code
stringlengths
31
1.05M
apis
list
extract_api
stringlengths
97
1.91M
#!./python27-gcc482/bin/python # coding: utf-8 """ BAIDU CLOUD action """ import os import sys import pickle import json import time import shutil import numpy as np sys.path.append( "/home/aistudio/work/PaddleVideo/applications/TableTennis/predict/action_detect" ) import models.bmn_infer as prop_model from utils.preprocess import get_images from utils.config_utils import parse_config, print_configs import utils.config_utils as config_utils import logger logger = logger.Logger() def load_model(cfg_file="configs/configs.yaml"): """ load_model """ logger.info("load model ... ") global infer_configs infer_configs = parse_config(cfg_file) print_configs(infer_configs, "Infer") t0 = time.time() global prop_model prop_model = prop_model.InferModel(infer_configs) t1 = time.time() logger.info("step0: load model time: {} min\n".format((t1 - t0) * 1.0 / 60)) def video_classify(video_name, dataset_dir): """ extract_feature """ logger.info('predict ... ') logger.info(video_name) # step 1: extract feature feature_path = dataset_dir + video_name video_features = pickle.load(open(feature_path, 'rb')) print('===video_features===', video_name) # step2: get proposal t0 = time.time() bmn_results = prop_model.predict(infer_configs, material=video_features) t1 = time.time() logger.info(np.array(bmn_results).shape) logger.info("step2: proposal time: {} min".format((t1 - t0) * 1.0 / 60)) return bmn_results if __name__ == '__main__': dataset_dir = '/home/aistudio/data/Features_test/' output_dir = '/home/aistudio/data' if not os.path.exists(output_dir + '/Output_for_bmn'): os.mkdir(output_dir + '/Output_for_bmn') results = [] load_model() directory = os.fsencode(dataset_dir) for file in os.listdir(directory): filename = os.fsdecode(file) bmn_results = video_classify(filename, dataset_dir) results.append({ 'video_name': filename.split('.pkl')[0], 'num_proposal': len(bmn_results), 'bmn_results': bmn_results }) with open(output_dir + '/Output_for_bmn/prop.json', 'w', encoding='utf-8') as f: data = json.dumps(results, indent=4, ensure_ascii=False) f.write(data) print('Done with the inference!')
[ "sys.path.append", "logger.info", "os.mkdir", "logger.Logger", "os.fsdecode", "os.path.exists", "models.bmn_infer.predict", "time.time", "json.dumps", "utils.config_utils.parse_config", "numpy.array", "models.bmn_infer.InferModel", "os.fsencode", "utils.config_utils.print_configs", "os.listdir" ]
[((169, 276), 'sys.path.append', 'sys.path.append', (['"""/home/aistudio/work/PaddleVideo/applications/TableTennis/predict/action_detect"""'], {}), "(\n '/home/aistudio/work/PaddleVideo/applications/TableTennis/predict/action_detect'\n )\n", (184, 276), False, 'import sys\n'), ((477, 492), 'logger.Logger', 'logger.Logger', ([], {}), '()\n', (490, 492), False, 'import logger\n'), ((579, 609), 'logger.info', 'logger.info', (['"""load model ... """'], {}), "('load model ... ')\n", (590, 609), False, 'import logger\n'), ((655, 677), 'utils.config_utils.parse_config', 'parse_config', (['cfg_file'], {}), '(cfg_file)\n', (667, 677), False, 'from utils.config_utils import parse_config, print_configs\n'), ((682, 719), 'utils.config_utils.print_configs', 'print_configs', (['infer_configs', '"""Infer"""'], {}), "(infer_configs, 'Infer')\n", (695, 719), False, 'from utils.config_utils import parse_config, print_configs\n'), ((730, 741), 'time.time', 'time.time', ([], {}), '()\n', (739, 741), False, 'import time\n'), ((781, 817), 'models.bmn_infer.InferModel', 'prop_model.InferModel', (['infer_configs'], {}), '(infer_configs)\n', (802, 817), True, 'import models.bmn_infer as prop_model\n'), ((827, 838), 'time.time', 'time.time', ([], {}), '()\n', (836, 838), False, 'import time\n'), ((1007, 1034), 'logger.info', 'logger.info', (['"""predict ... """'], {}), "('predict ... ')\n", (1018, 1034), False, 'import logger\n'), ((1039, 1062), 'logger.info', 'logger.info', (['video_name'], {}), '(video_name)\n', (1050, 1062), False, 'import logger\n'), ((1280, 1291), 'time.time', 'time.time', ([], {}), '()\n', (1289, 1291), False, 'import time\n'), ((1310, 1368), 'models.bmn_infer.predict', 'prop_model.predict', (['infer_configs'], {'material': 'video_features'}), '(infer_configs, material=video_features)\n', (1328, 1368), True, 'import models.bmn_infer as prop_model\n'), ((1378, 1389), 'time.time', 'time.time', ([], {}), '()\n', (1387, 1389), False, 'import time\n'), ((1819, 1843), 'os.fsencode', 'os.fsencode', (['dataset_dir'], {}), '(dataset_dir)\n', (1830, 1843), False, 'import os\n'), ((1861, 1882), 'os.listdir', 'os.listdir', (['directory'], {}), '(directory)\n', (1871, 1882), False, 'import os\n'), ((1670, 1716), 'os.path.exists', 'os.path.exists', (["(output_dir + '/Output_for_bmn')"], {}), "(output_dir + '/Output_for_bmn')\n", (1684, 1716), False, 'import os\n'), ((1726, 1766), 'os.mkdir', 'os.mkdir', (["(output_dir + '/Output_for_bmn')"], {}), "(output_dir + '/Output_for_bmn')\n", (1734, 1766), False, 'import os\n'), ((1903, 1920), 'os.fsdecode', 'os.fsdecode', (['file'], {}), '(file)\n', (1914, 1920), False, 'import os\n'), ((2270, 2319), 'json.dumps', 'json.dumps', (['results'], {'indent': '(4)', 'ensure_ascii': '(False)'}), '(results, indent=4, ensure_ascii=False)\n', (2280, 2319), False, 'import json\n'), ((1406, 1427), 'numpy.array', 'np.array', (['bmn_results'], {}), '(bmn_results)\n', (1414, 1427), True, 'import numpy as np\n')]
import numpy as np def ood_p_value(cost, bound, ubound=True): """Compute p-value""" violations = cost - bound if ubound else bound - cost violation = np.mean(violations) tau = max(violation, 0) m = len(cost) p_val = np.exp(-2 * m * (tau ** 2)) return 1 - p_val def ood_confidence(cost, bound, deltap, ubound=True): """Compute Delta C""" violations = cost - bound if ubound else bound - cost violation = np.mean(violations) m = len(cost) gamma = np.sqrt(np.log(1/deltap)/(2*m)) # Check if Delta C = violation - gamma > 0 for OOD detection if violation - gamma > 0: return True, violation - gamma else: return False, violation - gamma def ood_p_value_batch(costs, bound, batch=False): ps = [] for m in range(1,len(costs) + 1): p = ood_p_value(costs[:m], bound, ubound=True) ps.append(p) if batch: return ps[-1] else: return ps def ood_confidence_batch(costs, bound, deltap=0.04, batch=False): ps = [] for m in range(1, len(costs) + 1): p = ood_confidence(costs[:m], bound, deltap=deltap, ubound=True)[1] ps.append(p) if batch: return ps[-1] else: return ps def ood_msp_batch(model_output, batch=False): """Maximum Softmax Probability""" msp_single = 1 - np.max(model_output, axis=-1) msp_ood = np.cumsum(msp_single) / [i + 1 for i in range(len(msp_single))] if batch: return msp_ood[-1] else: return msp_ood def ood_maxlogit_batch(model_output, batch=False): """MaxLogit""" maxlogit_output = -np.log(model_output / (1 - model_output)) maxlogit_single = np.max(maxlogit_output, axis=-1) maxlogit_ood = -np.cumsum(maxlogit_single) / [i + 1 for i in range(len(maxlogit_single))] if batch: return maxlogit_ood[-1] else: return maxlogit_ood
[ "numpy.log", "numpy.cumsum", "numpy.max", "numpy.mean", "numpy.exp" ]
[((164, 183), 'numpy.mean', 'np.mean', (['violations'], {}), '(violations)\n', (171, 183), True, 'import numpy as np\n'), ((242, 267), 'numpy.exp', 'np.exp', (['(-2 * m * tau ** 2)'], {}), '(-2 * m * tau ** 2)\n', (248, 267), True, 'import numpy as np\n'), ((447, 466), 'numpy.mean', 'np.mean', (['violations'], {}), '(violations)\n', (454, 466), True, 'import numpy as np\n'), ((1684, 1716), 'numpy.max', 'np.max', (['maxlogit_output'], {'axis': '(-1)'}), '(maxlogit_output, axis=-1)\n', (1690, 1716), True, 'import numpy as np\n'), ((1343, 1372), 'numpy.max', 'np.max', (['model_output'], {'axis': '(-1)'}), '(model_output, axis=-1)\n', (1349, 1372), True, 'import numpy as np\n'), ((1387, 1408), 'numpy.cumsum', 'np.cumsum', (['msp_single'], {}), '(msp_single)\n', (1396, 1408), True, 'import numpy as np\n'), ((1620, 1661), 'numpy.log', 'np.log', (['(model_output / (1 - model_output))'], {}), '(model_output / (1 - model_output))\n', (1626, 1661), True, 'import numpy as np\n'), ((505, 523), 'numpy.log', 'np.log', (['(1 / deltap)'], {}), '(1 / deltap)\n', (511, 523), True, 'import numpy as np\n'), ((1737, 1763), 'numpy.cumsum', 'np.cumsum', (['maxlogit_single'], {}), '(maxlogit_single)\n', (1746, 1763), True, 'import numpy as np\n')]
import numpy as np from matplotlib.path import Path import matplotlib.patches as patches import scipy.linalg as lin import matplotlib.pyplot as plt def plotGMM(Mu, Sigma, color,display_mode, ax): a, nbData = np.shape(Mu) lightcolor = np.asarray(color) + np.asarray([0.6,0.6,0.6]) a = np.nonzero(lightcolor > 1) lightcolor[a] = 1 minsx = [] maxsx = [] minsy = [] maxsy = [] if display_mode==1: nbDrawingSeg = 40 t = np.linspace(-np.pi,np.pi,nbDrawingSeg) t = np.transpose(t) for j in range (0,nbData): stdev = lin.sqrtm(3*Sigma[:,:,j]) X = np.dot(np.transpose([np.cos(t), np.sin(t)]), np.real(stdev)) X = X + np.tile(np.transpose(Mu[:,j]), (nbDrawingSeg,1)) minsx.append(min(X[:,0])) maxsx.append(max(X[:,0])) minsy.append(min(X[:,1])) maxsy.append(max(X[:,1])) verts = [] codes = [] for i in range (0, nbDrawingSeg+1): if i==0: vert = (X[0,0], X[0,1]) code = Path.MOVETO elif i!=nbDrawingSeg: vert = (X[i,0], X[i,1]) code = Path.CURVE3 else: vert = (X[0,0], X[0,1]) code = Path.CURVE3 verts.append(vert) codes.append(code) path = Path(verts, codes) patch = patches.PathPatch(path, facecolor=lightcolor, edgecolor=color, lw=2) ax.add_patch(patch) ax.plot(Mu[0,:], Mu[1,:], "x",color = color) # ax.set_xlim(min(minsx),max(maxsx)) # ax.set_ylim(min(minsy),max(maxsy)) elif display_mode == 2: nbDrawingSeg = 40 t = np.linspace(-np.pi, np.pi, nbDrawingSeg) t = np.transpose(t) for j in range(0, nbData): stdev = lin.sqrtm(3 * Sigma[:, :, j]) X = np.dot(np.transpose([np.cos(t), np.sin(t)]), np.real(stdev)) X = X + np.tile(np.transpose(Mu[:, j]), (nbDrawingSeg, 1)) minsx.append(min(X[:, 0])) maxsx.append(max(X[:, 0])) minsy.append(min(X[:, 1])) maxsy.append(max(X[:, 1])) verts = [] codes = [] for i in range(0, nbDrawingSeg+1): if i == 0: vert = (X[0, 0], X[0, 1]) code = Path.MOVETO elif i != nbDrawingSeg: vert = (X[i, 0], X[i, 1]) code = Path.CURVE3 else: vert = (X[0, 0], X[0, 1]) code = Path.CURVE3 verts.append(vert) codes.append(code) path = Path(verts, codes) patch = patches.PathPatch(path, linestyle=None, color = lightcolor) ax.add_patch(patch) ax.plot(Mu[0, :], Mu[1, :], "-",lw = 3, color=color) # ax.set_xlim(min(minsx), max(maxsx)) # ax.set_ylim(min(minsy), max(maxsy))
[ "numpy.asarray", "numpy.transpose", "numpy.shape", "numpy.nonzero", "matplotlib.path.Path", "scipy.linalg.sqrtm", "numpy.sin", "numpy.linspace", "numpy.real", "numpy.cos", "matplotlib.patches.PathPatch" ]
[((213, 225), 'numpy.shape', 'np.shape', (['Mu'], {}), '(Mu)\n', (221, 225), True, 'import numpy as np\n'), ((297, 323), 'numpy.nonzero', 'np.nonzero', (['(lightcolor > 1)'], {}), '(lightcolor > 1)\n', (307, 323), True, 'import numpy as np\n'), ((243, 260), 'numpy.asarray', 'np.asarray', (['color'], {}), '(color)\n', (253, 260), True, 'import numpy as np\n'), ((263, 290), 'numpy.asarray', 'np.asarray', (['[0.6, 0.6, 0.6]'], {}), '([0.6, 0.6, 0.6])\n', (273, 290), True, 'import numpy as np\n'), ((470, 510), 'numpy.linspace', 'np.linspace', (['(-np.pi)', 'np.pi', 'nbDrawingSeg'], {}), '(-np.pi, np.pi, nbDrawingSeg)\n', (481, 510), True, 'import numpy as np\n'), ((521, 536), 'numpy.transpose', 'np.transpose', (['t'], {}), '(t)\n', (533, 536), True, 'import numpy as np\n'), ((592, 621), 'scipy.linalg.sqrtm', 'lin.sqrtm', (['(3 * Sigma[:, :, j])'], {}), '(3 * Sigma[:, :, j])\n', (601, 621), True, 'import scipy.linalg as lin\n'), ((1435, 1453), 'matplotlib.path.Path', 'Path', (['verts', 'codes'], {}), '(verts, codes)\n', (1439, 1453), False, 'from matplotlib.path import Path\n'), ((1474, 1542), 'matplotlib.patches.PathPatch', 'patches.PathPatch', (['path'], {'facecolor': 'lightcolor', 'edgecolor': 'color', 'lw': '(2)'}), '(path, facecolor=lightcolor, edgecolor=color, lw=2)\n', (1491, 1542), True, 'import matplotlib.patches as patches\n'), ((1788, 1828), 'numpy.linspace', 'np.linspace', (['(-np.pi)', 'np.pi', 'nbDrawingSeg'], {}), '(-np.pi, np.pi, nbDrawingSeg)\n', (1799, 1828), True, 'import numpy as np\n'), ((1841, 1856), 'numpy.transpose', 'np.transpose', (['t'], {}), '(t)\n', (1853, 1856), True, 'import numpy as np\n'), ((679, 693), 'numpy.real', 'np.real', (['stdev'], {}), '(stdev)\n', (686, 693), True, 'import numpy as np\n'), ((1913, 1942), 'scipy.linalg.sqrtm', 'lin.sqrtm', (['(3 * Sigma[:, :, j])'], {}), '(3 * Sigma[:, :, j])\n', (1922, 1942), True, 'import scipy.linalg as lin\n'), ((2775, 2793), 'matplotlib.path.Path', 'Path', (['verts', 'codes'], {}), '(verts, codes)\n', (2779, 2793), False, 'from matplotlib.path import Path\n'), ((2814, 2871), 'matplotlib.patches.PathPatch', 'patches.PathPatch', (['path'], {'linestyle': 'None', 'color': 'lightcolor'}), '(path, linestyle=None, color=lightcolor)\n', (2831, 2871), True, 'import matplotlib.patches as patches\n'), ((723, 745), 'numpy.transpose', 'np.transpose', (['Mu[:, j]'], {}), '(Mu[:, j])\n', (735, 745), True, 'import numpy as np\n'), ((2004, 2018), 'numpy.real', 'np.real', (['stdev'], {}), '(stdev)\n', (2011, 2018), True, 'import numpy as np\n'), ((655, 664), 'numpy.cos', 'np.cos', (['t'], {}), '(t)\n', (661, 664), True, 'import numpy as np\n'), ((666, 675), 'numpy.sin', 'np.sin', (['t'], {}), '(t)\n', (672, 675), True, 'import numpy as np\n'), ((2048, 2070), 'numpy.transpose', 'np.transpose', (['Mu[:, j]'], {}), '(Mu[:, j])\n', (2060, 2070), True, 'import numpy as np\n'), ((1980, 1989), 'numpy.cos', 'np.cos', (['t'], {}), '(t)\n', (1986, 1989), True, 'import numpy as np\n'), ((1991, 2000), 'numpy.sin', 'np.sin', (['t'], {}), '(t)\n', (1997, 2000), True, 'import numpy as np\n')]
""" Created on Wed Jun 17 14:01:23 2020 Correlation matrix of maps, rearranged correlation matrix @author: Jyotika.bahuguna """ import os import glob import numpy as np import pylab as pl import scipy.io as sio from copy import copy, deepcopy import pickle import matplotlib.cm as cm import pdb import h5py import pandas as pd import bct from collections import Counter import matplotlib.cm as cm #import analyze as anal import sys import glob import random sys.path.append("common/") import graph_prop_funcs_analyze as graph_anal # Raw data here data_dir = "../SpaethBahugunaData/ProcessedData/Adaptive_Dataset/" # Store data after preprocessing here data_target_dir = "./data/" if os.path.isdir("./Figure1/")== False: os.mkdir("./Figure1") fig_target_dir = "./Figure1/" # All subtypes - LC,LS,EC,ES,Ct,S-L/TR subtypes = os.listdir(data_dir) data_2d = pickle.load(open(data_target_dir+"data_2d_maps.pickle","rb")) data = pd.read_csv(data_target_dir+"meta_data.csv") cov_2d_dict = deepcopy(data_2d) # Gamma values for calculating the graph properties gammas = np.round(np.arange(0.0,1.5,0.17),2) graph_properties = dict() # An example gamma, to display the rearranged correlation maps after louvain community algorithm is run gamma_re_arrange = 1.02 gamma_re_arrange_ind = np.where(gammas == gamma_re_arrange)[0][0] # zones zone_names = ["B_contra","AX_contra","Alat_contra","Amed_contra","Amed_ipsi","Alat_ipsi","AX_ipsi","B_ipsi"] zone_lims = [(-233,-133),(-133,-108),(-108,-58),(-58,0),(0,50),(50,100),(100,125),(125,235)] zone_binning = np.arange(-235,235,5) ''' B_contra : -233 to -133 AX_contra : -133 to -108 Alat_contra : - 108 to -58 Amed_contra : -58 to 0 Amed ipsi :0 to 50 Alat_ipis = 50 to 100 AX_ipsi : 100 to 125 B_ipis : 125 to 285 ''' mat_type = "norm" # Read seeds and calculate graph properties for a different seed seeds_list = pickle.load(open(data_target_dir+"seeds.pickle","rb")) # Plot the correlation matrix and rearranged matrix for one seed #seed_plot = random.sample(list(seeds_list),1)[0] seed_plot = int(sys.argv[1]) print(seed_plot) def store_gp(ci_list_corr,corr_2d,participation_pos_all,participation_neg_all,mdz_all): zscore = [] for ci in ci_list_corr: zs = graph_anal.calc_module_degree_zscore(corr_2d,ci,True,False) zscore.append(zs) #rc = anal.calc_rich_club_wu(ci) # Rich club also gave nan #rich_club.append(rc) # independent of gammas mdz_all.append(zscore) part_pos, part_neg = graph_anal.calc_participation_coef_sign(corr_2d,ci_list_corr,False,True) participation_pos_all.append(part_pos) participation_neg_all.append(part_neg) # re arranging the correlation matroices list_nodes = [ bct.modularity.ci2ls(x1) for x1 in ci_list_corr] loc_assort_pos, loc_assort_neg = graph_anal.calc_local_assortativity_sign(corr_2d) return zscore, part_pos, part_neg, list_nodes, loc_assort_pos, loc_assort_neg for seed in seeds_list[:5]: print(seed) participation_pos_all = [] participation_neg_all = [] mdz_all = [] participation_pos_all_null = [] participation_neg_all_null = [] mdz_all_null = [] for st in subtypes: data_slice = data.loc[data["subtypes"]==st] num_subfigs = len(data_slice) fig = pl.figure(figsize=(20,20)) fig1 = pl.figure(figsize=(20,20)) fig2 = pl.figure(figsize=(20,20)) rows = int(np.round(np.sqrt(num_subfigs))) cols = rows print(st) # Plot all the maps of a subtype if rows*cols < num_subfigs: rows = rows+1 subfig_hands1 = [] subfig_hands2 = [] graph_properties[st] = dict() graph_properties[st]["modularity"] = dict() graph_properties[st]["indices"] = [] graph_properties[st]["names"] = [] fig1.suptitle("Subtype:"+st,fontsize=15,fontweight='bold') fig2.suptitle("Subtype:"+st+" rearranged, gamma = "+str(gamma_re_arrange),fontsize=15,fontweight='bold') for i,(rn,cn) in enumerate(zip(data_slice["rat_num"],data_slice["cell_num"])): subfig_hands1.append(fig1.add_subplot(rows,cols,i+1)) subfig_hands2.append(fig2.add_subplot(rows,cols,i+1)) graph_properties[st]["modularity"][i] = dict() graph_properties[st]["names"].append(rn+"-"+str(cn)) if str(cn) in list(data_2d[st][rn].keys()): cov_2d = np.cov(data_2d[st][rn][str(cn)]["map"].T) tot_amplitude = np.nansum(data_2d[st][rn][str(cn)]["map_nz"]) avg_amplitude = np.nanmean(data_2d[st][rn][str(cn)]["map_nz"]) nz_dim = np.shape(data_2d[st][rn][str(cn)]["map"]) active_sites = (len(np.where(data_2d[st][rn][str(cn)]["map"] > 3.0)[0])/(nz_dim[0]*nz_dim[1]))*100 # % active sites corr_2d = np.corrcoef(data_2d[st][rn][str(cn)]["map"].T,data_2d[st][rn][str(cn)]["map"].T)[:len(cov_2d),:len(cov_2d)] ind_nan = np.where(np.isnan(corr_2d)==True) if len(ind_nan[0]) > 0: ind_nonan = np.where(np.isnan(corr_2d)==False) xlim = (np.min(np.unique(ind_nonan[0])),np.max(np.unique(ind_nonan[0]))) ylim = (np.min(np.unique(ind_nonan[1])),np.max(np.unique(ind_nonan[1]))) corr_2d = corr_2d[xlim[0]:xlim[1],ylim[0]:ylim[1]] cov_2d_dict[st][rn][str(cn)] = dict() cov_2d_dict[st][rn][str(cn)]["cov"] = cov_2d if mat_type == "norm": corr_2d = corr_2d cov_2d_dict[st][rn][str(cn)]["corr"] = corr_2d # Find modularity index gammas,num_mods_cov, mod_index_cov,ci_list_cov = graph_anal.calc_modularity(cov_2d) _,num_mods_corr, mod_index_corr,ci_list_corr = graph_anal.calc_modularity(corr_2d) corr_2d_null = bct.randmio_und_signed(corr_2d,5)[0] # This function randomizes an undirected weighted network with positive and negative weights, while simultaneously preserving the degree distribution of positive and negative weights. The function does not preserve the cov_2d_dict[st][rn][str(cn)]["corr_null"] = corr_2d_null #+np.nanmin(corr_2d) _,num_mods_corr_null, mod_index_corr_null,ci_list_corr_null = graph_anal.calc_modularity(corr_2d_null) ''' zscore = [] # module degree zscore for ci in ci_list_corr: zs = graph_anal.calc_module_degree_zscore(corr_2d,ci,True,False) zscore.append(zs) mdz_all.append(zscore) part_pos, part_neg = graph_anal.calc_participation_coef_sign(corr_2d,ci_list_corr,False,True) participation_pos_all.append(part_pos) participation_neg_all.append(part_neg) # re arranging the correlation matroices list_nodes = [ bct.modularity.ci2ls(x1) for x1 in ci_list_corr] loc_assort_pos, loc_assort_neg = graph_anal.calc_local_assortativity_sign(corr_2d) ''' zscore, part_pos, part_neg, list_nodes, loc_assort_pos, loc_assort_neg = store_gp(ci_list_corr,corr_2d,participation_pos_all,participation_neg_all,mdz_all) zscore_null, part_pos_null, part_neg_null, list_nodes_null, loc_assort_pos_null, loc_assort_neg_null = store_gp(ci_list_corr_null,corr_2d_null,participation_pos_all_null,participation_neg_all_null,mdz_all_null) re_arranged_corr = graph_anal.get_re_arranged_matrix(ci_list_corr[gamma_re_arrange_ind],corr_2d) re_arranged_corr_null = graph_anal.get_re_arranged_matrix(ci_list_corr_null[gamma_re_arrange_ind],corr_2d_null) graph_properties[st]["modularity"][i]["cov"] = (mod_index_cov,num_mods_cov) graph_properties[st]["modularity"][i]["corr"] = (mod_index_corr,num_mods_corr) graph_properties[st]["modularity"][i]["corr_null"] = (mod_index_corr_null,num_mods_corr_null) graph_properties[st]["modularity"][i]["mod_list"] = ci_list_corr graph_properties[st]["modularity"][i]["mod_list_null"] = ci_list_corr_null graph_properties[st]["modularity"][i]["rearranged_corr"] = re_arranged_corr graph_properties[st]["modularity"][i]["rearranged_corr_null"] = re_arranged_corr_null graph_properties[st]["modularity"][i]["norm"] = np.linalg.norm(corr_2d) graph_properties[st]["modularity"][i]["total_amplitude"] = np.abs(tot_amplitude)*0.01 # pA graph_properties[st]["modularity"][i]["average_amplitude"] = np.abs(avg_amplitude)*0.01 # pA graph_properties[st]["modularity"][i]["percentage_active_sites"] = active_sites # align node numbers with position in the binned_pos if len(ind_nan[0]) > 0: ind_zone_bins = np.digitize(data_2d[st][rn][str(cn)]["pos_centered"][xlim[0]:xlim[1]],bins=zone_binning) graph_properties[st]["modularity"][i]["ind_zone_bins_node_num_mapping"] = (ind_zone_bins,np.arange(xlim[0],xlim[1])) else: ind_zone_bins = np.digitize(data_2d[st][rn][str(cn)]["pos_centered"],bins=zone_binning) graph_properties[st]["modularity"][i]["ind_zone_bins_node_num_mapping"] = (ind_zone_bins,np.arange(0,np.shape(data_2d[st][rn][str(cn)]["map"])[1])) # Store node wise participation coefficient, module degree zscore and local assortativity coefficient and average it over the zones on the basis of ind_zone_bins graph_properties[st]["modularity"][i]["participation_pos_zone"] = part_pos graph_properties[st]["modularity"][i]["participation_neg_zone"] = part_neg graph_properties[st]["modularity"][i]["module_degree_zscore_zone"] = zscore graph_properties[st]["modularity"][i]["local_assortativity_pos_whole_zone"] = loc_assort_pos # Participation coefficient of all nodes in the graph (whole graph participation coefficient is median of these distributions) graph_properties[st]["modularity"][i]["participation_whole"] = (np.median(part_pos,axis=1),np.median(part_neg,axis=1)) graph_properties[st]["modularity"][i]["participation_whole_null"] = (np.median(part_pos_null,axis=1),np.median(part_neg_null,axis=1)) # Participation coefficient on the hemisphere resolution - ipsilateral and contralateral if len(data_2d[st][rn][str(cn)]["ind_ipsi"]) > 0: part_pos_ipsi = np.array(part_pos)[:,np.min(data_2d[st][rn][str(cn)]["ind_ipsi"]):np.max(data_2d[st][rn][str(cn)]["ind_ipsi"])] part_pos_ipsi_null = np.array(part_pos_null)[:,np.min(data_2d[st][rn][str(cn)]["ind_ipsi"]):np.max(data_2d[st][rn][str(cn)]["ind_ipsi"])] part_neg_ipsi = np.array(part_neg)[:,np.min(data_2d[st][rn][str(cn)]["ind_ipsi"]):np.max(data_2d[st][rn][str(cn)]["ind_ipsi"])] part_neg_ipsi_null = np.array(part_neg_null)[:,np.min(data_2d[st][rn][str(cn)]["ind_ipsi"]):np.max(data_2d[st][rn][str(cn)]["ind_ipsi"])] graph_properties[st]["modularity"][i]["participation_ipsi"] = (np.median(part_pos_ipsi,axis=1),np.median(part_neg_ipsi,axis=1)) graph_properties[st]["modularity"][i]["participation_ipsi_null"] = (np.median(part_pos_ipsi_null,axis=1),np.median(part_neg_ipsi_null,axis=1)) if len(data_2d[st][rn][str(cn)]["ind_contra"]) > 0: part_pos_contra = np.array(part_pos)[:,np.min(data_2d[st][rn][str(cn)]["ind_contra"]):np.max(data_2d[st][rn][str(cn)]["ind_contra"])] part_pos_contra_null = np.array(part_pos_null)[:,np.min(data_2d[st][rn][str(cn)]["ind_contra"]):np.max(data_2d[st][rn][str(cn)]["ind_contra"])] part_neg_contra = np.array(part_neg)[:,np.min(data_2d[st][rn][str(cn)]["ind_contra"]):np.max(data_2d[st][rn][str(cn)]["ind_contra"])] part_neg_contra_null = np.array(part_neg_null)[:,np.min(data_2d[st][rn][str(cn)]["ind_contra"]):np.max(data_2d[st][rn][str(cn)]["ind_contra"])] graph_properties[st]["modularity"][i]["participation_contra_null"] = (np.median(part_pos_contra_null,axis=1),np.median(part_neg_contra_null,axis=1)) graph_properties[st]["modularity"][i]["participation_contra"] = (np.median(part_pos_contra,axis=1),np.median(part_neg_contra,axis=1)) # local assortativity for all nodes in the graph (whole graph local assortativity is median of these dsitributions) graph_properties[st]["modularity"][i]["local_assortativity_whole"] = (np.median(loc_assort_pos)) graph_properties[st]["modularity"][i]["local_assortativity_whole_null"] = (np.median(loc_assort_pos_null)) if len(data_2d[st][rn][str(cn)]["ind_ipsi"]) > 0: lim1 = np.min([len(loc_assort_pos),np.min(data_2d[st][rn][str(cn)]["ind_ipsi"])]) lim2 = np.min([len(loc_assort_pos),np.max(data_2d[st][rn][str(cn)]["ind_ipsi"])]) graph_properties[st]["modularity"][i]["local_assortativity_ipsi"] = (np.median(loc_assort_pos[lim1:lim2])) lim1n = np.min([len(loc_assort_pos_null),np.min(data_2d[st][rn][str(cn)]["ind_ipsi"])]) lim2n = np.min([len(loc_assort_pos_null),np.max(data_2d[st][rn][str(cn)]["ind_ipsi"])]) graph_properties[st]["modularity"][i]["local_assortativity_ipsi_null"] = (np.median(loc_assort_pos_null[lim1n:lim2n])) if len(data_2d[st][rn][str(cn)]["ind_contra"]) > 0: lim1 = np.min([len(loc_assort_pos),np.min(data_2d[st][rn][str(cn)]["ind_contra"])]) lim2 = np.min([len(loc_assort_pos),np.max(data_2d[st][rn][str(cn)]["ind_contra"])]) graph_properties[st]["modularity"][i]["local_assortativity_contra"] = (np.median(loc_assort_pos[lim1:lim2])) lim1n = np.min([len(loc_assort_pos_null),np.min(data_2d[st][rn][str(cn)]["ind_contra"])]) lim2n = np.min([len(loc_assort_pos_null),np.max(data_2d[st][rn][str(cn)]["ind_contra"])]) graph_properties[st]["modularity"][i]["local_assortativity_contra_null"] = (np.median(loc_assort_pos_null[lim1n:lim2n])) # Module degree zscore for all nodes in the graph (whole graph module degree zscore is median of these distributions) graph_properties[st]["modularity"][i]["module_degree_zscore_whole"] = np.median(zscore,axis=1) graph_properties[st]["modularity"][i]["module_degree_zscore_whole_null"] = np.median(zscore_null,axis=1) if len(data_2d[st][rn][str(cn)]["ind_ipsi"]) > 0: zscore_ipsi = np.array(zscore)[:,np.min(data_2d[st][rn][str(cn)]["ind_ipsi"]):np.max(data_2d[st][rn][str(cn)]["ind_ipsi"])] graph_properties[st]["modularity"][i]["module_degree_zscore_ipsi"] = np.median(zscore_ipsi,axis=1) zscore_ipsi_null = np.array(zscore_null)[:,np.min(data_2d[st][rn][str(cn)]["ind_ipsi"]):np.max(data_2d[st][rn][str(cn)]["ind_ipsi"])] graph_properties[st]["modularity"][i]["module_degree_zscore_ipsi_null"] = np.median(zscore_ipsi_null,axis=1) if len(data_2d[st][rn][str(cn)]["ind_contra"]) > 0: zscore_contra = np.array(zscore)[:,np.min(data_2d[st][rn][str(cn)]["ind_contra"]):np.max(data_2d[st][rn][str(cn)]["ind_contra"])] graph_properties[st]["modularity"][i]["module_degree_zscore_contra"] = np.median(zscore_contra,axis=1) zscore_contra_null = np.array(zscore_null)[:,np.min(data_2d[st][rn][str(cn)]["ind_contra"]):np.max(data_2d[st][rn][str(cn)]["ind_contra"])] graph_properties[st]["modularity"][i]["module_degree_zscore_contra_null"] = np.median(zscore_contra_null,axis=1) graph_properties[st]["indices"].append(i) vmin = np.nanmin(cov_2d)/2. vmax = np.nanmax(cov_2d)/2. #subfig_hands[-1].pcolor(cov_2d,cmap=cm.hot,vmin=vmin,vmax=vmax) vmin = np.nanmin(corr_2d)/2. vmax = np.nanmax(corr_2d)/2. print(vmin,vmax) subfig_hands1[-1].pcolor(corr_2d,cmap=cm.coolwarm,vmin=vmin,vmax=vmax) subfig_hands2[-1].pcolor(re_arranged_corr,cmap=cm.coolwarm,vmin=vmin,vmax=vmax) subfig_hands1[-1].set_aspect('equal') subfig_hands2[-1].set_aspect('equal') subfig_hands1[-1].set_title("rat num:"+str(rn)+",cell num:"+str(cn),fontsize=12,fontweight='bold') subfig_hands2[-1].set_title("rat num:"+str(rn)+",cell num:"+str(cn),fontsize=12,fontweight='bold') if i < (num_subfigs-2): subfig_hands1[-1].set_xticklabels([]) subfig_hands2[-1].set_xticklabels([]) graph_properties[st]["gammas"] = gammas if seed == seed_plot: fig1.subplots_adjust(left = 0.05,right=0.96,wspace=0.2,hspace=0.2,bottom=0.06,top=0.95) fig2.subplots_adjust(left = 0.05,right=0.96,wspace=0.2,hspace=0.2,bottom=0.06,top=0.95) fig1.savefig(fig_target_dir+"corr_maps_"+st+"_"+mat_type+".png") fig2.savefig(fig_target_dir+"corr_maps_rearranged_"+st+"_"+mat_type+"_"+str(seed)+".png") pickle.dump(cov_2d_dict,open(data_target_dir+"covariance_maps_"+mat_type+"_"+str(seed)+".pickle","wb")) pickle.dump(graph_properties,open(data_target_dir+"graph_properties_"+mat_type+"_"+str(seed)+".pickle","wb"))
[ "os.mkdir", "numpy.abs", "pandas.read_csv", "numpy.isnan", "numpy.arange", "pylab.figure", "numpy.linalg.norm", "graph_prop_funcs_analyze.calc_participation_coef_sign", "numpy.unique", "sys.path.append", "graph_prop_funcs_analyze.calc_module_degree_zscore", "graph_prop_funcs_analyze.get_re_arranged_matrix", "copy.deepcopy", "graph_prop_funcs_analyze.calc_local_assortativity_sign", "graph_prop_funcs_analyze.calc_modularity", "numpy.median", "bct.randmio_und_signed", "os.listdir", "numpy.nanmax", "os.path.isdir", "bct.modularity.ci2ls", "numpy.nanmin", "numpy.where", "numpy.array", "numpy.sqrt" ]
[((467, 493), 'sys.path.append', 'sys.path.append', (['"""common/"""'], {}), "('common/')\n", (482, 493), False, 'import sys\n'), ((835, 855), 'os.listdir', 'os.listdir', (['data_dir'], {}), '(data_dir)\n', (845, 855), False, 'import os\n'), ((935, 981), 'pandas.read_csv', 'pd.read_csv', (["(data_target_dir + 'meta_data.csv')"], {}), "(data_target_dir + 'meta_data.csv')\n", (946, 981), True, 'import pandas as pd\n'), ((994, 1011), 'copy.deepcopy', 'deepcopy', (['data_2d'], {}), '(data_2d)\n', (1002, 1011), False, 'from copy import copy, deepcopy\n'), ((1560, 1583), 'numpy.arange', 'np.arange', (['(-235)', '(235)', '(5)'], {}), '(-235, 235, 5)\n', (1569, 1583), True, 'import numpy as np\n'), ((694, 721), 'os.path.isdir', 'os.path.isdir', (['"""./Figure1/"""'], {}), "('./Figure1/')\n", (707, 721), False, 'import os\n'), ((732, 753), 'os.mkdir', 'os.mkdir', (['"""./Figure1"""'], {}), "('./Figure1')\n", (740, 753), False, 'import os\n'), ((1084, 1109), 'numpy.arange', 'np.arange', (['(0.0)', '(1.5)', '(0.17)'], {}), '(0.0, 1.5, 0.17)\n', (1093, 1109), True, 'import numpy as np\n'), ((2464, 2539), 'graph_prop_funcs_analyze.calc_participation_coef_sign', 'graph_anal.calc_participation_coef_sign', (['corr_2d', 'ci_list_corr', '(False)', '(True)'], {}), '(corr_2d, ci_list_corr, False, True)\n', (2503, 2539), True, 'import graph_prop_funcs_analyze as graph_anal\n'), ((2759, 2808), 'graph_prop_funcs_analyze.calc_local_assortativity_sign', 'graph_anal.calc_local_assortativity_sign', (['corr_2d'], {}), '(corr_2d)\n', (2799, 2808), True, 'import graph_prop_funcs_analyze as graph_anal\n'), ((1290, 1326), 'numpy.where', 'np.where', (['(gammas == gamma_re_arrange)'], {}), '(gammas == gamma_re_arrange)\n', (1298, 1326), True, 'import numpy as np\n'), ((2228, 2290), 'graph_prop_funcs_analyze.calc_module_degree_zscore', 'graph_anal.calc_module_degree_zscore', (['corr_2d', 'ci', '(True)', '(False)'], {}), '(corr_2d, ci, True, False)\n', (2264, 2290), True, 'import graph_prop_funcs_analyze as graph_anal\n'), ((2676, 2700), 'bct.modularity.ci2ls', 'bct.modularity.ci2ls', (['x1'], {}), '(x1)\n', (2696, 2700), False, 'import bct\n'), ((3244, 3271), 'pylab.figure', 'pl.figure', ([], {'figsize': '(20, 20)'}), '(figsize=(20, 20))\n', (3253, 3271), True, 'import pylab as pl\n'), ((3286, 3313), 'pylab.figure', 'pl.figure', ([], {'figsize': '(20, 20)'}), '(figsize=(20, 20))\n', (3295, 3313), True, 'import pylab as pl\n'), ((3328, 3355), 'pylab.figure', 'pl.figure', ([], {'figsize': '(20, 20)'}), '(figsize=(20, 20))\n', (3337, 3355), True, 'import pylab as pl\n'), ((3383, 3403), 'numpy.sqrt', 'np.sqrt', (['num_subfigs'], {}), '(num_subfigs)\n', (3390, 3403), True, 'import numpy as np\n'), ((5753, 5787), 'graph_prop_funcs_analyze.calc_modularity', 'graph_anal.calc_modularity', (['cov_2d'], {}), '(cov_2d)\n', (5779, 5787), True, 'import graph_prop_funcs_analyze as graph_anal\n'), ((5851, 5886), 'graph_prop_funcs_analyze.calc_modularity', 'graph_anal.calc_modularity', (['corr_2d'], {}), '(corr_2d)\n', (5877, 5886), True, 'import graph_prop_funcs_analyze as graph_anal\n'), ((6364, 6404), 'graph_prop_funcs_analyze.calc_modularity', 'graph_anal.calc_modularity', (['corr_2d_null'], {}), '(corr_2d_null)\n', (6390, 6404), True, 'import graph_prop_funcs_analyze as graph_anal\n'), ((7614, 7692), 'graph_prop_funcs_analyze.get_re_arranged_matrix', 'graph_anal.get_re_arranged_matrix', (['ci_list_corr[gamma_re_arrange_ind]', 'corr_2d'], {}), '(ci_list_corr[gamma_re_arrange_ind], corr_2d)\n', (7647, 7692), True, 'import graph_prop_funcs_analyze as graph_anal\n'), ((7733, 7825), 'graph_prop_funcs_analyze.get_re_arranged_matrix', 'graph_anal.get_re_arranged_matrix', (['ci_list_corr_null[gamma_re_arrange_ind]', 'corr_2d_null'], {}), '(ci_list_corr_null[gamma_re_arrange_ind],\n corr_2d_null)\n', (7766, 7825), True, 'import graph_prop_funcs_analyze as graph_anal\n'), ((8550, 8573), 'numpy.linalg.norm', 'np.linalg.norm', (['corr_2d'], {}), '(corr_2d)\n', (8564, 8573), True, 'import numpy as np\n'), ((12893, 12918), 'numpy.median', 'np.median', (['loc_assort_pos'], {}), '(loc_assort_pos)\n', (12902, 12918), True, 'import numpy as np\n'), ((13011, 13041), 'numpy.median', 'np.median', (['loc_assort_pos_null'], {}), '(loc_assort_pos_null)\n', (13020, 13041), True, 'import numpy as np\n'), ((14786, 14811), 'numpy.median', 'np.median', (['zscore'], {'axis': '(1)'}), '(zscore, axis=1)\n', (14795, 14811), True, 'import numpy as np\n'), ((14902, 14932), 'numpy.median', 'np.median', (['zscore_null'], {'axis': '(1)'}), '(zscore_null, axis=1)\n', (14911, 14932), True, 'import numpy as np\n'), ((5934, 5968), 'bct.randmio_und_signed', 'bct.randmio_und_signed', (['corr_2d', '(5)'], {}), '(corr_2d, 5)\n', (5956, 5968), False, 'import bct\n'), ((8650, 8671), 'numpy.abs', 'np.abs', (['tot_amplitude'], {}), '(tot_amplitude)\n', (8656, 8671), True, 'import numpy as np\n'), ((8759, 8780), 'numpy.abs', 'np.abs', (['avg_amplitude'], {}), '(avg_amplitude)\n', (8765, 8780), True, 'import numpy as np\n'), ((10344, 10371), 'numpy.median', 'np.median', (['part_pos'], {'axis': '(1)'}), '(part_pos, axis=1)\n', (10353, 10371), True, 'import numpy as np\n'), ((10371, 10398), 'numpy.median', 'np.median', (['part_neg'], {'axis': '(1)'}), '(part_neg, axis=1)\n', (10380, 10398), True, 'import numpy as np\n'), ((10484, 10516), 'numpy.median', 'np.median', (['part_pos_null'], {'axis': '(1)'}), '(part_pos_null, axis=1)\n', (10493, 10516), True, 'import numpy as np\n'), ((10516, 10548), 'numpy.median', 'np.median', (['part_neg_null'], {'axis': '(1)'}), '(part_neg_null, axis=1)\n', (10525, 10548), True, 'import numpy as np\n'), ((13403, 13439), 'numpy.median', 'np.median', (['loc_assort_pos[lim1:lim2]'], {}), '(loc_assort_pos[lim1:lim2])\n', (13412, 13439), True, 'import numpy as np\n'), ((13751, 13794), 'numpy.median', 'np.median', (['loc_assort_pos_null[lim1n:lim2n]'], {}), '(loc_assort_pos_null[lim1n:lim2n])\n', (13760, 13794), True, 'import numpy as np\n'), ((14165, 14201), 'numpy.median', 'np.median', (['loc_assort_pos[lim1:lim2]'], {}), '(loc_assort_pos[lim1:lim2])\n', (14174, 14201), True, 'import numpy as np\n'), ((14519, 14562), 'numpy.median', 'np.median', (['loc_assort_pos_null[lim1n:lim2n]'], {}), '(loc_assort_pos_null[lim1n:lim2n])\n', (14528, 14562), True, 'import numpy as np\n'), ((15232, 15262), 'numpy.median', 'np.median', (['zscore_ipsi'], {'axis': '(1)'}), '(zscore_ipsi, axis=1)\n', (15241, 15262), True, 'import numpy as np\n'), ((15510, 15545), 'numpy.median', 'np.median', (['zscore_ipsi_null'], {'axis': '(1)'}), '(zscore_ipsi_null, axis=1)\n', (15519, 15545), True, 'import numpy as np\n'), ((15856, 15888), 'numpy.median', 'np.median', (['zscore_contra'], {'axis': '(1)'}), '(zscore_contra, axis=1)\n', (15865, 15888), True, 'import numpy as np\n'), ((16144, 16181), 'numpy.median', 'np.median', (['zscore_contra_null'], {'axis': '(1)'}), '(zscore_contra_null, axis=1)\n', (16153, 16181), True, 'import numpy as np\n'), ((16283, 16300), 'numpy.nanmin', 'np.nanmin', (['cov_2d'], {}), '(cov_2d)\n', (16292, 16300), True, 'import numpy as np\n'), ((16327, 16344), 'numpy.nanmax', 'np.nanmax', (['cov_2d'], {}), '(cov_2d)\n', (16336, 16344), True, 'import numpy as np\n'), ((16453, 16471), 'numpy.nanmin', 'np.nanmin', (['corr_2d'], {}), '(corr_2d)\n', (16462, 16471), True, 'import numpy as np\n'), ((16498, 16516), 'numpy.nanmax', 'np.nanmax', (['corr_2d'], {}), '(corr_2d)\n', (16507, 16516), True, 'import numpy as np\n'), ((4983, 5000), 'numpy.isnan', 'np.isnan', (['corr_2d'], {}), '(corr_2d)\n', (4991, 5000), True, 'import numpy as np\n'), ((9231, 9258), 'numpy.arange', 'np.arange', (['xlim[0]', 'xlim[1]'], {}), '(xlim[0], xlim[1])\n', (9240, 9258), True, 'import numpy as np\n'), ((10757, 10775), 'numpy.array', 'np.array', (['part_pos'], {}), '(part_pos)\n', (10765, 10775), True, 'import numpy as np\n'), ((10910, 10933), 'numpy.array', 'np.array', (['part_pos_null'], {}), '(part_pos_null)\n', (10918, 10933), True, 'import numpy as np\n'), ((11063, 11081), 'numpy.array', 'np.array', (['part_neg'], {}), '(part_neg)\n', (11071, 11081), True, 'import numpy as np\n'), ((11216, 11239), 'numpy.array', 'np.array', (['part_neg_null'], {}), '(part_neg_null)\n', (11224, 11239), True, 'import numpy as np\n'), ((11416, 11448), 'numpy.median', 'np.median', (['part_pos_ipsi'], {'axis': '(1)'}), '(part_pos_ipsi, axis=1)\n', (11425, 11448), True, 'import numpy as np\n'), ((11448, 11480), 'numpy.median', 'np.median', (['part_neg_ipsi'], {'axis': '(1)'}), '(part_neg_ipsi, axis=1)\n', (11457, 11480), True, 'import numpy as np\n'), ((11569, 11606), 'numpy.median', 'np.median', (['part_pos_ipsi_null'], {'axis': '(1)'}), '(part_pos_ipsi_null, axis=1)\n', (11578, 11606), True, 'import numpy as np\n'), ((11606, 11643), 'numpy.median', 'np.median', (['part_neg_ipsi_null'], {'axis': '(1)'}), '(part_neg_ipsi_null, axis=1)\n', (11615, 11643), True, 'import numpy as np\n'), ((11750, 11768), 'numpy.array', 'np.array', (['part_pos'], {}), '(part_pos)\n', (11758, 11768), True, 'import numpy as np\n'), ((11909, 11932), 'numpy.array', 'np.array', (['part_pos_null'], {}), '(part_pos_null)\n', (11917, 11932), True, 'import numpy as np\n'), ((12068, 12086), 'numpy.array', 'np.array', (['part_neg'], {}), '(part_neg)\n', (12076, 12086), True, 'import numpy as np\n'), ((12227, 12250), 'numpy.array', 'np.array', (['part_neg_null'], {}), '(part_neg_null)\n', (12235, 12250), True, 'import numpy as np\n'), ((12438, 12477), 'numpy.median', 'np.median', (['part_pos_contra_null'], {'axis': '(1)'}), '(part_pos_contra_null, axis=1)\n', (12447, 12477), True, 'import numpy as np\n'), ((12477, 12516), 'numpy.median', 'np.median', (['part_neg_contra_null'], {'axis': '(1)'}), '(part_neg_contra_null, axis=1)\n', (12486, 12516), True, 'import numpy as np\n'), ((12602, 12636), 'numpy.median', 'np.median', (['part_pos_contra'], {'axis': '(1)'}), '(part_pos_contra, axis=1)\n', (12611, 12636), True, 'import numpy as np\n'), ((12636, 12670), 'numpy.median', 'np.median', (['part_neg_contra'], {'axis': '(1)'}), '(part_neg_contra, axis=1)\n', (12645, 12670), True, 'import numpy as np\n'), ((15033, 15049), 'numpy.array', 'np.array', (['zscore'], {}), '(zscore)\n', (15041, 15049), True, 'import numpy as np\n'), ((15301, 15322), 'numpy.array', 'np.array', (['zscore_null'], {}), '(zscore_null)\n', (15309, 15322), True, 'import numpy as np\n'), ((15651, 15667), 'numpy.array', 'np.array', (['zscore'], {}), '(zscore)\n', (15659, 15667), True, 'import numpy as np\n'), ((15929, 15950), 'numpy.array', 'np.array', (['zscore_null'], {}), '(zscore_null)\n', (15937, 15950), True, 'import numpy as np\n'), ((5089, 5106), 'numpy.isnan', 'np.isnan', (['corr_2d'], {}), '(corr_2d)\n', (5097, 5106), True, 'import numpy as np\n'), ((5150, 5173), 'numpy.unique', 'np.unique', (['ind_nonan[0]'], {}), '(ind_nonan[0])\n', (5159, 5173), True, 'import numpy as np\n'), ((5182, 5205), 'numpy.unique', 'np.unique', (['ind_nonan[0]'], {}), '(ind_nonan[0])\n', (5191, 5205), True, 'import numpy as np\n'), ((5243, 5266), 'numpy.unique', 'np.unique', (['ind_nonan[1]'], {}), '(ind_nonan[1])\n', (5252, 5266), True, 'import numpy as np\n'), ((5275, 5298), 'numpy.unique', 'np.unique', (['ind_nonan[1]'], {}), '(ind_nonan[1])\n', (5284, 5298), True, 'import numpy as np\n')]
import os import copy import yaml import numpy as np import autumn.post_processing as post_proc from autumn.tool_kit.scenarios import Scenario from ..countries import Country, CountryModel FILE_DIR = os.path.dirname(os.path.abspath(__file__)) OPTI_PARAMS_PATH = os.path.join(FILE_DIR, "opti_params.yml") with open(OPTI_PARAMS_PATH, "r") as yaml_file: opti_params = yaml.safe_load(yaml_file) aus = CountryModel(Country.AUSTRALIA) def objective_function(decision_variables, mode="by_age"): """ :param decision_variables: dictionary containing - mixing multipliers if mode == "by_age" OR - location multipliers if mode == "by_location" :param mode: either "by_age" or "by_location" :return: """ build_model = aus.build_model params = copy.deepcopy(aus.params) # Define the two scenarios: # baseline: with intervention # scenario 1: after intervention to test immunity if mode == "by_age": mixing_multipliers = decision_variables mixing_multipliers_matrix = build_mixing_multipliers_matrix(mixing_multipliers) params["default"].update({"mixing_matrix_multipliers": mixing_multipliers_matrix}) elif mode == "by_location": mixing_update_dictionary = {} for loc in ["school", "work", "other_locations"]: mixing_update_dictionary[loc + "_times"] = [0] mixing_update_dictionary[loc + "_values"] = [decision_variables[loc]] params["default"].update({"mixing": mixing_update_dictionary}) else: raise ValueError("The requested mode is not supported") # Add a scenario without any mixing multipliers end_time = params["default"]["end_time"] params["scenario_start_time"] = end_time - 1 params["scenarios"][1] = { "end_time": end_time + 50, "mixing_matrix_multipliers": None, "mixing": None, } scenario_0 = Scenario(build_model, idx=0, params=params) scenario_1 = Scenario(build_model, idx=1, params=params) scenario_0.run() scenario_1.run(base_model=scenario_0.model) models = [scenario_0.model, scenario_1.model] # Has herd immunity been reached? herd_immunity = has_immunity_been_reached(models[1]) # How many deaths total_nb_deaths = sum(models[0].derived_outputs["infection_deathsXall"]) return herd_immunity, total_nb_deaths, models def visualise_simulation(_models): pps = [] for scenario_index in range(len(_models)): pps.append( post_proc.PostProcessing( _models[scenario_index], requested_outputs=["prevXinfectiousXamong", "prevXrecoveredXamong"], scenario_number=scenario_index, requested_times={}, ) ) # FIXME: Matt broke this # old_outputs_plotter = Outputs(_models, pps, {}, plot_start_time=0) # old_outputs_plotter.plot_requested_outputs() def has_immunity_been_reached(_model): """ Determine whether herd immunity has been reached after running a model :param _model: a model run with no-intervention setting for testing herd-immunity :return: a boolean """ return max(_model.derived_outputs["incidence"]) == _model.derived_outputs["incidence"][0] def build_mixing_multipliers_matrix(mixing_multipliers): """ Builds a full 16x16 matrix of multipliers based on the parameters found in mixing_multipliers :param mixing_multipliers: a dictionary with the parameters a, b, c ,d ,e ,f :return: a matrix of multipliers """ mixing_multipliers_matrix = np.zeros((16, 16)) mixing_multipliers_matrix[0:3, 0:3] = mixing_multipliers["a"] * np.ones((3, 3)) mixing_multipliers_matrix[3:13, 3:13] = mixing_multipliers["b"] * np.ones((10, 10)) mixing_multipliers_matrix[13:, 13:] = mixing_multipliers["c"] * np.ones((3, 3)) mixing_multipliers_matrix[3:13, 0:3] = mixing_multipliers["d"] * np.ones((10, 3)) mixing_multipliers_matrix[0:3, 3:13] = mixing_multipliers["d"] * np.ones((3, 10)) mixing_multipliers_matrix[13:, 0:3] = mixing_multipliers["e"] * np.ones((3, 3)) mixing_multipliers_matrix[0:3, 13:] = mixing_multipliers["e"] * np.ones((3, 3)) mixing_multipliers_matrix[13:, 3:13] = mixing_multipliers["f"] * np.ones((3, 10)) mixing_multipliers_matrix[3:13, 13:] = mixing_multipliers["f"] * np.ones((10, 3)) return mixing_multipliers_matrix
[ "copy.deepcopy", "os.path.abspath", "autumn.post_processing.PostProcessing", "numpy.zeros", "numpy.ones", "autumn.tool_kit.scenarios.Scenario", "yaml.safe_load", "os.path.join" ]
[((267, 308), 'os.path.join', 'os.path.join', (['FILE_DIR', '"""opti_params.yml"""'], {}), "(FILE_DIR, 'opti_params.yml')\n", (279, 308), False, 'import os\n'), ((221, 246), 'os.path.abspath', 'os.path.abspath', (['__file__'], {}), '(__file__)\n', (236, 246), False, 'import os\n'), ((375, 400), 'yaml.safe_load', 'yaml.safe_load', (['yaml_file'], {}), '(yaml_file)\n', (389, 400), False, 'import yaml\n'), ((791, 816), 'copy.deepcopy', 'copy.deepcopy', (['aus.params'], {}), '(aus.params)\n', (804, 816), False, 'import copy\n'), ((1915, 1958), 'autumn.tool_kit.scenarios.Scenario', 'Scenario', (['build_model'], {'idx': '(0)', 'params': 'params'}), '(build_model, idx=0, params=params)\n', (1923, 1958), False, 'from autumn.tool_kit.scenarios import Scenario\n'), ((1976, 2019), 'autumn.tool_kit.scenarios.Scenario', 'Scenario', (['build_model'], {'idx': '(1)', 'params': 'params'}), '(build_model, idx=1, params=params)\n', (1984, 2019), False, 'from autumn.tool_kit.scenarios import Scenario\n'), ((3589, 3607), 'numpy.zeros', 'np.zeros', (['(16, 16)'], {}), '((16, 16))\n', (3597, 3607), True, 'import numpy as np\n'), ((3676, 3691), 'numpy.ones', 'np.ones', (['(3, 3)'], {}), '((3, 3))\n', (3683, 3691), True, 'import numpy as np\n'), ((3762, 3779), 'numpy.ones', 'np.ones', (['(10, 10)'], {}), '((10, 10))\n', (3769, 3779), True, 'import numpy as np\n'), ((3848, 3863), 'numpy.ones', 'np.ones', (['(3, 3)'], {}), '((3, 3))\n', (3855, 3863), True, 'import numpy as np\n'), ((3933, 3949), 'numpy.ones', 'np.ones', (['(10, 3)'], {}), '((10, 3))\n', (3940, 3949), True, 'import numpy as np\n'), ((4019, 4035), 'numpy.ones', 'np.ones', (['(3, 10)'], {}), '((3, 10))\n', (4026, 4035), True, 'import numpy as np\n'), ((4104, 4119), 'numpy.ones', 'np.ones', (['(3, 3)'], {}), '((3, 3))\n', (4111, 4119), True, 'import numpy as np\n'), ((4188, 4203), 'numpy.ones', 'np.ones', (['(3, 3)'], {}), '((3, 3))\n', (4195, 4203), True, 'import numpy as np\n'), ((4273, 4289), 'numpy.ones', 'np.ones', (['(3, 10)'], {}), '((3, 10))\n', (4280, 4289), True, 'import numpy as np\n'), ((4359, 4375), 'numpy.ones', 'np.ones', (['(10, 3)'], {}), '((10, 3))\n', (4366, 4375), True, 'import numpy as np\n'), ((2517, 2697), 'autumn.post_processing.PostProcessing', 'post_proc.PostProcessing', (['_models[scenario_index]'], {'requested_outputs': "['prevXinfectiousXamong', 'prevXrecoveredXamong']", 'scenario_number': 'scenario_index', 'requested_times': '{}'}), "(_models[scenario_index], requested_outputs=[\n 'prevXinfectiousXamong', 'prevXrecoveredXamong'], scenario_number=\n scenario_index, requested_times={})\n", (2541, 2697), True, 'import autumn.post_processing as post_proc\n')]
""" Utils operations ---------------- Collection of util operations for timeseries. """ import numpy as np from scipy import signal, interpolate def join_regimes(times, magnitudes): """Join different time series which represents events time series of different regimes and join altogether creating random values for the actual time series and scaling them using magnitudes information. Parameters ---------- times: list of np.ndarray the list of the event time timeseries considered. magnitudes: list the scale of the random values of these event series. Returns ------- times: np.ndarray the times samples for which we have values measured. values: np.ndarray the values of each time sample for the joined time-series. """ assert(len(times) == len(magnitudes)) values = [np.random.random(len(times[i]))*magnitudes[i] for i in range(len(times))] times = np.concatenate(times) values = np.concatenate(values) idxs = np.argsort(times) times = times[idxs] values = values[idxs] return times, values def format_as_regular_ts(times, values, intervals): """Format timeseries as regular timeseries. Parameters ---------- times: np.ndarray, shape (n,) the times sample we have values measured. values: np.ndarray, shape (n,) the values of the measured time samples. intervals: tuple (init, endit, step) the information needed to define the regular times sample. Returns ------- x: np.ndarray, shape (n,) the regular times samples for which we want the values measured. v: np.ndarray, shape (n,) the measured values for the regular times sample. """ x = np.arange(*intervals) v = interpolate.griddata(np.atleast_2d(times).T, values, np.atleast_2d(x).T, 'linear') v = v.squeeze() return x, v def apply_gaussianconvolved_ts(gridvalues, n_wind, stds): """Apply gaussian convolution to the given regular time series. Parameters ---------- gridvalues: np.ndarray, shape (n,) the values for the regular sample times. n_wind: int the size of the window in which we want to apply the convolution. stds: float the value of the standard deviation we want to have the gaussian filter we want to apply. Returns ------- convvalues: np.ndarray, shape (n,) the convolved resultant time series. """ wind = signal.gaussian(n_wind, stds) convvalues = signal.convolve(gridvalues, wind, 'same') return convvalues
[ "numpy.argsort", "numpy.arange", "scipy.signal.gaussian", "scipy.signal.convolve", "numpy.concatenate", "numpy.atleast_2d" ]
[((972, 993), 'numpy.concatenate', 'np.concatenate', (['times'], {}), '(times)\n', (986, 993), True, 'import numpy as np\n'), ((1007, 1029), 'numpy.concatenate', 'np.concatenate', (['values'], {}), '(values)\n', (1021, 1029), True, 'import numpy as np\n'), ((1041, 1058), 'numpy.argsort', 'np.argsort', (['times'], {}), '(times)\n', (1051, 1058), True, 'import numpy as np\n'), ((1776, 1797), 'numpy.arange', 'np.arange', (['*intervals'], {}), '(*intervals)\n', (1785, 1797), True, 'import numpy as np\n'), ((2542, 2571), 'scipy.signal.gaussian', 'signal.gaussian', (['n_wind', 'stds'], {}), '(n_wind, stds)\n', (2557, 2571), False, 'from scipy import signal, interpolate\n'), ((2589, 2630), 'scipy.signal.convolve', 'signal.convolve', (['gridvalues', 'wind', '"""same"""'], {}), "(gridvalues, wind, 'same')\n", (2604, 2630), False, 'from scipy import signal, interpolate\n'), ((1827, 1847), 'numpy.atleast_2d', 'np.atleast_2d', (['times'], {}), '(times)\n', (1840, 1847), True, 'import numpy as np\n'), ((1888, 1904), 'numpy.atleast_2d', 'np.atleast_2d', (['x'], {}), '(x)\n', (1901, 1904), True, 'import numpy as np\n')]
import numpy as np x1 = [1, 2, 3] x2 = [1, 1, 1] result = np.subtract(x1, x2) print(result) print(range(4))
[ "numpy.subtract" ]
[((60, 79), 'numpy.subtract', 'np.subtract', (['x1', 'x2'], {}), '(x1, x2)\n', (71, 79), True, 'import numpy as np\n')]
"""Support methods providing available stretching algorithms.""" # type annotations from __future__ import annotations from typing import TYPE_CHECKING # standard libraries import os from dataclasses import dataclass, field, InitVar from functools import partial import importlib # internal libraries from ..resources import CONFIG from .types import M, N # external libraries import numpy # static analysis if TYPE_CHECKING: from typing import Any, Callable, Iterable, Union from collections.abc import Container, Mapping, MutableSequence, Sequence C = Container[int] I = Iterable[int] F = Iterable[float] S = Sequence[str] D = Mapping[str, Any] # define library (public) interface __all__ = ['Stretching', ] # define configuration constants (internal) AXES = tuple(CONFIG['create']['grid']['axes']) METHODS = CONFIG['support']['stretch']['methods'] # define default paramater configuration constants (internal) ALPHA = CONFIG['support']['stretch']['alpha'] COLUMN = tuple(CONFIG['support']['stretch']['column']) DELIMITER = CONFIG['support']['stretch']['delimiter'] HEADER = CONFIG['support']['stretch']['header'] FUNCTION = tuple(CONFIG['support']['stretch']['function']) SOURCE = CONFIG['support']['stretch']['source'] def from_ascii(*, source: Iterable[str], column: Iterable[int], delimiter: Iterable[Union[str, int]], header: Iterable[int]) -> Callable[..., None]: """Factory method for implementing a ascii file interface for stretching algorithms.""" def wrapper(*, axes: C, coords: M, sizes: I, ndim: int, smin: F, smax: F) -> None: for axis, (s, c, d, h) in enumerate(zip(source, column, delimiter, header)): if axis < ndim and axis in axes: coords[axis] = numpy.genfromtxt(fname=s, usecols=(c, ), delimiter=d, skip_header=h, dtype=numpy.float_) return wrapper def from_python(*, path: Iterable[str], source: Iterable[str], function: Iterable[str], options: Mapping[str, Any]) -> Callable[..., None]: """Factory method for implementing a python interface for stretching algorithms.""" def wrapper(*, axes: C, coords: M, sizes: I, ndim: int, smin: F, smax: F) -> None: for axis, (p, s, f, size, low, high) in enumerate(zip(path, source, function, sizes, smin, smax)): if axis < ndim and axis in axes: loader = importlib.machinery.SourceFileLoader(s, os.path.join(p, s + '.py')) spec = importlib.util.spec_from_loader(loader.name, loader) module = importlib.util.module_from_spec(spec) loader.exec_module(module) kwargs = {kwarg: value[axis] for kwarg, value in options.items() if value[axis]} coords[axis] = getattr(module, f)(size, low, high, **kwargs) return wrapper def uniform(*, axes: C, coords: M, sizes: I, ndim: int, smin: F, smax: F) -> None: """Method implementing a uniform grid algorithm.""" for axis, (size, low, high) in enumerate(zip(sizes, smin, smax)): if axis < ndim and axis in axes: coords[axis] = numpy.linspace(low, high, size + 1) def tanh_mid(*, axes: C, coords: M, sizes: I, ndim: int, smin: F, smax: F, alpha: F) -> None: """Method implementing a symmetric hyperbolic tangent stretching algorithm.""" for axis, (size, low, high, a) in enumerate(zip(sizes, smin, smax, alpha)): if axis < ndim and axis in axes: coords[axis] = (high - low) * (numpy.tanh((-1.0 + 2.0 * numpy.linspace(0.0, 1.0, size + 1)) * numpy.arctanh(a)) / a + 1.0) / 2.0 + low class Stretching: """Class supporting the dispatching of axes to methods to build the grid.""" methods: S stretch: dict[str, Callable[..., None]] def __init__(self, methods: S, root: str, *, alpha: D = {}, column: D = {}, delimiter: D = {}, function: D = {}, header: D = {}, path: D = {}, source: D = {}, **kwargs): assert all(method in METHODS for method in methods), 'Unkown Stretching Method Specified!' self.methods = methods # fully specify function parameters with defaults if none provided s_alpha = numpy.array([alpha.get(key, ALPHA) for key in AXES]) s_column = [column.get(key, default) for key, default in zip(AXES, COLUMN)] s_delimiter = [delimiter.get(key, DELIMITER) for key in AXES] s_function = [function.get(key, default) for key, default in zip(AXES, FUNCTION)] s_header = [header.get(key, HEADER) for key in AXES] s_path = [path.get(key, root) for key in AXES] s_source = [source.get(key, SOURCE) for key in AXES] s_meta = {kwarg: [value.get(key, None) for key in AXES] for kwarg, value in kwargs.items()} self.stretch = { 'ascii': from_ascii(source=[os.path.join(p, s) for p, s in zip(s_path, s_source)], column=s_column, delimiter=s_delimiter, header=s_header), 'python': from_python(path=s_path, source=s_source, function=s_function, options=s_meta), 'uniform': uniform, 'tanh_mid': partial(tanh_mid, alpha=s_alpha), } def map_axes(self, check: str) -> list[int]: """Which axes does this method need to handle.""" return [axis for axis, method in enumerate(self.methods) if method == check] def any_axes(self, check: str) -> bool: """Does this method need to deal with any axes.""" return any(method == check for method in self.methods)
[ "functools.partial", "numpy.arctanh", "importlib.util.spec_from_loader", "numpy.genfromtxt", "numpy.linspace", "os.path.join", "importlib.util.module_from_spec" ]
[((3074, 3109), 'numpy.linspace', 'numpy.linspace', (['low', 'high', '(size + 1)'], {}), '(low, high, size + 1)\n', (3088, 3109), False, 'import numpy\n'), ((5110, 5142), 'functools.partial', 'partial', (['tanh_mid'], {'alpha': 's_alpha'}), '(tanh_mid, alpha=s_alpha)\n', (5117, 5142), False, 'from functools import partial\n'), ((1749, 1841), 'numpy.genfromtxt', 'numpy.genfromtxt', ([], {'fname': 's', 'usecols': '(c,)', 'delimiter': 'd', 'skip_header': 'h', 'dtype': 'numpy.float_'}), '(fname=s, usecols=(c,), delimiter=d, skip_header=h, dtype=\n numpy.float_)\n', (1765, 1841), False, 'import numpy\n'), ((2444, 2496), 'importlib.util.spec_from_loader', 'importlib.util.spec_from_loader', (['loader.name', 'loader'], {}), '(loader.name, loader)\n', (2475, 2496), False, 'import importlib\n'), ((2522, 2559), 'importlib.util.module_from_spec', 'importlib.util.module_from_spec', (['spec'], {}), '(spec)\n', (2553, 2559), False, 'import importlib\n'), ((2393, 2419), 'os.path.join', 'os.path.join', (['p', "(s + '.py')"], {}), "(p, s + '.py')\n", (2405, 2419), False, 'import os\n'), ((4788, 4806), 'os.path.join', 'os.path.join', (['p', 's'], {}), '(p, s)\n', (4800, 4806), False, 'import os\n'), ((3515, 3531), 'numpy.arctanh', 'numpy.arctanh', (['a'], {}), '(a)\n', (3528, 3531), False, 'import numpy\n'), ((3477, 3511), 'numpy.linspace', 'numpy.linspace', (['(0.0)', '(1.0)', '(size + 1)'], {}), '(0.0, 1.0, size + 1)\n', (3491, 3511), False, 'import numpy\n')]
''' Class for loading data into Pytorch float tensor From: https://gitlab.com/acasamitjana/latentmodels_ad ''' import torch from torch.functional import Tensor from torchvision import transforms from torch.utils.data import Dataset import numpy as np import pandas as pd class MyDataset(Dataset): def __init__(self, data, indices = False, transform=None): self.data = data if isinstance(data,(list, tuple)): self.data = [torch.from_numpy(d).float() if isinstance(d,np.ndarray) else d for d in self.data] self.N = len(self.data[0]) self.shape = np.shape(self.data[0]) elif isinstance(data,np.ndarray): self.data = torch.from_numpy(self.data).float() self.N = len(self.data) self.shape = np.shape(self.data) self.transform = transform self.indices = indices def __getitem__(self, index): if isinstance(self.data,list): x = [d[index] for d in self.data] else: x = self.data[index] if self.transform: x = self.transform(x) if self.indices: return x, index return x def __len__(self): return self.N class MyDataset_labels(Dataset): def __init__(self, data, labels, indices = False, transform=None): self.data = data self.labels = labels if isinstance(data,(list, tuple)): self.data = [torch.from_numpy(d).float() if isinstance(d,np.ndarray) else d for d in self.data] self.N = len(self.data[0]) self.shape = np.shape(self.data[0]) elif isinstance(data,np.ndarray): self.data = torch.from_numpy(self.data).float() self.N = len(self.data) self.shape = np.shape(self.data) self.labels = torch.from_numpy(self.labels).long() self.transform = transform self.indices = indices def __getitem__(self, index): if isinstance(self.data,list): x = [d[index] for d in self.data] else: x = self.data[index] if self.transform: x = self.transform(x) t = self.labels[index] if self.indices: return x, t, index return x, t def __len__(self): return self.N
[ "numpy.shape", "torch.from_numpy" ]
[((603, 625), 'numpy.shape', 'np.shape', (['self.data[0]'], {}), '(self.data[0])\n', (611, 625), True, 'import numpy as np\n'), ((1595, 1617), 'numpy.shape', 'np.shape', (['self.data[0]'], {}), '(self.data[0])\n', (1603, 1617), True, 'import numpy as np\n'), ((789, 808), 'numpy.shape', 'np.shape', (['self.data'], {}), '(self.data)\n', (797, 808), True, 'import numpy as np\n'), ((1781, 1800), 'numpy.shape', 'np.shape', (['self.data'], {}), '(self.data)\n', (1789, 1800), True, 'import numpy as np\n'), ((1836, 1865), 'torch.from_numpy', 'torch.from_numpy', (['self.labels'], {}), '(self.labels)\n', (1852, 1865), False, 'import torch\n'), ((692, 719), 'torch.from_numpy', 'torch.from_numpy', (['self.data'], {}), '(self.data)\n', (708, 719), False, 'import torch\n'), ((1684, 1711), 'torch.from_numpy', 'torch.from_numpy', (['self.data'], {}), '(self.data)\n', (1700, 1711), False, 'import torch\n'), ((456, 475), 'torch.from_numpy', 'torch.from_numpy', (['d'], {}), '(d)\n', (472, 475), False, 'import torch\n'), ((1448, 1467), 'torch.from_numpy', 'torch.from_numpy', (['d'], {}), '(d)\n', (1464, 1467), False, 'import torch\n')]
from matplotlib import pyplot as plt import argparse import matplotlib as mpl import numpy as np import cv2 import json from pathlib import Path from datetime import datetime def draw_marker(x, y, img, color=(0, 0, 255), cross_size=5): """Draw marker location on image.""" x, y = int(x), int(y) cv2.line(img, (x - cross_size, y), (x + cross_size, y), color, thickness=1) cv2.line(img, (x, y - cross_size), (x, y + cross_size), color, thickness=1) cv2.circle(img, (x, y), 3, color, 1) def click_event(event, x, y, flags, params): """Callback method for mouse click.""" window_name = params[0] img = params[1] calibration_markers_img = params[2] # Checking for right mouse clicks if event == cv2.EVENT_RBUTTONDOWN: calibration_markers_img.append([x, y]) draw_marker(x, y, img, color=(0, 0, 255)) # Paint marker location red cv2.imshow(window_name, img) def get_marker_img_pos(img): """Let user draw calibration marker positions in image""" window_name = 'image' marker_img_pos = [] cv2.namedWindow(window_name, cv2.WINDOW_GUI_NORMAL) cv2.resizeWindow(window_name, 960, 540) cv2.imshow(window_name, img) # Setting mouse handler for the image and calling the click_event() function cv2.setMouseCallback(window_name, click_event, [window_name, img, marker_img_pos]) # Wait for a key to be pressed to exit print("Please select 6 markers with the right mouse button, then press any key.") cv2.waitKey(0) cv2.destroyAllWindows() return np.array(marker_img_pos).astype(np.float32) def calculate_cam_pose(marker_pos, marker_img_pos, cam_mtx, dist_coeffs): """Calculate camera pose using marker positions in 3D and 2D.""" # Get initial estimation method = cv2.SOLVEPNP_EPNP ret, rvec_init, tvec_init = cv2.solvePnP(marker_pos, marker_img_pos, cam_mtx, dist_coeffs, flags=method) # Refine with iterative method method = cv2.SOLVEPNP_ITERATIVE ret, rvec, tvec = cv2.solvePnP(marker_pos, marker_img_pos, cam_mtx, dist_coeffs, rvec=rvec_init, tvec=tvec_init, useExtrinsicGuess=True, flags=method) return rvec, tvec def check_reprojection(img, marker_pos, marker_img_pos, rvec, tvec, cam_mtx, dist_coeffs): """Project marker positions from 3D to the image plane and compare with user indicated positions.""" marker_img_pos_proj, _ = cv2.projectPoints(marker_pos, rvec, tvec, cam_mtx, dist_coeffs) marker_img_pos_proj = marker_img_pos_proj.squeeze() # Check accuracy by reprojecting calibration markers error = np.linalg.norm(marker_img_pos - marker_img_pos_proj) / len(marker_img_pos) print(f"RMS error: {error}") for p in marker_img_pos: draw_marker(*p, img, color=(0, 0, 255)) for p in marker_img_pos_proj: draw_marker(*p, img, color=(0, 255, 0)) # Draw world axis cv2.drawFrameAxes(img, cam_mtx, dist_coeffs, rvec, tvec, 1) win_name = 'Reprojection' cv2.namedWindow(win_name, cv2.WINDOW_GUI_NORMAL) cv2.resizeWindow(win_name, 960, 540) cv2.imshow(win_name, img) print("Press any key to continue.") cv2.waitKey(0) cv2.destroyAllWindows() def save_extrinsic_calib(output_dir, rvec, tvec): """Save json file with extrinsic calibration in output directory.""" extrinsic_calib_data = {"rvec": rvec.tolist(), "tvec": tvec.tolist()} file_path = output_dir / 'extrinsic_calib.json' if file_path.exists(): answer = None while answer not in ['y', 'n']: answer = input("Extrinsic calibration file already exists. Do you want to overwrite? (y/n): ") if answer == 'y': break elif answer == 'n': time_str = datetime.now().strftime("%Y-%m-%d-%H-%M-%S") file_name = f"extrinsic_calib_{time_str}.json" file_path = output_dir / file_name break with open(file_path, "w") as f: json.dump(extrinsic_calib_data, f) print(f"Saved extrinsic calibration at {file_path}.") if __name__ == "__main__": parser = argparse.ArgumentParser(description='Calculate extrinsic camera calibration') parser.add_argument('video_file', type=str, help="Path to the video file") parser.add_argument('marker_file', type=str, help="Path to the .json file containing the 3D positions of the markers") parser.add_argument('intrinsic_calib', type=str, help="Path to the .json file containing the intrinsic camera calibration") parser.add_argument('--frame_id', type=int, help="Index of frame to use for calibration") parser.add_argument('--output', type=str, help='Output directory for calibration file') args = parser.parse_args() # Path to calibration video video_path = Path(args.video_file) if args.output is not None: output_dir = Path(args.output) else: output_dir = video_path.parent # Set index of frame to use for calibration if args.frame_id is not None: frame_id = args.frame_id else: frame_id = 0 # Get marker positions in 3D. Assume same coordinate system as motion capture recording. with open(args.marker_file) as f: marker_dict = json.load(f) marker_pos = np.array(marker_dict['pos']).astype(np.float32) # Load intrinsic camera calibration with open(args.intrinsic_calib) as f: intrinsic_calib = json.load(f) cam_mtx = np.array(intrinsic_calib['cam_mtx']) dist_coeffs = np.array(intrinsic_calib['dist_coeffs']) # Get frame for calibration cap = cv2.VideoCapture(args.video_file) cap.set(cv2.CAP_PROP_POS_FRAMES, frame_id) ret, frame = cap.read() # Get marker positions in 2D marker_img_pos = get_marker_img_pos(frame) rvec, tvec = calculate_cam_pose(marker_pos, marker_img_pos, cam_mtx, dist_coeffs) check_reprojection(frame, marker_pos, marker_img_pos, rvec, tvec, cam_mtx, dist_coeffs) save_extrinsic_calib(output_dir, rvec, tvec)
[ "argparse.ArgumentParser", "cv2.solvePnP", "pathlib.Path", "numpy.linalg.norm", "cv2.imshow", "cv2.line", "cv2.setMouseCallback", "cv2.drawFrameAxes", "cv2.destroyAllWindows", "datetime.datetime.now", "json.dump", "cv2.circle", "cv2.waitKey", "cv2.projectPoints", "cv2.resizeWindow", "json.load", "cv2.VideoCapture", "numpy.array", "cv2.namedWindow" ]
[((309, 384), 'cv2.line', 'cv2.line', (['img', '(x - cross_size, y)', '(x + cross_size, y)', 'color'], {'thickness': '(1)'}), '(img, (x - cross_size, y), (x + cross_size, y), color, thickness=1)\n', (317, 384), False, 'import cv2\n'), ((389, 464), 'cv2.line', 'cv2.line', (['img', '(x, y - cross_size)', '(x, y + cross_size)', 'color'], {'thickness': '(1)'}), '(img, (x, y - cross_size), (x, y + cross_size), color, thickness=1)\n', (397, 464), False, 'import cv2\n'), ((469, 505), 'cv2.circle', 'cv2.circle', (['img', '(x, y)', '(3)', 'color', '(1)'], {}), '(img, (x, y), 3, color, 1)\n', (479, 505), False, 'import cv2\n'), ((1074, 1125), 'cv2.namedWindow', 'cv2.namedWindow', (['window_name', 'cv2.WINDOW_GUI_NORMAL'], {}), '(window_name, cv2.WINDOW_GUI_NORMAL)\n', (1089, 1125), False, 'import cv2\n'), ((1130, 1169), 'cv2.resizeWindow', 'cv2.resizeWindow', (['window_name', '(960)', '(540)'], {}), '(window_name, 960, 540)\n', (1146, 1169), False, 'import cv2\n'), ((1174, 1202), 'cv2.imshow', 'cv2.imshow', (['window_name', 'img'], {}), '(window_name, img)\n', (1184, 1202), False, 'import cv2\n'), ((1291, 1377), 'cv2.setMouseCallback', 'cv2.setMouseCallback', (['window_name', 'click_event', '[window_name, img, marker_img_pos]'], {}), '(window_name, click_event, [window_name, img,\n marker_img_pos])\n', (1311, 1377), False, 'import cv2\n'), ((1510, 1524), 'cv2.waitKey', 'cv2.waitKey', (['(0)'], {}), '(0)\n', (1521, 1524), False, 'import cv2\n'), ((1530, 1553), 'cv2.destroyAllWindows', 'cv2.destroyAllWindows', ([], {}), '()\n', (1551, 1553), False, 'import cv2\n'), ((1847, 1923), 'cv2.solvePnP', 'cv2.solvePnP', (['marker_pos', 'marker_img_pos', 'cam_mtx', 'dist_coeffs'], {'flags': 'method'}), '(marker_pos, marker_img_pos, cam_mtx, dist_coeffs, flags=method)\n', (1859, 1923), False, 'import cv2\n'), ((2018, 2155), 'cv2.solvePnP', 'cv2.solvePnP', (['marker_pos', 'marker_img_pos', 'cam_mtx', 'dist_coeffs'], {'rvec': 'rvec_init', 'tvec': 'tvec_init', 'useExtrinsicGuess': '(True)', 'flags': 'method'}), '(marker_pos, marker_img_pos, cam_mtx, dist_coeffs, rvec=\n rvec_init, tvec=tvec_init, useExtrinsicGuess=True, flags=method)\n', (2030, 2155), False, 'import cv2\n'), ((2646, 2709), 'cv2.projectPoints', 'cv2.projectPoints', (['marker_pos', 'rvec', 'tvec', 'cam_mtx', 'dist_coeffs'], {}), '(marker_pos, rvec, tvec, cam_mtx, dist_coeffs)\n', (2663, 2709), False, 'import cv2\n'), ((3131, 3190), 'cv2.drawFrameAxes', 'cv2.drawFrameAxes', (['img', 'cam_mtx', 'dist_coeffs', 'rvec', 'tvec', '(1)'], {}), '(img, cam_mtx, dist_coeffs, rvec, tvec, 1)\n', (3148, 3190), False, 'import cv2\n'), ((3230, 3278), 'cv2.namedWindow', 'cv2.namedWindow', (['win_name', 'cv2.WINDOW_GUI_NORMAL'], {}), '(win_name, cv2.WINDOW_GUI_NORMAL)\n', (3245, 3278), False, 'import cv2\n'), ((3283, 3319), 'cv2.resizeWindow', 'cv2.resizeWindow', (['win_name', '(960)', '(540)'], {}), '(win_name, 960, 540)\n', (3299, 3319), False, 'import cv2\n'), ((3324, 3349), 'cv2.imshow', 'cv2.imshow', (['win_name', 'img'], {}), '(win_name, img)\n', (3334, 3349), False, 'import cv2\n'), ((3394, 3408), 'cv2.waitKey', 'cv2.waitKey', (['(0)'], {}), '(0)\n', (3405, 3408), False, 'import cv2\n'), ((3413, 3436), 'cv2.destroyAllWindows', 'cv2.destroyAllWindows', ([], {}), '()\n', (3434, 3436), False, 'import cv2\n'), ((4357, 4434), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Calculate extrinsic camera calibration"""'}), "(description='Calculate extrinsic camera calibration')\n", (4380, 4434), False, 'import argparse\n'), ((5032, 5053), 'pathlib.Path', 'Path', (['args.video_file'], {}), '(args.video_file)\n', (5036, 5053), False, 'from pathlib import Path\n'), ((5840, 5873), 'cv2.VideoCapture', 'cv2.VideoCapture', (['args.video_file'], {}), '(args.video_file)\n', (5856, 5873), False, 'import cv2\n'), ((897, 925), 'cv2.imshow', 'cv2.imshow', (['window_name', 'img'], {}), '(window_name, img)\n', (907, 925), False, 'import cv2\n'), ((2836, 2888), 'numpy.linalg.norm', 'np.linalg.norm', (['(marker_img_pos - marker_img_pos_proj)'], {}), '(marker_img_pos - marker_img_pos_proj)\n', (2850, 2888), True, 'import numpy as np\n'), ((4222, 4256), 'json.dump', 'json.dump', (['extrinsic_calib_data', 'f'], {}), '(extrinsic_calib_data, f)\n', (4231, 4256), False, 'import json\n'), ((5107, 5124), 'pathlib.Path', 'Path', (['args.output'], {}), '(args.output)\n', (5111, 5124), False, 'from pathlib import Path\n'), ((5475, 5487), 'json.load', 'json.load', (['f'], {}), '(f)\n', (5484, 5487), False, 'import json\n'), ((5666, 5678), 'json.load', 'json.load', (['f'], {}), '(f)\n', (5675, 5678), False, 'import json\n'), ((5697, 5733), 'numpy.array', 'np.array', (["intrinsic_calib['cam_mtx']"], {}), "(intrinsic_calib['cam_mtx'])\n", (5705, 5733), True, 'import numpy as np\n'), ((5756, 5796), 'numpy.array', 'np.array', (["intrinsic_calib['dist_coeffs']"], {}), "(intrinsic_calib['dist_coeffs'])\n", (5764, 5796), True, 'import numpy as np\n'), ((1567, 1591), 'numpy.array', 'np.array', (['marker_img_pos'], {}), '(marker_img_pos)\n', (1575, 1591), True, 'import numpy as np\n'), ((5509, 5537), 'numpy.array', 'np.array', (["marker_dict['pos']"], {}), "(marker_dict['pos'])\n", (5517, 5537), True, 'import numpy as np\n'), ((3996, 4010), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (4008, 4010), False, 'from datetime import datetime\n')]
# -*- coding: utf-8 -*- """ Created on Mon Feb 15 18:24:03 2021 @author: <NAME> """ import os import numpy as np import nibabel as nib # input_path = r'G:\MINCVM\PCLKO\PCP2-DTR\maps\\' # output_path = r'G:\MINCVM\PCLKO\PCP2-DTR\maps\Extracted\\' input_path = r'G:\MINCVM\PCLKO\HOPX-DTR\maps\\' output_path = r'G:\MINCVM\PCLKO\HOPX-DTR\maps\Extracted\\' for file in os.listdir(input_path): if file.endswith('.nii.gz'): image_name = file img = nib.load((input_path + image_name)) img_data = img.get_fdata() img_data = np.asarray(img_data) sizer = np.asarray(img_data.shape) sub_img = np.empty((sizer[0],sizer[1])) affine = np.diag([1,2,3,4]) sub_img = img_data[:,:,2] sub_img_nii = nib.Nifti1Image(sub_img,affine) nib.save(sub_img_nii,(output_path+image_name[:-7]+'_MapExtracted.nii.gz'))
[ "nibabel.Nifti1Image", "nibabel.load", "numpy.empty", "numpy.asarray", "nibabel.save", "numpy.diag", "os.listdir" ]
[((371, 393), 'os.listdir', 'os.listdir', (['input_path'], {}), '(input_path)\n', (381, 393), False, 'import os\n'), ((486, 519), 'nibabel.load', 'nib.load', (['(input_path + image_name)'], {}), '(input_path + image_name)\n', (494, 519), True, 'import nibabel as nib\n'), ((585, 605), 'numpy.asarray', 'np.asarray', (['img_data'], {}), '(img_data)\n', (595, 605), True, 'import numpy as np\n'), ((622, 648), 'numpy.asarray', 'np.asarray', (['img_data.shape'], {}), '(img_data.shape)\n', (632, 648), True, 'import numpy as np\n'), ((676, 706), 'numpy.empty', 'np.empty', (['(sizer[0], sizer[1])'], {}), '((sizer[0], sizer[1]))\n', (684, 706), True, 'import numpy as np\n'), ((723, 744), 'numpy.diag', 'np.diag', (['[1, 2, 3, 4]'], {}), '([1, 2, 3, 4])\n', (730, 744), True, 'import numpy as np\n'), ((816, 848), 'nibabel.Nifti1Image', 'nib.Nifti1Image', (['sub_img', 'affine'], {}), '(sub_img, affine)\n', (831, 848), True, 'import nibabel as nib\n'), ((865, 942), 'nibabel.save', 'nib.save', (['sub_img_nii', "(output_path + image_name[:-7] + '_MapExtracted.nii.gz')"], {}), "(sub_img_nii, output_path + image_name[:-7] + '_MapExtracted.nii.gz')\n", (873, 942), True, 'import nibabel as nib\n')]
import numpy as np import scipy.ndimage as nd def interpolate_nn(data: np.array) -> np.array: """ Function to fill nan values in a 2D array using nearest neighbor interpolation. Source: https://stackoverflow.com/a/27745627 Parameters ---------- data : np.array Data array (2D) in which areas with np.nan will be filled in with nearest neighbor. Returns ------- np.array: [TODO:description] """ ind = nd.distance_transform_edt(np.isnan(data), return_distances=False, return_indices=True) return data[tuple(ind)]
[ "numpy.isnan" ]
[((503, 517), 'numpy.isnan', 'np.isnan', (['data'], {}), '(data)\n', (511, 517), True, 'import numpy as np\n')]
from nose.tools import assert_equal, assert_true from numpy.testing import assert_array_equal import numpy as np import re from seqlearn.evaluation import bio_f_score, SequenceKFold def test_bio_f_score(): # Outputs from with the "conlleval" Perl script from CoNLL 2002. examples = [ ("OBIO", "OBIO", 1.), ("BII", "OBI", 0.), ("BB", "BI", 0.), ("BBII", "BBBB", 1 / 3.), ("BOOBIB", "BOBOOB", 2 / 3.), ] for y_true, y_pred, score in examples: y_true = list(y_true) y_pred = list(y_pred) assert_equal(score, bio_f_score(y_true, y_pred)) def test_kfold(): sequences = [ "BIIOOOBOO", "OOBIOOOBI", "OOOOO", "BIIOOOOO", "OBIOOBIIIII", "OOBII", "BIBIBIO", ] y = np.asarray(list(''.join(sequences))) for random_state in [75, 82, 91, 57, 291]: for indices in [False, True]: kfold = SequenceKFold(map(len, sequences), n_folds=3, shuffle=True, indices=indices, random_state=random_state) folds = list(iter(kfold)) for train, test in folds: if indices: assert_true(np.issubdtype(train.dtype, np.integer)) assert_true(np.issubdtype(test.dtype, np.integer)) assert_true(np.all(train < len(y))) assert_true(np.all(test < len(y))) else: assert_true(np.issubdtype(train.dtype, bool)) assert_true(np.issubdtype(test.dtype, bool)) assert_equal(len(train), len(y)) assert_equal(len(test), len(y)) assert_array_equal(~train, test) y_train = ''.join(y[train]) y_test = ''.join(y[test]) # consistent BIO labeling preserved assert_true(re.match(r'O*(?:BI*)O*', y_train)) assert_true(re.match(r'O*(?:BI*)O*', y_test))
[ "numpy.testing.assert_array_equal", "numpy.issubdtype", "re.match", "seqlearn.evaluation.bio_f_score" ]
[((590, 617), 'seqlearn.evaluation.bio_f_score', 'bio_f_score', (['y_true', 'y_pred'], {}), '(y_true, y_pred)\n', (601, 617), False, 'from seqlearn.evaluation import bio_f_score, SequenceKFold\n'), ((1761, 1793), 'numpy.testing.assert_array_equal', 'assert_array_equal', (['(~train)', 'test'], {}), '(~train, test)\n', (1779, 1793), False, 'from numpy.testing import assert_array_equal\n'), ((1961, 1993), 're.match', 're.match', (['"""O*(?:BI*)O*"""', 'y_train'], {}), "('O*(?:BI*)O*', y_train)\n", (1969, 1993), False, 'import re\n'), ((2024, 2055), 're.match', 're.match', (['"""O*(?:BI*)O*"""', 'y_test'], {}), "('O*(?:BI*)O*', y_test)\n", (2032, 2055), False, 'import re\n'), ((1261, 1299), 'numpy.issubdtype', 'np.issubdtype', (['train.dtype', 'np.integer'], {}), '(train.dtype, np.integer)\n', (1274, 1299), True, 'import numpy as np\n'), ((1333, 1370), 'numpy.issubdtype', 'np.issubdtype', (['test.dtype', 'np.integer'], {}), '(test.dtype, np.integer)\n', (1346, 1370), True, 'import numpy as np\n'), ((1537, 1569), 'numpy.issubdtype', 'np.issubdtype', (['train.dtype', 'bool'], {}), '(train.dtype, bool)\n', (1550, 1569), True, 'import numpy as np\n'), ((1603, 1634), 'numpy.issubdtype', 'np.issubdtype', (['test.dtype', 'bool'], {}), '(test.dtype, bool)\n', (1616, 1634), True, 'import numpy as np\n')]
import numpy as np import pandas as pd from typing import Union def unit_vector(azi:Union[int,float]) -> np.array: """ Get the unit vector2D of a given azimuth Input: azi -> (int,float) Azimuth in Degrees Return: u -> (np.ndarray) numpy array with a shape of (2,1) with the x and y components of unit vector """ assert isinstance(azi,(int,float,np.ndarray)) alpha = 90 - azi alpha_rad = np.deg2rad(alpha) x = np.cos(alpha_rad) y = np.sin(alpha_rad) p = np.array([[x,y]]) return p def projection_1d(x, azi, center=None): """ Get the 1D projection of a series of 2D Coordinates within a given azimuth direction Input: x -> (np.ndarray) Numpy array of shape (m,2) being m the number of coordinates azi -> (int,float) Azimuth in Degrees center -(list,np.ndarray) list or numpy array with the center Return: u -> (np.ndarray) numpy array with a shape of (m,1) """ assert isinstance(x,np.ndarray) and x.shape[1] == 2 assert isinstance(azi,(int,float,np.ndarray)) assert isinstance(center,(list,np.ndarray, type(None))) if isinstance(center,type(None)): center = x.mean(axis=0) else: center = np.atleast_1d(center) assert center.shape == (2,) #Normalize the coordinates by substracting the average coordinates x = x - center # Get the unit vector u = unit_vector(azi) # Projection over the azimuth direction cv = np.squeeze(np.dot(x,u.T)) return cv, center
[ "numpy.deg2rad", "numpy.sin", "numpy.array", "numpy.cos", "numpy.dot", "numpy.atleast_1d" ]
[((438, 455), 'numpy.deg2rad', 'np.deg2rad', (['alpha'], {}), '(alpha)\n', (448, 455), True, 'import numpy as np\n'), ((464, 481), 'numpy.cos', 'np.cos', (['alpha_rad'], {}), '(alpha_rad)\n', (470, 481), True, 'import numpy as np\n'), ((490, 507), 'numpy.sin', 'np.sin', (['alpha_rad'], {}), '(alpha_rad)\n', (496, 507), True, 'import numpy as np\n'), ((516, 534), 'numpy.array', 'np.array', (['[[x, y]]'], {}), '([[x, y]])\n', (524, 534), True, 'import numpy as np\n'), ((1250, 1271), 'numpy.atleast_1d', 'np.atleast_1d', (['center'], {}), '(center)\n', (1263, 1271), True, 'import numpy as np\n'), ((1516, 1530), 'numpy.dot', 'np.dot', (['x', 'u.T'], {}), '(x, u.T)\n', (1522, 1530), True, 'import numpy as np\n')]
import time import numpy as np import analyzer import config as cfg import explots import fileutils import motifutils as motif import visutils def _analysis(analysis_name, audio, fs, length, methods, name='audio', show_plot=(), k=cfg.N_ClUSTERS, title_hook='{}', threshold=cfg.K_THRESH): G_dict = {} results_dict = {} if not isinstance(methods, tuple) and not isinstance(methods, list): methods = (methods,) for m in methods: if analysis_name == 'Segmentation': starts, ends, motif_labels, G = analyzer.analyze(audio, fs, k_clusters=k, seg_length=length, seg_method=m, threshold=threshold) elif analysis_name == 'Similarity': starts, ends, motif_labels, G = analyzer.analyze(audio, fs, k, seg_length=length, similarity_method=m, threshold=threshold) elif analysis_name == 'K-Means': starts, ends, motif_labels, G = analyzer.analyze(audio, fs, m, seg_length=length, cluster_method=analysis_name, threshold=threshold) elif analysis_name == 'Clustering': starts, ends, motif_labels, G = analyzer.analyze(audio, fs, k, seg_length=length, cluster_method=m, threshold=threshold) elif analysis_name == 'Threshold': starts, ends, motif_labels, G = analyzer.analyze(audio, fs, threshold=m) else: print("Unrecognized analysis name: {exp_name}".format(exp_name=analysis_name)) return None, None G_dict[m] = G results = motif.pack_motif(starts, ends, motif_labels) results_dict[m] = results title_suffix = title_hook.format(m) explots.draw_results(audio, fs, results, show_plot, G=G, name=name, title_hook=title_suffix, draw_ref=(m is methods[0]), num_groups=k) return results_dict, G_dict def segmentation_analysis(audio, fs, length, name='audio', show_plot=(), methods=('regular', 'onset'), k=cfg.N_ClUSTERS): results_dict, G_dict = _analysis('Segmentation', audio, fs, length, methods, name=name, show_plot=show_plot, k=k, title_hook='with {} segmentation') return results_dict, G_dict def similarity_analysis(audio, fs, length, name='audio', show_plot=(), methods=('match', 'shazam'), k=cfg.N_ClUSTERS): results_dict, G_dict = _analysis('Similarity', audio, fs, length, methods, name=name, show_plot=show_plot, k=k, title_hook='with {} similarity') return results_dict, G_dict def k_means_analysis(audio, fs, length, name='audio', show_plot=(), k_clusters=(cfg.N_ClUSTERS, cfg.N_ClUSTERS + 1)): results_dict, G_dict = _analysis('K-Means', audio, fs, length, methods=k_clusters, name=name, show_plot=show_plot, title_hook='with {}-means clustering') return results_dict, G_dict def clustering_analysis(audio, fs, length, name='audio', show_plot=(), methods=('kmeans', 'agglom', 'spectral'), k=cfg.N_ClUSTERS): results_dict, G_dict = _analysis('Clustering', audio, fs, length, methods, name=name, show_plot=show_plot, k=k, title_hook='with {} clustering') return results_dict, G_dict def threshold_analysis(audio, fs, length, name='audio', show_plot=(), threshold=(0, 0.5, 1)): exp_name = 'Threshold' results_dict, G_dict = _analysis(exp_name, audio, fs, length, methods=threshold, name=name, show_plot=show_plot, title_hook='') # title_hook='with {} Threshold') return results_dict, G_dict # Write out an entire results set def write_results(audio, fs, name, out_dir, methods, results): for m in methods: obs_motifs = results[m] write_name = name + ' ' + str(m) write_motifs(audio, fs, write_name, out_dir, obs_motifs) # Write out all identified motifs in a single analysis def write_motifs(audio, fs, name, audio_dir, motifs): time_id = int(round(time.time() * 1000)) motif_labels = motifs[cfg.LABEL_IDX] num_motifs = motif_labels.shape[0] motif_dict = dict.fromkeys(np.unique(motif_labels), 0) for i in range(num_motifs): motif_start = int(motifs[cfg.START_IDX, i] * fs) motif_end = int(motifs[cfg.END_IDX, i] * fs) this_motif = audio[motif_start:motif_end] this_instance = motif_dict[motif_labels[i]] motif_dict[motif_labels[i]] = motif_dict[motif_labels[i]] + 1 this_name = "{name}_m{motif}_i{instance}_{id}".format(name=name, motif=int(motif_labels[i]), instance=this_instance, id=time_id) fileutils.write_audio(this_motif, fs, this_name, audio_dir) return def tune_length_with_audio(audio, fs): return cfg.SEGMENT_LENGTH * np.ceil(((audio.shape[0] / fs) / 30)).astype(int) def main(): name = 't20' in_dir = './bin/' out_dir = './bin/results' audio, fs = fileutils.load_audio(name, audio_dir=in_dir) # audio_labels = fileutils.load_labels(name, label_dir=in_dir) # Should be sensitive to the length of the track, as well as k # Perhaps length should be extended as song goes longer than 30 seconds; # 3 second = 30 seconds, 18 seconds = 3 min # length = tune_length_with_audio(audio, fs) length = cfg.SEGMENT_LENGTH # explots.draw_results_reference(audio, fs, audio_labels, name=name, # show_plot=('motif',)) # segmentation_analysis(audio, fs, length, num_motifs=3, name=name, # show_plot=('arc',)) # k_means_analysis(audio, fs, length, name=name, k_clusters=(5, 25, 50), # show_plot=('motif',)) thresh = 11 audio_sample = audio results, G_set = threshold_analysis(audio_sample, fs, length, name=name, show_plot=('motif','matrix'), threshold=thresh) write_motifs(audio_sample, fs, name, out_dir, results[thresh]) visutils.show() return if __name__ == '__main__': main()
[ "fileutils.write_audio", "numpy.ceil", "analyzer.analyze", "time.time", "visutils.show", "motifutils.pack_motif", "fileutils.load_audio", "explots.draw_results", "numpy.unique" ]
[((6261, 6305), 'fileutils.load_audio', 'fileutils.load_audio', (['name'], {'audio_dir': 'in_dir'}), '(name, audio_dir=in_dir)\n', (6281, 6305), False, 'import fileutils\n'), ((7285, 7300), 'visutils.show', 'visutils.show', ([], {}), '()\n', (7298, 7300), False, 'import visutils\n'), ((2297, 2341), 'motifutils.pack_motif', 'motif.pack_motif', (['starts', 'ends', 'motif_labels'], {}), '(starts, ends, motif_labels)\n', (2313, 2341), True, 'import motifutils as motif\n'), ((2429, 2565), 'explots.draw_results', 'explots.draw_results', (['audio', 'fs', 'results', 'show_plot'], {'G': 'G', 'name': 'name', 'title_hook': 'title_suffix', 'draw_ref': '(m is methods[0])', 'num_groups': 'k'}), '(audio, fs, results, show_plot, G=G, name=name,\n title_hook=title_suffix, draw_ref=m is methods[0], num_groups=k)\n', (2449, 2565), False, 'import explots\n'), ((5293, 5316), 'numpy.unique', 'np.unique', (['motif_labels'], {}), '(motif_labels)\n', (5302, 5316), True, 'import numpy as np\n'), ((5968, 6027), 'fileutils.write_audio', 'fileutils.write_audio', (['this_motif', 'fs', 'this_name', 'audio_dir'], {}), '(this_motif, fs, this_name, audio_dir)\n', (5989, 6027), False, 'import fileutils\n'), ((558, 657), 'analyzer.analyze', 'analyzer.analyze', (['audio', 'fs'], {'k_clusters': 'k', 'seg_length': 'length', 'seg_method': 'm', 'threshold': 'threshold'}), '(audio, fs, k_clusters=k, seg_length=length, seg_method=m,\n threshold=threshold)\n', (574, 657), False, 'import analyzer\n'), ((987, 1082), 'analyzer.analyze', 'analyzer.analyze', (['audio', 'fs', 'k'], {'seg_length': 'length', 'similarity_method': 'm', 'threshold': 'threshold'}), '(audio, fs, k, seg_length=length, similarity_method=m,\n threshold=threshold)\n', (1003, 1082), False, 'import analyzer\n'), ((5161, 5172), 'time.time', 'time.time', ([], {}), '()\n', (5170, 5172), False, 'import time\n'), ((6112, 6145), 'numpy.ceil', 'np.ceil', (['(audio.shape[0] / fs / 30)'], {}), '(audio.shape[0] / fs / 30)\n', (6119, 6145), True, 'import numpy as np\n'), ((1348, 1453), 'analyzer.analyze', 'analyzer.analyze', (['audio', 'fs', 'm'], {'seg_length': 'length', 'cluster_method': 'analysis_name', 'threshold': 'threshold'}), '(audio, fs, m, seg_length=length, cluster_method=\n analysis_name, threshold=threshold)\n', (1364, 1453), False, 'import analyzer\n'), ((1721, 1813), 'analyzer.analyze', 'analyzer.analyze', (['audio', 'fs', 'k'], {'seg_length': 'length', 'cluster_method': 'm', 'threshold': 'threshold'}), '(audio, fs, k, seg_length=length, cluster_method=m,\n threshold=threshold)\n', (1737, 1813), False, 'import analyzer\n'), ((2080, 2120), 'analyzer.analyze', 'analyzer.analyze', (['audio', 'fs'], {'threshold': 'm'}), '(audio, fs, threshold=m)\n', (2096, 2120), False, 'import analyzer\n')]
""" Synthesize speech from the extracted text. """ import os from os import system import matplotlib.pyplot as plt from tqdm import tqdm from pprint import pformat import logging from scipy.io import wavfile import numpy as np def _remove_if_exists(filepath: str): os.remove(filepath) if os.path.isfile(filepath) else None def _synthesize_wav(text: str, model_name: str = None): """Synthesize the wav audio file from the text (using the tts module). This function will write the synthesized audio to a file called 'tts_output.wav' in the current directory. Parameters ---------- text : str The source text that should be read. model_name : str (optional) If the user wants to use a different model than the standard one. """ if model_name is None: tts_command = 'tts --text "{}"'.format(text) else: tts_command = 'tts --model_name {} --text "{}"'.format( model_name, text ) # This will write the file to 'tts_output.wav' r = system(tts_command + "> /dev/null") if r != 0: logging.error( "Error occurred trying to synthesize speech, return value: {}" " command run: '{}'".format(r, tts_command) ) # The script requires this part to work properly # Otherwise we have no speech obviously quit(1) max_values_by_dtype = {"int16": 2 ** 15, "int32": 2 ** 16} def _trim_wav_file( filename: str = "./tts_output.wav", threshhold: float = 0.1, n_frames_after_threshhold: int = 500, ): """Trim a wave file so when later concatenated, the pauses aren't too long. Each file is scanned when the sound level first and last reaches the given threshhold. It is then trimmed after / before n frames distance from the first / last frame that exceeded the threshhold. Parameters ---------- filename : str Path to wav file which to trim threshhold : float Threshold until when to trim n_frames_after_threshhold : int Trim n frames after and before the threshhold is reached. """ # Read the wave file a = wavfile.read(filename) # Find important parameters framerate, signal = a num_frames = signal.shape[0] threshhold_int = int(threshhold * max_values_by_dtype[str(signal.dtype)]) signal_exceeding = np.array(np.abs(signal) > threshhold_int, dtype="int16") indices = np.argwhere(signal_exceeding) first, last = min(indices), max(indices) # Add some space before and after threshhold trim_start = (first - n_frames_after_threshhold)[0] trim_end = (last + n_frames_after_threshhold)[0] # The indices need to be in the correct range trim_start = max(0, trim_start) trim_end = min(num_frames, trim_end) # Find out if anything needs to be trimmed at all if trim_start == 0 and trim_end == num_frames: logging.info( "Not trimming file '{}' as it is not needed".format(filename) ) return trimmed_signal = signal[trim_start:trim_end] # Output a pretty debug log so everything can be debugged nicely logging.debug( "Trimming file with parameters: \n{}".format( pformat( { "filename": filename, "framerate": framerate, "trim_start": trim_start, "trim_end": trim_end, "threshhold": threshhold, "threshhold_int": threshhold_int, "wave_dtype": signal.dtype, "num_frames": num_frames, "seconds_original": num_frames / framerate, "seconds_removed": -(trimmed_signal.shape[0] / framerate) + (num_frames / framerate), } ) ) ) # Remove the original file _remove_if_exists(filename) # wavfile.write("trimmed.wav", framerate, trimmed_signal) wavfile.write(filename, framerate, trimmed_signal) def _transcode_with_ffmepg( text_piece_number: int, target_directory: str, source_file: str = "tts_output.wav", ): filename = os.path.join(target_directory, f"{text_piece_number:08}.mp3") ffmpeg_command = ( "ffmpeg -loglevel error -y -i {} -r 44100 -ac 1 {}".format( source_file, filename ) ) r = system(ffmpeg_command) if r != 0: logging.error( "Error occurred transcoding to mp3: return value {}, command run" " '{}'".format(r, ffmpeg_command) ) quit(1) return filename def _concat_mp3_files(output_file: str, filenames: list): # First create filename list for ffmpeg _remove_if_exists("mylist.txt") with open("mylist.txt", "w") as f: for f_name in filenames: f.write("file '{}'\n".format(f_name)) # Written the filename list ffmpeg_command = ( "ffmpeg -f concat -safe 0 -i mylist.txt -c copy -r 44100 -ac 1 {}" .format(output_file) ) r = system(ffmpeg_command) if r != 0: logging.error( "Error occurred concatenating mp3 files: '{}'".format( ffmpeg_command ) ) quit(1) else: logging.info( "Script successful, enjoy your audiobook at: '{}'".format( output_file ) ) # Now clean up for f in filenames: _remove_if_exists(f) def text_piece_generator(full_text: str): current_piece = "" sentences = full_text.split(".") logging.info( "Synthesizing a total of {} sentences with {} characters".format( len(sentences), len(full_text) ) ) for sentence in tqdm(sentences): # First split by sentences current_piece += sentence # If sentence has too many words, split further by comma # If it has too few words append the next one # For some reason the sentences still contain leading and trailing spaces current_piece = current_piece.rstrip(" ").lstrip(" ") words = current_piece.split(" ") logging.debug("Current text piece: '{}'".format(current_piece)) if len(words) < 12: if len(current_piece) > 0 and current_piece != " ": yield current_piece current_piece = "" else: for idx in range(0, len(words), 12): subwords = words[idx : idx + 12] subwords = " ".join(subwords) logging.debug("Subword: '{}'".format(subwords)) if len(subwords) > 0 and subwords != " ": yield subwords current_piece = "" # Make sure also the last sentence will be synthesized if len(current_piece) > 0: yield current_piece def synthesize_speech( text: str, output_file: str, model_name: str = None, ): # Maybe change this later if needed mp3_dir = os.path.curdir files_written = [] for piece_id, text_piece in enumerate(text_piece_generator(text)): # TODO: Find out when and why this happens if len(text_piece) > 0: logging.debug("Synthesizing: '{}'".format(text_piece)) # First synthesize the wav file _synthesize_wav(text_piece, model_name=model_name) # Now transcode to mp3 # First trim the wave file accordingly _trim_wav_file() filename = _transcode_with_ffmepg(piece_id, mp3_dir) files_written.append(filename) # Now concatenate all the mp3 files logging.info("Finished synthesizing, now concatenating the audiofiles") _concat_mp3_files(output_file, files_written) # Clean up some files _remove_if_exists("./mylist.txt") _remove_if_exists("./converted.html") _remove_if_exists("./tts_output.wav")
[ "tqdm.tqdm", "os.remove", "numpy.abs", "pprint.pformat", "os.system", "scipy.io.wavfile.write", "scipy.io.wavfile.read", "logging.info", "os.path.isfile", "numpy.argwhere", "os.path.join" ]
[((1039, 1074), 'os.system', 'system', (["(tts_command + '> /dev/null')"], {}), "(tts_command + '> /dev/null')\n", (1045, 1074), False, 'from os import system\n'), ((2158, 2180), 'scipy.io.wavfile.read', 'wavfile.read', (['filename'], {}), '(filename)\n', (2170, 2180), False, 'from scipy.io import wavfile\n'), ((2448, 2477), 'numpy.argwhere', 'np.argwhere', (['signal_exceeding'], {}), '(signal_exceeding)\n', (2459, 2477), True, 'import numpy as np\n'), ((4007, 4057), 'scipy.io.wavfile.write', 'wavfile.write', (['filename', 'framerate', 'trimmed_signal'], {}), '(filename, framerate, trimmed_signal)\n', (4020, 4057), False, 'from scipy.io import wavfile\n'), ((4203, 4264), 'os.path.join', 'os.path.join', (['target_directory', 'f"""{text_piece_number:08}.mp3"""'], {}), "(target_directory, f'{text_piece_number:08}.mp3')\n", (4215, 4264), False, 'import os\n'), ((4416, 4438), 'os.system', 'system', (['ffmpeg_command'], {}), '(ffmpeg_command)\n', (4422, 4438), False, 'from os import system\n'), ((5091, 5113), 'os.system', 'system', (['ffmpeg_command'], {}), '(ffmpeg_command)\n', (5097, 5113), False, 'from os import system\n'), ((5812, 5827), 'tqdm.tqdm', 'tqdm', (['sentences'], {}), '(sentences)\n', (5816, 5827), False, 'from tqdm import tqdm\n'), ((7699, 7770), 'logging.info', 'logging.info', (['"""Finished synthesizing, now concatenating the audiofiles"""'], {}), "('Finished synthesizing, now concatenating the audiofiles')\n", (7711, 7770), False, 'import logging\n'), ((295, 319), 'os.path.isfile', 'os.path.isfile', (['filepath'], {}), '(filepath)\n', (309, 319), False, 'import os\n'), ((272, 291), 'os.remove', 'os.remove', (['filepath'], {}), '(filepath)\n', (281, 291), False, 'import os\n'), ((2385, 2399), 'numpy.abs', 'np.abs', (['signal'], {}), '(signal)\n', (2391, 2399), True, 'import numpy as np\n'), ((3243, 3608), 'pprint.pformat', 'pformat', (["{'filename': filename, 'framerate': framerate, 'trim_start': trim_start,\n 'trim_end': trim_end, 'threshhold': threshhold, 'threshhold_int':\n threshhold_int, 'wave_dtype': signal.dtype, 'num_frames': num_frames,\n 'seconds_original': num_frames / framerate, 'seconds_removed': -(\n trimmed_signal.shape[0] / framerate) + num_frames / framerate}"], {}), "({'filename': filename, 'framerate': framerate, 'trim_start':\n trim_start, 'trim_end': trim_end, 'threshhold': threshhold,\n 'threshhold_int': threshhold_int, 'wave_dtype': signal.dtype,\n 'num_frames': num_frames, 'seconds_original': num_frames / framerate,\n 'seconds_removed': -(trimmed_signal.shape[0] / framerate) + num_frames /\n framerate})\n", (3250, 3608), False, 'from pprint import pformat\n')]
# Copyright 2022 Huawei Technologies Co., Ltd # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================ import numpy as np import pytest import mindspore.context as context import mindspore.nn as nn from mindspore import Tensor from mindspore.ops import operations as P tensor_scatter_func_map = { "update": P.TensorScatterUpdate, "min": P.TensorScatterMin, "max": P.TensorScatterMax, "add": P.TensorScatterAdd, "sub": P.TensorScatterSub, "mul": P.TensorScatterMul, "div": P.TensorScatterDiv, } np_benchmark_func_map = { "update": lambda a, b: b, "add": lambda a, b: a + b, "sub": lambda a, b: a - b, "mul": lambda a, b: a * b, "div": lambda a, b: a / b, "min": min, "max": max, } class TestTensorScatterFuncNet(nn.Cell): def __init__(self, func, input_x, indices, updates): super(TestTensorScatterFuncNet, self).__init__() self.scatter_func = tensor_scatter_func_map.get(func)() self.input_x = Tensor(input_x) self.indices = Tensor(indices) self.updates = Tensor(updates) def construct(self): out = self.scatter_func(self.input_x, self.indices, self.updates) return out def tensor_scatter_np_benchmark(np_func, input_x, indices, updates): """ Feature: benchmark to generate result. Description: benchmark function to generate result. Expectation: match to tensor scatter binary op. """ result = input_x.copy() benchmark_func = np_benchmark_func_map.get(np_func) for index, _ in np.ndenumerate(np.zeros(indices.shape[:-1])): out_index = tuple(indices[index]) result[out_index] = benchmark_func(result[out_index], updates[index]) return result @pytest.mark.level0 @pytest.mark.platform_x86_gpu_training @pytest.mark.env_onecard @pytest.mark.parametrize('func_name', ["update", "min", "max", "add", "sub", "mul", "div"]) @pytest.mark.parametrize('input_data_type', [np.float16, np.float32, np.float64, np.int8, np.int32]) @pytest.mark.parametrize('index_data_type', [np.int32, np.int64]) def test_tensor_scatter(func_name, input_data_type, index_data_type): """ Feature: test_tensor_scatter Description: Test the function of tensor scatter binary op. Expectation: match to numpy benchmark. """ context.set_context(mode=context.GRAPH_MODE) arr_input = np.arange(21).reshape(3, 7).astype(input_data_type) arr_indices = np.array([[0, 1], [1, 1], [0, 5], [0, 2], [2, 1]]).astype(index_data_type) arr_update = np.array([3.2, 1.1, 5.3, -2.2, -1.0]).astype(input_data_type) tensor_scatter_net = TestTensorScatterFuncNet(func_name, arr_input, arr_indices, arr_update) out = tensor_scatter_net() expected = tensor_scatter_np_benchmark(func_name, arr_input, arr_indices, arr_update) np.testing.assert_allclose(out.asnumpy(), expected, rtol=1e-6)
[ "mindspore.context.set_context", "numpy.zeros", "mindspore.Tensor", "numpy.array", "numpy.arange", "pytest.mark.parametrize" ]
[((2374, 2468), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""func_name"""', "['update', 'min', 'max', 'add', 'sub', 'mul', 'div']"], {}), "('func_name', ['update', 'min', 'max', 'add', 'sub',\n 'mul', 'div'])\n", (2397, 2468), False, 'import pytest\n'), ((2466, 2570), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""input_data_type"""', '[np.float16, np.float32, np.float64, np.int8, np.int32]'], {}), "('input_data_type', [np.float16, np.float32, np.\n float64, np.int8, np.int32])\n", (2489, 2570), False, 'import pytest\n'), ((2567, 2631), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""index_data_type"""', '[np.int32, np.int64]'], {}), "('index_data_type', [np.int32, np.int64])\n", (2590, 2631), False, 'import pytest\n'), ((2862, 2906), 'mindspore.context.set_context', 'context.set_context', ([], {'mode': 'context.GRAPH_MODE'}), '(mode=context.GRAPH_MODE)\n', (2881, 2906), True, 'import mindspore.context as context\n'), ((1548, 1563), 'mindspore.Tensor', 'Tensor', (['input_x'], {}), '(input_x)\n', (1554, 1563), False, 'from mindspore import Tensor\n'), ((1587, 1602), 'mindspore.Tensor', 'Tensor', (['indices'], {}), '(indices)\n', (1593, 1602), False, 'from mindspore import Tensor\n'), ((1626, 1641), 'mindspore.Tensor', 'Tensor', (['updates'], {}), '(updates)\n', (1632, 1641), False, 'from mindspore import Tensor\n'), ((2118, 2146), 'numpy.zeros', 'np.zeros', (['indices.shape[:-1]'], {}), '(indices.shape[:-1])\n', (2126, 2146), True, 'import numpy as np\n'), ((2993, 3043), 'numpy.array', 'np.array', (['[[0, 1], [1, 1], [0, 5], [0, 2], [2, 1]]'], {}), '([[0, 1], [1, 1], [0, 5], [0, 2], [2, 1]])\n', (3001, 3043), True, 'import numpy as np\n'), ((3085, 3122), 'numpy.array', 'np.array', (['[3.2, 1.1, 5.3, -2.2, -1.0]'], {}), '([3.2, 1.1, 5.3, -2.2, -1.0])\n', (3093, 3122), True, 'import numpy as np\n'), ((2923, 2936), 'numpy.arange', 'np.arange', (['(21)'], {}), '(21)\n', (2932, 2936), True, 'import numpy as np\n')]
import numpy as np import matplotlib.pyplot as plt from tqdm import tqdm from numpy.linalg import matrix_power from pre_process import * from eigenfaces import * import copy from pre_process import load_mat, separate_data def save_dataset(): # Load the data from the matrix X, [y] = load_mat('data/face.mat') dataset = {'train_x': [], 'train_y': [], 'test_x': [], 'test_y': []} # Perform train,test split dataset['train_x'], dataset['test_x'], dataset['train_y'], dataset['test_y'] = train_test_split(X.T, y, test_size=0.2,stratify=y) # Adjust data orientation dataset['train_x'] = dataset['train_x'].T dataset['test_x'] = dataset['test_x'].T types = ["training", "test"] # Save the data so that you do not have to do this over and over again i = 0 np.save(DATA_DIR +"processed_raw/data/training.npy",dataset['train_x']) np.save(DATA_DIR +"processed_raw/labels/training.npy",dataset['train_y']) np.save(DATA_DIR +"processed_raw/data/test.npy",dataset['test_x']) np.save(DATA_DIR +"processed_raw/labels/test.npy",dataset['test_y']) return dataset def load_data(): dataset = {'train_x': [], 'train_y': [], 'test_x': [], 'test_y': []} dataset['train_x'] = np.load(DATA_DIR +"processed_raw/data/training.npy") dataset['train_y'] = np.load(DATA_DIR +"processed_raw/labels/training.npy").T dataset['test_x'] = np.load(DATA_DIR +"processed_raw/data/test.npy") dataset['test_y'] = np.load(DATA_DIR +"processed_raw/labels/test.npy").T return dataset if __name__ == '__main__': save_dataset()
[ "numpy.save", "pre_process.load_mat", "numpy.load" ]
[((293, 318), 'pre_process.load_mat', 'load_mat', (['"""data/face.mat"""'], {}), "('data/face.mat')\n", (301, 318), False, 'from pre_process import load_mat, separate_data\n'), ((805, 878), 'numpy.save', 'np.save', (["(DATA_DIR + 'processed_raw/data/training.npy')", "dataset['train_x']"], {}), "(DATA_DIR + 'processed_raw/data/training.npy', dataset['train_x'])\n", (812, 878), True, 'import numpy as np\n'), ((881, 956), 'numpy.save', 'np.save', (["(DATA_DIR + 'processed_raw/labels/training.npy')", "dataset['train_y']"], {}), "(DATA_DIR + 'processed_raw/labels/training.npy', dataset['train_y'])\n", (888, 956), True, 'import numpy as np\n'), ((960, 1028), 'numpy.save', 'np.save', (["(DATA_DIR + 'processed_raw/data/test.npy')", "dataset['test_x']"], {}), "(DATA_DIR + 'processed_raw/data/test.npy', dataset['test_x'])\n", (967, 1028), True, 'import numpy as np\n'), ((1031, 1101), 'numpy.save', 'np.save', (["(DATA_DIR + 'processed_raw/labels/test.npy')", "dataset['test_y']"], {}), "(DATA_DIR + 'processed_raw/labels/test.npy', dataset['test_y'])\n", (1038, 1101), True, 'import numpy as np\n'), ((1238, 1291), 'numpy.load', 'np.load', (["(DATA_DIR + 'processed_raw/data/training.npy')"], {}), "(DATA_DIR + 'processed_raw/data/training.npy')\n", (1245, 1291), True, 'import numpy as np\n'), ((1398, 1447), 'numpy.load', 'np.load', (["(DATA_DIR + 'processed_raw/data/test.npy')"], {}), "(DATA_DIR + 'processed_raw/data/test.npy')\n", (1405, 1447), True, 'import numpy as np\n'), ((1316, 1371), 'numpy.load', 'np.load', (["(DATA_DIR + 'processed_raw/labels/training.npy')"], {}), "(DATA_DIR + 'processed_raw/labels/training.npy')\n", (1323, 1371), True, 'import numpy as np\n'), ((1471, 1522), 'numpy.load', 'np.load', (["(DATA_DIR + 'processed_raw/labels/test.npy')"], {}), "(DATA_DIR + 'processed_raw/labels/test.npy')\n", (1478, 1522), True, 'import numpy as np\n')]
# Harris Algorithm for corner detection and features extracting # R = λ1.λ2 − k(λ1 + λ2)^2 import cv2 as cv import numpy as np if __name__ == "__main__": img = cv.imread('../../assets/test10.jpg') img = cv.resize(img, None, fx=.5, fy=.5) cv.imshow("Original Image", img) # input img of corner harris is always a float32 grayscale img gray_img = cv.cvtColor(img, cv.COLOR_BGR2GRAY) gray_img = np.float32(gray_img) # detecting corners using harris corner detection dst = cv.cornerHarris(gray_img, 5, 5, .04) # dilating for marking the corners, not important dst = cv.dilate(dst, None) # thresholding, making all corners in the img black img[dst > 0.01 * dst.max()] = [0, 0, 0] cv.imshow('Corners Detected Image', img) cv.waitKey(0) cv.destroyAllWindows() # fill free to change the test img # doc: https://docs.opencv.org/master/dc/d0d/tutorial_py_features_harris.html
[ "cv2.dilate", "cv2.cvtColor", "cv2.waitKey", "numpy.float32", "cv2.destroyAllWindows", "cv2.imread", "cv2.imshow", "cv2.cornerHarris", "cv2.resize" ]
[((167, 203), 'cv2.imread', 'cv.imread', (['"""../../assets/test10.jpg"""'], {}), "('../../assets/test10.jpg')\n", (176, 203), True, 'import cv2 as cv\n'), ((214, 250), 'cv2.resize', 'cv.resize', (['img', 'None'], {'fx': '(0.5)', 'fy': '(0.5)'}), '(img, None, fx=0.5, fy=0.5)\n', (223, 250), True, 'import cv2 as cv\n'), ((253, 285), 'cv2.imshow', 'cv.imshow', (['"""Original Image"""', 'img'], {}), "('Original Image', img)\n", (262, 285), True, 'import cv2 as cv\n'), ((373, 408), 'cv2.cvtColor', 'cv.cvtColor', (['img', 'cv.COLOR_BGR2GRAY'], {}), '(img, cv.COLOR_BGR2GRAY)\n', (384, 408), True, 'import cv2 as cv\n'), ((424, 444), 'numpy.float32', 'np.float32', (['gray_img'], {}), '(gray_img)\n', (434, 444), True, 'import numpy as np\n'), ((510, 547), 'cv2.cornerHarris', 'cv.cornerHarris', (['gray_img', '(5)', '(5)', '(0.04)'], {}), '(gray_img, 5, 5, 0.04)\n', (525, 547), True, 'import cv2 as cv\n'), ((611, 631), 'cv2.dilate', 'cv.dilate', (['dst', 'None'], {}), '(dst, None)\n', (620, 631), True, 'import cv2 as cv\n'), ((737, 777), 'cv2.imshow', 'cv.imshow', (['"""Corners Detected Image"""', 'img'], {}), "('Corners Detected Image', img)\n", (746, 777), True, 'import cv2 as cv\n'), ((782, 795), 'cv2.waitKey', 'cv.waitKey', (['(0)'], {}), '(0)\n', (792, 795), True, 'import cv2 as cv\n'), ((800, 822), 'cv2.destroyAllWindows', 'cv.destroyAllWindows', ([], {}), '()\n', (820, 822), True, 'import cv2 as cv\n')]
#!/usr/bin/env python3 from __future__ import print_function import sys import math import numpy as np #ROS Imports import rospy from sensor_msgs.msg import Image, LaserScan from ackermann_msgs.msg import AckermannDriveStamped, AckermannDrive from visualization_msgs.msg import Marker #RQT reconfigure from dynamic_reconfigure.server import Server from follow_the_gap.cfg import gapparamsConfig LIDAR_SCANS = 1080 INFLATE_RADIUS = lambda d : int(1080 * np.arctan(WIDTH/(2*d)) / 4.71239) def reconfigure_callback(config, level): global MOVING_WINDOW global MIN_OBJ_DIST global WIDTH rospy.loginfo("""Reconfiugre Request: {moving_window}, {min_obj_dist}, {width}, """.format(**config)) #print("config.kp:", config.kp, "config.kd:", config.kd) MOVING_WINDOW = int(config.moving_window) MIN_OBJ_DIST = config.min_obj_dist WIDTH = config.width #print("\nkp:", kp, "kd:", kd) return config def get_quaternion_from_euler(roll, pitch, yaw): """ Convert an Euler angle to a quaternion. Input :param roll: The roll (rotation around x-axis) angle in radians. :param pitch: The pitch (rotation around y-axis) angle in radians. :param yaw: The yaw (rotation around z-axis) angle in radians. Output :return qx, qy, qz, qw: The orientation in quaternion [x,y,z,w] format """ qx = np.sin(roll/2) * np.cos(pitch/2) * np.cos(yaw/2) - np.cos(roll/2) * np.sin(pitch/2) * np.sin(yaw/2) qy = np.cos(roll/2) * np.sin(pitch/2) * np.cos(yaw/2) + np.sin(roll/2) * np.cos(pitch/2) * np.sin(yaw/2) qz = np.cos(roll/2) * np.cos(pitch/2) * np.sin(yaw/2) - np.sin(roll/2) * np.sin(pitch/2) * np.cos(yaw/2) qw = np.cos(roll/2) * np.cos(pitch/2) * np.cos(yaw/2) + np.sin(roll/2) * np.sin(pitch/2) * np.sin(yaw/2) return [qx, qy, qz, qw] class reactive_follow_gap: def __init__(self): # Topics & Subscriptions,Publishers lidarscan_topic = '/scan' drive_topic = '/nav' gaps_topic = '/gaps' angle_topic = '/angle' self.lidar_sub = rospy.Subscriber(lidarscan_topic, LaserScan, self.lidar_callback, queue_size=1) self.drive_pub = rospy.Publisher(drive_topic, AckermannDriveStamped, queue_size=1) self.gaps_pub = rospy.Publisher(gaps_topic, LaserScan, queue_size=1) self.angle_pub = rospy.Publisher(angle_topic, Marker, queue_size=1) def vizualize_internals(self, data, angle, vel, gaps): data2 = data data2.ranges = gaps[0].tolist() data2.intensities = gaps[1] self.gaps_pub.publish(data2) marker = Marker() marker.header.frame_id = "laser" marker.ns = "my_namespace" marker.id = 0 marker.type = Marker.ARROW marker.action = Marker.ADD marker.pose.position.x = 0 marker.pose.position.y = 0 marker.pose.position.z = 0 quaternion = get_quaternion_from_euler(0, 0, angle) marker.pose.orientation.x = quaternion[0] marker.pose.orientation.y = quaternion[1] marker.pose.orientation.z = quaternion[2] marker.pose.orientation.w = quaternion[3] marker.scale.x = vel marker.scale.y = 0.1 marker.scale.z = 0.1 marker.color.a = 1.0 marker.color.r = 0.0 marker.color.g = 1.0 marker.color.b = 0.0 marker.mesh_resource = "package://pr2_description/meshes/base_v0/base.dae" self.angle_pub.publish(marker) def get_intensities(self, closest, a, b, d): intensities = [10 for i in range(LIDAR_SCANS)] # not selected gap for i in range(a, b+1): # selected gap intensities[i] = 5 if closest - INFLATE_RADIUS(d) > 0: s = closest - INFLATE_RADIUS(d) else: s = 0 if closest + INFLATE_RADIUS(d) < LIDAR_SCANS: e = closest + INFLATE_RADIUS(d) else: e = LIDAR_SCANS - 1 for i in range(s, e+1): # obstacle area intensities[i] = 0 intensities[s] = 10 return intensities def find_angle(self, aim): right_angle = aim/LIDAR_SCANS * 4.71238898038469 right_to_middle_angle = 2.356194490192345 return right_angle - right_to_middle_angle def preprocess_lidar(self, ranges): """ Preprocess the LiDAR scan array. Expert implementation includes: 1.Setting each value to the mean over some window 2.Rejecting high values (eg. > 3m) """ # Apply running mean proc_ranges = np.convolve(ranges, np.ones(MOVING_WINDOW)/MOVING_WINDOW, mode='valid') # Add missing values from the running mean t = proc_ranges[0] for i in range( (MOVING_WINDOW-1)//2 ): proc_ranges = np.insert(proc_ranges, 0, t) t = proc_ranges[-1] for i in range( (MOVING_WINDOW-1)//2 ): proc_ranges= np.append(proc_ranges, t) # Reject high values for i in range(len(proc_ranges)): if proc_ranges[i] > MIN_OBJ_DIST: proc_ranges[i] = MIN_OBJ_DIST return proc_ranges def find_max_gap(self, closest_point, d): """ Return the start index & end index of the max gap in free_space_ranges """ if closest_point > LIDAR_SCANS/2: return [0, closest_point - INFLATE_RADIUS(d)] return [closest_point + INFLATE_RADIUS(d), LIDAR_SCANS-1] def find_best_point(self, start_i, end_i, ranges): """Start_i & end_i are start and end indicies of max-gap range, respectively Return index of best point in ranges Naive: Choose the furthest point within ranges and go there """ if end_i < LIDAR_SCANS/2: mxi = end_i for i in range(end_i, start_i-1, -1): if ranges[i] > ranges[mxi]: mxi = i elif start_i > LIDAR_SCANS/2: mxi = end_i for i in range(start_i, end_i+1): if ranges[i] > ranges[mxi]: mxi = i else: mxi1 = LIDAR_SCANS//2 for i in range(LIDAR_SCANS//2, end_i+1): if ranges[i] > ranges[mxi1]: mxi1 = i mxi2 = LIDAR_SCANS//2 for i in range(LIDAR_SCANS//2, start_i-1, -1): if ranges[i] > ranges[mxi2]: mxi2 = i if ranges[mxi1] == ranges[mxi2]: if mxi1 - LIDAR_SCANS/2 > LIDAR_SCANS/2 - mxi2: mxi = mxi2 else: mxi = mxi1 elif ranges[mxi1] > ranges[mxi2]: mxi = mxi1 else: mxi = mxi2 return mxi #return (end_i + start_i)//2 #return np.argmax(ranges[start_i:end_i+1]) + start_i def lidar_callback(self, data): """ Process each LiDAR scan as per the Follow Gap algorithm & publish an AckermannDriveStamped Message """ ranges = data.ranges proc_ranges = self.preprocess_lidar(ranges) # Find closest point to LiDAR closest = np.argmin(proc_ranges) # Find max length gap a, b = self.find_max_gap(closest, proc_ranges[closest]) colors = self.get_intensities(closest, a, b, proc_ranges[closest]) # Find the best point in the gap aim = self.find_best_point(a, b, proc_ranges) # Find angle angle = self.find_angle(aim) # Speed Controller if abs(angle) < 0.174533: vel = 2 elif abs(angle) < 0.349066: vel = 2 else: vel = 0.5 # Publish Drive message drive_msg = AckermannDriveStamped() drive_msg.header.stamp = rospy.Time.now() drive_msg.header.frame_id = "laser" drive_msg.drive.steering_angle = angle drive_msg.drive.speed = vel # -------------------------------------------------------- self.drive_pub.publish(drive_msg) # Publish Vizualizations self.vizualize_internals(data, angle, vel, [proc_ranges, colors]) def main(args): rospy.init_node("FollowGap_node", anonymous=True) srv = Server(gapparamsConfig, reconfigure_callback) rfgs = reactive_follow_gap() rospy.sleep(0.1) rospy.spin() if __name__ == '__main__': main(sys.argv)
[ "rospy.Subscriber", "rospy.Time.now", "rospy.Publisher", "rospy.sleep", "numpy.argmin", "ackermann_msgs.msg.AckermannDriveStamped", "numpy.insert", "numpy.append", "numpy.sin", "numpy.ones", "rospy.init_node", "visualization_msgs.msg.Marker", "numpy.cos", "rospy.spin", "numpy.arctan", "dynamic_reconfigure.server.Server" ]
[((8326, 8375), 'rospy.init_node', 'rospy.init_node', (['"""FollowGap_node"""'], {'anonymous': '(True)'}), "('FollowGap_node', anonymous=True)\n", (8341, 8375), False, 'import rospy\n'), ((8386, 8431), 'dynamic_reconfigure.server.Server', 'Server', (['gapparamsConfig', 'reconfigure_callback'], {}), '(gapparamsConfig, reconfigure_callback)\n', (8392, 8431), False, 'from dynamic_reconfigure.server import Server\n'), ((8469, 8485), 'rospy.sleep', 'rospy.sleep', (['(0.1)'], {}), '(0.1)\n', (8480, 8485), False, 'import rospy\n'), ((8490, 8502), 'rospy.spin', 'rospy.spin', ([], {}), '()\n', (8500, 8502), False, 'import rospy\n'), ((2085, 2164), 'rospy.Subscriber', 'rospy.Subscriber', (['lidarscan_topic', 'LaserScan', 'self.lidar_callback'], {'queue_size': '(1)'}), '(lidarscan_topic, LaserScan, self.lidar_callback, queue_size=1)\n', (2101, 2164), False, 'import rospy\n'), ((2190, 2255), 'rospy.Publisher', 'rospy.Publisher', (['drive_topic', 'AckermannDriveStamped'], {'queue_size': '(1)'}), '(drive_topic, AckermannDriveStamped, queue_size=1)\n', (2205, 2255), False, 'import rospy\n'), ((2280, 2332), 'rospy.Publisher', 'rospy.Publisher', (['gaps_topic', 'LaserScan'], {'queue_size': '(1)'}), '(gaps_topic, LaserScan, queue_size=1)\n', (2295, 2332), False, 'import rospy\n'), ((2358, 2408), 'rospy.Publisher', 'rospy.Publisher', (['angle_topic', 'Marker'], {'queue_size': '(1)'}), '(angle_topic, Marker, queue_size=1)\n', (2373, 2408), False, 'import rospy\n'), ((2623, 2631), 'visualization_msgs.msg.Marker', 'Marker', ([], {}), '()\n', (2629, 2631), False, 'from visualization_msgs.msg import Marker\n'), ((7311, 7333), 'numpy.argmin', 'np.argmin', (['proc_ranges'], {}), '(proc_ranges)\n', (7320, 7333), True, 'import numpy as np\n'), ((7886, 7909), 'ackermann_msgs.msg.AckermannDriveStamped', 'AckermannDriveStamped', ([], {}), '()\n', (7907, 7909), False, 'from ackermann_msgs.msg import AckermannDriveStamped, AckermannDrive\n'), ((7943, 7959), 'rospy.Time.now', 'rospy.Time.now', ([], {}), '()\n', (7957, 7959), False, 'import rospy\n'), ((1417, 1432), 'numpy.cos', 'np.cos', (['(yaw / 2)'], {}), '(yaw / 2)\n', (1423, 1432), True, 'import numpy as np\n'), ((1468, 1483), 'numpy.sin', 'np.sin', (['(yaw / 2)'], {}), '(yaw / 2)\n', (1474, 1483), True, 'import numpy as np\n'), ((1526, 1541), 'numpy.cos', 'np.cos', (['(yaw / 2)'], {}), '(yaw / 2)\n', (1532, 1541), True, 'import numpy as np\n'), ((1577, 1592), 'numpy.sin', 'np.sin', (['(yaw / 2)'], {}), '(yaw / 2)\n', (1583, 1592), True, 'import numpy as np\n'), ((1635, 1650), 'numpy.sin', 'np.sin', (['(yaw / 2)'], {}), '(yaw / 2)\n', (1641, 1650), True, 'import numpy as np\n'), ((1686, 1701), 'numpy.cos', 'np.cos', (['(yaw / 2)'], {}), '(yaw / 2)\n', (1692, 1701), True, 'import numpy as np\n'), ((1744, 1759), 'numpy.cos', 'np.cos', (['(yaw / 2)'], {}), '(yaw / 2)\n', (1750, 1759), True, 'import numpy as np\n'), ((1795, 1810), 'numpy.sin', 'np.sin', (['(yaw / 2)'], {}), '(yaw / 2)\n', (1801, 1810), True, 'import numpy as np\n'), ((4899, 4927), 'numpy.insert', 'np.insert', (['proc_ranges', '(0)', 't'], {}), '(proc_ranges, 0, t)\n', (4908, 4927), True, 'import numpy as np\n'), ((5042, 5067), 'numpy.append', 'np.append', (['proc_ranges', 't'], {}), '(proc_ranges, t)\n', (5051, 5067), True, 'import numpy as np\n'), ((458, 484), 'numpy.arctan', 'np.arctan', (['(WIDTH / (2 * d))'], {}), '(WIDTH / (2 * d))\n', (467, 484), True, 'import numpy as np\n'), ((1382, 1398), 'numpy.sin', 'np.sin', (['(roll / 2)'], {}), '(roll / 2)\n', (1388, 1398), True, 'import numpy as np\n'), ((1399, 1416), 'numpy.cos', 'np.cos', (['(pitch / 2)'], {}), '(pitch / 2)\n', (1405, 1416), True, 'import numpy as np\n'), ((1433, 1449), 'numpy.cos', 'np.cos', (['(roll / 2)'], {}), '(roll / 2)\n', (1439, 1449), True, 'import numpy as np\n'), ((1450, 1467), 'numpy.sin', 'np.sin', (['(pitch / 2)'], {}), '(pitch / 2)\n', (1456, 1467), True, 'import numpy as np\n'), ((1491, 1507), 'numpy.cos', 'np.cos', (['(roll / 2)'], {}), '(roll / 2)\n', (1497, 1507), True, 'import numpy as np\n'), ((1508, 1525), 'numpy.sin', 'np.sin', (['(pitch / 2)'], {}), '(pitch / 2)\n', (1514, 1525), True, 'import numpy as np\n'), ((1542, 1558), 'numpy.sin', 'np.sin', (['(roll / 2)'], {}), '(roll / 2)\n', (1548, 1558), True, 'import numpy as np\n'), ((1559, 1576), 'numpy.cos', 'np.cos', (['(pitch / 2)'], {}), '(pitch / 2)\n', (1565, 1576), True, 'import numpy as np\n'), ((1600, 1616), 'numpy.cos', 'np.cos', (['(roll / 2)'], {}), '(roll / 2)\n', (1606, 1616), True, 'import numpy as np\n'), ((1617, 1634), 'numpy.cos', 'np.cos', (['(pitch / 2)'], {}), '(pitch / 2)\n', (1623, 1634), True, 'import numpy as np\n'), ((1651, 1667), 'numpy.sin', 'np.sin', (['(roll / 2)'], {}), '(roll / 2)\n', (1657, 1667), True, 'import numpy as np\n'), ((1668, 1685), 'numpy.sin', 'np.sin', (['(pitch / 2)'], {}), '(pitch / 2)\n', (1674, 1685), True, 'import numpy as np\n'), ((1709, 1725), 'numpy.cos', 'np.cos', (['(roll / 2)'], {}), '(roll / 2)\n', (1715, 1725), True, 'import numpy as np\n'), ((1726, 1743), 'numpy.cos', 'np.cos', (['(pitch / 2)'], {}), '(pitch / 2)\n', (1732, 1743), True, 'import numpy as np\n'), ((1760, 1776), 'numpy.sin', 'np.sin', (['(roll / 2)'], {}), '(roll / 2)\n', (1766, 1776), True, 'import numpy as np\n'), ((1777, 1794), 'numpy.sin', 'np.sin', (['(pitch / 2)'], {}), '(pitch / 2)\n', (1783, 1794), True, 'import numpy as np\n'), ((4686, 4708), 'numpy.ones', 'np.ones', (['MOVING_WINDOW'], {}), '(MOVING_WINDOW)\n', (4693, 4708), True, 'import numpy as np\n')]
# import tensorflow as tf # # a = tf.get_variable("a", dtype=tf.int32, shape=[], initializer=tf.zeros_initializer()) # b = tf.get_variable("b", dtype=tf.float32,shape=[], initializer=tf.ones_initializer()) # # # f = tf.constant(6) # # # Definition of condition and body # def cond(a, b, f): # # # a = tf.Print(a,[a, tf.shape(a)], message="cond a : ") # # return tf.less(a,3) # # # def body(a, b, f): # # do some stuff with a, b # # # a = 1 # # a = tf.Print(a, [a], message="body a : ") # # add = tf.add(a, 1) # # add = tf.Print(add, [add], message="body add : ") # # with tf.control_dependencies([add]): # # f = tf.cond(tf.less(add,2), lambda :f.write(add, 3.2), lambda : f.write(add,4.1)) # b = f.read(a) # b = tf.Print(b, [b], message="body b : ") # # return add, b, f # # # Loop, 返回的tensor while 循环后的 a,b,f # # f = tf.TensorArray(dtype=tf.float32, size=1, dynamic_size=True,clear_after_read = False) # f = tf.TensorArray(dtype=tf.float32, size=1, dynamic_size=True) # # a, b, f = tf.while_loop(cond, body, [a, b, f]) # # result = f.stack() # # with tf.Session() as sess: # # tf.global_variables_initializer().run() # # a, b, result = sess.run([a, b, result]) # # print(result) import tensorflow as tf from tensorflow.python.ops import tensor_array_ops import numpy as np def body(time_var, attention_tracker): a = tf.random_uniform(shape=[2, 2], dtype=tf.int32, maxval=100) b = tf.constant(np.array([[1, 2], [3, 4]]), dtype=tf.int32) c = a + b attention_tracker = attention_tracker.write(time_var, c) # attention_tracker = tf.Print(attention_tracker, [attention_tracker], message="body : ") return time_var + 1 , attention_tracker def condition(time_var, attention_tracker): time_var = tf.Print(time_var, [time_var], message="condition time_var : ") return time_var < 10 x = tf.Variable(tf.constant(0, shape=[2, 2])) #如果 infer_shape=False 则需要指定element shape大小 attention_tracker = tensor_array_ops.TensorArray(tf.int32, size=1, dynamic_size=True, infer_shape=False, element_shape=[2, 2]) time = tf.Variable(1) time_new , attention_tracker_result = tf.while_loop(condition, body, [time, attention_tracker]) result = attention_tracker_result.stack() finally1 = tf.add(result, 1) with tf.Session() as sess: sess.run(tf.global_variables_initializer()) finally2 = sess.run([finally1]) print(finally2)
[ "tensorflow.random_uniform", "tensorflow.python.ops.tensor_array_ops.TensorArray", "tensorflow.global_variables_initializer", "tensorflow.add", "tensorflow.Session", "tensorflow.constant", "tensorflow.Variable", "tensorflow.Print", "numpy.array", "tensorflow.while_loop" ]
[((2001, 2111), 'tensorflow.python.ops.tensor_array_ops.TensorArray', 'tensor_array_ops.TensorArray', (['tf.int32'], {'size': '(1)', 'dynamic_size': '(True)', 'infer_shape': '(False)', 'element_shape': '[2, 2]'}), '(tf.int32, size=1, dynamic_size=True,\n infer_shape=False, element_shape=[2, 2])\n', (2029, 2111), False, 'from tensorflow.python.ops import tensor_array_ops\n'), ((2116, 2130), 'tensorflow.Variable', 'tf.Variable', (['(1)'], {}), '(1)\n', (2127, 2130), True, 'import tensorflow as tf\n'), ((2170, 2227), 'tensorflow.while_loop', 'tf.while_loop', (['condition', 'body', '[time, attention_tracker]'], {}), '(condition, body, [time, attention_tracker])\n', (2183, 2227), True, 'import tensorflow as tf\n'), ((2283, 2300), 'tensorflow.add', 'tf.add', (['result', '(1)'], {}), '(result, 1)\n', (2289, 2300), True, 'import tensorflow as tf\n'), ((1396, 1455), 'tensorflow.random_uniform', 'tf.random_uniform', ([], {'shape': '[2, 2]', 'dtype': 'tf.int32', 'maxval': '(100)'}), '(shape=[2, 2], dtype=tf.int32, maxval=100)\n', (1413, 1455), True, 'import tensorflow as tf\n'), ((1800, 1863), 'tensorflow.Print', 'tf.Print', (['time_var', '[time_var]'], {'message': '"""condition time_var : """'}), "(time_var, [time_var], message='condition time_var : ')\n", (1808, 1863), True, 'import tensorflow as tf\n'), ((1907, 1935), 'tensorflow.constant', 'tf.constant', (['(0)'], {'shape': '[2, 2]'}), '(0, shape=[2, 2])\n', (1918, 1935), True, 'import tensorflow as tf\n'), ((2307, 2319), 'tensorflow.Session', 'tf.Session', ([], {}), '()\n', (2317, 2319), True, 'import tensorflow as tf\n'), ((1477, 1503), 'numpy.array', 'np.array', (['[[1, 2], [3, 4]]'], {}), '([[1, 2], [3, 4]])\n', (1485, 1503), True, 'import numpy as np\n'), ((2343, 2376), 'tensorflow.global_variables_initializer', 'tf.global_variables_initializer', ([], {}), '()\n', (2374, 2376), True, 'import tensorflow as tf\n')]
import unittest import numpy as np import scipy.linalg as la from parla.drivers.interpolative import OSID1, OSID2, TSID1 from parla.comps.sketchers.aware import RS1 import parla.comps.sketchers.oblivious as oblivious import parla.utils.linalg_wrappers as ulaw import parla.tests.matmakers as matmakers from parla.tests.test_drivers.test_lowrank.test_osid import reference_osid def run_tsid_test(alg, m, n, rank, k, over, test_tol, seed): rng = np.random.default_rng(seed) A = matmakers.rand_low_rank(m, n, rank, rng) Z, I, X, J = alg(A, k, over, rng) A_id = Z @ (A[I, :][:, J] @ X) permuted_coeffs = Z[I, :] delta_norm = la.norm(permuted_coeffs - np.eye(k), ord='fro') assert delta_norm < 1e-8 permuted_coeffs = X[:, J] delta_norm = la.norm(permuted_coeffs - np.eye(k), ord='fro') assert delta_norm < 1e-8 err_rand = la.norm(A - A_id, ord='fro') if test_tol < 1e-8: rel_err = err_rand / la.norm(A, ord='fro') assert rel_err < test_tol else: A_id_ref, _, _ = reference_osid(A, k, 0) err_ref = la.norm(A - A_id_ref, ord='fro') rel_err = (err_rand - err_ref) / la.norm(A, ord='fro') print(rel_err) assert rel_err < test_tol #TODO: improve these tests class TestTSIDs(unittest.TestCase): def test_simple_exact(self): gaussian_operator = oblivious.SkOpGA() rso = RS1( sketch_op_gen=gaussian_operator, num_pass=0, stabilizer=ulaw.orth, passes_per_stab=1 ) osid = OSID1(rso) alg = TSID1(osid) m, n = 1000, 300 # Algorithm will start with a row ID run_tsid_test(alg, m, n, rank=290, k=290, over=0, test_tol=1e-12, seed=0) run_tsid_test(alg, m, n, rank=290, k=290, over=5, test_tol=1e-12, seed=2) run_tsid_test(alg, m, n, rank=30, k=30, over=0, test_tol=1e-12, seed=2) # Algorithm will start with a column ID m, n = 300, 1000 run_tsid_test(alg, m, n, rank=290, k=290, over=0, test_tol=1e-12, seed=0) run_tsid_test(alg, m, n, rank=290, k=290, over=5, test_tol=1e-12, seed=2) run_tsid_test(alg, m, n, rank=30, k=30, over=0, test_tol=1e-12, seed=2) def test_simple_approx(self): gaussian_operator = oblivious.SkOpGA() rso = RS1( sketch_op_gen=gaussian_operator, num_pass=2, stabilizer=ulaw.orth, passes_per_stab=1 ) osid = OSID1(rso) alg = TSID1(osid) m, n = 100, 30 run_tsid_test(alg, m, n, rank=30, k=27, over=3, test_tol=0.05, seed=0) run_tsid_test(alg, m, n, rank=30, k=25, over=4, test_tol=0.05, seed=0) # Re-run tests with wide data matrices m, n = 30, 100 run_tsid_test(alg, m, n, rank=30, k=27, over=3, test_tol=0.05, seed=0) run_tsid_test(alg, m, n, rank=30, k=25, over=4, test_tol=0.05, seed=0)
[ "parla.drivers.interpolative.TSID1", "parla.comps.sketchers.oblivious.SkOpGA", "parla.tests.test_drivers.test_lowrank.test_osid.reference_osid", "parla.tests.matmakers.rand_low_rank", "numpy.random.default_rng", "scipy.linalg.norm", "parla.comps.sketchers.aware.RS1", "numpy.eye", "parla.drivers.interpolative.OSID1" ]
[((450, 477), 'numpy.random.default_rng', 'np.random.default_rng', (['seed'], {}), '(seed)\n', (471, 477), True, 'import numpy as np\n'), ((486, 526), 'parla.tests.matmakers.rand_low_rank', 'matmakers.rand_low_rank', (['m', 'n', 'rank', 'rng'], {}), '(m, n, rank, rng)\n', (509, 526), True, 'import parla.tests.matmakers as matmakers\n'), ((866, 894), 'scipy.linalg.norm', 'la.norm', (['(A - A_id)'], {'ord': '"""fro"""'}), "(A - A_id, ord='fro')\n", (873, 894), True, 'import scipy.linalg as la\n'), ((1039, 1062), 'parla.tests.test_drivers.test_lowrank.test_osid.reference_osid', 'reference_osid', (['A', 'k', '(0)'], {}), '(A, k, 0)\n', (1053, 1062), False, 'from parla.tests.test_drivers.test_lowrank.test_osid import reference_osid\n'), ((1081, 1113), 'scipy.linalg.norm', 'la.norm', (['(A - A_id_ref)'], {'ord': '"""fro"""'}), "(A - A_id_ref, ord='fro')\n", (1088, 1113), True, 'import scipy.linalg as la\n'), ((1357, 1375), 'parla.comps.sketchers.oblivious.SkOpGA', 'oblivious.SkOpGA', ([], {}), '()\n', (1373, 1375), True, 'import parla.comps.sketchers.oblivious as oblivious\n'), ((1390, 1483), 'parla.comps.sketchers.aware.RS1', 'RS1', ([], {'sketch_op_gen': 'gaussian_operator', 'num_pass': '(0)', 'stabilizer': 'ulaw.orth', 'passes_per_stab': '(1)'}), '(sketch_op_gen=gaussian_operator, num_pass=0, stabilizer=ulaw.orth,\n passes_per_stab=1)\n', (1393, 1483), False, 'from parla.comps.sketchers.aware import RS1\n'), ((1553, 1563), 'parla.drivers.interpolative.OSID1', 'OSID1', (['rso'], {}), '(rso)\n', (1558, 1563), False, 'from parla.drivers.interpolative import OSID1, OSID2, TSID1\n'), ((1578, 1589), 'parla.drivers.interpolative.TSID1', 'TSID1', (['osid'], {}), '(osid)\n', (1583, 1589), False, 'from parla.drivers.interpolative import OSID1, OSID2, TSID1\n'), ((2287, 2305), 'parla.comps.sketchers.oblivious.SkOpGA', 'oblivious.SkOpGA', ([], {}), '()\n', (2303, 2305), True, 'import parla.comps.sketchers.oblivious as oblivious\n'), ((2320, 2413), 'parla.comps.sketchers.aware.RS1', 'RS1', ([], {'sketch_op_gen': 'gaussian_operator', 'num_pass': '(2)', 'stabilizer': 'ulaw.orth', 'passes_per_stab': '(1)'}), '(sketch_op_gen=gaussian_operator, num_pass=2, stabilizer=ulaw.orth,\n passes_per_stab=1)\n', (2323, 2413), False, 'from parla.comps.sketchers.aware import RS1\n'), ((2483, 2493), 'parla.drivers.interpolative.OSID1', 'OSID1', (['rso'], {}), '(rso)\n', (2488, 2493), False, 'from parla.drivers.interpolative import OSID1, OSID2, TSID1\n'), ((2508, 2519), 'parla.drivers.interpolative.TSID1', 'TSID1', (['osid'], {}), '(osid)\n', (2513, 2519), False, 'from parla.drivers.interpolative import OSID1, OSID2, TSID1\n'), ((674, 683), 'numpy.eye', 'np.eye', (['k'], {}), '(k)\n', (680, 683), True, 'import numpy as np\n'), ((799, 808), 'numpy.eye', 'np.eye', (['k'], {}), '(k)\n', (805, 808), True, 'import numpy as np\n'), ((948, 969), 'scipy.linalg.norm', 'la.norm', (['A'], {'ord': '"""fro"""'}), "(A, ord='fro')\n", (955, 969), True, 'import scipy.linalg as la\n'), ((1155, 1176), 'scipy.linalg.norm', 'la.norm', (['A'], {'ord': '"""fro"""'}), "(A, ord='fro')\n", (1162, 1176), True, 'import scipy.linalg as la\n')]
# Copyright (c) 2022 NVIDIA CORPORATION. All rights reserved. # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. import math import numpy as np import os import xml.etree.ElementTree as ET import warp as wp # SNU file format parser class MuscleUnit: def __init__(self): self.name = "" self.bones = [] self.points = [] class Skeleton: def __init__(self, root_xform, skeleton_file, muscle_file, builder, filter, armature=0.0): self.parse_skeleton(skeleton_file, builder, filter, root_xform, armature) self.parse_muscles(muscle_file, builder) def parse_skeleton(self, filename, builder, filter, root_xform, armature): file = ET.parse(filename) root = file.getroot() self.node_map = {} # map node names to link indices self.xform_map = {} # map node names to parent transforms self.mesh_map = {} # map mesh names to link indices objects self.coord_start = builder.joint_coord_count self.dof_start = builder.joint_dof_count type_map = { "Ball": wp.sim.JOINT_BALL, "Revolute": wp.sim.JOINT_REVOLUTE, "Prismatic": wp.sim.JOINT_PRISMATIC, "Free": wp.sim.JOINT_FREE, "Fixed": wp.sim.JOINT_FIXED } builder.add_articulation() for child in root: if (child.tag == "Node"): body = child.find("Body") joint = child.find("Joint") name = child.attrib["name"] parent = child.attrib["parent"] parent_X_s = wp.transform_identity() if parent in self.node_map: parent_link = self.node_map[parent] parent_X_s = self.xform_map[parent] else: parent_link = -1 body_xform = body.find("Transformation") joint_xform = joint.find("Transformation") body_mesh = body.attrib["obj"] body_size = np.fromstring(body.attrib["size"], sep=" ") body_type = body.attrib["type"] body_mass = body.attrib["mass"] body_R_s = np.fromstring(body_xform.attrib["linear"], sep=" ").reshape((3,3)) body_t_s = np.fromstring(body_xform.attrib["translation"], sep=" ") joint_R_s = np.fromstring(joint_xform.attrib["linear"], sep=" ").reshape((3,3)) joint_t_s = np.fromstring(joint_xform.attrib["translation"], sep=" ") joint_type = type_map[joint.attrib["type"]] joint_lower = np.array([-1.e+3]) joint_upper = np.array([1.e+3]) try: joint_lower = np.fromstring(joint.attrib["lower"], sep=" ") joint_upper = np.fromstring(joint.attrib["upper"], sep=" ") except: pass if ("axis" in joint.attrib): joint_axis = np.fromstring(joint.attrib["axis"], sep=" ") else: joint_axis = np.array((0.0, 0.0, 0.0)) body_X_s = wp.transform(body_t_s, wp.quat_from_matrix(body_R_s)) joint_X_s = wp.transform(joint_t_s, wp.quat_from_matrix(joint_R_s)) mesh_base = os.path.splitext(body_mesh)[0] mesh_file = mesh_base + ".usd" #----------------------------------- # one time conversion, put meshes into local body space (and meter units) # stage = Usd.Stage.Open("./assets/snu/OBJ/" + mesh_file) # geom = UsdGeom.Mesh.Get(stage, "/" + mesh_base + "_obj/defaultobject/defaultobject") # body_X_bs = wp.transform_inverse(body_X_s) # joint_X_bs = wp.transform_inverse(joint_X_s) # points = geom.GetPointsAttr().Get() # for i in range(len(points)): # p = wp.transform_point(joint_X_bs, points[i]*0.01) # points[i] = Gf.Vec3f(p.tolist()) # cm -> meters # geom.GetPointsAttr().Set(points) # extent = UsdGeom.Boundable.ComputeExtentFromPlugins(geom, 0.0) # geom.GetExtentAttr().Set(extent) # stage.Save() #-------------------------------------- link = -1 if len(filter) == 0 or name in filter: joint_X_p = wp.transform_multiply(wp.transform_inverse(parent_X_s), joint_X_s) body_X_c = wp.transform_multiply(wp.transform_inverse(joint_X_s), body_X_s) if (parent_link == -1): joint_X_p = wp.transform_identity() # add link link = builder.add_body( parent=parent_link, origin=wp.transform_multiply(root_xform, joint_X_s), joint_xform=joint_X_p, joint_axis=joint_axis, joint_type=joint_type, joint_target_ke=5.0, joint_target_kd=2.0, joint_limit_lower=joint_lower[0], joint_limit_upper=joint_upper[0], joint_limit_ke=1.e+3, joint_limit_kd=1.e+2, joint_armature=armature) # add shape shape = builder.add_shape_box( body=link, pos=body_X_c.p, rot=body_X_c.q, hx=body_size[0]*0.5, hy=body_size[1]*0.5, hz=body_size[2]*0.5, ke=1.e+3*5.0, kd=1.e+2*2.0, kf=1.e+3, mu=0.5) # add lookup in name->link map # save parent transform self.xform_map[name] = joint_X_s self.node_map[name] = link self.mesh_map[mesh_base] = link def parse_muscles(self, filename, builder): # list of MuscleUnits muscles = [] file = ET.parse(filename) root = file.getroot() self.muscle_start = len(builder.muscle_activation) for child in root: if (child.tag == "Unit"): unit_name = child.attrib["name"] unit_f0 = float(child.attrib["f0"]) unit_lm = float(child.attrib["lm"]) unit_lt = float(child.attrib["lt"]) unit_lmax = float(child.attrib["lmax"]) unit_pen = float(child.attrib["pen_angle"]) m = MuscleUnit() m.name = unit_name incomplete = False for waypoint in child.iter("Waypoint"): way_bone = waypoint.attrib["body"] way_link = self.node_map[way_bone] way_loc = np.fromstring(waypoint.attrib["p"], sep=" ", dtype=np.float32) if (way_link == -1): incomplete = True break # transform loc to joint local space joint_X_s = self.xform_map[way_bone] way_loc = wp.transform_point(wp.transform_inverse(joint_X_s), way_loc) m.bones.append(way_link) m.points.append(way_loc) if not incomplete: muscles.append(m) builder.add_muscle(m.bones, m.points, f0=unit_f0, lm=unit_lm, lt=unit_lt, lmax=unit_lmax, pen=unit_pen) self.muscles = muscles def parse_snu(root_xform, skeleton_file, muscle_file, builder, filter, armature=0.0): return Skeleton(root_xform, skeleton_file, muscle_file, builder, filter, armature=0.0)
[ "xml.etree.ElementTree.parse", "warp.transform_inverse", "warp.transform_identity", "warp.transform_multiply", "numpy.array", "warp.quat_from_matrix", "os.path.splitext", "numpy.fromstring" ]
[((1012, 1030), 'xml.etree.ElementTree.parse', 'ET.parse', (['filename'], {}), '(filename)\n', (1020, 1030), True, 'import xml.etree.ElementTree as ET\n'), ((6674, 6692), 'xml.etree.ElementTree.parse', 'ET.parse', (['filename'], {}), '(filename)\n', (6682, 6692), True, 'import xml.etree.ElementTree as ET\n'), ((1951, 1974), 'warp.transform_identity', 'wp.transform_identity', ([], {}), '()\n', (1972, 1974), True, 'import warp as wp\n'), ((2384, 2427), 'numpy.fromstring', 'np.fromstring', (["body.attrib['size']"], {'sep': '""" """'}), "(body.attrib['size'], sep=' ')\n", (2397, 2427), True, 'import numpy as np\n'), ((2646, 2702), 'numpy.fromstring', 'np.fromstring', (["body_xform.attrib['translation']"], {'sep': '""" """'}), "(body_xform.attrib['translation'], sep=' ')\n", (2659, 2702), True, 'import numpy as np\n'), ((2828, 2885), 'numpy.fromstring', 'np.fromstring', (["joint_xform.attrib['translation']"], {'sep': '""" """'}), "(joint_xform.attrib['translation'], sep=' ')\n", (2841, 2885), True, 'import numpy as np\n'), ((3006, 3025), 'numpy.array', 'np.array', (['[-1000.0]'], {}), '([-1000.0])\n', (3014, 3025), True, 'import numpy as np\n'), ((3055, 3073), 'numpy.array', 'np.array', (['[1000.0]'], {}), '([1000.0])\n', (3063, 3073), True, 'import numpy as np\n'), ((3129, 3174), 'numpy.fromstring', 'np.fromstring', (["joint.attrib['lower']"], {'sep': '""" """'}), "(joint.attrib['lower'], sep=' ')\n", (3142, 3174), True, 'import numpy as np\n'), ((3209, 3254), 'numpy.fromstring', 'np.fromstring', (["joint.attrib['upper']"], {'sep': '""" """'}), "(joint.attrib['upper'], sep=' ')\n", (3222, 3254), True, 'import numpy as np\n'), ((3383, 3427), 'numpy.fromstring', 'np.fromstring', (["joint.attrib['axis']"], {'sep': '""" """'}), "(joint.attrib['axis'], sep=' ')\n", (3396, 3427), True, 'import numpy as np\n'), ((3483, 3508), 'numpy.array', 'np.array', (['(0.0, 0.0, 0.0)'], {}), '((0.0, 0.0, 0.0))\n', (3491, 3508), True, 'import numpy as np\n'), ((3560, 3589), 'warp.quat_from_matrix', 'wp.quat_from_matrix', (['body_R_s'], {}), '(body_R_s)\n', (3579, 3589), True, 'import warp as wp\n'), ((3643, 3673), 'warp.quat_from_matrix', 'wp.quat_from_matrix', (['joint_R_s'], {}), '(joint_R_s)\n', (3662, 3673), True, 'import warp as wp\n'), ((3704, 3731), 'os.path.splitext', 'os.path.splitext', (['body_mesh'], {}), '(body_mesh)\n', (3720, 3731), False, 'import os\n'), ((7551, 7613), 'numpy.fromstring', 'np.fromstring', (["waypoint.attrib['p']"], {'sep': '""" """', 'dtype': 'np.float32'}), "(waypoint.attrib['p'], sep=' ', dtype=np.float32)\n", (7564, 7613), True, 'import numpy as np\n'), ((2552, 2603), 'numpy.fromstring', 'np.fromstring', (["body_xform.attrib['linear']"], {'sep': '""" """'}), "(body_xform.attrib['linear'], sep=' ')\n", (2565, 2603), True, 'import numpy as np\n'), ((2732, 2784), 'numpy.fromstring', 'np.fromstring', (["joint_xform.attrib['linear']"], {'sep': '""" """'}), "(joint_xform.attrib['linear'], sep=' ')\n", (2745, 2784), True, 'import numpy as np\n'), ((4919, 4951), 'warp.transform_inverse', 'wp.transform_inverse', (['parent_X_s'], {}), '(parent_X_s)\n', (4939, 4951), True, 'import warp as wp\n'), ((5017, 5048), 'warp.transform_inverse', 'wp.transform_inverse', (['joint_X_s'], {}), '(joint_X_s)\n', (5037, 5048), True, 'import warp as wp\n'), ((5141, 5164), 'warp.transform_identity', 'wp.transform_identity', ([], {}), '()\n', (5162, 5164), True, 'import warp as wp\n'), ((7917, 7948), 'warp.transform_inverse', 'wp.transform_inverse', (['joint_X_s'], {}), '(joint_X_s)\n', (7937, 7948), True, 'import warp as wp\n'), ((5318, 5362), 'warp.transform_multiply', 'wp.transform_multiply', (['root_xform', 'joint_X_s'], {}), '(root_xform, joint_X_s)\n', (5339, 5362), True, 'import warp as wp\n')]
# -*- coding: utf-8 -*- """ Created on Tue Dec 17 18:16:14 2019 @author: Kokkinos """ import numpy as np from base.bci_transducer import Transducer from base.data_setup import * from offline import Offline from Lib.warnings import warn class Simul(Offline): def __init__(self, mode = 'IMvsall', tim_window = 4, vote_window = 4, overlap = 0, TrnF = 0.5, IMdur = 4, Fs=None, filtering=None, bp = None, components = 4, red_type = None, FB_CSP = None, bank = None, neighbors = 5): # Transducer.__init__(self, Fs, filtering, bp, components, # red_type, FB_CSP, bank, neighbors) # # if mode == 'IMvsall' or 'IMvsRest' or 'Rvsall' or 'CSP_OVR' or 'sync': # self.mode = mode # else: # raise ValueError('Inappropriate mode value') # # self.TrnF = TrnF # self.IMdur = IMdur * Fs Offline.__init__(self, mode, TrnF, IMdur, Fs, filtering, bp, components, red_type, FB_CSP, bank, neighbors) if self.mode == 'sync': self.tim_window = self.IMdur self.vote_window = self.tim_window self.step = 2 * self.IMdur else: self.tim_window = tim_window * self.Fs self.vote_window = vote_window * self.Fs # if vote_window == tim_window: # self.overlap = 0 # if overlap != 0: # warn('Overlap value set to 0') # else: # self.overlap = overlap self.overlap = overlap self.step = int(self.tim_window * (1 - self.overlap)) def simul_test_specs(self, data, LABELS, trig): trigs, labels = data_specs(trig, self.IMdur, labels = LABELS, mode = self.mode) #setup testing data and labels Tr_data, Tr_labels, Tst_data ,Tst_labels = data_Split(data, LABELS, self.TrnF, trig = trigs[0], shuffle = False) tst_labels = rt_labels(self.IMdur, LABELS, self.TrnF, self.mode) return Tst_data, tst_labels def simul_predict(self, tst_data): tim_window = int(self.tim_window) step = self.step vote_window = int(self.vote_window) vote = [0] * len(self.bcis) prediction = [] for index in range(0, len(tst_data), step): chunk = (tst_data[index : index+tim_window].T) if len(chunk.T)<27: break chunk = chunk.reshape((1, chunk.shape[0], chunk.shape[1])) pred = [] for i, bci in enumerate(self.bcis[:-1]): pred.append(bci.predict(chunk)) if pred[i] != 0: vote[i] += 1 else: vote[i] -= 1 pred.append(self.bcis[-1].predict(chunk)) if pred[-1] == 1: vote[-1] += 1 else: vote[-1] -= 1 if (index + step) % vote_window == 0: if self.mode == 'IMvsall' or self.mode == 'IMvsRest': if vote[0] <= 0 and vote[1] <= 0: prediction.extend([0] * vote_window) elif vote[2] == 1: prediction.extend([1] * vote_window) else: prediction.extend([2] * vote_window) elif self.mode == 'Rvsall': if vote[0] <= 0: prediction.extend([0] * vote_window) elif vote[1] > 0: #tsek gia labels 0,1,2 prediction.extend([1] * vote_window) else: prediction.extend([2] * vote_window) else: prediction.extend([pred[-1]] * vote_window) vote = [0] * len(vote) return prediction if __name__ == '__main__': import scipy.io as sio """ EEG = sio.loadmat('lab_rec\PANTAZ_EEG_s2.mat')['EEGDATA'] LABELS = sio.loadmat('lab_rec\PANTAZ_LABELS_s2.mat')['LABELS'].flatten() trig = sio.loadmat('lab_rec\PANTAZ_TRIG_s2.mat')['trig'].flatten() Fs= 250 IMdur = 4*Fs TrnF = 0.5 bp = [5,30] EEG = EEG/1000000000 bank = [range(4,32,3),4] import time start = time.time() sim = Simul(mode = 'CSP_OVR', tim_window = 4, vote_window = 4, overlap = 0, Fs = Fs, filtering = 'full', bp = bp, FB_CSP = None, bank = bank) sim.offline_fit(EEG, LABELS, trig) tst_data, tst_labels = sim.simul_test_specs(EEG, LABELS, trig) pred = sim.simul_predict(tst_data) ac, cf = Results(pred, tst_labels, res_type = 'full') print(ac) print(cf) print(time.time()-start) """ electrodes = [10,11,13,14,26,27,29,30,42,43,45,46] EEG = sio.loadmat('datasets\BCICIV_ds1\BCICIV_calib_ds1f.mat')['cnt'][:,electrodes]#[:,20:30] LABELS = sio.loadmat('datasets\BCICIV_ds1\LABELS_ds1f.mat')['LABELS'].flatten() trig = sio.loadmat('datasets\BCICIV_ds1\\trig_ds1f.mat')['trig'].flatten() tst_data = sio.loadmat('datasets\BCICIV_ds1\BCICIV_eval_ds1f.mat')['cnt'][:,electrodes] tst_labels = sio.loadmat('datasets\BCICIV_ds1\LABELS_eval_ds1f.mat')['y'].flatten() tst_data = tst_data tst_labels = tst_labels # i = np.where(np.isnan(tst_labels)) # tst_data = np.delete(tst_data,i,0) # print(tst_data.shape) # tst_labels = np.delete(tst_labels,i) i = np.where(LABELS == -1) LABELS[i] = 2 i = np.where(tst_labels == -1) tst_labels[i] = 2 Fs= 100 IMdur = 4 TrnF = 1 bp = [1,19] EEG = EEG bank = [range(9,32,4),4] import time start = time.time() sim = Simul(mode = 'IMvsRest', tim_window = 4, vote_window = 4, overlap = 0, Fs = Fs, filtering = None, bp = bp, FB_CSP = 4, bank = bank, TrnF = TrnF) sim.offline_fit(EEG, LABELS, trig) # tst_data, tst_labels = sim.simul_test_specs(EEG, LABELS, trig) pred = sim.simul_predict(tst_data) pred = pred[:tst_data.shape[0]] tst_labels = tst_labels[:len(pred)] try: tst_labels = np.array(tst_labels) except: pass try: pred = np.array(pred) except: pass i = np.where(np.isnan(tst_labels)) pred = np.delete(pred,i) tst_labels = np.delete(tst_labels,i) ac, cf = Results(pred, tst_labels, res_type = 'full') print(ac) print(cf) mse = cf[0,1]+cf[0,2]+cf[1,0]+cf[2,0] + (cf[1,2]+cf[2,1])*2 print(mse/len(tst_labels)) print(sum(cf)) print(time.time()-start)
[ "offline.Offline.__init__", "scipy.io.loadmat", "numpy.isnan", "time.time", "numpy.where", "numpy.array", "numpy.delete" ]
[((6019, 6041), 'numpy.where', 'np.where', (['(LABELS == -1)'], {}), '(LABELS == -1)\n', (6027, 6041), True, 'import numpy as np\n'), ((6068, 6094), 'numpy.where', 'np.where', (['(tst_labels == -1)'], {}), '(tst_labels == -1)\n', (6076, 6094), True, 'import numpy as np\n'), ((6284, 6295), 'time.time', 'time.time', ([], {}), '()\n', (6293, 6295), False, 'import time\n'), ((6899, 6917), 'numpy.delete', 'np.delete', (['pred', 'i'], {}), '(pred, i)\n', (6908, 6917), True, 'import numpy as np\n'), ((6934, 6958), 'numpy.delete', 'np.delete', (['tst_labels', 'i'], {}), '(tst_labels, i)\n', (6943, 6958), True, 'import numpy as np\n'), ((943, 1054), 'offline.Offline.__init__', 'Offline.__init__', (['self', 'mode', 'TrnF', 'IMdur', 'Fs', 'filtering', 'bp', 'components', 'red_type', 'FB_CSP', 'bank', 'neighbors'], {}), '(self, mode, TrnF, IMdur, Fs, filtering, bp, components,\n red_type, FB_CSP, bank, neighbors)\n', (959, 1054), False, 'from offline import Offline\n'), ((6736, 6756), 'numpy.array', 'np.array', (['tst_labels'], {}), '(tst_labels)\n', (6744, 6756), True, 'import numpy as np\n'), ((6806, 6820), 'numpy.array', 'np.array', (['pred'], {}), '(pred)\n', (6814, 6820), True, 'import numpy as np\n'), ((6866, 6886), 'numpy.isnan', 'np.isnan', (['tst_labels'], {}), '(tst_labels)\n', (6874, 6886), True, 'import numpy as np\n'), ((5367, 5425), 'scipy.io.loadmat', 'sio.loadmat', (['"""datasets\\\\BCICIV_ds1\\\\BCICIV_calib_ds1f.mat"""'], {}), "('datasets\\\\BCICIV_ds1\\\\BCICIV_calib_ds1f.mat')\n", (5378, 5425), True, 'import scipy.io as sio\n'), ((5633, 5690), 'scipy.io.loadmat', 'sio.loadmat', (['"""datasets\\\\BCICIV_ds1\\\\BCICIV_eval_ds1f.mat"""'], {}), "('datasets\\\\BCICIV_ds1\\\\BCICIV_eval_ds1f.mat')\n", (5644, 5690), True, 'import scipy.io as sio\n'), ((7178, 7189), 'time.time', 'time.time', ([], {}), '()\n', (7187, 7189), False, 'import time\n'), ((5468, 5520), 'scipy.io.loadmat', 'sio.loadmat', (['"""datasets\\\\BCICIV_ds1\\\\LABELS_ds1f.mat"""'], {}), "('datasets\\\\BCICIV_ds1\\\\LABELS_ds1f.mat')\n", (5479, 5520), True, 'import scipy.io as sio\n'), ((5550, 5600), 'scipy.io.loadmat', 'sio.loadmat', (['"""datasets\\\\BCICIV_ds1\\\\trig_ds1f.mat"""'], {}), "('datasets\\\\BCICIV_ds1\\\\trig_ds1f.mat')\n", (5561, 5600), True, 'import scipy.io as sio\n'), ((5727, 5784), 'scipy.io.loadmat', 'sio.loadmat', (['"""datasets\\\\BCICIV_ds1\\\\LABELS_eval_ds1f.mat"""'], {}), "('datasets\\\\BCICIV_ds1\\\\LABELS_eval_ds1f.mat')\n", (5738, 5784), True, 'import scipy.io as sio\n')]
# -*- coding: utf-8 -*- from __future__ import unicode_literals # 导入相关模块 import numpy as np import random from random import shuffle from scipy import io import scipy.io as iso from utils import * # 全局变量,名字库的文件名 DataSet = "name.txt" def preprocess(data_set=DataSet): """ 对名字库进行预处理. 参数: dataset:文字库的文件名,默认为全局变量 返回值: char_to_ix:一个字典,字典的键为名字库中所有的字,值为其编码,实现由字得到编码 ix_to_char:一个字典,字典的键为名字库中字的编码,值为其对应的字,实现从编码得到字 """ with open(data_set, 'r', encoding="gbk") as f: data = f.read() chars = list(set(data)) # 取出名字库中所有的字,包括换行符 data_size, vocab_size = len(data), len(chars) # 计算总的字数和不重复的字数(包括换行符) # print('名字库中总共有%d个字(含换行符),不重复的字一共有%d个' % # (data_size, vocab_size)) char_to_ix = {ch: i for i, ch in enumerate(sorted(chars))} ix_to_char = {i: ch for i, ch in enumerate(sorted(chars))} return char_to_ix, ix_to_char def clip(gradients, maximum): ''' 防止出现梯度爆炸的情况,使梯度处于-maximum到maximum. 参数: gradients:一个包括网络中所有相关偏导数的字典(梯度字典),键分别为:"dWaa", "dWax", "dWya", "db", "dby" maximum:大于此值则被设置为此值,小于此值则被设置为-maximum 返回值: gradients:修改了的梯度字典 ''' for gradient in gradients: gradients[gradient] = gradients[ gradient].clip(min=-maximum, max=maximum) return gradients def sample(parameters, char_to_ix, first_name, seed): """ 对网络的输出根据输出的概率分布来进行采样,采集一组名字,直到名字超过两个字或者以换行符结尾 参数: parameters:一个包括网络中相关权重参数的字典,包括Waa, Wax, Wya, by, and b. char_to_ix:一个字典,字典的键为名字库中所有的字,值为其编码,实现由字得到编码 first_name:用户输入的姓氏 seed:固定随机数生成器的种子 Returns: indices:一个包括了得到的名字序列的编码的列表 """ # 将网络的权重和偏置参数解析出来 Waa, Wax, Wya, by, b = parameters['Waa'], parameters[ 'Wax'], parameters['Wya'], parameters['by'], parameters['b'] vocab_size = by.shape[0] n_a = Waa.shape[1] # 初始化第一个时间步的x输入为(vocab_size, 1)的0数组 x = np.zeros((vocab_size, 1)) # 初始化网络的初始激活值为(n_a, 1)的0数组 a_prev = np.zeros((n_a, 1)) indices = [] # 创建空列表,用于存放序列的编码(索引) idx = -1 # 初始化索引为-1,每次检测到新的字符时更新 counter = 0 # 对indices中的字符进行计数 newline_character = char_to_ix['\n'] # 获取换行符的编码 # 固定姓氏,但是也第一个时间步也运行了一次 a = np.tanh(np.dot(Wax, x) + np.dot(Waa, a_prev) + b) # 用于下一个时间步的输入激活值 idx = char_to_ix[first_name[0]] indices.append(idx) # 获取姓氏的编码,并添加到indices中 x = np.zeros((vocab_size, 1)) x[idx] = 1 # 将姓氏作为独热编码,作为第二个时间步的输入 a_prev = a # 考虑到有可能有复姓的情况,如果是复姓,则再运行一次时间步,并将输出设置为复姓的第二个字 if len(first_name) == 2: a = np.tanh(np.dot(Wax, x) + np.dot(Waa, a_prev) + b) idx = char_to_ix[first_name[1]] indices.append(idx) x = np.zeros((vocab_size, 1)) x[idx] = 1 a_prev = a # 继续运行后面的时间步,直到遇到换行符或者输出两个字 while (idx != newline_character and counter != 2): a = np.tanh(np.dot(Wax, x) + np.dot(Waa, a_prev) + b) z = np.dot(Wya, a) + by y = softmax(z) np.random.seed(counter + seed) # 根据该时间步输出中各个文字的概率来进行采样,采集到对应的编码 idx = np.random.choice(list(range(len(y))), p=y.ravel()) indices.append(idx) x = np.zeros((vocab_size, 1)) x[idx] = 1 a_prev = a seed += 1 counter += 1 if counter == 2: indices.append(char_to_ix['\n']) return indices def optimize(X, Y, a_prev, parameters, learning_rate=0.01): """ 优化训练模型. 参数: X:输入,名字库中的姓名对应的编码列表 Y:输出,名字库中的姓名对应列表,比X早一个时间步 a_prev:第一个时间步输入的激活值 parameters:网络的参数字典,包括: Wax:输入的权重矩阵,尺寸为(n_a, n_x) Waa:输入激活值的权重矩阵,尺寸为(n_a, n_a) Wya:输出的权重矩阵,尺寸为(n_y, n_a) b:输入的偏置,尺寸为(n_a, 1) by:输出的偏置,尺寸为(n_y, 1) learning_rate:学习速率 返回值: loss:损失函数的值 gradients:包含梯度的字典(与parameters对应),包括:dWax,dWaa,dWya,db,dby a[len(X)-1]:最后一个时间步的输入激活值 """ # 正向传播 loss, cache = rnn_forward(X, Y, a_prev, parameters) # 反向传播 gradients, a = rnn_backward(X, Y, parameters, cache) # 防止梯度爆炸 gradients = clip(gradients, 5) # 更新参数 parameters = update_parameters(parameters, gradients, learning_rate) return loss, gradients, a[len(X) - 1], parameters def model(examples, ix_to_char, char_to_ix, num_iterations=1500000, n_a=4, names=7, vocab_size=5880): """ 总模型,训练模型,训练过程中也产生部分名字. 参数: examples:名字库中名字形成的列表 char_to_ix:一个字典,字典的键为名字库中所有的字,值为其编码,实现由字得到编码 ix_to_char:一个字典,字典的键为名字库中字的编码,值为其对应的字,实现从编码得到字 num_iterations:迭代次数 n_a:激活值的尺寸 names:迭代过程中,每次打印名字时打印名字的数量 vocab_size:名字库中字符的数量 Returns: parameters:训练后得到的参数 """ # 进行时为了训练过程也能看到,实际对网络的参数训练没有影响 while True: first_name = input("请输入姓:").strip() if len(first_name) == 1 or len(first_name) == 2: break else: print("姓氏只能一个字或者两个字,请重新输入!!") n_x, n_y = vocab_size, vocab_size # 初始化参数 parameters = initialize_parameters(n_a, n_x, n_y) # 初始化损失函数 loss = get_initial_loss(vocab_size, names) # 初始化输入激活值 a_prev = np.zeros((n_a, 1)) # 循环迭代 for j in range(num_iterations): # 迭代一次,训练一个样本,防止,迭代次数过多,超出了examples的索引 index = j % len(examples) X = [None] + [char_to_ix[ch] for ch in examples[index]] Y = X[1:] + [char_to_ix["\n"]] # 调用上面写的optimize函数 curr_loss, gradients, a_prev, parameters = optimize( X, Y, a_prev, parameters, learning_rate=0.1) # 移动平均,加速迭代的过程 loss = smooth(loss, curr_loss) # 每2000次迭代,打印一次名字(names个) if j % 2000 == 0: print('Iteration: %d, Loss: %f' % (j, loss) + '\n') seed = 0 for name in range(names): sampled_indices = sample( parameters, char_to_ix, first_name, seed) print_sample(sampled_indices, ix_to_char) seed += 1 print('\n') return parameters if __name__ == "__main__": char_to_ix, ix_to_char = preprocess(data_set=DataSet) with open(DataSet) as f: examples = f.readlines() examples = [x.lower().strip() for x in examples] shuffle(examples) parameters = model(examples, ix_to_char, char_to_ix) io.savemat("parameters.mat", parameters) # 下载参数并使用模型 # 使用use_the_model.py
[ "numpy.random.seed", "random.shuffle", "numpy.zeros", "scipy.io.savemat", "numpy.dot" ]
[((1944, 1969), 'numpy.zeros', 'np.zeros', (['(vocab_size, 1)'], {}), '((vocab_size, 1))\n', (1952, 1969), True, 'import numpy as np\n'), ((2018, 2036), 'numpy.zeros', 'np.zeros', (['(n_a, 1)'], {}), '((n_a, 1))\n', (2026, 2036), True, 'import numpy as np\n'), ((2416, 2441), 'numpy.zeros', 'np.zeros', (['(vocab_size, 1)'], {}), '((vocab_size, 1))\n', (2424, 2441), True, 'import numpy as np\n'), ((5216, 5234), 'numpy.zeros', 'np.zeros', (['(n_a, 1)'], {}), '((n_a, 1))\n', (5224, 5234), True, 'import numpy as np\n'), ((6359, 6376), 'random.shuffle', 'shuffle', (['examples'], {}), '(examples)\n', (6366, 6376), False, 'from random import shuffle\n'), ((6440, 6480), 'scipy.io.savemat', 'io.savemat', (['"""parameters.mat"""', 'parameters'], {}), "('parameters.mat', parameters)\n", (6450, 6480), False, 'from scipy import io\n'), ((2726, 2751), 'numpy.zeros', 'np.zeros', (['(vocab_size, 1)'], {}), '((vocab_size, 1))\n', (2734, 2751), True, 'import numpy as np\n'), ((3014, 3044), 'numpy.random.seed', 'np.random.seed', (['(counter + seed)'], {}), '(counter + seed)\n', (3028, 3044), True, 'import numpy as np\n'), ((3197, 3222), 'numpy.zeros', 'np.zeros', (['(vocab_size, 1)'], {}), '((vocab_size, 1))\n', (3205, 3222), True, 'import numpy as np\n'), ((2961, 2975), 'numpy.dot', 'np.dot', (['Wya', 'a'], {}), '(Wya, a)\n', (2967, 2975), True, 'import numpy as np\n'), ((2261, 2275), 'numpy.dot', 'np.dot', (['Wax', 'x'], {}), '(Wax, x)\n', (2267, 2275), True, 'import numpy as np\n'), ((2278, 2297), 'numpy.dot', 'np.dot', (['Waa', 'a_prev'], {}), '(Waa, a_prev)\n', (2284, 2297), True, 'import numpy as np\n'), ((2601, 2615), 'numpy.dot', 'np.dot', (['Wax', 'x'], {}), '(Wax, x)\n', (2607, 2615), True, 'import numpy as np\n'), ((2618, 2637), 'numpy.dot', 'np.dot', (['Waa', 'a_prev'], {}), '(Waa, a_prev)\n', (2624, 2637), True, 'import numpy as np\n'), ((2906, 2920), 'numpy.dot', 'np.dot', (['Wax', 'x'], {}), '(Wax, x)\n', (2912, 2920), True, 'import numpy as np\n'), ((2923, 2942), 'numpy.dot', 'np.dot', (['Waa', 'a_prev'], {}), '(Waa, a_prev)\n', (2929, 2942), True, 'import numpy as np\n')]
import numpy as np import gimpact as gi # util functions def gen_cdmesh_vvnf(vertices, vertex_normals, faces): """ generate cdmesh given vertices, _, and faces :return: gimpact.TriMesh (require gimpact to be installed) author: weiwei date: 20210118 """ return gi.TriMesh(vertices, faces.flatten()) def is_collided(objcm0, objcm1): """ check if two objcm are collided after converting the specified cdmesh_type :param objcm0: :param objcm1: :return: author: weiwei date: 20210117 """ obj0 = gen_cdmesh_vvnf(*objcm0.extract_rotated_vvnf()) obj1 = gen_cdmesh_vvnf(*objcm1.extract_rotated_vvnf()) contacts = gi.trimesh_trimesh_collision(obj0, obj1) contact_points = [ct.point for ct in contacts] return (True, contact_points) if len(contact_points)>0 else (False, contact_points) def gen_plane_cdmesh(updirection=np.array([0, 0, 1]), offset=0, name='autogen'): """ generate a plane bulletrigidbody node :param updirection: the normal parameter of bulletplaneshape at panda3d :param offset: the d parameter of bulletplaneshape at panda3d :param name: :return: bulletrigidbody author: weiwei date: 20170202, tsukuba """ bulletplnode = BulletRigidBodyNode(name) bulletplshape = BulletPlaneShape(Vec3(updirection[0], updirection[1], updirection[2]), offset) bulletplshape.setMargin(0) bulletplnode.addShape(bulletplshape) return bulletplnode if __name__ == '__main__': import os, math, basis import numpy as np import visualization.panda.world as wd import modeling.geometric_model as gm import modeling.collision_model as cm # wd.World(cam_pos=[1.0, 1, .0, 1.0], lookat_pos=[0, 0, 0]) # objpath = os.path.join(basis.__path__[0], 'objects', 'bunnysim.stl') # objcm1= cm.CollisionModel(objpath) # homomat = np.eye(4) # homomat[:3, :3] = rm.rotmat_from_axangle([0, 0, 1], math.pi / 2) # homomat[:3, 3] = np.array([0.02, 0.02, 0]) # objcm1.set_homomat(homomat) # objcm1.set_rgba([1,1,.3,.2]) # objcm2 = objcm1.copy() # objcm2.set_pos(objcm1.get_pos()+np.array([.05,.02,.0])) # objcm1.change_cdmesh_type('convex_hull') # objcm2.change_cdmesh_type('obb') # iscollided, contacts = is_collided(objcm1, objcm2) # # objcm1.show_cdmesh(type='box') # # show_triangles_cdmesh(objcm1) # # show_triangles_cdmesh(objcm2) # show_cdmesh(objcm1) # show_cdmesh(objcm2) # # objcm1.show_cdmesh(type='box') # # objcm2.show_cdmesh(type='triangles') # objcm1.attach_to(base) # objcm2.attach_to(base) # print(iscollided) # for ct in contacts: # gm.gen_sphere(ct.point, radius=.001).attach_to(base) # # pfrom = np.array([0, 0, 0]) + np.array([1.0, 1.0, 1.0]) # # pto = np.array([0, 0, 0]) + np.array([-1.0, -1.0, -0.9]) # # hitpos, hitnrml = rayhit_triangles_closet(pfrom=pfrom, pto=pto, objcm=objcm) # # objcm.attach_to(base) # # objcm.show_cdmesh(type='box') # # objcm.show_cdmesh(type='convex_hull') # # gm.gen_sphere(hitpos, radius=.003, rgba=np.array([0, 1, 1, 1])).attach_to(base) # # gm.gen_stick(spos=pfrom, epos=pto, thickness=.002).attach_to(base) # # gm.gen_arrow(spos=hitpos, epos=hitpos + hitnrml * .07, thickness=.002, rgba=np.array([0, 1, 0, 1])).attach_to(base) # base.run() wd.World(cam_pos=[1.0, 1, .0, 1.0], lookat_pos=[0, 0, 0]) objpath = os.path.join(basis.__path__[0], 'objects', 'yumifinger.stl') objcm1= cm.CollisionModel(objpath, cdmesh_type='triangles') homomat = np.array([[ 5.00000060e-01, 7.00629234e-01, 5.09036899e-01, -3.43725011e-02], [ 8.66025329e-01, -4.04508471e-01, -2.93892622e-01, 5.41121606e-03], [-2.98023224e-08, 5.87785244e-01, -8.09016943e-01, 1.13636881e-01], [ 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 1.00000000e+00]]) homomat = np.array([[ 1.00000000e+00, 2.38935501e-16, 3.78436685e-17, -7.49999983e-03], [ 2.38935501e-16, -9.51056600e-01, -3.09017003e-01, 2.04893537e-02], [-3.78436685e-17, 3.09017003e-01, -9.51056600e-01, 1.22025304e-01], [ 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 1.00000000e+00]]) objcm1.set_homomat(homomat) objcm1.set_rgba([1,1,.3,.2]) objpath = os.path.join(basis.__path__[0], 'objects', 'tubebig.stl') objcm2= cm.CollisionModel(objpath, cdmesh_type='triangles') iscollided, contact_points = is_collided(objcm1, objcm2) # objcm1.show_cdmesh(type='box') # show_triangles_cdmesh(objcm1) # show_triangles_cdmesh(objcm2) objcm1.show_cdmesh() objcm2.show_cdmesh() # objcm1.show_cdmesh(type='box') # objcm2.show_cdmesh(type='triangles') objcm1.attach_to(base) objcm2.attach_to(base) print(iscollided) for ctpt in contact_points: gm.gen_sphere(ctpt, radius=.001).attach_to(base) # pfrom = np.array([0, 0, 0]) + np.array([1.0, 1.0, 1.0]) # pto = np.array([0, 0, 0]) + np.array([-1.0, -1.0, -0.9]) # hitpos, hitnrml = rayhit_triangles_closet(pfrom=pfrom, pto=pto, objcm=objcm) # objcm.attach_to(base) # objcm.show_cdmesh(type='box') # objcm.show_cdmesh(type='convex_hull') # gm.gen_sphere(hitpos, radius=.003, rgba=np.array([0, 1, 1, 1])).attach_to(base) # gm.gen_stick(spos=pfrom, epos=pto, thickness=.002).attach_to(base) # gm.gen_arrow(spos=hitpos, epos=hitpos + hitnrml * .07, thickness=.002, rgba=np.array([0, 1, 0, 1])).attach_to(base) base.run()
[ "modeling.collision_model.CollisionModel", "modeling.geometric_model.gen_sphere", "gimpact.trimesh_trimesh_collision", "numpy.array", "visualization.panda.world.World", "os.path.join" ]
[((678, 718), 'gimpact.trimesh_trimesh_collision', 'gi.trimesh_trimesh_collision', (['obj0', 'obj1'], {}), '(obj0, obj1)\n', (706, 718), True, 'import gimpact as gi\n'), ((892, 911), 'numpy.array', 'np.array', (['[0, 0, 1]'], {}), '([0, 0, 1])\n', (900, 911), True, 'import numpy as np\n'), ((3369, 3427), 'visualization.panda.world.World', 'wd.World', ([], {'cam_pos': '[1.0, 1, 0.0, 1.0]', 'lookat_pos': '[0, 0, 0]'}), '(cam_pos=[1.0, 1, 0.0, 1.0], lookat_pos=[0, 0, 0])\n', (3377, 3427), True, 'import visualization.panda.world as wd\n'), ((3441, 3501), 'os.path.join', 'os.path.join', (['basis.__path__[0]', '"""objects"""', '"""yumifinger.stl"""'], {}), "(basis.__path__[0], 'objects', 'yumifinger.stl')\n", (3453, 3501), False, 'import os, math, basis\n'), ((3514, 3565), 'modeling.collision_model.CollisionModel', 'cm.CollisionModel', (['objpath'], {'cdmesh_type': '"""triangles"""'}), "(objpath, cdmesh_type='triangles')\n", (3531, 3565), True, 'import modeling.collision_model as cm\n'), ((3580, 3798), 'numpy.array', 'np.array', (['[[0.50000006, 0.700629234, 0.509036899, -0.0343725011], [0.866025329, -\n 0.404508471, -0.293892622, 0.00541121606], [-2.98023224e-08, \n 0.587785244, -0.809016943, 0.113636881], [0.0, 0.0, 0.0, 1.0]]'], {}), '([[0.50000006, 0.700629234, 0.509036899, -0.0343725011], [\n 0.866025329, -0.404508471, -0.293892622, 0.00541121606], [-\n 2.98023224e-08, 0.587785244, -0.809016943, 0.113636881], [0.0, 0.0, 0.0,\n 1.0]])\n', (3588, 3798), True, 'import numpy as np\n'), ((3957, 4174), 'numpy.array', 'np.array', (['[[1.0, 2.38935501e-16, 3.78436685e-17, -0.00749999983], [2.38935501e-16, -\n 0.9510566, -0.309017003, 0.0204893537], [-3.78436685e-17, 0.309017003, \n -0.9510566, 0.122025304], [0.0, 0.0, 0.0, 1.0]]'], {}), '([[1.0, 2.38935501e-16, 3.78436685e-17, -0.00749999983], [\n 2.38935501e-16, -0.9510566, -0.309017003, 0.0204893537], [-\n 3.78436685e-17, 0.309017003, -0.9510566, 0.122025304], [0.0, 0.0, 0.0, \n 1.0]])\n', (3965, 4174), True, 'import numpy as np\n'), ((4400, 4457), 'os.path.join', 'os.path.join', (['basis.__path__[0]', '"""objects"""', '"""tubebig.stl"""'], {}), "(basis.__path__[0], 'objects', 'tubebig.stl')\n", (4412, 4457), False, 'import os, math, basis\n'), ((4470, 4521), 'modeling.collision_model.CollisionModel', 'cm.CollisionModel', (['objpath'], {'cdmesh_type': '"""triangles"""'}), "(objpath, cdmesh_type='triangles')\n", (4487, 4521), True, 'import modeling.collision_model as cm\n'), ((4938, 4971), 'modeling.geometric_model.gen_sphere', 'gm.gen_sphere', (['ctpt'], {'radius': '(0.001)'}), '(ctpt, radius=0.001)\n', (4951, 4971), True, 'import modeling.geometric_model as gm\n')]
# -*- coding: utf-8 -*- """ Steps of testing of SuperOperator class """ from behave import * import quantarhei as qr import numpy @given('I have a general superoperator S and two operators A and B') def step_given(context): S = qr.qm.TestSuperOperator("dim-3-AOA") A = qr.Hamiltonian(data=[[0.0, 0.1, 0.0], [0.1, 1.0, 0.2], [0.0, 0.2, 1.2]]) B = qr.Hamiltonian(data=[[0.0, 0.3, 0.1], [0.3, 1.0, 0.4], [0.1, 0.4, 2.0]]) context.S = S context.A = A context.B = B @when('I apply S to A to get operator C') def step_when(context): S = context.S A = context.A # This happens in the site basis C = S.apply(A) context.C = C @when('I transform S and A to the eigenbasis of B to get S_ and A_, respectively') def step_and(context): S = context.S A = context.A B = context.B with qr.eigenbasis_of(B): S_matrix = S._data A_matrix = A._data context.S_ = S_matrix context.A_ = A_matrix @when('I apply S_ to A_ to get operator D') def step_and2(context): S_ = context.S_ A_ = context.A_ # This happens in the basis of B eigenstates D = numpy.tensordot(S_, A_) context.D = D @when('I transform C into eigenbasis of B to get C_') def step_and3(context): # here we retrieve in eigenbasis of B what was calculated in site basis with qr.eigenbasis_of(context.B): C_ = context.C._data context.C_ = C_ @then('C_ equals D') def step_then(context): # we compare results calculated in different bases numpy.testing.assert_allclose(context.C_, context.D)
[ "numpy.tensordot", "numpy.testing.assert_allclose", "quantarhei.qm.TestSuperOperator", "quantarhei.Hamiltonian", "quantarhei.eigenbasis_of" ]
[((245, 281), 'quantarhei.qm.TestSuperOperator', 'qr.qm.TestSuperOperator', (['"""dim-3-AOA"""'], {}), "('dim-3-AOA')\n", (268, 281), True, 'import quantarhei as qr\n'), ((290, 362), 'quantarhei.Hamiltonian', 'qr.Hamiltonian', ([], {'data': '[[0.0, 0.1, 0.0], [0.1, 1.0, 0.2], [0.0, 0.2, 1.2]]'}), '(data=[[0.0, 0.1, 0.0], [0.1, 1.0, 0.2], [0.0, 0.2, 1.2]])\n', (304, 362), True, 'import quantarhei as qr\n'), ((431, 503), 'quantarhei.Hamiltonian', 'qr.Hamiltonian', ([], {'data': '[[0.0, 0.3, 0.1], [0.3, 1.0, 0.4], [0.1, 0.4, 2.0]]'}), '(data=[[0.0, 0.3, 0.1], [0.3, 1.0, 0.4], [0.1, 0.4, 2.0]])\n', (445, 503), True, 'import quantarhei as qr\n'), ((1305, 1328), 'numpy.tensordot', 'numpy.tensordot', (['S_', 'A_'], {}), '(S_, A_)\n', (1320, 1328), False, 'import numpy\n'), ((1725, 1777), 'numpy.testing.assert_allclose', 'numpy.testing.assert_allclose', (['context.C_', 'context.D'], {}), '(context.C_, context.D)\n', (1754, 1777), False, 'import numpy\n'), ((984, 1003), 'quantarhei.eigenbasis_of', 'qr.eigenbasis_of', (['B'], {}), '(B)\n', (1000, 1003), True, 'import quantarhei as qr\n'), ((1527, 1554), 'quantarhei.eigenbasis_of', 'qr.eigenbasis_of', (['context.B'], {}), '(context.B)\n', (1543, 1554), True, 'import quantarhei as qr\n')]
""" The lidar system, data (2 of 2 datasets) ======================================== Generate a chart of more complex data recorded by the lidar system """ import numpy as np import matplotlib.pyplot as plt waveform_2 = np.load('waveform_2.npy') t = np.arange(len(waveform_2)) fig, ax = plt.subplots(figsize=(8, 6)) plt.plot(t, waveform_2) plt.xlabel('Time [ns]') plt.ylabel('Amplitude [bins]') plt.show()
[ "numpy.load", "matplotlib.pyplot.show", "matplotlib.pyplot.plot", "matplotlib.pyplot.ylabel", "matplotlib.pyplot.xlabel", "matplotlib.pyplot.subplots" ]
[((224, 249), 'numpy.load', 'np.load', (['"""waveform_2.npy"""'], {}), "('waveform_2.npy')\n", (231, 249), True, 'import numpy as np\n'), ((293, 321), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {'figsize': '(8, 6)'}), '(figsize=(8, 6))\n', (305, 321), True, 'import matplotlib.pyplot as plt\n'), ((322, 345), 'matplotlib.pyplot.plot', 'plt.plot', (['t', 'waveform_2'], {}), '(t, waveform_2)\n', (330, 345), True, 'import matplotlib.pyplot as plt\n'), ((346, 369), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Time [ns]"""'], {}), "('Time [ns]')\n", (356, 369), True, 'import matplotlib.pyplot as plt\n'), ((370, 400), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Amplitude [bins]"""'], {}), "('Amplitude [bins]')\n", (380, 400), True, 'import matplotlib.pyplot as plt\n'), ((401, 411), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (409, 411), True, 'import matplotlib.pyplot as plt\n')]
# Copyright (c) 2018-2022, NVIDIA Corporation # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # 3. Neither the name of the copyright holder nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from ..rotation3d import * import numpy as np import torch q = torch.from_numpy(np.array([[0, 1, 2, 3], [-2, 3, -1, 5]], dtype=np.float32)) print("q", q) r = quat_normalize(q) x = torch.from_numpy(np.array([[1, 0, 0], [0, -1, 0]], dtype=np.float32)) print(r) print(quat_rotate(r, x)) angle = torch.from_numpy(np.array(np.random.rand() * 10.0, dtype=np.float32)) axis = torch.from_numpy( np.array([1, np.random.rand() * 10.0, np.random.rand() * 10.0], dtype=np.float32), ) print(repr(angle)) print(repr(axis)) rot = quat_from_angle_axis(angle, axis) x = torch.from_numpy(np.random.rand(5, 6, 3)) y = quat_rotate(quat_inverse(rot), quat_rotate(rot, x)) print(x.numpy()) print(y.numpy()) assert np.allclose(x.numpy(), y.numpy()) m = torch.from_numpy(np.array([[1, 0, 0], [0, 0, -1], [0, 1, 0]], dtype=np.float32)) r = quat_from_rotation_matrix(m) t = torch.from_numpy(np.array([0, 1, 0], dtype=np.float32)) se3 = transform_from_rotation_translation(r=r, t=t) print(se3) print(transform_apply(se3, t)) rot = quat_from_angle_axis( torch.from_numpy(np.array([45, -54], dtype=np.float32)), torch.from_numpy(np.array([[1, 0, 0], [0, 1, 0]], dtype=np.float32)), degree=True, ) trans = torch.from_numpy(np.array([[1, 1, 0], [1, 1, 0]], dtype=np.float32)) transform = transform_from_rotation_translation(r=rot, t=trans) t = transform_mul(transform, transform_inverse(transform)) gt = np.zeros((2, 7)) gt[:, 0] = 1.0 print(t.numpy()) print(gt) # assert np.allclose(t.numpy(), gt) transform2 = torch.from_numpy( np.array( [[1, 0, 0, 1], [0, 0, -1, 0], [0, 1, 0, 0], [0, 0, 0, 1]], dtype=np.float32 ), ) transform2 = euclidean_to_transform(transform2) print(transform2)
[ "numpy.array", "numpy.random.rand", "numpy.zeros" ]
[((2956, 2972), 'numpy.zeros', 'np.zeros', (['(2, 7)'], {}), '((2, 7))\n', (2964, 2972), True, 'import numpy as np\n'), ((1641, 1699), 'numpy.array', 'np.array', (['[[0, 1, 2, 3], [-2, 3, -1, 5]]'], {'dtype': 'np.float32'}), '([[0, 1, 2, 3], [-2, 3, -1, 5]], dtype=np.float32)\n', (1649, 1699), True, 'import numpy as np\n'), ((1758, 1809), 'numpy.array', 'np.array', (['[[1, 0, 0], [0, -1, 0]]'], {'dtype': 'np.float32'}), '([[1, 0, 0], [0, -1, 0]], dtype=np.float32)\n', (1766, 1809), True, 'import numpy as np\n'), ((2138, 2161), 'numpy.random.rand', 'np.random.rand', (['(5)', '(6)', '(3)'], {}), '(5, 6, 3)\n', (2152, 2161), True, 'import numpy as np\n'), ((2316, 2378), 'numpy.array', 'np.array', (['[[1, 0, 0], [0, 0, -1], [0, 1, 0]]'], {'dtype': 'np.float32'}), '([[1, 0, 0], [0, 0, -1], [0, 1, 0]], dtype=np.float32)\n', (2324, 2378), True, 'import numpy as np\n'), ((2434, 2471), 'numpy.array', 'np.array', (['[0, 1, 0]'], {'dtype': 'np.float32'}), '([0, 1, 0], dtype=np.float32)\n', (2442, 2471), True, 'import numpy as np\n'), ((2775, 2825), 'numpy.array', 'np.array', (['[[1, 1, 0], [1, 1, 0]]'], {'dtype': 'np.float32'}), '([[1, 1, 0], [1, 1, 0]], dtype=np.float32)\n', (2783, 2825), True, 'import numpy as np\n'), ((3087, 3177), 'numpy.array', 'np.array', (['[[1, 0, 0, 1], [0, 0, -1, 0], [0, 1, 0, 0], [0, 0, 0, 1]]'], {'dtype': 'np.float32'}), '([[1, 0, 0, 1], [0, 0, -1, 0], [0, 1, 0, 0], [0, 0, 0, 1]], dtype=\n np.float32)\n', (3095, 3177), True, 'import numpy as np\n'), ((2617, 2654), 'numpy.array', 'np.array', (['[45, -54]'], {'dtype': 'np.float32'}), '([45, -54], dtype=np.float32)\n', (2625, 2654), True, 'import numpy as np\n'), ((2678, 2728), 'numpy.array', 'np.array', (['[[1, 0, 0], [0, 1, 0]]'], {'dtype': 'np.float32'}), '([[1, 0, 0], [0, 1, 0]], dtype=np.float32)\n', (2686, 2728), True, 'import numpy as np\n'), ((1880, 1896), 'numpy.random.rand', 'np.random.rand', ([], {}), '()\n', (1894, 1896), True, 'import numpy as np\n'), ((1966, 1982), 'numpy.random.rand', 'np.random.rand', ([], {}), '()\n', (1980, 1982), True, 'import numpy as np\n'), ((1991, 2007), 'numpy.random.rand', 'np.random.rand', ([], {}), '()\n', (2005, 2007), True, 'import numpy as np\n')]
#!/usr/bin/env python import sys from scipy.stats import t from scipy.special import gammaln import numpy as np from numpy import pi,log,sqrt from numpy.linalg import slogdet,inv ################################ ### Multivariate Student's t ### ################################ ### Multivariate Student's t density (log) def dmvt(x,mu,Sigma,nu): ##### IMPORTANT: also the scalars MUST be np arrays ## Check that mu and Sigma have the appropriate dimension if mu.shape[0] != Sigma.shape[0]: raise ValueError("The arrays mu and Sigma must have compatible dimension.") if Sigma.shape[0] != 1: if Sigma.shape[0] != Sigma.shape[1]: raise ValueError("Sigma must be a squared matrix.") if mu.shape[0] == 1: ## Exception when the PDF is unidimensional return t.logpdf(x,df=nu,loc=mu,scale=sqrt(Sigma)) else: # Calculate the number of dimensions d = mu.shape[0] # Calculate the ratio of Gamma functions gamma_ratio = gammaln(nu/2.0 + d/2.0) - gammaln(nu/2.0) # Calculate the logarithm of the determinant logdet = -.5 * slogdet(Sigma)[1] - .5 * d * (log(pi) + log(nu)) # Invert the scale matrix, centre the vector and calculate the main expression Sigma_inv = inv(Sigma) x_center = x - mu main_exp = -.5 * (nu + d) * log(1 + (x_center.dot(Sigma_inv)).dot(x_center) / nu) # Return the result return gamma_ratio + logdet + main_exp ## log-density of the Student's t ### Multivariate Student's t density (log) -- computed efficiently (determinants and inverses are stored) def dmvt_efficient(x,mu,Sigma_inv,Sigma_logdet,nu): ##### IMPORTANT: the scalars MUST be numpy arrays ## Sigma_inv must be scaled by the degrees of freedom ## Check that mu and Sigma have the appropriate dimension if mu.shape[0] != Sigma_inv.shape[0]: raise ValueError("The arrays mu and Sigma must have compatible dimension.") if Sigma_inv.shape[0] != 1: if Sigma_inv.shape[0] != Sigma_inv.shape[1]: raise ValueError("Sigma must be a squared matrix.") if mu.shape[0] == 1: ## Exception when the PDF is unidimensional return t.logpdf(x,df=nu,loc=mu,scale=1/sqrt(Sigma_inv)) else: # Calculate the number of dimensions d = mu.shape[0] # Calculate the ratio of Gamma functions gamma_ratio = gammaln(.5*(nu + d)) - gammaln(.5*nu) # Calculate the logarithm of the determinant logdet = -.5 * Sigma_logdet - .5 * d * (log(pi) + log(nu)) # Centre the vector and calculate the main expression ### IMPORTANT: Sigma_inv MUST BE SCALED by the degrees of freedom in input x_center = x - mu main_exp = -.5 * (nu + d) * log(1 + (x_center.dot(Sigma_inv)).dot(x_center)) # Return the result return gamma_ratio + logdet + main_exp ## log-density of the Student's t
[ "numpy.log", "numpy.linalg.slogdet", "numpy.linalg.inv", "scipy.special.gammaln", "numpy.sqrt" ]
[((1188, 1198), 'numpy.linalg.inv', 'inv', (['Sigma'], {}), '(Sigma)\n', (1191, 1198), False, 'from numpy.linalg import slogdet, inv\n'), ((937, 964), 'scipy.special.gammaln', 'gammaln', (['(nu / 2.0 + d / 2.0)'], {}), '(nu / 2.0 + d / 2.0)\n', (944, 964), False, 'from scipy.special import gammaln\n'), ((963, 980), 'scipy.special.gammaln', 'gammaln', (['(nu / 2.0)'], {}), '(nu / 2.0)\n', (970, 980), False, 'from scipy.special import gammaln\n'), ((2222, 2245), 'scipy.special.gammaln', 'gammaln', (['(0.5 * (nu + d))'], {}), '(0.5 * (nu + d))\n', (2229, 2245), False, 'from scipy.special import gammaln\n'), ((2245, 2262), 'scipy.special.gammaln', 'gammaln', (['(0.5 * nu)'], {}), '(0.5 * nu)\n', (2252, 2262), False, 'from scipy.special import gammaln\n'), ((800, 811), 'numpy.sqrt', 'sqrt', (['Sigma'], {}), '(Sigma)\n', (804, 811), False, 'from numpy import pi, log, sqrt\n'), ((1044, 1058), 'numpy.linalg.slogdet', 'slogdet', (['Sigma'], {}), '(Sigma)\n', (1051, 1058), False, 'from numpy.linalg import slogdet, inv\n'), ((1074, 1081), 'numpy.log', 'log', (['pi'], {}), '(pi)\n', (1077, 1081), False, 'from numpy import pi, log, sqrt\n'), ((1084, 1091), 'numpy.log', 'log', (['nu'], {}), '(nu)\n', (1087, 1091), False, 'from numpy import pi, log, sqrt\n'), ((2082, 2097), 'numpy.sqrt', 'sqrt', (['Sigma_inv'], {}), '(Sigma_inv)\n', (2086, 2097), False, 'from numpy import pi, log, sqrt\n'), ((2350, 2357), 'numpy.log', 'log', (['pi'], {}), '(pi)\n', (2353, 2357), False, 'from numpy import pi, log, sqrt\n'), ((2360, 2367), 'numpy.log', 'log', (['nu'], {}), '(nu)\n', (2363, 2367), False, 'from numpy import pi, log, sqrt\n')]
import numpy as np def tensor2numpy(img_tensor): """ Helper method to transfer image from torch.tensor to numpy.array :param img_tensor: image in torch.tensor format :return: image in numpy.array format """ img = img_tensor.detach().cpu().numpy().transpose(1,2,0) ### not to take grad of img img= np.clip(img, 0, 1) # less than 0 = 0, bigger than 1 = 1 img = img.astype('float32') if img.shape[-1] == 1: img = np.squeeze(img) # e.x. (3,) and not (3, 1) return img
[ "numpy.squeeze", "numpy.clip" ]
[((315, 333), 'numpy.clip', 'np.clip', (['img', '(0)', '(1)'], {}), '(img, 0, 1)\n', (322, 333), True, 'import numpy as np\n'), ((441, 456), 'numpy.squeeze', 'np.squeeze', (['img'], {}), '(img)\n', (451, 456), True, 'import numpy as np\n')]
from __future__ import print_function from __future__ import division import torch import torch.nn as nn import torch.optim as optim import numpy as np print("PyTorch Version: ",torch.__version__) import pickle import os import scipy.io as sio import cv2 from model import * from pano import get_ini_cor from pano_opt_gen import optimize_cor_id import post_proc2 as post_proc from shapely.geometry import Polygon from scipy.ndimage.filters import maximum_filter from scipy.ndimage import convolve import scipy.signal import sys from sklearn.metrics import classification_report # general case # Top level data directory. Here we assume the format of the directory conforms # to the ImageFolder structure test_path = './data/matterport/mp3d_align/' weight_path = './model/resnet34_matterport.pth' save_path = './result_gen/' depth_path = './result_gen_depth/' depth_path_gt = './data/matterport/share_depth/' # Pre-trained models to choose from [resnet18, resnet34, resnet50] #model_name = "resnet18" model_name = "resnet34" #model_name = "resnet50" num_classes = 1024 print("Load Models...") # Define the encoder encoder = initialize_encoder(model_name, num_classes,use_pretrained=True) # Full model model_ft = SegNet(encoder, num_classes) model_ft.load_state_dict(torch.load(weight_path)) # Detect if we have a GPU available device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") # Send the model to GPU model_ft = model_ft.to(device) # evaluation mode model_ft.eval() def find_N_peaks(signal, r=29, min_v=0.05, N=None): max_v = maximum_filter(signal, size=r, mode='wrap') pk_loc = np.where(max_v == signal)[0] pk_loc = pk_loc[signal[pk_loc] > min_v] # check for odd case, remove one if (pk_loc.shape[0]%2)!=0: pk_id = np.argsort(-signal[pk_loc]) pk_loc = pk_loc[pk_id[:-1]] pk_loc = np.sort(pk_loc) if N is not None: order = np.argsort(-signal[pk_loc]) pk_loc = pk_loc[order[:N]] pk_loc = pk_loc[np.argsort(pk_loc)] return pk_loc, signal[pk_loc] def find_N_peaks_conv(signal, prominence, distance, N=4): locs, _ = scipy.signal.find_peaks(signal, prominence=prominence, distance=distance) pks = signal[locs] pk_id = np.argsort(-pks) pk_loc = locs[pk_id[:min(N, len(pks))]] pk_loc = np.sort(pk_loc) return pk_loc, signal[pk_loc] def get_ini_cor(cor_img, d1=21, d2=3): cor = convolve(cor_img, np.ones((d1, d1)), mode='constant', cval=0.0) cor_id = [] cor_ = cor_img.sum(0) cor_ = (cor_-np.amin(cor_))/np.ptp(cor_) min_v = 0.25#0.05 xs_ = find_N_peaks(cor_, r=26, min_v=min_v, N=None)[0] # spetial case for too less corner if xs_.shape[0] < 4: xs_ = find_N_peaks(cor_, r=26, min_v=0.05, N=None)[0] if xs_.shape[0] < 4: xs_ = find_N_peaks(cor_, r=26, min_v=0, N=None)[0] X_loc = xs_ for x in X_loc: x_ = int(np.round(x)) V_signal = cor[:, max(0, x_-d2):x_+d2+1].sum(1) y1, y2 = find_N_peaks_conv(V_signal, prominence=None, distance=20, N=2)[0] cor_id.append((x, y1)) cor_id.append((x, y2)) cor_id = np.array(cor_id, np.float64) return cor_id def test_general(dt_cor_id, gt_cor_id, w, h, losses): dt_floor_coor = dt_cor_id[1::2] dt_ceil_coor = dt_cor_id[0::2] gt_floor_coor = gt_cor_id[1::2] gt_ceil_coor = gt_cor_id[0::2] assert (dt_floor_coor[:, 0] != dt_ceil_coor[:, 0]).sum() == 0 assert (gt_floor_coor[:, 0] != gt_ceil_coor[:, 0]).sum() == 0 # Eval 3d IoU and height error(in meter) N = len(dt_floor_coor) ch = -1.6 dt_floor_xy = post_proc.np_coor2xy(dt_floor_coor, ch, 1024, 512, floorW=1, floorH=1) gt_floor_xy = post_proc.np_coor2xy(gt_floor_coor, ch, 1024, 512, floorW=1, floorH=1) dt_poly = Polygon(dt_floor_xy) gt_poly = Polygon(gt_floor_xy) area_dt = dt_poly.area area_gt = gt_poly.area if area_dt < 1e-05: print('too small room') # Add a result n_corners = len(gt_floor_coor) n_corners = str(n_corners) if n_corners < 14 else '14+' losses[n_corners]['2DIoU'].append(0) losses[n_corners]['3DIoU'].append(0) losses['overall']['2DIoU'].append(0) losses['overall']['3DIoU'].append(0) return area_inter = dt_poly.intersection(gt_poly).area area_union = dt_poly.union(gt_poly).area area_pred_wo_gt = dt_poly.difference(gt_poly).area area_gt_wo_pred = gt_poly.difference(dt_poly).area iou2d = area_inter / (area_gt + area_dt - area_inter) cch_dt = post_proc.get_z1(dt_floor_coor[:, 1], dt_ceil_coor[:, 1], ch, 512) cch_gt = post_proc.get_z1(gt_floor_coor[:, 1], gt_ceil_coor[:, 1], ch, 512) h_dt = abs(cch_dt.mean() - ch) h_gt = abs(cch_gt.mean() - ch) #iouH = min(h_dt, h_gt) / max(h_dt, h_gt) #iou3d = iou2d * iouH iou3d = (area_inter * min(h_dt, h_gt)) / (area_pred_wo_gt * h_dt + area_gt_wo_pred * h_gt + area_inter * max(h_dt, h_gt)) # Add a result n_corners = len(gt_floor_coor) n_corners = str(n_corners) if n_corners < 14 else '14+' losses[n_corners]['2DIoU'].append(iou2d) losses[n_corners]['3DIoU'].append(iou3d) losses['overall']['2DIoU'].append(iou2d) losses['overall']['3DIoU'].append(iou3d) # Load data gt_txt_path = '/data/czou4/Layout/_final_label_v2/test.txt' namelist = [] with open(gt_txt_path, 'r') as f: while(True): line = f.readline().strip() if not line: break namelist.append(line) criterion = nn.BCELoss() criterion2 = nn.BCELoss() cnt = 0 num = 0 loss_cor = 0.0 loss_pe = 0.0 loss_3d = 0.0 loss_sum = 0.0 losses = dict([ (n_corner, {'2DIoU': [], '3DIoU': [], 'rmse':[], 'delta_1':[]}) for n_corner in ['4', '6', '8', '10', '12', '14+', 'overall'] ]) # for precision recall target_names = ['4 corners', '6 corners', '8 corners', '10 corners', '12 corners', '14 corners', '16 corners', '18 corners'] y_true = np.zeros(len(namelist)) y_pred = np.zeros(len(namelist)) for file_list in namelist: #file_list = np.random.choice(namelist, 1) #file_list = file_list[0] print(file_list) file_list_sub = file_list.split(" ") pkl_path = os.path.join(test_path,file_list_sub[0],file_list_sub[1]) img = cv2.imread(os.path.join(pkl_path,'aligned_rgb.png')) img = img.astype('float32')/255.0 mask = cv2.imread(os.path.join(pkl_path,'aligned_line.png')) mask = mask.astype('float32')/255.0 gt = np.loadtxt(os.path.join(pkl_path,'cor.txt')) # lr flip img2 = np.fliplr(img).copy() mask2 = np.fliplr(mask).copy() image = torch.tensor(img).to(device).float() masks = torch.tensor(mask).to(device).float() inputs = image.permute(2,0,1) inputs = inputs.unsqueeze(0) masks = masks.permute(2,0,1) masks = masks.unsqueeze(0) inputs = torch.cat((inputs,masks),1) image2 = torch.tensor(img2).to(device).float() masks2 = torch.tensor(mask2).to(device).float() inputs2 = image2.permute(2,0,1) inputs2 = inputs2.unsqueeze(0) masks2 = masks2.permute(2,0,1) masks2 = masks2.unsqueeze(0) inputs2 = torch.cat((inputs2,masks2),1) inputs = torch.cat((inputs, inputs2),0) # forward outputs, outputs2 = model_ft(inputs) # lr flip and take mean outputs1 = outputs[1] outputs22 = outputs2[1] inv_idx = torch.arange(outputs1.size(2)-1, -1, -1).to(device).long() outputs1 = outputs1.index_select(2, inv_idx) outputs = torch.mean(torch.cat((outputs[0].unsqueeze(0), outputs1.unsqueeze(0)), 0), 0, True) outputs22 = outputs22.index_select(2, inv_idx) outputs2 = torch.mean(torch.cat((outputs2[0].unsqueeze(0), outputs22.unsqueeze(0)), 0), 0, True) outputs = outputs.squeeze(0).permute(1,2,0) outputs2 = outputs2.squeeze(0).squeeze(0) inputs = inputs[0].permute(1,2,0) #gradient ascent refinement cor_img = outputs2.data.cpu().numpy() edg_img = outputs.data.cpu().numpy() #general layout, tp view cor_ = cor_img.sum(0) cor_ = (cor_-np.amin(cor_))/np.ptp(cor_) min_v = 0.25#0.05 xs_ = find_N_peaks(cor_, r=26, min_v=min_v, N=None)[0] # spetial case for too less corner if xs_.shape[0] < 4: xs_ = find_N_peaks(cor_, r=26, min_v=0.05, N=None)[0] if xs_.shape[0] < 4: xs_ = find_N_peaks(cor_, r=26, min_v=0, N=None)[0] # get ceil and floor line ceil_img = edg_img[:,:,1] floor_img = edg_img[:,:,2] ceil_idx = np.argmax(ceil_img, axis=0) floor_idx = np.argmax(floor_img, axis=0) # Init floor/ceil plane z0 = 50 force_cuboid=False _, z1 = post_proc.np_refine_by_fix_z(ceil_idx, floor_idx, z0) # Generate general wall-wall cor, xy_cor = post_proc.gen_ww(xs_, ceil_idx, z0, tol=abs(0.16 * z1 / 1.6), force_cuboid=force_cuboid) if not force_cuboid: # Check valid (for fear self-intersection) xy2d = np.zeros((len(xy_cor), 2), np.float32) for i in range(len(xy_cor)): xy2d[i, xy_cor[i]['type']] = xy_cor[i]['val'] xy2d[i, xy_cor[i-1]['type']] = xy_cor[i-1]['val'] if not Polygon(xy2d).is_valid: # actually it's not force cuboid, just assume all corners are visible, go back to original LayoutNet initialization #print( # 'Fail to generate valid general layout!! ' # 'Generate cuboid as fallback.', # file=sys.stderr) cor_id = get_ini_cor(cor_img, 21, 3) force_cuboid= True if not force_cuboid: # Expand with btn coory cor = np.hstack([cor, post_proc.infer_coory(cor[:, 1], z1 - z0, z0)[:, None]]) # Collect corner position in equirectangular cor_id = np.zeros((len(cor)*2, 2), np.float32) for j in range(len(cor)): cor_id[j*2] = cor[j, 0], cor[j, 1] cor_id[j*2 + 1] = cor[j, 0], cor[j, 2] # refinement cor_id = optimize_cor_id(cor_id, edg_img, cor_img, num_iters=100, verbose=False) test_general(cor_id, gt, 1024, 512, losses) # save, uncomment to generate depth map #print(save_path+file_list_sub[0]+'_'+file_list_sub[1]+'.mat') #sio.savemat(save_path+file_list_sub[0]+'_'+file_list_sub[1]+'.mat',{'cor_id':cor_id}) #load pred_depth = depth_path+file_list_sub[0]+'_'+file_list_sub[1]+'.mat' if os.path.exists(pred_depth): pred_depth = sio.loadmat(pred_depth) pred_depth = pred_depth['im_depth'] #gt gt_depth = np.load(os.path.join(depth_path_gt, file_list_sub[0], file_list_sub[1], 'new_depth.npy')) pred_depth = cv2.resize(pred_depth, (gt_depth.shape[1], gt_depth.shape[0])) # rmse pred_depth = pred_depth[np.nonzero(gt_depth)] gt_depth = gt_depth[np.nonzero(gt_depth)] rmse = np.average((gt_depth - pred_depth) ** 2) ** 0.5 # delta_1 max_map = np.where(gt_depth/pred_depth > pred_depth/gt_depth, gt_depth/pred_depth, pred_depth/gt_depth) delta_1 = np.average(np.where(max_map < 1.25, 1, 0)) # Add a result n_corners = len(gt[1::2]) n_corners = str(n_corners) if n_corners < 14 else '14+' losses[n_corners]['rmse'].append(rmse) losses[n_corners]['delta_1'].append(delta_1) losses['overall']['rmse'].append(rmse) losses['overall']['delta_1'].append(delta_1) torch.cuda.empty_cache() #del outputs1, outputs, outputs2, outputs22, labels, labels2, inputs, inputs2, loss del outputs1, outputs, outputs2, outputs22, inputs, inputs2 y_true[cnt] = int(gt.shape[0]//2//2-2) y_pred[cnt] = int(cor_id.shape[0]//2//2-2) cnt += 1 num += 1 iou2d = np.array(losses['overall']['2DIoU']) iou3d = np.array(losses['overall']['3DIoU']) rmse = np.array(losses['overall']['rmse']) delta_1 = np.array(losses['overall']['delta_1']) print('No. {}, 2d Loss: {:.6f}, 3d Loss: {:.6f}, rmse: {:.6f}, delta_1: {:.6f}'.format(cnt,iou2d.mean() * 100,iou3d.mean() * 100, rmse.mean() *100, delta_1.mean()*100)) for k, result in losses.items(): iou2d = np.array(result['2DIoU']) iou3d = np.array(result['3DIoU']) rmse = np.array(result['rmse']) delta_1 = np.array(result['delta_1']) if len(iou2d) == 0: continue print('GT #Corners: %s (%d instances)' % (k, len(iou2d))) print(' 2DIoU: %.2f' % ( iou2d.mean() * 100)) print(' 3DIoU: %.2f' % ( iou3d.mean() * 100)) print(' RMSE: %.2f' % ( rmse.mean()*100)) print(' Delta_1: %.2f' % ( delta_1.mean()*100)) print(classification_report(y_true, y_pred, target_names=target_names))
[ "pano_opt_gen.optimize_cor_id", "numpy.amin", "numpy.argmax", "scipy.io.loadmat", "torch.cat", "sklearn.metrics.classification_report", "numpy.ones", "numpy.argsort", "os.path.join", "numpy.round", "torch.nn.BCELoss", "shapely.geometry.Polygon", "torch.load", "os.path.exists", "pano.get_ini_cor", "cv2.resize", "numpy.average", "post_proc2.get_z1", "numpy.sort", "numpy.fliplr", "torch.cuda.is_available", "post_proc2.np_refine_by_fix_z", "scipy.ndimage.filters.maximum_filter", "post_proc2.infer_coory", "numpy.ptp", "post_proc2.np_coor2xy", "numpy.nonzero", "numpy.where", "numpy.array", "torch.cuda.empty_cache", "torch.tensor" ]
[((5674, 5686), 'torch.nn.BCELoss', 'nn.BCELoss', ([], {}), '()\n', (5684, 5686), True, 'import torch.nn as nn\n'), ((5700, 5712), 'torch.nn.BCELoss', 'nn.BCELoss', ([], {}), '()\n', (5710, 5712), True, 'import torch.nn as nn\n'), ((1279, 1302), 'torch.load', 'torch.load', (['weight_path'], {}), '(weight_path)\n', (1289, 1302), False, 'import torch\n'), ((1568, 1611), 'scipy.ndimage.filters.maximum_filter', 'maximum_filter', (['signal'], {'size': 'r', 'mode': '"""wrap"""'}), "(signal, size=r, mode='wrap')\n", (1582, 1611), False, 'from scipy.ndimage.filters import maximum_filter\n'), ((2317, 2333), 'numpy.argsort', 'np.argsort', (['(-pks)'], {}), '(-pks)\n', (2327, 2333), True, 'import numpy as np\n'), ((2391, 2406), 'numpy.sort', 'np.sort', (['pk_loc'], {}), '(pk_loc)\n', (2398, 2406), True, 'import numpy as np\n'), ((3264, 3292), 'numpy.array', 'np.array', (['cor_id', 'np.float64'], {}), '(cor_id, np.float64)\n', (3272, 3292), True, 'import numpy as np\n'), ((3747, 3817), 'post_proc2.np_coor2xy', 'post_proc.np_coor2xy', (['dt_floor_coor', 'ch', '(1024)', '(512)'], {'floorW': '(1)', 'floorH': '(1)'}), '(dt_floor_coor, ch, 1024, 512, floorW=1, floorH=1)\n', (3767, 3817), True, 'import post_proc2 as post_proc\n'), ((3836, 3906), 'post_proc2.np_coor2xy', 'post_proc.np_coor2xy', (['gt_floor_coor', 'ch', '(1024)', '(512)'], {'floorW': '(1)', 'floorH': '(1)'}), '(gt_floor_coor, ch, 1024, 512, floorW=1, floorH=1)\n', (3856, 3906), True, 'import post_proc2 as post_proc\n'), ((3921, 3941), 'shapely.geometry.Polygon', 'Polygon', (['dt_floor_xy'], {}), '(dt_floor_xy)\n', (3928, 3941), False, 'from shapely.geometry import Polygon\n'), ((3956, 3976), 'shapely.geometry.Polygon', 'Polygon', (['gt_floor_xy'], {}), '(gt_floor_xy)\n', (3963, 3976), False, 'from shapely.geometry import Polygon\n'), ((4707, 4773), 'post_proc2.get_z1', 'post_proc.get_z1', (['dt_floor_coor[:, 1]', 'dt_ceil_coor[:, 1]', 'ch', '(512)'], {}), '(dt_floor_coor[:, 1], dt_ceil_coor[:, 1], ch, 512)\n', (4723, 4773), True, 'import post_proc2 as post_proc\n'), ((4787, 4853), 'post_proc2.get_z1', 'post_proc.get_z1', (['gt_floor_coor[:, 1]', 'gt_ceil_coor[:, 1]', 'ch', '(512)'], {}), '(gt_floor_coor[:, 1], gt_ceil_coor[:, 1], ch, 512)\n', (4803, 4853), True, 'import post_proc2 as post_proc\n'), ((6367, 6426), 'os.path.join', 'os.path.join', (['test_path', 'file_list_sub[0]', 'file_list_sub[1]'], {}), '(test_path, file_list_sub[0], file_list_sub[1])\n', (6379, 6426), False, 'import os\n'), ((7022, 7051), 'torch.cat', 'torch.cat', (['(inputs, masks)', '(1)'], {}), '((inputs, masks), 1)\n', (7031, 7051), False, 'import torch\n'), ((7308, 7339), 'torch.cat', 'torch.cat', (['(inputs2, masks2)', '(1)'], {}), '((inputs2, masks2), 1)\n', (7317, 7339), False, 'import torch\n'), ((7352, 7383), 'torch.cat', 'torch.cat', (['(inputs, inputs2)', '(0)'], {}), '((inputs, inputs2), 0)\n', (7361, 7383), False, 'import torch\n'), ((8656, 8683), 'numpy.argmax', 'np.argmax', (['ceil_img'], {'axis': '(0)'}), '(ceil_img, axis=0)\n', (8665, 8683), True, 'import numpy as np\n'), ((8700, 8728), 'numpy.argmax', 'np.argmax', (['floor_img'], {'axis': '(0)'}), '(floor_img, axis=0)\n', (8709, 8728), True, 'import numpy as np\n'), ((8804, 8857), 'post_proc2.np_refine_by_fix_z', 'post_proc.np_refine_by_fix_z', (['ceil_idx', 'floor_idx', 'z0'], {}), '(ceil_idx, floor_idx, z0)\n', (8832, 8857), True, 'import post_proc2 as post_proc\n'), ((10121, 10192), 'pano_opt_gen.optimize_cor_id', 'optimize_cor_id', (['cor_id', 'edg_img', 'cor_img'], {'num_iters': '(100)', 'verbose': '(False)'}), '(cor_id, edg_img, cor_img, num_iters=100, verbose=False)\n', (10136, 10192), False, 'from pano_opt_gen import optimize_cor_id\n'), ((10545, 10571), 'os.path.exists', 'os.path.exists', (['pred_depth'], {}), '(pred_depth)\n', (10559, 10571), False, 'import os\n'), ((11598, 11622), 'torch.cuda.empty_cache', 'torch.cuda.empty_cache', ([], {}), '()\n', (11620, 11622), False, 'import torch\n'), ((11909, 11945), 'numpy.array', 'np.array', (["losses['overall']['2DIoU']"], {}), "(losses['overall']['2DIoU'])\n", (11917, 11945), True, 'import numpy as np\n'), ((11958, 11994), 'numpy.array', 'np.array', (["losses['overall']['3DIoU']"], {}), "(losses['overall']['3DIoU'])\n", (11966, 11994), True, 'import numpy as np\n'), ((12006, 12041), 'numpy.array', 'np.array', (["losses['overall']['rmse']"], {}), "(losses['overall']['rmse'])\n", (12014, 12041), True, 'import numpy as np\n'), ((12056, 12094), 'numpy.array', 'np.array', (["losses['overall']['delta_1']"], {}), "(losses['overall']['delta_1'])\n", (12064, 12094), True, 'import numpy as np\n'), ((12315, 12340), 'numpy.array', 'np.array', (["result['2DIoU']"], {}), "(result['2DIoU'])\n", (12323, 12340), True, 'import numpy as np\n'), ((12353, 12378), 'numpy.array', 'np.array', (["result['3DIoU']"], {}), "(result['3DIoU'])\n", (12361, 12378), True, 'import numpy as np\n'), ((12390, 12414), 'numpy.array', 'np.array', (["result['rmse']"], {}), "(result['rmse'])\n", (12398, 12414), True, 'import numpy as np\n'), ((12429, 12456), 'numpy.array', 'np.array', (["result['delta_1']"], {}), "(result['delta_1'])\n", (12437, 12456), True, 'import numpy as np\n'), ((12778, 12842), 'sklearn.metrics.classification_report', 'classification_report', (['y_true', 'y_pred'], {'target_names': 'target_names'}), '(y_true, y_pred, target_names=target_names)\n', (12799, 12842), False, 'from sklearn.metrics import classification_report\n'), ((1375, 1400), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (1398, 1400), False, 'import torch\n'), ((1625, 1650), 'numpy.where', 'np.where', (['(max_v == signal)'], {}), '(max_v == signal)\n', (1633, 1650), True, 'import numpy as np\n'), ((1783, 1810), 'numpy.argsort', 'np.argsort', (['(-signal[pk_loc])'], {}), '(-signal[pk_loc])\n', (1793, 1810), True, 'import numpy as np\n'), ((1864, 1879), 'numpy.sort', 'np.sort', (['pk_loc'], {}), '(pk_loc)\n', (1871, 1879), True, 'import numpy as np\n'), ((1918, 1945), 'numpy.argsort', 'np.argsort', (['(-signal[pk_loc])'], {}), '(-signal[pk_loc])\n', (1928, 1945), True, 'import numpy as np\n'), ((2509, 2526), 'numpy.ones', 'np.ones', (['(d1, d1)'], {}), '((d1, d1))\n', (2516, 2526), True, 'import numpy as np\n'), ((2629, 2641), 'numpy.ptp', 'np.ptp', (['cor_'], {}), '(cor_)\n', (2635, 2641), True, 'import numpy as np\n'), ((6446, 6487), 'os.path.join', 'os.path.join', (['pkl_path', '"""aligned_rgb.png"""'], {}), "(pkl_path, 'aligned_rgb.png')\n", (6458, 6487), False, 'import os\n'), ((6548, 6590), 'os.path.join', 'os.path.join', (['pkl_path', '"""aligned_line.png"""'], {}), "(pkl_path, 'aligned_line.png')\n", (6560, 6590), False, 'import os\n'), ((6651, 6684), 'os.path.join', 'os.path.join', (['pkl_path', '"""cor.txt"""'], {}), "(pkl_path, 'cor.txt')\n", (6663, 6684), False, 'import os\n'), ((8238, 8250), 'numpy.ptp', 'np.ptp', (['cor_'], {}), '(cor_)\n', (8244, 8250), True, 'import numpy as np\n'), ((10594, 10617), 'scipy.io.loadmat', 'sio.loadmat', (['pred_depth'], {}), '(pred_depth)\n', (10605, 10617), True, 'import scipy.io as sio\n'), ((10813, 10875), 'cv2.resize', 'cv2.resize', (['pred_depth', '(gt_depth.shape[1], gt_depth.shape[0])'], {}), '(pred_depth, (gt_depth.shape[1], gt_depth.shape[0]))\n', (10823, 10875), False, 'import cv2\n'), ((11108, 11213), 'numpy.where', 'np.where', (['(gt_depth / pred_depth > pred_depth / gt_depth)', '(gt_depth / pred_depth)', '(pred_depth / gt_depth)'], {}), '(gt_depth / pred_depth > pred_depth / gt_depth, gt_depth /\n pred_depth, pred_depth / gt_depth)\n', (11116, 11213), True, 'import numpy as np\n'), ((2005, 2023), 'numpy.argsort', 'np.argsort', (['pk_loc'], {}), '(pk_loc)\n', (2015, 2023), True, 'import numpy as np\n'), ((2614, 2627), 'numpy.amin', 'np.amin', (['cor_'], {}), '(cor_)\n', (2621, 2627), True, 'import numpy as np\n'), ((3005, 3016), 'numpy.round', 'np.round', (['x'], {}), '(x)\n', (3013, 3016), True, 'import numpy as np\n'), ((6711, 6725), 'numpy.fliplr', 'np.fliplr', (['img'], {}), '(img)\n', (6720, 6725), True, 'import numpy as np\n'), ((6745, 6760), 'numpy.fliplr', 'np.fliplr', (['mask'], {}), '(mask)\n', (6754, 6760), True, 'import numpy as np\n'), ((8223, 8236), 'numpy.amin', 'np.amin', (['cor_'], {}), '(cor_)\n', (8230, 8236), True, 'import numpy as np\n'), ((9642, 9669), 'pano.get_ini_cor', 'get_ini_cor', (['cor_img', '(21)', '(3)'], {}), '(cor_img, 21, 3)\n', (9653, 9669), False, 'from pano import get_ini_cor\n'), ((10710, 10795), 'os.path.join', 'os.path.join', (['depth_path_gt', 'file_list_sub[0]', 'file_list_sub[1]', '"""new_depth.npy"""'], {}), "(depth_path_gt, file_list_sub[0], file_list_sub[1], 'new_depth.npy'\n )\n", (10722, 10795), False, 'import os\n'), ((10931, 10951), 'numpy.nonzero', 'np.nonzero', (['gt_depth'], {}), '(gt_depth)\n', (10941, 10951), True, 'import numpy as np\n'), ((10981, 11001), 'numpy.nonzero', 'np.nonzero', (['gt_depth'], {}), '(gt_depth)\n', (10991, 11001), True, 'import numpy as np\n'), ((11018, 11058), 'numpy.average', 'np.average', (['((gt_depth - pred_depth) ** 2)'], {}), '((gt_depth - pred_depth) ** 2)\n', (11028, 11058), True, 'import numpy as np\n'), ((11231, 11261), 'numpy.where', 'np.where', (['(max_map < 1.25)', '(1)', '(0)'], {}), '(max_map < 1.25, 1, 0)\n', (11239, 11261), True, 'import numpy as np\n'), ((9306, 9319), 'shapely.geometry.Polygon', 'Polygon', (['xy2d'], {}), '(xy2d)\n', (9313, 9319), False, 'from shapely.geometry import Polygon\n'), ((6781, 6798), 'torch.tensor', 'torch.tensor', (['img'], {}), '(img)\n', (6793, 6798), False, 'import torch\n'), ((6830, 6848), 'torch.tensor', 'torch.tensor', (['mask'], {}), '(mask)\n', (6842, 6848), False, 'import torch\n'), ((7064, 7082), 'torch.tensor', 'torch.tensor', (['img2'], {}), '(img2)\n', (7076, 7082), False, 'import torch\n'), ((7115, 7134), 'torch.tensor', 'torch.tensor', (['mask2'], {}), '(mask2)\n', (7127, 7134), False, 'import torch\n'), ((9793, 9838), 'post_proc2.infer_coory', 'post_proc.infer_coory', (['cor[:, 1]', '(z1 - z0)', 'z0'], {}), '(cor[:, 1], z1 - z0, z0)\n', (9814, 9838), True, 'import post_proc2 as post_proc\n')]
"""Process images into timed Morse signals.""" import collections import operator import threading import time from Queue import Queue import libmorse import numpy from PIL import ImageFilter from morseus import settings from morseus.settings import LOGGING class Decoder(object): """Interpret black & white images as Morse code.""" BW_MODE = "L" MONO_MODE = "1" MONO_THRESHOLD = settings.MONO_THRESHOLD LIGHT_DARK_RATIO = settings.LIGHT_DARK_RATIO MAX_SIGNALS = 128 def __init__(self, debug): """Instantiate `Decoder` object with the arguments below. :param bool debug: show debug messages or not """ # Last created thread (waiting purposes). self._last_thread = None # Morse translator. self._translate = libmorse.translate_morse( use_logging=LOGGING.USE, debug=debug) # Initialize translator coroutine. self._translator = self._translate.next()[0] self._translate_lock = threading.Lock() # Output queue of string letters. self._letters_queue = Queue() @staticmethod def _flood_fill(image, node, seen): """Find white spots and return their area.""" queue = collections.deque() area = 0 def add_pos(pos): # Check position and retrieve pixel. width, height = image.size valid = 0 <= pos[0] < width and 0 <= pos[1] < height if not valid: return False pixel = image.getpixel(pos) lin, col = pos if not pixel or seen[lin, col]: return False # White pixel detected. queue.append(pos) seen[lin, col] = True return True area += add_pos(node) moves = [(0, 1), (0, -1), (1, 0), (-1, 0)] while queue: node = queue.pop() for move in moves: adj = tuple(map(sum, zip(node, move))) area += add_pos(adj) return area @classmethod def _examine_circles(cls, image, img_area): """Check if we have the usual spot & noise pattern.""" areas = [] width, height = image.size # Generate the visiting matrix. seen = numpy.zeros((width, height)) # Take each white not visited pixel and identify spot from it. for xpix in range(width): for ypix in range(height): pixel = image.getpixel((xpix, ypix)) if not pixel or seen[xpix, ypix]: continue # We've got a non-visited white pixel. area = cls._flood_fill(image, (xpix, ypix), seen) areas.append(area) if not areas: # No spots detected. return False # Now compare all the areas in order to check the pattern. main_area = max(areas) areas.remove(main_area) noise = True # rest of the spots are just noise for area in areas: ratio = float(area) / main_area if ratio > settings.SPOT_NOISE_RATIO: # Not noise anymore. noise = False break # If we remain with the `noise`, then we have a recognized pattern. # Also check if the spot isn't too tiny. ratio = float(main_area) / img_area return noise and ratio > settings.SPOT_MIN_RATIO def _add_image(self, image, delta, last_thread): """Add or discard new capture for analysing.""" # Convert to black & white, then apply blur. image = image.convert(mode=self.BW_MODE).filter(ImageFilter.BLUR) # Convert to monochrome. mono_func = lambda pixel: pixel > self.MONO_THRESHOLD and 255 image = image.point(mono_func, mode=self.MONO_MODE) # Get image area and try to crop the extra space. img_area = operator.mul(*image.size) if settings.BOUNDING_BOX: # Crop unnecessary void around the light object. box = image.getbbox() if box: # Check if the new area isn't too small comparing to the # original. box_area = operator.mul( *map(lambda pair: abs(box[pair[0]] - box[pair[1]]), [(0, 2), (1, 3)]) ) if float(box_area) / img_area > settings.BOX_MIN_RATIO: image = image.crop(box=box) # Decide if there's light or dark. hist = image.histogram() blacks = hist[0] if blacks: light_dark = float(hist[-1]) / blacks signal = light_dark > self.LIGHT_DARK_RATIO if not signal and light_dark: signal = self._examine_circles(image, img_area) else: signal = True item = (signal, delta * settings.SECOND) if last_thread: last_thread.join() with self._translate_lock: # isn't necessary, but paranoia reasons self._translator, letters = self._translate.send(item) if letters: self._letters_queue.put(letters) self._letters_queue.task_done() def add_image(self, *args, **kwargs): """Threaded scaffold for adding images into processing.""" kwargs["last_thread"] = self._last_thread thread = threading.Thread( target=self._add_image, args=args, kwargs=kwargs ) thread.start() self._last_thread = thread def get_letters(self): """Retrieve all present letters in the queue as as string.""" all_letters = [] while not self._letters_queue.empty(): letters = self._letters_queue.get() all_letters.extend(letters) return "".join(all_letters) def get_learnt_metrics(self): """Returns learnt translator `unit` and `config`.""" trans = self._translator return trans.unit, trans.config def close(self): """Close the translator and free resources.""" # Wait for the last started thread to finish (and all before it). if self._last_thread: self._last_thread.join() self._translator.wait() self._translator.close() class Encoder(object): """Encode text into Morse signals.""" def __init__(self, text, signal_func, stop_event, decoder, debug, adaptive): """Instantiate `Encoder` object with the mandatory arguments below. :param str text: text to be translated :param signal_func: function that is called for each new state of the signal display :param stop_event: threading event which signals when to stop the processing & interpretation :param decoder: Decoder object used to read latest learnt metrics :param bool debug: show debug messages or not :param bool adaptive: "talk" in the same way we "listened" """ self._text = text self._signal_func = signal_func self._stop_event = stop_event self._decoder = decoder # Create translator object for encoding text into Morse code quanta. self._translator = libmorse.AlphabetTranslator( use_logging=LOGGING.USE, debug=debug) # Use learnt unit and ratios instead of the default hardcoded ones. if adaptive: unit, config = decoder.get_learnt_metrics() if unit: # Use it when we have a learnt `unit` only. self._translator.unit = unit # We're having ratios no matter what, because we start with a # predefined standard set (which should be followed by any # sender as closest as it can). self._translator.update_ratios(config) def start(self): """Starts the whole process as a blocking call until finish or stopped. """ # Send and process all characters at once. items = list(self._text.upper()) for item in items: self._translator.put(item) _, result = libmorse.get_translator_results( self._translator, force_wait=True ) self._translator.close() # Now send these resulted signals according to their duration. for state, delta in result: self._signal_func(state) time.sleep(delta / settings.SECOND) if self._stop_event.is_set(): break # Every time we're ending with a silence. self._signal_func(False)
[ "threading.Thread", "libmorse.get_translator_results", "Queue.Queue", "numpy.zeros", "libmorse.AlphabetTranslator", "time.sleep", "threading.Lock", "libmorse.translate_morse", "operator.mul", "collections.deque" ]
[((802, 864), 'libmorse.translate_morse', 'libmorse.translate_morse', ([], {'use_logging': 'LOGGING.USE', 'debug': 'debug'}), '(use_logging=LOGGING.USE, debug=debug)\n', (826, 864), False, 'import libmorse\n'), ((1005, 1021), 'threading.Lock', 'threading.Lock', ([], {}), '()\n', (1019, 1021), False, 'import threading\n'), ((1094, 1101), 'Queue.Queue', 'Queue', ([], {}), '()\n', (1099, 1101), False, 'from Queue import Queue\n'), ((1231, 1250), 'collections.deque', 'collections.deque', ([], {}), '()\n', (1248, 1250), False, 'import collections\n'), ((2283, 2311), 'numpy.zeros', 'numpy.zeros', (['(width, height)'], {}), '((width, height))\n', (2294, 2311), False, 'import numpy\n'), ((3928, 3953), 'operator.mul', 'operator.mul', (['*image.size'], {}), '(*image.size)\n', (3940, 3953), False, 'import operator\n'), ((5419, 5485), 'threading.Thread', 'threading.Thread', ([], {'target': 'self._add_image', 'args': 'args', 'kwargs': 'kwargs'}), '(target=self._add_image, args=args, kwargs=kwargs)\n', (5435, 5485), False, 'import threading\n'), ((7294, 7359), 'libmorse.AlphabetTranslator', 'libmorse.AlphabetTranslator', ([], {'use_logging': 'LOGGING.USE', 'debug': 'debug'}), '(use_logging=LOGGING.USE, debug=debug)\n', (7321, 7359), False, 'import libmorse\n'), ((8192, 8258), 'libmorse.get_translator_results', 'libmorse.get_translator_results', (['self._translator'], {'force_wait': '(True)'}), '(self._translator, force_wait=True)\n', (8223, 8258), False, 'import libmorse\n'), ((8471, 8506), 'time.sleep', 'time.sleep', (['(delta / settings.SECOND)'], {}), '(delta / settings.SECOND)\n', (8481, 8506), False, 'import time\n')]
# ********************************************************************************************************************** # # brief: Mask R-CNN # Configurations and data loading code for the sun rgbd dataset. # # author: <NAME> # date: 19.04.2020 # # ********************************************************************************************************************** import os import sys import math import random import numpy as np import cv2 import skimage.draw import skimage.io # Root directory of the project ROOT_DIR = os.path.abspath("../../") # Import Mask RCNN sys.path.append(ROOT_DIR) # To find local version of the library from mrcnn.config import Config from mrcnn import utils class SunRGBConfig(Config): """Configuration for training on the sun rgbd dataset. Derives from the base Config class and overrides values specific to the sun rgbd dataset. """ # Give the configuration a recognizable name NAME = "sunrgb" # Train on 1 GPU and 8 images per GPU. We can put multiple images on each # GPU because the images are small. Batch size is 8 (GPUs * images/GPU). GPU_COUNT = 1 IMAGES_PER_GPU = 1 # Number of classes (including background) NUM_CLASSES = 1 + 13 # background + 13 classes # Use small images for faster training. Set the limits of the small side # the large side, and that determines the image shape. IMAGE_MIN_DIM = 512 IMAGE_MAX_DIM = 512 # smaller anchors, since images are 512x512 RPN_ANCHOR_SCALES = (16, 32, 64, 128, 256) # Reduce training ROIs per image because the images are small and have # few objects. Aim to allow ROI sampling to pick 33% positive ROIs. TRAIN_ROIS_PER_IMAGE = 50 # Use a small epoch since the data is simple STEPS_PER_EPOCH = 500 # use small validation steps since the epoch is small # VALIDATION_STEPS = 5 # Skip detections with < 90% confidence # DETECTION_MIN_CONFIDENCE = 0.9 class SunRGBDataset(utils.Dataset): """Generates the sun rgbd dataset. Only uses the RGB Images """ def load_sun_rgb(self, dataset_dir, subset): """Load a subset of the sun rgbd dataset. Only use the rgb images dataset_dir: Root directory of the dataset. subset: Subset to load: train or val """ # Add classes. We have only one class to add. self.add_class("sunrgb", 1, "bed") self.add_class("sunrgb", 2, "books") self.add_class("sunrgb", 3, "ceiling") self.add_class("sunrgb", 4, "chair") self.add_class("sunrgb", 5, "floor") self.add_class("sunrgb", 6, "furniture") self.add_class("sunrgb", 7, "objects") self.add_class("sunrgb", 8, "picture") self.add_class("sunrgb", 9, "sofa") self.add_class("sunrgb", 10, "table") self.add_class("sunrgb", 11, "tv") self.add_class("sunrgb", 12, "wall") self.add_class("sunrgb", 13, "window") # Train or validation dataset? assert subset in ["train13", "test13", "split/test13", "split/val13"] dataset_file = os.path.join(dataset_dir, subset + ".txt") # Load annotations f = open(dataset_file, "r") annotations = list(f) f.close() # Add images for a in annotations: files = a.split(" ") rgb_image = files[0] lbl_image = files[2] rgb_image_path = os.path.join(dataset_dir, rgb_image) lbl_image_path = os.path.join(dataset_dir, lbl_image) rgb_image_path = rgb_image_path.strip() lbl_image_path = lbl_image_path.strip() msk_full_path = lbl_image_path + ".mask.npy" cls_full_path = lbl_image_path + ".class_ids.npy" self.add_image( "sunrgb", image_id=rgb_image, # use file name as a unique image id path=rgb_image_path, lbl_image_path=lbl_image_path, msk_full_path=msk_full_path, cls_full_path=cls_full_path, #rgb_image=self.open_image(rgb_image_path), #masks=self.open_mask(msk_full_path), #class_ids=self.open_class_ids(cls_full_path) ) def image_reference(self, image_id): """Return the path of the image.""" info = self.image_info[image_id] if info["source"] == "sunrgb": return info["path"] else: super(self.__class__, self).image_reference(image_id) def open_mask(self, path): return np.load(path) def open_class_ids(self, path): return np.load(path) def load_mask(self, image_id): """Generate instance masks for an image. Returns: masks: A bool array of shape [height, width, instance count] with one mask per instance. class_ids: a 1D array of class IDs of the instance masks. """ # If not a sun dataset image, delegate to parent class. image_info = self.image_info[image_id] if image_info["source"] != "sunrgb": return super(self.__class__, self).load_mask(image_id) #return self.image_info[image_id]['masks'], self.image_info[image_id]['class_ids'] return self.open_mask(self.image_info[image_id]['msk_full_path']), self.open_class_ids(self.image_info[image_id]['cls_full_path']) def open_image(self, image_path): # Load image image = skimage.io.imread(image_path) return image def load_image(self, image_id): """access in memory image """ # If not a sun dataset image, delegate to parent class. image_info = self.image_info[image_id] if image_info["source"] != "sunrgb": return super(self.__class__, self).load_mask(image_id) return self.open_image(self.image_info[image_id]['path']) #return self.image_info[image_id]['rgb_image']
[ "sys.path.append", "os.path.abspath", "os.path.join", "numpy.load" ]
[((548, 573), 'os.path.abspath', 'os.path.abspath', (['"""../../"""'], {}), "('../../')\n", (563, 573), False, 'import os\n'), ((594, 619), 'sys.path.append', 'sys.path.append', (['ROOT_DIR'], {}), '(ROOT_DIR)\n', (609, 619), False, 'import sys\n'), ((3123, 3165), 'os.path.join', 'os.path.join', (['dataset_dir', "(subset + '.txt')"], {}), "(dataset_dir, subset + '.txt')\n", (3135, 3165), False, 'import os\n'), ((4603, 4616), 'numpy.load', 'np.load', (['path'], {}), '(path)\n', (4610, 4616), True, 'import numpy as np\n'), ((4669, 4682), 'numpy.load', 'np.load', (['path'], {}), '(path)\n', (4676, 4682), True, 'import numpy as np\n'), ((3459, 3495), 'os.path.join', 'os.path.join', (['dataset_dir', 'rgb_image'], {}), '(dataset_dir, rgb_image)\n', (3471, 3495), False, 'import os\n'), ((3525, 3561), 'os.path.join', 'os.path.join', (['dataset_dir', 'lbl_image'], {}), '(dataset_dir, lbl_image)\n', (3537, 3561), False, 'import os\n')]
# -*- mode: python; coding: utf-8 -*- # Copyright 2016-2017 <NAME> <<EMAIL>> and collaborators # Licensed under the MIT License """Various helpers for X-ray analysis that rely on CIAO tools. """ from __future__ import absolute_import, division, print_function, unicode_literals __all__ = str(''' get_region_area count_events compute_bgband simple_srcflux ''').split () def get_region_area (env, evtpath, region): with env.slurp (argv=['dmlist', '%s[sky=%s]' % (evtpath, region), 'subspace'], linebreak=True) as s: for etype, payload in s: if etype != 'stdout': continue if b'Region area' not in payload: continue return float (payload.split ()[-1]) raise Exception ('parsing of dmlist output failed') def count_events (env, evtpath, filter): """TODO: this can probably be replaced with simply reading the file ourselves! """ with env.slurp (argv=['dmstat', '%s%s[cols energy]' % (evtpath, filter)], linebreak=True) as s: for etype, payload in s: if etype != 'stdout': continue if b'good:' not in payload: continue return int (payload.split ()[-1]) raise Exception ('parsing of dmlist output failed') def compute_bgband (evtpath, srcreg, bkgreg, ebins, env=None): """Compute background information for a source in one or more energy bands. evtpath Path to a CIAO events file srcreg String specifying the source region to consider; use 'region(path.reg)' if you have the region saved in a file. bkgreg String specifying the background region to consider; same format as srcreg ebins Iterable of 2-tuples giving low and high bounds of the energy bins to consider, measured in eV. env An optional CiaoEnvironment instance; default settings are used if unspecified. Returns a DataFrame containing at least the following columns: elo The low bound of this energy bin, in eV. ehi The high bound of this energy bin, in eV. ewidth The width of the bin in eV; simply `abs(ehi - elo)`. nsrc The number of events within the specified source region and energy range. nbkg The number of events within the specified background region and energy range. nbkg_scaled The number of background events scaled to the source area; not an integer. nsrc_subbed The estimated number of non-background events in the source region; simply `nsrc - nbkg_scaled`. log_prob_bkg The logarithm of the probability that all counts in the source region are due to background events. src_sigma The confidence of source detection in sigma inferred from log_prob_bkg. The probability of backgrounditude is computed as: b^s * exp (-b) / s! where `b` is `nbkg_scaled` and `s` is `nsrc`. The confidence of source detection is computed as: sqrt(2) * erfcinv (prob_bkg) where `erfcinv` is the inverse complementary error function. """ import numpy as np import pandas as pd from scipy.special import erfcinv, gammaln if env is None: from . import CiaoEnvironment env = CiaoEnvironment () srcarea = get_region_area (env, evtpath, srcreg) bkgarea = get_region_area (env, evtpath, bkgreg) srccounts = [count_events (env, evtpath, '[sky=%s][energy=%d:%d]' % (srcreg, elo, ehi)) for elo, ehi in ebins] bkgcounts = [count_events (env, evtpath, '[sky=%s][energy=%d:%d]' % (bkgreg, elo, ehi)) for elo, ehi in ebins] df = pd.DataFrame ({ 'elo': [t[0] for t in ebins], 'ehi': [t[1] for t in ebins], 'nsrc': srccounts, 'nbkg': bkgcounts }) df['ewidth'] = np.abs (df['ehi'] - df['elo']) df['nbkg_scaled'] = df['nbkg'] * srcarea / bkgarea df['log_prob_bkg'] = df['nsrc'] * np.log (df['nbkg_scaled']) - df['nbkg_scaled'] - gammaln (df['nsrc'] + 1) df['src_sigma'] = np.sqrt (2) * erfcinv (np.exp (df['log_prob_bkg'])) df['nsrc_subbed'] = df['nsrc'] - df['nbkg_scaled'] return df def _rmtree_error (func, path, excinfo): from ...cli import warn warn ('couldn\'t delete temporary file %s: %s (%s)', path, excinfo[0], func) def simple_srcflux(env, infile=None, psfmethod='arfcorr', conf=0.68, verbose=0, **kwargs): """Run the CIAO "srcflux" script and retrieve its results. *infile* The input events file; must be specified. The computation is done in a temporary directory, so this path — and all others passed in as arguments — **must be made absolute**. *psfmethod* = "arfcorr" The PSF modeling method to be used; see the "srcflux" documentation. *conf* = 0.68 The confidence limit to detect. We default to 1 sigma, instead of the 90% mark, which is the srcflux default. *verbose* = 0 The level of verbosity to be used by the tool. *kwargs* Remaining keyword arguments are passed to the tool as command-line keyword arguments, with values stringified. Returns: A :class:`pandas.DataFrame` extracted from the results table generated by the tool. There is one row for each source analyzed; in common usage, this means that there will be one row. """ from ...io import Path import shutil, signal, tempfile if infile is None: raise ValueError('must specify infile') kwargs.update(dict( infile = infile, psfmethod = psfmethod, conf = conf, verbose = verbose, clobber = 'yes', outroot = 'sf', )) argv = ['srcflux'] + ['%s=%s' % t for t in kwargs.items()] argstr = ' '.join(argv) tempdir = None try: tempdir = tempfile.mkdtemp(prefix='srcflux') proc = env.launch(argv, cwd=tempdir, shell=False) retcode = proc.wait() if retcode > 0: raise RuntimeError('command "%s" failed with exit code %d' % (argstr, retcode)) elif retcode == -signal.SIGINT: raise KeyboardInterrupt() elif retcode < 0: raise RuntimeError('command "%s" killed by signal %d' % (argstr, -retcode)) tables = list(Path(tempdir).glob('*.flux')) if len(tables) != 1: raise RuntimeError('expected exactly one flux table from srcflux; got %d' % len(tables)) return tables[0].read_fits_bintable(hdu=1) finally: if tempdir is not None: shutil.rmtree(tempdir, onerror=_rmtree_error)
[ "pandas.DataFrame", "numpy.abs", "numpy.log", "tempfile.mkdtemp", "numpy.exp", "scipy.special.gammaln", "shutil.rmtree", "numpy.sqrt" ]
[((3667, 3783), 'pandas.DataFrame', 'pd.DataFrame', (["{'elo': [t[0] for t in ebins], 'ehi': [t[1] for t in ebins], 'nsrc':\n srccounts, 'nbkg': bkgcounts}"], {}), "({'elo': [t[0] for t in ebins], 'ehi': [t[1] for t in ebins],\n 'nsrc': srccounts, 'nbkg': bkgcounts})\n", (3679, 3783), True, 'import pandas as pd\n'), ((3839, 3868), 'numpy.abs', 'np.abs', (["(df['ehi'] - df['elo'])"], {}), "(df['ehi'] - df['elo'])\n", (3845, 3868), True, 'import numpy as np\n'), ((4012, 4035), 'scipy.special.gammaln', 'gammaln', (["(df['nsrc'] + 1)"], {}), "(df['nsrc'] + 1)\n", (4019, 4035), False, 'from scipy.special import erfcinv, gammaln\n'), ((4059, 4069), 'numpy.sqrt', 'np.sqrt', (['(2)'], {}), '(2)\n', (4066, 4069), True, 'import numpy as np\n'), ((5844, 5878), 'tempfile.mkdtemp', 'tempfile.mkdtemp', ([], {'prefix': '"""srcflux"""'}), "(prefix='srcflux')\n", (5860, 5878), False, 'import shutil, signal, tempfile\n'), ((4082, 4108), 'numpy.exp', 'np.exp', (["df['log_prob_bkg']"], {}), "(df['log_prob_bkg'])\n", (4088, 4108), True, 'import numpy as np\n'), ((6569, 6614), 'shutil.rmtree', 'shutil.rmtree', (['tempdir'], {'onerror': '_rmtree_error'}), '(tempdir, onerror=_rmtree_error)\n', (6582, 6614), False, 'import shutil, signal, tempfile\n'), ((3963, 3988), 'numpy.log', 'np.log', (["df['nbkg_scaled']"], {}), "(df['nbkg_scaled'])\n", (3969, 3988), True, 'import numpy as np\n')]
import numpy as np import matplotlib.pyplot as plt np.random.seed(19680801) n_bins = 10 x = np.random.randn(1000, 3) print(x.shape) fig, ((ax0, ax1), (ax2, ax3)) = plt.subplots(nrows=2, ncols=2) colors = ['red', 'tan', 'lime'] ax0.hist(x, n_bins, density=True, histtype='bar', color=colors, label=colors) ax0.legend(prop={'size': 10}) ax0.set_title('bars with legend') ax1.hist(x, n_bins, density=True, histtype='bar', stacked=True) ax1.set_title('stacked bar') ax2.hist(x, n_bins, histtype='step', stacked=True, fill=False) ax2.set_title('stack step (unfilled)') # Make a multiple-histogram of data-sets with different length. x_multi = [np.random.randn(n) for n in [10000, 5000, 2000]] ax3.hist(x_multi, n_bins, histtype='bar') ax3.set_title('different sample sizes') fig.tight_layout() plt.show()
[ "matplotlib.pyplot.show", "numpy.random.seed", "matplotlib.pyplot.subplots", "numpy.random.randn" ]
[((52, 76), 'numpy.random.seed', 'np.random.seed', (['(19680801)'], {}), '(19680801)\n', (66, 76), True, 'import numpy as np\n'), ((94, 118), 'numpy.random.randn', 'np.random.randn', (['(1000)', '(3)'], {}), '(1000, 3)\n', (109, 118), True, 'import numpy as np\n'), ((166, 196), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {'nrows': '(2)', 'ncols': '(2)'}), '(nrows=2, ncols=2)\n', (178, 196), True, 'import matplotlib.pyplot as plt\n'), ((796, 806), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (804, 806), True, 'import matplotlib.pyplot as plt\n'), ((645, 663), 'numpy.random.randn', 'np.random.randn', (['n'], {}), '(n)\n', (660, 663), True, 'import numpy as np\n')]
# Python modules # 3rd party modules import numpy as np # Our modules def op_rmbadaverages( data, sw, nsd='3', domain='t'): """ USAGE: badAverages, metric = op_rmbadaverages(data, sw, nsd=nsd, domain=domain) DESCRIPTION: Removes motion corrupted averages from a dataset containing multiple averages. Bad averages are identified by calculating a 'likeness' metric for each average by subtracting each average from the median average, and then calculating the summed square of real part of the difference. Likeness metrics greater than 'nsd' above the mean are discarded. Inputs: data (ndarray, complex): shape=(navg,npts) complex k-space data sw (float): sweep width in Hz nsd (float): def=3.0, number of standard deviations to use a rejection threshold domain (string): def='t', domain ('t' or 'f') in which to perform calculations Outputs: badAverages (list, int): list of indices indicating the averages that were 'bad' in this data array. Can be empty. metric (list, float): list of unlikeness metrics corresponding to all input averages. Derived from FID-A project: module - op_rmbadaverages.m <NAME>, McGill University 2014. """ nfid, npts = data.shape raw = data.copy() t = np.arange(npts) / sw x = np.arange(nfid) if nfid == 1: raise ValueError('ERROR: Averaging has already been performed! Aborting!') # algorithm can be applied to Frequency or Time domain data if domain in ['t', 'T']: tmax = 0.4 # from fida_run_pressproc_auto.m trange = np.logical_and(t >= 0, t <= tmax) elif domain in ['f', 'F']: raw *= np.exp(-(t * np.pi * 10.0)) # 10 Hz lorentz - from fida_run_pressproc_auto.m raw = np.fft.fftshift(np.fft.ifft(raw, axis=1), axes=1) inmed = np.squeeze(np.median(raw.real, axis=0) + 1j*np.median(raw.imag, axis=0)) # calculate median if domain == 't' or domain == 'T': metric = np.sum((raw[:,trange].real - inmed[trange].real)**2, axis=1) elif domain=='f' or domain=='F': metric = np.sum((raw.real - inmed.real) ** 2, axis=1) # z-transform the metric so it's centered about zero, with stdev of 1.0 zmetric = (metric-np.mean(metric))/np.std(metric) pfit = np.polyfit(x, zmetric, 2) pval = np.polyval(pfit,x) # mask FIDs with metrics > nsd standard deviations from the mean metric value mask = zmetric > pval+nsd badAverages = np.array(x[mask], dtype=np.int) # these are the corrupted indices return badAverages, metric
[ "numpy.fft.ifft", "numpy.sum", "numpy.logical_and", "numpy.polyfit", "numpy.polyval", "numpy.std", "numpy.median", "numpy.mean", "numpy.arange", "numpy.array", "numpy.exp" ]
[((1365, 1380), 'numpy.arange', 'np.arange', (['nfid'], {}), '(nfid)\n', (1374, 1380), True, 'import numpy as np\n'), ((2392, 2417), 'numpy.polyfit', 'np.polyfit', (['x', 'zmetric', '(2)'], {}), '(x, zmetric, 2)\n', (2402, 2417), True, 'import numpy as np\n'), ((2429, 2448), 'numpy.polyval', 'np.polyval', (['pfit', 'x'], {}), '(pfit, x)\n', (2439, 2448), True, 'import numpy as np\n'), ((2584, 2615), 'numpy.array', 'np.array', (['x[mask]'], {'dtype': 'np.int'}), '(x[mask], dtype=np.int)\n', (2592, 2615), True, 'import numpy as np\n'), ((1336, 1351), 'numpy.arange', 'np.arange', (['npts'], {}), '(npts)\n', (1345, 1351), True, 'import numpy as np\n'), ((1689, 1722), 'numpy.logical_and', 'np.logical_and', (['(t >= 0)', '(t <= tmax)'], {}), '(t >= 0, t <= tmax)\n', (1703, 1722), True, 'import numpy as np\n'), ((2089, 2152), 'numpy.sum', 'np.sum', (['((raw[:, trange].real - inmed[trange].real) ** 2)'], {'axis': '(1)'}), '((raw[:, trange].real - inmed[trange].real) ** 2, axis=1)\n', (2095, 2152), True, 'import numpy as np\n'), ((2366, 2380), 'numpy.std', 'np.std', (['metric'], {}), '(metric)\n', (2372, 2380), True, 'import numpy as np\n'), ((1769, 1796), 'numpy.exp', 'np.exp', (['(-(t * np.pi * 10.0))'], {}), '(-(t * np.pi * 10.0))\n', (1775, 1796), True, 'import numpy as np\n'), ((1950, 1977), 'numpy.median', 'np.median', (['raw.real'], {'axis': '(0)'}), '(raw.real, axis=0)\n', (1959, 1977), True, 'import numpy as np\n'), ((2204, 2248), 'numpy.sum', 'np.sum', (['((raw.real - inmed.real) ** 2)'], {'axis': '(1)'}), '((raw.real - inmed.real) ** 2, axis=1)\n', (2210, 2248), True, 'import numpy as np\n'), ((2349, 2364), 'numpy.mean', 'np.mean', (['metric'], {}), '(metric)\n', (2356, 2364), True, 'import numpy as np\n'), ((1892, 1916), 'numpy.fft.ifft', 'np.fft.ifft', (['raw'], {'axis': '(1)'}), '(raw, axis=1)\n', (1903, 1916), True, 'import numpy as np\n'), ((1983, 2010), 'numpy.median', 'np.median', (['raw.imag'], {'axis': '(0)'}), '(raw.imag, axis=0)\n', (1992, 2010), True, 'import numpy as np\n')]
""" This file contains functions for plotting the performance of the model for censored data. """ import numpy as np import pandas as pd import seaborn as sns from copy import deepcopy import random from .figureCommon import ( getSetup, subplotLabel, commonAnalyze, pi, T, E2, num_data_points, min_num_lineages, max_num_lineages, ) from ..LineageTree import LineageTree from ..plotTree import plotLineage scatter_state_1_kws = { "alpha": 0.33, "marker": "+", "s": 20, } def regGen(num): random.seed(0) tmp = LineageTree.init_from_parameters(pi, T, E2, desired_num_cells=num) while len(tmp.output_lineage) < 5: tmp = LineageTree.init_from_parameters(pi, T, E2, desired_num_cells=num) return tmp def cenGen(num): random.seed(0) tmp = LineageTree.init_from_parameters(pi, T, E2, desired_num_cells=num, censor_condition=3, desired_experiment_time=250) while len(tmp.output_lineage) < 5: tmp = LineageTree.init_from_parameters(pi, T, E2, desired_num_cells=num, censor_condition=3, desired_experiment_time=250) return tmp def makeFigure(): """ Makes fig 4. """ x_Sim, output_Sim, x_Cen, output_Cen = accuracy() # Get list of axis objects ax, f = getSetup((9, 6), (2, 2)) figureMaker3(ax, x_Sim, output_Sim, x_Cen, output_Cen) subplotLabel(ax) return f def accuracy(): """ Calculates accuracy and parameter estimation over an increasing number of cells in a lineage for a uncensored two-state model. We increase the desired number of cells in a lineage by the experiment time. """ # Creating a list of populations to analyze over num_lineages = np.linspace(min_num_lineages, max_num_lineages, num_data_points, dtype=int) num_cells = np.linspace(5, 31, num_data_points, dtype=int) list_of_fpi = [pi] * num_lineages.size # Adding populations into a holder for analysing list_of_populationsSim = [[cenGen(num_cells[i]) for _ in range(num)] for i, num in enumerate(num_lineages)] SecondPopulation = deepcopy(list_of_populationsSim) for lin_list in SecondPopulation: for lins in lin_list: for cells in lins.output_lineage: if cells.obs[4] == 0.0: cells.obs[4] = 1.0 assert np.isfinite(cells.obs[2]) if cells.obs[5] == 0.0: cells.obs[5] = 1.0 assert np.isfinite(cells.obs[3]) x_Sim, _, output_Sim, _ = commonAnalyze(SecondPopulation, 2, list_of_fpi=list_of_fpi) x_Cen, _, output_Cen, _ = commonAnalyze(list_of_populationsSim, 2, list_of_fpi=list_of_fpi) return x_Sim, output_Sim, x_Cen, output_Cen def figureMaker3(ax, x_Sim, output_Sim, x_Cen, output_Cen, xlabel="Number of Cells"): """ Makes a 2 panel figures displaying state accuracy estimation across lineages of different censoring states. """ Accuracy_Sim = output_Sim["balanced_accuracy_score"] Accuracy_Cen = output_Cen["balanced_accuracy_score"] accuracy_sim_df = pd.DataFrame(columns=["Cell number", "State Assignment Accuracy"]) accuracy_sim_df["Cell number"] = x_Sim accuracy_sim_df["State Assignment Accuracy"] = Accuracy_Sim accuracy_cen_df = pd.DataFrame(columns=["Cell number", "State Assignment Accuracy"]) accuracy_cen_df["Cell number"] = x_Cen accuracy_cen_df["State Assignment Accuracy"] = Accuracy_Cen i = 0 plotLineage(regGen(45), axes=ax[i], censore=False) ax[i].axis('off') i += 1 plotLineage(cenGen(45), axes=ax[i], censore=True) ax[i].axis('off') i += 1 ax[i].axhline(y=100, ls='--', c='k', alpha=0.5) sns.regplot(x="Cell number", y="State Assignment Accuracy", data=accuracy_sim_df, ax=ax[i], lowess=True, marker='+', scatter_kws=scatter_state_1_kws) ax[i].set_xlabel(xlabel) ax[i].set_ylim(bottom=0, top=101) ax[i].set_ylabel(r"State Accuracy [%]") ax[i].set_title("Censored data, uncensored model") i += 1 ax[i].axhline(y=100, ls='--', c='k', alpha=0.5) sns.regplot(x="Cell number", y="State Assignment Accuracy", data=accuracy_cen_df, ax=ax[i], lowess=True, marker='+', scatter_kws=scatter_state_1_kws) ax[i].set_xlabel(xlabel) ax[i].set_ylim(bottom=0, top=101) ax[i].set_ylabel(r"State Accuracy [%]") ax[i].set_title("Censored data, censored model")
[ "pandas.DataFrame", "copy.deepcopy", "numpy.isfinite", "seaborn.regplot", "random.seed", "numpy.linspace" ]
[((543, 557), 'random.seed', 'random.seed', (['(0)'], {}), '(0)\n', (554, 557), False, 'import random\n'), ((793, 807), 'random.seed', 'random.seed', (['(0)'], {}), '(0)\n', (804, 807), False, 'import random\n'), ((1719, 1794), 'numpy.linspace', 'np.linspace', (['min_num_lineages', 'max_num_lineages', 'num_data_points'], {'dtype': 'int'}), '(min_num_lineages, max_num_lineages, num_data_points, dtype=int)\n', (1730, 1794), True, 'import numpy as np\n'), ((1811, 1857), 'numpy.linspace', 'np.linspace', (['(5)', '(31)', 'num_data_points'], {'dtype': 'int'}), '(5, 31, num_data_points, dtype=int)\n', (1822, 1857), True, 'import numpy as np\n'), ((2091, 2123), 'copy.deepcopy', 'deepcopy', (['list_of_populationsSim'], {}), '(list_of_populationsSim)\n', (2099, 2123), False, 'from copy import deepcopy\n'), ((3093, 3159), 'pandas.DataFrame', 'pd.DataFrame', ([], {'columns': "['Cell number', 'State Assignment Accuracy']"}), "(columns=['Cell number', 'State Assignment Accuracy'])\n", (3105, 3159), True, 'import pandas as pd\n'), ((3290, 3356), 'pandas.DataFrame', 'pd.DataFrame', ([], {'columns': "['Cell number', 'State Assignment Accuracy']"}), "(columns=['Cell number', 'State Assignment Accuracy'])\n", (3302, 3356), True, 'import pandas as pd\n'), ((3708, 3867), 'seaborn.regplot', 'sns.regplot', ([], {'x': '"""Cell number"""', 'y': '"""State Assignment Accuracy"""', 'data': 'accuracy_sim_df', 'ax': 'ax[i]', 'lowess': '(True)', 'marker': '"""+"""', 'scatter_kws': 'scatter_state_1_kws'}), "(x='Cell number', y='State Assignment Accuracy', data=\n accuracy_sim_df, ax=ax[i], lowess=True, marker='+', scatter_kws=\n scatter_state_1_kws)\n", (3719, 3867), True, 'import seaborn as sns\n'), ((4092, 4251), 'seaborn.regplot', 'sns.regplot', ([], {'x': '"""Cell number"""', 'y': '"""State Assignment Accuracy"""', 'data': 'accuracy_cen_df', 'ax': 'ax[i]', 'lowess': '(True)', 'marker': '"""+"""', 'scatter_kws': 'scatter_state_1_kws'}), "(x='Cell number', y='State Assignment Accuracy', data=\n accuracy_cen_df, ax=ax[i], lowess=True, marker='+', scatter_kws=\n scatter_state_1_kws)\n", (4103, 4251), True, 'import seaborn as sns\n'), ((2344, 2369), 'numpy.isfinite', 'np.isfinite', (['cells.obs[2]'], {}), '(cells.obs[2])\n', (2355, 2369), True, 'import numpy as np\n'), ((2476, 2501), 'numpy.isfinite', 'np.isfinite', (['cells.obs[3]'], {}), '(cells.obs[3])\n', (2487, 2501), True, 'import numpy as np\n')]
__author__ = 'tsungyi' #modified by y2863 on December 20th 2021 import numpy as np import datetime import time from collections import defaultdict import pycocotools.mask as maskUtils from pycocotools.cocoeval import COCOeval, Params import copy class MetaGraspeval(COCOeval): def __init__(self, *args, **kwargs): super(MetaGraspeval, self).__init__(*args, **kwargs) self.ignore_layers = [3] def evaluateImg(self, imgId, catId, aRng, maxDet): ignore_layers = self.ignore_layers ''' perform evaluation for single category and image :return: dict (single image results) ''' p = self.params if p.useCats: gt = self._gts[imgId,catId] dt = self._dts[imgId,catId] else: gt = [_ for cId in p.catIds for _ in self._gts[imgId,cId]] dt = [_ for cId in p.catIds for _ in self._dts[imgId,cId]] if len(gt) == 0 and len(dt) ==0: return None for g in gt: if g['ignore'] or (g['area']<aRng[0] or g['area']>aRng[1]) or (g['layer'] in ignore_layers): g['_ignore'] = 1 else: g['_ignore'] = 0 # sort dt highest score first, sort gt ignore last gtind = np.argsort([g['_ignore'] for g in gt], kind='mergesort') gt = [gt[i] for i in gtind] dtind = np.argsort([-d['score'] for d in dt], kind='mergesort') dt = [dt[i] for i in dtind[0:maxDet]] iscrowd = [int(o['iscrowd']) for o in gt] # load computed ious ious = self.ious[imgId, catId][:, gtind] if len(self.ious[imgId, catId]) > 0 else self.ious[imgId, catId] T = len(p.iouThrs) G = len(gt) D = len(dt) gtm = np.zeros((T,G)) dtm = np.zeros((T,D)) dt_oc = np.zeros((T,D), dtype=np.float) dt_layer = np.zeros((T,D)) gtIg = np.array([g['_ignore'] for g in gt]) dtIg = np.zeros((T,D)) if not len(ious)==0: for tind, t in enumerate(p.iouThrs): for dind, d in enumerate(dt): # information about best match so far (m=-1 -> unmatched) iou = min([t,1-1e-10]) m = -1 for gind, g in enumerate(gt): # if this gt already matched, and not a crowd, continue if gtm[tind,gind]>0 and not iscrowd[gind]: continue # if dt matched to reg gt, and on ignore gt, stop if m>-1 and gtIg[m]==0 and gtIg[gind]==1: break # continue to next gt unless better match made if ious[dind,gind] < iou: continue # if match successful and best so far, store appropriately iou=ious[dind,gind] m=gind # if match made store id of match for both dt and gt if m ==-1: continue dtIg[tind,dind] = gtIg[m] dtm[tind,dind] = gt[m]['id'] dt_oc[tind,dind] = gt[m]['occlusion'] dt_layer[tind, dind] = gt[m]['layer'] gtm[tind,m] = d['id'] # set unmatched detections outside of area range to ignore a = np.array([d['area']<aRng[0] or d['area']>aRng[1] for d in dt]).reshape((1, len(dt))) dtIg = np.logical_or(dtIg, np.logical_and(dtm==0, np.repeat(a,T,0))) #if len(gt) > 0 and len(dt) > 0: # import pdb # pdb.set_trace() # store results for given image and category return { 'image_id': imgId, 'category_id': catId, 'aRng': aRng, 'maxDet': maxDet, 'dtIds': [d['id'] for d in dt], 'gtIds': [g['id'] for g in gt], 'dtMatches': dtm, 'gtMatches': gtm, 'dtScores': [d['score'] for d in dt], 'gtIgnore': gtIg, 'dtIgnore': dtIg, 'dtOcclusion': dt_oc, 'dtLayer': dt_layer, } def accumulate(self, p = None): ''' Accumulate per image evaluation results and store the result in self.eval :param p: input params for evaluation :return: None ''' print('Accumulating evaluation results...') tic = time.time() if not self.evalImgs: print('Please run evaluate() first') # allows input customized parameters if p is None: p = self.params p.catIds = p.catIds if p.useCats == 1 else [-1] T = len(p.iouThrs) R = len(p.recThrs) K = len(p.catIds) if p.useCats else 1 A = len(p.areaRng) M = len(p.maxDets) precision = -np.ones((T,R,K,A,M)) # -1 for the precision of absent categories recall = -np.ones((T,K,A,M)) scores = -np.ones((T,R,K,A,M)) # create dictionary for future indexing _pe = self._paramsEval catIds = _pe.catIds if _pe.useCats else [-1] setK = set(catIds) setA = set(map(tuple, _pe.areaRng)) setM = set(_pe.maxDets) setI = set(_pe.imgIds) # get inds to evaluate k_list = [n for n, k in enumerate(p.catIds) if k in setK] m_list = [m for n, m in enumerate(p.maxDets) if m in setM] a_list = [n for n, a in enumerate(map(lambda x: tuple(x), p.areaRng)) if a in setA] i_list = [n for n, i in enumerate(p.imgIds) if i in setI] I0 = len(_pe.imgIds) A0 = len(_pe.areaRng) # retrieve E at each category, area range, and max number of detections for k, k0 in enumerate(k_list): Nk = k0*A0*I0 for a, a0 in enumerate(a_list): Na = a0*I0 for m, maxDet in enumerate(m_list): E = [self.evalImgs[Nk + Na + i] for i in i_list] E = [e for e in E if not e is None] if len(E) == 0: continue dtScores = np.concatenate([e['dtScores'][0:maxDet] for e in E]) # different sorting method generates slightly different results. # mergesort is used to be consistent as Matlab implementation. inds = np.argsort(-dtScores, kind='mergesort') dtScoresSorted = dtScores[inds] dtm = np.concatenate([e['dtMatches'][:,0:maxDet] for e in E], axis=1)[:,inds] dt_oc = np.concatenate([e['dtOcclusion'][:,0:maxDet] for e in E], axis=1)[:,inds] dt_layer = np.concatenate([e['dtLayer'][:,0:maxDet] for e in E], axis=1)[:,inds] dtIg = np.concatenate([e['dtIgnore'][:,0:maxDet] for e in E], axis=1)[:,inds] gtIg = np.concatenate([e['gtIgnore'] for e in E]) npig = np.count_nonzero(gtIg==0 ) if npig == 0: continue tps = np.logical_and( dtm, np.logical_not(dtIg) ) fps = np.logical_and(np.logical_not(dtm), np.logical_not(dtIg) ) #weigh each sample based on occlusion tps = np.multiply(tps, 1.-dt_oc) tp_sum = np.cumsum(tps, axis=1).astype(dtype=np.float) fp_sum = np.cumsum(fps, axis=1).astype(dtype=np.float) for t, (tp, fp) in enumerate(zip(tp_sum, fp_sum)): tp = np.array(tp) fp = np.array(fp) nd = len(tp) rc = tp / npig pr = tp / (fp+tp+np.spacing(1)) q = np.zeros((R,)) ss = np.zeros((R,)) if nd: recall[t,k,a,m] = rc[-1] else: recall[t,k,a,m] = 0 # numpy is slow without cython optimization for accessing elements # use python array gets significant speed improvement pr = pr.tolist(); q = q.tolist() for i in range(nd-1, 0, -1): if pr[i] > pr[i-1]: pr[i-1] = pr[i] inds = np.searchsorted(rc, p.recThrs, side='left') try: for ri, pi in enumerate(inds): q[ri] = pr[pi] ss[ri] = dtScoresSorted[pi] except: pass precision[t,:,k,a,m] = np.array(q) scores[t,:,k,a,m] = np.array(ss) self.eval = { 'params': p, 'counts': [T, R, K, A, M], 'date': datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'), 'precision': precision, 'recall': recall, 'scores': scores, } toc = time.time() print('DONE (t={:0.2f}s).'.format( toc-tic)) class MetaGraspevalLayer(MetaGraspeval): def __init__(self, *args, **kwargs): super(MetaGraspevalLayer, self).__init__(*args, **kwargs) def accumulate(self, p = None): COCOeval.accumulate(self, p) class MetaGraspevalTop(MetaGraspevalLayer): def __init__(self, *args, **kwargs): super(MetaGraspevalTop, self).__init__(*args, **kwargs) self.ignore_layers = [1,2,3] class MetaGraspevalSecondary(MetaGraspevalLayer): def __init__(self, *args, **kwargs): super(MetaGraspevalSecondary, self).__init__(*args, **kwargs) self.ignore_layers = [0,3]
[ "numpy.count_nonzero", "numpy.multiply", "numpy.logical_not", "numpy.zeros", "numpy.ones", "numpy.searchsorted", "time.time", "numpy.argsort", "numpy.cumsum", "pycocotools.cocoeval.COCOeval.accumulate", "numpy.spacing", "numpy.array", "datetime.datetime.now", "numpy.concatenate", "numpy.repeat" ]
[((1281, 1337), 'numpy.argsort', 'np.argsort', (["[g['_ignore'] for g in gt]"], {'kind': '"""mergesort"""'}), "([g['_ignore'] for g in gt], kind='mergesort')\n", (1291, 1337), True, 'import numpy as np\n'), ((1390, 1447), 'numpy.argsort', 'np.argsort', (["[(-d['score']) for d in dt]"], {'kind': '"""mergesort"""'}), "([(-d['score']) for d in dt], kind='mergesort')\n", (1400, 1447), True, 'import numpy as np\n'), ((1768, 1784), 'numpy.zeros', 'np.zeros', (['(T, G)'], {}), '((T, G))\n', (1776, 1784), True, 'import numpy as np\n'), ((1799, 1815), 'numpy.zeros', 'np.zeros', (['(T, D)'], {}), '((T, D))\n', (1807, 1815), True, 'import numpy as np\n'), ((1832, 1864), 'numpy.zeros', 'np.zeros', (['(T, D)'], {'dtype': 'np.float'}), '((T, D), dtype=np.float)\n', (1840, 1864), True, 'import numpy as np\n'), ((1883, 1899), 'numpy.zeros', 'np.zeros', (['(T, D)'], {}), '((T, D))\n', (1891, 1899), True, 'import numpy as np\n'), ((1914, 1950), 'numpy.array', 'np.array', (["[g['_ignore'] for g in gt]"], {}), "([g['_ignore'] for g in gt])\n", (1922, 1950), True, 'import numpy as np\n'), ((1966, 1982), 'numpy.zeros', 'np.zeros', (['(T, D)'], {}), '((T, D))\n', (1974, 1982), True, 'import numpy as np\n'), ((4635, 4646), 'time.time', 'time.time', ([], {}), '()\n', (4644, 4646), False, 'import time\n'), ((9417, 9428), 'time.time', 'time.time', ([], {}), '()\n', (9426, 9428), False, 'import time\n'), ((9676, 9704), 'pycocotools.cocoeval.COCOeval.accumulate', 'COCOeval.accumulate', (['self', 'p'], {}), '(self, p)\n', (9695, 9704), False, 'from pycocotools.cocoeval import COCOeval, Params\n'), ((5104, 5128), 'numpy.ones', 'np.ones', (['(T, R, K, A, M)'], {}), '((T, R, K, A, M))\n', (5111, 5128), True, 'import numpy as np\n'), ((5192, 5213), 'numpy.ones', 'np.ones', (['(T, K, A, M)'], {}), '((T, K, A, M))\n', (5199, 5213), True, 'import numpy as np\n'), ((5234, 5258), 'numpy.ones', 'np.ones', (['(T, R, K, A, M)'], {}), '((T, R, K, A, M))\n', (5241, 5258), True, 'import numpy as np\n'), ((3454, 3522), 'numpy.array', 'np.array', (["[(d['area'] < aRng[0] or d['area'] > aRng[1]) for d in dt]"], {}), "([(d['area'] < aRng[0] or d['area'] > aRng[1]) for d in dt])\n", (3462, 3522), True, 'import numpy as np\n'), ((3597, 3615), 'numpy.repeat', 'np.repeat', (['a', 'T', '(0)'], {}), '(a, T, 0)\n', (3606, 3615), True, 'import numpy as np\n'), ((6399, 6451), 'numpy.concatenate', 'np.concatenate', (["[e['dtScores'][0:maxDet] for e in E]"], {}), "([e['dtScores'][0:maxDet] for e in E])\n", (6413, 6451), True, 'import numpy as np\n'), ((6648, 6687), 'numpy.argsort', 'np.argsort', (['(-dtScores)'], {'kind': '"""mergesort"""'}), "(-dtScores, kind='mergesort')\n", (6658, 6687), True, 'import numpy as np\n'), ((7171, 7213), 'numpy.concatenate', 'np.concatenate', (["[e['gtIgnore'] for e in E]"], {}), "([e['gtIgnore'] for e in E])\n", (7185, 7213), True, 'import numpy as np\n'), ((7241, 7268), 'numpy.count_nonzero', 'np.count_nonzero', (['(gtIg == 0)'], {}), '(gtIg == 0)\n', (7257, 7268), True, 'import numpy as np\n'), ((7589, 7618), 'numpy.multiply', 'np.multiply', (['tps', '(1.0 - dt_oc)'], {}), '(tps, 1.0 - dt_oc)\n', (7600, 7618), True, 'import numpy as np\n'), ((9240, 9263), 'datetime.datetime.now', 'datetime.datetime.now', ([], {}), '()\n', (9261, 9263), False, 'import datetime\n'), ((6768, 6832), 'numpy.concatenate', 'np.concatenate', (["[e['dtMatches'][:, 0:maxDet] for e in E]"], {'axis': '(1)'}), "([e['dtMatches'][:, 0:maxDet] for e in E], axis=1)\n", (6782, 6832), True, 'import numpy as np\n'), ((6869, 6935), 'numpy.concatenate', 'np.concatenate', (["[e['dtOcclusion'][:, 0:maxDet] for e in E]"], {'axis': '(1)'}), "([e['dtOcclusion'][:, 0:maxDet] for e in E], axis=1)\n", (6883, 6935), True, 'import numpy as np\n'), ((6975, 7037), 'numpy.concatenate', 'np.concatenate', (["[e['dtLayer'][:, 0:maxDet] for e in E]"], {'axis': '(1)'}), "([e['dtLayer'][:, 0:maxDet] for e in E], axis=1)\n", (6989, 7037), True, 'import numpy as np\n'), ((7072, 7135), 'numpy.concatenate', 'np.concatenate', (["[e['dtIgnore'][:, 0:maxDet] for e in E]"], {'axis': '(1)'}), "([e['dtIgnore'][:, 0:maxDet] for e in E], axis=1)\n", (7086, 7135), True, 'import numpy as np\n'), ((7397, 7417), 'numpy.logical_not', 'np.logical_not', (['dtIg'], {}), '(dtIg)\n', (7411, 7417), True, 'import numpy as np\n'), ((7461, 7480), 'numpy.logical_not', 'np.logical_not', (['dtm'], {}), '(dtm)\n', (7475, 7480), True, 'import numpy as np\n'), ((7482, 7502), 'numpy.logical_not', 'np.logical_not', (['dtIg'], {}), '(dtIg)\n', (7496, 7502), True, 'import numpy as np\n'), ((7867, 7879), 'numpy.array', 'np.array', (['tp'], {}), '(tp)\n', (7875, 7879), True, 'import numpy as np\n'), ((7909, 7921), 'numpy.array', 'np.array', (['fp'], {}), '(fp)\n', (7917, 7921), True, 'import numpy as np\n'), ((8083, 8097), 'numpy.zeros', 'np.zeros', (['(R,)'], {}), '((R,))\n', (8091, 8097), True, 'import numpy as np\n'), ((8127, 8141), 'numpy.zeros', 'np.zeros', (['(R,)'], {}), '((R,))\n', (8135, 8141), True, 'import numpy as np\n'), ((8714, 8757), 'numpy.searchsorted', 'np.searchsorted', (['rc', 'p.recThrs'], {'side': '"""left"""'}), "(rc, p.recThrs, side='left')\n", (8729, 8757), True, 'import numpy as np\n'), ((9065, 9076), 'numpy.array', 'np.array', (['q'], {}), '(q)\n', (9073, 9076), True, 'import numpy as np\n'), ((9121, 9133), 'numpy.array', 'np.array', (['ss'], {}), '(ss)\n', (9129, 9133), True, 'import numpy as np\n'), ((7646, 7668), 'numpy.cumsum', 'np.cumsum', (['tps'], {'axis': '(1)'}), '(tps, axis=1)\n', (7655, 7668), True, 'import numpy as np\n'), ((7721, 7743), 'numpy.cumsum', 'np.cumsum', (['fps'], {'axis': '(1)'}), '(fps, axis=1)\n', (7730, 7743), True, 'import numpy as np\n'), ((8039, 8052), 'numpy.spacing', 'np.spacing', (['(1)'], {}), '(1)\n', (8049, 8052), True, 'import numpy as np\n')]
#!/usr/bin/env python3 # file://mkpy3_finder_chart_tpf_overlay_v6.py # <NAME> # SETI Institute def mkpy3_finder_chart_tpf_overlay_v6( ax=None, survey_wcs=None, tpf=None, frame=None, colors=[None, "cornflowerblue", "red"], lws=[0, 3, 4], zorders=[0, 1, 2], verbose=None, ): """ Function: mkpy3_finder_chart_tpf_overlay_v6 Purpose: Plot the aperture overlay on top of the sky survey image. Parameters ---------- ax : matplotlib axes.Axes object axis object survey_wcs : World Coordinate System from FITS survey image HDU tpf : lightkurve tpf object (optional) a lightkurve object of a Kepler/K2/TESS Target Pixel File frame : int (optional) frame number of the Target Pixel File [starting at zero] colors : 3-item list of color names [Matplotlib] (optional) Default: [None, 'cornflowerblue', 'red'] lws : 3-item list of line widths [Matplotlib] (optional) Default: [0,3,4] zorders : 3-item list of zorder values (ioptional) Default: [0,1,2] verbose : bool (optional) if True, print extra information Returns: nothing <NAME> SETI Institute """ func_ = "mkpy3_finder_chart_tpf_overlay_v6" date_ = "2020NOV23" version_ = "xi" # import numpy as np import astropy.units as u import ntpath import os import mkpy3 assert ax is not None assert tpf is not None if frame is None: frame = 0 if verbose is None: verbose = False if verbose: print(frame, "=frame") print(colors, "=colors") print(lws, "=lws") print(zorders, "=zorders") print(verbose, "=verbose") print(ntpath.basename(tpf.path), "<--- TPF filename") print(os.path.dirname(tpf.path), "<--- TPF dirname") print() # ===== add overlay to plot ===== tpf_data = tpf.flux[frame] # get frame data # determine which pixels have data (not nans) or are in aperture mask # valid values: 0 = no data (nans), 1 = data, 2 = mask d = np.zeros(tpf_data.size, dtype=int) d[np.isfinite(tpf_data).flatten()] += 1 d[tpf.pipeline_mask.flatten()] += 1 # ========================================================================= # ----- # this will work even if using lightkurve.__version__ <= 2.0.dev # get the RA,DEC values for the pixel centers: pxrav = mkpy3.mkpy3_tpf_get_coordinates_v1(tpf=tpf)[0][frame].flatten() # ^--- pixel RA vector pxdecv = mkpy3.mkpy3_tpf_get_coordinates_v1(tpf=tpf)[1][frame].flatten() # ^--- pixel DEC vector # ^--- both function calls should succeed # ----- # ========================================================================= # # See comments by <NAME>: # https://github.com/KeplerGO/lightkurve/issues/14 # # convert RA,DEC to pixel coordinates of the *survey* image origin0 = 0 pixels = survey_wcs.wcs_world2pix(pxrav * u.degree, pxdecv * u.degree, origin0) # wcs_world2pix documentation: origin=0 (ZERO) when using Numpy ---------^ # xpx = pixels[0] # useful alias ypx = pixels[1] # useful alias # # reshape for plotting xy = np.reshape(pixels, (2, pixels[0].size)).T npixels = len(xy) # # compute median offsets [in *survey* pixels] between TPF pixels dx = np.nanmedian(np.diff(xpx)) dy = np.nanmedian(np.diff(ypx)) # # define locations of corners relative to pixel centers corners = np.array([[1.0, 1.0], [1.0, -1.0], [-1.0, -1.0], [-1.0, 1], [1.0, 1.0]]) # # offsetmatrix is a rotation/scaling matrix: offsetmatrix = np.array(((dx, -dy), (dy, dx))) / 2.0 # dx=cosine(theta) ---^ ^--- dy=sine(theta) # where theta is the rotation angle of offsetmatrix for i in range(len(corners)): corners[i] = np.cross(offsetmatrix, corners[i]) # # plot boundaries of each pixel for i in range(npixels): ccoords = xy[i] + corners k = d[i] c = colors[k] lw = lws[k] zorder = zorders[k] xxx = ccoords[:, 0] yyy = ccoords[:, 1] ax.plot(xxx, yyy, c=c, lw=lw, zorder=zorder) # rof # ========================================================================= if verbose: cadenceno = tpf.cadenceno[frame] print("%d =cadenceno <--- %d=frame" % (cadenceno, frame)) print("\n%s %s %s :-)" % (func_, date_, version_)) # fi return None # fed def xmkpy3_finder_chart_tpf_overlay_v6(): import matplotlib.pyplot as plt import astropy.units as u import sys import os import ntpath import argparse import ast import lightkurve as lk # ignore PEP8 warning of redefinition lk.log.setLevel("INFO") import mkpy3 # # argparse: BEGIN ========================================================= # parser = argparse.ArgumentParser() # parser.add_argument( "--tpf_filename", action="store", type=str, default=None, help="Filename of the Target Pixel File (TPF) [default: None]", ) parser.add_argument( "--frame", action="store", type=int, default=0, help="Frame number (integer) [default: 0]", ) parser.add_argument( "--survey", action="store", type=str, default="2MASS-J", help="Survey name (str) [default: '2MASS-J']", ) parser.add_argument( "--width_height_arcmin", action="store", type=float, default=2.0, help="Width and height size in arcmin (float) [default: 2.0]", ) parser.add_argument( "--show_plot", type=mkpy3.mkpy3_util_str2bool, default=True, help="If True, show the plot [default=True]", ) parser.add_argument( "--plotfile", action="store", type=str, default="mkpy3_plot.png", help="Filename of the output plotfile [default: 'mkpy3_plot.png']", ) parser.add_argument( "--overwrite", type=mkpy3.mkpy3_util_str2bool, default=False, help='If True, overwrite ("clobber") an existing output file ' "[default: False.", ) parser.add_argument( "--figsize", action="store", type=ast.literal_eval, default="[9,9]", help="2-item list of figure width and height [Matplotlib] (str) " '[default: "[9,9]"', ) parser.add_argument( "--title", action="store", type=str, default=None, help="Title of the finder chart (str) [default: None]", ) parser.add_argument( "--percentile", action="store", type=float, default=99.0, help="Percentile [percentage of pixels to keep: 0.0 to 100.0] " "(float) [default: 99.0]", ) parser.add_argument( "--cmap", action="store", type=str, default=None, help="Colormap name [Matplotlib] (str) [default: 'gray']", ) parser.add_argument( "--colors", action="store", type=ast.literal_eval, default="[None,'cornflowerblue','red']", help="3-item list of overlay color names [Matplotlib] (str) " "[default: \"['None','cornflowerblue','red']\"", ) parser.add_argument( "--lws", action="store", type=ast.literal_eval, default="[0,3,4]", help="3-item list of overlay line widths [Matplotlib] (str) " '[default: "[0,3,4]"', ) parser.add_argument( "--zorders", action="store", type=ast.literal_eval, default="[0,1,2]", help="3-item list of overlay zorder values [Matplotlib] (str) " '[default: "[0,1,2]"', ) parser.add_argument( "--marker_dict", action="store", type=ast.literal_eval, default="{'edgecolor':'yellow', 's':600, 'facecolor':'None', 'lw':3, " "'zorder':10}", help="marker kwargs (dictonary string) for ax.scatter() [Matplotlib] " "(str) [default: \"{'edgecolor':'yellow', 's':600, 'facecolor':'None'," " 'lw':3, 'zorder':10}\"", ) parser.add_argument( "--verbose", type=mkpy3.mkpy3_util_str2bool, default=False, help="Print extra information if True (bool) [default=False]", ) # args = parser.parse_args() tpf_filename = args.tpf_filename frame = args.frame survey = args.survey width_height_arcmin = args.width_height_arcmin show_plot = args.show_plot plotfile = args.plotfile overwrite = args.overwrite figsize = args.figsize title_ = args.title percentile = args.percentile cmap = args.cmap colors = args.colors lws = args.lws zorders = args.zorders marker_dict = args.marker_dict verbose = args.verbose # if verbose: print("%s =args.tpf_filename" % (args.tpf_filename)) print("%s =args.frame" % (args.frame)) print("'%s' =args.survey" % (args.survey)) print("%s =args.width_height_arcmin" % (args.width_height_arcmin)) print("%s =args.show_plot" % (args.show_plot)) print("'%s' =args.plotfile" % (args.plotfile)) print("%s =args.overwrite" % (args.overwrite)) print("%s =args.figsize" % (args.figsize)) print("%s =args.title" % (args.title)) print("%s =args.percentile" % (args.percentile)) print("%s =args.cmap" % (args.cmap)) print("%s =args.colors" % (args.colors)) print("%s =args.lws" % (args.lws)) print("%s =args.zorders" % (args.zorders)) print("%s =args.marker_dict" % (args.marker_dict)) print("%s =args.verbose" % (args.verbose)) print() # pass:if # # argparse: END =========================================================== # ok = (type(marker_dict) is dict) or (marker_dict is None) if not ok: print() print("**** ERROR ***** BAD ARGUMENT VALUE *****") print() print("marker_dict must be a dictionary or None:") print(marker_dict, "=marker_dict") print() sys.exit(1) # fi if tpf_filename is not None: mkpy3.mkpy3_util_check_file_exists(tpf_filename, True) tpf = lk.read(tpf_filename) else: tpf = lk.search_targetpixelfile( target="kepler-138b", mission="kepler", cadence="long", quarter=10 ).download(quality_bitmask=0) # 6--- exoplanet Kelper-138b is "KIC 7603200" print() print("No TargetPixelFile (TPF) filename given.") print() print( "Using default TPF [Kepler Q10 observations of exoplanet Kepler-" "138b (KIC 760320)]:" ) # fi print() print("TPF filename:", ntpath.basename(tpf.path)) print("TPF dirname: ", os.path.dirname(tpf.path)) print() ra_deg = tpf.ra dec_deg = tpf.dec if verbose: print() print(ra_deg, "=ra_deg") print(dec_deg, "=dec_deg") # fi print() # get survey image data # survey = '2MASS-J' # hard-wired option ( survey_hdu, survey_hdr, survey_data, survey_wcs, survey_cframe, ) = mkpy3.mkpy3_finder_chart_survey_fits_image_get_v1( ra_deg, dec_deg, radius_arcmin=width_height_arcmin, survey=survey, verbose=verbose, ) # create a matplotlib figure object fig = plt.figure(figsize=figsize) # create a matplotlib axis object with right ascension and declination axes ax = plt.subplot(projection=survey_wcs) # show the survey image mkpy3.mkpy3_finder_chart_image_show_v1( ax=ax, image_data=survey_data, percentile=percentile, cmap=cmap, verbose=verbose ) # show the TPF overlay mkpy3_finder_chart_tpf_overlay_v6( ax=ax, survey_wcs=survey_wcs, tpf=tpf, frame=frame, colors=colors, lws=lws, zorders=zorders, verbose=verbose, ) # add title if title_ is None: title_ = tpf.hdu[0].header["object"] # pass:if plt.suptitle(title_, size=25) # put a yellow circle at the target position if type(marker_dict) is dict: ax.scatter( ra_deg * u.deg, dec_deg * u.deg, transform=ax.get_transform(survey_cframe), **marker_dict ) # adjust the plot margins plt.subplots_adjust(left=0.2, right=0.9, top=0.9, bottom=0.2) if plotfile != "": if plotfile != "mkpy3_plot.png": mkpy3.mkpy3_util_check_file_exists(plotfile, overwrite) plt.savefig(plotfile, dpi=300) # , bbox_inches = "tight") print("\n%s <--- plotfile written :-)\n" % (plotfile)) # fi if show_plot: plt.ioff() plt.show() # fi plt.close() return None # fed # ============================================================================= if __name__ == "__main__": xmkpy3_finder_chart_tpf_overlay_v6() # fi # EOF
[ "argparse.ArgumentParser", "mkpy3.mkpy3_finder_chart_survey_fits_image_get_v1", "matplotlib.pyplot.suptitle", "lightkurve.read", "matplotlib.pyplot.figure", "mkpy3.mkpy3_util_check_file_exists", "matplotlib.pyplot.close", "lightkurve.log.setLevel", "mkpy3.mkpy3_finder_chart_image_show_v1", "os.path.dirname", "numpy.isfinite", "mkpy3.mkpy3_tpf_get_coordinates_v1", "numpy.reshape", "matplotlib.pyplot.show", "numpy.cross", "matplotlib.pyplot.subplots_adjust", "sys.exit", "matplotlib.pyplot.subplot", "ntpath.basename", "matplotlib.pyplot.ioff", "numpy.zeros", "lightkurve.search_targetpixelfile", "numpy.diff", "numpy.array", "matplotlib.pyplot.savefig" ]
[((2011, 2045), 'numpy.zeros', 'np.zeros', (['tpf_data.size'], {'dtype': 'int'}), '(tpf_data.size, dtype=int)\n', (2019, 2045), True, 'import numpy as np\n'), ((3441, 3513), 'numpy.array', 'np.array', (['[[1.0, 1.0], [1.0, -1.0], [-1.0, -1.0], [-1.0, 1], [1.0, 1.0]]'], {}), '([[1.0, 1.0], [1.0, -1.0], [-1.0, -1.0], [-1.0, 1], [1.0, 1.0]])\n', (3449, 3513), True, 'import numpy as np\n'), ((4719, 4742), 'lightkurve.log.setLevel', 'lk.log.setLevel', (['"""INFO"""'], {}), "('INFO')\n", (4734, 4742), True, 'import lightkurve as lk\n'), ((4867, 4892), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (4890, 4892), False, 'import argparse\n'), ((11296, 11433), 'mkpy3.mkpy3_finder_chart_survey_fits_image_get_v1', 'mkpy3.mkpy3_finder_chart_survey_fits_image_get_v1', (['ra_deg', 'dec_deg'], {'radius_arcmin': 'width_height_arcmin', 'survey': 'survey', 'verbose': 'verbose'}), '(ra_deg, dec_deg,\n radius_arcmin=width_height_arcmin, survey=survey, verbose=verbose)\n', (11345, 11433), False, 'import mkpy3\n'), ((11528, 11555), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': 'figsize'}), '(figsize=figsize)\n', (11538, 11555), True, 'import matplotlib.pyplot as plt\n'), ((11646, 11680), 'matplotlib.pyplot.subplot', 'plt.subplot', ([], {'projection': 'survey_wcs'}), '(projection=survey_wcs)\n', (11657, 11680), True, 'import matplotlib.pyplot as plt\n'), ((11714, 11838), 'mkpy3.mkpy3_finder_chart_image_show_v1', 'mkpy3.mkpy3_finder_chart_image_show_v1', ([], {'ax': 'ax', 'image_data': 'survey_data', 'percentile': 'percentile', 'cmap': 'cmap', 'verbose': 'verbose'}), '(ax=ax, image_data=survey_data,\n percentile=percentile, cmap=cmap, verbose=verbose)\n', (11752, 11838), False, 'import mkpy3\n'), ((12199, 12228), 'matplotlib.pyplot.suptitle', 'plt.suptitle', (['title_'], {'size': '(25)'}), '(title_, size=25)\n', (12211, 12228), True, 'import matplotlib.pyplot as plt\n'), ((12516, 12577), 'matplotlib.pyplot.subplots_adjust', 'plt.subplots_adjust', ([], {'left': '(0.2)', 'right': '(0.9)', 'top': '(0.9)', 'bottom': '(0.2)'}), '(left=0.2, right=0.9, top=0.9, bottom=0.2)\n', (12535, 12577), True, 'import matplotlib.pyplot as plt\n'), ((12930, 12941), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (12939, 12941), True, 'import matplotlib.pyplot as plt\n'), ((3150, 3189), 'numpy.reshape', 'np.reshape', (['pixels', '(2, pixels[0].size)'], {}), '(pixels, (2, pixels[0].size))\n', (3160, 3189), True, 'import numpy as np\n'), ((3311, 3323), 'numpy.diff', 'np.diff', (['xpx'], {}), '(xpx)\n', (3318, 3323), True, 'import numpy as np\n'), ((3347, 3359), 'numpy.diff', 'np.diff', (['ypx'], {}), '(ypx)\n', (3354, 3359), True, 'import numpy as np\n'), ((3588, 3619), 'numpy.array', 'np.array', (['((dx, -dy), (dy, dx))'], {}), '(((dx, -dy), (dy, dx)))\n', (3596, 3619), True, 'import numpy as np\n'), ((3798, 3832), 'numpy.cross', 'np.cross', (['offsetmatrix', 'corners[i]'], {}), '(offsetmatrix, corners[i])\n', (3806, 3832), True, 'import numpy as np\n'), ((10180, 10191), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (10188, 10191), False, 'import sys\n'), ((10247, 10301), 'mkpy3.mkpy3_util_check_file_exists', 'mkpy3.mkpy3_util_check_file_exists', (['tpf_filename', '(True)'], {}), '(tpf_filename, True)\n', (10281, 10301), False, 'import mkpy3\n'), ((10316, 10337), 'lightkurve.read', 'lk.read', (['tpf_filename'], {}), '(tpf_filename)\n', (10323, 10337), True, 'import lightkurve as lk\n'), ((10841, 10866), 'ntpath.basename', 'ntpath.basename', (['tpf.path'], {}), '(tpf.path)\n', (10856, 10866), False, 'import ntpath\n'), ((10895, 10920), 'os.path.dirname', 'os.path.dirname', (['tpf.path'], {}), '(tpf.path)\n', (10910, 10920), False, 'import os\n'), ((12719, 12749), 'matplotlib.pyplot.savefig', 'plt.savefig', (['plotfile'], {'dpi': '(300)'}), '(plotfile, dpi=300)\n', (12730, 12749), True, 'import matplotlib.pyplot as plt\n'), ((12882, 12892), 'matplotlib.pyplot.ioff', 'plt.ioff', ([], {}), '()\n', (12890, 12892), True, 'import matplotlib.pyplot as plt\n'), ((12901, 12911), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (12909, 12911), True, 'import matplotlib.pyplot as plt\n'), ((1656, 1681), 'ntpath.basename', 'ntpath.basename', (['tpf.path'], {}), '(tpf.path)\n', (1671, 1681), False, 'import ntpath\n'), ((1718, 1743), 'os.path.dirname', 'os.path.dirname', (['tpf.path'], {}), '(tpf.path)\n', (1733, 1743), False, 'import os\n'), ((12655, 12710), 'mkpy3.mkpy3_util_check_file_exists', 'mkpy3.mkpy3_util_check_file_exists', (['plotfile', 'overwrite'], {}), '(plotfile, overwrite)\n', (12689, 12710), False, 'import mkpy3\n'), ((2052, 2073), 'numpy.isfinite', 'np.isfinite', (['tpf_data'], {}), '(tpf_data)\n', (2063, 2073), True, 'import numpy as np\n'), ((10362, 10460), 'lightkurve.search_targetpixelfile', 'lk.search_targetpixelfile', ([], {'target': '"""kepler-138b"""', 'mission': '"""kepler"""', 'cadence': '"""long"""', 'quarter': '(10)'}), "(target='kepler-138b', mission='kepler', cadence=\n 'long', quarter=10)\n", (10387, 10460), True, 'import lightkurve as lk\n'), ((2355, 2398), 'mkpy3.mkpy3_tpf_get_coordinates_v1', 'mkpy3.mkpy3_tpf_get_coordinates_v1', ([], {'tpf': 'tpf'}), '(tpf=tpf)\n', (2389, 2398), False, 'import mkpy3\n'), ((2459, 2502), 'mkpy3.mkpy3_tpf_get_coordinates_v1', 'mkpy3.mkpy3_tpf_get_coordinates_v1', ([], {'tpf': 'tpf'}), '(tpf=tpf)\n', (2493, 2502), False, 'import mkpy3\n')]
##### IMPORTING PACKAGES ##### import pandas as pd import numpy as np import matplotlib as mpl import matplotlib.pyplot as plt from scipy.optimize import minimize from sklearn.preprocessing import PolynomialFeatures # pd.set_option('display.notebook_repr_html', False) # pd.set_option('display.max_columns', None) # pd.set_option('display.max_rows', 150) # pd.set_option('display.max_seq_items', None) # import seaborn as sns # sns.set_context('notebook') # sns.set_style('white') ##### SCATTER PLOT FUNCTION DEFINITION ##### def scatterPlot(data, label_x, label_y, label_pos, label_neg, axes=None): # Get indexes for class 0 and class 1 neg = data[:, 2] == 0 pos = data[:, 2] == 1 # If no specific axes object has been passed, get the current axes. if axes == None: axes = plt.gca() axes.scatter(data[pos][:, 0], data[pos][:, 1], marker='+', c='r', s=60, linewidth=2, label=label_pos) axes.scatter(data[neg][:, 0], data[neg][:, 1], c='g', s=60, label=label_neg) axes.set_xlabel(label_x) axes.set_ylabel(label_y) axes.legend(frameon=True, fancybox=True); ##### LOADING DATA SET GIVEN IN TEXT FORMAT ##### data = np.loadtxt('LogisticRegressionData1.txt', delimiter=',') print('Dimensions: ',data.shape) print(data[1:6,:]) X_withoutaugment = data[:,0:2] X = np.c_[np.ones((data.shape[0],1)), X_withoutaugment] y = np.c_[data[:,2]] print("\n DATA PLOT BEFORE LOGISTIC REGRESSION\n") print("========================================\n\n") scatterPlot(data, 'Feature1', 'Feature2', 'Positive Class', 'Negative Class') plt.show() ##### HYPOTHESIS FUNCTION IS A SIGMOID FOR LOGISTIC REGRESSION ##### def sigmoid(wtx): return(1 / (1 + np.exp(-wtx))) ##### USING THE COST FUNCTION EQUATION FOR THE LOGISTIC REGRESSION def costFunction(weight, X, y): m = y.size h = sigmoid(X.dot(weight)) J = -1 * (1 / m) * (np.log(h).T.dot(y) + np.log(1 - h).T.dot(1 - y)) if np.isnan(J[0]): return (np.inf) return (J[0]) ##### PARTIAL DERIVATIVE WITH RESPECT TO WEIGHTS def gradient(weight, X, y): m = y.size h = sigmoid(X.dot(weight.reshape(-1, 1))) grad = (1 / m) * X.T.dot(h - y) return (grad.flatten()) ##### INITIALISING INITIAL WEIGHT AND CALCULATING INITIAL COST initial_weight = np.zeros(X.shape[1]) cost = costFunction(initial_weight, X, y) grad = gradient(initial_weight, X, y) print('Cost: \n', cost) print('Grad: \n', grad) print('\n\n') ##### MINIMISING THE COST FUNCTION res = minimize(costFunction, initial_weight, args=(X,y), method=None, jac=gradient, options={'maxiter':500}) print(res) def predict(theta, X, threshold=0.5): p = sigmoid(X.dot(theta.T)) >= threshold return(p.astype('int')) # Assume Feature1 = 50 and Feature2=90. # Predict using the optimized Theta values from above (res.x) sigmoid(np.array([1, 50, 90]).dot(res.x.T)) p = predict(res.x, X) print('Train accuracy {}%'.format(100*sum(p == y.ravel())/p.size)) print("\n\n DATA PLOT AFTER LOGISTIC REGRESSION\n") print("=========================================\n\n") plt.scatter(50, 90, s=60, c='k', marker='v', label='(50, 90)') scatterPlot(data, 'Feature1', 'Feature2', 'Positive Class', 'Negative Class') x1_min, x1_max = X[:,1].min(), X[:,1].max(), x2_min, x2_max = X[:,2].min(), X[:,2].max(), xx1, xx2 = np.meshgrid(np.linspace(x1_min, x1_max), np.linspace(x2_min, x2_max)) h = sigmoid(np.c_[np.ones((xx1.ravel().shape[0],1)), xx1.ravel(), xx2.ravel()].dot(res.x)) h = h.reshape(xx1.shape) plt.contour(xx1, xx2, h, [0.5], linewidths=1, colors='b'); plt.show() #### REGULARIZATION #### LOADING THE DATA data2 = np.loadtxt('LogisticRegressionData2.txt', delimiter=',') print('Dimensions: ',data.shape) print(data[1:6,:]) #### INTIALISING FEATURE VECTOR AND LABEL VECTOR y = np.c_[data2[:,2]] X = data2[:,0:2] print("\n\n DATA PLOT BEFORE LOGISTIC REGRESSION\n") print("===========================================\n\n") scatterPlot(data2, 'Feature1', 'Feature2', 'y = 1', 'y = 0') plt.show() # AUGMENTED VECTOR poly = PolynomialFeatures(6) XX = poly.fit_transform(data2[:,0:2]) XX.shape # DEFINE COST FUNCTION def costFunctionReg(theta, reg, *args): m = y.size h = sigmoid(XX.dot(theta)) J = -1 * (1 / m) * (np.log(h).T.dot(y) + np.log(1 - h).T.dot(1 - y)) + (reg / (2 * m)) * np.sum( np.square(theta[1:])) if np.isnan(J[0]): return (np.inf) return (J[0]) # CALCULATE THE PARTIAL DERIVATIVE def gradientReg(theta, reg, *args): m = y.size h = sigmoid(XX.dot(theta.reshape(-1, 1))) grad = (1 / m) * XX.T.dot(h - y) + (reg / m) * np.r_[[[0]], theta[1:].reshape(-1, 1)] return (grad.flatten()) # INITIALISE THE WEIGHT AND CALCULATE THE INITIAL COST FUNCTION initial_weight = np.zeros(XX.shape[1]) costFunctionReg(initial_weight, 1, XX, y) fig, axes = plt.subplots(1, 3, sharey=True, figsize=(17, 5)) # Decision boundaries # Lambda = 0 : No regularization --> overfitting the training data # Lambda = 1 : Moderate Penalty ---> Good Regularisation # Lambda = 100 : High Penalty --> high bias ---> Even this is bad print("\n\n DATA PLOT AFTER LOG. REG. + REGULARISATION\n") print("==================================================\n\n") for i, C in enumerate([0, 1, 100]): # Optimize costFunctionReg res2 = minimize(costFunctionReg, initial_weight, args=(C, XX, y), method=None, jac=gradientReg, options={'maxiter': 3000}) # Accuracy accuracy = 100 * sum(predict(res2.x, XX) == y.ravel()) / y.size # Scatter plot of X,y scatterPlot(data2, 'Feature1', 'Feature2', 'y = 1', 'y = 0', axes.flatten()[i]) # Plot decisionboundary x1_min, x1_max = X[:, 0].min(), X[:, 0].max(), x2_min, x2_max = X[:, 1].min(), X[:, 1].max(), xx1, xx2 = np.meshgrid(np.linspace(x1_min, x1_max), np.linspace(x2_min, x2_max)) h = sigmoid(poly.fit_transform(np.c_[xx1.ravel(), xx2.ravel()]).dot(res2.x)) h = h.reshape(xx1.shape) axes.flatten()[i].contour(xx1, xx2, h, [0.5], linewidths=1, colors='g'); axes.flatten()[i].set_title('Train accuracy {}% with Lambda = {}'.format(np.round(accuracy, decimals=2), C)) plt.show()
[ "scipy.optimize.minimize", "matplotlib.pyplot.show", "numpy.log", "matplotlib.pyplot.scatter", "numpy.round", "numpy.zeros", "numpy.ones", "numpy.isnan", "numpy.square", "sklearn.preprocessing.PolynomialFeatures", "matplotlib.pyplot.contour", "numpy.loadtxt", "numpy.linspace", "matplotlib.pyplot.gca", "numpy.exp", "numpy.array", "matplotlib.pyplot.subplots" ]
[((1163, 1219), 'numpy.loadtxt', 'np.loadtxt', (['"""LogisticRegressionData1.txt"""'], {'delimiter': '""","""'}), "('LogisticRegressionData1.txt', delimiter=',')\n", (1173, 1219), True, 'import numpy as np\n'), ((1566, 1576), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (1574, 1576), True, 'import matplotlib.pyplot as plt\n'), ((2271, 2291), 'numpy.zeros', 'np.zeros', (['X.shape[1]'], {}), '(X.shape[1])\n', (2279, 2291), True, 'import numpy as np\n'), ((2476, 2585), 'scipy.optimize.minimize', 'minimize', (['costFunction', 'initial_weight'], {'args': '(X, y)', 'method': 'None', 'jac': 'gradient', 'options': "{'maxiter': 500}"}), "(costFunction, initial_weight, args=(X, y), method=None, jac=\n gradient, options={'maxiter': 500})\n", (2484, 2585), False, 'from scipy.optimize import minimize\n'), ((3048, 3110), 'matplotlib.pyplot.scatter', 'plt.scatter', (['(50)', '(90)'], {'s': '(60)', 'c': '"""k"""', 'marker': '"""v"""', 'label': '"""(50, 90)"""'}), "(50, 90, s=60, c='k', marker='v', label='(50, 90)')\n", (3059, 3110), True, 'import matplotlib.pyplot as plt\n'), ((3476, 3533), 'matplotlib.pyplot.contour', 'plt.contour', (['xx1', 'xx2', 'h', '[0.5]'], {'linewidths': '(1)', 'colors': '"""b"""'}), "(xx1, xx2, h, [0.5], linewidths=1, colors='b')\n", (3487, 3533), True, 'import matplotlib.pyplot as plt\n'), ((3535, 3545), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (3543, 3545), True, 'import matplotlib.pyplot as plt\n'), ((3598, 3654), 'numpy.loadtxt', 'np.loadtxt', (['"""LogisticRegressionData2.txt"""'], {'delimiter': '""","""'}), "('LogisticRegressionData2.txt', delimiter=',')\n", (3608, 3654), True, 'import numpy as np\n'), ((3969, 3979), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (3977, 3979), True, 'import matplotlib.pyplot as plt\n'), ((4007, 4028), 'sklearn.preprocessing.PolynomialFeatures', 'PolynomialFeatures', (['(6)'], {}), '(6)\n', (4025, 4028), False, 'from sklearn.preprocessing import PolynomialFeatures\n'), ((4725, 4746), 'numpy.zeros', 'np.zeros', (['XX.shape[1]'], {}), '(XX.shape[1])\n', (4733, 4746), True, 'import numpy as np\n'), ((4801, 4849), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(1)', '(3)'], {'sharey': '(True)', 'figsize': '(17, 5)'}), '(1, 3, sharey=True, figsize=(17, 5))\n', (4813, 4849), True, 'import matplotlib.pyplot as plt\n'), ((6115, 6125), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (6123, 6125), True, 'import matplotlib.pyplot as plt\n'), ((1928, 1942), 'numpy.isnan', 'np.isnan', (['J[0]'], {}), '(J[0])\n', (1936, 1942), True, 'import numpy as np\n'), ((3302, 3329), 'numpy.linspace', 'np.linspace', (['x1_min', 'x1_max'], {}), '(x1_min, x1_max)\n', (3313, 3329), True, 'import numpy as np\n'), ((3331, 3358), 'numpy.linspace', 'np.linspace', (['x2_min', 'x2_max'], {}), '(x2_min, x2_max)\n', (3342, 3358), True, 'import numpy as np\n'), ((4330, 4344), 'numpy.isnan', 'np.isnan', (['J[0]'], {}), '(J[0])\n', (4338, 4344), True, 'import numpy as np\n'), ((5267, 5387), 'scipy.optimize.minimize', 'minimize', (['costFunctionReg', 'initial_weight'], {'args': '(C, XX, y)', 'method': 'None', 'jac': 'gradientReg', 'options': "{'maxiter': 3000}"}), "(costFunctionReg, initial_weight, args=(C, XX, y), method=None, jac\n =gradientReg, options={'maxiter': 3000})\n", (5275, 5387), False, 'from scipy.optimize import minimize\n'), ((804, 813), 'matplotlib.pyplot.gca', 'plt.gca', ([], {}), '()\n', (811, 813), True, 'import matplotlib.pyplot as plt\n'), ((1314, 1341), 'numpy.ones', 'np.ones', (['(data.shape[0], 1)'], {}), '((data.shape[0], 1))\n', (1321, 1341), True, 'import numpy as np\n'), ((5756, 5783), 'numpy.linspace', 'np.linspace', (['x1_min', 'x1_max'], {}), '(x1_min, x1_max)\n', (5767, 5783), True, 'import numpy as np\n'), ((5785, 5812), 'numpy.linspace', 'np.linspace', (['x2_min', 'x2_max'], {}), '(x2_min, x2_max)\n', (5796, 5812), True, 'import numpy as np\n'), ((1686, 1698), 'numpy.exp', 'np.exp', (['(-wtx)'], {}), '(-wtx)\n', (1692, 1698), True, 'import numpy as np\n'), ((2814, 2835), 'numpy.array', 'np.array', (['[1, 50, 90]'], {}), '([1, 50, 90])\n', (2822, 2835), True, 'import numpy as np\n'), ((6078, 6108), 'numpy.round', 'np.round', (['accuracy'], {'decimals': '(2)'}), '(accuracy, decimals=2)\n', (6086, 6108), True, 'import numpy as np\n'), ((4300, 4320), 'numpy.square', 'np.square', (['theta[1:]'], {}), '(theta[1:])\n', (4309, 4320), True, 'import numpy as np\n'), ((1872, 1881), 'numpy.log', 'np.log', (['h'], {}), '(h)\n', (1878, 1881), True, 'import numpy as np\n'), ((1893, 1906), 'numpy.log', 'np.log', (['(1 - h)'], {}), '(1 - h)\n', (1899, 1906), True, 'import numpy as np\n'), ((4215, 4224), 'numpy.log', 'np.log', (['h'], {}), '(h)\n', (4221, 4224), True, 'import numpy as np\n'), ((4236, 4249), 'numpy.log', 'np.log', (['(1 - h)'], {}), '(1 - h)\n', (4242, 4249), True, 'import numpy as np\n')]
import abc import copy import itertools import logging from typing import ( Any, Callable, Dict, Iterable, Iterator, Mapping, Optional, Sequence, Set, Type, TypeVar, Union ) import numpy as np from smqtk_dataprovider import DataElement from smqtk_descriptors import DescriptorGenerator from smqtk_image_io import ImageReader from smqtk_core.configuration import ( from_config_dict, make_default_config, to_config_dict, ) from smqtk_descriptors.utils.parallel import parallel_map from smqtk_descriptors.utils.pytorch_utils import load_state_dict LOG = logging.getLogger(__name__) try: import torch # type: ignore from torch.utils.data import Dataset # type: ignore import torchvision.models # type: ignore import torchvision.transforms # type: ignore from torch.nn import functional as F # type: ignore except ModuleNotFoundError: torch = None # type: ignore __all__ = [ "TorchModuleDescriptorGenerator", "Resnet50SequentialTorchDescriptorGenerator", "AlignedReIDResNet50TorchDescriptorGenerator" ] T = TypeVar("T", bound="TorchModuleDescriptorGenerator") def normalize_vectors( v: np.ndarray, mode: Optional[Union[int, float, str]] = None ) -> np.ndarray: """ Array/Matrix normalization along max dimension (i.e. a=0 for 1D array, a=1 for 2D array, etc.). :param v: Vector to normalize. :param mode: ``numpy.linalg.norm`` order parameter. :return: Normalize version of the input array ``v``. """ if mode is not None: n = np.linalg.norm(v, mode, v.ndim - 1, keepdims=True) # replace 0's with 1's, preventing div-by-zero n[n == 0.] = 1. return v / n # When normalization off return v try: class ImgMatDataset (Dataset): def __init__( self, img_mat_list: Sequence[np.ndarray], transform: Callable[[Iterable[np.ndarray]], "torch.Tensor"] ) -> None: self.img_mat_list = img_mat_list self.transform = transform def __getitem__(self, index: int) -> "torch.Tensor": return self.transform(self.img_mat_list[index]) def __len__(self) -> int: return len(self.img_mat_list) except NameError: pass class TorchModuleDescriptorGenerator (DescriptorGenerator): """ Descriptor generator using some torch module. :param image_reader: Image reader algorithm to use for image loading. :param image_load_threads: Number of threads to use for parallel image loading. Set to "None" to use all available CPU threads. This is 1 (serial) by default. :param weights_filepath: Optional filepath to saved network weights to load. If this value is None then implementations should attempt to use their "pre-trained" mode if they have one. Otherwise an error is raised on model load when not provided. :param image_tform_threads: Number of threads to utilize when transforming image matrices for network input. Set to `None` to use all available CPU threads. This is 1 (serial) by default). :param batch_size: Batch size use for model computation. :param use_gpu: If the model should be loaded onto, and processed on, the GPU. :param cuda_device: Specific device value to pass to the CUDA transfer calls if `use_gpu` us enabled. :param normalize: Optionally normalize descriptor vectors as they are produced. We use ``numpy.linalg.norm`` so any valid value for the ``ord`` parameter is acceptable here. :param iter_runtime: By default the input image matrix data is accumulated into a list in order to utilize `torch.utils.data.DataLoader` for batching. If this is parameter is True however, we use a custom parallel iteration pipeline for image transformation into network appropriate tensors. Using this mode changes the maximum RAM usage profile to be linear with batch-size instead of input image data amount, as well as having lower latency to first yield. This mode is idea for streaming input or high input volume situations. This mode currently has a short-coming of working only in a threaded manner so it is not as fast as using the `DataLoader` avenue. :param global_average_pool: Optionally apply a GAP operation to the spatial dimension of the feature vector that is returned by the descriptor generator. Some models return a w x h x k tensor and flatten them into a single dimension, which can remove the spatial context of the features. Taking an average over each channel can improve the clustering in some cases. """ @classmethod def is_usable(cls) -> bool: valid = torch is not None if not valid: LOG.debug("Torch python module not imported") return valid @classmethod def get_default_config(cls) -> Dict[str, Any]: c = super().get_default_config() c['image_reader'] = make_default_config(ImageReader.get_impls()) return c @classmethod def from_config( cls: Type[T], config_dict: Dict, merge_default: bool = True ) -> T: # Copy config to prevent input modification config_dict = copy.deepcopy(config_dict) config_dict['image_reader'] = from_config_dict( config_dict['image_reader'], ImageReader.get_impls() ) return super().from_config(config_dict, merge_default) def __init__( self, image_reader: ImageReader, image_load_threads: Optional[int] = 1, weights_filepath: Optional[str] = None, image_tform_threads: Optional[int] = 1, batch_size: int = 32, use_gpu: bool = False, cuda_device: Optional[int] = None, normalize: Optional[Union[int, float, str]] = None, iter_runtime: bool = False, global_average_pool: bool = False ): super().__init__() self.image_reader = image_reader self.image_load_threads = image_load_threads self.weights_filepath = weights_filepath self.image_tform_threads = image_tform_threads self.batch_size = batch_size self.use_gpu = use_gpu self.cuda_device = cuda_device self.normalize = normalize self.iter_runtime = iter_runtime self.global_average_pool = global_average_pool # Place-holder for the torch.nn.Module loaded. self.module: Optional[torch.nn.Module] = None # Just load model on construction # - this may have issues in multi-threaded/processed contexts. Use # will tell. self._ensure_module() @abc.abstractmethod def _load_module(self) -> "torch.nn.Module": """ :return: Load and return the module. """ @abc.abstractmethod def _make_transform(self) -> Callable[[Iterable[DataElement]], "torch.Tensor"]: """ :returns: A callable that takes in a ``numpy.ndarray`` image matrix and returns a transformed version as a ``torch.Tensor``. """ def __getstate__(self) -> Dict[str, Any]: return self.get_config() def __setstate__(self, state: Mapping[str, Any]) -> None: # This ``__dict__.update`` works because configuration parameters # exactly match up with instance attributes currently. self.__dict__.update(state) # Translate nested Configurable instance configurations into actual # object instances. self.image_reader = from_config_dict( state['image_reader'], ImageReader.get_impls() ) self._ensure_module() def valid_content_types(self) -> Set: return self.image_reader.valid_content_types() def is_valid_element(self, data_element: DataElement) -> bool: # Check element validity though the ImageReader algorithm instance return self.image_reader.is_valid_element(data_element) def _ensure_module(self) -> "torch.nn.Module": if self.module is None: module = self._load_module() if self.weights_filepath: checkpoint = torch.load(self.weights_filepath, # In-case weights were saved with the # context of a non-CPU device. map_location="cpu") # A common alternative pattern is for training to save # checkpoints/state-dicts as a nested dict that contains the # state-dict under the key 'state_dict'. if 'state_dict' in checkpoint: checkpoint = checkpoint['state_dict'] elif 'state_dicts' in checkpoint: checkpoint = checkpoint['state_dicts'][0] # Align model and checkpoint and load weights load_state_dict(module, checkpoint) module.eval() if self.use_gpu: module = module.cuda(self.cuda_device) self.module = module return self.module def _generate_arrays(self, data_iter: Iterable[DataElement]) -> Iterable[np.ndarray]: # Generically load image data [in parallel], iterating results into # template method. ir_load: Callable[..., Any] = self.image_reader.load_as_matrix i_load_threads = self.image_load_threads gen_fn = ( self.generate_arrays_from_images_naive, # False self.generate_arrays_from_images_iter, # True )[self.iter_runtime] if i_load_threads is None or i_load_threads > 1: return gen_fn( parallel_map(ir_load, data_iter, cores=i_load_threads) ) else: return gen_fn( ir_load(d) for d in data_iter ) # NOTE: may need to create wrapper function around _make_transform # that adds a PIL.Image.from_array and convert transformation to # ensure being in the expected image format for the network. def generate_arrays_from_images_naive( self, img_mat_iter: Iterable[DataElement] ) -> Iterable[np.ndarray]: model = self._ensure_module() # Just gather all input into list for pytorch dataset wrapping img_mat_list = list(img_mat_iter) tform_img_fn = self._make_transform() use_gpu = self.use_gpu cuda_device = self.cuda_device if self.image_tform_threads is not None: num_workers: int = min(self.image_tform_threads, len(img_mat_list)) else: num_workers = len(img_mat_list) dl = torch.utils.data.DataLoader( ImgMatDataset(img_mat_list, tform_img_fn), batch_size=self.batch_size, # Don't need more workers than we have input, so don't bother # spinning them up... num_workers=num_workers, # Use pinned memory when we're in use-gpu mode. pin_memory=use_gpu is True) for batch_input in dl: # batch_input: batch_size x channels x height x width if use_gpu: batch_input = batch_input.cuda(cuda_device) feats = self._forward(model, batch_input) for f in feats: yield f def generate_arrays_from_images_iter( self, img_mat_iter: Iterable[DataElement] ) -> Iterable[np.ndarray]: """ Template method for implementation to define descriptor generation over input image matrices. :param img_mat_iter: Iterable of numpy arrays representing input image matrices. :raises :return: Iterable of numpy arrays in parallel association with the input image matrices. """ model = self._ensure_module() # Set up running parallelize # - Not utilizing a DataLoader due to input being an iterator where # we don't know the size of input a priori. tform_img_fn: Callable[..., Any] = self._make_transform() tform_threads = self.image_tform_threads if tform_threads is None or tform_threads > 1: tfed_mat_iter: Iterator = parallel_map(tform_img_fn, img_mat_iter, cores=self.image_tform_threads, name="tform_img", ordered=True) else: tfed_mat_iter = ( tform_img_fn(mat) for mat in img_mat_iter ) batch_size = self.batch_size use_gpu = self.use_gpu # We don't know the shape of input data yet. batch_tensor = None #: :type: list[torch.Tensor] batch_slice = list(itertools.islice(tfed_mat_iter, batch_size)) cuda_device = self.cuda_device while batch_slice: # Use batch tensor unless this is the leaf batch, in which case # we need to allocate a reduced size one. if batch_tensor is None or len(batch_slice) != batch_size: batch_size = len(batch_slice) batch_tensor = torch.empty([len(batch_slice)] + list(batch_slice[0].shape)) if use_gpu: # When using the GPU, attempt to use page-locked memory. # https://devblogs.nvidia.com/how-optimize-data-transfers-cuda-cc/ batch_tensor.pin_memory() # Fill in tensor with batch image matrices for i in range(batch_size): batch_tensor[i, :] = batch_slice[i] process_tensor = batch_tensor if use_gpu: # Copy input data tensor in batch to GPU. # - Need to use the same CUDA device that model is loaded on. process_tensor = batch_tensor.cuda(cuda_device) feats = self._forward(model, process_tensor) for f in feats: yield f #: :type: list[torch.Tensor] batch_slice = list(itertools.islice(tfed_mat_iter, batch_size)) def _forward(self, model: "torch.nn.Module", model_input: "torch.Tensor") -> np.ndarray: """ Template method for implementation of forward pass of model. :param model: Network module with loaded weights :param model_input: Tensor that has been appropriately shaped and placed onto target inference hardware. :return: Tensor output of module() call """ with torch.no_grad(): feats = model(model_input) # Apply global average pool if self.global_average_pool and len(feats.size()) > 2: feats = F.avg_pool2d(feats, feats.size()[2:]) feats = feats.view(feats.size(0), -1) feats_np = np.squeeze(feats.cpu().numpy().astype(np.float32)) if len(feats_np.shape) < 2: # Add a dim if the batch size was only one (first dim squeezed # down). feats_np = np.expand_dims(feats_np, 0) # Normalizing *after* squeezing for axis sanity. feats_np = normalize_vectors(feats_np, self.normalize) return feats_np def get_config(self) -> Dict[str, Any]: return { "image_reader": to_config_dict(self.image_reader), "image_load_threads": self.image_load_threads, "weights_filepath": self.weights_filepath, "image_tform_threads": self.image_tform_threads, "batch_size": self.batch_size, "use_gpu": self.use_gpu, "cuda_device": self.cuda_device, "normalize": self.normalize, "iter_runtime": self.iter_runtime, "global_average_pool": self.global_average_pool } class Resnet50SequentialTorchDescriptorGenerator (TorchModuleDescriptorGenerator): """ Use torchvision.models.resnet50, but chop off the final fully-connected layer as a ``torch.nn.Sequential``. """ @classmethod def is_usable(cls) -> bool: valid = torch is not None if not valid: LOG.debug("Torch python module not imported") return valid def _load_module(self) -> "torch.nn.Module": pretrained = self.weights_filepath is None m = torchvision.models.resnet50( pretrained=pretrained ) if pretrained: LOG.info("Using pre-trained weights for pytorch ResNet-50 " "network.") return torch.nn.Sequential( *tuple(m.children())[:-1] ) def _make_transform(self) -> Callable[[Iterable[np.ndarray]], "torch.Tensor"]: # Transform based on: https://pytorch.org/hub/pytorch_vision_resnet/ return torchvision.transforms.Compose([ torchvision.transforms.ToPILImage(mode='RGB'), torchvision.transforms.Resize((224, 224)), torchvision.transforms.ToTensor(), torchvision.transforms.Normalize( mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225] ) ]) class AlignedReIDResNet50TorchDescriptorGenerator (TorchModuleDescriptorGenerator): """ Descriptor generator for computing Aligned Re-ID++ descriptors. """ @classmethod def is_usable(cls) -> bool: valid = torch is not None if not valid: LOG.debug("Torch python module not imported") return valid def _load_module(self) -> "torch.nn.Module": pretrained = self.weights_filepath is None # Pre-initialization with imagenet model important - provided # checkpoint potentially missing layers m = torchvision.models.resnet50( pretrained=True ) if pretrained: LOG.info("Using pre-trained weights for pytorch ResNet-50 " "network.") # Return model without pool and linear layer return torch.nn.Sequential( *tuple(m.children())[:-2] ) def _forward(self, model: "torch.nn.Module", model_input: "torch.Tensor") -> np.ndarray: with torch.no_grad(): feats = model(model_input) # Use only global features from return of (global_feats, local_feats) if isinstance(feats, tuple): feats = feats[0] feats = F.avg_pool2d(feats, feats.size()[2:]) feats = feats.view(feats.size(0), -1) feats_np = np.squeeze(feats.cpu().numpy().astype(np.float32)) if len(feats_np.shape) < 2: # Add a dim if the batch size was only one (first dim squeezed # down). feats_np = np.expand_dims(feats_np, 0) # Normalizing *after* squeezing for axis sanity. feats_np = normalize_vectors(feats_np, self.normalize) return feats_np def _make_transform(self) -> Callable[[Iterable[np.ndarray]], "torch.Tensor"]: # Transform based on: https://pytorch.org/hub/pytorch_vision_resnet/ return torchvision.transforms.Compose([ torchvision.transforms.ToPILImage(mode='RGB'), torchvision.transforms.Resize((224, 224)), torchvision.transforms.ToTensor(), torchvision.transforms.Normalize( mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225] ) ])
[ "smqtk_core.configuration.to_config_dict", "copy.deepcopy", "smqtk_image_io.ImageReader.get_impls", "torch.load", "smqtk_descriptors.utils.pytorch_utils.load_state_dict", "numpy.expand_dims", "numpy.linalg.norm", "itertools.islice", "typing.TypeVar", "smqtk_descriptors.utils.parallel.parallel_map", "torch.no_grad", "logging.getLogger" ]
[((575, 602), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (592, 602), False, 'import logging\n'), ((1070, 1122), 'typing.TypeVar', 'TypeVar', (['"""T"""'], {'bound': '"""TorchModuleDescriptorGenerator"""'}), "('T', bound='TorchModuleDescriptorGenerator')\n", (1077, 1122), False, 'from typing import Any, Callable, Dict, Iterable, Iterator, Mapping, Optional, Sequence, Set, Type, TypeVar, Union\n'), ((1541, 1591), 'numpy.linalg.norm', 'np.linalg.norm', (['v', 'mode', '(v.ndim - 1)'], {'keepdims': '(True)'}), '(v, mode, v.ndim - 1, keepdims=True)\n', (1555, 1591), True, 'import numpy as np\n'), ((5397, 5423), 'copy.deepcopy', 'copy.deepcopy', (['config_dict'], {}), '(config_dict)\n', (5410, 5423), False, 'import copy\n'), ((5146, 5169), 'smqtk_image_io.ImageReader.get_impls', 'ImageReader.get_impls', ([], {}), '()\n', (5167, 5169), False, 'from smqtk_image_io import ImageReader\n'), ((5533, 5556), 'smqtk_image_io.ImageReader.get_impls', 'ImageReader.get_impls', ([], {}), '()\n', (5554, 5556), False, 'from smqtk_image_io import ImageReader\n'), ((7755, 7778), 'smqtk_image_io.ImageReader.get_impls', 'ImageReader.get_impls', ([], {}), '()\n', (7776, 7778), False, 'from smqtk_image_io import ImageReader\n'), ((12448, 12556), 'smqtk_descriptors.utils.parallel.parallel_map', 'parallel_map', (['tform_img_fn', 'img_mat_iter'], {'cores': 'self.image_tform_threads', 'name': '"""tform_img"""', 'ordered': '(True)'}), "(tform_img_fn, img_mat_iter, cores=self.image_tform_threads,\n name='tform_img', ordered=True)\n", (12460, 12556), False, 'from smqtk_descriptors.utils.parallel import parallel_map\n'), ((13104, 13147), 'itertools.islice', 'itertools.islice', (['tfed_mat_iter', 'batch_size'], {}), '(tfed_mat_iter, batch_size)\n', (13120, 13147), False, 'import itertools\n'), ((14909, 14924), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (14922, 14924), False, 'import torch\n'), ((15399, 15426), 'numpy.expand_dims', 'np.expand_dims', (['feats_np', '(0)'], {}), '(feats_np, 0)\n', (15413, 15426), True, 'import numpy as np\n'), ((15663, 15696), 'smqtk_core.configuration.to_config_dict', 'to_config_dict', (['self.image_reader'], {}), '(self.image_reader)\n', (15677, 15696), False, 'from smqtk_core.configuration import from_config_dict, make_default_config, to_config_dict\n'), ((18509, 18524), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (18522, 18524), False, 'import torch\n'), ((19037, 19064), 'numpy.expand_dims', 'np.expand_dims', (['feats_np', '(0)'], {}), '(feats_np, 0)\n', (19051, 19064), True, 'import numpy as np\n'), ((8316, 8369), 'torch.load', 'torch.load', (['self.weights_filepath'], {'map_location': '"""cpu"""'}), "(self.weights_filepath, map_location='cpu')\n", (8326, 8369), False, 'import torch\n'), ((9061, 9096), 'smqtk_descriptors.utils.pytorch_utils.load_state_dict', 'load_state_dict', (['module', 'checkpoint'], {}), '(module, checkpoint)\n', (9076, 9096), False, 'from smqtk_descriptors.utils.pytorch_utils import load_state_dict\n'), ((9860, 9914), 'smqtk_descriptors.utils.parallel.parallel_map', 'parallel_map', (['ir_load', 'data_iter'], {'cores': 'i_load_threads'}), '(ir_load, data_iter, cores=i_load_threads)\n', (9872, 9914), False, 'from smqtk_descriptors.utils.parallel import parallel_map\n'), ((14432, 14475), 'itertools.islice', 'itertools.islice', (['tfed_mat_iter', 'batch_size'], {}), '(tfed_mat_iter, batch_size)\n', (14448, 14475), False, 'import itertools\n')]
import logging import numpy as np import os import pandas as pd import sqlite3 root_path = os.path.dirname(os.path.realpath(__file__)) runlog = logging.getLogger('runlog') alglog = logging.getLogger('alglog') def drillinginfo(file): """ Reads the production data file in the drillinginfo.com format. :param file: :return: production """ runlog.info('READ: Production data from drillinginfo.com from file: {0}'.format(file)) def production_monthyear(file): """ Reads the production data from the month (column) by year (row) data into a dataframe. :param file: File location :type file: str :return: Production Data Table :rtype: dataframe """ runlog.info('READ: Production data table from file: {0}.'.format(file)) try: df = pd.read_csv(file, delimiter=',', header=0, dtype=np.float64, names=['Year', 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December', 'Total']) except FileNotFoundError: runlog.error('READ: File {0} does not exist'.format(file)) raise FileNotFoundError('File {0} does not exist'.format(file)) return df def production_by_month(dataframe=None, file=None): """ Converts datafrom table :param dataframe: Production Dataframe :type dataframe: dataframe :param file: File location :type file: str :return: Production data by month :rtype: numpy.array """ if not isinstance(dataframe, pd.DataFrame) and file is None: runlog.error('READ: Missing args') raise ValueError('READ: Missing args.') if not isinstance(dataframe, pd.DataFrame) or dataframe.empty: dataframe = production_monthyear(file) year = list() production = list() for y in range(0, len(dataframe.Year)): for m in range(1, 13): year.append(dataframe.iloc[y][0] + m / 12) production.append(dataframe.iloc[y][m]) return np.array([year, production]) def read_file(file): runlog.info('Read from {0} file.'.format(file)) txt_file = list() f = open(file, 'r', encoding='utf-8-sig') for line in f: txt_file.append(line.strip().split(',')) f.close() return txt_file def open_database(file=None): if file is None: runlog.error('DATABASE: Missing file input.') raise FileNotFoundError('DATABASE: Missing file input.') runlog.info('DATABASE: Opening {0} database.'.format(file)) try: conn = sqlite3.connect(file) except sqlite3.InterfaceError: runlog.error('DATABASE: Database interface error.') raise sqlite3.InterfaceError else: cursor = conn.cursor() runlog.info('DATABASE: Database {0} opened.'.format(file)) return cursor, conn def close_database(cursor, conn): cursor.close() conn.close() runlog.info('DATABASE: Database closed.')
[ "pandas.read_csv", "os.path.realpath", "sqlite3.connect", "numpy.array", "logging.getLogger" ]
[((145, 172), 'logging.getLogger', 'logging.getLogger', (['"""runlog"""'], {}), "('runlog')\n", (162, 172), False, 'import logging\n'), ((182, 209), 'logging.getLogger', 'logging.getLogger', (['"""alglog"""'], {}), "('alglog')\n", (199, 209), False, 'import logging\n'), ((108, 134), 'os.path.realpath', 'os.path.realpath', (['__file__'], {}), '(__file__)\n', (124, 134), False, 'import os\n'), ((2040, 2068), 'numpy.array', 'np.array', (['[year, production]'], {}), '([year, production])\n', (2048, 2068), True, 'import numpy as np\n'), ((798, 1013), 'pandas.read_csv', 'pd.read_csv', (['file'], {'delimiter': '""","""', 'header': '(0)', 'dtype': 'np.float64', 'names': "['Year', 'January', 'February', 'March', 'April', 'May', 'June', 'July',\n 'August', 'September', 'October', 'November', 'December', 'Total']"}), "(file, delimiter=',', header=0, dtype=np.float64, names=['Year',\n 'January', 'February', 'March', 'April', 'May', 'June', 'July',\n 'August', 'September', 'October', 'November', 'December', 'Total'])\n", (809, 1013), True, 'import pandas as pd\n'), ((2577, 2598), 'sqlite3.connect', 'sqlite3.connect', (['file'], {}), '(file)\n', (2592, 2598), False, 'import sqlite3\n')]
#! /usr/bin/env python2.6 import matplotlib matplotlib.use('Agg') import denudationRateAnalysis as dra import numpy as np data = dra.read_csv('portengadata.csv') del(data[0]) ksn_vec, area_vec = dra.calculate_ksn_for_data(data,1000000,0.6) np.savez_compressed('ksn_area_data_0_6.npz', ksn_vec = ksn_vec, area_vec = area_vec)
[ "numpy.savez_compressed", "matplotlib.use", "denudationRateAnalysis.read_csv", "denudationRateAnalysis.calculate_ksn_for_data" ]
[((45, 66), 'matplotlib.use', 'matplotlib.use', (['"""Agg"""'], {}), "('Agg')\n", (59, 66), False, 'import matplotlib\n'), ((132, 164), 'denudationRateAnalysis.read_csv', 'dra.read_csv', (['"""portengadata.csv"""'], {}), "('portengadata.csv')\n", (144, 164), True, 'import denudationRateAnalysis as dra\n'), ((198, 244), 'denudationRateAnalysis.calculate_ksn_for_data', 'dra.calculate_ksn_for_data', (['data', '(1000000)', '(0.6)'], {}), '(data, 1000000, 0.6)\n', (224, 244), True, 'import denudationRateAnalysis as dra\n'), ((244, 329), 'numpy.savez_compressed', 'np.savez_compressed', (['"""ksn_area_data_0_6.npz"""'], {'ksn_vec': 'ksn_vec', 'area_vec': 'area_vec'}), "('ksn_area_data_0_6.npz', ksn_vec=ksn_vec, area_vec=area_vec\n )\n", (263, 329), True, 'import numpy as np\n')]
"""Generates some data from random gaussian blobs and renders it""" import matplotlib.pyplot as plt import matplotlib.colors as mcolors import pca3dvis.pcs as pcs import pca3dvis.worker as worker import numpy as np FEATURES = 10 """The embedded space of the generated data. Every later snapshot has one more feature just to see that doesn't hurt anything""" CLUSTERS = 5 """How many clusters are made in the embedding space""" SNAPSHOTS = 2 """How many "snapshots" we generate""" SAMPLES_PER_CLUST = 200 """How many samples in each cluster""" CLUST_STD = 0.2 """Standard deviation of each cluster""" DRAFT = True """If draft settings are used for the video (ie. lower quality, but faster)""" def gaus_ball(center: np.ndarray, std: int, num_samples: int): """Produces a gaussian ball with the given center and std deviation""" return ( np.random.randn(num_samples, center.shape[0]).astype(center.dtype) * std + center ) def _main(): # First generate some data! datas = [] for snap in range(SNAPSHOTS): # We are looping over each of the snapshots we have. Since we are # generating points randomly, these snapshots are meaningless, but # we will see how these points are rendered centers = np.random.uniform(-2, 2, (CLUSTERS, FEATURES + snap)) # Get a center for each cluster uniformly on a cube with sidelengths # 4 centered at the origin data = np.concatenate( tuple( gaus_ball(cent, CLUST_STD, SAMPLES_PER_CLUST) for cent in centers ), 0 ) # Sample 200 points from each cluster and append them to the data # (but faster) datas.append(data) lbls = np.concatenate( tuple( np.zeros((SAMPLES_PER_CLUST,), data.dtype) + i for i in range(CLUSTERS) ), 0 ) # Each cluster has its own label cmap = plt.get_cmap('Set1') markers = [ # An array with 1 marker for each point ( # The first marker np.ones(lbls.shape, dtype='bool'), # a mask containing every point { 'c': lbls, # color these points based on their label 'cmap': cmap, # to decide to color from the label, use the colormap 's': 20, # the points should be around 20px 'marker': 'o', # use a circle to represent these points 'norm': mcolors.Normalize(0, CLUSTERS - 1) # the smallest label is 0, largest is CLUSTERS-1 } ) ] proj = pcs.get_pc_trajectory(datas, lbls) # This performs linear dimensionality-reduction using principal component # analysis to get the three-dimensional points we can actually plot worker.generate( proj, # Plot the points we found markers, # use the markers we made earlier ['Gaussian Balls (1)', 'Gaussian Balls (2)'], # title the different slices as so 'out/examples/gaus_balls', # store the result in this folder DRAFT # determines if we should store low quality (if True) or high quality (if False) ) # That's it! if __name__ == '__main__': _main()
[ "numpy.random.uniform", "matplotlib.pyplot.get_cmap", "matplotlib.colors.Normalize", "numpy.random.randn", "pca3dvis.worker.generate", "numpy.zeros", "numpy.ones", "pca3dvis.pcs.get_pc_trajectory" ]
[((2019, 2039), 'matplotlib.pyplot.get_cmap', 'plt.get_cmap', (['"""Set1"""'], {}), "('Set1')\n", (2031, 2039), True, 'import matplotlib.pyplot as plt\n'), ((2667, 2701), 'pca3dvis.pcs.get_pc_trajectory', 'pcs.get_pc_trajectory', (['datas', 'lbls'], {}), '(datas, lbls)\n', (2688, 2701), True, 'import pca3dvis.pcs as pcs\n'), ((2861, 2975), 'pca3dvis.worker.generate', 'worker.generate', (['proj', 'markers', "['Gaussian Balls (1)', 'Gaussian Balls (2)']", '"""out/examples/gaus_balls"""', 'DRAFT'], {}), "(proj, markers, ['Gaussian Balls (1)', 'Gaussian Balls (2)'],\n 'out/examples/gaus_balls', DRAFT)\n", (2876, 2975), True, 'import pca3dvis.worker as worker\n'), ((1300, 1353), 'numpy.random.uniform', 'np.random.uniform', (['(-2)', '(2)', '(CLUSTERS, FEATURES + snap)'], {}), '(-2, 2, (CLUSTERS, FEATURES + snap))\n', (1317, 1353), True, 'import numpy as np\n'), ((2140, 2173), 'numpy.ones', 'np.ones', (['lbls.shape'], {'dtype': '"""bool"""'}), "(lbls.shape, dtype='bool')\n", (2147, 2173), True, 'import numpy as np\n'), ((2536, 2570), 'matplotlib.colors.Normalize', 'mcolors.Normalize', (['(0)', '(CLUSTERS - 1)'], {}), '(0, CLUSTERS - 1)\n', (2553, 2570), True, 'import matplotlib.colors as mcolors\n'), ((877, 922), 'numpy.random.randn', 'np.random.randn', (['num_samples', 'center.shape[0]'], {}), '(num_samples, center.shape[0])\n', (892, 922), True, 'import numpy as np\n'), ((1852, 1894), 'numpy.zeros', 'np.zeros', (['(SAMPLES_PER_CLUST,)', 'data.dtype'], {}), '((SAMPLES_PER_CLUST,), data.dtype)\n', (1860, 1894), True, 'import numpy as np\n')]
import numpy as np from pendulum.pendulum import Pendulum2D import matplotlib.pyplot as plt h = 0.001 # [s] Integration step t0 = 0 # [s] Starting time tf = 10 # [s] End time g = 9.81 # [m/s^2] Gravitational acceleration L = 1 # [m] Pendulum length theta_0 = np.pi/2 # ['] Pendulum Starting position omega_0 = np.pi/10 # [rad/s] Pendulum starting speed # Pre-initialize matrices time = np.linspace(t0, tf, int((tf-t0)/h)) theta = np.zeros(np.shape(time)) omega = np.zeros(np.shape(time)) # Insert initial conditions in vectors theta[0] = theta_0 omega[0] = omega_0 p = Pendulum2D(h, g, L, theta_0, omega_0, t0) for num, t in enumerate(time[:-1]): p.iterate() theta[num+1] = p.theta omega[num+1] = p.omega # Translate radians to degrees theta = theta*180/np.pi omega = omega*180/np.pi plt.figure() plt.title(r"Phase Space Diagram($\theta,\omega$)") plt.plot(theta, omega, "k-", linewidth=1) plt.xlabel(r"$\theta$ [$\degree$]") plt.ylabel(r"$\omega$ [$\degree/s$]") plt.figure() plt.title(r"Position over time $\theta(t)$") plt.plot(time, theta, "k.-", linewidth=1, markersize=10) plt.xlabel("t [s]") plt.ylabel(r"$\theta(t)$ [$\degree$]") plt.show()
[ "matplotlib.pyplot.title", "matplotlib.pyplot.show", "pendulum.pendulum.Pendulum2D", "matplotlib.pyplot.plot", "numpy.shape", "matplotlib.pyplot.figure", "matplotlib.pyplot.ylabel", "matplotlib.pyplot.xlabel" ]
[((668, 709), 'pendulum.pendulum.Pendulum2D', 'Pendulum2D', (['h', 'g', 'L', 'theta_0', 'omega_0', 't0'], {}), '(h, g, L, theta_0, omega_0, t0)\n', (678, 709), False, 'from pendulum.pendulum import Pendulum2D\n'), ((898, 910), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (908, 910), True, 'import matplotlib.pyplot as plt\n'), ((911, 962), 'matplotlib.pyplot.title', 'plt.title', (['"""Phase Space Diagram($\\\\theta,\\\\omega$)"""'], {}), "('Phase Space Diagram($\\\\theta,\\\\omega$)')\n", (920, 962), True, 'import matplotlib.pyplot as plt\n'), ((962, 1003), 'matplotlib.pyplot.plot', 'plt.plot', (['theta', 'omega', '"""k-"""'], {'linewidth': '(1)'}), "(theta, omega, 'k-', linewidth=1)\n", (970, 1003), True, 'import matplotlib.pyplot as plt\n'), ((1004, 1040), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""$\\\\theta$ [$\\\\degree$]"""'], {}), "('$\\\\theta$ [$\\\\degree$]')\n", (1014, 1040), True, 'import matplotlib.pyplot as plt\n'), ((1040, 1078), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""$\\\\omega$ [$\\\\degree/s$]"""'], {}), "('$\\\\omega$ [$\\\\degree/s$]')\n", (1050, 1078), True, 'import matplotlib.pyplot as plt\n'), ((1079, 1091), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (1089, 1091), True, 'import matplotlib.pyplot as plt\n'), ((1092, 1136), 'matplotlib.pyplot.title', 'plt.title', (['"""Position over time $\\\\theta(t)$"""'], {}), "('Position over time $\\\\theta(t)$')\n", (1101, 1136), True, 'import matplotlib.pyplot as plt\n'), ((1137, 1193), 'matplotlib.pyplot.plot', 'plt.plot', (['time', 'theta', '"""k.-"""'], {'linewidth': '(1)', 'markersize': '(10)'}), "(time, theta, 'k.-', linewidth=1, markersize=10)\n", (1145, 1193), True, 'import matplotlib.pyplot as plt\n'), ((1194, 1213), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""t [s]"""'], {}), "('t [s]')\n", (1204, 1213), True, 'import matplotlib.pyplot as plt\n'), ((1214, 1253), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""$\\\\theta(t)$ [$\\\\degree$]"""'], {}), "('$\\\\theta(t)$ [$\\\\degree$]')\n", (1224, 1253), True, 'import matplotlib.pyplot as plt\n'), ((1254, 1264), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (1262, 1264), True, 'import matplotlib.pyplot as plt\n'), ((536, 550), 'numpy.shape', 'np.shape', (['time'], {}), '(time)\n', (544, 550), True, 'import numpy as np\n'), ((569, 583), 'numpy.shape', 'np.shape', (['time'], {}), '(time)\n', (577, 583), True, 'import numpy as np\n')]
import numpy as np import math eye_vec = np.array([0, 0, 0]) at_vec = np.array([0, 0, -1]) up_vec = np.array([0, 1, 0]) viewport = np.array([0, 0 , 800, 600]) coordinates = (np.array([10, 20 ,100, 0])) near = 1 far = 100 def norm(vector): return vector/np.sqrt(np.sum(np.square(vector))) def view_matrix(eye, at, up): z_axis = norm(eye-at) x_axis = norm(np.cross(up, z_axis)) y_axis = np.cross(z_axis, x_axis) x_pos = np.dot(x_axis, eye) y_pos = np.dot(y_axis, eye) z_pos = np.dot(z_axis, eye) x = np.append(x_axis, x_pos) y = np.append(y_axis, y_pos) z = np.append(z_axis, z_pos) view = np.array([x, y, z, np.array([0, 0, 0, 1])]) return np.transpose(view) def projection_matrix(aspect_ratio, fov, near, far): projection = np.eye(4,4) projection[0][0] = 1/math.tan(fov/2)/aspect_ratio projection[1][1] = 1/math.tan(fov/2) projection[2][2] = far / (far - near) projection[2][3] = - 2 * far * near / (far - near) projection[3][2] = -1 return projection def unproject(win_x, win_y, win_z, view, projection, viewport): A = np.matmul(projection, view).astype(dtype=np.float32) M = np.linalg.inv(A) IN = np.empty((4)) IN[0] = (win_x - viewport[0])/viewport[2]*2.0 - 1.0 IN[1] = (win_y - viewport[1])/viewport[3]*2.0 - 1.0 IN[2] = 2.0*win_z - 1.0 OUT = np.matmul(M, IN) return OUT[0]*OUT[3], OUT[1]*OUT[3], OUT[2]*OUT[3] view = view_matrix(eye_vec, at_vec, up_vec) projection = projection_matrix(800/600, math.radians(40.0), 1.0, 10.0) print(unproject(0, 0, 10, view, projection, viewport))
[ "numpy.eye", "math.radians", "numpy.empty", "math.tan", "numpy.square", "numpy.cross", "numpy.transpose", "numpy.append", "numpy.array", "numpy.linalg.inv", "numpy.matmul", "numpy.dot" ]
[((42, 61), 'numpy.array', 'np.array', (['[0, 0, 0]'], {}), '([0, 0, 0])\n', (50, 61), True, 'import numpy as np\n'), ((71, 91), 'numpy.array', 'np.array', (['[0, 0, -1]'], {}), '([0, 0, -1])\n', (79, 91), True, 'import numpy as np\n'), ((101, 120), 'numpy.array', 'np.array', (['[0, 1, 0]'], {}), '([0, 1, 0])\n', (109, 120), True, 'import numpy as np\n'), ((132, 158), 'numpy.array', 'np.array', (['[0, 0, 800, 600]'], {}), '([0, 0, 800, 600])\n', (140, 158), True, 'import numpy as np\n'), ((175, 201), 'numpy.array', 'np.array', (['[10, 20, 100, 0]'], {}), '([10, 20, 100, 0])\n', (183, 201), True, 'import numpy as np\n'), ((404, 428), 'numpy.cross', 'np.cross', (['z_axis', 'x_axis'], {}), '(z_axis, x_axis)\n', (412, 428), True, 'import numpy as np\n'), ((441, 460), 'numpy.dot', 'np.dot', (['x_axis', 'eye'], {}), '(x_axis, eye)\n', (447, 460), True, 'import numpy as np\n'), ((473, 492), 'numpy.dot', 'np.dot', (['y_axis', 'eye'], {}), '(y_axis, eye)\n', (479, 492), True, 'import numpy as np\n'), ((505, 524), 'numpy.dot', 'np.dot', (['z_axis', 'eye'], {}), '(z_axis, eye)\n', (511, 524), True, 'import numpy as np\n'), ((533, 557), 'numpy.append', 'np.append', (['x_axis', 'x_pos'], {}), '(x_axis, x_pos)\n', (542, 557), True, 'import numpy as np\n'), ((566, 590), 'numpy.append', 'np.append', (['y_axis', 'y_pos'], {}), '(y_axis, y_pos)\n', (575, 590), True, 'import numpy as np\n'), ((599, 623), 'numpy.append', 'np.append', (['z_axis', 'z_pos'], {}), '(z_axis, z_pos)\n', (608, 623), True, 'import numpy as np\n'), ((690, 708), 'numpy.transpose', 'np.transpose', (['view'], {}), '(view)\n', (702, 708), True, 'import numpy as np\n'), ((780, 792), 'numpy.eye', 'np.eye', (['(4)', '(4)'], {}), '(4, 4)\n', (786, 792), True, 'import numpy as np\n'), ((1167, 1183), 'numpy.linalg.inv', 'np.linalg.inv', (['A'], {}), '(A)\n', (1180, 1183), True, 'import numpy as np\n'), ((1194, 1205), 'numpy.empty', 'np.empty', (['(4)'], {}), '(4)\n', (1202, 1205), True, 'import numpy as np\n'), ((1359, 1375), 'numpy.matmul', 'np.matmul', (['M', 'IN'], {}), '(M, IN)\n', (1368, 1375), True, 'import numpy as np\n'), ((1520, 1538), 'math.radians', 'math.radians', (['(40.0)'], {}), '(40.0)\n', (1532, 1538), False, 'import math\n'), ((369, 389), 'numpy.cross', 'np.cross', (['up', 'z_axis'], {}), '(up, z_axis)\n', (377, 389), True, 'import numpy as np\n'), ((871, 888), 'math.tan', 'math.tan', (['(fov / 2)'], {}), '(fov / 2)\n', (879, 888), False, 'import math\n'), ((654, 676), 'numpy.array', 'np.array', (['[0, 0, 0, 1]'], {}), '([0, 0, 0, 1])\n', (662, 676), True, 'import numpy as np\n'), ((817, 834), 'math.tan', 'math.tan', (['(fov / 2)'], {}), '(fov / 2)\n', (825, 834), False, 'import math\n'), ((1106, 1133), 'numpy.matmul', 'np.matmul', (['projection', 'view'], {}), '(projection, view)\n', (1115, 1133), True, 'import numpy as np\n'), ((274, 291), 'numpy.square', 'np.square', (['vector'], {}), '(vector)\n', (283, 291), True, 'import numpy as np\n')]
import matplotlib.pyplot as plt import pandas as pd import os import json import urllib.request as request import numpy as np from time import time from datetime import datetime, timedelta from math import log # COSTANTI ############################################################################################ # URL da cui scaricare i dati necessari URLS = { "nazionale": "https://raw.githubusercontent.com/pcm-dpc/COVID-19/master/dati-andamento-nazionale/dpc-covid19-ita-andamento-nazionale.csv", "regioni": "https://raw.githubusercontent.com/pcm-dpc/COVID-19/master/dati-regioni/dpc-covid19-ita-regioni.csv", "vaccini_summary": "https://raw.githubusercontent.com/italia/covid19-opendata-vaccini/master/dati/vaccini-summary-latest.csv", "anagrafica_vaccini_summary": "https://raw.githubusercontent.com/italia/covid19-opendata-vaccini/master/dati/anagrafica-vaccini-summary-latest.csv", "somministrazioni_vaccini_summary": "https://raw.githubusercontent.com/italia/covid19-opendata-vaccini/master/dati/somministrazioni-vaccini-summary-latest.csv", "consegne_vaccini": "https://raw.githubusercontent.com/italia/covid19-opendata-vaccini/master/dati/consegne-vaccini-latest.csv", "somministrazioni_vaccini": "https://raw.githubusercontent.com/italia/covid19-opendata-vaccini/master/dati/somministrazioni-vaccini-latest.csv", "monitoraggi_iss": "https://raw.githubusercontent.com/sphoneix22/monitoraggi-ISS/main/dati/monitoraggio-nazionale.csv", "monitoraggi_iss_regioni": "https://raw.githubusercontent.com/sphoneix22/monitoraggi-ISS/main/dati/monitoraggio-regioni.csv", "agenas": "https://raw.githubusercontent.com/ondata/covid19italia/master/webservices/agenas/processing/postiletto-e-ricoverati-areaNonCritica_date_dw.csv" } # Colonne che necessitano la conversione in formato datetime (tutti i csv) DATETIME_COLUMNS = ["data", "data_somministrazione", "data_consegna", "inizio_range", "fine_range", "data_report"] REGIONI = [ "Abruzzo", "Basilicata", "Calabria", "Campania", "Emilia-Romagna", "<NAME>", "Lazio", "Liguria", "Lombardia", "Marche", "Molise", "<NAME>", "<NAME>", "Piemonte", "Puglia", "Sardegna", "Sicilia", "Toscana", "Umbria", "Valle d'Aosta", "Veneto" ] FASCE_POPOLAZIONE = { "12-19": { "nazionale": 4574015, "Abruzzo": 92684, "Basilicata": 41943, "Calabria": 149525, "Campania": 509030, "Emilia-Romagna": 324726, "<NAME>": 84946, "Lazio": 429319, "Liguria": 101710, "Lombardia": 765276, "Marche": 110094, "Molise": 20956, "<NAME>": 46311, "<NAME>": 44701, "Piemonte": 307148, "Puglia": 321751, "Sardegna": 109048, "Sicilia": 404722, "Toscana": 263891, "Umbria": 62519, "Valle d'Aosta": 9465, "Veneto": 374250 }, "20-29": { "nazionale": 6084382, "Abruzzo": 130083, "Basilicata": 61183, "Calabria": 213889, "Campania": 693479, "Emilia-Romagna": 420660, "<NAME>": 109351, "Lazio": 564461, "Liguria": 136323, "Lombardia": 986159, "Marche": 146739, "Molise": 32122, "<NAME>": 61094, "<NAME>": 57755, "Piemonte": 406190, "Puglia": 439275, "Sardegna": 152275, "Sicilia": 559157, "Toscana": 339743, "Umbria": 339743, "Valle d'Aosta": 11870, "Veneto": 481226 }, "30-39": { "nazionale": 7552646, "Abruzzo": 150713, "Basilicata": 65204, "Calabria": 236668, "Campania": 715258, "Emilia-Romagna": 501241, "<NAME>": 125629, "Lazio": 682708, "Liguria": 147602, "Lombardia": 1164199, "Marche": 166387, "Molise": 34661, "<NAME>": 63127, "<NAME>": 61062, "Piemonte": 459367, "Puglia": 460961, "Sardegna": 185432, "Sicilia": 589747, "Toscana": 401488, "Umbria": 97163, "<NAME>'Aosta": 13174, "Veneto": 532841 }, "40-49": { "nazionale": 8937229, "Abruzzo": 190060, "Basilicata": 78467, "Calabria": 266417, "Campania": 835597, "Emilia-Romagna": 693312, "<NAME>": 178677, "Lazio": 906328, "Liguria": 212370, "Lombardia": 1545073, "Marche": 224450, "Molise": 42214, "<NAME>": 75664, "<NAME>": 78088, "Piemonte": 632745, "Puglia": 583292, "Sardegna": 250930, "Sicilia": 698439, "Toscana": 556667, "Umbria": 127832, "Valle d'Aosta": 18555, "Veneto": 742052 }, "50-59": { "nazionale": 9414195, "Abruzzo": 204157, "Basilicata": 605586, "Calabria": 286804, "Campania": 868684, "Emilia-Romagna": 704097, "<NAME>": 196083, "Lazio": 932830, "Liguria": 252685, "Lombardia": 1592109, "Marche": 236194, "Molise": 47443, "<NAME>": 83539, "<NAME>": 85805, "Piemonte": 688698, "Puglia": 605586, "Sardegna": 266068, "Sicilia": 732965, "Toscana": 587110, "Umbria": 135299, "Valle d'Aosta": 20757, "Veneto": 799460 }, "60-69": { "nazionale": 7364364, "Abruzzo": 167705, "Basilicata": 72817, "Calabria": 241215, "Campania": 670867, "Emilia-Romagna": 542211, "<NAME>": 155789, "Lazio": 697089, "Liguria": 202775, "Lombardia": 1189118, "Marche": 193166, "Molise": 40509, "<NAME>": 57041, "<NAME>": 67027, "Piemonte": 558231, "Puglia": 490900, "Sardegna": 223641, "Sicilia": 601201, "Toscana": 463253, "Umbria": 110539, "<NAME>'Aosta": 16060, "Veneto": 603210 }, "70-79": { "nazionale": 5968373, "Abruzzo": 130572, "Basilicata": 51805, "Calabria": 175208, "Campania": 484380, "Emilia-Romagna": 457129, "<NAME>": 141409, "Lazio": 552007, "Liguria": 186034, "Lombardia": 996209, "Marche": 155941, "Molise": 30291, "<NAME>": 46613, "<NAME>": 52316, "Piemonte": 477416, "Puglia": 390534, "Sardegna": 170857, "Sicilia": 456965, "Toscana": 410151, "Umbria": 95004, "Valle d'Aosta": 13089, "Veneto": 494443 }, "80-89": { "nazionale": 3628160, "Abruzzo": 84488, "Basilicata": 36107, "Calabria": 107720, "Campania": 255273, "Emilia-Romagna": 297666, "<NAME>": 83307, "Lazio": 331378, "Liguria": 125810, "Lombardia": 609477, "Marche": 107825, "Molise": 21038, "<NAME>": 27108, "<NAME>": 30464, "Piemonte": 306712, "Puglia": 222224, "Sardegna": 95172, "Sicilia": 263130, "Toscana": 259653, "Umbria": 62778, "Valle d'Aosta": 7800, "Veneto": 293030 }, "90+": { "nazionale": 791543, "Abruzzo": 19515, "Basilicata": 7823, "Calabria": 23058, "Campania": 49044, "Emilia-Romagna": 71687, "<NAME>": 20186, "Lazio": 69227, "Liguria": 30159, "Lombardia": 128163, "Marche": 25540, "Molise": 5219, "<NAME>": 6165, "<NAME>": 7922, "Piemonte": 64688, "Puglia": 45902, "Sardegna": 21111, "Sicilia": 52785, "Toscana": 60936, "Umbria": 15139, "<NAME>": 1764, "Veneto": 65510 }, "totale": { "nazionale": 59641488, "Abruzzo": 1293941, "Basilicata": 553254, "Calabria": 1894110, "Campania": 5712143, "Emilia-Romagna": 4464119, "<NAME>": 1206216, "Lazio": 5755700, "Liguria": 1524826, "Lombardia": 10027602, "Marche": 1512672, "Molise": 300516, "<NAME>": 532644, "<NAME>": 545425, "Piemonte": 4311217, "Puglia": 3953305, "Sardegna": 1611621, "Sicilia": 4875290, "Toscana": 3692555, "Umbria": 870165, "<NAME>": 125034, "Veneto": 4879133 } } # ultimo aggiornamento 23/4/21 CONSEGNE_VACCINI = { # comprende anche le dosi iniziali di PF/BT "Q1": { "Janssen": 0, "Moderna": 1330000, "Pfizer/BioNTech": 8749260, "AstraZeneca": 4116000 }, "Q2": { "Jannsen": 7307292, "Moderna": 4650000, "Pfizer/BioNTech": 32714370, "AstraZeneca": 10042500 } } # Contiene tutti i dati elaborati data = {} ############################################################################################ # UTILS ############################################################################################ def download_csv(name, url): dataframe = pd.read_csv(url) for col in DATETIME_COLUMNS: if col in dataframe: dataframe[col] = pd.to_datetime( dataframe[col], format="%Y-%m-%dT%H:%M:%S") # Codici ISTAT delle regioni # 01 PIEMONTE 02 <NAME>’AOSTA 03 LOMBARDIA 04 TRENTINO A. A. 05 VENETO 06 FRIULI V. G 07 LIGURIA 08 EMILIA ROMAGNA 09 TOSCANA # 10 UMBRIA 11 MARCHE 12 LAZIO 13 ABRUZZI 14 MOLISE 15 CAMPANIA 16 PUGLIE 17 BASILICATA 18 CALABRIA 19 SICILIA 20 SARDEGNA # 21 BOLZANO 22 TRENTO if name == "regioni": data["regioni"] = {} for codice_regione in [x for x in range(1, 23) if x != 4]: data_regione = dataframe[dataframe["codice_regione"] == codice_regione] data["regioni"][codice_regione] = {"completo": data_regione} data["regioni"][codice_regione]["maggio"] = data_regione[data_regione["data"] > datetime(year=2021, month=4, day=30)] elif name == "nazionale": data["nazionale"] = {"completo": dataframe, "maggio": dataframe[dataframe["data"] > datetime( year=2021, month=4, day=30)]} elif name == "somministrazioni_vaccini_summary": data["somministrazioni_vaccini_summary"] = {"nazionale": dataframe} data["somministrazioni_vaccini_summary"]["regioni"] = {} for codice_regione in [x for x in range(1, 22) if x != 4]: data_regione = dataframe[dataframe["codice_regione_ISTAT"] == codice_regione] data["somministrazioni_vaccini_summary"]["regioni"][codice_regione] = data_regione data["somministrazioni_vaccini_summary"]["regioni"][21] = dataframe[ dataframe["nome_area"] == "Provincia Autonoma Trento"] data["somministrazioni_vaccini_summary"]["regioni"][22] = dataframe[ dataframe["nome_area"] == "Provincia Autonoma Bolzano / Bozen"] elif name == "somministrazioni_vaccini": data["somministrazioni_vaccini"] = {"nazionale": dataframe} data["somministrazioni_vaccini"]["regioni"] = {} # In questo dataset le P.A. hanno lo stesso codice istat (4) ma differente denominazione for codice_regione in [x for x in range(1, 22) if x != 4]: data_regione = dataframe[dataframe["codice_regione_ISTAT"] == codice_regione] data["somministrazioni_vaccini"]["regioni"][codice_regione] = data_regione data["somministrazioni_vaccini"]["regioni"][21] = dataframe[ dataframe["nome_area"] == "Provincia Autonoma Trento"] data["somministrazioni_vaccini"]["regioni"][22] = dataframe[ dataframe["nome_area"] == "Provincia Autonoma Bolzano / Bozen"] elif name == "monitoraggi_iss_regioni": data["monitoraggi_iss_regioni"] = {} for regione in REGIONI: data_regione = dataframe[dataframe["regione"] == regione] data["monitoraggi_iss_regioni"][regione] = data_regione else: data[name] = dataframe def create_media_mobile(data): count = [] result = [] for el in data: count.append(el) result.append(sum(count) / len(count)) if len(count) == 7: count.pop(0) return result def create_delta(data): latest = 0 delta = [] for row in data: delta.append(row - latest) latest = row return delta def create_incidenza(data, regione): count = [] result = [] for row in data: count.append(row) result.append( (sum(count) / FASCE_POPOLAZIONE["totale"][regione]) * 100000) if len(count) == 7: count.pop(0) return result def shape_adjust(data): start = min([list(x.keys())[0] for x in data]) end = max([list(x.keys())[-1] for x in data]) current = start while current <= end: for el in data: if current not in el.keys(): el[current] = 0 current = current + timedelta(days=1) return data def order(data): start = min([list(x.keys())[0] for x in data]) end = max([list(x.keys())[-1] for x in data]) new_data = [{} for x in data] current = start while current <= end: for x in data: new_data[data.index(x)][current] = x[current] current += timedelta(days=1) return new_data def create_soglie(regione, ti=True): result = {} if regione == "nazionale": pl_ti = data["agenas"]["PL in Terapia Intensiva"].sum() pl_am = data["agenas"]["PL in Area Non Critica"].sum() else: regione_df = data["agenas"][data["agenas"]["Regioni"] == regione] pl_ti = regione_df["PL in Terapia Intensiva"].sum() pl_am = regione_df["PL in Area Non Critica"].sum() if ti: result[pl_ti / 100 * 30] = ["30% occupazione", "red"] result[pl_ti / 100 * 20] = ["20% occupazione", "orange"] result[pl_ti / 100 * 10] = ["10% occupazione", "yellow"] else: result[pl_am / 100 * 40] = ["40% occupazione", "red"] result[pl_am / 100 * 30] = ["30% occupazione", "orange"] result[pl_am / 100 * 15] = ["15% occupazione", "yellow"] return result # GRAFICI ############################################################################################ def plot(x, y, title, output, xlabel=None, ylabel=None, media_mobile=None, legend=None, color=None, grid="y", hline=None, vline=None, marker=None, footer=None, alpha=0.8, log=False): fig, ax = plt.subplots() line, = ax.plot(x, y, linestyle="solid", marker=marker, alpha=alpha) if media_mobile: ax.plot(x, media_mobile, color="orange") ax.legend(legend, prop={"size": 7}) if color: line.set_color(color) if grid: ax.grid(axis=grid) if hline: for el in hline: plt.axhline(el, 0, 1, label=hline[el][0], color=hline[el][1]) plt.fill_between(x, y, color='#539ecd') plt.legend(loc=1, fontsize="small") if vline: plt.axvline(vline, 0, 1, color="red") if log: plt.yscale("log") fig.autofmt_xdate() ax.set_title(title) ax.set_xlabel(xlabel) ax.set_ylabel(ylabel) plt.figtext(0.99, 0.01, footer, horizontalalignment='right') fig.savefig(CWD + output, dpi=200) plt.close('all') def stackplot(x, y1, y2, title, label, output, yticks=None, footer=None, y3=None): fig, ax = plt.subplots() if y3: ax.stackplot(x, y1, y2, y3, labels=label) else: ax.stackplot(x, y1, y2, labels=label) if yticks: ax.set_yticks(yticks) ax.set_title(title) ax.legend(label, loc="upper left", prop={"size": 7}) ax.grid(axis="y") fig.autofmt_xdate() plt.figtext(0.99, 0.01, footer, horizontalalignment='right') fig.savefig(CWD + output, dpi=200) plt.close('all') def deltaplot(x, y, title, output, footer=None): fig, ax = plt.subplots() color = ["orange" if x >= 0 else "red" for x in y] plt.vlines(x=x, ymin=0, ymax=y, color=color, alpha=0.7) ax.set_title(title) fig.autofmt_xdate() ax.grid(axis="y") plt.figtext(0.99, 0.01, footer, horizontalalignment='right') fig.savefig(CWD + output, dpi=200) plt.close('all') def barplot(x, y, title, output, horizontal=False, xticks=None, yticks=None, grid="y", bottom=None, ylabel=None, label1=None, label2=None, xticklabels=None, footer=None): fig, ax = plt.subplots() if horizontal: ax.barh(x, y, label=label1) else: ax.bar(x, y, label=label1) plt.title(title) if grid: ax.grid(axis=grid) if xticks: plt.xticks(xticks) if yticks: plt.yticks(yticks) if bottom and horizontal: ax.barh(x, bottom, bottom=y, label=label2) elif bottom: ax.bar(x, bottom, bottom=y, label=label2) if label1 or label2: plt.legend() if ylabel: ax.set_ylabel(ylabel) if xticklabels: plt.xticks([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) ax.set_xticklabels(xticklabels) plt.figtext(0.99, 0.01, footer, horizontalalignment='right') plt.tight_layout() fig.savefig(CWD + output, dpi=200) plt.close('all') def pieplot(slices, labels, title, output, footer=None): fig, ax = plt.subplots() ax.pie(slices, labels=labels) plt.title(title) plt.figtext(0.99, 0.01, footer, horizontalalignment='right') fig.savefig(CWD + output, dpi=200) plt.close('all') def grafico_vaccinati_fascia_anagrafica(x, prima_dose, seconda_dose, monodose, title, footer, output): fig, ax = plt.subplots() ax.bar(x, prima_dose, label="Prima dose") ax.bar(x, seconda_dose, bottom=prima_dose, label="Seconda dose") ax.bar(x, monodose, bottom=np.array(prima_dose) + np.array(seconda_dose), label="Monodose") ax.grid() plt.title(title) plt.figtext(0.99, 0.01, footer, horizontalalignment='right') plt.legend() fig.savefig(CWD + output, dpi=200) plt.close('all') def grafico_vaccini_fascia_eta(data, media_mobile, title, footer, output): fig, ax = plt.subplots() start = min([min(list(x.keys())) for x in data]) end = max([max(list(x.keys())) for x in data]) ordered_data = [{}, {}, {}, {}, {}, {}, {}, {}, {}] current = start while current <= end: for index in range(len(data)): ordered_data[index][current] = data[index][current] current = current + timedelta(days=1) xvalues = np.array(list(ordered_data[4].keys())) arrays = [np.array(list(x.values())) for x in ordered_data] ax.bar(xvalues, arrays[0], label="12-19") ax.bar(xvalues, arrays[1], label="20-29", bottom=arrays[0]) ax.bar(xvalues, arrays[2], label="30-39", bottom=arrays[0]+arrays[1]) ax.bar(xvalues, arrays[3], label="40-49", bottom=arrays[0]+arrays[1]+arrays[2]) ax.bar(xvalues, arrays[4], label="50-59", bottom=arrays[0]+arrays[1]+arrays[2]+arrays[3]) ax.bar(xvalues, arrays[5], label="60-69", bottom=arrays[0]+arrays[1]+arrays[2]+arrays[3]+arrays[4]) ax.bar(xvalues, arrays[6], label="70-79", bottom=arrays[0] + arrays[1]+arrays[2]+arrays[3]+arrays[4]+arrays[5]) ax.bar(xvalues, arrays[7], label="80-89", bottom=arrays[0] + arrays[1]+arrays[2]+arrays[3]+arrays[4]+arrays[5]+arrays[6]) ax.bar(xvalues, arrays[8], label="90+", bottom=arrays[0]+arrays[1] + arrays[2]+arrays[3]+arrays[4]+arrays[5]+arrays[6]+arrays[7]) ax.grid("y") ax.plot(media_mobile[0], media_mobile[1], color="black", linewidth=1, label="Media mobile settimanale") plt.title(title) plt.legend() plt.figtext(0.99, 0.01, footer, horizontalalignment='right') fig.autofmt_xdate() plt.gcf().axes[0].yaxis.get_major_formatter().set_scientific(False) fig.savefig(CWD + output, dpi=200) plt.close("all") def grafico_vaccini_fornitore(pfizer, moderna, astrazeneca, janssen, media_mobile, title, footer, output): fig, ax = plt.subplots() x_pfizer = list(pfizer.keys()) x_pfizer.sort() y_pfizer = [] y_moderna = [] y_astrazeneca = [] y_janssen = [] for x_value in x_pfizer: y_pfizer.append(pfizer[x_value]) y_moderna.append(moderna[x_value]) y_astrazeneca.append(astrazeneca[x_value]) y_janssen.append(janssen[x_value]) moderna_array = np.array(y_moderna) pfizer_array = np.array(y_pfizer) astrazeneca_array = np.array(y_astrazeneca) ax.bar(x_pfizer, y_pfizer, label="Pfizer/BioNTech") ax.bar(x_pfizer, y_moderna, bottom=y_pfizer, label="Moderna") ax.bar(x_pfizer, y_astrazeneca, bottom=moderna_array+pfizer_array, label="AstraZeneca") ax.bar(x_pfizer, y_janssen, bottom=astrazeneca_array + moderna_array+pfizer_array, label="Janssen") ax.grid(axis="y") ax.plot(media_mobile[0], media_mobile[1], color="black", linewidth=1, label="Media mobile settimanale") plt.title(title) plt.legend() plt.figtext(0.99, 0.01, footer, horizontalalignment='right') fig.autofmt_xdate() plt.gcf().axes[0].yaxis.get_major_formatter().set_scientific(False) fig.savefig(CWD + output, dpi=200) plt.close("all") def grafico_consegne_totale(consegne, consegne_previste, footer, output): fig, ax = plt.subplots() x_axis = np.arange(len(consegne.keys())) ax.ticklabel_format(useOffset=False, style='plain') ax.bar(x_axis - 0.2, consegne.values(), 0.35, label="Consegne avvenute") plt.title("Consegne totali vaccini (al 23/4/2021)") ax.grid() ax.bar(x_axis + 0.2, consegne_previste["Q2"].values(), 0.35, label="Consegne previste Q2", bottom=np.array(list( consegne_previste["Q1"].values()))) ax.bar(x_axis + 0.2, consegne_previste["Q1"].values(), 0.35, label="Consegne previste Q1") plt.xticks(x_axis, ["Janssen", "Moderna", "Pfizer/BioNTech", "AstraZeneca"]) plt.legend() plt.figtext(0.99, 0.01, footer, horizontalalignment='right') plt.tight_layout() fig.savefig(CWD + output, dpi=200) plt.close('all') def grafico_rt(x_rt, x_contagi, rt, contagi, title, footer, output): fig, ax = plt.subplots() ax.set_ylabel("Positivi giornalieri") ax2 = ax.twinx() ax2.set_ylabel("Valore R") ax.plot(x_contagi, contagi, alpha=0.4, linestyle="dashed") ax2.plot(x_rt, rt, marker=".") ax2.axhline(y=1, color="red", linestyle="dashed") fig.autofmt_xdate() ax.legend(["Nuovi positivi giornalieri"]) ax2.legend(["Andamento Rt"]) plt.title(title) plt.figtext(0.99, 0.01, footer, horizontalalignment='right') plt.grid() fig.savefig(CWD + output, dpi=200) plt.close('all') def grafico_vaccini_cumulativo(data, title, footer, output): fig, ax = plt.subplots() ax.plot(data[0].keys(), create_media_mobile( data[0].values()), label="12-19") ax.plot(data[1].keys(), create_media_mobile( data[1].values()), label="20-29") ax.plot(data[2].keys(), create_media_mobile( data[2].values()), label="30-39") ax.plot(data[3].keys(), create_media_mobile( data[3].values()), label="40-49") ax.plot(data[4].keys(), create_media_mobile( data[4].values()), label="50-59") ax.plot(data[5].keys(), create_media_mobile( data[5].values()), label="60-69") ax.plot(data[6].keys(), create_media_mobile( data[6].values()), label="70-79") ax.plot(data[7].keys(), create_media_mobile( data[7].values()), label="80-89") ax.plot(data[8].keys(), create_media_mobile(data[8].values()), label="90+") plt.title(title) plt.figtext(0.99, 0.01, footer, horizontalalignment='right') plt.legend() fig.autofmt_xdate() fig.savefig(CWD + output, dpi=200) plt.close('all') def grafico_doubling_time(data, title, footer, output, growth=False): doubling_times = [0, 0, 0, 0, 0, 0, 0] growth_rates = [0,0,0,0,0,0,0] i = 7 while i < len(data[1]): day = data[1].iat[i] last_week = data[1].iat[i-7] delta = (day-last_week)/last_week growth_rates.append(delta*100) doubling_times.append((log(2)/log(1+delta))*7) i += 1 fig, ax = plt.subplots() if growth: ax.plot(data[0], create_media_mobile(growth_rates), linestyle="-") else: ax.plot(data[0], doubling_times, linestyle="-", linewidth=3) ax.set_yticks(np.arange(-30, 30, 5)) ax.set_ylim([-30, 30]) plt.title(title) plt.figtext(0.99, 0.01, footer, horizontalalignment='right') plt.grid(True) fig.autofmt_xdate() fig.savefig(CWD + output, dpi=200) plt.close('all') ############################################################################################ def epidemia(): os.makedirs(f"{CWD}/graphs/epidemia", exist_ok=True) last_update = data["nazionale"]["completo"]["data"].iat[-1] summary = f"DATI NAZIONALI {last_update}\n\n" contagi_media = create_media_mobile( data["nazionale"]["completo"]["nuovi_positivi"]) # Grafico nuovi positivi print("Grafico nuovi positivi...") plot( data["nazionale"]["completo"]["data"], data["nazionale"]["completo"]["nuovi_positivi"], "Andamento contagi giornalieri", "/graphs/epidemia/nuovi_positivi.jpg", media_mobile=contagi_media, legend=["Contagi giornalieri", "Media mobile settimanale"], footer=f"Fonte dati: PCM-DPC | Ultimo aggiornamento: {last_update}" ) plot( data["nazionale"]["maggio"]["data"], data["nazionale"]["maggio"]["nuovi_positivi"], "Andamento contagi giornalieri (scala logaritmica)", "/graphs/epidemia/nuovi_positivi_log.jpg", media_mobile=create_media_mobile( data["nazionale"]["maggio"]["nuovi_positivi"]), legend=["Contagi giornalieri", "Media mobile settimanale"], footer=f"Fonte dati: PCM-DPC | Ultimo aggiornamento: {last_update}", log=True ) today = data["nazionale"]["completo"]["nuovi_positivi"].iat[-1] last_week = data["nazionale"]["completo"]["nuovi_positivi"].iat[-8] delta = (today-last_week)/last_week delta_perc = round(delta*100, 0) summary += "Nuovi positivi: {} ({:+}%)\n".format( today, delta_perc) if delta > 0: summary += "Tempo di raddoppio: {} giorni\n".format(round(log(2)/log(1+delta)*7, 0)) elif delta < 0: summary += "Tempo di dimezzamento: {} giorni\n".format(round(log(2)/log(1+abs(delta))*7, 0)) today = contagi_media[-1] last_week = contagi_media[-8] delta = (today-last_week)/last_week if delta > 0: summary += "Tempo di raddoppio (media 7 giorni): {} giorni\n".format(round(log(2)/log(1+delta)*7, 0)) elif delta < 0: summary += "Tempo di dimezzamento (media 7 giorni): {} giorni\n".format(round(log(2)/log(1+abs(delta))*7, 0)) # Stackplot ospedalizzati print("Grafico ospedalizzati...") plot( data["nazionale"]["completo"]["data"], data["nazionale"]["completo"]["ricoverati_con_sintomi"], "Occupazione area medica", "/graphs/epidemia/occupazione_am.jpg", footer=f"Fonte dati: PCM-DPC | Ultimo aggiornamento: {last_update}", hline=create_soglie("nazionale", ti=False) ) plot( data["nazionale"]["completo"]["data"], data["nazionale"]["completo"]["terapia_intensiva"], "Occupazione TI", "/graphs/epidemia/occupazione_ti.jpg", footer=f"Fonte dati: PCM-DPC | Ultimo aggiornamento: {last_update}", hline=create_soglie("nazionale") ) summary += "Ospedalizzati ordinari: {} ({}%)\nTerapie intensive: {} ({}%)\n".format( data["nazionale"]["completo"]["ricoverati_con_sintomi"].iat[-1], round(data["nazionale"]["completo"]["ricoverati_con_sintomi"].iat[-1] * 100 / data["agenas"]["PL in Area Non Critica"].sum(), 1), data["nazionale"]["completo"]["terapia_intensiva"].iat[-1], round(data["nazionale"]["completo"]["terapia_intensiva"].iat[-1] * 100 / data["agenas"]["PL in Terapia Intensiva"].sum(), 1) ) # Grafico ingressi in terapia intensiva print("Grafico ingressi TI...") media_ti = create_media_mobile( data["nazionale"]["completo"]["ingressi_terapia_intensiva"]) plot( data["nazionale"]["completo"]["data"], data["nazionale"]["completo"]["ingressi_terapia_intensiva"], "Ingressi giornalieri in terapia intensiva", "/graphs/epidemia/ingressi_ti.jpg", media_mobile=media_ti, legend=["Ingressi TI", "Media mobile settimanale"], footer=f"Fonte dati: PCM-DPC | Ultimo aggiornamento: {last_update}" ) plot( data["nazionale"]["maggio"]["data"], data["nazionale"]["maggio"]["ingressi_terapia_intensiva"], "Ingressi giornalieri in terapia intensiva (scala logaritmica)", "/graphs/epidemia/ingressi_ti_log.jpg", media_mobile=create_media_mobile( data["nazionale"]["maggio"]["ingressi_terapia_intensiva"]), legend=["Ingressi TI", "Media mobile settimanale"], footer=f"Fonte dati: PCM-DPC | Ultimo aggiornamento: {last_update}", log=True ) today = data["nazionale"]["completo"]["ingressi_terapia_intensiva"].iat[-1] last_week = data["nazionale"]["completo"]["ingressi_terapia_intensiva"].iat[-8] if last_week == 0: delta = 0 delta_perc = 0 else: delta = (today-last_week)/last_week delta_perc = round(delta*100, 0) summary += "Ingressi TI: {} ({:+}%)\n".format( today, delta_perc) if delta > 0: summary += "Tempo di raddoppio: {} giorni\n".format(round(log(2)/log(1+delta)*7), 0) elif delta < 0: summary += "Tempo di dimezzamento: {} giorni\n".format(round(log(2)/log(1+abs(delta))*7, 0)) today = media_ti[-1] last_week = media_ti[-8] if last_week == 0: delta = 0 delta_perc = 0 else: delta = (today-last_week)/last_week if delta > 0: summary += "Tempo di raddoppio (media 7 giorni): {} giorni\n".format(round(log(2)/log(1+delta)*7), 0) elif delta < 0: summary += "Tempo di dimezzamento (media 7 giorni): {} giorni\n".format(round(log(2)/log(1+abs(delta))*7, 0)) # Grafico variazione totale positivi print("Grafico variazione totale positivi...") deltaplot( data["nazionale"]["completo"]["data"], data["nazionale"]["completo"]["variazione_totale_positivi"], "Variazione giornaliera totale positivi", "/graphs/epidemia/variazione_totale_positivi.jpg", footer=f"Fonte dati: PCM-DPC | Ultimo aggiornamento: {last_update}" ) summary += "Variazione totale totale positivi: {}\n".format( data["nazionale"]["completo"]["variazione_totale_positivi"].iat[-1]) # Grafico variazione totale ospedalizzati print("Grafico variazione totale ospedalizzati...") delta = create_delta(data["nazionale"]["completo"]["totale_ospedalizzati"]) deltaplot( data["nazionale"]["completo"]["data"], delta, "Variazione totale ospedalizzati", "/graphs/epidemia/variazione_totale_ospedalizzati.jpg", footer=f"Fonte dati: PCM-DPC | Ultimo aggiornamento: {last_update}" ) summary += "Variazione totale ospedalizzati: {}\n".format(delta[-1]) # Grafico variazione occupazione TI print("Grafico variazione TI") delta = create_delta(data["nazionale"]["completo"]["terapia_intensiva"]) deltaplot( data["nazionale"]["completo"]["data"], delta, "Variazione occupazione TI", "/graphs/epidemia/variazione_ti.jpg", footer=f"Fonte dati: PCM-DPC | Ultimo aggiornamento: {last_update}" ) summary += "Variazione TI: {}\n".format(delta[-1]) # Grafico variazione totale ospedalizzati print("Grafico variazione ricoverati con sintomi...") delta = create_delta(data["nazionale"]["completo"] ["ricoverati_con_sintomi"]) deltaplot( data["nazionale"]["completo"]["data"], delta, "Variazione ospedalizzati ordinari", "/graphs/epidemia/variazione_ospedalizzati_ordinari.jpg", footer=f"Fonte dati: PCM-DPC | Ultimo aggiornamento: {last_update}" ) summary += "Variazione ricoverati con sintomi: {}\n".format(delta[-1]) # Grafico deceduti print("Grafico deceduti...") plot( data["nazionale"]["completo"]["data"], data["nazionale"]["completo"]["deceduti"], "<NAME>", "/graphs/epidemia/deceduti.jpg", color="black", footer=f"Fonte dati: PCM-DPC | Ultimo aggiornamento: {last_update}" ) summary += "Deceduti totali: {}\n".format( data["nazionale"]["completo"]["deceduti"].iat[-1]) # Grafico deceduti giornalieri print("Grafico deceduti giornalieri...") delta = create_delta(data["nazionale"]["completo"]["deceduti"]) plot( data["nazionale"]["completo"]["data"], delta, "Deceduti giornalieri", "/graphs/epidemia/deceduti_giornalieri.jpg", media_mobile=create_media_mobile( create_delta(data["nazionale"]["completo"]["deceduti"])), legend=["Deceduti giornalieri", "Media mobile settimanale"], color="black", footer=f"Fonte dati: PCM-DPC | Ultimo aggiornamento: {last_update}" ) delta_maggio = create_delta(data["nazionale"]["maggio"]["deceduti"]) plot( data["nazionale"]["maggio"]["data"], delta_maggio, "Deceduti giornalieri (scala logaritmica)", "/graphs/epidemia/deceduti_giornalieri_log.jpg", media_mobile=create_media_mobile( create_delta(data["nazionale"]["maggio"]["deceduti"])), legend=["Deceduti giornalieri", "Media mobile settimanale"], color="black", footer=f"Fonte dati: PCM-DPC | Ultimo aggiornamento: {last_update}", log=True ) today = delta[-1] last_week = delta[-8] delta_perc = round((today-last_week)/last_week*100, 0) summary += "Deceduti giornalieri: {} ({:+}%)\n".format( delta[-1], delta_perc) print("Grafico incidenza...") incidenza = create_incidenza( data["nazionale"]["completo"]["nuovi_positivi"], "nazionale") plot( data["nazionale"]["completo"]["data"], incidenza, "Incidenza di nuovi positivi ogni 100000 abitanti\nnell'arco di 7 giorni", "/graphs/epidemia/incidenza_contagio.jpg", footer=f"Fonte dati: PCM-DPC | Ultimo aggiornamento: {last_update}", hline={50: ["", "orange"], 150: ["", "red"]} ) today = incidenza[-1] last_week = incidenza[-8] delta = round((today-last_week)/last_week*100, 0) summary += f"Incidenza: {incidenza[-1]} ({delta:+}%)\n\n" print("Grafico rt") grafico_rt( data["monitoraggi_iss"]["fine_range"], data["nazionale"]["completo"]["data"], data["monitoraggi_iss"]["rt_puntuale"], data["nazionale"]["completo"]["nuovi_positivi"], "Andamento Rt nazionale", f"Fonte dati: ISS | Ultimo aggiornamento: {last_update}", "/graphs/epidemia/rt.jpg", ) print("Grafico doubling time") grafico_doubling_time( [ data["nazionale"]["maggio"]["data"], data["nazionale"]["maggio"]["nuovi_positivi"] ], "Tempo di raddoppio", f"Fonte dati: PCM-DPC | Ultimo aggiornamento: {last_update}", "/graphs/epidemia/tempo_raddoppio_maggio.jpg" ) grafico_doubling_time( [ data["nazionale"]["completo"]["data"], data["nazionale"]["completo"]["nuovi_positivi"] ], "Growth rates", f"Fonte dati: PCM-DPC | Ultimo aggiornamento: {last_update}", "/graphs/epidemia/growth_rates.jpg", growth=True ) summary += "DATI REGIONI\n\n" for regione in data["regioni"].keys(): denominazione_regione = data["regioni"][regione]["completo"]["denominazione_regione"].iloc[0] summary += f"{denominazione_regione}\n" contagi_media = create_media_mobile( data["regioni"][regione]["completo"]["nuovi_positivi"]) print(f"Regione {regione}...") print("Grafico nuovi positivi...") plot( data["regioni"][regione]["completo"]["data"], data["regioni"][regione]["completo"]["nuovi_positivi"], f"Andamento contagi giornalieri {denominazione_regione}", f"/graphs/epidemia/nuovi_positivi_{denominazione_regione}.jpg", media_mobile=contagi_media, legend=["Contagi giornalieri", "Media mobile settimanale"], footer=f"Fonte dati: PCM-DPC | Ultimo aggiornamento: {last_update}" ) plot( data["regioni"][regione]["maggio"]["data"], data["regioni"][regione]["maggio"]["nuovi_positivi"], f"Andamento contagi giornalieri {denominazione_regione} (scala log.)", f"/graphs/epidemia/nuovi_positivi_{denominazione_regione}_log.jpg", media_mobile=create_media_mobile( data["regioni"][regione]["maggio"]["nuovi_positivi"]), legend=["Contagi giornalieri", "Media mobile settimanale"], footer=f"Fonte dati: PCM-DPC | Ultimo aggiornamento: {last_update}", log=True ) today = data["regioni"][regione]["completo"]["nuovi_positivi"].iat[-1] last_week = data["regioni"][regione]["completo"]["nuovi_positivi"].iat[-8] delta = (today-last_week)/last_week delta_perc = round(delta*100, 0) summary += "Nuovi positivi: {} ({:+}%)\n".format( today, delta_perc) if delta > 0: summary += "Tempo di raddoppio: {} giorni\n".format(round(log(2)/log(1+delta)*7, 0)) elif delta < 0: summary += "Tempo di dimezzamento: {} giorni\n".format(round(log(2)/log(1+abs(delta))*7, 0)) today = contagi_media[-1] last_week = contagi_media[-8] delta = (today-last_week)/last_week if delta > 0: summary += "Tempo di raddoppio (media 7 giorni): {} giorni\n".format(round(log(2)/log(1+delta)*7, 0)) elif delta < 0: summary += "Tempo di dimezzamento (media 7 giorni): {} giorni\n".format(round(log(2)/log(1+abs(delta))*7, 0)) # Stackplot ospedalizzati print("Grafico ospedalizzati...") plot( data["regioni"][regione]["completo"]["data"], data["regioni"][regione]["completo"]["terapia_intensiva"], f"Occupazione TI - {denominazione_regione}", f"/graphs/epidemia/occupazione_ti_{denominazione_regione}.jpg", footer=f"Fonte dati: PCM-DPC | Ultimo aggiornamento: {last_update}", hline=create_soglie(denominazione_regione) ) plot( data["regioni"][regione]["completo"]["data"], data["regioni"][regione]["completo"]["ricoverati_con_sintomi"], f"Occupazione Area Medica - {denominazione_regione}", f"/graphs/epidemia/occupazione_am_{denominazione_regione}.jpg", footer=f"Fonte dati: PCM-DPC | Ultimo aggiornamento: {last_update}", hline=create_soglie(denominazione_regione, ti=False) ) agenas = data["agenas"][data["agenas"]["Regioni"] == denominazione_regione] occupazione_ti = round(data["regioni"][regione]["completo"]["terapia_intensiva"].iat[-1] * 100 / agenas["PL in Terapia Intensiva"].sum(), 1) occupazione_am = round(data["regioni"][regione]["completo"]["ricoverati_con_sintomi"].iat[-1] * 100 / agenas["PL in Area Non Critica"].sum(), 1) summary += "TI: {} ({}%)\nRicoverati con sintomi: {} ({}%)\n".format( data["regioni"][regione]["completo"]["terapia_intensiva"].iat[-1], occupazione_ti, data["regioni"][regione]["completo"]["ricoverati_con_sintomi"].iat[-1], occupazione_am ) # Grafico ingressi in terapia intensiva print("Grafico ingressi TI...") media_ti = create_media_mobile( data["regioni"][regione]["completo"]["ingressi_terapia_intensiva"]) plot( data["regioni"][regione]["completo"]["data"], data["regioni"][regione]["completo"]["ingressi_terapia_intensiva"], f"Ingressi giornalieri in terapia intensiva {denominazione_regione}", f"/graphs/epidemia/ingressi_ti_{denominazione_regione}.jpg", media_mobile=media_ti, legend=["Ingressi TI", "Media mobile settimanale"], footer=f"Fonte dati: PCM-DPC | Ultimo aggiornamento: {last_update}" ) plot( data["regioni"][regione]["maggio"]["data"], data["regioni"][regione]["maggio"]["ingressi_terapia_intensiva"], f"Ingressi giornalieri in terapia intensiva {denominazione_regione} (scala log.)", f"/graphs/epidemia/ingressi_ti_{denominazione_regione}_log.jpg", media_mobile=create_media_mobile( data["regioni"][regione]["maggio"]["ingressi_terapia_intensiva"]), legend=["Ingressi TI", "Media mobile settimanale"], footer=f"Fonte dati: PCM-DPC | Ultimo aggiornamento: {last_update}", log=True ) today = data["regioni"][regione]["completo"]["ingressi_terapia_intensiva"].iat[-1] last_week = data["regioni"][regione]["completo"]["ingressi_terapia_intensiva"].iat[-8] if last_week == 0: delta = 0 delta_perc = 0 else: delta = (today-last_week)/last_week delta_perc = round(delta*100, 0) summary += "Ingressi TI: {} ({:+}%)\n".format( today, delta) if delta > 0: summary += "Tempo di raddoppio: {} giorni\n".format(round(log(2)/log(1+delta)*7), 0) elif delta < 0: summary += "Tempo di dimezzamento: {} giorni\n".format(round(log(2)/log(1+abs(delta))*7, 0)) today = media_ti[-1] last_week = media_ti[-8] if last_week == 0: delta = 0 delta_perc = 0 else: delta = (today-last_week)/last_week if delta > 0: summary += "Tempo di raddoppio (media 7 giorni): {} giorni\n".format(round(log(2)/log(1+delta)*7), 0) elif delta < 0: summary += "Tempo di dimezzamento (media 7 giorni): {} giorni\n".format(round(log(2)/log(1+abs(delta))*7, 0)) # Grafico variazione totale positivi print("Grafico variazione totale positivi...") deltaplot( data["regioni"][regione]["completo"]["data"], data["regioni"][regione]["completo"]["variazione_totale_positivi"], f"Variazione giornaliera totale positivi {denominazione_regione}", f"/graphs/epidemia/variazione_totale_positivi_{denominazione_regione}.jpg", footer=f"Fonte dati: PCM-DPC | Ultimo aggiornamento: {last_update}" ) summary += "Variazione totale positivi: {}\n".format( data["regioni"][regione]["completo"]["variazione_totale_positivi"].iat[-1]) # Grafico variazione totale ospedalizzati print("Grafico variazione totale ospedalizzati...") deltaplot( data["regioni"][regione]["completo"]["data"], create_delta(data["regioni"][regione]["completo"] ["totale_ospedalizzati"]), f"Variazione totale ospedalizzati {denominazione_regione}", f"/graphs/epidemia/variazione_totale_ospedalizzati_{denominazione_regione}.jpg", footer=f"Fonte dati: PCM-DPC | Ultimo aggiornamento: {last_update}" ) summary += "Variazione totale ospedalizzati: {}\n".format( create_delta(data["regioni"][regione]["completo"]["totale_ospedalizzati"])[-1]) # Grafico variazione occupazione TI print("Grafico variazione TI") deltaplot( data["regioni"][regione]["completo"]["data"], create_delta(data["regioni"][regione] ["completo"]["terapia_intensiva"]), f"Variazione occupazione TI {denominazione_regione}", f"/graphs/epidemia/variazione_ti_{denominazione_regione}.jpg", footer=f"Fonte dati: PCM-DPC | Ultimo aggiornamento: {last_update}" ) summary += "Variazione TI: {}\n".format(create_delta( data["regioni"][regione]["completo"]["terapia_intensiva"])[-1]) # Grafico variazione totale ospedalizzati print("Grafico variazione ricoverati con sintomi...") deltaplot( data["regioni"][regione]["completo"]["data"], create_delta(data["regioni"][regione]["completo"] ["ricoverati_con_sintomi"]), f"Variazione ospedalizzati ordinari {denominazione_regione}", f"/graphs/epidemia/variazione_ospedalizzati_ordinari_{denominazione_regione}.jpg", footer=f"Fonte dati: PCM-DPC | Ultimo aggiornamento: {last_update}" ) summary += "Variazione ricoverati con sintomi: {}\n".format( create_delta(data["regioni"][regione]["completo"]["ricoverati_con_sintomi"])[-1]) # Grafico deceduti print("Grafico deceduti...") plot( data["regioni"][regione]["completo"]["data"], data["regioni"][regione]["completo"]["deceduti"], f"Andamento deceduti {denominazione_regione}", f"/graphs/epidemia/deceduti_{denominazione_regione}.jpg", color="black", footer=f"Fonte dati: PCM-DPC | Ultimo aggiornamento: {last_update}" ) summary += "Deceduti totali: {}\n".format( data["regioni"][regione]["completo"]["deceduti"].iat[-1]) # Grafico deceduti giornalieri print("Grafico deceduti giornalieri...") delta = create_delta(data["regioni"][regione]["completo"]["deceduti"]) plot( data["regioni"][regione]["completo"]["data"], delta, f"Deceduti giornalieri {denominazione_regione}", f"/graphs/epidemia/deceduti_giornalieri_{denominazione_regione}.jpg", media_mobile=create_media_mobile( create_delta(data["regioni"][regione]["completo"]["deceduti"])), legend=["Deceduti giornalieri", "Media mobile settimanale"], color="black", footer=f"Fonte dati: PCM-DPC | Ultimo aggiornamento: {last_update}" ) delta_maggio = create_delta( data["regioni"][regione]["maggio"]["deceduti"]) plot( data["regioni"][regione]["maggio"]["data"], delta_maggio, f"Deceduti giornalieri {denominazione_regione} (scala log.)", f"/graphs/epidemia/deceduti_giornalieri_{denominazione_regione}_log.jpg", media_mobile=create_media_mobile( create_delta(data["regioni"][regione]["maggio"]["deceduti"])), legend=["Deceduti giornalieri", "Media mobile settimanale"], color="black", footer=f"Fonte dati: PCM-DPC | Ultimo aggiornamento: {last_update}", log=True ) today = delta[-1] last_week = delta[-8] if last_week == 0: delta_perc = 0 else: delta_perc = round((today-last_week)/last_week*100, 0) summary += "Deceduti giornalieri: {} ({:+}%)\n".format( today, delta_perc) print("Grafico incidenza...") incidenza = create_incidenza( data["regioni"][regione]["completo"]["nuovi_positivi"], denominazione_regione) plot( data["regioni"][regione]["completo"]["data"], incidenza, f"Incidenza di nuovi positivi ogni 100000 abitanti\nnell'arco di 7 giorni in {denominazione_regione}", f"/graphs/epidemia/incidenza_contagio_{denominazione_regione}.jpg", footer=f"Fonte dati: PCM-DPC | Ultimo aggiornamento: {last_update}", hline={50: ["", "orange"], 150: ["", "red"]} ) today = incidenza[-1] last_week = incidenza[-8] delta_perc = round((today-last_week)/last_week*100, 0) summary += f"Incidenza: {incidenza[-1]} ({delta_perc:+}%)\n" print("Grafico rt") grafico_rt( data["monitoraggi_iss_regioni"][denominazione_regione]["fine_range"], data["regioni"][regione]["completo"]["data"], data["monitoraggi_iss_regioni"][denominazione_regione]["rt_puntuale"], data["regioni"][regione]["completo"]["nuovi_positivi"], f"Andamento Rt - {denominazione_regione}", f"Fonte dati: PCM-DPC | Ultimo aggiornamento: {last_update}", f"/graphs/epidemia/rt_{denominazione_regione}.jpg", ) if today < 50: colore = "Bianca" elif 50 < today < 150: if occupazione_am < 15 or occupazione_ti < 10: colore = "Bianca" else: colore = "Gialla" elif today > 150: if occupazione_am < 15 or occupazione_ti < 10: colore = "Bianca" elif occupazione_am < 30 or occupazione_ti < 20: colore = "Gialla" elif occupazione_am < 40 or occupazione_ti < 30: colore = "Arancione" else: colore = "Rossa" summary += f"Colore: {colore}\n\n" return summary def vaccini(): os.makedirs(f"{CWD}/graphs/vaccini", exist_ok=True) last_update = json.loads(request.urlopen( "https://raw.githubusercontent.com/italia/covid19-opendata-vaccini/master/dati/last-update-dataset.json").read())["ultimo_aggiornamento"] last_update = pd.to_datetime(last_update).strftime("%d-%m alle %H:%M %Z") summary = f"DATI VACCINAZIONE\n\nDATI NAZIONALI\nUltimo aggiornamento:\n{last_update}\n" print("Grafico percentuale somministrazione...") barplot( data["vaccini_summary"]["area"], data["vaccini_summary"]["percentuale_somministrazione"], "Percentuale dosi somministrate per regioni", "/graphs/vaccini/percentuale_somministrazione_regioni.jpg", xticks=range(0, 100, 5), horizontal=True, grid="x", footer=f"Fonte dati: Covid19 Opendata Vaccini | Ultimo aggiornamento: {last_update}" ) summary += "Percentuale somministrazione:\n" for i in range(0, 21): regione = data["vaccini_summary"]["area"][i] perc = data["vaccini_summary"]["percentuale_somministrazione"][i] summary += f"{regione}: {perc}%\n" print("Grafico popolazione vaccinata seconda dose...") janssen = data["somministrazioni_vaccini"]["nazionale"][data["somministrazioni_vaccini"] ["nazionale"]["fornitore"] == "Janssen"] monodose = janssen["prima_dose"].sum() pregressa_infezione = data["somministrazioni_vaccini"]["nazionale"]["pregressa_infezione"].sum( ) vaccinati_seconda_dose = data["anagrafica_vaccini_summary"]["seconda_dose"].sum( ) popolazione_totale = FASCE_POPOLAZIONE["totale"]['nazionale'] completamente_vaccinati = vaccinati_seconda_dose+monodose+pregressa_infezione pieplot( [ popolazione_totale, completamente_vaccinati ], [ f"Totale popolazione\n ({popolazione_totale})", f"Persone vaccinate\n ({completamente_vaccinati}, {round((completamente_vaccinati / popolazione_totale) * 100, 2)}%)" ], "Persone che hanno completato il ciclo di vaccinazione\nsul totale della popolazione", "/graphs/vaccini/percentuale_vaccinati.jpg", footer=f"Fonte dati: Covid19 Opendata Vaccini | Ultimo aggiornamento: {last_update}" ) summary += f"\nPercentuale popolazione che ha terminato il ciclo di vaccinazione: {completamente_vaccinati} ({round((completamente_vaccinati / popolazione_totale) * 100, 2)}%)\n" print("Grafico popolazione vaccinata prima dose...") vaccinati_prima_dose = data["anagrafica_vaccini_summary"]["prima_dose"].sum( ) pieplot( [ popolazione_totale, vaccinati_prima_dose ], [ f"Totale popolazione\n ({popolazione_totale})", f"Persone vaccinate\n ({vaccinati_prima_dose}, {round((vaccinati_prima_dose / popolazione_totale) * 100, 2)}%)" ], "Persone che hanno ricevuto almeno una dose\nsul totale della popolazione", "/graphs/vaccini/percentuale_vaccinati_prima_dose.jpg", footer=f"Fonte dati: Covid19 Opendata Vaccini | Ultimo aggiornamento: {last_update}" ) summary += f"\nPercentuale popolazione vaccinata con la prima dose: {vaccinati_prima_dose} ({round((vaccinati_prima_dose / popolazione_totale) * 100, 2)}%)\n" print("Grafico vaccinazione giornaliere, prima e seconda dose...") somministrazioni = data["somministrazioni_vaccini_summary"]["nazionale"].groupby("data_somministrazione")[ "totale"].sum().to_dict() prima_dose = data["somministrazioni_vaccini_summary"]["nazionale"].groupby("data_somministrazione")[ "prima_dose"].sum().to_dict() seconda_dose = data["somministrazioni_vaccini_summary"]["nazionale"].groupby("data_somministrazione")[ "seconda_dose"].sum().to_dict() pregressa_infezione = data["somministrazioni_vaccini_summary"]["nazionale"].groupby( "data_somministrazione")["pregressa_infezione"].sum().to_dict() monodose = janssen.groupby("data_somministrazione")[ "prima_dose"].sum().to_dict() for day in prima_dose: if day in monodose.keys(): prima_dose[day] -= monodose[day] for day in seconda_dose: if day in pregressa_infezione.keys(): seconda_dose[day] += pregressa_infezione[day] adjusted = shape_adjust([prima_dose, seconda_dose, monodose]) stackplot( somministrazioni.keys(), adjusted[0].values(), adjusted[1].values(), "Vaccinazioni giornaliere", ["Prima dose", "Seconda dose", "Monodose"], "/graphs/vaccini/vaccinazioni_giornaliere_dosi.jpg", footer=f"Fonte dati: Covid19 Opendata Vaccini | Ultimo aggiornamento: {last_update}", y3=adjusted[2].values() ) today = list(somministrazioni.values())[-1] yesterday = list(somministrazioni.values())[-2] yeyesterday = list(somministrazioni.values())[-3] last_week_1 = list(somministrazioni.values())[-8] last_week_2 = list(somministrazioni.values())[-9] last_week_3 = list(somministrazioni.values())[-10] delta_perc_1 = round((today-last_week_1)/last_week_1*100, 0) delta_perc_2 = round((yesterday-last_week_2)/last_week_2*100, 0) delta_perc_3 = round((yeyesterday-last_week_3)/last_week_3*100, 0) summary += f"\nVaccinazioni giornaliere:\nOggi:{today} ({delta_perc_1:+}%)\nIeri:{yesterday} ({delta_perc_2:+}%)\nL'altro ieri: {yeyesterday} ({delta_perc_3:+}%)\n\n" print("Grafico somministrazioni giornaliere per fornitore") astrazeneca = data["somministrazioni_vaccini"]["nazionale"][data["somministrazioni_vaccini"] ["nazionale"]["fornitore"] == "Vaxzevria (AstraZeneca)"] astrazeneca = (astrazeneca.groupby("data_somministrazione")["prima_dose"].sum( ) + astrazeneca.groupby("data_somministrazione")["seconda_dose"].sum()).to_dict() pfizer = data["somministrazioni_vaccini"]["nazionale"][data["somministrazioni_vaccini"] ["nazionale"]["fornitore"] == "Pfizer/BioNTech"] pfizer = (pfizer.groupby("data_somministrazione")["prima_dose"].sum( ) + pfizer.groupby("data_somministrazione")["seconda_dose"].sum()).to_dict() moderna = data["somministrazioni_vaccini"]["nazionale"][data["somministrazioni_vaccini"] ["nazionale"]["fornitore"] == "Moderna"] moderna = (moderna.groupby("data_somministrazione")["prima_dose"].sum( ) + moderna.groupby("data_somministrazione")["seconda_dose"].sum()).to_dict() adjusted = shape_adjust([pfizer, moderna, astrazeneca, monodose]) media_mobile_somministrazioni = create_media_mobile( somministrazioni.values()) grafico_vaccini_fornitore( adjusted[0], adjusted[1], adjusted[2], adjusted[3], [somministrazioni.keys(), media_mobile_somministrazioni], "Somministrazioni giornaliere per fornitore", f"Fonte dati: Covid19 Opendata Vaccini | Ultimo aggiornamento: {last_update}", "/graphs/vaccini/somministrazioni_giornaliere_fornitore.jpg" ) print("Grafico somministrazioni giornaliere per fascia d'età") somministrazioni_fasce = [] prime_dosi_fasce = [] for i in range(len(data["anagrafica_vaccini_summary"]["fascia_anagrafica"])): fascia = data["anagrafica_vaccini_summary"]["fascia_anagrafica"].iat[i] prima_dose = data["somministrazioni_vaccini"]["nazionale"][data["somministrazioni_vaccini"]["nazionale"] ["fascia_anagrafica"] == fascia].groupby("data_somministrazione")["prima_dose"].sum().to_dict() seconda_dose = data["somministrazioni_vaccini"]["nazionale"][data["somministrazioni_vaccini"]["nazionale"] ["fascia_anagrafica"] == fascia].groupby("data_somministrazione")["seconda_dose"].sum().to_dict() pregressa_infezione = data["somministrazioni_vaccini"]["nazionale"][data["somministrazioni_vaccini"]["nazionale"] ["fascia_anagrafica"] == fascia].groupby("data_somministrazione")["pregressa_infezione"].sum().to_dict() for day in seconda_dose: if day in pregressa_infezione.keys(): seconda_dose[day] += pregressa_infezione[day] result = {} for date in prima_dose.keys(): result[date] = prima_dose[date] + seconda_dose[date] somministrazioni_fasce.append(result) prime_dosi_fasce.append(prima_dose) adjusted = shape_adjust(somministrazioni_fasce) grafico_vaccini_fascia_eta( adjusted, [somministrazioni.keys(), media_mobile_somministrazioni], "Somministrazioni giornaliere per fascia d'età", f"Fonte dati: Covid19 Opendata Vaccini | Ultimo aggiornamento: {last_update}", "/graphs/vaccini/somministrazioni_giornaliere_fascia_anagrafica.jpg" ) grafico_vaccini_cumulativo( prime_dosi_fasce, "Prime dosi giornaliere per fascia d'età MM7", f"Fonte dati: Covid19 Opendata Vaccini | Ultimo aggiornamento: {last_update}", "/graphs/vaccini/prime_dosi_fascia.jpg" ) print("Grafico fasce popolazione...") y_values_prima_dose = [] y_values_seconda_dose = [] y_values_monodose = [] for index, row in data["anagrafica_vaccini_summary"].iterrows(): janssen_fascia = janssen[janssen["fascia_anagrafica"] == row["fascia_anagrafica"]]["prima_dose"].sum() perc_prima_dose = (row["prima_dose"] - row["seconda_dose"] - janssen_fascia) / FASCE_POPOLAZIONE[row["fascia_anagrafica"]][ "nazionale"] sec_dose = row["seconda_dose"] + row["pregressa_infezione"] perc_seconda_dose = sec_dose / \ FASCE_POPOLAZIONE[row["fascia_anagrafica"]]["nazionale"] perc_monodose = janssen_fascia / \ FASCE_POPOLAZIONE[row["fascia_anagrafica"]]["nazionale"] y_values_prima_dose.append(perc_prima_dose * 100) y_values_seconda_dose.append(perc_seconda_dose * 100) y_values_monodose.append(perc_monodose * 100) grafico_vaccinati_fascia_anagrafica( data["anagrafica_vaccini_summary"]["fascia_anagrafica"], y_values_prima_dose, y_values_seconda_dose, y_values_monodose, "Somministrazione vaccini per fascia d'età", f"Fonte dati: Covid19 Opendata Vaccini | Ultimo aggiornamento: {last_update}", "/graphs/vaccini/somministrazione_fascia_eta.jpg" ) summary += "Percentuali fascia anagrafica:\n" for i in range(len(data["anagrafica_vaccini_summary"]["fascia_anagrafica"])): fascia = data["anagrafica_vaccini_summary"]["fascia_anagrafica"].iat[i] summary += f"{fascia}: {y_values_seconda_dose[i]}% ({y_values_prima_dose[i]}%)\n" print("Grafico consegne vaccino...") consegne = data["consegne_vaccini"].groupby( "data_consegna")["numero_dosi"].sum().to_dict() consegne_astrazeneca = data["consegne_vaccini"][data["consegne_vaccini"]["fornitore"] == "Vaxzevria (AstraZeneca)"].groupby("data_consegna")["numero_dosi"].sum().to_dict() consegne_moderna = data["consegne_vaccini"][data["consegne_vaccini"]["fornitore"] == "Moderna"].groupby("data_consegna")["numero_dosi"].sum().to_dict() consegne_pfizer = data["consegne_vaccini"][data["consegne_vaccini"]["fornitore"] == "Pfizer/BioNTech"].groupby("data_consegna")["numero_dosi"].sum().to_dict() consegne_janssen = data["consegne_vaccini"][data["consegne_vaccini"]["fornitore"] == "Janssen"].groupby("data_consegna")["numero_dosi"].sum().to_dict() adjusted = shape_adjust( [consegne_pfizer, consegne_moderna, consegne_astrazeneca, consegne_janssen]) media_mobile = create_media_mobile(consegne.values()) grafico_vaccini_fornitore( adjusted[0], adjusted[1], adjusted[2], adjusted[3], [consegne.keys(), media_mobile], "Consegne vaccini", f"Fonte dati: Covid19 Opendata Vaccini | Ultimo aggiornamento: {last_update}", "/graphs/vaccini/consegne_vaccini.jpg" ) summary += f"\nMedia consegne vaccino:\n{media_mobile[-1]}\n\n" print("Grafico consegne totali vaccini") fornitori = data["consegne_vaccini"].groupby( "fornitore")["numero_dosi"].sum().to_dict() grafico_consegne_totale( fornitori, CONSEGNE_VACCINI, f"Fonte dati: Covid19 Opendata Vaccini | Ultimo aggiornamento: {last_update}", "/graphs/vaccini/consegne_totali_vaccini.jpg" ) summary += "Consegne totali:\n" for el in fornitori: summary += f"{el}: {fornitori[el]}\n" summary += "\nDATI REGIONALI\n\n" for regione in data["somministrazioni_vaccini_summary"]["regioni"].keys(): print(f"Regione {regione}") denominazione_regione = data["regioni"][regione]["completo"]["denominazione_regione"].iloc[0] summary += f"\n{denominazione_regione}\n" print("Grafico vaccinazione giornaliere, prima e seconda dose...") dataframe = data["somministrazioni_vaccini"]["regioni"][regione] janssen = dataframe[dataframe["fornitore"] == "Janssen"] somministrazioni = \ data["somministrazioni_vaccini_summary"]["regioni"][regione].groupby("data_somministrazione")[ "totale"].sum().to_dict() prima_dose = data["somministrazioni_vaccini_summary"]["regioni"][regione].groupby("data_somministrazione")[ "prima_dose"].sum().to_dict() seconda_dose = data["somministrazioni_vaccini_summary"]["regioni"][regione].groupby("data_somministrazione")[ "seconda_dose"].sum().to_dict() pregressa_infezione = data["somministrazioni_vaccini_summary"]["regioni"][regione].groupby( "data_somministrazione")["pregressa_infezione"].sum().to_dict() monodose = janssen.groupby("data_somministrazione")[ "prima_dose"].sum().to_dict() for day in prima_dose: if day in monodose.keys(): prima_dose[day] -= monodose[day] for day in seconda_dose: if day in pregressa_infezione.keys(): seconda_dose[day] += pregressa_infezione[day] adjusted = order(shape_adjust([prima_dose, seconda_dose, monodose])) stackplot( adjusted[0].keys(), adjusted[0].values(), adjusted[1].values(), f"Vaccinazioni giornaliere in {denominazione_regione}", ["Prima dose", "Seconda dose", "Monodose"], f"/graphs/vaccini/vaccinazioni_giornaliere_dosi_{denominazione_regione}.jpg", footer=f"Fonte dati: Covid19 Opendata Vaccini | Ultimo aggiornamento: {last_update}", y3=adjusted[2].values() ) today = list(somministrazioni.values())[-1] yesterday = list(somministrazioni.values())[-2] yeyesterday = list(somministrazioni.values())[-3] last_week_1 = list(somministrazioni.values())[-8] last_week_2 = list(somministrazioni.values())[-9] last_week_3 = list(somministrazioni.values())[-10] delta_perc_1 = round((today-last_week_1)/last_week_1*100, 0) delta_perc_2 = round((yesterday-last_week_2)/last_week_2*100, 0) delta_perc_3 = round((yeyesterday-last_week_3)/last_week_3*100, 0) summary += f"\nVaccinazioni giornaliere:\nOggi:{today} ({delta_perc_1:+}%)\nIeri:{yesterday} ({delta_perc_2:+}%)\nL'altro ieri: {yeyesterday} ({delta_perc_3:+}%)\n\n" print("Grafico somministrazioni giornaliere per fornitore") astrazeneca = dataframe[dataframe["fornitore"] == "Vaxzevria (AstraZeneca)"] astrazeneca = (astrazeneca.groupby("data_somministrazione")["prima_dose"].sum( ) + astrazeneca.groupby("data_somministrazione")["seconda_dose"].sum()).to_dict() pfizer = dataframe[dataframe["fornitore"] == "Pfizer/BioNTech"] pfizer = (pfizer.groupby("data_somministrazione")["prima_dose"].sum( ) + pfizer.groupby("data_somministrazione")["seconda_dose"].sum()).to_dict() moderna = dataframe[dataframe["fornitore"] == "Moderna"] moderna = (moderna.groupby("data_somministrazione")["prima_dose"].sum( ) + moderna.groupby("data_somministrazione")["seconda_dose"].sum()).to_dict() adjusted = shape_adjust([pfizer, moderna, astrazeneca, monodose]) media_mobile_somministrazioni = create_media_mobile( somministrazioni.values()) grafico_vaccini_fornitore( adjusted[0], adjusted[1], adjusted[2], adjusted[3], [somministrazioni.keys(), media_mobile_somministrazioni], f"Somministrazioni giornaliere per fornitore - {denominazione_regione}", f"Fonte dati: Covid19 Opendata Vaccini | Ultimo aggiornamento: {last_update}", f"/graphs/vaccini/somministrazioni_giornaliere_fornitore_{denominazione_regione}.jpg" ) print("Grafico somministrazioni giornaliere per fascia d'età") somministrazioni_fasce = [] prima_dose_fasce = [] for i in range(len(data["anagrafica_vaccini_summary"]["fascia_anagrafica"])): fascia = data["anagrafica_vaccini_summary"]["fascia_anagrafica"].iat[i] prima_dose = data["somministrazioni_vaccini"]["regioni"][regione][data["somministrazioni_vaccini"]["regioni"] [regione]["fascia_anagrafica"] == fascia].groupby("data_somministrazione")["prima_dose"].sum().to_dict() seconda_dose = data["somministrazioni_vaccini"]["regioni"][regione][data["somministrazioni_vaccini"]["regioni"] [regione]["fascia_anagrafica"] == fascia].groupby("data_somministrazione")["seconda_dose"].sum().to_dict() pregressa_infezione = data["somministrazioni_vaccini"]["regioni"][regione][data["somministrazioni_vaccini"]["regioni"] [regione]["fascia_anagrafica"] == fascia].groupby("data_somministrazione")["pregressa_infezione"].sum().to_dict() for day in seconda_dose: if day in pregressa_infezione.keys(): seconda_dose[day] += pregressa_infezione[day] result = {} for date in prima_dose.keys(): result[date] = prima_dose[date] + seconda_dose[date] prima_dose_fasce.append(prima_dose) somministrazioni_fasce.append(result) adjusted = shape_adjust(somministrazioni_fasce) grafico_vaccini_fascia_eta( adjusted, [somministrazioni.keys(), media_mobile_somministrazioni], f"Somministrazioni giornaliere per fascia d'età - {denominazione_regione}", f"Fonte dati: Covid19 Opendata Vaccini | Ultimo aggiornamento: {last_update}", f"/graphs/vaccini/somministrazioni_giornaliere_fascia_anagrafica_{denominazione_regione}.jpg" ) grafico_vaccini_cumulativo( prima_dose_fasce, f"Prime dosi giornaliere per fascia d'età - {denominazione_regione} MM7", f"Fonte dati: Covid19 Opendata Vaccini | Ultimo aggiornamento: {last_update}", f"/graphs/vaccini/prime_dosi_fascia_{denominazione_regione}.jpg" ) print("Grafico fasce popolazione...") y_values_prima_dose = [] y_values_seconda_dose = [] y_values_monodose = [] for fascia in FASCE_POPOLAZIONE: if fascia == "totale": continue prima_dose = dataframe[dataframe["fascia_anagrafica"] == fascia]["prima_dose"].sum() sec_dose = dataframe[dataframe["fascia_anagrafica"] == fascia]["seconda_dose"].sum() pregressa_infezione = dataframe[dataframe["fascia_anagrafica"] == fascia]["pregressa_infezione"].sum() monodose = janssen[janssen["fascia_anagrafica"] == fascia]["prima_dose"].sum() seconda_dose = sec_dose + pregressa_infezione perc_prima_dose = (prima_dose - seconda_dose - monodose) / \ FASCE_POPOLAZIONE[fascia][denominazione_regione] perc_seconda_dose = ( seconda_dose / FASCE_POPOLAZIONE[fascia][denominazione_regione]) y_values_prima_dose.append(perc_prima_dose * 100) y_values_seconda_dose.append(perc_seconda_dose * 100) y_values_monodose.append(perc_monodose * 100) grafico_vaccinati_fascia_anagrafica( data["anagrafica_vaccini_summary"]["fascia_anagrafica"], y_values_prima_dose, y_values_seconda_dose, y_values_monodose, f"Somministrazione vaccini per fascia d'età in {denominazione_regione}", f"Fonte dati: Covid19 Opendata Vaccini | Ultimo aggiornamento: {last_update}", f"/graphs/vaccini/somministrazione_fascia_eta_{denominazione_regione}.jpg" ) for i in range(len(data["anagrafica_vaccini_summary"]["fascia_anagrafica"])): fascia = data["anagrafica_vaccini_summary"]["fascia_anagrafica"].iat[i] summary += f"{fascia}: {y_values_seconda_dose[i]}% ({y_values_prima_dose[i]} %)\n" return summary if __name__ == "__main__": # Inizializza i dati start_time = time() print("--- Inizializzazione dataset...") for url_name in URLS.keys(): download_csv(url_name, URLS[url_name]) CWD = os.path.abspath(os.path.dirname(__file__)) os.makedirs(f"{CWD}/graphs", exist_ok=True) plt.style.use("seaborn-dark") print("Dati caricati con successo.\n-----------------------------") print("Inizio generazione grafici epidemia...") sum_epidemia = epidemia() print("-----------------------------\nInizio generazione grafici vaccini...") sum_vaccini = vaccini() with open(f"{CWD}/summary_epidemia.txt", 'w') as f: f.write(sum_epidemia) with open(f"{CWD}/summary_vaccini.txt", "w") as f: f.write(sum_vaccini) delta = (time() - start_time)//1 print( f"-----------------------------\nScript completato con successo in {int(delta)} s. I risultati si trovano nella cartella graphs.")
[ "matplotlib.pyplot.title", "matplotlib.pyplot.yscale", "pandas.read_csv", "matplotlib.pyplot.style.use", "numpy.arange", "matplotlib.pyplot.fill_between", "matplotlib.pyplot.tight_layout", "matplotlib.pyplot.axvline", "matplotlib.pyplot.close", "os.path.dirname", "matplotlib.pyplot.yticks", "urllib.request.urlopen", "datetime.timedelta", "math.log", "matplotlib.pyplot.xticks", "matplotlib.pyplot.subplots", "matplotlib.pyplot.axhline", "matplotlib.pyplot.legend", "matplotlib.pyplot.figtext", "datetime.datetime", "pandas.to_datetime", "matplotlib.pyplot.gcf", "matplotlib.pyplot.grid", "os.makedirs", "matplotlib.pyplot.vlines", "time.time", "numpy.array" ]
[((9244, 9260), 'pandas.read_csv', 'pd.read_csv', (['url'], {}), '(url)\n', (9255, 9260), True, 'import pandas as pd\n'), ((14836, 14850), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (14848, 14850), True, 'import matplotlib.pyplot as plt\n'), ((15535, 15595), 'matplotlib.pyplot.figtext', 'plt.figtext', (['(0.99)', '(0.01)', 'footer'], {'horizontalalignment': '"""right"""'}), "(0.99, 0.01, footer, horizontalalignment='right')\n", (15546, 15595), True, 'import matplotlib.pyplot as plt\n'), ((15640, 15656), 'matplotlib.pyplot.close', 'plt.close', (['"""all"""'], {}), "('all')\n", (15649, 15656), True, 'import matplotlib.pyplot as plt\n'), ((15756, 15770), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (15768, 15770), True, 'import matplotlib.pyplot as plt\n'), ((16066, 16126), 'matplotlib.pyplot.figtext', 'plt.figtext', (['(0.99)', '(0.01)', 'footer'], {'horizontalalignment': '"""right"""'}), "(0.99, 0.01, footer, horizontalalignment='right')\n", (16077, 16126), True, 'import matplotlib.pyplot as plt\n'), ((16170, 16186), 'matplotlib.pyplot.close', 'plt.close', (['"""all"""'], {}), "('all')\n", (16179, 16186), True, 'import matplotlib.pyplot as plt\n'), ((16252, 16266), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (16264, 16266), True, 'import matplotlib.pyplot as plt\n'), ((16326, 16381), 'matplotlib.pyplot.vlines', 'plt.vlines', ([], {'x': 'x', 'ymin': '(0)', 'ymax': 'y', 'color': 'color', 'alpha': '(0.7)'}), '(x=x, ymin=0, ymax=y, color=color, alpha=0.7)\n', (16336, 16381), True, 'import matplotlib.pyplot as plt\n'), ((16456, 16516), 'matplotlib.pyplot.figtext', 'plt.figtext', (['(0.99)', '(0.01)', 'footer'], {'horizontalalignment': '"""right"""'}), "(0.99, 0.01, footer, horizontalalignment='right')\n", (16467, 16516), True, 'import matplotlib.pyplot as plt\n'), ((16561, 16577), 'matplotlib.pyplot.close', 'plt.close', (['"""all"""'], {}), "('all')\n", (16570, 16577), True, 'import matplotlib.pyplot as plt\n'), ((16777, 16791), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (16789, 16791), True, 'import matplotlib.pyplot as plt\n'), ((16898, 16914), 'matplotlib.pyplot.title', 'plt.title', (['title'], {}), '(title)\n', (16907, 16914), True, 'import matplotlib.pyplot as plt\n'), ((17401, 17461), 'matplotlib.pyplot.figtext', 'plt.figtext', (['(0.99)', '(0.01)', 'footer'], {'horizontalalignment': '"""right"""'}), "(0.99, 0.01, footer, horizontalalignment='right')\n", (17412, 17461), True, 'import matplotlib.pyplot as plt\n'), ((17466, 17484), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (17482, 17484), True, 'import matplotlib.pyplot as plt\n'), ((17529, 17545), 'matplotlib.pyplot.close', 'plt.close', (['"""all"""'], {}), "('all')\n", (17538, 17545), True, 'import matplotlib.pyplot as plt\n'), ((17619, 17633), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (17631, 17633), True, 'import matplotlib.pyplot as plt\n'), ((17672, 17688), 'matplotlib.pyplot.title', 'plt.title', (['title'], {}), '(title)\n', (17681, 17688), True, 'import matplotlib.pyplot as plt\n'), ((17693, 17753), 'matplotlib.pyplot.figtext', 'plt.figtext', (['(0.99)', '(0.01)', 'footer'], {'horizontalalignment': '"""right"""'}), "(0.99, 0.01, footer, horizontalalignment='right')\n", (17704, 17753), True, 'import matplotlib.pyplot as plt\n'), ((17798, 17814), 'matplotlib.pyplot.close', 'plt.close', (['"""all"""'], {}), "('all')\n", (17807, 17814), True, 'import matplotlib.pyplot as plt\n'), ((17934, 17948), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (17946, 17948), True, 'import matplotlib.pyplot as plt\n'), ((18192, 18208), 'matplotlib.pyplot.title', 'plt.title', (['title'], {}), '(title)\n', (18201, 18208), True, 'import matplotlib.pyplot as plt\n'), ((18213, 18273), 'matplotlib.pyplot.figtext', 'plt.figtext', (['(0.99)', '(0.01)', 'footer'], {'horizontalalignment': '"""right"""'}), "(0.99, 0.01, footer, horizontalalignment='right')\n", (18224, 18273), True, 'import matplotlib.pyplot as plt\n'), ((18278, 18290), 'matplotlib.pyplot.legend', 'plt.legend', ([], {}), '()\n', (18288, 18290), True, 'import matplotlib.pyplot as plt\n'), ((18336, 18352), 'matplotlib.pyplot.close', 'plt.close', (['"""all"""'], {}), "('all')\n", (18345, 18352), True, 'import matplotlib.pyplot as plt\n'), ((18444, 18458), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (18456, 18458), True, 'import matplotlib.pyplot as plt\n'), ((19982, 19998), 'matplotlib.pyplot.title', 'plt.title', (['title'], {}), '(title)\n', (19991, 19998), True, 'import matplotlib.pyplot as plt\n'), ((20003, 20015), 'matplotlib.pyplot.legend', 'plt.legend', ([], {}), '()\n', (20013, 20015), True, 'import matplotlib.pyplot as plt\n'), ((20020, 20080), 'matplotlib.pyplot.figtext', 'plt.figtext', (['(0.99)', '(0.01)', 'footer'], {'horizontalalignment': '"""right"""'}), "(0.99, 0.01, footer, horizontalalignment='right')\n", (20031, 20080), True, 'import matplotlib.pyplot as plt\n'), ((20222, 20238), 'matplotlib.pyplot.close', 'plt.close', (['"""all"""'], {}), "('all')\n", (20231, 20238), True, 'import matplotlib.pyplot as plt\n'), ((20362, 20376), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (20374, 20376), True, 'import matplotlib.pyplot as plt\n'), ((20741, 20760), 'numpy.array', 'np.array', (['y_moderna'], {}), '(y_moderna)\n', (20749, 20760), True, 'import numpy as np\n'), ((20780, 20798), 'numpy.array', 'np.array', (['y_pfizer'], {}), '(y_pfizer)\n', (20788, 20798), True, 'import numpy as np\n'), ((20823, 20846), 'numpy.array', 'np.array', (['y_astrazeneca'], {}), '(y_astrazeneca)\n', (20831, 20846), True, 'import numpy as np\n'), ((21345, 21361), 'matplotlib.pyplot.title', 'plt.title', (['title'], {}), '(title)\n', (21354, 21361), True, 'import matplotlib.pyplot as plt\n'), ((21366, 21378), 'matplotlib.pyplot.legend', 'plt.legend', ([], {}), '()\n', (21376, 21378), True, 'import matplotlib.pyplot as plt\n'), ((21383, 21443), 'matplotlib.pyplot.figtext', 'plt.figtext', (['(0.99)', '(0.01)', 'footer'], {'horizontalalignment': '"""right"""'}), "(0.99, 0.01, footer, horizontalalignment='right')\n", (21394, 21443), True, 'import matplotlib.pyplot as plt\n'), ((21585, 21601), 'matplotlib.pyplot.close', 'plt.close', (['"""all"""'], {}), "('all')\n", (21594, 21601), True, 'import matplotlib.pyplot as plt\n'), ((21692, 21706), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (21704, 21706), True, 'import matplotlib.pyplot as plt\n'), ((21892, 21943), 'matplotlib.pyplot.title', 'plt.title', (['"""Consegne totali vaccini (al 23/4/2021)"""'], {}), "('Consegne totali vaccini (al 23/4/2021)')\n", (21901, 21943), True, 'import matplotlib.pyplot as plt\n'), ((22232, 22308), 'matplotlib.pyplot.xticks', 'plt.xticks', (['x_axis', "['Janssen', 'Moderna', 'Pfizer/BioNTech', 'AstraZeneca']"], {}), "(x_axis, ['Janssen', 'Moderna', 'Pfizer/BioNTech', 'AstraZeneca'])\n", (22242, 22308), True, 'import matplotlib.pyplot as plt\n'), ((22328, 22340), 'matplotlib.pyplot.legend', 'plt.legend', ([], {}), '()\n', (22338, 22340), True, 'import matplotlib.pyplot as plt\n'), ((22346, 22406), 'matplotlib.pyplot.figtext', 'plt.figtext', (['(0.99)', '(0.01)', 'footer'], {'horizontalalignment': '"""right"""'}), "(0.99, 0.01, footer, horizontalalignment='right')\n", (22357, 22406), True, 'import matplotlib.pyplot as plt\n'), ((22411, 22429), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (22427, 22429), True, 'import matplotlib.pyplot as plt\n'), ((22474, 22490), 'matplotlib.pyplot.close', 'plt.close', (['"""all"""'], {}), "('all')\n", (22483, 22490), True, 'import matplotlib.pyplot as plt\n'), ((22576, 22590), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (22588, 22590), True, 'import matplotlib.pyplot as plt\n'), ((22947, 22963), 'matplotlib.pyplot.title', 'plt.title', (['title'], {}), '(title)\n', (22956, 22963), True, 'import matplotlib.pyplot as plt\n'), ((22968, 23028), 'matplotlib.pyplot.figtext', 'plt.figtext', (['(0.99)', '(0.01)', 'footer'], {'horizontalalignment': '"""right"""'}), "(0.99, 0.01, footer, horizontalalignment='right')\n", (22979, 23028), True, 'import matplotlib.pyplot as plt\n'), ((23033, 23043), 'matplotlib.pyplot.grid', 'plt.grid', ([], {}), '()\n', (23041, 23043), True, 'import matplotlib.pyplot as plt\n'), ((23089, 23105), 'matplotlib.pyplot.close', 'plt.close', (['"""all"""'], {}), "('all')\n", (23098, 23105), True, 'import matplotlib.pyplot as plt\n'), ((23183, 23197), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (23195, 23197), True, 'import matplotlib.pyplot as plt\n'), ((24012, 24028), 'matplotlib.pyplot.title', 'plt.title', (['title'], {}), '(title)\n', (24021, 24028), True, 'import matplotlib.pyplot as plt\n'), ((24033, 24093), 'matplotlib.pyplot.figtext', 'plt.figtext', (['(0.99)', '(0.01)', 'footer'], {'horizontalalignment': '"""right"""'}), "(0.99, 0.01, footer, horizontalalignment='right')\n", (24044, 24093), True, 'import matplotlib.pyplot as plt\n'), ((24098, 24110), 'matplotlib.pyplot.legend', 'plt.legend', ([], {}), '()\n', (24108, 24110), True, 'import matplotlib.pyplot as plt\n'), ((24180, 24196), 'matplotlib.pyplot.close', 'plt.close', (['"""all"""'], {}), "('all')\n", (24189, 24196), True, 'import matplotlib.pyplot as plt\n'), ((24619, 24633), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (24631, 24633), True, 'import matplotlib.pyplot as plt\n'), ((24885, 24901), 'matplotlib.pyplot.title', 'plt.title', (['title'], {}), '(title)\n', (24894, 24901), True, 'import matplotlib.pyplot as plt\n'), ((24906, 24966), 'matplotlib.pyplot.figtext', 'plt.figtext', (['(0.99)', '(0.01)', 'footer'], {'horizontalalignment': '"""right"""'}), "(0.99, 0.01, footer, horizontalalignment='right')\n", (24917, 24966), True, 'import matplotlib.pyplot as plt\n'), ((24971, 24985), 'matplotlib.pyplot.grid', 'plt.grid', (['(True)'], {}), '(True)\n', (24979, 24985), True, 'import matplotlib.pyplot as plt\n'), ((25055, 25071), 'matplotlib.pyplot.close', 'plt.close', (['"""all"""'], {}), "('all')\n", (25064, 25071), True, 'import matplotlib.pyplot as plt\n'), ((25189, 25241), 'os.makedirs', 'os.makedirs', (['f"""{CWD}/graphs/epidemia"""'], {'exist_ok': '(True)'}), "(f'{CWD}/graphs/epidemia', exist_ok=True)\n", (25200, 25241), False, 'import os\n'), ((49994, 50045), 'os.makedirs', 'os.makedirs', (['f"""{CWD}/graphs/vaccini"""'], {'exist_ok': '(True)'}), "(f'{CWD}/graphs/vaccini', exist_ok=True)\n", (50005, 50045), False, 'import os\n'), ((72043, 72049), 'time.time', 'time', ([], {}), '()\n', (72047, 72049), False, 'from time import time\n'), ((72232, 72275), 'os.makedirs', 'os.makedirs', (['f"""{CWD}/graphs"""'], {'exist_ok': '(True)'}), "(f'{CWD}/graphs', exist_ok=True)\n", (72243, 72275), False, 'import os\n'), ((72280, 72309), 'matplotlib.pyplot.style.use', 'plt.style.use', (['"""seaborn-dark"""'], {}), "('seaborn-dark')\n", (72293, 72309), True, 'import matplotlib.pyplot as plt\n'), ((13644, 13661), 'datetime.timedelta', 'timedelta', ([], {'days': '(1)'}), '(days=1)\n', (13653, 13661), False, 'from datetime import datetime, timedelta\n'), ((15246, 15285), 'matplotlib.pyplot.fill_between', 'plt.fill_between', (['x', 'y'], {'color': '"""#539ecd"""'}), "(x, y, color='#539ecd')\n", (15262, 15285), True, 'import matplotlib.pyplot as plt\n'), ((15294, 15329), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'loc': '(1)', 'fontsize': '"""small"""'}), "(loc=1, fontsize='small')\n", (15304, 15329), True, 'import matplotlib.pyplot as plt\n'), ((15353, 15390), 'matplotlib.pyplot.axvline', 'plt.axvline', (['vline', '(0)', '(1)'], {'color': '"""red"""'}), "(vline, 0, 1, color='red')\n", (15364, 15390), True, 'import matplotlib.pyplot as plt\n'), ((15412, 15429), 'matplotlib.pyplot.yscale', 'plt.yscale', (['"""log"""'], {}), "('log')\n", (15422, 15429), True, 'import matplotlib.pyplot as plt\n'), ((16980, 16998), 'matplotlib.pyplot.xticks', 'plt.xticks', (['xticks'], {}), '(xticks)\n', (16990, 16998), True, 'import matplotlib.pyplot as plt\n'), ((17023, 17041), 'matplotlib.pyplot.yticks', 'plt.yticks', (['yticks'], {}), '(yticks)\n', (17033, 17041), True, 'import matplotlib.pyplot as plt\n'), ((17225, 17237), 'matplotlib.pyplot.legend', 'plt.legend', ([], {}), '()\n', (17235, 17237), True, 'import matplotlib.pyplot as plt\n'), ((17313, 17355), 'matplotlib.pyplot.xticks', 'plt.xticks', (['[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]'], {}), '([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])\n', (17323, 17355), True, 'import matplotlib.pyplot as plt\n'), ((72201, 72226), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (72216, 72226), False, 'import os\n'), ((9353, 9411), 'pandas.to_datetime', 'pd.to_datetime', (['dataframe[col]'], {'format': '"""%Y-%m-%dT%H:%M:%S"""'}), "(dataframe[col], format='%Y-%m-%dT%H:%M:%S')\n", (9367, 9411), True, 'import pandas as pd\n'), ((13309, 13326), 'datetime.timedelta', 'timedelta', ([], {'days': '(1)'}), '(days=1)\n', (13318, 13326), False, 'from datetime import datetime, timedelta\n'), ((15176, 15237), 'matplotlib.pyplot.axhline', 'plt.axhline', (['el', '(0)', '(1)'], {'label': 'hline[el][0]', 'color': 'hline[el][1]'}), '(el, 0, 1, label=hline[el][0], color=hline[el][1])\n', (15187, 15237), True, 'import matplotlib.pyplot as plt\n'), ((18797, 18814), 'datetime.timedelta', 'timedelta', ([], {'days': '(1)'}), '(days=1)\n', (18806, 18814), False, 'from datetime import datetime, timedelta\n'), ((24826, 24847), 'numpy.arange', 'np.arange', (['(-30)', '(30)', '(5)'], {}), '(-30, 30, 5)\n', (24835, 24847), True, 'import numpy as np\n'), ((50256, 50283), 'pandas.to_datetime', 'pd.to_datetime', (['last_update'], {}), '(last_update)\n', (50270, 50283), True, 'import pandas as pd\n'), ((72763, 72769), 'time.time', 'time', ([], {}), '()\n', (72767, 72769), False, 'from time import time\n'), ((18096, 18116), 'numpy.array', 'np.array', (['prima_dose'], {}), '(prima_dose)\n', (18104, 18116), True, 'import numpy as np\n'), ((18130, 18152), 'numpy.array', 'np.array', (['seconda_dose'], {}), '(seconda_dose)\n', (18138, 18152), True, 'import numpy as np\n'), ((10224, 10260), 'datetime.datetime', 'datetime', ([], {'year': '(2021)', 'month': '(4)', 'day': '(30)'}), '(year=2021, month=4, day=30)\n', (10232, 10260), False, 'from datetime import datetime, timedelta\n'), ((24564, 24570), 'math.log', 'log', (['(2)'], {}), '(2)\n', (24567, 24570), False, 'from math import log\n'), ((24571, 24585), 'math.log', 'log', (['(1 + delta)'], {}), '(1 + delta)\n', (24574, 24585), False, 'from math import log\n'), ((50075, 50206), 'urllib.request.urlopen', 'request.urlopen', (['"""https://raw.githubusercontent.com/italia/covid19-opendata-vaccini/master/dati/last-update-dataset.json"""'], {}), "(\n 'https://raw.githubusercontent.com/italia/covid19-opendata-vaccini/master/dati/last-update-dataset.json'\n )\n", (50090, 50206), True, 'import urllib.request as request\n'), ((10384, 10420), 'datetime.datetime', 'datetime', ([], {'year': '(2021)', 'month': '(4)', 'day': '(30)'}), '(year=2021, month=4, day=30)\n', (10392, 10420), False, 'from datetime import datetime, timedelta\n'), ((26788, 26794), 'math.log', 'log', (['(2)'], {}), '(2)\n', (26791, 26794), False, 'from math import log\n'), ((26795, 26809), 'math.log', 'log', (['(1 + delta)'], {}), '(1 + delta)\n', (26798, 26809), False, 'from math import log\n'), ((27142, 27148), 'math.log', 'log', (['(2)'], {}), '(2)\n', (27145, 27148), False, 'from math import log\n'), ((27149, 27163), 'math.log', 'log', (['(1 + delta)'], {}), '(1 + delta)\n', (27152, 27163), False, 'from math import log\n'), ((30128, 30134), 'math.log', 'log', (['(2)'], {}), '(2)\n', (30131, 30134), False, 'from math import log\n'), ((30135, 30149), 'math.log', 'log', (['(1 + delta)'], {}), '(1 + delta)\n', (30138, 30149), False, 'from math import log\n'), ((30551, 30557), 'math.log', 'log', (['(2)'], {}), '(2)\n', (30554, 30557), False, 'from math import log\n'), ((30558, 30572), 'math.log', 'log', (['(1 + delta)'], {}), '(1 + delta)\n', (30561, 30572), False, 'from math import log\n'), ((26904, 26910), 'math.log', 'log', (['(2)'], {}), '(2)\n', (26907, 26910), False, 'from math import log\n'), ((27275, 27281), 'math.log', 'log', (['(2)'], {}), '(2)\n', (27278, 27281), False, 'from math import log\n'), ((30244, 30250), 'math.log', 'log', (['(2)'], {}), '(2)\n', (30247, 30250), False, 'from math import log\n'), ((30684, 30690), 'math.log', 'log', (['(2)'], {}), '(2)\n', (30687, 30690), False, 'from math import log\n'), ((38245, 38251), 'math.log', 'log', (['(2)'], {}), '(2)\n', (38248, 38251), False, 'from math import log\n'), ((38252, 38266), 'math.log', 'log', (['(1 + delta)'], {}), '(1 + delta)\n', (38255, 38266), False, 'from math import log\n'), ((38627, 38633), 'math.log', 'log', (['(2)'], {}), '(2)\n', (38630, 38633), False, 'from math import log\n'), ((38634, 38648), 'math.log', 'log', (['(1 + delta)'], {}), '(1 + delta)\n', (38637, 38648), False, 'from math import log\n'), ((42320, 42326), 'math.log', 'log', (['(2)'], {}), '(2)\n', (42323, 42326), False, 'from math import log\n'), ((42327, 42341), 'math.log', 'log', (['(1 + delta)'], {}), '(1 + delta)\n', (42330, 42341), False, 'from math import log\n'), ((42787, 42793), 'math.log', 'log', (['(2)'], {}), '(2)\n', (42790, 42793), False, 'from math import log\n'), ((42794, 42808), 'math.log', 'log', (['(1 + delta)'], {}), '(1 + delta)\n', (42797, 42808), False, 'from math import log\n'), ((20109, 20118), 'matplotlib.pyplot.gcf', 'plt.gcf', ([], {}), '()\n', (20116, 20118), True, 'import matplotlib.pyplot as plt\n'), ((21472, 21481), 'matplotlib.pyplot.gcf', 'plt.gcf', ([], {}), '()\n', (21479, 21481), True, 'import matplotlib.pyplot as plt\n'), ((38369, 38375), 'math.log', 'log', (['(2)'], {}), '(2)\n', (38372, 38375), False, 'from math import log\n'), ((38768, 38774), 'math.log', 'log', (['(2)'], {}), '(2)\n', (38771, 38774), False, 'from math import log\n'), ((42444, 42450), 'math.log', 'log', (['(2)'], {}), '(2)\n', (42447, 42450), False, 'from math import log\n'), ((42928, 42934), 'math.log', 'log', (['(2)'], {}), '(2)\n', (42931, 42934), False, 'from math import log\n')]
import cv2, numpy as np img = np.zeros((512,512,3),np.uint8) #print(img.shape) #img[200:300,100:300] = 255,0,0 cv2.line(img,(0,0),(img.shape[1],img.shape[0]),(0,255,0),3) cv2.rectangle(img,(0,0),(250,350),(0,0,255),cv2.FILLED) cv2.circle(img,(400,50),30,(255,255,0),5) cv2.putText(img," OPENCV ",(300,200),cv2.FONT_HERSHEY_COMPLEX,1,(0,150,0)) cv2.imshow("image",img) cv2.waitKey(0)
[ "cv2.line", "cv2.circle", "cv2.putText", "cv2.waitKey", "numpy.zeros", "cv2.rectangle", "cv2.imshow" ]
[((31, 64), 'numpy.zeros', 'np.zeros', (['(512, 512, 3)', 'np.uint8'], {}), '((512, 512, 3), np.uint8)\n', (39, 64), True, 'import cv2, numpy as np\n'), ((113, 180), 'cv2.line', 'cv2.line', (['img', '(0, 0)', '(img.shape[1], img.shape[0])', '(0, 255, 0)', '(3)'], {}), '(img, (0, 0), (img.shape[1], img.shape[0]), (0, 255, 0), 3)\n', (121, 180), False, 'import cv2, numpy as np\n'), ((173, 236), 'cv2.rectangle', 'cv2.rectangle', (['img', '(0, 0)', '(250, 350)', '(0, 0, 255)', 'cv2.FILLED'], {}), '(img, (0, 0), (250, 350), (0, 0, 255), cv2.FILLED)\n', (186, 236), False, 'import cv2, numpy as np\n'), ((229, 277), 'cv2.circle', 'cv2.circle', (['img', '(400, 50)', '(30)', '(255, 255, 0)', '(5)'], {}), '(img, (400, 50), 30, (255, 255, 0), 5)\n', (239, 277), False, 'import cv2, numpy as np\n'), ((271, 358), 'cv2.putText', 'cv2.putText', (['img', '""" OPENCV """', '(300, 200)', 'cv2.FONT_HERSHEY_COMPLEX', '(1)', '(0, 150, 0)'], {}), "(img, ' OPENCV ', (300, 200), cv2.FONT_HERSHEY_COMPLEX, 1, (0, \n 150, 0))\n", (282, 358), False, 'import cv2, numpy as np\n'), ((347, 371), 'cv2.imshow', 'cv2.imshow', (['"""image"""', 'img'], {}), "('image', img)\n", (357, 371), False, 'import cv2, numpy as np\n'), ((372, 386), 'cv2.waitKey', 'cv2.waitKey', (['(0)'], {}), '(0)\n', (383, 386), False, 'import cv2, numpy as np\n')]
''' Created on April 27, 2018 @author: <NAME> ''' from evaluation.experiment import Experiment import data.load_data as load_data import numpy as np import os gt, annos, doc_start, text, gt_nocrowd, doc_start_nocrowd, text_nocrowd, gt_val, _ = \ load_data.load_ner_data(False) # debug with subset ------- s = 100 idxs = np.argwhere(gt!=-1)[:s, 0] gt = gt[idxs] annos = annos[idxs] doc_start = doc_start[idxs] text = text[idxs] gt_val = gt_val[idxs] # ------------------------- num_reps = 10 batch_frac = 0.03 AL_iters = 10 output_dir = os.path.join(load_data.output_root_dir, 'ner_al') if not os.path.isdir(output_dir): os.mkdir(output_dir) # ACTIVE LEARNING WITH UNCERTAINTY SAMPLING for rep in range(1, num_reps): beta0_factor = 0.1 alpha0_diags = 1 # best_diags alpha0_factor = 1 # 9 # best_factor exp = Experiment(output_dir, 9, annos, gt, doc_start, text, annos, gt_val, doc_start, text, alpha0_factor=alpha0_factor, alpha0_diags=alpha0_diags, beta0_factor=beta0_factor, max_iter=20, crf_probs=True, rep=rep) exp.methods = [ 'bac_seq_integrateIF', 'HMM_crowd', ] results, preds, probs, results_nocrowd, preds_nocrowd, probs_nocrowd = exp.run_methods( active_learning=True, AL_batch_fraction=batch_frac, max_AL_iters=AL_iters ) beta0_factor = 0.1 alpha0_diags = 100 # best_diags alpha0_factor = 0.1 #9 # best_factor exp = Experiment(output_dir, 9, annos, gt, doc_start, text, annos, gt_val, doc_start, text, alpha0_factor=alpha0_factor, alpha0_diags=alpha0_diags, beta0_factor=beta0_factor, max_iter=20, crf_probs=True, rep=rep) # run all the methods that don't require tuning here exp.methods = [ 'bac_ibcc_integrateIF', ] results, preds, probs, results_nocrowd, preds_nocrowd, probs_nocrowd = exp.run_methods( active_learning=True, AL_batch_fraction=batch_frac, max_AL_iters=AL_iters ) beta0_factor = 10 alpha0_diags = 1 # best_diags alpha0_factor = 1#9 # best_factor exp = Experiment(output_dir, 9, annos, gt, doc_start, text, annos, gt_val, doc_start, text, alpha0_factor=alpha0_factor, alpha0_diags=alpha0_diags, beta0_factor=beta0_factor, max_iter=20, crf_probs=True, rep=rep) exp.methods = [ 'bac_vec_integrateIF', ] results, preds, probs, results_nocrowd, preds_nocrowd, probs_nocrowd = exp.run_methods( active_learning=True, AL_batch_fraction=batch_frac, max_AL_iters=AL_iters ) beta0_factor = 0.1 alpha0_diags = 1 # best_diags alpha0_factor = 0.1#9 # best_factor exp = Experiment(output_dir, 9, annos, gt, doc_start, text, annos, gt_val, doc_start, text, alpha0_factor=alpha0_factor, alpha0_diags=alpha0_diags, beta0_factor=beta0_factor, max_iter=20, crf_probs=True, rep=rep) exp.methods = [ 'ibcc', 'ds', 'majority' ] results, preds, probs, results_nocrowd, preds_nocrowd, probs_nocrowd = exp.run_methods( active_learning=True, AL_batch_fraction=batch_frac, max_AL_iters=AL_iters )
[ "os.mkdir", "data.load_data.load_ner_data", "os.path.isdir", "evaluation.experiment.Experiment", "numpy.argwhere", "os.path.join" ]
[((252, 282), 'data.load_data.load_ner_data', 'load_data.load_ner_data', (['(False)'], {}), '(False)\n', (275, 282), True, 'import data.load_data as load_data\n'), ((545, 594), 'os.path.join', 'os.path.join', (['load_data.output_root_dir', '"""ner_al"""'], {}), "(load_data.output_root_dir, 'ner_al')\n", (557, 594), False, 'import os\n'), ((327, 348), 'numpy.argwhere', 'np.argwhere', (['(gt != -1)'], {}), '(gt != -1)\n', (338, 348), True, 'import numpy as np\n'), ((602, 627), 'os.path.isdir', 'os.path.isdir', (['output_dir'], {}), '(output_dir)\n', (615, 627), False, 'import os\n'), ((633, 653), 'os.mkdir', 'os.mkdir', (['output_dir'], {}), '(output_dir)\n', (641, 653), False, 'import os\n'), ((840, 1054), 'evaluation.experiment.Experiment', 'Experiment', (['output_dir', '(9)', 'annos', 'gt', 'doc_start', 'text', 'annos', 'gt_val', 'doc_start', 'text'], {'alpha0_factor': 'alpha0_factor', 'alpha0_diags': 'alpha0_diags', 'beta0_factor': 'beta0_factor', 'max_iter': '(20)', 'crf_probs': '(True)', 'rep': 'rep'}), '(output_dir, 9, annos, gt, doc_start, text, annos, gt_val,\n doc_start, text, alpha0_factor=alpha0_factor, alpha0_diags=alpha0_diags,\n beta0_factor=beta0_factor, max_iter=20, crf_probs=True, rep=rep)\n', (850, 1054), False, 'from evaluation.experiment import Experiment\n'), ((1459, 1673), 'evaluation.experiment.Experiment', 'Experiment', (['output_dir', '(9)', 'annos', 'gt', 'doc_start', 'text', 'annos', 'gt_val', 'doc_start', 'text'], {'alpha0_factor': 'alpha0_factor', 'alpha0_diags': 'alpha0_diags', 'beta0_factor': 'beta0_factor', 'max_iter': '(20)', 'crf_probs': '(True)', 'rep': 'rep'}), '(output_dir, 9, annos, gt, doc_start, text, annos, gt_val,\n doc_start, text, alpha0_factor=alpha0_factor, alpha0_diags=alpha0_diags,\n beta0_factor=beta0_factor, max_iter=20, crf_probs=True, rep=rep)\n', (1469, 1673), False, 'from evaluation.experiment import Experiment\n'), ((2126, 2340), 'evaluation.experiment.Experiment', 'Experiment', (['output_dir', '(9)', 'annos', 'gt', 'doc_start', 'text', 'annos', 'gt_val', 'doc_start', 'text'], {'alpha0_factor': 'alpha0_factor', 'alpha0_diags': 'alpha0_diags', 'beta0_factor': 'beta0_factor', 'max_iter': '(20)', 'crf_probs': '(True)', 'rep': 'rep'}), '(output_dir, 9, annos, gt, doc_start, text, annos, gt_val,\n doc_start, text, alpha0_factor=alpha0_factor, alpha0_diags=alpha0_diags,\n beta0_factor=beta0_factor, max_iter=20, crf_probs=True, rep=rep)\n', (2136, 2340), False, 'from evaluation.experiment import Experiment\n'), ((2738, 2952), 'evaluation.experiment.Experiment', 'Experiment', (['output_dir', '(9)', 'annos', 'gt', 'doc_start', 'text', 'annos', 'gt_val', 'doc_start', 'text'], {'alpha0_factor': 'alpha0_factor', 'alpha0_diags': 'alpha0_diags', 'beta0_factor': 'beta0_factor', 'max_iter': '(20)', 'crf_probs': '(True)', 'rep': 'rep'}), '(output_dir, 9, annos, gt, doc_start, text, annos, gt_val,\n doc_start, text, alpha0_factor=alpha0_factor, alpha0_diags=alpha0_diags,\n beta0_factor=beta0_factor, max_iter=20, crf_probs=True, rep=rep)\n', (2748, 2952), False, 'from evaluation.experiment import Experiment\n')]
import h5py import numpy import numpy as np from pathlib import Path import torch from matplotlib import pyplot title_font = { 'fontsize': 50, 'fontweight': 'bold' } file_path = 'data/raw/MVP_Test_CP.h5' input_file = h5py.File(file_path, 'r') index = 4000 temp = index // 26 incomplete_pcd = np.array(input_file['incomplete_pcds'][index]) complete_pcd = np.array(input_file['complete_pcds'][temp]) label = np.array(input_file['labels'][index]) target_pcd = incomplete_pcd label_pcd = incomplete_pcd label_name = "incomplete" print(complete_pcd.shape) partial_ppp = [point for point in target_pcd if point[0] >= 0 and point[1] >= 0 and point[2] >= 0] partial_npp = [point for point in target_pcd if point[0] < 0 and point[1] >= 0 and point[2] >= 0] partial_pnp = [point for point in target_pcd if point[0] >= 0 and point[1] < 0 and point[2] >= 0] partial_ppn = [point for point in target_pcd if point[0] >= 0 and point[1] >= 0 and point[2] < 0] partial_pnn = [point for point in target_pcd if point[0] >= 0 and point[1] < 0 and point[2] < 0] partial_npn = [point for point in target_pcd if point[0] < 0 and point[1] >= 0 and point[2] < 0] partial_nnp = [point for point in target_pcd if point[0] < 0 and point[1] < 0 and point[2] >= 0] partial_nnn = [point for point in target_pcd if point[0] < 0 and point[1] < 0 and point[2] < 0] partial_ppp = np.array(partial_ppp) partial_npp = np.array(partial_npp) partial_pnp = np.array(partial_pnp) partial_ppn = np.array(partial_ppn) partial_pnn = np.array(partial_pnn) partial_npn = np.array(partial_npn) partial_nnp = np.array(partial_nnp) partial_nnn = np.array(partial_nnn) fig = pyplot.figure(figsize=(30, 30)) print( partial_ppp.shape[0] + partial_npp.shape[0] + partial_pnp.shape[0] + partial_ppn.shape[0] + partial_pnn.shape[0] + partial_npn.shape[0] + partial_nnp.shape[0] + partial_nnn.shape[0] ) if partial_ppp.ndim == 2: ppp = fig.add_subplot(3, 3, 1, projection="3d") ppp.scatter(partial_ppp[:, 0], partial_ppp[:, 2], partial_ppp[:, 1], c='royalblue') pyplot.title("ppp", fontdict=title_font) if partial_npp.ndim == 2: npp = fig.add_subplot(3, 3, 2, projection="3d") npp.scatter(partial_npp[:, 0], partial_npp[:, 2], partial_npp[:, 1], c='royalblue') pyplot.title("npp", fontdict=title_font) if partial_pnp.ndim == 2: pnp = fig.add_subplot(3, 3, 3, projection="3d") pnp.scatter(partial_pnp[:, 0], partial_pnp[:, 2], partial_pnp[:, 1], c='royalblue') pyplot.title("pnp", fontdict=title_font) if partial_ppn.ndim == 2: ppn = fig.add_subplot(3, 3, 4, projection="3d") ppn.scatter(partial_ppn[:, 0], partial_ppn[:, 2], partial_ppn[:, 1], c='royalblue') pyplot.title("ppn", fontdict=title_font) if partial_pnn.ndim == 2: pnn = fig.add_subplot(3, 3, 5, projection="3d") pnn.scatter(partial_pnn[:, 0], partial_pnn[:, 2], partial_pnn[:, 1], c='royalblue') pyplot.title("pnn", fontdict=title_font) if partial_npn.ndim == 2: npn = fig.add_subplot(3, 3, 6, projection="3d") npn.scatter(partial_npn[:, 0], partial_npn[:, 2], partial_npn[:, 1], c='royalblue') pyplot.title("npn", fontdict=title_font) if partial_nnp.ndim == 2: nnp = fig.add_subplot(3, 3, 7, projection="3d") nnp.scatter(partial_nnp[:, 0], partial_nnp[:, 2], partial_nnp[:, 1], c='royalblue') pyplot.title("nnp", fontdict=title_font) if partial_nnn.ndim == 2: nnn = fig.add_subplot(3, 3, 8, projection="3d") nnn.scatter(partial_nnn[:, 0], partial_nnn[:, 2], partial_nnn[:, 1], c='royalblue') pyplot.title("nnn", fontdict=title_font) if label_pcd.ndim == 2: label_plot = fig.add_subplot(3, 3, 9, projection="3d") label_plot.scatter(label_pcd[:, 0], label_pcd[:, 2], label_pcd[:, 1], c='royalblue') pyplot.title(label_name, fontdict=title_font) pyplot.show() # # # # # # ax2 = fig.add_subplot(122, projection="3d") # ax2.scatter(incomplete_pcd[:, 0], incomplete_pcd[:, 2], incomplete_pcd[:, 1], c='red') # pyplot.show() # # print(incomplete_pcd.shape) # print(complete_pcd.shape) # # for index in range(100): # temp = index // 26 # incomplete_pcd = np.array(input_file['incomplete_pcds'][index]) # complete_pcd = np.array(input_file['complete_pcds'][temp]) # # print(incomplete_pcd.shape, complete_pcd.shape)
[ "matplotlib.pyplot.title", "h5py.File", "matplotlib.pyplot.show", "matplotlib.pyplot.figure", "numpy.array" ]
[((228, 253), 'h5py.File', 'h5py.File', (['file_path', '"""r"""'], {}), "(file_path, 'r')\n", (237, 253), False, 'import h5py\n'), ((305, 351), 'numpy.array', 'np.array', (["input_file['incomplete_pcds'][index]"], {}), "(input_file['incomplete_pcds'][index])\n", (313, 351), True, 'import numpy as np\n'), ((367, 410), 'numpy.array', 'np.array', (["input_file['complete_pcds'][temp]"], {}), "(input_file['complete_pcds'][temp])\n", (375, 410), True, 'import numpy as np\n'), ((419, 456), 'numpy.array', 'np.array', (["input_file['labels'][index]"], {}), "(input_file['labels'][index])\n", (427, 456), True, 'import numpy as np\n'), ((1362, 1383), 'numpy.array', 'np.array', (['partial_ppp'], {}), '(partial_ppp)\n', (1370, 1383), True, 'import numpy as np\n'), ((1398, 1419), 'numpy.array', 'np.array', (['partial_npp'], {}), '(partial_npp)\n', (1406, 1419), True, 'import numpy as np\n'), ((1434, 1455), 'numpy.array', 'np.array', (['partial_pnp'], {}), '(partial_pnp)\n', (1442, 1455), True, 'import numpy as np\n'), ((1470, 1491), 'numpy.array', 'np.array', (['partial_ppn'], {}), '(partial_ppn)\n', (1478, 1491), True, 'import numpy as np\n'), ((1506, 1527), 'numpy.array', 'np.array', (['partial_pnn'], {}), '(partial_pnn)\n', (1514, 1527), True, 'import numpy as np\n'), ((1542, 1563), 'numpy.array', 'np.array', (['partial_npn'], {}), '(partial_npn)\n', (1550, 1563), True, 'import numpy as np\n'), ((1578, 1599), 'numpy.array', 'np.array', (['partial_nnp'], {}), '(partial_nnp)\n', (1586, 1599), True, 'import numpy as np\n'), ((1614, 1635), 'numpy.array', 'np.array', (['partial_nnn'], {}), '(partial_nnn)\n', (1622, 1635), True, 'import numpy as np\n'), ((1643, 1674), 'matplotlib.pyplot.figure', 'pyplot.figure', ([], {'figsize': '(30, 30)'}), '(figsize=(30, 30))\n', (1656, 1674), False, 'from matplotlib import pyplot\n'), ((3819, 3832), 'matplotlib.pyplot.show', 'pyplot.show', ([], {}), '()\n', (3830, 3832), False, 'from matplotlib import pyplot\n'), ((2070, 2110), 'matplotlib.pyplot.title', 'pyplot.title', (['"""ppp"""'], {'fontdict': 'title_font'}), "('ppp', fontdict=title_font)\n", (2082, 2110), False, 'from matplotlib import pyplot\n'), ((2282, 2322), 'matplotlib.pyplot.title', 'pyplot.title', (['"""npp"""'], {'fontdict': 'title_font'}), "('npp', fontdict=title_font)\n", (2294, 2322), False, 'from matplotlib import pyplot\n'), ((2494, 2534), 'matplotlib.pyplot.title', 'pyplot.title', (['"""pnp"""'], {'fontdict': 'title_font'}), "('pnp', fontdict=title_font)\n", (2506, 2534), False, 'from matplotlib import pyplot\n'), ((2706, 2746), 'matplotlib.pyplot.title', 'pyplot.title', (['"""ppn"""'], {'fontdict': 'title_font'}), "('ppn', fontdict=title_font)\n", (2718, 2746), False, 'from matplotlib import pyplot\n'), ((2918, 2958), 'matplotlib.pyplot.title', 'pyplot.title', (['"""pnn"""'], {'fontdict': 'title_font'}), "('pnn', fontdict=title_font)\n", (2930, 2958), False, 'from matplotlib import pyplot\n'), ((3130, 3170), 'matplotlib.pyplot.title', 'pyplot.title', (['"""npn"""'], {'fontdict': 'title_font'}), "('npn', fontdict=title_font)\n", (3142, 3170), False, 'from matplotlib import pyplot\n'), ((3342, 3382), 'matplotlib.pyplot.title', 'pyplot.title', (['"""nnp"""'], {'fontdict': 'title_font'}), "('nnp', fontdict=title_font)\n", (3354, 3382), False, 'from matplotlib import pyplot\n'), ((3554, 3594), 'matplotlib.pyplot.title', 'pyplot.title', (['"""nnn"""'], {'fontdict': 'title_font'}), "('nnn', fontdict=title_font)\n", (3566, 3594), False, 'from matplotlib import pyplot\n'), ((3772, 3817), 'matplotlib.pyplot.title', 'pyplot.title', (['label_name'], {'fontdict': 'title_font'}), '(label_name, fontdict=title_font)\n', (3784, 3817), False, 'from matplotlib import pyplot\n')]
import numpy as np import pandas as pd import urllib.request import json import time import argparse from youtube_transcript_api import YouTubeTranscriptApi # Note: An API key is only necessary when getting videos from a channel global api_key api_key = '' def get_channel_videos(channel_id, delay=0): if api_key == '': raise Exception("Must specify an API key. See README.md for more info.") base_search_url = 'https://www.googleapis.com/youtube/v3/search?' first_url = base_search_url+'key={}&channelId={}&part=snippet,id&order=date&maxResults=25'.format(api_key, channel_id) titles = [] video_links = [] url = first_url while True: time.sleep(delay) inp = urllib.request.urlopen(url) resp = json.load(inp) for i in resp['items']: if i['id']['kind'] == "youtube#video": title = i['snippet']['title'] if 'Season' in title and 'Episode' in title: titles.append(title) video_links.append(i['id']['videoId']) try: next_page_token = resp['nextPageToken'] url = first_url + '&pageToken={}'.format(next_page_token) except: break return titles, video_links def clean_links(links): if isinstance(links, list): links = np.array(links) clean_link = lambda l: l[l.index("v=") + 2:] if 'youtube' in l.lower() else l f = np.vectorize(clean_link) return f(links) def load_transcript(link): try: d = YouTubeTranscriptApi.get_transcript(link) return ' '.join([i['text'] for i in d]), True except: return '', False def main(): parser = argparse.ArgumentParser() parser.add_argument('data', type=str, help='Path to save all tanscript .txt data') parser.add_argument('-l', '--links', help='Path for csv file containing video titles and links', default=None) parser.add_argument('-c', '--channel', help='Download all video transcripts from a given channel ID (Requires API key)', default=None) parser.add_argument('-s', '--separate', help="Path to save transcripts as separate .txt files", default="transcripts/") args = parser.parse_args() # Process arguments args.data = args.data + '.txt' if args.data[-4:] != '.txt' else args.data args.separate = args.separate + '/' if args.separate[-1] != '/' else args.separate # Get all YouTube video links from a given YouTube channel if args.channel is not None: titles, links = get_channel_videos(args.channel, delay=0.05) d = {'title': titles, 'link': links} df = pd.DataFrame(d) df.to_csv('links.csv', index=False) # Get YouTube video links from a csv file elif args.links is not None: df = pd.read_csv(args.links) titles = df.title.values links = df.link.values else: raise Exception("Use either '--links' or '--channel' to specify YouTube videos to load. See README.md for more info.") links = clean_links(links) # Load transcripts data_file = open(args.data, "w", encoding="utf-8") for count, link in enumerate(links): # Get transcript transcript, passed = load_transcript(link) if passed: # Save transcript to separate file text_file = open(args.separate + titles[count] + ".txt", "w", encoding="utf-8") text_file.write(transcript) text_file.close() # Save transcript to main file data_file.write(transcript + '\n') print("Done processing ({}/{}):".format(count+1, len(links)), titles[count]) else: print("Couldn't get transcript ({}/{}):".format(count+1, len(links)), titles[count]) data_file.close() if __name__ == "__main__": main()
[ "pandas.DataFrame", "json.load", "numpy.vectorize", "argparse.ArgumentParser", "pandas.read_csv", "youtube_transcript_api.YouTubeTranscriptApi.get_transcript", "time.sleep", "numpy.array" ]
[((1452, 1476), 'numpy.vectorize', 'np.vectorize', (['clean_link'], {}), '(clean_link)\n', (1464, 1476), True, 'import numpy as np\n'), ((1707, 1732), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (1730, 1732), False, 'import argparse\n'), ((690, 707), 'time.sleep', 'time.sleep', (['delay'], {}), '(delay)\n', (700, 707), False, 'import time\n'), ((765, 779), 'json.load', 'json.load', (['inp'], {}), '(inp)\n', (774, 779), False, 'import json\n'), ((1345, 1360), 'numpy.array', 'np.array', (['links'], {}), '(links)\n', (1353, 1360), True, 'import numpy as np\n'), ((1547, 1588), 'youtube_transcript_api.YouTubeTranscriptApi.get_transcript', 'YouTubeTranscriptApi.get_transcript', (['link'], {}), '(link)\n', (1582, 1588), False, 'from youtube_transcript_api import YouTubeTranscriptApi\n'), ((2645, 2660), 'pandas.DataFrame', 'pd.DataFrame', (['d'], {}), '(d)\n', (2657, 2660), True, 'import pandas as pd\n'), ((2798, 2821), 'pandas.read_csv', 'pd.read_csv', (['args.links'], {}), '(args.links)\n', (2809, 2821), True, 'import pandas as pd\n')]
from flask import Flask, render_template, jsonify, request, url_for from shapely.geometry import Point as Shapely_point, mapping from geojson import Point as Geoj_point, Polygon as Geoj_polygon, Feature, FeatureCollection from datetime import datetime from sqlalchemy import * import pandas as pd import geopandas as gpd import numpy as np #import psycopg2 as pg import json import leaflet as L from elastic_app_search import Client from elasticsearch import Elasticsearch from elasticapm.contrib.flask import ElasticAPM import matplotlib.colors as cl import h3 import h3.api.basic_int as h3int import json import h3pandas import cmasher as cmr import plotly import plotly.express as px from scipy.stats import percentileofscore from scipy import stats import plotly.graph_objects as go import os import datetime from netCDF4 import Dataset import shapely.wkt import folium import ftplib from ftplib import FTP from pathlib import Path from os import path, walk import timezonefinder, pytz import plotly.express as px import plotly.graph_objects as go from geopy.geocoders import Nominatim import math #from models import * def fixVarName(varName): newVarName = str(varName[1:-1]) newVarName = str(newVarName).replace(' ','').replace(':','_').replace('.','D').replace('-','M') return newVarName ############ globals outDir = '/home/sumer/my_project_dir/ncep/' updated_data_available_file = '/home/sumer/weather/weather-forecast/updated_data_available.txt' #outDir = '/root/ncep/data/' #updated_data_available_file = '/root/ncep/scripts/updated_data_available.txt' list_of_ncfiles = [x for x in os.listdir(outDir) if x.endswith('.nc')] list_of_ncfiles.sort() time_dim = len(list_of_ncfiles) """ varDict = {'TMP_2maboveground': 'Air Temp [C] (2 m above surface)', 'TSOIL_0D1M0D4mbelowground':'Soil Temperature [C] - 0.1-0.4 m below ground', 'SOILW_0D1M0D4mbelowground':'Volumetric Soil Moisture Content [Fraction] - 0.1-0.4 m below ground', 'CRAIN_surface':'Rainfall Boolean [1/0]', } #varList = ['TMP_2maboveground','TSOIL_0D1M0D4mbelowground','SOILW_0D1M0D4mbelowground', 'CRAIN_surface'] """ #Relative Humidity [%] var1 = ':RH:2 m above ground:' #Temperature [K] var2 = ':TMP:2 m above ground:' #Soil Temperature [K] var3 = ':TSOIL:0-0.1 m below ground:' var4 = ':TSOIL:0.1-0.4 m below ground:' var5 = ':TSOIL:0.4-1 m below ground:' var6 = ':TSOIL:1-2 m below ground:' #Volumetric Soil Moisture Content [Fraction] var7 = ':SOILW:0-0.1 m below ground:' var8 = ':SOILW:0.1-0.4 m below ground:' var9 = ':SOILW:0.4-1 m below ground:' var10 = ':SOILW:1-2 m below ground:' #Specific Humidity [kg/kg] var11 = ':SPFH:2 m above ground:' #Dew Point Temperature [K] var12 = ':DPT:2 m above ground:' #Pressure Reduced to MSL [Pa] var13 = ':PRMSL:mean sea level:' #Pressure [Pa] var14 = ':PRES:max wind:' #Wind Speed (Gust) [m/s] var15 = ':GUST:surface:' #Total Cloud Cover [%] var16 = ':TCDC:entire atmosphere:' #Downward Short-Wave Radiation Flux [W/m^2] var17 = ':DSWRF:surface:' #Downward Long-Wave Radiation Flux [W/m^2] var18 = ':DLWRF:surface:' #Upward Short-Wave Radiation Flux [W/m^2] var19 = ':USWRF:surface:' #Upward Long-Wave Radiation Flux [W/m^2] var20 = ':ULWRF:surface:' #Upward Long-Wave Radiation Flux [W/m^2] var20 = ':ULWRF:surface:' #Soil Type [-] var21 = ':SOTYP:surface:' #Categorical Rain [-] (3 hr forecast) var22 = ':CRAIN:surface:' #Precipitation Rate [kg/m^2/s] var23 = ':PRATE:surface:' varStr = var1+'|'+var2+'|'+var3+'|'+var4+'|'+var5+'|'+var6+'|'+var7+'|'+var8+'|'+var9+'|'+var10+'|'+var11+'|'+var12+'|'+var13+'|'+var14+'|'+var15+'|'+var16+'|'+var17+'|'+var18+'|'+var19+'|'+var20+'|'+var21+'|'+var22+'|'+var23 ############################################### varDict = {fixVarName(var2) : 'Air Temp [C] (2 m above surface)', fixVarName(var4) : 'Soil Temperature [C] - 0.1-0.4 m below ground', fixVarName(var8) : 'Volumetric Soil Moisture Content [Fraction] - 0.1-0.4 m below ground', fixVarName(var22) : 'Rainfall Boolean [1/0]', fixVarName(var23) : 'Precipitation Rate [mm]', fixVarName(var1) : 'Relative Humidity [%]', fixVarName(var12) : 'Dew Point Temperature [C]', fixVarName(var13) : 'Pressure Reduced to MSL [Pa]', fixVarName(var14) : 'Pressure [Pa]', fixVarName(var15) : 'Wind Speed (Gust) [m/s]', fixVarName(var16) : 'Total Cloud Cover [%]', } varList = list(varDict.keys()) var_val3D = [] var_val4D = [] #NOTE: the variable are in opposite order var_val4D[lat, lon, forecast_time_index, 0/1/2/3, where 0=CRAIN, 1=SOILW... etc] updatedDtStr = list_of_ncfiles[0].split('__')[0] updatedDt = datetime.datetime.strptime(updatedDtStr,'%Y%m%d_%H%M%S') updatedDtDisplay = datetime.datetime.strftime(updatedDt, '%Y-%m-%dT%H%M%S') #get the forecast end dt forecastEndDtStr = list_of_ncfiles[-1].split('__')[1].split('__')[0] forecastEndDt = datetime.datetime.strptime(forecastEndDtStr,'%Y%m%d_%H%M%S') forecastEndDtDisplay = datetime.datetime.strftime(forecastEndDt, '%Y-%m-%dT%H%M%S') i=0 for varName in varList: tm_arr = [] print('Reading data for: '+ varName) j=0 for f in list_of_ncfiles: #f = '20211209_000000__20211212_210000__093___gfs.t00z.pgrb2.0p25.f093.grb2.nc' ncin = Dataset(outDir+f, "r") titleStr = varDict[varName] var_mat = ncin.variables[varName][:] if 'Temp' in titleStr: var_val = var_mat.squeeze() - 273.15 #convert to DegC elif 'Precipitation Rate' in titleStr: var_val = var_mat.squeeze() * 3600 #convert to mm/hr else: var_val = var_mat.squeeze() lons = ncin.variables['longitude'][:] lats = ncin.variables['latitude'][:] tms = ncin.variables['time'][:] #tmstmpStr = datetime.datetime.fromtimestamp(tm.data[0]).strftime('%Y%m%d%H%M%S') if j>0: var_val3D = np.dstack((var_val3D,var_val.data)) else: var_val3D = var_val.data tm_arr.append(tms.data[0]) ncin.close() j=j+1 if i>0: var_val3D_rshp = np.reshape(var_val3D , (720,1440,time_dim,1)) var_val4D = np.append( var_val3D_rshp , var_val4D , axis = 3) else: var_val4D = np.reshape(var_val3D , (720,1440,time_dim,1)) i=i+1 def fixToLocalTime(df,lat,lon): tf = timezonefinder.TimezoneFinder() # From the lat/long, get the tz-database-style time zone name (e.g. 'America/Vancouver') or None timezone_str = tf.certain_timezone_at(lat=float(lat), lng=float(lon)) timezone = pytz.timezone(timezone_str) df['FORECAST_DATE_LOCAL']=df.FORECAST_DATE_UTC.apply(lambda x: x + timezone.utcoffset(x)) return df def getWeatherForecastVars(): weatherForecastVars = {} weatherForecastVars['source'] = 'United States NOAA - NOMADS Global Forecast Model' weatherForecastVars['variables'] = list(varDict.values()) weatherForecastVars['updated at time [UTC]'] = updatedDt weatherForecastVars['forecast start time [UTC]'] = updatedDtDisplay weatherForecastVars['forecast end time [UTC]'] = forecastEndDtDisplay weatherForecastVars['forecast type'] = 'hourly' weatherForecastVars['Number of time intervals'] = time_dim return weatherForecastVars def get4DWeatherForecast(lon, lat): df_all = pd.DataFrame() try: lat = float(lat) lon = float(lon) idx=len(varList)-1 updated_dtStr = list_of_ncfiles[0].split('__')[0] updated_dt = datetime.datetime.strptime(updated_dtStr, '%Y%m%d_%H%M%S') df_all = pd.DataFrame() updated_dts = [updated_dt for x in range(0,len(tm_arr))] forecast_dts = [datetime.datetime.utcfromtimestamp(int(x)) for x in tm_arr] df_all['UPDATED_DATE_UTC']=updated_dts df_all['FORECAST_DATE_UTC']=forecast_dts for varName in varList: df = pd.DataFrame() #print(varName) #try: titleStr = varDict[varName] lon_ind = [i for i,v in enumerate(lons.data) if v >= lon][0] lat_ind = [i for i,v in enumerate(lats.data) if v >= lat][0] vv = var_val4D[lat_ind, lon_ind,:,idx] df[titleStr]=vv df_all = pd.concat([df_all, df],axis=1) idx=idx-1 except Exception as e: print(e) return df_all ############ #create the app app = Flask(__name__) app.config['JSON_SORT_KEYS']=False error_res = {} #rendering the entry using any of these routes: @app.route('/') @app.route('/index') @app.route('/home') def index(): return render_template('index.html') #global weather forecast implementation @app.route('/weatherForecastVariables') def weatherForecastVariables(): try: weatherForcastVars = getWeatherForecastVars() except ValueError: error_res['db function call error'] = 'function call failed for getWeatherForecastVars' error_msg = jsonify(error_res) return jsonify(weatherForcastVars) #global weather forecast implementation @app.route('/weatherForecast') def weatherForecast(): returnType = 'json' #default lat = request.args.get('lat') lon = request.args.get('lon') try: returnType = request.args.get('format') except: returnType = 'json' try: weatherForcast_df = get4DWeatherForecast(lon, lat) localWeatherForcast_df = fixToLocalTime(weatherForcast_df,lat,lon) try: #try and get a location, if not, then just report on lat, lon geolocator = Nominatim(user_agent="myGeolocator") locStr = geolocator.reverse(str(lat)+","+str(lon)) tok = locStr.address.split(' ') loc = ' '.join(tok[3:]) except: loc='Lat='+lat+', Lon='+lon #Make the various graphs varName = 'Air Temp [C] (2 m above surface)' df = localWeatherForcast_df[['FORECAST_DATE_LOCAL',varName]] df.set_index(['FORECAST_DATE_LOCAL'], inplace=True, drop=True) fig = px.line(df, y=varName, title='Hourly Forecast for '+loc) airTempGraph = json.dumps(fig, cls=plotly.utils.PlotlyJSONEncoder) varName = 'Soil Temperature [C] - 0.1-0.4 m below ground' df = localWeatherForcast_df[['FORECAST_DATE_LOCAL',varName]] df.set_index(['FORECAST_DATE_LOCAL'], inplace=True, drop=True) fig = px.line(df, y=varName, title='Hourly Forecast for '+loc) soilTempGraph = json.dumps(fig, cls=plotly.utils.PlotlyJSONEncoder) varName = 'Volumetric Soil Moisture Content [Fraction] - 0.1-0.4 m below ground' df = localWeatherForcast_df[['FORECAST_DATE_LOCAL',varName]] df.set_index(['FORECAST_DATE_LOCAL'], inplace=True, drop=True) fig = px.line(df, y=varName, title='Hourly Forecast for '+loc) soilMoistureGraph = json.dumps(fig, cls=plotly.utils.PlotlyJSONEncoder) varName = 'Rainfall Boolean [1/0]' df = localWeatherForcast_df[['FORECAST_DATE_LOCAL',varName]] df.set_index(['FORECAST_DATE_LOCAL'], inplace=True, drop=True) fig = px.line(df, y=varName, title='Hourly Forecast for '+loc) rainBoolGraph = json.dumps(fig, cls=plotly.utils.PlotlyJSONEncoder) varName = 'Precipitation Rate [mm]' df = localWeatherForcast_df[['FORECAST_DATE_LOCAL',varName]] df.set_index(['FORECAST_DATE_LOCAL'], inplace=True, drop=True) fig = px.line(df, y=varName, title='Hourly Forecast for '+loc) precipGraph = json.dumps(fig, cls=plotly.utils.PlotlyJSONEncoder) varName = 'Relative Humidity [%]' df = localWeatherForcast_df[['FORECAST_DATE_LOCAL',varName]] df.set_index(['FORECAST_DATE_LOCAL'], inplace=True, drop=True) fig = px.line(df, y=varName, title='Hourly Forecast for '+loc) relativeHumidityGraph = json.dumps(fig, cls=plotly.utils.PlotlyJSONEncoder) varName = 'Dew Point Temperature [C]' df = localWeatherForcast_df[['FORECAST_DATE_LOCAL',varName]] df.set_index(['FORECAST_DATE_LOCAL'], inplace=True, drop=True) fig = px.line(df, y=varName, title='Hourly Forecast for '+loc) dewPointGraph = json.dumps(fig, cls=plotly.utils.PlotlyJSONEncoder) varName = 'Pressure Reduced to MSL [Pa]' df = localWeatherForcast_df[['FORECAST_DATE_LOCAL',varName]] df.set_index(['FORECAST_DATE_LOCAL'], inplace=True, drop=True) fig = px.line(df, y=varName, title='Hourly Forecast for '+loc) mslPressureGraph = json.dumps(fig, cls=plotly.utils.PlotlyJSONEncoder) varName = 'Pressure [Pa]' df = localWeatherForcast_df[['FORECAST_DATE_LOCAL',varName]] df.set_index(['FORECAST_DATE_LOCAL'], inplace=True, drop=True) fig = px.line(df, y=varName, title='Hourly Forecast for '+loc) pressureGraph = json.dumps(fig, cls=plotly.utils.PlotlyJSONEncoder) varName = 'Wind Speed (Gust) [m/s]' df = localWeatherForcast_df[['FORECAST_DATE_LOCAL',varName]] df.set_index(['FORECAST_DATE_LOCAL'], inplace=True, drop=True) fig = px.line(df, y=varName, title='Hourly Forecast for '+loc) windSpeedGraph = json.dumps(fig, cls=plotly.utils.PlotlyJSONEncoder) varName = 'Total Cloud Cover [%]' df = localWeatherForcast_df[['FORECAST_DATE_LOCAL',varName]] df.set_index(['FORECAST_DATE_LOCAL'], inplace=True, drop=True) fig = px.line(df, y=varName, title='Hourly Forecast for '+loc) cloudCoverGraph = json.dumps(fig, cls=plotly.utils.PlotlyJSONEncoder) except ValueError: error_res['db function call error'] = 'DB function call failed for getWeatherForecast' error_res['value given'] = 'lat='+str(lat)+', lon='+(str(lon)) error_msg = jsonify(error_res) if len(weatherForcast_df)>0: if (returnType=='json'): res = jsonify(weatherForcast_df.to_dict(orient='records')) else: res = render_template('forecast.html', airTempGraph=airTempGraph, soilTempGraph=soilTempGraph, soilMoistureGraph=soilMoistureGraph, rainBoolGraph=rainBoolGraph, precipGraph=precipGraph, relativeHumidityGraph=relativeHumidityGraph, dewPointGraph=dewPointGraph, mslPressureGraph=mslPressureGraph, pressureGraph=pressureGraph, windSpeedGraph=windSpeedGraph, cloudCoverGraph=cloudCoverGraph, ) else: res = "{'Error': 'WeatherForecast function returned no data'}" return res #main to run the app if __name__ == '__main__': extra_files = [updated_data_available_file,] app.run(host='0.0.0.0' , port=5000, debug=True, extra_files=extra_files)
[ "datetime.datetime.strftime", "pandas.DataFrame", "netCDF4.Dataset", "numpy.dstack", "flask.request.args.get", "flask.Flask", "timezonefinder.TimezoneFinder", "plotly.express.line", "json.dumps", "geopy.geocoders.Nominatim", "numpy.append", "datetime.datetime.strptime", "flask.jsonify", "pytz.timezone", "flask.render_template", "numpy.reshape", "pandas.concat", "os.listdir" ]
[((4628, 4685), 'datetime.datetime.strptime', 'datetime.datetime.strptime', (['updatedDtStr', '"""%Y%m%d_%H%M%S"""'], {}), "(updatedDtStr, '%Y%m%d_%H%M%S')\n", (4654, 4685), False, 'import datetime\n'), ((4704, 4760), 'datetime.datetime.strftime', 'datetime.datetime.strftime', (['updatedDt', '"""%Y-%m-%dT%H%M%S"""'], {}), "(updatedDt, '%Y-%m-%dT%H%M%S')\n", (4730, 4760), False, 'import datetime\n'), ((4872, 4933), 'datetime.datetime.strptime', 'datetime.datetime.strptime', (['forecastEndDtStr', '"""%Y%m%d_%H%M%S"""'], {}), "(forecastEndDtStr, '%Y%m%d_%H%M%S')\n", (4898, 4933), False, 'import datetime\n'), ((4956, 5016), 'datetime.datetime.strftime', 'datetime.datetime.strftime', (['forecastEndDt', '"""%Y-%m-%dT%H%M%S"""'], {}), "(forecastEndDt, '%Y-%m-%dT%H%M%S')\n", (4982, 5016), False, 'import datetime\n'), ((7968, 7983), 'flask.Flask', 'Flask', (['__name__'], {}), '(__name__)\n', (7973, 7983), False, 'from flask import Flask, render_template, jsonify, request, url_for\n'), ((6135, 6166), 'timezonefinder.TimezoneFinder', 'timezonefinder.TimezoneFinder', ([], {}), '()\n', (6164, 6166), False, 'import timezonefinder, pytz\n'), ((6348, 6375), 'pytz.timezone', 'pytz.timezone', (['timezone_str'], {}), '(timezone_str)\n', (6361, 6375), False, 'import timezonefinder, pytz\n'), ((7068, 7082), 'pandas.DataFrame', 'pd.DataFrame', ([], {}), '()\n', (7080, 7082), True, 'import pandas as pd\n'), ((8162, 8191), 'flask.render_template', 'render_template', (['"""index.html"""'], {}), "('index.html')\n", (8177, 8191), False, 'from flask import Flask, render_template, jsonify, request, url_for\n'), ((8513, 8540), 'flask.jsonify', 'jsonify', (['weatherForcastVars'], {}), '(weatherForcastVars)\n', (8520, 8540), False, 'from flask import Flask, render_template, jsonify, request, url_for\n'), ((8674, 8697), 'flask.request.args.get', 'request.args.get', (['"""lat"""'], {}), "('lat')\n", (8690, 8697), False, 'from flask import Flask, render_template, jsonify, request, url_for\n'), ((8705, 8728), 'flask.request.args.get', 'request.args.get', (['"""lon"""'], {}), "('lon')\n", (8721, 8728), False, 'from flask import Flask, render_template, jsonify, request, url_for\n'), ((1607, 1625), 'os.listdir', 'os.listdir', (['outDir'], {}), '(outDir)\n', (1617, 1625), False, 'import os\n'), ((5223, 5247), 'netCDF4.Dataset', 'Dataset', (['(outDir + f)', '"""r"""'], {}), "(outDir + f, 'r')\n", (5230, 5247), False, 'from netCDF4 import Dataset\n'), ((5912, 5959), 'numpy.reshape', 'np.reshape', (['var_val3D', '(720, 1440, time_dim, 1)'], {}), '(var_val3D, (720, 1440, time_dim, 1))\n', (5922, 5959), True, 'import numpy as np\n'), ((5972, 6016), 'numpy.append', 'np.append', (['var_val3D_rshp', 'var_val4D'], {'axis': '(3)'}), '(var_val3D_rshp, var_val4D, axis=3)\n', (5981, 6016), True, 'import numpy as np\n'), ((6043, 6090), 'numpy.reshape', 'np.reshape', (['var_val3D', '(720, 1440, time_dim, 1)'], {}), '(var_val3D, (720, 1440, time_dim, 1))\n', (6053, 6090), True, 'import numpy as np\n'), ((7216, 7274), 'datetime.datetime.strptime', 'datetime.datetime.strptime', (['updated_dtStr', '"""%Y%m%d_%H%M%S"""'], {}), "(updated_dtStr, '%Y%m%d_%H%M%S')\n", (7242, 7274), False, 'import datetime\n'), ((7287, 7301), 'pandas.DataFrame', 'pd.DataFrame', ([], {}), '()\n', (7299, 7301), True, 'import pandas as pd\n'), ((8750, 8776), 'flask.request.args.get', 'request.args.get', (['"""format"""'], {}), "('format')\n", (8766, 8776), False, 'from flask import Flask, render_template, jsonify, request, url_for\n'), ((9429, 9487), 'plotly.express.line', 'px.line', (['df'], {'y': 'varName', 'title': "('Hourly Forecast for ' + loc)"}), "(df, y=varName, title='Hourly Forecast for ' + loc)\n", (9436, 9487), True, 'import plotly.express as px\n'), ((9503, 9554), 'json.dumps', 'json.dumps', (['fig'], {'cls': 'plotly.utils.PlotlyJSONEncoder'}), '(fig, cls=plotly.utils.PlotlyJSONEncoder)\n', (9513, 9554), False, 'import json\n'), ((9753, 9811), 'plotly.express.line', 'px.line', (['df'], {'y': 'varName', 'title': "('Hourly Forecast for ' + loc)"}), "(df, y=varName, title='Hourly Forecast for ' + loc)\n", (9760, 9811), True, 'import plotly.express as px\n'), ((9828, 9879), 'json.dumps', 'json.dumps', (['fig'], {'cls': 'plotly.utils.PlotlyJSONEncoder'}), '(fig, cls=plotly.utils.PlotlyJSONEncoder)\n', (9838, 9879), False, 'import json\n'), ((10101, 10159), 'plotly.express.line', 'px.line', (['df'], {'y': 'varName', 'title': "('Hourly Forecast for ' + loc)"}), "(df, y=varName, title='Hourly Forecast for ' + loc)\n", (10108, 10159), True, 'import plotly.express as px\n'), ((10180, 10231), 'json.dumps', 'json.dumps', (['fig'], {'cls': 'plotly.utils.PlotlyJSONEncoder'}), '(fig, cls=plotly.utils.PlotlyJSONEncoder)\n', (10190, 10231), False, 'import json\n'), ((10407, 10465), 'plotly.express.line', 'px.line', (['df'], {'y': 'varName', 'title': "('Hourly Forecast for ' + loc)"}), "(df, y=varName, title='Hourly Forecast for ' + loc)\n", (10414, 10465), True, 'import plotly.express as px\n'), ((10482, 10533), 'json.dumps', 'json.dumps', (['fig'], {'cls': 'plotly.utils.PlotlyJSONEncoder'}), '(fig, cls=plotly.utils.PlotlyJSONEncoder)\n', (10492, 10533), False, 'import json\n'), ((10709, 10767), 'plotly.express.line', 'px.line', (['df'], {'y': 'varName', 'title': "('Hourly Forecast for ' + loc)"}), "(df, y=varName, title='Hourly Forecast for ' + loc)\n", (10716, 10767), True, 'import plotly.express as px\n'), ((10782, 10833), 'json.dumps', 'json.dumps', (['fig'], {'cls': 'plotly.utils.PlotlyJSONEncoder'}), '(fig, cls=plotly.utils.PlotlyJSONEncoder)\n', (10792, 10833), False, 'import json\n'), ((11007, 11065), 'plotly.express.line', 'px.line', (['df'], {'y': 'varName', 'title': "('Hourly Forecast for ' + loc)"}), "(df, y=varName, title='Hourly Forecast for ' + loc)\n", (11014, 11065), True, 'import plotly.express as px\n'), ((11090, 11141), 'json.dumps', 'json.dumps', (['fig'], {'cls': 'plotly.utils.PlotlyJSONEncoder'}), '(fig, cls=plotly.utils.PlotlyJSONEncoder)\n', (11100, 11141), False, 'import json\n'), ((11319, 11377), 'plotly.express.line', 'px.line', (['df'], {'y': 'varName', 'title': "('Hourly Forecast for ' + loc)"}), "(df, y=varName, title='Hourly Forecast for ' + loc)\n", (11326, 11377), True, 'import plotly.express as px\n'), ((11394, 11445), 'json.dumps', 'json.dumps', (['fig'], {'cls': 'plotly.utils.PlotlyJSONEncoder'}), '(fig, cls=plotly.utils.PlotlyJSONEncoder)\n', (11404, 11445), False, 'import json\n'), ((11626, 11684), 'plotly.express.line', 'px.line', (['df'], {'y': 'varName', 'title': "('Hourly Forecast for ' + loc)"}), "(df, y=varName, title='Hourly Forecast for ' + loc)\n", (11633, 11684), True, 'import plotly.express as px\n'), ((11704, 11755), 'json.dumps', 'json.dumps', (['fig'], {'cls': 'plotly.utils.PlotlyJSONEncoder'}), '(fig, cls=plotly.utils.PlotlyJSONEncoder)\n', (11714, 11755), False, 'import json\n'), ((11921, 11979), 'plotly.express.line', 'px.line', (['df'], {'y': 'varName', 'title': "('Hourly Forecast for ' + loc)"}), "(df, y=varName, title='Hourly Forecast for ' + loc)\n", (11928, 11979), True, 'import plotly.express as px\n'), ((11996, 12047), 'json.dumps', 'json.dumps', (['fig'], {'cls': 'plotly.utils.PlotlyJSONEncoder'}), '(fig, cls=plotly.utils.PlotlyJSONEncoder)\n', (12006, 12047), False, 'import json\n'), ((12223, 12281), 'plotly.express.line', 'px.line', (['df'], {'y': 'varName', 'title': "('Hourly Forecast for ' + loc)"}), "(df, y=varName, title='Hourly Forecast for ' + loc)\n", (12230, 12281), True, 'import plotly.express as px\n'), ((12299, 12350), 'json.dumps', 'json.dumps', (['fig'], {'cls': 'plotly.utils.PlotlyJSONEncoder'}), '(fig, cls=plotly.utils.PlotlyJSONEncoder)\n', (12309, 12350), False, 'import json\n'), ((12524, 12582), 'plotly.express.line', 'px.line', (['df'], {'y': 'varName', 'title': "('Hourly Forecast for ' + loc)"}), "(df, y=varName, title='Hourly Forecast for ' + loc)\n", (12531, 12582), True, 'import plotly.express as px\n'), ((12601, 12652), 'json.dumps', 'json.dumps', (['fig'], {'cls': 'plotly.utils.PlotlyJSONEncoder'}), '(fig, cls=plotly.utils.PlotlyJSONEncoder)\n', (12611, 12652), False, 'import json\n'), ((5759, 5795), 'numpy.dstack', 'np.dstack', (['(var_val3D, var_val.data)'], {}), '((var_val3D, var_val.data))\n', (5768, 5795), True, 'import numpy as np\n'), ((7558, 7572), 'pandas.DataFrame', 'pd.DataFrame', ([], {}), '()\n', (7570, 7572), True, 'import pandas as pd\n'), ((7835, 7866), 'pandas.concat', 'pd.concat', (['[df_all, df]'], {'axis': '(1)'}), '([df_all, df], axis=1)\n', (7844, 7866), True, 'import pandas as pd\n'), ((8485, 8503), 'flask.jsonify', 'jsonify', (['error_res'], {}), '(error_res)\n', (8492, 8503), False, 'from flask import Flask, render_template, jsonify, request, url_for\n'), ((9024, 9060), 'geopy.geocoders.Nominatim', 'Nominatim', ([], {'user_agent': '"""myGeolocator"""'}), "(user_agent='myGeolocator')\n", (9033, 9060), False, 'from geopy.geocoders import Nominatim\n'), ((12844, 12862), 'flask.jsonify', 'jsonify', (['error_res'], {}), '(error_res)\n', (12851, 12862), False, 'from flask import Flask, render_template, jsonify, request, url_for\n'), ((13000, 13406), 'flask.render_template', 'render_template', (['"""forecast.html"""'], {'airTempGraph': 'airTempGraph', 'soilTempGraph': 'soilTempGraph', 'soilMoistureGraph': 'soilMoistureGraph', 'rainBoolGraph': 'rainBoolGraph', 'precipGraph': 'precipGraph', 'relativeHumidityGraph': 'relativeHumidityGraph', 'dewPointGraph': 'dewPointGraph', 'mslPressureGraph': 'mslPressureGraph', 'pressureGraph': 'pressureGraph', 'windSpeedGraph': 'windSpeedGraph', 'cloudCoverGraph': 'cloudCoverGraph'}), "('forecast.html', airTempGraph=airTempGraph, soilTempGraph=\n soilTempGraph, soilMoistureGraph=soilMoistureGraph, rainBoolGraph=\n rainBoolGraph, precipGraph=precipGraph, relativeHumidityGraph=\n relativeHumidityGraph, dewPointGraph=dewPointGraph, mslPressureGraph=\n mslPressureGraph, pressureGraph=pressureGraph, windSpeedGraph=\n windSpeedGraph, cloudCoverGraph=cloudCoverGraph)\n", (13015, 13406), False, 'from flask import Flask, render_template, jsonify, request, url_for\n')]
from lenskit import topn import numpy as np import lk_test_utils as lktu def test_unrated(): ratings = lktu.ml_pandas.renamed.ratings unrate = topn.UnratedCandidates(ratings) cs = unrate(100) items = ratings.item.unique() rated = ratings[ratings.user == 100].item.unique() assert len(cs) == len(items) - len(rated) assert len(np.intersect1d(cs, rated)) == 0
[ "lenskit.topn.UnratedCandidates", "numpy.intersect1d" ]
[((155, 186), 'lenskit.topn.UnratedCandidates', 'topn.UnratedCandidates', (['ratings'], {}), '(ratings)\n', (177, 186), False, 'from lenskit import topn\n'), ((359, 384), 'numpy.intersect1d', 'np.intersect1d', (['cs', 'rated'], {}), '(cs, rated)\n', (373, 384), True, 'import numpy as np\n')]
import cv2 as cv import numpy as np import time import matplotlib.pyplot as plt def ntr(vid,n,d): blank_image = np.zeros((1920,1080,3), np.uint8) fps= int(vid.get(cv.CAP_PROP_FPS)) data = [] fm = 0 out = cv.VideoWriter((d + "\\dots" + str(n) + ".avi"),cv.VideoWriter_fourcc('M','J','P','G'), fps/2, (1080,1920)) ximg = d + "\\dot"+str(n)+".png" while vid.isOpened(): r,f= vid.read() fm +=1 if r == True: gray = cv.cvtColor(f,cv.COLOR_RGB2GRAY) _ , mask = cv.threshold(gray,50,255,cv.THRESH_BINARY) mask = cv.GaussianBlur(mask, (3, 3), 0) img_hsv = cv.cvtColor(f, cv.COLOR_BGR2HSV) hsv_color1 = np.asarray([132, 88, 75]) hsv_color2 = np.asarray([240, 230, 220]) mask1 = cv.inRange(img_hsv, hsv_color1, hsv_color2) mask = mask + mask1 contours, _ = cv.findContours(mask,cv.RETR_TREE,cv.CHAIN_APPROX_SIMPLE) for cnt in contours: area = cv.contourArea(cnt) if area < 500: #cv.drawContours(f, [cnt],-1, (0,255,0),2) x ,y , w, h = cv.boundingRect(cnt) #cv.putText(f,str(area), (x+w+sc-15,y+h+sc+15),cv.FONT_HERSHEY_PLAIN,1,(0,255,0),1) cx = int(x+w/2) cy = int(y+h/2) v = np.sqrt(w**2 + h**2) * 125 data.append([cx,cy,fm,v]) cv.circle(blank_image,(cx,cy),2,(255,0,0),-1) #print("At frame "+ str(fm)) #cv.imshow("mask",blank_image) out.write(blank_image) cv.imwrite(ximg,blank_image) if cv.waitKey(1) & 0xFF == ord('q'): break else: break out.release() vid.release() print("Video is proccsed for " + str(n)) #plot of x-distance againsts time '''fig1, ax1 = plt.subplots() fig2, ax2 = plt.subplots() fig3, ax3 = plt.subplots() fig4, ax4 = plt.subplots() #print(data) exp = lambda x: 10**(x) log = lambda x: np.log10(x) ax3.plot(np.linspace(0,len(nppft),len(nppft)),nppft,"xb") #plot of number of particles per frame againsts time for i in data: if i[2] > 1500: ax1.plot((i[2]/60, np.abs(i[0]-center)*sc),"xr") ax2.plot(i[2]/60,i[3],"xy") #plot of v againsts time #ax3.plot(i[2]/60,i[4],"xb") #plot of number of particles per frame againsts time ax4.plot((np.abs(i[0]-center)*sc),(i[3]),"kx") print("Making XDT for " +str(n)) ax1.set_ylabel("Horizontal distance (cm)") ax1.set_xlabel("Time (s)") ax1.set_title("Graph of x-distance againsts frames of recording " + str(n)) ax1.grid() fig1.savefig('XDT'+str(n)+'.png') print("XDT done, making VT for " +str(n)) ax2.set_ylabel("Speed (cm per sec)") ax2.set_xlabel("Time (s)") ax2.set_title("Graph of speed againsts Time of recording " + str(n)) ax2.grid() fig2.savefig('VT'+str(n)+'.png') print("VT done, making MPPFT for " +str(n)) ax3.set_ylabel("Number of particles per frame") ax3.set_xlabel("Time (s)") ax3.set_title("Number of particles per frame of recording " + str(n)) ax3.grid() fig3.savefig('NPPFT'+str(n)+'.png') print("NPPFT done, making VX for " +str(n)) ax4.set_ylabel("Speed") ax4.set_xlabel("x-distance (cm)") ax4.set_title("Speed againsts x-distance of recording " + str(n)) ax4.grid() fig4.savefig('VX'+str(n)+'.png') print("VX done for " +str(n))''' nm = d +"\\position_data_" + str(n) + ".csv" np.savetxt(nm, data, delimiter=",", fmt="%.2f",header="cx,cy,n,v", comments="") print("DONE for "+ str(n))
[ "cv2.GaussianBlur", "cv2.contourArea", "cv2.circle", "cv2.VideoWriter_fourcc", "cv2.cvtColor", "cv2.imwrite", "cv2.threshold", "numpy.savetxt", "numpy.zeros", "numpy.asarray", "cv2.waitKey", "cv2.boundingRect", "cv2.inRange", "cv2.findContours", "numpy.sqrt" ]
[((123, 158), 'numpy.zeros', 'np.zeros', (['(1920, 1080, 3)', 'np.uint8'], {}), '((1920, 1080, 3), np.uint8)\n', (131, 158), True, 'import numpy as np\n'), ((3772, 3857), 'numpy.savetxt', 'np.savetxt', (['nm', 'data'], {'delimiter': '""","""', 'fmt': '"""%.2f"""', 'header': '"""cx,cy,n,v"""', 'comments': '""""""'}), "(nm, data, delimiter=',', fmt='%.2f', header='cx,cy,n,v', comments=''\n )\n", (3782, 3857), True, 'import numpy as np\n'), ((283, 324), 'cv2.VideoWriter_fourcc', 'cv.VideoWriter_fourcc', (['"""M"""', '"""J"""', '"""P"""', '"""G"""'], {}), "('M', 'J', 'P', 'G')\n", (304, 324), True, 'import cv2 as cv\n'), ((492, 525), 'cv2.cvtColor', 'cv.cvtColor', (['f', 'cv.COLOR_RGB2GRAY'], {}), '(f, cv.COLOR_RGB2GRAY)\n', (503, 525), True, 'import cv2 as cv\n'), ((549, 594), 'cv2.threshold', 'cv.threshold', (['gray', '(50)', '(255)', 'cv.THRESH_BINARY'], {}), '(gray, 50, 255, cv.THRESH_BINARY)\n', (561, 594), True, 'import cv2 as cv\n'), ((612, 644), 'cv2.GaussianBlur', 'cv.GaussianBlur', (['mask', '(3, 3)', '(0)'], {}), '(mask, (3, 3), 0)\n', (627, 644), True, 'import cv2 as cv\n'), ((668, 700), 'cv2.cvtColor', 'cv.cvtColor', (['f', 'cv.COLOR_BGR2HSV'], {}), '(f, cv.COLOR_BGR2HSV)\n', (679, 700), True, 'import cv2 as cv\n'), ((727, 752), 'numpy.asarray', 'np.asarray', (['[132, 88, 75]'], {}), '([132, 88, 75])\n', (737, 752), True, 'import numpy as np\n'), ((779, 806), 'numpy.asarray', 'np.asarray', (['[240, 230, 220]'], {}), '([240, 230, 220])\n', (789, 806), True, 'import numpy as np\n'), ((828, 871), 'cv2.inRange', 'cv.inRange', (['img_hsv', 'hsv_color1', 'hsv_color2'], {}), '(img_hsv, hsv_color1, hsv_color2)\n', (838, 871), True, 'import cv2 as cv\n'), ((932, 991), 'cv2.findContours', 'cv.findContours', (['mask', 'cv.RETR_TREE', 'cv.CHAIN_APPROX_SIMPLE'], {}), '(mask, cv.RETR_TREE, cv.CHAIN_APPROX_SIMPLE)\n', (947, 991), True, 'import cv2 as cv\n'), ((1740, 1769), 'cv2.imwrite', 'cv.imwrite', (['ximg', 'blank_image'], {}), '(ximg, blank_image)\n', (1750, 1769), True, 'import cv2 as cv\n'), ((1052, 1071), 'cv2.contourArea', 'cv.contourArea', (['cnt'], {}), '(cnt)\n', (1066, 1071), True, 'import cv2 as cv\n'), ((1215, 1235), 'cv2.boundingRect', 'cv.boundingRect', (['cnt'], {}), '(cnt)\n', (1230, 1235), True, 'import cv2 as cv\n'), ((1559, 1611), 'cv2.circle', 'cv.circle', (['blank_image', '(cx, cy)', '(2)', '(255, 0, 0)', '(-1)'], {}), '(blank_image, (cx, cy), 2, (255, 0, 0), -1)\n', (1568, 1611), True, 'import cv2 as cv\n'), ((1785, 1798), 'cv2.waitKey', 'cv.waitKey', (['(1)'], {}), '(1)\n', (1795, 1798), True, 'import cv2 as cv\n'), ((1456, 1480), 'numpy.sqrt', 'np.sqrt', (['(w ** 2 + h ** 2)'], {}), '(w ** 2 + h ** 2)\n', (1463, 1480), True, 'import numpy as np\n')]
import time import matplotlib.pyplot as plt import numpy as np import torch import math import pickle plt.style.use('fivethirtyeight') print(f'Imports complete') def sin(x): return math.sin(x*np.pi/180) def cos(x): return math.cos(x*np.pi/180) class Rocket(): def __init__(self, init_pos, init_vel): self.init_position = init_pos # meters both pos_x and pos_y self.init_velocity = init_vel # m/s both vel_x and vel_y self.gravity = 9.81 # N.m/s^2 self.rocket_mass = 25000 # Kg def actions(self, n, prev_thrust, prev_gimbal): self.thrust0 = 0 self.thrust100 = 845222 # N self.thrust50 = self.thrustMax*0.50 # N self.thrust30 = self.thrustMax*0.30 # N self.thrust20 = self.thrustMax*0.20 # N self.gimbal_left = -7.0 # Degrees engine turns right self.gimbal_right = 7.0 # Degrees engine turns left self.gimbal_zero = 0 # Degrees action_space = [self.thrust0, self.thrust100, self.thrust50, self.thrust30, self.thrust20, self.gimbal_zero, self.gimbal_left, self.gimbal_right] thrust = prev_thrust gimbal = prev_gimbal if n <= 4: if action_space[n] == prev_thrust: thrust = prev_thrust gimbal = prev_gimbal else: thrust = action_space[n] else: if action_space[n] == prev_gimbal: gimbal = prev_gimbal thrust = prev_thrust else: gimbal = action_space[n] return (thrust, gimbal) def pos_vel(self, time_interval, thrust, gimbal, u_x, u_y, init_pos_x, init_pos_y): acc_x = thrust*sin(gimbal)/self.rocket_mass acc_y = ((thrust*cos(gimbal)) - (self.rocket_mass*self.gravity))/self.rocket_mass vel_x = u_x + acc_x*time_interval vel_y = u_y + acc_y*time_interval pos_x = init_pos_x pos_y = init_pos_y pos_x += vel_x*time_interval pos_y += vel_y*time_interval observation = [(pos_x, pos_y), (vel_x, vel_y)] return observation def reward(self, observation, t): pos_x, pos_y = observation[0] vel_x, vel_y = observation[1] fire_time_reward = -t*10 position_offset_reward = - \ (math.sqrt(((pos_x-land_x)/1000)**2+((pos_y-land_y)/1000)**2)) final_velocity_reward = - \ (math.sqrt(((pos_y-land_y)/1000.0)**2)*(vel_y*100) + math.sqrt(((pos_x-land_x)/1000.0)**2)*(vel_x*100)) if bool((pos_y - land_y)**2 < 100 and vel_y < 5 and vel_y > 0) and bool((pos_x - land_x)**2 < 10 and vel_x < 2 and vel_x > 0): done_reward = 1000 done = True print('Done') else: done_reward = -1000 done = False reward = fire_time_reward + position_offset_reward + \ final_velocity_reward + done_reward return reward, done time_interval = 0.25 # seconds init_pos_x, init_pos_y = -3000, 41000 init_vel_x, init_vel_y = 10, -561 init_thrust = 0 init_gimbal = 0 land_x = 0 land_y = 0 N_ACTIONS = 8 rocket = Rocket((init_pos_x, init_pos_y), (init_vel_x, init_vel_y)) thrust = init_thrust gimbal = init_gimbal u_x = init_vel_x u_y = init_vel_y done = False q_table = [] #---------------yet to be defined while not done: for i in np.arange(0, 50+time_interval, time_interval): action = np.argmax(q_table[pos_x][pos_y][vel_x][vel_y]) thrust, gimbal = rocket.actions(action, prev_thrust, prev_gimbal) observation = rocket.pos_vel( time_interval, thrust, gimbal, u_x, u_y, init_pos_x, init_pos_y) reward, done = rocket.reward(observation, i) # The actual training of the agent train() #------------yet to be defined pos_x, pos_y = observation[0] v_x, v_y = observation[1] u_x, u_y = v_x, v_y init_pos_x, init_pos_y = pos_x, pos_y file_name = 'q_table.pickle' pickle.dump(q_table, open(f'./{file_name}', 'wb')) print('Q table saved.')
[ "math.sqrt", "numpy.argmax", "math.sin", "matplotlib.pyplot.style.use", "numpy.arange", "math.cos" ]
[((102, 134), 'matplotlib.pyplot.style.use', 'plt.style.use', (['"""fivethirtyeight"""'], {}), "('fivethirtyeight')\n", (115, 134), True, 'import matplotlib.pyplot as plt\n'), ((187, 212), 'math.sin', 'math.sin', (['(x * np.pi / 180)'], {}), '(x * np.pi / 180)\n', (195, 212), False, 'import math\n'), ((234, 259), 'math.cos', 'math.cos', (['(x * np.pi / 180)'], {}), '(x * np.pi / 180)\n', (242, 259), False, 'import math\n'), ((3421, 3468), 'numpy.arange', 'np.arange', (['(0)', '(50 + time_interval)', 'time_interval'], {}), '(0, 50 + time_interval, time_interval)\n', (3430, 3468), True, 'import numpy as np\n'), ((3485, 3531), 'numpy.argmax', 'np.argmax', (['q_table[pos_x][pos_y][vel_x][vel_y]'], {}), '(q_table[pos_x][pos_y][vel_x][vel_y])\n', (3494, 3531), True, 'import numpy as np\n'), ((2357, 2431), 'math.sqrt', 'math.sqrt', (['(((pos_x - land_x) / 1000) ** 2 + ((pos_y - land_y) / 1000) ** 2)'], {}), '(((pos_x - land_x) / 1000) ** 2 + ((pos_y - land_y) / 1000) ** 2)\n', (2366, 2431), False, 'import math\n'), ((2468, 2511), 'math.sqrt', 'math.sqrt', (['(((pos_y - land_y) / 1000.0) ** 2)'], {}), '(((pos_y - land_y) / 1000.0) ** 2)\n', (2477, 2511), False, 'import math\n'), ((2533, 2576), 'math.sqrt', 'math.sqrt', (['(((pos_x - land_x) / 1000.0) ** 2)'], {}), '(((pos_x - land_x) / 1000.0) ** 2)\n', (2542, 2576), False, 'import math\n')]
# https://deeplearningcourses.com/c/data-science-supervised-machine-learning-in-python # https://www.udemy.com/data-science-supervised-machine-learning-in-python from __future__ import print_function, division from future.utils import iteritems from builtins import range, input # Note: you may need to update your version of future # sudo pip install -U future import numpy as np import matplotlib.pyplot as plt from knn import KNN def get_data(): width = 8 height = 8 N = width * height X = np.zeros((N, 2)) Y = np.zeros(N) n = 0 start_t = 0 for i in range(width): t = start_t for j in range(height): X[n] = [i, j] Y[n] = t n += 1 t = (t + 1) % 2 # alternate between 0 and 1 start_t = (start_t + 1) % 2 return X, Y if __name__ == '__main__': X, Y = get_data() # display the data plt.scatter(X[:,0], X[:,1], s=100, c=Y, alpha=0.5) plt.show() # get the accuracy model = KNN(3) model.fit(X, Y) print("Train accuracy:", model.score(X, Y))
[ "matplotlib.pyplot.show", "matplotlib.pyplot.scatter", "numpy.zeros", "knn.KNN", "builtins.range" ]
[((512, 528), 'numpy.zeros', 'np.zeros', (['(N, 2)'], {}), '((N, 2))\n', (520, 528), True, 'import numpy as np\n'), ((537, 548), 'numpy.zeros', 'np.zeros', (['N'], {}), '(N)\n', (545, 548), True, 'import numpy as np\n'), ((588, 600), 'builtins.range', 'range', (['width'], {}), '(width)\n', (593, 600), False, 'from builtins import range, input\n'), ((907, 959), 'matplotlib.pyplot.scatter', 'plt.scatter', (['X[:, 0]', 'X[:, 1]'], {'s': '(100)', 'c': 'Y', 'alpha': '(0.5)'}), '(X[:, 0], X[:, 1], s=100, c=Y, alpha=0.5)\n', (918, 959), True, 'import matplotlib.pyplot as plt\n'), ((962, 972), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (970, 972), True, 'import matplotlib.pyplot as plt\n'), ((1009, 1015), 'knn.KNN', 'KNN', (['(3)'], {}), '(3)\n', (1012, 1015), False, 'from knn import KNN\n'), ((639, 652), 'builtins.range', 'range', (['height'], {}), '(height)\n', (644, 652), False, 'from builtins import range, input\n')]
# Copyright 2017 Google 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. # ============================================================================== """Example script to train the DNC on a repeated copy task.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf import sonnet as snt from tensorflow.contrib.layers.python.layers import initializers from tensorflow.python.ops import array_ops from tensorflow.python.framework import constant_op from tensorflow.python.ops import nn from dnc import dnc import numpy as np import cv2 from scipy import ndimage as nd from PIL import Image import os, sys import time from utility import alrc, auto_name from scipy.stats import norm experiment_number = 280 FLAGS = tf.flags.FLAGS # Model parameters tf.flags.DEFINE_integer("hidden_size", 256, "Size of LSTM hidden layer.") tf.flags.DEFINE_integer("memory_size", 16, "The number of memory slots.") tf.flags.DEFINE_integer("word_size", 64, "The width of each memory slot.") tf.flags.DEFINE_integer("num_write_heads", 1, "Number of memory write heads.") tf.flags.DEFINE_integer("num_read_heads", 4, "Number of memory read heads.") tf.flags.DEFINE_integer("clip_value", 0, "Maximum absolute value of controller and dnc outputs.") tf.flags.DEFINE_bool("use_batch_norm", True, "Use batch normalization in generator.") tf.flags.DEFINE_string("model", "LSTM", "LSTM or DNC.") tf.flags.DEFINE_integer("projection_size", 0, "Size of projection layer. Zero for no projection.") tf.flags.DEFINE_integer("lstm_depth", 2, "Number of LSTM cells deep.") tf.flags.DEFINE_bool("is_input_embedder", False, "Embed inputs before they are input.") tf.flags.DEFINE_bool("is_variable_initial_states", True, "Trainable initial states rather than zero states.") tf.flags.DEFINE_bool("is_layer_norm", False, "Use layer normalization in recurrent networks.") # Optimizer parameters. tf.flags.DEFINE_integer("batch_size", 32, "Batch size for training.") tf.flags.DEFINE_integer("replay_size", 32, "Maximum examples in ring buffer.") tf.flags.DEFINE_integer("avg_replays", 1, "Mean frequency each experience is used.") tf.flags.DEFINE_integer("replay_add_frequency", 1, "How often to add expereinces to ring buffer.") tf.flags.DEFINE_bool("is_cyclic_replay", False, "True to cyclically replace experiences.") tf.flags.DEFINE_float("max_grad_norm", 50, "Gradient clipping norm limit.") tf.flags.DEFINE_float("L2_norm", 1.e-5, "Decay rate for L2 regularization. 0 for no regularization.") tf.flags.DEFINE_float("grad_clip_norm", 0, "Threshold to clip gradient sizes to. Zero for no clipping.") tf.flags.DEFINE_float("grad_clip_value", 0.000, "Threshold to clip gradient sizes to. Zero for no clipping.") # Task parameters tf.flags.DEFINE_integer("img_side", 96, "Number of image pixels for square image") tf.flags.DEFINE_integer("num_steps", 20, "Number of image pixels for square image") tf.flags.DEFINE_integer("step_size", 20, "Distance STEM probe moves at each step (in px).") tf.flags.DEFINE_integer("num_actions", 1, "Number of parameters to describe actions.") tf.flags.DEFINE_integer("shuffle_size", 2000, "Size of moving buffer to sample data from.") tf.flags.DEFINE_integer("prefetch_size", 10, "Number of batches to prepare in advance.") # Training options. tf.flags.DEFINE_float("actor_lr", 0.0005, "Actor learning rate.") tf.flags.DEFINE_float("critic_lr", 0.001, "Critic learning rate.") tf.flags.DEFINE_float("generator_lr", 0.003, "Generator learning rate.") tf.flags.DEFINE_float("discriminator_lr", 0.003, "Discriminator learning rate.") tf.flags.DEFINE_float("specificity", 0.0, "Weight specificity loss. Zero for no specificity loss.") tf.flags.DEFINE_float("loss_norm_decay", 0.997, "Weight for loss normalization. Zero for no normalization.") tf.flags.DEFINE_float("rnn_norm_decay", 0., "Weight for critic loss normalization. Zero for no normalization.") tf.flags.DEFINE_bool("is_immediate_critic_loss", False, "True to not backpropagate.") tf.flags.DEFINE_bool("is_target_actor_feedback", False, "True to use target critic to train actor.") tf.flags.DEFINE_bool("is_ranked_loss", False, "Loses are indices in sorted arrays.") tf.flags.DEFINE_float("gamma", 0.97, "Reward/loss decay.") tf.flags.DEFINE_float("loss_gamma", 1., "Reward/loss decay applied directly to losses.") tf.flags.DEFINE_float("loss_norm_clip", 0., "Norm to clip losses to.") tf.flags.DEFINE_bool("is_advantage_actor_critic", False, "Use advantage rather than Q errors for actor.") tf.flags.DEFINE_bool("is_direct_advantage", False, "Use predicted Q minus exploration Q errors for actor.") tf.flags.DEFINE_bool("is_cyclic_generator_learning_rate", True, "True for sawtooth oscillations.") tf.flags.DEFINE_bool("is_decaying_generator_learning_rate", True, "True for decay envelope for sawtooth oscillations.") tf.flags.DEFINE_integer("supervision_iters", 1, "Starting value for supeversion.") tf.flags.DEFINE_float("supervision_start", 0., "Starting value for supeversion.") tf.flags.DEFINE_float("supervision_end", 0., "Starting value for supeversion.") if FLAGS.supervision_iters: #Flag will not be used tf.flags.DEFINE_float("supervision", 0.5, "Weighting for known discounted future reward.") else: #Flag will be used tf.flags.DEFINE_float("supervision", 0.0, "Weighting for known discounted future reward.") tf.flags.DEFINE_bool("is_target_actor", False and FLAGS.supervision != 1, "True to use target actor.") tf.flags.DEFINE_bool("is_target_critic", True and FLAGS.supervision != 1, "True to use target critic.") tf.flags.DEFINE_bool("is_target_generator", False, "True to use target generator.") tf.flags.DEFINE_integer("update_frequency", 0, "Frequency of hard target network updates. Zero for soft updates.") tf.flags.DEFINE_float("target_decay", 0.997, "Decay rate for target network soft updates.") tf.flags.DEFINE_bool("is_generator_batch_norm_tracked", False, "True to track generator batch normalization.") tf.flags.DEFINE_bool("is_positive_qs", False, "Whether to clip qs to be positive.") tf.flags.DEFINE_bool("is_norm_q", False, "Whether to set mean of q values.") tf.flags.DEFINE_bool("is_infilled", False, "True to use infilling rather than generator.") tf.flags.DEFINE_bool("is_prev_position_input", True, "True to input previous positions.") tf.flags.DEFINE_bool("is_ornstein_uhlenbeck", True, "True for O-U exploration noise.") tf.flags.DEFINE_bool("is_noise_decay", True, "Decay noise if true.") tf.flags.DEFINE_float("ou_theta", 0.1, "Drift back to mean.") tf.flags.DEFINE_float("ou_sigma", 0.2, "Size of random process.") tf.flags.DEFINE_float("exploration_loss", 0., "Exploration loss.") tf.flags.DEFINE_float("uniform_coverage_loss", 0, "Additive uniform coverage loss.") tf.flags.DEFINE_bool("is_rel_to_truth", False, "True to normalize losses using expected losses.") tf.flags.DEFINE_bool("is_clipped_reward", True, "True to clip rewards.") tf.flags.DEFINE_bool("is_clipped_critic", False, "True to clip critic predictions for actor training.") tf.flags.DEFINE_float("over_edge_penalty", 0.05, "Penalty for action going over edge of image.") tf.flags.DEFINE_float("end_edge_penalty", 0.0, "Penalty for action going over edge of image.") tf.flags.DEFINE_bool("is_prioritized_replay", False, "True to prioritize the replay of difficult experiences.") tf.flags.DEFINE_bool("is_biased_prioritized_replay", False, "Priority sampling without bias correction.") tf.flags.DEFINE_bool("is_relative_to_spirals", False, "True to compare generator losses against losses for spirals.") tf.flags.DEFINE_bool("is_self_competition", True, "Oh it is on. True to compete against past versions of itself.") tf.flags.DEFINE_float("norm_generator_losses_decay", 0., "Divide generator losses by their running mean. Zero for no normalization.") tf.flags.DEFINE_float("replay_decay", 0.999, "Decay rates to calculate loss moments.") tf.flags.DEFINE_bool("is_minmax_reward", False, "True to use highest losses for actor loss.") tf.flags.DEFINE_integer("start_iter", 0, "Starting iteration") tf.flags.DEFINE_integer("train_iters", 1_000_000, "Training iterations") tf.flags.DEFINE_integer("val_examples", 20_000, "Number of validation examples") tf.flags.DEFINE_float("style_loss", 0., "Weighting of style loss. Zero for no style loss.") tf.flags.DEFINE_float("spike_loss", 0., "Penalize critic for spikey predictions.") tf.flags.DEFINE_float("step_incr", np.sqrt(2), "Number of pixels per step.") tf.flags.DEFINE_string("model_dir", f"//ads.warwick.ac.uk/shared/HCSS6/Shared305/Microscopy/Jeffrey-Ede/models/recurrent_conv-1/{experiment_number}/", "Working directory.") tf.flags.DEFINE_string("data_file", "//Desktop-sa1evjv/h/96x96_stem_crops.npy", "Datafile containing 19769 96x96 downsampled STEM crops.") tf.flags.DEFINE_integer("report_freq", 10, "How often to print losses to the console.") os.chdir(FLAGS.model_dir) sys.path.insert(0, FLAGS.model_dir) def l1_batch_norm(x): mu = tf.reduce_mean(x, axis=0, keepdims=True) d = np.sqrt(np.pi/2)*tf.reduce_mean(tf.abs(x-mu)) return (x - mu) / d def sobel_edges(image): """Returns a tensor holding Sobel edge maps. Arguments: image: Image tensor with shape [batch_size, h, w, d] and type float32 or float64. The image(s) must be 2x2 or larger. Returns: Tensor holding edge maps for each channel. Returns a tensor with shape [batch_size, h, w, d, 2] where the last two dimensions hold [[dy[0], dx[0]], [dy[1], dx[1]], ..., [dy[d-1], dx[d-1]]] calculated using the Sobel filter. """ # Define vertical and horizontal Sobel filters. static_image_shape = image.get_shape() image_shape = array_ops.shape(image) kernels = [[[-1, -2, -1], [0, 0, 0], [1, 2, 1]], [[-1, 0, 1], [-2, 0, 2], [-1, 0, 1]]] num_kernels = len(kernels) kernels = np.transpose(np.asarray(kernels), (1, 2, 0)) kernels = np.expand_dims(kernels, -2) kernels_tf = constant_op.constant(kernels, dtype=image.dtype) kernels_tf = array_ops.tile( kernels_tf, [1, 1, image_shape[-1], 1], name='sobel_filters') # Use depth-wise convolution to calculate edge maps per channel. pad_sizes = [[0, 0], [1, 1], [1, 1], [0, 0]] padded = array_ops.pad(image, pad_sizes, mode='REFLECT') # Output tensor has shape [batch_size, h, w, d * num_kernels]. strides = [1, 1, 1, 1] output = nn.depthwise_conv2d(padded, kernels_tf, strides, 'VALID') # Reshape to [batch_size, h, w, d, num_kernels]. shape = array_ops.concat([image_shape, [num_kernels]], 0) output = array_ops.reshape(output, shape=shape) output.set_shape(static_image_shape.concatenate([num_kernels])) return output def norm_img(img, min=None, max=None, get_min_and_max=False): if min == None: min = np.min(img) if max == None: max = np.max(img) if np.absolute(min-max) < 1.e-6: img.fill(0.) else: a = 0.5*(min+max) b = 0.5*(max-min) img = (img-a) / b if get_min_and_max: return img.astype(np.float32), (min, max) else: return img.astype(np.float32) def scale0to1(img): """Rescale image between 0 and 1""" img = img.astype(np.float32) min = np.min(img) max = np.max(img) if np.absolute(min-max) < 1.e-6: img.fill(0.5) else: img = (img - min)/(max - min) return img.astype(np.float32) def disp(img): #if len(img.shape) == 3: # img = np.sum(img, axis=2) cv2.namedWindow('CV_Window', cv2.WINDOW_NORMAL) cv2.imshow('CV_Window', scale0to1(img)) cv2.waitKey(0) return def run_model(input_sequence, output_size): """Runs model on input sequence.""" access_config = { "memory_size": FLAGS.memory_size, "word_size": FLAGS.word_size, "num_reads": FLAGS.num_read_heads, "num_writes": FLAGS.num_write_heads, } controller_config = { "hidden_size": FLAGS.hidden_size, "use_layer_norm": FLAGS.is_layer_norm, } clip_value = FLAGS.clip_value dnc_core = dnc.DNC(access_config, controller_config, output_size, clip_value) initial_state = dnc_core.initial_state(FLAGS.batch_size) output_sequence, _ = tf.nn.dynamic_rnn( cell=dnc_core, inputs=input_sequence, time_major=True, initial_state=initial_state) return output_sequence def sigmoid(x): return 1/(1 + np.exp(-x)) class RingBuffer(object): def __init__( self, action_shape, observation_shape, full_scan_shape, batch_size, buffer_size=1000, num_past_losses=None, ): self.buffer_size = buffer_size self.actions = np.zeros([buffer_size]+list(action_shape)[1:]) self.observations = np.zeros([buffer_size]+list(observation_shape)[1:]) self.full_scans = np.zeros([buffer_size]+list(full_scan_shape)[1:]) self.position = 0 self._batch_size = batch_size self._input_batch_size = batch_size // FLAGS.avg_replays if FLAGS.is_prioritized_replay or FLAGS.is_biased_prioritized_replay: self.accesses = np.zeros([buffer_size]) self.priorities = np.ones([buffer_size]) self.indices = np.arange(buffer_size) self._is_accessed = False if FLAGS.is_self_competition: self.mu1 = 0.5 self.mu2 = 0.5 self.std = np.sqrt(self.mu2 - self.mu1**2 + 1.e-3) self.d_mu1 = 0.5 self.d_mu2 = 0.5 self.d_std = np.sqrt(self.d_mu2 - self.d_mu1**2 + 1.e-3) self.past_losses = np.zeros([num_past_losses]) self.next_losses = np.zeros([num_past_losses]) self.labels = np.zeros([buffer_size], np.int32) def add(self, actions, observations, full_scans, labels=None): if FLAGS.is_cyclic_replay: i0 = self.position % self.buffer_size else: if self.position < self.buffer_size: i0 = self.position else: i0 = np.random.randint(0, self.buffer_size) num_before_cycle = min(self.buffer_size-i0, self._input_batch_size) self.actions[i0:i0+num_before_cycle] = actions[:num_before_cycle] self.observations[i0:i0+num_before_cycle] = observations[:num_before_cycle] self.full_scans[i0:i0+num_before_cycle] = full_scans[:num_before_cycle] num_remaining = self._input_batch_size - num_before_cycle if num_remaining > 0: self.actions[0:num_remaining] = actions[num_before_cycle:] self.observations[:num_remaining] = observations[num_before_cycle:] self.full_scans[:num_remaining] = full_scans[num_before_cycle:] if FLAGS.is_prioritized_replay or FLAGS.is_biased_prioritized_replay: if self._is_accessed: mean_priority = np.mean(self.priorities[self.accesses > 0]) else: mean_priority = 1. self.priorities[i0:i0+num_before_cycle] = mean_priority*np.ones([num_before_cycle]) if num_before_cycle < self._input_batch_size: self.priorities[0:num_remaining] = mean_priority*np.ones([self._input_batch_size - num_before_cycle]) if FLAGS.is_self_competition: self.labels[i0:i0+num_before_cycle] = labels[:num_before_cycle] if num_remaining > 0: self.labels[0:num_remaining] = labels[num_before_cycle:] #self.past_losses[labels] = self.next_losses[labels] #self.next_losses[labels] = losses #self.mu1 = FLAGS.replay_decay*self.mu1 + (1-FLAGS.replay_decay)*np.mean(losses) #self.mu2 = FLAGS.replay_decay*self.mu2 + (1-FLAGS.replay_decay)*np.mean(losses**2) #self.std = np.sqrt(self.mu2 - self.mu1**2 + 1.e-3) #diffs = losses - self.past_losses[labels] #self.d_mu1 = FLAGS.replay_decay*self.d_mu1 + (1-FLAGS.replay_decay)*np.mean(diffs) #self.d_mu2 = FLAGS.replay_decay*self.d_mu2 + (1-FLAGS.replay_decay)*np.mean(diffs**2) #self.d_std = np.sqrt(self.d_mu2 - self.d_mu1**2 + 1.e-3) self.position += self._input_batch_size def loss_fn(self, next_loss, prev_loss): mse_loss = next_loss#(next_loss - self.mu1) / self.std #exp_loss = (next_loss - prev_loss - self.d_mu1) / self.d_std loss = mse_loss#sigmoid(mse_loss) # sigmoid(exp_loss) return loss def get(self): limit = min(self.position, self.buffer_size) if FLAGS.is_prioritized_replay: sample_idxs = np.random.choice( self.indices, size=self._batch_size, replace=False, p=self.priorities/np.sum(self.priorities) ) #alpha=1 beta = 0.5 + 0.5*(FLAGS.train_iters - self.position)/FLAGS.train_iters sampled_priority_weights = self.priorities[sample_idxs]**( -beta ) sampled_priority_weights /= np.max(sampled_priority_weights) elif FLAGS.is_biased_prioritized_replay: alpha = 1#(FLAGS.train_iters - self.position)/FLAGS.train_iters priorities = self.priorities**alpha sample_idxs = np.random.choice( self.indices, size=self._batch_size, replace=False, p=self.priorities/np.sum(self.priorities) ) else: sample_idxs = np.random.randint(0, limit, size=self._batch_size) sampled_actions = np.stack([self.actions[i] for i in sample_idxs]) sampled_observations = np.stack([self.observations[i] for i in sample_idxs]) sampled_full_scans = np.stack([self.full_scans[i] for i in sample_idxs]) if FLAGS.is_prioritized_replay: return sampled_actions, sampled_observations, sample_idxs, sampled_priority_weights #elif FLAGS.is_biased_prioritized_replay: #return sampled_actions, sampled_observations, sample_idxs elif FLAGS.is_self_competition: sampled_labels = np.stack([self.labels[i] for i in sample_idxs]) sampled_past_losses = np.stack([self.next_losses[i] for i in sampled_labels]) return sampled_actions, sampled_observations, sample_idxs, sampled_past_losses, sampled_full_scans else: return sampled_actions, sampled_observations def update_priorities(self, idxs, priorities): """For prioritized experience replay""" self._is_accessed = True self.priorities[idxs] = priorities self.accesses[idxs] = 1. class Agent(snt.AbstractModule): def __init__( self, num_outputs, name, is_new=False, noise_decay=None, is_double_critic=False, sampled_full_scans=None, val_full_scans=None ): super(Agent, self).__init__(name=name) access_config = { "memory_size": FLAGS.memory_size, "word_size": FLAGS.word_size, "num_reads": FLAGS.num_read_heads, "num_writes": FLAGS.num_write_heads, } controller_config = { "hidden_size": FLAGS.hidden_size, #"projection_size": FLAGS.projection_size or None, } clip_value = FLAGS.clip_value self.is_actor = "actor" in name with self._enter_variable_scope(): components = dnc.Components(access_config, controller_config, num_outputs) self._dnc_core = dnc.DNC( components, num_outputs, clip_value, is_new=False, is_double_critic=is_double_critic, is_actor=self.is_actor) if is_new: self._dnc_core_new = dnc.DNC( components, num_outputs, clip_value, is_new=True, noise_decay=noise_decay, sampled_full_scans=sampled_full_scans, is_noise=True, is_actor=self.is_actor ) if not val_full_scans is None: self._dnc_core_val = dnc.DNC( components, num_outputs, clip_value, is_new=True, sampled_full_scans=val_full_scans, is_actor=self.is_actor ) self._initial_state = self._dnc_core.initial_state(FLAGS.batch_size) self._new_start = self._dnc_core.initial_state(FLAGS.batch_size // FLAGS.avg_replays) #self._action_embedder = snt.Linear(output_size=64) #self._observation_embedder = snt.Linear(output_size=64) def _build(self, observations, actions): #Tiling here is a hack to make inputs the same size num_tiles = 2 // (actions.get_shape().as_list()[-1] // FLAGS.num_actions) tiled_actions = tf.tile(actions, [1, 1, num_tiles]) input_sequence = tf.concat([observations, tiled_actions], axis=-1) self._dnc_core.first = True output_sequence, _ = tf.nn.dynamic_rnn( cell=self._dnc_core, inputs=input_sequence, time_major=False, initial_state=self._initial_state ) return output_sequence def get_new_experience(self): self._dnc_core_new.first = True output_sequence, _ = tf.nn.dynamic_rnn( cell=self._dnc_core_new, inputs=tf.zeros([FLAGS.batch_size // FLAGS.avg_replays, FLAGS.num_steps, 1]), time_major=False, initial_state=self._new_start ) if hasattr(tf, 'ensure_shape'): output_sequence = tf.ensure_shape( output_sequence, [FLAGS.batch_size // FLAGS.avg_replays, FLAGS.num_steps, FLAGS.step_size+FLAGS.num_actions]) else: output_sequence = tf.reshape( output_sequence, [FLAGS.batch_size // FLAGS.avg_replays, FLAGS.num_steps, FLAGS.step_size+FLAGS.num_actions]) observations = output_sequence[:,:,:FLAGS.step_size] actions = output_sequence[:,:,FLAGS.step_size:] return observations, actions def get_val_experience(self): self._dnc_core_val.first = True output_sequence, _ = tf.nn.dynamic_rnn( cell=self._dnc_core_val, inputs=tf.zeros([FLAGS.batch_size // FLAGS.avg_replays, FLAGS.num_steps, 1]), time_major=False, initial_state=self._new_start ) if hasattr(tf, 'ensure_shape'): output_sequence = tf.ensure_shape( output_sequence, [FLAGS.batch_size // FLAGS.avg_replays, FLAGS.num_steps, FLAGS.step_size+FLAGS.num_actions]) else: output_sequence = tf.reshape( output_sequence, [FLAGS.batch_size // FLAGS.avg_replays, FLAGS.num_steps, FLAGS.step_size+FLAGS.num_actions]) observations = output_sequence[:,:,:FLAGS.step_size] actions = output_sequence[:,:,FLAGS.step_size:] return observations, actions @property def variables(self): with self._enter_variable_scope(): return tf.get_collection( tf.GraphKeys.GLOBAL_VARIABLES, scope=tf.get_variable_scope().name ) @property def trainable_variables(self): with self._enter_variable_scope(): return tf.get_collection( tf.GraphKeys.TRAINABLE_VARIABLES, scope=tf.get_variable_scope().name ) def spectral_norm(w, iteration=1, in_place_updates=False): """Spectral normalization. It imposes Lipschitz continuity by constraining the spectral norm (maximum singular value) of weight matrices. Inputs: w: Weight matrix to spectrally normalize. iteration: Number of times to apply the power iteration method to enforce spectral norm. Returns: Weight matrix with spectral normalization control dependencies. """ w0 = w w_shape = w.shape.as_list() w = tf.reshape(w, [-1, w_shape[-1]]) u = tf.get_variable(auto_name("u"), [1, w_shape[-1]], initializer=tf.random_normal_initializer(mean=0.,stddev=0.03), trainable=False) u_hat = u v_hat = None for i in range(iteration): """ power iteration Usually iteration = 1 will be enough """ v_ = tf.matmul(u_hat, tf.transpose(w)) v_hat = tf.nn.l2_normalize(v_) u_ = tf.matmul(v_hat, w) u_hat = tf.nn.l2_normalize(u_) u_hat = tf.stop_gradient(u_hat) v_hat = tf.stop_gradient(v_hat) sigma = tf.matmul(tf.matmul(v_hat, w), tf.transpose(u_hat)) if in_place_updates: #In-place control dependencies bottlenect training with tf.control_dependencies([u.assign(u_hat)]): w_norm = w / sigma w_norm = tf.reshape(w_norm, w_shape) else: #Execute control dependency in parallel with other update ops tf.add_to_collection(tf.GraphKeys.UPDATE_OPS, u.assign(u_hat)) w_norm = w / sigma w_norm = tf.reshape(w_norm, w_shape) return w_norm def spectral_norm_conv( inputs, num_outputs, stride=1, kernel_size=3, padding='VALID', biases_initializer=tf.zeros_initializer() ): """Convolutional layer with spectrally normalized weights.""" w = tf.get_variable(auto_name("kernel"), shape=[kernel_size, kernel_size, inputs.get_shape()[-1], num_outputs]) x = tf.nn.conv2d(input=inputs, filter=spectral_norm(w), strides=[1, stride, stride, 1], padding=padding) if biases_initializer != None: b = tf.get_variable(auto_name("bias"), [num_outputs], initializer=biases_initializer) x = tf.nn.bias_add(x, b) return x def conv( inputs, num_outputs, kernel_size=3, stride=1, padding='SAME', data_format="NHWC", actv_fn=tf.nn.relu, is_batch_norm=True, is_spectral_norm=False, is_depthwise_sep=False, extra_batch_norm=False, biases_initializer=tf.zeros_initializer, weights_initializer=initializers.xavier_initializer, transpose=False, is_training=True ): """Convenience function for a strided convolutional or transpositional convolutional layer. Intro: https://towardsdatascience.com/intuitively-understanding-convolutions-for-deep-learning-1f6f42faee1. The order is: Activation (Optional) -> Batch Normalization (optional) -> Convolutions. Inputs: inputs: Tensor of shape `[batch_size, height, width, channels]` to apply convolutions to. num_outputs: Number of feature channels to output. kernel_size: Side lenth of square convolutional kernels. stride: Distance between convolutional kernel applications. padding: 'SAME' for zero padding where kernels go over the edge. 'VALID' to discard features where kernels go over the edge. activ_fn: non-linearity to apply after summing convolutions. is_batch_norm: If True, add batch normalization after activation. is_spectral_norm: If True, spectrally normalize weights. is_depthwise_sep: If True, depthwise separate convolutions into depthwise spatial convolutions, then 1x1 pointwise convolutions. extra_batch_norm: If True and convolutions are depthwise separable, implement batch normalization between depthwise and pointwise convolutions. biases_initializer: Function to initialize biases with. None for no biases. weights_initializer: Function to initialize weights with. None for no weights. transpose: If True, apply convolutional layer transpositionally to the described convolutional layer. is_training: If True, use training specific operations e.g. batch normalization update ops. Returns: Output of convolutional layer. """ x = inputs num_spatial_dims = len(x.get_shape().as_list()) - 2 if biases_initializer == None: biases_initializer = lambda: None if weights_initializer == None: weights_initializer = lambda: None if not is_spectral_norm: #Convolutional layer without spectral normalization if transpose: stride0 = 1 if type(stride) == list or is_depthwise_sep or stride % 1: #Apparently there is no implementation of transpositional #depthwise separable convolutions, so bilinearly upsample then #depthwise separably convolute if kernel_size != 1: x = tf.image.resize_bilinear( images=x, size=stride if type(stride) == list else \ [int(stride*d) for d in x.get_shape().as_list()[1:3]], align_corners=True ) stride0 = stride stride = 1 if type(stride0) == list and not is_depthwise_sep: layer = tf.contrib.layers.conv2d elif is_depthwise_sep: layer = tf.contrib.layers.separable_conv2d else: layer = tf.contrib.layers.conv2d_transpose x = layer( inputs=x, num_outputs=num_outputs, kernel_size=kernel_size, stride=stride, padding=padding, data_format=data_format, activation_fn=None, weights_initializer=weights_initializer(), biases_initializer=biases_initializer()) if type(stride0) != list: if (is_depthwise_sep or stride0 % 1) and kernel_size == 1: x = tf.image.resize_bilinear( images=x, size=[int(stride0*d) for d in x.get_shape().as_list()[1:3]], align_corners=True ) else: if num_spatial_dims == 1: layer = tf.contrib.layers.conv1d elif num_spatial_dims == 2: if is_depthwise_sep: layer = tf.contrib.layers.separable_conv2d else: layer = tf.contrib.layers.conv2d x = layer( inputs=x, num_outputs=num_outputs, kernel_size=kernel_size, stride=stride, padding=padding, data_format=data_format, activation_fn=None, weights_initializer=weights_initializer(), biases_initializer=biases_initializer()) else: #Weights are spectrally normalized x = spectral_norm_conv( inputs=x, num_outputs=num_outputs, stride=stride, kernel_size=kernel_size, padding=padding, biases_initializer=biases_initializer()) if actv_fn: x = actv_fn(x) if is_batch_norm and FLAGS.use_batch_norm: x = tf.contrib.layers.batch_norm(x, is_training=is_training) #x = l1_batch_norm(x) return x def residual_block(inputs, skip=3, is_training=True): """Residual block whre the input is added to the signal after skipping some layers. This architecture is good for learning purturbative transformations. If no layer is provided, it defaults to a convolutional layer. Deep residual learning: https://arxiv.org/abs/1512.03385. Inputs: inputs: Tensor to apply residual block to. Outputs of every layer will have the same shape. skip: Number of layers to skip before adding input to layer output. layer: Layer to apply in residual block. Defaults to convolutional layer. Custom layers must support `inputs`, `num_outputs` and `is_training` arguments. Returns: Final output of residual block. """ x = x0 = inputs def layer(inputs, num_outputs, is_training, is_batch_norm, actv_fn): x = conv( inputs=inputs, num_outputs=num_outputs, is_training=is_training, actv_fn=actv_fn ) return x for i in range(skip): x = layer( inputs=x, num_outputs=x.get_shape()[-1], is_training=is_training, is_batch_norm=i < skip - 1, actv_fn=tf.nn.relu ) x += x0 if FLAGS.use_batch_norm: x = tf.contrib.layers.batch_norm(x, is_training=is_training) #x = l1_batch_norm(x) return x class Discriminator(snt.AbstractModule): def __init__(self, name, is_training ): super(Discriminator, self).__init__(name=name) self._is_training = is_training def _build(self, inputs): x = inputs std_actv = tf.nn.relu#lambda x: tf.nn.leaky_relu(x, alpha=0.1) is_training = self._is_training is_depthwise_sep = False base_size = 32 for i in range(0, 5): x = conv( x, num_outputs=base_size*2**i, kernel_size=4, stride=2, is_depthwise_sep=is_depthwise_sep, is_training=is_training, actv_fn=std_actv ) x = tf.layers.flatten(x) x = tf.layers.dense(x, 1) x = tf.contrib.layers.batch_norm(x, is_training=is_training) return x @property def variables(self): with self._enter_variable_scope(): return tf.get_collection( tf.GraphKeys.GLOBAL_VARIABLES, scope=tf.get_variable_scope().name ) @property def trainable_variables(self): with self._enter_variable_scope(): return tf.get_collection( tf.GraphKeys.TRAINABLE_VARIABLES, scope=tf.get_variable_scope().name ) class Generator(snt.AbstractModule): def __init__(self, name, is_training ): super(Generator, self).__init__(name=name) self._is_training = is_training def _build(self, inputs): x = inputs std_actv = tf.nn.relu#lambda x: tf.nn.leaky_relu(x, alpha=0.1) is_training = self._is_training is_depthwise_sep = False base_size = 32 #x = tf.contrib.layers.batch_norm(x, is_training=is_training) x = conv( x, num_outputs=32, is_training=is_training, actv_fn=std_actv ) #Encoder for i in range(1, 3): x = conv( x, num_outputs=base_size*2**i, stride=2, is_depthwise_sep=is_depthwise_sep, is_training=is_training, actv_fn=std_actv ) if i == 2: low_level = x #Residual blocks for _ in range(5): #Number of blocks x = residual_block( x, skip=3, is_training=is_training ) #Decoder for i in range(1, -1, -1): x = conv( x, num_outputs=base_size*2**i, stride=2, is_depthwise_sep=is_depthwise_sep, is_training=is_training, transpose=True, actv_fn=std_actv ) x = conv( x, num_outputs=base_size, is_depthwise_sep=is_depthwise_sep, is_training=is_training ) #Project features onto output image x = conv( x, num_outputs=1, biases_initializer=None, actv_fn=None, is_batch_norm=False, is_training=is_training ) return x @property def variables(self): with self._enter_variable_scope(): return tf.get_collection( tf.GraphKeys.GLOBAL_VARIABLES, scope=tf.get_variable_scope().name ) @property def trainable_variables(self): with self._enter_variable_scope(): return tf.get_collection( tf.GraphKeys.TRAINABLE_VARIABLES, scope=tf.get_variable_scope().name ) def construct_partial_scans(actions, observations): """ actions: [batch_size, num_steps, 2] observations: [batch_size, num_steps, 10] """ if FLAGS.num_actions == 1: actions = FLAGS.step_incr*np.concatenate((np.cos(actions), np.sin(actions)), axis=-1) #Last action unused and the first action is always the same actions = np.concatenate((np.ones([FLAGS.batch_size // FLAGS.avg_replays, 1, 2]), actions[:,:-1,:]), axis=1) starts = 0.5*FLAGS.img_side + FLAGS.step_size*(np.cumsum(actions, axis=1) - actions) #starts = np.zeros(actions.shape) #starts[:,0,:] = actions[:,0,:] #for i in range(1, FLAGS.num_steps): # starts[:,i,:] = actions[:,i,:] + starts[:,i-1,:] #starts -= actions #starts *= FLAGS.step_size #starts += 0.5*FLAGS.img_side positions = np.stack([starts + i*actions for i in range(FLAGS.step_size)], axis=-2) x = np.minimum(np.maximum(positions, 0), FLAGS.img_side-1) indices = [] for j in range(FLAGS.batch_size // FLAGS.avg_replays): for k in range(FLAGS.num_steps): for i in range(FLAGS.step_size): indices.append( [j, int(x[j,k,i,0]), int(x[j,k,i,1])] ) indices = np.array(indices) indices = tuple([indices[:,i] for i in range(3)]) partial_scans = np.zeros([FLAGS.batch_size // FLAGS.avg_replays, FLAGS.img_side, FLAGS.img_side]) masks = np.zeros([FLAGS.batch_size // FLAGS.avg_replays, FLAGS.img_side, FLAGS.img_side]) partial_scans[indices] = observations.reshape([-1]) masks[indices] = 1 partial_scans /= np.maximum(masks, 1) masks = np.minimum(masks, 1) partial_scans = np.stack([partial_scans, masks], axis=-1) return partial_scans def target_update_ops(target_network, network, decay=FLAGS.target_decay, l2_norm=False): t_vars = target_network.variables v_vars = network.variables update_ops = [] for t, v in zip(t_vars, v_vars): if FLAGS.is_generator_batch_norm_tracked or not "BatchNorm" in t.name: #Don't track batch normalization if l2_norm: v_new = (1-FLAGS.L2_norm)*v op = v.assign(v_new) update_ops.append(op) else: v_new = v op = t.assign(decay*t + (1-decay)*v_new) update_ops.append(op) #print(t.name.replace("target_", "") == v.name, t.name.replace("target_", ""), v.name) return update_ops def weight_decay_ops(network, weight_decay): v_vars = network.variables update_ops = [] for v in v_vars: v_new = (1-weight_decay)*v op = v.assign(v_new) update_ops.append(op) return update_ops def augmenter(image): image = flip_rotate(image, np.random.randint(0, 8)) image = cv2.GaussianBlur(image, (5, 5), 2.5, None, 2.5) return image def load_data(shape): data_ph = tf.placeholder(tf.float32, shape=list(shape)) ds = tf.data.Dataset.from_tensor_slices(tuple([data_ph])) ds = ds.map(lambda image: tf.reshape(tf.py_func(augmenter, [image], [tf.float32]), [FLAGS.img_side, FLAGS.img_side, 1])) if FLAGS.is_self_competition: labels = tf.data.Dataset.range(0, list(shape)[0]) ds = tf.data.Dataset.zip((ds, labels)) ds = ds.shuffle(buffer_size=FLAGS.shuffle_size) ds = ds.repeat() ds = ds.batch(FLAGS.batch_size // FLAGS.avg_replays) ds = ds.prefetch(FLAGS.prefetch_size) iterator = ds.make_initializable_iterator() return data_ph, iterator @tf.custom_gradient def overwrite_grads(x, y): print("OG", x, y) def grad(dy): return y, None return x, grad def infill(data, mask): #b = mask > 0 #data[b] = cv2.GaussianBlur(data, (5, 5), 2.5, None, 2.5)[b] / \ # cv2.GaussianBlur(mask.astype(np.float32), (5, 5), 2.5, None, 2.5)[b] return data[tuple(nd.distance_transform_edt(np.equal(mask, 0), return_distances=False, return_indices=True))] #def infill(data, mask): # return data[tuple(nd.distance_transform_edt(np.equal(mask, 0), return_distances=False, return_indices=True))] #def infill(data, mask): # x = np.zeros(data.shape) # c = (cv2.GaussianBlur(mask.astype(np.float32), (7, 7), 3.5, None, 3.5) > 0).astype(np.float32) # truth = data[tuple(nd.distance_transform_edt(np.equal(mask, 0), return_distances=False, return_indices=True))] # x = (truth*c).astype(np.float32) # return x def fill(input): return np.expand_dims(np.stack([infill(img, mask) for img, mask in zip(input[:,:,:,0], input[:,:,:,1])]), -1) def flip_rotate(img, choice): """Applies a random flip || rotation to the image, possibly leaving it unchanged""" if choice == 0: return img elif choice == 1: return np.rot90(img, 1) elif choice == 2: return np.rot90(img, 2) elif choice == 3: return np.rot90(img, 3) elif choice == 4: return np.flip(img, 0) elif choice == 5: return np.flip(img, 1) elif choice == 6: return np.flip(np.rot90(img, 1), 0) else: return np.flip(np.rot90(img, 1), 1) def draw_spiral(coverage, side, num_steps=10_000): """Duration spent at each location as a particle falls in a magnetic field. Trajectory chosen so that the duration density is (approx.) evenly distributed. Trajectory is calculated stepwise. Args: coverage: Average amount of time spent at a random pixel side: Sidelength of square image that the motion is inscribed on. Returns: A spiral """ #Use size that is larger than the image size = int(np.ceil(np.sqrt(2)*side)) #Maximum radius of motion R = size/2 #Get constant in equation of motion k = 1/ (2*np.pi*coverage) #Maximum theta that is in the image theta_max = R / k #Equispaced steps theta = np.arange(0, theta_max, theta_max/num_steps) r = k * theta #Convert to cartesian, with (0,0) at the center of the image x = r*np.cos(theta) + R y = r*np.sin(theta) + R #Draw spiral z = np.empty((x.size + y.size,), dtype=x.dtype) z[0::2] = x z[1::2] = y z = list(z) img = Image.new('F', (size,size), "black") img_draw = ImageDraw.Draw(img) img_draw = img_draw.line(z) img = np.asarray(img) img = img[size//2-side//2:size//2+side//2+side%2, size//2-side//2:size//2+side//2+side%2] return img def average_filter(image): kernel = tf.ones([5,5,1,1]) filtered_image = tf.nn.conv2d(image, kernel, strides=[1, 1, 1, 1], padding="VALID") return filtered_image def pad(tensor, size): d1_pad = size[0] d2_pad = size[1] paddings = tf.constant([[0, 0], [d1_pad, d1_pad], [d2_pad, d2_pad], [0, 0]], dtype=tf.int32) padded = tf.pad(tensor, paddings, mode="REFLECT") return padded def gaussian_kernel(size: int, mean: float, std: float, ): """Makes 2D gaussian Kernel for convolution.""" d = tf.distributions.Normal(mean, std) vals = d.prob(tf.range(start = -size, limit = size + 1, dtype = tf.float32)) gauss_kernel = tf.einsum('i,j->ij', vals, vals) return gauss_kernel / tf.reduce_sum(gauss_kernel) def blur(image, size=2, std_dev=2.5, is_pad=True): gauss_kernel = gaussian_kernel( size, 0., std_dev ) #Expand dimensions of `gauss_kernel` for `tf.nn.conv2d` signature gauss_kernel = gauss_kernel[:, :, tf.newaxis, tf.newaxis] #Convolve if is_pad: image = pad(image, (size,size)) return tf.nn.conv2d(image, gauss_kernel, strides=[1, 1, 1, 1], padding="VALID") def calc_generator_losses(img1, img2): #if FLAGS.data_file == "//Desktop-sa1evjv/h/96x96_stem_crops.npy": # img2 = blur(img2) #Gaussian blur c = 10 #scale factor for historical reasons... Does nothing after first iterations generator_losses = c*tf.reduce_mean( (img1 - img2)**2, axis=[1,2,3] ) losses = generator_losses if FLAGS.style_loss: edges1 = sobel_edges(img1) edges2 = sobel_edges(img2) generator_losses += FLAGS.style_loss*c*tf.reduce_mean( (edges1 - edges2)**2, axis=[1,2,3,4] ) return generator_losses, losses def construct_scans(sampled_actions, sampled_observations, replay_sampled_full_scans): replay_partial_scans = construct_partial_scans(sampled_actions, sampled_observations) if not FLAGS.is_infilled: sampled_full_scans = [] partial_scans = [] spiral_scans = [] for sampled_full_scan, partial_scan in zip(replay_sampled_full_scans, replay_partial_scans): c = np.random.randint(0, 8) sampled_full_scans.append( flip_rotate(sampled_full_scan, c) ) partial_scans.append( flip_rotate(partial_scan, c) ) if FLAGS.is_relative_to_spirals: spiral_scan = spiral * sampled_full_scan spiral_scans.append( flip_rotate(spiral_scan, c) ) sampled_full_scans = np.stack( sampled_full_scans ) partial_scans = np.stack( partial_scans ) else: sampled_full_scans = replay_sampled_full_scans partial_scans = replay_partial_scans return partial_scans.astype(np.float32), sampled_full_scans.astype(np.float32) def avg_bn(x): if FLAGS.is_infilled: print("HELLO") y = 3*x return y else: mu = tf.reduce_mean(x) avg_mu = tf.get_variable(auto_name("avg_mu"), initializer=tf.constant(0.5, dtype=tf.float32)) update_op = avg_mu.assign(FLAGS.loss_norm_decay*avg_mu+(1-FLAGS.loss_norm_decay)*mu) with tf.control_dependencies([update_op]): return x / tf.stop_gradient(avg_mu) #mu2 = tf.reduce_mean(x**2) #avg_mu = tf.get_variable(auto_name("avg_mu"), initializer=tf.constant(0.5, dtype=tf.float32)) #avg_mu2 = tf.get_variable(auto_name("avg_mu2"), initializer=tf.constant(1, dtype=tf.float32)) #update_ops = [avg_mu.assign(FLAGS.loss_norm_decay*avg_mu+(1-FLAGS.loss_norm_decay)*mu), # avg_mu2.assign(FLAGS.loss_norm_decay*avg_mu2+(1-FLAGS.loss_norm_decay)*mu2)] #std = tf.sqrt(avg_mu2 - avg_mu**2 + 1.e-6) #with tf.control_dependencies(update_ops): # return tf.sigmoid( (x - avg_mu) / std ) def rnn_loss_norm(loss): mean = tf.reduce_mean(loss, axis=0, keepdims=True) return loss / tf.stop_gradient(mean) def norm_clip(x, clip): rms = tf.sqrt(tf.reduce_mean(x**2)) avg_mu = tf.get_variable(auto_name("avg_rms"), initializer=tf.constant(1., dtype=tf.float32)) update_op = avg_mu.assign(0.997*avg_mu+(1-0.997)*rms) with tf.control_dependencies([update_op]): return tf.tanh( x / (clip*avg_mu) ) def rnn_action_uniformity_loss(x, sigma, num_points, min_val, max_val): #points = tf.lin_space(start=min_val, stop=max_val, num=num_points) #points = tf.expand_dims(tf.expand_dims(points, axis=0), axis=0) #Add batch and time dimensions np_points = np.linspace(min_val, max_val, num_points) np_points = np_points[np.newaxis, np.newaxis, ...] np_weights = norm.cdf((np.pi + np_points)/sigma) + norm.cdf((np.pi - np_points)/sigma) np_weights = 1/np_weights points = tf.convert_to_tensor(np_points.astype(np.float32)) weights = tf.convert_to_tensor(np_weights.astype(np.float32)) print("POINTS", points) dists = (x-points)**2/(2*sigma**2) density = weights*tf.exp(-dists) #density = tf.where( dists < 4.5, tf.exp(-dists), tf.zeros(dists.shape) ) density = tf.reduce_sum(density, axis=0) #density = tf.exp(- tf.minimum( , 4.5 ) ) #Broadcast points. 10 for numerical stability pdf = density / tf.reduce_sum(density, axis=-1, keepdims=True) l2_norm = tf.sqrt(tf.reduce_sum(pdf**2, axis=-1)) sqrt_d = np.sqrt(num_points) #with tf.control_dependencies([tf.print(pdf[0,13:19])]): loss = (l2_norm*sqrt_d - 1) / (sqrt_d - 1) return loss def rmsprop_clip_by_value(optimizer, grads_and_vars, limit): new_grads_and_vars = [] for (g, v) in grads_and_vars: rms = tf.sqrt(tf.reduce_mean(optimizer.get_slot(v, "v"))) new_g = tf.clip_by_value(g, -limit*rms, limit*rms) new_grads_and_vars.append((new_g, v)) return new_grads_and_vars def main(unused_argv): """Trains the DNC and periodically reports the loss.""" graph = tf.get_default_graph() action_shape = [FLAGS.batch_size, FLAGS.num_steps, FLAGS.num_actions] observation_shape = [FLAGS.batch_size, FLAGS.num_steps, FLAGS.step_size] full_scan_shape = [FLAGS.batch_size // FLAGS.avg_replays, FLAGS.img_side, FLAGS.img_side, 1] partial_scan_shape = [FLAGS.batch_size // FLAGS.avg_replays, FLAGS.img_side, FLAGS.img_side, 2] images = np.load(FLAGS.data_file) images[np.logical_not(np.isfinite(images))] = 0 images = np.stack([norm_img(x) for x in images]) train_images = images[:int(0.8*len(images))] val_images = images[int(0.8*len(images)):] train_data_ph, train_iterator = load_data(train_images.shape) val_data_ph, val_iterator = load_data(val_images.shape) if FLAGS.is_self_competition: (full_scans, labels) = train_iterator.get_next() (val_full_scans, val_labels) = val_iterator.get_next() else: (full_scans, ) = train_iterator.get_next() (val_full_scans, ) = val_iterator.get_next() if hasattr(tf, 'ensure_shape'): full_scans = tf.ensure_shape(full_scans, full_scan_shape) val_full_scans = tf.ensure_shape(val_full_scans, full_scan_shape) else: full_scans = tf.reshape(full_scans, full_scan_shape) val_full_scans = tf.reshape(full_scans, full_scan_shape) replay = RingBuffer( action_shape=action_shape, observation_shape=observation_shape, full_scan_shape=full_scan_shape, batch_size=FLAGS.batch_size, buffer_size=FLAGS.replay_size, num_past_losses=train_images.shape[0], ) replay_actions_ph = tf.placeholder(tf.float32, shape=action_shape, name="replay_action") replay_observations_ph = tf.placeholder(tf.float32, shape=observation_shape, name="replay_observation") replay_full_scans_ph = tf.placeholder(tf.float32, shape=full_scan_shape, name="replay_full_scan") partial_scans_ph = tf.placeholder(tf.float32, shape=partial_scan_shape, name="replay_partial_scan") is_training_ph = tf.placeholder(tf.bool, name="is_training") if FLAGS.over_edge_penalty: over_edge_penalty_ph = tf.placeholder(tf.float32, name="over_edge_penalty") if FLAGS.is_noise_decay: noise_decay_ph = tf.placeholder(tf.float32, shape=(), name="noise_decay") else: noise_decay_ph = None decay_ph = tf.placeholder(tf.float32, name="target_decay") if FLAGS.supervision_iters: supervision_ph = tf.placeholder(tf.float32, name="supervision") else: supervision_ph = FLAGS.supervision if FLAGS.is_prioritized_replay: priority_weights_ph = tf.placeholder(tf.float32, shape=[FLAGS.batch_size], name="priority_weights") batch_size = FLAGS.batch_size if FLAGS.is_relative_to_spirals: coverage = FLAGS.num_steps*FLAGS.step_size/FLAGS.img_side**2 spiral = draw_spiral(coverage=coverage, side=FLAGS.img_side) ys = [1/i**2 for i in range(9, 2, -1)] xs = [np.sum(draw_spiral(coverage=c, side=FLAGS.img_side)) / FLAGS.img_side**2 for c in ys] ub_idx = next(i for i, x in xs if x > coverage) lb = xs[ub_idx-1] ub = xs[ub_idx] input_coverage = ( (coverage - lb)*X + (ub - coverage)*Y ) / (lb - ub) actor = Agent( num_outputs=FLAGS.num_actions, is_new=True, noise_decay=noise_decay_ph, sampled_full_scans=full_scans, val_full_scans=val_full_scans, name="actor" ) if FLAGS.is_target_actor: target_actor = Agent(num_outputs=FLAGS.num_actions, name="target_actor") critic = Agent(num_outputs=1, is_double_critic=True, name="critic") target_critic = Agent(num_outputs=1, is_double_critic=True, name="target_critic") new_observations, new_actions = actor.get_new_experience() #if hasattr(tf, 'ensure_shape'): # partial_scans_ph = tf.ensure_shape(partial_scans_ph, partial_scan_shape) # replay_full_scans_ph = tf.ensure_shape(replay_full_scans_ph, full_scan_shape) #else: # partial_scans_ph = tf.reshape(partial_scans_ph, partial_scan_shape) # replay_full_scans_ph = tf.reshape(replay_full_scans_ph, full_scan_shape) #Last actions are unused replay_observations = replay_observations_ph[:,:-1,:] replay_actions = replay_actions_ph[:,:-1,:] #First action must be added for actors (not critics) if FLAGS.num_actions == 2: start_actions = FLAGS.step_incr*tf.ones([FLAGS.batch_size, 1, FLAGS.num_actions])/np.sqrt(2) elif FLAGS.num_actions == 1: start_actions = (np.pi/4) * tf.ones([batch_size, 1, FLAGS.num_actions]) started_replay_actions = tf.concat([start_actions, replay_actions[:,:-1,:]], axis=1) actions = actor(replay_observations, started_replay_actions) if FLAGS.is_target_actor: target_actions = target_actor(replay_observations, started_replay_actions) elif FLAGS.supervision != 1: target_actions = actions #The last action is never used, and the first action is diagonally north-east #Shifting because network expect actions from previous steps to be inputted #start_actions = tf.ones([FLAGS.batch_size, 1, FLAGS.num_actions])/np.sqrt(2) #actions = tf.concat([start_actions, actions[:, :-1, :]], axis=1) #target_actions = tf.concat([start_actions, target_actions[:, :-1, :]], axis=1) actor_actions = tf.concat([replay_actions, actions], axis=-1) qs = critic(replay_observations, actor_actions) critic_qs = qs[:,:,:1] if FLAGS.is_target_critic and not FLAGS.is_target_actor_feedback: actor_qs = qs[:,:,1:] if FLAGS.is_target_critic: target_actor_actions = tf.concat([replay_actions, target_actions], axis=-1) target_qs = target_critic(replay_observations, target_actor_actions) target_actor_qs = target_qs[:,:,1:] if FLAGS.is_target_actor_feedback: actor_qs = target_actor_qs target_actor_qs = tf.stop_gradient(target_actor_qs) elif FLAGS.supervision != 1: target_actor_qs = actor_qs#critic(replay_observations, target_actor_actions)[:,:,1:] target_actor_qs = tf.stop_gradient(target_actor_qs) #if FLAGS.is_positive_qs and (FLAGS.is_target_critic or FLAGS.supervision != 1): #critic_qs = tf.abs(critic_qs) #actor_qs = tf.abs(actor_qs) #target_actor_qs = tf.abs(target_actor_qs) #target_actor_qs = tf.clip_by_value(target_actor_qs, 0, 1) #if FLAGS.loss_norm_decay: # processed_replay_losses_ph = avg_bn(replay_losses_ph) #else: # processed_replay_losses_ph = replay_losses_ph #if FLAGS.is_norm_q: # critic_qs /= tf.reduce_mean(tf.nn.relu(critic_qs), axis=0, keepdims=True) # actor_qs /= tf.reduce_mean(tf.nn.relu(actor_qs), axis=0, keepdims=True) # target_actor_qs /= tf.reduce_mean(tf.nn.relu(target_actor_qs), axis=0, keepdims=True) #replay_losses_ph /= tf.reduce_mean(replay_losses_ph) if not FLAGS.is_infilled: generator = Generator(name="generator", is_training=is_training_ph) #blurred_partial_scans = tf.concat( # [blur(partial_scans_ph[:,:,:,i:i+1], size=4, std_dev=2.5) for i in range(2)], # axis=-1) generation = generator(partial_scans_ph) else: generation = tf.py_func(fill, [partial_scans_ph], tf.float32) if hasattr(tf, 'ensure_shape'): generation = tf.ensure_shape(generation, full_scan_shape) else: generation = tf.reshape(generation, full_scan_shape) generator_losses, losses = calc_generator_losses(generation, replay_full_scans_ph) unclipped_losses = losses #losses = generator_losses print("Losses", losses) if FLAGS.is_clipped_reward: losses = alrc(losses) if FLAGS.loss_norm_decay: losses = avg_bn(losses) #if FLAGS.is_clipped_reward: # losses /= 3 # losses = tf.minimum(losses, tf.sqrt(losses)) if FLAGS.uniform_coverage_loss: side = int(np.sqrt(FLAGS.img_side**2 / (FLAGS.num_steps*FLAGS.step_size))) blurred_path = blur(partial_scans_ph[:,:,:,1:], size=3*side, std_dev=1.0*side, is_pad=False) blurred_path /= FLAGS.num_steps*FLAGS.step_size / FLAGS.img_side**2 uniformity_loss = tf.reduce_mean( (blurred_path - 1)**2 ) #blurred_path /= tf.reduce_sum(blurred_path, axis=[1,2,3], keepdims=True) #uniformity_loss = tf.sqrt(tf.reduce_sum(blurred_path**2, axis=[1,2,3])) #uniformity_loss = (FLAGS.img_side*uniformity_loss - 1) / (FLAGS.img_side - 1) losses += noise_decay_ph*FLAGS.uniform_coverage_loss*uniformity_loss if FLAGS.is_target_generator and not FLAGS.is_infilled: target_generator = Generator(name="target_generator", is_training=is_training_ph) target_generation = target_generator(partial_scans_ph) if FLAGS.is_minmax_reward: errors = (target_generation - replay_full_scans_ph)**2 losses = tf.reduce_max( average_filter(errors), reduction_indices=[1,2,3] ) else: target_generator_losses, losses = calc_generator_losses(target_generation, replay_full_scans_ph) losses = target_generator_losses #For RL else: if FLAGS.is_minmax_reward: errors = (generation - replay_full_scans_ph)**2 losses = tf.reduce_max( average_filter(errors), reduction_indices=[1,2,3] ) if FLAGS.specificity: discriminator = Discriminator(name="discriminator", is_training=is_training_ph) true_ps = tf.stack( [replay_full_scans_ph[:,:,:,0], partial_scans_ph[:,:,:,1]], axis=-1 ) permuted_paths = tf.concat([partial_scans_ph[1:,:,:,1], partial_scans_ph[:1,:,:,1]], axis=0) false_ps = tf.stack( [replay_full_scans_ph[:,:,:,0], permuted_paths], axis=-1 ) discr_inputs = tf.concat([true_ps, false_ps], axis=0) discr_outputs = discriminator(discr_inputs) discr_outputs, avg_discr_outputs = avg_bn(discr_outputs) true_outputs = discr_outputs[:FLAGS.batch_size // FLAGS.avg_replays] false_outputs = discr_outputs[FLAGS.batch_size // FLAGS.avg_replays:] diffs = true_outputs - false_outputs discriminator_losses = tf.reduce_mean( diffs ) + tf.reduce_mean( discr_outputs**2 ) avg_true_outputs = avg_discr_outputs[:FLAGS.batch_size // FLAGS.avg_replays, 0] losses += FLAGS.specificity*avg_true_outputs if FLAGS.end_edge_penalty: if FLAGS.num_actions == 2: cartesian_new_actions = replay_actions_ph elif FLAGS.num_actions == 1: cartesian_new_actions = FLAGS.step_incr*tf.concat([tf.cos(replay_actions_ph), tf.sin(replay_actions_ph)], axis=-1) positions = ( 0.5 + #middle of image FLAGS.step_incr*FLAGS.step_size/FLAGS.img_side + #First step (FLAGS.step_size/FLAGS.img_side)*tf.cumsum(cartesian_new_actions[:,:-1,:], axis=1) # Actions ) is_over_edge = tf.logical_or(tf.greater(positions, 1), tf.less(positions, 0)) is_over_edge = tf.logical_or(is_over_edge[:,:,0], is_over_edge[:,:,1]) over_edge_losses = tf.where( is_over_edge, over_edge_penalty_ph*tf.ones(is_over_edge.get_shape()), tf.zeros(is_over_edge.get_shape()) ) over_edge_losses = tf.reduce_sum(over_edge_losses, axis=-1) losses += over_edge_losses val_observations, val_actions = actor.get_val_experience() #if FLAGS.norm_generator_losses_decay: # mu = tf.get_variable(name="loss_mean", initializer=tf.constant(1., dtype=tf.float32)) # mu_op = mu.assign(FLAGS.norm_generator_losses_decay*mu+(1-FLAGS.norm_generator_losses_decay)*tf.reduce_mean(losses)) # tf.add_to_collection(tf.GraphKeys.UPDATE_OPS, mu_op) # losses /= tf.stop_gradient(mu) #if FLAGS.is_clipped_reward: # losses = alrc(losses) #if FLAGS.is_self_competition: # self_competition_losses = tf.where( # past_losses_ph > unclipped_losses, # tf.ones([FLAGS.batch_size]), # tf.zeros([FLAGS.batch_size]) # ) # losses += self_competition_losses if FLAGS.over_edge_penalty: if FLAGS.num_actions == 2: cartesian_new_actions = replay_actions_ph elif FLAGS.num_actions == 1: cartesian_new_actions = FLAGS.step_incr*tf.concat([tf.cos(replay_actions_ph), tf.sin(replay_actions_ph)], axis=-1) positions = ( 0.5 + #middle of image FLAGS.step_incr*FLAGS.step_size/FLAGS.img_side + #First step (FLAGS.step_size/FLAGS.img_side)*tf.cumsum(cartesian_new_actions[:,:-1,:], axis=1) # Actions ) is_over_edge = tf.logical_or(tf.greater(positions, 1), tf.less(positions, 0)) is_over_edge = tf.logical_or(is_over_edge[:,:,0], is_over_edge[:,:,1]) over_edge_losses = tf.where( is_over_edge, over_edge_penalty_ph*tf.ones(is_over_edge.get_shape()), tf.zeros(is_over_edge.get_shape()) ) #over_edge_losses = tf.cumsum(over_edge_losses, axis=1) if FLAGS.supervision > 0 or FLAGS.is_advantage_actor_critic: supervised_losses = [] for i in reversed(range(FLAGS.num_steps-1)): if i == FLAGS.num_steps-1 - 1: #Extra -1 as idxs start from 0 step_loss = tf.expand_dims(losses, axis=-1) else: step_loss = FLAGS.gamma*step_loss #if FLAGS.over_edge_penalty: # step_loss += over_edge_losses[:,i:i+1] supervised_losses.append(step_loss) supervised_losses = tf.concat(supervised_losses, axis=-1) if FLAGS.supervision < 1: bellman_losses = tf.concat( [FLAGS.gamma*target_actor_qs[:,1:,0], tf.expand_dims(losses, axis=-1)], axis=-1 ) bellman_losses = supervision_ph * supervised_losses + (1 - supervision_ph) * bellman_losses else: bellman_losses = supervised_losses if FLAGS.over_edge_penalty: bellman_losses += over_edge_losses if FLAGS.loss_gamma != 1: loss_gamma_decays = FLAGS.loss_gamma**tf.expand_dims(tf.lin_space(FLAGS.num_steps-2.0, 0.0, FLAGS.num_steps-1), axis=0) if FLAGS.is_prioritized_replay: unweighted_critic_losses = tf.reduce_mean( ( critic_qs[:,:,0] - bellman_losses )**2, axis=-1 ) critic_losses = tf.reduce_mean( priority_weights_ph*unweighted_critic_losses ) else: critic_qs_slice = critic_qs[:,:,0] critic_losses = ( critic_qs_slice - bellman_losses )**2 if FLAGS.is_clipped_critic: critic_losses = alrc( critic_losses ) if FLAGS.rnn_norm_decay: critic_losses = rnn_loss_norm(critic_losses) if FLAGS.loss_gamma != 1: critic_losses *= loss_gamma_decays**2 if FLAGS.is_biased_prioritized_replay: unweighted_critic_losses = critic_losses[:,-1] critic_losses = tf.reduce_mean( critic_losses ) if FLAGS.spike_loss: diffs = critic_qs_slice[:,1:] - critic_qs_slice[:,:-1] diffs_start = diffs[:,1:] diffs_end = diffs[:,:-1] spike_losses = tf.where(diffs_start*diffs_end < 0, tf.minimum(tf.abs(diffs_start), tf.abs(diffs_end)), tf.zeros(diffs_start.get_shape()) ) critic_losses += FLAGS.spike_loss*tf.reduce_mean(spike_losses) if FLAGS.is_advantage_actor_critic: actor_losses = tf.reduce_mean( supervised_losses - actor_qs[:,:,0] ) else: if FLAGS.is_clipped_critic: actor_losses = alrc(actor_qs[:,:,0]) else: actor_losses = actor_qs[:,:,0] if FLAGS.is_direct_advantage: bases0 = FLAGS.gamma*tf.reduce_mean(critic_qs[:,:1,0], axis=0, keepdims=True) bases0 = tf.tile(bases0, [FLAGS.batch_size, 1]) bases = tf.concat([bases0, critic_qs[:,:-1,0]], axis=1) actor_losses = actor_losses - bases #if FLAGS.rnn_norm_decay: # actor_losses = rnn_loss_norm(actor_losses, absolute=True) if FLAGS.loss_gamma != 1: actor_losses *= loss_gamma_decays actor_losses = tf.reduce_mean( actor_losses ) if FLAGS.exploration_loss: exploration_losses = rnn_action_uniformity_loss(actions, np.pi/32, 32, -np.pi, np.pi) actor_losses += noise_decay_ph*FLAGS.exploration_loss*tf.reduce_mean(exploration_losses) if FLAGS.loss_norm_clip: actor_losses = norm_clip(actor_losses, FLAGS.loss_norm_clip) critic_losses = norm_clip(critic_losses, FLAGS.loss_norm_clip) #critic_losses /= FLAGS.num_steps #actor_losses /= FLAGS.num_steps #Outputs to provide feedback for the developer info = { "actor_losses": actor_losses, "critic_losses": critic_losses, "generator_losses": tf.reduce_mean(unclipped_losses) } if FLAGS.specificity: info.update({"discriminator_output": avg_true_outputs[0]}) if FLAGS.is_prioritized_replay or FLAGS.is_biased_prioritized_replay: info.update( {"priority_weights": unweighted_critic_losses} ) if FLAGS.is_self_competition: info.update( {"unclipped_losses": unclipped_losses} ) outputs = { "generation": generation[0,:,:,0], "truth": replay_full_scans_ph[0,:,:,0], "input": partial_scans_ph[0,:,:,0] } history_op = { "actions": new_actions, "observations": new_observations, "labels": labels, "full_scans": full_scans } if FLAGS.is_self_competition: history_op.update( {"labels": labels} ) ##Modify actor gradients #[actor_grads] = tf.gradients(actor_losses, replay_actions_ph) #actor_losses = overwrite_grads(actions, actor_grads) start_iter = FLAGS.start_iter train_iters = FLAGS.train_iters config = tf.ConfigProto() config.gpu_options.allow_growth = True #Only use required GPU memory #config.gpu_options.force_gpu_compatible = True model_dir = FLAGS.model_dir log_filepath = model_dir + "log.txt" save_period = 1; save_period *= 3600 log_file = open(log_filepath, "a") with tf.Session(config=config) as sess: if FLAGS.is_target_actor: if FLAGS.update_frequency <= 1: update_target_actor_op = target_update_ops(target_actor, actor, decay=decay_ph, l2_norm=FLAGS.L2_norm) else: update_target_actor_op = [] initial_update_target_actor_op = target_update_ops(target_actor, actor, decay=0, l2_norm=FLAGS.L2_norm) else: update_target_actor_op = weight_decay_ops(actor, FLAGS.L2_norm) initial_update_target_actor_op = weight_decay_ops(actor, FLAGS.L2_norm) if FLAGS.is_target_critic: if FLAGS.update_frequency <= 1: update_target_critic_op = target_update_ops(target_critic, critic, decay=decay_ph, l2_norm=FLAGS.L2_norm) else: update_target_critic_op = [] initial_update_target_critic_op = target_update_ops(target_critic, critic, decay=0, l2_norm=FLAGS.L2_norm) else: update_target_critic_op = weight_decay_ops(critic, FLAGS.L2_norm) initial_update_target_critic_op = weight_decay_ops(critic, FLAGS.L2_norm) if FLAGS.is_target_generator and not FLAGS.is_infilled: if FLAGS.update_frequency <= 1: update_target_generator_op = target_update_ops(target_generator, generator, decay=decay_ph, l2_norm=FLAGS.L2_norm) else: update_target_generator_op = [] initial_update_target_generator_op = target_update_ops(target_generator, generator, decay=0, l2_norm=FLAGS.L2_norm) elif not FLAGS.is_infilled: update_target_generator_op = weight_decay_ops(generator, FLAGS.L2_norm) initial_update_target_generator_op = weight_decay_ops(generator, FLAGS.L2_norm) else: update_target_generator_op = [] initial_update_target_generator_op = [] initial_update_target_network_ops = ( initial_update_target_actor_op + initial_update_target_critic_op + initial_update_target_generator_op ) actor_lr = FLAGS.actor_lr critic_lr = FLAGS.critic_lr if FLAGS.is_cyclic_generator_learning_rate and not FLAGS.is_infilled: generator_lr = tf.placeholder(tf.float32, name="generator_lr") else: generator_lr = FLAGS.generator_lr #critic_rep = (critic_qs[:,:,0] - bellman_losses)**2 #ps = [critic_qs[0,:,0], target_actor_qs[0,:,0], bellman_losses[0], critic_rep[0]] #ps = [critic.trainable_variables[0], target_critic.trainable_variables[0]] ps = [] #p = bellman_losses[0] #p = generation[0,:,:,0] train_op_dependencies = tf.get_collection(tf.GraphKeys.UPDATE_OPS) if not FLAGS.update_frequency: update_target_network_ops = ( update_target_actor_op + update_target_critic_op + update_target_generator_op ) if FLAGS.grad_clip_value: step = tf.Variable(0., trainable=False, name='step') step_op = step.assign_add(1) update_target_network_ops += [step_op] train_op_dependencies += update_target_network_ops train_ops = [] with tf.control_dependencies(train_op_dependencies): actor_optimizer = tf.train.RMSPropOptimizer(learning_rate=actor_lr) critic_optimizer = tf.train.RMSPropOptimizer(learning_rate=critic_lr) actor_grads = actor_optimizer.compute_gradients( loss=actor_losses, var_list=actor.trainable_variables) critic_grads = critic_optimizer.compute_gradients( loss=critic_losses, var_list=critic.trainable_variables) #if FLAGS.grad_clip_value: # actor_optimizer._create_slots(actor.trainable_variables) # critic_optimizer._create_slots(critic.trainable_variables) # actor_optimizer._create_slots = lambda var_list: None # critic_optimizer._create_slots = lambda var_list: None # limit = FLAGS.grad_clip_value*tf.maximum(10_000*(5_000 - step), 1.) # actor_grads = rmsprop_clip_by_value(actor_optimizer, actor_grads, limit) # critic_grads = rmsprop_clip_by_value(critic_optimizer, critic_grads, limit) if FLAGS.grad_clip_value: #ps = [tf.reduce_max(tf.abs(g)) for (g, v) in actor_grads] #with tf.control_dependencies([tf.Print(p, [p]) for p in ps]): actor_grads = [(tf.clip_by_value(g, -FLAGS.grad_clip_value, FLAGS.grad_clip_value), v) for (g, v) in actor_grads] #ps = [tf.reduce_mean(tf.abs(g)) for (g, v) in critic_grads] #with tf.control_dependencies([tf.Print(p, [p]) for p in ps]): critic_grads = [(tf.clip_by_value(g, -FLAGS.grad_clip_value, FLAGS.grad_clip_value), v) for (g, v) in critic_grads] if FLAGS.grad_clip_norm: #ps = [tf.reduce_max(tf.abs(g)) for (g, v) in actor_grads] #with tf.control_dependencies([tf.Print(p, [p]) for p in ps]): actor_grads = [(tf.clip_by_norm(g, FLAGS.grad_clip_norm), v) for (g, v) in actor_grads] #ps = [tf.reduce_mean(tf.abs(g)) for (g, v) in critic_grads] #with tf.control_dependencies([tf.Print(p, [p]) for p in ps]): critic_grads = [(tf.clip_by_norm(g, FLAGS.grad_clip_norm), v) for (g, v) in critic_grads] actor_train_op = actor_optimizer.apply_gradients(actor_grads) critic_train_op = critic_optimizer.apply_gradients(critic_grads) train_ops += [actor_train_op, critic_train_op] if not FLAGS.is_infilled: generator_train_op = tf.train.AdamOptimizer(learning_rate=generator_lr).minimize( loss=generator_losses, var_list=generator.trainable_variables) train_ops.append(generator_train_op) if FLAGS.specificity: discriminator_train_op = tf.train.AdamOptimizer(learning_rate=FLAGS.discriminator_lr).minimize( loss=discriminator_losses, var_list=discriminator.trainable_variables) train_ops.append(discriminator_train_op) feed_dict = {is_training_ph: np.bool(True), decay_ph: np.float32(0.99)} sess.run(tf.global_variables_initializer(), feed_dict=feed_dict) saver = tf.train.Saver(max_to_keep=1) noteable_saver = tf.train.Saver(max_to_keep=2) saver.restore( sess, tf.train.latest_checkpoint(model_dir+"noteable_ckpt/") ) sess.run(train_iterator.initializer, feed_dict={train_data_ph: train_images}) sess.run(val_iterator.initializer, feed_dict={val_data_ph: val_images}) #Add first experiences to the replay if FLAGS.is_noise_decay: feed_dict.update({noise_decay_ph: np.float32(1)}) for _ in range(FLAGS.avg_replays): history = sess.run( history_op, feed_dict=feed_dict) replay.add(**history) time0 = time.time() for iter in range(start_iter, train_iters): #Sample experiences from the replay if FLAGS.is_prioritized_replay: sampled_actions, sampled_observations, replay_sampled_full_scans, sample_idxs, sampled_priority_weights = replay.get() #elif FLAGS.is_biased_prioritized_replay: # sampled_actions, sampled_observations, replay_sampled_full_scans, sample_idxs = replay.get() elif FLAGS.is_self_competition: sampled_actions, sampled_observations, sample_idxs, sampled_past_losses, replay_sampled_full_scans = replay.get() else: sampled_actions, sampled_observations, replay_sampled_full_scans = replay.get() if FLAGS.is_ranked_loss: idxs = np.argsort(sampled_past_losses) sampled_past_losses[idxs] = np.linspace(0, 1, FLAGS.batch_size) target_decay = FLAGS.target_decay**( 1 + max(100_000 - iter, 0)/10_000 ) augmented_partial_scans, augmented_full_scans = construct_scans( sampled_actions, sampled_observations, replay_sampled_full_scans ) feed_dict = { replay_actions_ph: sampled_actions, replay_observations_ph: sampled_observations, is_training_ph: np.bool(True), decay_ph: np.float32(target_decay), partial_scans_ph: augmented_partial_scans, replay_full_scans_ph: augmented_full_scans } if FLAGS.over_edge_penalty: penalty = np.float32(FLAGS.over_edge_penalty) #penalty = np.float32( FLAGS.over_edge_penalty*max((10_000 - iter)/10_000, 0) ) feed_dict.update( {over_edge_penalty_ph: penalty} ) if FLAGS.is_noise_decay: noise_decay = np.float32( np.maximum( ((train_iters//2 - iter)/(train_iters//2))**2, 0) ) feed_dict.update( {noise_decay_ph: noise_decay} ) if FLAGS.is_prioritized_replay: feed_dict.update({priority_weights_ph: sampled_priority_weights}) if FLAGS.supervision_iters: supervision = FLAGS.supervision_start + min(iter, FLAGS.supervision_iters)*(FLAGS.supervision_end-FLAGS.supervision_start) / FLAGS.supervision_iters feed_dict.update( {supervision_ph: supervision } ) if FLAGS.is_cyclic_generator_learning_rate and not FLAGS.is_infilled: if FLAGS.is_decaying_generator_learning_rate: envelope = FLAGS.generator_lr * 0.75**(iter/(train_iters//5)) else: envelope = FLAGS.generator_lr cycle_half = train_iters//(10 - 1) cycle_full = 2*cycle_half cyclic_sawtooth = 1 - (min(iter%cycle_full, cycle_half) - min(iter%cycle_full - cycle_half, 0))/cycle_half cyclic_lr = envelope*(0.2 + 0.8*cyclic_sawtooth) feed_dict.update( {generator_lr: np.float32(cyclic_lr)} ) #Train if True: history, step_info, step_outputs = sess.run([history_op, info, outputs], feed_dict=feed_dict) for k in step_outputs: save_loc = FLAGS.model_dir + k + str(iter)+".tif" Image.fromarray( (0.5*step_outputs[k]+0.5).astype(np.float32) ).save( save_loc ) else: _, history, step_info = sess.run([train_ops, history_op, info], feed_dict=feed_dict) if iter < 100_000 or not np.random.randint(0, int(max(iter/100_000, 1)*FLAGS.replay_add_frequency)): replay.add(**history) if iter >= 100: quit() if FLAGS.update_frequency: period = max(int(min(iter/100_000, 1)*(FLAGS.update_frequency-1)), 1) if not iter % np.random.randint(1, 1 + period): sess.run(initial_update_target_network_ops, feed_dict=feed_dict) if FLAGS.is_prioritized_replay or FLAGS.is_biased_prioritized_replay: replay.update_priorities(sample_idxs, step_info["priority_weights"]) output = f"Iter: {iter}" for k in step_info: if k not in ["priority_weights", "unclipped_losses"]: output += f", {k}: {step_info[k]}" if not iter % FLAGS.report_freq: print(output) #if "nan" in output: # saver.restore( # sess, # tf.train.latest_checkpoint(model_dir+"model/") # ) if iter in [train_iters//2-1, train_iters-1]: noteable_saver.save(sess, save_path=model_dir+"noteable_ckpt/model", global_step=iter) time0 = time.time() start_iter = iter elif time.time() >= time0 + save_period: saver.save(sess, save_path=model_dir+"model/model", global_step=iter) time0 = time.time() val_losses_list = [] for iter in range(0, FLAGS.val_examples//FLAGS.batch_size): #Add experiences to the replay feed_dict = {is_training_ph: np.bool(True)} sampled_actions, sampled_observations, sampled_full_scans = sess.run( [val_actions, val_observations, val_full_scans], feed_dict=feed_dict ) partial_scans = construct_partial_scans(sampled_actions, sampled_observations) feed_dict = { replay_actions_ph: sampled_actions, replay_observations_ph: sampled_observations, replay_full_scans_ph: sampled_full_scans, partial_scans_ph: partial_scans, is_training_ph: np.bool(False) } val_losses = sess.run( unclipped_losses, feed_dict=feed_dict ) val_losses_list.append( val_losses ) val_losses = np.concatenate(tuple(val_losses_list), axis=0) np.save(model_dir + "val_losses.npy", val_losses) if __name__ == "__main__": tf.app.run()
[ "tensorflow.einsum", "numpy.sum", "tensorflow.clip_by_value", "tensorflow.cumsum", "numpy.ones", "utility.alrc", "numpy.argsort", "numpy.arange", "utility.auto_name", "numpy.exp", "tensorflow.python.ops.array_ops.shape", "tensorflow.stack", "numpy.max", "tensorflow.python.ops.array_ops.pad", "tensorflow.ensure_shape", "tensorflow.ones", "numpy.minimum", "numpy.save", "tensorflow.stop_gradient", "numpy.min", "tensorflow.random_normal_initializer", "tensorflow.data.Dataset.zip", "tensorflow.lin_space", "tensorflow.expand_dims", "tensorflow.flags.DEFINE_string", "dnc.dnc.Components", "numpy.array", "tensorflow.cos", "tensorflow.python.ops.nn.depthwise_conv2d", "tensorflow.train.RMSPropOptimizer", "tensorflow.nn.l2_normalize", "tensorflow.python.framework.constant_op.constant", "tensorflow.nn.conv2d", "os.chdir", "tensorflow.less", "tensorflow.logical_or", "numpy.isfinite", "numpy.bool", "tensorflow.nn.bias_add", "numpy.stack", "tensorflow.train.Saver", "numpy.flip", "tensorflow.flags.DEFINE_bool", "numpy.expand_dims", "tensorflow.train.AdamOptimizer", "cv2.GaussianBlur", "PIL.Image.new", "numpy.maximum", "numpy.empty", "tensorflow.python.ops.array_ops.reshape", "tensorflow.ConfigProto", "numpy.sin", "numpy.mean", "tensorflow.Variable", "tensorflow.greater", "tensorflow.python.ops.array_ops.tile", "tensorflow.abs", "tensorflow.sin", "tensorflow.pad", "tensorflow.concat", "numpy.equal", "numpy.cumsum", "numpy.linspace", "tensorflow.range", "tensorflow.control_dependencies", "cv2.waitKey", "tensorflow.reduce_mean", "tensorflow.layers.flatten", "tensorflow.tile", "tensorflow.zeros_initializer", "tensorflow.flags.DEFINE_float", "tensorflow.py_func", "tensorflow.nn.dynamic_rnn", "numpy.zeros", "sys.path.insert", "time.time", "cv2.namedWindow", "numpy.absolute", "numpy.load", "tensorflow.reduce_sum", "tensorflow.get_collection", "tensorflow.reshape", "tensorflow.get_variable_scope", "tensorflow.matmul", "numpy.random.randint", "numpy.rot90", "tensorflow.train.latest_checkpoint", "tensorflow.get_default_graph", "scipy.stats.norm.cdf", "tensorflow.placeholder", "tensorflow.exp", "tensorflow.clip_by_norm", "tensorflow.app.run", "tensorflow.global_variables_initializer", "numpy.asarray", "tensorflow.Session", "tensorflow.constant", "tensorflow.transpose", "tensorflow.distributions.Normal", "numpy.cos", "tensorflow.flags.DEFINE_integer", "tensorflow.python.ops.array_ops.concat", "numpy.float32", "dnc.dnc.DNC", "tensorflow.layers.dense", "tensorflow.contrib.layers.batch_norm", "tensorflow.zeros", "tensorflow.tanh", "numpy.sqrt" ]
[((1402, 1475), 'tensorflow.flags.DEFINE_integer', 'tf.flags.DEFINE_integer', (['"""hidden_size"""', '(256)', '"""Size of LSTM hidden layer."""'], {}), "('hidden_size', 256, 'Size of LSTM hidden layer.')\n", (1425, 1475), True, 'import tensorflow as tf\n'), ((1477, 1550), 'tensorflow.flags.DEFINE_integer', 'tf.flags.DEFINE_integer', (['"""memory_size"""', '(16)', '"""The number of memory slots."""'], {}), "('memory_size', 16, 'The number of memory slots.')\n", (1500, 1550), True, 'import tensorflow as tf\n'), ((1552, 1626), 'tensorflow.flags.DEFINE_integer', 'tf.flags.DEFINE_integer', (['"""word_size"""', '(64)', '"""The width of each memory slot."""'], {}), "('word_size', 64, 'The width of each memory slot.')\n", (1575, 1626), True, 'import tensorflow as tf\n'), ((1628, 1706), 'tensorflow.flags.DEFINE_integer', 'tf.flags.DEFINE_integer', (['"""num_write_heads"""', '(1)', '"""Number of memory write heads."""'], {}), "('num_write_heads', 1, 'Number of memory write heads.')\n", (1651, 1706), True, 'import tensorflow as tf\n'), ((1708, 1784), 'tensorflow.flags.DEFINE_integer', 'tf.flags.DEFINE_integer', (['"""num_read_heads"""', '(4)', '"""Number of memory read heads."""'], {}), "('num_read_heads', 4, 'Number of memory read heads.')\n", (1731, 1784), True, 'import tensorflow as tf\n'), ((1786, 1887), 'tensorflow.flags.DEFINE_integer', 'tf.flags.DEFINE_integer', (['"""clip_value"""', '(0)', '"""Maximum absolute value of controller and dnc outputs."""'], {}), "('clip_value', 0,\n 'Maximum absolute value of controller and dnc outputs.')\n", (1809, 1887), True, 'import tensorflow as tf\n'), ((1885, 1974), 'tensorflow.flags.DEFINE_bool', 'tf.flags.DEFINE_bool', (['"""use_batch_norm"""', '(True)', '"""Use batch normalization in generator."""'], {}), "('use_batch_norm', True,\n 'Use batch normalization in generator.')\n", (1905, 1974), True, 'import tensorflow as tf\n'), ((1974, 2029), 'tensorflow.flags.DEFINE_string', 'tf.flags.DEFINE_string', (['"""model"""', '"""LSTM"""', '"""LSTM or DNC."""'], {}), "('model', 'LSTM', 'LSTM or DNC.')\n", (1996, 2029), True, 'import tensorflow as tf\n'), ((2033, 2135), 'tensorflow.flags.DEFINE_integer', 'tf.flags.DEFINE_integer', (['"""projection_size"""', '(0)', '"""Size of projection layer. Zero for no projection."""'], {}), "('projection_size', 0,\n 'Size of projection layer. Zero for no projection.')\n", (2056, 2135), True, 'import tensorflow as tf\n'), ((2133, 2203), 'tensorflow.flags.DEFINE_integer', 'tf.flags.DEFINE_integer', (['"""lstm_depth"""', '(2)', '"""Number of LSTM cells deep."""'], {}), "('lstm_depth', 2, 'Number of LSTM cells deep.')\n", (2156, 2203), True, 'import tensorflow as tf\n'), ((2207, 2298), 'tensorflow.flags.DEFINE_bool', 'tf.flags.DEFINE_bool', (['"""is_input_embedder"""', '(False)', '"""Embed inputs before they are input."""'], {}), "('is_input_embedder', False,\n 'Embed inputs before they are input.')\n", (2227, 2298), True, 'import tensorflow as tf\n'), ((2296, 2409), 'tensorflow.flags.DEFINE_bool', 'tf.flags.DEFINE_bool', (['"""is_variable_initial_states"""', '(True)', '"""Trainable initial states rather than zero states."""'], {}), "('is_variable_initial_states', True,\n 'Trainable initial states rather than zero states.')\n", (2316, 2409), True, 'import tensorflow as tf\n'), ((2409, 2507), 'tensorflow.flags.DEFINE_bool', 'tf.flags.DEFINE_bool', (['"""is_layer_norm"""', '(False)', '"""Use layer normalization in recurrent networks."""'], {}), "('is_layer_norm', False,\n 'Use layer normalization in recurrent networks.')\n", (2429, 2507), True, 'import tensorflow as tf\n'), ((2532, 2601), 'tensorflow.flags.DEFINE_integer', 'tf.flags.DEFINE_integer', (['"""batch_size"""', '(32)', '"""Batch size for training."""'], {}), "('batch_size', 32, 'Batch size for training.')\n", (2555, 2601), True, 'import tensorflow as tf\n'), ((2605, 2683), 'tensorflow.flags.DEFINE_integer', 'tf.flags.DEFINE_integer', (['"""replay_size"""', '(32)', '"""Maximum examples in ring buffer."""'], {}), "('replay_size', 32, 'Maximum examples in ring buffer.')\n", (2628, 2683), True, 'import tensorflow as tf\n'), ((2685, 2773), 'tensorflow.flags.DEFINE_integer', 'tf.flags.DEFINE_integer', (['"""avg_replays"""', '(1)', '"""Mean frequency each experience is used."""'], {}), "('avg_replays', 1,\n 'Mean frequency each experience is used.')\n", (2708, 2773), True, 'import tensorflow as tf\n'), ((2771, 2873), 'tensorflow.flags.DEFINE_integer', 'tf.flags.DEFINE_integer', (['"""replay_add_frequency"""', '(1)', '"""How often to add expereinces to ring buffer."""'], {}), "('replay_add_frequency', 1,\n 'How often to add expereinces to ring buffer.')\n", (2794, 2873), True, 'import tensorflow as tf\n'), ((2871, 2965), 'tensorflow.flags.DEFINE_bool', 'tf.flags.DEFINE_bool', (['"""is_cyclic_replay"""', '(False)', '"""True to cyclically replace experiences."""'], {}), "('is_cyclic_replay', False,\n 'True to cyclically replace experiences.')\n", (2891, 2965), True, 'import tensorflow as tf\n'), ((2965, 3040), 'tensorflow.flags.DEFINE_float', 'tf.flags.DEFINE_float', (['"""max_grad_norm"""', '(50)', '"""Gradient clipping norm limit."""'], {}), "('max_grad_norm', 50, 'Gradient clipping norm limit.')\n", (2986, 3040), True, 'import tensorflow as tf\n'), ((3042, 3147), 'tensorflow.flags.DEFINE_float', 'tf.flags.DEFINE_float', (['"""L2_norm"""', '(1e-05)', '"""Decay rate for L2 regularization. 0 for no regularization."""'], {}), "('L2_norm', 1e-05,\n 'Decay rate for L2 regularization. 0 for no regularization.')\n", (3063, 3147), True, 'import tensorflow as tf\n'), ((3147, 3255), 'tensorflow.flags.DEFINE_float', 'tf.flags.DEFINE_float', (['"""grad_clip_norm"""', '(0)', '"""Threshold to clip gradient sizes to. Zero for no clipping."""'], {}), "('grad_clip_norm', 0,\n 'Threshold to clip gradient sizes to. Zero for no clipping.')\n", (3168, 3255), True, 'import tensorflow as tf\n'), ((3253, 3364), 'tensorflow.flags.DEFINE_float', 'tf.flags.DEFINE_float', (['"""grad_clip_value"""', '(0.0)', '"""Threshold to clip gradient sizes to. Zero for no clipping."""'], {}), "('grad_clip_value', 0.0,\n 'Threshold to clip gradient sizes to. Zero for no clipping.')\n", (3274, 3364), True, 'import tensorflow as tf\n'), ((3385, 3471), 'tensorflow.flags.DEFINE_integer', 'tf.flags.DEFINE_integer', (['"""img_side"""', '(96)', '"""Number of image pixels for square image"""'], {}), "('img_side', 96,\n 'Number of image pixels for square image')\n", (3408, 3471), True, 'import tensorflow as tf\n'), ((3469, 3556), 'tensorflow.flags.DEFINE_integer', 'tf.flags.DEFINE_integer', (['"""num_steps"""', '(20)', '"""Number of image pixels for square image"""'], {}), "('num_steps', 20,\n 'Number of image pixels for square image')\n", (3492, 3556), True, 'import tensorflow as tf\n'), ((3554, 3649), 'tensorflow.flags.DEFINE_integer', 'tf.flags.DEFINE_integer', (['"""step_size"""', '(20)', '"""Distance STEM probe moves at each step (in px)."""'], {}), "('step_size', 20,\n 'Distance STEM probe moves at each step (in px).')\n", (3577, 3649), True, 'import tensorflow as tf\n'), ((3647, 3737), 'tensorflow.flags.DEFINE_integer', 'tf.flags.DEFINE_integer', (['"""num_actions"""', '(1)', '"""Number of parameters to describe actions."""'], {}), "('num_actions', 1,\n 'Number of parameters to describe actions.')\n", (3670, 3737), True, 'import tensorflow as tf\n'), ((3735, 3830), 'tensorflow.flags.DEFINE_integer', 'tf.flags.DEFINE_integer', (['"""shuffle_size"""', '(2000)', '"""Size of moving buffer to sample data from."""'], {}), "('shuffle_size', 2000,\n 'Size of moving buffer to sample data from.')\n", (3758, 3830), True, 'import tensorflow as tf\n'), ((3828, 3920), 'tensorflow.flags.DEFINE_integer', 'tf.flags.DEFINE_integer', (['"""prefetch_size"""', '(10)', '"""Number of batches to prepare in advance."""'], {}), "('prefetch_size', 10,\n 'Number of batches to prepare in advance.')\n", (3851, 3920), True, 'import tensorflow as tf\n'), ((3941, 4006), 'tensorflow.flags.DEFINE_float', 'tf.flags.DEFINE_float', (['"""actor_lr"""', '(0.0005)', '"""Actor learning rate."""'], {}), "('actor_lr', 0.0005, 'Actor learning rate.')\n", (3962, 4006), True, 'import tensorflow as tf\n'), ((4008, 4074), 'tensorflow.flags.DEFINE_float', 'tf.flags.DEFINE_float', (['"""critic_lr"""', '(0.001)', '"""Critic learning rate."""'], {}), "('critic_lr', 0.001, 'Critic learning rate.')\n", (4029, 4074), True, 'import tensorflow as tf\n'), ((4076, 4148), 'tensorflow.flags.DEFINE_float', 'tf.flags.DEFINE_float', (['"""generator_lr"""', '(0.003)', '"""Generator learning rate."""'], {}), "('generator_lr', 0.003, 'Generator learning rate.')\n", (4097, 4148), True, 'import tensorflow as tf\n'), ((4150, 4235), 'tensorflow.flags.DEFINE_float', 'tf.flags.DEFINE_float', (['"""discriminator_lr"""', '(0.003)', '"""Discriminator learning rate."""'], {}), "('discriminator_lr', 0.003, 'Discriminator learning rate.'\n )\n", (4171, 4235), True, 'import tensorflow as tf\n'), ((4234, 4337), 'tensorflow.flags.DEFINE_float', 'tf.flags.DEFINE_float', (['"""specificity"""', '(0.0)', '"""Weight specificity loss. Zero for no specificity loss."""'], {}), "('specificity', 0.0,\n 'Weight specificity loss. Zero for no specificity loss.')\n", (4255, 4337), True, 'import tensorflow as tf\n'), ((4335, 4447), 'tensorflow.flags.DEFINE_float', 'tf.flags.DEFINE_float', (['"""loss_norm_decay"""', '(0.997)', '"""Weight for loss normalization. Zero for no normalization."""'], {}), "('loss_norm_decay', 0.997,\n 'Weight for loss normalization. Zero for no normalization.')\n", (4356, 4447), True, 'import tensorflow as tf\n'), ((4445, 4561), 'tensorflow.flags.DEFINE_float', 'tf.flags.DEFINE_float', (['"""rnn_norm_decay"""', '(0.0)', '"""Weight for critic loss normalization. Zero for no normalization."""'], {}), "('rnn_norm_decay', 0.0,\n 'Weight for critic loss normalization. Zero for no normalization.')\n", (4466, 4561), True, 'import tensorflow as tf\n'), ((4560, 4649), 'tensorflow.flags.DEFINE_bool', 'tf.flags.DEFINE_bool', (['"""is_immediate_critic_loss"""', '(False)', '"""True to not backpropagate."""'], {}), "('is_immediate_critic_loss', False,\n 'True to not backpropagate.')\n", (4580, 4649), True, 'import tensorflow as tf\n'), ((4649, 4753), 'tensorflow.flags.DEFINE_bool', 'tf.flags.DEFINE_bool', (['"""is_target_actor_feedback"""', '(False)', '"""True to use target critic to train actor."""'], {}), "('is_target_actor_feedback', False,\n 'True to use target critic to train actor.')\n", (4669, 4753), True, 'import tensorflow as tf\n'), ((4751, 4839), 'tensorflow.flags.DEFINE_bool', 'tf.flags.DEFINE_bool', (['"""is_ranked_loss"""', '(False)', '"""Loses are indices in sorted arrays."""'], {}), "('is_ranked_loss', False,\n 'Loses are indices in sorted arrays.')\n", (4771, 4839), True, 'import tensorflow as tf\n'), ((4841, 4899), 'tensorflow.flags.DEFINE_float', 'tf.flags.DEFINE_float', (['"""gamma"""', '(0.97)', '"""Reward/loss decay."""'], {}), "('gamma', 0.97, 'Reward/loss decay.')\n", (4862, 4899), True, 'import tensorflow as tf\n'), ((4901, 4994), 'tensorflow.flags.DEFINE_float', 'tf.flags.DEFINE_float', (['"""loss_gamma"""', '(1.0)', '"""Reward/loss decay applied directly to losses."""'], {}), "('loss_gamma', 1.0,\n 'Reward/loss decay applied directly to losses.')\n", (4922, 4994), True, 'import tensorflow as tf\n'), ((4993, 5064), 'tensorflow.flags.DEFINE_float', 'tf.flags.DEFINE_float', (['"""loss_norm_clip"""', '(0.0)', '"""Norm to clip losses to."""'], {}), "('loss_norm_clip', 0.0, 'Norm to clip losses to.')\n", (5014, 5064), True, 'import tensorflow as tf\n'), ((5067, 5176), 'tensorflow.flags.DEFINE_bool', 'tf.flags.DEFINE_bool', (['"""is_advantage_actor_critic"""', '(False)', '"""Use advantage rather than Q errors for actor."""'], {}), "('is_advantage_actor_critic', False,\n 'Use advantage rather than Q errors for actor.')\n", (5087, 5176), True, 'import tensorflow as tf\n'), ((5174, 5285), 'tensorflow.flags.DEFINE_bool', 'tf.flags.DEFINE_bool', (['"""is_direct_advantage"""', '(False)', '"""Use predicted Q minus exploration Q errors for actor."""'], {}), "('is_direct_advantage', False,\n 'Use predicted Q minus exploration Q errors for actor.')\n", (5194, 5285), True, 'import tensorflow as tf\n'), ((5285, 5387), 'tensorflow.flags.DEFINE_bool', 'tf.flags.DEFINE_bool', (['"""is_cyclic_generator_learning_rate"""', '(True)', '"""True for sawtooth oscillations."""'], {}), "('is_cyclic_generator_learning_rate', True,\n 'True for sawtooth oscillations.')\n", (5305, 5387), True, 'import tensorflow as tf\n'), ((5385, 5508), 'tensorflow.flags.DEFINE_bool', 'tf.flags.DEFINE_bool', (['"""is_decaying_generator_learning_rate"""', '(True)', '"""True for decay envelope for sawtooth oscillations."""'], {}), "('is_decaying_generator_learning_rate', True,\n 'True for decay envelope for sawtooth oscillations.')\n", (5405, 5508), True, 'import tensorflow as tf\n'), ((5508, 5594), 'tensorflow.flags.DEFINE_integer', 'tf.flags.DEFINE_integer', (['"""supervision_iters"""', '(1)', '"""Starting value for supeversion."""'], {}), "('supervision_iters', 1,\n 'Starting value for supeversion.')\n", (5531, 5594), True, 'import tensorflow as tf\n'), ((5592, 5678), 'tensorflow.flags.DEFINE_float', 'tf.flags.DEFINE_float', (['"""supervision_start"""', '(0.0)', '"""Starting value for supeversion."""'], {}), "('supervision_start', 0.0,\n 'Starting value for supeversion.')\n", (5613, 5678), True, 'import tensorflow as tf\n'), ((5675, 5760), 'tensorflow.flags.DEFINE_float', 'tf.flags.DEFINE_float', (['"""supervision_end"""', '(0.0)', '"""Starting value for supeversion."""'], {}), "('supervision_end', 0.0, 'Starting value for supeversion.'\n )\n", (5696, 5760), True, 'import tensorflow as tf\n'), ((6040, 6146), 'tensorflow.flags.DEFINE_bool', 'tf.flags.DEFINE_bool', (['"""is_target_actor"""', '(False and FLAGS.supervision != 1)', '"""True to use target actor."""'], {}), "('is_target_actor', False and FLAGS.supervision != 1,\n 'True to use target actor.')\n", (6060, 6146), True, 'import tensorflow as tf\n'), ((6144, 6251), 'tensorflow.flags.DEFINE_bool', 'tf.flags.DEFINE_bool', (['"""is_target_critic"""', '(True and FLAGS.supervision != 1)', '"""True to use target critic."""'], {}), "('is_target_critic', True and FLAGS.supervision != 1,\n 'True to use target critic.')\n", (6164, 6251), True, 'import tensorflow as tf\n'), ((6249, 6336), 'tensorflow.flags.DEFINE_bool', 'tf.flags.DEFINE_bool', (['"""is_target_generator"""', '(False)', '"""True to use target generator."""'], {}), "('is_target_generator', False,\n 'True to use target generator.')\n", (6269, 6336), True, 'import tensorflow as tf\n'), ((6336, 6454), 'tensorflow.flags.DEFINE_integer', 'tf.flags.DEFINE_integer', (['"""update_frequency"""', '(0)', '"""Frequency of hard target network updates. Zero for soft updates."""'], {}), "('update_frequency', 0,\n 'Frequency of hard target network updates. Zero for soft updates.')\n", (6359, 6454), True, 'import tensorflow as tf\n'), ((6452, 6547), 'tensorflow.flags.DEFINE_float', 'tf.flags.DEFINE_float', (['"""target_decay"""', '(0.997)', '"""Decay rate for target network soft updates."""'], {}), "('target_decay', 0.997,\n 'Decay rate for target network soft updates.')\n", (6473, 6547), True, 'import tensorflow as tf\n'), ((6545, 6659), 'tensorflow.flags.DEFINE_bool', 'tf.flags.DEFINE_bool', (['"""is_generator_batch_norm_tracked"""', '(False)', '"""True to track generator batch normalization."""'], {}), "('is_generator_batch_norm_tracked', False,\n 'True to track generator batch normalization.')\n", (6565, 6659), True, 'import tensorflow as tf\n'), ((6659, 6746), 'tensorflow.flags.DEFINE_bool', 'tf.flags.DEFINE_bool', (['"""is_positive_qs"""', '(False)', '"""Whether to clip qs to be positive."""'], {}), "('is_positive_qs', False,\n 'Whether to clip qs to be positive.')\n", (6679, 6746), True, 'import tensorflow as tf\n'), ((6744, 6820), 'tensorflow.flags.DEFINE_bool', 'tf.flags.DEFINE_bool', (['"""is_norm_q"""', '(False)', '"""Whether to set mean of q values."""'], {}), "('is_norm_q', False, 'Whether to set mean of q values.')\n", (6764, 6820), True, 'import tensorflow as tf\n'), ((6824, 6918), 'tensorflow.flags.DEFINE_bool', 'tf.flags.DEFINE_bool', (['"""is_infilled"""', '(False)', '"""True to use infilling rather than generator."""'], {}), "('is_infilled', False,\n 'True to use infilling rather than generator.')\n", (6844, 6918), True, 'import tensorflow as tf\n'), ((6918, 7011), 'tensorflow.flags.DEFINE_bool', 'tf.flags.DEFINE_bool', (['"""is_prev_position_input"""', '(True)', '"""True to input previous positions."""'], {}), "('is_prev_position_input', True,\n 'True to input previous positions.')\n", (6938, 7011), True, 'import tensorflow as tf\n'), ((7011, 7101), 'tensorflow.flags.DEFINE_bool', 'tf.flags.DEFINE_bool', (['"""is_ornstein_uhlenbeck"""', '(True)', '"""True for O-U exploration noise."""'], {}), "('is_ornstein_uhlenbeck', True,\n 'True for O-U exploration noise.')\n", (7031, 7101), True, 'import tensorflow as tf\n'), ((7099, 7167), 'tensorflow.flags.DEFINE_bool', 'tf.flags.DEFINE_bool', (['"""is_noise_decay"""', '(True)', '"""Decay noise if true."""'], {}), "('is_noise_decay', True, 'Decay noise if true.')\n", (7119, 7167), True, 'import tensorflow as tf\n'), ((7169, 7230), 'tensorflow.flags.DEFINE_float', 'tf.flags.DEFINE_float', (['"""ou_theta"""', '(0.1)', '"""Drift back to mean."""'], {}), "('ou_theta', 0.1, 'Drift back to mean.')\n", (7190, 7230), True, 'import tensorflow as tf\n'), ((7232, 7297), 'tensorflow.flags.DEFINE_float', 'tf.flags.DEFINE_float', (['"""ou_sigma"""', '(0.2)', '"""Size of random process."""'], {}), "('ou_sigma', 0.2, 'Size of random process.')\n", (7253, 7297), True, 'import tensorflow as tf\n'), ((7301, 7368), 'tensorflow.flags.DEFINE_float', 'tf.flags.DEFINE_float', (['"""exploration_loss"""', '(0.0)', '"""Exploration loss."""'], {}), "('exploration_loss', 0.0, 'Exploration loss.')\n", (7322, 7368), True, 'import tensorflow as tf\n'), ((7369, 7457), 'tensorflow.flags.DEFINE_float', 'tf.flags.DEFINE_float', (['"""uniform_coverage_loss"""', '(0)', '"""Additive uniform coverage loss."""'], {}), "('uniform_coverage_loss', 0,\n 'Additive uniform coverage loss.')\n", (7390, 7457), True, 'import tensorflow as tf\n'), ((7457, 7558), 'tensorflow.flags.DEFINE_bool', 'tf.flags.DEFINE_bool', (['"""is_rel_to_truth"""', '(False)', '"""True to normalize losses using expected losses."""'], {}), "('is_rel_to_truth', False,\n 'True to normalize losses using expected losses.')\n", (7477, 7558), True, 'import tensorflow as tf\n'), ((7558, 7630), 'tensorflow.flags.DEFINE_bool', 'tf.flags.DEFINE_bool', (['"""is_clipped_reward"""', '(True)', '"""True to clip rewards."""'], {}), "('is_clipped_reward', True, 'True to clip rewards.')\n", (7578, 7630), True, 'import tensorflow as tf\n'), ((7632, 7739), 'tensorflow.flags.DEFINE_bool', 'tf.flags.DEFINE_bool', (['"""is_clipped_critic"""', '(False)', '"""True to clip critic predictions for actor training."""'], {}), "('is_clipped_critic', False,\n 'True to clip critic predictions for actor training.')\n", (7652, 7739), True, 'import tensorflow as tf\n'), ((7739, 7839), 'tensorflow.flags.DEFINE_float', 'tf.flags.DEFINE_float', (['"""over_edge_penalty"""', '(0.05)', '"""Penalty for action going over edge of image."""'], {}), "('over_edge_penalty', 0.05,\n 'Penalty for action going over edge of image.')\n", (7760, 7839), True, 'import tensorflow as tf\n'), ((7837, 7935), 'tensorflow.flags.DEFINE_float', 'tf.flags.DEFINE_float', (['"""end_edge_penalty"""', '(0.0)', '"""Penalty for action going over edge of image."""'], {}), "('end_edge_penalty', 0.0,\n 'Penalty for action going over edge of image.')\n", (7858, 7935), True, 'import tensorflow as tf\n'), ((7935, 8050), 'tensorflow.flags.DEFINE_bool', 'tf.flags.DEFINE_bool', (['"""is_prioritized_replay"""', '(False)', '"""True to prioritize the replay of difficult experiences."""'], {}), "('is_prioritized_replay', False,\n 'True to prioritize the replay of difficult experiences.')\n", (7955, 8050), True, 'import tensorflow as tf\n'), ((8048, 8157), 'tensorflow.flags.DEFINE_bool', 'tf.flags.DEFINE_bool', (['"""is_biased_prioritized_replay"""', '(False)', '"""Priority sampling without bias correction."""'], {}), "('is_biased_prioritized_replay', False,\n 'Priority sampling without bias correction.')\n", (8068, 8157), True, 'import tensorflow as tf\n'), ((8157, 8278), 'tensorflow.flags.DEFINE_bool', 'tf.flags.DEFINE_bool', (['"""is_relative_to_spirals"""', '(False)', '"""True to compare generator losses against losses for spirals."""'], {}), "('is_relative_to_spirals', False,\n 'True to compare generator losses against losses for spirals.')\n", (8177, 8278), True, 'import tensorflow as tf\n'), ((8278, 8396), 'tensorflow.flags.DEFINE_bool', 'tf.flags.DEFINE_bool', (['"""is_self_competition"""', '(True)', '"""Oh it is on. True to compete against past versions of itself."""'], {}), "('is_self_competition', True,\n 'Oh it is on. True to compete against past versions of itself.')\n", (8298, 8396), True, 'import tensorflow as tf\n'), ((8396, 8539), 'tensorflow.flags.DEFINE_float', 'tf.flags.DEFINE_float', (['"""norm_generator_losses_decay"""', '(0.0)', '"""Divide generator losses by their running mean. Zero for no normalization."""'], {}), "('norm_generator_losses_decay', 0.0,\n 'Divide generator losses by their running mean. Zero for no normalization.'\n )\n", (8417, 8539), True, 'import tensorflow as tf\n'), ((8531, 8621), 'tensorflow.flags.DEFINE_float', 'tf.flags.DEFINE_float', (['"""replay_decay"""', '(0.999)', '"""Decay rates to calculate loss moments."""'], {}), "('replay_decay', 0.999,\n 'Decay rates to calculate loss moments.')\n", (8552, 8621), True, 'import tensorflow as tf\n'), ((8621, 8718), 'tensorflow.flags.DEFINE_bool', 'tf.flags.DEFINE_bool', (['"""is_minmax_reward"""', '(False)', '"""True to use highest losses for actor loss."""'], {}), "('is_minmax_reward', False,\n 'True to use highest losses for actor loss.')\n", (8641, 8718), True, 'import tensorflow as tf\n'), ((8718, 8780), 'tensorflow.flags.DEFINE_integer', 'tf.flags.DEFINE_integer', (['"""start_iter"""', '(0)', '"""Starting iteration"""'], {}), "('start_iter', 0, 'Starting iteration')\n", (8741, 8780), True, 'import tensorflow as tf\n'), ((8782, 8852), 'tensorflow.flags.DEFINE_integer', 'tf.flags.DEFINE_integer', (['"""train_iters"""', '(1000000)', '"""Training iterations"""'], {}), "('train_iters', 1000000, 'Training iterations')\n", (8805, 8852), True, 'import tensorflow as tf\n'), ((8856, 8935), 'tensorflow.flags.DEFINE_integer', 'tf.flags.DEFINE_integer', (['"""val_examples"""', '(20000)', '"""Number of validation examples"""'], {}), "('val_examples', 20000, 'Number of validation examples')\n", (8879, 8935), True, 'import tensorflow as tf\n'), ((8940, 9036), 'tensorflow.flags.DEFINE_float', 'tf.flags.DEFINE_float', (['"""style_loss"""', '(0.0)', '"""Weighting of style loss. Zero for no style loss."""'], {}), "('style_loss', 0.0,\n 'Weighting of style loss. Zero for no style loss.')\n", (8961, 9036), True, 'import tensorflow as tf\n'), ((9033, 9120), 'tensorflow.flags.DEFINE_float', 'tf.flags.DEFINE_float', (['"""spike_loss"""', '(0.0)', '"""Penalize critic for spikey predictions."""'], {}), "('spike_loss', 0.0,\n 'Penalize critic for spikey predictions.')\n", (9054, 9120), True, 'import tensorflow as tf\n'), ((9199, 9380), 'tensorflow.flags.DEFINE_string', 'tf.flags.DEFINE_string', (['"""model_dir"""', 'f"""//ads.warwick.ac.uk/shared/HCSS6/Shared305/Microscopy/Jeffrey-Ede/models/recurrent_conv-1/{experiment_number}/"""', '"""Working directory."""'], {}), "('model_dir',\n f'//ads.warwick.ac.uk/shared/HCSS6/Shared305/Microscopy/Jeffrey-Ede/models/recurrent_conv-1/{experiment_number}/'\n , 'Working directory.')\n", (9221, 9380), True, 'import tensorflow as tf\n'), ((9423, 9569), 'tensorflow.flags.DEFINE_string', 'tf.flags.DEFINE_string', (['"""data_file"""', '"""//Desktop-sa1evjv/h/96x96_stem_crops.npy"""', '"""Datafile containing 19769 96x96 downsampled STEM crops."""'], {}), "('data_file',\n '//Desktop-sa1evjv/h/96x96_stem_crops.npy',\n 'Datafile containing 19769 96x96 downsampled STEM crops.')\n", (9445, 9569), True, 'import tensorflow as tf\n'), ((9613, 9704), 'tensorflow.flags.DEFINE_integer', 'tf.flags.DEFINE_integer', (['"""report_freq"""', '(10)', '"""How often to print losses to the console."""'], {}), "('report_freq', 10,\n 'How often to print losses to the console.')\n", (9636, 9704), True, 'import tensorflow as tf\n'), ((9706, 9731), 'os.chdir', 'os.chdir', (['FLAGS.model_dir'], {}), '(FLAGS.model_dir)\n', (9714, 9731), False, 'import os, sys\n'), ((9733, 9768), 'sys.path.insert', 'sys.path.insert', (['(0)', 'FLAGS.model_dir'], {}), '(0, FLAGS.model_dir)\n', (9748, 9768), False, 'import os, sys\n'), ((5819, 5913), 'tensorflow.flags.DEFINE_float', 'tf.flags.DEFINE_float', (['"""supervision"""', '(0.5)', '"""Weighting for known discounted future reward."""'], {}), "('supervision', 0.5,\n 'Weighting for known discounted future reward.')\n", (5840, 5913), True, 'import tensorflow as tf\n'), ((5946, 6040), 'tensorflow.flags.DEFINE_float', 'tf.flags.DEFINE_float', (['"""supervision"""', '(0.0)', '"""Weighting for known discounted future reward."""'], {}), "('supervision', 0.0,\n 'Weighting for known discounted future reward.')\n", (5967, 6040), True, 'import tensorflow as tf\n'), ((9154, 9164), 'numpy.sqrt', 'np.sqrt', (['(2)'], {}), '(2)\n', (9161, 9164), True, 'import numpy as np\n'), ((9808, 9848), 'tensorflow.reduce_mean', 'tf.reduce_mean', (['x'], {'axis': '(0)', 'keepdims': '(True)'}), '(x, axis=0, keepdims=True)\n', (9822, 9848), True, 'import tensorflow as tf\n'), ((10521, 10543), 'tensorflow.python.ops.array_ops.shape', 'array_ops.shape', (['image'], {}), '(image)\n', (10536, 10543), False, 'from tensorflow.python.ops import array_ops\n'), ((10749, 10776), 'numpy.expand_dims', 'np.expand_dims', (['kernels', '(-2)'], {}), '(kernels, -2)\n', (10763, 10776), True, 'import numpy as np\n'), ((10793, 10841), 'tensorflow.python.framework.constant_op.constant', 'constant_op.constant', (['kernels'], {'dtype': 'image.dtype'}), '(kernels, dtype=image.dtype)\n', (10813, 10841), False, 'from tensorflow.python.framework import constant_op\n'), ((10860, 10936), 'tensorflow.python.ops.array_ops.tile', 'array_ops.tile', (['kernels_tf', '[1, 1, image_shape[-1], 1]'], {'name': '"""sobel_filters"""'}), "(kernels_tf, [1, 1, image_shape[-1], 1], name='sobel_filters')\n", (10874, 10936), False, 'from tensorflow.python.ops import array_ops\n'), ((11075, 11122), 'tensorflow.python.ops.array_ops.pad', 'array_ops.pad', (['image', 'pad_sizes'], {'mode': '"""REFLECT"""'}), "(image, pad_sizes, mode='REFLECT')\n", (11088, 11122), False, 'from tensorflow.python.ops import array_ops\n'), ((11229, 11286), 'tensorflow.python.ops.nn.depthwise_conv2d', 'nn.depthwise_conv2d', (['padded', 'kernels_tf', 'strides', '"""VALID"""'], {}), "(padded, kernels_tf, strides, 'VALID')\n", (11248, 11286), False, 'from tensorflow.python.ops import nn\n'), ((11352, 11401), 'tensorflow.python.ops.array_ops.concat', 'array_ops.concat', (['[image_shape, [num_kernels]]', '(0)'], {}), '([image_shape, [num_kernels]], 0)\n', (11368, 11401), False, 'from tensorflow.python.ops import array_ops\n'), ((11414, 11452), 'tensorflow.python.ops.array_ops.reshape', 'array_ops.reshape', (['output'], {'shape': 'shape'}), '(output, shape=shape)\n', (11431, 11452), False, 'from tensorflow.python.ops import array_ops\n'), ((12105, 12116), 'numpy.min', 'np.min', (['img'], {}), '(img)\n', (12111, 12116), True, 'import numpy as np\n'), ((12128, 12139), 'numpy.max', 'np.max', (['img'], {}), '(img)\n', (12134, 12139), True, 'import numpy as np\n'), ((12379, 12426), 'cv2.namedWindow', 'cv2.namedWindow', (['"""CV_Window"""', 'cv2.WINDOW_NORMAL'], {}), "('CV_Window', cv2.WINDOW_NORMAL)\n", (12394, 12426), False, 'import cv2\n'), ((12477, 12491), 'cv2.waitKey', 'cv2.waitKey', (['(0)'], {}), '(0)\n', (12488, 12491), False, 'import cv2\n'), ((12950, 13016), 'dnc.dnc.DNC', 'dnc.DNC', (['access_config', 'controller_config', 'output_size', 'clip_value'], {}), '(access_config, controller_config, output_size, clip_value)\n', (12957, 13016), False, 'from dnc import dnc\n'), ((13101, 13206), 'tensorflow.nn.dynamic_rnn', 'tf.nn.dynamic_rnn', ([], {'cell': 'dnc_core', 'inputs': 'input_sequence', 'time_major': '(True)', 'initial_state': 'initial_state'}), '(cell=dnc_core, inputs=input_sequence, time_major=True,\n initial_state=initial_state)\n', (13118, 13206), True, 'import tensorflow as tf\n'), ((25588, 25620), 'tensorflow.reshape', 'tf.reshape', (['w', '[-1, w_shape[-1]]'], {}), '(w, [-1, w_shape[-1]])\n', (25598, 25620), True, 'import tensorflow as tf\n'), ((26182, 26205), 'tensorflow.stop_gradient', 'tf.stop_gradient', (['u_hat'], {}), '(u_hat)\n', (26198, 26205), True, 'import tensorflow as tf\n'), ((26219, 26242), 'tensorflow.stop_gradient', 'tf.stop_gradient', (['v_hat'], {}), '(v_hat)\n', (26235, 26242), True, 'import tensorflow as tf\n'), ((26933, 26955), 'tensorflow.zeros_initializer', 'tf.zeros_initializer', ([], {}), '()\n', (26953, 26955), True, 'import tensorflow as tf\n'), ((39850, 39867), 'numpy.array', 'np.array', (['indices'], {}), '(indices)\n', (39858, 39867), True, 'import numpy as np\n'), ((39946, 40032), 'numpy.zeros', 'np.zeros', (['[FLAGS.batch_size // FLAGS.avg_replays, FLAGS.img_side, FLAGS.img_side]'], {}), '([FLAGS.batch_size // FLAGS.avg_replays, FLAGS.img_side, FLAGS.\n img_side])\n', (39954, 40032), True, 'import numpy as np\n'), ((40041, 40127), 'numpy.zeros', 'np.zeros', (['[FLAGS.batch_size // FLAGS.avg_replays, FLAGS.img_side, FLAGS.img_side]'], {}), '([FLAGS.batch_size // FLAGS.avg_replays, FLAGS.img_side, FLAGS.\n img_side])\n', (40049, 40127), True, 'import numpy as np\n'), ((40234, 40254), 'numpy.maximum', 'np.maximum', (['masks', '(1)'], {}), '(masks, 1)\n', (40244, 40254), True, 'import numpy as np\n'), ((40268, 40288), 'numpy.minimum', 'np.minimum', (['masks', '(1)'], {}), '(masks, 1)\n', (40278, 40288), True, 'import numpy as np\n'), ((40312, 40353), 'numpy.stack', 'np.stack', (['[partial_scans, masks]'], {'axis': '(-1)'}), '([partial_scans, masks], axis=-1)\n', (40320, 40353), True, 'import numpy as np\n'), ((41476, 41523), 'cv2.GaussianBlur', 'cv2.GaussianBlur', (['image', '(5, 5)', '(2.5)', 'None', '(2.5)'], {}), '(image, (5, 5), 2.5, None, 2.5)\n', (41492, 41523), False, 'import cv2\n'), ((44654, 44700), 'numpy.arange', 'np.arange', (['(0)', 'theta_max', '(theta_max / num_steps)'], {}), '(0, theta_max, theta_max / num_steps)\n', (44663, 44700), True, 'import numpy as np\n'), ((44873, 44916), 'numpy.empty', 'np.empty', (['(x.size + y.size,)'], {'dtype': 'x.dtype'}), '((x.size + y.size,), dtype=x.dtype)\n', (44881, 44916), True, 'import numpy as np\n'), ((44983, 45020), 'PIL.Image.new', 'Image.new', (['"""F"""', '(size, size)', '"""black"""'], {}), "('F', (size, size), 'black')\n", (44992, 45020), False, 'from PIL import Image\n'), ((45106, 45121), 'numpy.asarray', 'np.asarray', (['img'], {}), '(img)\n', (45116, 45121), True, 'import numpy as np\n'), ((45299, 45320), 'tensorflow.ones', 'tf.ones', (['[5, 5, 1, 1]'], {}), '([5, 5, 1, 1])\n', (45306, 45320), True, 'import tensorflow as tf\n'), ((45340, 45406), 'tensorflow.nn.conv2d', 'tf.nn.conv2d', (['image', 'kernel'], {'strides': '[1, 1, 1, 1]', 'padding': '"""VALID"""'}), "(image, kernel, strides=[1, 1, 1, 1], padding='VALID')\n", (45352, 45406), True, 'import tensorflow as tf\n'), ((45524, 45610), 'tensorflow.constant', 'tf.constant', (['[[0, 0], [d1_pad, d1_pad], [d2_pad, d2_pad], [0, 0]]'], {'dtype': 'tf.int32'}), '([[0, 0], [d1_pad, d1_pad], [d2_pad, d2_pad], [0, 0]], dtype=tf.\n int32)\n', (45535, 45610), True, 'import tensorflow as tf\n'), ((45620, 45660), 'tensorflow.pad', 'tf.pad', (['tensor', 'paddings'], {'mode': '"""REFLECT"""'}), "(tensor, paddings, mode='REFLECT')\n", (45626, 45660), True, 'import tensorflow as tf\n'), ((45857, 45891), 'tensorflow.distributions.Normal', 'tf.distributions.Normal', (['mean', 'std'], {}), '(mean, std)\n', (45880, 45891), True, 'import tensorflow as tf\n'), ((45998, 46030), 'tensorflow.einsum', 'tf.einsum', (['"""i,j->ij"""', 'vals', 'vals'], {}), "('i,j->ij', vals, vals)\n", (46007, 46030), True, 'import tensorflow as tf\n'), ((46421, 46493), 'tensorflow.nn.conv2d', 'tf.nn.conv2d', (['image', 'gauss_kernel'], {'strides': '[1, 1, 1, 1]', 'padding': '"""VALID"""'}), "(image, gauss_kernel, strides=[1, 1, 1, 1], padding='VALID')\n", (46433, 46493), True, 'import tensorflow as tf\n'), ((49252, 49295), 'tensorflow.reduce_mean', 'tf.reduce_mean', (['loss'], {'axis': '(0)', 'keepdims': '(True)'}), '(loss, axis=0, keepdims=True)\n', (49266, 49295), True, 'import tensorflow as tf\n'), ((49931, 49972), 'numpy.linspace', 'np.linspace', (['min_val', 'max_val', 'num_points'], {}), '(min_val, max_val, num_points)\n', (49942, 49972), True, 'import numpy as np\n'), ((50491, 50521), 'tensorflow.reduce_sum', 'tf.reduce_sum', (['density'], {'axis': '(0)'}), '(density, axis=0)\n', (50504, 50521), True, 'import tensorflow as tf\n'), ((50760, 50779), 'numpy.sqrt', 'np.sqrt', (['num_points'], {}), '(num_points)\n', (50767, 50779), True, 'import numpy as np\n'), ((51358, 51380), 'tensorflow.get_default_graph', 'tf.get_default_graph', ([], {}), '()\n', (51378, 51380), True, 'import tensorflow as tf\n'), ((51751, 51775), 'numpy.load', 'np.load', (['FLAGS.data_file'], {}), '(FLAGS.data_file)\n', (51758, 51775), True, 'import numpy as np\n'), ((53027, 53095), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32'], {'shape': 'action_shape', 'name': '"""replay_action"""'}), "(tf.float32, shape=action_shape, name='replay_action')\n", (53041, 53095), True, 'import tensorflow as tf\n'), ((53126, 53204), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32'], {'shape': 'observation_shape', 'name': '"""replay_observation"""'}), "(tf.float32, shape=observation_shape, name='replay_observation')\n", (53140, 53204), True, 'import tensorflow as tf\n'), ((53235, 53309), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32'], {'shape': 'full_scan_shape', 'name': '"""replay_full_scan"""'}), "(tf.float32, shape=full_scan_shape, name='replay_full_scan')\n", (53249, 53309), True, 'import tensorflow as tf\n'), ((53334, 53419), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32'], {'shape': 'partial_scan_shape', 'name': '"""replay_partial_scan"""'}), "(tf.float32, shape=partial_scan_shape, name='replay_partial_scan'\n )\n", (53348, 53419), True, 'import tensorflow as tf\n'), ((53439, 53482), 'tensorflow.placeholder', 'tf.placeholder', (['tf.bool'], {'name': '"""is_training"""'}), "(tf.bool, name='is_training')\n", (53453, 53482), True, 'import tensorflow as tf\n'), ((53778, 53825), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32'], {'name': '"""target_decay"""'}), "(tf.float32, name='target_decay')\n", (53792, 53825), True, 'import tensorflow as tf\n'), ((56155, 56216), 'tensorflow.concat', 'tf.concat', (['[start_actions, replay_actions[:, :-1, :]]'], {'axis': '(1)'}), '([start_actions, replay_actions[:, :-1, :]], axis=1)\n', (56164, 56216), True, 'import tensorflow as tf\n'), ((56897, 56942), 'tensorflow.concat', 'tf.concat', (['[replay_actions, actions]'], {'axis': '(-1)'}), '([replay_actions, actions], axis=-1)\n', (56906, 56942), True, 'import tensorflow as tf\n'), ((69980, 69996), 'tensorflow.ConfigProto', 'tf.ConfigProto', ([], {}), '()\n', (69994, 69996), True, 'import tensorflow as tf\n'), ((84234, 84246), 'tensorflow.app.run', 'tf.app.run', ([], {}), '()\n', (84244, 84246), True, 'import tensorflow as tf\n'), ((9858, 9876), 'numpy.sqrt', 'np.sqrt', (['(np.pi / 2)'], {}), '(np.pi / 2)\n', (9865, 9876), True, 'import numpy as np\n'), ((10704, 10723), 'numpy.asarray', 'np.asarray', (['kernels'], {}), '(kernels)\n', (10714, 10723), True, 'import numpy as np\n'), ((11646, 11657), 'numpy.min', 'np.min', (['img'], {}), '(img)\n', (11652, 11657), True, 'import numpy as np\n'), ((11694, 11705), 'numpy.max', 'np.max', (['img'], {}), '(img)\n', (11700, 11705), True, 'import numpy as np\n'), ((11716, 11738), 'numpy.absolute', 'np.absolute', (['(min - max)'], {}), '(min - max)\n', (11727, 11738), True, 'import numpy as np\n'), ((12150, 12172), 'numpy.absolute', 'np.absolute', (['(min - max)'], {}), '(min - max)\n', (12161, 12172), True, 'import numpy as np\n'), ((18622, 18670), 'numpy.stack', 'np.stack', (['[self.actions[i] for i in sample_idxs]'], {}), '([self.actions[i] for i in sample_idxs])\n', (18630, 18670), True, 'import numpy as np\n'), ((18703, 18756), 'numpy.stack', 'np.stack', (['[self.observations[i] for i in sample_idxs]'], {}), '([self.observations[i] for i in sample_idxs])\n', (18711, 18756), True, 'import numpy as np\n'), ((18787, 18838), 'numpy.stack', 'np.stack', (['[self.full_scans[i] for i in sample_idxs]'], {}), '([self.full_scans[i] for i in sample_idxs])\n', (18795, 18838), True, 'import numpy as np\n'), ((22246, 22281), 'tensorflow.tile', 'tf.tile', (['actions', '[1, 1, num_tiles]'], {}), '(actions, [1, 1, num_tiles])\n', (22253, 22281), True, 'import tensorflow as tf\n'), ((22308, 22357), 'tensorflow.concat', 'tf.concat', (['[observations, tiled_actions]'], {'axis': '(-1)'}), '([observations, tiled_actions], axis=-1)\n', (22317, 22357), True, 'import tensorflow as tf\n'), ((22429, 22548), 'tensorflow.nn.dynamic_rnn', 'tf.nn.dynamic_rnn', ([], {'cell': 'self._dnc_core', 'inputs': 'input_sequence', 'time_major': '(False)', 'initial_state': 'self._initial_state'}), '(cell=self._dnc_core, inputs=input_sequence, time_major=\n False, initial_state=self._initial_state)\n', (22446, 22548), True, 'import tensorflow as tf\n'), ((25650, 25664), 'utility.auto_name', 'auto_name', (['"""u"""'], {}), "('u')\n", (25659, 25664), False, 'from utility import alrc, auto_name\n'), ((26068, 26090), 'tensorflow.nn.l2_normalize', 'tf.nn.l2_normalize', (['v_'], {}), '(v_)\n', (26086, 26090), True, 'import tensorflow as tf\n'), ((26107, 26126), 'tensorflow.matmul', 'tf.matmul', (['v_hat', 'w'], {}), '(v_hat, w)\n', (26116, 26126), True, 'import tensorflow as tf\n'), ((26144, 26166), 'tensorflow.nn.l2_normalize', 'tf.nn.l2_normalize', (['u_'], {}), '(u_)\n', (26162, 26166), True, 'import tensorflow as tf\n'), ((26268, 26287), 'tensorflow.matmul', 'tf.matmul', (['v_hat', 'w'], {}), '(v_hat, w)\n', (26277, 26287), True, 'import tensorflow as tf\n'), ((26289, 26308), 'tensorflow.transpose', 'tf.transpose', (['u_hat'], {}), '(u_hat)\n', (26301, 26308), True, 'import tensorflow as tf\n'), ((26740, 26767), 'tensorflow.reshape', 'tf.reshape', (['w_norm', 'w_shape'], {}), '(w_norm, w_shape)\n', (26750, 26767), True, 'import tensorflow as tf\n'), ((27062, 27081), 'utility.auto_name', 'auto_name', (['"""kernel"""'], {}), "('kernel')\n", (27071, 27081), False, 'from utility import alrc, auto_name\n'), ((27438, 27458), 'tensorflow.nn.bias_add', 'tf.nn.bias_add', (['x', 'b'], {}), '(x, b)\n', (27452, 27458), True, 'import tensorflow as tf\n'), ((32927, 32983), 'tensorflow.contrib.layers.batch_norm', 'tf.contrib.layers.batch_norm', (['x'], {'is_training': 'is_training'}), '(x, is_training=is_training)\n', (32955, 32983), True, 'import tensorflow as tf\n'), ((34435, 34491), 'tensorflow.contrib.layers.batch_norm', 'tf.contrib.layers.batch_norm', (['x'], {'is_training': 'is_training'}), '(x, is_training=is_training)\n', (34463, 34491), True, 'import tensorflow as tf\n'), ((35365, 35385), 'tensorflow.layers.flatten', 'tf.layers.flatten', (['x'], {}), '(x)\n', (35382, 35385), True, 'import tensorflow as tf\n'), ((35399, 35420), 'tensorflow.layers.dense', 'tf.layers.dense', (['x', '(1)'], {}), '(x, 1)\n', (35414, 35420), True, 'import tensorflow as tf\n'), ((35434, 35490), 'tensorflow.contrib.layers.batch_norm', 'tf.contrib.layers.batch_norm', (['x'], {'is_training': 'is_training'}), '(x, is_training=is_training)\n', (35462, 35490), True, 'import tensorflow as tf\n'), ((39550, 39574), 'numpy.maximum', 'np.maximum', (['positions', '(0)'], {}), '(positions, 0)\n', (39560, 39574), True, 'import numpy as np\n'), ((41438, 41461), 'numpy.random.randint', 'np.random.randint', (['(0)', '(8)'], {}), '(0, 8)\n', (41455, 41461), True, 'import numpy as np\n'), ((41935, 41968), 'tensorflow.data.Dataset.zip', 'tf.data.Dataset.zip', (['(ds, labels)'], {}), '((ds, labels))\n', (41954, 41968), True, 'import tensorflow as tf\n'), ((45913, 45968), 'tensorflow.range', 'tf.range', ([], {'start': '(-size)', 'limit': '(size + 1)', 'dtype': 'tf.float32'}), '(start=-size, limit=size + 1, dtype=tf.float32)\n', (45921, 45968), True, 'import tensorflow as tf\n'), ((46060, 46087), 'tensorflow.reduce_sum', 'tf.reduce_sum', (['gauss_kernel'], {}), '(gauss_kernel)\n', (46073, 46087), True, 'import tensorflow as tf\n'), ((46769, 46819), 'tensorflow.reduce_mean', 'tf.reduce_mean', (['((img1 - img2) ** 2)'], {'axis': '[1, 2, 3]'}), '((img1 - img2) ** 2, axis=[1, 2, 3])\n', (46783, 46819), True, 'import tensorflow as tf\n'), ((47888, 47916), 'numpy.stack', 'np.stack', (['sampled_full_scans'], {}), '(sampled_full_scans)\n', (47896, 47916), True, 'import numpy as np\n'), ((47944, 47967), 'numpy.stack', 'np.stack', (['partial_scans'], {}), '(partial_scans)\n', (47952, 47967), True, 'import numpy as np\n'), ((48306, 48323), 'tensorflow.reduce_mean', 'tf.reduce_mean', (['x'], {}), '(x)\n', (48320, 48323), True, 'import tensorflow as tf\n'), ((49317, 49339), 'tensorflow.stop_gradient', 'tf.stop_gradient', (['mean'], {}), '(mean)\n', (49333, 49339), True, 'import tensorflow as tf\n'), ((49386, 49408), 'tensorflow.reduce_mean', 'tf.reduce_mean', (['(x ** 2)'], {}), '(x ** 2)\n', (49400, 49408), True, 'import tensorflow as tf\n'), ((49440, 49460), 'utility.auto_name', 'auto_name', (['"""avg_rms"""'], {}), "('avg_rms')\n", (49449, 49460), False, 'from utility import alrc, auto_name\n'), ((49580, 49616), 'tensorflow.control_dependencies', 'tf.control_dependencies', (['[update_op]'], {}), '([update_op])\n', (49603, 49616), True, 'import tensorflow as tf\n'), ((49634, 49662), 'tensorflow.tanh', 'tf.tanh', (['(x / (clip * avg_mu))'], {}), '(x / (clip * avg_mu))\n', (49641, 49662), True, 'import tensorflow as tf\n'), ((50049, 50086), 'scipy.stats.norm.cdf', 'norm.cdf', (['((np.pi + np_points) / sigma)'], {}), '((np.pi + np_points) / sigma)\n', (50057, 50086), False, 'from scipy.stats import norm\n'), ((50087, 50124), 'scipy.stats.norm.cdf', 'norm.cdf', (['((np.pi - np_points) / sigma)'], {}), '((np.pi - np_points) / sigma)\n', (50095, 50124), False, 'from scipy.stats import norm\n'), ((50382, 50396), 'tensorflow.exp', 'tf.exp', (['(-dists)'], {}), '(-dists)\n', (50388, 50396), True, 'import tensorflow as tf\n'), ((50640, 50686), 'tensorflow.reduce_sum', 'tf.reduce_sum', (['density'], {'axis': '(-1)', 'keepdims': '(True)'}), '(density, axis=-1, keepdims=True)\n', (50653, 50686), True, 'import tensorflow as tf\n'), ((50712, 50744), 'tensorflow.reduce_sum', 'tf.reduce_sum', (['(pdf ** 2)'], {'axis': '(-1)'}), '(pdf ** 2, axis=-1)\n', (50725, 50744), True, 'import tensorflow as tf\n'), ((51129, 51175), 'tensorflow.clip_by_value', 'tf.clip_by_value', (['g', '(-limit * rms)', '(limit * rms)'], {}), '(g, -limit * rms, limit * rms)\n', (51145, 51175), True, 'import tensorflow as tf\n'), ((52452, 52496), 'tensorflow.ensure_shape', 'tf.ensure_shape', (['full_scans', 'full_scan_shape'], {}), '(full_scans, full_scan_shape)\n', (52467, 52496), True, 'import tensorflow as tf\n'), ((52523, 52571), 'tensorflow.ensure_shape', 'tf.ensure_shape', (['val_full_scans', 'full_scan_shape'], {}), '(val_full_scans, full_scan_shape)\n', (52538, 52571), True, 'import tensorflow as tf\n'), ((52605, 52644), 'tensorflow.reshape', 'tf.reshape', (['full_scans', 'full_scan_shape'], {}), '(full_scans, full_scan_shape)\n', (52615, 52644), True, 'import tensorflow as tf\n'), ((52671, 52710), 'tensorflow.reshape', 'tf.reshape', (['full_scans', 'full_scan_shape'], {}), '(full_scans, full_scan_shape)\n', (52681, 52710), True, 'import tensorflow as tf\n'), ((53550, 53602), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32'], {'name': '"""over_edge_penalty"""'}), "(tf.float32, name='over_edge_penalty')\n", (53564, 53602), True, 'import tensorflow as tf\n'), ((53661, 53717), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32'], {'shape': '()', 'name': '"""noise_decay"""'}), "(tf.float32, shape=(), name='noise_decay')\n", (53675, 53717), True, 'import tensorflow as tf\n'), ((53887, 53933), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32'], {'name': '"""supervision"""'}), "(tf.float32, name='supervision')\n", (53901, 53933), True, 'import tensorflow as tf\n'), ((54059, 54136), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32'], {'shape': '[FLAGS.batch_size]', 'name': '"""priority_weights"""'}), "(tf.float32, shape=[FLAGS.batch_size], name='priority_weights')\n", (54073, 54136), True, 'import tensorflow as tf\n'), ((57194, 57246), 'tensorflow.concat', 'tf.concat', (['[replay_actions, target_actions]'], {'axis': '(-1)'}), '([replay_actions, target_actions], axis=-1)\n', (57203, 57246), True, 'import tensorflow as tf\n'), ((57487, 57520), 'tensorflow.stop_gradient', 'tf.stop_gradient', (['target_actor_qs'], {}), '(target_actor_qs)\n', (57503, 57520), True, 'import tensorflow as tf\n'), ((58882, 58930), 'tensorflow.py_func', 'tf.py_func', (['fill', '[partial_scans_ph]', 'tf.float32'], {}), '(fill, [partial_scans_ph], tf.float32)\n', (58892, 58930), True, 'import tensorflow as tf\n'), ((59361, 59373), 'utility.alrc', 'alrc', (['losses'], {}), '(losses)\n', (59365, 59373), False, 'from utility import alrc, auto_name\n'), ((59886, 59925), 'tensorflow.reduce_mean', 'tf.reduce_mean', (['((blurred_path - 1) ** 2)'], {}), '((blurred_path - 1) ** 2)\n', (59900, 59925), True, 'import tensorflow as tf\n'), ((61193, 61280), 'tensorflow.stack', 'tf.stack', (['[replay_full_scans_ph[:, :, :, 0], partial_scans_ph[:, :, :, 1]]'], {'axis': '(-1)'}), '([replay_full_scans_ph[:, :, :, 0], partial_scans_ph[:, :, :, 1]],\n axis=-1)\n', (61201, 61280), True, 'import tensorflow as tf\n'), ((61299, 61384), 'tensorflow.concat', 'tf.concat', (['[partial_scans_ph[1:, :, :, 1], partial_scans_ph[:1, :, :, 1]]'], {'axis': '(0)'}), '([partial_scans_ph[1:, :, :, 1], partial_scans_ph[:1, :, :, 1]],\n axis=0)\n', (61308, 61384), True, 'import tensorflow as tf\n'), ((61395, 61464), 'tensorflow.stack', 'tf.stack', (['[replay_full_scans_ph[:, :, :, 0], permuted_paths]'], {'axis': '(-1)'}), '([replay_full_scans_ph[:, :, :, 0], permuted_paths], axis=-1)\n', (61403, 61464), True, 'import tensorflow as tf\n'), ((61490, 61528), 'tensorflow.concat', 'tf.concat', (['[true_ps, false_ps]'], {'axis': '(0)'}), '([true_ps, false_ps], axis=0)\n', (61499, 61528), True, 'import tensorflow as tf\n'), ((62767, 62826), 'tensorflow.logical_or', 'tf.logical_or', (['is_over_edge[:, :, 0]', 'is_over_edge[:, :, 1]'], {}), '(is_over_edge[:, :, 0], is_over_edge[:, :, 1])\n', (62780, 62826), True, 'import tensorflow as tf\n'), ((63050, 63090), 'tensorflow.reduce_sum', 'tf.reduce_sum', (['over_edge_losses'], {'axis': '(-1)'}), '(over_edge_losses, axis=-1)\n', (63063, 63090), True, 'import tensorflow as tf\n'), ((64591, 64650), 'tensorflow.logical_or', 'tf.logical_or', (['is_over_edge[:, :, 0]', 'is_over_edge[:, :, 1]'], {}), '(is_over_edge[:, :, 0], is_over_edge[:, :, 1])\n', (64604, 64650), True, 'import tensorflow as tf\n'), ((65454, 65491), 'tensorflow.concat', 'tf.concat', (['supervised_losses'], {'axis': '(-1)'}), '(supervised_losses, axis=-1)\n', (65463, 65491), True, 'import tensorflow as tf\n'), ((66158, 66225), 'tensorflow.reduce_mean', 'tf.reduce_mean', (['((critic_qs[:, :, 0] - bellman_losses) ** 2)'], {'axis': '(-1)'}), '((critic_qs[:, :, 0] - bellman_losses) ** 2, axis=-1)\n', (66172, 66225), True, 'import tensorflow as tf\n'), ((66251, 66313), 'tensorflow.reduce_mean', 'tf.reduce_mean', (['(priority_weights_ph * unweighted_critic_losses)'], {}), '(priority_weights_ph * unweighted_critic_losses)\n', (66265, 66313), True, 'import tensorflow as tf\n'), ((66841, 66870), 'tensorflow.reduce_mean', 'tf.reduce_mean', (['critic_losses'], {}), '(critic_losses)\n', (66855, 66870), True, 'import tensorflow as tf\n'), ((67457, 67510), 'tensorflow.reduce_mean', 'tf.reduce_mean', (['(supervised_losses - actor_qs[:, :, 0])'], {}), '(supervised_losses - actor_qs[:, :, 0])\n', (67471, 67510), True, 'import tensorflow as tf\n'), ((68214, 68242), 'tensorflow.reduce_mean', 'tf.reduce_mean', (['actor_losses'], {}), '(actor_losses)\n', (68228, 68242), True, 'import tensorflow as tf\n'), ((68918, 68950), 'tensorflow.reduce_mean', 'tf.reduce_mean', (['unclipped_losses'], {}), '(unclipped_losses)\n', (68932, 68950), True, 'import tensorflow as tf\n'), ((70295, 70320), 'tensorflow.Session', 'tf.Session', ([], {'config': 'config'}), '(config=config)\n', (70305, 70320), True, 'import tensorflow as tf\n'), ((73092, 73134), 'tensorflow.get_collection', 'tf.get_collection', (['tf.GraphKeys.UPDATE_OPS'], {}), '(tf.GraphKeys.UPDATE_OPS)\n', (73109, 73134), True, 'import tensorflow as tf\n'), ((77154, 77183), 'tensorflow.train.Saver', 'tf.train.Saver', ([], {'max_to_keep': '(1)'}), '(max_to_keep=1)\n', (77168, 77183), True, 'import tensorflow as tf\n'), ((77210, 77239), 'tensorflow.train.Saver', 'tf.train.Saver', ([], {'max_to_keep': '(2)'}), '(max_to_keep=2)\n', (77224, 77239), True, 'import tensorflow as tf\n'), ((77889, 77900), 'time.time', 'time.time', ([], {}), '()\n', (77898, 77900), False, 'import time\n'), ((84151, 84200), 'numpy.save', 'np.save', (["(model_dir + 'val_losses.npy')", 'val_losses'], {}), "(model_dir + 'val_losses.npy', val_losses)\n", (84158, 84200), True, 'import numpy as np\n'), ((9890, 9904), 'tensorflow.abs', 'tf.abs', (['(x - mu)'], {}), '(x - mu)\n', (9896, 9904), True, 'import tensorflow as tf\n'), ((13300, 13310), 'numpy.exp', 'np.exp', (['(-x)'], {}), '(-x)\n', (13306, 13310), True, 'import numpy as np\n'), ((14066, 14089), 'numpy.zeros', 'np.zeros', (['[buffer_size]'], {}), '([buffer_size])\n', (14074, 14089), True, 'import numpy as np\n'), ((14121, 14143), 'numpy.ones', 'np.ones', (['[buffer_size]'], {}), '([buffer_size])\n', (14128, 14143), True, 'import numpy as np\n'), ((14172, 14194), 'numpy.arange', 'np.arange', (['buffer_size'], {}), '(buffer_size)\n', (14181, 14194), True, 'import numpy as np\n'), ((14357, 14398), 'numpy.sqrt', 'np.sqrt', (['(self.mu2 - self.mu1 ** 2 + 0.001)'], {}), '(self.mu2 - self.mu1 ** 2 + 0.001)\n', (14364, 14398), True, 'import numpy as np\n'), ((14485, 14530), 'numpy.sqrt', 'np.sqrt', (['(self.d_mu2 - self.d_mu1 ** 2 + 0.001)'], {}), '(self.d_mu2 - self.d_mu1 ** 2 + 0.001)\n', (14492, 14530), True, 'import numpy as np\n'), ((14563, 14590), 'numpy.zeros', 'np.zeros', (['[num_past_losses]'], {}), '([num_past_losses])\n', (14571, 14590), True, 'import numpy as np\n'), ((14623, 14650), 'numpy.zeros', 'np.zeros', (['[num_past_losses]'], {}), '([num_past_losses])\n', (14631, 14650), True, 'import numpy as np\n'), ((14678, 14711), 'numpy.zeros', 'np.zeros', (['[buffer_size]', 'np.int32'], {}), '([buffer_size], np.int32)\n', (14686, 14711), True, 'import numpy as np\n'), ((18062, 18094), 'numpy.max', 'np.max', (['sampled_priority_weights'], {}), '(sampled_priority_weights)\n', (18068, 18094), True, 'import numpy as np\n'), ((20579, 20640), 'dnc.dnc.Components', 'dnc.Components', (['access_config', 'controller_config', 'num_outputs'], {}), '(access_config, controller_config, num_outputs)\n', (20593, 20640), False, 'from dnc import dnc\n'), ((20673, 20795), 'dnc.dnc.DNC', 'dnc.DNC', (['components', 'num_outputs', 'clip_value'], {'is_new': '(False)', 'is_double_critic': 'is_double_critic', 'is_actor': 'self.is_actor'}), '(components, num_outputs, clip_value, is_new=False, is_double_critic\n =is_double_critic, is_actor=self.is_actor)\n', (20680, 20795), False, 'from dnc import dnc\n'), ((23068, 23199), 'tensorflow.ensure_shape', 'tf.ensure_shape', (['output_sequence', '[FLAGS.batch_size // FLAGS.avg_replays, FLAGS.num_steps, FLAGS.step_size +\n FLAGS.num_actions]'], {}), '(output_sequence, [FLAGS.batch_size // FLAGS.avg_replays,\n FLAGS.num_steps, FLAGS.step_size + FLAGS.num_actions])\n', (23083, 23199), True, 'import tensorflow as tf\n'), ((23276, 23403), 'tensorflow.reshape', 'tf.reshape', (['output_sequence', '[FLAGS.batch_size // FLAGS.avg_replays, FLAGS.num_steps, FLAGS.step_size +\n FLAGS.num_actions]'], {}), '(output_sequence, [FLAGS.batch_size // FLAGS.avg_replays, FLAGS.\n num_steps, FLAGS.step_size + FLAGS.num_actions])\n', (23286, 23403), True, 'import tensorflow as tf\n'), ((24017, 24148), 'tensorflow.ensure_shape', 'tf.ensure_shape', (['output_sequence', '[FLAGS.batch_size // FLAGS.avg_replays, FLAGS.num_steps, FLAGS.step_size +\n FLAGS.num_actions]'], {}), '(output_sequence, [FLAGS.batch_size // FLAGS.avg_replays,\n FLAGS.num_steps, FLAGS.step_size + FLAGS.num_actions])\n', (24032, 24148), True, 'import tensorflow as tf\n'), ((24225, 24352), 'tensorflow.reshape', 'tf.reshape', (['output_sequence', '[FLAGS.batch_size // FLAGS.avg_replays, FLAGS.num_steps, FLAGS.step_size +\n FLAGS.num_actions]'], {}), '(output_sequence, [FLAGS.batch_size // FLAGS.avg_replays, FLAGS.\n num_steps, FLAGS.step_size + FLAGS.num_actions])\n', (24235, 24352), True, 'import tensorflow as tf\n'), ((25746, 25797), 'tensorflow.random_normal_initializer', 'tf.random_normal_initializer', ([], {'mean': '(0.0)', 'stddev': '(0.03)'}), '(mean=0.0, stddev=0.03)\n', (25774, 25797), True, 'import tensorflow as tf\n'), ((26034, 26049), 'tensorflow.transpose', 'tf.transpose', (['w'], {}), '(w)\n', (26046, 26049), True, 'import tensorflow as tf\n'), ((26510, 26537), 'tensorflow.reshape', 'tf.reshape', (['w_norm', 'w_shape'], {}), '(w_norm, w_shape)\n', (26520, 26537), True, 'import tensorflow as tf\n'), ((27359, 27376), 'utility.auto_name', 'auto_name', (['"""bias"""'], {}), "('bias')\n", (27368, 27376), False, 'from utility import alrc, auto_name\n'), ((38994, 39048), 'numpy.ones', 'np.ones', (['[FLAGS.batch_size // FLAGS.avg_replays, 1, 2]'], {}), '([FLAGS.batch_size // FLAGS.avg_replays, 1, 2])\n', (39001, 39048), True, 'import numpy as np\n'), ((43501, 43517), 'numpy.rot90', 'np.rot90', (['img', '(1)'], {}), '(img, 1)\n', (43509, 43517), True, 'import numpy as np\n'), ((44797, 44810), 'numpy.cos', 'np.cos', (['theta'], {}), '(theta)\n', (44803, 44810), True, 'import numpy as np\n'), ((44826, 44839), 'numpy.sin', 'np.sin', (['theta'], {}), '(theta)\n', (44832, 44839), True, 'import numpy as np\n'), ((46997, 47054), 'tensorflow.reduce_mean', 'tf.reduce_mean', (['((edges1 - edges2) ** 2)'], {'axis': '[1, 2, 3, 4]'}), '((edges1 - edges2) ** 2, axis=[1, 2, 3, 4])\n', (47011, 47054), True, 'import tensorflow as tf\n'), ((47516, 47539), 'numpy.random.randint', 'np.random.randint', (['(0)', '(8)'], {}), '(0, 8)\n', (47533, 47539), True, 'import numpy as np\n'), ((48358, 48377), 'utility.auto_name', 'auto_name', (['"""avg_mu"""'], {}), "('avg_mu')\n", (48367, 48377), False, 'from utility import alrc, auto_name\n'), ((48539, 48575), 'tensorflow.control_dependencies', 'tf.control_dependencies', (['[update_op]'], {}), '([update_op])\n', (48562, 48575), True, 'import tensorflow as tf\n'), ((49474, 49508), 'tensorflow.constant', 'tf.constant', (['(1.0)'], {'dtype': 'tf.float32'}), '(1.0, dtype=tf.float32)\n', (49485, 49508), True, 'import tensorflow as tf\n'), ((51803, 51822), 'numpy.isfinite', 'np.isfinite', (['images'], {}), '(images)\n', (51814, 51822), True, 'import numpy as np\n'), ((55989, 55999), 'numpy.sqrt', 'np.sqrt', (['(2)'], {}), '(2)\n', (55996, 55999), True, 'import numpy as np\n'), ((57676, 57709), 'tensorflow.stop_gradient', 'tf.stop_gradient', (['target_actor_qs'], {}), '(target_actor_qs)\n', (57692, 57709), True, 'import tensorflow as tf\n'), ((58998, 59042), 'tensorflow.ensure_shape', 'tf.ensure_shape', (['generation', 'full_scan_shape'], {}), '(generation, full_scan_shape)\n', (59013, 59042), True, 'import tensorflow as tf\n'), ((59084, 59123), 'tensorflow.reshape', 'tf.reshape', (['generation', 'full_scan_shape'], {}), '(generation, full_scan_shape)\n', (59094, 59123), True, 'import tensorflow as tf\n'), ((59612, 59678), 'numpy.sqrt', 'np.sqrt', (['(FLAGS.img_side ** 2 / (FLAGS.num_steps * FLAGS.step_size))'], {}), '(FLAGS.img_side ** 2 / (FLAGS.num_steps * FLAGS.step_size))\n', (59619, 59678), True, 'import numpy as np\n'), ((61891, 61912), 'tensorflow.reduce_mean', 'tf.reduce_mean', (['diffs'], {}), '(diffs)\n', (61905, 61912), True, 'import tensorflow as tf\n'), ((61917, 61951), 'tensorflow.reduce_mean', 'tf.reduce_mean', (['(discr_outputs ** 2)'], {}), '(discr_outputs ** 2)\n', (61931, 61951), True, 'import tensorflow as tf\n'), ((62694, 62718), 'tensorflow.greater', 'tf.greater', (['positions', '(1)'], {}), '(positions, 1)\n', (62704, 62718), True, 'import tensorflow as tf\n'), ((62720, 62741), 'tensorflow.less', 'tf.less', (['positions', '(0)'], {}), '(positions, 0)\n', (62727, 62741), True, 'import tensorflow as tf\n'), ((64518, 64542), 'tensorflow.greater', 'tf.greater', (['positions', '(1)'], {}), '(positions, 1)\n', (64528, 64542), True, 'import tensorflow as tf\n'), ((64544, 64565), 'tensorflow.less', 'tf.less', (['positions', '(0)'], {}), '(positions, 0)\n', (64551, 64565), True, 'import tensorflow as tf\n'), ((66502, 66521), 'utility.alrc', 'alrc', (['critic_losses'], {}), '(critic_losses)\n', (66506, 66521), False, 'from utility import alrc, auto_name\n'), ((67587, 67610), 'utility.alrc', 'alrc', (['actor_qs[:, :, 0]'], {}), '(actor_qs[:, :, 0])\n', (67591, 67610), False, 'from utility import alrc, auto_name\n'), ((67822, 67860), 'tensorflow.tile', 'tf.tile', (['bases0', '[FLAGS.batch_size, 1]'], {}), '(bases0, [FLAGS.batch_size, 1])\n', (67829, 67860), True, 'import tensorflow as tf\n'), ((67884, 67933), 'tensorflow.concat', 'tf.concat', (['[bases0, critic_qs[:, :-1, 0]]'], {'axis': '(1)'}), '([bases0, critic_qs[:, :-1, 0]], axis=1)\n', (67893, 67933), True, 'import tensorflow as tf\n'), ((72621, 72668), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32'], {'name': '"""generator_lr"""'}), "(tf.float32, name='generator_lr')\n", (72635, 72668), True, 'import tensorflow as tf\n'), ((73690, 73736), 'tensorflow.control_dependencies', 'tf.control_dependencies', (['train_op_dependencies'], {}), '(train_op_dependencies)\n', (73713, 73736), True, 'import tensorflow as tf\n'), ((73769, 73818), 'tensorflow.train.RMSPropOptimizer', 'tf.train.RMSPropOptimizer', ([], {'learning_rate': 'actor_lr'}), '(learning_rate=actor_lr)\n', (73794, 73818), True, 'import tensorflow as tf\n'), ((73851, 73901), 'tensorflow.train.RMSPropOptimizer', 'tf.train.RMSPropOptimizer', ([], {'learning_rate': 'critic_lr'}), '(learning_rate=critic_lr)\n', (73876, 73901), True, 'import tensorflow as tf\n'), ((76996, 77009), 'numpy.bool', 'np.bool', (['(True)'], {}), '(True)\n', (77003, 77009), True, 'import numpy as np\n'), ((77043, 77059), 'numpy.float32', 'np.float32', (['(0.99)'], {}), '(0.99)\n', (77053, 77059), True, 'import numpy as np\n'), ((77079, 77112), 'tensorflow.global_variables_initializer', 'tf.global_variables_initializer', ([], {}), '()\n', (77110, 77112), True, 'import tensorflow as tf\n'), ((77301, 77357), 'tensorflow.train.latest_checkpoint', 'tf.train.latest_checkpoint', (["(model_dir + 'noteable_ckpt/')"], {}), "(model_dir + 'noteable_ckpt/')\n", (77327, 77357), True, 'import tensorflow as tf\n'), ((15021, 15059), 'numpy.random.randint', 'np.random.randint', (['(0)', 'self.buffer_size'], {}), '(0, self.buffer_size)\n', (15038, 15059), True, 'import numpy as np\n'), ((15861, 15904), 'numpy.mean', 'np.mean', (['self.priorities[self.accesses > 0]'], {}), '(self.priorities[self.accesses > 0])\n', (15868, 15904), True, 'import numpy as np\n'), ((16029, 16056), 'numpy.ones', 'np.ones', (['[num_before_cycle]'], {}), '([num_before_cycle])\n', (16036, 16056), True, 'import numpy as np\n'), ((18542, 18592), 'numpy.random.randint', 'np.random.randint', (['(0)', 'limit'], {'size': 'self._batch_size'}), '(0, limit, size=self._batch_size)\n', (18559, 18592), True, 'import numpy as np\n'), ((19173, 19220), 'numpy.stack', 'np.stack', (['[self.labels[i] for i in sample_idxs]'], {}), '([self.labels[i] for i in sample_idxs])\n', (19181, 19220), True, 'import numpy as np\n'), ((19256, 19311), 'numpy.stack', 'np.stack', (['[self.next_losses[i] for i in sampled_labels]'], {}), '([self.next_losses[i] for i in sampled_labels])\n', (19264, 19311), True, 'import numpy as np\n'), ((20962, 21131), 'dnc.dnc.DNC', 'dnc.DNC', (['components', 'num_outputs', 'clip_value'], {'is_new': '(True)', 'noise_decay': 'noise_decay', 'sampled_full_scans': 'sampled_full_scans', 'is_noise': '(True)', 'is_actor': 'self.is_actor'}), '(components, num_outputs, clip_value, is_new=True, noise_decay=\n noise_decay, sampled_full_scans=sampled_full_scans, is_noise=True,\n is_actor=self.is_actor)\n', (20969, 21131), False, 'from dnc import dnc\n'), ((22834, 22903), 'tensorflow.zeros', 'tf.zeros', (['[FLAGS.batch_size // FLAGS.avg_replays, FLAGS.num_steps, 1]'], {}), '([FLAGS.batch_size // FLAGS.avg_replays, FLAGS.num_steps, 1])\n', (22842, 22903), True, 'import tensorflow as tf\n'), ((23783, 23852), 'tensorflow.zeros', 'tf.zeros', (['[FLAGS.batch_size // FLAGS.avg_replays, FLAGS.num_steps, 1]'], {}), '([FLAGS.batch_size // FLAGS.avg_replays, FLAGS.num_steps, 1])\n', (23791, 23852), True, 'import tensorflow as tf\n'), ((39131, 39157), 'numpy.cumsum', 'np.cumsum', (['actions'], {'axis': '(1)'}), '(actions, axis=1)\n', (39140, 39157), True, 'import numpy as np\n'), ((41741, 41785), 'tensorflow.py_func', 'tf.py_func', (['augmenter', '[image]', '[tf.float32]'], {}), '(augmenter, [image], [tf.float32])\n', (41751, 41785), True, 'import tensorflow as tf\n'), ((42615, 42632), 'numpy.equal', 'np.equal', (['mask', '(0)'], {}), '(mask, 0)\n', (42623, 42632), True, 'import numpy as np\n'), ((43557, 43573), 'numpy.rot90', 'np.rot90', (['img', '(2)'], {}), '(img, 2)\n', (43565, 43573), True, 'import numpy as np\n'), ((44408, 44418), 'numpy.sqrt', 'np.sqrt', (['(2)'], {}), '(2)\n', (44415, 44418), True, 'import numpy as np\n'), ((48391, 48425), 'tensorflow.constant', 'tf.constant', (['(0.5)'], {'dtype': 'tf.float32'}), '(0.5, dtype=tf.float32)\n', (48402, 48425), True, 'import tensorflow as tf\n'), ((48601, 48625), 'tensorflow.stop_gradient', 'tf.stop_gradient', (['avg_mu'], {}), '(avg_mu)\n', (48617, 48625), True, 'import tensorflow as tf\n'), ((55939, 55988), 'tensorflow.ones', 'tf.ones', (['[FLAGS.batch_size, 1, FLAGS.num_actions]'], {}), '([FLAGS.batch_size, 1, FLAGS.num_actions])\n', (55946, 55988), True, 'import tensorflow as tf\n'), ((56071, 56114), 'tensorflow.ones', 'tf.ones', (['[batch_size, 1, FLAGS.num_actions]'], {}), '([batch_size, 1, FLAGS.num_actions])\n', (56078, 56114), True, 'import tensorflow as tf\n'), ((62579, 62630), 'tensorflow.cumsum', 'tf.cumsum', (['cartesian_new_actions[:, :-1, :]'], {'axis': '(1)'}), '(cartesian_new_actions[:, :-1, :], axis=1)\n', (62588, 62630), True, 'import tensorflow as tf\n'), ((64403, 64454), 'tensorflow.cumsum', 'tf.cumsum', (['cartesian_new_actions[:, :-1, :]'], {'axis': '(1)'}), '(cartesian_new_actions[:, :-1, :], axis=1)\n', (64412, 64454), True, 'import tensorflow as tf\n'), ((65171, 65202), 'tensorflow.expand_dims', 'tf.expand_dims', (['losses'], {'axis': '(-1)'}), '(losses, axis=-1)\n', (65185, 65202), True, 'import tensorflow as tf\n'), ((65613, 65644), 'tensorflow.expand_dims', 'tf.expand_dims', (['losses'], {'axis': '(-1)'}), '(losses, axis=-1)\n', (65627, 65644), True, 'import tensorflow as tf\n'), ((66016, 66077), 'tensorflow.lin_space', 'tf.lin_space', (['(FLAGS.num_steps - 2.0)', '(0.0)', '(FLAGS.num_steps - 1)'], {}), '(FLAGS.num_steps - 2.0, 0.0, FLAGS.num_steps - 1)\n', (66028, 66077), True, 'import tensorflow as tf\n'), ((67361, 67389), 'tensorflow.reduce_mean', 'tf.reduce_mean', (['spike_losses'], {}), '(spike_losses)\n', (67375, 67389), True, 'import tensorflow as tf\n'), ((67743, 67801), 'tensorflow.reduce_mean', 'tf.reduce_mean', (['critic_qs[:, :1, 0]'], {'axis': '(0)', 'keepdims': '(True)'}), '(critic_qs[:, :1, 0], axis=0, keepdims=True)\n', (67757, 67801), True, 'import tensorflow as tf\n'), ((68455, 68489), 'tensorflow.reduce_mean', 'tf.reduce_mean', (['exploration_losses'], {}), '(exploration_losses)\n', (68469, 68489), True, 'import tensorflow as tf\n'), ((73436, 73482), 'tensorflow.Variable', 'tf.Variable', (['(0.0)'], {'trainable': '(False)', 'name': '"""step"""'}), "(0.0, trainable=False, name='step')\n", (73447, 73482), True, 'import tensorflow as tf\n'), ((78708, 78739), 'numpy.argsort', 'np.argsort', (['sampled_past_losses'], {}), '(sampled_past_losses)\n', (78718, 78739), True, 'import numpy as np\n'), ((78785, 78820), 'numpy.linspace', 'np.linspace', (['(0)', '(1)', 'FLAGS.batch_size'], {}), '(0, 1, FLAGS.batch_size)\n', (78796, 78820), True, 'import numpy as np\n'), ((79303, 79316), 'numpy.bool', 'np.bool', (['(True)'], {}), '(True)\n', (79310, 79316), True, 'import numpy as np\n'), ((79345, 79369), 'numpy.float32', 'np.float32', (['target_decay'], {}), '(target_decay)\n', (79355, 79369), True, 'import numpy as np\n'), ((79580, 79615), 'numpy.float32', 'np.float32', (['FLAGS.over_edge_penalty'], {}), '(FLAGS.over_edge_penalty)\n', (79590, 79615), True, 'import numpy as np\n'), ((82898, 82909), 'time.time', 'time.time', ([], {}), '()\n', (82907, 82909), False, 'import time\n'), ((83310, 83323), 'numpy.bool', 'np.bool', (['(True)'], {}), '(True)\n', (83317, 83323), True, 'import numpy as np\n'), ((83911, 83925), 'numpy.bool', 'np.bool', (['(False)'], {}), '(False)\n', (83918, 83925), True, 'import numpy as np\n'), ((16182, 16234), 'numpy.ones', 'np.ones', (['[self._input_batch_size - num_before_cycle]'], {}), '([self._input_batch_size - num_before_cycle])\n', (16189, 16234), True, 'import numpy as np\n'), ((21409, 21529), 'dnc.dnc.DNC', 'dnc.DNC', (['components', 'num_outputs', 'clip_value'], {'is_new': '(True)', 'sampled_full_scans': 'val_full_scans', 'is_actor': 'self.is_actor'}), '(components, num_outputs, clip_value, is_new=True,\n sampled_full_scans=val_full_scans, is_actor=self.is_actor)\n', (21416, 21529), False, 'from dnc import dnc\n'), ((38852, 38867), 'numpy.cos', 'np.cos', (['actions'], {}), '(actions)\n', (38858, 38867), True, 'import numpy as np\n'), ((38869, 38884), 'numpy.sin', 'np.sin', (['actions'], {}), '(actions)\n', (38875, 38884), True, 'import numpy as np\n'), ((43613, 43629), 'numpy.rot90', 'np.rot90', (['img', '(3)'], {}), '(img, 3)\n', (43621, 43629), True, 'import numpy as np\n'), ((67163, 67182), 'tensorflow.abs', 'tf.abs', (['diffs_start'], {}), '(diffs_start)\n', (67169, 67182), True, 'import tensorflow as tf\n'), ((67184, 67201), 'tensorflow.abs', 'tf.abs', (['diffs_end'], {}), '(diffs_end)\n', (67190, 67201), True, 'import tensorflow as tf\n'), ((77670, 77683), 'numpy.float32', 'np.float32', (['(1)'], {}), '(1)\n', (77680, 77683), True, 'import numpy as np\n'), ((79865, 79933), 'numpy.maximum', 'np.maximum', (['(((train_iters // 2 - iter) / (train_iters // 2)) ** 2)', '(0)'], {}), '(((train_iters // 2 - iter) / (train_iters // 2)) ** 2, 0)\n', (79875, 79933), True, 'import numpy as np\n'), ((82963, 82974), 'time.time', 'time.time', ([], {}), '()\n', (82972, 82974), False, 'import time\n'), ((83111, 83122), 'time.time', 'time.time', ([], {}), '()\n', (83120, 83122), False, 'import time\n'), ((17801, 17824), 'numpy.sum', 'np.sum', (['self.priorities'], {}), '(self.priorities)\n', (17807, 17824), True, 'import numpy as np\n'), ((24741, 24764), 'tensorflow.get_variable_scope', 'tf.get_variable_scope', ([], {}), '()\n', (24762, 24764), True, 'import tensorflow as tf\n'), ((25000, 25023), 'tensorflow.get_variable_scope', 'tf.get_variable_scope', ([], {}), '()\n', (25021, 25023), True, 'import tensorflow as tf\n'), ((35709, 35732), 'tensorflow.get_variable_scope', 'tf.get_variable_scope', ([], {}), '()\n', (35730, 35732), True, 'import tensorflow as tf\n'), ((35968, 35991), 'tensorflow.get_variable_scope', 'tf.get_variable_scope', ([], {}), '()\n', (35989, 35991), True, 'import tensorflow as tf\n'), ((38297, 38320), 'tensorflow.get_variable_scope', 'tf.get_variable_scope', ([], {}), '()\n', (38318, 38320), True, 'import tensorflow as tf\n'), ((38556, 38579), 'tensorflow.get_variable_scope', 'tf.get_variable_scope', ([], {}), '()\n', (38577, 38579), True, 'import tensorflow as tf\n'), ((43669, 43684), 'numpy.flip', 'np.flip', (['img', '(0)'], {}), '(img, 0)\n', (43676, 43684), True, 'import numpy as np\n'), ((75024, 75090), 'tensorflow.clip_by_value', 'tf.clip_by_value', (['g', '(-FLAGS.grad_clip_value)', 'FLAGS.grad_clip_value'], {}), '(g, -FLAGS.grad_clip_value, FLAGS.grad_clip_value)\n', (75040, 75090), True, 'import tensorflow as tf\n'), ((75348, 75414), 'tensorflow.clip_by_value', 'tf.clip_by_value', (['g', '(-FLAGS.grad_clip_value)', 'FLAGS.grad_clip_value'], {}), '(g, -FLAGS.grad_clip_value, FLAGS.grad_clip_value)\n', (75364, 75414), True, 'import tensorflow as tf\n'), ((75712, 75752), 'tensorflow.clip_by_norm', 'tf.clip_by_norm', (['g', 'FLAGS.grad_clip_norm'], {}), '(g, FLAGS.grad_clip_norm)\n', (75727, 75752), True, 'import tensorflow as tf\n'), ((76010, 76050), 'tensorflow.clip_by_norm', 'tf.clip_by_norm', (['g', 'FLAGS.grad_clip_norm'], {}), '(g, FLAGS.grad_clip_norm)\n', (76025, 76050), True, 'import tensorflow as tf\n'), ((76413, 76463), 'tensorflow.train.AdamOptimizer', 'tf.train.AdamOptimizer', ([], {'learning_rate': 'generator_lr'}), '(learning_rate=generator_lr)\n', (76435, 76463), True, 'import tensorflow as tf\n'), ((76709, 76769), 'tensorflow.train.AdamOptimizer', 'tf.train.AdamOptimizer', ([], {'learning_rate': 'FLAGS.discriminator_lr'}), '(learning_rate=FLAGS.discriminator_lr)\n', (76731, 76769), True, 'import tensorflow as tf\n'), ((81051, 81072), 'numpy.float32', 'np.float32', (['cyclic_lr'], {}), '(cyclic_lr)\n', (81061, 81072), True, 'import numpy as np\n'), ((81947, 81979), 'numpy.random.randint', 'np.random.randint', (['(1)', '(1 + period)'], {}), '(1, 1 + period)\n', (81964, 81979), True, 'import numpy as np\n'), ((18457, 18480), 'numpy.sum', 'np.sum', (['self.priorities'], {}), '(self.priorities)\n', (18463, 18480), True, 'import numpy as np\n'), ((43724, 43739), 'numpy.flip', 'np.flip', (['img', '(1)'], {}), '(img, 1)\n', (43731, 43739), True, 'import numpy as np\n'), ((62334, 62359), 'tensorflow.cos', 'tf.cos', (['replay_actions_ph'], {}), '(replay_actions_ph)\n', (62340, 62359), True, 'import tensorflow as tf\n'), ((62361, 62386), 'tensorflow.sin', 'tf.sin', (['replay_actions_ph'], {}), '(replay_actions_ph)\n', (62367, 62386), True, 'import tensorflow as tf\n'), ((64158, 64183), 'tensorflow.cos', 'tf.cos', (['replay_actions_ph'], {}), '(replay_actions_ph)\n', (64164, 64183), True, 'import tensorflow as tf\n'), ((64185, 64210), 'tensorflow.sin', 'tf.sin', (['replay_actions_ph'], {}), '(replay_actions_ph)\n', (64191, 64210), True, 'import tensorflow as tf\n'), ((43787, 43803), 'numpy.rot90', 'np.rot90', (['img', '(1)'], {}), '(img, 1)\n', (43795, 43803), True, 'import numpy as np\n'), ((43843, 43859), 'numpy.rot90', 'np.rot90', (['img', '(1)'], {}), '(img, 1)\n', (43851, 43859), True, 'import numpy as np\n')]
import pandas as pd from math import isnan import numpy as np from train import GRUTree from train import visualize import os import cPickle from sklearn.model_selection import train_test_split from sklearn.metrics import roc_auc_score, mean_squared_error, accuracy_score def preprocess(dataset): # complete missing age with median dataset['Age'].fillna(dataset['Age'].median(), inplace=True) # complete embarked with mode dataset['Embarked'].fillna(dataset['Embarked'].mode()[0], inplace=True) # complete missing fare with median dataset['Fare'].fillna(dataset['Fare'].median(), inplace=True) # delete the cabin feature/column and others previously stated to exclude in train dataset drop_column = ['PassengerId', 'Cabin', 'Ticket'] dataset.drop(drop_column, axis=1, inplace=True) # Discrete variables dataset['FamilySize'] = dataset['SibSp'] + dataset['Parch'] + 1 dataset['IsAlone'] = "Alone" # initialize to yes/1 is alone dataset['IsAlone'].loc[dataset['FamilySize'] > 1] = "Not alone" # now update to no/0 if family size is greater than 1 dataset.drop(["SibSp", "Parch"], axis=1, inplace=True) # quick and dirty code split title from name: http://www.pythonforbeginners.com/dictionary/python-split dataset['Title'] = dataset['Name'].str.split(", ", expand=True)[1].str.split(".", expand=True)[0] # Continuous variable bins; qcut vs cut: https://stackoverflow.com/questions/30211923/what-is-the-difference-between-pandas-qcut-and-pandas-cut # Fare Bins/Buckets using qcut or frequency bins: https://pandas.pydata.org/pandas-docs/stable/generated/pandas.qcut.html #dataset['FareBin'] = pd.qcut(dataset['Fare'], 4) # Age Bins/Buckets using cut or value bins: https://pandas.pydata.org/pandas-docs/stable/generated/pandas.cut.html #dataset['AgeBin'] = pd.cut(dataset['Age'].astype(int), 5) # cleanup rare title names # print(data1['Title'].value_counts()) stat_min = 10 # while small is arbitrary, we'll use the common minimum in statistics: http://nicholasjjackson.com/2012/03/08/sample-size-is-10-a-magic-number/ title_names = (dataset['Title'].value_counts() < stat_min) # this will create a true false series with title name as index # apply and lambda functions are quick and dirty code to find and replace with fewer lines of code: https://community.modeanalytics.com/python/tutorial/pandas-groupby-and-python-lambda-functions/ dataset['Title'] = dataset['Title'].apply(lambda x: 'Misc' if title_names.loc[x] == True else x) dataset.drop("Name", axis=1, inplace=True) return pd.get_dummies(dataset) if __name__ == "__main__": dataframe = pd.read_csv("titanic_data/train.csv") target = dataframe["Survived"] data = dataframe.drop("Survived", axis=1) data = preprocess(data) samples, features = data.shape X_train, X_test, y_train, y_test = train_test_split(data.values, target, test_size = 0.33) X_train = np.swapaxes(X_train, axis1=0, axis2=1) X_test = np.swapaxes(X_test, axis1=0, axis2=1) F_train = np.array(range(0, int(round(samples*(0.66))))) F_test = np.array(range(0, int(round(samples*(0.33))))) y_train = y_train[np.newaxis, :] y_test = y_test[np.newaxis, :] #Build Model gru = GRUTree(features, 1, [25], 1, strength=1000) gru.train(X_train, F_train, y_train, iters_retrain=25, num_iters=300, batch_size=10, lr=1e-2, param_scale=0.1, log_every=10) if not os.path.isdir('./trained_models_titanic'): os.mkdir('./trained_models_titanic') with open('./trained_models_titanic/trained_weights.pkl', 'wb') as fp: cPickle.dump({'gru': gru.gru.weights, 'mlp': gru.mlp.weights}, fp) print('saved trained model to ./trained_models_titanic') visualize(gru.tree, './trained_models_titanic/tree.pdf') print('saved final decision tree to ./trained_models_titanic') y_hat = gru.pred_fun(gru.weights, X_test, F_test) auc_test = roc_auc_score(y_test.T, y_hat.T) print('Test AUC: {:.2f}'.format(auc_test)) auc_test = mean_squared_error(y_test.T, y_hat.T) print('Test MSE: {:.2f}'.format(auc_test)) auc_test = accuracy_score(y_test.T, np.round(y_hat.T)) print('Test ACC: {:.2f}'.format(auc_test))
[ "os.mkdir", "pandas.read_csv", "pandas.get_dummies", "sklearn.model_selection.train_test_split", "os.path.isdir", "sklearn.metrics.roc_auc_score", "cPickle.dump", "numpy.swapaxes", "train.visualize", "train.GRUTree", "numpy.round", "sklearn.metrics.mean_squared_error" ]
[((2613, 2636), 'pandas.get_dummies', 'pd.get_dummies', (['dataset'], {}), '(dataset)\n', (2627, 2636), True, 'import pandas as pd\n'), ((2682, 2719), 'pandas.read_csv', 'pd.read_csv', (['"""titanic_data/train.csv"""'], {}), "('titanic_data/train.csv')\n", (2693, 2719), True, 'import pandas as pd\n'), ((2905, 2958), 'sklearn.model_selection.train_test_split', 'train_test_split', (['data.values', 'target'], {'test_size': '(0.33)'}), '(data.values, target, test_size=0.33)\n', (2921, 2958), False, 'from sklearn.model_selection import train_test_split\n'), ((2976, 3014), 'numpy.swapaxes', 'np.swapaxes', (['X_train'], {'axis1': '(0)', 'axis2': '(1)'}), '(X_train, axis1=0, axis2=1)\n', (2987, 3014), True, 'import numpy as np\n'), ((3028, 3065), 'numpy.swapaxes', 'np.swapaxes', (['X_test'], {'axis1': '(0)', 'axis2': '(1)'}), '(X_test, axis1=0, axis2=1)\n', (3039, 3065), True, 'import numpy as np\n'), ((3288, 3332), 'train.GRUTree', 'GRUTree', (['features', '(1)', '[25]', '(1)'], {'strength': '(1000)'}), '(features, 1, [25], 1, strength=1000)\n', (3295, 3332), False, 'from train import GRUTree\n'), ((3797, 3853), 'train.visualize', 'visualize', (['gru.tree', '"""./trained_models_titanic/tree.pdf"""'], {}), "(gru.tree, './trained_models_titanic/tree.pdf')\n", (3806, 3853), False, 'from train import visualize\n'), ((3991, 4023), 'sklearn.metrics.roc_auc_score', 'roc_auc_score', (['y_test.T', 'y_hat.T'], {}), '(y_test.T, y_hat.T)\n', (4004, 4023), False, 'from sklearn.metrics import roc_auc_score, mean_squared_error, accuracy_score\n'), ((4087, 4124), 'sklearn.metrics.mean_squared_error', 'mean_squared_error', (['y_test.T', 'y_hat.T'], {}), '(y_test.T, y_hat.T)\n', (4105, 4124), False, 'from sklearn.metrics import roc_auc_score, mean_squared_error, accuracy_score\n'), ((3488, 3529), 'os.path.isdir', 'os.path.isdir', (['"""./trained_models_titanic"""'], {}), "('./trained_models_titanic')\n", (3501, 3529), False, 'import os\n'), ((3539, 3575), 'os.mkdir', 'os.mkdir', (['"""./trained_models_titanic"""'], {}), "('./trained_models_titanic')\n", (3547, 3575), False, 'import os\n'), ((3660, 3726), 'cPickle.dump', 'cPickle.dump', (["{'gru': gru.gru.weights, 'mlp': gru.mlp.weights}", 'fp'], {}), "({'gru': gru.gru.weights, 'mlp': gru.mlp.weights}, fp)\n", (3672, 3726), False, 'import cPickle\n'), ((4213, 4230), 'numpy.round', 'np.round', (['y_hat.T'], {}), '(y_hat.T)\n', (4221, 4230), True, 'import numpy as np\n')]
from hetu import get_worker_communicate from hetu.preduce import PartialReduce from hetu import ndarray import hetu as ht import ctypes import argparse import numpy as np from tqdm import tqdm import time import random def test(args): comm = get_worker_communicate() rank = comm.rank() comm.ssp_init(rank // 2, 2, 0) for i in range(10): print("rank =", rank, " stage =", i) comm.ssp_sync(rank // 2, i) time.sleep(rank * 0.1) def test2(): p = PartialReduce() comm = ht.wrapped_mpi_nccl_init() val = np.repeat(comm.rank, 1024) val = ndarray.array(val, ctx=ndarray.gpu(comm.rank)) for i in range(10): partner = p.get_partner() p.preduce(val, partner) print(partner, val.asnumpy()) if __name__ == '__main__': parser = argparse.ArgumentParser() args = parser.parse_args() ht.worker_init() test2() ht.worker_finish()
[ "hetu.get_worker_communicate", "hetu.worker_finish", "hetu.wrapped_mpi_nccl_init", "argparse.ArgumentParser", "time.sleep", "hetu.preduce.PartialReduce", "hetu.ndarray.gpu", "hetu.worker_init", "numpy.repeat" ]
[((249, 273), 'hetu.get_worker_communicate', 'get_worker_communicate', ([], {}), '()\n', (271, 273), False, 'from hetu import get_worker_communicate\n'), ((490, 505), 'hetu.preduce.PartialReduce', 'PartialReduce', ([], {}), '()\n', (503, 505), False, 'from hetu.preduce import PartialReduce\n'), ((517, 543), 'hetu.wrapped_mpi_nccl_init', 'ht.wrapped_mpi_nccl_init', ([], {}), '()\n', (541, 543), True, 'import hetu as ht\n'), ((554, 580), 'numpy.repeat', 'np.repeat', (['comm.rank', '(1024)'], {}), '(comm.rank, 1024)\n', (563, 580), True, 'import numpy as np\n'), ((807, 832), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (830, 832), False, 'import argparse\n'), ((868, 884), 'hetu.worker_init', 'ht.worker_init', ([], {}), '()\n', (882, 884), True, 'import hetu as ht\n'), ((901, 919), 'hetu.worker_finish', 'ht.worker_finish', ([], {}), '()\n', (917, 919), True, 'import hetu as ht\n'), ((445, 467), 'time.sleep', 'time.sleep', (['(rank * 0.1)'], {}), '(rank * 0.1)\n', (455, 467), False, 'import time\n'), ((614, 636), 'hetu.ndarray.gpu', 'ndarray.gpu', (['comm.rank'], {}), '(comm.rank)\n', (625, 636), False, 'from hetu import ndarray\n')]
"""Image functions for PET data reconstruction and processing.""" import glob import logging import math import multiprocessing import os import re import shutil from subprocess import run import nibabel as nib import numpy as np import pydicom as dcm from niftypet import nimpa from .. import mmraux from .. import resources as rs log = logging.getLogger(__name__) OFFSET_DEFAULT = np.array([0., 0., 0.]) ct_nans = -1024 # ================================================================================== # IMAGE ROUTINES # ================================================================================== def convert2e7(img, Cnt): '''Convert GPU optimised image to Siemens/E7 image shape (127,344,344).''' margin = (Cnt['SO_IMX'] - Cnt['SZ_IMX']) // 2 # permute the dims first imo = np.transpose(img, (2, 0, 1)) nvz = img.shape[2] # > get the x-axis filler and apply it filler = np.zeros((nvz, Cnt['SZ_IMY'], margin), dtype=np.float32) imo = np.concatenate((filler, imo, filler), axis=2) # > get the y-axis filler and apply it filler = np.zeros((nvz, margin, Cnt['SO_IMX']), dtype=np.float32) imo = np.concatenate((filler, imo, filler), axis=1) return imo def convert2dev(im, Cnt): '''Reshape Siemens/E7 (default) image for optimal GPU execution.''' if im.shape[1] != Cnt['SO_IMY'] or im.shape[2] != Cnt['SO_IMX']: raise ValueError('e> input image array is not of the correct Siemens shape.') if 'rSZ_IMZ' in Cnt and im.shape[0] != Cnt['rSZ_IMZ']: log.warning('the axial number of voxels does not match the reduced rings.') elif 'rSZ_IMZ' not in Cnt and im.shape[0] != Cnt['SZ_IMZ']: log.warning('the axial number of voxels does not match the rings.') im_sqzd = np.zeros((im.shape[0], Cnt['SZ_IMY'], Cnt['SZ_IMX']), dtype=np.float32) margin = int((Cnt['SO_IMX'] - Cnt['SZ_IMX']) / 2) margin_ = -margin if margin == 0: margin = None margin_ = None im_sqzd = im[:, margin:margin_, margin:margin_] im_sqzd = np.transpose(im_sqzd, (1, 2, 0)) return im_sqzd def cropxy(im, imsize, datain, Cnt, store_pth=''): ''' Crop image transaxially to the size in tuple <imsize>. Return the image and the affine matrix. ''' if not imsize[0] % 2 == 0 and not imsize[1] % 2 == 0: log.error('image size has to be an even number!') return None # cropping indexes i0 = int((Cnt['SO_IMX'] - imsize[0]) / 2) i1 = int((Cnt['SO_IMY'] + imsize[1]) / 2) B = image_affine(datain, Cnt, gantry_offset=False) B[0, 3] -= 10 * Cnt['SO_VXX'] * i0 B[1, 3] += 10 * Cnt['SO_VXY'] * (Cnt['SO_IMY'] - i1) cim = im[:, i0:i1, i0:i1] if store_pth != '': nimpa.array2nii(cim[::-1, ::-1, :], B, store_pth, descrip='cropped') log.info('saved cropped image to:\n{}'.format(store_pth)) return cim, B def image_affine(datain, Cnt, gantry_offset=False): '''Creates a blank reference image, to which another image will be resampled''' # ------get necessary data for ----- # gantry offset if gantry_offset: goff, tpo = mmraux.lm_pos(datain, Cnt) else: goff = np.zeros((3)) vbed, hbed = mmraux.vh_bedpos(datain, Cnt) if 'rNRNG' in Cnt and 'rSO_IMZ' in Cnt: imz = Cnt['rSO_IMZ'] else: imz = Cnt['SO_IMZ'] # create a reference empty mu-map image B = np.diag(np.array([-10 * Cnt['SO_VXX'], 10 * Cnt['SO_VXY'], 10 * Cnt['SO_VXZ'], 1])) B[0, 3] = 10 * (.5 * Cnt['SO_IMX'] * Cnt['SO_VXX'] + goff[0]) B[1, 3] = 10 * ((-.5 * Cnt['SO_IMY'] + 1) * Cnt['SO_VXY'] - goff[1]) B[2, 3] = 10 * ((-.5 * imz + 1) * Cnt['SO_VXZ'] - goff[2] + hbed) # ------------------------------------------------------------------------------------- return B def getmu_off(mu, Cnt, Offst=OFFSET_DEFAULT): # phange the shape to 3D mu.shape = (Cnt['SO_IMZ'], Cnt['SO_IMY'], Cnt['SO_IMX']) # ------------------------------------------------------------------------- # CORRECT THE MU-MAP for GANTRY OFFSET # ------------------------------------------------------------------------- Cim = { 'VXSOx': 0.208626, 'VXSOy': 0.208626, 'VXSOz': 0.203125, 'VXNOx': 344, 'VXNOy': 344, 'VXNOz': 127, 'VXSRx': 0.208626, 'VXSRy': 0.208626, 'VXSRz': 0.203125, 'VXNRx': 344, 'VXNRy': 344, 'VXNRz': 127} # priginal image offset Cim['OFFOx'] = -0.5 * Cim['VXNOx'] * Cim['VXSOx'] Cim['OFFOy'] = -0.5 * Cim['VXNOy'] * Cim['VXSOy'] Cim['OFFOz'] = -0.5 * Cim['VXNOz'] * Cim['VXSOz'] # pesampled image offset Cim['OFFRx'] = -0.5 * Cim['VXNRx'] * Cim['VXSRx'] Cim['OFFRy'] = -0.5 * Cim['VXNRy'] * Cim['VXSRy'] Cim['OFFRz'] = -0.5 * Cim['VXNRz'] * Cim['VXSRz'] # pransformation matrix A = np.array( [[1., 0., 0., Offst[0]], [0., 1., 0., Offst[1]], [0., 0., 1., Offst[2]], [0., 0., 0., 1.]], dtype=np.float32) # ppply the gantry offset to the mu-map mur = nimpa.prc.improc.resample(mu, A, Cim) return mur def getinterfile_off(fmu, Cnt, Offst=OFFSET_DEFAULT): ''' Return the floating point mu-map in an array from Interfile, accounting for image offset (does slow interpolation). ''' # pead the image file f = open(fmu, 'rb') mu = np.fromfile(f, np.float32) f.close() # save_im(mur, Cnt, os.path.dirname(fmu) + '/mur.nii') # ------------------------------------------------------------------------- mur = getmu_off(mu, Cnt) # > create GPU version of the mu-map murs = convert2dev(mur, Cnt) # > number of voxels nvx = mu.shape[0] # > get the basic stats mumax = np.max(mur) mumin = np.min(mur) # > number of voxels greater than 10% of max image value n10mx = np.sum(mur > 0.1 * mumax) # > return image dictionary with the image itself and some other stats mu_dct = {'im': mur, 'ims': murs, 'max': mumax, 'min': mumin, 'nvx': nvx, 'n10mx': n10mx} return mu_dct def getinterfile(fim, Cnt): '''Return the floating point image file in an array from an Interfile file.''' # pead the image file f = open(fim, 'rb') im = np.fromfile(f, np.float32) f.close() # pumber of voxels nvx = im.shape[0] # phange the shape to 3D im.shape = (Cnt['SO_IMZ'], Cnt['SO_IMY'], Cnt['SO_IMX']) # pet the basic stats immax = np.max(im) immin = np.min(im) # pumber of voxels greater than 10% of max image value n10mx = np.sum(im > 0.1 * immax) # peorganise the image for optimal gpu execution im_sqzd = convert2dev(im, Cnt) # peturn image dictionary with the image itself and some other stats im_dct = {'im': im, 'ims': im_sqzd, 'max': immax, 'min': immin, 'nvx': nvx, 'n10mx': n10mx} return im_dct # define uniform cylinder def get_cylinder(Cnt, rad=25, xo=0, yo=0, unival=1, gpu_dim=False): """ Outputs image with a uniform cylinder of intensity = unival, radius = rad, and transaxial centre (xo, yo) """ imdsk = np.zeros((1, Cnt['SO_IMX'], Cnt['SO_IMY']), dtype=np.float32) for t in np.arange(0, math.pi, math.pi / (2*360)): x = xo + rad * math.cos(t) y = yo + rad * math.sin(t) yf = np.arange(-y + 2*yo, y, Cnt['SO_VXY'] / 2) v = np.int32(.5 * Cnt['SO_IMX'] - np.ceil(yf / Cnt['SO_VXY'])) u = np.int32(.5 * Cnt['SO_IMY'] + np.floor(x / Cnt['SO_VXY'])) imdsk[0, v, u] = unival if 'rSO_IMZ' in Cnt: nvz = Cnt['rSO_IMZ'] else: nvz = Cnt['SO_IMZ'] imdsk = np.repeat(imdsk, nvz, axis=0) if gpu_dim: imdsk = convert2dev(imdsk, Cnt) return imdsk def hu2mu(im): '''HU units to 511keV PET mu-values''' # convert nans to -1024 for the HU values only im[np.isnan(im)] = ct_nans # constants muwater = 0.096 mubone = 0.172 rhowater = 0.158 rhobone = 0.326 uim = np.zeros(im.shape, dtype=np.float32) uim[im <= 0] = muwater * (1 + im[im <= 0] * 1e-3) uim[im > 0] = muwater * (1 + im[im > 0] * 1e-3 * rhowater / muwater * (mubone-muwater) / (rhobone-rhowater)) # remove negative values uim[uim < 0] = 0 return uim # ===================================================================================== # object/patient mu-map resampling to NIfTI # better use dcm2niix def mudcm2nii(datain, Cnt): '''DICOM mu-map to NIfTI''' mu, pos, ornt = nimpa.dcm2im(datain['mumapDCM']) mu *= 0.0001 A = pos['AFFINE'] A[0, 0] *= -1 A[0, 3] *= -1 A[1, 3] += A[1, 1] nimpa.array2nii(mu[:, ::-1, :], A, os.path.join(os.path.dirname(datain['mumapDCM']), 'mu.nii.gz')) # ------get necessary data for creating a blank reference image (to which resample)----- # gantry offset goff, tpo = mmraux.lm_pos(datain, Cnt) ihdr, csainfo = mmraux.hdr_lm(datain) # ptart horizontal bed position p = re.compile(r'start horizontal bed position.*\d{1,3}\.*\d*') m = p.search(ihdr) fi = ihdr[m.start():m.end()].find('=') hbedpos = 0.1 * float(ihdr[m.start() + fi + 1:m.end()]) B = np.diag(np.array([-10 * Cnt['SO_VXX'], 10 * Cnt['SO_VXY'], 10 * Cnt['SO_VXZ'], 1])) B[0, 3] = 10 * (.5 * Cnt['SO_IMX'] * Cnt['SO_VXX'] + goff[0]) B[1, 3] = 10 * ((-.5 * Cnt['SO_IMY'] + 1) * Cnt['SO_VXY'] - goff[1]) B[2, 3] = 10 * ((-.5 * Cnt['SO_IMZ'] + 1) * Cnt['SO_VXZ'] - goff[2] + hbedpos) im = np.zeros((Cnt['SO_IMZ'], Cnt['SO_IMY'], Cnt['SO_IMX']), dtype=np.float32) nimpa.array2nii(im, B, os.path.join(os.path.dirname(datain['mumapDCM']), 'muref.nii.gz')) # ------------------------------------------------------------------------------------- fmu = os.path.join(os.path.dirname(datain['mumapDCM']), 'mu_r.nii.gz') if os.path.isfile(Cnt['RESPATH']): run([ Cnt['RESPATH'], '-ref', os.path.join(os.path.dirname(datain['mumapDCM']), 'muref.nii.gz'), '-flo', os.path.join(os.path.dirname(datain['mumapDCM']), 'mu.nii.gz'), '-res', fmu, '-pad', '0']) else: log.error('path to resampling executable is incorrect!') raise IOError('Error launching NiftyReg for image resampling.') return fmu def obj_mumap( datain, params=None, outpath='', comment='', store=False, store_npy=False, gantry_offset=True, del_auxilary=True, ): '''Get the object mu-map from DICOM images''' if params is None: params = {} # three ways of passing scanner constants <Cnt> are here decoded if 'Cnt' in params: Cnt = params['Cnt'] elif 'SO_IMZ' in params: Cnt = params else: Cnt = rs.get_mmr_constants() # output folder if outpath == '': fmudir = os.path.join(datain['corepath'], 'mumap-obj') else: fmudir = os.path.join(outpath, 'mumap-obj') nimpa.create_dir(fmudir) # > ref file name fmuref = os.path.join(fmudir, 'muref.nii.gz') # > ref affine B = image_affine(datain, Cnt, gantry_offset=gantry_offset) # > ref image (blank) im = np.zeros((Cnt['SO_IMZ'], Cnt['SO_IMY'], Cnt['SO_IMX']), dtype=np.float32) # > store ref image nimpa.array2nii(im, B, fmuref) # check if the object dicom files for MR-based mu-map exists if 'mumapDCM' not in datain or not os.path.isdir(datain['mumapDCM']): log.error('DICOM folder for the mu-map does not exist.') return None fnii = 'converted-from-object-DICOM_' tstmp = nimpa.time_stamp(simple_ascii=True) # find residual(s) from previous runs and delete them resdcm = glob.glob(os.path.join(fmudir, '*' + fnii + '*.nii*')) for d in resdcm: os.remove(d) # convert the DICOM mu-map images to nii run([Cnt['DCM2NIIX'], '-f', fnii + tstmp, '-o', fmudir, datain['mumapDCM']]) # piles for the T1w, pick one: fmunii = glob.glob(os.path.join(fmudir, '*' + fnii + tstmp + '*.nii*'))[0] # fmunii = glob.glob( os.path.join(datain['mumapDCM'], '*converted*.nii*') ) # fmunii = fmunii[0] # the converted nii image resample to the reference size fmu = os.path.join(fmudir, comment + 'mumap_tmp.nii.gz') if os.path.isfile(Cnt['RESPATH']): cmd = [Cnt['RESPATH'], '-ref', fmuref, '-flo', fmunii, '-res', fmu, '-pad', '0'] if log.getEffectiveLevel() > logging.INFO: cmd.append('-voff') run(cmd) else: log.error('path to resampling executable is incorrect!') raise IOError('Path to executable is incorrect!') nim = nib.load(fmu) # get the affine transform A = nim.get_sform() mu = nim.get_fdata(dtype=np.float32) mu = np.transpose(mu[:, ::-1, ::-1], (2, 1, 0)) # convert to mu-values mu = np.float32(mu) / 1e4 mu[mu < 0] = 0 # > return image dictionary with the image itself and some other stats mu_dct = {'im': mu, 'affine': A} if not del_auxilary: mu_dct['fmuref'] = fmuref # > store the mu-map if requested if store_npy: # to numpy array fnp = os.path.join(fmudir, "mumap-from-DICOM.npz") np.savez(fnp, mu=mu, A=A) if store: # with this file name fmumap = os.path.join(fmudir, 'mumap-from-DICOM_no-alignment' + comment + '.nii.gz') nimpa.array2nii(mu[::-1, ::-1, :], A, fmumap) mu_dct['fim'] = fmumap if del_auxilary: os.remove(fmuref) os.remove(fmunii) os.remove(fmu) if [f for f in os.listdir(fmudir) if not f.startswith('.') and not f.endswith('.json')] == []: shutil.rmtree(fmudir) return mu_dct # ================================================================================ # pCT/UTE MU-MAP ALIGNED # -------------------------------------------------------------------------------- def align_mumap( datain, scanner_params=None, outpath='', reg_tool='niftyreg', use_stored=False, hst=None, t0=0, t1=0, itr=2, faff='', fpet='', fcomment='', store=False, store_npy=False, petopt='ac', musrc='ute', # another option is pct for mu-map source ute_name='UTE2', del_auxilary=True, verbose=False, ): ''' Align the a pCT or MR-derived mu-map to a PET image reconstructed to chosen specifications (e.g., with/without attenuation and scatter corrections) use_sotred only works if hst or t0/t1 given but not when faff. ''' if scanner_params is None: scanner_params = {} # > output folder if outpath == '': opth = os.path.join(datain['corepath'], 'mumap-obj') else: opth = os.path.join(outpath, 'mumap-obj') # > create the folder, if not existent nimpa.create_dir(opth) # > get the timing of PET if affine not given if faff == '' and hst is not None and isinstance(hst, dict) and 't0' in hst: t0 = hst['t0'] t1 = hst['t1'] # > file name for the output mu-map fnm = 'mumap-' + musrc.upper() # > output dictionary mu_dct = {} # --------------------------------------------------------------------------- # > used stored if requested if use_stored: fmu_stored = fnm + '-aligned-to_t'\ + str(t0)+'-'+str(t1)+'_'+petopt.upper()\ + fcomment fmupath = os.path.join(opth, fmu_stored + '.nii.gz') if os.path.isfile(fmupath): mudct_stored = nimpa.getnii(fmupath, output='all') # > create output dictionary mu_dct['im'] = mudct_stored['im'] mu_dct['affine'] = mudct_stored['affine'] # pu_dct['faff'] = faff return mu_dct # --------------------------------------------------------------------------- # > tmp folder for not aligned mu-maps tmpdir = os.path.join(opth, 'tmp') nimpa.create_dir(tmpdir) # > three ways of passing scanner constants <Cnt> are here decoded if 'Cnt' in scanner_params: Cnt = scanner_params['Cnt'] elif 'SO_IMZ' in scanner_params: Cnt = scanner_params else: Cnt = rs.get_mmr_constants() # > if affine not provided histogram the LM data for recon and registration if not os.path.isfile(faff): from niftypet.nipet.prj import mmrrec # -histogram the list data if needed if hst is None: from niftypet.nipet import mmrhist if 'txLUT' in scanner_params: hst = mmrhist(datain, scanner_params, t0=t0, t1=t1) else: raise ValueError('Full scanner are parameters not provided\ but are required for histogramming.') # ======================================================== # -get hardware mu-map if 'hmumap' in datain and os.path.isfile(datain['hmumap']): muh = np.load(datain['hmumap'], allow_pickle=True)["hmu"] (log.info if verbose else log.debug)('loaded hardware mu-map from file:\n{}'.format( datain['hmumap'])) elif outpath != '': hmupath = os.path.join(outpath, "mumap-hdw", "hmumap.npz") if os.path.isfile(hmupath): muh = np.load(hmupath, allow_pickle=True)["hmu"] datain["hmumap"] = hmupath else: raise IOError('Invalid path to the hardware mu-map') else: log.error('the hardware mu-map is required first.') raise IOError('Could not find the hardware mu-map!') # ======================================================== # -check if T1w image is available if not {'MRT1W#', 'T1nii', 'T1bc', 'T1N4'}.intersection(datain): log.error('no MR T1w images required for co-registration!') raise IOError('T1w image could not be obtained!') # ======================================================== # -if the affine is not given, # -it will be generated by reconstructing PET image, with some or no corrections if not os.path.isfile(faff): # first recon pet to get the T1 aligned to it if petopt == 'qnt': # --------------------------------------------- # OPTION 1 (quantitative recon with all corrections using MR-based mu-map) # get UTE object mu-map (may not be in register with the PET data) mudic = obj_mumap(datain, Cnt, outpath=tmpdir, del_auxilary=del_auxilary) muo = mudic['im'] # reconstruct PET image with UTE mu-map to which co-register T1w recout = mmrrec.osemone(datain, [muh, muo], hst, scanner_params, recmod=3, itr=itr, fwhm=0., fcomment=fcomment + '_QNT-UTE', outpath=os.path.join(outpath, 'PET', 'positioning'), store_img=True) elif petopt == 'nac': # --------------------------------------------- # OPTION 2 (recon without any corrections for scatter and attenuation) # reconstruct PET image with UTE mu-map to which co-register T1w muo = np.zeros(muh.shape, dtype=muh.dtype) recout = mmrrec.osemone(datain, [muh, muo], hst, scanner_params, recmod=1, itr=itr, fwhm=0., fcomment=fcomment + '_NAC', outpath=os.path.join(outpath, 'PET', 'positioning'), store_img=True) elif petopt == 'ac': # --------------------------------------------- # OPTION 3 (recon with attenuation correction only but no scatter) # reconstruct PET image with UTE mu-map to which co-register T1w mudic = obj_mumap(datain, Cnt, outpath=tmpdir, del_auxilary=del_auxilary) muo = mudic['im'] recout = mmrrec.osemone(datain, [muh, muo], hst, scanner_params, recmod=1, itr=itr, fwhm=0., fcomment=fcomment + '_AC-UTE', outpath=os.path.join(outpath, 'PET', 'positioning'), store_img=True) fpet = recout.fpet mu_dct['fpet'] = fpet # ------------------------------ if musrc == 'ute' and ute_name in datain and os.path.exists(datain[ute_name]): # change to NIfTI if the UTE sequence is in DICOM files (folder) if os.path.isdir(datain[ute_name]): fnew = os.path.basename(datain[ute_name]) run([Cnt['DCM2NIIX'], '-f', fnew, datain[ute_name]]) fute = glob.glob(os.path.join(datain[ute_name], fnew + '*nii*'))[0] elif os.path.isfile(datain[ute_name]): fute = datain[ute_name] # get the affine transformation if reg_tool == 'spm': regdct = nimpa.coreg_spm(fpet, fute, outpath=os.path.join(outpath, 'PET', 'positioning')) elif reg_tool == 'niftyreg': regdct = nimpa.affine_niftyreg( fpet, fute, outpath=os.path.join(outpath, 'PET', 'positioning'), executable=Cnt['REGPATH'], omp=multiprocessing.cpu_count() / 2, # pcomment=fcomment, rigOnly=True, affDirect=False, maxit=5, speed=True, pi=50, pv=50, smof=0, smor=0, rmsk=True, fmsk=True, rfwhm=15., # pillilitres rthrsh=0.05, ffwhm=15., # pillilitres fthrsh=0.05, verbose=verbose) else: raise ValueError('unknown registration tool requested') faff_mrpet = regdct['faff'] elif musrc == 'pct': ft1w = nimpa.pick_t1w(datain) if reg_tool == 'spm': regdct = nimpa.coreg_spm(fpet, ft1w, outpath=os.path.join(outpath, 'PET', 'positioning')) elif reg_tool == 'niftyreg': regdct = nimpa.affine_niftyreg( fpet, ft1w, outpath=os.path.join(outpath, 'PET', 'positioning'), executable=Cnt['REGPATH'], omp=multiprocessing.cpu_count() / 2, rigOnly=True, affDirect=False, maxit=5, speed=True, pi=50, pv=50, smof=0, smor=0, rmsk=True, fmsk=True, rfwhm=15., # pillilitres rthrsh=0.05, ffwhm=15., # pillilitres fthrsh=0.05, verbose=verbose) else: raise ValueError('unknown registration tool requested') faff_mrpet = regdct['faff'] else: raise IOError('Floating MR image not provided or is invalid.') else: faff_mrpet = faff regdct = {} if not os.path.isfile(fpet): raise IOError('e> the reference PET should be supplied with the affine.') # > output file name for the aligned mu-maps if musrc == 'pct': # > convert to mu-values before resampling to avoid artefacts with negative values nii = nib.load(datain['pCT']) img = nii.get_fdata(dtype=np.float32) img_mu = hu2mu(img) nii_mu = nib.Nifti1Image(img_mu, nii.affine) fflo = os.path.join(tmpdir, 'pct2mu-not-aligned.nii.gz') nib.save(nii_mu, fflo) freg = os.path.join(opth, 'pct2mu-aligned-' + fcomment + '.nii.gz') elif musrc == 'ute': freg = os.path.join(opth, 'UTE-res-tmp' + fcomment + '.nii.gz') if 'UTE' not in datain: fnii = 'converted-from-DICOM_' tstmp = nimpa.time_stamp(simple_ascii=True) # convert the DICOM mu-map images to nii if 'mumapDCM' not in datain: raise IOError('DICOM with the UTE mu-map are not given.') run([Cnt['DCM2NIIX'], '-f', fnii + tstmp, '-o', opth, datain['mumapDCM']]) # piles for the T1w, pick one: fflo = glob.glob(os.path.join(opth, '*' + fnii + tstmp + '*.nii*'))[0] else: if os.path.isfile(datain['UTE']): fflo = datain['UTE'] else: raise IOError('The provided NIfTI UTE path is not valid.') # > call the resampling routine to get the pCT/UTE in place if reg_tool == "spm": nimpa.resample_spm(fpet, fflo, faff_mrpet, fimout=freg, del_ref_uncmpr=True, del_flo_uncmpr=True, del_out_uncmpr=True) else: nimpa.resample_niftyreg(fpet, fflo, faff_mrpet, fimout=freg, executable=Cnt['RESPATH'], verbose=verbose) # -get the NIfTI of registered image nim = nib.load(freg) A = nim.affine imreg = nim.get_fdata(dtype=np.float32) imreg = imreg[:, ::-1, ::-1] imreg = np.transpose(imreg, (2, 1, 0)) # -convert to mu-values; sort out the file name too. if musrc == 'pct': mu = imreg elif musrc == 'ute': mu = np.float32(imreg) / 1e4 # -remove the converted file from DICOMs os.remove(fflo) else: raise NameError('Confused o_O') # > get rid of negatives and nans mu[mu < 0] = 0 mu[np.isnan(mu)] = 0 # > return image dictionary with the image itself and other parameters mu_dct['im'] = mu mu_dct['affine'] = A mu_dct['faff'] = faff_mrpet if store or store_npy: nimpa.create_dir(opth) if faff == '': fname = fnm + '-aligned-to_t'\ + str(t0)+'-'+str(t1)+'_'+petopt.upper()\ + fcomment else: fname = fnm + '-aligned-to-given-affine' + fcomment if store_npy: fnp = os.path.join(opth, fname + ".npz") np.savez(fnp, mu=mu, A=A) if store: # > NIfTI fmu = os.path.join(opth, fname + '.nii.gz') nimpa.array2nii(mu[::-1, ::-1, :], A, fmu) mu_dct['fim'] = fmu if del_auxilary: os.remove(freg) if musrc == 'ute' and not os.path.isfile(faff): os.remove(fute) shutil.rmtree(tmpdir) return mu_dct # ================================================================================ # PSEUDO CT MU-MAP # -------------------------------------------------------------------------------- def pct_mumap(datain, scanner_params, hst=None, t0=0, t1=0, itr=2, petopt='ac', faff='', fpet='', fcomment='', outpath='', store_npy=False, store=False, verbose=False): ''' GET THE MU-MAP from pCT IMAGE (which is in T1w space) * the mu-map will be registered to PET which will be reconstructed for time frame t0-t1 * it f0 and t1 are not given the whole LM dataset will be reconstructed * the reconstructed PET can be attenuation and scatter corrected or NOT using petopt ''' if hst is None: hst = [] # constants, transaxial and axial LUTs are extracted Cnt = scanner_params['Cnt'] if not os.path.isfile(faff): from niftypet.nipet.prj import mmrrec # histogram the list data if needed if not hst: from niftypet.nipet.lm import mmrhist hst = mmrhist(datain, scanner_params, t0=t0, t1=t1) # get hardware mu-map if datain.get("hmumap", "").endswith(".npz") and os.path.isfile(datain["hmumap"]): muh = np.load(datain["hmumap"], allow_pickle=True)["hmu"] (log.info if verbose else log.debug)('loaded hardware mu-map from file:\n{}'.format( datain['hmumap'])) elif outpath: hmupath = os.path.join(outpath, "mumap-hdw", "hmumap.npz") if os.path.isfile(hmupath): muh = np.load(hmupath, allow_pickle=True)["hmu"] datain['hmumap'] = hmupath else: raise IOError('Invalid path to the hardware mu-map') else: log.error('The hardware mu-map is required first.') raise IOError('Could not find the hardware mu-map!') if not {'MRT1W#', 'T1nii', 'T1bc'}.intersection(datain): log.error('no MR T1w images required for co-registration!') raise IOError('Missing MR data') # ---------------------------------- # output dictionary mu_dct = {} if not os.path.isfile(faff): # first recon pet to get the T1 aligned to it if petopt == 'qnt': # --------------------------------------------- # OPTION 1 (quantitative recon with all corrections using MR-based mu-map) # get UTE object mu-map (may not be in register with the PET data) mudic = obj_mumap(datain, Cnt) muo = mudic['im'] # reconstruct PET image with UTE mu-map to which co-register T1w recout = mmrrec.osemone(datain, [muh, muo], hst, scanner_params, recmod=3, itr=itr, fwhm=0., fcomment=fcomment + '_qntUTE', outpath=os.path.join(outpath, 'PET', 'positioning'), store_img=True) elif petopt == 'nac': # --------------------------------------------- # OPTION 2 (recon without any corrections for scatter and attenuation) # reconstruct PET image with UTE mu-map to which co-register T1w muo = np.zeros(muh.shape, dtype=muh.dtype) recout = mmrrec.osemone(datain, [muh, muo], hst, scanner_params, recmod=1, itr=itr, fwhm=0., fcomment=fcomment + '_NAC', outpath=os.path.join(outpath, 'PET', 'positioning'), store_img=True) elif petopt == 'ac': # --------------------------------------------- # OPTION 3 (recon with attenuation correction only but no scatter) # reconstruct PET image with UTE mu-map to which co-register T1w mudic = obj_mumap(datain, Cnt, outpath=outpath) muo = mudic['im'] recout = mmrrec.osemone(datain, [muh, muo], hst, scanner_params, recmod=1, itr=itr, fwhm=0., fcomment=fcomment + '_AC', outpath=os.path.join(outpath, 'PET', 'positioning'), store_img=True) fpet = recout.fpet mu_dct['fpet'] = fpet # ------------------------------ # get the affine transformation ft1w = nimpa.pick_t1w(datain) try: regdct = nimpa.coreg_spm(fpet, ft1w, outpath=os.path.join(outpath, 'PET', 'positioning')) except Exception: regdct = nimpa.affine_niftyreg( fpet, ft1w, outpath=os.path.join(outpath, 'PET', 'positioning'), # pcomment=fcomment, executable=Cnt['REGPATH'], omp=multiprocessing.cpu_count() / 2, rigOnly=True, affDirect=False, maxit=5, speed=True, pi=50, pv=50, smof=0, smor=0, rmsk=True, fmsk=True, rfwhm=15., # pillilitres rthrsh=0.05, ffwhm=15., # pillilitres fthrsh=0.05, verbose=verbose) faff = regdct['faff'] # ------------------------------ # pCT file name if outpath == '': pctdir = os.path.dirname(datain['pCT']) else: pctdir = os.path.join(outpath, 'mumap-obj') mmraux.create_dir(pctdir) fpct = os.path.join(pctdir, 'pCT_r_tmp' + fcomment + '.nii.gz') # > call the resampling routine to get the pCT in place if os.path.isfile(Cnt['RESPATH']): cmd = [ Cnt['RESPATH'], '-ref', fpet, '-flo', datain['pCT'], '-trans', faff, '-res', fpct, '-pad', '0'] if log.getEffectiveLevel() > logging.INFO: cmd.append('-voff') run(cmd) else: log.error('path to resampling executable is incorrect!') raise IOError('Incorrect path to executable!') # get the NIfTI of the pCT nim = nib.load(fpct) A = nim.get_sform() pct = nim.get_fdata(dtype=np.float32) pct = pct[:, ::-1, ::-1] pct = np.transpose(pct, (2, 1, 0)) # convert the HU units to mu-values mu = hu2mu(pct) # get rid of negatives mu[mu < 0] = 0 # return image dictionary with the image itself and other parameters mu_dct['im'] = mu mu_dct['affine'] = A mu_dct['faff'] = faff if store: # now save to numpy array and NIfTI in this folder if outpath == '': pctumapdir = os.path.join(datain['corepath'], 'mumap-obj') else: pctumapdir = os.path.join(outpath, 'mumap-obj') mmraux.create_dir(pctumapdir) # > Numpy if store_npy: fnp = os.path.join(pctumapdir, "mumap-pCT.npz") np.savez(fnp, mu=mu, A=A) # > NIfTI fmu = os.path.join(pctumapdir, 'mumap-pCT' + fcomment + '.nii.gz') nimpa.array2nii(mu[::-1, ::-1, :], A, fmu) mu_dct['fim'] = fmu datain['mumapCT'] = fmu return mu_dct # ******************************************************************************** # GET HARDWARE MU-MAPS with positions and offsets # -------------------------------------------------------------------------------- def hdr_mu(datain, Cnt): '''Get the headers from DICOM data file''' # pet one of the DICOM files of the mu-map if 'mumapDCM' in datain: files = glob.glob(os.path.join(datain['mumapDCM'], '*.dcm')) files.extend(glob.glob(os.path.join(datain['mumapDCM'], '*.DCM'))) files.extend(glob.glob(os.path.join(datain['mumapDCM'], '*.ima'))) files.extend(glob.glob(os.path.join(datain['mumapDCM'], '*.IMA'))) dcmf = files[0] else: raise NameError('no DICOM or DICOM filed <CSA Series Header Info> found!') if os.path.isfile(dcmf): dhdr = dcm.read_file(dcmf) else: log.error('DICOM mMR mu-maps are not valid files!') return None # CSA Series Header Info if [0x29, 0x1020] in dhdr: csahdr = dhdr[0x29, 0x1020].value log.info('got CSA mu-map info from the DICOM header.') return csahdr, dhdr def hmu_shape(hdr): # pegular expression to find the shape p = re.compile(r'(?<=:=)\s*\d{1,4}') # x: dim [1] i0 = hdr.find('matrix size[1]') i1 = i0 + hdr[i0:].find('\n') u = int(p.findall(hdr[i0:i1])[0]) # x: dim [2] i0 = hdr.find('matrix size[2]') i1 = i0 + hdr[i0:].find('\n') v = int(p.findall(hdr[i0:i1])[0]) # x: dim [3] i0 = hdr.find('matrix size[3]') i1 = i0 + hdr[i0:].find('\n') w = int(p.findall(hdr[i0:i1])[0]) return w, v, u def hmu_voxsize(hdr): # pegular expression to find the shape p = re.compile(r'(?<=:=)\s*\d{1,2}[.]\d{1,10}') # x: dim [1] i0 = hdr.find('scale factor (mm/pixel) [1]') i1 = i0 + hdr[i0:].find('\n') vx = float(p.findall(hdr[i0:i1])[0]) # x: dim [2] i0 = hdr.find('scale factor (mm/pixel) [2]') i1 = i0 + hdr[i0:].find('\n') vy = float(p.findall(hdr[i0:i1])[0]) # x: dim [3] i0 = hdr.find('scale factor (mm/pixel) [3]') i1 = i0 + hdr[i0:].find('\n') vz = float(p.findall(hdr[i0:i1])[0]) return np.array([0.1 * vz, 0.1 * vy, 0.1 * vx]) def hmu_origin(hdr): # pegular expression to find the origin p = re.compile(r'(?<=:=)\s*\d{1,5}[.]\d{1,10}') # x: dim [1] i0 = hdr.find('$umap origin (pixels) [1]') i1 = i0 + hdr[i0:].find('\n') x = float(p.findall(hdr[i0:i1])[0]) # x: dim [2] i0 = hdr.find('$umap origin (pixels) [2]') i1 = i0 + hdr[i0:].find('\n') y = float(p.findall(hdr[i0:i1])[0]) # x: dim [3] i0 = hdr.find('$umap origin (pixels) [3]') i1 = i0 + hdr[i0:].find('\n') z = -float(p.findall(hdr[i0:i1])[0]) return np.array([z, y, x]) def hmu_offset(hdr): # pegular expression to find the origin p = re.compile(r'(?<=:=)\s*\d{1,5}[.]\d{1,10}') if hdr.find('$origin offset') > 0: # x: dim [1] i0 = hdr.find('$origin offset (mm) [1]') i1 = i0 + hdr[i0:].find('\n') x = float(p.findall(hdr[i0:i1])[0]) # x: dim [2] i0 = hdr.find('$origin offset (mm) [2]') i1 = i0 + hdr[i0:].find('\n') y = float(p.findall(hdr[i0:i1])[0]) # x: dim [3] i0 = hdr.find('$origin offset (mm) [3]') i1 = i0 + hdr[i0:].find('\n') z = -float(p.findall(hdr[i0:i1])[0]) return np.array([0.1 * z, 0.1 * y, 0.1 * x]) else: return np.array([0.0, 0.0, 0.0]) def rd_hmu(fh): # --read hdr file-- f = open(fh, 'r') hdr = f.read() f.close() # ----------------- # pegular expression to find the file name p = re.compile(r'(?<=:=)\s*\w*[.]\w*') i0 = hdr.find('!name of data file') i1 = i0 + hdr[i0:].find('\n') fbin = p.findall(hdr[i0:i1])[0] # --read img file-- f = open(os.path.join(os.path.dirname(fh), fbin.strip()), 'rb') im = np.fromfile(f, np.float32) f.close() # ----------------- return hdr, im def get_hmupos(datain, parts, Cnt, outpath=''): # check if registration executable exists if not os.path.isfile(Cnt['RESPATH']): raise IOError('No registration executable found!') # ----- get positions from the DICOM list-mode file ----- ihdr, csainfo = mmraux.hdr_lm(datain, Cnt) # pable position origin fi = csainfo.find(b'TablePositionOrigin') tpostr = csainfo[fi:fi + 200] tpo = re.sub(b'[^a-zA-Z0-9.\\-]', b'', tpostr).split(b'M') tpozyx = np.array([float(tpo[-1]), float(tpo[-2]), float(tpo[-3])]) / 10 log.info('table position (z,y,x) (cm): {}'.format(tpozyx)) # -------------------------------------------------------- # ------- get positions from the DICOM mu-map file ------- csamu, dhdr = hdr_mu(datain, Cnt) # > get the indices where the table offset may reside: idxs = [m.start() for m in re.finditer(b'GantryTableHomeOffset(?!_)', csamu)] # > loop over the indices and find those which are correct found_off = False for i in idxs: gtostr1 = csamu[i:i + 300] gtostr2 = re.sub(b'[^a-zA-Z0-9.\\-]', b'', gtostr1) # gantry table offset, through conversion of string to float gtoxyz = re.findall(b'(?<=M)-*[\\d]{1,4}\\.[\\d]{6,9}', gtostr2) gtozyx = np.float32(gtoxyz)[::-1] / 10 if len(gtoxyz) > 3: log.warning('the gantry table offset got more than 3 entries detected--check needed.') gtozyx = gtozyx[-3:] if abs(gtozyx[0]) > 20 and abs(gtozyx[1]) < 20 and abs(gtozyx[2]) < 2: found_off = True break if found_off: log.info('gantry table offset (z,y,x) (cm): {}'.format(gtozyx)) else: raise ValueError('Could not find the gantry table offset or the offset is unusual.') # -------------------------------------------------------- # create the folder for hardware mu-maps if outpath == '': dirhmu = os.path.join(datain['corepath'], 'mumap-hdw') else: dirhmu = os.path.join(outpath, 'mumap-hdw') mmraux.create_dir(dirhmu) # get the reference nii image fref = os.path.join(dirhmu, 'hmuref.nii.gz') # ptart horizontal bed position p = re.compile(r'start horizontal bed position.*\d{1,3}\.*\d*') m = p.search(ihdr) fi = ihdr[m.start():m.end()].find('=') hbedpos = 0.1 * float(ihdr[m.start() + fi + 1:m.end()]) # ptart vertical bed position p = re.compile(r'start vertical bed position.*\d{1,3}\.*\d*') m = p.search(ihdr) fi = ihdr[m.start():m.end()].find('=') vbedpos = 0.1 * float(ihdr[m.start() + fi + 1:m.end()]) log.info('creating reference NIfTI image for resampling') B = np.diag(np.array([-10 * Cnt['SO_VXX'], 10 * Cnt['SO_VXY'], 10 * Cnt['SO_VXZ'], 1])) B[0, 3] = 10 * (.5 * Cnt['SO_IMX']) * Cnt['SO_VXX'] B[1, 3] = 10 * (-.5 * Cnt['SO_IMY'] + 1) * Cnt['SO_VXY'] B[2, 3] = 10 * ((-.5 * Cnt['SO_IMZ'] + 1) * Cnt['SO_VXZ'] + hbedpos) nimpa.array2nii(np.zeros((Cnt['SO_IMZ'], Cnt['SO_IMY'], Cnt['SO_IMX']), dtype=np.float32), B, fref) # pefine a dictionary of all positions/offsets of hardware mu-maps hmupos = [None] * 5 hmupos[0] = { 'TabPosOrg': tpozyx, # prom DICOM of LM file 'GanTabOff': gtozyx, # prom DICOM of mMR mu-map file 'HBedPos': hbedpos, # prom Interfile of LM file [cm] 'VBedPos': vbedpos, # prom Interfile of LM file [cm] 'niipath': fref} # -------------------------------------------------------------------------- # iteratively go through the mu-maps and add them as needed for i in parts: fh = os.path.join(Cnt['HMUDIR'], Cnt['HMULIST'][i - 1]) # get the interfile header and binary data hdr, im = rd_hmu(fh) # pet shape, origin, offset and voxel size s = hmu_shape(hdr) im.shape = s # get the origin, offset and voxel size for the mu-map interfile data org = hmu_origin(hdr) off = hmu_offset(hdr) vs = hmu_voxsize(hdr) # corner voxel position for the interfile image data vpos = (-org * vs + off + gtozyx - tpozyx) # pdd to the dictionary hmupos[i] = { 'vpos': vpos, 'shape': s, # prom interfile 'iorg': org, # prom interfile 'ioff': off, # prom interfile 'ivs': vs, # prom interfile 'img': im, # prom interfile 'niipath': os.path.join(dirhmu, '_' + Cnt['HMULIST'][i - 1].split('.')[0] + '.nii.gz')} log.info('creating mu-map for: {}'.format(Cnt['HMULIST'][i - 1])) A = np.diag(np.append(10 * vs[::-1], 1)) A[0, 0] *= -1 A[0, 3] = 10 * (-vpos[2]) A[1, 3] = -10 * ((s[1] - 1) * vs[1] + vpos[1]) A[2, 3] = -10 * ((s[0] - 1) * vs[0] - vpos[0]) nimpa.array2nii(im[::-1, ::-1, :], A, hmupos[i]['niipath']) # resample using nify.reg fout = os.path.join(os.path.dirname(hmupos[0]['niipath']), 'r' + os.path.basename(hmupos[i]['niipath']).split('.')[0] + '.nii.gz') cmd = [ Cnt['RESPATH'], '-ref', hmupos[0]['niipath'], '-flo', hmupos[i]['niipath'], '-res', fout, '-pad', '0'] if log.getEffectiveLevel() > logging.INFO: cmd.append('-voff') run(cmd) return hmupos def hdw_mumap(datain, hparts, params, outpath='', use_stored=False, del_interm=True): '''Get hardware mu-map components, including bed, coils etc.''' # two ways of passing Cnt are here decoded if 'Cnt' in params: Cnt = params['Cnt'] else: Cnt = params if outpath != '': fmudir = os.path.join(outpath, 'mumap-hdw') else: fmudir = os.path.join(datain['corepath'], 'mumap-hdw') nimpa.create_dir(fmudir) # if requested to use the stored hardware mu_map get it from the path in datain if use_stored and "hmumap" in datain and os.path.isfile(datain["hmumap"]): if datain['hmumap'].endswith(('.nii', '.nii.gz')): dct = nimpa.getnii(datain['hmumap'], output='all') hmu = dct['im'] A = dct['affine'] fmu = datain['hmumap'] elif datain["hmumap"].endswith(".npz"): arr = np.load(datain["hmumap"], allow_pickle=True) hmu, A, fmu = arr["hmu"], arr["A"], arr["fmu"] log.info('loaded hardware mu-map from file: {}'.format(datain['hmumap'])) fnp = datain['hmumap'] elif outpath and os.path.isfile(os.path.join(fmudir, "hmumap.npz")): fnp = os.path.join(fmudir, "hmumap.npz") arr = np.load(fnp, allow_pickle=True) hmu, A, fmu = arr["hmu"], arr["A"], arr["fmu"] datain['hmumap'] = fnp # otherwise generate it from the parts through resampling the high resolution CT images else: hmupos = get_hmupos(datain, hparts, Cnt, outpath=outpath) # just to get the dims, get the ref image nimo = nib.load(hmupos[0]['niipath']) A = nimo.affine imo = nimo.get_fdata(dtype=np.float32) imo[:] = 0 for i in hparts: fin = os.path.join( os.path.dirname(hmupos[0]['niipath']), 'r' + os.path.basename(hmupos[i]['niipath']).split('.')[0] + '.nii.gz') nim = nib.load(fin) mu = nim.get_fdata(dtype=np.float32) mu[mu < 0] = 0 imo += mu hdr = nimo.header hdr['cal_max'] = np.max(imo) hdr['cal_min'] = np.min(imo) fmu = os.path.join(os.path.dirname(hmupos[0]['niipath']), 'hardware_umap.nii.gz') hmu_nii = nib.Nifti1Image(imo, A) nib.save(hmu_nii, fmu) hmu = np.transpose(imo[:, ::-1, ::-1], (2, 1, 0)) # save the objects to numpy arrays fnp = os.path.join(fmudir, "hmumap.npz") np.savez(fnp, hmu=hmu, A=A, fmu=fmu) # ppdate the datain dictionary (assuming it is mutable) datain['hmumap'] = fnp if del_interm: for fname in glob.glob(os.path.join(fmudir, '_*.nii*')): os.remove(fname) for fname in glob.glob(os.path.join(fmudir, 'r_*.nii*')): os.remove(fname) # peturn image dictionary with the image itself and some other stats hmu_dct = {'im': hmu, 'fim': fmu, 'affine': A} if 'fnp' in locals(): hmu_dct['fnp'] = fnp return hmu_dct def rmumaps(datain, Cnt, t0=0, t1=0, use_stored=False): ''' get the mu-maps for hardware and object and trim it axially for reduced rings case ''' from niftypet.nipet.lm import mmrhist from niftypet.nipet.prj import mmrrec fcomment = '(R)' # get hardware mu-map if os.path.isfile(datain['hmumap']) and use_stored: muh = np.load(datain["hmumap"], allow_pickle=True)["hmu"] log.info('loaded hardware mu-map from file:\n{}'.format(datain['hmumap'])) else: hmudic = hdw_mumap(datain, [1, 2, 4], Cnt) muh = hmudic['im'] # get pCT mu-map if stored in numpy file and then exit, otherwise do all the processing if os.path.isfile(datain['mumapCT']) and use_stored: mup = np.load(datain["mumapCT"], allow_pickle=True)["mu"] muh = muh[2 * Cnt['RNG_STRT']:2 * Cnt['RNG_END'], :, :] mup = mup[2 * Cnt['RNG_STRT']:2 * Cnt['RNG_END'], :, :] return [muh, mup] # get UTE object mu-map (may be not in register with the PET data) if os.path.isfile(datain['mumapUTE']) and use_stored: muo, _ = np.load(datain['mumapUTE'], allow_pickle=True) else: mudic = obj_mumap(datain, Cnt, store=True) muo = mudic['im'] if os.path.isfile(datain['pCT']): # reconstruct PET image with default settings to be used to alight pCT mu-map params = mmraux.get_mmrparams() Cnt_ = params['Cnt'] txLUT_ = params['txLUT'] axLUT_ = params['axLUT'] # histogram for reconstruction with UTE mu-map hst = mmrhist.hist(datain, txLUT_, axLUT_, Cnt_, t0=t0, t1=t1) # reconstruct PET image with UTE mu-map to which co-register T1w recute = mmrrec.osemone(datain, [muh, muo], hst, params, recmod=3, itr=4, fwhm=0., store_img=True, fcomment=fcomment + '_QNT-UTE') # --- MR T1w if os.path.isfile(datain['T1nii']): ft1w = datain['T1nii'] elif os.path.isfile(datain['T1bc']): ft1w = datain['T1bc'] elif os.path.isdir(datain['MRT1W']): # create file name for the converted NIfTI image fnii = 'converted' run([Cnt['DCM2NIIX'], '-f', fnii, datain['T1nii']]) ft1nii = glob.glob(os.path.join(datain['T1nii'], '*converted*.nii*')) ft1w = ft1nii[0] else: raise IOError('Disaster: no T1w image!') # putput for the T1w in register with PET ft1out = os.path.join(os.path.dirname(ft1w), 'T1w_r' + '.nii.gz') # pext file fo rthe affine transform T1w->PET faff = os.path.join(os.path.dirname(ft1w), fcomment + 'mr2pet_affine' + '.txt') # time.strftime('%d%b%y_%H.%M',time.gmtime()) # > call the registration routine if os.path.isfile(Cnt['REGPATH']): cmd = [ Cnt['REGPATH'], '-ref', recute.fpet, '-flo', ft1w, '-rigOnly', '-speeeeed', '-aff', faff, '-res', ft1out] if log.getEffectiveLevel() > logging.INFO: cmd.append('-voff') run(cmd) else: raise IOError('Path to registration executable is incorrect!') # pet the pCT mu-map with the above faff pmudic = pct_mumap(datain, txLUT_, axLUT_, Cnt, faff=faff, fpet=recute.fpet, fcomment=fcomment) mup = pmudic['im'] muh = muh[2 * Cnt['RNG_STRT']:2 * Cnt['RNG_END'], :, :] mup = mup[2 * Cnt['RNG_STRT']:2 * Cnt['RNG_END'], :, :] return [muh, mup] else: muh = muh[2 * Cnt['RNG_STRT']:2 * Cnt['RNG_END'], :, :] muo = muo[2 * Cnt['RNG_STRT']:2 * Cnt['RNG_END'], :, :] return [muh, muo]
[ "os.remove", "numpy.load", "numpy.sum", "niftypet.nipet.lm.mmrhist", "re.finditer", "numpy.floor", "numpy.isnan", "os.path.isfile", "numpy.arange", "shutil.rmtree", "niftypet.nipet.lm.mmrhist.hist", "os.path.join", "multiprocessing.cpu_count", "niftypet.nimpa.dcm2im", "os.path.dirname", "numpy.transpose", "niftypet.nimpa.pick_t1w", "os.path.exists", "nibabel.save", "numpy.append", "numpy.max", "re.findall", "math.cos", "re.sub", "niftypet.nimpa.time_stamp", "numpy.repeat", "nibabel.Nifti1Image", "numpy.ceil", "os.path.basename", "math.sin", "niftypet.nimpa.prc.improc.resample", "numpy.min", "numpy.savez", "niftypet.nimpa.array2nii", "os.listdir", "numpy.concatenate", "re.compile", "niftypet.nimpa.resample_niftyreg", "subprocess.run", "niftypet.nimpa.resample_spm", "nibabel.load", "pydicom.read_file", "numpy.fromfile", "os.path.isdir", "numpy.float32", "niftypet.nimpa.getnii", "numpy.zeros", "niftypet.nimpa.create_dir", "numpy.array", "niftypet.nipet.prj.mmrrec.osemone", "logging.getLogger" ]
[((343, 370), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (360, 370), False, 'import logging\n'), ((388, 413), 'numpy.array', 'np.array', (['[0.0, 0.0, 0.0]'], {}), '([0.0, 0.0, 0.0])\n', (396, 413), True, 'import numpy as np\n'), ((813, 841), 'numpy.transpose', 'np.transpose', (['img', '(2, 0, 1)'], {}), '(img, (2, 0, 1))\n', (825, 841), True, 'import numpy as np\n'), ((923, 979), 'numpy.zeros', 'np.zeros', (["(nvz, Cnt['SZ_IMY'], margin)"], {'dtype': 'np.float32'}), "((nvz, Cnt['SZ_IMY'], margin), dtype=np.float32)\n", (931, 979), True, 'import numpy as np\n'), ((990, 1035), 'numpy.concatenate', 'np.concatenate', (['(filler, imo, filler)'], {'axis': '(2)'}), '((filler, imo, filler), axis=2)\n', (1004, 1035), True, 'import numpy as np\n'), ((1093, 1149), 'numpy.zeros', 'np.zeros', (["(nvz, margin, Cnt['SO_IMX'])"], {'dtype': 'np.float32'}), "((nvz, margin, Cnt['SO_IMX']), dtype=np.float32)\n", (1101, 1149), True, 'import numpy as np\n'), ((1160, 1205), 'numpy.concatenate', 'np.concatenate', (['(filler, imo, filler)'], {'axis': '(1)'}), '((filler, imo, filler), axis=1)\n', (1174, 1205), True, 'import numpy as np\n'), ((1775, 1846), 'numpy.zeros', 'np.zeros', (["(im.shape[0], Cnt['SZ_IMY'], Cnt['SZ_IMX'])"], {'dtype': 'np.float32'}), "((im.shape[0], Cnt['SZ_IMY'], Cnt['SZ_IMX']), dtype=np.float32)\n", (1783, 1846), True, 'import numpy as np\n'), ((2055, 2087), 'numpy.transpose', 'np.transpose', (['im_sqzd', '(1, 2, 0)'], {}), '(im_sqzd, (1, 2, 0))\n', (2067, 2087), True, 'import numpy as np\n'), ((4813, 4949), 'numpy.array', 'np.array', (['[[1.0, 0.0, 0.0, Offst[0]], [0.0, 1.0, 0.0, Offst[1]], [0.0, 0.0, 1.0,\n Offst[2]], [0.0, 0.0, 0.0, 1.0]]'], {'dtype': 'np.float32'}), '([[1.0, 0.0, 0.0, Offst[0]], [0.0, 1.0, 0.0, Offst[1]], [0.0, 0.0, \n 1.0, Offst[2]], [0.0, 0.0, 0.0, 1.0]], dtype=np.float32)\n', (4821, 4949), True, 'import numpy as np\n'), ((5003, 5040), 'niftypet.nimpa.prc.improc.resample', 'nimpa.prc.improc.resample', (['mu', 'A', 'Cim'], {}), '(mu, A, Cim)\n', (5028, 5040), False, 'from niftypet import nimpa\n'), ((5311, 5337), 'numpy.fromfile', 'np.fromfile', (['f', 'np.float32'], {}), '(f, np.float32)\n', (5322, 5337), True, 'import numpy as np\n'), ((5682, 5693), 'numpy.max', 'np.max', (['mur'], {}), '(mur)\n', (5688, 5693), True, 'import numpy as np\n'), ((5706, 5717), 'numpy.min', 'np.min', (['mur'], {}), '(mur)\n', (5712, 5717), True, 'import numpy as np\n'), ((5791, 5816), 'numpy.sum', 'np.sum', (['(mur > 0.1 * mumax)'], {}), '(mur > 0.1 * mumax)\n', (5797, 5816), True, 'import numpy as np\n'), ((6176, 6202), 'numpy.fromfile', 'np.fromfile', (['f', 'np.float32'], {}), '(f, np.float32)\n', (6187, 6202), True, 'import numpy as np\n'), ((6392, 6402), 'numpy.max', 'np.max', (['im'], {}), '(im)\n', (6398, 6402), True, 'import numpy as np\n'), ((6415, 6425), 'numpy.min', 'np.min', (['im'], {}), '(im)\n', (6421, 6425), True, 'import numpy as np\n'), ((6498, 6522), 'numpy.sum', 'np.sum', (['(im > 0.1 * immax)'], {}), '(im > 0.1 * immax)\n', (6504, 6522), True, 'import numpy as np\n'), ((7041, 7102), 'numpy.zeros', 'np.zeros', (["(1, Cnt['SO_IMX'], Cnt['SO_IMY'])"], {'dtype': 'np.float32'}), "((1, Cnt['SO_IMX'], Cnt['SO_IMY']), dtype=np.float32)\n", (7049, 7102), True, 'import numpy as np\n'), ((7116, 7158), 'numpy.arange', 'np.arange', (['(0)', 'math.pi', '(math.pi / (2 * 360))'], {}), '(0, math.pi, math.pi / (2 * 360))\n', (7125, 7158), True, 'import numpy as np\n'), ((7562, 7591), 'numpy.repeat', 'np.repeat', (['imdsk', 'nvz'], {'axis': '(0)'}), '(imdsk, nvz, axis=0)\n', (7571, 7591), True, 'import numpy as np\n'), ((7905, 7941), 'numpy.zeros', 'np.zeros', (['im.shape'], {'dtype': 'np.float32'}), '(im.shape, dtype=np.float32)\n', (7913, 7941), True, 'import numpy as np\n'), ((8439, 8471), 'niftypet.nimpa.dcm2im', 'nimpa.dcm2im', (["datain['mumapDCM']"], {}), "(datain['mumapDCM'])\n", (8451, 8471), False, 'from niftypet import nimpa\n'), ((8936, 8997), 're.compile', 're.compile', (['"""start horizontal bed position.*\\\\d{1,3}\\\\.*\\\\d*"""'], {}), "('start horizontal bed position.*\\\\d{1,3}\\\\.*\\\\d*')\n", (8946, 8997), False, 'import re\n'), ((9446, 9519), 'numpy.zeros', 'np.zeros', (["(Cnt['SO_IMZ'], Cnt['SO_IMY'], Cnt['SO_IMX'])"], {'dtype': 'np.float32'}), "((Cnt['SO_IMZ'], Cnt['SO_IMY'], Cnt['SO_IMX']), dtype=np.float32)\n", (9454, 9519), True, 'import numpy as np\n'), ((9788, 9818), 'os.path.isfile', 'os.path.isfile', (["Cnt['RESPATH']"], {}), "(Cnt['RESPATH'])\n", (9802, 9818), False, 'import os\n'), ((10885, 10909), 'niftypet.nimpa.create_dir', 'nimpa.create_dir', (['fmudir'], {}), '(fmudir)\n', (10901, 10909), False, 'from niftypet import nimpa\n'), ((10946, 10982), 'os.path.join', 'os.path.join', (['fmudir', '"""muref.nii.gz"""'], {}), "(fmudir, 'muref.nii.gz')\n", (10958, 10982), False, 'import os\n'), ((11102, 11175), 'numpy.zeros', 'np.zeros', (["(Cnt['SO_IMZ'], Cnt['SO_IMY'], Cnt['SO_IMX'])"], {'dtype': 'np.float32'}), "((Cnt['SO_IMZ'], Cnt['SO_IMY'], Cnt['SO_IMX']), dtype=np.float32)\n", (11110, 11175), True, 'import numpy as np\n'), ((11205, 11235), 'niftypet.nimpa.array2nii', 'nimpa.array2nii', (['im', 'B', 'fmuref'], {}), '(im, B, fmuref)\n', (11220, 11235), False, 'from niftypet import nimpa\n'), ((11516, 11551), 'niftypet.nimpa.time_stamp', 'nimpa.time_stamp', ([], {'simple_ascii': '(True)'}), '(simple_ascii=True)\n', (11532, 11551), False, 'from niftypet import nimpa\n'), ((11771, 11847), 'subprocess.run', 'run', (["[Cnt['DCM2NIIX'], '-f', fnii + tstmp, '-o', fmudir, datain['mumapDCM']]"], {}), "([Cnt['DCM2NIIX'], '-f', fnii + tstmp, '-o', fmudir, datain['mumapDCM']])\n", (11774, 11847), False, 'from subprocess import run\n'), ((12140, 12190), 'os.path.join', 'os.path.join', (['fmudir', "(comment + 'mumap_tmp.nii.gz')"], {}), "(fmudir, comment + 'mumap_tmp.nii.gz')\n", (12152, 12190), False, 'import os\n'), ((12198, 12228), 'os.path.isfile', 'os.path.isfile', (["Cnt['RESPATH']"], {}), "(Cnt['RESPATH'])\n", (12212, 12228), False, 'import os\n'), ((12563, 12576), 'nibabel.load', 'nib.load', (['fmu'], {}), '(fmu)\n', (12571, 12576), True, 'import nibabel as nib\n'), ((12682, 12724), 'numpy.transpose', 'np.transpose', (['mu[:, ::-1, ::-1]', '(2, 1, 0)'], {}), '(mu[:, ::-1, ::-1], (2, 1, 0))\n', (12694, 12724), True, 'import numpy as np\n'), ((14742, 14764), 'niftypet.nimpa.create_dir', 'nimpa.create_dir', (['opth'], {}), '(opth)\n', (14758, 14764), False, 'from niftypet import nimpa\n'), ((15839, 15864), 'os.path.join', 'os.path.join', (['opth', '"""tmp"""'], {}), "(opth, 'tmp')\n", (15851, 15864), False, 'import os\n'), ((15869, 15893), 'niftypet.nimpa.create_dir', 'nimpa.create_dir', (['tmpdir'], {}), '(tmpdir)\n', (15885, 15893), False, 'from niftypet import nimpa\n'), ((25368, 25382), 'nibabel.load', 'nib.load', (['freg'], {}), '(freg)\n', (25376, 25382), True, 'import nibabel as nib\n'), ((25491, 25521), 'numpy.transpose', 'np.transpose', (['imreg', '(2, 1, 0)'], {}), '(imreg, (2, 1, 0))\n', (25503, 25521), True, 'import numpy as np\n'), ((32405, 32461), 'os.path.join', 'os.path.join', (['pctdir', "('pCT_r_tmp' + fcomment + '.nii.gz')"], {}), "(pctdir, 'pCT_r_tmp' + fcomment + '.nii.gz')\n", (32417, 32461), False, 'import os\n'), ((32530, 32560), 'os.path.isfile', 'os.path.isfile', (["Cnt['RESPATH']"], {}), "(Cnt['RESPATH'])\n", (32544, 32560), False, 'import os\n'), ((32970, 32984), 'nibabel.load', 'nib.load', (['fpct'], {}), '(fpct)\n', (32978, 32984), True, 'import nibabel as nib\n'), ((33090, 33118), 'numpy.transpose', 'np.transpose', (['pct', '(2, 1, 0)'], {}), '(pct, (2, 1, 0))\n', (33102, 33118), True, 'import numpy as np\n'), ((34803, 34823), 'os.path.isfile', 'os.path.isfile', (['dcmf'], {}), '(dcmf)\n', (34817, 34823), False, 'import os\n'), ((35212, 35245), 're.compile', 're.compile', (['"""(?<=:=)\\\\s*\\\\d{1,4}"""'], {}), "('(?<=:=)\\\\s*\\\\d{1,4}')\n", (35222, 35245), False, 'import re\n'), ((35714, 35759), 're.compile', 're.compile', (['"""(?<=:=)\\\\s*\\\\d{1,2}[.]\\\\d{1,10}"""'], {}), "('(?<=:=)\\\\s*\\\\d{1,2}[.]\\\\d{1,10}')\n", (35724, 35759), False, 'import re\n'), ((36192, 36232), 'numpy.array', 'np.array', (['[0.1 * vz, 0.1 * vy, 0.1 * vx]'], {}), '([0.1 * vz, 0.1 * vy, 0.1 * vx])\n', (36200, 36232), True, 'import numpy as np\n'), ((36308, 36353), 're.compile', 're.compile', (['"""(?<=:=)\\\\s*\\\\d{1,5}[.]\\\\d{1,10}"""'], {}), "('(?<=:=)\\\\s*\\\\d{1,5}[.]\\\\d{1,10}')\n", (36318, 36353), False, 'import re\n'), ((36778, 36797), 'numpy.array', 'np.array', (['[z, y, x]'], {}), '([z, y, x])\n', (36786, 36797), True, 'import numpy as np\n'), ((36873, 36918), 're.compile', 're.compile', (['"""(?<=:=)\\\\s*\\\\d{1,5}[.]\\\\d{1,10}"""'], {}), "('(?<=:=)\\\\s*\\\\d{1,5}[.]\\\\d{1,10}')\n", (36883, 36918), False, 'import re\n'), ((37693, 37729), 're.compile', 're.compile', (['"""(?<=:=)\\\\s*\\\\w*[.]\\\\w*"""'], {}), "('(?<=:=)\\\\s*\\\\w*[.]\\\\w*')\n", (37703, 37729), False, 'import re\n'), ((37939, 37965), 'numpy.fromfile', 'np.fromfile', (['f', 'np.float32'], {}), '(f, np.float32)\n', (37950, 37965), True, 'import numpy as np\n'), ((40146, 40183), 'os.path.join', 'os.path.join', (['dirhmu', '"""hmuref.nii.gz"""'], {}), "(dirhmu, 'hmuref.nii.gz')\n", (40158, 40183), False, 'import os\n'), ((40229, 40290), 're.compile', 're.compile', (['"""start horizontal bed position.*\\\\d{1,3}\\\\.*\\\\d*"""'], {}), "('start horizontal bed position.*\\\\d{1,3}\\\\.*\\\\d*')\n", (40239, 40290), False, 'import re\n'), ((40458, 40517), 're.compile', 're.compile', (['"""start vertical bed position.*\\\\d{1,3}\\\\.*\\\\d*"""'], {}), "('start vertical bed position.*\\\\d{1,3}\\\\.*\\\\d*')\n", (40468, 40517), False, 'import re\n'), ((43832, 43856), 'niftypet.nimpa.create_dir', 'nimpa.create_dir', (['fmudir'], {}), '(fmudir)\n', (43848, 43856), False, 'from niftypet import nimpa\n'), ((47697, 47726), 'os.path.isfile', 'os.path.isfile', (["datain['pCT']"], {}), "(datain['pCT'])\n", (47711, 47726), False, 'import os\n'), ((2747, 2815), 'niftypet.nimpa.array2nii', 'nimpa.array2nii', (['cim[::-1, ::-1, :]', 'B', 'store_pth'], {'descrip': '"""cropped"""'}), "(cim[::-1, ::-1, :], B, store_pth, descrip='cropped')\n", (2762, 2815), False, 'from niftypet import nimpa\n'), ((3195, 3206), 'numpy.zeros', 'np.zeros', (['(3)'], {}), '(3)\n', (3203, 3206), True, 'import numpy as np\n'), ((3429, 3503), 'numpy.array', 'np.array', (["[-10 * Cnt['SO_VXX'], 10 * Cnt['SO_VXY'], 10 * Cnt['SO_VXZ'], 1]"], {}), "([-10 * Cnt['SO_VXX'], 10 * Cnt['SO_VXY'], 10 * Cnt['SO_VXZ'], 1])\n", (3437, 3503), True, 'import numpy as np\n'), ((7241, 7285), 'numpy.arange', 'np.arange', (['(-y + 2 * yo)', 'y', "(Cnt['SO_VXY'] / 2)"], {}), "(-y + 2 * yo, y, Cnt['SO_VXY'] / 2)\n", (7250, 7285), True, 'import numpy as np\n'), ((7775, 7787), 'numpy.isnan', 'np.isnan', (['im'], {}), '(im)\n', (7783, 7787), True, 'import numpy as np\n'), ((9139, 9213), 'numpy.array', 'np.array', (["[-10 * Cnt['SO_VXX'], 10 * Cnt['SO_VXY'], 10 * Cnt['SO_VXZ'], 1]"], {}), "([-10 * Cnt['SO_VXX'], 10 * Cnt['SO_VXY'], 10 * Cnt['SO_VXZ'], 1])\n", (9147, 9213), True, 'import numpy as np\n'), ((9729, 9764), 'os.path.dirname', 'os.path.dirname', (["datain['mumapDCM']"], {}), "(datain['mumapDCM'])\n", (9744, 9764), False, 'import os\n'), ((10773, 10818), 'os.path.join', 'os.path.join', (["datain['corepath']", '"""mumap-obj"""'], {}), "(datain['corepath'], 'mumap-obj')\n", (10785, 10818), False, 'import os\n'), ((10846, 10880), 'os.path.join', 'os.path.join', (['outpath', '"""mumap-obj"""'], {}), "(outpath, 'mumap-obj')\n", (10858, 10880), False, 'import os\n'), ((11634, 11677), 'os.path.join', 'os.path.join', (['fmudir', "('*' + fnii + '*.nii*')"], {}), "(fmudir, '*' + fnii + '*.nii*')\n", (11646, 11677), False, 'import os\n'), ((11708, 11720), 'os.remove', 'os.remove', (['d'], {}), '(d)\n', (11717, 11720), False, 'import os\n'), ((12410, 12418), 'subprocess.run', 'run', (['cmd'], {}), '(cmd)\n', (12413, 12418), False, 'from subprocess import run\n'), ((12761, 12775), 'numpy.float32', 'np.float32', (['mu'], {}), '(mu)\n', (12771, 12775), True, 'import numpy as np\n'), ((13069, 13113), 'os.path.join', 'os.path.join', (['fmudir', '"""mumap-from-DICOM.npz"""'], {}), "(fmudir, 'mumap-from-DICOM.npz')\n", (13081, 13113), False, 'import os\n'), ((13122, 13147), 'numpy.savez', 'np.savez', (['fnp'], {'mu': 'mu', 'A': 'A'}), '(fnp, mu=mu, A=A)\n', (13130, 13147), True, 'import numpy as np\n'), ((13210, 13285), 'os.path.join', 'os.path.join', (['fmudir', "('mumap-from-DICOM_no-alignment' + comment + '.nii.gz')"], {}), "(fmudir, 'mumap-from-DICOM_no-alignment' + comment + '.nii.gz')\n", (13222, 13285), False, 'import os\n'), ((13294, 13339), 'niftypet.nimpa.array2nii', 'nimpa.array2nii', (['mu[::-1, ::-1, :]', 'A', 'fmumap'], {}), '(mu[::-1, ::-1, :], A, fmumap)\n', (13309, 13339), False, 'from niftypet import nimpa\n'), ((13401, 13418), 'os.remove', 'os.remove', (['fmuref'], {}), '(fmuref)\n', (13410, 13418), False, 'import os\n'), ((13427, 13444), 'os.remove', 'os.remove', (['fmunii'], {}), '(fmunii)\n', (13436, 13444), False, 'import os\n'), ((13453, 13467), 'os.remove', 'os.remove', (['fmu'], {}), '(fmu)\n', (13462, 13467), False, 'import os\n'), ((14588, 14633), 'os.path.join', 'os.path.join', (["datain['corepath']", '"""mumap-obj"""'], {}), "(datain['corepath'], 'mumap-obj')\n", (14600, 14633), False, 'import os\n'), ((14659, 14693), 'os.path.join', 'os.path.join', (['outpath', '"""mumap-obj"""'], {}), "(outpath, 'mumap-obj')\n", (14671, 14693), False, 'import os\n'), ((15354, 15396), 'os.path.join', 'os.path.join', (['opth', "(fmu_stored + '.nii.gz')"], {}), "(opth, fmu_stored + '.nii.gz')\n", (15366, 15396), False, 'import os\n'), ((15409, 15432), 'os.path.isfile', 'os.path.isfile', (['fmupath'], {}), '(fmupath)\n', (15423, 15432), False, 'import os\n'), ((16239, 16259), 'os.path.isfile', 'os.path.isfile', (['faff'], {}), '(faff)\n', (16253, 16259), False, 'import os\n'), ((16808, 16840), 'os.path.isfile', 'os.path.isfile', (["datain['hmumap']"], {}), "(datain['hmumap'])\n", (16822, 16840), False, 'import os\n'), ((17961, 17981), 'os.path.isfile', 'os.path.isfile', (['faff'], {}), '(faff)\n', (17975, 17981), False, 'import os\n'), ((23792, 23815), 'nibabel.load', 'nib.load', (["datain['pCT']"], {}), "(datain['pCT'])\n", (23800, 23815), True, 'import nibabel as nib\n'), ((23907, 23942), 'nibabel.Nifti1Image', 'nib.Nifti1Image', (['img_mu', 'nii.affine'], {}), '(img_mu, nii.affine)\n', (23922, 23942), True, 'import nibabel as nib\n'), ((23958, 24007), 'os.path.join', 'os.path.join', (['tmpdir', '"""pct2mu-not-aligned.nii.gz"""'], {}), "(tmpdir, 'pct2mu-not-aligned.nii.gz')\n", (23970, 24007), False, 'import os\n'), ((24016, 24038), 'nibabel.save', 'nib.save', (['nii_mu', 'fflo'], {}), '(nii_mu, fflo)\n', (24024, 24038), True, 'import nibabel as nib\n'), ((24055, 24115), 'os.path.join', 'os.path.join', (['opth', "('pct2mu-aligned-' + fcomment + '.nii.gz')"], {}), "(opth, 'pct2mu-aligned-' + fcomment + '.nii.gz')\n", (24067, 24115), False, 'import os\n'), ((25015, 25137), 'niftypet.nimpa.resample_spm', 'nimpa.resample_spm', (['fpet', 'fflo', 'faff_mrpet'], {'fimout': 'freg', 'del_ref_uncmpr': '(True)', 'del_flo_uncmpr': '(True)', 'del_out_uncmpr': '(True)'}), '(fpet, fflo, faff_mrpet, fimout=freg, del_ref_uncmpr=True,\n del_flo_uncmpr=True, del_out_uncmpr=True)\n', (25033, 25137), False, 'from niftypet import nimpa\n'), ((25179, 25288), 'niftypet.nimpa.resample_niftyreg', 'nimpa.resample_niftyreg', (['fpet', 'fflo', 'faff_mrpet'], {'fimout': 'freg', 'executable': "Cnt['RESPATH']", 'verbose': 'verbose'}), "(fpet, fflo, faff_mrpet, fimout=freg, executable=Cnt\n ['RESPATH'], verbose=verbose)\n", (25202, 25288), False, 'from niftypet import nimpa\n'), ((25872, 25884), 'numpy.isnan', 'np.isnan', (['mu'], {}), '(mu)\n', (25880, 25884), True, 'import numpy as np\n'), ((26081, 26103), 'niftypet.nimpa.create_dir', 'nimpa.create_dir', (['opth'], {}), '(opth)\n', (26097, 26103), False, 'from niftypet import nimpa\n'), ((26373, 26407), 'os.path.join', 'os.path.join', (['opth', "(fname + '.npz')"], {}), "(opth, fname + '.npz')\n", (26385, 26407), False, 'import os\n'), ((26416, 26441), 'numpy.savez', 'np.savez', (['fnp'], {'mu': 'mu', 'A': 'A'}), '(fnp, mu=mu, A=A)\n', (26424, 26441), True, 'import numpy as np\n'), ((26488, 26525), 'os.path.join', 'os.path.join', (['opth', "(fname + '.nii.gz')"], {}), "(opth, fname + '.nii.gz')\n", (26500, 26525), False, 'import os\n'), ((26534, 26576), 'niftypet.nimpa.array2nii', 'nimpa.array2nii', (['mu[::-1, ::-1, :]', 'A', 'fmu'], {}), '(mu[::-1, ::-1, :], A, fmu)\n', (26549, 26576), False, 'from niftypet import nimpa\n'), ((26635, 26650), 'os.remove', 'os.remove', (['freg'], {}), '(freg)\n', (26644, 26650), False, 'import os\n'), ((26744, 26765), 'shutil.rmtree', 'shutil.rmtree', (['tmpdir'], {}), '(tmpdir)\n', (26757, 26765), False, 'import shutil\n'), ((27627, 27647), 'os.path.isfile', 'os.path.isfile', (['faff'], {}), '(faff)\n', (27641, 27647), False, 'import os\n'), ((27954, 27986), 'os.path.isfile', 'os.path.isfile', (["datain['hmumap']"], {}), "(datain['hmumap'])\n", (27968, 27986), False, 'import os\n'), ((28873, 28893), 'os.path.isfile', 'os.path.isfile', (['faff'], {}), '(faff)\n', (28887, 28893), False, 'import os\n'), ((31143, 31165), 'niftypet.nimpa.pick_t1w', 'nimpa.pick_t1w', (['datain'], {}), '(datain)\n', (31157, 31165), False, 'from niftypet import nimpa\n'), ((32271, 32301), 'os.path.dirname', 'os.path.dirname', (["datain['pCT']"], {}), "(datain['pCT'])\n", (32286, 32301), False, 'import os\n'), ((32329, 32363), 'os.path.join', 'os.path.join', (['outpath', '"""mumap-obj"""'], {}), "(outpath, 'mumap-obj')\n", (32341, 32363), False, 'import os\n'), ((32789, 32797), 'subprocess.run', 'run', (['cmd'], {}), '(cmd)\n', (32792, 32797), False, 'from subprocess import run\n'), ((33826, 33886), 'os.path.join', 'os.path.join', (['pctumapdir', "('mumap-pCT' + fcomment + '.nii.gz')"], {}), "(pctumapdir, 'mumap-pCT' + fcomment + '.nii.gz')\n", (33838, 33886), False, 'import os\n'), ((33895, 33937), 'niftypet.nimpa.array2nii', 'nimpa.array2nii', (['mu[::-1, ::-1, :]', 'A', 'fmu'], {}), '(mu[::-1, ::-1, :], A, fmu)\n', (33910, 33937), False, 'from niftypet import nimpa\n'), ((34840, 34859), 'pydicom.read_file', 'dcm.read_file', (['dcmf'], {}), '(dcmf)\n', (34853, 34859), True, 'import pydicom as dcm\n'), ((37428, 37465), 'numpy.array', 'np.array', (['[0.1 * z, 0.1 * y, 0.1 * x]'], {}), '([0.1 * z, 0.1 * y, 0.1 * x])\n', (37436, 37465), True, 'import numpy as np\n'), ((37491, 37516), 'numpy.array', 'np.array', (['[0.0, 0.0, 0.0]'], {}), '([0.0, 0.0, 0.0])\n', (37499, 37516), True, 'import numpy as np\n'), ((38130, 38160), 'os.path.isfile', 'os.path.isfile', (["Cnt['RESPATH']"], {}), "(Cnt['RESPATH'])\n", (38144, 38160), False, 'import os\n'), ((39104, 39145), 're.sub', 're.sub', (["b'[^a-zA-Z0-9.\\\\-]'", "b''", 'gtostr1'], {}), "(b'[^a-zA-Z0-9.\\\\-]', b'', gtostr1)\n", (39110, 39145), False, 'import re\n'), ((39232, 39287), 're.findall', 're.findall', (["b'(?<=M)-*[\\\\d]{1,4}\\\\.[\\\\d]{6,9}'", 'gtostr2'], {}), "(b'(?<=M)-*[\\\\d]{1,4}\\\\.[\\\\d]{6,9}', gtostr2)\n", (39242, 39287), False, 'import re\n'), ((39963, 40008), 'os.path.join', 'os.path.join', (["datain['corepath']", '"""mumap-hdw"""'], {}), "(datain['corepath'], 'mumap-hdw')\n", (39975, 40008), False, 'import os\n'), ((40036, 40070), 'os.path.join', 'os.path.join', (['outpath', '"""mumap-hdw"""'], {}), "(outpath, 'mumap-hdw')\n", (40048, 40070), False, 'import os\n'), ((40721, 40795), 'numpy.array', 'np.array', (["[-10 * Cnt['SO_VXX'], 10 * Cnt['SO_VXY'], 10 * Cnt['SO_VXZ'], 1]"], {}), "([-10 * Cnt['SO_VXX'], 10 * Cnt['SO_VXY'], 10 * Cnt['SO_VXZ'], 1])\n", (40729, 40795), True, 'import numpy as np\n'), ((41007, 41080), 'numpy.zeros', 'np.zeros', (["(Cnt['SO_IMZ'], Cnt['SO_IMY'], Cnt['SO_IMX'])"], {'dtype': 'np.float32'}), "((Cnt['SO_IMZ'], Cnt['SO_IMY'], Cnt['SO_IMX']), dtype=np.float32)\n", (41015, 41080), True, 'import numpy as np\n'), ((41667, 41717), 'os.path.join', 'os.path.join', (["Cnt['HMUDIR']", "Cnt['HMULIST'][i - 1]"], {}), "(Cnt['HMUDIR'], Cnt['HMULIST'][i - 1])\n", (41679, 41717), False, 'import os\n'), ((42869, 42928), 'niftypet.nimpa.array2nii', 'nimpa.array2nii', (['im[::-1, ::-1, :]', 'A', "hmupos[i]['niipath']"], {}), "(im[::-1, ::-1, :], A, hmupos[i]['niipath'])\n", (42884, 42928), False, 'from niftypet import nimpa\n'), ((43365, 43373), 'subprocess.run', 'run', (['cmd'], {}), '(cmd)\n', (43368, 43373), False, 'from subprocess import run\n'), ((43719, 43753), 'os.path.join', 'os.path.join', (['outpath', '"""mumap-hdw"""'], {}), "(outpath, 'mumap-hdw')\n", (43731, 43753), False, 'import os\n'), ((43781, 43826), 'os.path.join', 'os.path.join', (["datain['corepath']", '"""mumap-hdw"""'], {}), "(datain['corepath'], 'mumap-hdw')\n", (43793, 43826), False, 'import os\n'), ((43987, 44019), 'os.path.isfile', 'os.path.isfile', (["datain['hmumap']"], {}), "(datain['hmumap'])\n", (44001, 44019), False, 'import os\n'), ((46752, 46784), 'os.path.isfile', 'os.path.isfile', (["datain['hmumap']"], {}), "(datain['hmumap'])\n", (46766, 46784), False, 'import os\n'), ((47138, 47171), 'os.path.isfile', 'os.path.isfile', (["datain['mumapCT']"], {}), "(datain['mumapCT'])\n", (47152, 47171), False, 'import os\n'), ((47487, 47521), 'os.path.isfile', 'os.path.isfile', (["datain['mumapUTE']"], {}), "(datain['mumapUTE'])\n", (47501, 47521), False, 'import os\n'), ((47555, 47601), 'numpy.load', 'np.load', (["datain['mumapUTE']"], {'allow_pickle': '(True)'}), "(datain['mumapUTE'], allow_pickle=True)\n", (47562, 47601), True, 'import numpy as np\n'), ((48019, 48075), 'niftypet.nipet.lm.mmrhist.hist', 'mmrhist.hist', (['datain', 'txLUT_', 'axLUT_', 'Cnt_'], {'t0': 't0', 't1': 't1'}), '(datain, txLUT_, axLUT_, Cnt_, t0=t0, t1=t1)\n', (48031, 48075), False, 'from niftypet.nipet.lm import mmrhist\n'), ((48166, 48292), 'niftypet.nipet.prj.mmrrec.osemone', 'mmrrec.osemone', (['datain', '[muh, muo]', 'hst', 'params'], {'recmod': '(3)', 'itr': '(4)', 'fwhm': '(0.0)', 'store_img': '(True)', 'fcomment': "(fcomment + '_QNT-UTE')"}), "(datain, [muh, muo], hst, params, recmod=3, itr=4, fwhm=0.0,\n store_img=True, fcomment=fcomment + '_QNT-UTE')\n", (48180, 48292), False, 'from niftypet.nipet.prj import mmrrec\n'), ((48352, 48383), 'os.path.isfile', 'os.path.isfile', (["datain['T1nii']"], {}), "(datain['T1nii'])\n", (48366, 48383), False, 'import os\n'), ((49252, 49282), 'os.path.isfile', 'os.path.isfile', (["Cnt['REGPATH']"], {}), "(Cnt['REGPATH'])\n", (49266, 49282), False, 'import os\n'), ((8642, 8677), 'os.path.dirname', 'os.path.dirname', (["datain['mumapDCM']"], {}), "(datain['mumapDCM'])\n", (8657, 8677), False, 'import os\n'), ((9560, 9595), 'os.path.dirname', 'os.path.dirname', (["datain['mumapDCM']"], {}), "(datain['mumapDCM'])\n", (9575, 9595), False, 'import os\n'), ((11341, 11374), 'os.path.isdir', 'os.path.isdir', (["datain['mumapDCM']"], {}), "(datain['mumapDCM'])\n", (11354, 11374), False, 'import os\n'), ((11906, 11957), 'os.path.join', 'os.path.join', (['fmudir', "('*' + fnii + tstmp + '*.nii*')"], {}), "(fmudir, '*' + fnii + tstmp + '*.nii*')\n", (11918, 11957), False, 'import os\n'), ((13600, 13621), 'shutil.rmtree', 'shutil.rmtree', (['fmudir'], {}), '(fmudir)\n', (13613, 13621), False, 'import shutil\n'), ((15461, 15496), 'niftypet.nimpa.getnii', 'nimpa.getnii', (['fmupath'], {'output': '"""all"""'}), "(fmupath, output='all')\n", (15473, 15496), False, 'from niftypet import nimpa\n'), ((16856, 16900), 'numpy.load', 'np.load', (["datain['hmumap']"], {'allow_pickle': '(True)'}), "(datain['hmumap'], allow_pickle=True)\n", (16863, 16900), True, 'import numpy as np\n'), ((17074, 17122), 'os.path.join', 'os.path.join', (['outpath', '"""mumap-hdw"""', '"""hmumap.npz"""'], {}), "(outpath, 'mumap-hdw', 'hmumap.npz')\n", (17086, 17122), False, 'import os\n'), ((17134, 17157), 'os.path.isfile', 'os.path.isfile', (['hmupath'], {}), '(hmupath)\n', (17148, 17157), False, 'import os\n'), ((20304, 20336), 'os.path.exists', 'os.path.exists', (['datain[ute_name]'], {}), '(datain[ute_name])\n', (20318, 20336), False, 'import os\n'), ((20430, 20461), 'os.path.isdir', 'os.path.isdir', (['datain[ute_name]'], {}), '(datain[ute_name])\n', (20443, 20461), False, 'import os\n'), ((23505, 23525), 'os.path.isfile', 'os.path.isfile', (['fpet'], {}), '(fpet)\n', (23519, 23525), False, 'import os\n'), ((24157, 24213), 'os.path.join', 'os.path.join', (['opth', "('UTE-res-tmp' + fcomment + '.nii.gz')"], {}), "(opth, 'UTE-res-tmp' + fcomment + '.nii.gz')\n", (24169, 24213), False, 'import os\n'), ((25741, 25756), 'os.remove', 'os.remove', (['fflo'], {}), '(fflo)\n', (25750, 25756), False, 'import os\n'), ((26720, 26735), 'os.remove', 'os.remove', (['fute'], {}), '(fute)\n', (26729, 26735), False, 'import os\n'), ((27828, 27873), 'niftypet.nipet.lm.mmrhist', 'mmrhist', (['datain', 'scanner_params'], {'t0': 't0', 't1': 't1'}), '(datain, scanner_params, t0=t0, t1=t1)\n', (27835, 27873), False, 'from niftypet.nipet.lm import mmrhist\n'), ((28002, 28046), 'numpy.load', 'np.load', (["datain['hmumap']"], {'allow_pickle': '(True)'}), "(datain['hmumap'], allow_pickle=True)\n", (28009, 28046), True, 'import numpy as np\n'), ((28214, 28262), 'os.path.join', 'os.path.join', (['outpath', '"""mumap-hdw"""', '"""hmumap.npz"""'], {}), "(outpath, 'mumap-hdw', 'hmumap.npz')\n", (28226, 28262), False, 'import os\n'), ((28274, 28297), 'os.path.isfile', 'os.path.isfile', (['hmupath'], {}), '(hmupath)\n', (28288, 28297), False, 'import os\n'), ((33497, 33542), 'os.path.join', 'os.path.join', (["datain['corepath']", '"""mumap-obj"""'], {}), "(datain['corepath'], 'mumap-obj')\n", (33509, 33542), False, 'import os\n'), ((33582, 33616), 'os.path.join', 'os.path.join', (['outpath', '"""mumap-obj"""'], {}), "(outpath, 'mumap-obj')\n", (33594, 33616), False, 'import os\n'), ((33713, 33754), 'os.path.join', 'os.path.join', (['pctumapdir', '"""mumap-pCT.npz"""'], {}), "(pctumapdir, 'mumap-pCT.npz')\n", (33725, 33754), False, 'import os\n'), ((33767, 33792), 'numpy.savez', 'np.savez', (['fnp'], {'mu': 'mu', 'A': 'A'}), '(fnp, mu=mu, A=A)\n', (33775, 33792), True, 'import numpy as np\n'), ((34411, 34452), 'os.path.join', 'os.path.join', (["datain['mumapDCM']", '"""*.dcm"""'], {}), "(datain['mumapDCM'], '*.dcm')\n", (34423, 34452), False, 'import os\n'), ((37888, 37907), 'os.path.dirname', 'os.path.dirname', (['fh'], {}), '(fh)\n', (37903, 37907), False, 'import os\n'), ((38448, 38488), 're.sub', 're.sub', (["b'[^a-zA-Z0-9.\\\\-]'", "b''", 'tpostr'], {}), "(b'[^a-zA-Z0-9.\\\\-]', b'', tpostr)\n", (38454, 38488), False, 'import re\n'), ((38896, 38945), 're.finditer', 're.finditer', (["b'GantryTableHomeOffset(?!_)'", 'csamu'], {}), "(b'GantryTableHomeOffset(?!_)', csamu)\n", (38907, 38945), False, 'import re\n'), ((42666, 42693), 'numpy.append', 'np.append', (['(10 * vs[::-1])', '(1)'], {}), '(10 * vs[::-1], 1)\n', (42675, 42693), True, 'import numpy as np\n'), ((42992, 43029), 'os.path.dirname', 'os.path.dirname', (["hmupos[0]['niipath']"], {}), "(hmupos[0]['niipath'])\n", (43007, 43029), False, 'import os\n'), ((44098, 44142), 'niftypet.nimpa.getnii', 'nimpa.getnii', (["datain['hmumap']"], {'output': '"""all"""'}), "(datain['hmumap'], output='all')\n", (44110, 44142), False, 'from niftypet import nimpa\n'), ((44614, 44648), 'os.path.join', 'os.path.join', (['fmudir', '"""hmumap.npz"""'], {}), "(fmudir, 'hmumap.npz')\n", (44626, 44648), False, 'import os\n'), ((44663, 44694), 'numpy.load', 'np.load', (['fnp'], {'allow_pickle': '(True)'}), '(fnp, allow_pickle=True)\n', (44670, 44694), True, 'import numpy as np\n'), ((45014, 45044), 'nibabel.load', 'nib.load', (["hmupos[0]['niipath']"], {}), "(hmupos[0]['niipath'])\n", (45022, 45044), True, 'import nibabel as nib\n'), ((45519, 45530), 'numpy.max', 'np.max', (['imo'], {}), '(imo)\n', (45525, 45530), True, 'import numpy as np\n'), ((45556, 45567), 'numpy.min', 'np.min', (['imo'], {}), '(imo)\n', (45562, 45567), True, 'import numpy as np\n'), ((45676, 45699), 'nibabel.Nifti1Image', 'nib.Nifti1Image', (['imo', 'A'], {}), '(imo, A)\n', (45691, 45699), True, 'import nibabel as nib\n'), ((45708, 45730), 'nibabel.save', 'nib.save', (['hmu_nii', 'fmu'], {}), '(hmu_nii, fmu)\n', (45716, 45730), True, 'import nibabel as nib\n'), ((45746, 45789), 'numpy.transpose', 'np.transpose', (['imo[:, ::-1, ::-1]', '(2, 1, 0)'], {}), '(imo[:, ::-1, ::-1], (2, 1, 0))\n', (45758, 45789), True, 'import numpy as np\n'), ((45848, 45882), 'os.path.join', 'os.path.join', (['fmudir', '"""hmumap.npz"""'], {}), "(fmudir, 'hmumap.npz')\n", (45860, 45882), False, 'import os\n'), ((45891, 45927), 'numpy.savez', 'np.savez', (['fnp'], {'hmu': 'hmu', 'A': 'A', 'fmu': 'fmu'}), '(fnp, hmu=hmu, A=A, fmu=fmu)\n', (45899, 45927), True, 'import numpy as np\n'), ((46815, 46859), 'numpy.load', 'np.load', (["datain['hmumap']"], {'allow_pickle': '(True)'}), "(datain['hmumap'], allow_pickle=True)\n", (46822, 46859), True, 'import numpy as np\n'), ((47202, 47247), 'numpy.load', 'np.load', (["datain['mumapCT']"], {'allow_pickle': '(True)'}), "(datain['mumapCT'], allow_pickle=True)\n", (47209, 47247), True, 'import numpy as np\n'), ((48433, 48463), 'os.path.isfile', 'os.path.isfile', (["datain['T1bc']"], {}), "(datain['T1bc'])\n", (48447, 48463), False, 'import os\n'), ((48959, 48980), 'os.path.dirname', 'os.path.dirname', (['ft1w'], {}), '(ft1w)\n', (48974, 48980), False, 'import os\n'), ((49085, 49106), 'os.path.dirname', 'os.path.dirname', (['ft1w'], {}), '(ft1w)\n', (49100, 49106), False, 'import os\n'), ((49545, 49553), 'subprocess.run', 'run', (['cmd'], {}), '(cmd)\n', (49548, 49553), False, 'from subprocess import run\n'), ((7181, 7192), 'math.cos', 'math.cos', (['t'], {}), '(t)\n', (7189, 7192), False, 'import math\n'), ((7216, 7227), 'math.sin', 'math.sin', (['t'], {}), '(t)\n', (7224, 7227), False, 'import math\n'), ((7326, 7353), 'numpy.ceil', 'np.ceil', (["(yf / Cnt['SO_VXY'])"], {}), "(yf / Cnt['SO_VXY'])\n", (7333, 7353), True, 'import numpy as np\n'), ((7397, 7424), 'numpy.floor', 'np.floor', (["(x / Cnt['SO_VXY'])"], {}), "(x / Cnt['SO_VXY'])\n", (7405, 7424), True, 'import numpy as np\n'), ((16488, 16533), 'niftypet.nipet.lm.mmrhist', 'mmrhist', (['datain', 'scanner_params'], {'t0': 't0', 't1': 't1'}), '(datain, scanner_params, t0=t0, t1=t1)\n', (16495, 16533), False, 'from niftypet.nipet.lm import mmrhist\n'), ((19087, 19123), 'numpy.zeros', 'np.zeros', (['muh.shape'], {'dtype': 'muh.dtype'}), '(muh.shape, dtype=muh.dtype)\n', (19095, 19123), True, 'import numpy as np\n'), ((20486, 20520), 'os.path.basename', 'os.path.basename', (['datain[ute_name]'], {}), '(datain[ute_name])\n', (20502, 20520), False, 'import os\n'), ((20537, 20589), 'subprocess.run', 'run', (["[Cnt['DCM2NIIX'], '-f', fnew, datain[ute_name]]"], {}), "([Cnt['DCM2NIIX'], '-f', fnew, datain[ute_name]])\n", (20540, 20589), False, 'from subprocess import run\n'), ((20691, 20723), 'os.path.isfile', 'os.path.isfile', (['datain[ute_name]'], {}), '(datain[ute_name])\n', (20705, 20723), False, 'import os\n'), ((22108, 22130), 'niftypet.nimpa.pick_t1w', 'nimpa.pick_t1w', (['datain'], {}), '(datain)\n', (22122, 22130), False, 'from niftypet import nimpa\n'), ((24309, 24344), 'niftypet.nimpa.time_stamp', 'nimpa.time_stamp', ([], {'simple_ascii': '(True)'}), '(simple_ascii=True)\n', (24325, 24344), False, 'from niftypet import nimpa\n'), ((24525, 24599), 'subprocess.run', 'run', (["[Cnt['DCM2NIIX'], '-f', fnii + tstmp, '-o', opth, datain['mumapDCM']]"], {}), "([Cnt['DCM2NIIX'], '-f', fnii + tstmp, '-o', opth, datain['mumapDCM']])\n", (24528, 24599), False, 'from subprocess import run\n'), ((24755, 24784), 'os.path.isfile', 'os.path.isfile', (["datain['UTE']"], {}), "(datain['UTE'])\n", (24769, 24784), False, 'import os\n'), ((25660, 25677), 'numpy.float32', 'np.float32', (['imreg'], {}), '(imreg)\n', (25670, 25677), True, 'import numpy as np\n'), ((26686, 26706), 'os.path.isfile', 'os.path.isfile', (['faff'], {}), '(faff)\n', (26700, 26706), False, 'import os\n'), ((29955, 29991), 'numpy.zeros', 'np.zeros', (['muh.shape'], {'dtype': 'muh.dtype'}), '(muh.shape, dtype=muh.dtype)\n', (29963, 29991), True, 'import numpy as np\n'), ((34485, 34526), 'os.path.join', 'os.path.join', (["datain['mumapDCM']", '"""*.DCM"""'], {}), "(datain['mumapDCM'], '*.DCM')\n", (34497, 34526), False, 'import os\n'), ((34560, 34601), 'os.path.join', 'os.path.join', (["datain['mumapDCM']", '"""*.ima"""'], {}), "(datain['mumapDCM'], '*.ima')\n", (34572, 34601), False, 'import os\n'), ((34635, 34676), 'os.path.join', 'os.path.join', (["datain['mumapDCM']", '"""*.IMA"""'], {}), "(datain['mumapDCM'], '*.IMA')\n", (34647, 34676), False, 'import os\n'), ((39305, 39323), 'numpy.float32', 'np.float32', (['gtoxyz'], {}), '(gtoxyz)\n', (39315, 39323), True, 'import numpy as np\n'), ((44302, 44346), 'numpy.load', 'np.load', (["datain['hmumap']"], {'allow_pickle': '(True)'}), "(datain['hmumap'], allow_pickle=True)\n", (44309, 44346), True, 'import numpy as np\n'), ((44563, 44597), 'os.path.join', 'os.path.join', (['fmudir', '"""hmumap.npz"""'], {}), "(fmudir, 'hmumap.npz')\n", (44575, 44597), False, 'import os\n'), ((45354, 45367), 'nibabel.load', 'nib.load', (['fin'], {}), '(fin)\n', (45362, 45367), True, 'import nibabel as nib\n'), ((45595, 45632), 'os.path.dirname', 'os.path.dirname', (["hmupos[0]['niipath']"], {}), "(hmupos[0]['niipath'])\n", (45610, 45632), False, 'import os\n'), ((48512, 48542), 'os.path.isdir', 'os.path.isdir', (["datain['MRT1W']"], {}), "(datain['MRT1W'])\n", (48525, 48542), False, 'import os\n'), ((9895, 9930), 'os.path.dirname', 'os.path.dirname', (["datain['mumapDCM']"], {}), "(datain['mumapDCM'])\n", (9910, 9930), False, 'import os\n'), ((9982, 10017), 'os.path.dirname', 'os.path.dirname', (["datain['mumapDCM']"], {}), "(datain['mumapDCM'])\n", (9997, 10017), False, 'import os\n'), ((13492, 13510), 'os.listdir', 'os.listdir', (['fmudir'], {}), '(fmudir)\n', (13502, 13510), False, 'import os\n'), ((17177, 17212), 'numpy.load', 'np.load', (['hmupath'], {'allow_pickle': '(True)'}), '(hmupath, allow_pickle=True)\n', (17184, 17212), True, 'import numpy as np\n'), ((18701, 18744), 'os.path.join', 'os.path.join', (['outpath', '"""PET"""', '"""positioning"""'], {}), "(outpath, 'PET', 'positioning')\n", (18713, 18744), False, 'import os\n'), ((28317, 28352), 'numpy.load', 'np.load', (['hmupath'], {'allow_pickle': '(True)'}), '(hmupath, allow_pickle=True)\n', (28324, 28352), True, 'import numpy as np\n'), ((29569, 29612), 'os.path.join', 'os.path.join', (['outpath', '"""PET"""', '"""positioning"""'], {}), "(outpath, 'PET', 'positioning')\n", (29581, 29612), False, 'import os\n'), ((31273, 31316), 'os.path.join', 'os.path.join', (['outpath', '"""PET"""', '"""positioning"""'], {}), "(outpath, 'PET', 'positioning')\n", (31285, 31316), False, 'import os\n'), ((45209, 45246), 'os.path.dirname', 'os.path.dirname', (["hmupos[0]['niipath']"], {}), "(hmupos[0]['niipath'])\n", (45224, 45246), False, 'import os\n'), ((46082, 46113), 'os.path.join', 'os.path.join', (['fmudir', '"""_*.nii*"""'], {}), "(fmudir, '_*.nii*')\n", (46094, 46113), False, 'import os\n'), ((46132, 46148), 'os.remove', 'os.remove', (['fname'], {}), '(fname)\n', (46141, 46148), False, 'import os\n'), ((46184, 46216), 'os.path.join', 'os.path.join', (['fmudir', '"""r_*.nii*"""'], {}), "(fmudir, 'r_*.nii*')\n", (46196, 46216), False, 'import os\n'), ((46235, 46251), 'os.remove', 'os.remove', (['fname'], {}), '(fname)\n', (46244, 46251), False, 'import os\n'), ((48648, 48699), 'subprocess.run', 'run', (["[Cnt['DCM2NIIX'], '-f', fnii, datain['T1nii']]"], {}), "([Cnt['DCM2NIIX'], '-f', fnii, datain['T1nii']])\n", (48651, 48699), False, 'from subprocess import run\n'), ((19337, 19380), 'os.path.join', 'os.path.join', (['outpath', '"""PET"""', '"""positioning"""'], {}), "(outpath, 'PET', 'positioning')\n", (19349, 19380), False, 'import os\n'), ((20623, 20669), 'os.path.join', 'os.path.join', (['datain[ute_name]', "(fnew + '*nii*')"], {}), "(datain[ute_name], fnew + '*nii*')\n", (20635, 20669), False, 'import os\n'), ((20946, 20989), 'os.path.join', 'os.path.join', (['outpath', '"""PET"""', '"""positioning"""'], {}), "(outpath, 'PET', 'positioning')\n", (20958, 20989), False, 'import os\n'), ((24672, 24721), 'os.path.join', 'os.path.join', (['opth', "('*' + fnii + tstmp + '*.nii*')"], {}), "(opth, '*' + fnii + tstmp + '*.nii*')\n", (24684, 24721), False, 'import os\n'), ((30205, 30248), 'os.path.join', 'os.path.join', (['outpath', '"""PET"""', '"""positioning"""'], {}), "(outpath, 'PET', 'positioning')\n", (30217, 30248), False, 'import os\n'), ((31456, 31499), 'os.path.join', 'os.path.join', (['outpath', '"""PET"""', '"""positioning"""'], {}), "(outpath, 'PET', 'positioning')\n", (31468, 31499), False, 'import os\n'), ((48731, 48780), 'os.path.join', 'os.path.join', (["datain['T1nii']", '"""*converted*.nii*"""'], {}), "(datain['T1nii'], '*converted*.nii*')\n", (48743, 48780), False, 'import os\n'), ((20033, 20076), 'os.path.join', 'os.path.join', (['outpath', '"""PET"""', '"""positioning"""'], {}), "(outpath, 'PET', 'positioning')\n", (20045, 20076), False, 'import os\n'), ((21160, 21203), 'os.path.join', 'os.path.join', (['outpath', '"""PET"""', '"""positioning"""'], {}), "(outpath, 'PET', 'positioning')\n", (21172, 21203), False, 'import os\n'), ((22268, 22311), 'os.path.join', 'os.path.join', (['outpath', '"""PET"""', '"""positioning"""'], {}), "(outpath, 'PET', 'positioning')\n", (22280, 22311), False, 'import os\n'), ((30870, 30913), 'os.path.join', 'os.path.join', (['outpath', '"""PET"""', '"""positioning"""'], {}), "(outpath, 'PET', 'positioning')\n", (30882, 30913), False, 'import os\n'), ((31585, 31612), 'multiprocessing.cpu_count', 'multiprocessing.cpu_count', ([], {}), '()\n', (31610, 31612), False, 'import multiprocessing\n'), ((21276, 21303), 'multiprocessing.cpu_count', 'multiprocessing.cpu_count', ([], {}), '()\n', (21301, 21303), False, 'import multiprocessing\n'), ((22482, 22525), 'os.path.join', 'os.path.join', (['outpath', '"""PET"""', '"""positioning"""'], {}), "(outpath, 'PET', 'positioning')\n", (22494, 22525), False, 'import os\n'), ((43065, 43103), 'os.path.basename', 'os.path.basename', (["hmupos[i]['niipath']"], {}), "(hmupos[i]['niipath'])\n", (43081, 43103), False, 'import os\n'), ((22598, 22625), 'multiprocessing.cpu_count', 'multiprocessing.cpu_count', ([], {}), '()\n', (22623, 22625), False, 'import multiprocessing\n'), ((45270, 45308), 'os.path.basename', 'os.path.basename', (["hmupos[i]['niipath']"], {}), "(hmupos[i]['niipath'])\n", (45286, 45308), False, 'import os\n')]
""" Usage: kungfu-run -q -np 4 python3 -m kungfu.tensorflow.v1.benchmarks --method CPU kungfu-run -q -np 4 python3 -m kungfu.tensorflow.v1.benchmarks --method NCCL kungfu-run -q -np 4 python3 -m kungfu.tensorflow.v1.benchmarks --method NCCL+CPU mpirun -np 4 python3 -m kungfu.tensorflow.v1.benchmarks --method HOROVOD """ import argparse import os import sys import numpy as np import tensorflow as tf from kungfu._utils import measure, one_based_range from kungfu.python import _get_cuda_index from kungfu.tensorflow.ops import (current_cluster_size, current_rank, group_all_reduce, group_nccl_all_reduce) from kungfu.tensorflow.ops.collective import group_hierarchical_nccl_all_reduce from kungfu.tensorflow.v1.benchmarks import model_sizes from kungfu.tensorflow.v1.helpers.utils import show_rate, show_size from tensorflow.python.util import deprecation deprecation._PRINT_DEPRECATION_WARNINGS = False def _tensor_size(t): return t.shape.num_elements() * t.dtype.size def hvd_init(): import horovod.tensorflow as hvd hvd.init() def hvd_group_all_reduce(ts): import horovod.tensorflow as hvd return [hvd.allreduce(t, average=False) for t in ts] def get_cluster_size(method): if method == 'HOROVOD': import horovod.tensorflow as hvd return hvd.size() else: return current_cluster_size() def get_rank(method): if method == 'HOROVOD': import horovod.tensorflow as hvd return hvd.rank() else: return current_rank() _group_all_reduce_func = { 'CPU': group_all_reduce, 'NCCL': group_nccl_all_reduce, 'NCCL+CPU': group_hierarchical_nccl_all_reduce, 'HOROVOD': hvd_group_all_reduce, } _model_sizes = { 'ResNet50': model_sizes.resnet50_imagenet, 'VGG16': model_sizes.vgg16_imagenet, 'BERT': model_sizes.bert, } def _config(method): config = tf.ConfigProto() config.gpu_options.allow_growth = True if method == 'HOROVOD': import horovod.tensorflow as hvd config.gpu_options.visible_device_list = str(hvd.local_rank()) else: config.gpu_options.visible_device_list = str(_get_cuda_index()) return config def _rank(method): if method == 'HOROVOD': import horovod.tensorflow as hvd return hvd.rank() else: return current_rank() def parse_args(): p = argparse.ArgumentParser(description='Perf Benchmarks.') p.add_argument('--model', type=str, default='ResNet50', help='ResNet50 | VGG16 | BERT') p.add_argument('--method', type=str, default='CPU', help='CPU | NCCL | HOROVOD') p.add_argument('--fuse', action='store_true', default=False, help='') p.add_argument('--max-count', type=int, default=0, help='max grad count') p.add_argument('--steps', type=int, default=10, help='number of steps to run') p.add_argument('--warmup-steps', type=int, default=5, help='number of warmup steps') return p.parse_args() def log_detailed_result(value, error, attrs): import json attr_str = json.dumps(attrs, separators=(',', ':')) # grep -o RESULT.* *.log unit = 'GiB/s' print('RESULT: %f +-%f (%s) %s' % (value, error, unit, attr_str)) def log_final_result(values, args): attrs = { 'method': args.method, 'np': get_cluster_size(args.method), 'model': args.model, 'fuse': args.fuse, } values = np.array(values) if args.method != 'HOROVOD': attrs['strategy'] = os.getenv('KUNGFU_ALLREDUCE_STRATEGY') attrs['nvlink'] = os.getenv('KUNGFU_ALLOW_NVLINK') log_detailed_result(values.mean(), 1.96 * values.std(), attrs) def all_reduce_benchmark(sizes, dtype, args): rank = _rank(args.method) def log(msg): if rank == 0: print(msg) xs = [tf.Variable(tf.ones([n], dtype)) for n in sizes] tot_size = sum(_tensor_size(x) for x in xs) np = get_cluster_size(args.method) multiplier = 4 * (np - 1) log('all reduce %d tensors of total size: %s among %d peers, using %s' % (len(sizes), show_size(tot_size), np, args.method)) ys = _group_all_reduce_func[args.method](xs) init = tf.global_variables_initializer() values = [] with tf.Session(config=_config(args.method)) as sess: duration, _ = measure(lambda: sess.run(init)) log('tensorflow init took %.fs' % (duration)) for step in one_based_range(args.warmup_steps): duration, _ = measure(lambda: sess.run(ys)) log('warmup step %d, took %.2fs, equivalent data rate: %s' % (step, duration, show_rate(tot_size * multiplier, duration))) for step in one_based_range(args.steps): duration, _ = measure(lambda: sess.run(ys)) gi = 1024 * 1024 * 1024 values.append(tot_size * multiplier / gi / duration) log('step %d, took %.2fs, equivalent data rate: %s' % (step, duration, show_rate(tot_size * multiplier, duration))) if get_rank(args.method) == 0: log_final_result(values, args) def main(_): args = parse_args() if args.method == 'HOROVOD': hvd_init() dtype = tf.float32 sizes = _model_sizes[args.model] if args.fuse: sizes = [sum(sizes)] if args.max_count > 0 and len(sizes) > args.max_count: sizes = sizes[:args.max_count] all_reduce_benchmark(sizes, dtype, args) if __name__ == "__main__": main(sys.argv)
[ "tensorflow.ones", "horovod.tensorflow.local_rank", "kungfu.python._get_cuda_index", "horovod.tensorflow.init", "argparse.ArgumentParser", "horovod.tensorflow.allreduce", "horovod.tensorflow.size", "tensorflow.global_variables_initializer", "kungfu.tensorflow.v1.helpers.utils.show_size", "json.dumps", "kungfu.tensorflow.ops.current_rank", "tensorflow.ConfigProto", "numpy.array", "kungfu._utils.one_based_range", "kungfu.tensorflow.v1.helpers.utils.show_rate", "os.getenv", "horovod.tensorflow.rank", "kungfu.tensorflow.ops.current_cluster_size" ]
[((1091, 1101), 'horovod.tensorflow.init', 'hvd.init', ([], {}), '()\n', (1099, 1101), True, 'import horovod.tensorflow as hvd\n'), ((1920, 1936), 'tensorflow.ConfigProto', 'tf.ConfigProto', ([], {}), '()\n', (1934, 1936), True, 'import tensorflow as tf\n'), ((2404, 2459), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Perf Benchmarks."""'}), "(description='Perf Benchmarks.')\n", (2427, 2459), False, 'import argparse\n'), ((3294, 3334), 'json.dumps', 'json.dumps', (['attrs'], {'separators': "(',', ':')"}), "(attrs, separators=(',', ':'))\n", (3304, 3334), False, 'import json\n'), ((3656, 3672), 'numpy.array', 'np.array', (['values'], {}), '(values)\n', (3664, 3672), True, 'import numpy as np\n'), ((4417, 4450), 'tensorflow.global_variables_initializer', 'tf.global_variables_initializer', ([], {}), '()\n', (4448, 4450), True, 'import tensorflow as tf\n'), ((1183, 1214), 'horovod.tensorflow.allreduce', 'hvd.allreduce', (['t'], {'average': '(False)'}), '(t, average=False)\n', (1196, 1214), True, 'import horovod.tensorflow as hvd\n'), ((1344, 1354), 'horovod.tensorflow.size', 'hvd.size', ([], {}), '()\n', (1352, 1354), True, 'import horovod.tensorflow as hvd\n'), ((1380, 1402), 'kungfu.tensorflow.ops.current_cluster_size', 'current_cluster_size', ([], {}), '()\n', (1400, 1402), False, 'from kungfu.tensorflow.ops import current_cluster_size, current_rank, group_all_reduce, group_nccl_all_reduce\n'), ((1511, 1521), 'horovod.tensorflow.rank', 'hvd.rank', ([], {}), '()\n', (1519, 1521), True, 'import horovod.tensorflow as hvd\n'), ((1547, 1561), 'kungfu.tensorflow.ops.current_rank', 'current_rank', ([], {}), '()\n', (1559, 1561), False, 'from kungfu.tensorflow.ops import current_cluster_size, current_rank, group_all_reduce, group_nccl_all_reduce\n'), ((2325, 2335), 'horovod.tensorflow.rank', 'hvd.rank', ([], {}), '()\n', (2333, 2335), True, 'import horovod.tensorflow as hvd\n'), ((2361, 2375), 'kungfu.tensorflow.ops.current_rank', 'current_rank', ([], {}), '()\n', (2373, 2375), False, 'from kungfu.tensorflow.ops import current_cluster_size, current_rank, group_all_reduce, group_nccl_all_reduce\n'), ((3734, 3772), 'os.getenv', 'os.getenv', (['"""KUNGFU_ALLREDUCE_STRATEGY"""'], {}), "('KUNGFU_ALLREDUCE_STRATEGY')\n", (3743, 3772), False, 'import os\n'), ((3799, 3831), 'os.getenv', 'os.getenv', (['"""KUNGFU_ALLOW_NVLINK"""'], {}), "('KUNGFU_ALLOW_NVLINK')\n", (3808, 3831), False, 'import os\n'), ((4655, 4689), 'kungfu._utils.one_based_range', 'one_based_range', (['args.warmup_steps'], {}), '(args.warmup_steps)\n', (4670, 4689), False, 'from kungfu._utils import measure, one_based_range\n'), ((4919, 4946), 'kungfu._utils.one_based_range', 'one_based_range', (['args.steps'], {}), '(args.steps)\n', (4934, 4946), False, 'from kungfu._utils import measure, one_based_range\n'), ((2102, 2118), 'horovod.tensorflow.local_rank', 'hvd.local_rank', ([], {}), '()\n', (2116, 2118), True, 'import horovod.tensorflow as hvd\n'), ((2183, 2200), 'kungfu.python._get_cuda_index', '_get_cuda_index', ([], {}), '()\n', (2198, 2200), False, 'from kungfu.python import _get_cuda_index\n'), ((4064, 4083), 'tensorflow.ones', 'tf.ones', (['[n]', 'dtype'], {}), '([n], dtype)\n', (4071, 4083), True, 'import tensorflow as tf\n'), ((4316, 4335), 'kungfu.tensorflow.v1.helpers.utils.show_size', 'show_size', (['tot_size'], {}), '(tot_size)\n', (4325, 4335), False, 'from kungfu.tensorflow.v1.helpers.utils import show_rate, show_size\n'), ((4853, 4895), 'kungfu.tensorflow.v1.helpers.utils.show_rate', 'show_rate', (['(tot_size * multiplier)', 'duration'], {}), '(tot_size * multiplier, duration)\n', (4862, 4895), False, 'from kungfu.tensorflow.v1.helpers.utils import show_rate, show_size\n'), ((5204, 5246), 'kungfu.tensorflow.v1.helpers.utils.show_rate', 'show_rate', (['(tot_size * multiplier)', 'duration'], {}), '(tot_size * multiplier, duration)\n', (5213, 5246), False, 'from kungfu.tensorflow.v1.helpers.utils import show_rate, show_size\n')]
import numpy as np from shapely.geometry import LineString, Polygon import plotly.graph_objs as go import utils.camera as cam_utils import cv2 import matplotlib import os from os import listdir from os.path import isfile, join, exists import soccer import argparse import utils.io as io from tqdm import tqdm import plotly as py from plotly.tools import FigureFactory as FF import scipy # W, H = 104.73, 67.74 W, H = 103.0, 67.0 ################################################################################ # plots all players from arguments in plotly # arguments: list of all 22 players and their keypoints in 3D (0-10 Denmark, 11-21 Swiss) ################################################################################ def plot_all_players(players_3d): # plot the field plot_data = [] plot_field(plot_data) rgb_color = 'rgb(0, 0, 0)' for i in players_3d: if (i == 11): rgb_color = 'rgb(255, 8, 0)' #different color for the different teams plot_player(players_3d[i], plot_data, rgb_color) # layout parameters layout = dict( width=1500, height=750, plot_bgcolor='rgb(0,0,0)', autosize=False, title='camera location', showlegend=False, margin=dict( r=0, l=10, b=0, t=30), scene=dict( xaxis=dict( gridcolor='rgb(255, 255, 255)', zerolinecolor='rgb(255, 255, 255)', showbackground=True, backgroundcolor='rgb(230, 230,230)', range=[-60, 60] ), yaxis=dict( gridcolor='rgb(255, 255, 255)', zerolinecolor='rgb(255, 255, 255)', showbackground=True, backgroundcolor='rgb(230, 230,230)', range=[0, 10] ), zaxis=dict( gridcolor='rgb(255, 255, 255)', zerolinecolor='rgb(255, 255, 255)', showbackground=True, backgroundcolor='rgb(230, 230,230)', range=[-40, 40] ), camera=dict( up=dict( x=0, y=1, z=0 ), eye=dict( x=1.2, y=0.7100, z=1.2, ) ), aspectratio=dict(x=1, y=0.08333333333, z=0.66666666666), aspectmode='manual' ), ) fig = dict(data=plot_data, layout=layout) py.offline.plot(fig, filename='/home/bunert/Data/results/players.html') def plot_player(players, plot_data, rgb_color): limps = np.array([[0, 1], [1, 2], [2, 3], [3, 4], [1, 5], [5, 6], [6, 7], [1, 11], [11, 12], [12, 13], [1, 8], [8, 9], [9, 10], [14, 15], [16, 17], [0, 14], [0, 15], [14, 16], [15, 17], [8, 11], [2, 8], [5, 11]]) players = np.asmatrix(players) for i in range(len(limps)): plot_data.append(go.Scatter3d(x=[players[limps[i][0]][0,0], players[limps[i][1]][0,0]], y=[players[limps[i][0]][0,1], players[limps[i][1]][0,1]], z=[players[limps[i][0]][0,2], players[limps[i][1]][0,2]], mode='lines', line=dict(color=rgb_color, width=3))) # higher nn lead to preciser cicles but longer computation def make_field_circle(r=9.15, nn=7): """ Returns points that lie on a circle on the ground :param r: radius :param nn: points per arc? :return: 3D points on a circle with y = 0 """ d = 2 * np.pi * r n = int(nn * d) return [(np.cos(2 * np.pi / n * x) * r, 0, np.sin(2 * np.pi / n * x) * r) for x in range(0, n + 1)] # sort the polygon to plot the convex hull of the polygon def PolygonSort(corners): n = len(corners) cx = float(sum(x for x, y in corners)) / n cy = float(sum(y for x, y in corners)) / n cornersWithAngles = [] for x, y in corners: an = (np.arctan2(y - cy, x - cx) + 2.0 * np.pi) % (2.0 * np.pi) cornersWithAngles.append((x, y, an)) cornersWithAngles.sort(key=lambda tup: tup[2]) return map(lambda tuple: (tuple[0], tuple[1]), cornersWithAngles) # return the points for the straight lines of the field def get_field_points_limited(): outer_rectangle = np.array([[-W / 2., 0, H / 2.], [-W / 2., 0, -H / 2.], [W / 2., 0, -H / 2.], [W / 2., 0, H / 2.]]) left_big_box = np.array([[-W / 2., 0, 40.32/2.], [-W / 2., 0, -40.32 / 2.], [-W / 2. + 16.5, 0, -40.32 / 2.], [-W / 2.+16.5, 0, 40.32/2.]]) right_big_box = np.array([[W/2.-16.5, 0, 40.32/2.], [W/2., 0, 40.32/2.], [W/2., 0, -40.32/2.], [W/2.-16.5, 0, -40.32/2.]]) left_small_box = np.array([[-W/2., 0, 18.32/2.], [-W / 2., 0, -18.32 / 2.], [-W / 2. + 5.5, 0, -18.32 / 2.], [-W/2.+5.5, 0, 18.32/2.]]) right_small_box = np.array([[W/2.-5.5, 0, 18.32/2.], [W/2., 0, 18.32/2.], [W/2., 0, -18.32/2.], [W/2.-5.5, 0, -18.32/2.]]) mid_line = np.array([[0., 0., H / 2], [0., 0., -H / 2]]) return [outer_rectangle, left_big_box, right_big_box, left_small_box, right_small_box, mid_line] # draw a box out of 4 data points def draw_box(b, data): data.append(go.Scatter3d(x=[b.item(0), b.item(3)], y=[0, 0], z=[b.item(2), b.item(5)], mode='lines', line=dict(color='rgb(0,0,0)', width=3))) data.append(go.Scatter3d(x=[b.item(0), b.item(9)], y=[0, 0], z=[b.item(2), b.item(11)], mode='lines', line=dict(color='rgb(0,0,0)', width=3))) data.append(go.Scatter3d(x=[b.item(3), b.item(6)], y=[0, 0], z=[b.item(5), b.item(8)], mode='lines', line=dict(color='rgb(0,0,0)', width=3))) data.append(go.Scatter3d(x=[b.item(6), b.item(9)], y=[0, 0], z=[b.item(8), b.item(11)], mode='lines', line=dict(color='rgb(0,0,0)', width=3))) # draw a single line def draw_line(b, data): data.append(go.Scatter3d(x=[b.item(0), b.item(3)], y=[0, 0], z=[b.item(2), b.item(5)], mode='lines', line=dict(color='rgb(0,0,0)', width=3))) def connect_points(p1, p2, data): data.append(go.Scatter3d(x=[p1[0], p2[0]], y=[p1[1], p2[1]], z=[p1[2], p2[2]], mode='lines', line=dict(color='rgb(0,0,0)', width=3))) # middle circle def draw_middlecircle(data): corners = np.array(make_field_circle(9.15)) tuples = [] for i in range(len(corners)): tuples.append((corners[i, 0], corners[i, 2])) corners_sorted = list(PolygonSort(tuples)) x = [corner[0] for corner in corners_sorted] z = [corner[1] for corner in corners_sorted] draw_circle(data, x, z) # draw a cicle def draw_circle(data, x, z): for i in range(len(x)-1): data.append(go.Scatter3d(x=[x[i], x[i+1]], y=[0, 0], z=[z[i], z[i+1]], mode='lines', line=dict(color='rgb(0,0,0)', width=3))) data.append(go.Scatter3d(x=[x[len(x)-1], x[0]], y=[0, 0], z=[z[len(z)-1], z[0]], mode='lines', line=dict(color='rgb(0,0,0)', width=3))) # left halft circle def draw_lefthalf_circle(data): left_half_circile = np.array(make_field_circle(9.15)) left_half_circile[:, 0] = left_half_circile[:, 0] - W / 2. + 11.0 index = left_half_circile[:, 0] > (-W / 2. + 16.5) left_half_circile = left_half_circile[index, :] tuples = [] for i in range(len(left_half_circile)): tuples.append((left_half_circile[i, 0], left_half_circile[i, 2])) corners_sorted = list(PolygonSort(tuples)) x = [corner[0] for corner in corners_sorted] z = [corner[1] for corner in corners_sorted] draw_circle(data, x, z) # right half circle def draw_righthalf_circle(data): right_half_circile = np.array(make_field_circle(9.15)) right_half_circile[:, 0] = right_half_circile[:, 0] + W / 2. - 11.0 index = right_half_circile[:, 0] < (W / 2. - 16.5) right_half_circile = right_half_circile[index, :] tuples = [] for i in range(len(right_half_circile)): tuples.append((right_half_circile[i, 0], right_half_circile[i, 2])) corners_sorted = list(PolygonSort(tuples)) x = [corner[0] for corner in corners_sorted] z = [corner[1] for corner in corners_sorted] draw_circle(data, x, z) # plot the whole field def plot_field(data): field_list = get_field_points_limited() for i in range(len(field_list)): if (i <= 4): draw_box(field_list[i], data) elif (i == 5): draw_line(field_list[i], data) draw_lefthalf_circle(data) draw_righthalf_circle(data) draw_middlecircle(data) # plot one camera # needs to get extended: # - frame number hardcoded # - iterate through all cameras available def plot_camera(data, db, name): cam = cam_utils.Camera(name, db.calib[db.frame_basenames[0]]['A'], db.calib[db.frame_basenames[0]] ['R'], db.calib[db.frame_basenames[0]]['T'], db.shape[0], db.shape[1]) data.append(go.Scatter3d(go.Scatter3d( x=[cam.get_position().item(0, 0)], y=[cam.get_position().item(1, 0)], z=[cam.get_position().item(2, 0)], text=cam.name, mode='markers+text', hoverinfo='none', marker=dict( sizemode='diameter', sizeref=750, # info on sizeref: https://plot.ly/python/reference/#scatter-marker-sizeref size=9, color='rgb(30, 70, 180)', )))) ################################################################################ # Original draw file: ################################################################################ def get_field_points(): outer_rectangle = np.array([[-W / 2., 0, H / 2.], [-W / 2., 0, -H / 2.], [W / 2., 0, -H / 2.], [W / 2., 0, H / 2.]]) mid_line = np.array([[0., 0., H / 2], [0., 0., -H / 2]]) left_big_box = np.array([[-W / 2., 0, 40.32/2.], [-W / 2., 0, -40.32 / 2.], [-W / 2. + 16.5, 0, -40.32 / 2.], [-W/2.+16.5, 0, 40.32/2.]]) right_big_box = np.array([[W/2.-16.5, 0, 40.32/2.], [W/2., 0, 40.32/2.], [W/2., 0, -40.32/2.], [W/2.-16.5, 0, -40.32/2.]]) left_small_box = np.array([[-W/2., 0, 18.32/2.], [-W / 2., 0, -18.32 / 2.], [-W / 2. + 5.5, 0, -18.32 / 2.], [-W/2.+5.5, 0, 18.32/2.]]) right_small_box = np.array([[W/2.-5.5, 0, 18.32/2.], [W/2., 0, 18.32/2.], [W/2., 0, -18.32/2.], [W/2.-5.5, 0, -18.32/2.]]) central_circle = np.array(make_field_circle(r=9.15, nn=1)) left_half_circile = np.array(make_field_circle(9.15)) left_half_circile[:, 0] = left_half_circile[:, 0] - W / 2. + 11.0 index = left_half_circile[:, 0] > (-W / 2. + 16.5) left_half_circile = left_half_circile[index, :] right_half_circile = np.array(make_field_circle(9.15)) right_half_circile[:, 0] = right_half_circile[:, 0] + W / 2. - 11.0 index = right_half_circile[:, 0] < (W / 2. - 16.5) right_half_circile = right_half_circile[index, :] return [outer_rectangle, left_big_box, right_big_box, left_small_box, right_small_box, left_half_circile, right_half_circile, central_circle, mid_line] def project_field_to_image(camera): field_list = get_field_points() field_points2d = [] for i in range(len(field_list)): tmp, depth = camera.project(field_list[i]) behind_points = (depth < 0).nonzero()[0] tmp[behind_points, :] *= -1 field_points2d.append(tmp) return field_points2d def draw_field(camera): field_points2d = project_field_to_image(camera) h, w = camera.height, camera.width # Check if the entities are 7 assert len(field_points2d) == 9 img_polygon = Polygon([(0, 0), (w - 1, 0), (w - 1, h - 1), (0, h - 1)]) canvas = np.zeros((h, w, 3), dtype=np.uint8) mask = np.zeros((h, w, 3), dtype=np.uint8) # Draw the boxes for i in range(5): # And make a new image with the projected field linea = LineString([(field_points2d[i][0, :]), (field_points2d[i][1, :])]) lineb = LineString([(field_points2d[i][1, :]), (field_points2d[i][2, :])]) linec = LineString([(field_points2d[i][2, :]), (field_points2d[i][3, :])]) lined = LineString([(field_points2d[i][3, :]), (field_points2d[i][0, :])]) if i == 0: polygon0 = Polygon([(field_points2d[i][0, :]), (field_points2d[i][1, :]), (field_points2d[i][2, :]), (field_points2d[i][3, :])]) intersect0 = img_polygon.intersection(polygon0) if not intersect0.is_empty: pts = np.array(list(intersect0.exterior.coords), dtype=np.int32) pts = pts[:, :].reshape((-1, 1, 2)) cv2.fillConvexPoly(mask, pts, (255, 255, 255)) intersect0 = img_polygon.intersection(linea) if not intersect0.is_empty: pts = np.array(list(list(intersect0.coords)), dtype=np.int32) cv2.line(canvas, (pts[0, 0], pts[0, 1]), (pts[1, 0], pts[1, 1]), (255, 255, 255)) intersect0 = img_polygon.intersection(lineb) if not intersect0.is_empty: pts = np.array(list(list(intersect0.coords)), dtype=np.int32) if pts.shape[0] < 2: continue cv2.line(canvas, (pts[0, 0], pts[0, 1]), (pts[1, 0], pts[1, 1]), (255, 255, 255)) intersect0 = img_polygon.intersection(linec) if not intersect0.is_empty: pts = np.array(list(list(intersect0.coords)), dtype=np.int32) if pts.shape[0] == 2: cv2.line(canvas, (pts[0, 0], pts[0, 1]), (pts[1, 0], pts[1, 1]), (255, 255, 255)) intersect0 = img_polygon.intersection(lined) if not intersect0.is_empty: pts = np.array(list(list(intersect0.coords)), dtype=np.int32) cv2.line(canvas, (pts[0, 0], pts[0, 1]), (pts[1, 0], pts[1, 1]), (255, 255, 255)) # Mid line line1 = LineString([(field_points2d[8][0, :]), (field_points2d[8][1, :])]) intersect1 = img_polygon.intersection(line1) if not intersect1.is_empty: pts = np.array(list(list(intersect1.coords)), dtype=np.int32) pts = pts[:, :].reshape((-1, 1, 2)) cv2.fillConvexPoly(canvas, pts, (255, 255, 255), ) # Circles for ii in range(5, 8): for i in range(field_points2d[ii].shape[0] - 1): line2 = LineString([(field_points2d[ii][i, :]), (field_points2d[ii][i + 1, :])]) intersect2 = img_polygon.intersection(line2) if not intersect2.is_empty: pts = np.array(list(list(intersect2.coords)), dtype=np.int32) pts = pts[:, :].reshape((-1, 1, 2)) cv2.fillConvexPoly(canvas, pts, (255, 255, 255), ) return canvas[:, :, 0] / 255., mask[:, :, 0] / 255. def draw_skeleton(keypoints, h, w): limps = np.array( [[0, 1], [1, 2], [2, 3], [3, 4], [1, 5], [5, 6], [6, 7], [1, 11], [11, 12], [12, 13], [1, 8], [8, 9], [9, 10], [14, 15], [16, 17], [0, 14], [0, 15], [14, 16], [15, 17], [8, 11], [2, 8], [5, 11]]) fg_label = 1 output = np.zeros((h, w, 3), dtype=np.float32) for k in range(limps.shape[0]): kp1, kp2 = limps[k, :].astype(int) bone_start = keypoints[kp1, :] bone_end = keypoints[kp2, :] bone_start[0] = np.maximum(np.minimum(bone_start[0], w - 1), 0.) bone_start[1] = np.maximum(np.minimum(bone_start[1], h - 1), 0.) bone_end[0] = np.maximum(np.minimum(bone_end[0], w - 1), 0.) bone_end[1] = np.maximum(np.minimum(bone_end[1], h - 1), 0.) if bone_start[2] > 0.0: output[int(bone_start[1]), int(bone_start[0])] = 1 cv2.circle(output, (int(bone_start[0]), int(bone_start[1])), 2, (fg_label, 0, 0), -1) if bone_end[2] > 0.0: output[int(bone_end[1]), int(bone_end[0])] = 1 cv2.circle(output, (int(bone_end[0]), int(bone_end[1])), 2, (fg_label, 0, 0), -1) if bone_start[2] > 0.0 and bone_end[2] > 0.0: cv2.line(output, (int(bone_start[0]), int(bone_start[1])), (int(bone_end[0]), int(bone_end[1])), (fg_label, 0, 0), 1) return output[:, :, 0] def draw_skeleton_on_image(img, poses, cmap_fun, one_color=False, pose_color=None): limps = np.array( [[0, 1], [1, 2], [2, 3], [3, 4], [1, 5], [5, 6], [6, 7], [1, 11], [11, 12], [12, 13], [1, 8], [8, 9], [9, 10], [14, 15], [16, 17], [0, 14], [0, 15], [14, 16], [15, 17], [8, 11], [2, 8], [5, 11]]) for i in range(len(poses)): if poses[i] is None: continue if one_color: clr = cmap_fun(0.5) else: if pose_color is None: clr = cmap_fun(i / float(len(poses))) else: clr = cmap_fun(pose_color[i]) for k in range(limps.shape[0]): kp1, kp2 = limps[k, :].astype(int) x1, y1, s1 = poses[i][kp1, :] x2, y2, s2 = poses[i][kp2, :] if s1 == 0 or s2 == 0: continue cv2.line(img, (int(x1), int(y1)), (int(x2), int(y2)), (int(clr[0]*255), int(clr[1]*255), int(clr[2]*255)), 3) def draw_skeleton_on_image_2dposes(img, poses, cmap_fun, one_color=False, pose_color=None): limps = np.array( [[0, 1], [1, 2], [2, 3], [3, 4], [1, 5], [5, 6], [6, 7], [1, 11], [11, 12], [12, 13], [1, 8], [8, 9], [9, 10], [14, 15], [16, 17], [0, 14], [0, 15], [14, 16], [15, 17], [8, 11], [2, 8], [5, 11]]) for i in range(len(poses)): if poses[i] is None: continue if one_color: clr = cmap_fun(0.5) else: if pose_color is None: clr = cmap_fun(i / float(len(poses))) else: clr = cmap_fun(pose_color[i]) for k in range(limps.shape[0]): kp1, kp2 = limps[k, :].astype(int) x1, y1 = poses[kp1][0] x2, y2 = poses[kp2][0] cv2.line(img, (int(x1), int(y1)), (int(x2), int(y2)), (int(clr[0]*255), int(clr[1]*255), int(clr[2]*255)), 3) def draw_skeleton_on_image_2dposes_color(img, poses, color, lineType): limps = np.array( [[0, 1], [1, 2], [2, 3], [3, 4], [1, 5], [5, 6], [6, 7], [1, 11], [11, 12], [12, 13], [1, 8], [8, 9], [9, 10], [14, 15], [16, 17], [0, 14], [0, 15], [14, 16], [15, 17], [8, 11], [2, 8], [5, 11]]) for i in range(len(poses)): if poses[i] is None: continue for k in range(limps.shape[0]): kp1, kp2 = limps[k, :].astype(int) x1, y1 = poses[kp1][0] x2, y2 = poses[kp2][0] cv2.line(img, (int(x1), int(y1)), (int(x2), int(y2)), color, lineType) ################################################################################ # Project all players on the frame number image of the given db_cam # -> get the players_3d array as argument ################################################################################ def project_3d_players_on_image(db_cam, players_3d, frame, num=1): frame_name = db_cam.frame_basenames[frame] camera = cam_utils.Camera("Cam", db_cam.calib[frame_name]['A'], db_cam.calib[frame_name]['R'], db_cam.calib[frame_name]['T'], db_cam.shape[0], db_cam.shape[1]) cmap = matplotlib.cm.get_cmap('hsv') img = db_cam.get_frame(frame, dtype=np.uint8) for k in players_3d: points2d = [] for i in range(len(players_3d[k])): tmp, depth = camera.project(players_3d[k][i]) behind_points = (depth < 0).nonzero()[0] tmp[behind_points, :] *= -1 points2d.append(tmp) draw_skeleton_on_image_2dposes(img, points2d, cmap, one_color=True) num_str = str(num) cv2.imwrite('~/Downloads/'+ db_cam.name + '_3d_'+ num_str + '.jpg',np.uint8(img[:, :, (2, 1, 0)])) ################################################################################ # Project the players on the frame number image of the given db_cam ################################################################################ def draw_2d_players_on_image(db_cam, players_2d, frame, player=False): cmap = matplotlib.cm.get_cmap('hsv') img = db_cam.get_frame(frame, dtype=np.uint8) # if just one player: place in array to get draw working if (player): draw_skeleton_on_image_2dposes(img, players_2d[player], cmap, one_color=True) else: for i in range (len(players_2d)): draw_skeleton_on_image_2dposes(img, players_2d[i], cmap, one_color=True) cv2.imwrite('~/Downloads/'+ db_cam.name + '_2d' + '.jpg',np.uint8(img[:, :, (2, 1, 0)])) ################################################################################ # Draw all players (2D dictionary) on the first (frame 0) image from one Kamera db_cam: # players_2d_dict: [[x,y,prec]] ################################################################################ def draw_openpose_on_image(db_cam, players_2d_dict, frame, player=False): # if just one player: place in array to get draw working cmap = matplotlib.cm.get_cmap('hsv') img = db_cam.get_frame(frame, dtype=np.uint8) if (player): print("Just one player projected") draw_skeleton_on_image(img, [players_2d_dict[player]], cmap, one_color=True) else: players_2d = [ v for v in players_2d_dict.values() ] draw_skeleton_on_image(img, players_2d, cmap, one_color=True) cv2.imwrite('~/Downloads/'+ db_cam.name + '_openpose' + '.jpg',np.uint8(img[:, :, (2, 1, 0)]))
[ "cv2.line", "numpy.uint8", "numpy.minimum", "numpy.arctan2", "shapely.geometry.Polygon", "matplotlib.cm.get_cmap", "numpy.zeros", "plotly.offline.plot", "shapely.geometry.LineString", "numpy.sin", "numpy.asmatrix", "numpy.array", "numpy.cos", "cv2.fillConvexPoly", "utils.camera.Camera" ]
[((2573, 2644), 'plotly.offline.plot', 'py.offline.plot', (['fig'], {'filename': '"""/home/bunert/Data/results/players.html"""'}), "(fig, filename='/home/bunert/Data/results/players.html')\n", (2588, 2644), True, 'import plotly as py\n'), ((2706, 2919), 'numpy.array', 'np.array', (['[[0, 1], [1, 2], [2, 3], [3, 4], [1, 5], [5, 6], [6, 7], [1, 11], [11, 12],\n [12, 13], [1, 8], [8, 9], [9, 10], [14, 15], [16, 17], [0, 14], [0, 15],\n [14, 16], [15, 17], [8, 11], [2, 8], [5, 11]]'], {}), '([[0, 1], [1, 2], [2, 3], [3, 4], [1, 5], [5, 6], [6, 7], [1, 11],\n [11, 12], [12, 13], [1, 8], [8, 9], [9, 10], [14, 15], [16, 17], [0, 14\n ], [0, 15], [14, 16], [15, 17], [8, 11], [2, 8], [5, 11]])\n', (2714, 2919), True, 'import numpy as np\n'), ((2938, 2958), 'numpy.asmatrix', 'np.asmatrix', (['players'], {}), '(players)\n', (2949, 2958), True, 'import numpy as np\n'), ((4283, 4393), 'numpy.array', 'np.array', (['[[-W / 2.0, 0, H / 2.0], [-W / 2.0, 0, -H / 2.0], [W / 2.0, 0, -H / 2.0], [\n W / 2.0, 0, H / 2.0]]'], {}), '([[-W / 2.0, 0, H / 2.0], [-W / 2.0, 0, -H / 2.0], [W / 2.0, 0, -H /\n 2.0], [W / 2.0, 0, H / 2.0]])\n', (4291, 4393), True, 'import numpy as np\n'), ((4498, 4641), 'numpy.array', 'np.array', (['[[-W / 2.0, 0, 40.32 / 2.0], [-W / 2.0, 0, -40.32 / 2.0], [-W / 2.0 + 16.5,\n 0, -40.32 / 2.0], [-W / 2.0 + 16.5, 0, 40.32 / 2.0]]'], {}), '([[-W / 2.0, 0, 40.32 / 2.0], [-W / 2.0, 0, -40.32 / 2.0], [-W / \n 2.0 + 16.5, 0, -40.32 / 2.0], [-W / 2.0 + 16.5, 0, 40.32 / 2.0]])\n', (4506, 4641), True, 'import numpy as np\n'), ((4731, 4869), 'numpy.array', 'np.array', (['[[W / 2.0 - 16.5, 0, 40.32 / 2.0], [W / 2.0, 0, 40.32 / 2.0], [W / 2.0, 0, \n -40.32 / 2.0], [W / 2.0 - 16.5, 0, -40.32 / 2.0]]'], {}), '([[W / 2.0 - 16.5, 0, 40.32 / 2.0], [W / 2.0, 0, 40.32 / 2.0], [W /\n 2.0, 0, -40.32 / 2.0], [W / 2.0 - 16.5, 0, -40.32 / 2.0]])\n', (4739, 4869), True, 'import numpy as np\n'), ((4950, 5091), 'numpy.array', 'np.array', (['[[-W / 2.0, 0, 18.32 / 2.0], [-W / 2.0, 0, -18.32 / 2.0], [-W / 2.0 + 5.5, \n 0, -18.32 / 2.0], [-W / 2.0 + 5.5, 0, 18.32 / 2.0]]'], {}), '([[-W / 2.0, 0, 18.32 / 2.0], [-W / 2.0, 0, -18.32 / 2.0], [-W / \n 2.0 + 5.5, 0, -18.32 / 2.0], [-W / 2.0 + 5.5, 0, 18.32 / 2.0]])\n', (4958, 5091), True, 'import numpy as np\n'), ((5185, 5322), 'numpy.array', 'np.array', (['[[W / 2.0 - 5.5, 0, 18.32 / 2.0], [W / 2.0, 0, 18.32 / 2.0], [W / 2.0, 0, -\n 18.32 / 2.0], [W / 2.0 - 5.5, 0, -18.32 / 2.0]]'], {}), '([[W / 2.0 - 5.5, 0, 18.32 / 2.0], [W / 2.0, 0, 18.32 / 2.0], [W / \n 2.0, 0, -18.32 / 2.0], [W / 2.0 - 5.5, 0, -18.32 / 2.0]])\n', (5193, 5322), True, 'import numpy as np\n'), ((5402, 5451), 'numpy.array', 'np.array', (['[[0.0, 0.0, H / 2], [0.0, 0.0, -H / 2]]'], {}), '([[0.0, 0.0, H / 2], [0.0, 0.0, -H / 2]])\n', (5410, 5451), True, 'import numpy as np\n'), ((9244, 9416), 'utils.camera.Camera', 'cam_utils.Camera', (['name', "db.calib[db.frame_basenames[0]]['A']", "db.calib[db.frame_basenames[0]]['R']", "db.calib[db.frame_basenames[0]]['T']", 'db.shape[0]', 'db.shape[1]'], {}), "(name, db.calib[db.frame_basenames[0]]['A'], db.calib[db.\n frame_basenames[0]]['R'], db.calib[db.frame_basenames[0]]['T'], db.\n shape[0], db.shape[1])\n", (9260, 9416), True, 'import utils.camera as cam_utils\n'), ((10147, 10257), 'numpy.array', 'np.array', (['[[-W / 2.0, 0, H / 2.0], [-W / 2.0, 0, -H / 2.0], [W / 2.0, 0, -H / 2.0], [\n W / 2.0, 0, H / 2.0]]'], {}), '([[-W / 2.0, 0, H / 2.0], [-W / 2.0, 0, -H / 2.0], [W / 2.0, 0, -H /\n 2.0], [W / 2.0, 0, H / 2.0]])\n', (10155, 10257), True, 'import numpy as np\n'), ((10358, 10407), 'numpy.array', 'np.array', (['[[0.0, 0.0, H / 2], [0.0, 0.0, -H / 2]]'], {}), '([[0.0, 0.0, H / 2], [0.0, 0.0, -H / 2]])\n', (10366, 10407), True, 'import numpy as np\n'), ((10449, 10592), 'numpy.array', 'np.array', (['[[-W / 2.0, 0, 40.32 / 2.0], [-W / 2.0, 0, -40.32 / 2.0], [-W / 2.0 + 16.5,\n 0, -40.32 / 2.0], [-W / 2.0 + 16.5, 0, 40.32 / 2.0]]'], {}), '([[-W / 2.0, 0, 40.32 / 2.0], [-W / 2.0, 0, -40.32 / 2.0], [-W / \n 2.0 + 16.5, 0, -40.32 / 2.0], [-W / 2.0 + 16.5, 0, 40.32 / 2.0]])\n', (10457, 10592), True, 'import numpy as np\n'), ((10680, 10818), 'numpy.array', 'np.array', (['[[W / 2.0 - 16.5, 0, 40.32 / 2.0], [W / 2.0, 0, 40.32 / 2.0], [W / 2.0, 0, \n -40.32 / 2.0], [W / 2.0 - 16.5, 0, -40.32 / 2.0]]'], {}), '([[W / 2.0 - 16.5, 0, 40.32 / 2.0], [W / 2.0, 0, 40.32 / 2.0], [W /\n 2.0, 0, -40.32 / 2.0], [W / 2.0 - 16.5, 0, -40.32 / 2.0]])\n', (10688, 10818), True, 'import numpy as np\n'), ((10899, 11040), 'numpy.array', 'np.array', (['[[-W / 2.0, 0, 18.32 / 2.0], [-W / 2.0, 0, -18.32 / 2.0], [-W / 2.0 + 5.5, \n 0, -18.32 / 2.0], [-W / 2.0 + 5.5, 0, 18.32 / 2.0]]'], {}), '([[-W / 2.0, 0, 18.32 / 2.0], [-W / 2.0, 0, -18.32 / 2.0], [-W / \n 2.0 + 5.5, 0, -18.32 / 2.0], [-W / 2.0 + 5.5, 0, 18.32 / 2.0]])\n', (10907, 11040), True, 'import numpy as np\n'), ((11134, 11271), 'numpy.array', 'np.array', (['[[W / 2.0 - 5.5, 0, 18.32 / 2.0], [W / 2.0, 0, 18.32 / 2.0], [W / 2.0, 0, -\n 18.32 / 2.0], [W / 2.0 - 5.5, 0, -18.32 / 2.0]]'], {}), '([[W / 2.0 - 5.5, 0, 18.32 / 2.0], [W / 2.0, 0, 18.32 / 2.0], [W / \n 2.0, 0, -18.32 / 2.0], [W / 2.0 - 5.5, 0, -18.32 / 2.0]])\n', (11142, 11271), True, 'import numpy as np\n'), ((12588, 12645), 'shapely.geometry.Polygon', 'Polygon', (['[(0, 0), (w - 1, 0), (w - 1, h - 1), (0, h - 1)]'], {}), '([(0, 0), (w - 1, 0), (w - 1, h - 1), (0, h - 1)])\n', (12595, 12645), False, 'from shapely.geometry import LineString, Polygon\n'), ((12660, 12695), 'numpy.zeros', 'np.zeros', (['(h, w, 3)'], {'dtype': 'np.uint8'}), '((h, w, 3), dtype=np.uint8)\n', (12668, 12695), True, 'import numpy as np\n'), ((12707, 12742), 'numpy.zeros', 'np.zeros', (['(h, w, 3)'], {'dtype': 'np.uint8'}), '((h, w, 3), dtype=np.uint8)\n', (12715, 12742), True, 'import numpy as np\n'), ((15002, 15064), 'shapely.geometry.LineString', 'LineString', (['[field_points2d[8][0, :], field_points2d[8][1, :]]'], {}), '([field_points2d[8][0, :], field_points2d[8][1, :]])\n', (15012, 15064), False, 'from shapely.geometry import LineString, Polygon\n'), ((15974, 16187), 'numpy.array', 'np.array', (['[[0, 1], [1, 2], [2, 3], [3, 4], [1, 5], [5, 6], [6, 7], [1, 11], [11, 12],\n [12, 13], [1, 8], [8, 9], [9, 10], [14, 15], [16, 17], [0, 14], [0, 15],\n [14, 16], [15, 17], [8, 11], [2, 8], [5, 11]]'], {}), '([[0, 1], [1, 2], [2, 3], [3, 4], [1, 5], [5, 6], [6, 7], [1, 11],\n [11, 12], [12, 13], [1, 8], [8, 9], [9, 10], [14, 15], [16, 17], [0, 14\n ], [0, 15], [14, 16], [15, 17], [8, 11], [2, 8], [5, 11]])\n', (15982, 16187), True, 'import numpy as np\n'), ((16229, 16266), 'numpy.zeros', 'np.zeros', (['(h, w, 3)'], {'dtype': 'np.float32'}), '((h, w, 3), dtype=np.float32)\n', (16237, 16266), True, 'import numpy as np\n'), ((17418, 17631), 'numpy.array', 'np.array', (['[[0, 1], [1, 2], [2, 3], [3, 4], [1, 5], [5, 6], [6, 7], [1, 11], [11, 12],\n [12, 13], [1, 8], [8, 9], [9, 10], [14, 15], [16, 17], [0, 14], [0, 15],\n [14, 16], [15, 17], [8, 11], [2, 8], [5, 11]]'], {}), '([[0, 1], [1, 2], [2, 3], [3, 4], [1, 5], [5, 6], [6, 7], [1, 11],\n [11, 12], [12, 13], [1, 8], [8, 9], [9, 10], [14, 15], [16, 17], [0, 14\n ], [0, 15], [14, 16], [15, 17], [8, 11], [2, 8], [5, 11]])\n', (17426, 17631), True, 'import numpy as np\n'), ((18428, 18641), 'numpy.array', 'np.array', (['[[0, 1], [1, 2], [2, 3], [3, 4], [1, 5], [5, 6], [6, 7], [1, 11], [11, 12],\n [12, 13], [1, 8], [8, 9], [9, 10], [14, 15], [16, 17], [0, 14], [0, 15],\n [14, 16], [15, 17], [8, 11], [2, 8], [5, 11]]'], {}), '([[0, 1], [1, 2], [2, 3], [3, 4], [1, 5], [5, 6], [6, 7], [1, 11],\n [11, 12], [12, 13], [1, 8], [8, 9], [9, 10], [14, 15], [16, 17], [0, 14\n ], [0, 15], [14, 16], [15, 17], [8, 11], [2, 8], [5, 11]])\n', (18436, 18641), True, 'import numpy as np\n'), ((19343, 19556), 'numpy.array', 'np.array', (['[[0, 1], [1, 2], [2, 3], [3, 4], [1, 5], [5, 6], [6, 7], [1, 11], [11, 12],\n [12, 13], [1, 8], [8, 9], [9, 10], [14, 15], [16, 17], [0, 14], [0, 15],\n [14, 16], [15, 17], [8, 11], [2, 8], [5, 11]]'], {}), '([[0, 1], [1, 2], [2, 3], [3, 4], [1, 5], [5, 6], [6, 7], [1, 11],\n [11, 12], [12, 13], [1, 8], [8, 9], [9, 10], [14, 15], [16, 17], [0, 14\n ], [0, 15], [14, 16], [15, 17], [8, 11], [2, 8], [5, 11]])\n', (19351, 19556), True, 'import numpy as np\n'), ((20292, 20451), 'utils.camera.Camera', 'cam_utils.Camera', (['"""Cam"""', "db_cam.calib[frame_name]['A']", "db_cam.calib[frame_name]['R']", "db_cam.calib[frame_name]['T']", 'db_cam.shape[0]', 'db_cam.shape[1]'], {}), "('Cam', db_cam.calib[frame_name]['A'], db_cam.calib[\n frame_name]['R'], db_cam.calib[frame_name]['T'], db_cam.shape[0],\n db_cam.shape[1])\n", (20308, 20451), True, 'import utils.camera as cam_utils\n'), ((20455, 20484), 'matplotlib.cm.get_cmap', 'matplotlib.cm.get_cmap', (['"""hsv"""'], {}), "('hsv')\n", (20477, 20484), False, 'import matplotlib\n'), ((21327, 21356), 'matplotlib.cm.get_cmap', 'matplotlib.cm.get_cmap', (['"""hsv"""'], {}), "('hsv')\n", (21349, 21356), False, 'import matplotlib\n'), ((22233, 22262), 'matplotlib.cm.get_cmap', 'matplotlib.cm.get_cmap', (['"""hsv"""'], {}), "('hsv')\n", (22255, 22262), False, 'import matplotlib\n'), ((12861, 12923), 'shapely.geometry.LineString', 'LineString', (['[field_points2d[i][0, :], field_points2d[i][1, :]]'], {}), '([field_points2d[i][0, :], field_points2d[i][1, :]])\n', (12871, 12923), False, 'from shapely.geometry import LineString, Polygon\n'), ((12973, 13035), 'shapely.geometry.LineString', 'LineString', (['[field_points2d[i][1, :], field_points2d[i][2, :]]'], {}), '([field_points2d[i][1, :], field_points2d[i][2, :]])\n', (12983, 13035), False, 'from shapely.geometry import LineString, Polygon\n'), ((13085, 13147), 'shapely.geometry.LineString', 'LineString', (['[field_points2d[i][2, :], field_points2d[i][3, :]]'], {}), '([field_points2d[i][2, :], field_points2d[i][3, :]])\n', (13095, 13147), False, 'from shapely.geometry import LineString, Polygon\n'), ((13197, 13259), 'shapely.geometry.LineString', 'LineString', (['[field_points2d[i][3, :], field_points2d[i][0, :]]'], {}), '([field_points2d[i][3, :], field_points2d[i][0, :]])\n', (13207, 13259), False, 'from shapely.geometry import LineString, Polygon\n'), ((15297, 15345), 'cv2.fillConvexPoly', 'cv2.fillConvexPoly', (['canvas', 'pts', '(255, 255, 255)'], {}), '(canvas, pts, (255, 255, 255))\n', (15315, 15345), False, 'import cv2\n'), ((20981, 21011), 'numpy.uint8', 'np.uint8', (['img[:, :, (2, 1, 0)]'], {}), '(img[:, :, (2, 1, 0)])\n', (20989, 21011), True, 'import numpy as np\n'), ((21771, 21801), 'numpy.uint8', 'np.uint8', (['img[:, :, (2, 1, 0)]'], {}), '(img[:, :, (2, 1, 0)])\n', (21779, 21801), True, 'import numpy as np\n'), ((22666, 22696), 'numpy.uint8', 'np.uint8', (['img[:, :, (2, 1, 0)]'], {}), '(img[:, :, (2, 1, 0)])\n', (22674, 22696), True, 'import numpy as np\n'), ((13335, 13449), 'shapely.geometry.Polygon', 'Polygon', (['[field_points2d[i][0, :], field_points2d[i][1, :], field_points2d[i][2, :],\n field_points2d[i][3, :]]'], {}), '([field_points2d[i][0, :], field_points2d[i][1, :], field_points2d[i\n ][2, :], field_points2d[i][3, :]])\n', (13342, 13449), False, 'from shapely.geometry import LineString, Polygon\n'), ((14022, 14107), 'cv2.line', 'cv2.line', (['canvas', '(pts[0, 0], pts[0, 1])', '(pts[1, 0], pts[1, 1])', '(255, 255, 255)'], {}), '(canvas, (pts[0, 0], pts[0, 1]), (pts[1, 0], pts[1, 1]), (255, 255,\n 255))\n', (14030, 14107), False, 'import cv2\n'), ((14338, 14423), 'cv2.line', 'cv2.line', (['canvas', '(pts[0, 0], pts[0, 1])', '(pts[1, 0], pts[1, 1])', '(255, 255, 255)'], {}), '(canvas, (pts[0, 0], pts[0, 1]), (pts[1, 0], pts[1, 1]), (255, 255,\n 255))\n', (14346, 14423), False, 'import cv2\n'), ((14892, 14977), 'cv2.line', 'cv2.line', (['canvas', '(pts[0, 0], pts[0, 1])', '(pts[1, 0], pts[1, 1])', '(255, 255, 255)'], {}), '(canvas, (pts[0, 0], pts[0, 1]), (pts[1, 0], pts[1, 1]), (255, 255,\n 255))\n', (14900, 14977), False, 'import cv2\n'), ((15467, 15535), 'shapely.geometry.LineString', 'LineString', (['[field_points2d[ii][i, :], field_points2d[ii][i + 1, :]]'], {}), '([field_points2d[ii][i, :], field_points2d[ii][i + 1, :]])\n', (15477, 15535), False, 'from shapely.geometry import LineString, Polygon\n'), ((16458, 16490), 'numpy.minimum', 'np.minimum', (['bone_start[0]', '(w - 1)'], {}), '(bone_start[0], w - 1)\n', (16468, 16490), True, 'import numpy as np\n'), ((16531, 16563), 'numpy.minimum', 'np.minimum', (['bone_start[1]', '(h - 1)'], {}), '(bone_start[1], h - 1)\n', (16541, 16563), True, 'import numpy as np\n'), ((16603, 16633), 'numpy.minimum', 'np.minimum', (['bone_end[0]', '(w - 1)'], {}), '(bone_end[0], w - 1)\n', (16613, 16633), True, 'import numpy as np\n'), ((16672, 16702), 'numpy.minimum', 'np.minimum', (['bone_end[1]', '(h - 1)'], {}), '(bone_end[1], h - 1)\n', (16682, 16702), True, 'import numpy as np\n'), ((3590, 3615), 'numpy.cos', 'np.cos', (['(2 * np.pi / n * x)'], {}), '(2 * np.pi / n * x)\n', (3596, 3615), True, 'import numpy as np\n'), ((3624, 3649), 'numpy.sin', 'np.sin', (['(2 * np.pi / n * x)'], {}), '(2 * np.pi / n * x)\n', (3630, 3649), True, 'import numpy as np\n'), ((3947, 3973), 'numpy.arctan2', 'np.arctan2', (['(y - cy)', '(x - cx)'], {}), '(y - cy, x - cx)\n', (3957, 3973), True, 'import numpy as np\n'), ((13799, 13845), 'cv2.fillConvexPoly', 'cv2.fillConvexPoly', (['mask', 'pts', '(255, 255, 255)'], {}), '(mask, pts, (255, 255, 255))\n', (13817, 13845), False, 'import cv2\n'), ((14634, 14719), 'cv2.line', 'cv2.line', (['canvas', '(pts[0, 0], pts[0, 1])', '(pts[1, 0], pts[1, 1])', '(255, 255, 255)'], {}), '(canvas, (pts[0, 0], pts[0, 1]), (pts[1, 0], pts[1, 1]), (255, 255,\n 255))\n', (14642, 14719), False, 'import cv2\n'), ((15815, 15863), 'cv2.fillConvexPoly', 'cv2.fillConvexPoly', (['canvas', 'pts', '(255, 255, 255)'], {}), '(canvas, pts, (255, 255, 255))\n', (15833, 15863), False, 'import cv2\n')]
import numpy as np import networkx as nx import matplotlib.pyplot as plt import matplotlib as mpl from .paths import paths_prob_to_edges_flux def flattened(G, scale=1, vertical=False): """Get flattened positions for a genotype-phenotype graph. Parameters ---------- G : GenotypePhenotypeGraph object A genotype-phenotype objects scale : float (default=1) density of the nodes. Returns ------- positions: dict positions of all nodes in network (i.e. {index: [x,y]}) """ # Get the binary genotypes from GPM # Set level of nodes and begin calc offset on the fly graph = G offsets = {} positions = {} for n in range(len(list(G.nodes()))): node = graph.node[n] # Calculate the level of each node level = node["binary"].count("1") if level in offsets: offsets[level] += 1 else: offsets[level] = 1 positions[n] = [level] # Center the offsets on 0 for key, val in offsets.items(): offsets[key] = list(np.arange(val) - (val-1)/2.0) # Offset positions if vertical: for n in range(len(list(G.nodes()))): pos = offsets[positions[n][0]].pop(0) scaled = scale*pos positions[n].insert(0, scaled) positions[n][-1] *= -1 else: for n in range(len(list(G.nodes()))): pos = offsets[positions[n][0]].pop(0) scaled = scale*pos positions[n].append(scaled) return positions def draw_flattened( G, ax=None, nodelist=[], vmin=None, vmax=None, cmap='plasma', colorbar=False, **kwds): """Draw the GenotypePhenotypeGraph using Matplotlib. Draw the graph with Matplotlib with options for node positions, labeling, titles, and many other drawing features. See draw() for simple drawing without labels or axes. Parameters ---------- G : graph A networkx graph pos : dictionary, optional A dictionary with nodes as keys and positions as values. If not specified a spring layout positioning will be computed. See :py:mod:`networkx.drawing.layout` for functions that compute node positions. arrows : bool, optional (default=False) For directed graphs, if True draw arrowheads. with_labels : bool, optional (default=True) Set to True to draw labels on the nodes. ax : Matplotlib Axes object, optional Draw the graph in the specified Matplotlib axes. nodelist : list, optional (default G.nodes()) Draw only specified nodes edgelist : list, optional (default=G.edges()) Draw only specified edges node_size : scalar or array, optional (default=300) Size of nodes. If an array is specified it must be the same length as nodelist. node_color : color string, or array of floats, (default=phenotypes) Node color. Can be a single color format string, or a sequence of colors with the same length as nodelist. If numeric values are specified they will be mapped to colors using the cmap and vmin,vmax parameters. See matplotlib.scatter for more details. node_shape : string, optional (default='o') The shape of the node. Specification is as matplotlib.scatter marker, one of 'so^>v<dph8'. alpha : float, optional (default=1.0) The node and edge transparency cmap : Matplotlib colormap, optional (default='plasmas') Colormap for mapping intensities of nodes vmin,vmax : float, optional (default=None) Minimum and maximum for node colormap scaling linewidths : [None | scalar | sequence] Line width of symbol border (default =1.0) width : float, optional (default=1.0) Line width of edges color_bar : False If True, show colorbar for nodes. edge_color : color string, or array of floats (default='gray') Edge color. Can be a single color format string, or a sequence of colors with the same length as edgelist. If numeric values are specified they will be mapped to colors using the edge_cmap and edge_vmin,edge_vmax parameters. edge_cmap : Matplotlib colormap, optional (default=None) Colormap for mapping intensities of edges edge_vmin,edge_vmax : floats, optional (default=None) Minimum and maximum for edge colormap scaling style : string, optional (default='solid') Edge line style (solid|dashed|dotted,dashdot) labels : dictionary, optional (default='genotypes') Node labels in a dictionary keyed by node of text labels font_size : int, optional (default=12) Font size for text labels font_color : string, optional (default='k' black) Font color string font_weight : string, optional (default='normal') Font weight font_family : string, optional (default='sans-serif') Font family label : string, optional Label for graph legend Notes ----- For directed graphs, "arrows" (actually just thicker stubs) are drawn at the head end. Arrows can be turned off with keyword arrows=False. Yes, it is ugly but drawing proper arrows with Matplotlib this way is tricky. """ if ax is None: fig, ax = plt.subplots() else: fig = ax.get_figure() ax.spines['right'].set_visible(False) ax.spines['left'].set_visible(False) ax.spines['top'].set_visible(False) ax.spines['bottom'].set_visible(False) ax.set_xticks([]) ax.set_yticks([]) # Flattened position pos = flattened(G, vertical=True) if not nodelist: nodelist = list(G.nodes().keys()) if vmax is None: phenotypes = G.gpm.phenotypes vmin = min(phenotypes) vmax = max(phenotypes) # Default options options = dict( pos=pos, nodelist=nodelist, arrows=False, vmin=vmin, vmax=vmax, node_color=[G.nodes[n]['phenotypes'] for n in nodelist], cmap=cmap, edge_color='gray', labels={n: G.nodes[n]['genotypes'] for n in nodelist} ) options.update(**kwds) # Draw fig nx.draw_networkx(G, **options) # Add a colorbar? if colorbar: norm = mpl.colors.Normalize( vmin=vmin, vmax=vmax) # create a ScalarMappable and initialize a data structure cm = mpl.cm.ScalarMappable(cmap=cmap, norm=norm) cm.set_array([]) fig.colorbar(cm) def draw_paths( G, paths, pos=None, edge_equal=False, edge_scalar=1.0, edge_color='k', style='solid', edge_alpha=1.0, arrows=False, arrowstyle='-|>', arrowsize=10, nodelist=None, node_size=300, node_color='r', node_shape='o', alpha=1.0, cmap='plasma', vmin=None, vmax=None, ax=None, linewidths=None, edgecolors=None, label=None, ): """Draw paths in GenotypePhenotypeGraph Parameters ---------- G : graph A networkx graph pos : dictionary A dictionary with nodes as keys and positions as values. Positions should be sequences of length 2. edgelist : collection of edge tuples Draw only specified edges(default=G.edges()) width : float, or array of floats Line width of edges (default=1.0) edge_color : color string, or array of floats Edge color. Can be a single color format string (default='r'), or a sequence of colors with the same length as edgelist. If numeric values are specified they will be mapped to colors using the edge_cmap and edge_vmin,edge_vmax parameters. style : string Edge line style (default='solid') (solid|dashed|dotted,dashdot) alpha : float The edge transparency (default=1.0) edge_ cmap : Matplotlib colormap Colormap for mapping intensities of edges (default=None) edge_vmin,edge_vmax : floats Minimum and maximum for edge colormap scaling (default=None) ax : Matplotlib Axes object, optional Draw the graph in the specified Matplotlib axes. arrows : bool, optional (default=True) For directed graphs, if True draw arrowheads. Note: Arrows will be the same color as edges. arrowstyle : str, optional (default='-|>') For directed graphs, choose the style of the arrow heads. See :py:class: `matplotlib.patches.ArrowStyle` for more options. arrowsize : int, optional (default=10) For directed graphs, choose the size of the arrow head head's length and width. See :py:class: `matplotlib.patches.FancyArrowPatch` for attribute `mutation_scale` for more info. label : [None| string] Label for legend """ # Get Figure. if ax is None: fig, ax = plt.subplots() else: fig = ax.get_figure() ax.spines['right'].set_visible(False) ax.spines['left'].set_visible(False) ax.spines['top'].set_visible(False) ax.spines['bottom'].set_visible(False) ax.set_xticks([]) ax.set_yticks([]) # Get positions of nodes. if pos is None: pos = flattened(G, vertical=True) # Get flux through edges edges = paths_prob_to_edges_flux(paths) edgelist = list(edges.keys()) edge_widths = np.array(list(edges.values())) if edge_equal: # Remove for zero prob edges edge_widths[edge_widths > 0] = 1 width = edge_scalar * edge_widths else: width = edge_scalar * edge_widths if not nodelist: nodelist = list(G.nodes().keys()) if vmax is None: phenotypes = G.gpm.phenotypes vmin = min(phenotypes) vmax = max(phenotypes) # Default options node_options = dict( nodelist=nodelist, vmin=vmin, vmax=vmax, node_size=node_size, node_color=[G.nodes[n]['phenotypes'] for n in nodelist], cmap=cmap, labels={n: G.nodes[n]['genotypes'] for n in nodelist} ) # Draw edges nx.draw_networkx_edges( G=G, pos=pos, edgelist=edgelist, width=width, edge_color=edge_color, ax=ax, style=style, alpha=edge_alpha, arrows=arrows, arrowstyle=arrowstyle, arrowsize=arrowsize, ) # Draw nodes. nx.draw_networkx_nodes( G=G, pos=pos, ax=ax, **node_options )
[ "networkx.draw_networkx_edges", "matplotlib.colors.Normalize", "matplotlib.cm.ScalarMappable", "networkx.draw_networkx", "networkx.draw_networkx_nodes", "numpy.arange", "matplotlib.pyplot.subplots" ]
[((6234, 6264), 'networkx.draw_networkx', 'nx.draw_networkx', (['G'], {}), '(G, **options)\n', (6250, 6264), True, 'import networkx as nx\n'), ((10099, 10296), 'networkx.draw_networkx_edges', 'nx.draw_networkx_edges', ([], {'G': 'G', 'pos': 'pos', 'edgelist': 'edgelist', 'width': 'width', 'edge_color': 'edge_color', 'ax': 'ax', 'style': 'style', 'alpha': 'edge_alpha', 'arrows': 'arrows', 'arrowstyle': 'arrowstyle', 'arrowsize': 'arrowsize'}), '(G=G, pos=pos, edgelist=edgelist, width=width,\n edge_color=edge_color, ax=ax, style=style, alpha=edge_alpha, arrows=\n arrows, arrowstyle=arrowstyle, arrowsize=arrowsize)\n', (10121, 10296), True, 'import networkx as nx\n'), ((10406, 10465), 'networkx.draw_networkx_nodes', 'nx.draw_networkx_nodes', ([], {'G': 'G', 'pos': 'pos', 'ax': 'ax'}), '(G=G, pos=pos, ax=ax, **node_options)\n', (10428, 10465), True, 'import networkx as nx\n'), ((5345, 5359), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (5357, 5359), True, 'import matplotlib.pyplot as plt\n'), ((6320, 6362), 'matplotlib.colors.Normalize', 'mpl.colors.Normalize', ([], {'vmin': 'vmin', 'vmax': 'vmax'}), '(vmin=vmin, vmax=vmax)\n', (6340, 6362), True, 'import matplotlib as mpl\n'), ((6468, 6511), 'matplotlib.cm.ScalarMappable', 'mpl.cm.ScalarMappable', ([], {'cmap': 'cmap', 'norm': 'norm'}), '(cmap=cmap, norm=norm)\n', (6489, 6511), True, 'import matplotlib as mpl\n'), ((8889, 8903), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (8901, 8903), True, 'import matplotlib.pyplot as plt\n'), ((1069, 1083), 'numpy.arange', 'np.arange', (['val'], {}), '(val)\n', (1078, 1083), True, 'import numpy as np\n')]
import numpy as np import tensorflow as tf import random import os from collections import deque from random import randint from envFive import envFive import player.dqn as dqn INPUT_SIZE = 12 OUTPUT_SIZE = 10 DISCOUNT_RATE = 0.99 REPLAY_MEMORY = 50000 MAX_EPISODE = 100000 BATCH_SIZE = 64 # minimum epsilon for epsilon greedy MIN_E = 0.0 # epsilon will be `MIN_E` at `EPSILON_DECAYING_EPISODE` #EPSILON_DECAYING_EPISODE = MAX_EPISODE * 0.01 EPSILON_DECAYING_EPISODE = MAX_EPISODE * 0.2 def annealing_epsilon(episode: int, min_e: float, max_e: float, target_episode: int) -> float: slope = (min_e - max_e) / (target_episode) intercept = max_e return max(min_e, slope * episode + intercept) def train_minibatch(DQN: dqn.DQN, train_batch: list) -> float: state_array = np.vstack([x[0] for x in train_batch]) action_array = np.array([x[1] for x in train_batch]) reward_array = np.array([x[2] for x in train_batch]) next_state_array = np.vstack([x[3] for x in train_batch]) done_array = np.array([x[4] for x in train_batch]) X_batch = state_array y_batch = DQN.predict(state_array) Q_target = reward_array + DISCOUNT_RATE * np.max(DQN.predict(next_state_array), axis=1) * ~done_array y_batch[np.arange(len(X_batch)), action_array] = Q_target # Train our network using target and predicted Q values on each episode loss, _ = DQN.update(X_batch, y_batch) return loss env = envFive() if __name__ == '__main__': print("HELL WORLD") replay_buffer = deque(maxlen=REPLAY_MEMORY) last_100_game_reward = deque(maxlen=100) # 연쇄를 끊는다...크큭 combo = 0 max_combo = 17 endgame = False with tf.Session() as sess: mainDQN = dqn.DQN(sess, INPUT_SIZE, OUTPUT_SIZE) init = tf.global_variables_initializer() sess.run(init) saver = tf.train.Saver() CHECK_POINT_DIR = "./save" for episode in range(MAX_EPISODE): e = annealing_epsilon(episode, MIN_E, 1.0, EPSILON_DECAYING_EPISODE) done = False state = env.reset() info = [] step_count = 0 while not done: if np.random.rand() < e: action = env.getRandomCardA() else: action = np.argmax(mainDQN.predict(state)) next_state, reward, done, info = env.step(action) if done: reward = -1 replay_buffer.append((state, action, reward, next_state, done)) state = next_state step_count += 1 if len(replay_buffer) > BATCH_SIZE and not endgame: minibatch = random.sample(replay_buffer, BATCH_SIZE) train_minibatch(mainDQN, minibatch) # 한 게임에서 승패여부 판정 및 출력 #print("[Episode {:>5}] steps: {:>5} e: {:>5.2f}".format(episode, step_count, e)) result = "?" if info[0] > info[1]: result = "승리" combo += 1 elif info[0] < info[1]: result = "패배" combo = 0 else: result = "동점" if combo > 11: print(str(episode) + " : " + result + " : " + str(combo)) # 최근 100 게임의 평균 측정 last_100_game_reward.append(step_count) if len(last_100_game_reward) == last_100_game_reward.maxlen: avg_reward = np.mean(last_100_game_reward) if avg_reward > 4.69: print("Reached goal within {} episodes with avg reward {}, combo {}".format(episode, avg_reward, combo)) if combo > 5 and e == 0: saver.save(sess, CHECK_POINT_DIR, global_step=episode) if not endgame and combo >= max_combo: print(str(max_combo) + "분할!") endgame = True
[ "tensorflow.train.Saver", "player.dqn.DQN", "tensorflow.global_variables_initializer", "random.sample", "tensorflow.Session", "numpy.mean", "numpy.array", "numpy.random.rand", "numpy.vstack", "envFive.envFive", "collections.deque" ]
[((1444, 1453), 'envFive.envFive', 'envFive', ([], {}), '()\n', (1451, 1453), False, 'from envFive import envFive\n'), ((794, 832), 'numpy.vstack', 'np.vstack', (['[x[0] for x in train_batch]'], {}), '([x[0] for x in train_batch])\n', (803, 832), True, 'import numpy as np\n'), ((852, 889), 'numpy.array', 'np.array', (['[x[1] for x in train_batch]'], {}), '([x[1] for x in train_batch])\n', (860, 889), True, 'import numpy as np\n'), ((909, 946), 'numpy.array', 'np.array', (['[x[2] for x in train_batch]'], {}), '([x[2] for x in train_batch])\n', (917, 946), True, 'import numpy as np\n'), ((970, 1008), 'numpy.vstack', 'np.vstack', (['[x[3] for x in train_batch]'], {}), '([x[3] for x in train_batch])\n', (979, 1008), True, 'import numpy as np\n'), ((1026, 1063), 'numpy.array', 'np.array', (['[x[4] for x in train_batch]'], {}), '([x[4] for x in train_batch])\n', (1034, 1063), True, 'import numpy as np\n'), ((1528, 1555), 'collections.deque', 'deque', ([], {'maxlen': 'REPLAY_MEMORY'}), '(maxlen=REPLAY_MEMORY)\n', (1533, 1555), False, 'from collections import deque\n'), ((1583, 1600), 'collections.deque', 'deque', ([], {'maxlen': '(100)'}), '(maxlen=100)\n', (1588, 1600), False, 'from collections import deque\n'), ((1688, 1700), 'tensorflow.Session', 'tf.Session', ([], {}), '()\n', (1698, 1700), True, 'import tensorflow as tf\n'), ((1728, 1766), 'player.dqn.DQN', 'dqn.DQN', (['sess', 'INPUT_SIZE', 'OUTPUT_SIZE'], {}), '(sess, INPUT_SIZE, OUTPUT_SIZE)\n', (1735, 1766), True, 'import player.dqn as dqn\n'), ((1782, 1815), 'tensorflow.global_variables_initializer', 'tf.global_variables_initializer', ([], {}), '()\n', (1813, 1815), True, 'import tensorflow as tf\n'), ((1856, 1872), 'tensorflow.train.Saver', 'tf.train.Saver', ([], {}), '()\n', (1870, 1872), True, 'import tensorflow as tf\n'), ((3503, 3532), 'numpy.mean', 'np.mean', (['last_100_game_reward'], {}), '(last_100_game_reward)\n', (3510, 3532), True, 'import numpy as np\n'), ((2200, 2216), 'numpy.random.rand', 'np.random.rand', ([], {}), '()\n', (2214, 2216), True, 'import numpy as np\n'), ((2732, 2772), 'random.sample', 'random.sample', (['replay_buffer', 'BATCH_SIZE'], {}), '(replay_buffer, BATCH_SIZE)\n', (2745, 2772), False, 'import random\n')]
from si_prefix import si_format import numpy as np known_units = {"mA" : 1e-3, "uA" : 1e-6, "nA" : 1e-9, "pA" : 1e-12, "fA" : 1e-15, "nV" : 1e-9, "uV" : 1e-6, "mV" : 1e-3, "ns" : 1e-9, "us" : 1e-6, "ms" : 1e-3, "KHz" : 1e3, "MHz" : 1e6, "GHz" : 1e9 } def fix_units(unit): scaler = 1 if unit in known_units.keys(): scaler = known_units[unit] unit = unit[1:] return unit, scaler def format_value_and_unit(value, unit, precision = 1): unit, scaler = fix_units(unit) if np.isnan(value): value = 0 return si_format(value*scaler,precision) + unit def format_unit(unit): return fix_units(unit)[0] def return_unit_scaler(unit): return fix_units(unit)[1] if __name__ == '__main__': s =format_value_and_unit(50, 'mV', precision = 3) print(s)
[ "si_prefix.si_format", "numpy.isnan" ]
[((569, 584), 'numpy.isnan', 'np.isnan', (['value'], {}), '(value)\n', (577, 584), True, 'import numpy as np\n'), ((615, 651), 'si_prefix.si_format', 'si_format', (['(value * scaler)', 'precision'], {}), '(value * scaler, precision)\n', (624, 651), False, 'from si_prefix import si_format\n')]
import cfg import sys import onnx import numpy as np import cv2 import onnxruntime import logging from tool.utils import plot_boxes_cv2, post_processing, load_class_names # Logging Setup logger = logging.getLogger(__name__) logger.setLevel(logging.INFO) file_handler = logging.FileHandler("logs/detector.log") formatter = logging.Formatter("%(asctime)s:%(levelname)s:%(name)s:%(message)s") file_handler.setFormatter(formatter) logger.addHandler(file_handler) model = onnxruntime.InferenceSession(cfg.MODEL_PATH) logger.info(f"Model loaded") class Detector: def __init__(self, image_path, filename): self.image_path = image_path self.filename = filename def detect(self): """Detect if image is Aadhaar and save image if detected""" logger.info(f"The model expects input shape: {model.get_inputs()[0].shape}") image_src = cv2.imread(self.image_path) IN_IMAGE_H = model.get_inputs()[0].shape[2] IN_IMAGE_W = model.get_inputs()[0].shape[3] # Input resized = cv2.resize( image_src, (IN_IMAGE_W, IN_IMAGE_H), interpolation=cv2.INTER_LINEAR ) img_in = cv2.cvtColor(resized, cv2.COLOR_BGR2RGB) img_in = np.transpose(img_in, (2, 0, 1)).astype(np.float32) img_in = np.expand_dims(img_in, axis=0) img_in /= 255.0 logger.info(f"Shape of the network input after preprocessing: {img_in.shape}") # Compute input_name = model.get_inputs()[0].name outputs = model.run(None, {input_name: img_in}) boxes = post_processing(img_in, 0.4, 0.6, outputs) logger.info(f"Post Processing output : {boxes}") if np.array(boxes).size: namesfile = cfg.NAMESFILE class_names = load_class_names(namesfile) if plot_boxes_cv2( image_src, boxes[0], savename=self.filename, class_names=class_names ): # Detect image and save image with bounding boxes if Aadhaar card detected return 1 else: return 0 else: logger.info("Uploaded Image is not Aadhaar") return 0
[ "cv2.resize", "logging.FileHandler", "cv2.cvtColor", "numpy.transpose", "numpy.expand_dims", "logging.Formatter", "onnxruntime.InferenceSession", "cv2.imread", "tool.utils.load_class_names", "numpy.array", "tool.utils.plot_boxes_cv2", "tool.utils.post_processing", "logging.getLogger" ]
[((197, 224), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (214, 224), False, 'import logging\n'), ((271, 311), 'logging.FileHandler', 'logging.FileHandler', (['"""logs/detector.log"""'], {}), "('logs/detector.log')\n", (290, 311), False, 'import logging\n'), ((324, 391), 'logging.Formatter', 'logging.Formatter', (['"""%(asctime)s:%(levelname)s:%(name)s:%(message)s"""'], {}), "('%(asctime)s:%(levelname)s:%(name)s:%(message)s')\n", (341, 391), False, 'import logging\n'), ((471, 515), 'onnxruntime.InferenceSession', 'onnxruntime.InferenceSession', (['cfg.MODEL_PATH'], {}), '(cfg.MODEL_PATH)\n', (499, 515), False, 'import onnxruntime\n'), ((878, 905), 'cv2.imread', 'cv2.imread', (['self.image_path'], {}), '(self.image_path)\n', (888, 905), False, 'import cv2\n'), ((1045, 1124), 'cv2.resize', 'cv2.resize', (['image_src', '(IN_IMAGE_W, IN_IMAGE_H)'], {'interpolation': 'cv2.INTER_LINEAR'}), '(image_src, (IN_IMAGE_W, IN_IMAGE_H), interpolation=cv2.INTER_LINEAR)\n', (1055, 1124), False, 'import cv2\n'), ((1164, 1204), 'cv2.cvtColor', 'cv2.cvtColor', (['resized', 'cv2.COLOR_BGR2RGB'], {}), '(resized, cv2.COLOR_BGR2RGB)\n', (1176, 1204), False, 'import cv2\n'), ((1290, 1320), 'numpy.expand_dims', 'np.expand_dims', (['img_in'], {'axis': '(0)'}), '(img_in, axis=0)\n', (1304, 1320), True, 'import numpy as np\n'), ((1573, 1615), 'tool.utils.post_processing', 'post_processing', (['img_in', '(0.4)', '(0.6)', 'outputs'], {}), '(img_in, 0.4, 0.6, outputs)\n', (1588, 1615), False, 'from tool.utils import plot_boxes_cv2, post_processing, load_class_names\n'), ((1685, 1700), 'numpy.array', 'np.array', (['boxes'], {}), '(boxes)\n', (1693, 1700), True, 'import numpy as np\n'), ((1772, 1799), 'tool.utils.load_class_names', 'load_class_names', (['namesfile'], {}), '(namesfile)\n', (1788, 1799), False, 'from tool.utils import plot_boxes_cv2, post_processing, load_class_names\n'), ((1815, 1904), 'tool.utils.plot_boxes_cv2', 'plot_boxes_cv2', (['image_src', 'boxes[0]'], {'savename': 'self.filename', 'class_names': 'class_names'}), '(image_src, boxes[0], savename=self.filename, class_names=\n class_names)\n', (1829, 1904), False, 'from tool.utils import plot_boxes_cv2, post_processing, load_class_names\n'), ((1222, 1253), 'numpy.transpose', 'np.transpose', (['img_in', '(2, 0, 1)'], {}), '(img_in, (2, 0, 1))\n', (1234, 1253), True, 'import numpy as np\n')]
# Copyright 2020 Tsinghua University, Author: <NAME> # Apache 2.0. # This script contrains TRF semi-supervised (JRF) training experiments. import tensorflow as tf import numpy as np import json import os from base import * import trf_semi import argparse paser = argparse.ArgumentParser() paser.add_argument('--alpha', default=0.1, type=float) paser.add_argument('--cw', default=1, type=float) paser.add_argument('--tw', default=0, type=float) paser.add_argument('--data', default='one-ten', type=str) paser.add_argument('--task', default='pos', type=str) paser.add_argument('--sf', default='', type=str) paser.add_argument('--model', default='', type=str) paser.add_argument('--mode', default='train', type=str) paser.add_argument('--bs', default=32, type=int) paser.add_argument('--lr', default = 0.1, type=float) paser.add_argument('--do', default=0.5, type=float) paser.add_argument('--unl', default=50, type=int) paser.add_argument('--lab', default=1, type=int) paser.add_argument('--lrd', default=0.03, type=float) paser.add_argument('--nbest', default=0, type=int) paser.add_argument('--opt', default='momentum', type=str) paser.add_argument('--std', default=1, type=int) paser.add_argument('--word_emb', action='store_false', default=True) paser.add_argument('--steps', default=0, type=int) paser.add_argument('--seed', default=1, type=int) paser.add_argument('--sgd', default=0, type=int) paser.add_argument('--maxnorm', default=10, type=float) paser.add_argument('--maxstep', default=0, type=int) paser.add_argument('--hl', default=1, type=int) # 'train1000/trf_noise1.0_blstm_cnn_we100_ce30_c2wcnn_dropout0.5_adampretrain_baseline/crf_models/TRF-uns_ep11.ckpt' args = paser.parse_args() print(args) tf.set_random_seed(args.seed) np.random.seed(args.seed) import random random.seed(args.seed) def main(): with open('data/processed/%s/data.info'%args.task) as f: data_info = json.load(f) nbest=None if args.nbest: nbest = [ "data/raw/WSJ92-test-data/1000best.sent", "data/raw/WSJ92-test-data/transcript.txt", "data/raw/WSJ92-test-data/1000best.acscore", "data/raw/WSJ92-test-data/1000best.lmscore" ] task2all = {'pos': 56554, 'ner': 14041, 'chunk': 7436} train_num = task2all[args.task] // args.lab if args.nbest: data = seq.Data(vocab_files=data_info['vocab'], train_list=data_info['train%d' % train_num], valid_list=data_info['valid'], test_list=data_info['test'], ) else: data = seq.Data(vocab_files=data_info['vocab'], train_list=data_info['train%d.part%d'%(train_num,args.unl)], valid_list=data_info['valid'], test_list=data_info['test'], max_len=60 ) data_full = seq.Data(vocab_files=data_info['vocab'], train_list=data_info['train%d'%train_num], valid_list=data_info['valid'], test_list=data_info['test'] ) config = trf_semi.Config(data) config.nbest=args.nbest config.mix_config.std = args.std config.mix_config.c2w_type = 'cnn' config.mix_config.chr_embedding_size = 50 config.mix_config.c2w_cnn_size = 100 config.mix_config.c2w_cnn_width = [2, 3, 4] config.mix_config.rnn_hidden_size = 512 config.mix_config.rnn_hidden_layers = args.hl config.mix_config.embedding_size = 300 config.mix_config.rnn_proj_size = 512 config.mix_config.opt_method = args.opt config.sampler_config.optimize_method =args.opt config.sampler_config.learning_rate = args.lr if args.sgd: config.sampler_config.optimize_method = 'SGD' config.mix_config.dropout = args.do config.mix_config.trf_dropout = args.do config.mix_config.crf_weight = args.cw config.mix_config.trf_weight = args.tw config.crf_batch_size = 64 config.trf_batch_size = args.bs config.data_factor = 1 config.mix_config.inter_alpha = args.alpha if args.word_emb: config.mix_config.embedding_init_npy = data_info['word_emb_d300'] if args.maxstep>0: config.max_steps=args.maxstep elif args.lab==1: config.max_steps= 40000 else: config.max_steps= 20000 if args.nbest: config.eval_every = 1000 else: config.eval_every = 500 config.warm_up_steps=100 config.lr_decay = 0.005 config.lr=args.lr logdir = 'models/%s_trf_semi_lab%dunl%d_%s/' % (args.task, args.lab, args.unl, args.sf) logdir = wb.mklogdir(logdir,is_recreate=True) config.print() m = trf_semi.TRF(config, data, data_full, logdir, device='/gpu:0') if args.model: variables = tf.contrib.slim.get_variables_to_restore() print('----------------------') print(len(variables)) print('----------------------') if 'bilm' in args.model: variables_to_restore = [v for v in variables if 'edge_mat' not in v.name and 'final_linear' not in v.name and 'auxiliary_lstm' not in v.name and 'logz' not in v.name and v.trainable == True] elif 'pretrain' in args.model: variables_to_restore = [v for v in variables if 'edge_mat' not in v.name and 'final_linear' not in v.name and 'auxiliary_lstm' not in v.name and v.trainable == True] else: variables_to_restore = [v for v in variables if 'auxiliary_lstm' not in v.name and 'logz' not in v.name and v.trainable == True] model_path = tf.train.latest_checkpoint('models/' + args.model + '/check_models') print('----------------------') print(len(variables_to_restore)) for v in variables_to_restore: print(v.name) print('----------------------') saver = tf.train.Saver(variables_to_restore) sv = tf.train.Supervisor(logdir=os.path.join(logdir, 'logs')) sv.summary_writer.add_graph(tf.get_default_graph()) # write the graph to logs session_config = tf.ConfigProto(allow_soft_placement=True, log_device_placement=False) # session_config.gpu_options.allow_growth = True with sv.managed_session(config=session_config) as session: with session.as_default(): m.initialize() if args.model: saver.restore(session, model_path) ops = trf_semi.DefaultOps(args, m, data.datas[-2], data.datas[-1], id2tag_name=data_info['id2tag'],nbest_files=nbest) m.train(0.1, ops,args.steps) m.best_saver.restore(session, tf.train.latest_checkpoint(m.best_save_name)) ops = trf_semi.DefaultOps(args, m, data.datas[-2], data.datas[-1], id2tag_name=data_info['id2tag'], test=True,nbest_files=nbest) print('------------begin test-----------') ops.perform(0, 0) if __name__ == '__main__': main()
[ "trf_semi.TRF", "json.load", "numpy.random.seed", "argparse.ArgumentParser", "tensorflow.contrib.slim.get_variables_to_restore", "tensorflow.train.Saver", "trf_semi.DefaultOps", "tensorflow.set_random_seed", "tensorflow.get_default_graph", "tensorflow.ConfigProto", "tensorflow.train.latest_checkpoint", "random.seed", "trf_semi.Config", "os.path.join" ]
[((267, 292), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (290, 292), False, 'import argparse\n'), ((1715, 1744), 'tensorflow.set_random_seed', 'tf.set_random_seed', (['args.seed'], {}), '(args.seed)\n', (1733, 1744), True, 'import tensorflow as tf\n'), ((1745, 1770), 'numpy.random.seed', 'np.random.seed', (['args.seed'], {}), '(args.seed)\n', (1759, 1770), True, 'import numpy as np\n'), ((1785, 1807), 'random.seed', 'random.seed', (['args.seed'], {}), '(args.seed)\n', (1796, 1807), False, 'import random\n'), ((3182, 3203), 'trf_semi.Config', 'trf_semi.Config', (['data'], {}), '(data)\n', (3197, 3203), False, 'import trf_semi\n'), ((4751, 4813), 'trf_semi.TRF', 'trf_semi.TRF', (['config', 'data', 'data_full', 'logdir'], {'device': '"""/gpu:0"""'}), "(config, data, data_full, logdir, device='/gpu:0')\n", (4763, 4813), False, 'import trf_semi\n'), ((6118, 6187), 'tensorflow.ConfigProto', 'tf.ConfigProto', ([], {'allow_soft_placement': '(True)', 'log_device_placement': '(False)'}), '(allow_soft_placement=True, log_device_placement=False)\n', (6132, 6187), True, 'import tensorflow as tf\n'), ((1902, 1914), 'json.load', 'json.load', (['f'], {}), '(f)\n', (1911, 1914), False, 'import json\n'), ((4854, 4896), 'tensorflow.contrib.slim.get_variables_to_restore', 'tf.contrib.slim.get_variables_to_restore', ([], {}), '()\n', (4894, 4896), True, 'import tensorflow as tf\n'), ((5638, 5706), 'tensorflow.train.latest_checkpoint', 'tf.train.latest_checkpoint', (["('models/' + args.model + '/check_models')"], {}), "('models/' + args.model + '/check_models')\n", (5664, 5706), True, 'import tensorflow as tf\n'), ((5910, 5946), 'tensorflow.train.Saver', 'tf.train.Saver', (['variables_to_restore'], {}), '(variables_to_restore)\n', (5924, 5946), True, 'import tensorflow as tf\n'), ((6046, 6068), 'tensorflow.get_default_graph', 'tf.get_default_graph', ([], {}), '()\n', (6066, 6068), True, 'import tensorflow as tf\n'), ((5984, 6012), 'os.path.join', 'os.path.join', (['logdir', '"""logs"""'], {}), "(logdir, 'logs')\n", (5996, 6012), False, 'import os\n'), ((6463, 6580), 'trf_semi.DefaultOps', 'trf_semi.DefaultOps', (['args', 'm', 'data.datas[-2]', 'data.datas[-1]'], {'id2tag_name': "data_info['id2tag']", 'nbest_files': 'nbest'}), "(args, m, data.datas[-2], data.datas[-1], id2tag_name=\n data_info['id2tag'], nbest_files=nbest)\n", (6482, 6580), False, 'import trf_semi\n'), ((6722, 6850), 'trf_semi.DefaultOps', 'trf_semi.DefaultOps', (['args', 'm', 'data.datas[-2]', 'data.datas[-1]'], {'id2tag_name': "data_info['id2tag']", 'test': '(True)', 'nbest_files': 'nbest'}), "(args, m, data.datas[-2], data.datas[-1], id2tag_name=\n data_info['id2tag'], test=True, nbest_files=nbest)\n", (6741, 6850), False, 'import trf_semi\n'), ((6658, 6702), 'tensorflow.train.latest_checkpoint', 'tf.train.latest_checkpoint', (['m.best_save_name'], {}), '(m.best_save_name)\n', (6684, 6702), True, 'import tensorflow as tf\n')]
import json import os import pathlib import pickle import unittest from test.test_api.utils import dummy_do_dummy_prediction, dummy_eval_function import ConfigSpace as CS from ConfigSpace.configuration_space import Configuration import numpy as np import pandas as pd import pytest import sklearn import sklearn.datasets from sklearn.base import BaseEstimator from sklearn.base import clone from sklearn.ensemble import VotingClassifier, VotingRegressor from smac.runhistory.runhistory import RunHistory from autoPyTorch.api.tabular_classification import TabularClassificationTask from autoPyTorch.api.tabular_regression import TabularRegressionTask from autoPyTorch.datasets.resampling_strategy import ( CrossValTypes, HoldoutValTypes, ) from autoPyTorch.optimizer.smbo import AutoMLSMBO from autoPyTorch.pipeline.base_pipeline import BasePipeline from autoPyTorch.pipeline.components.setup.traditional_ml.traditional_learner import _traditional_learners from autoPyTorch.pipeline.components.training.metrics.metrics import accuracy CV_NUM_SPLITS = 2 HOLDOUT_NUM_SPLITS = 1 # Test # ==== @unittest.mock.patch('autoPyTorch.evaluation.train_evaluator.eval_function', new=dummy_eval_function) @pytest.mark.parametrize('openml_id', (40981, )) @pytest.mark.parametrize('resampling_strategy,resampling_strategy_args', ((HoldoutValTypes.holdout_validation, None), (CrossValTypes.k_fold_cross_validation, {'num_splits': CV_NUM_SPLITS}) )) def test_tabular_classification(openml_id, resampling_strategy, backend, resampling_strategy_args, n_samples): # Get the data and check that contents of data-manager make sense X, y = sklearn.datasets.fetch_openml( data_id=int(openml_id), return_X_y=True, as_frame=True ) X, y = X.iloc[:n_samples], y.iloc[:n_samples] X_train, X_test, y_train, y_test = sklearn.model_selection.train_test_split( X, y, random_state=42) # Search for a good configuration estimator = TabularClassificationTask( backend=backend, resampling_strategy=resampling_strategy, resampling_strategy_args=resampling_strategy_args, seed=42, ) with unittest.mock.patch.object(estimator, '_do_dummy_prediction', new=dummy_do_dummy_prediction): estimator.search( X_train=X_train, y_train=y_train, X_test=X_test, y_test=y_test, optimize_metric='accuracy', total_walltime_limit=40, func_eval_time_limit_secs=10, enable_traditional_pipeline=False, ) # Internal dataset has expected settings assert estimator.dataset.task_type == 'tabular_classification' expected_num_splits = HOLDOUT_NUM_SPLITS if resampling_strategy == HoldoutValTypes.holdout_validation \ else CV_NUM_SPLITS assert estimator.resampling_strategy == resampling_strategy assert estimator.dataset.resampling_strategy == resampling_strategy assert len(estimator.dataset.splits) == expected_num_splits # TODO: check for budget # Check for the created files tmp_dir = estimator._backend.temporary_directory loaded_datamanager = estimator._backend.load_datamanager() assert len(loaded_datamanager.train_tensors) == len(estimator.dataset.train_tensors) expected_files = [ 'smac3-output/run_42/configspace.json', 'smac3-output/run_42/runhistory.json', 'smac3-output/run_42/scenario.txt', 'smac3-output/run_42/stats.json', 'smac3-output/run_42/train_insts.txt', 'smac3-output/run_42/trajectory.json', '.autoPyTorch/datamanager.pkl', '.autoPyTorch/ensemble_read_preds.pkl', '.autoPyTorch/start_time_42', '.autoPyTorch/ensemble_history.json', '.autoPyTorch/ensemble_read_losses.pkl', '.autoPyTorch/true_targets_ensemble.npy', ] for expected_file in expected_files: assert os.path.exists(os.path.join(tmp_dir, expected_file)), "{}/{}/{}".format( tmp_dir, [data for data in pathlib.Path(tmp_dir).glob('*')], expected_file, ) # Check that smac was able to find proper models succesful_runs = [run_value.status for run_value in estimator.run_history.data.values( ) if 'SUCCESS' in str(run_value.status)] assert len(succesful_runs) > 1, [(k, v) for k, v in estimator.run_history.data.items()] # Search for an existing run key in disc. A individual model might have # a timeout and hence was not written to disc successful_num_run = None SUCCESS = False for i, (run_key, value) in enumerate(estimator.run_history.data.items()): if 'SUCCESS' in str(value.status): run_key_model_run_dir = estimator._backend.get_numrun_directory( estimator.seed, run_key.config_id + 1, run_key.budget) successful_num_run = run_key.config_id + 1 if os.path.exists(run_key_model_run_dir): # Runkey config id is different from the num_run # more specifically num_run = config_id + 1(dummy) SUCCESS = True break assert SUCCESS, f"Successful run was not properly saved for num_run: {successful_num_run}" if resampling_strategy == HoldoutValTypes.holdout_validation: model_file = os.path.join(run_key_model_run_dir, f"{estimator.seed}.{successful_num_run}.{run_key.budget}.model") assert os.path.exists(model_file), model_file model = estimator._backend.load_model_by_seed_and_id_and_budget( estimator.seed, successful_num_run, run_key.budget) elif resampling_strategy == CrossValTypes.k_fold_cross_validation: model_file = os.path.join( run_key_model_run_dir, f"{estimator.seed}.{successful_num_run}.{run_key.budget}.cv_model" ) assert os.path.exists(model_file), model_file model = estimator._backend.load_cv_model_by_seed_and_id_and_budget( estimator.seed, successful_num_run, run_key.budget) assert isinstance(model, VotingClassifier) assert len(model.estimators_) == CV_NUM_SPLITS else: pytest.fail(resampling_strategy) # Make sure that predictions on the test data are printed and make sense test_prediction = os.path.join(run_key_model_run_dir, estimator._backend.get_prediction_filename( 'test', estimator.seed, successful_num_run, run_key.budget)) assert os.path.exists(test_prediction), test_prediction assert np.shape(np.load(test_prediction, allow_pickle=True))[0] == np.shape(X_test)[0] # Also, for ensemble builder, the OOF predictions should be there and match # the Ground truth that is also physically printed to disk ensemble_prediction = os.path.join(run_key_model_run_dir, estimator._backend.get_prediction_filename( 'ensemble', estimator.seed, successful_num_run, run_key.budget)) assert os.path.exists(ensemble_prediction), ensemble_prediction assert np.shape(np.load(ensemble_prediction, allow_pickle=True))[0] == np.shape( estimator._backend.load_targets_ensemble() )[0] # Ensemble Builder produced an ensemble estimator.ensemble_ is not None # There should be a weight for each element of the ensemble assert len(estimator.ensemble_.identifiers_) == len(estimator.ensemble_.weights_) y_pred = estimator.predict(X_test) assert np.shape(y_pred)[0] == np.shape(X_test)[0] # Make sure that predict proba has the expected shape probabilites = estimator.predict_proba(X_test) assert np.shape(probabilites) == (np.shape(X_test)[0], 2) score = estimator.score(y_pred, y_test) assert 'accuracy' in score # check incumbent config and results incumbent_config, incumbent_results = estimator.get_incumbent_results() assert isinstance(incumbent_config, Configuration) assert isinstance(incumbent_results, dict) assert 'opt_loss' in incumbent_results, "run history: {}, successful_num_run: {}".format(estimator.run_history.data, successful_num_run) assert 'train_loss' in incumbent_results # Check that we can pickle dump_file = os.path.join(estimator._backend.temporary_directory, 'dump.pkl') with open(dump_file, 'wb') as f: pickle.dump(estimator, f) with open(dump_file, 'rb') as f: restored_estimator = pickle.load(f) restored_estimator.predict(X_test) # Test refit on dummy data estimator.refit(dataset=backend.load_datamanager()) # Make sure that a configuration space is stored in the estimator assert isinstance(estimator.get_search_space(), CS.ConfigurationSpace) # test fit on dummy data assert isinstance(estimator.fit(dataset=backend.load_datamanager()), BasePipeline) @pytest.mark.parametrize('openml_name', ("boston", )) @unittest.mock.patch('autoPyTorch.evaluation.train_evaluator.eval_function', new=dummy_eval_function) @pytest.mark.parametrize('resampling_strategy,resampling_strategy_args', ((HoldoutValTypes.holdout_validation, None), (CrossValTypes.k_fold_cross_validation, {'num_splits': CV_NUM_SPLITS}) )) def test_tabular_regression(openml_name, resampling_strategy, backend, resampling_strategy_args, n_samples): # Get the data and check that contents of data-manager make sense X, y = sklearn.datasets.fetch_openml( openml_name, return_X_y=True, as_frame=True ) X, y = X.iloc[:n_samples], y.iloc[:n_samples] # normalize values y = (y - y.mean()) / y.std() # fill NAs for now since they are not yet properly handled for column in X.columns: if X[column].dtype.name == "category": X[column] = pd.Categorical(X[column], categories=list(X[column].cat.categories) + ["missing"]).fillna("missing") else: X[column] = X[column].fillna(0) X_train, X_test, y_train, y_test = sklearn.model_selection.train_test_split( X, y, random_state=1) # Search for a good configuration estimator = TabularRegressionTask( backend=backend, resampling_strategy=resampling_strategy, resampling_strategy_args=resampling_strategy_args, seed=42, ) with unittest.mock.patch.object(estimator, '_do_dummy_prediction', new=dummy_do_dummy_prediction): estimator.search( X_train=X_train, y_train=y_train, X_test=X_test, y_test=y_test, optimize_metric='r2', total_walltime_limit=40, func_eval_time_limit_secs=10, enable_traditional_pipeline=False, ) # Internal dataset has expected settings assert estimator.dataset.task_type == 'tabular_regression' expected_num_splits = HOLDOUT_NUM_SPLITS if resampling_strategy == HoldoutValTypes.holdout_validation\ else CV_NUM_SPLITS assert estimator.resampling_strategy == resampling_strategy assert estimator.dataset.resampling_strategy == resampling_strategy assert len(estimator.dataset.splits) == expected_num_splits # TODO: check for budget # Check for the created files tmp_dir = estimator._backend.temporary_directory loaded_datamanager = estimator._backend.load_datamanager() assert len(loaded_datamanager.train_tensors) == len(estimator.dataset.train_tensors) expected_files = [ 'smac3-output/run_42/configspace.json', 'smac3-output/run_42/runhistory.json', 'smac3-output/run_42/scenario.txt', 'smac3-output/run_42/stats.json', 'smac3-output/run_42/train_insts.txt', 'smac3-output/run_42/trajectory.json', '.autoPyTorch/datamanager.pkl', '.autoPyTorch/ensemble_read_preds.pkl', '.autoPyTorch/start_time_42', '.autoPyTorch/ensemble_history.json', '.autoPyTorch/ensemble_read_losses.pkl', '.autoPyTorch/true_targets_ensemble.npy', ] for expected_file in expected_files: assert os.path.exists(os.path.join(tmp_dir, expected_file)), expected_file # Check that smac was able to find proper models succesful_runs = [run_value.status for run_value in estimator.run_history.data.values( ) if 'SUCCESS' in str(run_value.status)] assert len(succesful_runs) >= 1, [(k, v) for k, v in estimator.run_history.data.items()] # Search for an existing run key in disc. A individual model might have # a timeout and hence was not written to disc successful_num_run = None SUCCESS = False for i, (run_key, value) in enumerate(estimator.run_history.data.items()): if 'SUCCESS' in str(value.status): run_key_model_run_dir = estimator._backend.get_numrun_directory( estimator.seed, run_key.config_id + 1, run_key.budget) successful_num_run = run_key.config_id + 1 if os.path.exists(run_key_model_run_dir): # Runkey config id is different from the num_run # more specifically num_run = config_id + 1(dummy) SUCCESS = True break assert SUCCESS, f"Successful run was not properly saved for num_run: {successful_num_run}" if resampling_strategy == HoldoutValTypes.holdout_validation: model_file = os.path.join(run_key_model_run_dir, f"{estimator.seed}.{successful_num_run}.{run_key.budget}.model") assert os.path.exists(model_file), model_file model = estimator._backend.load_model_by_seed_and_id_and_budget( estimator.seed, successful_num_run, run_key.budget) elif resampling_strategy == CrossValTypes.k_fold_cross_validation: model_file = os.path.join( run_key_model_run_dir, f"{estimator.seed}.{successful_num_run}.{run_key.budget}.cv_model" ) assert os.path.exists(model_file), model_file model = estimator._backend.load_cv_model_by_seed_and_id_and_budget( estimator.seed, successful_num_run, run_key.budget) assert isinstance(model, VotingRegressor) assert len(model.estimators_) == CV_NUM_SPLITS else: pytest.fail(resampling_strategy) # Make sure that predictions on the test data are printed and make sense test_prediction = os.path.join(run_key_model_run_dir, estimator._backend.get_prediction_filename( 'test', estimator.seed, successful_num_run, run_key.budget)) assert os.path.exists(test_prediction), test_prediction assert np.shape(np.load(test_prediction, allow_pickle=True))[0] == np.shape(X_test)[0] # Also, for ensemble builder, the OOF predictions should be there and match # the Ground truth that is also physically printed to disk ensemble_prediction = os.path.join(run_key_model_run_dir, estimator._backend.get_prediction_filename( 'ensemble', estimator.seed, successful_num_run, run_key.budget)) assert os.path.exists(ensemble_prediction), ensemble_prediction assert np.shape(np.load(ensemble_prediction, allow_pickle=True))[0] == np.shape( estimator._backend.load_targets_ensemble() )[0] # Ensemble Builder produced an ensemble estimator.ensemble_ is not None # There should be a weight for each element of the ensemble assert len(estimator.ensemble_.identifiers_) == len(estimator.ensemble_.weights_) y_pred = estimator.predict(X_test) assert np.shape(y_pred)[0] == np.shape(X_test)[0] score = estimator.score(y_pred, y_test) assert 'r2' in score # check incumbent config and results incumbent_config, incumbent_results = estimator.get_incumbent_results() assert isinstance(incumbent_config, Configuration) assert isinstance(incumbent_results, dict) assert 'opt_loss' in incumbent_results, "run history: {}, successful_num_run: {}".format(estimator.run_history.data, successful_num_run) assert 'train_loss' in incumbent_results, estimator.run_history.data # Check that we can pickle dump_file = os.path.join(estimator._backend.temporary_directory, 'dump.pkl') with open(dump_file, 'wb') as f: pickle.dump(estimator, f) with open(dump_file, 'rb') as f: restored_estimator = pickle.load(f) restored_estimator.predict(X_test) # Test refit on dummy data estimator.refit(dataset=backend.load_datamanager()) # Make sure that a configuration space is stored in the estimator assert isinstance(estimator.get_search_space(), CS.ConfigurationSpace) representation = estimator.show_models() assert isinstance(representation, str) assert 'Weight' in representation assert 'Preprocessing' in representation assert 'Estimator' in representation @pytest.mark.parametrize('openml_id', ( 1590, # Adult to test NaN in categorical columns )) def test_tabular_input_support(openml_id, backend): """ Make sure we can process inputs with NaN in categorical and Object columns when the later is possible """ # Get the data and check that contents of data-manager make sense X, y = sklearn.datasets.fetch_openml( data_id=int(openml_id), return_X_y=True, as_frame=True ) # Make sure we are robust against objects X[X.columns[0]] = X[X.columns[0]].astype(object) X_train, X_test, y_train, y_test = sklearn.model_selection.train_test_split( X, y, random_state=1) # Search for a good configuration estimator = TabularClassificationTask( backend=backend, resampling_strategy=HoldoutValTypes.holdout_validation, ensemble_size=0, ) estimator._do_dummy_prediction = unittest.mock.MagicMock() with unittest.mock.patch.object(AutoMLSMBO, 'run_smbo') as AutoMLSMBOMock: AutoMLSMBOMock.return_value = (RunHistory(), {}, 'epochs') estimator.search( X_train=X_train, y_train=y_train, X_test=X_test, y_test=y_test, optimize_metric='accuracy', total_walltime_limit=150, func_eval_time_limit_secs=50, enable_traditional_pipeline=False, load_models=False, ) @pytest.mark.parametrize("fit_dictionary_tabular", ['classification_categorical_only'], indirect=True) def test_do_dummy_prediction(dask_client, fit_dictionary_tabular): backend = fit_dictionary_tabular['backend'] estimator = TabularClassificationTask( backend=backend, resampling_strategy=HoldoutValTypes.holdout_validation, ensemble_size=0, ) # Setup pre-requisites normally set by search() estimator._create_dask_client() estimator._metric = accuracy estimator._logger = estimator._get_logger('test') estimator._memory_limit = 5000 estimator._time_for_task = 60 estimator._disable_file_output = [] estimator._all_supported_metrics = False with pytest.raises(ValueError, match=r".*Dummy prediction failed with run state.*"): with unittest.mock.patch('autoPyTorch.evaluation.train_evaluator.eval_function') as dummy: dummy.side_effect = MemoryError estimator._do_dummy_prediction() estimator._do_dummy_prediction() # Ensure that the dummy predictions are not in the current working # directory, but in the temporary directory. assert not os.path.exists(os.path.join(os.getcwd(), '.autoPyTorch')) assert os.path.exists(os.path.join( backend.temporary_directory, '.autoPyTorch', 'runs', '1_1_50.0', 'predictions_ensemble_1_1_50.0.npy') ) model_path = os.path.join(backend.temporary_directory, '.autoPyTorch', 'runs', '1_1_50.0', '1.1.50.0.model') # Make sure the dummy model complies with scikit learn # get/set params assert os.path.exists(model_path) with open(model_path, 'rb') as model_handler: clone(pickle.load(model_handler)) estimator._close_dask_client() estimator._clean_logger() del estimator @unittest.mock.patch('autoPyTorch.evaluation.train_evaluator.eval_function', new=dummy_eval_function) @pytest.mark.parametrize('openml_id', (40981, )) def test_portfolio_selection(openml_id, backend, n_samples): # Get the data and check that contents of data-manager make sense X, y = sklearn.datasets.fetch_openml( data_id=int(openml_id), return_X_y=True, as_frame=True ) X, y = X.iloc[:n_samples], y.iloc[:n_samples] X_train, X_test, y_train, y_test = sklearn.model_selection.train_test_split( X, y, random_state=1) # Search for a good configuration estimator = TabularClassificationTask( backend=backend, resampling_strategy=HoldoutValTypes.holdout_validation, ) with unittest.mock.patch.object(estimator, '_do_dummy_prediction', new=dummy_do_dummy_prediction): estimator.search( X_train=X_train, y_train=y_train, X_test=X_test, y_test=y_test, optimize_metric='accuracy', total_walltime_limit=30, func_eval_time_limit_secs=5, enable_traditional_pipeline=False, portfolio_selection=os.path.join(os.path.dirname(__file__), "../../autoPyTorch/configs/greedy_portfolio.json") ) successful_config_ids = [run_key.config_id for run_key, run_value in estimator.run_history.data.items( ) if 'SUCCESS' in str(run_value.status)] successful_configs = [estimator.run_history.ids_config[id].get_dictionary() for id in successful_config_ids] portfolio_configs = json.load(open(os.path.join(os.path.dirname(__file__), "../../autoPyTorch/configs/greedy_portfolio.json"))) # check if any configs from greedy portfolio were compatible with australian assert any(successful_config in portfolio_configs for successful_config in successful_configs) @unittest.mock.patch('autoPyTorch.evaluation.train_evaluator.eval_function', new=dummy_eval_function) @pytest.mark.parametrize('openml_id', (40981, )) def test_portfolio_selection_failure(openml_id, backend, n_samples): # Get the data and check that contents of data-manager make sense X, y = sklearn.datasets.fetch_openml( data_id=int(openml_id), return_X_y=True, as_frame=True ) X, y = X.iloc[:n_samples], y.iloc[:n_samples] X_train, X_test, y_train, y_test = sklearn.model_selection.train_test_split( X, y, random_state=1) estimator = TabularClassificationTask( backend=backend, resampling_strategy=HoldoutValTypes.holdout_validation, ) with pytest.raises(FileNotFoundError, match=r"The path: .+? provided for 'portfolio_selection' " r"for the file containing the portfolio configurations " r"does not exist\. Please provide a valid path"): estimator.search( X_train=X_train, y_train=y_train, X_test=X_test, y_test=y_test, optimize_metric='accuracy', total_walltime_limit=30, func_eval_time_limit_secs=5, enable_traditional_pipeline=False, portfolio_selection="random_path_to_test.json" ) # TODO: Make faster when https://github.com/automl/Auto-PyTorch/pull/223 is incorporated @pytest.mark.parametrize("fit_dictionary_tabular", ['classification_categorical_only'], indirect=True) def test_do_traditional_pipeline(fit_dictionary_tabular): backend = fit_dictionary_tabular['backend'] estimator = TabularClassificationTask( backend=backend, resampling_strategy=HoldoutValTypes.holdout_validation, ensemble_size=0, ) # Setup pre-requisites normally set by search() estimator._create_dask_client() estimator._metric = accuracy estimator._logger = estimator._get_logger('test') estimator._memory_limit = 5000 estimator._time_for_task = 60 estimator._disable_file_output = [] estimator._all_supported_metrics = False estimator._do_traditional_prediction(time_left=60, func_eval_time_limit_secs=30) # The models should not be on the current directory assert not os.path.exists(os.path.join(os.getcwd(), '.autoPyTorch')) # Then we should have fitted 5 classifiers # Maybe some of them fail (unlikely, but we do not control external API) # but we want to make this test robust at_least_one_model_checked = False for i in range(2, 7): pred_path = os.path.join( backend.temporary_directory, '.autoPyTorch', 'runs', f"1_{i}_50.0", f"predictions_ensemble_1_{i}_50.0.npy" ) if not os.path.exists(pred_path): continue model_path = os.path.join(backend.temporary_directory, '.autoPyTorch', 'runs', f"1_{i}_50.0", f"1.{i}.50.0.model") # Make sure the dummy model complies with scikit learn # get/set params assert os.path.exists(model_path) with open(model_path, 'rb') as model_handler: model = pickle.load(model_handler) clone(model) assert model.config == list(_traditional_learners.keys())[i - 2] at_least_one_model_checked = True if not at_least_one_model_checked: pytest.fail("Not even one single traditional pipeline was fitted") estimator._close_dask_client() estimator._clean_logger() del estimator @pytest.mark.parametrize("api_type", [TabularClassificationTask, TabularRegressionTask]) def test_unsupported_msg(api_type): api = api_type() with pytest.raises(ValueError, match=r".*is only supported after calling search. Kindly .*"): api.predict(np.ones((10, 10))) @pytest.mark.parametrize("fit_dictionary_tabular", ['classification_categorical_only'], indirect=True) @pytest.mark.parametrize("api_type", [TabularClassificationTask, TabularRegressionTask]) def test_build_pipeline(api_type, fit_dictionary_tabular): api = api_type() pipeline = api.build_pipeline(fit_dictionary_tabular['dataset_properties']) assert isinstance(pipeline, BaseEstimator) assert len(pipeline.steps) > 0
[ "autoPyTorch.api.tabular_classification.TabularClassificationTask", "pickle.dump", "numpy.load", "smac.runhistory.runhistory.RunHistory", "sklearn.model_selection.train_test_split", "numpy.ones", "numpy.shape", "pathlib.Path", "pickle.load", "pytest.mark.parametrize", "sklearn.datasets.fetch_openml", "os.path.join", "sklearn.base.clone", "unittest.mock.patch.object", "unittest.mock.MagicMock", "os.path.dirname", "pytest.fail", "os.path.exists", "pytest.raises", "autoPyTorch.api.tabular_regression.TabularRegressionTask", "unittest.mock.patch", "autoPyTorch.pipeline.components.setup.traditional_ml.traditional_learner._traditional_learners.keys", "os.getcwd" ]
[((1110, 1214), 'unittest.mock.patch', 'unittest.mock.patch', (['"""autoPyTorch.evaluation.train_evaluator.eval_function"""'], {'new': 'dummy_eval_function'}), "('autoPyTorch.evaluation.train_evaluator.eval_function',\n new=dummy_eval_function)\n", (1129, 1214), False, 'import unittest\n'), ((1233, 1279), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""openml_id"""', '(40981,)'], {}), "('openml_id', (40981,))\n", (1256, 1279), False, 'import pytest\n'), ((1282, 1481), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""resampling_strategy,resampling_strategy_args"""', "((HoldoutValTypes.holdout_validation, None), (CrossValTypes.\n k_fold_cross_validation, {'num_splits': CV_NUM_SPLITS}))"], {}), "('resampling_strategy,resampling_strategy_args', ((\n HoldoutValTypes.holdout_validation, None), (CrossValTypes.\n k_fold_cross_validation, {'num_splits': CV_NUM_SPLITS})))\n", (1305, 1481), False, 'import pytest\n'), ((9239, 9290), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""openml_name"""', "('boston',)"], {}), "('openml_name', ('boston',))\n", (9262, 9290), False, 'import pytest\n'), ((9293, 9397), 'unittest.mock.patch', 'unittest.mock.patch', (['"""autoPyTorch.evaluation.train_evaluator.eval_function"""'], {'new': 'dummy_eval_function'}), "('autoPyTorch.evaluation.train_evaluator.eval_function',\n new=dummy_eval_function)\n", (9312, 9397), False, 'import unittest\n'), ((9416, 9615), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""resampling_strategy,resampling_strategy_args"""', "((HoldoutValTypes.holdout_validation, None), (CrossValTypes.\n k_fold_cross_validation, {'num_splits': CV_NUM_SPLITS}))"], {}), "('resampling_strategy,resampling_strategy_args', ((\n HoldoutValTypes.holdout_validation, None), (CrossValTypes.\n k_fold_cross_validation, {'num_splits': CV_NUM_SPLITS})))\n", (9439, 9615), False, 'import pytest\n'), ((17590, 17635), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""openml_id"""', '(1590,)'], {}), "('openml_id', (1590,))\n", (17613, 17635), False, 'import pytest\n'), ((19003, 19109), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""fit_dictionary_tabular"""', "['classification_categorical_only']"], {'indirect': '(True)'}), "('fit_dictionary_tabular', [\n 'classification_categorical_only'], indirect=True)\n", (19026, 19109), False, 'import pytest\n'), ((20890, 20994), 'unittest.mock.patch', 'unittest.mock.patch', (['"""autoPyTorch.evaluation.train_evaluator.eval_function"""'], {'new': 'dummy_eval_function'}), "('autoPyTorch.evaluation.train_evaluator.eval_function',\n new=dummy_eval_function)\n", (20909, 20994), False, 'import unittest\n'), ((21013, 21059), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""openml_id"""', '(40981,)'], {}), "('openml_id', (40981,))\n", (21036, 21059), False, 'import pytest\n'), ((22845, 22949), 'unittest.mock.patch', 'unittest.mock.patch', (['"""autoPyTorch.evaluation.train_evaluator.eval_function"""'], {'new': 'dummy_eval_function'}), "('autoPyTorch.evaluation.train_evaluator.eval_function',\n new=dummy_eval_function)\n", (22864, 22949), False, 'import unittest\n'), ((22968, 23014), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""openml_id"""', '(40981,)'], {}), "('openml_id', (40981,))\n", (22991, 23014), False, 'import pytest\n'), ((24320, 24426), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""fit_dictionary_tabular"""', "['classification_categorical_only']"], {'indirect': '(True)'}), "('fit_dictionary_tabular', [\n 'classification_categorical_only'], indirect=True)\n", (24343, 24426), False, 'import pytest\n'), ((26504, 26595), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""api_type"""', '[TabularClassificationTask, TabularRegressionTask]'], {}), "('api_type', [TabularClassificationTask,\n TabularRegressionTask])\n", (26527, 26595), False, 'import pytest\n'), ((26789, 26895), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""fit_dictionary_tabular"""', "['classification_categorical_only']"], {'indirect': '(True)'}), "('fit_dictionary_tabular', [\n 'classification_categorical_only'], indirect=True)\n", (26812, 26895), False, 'import pytest\n'), ((26892, 26983), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""api_type"""', '[TabularClassificationTask, TabularRegressionTask]'], {}), "('api_type', [TabularClassificationTask,\n TabularRegressionTask])\n", (26915, 26983), False, 'import pytest\n'), ((1941, 2004), 'sklearn.model_selection.train_test_split', 'sklearn.model_selection.train_test_split', (['X', 'y'], {'random_state': '(42)'}), '(X, y, random_state=42)\n', (1981, 2004), False, 'import sklearn\n'), ((2069, 2221), 'autoPyTorch.api.tabular_classification.TabularClassificationTask', 'TabularClassificationTask', ([], {'backend': 'backend', 'resampling_strategy': 'resampling_strategy', 'resampling_strategy_args': 'resampling_strategy_args', 'seed': '(42)'}), '(backend=backend, resampling_strategy=\n resampling_strategy, resampling_strategy_args=resampling_strategy_args,\n seed=42)\n', (2094, 2221), False, 'from autoPyTorch.api.tabular_classification import TabularClassificationTask\n'), ((6670, 6701), 'os.path.exists', 'os.path.exists', (['test_prediction'], {}), '(test_prediction)\n', (6684, 6701), False, 'import os\n'), ((7304, 7339), 'os.path.exists', 'os.path.exists', (['ensemble_prediction'], {}), '(ensemble_prediction)\n', (7318, 7339), False, 'import os\n'), ((8627, 8691), 'os.path.join', 'os.path.join', (['estimator._backend.temporary_directory', '"""dump.pkl"""'], {}), "(estimator._backend.temporary_directory, 'dump.pkl')\n", (8639, 8691), False, 'import os\n'), ((9875, 9949), 'sklearn.datasets.fetch_openml', 'sklearn.datasets.fetch_openml', (['openml_name'], {'return_X_y': '(True)', 'as_frame': '(True)'}), '(openml_name, return_X_y=True, as_frame=True)\n', (9904, 9949), False, 'import sklearn\n'), ((10489, 10551), 'sklearn.model_selection.train_test_split', 'sklearn.model_selection.train_test_split', (['X', 'y'], {'random_state': '(1)'}), '(X, y, random_state=1)\n', (10529, 10551), False, 'import sklearn\n'), ((10616, 10764), 'autoPyTorch.api.tabular_regression.TabularRegressionTask', 'TabularRegressionTask', ([], {'backend': 'backend', 'resampling_strategy': 'resampling_strategy', 'resampling_strategy_args': 'resampling_strategy_args', 'seed': '(42)'}), '(backend=backend, resampling_strategy=\n resampling_strategy, resampling_strategy_args=resampling_strategy_args,\n seed=42)\n', (10637, 10764), False, 'from autoPyTorch.api.tabular_regression import TabularRegressionTask\n'), ((15074, 15105), 'os.path.exists', 'os.path.exists', (['test_prediction'], {}), '(test_prediction)\n', (15088, 15105), False, 'import os\n'), ((15708, 15743), 'os.path.exists', 'os.path.exists', (['ensemble_prediction'], {}), '(ensemble_prediction)\n', (15722, 15743), False, 'import os\n'), ((16882, 16946), 'os.path.join', 'os.path.join', (['estimator._backend.temporary_directory', '"""dump.pkl"""'], {}), "(estimator._backend.temporary_directory, 'dump.pkl')\n", (16894, 16946), False, 'import os\n'), ((18194, 18256), 'sklearn.model_selection.train_test_split', 'sklearn.model_selection.train_test_split', (['X', 'y'], {'random_state': '(1)'}), '(X, y, random_state=1)\n', (18234, 18256), False, 'import sklearn\n'), ((18320, 18440), 'autoPyTorch.api.tabular_classification.TabularClassificationTask', 'TabularClassificationTask', ([], {'backend': 'backend', 'resampling_strategy': 'HoldoutValTypes.holdout_validation', 'ensemble_size': '(0)'}), '(backend=backend, resampling_strategy=\n HoldoutValTypes.holdout_validation, ensemble_size=0)\n', (18345, 18440), False, 'from autoPyTorch.api.tabular_classification import TabularClassificationTask\n'), ((18505, 18530), 'unittest.mock.MagicMock', 'unittest.mock.MagicMock', ([], {}), '()\n', (18528, 18530), False, 'import unittest\n'), ((19236, 19356), 'autoPyTorch.api.tabular_classification.TabularClassificationTask', 'TabularClassificationTask', ([], {'backend': 'backend', 'resampling_strategy': 'HoldoutValTypes.holdout_validation', 'ensemble_size': '(0)'}), '(backend=backend, resampling_strategy=\n HoldoutValTypes.holdout_validation, ensemble_size=0)\n', (19261, 19356), False, 'from autoPyTorch.api.tabular_classification import TabularClassificationTask\n'), ((20405, 20504), 'os.path.join', 'os.path.join', (['backend.temporary_directory', '""".autoPyTorch"""', '"""runs"""', '"""1_1_50.0"""', '"""1.1.50.0.model"""'], {}), "(backend.temporary_directory, '.autoPyTorch', 'runs',\n '1_1_50.0', '1.1.50.0.model')\n", (20417, 20504), False, 'import os\n'), ((20683, 20709), 'os.path.exists', 'os.path.exists', (['model_path'], {}), '(model_path)\n', (20697, 20709), False, 'import os\n'), ((21402, 21464), 'sklearn.model_selection.train_test_split', 'sklearn.model_selection.train_test_split', (['X', 'y'], {'random_state': '(1)'}), '(X, y, random_state=1)\n', (21442, 21464), False, 'import sklearn\n'), ((21529, 21632), 'autoPyTorch.api.tabular_classification.TabularClassificationTask', 'TabularClassificationTask', ([], {'backend': 'backend', 'resampling_strategy': 'HoldoutValTypes.holdout_validation'}), '(backend=backend, resampling_strategy=\n HoldoutValTypes.holdout_validation)\n', (21554, 21632), False, 'from autoPyTorch.api.tabular_classification import TabularClassificationTask\n'), ((23365, 23427), 'sklearn.model_selection.train_test_split', 'sklearn.model_selection.train_test_split', (['X', 'y'], {'random_state': '(1)'}), '(X, y, random_state=1)\n', (23405, 23427), False, 'import sklearn\n'), ((23454, 23557), 'autoPyTorch.api.tabular_classification.TabularClassificationTask', 'TabularClassificationTask', ([], {'backend': 'backend', 'resampling_strategy': 'HoldoutValTypes.holdout_validation'}), '(backend=backend, resampling_strategy=\n HoldoutValTypes.holdout_validation)\n', (23479, 23557), False, 'from autoPyTorch.api.tabular_classification import TabularClassificationTask\n'), ((24544, 24664), 'autoPyTorch.api.tabular_classification.TabularClassificationTask', 'TabularClassificationTask', ([], {'backend': 'backend', 'resampling_strategy': 'HoldoutValTypes.holdout_validation', 'ensemble_size': '(0)'}), '(backend=backend, resampling_strategy=\n HoldoutValTypes.holdout_validation, ensemble_size=0)\n', (24569, 24664), False, 'from autoPyTorch.api.tabular_classification import TabularClassificationTask\n'), ((2262, 2359), 'unittest.mock.patch.object', 'unittest.mock.patch.object', (['estimator', '"""_do_dummy_prediction"""'], {'new': 'dummy_do_dummy_prediction'}), "(estimator, '_do_dummy_prediction', new=\n dummy_do_dummy_prediction)\n", (2288, 2359), False, 'import unittest\n'), ((5397, 5501), 'os.path.join', 'os.path.join', (['run_key_model_run_dir', 'f"""{estimator.seed}.{successful_num_run}.{run_key.budget}.model"""'], {}), "(run_key_model_run_dir,\n f'{estimator.seed}.{successful_num_run}.{run_key.budget}.model')\n", (5409, 5501), False, 'import os\n'), ((5547, 5573), 'os.path.exists', 'os.path.exists', (['model_file'], {}), '(model_file)\n', (5561, 5573), False, 'import os\n'), ((7953, 7975), 'numpy.shape', 'np.shape', (['probabilites'], {}), '(probabilites)\n', (7961, 7975), True, 'import numpy as np\n'), ((8738, 8763), 'pickle.dump', 'pickle.dump', (['estimator', 'f'], {}), '(estimator, f)\n', (8749, 8763), False, 'import pickle\n'), ((8831, 8845), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (8842, 8845), False, 'import pickle\n'), ((10805, 10902), 'unittest.mock.patch.object', 'unittest.mock.patch.object', (['estimator', '"""_do_dummy_prediction"""'], {'new': 'dummy_do_dummy_prediction'}), "(estimator, '_do_dummy_prediction', new=\n dummy_do_dummy_prediction)\n", (10831, 10902), False, 'import unittest\n'), ((13803, 13907), 'os.path.join', 'os.path.join', (['run_key_model_run_dir', 'f"""{estimator.seed}.{successful_num_run}.{run_key.budget}.model"""'], {}), "(run_key_model_run_dir,\n f'{estimator.seed}.{successful_num_run}.{run_key.budget}.model')\n", (13815, 13907), False, 'import os\n'), ((13953, 13979), 'os.path.exists', 'os.path.exists', (['model_file'], {}), '(model_file)\n', (13967, 13979), False, 'import os\n'), ((16993, 17018), 'pickle.dump', 'pickle.dump', (['estimator', 'f'], {}), '(estimator, f)\n', (17004, 17018), False, 'import pickle\n'), ((17086, 17100), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (17097, 17100), False, 'import pickle\n'), ((18541, 18591), 'unittest.mock.patch.object', 'unittest.mock.patch.object', (['AutoMLSMBO', '"""run_smbo"""'], {}), "(AutoMLSMBO, 'run_smbo')\n", (18567, 18591), False, 'import unittest\n'), ((19723, 19800), 'pytest.raises', 'pytest.raises', (['ValueError'], {'match': '""".*Dummy prediction failed with run state.*"""'}), "(ValueError, match='.*Dummy prediction failed with run state.*')\n", (19736, 19800), False, 'import pytest\n'), ((20249, 20367), 'os.path.join', 'os.path.join', (['backend.temporary_directory', '""".autoPyTorch"""', '"""runs"""', '"""1_1_50.0"""', '"""predictions_ensemble_1_1_50.0.npy"""'], {}), "(backend.temporary_directory, '.autoPyTorch', 'runs',\n '1_1_50.0', 'predictions_ensemble_1_1_50.0.npy')\n", (20261, 20367), False, 'import os\n'), ((21661, 21758), 'unittest.mock.patch.object', 'unittest.mock.patch.object', (['estimator', '"""_do_dummy_prediction"""'], {'new': 'dummy_do_dummy_prediction'}), "(estimator, '_do_dummy_prediction', new=\n dummy_do_dummy_prediction)\n", (21687, 21758), False, 'import unittest\n'), ((23585, 23784), 'pytest.raises', 'pytest.raises', (['FileNotFoundError'], {'match': '"""The path: .+? provided for \'portfolio_selection\' for the file containing the portfolio configurations does not exist\\\\. Please provide a valid path"""'}), '(FileNotFoundError, match=\n "The path: .+? provided for \'portfolio_selection\' for the file containing the portfolio configurations does not exist\\\\. Please provide a valid path"\n )\n', (23598, 23784), False, 'import pytest\n'), ((25490, 25614), 'os.path.join', 'os.path.join', (['backend.temporary_directory', '""".autoPyTorch"""', '"""runs"""', 'f"""1_{i}_50.0"""', 'f"""predictions_ensemble_1_{i}_50.0.npy"""'], {}), "(backend.temporary_directory, '.autoPyTorch', 'runs',\n f'1_{i}_50.0', f'predictions_ensemble_1_{i}_50.0.npy')\n", (25502, 25614), False, 'import os\n'), ((25730, 25835), 'os.path.join', 'os.path.join', (['backend.temporary_directory', '""".autoPyTorch"""', '"""runs"""', 'f"""1_{i}_50.0"""', 'f"""1.{i}.50.0.model"""'], {}), "(backend.temporary_directory, '.autoPyTorch', 'runs',\n f'1_{i}_50.0', f'1.{i}.50.0.model')\n", (25742, 25835), False, 'import os\n'), ((26038, 26064), 'os.path.exists', 'os.path.exists', (['model_path'], {}), '(model_path)\n', (26052, 26064), False, 'import os\n'), ((26174, 26186), 'sklearn.base.clone', 'clone', (['model'], {}), '(model)\n', (26179, 26186), False, 'from sklearn.base import clone\n'), ((26349, 26415), 'pytest.fail', 'pytest.fail', (['"""Not even one single traditional pipeline was fitted"""'], {}), "('Not even one single traditional pipeline was fitted')\n", (26360, 26415), False, 'import pytest\n'), ((26658, 26749), 'pytest.raises', 'pytest.raises', (['ValueError'], {'match': '""".*is only supported after calling search. Kindly .*"""'}), "(ValueError, match=\n '.*is only supported after calling search. Kindly .*')\n", (26671, 26749), False, 'import pytest\n'), ((4011, 4047), 'os.path.join', 'os.path.join', (['tmp_dir', 'expected_file'], {}), '(tmp_dir, expected_file)\n', (4023, 4047), False, 'import os\n'), ((4989, 5026), 'os.path.exists', 'os.path.exists', (['run_key_model_run_dir'], {}), '(run_key_model_run_dir)\n', (5003, 5026), False, 'import os\n'), ((5815, 5922), 'os.path.join', 'os.path.join', (['run_key_model_run_dir', 'f"""{estimator.seed}.{successful_num_run}.{run_key.budget}.cv_model"""'], {}), "(run_key_model_run_dir,\n f'{estimator.seed}.{successful_num_run}.{run_key.budget}.cv_model')\n", (5827, 5922), False, 'import os\n'), ((5968, 5994), 'os.path.exists', 'os.path.exists', (['model_file'], {}), '(model_file)\n', (5982, 5994), False, 'import os\n'), ((6272, 6304), 'pytest.fail', 'pytest.fail', (['resampling_strategy'], {}), '(resampling_strategy)\n', (6283, 6304), False, 'import pytest\n'), ((6790, 6806), 'numpy.shape', 'np.shape', (['X_test'], {}), '(X_test)\n', (6798, 6806), True, 'import numpy as np\n'), ((7789, 7805), 'numpy.shape', 'np.shape', (['y_pred'], {}), '(y_pred)\n', (7797, 7805), True, 'import numpy as np\n'), ((7812, 7828), 'numpy.shape', 'np.shape', (['X_test'], {}), '(X_test)\n', (7820, 7828), True, 'import numpy as np\n'), ((12543, 12579), 'os.path.join', 'os.path.join', (['tmp_dir', 'expected_file'], {}), '(tmp_dir, expected_file)\n', (12555, 12579), False, 'import os\n'), ((13395, 13432), 'os.path.exists', 'os.path.exists', (['run_key_model_run_dir'], {}), '(run_key_model_run_dir)\n', (13409, 13432), False, 'import os\n'), ((14221, 14328), 'os.path.join', 'os.path.join', (['run_key_model_run_dir', 'f"""{estimator.seed}.{successful_num_run}.{run_key.budget}.cv_model"""'], {}), "(run_key_model_run_dir,\n f'{estimator.seed}.{successful_num_run}.{run_key.budget}.cv_model')\n", (14233, 14328), False, 'import os\n'), ((14374, 14400), 'os.path.exists', 'os.path.exists', (['model_file'], {}), '(model_file)\n', (14388, 14400), False, 'import os\n'), ((14676, 14708), 'pytest.fail', 'pytest.fail', (['resampling_strategy'], {}), '(resampling_strategy)\n', (14687, 14708), False, 'import pytest\n'), ((15194, 15210), 'numpy.shape', 'np.shape', (['X_test'], {}), '(X_test)\n', (15202, 15210), True, 'import numpy as np\n'), ((16194, 16210), 'numpy.shape', 'np.shape', (['y_pred'], {}), '(y_pred)\n', (16202, 16210), True, 'import numpy as np\n'), ((16217, 16233), 'numpy.shape', 'np.shape', (['X_test'], {}), '(X_test)\n', (16225, 16233), True, 'import numpy as np\n'), ((18650, 18662), 'smac.runhistory.runhistory.RunHistory', 'RunHistory', ([], {}), '()\n', (18660, 18662), False, 'from smac.runhistory.runhistory import RunHistory\n'), ((19816, 19891), 'unittest.mock.patch', 'unittest.mock.patch', (['"""autoPyTorch.evaluation.train_evaluator.eval_function"""'], {}), "('autoPyTorch.evaluation.train_evaluator.eval_function')\n", (19835, 19891), False, 'import unittest\n'), ((20774, 20800), 'pickle.load', 'pickle.load', (['model_handler'], {}), '(model_handler)\n', (20785, 20800), False, 'import pickle\n'), ((25660, 25685), 'os.path.exists', 'os.path.exists', (['pred_path'], {}), '(pred_path)\n', (25674, 25685), False, 'import os\n'), ((26139, 26165), 'pickle.load', 'pickle.load', (['model_handler'], {}), '(model_handler)\n', (26150, 26165), False, 'import pickle\n'), ((26767, 26784), 'numpy.ones', 'np.ones', (['(10, 10)'], {}), '((10, 10))\n', (26774, 26784), True, 'import numpy as np\n'), ((6739, 6782), 'numpy.load', 'np.load', (['test_prediction'], {'allow_pickle': '(True)'}), '(test_prediction, allow_pickle=True)\n', (6746, 6782), True, 'import numpy as np\n'), ((7381, 7428), 'numpy.load', 'np.load', (['ensemble_prediction'], {'allow_pickle': '(True)'}), '(ensemble_prediction, allow_pickle=True)\n', (7388, 7428), True, 'import numpy as np\n'), ((7980, 7996), 'numpy.shape', 'np.shape', (['X_test'], {}), '(X_test)\n', (7988, 7996), True, 'import numpy as np\n'), ((15143, 15186), 'numpy.load', 'np.load', (['test_prediction'], {'allow_pickle': '(True)'}), '(test_prediction, allow_pickle=True)\n', (15150, 15186), True, 'import numpy as np\n'), ((15785, 15832), 'numpy.load', 'np.load', (['ensemble_prediction'], {'allow_pickle': '(True)'}), '(ensemble_prediction, allow_pickle=True)\n', (15792, 15832), True, 'import numpy as np\n'), ((20193, 20204), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (20202, 20204), False, 'import os\n'), ((22530, 22555), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (22545, 22555), False, 'import os\n'), ((25207, 25218), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (25216, 25218), False, 'import os\n'), ((22079, 22104), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (22094, 22104), False, 'import os\n'), ((26223, 26251), 'autoPyTorch.pipeline.components.setup.traditional_ml.traditional_learner._traditional_learners.keys', '_traditional_learners.keys', ([], {}), '()\n', (26249, 26251), False, 'from autoPyTorch.pipeline.components.setup.traditional_ml.traditional_learner import _traditional_learners\n'), ((4120, 4141), 'pathlib.Path', 'pathlib.Path', (['tmp_dir'], {}), '(tmp_dir)\n', (4132, 4141), False, 'import pathlib\n')]
import itertools import numpy import tensorflow from tensorflow.python.keras import backend as K from .base_layer import ComplexLayer class ComplexDense(ComplexLayer): def __init__(self, units, activation=None, use_bias=True, kernel_initializer='complex_glorot', bias_initializer='zeros', multiply_units_by_input_dim=False, **kwargs): super(ComplexDense, self).__init__(**kwargs) self.units = units self.activation = activation self.use_bias = use_bias self.kernel_initializer = kernel_initializer self.bias_initializer = bias_initializer self.multiply_units_by_input_dim = multiply_units_by_input_dim def build(self, input_shape): assert len(input_shape) == 2 input_dim = int(input_shape[-1]) units = self.units if self.multiply_units_by_input_dim: units *= input_dim self.kernel = self.add_complex_weight(name='kernel', shape=(input_dim, units), complex_initializer=self.kernel_initializer, trainable=True, dtype=self.params_dtype) if self.use_bias: self.bias = self.add_complex_weight(name='bias', shape=(units,), complex_initializer=self.bias_initializer, trainable=True, dtype=self.params_dtype) else: self.bias = None self.built = True def call(self, inputs): output = K.dot(inputs, self.kernel) if self.use_bias: output = K.bias_add(output, self.bias, data_format='channels_last') if self.activation is not None: output = self.activation(output) return output class TranslationInvariantComplexDense(ComplexDense): def __init__(self, units, **kwargs): super(TranslationInvariantComplexDense, self).__init__(units, multiply_units_by_input_dim=True, **kwargs) def build(self, input_shape): assert len(input_shape) >= 2 input_dims = tuple([int(s) for s in input_shape[1:]]) self.number_of_visible = numpy.prod(input_dims) self.bare_kernel = self.add_complex_weight(name='kernel', shape=input_dims + (self.units,), complex_initializer=self.kernel_initializer, trainable=True, dtype=self.params_dtype) all_axes = tuple(list(range(len(input_dims)))) kernel_translations = [tensorflow.manip.roll(self.bare_kernel, i, all_axes) for i in itertools.product(*[range(dim_size) for dim_size in input_dims])] self.kernel = tensorflow.reshape(tensorflow.stack(kernel_translations, axis=-1), (self.number_of_visible, -1)) if self.use_bias: self.bare_bias = self.add_complex_weight(name='bias', shape=(self.units,), complex_initializer=self.bias_initializer, trainable=True, dtype=self.params_dtype) self.bias = tensorflow.reshape(tensorflow.stack([self.bare_bias] * self.number_of_visible, axis=-1), (-1,)) else: self.bias = None self.built = True def call(self, inputs): return super().call(tensorflow.reshape(inputs, (-1, self.number_of_visible)))
[ "tensorflow.manip.roll", "tensorflow.python.keras.backend.bias_add", "tensorflow.reshape", "tensorflow.stack", "tensorflow.python.keras.backend.dot", "numpy.prod" ]
[((1768, 1794), 'tensorflow.python.keras.backend.dot', 'K.dot', (['inputs', 'self.kernel'], {}), '(inputs, self.kernel)\n', (1773, 1794), True, 'from tensorflow.python.keras import backend as K\n'), ((2449, 2471), 'numpy.prod', 'numpy.prod', (['input_dims'], {}), '(input_dims)\n', (2459, 2471), False, 'import numpy\n'), ((1842, 1900), 'tensorflow.python.keras.backend.bias_add', 'K.bias_add', (['output', 'self.bias'], {'data_format': '"""channels_last"""'}), "(output, self.bias, data_format='channels_last')\n", (1852, 1900), True, 'from tensorflow.python.keras import backend as K\n'), ((2949, 3001), 'tensorflow.manip.roll', 'tensorflow.manip.roll', (['self.bare_kernel', 'i', 'all_axes'], {}), '(self.bare_kernel, i, all_axes)\n', (2970, 3001), False, 'import tensorflow\n'), ((3149, 3195), 'tensorflow.stack', 'tensorflow.stack', (['kernel_translations'], {'axis': '(-1)'}), '(kernel_translations, axis=-1)\n', (3165, 3195), False, 'import tensorflow\n'), ((3883, 3939), 'tensorflow.reshape', 'tensorflow.reshape', (['inputs', '(-1, self.number_of_visible)'], {}), '(inputs, (-1, self.number_of_visible))\n', (3901, 3939), False, 'import tensorflow\n'), ((3680, 3748), 'tensorflow.stack', 'tensorflow.stack', (['([self.bare_bias] * self.number_of_visible)'], {'axis': '(-1)'}), '([self.bare_bias] * self.number_of_visible, axis=-1)\n', (3696, 3748), False, 'import tensorflow\n')]
import numpy as np import matplotlib.pyplot as plt class ZSpreadModel: def __init__(self, params, b_t, c_t, T, n_step): self.m_params = params self.m_b_t = b_t self.m_c_t = c_t self.m_time_grid = np.linspace(0, T, n_step) def optimal_portfolio(self, z, t): b_t = self.get_b_t(t) c_t = self.get_c_t(t) if b_t is None: raise ValueError('b_t was None.') if c_t is None: raise ValueError('c_t was None.') A = 1.0/(1.0 - self.m_params.m_gamma) * np.matmul( np.linalg.inv(self.m_params.m_sigma_1), (self.m_params.m_mu + np.matmul(np.diag(self.m_params.m_delta.flatten()), z))) B = 1.0/(1.0 - self.m_params.m_gamma) * np.matmul(np.matmul(np.linalg.inv(self.m_params.m_sigma_1), self.m_params.m_sigma_2), 2*np.matmul(c_t, z) + b_t) result = A + B return result def get_b_t(self, t): """ :param t: :return: """ result = None for i, t_p in enumerate(self.m_time_grid): if t_p >= t: result = self.m_b_t[i] return result def get_c_t(self, t): """ :param t: :return: """ result = None for i, t_p in enumerate(self.m_time_grid): if t_p >= t: result = self.m_c_t[i] return result def plot_c_t(self): fig, ax = plt.subplots(figsize=(6, 6)) for i in range(0, self.m_params.m_rho.shape[0]): for j in range(0, self.m_params.m_rho.shape[0]): ax.plot([c_t[i, j] for k, c_t in self.m_c_t.items()]) plt.show() def plot_b_t(self): fig, ax = plt.subplots(figsize=(6, 6)) for i in range(0, self.m_params.m_rho.shape[0]): ax.plot([c_t[i] for k, c_t in self.m_b_t.items()]) plt.show()
[ "matplotlib.pyplot.show", "numpy.linalg.inv", "numpy.matmul", "numpy.linspace", "matplotlib.pyplot.subplots" ]
[((236, 261), 'numpy.linspace', 'np.linspace', (['(0)', 'T', 'n_step'], {}), '(0, T, n_step)\n', (247, 261), True, 'import numpy as np\n'), ((1474, 1502), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {'figsize': '(6, 6)'}), '(figsize=(6, 6))\n', (1486, 1502), True, 'import matplotlib.pyplot as plt\n'), ((1699, 1709), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (1707, 1709), True, 'import matplotlib.pyplot as plt\n'), ((1754, 1782), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {'figsize': '(6, 6)'}), '(figsize=(6, 6))\n', (1766, 1782), True, 'import matplotlib.pyplot as plt\n'), ((1911, 1921), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (1919, 1921), True, 'import matplotlib.pyplot as plt\n'), ((576, 614), 'numpy.linalg.inv', 'np.linalg.inv', (['self.m_params.m_sigma_1'], {}), '(self.m_params.m_sigma_1)\n', (589, 614), True, 'import numpy as np\n'), ((776, 814), 'numpy.linalg.inv', 'np.linalg.inv', (['self.m_params.m_sigma_1'], {}), '(self.m_params.m_sigma_1)\n', (789, 814), True, 'import numpy as np\n'), ((866, 883), 'numpy.matmul', 'np.matmul', (['c_t', 'z'], {}), '(c_t, z)\n', (875, 883), True, 'import numpy as np\n')]
# This code is copied from a github respotry 2020.08.08 8:54 a.m. # This code is copied from a github respotry 2020.08.10 10:00 a.m. # this code is to add logging function and siplify the main file. By Ruibing 2020.08.11.15:11 import argparse import os import random import shutil import time import warnings from config import config, update_config import logging import pprint import numpy as np import _init_paths import callback import metric import create_logger import model_lib import torch import torch.nn as nn import torch.nn.parallel import torch.backends.cudnn as cudnn import torch.distributed as dist import torch.optim import torch.multiprocessing as mp import torch.utils.data import torch.utils.data.distributed import torchvision.transforms as transforms import torchvision.datasets as datasets import torchvision.models as models def parse_args(): parser = argparse.ArgumentParser(description='MOCT image classification network') # general parser.add_argument('--cfg', help='experiment configure file name', required=True, type=str) args, rest = parser.parse_known_args() # update config update_config(args.cfg) return args best_acc1 = 0 def main(): args = parse_args() curr_path = os.path.abspath(os.path.dirname(__file__)) logger, final_output_path = create_logger.create_logger(curr_path, args.cfg, config) print('Using config:') pprint.pprint(config) logger.info('training config:{}\n'.format(pprint.pformat(config))) os.environ["CUDA_VISIBLE_DEVICES"] = config.gpu if config.seed is not None: random.seed(config.seed) torch.manual_seed(config.seed) cudnn.deterministic = True warnings.warn('You have chosen to seed training. ' 'This will turn on the CUDNN deterministic setting, ' 'which can slow down your training considerably! ' 'You may see unexpected behavior when restarting ' 'from checkpoints.') if config.dist_url == "env://" and config.world_size == -1: config.world_size = int(os.environ["WORLD_SIZE"]) config.distributed = config.world_size > 1 or config.multiprocessing_distributed ngpus_per_node = torch.cuda.device_count() if config.multiprocessing_distributed: # Since we have ngpus_per_node processes per node, the total world_size # needs to be adjusted accordingly config.world_size = ngpus_per_node * config.world_size # Use torch.multiprocessing.spawn to launch distributed processes: the # main_worker process function mp.spawn(main_worker, nprocs=ngpus_per_node, args=(ngpus_per_node, config, logger, final_output_path)) else: # Simply call main_worker function main_worker(config.gpu, ngpus_per_node, config, logger, final_output_path) def main_worker(gpu, ngpus_per_node, config, logger, output_pt): global best_acc1 if config.gpu is not None: print("Use GPU: {} for training".format(gpu)) if config.distributed: config.gpu = gpu if config.dist_url == "env://" and config.rank == -1: config.rank = int(os.environ["RANK"]) if config.multiprocessing_distributed: # For multiprocessing distributed training, rank needs to be the # global rank among all the processes config.rank = config.rank * ngpus_per_node + gpu dist.init_process_group(backend=config.dist_backend, init_method=config.dist_url, world_size=config.world_size, rank=config.rank) else: config.gpu = 0 model, input_size = model_lib.initialize_model(config.arch, config.num_cls, use_pretrained=config.pretrained) model = nn.Sequential(model, nn.Sigmoid()) if not torch.cuda.is_available(): print('using CPU, this will be slow') elif config.distributed: # For multiprocessing distributed, DistributedDataParallel constructor # should always set the single device scope, otherwise, # DistributedDataParallel will use all available devices. if config.gpu is not None: torch.cuda.set_device(config.gpu) model.cuda(config.gpu) # When using a single GPU per process and per # DistributedDataParallel, we need to divide the batch size # ourselves based on the total number of GPUs we have config.batch_size = int(config.batch_size / ngpus_per_node) config.workers = int((config.workers + ngpus_per_node - 1) / ngpus_per_node) model = torch.nn.parallel.DistributedDataParallel(model, device_ids=[config.gpu]) else: model.cuda() # DistributedDataParallel will divide and allocate batch_size to all # available GPUs if device_ids are not set model = torch.nn.parallel.DistributedDataParallel(model) elif torch.cuda.device_count() == 1: torch.cuda.set_device(0) model = model.cuda(0) else: # DataParallel will divide and allocate batch_size to all available GPUs if config.arch.startswith('alexnet') or config.arch.startswith('vgg'): model[0].features = torch.nn.DataParallel(model[0].features) model.cuda() else: model = torch.nn.DataParallel(model).cuda() # define loss function (criterion) and optimizer criterion = nn.BCELoss().cuda() optimizer = torch.optim.SGD(model.parameters(), config.lr, momentum=config.momentum, weight_decay=config.weight_decay) # optionally resume from a checkpoint if config.resume: resume_file = os.path.join(output_pt, config.arch + '_' + str(config.resume) + '_epoch' + '.pth.tar') if os.path.isfile(resume_file): print("=> loading checkpoint '{}'".format(resume_file)) logger.info("=> loading checkpoint '{}'".format(resume_file)) if config.gpu is None: checkpoint = torch.load(resume_file) else: # Map model to be loaded to specified single gpu. loc = 'cuda:'+ str(config.gpu) checkpoint = torch.load(resume_file, map_location=loc) config.start_epoch = checkpoint['epoch'] best_acc1 = checkpoint['best_acc1'] model.load_state_dict(checkpoint['state_dict']) optimizer.load_state_dict(checkpoint['optimizer']) print("=> loaded checkpoint '{}' (epoch {})" .format(resume_file, checkpoint['epoch'])) logger.info("=> loaded checkpoint '{}' (epoch {})" .format(resume_file, checkpoint['epoch'])) else: print("=> no checkpoint found at '{}'".format(resume_file)) logger.info("=> no checkpoint found at '{}'".format(resume_file)) cudnn.benchmark = True # Data loading code cur_path = os.path.abspath(os.path.dirname(__file__)) data_root_pt = os.path.join(cur_path, 'data', 'MOCT', 'Data', 'jpeg_imgs') traindir = os.path.join(data_root_pt, 'train') valdir = os.path.join(data_root_pt, 'vis') normalize = transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]) train_dataset = datasets.ImageFolder( traindir, transforms.Compose([ transforms.RandomResizedCrop(224), transforms.RandomHorizontalFlip(), transforms.ToTensor(), normalize, ])) if config.distributed: train_sampler = torch.utils.data.distributed.DistributedSampler(train_dataset) else: train_sampler = None train_loader = torch.utils.data.DataLoader( train_dataset, batch_size=config.batch_size, shuffle=(train_sampler is None), num_workers=config.workers, pin_memory=True, sampler=train_sampler) val_loader = torch.utils.data.DataLoader( datasets.ImageFolder(valdir, transforms.Compose([ transforms.Resize(256), transforms.CenterCrop(224), transforms.ToTensor(), normalize, ])), batch_size=config.batch_size, shuffle=False, num_workers=config.workers, pin_memory=True) if config.evaluate: validate(val_loader, model, criterion, config, logger, output_pt) return lr_scheduler = callback.lr_scheduler(config.lr_epoch, config.lr_inter, config.lr, config.lr_factor, config.warmup, config.warmup_lr, config.warmup_epoch) for epoch in range(config.start_epoch, config.epochs): if config.distributed: train_sampler.set_epoch(epoch) lr_scheduler(optimizer, epoch, logger) # train for one epoch train(train_loader, model, criterion, optimizer, epoch, config, logger, output_pt) # evaluate on validation set acc1 = validate(val_loader, model, criterion, config, logger, output_pt) # remember best acc@1 and save checkpoint is_best = acc1 > best_acc1 best_acc1 = max(acc1, best_acc1) if not config.multiprocessing_distributed or (config.multiprocessing_distributed and config.rank % ngpus_per_node == 0): file_name = os.path.join(output_pt, config.arch + '_' + str(epoch+1) + '_epoch' + '.pth.tar') callback.save_checkpoint({ 'epoch': epoch + 1, 'arch': config.arch, 'state_dict': model.state_dict(), 'best_acc1': best_acc1, 'optimizer': optimizer.state_dict(), }, is_best, filename= file_name) logger.info('Save the model as {:}'.format(config.arch + '_' + str(epoch+1) + '_epoch' + '.pth.tar')) def train(train_loader, model, criterion, optimizer, epoch, config, logger, output_pt): batch_time = callback.AverageMeter('Time=', ':6.3f') data_time = callback.AverageMeter('Data=', ':6.5f') losses = callback.AverageMeter('Loss=', ':.4e') acc = callback.AverageMeter('Acc=', ':1.3f') prec = callback.AverageMeter('Pre=', ':1.3f') rec = callback.AverageMeter('Rec=', ':1.3f') progress = callback.ProgressMeter( len(train_loader), [batch_time, data_time, losses, acc, prec, rec], logger, prefix="Epoch: [{}]".format(epoch)) # define roc and auc variables outputs = np.empty([0,1], dtype = np.float32) targets = np.empty([0,1], dtype = np.float32) # switch to train mode model.train() end = time.time() for i, (images, target) in enumerate(train_loader): # measure data loading time data_time.update(time.time() - end, images.size(0)) target = target.type(torch.FloatTensor) target_ = torch.unsqueeze(target, 1) if config.gpu is not None: gpu_id = int(config.gpu) images = images.cuda(gpu_id, non_blocking=True) if torch.cuda.is_available(): target_ = target_.cuda(gpu_id, non_blocking=True) # compute output output = model(images) loss = criterion(output, target_) # measure accuracy and record loss acc_ = metric.accuracy(output, target_) pre_ = metric.precision(output, target_) rec_ = metric.recall(output, target_) losses.update(loss.item() * images.size(0), images.size(0)) acc.update(acc_[0], acc_[1]) prec.update(pre_[0], pre_[1]) rec.update(rec_[0], rec_[1]) # compute gradient and do SGD step optimizer.zero_grad() loss.backward() optimizer.step() # record results and labels for computing auc and roc outputs = np.concatenate([outputs, output.cpu().detach().numpy()]) targets = np.concatenate([targets, target_.cpu().numpy()]) # measure elapsed time batch_time.update(time.time() - end, images.size(0)) end = time.time() if i % config.print_freq == 0: progress.display(i) F1 = 2 * prec.avg * rec.avg / (prec.avg + rec.avg + 1e-6) fpr, tpr, roc_auc = metric.roc(outputs, targets) print('Final Train-Loss:{losses.avg:.3f} \t Train-Acc:{acc.avg:.3f} \t Train-Prec:{prec.avg:.3f} \t Train-Recall:{rec.avg:.3f} \t Train-F1:{f1:.3f} \t Train-Auc:{auc:.3f}' .format(losses=losses, acc=acc, prec=prec, rec=rec, f1=F1, auc=roc_auc)) logger.info('Final Train-Loss:{losses.avg:.3f} \t Train-Acc:{acc.avg:.3f} \t Train-Prec:{prec.avg:.3f} \t Train-Recall:{rec.avg:.3f} \t Train-F1:{f1:.3f} \t Train-Auc:{auc:.3f}' .format(losses=losses, acc=acc, prec=prec, rec=rec, f1=F1, auc=roc_auc)) def validate(val_loader, model, criterion, config, logger, output_pt): batch_time = callback.AverageMeter('Time=', ':6.3f') data_time = callback.AverageMeter('Data=', ':6.5f') losses = callback.AverageMeter('Loss=', ':.4e') acc = callback.AverageMeter('Acc=', ':1.3f') prec = callback.AverageMeter('Pre=', ':1.3f') rec = callback.AverageMeter('Rec=', ':1.3f') progress = callback.ProgressMeter( len(val_loader), [batch_time, data_time, losses, acc, prec, rec], logger, prefix='Test: ') # define roc and auc variables outputs = np.empty([0,1], dtype = np.float32) targets = np.empty([0,1], dtype = np.float32) # switch to evaluate mode model.eval() with torch.no_grad(): end = time.time() for i, (images, target) in enumerate(val_loader): # measure data loading time data_time.update(time.time() - end, images.size(0)) target = target.type(torch.FloatTensor) target_ = torch.unsqueeze(target, 1) if config.gpu is not None: gpu_id = int(config.gpu) images = images.cuda(gpu_id, non_blocking=True) if torch.cuda.is_available(): target_ = target_.cuda(gpu_id, non_blocking=True) # compute output output = model(images) loss = criterion(output, target_) if config.vis: imshow(images, title=target[0]) # measure accuracy and record loss acc_ = metric.accuracy(output, target_) pre_ = metric.precision(output, target_) rec_ = metric.recall(output, target_) losses.update(loss.item()*images.size(0), images.size(0)) acc.update(acc_[0], acc_[1]) prec.update(pre_[0], pre_[1]) rec.update(rec_[0], rec_[1]) # record results and labels for computing auc and roc outputs = np.concatenate([outputs, output.cpu().numpy()]) targets = np.concatenate([targets, target_.cpu().numpy()]) # measure elapsed time batch_time.update(time.time() - end, images.size(0)) end = time.time() if i % config.print_freq == 0: progress.display(i) F1 = 2* prec.avg * rec.avg/(prec.avg + rec.avg + 1e-6) fpr, tpr, roc_auc = metric.roc(outputs, targets) print('Final Validation-Loss:{losses.avg:.3f} \t Validation-Acc:{acc.avg:.3f} \t Validation-Prec:{prec.avg:.3f} \t Validation-Recall:{rec.avg:.3f} \t Validation-F1:{f1:.3f} \t Validation-Auc:{auc:.3f}' .format(losses=losses, acc=acc, prec=prec, rec=rec, f1= F1, auc=roc_auc)) logger.info('Final Validation-Loss:{losses.avg:.3f} \t Validation-Acc:{acc.avg:.3f} \t Validation-Prec:{prec.avg:.3f} \t Validation-Recall:{rec.avg:.3f} \t Validation-F1:{f1:.3f} \t Validation-Auc:{auc:.3f}' .format(losses=losses, acc=acc, prec=prec, rec=rec, f1= F1, auc=roc_auc)) return acc.avg def imshow(images, title=None): """Imshow for Tensor.""" import numpy as np import matplotlib.pyplot as plt import torchvision inp = torchvision.utils.make_grid(images[0]) inp = inp.cpu().numpy().transpose((1, 2, 0)) mean = np.array([0.485, 0.456, 0.406]) std = np.array([0.229, 0.224, 0.225]) inp = std * inp + mean inp = np.clip(inp, 0, 1) plt.imshow(inp) if title is not None: im_title = 'Probability:{:}'.format(title.cpu().numpy()) plt.gca().text(inp.shape[0]/2-7, 10, im_title,fontsize=12, color='white') plt.show() if __name__ == '__main__': main()
[ "pprint.pformat", "argparse.ArgumentParser", "config.update_config", "numpy.empty", "numpy.clip", "torch.cuda.device_count", "os.path.isfile", "pprint.pprint", "matplotlib.pyplot.gca", "torchvision.transforms.Normalize", "torch.no_grad", "os.path.join", "torch.nn.BCELoss", "torch.utils.data.DataLoader", "model_lib.initialize_model", "matplotlib.pyplot.imshow", "callback.AverageMeter", "os.path.dirname", "metric.roc", "torch.nn.parallel.DistributedDataParallel", "torch.load", "torchvision.transforms.ToTensor", "torch.utils.data.distributed.DistributedSampler", "random.seed", "callback.lr_scheduler", "torch.cuda.set_device", "torchvision.transforms.CenterCrop", "matplotlib.pyplot.show", "torchvision.transforms.RandomHorizontalFlip", "torch.manual_seed", "config.config.arch.startswith", "create_logger.create_logger", "torch.cuda.is_available", "torch.unsqueeze", "metric.recall", "torch.nn.Sigmoid", "torchvision.transforms.Resize", "torch.distributed.init_process_group", "torch.multiprocessing.spawn", "torch.nn.DataParallel", "time.time", "torchvision.utils.make_grid", "metric.precision", "numpy.array", "warnings.warn", "torchvision.transforms.RandomResizedCrop", "metric.accuracy" ]
[((921, 993), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""MOCT image classification network"""'}), "(description='MOCT image classification network')\n", (944, 993), False, 'import argparse\n'), ((1181, 1204), 'config.update_config', 'update_config', (['args.cfg'], {}), '(args.cfg)\n', (1194, 1204), False, 'from config import config, update_config\n'), ((1376, 1432), 'create_logger.create_logger', 'create_logger.create_logger', (['curr_path', 'args.cfg', 'config'], {}), '(curr_path, args.cfg, config)\n', (1403, 1432), False, 'import create_logger\n'), ((1466, 1487), 'pprint.pprint', 'pprint.pprint', (['config'], {}), '(config)\n', (1479, 1487), False, 'import pprint\n'), ((2327, 2352), 'torch.cuda.device_count', 'torch.cuda.device_count', ([], {}), '()\n', (2350, 2352), False, 'import torch\n'), ((3783, 3877), 'model_lib.initialize_model', 'model_lib.initialize_model', (['config.arch', 'config.num_cls'], {'use_pretrained': 'config.pretrained'}), '(config.arch, config.num_cls, use_pretrained=\n config.pretrained)\n', (3809, 3877), False, 'import model_lib\n'), ((7250, 7309), 'os.path.join', 'os.path.join', (['cur_path', '"""data"""', '"""MOCT"""', '"""Data"""', '"""jpeg_imgs"""'], {}), "(cur_path, 'data', 'MOCT', 'Data', 'jpeg_imgs')\n", (7262, 7309), False, 'import os\n'), ((7326, 7361), 'os.path.join', 'os.path.join', (['data_root_pt', '"""train"""'], {}), "(data_root_pt, 'train')\n", (7338, 7361), False, 'import os\n'), ((7376, 7409), 'os.path.join', 'os.path.join', (['data_root_pt', '"""vis"""'], {}), "(data_root_pt, 'vis')\n", (7388, 7409), False, 'import os\n'), ((7427, 7502), 'torchvision.transforms.Normalize', 'transforms.Normalize', ([], {'mean': '[0.485, 0.456, 0.406]', 'std': '[0.229, 0.224, 0.225]'}), '(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])\n', (7447, 7502), True, 'import torchvision.transforms as transforms\n'), ((7985, 8165), 'torch.utils.data.DataLoader', 'torch.utils.data.DataLoader', (['train_dataset'], {'batch_size': 'config.batch_size', 'shuffle': '(train_sampler is None)', 'num_workers': 'config.workers', 'pin_memory': '(True)', 'sampler': 'train_sampler'}), '(train_dataset, batch_size=config.batch_size,\n shuffle=train_sampler is None, num_workers=config.workers, pin_memory=\n True, sampler=train_sampler)\n', (8012, 8165), False, 'import torch\n'), ((8686, 8829), 'callback.lr_scheduler', 'callback.lr_scheduler', (['config.lr_epoch', 'config.lr_inter', 'config.lr', 'config.lr_factor', 'config.warmup', 'config.warmup_lr', 'config.warmup_epoch'], {}), '(config.lr_epoch, config.lr_inter, config.lr, config.\n lr_factor, config.warmup, config.warmup_lr, config.warmup_epoch)\n', (8707, 8829), False, 'import callback\n'), ((10255, 10294), 'callback.AverageMeter', 'callback.AverageMeter', (['"""Time="""', '""":6.3f"""'], {}), "('Time=', ':6.3f')\n", (10276, 10294), False, 'import callback\n'), ((10312, 10351), 'callback.AverageMeter', 'callback.AverageMeter', (['"""Data="""', '""":6.5f"""'], {}), "('Data=', ':6.5f')\n", (10333, 10351), False, 'import callback\n'), ((10366, 10404), 'callback.AverageMeter', 'callback.AverageMeter', (['"""Loss="""', '""":.4e"""'], {}), "('Loss=', ':.4e')\n", (10387, 10404), False, 'import callback\n'), ((10416, 10454), 'callback.AverageMeter', 'callback.AverageMeter', (['"""Acc="""', '""":1.3f"""'], {}), "('Acc=', ':1.3f')\n", (10437, 10454), False, 'import callback\n'), ((10467, 10505), 'callback.AverageMeter', 'callback.AverageMeter', (['"""Pre="""', '""":1.3f"""'], {}), "('Pre=', ':1.3f')\n", (10488, 10505), False, 'import callback\n'), ((10517, 10555), 'callback.AverageMeter', 'callback.AverageMeter', (['"""Rec="""', '""":1.3f"""'], {}), "('Rec=', ':1.3f')\n", (10538, 10555), False, 'import callback\n'), ((10790, 10824), 'numpy.empty', 'np.empty', (['[0, 1]'], {'dtype': 'np.float32'}), '([0, 1], dtype=np.float32)\n', (10798, 10824), True, 'import numpy as np\n'), ((10841, 10875), 'numpy.empty', 'np.empty', (['[0, 1]'], {'dtype': 'np.float32'}), '([0, 1], dtype=np.float32)\n', (10849, 10875), True, 'import numpy as np\n'), ((10939, 10950), 'time.time', 'time.time', ([], {}), '()\n', (10948, 10950), False, 'import time\n'), ((12548, 12576), 'metric.roc', 'metric.roc', (['outputs', 'targets'], {}), '(outputs, targets)\n', (12558, 12576), False, 'import metric\n'), ((13195, 13234), 'callback.AverageMeter', 'callback.AverageMeter', (['"""Time="""', '""":6.3f"""'], {}), "('Time=', ':6.3f')\n", (13216, 13234), False, 'import callback\n'), ((13252, 13291), 'callback.AverageMeter', 'callback.AverageMeter', (['"""Data="""', '""":6.5f"""'], {}), "('Data=', ':6.5f')\n", (13273, 13291), False, 'import callback\n'), ((13306, 13344), 'callback.AverageMeter', 'callback.AverageMeter', (['"""Loss="""', '""":.4e"""'], {}), "('Loss=', ':.4e')\n", (13327, 13344), False, 'import callback\n'), ((13356, 13394), 'callback.AverageMeter', 'callback.AverageMeter', (['"""Acc="""', '""":1.3f"""'], {}), "('Acc=', ':1.3f')\n", (13377, 13394), False, 'import callback\n'), ((13407, 13445), 'callback.AverageMeter', 'callback.AverageMeter', (['"""Pre="""', '""":1.3f"""'], {}), "('Pre=', ':1.3f')\n", (13428, 13445), False, 'import callback\n'), ((13457, 13495), 'callback.AverageMeter', 'callback.AverageMeter', (['"""Rec="""', '""":1.3f"""'], {}), "('Rec=', ':1.3f')\n", (13478, 13495), False, 'import callback\n'), ((13709, 13743), 'numpy.empty', 'np.empty', (['[0, 1]'], {'dtype': 'np.float32'}), '([0, 1], dtype=np.float32)\n', (13717, 13743), True, 'import numpy as np\n'), ((13760, 13794), 'numpy.empty', 'np.empty', (['[0, 1]'], {'dtype': 'np.float32'}), '([0, 1], dtype=np.float32)\n', (13768, 13794), True, 'import numpy as np\n'), ((16381, 16419), 'torchvision.utils.make_grid', 'torchvision.utils.make_grid', (['images[0]'], {}), '(images[0])\n', (16408, 16419), False, 'import torchvision\n'), ((16482, 16513), 'numpy.array', 'np.array', (['[0.485, 0.456, 0.406]'], {}), '([0.485, 0.456, 0.406])\n', (16490, 16513), True, 'import numpy as np\n'), ((16525, 16556), 'numpy.array', 'np.array', (['[0.229, 0.224, 0.225]'], {}), '([0.229, 0.224, 0.225])\n', (16533, 16556), True, 'import numpy as np\n'), ((16596, 16614), 'numpy.clip', 'np.clip', (['inp', '(0)', '(1)'], {}), '(inp, 0, 1)\n', (16603, 16614), True, 'import numpy as np\n'), ((16620, 16635), 'matplotlib.pyplot.imshow', 'plt.imshow', (['inp'], {}), '(inp)\n', (16630, 16635), True, 'import matplotlib.pyplot as plt\n'), ((16843, 16853), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (16851, 16853), True, 'import matplotlib.pyplot as plt\n'), ((1316, 1341), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (1331, 1341), False, 'import os\n'), ((1659, 1683), 'random.seed', 'random.seed', (['config.seed'], {}), '(config.seed)\n', (1670, 1683), False, 'import random\n'), ((1693, 1723), 'torch.manual_seed', 'torch.manual_seed', (['config.seed'], {}), '(config.seed)\n', (1710, 1723), False, 'import torch\n'), ((1769, 1994), 'warnings.warn', 'warnings.warn', (['"""You have chosen to seed training. This will turn on the CUDNN deterministic setting, which can slow down your training considerably! You may see unexpected behavior when restarting from checkpoints."""'], {}), "(\n 'You have chosen to seed training. This will turn on the CUDNN deterministic setting, which can slow down your training considerably! You may see unexpected behavior when restarting from checkpoints.'\n )\n", (1782, 1994), False, 'import warnings\n'), ((2715, 2821), 'torch.multiprocessing.spawn', 'mp.spawn', (['main_worker'], {'nprocs': 'ngpus_per_node', 'args': '(ngpus_per_node, config, logger, final_output_path)'}), '(main_worker, nprocs=ngpus_per_node, args=(ngpus_per_node, config,\n logger, final_output_path))\n', (2723, 2821), True, 'import torch.multiprocessing as mp\n'), ((3558, 3692), 'torch.distributed.init_process_group', 'dist.init_process_group', ([], {'backend': 'config.dist_backend', 'init_method': 'config.dist_url', 'world_size': 'config.world_size', 'rank': 'config.rank'}), '(backend=config.dist_backend, init_method=config.\n dist_url, world_size=config.world_size, rank=config.rank)\n', (3581, 3692), True, 'import torch.distributed as dist\n'), ((3907, 3919), 'torch.nn.Sigmoid', 'nn.Sigmoid', ([], {}), '()\n', (3917, 3919), True, 'import torch.nn as nn\n'), ((3935, 3960), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (3958, 3960), False, 'import torch\n'), ((6002, 6029), 'os.path.isfile', 'os.path.isfile', (['resume_file'], {}), '(resume_file)\n', (6016, 6029), False, 'import os\n'), ((7203, 7228), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (7218, 7228), False, 'import os\n'), ((7859, 7921), 'torch.utils.data.distributed.DistributedSampler', 'torch.utils.data.distributed.DistributedSampler', (['train_dataset'], {}), '(train_dataset)\n', (7906, 7921), False, 'import torch\n'), ((11176, 11202), 'torch.unsqueeze', 'torch.unsqueeze', (['target', '(1)'], {}), '(target, 1)\n', (11191, 11202), False, 'import torch\n'), ((11352, 11377), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (11375, 11377), False, 'import torch\n'), ((11607, 11639), 'metric.accuracy', 'metric.accuracy', (['output', 'target_'], {}), '(output, target_)\n', (11622, 11639), False, 'import metric\n'), ((11656, 11689), 'metric.precision', 'metric.precision', (['output', 'target_'], {}), '(output, target_)\n', (11672, 11689), False, 'import metric\n'), ((11706, 11736), 'metric.recall', 'metric.recall', (['output', 'target_'], {}), '(output, target_)\n', (11719, 11736), False, 'import metric\n'), ((12371, 12382), 'time.time', 'time.time', ([], {}), '()\n', (12380, 12382), False, 'import time\n'), ((13859, 13874), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (13872, 13874), False, 'import torch\n'), ((13891, 13902), 'time.time', 'time.time', ([], {}), '()\n', (13900, 13902), False, 'import time\n'), ((15559, 15587), 'metric.roc', 'metric.roc', (['outputs', 'targets'], {}), '(outputs, targets)\n', (15569, 15587), False, 'import metric\n'), ((1535, 1557), 'pprint.pformat', 'pprint.pformat', (['config'], {}), '(config)\n', (1549, 1557), False, 'import pprint\n'), ((5601, 5613), 'torch.nn.BCELoss', 'nn.BCELoss', ([], {}), '()\n', (5611, 5613), True, 'import torch.nn as nn\n'), ((14148, 14174), 'torch.unsqueeze', 'torch.unsqueeze', (['target', '(1)'], {}), '(target, 1)\n', (14163, 14174), False, 'import torch\n'), ((14340, 14365), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (14363, 14365), False, 'import torch\n'), ((14696, 14728), 'metric.accuracy', 'metric.accuracy', (['output', 'target_'], {}), '(output, target_)\n', (14711, 14728), False, 'import metric\n'), ((14749, 14782), 'metric.precision', 'metric.precision', (['output', 'target_'], {}), '(output, target_)\n', (14765, 14782), False, 'import metric\n'), ((14803, 14833), 'metric.recall', 'metric.recall', (['output', 'target_'], {}), '(output, target_)\n', (14816, 14833), False, 'import metric\n'), ((15369, 15380), 'time.time', 'time.time', ([], {}), '()\n', (15378, 15380), False, 'import time\n'), ((4300, 4333), 'torch.cuda.set_device', 'torch.cuda.set_device', (['config.gpu'], {}), '(config.gpu)\n', (4321, 4333), False, 'import torch\n'), ((4753, 4826), 'torch.nn.parallel.DistributedDataParallel', 'torch.nn.parallel.DistributedDataParallel', (['model'], {'device_ids': '[config.gpu]'}), '(model, device_ids=[config.gpu])\n', (4794, 4826), False, 'import torch\n'), ((5027, 5075), 'torch.nn.parallel.DistributedDataParallel', 'torch.nn.parallel.DistributedDataParallel', (['model'], {}), '(model)\n', (5068, 5075), False, 'import torch\n'), ((5086, 5111), 'torch.cuda.device_count', 'torch.cuda.device_count', ([], {}), '()\n', (5109, 5111), False, 'import torch\n'), ((5127, 5151), 'torch.cuda.set_device', 'torch.cuda.set_device', (['(0)'], {}), '(0)\n', (5148, 5151), False, 'import torch\n'), ((6241, 6264), 'torch.load', 'torch.load', (['resume_file'], {}), '(resume_file)\n', (6251, 6264), False, 'import torch\n'), ((6429, 6470), 'torch.load', 'torch.load', (['resume_file'], {'map_location': 'loc'}), '(resume_file, map_location=loc)\n', (6439, 6470), False, 'import torch\n'), ((7648, 7681), 'torchvision.transforms.RandomResizedCrop', 'transforms.RandomResizedCrop', (['(224)'], {}), '(224)\n', (7676, 7681), True, 'import torchvision.transforms as transforms\n'), ((7696, 7729), 'torchvision.transforms.RandomHorizontalFlip', 'transforms.RandomHorizontalFlip', ([], {}), '()\n', (7727, 7729), True, 'import torchvision.transforms as transforms\n'), ((7744, 7765), 'torchvision.transforms.ToTensor', 'transforms.ToTensor', ([], {}), '()\n', (7763, 7765), True, 'import torchvision.transforms as transforms\n'), ((11071, 11082), 'time.time', 'time.time', ([], {}), '()\n', (11080, 11082), False, 'import time\n'), ((12321, 12332), 'time.time', 'time.time', ([], {}), '()\n', (12330, 12332), False, 'import time\n'), ((16738, 16747), 'matplotlib.pyplot.gca', 'plt.gca', ([], {}), '()\n', (16745, 16747), True, 'import matplotlib.pyplot as plt\n'), ((5288, 5321), 'config.config.arch.startswith', 'config.arch.startswith', (['"""alexnet"""'], {}), "('alexnet')\n", (5310, 5321), False, 'from config import config, update_config\n'), ((5325, 5354), 'config.config.arch.startswith', 'config.arch.startswith', (['"""vgg"""'], {}), "('vgg')\n", (5347, 5354), False, 'from config import config, update_config\n'), ((5389, 5429), 'torch.nn.DataParallel', 'torch.nn.DataParallel', (['model[0].features'], {}), '(model[0].features)\n', (5410, 5429), False, 'import torch\n'), ((8299, 8321), 'torchvision.transforms.Resize', 'transforms.Resize', (['(256)'], {}), '(256)\n', (8316, 8321), True, 'import torchvision.transforms as transforms\n'), ((8336, 8362), 'torchvision.transforms.CenterCrop', 'transforms.CenterCrop', (['(224)'], {}), '(224)\n', (8357, 8362), True, 'import torchvision.transforms as transforms\n'), ((8377, 8398), 'torchvision.transforms.ToTensor', 'transforms.ToTensor', ([], {}), '()\n', (8396, 8398), True, 'import torchvision.transforms as transforms\n'), ((14035, 14046), 'time.time', 'time.time', ([], {}), '()\n', (14044, 14046), False, 'import time\n'), ((15315, 15326), 'time.time', 'time.time', ([], {}), '()\n', (15324, 15326), False, 'import time\n'), ((5492, 5520), 'torch.nn.DataParallel', 'torch.nn.DataParallel', (['model'], {}), '(model)\n', (5513, 5520), False, 'import torch\n')]
"""Functions for making lens-shaped surfaces.""" from dataclasses import dataclass from typing import Sequence, Tuple, Callable import numpy as np from .. import functions from ..types import Sequence2, Sequence3 from ..sdb import * __all__ = ['make_spherical_singlet', 'make_toroidal_singlet', 'make_spherical_singlet_square_array', 'make_circle', 'make_rectangle'] @dataclass class LensShape: max_radius: float make_edge: Callable[[Sequence2[float]], Surface] make_bound: Callable[[Sequence3[float]], Primitive] def make_circle(radius: float) -> LensShape: def make_edge(vertex0): return InfiniteCylinder(radius, vertex0) def make_bound(vertex0, z0, z1): # TODO make FiniteCylinder primitive and use it instead. return Box((radius, radius, (z1 - z0)/2), (vertex0[0], vertex0[1], vertex0[2] + (z1 + z0)/2)) return LensShape(radius, make_edge, make_bound) def make_rectangle(width: float, height: float) -> LensShape: max_radius = (width**2 + height**2)**0.5/2 def make_edge(vertex0): return InfiniteRectangularPrism(width, height, center=vertex0) def make_bound(vertex0, z0, z1): return Box((width/2, height/2, (z1 - z0)/2), (vertex0[0], vertex0[1], vertex0[2] + (z1 + z0)/2)) return LensShape(max_radius, make_edge, make_bound) def make_spherical_singlet(roc0: float, roc1: float, thickness: float, shape: LensShape, vertex0: Sequence3[float]) -> Surface: """Make circular or rectangular spherical singlet with given radii of curvatures and vertex coordinate. Radii of curvatures obey normal optics convention i.e. biconvex is roc0 > 0, roc1 < 0. """ vertex0 = np.asarray(vertex0, float) s0 = SphericalSag(roc0, 1, vertex0) s1 = SphericalSag(roc1, -1, vertex0 + (0, 0, thickness)) s2 = shape.make_edge(vertex0[:2]) z0 = min(functions.calc_sphere_sag(roc0, shape.max_radius), 0) z1 = thickness + max(functions.calc_sphere_sag(roc1, shape.max_radius), 0) bound = shape.make_bound(vertex0, z0, z1) return IntersectionOp((s0, s1, s2), bound) def make_toroidal_singlet(rocs0, rocs1, thickness, radius: float, vertex0:Sequence[float]=(0,0,0), shape:str='circle'): vertex0 = np.asarray(vertex0) s0 = ToroidalSag(rocs0, 1, vertex0) s1 = ToroidalSag(rocs1, -1, vertex0 + (0, 0, thickness)) if shape == 'circle': s2 = InfiniteCylinder(radius, vertex0[:2]) elif shape == 'square': side_length = radius*2**0.5 s2 = InfiniteRectangularPrism(side_length, center=vertex0[:2]) else: raise ValueError(f'Unknown shape {shape}.') return IntersectionOp((s0, s1, s2)) def make_spherical_singlet_square_array(roc0, roc1, thickness, pitch, size, face_center=None): pitch = np.asarray(pitch) assert pitch.shape == (2,) size = np.asarray(size) assert size.shape == (2,) if face_center is None: face_center = 0, 0, 0 face_center = np.asarray(face_center) assert face_center.shape == (3,) s0 = FiniteRectangularArray(pitch, size, SphericalSag(roc0, 1, (0, 0, face_center[2])), center=face_center[:2]) s1 = FiniteRectangularArray(pitch, size, SphericalSag(roc1, -1, (0, 0, face_center[2] + thickness)), center=face_center[:2]) s2 = InfiniteRectangularPrism(*(pitch*size), face_center[:2]) radius = sum(pitch**2)**0.5/2 z0 = min(functions.calc_sphere_sag(roc0, radius), 0) z1 = thickness + max(functions.calc_sphere_sag(roc1, radius), 0) bound = Box((size[0]*pitch[0]/2, size[1]*pitch[1]/2, (z1 - z0)/2), (face_center[0], face_center[1], face_center[2] + (z1 + z0)/2)) return IntersectionOp((s0, s1, s2), bound)
[ "numpy.asarray" ]
[((1665, 1691), 'numpy.asarray', 'np.asarray', (['vertex0', 'float'], {}), '(vertex0, float)\n', (1675, 1691), True, 'import numpy as np\n'), ((2206, 2225), 'numpy.asarray', 'np.asarray', (['vertex0'], {}), '(vertex0)\n', (2216, 2225), True, 'import numpy as np\n'), ((2749, 2766), 'numpy.asarray', 'np.asarray', (['pitch'], {}), '(pitch)\n', (2759, 2766), True, 'import numpy as np\n'), ((2809, 2825), 'numpy.asarray', 'np.asarray', (['size'], {}), '(size)\n', (2819, 2825), True, 'import numpy as np\n'), ((2932, 2955), 'numpy.asarray', 'np.asarray', (['face_center'], {}), '(face_center)\n', (2942, 2955), True, 'import numpy as np\n')]
# %%-- Import import torch import copy import torch.nn as nn import torch.nn.parallel import torch.optim as optim import torch.utils.data as Data from torch.autograd import Variable import numpy as np import pandas as pd pd.options.mode.chained_assignment = None # default='warn' import time import datetime import gc from torchvision import datasets, models, transforms from sklearn.model_selection import train_test_split from sklearn.metrics import confusion_matrix from sklearn import metrics from sklearn import preprocessing from pandas.plotting import scatter_matrix import scipy import seaborn as sns import matplotlib.pyplot as plt import matplotlib as mpl import matplotlib.font_manager as fm from matplotlib.collections import QuadMesh from scipy import interp from LumiGAN.logger import Logger from LumiGAN.dataset import Dataset from .matplotlibstyle import * # %%- class Ptcompute(): #---- Class constants def __init__(self,datahandler,model,name : str,save : bool): ' Initialize attributes and trace files. Default values are saved here' #-------- Check if we're using PyTorch if not "torch"in str(model.__class__.__bases__): raise ValueError('Passed model not in Torch module') #-------- Check for GPU self.device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") self.isGPU = torch.cuda.is_available() torch.backends.cudnn.benchmark = True #-------- Define files to save timestamp = datetime.datetime.now().strftime("%Y-%m-%d_%H-%M") tracefile = datahandler.pathDic['traces']+timestamp+"_"+"_trace_"+name+".txt" logger = Logger(tracefile) #-------- Attributes and default values self.name = name self.timestamp = timestamp self.dh = datahandler self.save = save self.tracefile = tracefile self.split_size = 0.1 self.logger = logger self.model = model self.trainNum = 0 self.subset_size = None self.batch_size = None self.n_epochs = 25 self.optimizer = None self.loss = None self.learning_rate = 0.0001 self.scaler = None self.CM_fz = 13 def initTraining(self): 'Record Hyper parameter on console and log file' if self.save: self.logger.open() #-------- Print name print(">"*80) print(" "*np.max([0,np.int((80-len(self.name))/2)])+self.name) print("<"*80) print("\n") #-------- Print attributes title = "ATTRIBUTES" print("="*np.max([0,np.int((40-len(title))/2)+(40-len(title))%2])+" "+title+" "+"="*np.max([0,np.int((40-len(title))/2)])) attr = self.__dict__ attr['Working directory']=self.dh.pathDic['workdir'] for k in attr: if k == "model" : continue if k == "logger" : continue if k == "trainNum" : continue if k == 'dh': continue if k == 'optimizer': continue if k == 'loss': continue if k == 'learning_rate': continue if k == 'n_epochs': continue if k == 'batch_size': continue if k == 'subset_size': continue if k == 'split_size': continue if k == 'scaler': continue print("\t",k,"-"*(1+len(max(attr,key=len))-len(k)),">",attr[k]) print("\n") self.regResults = [] self.classResults = [] #-------- Print model title = "MODEL" print("="*np.max([0,np.int((40-len(title))/2)+(40-len(title))%2])+" "+title+" "+"="*np.max([0,np.int((40-len(title))/2)])) print(self.model) print("\n") if self.save: self.logger.close() def trainModel(self,Ycol,transform,transformTrain=None,randomSeed=None,split_randomSeed=None,comment=""): 'Main functions that trains the model - MODEL WILL REMEMBER PREVIOUS TRAINING' self.trainNum+=1 if not randomSeed : randomSeed = np.random.randint(1000) if not split_randomSeed : split_randomSeed = np.random.randint(1000) torch.manual_seed(randomSeed) self.comment = comment if self.save: self.logger.open() title = "TRAINING #"+str(self.trainNum) print(">"*60) print(" "*np.max([0,np.int((60-len(title))/2)])+title) print("<"*60) print("\n") #-------- Prediction type and normalization if needed self.nb_classes=len(self.dh.matchDf[Ycol].value_counts()) self.predictType = "Classification" isReg = False if self.nb_classes > 100 : # Maximum number of class instances is 100 before switching to regression self.predictType = "Regression" isReg = True if isReg and not self.scaler: self.scaler = preprocessing.MinMaxScaler() if isReg: self.scaler.fit(self.dh.matchDf[Ycol].values.reshape(-1,1)) #-------- Train and Test set splitting df = self.dh.matchDf.copy(deep=True) if self.subset_size: df = df.sample(self.subset_size, random_state = randomSeed) if isReg: df[Ycol] = self.scaler.transform(df[Ycol].values.reshape(-1,1)) df_train, df_test = train_test_split(df,test_size = self.split_size,random_state=split_randomSeed) partition = {'train': np.array(df_train['path']), 'test': np.array(df_test['path']) } labels = {} for label, path in zip(df[Ycol],df['path']): labels[path]=label if not transformTrain : transformTrain=transform Train_set = Dataset(partition['train'], labels, transformTrain) Test_set = Dataset(partition['test'], labels, transform) #-------- Other intiailizations if not self.optimizer : self.optimizer = optim.Adam(self.model.parameters(),lr=self.learning_rate) if not self.loss: self.loss = nn.MSELoss() if isReg else nn.CrossEntropyLoss() if not self.batch_size: self.batch_size= np.min(np.max(len(df)/100,1),50) # Default batch size between 1 and 50 as 1% of dataset #-------- Prep saving files self.figurefile = self.dh.pathDic['figures']+self.timestamp+"_"+self.name+"_"+str(self.trainNum)+"_"+comment+".png" self.predictfile = self.dh.pathDic['outputs']+self.timestamp+"_"+self.name+"_"+str(self.trainNum)+"_"+comment+".csv" self.modelfile = self.dh.pathDic['models']+self.timestamp+"_"+self.name+"_"+str(self.trainNum)+"_"+comment+".sav" #-------- Log Data information title = "HYPERPARAMETERS" print("="*np.max([0,np.int((40-len(title))/2)+(40-len(title))%2])+" "+title+" "+"="*np.max([0,np.int((40-len(title))/2)])) toprint = { "Training ID" : self.trainNum, "Random seed":randomSeed, "Split random seed":split_randomSeed, "Model file" : self.modelfile, "Figure file" : self.figurefile, "Predicted file" : self.predictfile, "Datafile" : self.dh.pathDic['Matchfile'], "Dataset length" : len(self.dh.matchDf), "Subset requested" : self.subset_size, "Training set length" : len(df_train), "Testing set length" : len(df_test), "Test/train size ratio" : self.split_size, "Predicted column" : Ycol, "Prediction type" : self.predictType, "Number of unique instances" : self.nb_classes, "Batch size" : self.batch_size, "Learning rate" : self.learning_rate, "Number of epochs" : self.n_epochs, "Loss function" : self.loss, "Optimizer" : self.optimizer, "Training set transformation" : transformTrain, "Testing set transformation" : transform, "Scaler": self.scaler, } for k in toprint: print("\t",k,"-"*(1+len(max(toprint,key=len))-len(k)),">",toprint[k]) print("\n") #-------- Training loop title = "TRAINING" print("="*np.max([0,np.int((40-len(title))/2)+(40-len(title))%2])+" "+title+" "+"="*np.max([0,np.int((40-len(title))/2)])) if self.isGPU: self.model.cuda() for i in range(1): # Get training data train_loader = Data.DataLoader(Train_set, batch_size=self.batch_size,shuffle=True,num_workers=4,drop_last=True,) test_loader = Data.DataLoader(Test_set,batch_size=self.batch_size,shuffle=False,num_workers=4) n_batches = len(train_loader) # Time for printing training_start_time = time.time() tab_train_loss = [] tab_test_loss = [] # Loop for n_epochs self.model.train() for epoch in range(self.n_epochs): running_loss = 0.0 print_every = n_batches // 10 if n_batches//10>1 else 1 start_time = time.time() start_epoch_time = time.time() tab_epoch_train_loss = [] print(" ----Epoch {}----".format(epoch+1)) for i, data in enumerate(train_loader, 0): # Get inputs inputs, targets = data if self.isGPU: inputs, targets = inputs.cuda(), targets.cuda() # Set the parameter gradients to zero self.optimizer.zero_grad() # Forward pass, backward pass, optimize outputs = self.model(inputs) loss_size = self.loss(outputs, targets.float()) if isReg else self.loss(outputs, targets) loss_size.backward() self.optimizer.step() # Print statistics running_loss += loss_size.item() if self.isGPU: tab_epoch_train_loss.append(loss_size.cpu().detach().numpy()) else: tab_epoch_train_loss.append(loss_size.detach().numpy()) #Print every 10th batch of an epoch if (i + 1) % (print_every + 1) == 0: print("\t {:d}% \t train loss: {:.2e} took {:.1f}s".format(int(100 * (i+1) / n_batches), running_loss / print_every, time.time() - start_time)) #Reset running loss and time running_loss = 0.0 start_time = time.time() # Clear GPU mempry if self.isGPU: inputs, targets, outputs, loss_size = inputs.cpu(), targets.cpu(), outputs.cpu(), loss_size.cpu() del inputs, targets, data, outputs, loss_size torch.cuda.empty_cache() tab_train_loss.append(tab_epoch_train_loss) # At the end of the epoch, do a pass on the test set self.model.eval() total_test_loss = 0 for i, data in enumerate(test_loader, 0): # Get inputs inputs, targets = data if self.isGPU: inputs, targets = inputs.cuda(), targets.cuda() # Forward pass outputs = self.model(inputs) loss_size = self.loss(outputs, targets.float()) if isReg else self.loss(outputs, targets) if self.isGPU: total_test_loss += loss_size.cpu().detach().numpy() else: total_test_loss += loss_size.detach().numpy() tab_test_loss.append(1/len(test_loader)*total_test_loss) print("\t Done \t test loss : {0:.2e} took {1:.1f}s".format(total_test_loss / len(test_loader),time.time()-start_epoch_time)) self.model.train() if self.isGPU: inputs, targets, outputs, loss_size = inputs.cpu(), targets.cpu(), outputs.cpu(), loss_size.cpu() del inputs, targets, outputs, loss_size torch.cuda.empty_cache() print("\n") print("\n") #-------- Results title = "RESULTS" print("="*np.max([0,np.int((40-len(title))/2)+(40-len(title))%2])+" "+title+" "+"="*np.max([0,np.int((40-len(title))/2)])) totalTrainTime = time.time()-training_start_time self.model.eval() # Calculate predcited vs actual values for plot tab_Actual=[] tab_Pred=[] if not isReg : tab_Prob=dict() for label in sorted(self.dh.matchDf['Bins'].unique()): tab_Prob[label]=[] test_loader = Data.DataLoader(Test_set,batch_size=1,shuffle=False,num_workers=0) for inputs, targets in test_loader: if self.isGPU: inputs, targets = inputs.cuda(), targets.cuda() #Forward pass outputs = self.model(inputs) if self.isGPU: targets = targets.cpu().detach().numpy()[0] else: targets = targets.detach().numpy()[0] tab_Actual.append(targets) if isReg: if self.isGPU: outputs = outputs.cpu().detach().numpy().tolist()[0][0] else: outputs = outputs.detach().numpy().tolist()[0][0] tab_Pred.append(outputs) else: prediction = nn.Softmax(dim=1)(outputs) if self.isGPU: prediction = prediction.cpu().detach().numpy()[0] else: prediction = prediction.detach().numpy()[0] tab_Pred.append(np.argmax(prediction)) for i,label in zip(range(self.nb_classes),sorted(self.dh.matchDf['Bins'].unique())): tab_Prob[label].append(prediction[i]) if self.isGPU: inputs=inputs.cpu() del inputs, targets, outputs torch.cuda.empty_cache() # Report results if isReg: tab_Actual = self.scaler.inverse_transform(np.array(tab_Actual).reshape(1,-1)).tolist()[0] tab_Pred = self.scaler.inverse_transform(np.array(tab_Pred).reshape(1,-1)).tolist()[0] slope,intercept,Rsq,_ ,_ = scipy.stats.linregress(tab_Actual, tab_Pred) results = { "Reference":self.timestamp+"_"+self.name+"_"+str(self.trainNum)+"_"+comment, "Training ID": str(self.trainNum), "Total training time (s)": "{:.2f}".format(totalTrainTime), "Average training time per epoch (s)": "{:.2f}".format(totalTrainTime/self.n_epochs), "Final training score": "{:.2e}".format(np.mean(tab_train_loss[-1])), "Best training score": "{:.2e}".format(np.min([np.mean(avg) for avg in tab_train_loss])), "Final testing score": "{:.2e}".format(tab_test_loss[-1]), "Best testing score": "{:.2e}".format(np.min(tab_test_loss)), "True vs predicted slope":"{:.2e}".format(slope), "True vs predicted intercept":"{:.2e}".format(intercept), "True vs predicted Rsquare":"{:.3f}".format(Rsq), } for k in results: print("\t",k,"-"*(1+len(max(results,key=len))-len(k)),">",results[k]) self.regResults.append(results) print("\n") else: results = { "Reference":self.timestamp+"_"+self.name+"_"+str(self.trainNum)+"_"+comment, "Training ID": str(self.trainNum), "Total training time (s)": "{:.2f}".format(totalTrainTime), "Average training time per epoch": "{:.2f} s".format(totalTrainTime/self.n_epochs), "Final training score": "{:.2e}".format(np.mean(tab_train_loss[-1])), "Best training score": "{:.2e}".format(np.min([np.mean(avg) for avg in tab_train_loss])), "Final testing score": "{:.2e}".format(tab_test_loss[-1]), "Best testing score": "{:.2e}".format(np.min(tab_test_loss)), "Weighted Accuracy": "{:.3f}".format(metrics.accuracy_score(tab_Actual,tab_Pred)), "Weighted F1-score": "{:.3f}".format(metrics.f1_score(tab_Actual,tab_Pred,average='weighted')), "Weighted Precision": "{:.3f}".format(metrics.precision_score(tab_Actual,tab_Pred,average='weighted')), "Weighted Recall": "{:.3f}".format(metrics.recall_score(tab_Actual,tab_Pred,average='weighted')), } # Compute score per label for i,s in zip(range(self.nb_classes),metrics.recall_score(tab_Actual,tab_Pred,average=None)): results["Recall - class "+str(i)]="{:.3f}".format(s) for i,s in zip(range(self.nb_classes),metrics.precision_score(tab_Actual,tab_Pred,average=None)): results["Precision - class "+str(i)]="{:.3f}".format(s) for i,s in zip(range(self.nb_classes),metrics.f1_score(tab_Actual,tab_Pred,average=None)): results["F1-score - class "+str(i)]="{:.3f}".format(s) # Compute ROC curves fpr = dict() tpr = dict() roc_auc = dict() for i,label in zip(range(self.nb_classes),sorted(self.dh.matchDf['Bins'].unique())): fpr[i], tpr[i], _ = metrics.roc_curve(tab_Actual, tab_Prob[label],pos_label=i) roc_auc[i] = metrics.auc(fpr[i], tpr[i]) results["AUC - class "+str(i)] = "{:.3f}".format(roc_auc[i]) # First aggregate all false positive rates all_fpr = np.unique(np.concatenate([fpr[i] for i in range(self.nb_classes)])) # Then interpolate all ROC curves at this points mean_tpr = np.zeros_like(all_fpr) for i in range(self.nb_classes): mean_tpr += scipy.interp(all_fpr, fpr[i], tpr[i]) # Finally average it and compute AUC mean_tpr /= self.nb_classes fpr["macro"] = all_fpr tpr["macro"] = mean_tpr roc_auc["macro"] = metrics.auc(fpr["macro"], tpr["macro"]) results["Macro AUC"] = "{:.3f}".format(roc_auc["macro"]) for k in results: print("\t",k,"-"*(1+len(max(results,key=len))-len(k)),">",results[k]) self.classResults.append(results) print("\n") title = "LABELS CLASS ID" print("="*np.max([0,np.int((40-len(title))/2)+(40-len(title))%2])+" "+title+" "+"="*np.max([0,np.int((40-len(title))/2)])) toprint={} for i,label in zip(range(self.nb_classes),sorted(self.dh.matchDf['Bins'].unique())): toprint[str(i)]=label self.vocab=toprint for k in toprint: print("\t",k,"-"*(1+len(max(toprint,key=len))-len(k)),">",toprint[k]) print("\n") title = "CLASSIFICATION REPORT" print("="*np.max([0,np.int((40-len(title))/2)+(40-len(title))%2])+" "+title+" "+"="*np.max([0,np.int((40-len(title))/2)])) print(metrics.classification_report(tab_Actual,tab_Pred, digits=3)) print("\n") # Graphs for i in range(1): plt.figure(figsize = (10,10)) gs = mpl.gridspec.GridSpec(2, 2) tab_epoch = range(1,self.n_epochs+1,1) ax1 = plt.subplot(gs[0,:]) if isReg else plt.subplot(gs[0,:-1]) ax1.set_ylabel('Loss (a.u)', fontsize=14) ax1.set_xlabel('Epoch ', fontsize=14) ax1.set_title('Learning curves', fontsize=16) train_avg_loss=[] for x,y in zip(tab_epoch,tab_train_loss): #ax1.scatter([x]*len(y),y,c="C1",marker=".") train_avg_loss.append(np.mean(y)) ax1.plot(tab_epoch,train_avg_loss,'.-',c="C1",label='Training loss') ax1.plot(tab_epoch,tab_test_loss,'.-',c="C4",label='Testing loss') ax1.legend() if isReg: ax2 = plt.subplot(gs[1,:]) ax2.set_xlabel('True value', fontsize=14) ax2.set_ylabel('Predicted value', fontsize=14) ax2.plot([min([min(tab_Actual),min(tab_Pred)]),max([max(tab_Actual),max(tab_Pred)])],[min([min(tab_Actual),min(tab_Pred)]),max([max(tab_Actual),max(tab_Pred)])],linestyle="--",c="C3") ax2.scatter(tab_Actual, tab_Pred, c="C0", marker=".") else: ax2 = plt.subplot(gs[1,:]) ax2.set_xlabel('Specificity', fontsize=14) ax2.set_ylabel('Sensitivity', fontsize=14) ax2.set_title('ROC curves', fontsize=16) ax2.plot(fpr["macro"],tpr["macro"],label="Macro-average (auc={0:0.3f})".format(roc_auc["macro"])) for i,label in zip(range(self.nb_classes),sorted(self.dh.matchDf['Bins'].unique())): plt.plot(fpr[i],tpr[i],linestyle=':',label="{0} (auc={1:0.3f})".format(label,roc_auc[i])) ax2.plot([0, 1], [0, 1], 'k--') ax2.legend(fontsize=self.CM_fz) ax3 = plt.subplot(gs[0,-1]) CM_labels = sorted(self.dh.matchDf['Bins'].unique()) CM_data = metrics.confusion_matrix(tab_Actual,tab_Pred) try: df_CM =pd.DataFrame(CM_data,index=CM_labels[:len(CM_data)], columns=CM_labels[:len(CM_data)]).transpose() except: df_CM =pd.DataFrame(CM_data).transpose() self.CM=df_CM for i in range(1): sum_CM = np.array( df_CM.to_records(index=False).tolist()).sum() max_CM = np.array( df_CM.to_records(index=False).tolist()).max() self.df_CM =df_CM sns.heatmap( df_CM, annot=True, ax=ax3, cbar=False, fmt="d", square=True, linewidths=.5, linecolor='w', annot_kws={"size": self.CM_fz} ) ax3.set_xticklabels(ax3.get_xticklabels(), rotation = 45, fontsize = 10) ax3.set_yticklabels(ax3.get_yticklabels(), rotation = 25, fontsize = 10) for t in ax3.xaxis.get_major_ticks(): t.tick1On = False t.tick2On = False for t in ax3.yaxis.get_major_ticks(): t.tick1On = False t.tick2On = False for i in range(1): #face colors list quadmesh = ax3.findobj(QuadMesh)[0] facecolors = quadmesh.get_facecolors() #iter in text elements array_df = np.array( df_CM.to_records(index=False).tolist()) text_add_glob = []; text_del_glob = []; posi = -1 #from left to right, bottom to top. fz=self.CM_fz # fontsize of text for oText in ax3.collections[0].axes.texts: #ax.texts: pos = np.array( oText.get_position()) - [0.5,0.5] lin = int(pos[1]); col = int(pos[0]); posi += 1 #set text text_add = []; text_del = []; cell_val = array_df[lin][col] tot_all = array_df[-1][-1] per = (float(cell_val) / tot_all) * 100 curr_column = array_df[:,col] ccl = len(curr_column) if(per > 0): txt = '%s\n%.2f%%' %(cell_val, per) else: txt = '' oText.set_text(txt) #main diagonal if(col == lin): #set color of the textin the diagonal to white oText.set_color('k') # set background color in the diagonal to blue facecolors[posi] = np.append(np.array(plt.cm.datad['Greens'][np.minimum(5,int(10*cell_val/max_CM))]),1) else: oText.set_color('k') facecolors[posi] = np.append(np.array(plt.cm.datad['Reds'][np.minimum(5,int(10*cell_val/max_CM))]),1) text_add_glob .extend(text_add) text_del_glob .extend(text_del) #remove the old ones for item in text_del_glob: item.remove() #append the new ones for item in text_add_glob: ax3.text(item['x'], item['y'], item['text'], **item['kw']) ax3.set_xlabel('True labels', fontsize=14) ax3.set_ylabel('Predicted labels', fontsize=14) ax3.set_title('Confusion matrix', fontsize=16) plt.suptitle(self.timestamp+"_"+self.name+"_"+str(self.trainNum)+"_"+comment, fontsize=18) plt.tight_layout(rect=[0,0, 1, 0.93]) if self.save: plt.savefig(self.figurefile,transparent=True,bbox_inches='tight') plt.show() plt.close() self.lossPlots=pd.DataFrame({'epoch':tab_epoch,'train_loss':train_avg_loss,'test_loss':tab_test_loss}) #-------- Save model if self.save: self.logger.close() # Save self.model if self.isGPU: self.model=self.model.cpu() torch.cuda.empty_cache() if self.save: torch.save(self.model.state_dict(),self.modelfile) #-------- Save predict file df_test['True'] = tab_Actual df_test["Predicted"] = tab_Pred if self.save: df_test.to_csv(self.predictfile, index = None, header=True) def selectCNN(key,nClass,preTrain=True,reqGrad=True): # Adjust models connected layer to nClass if "ResNet" in key: model = models.resnet18(pretrained=preTrain) for param in model.parameters(): param.requires_grad = reqGrad num_ftrs = model.fc.in_features model.fc = nn.Sequential( nn.Linear(num_ftrs, int(num_ftrs/2)), nn.BatchNorm1d(int(num_ftrs/2)), nn.ReLU(), nn.Dropout(p=0.2, inplace=False), nn.Linear( int(num_ftrs/2),nClass) ) model.fc.in_features = num_ftrs elif "AlexNet" in key: model = models.alexnet(pretrained=preTrain) for param in model.parameters(): param.requires_grad = reqGrad num_ftrs = model.classifier[6].in_features model.classifier[6] = nn.Sequential( nn.Linear(num_ftrs, int(num_ftrs/2)), nn.BatchNorm1d(int(num_ftrs/2)), nn.ReLU(), nn.Dropout(p=0.2, inplace=False), nn.Linear( int(num_ftrs/2),nClass) ) model.classifier[6].in_features=num_ftrs elif "VGG" in key: model = models.vgg11_bn(pretrained=preTrain) for param in model.parameters(): param.requires_grad = reqGrad num_ftrs = model.classifier[6].in_features model.classifier[6] = nn.Sequential( nn.Linear(num_ftrs, int(num_ftrs/2)), nn.BatchNorm1d(int(num_ftrs/2)), nn.ReLU(), nn.Dropout(p=0.2, inplace=False), nn.Linear( int(num_ftrs/2),nClass) ) model.classifier[6].in_features=num_ftrs elif "SqueezeNet" in key: model = models.squeezenet1_0(pretrained=preTrain) for param in model.parameters(): param.requires_grad = reqGrad model.classifier[1] = nn.Conv2d(512, nClass, kernel_size=(1,1), stride=(1,1)) model.num_classes = nClass elif "DenseNet" in key: model = models.densenet121(pretrained=preTrain) for param in model.parameters(): param.requires_grad = reqGrad num_ftrs = model.classifier.in_features model.classifier = nn.Sequential( nn.Linear(num_ftrs, int(num_ftrs/2)), nn.BatchNorm1d(int(num_ftrs/2)), nn.ReLU(), nn.Dropout(p=0.2, inplace=False), nn.Linear( int(num_ftrs/2),nClass) ) model.classifier.in_features = num_ftrs else: print("No model selected") model = None return(model) def freezeCNN(key,model): if "ResNet" in key: num_ftrs = model.fc.in_features temp_w = model.fc[0].weight.values temp_b = model.fc[0].bias.values model.fc = nn.Sequential( nn.Linear(num_ftrs, int(num_ftrs/2)), nn.BatchNorm1d(int(num_ftrs/2)), nn.ReLU(), ) model.fc[0].weight.values=temp_w model.fc[0].bias.values=temp_b model.fc.in_features = num_ftrs elif "AlexNet" in key: num_ftrs = model.classifier[6].in_features temp_w = model.classifier[6][0].weight.values temp_b = model.classifier[6][0].bias.values model.classifier[6] = nn.Sequential( nn.Linear(num_ftrs, int(num_ftrs/2)), nn.BatchNorm1d(int(num_ftrs/2)), nn.ReLU(), ) model.classifier[6][0].weight.values = temp_w model.classifier[6][0].bias.values = temp_b model.classifier[6].in_features = num_ftrs elif "VGG" in key: num_ftrs = model.classifier[6].in_features temp_w = model.classifier[6][0].weight.values temp_b = model.classifier[6][0].bias.values model.classifier[6] = nn.Sequential( nn.Linear(num_ftrs, int(num_ftrs/2)), nn.BatchNorm1d(int(num_ftrs/2)), nn.ReLU(), ) model.classifier[6][0].weight.values = temp_w model.classifier[6][0].bias.values = temp_b model.classifier[6].in_features = num_ftrs elif "SqueezeNet" in key: model.classifier[1] = nn.Dropout(p=0, inplace=False) elif "DenseNet" in key: num_ftrs = model.classifier.in_features temp_w = model.classifier[0].weight.values temp_b = model.classifier[0].bias.values model.classifier = nn.Sequential( nn.Linear(num_ftrs, int(num_ftrs/2)), nn.BatchNorm1d(int(num_ftrs/2)), nn.ReLU(), ) model.classifier[0].weight.values = temp_w model.classifier[0].bias.values = temp_b model.classifier.in_features = num_ftrs else: print("No model selected") model = None return(model) def addClassificationCNN(key,model,nClass): if "ResNet" in key: num_ftrs = model.fc.in_features model.fc = nn.Sequential( nn.Linear(num_ftrs, int(num_ftrs/2)), nn.BatchNorm1d(int(num_ftrs/2)), nn.ReLU(), nn.Dropout(p=0.2, inplace=False), nn.Linear( int(num_ftrs/2),nClass) ) model.fc.in_features = num_ftrs elif "AlexNet" in key: num_ftrs = model.classifier[6].in_features model.classifier[6] = nn.Sequential( nn.Linear(num_ftrs, int(num_ftrs/2)), nn.BatchNorm1d(int(num_ftrs/2)), nn.ReLU(), nn.Dropout(p=0.2, inplace=False), nn.Linear( int(num_ftrs/2),nClass) ) model.classifier[6].in_features=num_ftrs elif "VGG" in key: num_ftrs = model.classifier[6].in_features model.classifier[6] = nn.Sequential( nn.Linear(num_ftrs, int(num_ftrs/2)), nn.BatchNorm1d(int(num_ftrs/2)), nn.ReLU(), nn.Dropout(p=0.2, inplace=False), nn.Linear( int(num_ftrs/2),nClass) ) model.classifier[6].in_features=num_ftrs elif "SqueezeNet" in key: model.classifier[1] = nn.Conv2d(512, nClass, kernel_size=(1,1), stride=(1,1)) model.num_classes = nClass elif "DenseNet" in key: num_ftrs = model.classifier.in_features model.classifier = nn.Sequential( nn.Linear(num_ftrs, int(num_ftrs/2)), nn.BatchNorm1d(int(num_ftrs/2)), nn.ReLU(), nn.Dropout(p=0.2, inplace=False), nn.Linear( int(num_ftrs/2),nClass) ) model.classifier.in_features = num_ftrs else: print("No model selected") model = None return(model) def extractFeature(model,df,transform,batch_size=1): isGPU = torch.cuda.is_available() partition = {'data': np.array(df['path'])} labels = {} for label, path in zip(df['path'],df['path']): labels[path]=label set = Dataset(partition['data'], labels, transform) loader = Data.DataLoader(set,batch_size=batch_size,shuffle=False,num_workers=4) model.eval() if isGPU: model.cuda() p=0 print('Extracting features') batch_df=pd.DataFrame() for inputs, targets in loader: p+=1 print(' \t Batch '+str(p)+' of '+str(len(loader))) if isGPU: inputs = inputs.cuda() outputs = model(inputs) if isGPU: outputs = outputs.cpu().detach().numpy().tolist() inputs=inputs.cpu() np.shape(outputs) np.shape(targets) batch_df_temp = pd.DataFrame(outputs) Xcols = ['CNN_'+str(j) for j in batch_df_temp.columns] batch_df_temp.columns = Xcols batch_df_temp['path']=targets batch_df = batch_df.append(batch_df_temp) del inputs, targets, outputs torch.cuda.empty_cache() if isGPU: model=model.cpu() torch.cuda.empty_cache() out = pd.merge(df,batch_df,on="path") return(Xcols,out)
[ "torch.nn.Dropout", "seaborn.heatmap", "numpy.argmax", "sklearn.model_selection.train_test_split", "sklearn.metrics.accuracy_score", "sklearn.preprocessing.MinMaxScaler", "sklearn.metrics.classification_report", "numpy.shape", "LumiGAN.dataset.Dataset", "numpy.random.randint", "matplotlib.pyplot.figure", "sklearn.metrics.f1_score", "torch.nn.Softmax", "numpy.mean", "matplotlib.pyplot.tight_layout", "pandas.DataFrame", "torch.nn.MSELoss", "numpy.zeros_like", "torch.utils.data.DataLoader", "matplotlib.pyplot.close", "pandas.merge", "scipy.stats.linregress", "datetime.datetime.now", "torchvision.models.resnet18", "matplotlib.pyplot.show", "torchvision.models.vgg11_bn", "torch.manual_seed", "torchvision.models.alexnet", "torch.nn.Conv2d", "sklearn.metrics.recall_score", "scipy.interp", "numpy.min", "torch.cuda.is_available", "torchvision.models.squeezenet1_0", "matplotlib.pyplot.subplot", "torch.nn.ReLU", "sklearn.metrics.roc_curve", "torchvision.models.densenet121", "torch.nn.CrossEntropyLoss", "LumiGAN.logger.Logger", "time.time", "sklearn.metrics.auc", "numpy.array", "torch.cuda.empty_cache", "sklearn.metrics.precision_score", "sklearn.metrics.confusion_matrix", "matplotlib.gridspec.GridSpec", "matplotlib.pyplot.savefig" ]
[((1375, 1400), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (1398, 1400), False, 'import torch\n'), ((1663, 1680), 'LumiGAN.logger.Logger', 'Logger', (['tracefile'], {}), '(tracefile)\n', (1669, 1680), False, 'from LumiGAN.logger import Logger\n'), ((4128, 4157), 'torch.manual_seed', 'torch.manual_seed', (['randomSeed'], {}), '(randomSeed)\n', (4145, 4157), False, 'import torch\n'), ((5239, 5317), 'sklearn.model_selection.train_test_split', 'train_test_split', (['df'], {'test_size': 'self.split_size', 'random_state': 'split_randomSeed'}), '(df, test_size=self.split_size, random_state=split_randomSeed)\n', (5255, 5317), False, 'from sklearn.model_selection import train_test_split\n'), ((5593, 5644), 'LumiGAN.dataset.Dataset', 'Dataset', (["partition['train']", 'labels', 'transformTrain'], {}), "(partition['train'], labels, transformTrain)\n", (5600, 5644), False, 'from LumiGAN.dataset import Dataset\n'), ((5664, 5709), 'LumiGAN.dataset.Dataset', 'Dataset', (["partition['test']", 'labels', 'transform'], {}), "(partition['test'], labels, transform)\n", (5671, 5709), False, 'from LumiGAN.dataset import Dataset\n'), ((12719, 12788), 'torch.utils.data.DataLoader', 'Data.DataLoader', (['Test_set'], {'batch_size': '(1)', 'shuffle': '(False)', 'num_workers': '(0)'}), '(Test_set, batch_size=1, shuffle=False, num_workers=0)\n', (12734, 12788), True, 'import torch.utils.data as Data\n'), ((25785, 25881), 'pandas.DataFrame', 'pd.DataFrame', (["{'epoch': tab_epoch, 'train_loss': train_avg_loss, 'test_loss': tab_test_loss}"], {}), "({'epoch': tab_epoch, 'train_loss': train_avg_loss, 'test_loss':\n tab_test_loss})\n", (25797, 25881), True, 'import pandas as pd\n'), ((33517, 33542), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (33540, 33542), False, 'import torch\n'), ((33714, 33759), 'LumiGAN.dataset.Dataset', 'Dataset', (["partition['data']", 'labels', 'transform'], {}), "(partition['data'], labels, transform)\n", (33721, 33759), False, 'from LumiGAN.dataset import Dataset\n'), ((33777, 33850), 'torch.utils.data.DataLoader', 'Data.DataLoader', (['set'], {'batch_size': 'batch_size', 'shuffle': '(False)', 'num_workers': '(4)'}), '(set, batch_size=batch_size, shuffle=False, num_workers=4)\n', (33792, 33850), True, 'import torch.utils.data as Data\n'), ((33966, 33980), 'pandas.DataFrame', 'pd.DataFrame', ([], {}), '()\n', (33978, 33980), True, 'import pandas as pd\n'), ((34742, 34766), 'torch.cuda.empty_cache', 'torch.cuda.empty_cache', ([], {}), '()\n', (34764, 34766), False, 'import torch\n'), ((34781, 34814), 'pandas.merge', 'pd.merge', (['df', 'batch_df'], {'on': '"""path"""'}), "(df, batch_df, on='path')\n", (34789, 34814), True, 'import pandas as pd\n'), ((4019, 4042), 'numpy.random.randint', 'np.random.randint', (['(1000)'], {}), '(1000)\n', (4036, 4042), True, 'import numpy as np\n'), ((4096, 4119), 'numpy.random.randint', 'np.random.randint', (['(1000)'], {}), '(1000)\n', (4113, 4119), True, 'import numpy as np\n'), ((4836, 4864), 'sklearn.preprocessing.MinMaxScaler', 'preprocessing.MinMaxScaler', ([], {}), '()\n', (4862, 4864), False, 'from sklearn import preprocessing\n'), ((5348, 5374), 'numpy.array', 'np.array', (["df_train['path']"], {}), "(df_train['path'])\n", (5356, 5374), True, 'import numpy as np\n'), ((5384, 5409), 'numpy.array', 'np.array', (["df_test['path']"], {}), "(df_test['path'])\n", (5392, 5409), True, 'import numpy as np\n'), ((8295, 8398), 'torch.utils.data.DataLoader', 'Data.DataLoader', (['Train_set'], {'batch_size': 'self.batch_size', 'shuffle': '(True)', 'num_workers': '(4)', 'drop_last': '(True)'}), '(Train_set, batch_size=self.batch_size, shuffle=True,\n num_workers=4, drop_last=True)\n', (8310, 8398), True, 'import torch.utils.data as Data\n'), ((8419, 8506), 'torch.utils.data.DataLoader', 'Data.DataLoader', (['Test_set'], {'batch_size': 'self.batch_size', 'shuffle': '(False)', 'num_workers': '(4)'}), '(Test_set, batch_size=self.batch_size, shuffle=False,\n num_workers=4)\n', (8434, 8506), True, 'import torch.utils.data as Data\n'), ((8611, 8622), 'time.time', 'time.time', ([], {}), '()\n', (8620, 8622), False, 'import time\n'), ((12385, 12396), 'time.time', 'time.time', ([], {}), '()\n', (12394, 12396), False, 'import time\n'), ((14343, 14387), 'scipy.stats.linregress', 'scipy.stats.linregress', (['tab_Actual', 'tab_Pred'], {}), '(tab_Actual, tab_Pred)\n', (14365, 14387), False, 'import scipy\n'), ((17892, 17914), 'numpy.zeros_like', 'np.zeros_like', (['all_fpr'], {}), '(all_fpr)\n', (17905, 17914), True, 'import numpy as np\n'), ((18221, 18260), 'sklearn.metrics.auc', 'metrics.auc', (["fpr['macro']", "tpr['macro']"], {}), "(fpr['macro'], tpr['macro'])\n", (18232, 18260), False, 'from sklearn import metrics\n'), ((19363, 19391), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(10, 10)'}), '(figsize=(10, 10))\n', (19373, 19391), True, 'import matplotlib.pyplot as plt\n'), ((19410, 19437), 'matplotlib.gridspec.GridSpec', 'mpl.gridspec.GridSpec', (['(2)', '(2)'], {}), '(2, 2)\n', (19431, 19437), True, 'import matplotlib as mpl\n'), ((25585, 25623), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {'rect': '[0, 0, 1, 0.93]'}), '(rect=[0, 0, 1, 0.93])\n', (25601, 25623), True, 'import matplotlib.pyplot as plt\n'), ((25727, 25737), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (25735, 25737), True, 'import matplotlib.pyplot as plt\n'), ((25750, 25761), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (25759, 25761), True, 'import matplotlib.pyplot as plt\n'), ((26050, 26074), 'torch.cuda.empty_cache', 'torch.cuda.empty_cache', ([], {}), '()\n', (26072, 26074), False, 'import torch\n'), ((26504, 26540), 'torchvision.models.resnet18', 'models.resnet18', ([], {'pretrained': 'preTrain'}), '(pretrained=preTrain)\n', (26519, 26540), False, 'from torchvision import datasets, models, transforms\n'), ((33572, 33592), 'numpy.array', 'np.array', (["df['path']"], {}), "(df['path'])\n", (33580, 33592), True, 'import numpy as np\n'), ((34317, 34334), 'numpy.shape', 'np.shape', (['outputs'], {}), '(outputs)\n', (34325, 34334), True, 'import numpy as np\n'), ((34347, 34364), 'numpy.shape', 'np.shape', (['targets'], {}), '(targets)\n', (34355, 34364), True, 'import numpy as np\n'), ((34393, 34414), 'pandas.DataFrame', 'pd.DataFrame', (['outputs'], {}), '(outputs)\n', (34405, 34414), True, 'import pandas as pd\n'), ((34673, 34697), 'torch.cuda.empty_cache', 'torch.cuda.empty_cache', ([], {}), '()\n', (34695, 34697), False, 'import torch\n'), ((1316, 1341), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (1339, 1341), False, 'import torch\n'), ((1509, 1532), 'datetime.datetime.now', 'datetime.datetime.now', ([], {}), '()\n', (1530, 1532), False, 'import datetime\n'), ((5898, 5910), 'torch.nn.MSELoss', 'nn.MSELoss', ([], {}), '()\n', (5908, 5910), True, 'import torch.nn as nn\n'), ((5925, 5946), 'torch.nn.CrossEntropyLoss', 'nn.CrossEntropyLoss', ([], {}), '()\n', (5944, 5946), True, 'import torch.nn as nn\n'), ((8935, 8946), 'time.time', 'time.time', ([], {}), '()\n', (8944, 8946), False, 'import time\n'), ((8982, 8993), 'time.time', 'time.time', ([], {}), '()\n', (8991, 8993), False, 'import time\n'), ((14031, 14055), 'torch.cuda.empty_cache', 'torch.cuda.empty_cache', ([], {}), '()\n', (14053, 14055), False, 'import torch\n'), ((16735, 16791), 'sklearn.metrics.recall_score', 'metrics.recall_score', (['tab_Actual', 'tab_Pred'], {'average': 'None'}), '(tab_Actual, tab_Pred, average=None)\n', (16755, 16791), False, 'from sklearn import metrics\n'), ((16911, 16970), 'sklearn.metrics.precision_score', 'metrics.precision_score', (['tab_Actual', 'tab_Pred'], {'average': 'None'}), '(tab_Actual, tab_Pred, average=None)\n', (16934, 16970), False, 'from sklearn import metrics\n'), ((17093, 17145), 'sklearn.metrics.f1_score', 'metrics.f1_score', (['tab_Actual', 'tab_Pred'], {'average': 'None'}), '(tab_Actual, tab_Pred, average=None)\n', (17109, 17145), False, 'from sklearn import metrics\n'), ((17464, 17523), 'sklearn.metrics.roc_curve', 'metrics.roc_curve', (['tab_Actual', 'tab_Prob[label]'], {'pos_label': 'i'}), '(tab_Actual, tab_Prob[label], pos_label=i)\n', (17481, 17523), False, 'from sklearn import metrics\n'), ((17552, 17579), 'sklearn.metrics.auc', 'metrics.auc', (['fpr[i]', 'tpr[i]'], {}), '(fpr[i], tpr[i])\n', (17563, 17579), False, 'from sklearn import metrics\n'), ((17988, 18025), 'scipy.interp', 'scipy.interp', (['all_fpr', 'fpr[i]', 'tpr[i]'], {}), '(all_fpr, fpr[i], tpr[i])\n', (18000, 18025), False, 'import scipy\n'), ((19220, 19281), 'sklearn.metrics.classification_report', 'metrics.classification_report', (['tab_Actual', 'tab_Pred'], {'digits': '(3)'}), '(tab_Actual, tab_Pred, digits=3)\n', (19249, 19281), False, 'from sklearn import metrics\n'), ((19507, 19528), 'matplotlib.pyplot.subplot', 'plt.subplot', (['gs[0, :]'], {}), '(gs[0, :])\n', (19518, 19528), True, 'import matplotlib.pyplot as plt\n'), ((19542, 19565), 'matplotlib.pyplot.subplot', 'plt.subplot', (['gs[0, :-1]'], {}), '(gs[0, :-1])\n', (19553, 19565), True, 'import matplotlib.pyplot as plt\n'), ((20151, 20172), 'matplotlib.pyplot.subplot', 'plt.subplot', (['gs[1, :]'], {}), '(gs[1, :])\n', (20162, 20172), True, 'import matplotlib.pyplot as plt\n'), ((20603, 20624), 'matplotlib.pyplot.subplot', 'plt.subplot', (['gs[1, :]'], {}), '(gs[1, :])\n', (20614, 20624), True, 'import matplotlib.pyplot as plt\n'), ((21244, 21266), 'matplotlib.pyplot.subplot', 'plt.subplot', (['gs[0, -1]'], {}), '(gs[0, -1])\n', (21255, 21266), True, 'import matplotlib.pyplot as plt\n'), ((21361, 21407), 'sklearn.metrics.confusion_matrix', 'metrics.confusion_matrix', (['tab_Actual', 'tab_Pred'], {}), '(tab_Actual, tab_Pred)\n', (21385, 21407), False, 'from sklearn import metrics\n'), ((25649, 25716), 'matplotlib.pyplot.savefig', 'plt.savefig', (['self.figurefile'], {'transparent': '(True)', 'bbox_inches': '"""tight"""'}), "(self.figurefile, transparent=True, bbox_inches='tight')\n", (25660, 25716), True, 'import matplotlib.pyplot as plt\n'), ((26817, 26826), 'torch.nn.ReLU', 'nn.ReLU', ([], {}), '()\n', (26824, 26826), True, 'import torch.nn as nn\n'), ((26844, 26876), 'torch.nn.Dropout', 'nn.Dropout', ([], {'p': '(0.2)', 'inplace': '(False)'}), '(p=0.2, inplace=False)\n', (26854, 26876), True, 'import torch.nn as nn\n'), ((27039, 27074), 'torchvision.models.alexnet', 'models.alexnet', ([], {'pretrained': 'preTrain'}), '(pretrained=preTrain)\n', (27053, 27074), False, 'from torchvision import datasets, models, transforms\n'), ((29426, 29435), 'torch.nn.ReLU', 'nn.ReLU', ([], {}), '()\n', (29433, 29435), True, 'import torch.nn as nn\n'), ((31721, 31730), 'torch.nn.ReLU', 'nn.ReLU', ([], {}), '()\n', (31728, 31730), True, 'import torch.nn as nn\n'), ((31748, 31780), 'torch.nn.Dropout', 'nn.Dropout', ([], {'p': '(0.2)', 'inplace': '(False)'}), '(p=0.2, inplace=False)\n', (31758, 31780), True, 'import torch.nn as nn\n'), ((12100, 12124), 'torch.cuda.empty_cache', 'torch.cuda.empty_cache', ([], {}), '()\n', (12122, 12124), False, 'import torch\n'), ((13479, 13496), 'torch.nn.Softmax', 'nn.Softmax', ([], {'dim': '(1)'}), '(dim=1)\n', (13489, 13496), True, 'import torch.nn as nn\n'), ((13725, 13746), 'numpy.argmax', 'np.argmax', (['prediction'], {}), '(prediction)\n', (13734, 13746), True, 'import numpy as np\n'), ((14790, 14817), 'numpy.mean', 'np.mean', (['tab_train_loss[-1]'], {}), '(tab_train_loss[-1])\n', (14797, 14817), True, 'import numpy as np\n'), ((15055, 15076), 'numpy.min', 'np.min', (['tab_test_loss'], {}), '(tab_test_loss)\n', (15061, 15076), True, 'import numpy as np\n'), ((15897, 15924), 'numpy.mean', 'np.mean', (['tab_train_loss[-1]'], {}), '(tab_train_loss[-1])\n', (15904, 15924), True, 'import numpy as np\n'), ((16162, 16183), 'numpy.min', 'np.min', (['tab_test_loss'], {}), '(tab_test_loss)\n', (16168, 16183), True, 'import numpy as np\n'), ((16239, 16283), 'sklearn.metrics.accuracy_score', 'metrics.accuracy_score', (['tab_Actual', 'tab_Pred'], {}), '(tab_Actual, tab_Pred)\n', (16261, 16283), False, 'from sklearn import metrics\n'), ((16338, 16396), 'sklearn.metrics.f1_score', 'metrics.f1_score', (['tab_Actual', 'tab_Pred'], {'average': '"""weighted"""'}), "(tab_Actual, tab_Pred, average='weighted')\n", (16354, 16396), False, 'from sklearn import metrics\n'), ((16451, 16516), 'sklearn.metrics.precision_score', 'metrics.precision_score', (['tab_Actual', 'tab_Pred'], {'average': '"""weighted"""'}), "(tab_Actual, tab_Pred, average='weighted')\n", (16474, 16516), False, 'from sklearn import metrics\n'), ((16568, 16630), 'sklearn.metrics.recall_score', 'metrics.recall_score', (['tab_Actual', 'tab_Pred'], {'average': '"""weighted"""'}), "(tab_Actual, tab_Pred, average='weighted')\n", (16588, 16630), False, 'from sklearn import metrics\n'), ((19910, 19920), 'numpy.mean', 'np.mean', (['y'], {}), '(y)\n', (19917, 19920), True, 'import numpy as np\n'), ((21932, 22071), 'seaborn.heatmap', 'sns.heatmap', (['df_CM'], {'annot': '(True)', 'ax': 'ax3', 'cbar': '(False)', 'fmt': '"""d"""', 'square': '(True)', 'linewidths': '(0.5)', 'linecolor': '"""w"""', 'annot_kws': "{'size': self.CM_fz}"}), "(df_CM, annot=True, ax=ax3, cbar=False, fmt='d', square=True,\n linewidths=0.5, linecolor='w', annot_kws={'size': self.CM_fz})\n", (21943, 22071), True, 'import seaborn as sns\n'), ((27373, 27382), 'torch.nn.ReLU', 'nn.ReLU', ([], {}), '()\n', (27380, 27382), True, 'import torch.nn as nn\n'), ((27400, 27432), 'torch.nn.Dropout', 'nn.Dropout', ([], {'p': '(0.2)', 'inplace': '(False)'}), '(p=0.2, inplace=False)\n', (27410, 27432), True, 'import torch.nn as nn\n'), ((27599, 27635), 'torchvision.models.vgg11_bn', 'models.vgg11_bn', ([], {'pretrained': 'preTrain'}), '(pretrained=preTrain)\n', (27614, 27635), False, 'from torchvision import datasets, models, transforms\n'), ((29951, 29960), 'torch.nn.ReLU', 'nn.ReLU', ([], {}), '()\n', (29958, 29960), True, 'import torch.nn as nn\n'), ((32146, 32155), 'torch.nn.ReLU', 'nn.ReLU', ([], {}), '()\n', (32153, 32155), True, 'import torch.nn as nn\n'), ((32173, 32205), 'torch.nn.Dropout', 'nn.Dropout', ([], {'p': '(0.2)', 'inplace': '(False)'}), '(p=0.2, inplace=False)\n', (32183, 32205), True, 'import torch.nn as nn\n'), ((10465, 10476), 'time.time', 'time.time', ([], {}), '()\n', (10474, 10476), False, 'import time\n'), ((10770, 10794), 'torch.cuda.empty_cache', 'torch.cuda.empty_cache', ([], {}), '()\n', (10792, 10794), False, 'import torch\n'), ((27934, 27943), 'torch.nn.ReLU', 'nn.ReLU', ([], {}), '()\n', (27941, 27943), True, 'import torch.nn as nn\n'), ((27961, 27993), 'torch.nn.Dropout', 'nn.Dropout', ([], {'p': '(0.2)', 'inplace': '(False)'}), '(p=0.2, inplace=False)\n', (27971, 27993), True, 'import torch.nn as nn\n'), ((28167, 28208), 'torchvision.models.squeezenet1_0', 'models.squeezenet1_0', ([], {'pretrained': 'preTrain'}), '(pretrained=preTrain)\n', (28187, 28208), False, 'from torchvision import datasets, models, transforms\n'), ((28318, 28375), 'torch.nn.Conv2d', 'nn.Conv2d', (['(512)', 'nClass'], {'kernel_size': '(1, 1)', 'stride': '(1, 1)'}), '(512, nClass, kernel_size=(1, 1), stride=(1, 1))\n', (28327, 28375), True, 'import torch.nn as nn\n'), ((30509, 30518), 'torch.nn.ReLU', 'nn.ReLU', ([], {}), '()\n', (30516, 30518), True, 'import torch.nn as nn\n'), ((30771, 30801), 'torch.nn.Dropout', 'nn.Dropout', ([], {'p': '(0)', 'inplace': '(False)'}), '(p=0, inplace=False)\n', (30781, 30801), True, 'import torch.nn as nn\n'), ((32575, 32584), 'torch.nn.ReLU', 'nn.ReLU', ([], {}), '()\n', (32582, 32584), True, 'import torch.nn as nn\n'), ((32602, 32634), 'torch.nn.Dropout', 'nn.Dropout', ([], {'p': '(0.2)', 'inplace': '(False)'}), '(p=0.2, inplace=False)\n', (32612, 32634), True, 'import torch.nn as nn\n'), ((32822, 32879), 'torch.nn.Conv2d', 'nn.Conv2d', (['(512)', 'nClass'], {'kernel_size': '(1, 1)', 'stride': '(1, 1)'}), '(512, nClass, kernel_size=(1, 1), stride=(1, 1))\n', (32831, 32879), True, 'import torch.nn as nn\n'), ((11805, 11816), 'time.time', 'time.time', ([], {}), '()\n', (11814, 11816), False, 'import time\n'), ((14883, 14895), 'numpy.mean', 'np.mean', (['avg'], {}), '(avg)\n', (14890, 14895), True, 'import numpy as np\n'), ((15990, 16002), 'numpy.mean', 'np.mean', (['avg'], {}), '(avg)\n', (15997, 16002), True, 'import numpy as np\n'), ((28465, 28504), 'torchvision.models.densenet121', 'models.densenet121', ([], {'pretrained': 'preTrain'}), '(pretrained=preTrain)\n', (28483, 28504), False, 'from torchvision import datasets, models, transforms\n'), ((21605, 21626), 'pandas.DataFrame', 'pd.DataFrame', (['CM_data'], {}), '(CM_data)\n', (21617, 21626), True, 'import pandas as pd\n'), ((28797, 28806), 'torch.nn.ReLU', 'nn.ReLU', ([], {}), '()\n', (28804, 28806), True, 'import torch.nn as nn\n'), ((28824, 28856), 'torch.nn.Dropout', 'nn.Dropout', ([], {'p': '(0.2)', 'inplace': '(False)'}), '(p=0.2, inplace=False)\n', (28834, 28856), True, 'import torch.nn as nn\n'), ((31159, 31168), 'torch.nn.ReLU', 'nn.ReLU', ([], {}), '()\n', (31166, 31168), True, 'import torch.nn as nn\n'), ((33166, 33175), 'torch.nn.ReLU', 'nn.ReLU', ([], {}), '()\n', (33173, 33175), True, 'import torch.nn as nn\n'), ((33193, 33225), 'torch.nn.Dropout', 'nn.Dropout', ([], {'p': '(0.2)', 'inplace': '(False)'}), '(p=0.2, inplace=False)\n', (33203, 33225), True, 'import torch.nn as nn\n'), ((10305, 10316), 'time.time', 'time.time', ([], {}), '()\n', (10314, 10316), False, 'import time\n'), ((14157, 14177), 'numpy.array', 'np.array', (['tab_Actual'], {}), '(tab_Actual)\n', (14165, 14177), True, 'import numpy as np\n'), ((14258, 14276), 'numpy.array', 'np.array', (['tab_Pred'], {}), '(tab_Pred)\n', (14266, 14276), True, 'import numpy as np\n')]
# -*- coding: utf-8 -*- import numpy from scipy import spatial from numpy import matrix from math import sqrt from panda3d.core import Point3, TransformState from panda3d.bullet import BulletSphereShape, BulletRigidBodyNode from random import uniform, gauss, random from time import time import math from cellpack.mgl_tools.bhtree import bhtreelib from cellpack.autopack.transformation import angle_between_vectors from cellpack.autopack.ldSequence import SphereHalton from .utils import rotVectToVect import cellpack.autopack as autopack from .multi_cylinder import MultiCylindersIngr helper = autopack.helper class GrowIngredient(MultiCylindersIngr): def __init__( self, molarity=0.0, radii=None, positions=None, positions2=None, sphereFile=None, packingPriority=0, name=None, pdb=None, color=None, nbJitter=5, jitterMax=(1, 1, 1), perturbAxisAmplitude=0.1, length=10.0, closed=False, modelType="Cylinders", biased=1.0, principalVector=(1, 0, 0), meshFile=None, packingMode="random", placeType="jitter", marge=20.0, meshObject=None, orientation=(1, 0, 0), nbMol=0, Type="Grow", walkingMode="sphere", **kw ): MultiCylindersIngr.__init__( self, molarity=molarity, radii=radii, positions=positions, positions2=positions2, sphereFile=sphereFile, packingPriority=packingPriority, name=name, pdb=pdb, color=color, nbJitter=nbJitter, jitterMax=jitterMax, perturbAxisAmplitude=perturbAxisAmplitude, principalVector=principalVector, meshFile=meshFile, packingMode=packingMode, placeType=placeType, meshObject=meshObject, nbMol=nbMol, Type=Type, **kw ) if name is None: name = "%s_%f" % (str(radii), molarity) self.name = name self.singleSphere = False self.modelType = modelType self.collisionLevel = 0 self.minRadius = self.radii[0][0] self.encapsulatingRadius = self.radii[0][0] self.marge = marge self.length = length self.closed = closed self.nbCurve = 0 self.results = [] self.start_positions = [] self.listePtLinear = [] self.listePtCurve = [] # snake self.Ptis = [] # snakePts self.startGridPoint = [] self.currentLength = 0.0 # snakelength self.direction = None # direction of growing # can be place either using grid point/jittering or dynamics # self.uLength = 0. #length of the cylinder or averall radius for sphere, this is the lenght of one unit self.uLength = 10 if "uLength" in kw: self.uLength = kw["uLength"] else: v, u = self.vi.measure_distance(self.positions, self.positions2, vec=True) self.uLength = abs(u) self.encapsulatingRadius = self.uLength / 2.0 self.unitNumberF = 0 # number of unit pose so far forward self.unitNumberR = 0 # number of unit pose so far reverse self.orientation = orientation self.seedOnPlus = True # The filament should continue to grow on its (+) end self.seedOnMinus = False # The filamen should continue to grow on its (-) end. # if self.compNum > 0 : # self.seedOnMinus = False self.vector = [0.0, 0.0, 0.0] self.biased = biased self.absoluteLengthMax = 99999999.9999 # (default value is infinite or some safety number like 1billion) self.probableLengthEquation = None # (this can be a number or an equation, e.g., every actin should grow to # 10 units long, or this actin fiber seed instance should grow to (random*10)^2 # actually its a function of self.uLength like self.uLength * 10. or *(random*10)^2 self.ingGrowthMatrix = numpy.identity(4) # (ultimately, we'll build a database for these (<NAME> has a few examples), # but users should be able to put in their own, so for a test for now, lets say we'll # grow one unit for a singleSphereIng r=60 along its X as [55,0,0;1,0,0;0,1,0;0,0,1] self.ingGrowthWobbleFormula = None # (this could be a rotation matrix to make a helix, or just a formula, # like the precession algorithm Michel and I already put in # for surface ingredients. self.constraintMarge = False self.cutoff_boundary = 1.0 self.cutoff_surface = 5.0 self.useHalton = True self.use_rbsphere = ( False # use sphere instead of cylinder or collision with bullet ) if "useHalton" in kw: self.useHalton = kw["useHalton"] if "constraintMarge" in kw: self.constraintMarge = kw["constraintMarge"] if "cutoff_boundary" in kw: self.cutoff_boundary = kw["cutoff_boundary"] if "cutoff_surface" in kw: self.cutoff_surface = kw["cutoff_surface"] if "use_rbsphere" in kw: self.use_rbsphere = kw["use_rbsphere"] if "encapsulatingRadius" in kw: self.use_rbsphere = kw["encapsulatingRadius"] # mesh object representing one uLength? or a certain length self.unitParent = None self.unitParentLength = 0.0 self.walkingMode = walkingMode # ["sphere","lattice"] self.walkingType = "stepbystep" # or atonce self.compMask = [] self.prev_v3 = [] # default should be compId if "compMask" in kw: if type(kw["compMask"]) is str: self.compMask = eval(kw["compMask"]) else: self.compMask = kw["compMask"] # create a simple geom if none pass? # self.compMask=[] if self.mesh is None and autopack.helper is not None: p = None if not autopack.helper.nogui: # build a cylinder and make it length uLength, radius radii[0] # this mesh is used bu RAPID for collision p = autopack.helper.getObject("autopackHider") if p is None: p = autopack.helper.newEmpty("autopackHider") if autopack.helper.host.find("blender") == -1: autopack.helper.toggleDisplay(p, False) # is axis working ? self.mesh = autopack.helper.Cylinder( self.name + "_basic", radius=self.radii[0][0] * 1.24, length=self.uLength, res=32, parent="autopackHider", axis=self.orientation, )[0] if autopack.helper.nogui: self.getData() self.sphere_points_nb = 50000 self.sphere_points = numpy.array(SphereHalton(self.sphere_points_nb, 5)) self.sphere_points_mask = numpy.ones(self.sphere_points_nb, "i") self.sphere_points_masked = None # need to define the binder/modifier. This is different from partner # Every nth place alternative repesentation # name proba is this for ingredient in general ? self.alternates_names = [] if "alternates_names" in kw: self.alternates_names = kw["alternates_names"] self.alternates_proba = [] if "alternates_proba" in kw: self.alternates_proba = kw["alternates_proba"] self.alternates_weight = [] if "alternates_weight" in kw: self.alternates_weight = kw["alternates_weight"] self.prev_alt = None self.prev_was_alternate = False self.prev_alt_pt = None self.mini_interval = 2 self.alternate_interval = 0 # keep record of point Id that are bound to alternate and change the # representation according. self.safetycutoff = 10 self.KWDS["length"] = {} self.KWDS["closed"] = {} self.KWDS["uLength"] = {} self.KWDS["biased"] = {} self.KWDS["marge"] = {} self.KWDS["orientation"] = {} self.KWDS["walkingMode"] = {} self.KWDS["constraintMarge"] = {} self.KWDS["useHalton"] = {} self.KWDS["compMask"] = {} self.KWDS["use_rbsphere"] = {} self.OPTIONS["length"] = { "name": "length", "value": self.length, "default": self.length, "type": "float", "min": 0, "max": 10000, "description": "snake total length", } self.OPTIONS["uLength"] = { "name": "uLength", "value": self.uLength, "default": self.uLength, "type": "float", "min": 0, "max": 10000, "description": "snake unit length", } self.OPTIONS["closed"] = { "name": "closed", "value": False, "default": False, "type": "bool", "min": 0.0, "max": 0.0, "description": "closed snake", } self.OPTIONS["biased"] = { "name": "biased", "value": 0.0, "default": 0.0, "type": "float", "min": 0, "max": 10, "description": "snake biased", } self.OPTIONS["marge"] = { "name": "marge", "value": 10.0, "default": 10.0, "type": "float", "min": 0, "max": 10000, "description": "snake angle marge", } self.OPTIONS["constraintMarge"] = { "name": "constraintMarge", "value": False, "default": False, "type": "bool", "min": 0.0, "max": 0.0, "description": "lock the marge", } self.OPTIONS["orientation"] = { "name": "orientation", "value": [0.0, 1.0, 0.0], "default": [0.0, 1.0, 0.0], "min": 0, "max": 1, "type": "vector", "description": "snake orientation", } self.OPTIONS["walkingMode"] = { "name": "walkingMode", "value": "random", "values": ["sphere", "lattice"], "min": 0.0, "max": 0.0, "default": "sphere", "type": "liste", "description": "snake mode", } self.OPTIONS["useHalton"] = { "name": "useHalton", "value": True, "default": True, "type": "bool", "min": 0.0, "max": 0.0, "description": "use spherica halton distribution", } self.OPTIONS["compMask"] = { "name": "compMask", "value": "0", "values": "0", "min": 0.0, "max": 0.0, "default": "0", "type": "string", "description": "allowed compartments", } self.OPTIONS["use_rbsphere"] = { "name": "use_rbsphere", "value": False, "default": False, "type": "bool", "min": 0.0, "max": 0.0, "description": "use sphere instead of cylinder wih bullet", } def get_new_distance_values( self, jtrans, rotMatj, gridPointsCoords, distance, dpad ): insidePoints = {} newDistPoints = {} cent1T = self.transformPoints(jtrans, rotMatj, self.positions[-1]) cent2T = self.transformPoints(jtrans, rotMatj, self.positions2[-1]) for radc, p1, p2 in zip(self.radii[-1], cent1T, cent2T): x1, y1, z1 = p1 x2, y2, z2 = p2 vx, vy, vz = vect = (x2 - x1, y2 - y1, z2 - z1) lengthsq = vx * vx + vy * vy + vz * vz length = sqrt(lengthsq) cx, cy, cz = posc = x1 + vx * 0.5, y1 + vy * 0.5, z1 + vz * 0.5 radt = length + radc + dpad bb = ([cx - radt, cy - radt, cz - radt], [cx + radt, cy + radt, cz + radt]) pointsInCube = self.env.callFunction( self.env.grid.getPointsInCube, (bb, posc, radt) ) pd = numpy.take(gridPointsCoords, pointsInCube, 0) - p1 dotp = numpy.dot(pd, vect) d2toP1 = numpy.sum(pd * pd, 1) dsq = d2toP1 - dotp * dotp / lengthsq pd2 = numpy.take(gridPointsCoords, pointsInCube, 0) - p2 d2toP2 = numpy.sum(pd2 * pd2, 1) for pti, pt in enumerate(pointsInCube): if pt in insidePoints: continue if dotp[pti] < 0.0: # outside 1st cap d = sqrt(d2toP1[pti]) if d < distance[pt]: # point in region of influence if pt in newDistPoints: if d < newDistPoints[pt]: newDistPoints[pt] = d else: newDistPoints[pt] = d elif dotp[pti] > lengthsq: d = sqrt(d2toP2[pti]) if d < distance[pt]: # point in region of influence if pt in newDistPoints: if d < newDistPoints[pt]: newDistPoints[pt] = d else: newDistPoints[pt] = d else: d = sqrt(dsq[pti]) - radc if d < 0.0: # point is inside dropped sphere if pt in insidePoints: if d < insidePoints[pt]: insidePoints[pt] = d else: insidePoints[pt] = d return insidePoints, newDistPoints def resetSphereDistribution(self): # given a radius, create the sphere distribution self.sphere_points = SphereHalton(self.sphere_points_nb, 5) self.sphere_points_mask = numpy.ones(self.sphere_points_nb, "i") def getNextPoint(self): # pick a random point from the sphere point distribution pointsmask = numpy.nonzero(self.sphere_points_mask)[0] if not len(pointsmask): print("no sphere point available from mask") return None ptIndr = int(uniform(0.0, 1.0) * len(pointsmask)) sp_pt_indice = pointsmask[ptIndr] np = numpy.array(self.sphere_points[sp_pt_indice]) * numpy.array(self.jitterMax) return ( numpy.array(self.vi.unit_vector(np)) * self.uLength ) # biased by jitterMax ? def mask_sphere_points_boundary(self, pt, boundingBox=None): if boundingBox is None: boundingBox = self.env.fillBB pts = (numpy.array(self.sphere_points) * self.uLength) + pt points_mask = numpy.nonzero(self.sphere_points_mask)[0] if len(points_mask): mask = [not self.point_is_not_available(pt) for pt in pts[points_mask]] if len(mask): self.sphere_points_mask[points_mask] = numpy.logical_and( mask, self.sphere_points_mask[points_mask] ) def mask_sphere_points_ingredients(self, pt, listeclosest): listeclosest = [ elem for elem in listeclosest if not isinstance(elem[3], autopack.Compartment.Compartment) ] points_mask = numpy.nonzero(self.sphere_points_mask)[0] if len(listeclosest) and len(points_mask): points = numpy.array(listeclosest)[:, 1] ingrs = numpy.array(listeclosest)[:, 3] radius = [float(ingr.encapsulatingRadius) for ingr in ingrs] # this distance is between unit vector and 3d points... # translate and scale the spheres points sp = numpy.array(self.sphere_points, dtype=numpy.float64, copy=False) dp = sp[points_mask] * self.uLength + pt pts = numpy.array(points.tolist(), dtype=numpy.float64, copy=False) # distance between sphere point and ingredient positions distances = spatial.distance.cdist(pts, dp) # empty mask for the point mask = numpy.nonzero(numpy.ones(len(dp)))[0] # mas cumulative ?for for i in range(len(distances)): # if distance is >= to ingredient encapsulatingRadius we keep the point m = numpy.greater_equal(distances[i], radius[i]) mask = numpy.logical_and(mask, m) # ponts to keep self.sphere_points_mask[points_mask] = numpy.logical_and( mask, self.sphere_points_mask[points_mask] ) # indices = numpy.nonzero(mask)[0]#indice f # i = self.sphere_points_mask[indices] # self.sphere_points_mask = i def mask_sphere_points_dihedral(self, v1, v2, marge_out, marge_diedral, v3=[]): print("mask_sphere_points_dihedral") points_mask = numpy.nonzero(self.sphere_points_mask)[0] if len(v3): # a=angle_between_vectors(self.vi.unit_vector(v2),self.sphere_points[points_mask], axis=1) d = angle_between_vectors( self.vi.unit_vector(v3), self.sphere_points[points_mask], axis=1 ) if type(marge_out) is float: marge_out = [0.0, marge_out] # mask1 = numpy.logical_and(a<math.radians(marge_out[1]), a > math.radians(marge_out[0]))#794 mask4 = numpy.less(d, math.radians(5)) # 18 # mask3 = numpy.logical_and(mask4,mask1)#0? self.sphere_points_mask[points_mask] = numpy.logical_and( mask4, self.sphere_points_mask[points_mask] ) else: a = angle_between_vectors( self.vi.unit_vector(v2), self.sphere_points[points_mask], axis=1 ) b = angle_between_vectors( self.vi.unit_vector(v1), self.sphere_points[points_mask], axis=1 ) if type(marge_out) is float: marge_out = [0.0, marge_out] if type(marge_diedral) is float: marge_diedral = [0.0, marge_diedral] mask1 = numpy.logical_and( a < math.radians(marge_out[1]), a > math.radians(marge_out[0]) ) mask2 = numpy.logical_and( b < math.radians(marge_diedral[1]), b > math.radians(marge_diedral[0]) ) mask3 = numpy.logical_and(mask1, mask2) self.sphere_points_mask[points_mask] = numpy.logical_and( mask3, self.sphere_points_mask[points_mask] ) def mask_sphere_points_angle(self, v, marge_in): # mask first with angle # adjust the points to current transfomation? or normalize current vector ? points_mask = numpy.nonzero(self.sphere_points_mask)[0] a = angle_between_vectors( self.vi.unit_vector(v), self.sphere_points[points_mask], axis=1 ) if type(marge_in) is float: mask = numpy.less(a, math.radians(marge_in)) else: mask = numpy.logical_and( a < math.radians(marge_in[1]), a > math.radians(marge_in[0]) ) self.sphere_points_mask[points_mask] = numpy.logical_and( mask, self.sphere_points_mask[points_mask] ) def mask_sphere_points_vector(self, v, pt, alternate): points_mask = numpy.nonzero(self.sphere_points_mask)[0] # pick the point that are close to pt2-pt3 # align v to pt1-pt2, apply to pt2-pt3 # mesure angle pta = self.partners[alternate].getProperties("pt1") ptb = self.partners[alternate].getProperties("pt2") ptc = self.partners[alternate].getProperties("pt3") toalign = numpy.array(ptb) - numpy.array(pta) m = numpy.array(rotVectToVect(toalign, v)).transpose() m[3, :3] = numpy.array(pt) # jtrans pts = autopack.helper.ApplyMatrix([pta], m.transpose()) # transpose ? v = numpy.array(pt) - pts[0] m[3, :3] = numpy.array(pt) + v newPts = autopack.helper.ApplyMatrix([ptb, ptc], m.transpose()) # transpose ? a = angle_between_vectors( self.vi.unit_vector(newPts[1] - newPts[0]), self.sphere_points[points_mask], axis=1, ) mask = numpy.less(a, math.radians(5.0)) self.sphere_points_mask[points_mask] = numpy.logical_and( mask, self.sphere_points_mask[points_mask] ) def mask_sphere_points( self, v, pt, marge, listeclosest, cutoff, alternate=None, pv=None, marge_diedral=None, v3=[], ): # self.sphere_points_mask=numpy.ones(10000,'i') print("mask_sphere_points ", marge_diedral, marge, len(listeclosest)) if marge_diedral is not None: self.mask_sphere_points_dihedral(pv, v, marge, marge_diedral, v3) else: if alternate is not None: self.mask_sphere_points_vector(v, pt, alternate) else: self.mask_sphere_points_angle(v, marge) # storethe mask point sphere_points_mask_copy = numpy.copy(self.sphere_points_mask) self.mask_sphere_points_ingredients(pt, listeclosest) if not len(numpy.nonzero(self.sphere_points_mask)[0]): self.sphere_points_mask = numpy.copy(sphere_points_mask_copy) # self.mask_sphere_points_boundary(pt) # print ("after mask2 ",len( numpy.nonzero(self.sphere_points_mask)[0])) def reset(self): self.nbCurve = 0 self.results = [] self.listePtLinear = [] self.listePtCurve = [] # snake self.Ptis = [] # snakePts self.currentLength = 0.0 # snakelength # update he cylinder ? def getNextPtIndCyl(self, jtrans, rotMatj, freePoints, histoVol): # print jtrans, rotMatj cent2T = self.transformPoints(jtrans, rotMatj, self.positions[-1]) jx, jy, jz = self.jitterMax jitter = self.getMaxJitter(histoVol.smallestProteinSize) if len(cent2T) == 1: cent2T = cent2T[0] tx, ty, tz = cent2T dx = ( jx * jitter * gauss(0.0, 0.3) ) # This is an incorrect jitter use the uniform random with sphereical rejection dy = jy * jitter * gauss(0.0, 0.3) dz = jz * jitter * gauss(0.0, 0.3) nexPt = (tx + dx, ty + dy, tz + dz) # where is this point in the grid # ptInd = histoVol.grid.getPointFrom3D(nexPt) t, r = self.oneJitter(histoVol.smallestProteinSize, cent2T, rotMatj) dist, ptInd = histoVol.grid.getClosestGridPoint(t) dv = numpy.array(nexPt) - numpy.array(cent2T) d = numpy.sum(dv * dv) return ptInd, dv, sqrt(d) def getJtransRot_r(self, pt1, pt2, length=None): if length is None: length = self.uLength v = numpy.array(pt2) - numpy.array(pt1) pmx = rotVectToVect(numpy.array(self.orientation) * length, v, i=None) return ( numpy.array(pmx), numpy.array(pt1) + numpy.array(v) / 2.0, ) # .transpose()jtrans def getJtransRot(self, pt1, pt2): v, d = self.vi.measure_distance(pt1, pt2, vec=True) length, mat = autopack.helper.getTubePropertiesMatrix(pt1, pt2) return ( numpy.array(mat), numpy.array(pt1) + numpy.array(v) / 2.0, ) # .transpose()jtrans # Start jtrans section that is new since Sept 8, 2011 version n = numpy.array(pt1) - numpy.array(pt2) # normalize the vector n nn = self.vi.unit_vector(n) # why normalize ? # get axis of rotation between the plane normal and Z v1 = nn v2 = numpy.array([0.0, 0.0, 1.0]) # self.orientation) #[0.,0.,1.0] cr = numpy.cross(v1, v2) axis = self.vi.unit_vector(cr) # get the angle between the plane normal and Z angle = self.vi.angle_between_vectors(v2, v1) # get the rotation matrix between plane normal and Z mx = self.vi.rotation_matrix(-angle, axis) # .transpose()-angle ? # End jtrans section that is new since Sept 8, 2011 version matrix = mx.transpose() # self.vi.ToMat(mx).transpose()#Why ToMat here ? rotMatj = matrix.reshape((4, 4)) return ( rotMatj.transpose(), numpy.array(pt1) + numpy.array(v) / 2.0, ) # .transpose()jtrans def walkLatticeSurface( self, pts, distance, histoVol, size, mask, marge=999.0, checkcollision=True, saw=True, ): cx, cy, cz = posc = pts step = histoVol.grid.gridSpacing * size bb = ([cx - step, cy - step, cz - step], [cx + step, cy + step, cz + step]) pointsInCube = histoVol.grid.getPointsInCube(bb, posc, step, addSP=False) o = self.env.compartments[abs(self.compNum) - 1] sfpts = o.surfacePointsCoords found = False attempted = 0 safetycutoff = 200 if self.runTimeDisplay: name = "walking" + self.name sp = self.vi.getObject(name) if sp is None: sp = self.vi.Sphere(name, radius=10.0)[0] self.vi.update() while not found: if attempted > safetycutoff: return None, False newPtId = int(random() * len(sfpts)) v = sfpts[newPtId] # histoVol.grid.masterGridPositions[newPtId] if self.runTimeDisplay: self.vi.setTranslation(sp, self.vi.FromVec(v)) self.vi.update() if saw: # check if already taken, but didnt prevent cross if pointsInCube[newPtId] in self.Ptis: attempted += 1 continue cx, cy, cz = posc = pts angle = self.vi.angle_between_vectors(numpy.array(posc), numpy.array(v)) v, d = self.vi.measure_distance(numpy.array(posc), numpy.array(v), vec=True) if abs(math.degrees(angle)) <= marge: closeS = self.checkPointSurface(v, cutoff=self.cutoff_surface) inComp = self.checkPointComp(v) if closeS or not inComp: # or d > self.uLength: attempted += 1 continue if checkcollision: m = numpy.identity(4) collision = self.checkSphCollisions( [v], [float(self.uLength) * 1.0], [0.0, 0.0, 0.0], m, 0, histoVol.grid.masterGridPositions, distance, histoVol, ) if not collision: found = True self.Ptis.append(pointsInCube[newPtId]) return v, True else: # increment the range if not self.constraintMarge: if marge >= 180: return None, False marge += 1 attempted += 1 continue found = True self.Ptis.append(pointsInCube[newPtId]) return v, True else: attempted += 1 continue def walkLattice( self, pts, distance, histoVol, size, marge=999.0, checkcollision=True, saw=True ): # take the next random point in the windows size +1 +2 # extended = histoVol.getPointsInCube() cx, cy, cz = posc = pts # histoVol.grid.masterGridPositions[ptId] step = histoVol.grid.gridSpacing * size bb = ([cx - step, cy - step, cz - step], [cx + step, cy + step, cz + step]) if self.runTimeDisplay > 1: box = self.vi.getObject("collBox") if box is None: box = self.vi.Box("collBox", cornerPoints=bb, visible=1) else: # self.vi.toggleDisplay(box,True) self.vi.updateBox(box, cornerPoints=bb) self.vi.update() pointsInCube = histoVol.grid.getPointsInCube(bb, posc, step, addSP=False) pointsInCubeCoords = numpy.take( histoVol.grid.masterGridPositions, pointsInCube, 0 ) # take a random point from it OR use gradient info OR constrain by angle found = False attempted = 0 safetycutoff = 200 if self.runTimeDisplay: name = "walking" + self.name sp = self.vi.getObject(name) if sp is None: sp = self.vi.Sphere(name, radius=10.0)[0] namep = "latticePoints" pts = self.vi.getObject(namep) if pts is None: pts = self.vi.Points(namep) pts.Set(vertices=pointsInCubeCoords) # sp.SetAbsPos(self.vi.FromVec(startingPoint)) self.vi.update() while not found: if attempted > safetycutoff: return None, False newPtId = int(random() * len(pointsInCube)) v = pointsInCubeCoords[ newPtId ] # histoVol.grid.masterGridPositions[newPtId] if self.runTimeDisplay: self.vi.setTranslation(sp, self.vi.FromVec(v)) self.vi.update() if saw: # check if already taken, but didnt prevent cross if pointsInCube[newPtId] in self.Ptis: attempted += 1 continue angle = self.vi.angle_between_vectors(numpy.array(posc), numpy.array(v)) v, d = self.vi.measure_distance(numpy.array(posc), numpy.array(v), vec=True) if abs(math.degrees(angle)) <= marge: closeS = self.checkPointSurface(v, cutoff=self.cutoff_surface) inComp = self.checkPointComp(v) if closeS or not inComp: # or d > self.uLength: attempted += 1 continue if checkcollision: m = numpy.identity(4) collision = self.collision_jitter( [v], [float(self.uLength) * 1.0], [0.0, 0.0, 0.0], m, 0, histoVol.grid.masterGridPositions, distance, histoVol, ) if not collision: found = True self.Ptis.append(pointsInCube[newPtId]) return v, True else: # increment the range if not self.constraintMarge: if marge >= 180: return None, False marge += 1 attempted += 1 continue found = True self.Ptis.append(pointsInCube[newPtId]) return v, True else: attempted += 1 continue def walkSphere(self, pt1, pt2, distance, histoVol, marge=90.0, checkcollision=True): """use a random point on a sphere of radius uLength, and useCylinder collision on the grid""" v, d = self.vi.measure_distance(pt1, pt2, vec=True) found = False attempted = 0 pt = [0.0, 0.0, 0.0] angle = 0.0 safetycutoff = 10000 if self.constraintMarge: safetycutoff = 200 if self.runTimeDisplay: name = "walking" + self.name sp = self.vi.getObject(name) if sp is None: sp = self.vi.Sphere(name, radius=2.0)[0] # sp.SetAbsPos(self.vi.FromVec(startingPoint)) self.vi.update() while not found: # main loop thattryto found the next point (similar to jitter) if attempted >= safetycutoff: return None, False # numpy.array(pt2).flatten()+numpy.array(pt),False print("length is ", self.uLength) pt = self.vi.randpoint_onsphere( self.uLength ) # *numpy.array(self.jitterMax) # the new position is the previous point (pt2) plus the random point newPt = numpy.array(pt2).flatten() + numpy.array(pt) if self.runTimeDisplay >= 2: self.vi.setTranslation(sp, newPt) self.vi.update() # compute the angle between the previous direction (pt1->pt2) and the new random one (pt) angle = self.vi.angle_between_vectors(numpy.array(v), numpy.array(pt)) # first test angle less than the constraint angle if abs(math.degrees(angle)) <= marge: # check if in bounding box inside = histoVol.grid.checkPointInside( newPt, dist=self.cutoff_boundary, jitter=self.jitterMax ) closeS = self.checkPointSurface(newPt, cutoff=self.cutoff_surface) inComp = self.checkPointComp(newPt) if not inside or closeS or not inComp: if not self.constraintMarge: if marge >= 175: return None, False marge += 1 else: attempted += 1 continue # optionally check for collision if checkcollision: if self.modelType == "Cylinders": # outise is consider as collision...? # rotMatj,jtrans=self.getJtransRot(numpy.array(pt2).flatten(),newPt) m = [ [1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 1.0], ] # collision = self.checkSphCollisions([newPt,],[float(self.uLength)*1.,], # [0.,0.,0.], m, 0, # histoVol.grid.masterGridPositions, # distance, # histoVol) # use panda ? collision = self.checkCylCollisions( [numpy.array(pt2).flatten()], [newPt], self.radii[-1], [0.0, 0.0, 0.0], m, histoVol.grid.masterGridPositions, distance, histoVol, ) if not collision: found = True return numpy.array(pt2).flatten() + numpy.array(pt), True else: # increment the range if not self.constraintMarge: if marge >= 180: return None, False marge += 1 else: attempted += 1 continue else: found = True return numpy.array(pt2).flatten() + numpy.array(pt), True # attempted += 1 else: attempted += 1 continue attempted += 1 return numpy.array(pt2).flatten() + numpy.array(pt), True def getInterpolatedSphere(self, pt1, pt2): v, d = self.vi.measure_distance(pt1, pt2, vec=True) # d=self.uLength sps = numpy.arange(0, d, self.minRadius * 2) r = [] p = [] pt1 = numpy.array(pt1) pt2 = numpy.array(pt2) vn = numpy.array(v) / numpy.linalg.norm(numpy.array(v)) # normalized p.append(pt1) r.append(self.minRadius) for i, sp in enumerate(sps[1:]): r.append(self.minRadius) p.append(pt1 + (vn * sp)) p.append(pt2) r.append(self.minRadius) return [r, p] def addRBsegment(self, pt1, pt2, nodeid=""): # build a rigid body of multisphere along pt1topt2 r, p = self.getInterpolatedSphere(pt1, pt2) print("pos len", len(p), " ", len(r)) inodenp = self.add_rb_multi_sphere() print("node build ", inodenp) inodenp.setCollideMask(self.env.BitMask32.allOn()) inodenp.node().setAngularDamping(1.0) inodenp.node().setLinearDamping(1.0) print("attach node to world") # inodenp.setMat(pmat) self.env.world.attachRigidBody(inodenp.node()) print("node attached to world") inodenp = inodenp.node() print("add msphere ", inodenp) self.env.rb_panda.append(inodenp) return inodenp def walkSpherePanda( self, pt1, pt2, distance, histoVol, marge=90.0, checkcollision=True, usePP=False ): """use a random point on a sphere of radius uLength, and useCylinder collision on the grid""" v, d = self.vi.measure_distance(pt1, pt2, vec=True) found = False attempted = 0 pt = [0.0, 0.0, 0.0] safetycutoff = self.rejectionThreshold if self.constraintMarge: safetycutoff = self.rejectionThreshold if self.runTimeDisplay: name = "walking" + self.name sp = self.vi.getObject(name) if sp is None: sp = self.vi.Sphere(name, radius=2.0)[0] # sp.SetAbsPos(self.vi.FromVec(startingPoint)) self.vi.update() liste_nodes = [] cutoff = self.env.largestProteinSize + self.uLength closesbody_indice = self.getClosestIngredient(pt2, self.env, cutoff=cutoff) liste_nodes = self.get_rbNodes( closesbody_indice, pt2, prevpoint=pt1, getInfo=True ) alternate, ia = self.pick_alternate() print("pick alternate", alternate, ia, self.prev_alt) if self.prev_was_alternate: alternate = None p_alternate = None # self.partners[alternate]#self.env.getIngrFromNameInRecipe(alternate,self.recipe ) # if p_alternate.getProperties("bend"): nextPoint = None # p_alternate.getProperties("pt2") marge_in = None # p_alternate.getProperties("marge_in") dihedral = None # p_alternate.getProperties("diehdral")#for next point length = None # p_alternate.getProperties("length")#for next point # prepare halton if needed newPt = None newPts = [] if self.prev_alt is not None: # and self.prev_alt_pt is not None: p_alternate = self.partners[self.prev_alt] dihedral = p_alternate.getProperties("diehdral") nextPoint = p_alternate.getProperties("pt2") # v3=numpy.array(p_alternate.getProperties("pt4"))-numpy.array(p_alternate.getProperties("pt3")) marge_out = p_alternate.getProperties("marge_out") # marge out ? if dihedral is not None: self.mask_sphere_points( v, pt1, marge_out, liste_nodes, 0, pv=self.prev_vec, marge_diedral=dihedral, v3=self.prev_v3, ) alternate = None if self.prev_alt is not None: point_is_not_available = True elif alternate and not self.prev_was_alternate: # next point shouldnt be an alternate p_alternate = self.partners[ alternate ] # self.env.getIngrFromNameInRecipe(alternate,self.recipe ) # if p_alternate.getProperties("bend"): entrypoint = p_alternate.getProperties("pt1") nextPoint = p_alternate.getProperties("pt2") marge_in = p_alternate.getProperties("marge_in") dihedral = p_alternate.getProperties("diehdral") # for next point length = p_alternate.getProperties("length") # for next point if entrypoint is not None: self.mask_sphere_points( v, pt2, marge_in, liste_nodes, 0, pv=None, marge_diedral=None, alternate=alternate, ) elif marge_in is not None: self.mask_sphere_points( v, pt2, marge_in, liste_nodes, 0, pv=None, marge_diedral=None ) else: self.mask_sphere_points(v, pt2, marge + 2.0, liste_nodes, 0) self.prev_was_alternate = True elif self.useHalton: self.mask_sphere_points(v, pt2, marge + 2.0, liste_nodes, 0) if histoVol.runTimeDisplay: points_mask = numpy.nonzero(self.sphere_points_mask)[0] verts = self.sphere_points[points_mask] * self.uLength + pt2 name = "Hcloud" + self.name pc = self.vi.getObject(name) if pc is None: pc = self.vi.PointCloudObject(name, vertices=verts)[0] else: self.vi.updateMesh(pc, vertices=verts) self.vi.update() while not found: print("attempt ", attempted, marge) # main loop thattryto found the next point (similar to jitter) if attempted >= safetycutoff: print("break too much attempt ", attempted, safetycutoff) return None, False # numpy.array(pt2).flatten()+numpy.array(pt),False # pt = numpy.array(self.vi.randpoint_onsphere(self.uLength,biased=(uniform(0.,1.0)*marge)/360.0))*numpy.array([1,1,0]) point_is_not_available = True newPt = None if self.prev_alt is not None: if dihedral is not None: newPt = self.pickAlternateHalton(pt1, pt2, None) elif nextPoint is not None: newPt = self.prev_alt_pt if newPt is None: print( "no sphere points available with prev_alt", dihedral, nextPoint ) self.prev_alt = None return None, False attempted += 1 # ? continue elif alternate: if marge_in is not None: newPt = self.pickAlternateHalton(pt1, pt2, length) if newPt is None: print("no sphere points available with marge_in") return None, False jtrans, rotMatj = self.get_alternate_position( alternate, ia, v, pt2, newPt ) elif nextPoint is not None: newPts, jtrans, rotMatj = self.place_alternate( alternate, ia, v, pt1, pt2 ) # found = self.check_alternate_collision(pt2,newPts,jtrans,rotMatj) newPt = newPts[0] # attempted should be to safetycutoff attempted = safetycutoff if newPt is None: print("no points available place_alternate") return None, False else: # no constraint we just place alternate relatively to the given halton new points newPt = self.pickAlternateHalton(pt1, pt2, length) if newPt is None: print("no sphere points available with marge_in") return None, False jtrans, rotMatj = self.get_alternate_position( alternate, ia, v, pt2, newPt ) elif self.useHalton: newPt = self.pickHalton(pt1, pt2) if newPt is None: print("no sphere points available with marge_in") return None, False else: newPt = self.pickRandomSphere(pt1, pt2, marge, v) if histoVol.runTimeDisplay: self.vi.setTranslation(sp, newPt) self.vi.update() print("picked point", newPt) if newPt is None: print("no points available") return None, False r = [False] point_is_not_available = self.point_is_not_available(newPt) print( "point is available", point_is_not_available, self.constraintMarge, marge, attempted, self.rejectionThreshold, ) if point_is_not_available: if not self.constraintMarge: if marge >= 175: attempted += 1 continue if attempted % (self.rejectionThreshold / 3) == 0 and not alternate: marge += 1 attempted = 0 # need to recompute the mask if not alternate and self.useHalton and self.prev_alt is None: self.sphere_points_mask = numpy.ones( self.sphere_points_nb, "i" ) self.mask_sphere_points(v, pt2, marge + 2.0, liste_nodes, 0) if histoVol.runTimeDisplay: points_mask = numpy.nonzero(self.sphere_points_mask)[0] verts = ( self.sphere_points[points_mask] * self.uLength + pt2 ) name = "Hcloud" + self.name pc = self.vi.getObject(name) if pc is None: pc = self.vi.PointCloudObject(name, vertices=verts)[ 0 ] else: self.vi.updateMesh(pc, vertices=verts) self.vi.update() attempted += 1 print("rejected boundary") continue if checkcollision: collision = False cutoff = histoVol.largestProteinSize + self.uLength if not alternate: prev = None if len(histoVol.rTrans) > 2: prev = histoVol.rTrans[-1] a = numpy.array(newPt) - numpy.array(pt2).flatten() numpy.array(pt2).flatten() + a # this s where we use panda rotMatj = [ [1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 1.0], ] jtrans = [0.0, 0.0, 0.0] # move it or generate it inplace # oldpos1=self.positions # oldpos2=self.positions2 # self.positions=[[numpy.array(pt2).flatten()],] # self.positions2=[[newPt],] # if self.use_rbsphere : # rbnode = self.addRBsegment(numpy.array(pt2).flatten(),newPt) # else : # rbnode = histoVol.callFunction(histoVol.addRB,(self, numpy.array(jtrans), numpy.array(rotMatj),),{"rtype":self.Type},)#cylinder # #histoVol.callFunction(histoVol.moveRBnode,(rbnode, jtrans, rotMatj,)) # if inside organelle check for collision with it ? # self.positions=oldpos1 # self.positions2=oldpos2 rotMatj, jtrans = self.getJtransRot( numpy.array(pt2).flatten(), newPt ) rbnode = self.get_rb_model() self.env.callFunction( self.env.moveRBnode, ( rbnode, jtrans, rotMatj, ), ) if len(self.env.rTrans) == 0: r = [False] else: prev = None if len(self.env.rTrans) > 2: prev = self.env.rTrans[-1] closesbody_indice = self.getClosestIngredient( newPt, histoVol, cutoff=cutoff ) # vself.radii[0][0]*2.0 if len(closesbody_indice) == 0: print("No CloseBody") r = [False] # closesbody_indice[0] == -1 else: print("collision get RB ", len(closesbody_indice)) liste_nodes = self.get_rbNodes( closesbody_indice, jtrans, prevpoint=prev, getInfo=True ) if usePP: # use self.grab_cb and self.pp_server # Divide the task or just submit job n = 0 self.env.grab_cb.reset() for i in range(len(liste_nodes) / autopack.ncpus): for c in range(autopack.ncpus): self.env.pp_server.submit( self.env.world.contactTestPair, (rbnode, liste_nodes[n][0]), callback=self.env.grab_cb.grab, ) n += 1 self.env.pp_server.wait() r.extend(self.env.grab_cb.collision[:]) if True in r: break else: for node in liste_nodes: self.env.moveRBnode(node[0], node[1], node[2]) col = ( self.env.world.contactTestPair( rbnode, node[0] ).getNumContacts() > 0 ) print("collision? ", col) r = [col] if col: break collision = True in r if not collision: self.alternate_interval += 1 if self.alternate_interval >= self.mini_interval: self.prev_was_alternate = False self.prev_alt = None self.prev_vec = None self.update_data_tree( numpy.array(pt2).flatten(), rotMatj, pt1=pt2, pt2=newPt ) # jtrans # histoVol.callFunction(histoVol.delRB,(rbnode,)) return newPt, True else: print("alternate collision") rotMatj1, jtrans1 = self.getJtransRot_r( numpy.array(pt2).flatten(), newPt ) # collision,liste_nodes = self.collision_rapid(jtrans1,rotMatj1,cutoff=cutoff,usePP=usePP,point=newPt) # the collision shouldnt look for previous cylinder collision_alternate, liste_nodes = self.partners[ alternate ].ingr.pandaBullet_collision(jtrans, rotMatj, None, getnodes=True) collision = ( collision_alternate # (collision or collision_alternate) ) if not collision: # what about point in curve and result # self.update_data_tree(jtrans1,rotMatj1,pt1=pt2,pt2=newPt) # self.update_data_tree(jtrans1,rotMatj1,pt1=newPt,pt2=newPts[1]) self.partners[alternate].ingr.update_data_tree(jtrans, rotMatj) self.compartment.molecules.append( [jtrans, rotMatj, self.partners[alternate].ingr, 0] ) # transpose ? newv, d1 = self.vi.measure_distance(pt2, newPt, vec=True) # v,d2 = self.vi.measure_distance(newPt,newPts[1],vec=True) # self.currentLength += d1 if dihedral is not None: self.prev_alt = alternate self.prev_v3 = self.getV3( numpy.array(pt2).flatten(), newPt, alternate ) self.prev_vec = v if nextPoint is not None and dihedral is None: self.prev_alt_pt = newPts[1] # treat special case of starting other ingr start_ingr_name = self.partners[alternate].getProperties( "st_ingr" ) if start_ingr_name is not None: # add new starting positions start_ingr = self.env.getIngrFromName(start_ingr_name) matrice = numpy.array(rotMatj) # .transpose() matrice[3, :3] = jtrans newPts = self.get_alternate_starting_point( numpy.array(pt2).flatten(), newPt, alternate ) start_ingr.start_positions.append([newPts[0], newPts[1]]) start_ingr.nbMol += 1 # add a mol # we need to store self.alternate_interval = 0 return newPt, True else: self.prev_alt_pt = None # print (" collide ?",collision) if collision: # increment the range if alternate: attempted = safetycutoff elif not self.constraintMarge: if marge >= 180: # pi attempted += 1 continue if ( attempted % (self.rejectionThreshold / 3) == 0 and not alternate ): marge += 1 attempted = 0 # need to recompute the mask if ( not alternate and self.useHalton and self.prev_alt is None ): self.sphere_points_mask = numpy.ones( self.sphere_points_nb, "i" ) self.mask_sphere_points( v, pt2, marge + 2.0, liste_nodes, 0 ) if self.runTimeDisplay: points_mask = numpy.nonzero( self.sphere_points_mask )[0] v = ( self.sphere_points[points_mask] * self.uLength + pt2 ) name = "Hcloud" + self.name sp = self.vi.getObject(name) if sp is None: pc = self.vi.PointCloudObject( "bbpoint", vertices=v )[0] else: self.vi.updateMesh(pc, vertices=v) self.vi.update() else: attempted += 1 else: attempted += 1 print("rejected collision") continue else: found = True # histoVol.callFunction(histoVol.delRB,(rbnode,)) return numpy.array(pt2).flatten() + numpy.array(pt), True print("end loop add attempt ", attempted) attempted += 1 # histoVol.callFunction(histoVol.delRB,(rbnode,)) return numpy.array(pt2).flatten() + numpy.array(pt), True def walkSpherePandaOLD( self, pt1, pt2, distance, histoVol, marge=90.0, checkcollision=True, usePP=False ): """use a random point on a sphere of radius uLength, and useCylinder collision on the grid""" v, d = self.vi.measure_distance(pt1, pt2, vec=True) found = False attempted = 0 pt = [0.0, 0.0, 0.0] angle = 0.0 safetycutoff = 1000 if self.constraintMarge: safetycutoff = 200 if self.runTimeDisplay: name = "walking" + self.name sp = self.vi.getObject(name) if sp is None: sp = self.vi.Sphere(name, radius=2.0)[0] # sp.SetAbsPos(self.vi.FromVec(startingPoint)) self.vi.update() liste_nodes = [] while not found: print("attempt ", attempted, marge) # main loop thattryto found the next point (similar to jitter) if attempted >= safetycutoff: print("break too much attempt ", attempted, safetycutoff) return None, False # numpy.array(pt2).flatten()+numpy.array(pt),False # pt = numpy.array(self.vi.randpoint_onsphere(self.uLength,biased=(uniform(0.,1.0)*marge)/360.0))*numpy.array([1,1,0]) test = False if self.useHalton: self.mask_sphere_points(v, pt2, marge + 2.0, liste_nodes, 0) p = self.getNextPoint() if p is None: print("no sphere points available") return ( None, False, ) # numpy.array(pt2).flatten()+numpy.array(pt),False p = numpy.array(p) * self.uLength pt = numpy.array(p) * numpy.array(self.jitterMax) # ? newPt = numpy.array(pt2).flatten() + numpy.array(pt) if self.runTimeDisplay >= 2: self.vi.setTranslation(sp, newPt) self.vi.update() test = True else: p = self.vi.advance_randpoint_onsphere( self.uLength, marge=math.radians(marge), vector=v ) pt = numpy.array(p) * numpy.array(self.jitterMax) # ? # the new position is the previous point (pt2) plus the random point newPt = numpy.array(pt2).flatten() + numpy.array(pt) if self.runTimeDisplay >= 2: self.vi.setTranslation(sp, newPt) self.vi.update() # compute the angle between the previous direction (pt1->pt2) and the new random one (pt) angle = self.vi.angle_between_vectors(numpy.array(v), numpy.array(pt)) test = abs(math.degrees(angle)) <= marge + 2.0 if test: r = [False] # check if in bounding box inComp = True closeS = False inside = histoVol.grid.checkPointInside( newPt, dist=self.cutoff_boundary, jitter=self.jitterMax ) if inside: inComp = self.checkPointComp(newPt) if inComp: # check how far from surface ? closeS = self.checkPointSurface( newPt, cutoff=self.cutoff_surface ) if not inside or closeS or not inComp: print( "inside,closeS ", not inside, closeS, not inComp, newPt, marge ) if not self.constraintMarge: if marge >= 175: print("no second point not constraintMarge 1 ", marge) return None, False marge += 1 else: print("inside,closeS ", inside, closeS, inComp, newPt, marge) attempted += 1 continue # optionally check for collision if checkcollision: # this s where we use panda rotMatj = [ [1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 1.0], ] jtrans = [0.0, 0.0, 0.0] # move it or generate it inplace oldpos1 = self.positions oldpos2 = self.positions2 self.positions = [ [numpy.array(pt2).flatten()], ] self.positions2 = [ [newPt], ] if self.use_rbsphere: print("new RB ") rbnode = self.addRBsegment(numpy.array(pt2).flatten(), newPt) else: rbnode = histoVol.callFunction( histoVol.addRB, ( self, numpy.array(jtrans), numpy.array(rotMatj), ), {"rtype": self.Type}, ) # cylinder # histoVol.callFunction(histoVol.moveRBnode,(rbnode, jtrans, rotMatj,)) # if inside organelle check for collision with it ? self.positions = oldpos1 self.positions2 = oldpos2 # check collision using bullet # get closest object? cutoff = histoVol.largestProteinSize + self.uLength if len(self.env.rTrans) == 0: r = [False] else: prev = None if len(self.env.rTrans) > 2: prev = self.env.rTrans[-1] closesbody_indice = self.getClosestIngredient( newPt, histoVol, cutoff=cutoff ) # vself.radii[0][0]*2.0 if len(closesbody_indice) == 0: r = [False] # closesbody_indice[0] == -1 else: liste_nodes = self.get_rbNodes( closesbody_indice, jtrans, prevpoint=prev, getInfo=True ) if usePP: # use self.grab_cb and self.pp_server # Divide the task or just submit job n = 0 self.env.grab_cb.reset() for i in range(len(liste_nodes) / autopack.ncpus): for c in range(autopack.ncpus): self.env.pp_server.submit( self.env.world.contactTestPair, (rbnode, liste_nodes[n][0]), callback=self.env.grab_cb.grab, ) n += 1 self.env.pp_server.wait() r.extend(self.env.grab_cb.collision[:]) if True in r: break else: for node in liste_nodes: col = ( self.env.world.contactTestPair( rbnode, node[0] ).getNumContacts() > 0 ) r = [col] if col: break collision = True in r if not collision: histoVol.static.append(rbnode) histoVol.moving = None found = True histoVol.nb_ingredient += 1 histoVol.rTrans.append(numpy.array(pt2).flatten()) histoVol.rRot.append(numpy.array(rotMatj)) # rotMatj r histoVol.rIngr.append(self) histoVol.result.append( [[numpy.array(pt2).flatten(), newPt], rotMatj, self, 0] ) histoVol.callFunction(histoVol.delRB, (rbnode,)) # histoVol.close_ingr_bhtree.InsertRBHPoint((jtrans[0],jtrans[1],jtrans[2]),radius,None,histoVol.nb_ingredient) if histoVol.treemode == "bhtree": # "cKDTree" # if len(histoVol.rTrans) > 1 : bhtreelib.freeBHtree(histoVol.close_ingr_bhtree) histoVol.close_ingr_bhtree = bhtreelib.BHtree( histoVol.rTrans, None, 10 ) else: # rebuild kdtree if len(self.env.rTrans) > 1: histoVol.close_ingr_bhtree = spatial.cKDTree( histoVol.rTrans, leafsize=10 ) return numpy.array(pt2).flatten() + numpy.array(pt), True else: # increment the range if not self.constraintMarge: if marge >= 180: # pi return None, False marge += 1 else: attempted += 1 continue else: found = True histoVol.callFunction(histoVol.delRB, (rbnode,)) return numpy.array(pt2).flatten() + numpy.array(pt), True else: print("not in the marge ", abs(math.degrees(angle)), marge) attempted += 1 continue attempted += 1 histoVol.callFunction(histoVol.delRB, (rbnode,)) return numpy.array(pt2).flatten() + numpy.array(pt), True def walkSphereRAPIDold( self, pt1, pt2, distance, histoVol, marge=90.0, checkcollision=True, usePP=False ): """use a random point on a sphere of radius uLength, and useCylinder collision on the grid""" v, d = self.vi.measure_distance(pt1, pt2, vec=True) found = False attempted = 0 pt = [0.0, 0.0, 0.0] angle = 0.0 safetycutoff = 50 if self.constraintMarge: safetycutoff = 50 if self.runTimeDisplay: name = "walking" + self.name sp = self.vi.getObject(name) if sp is None: sp = self.vi.Sphere(name, radius=2.0)[0] self.vi.update() # do we use the cylindr or the alternate / partner liste_nodes = [] cutoff = self.env.largestProteinSize + self.uLength closesbody_indice = self.getClosestIngredient(pt2, self.env, cutoff=cutoff) liste_nodes = self.get_rapid_nodes(closesbody_indice, pt2, prevpoint=pt1) # mask using boundary and ingredient # self.mask_sphere_points_boundary(pt2) # self.mask_sphere_points_ingredients(pt2,liste_nodes) # mask_sphere_points_start = self.sphere_points_mask[:] while not found: self.sphere_points_mask = numpy.ones( 10000, "i" ) # mask_sphere_points_start[:] dihedral = None nextPoint = None # liste_nodes=[] print("attempt ", attempted, marge) # main loop thattryto found the next point (similar to jitter) if attempted >= safetycutoff: print("break too much attempt ", attempted, safetycutoff) return None, False # numpy.array(pt2).flatten()+numpy.array(pt),False # pt = numpy.array(self.vi.randpoint_onsphere(self.uLength,biased=(uniform(0.,1.0)*marge)/360.0))*numpy.array([1,1,0]) test = False newPt = None alternate, ia = self.pick_alternate() print("pick alternate", alternate, ia, self.prev_alt) # thats the ame of the ingedient used as alternate if self.prev_alt is not None: # and self.prev_alt_pt is not None: newPt = self.prev_alt_pt test = True if self.prev_alt_pt is not None: self.prev_alt_pt = None alternate = None t1 = time() if newPt is not None: test = True # elif autopack.helper.measure_distance(pt1,pt2) == 0.0: # return None,False elif alternate: p_alternate = self.partners[ alternate ] # self.env.getIngrFromNameInRecipe(alternate,self.recipe ) # if p_alternate.getProperties("bend"): nextPoint = p_alternate.getProperties("pt2") marge_in = p_alternate.getProperties("marge_in") dihedral = p_alternate.getProperties("diehdral") # for next point length = p_alternate.getProperties("length") # for next point if marge_in is not None: self.mask_sphere_points( v, pt2, marge_in, liste_nodes, 0, pv=None, marge_diedral=None ) p = self.getNextPoint() if p is None: print("no sphere points available with marge_in") # try again ? attempted += 1 continue # return None,False if length is not None: p = (p / self.uLength) * length newPt = numpy.array(pt2).flatten() + numpy.array(p) jtrans, rotMatj = self.get_alternate_position( alternate, ia, v, pt2, newPt ) else: newPts, jtrans, rotMatj = self.place_alternate( alternate, ia, v, pt1, pt2 ) # found = self.check_alternate_collision(pt2,newPts,jtrans,rotMatj) newPt = newPts[0] test = True elif self.useHalton: self.mask_sphere_points(v, pt2, marge + 2.0, liste_nodes, 0) p = self.getNextPoint() if p is None: print("no sphere points available with halton", pt2, v) marge += 1 attempted += 1 continue p = numpy.array(p) # *self.uLength pt = numpy.array(p) # *numpy.array(self.jitterMax)#? newPt = numpy.array(pt2).flatten() + numpy.array(pt) test = True else: p = self.vi.advance_randpoint_onsphere( self.uLength, marge=math.radians(marge), vector=v ) pt = numpy.array(p) * numpy.array(self.jitterMax) # the new position is the previous point (pt2) plus the random point newPt = numpy.array(pt2).flatten() + numpy.array(pt) # compute the angle between the previous direction (pt1->pt2) and the new random one (pt) angle = self.vi.angle_between_vectors(numpy.array(v), numpy.array(pt)) test = abs(math.degrees(angle)) <= marge + 2.0 if self.runTimeDisplay >= 2: self.vi.setTranslation(sp, newPt) self.vi.update() print("time to pick point ", time() - t1) if test: test = self.point_is_not_available(newPt) if test: if not self.constraintMarge: if marge >= 175: print("no second point not constraintMarge 1 ", marge) return None, False marge += 1 else: attempted += 1 print("rejected boundary") continue # optionally check for collision if checkcollision: collision = False cutoff = histoVol.largestProteinSize + self.uLength if not alternate: prev = None if len(histoVol.rTrans) > 2: prev = histoVol.rTrans[-1] # this s where we use panda rotMatj = [ [1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 1.0], ] jtrans = [0.0, 0.0, 0.0] # rbnode = self.get_rapid_model() rotMatj, jtrans = self.getJtransRot( numpy.array(pt2).flatten(), newPt ) collision, liste_nodes = self.collision_rapid( jtrans, rotMatj, cutoff=cutoff, usePP=usePP, point=newPt, prevpoint=prev, ) if not collision: self.prev_alt = None self.update_data_tree(jtrans, rotMatj, pt1=pt2, pt2=newPt) return newPt, True else: rotMatj1, jtrans1 = self.getJtransRot_r( numpy.array(pt2).flatten(), newPt ) collision, liste_nodes = self.collision_rapid( jtrans1, rotMatj1, cutoff=cutoff, usePP=usePP, point=newPt ) # the collision shouldnt look for previous cylinder collision_alternate, liste_nodes = self.partners[ alternate ].ingr.collision_rapid( jtrans, rotMatj, usePP=usePP, liste_nodes=liste_nodes ) collision = ( collision_alternate # (collision or collision_alternate) ) # print "collision",collision,collision_alternate,len(liste_nodes) if not collision: # what about point in curve and result # self.update_data_tree(jtrans1,rotMatj1,pt1=pt2,pt2=newPt) # self.update_data_tree(jtrans1,rotMatj1,pt1=newPt,pt2=newPts[1]) self.partners[alternate].ingr.update_data_tree( jtrans, rotMatj ) self.compartment.molecules.append( [ jtrans, rotMatj.transpose(), self.partners[alternate].ingr, 0, ] ) newv, d1 = self.vi.measure_distance(pt2, newPt, vec=True) # v,d2 = self.vi.measure_distance(newPt,newPts[1],vec=True) # self.currentLength += d1 self.prev_alt = alternate if dihedral is not None: self.mask_sphere_points( newv, pt2, marge_in, liste_nodes, 0, pv=v, marge_diedral=dihedral, ) p = self.getNextPoint() self.prev_alt_pt = numpy.array( newPt ).flatten() + numpy.array(pt) elif nextPoint is not None: self.prev_alt_pt = newPts[1] # treat special case of starting other ingr start_ingr_name = self.partners[alternate].getProperties( "st_ingr" ) if start_ingr_name is not None: # add new starting positions start_ingr = self.env.getIngrFromName(start_ingr_name) matrice = numpy.array(rotMatj) # .transpose() matrice[3, :3] = jtrans newPts = self.get_alternate_starting_point( matrice, alternate ) start_ingr.start_positions.append( [newPts[0], newPts[1]] ) return newPt, True else: self.prev_alt_pt = None if collision: # increment the range if not self.constraintMarge: if marge >= 180: # pi print("no second point not constraintMarge 2 ", marge) return None, False # print ("upate marge because collision ", marge) marge += 1 else: # print ("collision") attempted += 1 print("rejected collision") continue else: found = True # print ("found !") return numpy.array(pt2).flatten() + numpy.array(pt), True # attempted += 1 else: print("not in the marge ", abs(math.degrees(angle)), marge) attempted += 1 continue print("end loop add attempt ", attempted) attempted += 1 return numpy.array(pt2).flatten() + numpy.array(pt), True def pickHalton(self, pt1, pt2): p = self.getNextPoint() if p is None: return None p = numpy.array(p) # *self.uLength pt = numpy.array(p) # *numpy.array(self.jitterMax)#? return numpy.array(pt2).flatten() + numpy.array(pt) def pickRandomSphere(self, pt1, pt2, marge, v): p = self.vi.advance_randpoint_onsphere( self.uLength, marge=math.radians(marge), vector=v ) pt = numpy.array(p) * numpy.array(self.jitterMax) # the new position is the previous point (pt2) plus the random point newPt = numpy.array(pt2).flatten() + numpy.array(pt) # compute the angle between the previous direction (pt1->pt2) and the new random one (pt) # angle=self.vi.angle_between_vectors(numpy.array(v),numpy.array(pt)) # test= abs(math.degrees(angle)) <= marge+2.0 return newPt def pickAlternateHalton(self, pt1, pt2, length): p = self.getNextPoint() if p is None: return None # return None,False if length is not None: p = (p / self.uLength) * length newPt = numpy.array(pt2).flatten() + numpy.array(p) return newPt def walkSphereRAPID( self, pt1, pt2, distance, histoVol, marge=90.0, checkcollision=True, usePP=False ): """use a random point on a sphere of radius uLength, and useCylinder collision on the grid""" v, d = self.vi.measure_distance(pt1, pt2, vec=True) found = False attempted = 0 pt = [0.0, 0.0, 0.0] safetycutoff = self.rejectionThreshold # angle / 360 sp = None pc = None if self.constraintMarge: safetycutoff = self.rejectionThreshold if histoVol.runTimeDisplay: name = "walking" + self.name sp = self.vi.getObject(name) if sp is None: sp = self.vi.Sphere(name, radius=2.0)[0] # sp.SetAbsPos(self.vi.FromVec(startingPoint)) self.vi.update() # do we use the cylinder or the alternate / partner liste_nodes = [] cutoff = self.env.largestProteinSize + self.uLength closesbody_indice = self.getClosestIngredient(pt2, self.env, cutoff=cutoff) liste_nodes = self.get_rapid_nodes(closesbody_indice, pt2, prevpoint=pt1) # mask using boundary and ingredient # self.mask_sphere_points_boundary(pt2) # self.mask_sphere_points_ingredients(pt2,liste_nodes) # mask_sphere_points_start = self.sphere_points_mask[:] alternate, ia = self.pick_alternate() print("pick alternate", alternate, ia, self.prev_alt) if self.prev_was_alternate: alternate = None p_alternate = None # self.partners[alternate]#self.env.getIngrFromNameInRecipe(alternate,self.recipe ) # if p_alternate.getProperties("bend"): nextPoint = None # p_alternate.getProperties("pt2") marge_in = None # p_alternate.getProperties("marge_in") dihedral = None # p_alternate.getProperties("diehdral")#for next point length = None # p_alternate.getProperties("length")#for next point # prepare halton if needed newPt = None newPts = [] # thats the name of the ingedient used as alternate if self.prev_alt is not None: # and self.prev_alt_pt is not None: p_alternate = self.partners[self.prev_alt] dihedral = p_alternate.getProperties("diehdral") nextPoint = p_alternate.getProperties("pt2") marge_in = p_alternate.getProperties("marge_out") # marge out ? if dihedral is not None: self.mask_sphere_points( v, pt1, marge_in, liste_nodes, 0, pv=self.prev_vec, marge_diedral=dihedral, ) alternate = None if self.prev_alt is not None: point_is_not_available = True elif alternate and not self.prev_was_alternate: # next point shouldnt be an alternate p_alternate = self.partners[ alternate ] # self.env.getIngrFromNameInRecipe(alternate,self.recipe ) # if p_alternate.getProperties("bend"): nextPoint = p_alternate.getProperties("pt2") marge_in = p_alternate.getProperties("marge_in") dihedral = p_alternate.getProperties("diehdral") # for next point length = p_alternate.getProperties("length") # for next point if marge_in is not None: self.mask_sphere_points( v, pt2, marge_in, liste_nodes, 0, pv=None, marge_diedral=None ) else: self.mask_sphere_points(v, pt2, marge + 2.0, liste_nodes, 0) self.prev_was_alternate = True elif self.useHalton: self.mask_sphere_points(v, pt2, marge + 2.0, liste_nodes, 0) if histoVol.runTimeDisplay: points_mask = numpy.nonzero(self.sphere_points_mask)[0] verts = self.sphere_points[points_mask] * self.uLength + pt2 name = "Hcloud" + self.name pc = self.vi.getObject(name) if pc is None: pc = self.vi.PointCloudObject(name, vertices=verts)[0] else: self.vi.updateMesh(pc, vertices=verts) self.vi.update() while not found: # try to drop at newPoint, # self.sphere_points_mask = numpy.ones(10000,'i') #mask_sphere_points_start[:] # dihedral= None # nextPoint = None # liste_nodes=[] print("attempt ", attempted, marge) # main loop thattryto found the next point (similar to jitter) if attempted > safetycutoff: print("break too much attempt ", attempted, safetycutoff) return None, False # numpy.array(pt2).flatten()+numpy.array(pt),False # pt = numpy.array(self.vi.randpoint_onsphere(self.uLength,biased=(uniform(0.,1.0)*marge)/360.0))*numpy.array([1,1,0]) point_is_not_available = True newPt = None if self.prev_alt is not None: if dihedral is not None: newPt = self.pickAlternateHalton(pt1, pt2, None) elif nextPoint is not None: newPt = self.prev_alt_pt if newPt is None: print( "no sphere points available with prev_alt", dihedral, nextPoint ) self.prev_alt = None return None, False attempted += 1 continue elif alternate: if marge_in is not None: newPt = self.pickAlternateHalton(pt1, pt2, length) if newPt is None: print("no sphere points available with marge_in") return None, False jtrans, rotMatj = self.get_alternate_position( alternate, ia, v, pt2, newPt ) elif nextPoint is not None: newPts, jtrans, rotMatj = self.place_alternate( alternate, ia, v, pt1, pt2 ) # found = self.check_alternate_collision(pt2,newPts,jtrans,rotMatj) newPt = newPts[0] if newPt is None: print("no points available place_alternate") return None, False else: # no constraint we just place alternate relatively to the given halton new points newPt = self.pickAlternateHalton(pt1, pt2, length) if newPt is None: print("no sphere points available with marge_in") return None, False jtrans, rotMatj = self.get_alternate_position( alternate, ia, v, pt2, newPt ) elif self.useHalton: newPt = self.pickHalton(pt1, pt2) if newPt is None: print("no sphere points available with marge_in") return None, False else: newPt = self.pickRandomSphere(pt1, pt2, marge, v) if histoVol.runTimeDisplay: self.vi.setTranslation(sp, newPt) self.vi.update() print("picked point", newPt) if newPt is None: print("no points available") return None, False point_is_not_available = self.point_is_not_available(newPt) if point_is_not_available: if not self.constraintMarge: if marge >= 175: attempted += 1 continue # print ("no second point not constraintMarge 1 ", marge) # self.prev_alt = None # return None,False if attempted % (self.rejectionThreshold / 3) == 0: marge += 1 attempted = 0 # need to recompute the mask if not alternate and self.useHalton and self.prev_alt is None: self.sphere_points_mask = numpy.ones( self.sphere_points_nb, "i" ) self.mask_sphere_points(v, pt2, marge + 2.0, liste_nodes, 0) if histoVol.runTimeDisplay: points_mask = numpy.nonzero(self.sphere_points_mask)[0] verts = ( self.sphere_points[points_mask] * self.uLength + pt2 ) name = "Hcloud" + self.name pc = self.vi.getObject(name) if pc is None: pc = self.vi.PointCloudObject(name, vertices=verts)[ 0 ] else: self.vi.updateMesh(pc, vertices=verts) self.vi.update() attempted += 1 print("rejected boundary") continue # optionally check for collision if checkcollision: collision = False cutoff = histoVol.largestProteinSize + self.uLength if not alternate: prev = None if len(histoVol.rTrans) > 2: prev = histoVol.rTrans[-1] a = numpy.array(newPt) - numpy.array(pt2).flatten() numpy.array(pt2).flatten() + a # this s where we use panda rotMatj = [ [1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 1.0], ] jtrans = [0.0, 0.0, 0.0] # rbnode = self.get_rapid_model() rotMatj, jtrans = self.getJtransRot( numpy.array(pt2).flatten(), newPt ) collision, liste_nodes = self.collision_rapid( jtrans, rotMatj, cutoff=cutoff, usePP=usePP, point=newPt, prevpoint=prev, ) if not collision: self.alternate_interval += 1 if self.alternate_interval >= self.mini_interval: self.prev_was_alternate = False self.prev_alt = None self.prev_vec = None self.update_data_tree(jtrans, rotMatj, pt1=pt2, pt2=newPt) return newPt, True else: rotMatj1, jtrans1 = self.getJtransRot_r( numpy.array(pt2).flatten(), newPt ) # collision,liste_nodes = self.collision_rapid(jtrans1,rotMatj1,cutoff=cutoff,usePP=usePP,point=newPt) # the collision shouldnt look for previous cylinder collision_alternate, liste_nodes = self.partners[ alternate ].ingr.collision_rapid( jtrans, rotMatj, usePP=usePP ) # ,liste_nodes=liste_nodes) collision = ( collision_alternate # (collision or collision_alternate) ) if not collision: # what about point in curve and result # self.update_data_tree(jtrans1,rotMatj1,pt1=pt2,pt2=newPt) # self.update_data_tree(jtrans1,rotMatj1,pt1=newPt,pt2=newPts[1]) self.partners[alternate].ingr.update_data_tree(jtrans, rotMatj) self.compartment.molecules.append( [ jtrans, rotMatj.transpose(), self.partners[alternate].ingr, 0, ] ) newv, d1 = self.vi.measure_distance(pt2, newPt, vec=True) # v,d2 = self.vi.measure_distance(newPt,newPts[1],vec=True) # self.currentLength += d1 if dihedral is not None: self.prev_alt = alternate # self.prev_v3 = self.getV3 self.prev_vec = v if nextPoint is not None and dihedral is None: self.prev_alt_pt = newPts[1] # treat special case of starting other ingr start_ingr_name = self.partners[alternate].getProperties( "st_ingr" ) if start_ingr_name is not None: # add new starting positions start_ingr = self.env.getIngrFromName(start_ingr_name) matrice = numpy.array(rotMatj) # .transpose() matrice[3, :3] = jtrans snewPts = self.get_alternate_starting_point( matrice, alternate ) start_ingr.start_positions.append([snewPts[0], snewPts[1]]) start_ingr.nbMol += 1 # add a mol # we need to store self.alternate_interval = 0 return newPt, True else: self.prev_alt_pt = None if collision: # increment the range if not self.constraintMarge: if marge >= 180: # pi attempted += 1 continue if attempted % (self.rejectionThreshold / 3) == 0: marge += 1 attempted = 0 # need to recompute the mask if ( not alternate and self.useHalton and self.prev_alt is None ): self.sphere_points_mask = numpy.ones( self.sphere_points_nb, "i" ) self.mask_sphere_points( v, pt2, marge + 2.0, liste_nodes, 0 ) if self.runTimeDisplay: points_mask = numpy.nonzero( self.sphere_points_mask )[0] v = ( self.sphere_points[points_mask] * self.uLength + pt2 ) name = "Hcloud" + self.name sp = self.vi.getObject(name) if sp is None: pc = self.vi.PointCloudObject( "bbpoint", vertices=v )[0] else: self.vi.updateMesh(pc, vertices=v) self.vi.update() else: attempted += 1 else: attempted += 1 print("rejected collision") continue else: found = True return numpy.array(pt2).flatten() + numpy.array(pt), True print("end loop add attempt ", attempted) attempted += 1 return numpy.array(pt2).flatten() + numpy.array(pt), True def resetLastPoint(self, listePtCurve): self.env.nb_ingredient -= 1 self.env.rTrans.pop(len(self.env.rTrans) - 1) self.env.rRot.pop(len(self.env.rRot) - 1) # rotMatj self.env.rIngr.pop(len(self.env.rIngr) - 1) self.env.result.pop(len(self.env.result) - 1) if self.env.treemode == "bhtree": # "cKDTree" if len(self.env.rTrans) > 1: bhtreelib.freeBHtree(self.env.close_ingr_bhtree) if len(self.env.rTrans): self.env.close_ingr_bhtree = bhtreelib.BHtree(self.env.rTrans, None, 10) else: # rebuild kdtree if len(self.env.rTrans) > 1: self.env.close_ingr_bhtree = spatial.cKDTree( self.env.rTrans, leafsize=10 ) # also remove from the result ? self.results.pop(len(self.results) - 1) self.currentLength -= self.uLength # not enought the information is still here listePtCurve.pop(len(listePtCurve) - 1) def grow( self, previousPoint, startingPoint, secondPoint, listePtCurve, listePtLinear, histoVol, ptInd, freePoints, nbFreePoints, distance, dpad, stepByStep=False, r=False, usePP=False, ): # r is for reverse growing Done = False runTimeDisplay = histoVol.runTimeDisplay gridPointsCoords = histoVol.grid.masterGridPositions if runTimeDisplay: parent = histoVol.afviewer.orgaToMasterGeom[self] k = 0 success = False safetycutoff = self.safetycutoff # if self.constraintMarge: # safetycutoff = 50 counter = 0 mask = None if self.walkingMode == "lattice" and self.compNum > 0: o = self.env.compartments[abs(self.compNum) - 1] v = o.surfacePointsCoords mask = numpy.ones(len(v), int) alternate = False previousPoint_store = None while not Done: # rest the mask self.sphere_points_mask = numpy.ones(10000, "i") alternate = False print("attempt K ", k) if k > safetycutoff: print("break safetycutoff", k) return success, nbFreePoints, freePoints previousPoint_store = previousPoint previousPoint = startingPoint startingPoint = secondPoint if runTimeDisplay: # or histoVol.afviewer.doSpheres: name = str(len(listePtLinear)) + "sp" + self.name + str(ptInd) if r: name = str(len(listePtLinear) + 1) + "sp" + self.name + str(ptInd) sp = self.vi.Sphere(name, radius=self.radii[0][0], parent=parent)[0] self.vi.setTranslation(sp, pos=startingPoint) # sp.SetAbsPos(self.vi.FromVec(startingPoint)) # sp=self.vi.newInstance(name,histoVol.afviewer.pesph, # location=startingPoint,parent=parent) # self.vi.scaleObj(sp,self.radii[0][0]) self.vi.update() # pick next point and test collision. if self.walkingMode == "sphere": if self.placeType == "pandaBullet": secondPoint, success = self.walkSpherePanda( previousPoint, startingPoint, distance, histoVol, marge=self.marge, checkcollision=True, usePP=usePP, ) if secondPoint is None: return False, nbFreePoints, freePoints elif self.placeType == "RAPID": # call function t1 = time() secondPoint, success = self.walkSphereRAPID( previousPoint, startingPoint, distance, histoVol, marge=self.marge, checkcollision=True, usePP=usePP, ) print("walk rapid ", time() - t1) if secondPoint is None: return False, nbFreePoints, freePoints else: secondPoint, success = self.walkSphere( previousPoint, startingPoint, distance, histoVol, marge=self.marge, checkcollision=True, ) if self.walkingMode == "lattice" and self.compNum > 0: secondPoint, success, mask = self.walkLatticeSurface( startingPoint, distance, histoVol, 2, mask, marge=self.marge, checkcollision=False, saw=True, ) elif self.walkingMode == "lattice": secondPoint, success = self.walkLattice( startingPoint, distance, histoVol, 2, marge=self.marge, checkcollision=False, saw=True, ) if secondPoint is None or not success: # no available point? try again ? secondPoint = numpy.array(previousPoint) startingPoint = previousPoint_store k += 1 continue if len(secondPoint) == 2: alternate = True startingPoint = secondPoint[0] secondPoint = secondPoint[1] v, d = self.vi.measure_distance(startingPoint, secondPoint, vec=True) rotMatj, jtrans = self.getJtransRot(startingPoint, secondPoint) if r: # reverse mode rotMatj, jtrans = self.getJtransRot(secondPoint, startingPoint) cent1T = self.transformPoints(jtrans, rotMatj, self.positions[-1]) cent2T = self.transformPoints(jtrans, rotMatj, self.positions2[-1]) print( "here is output of walk", secondPoint, startingPoint, success, alternate, len(secondPoint), ) if success: print("success grow") # do not append if alternate was used if self.prev_alt is None: self.results.append([jtrans, rotMatj]) if r: if alternate: listePtLinear.insert(0, startingPoint) listePtLinear.insert(0, secondPoint) else: if alternate: listePtLinear.append(startingPoint) listePtLinear.append(secondPoint) self.currentLength += d if runTimeDisplay: print("cylinder with", cent1T, cent2T) name = str(len(listePtLinear)) + self.name + str(ptInd) + "cyl" if r: name = ( str(len(listePtLinear) + 1) + self.name + str(ptInd) + "cyl" ) self.vi.oneCylinder( name, cent1T, cent2T, parent=parent, instance=histoVol.afviewer.becyl, radius=self.radii[0][0], ) self.vi.update() if r: listePtCurve.insert(0, jtrans) else: listePtCurve.append(jtrans) # if success: # for jtrans,rotMatj in self.results: # every two we update distance from the previous if len(self.results) >= 1: # jtrans, rotMatj = self.results[-1] # print "trasnfor",jtrans,rotMatj # cent1T=self.transformPoints(jtrans, rotMatj, self.positions[-1]) insidePoints = {} newDistPoints = {} # rotMatj=[[ 1., 0., 0., 0.], # [ 0., 1., 0., 0.], # [ 0., 0., 1., 0.], # [ 0., 0., 0., 1.]] # jtrans = [0.,0.,0.] # #move it or generate it inplace # oldpos1=self.positions # oldpos2=self.positions2 # if len(cent1T) == 1 : # cent1T=cent1T[0] # if len(cent2T) == 1 : # cent2T=cent2T[0] # self.positions=[[cent1T],] # self.positions2=[[cent2T],] # rbnode = histoVol.callFunction(histoVol.addRB,(self, numpy.array(jtrans), numpy.array(rotMatj),),{"rtype":self.Type},)#cylinder # histoVol.callFunction(histoVol.moveRBnode,(rbnode, jtrans, rotMatj,)) insidePoints, newDistPoints = self.getInsidePoints( histoVol.grid, gridPointsCoords, dpad, distance, centT=cent1T, jtrans=jtrans, rotMatj=rotMatj, ) nbFreePoints = self.updateDistances( insidePoints, newDistPoints, freePoints, nbFreePoints, distance, ) if histoVol.afviewer is not None and hasattr(histoVol.afviewer, "vi"): histoVol.afviewer.vi.progressBar( progress=int((self.currentLength / self.length) * 100), label=self.name + str(self.currentLength / self.length) + " " + str(self.nbCurve) + "/" + str(self.nbMol), ) else: autopack.helper.progressBar( progress=int((self.currentLength / self.length) * 100), label=self.name + str(self.currentLength / self.length) + " " + str(self.nbCurve) + "/" + str(self.nbMol), ) # Start Graham on 5/16/12 This progress bar doesn't work properly... compare with my version in HistoVol if self.currentLength >= self.length: Done = True self.counter = counter + 1 else: secondPoint = startingPoint break return success, nbFreePoints, freePoints def updateGrid( self, rg, histoVol, dpad, freePoints, nbFreePoints, distance, gridPointsCoords, ): for i in range(rg): # len(self.results)): jtrans, rotMatj = self.results[-i] cent1T = self.transformPoints(jtrans, rotMatj, self.positions[-1]) insidePoints = {} newDistPoints = {} insidePoints, newDistPoints = self.getInsidePoints( histoVol.grid, gridPointsCoords, dpad, distance, centT=cent1T, jtrans=jtrans, rotMatj=rotMatj, ) # update free points nbFreePoints = self.updateDistances( insidePoints, newDistPoints, freePoints, nbFreePoints, distance ) return nbFreePoints, freePoints def getFirstPoint(self, ptInd, seed=0): if self.compNum > 0: # surfacegrowing: first point is aling to the normal: v2 = self.env.compartments[abs(self.compNum) - 1].surfacePointsNormals[ ptInd ] secondPoint = ( numpy.array(self.startingpoint) + numpy.array(v2) * self.uLength ) else: # randomize the orientation in the hemisphere following the direction. v = self.vi.rotate_about_axis( numpy.array(self.orientation), random() * math.radians(self.marge), # or marge ? axis=list(self.orientation).index(0), ) self.vector = ( numpy.array(v).flatten() * self.uLength * self.jitterMax ) # = (1,0,0)self.vector.flatten() secondPoint = self.startingpoint + self.vector # seed="F" if seed: seed = "R" secondPoint = self.startingpoint - self.vector else: seed = "F" inside = self.env.grid.checkPointInside( secondPoint, dist=self.cutoff_boundary, jitter=self.jitterMax ) closeS = False if inside and self.compNum <= 0: # only if not surface ingredient closeS = self.checkPointSurface(secondPoint, cutoff=self.cutoff_surface) if not inside or closeS: safety = 30 k = 0 while not inside or closeS: if k > safety: # print("cant find first inside point", inside, closeS) return None else: k += 1 p = self.vi.advance_randpoint_onsphere( self.uLength, marge=math.radians(self.marge), vector=self.vector ) pt = numpy.array(p) * numpy.array(self.jitterMax) secondPoint = self.startingpoint + numpy.array(pt) inside = self.env.grid.checkPointInside( secondPoint, dist=self.cutoff_boundary, jitter=self.jitterMax ) if self.compNum <= 0: closeS = self.checkPointSurface( secondPoint, cutoff=self.cutoff_surface ) if self.runTimeDisplay: parent = self.env.afviewer.orgaToMasterGeom[self] name = "Startsp" + self.name + seed # sp=self.vi.Sphere(name,radius=self.radii[0][0],parent=parent)[0] if seed == "F": # sp=self.vi.newInstance(name,self.env.afviewer.pesph, # location=self.startingpoint,parent=parent) # self.vi.scaleObj(sp,self.radii[0][0]) sp = self.vi.Sphere(name, radius=self.radii[0][0], parent=parent)[0] self.vi.setTranslation(sp, pos=self.startingpoint) # sp.SetAbsPos(self.vi.FromVec(startingPoint)) self.vi.oneCylinder( name + "cyl", self.startingpoint, secondPoint, instance=self.env.afviewer.becyl, parent=parent, radius=self.radii[0][0], ) self.vi.update() return secondPoint def add_rb_multi_sphere(self): inodenp = self.env.worldNP.attachNewNode(BulletRigidBodyNode(self.name)) inodenp.node().setMass(1.0) level = self.deepest_level centers = self.positions[level] radii = self.radii[level] for radc, posc in zip(radii, centers): shape = BulletSphereShape(radc) inodenp.node().addShape( shape, TransformState.makePos(Point3(posc[0], posc[1], posc[2])) ) # return inodenp def jitter_place( self, histoVol, ptInd, freePoints, nbFreePoints, distance, dpad, usePP=False, ): if type(self.compMask) is str: self.compMask = eval(self.compMask) self.prepare_alternates() success = True self.vi = autopack.helper self.env = histoVol gridPointsCoords = histoVol.grid.masterGridPositions self.runTimeDisplay = histoVol.runTimeDisplay normal = None # jitter the first point if self.compNum > 0: normal = histoVol.compartments[abs(self.compNum) - 1].surfacePointsNormals[ ptInd ] self.startingpoint = previousPoint = startingPoint = self.jitterPosition( numpy.array(histoVol.grid.masterGridPositions[ptInd]), histoVol.smallestProteinSize, normal=normal, ) v, u = self.vi.measure_distance(self.positions, self.positions2, vec=True) self.vector = numpy.array(self.orientation) * self.uLength if u != self.uLength: self.positions2 = [[self.vector]] if self.compNum == 0: compartment = self.env else: compartment = self.env.compartments[abs(self.compNum) - 1] self.compartment = compartment secondPoint = self.getFirstPoint(ptInd) # check collision ? # if we have starting position available use it if self.nbCurve < len(self.start_positions): self.startingpoint = previousPoint = startingPoint = self.start_positions[ self.nbCurve ][0] secondPoint = self.start_positions[self.nbCurve][1] if secondPoint is None: return success, nbFreePoints rotMatj, jtrans = self.getJtransRot(startingPoint, secondPoint) # test for collision # return success, nbFreePoints self.results.append([jtrans, rotMatj]) if self.placeType == "pandaBullet": self.env.nb_ingredient += 1 self.env.rTrans.append(numpy.array(startingPoint).flatten()) self.env.rRot.append(numpy.array(numpy.identity(4))) # rotMatj self.env.rIngr.append(self) self.env.result.append( [[numpy.array(startingPoint).flatten(), secondPoint], rotMatj, self, 0] ) # if len(self.env.rTrans) > 1 : bhtreelib.freeBHtree(self.env.close_ingr_bhtree) # if len(self.env.rTrans) : self.env.close_ingr_bhtree=bhtreelib.BHtree( self.env.rTrans, None, 10) elif self.placeType == "RAPID": self.env.nb_ingredient += 1 self.env.rTrans.append(numpy.array(jtrans).flatten()) self.env.rRot.append(numpy.array(rotMatj)) # rotMatj self.env.rIngr.append(self) self.env.result.append( [[numpy.array(startingPoint).flatten(), secondPoint], rotMatj, self, 0] ) if self.env.treemode == "bhtree": # "cKDTree" # if len(self.env.rTrans) > 1 : bhtreelib.freeBHtree(self.env.close_ingr_bhtree) if len(self.env.rTrans): self.env.close_ingr_bhtree = bhtreelib.BHtree(self.env.rTrans, None, 10) else: # rebuild kdtree if len(self.env.rTrans) > 1: self.env.close_ingr_bhtree = spatial.cKDTree( self.env.rTrans, leafsize=10 ) self.currentLength = 0.0 # self.Ptis=[ptInd,histoVol.grid.getPointFrom3D(secondPoint)] dist, pid = histoVol.grid.getClosestGridPoint(secondPoint) self.Ptis = [ptInd, pid] print("the starting point on the grid was ", startingPoint, pid, ptInd) listePtCurve = [jtrans] listePtLinear = [startingPoint, secondPoint] # grow until reach self.currentLength >= self.length # or attempt > safety success, nbFreePoints, freePoints = self.grow( previousPoint, startingPoint, secondPoint, listePtCurve, listePtLinear, histoVol, ptInd, freePoints, nbFreePoints, distance, dpad, stepByStep=False, usePP=usePP, ) nbFreePoints, freePoints = self.updateGrid( 2, histoVol, dpad, freePoints, nbFreePoints, distance, gridPointsCoords, ) if self.seedOnMinus: success, nbFreePoints, freePoints = self.grow( previousPoint, listePtLinear[1], listePtLinear[0], listePtCurve, listePtLinear, histoVol, ptInd, freePoints, nbFreePoints, distance, dpad, stepByStep=False, r=True, ) nbFreePoints, freePoints = self.updateGrid( 2, histoVol, dpad, freePoints, nbFreePoints, distance, gridPointsCoords, ) # store result in molecule self.log.info("res %d", len(self.results)) for i in range(len(self.results)): jtrans, rotMatj = self.results[-i] dist, ptInd = histoVol.grid.getClosestGridPoint(jtrans) compartment.molecules.append([jtrans, rotMatj, self, ptInd]) # reset the result ? self.results = [] # print ("After :",listePtLinear) self.listePtCurve.append(listePtCurve) self.listePtLinear.append(listePtLinear) self.nbCurve += 1 self.completion = float(self.nbCurve) / float(self.nbMol) self.log.info("completion %r %r %r", self.completion, self.nbCurve, self.nbMol) return success, nbFreePoints def prepare_alternates( self, ): if len(self.partners): self.alternates_names = ( self.partners.keys() ) # self.partners_name#[p.name for p in self.partners.values()] # self.alternates_weight = [self.partners[name].weight for name in self.partners] self.alternates_weight = [ self.partners[name].ingr.weight for name in self.partners ] self.alternates_proba = [ self.partners[name].ingr.proba_binding for name in self.partners ] def prepare_alternates_proba( self, ): thw = [] tw = 0.0 weights = self.alternates_proba # python3?#dict.copy().keys() for i, w in enumerate(weights): tw += w thw.append(tw) self.alternates_proba = thw def pick_random_alternate( self, ): if not len(self.alternates_names): return None, 0 r = uniform(0, 1.0) ar = uniform(0, 1.0) # weights = self.alternates_weight[:] proba = self.alternates_proba[:] alti = int((r * (len(self.alternates_names)))) # round? # print (alti,proba[alti],ar,self.alternates_names[alti]) if ar < proba[alti]: return self.alternates_names[alti], alti return None, 0 def pick_alternate( self, ): # whats he current length ie number of point so far # whats are he number of alternate and theyre proba # pick an alternate according length and proba # liste_proba # liste_alternate # dice = uniform(0.0,1.0) # int(uniform(0.0,1.0)*len(self.sphere_points_mask)) alt_name = None # if it is the first two segment dont do it if self.currentLength <= self.uLength * 2.0: return None, 0 # return self.pick_random_alternate() weights = self.alternates_weight # python3?#dict.copy().keys() rnd = uniform(0, 1.0) * sum(weights) # * (self.currentLength / self.length) i = 0 for i, w in enumerate(weights): rnd -= w if rnd < 0: r = uniform(0, 1.0) # print (r,self.alternates_proba[i]) if r < self.alternates_proba[i]: alt_name = self.alternates_names[i] break # alternates_names point to an ingredients id? return alt_name, i def get_alternate_position(self, alternate, alti, v, pt1, pt2): length = self.partners[alternate].getProperties("length") # rotation that align snake orientation to current segment rotMatj, jtrans = self.getJtransRot_r( numpy.array(pt1).flatten(), numpy.array(pt2).flatten(), length=length ) # jtrans is the position between pt1 and pt2 prevMat = numpy.array(rotMatj) # jtrans=autopack.helper.ApplyMatrix([jtrans],prevMat.transpose())[0] prevMat[3, :3] = numpy.array(pt1) # jtrans rotMatj = numpy.identity(4) # oldv is v we can ether align to v or newv newv = numpy.array(pt2) - numpy.array(pt1) # use v ? for additional point ? ptb = self.partners[alternate].getProperties("pt2") ptc = self.partners[alternate].getProperties("pt3") toalign = numpy.array(ptc) - numpy.array(ptb) m = numpy.array(rotVectToVect(toalign, newv)).transpose() m[3, :3] = numpy.array(pt1) # jtrans pts = autopack.helper.ApplyMatrix([ptb], m.transpose()) # transpose ? v = numpy.array(pt1) - pts[0] m[3, :3] = numpy.array(pt1) + v # - (newpt1-pts[0]) # rotMatj,jt=self.getJtransRot_r(numpy.array(ptb).flatten(), # numpy.array(ptc).flatten(), # length = length) # rotMatj[3,:3] = -numpy.array(ptb) # globalM1 = numpy.array(matrix(rotMatj)*matrix(prevMat)) # # offset = numpy.array(ptb)+toalign/2.0 # npts=numpy.array([pta,ptb,offset,ptc])-numpy.array([ptb]) # pts=autopack.helper.ApplyMatrix(npts,globalM1.transpose())#transpose ? # trans = numpy.array(jtrans)-1.5*pts[1]-pts[2] # now apply matrix and get the offset # prevMat = numpy.array(globalM1) # jtrans=autopack.helper.ApplyMatrix([jtrans],prevMat.transpose())[0] # prevMat[3,:3] = jtrans # npt2=autopack.helper.ApplyMatrix([ptb],prevMat.transpose())[0] # offset = numpy.array(npt2) -numpy.array(pt1) # jtrans=numpy.array(jtrans)-offset # toalign = numpy.array(ptb) -numpy.array(pta) # globalM2 = numpy.array(rotVectToVect(toalign,v)) # compare to superimposition_matrix # print globalM1,quaternion_from_matrix(globalM1).tolist() # print globalM2,quaternion_from_matrix(globalM2).tolist() # center them # c1=autopack.helper.getCenter([ptb,ptc]) # c2=autopack.helper.getCenter([pt1,pt2]) # globalM = superimposition_matrix(numpy.array([ptb,ptc])-c1,numpy.array([pt1,pt2])-c2) # print globalM,quaternion_from_matrix(globalM).tolist() rotMatj = numpy.identity(4) rotMatj[:3, :3] = m[:3, :3].transpose() jtrans = m[3, :3] # print ("will try to place alterate at ",jtrans) return jtrans, rotMatj def get_alternate_position_p(self, alternate, alti, v, pt1, pt2): length = self.partners[alternate].getProperties("length") rotMatj, jtrans = self.getJtransRot_r( numpy.array(pt1).flatten(), numpy.array(pt2).flatten(), length=length ) prevMat = numpy.array(rotMatj) # jtrans=autopack.helper.ApplyMatrix([jtrans],prevMat.transpose())[0] prevMat[3, :3] = jtrans rotMatj = numpy.identity(4) localMR = self.partners_position[alti] # instead use rotVectToVect from current -> to local -> # align p2->p3 vector to pt1->pt2 globalM = numpy.array(matrix(localMR) * matrix(prevMat)) jtrans = globalM[3, :3] rotMatj[:3, :3] = globalM[:3, :3] # print ("will try to place alterate at ",jtrans) return jtrans, rotMatj def getV3(self, pt1, pt2, alternate): length = self.partners[alternate].getProperties("length") rotMatj, jtrans = self.getJtransRot_r( numpy.array(pt1).flatten(), numpy.array(pt2).flatten(), length=length ) # jtrans is the position between pt1 and pt2 prevMat = numpy.array(rotMatj) prevMat[3, :3] = numpy.array(pt1) # jtrans newv = numpy.array(pt2) - numpy.array(pt1) ptb = self.partners[alternate].getProperties("pt2") ptc = self.partners[alternate].getProperties("pt3") ptd = self.partners[alternate].getProperties("pt4") toalign = numpy.array(ptc) - numpy.array(ptb) m = numpy.array(rotVectToVect(toalign, newv)).transpose() m[3, :3] = numpy.array(pt1) # jtrans pts = autopack.helper.ApplyMatrix([ptb], m.transpose()) # transpose ? v = numpy.array(pt1) - pts[0] m[3, :3] = numpy.array(pt1) + v newPts = autopack.helper.ApplyMatrix([ptc, ptd], m.transpose()) # transpose ? print("we got pt3,pt4 ", newPts) return numpy.array(newPts[1]) - numpy.array(newPts[0]) def get_alternate_starting_point(self, pt1, pt2, alternate): spt1 = self.partners[alternate].getProperties("st_pt1") spt2 = self.partners[alternate].getProperties("st_pt2") length = self.partners[alternate].getProperties("length") rotMatj, jtrans = self.getJtransRot_r( numpy.array(pt1).flatten(), numpy.array(pt2).flatten(), length=length ) # jtrans is the position between pt1 and pt2 prevMat = numpy.array(rotMatj) prevMat[3, :3] = numpy.array(pt1) # jtrans newv = numpy.array(pt2) - numpy.array(pt1) ptb = self.partners[alternate].getProperties("pt2") ptc = self.partners[alternate].getProperties("pt3") toalign = numpy.array(ptc) - numpy.array(ptb) m = numpy.array(rotVectToVect(toalign, newv)).transpose() m[3, :3] = numpy.array(pt1) # jtrans pts = autopack.helper.ApplyMatrix([ptb], m.transpose()) # transpose ? v = numpy.array(pt1) - pts[0] m[3, :3] = numpy.array(pt1) + v newPts = autopack.helper.ApplyMatrix([spt1, spt2], m.transpose()) # transpose ? return newPts def place_alternate(self, alternate, alti, v, pt1, pt2): pta = self.partners[alternate].getProperties("pt1") ptb = self.partners[alternate].getProperties("pt2") ptc = self.partners[alternate].getProperties("pt3") ptd = self.partners[alternate].getProperties("pt4") prevMat = numpy.identity(4) if ptb is not None: rotMatj, jtrans = self.getJtransRot_r( numpy.array(pt1).flatten(), numpy.array(pt2).flatten() ) toalign = numpy.array(ptb) - numpy.array(pta) newv = numpy.array(pt2) - numpy.array(pt1) prevMat = numpy.array(rotVectToVect(toalign, newv)) newPts = autopack.helper.ApplyMatrix( [ptc, ptd], prevMat.transpose() ) # partner positions ? prevMat[3, :3] = jtrans else: newPt = self.pickHalton(pt1, pt2) newPts = [newPt] rotMatj, jtrans = self.getJtransRot_r( numpy.array(pt2).flatten(), numpy.array(newPt).flatten() ) prevMat = numpy.array(rotMatj) # jtrans=autopack.helper.ApplyMatrix([jtrans],prevMat.transpose())[0] prevMat[3, :3] = jtrans rotMatj = numpy.identity(4) return newPts, jtrans, rotMatj def place_alternate_p(self, alternate, alti, v, pt1, pt2): # previou transformation # distance,mat = autopack.helper.getTubePropertiesMatrix(pt1,pt2) # prevMat = numpy.array(mat) # rotMatj,jtrans=self.getJtransRot(numpy.array(pt2).flatten(),numpy.array(pt1).flatten()) # should apply first to get the new list of point, and length p_alternate = self.partners[ alternate ] # self.env.getIngrFromNameInRecipe(alternate,self.recipe ) # if p_alternate.getProperties("bend"): out1 = p_alternate.getProperties("pt1") out2 = p_alternate.getProperties("pt2") if out1 is not None: rotMatj, jtrans = self.getJtransRot_r( numpy.array(pt1).flatten(), numpy.array(pt2).flatten() ) prevMat = numpy.array(rotMatj) # jtrans=autopack.helper.ApplyMatrix([jtrans],prevMat.transpose())[0] prevMat[3, :3] = jtrans newPts = autopack.helper.ApplyMatrix( [out1, out2], prevMat.transpose() ) # partner positions ? else: newPt = self.pickHalton(pt1, pt2) newPts = [newPt] rotMatj, jtrans = self.getJtransRot_r( numpy.array(pt2).flatten(), numpy.array(newPt).flatten() ) prevMat = numpy.array(rotMatj) # jtrans=autopack.helper.ApplyMatrix([jtrans],prevMat.transpose())[0] prevMat[3, :3] = jtrans rotMatj = numpy.identity(4) # print ("som math",out1,out2,newPts) # need also to get the alternate_ingredint new position and add it. localMR = self.partners_position[alti] globalM = numpy.array(matrix(localMR) * matrix(prevMat)) jtrans = globalM[3, :3] rotMatj[:3, :3] = globalM[:3, :3] # print ("will try to place alterate at ",jtrans) return newPts, jtrans, rotMatj # we need to add this guy a new mol and tak in account his molarity ? # should actually the partner system and the step/step class ActinIngredient(GrowIngredient): def __init__( self, molarity, radii=[[50.0]], positions=None, positions2=None, sphereFile=None, packingPriority=0, name=None, pdb=None, color=None, nbJitter=5, jitterMax=(1, 1, 1), perturbAxisAmplitude=0.1, length=10.0, closed=False, modelType="Cylinders", biased=1.0, Type="Actine", principalVector=(1, 0, 0), meshFile=None, packingMode="random", placeType="jitter", marge=35.0, influenceRad=100.0, meshObject=None, orientation=(1, 0, 0), nbMol=0, **kw ): GrowIngredient.__init__( self, molarity, radii, positions, positions2, sphereFile, packingPriority, name, pdb, color, nbJitter, jitterMax, perturbAxisAmplitude, length, closed, modelType, biased, principalVector, meshFile, packingMode, placeType, marge, meshObject, orientation, nbMol, Type, **kw ) if name is None: name = "Actine_%s_%f" % (str(radii), molarity) self.isAttractor = True self.constraintMarge = True self.seedOnMinus = True self.influenceRad = influenceRad self.oneSuperTurn = 825.545 # cm from c4d graham file self.oneDimerSize = 100.0 # 200 =2 self.cutoff_surface = 50.0 self.cutoff_boundary = 1.0 def updateFromBB(self, grid): return r = grid.getRadius() self.positions = [0.0, 0.0, 0.0] self.positions2 = [r, 0.0, 0.0] self.principalVector = [1.0, 0.0, 0.0] self.uLength = r self.length = 2 * r
[ "cellpack.autopack.helper.toggleDisplay", "numpy.sum", "panda3d.bullet.BulletRigidBodyNode", "numpy.ones", "panda3d.core.Point3", "panda3d.bullet.BulletSphereShape", "numpy.arange", "scipy.spatial.cKDTree", "random.gauss", "cellpack.autopack.helper.host.find", "numpy.copy", "math.radians", "numpy.identity", "numpy.matrix.reshape", "cellpack.autopack.helper.getTubePropertiesMatrix", "cellpack.mgl_tools.bhtree.bhtreelib.freeBHtree", "scipy.spatial.distance.cdist", "math.sqrt", "numpy.cross", "random.random", "numpy.dot", "cellpack.autopack.helper.Cylinder", "math.degrees", "numpy.greater_equal", "numpy.matrix", "cellpack.autopack.ldSequence.SphereHalton", "numpy.logical_and", "random.uniform", "cellpack.autopack.helper.newEmpty", "time.time", "numpy.nonzero", "cellpack.autopack.helper.getObject", "numpy.array", "numpy.take", "cellpack.mgl_tools.bhtree.bhtreelib.BHtree" ]
[((4183, 4200), 'numpy.identity', 'numpy.identity', (['(4)'], {}), '(4)\n', (4197, 4200), False, 'import numpy\n'), ((7186, 7224), 'numpy.ones', 'numpy.ones', (['self.sphere_points_nb', '"""i"""'], {}), "(self.sphere_points_nb, 'i')\n", (7196, 7224), False, 'import numpy\n'), ((14265, 14303), 'cellpack.autopack.ldSequence.SphereHalton', 'SphereHalton', (['self.sphere_points_nb', '(5)'], {}), '(self.sphere_points_nb, 5)\n', (14277, 14303), False, 'from cellpack.autopack.ldSequence import SphereHalton\n'), ((14338, 14376), 'numpy.ones', 'numpy.ones', (['self.sphere_points_nb', '"""i"""'], {}), "(self.sphere_points_nb, 'i')\n", (14348, 14376), False, 'import numpy\n'), ((19693, 19754), 'numpy.logical_and', 'numpy.logical_and', (['mask', 'self.sphere_points_mask[points_mask]'], {}), '(mask, self.sphere_points_mask[points_mask])\n', (19710, 19754), False, 'import numpy\n'), ((20338, 20353), 'numpy.array', 'numpy.array', (['pt'], {}), '(pt)\n', (20349, 20353), False, 'import numpy\n'), ((20867, 20928), 'numpy.logical_and', 'numpy.logical_and', (['mask', 'self.sphere_points_mask[points_mask]'], {}), '(mask, self.sphere_points_mask[points_mask])\n', (20884, 20928), False, 'import numpy\n'), ((21674, 21709), 'numpy.copy', 'numpy.copy', (['self.sphere_points_mask'], {}), '(self.sphere_points_mask)\n', (21684, 21709), False, 'import numpy\n'), ((23260, 23278), 'numpy.sum', 'numpy.sum', (['(dv * dv)'], {}), '(dv * dv)\n', (23269, 23278), False, 'import numpy\n'), ((23808, 23857), 'cellpack.autopack.helper.getTubePropertiesMatrix', 'autopack.helper.getTubePropertiesMatrix', (['pt1', 'pt2'], {}), '(pt1, pt2)\n', (23847, 23857), True, 'import cellpack.autopack as autopack\n'), ((24289, 24317), 'numpy.array', 'numpy.array', (['[0.0, 0.0, 1.0]'], {}), '([0.0, 0.0, 1.0])\n', (24300, 24317), False, 'import numpy\n'), ((24365, 24384), 'numpy.cross', 'numpy.cross', (['v1', 'v2'], {}), '(v1, v2)\n', (24376, 24384), False, 'import numpy\n'), ((24839, 24861), 'numpy.matrix.reshape', 'matrix.reshape', (['(4, 4)'], {}), '((4, 4))\n', (24853, 24861), False, 'from numpy import matrix\n'), ((28942, 29004), 'numpy.take', 'numpy.take', (['histoVol.grid.masterGridPositions', 'pointsInCube', '(0)'], {}), '(histoVol.grid.masterGridPositions, pointsInCube, 0)\n', (28952, 29004), False, 'import numpy\n'), ((36788, 36826), 'numpy.arange', 'numpy.arange', (['(0)', 'd', '(self.minRadius * 2)'], {}), '(0, d, self.minRadius * 2)\n', (36800, 36826), False, 'import numpy\n'), ((36871, 36887), 'numpy.array', 'numpy.array', (['pt1'], {}), '(pt1)\n', (36882, 36887), False, 'import numpy\n'), ((36902, 36918), 'numpy.array', 'numpy.array', (['pt2'], {}), '(pt2)\n', (36913, 36918), False, 'import numpy\n'), ((82550, 82564), 'numpy.array', 'numpy.array', (['p'], {}), '(p)\n', (82561, 82564), False, 'import numpy\n'), ((82595, 82609), 'numpy.array', 'numpy.array', (['p'], {}), '(p)\n', (82606, 82609), False, 'import numpy\n'), ((124092, 124107), 'random.uniform', 'uniform', (['(0)', '(1.0)'], {}), '(0, 1.0)\n', (124099, 124107), False, 'from random import uniform, gauss, random\n'), ((124121, 124136), 'random.uniform', 'uniform', (['(0)', '(1.0)'], {}), '(0, 1.0)\n', (124128, 124136), False, 'from random import uniform, gauss, random\n'), ((126007, 126027), 'numpy.array', 'numpy.array', (['rotMatj'], {}), '(rotMatj)\n', (126018, 126027), False, 'import numpy\n'), ((126131, 126147), 'numpy.array', 'numpy.array', (['pt1'], {}), '(pt1)\n', (126142, 126147), False, 'import numpy\n'), ((126176, 126193), 'numpy.identity', 'numpy.identity', (['(4)'], {}), '(4)\n', (126190, 126193), False, 'import numpy\n'), ((126597, 126613), 'numpy.array', 'numpy.array', (['pt1'], {}), '(pt1)\n', (126608, 126613), False, 'import numpy\n'), ((128342, 128359), 'numpy.identity', 'numpy.identity', (['(4)'], {}), '(4)\n', (128356, 128359), False, 'import numpy\n'), ((128817, 128837), 'numpy.array', 'numpy.array', (['rotMatj'], {}), '(rotMatj)\n', (128828, 128837), False, 'import numpy\n'), ((128966, 128983), 'numpy.identity', 'numpy.identity', (['(4)'], {}), '(4)\n', (128980, 128983), False, 'import numpy\n'), ((129686, 129706), 'numpy.array', 'numpy.array', (['rotMatj'], {}), '(rotMatj)\n', (129697, 129706), False, 'import numpy\n'), ((129732, 129748), 'numpy.array', 'numpy.array', (['pt1'], {}), '(pt1)\n', (129743, 129748), False, 'import numpy\n'), ((130129, 130145), 'numpy.array', 'numpy.array', (['pt1'], {}), '(pt1)\n', (130140, 130145), False, 'import numpy\n'), ((130975, 130995), 'numpy.array', 'numpy.array', (['rotMatj'], {}), '(rotMatj)\n', (130986, 130995), False, 'import numpy\n'), ((131021, 131037), 'numpy.array', 'numpy.array', (['pt1'], {}), '(pt1)\n', (131032, 131037), False, 'import numpy\n'), ((131358, 131374), 'numpy.array', 'numpy.array', (['pt1'], {}), '(pt1)\n', (131369, 131374), False, 'import numpy\n'), ((131973, 131990), 'numpy.identity', 'numpy.identity', (['(4)'], {}), '(4)\n', (131987, 131990), False, 'import numpy\n'), ((132909, 132926), 'numpy.identity', 'numpy.identity', (['(4)'], {}), '(4)\n', (132923, 132926), False, 'import numpy\n'), ((134498, 134515), 'numpy.identity', 'numpy.identity', (['(4)'], {}), '(4)\n', (134512, 134515), False, 'import numpy\n'), ((7112, 7150), 'cellpack.autopack.ldSequence.SphereHalton', 'SphereHalton', (['self.sphere_points_nb', '(5)'], {}), '(self.sphere_points_nb, 5)\n', (7124, 7150), False, 'from cellpack.autopack.ldSequence import SphereHalton\n'), ((12145, 12159), 'math.sqrt', 'sqrt', (['lengthsq'], {}), '(lengthsq)\n', (12149, 12159), False, 'from math import sqrt\n'), ((12580, 12599), 'numpy.dot', 'numpy.dot', (['pd', 'vect'], {}), '(pd, vect)\n', (12589, 12599), False, 'import numpy\n'), ((12621, 12642), 'numpy.sum', 'numpy.sum', (['(pd * pd)', '(1)'], {}), '(pd * pd, 1)\n', (12630, 12642), False, 'import numpy\n'), ((12784, 12807), 'numpy.sum', 'numpy.sum', (['(pd2 * pd2)', '(1)'], {}), '(pd2 * pd2, 1)\n', (12793, 12807), False, 'import numpy\n'), ((14492, 14530), 'numpy.nonzero', 'numpy.nonzero', (['self.sphere_points_mask'], {}), '(self.sphere_points_mask)\n', (14505, 14530), False, 'import numpy\n'), ((14760, 14805), 'numpy.array', 'numpy.array', (['self.sphere_points[sp_pt_indice]'], {}), '(self.sphere_points[sp_pt_indice])\n', (14771, 14805), False, 'import numpy\n'), ((14808, 14835), 'numpy.array', 'numpy.array', (['self.jitterMax'], {}), '(self.jitterMax)\n', (14819, 14835), False, 'import numpy\n'), ((15182, 15220), 'numpy.nonzero', 'numpy.nonzero', (['self.sphere_points_mask'], {}), '(self.sphere_points_mask)\n', (15195, 15220), False, 'import numpy\n'), ((15767, 15805), 'numpy.nonzero', 'numpy.nonzero', (['self.sphere_points_mask'], {}), '(self.sphere_points_mask)\n', (15780, 15805), False, 'import numpy\n'), ((16176, 16240), 'numpy.array', 'numpy.array', (['self.sphere_points'], {'dtype': 'numpy.float64', 'copy': '(False)'}), '(self.sphere_points, dtype=numpy.float64, copy=False)\n', (16187, 16240), False, 'import numpy\n'), ((16467, 16498), 'scipy.spatial.distance.cdist', 'spatial.distance.cdist', (['pts', 'dp'], {}), '(pts, dp)\n', (16489, 16498), False, 'from scipy import spatial\n'), ((16955, 17016), 'numpy.logical_and', 'numpy.logical_and', (['mask', 'self.sphere_points_mask[points_mask]'], {}), '(mask, self.sphere_points_mask[points_mask])\n', (16972, 17016), False, 'import numpy\n'), ((17348, 17386), 'numpy.nonzero', 'numpy.nonzero', (['self.sphere_points_mask'], {}), '(self.sphere_points_mask)\n', (17361, 17386), False, 'import numpy\n'), ((18027, 18089), 'numpy.logical_and', 'numpy.logical_and', (['mask4', 'self.sphere_points_mask[points_mask]'], {}), '(mask4, self.sphere_points_mask[points_mask])\n', (18044, 18089), False, 'import numpy\n'), ((18878, 18909), 'numpy.logical_and', 'numpy.logical_and', (['mask1', 'mask2'], {}), '(mask1, mask2)\n', (18895, 18909), False, 'import numpy\n'), ((18961, 19023), 'numpy.logical_and', 'numpy.logical_and', (['mask3', 'self.sphere_points_mask[points_mask]'], {}), '(mask3, self.sphere_points_mask[points_mask])\n', (18978, 19023), False, 'import numpy\n'), ((19246, 19284), 'numpy.nonzero', 'numpy.nonzero', (['self.sphere_points_mask'], {}), '(self.sphere_points_mask)\n', (19259, 19284), False, 'import numpy\n'), ((19859, 19897), 'numpy.nonzero', 'numpy.nonzero', (['self.sphere_points_mask'], {}), '(self.sphere_points_mask)\n', (19872, 19897), False, 'import numpy\n'), ((20220, 20236), 'numpy.array', 'numpy.array', (['ptb'], {}), '(ptb)\n', (20231, 20236), False, 'import numpy\n'), ((20239, 20255), 'numpy.array', 'numpy.array', (['pta'], {}), '(pta)\n', (20250, 20255), False, 'import numpy\n'), ((20455, 20470), 'numpy.array', 'numpy.array', (['pt'], {}), '(pt)\n', (20466, 20470), False, 'import numpy\n'), ((20499, 20514), 'numpy.array', 'numpy.array', (['pt'], {}), '(pt)\n', (20510, 20514), False, 'import numpy\n'), ((20801, 20818), 'math.radians', 'math.radians', (['(5.0)'], {}), '(5.0)\n', (20813, 20818), False, 'import math\n'), ((21873, 21908), 'numpy.copy', 'numpy.copy', (['sphere_points_mask_copy'], {}), '(sphere_points_mask_copy)\n', (21883, 21908), False, 'import numpy\n'), ((22726, 22741), 'random.gauss', 'gauss', (['(0.0)', '(0.3)'], {}), '(0.0, 0.3)\n', (22731, 22741), False, 'from random import uniform, gauss, random\n'), ((22859, 22874), 'random.gauss', 'gauss', (['(0.0)', '(0.3)'], {}), '(0.0, 0.3)\n', (22864, 22874), False, 'from random import uniform, gauss, random\n'), ((22902, 22917), 'random.gauss', 'gauss', (['(0.0)', '(0.3)'], {}), '(0.0, 0.3)\n', (22907, 22917), False, 'from random import uniform, gauss, random\n'), ((23207, 23225), 'numpy.array', 'numpy.array', (['nexPt'], {}), '(nexPt)\n', (23218, 23225), False, 'import numpy\n'), ((23228, 23247), 'numpy.array', 'numpy.array', (['cent2T'], {}), '(cent2T)\n', (23239, 23247), False, 'import numpy\n'), ((23305, 23312), 'math.sqrt', 'sqrt', (['d'], {}), '(d)\n', (23309, 23312), False, 'from math import sqrt\n'), ((23440, 23456), 'numpy.array', 'numpy.array', (['pt2'], {}), '(pt2)\n', (23451, 23456), False, 'import numpy\n'), ((23459, 23475), 'numpy.array', 'numpy.array', (['pt1'], {}), '(pt1)\n', (23470, 23475), False, 'import numpy\n'), ((23584, 23600), 'numpy.array', 'numpy.array', (['pmx'], {}), '(pmx)\n', (23595, 23600), False, 'import numpy\n'), ((23887, 23903), 'numpy.array', 'numpy.array', (['mat'], {}), '(mat)\n', (23898, 23903), False, 'import numpy\n'), ((24073, 24089), 'numpy.array', 'numpy.array', (['pt1'], {}), '(pt1)\n', (24084, 24089), False, 'import numpy\n'), ((24092, 24108), 'numpy.array', 'numpy.array', (['pt2'], {}), '(pt2)\n', (24103, 24108), False, 'import numpy\n'), ((36932, 36946), 'numpy.array', 'numpy.array', (['v'], {}), '(v)\n', (36943, 36946), False, 'import numpy\n'), ((70931, 70953), 'numpy.ones', 'numpy.ones', (['(10000)', '"""i"""'], {}), "(10000, 'i')\n", (70941, 70953), False, 'import numpy\n'), ((72078, 72084), 'time.time', 'time', ([], {}), '()\n', (72082, 72084), False, 'from time import time\n'), ((82688, 82703), 'numpy.array', 'numpy.array', (['pt'], {}), '(pt)\n', (82699, 82703), False, 'import numpy\n'), ((82890, 82904), 'numpy.array', 'numpy.array', (['p'], {}), '(p)\n', (82901, 82904), False, 'import numpy\n'), ((82907, 82934), 'numpy.array', 'numpy.array', (['self.jitterMax'], {}), '(self.jitterMax)\n', (82918, 82934), False, 'import numpy\n'), ((83057, 83072), 'numpy.array', 'numpy.array', (['pt'], {}), '(pt)\n', (83068, 83072), False, 'import numpy\n'), ((83622, 83636), 'numpy.array', 'numpy.array', (['p'], {}), '(p)\n', (83633, 83636), False, 'import numpy\n'), ((102567, 102589), 'numpy.ones', 'numpy.ones', (['(10000)', '"""i"""'], {}), "(10000, 'i')\n", (102577, 102589), False, 'import numpy\n'), ((116633, 116663), 'panda3d.bullet.BulletRigidBodyNode', 'BulletRigidBodyNode', (['self.name'], {}), '(self.name)\n', (116652, 116663), False, 'from panda3d.bullet import BulletSphereShape, BulletRigidBodyNode\n'), ((116877, 116900), 'panda3d.bullet.BulletSphereShape', 'BulletSphereShape', (['radc'], {}), '(radc)\n', (116894, 116900), False, 'from panda3d.bullet import BulletSphereShape, BulletRigidBodyNode\n'), ((117859, 117912), 'numpy.array', 'numpy.array', (['histoVol.grid.masterGridPositions[ptInd]'], {}), '(histoVol.grid.masterGridPositions[ptInd])\n', (117870, 117912), False, 'import numpy\n'), ((118099, 118128), 'numpy.array', 'numpy.array', (['self.orientation'], {}), '(self.orientation)\n', (118110, 118128), False, 'import numpy\n'), ((125112, 125127), 'random.uniform', 'uniform', (['(0)', '(1.0)'], {}), '(0, 1.0)\n', (125119, 125127), False, 'from random import uniform, gauss, random\n'), ((126261, 126277), 'numpy.array', 'numpy.array', (['pt2'], {}), '(pt2)\n', (126272, 126277), False, 'import numpy\n'), ((126280, 126296), 'numpy.array', 'numpy.array', (['pt1'], {}), '(pt1)\n', (126291, 126296), False, 'import numpy\n'), ((126476, 126492), 'numpy.array', 'numpy.array', (['ptc'], {}), '(ptc)\n', (126487, 126492), False, 'import numpy\n'), ((126495, 126511), 'numpy.array', 'numpy.array', (['ptb'], {}), '(ptb)\n', (126506, 126511), False, 'import numpy\n'), ((126715, 126731), 'numpy.array', 'numpy.array', (['pt1'], {}), '(pt1)\n', (126726, 126731), False, 'import numpy\n'), ((126760, 126776), 'numpy.array', 'numpy.array', (['pt1'], {}), '(pt1)\n', (126771, 126776), False, 'import numpy\n'), ((129774, 129790), 'numpy.array', 'numpy.array', (['pt2'], {}), '(pt2)\n', (129785, 129790), False, 'import numpy\n'), ((129793, 129809), 'numpy.array', 'numpy.array', (['pt1'], {}), '(pt1)\n', (129804, 129809), False, 'import numpy\n'), ((130008, 130024), 'numpy.array', 'numpy.array', (['ptc'], {}), '(ptc)\n', (130019, 130024), False, 'import numpy\n'), ((130027, 130043), 'numpy.array', 'numpy.array', (['ptb'], {}), '(ptb)\n', (130038, 130043), False, 'import numpy\n'), ((130247, 130263), 'numpy.array', 'numpy.array', (['pt1'], {}), '(pt1)\n', (130258, 130263), False, 'import numpy\n'), ((130292, 130308), 'numpy.array', 'numpy.array', (['pt1'], {}), '(pt1)\n', (130303, 130308), False, 'import numpy\n'), ((130456, 130478), 'numpy.array', 'numpy.array', (['newPts[1]'], {}), '(newPts[1])\n', (130467, 130478), False, 'import numpy\n'), ((130481, 130503), 'numpy.array', 'numpy.array', (['newPts[0]'], {}), '(newPts[0])\n', (130492, 130503), False, 'import numpy\n'), ((131063, 131079), 'numpy.array', 'numpy.array', (['pt2'], {}), '(pt2)\n', (131074, 131079), False, 'import numpy\n'), ((131082, 131098), 'numpy.array', 'numpy.array', (['pt1'], {}), '(pt1)\n', (131093, 131098), False, 'import numpy\n'), ((131237, 131253), 'numpy.array', 'numpy.array', (['ptc'], {}), '(ptc)\n', (131248, 131253), False, 'import numpy\n'), ((131256, 131272), 'numpy.array', 'numpy.array', (['ptb'], {}), '(ptb)\n', (131267, 131272), False, 'import numpy\n'), ((131476, 131492), 'numpy.array', 'numpy.array', (['pt1'], {}), '(pt1)\n', (131487, 131492), False, 'import numpy\n'), ((131521, 131537), 'numpy.array', 'numpy.array', (['pt1'], {}), '(pt1)\n', (131532, 131537), False, 'import numpy\n'), ((132752, 132772), 'numpy.array', 'numpy.array', (['rotMatj'], {}), '(rotMatj)\n', (132763, 132772), False, 'import numpy\n'), ((133816, 133836), 'numpy.array', 'numpy.array', (['rotMatj'], {}), '(rotMatj)\n', (133827, 133836), False, 'import numpy\n'), ((134341, 134361), 'numpy.array', 'numpy.array', (['rotMatj'], {}), '(rotMatj)\n', (134352, 134361), False, 'import numpy\n'), ((6369, 6411), 'cellpack.autopack.helper.getObject', 'autopack.helper.getObject', (['"""autopackHider"""'], {}), "('autopackHider')\n", (6394, 6411), True, 'import cellpack.autopack as autopack\n'), ((6695, 6859), 'cellpack.autopack.helper.Cylinder', 'autopack.helper.Cylinder', (["(self.name + '_basic')"], {'radius': '(self.radii[0][0] * 1.24)', 'length': 'self.uLength', 'res': '(32)', 'parent': '"""autopackHider"""', 'axis': 'self.orientation'}), "(self.name + '_basic', radius=self.radii[0][0] * \n 1.24, length=self.uLength, res=32, parent='autopackHider', axis=self.\n orientation)\n", (6719, 6859), True, 'import cellpack.autopack as autopack\n'), ((12510, 12555), 'numpy.take', 'numpy.take', (['gridPointsCoords', 'pointsInCube', '(0)'], {}), '(gridPointsCoords, pointsInCube, 0)\n', (12520, 12555), False, 'import numpy\n'), ((12712, 12757), 'numpy.take', 'numpy.take', (['gridPointsCoords', 'pointsInCube', '(0)'], {}), '(gridPointsCoords, pointsInCube, 0)\n', (12722, 12757), False, 'import numpy\n'), ((14668, 14685), 'random.uniform', 'uniform', (['(0.0)', '(1.0)'], {}), '(0.0, 1.0)\n', (14675, 14685), False, 'from random import uniform, gauss, random\n'), ((15107, 15138), 'numpy.array', 'numpy.array', (['self.sphere_points'], {}), '(self.sphere_points)\n', (15118, 15138), False, 'import numpy\n'), ((15418, 15479), 'numpy.logical_and', 'numpy.logical_and', (['mask', 'self.sphere_points_mask[points_mask]'], {}), '(mask, self.sphere_points_mask[points_mask])\n', (15435, 15479), False, 'import numpy\n'), ((15881, 15906), 'numpy.array', 'numpy.array', (['listeclosest'], {}), '(listeclosest)\n', (15892, 15906), False, 'import numpy\n'), ((15933, 15958), 'numpy.array', 'numpy.array', (['listeclosest'], {}), '(listeclosest)\n', (15944, 15958), False, 'import numpy\n'), ((16781, 16825), 'numpy.greater_equal', 'numpy.greater_equal', (['distances[i]', 'radius[i]'], {}), '(distances[i], radius[i])\n', (16800, 16825), False, 'import numpy\n'), ((16849, 16875), 'numpy.logical_and', 'numpy.logical_and', (['mask', 'm'], {}), '(mask, m)\n', (16866, 16875), False, 'import numpy\n'), ((17885, 17900), 'math.radians', 'math.radians', (['(5)'], {}), '(5)\n', (17897, 17900), False, 'import math\n'), ((19478, 19500), 'math.radians', 'math.radians', (['marge_in'], {}), '(marge_in)\n', (19490, 19500), False, 'import math\n'), ((23504, 23533), 'numpy.array', 'numpy.array', (['self.orientation'], {}), '(self.orientation)\n', (23515, 23533), False, 'import numpy\n'), ((23614, 23630), 'numpy.array', 'numpy.array', (['pt1'], {}), '(pt1)\n', (23625, 23630), False, 'import numpy\n'), ((23917, 23933), 'numpy.array', 'numpy.array', (['pt1'], {}), '(pt1)\n', (23928, 23933), False, 'import numpy\n'), ((24924, 24940), 'numpy.array', 'numpy.array', (['pt1'], {}), '(pt1)\n', (24935, 24940), False, 'import numpy\n'), ((26469, 26486), 'numpy.array', 'numpy.array', (['posc'], {}), '(posc)\n', (26480, 26486), False, 'import numpy\n'), ((26488, 26502), 'numpy.array', 'numpy.array', (['v'], {}), '(v)\n', (26499, 26502), False, 'import numpy\n'), ((26548, 26565), 'numpy.array', 'numpy.array', (['posc'], {}), '(posc)\n', (26559, 26565), False, 'import numpy\n'), ((26567, 26581), 'numpy.array', 'numpy.array', (['v'], {}), '(v)\n', (26578, 26581), False, 'import numpy\n'), ((30315, 30332), 'numpy.array', 'numpy.array', (['posc'], {}), '(posc)\n', (30326, 30332), False, 'import numpy\n'), ((30334, 30348), 'numpy.array', 'numpy.array', (['v'], {}), '(v)\n', (30345, 30348), False, 'import numpy\n'), ((30394, 30411), 'numpy.array', 'numpy.array', (['posc'], {}), '(posc)\n', (30405, 30411), False, 'import numpy\n'), ((30413, 30427), 'numpy.array', 'numpy.array', (['v'], {}), '(v)\n', (30424, 30427), False, 'import numpy\n'), ((33129, 33144), 'numpy.array', 'numpy.array', (['pt'], {}), '(pt)\n', (33140, 33144), False, 'import numpy\n'), ((33421, 33435), 'numpy.array', 'numpy.array', (['v'], {}), '(v)\n', (33432, 33435), False, 'import numpy\n'), ((33437, 33452), 'numpy.array', 'numpy.array', (['pt'], {}), '(pt)\n', (33448, 33452), False, 'import numpy\n'), ((36612, 36627), 'numpy.array', 'numpy.array', (['pt'], {}), '(pt)\n', (36623, 36627), False, 'import numpy\n'), ((36967, 36981), 'numpy.array', 'numpy.array', (['v'], {}), '(v)\n', (36978, 36981), False, 'import numpy\n'), ((42081, 42119), 'numpy.nonzero', 'numpy.nonzero', (['self.sphere_points_mask'], {}), '(self.sphere_points_mask)\n', (42094, 42119), False, 'import numpy\n'), ((58994, 59009), 'numpy.array', 'numpy.array', (['pt'], {}), '(pt)\n', (59005, 59009), False, 'import numpy\n'), ((69620, 69635), 'numpy.array', 'numpy.array', (['pt'], {}), '(pt)\n', (69631, 69635), False, 'import numpy\n'), ((82401, 82416), 'numpy.array', 'numpy.array', (['pt'], {}), '(pt)\n', (82412, 82416), False, 'import numpy\n'), ((82837, 82856), 'math.radians', 'math.radians', (['marge'], {}), '(marge)\n', (82849, 82856), False, 'import math\n'), ((87567, 87605), 'numpy.nonzero', 'numpy.nonzero', (['self.sphere_points_mask'], {}), '(self.sphere_points_mask)\n', (87580, 87605), False, 'import numpy\n'), ((100381, 100396), 'numpy.array', 'numpy.array', (['pt'], {}), '(pt)\n', (100392, 100396), False, 'import numpy\n'), ((100817, 100865), 'cellpack.mgl_tools.bhtree.bhtreelib.freeBHtree', 'bhtreelib.freeBHtree', (['self.env.close_ingr_bhtree'], {}), '(self.env.close_ingr_bhtree)\n', (100837, 100865), False, 'from cellpack.mgl_tools.bhtree import bhtreelib\n'), ((100948, 100991), 'cellpack.mgl_tools.bhtree.bhtreelib.BHtree', 'bhtreelib.BHtree', (['self.env.rTrans', 'None', '(10)'], {}), '(self.env.rTrans, None, 10)\n', (100964, 100991), False, 'from cellpack.mgl_tools.bhtree import bhtreelib\n'), ((101121, 101166), 'scipy.spatial.cKDTree', 'spatial.cKDTree', (['self.env.rTrans'], {'leafsize': '(10)'}), '(self.env.rTrans, leafsize=10)\n', (101136, 101166), False, 'from scipy import spatial\n'), ((106113, 106139), 'numpy.array', 'numpy.array', (['previousPoint'], {}), '(previousPoint)\n', (106124, 106139), False, 'import numpy\n'), ((113311, 113342), 'numpy.array', 'numpy.array', (['self.startingpoint'], {}), '(self.startingpoint)\n', (113322, 113342), False, 'import numpy\n'), ((113546, 113575), 'numpy.array', 'numpy.array', (['self.orientation'], {}), '(self.orientation)\n', (113557, 113575), False, 'import numpy\n'), ((120292, 120335), 'cellpack.mgl_tools.bhtree.bhtreelib.BHtree', 'bhtreelib.BHtree', (['self.env.rTrans', 'None', '(10)'], {}), '(self.env.rTrans, None, 10)\n', (120308, 120335), False, 'from cellpack.mgl_tools.bhtree import bhtreelib\n'), ((120465, 120510), 'scipy.spatial.cKDTree', 'spatial.cKDTree', (['self.env.rTrans'], {'leafsize': '(10)'}), '(self.env.rTrans, leafsize=10)\n', (120480, 120510), False, 'from scipy import spatial\n'), ((125302, 125317), 'random.uniform', 'uniform', (['(0)', '(1.0)'], {}), '(0, 1.0)\n', (125309, 125317), False, 'from random import uniform, gauss, random\n'), ((129169, 129184), 'numpy.matrix', 'matrix', (['localMR'], {}), '(localMR)\n', (129175, 129184), False, 'from numpy import matrix\n'), ((129187, 129202), 'numpy.matrix', 'matrix', (['prevMat'], {}), '(prevMat)\n', (129193, 129202), False, 'from numpy import matrix\n'), ((132177, 132193), 'numpy.array', 'numpy.array', (['ptb'], {}), '(ptb)\n', (132188, 132193), False, 'import numpy\n'), ((132196, 132212), 'numpy.array', 'numpy.array', (['pta'], {}), '(pta)\n', (132207, 132212), False, 'import numpy\n'), ((132232, 132248), 'numpy.array', 'numpy.array', (['pt2'], {}), '(pt2)\n', (132243, 132248), False, 'import numpy\n'), ((132251, 132267), 'numpy.array', 'numpy.array', (['pt1'], {}), '(pt1)\n', (132262, 132267), False, 'import numpy\n'), ((134715, 134730), 'numpy.matrix', 'matrix', (['localMR'], {}), '(localMR)\n', (134721, 134730), False, 'from numpy import matrix\n'), ((134733, 134748), 'numpy.matrix', 'matrix', (['prevMat'], {}), '(prevMat)\n', (134739, 134748), False, 'from numpy import matrix\n'), ((6466, 6507), 'cellpack.autopack.helper.newEmpty', 'autopack.helper.newEmpty', (['"""autopackHider"""'], {}), "('autopackHider')\n", (6490, 6507), True, 'import cellpack.autopack as autopack\n'), ((13009, 13026), 'math.sqrt', 'sqrt', (['d2toP1[pti]'], {}), '(d2toP1[pti])\n', (13013, 13026), False, 'from math import sqrt\n'), ((18645, 18671), 'math.radians', 'math.radians', (['marge_out[1]'], {}), '(marge_out[1])\n', (18657, 18671), False, 'import math\n'), ((18677, 18703), 'math.radians', 'math.radians', (['marge_out[0]'], {}), '(marge_out[0])\n', (18689, 18703), False, 'import math\n'), ((18777, 18807), 'math.radians', 'math.radians', (['marge_diedral[1]'], {}), '(marge_diedral[1])\n', (18789, 18807), False, 'import math\n'), ((18813, 18843), 'math.radians', 'math.radians', (['marge_diedral[0]'], {}), '(marge_diedral[0])\n', (18825, 18843), False, 'import math\n'), ((19574, 19599), 'math.radians', 'math.radians', (['marge_in[1]'], {}), '(marge_in[1])\n', (19586, 19599), False, 'import math\n'), ((19605, 19630), 'math.radians', 'math.radians', (['marge_in[0]'], {}), '(marge_in[0])\n', (19617, 19630), False, 'import math\n'), ((21791, 21829), 'numpy.nonzero', 'numpy.nonzero', (['self.sphere_points_mask'], {}), '(self.sphere_points_mask)\n', (21804, 21829), False, 'import numpy\n'), ((23633, 23647), 'numpy.array', 'numpy.array', (['v'], {}), '(v)\n', (23644, 23647), False, 'import numpy\n'), ((23936, 23950), 'numpy.array', 'numpy.array', (['v'], {}), '(v)\n', (23947, 23950), False, 'import numpy\n'), ((24943, 24957), 'numpy.array', 'numpy.array', (['v'], {}), '(v)\n', (24954, 24957), False, 'import numpy\n'), ((25961, 25969), 'random.random', 'random', ([], {}), '()\n', (25967, 25969), False, 'from random import uniform, gauss, random\n'), ((26612, 26631), 'math.degrees', 'math.degrees', (['angle'], {}), '(angle)\n', (26624, 26631), False, 'import math\n'), ((26958, 26975), 'numpy.identity', 'numpy.identity', (['(4)'], {}), '(4)\n', (26972, 26975), False, 'import numpy\n'), ((29793, 29801), 'random.random', 'random', ([], {}), '()\n', (29799, 29801), False, 'from random import uniform, gauss, random\n'), ((30458, 30477), 'math.degrees', 'math.degrees', (['angle'], {}), '(angle)\n', (30470, 30477), False, 'import math\n'), ((30804, 30821), 'numpy.identity', 'numpy.identity', (['(4)'], {}), '(4)\n', (30818, 30821), False, 'import numpy\n'), ((33535, 33554), 'math.degrees', 'math.degrees', (['angle'], {}), '(angle)\n', (33547, 33554), False, 'import math\n'), ((60724, 60738), 'numpy.array', 'numpy.array', (['p'], {}), '(p)\n', (60735, 60738), False, 'import numpy\n'), ((60775, 60789), 'numpy.array', 'numpy.array', (['p'], {}), '(p)\n', (60786, 60789), False, 'import numpy\n'), ((60792, 60819), 'numpy.array', 'numpy.array', (['self.jitterMax'], {}), '(self.jitterMax)\n', (60803, 60819), False, 'import numpy\n'), ((60878, 60893), 'numpy.array', 'numpy.array', (['pt'], {}), '(pt)\n', (60889, 60893), False, 'import numpy\n'), ((61241, 61255), 'numpy.array', 'numpy.array', (['p'], {}), '(p)\n', (61252, 61255), False, 'import numpy\n'), ((61258, 61285), 'numpy.array', 'numpy.array', (['self.jitterMax'], {}), '(self.jitterMax)\n', (61269, 61285), False, 'import numpy\n'), ((61429, 61444), 'numpy.array', 'numpy.array', (['pt'], {}), '(pt)\n', (61440, 61444), False, 'import numpy\n'), ((61741, 61755), 'numpy.array', 'numpy.array', (['v'], {}), '(v)\n', (61752, 61755), False, 'import numpy\n'), ((61757, 61772), 'numpy.array', 'numpy.array', (['pt'], {}), '(pt)\n', (61768, 61772), False, 'import numpy\n'), ((75291, 75297), 'time.time', 'time', ([], {}), '()\n', (75295, 75297), False, 'from time import time\n'), ((82659, 82675), 'numpy.array', 'numpy.array', (['pt2'], {}), '(pt2)\n', (82670, 82675), False, 'import numpy\n'), ((83028, 83044), 'numpy.array', 'numpy.array', (['pt2'], {}), '(pt2)\n', (83039, 83044), False, 'import numpy\n'), ((83593, 83609), 'numpy.array', 'numpy.array', (['pt2'], {}), '(pt2)\n', (83604, 83609), False, 'import numpy\n'), ((113345, 113360), 'numpy.array', 'numpy.array', (['v2'], {}), '(v2)\n', (113356, 113360), False, 'import numpy\n'), ((113593, 113601), 'random.random', 'random', ([], {}), '()\n', (113599, 113601), False, 'from random import uniform, gauss, random\n'), ((113604, 113628), 'math.radians', 'math.radians', (['self.marge'], {}), '(self.marge)\n', (113616, 113628), False, 'import math\n'), ((116984, 117017), 'panda3d.core.Point3', 'Point3', (['posc[0]', 'posc[1]', 'posc[2]'], {}), '(posc[0], posc[1], posc[2])\n', (116990, 117017), False, 'from panda3d.core import Point3, TransformState\n'), ((119255, 119272), 'numpy.identity', 'numpy.identity', (['(4)'], {}), '(4)\n', (119269, 119272), False, 'import numpy\n'), ((119850, 119870), 'numpy.array', 'numpy.array', (['rotMatj'], {}), '(rotMatj)\n', (119861, 119870), False, 'import numpy\n'), ((125856, 125872), 'numpy.array', 'numpy.array', (['pt1'], {}), '(pt1)\n', (125867, 125872), False, 'import numpy\n'), ((125884, 125900), 'numpy.array', 'numpy.array', (['pt2'], {}), '(pt2)\n', (125895, 125900), False, 'import numpy\n'), ((128719, 128735), 'numpy.array', 'numpy.array', (['pt1'], {}), '(pt1)\n', (128730, 128735), False, 'import numpy\n'), ((128747, 128763), 'numpy.array', 'numpy.array', (['pt2'], {}), '(pt2)\n', (128758, 128763), False, 'import numpy\n'), ((129535, 129551), 'numpy.array', 'numpy.array', (['pt1'], {}), '(pt1)\n', (129546, 129551), False, 'import numpy\n'), ((129563, 129579), 'numpy.array', 'numpy.array', (['pt2'], {}), '(pt2)\n', (129574, 129579), False, 'import numpy\n'), ((130824, 130840), 'numpy.array', 'numpy.array', (['pt1'], {}), '(pt1)\n', (130835, 130840), False, 'import numpy\n'), ((130852, 130868), 'numpy.array', 'numpy.array', (['pt2'], {}), '(pt2)\n', (130863, 130868), False, 'import numpy\n'), ((6531, 6567), 'cellpack.autopack.helper.host.find', 'autopack.helper.host.find', (['"""blender"""'], {}), "('blender')\n", (6556, 6567), True, 'import cellpack.autopack as autopack\n'), ((6599, 6638), 'cellpack.autopack.helper.toggleDisplay', 'autopack.helper.toggleDisplay', (['p', '(False)'], {}), '(p, False)\n', (6628, 6638), True, 'import cellpack.autopack as autopack\n'), ((13403, 13420), 'math.sqrt', 'sqrt', (['d2toP2[pti]'], {}), '(d2toP2[pti])\n', (13407, 13420), False, 'from math import sqrt\n'), ((33100, 33116), 'numpy.array', 'numpy.array', (['pt2'], {}), '(pt2)\n', (33111, 33116), False, 'import numpy\n'), ((36583, 36599), 'numpy.array', 'numpy.array', (['pt2'], {}), '(pt2)\n', (36594, 36599), False, 'import numpy\n'), ((47954, 47972), 'numpy.array', 'numpy.array', (['newPt'], {}), '(newPt)\n', (47965, 47972), False, 'import numpy\n'), ((58789, 58804), 'numpy.array', 'numpy.array', (['pt'], {}), '(pt)\n', (58800, 58804), False, 'import numpy\n'), ((58965, 58981), 'numpy.array', 'numpy.array', (['pt2'], {}), '(pt2)\n', (58976, 58981), False, 'import numpy\n'), ((61172, 61191), 'math.radians', 'math.radians', (['marge'], {}), '(marge)\n', (61184, 61191), False, 'import math\n'), ((61801, 61820), 'math.degrees', 'math.degrees', (['angle'], {}), '(angle)\n', (61813, 61820), False, 'import math\n'), ((69407, 69426), 'math.degrees', 'math.degrees', (['angle'], {}), '(angle)\n', (69419, 69426), False, 'import math\n'), ((69591, 69607), 'numpy.array', 'numpy.array', (['pt2'], {}), '(pt2)\n', (69602, 69607), False, 'import numpy\n'), ((74289, 74303), 'numpy.array', 'numpy.array', (['p'], {}), '(p)\n', (74300, 74303), False, 'import numpy\n'), ((74342, 74356), 'numpy.array', 'numpy.array', (['p'], {}), '(p)\n', (74353, 74356), False, 'import numpy\n'), ((82191, 82210), 'math.degrees', 'math.degrees', (['angle'], {}), '(angle)\n', (82203, 82210), False, 'import math\n'), ((82372, 82388), 'numpy.array', 'numpy.array', (['pt2'], {}), '(pt2)\n', (82383, 82388), False, 'import numpy\n'), ((93496, 93514), 'numpy.array', 'numpy.array', (['newPt'], {}), '(newPt)\n', (93507, 93514), False, 'import numpy\n'), ((100234, 100249), 'numpy.array', 'numpy.array', (['pt'], {}), '(pt)\n', (100245, 100249), False, 'import numpy\n'), ((100352, 100368), 'numpy.array', 'numpy.array', (['pt2'], {}), '(pt2)\n', (100363, 100368), False, 'import numpy\n'), ((104375, 104381), 'time.time', 'time', ([], {}), '()\n', (104379, 104381), False, 'from time import time\n'), ((114989, 115003), 'numpy.array', 'numpy.array', (['p'], {}), '(p)\n', (115000, 115003), False, 'import numpy\n'), ((115006, 115033), 'numpy.array', 'numpy.array', (['self.jitterMax'], {}), '(self.jitterMax)\n', (115017, 115033), False, 'import numpy\n'), ((115089, 115104), 'numpy.array', 'numpy.array', (['pt'], {}), '(pt)\n', (115100, 115104), False, 'import numpy\n'), ((119172, 119198), 'numpy.array', 'numpy.array', (['startingPoint'], {}), '(startingPoint)\n', (119183, 119198), False, 'import numpy\n'), ((132086, 132102), 'numpy.array', 'numpy.array', (['pt1'], {}), '(pt1)\n', (132097, 132102), False, 'import numpy\n'), ((132114, 132130), 'numpy.array', 'numpy.array', (['pt2'], {}), '(pt2)\n', (132125, 132130), False, 'import numpy\n'), ((132659, 132675), 'numpy.array', 'numpy.array', (['pt2'], {}), '(pt2)\n', (132670, 132675), False, 'import numpy\n'), ((132687, 132705), 'numpy.array', 'numpy.array', (['newPt'], {}), '(newPt)\n', (132698, 132705), False, 'import numpy\n'), ((133725, 133741), 'numpy.array', 'numpy.array', (['pt1'], {}), '(pt1)\n', (133736, 133741), False, 'import numpy\n'), ((133753, 133769), 'numpy.array', 'numpy.array', (['pt2'], {}), '(pt2)\n', (133764, 133769), False, 'import numpy\n'), ((134248, 134264), 'numpy.array', 'numpy.array', (['pt2'], {}), '(pt2)\n', (134259, 134264), False, 'import numpy\n'), ((134276, 134294), 'numpy.array', 'numpy.array', (['newPt'], {}), '(newPt)\n', (134287, 134294), False, 'import numpy\n'), ((13776, 13790), 'math.sqrt', 'sqrt', (['dsq[pti]'], {}), '(dsq[pti])\n', (13780, 13790), False, 'from math import sqrt\n'), ((36393, 36408), 'numpy.array', 'numpy.array', (['pt'], {}), '(pt)\n', (36404, 36408), False, 'import numpy\n'), ((46533, 46571), 'numpy.ones', 'numpy.ones', (['self.sphere_points_nb', '"""i"""'], {}), "(self.sphere_points_nb, 'i')\n", (46543, 46571), False, 'import numpy\n'), ((55555, 55575), 'numpy.array', 'numpy.array', (['rotMatj'], {}), '(rotMatj)\n', (55566, 55575), False, 'import numpy\n'), ((60849, 60865), 'numpy.array', 'numpy.array', (['pt2'], {}), '(pt2)\n', (60860, 60865), False, 'import numpy\n'), ((61400, 61416), 'numpy.array', 'numpy.array', (['pt2'], {}), '(pt2)\n', (61411, 61416), False, 'import numpy\n'), ((67603, 67623), 'numpy.array', 'numpy.array', (['rotMatj'], {}), '(rotMatj)\n', (67614, 67623), False, 'import numpy\n'), ((68294, 68337), 'cellpack.mgl_tools.bhtree.bhtreelib.BHtree', 'bhtreelib.BHtree', (['histoVol.rTrans', 'None', '(10)'], {}), '(histoVol.rTrans, None, 10)\n', (68310, 68337), False, 'from cellpack.mgl_tools.bhtree import bhtreelib\n'), ((69320, 69335), 'numpy.array', 'numpy.array', (['pt'], {}), '(pt)\n', (69331, 69335), False, 'import numpy\n'), ((73444, 73458), 'numpy.array', 'numpy.array', (['p'], {}), '(p)\n', (73455, 73458), False, 'import numpy\n'), ((74444, 74459), 'numpy.array', 'numpy.array', (['pt'], {}), '(pt)\n', (74455, 74459), False, 'import numpy\n'), ((74671, 74685), 'numpy.array', 'numpy.array', (['p'], {}), '(p)\n', (74682, 74685), False, 'import numpy\n'), ((74688, 74715), 'numpy.array', 'numpy.array', (['self.jitterMax'], {}), '(self.jitterMax)\n', (74699, 74715), False, 'import numpy\n'), ((74854, 74869), 'numpy.array', 'numpy.array', (['pt'], {}), '(pt)\n', (74865, 74869), False, 'import numpy\n'), ((75030, 75044), 'numpy.array', 'numpy.array', (['v'], {}), '(v)\n', (75041, 75044), False, 'import numpy\n'), ((75046, 75061), 'numpy.array', 'numpy.array', (['pt'], {}), '(pt)\n', (75057, 75061), False, 'import numpy\n'), ((82052, 82067), 'numpy.array', 'numpy.array', (['pt'], {}), '(pt)\n', (82063, 82067), False, 'import numpy\n'), ((92031, 92069), 'numpy.ones', 'numpy.ones', (['self.sphere_points_nb', '"""i"""'], {}), "(self.sphere_points_nb, 'i')\n", (92041, 92069), False, 'import numpy\n'), ((97325, 97345), 'numpy.array', 'numpy.array', (['rotMatj'], {}), '(rotMatj)\n', (97336, 97345), False, 'import numpy\n'), ((113756, 113770), 'numpy.array', 'numpy.array', (['v'], {}), '(v)\n', (113767, 113770), False, 'import numpy\n'), ((114897, 114921), 'math.radians', 'math.radians', (['self.marge'], {}), '(self.marge)\n', (114909, 114921), False, 'import math\n'), ((119786, 119805), 'numpy.array', 'numpy.array', (['jtrans'], {}), '(jtrans)\n', (119797, 119805), False, 'import numpy\n'), ((47975, 47991), 'numpy.array', 'numpy.array', (['pt2'], {}), '(pt2)\n', (47986, 47991), False, 'import numpy\n'), ((48022, 48038), 'numpy.array', 'numpy.array', (['pt2'], {}), '(pt2)\n', (48033, 48038), False, 'import numpy\n'), ((49507, 49523), 'numpy.array', 'numpy.array', (['pt2'], {}), '(pt2)\n', (49518, 49523), False, 'import numpy\n'), ((53332, 53348), 'numpy.array', 'numpy.array', (['pt2'], {}), '(pt2)\n', (53343, 53348), False, 'import numpy\n'), ((58760, 58776), 'numpy.array', 'numpy.array', (['pt2'], {}), '(pt2)\n', (58771, 58776), False, 'import numpy\n'), ((64245, 64264), 'numpy.array', 'numpy.array', (['jtrans'], {}), '(jtrans)\n', (64256, 64264), False, 'import numpy\n'), ((64298, 64318), 'numpy.array', 'numpy.array', (['rotMatj'], {}), '(rotMatj)\n', (64309, 64318), False, 'import numpy\n'), ((68593, 68638), 'scipy.spatial.cKDTree', 'spatial.cKDTree', (['histoVol.rTrans'], {'leafsize': '(10)'}), '(histoVol.rTrans, leafsize=10)\n', (68608, 68638), False, 'from scipy import spatial\n'), ((68769, 68784), 'numpy.array', 'numpy.array', (['pt'], {}), '(pt)\n', (68780, 68784), False, 'import numpy\n'), ((74602, 74621), 'math.radians', 'math.radians', (['marge'], {}), '(marge)\n', (74614, 74621), False, 'import math\n'), ((75090, 75109), 'math.degrees', 'math.degrees', (['angle'], {}), '(angle)\n', (75102, 75109), False, 'import math\n'), ((80684, 80704), 'numpy.array', 'numpy.array', (['rotMatj'], {}), '(rotMatj)\n', (80695, 80704), False, 'import numpy\n'), ((93517, 93533), 'numpy.array', 'numpy.array', (['pt2'], {}), '(pt2)\n', (93528, 93533), False, 'import numpy\n'), ((93564, 93580), 'numpy.array', 'numpy.array', (['pt2'], {}), '(pt2)\n', (93575, 93580), False, 'import numpy\n'), ((94080, 94096), 'numpy.array', 'numpy.array', (['pt2'], {}), '(pt2)\n', (94091, 94096), False, 'import numpy\n'), ((94991, 95007), 'numpy.array', 'numpy.array', (['pt2'], {}), '(pt2)\n', (95002, 95007), False, 'import numpy\n'), ((98677, 98715), 'numpy.ones', 'numpy.ones', (['self.sphere_points_nb', '"""i"""'], {}), "(self.sphere_points_nb, 'i')\n", (98687, 98715), False, 'import numpy\n'), ((100205, 100221), 'numpy.array', 'numpy.array', (['pt2'], {}), '(pt2)\n', (100216, 100221), False, 'import numpy\n'), ((104780, 104786), 'time.time', 'time', ([], {}), '()\n', (104784, 104786), False, 'from time import time\n'), ((119380, 119406), 'numpy.array', 'numpy.array', (['startingPoint'], {}), '(startingPoint)\n', (119391, 119406), False, 'import numpy\n'), ((35885, 35900), 'numpy.array', 'numpy.array', (['pt'], {}), '(pt)\n', (35896, 35900), False, 'import numpy\n'), ((36364, 36380), 'numpy.array', 'numpy.array', (['pt2'], {}), '(pt2)\n', (36375, 36380), False, 'import numpy\n'), ((46825, 46863), 'numpy.nonzero', 'numpy.nonzero', (['self.sphere_points_mask'], {}), '(self.sphere_points_mask)\n', (46838, 46863), False, 'import numpy\n'), ((52943, 52959), 'numpy.array', 'numpy.array', (['pt2'], {}), '(pt2)\n', (52954, 52959), False, 'import numpy\n'), ((57151, 57189), 'numpy.ones', 'numpy.ones', (['self.sphere_points_nb', '"""i"""'], {}), "(self.sphere_points_nb, 'i')\n", (57161, 57189), False, 'import numpy\n'), ((63704, 63720), 'numpy.array', 'numpy.array', (['pt2'], {}), '(pt2)\n', (63715, 63720), False, 'import numpy\n'), ((63984, 64000), 'numpy.array', 'numpy.array', (['pt2'], {}), '(pt2)\n', (63995, 64000), False, 'import numpy\n'), ((67530, 67546), 'numpy.array', 'numpy.array', (['pt2'], {}), '(pt2)\n', (67541, 67546), False, 'import numpy\n'), ((69291, 69307), 'numpy.array', 'numpy.array', (['pt2'], {}), '(pt2)\n', (69302, 69307), False, 'import numpy\n'), ((73415, 73431), 'numpy.array', 'numpy.array', (['pt2'], {}), '(pt2)\n', (73426, 73431), False, 'import numpy\n'), ((74415, 74431), 'numpy.array', 'numpy.array', (['pt2'], {}), '(pt2)\n', (74426, 74431), False, 'import numpy\n'), ((74825, 74841), 'numpy.array', 'numpy.array', (['pt2'], {}), '(pt2)\n', (74836, 74841), False, 'import numpy\n'), ((76709, 76725), 'numpy.array', 'numpy.array', (['pt2'], {}), '(pt2)\n', (76720, 76725), False, 'import numpy\n'), ((77452, 77468), 'numpy.array', 'numpy.array', (['pt2'], {}), '(pt2)\n', (77463, 77468), False, 'import numpy\n'), ((80071, 80086), 'numpy.array', 'numpy.array', (['pt'], {}), '(pt)\n', (80082, 80086), False, 'import numpy\n'), ((82023, 82039), 'numpy.array', 'numpy.array', (['pt2'], {}), '(pt2)\n', (82034, 82039), False, 'import numpy\n'), ((92323, 92361), 'numpy.nonzero', 'numpy.nonzero', (['self.sphere_points_mask'], {}), '(self.sphere_points_mask)\n', (92336, 92361), False, 'import numpy\n'), ((119977, 120003), 'numpy.array', 'numpy.array', (['startingPoint'], {}), '(startingPoint)\n', (119988, 120003), False, 'import numpy\n'), ((35387, 35403), 'numpy.array', 'numpy.array', (['pt2'], {}), '(pt2)\n', (35398, 35403), False, 'import numpy\n'), ((54862, 54878), 'numpy.array', 'numpy.array', (['pt2'], {}), '(pt2)\n', (54873, 54878), False, 'import numpy\n'), ((55748, 55764), 'numpy.array', 'numpy.array', (['pt2'], {}), '(pt2)\n', (55759, 55764), False, 'import numpy\n'), ((68740, 68756), 'numpy.array', 'numpy.array', (['pt2'], {}), '(pt2)\n', (68751, 68756), False, 'import numpy\n'), ((99055, 99093), 'numpy.nonzero', 'numpy.nonzero', (['self.sphere_points_mask'], {}), '(self.sphere_points_mask)\n', (99068, 99093), False, 'import numpy\n'), ((35856, 35872), 'numpy.array', 'numpy.array', (['pt2'], {}), '(pt2)\n', (35867, 35872), False, 'import numpy\n'), ((57529, 57567), 'numpy.nonzero', 'numpy.nonzero', (['self.sphere_points_mask'], {}), '(self.sphere_points_mask)\n', (57542, 57567), False, 'import numpy\n'), ((67768, 67784), 'numpy.array', 'numpy.array', (['pt2'], {}), '(pt2)\n', (67779, 67784), False, 'import numpy\n'), ((79970, 79988), 'numpy.array', 'numpy.array', (['newPt'], {}), '(newPt)\n', (79981, 79988), False, 'import numpy\n')]
#!/usr/bin/env python from dipy.data import get_sphere from nose.tools import assert_equal import numpy as np from scipy.spatial.distance import (cosine, euclidean, mahalanobis) from scipy.special import logsumexp, softmax import torch from torch.nn.utils.rnn import PackedSequence from dwi_ml.models.direction_getter_models import ( CosineRegressionDirectionGetter, FisherVonMisesDirectionGetter, GaussianMixtureDirectionGetter, L2RegressionDirectionGetter, SingleGaussianDirectionGetter, SphereClassificationDirectionGetter) from dwi_ml.models.utils.fisher_von_mises import ( fisher_von_mises_log_prob_vector) d = 3 def independent_gaussian_log_prob_vector(x, mus, sigmas): """ Equivalent to the torch method in model.utils.gaussians. Easier to test. Parameters ---------- x = the variable mu = mean of the gaussian (x,y,z directions) sigmas = standard deviation of the gaussian (x,y,z directions) """ # The inverse of a diagonal matrix is just inverting values on the # diagonal cov_inv = np.eye(d) * (1 / sigmas ** 2) # sum(log) = log(prod) logpdf = -d / 2 * np.log(2 * np.pi) - np.log(np.prod(sigmas)) \ - 0.5 * mahalanobis(x[:3], mus, cov_inv) ** 2 return logpdf """ Included tests are: test_cosine_regression_loss() - identical vectors - vectors with same angles - vectors at 90 degrees - vectors at 180 degrees - comparison with scipy.spatial.distance.cosine test_l2regression_loss() - identical vectors - comparison with scipy.spatial.distance.euclidean test_gaussian_loss() - x = mu - comparison with (manual + scipy) test_mixture_loss() - comparison with (manual + scipy) """ # toDo # test fisher <NAME> tol = 1e-5 def get_random_vector(size=3): scaling = np.random.randint(1, 10) return np.array(np.random.randn(size), dtype=np.float32) * scaling def prepare_tensor(a): if isinstance(a, tuple): a = tuple([torch.as_tensor(i[None, :], dtype=torch.float32) for i in a]) elif isinstance(a, np.ndarray): a = torch.as_tensor(a[None, :], dtype=torch.float32) return a def prepare_packedsequence(a): if not isinstance(a, PackedSequence): a = PackedSequence(data=(torch.as_tensor(a[None, :], dtype=torch.float32)), batch_sizes=torch.as_tensor([1])) return a def compute_loss_tensor(outputs, targets, model): outputs = prepare_tensor(outputs) targets = prepare_tensor(targets) mean_loss = model.compute_loss(outputs, targets) # print("Means loss: {}.".format(mean_loss)) return np.asarray(mean_loss) def test_cosine_regression_loss(): np.random.seed(1234) model = CosineRegressionDirectionGetter(3) print(" - Identical vectors x: expecting -1") a = np.array([1, 0, 0]) b = np.array([1, 0, 0]) expected = np.array(-1) value = compute_loss_tensor(a, b, model) assert_equal(value, expected) print(" - Identical vectors y: expecting -1") a = np.array([0, 1, 0]) b = np.array([0, 1, 0]) expected = np.array(-1) value = compute_loss_tensor(a, b, model) assert_equal(value, expected) print(" - Identical vectors z: expecting -1") a = np.array([0, 0, 1]) b = np.array([0, 0, 1]) expected = np.array(-1) value = compute_loss_tensor(a, b, model) assert_equal(value, expected) print(" - Vectors with same angle: expecting -1") scales = np.random.random(20) * 20 for s in scales: a = np.array([1, 0, 0]) b = a * s expected = np.array(-1) value = compute_loss_tensor(a, b, model) assert_equal(value, expected) print(" - Vectors with at 90 degrees 1: expecting 0") a = np.array([1, 0, 0]) b = np.array([0, 1, 0]) expected = np.array(0) value = compute_loss_tensor(a, b, model) assert_equal(value, expected) print(" - Vectors with at 90 degrees 2: expecting 0") a = np.array([1, 0, 0]) b = np.array([0, 0, 1]) expected = np.array(0) value = compute_loss_tensor(a, b, model) assert_equal(value, expected) print(" - Vectors with at 90 degrees random: expecting 0") for _ in range(20): a = get_random_vector(3) b = get_random_vector(3) c = np.cross(a, b) expected = np.array(0) value = compute_loss_tensor(a, c, model) assert np.allclose(value, expected, atol=tol), \ "Failed; got: {}; expected: {}".format(value, expected) value = compute_loss_tensor(b, c, model) assert np.allclose(value, expected, atol=tol), \ "Failed; got: {}; expected: {}".format(value, expected) print(" - Vectors with at 180 degrees random: expecting 1") for _ in range(20): a = get_random_vector(3) b = np.array(-a * (np.random.random() + 1e-3) * np.random.randint(1, 10), dtype=np.float32) expected = np.array(1) value = compute_loss_tensor(a, b, model) assert np.allclose(value, expected, atol=tol), \ "Failed; got: {}; expected: {}".format(value, expected) print(" - Random vectors: comparing with cosine.") for _ in range(200): a = get_random_vector(3) b = get_random_vector(3) # model outputs -cos(a,b), but cosine computes 1-cos(a,b) expected = cosine(a, b) - 1 value = compute_loss_tensor(a, b, model) assert np.allclose(value, expected, atol=tol), \ "Failed; got: {}; expected: {}".format(value, expected) def test_l2regression_loss(): np.random.seed(1234) model = L2RegressionDirectionGetter(1) print(" - Identical vectors: expecting 0") a = get_random_vector(3) b = a expected = np.array(0) value = compute_loss_tensor(a, b, model) assert np.allclose(value, expected, atol=tol),\ "Failed; got: {}; expected: {}".format(value, expected) # Test for random vector, compared to scipy's euclidean for _ in range(200): a = get_random_vector(3) b = get_random_vector(3) expected = euclidean(a, b) value = compute_loss_tensor(a, b, model) assert np.allclose(value, expected, atol=tol),\ "Failed; got: {}; expected: {}".format(value, expected) def test_sphere_classification_loss(): model = SphereClassificationDirectionGetter(1) sphere = get_sphere('symmetric724') print(" - Neg log likelihood, expecting -ln(softmax).") print(" - Exactly the right class.") # exactly the right class (#1) # Note. To be realistic: # With as many classes (724), the value of the output must be very # high to have a low loss. The outputs (logits) don't have to be # probabilities, as a softmax will be applied by torch. logit = np.zeros((1, 724)).astype('float32') logit[0, 1] = 100 b = sphere.vertices[1] expected = -np.log(softmax(logit))[0, 1] value = compute_loss_tensor(logit, b, model) assert np.allclose(value, expected, atol=tol), \ "Failed; got: {}; expected: {}".format(value, expected) print(" - With eps difference in the target: Should get the same " "class.") logit = np.zeros((1, 724)).astype('float32') logit[0, 1] = 1 eps = 1e-3 b = sphere.vertices[1] + eps expected = -np.log(softmax(logit))[0, 1] value = compute_loss_tensor(logit, b, model) assert np.allclose(value, expected, atol=tol), \ "Failed; got: {}; expected: {}".format(value, expected) print(" - Exactly the right class test 2.") logit = np.random.rand(1, 724).astype('float32') logit[0, 1] = 1 b = sphere.vertices[1] expected = -np.log(softmax(logit))[0, 1] value = compute_loss_tensor(logit, b, model) assert np.allclose(value, expected, atol=tol), \ "Failed; got: {}; expected: {}".format(value, expected) print(" - Random") logit = np.random.rand(1, 724).astype('float32') b = sphere.vertices[1] expected = -np.log(softmax(logit))[0, 1] value = compute_loss_tensor(logit, b, model) assert np.allclose(value, expected, atol=tol), \ "Failed; got: {}; expected: {}".format(value, expected) def test_gaussian_loss(): np.random.seed(1234) model = SingleGaussianDirectionGetter(1) print(" - Expecting mahalanobis value") print(" - x = mu") for _ in range(20): a_means = get_random_vector(3) a_sigmas = np.exp(get_random_vector(3)) b = a_means # expected: x-mu = 0 ==> mahalanobis = 0 expected = -(-3 / 2 * np.log(2 * np.pi) - np.log(np.prod(a_sigmas))) value = compute_loss_tensor((a_means, a_sigmas), b, model) assert np.allclose(value, expected, atol=tol), \ "Failed; got: {}; expected: {}".format(value, expected) print(" - random") for _ in range(200): a_means = get_random_vector(3) a_sigmas = np.exp(get_random_vector(3)) b = get_random_vector(3) # Manual logpdf computation logpdf = independent_gaussian_log_prob_vector(b, a_means, a_sigmas) expected = -logpdf value = compute_loss_tensor((a_means, a_sigmas), b, model) assert np.allclose(value, expected, atol=tol), \ "Failed; got: {}; expected: {}".format(value, expected) def test_mixture_loss(): np.random.seed(1234) model = GaussianMixtureDirectionGetter(1) print(" - Expecting neg logsumexp(log_mixture + logpdf)") print(" - Random") for _ in range(200): # 3 Gaussians * (1 mixture param + 3 means + 3 variances) # (no correlations) a_mixture_logits = get_random_vector(3) a_means = get_random_vector(3 * 3).reshape((3, 3)) a_sigmas = np.exp(get_random_vector(3 * 3)).reshape((3, 3)) b = get_random_vector(3) # Manual logpdf computation mixture_params = softmax(a_mixture_logits) logpdfs = np.array([independent_gaussian_log_prob_vector(b, a_means[i], a_sigmas[i]) for i in range(3)]) expected = -logsumexp(np.log(mixture_params) + logpdfs) value = compute_loss_tensor( (a_mixture_logits, a_means, a_sigmas), b, model) assert np.allclose(value, expected, atol=tol), \ "Failed; got: {}; expected: {}".format(value, expected) def test_fisher_von_mises(): model = FisherVonMisesDirectionGetter(1) print(" - Expecting log prob.") print(" - x = mu") a_means = get_random_vector(3) a_kappa = np.exp(get_random_vector(1)) b = a_means expected = -fisher_von_mises_log_prob_vector(a_means, a_kappa, b) value = compute_loss_tensor((a_means, a_kappa), b, model) assert np.allclose(value, expected, atol=tol), \ "Failed; got: {}; expected: {}".format(value, expected) print(" - Random") a_means = get_random_vector(3) a_kappa = np.exp(get_random_vector(1)) b = get_random_vector(3) expected = -fisher_von_mises_log_prob_vector(a_means, a_kappa, b) value = compute_loss_tensor((a_means, a_kappa), b, model) assert np.allclose(value, expected, atol=tol), \ "Failed; got: {}; expected: {}".format(value, expected) def main(): print('Testing cosine regression loss') test_cosine_regression_loss() print('\nTesting l2 regression loss') test_l2regression_loss() print('\nTesting sphere classification loss') test_sphere_classification_loss() print('\nTesting gaussian loss') test_gaussian_loss() print('\nTesting mixture loss') test_mixture_loss() print('\nTesting fisher-Von mises loss') test_fisher_von_mises() if __name__ == '__main__': main()
[ "numpy.random.seed", "dwi_ml.models.direction_getter_models.GaussianMixtureDirectionGetter", "numpy.allclose", "dipy.data.get_sphere", "scipy.spatial.distance.mahalanobis", "numpy.random.randint", "dwi_ml.models.direction_getter_models.SingleGaussianDirectionGetter", "dwi_ml.models.utils.fisher_von_mises.fisher_von_mises_log_prob_vector", "numpy.prod", "scipy.spatial.distance.euclidean", "numpy.random.randn", "dwi_ml.models.direction_getter_models.SphereClassificationDirectionGetter", "dwi_ml.models.direction_getter_models.FisherVonMisesDirectionGetter", "torch.as_tensor", "numpy.asarray", "dwi_ml.models.direction_getter_models.CosineRegressionDirectionGetter", "numpy.cross", "dwi_ml.models.direction_getter_models.L2RegressionDirectionGetter", "scipy.special.softmax", "scipy.spatial.distance.cosine", "numpy.log", "numpy.zeros", "nose.tools.assert_equal", "numpy.random.random", "numpy.array", "numpy.random.rand", "numpy.eye" ]
[((1863, 1887), 'numpy.random.randint', 'np.random.randint', (['(1)', '(10)'], {}), '(1, 10)\n', (1880, 1887), True, 'import numpy as np\n'), ((2752, 2773), 'numpy.asarray', 'np.asarray', (['mean_loss'], {}), '(mean_loss)\n', (2762, 2773), True, 'import numpy as np\n'), ((2815, 2835), 'numpy.random.seed', 'np.random.seed', (['(1234)'], {}), '(1234)\n', (2829, 2835), True, 'import numpy as np\n'), ((2848, 2882), 'dwi_ml.models.direction_getter_models.CosineRegressionDirectionGetter', 'CosineRegressionDirectionGetter', (['(3)'], {}), '(3)\n', (2879, 2882), False, 'from dwi_ml.models.direction_getter_models import CosineRegressionDirectionGetter, FisherVonMisesDirectionGetter, GaussianMixtureDirectionGetter, L2RegressionDirectionGetter, SingleGaussianDirectionGetter, SphereClassificationDirectionGetter\n'), ((2943, 2962), 'numpy.array', 'np.array', (['[1, 0, 0]'], {}), '([1, 0, 0])\n', (2951, 2962), True, 'import numpy as np\n'), ((2971, 2990), 'numpy.array', 'np.array', (['[1, 0, 0]'], {}), '([1, 0, 0])\n', (2979, 2990), True, 'import numpy as np\n'), ((3006, 3018), 'numpy.array', 'np.array', (['(-1)'], {}), '(-1)\n', (3014, 3018), True, 'import numpy as np\n'), ((3068, 3097), 'nose.tools.assert_equal', 'assert_equal', (['value', 'expected'], {}), '(value, expected)\n', (3080, 3097), False, 'from nose.tools import assert_equal\n'), ((3158, 3177), 'numpy.array', 'np.array', (['[0, 1, 0]'], {}), '([0, 1, 0])\n', (3166, 3177), True, 'import numpy as np\n'), ((3186, 3205), 'numpy.array', 'np.array', (['[0, 1, 0]'], {}), '([0, 1, 0])\n', (3194, 3205), True, 'import numpy as np\n'), ((3221, 3233), 'numpy.array', 'np.array', (['(-1)'], {}), '(-1)\n', (3229, 3233), True, 'import numpy as np\n'), ((3283, 3312), 'nose.tools.assert_equal', 'assert_equal', (['value', 'expected'], {}), '(value, expected)\n', (3295, 3312), False, 'from nose.tools import assert_equal\n'), ((3373, 3392), 'numpy.array', 'np.array', (['[0, 0, 1]'], {}), '([0, 0, 1])\n', (3381, 3392), True, 'import numpy as np\n'), ((3401, 3420), 'numpy.array', 'np.array', (['[0, 0, 1]'], {}), '([0, 0, 1])\n', (3409, 3420), True, 'import numpy as np\n'), ((3436, 3448), 'numpy.array', 'np.array', (['(-1)'], {}), '(-1)\n', (3444, 3448), True, 'import numpy as np\n'), ((3498, 3527), 'nose.tools.assert_equal', 'assert_equal', (['value', 'expected'], {}), '(value, expected)\n', (3510, 3527), False, 'from nose.tools import assert_equal\n'), ((3881, 3900), 'numpy.array', 'np.array', (['[1, 0, 0]'], {}), '([1, 0, 0])\n', (3889, 3900), True, 'import numpy as np\n'), ((3909, 3928), 'numpy.array', 'np.array', (['[0, 1, 0]'], {}), '([0, 1, 0])\n', (3917, 3928), True, 'import numpy as np\n'), ((3944, 3955), 'numpy.array', 'np.array', (['(0)'], {}), '(0)\n', (3952, 3955), True, 'import numpy as np\n'), ((4005, 4034), 'nose.tools.assert_equal', 'assert_equal', (['value', 'expected'], {}), '(value, expected)\n', (4017, 4034), False, 'from nose.tools import assert_equal\n'), ((4103, 4122), 'numpy.array', 'np.array', (['[1, 0, 0]'], {}), '([1, 0, 0])\n', (4111, 4122), True, 'import numpy as np\n'), ((4131, 4150), 'numpy.array', 'np.array', (['[0, 0, 1]'], {}), '([0, 0, 1])\n', (4139, 4150), True, 'import numpy as np\n'), ((4166, 4177), 'numpy.array', 'np.array', (['(0)'], {}), '(0)\n', (4174, 4177), True, 'import numpy as np\n'), ((4227, 4256), 'nose.tools.assert_equal', 'assert_equal', (['value', 'expected'], {}), '(value, expected)\n', (4239, 4256), False, 'from nose.tools import assert_equal\n'), ((5731, 5751), 'numpy.random.seed', 'np.random.seed', (['(1234)'], {}), '(1234)\n', (5745, 5751), True, 'import numpy as np\n'), ((5764, 5794), 'dwi_ml.models.direction_getter_models.L2RegressionDirectionGetter', 'L2RegressionDirectionGetter', (['(1)'], {}), '(1)\n', (5791, 5794), False, 'from dwi_ml.models.direction_getter_models import CosineRegressionDirectionGetter, FisherVonMisesDirectionGetter, GaussianMixtureDirectionGetter, L2RegressionDirectionGetter, SingleGaussianDirectionGetter, SphereClassificationDirectionGetter\n'), ((5898, 5909), 'numpy.array', 'np.array', (['(0)'], {}), '(0)\n', (5906, 5909), True, 'import numpy as np\n'), ((5966, 6004), 'numpy.allclose', 'np.allclose', (['value', 'expected'], {'atol': 'tol'}), '(value, expected, atol=tol)\n', (5977, 6004), True, 'import numpy as np\n'), ((6484, 6522), 'dwi_ml.models.direction_getter_models.SphereClassificationDirectionGetter', 'SphereClassificationDirectionGetter', (['(1)'], {}), '(1)\n', (6519, 6522), False, 'from dwi_ml.models.direction_getter_models import CosineRegressionDirectionGetter, FisherVonMisesDirectionGetter, GaussianMixtureDirectionGetter, L2RegressionDirectionGetter, SingleGaussianDirectionGetter, SphereClassificationDirectionGetter\n'), ((6536, 6562), 'dipy.data.get_sphere', 'get_sphere', (['"""symmetric724"""'], {}), "('symmetric724')\n", (6546, 6562), False, 'from dipy.data import get_sphere\n'), ((7139, 7177), 'numpy.allclose', 'np.allclose', (['value', 'expected'], {'atol': 'tol'}), '(value, expected, atol=tol)\n', (7150, 7177), True, 'import numpy as np\n'), ((7564, 7602), 'numpy.allclose', 'np.allclose', (['value', 'expected'], {'atol': 'tol'}), '(value, expected, atol=tol)\n', (7575, 7602), True, 'import numpy as np\n'), ((7929, 7967), 'numpy.allclose', 'np.allclose', (['value', 'expected'], {'atol': 'tol'}), '(value, expected, atol=tol)\n', (7940, 7967), True, 'import numpy as np\n'), ((8249, 8287), 'numpy.allclose', 'np.allclose', (['value', 'expected'], {'atol': 'tol'}), '(value, expected, atol=tol)\n', (8260, 8287), True, 'import numpy as np\n'), ((8387, 8407), 'numpy.random.seed', 'np.random.seed', (['(1234)'], {}), '(1234)\n', (8401, 8407), True, 'import numpy as np\n'), ((8420, 8452), 'dwi_ml.models.direction_getter_models.SingleGaussianDirectionGetter', 'SingleGaussianDirectionGetter', (['(1)'], {}), '(1)\n', (8449, 8452), False, 'from dwi_ml.models.direction_getter_models import CosineRegressionDirectionGetter, FisherVonMisesDirectionGetter, GaussianMixtureDirectionGetter, L2RegressionDirectionGetter, SingleGaussianDirectionGetter, SphereClassificationDirectionGetter\n'), ((9517, 9537), 'numpy.random.seed', 'np.random.seed', (['(1234)'], {}), '(1234)\n', (9531, 9537), True, 'import numpy as np\n'), ((9550, 9583), 'dwi_ml.models.direction_getter_models.GaussianMixtureDirectionGetter', 'GaussianMixtureDirectionGetter', (['(1)'], {}), '(1)\n', (9580, 9583), False, 'from dwi_ml.models.direction_getter_models import CosineRegressionDirectionGetter, FisherVonMisesDirectionGetter, GaussianMixtureDirectionGetter, L2RegressionDirectionGetter, SingleGaussianDirectionGetter, SphereClassificationDirectionGetter\n'), ((10629, 10661), 'dwi_ml.models.direction_getter_models.FisherVonMisesDirectionGetter', 'FisherVonMisesDirectionGetter', (['(1)'], {}), '(1)\n', (10658, 10661), False, 'from dwi_ml.models.direction_getter_models import CosineRegressionDirectionGetter, FisherVonMisesDirectionGetter, GaussianMixtureDirectionGetter, L2RegressionDirectionGetter, SingleGaussianDirectionGetter, SphereClassificationDirectionGetter\n'), ((10967, 11005), 'numpy.allclose', 'np.allclose', (['value', 'expected'], {'atol': 'tol'}), '(value, expected, atol=tol)\n', (10978, 11005), True, 'import numpy as np\n'), ((11353, 11391), 'numpy.allclose', 'np.allclose', (['value', 'expected'], {'atol': 'tol'}), '(value, expected, atol=tol)\n', (11364, 11391), True, 'import numpy as np\n'), ((1057, 1066), 'numpy.eye', 'np.eye', (['d'], {}), '(d)\n', (1063, 1066), True, 'import numpy as np\n'), ((3597, 3617), 'numpy.random.random', 'np.random.random', (['(20)'], {}), '(20)\n', (3613, 3617), True, 'import numpy as np\n'), ((3656, 3675), 'numpy.array', 'np.array', (['[1, 0, 0]'], {}), '([1, 0, 0])\n', (3664, 3675), True, 'import numpy as np\n'), ((3713, 3725), 'numpy.array', 'np.array', (['(-1)'], {}), '(-1)\n', (3721, 3725), True, 'import numpy as np\n'), ((3783, 3812), 'nose.tools.assert_equal', 'assert_equal', (['value', 'expected'], {}), '(value, expected)\n', (3795, 3812), False, 'from nose.tools import assert_equal\n'), ((4424, 4438), 'numpy.cross', 'np.cross', (['a', 'b'], {}), '(a, b)\n', (4432, 4438), True, 'import numpy as np\n'), ((4458, 4469), 'numpy.array', 'np.array', (['(0)'], {}), '(0)\n', (4466, 4469), True, 'import numpy as np\n'), ((4535, 4573), 'numpy.allclose', 'np.allclose', (['value', 'expected'], {'atol': 'tol'}), '(value, expected, atol=tol)\n', (4546, 4573), True, 'import numpy as np\n'), ((4710, 4748), 'numpy.allclose', 'np.allclose', (['value', 'expected'], {'atol': 'tol'}), '(value, expected, atol=tol)\n', (4721, 4748), True, 'import numpy as np\n'), ((5083, 5094), 'numpy.array', 'np.array', (['(1)'], {}), '(1)\n', (5091, 5094), True, 'import numpy as np\n'), ((5160, 5198), 'numpy.allclose', 'np.allclose', (['value', 'expected'], {'atol': 'tol'}), '(value, expected, atol=tol)\n', (5171, 5198), True, 'import numpy as np\n'), ((5585, 5623), 'numpy.allclose', 'np.allclose', (['value', 'expected'], {'atol': 'tol'}), '(value, expected, atol=tol)\n', (5596, 5623), True, 'import numpy as np\n'), ((6242, 6257), 'scipy.spatial.distance.euclidean', 'euclidean', (['a', 'b'], {}), '(a, b)\n', (6251, 6257), False, 'from scipy.spatial.distance import cosine, euclidean, mahalanobis\n'), ((6322, 6360), 'numpy.allclose', 'np.allclose', (['value', 'expected'], {'atol': 'tol'}), '(value, expected, atol=tol)\n', (6333, 6360), True, 'import numpy as np\n'), ((8869, 8907), 'numpy.allclose', 'np.allclose', (['value', 'expected'], {'atol': 'tol'}), '(value, expected, atol=tol)\n', (8880, 8907), True, 'import numpy as np\n'), ((9376, 9414), 'numpy.allclose', 'np.allclose', (['value', 'expected'], {'atol': 'tol'}), '(value, expected, atol=tol)\n', (9387, 9414), True, 'import numpy as np\n'), ((10066, 10091), 'scipy.special.softmax', 'softmax', (['a_mixture_logits'], {}), '(a_mixture_logits)\n', (10073, 10091), False, 'from scipy.special import logsumexp, softmax\n'), ((10476, 10514), 'numpy.allclose', 'np.allclose', (['value', 'expected'], {'atol': 'tol'}), '(value, expected, atol=tol)\n', (10487, 10514), True, 'import numpy as np\n'), ((10840, 10893), 'dwi_ml.models.utils.fisher_von_mises.fisher_von_mises_log_prob_vector', 'fisher_von_mises_log_prob_vector', (['a_means', 'a_kappa', 'b'], {}), '(a_means, a_kappa, b)\n', (10872, 10893), False, 'from dwi_ml.models.utils.fisher_von_mises import fisher_von_mises_log_prob_vector\n'), ((11226, 11279), 'dwi_ml.models.utils.fisher_von_mises.fisher_von_mises_log_prob_vector', 'fisher_von_mises_log_prob_vector', (['a_means', 'a_kappa', 'b'], {}), '(a_means, a_kappa, b)\n', (11258, 11279), False, 'from dwi_ml.models.utils.fisher_von_mises import fisher_von_mises_log_prob_vector\n'), ((1908, 1929), 'numpy.random.randn', 'np.random.randn', (['size'], {}), '(size)\n', (1923, 1929), True, 'import numpy as np\n'), ((2161, 2209), 'torch.as_tensor', 'torch.as_tensor', (['a[None, :]'], {'dtype': 'torch.float32'}), '(a[None, :], dtype=torch.float32)\n', (2176, 2209), False, 'import torch\n'), ((5503, 5515), 'scipy.spatial.distance.cosine', 'cosine', (['a', 'b'], {}), '(a, b)\n', (5509, 5515), False, 'from scipy.spatial.distance import cosine, euclidean, mahalanobis\n'), ((6948, 6966), 'numpy.zeros', 'np.zeros', (['(1, 724)'], {}), '((1, 724))\n', (6956, 6966), True, 'import numpy as np\n'), ((7354, 7372), 'numpy.zeros', 'np.zeros', (['(1, 724)'], {}), '((1, 724))\n', (7362, 7372), True, 'import numpy as np\n'), ((7736, 7758), 'numpy.random.rand', 'np.random.rand', (['(1)', '(724)'], {}), '(1, 724)\n', (7750, 7758), True, 'import numpy as np\n'), ((8076, 8098), 'numpy.random.rand', 'np.random.rand', (['(1)', '(724)'], {}), '(1, 724)\n', (8090, 8098), True, 'import numpy as np\n'), ((1137, 1154), 'numpy.log', 'np.log', (['(2 * np.pi)'], {}), '(2 * np.pi)\n', (1143, 1154), True, 'import numpy as np\n'), ((1164, 1179), 'numpy.prod', 'np.prod', (['sigmas'], {}), '(sigmas)\n', (1171, 1179), True, 'import numpy as np\n'), ((1204, 1236), 'scipy.spatial.distance.mahalanobis', 'mahalanobis', (['x[:3]', 'mus', 'cov_inv'], {}), '(x[:3], mus, cov_inv)\n', (1215, 1236), False, 'from scipy.spatial.distance import cosine, euclidean, mahalanobis\n'), ((2032, 2080), 'torch.as_tensor', 'torch.as_tensor', (['i[None, :]'], {'dtype': 'torch.float32'}), '(i[None, :], dtype=torch.float32)\n', (2047, 2080), False, 'import torch\n'), ((2331, 2379), 'torch.as_tensor', 'torch.as_tensor', (['a[None, :]'], {'dtype': 'torch.float32'}), '(a[None, :], dtype=torch.float32)\n', (2346, 2379), False, 'import torch\n'), ((2470, 2490), 'torch.as_tensor', 'torch.as_tensor', (['[1]'], {}), '([1])\n', (2485, 2490), False, 'import torch\n'), ((5020, 5044), 'numpy.random.randint', 'np.random.randint', (['(1)', '(10)'], {}), '(1, 10)\n', (5037, 5044), True, 'import numpy as np\n'), ((7057, 7071), 'scipy.special.softmax', 'softmax', (['logit'], {}), '(logit)\n', (7064, 7071), False, 'from scipy.special import logsumexp, softmax\n'), ((7482, 7496), 'scipy.special.softmax', 'softmax', (['logit'], {}), '(logit)\n', (7489, 7496), False, 'from scipy.special import logsumexp, softmax\n'), ((7847, 7861), 'scipy.special.softmax', 'softmax', (['logit'], {}), '(logit)\n', (7854, 7861), False, 'from scipy.special import logsumexp, softmax\n'), ((8167, 8181), 'scipy.special.softmax', 'softmax', (['logit'], {}), '(logit)\n', (8174, 8181), False, 'from scipy.special import logsumexp, softmax\n'), ((8739, 8756), 'numpy.log', 'np.log', (['(2 * np.pi)'], {}), '(2 * np.pi)\n', (8745, 8756), True, 'import numpy as np\n'), ((8766, 8783), 'numpy.prod', 'np.prod', (['a_sigmas'], {}), '(a_sigmas)\n', (8773, 8783), True, 'import numpy as np\n'), ((10328, 10350), 'numpy.log', 'np.log', (['mixture_params'], {}), '(mixture_params)\n', (10334, 10350), True, 'import numpy as np\n'), ((4970, 4988), 'numpy.random.random', 'np.random.random', ([], {}), '()\n', (4986, 4988), True, 'import numpy as np\n')]
''' Using code learnt from https://www.datacamp.com/community/tutorials ''' from sklearn import datasets, svm, metrics import numpy as np import matplotlib.pyplot as plt import random from sklearn.model_selection import train_test_split # import minst dataset b = datasets.load_digits() # print out the number and labels name print(f'There are {len(b.target_names)} labels names') print(f'These names are :\n {b.target_names}\n') number_of_examples = b.data.shape[0] print(f'The number of examples are {number_of_examples}') # Show a random single image random_selection = random.randint(0, number_of_examples) img = b.data[random_selection].reshape([8, 8]) / 16 col_map = plt.get_cmap('gray') plt.imshow(img, cmap=col_map) plt.show() # select just a few pixels create a random boolean mask boolean_mask = np.random.choice(a=[False, True], size=64) def get_mod_x(data,mask): mod_x = [] for d in data: mod_x.append(d[mask]) return mod_x def do_training_and_predicting(data, labels): # split the data set into training (80%) and test set(20%) x_train, x_test, y_train, y_test = train_test_split(data, labels, test_size=0.2, random_state=109) clf = svm.SVC(gamma='auto') clf.fit(x_train, y_train) y_pred = clf.predict(x_test) # Import sklearn.metrics to model accuracy return metrics.accuracy_score(y_test, y_pred) do_training_and_predicting(b.data, b.target) do_training_and_predicting(get_mod_x(b.data, boolean_mask), b.target) # try do GA population masks Initialise pop_size = 10 elitism = 5 count = 0 solution_found = False population = [] pop_X = [] for i in range(pop_size): population.append(np.random.choice(a=[False, True], size=64)) while not solution_found and count < 10: result = [] for i in range(10): result.append(do_training_and_predicting(get_mod_x(b.data, population[i]), b.target)) # we keep top elitism_idx = np.argsort(result[-elitism:]) new_population = [] for i in elitism_idx: new_population.append(population[i]) for i in range(pop_size - elitism): new_population.append(np.random.choice(a=[False, True], size=64)) population = new_population print(f' best result = {result[np.argsort(result)[-1]]}') print(f'\n\n generation {count}\n\n') count = count + 1
[ "sklearn.datasets.load_digits", "matplotlib.pyplot.show", "matplotlib.pyplot.get_cmap", "random.randint", "sklearn.svm.SVC", "matplotlib.pyplot.imshow", "sklearn.model_selection.train_test_split", "sklearn.metrics.accuracy_score", "numpy.argsort", "numpy.random.choice" ]
[((268, 290), 'sklearn.datasets.load_digits', 'datasets.load_digits', ([], {}), '()\n', (288, 290), False, 'from sklearn import datasets, svm, metrics\n'), ((580, 617), 'random.randint', 'random.randint', (['(0)', 'number_of_examples'], {}), '(0, number_of_examples)\n', (594, 617), False, 'import random\n'), ((680, 700), 'matplotlib.pyplot.get_cmap', 'plt.get_cmap', (['"""gray"""'], {}), "('gray')\n", (692, 700), True, 'import matplotlib.pyplot as plt\n'), ((701, 730), 'matplotlib.pyplot.imshow', 'plt.imshow', (['img'], {'cmap': 'col_map'}), '(img, cmap=col_map)\n', (711, 730), True, 'import matplotlib.pyplot as plt\n'), ((731, 741), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (739, 741), True, 'import matplotlib.pyplot as plt\n'), ((814, 856), 'numpy.random.choice', 'np.random.choice', ([], {'a': '[False, True]', 'size': '(64)'}), '(a=[False, True], size=64)\n', (830, 856), True, 'import numpy as np\n'), ((1116, 1179), 'sklearn.model_selection.train_test_split', 'train_test_split', (['data', 'labels'], {'test_size': '(0.2)', 'random_state': '(109)'}), '(data, labels, test_size=0.2, random_state=109)\n', (1132, 1179), False, 'from sklearn.model_selection import train_test_split\n'), ((1190, 1211), 'sklearn.svm.SVC', 'svm.SVC', ([], {'gamma': '"""auto"""'}), "(gamma='auto')\n", (1197, 1211), False, 'from sklearn import datasets, svm, metrics\n'), ((1333, 1371), 'sklearn.metrics.accuracy_score', 'metrics.accuracy_score', (['y_test', 'y_pred'], {}), '(y_test, y_pred)\n', (1355, 1371), False, 'from sklearn import datasets, svm, metrics\n'), ((1922, 1951), 'numpy.argsort', 'np.argsort', (['result[-elitism:]'], {}), '(result[-elitism:])\n', (1932, 1951), True, 'import numpy as np\n'), ((1665, 1707), 'numpy.random.choice', 'np.random.choice', ([], {'a': '[False, True]', 'size': '(64)'}), '(a=[False, True], size=64)\n', (1681, 1707), True, 'import numpy as np\n'), ((2117, 2159), 'numpy.random.choice', 'np.random.choice', ([], {'a': '[False, True]', 'size': '(64)'}), '(a=[False, True], size=64)\n', (2133, 2159), True, 'import numpy as np\n'), ((2228, 2246), 'numpy.argsort', 'np.argsort', (['result'], {}), '(result)\n', (2238, 2246), True, 'import numpy as np\n')]
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import os import pickle import sys import matplotlib.pyplot as plt import numpy as np from matplotlib import gridspec # TODO: store in pandas dataframe class Journal: """Journal. Class for representing the Hodgkin-Huxley model. All model parameters can be accessed (get or set) as class attributes. The following solutions are available as class attributes after calling the class method `solve`: Attributes ---------- t : array_like The time array of the spike. V : array_like The voltage array of the spike. """ def __init__(self): """Define the model parameters. Parameters ---------- V_rest : float, default: -65. Resting potential of neuron in units: mV Cm : float, default: 1. Membrane capacitance in units: μF/cm**2 gbar_K : float, default: 36. Potassium conductance in units: mS/cm**2 gbar_Na : float, default: 120. Sodium conductance in units: mS/cm**2 gbar_L : float, default: 0.3. Leak conductance in units: mS/cm**2 E_K : float, default: -77. Potassium reversal potential in units: mV E_Na : float, default: 50. Sodium reversal potential in units: mV E_L : float, default: -54.4 Leak reversal potential in units: mV Notes ----- Default parameter values as given by Hodgkin and Huxley (1952). """ self.accepted_parameters = {} self.parameter_names = [] self.parameter_names_tex = [] self.labels = [] self.distances = [] self.sumstats = [] self._n_parameters = 0 self.configuration = {} self.sampler_summary = {} self._journal_started = False def _start_journal(self): self._journal_started = True def _check_journal_status(self): if not self._journal_started: msg = "Journal unavailable; run an inference scheme first" raise ValueError(msg) def _check_true_parameter_values(self, true_parameter_values): if not isinstance(true_parameter_values, list): msg = "True parameter values must be provided in a list" raise ValueError(msg) if self._n_parameters != len(true_parameter_values): msg = "The number of true parameter values in list must equal the number of inferred parameters." raise ValueError(msg) def _add_config(self, simulator, inference_scheme, distance, n_simulations, epsilon): """ docs """ self.configuration["Simulator model"] = simulator.__name__ self.configuration["Inference scheme"] = inference_scheme self.configuration["Distance metric"] = distance.__name__ self.configuration["Number of simulations"] = n_simulations self.configuration["Epsilon"] = epsilon def _add_parameter_names(self, priors): for parameter in priors: name = parameter.name tex = parameter.tex self.parameter_names.append(name) self.accepted_parameters[name] = [] self.parameter_names_tex.append(tex) self._n_parameters += 1 if tex is None: self.labels.append(name) else: self.labels.append(tex) def _add_accepted_parameters(self, thetas): """ docs """ for parameter_name, theta in zip(self.parameter_names, thetas): self.accepted_parameters[parameter_name].append(theta) def _add_distance(self, distance): """ docs """ self.distances.append(distance) def _add_sumstat(self, sumstat): """ docs """ self.sumstats.append(sumstat) def _add_sampler_summary(self, number_of_simulations, accepted_count): """ docs """ accept_ratio = accepted_count / number_of_simulations # number of parameters estimated self.sampler_summary["Number of simulations"] = number_of_simulations self.sampler_summary["Number of accepted simulations"] = accepted_count self.sampler_summary["Acceptance ratio"] = accept_ratio # posterior means # uncertainty @property def get_accepted_parameters(self): """ docs """ return self.accepted_parameters def _get_params_as_arrays(self): """ Transform data of accepted parameters to 1D arrays """ samples = self.get_accepted_parameters if len(self.parameter_names) > 1: params = (np.asarray(samples[name], float).squeeze() if np.asarray( samples[name], float).ndim > 1 else np.asarray(samples[name], float) for name in self.parameter_names) else: samples = np.asarray(samples[self.parameter_names[0]], float) params = samples.squeeze() if samples.ndim > 1 else samples return params def _point_estimates(self): """ Calculate point estimate of inferred parameters """ *samples, = self._get_params_as_arrays() if self._n_parameters == 1: point_estimates = [np.mean(samples)] else: point_estimates = [np.mean(sample) for sample in samples] return point_estimates @property def get_distances(self): """ docs """ self._check_journal_status() return self.distances @property def get_number_of_simulations(self): self._check_journal_status() return self.sampler_summary["Number of simulations"] @property def get_number_of_accepted_simulations(self): self._check_journal_status() return self.sampler_summary["Number of accepted simulations"] @property def get_acceptance_ratio(self): self._check_journal_status() return self.sampler_summary["Acceptance ratio"] def _samples(self, name): pass def _kde(self): pass def _set_plot_style(self): params = {'legend.fontsize': 'large', 'axes.labelsize': 'large', 'axes.titlesize': 'large', 'xtick.labelsize': 'large', 'ytick.labelsize': 'large', 'legend.fontsize': 'large', 'legend.handlelength': 2} plt.rcParams.update(params) plt.rc('text', usetex=True) ''' def _add_histplot(self, data, ax, index, density, point_estimates, true_vals_bool, true_parameter_values): n_bins = self._freedman_diaconis_rule(data) ax.hist(data, density=density, histtype='bar', edgecolor=None, color='steelblue', alpha=0.5, bins=n_bins, label="Accepted samples") ax.axvline( point_estimates[index], color='b', label="Point estimate") if true_vals_bool: ax.axvline( true_parameter_values[index], color='r', linestyle='--', label="Groundtruth") ax.set_xlabel(self.labels[index]) ax.set_title("Histogram of accepted " + self.labels[index]) ''' def histplot(self, density=True, show=True, dpi=120, path_to_save=None, true_parameter_values=None): """ histogram(s) of sampled parameter(s) """ # run checks self._check_journal_status() true_vals_bool = False if true_parameter_values is not None: self._check_true_parameter_values(true_parameter_values) true_vals_bool = True # get sampled parameters *data, = self._get_params_as_arrays() point_estimates = self._point_estimates() fig = plt.figure(figsize=(8, 6), tight_layout=True, dpi=dpi) self._set_plot_style() N = self._n_parameters if N == 1: ax = plt.subplot(111) legend_position = 0 index = 0 self._add_histplot( data, ax, index, density, point_estimates, true_vals_bool, true_parameter_values) else: if N == 2 or N == 4: cols = 2 legend_position = 1 else: cols = 3 legend_position = 2 rows = int(np.ceil(N / cols)) gs = gridspec.GridSpec(ncols=cols, nrows=rows, figure=fig) for index, data in enumerate(data): ax = fig.add_subplot(gs[index]) self._add_histplot( data, ax, index, density, point_estimates, true_vals_bool, true_parameter_values) handles, labels = plt.gca().get_legend_handles_labels() if true_vals_bool: order = [2, 0, 1] else: order = [1, 0] plt.legend([handles[idx] for idx in order], [labels[idx] for idx in order], loc='center left', bbox_to_anchor=(1.04, 0.5), fancybox=True, borderaxespad=0.1, ncol=1 ) if path_to_save is not None: fig.savefig(path_to_save, dpi=dpi) if show: plt.show() def adjusted_histplot(): # regression adjusted pass def kdeplot(self, kernel="gaussian"): ax[1].plot(x, kernel.evaluate(x), label="approximate posterior") pass def distplot(self, kde=True, kde_kwds=None, ax=None): """ """ if ax is None: ax = plt.gca() pass def posterior_kde(self, kernel="gaussian"): pass @ property def summary(self): pass @ property def print_summary(self): pass def save(self, filename): """ Stores the journal to disk. Parameters ---------- filename: string the location of the file to store the current object to. """ with open(filename, 'wb') as output: pickle.dump(self, output, -1) def load(self, filename): with open(filename, 'rb') as input: journal = pickle.load(input) return journal ''' @staticmethod def run_lra( theta: torch.Tensor, x: torch.Tensor, observation: torch.Tensor, sample_weight=None, ) -> torch.Tensor: """Return parameters adjusted with linear regression adjustment. Implementation as in Beaumont et al. 2002: https://arxiv.org/abs/1707.01254 """ theta_adjusted = theta for parameter_idx in range(theta.shape[1]): regression_model = LinearRegression(fit_intercept=True) regression_model.fit( X=x, y=theta[:, parameter_idx], sample_weight=sample_weight, ) theta_adjusted[:, parameter_idx] += regression_model.predict( observation.reshape(1, -1) ) theta_adjusted[:, parameter_idx] -= regression_model.predict(x) return theta_adjusted '''
[ "matplotlib.pyplot.subplot", "pickle.dump", "matplotlib.pyplot.show", "numpy.ceil", "numpy.asarray", "matplotlib.pyplot.legend", "matplotlib.pyplot.figure", "matplotlib.pyplot.rcParams.update", "pickle.load", "matplotlib.pyplot.rc", "numpy.mean", "matplotlib.pyplot.gca", "matplotlib.gridspec.GridSpec" ]
[((6530, 6557), 'matplotlib.pyplot.rcParams.update', 'plt.rcParams.update', (['params'], {}), '(params)\n', (6549, 6557), True, 'import matplotlib.pyplot as plt\n'), ((6566, 6593), 'matplotlib.pyplot.rc', 'plt.rc', (['"""text"""'], {'usetex': '(True)'}), "('text', usetex=True)\n", (6572, 6593), True, 'import matplotlib.pyplot as plt\n'), ((7834, 7888), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(8, 6)', 'tight_layout': '(True)', 'dpi': 'dpi'}), '(figsize=(8, 6), tight_layout=True, dpi=dpi)\n', (7844, 7888), True, 'import matplotlib.pyplot as plt\n'), ((8896, 9068), 'matplotlib.pyplot.legend', 'plt.legend', (['[handles[idx] for idx in order]', '[labels[idx] for idx in order]'], {'loc': '"""center left"""', 'bbox_to_anchor': '(1.04, 0.5)', 'fancybox': '(True)', 'borderaxespad': '(0.1)', 'ncol': '(1)'}), "([handles[idx] for idx in order], [labels[idx] for idx in order],\n loc='center left', bbox_to_anchor=(1.04, 0.5), fancybox=True,\n borderaxespad=0.1, ncol=1)\n", (8906, 9068), True, 'import matplotlib.pyplot as plt\n'), ((4968, 5019), 'numpy.asarray', 'np.asarray', (['samples[self.parameter_names[0]]', 'float'], {}), '(samples[self.parameter_names[0]], float)\n', (4978, 5019), True, 'import numpy as np\n'), ((7989, 8005), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(111)'], {}), '(111)\n', (8000, 8005), True, 'import matplotlib.pyplot as plt\n'), ((8436, 8489), 'matplotlib.gridspec.GridSpec', 'gridspec.GridSpec', ([], {'ncols': 'cols', 'nrows': 'rows', 'figure': 'fig'}), '(ncols=cols, nrows=rows, figure=fig)\n', (8453, 8489), False, 'from matplotlib import gridspec\n'), ((9309, 9319), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (9317, 9319), True, 'import matplotlib.pyplot as plt\n'), ((9645, 9654), 'matplotlib.pyplot.gca', 'plt.gca', ([], {}), '()\n', (9652, 9654), True, 'import matplotlib.pyplot as plt\n'), ((10122, 10151), 'pickle.dump', 'pickle.dump', (['self', 'output', '(-1)'], {}), '(self, output, -1)\n', (10133, 10151), False, 'import pickle\n'), ((10249, 10267), 'pickle.load', 'pickle.load', (['input'], {}), '(input)\n', (10260, 10267), False, 'import pickle\n'), ((5343, 5359), 'numpy.mean', 'np.mean', (['samples'], {}), '(samples)\n', (5350, 5359), True, 'import numpy as np\n'), ((5406, 5421), 'numpy.mean', 'np.mean', (['sample'], {}), '(sample)\n', (5413, 5421), True, 'import numpy as np\n'), ((8400, 8417), 'numpy.ceil', 'np.ceil', (['(N / cols)'], {}), '(N / cols)\n', (8407, 8417), True, 'import numpy as np\n'), ((8751, 8760), 'matplotlib.pyplot.gca', 'plt.gca', ([], {}), '()\n', (8758, 8760), True, 'import matplotlib.pyplot as plt\n'), ((4865, 4897), 'numpy.asarray', 'np.asarray', (['samples[name]', 'float'], {}), '(samples[name], float)\n', (4875, 4897), True, 'import numpy as np\n'), ((4801, 4833), 'numpy.asarray', 'np.asarray', (['samples[name]', 'float'], {}), '(samples[name], float)\n', (4811, 4833), True, 'import numpy as np\n'), ((4755, 4787), 'numpy.asarray', 'np.asarray', (['samples[name]', 'float'], {}), '(samples[name], float)\n', (4765, 4787), True, 'import numpy as np\n')]
#!/usr/bin/python #-*- coding:utf-8 -*- import sys import struct import numpy as np import tensorflow as tf import random def matmul_f32(): para = [] dim0 = [] dim1 = [] # init the input data and parameters dim_count = int(np.random.randint(4, high=6, size=1)) for i in range(0, dim_count-2): in_size = int(np.random.randint(1, high=16, size=1)) dim0.append(in_size) dim1.append(in_size) zero_point1 = int(np.random.randint(-6, high=6, size=1)) std1 = int(np.random.randint(1, high=20, size=1)) zero_point2 = int(np.random.randint(-6, high=6, size=1)) std2 = int(np.random.randint(1, high=20, size=1)) trans_a_flag = False trans_b_flag = False in_sizei = int(np.random.randint(1, high=32, size=1)) in_sizek = int(np.random.randint(1, high=32, size=1)) in_sizej = int(np.random.randint(1, high=32, size=1)) trans_a = random.choice((0, 1)) trans_b = random.choice((0, 1)) if (trans_a == 0 and trans_b == 0): dim0.append(in_sizei) dim0.append(in_sizek) dim1.append(in_sizek) dim1.append(in_sizej) elif(trans_a == 1 and trans_b == 0): dim0.append(in_sizek) dim0.append(in_sizei) dim1.append(in_sizek) dim1.append(in_sizej) trans_a_flag = True elif (trans_a == 0 and trans_b == 1): dim0.append(in_sizei) dim0.append(in_sizek) dim1.append(in_sizej) dim1.append(in_sizek) trans_b_flag = True else: dim0.append(in_sizek) dim0.append(in_sizei) dim1.append(in_sizej) dim1.append(in_sizek) trans_a_flag = True trans_b_flag = True src_in0 = np.random.normal(zero_point1, std1, size=dim0) src_in1 = np.random.normal(zero_point2, std2, size=dim1) src_in0 = src_in0.astype(np.float32) src_in1 = src_in1.astype(np.float32) out_calcu = tf.matmul(src_in0, src_in1, transpose_a=trans_a_flag, transpose_b=trans_b_flag) sess = tf.Session() src_out = sess.run(out_calcu) src_in_0 = src_in0.flatten() src_in_1 = src_in1.flatten() src_out_1 = src_out.flatten() total_size = len(src_in_0) + len(src_in_1) + len(src_out_1) + 3 * len(dim0) + 3 para.append(total_size) para.append(trans_a) para.append(trans_b) para.append(len(dim0)) with open("matmul_data_f32.bin", "wb") as fp: data = struct.pack(('%di' % len(para)), *para) fp.write(data) data = struct.pack(('%di' % len(dim0)), *dim0) fp.write(data) data = struct.pack(('%di' % len(dim1)), *dim1) fp.write(data) data = struct.pack(('%di' % len(np.shape(src_out))), *np.shape(src_out)) fp.write(data) data = struct.pack(('%df' % len(src_in_0)), *src_in_0) fp.write(data) data = struct.pack(('%df' % len(src_in_1)), *src_in_1) fp.write(data) data = struct.pack(('%df' % len(src_out_1)), *src_out_1) fp.write(data) fp.close() return 0 if __name__ == '__main__': matmul_f32() print("end")
[ "tensorflow.Session", "random.choice", "numpy.shape", "tensorflow.matmul", "numpy.random.randint", "numpy.random.normal" ]
[((926, 947), 'random.choice', 'random.choice', (['(0, 1)'], {}), '((0, 1))\n', (939, 947), False, 'import random\n'), ((962, 983), 'random.choice', 'random.choice', (['(0, 1)'], {}), '((0, 1))\n', (975, 983), False, 'import random\n'), ((1724, 1770), 'numpy.random.normal', 'np.random.normal', (['zero_point1', 'std1'], {'size': 'dim0'}), '(zero_point1, std1, size=dim0)\n', (1740, 1770), True, 'import numpy as np\n'), ((1785, 1831), 'numpy.random.normal', 'np.random.normal', (['zero_point2', 'std2'], {'size': 'dim1'}), '(zero_point2, std2, size=dim1)\n', (1801, 1831), True, 'import numpy as np\n'), ((1931, 2010), 'tensorflow.matmul', 'tf.matmul', (['src_in0', 'src_in1'], {'transpose_a': 'trans_a_flag', 'transpose_b': 'trans_b_flag'}), '(src_in0, src_in1, transpose_a=trans_a_flag, transpose_b=trans_b_flag)\n', (1940, 2010), True, 'import tensorflow as tf\n'), ((2022, 2034), 'tensorflow.Session', 'tf.Session', ([], {}), '()\n', (2032, 2034), True, 'import tensorflow as tf\n'), ((247, 283), 'numpy.random.randint', 'np.random.randint', (['(4)'], {'high': '(6)', 'size': '(1)'}), '(4, high=6, size=1)\n', (264, 283), True, 'import numpy as np\n'), ((463, 500), 'numpy.random.randint', 'np.random.randint', (['(-6)'], {'high': '(6)', 'size': '(1)'}), '(-6, high=6, size=1)\n', (480, 500), True, 'import numpy as np\n'), ((524, 561), 'numpy.random.randint', 'np.random.randint', (['(1)'], {'high': '(20)', 'size': '(1)'}), '(1, high=20, size=1)\n', (541, 561), True, 'import numpy as np\n'), ((585, 622), 'numpy.random.randint', 'np.random.randint', (['(-6)'], {'high': '(6)', 'size': '(1)'}), '(-6, high=6, size=1)\n', (602, 622), True, 'import numpy as np\n'), ((646, 683), 'numpy.random.randint', 'np.random.randint', (['(1)'], {'high': '(20)', 'size': '(1)'}), '(1, high=20, size=1)\n', (663, 683), True, 'import numpy as np\n'), ((756, 793), 'numpy.random.randint', 'np.random.randint', (['(1)'], {'high': '(32)', 'size': '(1)'}), '(1, high=32, size=1)\n', (773, 793), True, 'import numpy as np\n'), ((814, 851), 'numpy.random.randint', 'np.random.randint', (['(1)'], {'high': '(32)', 'size': '(1)'}), '(1, high=32, size=1)\n', (831, 851), True, 'import numpy as np\n'), ((872, 909), 'numpy.random.randint', 'np.random.randint', (['(1)'], {'high': '(32)', 'size': '(1)'}), '(1, high=32, size=1)\n', (889, 909), True, 'import numpy as np\n'), ((343, 380), 'numpy.random.randint', 'np.random.randint', (['(1)'], {'high': '(16)', 'size': '(1)'}), '(1, high=16, size=1)\n', (360, 380), True, 'import numpy as np\n'), ((2712, 2729), 'numpy.shape', 'np.shape', (['src_out'], {}), '(src_out)\n', (2720, 2729), True, 'import numpy as np\n'), ((2690, 2707), 'numpy.shape', 'np.shape', (['src_out'], {}), '(src_out)\n', (2698, 2707), True, 'import numpy as np\n')]
#!/usr/bin/env python # encoding: utf-8 import struct from numpy import ( int32, int64, float32, float64, int8, uint8, int16, uint16, uint32, uint64, frombuffer ) import struct _const = { 'i32.const': int32, 'i64.const': int64, 'f32,const': float32, 'f64.const': float64, } _binary = { # 32-bit integer 'i32.add': lambda x, y: int32(x + y), 'i32.sub': lambda x, y: int32(x - y), 'i32.mul': lambda x, y: int32(x * y), 'i32.div_s': lambda x, y: int32(x // y), 'i32.div_u': lambda x, y: int32(uint32(x) // uint32(y)), 'i32.and': lambda x, y: int32(x & y), 'i32.or': lambda x, y: int32(int32(x) | int32(y)), 'i32.xor': lambda x, y: int32(x ^ y), 'i32.rem_s': lambda x, y: int32(x % y), 'i32.rem_u': lambda x, y: int32(uint32(x) * uint32(y)), 'i32.eq': lambda x, y: int32(x == y), 'i32.ne': lambda x, y: int32(x != y), 'i32.lt_s': lambda x, y: int32(x < y), 'i32.le_s': lambda x, y: int32(x <= y), 'i32.gt_s': lambda x, y: int32(x > y), 'i32.ge_s': lambda x, y: int32(x >= y), 'i32.lt_u': lambda x, y: int32(uint32(x) < uint32(y)), 'i32.gt_u': lambda x, y: int32(uint32(x) > uint32(y)), 'i32.le_u': lambda x, y: int32(uint32(x) <= uint32(y)), 'i32.ge_u': lambda x, y: int32(uint32(x) >= uint32(y)), 'i32.rotr': lambda x, y: int32((x >> y) | ((x & ((2**y)-1)) << (32-y))), 'i32.rotl': lambda x, y: int32((x << y) | ((x & ((2**y)-1)) >> (32-y))), 'i32.shr_u': lambda x, y: int32(int(uint32(x)) >> int(y)), 'i32.shl': lambda x, y: int32(x << y), # 64-bit integer 'i64.add': lambda x, y: int64(x + y), 'i64.sub': lambda x, y: int64(x - y), 'i64.mul': lambda x, y: int64(x * y), 'i64.div_s': lambda x, y: int64(x // y), 'i64.div_u': lambda x, y: int64(uint64(x) // uint64(y)), 'i64.and': lambda x, y: int64(x & y), 'i64.or': lambda x, y: int64(x | y), 'i64.xor': lambda x, y: int64(x ^ y), 'i64.rem_s': lambda x, y: int64(x % y), 'i64.rem_u': lambda x, y: int64(uint64(x) * uint64(y)), 'i64.eq': lambda x, y: int64(x == y), 'i64.ne': lambda x, y: int64(x != y), 'i64.lt_s': lambda x, y: int64(x < y), 'i64.le_s': lambda x, y: int64(x <= y), 'i64.gt_s': lambda x, y: int64(x > y), 'i64.ge_s': lambda x, y: int64(x >= y), 'i64.lt_u': lambda x, y: int64(uint64(x) < uint64(y)), 'i64.gt_u': lambda x, y: int64(uint64(x) > uint64(y)), 'i64.le_u': lambda x, y: int64(uint64(x) <= uint64(y)), 'i64.ge_u': lambda x, y: int64(uint64(x) >= uint64(y)), 'i64.rotr': lambda x, y: int64((x >> y) | ((x & ((2**y)-1)) << (64-y))), 'i64.rotl': lambda x, y: int64((x << y) | ((x & ((2**y)-1)) >> (64-y))), 'i64.shr_u': lambda x, y: int64(int(uint64(x)) >> int(y)), 'i64.shl': lambda x, y: int64(x << y), # 64 bit float 'f64.add': lambda x, y: float64(x + y), 'f64.sub': lambda x, y: float64(x - y), 'f64.mul': lambda x, y: float64(x * y), 'f64.div': lambda x, y: float64(x / y), 'f64.eq': lambda x, y: float64(x == y), 'f64.ne': lambda x, y: float64(x != y), 'f64.lt': lambda x, y: float64(x < y), 'f64.gt': lambda x, y: float64(x > y), 'f64.le': lambda x, y: float64(x <= y), 'f64.ge': lambda x, y: float64(x >= y), } import math _unary = { 'i32.eqz': lambda x: int32(x==0), 'i32.clz': lambda x: int32(32 - len(bin(uint32(x))[2:])), 'i32.ctz': lambda x: int32(len(bin(uint32(x)).rsplit('1', 1)[-1])), 'i32.wrap_i64': lambda x: int32(uint64(x)), 'i64.extend_i32_u': lambda x: int64(uint32(x)), 'f64.reinterpret_i64': lambda x: frombuffer(x.tobytes(), float64)[0], 'f64.sqrt': lambda x: float64(math.sqrt(x)), 'f64.convert_i32_u': lambda x: float64(uint32(x)), } _load = { 'i32.load': lambda raw: frombuffer(raw, int32)[0], 'i64.load': lambda raw: frombuffer(raw, int64)[0], 'f64.load': lambda raw: frombuffer(raw, float64)[0], 'i32.load8_s': lambda raw: int32(frombuffer(raw, int8)[0]), 'i32.load8_u': lambda raw: int32(frombuffer(raw, uint8)[0]), 'i32.load16_s': lambda raw: int32(frombuffer(raw, int16)[0]), 'i32.load16_u': lambda raw: int32(frombuffer(raw, uint16)[0]), 'i64.load8_s': lambda raw: int64(frombuffer(raw, int8)[0]), 'i64.load8_u': lambda raw: int64(frombuffer(raw, uint8)[0]), 'i64.load16_s': lambda raw: int64(frombuffer(raw, int16)[0]), 'i64.load16_u': lambda raw: int64(frombuffer(raw, uint16)[0]), 'i64.load32_s': lambda raw: int64(frombuffer(raw, int32)[0]), 'i64.load32_u': lambda raw: int64(frombuffer(raw, uint32)[0]), } _store = { 'i32.store': lambda val: val.tobytes(), 'i64.store': lambda val: val.tobytes(), 'f64.store': lambda val: val.tobytes(), 'i32.store8': lambda val: val.tobytes()[:1], 'i32.store16': lambda val: val.tobytes()[:2], 'i64.store8': lambda val: val.tobytes()[:1], 'i64.store16': lambda val: val.tobytes()[:2], 'i64.store32': lambda val: val.tobytes()[:4], } class Function: def __init__(self, nparams, returns, code): self.nparams = nparams self.returns = returns self.code = code class ImportFunction: def __init__(self, nparams, returns, call): self.nparams = nparams self.returns = returns self.call = call class Machine: def __init__(self, functions, memsize=65536): self.functions = functions self.items = [] self.memory = bytearray(memsize) def load(self, addr): return struct.unpack('<d', self.memory[addr: addr + 8])[0] def store(self, addr, val): self.memory[addr: addr+8] = struct.pack('<d', val) def push(self, item): assert type(item) in {int32, int64, float32, float64,} self.items.append(item) def pop(self): return self.items.pop() def call(self, func, *args): locals = dict(enumerate(args)) if isinstance(func, Function): try: self.execute(func.code, locals) except Return: pass if func.returns: return self.pop() else: return func.call(*args) def execute(self, instructions, locals): for op, *args in instructions: # print(op, args, self.items) if op in _const: self.push(_const[op](args[0])) elif op in _binary: right = self.pop() left = self.pop() self.push(_binary[op](left, right)) elif op in _unary: self.push(_unary[op](self.pop())) elif op in _load: addr = self.pop() + args[1] # offset self.push(_load[op](self.memory[addr:addr+8])) elif op in _store: val = self.pop() addr = self.pop() + args[1] raw = _store[op](val) self.memory[addr:addr+len(raw)]=raw elif op == 'memory.size': self.push(int32(len(self.memory)//65536)) elif op == 'memory.grow': npages = self.pop() self.memory.extend(bytes(npages* 65536)) self.push(int32(len(self.memory)//65536)) elif op == 'local.get': self.push(locals[args[0]]) elif op == 'local.set': locals[args[0]] = self.pop() elif op == 'local.tee': locals[args[0]] = self.items[-1] elif op =='drop': self.pop() elif op =='select': c = self.pop() v2 = self.pop() v1 = self.pop() self.push(v1 if c else v2) elif op == 'call': func = self.functions[args[0]] fargs = reversed([self.pop() for _ in range(func.nparams)]) result = self.call(func, *fargs) if func.returns: self.push(result) # if (test) {consequence} else {alternative} elif op == 'br': raise Break(args[0]) elif op == 'br_if': if self.pop(): raise Break(args[0]) elif op == 'br_table': n = self.pop() if n < len(args[0]): raise Break(args[0][n]) else: raise Break(args[1]) elif op == 'block': # ('block', type, [instructions]) try: self.execute(args[1], locals) except Break as b: if b.level > 0: b.level -= 1 raise elif op == 'loop': while True: try: self.execute(args[1], locals) break except Break as b: if b.level > 0: b.level -= 1 raise # while (test) {body} # ('block', [ # ('loop', [ # lable 0 # not test # ('br_if', 1) # Goto 1 # body # ('br', 0), # Goto 0 # ] # ) # ]) # label 1 elif op == 'return': raise Return() else: raise RuntimeError(f'Bad op {op}') class Break(Exception): def __init__(self, level): self.level = level class Return(Exception): pass def example(): def py_display_player(x): import time print(' '*int(x) + '<0:>') time.sleep(0.02) display_player = ImportFunction(nparams=1, returns=None,call=py_display_player) # def update_position(x, v, dt): # return x + v * dt update_position = Function(nparams=3, returns=True, code=[ ('local_get', 0), ('local_get', 1), ('local_get', 2), ('mul',), ('add',), ]) functions = [update_position, display_player] # # x = 2 # v = 3 # x = x + v * 0.1 x_addr = 22 v_addr = 42 code = [ ('const', x_addr), ('const', x_addr), ('load',), ('const', v_addr), ('load',), ('const', 0.1), ('call', 0), ('store',), ] m = Machine(functions) m.store(x_addr, 2.0) m.store(v_addr, 3.0) # while x > 0 { # x = update_position(x, v, 0.1) # if x > 70 { # v = -v # } # } m.execute([ ('block', [ ('loop', [ ('const', x_addr), ('load',), ('call', 1), ('const', x_addr), ('load',), ('const', 0.0), ('le',), ('br_if', 1), ('const', x_addr), ('const', x_addr), ('load',), ('const', v_addr), ('load',), ('const', 0.1), ('call', 0), ('store',), ('block', [ ('const', x_addr), ('load',), ('const', 70), ('ge',), ('block', [ ('br_if', 0), ('br', 1), ]), ('const', v_addr), ('const', 0.0), ('const', v_addr), ('load',), ('sub',), ('store',), ]), ('br', 0), ]) ]) ], None) # m = Machine(functions) # m.store(x_addr, 2.0) # m.store(v_addr, 3.0) # m.execute(code, None) print(f'Result: {m.load(x_addr)}') if __name__ == '__main__': example()
[ "numpy.uint32", "numpy.uint64", "math.sqrt", "numpy.frombuffer", "struct.unpack", "struct.pack", "time.sleep", "numpy.int32", "numpy.int64", "numpy.float64" ]
[((362, 374), 'numpy.int32', 'int32', (['(x + y)'], {}), '(x + y)\n', (367, 374), False, 'from numpy import int32, int64, float32, float64, int8, uint8, int16, uint16, uint32, uint64, frombuffer\n'), ((404, 416), 'numpy.int32', 'int32', (['(x - y)'], {}), '(x - y)\n', (409, 416), False, 'from numpy import int32, int64, float32, float64, int8, uint8, int16, uint16, uint32, uint64, frombuffer\n'), ((446, 458), 'numpy.int32', 'int32', (['(x * y)'], {}), '(x * y)\n', (451, 458), False, 'from numpy import int32, int64, float32, float64, int8, uint8, int16, uint16, uint32, uint64, frombuffer\n'), ((490, 503), 'numpy.int32', 'int32', (['(x // y)'], {}), '(x // y)\n', (495, 503), False, 'from numpy import int32, int64, float32, float64, int8, uint8, int16, uint16, uint32, uint64, frombuffer\n'), ((594, 606), 'numpy.int32', 'int32', (['(x & y)'], {}), '(x & y)\n', (599, 606), False, 'from numpy import int32, int64, float32, float64, int8, uint8, int16, uint16, uint32, uint64, frombuffer\n'), ((691, 703), 'numpy.int32', 'int32', (['(x ^ y)'], {}), '(x ^ y)\n', (696, 703), False, 'from numpy import int32, int64, float32, float64, int8, uint8, int16, uint16, uint32, uint64, frombuffer\n'), ((735, 747), 'numpy.int32', 'int32', (['(x % y)'], {}), '(x % y)\n', (740, 747), False, 'from numpy import int32, int64, float32, float64, int8, uint8, int16, uint16, uint32, uint64, frombuffer\n'), ((836, 849), 'numpy.int32', 'int32', (['(x == y)'], {}), '(x == y)\n', (841, 849), False, 'from numpy import int32, int64, float32, float64, int8, uint8, int16, uint16, uint32, uint64, frombuffer\n'), ((878, 891), 'numpy.int32', 'int32', (['(x != y)'], {}), '(x != y)\n', (883, 891), False, 'from numpy import int32, int64, float32, float64, int8, uint8, int16, uint16, uint32, uint64, frombuffer\n'), ((922, 934), 'numpy.int32', 'int32', (['(x < y)'], {}), '(x < y)\n', (927, 934), False, 'from numpy import int32, int64, float32, float64, int8, uint8, int16, uint16, uint32, uint64, frombuffer\n'), ((965, 978), 'numpy.int32', 'int32', (['(x <= y)'], {}), '(x <= y)\n', (970, 978), False, 'from numpy import int32, int64, float32, float64, int8, uint8, int16, uint16, uint32, uint64, frombuffer\n'), ((1009, 1021), 'numpy.int32', 'int32', (['(x > y)'], {}), '(x > y)\n', (1014, 1021), False, 'from numpy import int32, int64, float32, float64, int8, uint8, int16, uint16, uint32, uint64, frombuffer\n'), ((1052, 1065), 'numpy.int32', 'int32', (['(x >= y)'], {}), '(x >= y)\n', (1057, 1065), False, 'from numpy import int32, int64, float32, float64, int8, uint8, int16, uint16, uint32, uint64, frombuffer\n'), ((1334, 1376), 'numpy.int32', 'int32', (['(x >> y | (x & 2 ** y - 1) << 32 - y)'], {}), '(x >> y | (x & 2 ** y - 1) << 32 - y)\n', (1339, 1376), False, 'from numpy import int32, int64, float32, float64, int8, uint8, int16, uint16, uint32, uint64, frombuffer\n'), ((1411, 1453), 'numpy.int32', 'int32', (['(x << y | (x & 2 ** y - 1) >> 32 - y)'], {}), '(x << y | (x & 2 ** y - 1) >> 32 - y)\n', (1416, 1453), False, 'from numpy import int32, int64, float32, float64, int8, uint8, int16, uint16, uint32, uint64, frombuffer\n'), ((1550, 1563), 'numpy.int32', 'int32', (['(x << y)'], {}), '(x << y)\n', (1555, 1563), False, 'from numpy import int32, int64, float32, float64, int8, uint8, int16, uint16, uint32, uint64, frombuffer\n'), ((1616, 1628), 'numpy.int64', 'int64', (['(x + y)'], {}), '(x + y)\n', (1621, 1628), False, 'from numpy import int32, int64, float32, float64, int8, uint8, int16, uint16, uint32, uint64, frombuffer\n'), ((1658, 1670), 'numpy.int64', 'int64', (['(x - y)'], {}), '(x - y)\n', (1663, 1670), False, 'from numpy import int32, int64, float32, float64, int8, uint8, int16, uint16, uint32, uint64, frombuffer\n'), ((1700, 1712), 'numpy.int64', 'int64', (['(x * y)'], {}), '(x * y)\n', (1705, 1712), False, 'from numpy import int32, int64, float32, float64, int8, uint8, int16, uint16, uint32, uint64, frombuffer\n'), ((1744, 1757), 'numpy.int64', 'int64', (['(x // y)'], {}), '(x // y)\n', (1749, 1757), False, 'from numpy import int32, int64, float32, float64, int8, uint8, int16, uint16, uint32, uint64, frombuffer\n'), ((1848, 1860), 'numpy.int64', 'int64', (['(x & y)'], {}), '(x & y)\n', (1853, 1860), False, 'from numpy import int32, int64, float32, float64, int8, uint8, int16, uint16, uint32, uint64, frombuffer\n'), ((1889, 1901), 'numpy.int64', 'int64', (['(x | y)'], {}), '(x | y)\n', (1894, 1901), False, 'from numpy import int32, int64, float32, float64, int8, uint8, int16, uint16, uint32, uint64, frombuffer\n'), ((1931, 1943), 'numpy.int64', 'int64', (['(x ^ y)'], {}), '(x ^ y)\n', (1936, 1943), False, 'from numpy import int32, int64, float32, float64, int8, uint8, int16, uint16, uint32, uint64, frombuffer\n'), ((1975, 1987), 'numpy.int64', 'int64', (['(x % y)'], {}), '(x % y)\n', (1980, 1987), False, 'from numpy import int32, int64, float32, float64, int8, uint8, int16, uint16, uint32, uint64, frombuffer\n'), ((2076, 2089), 'numpy.int64', 'int64', (['(x == y)'], {}), '(x == y)\n', (2081, 2089), False, 'from numpy import int32, int64, float32, float64, int8, uint8, int16, uint16, uint32, uint64, frombuffer\n'), ((2118, 2131), 'numpy.int64', 'int64', (['(x != y)'], {}), '(x != y)\n', (2123, 2131), False, 'from numpy import int32, int64, float32, float64, int8, uint8, int16, uint16, uint32, uint64, frombuffer\n'), ((2162, 2174), 'numpy.int64', 'int64', (['(x < y)'], {}), '(x < y)\n', (2167, 2174), False, 'from numpy import int32, int64, float32, float64, int8, uint8, int16, uint16, uint32, uint64, frombuffer\n'), ((2205, 2218), 'numpy.int64', 'int64', (['(x <= y)'], {}), '(x <= y)\n', (2210, 2218), False, 'from numpy import int32, int64, float32, float64, int8, uint8, int16, uint16, uint32, uint64, frombuffer\n'), ((2249, 2261), 'numpy.int64', 'int64', (['(x > y)'], {}), '(x > y)\n', (2254, 2261), False, 'from numpy import int32, int64, float32, float64, int8, uint8, int16, uint16, uint32, uint64, frombuffer\n'), ((2292, 2305), 'numpy.int64', 'int64', (['(x >= y)'], {}), '(x >= y)\n', (2297, 2305), False, 'from numpy import int32, int64, float32, float64, int8, uint8, int16, uint16, uint32, uint64, frombuffer\n'), ((2574, 2616), 'numpy.int64', 'int64', (['(x >> y | (x & 2 ** y - 1) << 64 - y)'], {}), '(x >> y | (x & 2 ** y - 1) << 64 - y)\n', (2579, 2616), False, 'from numpy import int32, int64, float32, float64, int8, uint8, int16, uint16, uint32, uint64, frombuffer\n'), ((2651, 2693), 'numpy.int64', 'int64', (['(x << y | (x & 2 ** y - 1) >> 64 - y)'], {}), '(x << y | (x & 2 ** y - 1) >> 64 - y)\n', (2656, 2693), False, 'from numpy import int32, int64, float32, float64, int8, uint8, int16, uint16, uint32, uint64, frombuffer\n'), ((2790, 2803), 'numpy.int64', 'int64', (['(x << y)'], {}), '(x << y)\n', (2795, 2803), False, 'from numpy import int32, int64, float32, float64, int8, uint8, int16, uint16, uint32, uint64, frombuffer\n'), ((2853, 2867), 'numpy.float64', 'float64', (['(x + y)'], {}), '(x + y)\n', (2860, 2867), False, 'from numpy import int32, int64, float32, float64, int8, uint8, int16, uint16, uint32, uint64, frombuffer\n'), ((2897, 2911), 'numpy.float64', 'float64', (['(x - y)'], {}), '(x - y)\n', (2904, 2911), False, 'from numpy import int32, int64, float32, float64, int8, uint8, int16, uint16, uint32, uint64, frombuffer\n'), ((2941, 2955), 'numpy.float64', 'float64', (['(x * y)'], {}), '(x * y)\n', (2948, 2955), False, 'from numpy import int32, int64, float32, float64, int8, uint8, int16, uint16, uint32, uint64, frombuffer\n'), ((2985, 2999), 'numpy.float64', 'float64', (['(x / y)'], {}), '(x / y)\n', (2992, 2999), False, 'from numpy import int32, int64, float32, float64, int8, uint8, int16, uint16, uint32, uint64, frombuffer\n'), ((3028, 3043), 'numpy.float64', 'float64', (['(x == y)'], {}), '(x == y)\n', (3035, 3043), False, 'from numpy import int32, int64, float32, float64, int8, uint8, int16, uint16, uint32, uint64, frombuffer\n'), ((3072, 3087), 'numpy.float64', 'float64', (['(x != y)'], {}), '(x != y)\n', (3079, 3087), False, 'from numpy import int32, int64, float32, float64, int8, uint8, int16, uint16, uint32, uint64, frombuffer\n'), ((3116, 3130), 'numpy.float64', 'float64', (['(x < y)'], {}), '(x < y)\n', (3123, 3130), False, 'from numpy import int32, int64, float32, float64, int8, uint8, int16, uint16, uint32, uint64, frombuffer\n'), ((3159, 3173), 'numpy.float64', 'float64', (['(x > y)'], {}), '(x > y)\n', (3166, 3173), False, 'from numpy import int32, int64, float32, float64, int8, uint8, int16, uint16, uint32, uint64, frombuffer\n'), ((3202, 3217), 'numpy.float64', 'float64', (['(x <= y)'], {}), '(x <= y)\n', (3209, 3217), False, 'from numpy import int32, int64, float32, float64, int8, uint8, int16, uint16, uint32, uint64, frombuffer\n'), ((3246, 3261), 'numpy.float64', 'float64', (['(x >= y)'], {}), '(x >= y)\n', (3253, 3261), False, 'from numpy import int32, int64, float32, float64, int8, uint8, int16, uint16, uint32, uint64, frombuffer\n'), ((3314, 3327), 'numpy.int32', 'int32', (['(x == 0)'], {}), '(x == 0)\n', (3319, 3327), False, 'from numpy import int32, int64, float32, float64, int8, uint8, int16, uint16, uint32, uint64, frombuffer\n'), ((5611, 5633), 'struct.pack', 'struct.pack', (['"""<d"""', 'val'], {}), "('<d', val)\n", (5622, 5633), False, 'import struct\n'), ((9659, 9675), 'time.sleep', 'time.sleep', (['(0.02)'], {}), '(0.02)\n', (9669, 9675), False, 'import time\n'), ((3497, 3506), 'numpy.uint64', 'uint64', (['x'], {}), '(x)\n', (3503, 3506), False, 'from numpy import int32, int64, float32, float64, int8, uint8, int16, uint16, uint32, uint64, frombuffer\n'), ((3549, 3558), 'numpy.uint32', 'uint32', (['x'], {}), '(x)\n', (3555, 3558), False, 'from numpy import int32, int64, float32, float64, int8, uint8, int16, uint16, uint32, uint64, frombuffer\n'), ((3669, 3681), 'math.sqrt', 'math.sqrt', (['x'], {}), '(x)\n', (3678, 3681), False, 'import math\n'), ((3727, 3736), 'numpy.uint32', 'uint32', (['x'], {}), '(x)\n', (3733, 3736), False, 'from numpy import int32, int64, float32, float64, int8, uint8, int16, uint16, uint32, uint64, frombuffer\n'), ((3780, 3802), 'numpy.frombuffer', 'frombuffer', (['raw', 'int32'], {}), '(raw, int32)\n', (3790, 3802), False, 'from numpy import int32, int64, float32, float64, int8, uint8, int16, uint16, uint32, uint64, frombuffer\n'), ((3835, 3857), 'numpy.frombuffer', 'frombuffer', (['raw', 'int64'], {}), '(raw, int64)\n', (3845, 3857), False, 'from numpy import int32, int64, float32, float64, int8, uint8, int16, uint16, uint32, uint64, frombuffer\n'), ((3890, 3914), 'numpy.frombuffer', 'frombuffer', (['raw', 'float64'], {}), '(raw, float64)\n', (3900, 3914), False, 'from numpy import int32, int64, float32, float64, int8, uint8, int16, uint16, uint32, uint64, frombuffer\n'), ((5490, 5537), 'struct.unpack', 'struct.unpack', (['"""<d"""', 'self.memory[addr:addr + 8]'], {}), "('<d', self.memory[addr:addr + 8])\n", (5503, 5537), False, 'import struct\n'), ((541, 550), 'numpy.uint32', 'uint32', (['x'], {}), '(x)\n', (547, 550), False, 'from numpy import int32, int64, float32, float64, int8, uint8, int16, uint16, uint32, uint64, frombuffer\n'), ((554, 563), 'numpy.uint32', 'uint32', (['y'], {}), '(y)\n', (560, 563), False, 'from numpy import int32, int64, float32, float64, int8, uint8, int16, uint16, uint32, uint64, frombuffer\n'), ((641, 649), 'numpy.int32', 'int32', (['x'], {}), '(x)\n', (646, 649), False, 'from numpy import int32, int64, float32, float64, int8, uint8, int16, uint16, uint32, uint64, frombuffer\n'), ((652, 660), 'numpy.int32', 'int32', (['y'], {}), '(y)\n', (657, 660), False, 'from numpy import int32, int64, float32, float64, int8, uint8, int16, uint16, uint32, uint64, frombuffer\n'), ((785, 794), 'numpy.uint32', 'uint32', (['x'], {}), '(x)\n', (791, 794), False, 'from numpy import int32, int64, float32, float64, int8, uint8, int16, uint16, uint32, uint64, frombuffer\n'), ((797, 806), 'numpy.uint32', 'uint32', (['y'], {}), '(y)\n', (803, 806), False, 'from numpy import int32, int64, float32, float64, int8, uint8, int16, uint16, uint32, uint64, frombuffer\n'), ((1102, 1111), 'numpy.uint32', 'uint32', (['x'], {}), '(x)\n', (1108, 1111), False, 'from numpy import int32, int64, float32, float64, int8, uint8, int16, uint16, uint32, uint64, frombuffer\n'), ((1114, 1123), 'numpy.uint32', 'uint32', (['y'], {}), '(y)\n', (1120, 1123), False, 'from numpy import int32, int64, float32, float64, int8, uint8, int16, uint16, uint32, uint64, frombuffer\n'), ((1161, 1170), 'numpy.uint32', 'uint32', (['x'], {}), '(x)\n', (1167, 1170), False, 'from numpy import int32, int64, float32, float64, int8, uint8, int16, uint16, uint32, uint64, frombuffer\n'), ((1173, 1182), 'numpy.uint32', 'uint32', (['y'], {}), '(y)\n', (1179, 1182), False, 'from numpy import int32, int64, float32, float64, int8, uint8, int16, uint16, uint32, uint64, frombuffer\n'), ((1220, 1229), 'numpy.uint32', 'uint32', (['x'], {}), '(x)\n', (1226, 1229), False, 'from numpy import int32, int64, float32, float64, int8, uint8, int16, uint16, uint32, uint64, frombuffer\n'), ((1233, 1242), 'numpy.uint32', 'uint32', (['y'], {}), '(y)\n', (1239, 1242), False, 'from numpy import int32, int64, float32, float64, int8, uint8, int16, uint16, uint32, uint64, frombuffer\n'), ((1280, 1289), 'numpy.uint32', 'uint32', (['x'], {}), '(x)\n', (1286, 1289), False, 'from numpy import int32, int64, float32, float64, int8, uint8, int16, uint16, uint32, uint64, frombuffer\n'), ((1293, 1302), 'numpy.uint32', 'uint32', (['y'], {}), '(y)\n', (1299, 1302), False, 'from numpy import int32, int64, float32, float64, int8, uint8, int16, uint16, uint32, uint64, frombuffer\n'), ((1795, 1804), 'numpy.uint64', 'uint64', (['x'], {}), '(x)\n', (1801, 1804), False, 'from numpy import int32, int64, float32, float64, int8, uint8, int16, uint16, uint32, uint64, frombuffer\n'), ((1808, 1817), 'numpy.uint64', 'uint64', (['y'], {}), '(y)\n', (1814, 1817), False, 'from numpy import int32, int64, float32, float64, int8, uint8, int16, uint16, uint32, uint64, frombuffer\n'), ((2025, 2034), 'numpy.uint64', 'uint64', (['x'], {}), '(x)\n', (2031, 2034), False, 'from numpy import int32, int64, float32, float64, int8, uint8, int16, uint16, uint32, uint64, frombuffer\n'), ((2037, 2046), 'numpy.uint64', 'uint64', (['y'], {}), '(y)\n', (2043, 2046), False, 'from numpy import int32, int64, float32, float64, int8, uint8, int16, uint16, uint32, uint64, frombuffer\n'), ((2342, 2351), 'numpy.uint64', 'uint64', (['x'], {}), '(x)\n', (2348, 2351), False, 'from numpy import int32, int64, float32, float64, int8, uint8, int16, uint16, uint32, uint64, frombuffer\n'), ((2354, 2363), 'numpy.uint64', 'uint64', (['y'], {}), '(y)\n', (2360, 2363), False, 'from numpy import int32, int64, float32, float64, int8, uint8, int16, uint16, uint32, uint64, frombuffer\n'), ((2401, 2410), 'numpy.uint64', 'uint64', (['x'], {}), '(x)\n', (2407, 2410), False, 'from numpy import int32, int64, float32, float64, int8, uint8, int16, uint16, uint32, uint64, frombuffer\n'), ((2413, 2422), 'numpy.uint64', 'uint64', (['y'], {}), '(y)\n', (2419, 2422), False, 'from numpy import int32, int64, float32, float64, int8, uint8, int16, uint16, uint32, uint64, frombuffer\n'), ((2460, 2469), 'numpy.uint64', 'uint64', (['x'], {}), '(x)\n', (2466, 2469), False, 'from numpy import int32, int64, float32, float64, int8, uint8, int16, uint16, uint32, uint64, frombuffer\n'), ((2473, 2482), 'numpy.uint64', 'uint64', (['y'], {}), '(y)\n', (2479, 2482), False, 'from numpy import int32, int64, float32, float64, int8, uint8, int16, uint16, uint32, uint64, frombuffer\n'), ((2520, 2529), 'numpy.uint64', 'uint64', (['x'], {}), '(x)\n', (2526, 2529), False, 'from numpy import int32, int64, float32, float64, int8, uint8, int16, uint16, uint32, uint64, frombuffer\n'), ((2533, 2542), 'numpy.uint64', 'uint64', (['y'], {}), '(y)\n', (2539, 2542), False, 'from numpy import int32, int64, float32, float64, int8, uint8, int16, uint16, uint32, uint64, frombuffer\n'), ((3956, 3977), 'numpy.frombuffer', 'frombuffer', (['raw', 'int8'], {}), '(raw, int8)\n', (3966, 3977), False, 'from numpy import int32, int64, float32, float64, int8, uint8, int16, uint16, uint32, uint64, frombuffer\n'), ((4020, 4042), 'numpy.frombuffer', 'frombuffer', (['raw', 'uint8'], {}), '(raw, uint8)\n', (4030, 4042), False, 'from numpy import int32, int64, float32, float64, int8, uint8, int16, uint16, uint32, uint64, frombuffer\n'), ((4086, 4108), 'numpy.frombuffer', 'frombuffer', (['raw', 'int16'], {}), '(raw, int16)\n', (4096, 4108), False, 'from numpy import int32, int64, float32, float64, int8, uint8, int16, uint16, uint32, uint64, frombuffer\n'), ((4152, 4175), 'numpy.frombuffer', 'frombuffer', (['raw', 'uint16'], {}), '(raw, uint16)\n', (4162, 4175), False, 'from numpy import int32, int64, float32, float64, int8, uint8, int16, uint16, uint32, uint64, frombuffer\n'), ((4218, 4239), 'numpy.frombuffer', 'frombuffer', (['raw', 'int8'], {}), '(raw, int8)\n', (4228, 4239), False, 'from numpy import int32, int64, float32, float64, int8, uint8, int16, uint16, uint32, uint64, frombuffer\n'), ((4282, 4304), 'numpy.frombuffer', 'frombuffer', (['raw', 'uint8'], {}), '(raw, uint8)\n', (4292, 4304), False, 'from numpy import int32, int64, float32, float64, int8, uint8, int16, uint16, uint32, uint64, frombuffer\n'), ((4348, 4370), 'numpy.frombuffer', 'frombuffer', (['raw', 'int16'], {}), '(raw, int16)\n', (4358, 4370), False, 'from numpy import int32, int64, float32, float64, int8, uint8, int16, uint16, uint32, uint64, frombuffer\n'), ((4414, 4437), 'numpy.frombuffer', 'frombuffer', (['raw', 'uint16'], {}), '(raw, uint16)\n', (4424, 4437), False, 'from numpy import int32, int64, float32, float64, int8, uint8, int16, uint16, uint32, uint64, frombuffer\n'), ((4481, 4503), 'numpy.frombuffer', 'frombuffer', (['raw', 'int32'], {}), '(raw, int32)\n', (4491, 4503), False, 'from numpy import int32, int64, float32, float64, int8, uint8, int16, uint16, uint32, uint64, frombuffer\n'), ((4547, 4570), 'numpy.frombuffer', 'frombuffer', (['raw', 'uint32'], {}), '(raw, uint32)\n', (4557, 4570), False, 'from numpy import int32, int64, float32, float64, int8, uint8, int16, uint16, uint32, uint64, frombuffer\n'), ((1499, 1508), 'numpy.uint32', 'uint32', (['x'], {}), '(x)\n', (1505, 1508), False, 'from numpy import int32, int64, float32, float64, int8, uint8, int16, uint16, uint32, uint64, frombuffer\n'), ((2739, 2748), 'numpy.uint64', 'uint64', (['x'], {}), '(x)\n', (2745, 2748), False, 'from numpy import int32, int64, float32, float64, int8, uint8, int16, uint16, uint32, uint64, frombuffer\n'), ((3371, 3380), 'numpy.uint32', 'uint32', (['x'], {}), '(x)\n', (3377, 3380), False, 'from numpy import int32, int64, float32, float64, int8, uint8, int16, uint16, uint32, uint64, frombuffer\n'), ((3428, 3437), 'numpy.uint32', 'uint32', (['x'], {}), '(x)\n', (3434, 3437), False, 'from numpy import int32, int64, float32, float64, int8, uint8, int16, uint16, uint32, uint64, frombuffer\n')]
import sys import matplotlib import matplotlib.pyplot as plt import numpy as np from matplotlib.ticker import MultipleLocator majorLocatorX = MultipleLocator(5) minorLocatorX = MultipleLocator(5) majorLocatorY = MultipleLocator(20) minorLocatorY = MultipleLocator(10) a1985 = [2] a1987 = [3] a1995 = [4, 5] a1996 = [6] a1997 = [7] a2000 = [8, 16] a2002 = [9, 10] a2003 = [11, 13] a2005 = [12] a2009 = [17] a2010 = [18, 20, 21, 22, 23, 24] a2011 = [15, 39, 40, 41, 42, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 60, 61, 62] a2012 = [26, 28, 36, 68, 78, 88, 90, 100, 106, 114, 116, 118, 120, 132] a2013 = [19, 25, 27, 34, 37, 38, 43, 44, 45, 46, 58, 64, 66, 70, 72, 74, 76, 80, 82, 84, 86, 92, 94, 96, 98, 102, 104, 108, 110] a2014 = [29, 30, 31, 32, 33, 35, 57, 59, 63, 65, 67, 69, 71, 73, 75, 77, 79, 81, 83, 85, 112, 122, 124, 126, 128, 130, 134, 136, 138, 140, 142, 144, 146] y1985 = [1985] * len(a1985) y1987 = [1987] * len(a1987) y1995 = [1995] * len(a1995) y1997 = [1997] * len(a1997) y2000 = [2000] * len(a2000) y2002 = [2002] * len(a2002) y2003 = [2003] * len(a2003) y2005 = [2005] * len(a2005) y2009 = [2009] * len(a2009) y2010 = [2010] * len(a2010) y2011 = [2011] * len(a2011) y2012 = [2012] * len(a2012) y2013 = [2013] * len(a2013) y2014 = [2014] * len(a2014) years = y1985 + y1987 + y1995 + y1997 + y2000 + y2002 + y2003 + y2005 + y2009 + y2010 + y2011 + y2012 + y2013 + y2014 masses = a1985 + a1987 + a1995 + a1997 + a2000 + a2002 + a2003 + a2005 + a2009 + a2010 + a2011 + a2012 + a2013 + a2014 x1 = np.linspace(1985, 2020, 100) y1 = 0.01 * np.exp(0.34657 * (x1 - 1985)) plt.rc('font', family='serif') fig, ax = plt.subplots() #ax.scatter(years, masses, 75, marker='o', color=(1.0,0.4,0), edgecolor='black', linewidth = 0.9) plt.scatter(years, masses, 75, marker='o', color=(1.0,0.4,0), edgecolor='black', linewidth = 0.9) #plt.plot(x1, y1) plt.xlabel(r'$\mathrm{Year}$', fontsize=16) plt.ylabel(r'$\mathrm{Mass\ Number\ (A)}$', fontsize=16) plt.axis([1984, 2015, 0, 150]) ax.xaxis.set_major_locator(majorLocatorX) ax.xaxis.set_minor_locator(minorLocatorX) ax.yaxis.set_major_locator(majorLocatorY) ax.yaxis.set_minor_locator(minorLocatorY) #plt.xaxis.set_major_locator(majorLocatorX) #plt.xaxis.set_minor_locator(minorLocatorX) #plt.yaxis.set_major_locator(majorLocatorY) #plt.yaxis.set_minor_locator(minorLocatorY) plt.savefig('ab-initio_progress.pdf', format='pdf', bbox_inches='tight') plt.show()
[ "matplotlib.pyplot.show", "matplotlib.pyplot.scatter", "matplotlib.pyplot.ylabel", "matplotlib.pyplot.axis", "matplotlib.pyplot.rc", "numpy.linspace", "numpy.exp", "matplotlib.ticker.MultipleLocator", "matplotlib.pyplot.xlabel", "matplotlib.pyplot.subplots", "matplotlib.pyplot.savefig" ]
[((143, 161), 'matplotlib.ticker.MultipleLocator', 'MultipleLocator', (['(5)'], {}), '(5)\n', (158, 161), False, 'from matplotlib.ticker import MultipleLocator\n'), ((178, 196), 'matplotlib.ticker.MultipleLocator', 'MultipleLocator', (['(5)'], {}), '(5)\n', (193, 196), False, 'from matplotlib.ticker import MultipleLocator\n'), ((213, 232), 'matplotlib.ticker.MultipleLocator', 'MultipleLocator', (['(20)'], {}), '(20)\n', (228, 232), False, 'from matplotlib.ticker import MultipleLocator\n'), ((249, 268), 'matplotlib.ticker.MultipleLocator', 'MultipleLocator', (['(10)'], {}), '(10)\n', (264, 268), False, 'from matplotlib.ticker import MultipleLocator\n'), ((1514, 1542), 'numpy.linspace', 'np.linspace', (['(1985)', '(2020)', '(100)'], {}), '(1985, 2020, 100)\n', (1525, 1542), True, 'import numpy as np\n'), ((1586, 1616), 'matplotlib.pyplot.rc', 'plt.rc', (['"""font"""'], {'family': '"""serif"""'}), "('font', family='serif')\n", (1592, 1616), True, 'import matplotlib.pyplot as plt\n'), ((1628, 1642), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (1640, 1642), True, 'import matplotlib.pyplot as plt\n'), ((1742, 1844), 'matplotlib.pyplot.scatter', 'plt.scatter', (['years', 'masses', '(75)'], {'marker': '"""o"""', 'color': '(1.0, 0.4, 0)', 'edgecolor': '"""black"""', 'linewidth': '(0.9)'}), "(years, masses, 75, marker='o', color=(1.0, 0.4, 0), edgecolor=\n 'black', linewidth=0.9)\n", (1753, 1844), True, 'import matplotlib.pyplot as plt\n'), ((1858, 1901), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""$\\\\mathrm{Year}$"""'], {'fontsize': '(16)'}), "('$\\\\mathrm{Year}$', fontsize=16)\n", (1868, 1901), True, 'import matplotlib.pyplot as plt\n'), ((1902, 1960), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""$\\\\mathrm{Mass\\\\ Number\\\\ (A)}$"""'], {'fontsize': '(16)'}), "('$\\\\mathrm{Mass\\\\ Number\\\\ (A)}$', fontsize=16)\n", (1912, 1960), True, 'import matplotlib.pyplot as plt\n'), ((1959, 1989), 'matplotlib.pyplot.axis', 'plt.axis', (['[1984, 2015, 0, 150]'], {}), '([1984, 2015, 0, 150])\n', (1967, 1989), True, 'import matplotlib.pyplot as plt\n'), ((2337, 2409), 'matplotlib.pyplot.savefig', 'plt.savefig', (['"""ab-initio_progress.pdf"""'], {'format': '"""pdf"""', 'bbox_inches': '"""tight"""'}), "('ab-initio_progress.pdf', format='pdf', bbox_inches='tight')\n", (2348, 2409), True, 'import matplotlib.pyplot as plt\n'), ((2410, 2420), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (2418, 2420), True, 'import matplotlib.pyplot as plt\n'), ((1555, 1584), 'numpy.exp', 'np.exp', (['(0.34657 * (x1 - 1985))'], {}), '(0.34657 * (x1 - 1985))\n', (1561, 1584), True, 'import numpy as np\n')]
from hazma.vector_mediator import VectorMediator, KineticMixing from hazma.parameters import vh from hazma.parameters import electron_mass as me import numpy as np import os from os import path def e_cm_mw(mx, vrel=1e-3): """Computes DM COM energy, assuming its velocity is much less than c. """ return 2 * mx * (1 + 0.5 * vrel ** 2) def save_data(params_list, Models): """Generates and saves data for a set of scalar mediator models. """ # Make data directory data_dir = path.join(path.dirname(__file__), "data") if not path.exists(path.join(data_dir)): os.makedirs(data_dir) for i, (params, Model) in enumerate(zip(params_list, Models)): # Make directory for model cur_dir = path.join(data_dir, "vm_{}".format(i + 1)) print("writing tests to {}".format(cur_dir)) if not path.exists(cur_dir): os.makedirs(cur_dir) model = Model(**params) np.save(path.join(cur_dir, "params.npy"), params) # Particle physics quantities e_cm = e_cm_mw(model.mx) np.save(path.join(cur_dir, "e_cm.npy"), e_cm) np.save( path.join(cur_dir, "ann_cross_sections.npy"), model.annihilation_cross_sections(e_cm), ) np.save( path.join(cur_dir, "ann_branching_fractions.npy"), model.annihilation_branching_fractions(e_cm), ) np.save(path.join(cur_dir, "partial_widths.npy"), model.partial_widths()) # Gamma-ray spectra e_gams = np.geomspace(1.0, e_cm, 10) np.save(path.join(cur_dir, "e_gams.npy"), e_gams) np.save(path.join(cur_dir, "spectra.npy"), model.spectra(e_gams, e_cm)) np.save(path.join(cur_dir, "gamma_ray_lines.npy"), model.gamma_ray_lines(e_cm)) # Positron spectra e_ps = np.geomspace(me, e_cm, 10) np.save(path.join(cur_dir, "e_ps.npy"), e_ps) np.save( path.join(cur_dir, "positron_spectra.npy"), model.positron_spectra(e_ps, e_cm), ) np.save(path.join(cur_dir, "positron_lines.npy"), model.positron_lines(e_cm)) def generate_test_data(): params = [] mx = 250.0 eps = 0.1 gvxx = 1.0 mvs = 2 * [125.0, 550.0] gvuus = 4 * [1.0] gvdds = 2 * [1.0, -1.0] gvsss = 4 * [1.0] gvees = 4 * [1.0] gvmumus = 4 * [1.0] for mv in [125.0, 550.0]: params.append({"mx": mx, "mv": mv, "gvxx": gvxx, "eps": eps}) for mv, gvuu, gvdd, gvss, gvee, gvmumu in zip( mvs, gvuus, gvdds, gvsss, gvees, gvmumus ): params.append( { "mx": mx, "mv": mv, "gvxx": gvxx, "gvuu": gvuu, "gvdd": gvdd, "gvss": gvss, "gvee": gvee, "gvmumu": gvmumu, } ) save_data(params, 2 * [KineticMixing] + 4 * [VectorMediator]) if __name__ == "__main__": generate_test_data()
[ "os.makedirs", "numpy.geomspace", "os.path.dirname", "os.path.exists", "os.path.join" ]
[((514, 536), 'os.path.dirname', 'path.dirname', (['__file__'], {}), '(__file__)\n', (526, 536), False, 'from os import path\n'), ((599, 620), 'os.makedirs', 'os.makedirs', (['data_dir'], {}), '(data_dir)\n', (610, 620), False, 'import os\n'), ((1539, 1566), 'numpy.geomspace', 'np.geomspace', (['(1.0)', 'e_cm', '(10)'], {}), '(1.0, e_cm, 10)\n', (1551, 1566), True, 'import numpy as np\n'), ((1836, 1862), 'numpy.geomspace', 'np.geomspace', (['me', 'e_cm', '(10)'], {}), '(me, e_cm, 10)\n', (1848, 1862), True, 'import numpy as np\n'), ((569, 588), 'os.path.join', 'path.join', (['data_dir'], {}), '(data_dir)\n', (578, 588), False, 'from os import path\n'), ((853, 873), 'os.path.exists', 'path.exists', (['cur_dir'], {}), '(cur_dir)\n', (864, 873), False, 'from os import path\n'), ((887, 907), 'os.makedirs', 'os.makedirs', (['cur_dir'], {}), '(cur_dir)\n', (898, 907), False, 'import os\n'), ((957, 989), 'os.path.join', 'path.join', (['cur_dir', '"""params.npy"""'], {}), "(cur_dir, 'params.npy')\n", (966, 989), False, 'from os import path\n'), ((1087, 1117), 'os.path.join', 'path.join', (['cur_dir', '"""e_cm.npy"""'], {}), "(cur_dir, 'e_cm.npy')\n", (1096, 1117), False, 'from os import path\n'), ((1154, 1198), 'os.path.join', 'path.join', (['cur_dir', '"""ann_cross_sections.npy"""'], {}), "(cur_dir, 'ann_cross_sections.npy')\n", (1163, 1198), False, 'from os import path\n'), ((1292, 1341), 'os.path.join', 'path.join', (['cur_dir', '"""ann_branching_fractions.npy"""'], {}), "(cur_dir, 'ann_branching_fractions.npy')\n", (1301, 1341), False, 'from os import path\n'), ((1427, 1467), 'os.path.join', 'path.join', (['cur_dir', '"""partial_widths.npy"""'], {}), "(cur_dir, 'partial_widths.npy')\n", (1436, 1467), False, 'from os import path\n'), ((1583, 1615), 'os.path.join', 'path.join', (['cur_dir', '"""e_gams.npy"""'], {}), "(cur_dir, 'e_gams.npy')\n", (1592, 1615), False, 'from os import path\n'), ((1641, 1674), 'os.path.join', 'path.join', (['cur_dir', '"""spectra.npy"""'], {}), "(cur_dir, 'spectra.npy')\n", (1650, 1674), False, 'from os import path\n'), ((1721, 1762), 'os.path.join', 'path.join', (['cur_dir', '"""gamma_ray_lines.npy"""'], {}), "(cur_dir, 'gamma_ray_lines.npy')\n", (1730, 1762), False, 'from os import path\n'), ((1879, 1909), 'os.path.join', 'path.join', (['cur_dir', '"""e_ps.npy"""'], {}), "(cur_dir, 'e_ps.npy')\n", (1888, 1909), False, 'from os import path\n'), ((1946, 1988), 'os.path.join', 'path.join', (['cur_dir', '"""positron_spectra.npy"""'], {}), "(cur_dir, 'positron_spectra.npy')\n", (1955, 1988), False, 'from os import path\n'), ((2064, 2104), 'os.path.join', 'path.join', (['cur_dir', '"""positron_lines.npy"""'], {}), "(cur_dir, 'positron_lines.npy')\n", (2073, 2104), False, 'from os import path\n')]
import torch import sys, os sys.path.insert(0, os.path.abspath(os.path.join(os.getcwd(), "./../../../../"))) sys.path.insert(0, os.path.abspath(os.path.join(os.getcwd(), "./../../../"))) from fedml_api.model.cv.vgg import vgg11_bn, VGG_SNIP from fedml_api.model.cv.resnet import resnet56 from fedml_api.model.cv.wrn.wrn import WRN import numpy as np # init_model = resnet56(10) # init_model = WRN(28, 4) init_model = vgg11_bn() init_model.load_state_dict(torch.load('./debug/0_model.pt')) # comp_model = resnet56(10) # comp_model = WRN(28, 4) comp_model = vgg11_bn() comp_model.load_state_dict(torch.load('./debug/2_model.pt')) # print(comp_model) count = 0 for param_tensor in init_model.state_dict(): # print(comp_model.state_dict()[param_tensor])p # if init_model.state_dict()[param_tensor].type() == 'torch.LongTensor': # print(param_tensor) # print(comp_model.state_dict()[param_tensor].type()) diff_params = init_model.state_dict()[param_tensor] - comp_model.state_dict()[param_tensor] diff_params = diff_params.view(-1).numpy() # diff_params = init_model.state_dict()[param_tensor].view(-1).numpy() # print(diff_params) count += sum(np.where(diff_params, 0, 1)) # print(diff_params) # break print(count)
[ "os.getcwd", "torch.load", "numpy.where", "fedml_api.model.cv.vgg.vgg11_bn" ]
[((418, 428), 'fedml_api.model.cv.vgg.vgg11_bn', 'vgg11_bn', ([], {}), '()\n', (426, 428), False, 'from fedml_api.model.cv.vgg import vgg11_bn, VGG_SNIP\n'), ((558, 568), 'fedml_api.model.cv.vgg.vgg11_bn', 'vgg11_bn', ([], {}), '()\n', (566, 568), False, 'from fedml_api.model.cv.vgg import vgg11_bn, VGG_SNIP\n'), ((456, 488), 'torch.load', 'torch.load', (['"""./debug/0_model.pt"""'], {}), "('./debug/0_model.pt')\n", (466, 488), False, 'import torch\n'), ((596, 628), 'torch.load', 'torch.load', (['"""./debug/2_model.pt"""'], {}), "('./debug/2_model.pt')\n", (606, 628), False, 'import torch\n'), ((1188, 1215), 'numpy.where', 'np.where', (['diff_params', '(0)', '(1)'], {}), '(diff_params, 0, 1)\n', (1196, 1215), True, 'import numpy as np\n'), ((76, 87), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (85, 87), False, 'import sys, os\n'), ((157, 168), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (166, 168), False, 'import sys, os\n')]
import sys import os import time import argparse import textwrap import smtplib import numpy import cv2 import movidius import imutils from imutils.video import VideoStream arguments = argparse.ArgumentParser( description="Heimdall AI Camera PoC using Intel Movidius Neural Compute Stick 1.") arguments.add_argument('-s', '--source', type=int, default=0, help="Index of the video device. ex. 0 for /dev/video0") arguments.add_argument('-pi', '--pi', type=bool, default=False, help="Enable raspberry pi cam support. Only use this if your sure you need it.") arguments.add_argument('-m', '--match_threshold', type=float, default=0.9, help="Percentage required for a mobile net object detection match in range of (0.0 - 1.0).") arguments.add_argument('-g', '--mobile_net_graph', type=str, default='ssd_mobilenet_ncs.graph', help="Path to the mobile net neural network graph file.") arguments.add_argument('-l', '--mobile_net_labels', type=str, default='labels.txt', help="Path to labels file for mobile net.") arguments.add_argument('-fps', '--fps', type=bool, default=False, help="Show fps your getting after processing.") arguments.add_argument('-alerts', '--alerts', type=str, default=None, help="Classification list that triggers alerts.") arguments.add_argument('-email', '--email', type=str, default=None, help="Email address to send email alerts too.") arguments.add_argument('-email_server', '--email_server', type=str, default="localhost", help="Email server to send email alerts from.") arguments.add_argument('-email_username', '--email_username', type=str, default=None, help="Email server username to send email alerts with.") arguments.add_argument('-email_password', '--email_password', type=str, default=None, help="Email server password to send email alerts with.") ARGS = arguments.parse_args() # classification(s) to search for based on labels.txt CLASS_BACKGROUND = 0 CLASS_AEROPLANE = 1 CLASS_BICYCLE = 2 CLASS_BIRD = 3 CLASS_BOAT = 4 CLASS_BOTTLE = 5 CLASS_BUS = 6 CLASS_CAR = 7 CLASS_CAT = 8 CLASS_CHAIR = 9 CLASS_COW = 10 CLASS_DINNINGTABLE = 11 CLASS_DOG = 12 CLASS_HORSE = 13 CLASS_MOTORBIKE = 14 CLASS_PERSON = 15 CLASS_POTTEDPLANT = 16 CLASS_SHEEP = 17 CLASS_SOFA = 18 CLASS_TRAIN = 19 CLASS_TV_MONITOR = 20 # classification labels LABELS = [line.rstrip('\n') for line in open(ARGS.mobile_net_labels) if line != 'classes\n'] # subject for the alert # text for the alert def alert_smtp(subject, text): message = textwrap.dedent("""\ From: %s To: %s Subject: %s %s """ % ("<EMAIL>", ", ".join(ARGS.email), "Heimdall Alert: " + subject, text)) print(message) server = smtplib.SMTP(ARGS.email_server) if (ARGS.email_username is not None and ARGS.email_password is not None): server.starttls() server.login(ARGS.email_username, ARGS.email_password) server.sendmail("<EMAIL>", ARGS.email, message) server.quit() # src is the source image to convert def bgr2rgb(src): return cv2.cvtColor(src, cv2.COLOR_BGR2RGB) # src is a cv2.imread you want to crop # x is the starting x position # y is the starting y position # width is the width of the area you want # height is the height of the area you want def crop(src, x, y, width, height): return src[y:y+height, x:x+width] # src is the image to scale def subscale(src): return (cv2.resize(src, tuple([300, 300])).astype(numpy.float16) - numpy.float16([127.5, 127.5, 127.5])) * 0.00789 # image is a cv2.imread # color is the border color def overlay(src, x, y, width, height, color=(255, 255, 0), thickness=2, left_label=None, right_label=None): cv2.rectangle(src, (x, y), (x + width, y + height), color, thickness) if (left_label is not None): cv2.putText(src, left_label, (x, y + 15), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (32, 32, 32), 2) if (right_label is not None): cv2.putText(src, right_label, (x + width - len(right_label) * 9, y + 15), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (32, 32, 32), 2) # image is a cv2.imread # color is the border color def overlay_detections(src, outputs, classifications): r = range(0, outputs['num_detections']) for i in r: classification = classifications[i] (y1, x1) = outputs.get('detection_boxes_' + str(i))[0] (y2, x2) = outputs.get('detection_boxes_' + str(i))[1] label = (LABELS[outputs.get('detection_classes_' + str(i))] + ": " + str(outputs.get('detection_scores_' + str(i))) + "%") overlay(src, x1, y1, x2 - x1, y2 - y1, classification[2], 2, label, classification[1]) # src is a cv2.imread # graph is the loaded facenet graph def inferance_objects(src, graph): scaled = subscale(bgr2rgb(src)) graph.LoadTensor(scaled, 'user object') output, t = graph.GetResult() return output def main(): device = movidius.attach(0) if (device is None): print("No movidius device was found.") exit() print("Attached to movidius device at " + device) mobilenet = movidius.allocate("mobilenet", ARGS.mobile_net_graph, device) video = VideoStream(src=ARGS.source, usePiCamera=ARGS.pi, resolution=(320, 240), framerate=30).start() print("Waiting for camera to start...") time.sleep(2.0) run_time = time.time() alert_time = time.time() print("Running...") frames = 0 while True: frame = video.read() if (frame is None): print("[ERROR] can't get frame data from camera?") break detections = movidius.ssd(inferance_objects( frame, mobilenet), ARGS.match_threshold, frame.shape) detections_range = range(0, detections['num_detections']) classifications = {} for i in detections_range: class_id = detections.get('detection_classes_' + str(i)) label = None color = (255, 255, 0) if (ARGS.alerts is not None): alerts = ARGS.alerts.replace(" ", "").split(",") for alert in alerts: if (class_id == alert): color = (0, 255, 0) if (time.time() - alert_time) > 120: alert_smtp(class_id, class_id + " was found.") alert_time = time.time() classifications[i] = (class_id, label, color) if (ARGS.fps): frames += 1 if (time.time() - run_time) > 1: print("[FPS] " + str(frames / (time.time() - run_time))) frames = 0 run_time = time.time() overlay_detections(frame, detections, classifications) cv2.imshow("Camera", frame) key = cv2.waitKey(1) & 0xFF if key == ord("q"): break movidius.deattach(0) print("Deattached from movidius device at " + device) cv2.destroyAllWindows() if __name__ == "__main__": sys.exit(main())
[ "numpy.float16", "imutils.video.VideoStream", "movidius.allocate", "cv2.putText", "argparse.ArgumentParser", "smtplib.SMTP", "cv2.cvtColor", "cv2.waitKey", "cv2.imshow", "time.sleep", "time.time", "cv2.rectangle", "movidius.attach", "movidius.deattach", "cv2.destroyAllWindows" ]
[((186, 297), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Heimdall AI Camera PoC using Intel Movidius Neural Compute Stick 1."""'}), "(description=\n 'Heimdall AI Camera PoC using Intel Movidius Neural Compute Stick 1.')\n", (209, 297), False, 'import argparse\n'), ((3172, 3203), 'smtplib.SMTP', 'smtplib.SMTP', (['ARGS.email_server'], {}), '(ARGS.email_server)\n', (3184, 3203), False, 'import smtplib\n'), ((3511, 3547), 'cv2.cvtColor', 'cv2.cvtColor', (['src', 'cv2.COLOR_BGR2RGB'], {}), '(src, cv2.COLOR_BGR2RGB)\n', (3523, 3547), False, 'import cv2\n'), ((4151, 4220), 'cv2.rectangle', 'cv2.rectangle', (['src', '(x, y)', '(x + width, y + height)', 'color', 'thickness'], {}), '(src, (x, y), (x + width, y + height), color, thickness)\n', (4164, 4220), False, 'import cv2\n'), ((5415, 5433), 'movidius.attach', 'movidius.attach', (['(0)'], {}), '(0)\n', (5430, 5433), False, 'import movidius\n'), ((5592, 5653), 'movidius.allocate', 'movidius.allocate', (['"""mobilenet"""', 'ARGS.mobile_net_graph', 'device'], {}), "('mobilenet', ARGS.mobile_net_graph, device)\n", (5609, 5653), False, 'import movidius\n'), ((5834, 5849), 'time.sleep', 'time.sleep', (['(2.0)'], {}), '(2.0)\n', (5844, 5849), False, 'import time\n'), ((5865, 5876), 'time.time', 'time.time', ([], {}), '()\n', (5874, 5876), False, 'import time\n'), ((5894, 5905), 'time.time', 'time.time', ([], {}), '()\n', (5903, 5905), False, 'import time\n'), ((7381, 7401), 'movidius.deattach', 'movidius.deattach', (['(0)'], {}), '(0)\n', (7398, 7401), False, 'import movidius\n'), ((7464, 7487), 'cv2.destroyAllWindows', 'cv2.destroyAllWindows', ([], {}), '()\n', (7485, 7487), False, 'import cv2\n'), ((4263, 4357), 'cv2.putText', 'cv2.putText', (['src', 'left_label', '(x, y + 15)', 'cv2.FONT_HERSHEY_SIMPLEX', '(0.5)', '(32, 32, 32)', '(2)'], {}), '(src, left_label, (x, y + 15), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (\n 32, 32, 32), 2)\n', (4274, 4357), False, 'import cv2\n'), ((7266, 7293), 'cv2.imshow', 'cv2.imshow', (['"""Camera"""', 'frame'], {}), "('Camera', frame)\n", (7276, 7293), False, 'import cv2\n'), ((3935, 3971), 'numpy.float16', 'numpy.float16', (['[127.5, 127.5, 127.5]'], {}), '([127.5, 127.5, 127.5])\n', (3948, 3971), False, 'import numpy\n'), ((5666, 5756), 'imutils.video.VideoStream', 'VideoStream', ([], {'src': 'ARGS.source', 'usePiCamera': 'ARGS.pi', 'resolution': '(320, 240)', 'framerate': '(30)'}), '(src=ARGS.source, usePiCamera=ARGS.pi, resolution=(320, 240),\n framerate=30)\n', (5677, 5756), False, 'from imutils.video import VideoStream\n'), ((7308, 7322), 'cv2.waitKey', 'cv2.waitKey', (['(1)'], {}), '(1)\n', (7319, 7322), False, 'import cv2\n'), ((7182, 7193), 'time.time', 'time.time', ([], {}), '()\n', (7191, 7193), False, 'import time\n'), ((7026, 7037), 'time.time', 'time.time', ([], {}), '()\n', (7035, 7037), False, 'import time\n'), ((6890, 6901), 'time.time', 'time.time', ([], {}), '()\n', (6899, 6901), False, 'import time\n'), ((6741, 6752), 'time.time', 'time.time', ([], {}), '()\n', (6750, 6752), False, 'import time\n'), ((7102, 7113), 'time.time', 'time.time', ([], {}), '()\n', (7111, 7113), False, 'import time\n')]
from __future__ import absolute_import import numpy as np from targets.marshalling.marshaller import Marshaller from targets.target_config import FileFormat class NumpyArrayMarshaller(Marshaller): type = np.ndarray file_format = FileFormat.numpy def target_to_value(self, target, **kwargs): """ :param obj: object to pickle :return: """ with target.open("rb") as fp: return np.load(fp, **kwargs) def value_to_target(self, value, target, **kwargs): """ :param obj: object to pickle :return: """ target.mkdir_parent() with target.open("wb") as fp: np.save(fp, value, **kwargs) class NumpyArrayPickleMarshaler(NumpyArrayMarshaller): file_format = FileFormat.pickle def target_to_value(self, target, **kwargs): return np.load(target.path, allow_pickle=True, **kwargs) def value_to_target(self, value, target, **kwargs): np.save(target.path, value, allow_pickle=True, **kwargs)
[ "numpy.load", "numpy.save" ]
[((867, 916), 'numpy.load', 'np.load', (['target.path'], {'allow_pickle': '(True)'}), '(target.path, allow_pickle=True, **kwargs)\n', (874, 916), True, 'import numpy as np\n'), ((982, 1038), 'numpy.save', 'np.save', (['target.path', 'value'], {'allow_pickle': '(True)'}), '(target.path, value, allow_pickle=True, **kwargs)\n', (989, 1038), True, 'import numpy as np\n'), ((443, 464), 'numpy.load', 'np.load', (['fp'], {}), '(fp, **kwargs)\n', (450, 464), True, 'import numpy as np\n'), ((680, 708), 'numpy.save', 'np.save', (['fp', 'value'], {}), '(fp, value, **kwargs)\n', (687, 708), True, 'import numpy as np\n')]
# <NAME>, April 2020 from helper_fns import * import numpy as np import matplotlib.pyplot as plt import math from bson import objectid data = process_lookup2() # Takes ~10 seconds def flip_state(s): return [1] + s[10:] + s[1:10] def get_cost_per_game(user, game): if game["_id"] == objectid.ObjectId("<KEY>"): return 0.0 costs = [] state = get_initial_state(game) user_pair = game["p1c1"][0] + game["p1c2"][0] if game["usernames"].index(user) == 1: user_pair = game["p2c1"][0] + game["p2c2"][0] if chars.index(user_pair[0]) > chars.index(user_pair[1]): user_pair = user_pair[1] + user_pair[0] for m in game["Moves"]: if int(m[1]) - 1 == game["usernames"].index(user): if m[1] == "1": costs += [cost(state, user_pair, m, data)] else: #print(game, flip_state(state), user_pair, m) costs += [cost(flip_state(state), user_pair, m, data)] if game["_id"] == objectid.ObjectId("<KEY>"): print(m, state) do_action(m, state) if math.isnan(np.average(costs)): # The player didn't get a single turn (monk flurry killed them turn 1, poor guy) return 0.0 return np.average(costs) results = {} for u in db.players.find({"Username": {"$exists": True}, "elo": {"$exists": True}, "Played": {"$gt": 0}}): games = [] for g in db.completed_games.find({"usernames": u["Username"], "winner": {"$exists": True}}): # for every game games += [g] games = sorted(games, key=lambda i: i['end_time']) for i in range(len(games)): if i in results.keys(): results[i] += [get_cost_per_game(u["Username"], games[i])] else: results[i] = [get_cost_per_game(u["Username"], games[i])] # results = {0: [0.01, 0.0, 0.023,x], <num_games_played>: [<list_of_costs>], .. } for i in range(max(results.keys())+1): print(i, np.average(results[i]), len(results[i]), results[i].count(0.0)/len(results[i])) if len(results[i]) < 20: results.pop(i) print(results) plt.bar(range(max(results.keys())), [results[i].count(0.0) for i in range(max(results.keys()))]) plt.bar(range(max(results.keys())), [len(results[i]) - results[i].count(0.0) for i in range(max(results.keys()))], bottom=[results[i].count(0.0) for i in range(max(results.keys()))]) ax2 = plt.twinx() plt.plot(range(max(results.keys())), [results[i].count(0.0)/len(results[i]) for i in range(max(results.keys()))]) plt.show()
[ "numpy.average", "matplotlib.pyplot.show", "bson.objectid.ObjectId", "matplotlib.pyplot.twinx" ]
[((2468, 2479), 'matplotlib.pyplot.twinx', 'plt.twinx', ([], {}), '()\n', (2477, 2479), True, 'import matplotlib.pyplot as plt\n'), ((2605, 2615), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (2613, 2615), True, 'import matplotlib.pyplot as plt\n'), ((1249, 1266), 'numpy.average', 'np.average', (['costs'], {}), '(costs)\n', (1259, 1266), True, 'import numpy as np\n'), ((301, 327), 'bson.objectid.ObjectId', 'objectid.ObjectId', (['"""<KEY>"""'], {}), "('<KEY>')\n", (318, 327), False, 'from bson import objectid\n'), ((1110, 1127), 'numpy.average', 'np.average', (['costs'], {}), '(costs)\n', (1120, 1127), True, 'import numpy as np\n'), ((1991, 2013), 'numpy.average', 'np.average', (['results[i]'], {}), '(results[i])\n', (2001, 2013), True, 'import numpy as np\n'), ((1007, 1033), 'bson.objectid.ObjectId', 'objectid.ObjectId', (['"""<KEY>"""'], {}), "('<KEY>')\n", (1024, 1033), False, 'from bson import objectid\n')]
import pyrealsense2 as rs import numpy as np import datetime as dt import time import multiprocessing as mp import os # import mpio import cv2 from queue import Queue import threading as th class RecordingJob(th.Thread): def __init__(self, video_name, queue): super(RecordingJob, self).__init__() self.stop_flag = th.Event() self.stop_flag.set() self.video_name = video_name self.queue = queue def run(self): self.num = 0 self.fourcc = cv2.VideoWriter_fourcc(*'XVID') self.out = cv2.VideoWriter(self.video_name, self.fourcc, 60, (640, 480)) while self.stop_flag.isSet(): # print(self.queue.qsize()) # self.num += 1 if not self.queue.empty(): self.out.write(self.queue.get()) # self.queue.get() self.num += 1 time.sleep(1) print(self.num) # print(self.queue.qsize()) self.out.release() print('Thread Exitted') def stop(self): self.stop_flag.clear() if __name__ == '__main__': directory_path = '0702test' if not os.path.exists(directory_path): os.mkdir(directory_path) rgb_video_name = directory_path + '/rgb.avi' f = open(directory_path + '/time.txt', 'w') # rgb_queue = mp.Queue() rgb_queue = Queue() # p = mpio.RGBRecordingClass(rgb_video_name, rgb_queue) # p.start() t = RecordingJob(rgb_video_name, rgb_queue) t.start() pipeline = rs.pipeline() config = rs.config() config.enable_stream(rs.stream.color, 640, 480, rs.format.bgr8, 60) profile = pipeline.start(config) frame_count = 0 sensors = profile.get_device().query_sensors() # print('Sensors are '+str(sensors)) for sensor in sensors: if sensor.supports(rs.option.auto_exposure_priority): # print('Start setting AE priority.') aep = sensor.get_option(rs.option.auto_exposure_priority) print('Original AEP = %d' % aep) aep = sensor.set_option(rs.option.auto_exposure_priority, 0) aep = sensor.get_option(rs.option.auto_exposure_priority) print('New AEP = %d' % aep) try: print('Start Recording %s' % (str(dt.datetime.now()))) date_start = time.time() while True: frames = pipeline.wait_for_frames() color_frame = frames.get_color_frame() f.write(str(time.time() * 1000) + '\n') if not color_frame: print('No color frame') color_image = color_frame.get_data() color_image = np.asanyarray(color_image) cv2.imshow('frame', color_image) cv2.waitKey(1) rgb_queue.put(color_image) frame_count += 1 total_elapsed = time.time() - date_start print('Frame num: %d, fps: %d' % (frame_count, frame_count / total_elapsed)) if frame_count >= 18000: break except Exception as e: print('Error is ', str(e)) finally: print(str(dt.datetime.now())) pipeline.stop() print('frame_count=', str(frame_count)) # p.stop() t.stop() # cv2.destroyAllWindows() f.close() print('end')
[ "os.mkdir", "cv2.VideoWriter_fourcc", "pyrealsense2.pipeline", "cv2.waitKey", "numpy.asanyarray", "os.path.exists", "pyrealsense2.config", "time.sleep", "time.time", "threading.Event", "cv2.VideoWriter", "cv2.imshow", "datetime.datetime.now", "queue.Queue" ]
[((1350, 1357), 'queue.Queue', 'Queue', ([], {}), '()\n', (1355, 1357), False, 'from queue import Queue\n'), ((1513, 1526), 'pyrealsense2.pipeline', 'rs.pipeline', ([], {}), '()\n', (1524, 1526), True, 'import pyrealsense2 as rs\n'), ((1540, 1551), 'pyrealsense2.config', 'rs.config', ([], {}), '()\n', (1549, 1551), True, 'import pyrealsense2 as rs\n'), ((337, 347), 'threading.Event', 'th.Event', ([], {}), '()\n', (345, 347), True, 'import threading as th\n'), ((504, 535), 'cv2.VideoWriter_fourcc', 'cv2.VideoWriter_fourcc', (["*'XVID'"], {}), "(*'XVID')\n", (526, 535), False, 'import cv2\n'), ((555, 616), 'cv2.VideoWriter', 'cv2.VideoWriter', (['self.video_name', 'self.fourcc', '(60)', '(640, 480)'], {}), '(self.video_name, self.fourcc, 60, (640, 480))\n', (570, 616), False, 'import cv2\n'), ((884, 897), 'time.sleep', 'time.sleep', (['(1)'], {}), '(1)\n', (894, 897), False, 'import time\n'), ((1142, 1172), 'os.path.exists', 'os.path.exists', (['directory_path'], {}), '(directory_path)\n', (1156, 1172), False, 'import os\n'), ((1182, 1206), 'os.mkdir', 'os.mkdir', (['directory_path'], {}), '(directory_path)\n', (1190, 1206), False, 'import os\n'), ((2307, 2318), 'time.time', 'time.time', ([], {}), '()\n', (2316, 2318), False, 'import time\n'), ((2640, 2666), 'numpy.asanyarray', 'np.asanyarray', (['color_image'], {}), '(color_image)\n', (2653, 2666), True, 'import numpy as np\n'), ((2680, 2712), 'cv2.imshow', 'cv2.imshow', (['"""frame"""', 'color_image'], {}), "('frame', color_image)\n", (2690, 2712), False, 'import cv2\n'), ((2725, 2739), 'cv2.waitKey', 'cv2.waitKey', (['(1)'], {}), '(1)\n', (2736, 2739), False, 'import cv2\n'), ((2840, 2851), 'time.time', 'time.time', ([], {}), '()\n', (2849, 2851), False, 'import time\n'), ((3108, 3125), 'datetime.datetime.now', 'dt.datetime.now', ([], {}), '()\n', (3123, 3125), True, 'import datetime as dt\n'), ((2265, 2282), 'datetime.datetime.now', 'dt.datetime.now', ([], {}), '()\n', (2280, 2282), True, 'import datetime as dt\n'), ((2464, 2475), 'time.time', 'time.time', ([], {}), '()\n', (2473, 2475), False, 'import time\n')]
# Copyright (c) 2019-2021 CRS4 # # 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 pytest import pyecvl._core.ecvl as ecvl_core import pyecvl.ecvl as ecvl_py def _empty_img(ecvl): if ecvl is ecvl_core: return ecvl.Image() return ecvl.Image.empty() @pytest.mark.parametrize("ecvl", [ecvl_core, ecvl_py]) def test_ResizeDim(ecvl): dims = [20, 40, 3] newdims = [10, 20] # no color channel img = ecvl.Image(dims, ecvl.DataType.uint8, "xyc", ecvl.ColorType.BGR) tmp = _empty_img(ecvl) ecvl.ResizeDim(img, tmp, newdims) assert tmp.dims_[:2] == newdims ecvl.ResizeDim(img, tmp, newdims, ecvl.InterpolationType.nearest) assert tmp.dims_[:2] == newdims @pytest.mark.parametrize("ecvl", [ecvl_core, ecvl_py]) def test_ResizeScale(ecvl): dims = [20, 40, 3] scales = [0.5, 0.5] # no color channel img = ecvl.Image(dims, ecvl.DataType.uint8, "xyc", ecvl.ColorType.BGR) tmp = _empty_img(ecvl) ecvl.ResizeScale(img, tmp, scales) assert tmp.dims_[:2] == [10, 20] ecvl.ResizeScale(img, tmp, scales, ecvl.InterpolationType.cubic) assert tmp.dims_[:2] == [10, 20] @pytest.mark.parametrize("ecvl", [ecvl_core, ecvl_py]) def test_Flip2D(ecvl): dims = [20, 40, 3] img = ecvl.Image(dims, ecvl.DataType.uint8, "xyc", ecvl.ColorType.BGR) tmp = _empty_img(ecvl) ecvl.Flip2D(img, tmp) assert tmp.dims_ == img.dims_ @pytest.mark.parametrize("ecvl", [ecvl_core, ecvl_py]) def test_Mirror2D(ecvl): dims = [20, 40, 3] img = ecvl.Image(dims, ecvl.DataType.uint8, "xyc", ecvl.ColorType.BGR) tmp = _empty_img(ecvl) ecvl.Mirror2D(img, tmp) assert tmp.dims_ == img.dims_ @pytest.mark.parametrize("ecvl", [ecvl_core, ecvl_py]) def test_Rotate2D(ecvl): dims = [20, 40, 3] img = ecvl.Image(dims, ecvl.DataType.uint8, "xyc", ecvl.ColorType.BGR) tmp = _empty_img(ecvl) angle, center, scale, interp = 9, [5, 5], 1.5, ecvl.InterpolationType.area ecvl.Rotate2D(img, tmp, angle) ecvl.Rotate2D(img, tmp, angle, center) ecvl.Rotate2D(img, tmp, angle, center, scale) ecvl.Rotate2D(img, tmp, angle, center, scale, interp) @pytest.mark.parametrize("ecvl", [ecvl_core, ecvl_py]) def test_RotateFullImage2D(ecvl): dims = [20, 40, 3] img = ecvl.Image(dims, ecvl.DataType.uint8, "xyc", ecvl.ColorType.BGR) tmp = _empty_img(ecvl) angle, scale, interp = 9, 1.5, ecvl.InterpolationType.lanczos4 ecvl.RotateFullImage2D(img, tmp, angle) ecvl.RotateFullImage2D(img, tmp, angle, scale) ecvl.RotateFullImage2D(img, tmp, angle, scale, interp) @pytest.mark.parametrize("ecvl", [ecvl_core, ecvl_py]) def test_ChangeColorSpace(ecvl): dims = [20, 40, 3] img = ecvl.Image(dims, ecvl.DataType.uint8, "xyc", ecvl.ColorType.BGR) tmp = _empty_img(ecvl) new_color = ecvl.ColorType.GRAY ecvl.ChangeColorSpace(img, tmp, new_color) assert tmp.colortype_ == new_color assert tmp.dims_[-1] == 1 @pytest.mark.parametrize("ecvl", [ecvl_core, ecvl_py]) def test_Threshold(ecvl): dims = [20, 40, 1] img = ecvl.Image(dims, ecvl.DataType.uint8, "xyc", ecvl.ColorType.GRAY) thr = ecvl.OtsuThreshold(img) tmp = _empty_img(ecvl) ttype = ecvl.ThresholdingType.BINARY_INV ecvl.Threshold(img, tmp, thr, 255) ecvl.Threshold(img, tmp, thr, 255, ttype) @pytest.mark.parametrize("ecvl", [ecvl_core, ecvl_py]) def test_MultiThreshold(ecvl): dims = [20, 40, 1] img = ecvl.Image(dims, ecvl.DataType.uint8, "xyc", ecvl.ColorType.GRAY) thresholds = ecvl.OtsuMultiThreshold(img) tmp = _empty_img(ecvl) ecvl.MultiThreshold(img, tmp, thresholds) ecvl.MultiThreshold(img, tmp, thresholds, 1) ecvl.MultiThreshold(img, tmp, thresholds, 1, 254) thresholds = ecvl.OtsuMultiThreshold(img, 3) tmp = _empty_img(ecvl) ecvl.MultiThreshold(img, tmp, thresholds) ecvl.MultiThreshold(img, tmp, thresholds, 1) ecvl.MultiThreshold(img, tmp, thresholds, 1, 254) @pytest.mark.parametrize("ecvl", [ecvl_core, ecvl_py]) def test_Filter2D(ecvl): dims = [20, 40, 3] img = ecvl.Image(dims, ecvl.DataType.uint8, "xyc", ecvl.ColorType.BGR) tmp = _empty_img(ecvl) # kernel must be float64, "xyc" and with one color channel kernel = ecvl.Image( [3, 3, 1], ecvl.DataType.float64, "xyc", ecvl.ColorType.GRAY ) a = np.array(kernel, copy=False) a.fill(0.11) dtype = ecvl.DataType.uint16 ecvl.Filter2D(img, tmp, kernel) ecvl.Filter2D(img, tmp, kernel, dtype) @pytest.mark.parametrize("ecvl", [ecvl_core, ecvl_py]) def test_SeparableFilter2D(ecvl): dims = [20, 40, 3] img = ecvl.Image(dims, ecvl.DataType.uint8, "xyc", ecvl.ColorType.BGR) tmp = _empty_img(ecvl) kerX, kerY, dtype = [1, 2, 1], [1, 0, -1], ecvl.DataType.uint16 ecvl.SeparableFilter2D(img, tmp, kerX, kerY) ecvl.SeparableFilter2D(img, tmp, kerX, kerY, dtype) @pytest.mark.parametrize("ecvl", [ecvl_core, ecvl_py]) def test_GaussianBlur(ecvl): dims = [20, 40, 3] img = ecvl.Image(dims, ecvl.DataType.uint8, "xyc", ecvl.ColorType.BGR) tmp = _empty_img(ecvl) sigmaY = 0.2 ecvl.GaussianBlur(img, tmp, 5, 5, 0.1) ecvl.GaussianBlur(img, tmp, 5, 5, 0.1, sigmaY) # alt overload in the ext module, called "GaussianBlur2" in the wrapper GaussianBlur2 = getattr(ecvl, "GaussianBlur2", ecvl.GaussianBlur) GaussianBlur2(img, tmp, 0.2) @pytest.mark.parametrize("ecvl", [ecvl_core, ecvl_py]) def test_AdditiveLaplaceNoise(ecvl): dims = [20, 40, 3] img = ecvl.Image(dims, ecvl.DataType.uint8, "xyc", ecvl.ColorType.BGR) tmp = _empty_img(ecvl) stddev = 255 * 0.05 ecvl.AdditiveLaplaceNoise(img, tmp, stddev) @pytest.mark.parametrize("ecvl", [ecvl_core, ecvl_py]) def test_AdditivePoissonNoise(ecvl): dims = [20, 40, 3] img = ecvl.Image(dims, ecvl.DataType.uint8, "xyc", ecvl.ColorType.BGR) tmp = _empty_img(ecvl) lambda_ = 2.0 ecvl.AdditivePoissonNoise(img, tmp, lambda_) @pytest.mark.parametrize("ecvl", [ecvl_core, ecvl_py]) def test_GammaContrast(ecvl): dims = [20, 40, 3] img = ecvl.Image(dims, ecvl.DataType.uint8, "xyc", ecvl.ColorType.BGR) tmp = _empty_img(ecvl) gamma = 3 ecvl.GammaContrast(img, tmp, gamma) @pytest.mark.parametrize("ecvl", [ecvl_core, ecvl_py]) def test_CoarseDropout(ecvl): dims = [20, 40, 3] img = ecvl.Image(dims, ecvl.DataType.uint8, "xyc", ecvl.ColorType.BGR) tmp = _empty_img(ecvl) prob, drop_size, per_channel = 0.5, 0.1, True ecvl.CoarseDropout(img, tmp, prob, drop_size, per_channel) @pytest.mark.parametrize("ecvl", [ecvl_core, ecvl_py]) def test_IntegralImage(ecvl): dims = [20, 40, 1] img = ecvl.Image(dims, ecvl.DataType.uint8, "xyc", ecvl.ColorType.GRAY) tmp = _empty_img(ecvl) dst_type = ecvl.DataType.float64 ecvl.IntegralImage(img, tmp) ecvl.IntegralImage(img, tmp, dst_type) @pytest.mark.parametrize("ecvl", [ecvl_core, ecvl_py]) def test_NonMaximaSuppression(ecvl): dims = [20, 40, 1] img = ecvl.Image(dims, ecvl.DataType.int32, "xyc", ecvl.ColorType.GRAY) tmp = _empty_img(ecvl) ecvl.NonMaximaSuppression(img, tmp) @pytest.mark.parametrize("ecvl", [ecvl_core, ecvl_py]) def test_GetMaxN(ecvl): a = np.asfortranarray(np.zeros(12, dtype=np.int32).reshape(3, 4, 1)) a[0, 1] = 3 a[1, 2] = 4 if ecvl is ecvl_core: img = ecvl.Image(a, "xyc", ecvl.ColorType.GRAY) else: img = ecvl.Image.fromarray(a, "xyc", ecvl.ColorType.GRAY) assert sorted(ecvl.GetMaxN(img, 2)) == [[0, 1], [1, 2]] @pytest.mark.parametrize("ecvl", [ecvl_core, ecvl_py]) def test_ConnectedComponentsLabeling(ecvl): dims = [20, 40, 1] img = ecvl.Image(dims, ecvl.DataType.uint8, "xyc", ecvl.ColorType.GRAY) tmp = _empty_img(ecvl) ecvl.ConnectedComponentsLabeling(img, tmp) @pytest.mark.parametrize("ecvl", [ecvl_core, ecvl_py]) def test_FindContours(ecvl): dims = [20, 40, 1] img = ecvl.Image(dims, ecvl.DataType.uint8, "xyc", ecvl.ColorType.GRAY) ecvl.FindContours(img) @pytest.mark.parametrize("ecvl", [ecvl_core, ecvl_py]) def test_HConcat(ecvl): img1 = ecvl.Image( [20, 40, 3], ecvl.DataType.uint8, "xyc", ecvl.ColorType.BGR ) img2 = ecvl.Image( [40, 40, 3], ecvl.DataType.uint8, "xyc", ecvl.ColorType.BGR ) tmp = _empty_img(ecvl) ecvl.HConcat([img1, img2], tmp) @pytest.mark.parametrize("ecvl", [ecvl_core, ecvl_py]) def test_VConcat(ecvl): img1 = ecvl.Image( [20, 40, 3], ecvl.DataType.uint8, "xyc", ecvl.ColorType.BGR ) img2 = ecvl.Image( [20, 20, 3], ecvl.DataType.uint8, "xyc", ecvl.ColorType.BGR ) tmp = _empty_img(ecvl) ecvl.VConcat([img1, img2], tmp) @pytest.mark.parametrize("ecvl", [ecvl_core, ecvl_py]) def test_Stack(ecvl): img1 = ecvl.Image( [20, 40, 3], ecvl.DataType.uint8, "xyc", ecvl.ColorType.BGR ) img2 = ecvl.Image( [20, 40, 3], ecvl.DataType.uint8, "xyc", ecvl.ColorType.BGR ) tmp = _empty_img(ecvl) ecvl.Stack([img1, img2], tmp) @pytest.mark.parametrize("ecvl", [ecvl_core, ecvl_py]) def test_Morphology(ecvl): dims = [20, 40, 3] img = ecvl.Image(dims, ecvl.DataType.uint8, "xyc", ecvl.ColorType.BGR) kernel = ecvl.Image( [5, 5, 1], ecvl.DataType.uint8, "xyc", ecvl.ColorType.BGR ) tmp = _empty_img(ecvl) ecvl.Morphology(img, tmp, ecvl.MorphType.MORPH_BLACKHAT, kernel) ecvl.Morphology(img, tmp, ecvl.MorphType.MORPH_BLACKHAT, kernel, [3, 3]) ecvl.Morphology( img, tmp, ecvl.MorphType.MORPH_BLACKHAT, kernel, [3, 3], 2 ) ecvl.Morphology( img, tmp, ecvl.MorphType.MORPH_BLACKHAT, kernel, [3, 3], 2, ecvl.BorderType.BORDER_REFLECT ) ecvl.Morphology( img, tmp, ecvl.MorphType.MORPH_BLACKHAT, kernel, [3, 3], 2, ecvl.BorderType.BORDER_REFLECT, 1 ) @pytest.mark.parametrize("ecvl", [ecvl_core, ecvl_py]) def test_Inpaint(ecvl): dims = [20, 40, 3] img = ecvl.Image(dims, ecvl.DataType.uint8, "xyc", ecvl.ColorType.BGR) mask = ecvl.Image( [20, 40, 1], ecvl.DataType.uint8, "xyc", ecvl.ColorType.BGR ) tmp = _empty_img(ecvl) ecvl.Inpaint(img, tmp, mask, 5.0) ecvl.Inpaint(img, tmp, mask, 5.0, ecvl.InpaintType.INPAINT_NS) @pytest.mark.parametrize("ecvl", [ecvl_core, ecvl_py]) def test_MeanStdDev(ecvl): dims = [20, 40, 3] img = ecvl.Image(dims, ecvl.DataType.uint8, "xyc", ecvl.ColorType.BGR) mean, stddev = ecvl.MeanStdDev(img) @pytest.mark.parametrize("ecvl", [ecvl_core, ecvl_py]) def test_Transpose(ecvl): img = ecvl.Image( [20, 40, 3], ecvl.DataType.uint8, "xyc", ecvl.ColorType.BGR ) tmp = _empty_img(ecvl) ecvl.Transpose(img, tmp) @pytest.mark.parametrize("ecvl", [ecvl_core, ecvl_py]) def test_GridDistortion(ecvl): dims = [20, 40, 3] img = ecvl.Image(dims, ecvl.DataType.uint8, "xyc", ecvl.ColorType.BGR) tmp = _empty_img(ecvl) ecvl.GridDistortion(img, tmp) ecvl.GridDistortion(img, tmp, 6) ecvl.GridDistortion(img, tmp, 6, [-0.5, 0.5]) ecvl.GridDistortion( img, tmp, 6, [-0.5, 0.5], ecvl.InterpolationType.nearest ) ecvl.GridDistortion( img, tmp, 6, [-0.5, 0.5], ecvl.InterpolationType.nearest, ecvl.BorderType.BORDER_CONSTANT ) ecvl.GridDistortion( img, tmp, 6, [-0.5, 0.5], ecvl.InterpolationType.nearest, ecvl.BorderType.BORDER_CONSTANT, 1 ) ecvl.GridDistortion( img, tmp, 6, [-0.5, 0.5], ecvl.InterpolationType.nearest, ecvl.BorderType.BORDER_CONSTANT, 1, 12345 ) @pytest.mark.parametrize("ecvl", [ecvl_core, ecvl_py]) def test_ElasticTransform(ecvl): dims = [20, 40, 3] img = ecvl.Image(dims, ecvl.DataType.uint8, "xyc", ecvl.ColorType.BGR) tmp = _empty_img(ecvl) ecvl.ElasticTransform(img, tmp) ecvl.ElasticTransform(img, tmp, 35) ecvl.ElasticTransform(img, tmp, 35, 5) ecvl.ElasticTransform(img, tmp, 35, 5, ecvl.InterpolationType.nearest) ecvl.ElasticTransform( img, tmp, 35, 5, ecvl.InterpolationType.nearest, ecvl.BorderType.BORDER_CONSTANT ) ecvl.ElasticTransform( img, tmp, 35, 5, ecvl.InterpolationType.nearest, ecvl.BorderType.BORDER_CONSTANT, 1 ) ecvl.ElasticTransform( img, tmp, 35, 5, ecvl.InterpolationType.nearest, ecvl.BorderType.BORDER_CONSTANT, 1, 12345 ) @pytest.mark.parametrize("ecvl", [ecvl_core, ecvl_py]) def test_OpticalDistortion(ecvl): dims = [20, 40, 3] img = ecvl.Image(dims, ecvl.DataType.uint8, "xyc", ecvl.ColorType.BGR) tmp = _empty_img(ecvl) ecvl.OpticalDistortion(img, tmp) ecvl.OpticalDistortion(img, tmp) ecvl.OpticalDistortion(img, tmp, [-0.5, 0.5]) ecvl.OpticalDistortion(img, tmp, [-0.5, 0.5], [-0.2, 0.2]) ecvl.OpticalDistortion( img, tmp, [-0.5, 0.5], [-0.2, 0.2], ecvl.InterpolationType.nearest ) ecvl.OpticalDistortion( img, tmp, [-0.5, 0.5], [-0.2, 0.2], ecvl.InterpolationType.nearest, ecvl.BorderType.BORDER_CONSTANT ) ecvl.OpticalDistortion( img, tmp, [-0.5, 0.5], [-0.2, 0.2], ecvl.InterpolationType.nearest, ecvl.BorderType.BORDER_CONSTANT, 12345 ) @pytest.mark.parametrize("ecvl", [ecvl_core, ecvl_py]) def test_Salt(ecvl): dims = [20, 40, 3] img = ecvl.Image(dims, ecvl.DataType.uint8, "xyc", ecvl.ColorType.BGR) tmp = _empty_img(ecvl) ecvl.Salt(img, tmp, 0.4) ecvl.Salt(img, tmp, 0.4, True) ecvl.Salt(img, tmp, 0.4, True, 12345) @pytest.mark.parametrize("ecvl", [ecvl_core, ecvl_py]) def test_Pepper(ecvl): dims = [20, 40, 3] img = ecvl.Image(dims, ecvl.DataType.uint8, "xyc", ecvl.ColorType.BGR) tmp = _empty_img(ecvl) ecvl.Pepper(img, tmp, 0.4) ecvl.Pepper(img, tmp, 0.4, True) ecvl.Pepper(img, tmp, 0.4, True, 12345) @pytest.mark.parametrize("ecvl", [ecvl_core, ecvl_py]) def test_SaltAndPepper(ecvl): dims = [20, 40, 3] img = ecvl.Image(dims, ecvl.DataType.uint8, "xyc", ecvl.ColorType.BGR) tmp = _empty_img(ecvl) ecvl.SaltAndPepper(img, tmp, 0.4) ecvl.SaltAndPepper(img, tmp, 0.4, True) ecvl.SaltAndPepper(img, tmp, 0.4, True, 12345) @pytest.mark.parametrize("ecvl", [ecvl_core, ecvl_py]) def test_SliceTimingCorrection(ecvl): dims = [20, 40, 10, 30] spacings = [1, 2, 3, 4] img = ecvl.Image( dims, ecvl.DataType.float32, "xyzt", ecvl.ColorType.none, spacings ) tmp = _empty_img(ecvl) ecvl.SliceTimingCorrection(img, tmp) ecvl.SliceTimingCorrection(img, tmp, True) ecvl.SliceTimingCorrection(img, tmp, True, True) @pytest.mark.parametrize("ecvl", [ecvl_core, ecvl_py]) def test_DrawEllipse(ecvl): dims = [20, 20, 3] img = ecvl.Image(dims, ecvl.DataType.uint8, "xyc", ecvl.ColorType.BGR) ecvl.DrawEllipse(img, [10, 10], [7, 5], 15, [100]) ecvl.DrawEllipse(img, [10, 10], [7, 5], 15, [50, 50, 50]) ecvl.DrawEllipse(img, [10, 10], [7, 5], 15, [50, 50, 50], 2) @pytest.mark.parametrize("ecvl", [ecvl_core, ecvl_py]) def test_Moments(ecvl): dims = [20, 20, 3] img = ecvl.Image(dims, ecvl.DataType.uint8, "xyc", ecvl.ColorType.GRAY) moments = _empty_img(ecvl) ecvl.Moments(img, moments) assert moments.dims_ == [4, 4] assert moments.elemtype_ == ecvl.DataType.float64 ecvl.Moments(img, moments, 2) assert moments.dims_ == [3, 3] assert moments.elemtype_ == ecvl.DataType.float64 datatype = ecvl.DataType.float32 ecvl.Moments(img, moments, 2, datatype) assert moments.dims_ == [3, 3] assert moments.elemtype_ == datatype @pytest.mark.parametrize("ecvl", [ecvl_core, ecvl_py]) def test_CentralMoments(ecvl): dims = [20, 20, 3] img = ecvl.Image(dims, ecvl.DataType.uint8, "xyc", ecvl.ColorType.GRAY) moments = _empty_img(ecvl) ecvl.CentralMoments(img, moments, [10., 10.]) assert moments.dims_ == [4, 4] assert moments.elemtype_ == ecvl.DataType.float64 ecvl.CentralMoments(img, moments, [10., 10.], 2) assert moments.dims_ == [3, 3] assert moments.elemtype_ == ecvl.DataType.float64 datatype = ecvl.DataType.float32 ecvl.CentralMoments(img, moments, [10., 10.], 2, datatype) assert moments.dims_ == [3, 3] assert moments.elemtype_ == datatype @pytest.mark.parametrize("ecvl", [ecvl_core, ecvl_py]) def test_DropColorChannel(ecvl): dims = [20, 20, 3] img = ecvl.Image(dims, ecvl.DataType.uint8, "xyc", ecvl.ColorType.GRAY) ecvl.DropColorChannel(img) assert img.dims_ == [20, 20] assert img.channels_ == "xy" assert img.colortype_ == ecvl.ColorType.none @pytest.mark.parametrize("ecvl", [ecvl_core, ecvl_py]) def test_Normalize(ecvl): dims = [20, 40, 3] img = ecvl.Image(dims, ecvl.DataType.uint8, "xyc", ecvl.ColorType.BGR) tmp = _empty_img(ecvl) ecvl.Normalize(img, tmp, 20, 5.5) ecvl.Normalize(img, tmp, [20], [5.5]) @pytest.mark.parametrize("ecvl", [ecvl_core, ecvl_py]) def test_Normalize_separate(ecvl): dims = [20, 40, 3] img = ecvl.Image(dims, ecvl.DataType.uint8, "xyc", ecvl.ColorType.BGR) tmp = _empty_img(ecvl) ecvl.Normalize(img, tmp, [20, 19, 21], [5, 5.5, 6]) @pytest.mark.parametrize("ecvl", [ecvl_core, ecvl_py]) def test_CenterCrop(ecvl): dims = [20, 40, 3] img = ecvl.Image(dims, ecvl.DataType.uint8, "xyc", ecvl.ColorType.BGR) tmp = _empty_img(ecvl) ecvl.CenterCrop(img, tmp, [10, 20]) @pytest.mark.parametrize("ecvl", [ecvl_core, ecvl_py]) def test_ScaleTo(ecvl): dims = [20, 40, 3] img = ecvl.Image(dims, ecvl.DataType.uint8, "xyc", ecvl.ColorType.BGR) tmp = _empty_img(ecvl) ecvl.ScaleTo(img, tmp, 1, 254) @pytest.mark.parametrize("ecvl", [ecvl_core, ecvl_py]) def test_Pad(ecvl): dims = [20, 40, 3] img = ecvl.Image(dims, ecvl.DataType.uint8, "xyc", ecvl.ColorType.BGR) tmp = _empty_img(ecvl) for padding in [3], [2, 3], [1, 2, 3, 4]: ecvl.Pad(img, tmp, padding) ecvl.Pad(img, tmp, [3], ecvl.BorderType.BORDER_REFLECT_101) ecvl.Pad(img, tmp, [3], ecvl.BorderType.BORDER_CONSTANT, 255) @pytest.mark.parametrize("ecvl", [ecvl_core, ecvl_py]) def test_RandomCrop(ecvl): dims = [20, 40, 3] img = ecvl.Image(dims, ecvl.DataType.uint8, "xyc", ecvl.ColorType.BGR) tmp = _empty_img(ecvl) ecvl.RandomCrop(img, tmp, [10, 20]) with pytest.raises(RuntimeError): ecvl.RandomCrop(img, tmp, [22, 42]) ecvl.RandomCrop(img, tmp, [22, 42], True) ecvl.RandomCrop(img, tmp, [22, 42], True, ecvl.BorderType.BORDER_REFLECT_101) ecvl.RandomCrop(img, tmp, [22, 42], True, ecvl.BorderType.BORDER_CONSTANT, 1) ecvl.RandomCrop(img, tmp, [22, 42], True, ecvl.BorderType.BORDER_CONSTANT, 1, 12345)
[ "numpy.zeros", "pytest.mark.parametrize", "pytest.raises", "numpy.array" ]
[((1302, 1355), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""ecvl"""', '[ecvl_core, ecvl_py]'], {}), "('ecvl', [ecvl_core, ecvl_py])\n", (1325, 1355), False, 'import pytest\n'), ((1733, 1786), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""ecvl"""', '[ecvl_core, ecvl_py]'], {}), "('ecvl', [ecvl_core, ecvl_py])\n", (1756, 1786), False, 'import pytest\n'), ((2169, 2222), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""ecvl"""', '[ecvl_core, ecvl_py]'], {}), "('ecvl', [ecvl_core, ecvl_py])\n", (2192, 2222), False, 'import pytest\n'), ((2434, 2487), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""ecvl"""', '[ecvl_core, ecvl_py]'], {}), "('ecvl', [ecvl_core, ecvl_py])\n", (2457, 2487), False, 'import pytest\n'), ((2703, 2756), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""ecvl"""', '[ecvl_core, ecvl_py]'], {}), "('ecvl', [ecvl_core, ecvl_py])\n", (2726, 2756), False, 'import pytest\n'), ((3175, 3228), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""ecvl"""', '[ecvl_core, ecvl_py]'], {}), "('ecvl', [ecvl_core, ecvl_py])\n", (3198, 3228), False, 'import pytest\n'), ((3612, 3665), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""ecvl"""', '[ecvl_core, ecvl_py]'], {}), "('ecvl', [ecvl_core, ecvl_py])\n", (3635, 3665), False, 'import pytest\n'), ((3979, 4032), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""ecvl"""', '[ecvl_core, ecvl_py]'], {}), "('ecvl', [ecvl_core, ecvl_py])\n", (4002, 4032), False, 'import pytest\n'), ((4352, 4405), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""ecvl"""', '[ecvl_core, ecvl_py]'], {}), "('ecvl', [ecvl_core, ecvl_py])\n", (4375, 4405), False, 'import pytest\n'), ((4986, 5039), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""ecvl"""', '[ecvl_core, ecvl_py]'], {}), "('ecvl', [ecvl_core, ecvl_py])\n", (5009, 5039), False, 'import pytest\n'), ((5522, 5575), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""ecvl"""', '[ecvl_core, ecvl_py]'], {}), "('ecvl', [ecvl_core, ecvl_py])\n", (5545, 5575), False, 'import pytest\n'), ((5911, 5964), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""ecvl"""', '[ecvl_core, ecvl_py]'], {}), "('ecvl', [ecvl_core, ecvl_py])\n", (5934, 5964), False, 'import pytest\n'), ((6412, 6465), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""ecvl"""', '[ecvl_core, ecvl_py]'], {}), "('ecvl', [ecvl_core, ecvl_py])\n", (6435, 6465), False, 'import pytest\n'), ((6703, 6756), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""ecvl"""', '[ecvl_core, ecvl_py]'], {}), "('ecvl', [ecvl_core, ecvl_py])\n", (6726, 6756), False, 'import pytest\n'), ((6989, 7042), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""ecvl"""', '[ecvl_core, ecvl_py]'], {}), "('ecvl', [ecvl_core, ecvl_py])\n", (7012, 7042), False, 'import pytest\n'), ((7255, 7308), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""ecvl"""', '[ecvl_core, ecvl_py]'], {}), "('ecvl', [ecvl_core, ecvl_py])\n", (7278, 7308), False, 'import pytest\n'), ((7580, 7633), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""ecvl"""', '[ecvl_core, ecvl_py]'], {}), "('ecvl', [ecvl_core, ecvl_py])\n", (7603, 7633), False, 'import pytest\n'), ((7906, 7959), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""ecvl"""', '[ecvl_core, ecvl_py]'], {}), "('ecvl', [ecvl_core, ecvl_py])\n", (7929, 7959), False, 'import pytest\n'), ((8166, 8219), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""ecvl"""', '[ecvl_core, ecvl_py]'], {}), "('ecvl', [ecvl_core, ecvl_py])\n", (8189, 8219), False, 'import pytest\n'), ((8570, 8623), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""ecvl"""', '[ecvl_core, ecvl_py]'], {}), "('ecvl', [ecvl_core, ecvl_py])\n", (8593, 8623), False, 'import pytest\n'), ((8844, 8897), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""ecvl"""', '[ecvl_core, ecvl_py]'], {}), "('ecvl', [ecvl_core, ecvl_py])\n", (8867, 8897), False, 'import pytest\n'), ((9056, 9109), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""ecvl"""', '[ecvl_core, ecvl_py]'], {}), "('ecvl', [ecvl_core, ecvl_py])\n", (9079, 9109), False, 'import pytest\n'), ((9394, 9447), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""ecvl"""', '[ecvl_core, ecvl_py]'], {}), "('ecvl', [ecvl_core, ecvl_py])\n", (9417, 9447), False, 'import pytest\n'), ((9732, 9785), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""ecvl"""', '[ecvl_core, ecvl_py]'], {}), "('ecvl', [ecvl_core, ecvl_py])\n", (9755, 9785), False, 'import pytest\n'), ((10066, 10119), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""ecvl"""', '[ecvl_core, ecvl_py]'], {}), "('ecvl', [ecvl_core, ecvl_py])\n", (10089, 10119), False, 'import pytest\n'), ((10883, 10936), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""ecvl"""', '[ecvl_core, ecvl_py]'], {}), "('ecvl', [ecvl_core, ecvl_py])\n", (10906, 10936), False, 'import pytest\n'), ((11291, 11344), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""ecvl"""', '[ecvl_core, ecvl_py]'], {}), "('ecvl', [ecvl_core, ecvl_py])\n", (11314, 11344), False, 'import pytest\n'), ((11513, 11566), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""ecvl"""', '[ecvl_core, ecvl_py]'], {}), "('ecvl', [ecvl_core, ecvl_py])\n", (11536, 11566), False, 'import pytest\n'), ((11748, 11801), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""ecvl"""', '[ecvl_core, ecvl_py]'], {}), "('ecvl', [ecvl_core, ecvl_py])\n", (11771, 11801), False, 'import pytest\n'), ((12602, 12655), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""ecvl"""', '[ecvl_core, ecvl_py]'], {}), "('ecvl', [ecvl_core, ecvl_py])\n", (12625, 12655), False, 'import pytest\n'), ((13414, 13467), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""ecvl"""', '[ecvl_core, ecvl_py]'], {}), "('ecvl', [ecvl_core, ecvl_py])\n", (13437, 13467), False, 'import pytest\n'), ((14233, 14286), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""ecvl"""', '[ecvl_core, ecvl_py]'], {}), "('ecvl', [ecvl_core, ecvl_py])\n", (14256, 14286), False, 'import pytest\n'), ((14542, 14595), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""ecvl"""', '[ecvl_core, ecvl_py]'], {}), "('ecvl', [ecvl_core, ecvl_py])\n", (14565, 14595), False, 'import pytest\n'), ((14859, 14912), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""ecvl"""', '[ecvl_core, ecvl_py]'], {}), "('ecvl', [ecvl_core, ecvl_py])\n", (14882, 14912), False, 'import pytest\n'), ((15204, 15257), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""ecvl"""', '[ecvl_core, ecvl_py]'], {}), "('ecvl', [ecvl_core, ecvl_py])\n", (15227, 15257), False, 'import pytest\n'), ((15626, 15679), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""ecvl"""', '[ecvl_core, ecvl_py]'], {}), "('ecvl', [ecvl_core, ecvl_py])\n", (15649, 15679), False, 'import pytest\n'), ((15991, 16044), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""ecvl"""', '[ecvl_core, ecvl_py]'], {}), "('ecvl', [ecvl_core, ecvl_py])\n", (16014, 16044), False, 'import pytest\n'), ((16602, 16655), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""ecvl"""', '[ecvl_core, ecvl_py]'], {}), "('ecvl', [ecvl_core, ecvl_py])\n", (16625, 16655), False, 'import pytest\n'), ((17277, 17330), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""ecvl"""', '[ecvl_core, ecvl_py]'], {}), "('ecvl', [ecvl_core, ecvl_py])\n", (17300, 17330), False, 'import pytest\n'), ((17612, 17665), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""ecvl"""', '[ecvl_core, ecvl_py]'], {}), "('ecvl', [ecvl_core, ecvl_py])\n", (17635, 17665), False, 'import pytest\n'), ((17900, 17953), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""ecvl"""', '[ecvl_core, ecvl_py]'], {}), "('ecvl', [ecvl_core, ecvl_py])\n", (17923, 17953), False, 'import pytest\n'), ((18173, 18226), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""ecvl"""', '[ecvl_core, ecvl_py]'], {}), "('ecvl', [ecvl_core, ecvl_py])\n", (18196, 18226), False, 'import pytest\n'), ((18422, 18475), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""ecvl"""', '[ecvl_core, ecvl_py]'], {}), "('ecvl', [ecvl_core, ecvl_py])\n", (18445, 18475), False, 'import pytest\n'), ((18663, 18716), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""ecvl"""', '[ecvl_core, ecvl_py]'], {}), "('ecvl', [ecvl_core, ecvl_py])\n", (18686, 18716), False, 'import pytest\n'), ((19077, 19130), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""ecvl"""', '[ecvl_core, ecvl_py]'], {}), "('ecvl', [ecvl_core, ecvl_py])\n", (19100, 19130), False, 'import pytest\n'), ((5361, 5389), 'numpy.array', 'np.array', (['kernel'], {'copy': '(False)'}), '(kernel, copy=False)\n', (5369, 5389), True, 'import numpy as np\n'), ((19332, 19359), 'pytest.raises', 'pytest.raises', (['RuntimeError'], {}), '(RuntimeError)\n', (19345, 19359), False, 'import pytest\n'), ((8270, 8298), 'numpy.zeros', 'np.zeros', (['(12)'], {'dtype': 'np.int32'}), '(12, dtype=np.int32)\n', (8278, 8298), True, 'import numpy as np\n')]
import numpy as np import pandas as pd class FplusTreeSampling(object): """ F+ tree for sampling from a large population Construct in O(N) time Sample and update in O(log(N)) time """ def __init__(self, dimension, weights=None): self.dimension = dimension self.layers = int(np.ceil(np.log2(dimension))) self.F = [np.array([])] * self.layers self.initialize(weights) def initialize(self, weights=None): """ initialize F+ tree with uniform weights """ # initialzie last layer with weights if weights is None: weight = 1.0 / self.dimension self.F[-1] = np.ones((self.dimension,)) * weight else: self.F[-1] = weights # for l in range(self.layers-2, -1 , -1): # weight *= 2 # length = int(np.ceil(self.F[l+1].shape[0]/2.0)) # self.F[l] = np.ones((length,)) * weight # if len(self.F[l+1])%2 != 0 : # self.F[l][-1] = self.F[l+1][-1] # else: # self.F[l][-1] = self.F[l+1][-1] + self.F[l+1][-2] # assert(self.F[0][0] + self.F[0][1] == 1.0) for l in range(self.layers - 2, -1, -1): length = int(np.ceil(self.F[l + 1].shape[0] / 2.0)) self.F[l] = np.ones((length,)) if len(self.F[l + 1]) % 2 != 0: self.F[l][:-1] = self.F[l + 1][:-1].reshape((-1, 2)).sum(axis=1) self.F[l][-1] = self.F[l + 1][-1] else: self.F[l] = self.F[l + 1].reshape((-1, 2)).sum(axis=1) def print_graph(self): if self.dimension > 1000: print("Are you crazy?") return for fl in self.F: for prob in fl: print(prob, " ") print("||") def total_weight(self): """ return the total weight sum """ return self.F[0][0] + self.F[0][1] def get_weight(self, indices): """ return the weight of given indices """ return self.F[-1][indices] def sample_batch(self, batch_size): """ sample a batch without replacement """ indices = np.zeros((batch_size,), dtype=np.int) weights = np.zeros((batch_size,), dtype=np.float) for i in range(batch_size): indices[i] = self.__sample() weights[i] = self.F[-1][indices[i]] self.__update(indices[i], 0) # wighout replacement self.update_batch(indices, weights) # resume their original weights return indices def update_batch(self, indices, probs): """ update weights of a given batch """ for i, p in zip(indices, probs): self.__update(i, p) def __sample(self): """ sample a single node, in log(N) time """ u = np.random.sample() * self.F[0][0] i = 0 for fl in self.F[1:]: # i_left = 2*i # i_right = 2*i +1 if u > fl[2 * i] and fl.shape[0] >= 2 * (i + 1): # then chose i_right u -= fl[2 * i] i = 2 * i + 1 else: i = 2 * i return i def __update(self, idx, prob): """ update weight of a single node, in log(N) time """ delta = prob - self.F[-1][idx] for l in range(self.layers - 1, -1, -1): self.F[l][idx] += delta idx = idx // 2
[ "numpy.ceil", "numpy.log2", "numpy.zeros", "numpy.ones", "numpy.array", "numpy.random.sample" ]
[((2227, 2264), 'numpy.zeros', 'np.zeros', (['(batch_size,)'], {'dtype': 'np.int'}), '((batch_size,), dtype=np.int)\n', (2235, 2264), True, 'import numpy as np\n'), ((2283, 2322), 'numpy.zeros', 'np.zeros', (['(batch_size,)'], {'dtype': 'np.float'}), '((batch_size,), dtype=np.float)\n', (2291, 2322), True, 'import numpy as np\n'), ((1320, 1338), 'numpy.ones', 'np.ones', (['(length,)'], {}), '((length,))\n', (1327, 1338), True, 'import numpy as np\n'), ((2900, 2918), 'numpy.random.sample', 'np.random.sample', ([], {}), '()\n', (2916, 2918), True, 'import numpy as np\n'), ((325, 343), 'numpy.log2', 'np.log2', (['dimension'], {}), '(dimension)\n', (332, 343), True, 'import numpy as np\n'), ((364, 376), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (372, 376), True, 'import numpy as np\n'), ((679, 705), 'numpy.ones', 'np.ones', (['(self.dimension,)'], {}), '((self.dimension,))\n', (686, 705), True, 'import numpy as np\n'), ((1257, 1294), 'numpy.ceil', 'np.ceil', (['(self.F[l + 1].shape[0] / 2.0)'], {}), '(self.F[l + 1].shape[0] / 2.0)\n', (1264, 1294), True, 'import numpy as np\n')]
# -*- coding: utf-8 -*- ''' Budget Support Vector Machine under POM6 ''' __author__ = "<NAME>" __date__ = "Apr. 2021" import numpy as np from MMLL.models.Common_to_all_POMs import Common_to_all_POMs from transitions import State from transitions.extensions import GraphMachine #from pympler import asizeof #asizeof.asizeof(my_object) from sklearn.metrics import roc_curve, auc from pympler import asizeof #asizeof.asizeof(my_object) import pickle import dill import time class Model(): """ Budget Support Vector Machine model. """ def __init__(self): self.C = None self.w = None self.sigma = None self.Csvm = None self.is_trained = False self.supported_formats = ['pkl', 'onnx', 'pmml'] t = time.time() seed = int((t - int(t)) * 10000) np.random.seed(seed=seed) def predict(self, X): """ Predicts outputs given the inputs Parameters ---------- X: ndarray Matrix with the input values Returns ------- prediction_values: ndarray """ NP = X.shape[0] NC = self.C.shape[0] XC2 = -2 * np.dot(X, self.C.T) XC2 += np.sum(np.multiply(X, X), axis=1).reshape((NP, 1)) XC2 += np.sum(np.multiply(self.C, self.C), axis=1).reshape((1, NC)) # Gauss KXC = np.exp(-XC2 / 2.0 / (self.sigma ** 2)) #1 ./ ( 1 + ((x).^2 / (2 * sigma ^2 ))); #KXC = 1 / (1 + (XC2 / 2.0 / (self.sigma ** 2) ) ) # bias KXC = np.hstack( (np.ones((NP, 1)), KXC)) prediction_values = np.dot(KXC, self.w) return prediction_values def save(self, filename=None): """ Saves the trained model to file. The valid file extensions are: - "pkl": saves the model as a Python3 pickle file - "onnx": saves the model using Open Neural Network Exchange format (ONNX)' - "pmml": saves the model using Predictive Model Markup Language (PMML)' Parameters ---------- filename: string path+filename """ if filename is None: print('=' * 80) print('Model Save Error: A valid filename must be provided, otherwise nothing is saved. The valid file extensions are:') print('\t - "pkl": saves the model as a Python3 pickle file') print('\t - "onnx": saves the model using Open Neural Network Exchange format (ONNX)') print('\t - "pmml": saves the model using Predictive Model Markup Language (PMML)') print('=' * 80) else: # Checking filename extension extension = filename.split('.')[-1] if extension not in self.supported_formats: print('=' * 80) print('Model Save Error: Unsupported format. The valid file extensions are:') print('\t - "pkl": saves the model as a Python3 pickle file') print('\t - "onnx": saves the model using Open Neural Network Exchange format (ONNX)') print('\t - "pmml": saves the model using Predictive Model Markup Language (PMML)') print('=' * 80) else: if not self.is_trained: print('=' * 80) print('Model Save Error: model not trained yet, nothing to save.') print('=' * 80) else: try: if extension == 'pkl': with open(filename, 'wb') as f: pickle.dump(self, f) print('=' * 80) print('Model saved at %s in pickle format.' %filename) print('=' * 80) elif extension == 'onnx': from skl2onnx import convert_sklearn # conda install -c conda-forge skl2onnx from skl2onnx.common.data_types import FloatTensorType from sklearn.svm import SVR NC = self.C.shape[0] NI = self.C.shape[1] gamma = 1 / 2 / self.sigma**2 export_model = SVR(C=1.0, gamma=gamma) X = np.random.normal(0, 1, (100, NI)) w = np.random.normal(0, 1, (NI, 1)) y = np.sign(np.dot(X, w)).ravel() export_model.fit(X, y) export_model.support_vectors_ = self.C export_model._dual_coef_ = self.w[1:, :].T export_model.dual_coef_ = self.w[1:, :].T export_model._intercept_ = self.w[0, :] export_model.intercept_ = self.w[0, :] export_model.n_support_[0] = NC export_model.support_ = np.array(range(NC)) # Convert into ONNX format input_type = [('float_input', FloatTensorType([None, NI]))] onnx_model = convert_sklearn(export_model, initial_types=input_type) with open(filename, "wb") as f: f.write(onnx_model.SerializeToString()) print('=' * 80) print('Model saved at %s in ONNX format.' %filename) print('=' * 80) elif extension == 'pmml': from sklearn2pmml import sklearn2pmml # pip install git+https://github.com/jpmml/sklearn2pmml.git from sklearn2pmml.pipeline import PMMLPipeline from sklearn.svm import SVR NC = self.C.shape[0] NI = self.C.shape[1] gamma = 1 / 2 / self.sigma**2 export_model = SVR(C=1.0, gamma=gamma) X = np.random.normal(0, 1, (100, NI)) w = np.random.normal(0, 1, (NI, 1)) y = np.sign(np.dot(X, w)).ravel() export_model.fit(X, y) export_model.support_vectors_ = self.C export_model._dual_coef_ = self.w[1:, :].T export_model.dual_coef_ = self.w[1:, :].T export_model._intercept_ = self.w[0, :] export_model.intercept_ = self.w[0, :] export_model.n_support_[0] = NC export_model.support_ = np.array(range(NC)) pipeline = PMMLPipeline([("estimator", export_model)]) sklearn2pmml(pipeline, filename, with_repr = True) print('=' * 80) print('Model saved at %s in PMML format.' %filename) print('=' * 80) else: print('=' * 80) print('Model Save Error: model cannot be saved at %s.' %filename) print('=' * 80) except: print('=' * 80) print('Model Save Error: model cannot be saved at %s, please check the provided path/filename.' %filename) print('=' * 80) raise class BSVM_Master(Common_to_all_POMs): """ This class implements the Budget Support Vector Machine, run at Master node. It inherits from Common_to_all_POMs. """ def __init__(self, master_address, workers_addresses, model_type, comms, logger, verbose=True, **kwargs): """ Create a :class:`BSVM_Master` instance. Parameters ---------- master_address: string address of the master node workers_addresses: list of strings list of the addresses of the workers comms: comms object instance object providing communications logger: class:`logging.Logger` logging object instance verbose: boolean indicates if messages are print or not on screen kwargs: Keyword arguments. """ super().__init__() self.pom = 6 self.model_type = model_type self.name = self.model_type + '_Master' # Name self.master_address = master_address self.workers_addresses = workers_addresses self.epsilon = 0.00000001 # to avoid log(0) try: kwargs.update(kwargs['model_parameters']) del kwargs['model_parameters'] except Exception as err: pass self.process_kwargs(kwargs) # Convert workers_addresses -> '0', '1', + send_to dict self.broadcast_addresses = workers_addresses self.Nworkers = len(workers_addresses) # Nworkers self.workers_addresses = list(range(self.Nworkers)) self.workers_addresses = [str(x) for x in self.workers_addresses] self.send_to = {} self.receive_from = {} for k in range(self.Nworkers): self.send_to.update({str(k): workers_addresses[k]}) self.receive_from.update({workers_addresses[k]: str(k)}) self.logger = logger # logger self.comms = comms # comms lib self.verbose = verbose # print on screen when true self.NI = None self.state_dict = {} # dictionary storing the execution state for k in range(0, self.Nworkers): self.state_dict.update({self.workers_addresses[k]: ''}) # we extract the model_parameters as extra kwargs, to be all jointly processed try: kwargs.update(kwargs['model_parameters']) del kwargs['model_parameters'] except Exception as err: pass self.process_kwargs(kwargs) self.create_FSM_master() self.FSMmaster.master_address = master_address self.message_counter = 100 # used to number the messages self.cryptonode_address = None self.KTK_dict = {} self.KTy_dict = {} #self.NC = self.C.shape[0] self.NI = self.C.shape[1] self.newNI_dict = {} self.model = Model() self.model.C = self.C self.model.sigma = np.sqrt(self.NI) * self.fsigma self.model.Csvm = self.Csvm self.Kacum_dict = {} self.grady_dict = {} self.s0_dict = {} self.s1_dict = {} self.grads_dict = {} self.Ztr_dict = {} self.NPtr_dict = {} self.eps = 0.0000001 t = time.time() seed = int((t - int(t)) * 10000) np.random.seed(seed=seed) def create_FSM_master(self): """ Creates a Finite State Machine to be run at the Master Node Parameters ---------- None """ self.display(self.name + ': creating FSM') states_master = [ State(name='waiting_order', on_enter=['while_waiting_order']), State(name='update_tr_data', on_enter=['while_update_tr_data']), State(name='getting_KTK', on_enter=['while_getting_KTK']), State(name='selecting_C', on_enter=['while_selecting_C']), State(name='sending_C', on_enter=['while_sending_C']), State(name='computing_XTw', on_enter=['while_computing_XTw']), State(name='computing_oi', on_enter=['while_computing_oi']), State(name='updating_w', on_enter=['while_updating_w']) ] transitions_master = [ ['go_update_tr_data', 'waiting_order', 'update_tr_data'], ['go_waiting_order', 'update_tr_data', 'waiting_order'], ['go_selecting_C', 'waiting_order', 'selecting_C'], ['go_waiting_order', 'selecting_C', 'waiting_order'], ['go_sending_C', 'waiting_order', 'sending_C'], ['go_waiting_order', 'sending_C', 'waiting_order'], ['go_computing_oi', 'waiting_order', 'computing_oi'], ['go_waiting_order', 'computing_oi', 'waiting_order'], ['go_getting_KTK', 'waiting_order', 'getting_KTK'], ['go_waiting_order', 'getting_KTK', 'waiting_order'], ['go_computing_XTw', 'waiting_order', 'computing_XTw'], ['go_waiting_order', 'computing_XTw', 'waiting_order'], ['go_updating_w', 'waiting_order', 'updating_w'], ['go_waiting_order', 'updating_w', 'waiting_order'] ] class FSM_master(object): self.name = 'FSM_master' def while_waiting_order(self, MLmodel): MLmodel.display(MLmodel.name + ': WAITING for instructions...') return def while_update_tr_data(self, MLmodel): try: action = 'update_tr_data' data = {} packet = {'action': action, 'to': 'MLmodel', 'data': data, 'sender': MLmodel.master_address} message_id = MLmodel.master_address+'_'+str(MLmodel.message_counter) packet.update({'message_id': message_id}) MLmodel.message_counter += 1 size_bytes = asizeof.asizeof(dill.dumps(packet)) MLmodel.display('COMMS_MASTER_BROADCAST %s, id = %s, bytes=%s' % (action, message_id, str(size_bytes)), verbose=False) MLmodel.comms.broadcast(packet) MLmodel.display(MLmodel.name + ': broadcasted update_tr_data to all Workers') except Exception as err: raise ''' message = "ERROR: %s %s" % (str(err), str(type(err))) MLmodel.display('\n ' + '='*50 + '\n' + message + '\n ' + '='*50 + '\n' ) MLmodel.display('ERROR AT while_update_tr_data') import code code.interact(local=locals()) ''' return def while_selecting_C(self, MLmodel): try: action = 'selecting_C' data = {'C': MLmodel.model.C, 'sigma': MLmodel.model.sigma} packet = {'action': action, 'to': 'MLmodel', 'data': data, 'sender': MLmodel.master_address} message_id = MLmodel.master_address+'_'+str(MLmodel.message_counter) packet.update({'message_id': message_id}) MLmodel.message_counter += 1 size_bytes = asizeof.asizeof(dill.dumps(packet)) MLmodel.display('COMMS_MASTER_BROADCAST %s, id = %s, bytes=%s' % (action, message_id, str(size_bytes)), verbose=False) if MLmodel.selected_workers is None: MLmodel.comms.broadcast(packet) MLmodel.display(MLmodel.name + ': broadcasted C to all Workers') else: MLmodel.comms.broadcast(packet, MLmodel.selected_workers) MLmodel.display(MLmodel.name + ': broadcasted C to Workers: %s' % str([MLmodel.receive_from[w] for w in MLmodel.selected_workers])) except Exception as err: raise ''' print('ERROR AT while_selecting_C') import code code.interact(local=locals()) ''' return def while_sending_C(self, MLmodel): try: action = 'sending_C' data = {'C': MLmodel.model.C, 'sigma': MLmodel.model.sigma, 'Csvm': MLmodel.model.Csvm} packet = {'action': action, 'to': 'MLmodel', 'data': data, 'sender': MLmodel.master_address} message_id = MLmodel.master_address+'_'+str(MLmodel.message_counter) packet.update({'message_id': message_id}) MLmodel.message_counter += 1 size_bytes = asizeof.asizeof(dill.dumps(packet)) MLmodel.display('COMMS_MASTER_BROADCAST %s, id = %s, bytes=%s' % (action, message_id, str(size_bytes)), verbose=False) if MLmodel.selected_workers is None: MLmodel.comms.broadcast(packet) MLmodel.display(MLmodel.name + ': broadcasted C to all Workers') else: MLmodel.comms.broadcast(packet, MLmodel.selected_workers) MLmodel.display(MLmodel.name + ': broadcasted C to Workers: %s' % str([MLmodel.receive_from[w] for w in MLmodel.selected_workers])) except Exception as err: raise ''' print('ERROR AT while_sending_C') import code code.interact(local=locals()) ''' return def while_computing_XTw(self, MLmodel): try: MLmodel.display('PROC_MASTER_START', verbose=False) action = 'computing_XTw' MLmodel.x = MLmodel.model.w.T NItrain = MLmodel.x.shape[1] K = int(NItrain / 2) # Guardar MLmodel.A = np.random.uniform(-10, 10, K).reshape((1, K)) MLmodel.C = np.random.uniform(-10, 10, K).reshape((1, K)) MLmodel.xa = MLmodel.x[:, 0:K] MLmodel.xb = MLmodel.x[:, K:] # Enviar xa_ = MLmodel.xa + MLmodel.A xb_ = MLmodel.xb + MLmodel.C P = MLmodel.A + MLmodel.C # warning, check the sum is nonzero (low prob...) # broadcasts xa_, xb_, P action = 'sending_xaxbP' data = {'xa_': xa_, 'xb_': xb_, 'P': P} del xa_, xb_, P MLmodel.display('PROC_MASTER_END', verbose=False) #message_id = MLmodel.master_address + '_' + str(MLmodel.message_counter) #packet = {'action': action, 'to': 'MLmodel', 'data': data, 'sender': MLmodel.master_address, 'message_id': message_id} packet = {'action': action, 'to': 'MLmodel', 'data': data, 'sender': MLmodel.master_address} message_id = MLmodel.master_address+'_'+str(MLmodel.message_counter) packet.update({'message_id': message_id}) MLmodel.message_counter += 1 size_bytes = asizeof.asizeof(dill.dumps(packet)) MLmodel.display('COMMS_MASTER_BROADCAST %s, id = %s, bytes=%s' % (action, message_id, str(size_bytes)), verbose=False) del data if MLmodel.selected_workers is None: MLmodel.comms.broadcast(packet) MLmodel.display(MLmodel.name + ': computing_XTw with all Workers') else: recipients = [MLmodel.send_to[w] for w in MLmodel.selected_workers] MLmodel.comms.broadcast(packet, recipients) MLmodel.display(MLmodel.name + ': computing_XTw with Workers: %s' % str(MLmodel.selected_workers)) except Exception as err: raise ''' message = "ERROR: %s %s" % (str(err), str(type(err))) MLmodel.display('\n ' + '='*50 + '\n' + message + '\n ' + '='*50 + '\n' ) MLmodel.display('ERROR AT while_computing_XTw') import code code.interact(local=locals()) ''' return def while_computing_oi(self, MLmodel): # MLmodel.s0_dict, MLmodel.s1_dict try: MLmodel.o_dict = {} for addr in MLmodel.workers_addresses: MLmodel.display('PROC_MASTER_START', verbose=False) #MLmodel.display('PROC_MASTER_START', verbose=False) U0 = MLmodel.s0_dict[addr]['ya_0'] * (MLmodel.xa + 2 * MLmodel.A) + MLmodel.s0_dict[addr]['yb_0'] * (MLmodel.xb + 2 * MLmodel.C) + MLmodel.s0_dict[addr]['Q0'] * (MLmodel.A + 2 * MLmodel.C) u0 = np.sum(U0, axis=1) del U0 s0 = u0 + MLmodel.s0_dict[addr]['v0'] del u0 NPtr0 = s0.shape[0] y0 = -np.ones(NPtr0) e0 = y0 - s0 del s0 # Weighting values a a0 = np.ones(NPtr0) ey0 = e0 * y0 which0 = ey0 >= MLmodel.eps a0[which0] = 2 * MLmodel.Csvm / ey0[which0] which0 = ey0 < MLmodel.eps a0[which0] = 2 * MLmodel.Csvm / MLmodel.eps which0 = ey0 < 0 a0[which0] = 0 a0 = a0.reshape((-1, 1)) del ey0, e0, which0 Rzz0 = MLmodel.Ztr_dict[addr]['Ztr0'] * a0 rzt0 = np.dot(Rzz0.T, y0) Rzz0 = np.dot(Rzz0.T, MLmodel.Ztr_dict[addr]['Ztr0']) del a0, y0 U1 = MLmodel.s1_dict[addr]['ya_1'] * (MLmodel.xa + 2 * MLmodel.A) + MLmodel.s1_dict[addr]['yb_1'] * (MLmodel.xb + 2 * MLmodel.C) + MLmodel.s1_dict[addr]['Q1'] * (MLmodel.A + 2 * MLmodel.C) u1 = np.sum(U1, axis=1) del U1 s1 = u1 + MLmodel.s1_dict[addr]['v1'] del u1 NPtr1 = s1.shape[0] y1 = np.ones(NPtr1) e1 = y1 - s1 del s1 # Weighting values a a1 = np.ones(NPtr1) ey1 = e1 * y1 which1 = ey1 >= MLmodel.eps a1[which1] = 2 * MLmodel.Csvm / ey1[which1] which1 = ey1 < MLmodel.eps a1[which1] = 2 * MLmodel.Csvm / MLmodel.eps which1 = ey1 < 0 a1[which1] = 0 a1 = a1.reshape((-1, 1)) del ey1, e1, which1 Rzz1 = MLmodel.Ztr_dict[addr]['Ztr1'] * a1 rzt1 = np.dot(Rzz1.T, y1) Rzz1 = np.dot(Rzz1.T, MLmodel.Ztr_dict[addr]['Ztr1']) del a1, y1 # Needed ? MLmodel.NPtr_dict.update({addr: NPtr0 + NPtr1}) action = 'sending_Rzz_rzt' data = {'Rzz': Rzz0 + Rzz1, 'rzt': rzt0 + rzt1} del Rzz0, Rzz1, rzt0, rzt1 MLmodel.display('PROC_MASTER_END', verbose=False) #message_id = MLmodel.master_address + '_' + str(MLmodel.message_counter) #packet = {'action': action, 'to': 'MLmodel', 'data': data, 'sender': MLmodel.master_address, 'message_id': message_id} packet = {'action': action, 'to': 'MLmodel', 'data': data, 'sender': MLmodel.master_address} del data message_id = MLmodel.master_address+'_'+str(MLmodel.message_counter) packet.update({'message_id': message_id}) MLmodel.message_counter += 1 size_bytes = asizeof.asizeof(dill.dumps(packet)) MLmodel.display('COMMS_MASTER_SEND %s to %s, id = %s, bytes=%s' % (action, addr, message_id, str(size_bytes)), verbose=False) MLmodel.comms.send(packet, MLmodel.send_to[addr]) #del packet, size_bytes, message_id del packet MLmodel.display(MLmodel.name + ' %s: sent sending_Rzz to %s' % (str(MLmodel.master_address), str(addr))) del MLmodel.xa, MLmodel.xb, MLmodel.A, MLmodel.C except: raise ''' print('ERROR AT while_computing_oi') import code code.interact(local=locals()) ''' return def while_getting_KTK(self, MLmodel): try: action = 'compute_KTK' data = {'w': MLmodel.model.w} packet = {'action': action, 'to': 'MLmodel', 'data': data, 'sender': MLmodel.master_address} message_id = MLmodel.master_address+'_'+str(MLmodel.message_counter) packet.update({'message_id': message_id}) MLmodel.message_counter += 1 size_bytes = asizeof.asizeof(dill.dumps(packet)) MLmodel.display('COMMS_MASTER_BROADCAST %s, id = %s, bytes=%s' % (action, message_id, str(size_bytes)), verbose=False) if MLmodel.selected_workers is None: MLmodel.comms.broadcast(packet) MLmodel.display(MLmodel.name + ': broadcasted compute_KTK to all workers') else: MLmodel.comms.broadcast(packet, MLmodel.selected_workers) MLmodel.display(MLmodel.name + ': broadcasted compute_KTK to Workers: %s' % str([MLmodel.receive_from[w] for w in MLmodel.selected_workers])) except Exception as err: raise ''' print('ERROR AT while_getting_KTK') import code code.interact(local=locals()) ''' return def while_updating_w(self, MLmodel): try: MLmodel.display('PROC_MASTER_START', verbose=False) MLmodel.KTK_accum = np.zeros((MLmodel.NItrain, MLmodel.NItrain)) MLmodel.KTy_accum = np.zeros((MLmodel.NItrain, 1)) for waddr in MLmodel.workers_addresses: MLmodel.KTK_accum += MLmodel.KTK_dict[waddr] MLmodel.KTy_accum += MLmodel.KTy_dict[waddr].reshape((-1, 1)) MLmodel.new_w = np.dot(np.linalg.inv(MLmodel.KTK_accum + MLmodel.Kcc), MLmodel.KTy_accum) MLmodel.display('PROC_MASTER_END', verbose=False) except Exception as err: raise ''' print('ERROR AT while_updating_w') import code code.interact(local=locals()) ''' return def while_Exit(self, MLmodel): #print('while_Exit') return self.FSMmaster = FSM_master() self.grafmachine_master = GraphMachine(model=self.FSMmaster, states=states_master, transitions=transitions_master, initial='waiting_order', show_auto_transitions=False, # default value is False title="Finite State Machine modelling the behaviour of the master", show_conditions=False) return def reset(self, NI): """ Create some empty variables needed by the Master Node Parameters ---------- NI: integer Number of input features """ self.NI = NI self.model.w = np.random.normal(0, 0.001, (self.NI + 1, 1)) # weights in plaintext, first value is bias self.w_old = np.random.normal(0, 1.0, (self.NI + 1, 1)) self.XTDaX_accum = np.zeros((self.NI + 1, self.NI + 1)) # Cov. matrix in plaintext self.XTDast_accum = np.zeros((self.NI + 1, 1)) # Cov. matrix in plaintext self.preds_dict = {} # dictionary storing the prediction errors self.XTX_dict = {} self.XTy_dict = {} self.display(self.name + ': Resetting local data') def train_Master(self): """ This is the main training loop, it runs the following actions until the stop condition is met: - Update the execution state - Process the received packets - Perform actions according to the state Parameters ---------- None """ self.display(self.name + ': Starting training') self.display('MASTER_INIT', verbose=False) self.FSMmaster.go_update_tr_data(self) self.run_Master() # Checking the new NI values newNIs = list(set(list(self.newNI_dict.values()))) if len(newNIs) > 1: message = 'ERROR: the training data has different number of features...' self.display(message) self.display(list(self.newNI_dict.values())) raise Exception(message) else: self.reset(newNIs[0]) ## Adding bias to validation data, if any #if self.Xval_b is not None: # self.Xval_b = self.add_bias(self.Xval_b).astype(float) # self.yval = self.yval.astype(float) ''' self.FSMmaster.go_selecting_C(self) self.run_Master() # Selecting centroids with largest projection Ncandidates = self.C.shape[0] Kacum_total = np.zeros(Ncandidates) for addr in self.workers_addresses: Kacum_total += self.Kacum_dict[addr].ravel() index = np.argsort(-Kacum_total) self.C = self.C[index[0: self.NC], :] ''' self.display('PROC_MASTER_START', verbose=False) self.model.C = self.C self.NC = self.C.shape[0] # computing Kcc, only once X = self.model.C XC2 = -2 * np.dot(X, self.model.C.T) XC2 += np.sum(np.multiply(X, X), axis=1).reshape((self.NC, 1)) XC2 += np.sum(np.multiply(self.model.C, self.model.C), axis=1).reshape((1, self.NC)) KCC = np.exp(-XC2 / 2.0 / (self.model.sigma ** 2)) self.Kcc = np.zeros((self.NC + 1, self.NC + 1)) self.Kcc[1:, 1:] = KCC self.Kcc[0, 0] = 0.00001 self.Bob_data_s = False self.Bob_data_grad = False self.NI = self.NC + 1 # Checking dimensions if int(self.NI / 2) != self.NI / 2: # add one value self.w_orig_size = self.NI self.NItrain = self.NI + 1 # Adding row and column to Kcc self.Kcc = np.hstack((self.Kcc, np.zeros((self.NI, 1)))) self.Kcc = np.vstack((self.Kcc, np.zeros((1, self.NI + 1)))) self.Kcc[self.NI, self.NI] = 1.0 else: self.w_orig_size = self.NI self.NItrain = self.NI # Computing and storing KXC_val if self.Xval is not None: XC2 = -2 * np.dot(self.Xval, self.C.T) XC2 += np.sum(np.multiply(self.Xval, self.Xval), axis=1).reshape((-1, 1)) XC2 += np.sum(np.multiply(self.C, self.C), axis=1).reshape((1, self.NC)) # Gauss KXC_val = np.exp(-XC2 / 2.0 / (self.model.sigma ** 2)) self.KXC_val = np.hstack( (np.ones((self.Xval.shape[0], 1)), KXC_val)) # NP_val x NC + 1 self.yval.astype(float).reshape((-1, 1)) self.model.w = np.random.normal(0, 0.0001, (self.NItrain, 1)) # weights in plaintext, first value is bias self.w_old = np.random.normal(0, 1.0, (self.NItrain, 1)) self.stop_training = False self.kiter = 0 self.display('PROC_MASTER_END', verbose=False) self.FSMmaster.go_sending_C(self) self.run_Master() self.ACC_val = 0 self.ACC_val_old = 0 while not self.stop_training: self.display('MASTER_ITER_START', verbose=False) self.w_old = self.model.w.copy() #self.ce_val_old = self.ce_val #self.FSMmaster.go_getting_KTK(self) #self.run_Master() self.FSMmaster.go_computing_XTw(self) self.run_Master() # We receive self.s_dict, self.Ztr_dict (once) self.FSMmaster.go_computing_oi(self) self.run_Master() # Updating w self.FSMmaster.go_updating_w(self) self.FSMmaster.go_waiting_order(self) self.kiter += 1 # Stop if Maxiter is reached if self.kiter == self.Nmaxiter: self.stop_training = True self.display('PROC_MASTER_START', verbose=False) if self.Xval is None: # A validation set is not provided self.model.w = (1 - self.landa) * self.w_old + self.landa * self.new_w inc_w = np.linalg.norm(self.model.w - self.w_old) / np.linalg.norm(self.w_old) message = 'Maxiter = %d, iter = %d, inc_w = %f' % (self.Nmaxiter, self.kiter, inc_w) #self.display(message) print(message) if inc_w <= self.conv_stop: self.stop_training = True else: # prediciendo para yval NIval = self.KXC_val.shape[1] #w_ = self.new_w[0: NIval] w_ = ((1 - self.landa) * self.w_old + self.landa * self.new_w)[0: NIval] preds_val = np.dot(self.KXC_val, w_) ACC_val = np.mean(np.sign(preds_val).ravel() == (self.yval * 2 -1)) if ACC_val > self.ACC_val_old: # retain the new self.model.w = (1 - self.landa) * self.w_old + self.landa * self.new_w self.ACC_val_old = ACC_val message = 'Maxiter = %d, iter = %d, ACC val = %f' % (self.Nmaxiter, self.kiter, ACC_val) print(message) else: # restore the previous one and stop self.model.w = self.w_old self.stop_training = True ''' NIval = self.KXC_val.shape[1] w_ = self.model.w[0: NIval] w_old_ = self.w_old[0: NIval] Kcc_ = self.Kcc[0: NIval, :] Kcc_ = Kcc_[:, 0: NIval] ''' self.w_old = self.model.w.copy() ''' if CEval_opt < self.ce_val_old: message = 'Maxiter = %d, iter = %d, CE val = %f' % (self.Nmaxiter, self.kiter, CEval_opt) print(message) self.model.w = (1.0 - landa_opt) * self.w_old + landa_opt * self.model.w self.ce_val = CEval_opt else: self.stop_training = True # We retain the last weight values self.model.w = self.w_old ''' ''' CE_val = [] landas = np.arange(0, 1.0, 0.01) which1 = (self.yval * 2 - 1) == 1 which_1 = (self.yval * 2 - 1) == -1 NP1 = np.sum(which1) NP_1 = np.sum(which_1) Xw = np.dot(self.KXC_val, w_) Xw_old = np.dot(self.KXC_val, w_old_) for landa in landas: w_tmp = landa * w_ + (1 - landa) * w_old_ o_tmp = landa * Xw + (1 - landa) * Xw_old ce_val = np.mean(self.cross_entropy(self.sigm(o_tmp), self.yval, self.epsilon)) CE_val.append(ce_val) e = (self.yval * 2 - 1) - o_tmp ey = (e * (self.yval * 2 - 1)).ravel() which = ey < 0 ey[which] = 0 Lp = 0.5 * np.dot(w_tmp.T, Kcc_) Lp = np.dot(Lp, w_tmp)[0, 0] Lp = Lp + self.Csvm * np.sum(ey) ERR_val.append(Lp) aciertos = np.sign(self.yval * 2 - 1) == np.sign(o_tmp) acc = (np.sum(aciertos[which1]) / NP1 + np.sum(aciertos[which_1]) / NP_1 )/ 2 fpr_val, tpr_val, thresholds_val = roc_curve(list(self.yval * 2 - 1), o_tmp) roc_auc_val = auc(fpr_val, tpr_val) ERR_val.append(roc_auc_val) ACC_val.append(acc) # Positions that fit the target value max_pos = np.argmax(ACC_val) ACCval_opt = ACC_val[max_pos] indices = np.array(range(len(landas)))[ACC_val == ACCval_opt] max_pos = indices[0] # first max_pos = indices[-1] # last landa_opt = landas[max_pos] ''' ''' # Positions that fit the target value min_pos = np.argmin(CE_val) CEval_opt = CE_val[min_pos] indices = np.array(range(len(landas)))[CE_val == CEval_opt] min_pos = indices[0] # first landa_opt = landas[min_pos] if np.sum(ERR_val == AUCval_opt) > 1: print('STOP HERE') import code code.interact(local=locals()) ''' #inc_err_val = (self.err_val_old - self.err_val)/ self.err_val #self.display(message) #inc_w = np.linalg.norm(self.model.w - self.w_old) / np.linalg.norm(self.w_old) #print('Optimal landa = %f, Lp val=%f' % (landa_opt, Lp_opt)) #self.err_val = Lp_opt #self.err_val = roc_auc_val ''' inc_err_val = (self.err_val_old - self.err_val)/ self.err_val # Stop if convergence is reached if inc_err_val < self.conv_stop: self.stop_training = True message = 'Maxiter = %d, iter = %d, inc_Lp_val = %f, inc_w = %f' % (self.Nmaxiter, self.kiter, inc_err_val, inc_w) #self.display(message) print(message) message = 'Maxiter = %d, iter = %d, inc_w = %f' % (self.Nmaxiter, self.kiter, inc_w) if inc_w <= self.conv_stop: self.stop_training = True ''' self.display('PROC_MASTER_END', verbose=False) self.display('MASTER_ITER_END', verbose=False) self.display(self.name + ': Training is done') self.model.niter = self.kiter self.model.is_trained = True self.model.w = self.model.w[0:self.w_orig_size, :] self.display('MASTER_FINISH', verbose=False) def Update_State_Master(self): """ We update control the flow given some conditions and parameters Parameters ---------- None """ if self.chekAllStates('ACK_update_tr_data'): self.FSMmaster.go_waiting_order(self) if self.chekAllStates('ACK_projecting_C'): self.FSMmaster.go_waiting_order(self) if self.chekAllStates('ACK_storing_C'): self.FSMmaster.go_waiting_order(self) if self.chekAllStates('ACK_sending_s'): if not self.Bob_data_s: self.Bob_data_s = True self.FSMmaster.go_waiting_order(self) if self.chekAllStates('ACK_sending_KTK'): self.FSMmaster.go_waiting_order(self) def ProcessReceivedPacket_Master(self, packet, sender): """ Process the received packet at Master and take some actions, possibly changing the state Parameters ---------- packet: packet object packet received (usually a dict with various content) sender: string id of the sender """ if packet is not None: try: #sender = packet['sender'] sender = self.receive_from[packet['sender']] if packet['action'][0:3] == 'ACK': self.display(self.name + ': received ACK from %s: %s' % (str(sender), packet['action'])) self.state_dict[sender] = packet['action'] try: self.display('COMMS_MASTER_RECEIVED %s from %s, id=%s' % (packet['action'], sender, str(packet['message_id'])), verbose=False) except: self.display('MASTER MISSING message_id in %s from %s' % (packet['action'], sender), verbose=False) pass if packet['action'] == 'ACK_update_tr_data': self.newNI_dict.update({sender: packet['data']['newNI']}) if packet['action'] == 'ACK_projecting_C': self.Kacum_dict.update({sender: packet['data']['Kacum']}) if packet['action'] == 'ACK_sending_s': if not self.Bob_data_s: self.s0_dict.update({sender: {'ya_0': packet['data']['ya_0'], 'yb_0': packet['data']['yb_0'], 'Q0': packet['data']['Q0'], 'v0': packet['data']['v0']}}) self.s1_dict.update({sender: {'ya_1': packet['data']['ya_1'], 'yb_1': packet['data']['yb_1'], 'Q1': packet['data']['Q1'], 'v1': packet['data']['v1']}}) self.Ztr_dict.update({sender: {'Ztr0': packet['data']['Ztr0'], 'Ztr1': packet['data']['Ztr1']}}) else: self.s0_dict[sender]['v0'] = packet['data']['v0'] self.s1_dict[sender]['v1'] = packet['data']['v1'] if packet['action'] == 'ACK_sending_KTK': self.KTK_dict.update({sender: packet['data']['KTK']}) self.KTy_dict.update({sender: packet['data']['KTy']}) except Exception as err: raise ''' print('ERROR AT ProcessReceivedPacket_Master') import code code.interact(local=locals()) ''' return #=============================================================== # Worker #=============================================================== class BSVM_Worker(Common_to_all_POMs): ''' Class implementing Support Vector Machine (budgeted, private model), run at Worker ''' def __init__(self, master_address, worker_address, model_type, comms, logger, verbose=True, Xtr_b=None, ytr=None): """ Create a :class:`BSVM_Worker` instance. Parameters ---------- master_address: string address of the master node worker_address: string id of this worker model_type: string type of ML model comms: comms object instance object providing communications logger: class:`logging.Logger` logging object instance verbose: boolean indicates if messages are print or not on screen Xtr_b: ndarray 2-D numpy array containing the input training patterns ytr: ndarray 1-D numpy array containing the target training values """ self.pom = 6 self.master_address = master_address self.worker_address = worker_address # The id of this Worker #self.workers_addresses = workers_addresses # The id of this Worker self.model_type = model_type self.comms = comms # The comms library self.logger = logger # logger self.name = model_type + '_Worker' # Name self.verbose = verbose # print on screen when true self.Xtr_b = Xtr_b self.ytr = ytr self.NPtr = len(ytr) self.w = None self.create_FSM_worker() self.message_id = 0 # used to number the messages self.eps = 0.0000001 self.Bob_data_s = False self.Bob_data_grad = False self.message_counter = 100 t = time.time() seed = int((t - int(t)) * 10000) np.random.seed(seed=seed) def create_FSM_worker(self): """ Creates a Finite State Machine to be run at the Worker Node Parameters ---------- None """ self.name = 'FSM_worker' self.display(self.name + ' %s: creating FSM' % (str(self.worker_address))) class FSM_worker(object): name = 'FSM_worker' def while_waiting_order(self, MLmodel): MLmodel.display(MLmodel.name + ' %s: WAITING for instructions...' % (str(MLmodel.worker_address))) return def while_setting_tr_data(self, MLmodel, packet): try: NPtr, newNI = MLmodel.Xtr_b.shape #MLmodel.Xtr_b = MLmodel.add_bias(MLmodel.Xtr_b).astype(float) MLmodel.ytr = MLmodel.ytr.astype(float) action = 'ACK_update_tr_data' data = {'newNI': newNI} packet = {'action': action, 'data': data, 'sender': MLmodel.worker_address} message_id = 'worker_' + MLmodel.worker_address + '_' + str(MLmodel.message_counter) packet.update({'message_id': message_id}) MLmodel.message_counter += 1 size_bytes = asizeof.asizeof(dill.dumps(packet)) MLmodel.display('COMMS_WORKER_SEND %s to %s, id = %s, bytes=%s' % (action, MLmodel.master_address, message_id, str(size_bytes)), verbose=False) MLmodel.comms.send(packet, MLmodel.master_address) MLmodel.display(MLmodel.name + ' %s: sent ACK_update_tr_data' % (str(MLmodel.worker_address))) except Exception as err: raise ''' message = "ERROR: %s %s" % (str(err), str(type(err))) MLmodel.display('\n ' + '='*50 + '\n' + message + '\n ' + '='*50 + '\n' ) import code code.interact(local=locals()) #MLmodel.display('ERROR AT while_computing_XTDaX') ''' def while_projecting_C(self, MLmodel, packet): # We project X over C and return accumulated try: MLmodel.display('PROC_WORKER_START', verbose=False) MLmodel.C = packet['data']['C'] NC = MLmodel.C.shape[0] MLmodel.sigma = packet['data']['sigma'] NI = MLmodel.Xtr_b.shape[1] NP = MLmodel.Xtr_b.shape[0] #MLmodel.sigma = np.sqrt(NI) * MLmodel.fsigma X = MLmodel.Xtr_b XC2 = -2 * np.dot(X, MLmodel.C.T) XC2 += np.sum(np.multiply(X, X), axis=1).reshape((NP, 1)) XC2 += np.sum(np.multiply(MLmodel.C, MLmodel.C), axis=1).reshape((1, NC)) # Gauss KXC = np.exp(-XC2 / 2.0 / (MLmodel.sigma ** 2)) #Kacum contains the number of closest patterns winners = list(np.argmax(KXC, axis=1)) Kacum = np.zeros((NC, 1)) for kc in range(NC): Kacum[kc] = winners.count(kc) #Kacum = np.sum(KXC, axis = 0) MLmodel.display('PROC_WORKER_END', verbose=False) action = 'ACK_projecting_C' data = {'Kacum': Kacum} packet = {'action': action, 'data': data, 'sender': MLmodel.worker_address} message_id = 'worker_' + MLmodel.worker_address + '_' + str(MLmodel.message_counter) packet.update({'message_id': message_id}) MLmodel.message_counter += 1 size_bytes = asizeof.asizeof(dill.dumps(packet)) MLmodel.display('COMMS_WORKER_SEND %s to %s, id = %s, bytes=%s' % (action, MLmodel.master_address, message_id, str(size_bytes)), verbose=False) MLmodel.comms.send(packet, MLmodel.master_address) MLmodel.display(MLmodel.name + ' %s: sent ACK_projecting_C' % (str(MLmodel.worker_address))) except Exception as err: raise ''' print('ERROR AT while_projecting_C') import code code.interact(local=locals()) ''' return def while_storing_C(self, MLmodel, packet): # We store C and compute KXC try: MLmodel.display('PROC_WORKER_START', verbose=False) MLmodel.C = packet['data']['C'] MLmodel.Csvm = packet['data']['Csvm'] NC = MLmodel.C.shape[0] MLmodel.sigma = packet['data']['sigma'] NI = MLmodel.Xtr_b.shape[1] NP = MLmodel.Xtr_b.shape[0] #MLmodel.sigma = np.sqrt(NI) * MLmodel.fsigma X = MLmodel.Xtr_b XC2 = -2 * np.dot(X, MLmodel.C.T) XC2 += np.sum(np.multiply(X, X), axis=1).reshape((NP, 1)) XC2 += np.sum(np.multiply(MLmodel.C, MLmodel.C), axis=1).reshape((1, NC)) # Gauss KXC = np.exp(-XC2 / 2.0 / (MLmodel.sigma ** 2)) # Poly #KXC = 1 / (1 + (XC2 / 2.0 / (MLmodel.sigma ** 2) ) ) MLmodel.KXC = np.hstack( (np.ones((NP, 1)), KXC)) # NP x NC + 1 # Checking for even features MLmodel.NI = MLmodel.KXC.shape[1] MLmodel.NPtr = MLmodel.KXC.shape[0] if MLmodel.NI/2 != int(MLmodel.NI/2): MLmodel.KXC = np.hstack((MLmodel.KXC, np.random.normal(0, 0.0001, (MLmodel.NPtr, 1)))) MLmodel.NPtr_train = MLmodel.KXC.shape[0] MLmodel.NI_train = MLmodel.KXC.shape[1] # RMD MLmodel.Cmat = np.random.normal(0, 1, (MLmodel.NI_train, MLmodel.NI_train)) MLmodel.Dmat = np.linalg.inv(MLmodel.Cmat) which0 = (MLmodel.ytr == 0).ravel() MLmodel.Ztr0 = np.dot(MLmodel.KXC[which0, :], MLmodel.Cmat) which1 = (MLmodel.ytr == 1).ravel() MLmodel.Ztr1 = np.dot(MLmodel.KXC[which1, :], MLmodel.Cmat) MLmodel.display('PROC_WORKER_END', verbose=False) action = 'ACK_storing_C' data = {} packet = {'action': action, 'data': data, 'sender': MLmodel.worker_address} message_id = 'worker_' + MLmodel.worker_address + '_' + str(MLmodel.message_counter) packet.update({'message_id': message_id}) MLmodel.message_counter += 1 size_bytes = asizeof.asizeof(dill.dumps(packet)) MLmodel.display('COMMS_WORKER_SEND %s to %s, id = %s, bytes=%s' % (action, MLmodel.master_address, message_id, str(size_bytes)), verbose=False) MLmodel.comms.send(packet, MLmodel.master_address) MLmodel.display(MLmodel.name + ' %s: sent ACK_storing_C' % (str(MLmodel.worker_address))) except Exception as err: raise ''' print('ERROR AT while_storing_C') import code code.interact(local=locals()) ''' def while_computing_s(self, MLmodel, packet): try: MLmodel.display('PROC_WORKER_START', verbose=False) xa_ = packet['data']['xa_'] xb_ = packet['data']['xb_'] P = packet['data']['P'] # Only once if not MLmodel.Bob_data_s: K = int(MLmodel.NI_train / 2) #MLmodel.ytr = MLmodel.ytr * 2 -1 which0 = (MLmodel.ytr == 0).ravel() MLmodel.NPtr_train0 = np.sum(which0) which1 = (MLmodel.ytr == 1).ravel() MLmodel.NPtr_train1 = np.sum(which1) y0 = MLmodel.KXC[which0, :] MLmodel.yas0 = y0[:, 0:K] MLmodel.ybs0 = y0[:, K:] del y0 MLmodel.Bs0 = np.random.uniform(-10, 10, (MLmodel.NPtr_train0, K)) MLmodel.Ds0 = np.random.uniform(-10, 10, (MLmodel.NPtr_train0, K)) MLmodel.Qs0 = MLmodel.Bs0 - MLmodel.Ds0 # warning, check the sum is nonzero (low prob...) MLmodel.ya_s0 = MLmodel.Bs0 - MLmodel.yas0 MLmodel.yb_s0 = MLmodel.Ds0 - MLmodel.ybs0 y1 = MLmodel.KXC[which1, :] MLmodel.yas1 = y1[:, 0:K] MLmodel.ybs1 = y1[:, K:] del y1 MLmodel.Bs1 = np.random.uniform(-10, 10, (MLmodel.NPtr_train1, K)) MLmodel.Ds1 = np.random.uniform(-10, 10, (MLmodel.NPtr_train1, K)) MLmodel.Qs1 = MLmodel.Bs1 - MLmodel.Ds1 # warning, check the sum is nonzero (low prob...) MLmodel.ya_s1 = MLmodel.Bs1 - MLmodel.yas1 MLmodel.yb_s1 = MLmodel.Ds1 - MLmodel.ybs1 V0 = xa_ * (2 * MLmodel.yas0 - MLmodel.Bs0) + xb_ * (2 * MLmodel.ybs0 - MLmodel.Ds0) + P * (MLmodel.Ds0 - 2 * MLmodel.Bs0) v0 = np.sum(V0, axis=1) V1 = xa_ * (2 * MLmodel.yas1 - MLmodel.Bs1) + xb_ * (2 * MLmodel.ybs1 - MLmodel.Ds1) + P * (MLmodel.Ds1 - 2 * MLmodel.Bs1) v1 = np.sum(V1, axis=1) del xa_, xb_, P, V0, V1 MLmodel.display('PROC_WORKER_END', verbose=False) # send to Master ya_, yb_, Q, v action = 'ACK_sending_s' #message_id = 'worker_' + MLmodel.worker_address + '_' + str(MLmodel.message_counter) if not MLmodel.Bob_data_s: data = {'ya_0': MLmodel.ya_s0, 'yb_0': MLmodel.yb_s0, 'Q0': MLmodel.Qs0, 'v0': v0, 'Ztr0': MLmodel.Ztr0, 'Ztr1': MLmodel.Ztr1} data.update({'ya_1': MLmodel.ya_s1, 'yb_1': MLmodel.yb_s1, 'Q1': MLmodel.Qs1, 'v1': v1}) MLmodel.Bob_data_s = True else: data = {'v0': v0, 'v1': v1} del v0, v1 packet = {'action': action, 'data': data, 'sender': MLmodel.worker_address} message_id = 'worker_' + MLmodel.worker_address + '_' + str(MLmodel.message_counter) packet.update({'message_id': message_id}) MLmodel.message_counter += 1 size_bytes = asizeof.asizeof(dill.dumps(packet)) MLmodel.display('COMMS_WORKER_SEND %s to %s, id = %s, bytes=%s' % (action, MLmodel.master_address, message_id, str(size_bytes)), verbose=False) del data MLmodel.comms.send(packet, MLmodel.master_address) del packet#, size_bytes MLmodel.display(MLmodel.name + ' %s: sent ACK_sending_s' % (str(MLmodel.worker_address))) except: raise ''' print('ERROR AT while_computing_s') import code code.interact(local=locals()) ''' return def while_computing_KTK(self, MLmodel, packet): try: MLmodel.display('PROC_WORKER_START', verbose=False) KTK = np.dot(MLmodel.Dmat.T, packet['data']['Rzz']) KTK = np.dot(KTK, MLmodel.Dmat) KTy = np.dot(MLmodel.Dmat.T, packet['data']['rzt']) MLmodel.display('PROC_WORKER_END', verbose=False) action = 'ACK_sending_KTK' data = {'KTK': KTK, 'KTy': KTy} del KTK, KTy packet = {'action': action, 'data': data, 'sender': MLmodel.worker_address} message_id = 'worker_' + MLmodel.worker_address + '_' + str(MLmodel.message_counter) packet.update({'message_id': message_id}) MLmodel.message_counter += 1 size_bytes = asizeof.asizeof(dill.dumps(packet)) MLmodel.display('COMMS_WORKER_SEND %s to %s, id = %s, bytes=%s' % (action, MLmodel.master_address, message_id, str(size_bytes)), verbose=False) MLmodel.comms.send(packet, MLmodel.master_address) MLmodel.display(MLmodel.name + ' %s: sent ACK_sending_KTK' % (str(MLmodel.worker_address))) except Exception as err: raise ''' print('ERROR AT while_computing_KTK') import code code.interact(local=locals()) pass ''' return states_worker = [ State(name='waiting_order', on_enter=['while_waiting_order']), State(name='setting_tr_data', on_enter=['while_setting_tr_data']), State(name='projecting_C', on_enter=['while_projecting_C']), State(name='storing_C', on_enter=['while_storing_C']), State(name='computing_s', on_enter=['while_computing_s']), State(name='computing_KTK', on_enter=['while_computing_KTK']), State(name='computing_KXC', on_enter=['while_computing_KXC']), State(name='Exit', on_enter=['while_Exit']) ] transitions_worker = [ ['go_setting_tr_data', 'waiting_order', 'setting_tr_data'], ['done_setting_tr_data', 'setting_tr_data', 'waiting_order'], ['go_projecting_C', 'waiting_order', 'projecting_C'], ['done_projecting_C', 'projecting_C', 'waiting_order'], ['go_storing_C', 'waiting_order', 'storing_C'], ['done_storing_C', 'storing_C', 'waiting_order'], ['go_computing_s', 'waiting_order', 'computing_s'], ['done_computing_s', 'computing_s', 'waiting_order'], ['go_computing_KXC', 'waiting_order', 'computing_KXC'], ['done_computing_KXC', 'computing_KXC', 'waiting_order'], ['go_computing_KTK', 'waiting_order', 'computing_KTK'], ['done_computing_KTK', 'computing_KTK', 'waiting_order'], ['go_exit', 'waiting_order', 'Exit'] ] self.FSMworker = FSM_worker() self.grafmachine_worker = GraphMachine(model=self.FSMworker, states=states_worker, transitions=transitions_worker, initial='waiting_order', show_auto_transitions=False, # default value is False title="Finite State Machine modelling the behaviour of worker No. %s" % str(self.worker_address), show_conditions=False) return def ProcessReceivedPacket_Worker(self, packet, sender): """ Take an action after receiving a packet Parameters ---------- packet: packet object packet received (usually a dict with various content) sender: string id of the sender """ self.terminate = False try: self.display('COMMS_WORKER_RECEIVED %s from %s, id=%s' % (packet['action'], sender, str(packet['message_id'])), verbose=False) except: self.display('WORKER MISSING message_id in %s from %s' % (packet['action'], sender), verbose=False) pass if packet is not None: try: # Exit the process if packet['action'] == 'STOP': self.display(self.name + ' %s: terminated by Master' % (str(self.worker_address))) self.display('EXIT_WORKER') self.terminate = True if packet['action'] == 'update_tr_data': # We update the training data self.FSMworker.go_setting_tr_data(self, packet) self.FSMworker.done_setting_tr_data(self) if packet['action'] == 'compute_KTK': self.FSMworker.go_computing_KTK(self, packet) self.FSMworker.done_computing_KTK(self) if packet['action'] == 'selecting_C': #self.C = packet['data']['C'] self.FSMworker.go_projecting_C(self, packet) self.FSMworker.done_projecting_C(self) if packet['action'] == 'sending_C': #self.C = packet['data']['C'] self.FSMworker.go_storing_C(self, packet) self.FSMworker.done_storing_C(self) if packet['action'] == 'sending_xaxbP': self.FSMworker.go_computing_s(self, packet) self.FSMworker.done_computing_s(self) if packet['action'] == 'sending_Rzz_rzt': self.FSMworker.go_computing_KTK(self, packet) self.FSMworker.done_computing_KTK(self) except Exception as err: raise ''' print('ERROR AT CheckNewPacket_worker') import code code.interact(local=locals()) ''' return self.terminate
[ "pickle.dump", "numpy.random.seed", "numpy.sum", "numpy.argmax", "numpy.ones", "numpy.linalg.norm", "numpy.exp", "numpy.random.normal", "transitions.extensions.GraphMachine", "numpy.multiply", "skl2onnx.common.data_types.FloatTensorType", "transitions.State", "dill.dumps", "numpy.linalg.inv", "numpy.dot", "sklearn2pmml.sklearn2pmml", "numpy.random.uniform", "sklearn.svm.SVR", "numpy.zeros", "time.time", "skl2onnx.convert_sklearn", "numpy.sign", "sklearn2pmml.pipeline.PMMLPipeline", "numpy.sqrt" ]
[((796, 807), 'time.time', 'time.time', ([], {}), '()\n', (805, 807), False, 'import time\n'), ((859, 884), 'numpy.random.seed', 'np.random.seed', ([], {'seed': 'seed'}), '(seed=seed)\n', (873, 884), True, 'import numpy as np\n'), ((1436, 1472), 'numpy.exp', 'np.exp', (['(-XC2 / 2.0 / self.sigma ** 2)'], {}), '(-XC2 / 2.0 / self.sigma ** 2)\n', (1442, 1472), True, 'import numpy as np\n'), ((1684, 1703), 'numpy.dot', 'np.dot', (['KXC', 'self.w'], {}), '(KXC, self.w)\n', (1690, 1703), True, 'import numpy as np\n'), ((11585, 11596), 'time.time', 'time.time', ([], {}), '()\n', (11594, 11596), False, 'import time\n'), ((11648, 11673), 'numpy.random.seed', 'np.random.seed', ([], {'seed': 'seed'}), '(seed=seed)\n', (11662, 11673), True, 'import numpy as np\n'), ((28800, 29052), 'transitions.extensions.GraphMachine', 'GraphMachine', ([], {'model': 'self.FSMmaster', 'states': 'states_master', 'transitions': 'transitions_master', 'initial': '"""waiting_order"""', 'show_auto_transitions': '(False)', 'title': '"""Finite State Machine modelling the behaviour of the master"""', 'show_conditions': '(False)'}), "(model=self.FSMmaster, states=states_master, transitions=\n transitions_master, initial='waiting_order', show_auto_transitions=\n False, title=\n 'Finite State Machine modelling the behaviour of the master',\n show_conditions=False)\n", (28812, 29052), False, 'from transitions.extensions import GraphMachine\n'), ((29418, 29462), 'numpy.random.normal', 'np.random.normal', (['(0)', '(0.001)', '(self.NI + 1, 1)'], {}), '(0, 0.001, (self.NI + 1, 1))\n', (29434, 29462), True, 'import numpy as np\n'), ((29534, 29576), 'numpy.random.normal', 'np.random.normal', (['(0)', '(1.0)', '(self.NI + 1, 1)'], {}), '(0, 1.0, (self.NI + 1, 1))\n', (29550, 29576), True, 'import numpy as np\n'), ((29605, 29641), 'numpy.zeros', 'np.zeros', (['(self.NI + 1, self.NI + 1)'], {}), '((self.NI + 1, self.NI + 1))\n', (29613, 29641), True, 'import numpy as np\n'), ((29701, 29727), 'numpy.zeros', 'np.zeros', (['(self.NI + 1, 1)'], {}), '((self.NI + 1, 1))\n', (29709, 29727), True, 'import numpy as np\n'), ((32029, 32071), 'numpy.exp', 'np.exp', (['(-XC2 / 2.0 / self.model.sigma ** 2)'], {}), '(-XC2 / 2.0 / self.model.sigma ** 2)\n', (32035, 32071), True, 'import numpy as np\n'), ((32095, 32131), 'numpy.zeros', 'np.zeros', (['(self.NC + 1, self.NC + 1)'], {}), '((self.NC + 1, self.NC + 1))\n', (32103, 32131), True, 'import numpy as np\n'), ((33377, 33423), 'numpy.random.normal', 'np.random.normal', (['(0)', '(0.0001)', '(self.NItrain, 1)'], {}), '(0, 0.0001, (self.NItrain, 1))\n', (33393, 33423), True, 'import numpy as np\n'), ((33495, 33538), 'numpy.random.normal', 'np.random.normal', (['(0)', '(1.0)', '(self.NItrain, 1)'], {}), '(0, 1.0, (self.NItrain, 1))\n', (33511, 33538), True, 'import numpy as np\n'), ((46473, 46484), 'time.time', 'time.time', ([], {}), '()\n', (46482, 46484), False, 'import time\n'), ((46536, 46561), 'numpy.random.seed', 'np.random.seed', ([], {'seed': 'seed'}), '(seed=seed)\n', (46550, 46561), True, 'import numpy as np\n'), ((1236, 1255), 'numpy.dot', 'np.dot', (['X', 'self.C.T'], {}), '(X, self.C.T)\n', (1242, 1255), True, 'import numpy as np\n'), ((11270, 11286), 'numpy.sqrt', 'np.sqrt', (['self.NI'], {}), '(self.NI)\n', (11277, 11286), True, 'import numpy as np\n'), ((11957, 12018), 'transitions.State', 'State', ([], {'name': '"""waiting_order"""', 'on_enter': "['while_waiting_order']"}), "(name='waiting_order', on_enter=['while_waiting_order'])\n", (11962, 12018), False, 'from transitions import State\n'), ((12033, 12096), 'transitions.State', 'State', ([], {'name': '"""update_tr_data"""', 'on_enter': "['while_update_tr_data']"}), "(name='update_tr_data', on_enter=['while_update_tr_data'])\n", (12038, 12096), False, 'from transitions import State\n'), ((12111, 12168), 'transitions.State', 'State', ([], {'name': '"""getting_KTK"""', 'on_enter': "['while_getting_KTK']"}), "(name='getting_KTK', on_enter=['while_getting_KTK'])\n", (12116, 12168), False, 'from transitions import State\n'), ((12183, 12240), 'transitions.State', 'State', ([], {'name': '"""selecting_C"""', 'on_enter': "['while_selecting_C']"}), "(name='selecting_C', on_enter=['while_selecting_C'])\n", (12188, 12240), False, 'from transitions import State\n'), ((12255, 12308), 'transitions.State', 'State', ([], {'name': '"""sending_C"""', 'on_enter': "['while_sending_C']"}), "(name='sending_C', on_enter=['while_sending_C'])\n", (12260, 12308), False, 'from transitions import State\n'), ((12325, 12386), 'transitions.State', 'State', ([], {'name': '"""computing_XTw"""', 'on_enter': "['while_computing_XTw']"}), "(name='computing_XTw', on_enter=['while_computing_XTw'])\n", (12330, 12386), False, 'from transitions import State\n'), ((12401, 12460), 'transitions.State', 'State', ([], {'name': '"""computing_oi"""', 'on_enter': "['while_computing_oi']"}), "(name='computing_oi', on_enter=['while_computing_oi'])\n", (12406, 12460), False, 'from transitions import State\n'), ((12477, 12532), 'transitions.State', 'State', ([], {'name': '"""updating_w"""', 'on_enter': "['while_updating_w']"}), "(name='updating_w', on_enter=['while_updating_w'])\n", (12482, 12532), False, 'from transitions import State\n'), ((31822, 31847), 'numpy.dot', 'np.dot', (['X', 'self.model.C.T'], {}), '(X, self.model.C.T)\n', (31828, 31847), True, 'import numpy as np\n'), ((33147, 33189), 'numpy.exp', 'np.exp', (['(-XC2 / 2.0 / self.model.sigma ** 2)'], {}), '(-XC2 / 2.0 / self.model.sigma ** 2)\n', (33153, 33189), True, 'import numpy as np\n'), ((60449, 60510), 'transitions.State', 'State', ([], {'name': '"""waiting_order"""', 'on_enter': "['while_waiting_order']"}), "(name='waiting_order', on_enter=['while_waiting_order'])\n", (60454, 60510), False, 'from transitions import State\n'), ((60525, 60590), 'transitions.State', 'State', ([], {'name': '"""setting_tr_data"""', 'on_enter': "['while_setting_tr_data']"}), "(name='setting_tr_data', on_enter=['while_setting_tr_data'])\n", (60530, 60590), False, 'from transitions import State\n'), ((60605, 60664), 'transitions.State', 'State', ([], {'name': '"""projecting_C"""', 'on_enter': "['while_projecting_C']"}), "(name='projecting_C', on_enter=['while_projecting_C'])\n", (60610, 60664), False, 'from transitions import State\n'), ((60679, 60732), 'transitions.State', 'State', ([], {'name': '"""storing_C"""', 'on_enter': "['while_storing_C']"}), "(name='storing_C', on_enter=['while_storing_C'])\n", (60684, 60732), False, 'from transitions import State\n'), ((60749, 60806), 'transitions.State', 'State', ([], {'name': '"""computing_s"""', 'on_enter': "['while_computing_s']"}), "(name='computing_s', on_enter=['while_computing_s'])\n", (60754, 60806), False, 'from transitions import State\n'), ((60823, 60884), 'transitions.State', 'State', ([], {'name': '"""computing_KTK"""', 'on_enter': "['while_computing_KTK']"}), "(name='computing_KTK', on_enter=['while_computing_KTK'])\n", (60828, 60884), False, 'from transitions import State\n'), ((60899, 60960), 'transitions.State', 'State', ([], {'name': '"""computing_KXC"""', 'on_enter': "['while_computing_KXC']"}), "(name='computing_KXC', on_enter=['while_computing_KXC'])\n", (60904, 60960), False, 'from transitions import State\n'), ((60975, 61018), 'transitions.State', 'State', ([], {'name': '"""Exit"""', 'on_enter': "['while_Exit']"}), "(name='Exit', on_enter=['while_Exit'])\n", (60980, 61018), False, 'from transitions import State\n'), ((1631, 1647), 'numpy.ones', 'np.ones', (['(NP, 1)'], {}), '((NP, 1))\n', (1638, 1647), True, 'import numpy as np\n'), ((32902, 32929), 'numpy.dot', 'np.dot', (['self.Xval', 'self.C.T'], {}), '(self.Xval, self.C.T)\n', (32908, 32929), True, 'import numpy as np\n'), ((35446, 35470), 'numpy.dot', 'np.dot', (['self.KXC_val', 'w_'], {}), '(self.KXC_val, w_)\n', (35452, 35470), True, 'import numpy as np\n'), ((1279, 1296), 'numpy.multiply', 'np.multiply', (['X', 'X'], {}), '(X, X)\n', (1290, 1296), True, 'import numpy as np\n'), ((1346, 1373), 'numpy.multiply', 'np.multiply', (['self.C', 'self.C'], {}), '(self.C, self.C)\n', (1357, 1373), True, 'import numpy as np\n'), ((27798, 27842), 'numpy.zeros', 'np.zeros', (['(MLmodel.NItrain, MLmodel.NItrain)'], {}), '((MLmodel.NItrain, MLmodel.NItrain))\n', (27806, 27842), True, 'import numpy as np\n'), ((27884, 27914), 'numpy.zeros', 'np.zeros', (['(MLmodel.NItrain, 1)'], {}), '((MLmodel.NItrain, 1))\n', (27892, 27914), True, 'import numpy as np\n'), ((31871, 31888), 'numpy.multiply', 'np.multiply', (['X', 'X'], {}), '(X, X)\n', (31882, 31888), True, 'import numpy as np\n'), ((31943, 31982), 'numpy.multiply', 'np.multiply', (['self.model.C', 'self.model.C'], {}), '(self.model.C, self.model.C)\n', (31954, 31982), True, 'import numpy as np\n'), ((32564, 32586), 'numpy.zeros', 'np.zeros', (['(self.NI, 1)'], {}), '((self.NI, 1))\n', (32572, 32586), True, 'import numpy as np\n'), ((32634, 32660), 'numpy.zeros', 'np.zeros', (['(1, self.NI + 1)'], {}), '((1, self.NI + 1))\n', (32642, 32660), True, 'import numpy as np\n'), ((33233, 33265), 'numpy.ones', 'np.ones', (['(self.Xval.shape[0], 1)'], {}), '((self.Xval.shape[0], 1))\n', (33240, 33265), True, 'import numpy as np\n'), ((34828, 34869), 'numpy.linalg.norm', 'np.linalg.norm', (['(self.model.w - self.w_old)'], {}), '(self.model.w - self.w_old)\n', (34842, 34869), True, 'import numpy as np\n'), ((34872, 34898), 'numpy.linalg.norm', 'np.linalg.norm', (['self.w_old'], {}), '(self.w_old)\n', (34886, 34898), True, 'import numpy as np\n'), ((49598, 49637), 'numpy.exp', 'np.exp', (['(-XC2 / 2.0 / MLmodel.sigma ** 2)'], {}), '(-XC2 / 2.0 / MLmodel.sigma ** 2)\n', (49604, 49637), True, 'import numpy as np\n'), ((49821, 49838), 'numpy.zeros', 'np.zeros', (['(NC, 1)'], {}), '((NC, 1))\n', (49829, 49838), True, 'import numpy as np\n'), ((52125, 52164), 'numpy.exp', 'np.exp', (['(-XC2 / 2.0 / MLmodel.sigma ** 2)'], {}), '(-XC2 / 2.0 / MLmodel.sigma ** 2)\n', (52131, 52164), True, 'import numpy as np\n'), ((52887, 52947), 'numpy.random.normal', 'np.random.normal', (['(0)', '(1)', '(MLmodel.NI_train, MLmodel.NI_train)'], {}), '(0, 1, (MLmodel.NI_train, MLmodel.NI_train))\n', (52903, 52947), True, 'import numpy as np\n'), ((52984, 53011), 'numpy.linalg.inv', 'np.linalg.inv', (['MLmodel.Cmat'], {}), '(MLmodel.Cmat)\n', (52997, 53011), True, 'import numpy as np\n'), ((53105, 53149), 'numpy.dot', 'np.dot', (['MLmodel.KXC[which0, :]', 'MLmodel.Cmat'], {}), '(MLmodel.KXC[which0, :], MLmodel.Cmat)\n', (53111, 53149), True, 'import numpy as np\n'), ((53243, 53287), 'numpy.dot', 'np.dot', (['MLmodel.KXC[which1, :]', 'MLmodel.Cmat'], {}), '(MLmodel.KXC[which1, :], MLmodel.Cmat)\n', (53249, 53287), True, 'import numpy as np\n'), ((56654, 56672), 'numpy.sum', 'np.sum', (['V0'], {'axis': '(1)'}), '(V0, axis=1)\n', (56660, 56672), True, 'import numpy as np\n'), ((56843, 56861), 'numpy.sum', 'np.sum', (['V1'], {'axis': '(1)'}), '(V1, axis=1)\n', (56849, 56861), True, 'import numpy as np\n'), ((58959, 59004), 'numpy.dot', 'np.dot', (['MLmodel.Dmat.T', "packet['data']['Rzz']"], {}), "(MLmodel.Dmat.T, packet['data']['Rzz'])\n", (58965, 59004), True, 'import numpy as np\n'), ((59034, 59059), 'numpy.dot', 'np.dot', (['KTK', 'MLmodel.Dmat'], {}), '(KTK, MLmodel.Dmat)\n', (59040, 59059), True, 'import numpy as np\n'), ((59089, 59134), 'numpy.dot', 'np.dot', (['MLmodel.Dmat.T', "packet['data']['rzt']"], {}), "(MLmodel.Dmat.T, packet['data']['rzt'])\n", (59095, 59134), True, 'import numpy as np\n'), ((14318, 14336), 'dill.dumps', 'dill.dumps', (['packet'], {}), '(packet)\n', (14328, 14336), False, 'import dill\n'), ((15685, 15703), 'dill.dumps', 'dill.dumps', (['packet'], {}), '(packet)\n', (15695, 15703), False, 'import dill\n'), ((17228, 17246), 'dill.dumps', 'dill.dumps', (['packet'], {}), '(packet)\n', (17238, 17246), False, 'import dill\n'), ((19888, 19906), 'dill.dumps', 'dill.dumps', (['packet'], {}), '(packet)\n', (19898, 19906), False, 'import dill\n'), ((21737, 21755), 'numpy.sum', 'np.sum', (['U0'], {'axis': '(1)'}), '(U0, axis=1)\n', (21743, 21755), True, 'import numpy as np\n'), ((22126, 22140), 'numpy.ones', 'np.ones', (['NPtr0'], {}), '(NPtr0)\n', (22133, 22140), True, 'import numpy as np\n'), ((22702, 22720), 'numpy.dot', 'np.dot', (['Rzz0.T', 'y0'], {}), '(Rzz0.T, y0)\n', (22708, 22720), True, 'import numpy as np\n'), ((22753, 22799), 'numpy.dot', 'np.dot', (['Rzz0.T', "MLmodel.Ztr_dict[addr]['Ztr0']"], {}), "(Rzz0.T, MLmodel.Ztr_dict[addr]['Ztr0'])\n", (22759, 22799), True, 'import numpy as np\n'), ((23082, 23100), 'numpy.sum', 'np.sum', (['U1'], {'axis': '(1)'}), '(U1, axis=1)\n', (23088, 23100), True, 'import numpy as np\n'), ((23307, 23321), 'numpy.ones', 'np.ones', (['NPtr1'], {}), '(NPtr1)\n', (23314, 23321), True, 'import numpy as np\n'), ((23470, 23484), 'numpy.ones', 'np.ones', (['NPtr1'], {}), '(NPtr1)\n', (23477, 23484), True, 'import numpy as np\n'), ((24046, 24064), 'numpy.dot', 'np.dot', (['Rzz1.T', 'y1'], {}), '(Rzz1.T, y1)\n', (24052, 24064), True, 'import numpy as np\n'), ((24097, 24143), 'numpy.dot', 'np.dot', (['Rzz1.T', "MLmodel.Ztr_dict[addr]['Ztr1']"], {}), "(Rzz1.T, MLmodel.Ztr_dict[addr]['Ztr1'])\n", (24103, 24143), True, 'import numpy as np\n'), ((26617, 26635), 'dill.dumps', 'dill.dumps', (['packet'], {}), '(packet)\n', (26627, 26635), False, 'import dill\n'), ((28179, 28225), 'numpy.linalg.inv', 'np.linalg.inv', (['(MLmodel.KTK_accum + MLmodel.Kcc)'], {}), '(MLmodel.KTK_accum + MLmodel.Kcc)\n', (28192, 28225), True, 'import numpy as np\n'), ((32957, 32990), 'numpy.multiply', 'np.multiply', (['self.Xval', 'self.Xval'], {}), '(self.Xval, self.Xval)\n', (32968, 32990), True, 'import numpy as np\n'), ((33044, 33071), 'numpy.multiply', 'np.multiply', (['self.C', 'self.C'], {}), '(self.C, self.C)\n', (33055, 33071), True, 'import numpy as np\n'), ((47907, 47925), 'dill.dumps', 'dill.dumps', (['packet'], {}), '(packet)\n', (47917, 47925), False, 'import dill\n'), ((49345, 49367), 'numpy.dot', 'np.dot', (['X', 'MLmodel.C.T'], {}), '(X, MLmodel.C.T)\n', (49351, 49367), True, 'import numpy as np\n'), ((49768, 49790), 'numpy.argmax', 'np.argmax', (['KXC'], {'axis': '(1)'}), '(KXC, axis=1)\n', (49777, 49790), True, 'import numpy as np\n'), ((50525, 50543), 'dill.dumps', 'dill.dumps', (['packet'], {}), '(packet)\n', (50535, 50543), False, 'import dill\n'), ((51872, 51894), 'numpy.dot', 'np.dot', (['X', 'MLmodel.C.T'], {}), '(X, MLmodel.C.T)\n', (51878, 51894), True, 'import numpy as np\n'), ((53828, 53846), 'dill.dumps', 'dill.dumps', (['packet'], {}), '(packet)\n', (53838, 53846), False, 'import dill\n'), ((55088, 55102), 'numpy.sum', 'np.sum', (['which0'], {}), '(which0)\n', (55094, 55102), True, 'import numpy as np\n'), ((55211, 55225), 'numpy.sum', 'np.sum', (['which1'], {}), '(which1)\n', (55217, 55225), True, 'import numpy as np\n'), ((55453, 55505), 'numpy.random.uniform', 'np.random.uniform', (['(-10)', '(10)', '(MLmodel.NPtr_train0, K)'], {}), '(-10, 10, (MLmodel.NPtr_train0, K))\n', (55470, 55505), True, 'import numpy as np\n'), ((55545, 55597), 'numpy.random.uniform', 'np.random.uniform', (['(-10)', '(10)', '(MLmodel.NPtr_train0, K)'], {}), '(-10, 10, (MLmodel.NPtr_train0, K))\n', (55562, 55597), True, 'import numpy as np\n'), ((56081, 56133), 'numpy.random.uniform', 'np.random.uniform', (['(-10)', '(10)', '(MLmodel.NPtr_train1, K)'], {}), '(-10, 10, (MLmodel.NPtr_train1, K))\n', (56098, 56133), True, 'import numpy as np\n'), ((56173, 56225), 'numpy.random.uniform', 'np.random.uniform', (['(-10)', '(10)', '(MLmodel.NPtr_train1, K)'], {}), '(-10, 10, (MLmodel.NPtr_train1, K))\n', (56190, 56225), True, 'import numpy as np\n'), ((58057, 58075), 'dill.dumps', 'dill.dumps', (['packet'], {}), '(packet)\n', (58067, 58075), False, 'import dill\n'), ((59712, 59730), 'dill.dumps', 'dill.dumps', (['packet'], {}), '(packet)\n', (59722, 59730), False, 'import dill\n'), ((18559, 18588), 'numpy.random.uniform', 'np.random.uniform', (['(-10)', '(10)', 'K'], {}), '(-10, 10, K)\n', (18576, 18588), True, 'import numpy as np\n'), ((18638, 18667), 'numpy.random.uniform', 'np.random.uniform', (['(-10)', '(10)', 'K'], {}), '(-10, 10, K)\n', (18655, 18667), True, 'import numpy as np\n'), ((21963, 21977), 'numpy.ones', 'np.ones', (['NPtr0'], {}), '(NPtr0)\n', (21970, 21977), True, 'import numpy as np\n'), ((25239, 25257), 'dill.dumps', 'dill.dumps', (['packet'], {}), '(packet)\n', (25249, 25257), False, 'import dill\n'), ((52321, 52337), 'numpy.ones', 'np.ones', (['(NP, 1)'], {}), '((NP, 1))\n', (52328, 52337), True, 'import numpy as np\n'), ((3867, 3887), 'pickle.dump', 'pickle.dump', (['self', 'f'], {}), '(self, f)\n', (3878, 3887), False, 'import pickle\n'), ((4620, 4643), 'sklearn.svm.SVR', 'SVR', ([], {'C': '(1.0)', 'gamma': 'gamma'}), '(C=1.0, gamma=gamma)\n', (4623, 4643), False, 'from sklearn.svm import SVR\n'), ((4677, 4710), 'numpy.random.normal', 'np.random.normal', (['(0)', '(1)', '(100, NI)'], {}), '(0, 1, (100, NI))\n', (4693, 4710), True, 'import numpy as np\n'), ((4744, 4775), 'numpy.random.normal', 'np.random.normal', (['(0)', '(1)', '(NI, 1)'], {}), '(0, 1, (NI, 1))\n', (4760, 4775), True, 'import numpy as np\n'), ((5562, 5617), 'skl2onnx.convert_sklearn', 'convert_sklearn', (['export_model'], {'initial_types': 'input_type'}), '(export_model, initial_types=input_type)\n', (5577, 5617), False, 'from skl2onnx import convert_sklearn\n'), ((35506, 35524), 'numpy.sign', 'np.sign', (['preds_val'], {}), '(preds_val)\n', (35513, 35524), True, 'import numpy as np\n'), ((49403, 49420), 'numpy.multiply', 'np.multiply', (['X', 'X'], {}), '(X, X)\n', (49414, 49420), True, 'import numpy as np\n'), ((49482, 49515), 'numpy.multiply', 'np.multiply', (['MLmodel.C', 'MLmodel.C'], {}), '(MLmodel.C, MLmodel.C)\n', (49493, 49515), True, 'import numpy as np\n'), ((51930, 51947), 'numpy.multiply', 'np.multiply', (['X', 'X'], {}), '(X, X)\n', (51941, 51947), True, 'import numpy as np\n'), ((52009, 52042), 'numpy.multiply', 'np.multiply', (['MLmodel.C', 'MLmodel.C'], {}), '(MLmodel.C, MLmodel.C)\n', (52020, 52042), True, 'import numpy as np\n'), ((52647, 52693), 'numpy.random.normal', 'np.random.normal', (['(0)', '(0.0001)', '(MLmodel.NPtr, 1)'], {}), '(0, 0.0001, (MLmodel.NPtr, 1))\n', (52663, 52693), True, 'import numpy as np\n'), ((6497, 6520), 'sklearn.svm.SVR', 'SVR', ([], {'C': '(1.0)', 'gamma': 'gamma'}), '(C=1.0, gamma=gamma)\n', (6500, 6520), False, 'from sklearn.svm import SVR\n'), ((6554, 6587), 'numpy.random.normal', 'np.random.normal', (['(0)', '(1)', '(100, NI)'], {}), '(0, 1, (100, NI))\n', (6570, 6587), True, 'import numpy as np\n'), ((6621, 6652), 'numpy.random.normal', 'np.random.normal', (['(0)', '(1)', '(NI, 1)'], {}), '(0, 1, (NI, 1))\n', (6637, 6652), True, 'import numpy as np\n'), ((7320, 7363), 'sklearn2pmml.pipeline.PMMLPipeline', 'PMMLPipeline', (["[('estimator', export_model)]"], {}), "([('estimator', export_model)])\n", (7332, 7363), False, 'from sklearn2pmml.pipeline import PMMLPipeline\n'), ((7393, 7441), 'sklearn2pmml.sklearn2pmml', 'sklearn2pmml', (['pipeline', 'filename'], {'with_repr': '(True)'}), '(pipeline, filename, with_repr=True)\n', (7405, 7441), False, 'from sklearn2pmml import sklearn2pmml\n'), ((5490, 5517), 'skl2onnx.common.data_types.FloatTensorType', 'FloatTensorType', (['[None, NI]'], {}), '([None, NI])\n', (5505, 5517), False, 'from skl2onnx.common.data_types import FloatTensorType\n'), ((4817, 4829), 'numpy.dot', 'np.dot', (['X', 'w'], {}), '(X, w)\n', (4823, 4829), True, 'import numpy as np\n'), ((6694, 6706), 'numpy.dot', 'np.dot', (['X', 'w'], {}), '(X, w)\n', (6700, 6706), True, 'import numpy as np\n')]
# -*- coding: utf-8 -*- """ Automated Tool for Optimized Modelling (ATOM) Author: Mavs Description: Module containing the feature engineering estimators. """ # Standard packages import random import numpy as np import pandas as pd from typeguard import typechecked from typing import Optional, Union # Other packages import featuretools as ft from woodwork.column_schema import ColumnSchema from gplearn.genetic import SymbolicTransformer from sklearn.base import BaseEstimator from sklearn.decomposition import PCA from sklearn.feature_selection import ( f_classif, f_regression, mutual_info_classif, mutual_info_regression, chi2, SelectKBest, SelectFromModel, RFE, RFECV, SequentialFeatureSelector, ) # Own modules from .models import MODELS from .basetransformer import BaseTransformer from .data_cleaning import TransformerMixin, Scaler from .plots import FSPlotter from .utils import ( SCALAR, SEQUENCE, SEQUENCE_TYPES, X_TYPES, Y_TYPES, lst, to_df, get_custom_scorer, check_scaling, check_is_fitted, get_feature_importance, composed, crash, method_to_log, ) class FeatureExtractor(BaseEstimator, TransformerMixin, BaseTransformer): """Extract features from datetime columns. Create new features extracting datetime elements (day, month, year, etc...) from the provided columns. Columns of dtype `datetime64` are used as is. Categorical columns that can be successfully converted to a datetime format (less than 30% NaT values after conversion) are also used. Parameters ---------- features: str or sequence, optional (default=["day", "month", "year"]) Features to create from the datetime columns. Note that created features with zero variance (e.g. the feature hour in a column that only contains dates) are ignored. Allowed values are datetime attributes from `pandas.Series.dt`. fmt: str, sequence or None, optional (default=None) Format (`strptime`) of the categorical columns that need to be converted to datetime. If sequence, the n-th format corresponds to the n-th categorical column that can be successfully converted. If None, the format is inferred automatically from the first non NaN value. Values that can not be converted are returned as NaT. encoding_type: str, optional (default="ordinal") Type of encoding to use. Choose from: - "ordinal": Encode features in increasing order. - "cyclic": Encode features using sine and cosine to capture their cyclic nature. Note that this creates two columns for every feature. Non-cyclic features still use ordinal encoding. drop_columns: bool, optional (default=True) Whether to drop the original columns after extracting the features from it. verbose: int, optional (default=0) Verbosity level of the class. Possible values are: - 0 to not print anything. - 1 to print basic information. - 2 to print detailed information. logger: str, Logger or None, optional (default=None) - If None: Doesn't save a logging file. - If str: Name of the log file. Use "auto" for automatic naming. - Else: Python `logging.Logger` instance. """ def __init__( self, features: Union[str, SEQUENCE_TYPES] = ["day", "month", "year"], fmt: Optional[Union[str, SEQUENCE_TYPES]] = None, encoding_type: str = "ordinal", drop_columns: bool = True, verbose: int = 0, logger: Optional[Union[str, callable]] = None, ): super().__init__(verbose=verbose, logger=logger) self.fmt = fmt self.features = features self.encoding_type = encoding_type self.drop_columns = drop_columns @composed(crash, method_to_log, typechecked) def transform(self, X: X_TYPES, y: Optional[Y_TYPES] = None): """Extract the new features. Parameters ---------- X: dataframe-like Feature set with shape=(n_samples, n_features). y: int, str, sequence or None, optional (default=None) Does nothing. Implemented for continuity of the API. Returns ------- X: pd.DataFrame Transformed feature set. """ def encode_variable(idx, name, values, min_val=0, max_val=None): """Encode a feature in an ordinal or cyclic fashion.""" if self.encoding_type.lower() == "ordinal" or max_val is None: self.log(f" >>> Creating feature {name}.", 2) X.insert(idx, name, values) elif self.encoding_type.lower() == "cyclic": self.log(f" >>> Creating cyclic feature {name}.", 2) pos = 2 * np.pi * (values - min_val) / np.array(max_val) X.insert(idx, f"{name}_sin", np.sin(pos)) X.insert(idx, f"{name}_cos", np.cos(pos)) X, y = self._prepare_input(X, y) # Check parameters if self.encoding_type.lower() not in ("ordinal", "cyclic"): raise ValueError( "Invalid value for the encoding_type parameter, got " f"{self.encoding_type}. Choose from: ordinal, cyclic." ) self.log("Extracting datetime features...", 1) i = 0 for col in X.select_dtypes(exclude="number"): if X[col].dtype.name == "datetime64[ns]": col_dt = X[col] self.log(f" --> Extracting features from datetime column {col}.", 1) elif col in X.select_dtypes(exclude="number").columns: col_dt = pd.to_datetime( arg=X[col], errors="coerce", # Converts to NaT if he can't format format=self.fmt[i] if isinstance(self.fmt, SEQUENCE) else self.fmt, infer_datetime_format=True, ) # If >30% values are NaT, the conversion was unsuccessful nans = 100. * col_dt.isna().sum() / len(X) if nans >= 30: continue # Skip this column else: i += 1 self.log( f" --> Extracting features from categorical column {col}.", 1 ) # Extract features from the datetime column for fx in map(str.lower, lst(self.features)): if hasattr(col_dt.dt, fx.lower()): values = getattr(col_dt.dt, fx) else: raise ValueError( "Invalid value for the feature parameter. Value " f"{fx.lower()} is not an attribute of pd.Series.dt." ) # Skip if the information is not present in the format if not isinstance(values, pd.Series): self.log( f" >>> Extracting feature {fx} failed. " "Result is not a pd.Series.dt.", 2 ) continue min_val, max_val = 0, None # max_val=None -> feature is not cyclic if self.encoding_type.lower() == "cyclic": if fx == "microsecond": min_val, max_val = 0, 1e6 - 1 elif fx in ("second", "minute"): min_val, max_val = 0, 59 elif fx == "hour": min_val, max_val = 0, 23 elif fx in ("weekday", "dayofweek", "day_of_week"): min_val, max_val = 0, 6 elif fx in ("day", "dayofmonth", "day_of_month"): min_val, max_val = 1, col_dt.dt.daysinmonth elif fx in ("dayofyear", "day_of_year"): min_val = 1 max_val = [365 if i else 366 for i in col_dt.dt.is_leap_year] elif fx == "month": min_val, max_val = 1, 12 elif fx == "quarter": min_val, max_val = 1, 4 # Add every new feature after the previous one encode_variable( idx=X.columns.get_loc(col), name=f"{col}_{fx}", values=values, min_val=min_val, max_val=max_val, ) # Drop the original datetime column if self.drop_columns: X = X.drop(col, axis=1) return X class FeatureGenerator(BaseEstimator, TransformerMixin, BaseTransformer): """Apply automated feature engineering. Use Deep feature Synthesis or a genetic algorithm to create new combinations of existing features to capture the non-linear relations between the original features. Parameters ---------- strategy: str, optional (default="DFS") Strategy to crate new features. Choose from: - "DFS" to use Deep Feature Synthesis. - "GFG" or "genetic" to use Genetic Feature Generation. n_features: int or None, optional (default=None) Number of newly generated features to add to the dataset (no more than 1% of the population for the genetic strategy). If None, select all created features. generations: int, optional (default=20) Number of generations to evolve. Only for the genetic strategy. population: int, optional (default=500) Number of programs in each generation. Only for the genetic strategy. operators: str, sequence or None, optional (default=None) Mathematical operators to apply on the features. None for all. Choose from: add, sub, mul, div, sqrt, log, inv, sin, cos, tan. n_jobs: int, optional (default=1) Number of cores to use for parallel processing. - If >0: Number of cores to use. - If -1: Use all available cores. - If <-1: Use number of cores - 1 + `n_jobs`. verbose: int, optional (default=0) Verbosity level of the class. Possible values are: - 0 to not print anything. - 1 to print basic information. - 2 to print detailed information. logger: str, Logger or None, optional (default=None) - If None: Doesn't save a logging file. - If str: Name of the log file. Use "auto" for automatic naming. - Else: Python `logging.Logger` instance. random_state: int or None, optional (default=None) Seed used by the random number generator. If None, the random number generator is the `RandomState` used by `np.random`. Attributes ---------- symbolic_transformer: SymbolicTransformer Object used to calculate the genetic features. Only for the genetic strategy. genetic_features: pd.DataFrame Information on the newly created non-linear features. Only for the genetic strategy. Columns include: - name: Name of the feature (automatically created). - description: Operators used to create this feature. - fitness: Fitness score. """ def __init__( self, strategy: str = "DFS", n_features: Optional[int] = None, generations: int = 20, population: int = 500, operators: Optional[Union[str, SEQUENCE_TYPES]] = None, n_jobs: int = 1, verbose: int = 0, logger: Optional[Union[str, callable]] = None, random_state: Optional[int] = None, ): super().__init__( n_jobs=n_jobs, verbose=verbose, logger=logger, random_state=random_state, ) self.strategy = strategy self.n_features = n_features self.generations = generations self.population = population self.operators = operators self.symbolic_transformer = None self.genetic_features = None self._operators = None self._dfs_features = None self._is_fitted = False @composed(crash, method_to_log, typechecked) def fit(self, X: X_TYPES, y: Y_TYPES): """Fit to data. Parameters ---------- X: dataframe-like Feature set with shape=(n_samples, n_features). y: int, str or sequence - If int: Index of the target column in X. - If str: Name of the target column in X. - Else: Target column with shape=(n_samples,). Returns ------- self: FeatureGenerator """ X, y = self._prepare_input(X, y) if self.n_features is not None and self.n_features <= 0: raise ValueError( "Invalid value for the n_features parameter." f"Value should be >0, got {self.n_features}." ) if self.strategy.lower() in ("gfg", "genetic"): if self.population < 100: raise ValueError( "Invalid value for the population parameter." f"Value should be >100, got {self.population}." ) if self.generations < 1: raise ValueError( "Invalid value for the generations parameter." f"Value should be >100, got {self.generations}." ) if self.n_features and self.n_features > int(0.01 * self.population): raise ValueError( "Invalid value for the n_features parameter. Value " f"should be <1% of the population, got {self.n_features}." ) elif self.strategy.lower() != "dfs": raise ValueError( "Invalid value for the strategy parameter. Value " f"should be either 'dfs' or 'genetic', got {self.strategy}." ) default = ["add", "sub", "mul", "div", "sqrt", "log", "sin", "cos", "tan"] if not self.operators: # None or empty list self._operators = default else: self._operators = lst(self.operators) for operator in self._operators: if operator.lower() not in default: raise ValueError( "Invalid value in the operators parameter, got " f"{operator}. Choose from: {', '.join(default)}." ) self.log("Fitting FeatureGenerator...", 1) if self.strategy.lower() == "dfs": trans_primitives = [] for operator in self._operators: if operator.lower() == "add": trans_primitives.append("add_numeric") elif operator.lower() == "sub": trans_primitives.append("subtract_numeric") elif operator.lower() == "mul": trans_primitives.append("multiply_numeric") elif operator.lower() == "div": trans_primitives.append("divide_numeric") elif operator.lower() in ("sqrt", "log", "sin", "cos", "tan"): trans_primitives.append( ft.primitives.make_trans_primitive( function=lambda x: getattr(np, operator.lower())(x), input_types=[ColumnSchema()], return_type=ColumnSchema(semantic_tags=["numeric"]), name=operator.lower(), ) ) # Run deep feature synthesis with transformation primitives es = ft.EntitySet(dataframes={"X": (X, "_index", None, None, None, True)}) self._dfs_features = ft.dfs( target_dataframe_name="X", entityset=es, trans_primitives=trans_primitives, max_depth=1, features_only=True, ignore_columns={"X": ["_index"]}, ) # Since dfs doesn't return a specific feature order, we # enforce order by name to be deterministic new_dfs = [] for feature in sorted(map(str, self._dfs_features[X.shape[1] - 1:])): for fx in self._dfs_features: if feature == str(fx): new_dfs.append(fx) break self._dfs_features = self._dfs_features[: X.shape[1] - 1] + new_dfs # Make sure there are enough features (-1 because of index) max_features = len(self._dfs_features) - (X.shape[1] - 1) if not self.n_features or self.n_features > max_features: n_final_features = max_features else: n_final_features = self.n_features # Get random indices from the feature list idx_old = range(X.shape[1] - 1) idx_new = random.sample( range(X.shape[1] - 1, len(self._dfs_features)), n_final_features ) idx = list(idx_old) + list(idx_new) # Get random selection of features self._dfs_features = [ value for i, value in enumerate(self._dfs_features) if i in idx ] else: self.symbolic_transformer = SymbolicTransformer( generations=self.generations, population_size=self.population, hall_of_fame=int(0.1 * self.population), n_components=int(0.01 * self.population), init_depth=(1, 2), function_set=self._operators, feature_names=X.columns, verbose=0 if self.verbose < 2 else 1, n_jobs=self.n_jobs, random_state=self.random_state, ).fit(X, y) self._is_fitted = True return self @composed(crash, method_to_log, typechecked) def transform(self, X: X_TYPES, y: Optional[Y_TYPES] = None): """Generate new features. Parameters ---------- X: dataframe-like Feature set with shape=(n_samples, n_features). y: int, str, sequence or None, optional (default=None) Does nothing. Implemented for continuity of the API. Returns ------- X: pd.DataFrame Dataframe containing the newly generated features. """ check_is_fitted(self) X, y = self._prepare_input(X, y) self.log("Creating new features...", 1) if self.strategy.lower() == "dfs": es = ft.EntitySet(dataframes={"X": (X, "index", None, None, None, True)}) X = ft.calculate_feature_matrix( features=self._dfs_features, entityset=es, n_jobs=self.n_jobs, ) self.log( f" --> {len(self._dfs_features)} new " "features were added to the dataset.", 2 ) else: new_features = self.symbolic_transformer.transform(X) # ix = indices of new fxs that are not in the original set # descript = operators applied to create the new features # fitness = list of fitness scores of the new features ix, descript, fitness = [], [], [] for i, program in enumerate(self.symbolic_transformer): if str(program) not in X.columns: ix.append(i) descript.append(str(program)) fitness.append(program.fitness_) # Remove all identical features to those in the dataset new_features = new_features[:, ix] descript = [item for i, item in enumerate(descript) if i in ix] fitness = [item for i, item in enumerate(fitness) if i in ix] # Indices of all non duplicate elements in list ix = [ix for ix, v in enumerate(descript) if v not in descript[:ix]] # Remove all duplicate elements new_features = new_features[:, ix] descript = [item for i, item in enumerate(descript) if i in ix] fitness = [item for i, item in enumerate(fitness) if i in ix] # Check if any new features remain in the loop if len(descript) == 0: self.log( " --> WARNING! The genetic algorithm couldn't " "find any improving non-linear features.", 1 ) return X # Get indices of the best features if self.n_features and len(descript) > self.n_features: index = np.argpartition(fitness, -self.n_features)[-self.n_features:] else: index = range(len(descript)) # Select best features only new_features = new_features[:, index] # Create the genetic_features attribute features_df = pd.DataFrame(columns=["name", "description", "fitness"]) for i, idx in enumerate(index): features_df = features_df.append( { "name": "Feature " + str(1 + i + len(X.columns)), "description": descript[idx], "fitness": fitness[idx], }, ignore_index=True, ) self.genetic_features = features_df self.log( f" --> {len(self.genetic_features)} new " "features were added to the dataset.", 2 ) cols = list(X.columns) + list(self.genetic_features["name"]) X = pd.DataFrame(np.hstack((X, new_features)), columns=cols) return X class FeatureSelector(BaseEstimator, TransformerMixin, BaseTransformer, FSPlotter): """Apply feature selection techniques. Remove features according to the selected strategy. Ties between features with equal scores are broken in an unspecified way. Additionally, removes features with too low variance and finds pairs of collinear features based on the Pearson correlation coefficient. For each pair above the specified limit (in terms of absolute value), it removes one of the two. Parameters ---------- strategy: string or None, optional (default=None) Feature selection strategy to use. Choose from: - None: Do not perform any feature selection algorithm. - "univariate": Univariate F-test. - "PCA": Principal Component Analysis. - "SFM": Select best features according to a model. - "SFS"" Sequential Feature Selection. - "RFE": Recursive Feature Elimination. - "RFECV": RFE with cross-validated selection. Note that the SFS, RFE and RFECV strategies don't work when the solver is a CatBoost model due to incompatibility of the APIs. solver: str, estimator or None, optional (default=None) Solver or model to use for the feature selection strategy. See sklearn's documentation for an extended description of the choices. Select None for the default option per strategy (only for univariate or PCA). - for "univariate", choose from: + "f_classif" + "f_regression" + "mutual_info_classif" + "mutual_info_regression" + "chi2" + Any function taking two arrays (X, y), and returning arrays (scores, p-values). - for "PCA", choose from: + "auto" (default) + "full" + "arpack" + "randomized" - for "SFM", "SFS", "RFE" and "RFECV": The base estimator. For SFM, RFE and RFECV, it should have either a `feature_importances_` or `coef_` attribute after fitting. You can use one of ATOM's predefined models. Add `_class` or `_reg` after the model's name to specify a classification or regression task, e.g. `solver="LGB_reg"` (not necessary if called from atom). No default option. n_features: int, float or None, optional (default=None) Number of features to select. Choose from: - if None: Select all features. - if < 1: Fraction of the total features to select. - if >= 1: Number of features to select. If strategy="SFM" and the threshold parameter is not specified, the threshold are automatically set to `-inf` to select the `n_features` features. If strategy="RFECV", `n_features` is the minimum number of features to select. max_frac_repeated: float or None, optional (default=1.) Remove features with the same value in at least this fraction of the total rows. The default is to keep all features with non-zero variance, i.e. remove the features that have the same value in all samples. If None, skip this step. max_correlation: float or None, optional (default=1.) Minimum Pearson correlation coefficient to identify correlated features. A value of 1 removes one of 2 equal columns. A dataframe of the removed features and their correlation values can be accessed through the collinear attribute. If None, skip this step. n_jobs: int, optional (default=1) Number of cores to use for parallel processing. - If >0: Number of cores to use. - If -1: Use all available cores. - If <-1: Use number of cores - 1 + `n_jobs`. verbose: int, optional (default=0) Verbosity level of the class. Possible values are: - 0 to not print anything. - 1 to print basic information. - 2 to print detailed information. logger: str, Logger or None, optional (default=None) - If None: Doesn't save a logging file. - If str: Name of the log file. Use "auto" for automatic naming. - Else: Python `logging.Logger` instance. random_state: int or None, optional (default=None) Seed used by the random number generator. If None, the random number generator is the `RandomState` used by `np.random`. **kwargs Any extra keyword argument for the PCA, SFM, SFS, RFE and RFECV estimators. See the corresponding documentation for the available options. Attributes ---------- collinear: pd.DataFrame Information on the removed collinear features. Columns include: - drop_feature: Name of the feature dropped by the method. - correlated feature: Name of the correlated features. - correlation_value: Pearson correlation coefficients of the feature pairs. feature_importance: list Remaining features ordered by importance. Only if strategy in ["univariate", "SFM, "RFE", "RFECV"]. For RFE and RFECV, the importance is extracted from the external estimator fitted on the reduced set. <strategy>: sklearn transformer Object (lowercase strategy) used to transform the data, e.g. `balancer.pca` for the PCA strategy. """ def __init__( self, strategy: Optional[str] = None, solver: Optional[Union[str, callable]] = None, n_features: Optional[SCALAR] = None, max_frac_repeated: Optional[SCALAR] = 1.0, max_correlation: Optional[float] = 1.0, n_jobs: int = 1, verbose: int = 0, logger: Optional[Union[str, callable]] = None, random_state: Optional[int] = None, **kwargs, ): super().__init__( n_jobs=n_jobs, verbose=verbose, logger=logger, random_state=random_state ) self.strategy = strategy self.solver = solver self.n_features = n_features self.max_frac_repeated = max_frac_repeated self.max_correlation = max_correlation self.kwargs = kwargs self.collinear = pd.DataFrame( columns=["drop_feature", "correlated_feature", "correlation_value"] ) self.feature_importance = None self.scaler = None self._solver = None self._n_features = None self._low_variance = {} self._is_fitted = False @composed(crash, method_to_log, typechecked) def fit(self, X: X_TYPES, y: Optional[Y_TYPES] = None): """Fit the feature selector to the data. Note that the univariate, sfm (when model is not fitted), sfs, rfe and rfecv strategies need a target column. Leaving it None will raise an exception. Parameters ---------- X: dataframe-like Feature set with shape=(n_samples, n_features). y: int, str, sequence or None, optional (default=None) - If None: y is ignored. - If int: Index of the target column in X. - If str: Name of the target column in X. - Else: Target column with shape=(n_samples,). Returns ------- self: FeatureSelector """ def check_y(): """For some strategies, y needs to be provided.""" if y is None: raise ValueError( "Invalid value for the y parameter. Value cannot " f"be None for strategy='{self.strategy}'." ) X, y = self._prepare_input(X, y) # Check parameters if isinstance(self.strategy, str): strats = ["univariate", "pca", "sfm", "sfs", "rfe", "rfecv"] if self.strategy.lower() not in strats: raise ValueError( "Invalid value for the strategy parameter. Choose " "from: univariate, PCA, SFM, RFE or RFECV." ) elif self.strategy.lower() == "univariate": solvers_dct = dict( f_classif=f_classif, f_regression=f_regression, mutual_info_classif=mutual_info_classif, mutual_info_regression=mutual_info_regression, chi2=chi2, ) if not self.solver: raise ValueError( "Invalid value for the solver parameter. The " f"value can't be None for strategy={self.strategy}" ) elif self.solver in solvers_dct: self._solver = solvers_dct[self.solver] elif isinstance(self.solver, str): raise ValueError( "Invalid value for the solver parameter, got " f"{self.solver}. Choose from: {', '.join(solvers_dct)}." ) else: self._solver = self.solver elif self.strategy.lower() == "pca": self._solver = "auto" if self.solver is None else self.solver else: if self.solver is None: raise ValueError( "Invalid value for the solver parameter. The " f"value can't be None for strategy={self.strategy}" ) elif isinstance(self.solver, str): # Assign goal depending on solver's ending if self.solver[-6:] == "_class": self.goal = "class" self._solver = self.solver[:-6] elif self.solver[-4:] == "_reg": self.goal = "reg" self._solver = self.solver[:-4] else: self._solver = self.solver # Get estimator from predefined models if self._solver not in MODELS: raise ValueError( "Invalid value for the solver parameter. Unknown " f"model: {self._solver}. Choose from: {', '.join(MODELS)}." ) else: self._solver = MODELS[self._solver](self).get_estimator() else: self._solver = self.solver if self.n_features is None: self._n_features = X.shape[1] elif self.n_features <= 0: raise ValueError( "Invalid value for the n_features parameter. " f"Value should be >0, got {self.n_features}." ) elif self.n_features < 1: self._n_features = int(self.n_features * X.shape[1]) else: self._n_features = self.n_features if self.max_frac_repeated is not None and not 0 <= self.max_frac_repeated <= 1: raise ValueError( "Invalid value for the max_frac_repeated parameter. Value " f"should be between 0 and 1, got {self.max_frac_repeated}." ) if self.max_correlation is not None and not 0 <= self.max_correlation <= 1: raise ValueError( "Invalid value for the max_correlation parameter. Value " f"shouldbe between 0 and 1, got {self.max_correlation}." ) self.log("Fitting FeatureSelector...", 1) # Remove features with too low variance if self.max_frac_repeated: for n, col in enumerate(X): unique, count = np.unique(X[col], return_counts=True) for u, c in zip(unique, count): # If count is larger than fraction of total... if c >= self.max_frac_repeated * len(X): self._low_variance[col] = [u, c // len(X) * 100] X = X.drop(col, axis=1) break # Remove features with too high correlation if self.max_correlation: max_ = self.max_correlation mtx = X.corr() # Pearson correlation coefficient matrix # Extract the upper triangle of the correlation matrix upper = mtx.where(np.triu(np.ones(mtx.shape).astype(bool), k=1)) # Select the features with correlations above or equal to the threshold to_drop = [i for i in upper.columns if any(abs(upper[i] >= max_))] # Iterate to record pairs of correlated features for col in to_drop: # Find the correlated features and corresponding values corr_features = list(upper.index[abs(upper[col]) >= max_]) corr_values = list(round(upper[col][abs(upper[col]) >= max_], 5)) # Update dataframe self.collinear = self.collinear.append( { "drop_feature": col, "correlated_feature": ", ".join(corr_features), "correlation_value": ", ".join(map(str, corr_values)), }, ignore_index=True, ) X = X.drop(to_drop, axis=1) if self.strategy is None: self._is_fitted = True return self # Exit feature_engineering elif self.strategy.lower() == "univariate": check_y() self.univariate = SelectKBest( score_func=self._solver, k=self._n_features, ).fit(X, y) elif self.strategy.lower() == "pca": if not check_scaling(X): self.scaler = Scaler().fit(X) X = self.scaler.transform(X) self.pca = PCA( n_components=None, # Select all because of the pca plots svd_solver=self._solver, random_state=self.random_state, **self.kwargs, ).fit(X) # Reset number of components self.pca.n_components_ = self._n_features elif self.strategy.lower() == "sfm": # If any of these attr exists, model is already fitted condition1 = hasattr(self._solver, "coef_") condition2 = hasattr(self._solver, "feature_importances_") self.kwargs["prefit"] = True if condition1 or condition2 else False # If threshold is not specified, select only based on _n_features if not self.kwargs.get("threshold"): self.kwargs["threshold"] = -np.inf self.sfm = SelectFromModel( estimator=self._solver, max_features=self._n_features, **self.kwargs, ) if self.kwargs["prefit"]: if len(self.sfm.get_support()) != X.shape[1]: raise ValueError( "Invalid value for the solver parameter. The " f"{self._solver.__class__.__name__} estimator " "is fitted with different columns than X!" ) self.sfm.estimator_ = self._solver else: check_y() self.sfm.fit(X, y) elif self.strategy.lower() == "sfs": self.sfs = SequentialFeatureSelector( estimator=self._solver, n_features_to_select=self._n_features, n_jobs=self.n_jobs, **self.kwargs, ).fit(X, y) elif self.strategy.lower() == "rfe": check_y() self.rfe = RFE( estimator=self._solver, n_features_to_select=self._n_features, **self.kwargs, ).fit(X, y) else: check_y() # Both RFECV and SFS use the scoring parameter if self.kwargs.get("scoring"): self.kwargs["scoring"] = get_custom_scorer(self.kwargs["scoring"]) if self.strategy.lower() == "rfecv": # Invert n_features to select them all (default option) if self._n_features == X.shape[1]: self._n_features = 1 self.rfecv = RFECV( estimator=self._solver, min_features_to_select=self._n_features, n_jobs=self.n_jobs, **self.kwargs, ).fit(X, y) self._is_fitted = True return self @composed(crash, method_to_log, typechecked) def transform(self, X: X_TYPES, y: Optional[Y_TYPES] = None): """Transform the data. Parameters ---------- X: dataframe-like Feature set with shape=(n_samples, n_features). y: int, str, sequence or None, optional (default=None) Does nothing. Only for continuity of API. Returns ------- X: pd.DataFrame Transformed feature set. """ check_is_fitted(self) X, y = self._prepare_input(X, y) columns = X.columns # Save columns for SFM self.log("Performing feature selection ...", 1) # Remove features with too low variance for key, value in self._low_variance.items(): self.log( f" --> Feature {key} was removed due to low variance. Value " f"{value[0]} repeated in {value[1]}% of the rows.", 2 ) X = X.drop(key, axis=1) # Remove features with too high correlation for col in self.collinear["drop_feature"]: self.log( f" --> Feature {col} was removed due to " "collinearity with another feature.", 2 ) X = X.drop(col, axis=1) # Perform selection based on strategy if self.strategy is None: return X elif self.strategy.lower() == "univariate": indices = np.argsort(get_feature_importance(self.univariate)) best_fxs = [X.columns[idx] for idx in indices][::-1] self.log( f" --> The univariate test selected " f"{self._n_features} features from the dataset.", 2 ) for n, column in enumerate(X): if not self.univariate.get_support()[n]: self.log( f" >>> Dropping feature {column} " f"(score: {self.univariate.scores_[n]:.2f} " f"p-value: {self.univariate.pvalues_[n]:.2f}).", 2 ) X = X.drop(column, axis=1) self.feature_importance = [fx for fx in best_fxs if fx in X.columns] elif self.strategy.lower() == "pca": self.log(" --> Applying Principal Component Analysis...", 2) if self.scaler: self.log(" >>> Scaling features...", 2) X = self.scaler.transform(X) n = self.pca.n_components_ columns = [f"Component {str(i)}" for i in range(1, n + 1)] X = to_df(self.pca.transform(X)[:, :n], index=X.index, columns=columns) var = np.array(self.pca.explained_variance_ratio_[:n]) self.log(f" >>> Total explained variance: {round(var.sum(), 3)}", 2) elif self.strategy.lower() == "sfm": # Here we use columns since some cols could be removed before by # variance or correlation checks and there would be cols mismatch indices = np.argsort(get_feature_importance(self.sfm.estimator_)) best_fxs = [columns[idx] for idx in indices][::-1] self.log( f" --> The {self._solver.__class__.__name__} estimator selected " f"{sum(self.sfm.get_support())} features from the dataset.", 2 ) for n, column in enumerate(X): if not self.sfm.get_support()[n]: self.log(f" >>> Dropping feature {column}.", 2) X = X.drop(column, axis=1) self.feature_importance = [fx for fx in best_fxs if fx in X.columns] elif self.strategy.lower() == "sfs": self.log( f" --> The SFS selected {self.sfs.n_features_to_select_}" " features from the dataset.", 2 ) for n, column in enumerate(X): if not self.sfs.support_[n]: self.log(f" >>> Dropping feature {column}.", 2) X = X.drop(column, axis=1) elif self.strategy.lower() == "rfe": self.log( f" --> The RFE selected {self.rfe.n_features_}" " features from the dataset.", 2 ) for n, column in enumerate(X): if not self.rfe.support_[n]: self.log( f" >>> Dropping feature {column} " f"(rank {self.rfe.ranking_[n]}).", 2 ) X = X.drop(column, axis=1) idx = np.argsort(get_feature_importance(self.rfe.estimator_)) self.feature_importance = list(X.columns[idx][::-1]) elif self.strategy.lower() == "rfecv": self.log( f" --> The RFECV selected {self.rfecv.n_features_}" " features from the dataset.", 2 ) for n, column in enumerate(X): if not self.rfecv.support_[n]: self.log( f" >>> Dropping feature {column} " f"(rank {self.rfecv.ranking_[n]}).", 2 ) X = X.drop(column, axis=1) idx = np.argsort(get_feature_importance(self.rfecv.estimator_)) self.feature_importance = list(X.columns[idx][::-1]) return X
[ "pandas.DataFrame", "sklearn.feature_selection.SequentialFeatureSelector", "sklearn.feature_selection.RFECV", "woodwork.column_schema.ColumnSchema", "sklearn.feature_selection.RFE", "featuretools.dfs", "numpy.ones", "numpy.hstack", "numpy.argpartition", "featuretools.EntitySet", "numpy.sin", "numpy.array", "sklearn.feature_selection.SelectFromModel", "numpy.cos", "featuretools.calculate_feature_matrix", "sklearn.decomposition.PCA", "sklearn.feature_selection.SelectKBest", "numpy.unique" ]
[((28379, 28464), 'pandas.DataFrame', 'pd.DataFrame', ([], {'columns': "['drop_feature', 'correlated_feature', 'correlation_value']"}), "(columns=['drop_feature', 'correlated_feature',\n 'correlation_value'])\n", (28391, 28464), True, 'import pandas as pd\n'), ((15848, 15917), 'featuretools.EntitySet', 'ft.EntitySet', ([], {'dataframes': "{'X': (X, '_index', None, None, None, True)}"}), "(dataframes={'X': (X, '_index', None, None, None, True)})\n", (15860, 15917), True, 'import featuretools as ft\n'), ((15951, 16109), 'featuretools.dfs', 'ft.dfs', ([], {'target_dataframe_name': '"""X"""', 'entityset': 'es', 'trans_primitives': 'trans_primitives', 'max_depth': '(1)', 'features_only': '(True)', 'ignore_columns': "{'X': ['_index']}"}), "(target_dataframe_name='X', entityset=es, trans_primitives=\n trans_primitives, max_depth=1, features_only=True, ignore_columns={'X':\n ['_index']})\n", (15957, 16109), True, 'import featuretools as ft\n'), ((18813, 18881), 'featuretools.EntitySet', 'ft.EntitySet', ([], {'dataframes': "{'X': (X, 'index', None, None, None, True)}"}), "(dataframes={'X': (X, 'index', None, None, None, True)})\n", (18825, 18881), True, 'import featuretools as ft\n'), ((18898, 18992), 'featuretools.calculate_feature_matrix', 'ft.calculate_feature_matrix', ([], {'features': 'self._dfs_features', 'entityset': 'es', 'n_jobs': 'self.n_jobs'}), '(features=self._dfs_features, entityset=es,\n n_jobs=self.n_jobs)\n', (18925, 18992), True, 'import featuretools as ft\n'), ((21166, 21222), 'pandas.DataFrame', 'pd.DataFrame', ([], {'columns': "['name', 'description', 'fitness']"}), "(columns=['name', 'description', 'fitness'])\n", (21178, 21222), True, 'import pandas as pd\n'), ((21899, 21927), 'numpy.hstack', 'np.hstack', (['(X, new_features)'], {}), '((X, new_features))\n', (21908, 21927), True, 'import numpy as np\n'), ((33870, 33907), 'numpy.unique', 'np.unique', (['X[col]'], {'return_counts': '(True)'}), '(X[col], return_counts=True)\n', (33879, 33907), True, 'import numpy as np\n'), ((20871, 20913), 'numpy.argpartition', 'np.argpartition', (['fitness', '(-self.n_features)'], {}), '(fitness, -self.n_features)\n', (20886, 20913), True, 'import numpy as np\n'), ((41476, 41524), 'numpy.array', 'np.array', (['self.pca.explained_variance_ratio_[:n]'], {}), '(self.pca.explained_variance_ratio_[:n])\n', (41484, 41524), True, 'import numpy as np\n'), ((4930, 4947), 'numpy.array', 'np.array', (['max_val'], {}), '(max_val)\n', (4938, 4947), True, 'import numpy as np\n'), ((4993, 5004), 'numpy.sin', 'np.sin', (['pos'], {}), '(pos)\n', (4999, 5004), True, 'import numpy as np\n'), ((5051, 5062), 'numpy.cos', 'np.cos', (['pos'], {}), '(pos)\n', (5057, 5062), True, 'import numpy as np\n'), ((35720, 35776), 'sklearn.feature_selection.SelectKBest', 'SelectKBest', ([], {'score_func': 'self._solver', 'k': 'self._n_features'}), '(score_func=self._solver, k=self._n_features)\n', (35731, 35776), False, 'from sklearn.feature_selection import f_classif, f_regression, mutual_info_classif, mutual_info_regression, chi2, SelectKBest, SelectFromModel, RFE, RFECV, SequentialFeatureSelector\n'), ((36871, 36961), 'sklearn.feature_selection.SelectFromModel', 'SelectFromModel', ([], {'estimator': 'self._solver', 'max_features': 'self._n_features'}), '(estimator=self._solver, max_features=self._n_features, **\n self.kwargs)\n', (36886, 36961), False, 'from sklearn.feature_selection import f_classif, f_regression, mutual_info_classif, mutual_info_regression, chi2, SelectKBest, SelectFromModel, RFE, RFECV, SequentialFeatureSelector\n'), ((34536, 34554), 'numpy.ones', 'np.ones', (['mtx.shape'], {}), '(mtx.shape)\n', (34543, 34554), True, 'import numpy as np\n'), ((36032, 36131), 'sklearn.decomposition.PCA', 'PCA', ([], {'n_components': 'None', 'svd_solver': 'self._solver', 'random_state': 'self.random_state'}), '(n_components=None, svd_solver=self._solver, random_state=self.\n random_state, **self.kwargs)\n', (36035, 36131), False, 'from sklearn.decomposition import PCA\n'), ((37589, 37717), 'sklearn.feature_selection.SequentialFeatureSelector', 'SequentialFeatureSelector', ([], {'estimator': 'self._solver', 'n_features_to_select': 'self._n_features', 'n_jobs': 'self.n_jobs'}), '(estimator=self._solver, n_features_to_select=self\n ._n_features, n_jobs=self.n_jobs, **self.kwargs)\n', (37614, 37717), False, 'from sklearn.feature_selection import f_classif, f_regression, mutual_info_classif, mutual_info_regression, chi2, SelectKBest, SelectFromModel, RFE, RFECV, SequentialFeatureSelector\n'), ((37893, 37979), 'sklearn.feature_selection.RFE', 'RFE', ([], {'estimator': 'self._solver', 'n_features_to_select': 'self._n_features'}), '(estimator=self._solver, n_features_to_select=self._n_features, **self.\n kwargs)\n', (37896, 37979), False, 'from sklearn.feature_selection import f_classif, f_regression, mutual_info_classif, mutual_info_regression, chi2, SelectKBest, SelectFromModel, RFE, RFECV, SequentialFeatureSelector\n'), ((38515, 38624), 'sklearn.feature_selection.RFECV', 'RFECV', ([], {'estimator': 'self._solver', 'min_features_to_select': 'self._n_features', 'n_jobs': 'self.n_jobs'}), '(estimator=self._solver, min_features_to_select=self._n_features,\n n_jobs=self.n_jobs, **self.kwargs)\n', (38520, 38624), False, 'from sklearn.feature_selection import f_classif, f_regression, mutual_info_classif, mutual_info_regression, chi2, SelectKBest, SelectFromModel, RFE, RFECV, SequentialFeatureSelector\n'), ((15618, 15657), 'woodwork.column_schema.ColumnSchema', 'ColumnSchema', ([], {'semantic_tags': "['numeric']"}), "(semantic_tags=['numeric'])\n", (15630, 15657), False, 'from woodwork.column_schema import ColumnSchema\n'), ((15561, 15575), 'woodwork.column_schema.ColumnSchema', 'ColumnSchema', ([], {}), '()\n', (15573, 15575), False, 'from woodwork.column_schema import ColumnSchema\n')]
""" position_analysis.py contains scripts for analyzing position data, as the name might imply. """ import ast import csv import glob import os import signal import sys import time from mpl_toolkits.mplot3d import Axes3D from sensor_msgs.msg import Image import cv2 import matplotlib.pyplot as plt import numpy as np import psutil import rospy import agent.config as agent_cfg import agent.plant_ros as plant_ros import agent.agent_utils as agent_utils import agent.agent_ros as agent_ros show_plant = True display_image = False outdir = '/media/jonathon/JON SATHER/Thesis/results/fixation_obs' class Camera(object): """ ROS camera subscriber. """ def __init__(self, topic='/harvester/camera2/image_raw'): self.sub = rospy.Subscriber(topic, Image, self._process_image_data, queue_size=1) self.obs = None def _process_image_data(self, ros_data): flat = np.fromstring(ros_data.data, np.uint8) full = np.reshape(flat, (ros_data.height, ros_data.width, -1)) self.obs = full[...,::-1] # convert to bgr # self.obs = cv2.resize(full, (self.obs_shape[0], self.obs_shape[1])) def arm_over_existing(obs, hemi, name='plant'): """ Overlays image with arm over previously annotated hemi. """ hemi_gray = cv2.cvtColor(hemi, cv2.COLOR_BGR2GRAY) _, hemi_mask = cv2.threshold(hemi_gray, 1, 255, cv2.THRESH_BINARY) hemi_mask_inv = 255 - hemi_mask obs_hsv = cv2.cvtColor(obs, cv2.COLOR_BGR2HSV) _, arm_mask = cv2.threshold(obs_hsv[:,:,1], 3, 255, cv2.THRESH_BINARY_INV) arm_mask_inv = 255 - arm_mask arm_fg = cv2.bitwise_and(obs, obs, mask=arm_mask) arm_fg_hemi = cv2.bitwise_and(arm_fg, arm_fg, mask=hemi_mask) arm_fg_no_hemi = cv2.bitwise_and(arm_fg, arm_fg, mask=hemi_mask_inv) existing = cv2.imread(os.path.join(outdir, name[:-4] + '_plant' + '.png')) existing_fg = cv2.bitwise_and(existing, existing, mask=arm_mask) existing_bg = cv2.bitwise_and(existing, existing, mask=arm_mask_inv) existing_fg_hemi = cv2.bitwise_and(existing_fg, existing_fg, mask=hemi_mask) arm_blend_hemi = cv2.addWeighted(arm_fg_hemi, 0.6, existing_fg_hemi, 0.4, 0.0) arm_blend = cv2.add(arm_blend_hemi, arm_fg_no_hemi) overlay = cv2.add(existing_bg, arm_blend) cv2.imwrite(os.path.join(outdir, name[:-4] + '_plant_arm_blend_hemi' + '.png'), overlay) def create_hemisphere(radius): """ Returns x,y,z data for plotting hemisphere of specified radius. """ phi, theta = np.mgrid[0:0.5*np.pi:100j, 0.0:2.0*np.pi:100j] x = radius*np.sin(phi)*np.cos(theta) y = radius*np.sin(phi)*np.sin(theta) z = radius*np.cos(phi) return (x, y, z) def create_hemi_image(radius): x_sph, y_sph, z_sph = create_hemisphere(radius=radius) fig = plt.figure(figsize=(8,8), dpi=100) ax = Axes3D(fig) ax.set_xlim3d(-radius, radius) ax.set_ylim3d(-radius, radius) ax.set_zlim3d(-0.2*(2*radius), 0.8*(2*radius)) ax.view_init(azim=225) ax.set_axis_off() ax.plot_surface(x_sph, y_sph, z_sph, rstride=1, cstride=1, color='c', alpha=0.3, linewidth=0) plt.savefig('hemi.png', transparent=True) plt.close(fig) time.sleep(1) return cv2.imread('hemi.png') def create_overlay_image(coords, rewards, obs, radius, hemi, name='plant'): """ Creates image overlay and saves to file. """ x_pos = [] y_pos = [] z_pos = [] x_neu = [] y_neu = [] z_neu = [] x_term = [] y_term = [] z_term = [] x = [] y = [] z = [] for idx, coord in enumerate(coords): if rewards[idx] == 1.0: x_pos.append(coord[0]) y_pos.append(coord[1]) z_pos.append(coord[2]) elif rewards[idx] == -0.1: x_neu.append(coord[0]) y_neu.append(coord[1]) z_neu.append(coord[2]) else: x_term.append(coord[0]) y_term.append(coord[1]) z_term.append(coord[2]) x.append(coord[0]) y.append(coord[1]) z.append(coord[2]) # plot points fig = plt.figure(figsize=(8,8), dpi=100) ax = Axes3D(fig) ax.set_xlim3d(-radius, radius) ax.set_ylim3d(-radius, radius) ax.set_zlim3d(-0.2*(2*radius), 0.8*(2*radius)) ax.scatter(x_pos, y_pos, z_pos, c='b', marker='*') ax.scatter(x_neu, y_neu, z_neu, c='y', marker='o') ax.scatter(x_term, y_term, z_term, c='r', marker='o') ax.view_init(azim=225+90) #225 ax.set_axis_off() plt.savefig('plot.png', transparent=True) plt.close(fig) time.sleep(1) plot = cv2.imread('plot.png') hemi_gray = cv2.cvtColor(hemi, cv2.COLOR_BGR2GRAY) _, hemi_mask = cv2.threshold(hemi_gray, 1, 255, cv2.THRESH_BINARY) hemi_mask_inv = 255 - hemi_mask hemi_fg = cv2.bitwise_and(hemi, hemi, mask=hemi_mask) obs_hsv = cv2.cvtColor(obs, cv2.COLOR_BGR2HSV) _, arm_mask = cv2.threshold(obs_hsv[:,:,1], 3, 255, cv2.THRESH_BINARY_INV) arm_mask_inv = 255 - arm_mask arm_fg = cv2.bitwise_and(obs, obs, mask=arm_mask) obs_fg = cv2.bitwise_and(obs, obs, mask=hemi_mask) obs_bg = cv2.bitwise_and(obs, obs, mask=hemi_mask_inv) hemi_blended = cv2.addWeighted(hemi_fg, 0.3, obs_fg, 0.7, 0.0) obs_hemi = cv2.add(hemi_blended, obs_bg) plot_gray = cv2.cvtColor(plot, cv2.COLOR_BGR2GRAY) _, plot_mask = cv2.threshold(plot_gray, 1, 255, cv2.THRESH_BINARY) plot_mask_inv = 255 - plot_mask plot_fg = cv2.bitwise_and(plot, plot, mask=plot_mask) obs_hemi_bg = cv2.bitwise_and(obs_hemi, obs_hemi, mask=plot_mask_inv) overlay_orig = cv2.add(plot_fg, obs_hemi_bg) overlay_fg = cv2.bitwise_and(overlay_orig, overlay_orig, mask=arm_mask) overlay_bg = cv2.bitwise_and(overlay_orig, overlay_orig, mask=arm_mask_inv) overlay = cv2.add(overlay_bg, arm_fg) cv2.imwrite(os.path.join(outdir, name[:-4] + '_plant_arm_blend' + '.png'), overlay) def exit_gracefully(sig, frame): """ Save configuration before exit. """ print('Signal: ' + str(sig)) kill_processes(['roslaunch', 'gzserver', 'gzclient']) sys.exit() def file_from_path(path): """ Extracts local filename from full path """ slashes = [pos for pos, char in enumerate(path) if char == '/'] return path[slashes[-1]+1:] def kill_processes(processes, delay=1): """ Kills processes in list. """ for proc in psutil.process_iter(): if proc.name in processes: print('killing process: ' + proc.name) proc.kill() time.sleep(delay) def spherical_to_cartesian(theta, phi, rho): """ Converts spherical coordinates into cartesian. """ x = rho * np.sin(phi) * np.cos(theta) y = rho * np.sin(phi) * np.sin(theta) z = rho * np.cos(phi) return x, y, z def main(): global show_plant signal.signal(signal.SIGINT, exit_gracefully) signal.signal(signal.SIGTERM, exit_gracefully) fixation_results_dir = '/media/jonathon/<NAME>/Thesis/results/fixation_test_extended' test_dirs = glob.glob(fixation_results_dir + '/*') rewards = [] coords = [] plant_files = [] # plant_list = ['model19.sdf', 'model84.sdf', 'model424.sdf', # 'model161.sdf', 'model309.sdf','model347.sdf', 'model363.sdf', # 'model49.sdf', 'model51.sdf', 'model107.sdf', 'model355.sdf', # 'model423.sdf'] # plant_list = ['model424.sdf', # 'model51.sdf', # 'model423.sdf'] plant_list = ['model122.sdf', 'model308.sdf', 'model74.sdf', 'model149.sdf'] pos_list = [(-0.6, 1.15), (-0.65, 1.4), (-.12, 1.11), (-1.6, 0.4)] while test_dirs: earliest = min(test_dirs, key=os.path.getctime) for fn in glob.glob(os.path.join(earliest, '*')): if fn[-3:] == 'sdf': spaces = [pos for pos, char in enumerate(fn) if char == ' '] for pos in spaces: fn = fn[:pos] + '\ ' + fn[pos+1:] plant_files.append(fn) break with open(os.path.join(earliest, 'ddpg.csv')) as csv_file: csv_reader = csv.DictReader(csv_file) for row in csv_reader: rewards.append(ast.literal_eval(row['all_rewards'])) hemi_coords = ast.literal_eval(row['all_j']) cart_coords = [] for sph in hemi_coords: (x, y, z) = spherical_to_cartesian(sph[0], sph[1], agent_cfg.hemi_radius) cart_coords.append((x,y,z)) # convert to xyz coords.append(cart_coords) test_dirs.remove(earliest) agent = agent_ros.HemiAgentROS(detector=False) agent.move_to_angles(theta=-1.0, phi=0.65) camera = Camera() # create and save hemi backdrop image hemi = create_hemi_image(radius=agent_cfg.hemi_radius) for plant_no in range(len(coords)): plant_name = file_from_path(plant_files[plant_no]) if plant_name in plant_list: # spawn plant and take image agent.plant.new(sdf=plant_files[plant_no]) time.sleep(25) (theta, phi) = pos_list[plant_list.index(plant_name)] agent.move_to_angles(theta=theta, phi=phi) time.sleep(5) cv2.imwrite( os.path.join(outdir, plant_name[:-4] + '_obs' + '.png'), agent.obs[...,::-1]) arm_over_existing(obs=camera.obs, hemi=hemi, name=plant_name) # create_overlay_image(coords=coords[plant_no], # rewards=rewards[plant_no], obs=camera.obs, # radius=agent_cfg.hemi_radius, hemi=hemi, name=plant_name) exit_gracefully(sig='program end', frame=None) if __name__ == "__main__": main()
[ "rospy.Subscriber", "cv2.bitwise_and", "agent.agent_ros.HemiAgentROS", "matplotlib.pyplot.figure", "numpy.sin", "glob.glob", "os.path.join", "psutil.process_iter", "cv2.cvtColor", "matplotlib.pyplot.close", "numpy.reshape", "numpy.fromstring", "mpl_toolkits.mplot3d.Axes3D", "csv.DictReader", "cv2.addWeighted", "time.sleep", "numpy.cos", "signal.signal", "cv2.add", "sys.exit", "cv2.threshold", "cv2.imread", "ast.literal_eval", "matplotlib.pyplot.savefig" ]
[((1299, 1337), 'cv2.cvtColor', 'cv2.cvtColor', (['hemi', 'cv2.COLOR_BGR2GRAY'], {}), '(hemi, cv2.COLOR_BGR2GRAY)\n', (1311, 1337), False, 'import cv2\n'), ((1357, 1408), 'cv2.threshold', 'cv2.threshold', (['hemi_gray', '(1)', '(255)', 'cv2.THRESH_BINARY'], {}), '(hemi_gray, 1, 255, cv2.THRESH_BINARY)\n', (1370, 1408), False, 'import cv2\n'), ((1470, 1506), 'cv2.cvtColor', 'cv2.cvtColor', (['obs', 'cv2.COLOR_BGR2HSV'], {}), '(obs, cv2.COLOR_BGR2HSV)\n', (1482, 1506), False, 'import cv2\n'), ((1525, 1587), 'cv2.threshold', 'cv2.threshold', (['obs_hsv[:, :, 1]', '(3)', '(255)', 'cv2.THRESH_BINARY_INV'], {}), '(obs_hsv[:, :, 1], 3, 255, cv2.THRESH_BINARY_INV)\n', (1538, 1587), False, 'import cv2\n'), ((1633, 1673), 'cv2.bitwise_and', 'cv2.bitwise_and', (['obs', 'obs'], {'mask': 'arm_mask'}), '(obs, obs, mask=arm_mask)\n', (1648, 1673), False, 'import cv2\n'), ((1692, 1739), 'cv2.bitwise_and', 'cv2.bitwise_and', (['arm_fg', 'arm_fg'], {'mask': 'hemi_mask'}), '(arm_fg, arm_fg, mask=hemi_mask)\n', (1707, 1739), False, 'import cv2\n'), ((1761, 1812), 'cv2.bitwise_and', 'cv2.bitwise_and', (['arm_fg', 'arm_fg'], {'mask': 'hemi_mask_inv'}), '(arm_fg, arm_fg, mask=hemi_mask_inv)\n', (1776, 1812), False, 'import cv2\n'), ((1911, 1961), 'cv2.bitwise_and', 'cv2.bitwise_and', (['existing', 'existing'], {'mask': 'arm_mask'}), '(existing, existing, mask=arm_mask)\n', (1926, 1961), False, 'import cv2\n'), ((1980, 2034), 'cv2.bitwise_and', 'cv2.bitwise_and', (['existing', 'existing'], {'mask': 'arm_mask_inv'}), '(existing, existing, mask=arm_mask_inv)\n', (1995, 2034), False, 'import cv2\n'), ((2058, 2115), 'cv2.bitwise_and', 'cv2.bitwise_and', (['existing_fg', 'existing_fg'], {'mask': 'hemi_mask'}), '(existing_fg, existing_fg, mask=hemi_mask)\n', (2073, 2115), False, 'import cv2\n'), ((2138, 2199), 'cv2.addWeighted', 'cv2.addWeighted', (['arm_fg_hemi', '(0.6)', 'existing_fg_hemi', '(0.4)', '(0.0)'], {}), '(arm_fg_hemi, 0.6, existing_fg_hemi, 0.4, 0.0)\n', (2153, 2199), False, 'import cv2\n'), ((2216, 2255), 'cv2.add', 'cv2.add', (['arm_blend_hemi', 'arm_fg_no_hemi'], {}), '(arm_blend_hemi, arm_fg_no_hemi)\n', (2223, 2255), False, 'import cv2\n'), ((2272, 2303), 'cv2.add', 'cv2.add', (['existing_bg', 'arm_blend'], {}), '(existing_bg, arm_blend)\n', (2279, 2303), False, 'import cv2\n'), ((2810, 2845), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(8, 8)', 'dpi': '(100)'}), '(figsize=(8, 8), dpi=100)\n', (2820, 2845), True, 'import matplotlib.pyplot as plt\n'), ((2854, 2865), 'mpl_toolkits.mplot3d.Axes3D', 'Axes3D', (['fig'], {}), '(fig)\n', (2860, 2865), False, 'from mpl_toolkits.mplot3d import Axes3D\n'), ((3151, 3192), 'matplotlib.pyplot.savefig', 'plt.savefig', (['"""hemi.png"""'], {'transparent': '(True)'}), "('hemi.png', transparent=True)\n", (3162, 3192), True, 'import matplotlib.pyplot as plt\n'), ((3197, 3211), 'matplotlib.pyplot.close', 'plt.close', (['fig'], {}), '(fig)\n', (3206, 3211), True, 'import matplotlib.pyplot as plt\n'), ((3216, 3229), 'time.sleep', 'time.sleep', (['(1)'], {}), '(1)\n', (3226, 3229), False, 'import time\n'), ((3241, 3263), 'cv2.imread', 'cv2.imread', (['"""hemi.png"""'], {}), "('hemi.png')\n", (3251, 3263), False, 'import cv2\n'), ((4136, 4171), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(8, 8)', 'dpi': '(100)'}), '(figsize=(8, 8), dpi=100)\n', (4146, 4171), True, 'import matplotlib.pyplot as plt\n'), ((4180, 4191), 'mpl_toolkits.mplot3d.Axes3D', 'Axes3D', (['fig'], {}), '(fig)\n', (4186, 4191), False, 'from mpl_toolkits.mplot3d import Axes3D\n'), ((4546, 4587), 'matplotlib.pyplot.savefig', 'plt.savefig', (['"""plot.png"""'], {'transparent': '(True)'}), "('plot.png', transparent=True)\n", (4557, 4587), True, 'import matplotlib.pyplot as plt\n'), ((4592, 4606), 'matplotlib.pyplot.close', 'plt.close', (['fig'], {}), '(fig)\n', (4601, 4606), True, 'import matplotlib.pyplot as plt\n'), ((4611, 4624), 'time.sleep', 'time.sleep', (['(1)'], {}), '(1)\n', (4621, 4624), False, 'import time\n'), ((4636, 4658), 'cv2.imread', 'cv2.imread', (['"""plot.png"""'], {}), "('plot.png')\n", (4646, 4658), False, 'import cv2\n'), ((4688, 4726), 'cv2.cvtColor', 'cv2.cvtColor', (['hemi', 'cv2.COLOR_BGR2GRAY'], {}), '(hemi, cv2.COLOR_BGR2GRAY)\n', (4700, 4726), False, 'import cv2\n'), ((4746, 4797), 'cv2.threshold', 'cv2.threshold', (['hemi_gray', '(1)', '(255)', 'cv2.THRESH_BINARY'], {}), '(hemi_gray, 1, 255, cv2.THRESH_BINARY)\n', (4759, 4797), False, 'import cv2\n'), ((4859, 4902), 'cv2.bitwise_and', 'cv2.bitwise_and', (['hemi', 'hemi'], {'mask': 'hemi_mask'}), '(hemi, hemi, mask=hemi_mask)\n', (4874, 4902), False, 'import cv2\n'), ((4923, 4959), 'cv2.cvtColor', 'cv2.cvtColor', (['obs', 'cv2.COLOR_BGR2HSV'], {}), '(obs, cv2.COLOR_BGR2HSV)\n', (4935, 4959), False, 'import cv2\n'), ((4978, 5040), 'cv2.threshold', 'cv2.threshold', (['obs_hsv[:, :, 1]', '(3)', '(255)', 'cv2.THRESH_BINARY_INV'], {}), '(obs_hsv[:, :, 1], 3, 255, cv2.THRESH_BINARY_INV)\n', (4991, 5040), False, 'import cv2\n'), ((5086, 5126), 'cv2.bitwise_and', 'cv2.bitwise_and', (['obs', 'obs'], {'mask': 'arm_mask'}), '(obs, obs, mask=arm_mask)\n', (5101, 5126), False, 'import cv2\n'), ((5141, 5182), 'cv2.bitwise_and', 'cv2.bitwise_and', (['obs', 'obs'], {'mask': 'hemi_mask'}), '(obs, obs, mask=hemi_mask)\n', (5156, 5182), False, 'import cv2\n'), ((5196, 5241), 'cv2.bitwise_and', 'cv2.bitwise_and', (['obs', 'obs'], {'mask': 'hemi_mask_inv'}), '(obs, obs, mask=hemi_mask_inv)\n', (5211, 5241), False, 'import cv2\n'), ((5262, 5309), 'cv2.addWeighted', 'cv2.addWeighted', (['hemi_fg', '(0.3)', 'obs_fg', '(0.7)', '(0.0)'], {}), '(hemi_fg, 0.3, obs_fg, 0.7, 0.0)\n', (5277, 5309), False, 'import cv2\n'), ((5325, 5354), 'cv2.add', 'cv2.add', (['hemi_blended', 'obs_bg'], {}), '(hemi_blended, obs_bg)\n', (5332, 5354), False, 'import cv2\n'), ((5373, 5411), 'cv2.cvtColor', 'cv2.cvtColor', (['plot', 'cv2.COLOR_BGR2GRAY'], {}), '(plot, cv2.COLOR_BGR2GRAY)\n', (5385, 5411), False, 'import cv2\n'), ((5431, 5482), 'cv2.threshold', 'cv2.threshold', (['plot_gray', '(1)', '(255)', 'cv2.THRESH_BINARY'], {}), '(plot_gray, 1, 255, cv2.THRESH_BINARY)\n', (5444, 5482), False, 'import cv2\n'), ((5548, 5591), 'cv2.bitwise_and', 'cv2.bitwise_and', (['plot', 'plot'], {'mask': 'plot_mask'}), '(plot, plot, mask=plot_mask)\n', (5563, 5591), False, 'import cv2\n'), ((5610, 5665), 'cv2.bitwise_and', 'cv2.bitwise_and', (['obs_hemi', 'obs_hemi'], {'mask': 'plot_mask_inv'}), '(obs_hemi, obs_hemi, mask=plot_mask_inv)\n', (5625, 5665), False, 'import cv2\n'), ((5696, 5725), 'cv2.add', 'cv2.add', (['plot_fg', 'obs_hemi_bg'], {}), '(plot_fg, obs_hemi_bg)\n', (5703, 5725), False, 'import cv2\n'), ((5748, 5806), 'cv2.bitwise_and', 'cv2.bitwise_and', (['overlay_orig', 'overlay_orig'], {'mask': 'arm_mask'}), '(overlay_orig, overlay_orig, mask=arm_mask)\n', (5763, 5806), False, 'import cv2\n'), ((5832, 5894), 'cv2.bitwise_and', 'cv2.bitwise_and', (['overlay_orig', 'overlay_orig'], {'mask': 'arm_mask_inv'}), '(overlay_orig, overlay_orig, mask=arm_mask_inv)\n', (5847, 5894), False, 'import cv2\n'), ((5922, 5949), 'cv2.add', 'cv2.add', (['overlay_bg', 'arm_fg'], {}), '(overlay_bg, arm_fg)\n', (5929, 5949), False, 'import cv2\n'), ((6220, 6230), 'sys.exit', 'sys.exit', ([], {}), '()\n', (6228, 6230), False, 'import sys\n'), ((6503, 6524), 'psutil.process_iter', 'psutil.process_iter', ([], {}), '()\n', (6522, 6524), False, 'import psutil\n'), ((6943, 6988), 'signal.signal', 'signal.signal', (['signal.SIGINT', 'exit_gracefully'], {}), '(signal.SIGINT, exit_gracefully)\n', (6956, 6988), False, 'import signal\n'), ((6993, 7039), 'signal.signal', 'signal.signal', (['signal.SIGTERM', 'exit_gracefully'], {}), '(signal.SIGTERM, exit_gracefully)\n', (7006, 7039), False, 'import signal\n'), ((7147, 7185), 'glob.glob', 'glob.glob', (["(fixation_results_dir + '/*')"], {}), "(fixation_results_dir + '/*')\n", (7156, 7185), False, 'import glob\n'), ((8783, 8821), 'agent.agent_ros.HemiAgentROS', 'agent_ros.HemiAgentROS', ([], {'detector': '(False)'}), '(detector=False)\n', (8805, 8821), True, 'import agent.agent_ros as agent_ros\n'), ((759, 829), 'rospy.Subscriber', 'rospy.Subscriber', (['topic', 'Image', 'self._process_image_data'], {'queue_size': '(1)'}), '(topic, Image, self._process_image_data, queue_size=1)\n', (775, 829), False, 'import rospy\n'), ((920, 958), 'numpy.fromstring', 'np.fromstring', (['ros_data.data', 'np.uint8'], {}), '(ros_data.data, np.uint8)\n', (933, 958), True, 'import numpy as np\n'), ((974, 1029), 'numpy.reshape', 'np.reshape', (['flat', '(ros_data.height, ros_data.width, -1)'], {}), '(flat, (ros_data.height, ros_data.width, -1))\n', (984, 1029), True, 'import numpy as np\n'), ((1840, 1891), 'os.path.join', 'os.path.join', (['outdir', "(name[:-4] + '_plant' + '.png')"], {}), "(outdir, name[:-4] + '_plant' + '.png')\n", (1852, 1891), False, 'import os\n'), ((2321, 2387), 'os.path.join', 'os.path.join', (['outdir', "(name[:-4] + '_plant_arm_blend_hemi' + '.png')"], {}), "(outdir, name[:-4] + '_plant_arm_blend_hemi' + '.png')\n", (2333, 2387), False, 'import os\n'), ((2605, 2618), 'numpy.cos', 'np.cos', (['theta'], {}), '(theta)\n', (2611, 2618), True, 'import numpy as np\n'), ((2646, 2659), 'numpy.sin', 'np.sin', (['theta'], {}), '(theta)\n', (2652, 2659), True, 'import numpy as np\n'), ((2675, 2686), 'numpy.cos', 'np.cos', (['phi'], {}), '(phi)\n', (2681, 2686), True, 'import numpy as np\n'), ((5967, 6028), 'os.path.join', 'os.path.join', (['outdir', "(name[:-4] + '_plant_arm_blend' + '.png')"], {}), "(outdir, name[:-4] + '_plant_arm_blend' + '.png')\n", (5979, 6028), False, 'import os\n'), ((6800, 6813), 'numpy.cos', 'np.cos', (['theta'], {}), '(theta)\n', (6806, 6813), True, 'import numpy as np\n'), ((6842, 6855), 'numpy.sin', 'np.sin', (['theta'], {}), '(theta)\n', (6848, 6855), True, 'import numpy as np\n'), ((6870, 6881), 'numpy.cos', 'np.cos', (['phi'], {}), '(phi)\n', (6876, 6881), True, 'import numpy as np\n'), ((2593, 2604), 'numpy.sin', 'np.sin', (['phi'], {}), '(phi)\n', (2599, 2604), True, 'import numpy as np\n'), ((2634, 2645), 'numpy.sin', 'np.sin', (['phi'], {}), '(phi)\n', (2640, 2645), True, 'import numpy as np\n'), ((6649, 6666), 'time.sleep', 'time.sleep', (['delay'], {}), '(delay)\n', (6659, 6666), False, 'import time\n'), ((6786, 6797), 'numpy.sin', 'np.sin', (['phi'], {}), '(phi)\n', (6792, 6797), True, 'import numpy as np\n'), ((6828, 6839), 'numpy.sin', 'np.sin', (['phi'], {}), '(phi)\n', (6834, 6839), True, 'import numpy as np\n'), ((7826, 7853), 'os.path.join', 'os.path.join', (['earliest', '"""*"""'], {}), "(earliest, '*')\n", (7838, 7853), False, 'import os\n'), ((8210, 8234), 'csv.DictReader', 'csv.DictReader', (['csv_file'], {}), '(csv_file)\n', (8224, 8234), False, 'import csv\n'), ((9242, 9256), 'time.sleep', 'time.sleep', (['(25)'], {}), '(25)\n', (9252, 9256), False, 'import time\n'), ((9391, 9404), 'time.sleep', 'time.sleep', (['(5)'], {}), '(5)\n', (9401, 9404), False, 'import time\n'), ((8136, 8170), 'os.path.join', 'os.path.join', (['earliest', '"""ddpg.csv"""'], {}), "(earliest, 'ddpg.csv')\n", (8148, 8170), False, 'import os\n'), ((8370, 8400), 'ast.literal_eval', 'ast.literal_eval', (["row['all_j']"], {}), "(row['all_j'])\n", (8386, 8400), False, 'import ast\n'), ((9460, 9515), 'os.path.join', 'os.path.join', (['outdir', "(plant_name[:-4] + '_obs' + '.png')"], {}), "(outdir, plant_name[:-4] + '_obs' + '.png')\n", (9472, 9515), False, 'import os\n'), ((8302, 8338), 'ast.literal_eval', 'ast.literal_eval', (["row['all_rewards']"], {}), "(row['all_rewards'])\n", (8318, 8338), False, 'import ast\n')]
#!/usr/bin/env python3 import os, sys sys.path.append(os.path.join(os.path.dirname(__file__), '..', 'lib')) from support import Database, Config import numpy as np import queue, math, socket, subprocess, support, threading import tensorflow as tf class Learn: def __init__(self, config): graph = tf.Graph() with graph.as_default(): model = Model(config) with tf.variable_scope('optimization'): epoch = tf.Variable(0, name='epoch', trainable=False) increment_epoch = epoch.assign_add(1) parameters = tf.trainable_variables() gradient = tf.gradients(model.loss, parameters) gradient, _ = tf.clip_by_global_norm(gradient, config.gradient_clip) optimizer = tf.train.AdamOptimizer(config.learning_rate) train = optimizer.apply_gradients(zip(gradient, parameters)) with tf.variable_scope('summary'): tf.scalar_summary('log_loss', tf.log(tf.reduce_sum(model.loss))) logger = tf.train.SummaryWriter(config.log_path, graph) summary = tf.merge_all_summaries() initialize = tf.initialize_variables(tf.all_variables(), name='initialize') saver = Saver(config) self.graph = graph self.model = model self.epoch = epoch self.increment_epoch = increment_epoch self.parameters = parameters self.train = train self.logger = logger self.summary = summary self.initialize = initialize self.saver = saver def count_parameters(self): return np.sum([int(np.prod(parameter.get_shape())) for parameter in self.parameters]) def run(self, target, monitor, config): print('Parameters: %d' % self.count_parameters()) print('Samples: %d' % target.sample_count) session = tf.Session(graph=self.graph) session.run(self.initialize) self.saver.restore(session) epoch = session.run(self.epoch) epoch_count = config.epoch_count - epoch % config.epoch_count for e in range(epoch, epoch + epoch_count): self._run_epoch(target, monitor, config, session, e) assert(session.run(self.increment_epoch) == e + 1) self.saver.save(session) def _run_epoch(self, target, monitor, config, session, e): for s in range(target.sample_count): t = e*target.sample_count + s if monitor.should_train(t): self._run_train(target, monitor, config, session, e, s, t) if monitor.should_predict(t): self._run_predict(target, monitor, config, session, e, s, t) def _run_train(self, target, monitor, config, session, e, s, t): sample = target.compute(s) feed = { self.model.start: self._zero_start(), self.model.x: np.reshape(sample, [1, -1, target.dimension_count]), self.model.y: np.reshape(support.shift(sample, -1), [1, -1, target.dimension_count]), } fetch = {'train': self.train, 'loss': self.model.loss, 'summary': self.summary} result = session.run(fetch, feed) loss = result['loss'].flatten() assert(np.all([not math.isnan(loss) for loss in loss])) monitor.train((e, s, t), loss) self.logger.add_summary(result['summary'], t) def _run_predict(self, target, monitor, config, session, e, s, t): sample = target.compute((s + 1) % target.sample_count) step_count = sample.shape[0] feed = {self.model.start: self._zero_start()} fetch = {'y_hat': self.model.y_hat, 'finish': self.model.finish} for i in range(step_count): feed[self.model.x] = np.reshape(sample[:(i + 1), :], [1, i + 1, -1]) y_hat = np.zeros([step_count, target.dimension_count]) for j in range(step_count - i - 1): result = session.run(fetch, feed) feed[self.model.start] = result['finish'] y_hat[j, :] = result['y_hat'][-1, :] feed[self.model.x] = np.reshape(y_hat[j, :], [1, 1, -1]) if not monitor.predict(support.shift(sample, -i - 1), y_hat): break def _zero_start(self): return np.zeros(self.model.start.get_shape(), np.float32) class Model: def __init__(self, config): x = tf.placeholder(tf.float32, [1, None, config.dimension_count], name='x') y = tf.placeholder(tf.float32, [1, None, config.dimension_count], name='y') with tf.variable_scope('network') as scope: cell = tf.nn.rnn_cell.LSTMCell(config.unit_count, state_is_tuple=True, cell_clip=config.cell_clip, forget_bias=config.forget_bias, use_peepholes=config.use_peepholes, initializer=config.network_initializer) cell = tf.nn.rnn_cell.MultiRNNCell([cell] * config.layer_count, state_is_tuple=True) start, state = Model._initialize(config) h, state = tf.nn.dynamic_rnn(cell, x, initial_state=state, parallel_iterations=1) finish = Model._finalize(state, config) y_hat, loss = Model._regress(h, y, config) self.x = x self.y = y self.y_hat = y_hat self.loss = loss self.start = start self.finish = finish def _finalize(state, config): parts = [] for i in range(config.layer_count): parts.append(state[i].c) parts.append(state[i].h) return tf.pack(parts, name='finish') def _initialize(config): start = tf.placeholder(tf.float32, [2 * config.layer_count, 1, config.unit_count], name='start') parts = tf.unpack(start) state = [] for i in range(config.layer_count): c, h = parts[2 * i], parts[2*i + 1] state.append(tf.nn.rnn_cell.LSTMStateTuple(c, h)) return start, tuple(state) def _regress(x, y, config): with tf.variable_scope('regression') as scope: unroll_count = tf.shape(x)[1] x = tf.squeeze(x, squeeze_dims=[0]) y = tf.squeeze(y, squeeze_dims=[0]) w = tf.get_variable('w', [config.unit_count, config.dimension_count], initializer=config.regression_initializer) b = tf.get_variable('b', [1, config.dimension_count]) y_hat = tf.matmul(x, w) + tf.tile(b, [unroll_count, 1]) loss = tf.reduce_mean(tf.squared_difference(y_hat, y)) return y_hat, loss class Monitor: def __init__(self, config): self.bind_address = config.bind_address self.work_schedule = np.cumsum(config.work_schedule) self.channels = {} self.lock = threading.Lock() threading.Thread(target=self._predict_server, daemon=True).start() def should_train(self, t): return True def should_predict(self, t): return (len(self.channels) > 0 and np.nonzero(self.work_schedule >= (t % self.work_schedule[-1]))[0][0] % 2 == 1) def train(self, progress, loss): sys.stdout.write('%4d %10d %10d' % progress) [sys.stdout.write(' %12.4e' % loss) for loss in loss] sys.stdout.write('\n') def predict(self, y, y_hat): self.lock.acquire() try: for channel in self.channels: channel.put((y, y_hat)) finally: self.lock.release() return len(self.channels) > 0 def _predict_client(self, connection, address): print('Start serving {}.'.format(address)) channel = queue.Queue() self.lock.acquire() try: self.channels[channel] = True finally: self.lock.release() try: client = connection.makefile(mode="w") while True: y, y_hat = channel.get() client.write(','.join([str(value) for value in y.flatten()]) + ',') client.write(','.join([str(value) for value in y_hat.flatten()]) + '\n') except Exception as e: print('Stop serving {} ({}).'.format(address, e)) self.lock.acquire() try: del self.channels[channel] finally: self.lock.release() def _predict_server(self): server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) server.bind(self.bind_address) server.listen(1) print('Listening to {}...'.format(self.bind_address)) while True: try: connection, address = server.accept() threading.Thread(target=self._predict_client, daemon=True, args=(connection, address)).start() except Exception as e: print('Encountered a problem ({}).'.format(e)) class Saver: def __init__(self, config): self.backend = tf.train.Saver() self.path = config.save_path def save(self, session): path = self.backend.save(session, self.path) print('Saved the model in "{}".'.format(path)) def restore(self, session): if os.path.isfile(self.path): if input('Found a model in "{}". Restore? '.format(self.path)) != 'no': self.backend.restore(session, self.path) print('Restored. Continue learning...') class Target: def __init__(self, config): database = Database(config) data = database.read()[:, 0] partition = database.partition() sample_count = partition.shape[0] samples, stack = {}, [] for k in range(sample_count): i, j = partition[k] samples[k] = data[i:j] stack.append(samples[k]) data = np.concatenate(stack) offset, scale = np.mean(data), np.std(data) for k in range(sample_count): samples[k] = np.reshape((samples[k] - offset) / scale, [-1, 1]) self.dimension_count = 1 self.sample_count = sample_count self.samples = samples def compute(self, k): return self.samples[k] class TestTarget: def __init__(self, config): self.dimension_count = 1 self.sample_count = 100000 def compute(self, k): return np.reshape(np.sin(4 * np.pi / 40 * np.arange(0, 40)), [-1, 1]) def main(config): learn = Learn(config) target = Target(config) monitor = Monitor(config) learn.run(target, monitor, config) if __name__ == '__main__': database_path = Database.find() output_path = os.path.dirname(database_path) name = os.path.basename(database_path).replace('.sqlite3', '') config = Config({ 'dimension_count': 1, 'database_path': database_path, 'layer_count': 1, 'unit_count': 200, 'cell_clip': 1.0, 'forget_bias': 1.0, 'use_peepholes': True, 'network_initializer': tf.random_uniform_initializer(-0.01, 0.01), 'regression_initializer': tf.random_normal_initializer(stddev=0.01), 'learning_rate': 1e-3, 'gradient_clip': 1.0, 'epoch_count': 100, 'log_path': os.path.join(output_path, 'log'), 'save_path': os.path.join(output_path, '{}.model'.format(name)), 'bind_address': ('0.0.0.0', 4242), 'work_schedule': [1000 - 10, 10], }) main(config)
[ "sys.stdout.write", "tensorflow.reduce_sum", "tensorflow.nn.rnn_cell.LSTMStateTuple", "tensorflow.trainable_variables", "socket.socket", "tensorflow.merge_all_summaries", "tensorflow.matmul", "os.path.isfile", "numpy.mean", "tensorflow.Variable", "numpy.arange", "tensorflow.nn.rnn_cell.LSTMCell", "os.path.join", "tensorflow.clip_by_global_norm", "tensorflow.get_variable", "tensorflow.random_uniform_initializer", "numpy.std", "os.path.dirname", "tensorflow.variable_scope", "threading.Lock", "tensorflow.placeholder", "numpy.cumsum", "numpy.reshape", "tensorflow.squeeze", "tensorflow.pack", "tensorflow.gradients", "support.Database.find", "tensorflow.unpack", "threading.Thread", "support.Database", "math.isnan", "tensorflow.train.Saver", "os.path.basename", "tensorflow.all_variables", "tensorflow.Session", "tensorflow.nn.rnn_cell.MultiRNNCell", "tensorflow.tile", "tensorflow.random_normal_initializer", "tensorflow.Graph", "tensorflow.squared_difference", "queue.Queue", "numpy.concatenate", "support.shift", "tensorflow.nn.dynamic_rnn", "tensorflow.train.SummaryWriter", "numpy.zeros", "numpy.nonzero", "tensorflow.shape", "tensorflow.train.AdamOptimizer" ]
[((10832, 10847), 'support.Database.find', 'Database.find', ([], {}), '()\n', (10845, 10847), False, 'from support import Database, Config\n'), ((10866, 10896), 'os.path.dirname', 'os.path.dirname', (['database_path'], {}), '(database_path)\n', (10881, 10896), False, 'import os, sys\n'), ((68, 93), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (83, 93), False, 'import os, sys\n'), ((311, 321), 'tensorflow.Graph', 'tf.Graph', ([], {}), '()\n', (319, 321), True, 'import tensorflow as tf\n'), ((1899, 1927), 'tensorflow.Session', 'tf.Session', ([], {'graph': 'self.graph'}), '(graph=self.graph)\n', (1909, 1927), True, 'import tensorflow as tf\n'), ((4412, 4483), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32', '[1, None, config.dimension_count]'], {'name': '"""x"""'}), "(tf.float32, [1, None, config.dimension_count], name='x')\n", (4426, 4483), True, 'import tensorflow as tf\n'), ((4496, 4567), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32', '[1, None, config.dimension_count]'], {'name': '"""y"""'}), "(tf.float32, [1, None, config.dimension_count], name='y')\n", (4510, 4567), True, 'import tensorflow as tf\n'), ((5735, 5764), 'tensorflow.pack', 'tf.pack', (['parts'], {'name': '"""finish"""'}), "(parts, name='finish')\n", (5742, 5764), True, 'import tensorflow as tf\n'), ((5811, 5903), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32', '[2 * config.layer_count, 1, config.unit_count]'], {'name': '"""start"""'}), "(tf.float32, [2 * config.layer_count, 1, config.unit_count],\n name='start')\n", (5825, 5903), True, 'import tensorflow as tf\n'), ((5947, 5963), 'tensorflow.unpack', 'tf.unpack', (['start'], {}), '(start)\n', (5956, 5963), True, 'import tensorflow as tf\n'), ((6908, 6939), 'numpy.cumsum', 'np.cumsum', (['config.work_schedule'], {}), '(config.work_schedule)\n', (6917, 6939), True, 'import numpy as np\n'), ((6987, 7003), 'threading.Lock', 'threading.Lock', ([], {}), '()\n', (7001, 7003), False, 'import queue, math, socket, subprocess, support, threading\n'), ((7345, 7389), 'sys.stdout.write', 'sys.stdout.write', (["('%4d %10d %10d' % progress)"], {}), "('%4d %10d %10d' % progress)\n", (7361, 7389), False, 'import os, sys\n'), ((7460, 7482), 'sys.stdout.write', 'sys.stdout.write', (['"""\n"""'], {}), "('\\n')\n", (7476, 7482), False, 'import os, sys\n'), ((7849, 7862), 'queue.Queue', 'queue.Queue', ([], {}), '()\n', (7860, 7862), False, 'import queue, math, socket, subprocess, support, threading\n'), ((8568, 8617), 'socket.socket', 'socket.socket', (['socket.AF_INET', 'socket.SOCK_STREAM'], {}), '(socket.AF_INET, socket.SOCK_STREAM)\n', (8581, 8617), False, 'import queue, math, socket, subprocess, support, threading\n'), ((9215, 9231), 'tensorflow.train.Saver', 'tf.train.Saver', ([], {}), '()\n', (9229, 9231), True, 'import tensorflow as tf\n'), ((9451, 9476), 'os.path.isfile', 'os.path.isfile', (['self.path'], {}), '(self.path)\n', (9465, 9476), False, 'import os, sys\n'), ((9741, 9757), 'support.Database', 'Database', (['config'], {}), '(config)\n', (9749, 9757), False, 'from support import Database, Config\n'), ((10067, 10088), 'numpy.concatenate', 'np.concatenate', (['stack'], {}), '(stack)\n', (10081, 10088), True, 'import numpy as np\n'), ((1067, 1113), 'tensorflow.train.SummaryWriter', 'tf.train.SummaryWriter', (['config.log_path', 'graph'], {}), '(config.log_path, graph)\n', (1089, 1113), True, 'import tensorflow as tf\n'), ((1136, 1160), 'tensorflow.merge_all_summaries', 'tf.merge_all_summaries', ([], {}), '()\n', (1158, 1160), True, 'import tensorflow as tf\n'), ((2911, 2962), 'numpy.reshape', 'np.reshape', (['sample', '[1, -1, target.dimension_count]'], {}), '(sample, [1, -1, target.dimension_count])\n', (2921, 2962), True, 'import numpy as np\n'), ((3767, 3812), 'numpy.reshape', 'np.reshape', (['sample[:i + 1, :]', '[1, i + 1, -1]'], {}), '(sample[:i + 1, :], [1, i + 1, -1])\n', (3777, 3812), True, 'import numpy as np\n'), ((3835, 3881), 'numpy.zeros', 'np.zeros', (['[step_count, target.dimension_count]'], {}), '([step_count, target.dimension_count])\n', (3843, 3881), True, 'import numpy as np\n'), ((4581, 4609), 'tensorflow.variable_scope', 'tf.variable_scope', (['"""network"""'], {}), "('network')\n", (4598, 4609), True, 'import tensorflow as tf\n'), ((4639, 4848), 'tensorflow.nn.rnn_cell.LSTMCell', 'tf.nn.rnn_cell.LSTMCell', (['config.unit_count'], {'state_is_tuple': '(True)', 'cell_clip': 'config.cell_clip', 'forget_bias': 'config.forget_bias', 'use_peepholes': 'config.use_peepholes', 'initializer': 'config.network_initializer'}), '(config.unit_count, state_is_tuple=True, cell_clip=\n config.cell_clip, forget_bias=config.forget_bias, use_peepholes=config.\n use_peepholes, initializer=config.network_initializer)\n', (4662, 4848), True, 'import tensorflow as tf\n'), ((5073, 5150), 'tensorflow.nn.rnn_cell.MultiRNNCell', 'tf.nn.rnn_cell.MultiRNNCell', (['([cell] * config.layer_count)'], {'state_is_tuple': '(True)'}), '([cell] * config.layer_count, state_is_tuple=True)\n', (5100, 5150), True, 'import tensorflow as tf\n'), ((5227, 5297), 'tensorflow.nn.dynamic_rnn', 'tf.nn.dynamic_rnn', (['cell', 'x'], {'initial_state': 'state', 'parallel_iterations': '(1)'}), '(cell, x, initial_state=state, parallel_iterations=1)\n', (5244, 5297), True, 'import tensorflow as tf\n'), ((6218, 6249), 'tensorflow.variable_scope', 'tf.variable_scope', (['"""regression"""'], {}), "('regression')\n", (6235, 6249), True, 'import tensorflow as tf\n'), ((6318, 6349), 'tensorflow.squeeze', 'tf.squeeze', (['x'], {'squeeze_dims': '[0]'}), '(x, squeeze_dims=[0])\n', (6328, 6349), True, 'import tensorflow as tf\n'), ((6366, 6397), 'tensorflow.squeeze', 'tf.squeeze', (['y'], {'squeeze_dims': '[0]'}), '(y, squeeze_dims=[0])\n', (6376, 6397), True, 'import tensorflow as tf\n'), ((6414, 6526), 'tensorflow.get_variable', 'tf.get_variable', (['"""w"""', '[config.unit_count, config.dimension_count]'], {'initializer': 'config.regression_initializer'}), "('w', [config.unit_count, config.dimension_count],\n initializer=config.regression_initializer)\n", (6429, 6526), True, 'import tensorflow as tf\n'), ((6571, 6620), 'tensorflow.get_variable', 'tf.get_variable', (['"""b"""', '[1, config.dimension_count]'], {}), "('b', [1, config.dimension_count])\n", (6586, 6620), True, 'import tensorflow as tf\n'), ((7399, 7433), 'sys.stdout.write', 'sys.stdout.write', (["(' %12.4e' % loss)"], {}), "(' %12.4e' % loss)\n", (7415, 7433), False, 'import os, sys\n'), ((10113, 10126), 'numpy.mean', 'np.mean', (['data'], {}), '(data)\n', (10120, 10126), True, 'import numpy as np\n'), ((10128, 10140), 'numpy.std', 'np.std', (['data'], {}), '(data)\n', (10134, 10140), True, 'import numpy as np\n'), ((10204, 10254), 'numpy.reshape', 'np.reshape', (['((samples[k] - offset) / scale)', '[-1, 1]'], {}), '((samples[k] - offset) / scale, [-1, 1])\n', (10214, 10254), True, 'import numpy as np\n'), ((10908, 10939), 'os.path.basename', 'os.path.basename', (['database_path'], {}), '(database_path)\n', (10924, 10939), False, 'import os, sys\n'), ((11225, 11267), 'tensorflow.random_uniform_initializer', 'tf.random_uniform_initializer', (['(-0.01)', '(0.01)'], {}), '(-0.01, 0.01)\n', (11254, 11267), True, 'import tensorflow as tf\n'), ((11303, 11344), 'tensorflow.random_normal_initializer', 'tf.random_normal_initializer', ([], {'stddev': '(0.01)'}), '(stddev=0.01)\n', (11331, 11344), True, 'import tensorflow as tf\n'), ((11455, 11487), 'os.path.join', 'os.path.join', (['output_path', '"""log"""'], {}), "(output_path, 'log')\n", (11467, 11487), False, 'import os, sys\n'), ((406, 439), 'tensorflow.variable_scope', 'tf.variable_scope', (['"""optimization"""'], {}), "('optimization')\n", (423, 439), True, 'import tensorflow as tf\n'), ((465, 510), 'tensorflow.Variable', 'tf.Variable', (['(0)'], {'name': '"""epoch"""', 'trainable': '(False)'}), "(0, name='epoch', trainable=False)\n", (476, 510), True, 'import tensorflow as tf\n'), ((594, 618), 'tensorflow.trainable_variables', 'tf.trainable_variables', ([], {}), '()\n', (616, 618), True, 'import tensorflow as tf\n'), ((646, 682), 'tensorflow.gradients', 'tf.gradients', (['model.loss', 'parameters'], {}), '(model.loss, parameters)\n', (658, 682), True, 'import tensorflow as tf\n'), ((713, 767), 'tensorflow.clip_by_global_norm', 'tf.clip_by_global_norm', (['gradient', 'config.gradient_clip'], {}), '(gradient, config.gradient_clip)\n', (735, 767), True, 'import tensorflow as tf\n'), ((796, 840), 'tensorflow.train.AdamOptimizer', 'tf.train.AdamOptimizer', (['config.learning_rate'], {}), '(config.learning_rate)\n', (818, 840), True, 'import tensorflow as tf\n'), ((935, 963), 'tensorflow.variable_scope', 'tf.variable_scope', (['"""summary"""'], {}), "('summary')\n", (952, 963), True, 'import tensorflow as tf\n'), ((1210, 1228), 'tensorflow.all_variables', 'tf.all_variables', ([], {}), '()\n', (1226, 1228), True, 'import tensorflow as tf\n'), ((3001, 3026), 'support.shift', 'support.shift', (['sample', '(-1)'], {}), '(sample, -1)\n', (3014, 3026), False, 'import queue, math, socket, subprocess, support, threading\n'), ((4128, 4163), 'numpy.reshape', 'np.reshape', (['y_hat[j, :]', '[1, 1, -1]'], {}), '(y_hat[j, :], [1, 1, -1])\n', (4138, 4163), True, 'import numpy as np\n'), ((6100, 6135), 'tensorflow.nn.rnn_cell.LSTMStateTuple', 'tf.nn.rnn_cell.LSTMStateTuple', (['c', 'h'], {}), '(c, h)\n', (6129, 6135), True, 'import tensorflow as tf\n'), ((6287, 6298), 'tensorflow.shape', 'tf.shape', (['x'], {}), '(x)\n', (6295, 6298), True, 'import tensorflow as tf\n'), ((6641, 6656), 'tensorflow.matmul', 'tf.matmul', (['x', 'w'], {}), '(x, w)\n', (6650, 6656), True, 'import tensorflow as tf\n'), ((6659, 6688), 'tensorflow.tile', 'tf.tile', (['b', '[unroll_count, 1]'], {}), '(b, [unroll_count, 1])\n', (6666, 6688), True, 'import tensorflow as tf\n'), ((6723, 6754), 'tensorflow.squared_difference', 'tf.squared_difference', (['y_hat', 'y'], {}), '(y_hat, y)\n', (6744, 6754), True, 'import tensorflow as tf\n'), ((7012, 7070), 'threading.Thread', 'threading.Thread', ([], {'target': 'self._predict_server', 'daemon': '(True)'}), '(target=self._predict_server, daemon=True)\n', (7028, 7070), False, 'import queue, math, socket, subprocess, support, threading\n'), ((3269, 3285), 'math.isnan', 'math.isnan', (['loss'], {}), '(loss)\n', (3279, 3285), False, 'import queue, math, socket, subprocess, support, threading\n'), ((4199, 4228), 'support.shift', 'support.shift', (['sample', '(-i - 1)'], {}), '(sample, -i - 1)\n', (4212, 4228), False, 'import queue, math, socket, subprocess, support, threading\n'), ((10614, 10630), 'numpy.arange', 'np.arange', (['(0)', '(40)'], {}), '(0, 40)\n', (10623, 10630), True, 'import numpy as np\n'), ((1018, 1043), 'tensorflow.reduce_sum', 'tf.reduce_sum', (['model.loss'], {}), '(model.loss)\n', (1031, 1043), True, 'import tensorflow as tf\n'), ((8920, 9010), 'threading.Thread', 'threading.Thread', ([], {'target': 'self._predict_client', 'daemon': '(True)', 'args': '(connection, address)'}), '(target=self._predict_client, daemon=True, args=(connection,\n address))\n', (8936, 9010), False, 'import queue, math, socket, subprocess, support, threading\n'), ((7220, 7280), 'numpy.nonzero', 'np.nonzero', (['(self.work_schedule >= t % self.work_schedule[-1])'], {}), '(self.work_schedule >= t % self.work_schedule[-1])\n', (7230, 7280), True, 'import numpy as np\n')]
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Jun 7 11:51:53 2019 @author: carsault """ #%% import pickle import torch from utilities import chordUtil from utilities.chordUtil import * from utilities import testFunc from utilities.testFunc import * from utilities import distance from utilities.distance import * from ACE_Analyzer import ACEAnalyzer from ACE_Analyzer.ACEAnalyzer import * import numpy as np import time #time.sleep(3600) # CUDA for PyTorch device = torch.device("cuda" if torch.cuda.is_available() else "cpu") dtype = torch.cuda.FloatTensor foldName = "modelSave200908" #modelType = ["mlpDecim", "mlpDecimKey", "mlpDecimBeat", "mlpDecimKeyBeat","mlpDecimAug","mlpDecimFamily"] #modelType = ["lstmDecim"] modelType = ["mlpDecimAug"] randm = [1, 2, 3, 4, 5] #alpha = ['functional'] alpha = ['a0','a2','a5','functional'] maxRepList = [1] alphaRep = ["Nope","alphaRep"] dictKey, listKey = chordUtil.getDictKey() correctDown = [0]*4 correctPos = [0]*8 totalDown = [0]*4 totalPos = [0]*8 musicalDist2 = 0 musicalDist4 = 0 dictFinalRes = {} specName = "" #test #modelType = ["mlpDecim"] #foldName = "modelSave190515" #randm = [1] #alpha = ['a0'] #%% def perplexityAccumulate(res, y, sPrev, nby ,one_hot = False): s = 0 oneHot = [] if one_hot == True: for i in range(len(y)): oneHot.append(y[i].index(max(y[i]))) else: oneHot = y for r, t in zip(res,oneHot): s += np.log2(r[t]) sPrev += s nby += len(y) return sPrev, nby def perplexityCompute(s,y): s /= -y return 2 ** s #%% def perplexity(res, y, one_hot = False): s = 0 oneHot = [] if one_hot == True: for i in range(len(y)): oneHot.append(y[i].index(max(y[i]))) else: oneHot = y for r, t in zip(res,oneHot): s += np.log2(r[t]) s /= -len(y) return 2 ** s #%% for alph in alpha: for model in modelType: if model == "mlpDecimFamily": str1 = "124" else: str1 = "1" for maxReps in maxRepList: if maxReps == 1: alphaRep = "Nope" else: alphaRep = "alphaRep" #if maxReps == 1 or model == "mlpDecim" or model == "mlpDecimAug" or model == "lstmDecim": if maxReps == 1 or model == "mlpDecim" or model == "mlpDecimAug": print("\n------\n------\nResult for " + model + "on alphabet " + alph + "\n------\n------\n") perp = [] rank = [] totRank = [] #Analyzer = ACEAnalyzer() if alph != "functional": dictChord, listChord = chordUtil.getDictChord(eval(alph)) distMat = testFunc.computeMat(dictChord, "euclidian") #if alphaRep == "alphaRep": # dictChord, listChord = chordUtil.getDictChordUpgrade(eval(alph), maxReps) dictKeyChord = {} dictKeyChordAll = {} for key in dictKey: dictKeyChord[key] = np.zeros(len(listChord)) dictKeyChordAll[key] = np.zeros(len(listChord)) Analyzer = ACEAnalyzer() AnalyzerDiat = ACEAnalyzer() AnalyzerNoDiat = ACEAnalyzer() if alph == "a0": dictFun = relatif totAcc = [] totAccRepeat = [] totAccDiat = [] totAccNoDiat = [] totKey= [] totDownbeat = [] totAccFun = [] totAcca0 = [] totAccDiat = [] totAccNoDiat = [] totAccDownbeat = [] totAccPos = [] totAccBeatPos = [] totDist = [] predTotDist = [] totDistPred = [] totDist2a = [] totDist4a = [] totDist2b = [] totDist4b = [] totDist2c = [] totDist4c = [] nbCorrectChordDiat = 0 nbCorrectChordNoDiat = 0 nbTotalDiat = 0 nbTotalNoDiat = 0 for rand in randm: ''' sumPred2ab = np.zeros(len(listChord)) sumTarg2ab = np.zeros(len(listChord)) sumPred4ab = np.zeros(len(listChord)) sumTarg4ab = np.zeros(len(listChord)) sumPred2c = np.zeros(len(listChord)) sumTarg2c = np.zeros(len(listChord)) sumPred4c = np.zeros(len(listChord)) sumTarg4c = np.zeros(len(listChord)) ''' correctDown = [0]*4 correctPos = [0]*8 totalDown = [0]*4 totalPos = [0]*8 correctBeatPos = np.zeros((4,8)) totalBeatPos = np.zeros((4,8)) accBeatPos = np.zeros((4,8)) musicalDist = 0 predMusicalDist = 0 acc2correct = 0 acc4correct = 0 musicalDist2a = 0 musicalDist4a = 0 musicalDist2b = 0 musicalDist4b = 0 musicalDist2c = 0 musicalDist4c = 0 #zerr = np.zeros(len(dictChord)) total = 0 totalRepeat = 0 totalDiat = 0 totalNoDiat = 0 acc = 0 accRepeat = 0 accDiat = 0 accNoDiat = 0 correct = 0 correctDiat = 0 correctNoDiat = 0 keycorrect = 0 downbeatcorrect = 0 correctReducFunc = 0 correctReduca0 = 0 #dataFolder = alph + "_1_" + str(rand) if alphaRep == "alphaRep": dataFolder = alph + "_1_" + str(rand) + "newRep" + str(maxReps) else: dataFolder = alph + "_124_" + str(rand) #modelName = dataFolder + "_" + str1 + "_" + model + specName if modelType == "mlpDecimFamily": modelName = dataFolder + "_124_" + model + specName else: modelName = dataFolder + "_" + str1 + "_" + model + specName #with open("testVector/" + foldName + '/' + modelName + '/' + "probVect_" + modelName + "_test.pkl", 'rb') as fp: with open(foldName + '/' + modelName + '/' + "res" + modelName + ".pkl", 'rb') as fp: dictDat = pickle.load(fp) #dictDat["X"] = dictDat["X"].cpu().numpy() #dictDat["y"] = dictDat["y"].cpu().numpy() totKey.append(dictDat["bestAccurKeyTest"]) totAccDownbeat.append(dictDat["bestAccurBeatTest"]) ''' if alph != "functional": #musicalDist = np.sum(np.matmul(dictDat["X"], distMat) * dictDat["y"]) musicalDist = 0 for i in range(len(dictDat["X"])): pred = np.argmax(dictDat["X"][i]) tgt = np.argmax(dictDat["y"][i]) # rank of the chords rank.append(len(np.where(dictDat["X"][i] > dictDat["X"][i][tgt])[0]) + 1) total += 1 totalDown[dictDat["beat"][i]] += 1 totalPos[dictDat["pos"][i]] += 1 totalBeatPos[dictDat["beat"][i],dictDat["pos"][i]] += 1 # Accuracy: if pred == tgt: correct += 1 correctDown[dictDat["beat"][i]] += 1 correctPos[dictDat["pos"][i]] += 1 correctBeatPos[dictDat["beat"][i],dictDat["pos"][i]] += 1 #if alphaRep != "alphaRep": # predMusicalDist += distMat[pred][tgt] if alph != "functional": predF = dictFun[reduChord(listChord[pred], alpha= 'a0', transp = 0)] tgtF = dictFun[reduChord(listChord[tgt], alpha= 'a0', transp = 0)] if predF == tgtF: correctReducFunc +=1 if alph != "functional" and alph != "a0": preda0 = reduChord(listChord[pred], alpha= 'a0', transp = 0) tgta0 = reduChord(listChord[tgt], alpha= 'a0', transp = 0) if preda0 == tgta0: correctReduca0 +=1 if alph != "functional": Analyzer.compare(chord = listChord[pred], target = listChord[tgt], key = listKey[dictDat["key"][i]], base_alpha = a5, print_comparison = False) root_target, qual_target = parse_mir_label(listChord[tgt]) root_target = normalized_note(root_target) root_target, qual_target = functional_tetrad(root_target, qual_target, listKey[dictDat["key"][i]], base_alpha = a5) degree_target = degree(root_target, qual_target, listKey[dictDat["key"][i]]) if degree_target == "non-diatonic": nbTotalNoDiat += 1 AnalyzerNoDiat.compare(chord = listChord[pred], target = listChord[tgt], key = listKey[dictDat["key"][i]], base_alpha = a5, print_comparison = False) totalNoDiat += 1 dictKeyChordAll[listKey[dictDat["key"][i]]][tgt] += 1 if pred == tgt: correctNoDiat += 1 # histogramm for each key on non diatonic target dictKeyChord[listKey[dictDat["key"][i]]][tgt] += 1 nbCorrectChordNoDiat += 1 else: AnalyzerDiat.compare(chord = listChord[pred], target = listChord[tgt], key = listKey[dictDat["key"][i]], base_alpha = a5, print_comparison = False) totalDiat += 1 nbTotalDiat += 1 if pred == tgt: correctDiat += 1 nbCorrectChordDiat += 1 if model == "mlpDecimAug" or model == "mlpDecimAugUp": if dictDat["key"][i] == dictDat["keyPred"][i]: keycorrect += 1 if dictDat["beat"][i] == dictDat["beatPred"][i]: downbeatcorrect += 1 #sPrev, nby = perplexityAccumulate(dictDat["X"].tolist(), dictDat["y"].tolist(), sPrev, nby, True) perp.append(perplexity(dictDat["X"].tolist(), dictDat["y"].tolist(), True)) totRank.append(np.mean(rank)) rank = [] acc = correct/total keyacc = keycorrect/total downbeatacc = downbeatcorrect/total if alph != "functional": accDiat = correctDiat/totalDiat accNoDiat = correctNoDiat/totalNoDiat accDownbeat = [int(b) / int(m) for b,m in zip(correctDown, totalDown)] accPos = [int(b) / int(m) for b,m in zip(correctPos, totalPos)] for i in range(len(totalBeatPos)): accBeatPos[i] = [int(b) / int(m) for b,m in zip(correctBeatPos[i], totalBeatPos[i])] totAcc.append(acc) totAccDiat.append(accDiat) totAccNoDiat.append(accNoDiat) totKey.append(keyacc) totDownbeat.append(downbeatacc) if alph != "functional": accFun = correctReducFunc/total totAccFun.append(accFun) if alph != "functional": acca0 = correctReduca0/total totAcca0.append(acca0) ''' ''' totAcc2.append(acc2) totAcc4.append(acc4) totAccDownbeat.append(accDownbeat) totAccPos.append(accPos) totAccBeatPos.append(accBeatPos) ''' ''' if alph != "functional": totDist.append(musicalDist/total) predTotDist.append(predMusicalDist/total) ''' #Pinting time ! #perp = perplexityCompute(sPrev, nby) """ f = open("histo_output/" + model + "_" + alph + "_" + str(maxReps) + "histoChord.txt","w") for key, value in dictKeyChord.items(): f.write("Histogramme on key : " + key + "\n") for nBchord in range(len(value)): f.write(listChord[nBchord] + ' = ' + str(value[nBchord])+ "\n") f.write("\n\n") f.close() f = open("histo_output/" + model + "_" + alph + "_" + str(maxReps) + "histoChordAll.txt","w") for key, value in dictKeyChordAll.items(): f.write("Histogramme on key : " + key + "\n") for nBchord in range(len(value)): f.write(listChord[nBchord] + ' = ' + str(value[nBchord])+ "\n") f.write("\n\n") f.close() f = open("histo_output/" + model + "_" + alph + "_" + str(maxReps) + "histoChordRatio.txt","w") for key, value in dictKeyChordAll.items(): f.write("Histogramme on key : " + key + "\n") for nBchord in range(len(value)): if value[nBchord] != 0: f.write(listChord[nBchord] + ' = ' + str(dictKeyChord[key][nBchord]/value[nBchord])+ "\n") f.write("\n\n") f.close() #save as pickle f = open("histo_output/" + model + "_" + alph + "_" + str(maxReps) + "histoChord.pkl","wb") pickle.dump(dictKeyChord,f) f.close() #save as pickle f = open("histo_output/" + model + "_" + alph + "_" + str(maxReps) + "histoChordAll.pkl","wb") pickle.dump(dictKeyChordAll,f) f.close() print("nbCorrectChordDiat :" + str(nbCorrectChordDiat)) print("nbCorrectChordNoDiat :" + str(nbCorrectChordNoDiat)) print("nbTotalDiat :" + str(nbTotalDiat)) print("nbTotalNoDiat :" + str(nbTotalNoDiat)) print("rank for " + model + " on alphabet " + alph + ": " + str(np.mean(totRank))) print("perp for " + model + " on alphabet " + alph + ": " + str(np.mean(perp))) print("acc for " + model + " on alphabet " + alph + ": " + str(np.mean(totAcc))) print("accDiat for " + model + " on alphabet " + alph + ": " + str(np.mean(totAccDiat))) print("accNoDiat for " + model + " on alphabet " + alph + ": " + str(np.mean(totAccNoDiat))) if alph != "functional": print("accFun for " + model + " on alphabet " + alph + ": " + str(np.mean(totAccFun))) if alph != "functional" and alph != "a0": print("acca0 for " + model + " on alphabet " + alph + ": " + str(np.mean(totAcca0))) print("rank_std for " + model + " on alphabet " + alph + ": " + str(np.std(totRank))) print("perp_std for " + model + " on alphabet " + alph + ": " + str(np.std(perp))) print("acc_std for " + model + " on alphabet " + alph + ": " + str(np.std(totAcc))) print("accDiat_std for " + model + " on alphabet " + alph + ": " + str(np.std(totAccDiat))) print("accNoDiat_std for " + model + " on alphabet " + alph + ": " + str(np.std(totAccNoDiat))) if alph != "functional": print("accFun_std for " + model + " on alphabet " + alph + ": " + str(np.std(totAccFun))) if alph != "functional" and alph != "a0": print("acca0_std for " + model + " on alphabet " + alph + ": " + str(np.std(totAcca0))) #print("acc2 for " + model + " on alphabet " + alph + ": " + str(np.mean(totAcc2))) #print("acc4 for " + model + " on alphabet " + alph + ": " + str(np.mean(totAcc4))) print("accDownbeat for " + model + " on alphabet " + alph + ": " + str(np.average(totAccDownbeat,axis=0))) print("accPos for " + model + " on alphabet " + alph + ": " + str(np.average(totAccPos,axis=0))) print("accBeatPos for " + model + " on alphabet " + alph + ": " + str(np.average(totAccBeatPos, axis = 0))) """ ''' if alph != "functional": print("Average Musical Distance for " + model + " on alphabet " + alph + ": " + str(np.mean(totDist))) print("Average Prediction Musical Distance for " + model + " on alphabet " + alph + ": " + str(np.mean(predTotDist))) if model == "mlpDecimAug" or model == "mlpDecimAugUp": print("accKey for " + model + " on alphabet " + alph + ": " + str(np.mean(totKey))) print("accBeat for " + model + " on alphabet " + alph + ": " + str(np.mean(totDownbeat))) print("accKey_std for " + model + " on alphabet " + alph + ": " + str(np.std(totKey))) print("accBeat_std for " + model + " on alphabet " + alph + ": " + str(np.std(totDownbeat))) ''' dictModel = {} dictCurrent = {} #basic info #dictModel["numParam"] = dictDat["numParam"] #dictModel["alpha"] = dictDat["alpha"] #dictModel["modelType"] = dictDat["modelType"] dictModel["key"] = np.mean(totKey) dictModel["key_std"] = np.std(totKey) dictModel["beat"] = np.mean(totDownbeat) dictModel["beat_std"] = np.std(totDownbeat) print("accKey for " + model + " on alphabet " + alph + ": " + str(np.mean(totKey))) print("accBeat for " + model + " on alphabet " + alph + ": " + str(np.mean(totDownbeat))) print("accKey_std for " + model + " on alphabet " + alph + ": " + str(np.std(totKey))) print("accBeat_std for " + model + " on alphabet " + alph + ": " + str(np.std(totDownbeat))) ''' dictModel["perp"] = np.mean(perp) dictModel["acc"] = np.mean(totAcc) dictModel["rank_std"] = np.std(totRank) dictModel["perp_std"] = np.std(perp) dictModel["acc_std"] = np.std(totAcc) #diat info dictModel["accDiat"] = np.mean(totAccDiat) dictModel["accNoDiat"] = np.mean(totAccNoDiat) dictModel["accDiat_std"] = np.std(totAccDiat) dictModel["accNoDiat_std"] = np.std(totAccNoDiat) #reductionInfo if alph != "functional": dictModel["accFun"] = np.mean(totAccFun) dictModel["accFun_std"] = np.std(totAccFun) if alph != "functional" and alph != "a0": dictModel["acca0"] = np.mean(totAcca0) dictModel["acca0_std"] = np.std(totAcca0) #position info dictModel["accDownbeat"] = np.average(totAccDownbeat,axis=0) dictModel["accPos"] = np.average(totAccPos,axis=0) dictModel["accBeatPos"] = np.average(totAccBeatPos, axis = 0) #Key beat info if model == "mlpDecimAug" or model == "mlpDecimAugUp": dictModel["accKey"] = np.mean(totKey) dictModel["accBeat"] = np.mean(totDownbeat) dictModel["accKey_std"] = np.std(totKey) dictModel["accBeat_std"] = np.std(totDownbeat) if alph != "functional": dictModel["MusicalDist"] = np.mean(totDist) dictModel["PredMusicalDist"] = np.mean(predTotDist) dictACE_stats = {} dictACE_degs = {} for anal, anal_name in zip([Analyzer, AnalyzerDiat, AnalyzerNoDiat],['all chords', 'diatonic target', 'non-diatonic target']): dictACE_stats_cur = {} dictACE_degs_cur = {} print("\n------\nSTATS for chord present in :" + anal_name+ "\n------") StatsErrorsSubstitutions = anal.stats_errors_substitutions(stats_on_errors_only = True) print("\nSTATS ERROR SUBSTITUTIONS:\n------") print("Errors explained by substitutions rules: {}% of total errors\n------".format(round(anal.total_errors_explained_by_substitutions*100.0/anal.total_errors,2))) print("DETAIL ERRORS EXPLAINED BY SUBSTITUTION RULES:") for error_type, stat in StatsErrorsSubstitutions.items(): #if stat*100 &gt; 1: dictACE_stats_cur[error_type] = stat if stat*100 > 1: print("{}: {}%".format(error_type, round(100*stat, 2))) # print(Analyzer.total_errors_degrees) # print(Analyzer.total_errors_when_non_diatonic_target) # print(Analyzer.total_non_diatonic_target) # print(Analyzer.degrees_analysis) StatsErrorsDegrees = anal.stats_errors_degrees(stats_on_errors_only = True) print("\nSTATS ERROR DEGREES:\n------") if anal_name != "diatonic target": print("Errors when the target is not diatonic: {}% ".format(round(anal.total_errors_when_non_diatonic_target*100.0/anal.total_non_diatonic_target,2))) print("Non diatonic target in {}% of the total errors".format(round(anal.total_errors_when_non_diatonic_target*100.0/anal.total_errors,2))) print("When relevant: incorrect degrees (modulo inclusions): {}% of total errors\n------".format(round(anal.total_errors_degrees*100.0/anal.total_errors,2))) print("DETAIL ERRORS OF DEGREES (modulo inclusions) WHEN THE TARGET IS DIATONIC:") for error_type, stat in StatsErrorsDegrees.items(): #if stat*100 &gt; 1: dictACE_degs_cur[error_type] = stat if stat*100 > 1: print("{}: {}%".format(error_type, round(100*stat,2))) dictACE_stats[anal_name] = dictACE_stats_cur dictACE_degs[anal_name] = dictACE_degs_cur #dictModel["MusicalDist2a"] = np.mean(totDist2a) #dictModel["MusicalDist4a"] = np.mean(totDist4a) #dictModel["MusicalDist2b"] = np.mean(totDist2b) #dictModel["MusicalDist4b"] = np.mean(totDist4b) #dictModel["MusicalDist2c"] = np.mean(totDist2c) #dictModel["MusicalDist4c"] = np.mean(totDist4c) #dictFinalRes[model + "_" + alph] = dictModel dictCurrent["res"] = dictModel dictCurrent["stats"] = dictACE_stats dictCurrent["degs"] = dictACE_degs dictFinalRes[model + "_" + alph + "_" + str(maxReps)] = dictCurrent print("\n\n") ''' dictCurrent["res"] = dictModel dictFinalRes[model + "_" + alph + "_" + str(maxReps)] = dictCurrent #dictFinalRes = dictFinalRes.cpu() sauv = open(foldName + "_DictFinaltest_keyBeat.pkl","wb") pickle.dump(dictFinalRes,sauv) sauv.close() print("analyses completed") #%%
[ "pickle.dump", "utilities.chordUtil.getDictKey", "utilities.testFunc.computeMat", "numpy.std", "numpy.log2", "numpy.zeros", "ACE_Analyzer.ACEAnalyzer", "numpy.mean", "torch.cuda.is_available", "pickle.load" ]
[((928, 950), 'utilities.chordUtil.getDictKey', 'chordUtil.getDictKey', ([], {}), '()\n', (948, 950), False, 'from utilities import chordUtil\n'), ((25321, 25352), 'pickle.dump', 'pickle.dump', (['dictFinalRes', 'sauv'], {}), '(dictFinalRes, sauv)\n', (25332, 25352), False, 'import pickle\n'), ((514, 539), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (537, 539), False, 'import torch\n'), ((1456, 1469), 'numpy.log2', 'np.log2', (['r[t]'], {}), '(r[t])\n', (1463, 1469), True, 'import numpy as np\n'), ((1837, 1850), 'numpy.log2', 'np.log2', (['r[t]'], {}), '(r[t])\n', (1844, 1850), True, 'import numpy as np\n'), ((19146, 19161), 'numpy.mean', 'np.mean', (['totKey'], {}), '(totKey)\n', (19153, 19161), True, 'import numpy as np\n'), ((19201, 19215), 'numpy.std', 'np.std', (['totKey'], {}), '(totKey)\n', (19207, 19215), True, 'import numpy as np\n'), ((19252, 19272), 'numpy.mean', 'np.mean', (['totDownbeat'], {}), '(totDownbeat)\n', (19259, 19272), True, 'import numpy as np\n'), ((19313, 19332), 'numpy.std', 'np.std', (['totDownbeat'], {}), '(totDownbeat)\n', (19319, 19332), True, 'import numpy as np\n'), ((2774, 2817), 'utilities.testFunc.computeMat', 'testFunc.computeMat', (['dictChord', '"""euclidian"""'], {}), "(dictChord, 'euclidian')\n", (2793, 2817), False, 'from utilities import testFunc\n'), ((3256, 3269), 'ACE_Analyzer.ACEAnalyzer', 'ACEAnalyzer', ([], {}), '()\n', (3267, 3269), False, 'from ACE_Analyzer import ACEAnalyzer\n'), ((3305, 3318), 'ACE_Analyzer.ACEAnalyzer', 'ACEAnalyzer', ([], {}), '()\n', (3316, 3318), False, 'from ACE_Analyzer import ACEAnalyzer\n'), ((3356, 3369), 'ACE_Analyzer.ACEAnalyzer', 'ACEAnalyzer', ([], {}), '()\n', (3367, 3369), False, 'from ACE_Analyzer import ACEAnalyzer\n'), ((5074, 5090), 'numpy.zeros', 'np.zeros', (['(4, 8)'], {}), '((4, 8))\n', (5082, 5090), True, 'import numpy as np\n'), ((5125, 5141), 'numpy.zeros', 'np.zeros', (['(4, 8)'], {}), '((4, 8))\n', (5133, 5141), True, 'import numpy as np\n'), ((5174, 5190), 'numpy.zeros', 'np.zeros', (['(4, 8)'], {}), '((4, 8))\n', (5182, 5190), True, 'import numpy as np\n'), ((7078, 7093), 'pickle.load', 'pickle.load', (['fp'], {}), '(fp)\n', (7089, 7093), False, 'import pickle\n'), ((19415, 19430), 'numpy.mean', 'np.mean', (['totKey'], {}), '(totKey)\n', (19422, 19430), True, 'import numpy as np\n'), ((19516, 19536), 'numpy.mean', 'np.mean', (['totDownbeat'], {}), '(totDownbeat)\n', (19523, 19536), True, 'import numpy as np\n'), ((19625, 19639), 'numpy.std', 'np.std', (['totKey'], {}), '(totKey)\n', (19631, 19639), True, 'import numpy as np\n'), ((19729, 19748), 'numpy.std', 'np.std', (['totDownbeat'], {}), '(totDownbeat)\n', (19735, 19748), True, 'import numpy as np\n')]
# test_yolov3.py # Basic script to test YOLOv3 model. # # Reference: https://machinelearningmastery.com/how-to-perform-object-detection-with-yolov3-in-keras/ from yolo3_one_file_to_detect_them_all import * import numpy as np from keras.models import load_model from keras.preprocessing.image import load_img, img_to_array import matplotlib.pyplot as plt from matplotlib.patches import Rectangle import pdb WEIGHTS = 'yolov3.weights' FILENAME = 'data/zebra.jpg' LABELS = ["person", "bicycle", "car", "motorbike", "aeroplane", "bus", "train", "truck", "boat", "traffic light", "fire hydrant", "stop sign", "parking meter", "bench", "bird", "cat", "dog", "horse", "sheep", "cow", "elephant", "bear", "zebra", "giraffe", "backpack", "umbrella", "handbag", "tie", "suitcase", "frisbee", "skis", "snowboard", "sports ball", "kite", "baseball bat", "baseball glove", "skateboard", "surfboard", "tennis racket", "bottle", "wine glass", "cup", "fork", "knife", "spoon", "bowl", "banana", "apple", "sandwich", "orange", "broccoli", "carrot", "hot dog", "pizza", "donut", "cake", "chair", "sofa", "pottedplant", "bed", "diningtable", "toilet", "tvmonitor", "laptop", "mouse", "remote", "keyboard", "cell phone", "microwave", "oven", "toaster", "sink", "refrigerator", "book", "clock", "vase", "scissors", "teddy bear", "hair drier", "toothbrush"] def main(): # Make YOLOv3 model, load weights, and save model = make_yolov3_model() weight_reader = WeightReader(WEIGHTS) weight_reader.load_weights(model) model.save('model.h5') # Load and use model on test image model = load_model('model.h5') wid, hei = 416, 416 # define expected input shape of the model img, w, h = load_image_pixels(FILENAME, (wid, hei)) pred = model.predict(img) print([a.shape for a in pred]) # Interpret results anchors = [[116, 90, 156, 198, 373, 326], [30, 61, 62, 45, 59, 119], [10, 13, 16, 30, 33, 23]] thold = 0.6 # confidence of class in the range [0,1] boxes = [] for i in range(len(pred)): boxes += decode_netout(pred[i][0], anchors[i], thold, hei, wid) correct_yolo_boxes(boxes, h, w, hei, wid) do_nms(boxes, 0.5) v_boxes, v_labels, v_scores = getboxes(boxes, LABELS, thold) for i in range(len(v_boxes)): print(v_labels[i], v_scores[i]) # Draw bounding box on image drawboxes(FILENAME, v_boxes, v_labels, v_scores) # plt.waitforbuttonpress() def load_image_pixels(filename, shape): '''Load and prepare an image for YOLOv3.''' img = load_img(filename) width, height = img.size # get actual size of image img = load_img(filename, target_size=shape) # load image with target size img = img_to_array(img) # convert to numpy array img = img.astype('float32') # scale pixel values to [0, 1] img /= 255.0 img = np.expand_dims(img, 0) # add a dimension so that we have one sample return img, width, height def getboxes(boxes, labels, thresh): '''Get all of the bounding boxes above a threshold.''' v_boxes, v_labels, v_scores = [], [], [] # enumerate all boxes for box in boxes: # enumerate all possible labels for i in range(len(labels)): # check if the threshold for this label is high enough if box.classes[i] > thresh: v_boxes.append(box) v_labels.append(labels[i]) v_scores.append(box.classes[i]*100) # don't break, many labels may trigger for one box return v_boxes, v_labels, v_scores def drawboxes(filename, v_boxes, v_labels, v_scores): '''Draw boxes with labels and scores on image from file.''' img = plt.imread(filename) plt.imshow(img) ax = plt.gca() for i in range(len(v_boxes)): box = v_boxes[i] y1, x1, y2, x2 = box.ymin, box.xmin, box.ymax, box.xmax width, height = x2 - x1, y2 - y1 rect = Rectangle((x1, y1), width, height, fill=False, color='white') ax.add_patch(rect) label = "%s (%.3f)" % (v_labels[i], v_scores[i]) plt.text(x1, y1, label, color='white') plt.axis('off') plt.show() if __name__ == "__main__": main()
[ "keras.models.load_model", "matplotlib.pyplot.show", "matplotlib.patches.Rectangle", "matplotlib.pyplot.imshow", "numpy.expand_dims", "matplotlib.pyplot.axis", "matplotlib.pyplot.text", "keras.preprocessing.image.img_to_array", "keras.preprocessing.image.load_img", "matplotlib.pyplot.gca", "matplotlib.pyplot.imread" ]
[((1628, 1650), 'keras.models.load_model', 'load_model', (['"""model.h5"""'], {}), "('model.h5')\n", (1638, 1650), False, 'from keras.models import load_model\n'), ((2566, 2584), 'keras.preprocessing.image.load_img', 'load_img', (['filename'], {}), '(filename)\n', (2574, 2584), False, 'from keras.preprocessing.image import load_img, img_to_array\n'), ((2652, 2689), 'keras.preprocessing.image.load_img', 'load_img', (['filename'], {'target_size': 'shape'}), '(filename, target_size=shape)\n', (2660, 2689), False, 'from keras.preprocessing.image import load_img, img_to_array\n'), ((2731, 2748), 'keras.preprocessing.image.img_to_array', 'img_to_array', (['img'], {}), '(img)\n', (2743, 2748), False, 'from keras.preprocessing.image import load_img, img_to_array\n'), ((2866, 2888), 'numpy.expand_dims', 'np.expand_dims', (['img', '(0)'], {}), '(img, 0)\n', (2880, 2888), True, 'import numpy as np\n'), ((3710, 3730), 'matplotlib.pyplot.imread', 'plt.imread', (['filename'], {}), '(filename)\n', (3720, 3730), True, 'import matplotlib.pyplot as plt\n'), ((3735, 3750), 'matplotlib.pyplot.imshow', 'plt.imshow', (['img'], {}), '(img)\n', (3745, 3750), True, 'import matplotlib.pyplot as plt\n'), ((3760, 3769), 'matplotlib.pyplot.gca', 'plt.gca', ([], {}), '()\n', (3767, 3769), True, 'import matplotlib.pyplot as plt\n'), ((4146, 4161), 'matplotlib.pyplot.axis', 'plt.axis', (['"""off"""'], {}), "('off')\n", (4154, 4161), True, 'import matplotlib.pyplot as plt\n'), ((4166, 4176), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (4174, 4176), True, 'import matplotlib.pyplot as plt\n'), ((3949, 4010), 'matplotlib.patches.Rectangle', 'Rectangle', (['(x1, y1)', 'width', 'height'], {'fill': '(False)', 'color': '"""white"""'}), "((x1, y1), width, height, fill=False, color='white')\n", (3958, 4010), False, 'from matplotlib.patches import Rectangle\n'), ((4103, 4141), 'matplotlib.pyplot.text', 'plt.text', (['x1', 'y1', 'label'], {'color': '"""white"""'}), "(x1, y1, label, color='white')\n", (4111, 4141), True, 'import matplotlib.pyplot as plt\n')]
# Lint as: python3 #!/usr/bin/env python # Copyright 2021 The CARFAC Authors. All Rights Reserved. # # This file is part of an implementation of Lyon's cochlear model: # "Cascade of Asymmetric Resonators with Fast-Acting Compression" # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests for carfac.tf.pz.""" from typing import Callable import unittest from absl import app import numpy as np import tensorflow as tf from . import pz class CoeffTest(unittest.TestCase): def testCoeffs(self): # We have a filter H, with poles P and zeros Q: # H = g * np.prod(Q - z) / np.prod(P - z) # Assuming Q = [1, 2, 3, 4, 5]: # H = g * (1 - z) * (2 - z) * (3 - z) * (4 - z) * (5 - z) / np.prod(P - z) # = Y / X # Y = X * g * (1 - z) * (2 - z) * (3 - z) * (4 - z) * (5 - z) / # np.prod(P - z) # Y = X * g * (z^-1 - 1) * (2 * z^-1 - 1) * (3 * z^-1 - 1) * (4 * z^-1 - 1) # * (5 * z^-1 - 1) / (np.prod(P - z) * z^-5) # Y * np.prod(P - z) * z^-5 = X * (z^-1 - 1) * (2 * z^-1 - 1) * # (3 * z^-1 - 1) * (4 * z^-1 - 1) * (5 * z^-1 - 1) # Y * np.prod(P - z) * z^-5 = X * (-1 + 15 * z^-1 - 85 * z^-2 + 225 * z^-3 # - 274 * z^-4 + 120 * z^-5) # Where (-1 + 15 * z^-1 - 85 * z^-2 + 225 * z^-3 - 274 * z^-4 + 120 * z^-5) # = -(qc0 + qc1 * z^-1 + qc2 * z^-2 + qc3 * z^-3 + qc4 * z^-4 + qc5 * # z^-5) # And coeffs_from_zeros returns [qc0, qc1, qc2, qc3, qc4, qc5] => # [1, -15, 85, -225, 274, -120] inputs: tf.Tensor = tf.constant([1, 2, 3, 4, 5], dtype=tf.complex128) outputs: tf.Tensor = pz.coeffs_from_zeros(inputs) expected_outputs = [1, -15, 85, -225, 274, -120] np.testing.assert_array_almost_equal(outputs, expected_outputs) class PZTest(unittest.TestCase): def assert_impulse_response(self, filt: Callable[[tf.Tensor], tf.Tensor], dtype: tf.DType, gain: tf.Tensor, poles: tf.Tensor, zeros: tf.Tensor): window_size = 64 impulse: np.ndarray = np.zeros([window_size], dtype=np.float32) impulse[0] = 1 impulse_spectrum: np.ndarray = np.fft.fft(impulse) z: np.ndarray = np.exp(np.linspace(0, 2 * np.pi, window_size, endpoint=False) * 1j) transfer_function: np.ndarray = ( tf.cast(gain, tf.complex128) * np.prod(zeros[None, :] - z[:, None], axis=1) / np.prod(poles[None, :] - z[:, None], axis=1)) expected_impulse_response: np.ndarray = np.fft.ifft( impulse_spectrum * transfer_function) # Since the filter requires batch and cell i/o dimensions. impulse_response = filt(tf.cast(impulse[None, :, None], dtype))[0, :, 0] np.testing.assert_array_almost_equal(impulse_response, expected_impulse_response) def testPZCell(self): for dtype in [tf.float32, tf.float64]: poles: np.ndarray = 0.5 * np.exp([np.pi * 0.5j]) poles: tf.Tensor = tf.concat([poles, tf.math.conj(poles)], axis=0) zeros: np.ndarray = 0.75 * np.exp([np.pi * 0.25j]) zeros: tf.Tensor = tf.concat([zeros, tf.math.conj(zeros)], axis=0) gain: tf.Tensor = tf.constant(1.5) pz_cell = pz.PZCell(gain, poles, zeros, dtype=dtype) pz_layer = tf.keras.layers.RNN(pz_cell, return_sequences=True, dtype=dtype) self.assert_impulse_response(pz_layer, dtype, gain, poles, zeros) def testTFFunction(self): for dtype in [tf.float32, tf.float64]: poles: np.ndarray = 0.1 * np.exp(np.pi * np.array([0.7j])) poles: tf.Tensor = tf.concat([poles, tf.math.conj(poles)], axis=0) zeros: np.ndarray = 0.75 * np.exp(np.pi * np.array([0.25j])) zeros: tf.Tensor = tf.concat([zeros, tf.math.conj(zeros)], axis=0) gain: tf.Tensor = tf.constant(2.4) pz_cell = pz.PZCell(gain, poles, zeros, dtype=dtype) pz_layer = tf.keras.layers.RNN(pz_cell, return_sequences=True, dtype=dtype) @tf.function def compute(inputs): # pylint: disable=cell-var-from-loop return pz_layer(inputs) self.assert_impulse_response(compute, dtype, gain, poles, zeros) def testGradients(self): tape = tf.GradientTape(persistent=True) pz_cell = pz.PZCell(1, 0.5 * np.exp([np.pi * 0.2j, np.pi * 0.5j]), 0.3 * np.exp([np.pi * 0.6j])) with tape: current: tf.Tensor = tf.ones([2, 1], dtype=pz_cell.dtype) state = tuple(tf.zeros(shape=[current.shape[0], size], dtype=pz_cell.dtype) for size in pz_cell.state_size) for _ in range(6): current, state = pz_cell.call(current, state) for v in [pz_cell.poles, pz_cell.zeros, pz_cell.gain]: self.assertTrue(np.isfinite(tape.gradient(current, v)).all()) def main(_): unittest.main() if __name__ == '__main__': app.run(main)
[ "unittest.main", "numpy.fft.ifft", "tensorflow.ones", "tensorflow.math.conj", "numpy.fft.fft", "tensorflow.keras.layers.RNN", "numpy.zeros", "tensorflow.constant", "tensorflow.cast", "absl.app.run", "tensorflow.zeros", "numpy.exp", "numpy.linspace", "numpy.array", "numpy.testing.assert_array_almost_equal", "tensorflow.GradientTape", "numpy.prod" ]
[((5852, 5867), 'unittest.main', 'unittest.main', ([], {}), '()\n', (5865, 5867), False, 'import unittest\n'), ((5898, 5911), 'absl.app.run', 'app.run', (['main'], {}), '(main)\n', (5905, 5911), False, 'from absl import app\n'), ((1992, 2041), 'tensorflow.constant', 'tf.constant', (['[1, 2, 3, 4, 5]'], {'dtype': 'tf.complex128'}), '([1, 2, 3, 4, 5], dtype=tf.complex128)\n', (2003, 2041), True, 'import tensorflow as tf\n'), ((2153, 2216), 'numpy.testing.assert_array_almost_equal', 'np.testing.assert_array_almost_equal', (['outputs', 'expected_outputs'], {}), '(outputs, expected_outputs)\n', (2189, 2216), True, 'import numpy as np\n'), ((2642, 2683), 'numpy.zeros', 'np.zeros', (['[window_size]'], {'dtype': 'np.float32'}), '([window_size], dtype=np.float32)\n', (2650, 2683), True, 'import numpy as np\n'), ((2738, 2757), 'numpy.fft.fft', 'np.fft.fft', (['impulse'], {}), '(impulse)\n', (2748, 2757), True, 'import numpy as np\n'), ((3227, 3276), 'numpy.fft.ifft', 'np.fft.ifft', (['(impulse_spectrum * transfer_function)'], {}), '(impulse_spectrum * transfer_function)\n', (3238, 3276), True, 'import numpy as np\n'), ((3432, 3517), 'numpy.testing.assert_array_almost_equal', 'np.testing.assert_array_almost_equal', (['impulse_response', 'expected_impulse_response'], {}), '(impulse_response,\n expected_impulse_response)\n', (3468, 3517), True, 'import numpy as np\n'), ((5205, 5237), 'tensorflow.GradientTape', 'tf.GradientTape', ([], {'persistent': '(True)'}), '(persistent=True)\n', (5220, 5237), True, 'import tensorflow as tf\n'), ((3120, 3164), 'numpy.prod', 'np.prod', (['(poles[None, :] - z[:, None])'], {'axis': '(1)'}), '(poles[None, :] - z[:, None], axis=1)\n', (3127, 3164), True, 'import numpy as np\n'), ((3905, 3921), 'tensorflow.constant', 'tf.constant', (['(1.5)'], {}), '(1.5)\n', (3916, 3921), True, 'import tensorflow as tf\n'), ((4076, 4140), 'tensorflow.keras.layers.RNN', 'tf.keras.layers.RNN', (['pz_cell'], {'return_sequences': '(True)', 'dtype': 'dtype'}), '(pz_cell, return_sequences=True, dtype=dtype)\n', (4095, 4140), True, 'import tensorflow as tf\n'), ((4661, 4677), 'tensorflow.constant', 'tf.constant', (['(2.4)'], {}), '(2.4)\n', (4672, 4677), True, 'import tensorflow as tf\n'), ((4832, 4896), 'tensorflow.keras.layers.RNN', 'tf.keras.layers.RNN', (['pz_cell'], {'return_sequences': '(True)', 'dtype': 'dtype'}), '(pz_cell, return_sequences=True, dtype=dtype)\n', (4851, 4896), True, 'import tensorflow as tf\n'), ((5429, 5465), 'tensorflow.ones', 'tf.ones', (['[2, 1]'], {'dtype': 'pz_cell.dtype'}), '([2, 1], dtype=pz_cell.dtype)\n', (5436, 5465), True, 'import tensorflow as tf\n'), ((2786, 2840), 'numpy.linspace', 'np.linspace', (['(0)', '(2 * np.pi)', 'window_size'], {'endpoint': '(False)'}), '(0, 2 * np.pi, window_size, endpoint=False)\n', (2797, 2840), True, 'import numpy as np\n'), ((3010, 3038), 'tensorflow.cast', 'tf.cast', (['gain', 'tf.complex128'], {}), '(gain, tf.complex128)\n', (3017, 3038), True, 'import tensorflow as tf\n'), ((3049, 3093), 'numpy.prod', 'np.prod', (['(zeros[None, :] - z[:, None])'], {'axis': '(1)'}), '(zeros[None, :] - z[:, None], axis=1)\n', (3056, 3093), True, 'import numpy as np\n'), ((3378, 3416), 'tensorflow.cast', 'tf.cast', (['impulse[None, :, None]', 'dtype'], {}), '(impulse[None, :, None], dtype)\n', (3385, 3416), True, 'import tensorflow as tf\n'), ((3655, 3677), 'numpy.exp', 'np.exp', (['[np.pi * 0.5j]'], {}), '([np.pi * 0.5j])\n', (3661, 3677), True, 'import numpy as np\n'), ((3784, 3807), 'numpy.exp', 'np.exp', (['[np.pi * 0.25j]'], {}), '([np.pi * 0.25j])\n', (3790, 3807), True, 'import numpy as np\n'), ((5295, 5331), 'numpy.exp', 'np.exp', (['[np.pi * 0.2j, np.pi * 0.5j]'], {}), '([np.pi * 0.2j, np.pi * 0.5j])\n', (5301, 5331), True, 'import numpy as np\n'), ((5363, 5385), 'numpy.exp', 'np.exp', (['[np.pi * 0.6j]'], {}), '([np.pi * 0.6j])\n', (5369, 5385), True, 'import numpy as np\n'), ((3721, 3740), 'tensorflow.math.conj', 'tf.math.conj', (['poles'], {}), '(poles)\n', (3733, 3740), True, 'import tensorflow as tf\n'), ((3851, 3870), 'tensorflow.math.conj', 'tf.math.conj', (['zeros'], {}), '(zeros)\n', (3863, 3870), True, 'import tensorflow as tf\n'), ((4467, 4486), 'tensorflow.math.conj', 'tf.math.conj', (['poles'], {}), '(poles)\n', (4479, 4486), True, 'import tensorflow as tf\n'), ((4607, 4626), 'tensorflow.math.conj', 'tf.math.conj', (['zeros'], {}), '(zeros)\n', (4619, 4626), True, 'import tensorflow as tf\n'), ((5486, 5547), 'tensorflow.zeros', 'tf.zeros', ([], {'shape': '[current.shape[0], size]', 'dtype': 'pz_cell.dtype'}), '(shape=[current.shape[0], size], dtype=pz_cell.dtype)\n', (5494, 5547), True, 'import tensorflow as tf\n'), ((4406, 4422), 'numpy.array', 'np.array', (['[0.7j]'], {}), '([0.7j])\n', (4414, 4422), True, 'import numpy as np\n'), ((4545, 4562), 'numpy.array', 'np.array', (['[0.25j]'], {}), '([0.25j])\n', (4553, 4562), True, 'import numpy as np\n')]
from .memory import Memory import collections import random import numpy as np eps = 1e-10 class PrioMemory(Memory): def __init__(self, model, memory_size=65536): self.model = model self.memory_size = memory_size self.memory = collections.OrderedDict() self.max_prio = 1.0 self.shape = None pass def remember(self, S, a, r, Snext, game_over): if self.shape is None: self.shape = S.shape entry = (S.tobytes(),a,r,Snext.tobytes(),game_over) if entry not in self.memory: self.memory[entry] = self.max_prio if self.memory_size is not None and len(self.memory) > self.memory_size: self.memory.popitem(last=False) def get_batch(self, batch_size, zeta=0.6, beta=0.4): entries = list(self.memory.keys()) probs = list(self.memory.values()) prob = np.array(probs) ** zeta prob = prob / np.sum(prob) chosen_idx = np.random.choice(len(self.memory), p=prob, size=batch_size, replace=False) chosen_entries = [entries[idx] for idx in chosen_idx] batch = [(np.frombuffer(S).reshape(self.shape),a,r,np.frombuffer(Sn).reshape(self.shape),game_over) for S,a,r,Sn,game_over in chosen_entries] n = len(self.memory) weights = np.array([(n*probs[idx]) ** (-beta) for idx in chosen_idx]) return batch, weights def update(self, gamma, batch): S,a,r,Sn,go = zip(*batch) preds = self.model.predict(np.array(S+Sn)) half = int(len(preds)/2) for i in range(len(batch)): v, vn = preds[i][a[i]], np.argmax(preds[i+half]) if go[i]: new_prio = abs(r[i] - v) + eps else: new_prio = abs(r[i] + gamma*(vn) - v) + eps entry = (S[i].tobytes(),a[i],r[i],Sn[i].tobytes(),go[i]) self.memory[entry] = new_prio def reset(self): self.memory = collections.OrderedDict()
[ "numpy.sum", "numpy.argmax", "numpy.frombuffer", "numpy.array", "collections.OrderedDict" ]
[((258, 283), 'collections.OrderedDict', 'collections.OrderedDict', ([], {}), '()\n', (281, 283), False, 'import collections\n'), ((1312, 1373), 'numpy.array', 'np.array', (['[((n * probs[idx]) ** -beta) for idx in chosen_idx]'], {}), '([((n * probs[idx]) ** -beta) for idx in chosen_idx])\n', (1320, 1373), True, 'import numpy as np\n'), ((1956, 1981), 'collections.OrderedDict', 'collections.OrderedDict', ([], {}), '()\n', (1979, 1981), False, 'import collections\n'), ((896, 911), 'numpy.array', 'np.array', (['probs'], {}), '(probs)\n', (904, 911), True, 'import numpy as np\n'), ((942, 954), 'numpy.sum', 'np.sum', (['prob'], {}), '(prob)\n', (948, 954), True, 'import numpy as np\n'), ((1508, 1524), 'numpy.array', 'np.array', (['(S + Sn)'], {}), '(S + Sn)\n', (1516, 1524), True, 'import numpy as np\n'), ((1629, 1655), 'numpy.argmax', 'np.argmax', (['preds[i + half]'], {}), '(preds[i + half])\n', (1638, 1655), True, 'import numpy as np\n'), ((1132, 1148), 'numpy.frombuffer', 'np.frombuffer', (['S'], {}), '(S)\n', (1145, 1148), True, 'import numpy as np\n'), ((1173, 1190), 'numpy.frombuffer', 'np.frombuffer', (['Sn'], {}), '(Sn)\n', (1186, 1190), True, 'import numpy as np\n')]
import numpy import chainer from chainer import functions from chainer_pointnet.models.conv_block import ConvBlock from chainer_pointnet.utils.grouping import query_ball_by_diff from chainer_pointnet.utils.sampling import farthest_point_sampling class SetAbstractionModule(chainer.Chain): def __init__(self, k, num_sample_in_region, radius, mlp, mlp2=None, in_channels=None, use_bn=True, activation=functions.relu, initial_idx=None, skip_initial=True, return_distance=False, residual=False): # k is number of sampled point (num_region) super(SetAbstractionModule, self).__init__() # Feature Extractor channel list assert isinstance(mlp, list) fe_ch_list = [in_channels] + mlp # Head channel list if mlp2 is None: mlp2 = [] assert isinstance(mlp2, list) head_ch_list = [mlp[-1]] + mlp2 with self.init_scope(): self.sampling_grouping = SamplingGroupingModule( k=k, num_sample_in_region=num_sample_in_region, radius=radius, initial_idx=initial_idx, skip_initial=skip_initial, return_distance=return_distance) self.feature_extractor_list = chainer.ChainList( *[ConvBlock(fe_ch_list[i], fe_ch_list[i+1], ksize=1, use_bn=use_bn, activation=activation, residual=residual ) for i in range(len(mlp))]) self.head_list = chainer.ChainList( *[ConvBlock(head_ch_list[i], head_ch_list[i + 1], ksize=1, use_bn=use_bn, activation=activation, residual=residual ) for i in range(len(mlp2))]) self.use_bn = use_bn def __call__(self, coord_points, feature_points=None): # coord_points (batch_size, num_point, coord_dim) # feature_points (batch_size, num_point, ch) # num_point, ch: coord_dim # grouped_points (batch_size, k, num_sample, channel) # center_points (batch_size, k, coord_dim) grouped_points, center_points, dist = self.sampling_grouping( coord_points, feature_points=feature_points) # set alias `h` -> (bs, channel, num_sample, k) # Note: transpose may be removed by optimizing shape sequence for sampling_groupoing h = functions.transpose(grouped_points, (0, 3, 2, 1)) # h (bs, ch, num_sample_in_region, k=num_group) for conv_block in self.feature_extractor_list: h = conv_block(h) # TODO: try other option of pooling function h = functions.max(h, axis=2, keepdims=True) # h (bs, ch, 1, k=num_group) for conv_block in self.head_list: h = conv_block(h) h = functions.transpose(h[:, :, 0, :], (0, 2, 1)) # points (bs, k, coord), h (bs, k, ch'), dist (bs, k, num_point) return center_points, h, dist def _to_array(var): """"Input: numpy, cupy array or Variable. Output: numpy or cupy array""" if isinstance(var, chainer.Variable): var = var.data return var #TODO: this does not have parameter, change it to function instead of chain. class SamplingGroupingModule(chainer.Chain): def __init__(self, k, num_sample_in_region, radius=None, use_coord=True, initial_idx=None, skip_initial=True, return_distance=False): super(SamplingGroupingModule, self).__init__() # number of center point (sampled point) self.k = k # number of points grouped in each region with radius self.radius = radius self.num_sample_in_region = num_sample_in_region self.use_coord = use_coord self.initial_idx = initial_idx self.skip_initial = skip_initial self.return_distance = return_distance def __call__(self, coord_points, feature_points=None): # input: coord_points (batch_size, num_point, coord_dim) # input: feature_points (batch_size, num_point, channel) batch_size, num_point, coord_dim = coord_points.shape # sampling -> this only decides indices, calculation is done by array farthest_indices, distances = farthest_point_sampling( _to_array(coord_points), self.k, initial_idx=self.initial_idx, skip_initial=self.skip_initial) # grouping grouped_indices = query_ball_by_diff( distances, self.num_sample_in_region, radius=self.radius) if not self.return_distance: distances = None # release memory # grouped_indices (batch_size, k, num_sample) # grouped_points (batch_size, k, num_sample, coord_dim) grouped_points = coord_points[self.xp.arange(batch_size)[:, None, None], grouped_indices, :] # center_points (batch_size, k, coord_dim) -> new_coord_points center_points = coord_points[self.xp.arange(batch_size)[:, None], farthest_indices, :] # calculate relative coordinate grouped_points = grouped_points - functions.broadcast_to( center_points[:, :, None, :], grouped_points.shape) if feature_points is None: new_feature_points = grouped_points else: # grouped_indices (batch_size, k, num_sample) # grouped_feature_points (batch_size, k, num_sample, channel) grouped_feature_points = feature_points[ self.xp.arange(batch_size)[:, None, None], grouped_indices, :] if self.use_coord: new_feature_points = functions.concat([grouped_points, grouped_feature_points], axis=3) else: new_feature_points = grouped_feature_points # new_feature_points (batch_size, k, num_sample, channel') # center_points (batch_size, k, coord_dim) -> new_coord_points # distances (batch_size, k, num_point) it is for feature_propagation return new_feature_points, center_points, distances if __name__ == '__main__': batch_size = 3 num_point = 100 coord_dim = 2 k = 5 num_sample_in_region = 8 radius = 0.4 mlp = [16, 16] # mlp2 = [32, 32] mlp2 = None device = -1 print('num_point', num_point, 'device', device) if device == -1: pts = numpy.random.uniform(0, 1, (batch_size, num_point, coord_dim)) else: import cupy pts = cupy.random.uniform(0, 1, (batch_size, num_point, coord_dim)) pts = pts.astype(numpy.float32) sam = SetAbstractionModule(k, num_sample_in_region, radius, mlp, mlp2=mlp2) coord, h = sam(pts) print('coord', type(coord), coord.shape) # (3, 5, 2) - (bs, k, coord) print('h', type(h), h.shape) # (3, 5, 32) - (bs, k, ch')
[ "numpy.random.uniform", "chainer_pointnet.utils.grouping.query_ball_by_diff", "chainer_pointnet.models.conv_block.ConvBlock", "chainer.functions.concat", "chainer.functions.max", "chainer.functions.broadcast_to", "cupy.random.uniform", "chainer.functions.transpose" ]
[((2467, 2516), 'chainer.functions.transpose', 'functions.transpose', (['grouped_points', '(0, 3, 2, 1)'], {}), '(grouped_points, (0, 3, 2, 1))\n', (2486, 2516), False, 'from chainer import functions\n'), ((2723, 2762), 'chainer.functions.max', 'functions.max', (['h'], {'axis': '(2)', 'keepdims': '(True)'}), '(h, axis=2, keepdims=True)\n', (2736, 2762), False, 'from chainer import functions\n'), ((2884, 2929), 'chainer.functions.transpose', 'functions.transpose', (['h[:, :, 0, :]', '(0, 2, 1)'], {}), '(h[:, :, 0, :], (0, 2, 1))\n', (2903, 2929), False, 'from chainer import functions\n'), ((4492, 4568), 'chainer_pointnet.utils.grouping.query_ball_by_diff', 'query_ball_by_diff', (['distances', 'self.num_sample_in_region'], {'radius': 'self.radius'}), '(distances, self.num_sample_in_region, radius=self.radius)\n', (4510, 4568), False, 'from chainer_pointnet.utils.grouping import query_ball_by_diff\n'), ((6435, 6497), 'numpy.random.uniform', 'numpy.random.uniform', (['(0)', '(1)', '(batch_size, num_point, coord_dim)'], {}), '(0, 1, (batch_size, num_point, coord_dim))\n', (6455, 6497), False, 'import numpy\n'), ((6542, 6603), 'cupy.random.uniform', 'cupy.random.uniform', (['(0)', '(1)', '(batch_size, num_point, coord_dim)'], {}), '(0, 1, (batch_size, num_point, coord_dim))\n', (6561, 6603), False, 'import cupy\n'), ((5135, 5209), 'chainer.functions.broadcast_to', 'functions.broadcast_to', (['center_points[:, :, None, :]', 'grouped_points.shape'], {}), '(center_points[:, :, None, :], grouped_points.shape)\n', (5157, 5209), False, 'from chainer import functions\n'), ((5711, 5777), 'chainer.functions.concat', 'functions.concat', (['[grouped_points, grouped_feature_points]'], {'axis': '(3)'}), '([grouped_points, grouped_feature_points], axis=3)\n', (5727, 5777), False, 'from chainer import functions\n'), ((1314, 1427), 'chainer_pointnet.models.conv_block.ConvBlock', 'ConvBlock', (['fe_ch_list[i]', 'fe_ch_list[i + 1]'], {'ksize': '(1)', 'use_bn': 'use_bn', 'activation': 'activation', 'residual': 'residual'}), '(fe_ch_list[i], fe_ch_list[i + 1], ksize=1, use_bn=use_bn,\n activation=activation, residual=residual)\n', (1323, 1427), False, 'from chainer_pointnet.models.conv_block import ConvBlock\n'), ((1600, 1717), 'chainer_pointnet.models.conv_block.ConvBlock', 'ConvBlock', (['head_ch_list[i]', 'head_ch_list[i + 1]'], {'ksize': '(1)', 'use_bn': 'use_bn', 'activation': 'activation', 'residual': 'residual'}), '(head_ch_list[i], head_ch_list[i + 1], ksize=1, use_bn=use_bn,\n activation=activation, residual=residual)\n', (1609, 1717), False, 'from chainer_pointnet.models.conv_block import ConvBlock\n')]
import numpy as np import ScanMatchPy import matlab import brainscore import brainio_collection from brainscore.benchmarks import Benchmark, ceil_score from brainscore.model_interface import BrainModel from brainscore.metrics import Score from brainscore.utils import fullname import logging from tqdm import tqdm class _KlabZhang2018ObjSearch(Benchmark): def __init__(self, ceil_score=None, assembly_name=None, identifier_suffix=""): self.human_score = Score([ceil_score, np.nan], coords={'aggregation': ['center', 'error']}, dims=['aggregation']) self._version = 1 self._identifier='klab.Zhang2018.ObjSearch-' + identifier_suffix self.parent='visual_search', self.paper_link='https://doi.org/10.1038/s41467-018-06217-x' self._assemblies = brainscore.get_assembly(assembly_name) self._stimuli = self._assemblies.stimulus_set self.fix = [[640, 512], [365, 988], [90, 512], [365, 36], [915, 36], [1190, 512], [915, 988]] self.max_fix = 6 self.data_len = 300 self._logger = logging.getLogger(fullname(self)) def __call__(self, candidate: BrainModel): self._metric = ScanMatchPy.initialize() self._logger.info("## Starting visual search task...") candidate.start_task(BrainModel.Task.object_search, fix=self.fix, max_fix=self.max_fix, data_len=self.data_len) self.cumm_perf, self.saccades = candidate.look_at(self._stimuli) # in saccades the first 7 index are the saccades whereas the last index denotes the index at which the target was found fix_model = self.saccades[:,:7,:] # first 7 saccades I_fix_model = self.saccades[:,7,:1] # index at which the target was found fix1 = matlab.int32(fix_model.tolist()) I_fix1 = matlab.int32(I_fix_model.tolist()) self._logger.info("## Search task done...\n") self._logger.info("## Calculating score...") scores = [] for sub_id in tqdm(range(15), desc="comparing with human data: "): data_human = self._assemblies.values[sub_id*self.data_len:(sub_id+1)*self.data_len] fix_human = data_human[:,:7,:] I_fix_human = data_human[:,7,:1] fix2 = matlab.int32(fix_human.tolist()) I_fix2 = matlab.int32(I_fix_human.tolist()) score = self._metric.findScore(fix1, fix2, I_fix1, I_fix2) scores.append(score) scores = np.asarray(scores) self.raw_score = np.mean(scores) self.std = np.std(scores)/np.sqrt(scores.shape[0]) self.model_score = Score([self.raw_score, self.std], coords={'aggregation': ['center', 'error']}, dims=['aggregation']) self._metric.terminate() ceiled_score = ceil_score(self.model_score, self.ceiling) self._logger.info("## Score calculated...\n") return ceiled_score @property def identifier(self): return self._identifier @property def version(self): return self._version @property def ceiling(self): return self.human_score def get_raw_data(self): return self.cumm_perf, self.saccades def KlabZhang2018ObjSearchObjArr(): return _KlabZhang2018ObjSearch(ceil_score=0.4411, assembly_name='klab.Zhang2018search_obj_array', identifier_suffix='objarr') class _KlabZhang2018VisualSearch(Benchmark): def __init__(self, ceil_score=None, assembly_name=None, identifier_suffix=""): self._logger = logging.getLogger(fullname(self)) self.human_score = Score([ceil_score, np.nan], coords={'aggregation': ['center', 'error']}, dims=['aggregation']) self._version = 1 self._identifier='klab.Zhang2018.VisualSearch-' + identifier_suffix self.parent = 'visual_search' self.paper_link='https://doi.org/10.1038/s41467-018-06217-x' self._assemblies = brainscore.get_assembly(assembly_name) self._stimuli = self._assemblies.stimulus_set self.max_fix = self._assemblies.fixation.values.shape[0] - 2 self.num_sub = np.max(self._assemblies.subjects.values) self.data_len = int(self._assemblies.presentation.values.shape[0]/self.num_sub) self.ior_size = 100 def __call__(self, candidate: BrainModel): self._metric = ScanMatchPy.initialize() self._logger.info("## Starting visual search task...") candidate.start_task(BrainModel.Task.visual_search, max_fix=self.max_fix, data_len=self.data_len, ior_size=self.ior_size) self.cumm_perf, self.saccades = candidate.look_at(self._stimuli) # in saccades the last index denotes the index at which the target was found fix_model = self.saccades[:,:self.max_fix+1,:] # first n saccades I_fix_model = self.saccades[:,self.max_fix+1,:1] # index at which the target was found fix1 = matlab.int32(fix_model.tolist()) I_fix1 = matlab.int32(I_fix_model.tolist()) self._logger.info("## Search task done...\n") self._logger.info("## Calculating score...") scores = [] for sub_id in tqdm(range(self.num_sub), desc="comparing with human data: "): data_human = self._assemblies.values[sub_id*self.data_len:(sub_id+1)*self.data_len] fix_human = data_human[:,:self.max_fix+1,:] I_fix_human = data_human[:,self.max_fix+1,:1] fix2 = matlab.int32(fix_human.tolist()) I_fix2 = matlab.int32(I_fix_human.tolist()) score = self._metric.findScore(fix1, fix2, I_fix1, I_fix2) scores.append(score) scores = np.asarray(scores) self.raw_score = np.mean(scores) self.std = np.std(scores)/np.sqrt(scores.shape[0]) self.model_score = Score([self.raw_score, self.std], coords={'aggregation': ['center', 'error']}, dims=['aggregation']) self._metric.terminate() ceiled_score = ceil_score(self.model_score, self.ceiling) self._logger.info("## Score calculated...\n") return ceiled_score @property def identifier(self): return self._identifier @property def version(self): return self._version @property def ceiling(self): return self.human_score def get_raw_data(self): return self.cumm_perf, self.saccades def KlabZhang2018VisualSearchWaldo(): return _KlabZhang2018VisualSearch(ceil_score=0.3519, assembly_name='klab.Zhang2018search_waldo', identifier_suffix="waldo") def KlabZhang2018VisualSearchNaturaldesign(): return _KlabZhang2018VisualSearch(ceil_score=0.3953, assembly_name='klab.Zhang2018search_naturaldesign', identifier_suffix="naturaldesign")
[ "brainscore.benchmarks.ceil_score", "numpy.std", "numpy.asarray", "ScanMatchPy.initialize", "brainscore.utils.fullname", "numpy.max", "numpy.mean", "brainscore.get_assembly", "brainscore.metrics.Score", "numpy.sqrt" ]
[((468, 566), 'brainscore.metrics.Score', 'Score', (['[ceil_score, np.nan]'], {'coords': "{'aggregation': ['center', 'error']}", 'dims': "['aggregation']"}), "([ceil_score, np.nan], coords={'aggregation': ['center', 'error']},\n dims=['aggregation'])\n", (473, 566), False, 'from brainscore.metrics import Score\n'), ((819, 857), 'brainscore.get_assembly', 'brainscore.get_assembly', (['assembly_name'], {}), '(assembly_name)\n', (842, 857), False, 'import brainscore\n'), ((1321, 1345), 'ScanMatchPy.initialize', 'ScanMatchPy.initialize', ([], {}), '()\n', (1343, 1345), False, 'import ScanMatchPy\n'), ((2592, 2610), 'numpy.asarray', 'np.asarray', (['scores'], {}), '(scores)\n', (2602, 2610), True, 'import numpy as np\n'), ((2637, 2652), 'numpy.mean', 'np.mean', (['scores'], {}), '(scores)\n', (2644, 2652), True, 'import numpy as np\n'), ((2740, 2845), 'brainscore.metrics.Score', 'Score', (['[self.raw_score, self.std]'], {'coords': "{'aggregation': ['center', 'error']}", 'dims': "['aggregation']"}), "([self.raw_score, self.std], coords={'aggregation': ['center', 'error'\n ]}, dims=['aggregation'])\n", (2745, 2845), False, 'from brainscore.metrics import Score\n'), ((2923, 2965), 'brainscore.benchmarks.ceil_score', 'ceil_score', (['self.model_score', 'self.ceiling'], {}), '(self.model_score, self.ceiling)\n', (2933, 2965), False, 'from brainscore.benchmarks import Benchmark, ceil_score\n'), ((3718, 3816), 'brainscore.metrics.Score', 'Score', (['[ceil_score, np.nan]'], {'coords': "{'aggregation': ['center', 'error']}", 'dims': "['aggregation']"}), "([ceil_score, np.nan], coords={'aggregation': ['center', 'error']},\n dims=['aggregation'])\n", (3723, 3816), False, 'from brainscore.metrics import Score\n'), ((4073, 4111), 'brainscore.get_assembly', 'brainscore.get_assembly', (['assembly_name'], {}), '(assembly_name)\n', (4096, 4111), False, 'import brainscore\n'), ((4259, 4299), 'numpy.max', 'np.max', (['self._assemblies.subjects.values'], {}), '(self._assemblies.subjects.values)\n', (4265, 4299), True, 'import numpy as np\n'), ((4487, 4511), 'ScanMatchPy.initialize', 'ScanMatchPy.initialize', ([], {}), '()\n', (4509, 4511), False, 'import ScanMatchPy\n'), ((5787, 5805), 'numpy.asarray', 'np.asarray', (['scores'], {}), '(scores)\n', (5797, 5805), True, 'import numpy as np\n'), ((5832, 5847), 'numpy.mean', 'np.mean', (['scores'], {}), '(scores)\n', (5839, 5847), True, 'import numpy as np\n'), ((5935, 6040), 'brainscore.metrics.Score', 'Score', (['[self.raw_score, self.std]'], {'coords': "{'aggregation': ['center', 'error']}", 'dims': "['aggregation']"}), "([self.raw_score, self.std], coords={'aggregation': ['center', 'error'\n ]}, dims=['aggregation'])\n", (5940, 6040), False, 'from brainscore.metrics import Score\n'), ((6118, 6160), 'brainscore.benchmarks.ceil_score', 'ceil_score', (['self.model_score', 'self.ceiling'], {}), '(self.model_score, self.ceiling)\n', (6128, 6160), False, 'from brainscore.benchmarks import Benchmark, ceil_score\n'), ((1234, 1248), 'brainscore.utils.fullname', 'fullname', (['self'], {}), '(self)\n', (1242, 1248), False, 'from brainscore.utils import fullname\n'), ((2672, 2686), 'numpy.std', 'np.std', (['scores'], {}), '(scores)\n', (2678, 2686), True, 'import numpy as np\n'), ((2687, 2711), 'numpy.sqrt', 'np.sqrt', (['scores.shape[0]'], {}), '(scores.shape[0])\n', (2694, 2711), True, 'import numpy as np\n'), ((3674, 3688), 'brainscore.utils.fullname', 'fullname', (['self'], {}), '(self)\n', (3682, 3688), False, 'from brainscore.utils import fullname\n'), ((5867, 5881), 'numpy.std', 'np.std', (['scores'], {}), '(scores)\n', (5873, 5881), True, 'import numpy as np\n'), ((5882, 5906), 'numpy.sqrt', 'np.sqrt', (['scores.shape[0]'], {}), '(scores.shape[0])\n', (5889, 5906), True, 'import numpy as np\n')]
import csv import cv2 import numpy as np lines = [] with open('/opt/carnd_p3/data/driving_log.csv') as csvfile: reader = csv.reader(csvfile) firstLineRead = False for line in reader: if not firstLineRead: firstLineRead = True else: lines.append(line) images = [] measurements = [] correction = 0.2 steering_correction=[0.0, correction, -correction] for line in lines: for i in range(3): source_path = line[i] filename=source_path.split('/')[-1] #print(filename) current_path = '/opt/carnd_p3/data/IMG/' + filename image = cv2.imread(current_path) images.append(image) images.append(cv2.flip(image,1)) measurement = float(line[3])+steering_correction[i] measurements.append(measurement) measurements.append(measurement*-1.0) x_train = np.array(images) y_train = np.array(measurements) from keras.models import Sequential from keras.layers import Flatten, Dense, Lambda, Convolution2D, Cropping2D, Dropout model = Sequential() model.add(Lambda(lambda x: x / 255.0 - 0.5, input_shape = (160,320,3))) model.add(Cropping2D(cropping=((70,0),(0,0)))) from keras.applications.inception_v3 import InceptionV3 from keras.callbacks import EarlyStopping, ModelCheckpoint model.add(InceptionV3(weights='imagenet', include_top=False, pooling=max)) model.add(Dropout(0.5)) model.add(Flatten()) model.add(Dense(1)) model.summary() model.compile(loss = 'mse' , optimizer = 'adam') es = EarlyStopping(monitor='val_loss', mode='min', verbose=1) mc = ModelCheckpoint('model.h5', monitor='val_loss', mode='min', verbose=1, save_best_only=True) history_object=model.fit(x_train, y_train, validation_split=0.2, shuffle = True, batch_size=128, epochs = 10, callbacks=[es, mc]) #model.fit(x_train, y_train, epochs = 7) model.save('model.h5') ### print the keys contained in the history object print(history_object.history.keys()) import matplotlib.pyplot as plt ### plot the training and validation loss for each epoch plt.plot(history_object.history['loss']) plt.plot(history_object.history['val_loss']) plt.title('model mean squared error loss') plt.ylabel('mean squared error loss') plt.xlabel('epoch') plt.legend(['training set', 'validation set'], loc='upper right') plt.show()
[ "matplotlib.pyplot.title", "csv.reader", "keras.layers.Cropping2D", "keras.layers.Flatten", "matplotlib.pyplot.show", "keras.callbacks.ModelCheckpoint", "keras.layers.Dropout", "matplotlib.pyplot.legend", "keras.applications.inception_v3.InceptionV3", "matplotlib.pyplot.ylabel", "cv2.flip", "matplotlib.pyplot.plot", "cv2.imread", "keras.callbacks.EarlyStopping", "numpy.array", "keras.layers.Lambda", "keras.layers.Dense", "keras.models.Sequential", "matplotlib.pyplot.xlabel" ]
[((881, 897), 'numpy.array', 'np.array', (['images'], {}), '(images)\n', (889, 897), True, 'import numpy as np\n'), ((908, 930), 'numpy.array', 'np.array', (['measurements'], {}), '(measurements)\n', (916, 930), True, 'import numpy as np\n'), ((1061, 1073), 'keras.models.Sequential', 'Sequential', ([], {}), '()\n', (1071, 1073), False, 'from keras.models import Sequential\n'), ((1520, 1576), 'keras.callbacks.EarlyStopping', 'EarlyStopping', ([], {'monitor': '"""val_loss"""', 'mode': '"""min"""', 'verbose': '(1)'}), "(monitor='val_loss', mode='min', verbose=1)\n", (1533, 1576), False, 'from keras.callbacks import EarlyStopping, ModelCheckpoint\n'), ((1582, 1677), 'keras.callbacks.ModelCheckpoint', 'ModelCheckpoint', (['"""model.h5"""'], {'monitor': '"""val_loss"""', 'mode': '"""min"""', 'verbose': '(1)', 'save_best_only': '(True)'}), "('model.h5', monitor='val_loss', mode='min', verbose=1,\n save_best_only=True)\n", (1597, 1677), False, 'from keras.callbacks import EarlyStopping, ModelCheckpoint\n'), ((2046, 2086), 'matplotlib.pyplot.plot', 'plt.plot', (["history_object.history['loss']"], {}), "(history_object.history['loss'])\n", (2054, 2086), True, 'import matplotlib.pyplot as plt\n'), ((2087, 2131), 'matplotlib.pyplot.plot', 'plt.plot', (["history_object.history['val_loss']"], {}), "(history_object.history['val_loss'])\n", (2095, 2131), True, 'import matplotlib.pyplot as plt\n'), ((2132, 2174), 'matplotlib.pyplot.title', 'plt.title', (['"""model mean squared error loss"""'], {}), "('model mean squared error loss')\n", (2141, 2174), True, 'import matplotlib.pyplot as plt\n'), ((2175, 2212), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""mean squared error loss"""'], {}), "('mean squared error loss')\n", (2185, 2212), True, 'import matplotlib.pyplot as plt\n'), ((2213, 2232), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""epoch"""'], {}), "('epoch')\n", (2223, 2232), True, 'import matplotlib.pyplot as plt\n'), ((2233, 2298), 'matplotlib.pyplot.legend', 'plt.legend', (["['training set', 'validation set']"], {'loc': '"""upper right"""'}), "(['training set', 'validation set'], loc='upper right')\n", (2243, 2298), True, 'import matplotlib.pyplot as plt\n'), ((2299, 2309), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (2307, 2309), True, 'import matplotlib.pyplot as plt\n'), ((126, 145), 'csv.reader', 'csv.reader', (['csvfile'], {}), '(csvfile)\n', (136, 145), False, 'import csv\n'), ((1084, 1144), 'keras.layers.Lambda', 'Lambda', (['(lambda x: x / 255.0 - 0.5)'], {'input_shape': '(160, 320, 3)'}), '(lambda x: x / 255.0 - 0.5, input_shape=(160, 320, 3))\n', (1090, 1144), False, 'from keras.layers import Flatten, Dense, Lambda, Convolution2D, Cropping2D, Dropout\n'), ((1156, 1194), 'keras.layers.Cropping2D', 'Cropping2D', ([], {'cropping': '((70, 0), (0, 0))'}), '(cropping=((70, 0), (0, 0)))\n', (1166, 1194), False, 'from keras.layers import Flatten, Dense, Lambda, Convolution2D, Cropping2D, Dropout\n'), ((1319, 1382), 'keras.applications.inception_v3.InceptionV3', 'InceptionV3', ([], {'weights': '"""imagenet"""', 'include_top': '(False)', 'pooling': 'max'}), "(weights='imagenet', include_top=False, pooling=max)\n", (1330, 1382), False, 'from keras.applications.inception_v3 import InceptionV3\n'), ((1394, 1406), 'keras.layers.Dropout', 'Dropout', (['(0.5)'], {}), '(0.5)\n', (1401, 1406), False, 'from keras.layers import Flatten, Dense, Lambda, Convolution2D, Cropping2D, Dropout\n'), ((1418, 1427), 'keras.layers.Flatten', 'Flatten', ([], {}), '()\n', (1425, 1427), False, 'from keras.layers import Flatten, Dense, Lambda, Convolution2D, Cropping2D, Dropout\n'), ((1439, 1447), 'keras.layers.Dense', 'Dense', (['(1)'], {}), '(1)\n', (1444, 1447), False, 'from keras.layers import Flatten, Dense, Lambda, Convolution2D, Cropping2D, Dropout\n'), ((628, 652), 'cv2.imread', 'cv2.imread', (['current_path'], {}), '(current_path)\n', (638, 652), False, 'import cv2\n'), ((704, 722), 'cv2.flip', 'cv2.flip', (['image', '(1)'], {}), '(image, 1)\n', (712, 722), False, 'import cv2\n')]