code
stringlengths
31
1.05M
apis
list
extract_api
stringlengths
97
1.91M
#importing import pandas as pd import os import numpy as np import seaborn as sns import matplotlib.pyplot as plt import argparse import csv ## parsing arguments parser = argparse.ArgumentParser() parser.add_argument("-n", "--nbins", type=int, help="The number of bins to divide each gene into") parser.add_argument("-i", "--infile", help="Input file containing SNV data") parser.add_argument("-s", "--sample", help="The name of the sample (will be applied to any output files)") parser.add_argument("-a", "--gtf", help="The reference file in modified gtf format") parser.add_argument("-o", "--outdir", help="The base directory for outputs") args = parser.parse_args() nbins = args.nbins sample = args.sample infile = args.infile gtf = args.gtf OUT_DIR = args.outdir if not nbins: nbin = 100 if not sample: print("No sample name given. Outputs will be prefixed with 'sample'.") sample = "sample" if not gtf: print("No annotation file given.") quit() if not infile: print("No input file given.") quit() if not OUT_DIR: OUT_DIR = "./" ## ## initializing variables chr_no = 14 ## change this based on your organism of interest total_hists = [] bin_sizes = [] def stack_genes(file, bin_no, ann_file): ## function that does the heavy lifting global total_hists global bin_sizes print("Working...") #import data, including only Region, Position, GeneID data = pd.read_csv(file, sep="\t", header=0, usecols=["Position", "GeneID"]) unique_genes, gene_freq = np.unique(data["GeneID"], return_counts=True) gene_freq_dict = dict(zip(unique_genes, gene_freq)) a = data.groupby("GeneID") b = a["Position"].apply(lambda s: s.tolist()) pos_dict = b.to_dict() #print(pos_dict) nc_list = list(map(int, pos_dict["-"])) print(len(nc_list)) ## import reference data gtf_data = pd.read_csv(ann_file, sep=",", header=0) num_genes = len(np.unique(gtf_data["GeneID"])) avg_length = np.average(gtf_data["Length"]) c = gtf_data.groupby("GeneID") ref_dict = gtf_data.set_index("GeneID").T.to_dict("list") #print(ref_dict) counta_5 = [] ## will contain hits 1kb from start -- putative 5' UTR counta_3 = [] ## will contain hits 1kb from end -- putative 3' UTR unannoated_nc_hits = [] ## will contain hits not annotated by a gene or a UTR lengths = [] histogram_dict = {} ## will contain gene, histogram pairs hist_over_all_genes = [] ## is a list of histogram arrays, one for each gene utr_dict = {} stack_dict = {x:(pos_dict[x], ref_dict[x]) for x in pos_dict if x in ref_dict} for gene, values in stack_dict.items(): snv_list, ref = values #snv_list = list(map(int, snv_list)) #ref = list(map(int, ref)) #print(ref) hist, bins = np.histogram(snv_list, bins = nbins, range = (ref[0], ref[1])) hist_as_list = hist.tolist() hist_over_all_genes.append(hist_as_list) lengths.append(ref[1]-ref[0]) histogram_dict.update({gene : hist_as_list}) for i in nc_list: if i in range(ref[0]-1000, ref[0]): counta_5.append(i) #nc_list.remove(i) elif i in range(ref[1], ref[1]+1000): counta_3.append(i) #nc_list.remove(i) else: unannoated_nc_hits.append(i) commonlist = [] for m in counta_5: if m in counta_3: commonlist.append(m) genes_processed_list = [] n = len(pos_dict) genes_processed_list.append(n) #print("counta_3", len(counta_3)) #print("counta_5", len(counta_5)) #print("unannotated", len(unannoated_nc_hits)) avg_length = np.average(lengths) bin_size = avg_length/nbins bin_sizes.append(bin_size) utr_dict.update({ "5'_UTR" : (len(counta_5)*bin_size/1000)}) utr_dict.update({ "3'_UTR" : (len(counta_3)*bin_size/1000)}) hist_df = pd.DataFrame.from_dict(data = histogram_dict, orient="index") hist_df.reset_index(inplace=True) #hist_df["Histogram"] = hist_df.values.to_list() names = [i for i in range(1,nbins+1)] names.insert(0, "GeneID") hist_df.columns = names #print(hist_df.head(5)) #hist_df.to_csv(sample+"_gene_histograms.txt", sep="\t", header = [i for i in range(1,nbins+1)], index=False) utr_labels = [k for k in utr_dict.keys()] utr_values = [v for v in utr_dict.values()] avg_hist = np.average(hist_over_all_genes, axis=0) avg_hist_list = avg_hist.tolist() bins = [j for j in range(1, len(avg_hist_list)+1)] plt.style.use("ggplot") plt.ylabel("Frequency per Bin") plt.xlabel("Bins") plt.xlim([-1,len(bins)]) plt.xticks(fontsize = 7, rotation = 90, ha="center", weight = 'bold') plt.semilogy(bins, avg_hist_list) plt.savefig(file+"_SNV_graph.jpg") plt.close() total_hists.append(avg_hist_list) stat_writer.writerow({"Chr": file, "#Unannotated Hits": len(nc_list), "#Genes Processed": n}) return() ## TMP_DIR = sample+"_tmp/" tmp_path = os.path.join(OUT_DIR, TMP_DIR) try: os.mkdir(tmp_path) except FileExistsError: pass ## split initial data file by chromosome number with open(infile) as datafile: data_reader = pd.read_csv(infile, sep= "\t", header = 0) for chr_no in range (1, chr_no+1): filename = data_reader[data_reader["Region"] == chr_no] if chr_no <= 9: filename.to_csv(tmp_path+sample+"chr"+str(0)+str(chr_no)+".txt", index = False, sep= '\t') else: filename.to_csv(tmp_path+sample+"chr"+str(chr_no)+".txt", index = False, sep= '\t') ## run stack_genes on the split files with open(OUT_DIR+sample+"stats_file.txt", "a", newline="") as stats: fields = ["Chr","#Unannotated Hits", "#Genes Processed"] stat_writer = csv.DictWriter(stats, fieldnames= fields, delimiter = "\t") stat_writer.writeheader() for chr_file in os.listdir(tmp_path): data_file = os.path.join(tmp_path,chr_file) stack_genes(data_file, nbins, gtf) avg_total_hist = np.average(total_hists, axis=0) avg_total_hist_list = avg_total_hist.tolist() bins = [i for i in range(1, (len(avg_total_hist)+1))] bins[0] = "TSS" bins[len(bins)-1] = "TTS" ## plotting plt.style.use("ggplot") plt.figure(figsize = (20, 7)) sns.barplot(x = bins, y = avg_total_hist_list, ci="sd", color="darkslateblue") plt.errorbar(x = [str(i) for i in bins], y = avg_total_hist_list, yerr = np.std(total_hists, axis=0), ecolor="darkorange", elinewidth=1.5) #plt.semilogy(bins, avg_total_hist_list, "-") plt.title("SNV Distribution on Averaged Gene Body"+" ("+sample+")") plt.ylabel("Frequency per Bin") plt.xlabel("Bins") plt.xlim([-1,len(bins)]) plt.xticks(fontsize = 8, rotation = 90, ha="center", weight = 'bold') plt.savefig(OUT_DIR+"/"+sample+"_SNV_graph.jpg") #plt.show() ## tabular record of plot data plot_data = dict(zip(bins, avg_total_hist_list)) plot_df = pd.DataFrame.from_dict(data = plot_data, orient="index") plot_df.reset_index(inplace=True) plot_df.columns = ["Bin", "Freq"] plot_df.to_csv(OUT_DIR+"/"+sample+"plot_data.txt", sep="\t", header = True, index = False) ## done, hopefully
[ "matplotlib.pyplot.title", "os.mkdir", "argparse.ArgumentParser", "pandas.read_csv", "matplotlib.pyplot.style.use", "matplotlib.pyplot.figure", "numpy.histogram", "os.path.join", "numpy.unique", "csv.DictWriter", "numpy.std", "matplotlib.pyplot.close", "matplotlib.pyplot.semilogy", "matplotlib.pyplot.xticks", "numpy.average", "pandas.DataFrame.from_dict", "seaborn.barplot", "matplotlib.pyplot.ylabel", "os.listdir", "matplotlib.pyplot.xlabel", "matplotlib.pyplot.savefig" ]
[((172, 197), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (195, 197), False, 'import argparse\n'), ((5090, 5120), 'os.path.join', 'os.path.join', (['OUT_DIR', 'TMP_DIR'], {}), '(OUT_DIR, TMP_DIR)\n', (5102, 5120), False, 'import os\n'), ((6074, 6105), 'numpy.average', 'np.average', (['total_hists'], {'axis': '(0)'}), '(total_hists, axis=0)\n', (6084, 6105), True, 'import numpy as np\n'), ((6262, 6285), 'matplotlib.pyplot.style.use', 'plt.style.use', (['"""ggplot"""'], {}), "('ggplot')\n", (6275, 6285), True, 'import matplotlib.pyplot as plt\n'), ((6286, 6313), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(20, 7)'}), '(figsize=(20, 7))\n', (6296, 6313), True, 'import matplotlib.pyplot as plt\n'), ((6316, 6390), 'seaborn.barplot', 'sns.barplot', ([], {'x': 'bins', 'y': 'avg_total_hist_list', 'ci': '"""sd"""', 'color': '"""darkslateblue"""'}), "(x=bins, y=avg_total_hist_list, ci='sd', color='darkslateblue')\n", (6327, 6390), True, 'import seaborn as sns\n'), ((6580, 6653), 'matplotlib.pyplot.title', 'plt.title', (["('SNV Distribution on Averaged Gene Body' + ' (' + sample + ')')"], {}), "('SNV Distribution on Averaged Gene Body' + ' (' + sample + ')')\n", (6589, 6653), True, 'import matplotlib.pyplot as plt\n'), ((6648, 6679), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Frequency per Bin"""'], {}), "('Frequency per Bin')\n", (6658, 6679), True, 'import matplotlib.pyplot as plt\n'), ((6680, 6698), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Bins"""'], {}), "('Bins')\n", (6690, 6698), True, 'import matplotlib.pyplot as plt\n'), ((6724, 6787), 'matplotlib.pyplot.xticks', 'plt.xticks', ([], {'fontsize': '(8)', 'rotation': '(90)', 'ha': '"""center"""', 'weight': '"""bold"""'}), "(fontsize=8, rotation=90, ha='center', weight='bold')\n", (6734, 6787), True, 'import matplotlib.pyplot as plt\n'), ((6794, 6848), 'matplotlib.pyplot.savefig', 'plt.savefig', (["(OUT_DIR + '/' + sample + '_SNV_graph.jpg')"], {}), "(OUT_DIR + '/' + sample + '_SNV_graph.jpg')\n", (6805, 6848), True, 'import matplotlib.pyplot as plt\n'), ((6946, 7000), 'pandas.DataFrame.from_dict', 'pd.DataFrame.from_dict', ([], {'data': 'plot_data', 'orient': '"""index"""'}), "(data=plot_data, orient='index')\n", (6968, 7000), True, 'import pandas as pd\n'), ((1409, 1478), 'pandas.read_csv', 'pd.read_csv', (['file'], {'sep': '"""\t"""', 'header': '(0)', 'usecols': "['Position', 'GeneID']"}), "(file, sep='\\t', header=0, usecols=['Position', 'GeneID'])\n", (1420, 1478), True, 'import pandas as pd\n'), ((1509, 1554), 'numpy.unique', 'np.unique', (["data['GeneID']"], {'return_counts': '(True)'}), "(data['GeneID'], return_counts=True)\n", (1518, 1554), True, 'import numpy as np\n'), ((1854, 1894), 'pandas.read_csv', 'pd.read_csv', (['ann_file'], {'sep': '""","""', 'header': '(0)'}), "(ann_file, sep=',', header=0)\n", (1865, 1894), True, 'import pandas as pd\n'), ((1963, 1993), 'numpy.average', 'np.average', (["gtf_data['Length']"], {}), "(gtf_data['Length'])\n", (1973, 1993), True, 'import numpy as np\n'), ((3743, 3762), 'numpy.average', 'np.average', (['lengths'], {}), '(lengths)\n', (3753, 3762), True, 'import numpy as np\n'), ((3970, 4029), 'pandas.DataFrame.from_dict', 'pd.DataFrame.from_dict', ([], {'data': 'histogram_dict', 'orient': '"""index"""'}), "(data=histogram_dict, orient='index')\n", (3992, 4029), True, 'import pandas as pd\n'), ((4477, 4516), 'numpy.average', 'np.average', (['hist_over_all_genes'], {'axis': '(0)'}), '(hist_over_all_genes, axis=0)\n', (4487, 4516), True, 'import numpy as np\n'), ((4619, 4642), 'matplotlib.pyplot.style.use', 'plt.style.use', (['"""ggplot"""'], {}), "('ggplot')\n", (4632, 4642), True, 'import matplotlib.pyplot as plt\n'), ((4647, 4678), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Frequency per Bin"""'], {}), "('Frequency per Bin')\n", (4657, 4678), True, 'import matplotlib.pyplot as plt\n'), ((4683, 4701), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Bins"""'], {}), "('Bins')\n", (4693, 4701), True, 'import matplotlib.pyplot as plt\n'), ((4735, 4798), 'matplotlib.pyplot.xticks', 'plt.xticks', ([], {'fontsize': '(7)', 'rotation': '(90)', 'ha': '"""center"""', 'weight': '"""bold"""'}), "(fontsize=7, rotation=90, ha='center', weight='bold')\n", (4745, 4798), True, 'import matplotlib.pyplot as plt\n'), ((4809, 4842), 'matplotlib.pyplot.semilogy', 'plt.semilogy', (['bins', 'avg_hist_list'], {}), '(bins, avg_hist_list)\n', (4821, 4842), True, 'import matplotlib.pyplot as plt\n'), ((4847, 4883), 'matplotlib.pyplot.savefig', 'plt.savefig', (["(file + '_SNV_graph.jpg')"], {}), "(file + '_SNV_graph.jpg')\n", (4858, 4883), True, 'import matplotlib.pyplot as plt\n'), ((4886, 4897), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (4895, 4897), True, 'import matplotlib.pyplot as plt\n'), ((5130, 5148), 'os.mkdir', 'os.mkdir', (['tmp_path'], {}), '(tmp_path)\n', (5138, 5148), False, 'import os\n'), ((5280, 5319), 'pandas.read_csv', 'pd.read_csv', (['infile'], {'sep': '"""\t"""', 'header': '(0)'}), "(infile, sep='\\t', header=0)\n", (5291, 5319), True, 'import pandas as pd\n'), ((5828, 5884), 'csv.DictWriter', 'csv.DictWriter', (['stats'], {'fieldnames': 'fields', 'delimiter': '"""\t"""'}), "(stats, fieldnames=fields, delimiter='\\t')\n", (5842, 5884), False, 'import csv\n'), ((5939, 5959), 'os.listdir', 'os.listdir', (['tmp_path'], {}), '(tmp_path)\n', (5949, 5959), False, 'import os\n'), ((1915, 1944), 'numpy.unique', 'np.unique', (["gtf_data['GeneID']"], {}), "(gtf_data['GeneID'])\n", (1924, 1944), True, 'import numpy as np\n'), ((2841, 2899), 'numpy.histogram', 'np.histogram', (['snv_list'], {'bins': 'nbins', 'range': '(ref[0], ref[1])'}), '(snv_list, bins=nbins, range=(ref[0], ref[1]))\n', (2853, 2899), True, 'import numpy as np\n'), ((5981, 6013), 'os.path.join', 'os.path.join', (['tmp_path', 'chr_file'], {}), '(tmp_path, chr_file)\n', (5993, 6013), False, 'import os\n'), ((6468, 6495), 'numpy.std', 'np.std', (['total_hists'], {'axis': '(0)'}), '(total_hists, axis=0)\n', (6474, 6495), True, 'import numpy as np\n')]
import sys import numpy as np import torch import torch.nn as nn class Net(nn.Module): def __init__(self, state, event): super().__init__() self.event = event self.state = state self.fc = nn.Linear(1, 1) self.welford = self.event.Welford() self.state["net"] = self event.optional.init_net_finished(self) def forward(self, net): count = np.prod([net.shape[s] for s in self.state["axes"]]) mean = net.double().mean(self.state["axes"]) var = net.double().var(self.state["axes"]) self.welford.updateWithMeanVar(count, mean, var) return net.flatten(1)[:, :self.state["dataset.num_classes"]] * self.fc.weight def after_epoch(state, event): del event # unused torch.set_printoptions(precision=8, linewidth=120) print("dataset mean:", state["net"].welford.mean) print("dataset var:", state["net"].welford.var) print("dataset std:", state["net"].welford.std) sys.exit(0) def register(mf): mf.load(["Welford", "noaugment"]) mf.register_defaults({ "axes": [0, 2, 3], "print_precision": 8 }) mf.overwrite_globals({ "shuffle": False, "mean": [0, 0, 0], "std": [1, 1, 1] }) mf.register_default_module('cpuloader', required_event='dataset', overwrite_globals={ "with_transform": False, "val_prop": 0.0, }) mf.register_event("init_net", Net, unique=True) mf.register_event("after_epoch", after_epoch)
[ "torch.set_printoptions", "numpy.prod", "sys.exit", "torch.nn.Linear" ]
[((772, 822), 'torch.set_printoptions', 'torch.set_printoptions', ([], {'precision': '(8)', 'linewidth': '(120)'}), '(precision=8, linewidth=120)\n', (794, 822), False, 'import torch\n'), ((985, 996), 'sys.exit', 'sys.exit', (['(0)'], {}), '(0)\n', (993, 996), False, 'import sys\n'), ((226, 241), 'torch.nn.Linear', 'nn.Linear', (['(1)', '(1)'], {}), '(1, 1)\n', (235, 241), True, 'import torch.nn as nn\n'), ((412, 463), 'numpy.prod', 'np.prod', (["[net.shape[s] for s in self.state['axes']]"], {}), "([net.shape[s] for s in self.state['axes']])\n", (419, 463), True, 'import numpy as np\n')]
import tensorflow as tf from config import * from networks import vgg16, FormResNet from ops import sobel import os,csv from PIL import Image import numpy as np from skimage.measure import compare_psnr as psnr from skimage.measure import compare_ssim as ssim from skimage import util class Main: def __init__(self): self.clean_img = tf.placeholder(tf.float32, [None, None, None, IMG_C]) self.noised_img = tf.placeholder(tf.float32, [None, None, None, IMG_C]) self.train_phase = tf.placeholder(tf.bool) form_resnet = FormResNet("FormResNet") self.denoised_img, self.res = form_resnet(self.noised_img, self.train_phase) self.L_pix = tf.reduce_mean(tf.reduce_sum(tf.square(self.denoised_img - self.clean_img), [1, 2, 3])) # self.Phi = vgg16(tf.concat([self.denoised_img, self.denoised_img, self.denoised_img], 3)) # self.Phi_ = vgg16(tf.concat([self.clean_img, self.clean_img, self.clean_img], 3)) self.Phi = vgg16(self.denoised_img) self.Phi_ = vgg16(self.clean_img) self.L_feat = tf.reduce_mean(tf.square(self.Phi - self.Phi_)) self.L_grad = tf.reduce_mean(tf.reduce_sum(tf.abs(sobel(self.denoised_img)[0] - sobel(self.clean_img)[0]) +\ tf.abs(sobel(self.denoised_img)[1] - sobel(self.clean_img)[1]), [1, 2, 3])) self.L_cross = (1 - ALPHA - BETA) * self.L_pix + ALPHA * self.L_feat + BETA * self.L_grad self.Opt = tf.train.AdamOptimizer(1e-4).minimize(self.L_cross) self.sess = tf.Session() saver = tf.train.Saver() # saver.restore(self.sess, "./save_para_3_sigma25_2/FormResNet25.ckpt") saver.restore(self.sess, "./sigma50_6000/FormResNet50.ckpt") #self.sess = tf.Session() #self.sess.run(tf.global_variables_initializer()) def train(self): filepath = "./TrainingSet//" filenames = os.listdir(filepath) saver = tf.train.Saver() for epoch in range(EPOCHS): for i in range(filenames.__len__()//BATCH_SIZE): cleaned_batch = np.zeros([BATCH_SIZE, IMG_H, IMG_W, IMG_C], dtype=np.float32) for idx, filename in enumerate(filenames[i*BATCH_SIZE:i*BATCH_SIZE+BATCH_SIZE]): cleaned_batch[idx, :, :, 0] = np.array(Image.open(filepath+filename)) noised_batch = cleaned_batch + np.random.normal(0, SIGMA, cleaned_batch.shape) noised_batch = np.clip(noised_batch,0,255) self.sess.run(self.Opt, feed_dict={self.clean_img: cleaned_batch, self.noised_img: noised_batch, self.train_phase: True}) if i % 10 == 0: [loss, denoised_img] = self.sess.run([self.L_cross, self.denoised_img], feed_dict={self.clean_img: cleaned_batch, self.noised_img: noised_batch, self.train_phase: False}) PSNR = psnr(np.uint8(cleaned_batch[0, :, :, 0]), np.uint8(denoised_img[0, :, :, 0])) SSIM = ssim(np.uint8(cleaned_batch[0, :, :, 0]), np.uint8(denoised_img[0, :, :, 0])) print("Epoch: %d, Step: %d, Loss: %g, psnr: %g, ssim: %g"%(epoch, i, loss, PSNR, SSIM)) compared = np.concatenate((cleaned_batch[0, :, :, 0], noised_batch[0, :, :, 0], denoised_img[0, :, :, 0]), 1) Image.fromarray(np.uint8(compared)).save("./TrainingResults//"+str(epoch)+"_"+str(i)+".jpg") if i % 500 == 0: saver.save(self.sess, "./save_para_3_sigma25//FormResNet.ckpt") np.random.shuffle(filenames) def test(self, cleaned_path="./Kodak24_256//img02_1.png"): cleaned_img = np.reshape(np.array(Image.open(cleaned_path), dtype=np.float32), [1, 256, 256, 3]) noised_img = cleaned_img + np.random.normal(0, SIGMA, cleaned_img.shape) n_img = cleaned_img + np.random.normal(0, 15, cleaned_img.shape) compared=np.concatenate((n_img[0, :, :, :], noised_img[0, :, :, :]), 1) Image.fromarray(np.uint8(compared)).show() # n_PSNR=n_SSIM=0 # for i in range(3): # n_PSNR += psnr(np.uint8(cleaned_img[0, :, :, i]), np.uint8(noised_img[0, :, :, i])) # n_SSIM += ssim(np.uint8(cleaned_img[0, :, :, i]), np.uint8(noised_img[0, :, :, i])) # n_PSNR/=3.0 # n_SSIM/=3.0 # print("n_psnr: %g, n_ssim: %g" % (n_PSNR, n_SSIM)) # [denoised_img] = self.sess.run([self.denoised_img], feed_dict={self.clean_img: cleaned_img, self.noised_img: noised_img, self.train_phase: False}) # PSNR=SSIM=0 # for i in range(3): # PSNR += psnr(np.uint8(cleaned_img[0, :, :, i]), np.uint8(denoised_img[0, :, :, i])) # SSIM += ssim(np.uint8(cleaned_img[0, :, :, i]), np.uint8(denoised_img[0, :, :, i])) # PSNR/=3.0 # SSIM/=3.0 # print("psnr: %g, ssim: %g" % (PSNR, SSIM)) # compared = np.concatenate((cleaned_img[0, :, :, :], noised_img[0, :, :, :], denoised_img[0, :, :, :]), 1) # Image.fromarray(np.uint8(compared)).show() def test_all(self, cleaned_path="./BSD500_256//"): filenames = os.listdir(cleaned_path) csvname = 'sigma50_bsd_6000.csv' csvfile = open(csvname, 'w', newline="") writer = csv.writer(csvfile,dialect='excel') writer.writerow(["num","PSNR","n_PSNR","c_SSIM","n_SSIM"]) idx = 0 tn_PSNR=tn_SSIM=tc_PSNR=tc_SSIM=0 for f in filenames: idx+=1 path = cleaned_path+f cleaned_img = np.reshape(np.array(Image.open(path), dtype=np.float32), [1, 256, 256, 3]) noised_img = cleaned_img + np.random.normal(0, SIGMA, cleaned_img.shape) noised_img = np.clip(noised_img,0,255) # c_batch = cleaned_img.astype('float32')/255. # noised_img=util.random_noise(c_batch,mode='poisson') # noised_img = noised_img.astype('float32')*255. n_PSNR=n_SSIM=0 for i in range(3): n_PSNR += psnr(np.uint8(cleaned_img[0, :, :, i]), np.uint8(noised_img[0, :, :, i])) n_SSIM += ssim(np.uint8(cleaned_img[0, :, :, i]), np.uint8(noised_img[0, :, :, i])) n_PSNR/=3.0 n_SSIM/=3.0 tn_PSNR+=n_PSNR tn_SSIM+=n_SSIM # print("n_psnr: %g, n_ssim: %g" % (n_PSNR, n_SSIM)) [denoised_img] = self.sess.run([self.denoised_img], feed_dict={self.clean_img: cleaned_img, self.noised_img: noised_img, self.train_phase: False}) PSNR=SSIM=0 for i in range(3): PSNR += psnr(np.uint8(cleaned_img[0, :, :, i]), np.uint8(denoised_img[0, :, :, i])) SSIM += ssim(np.uint8(cleaned_img[0, :, :, i]), np.uint8(denoised_img[0, :, :, i])) PSNR/=3.0 SSIM/=3.0 tc_PSNR+=PSNR tc_SSIM+=SSIM # print("psnr: %g, ssim: %g" % (PSNR, SSIM)) writer.writerow([idx,PSNR,n_PSNR,SSIM,n_SSIM]) tn_PSNR/=idx tn_SSIM/=idx tc_PSNR/=idx tc_SSIM/=idx writer.writerow(["average",tc_PSNR,tn_PSNR,tc_SSIM,tn_SSIM]) if __name__ == "__main__": m = Main() # m.test() m.test_all()
[ "numpy.uint8", "networks.vgg16", "csv.writer", "tensorflow.train.Saver", "numpy.random.shuffle", "ops.sobel", "tensorflow.Session", "numpy.zeros", "numpy.clip", "PIL.Image.open", "tensorflow.placeholder", "networks.FormResNet", "tensorflow.square", "numpy.random.normal", "tensorflow.train.AdamOptimizer", "os.listdir", "numpy.concatenate" ]
[((347, 400), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32', '[None, None, None, IMG_C]'], {}), '(tf.float32, [None, None, None, IMG_C])\n', (361, 400), True, 'import tensorflow as tf\n'), ((427, 480), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32', '[None, None, None, IMG_C]'], {}), '(tf.float32, [None, None, None, IMG_C])\n', (441, 480), True, 'import tensorflow as tf\n'), ((508, 531), 'tensorflow.placeholder', 'tf.placeholder', (['tf.bool'], {}), '(tf.bool)\n', (522, 531), True, 'import tensorflow as tf\n'), ((554, 578), 'networks.FormResNet', 'FormResNet', (['"""FormResNet"""'], {}), "('FormResNet')\n", (564, 578), False, 'from networks import vgg16, FormResNet\n'), ((984, 1008), 'networks.vgg16', 'vgg16', (['self.denoised_img'], {}), '(self.denoised_img)\n', (989, 1008), False, 'from networks import vgg16, FormResNet\n'), ((1029, 1050), 'networks.vgg16', 'vgg16', (['self.clean_img'], {}), '(self.clean_img)\n', (1034, 1050), False, 'from networks import vgg16, FormResNet\n'), ((1525, 1537), 'tensorflow.Session', 'tf.Session', ([], {}), '()\n', (1535, 1537), True, 'import tensorflow as tf\n'), ((1554, 1570), 'tensorflow.train.Saver', 'tf.train.Saver', ([], {}), '()\n', (1568, 1570), True, 'import tensorflow as tf\n'), ((1891, 1911), 'os.listdir', 'os.listdir', (['filepath'], {}), '(filepath)\n', (1901, 1911), False, 'import os, csv\n'), ((1928, 1944), 'tensorflow.train.Saver', 'tf.train.Saver', ([], {}), '()\n', (1942, 1944), True, 'import tensorflow as tf\n'), ((3897, 3959), 'numpy.concatenate', 'np.concatenate', (['(n_img[0, :, :, :], noised_img[0, :, :, :])', '(1)'], {}), '((n_img[0, :, :, :], noised_img[0, :, :, :]), 1)\n', (3911, 3959), True, 'import numpy as np\n'), ((5109, 5133), 'os.listdir', 'os.listdir', (['cleaned_path'], {}), '(cleaned_path)\n', (5119, 5133), False, 'import os, csv\n'), ((5241, 5277), 'csv.writer', 'csv.writer', (['csvfile'], {'dialect': '"""excel"""'}), "(csvfile, dialect='excel')\n", (5251, 5277), False, 'import os, csv\n'), ((1088, 1119), 'tensorflow.square', 'tf.square', (['(self.Phi - self.Phi_)'], {}), '(self.Phi - self.Phi_)\n', (1097, 1119), True, 'import tensorflow as tf\n'), ((3528, 3556), 'numpy.random.shuffle', 'np.random.shuffle', (['filenames'], {}), '(filenames)\n', (3545, 3556), True, 'import numpy as np\n'), ((3761, 3806), 'numpy.random.normal', 'np.random.normal', (['(0)', 'SIGMA', 'cleaned_img.shape'], {}), '(0, SIGMA, cleaned_img.shape)\n', (3777, 3806), True, 'import numpy as np\n'), ((3837, 3879), 'numpy.random.normal', 'np.random.normal', (['(0)', '(15)', 'cleaned_img.shape'], {}), '(0, 15, cleaned_img.shape)\n', (3853, 3879), True, 'import numpy as np\n'), ((5694, 5721), 'numpy.clip', 'np.clip', (['noised_img', '(0)', '(255)'], {}), '(noised_img, 0, 255)\n', (5701, 5721), True, 'import numpy as np\n'), ((714, 759), 'tensorflow.square', 'tf.square', (['(self.denoised_img - self.clean_img)'], {}), '(self.denoised_img - self.clean_img)\n', (723, 759), True, 'import tensorflow as tf\n'), ((1453, 1483), 'tensorflow.train.AdamOptimizer', 'tf.train.AdamOptimizer', (['(0.0001)'], {}), '(0.0001)\n', (1475, 1483), True, 'import tensorflow as tf\n'), ((2074, 2135), 'numpy.zeros', 'np.zeros', (['[BATCH_SIZE, IMG_H, IMG_W, IMG_C]'], {'dtype': 'np.float32'}), '([BATCH_SIZE, IMG_H, IMG_W, IMG_C], dtype=np.float32)\n', (2082, 2135), True, 'import numpy as np\n'), ((2449, 2478), 'numpy.clip', 'np.clip', (['noised_batch', '(0)', '(255)'], {}), '(noised_batch, 0, 255)\n', (2456, 2478), True, 'import numpy as np\n'), ((3663, 3687), 'PIL.Image.open', 'Image.open', (['cleaned_path'], {}), '(cleaned_path)\n', (3673, 3687), False, 'from PIL import Image\n'), ((5623, 5668), 'numpy.random.normal', 'np.random.normal', (['(0)', 'SIGMA', 'cleaned_img.shape'], {}), '(0, SIGMA, cleaned_img.shape)\n', (5639, 5668), True, 'import numpy as np\n'), ((2370, 2417), 'numpy.random.normal', 'np.random.normal', (['(0)', 'SIGMA', 'cleaned_batch.shape'], {}), '(0, SIGMA, cleaned_batch.shape)\n', (2386, 2417), True, 'import numpy as np\n'), ((3187, 3289), 'numpy.concatenate', 'np.concatenate', (['(cleaned_batch[0, :, :, 0], noised_batch[0, :, :, 0], denoised_img[0, :, :, 0])', '(1)'], {}), '((cleaned_batch[0, :, :, 0], noised_batch[0, :, :, 0],\n denoised_img[0, :, :, 0]), 1)\n', (3201, 3289), True, 'import numpy as np\n'), ((3984, 4002), 'numpy.uint8', 'np.uint8', (['compared'], {}), '(compared)\n', (3992, 4002), True, 'import numpy as np\n'), ((5529, 5545), 'PIL.Image.open', 'Image.open', (['path'], {}), '(path)\n', (5539, 5545), False, 'from PIL import Image\n'), ((5997, 6030), 'numpy.uint8', 'np.uint8', (['cleaned_img[0, :, :, i]'], {}), '(cleaned_img[0, :, :, i])\n', (6005, 6030), True, 'import numpy as np\n'), ((6032, 6064), 'numpy.uint8', 'np.uint8', (['noised_img[0, :, :, i]'], {}), '(noised_img[0, :, :, i])\n', (6040, 6064), True, 'import numpy as np\n'), ((6097, 6130), 'numpy.uint8', 'np.uint8', (['cleaned_img[0, :, :, i]'], {}), '(cleaned_img[0, :, :, i])\n', (6105, 6130), True, 'import numpy as np\n'), ((6132, 6164), 'numpy.uint8', 'np.uint8', (['noised_img[0, :, :, i]'], {}), '(noised_img[0, :, :, i])\n', (6140, 6164), True, 'import numpy as np\n'), ((6578, 6611), 'numpy.uint8', 'np.uint8', (['cleaned_img[0, :, :, i]'], {}), '(cleaned_img[0, :, :, i])\n', (6586, 6611), True, 'import numpy as np\n'), ((6613, 6647), 'numpy.uint8', 'np.uint8', (['denoised_img[0, :, :, i]'], {}), '(denoised_img[0, :, :, i])\n', (6621, 6647), True, 'import numpy as np\n'), ((6678, 6711), 'numpy.uint8', 'np.uint8', (['cleaned_img[0, :, :, i]'], {}), '(cleaned_img[0, :, :, i])\n', (6686, 6711), True, 'import numpy as np\n'), ((6713, 6747), 'numpy.uint8', 'np.uint8', (['denoised_img[0, :, :, i]'], {}), '(denoised_img[0, :, :, i])\n', (6721, 6747), True, 'import numpy as np\n'), ((2292, 2323), 'PIL.Image.open', 'Image.open', (['(filepath + filename)'], {}), '(filepath + filename)\n', (2302, 2323), False, 'from PIL import Image\n'), ((2870, 2905), 'numpy.uint8', 'np.uint8', (['cleaned_batch[0, :, :, 0]'], {}), '(cleaned_batch[0, :, :, 0])\n', (2878, 2905), True, 'import numpy as np\n'), ((2907, 2941), 'numpy.uint8', 'np.uint8', (['denoised_img[0, :, :, 0]'], {}), '(denoised_img[0, :, :, 0])\n', (2915, 2941), True, 'import numpy as np\n'), ((2975, 3010), 'numpy.uint8', 'np.uint8', (['cleaned_batch[0, :, :, 0]'], {}), '(cleaned_batch[0, :, :, 0])\n', (2983, 3010), True, 'import numpy as np\n'), ((3012, 3046), 'numpy.uint8', 'np.uint8', (['denoised_img[0, :, :, 0]'], {}), '(denoised_img[0, :, :, 0])\n', (3020, 3046), True, 'import numpy as np\n'), ((1179, 1203), 'ops.sobel', 'sobel', (['self.denoised_img'], {}), '(self.denoised_img)\n', (1184, 1203), False, 'from ops import sobel\n'), ((1209, 1230), 'ops.sobel', 'sobel', (['self.clean_img'], {}), '(self.clean_img)\n', (1214, 1230), False, 'from ops import sobel\n'), ((1267, 1291), 'ops.sobel', 'sobel', (['self.denoised_img'], {}), '(self.denoised_img)\n', (1272, 1291), False, 'from ops import sobel\n'), ((1297, 1318), 'ops.sobel', 'sobel', (['self.clean_img'], {}), '(self.clean_img)\n', (1302, 1318), False, 'from ops import sobel\n'), ((3322, 3340), 'numpy.uint8', 'np.uint8', (['compared'], {}), '(compared)\n', (3330, 3340), True, 'import numpy as np\n')]
""" This module provides the core object-oriented framework for generating synthetic data sets with clusters. The classes contained here are mainly abstract superclasses. They require subclasses to concretely implement much of the specified functionality. CLASSES AND METHODS ClusterData : top-level object for generating data __init__(self, n_clusters, n_dim, n_samples, class_bal, cov_geom, center_geom, data_dist, ...) generate_data(self, ...) to_csv(self, filename) CovGeom : sample cluster shapes __init__(self) make_cov(self, clusterdata) make_orthonormal_axes(self, n_dim, n_axes) CenterGeom : place cluster centers __init__(self) make_centers(self, clusterdata) ClassBal : sample number of points for each cluster __init__(self) make_class_sizes(self, clusterdata) DataDist : draw synthetic data for each cluster __init__(self) sample(self, clusterdata) sample_cluster(self, cluster_size, mean, axes, sd) """ import numpy as np import matplotlib.pyplot as plt import scipy.stats as stats from scipy.spatial.distance import mahalanobis class ClusterData: """ Instances of this class are data generators for sampling synthetic data sets with clusters. All generated data sets are different, but possess similar geometric characteristics, as specified by an instance of this class. Attributes ---------- center_geom : CenterGeom Algorithm for placing cluster centers centers : ndarray Cluster centers arranged in a matrix (each row is a center) class_bal : ClassBal Algorithm for sampling class sizes (number of points in each cluster) class_sizes : ndarray, dtype=int Number of points in each cluster cluster_axes : list of ndarray The i-th element stores the principal axes of the i-th cluster, arranged in matrix form so that each row is an axis cluster_sd : list of ndarray The i-th element stores the standard deviations along the principal axes of the i-th cluster cov : list of ndarray The i-th element stores the covariance matrix of the i-th cluster cov_geom : CovGeom Algorithm for sampling cluster shapes (covariance structures) cov_inv : list of ndarray The i-th element stores the inverse covariance matrix of the i-th cluster data : ndarray or None Data set sampled most recently with ClusterData.generate_data() data_dist : DataDist Distribution for drawing synthetic data labels : ndarray, dtype=int Cluster labels / class labels n_clusters : int Number of clusters to sample n_dim : int Dimensionality of the data n_samples : int Total number of samples to generate in each data set scale : float Reference length scale for generated data Methdods -------- __init__(self, n_clusters, n_dim, n_samples, class_bal, cov_geom, center_geom, data_dist, ...) generate_data(self, ...) to_csv(self, filename) """ def __init__(self, n_clusters, n_dim, n_samples, class_bal, cov_geom, center_geom, data_dist, scale=1.0): """ Instantiate a ClusterData object. Parameters ---------- n_clusters : int Number of clusters n_dim : int Dimensionality of data points n_samples : int Total number of data points class_bal : ClassBal object Samples number of points per cluster cov_geom : CovGeom object Samples cluster shapes (covariance structures) center_geom : CenterGeom object Places cluster centers data_dist : DataDist object Draws synthetic data for each cluster scale : float, optional Sets reference length scale for generated data Returns ------- self : ClusterData An instance of ClusterData """ self.n_clusters = n_clusters self.n_dim = n_dim self.n_samples = n_samples self.class_bal = class_bal self.cov_geom = cov_geom self.center_geom = center_geom self.data_dist = data_dist self.data = None self.labels = None self.centers = None self.class_sizes = None self.cov = None self.cov_inv = None self.cluster_axes = None self.cluster_sd = None self.scale = scale def to_csv(self, filename): """ Write the most recently generated data to a csv file. Parameters ---------- self : ClusterData The underlying data generator filename : str Filepath for storing data Returns ------- None Side effects ------------ .csv file is created at the location indicated by filename """ if (self.data is None): raise Exception('No data has been generated. Use ClusterData.generate_data to generate data.') else: np.savetxt(filename, self.data, delimiter=',') def modify_cov_structure(self,cov,cov_inv, cluster_axes, cluster_sd): """ Modify the covariance structure of a ClusterData object. Need to specify ALL attributes of the covariance structure. """ self.cov = cov self.cov_inv = cov_inv self.cluster_axes = cluster_axes self.cluster_sd = cluster_sd def draw_model(self,s=30,alpha_max=0.125, sd_max_bare=2,sd_max_density=4, mode='bare', h=0.1,dr=0.1, cluster_labels=True): """ Plot a sketch of the geometry underlying a probabilistic mixture model sampled by a ClusterData object. Parameters ---------- clusterdata : ClusterData object s : float alpha_max : sd_max_bare : sd_max_density : mode : str Specify the desired type of drawing. The options are 'bare' : draw each cluster as a central point and elliptical contour, which is located two standard deviations away from the mean 'density' : draw each cluster as a probability density that fades out gradually until the elliptical contour four standard deviations away from the mean 'arrows' : as in 'bare', except that arrows are added along the principal axes NOT IMPLEMENTED YET """ centers = self.centers sd = self.cluster_sd axes = self.cluster_axes for i in range(centers.shape[0]): # plot cluster center x_c = centers[i,0] y_c = centers[i,1] plt.scatter(x_c,y_c,c='k',s=s) if cluster_labels: plt.text(x_c,y_c,' ' + str(i),fontsize=16,va='center') if mode=='bare': # plot only a single elliptical contour and the cluster center r = sd_max_bare x = [r*sd[i][0]*np.cos(theta) for theta in np.arange(0,2*np.pi+h,h)] y = [r*sd[i][1]*np.sin(theta) for theta in np.arange(0,2*np.pi+h,h)] Z = np.transpose(axes[i]) @ np.array([x,y]) plt.plot(Z[0]+x_c,Z[1]+y_c,linewidth=2.5,linestyle='-',c='k') elif mode=='density': # plot elliptical density for j,r in enumerate(np.linspace(0,sd_max_density,int(sd_max_density/dr))): # plot ellipse x = [r*sd[i][0]*np.cos(theta) for theta in np.arange(0,2*np.pi+h,h)] y = [r*sd[i][1]*np.sin(theta) for theta in np.arange(0,2*np.pi+h,h)] Z = np.transpose(axes[i]) @ np.array([x,y]) plt.gca().fill(Z[0]+x_c,Z[1]+y_c,c='b',alpha=alpha_max*np.exp(-np.sqrt(r)),edgecolor=None) elif mode=='arrows': # plot cluster center, a single elliptical contour, and arrows along the principal axes raise NotImplementedError('the ability to plot arrows along the principal axes is coming soon') print('hello dair') return (plt.gcf(), plt.gca()) def generate_data(self,add_noise_vars=False, snr=None, p_over_n=None,seed=None,verbose=True): """ Sample a dataset with clusters. The output data set possesses the geometric characteristics specified by this ClusterData object. Info on adding noise features ----------------------------- Noise features can be added to the data. The arguments snr and p_over_n determine how many noise features are added. The argument snr refers to the desired ratio of meaningful features to noise features, whereas the argument p_over_n is the desired ratio of the total number of features (p) to the total number of samples (n). Thus, snr controls how "sparse" the resulting data is, whereas p_over_n determines how high-dimensional the data is (in the statistical sense). One or both of snr and p_over_n can be specified. If only one is given, add the desired number of noise features exactly. If both snr and p_over_n are given, add the least number of noise features that meets or exceeds the desired values of snr and p_over_n. Thus, the output data is as noisy or noisier than specified by either snr or p_over_n alone. Parameters ---------- self : ClusterData The underlying data generator add_noise_vars : bool If true, add noise features to the data. Need to set snr and/or p_over_n to control the amount of noise added. If both snr and p_over_n are given, add the least number of noise features that meets or exceeds both thresholds (snr and the p_over_n). snr : float Set the ratio between the number of meaningful features and the number of noise features. Only relevant when add_noise_vars=True. p_over_n : float Set the ratio between the total number of features (p) and the number of samples (n). Only relevant when add_noise_vars=True. seed : int or None Sets the seed for random data generation, if an int is given. Returns ------- X : ndarray Data matrix whose rows are the data points. y : ndarray Vector of cluster labels. """ if verbose: print('Compute class sizes...') self.class_sizes = self.class_bal.make_class_sizes(self,seed=seed) if verbose: print('Compute covariance structures...') axes, sd, cov, cov_inv = self.cov_geom.make_cov(self,seed=seed) self.cluster_axes = axes self.cluster_sd = sd self.cov = cov self.cov_inv = cov_inv if verbose: print('Place cluster centers...') self.centers = (self.center_geom).place_centers(self,seed=seed, verbose=False) # compute and report the max and min overlaps beween clusters overlap_mat = CenterGeom.overlap_matrix(self.centers,self.cov_inv) self.alpha_min_obs = CenterGeom.alpha_min_obs(overlap_mat) self.alpha_max_obs = CenterGeom.alpha_max_obs(overlap_mat) if verbose: print('Sample data...') self.data, self.labels = (self.data_dist).sample(self,seed=seed) if verbose: print('Success!') if add_noise_vars: self.data = self.add_noise(self.data,snr=snr,p_over_n=p_over_n,seed=seed) return (self.data, self.labels) def add_noise(self, data, snr, p_over_n, model='gauss_mimic', margin=0.1, print_warning=True,seed=None): """ Add noise features to given data. Choosing snr determines how "sparse" the resulting data is, whereas p_over_n determines how high-dimensional the data is. If only one of snr and p_over_n is given, add the exact number of noise features required to meet the threshold. If both snr and p_over_n are given, add the least number of noise features that meets or exceeds both thresholds. Thus, the resulting data is as noisy or noisier than required by either threshold. Parameters ---------- self : ClusterData The underlying data generator data : The data to which noise features are added. snr : float Set the ratio between the number of meaningful features and the number of noise features. p_over_n : float Set the ratio between the total number of features (p) and the number of samples (n). model : str Determine how noise features are calculated. seed : int or None Sets the seed for randomized data generation, if an int is given. Returns ------- out : ndarray Input data with added noise features. """ np.random.seed(seed) n_dim = data.shape[1] n_samples = data.shape[0] if (not snr) and (not p_over_n): raise Exception('Must provide either snr or p_over_n to determine ' + 'number of noise features to add.') else: if snr and not p_over_n: # add enough noise features to meet snr threshold n_noise_vars = int(np.ceil(n_dim / snr)) if p_over_n and not snr: # add enough noise features to meet p_over_n threshold if n_dim/n_samples <= p_over_n: n_noise_vars = int(np.ceil(p_over_n * n_samples)) - n_dim else: noise_vars = [] if print_warning: print('Warning: data already sufficiently high-dimensional,' + ' no noise features added.') if snr and p_over_n: # add enough noise features to meet both snr and p_over_n thresholds n_noise_vars = np.max([int(np.ceil(n_dim/snr)), int(np.ceil(n_samples*p_over_n))-n_dim]) # create noise feature_std = np.std(data,axis=0) feature_mean = np.mean(data,axis=0) # take a random feature, construct a Gaussian noise feature with the same mean+std Z = np.zeros((n,noise_dim)) for i in range(noise_dim): feature_idx = np.random.randint(0,p) mean = feature_mean[feature_idx] std = feature_std[feature_idx] Z[:,i] = np.random.normal(loc=mean,scale=std,size=n) # return data with noise features added return np.concatenate([data,Z],axis=1) class CovGeom: """ Specifies the covariance structure for ClusterData. This is largely an abstract superclass. To learn about a concrete implementation, see the documentation for maxmin.MaxMinCov. Methods ------- __init__(self) : abstract method make_cov(self,clusterdata) : abstract method make_orthonormal_axes(self,n_dim,n_axes) : implemented here """ def __init__(self): raise NotImplementedError('Cannot instantiate abstract CovGeom.'+ ' Choose a provided implementation,'+ ' e.g. maxmin.MaxMinCov, or code your'+ ' own algorithm for defining cluster'+ ' covariance structure.') def make_cov(self, clusterdata): raise NotImplementedError('Cannot sample covariance structure from'+ ' abstract CovGeom. Choose a provided' ' implementation, e.g. maxmin.MaxMinCov' + ', or code your own algorithm for defining' ' cluster covariance structure.') def make_orthonormal_axes(self, n_dim, n_axes, seed=None): """ Sample orthonormal axes for cluster generation. Create n_axes orthonormal axes in n_dim-dimensional space. Parameters ---------- self : CovGeom This instance of CovGeom n_dim : int Dimensionality of the data space n_axes : int Number of axes to generate seed : int or None Sets the seed for randomized axis generation, if an int is given. Returns ------- out : (n_axes, n_dim) ndarray Axes arranged as a matrix, each row is an axis """ ortho_matrix = stats.ortho_group.rvs(n_dim,random_state=seed) return ortho_matrix[:n_axes, :] class CenterGeom: """ Place cluster centers for ClusterData. This is an abstract superclass. To learn about a concrete implementation, see the documentation for centers.BoundedSepCenters. Methods ------- __init__(self) : abstract method make_centers(self, clusterdata) : abstract method compute_overlap : overlap_matrix : """ def __init__(self): raise NotImplementedError('Cannot instantiate abstract CenterGeom.'+ ' Choose a provided implementation,'+ ' e.g. centers.BoundedSepCenters, or code your'+ ' own algorithm for placing cluster centers.') def make_centers(self, clusterdata): raise NotImplementedError('Cannot sample cluster centers from abstract'+ ' CenterGeom. Choose a provided implementation,'+ ' e.g. centers.BoundedSepCenters, or code your'+ ' own algorithm for placing cluster centers.') def compute_overlap(center_1,cov_inv_1,center_2,cov_inv_2): """ Compute the level alpha of overlap between two clusters. """ # compute the mahalanobis distances and calculate the chi2_quantile dist1 = mahalanobis(center_1,center_2,cov_inv_1) dist2 = mahalanobis(center_1,center_2,cov_inv_2) chi2_quantile = (1/((1/dist1) + (1/dist2)))**2 # compute probability P(chi2 <= chi2_quantile) and get alpha df = len(center_1) alpha = 1 - (stats.chi2(df=df).cdf(chi2_quantile)) return alpha def overlap_matrix(centers,cov_inv): """ Compute the matrix of overlaps between pairs of clusters. """ n_centers = centers.shape[0] pw_overlap = np.zeros((n_centers,n_centers)) for i in range(n_centers): for j in range(i+1,n_centers): pw_overlap[i,j] = CenterGeom.compute_overlap(centers[i,:], cov_inv[i], centers[j,:], cov_inv[j]) #print('overlap', pw_overlap[i,j], ' by ', i,j) pw_overlap = pw_overlap + np.transpose(pw_overlap) return pw_overlap def alpha_max_obs(overlap_mat): """ Compute maximum overlap between pairs of cluster centers. """ return np.max(overlap_mat.flatten()) def alpha_min_obs(overlap_mat): """ Compute the minimax overlap between cluster centers. That is, for each cluster center, compute the maximum overlap (overlap with the nearest other center) and take the minimum of these overlaps. The resulting metric quantifies the degree of isolation of the most isolated cluster. """ n_centers = overlap_mat.shape[0] Z = overlap_mat.copy() #Z[np.arange(n_centers),np.arange(n_centers)] = np.Inf return np.min(np.max(Z,axis=1)) class ClassBal: """ Sample class sizes (number of data points in each cluster) for ClusterData. This is an abstract superclass. To learn about a concrete implementation, see the documentation for maxmin.MaxMinBal. Methods ------- __init__(self) : abstract method make_class_sizes(self, clusterdata) : abstract method """ def __init__(self): raise NotImplementedError('Cannot instantiate abstract ClassBal.' + ' Choose a provided implementation, e.g.'+ 'maxmin.MaxMinBal, or code your own '+ 'algorithm for sampling class sizes.') def make_class_sizes(self, clusterdata): raise NotImplementedError('Cannot sample class sizes from abstract'+ ' ClassBal. Choose a provided implementation,'+ ' e.g. maxmin.MaxMinBal, or code your own '+ 'algorithm for sampling class sizes.') class DataDist: """ Specify data distribution for ClusterData. This is largely an abstract superclass. To learn about concrete implementations, see the documentations for distributions.GaussianDist, distributions.ExpDist, or distributions.tDist. Methods ------- __init__(self) : abstract method sample(self, clusterdata) : implemented here sample_cluster(self, cluster_size, mean, axes, sd) : abstract method """ def __init__(self): raise NotImplementedError('Cannot instantiate abstract DataDist. Choose '+ ' a provided implementation, e.g. GaussianDist,' + ' or code your own data distribution.') def sample(self, clusterdata, seed=None): n_clusters = clusterdata.n_clusters n_samples = clusterdata.n_samples n_dim = clusterdata.n_dim class_sizes = clusterdata.class_sizes centers = clusterdata.centers axes = clusterdata.cluster_axes sd = clusterdata.cluster_sd X = np.full(shape=(n_samples, n_dim), fill_value=np.nan) y = np.full(n_samples, fill_value=np.nan).astype(int) start = 0 for i in range(n_clusters): end = start + class_sizes[i] # Set class label y[start:end] = i # Sample data X[start:end,:] = self.sample_cluster(class_size=class_sizes[i], mean=centers[i], axes=axes[i], sd=sd[i],seed=seed+i if seed else seed) start = end return (X, y) def sample_cluster(self, cluster_size, mean, axes, sd, seed=None): raise NotImplementedError('Cannot sample cluster from abstract DataDist. '+ 'Choose a provided implementation, e.g. ' 'GaussianDist, or code your own data distribution.')
[ "numpy.random.seed", "scipy.spatial.distance.mahalanobis", "numpy.mean", "numpy.random.randint", "numpy.arange", "numpy.random.normal", "matplotlib.pyplot.gca", "numpy.sin", "numpy.full", "numpy.std", "numpy.savetxt", "numpy.transpose", "numpy.max", "scipy.stats.ortho_group.rvs", "numpy.ceil", "scipy.stats.chi2", "numpy.cos", "matplotlib.pyplot.gcf", "numpy.concatenate", "matplotlib.pyplot.plot", "matplotlib.pyplot.scatter", "numpy.zeros", "numpy.array", "numpy.sqrt" ]
[((11365, 11385), 'numpy.random.seed', 'np.random.seed', (['seed'], {}), '(seed)\n', (11379, 11385), True, 'import numpy as np\n'), ((14294, 14341), 'scipy.stats.ortho_group.rvs', 'stats.ortho_group.rvs', (['n_dim'], {'random_state': 'seed'}), '(n_dim, random_state=seed)\n', (14315, 14341), True, 'import scipy.stats as stats\n'), ((15487, 15529), 'scipy.spatial.distance.mahalanobis', 'mahalanobis', (['center_1', 'center_2', 'cov_inv_1'], {}), '(center_1, center_2, cov_inv_1)\n', (15498, 15529), False, 'from scipy.spatial.distance import mahalanobis\n'), ((15538, 15580), 'scipy.spatial.distance.mahalanobis', 'mahalanobis', (['center_1', 'center_2', 'cov_inv_2'], {}), '(center_1, center_2, cov_inv_2)\n', (15549, 15580), False, 'from scipy.spatial.distance import mahalanobis\n'), ((15941, 15973), 'numpy.zeros', 'np.zeros', (['(n_centers, n_centers)'], {}), '((n_centers, n_centers))\n', (15949, 15973), True, 'import numpy as np\n'), ((18701, 18753), 'numpy.full', 'np.full', ([], {'shape': '(n_samples, n_dim)', 'fill_value': 'np.nan'}), '(shape=(n_samples, n_dim), fill_value=np.nan)\n', (18708, 18753), True, 'import numpy as np\n'), ((4485, 4531), 'numpy.savetxt', 'np.savetxt', (['filename', 'self.data'], {'delimiter': '""","""'}), "(filename, self.data, delimiter=',')\n", (4495, 4531), True, 'import numpy as np\n'), ((5910, 5943), 'matplotlib.pyplot.scatter', 'plt.scatter', (['x_c', 'y_c'], {'c': '"""k"""', 's': 's'}), "(x_c, y_c, c='k', s=s)\n", (5921, 5943), True, 'import matplotlib.pyplot as plt\n'), ((7111, 7120), 'matplotlib.pyplot.gcf', 'plt.gcf', ([], {}), '()\n', (7118, 7120), True, 'import matplotlib.pyplot as plt\n'), ((7122, 7131), 'matplotlib.pyplot.gca', 'plt.gca', ([], {}), '()\n', (7129, 7131), True, 'import matplotlib.pyplot as plt\n'), ((12317, 12337), 'numpy.std', 'np.std', (['data'], {'axis': '(0)'}), '(data, axis=0)\n', (12323, 12337), True, 'import numpy as np\n'), ((12355, 12376), 'numpy.mean', 'np.mean', (['data'], {'axis': '(0)'}), '(data, axis=0)\n', (12362, 12376), True, 'import numpy as np\n'), ((12470, 12494), 'numpy.zeros', 'np.zeros', (['(n, noise_dim)'], {}), '((n, noise_dim))\n', (12478, 12494), True, 'import numpy as np\n'), ((12749, 12782), 'numpy.concatenate', 'np.concatenate', (['[data, Z]'], {'axis': '(1)'}), '([data, Z], axis=1)\n', (12763, 12782), True, 'import numpy as np\n'), ((16237, 16261), 'numpy.transpose', 'np.transpose', (['pw_overlap'], {}), '(pw_overlap)\n', (16249, 16261), True, 'import numpy as np\n'), ((16899, 16916), 'numpy.max', 'np.max', (['Z'], {'axis': '(1)'}), '(Z, axis=1)\n', (16905, 16916), True, 'import numpy as np\n'), ((6341, 6410), 'matplotlib.pyplot.plot', 'plt.plot', (['(Z[0] + x_c)', '(Z[1] + y_c)'], {'linewidth': '(2.5)', 'linestyle': '"""-"""', 'c': '"""k"""'}), "(Z[0] + x_c, Z[1] + y_c, linewidth=2.5, linestyle='-', c='k')\n", (6349, 6410), True, 'import matplotlib.pyplot as plt\n'), ((12543, 12566), 'numpy.random.randint', 'np.random.randint', (['(0)', 'p'], {}), '(0, p)\n', (12560, 12566), True, 'import numpy as np\n'), ((12651, 12696), 'numpy.random.normal', 'np.random.normal', ([], {'loc': 'mean', 'scale': 'std', 'size': 'n'}), '(loc=mean, scale=std, size=n)\n', (12667, 12696), True, 'import numpy as np\n'), ((18760, 18797), 'numpy.full', 'np.full', (['n_samples'], {'fill_value': 'np.nan'}), '(n_samples, fill_value=np.nan)\n', (18767, 18797), True, 'import numpy as np\n'), ((6292, 6313), 'numpy.transpose', 'np.transpose', (['axes[i]'], {}), '(axes[i])\n', (6304, 6313), True, 'import numpy as np\n'), ((6316, 6332), 'numpy.array', 'np.array', (['[x, y]'], {}), '([x, y])\n', (6324, 6332), True, 'import numpy as np\n'), ((11705, 11725), 'numpy.ceil', 'np.ceil', (['(n_dim / snr)'], {}), '(n_dim / snr)\n', (11712, 11725), True, 'import numpy as np\n'), ((15728, 15745), 'scipy.stats.chi2', 'stats.chi2', ([], {'df': 'df'}), '(df=df)\n', (15738, 15745), True, 'import scipy.stats as stats\n'), ((6158, 6171), 'numpy.cos', 'np.cos', (['theta'], {}), '(theta)\n', (6164, 6171), True, 'import numpy as np\n'), ((6185, 6215), 'numpy.arange', 'np.arange', (['(0)', '(2 * np.pi + h)', 'h'], {}), '(0, 2 * np.pi + h, h)\n', (6194, 6215), True, 'import numpy as np\n'), ((6231, 6244), 'numpy.sin', 'np.sin', (['theta'], {}), '(theta)\n', (6237, 6244), True, 'import numpy as np\n'), ((6258, 6288), 'numpy.arange', 'np.arange', (['(0)', '(2 * np.pi + h)', 'h'], {}), '(0, 2 * np.pi + h, h)\n', (6267, 6288), True, 'import numpy as np\n'), ((6724, 6745), 'numpy.transpose', 'np.transpose', (['axes[i]'], {}), '(axes[i])\n', (6736, 6745), True, 'import numpy as np\n'), ((6748, 6764), 'numpy.array', 'np.array', (['[x, y]'], {}), '([x, y])\n', (6756, 6764), True, 'import numpy as np\n'), ((11875, 11904), 'numpy.ceil', 'np.ceil', (['(p_over_n * n_samples)'], {}), '(p_over_n * n_samples)\n', (11882, 11904), True, 'import numpy as np\n'), ((12203, 12223), 'numpy.ceil', 'np.ceil', (['(n_dim / snr)'], {}), '(n_dim / snr)\n', (12210, 12223), True, 'import numpy as np\n'), ((6588, 6601), 'numpy.cos', 'np.cos', (['theta'], {}), '(theta)\n', (6594, 6601), True, 'import numpy as np\n'), ((6615, 6645), 'numpy.arange', 'np.arange', (['(0)', '(2 * np.pi + h)', 'h'], {}), '(0, 2 * np.pi + h, h)\n', (6624, 6645), True, 'import numpy as np\n'), ((6662, 6675), 'numpy.sin', 'np.sin', (['theta'], {}), '(theta)\n', (6668, 6675), True, 'import numpy as np\n'), ((6689, 6719), 'numpy.arange', 'np.arange', (['(0)', '(2 * np.pi + h)', 'h'], {}), '(0, 2 * np.pi + h, h)\n', (6698, 6719), True, 'import numpy as np\n'), ((6770, 6779), 'matplotlib.pyplot.gca', 'plt.gca', ([], {}), '()\n', (6777, 6779), True, 'import matplotlib.pyplot as plt\n'), ((12241, 12270), 'numpy.ceil', 'np.ceil', (['(n_samples * p_over_n)'], {}), '(n_samples * p_over_n)\n', (12248, 12270), True, 'import numpy as np\n'), ((6833, 6843), 'numpy.sqrt', 'np.sqrt', (['r'], {}), '(r)\n', (6840, 6843), True, 'import numpy as np\n')]
import os from tqdm import tqdm from datetime import datetime import pandas as pd import numpy as np from scipy.io import wavfile import tensorflow as tf from tensorflow.keras.layers import Conv2D, MaxPool2D, Flatten from tensorflow.keras.layers import LSTM, TimeDistributed from tensorflow.keras.layers import Dropout, SpatialDropout2D, Dense from tensorflow.keras.models import Sequential from tensorflow.keras.callbacks import ModelCheckpoint, TensorBoard from tensorflow.keras.utils import to_categorical from sklearn.utils.class_weight import compute_class_weight from sklearn.model_selection import train_test_split from sklearn.decomposition import PCA import pickle from python_speech_features import mfcc import librosa from librosa.feature import melspectrogram from cfg import Config from buildfeats import build_rand_feat def get_conv_model(): model = Sequential() model.add(Conv2D(filters=16, kernel_size=(3, 3), activation='relu', strides=(1,1), padding='same', input_shape=input_shape)) model.add(Conv2D(16, (3, 3), activation='relu', strides=(1,1),padding='same')) model.add(Conv2D(32, (3, 3), activation='relu', strides=(1,1),padding='same')) # model.add(Conv2D(128, (3, 3), activation='relu', strides=(1,1), padding='same')) model.add(MaxPool2D((2,2))) model.add(Dropout(0.5)) model.add(Flatten()) # model.add(Dense(128, activation='relu')) model.add(Dropout(0.5)) model.add(Dense(32, activation='relu')) # model.add(Dropout(0.5)) model.add(Dense(5, activation='softmax')) model.summary() model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy']) return model def get_recurrent_model(): #shape of data for RNN is (n, time, feat) model = Sequential() model.add(LSTM(128, return_sequences=True, input_shape=input_shape)) model.add(LSTM(128, return_sequences=True)) model.add(Dropout(0.5)) model.add(TimeDistributed(Dense(64, activation='relu'))) model.add(TimeDistributed(Dense(32, activation='relu'))) model.add(TimeDistributed(Dense(16, activation='relu'))) model.add(TimeDistributed(Dense(8, activation='relu'))) model.add(Flatten()) model.add(Dense(5, activation='softmax')) model.summary() model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy']) return model config = Config(mode='conv') cur_df = pd.read_csv('data/train/roadsound_labels.csv', index_col=0) noisy_df = pd.read_csv('data/train_noisy/roadsound_labels.csv', index_col=0) df = pd.concat([cur_df, noisy_df], sort=True) df.set_index('fname', inplace=True) for f in df.index: rate, signal = wavfile.read('clean/'+f) df.at[f, 'length'] = signal.shape[0]/rate df = df[df.length > config.step/rate] classes = list(np.unique(df.labels)) class_dist = df.groupby(['labels'])['length'].mean() # n_samples = 2 * int(df['length'].sum() / 0.1) # 40 * total length of audio prob_dist = class_dist / class_dist.sum() choices = np.random.choice(class_dist.index, p=prob_dist) df, test_df, _, _ = train_test_split(df, df.labels) if config.mode == 'conv': X, y = build_rand_feat(config.p_path, df, 'train') X_test, y_test = build_rand_feat(config.val_p_path, test_df, 'val') y_flat = np.argmax(y, axis=1) # create an array of integer labels input_shape = (X.shape[1], X.shape[2]) model = get_conv_model() elif config.mode == 'time': print('mode is time(recurrent)') X, y = build_rand_feat(config.p_path, df, 'train') X_test, y_test = build_rand_feat(config.val_p_path, test_df, 'val') y_flat = np.argmax(y, axis=1) input_shape = (X.shape[1], X.shape[2]) model = get_recurrent_model() class_weight = compute_class_weight('balanced', np.unique(y_flat), y_flat) n_epochs = 2 batch_size = 128 checkpoint = ModelCheckpoint(config.model_path, monitor='val_acc', verbose=1, mode='max', save_best_only=True, save_weights_only=False, period=1) log_dir="logs/fit/" + datetime.datetime.now().strftime("%Y%m%d-%H%M%S") tensorboard = TensorBoard(log_dir=log_dir, histogram_freq=2, batch_size=batch_size, write_graph=True, write_grads=True, write_images=True) model.fit(X, y, epochs=n_epochs, batch_size=batch_size, shuffle=True, class_weight=class_weight, validation_data =(X_test, y_test) , callbacks=[checkpoint, tensorboard]) #if best model, save to config.model_path model.save(model, config.model_path) #save all models anyway datetime_model_path = "./models/{}epochs_{}.h5".format(n_epochs, datetime.now().strftime("%Y%m%d")) # _%H%M%S model.save(model, datetime_model_path)
[ "numpy.argmax", "pandas.read_csv", "sklearn.model_selection.train_test_split", "tensorflow.keras.layers.Dense", "datetime.datetime.datetime.now", "tensorflow.keras.callbacks.ModelCheckpoint", "scipy.io.wavfile.read", "tensorflow.keras.layers.MaxPool2D", "tensorflow.keras.models.Sequential", "numpy.unique", "tensorflow.keras.layers.Flatten", "buildfeats.build_rand_feat", "numpy.random.choice", "datetime.datetime.now", "pandas.concat", "cfg.Config", "tensorflow.keras.layers.Dropout", "tensorflow.keras.layers.Conv2D", "tensorflow.keras.layers.LSTM", "tensorflow.keras.callbacks.TensorBoard" ]
[((2472, 2491), 'cfg.Config', 'Config', ([], {'mode': '"""conv"""'}), "(mode='conv')\n", (2478, 2491), False, 'from cfg import Config\n'), ((2502, 2561), 'pandas.read_csv', 'pd.read_csv', (['"""data/train/roadsound_labels.csv"""'], {'index_col': '(0)'}), "('data/train/roadsound_labels.csv', index_col=0)\n", (2513, 2561), True, 'import pandas as pd\n'), ((2573, 2638), 'pandas.read_csv', 'pd.read_csv', (['"""data/train_noisy/roadsound_labels.csv"""'], {'index_col': '(0)'}), "('data/train_noisy/roadsound_labels.csv', index_col=0)\n", (2584, 2638), True, 'import pandas as pd\n'), ((2644, 2684), 'pandas.concat', 'pd.concat', (['[cur_df, noisy_df]'], {'sort': '(True)'}), '([cur_df, noisy_df], sort=True)\n', (2653, 2684), True, 'import pandas as pd\n'), ((3090, 3137), 'numpy.random.choice', 'np.random.choice', (['class_dist.index'], {'p': 'prob_dist'}), '(class_dist.index, p=prob_dist)\n', (3106, 3137), True, 'import numpy as np\n'), ((3159, 3190), 'sklearn.model_selection.train_test_split', 'train_test_split', (['df', 'df.labels'], {}), '(df, df.labels)\n', (3175, 3190), False, 'from sklearn.model_selection import train_test_split\n'), ((3986, 4122), 'tensorflow.keras.callbacks.ModelCheckpoint', 'ModelCheckpoint', (['config.model_path'], {'monitor': '"""val_acc"""', 'verbose': '(1)', 'mode': '"""max"""', 'save_best_only': '(True)', 'save_weights_only': '(False)', 'period': '(1)'}), "(config.model_path, monitor='val_acc', verbose=1, mode='max',\n save_best_only=True, save_weights_only=False, period=1)\n", (4001, 4122), False, 'from tensorflow.keras.callbacks import ModelCheckpoint, TensorBoard\n'), ((4235, 4363), 'tensorflow.keras.callbacks.TensorBoard', 'TensorBoard', ([], {'log_dir': 'log_dir', 'histogram_freq': '(2)', 'batch_size': 'batch_size', 'write_graph': '(True)', 'write_grads': '(True)', 'write_images': '(True)'}), '(log_dir=log_dir, histogram_freq=2, batch_size=batch_size,\n write_graph=True, write_grads=True, write_images=True)\n', (4246, 4363), False, 'from tensorflow.keras.callbacks import ModelCheckpoint, TensorBoard\n'), ((870, 882), 'tensorflow.keras.models.Sequential', 'Sequential', ([], {}), '()\n', (880, 882), False, 'from tensorflow.keras.models import Sequential\n'), ((1825, 1837), 'tensorflow.keras.models.Sequential', 'Sequential', ([], {}), '()\n', (1835, 1837), False, 'from tensorflow.keras.models import Sequential\n'), ((2760, 2786), 'scipy.io.wavfile.read', 'wavfile.read', (["('clean/' + f)"], {}), "('clean/' + f)\n", (2772, 2786), False, 'from scipy.io import wavfile\n'), ((2886, 2906), 'numpy.unique', 'np.unique', (['df.labels'], {}), '(df.labels)\n', (2895, 2906), True, 'import numpy as np\n'), ((3229, 3272), 'buildfeats.build_rand_feat', 'build_rand_feat', (['config.p_path', 'df', '"""train"""'], {}), "(config.p_path, df, 'train')\n", (3244, 3272), False, 'from buildfeats import build_rand_feat\n'), ((3294, 3344), 'buildfeats.build_rand_feat', 'build_rand_feat', (['config.val_p_path', 'test_df', '"""val"""'], {}), "(config.val_p_path, test_df, 'val')\n", (3309, 3344), False, 'from buildfeats import build_rand_feat\n'), ((3358, 3378), 'numpy.argmax', 'np.argmax', (['y'], {'axis': '(1)'}), '(y, axis=1)\n', (3367, 3378), True, 'import numpy as np\n'), ((3878, 3895), 'numpy.unique', 'np.unique', (['y_flat'], {}), '(y_flat)\n', (3887, 3895), True, 'import numpy as np\n'), ((897, 1015), 'tensorflow.keras.layers.Conv2D', 'Conv2D', ([], {'filters': '(16)', 'kernel_size': '(3, 3)', 'activation': '"""relu"""', 'strides': '(1, 1)', 'padding': '"""same"""', 'input_shape': 'input_shape'}), "(filters=16, kernel_size=(3, 3), activation='relu', strides=(1, 1),\n padding='same', input_shape=input_shape)\n", (903, 1015), False, 'from tensorflow.keras.layers import Conv2D, MaxPool2D, Flatten\n'), ((1050, 1119), 'tensorflow.keras.layers.Conv2D', 'Conv2D', (['(16)', '(3, 3)'], {'activation': '"""relu"""', 'strides': '(1, 1)', 'padding': '"""same"""'}), "(16, (3, 3), activation='relu', strides=(1, 1), padding='same')\n", (1056, 1119), False, 'from tensorflow.keras.layers import Conv2D, MaxPool2D, Flatten\n'), ((1134, 1203), 'tensorflow.keras.layers.Conv2D', 'Conv2D', (['(32)', '(3, 3)'], {'activation': '"""relu"""', 'strides': '(1, 1)', 'padding': '"""same"""'}), "(32, (3, 3), activation='relu', strides=(1, 1), padding='same')\n", (1140, 1203), False, 'from tensorflow.keras.layers import Conv2D, MaxPool2D, Flatten\n'), ((1304, 1321), 'tensorflow.keras.layers.MaxPool2D', 'MaxPool2D', (['(2, 2)'], {}), '((2, 2))\n', (1313, 1321), False, 'from tensorflow.keras.layers import Conv2D, MaxPool2D, Flatten\n'), ((1336, 1348), 'tensorflow.keras.layers.Dropout', 'Dropout', (['(0.5)'], {}), '(0.5)\n', (1343, 1348), False, 'from tensorflow.keras.layers import Dropout, SpatialDropout2D, Dense\n'), ((1364, 1373), 'tensorflow.keras.layers.Flatten', 'Flatten', ([], {}), '()\n', (1371, 1373), False, 'from tensorflow.keras.layers import Conv2D, MaxPool2D, Flatten\n'), ((1436, 1448), 'tensorflow.keras.layers.Dropout', 'Dropout', (['(0.5)'], {}), '(0.5)\n', (1443, 1448), False, 'from tensorflow.keras.layers import Dropout, SpatialDropout2D, Dense\n'), ((1464, 1492), 'tensorflow.keras.layers.Dense', 'Dense', (['(32)'], {'activation': '"""relu"""'}), "(32, activation='relu')\n", (1469, 1492), False, 'from tensorflow.keras.layers import Dropout, SpatialDropout2D, Dense\n'), ((1538, 1568), 'tensorflow.keras.layers.Dense', 'Dense', (['(5)'], {'activation': '"""softmax"""'}), "(5, activation='softmax')\n", (1543, 1568), False, 'from tensorflow.keras.layers import Dropout, SpatialDropout2D, Dense\n'), ((1852, 1909), 'tensorflow.keras.layers.LSTM', 'LSTM', (['(128)'], {'return_sequences': '(True)', 'input_shape': 'input_shape'}), '(128, return_sequences=True, input_shape=input_shape)\n', (1856, 1909), False, 'from tensorflow.keras.layers import LSTM, TimeDistributed\n'), ((1925, 1957), 'tensorflow.keras.layers.LSTM', 'LSTM', (['(128)'], {'return_sequences': '(True)'}), '(128, return_sequences=True)\n', (1929, 1957), False, 'from tensorflow.keras.layers import LSTM, TimeDistributed\n'), ((1973, 1985), 'tensorflow.keras.layers.Dropout', 'Dropout', (['(0.5)'], {}), '(0.5)\n', (1980, 1985), False, 'from tensorflow.keras.layers import Dropout, SpatialDropout2D, Dense\n'), ((2244, 2253), 'tensorflow.keras.layers.Flatten', 'Flatten', ([], {}), '()\n', (2251, 2253), False, 'from tensorflow.keras.layers import Conv2D, MaxPool2D, Flatten\n'), ((2269, 2299), 'tensorflow.keras.layers.Dense', 'Dense', (['(5)'], {'activation': '"""softmax"""'}), "(5, activation='softmax')\n", (2274, 2299), False, 'from tensorflow.keras.layers import Dropout, SpatialDropout2D, Dense\n'), ((3564, 3607), 'buildfeats.build_rand_feat', 'build_rand_feat', (['config.p_path', 'df', '"""train"""'], {}), "(config.p_path, df, 'train')\n", (3579, 3607), False, 'from buildfeats import build_rand_feat\n'), ((3629, 3679), 'buildfeats.build_rand_feat', 'build_rand_feat', (['config.val_p_path', 'test_df', '"""val"""'], {}), "(config.val_p_path, test_df, 'val')\n", (3644, 3679), False, 'from buildfeats import build_rand_feat\n'), ((3693, 3713), 'numpy.argmax', 'np.argmax', (['y'], {'axis': '(1)'}), '(y, axis=1)\n', (3702, 3713), True, 'import numpy as np\n'), ((2017, 2045), 'tensorflow.keras.layers.Dense', 'Dense', (['(64)'], {'activation': '"""relu"""'}), "(64, activation='relu')\n", (2022, 2045), False, 'from tensorflow.keras.layers import Dropout, SpatialDropout2D, Dense\n'), ((2078, 2106), 'tensorflow.keras.layers.Dense', 'Dense', (['(32)'], {'activation': '"""relu"""'}), "(32, activation='relu')\n", (2083, 2106), False, 'from tensorflow.keras.layers import Dropout, SpatialDropout2D, Dense\n'), ((2139, 2167), 'tensorflow.keras.layers.Dense', 'Dense', (['(16)'], {'activation': '"""relu"""'}), "(16, activation='relu')\n", (2144, 2167), False, 'from tensorflow.keras.layers import Dropout, SpatialDropout2D, Dense\n'), ((2200, 2227), 'tensorflow.keras.layers.Dense', 'Dense', (['(8)'], {'activation': '"""relu"""'}), "(8, activation='relu')\n", (2205, 2227), False, 'from tensorflow.keras.layers import Dropout, SpatialDropout2D, Dense\n'), ((4171, 4194), 'datetime.datetime.datetime.now', 'datetime.datetime.now', ([], {}), '()\n', (4192, 4194), False, 'from datetime import datetime\n'), ((4774, 4788), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (4786, 4788), False, 'from datetime import datetime\n')]
# Author: <NAME> # License: BSD import numpy as np from seglearn.datasets import load_watch from seglearn.base import TS_Data from seglearn import util def test_util(): df = load_watch() data = TS_Data(df['X'], df['side']) Xt, Xc = util.get_ts_data_parts(data) assert np.array_equal(Xc, df['side']) assert np.all([np.array_equal(Xt[i], df['X'][i]) for i in range(len(df['X']))]) util.check_ts_data(data, df['y']) util.check_ts_data(df['X'], df['y']) util.ts_stats(df['X'], df['y'], fs=1., class_labels=df['y_labels'])
[ "seglearn.base.TS_Data", "seglearn.util.check_ts_data", "seglearn.util.ts_stats", "seglearn.util.get_ts_data_parts", "seglearn.datasets.load_watch", "numpy.array_equal" ]
[((182, 194), 'seglearn.datasets.load_watch', 'load_watch', ([], {}), '()\n', (192, 194), False, 'from seglearn.datasets import load_watch\n'), ((207, 235), 'seglearn.base.TS_Data', 'TS_Data', (["df['X']", "df['side']"], {}), "(df['X'], df['side'])\n", (214, 235), False, 'from seglearn.base import TS_Data\n'), ((249, 277), 'seglearn.util.get_ts_data_parts', 'util.get_ts_data_parts', (['data'], {}), '(data)\n', (271, 277), False, 'from seglearn import util\n'), ((290, 320), 'numpy.array_equal', 'np.array_equal', (['Xc', "df['side']"], {}), "(Xc, df['side'])\n", (304, 320), True, 'import numpy as np\n'), ((410, 443), 'seglearn.util.check_ts_data', 'util.check_ts_data', (['data', "df['y']"], {}), "(data, df['y'])\n", (428, 443), False, 'from seglearn import util\n'), ((448, 484), 'seglearn.util.check_ts_data', 'util.check_ts_data', (["df['X']", "df['y']"], {}), "(df['X'], df['y'])\n", (466, 484), False, 'from seglearn import util\n'), ((490, 558), 'seglearn.util.ts_stats', 'util.ts_stats', (["df['X']", "df['y']"], {'fs': '(1.0)', 'class_labels': "df['y_labels']"}), "(df['X'], df['y'], fs=1.0, class_labels=df['y_labels'])\n", (503, 558), False, 'from seglearn import util\n'), ((340, 373), 'numpy.array_equal', 'np.array_equal', (['Xt[i]', "df['X'][i]"], {}), "(Xt[i], df['X'][i])\n", (354, 373), True, 'import numpy as np\n')]
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. from typing import Any, Dict, Optional import numpy as np from synthetic_problems import ( Branin1DEmbedding, Branin2DBase, Hartmann5DEmbedding, Hartmann6DBase, ) def get_benchmark_problem( name: str, num_contexts: int, benchmark_problem_args: Optional[Dict[str, Any]] = None, ): """generate benchmark problems. Args: 1. name: benchmark name 2. num_contexts: number of contexts n 3. args for creating benchmark - context_name_list. List of str. Default is [c0, c1, ..., cn] - context_weights. [w0, w1, ..., wn]. sum of w_i = 1. Default is [1/n] - context_embedding. """ benchmark_problem_args = benchmark_problem_args or {} context_name_list = benchmark_problem_args.get( "context_name_list", [f"c{i}" for i in range(num_contexts)] ) context_weights = np.array( benchmark_problem_args.get( "context_weights", np.ones(num_contexts) / num_contexts ) ) if name == "Branin2D": benchmark_problem = Branin2DBase( context_name_list=context_name_list, context_weights=context_weights ) elif name == "Hartmann6D": benchmark_problem = Hartmann6DBase( context_name_list=context_name_list, context_weights=context_weights ) elif name == "Branin1DEmbedding": benchmark_problem = Branin1DEmbedding( context_name_list=context_name_list, context_weights=context_weights, context_embedding=np.arange(0.0, 15.0, 15.0 / num_contexts).reshape( num_contexts, 1 ), ) elif name == "Hartmann5DEmbedding": context_embedding = np.array( benchmark_problem_args.get( "context_embedding", np.arange(0.0, 1.0, 1.0 / num_contexts) ) ) benchmark_problem = Hartmann5DEmbedding( context_name_list=context_name_list, context_weights=context_weights, context_embedding=context_embedding.reshape(num_contexts, 1), ) return benchmark_problem
[ "synthetic_problems.Hartmann6DBase", "numpy.arange", "numpy.ones", "synthetic_problems.Branin2DBase" ]
[((1242, 1329), 'synthetic_problems.Branin2DBase', 'Branin2DBase', ([], {'context_name_list': 'context_name_list', 'context_weights': 'context_weights'}), '(context_name_list=context_name_list, context_weights=\n context_weights)\n', (1254, 1329), False, 'from synthetic_problems import Branin1DEmbedding, Branin2DBase, Hartmann5DEmbedding, Hartmann6DBase\n'), ((1406, 1495), 'synthetic_problems.Hartmann6DBase', 'Hartmann6DBase', ([], {'context_name_list': 'context_name_list', 'context_weights': 'context_weights'}), '(context_name_list=context_name_list, context_weights=\n context_weights)\n', (1420, 1495), False, 'from synthetic_problems import Branin1DEmbedding, Branin2DBase, Hartmann5DEmbedding, Hartmann6DBase\n'), ((1134, 1155), 'numpy.ones', 'np.ones', (['num_contexts'], {}), '(num_contexts)\n', (1141, 1155), True, 'import numpy as np\n'), ((1985, 2024), 'numpy.arange', 'np.arange', (['(0.0)', '(1.0)', '(1.0 / num_contexts)'], {}), '(0.0, 1.0, 1.0 / num_contexts)\n', (1994, 2024), True, 'import numpy as np\n'), ((1722, 1763), 'numpy.arange', 'np.arange', (['(0.0)', '(15.0)', '(15.0 / num_contexts)'], {}), '(0.0, 15.0, 15.0 / num_contexts)\n', (1731, 1763), True, 'import numpy as np\n')]
import random import numpy as np def int_to_bin(number: int, length=8) -> str: b = bin(number)[2:] return ('0' * (-len(b) % length)) + b def bin_to_int(number: str) -> int: return int(number, base=2) def random_string(length=8): return ''.join([chr(random.randint(0, 127)) for _ in range(length)]) def max_message_length(I: np.ndarray) -> int: return (get_image_volume_optimum(I) - get_image_data_volume_bit_len(I)) // 8 def get_image_data_volume_bit_len(I: np.ndarray) -> int: return int(np.ceil(np.log2(get_image_volume_optimum(I) / 8))) def get_image_volume_optimum(I: np.ndarray) -> int: """:returns the number of bits of information we can store in an image""" return 2 * np.prod(I.shape) def get_bit_stream_from_plaintext(plaintext: str) -> list: stream = [] for letter in plaintext: letter_bin = int_to_bin(ord(letter)) for bit in letter_bin: stream.append(bit) return stream def add_bit_stream_to_color_channel(stream: list, C: list, start_point: int, position=7) -> None: for i, bit in enumerate(stream): pixel_bin = int_to_bin(C[i + start_point]) pixel_bin = pixel_bin[0:position] + bit + pixel_bin[position + 1:] C[i + start_point] = bin_to_int(pixel_bin) def get_channel_stream(I) -> list: B, R, G = np.ravel(I[:, :, 0]).tolist(), np.ravel(I[:, :, 2]).tolist(), np.ravel(I[:, :, 1]).tolist() return B + R + G def lsb_encrypt(I, plaintext: str): image_shape = I.shape[0:2] C = get_channel_stream(I) plaintext_len_bit_size = get_image_data_volume_bit_len(I) plaintext_len_bin = int_to_bin(len(plaintext), length=plaintext_len_bit_size) # adding length bits to the image for i in range(plaintext_len_bit_size): pixel_bin = int_to_bin(C[i]) pixel_bin = pixel_bin[0:7] + plaintext_len_bin[i] C[i] = bin_to_int(pixel_bin) # creating bit stream from plaintext stream = get_bit_stream_from_plaintext(plaintext) # adding the plaintext stream to the channel stream add_bit_stream_to_color_channel(stream[:np.prod(I.shape) - plaintext_len_bit_size], C, start_point=plaintext_len_bit_size, position=7) add_bit_stream_to_color_channel(stream[(np.prod(I.shape) - plaintext_len_bit_size):], C, start_point=0, position=6) B, R, G = C[:len(C) // 3], C[len(C) // 3: 2 * len(C) // 3], C[2 * len(C) // 3:] B = np.array(B).reshape(image_shape) R = np.array(R).reshape(image_shape) G = np.array(G).reshape(image_shape) # Adding the pixel layers back to the Image I[:, :, 0] = B I[:, :, 2] = R I[:, :, 1] = G return I def plaintext_from_bit_stream(stream: list) -> str: plaintext = '' for i in range(len(stream) // 8): byte = ''.join(stream[8 * i: 8 * i + 8]) letter = bin_to_int(byte) plaintext += chr(letter) return plaintext def get_stream_from_channel(channel: list, position: int) -> list: stream = [] for pixel in channel: pixel_bin = int_to_bin(pixel, length=8) pixel_bit = pixel_bin[position] stream.append(pixel_bit) return stream def lsb_decrypt(I) -> str: # Obtaining the B G R channel stream C = get_channel_stream(I) plaintext_len_bit_size = get_image_data_volume_bit_len(I) plaintext_len_bin = ''.join([int_to_bin(C[i])[7] for i in range(plaintext_len_bit_size)]) plaintext_len = bin_to_int(plaintext_len_bin) # creating the bit stream from the plaintext_len stream = get_stream_from_channel(channel=C, position=7) + get_stream_from_channel(channel=C, position=6) stream = stream[plaintext_len_bit_size:plaintext_len_bit_size + plaintext_len * 8] # creating plaintext from bit stream plaintext = plaintext_from_bit_stream(stream) return plaintext
[ "numpy.array", "random.randint", "numpy.prod", "numpy.ravel" ]
[((722, 738), 'numpy.prod', 'np.prod', (['I.shape'], {}), '(I.shape)\n', (729, 738), True, 'import numpy as np\n'), ((2411, 2422), 'numpy.array', 'np.array', (['B'], {}), '(B)\n', (2419, 2422), True, 'import numpy as np\n'), ((2452, 2463), 'numpy.array', 'np.array', (['R'], {}), '(R)\n', (2460, 2463), True, 'import numpy as np\n'), ((2493, 2504), 'numpy.array', 'np.array', (['G'], {}), '(G)\n', (2501, 2504), True, 'import numpy as np\n'), ((272, 294), 'random.randint', 'random.randint', (['(0)', '(127)'], {}), '(0, 127)\n', (286, 294), False, 'import random\n'), ((1335, 1355), 'numpy.ravel', 'np.ravel', (['I[:, :, 0]'], {}), '(I[:, :, 0])\n', (1343, 1355), True, 'import numpy as np\n'), ((1366, 1386), 'numpy.ravel', 'np.ravel', (['I[:, :, 2]'], {}), '(I[:, :, 2])\n', (1374, 1386), True, 'import numpy as np\n'), ((1397, 1417), 'numpy.ravel', 'np.ravel', (['I[:, :, 1]'], {}), '(I[:, :, 1])\n', (1405, 1417), True, 'import numpy as np\n'), ((2103, 2119), 'numpy.prod', 'np.prod', (['I.shape'], {}), '(I.shape)\n', (2110, 2119), True, 'import numpy as np\n'), ((2242, 2258), 'numpy.prod', 'np.prod', (['I.shape'], {}), '(I.shape)\n', (2249, 2258), True, 'import numpy as np\n')]
"""Use of Bertran to calculate sparse segments.""" import numpy as np import chaospy as cp def sparse_segment(cords): r""" Create a segment of a sparse grid. Convert a ol-index to sparse grid coordinates on ``[0, 1]^N`` hyper-cube. A sparse grid of order ``D`` coencide with the set of sparse_segments where ``||cords||_1 <= D``. More specifically, a segment of: .. math:: \cup_{cords \in C} sparse_segment(cords) == sparse_grid(M) where: .. math:: C = {cords: M=sum(cords)} Args: cords (numpy.ndarray): The segment to extract. ``cord`` must consist of non-negative integers. Returns: Q (numpy.ndarray): Sparse segment where ``Q.shape==(K, sum(M))`` and ``K`` is segment specific. Examples: >>> chaospy.bertran.sparse_segment([0, 2]) array([[0.5 , 0.125], [0.5 , 0.375], [0.5 , 0.625], [0.5 , 0.875]]) >>> chaospy.bertran.sparse_segment([0, 1, 0, 0]) array([[0.5 , 0.25, 0.5 , 0.5 ], [0.5 , 0.75, 0.5 , 0.5 ]]) """ cords = np.array(cords)+1 slices = [] for cord in cords: slices.append(slice(1, 2**cord+1, 2)) grid = np.mgrid[slices] indices = grid.reshape(len(cords), np.prod(grid.shape[1:])).T sgrid = indices*2.**-cords return sgrid
[ "numpy.array", "numpy.prod" ]
[((1165, 1180), 'numpy.array', 'np.array', (['cords'], {}), '(cords)\n', (1173, 1180), True, 'import numpy as np\n'), ((1336, 1359), 'numpy.prod', 'np.prod', (['grid.shape[1:]'], {}), '(grid.shape[1:])\n', (1343, 1359), True, 'import numpy as np\n')]
import ipinfo import numpy as np import re from rich.console import Console from rich.table import Column, Table import sys import time IPINFO_TOKEN = "<PASSWORD>_TOKEN" def parse_line(line: str): regex = r'[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}.[0-9]{3}Z CLOSE host=([a-zA-Z0-9]{0,4}:[a-zA-Z0-9]{0,4}:[a-zA-Z0-9]{0,4}:[a-zA-Z0-9]{0,4}(:|.)[a-zA-Z0-9]{0,4}(:|.)[a-zA-Z0-9]{0,4}(:|.)[a-zA-Z0-9]{0,4}) port=[0-9]{1,5} fd=[0-9]{1,4} time=([0-9]{1,7}.[0-9]{1,3}) bytes=([0-9]{1,6})' search = re.search(regex, line, re.IGNORECASE) ip = search.group(1) time = float(search.group(5)) sent_bytes = int(search.group(6)) return (ip, time, sent_bytes) def main(filename: str): print("reading") with open(filename, "r") as f: lines = f.readlines() handler = ipinfo.getHandler(IPINFO_TOKEN) times = [] sent_bytes = [] countries = {} ip_batch = [] # prep countries counter for c in handler.countries.keys(): countries[c] = 0 print("parsing") for l in lines: if "CLOSE host=" in l: try: result = parse_line(l) except AttributeError: continue ip_batch.append(result[0].replace("::ffff:", "") + "/country") times.append(result[1]) sent_bytes.append(result[2]) print("getting countries") batch_result = handler.getBatchDetails(ip_batch) for i in ip_batch: result = batch_result[i] if isinstance(result, str): countries[result] = countries[result] + 1 ordered_countries = sorted(countries.items(), key=lambda x:x[1], reverse=True) time_format_string = '%H:%M:%S' max_time = time.strftime(time_format_string, time.gmtime(max(times))) min_time = time.strftime(time_format_string, time.gmtime(min(times))) median_time = time.strftime(time_format_string, time.gmtime(np.median(times))) mean_time = time.strftime(time_format_string, time.gmtime(np.mean(times))) std_time = time.strftime(time_format_string, time.gmtime(np.std(times))) max_bytes = max(sent_bytes) min_bytes = min(sent_bytes) median_bytes = np.median(sent_bytes) mean_bytes = np.mean(sent_bytes) std_bytes = np.std(sent_bytes) console = Console() table = Table(show_header=True, header_style="bold dim") table.add_column("Top 5 Countries") table.add_column("Wasted Time Stats") table.add_column("Sent Bytes Stats") table.add_row(f"{handler.countries[ordered_countries[0][0]]}: [bold]{ordered_countries[0][1]}[/bold]", f"↑ [bold]{max_time}[/bold]", f"↑ [bold]{max_bytes}[/bold]") table.add_row(f"{handler.countries[ordered_countries[1][0]]}: [bold]{ordered_countries[1][1]}[/bold]", f"M [bold]{median_time}[/bold]", f"M [bold]{median_bytes:.2f}[/bold]") table.add_row(f"{handler.countries[ordered_countries[2][0]]}: [bold]{ordered_countries[2][1]}[/bold]", f"x̄ [bold]{mean_time}[/bold]", f"x̄ [bold]{mean_bytes:.2f}[/bold]") table.add_row(f"{handler.countries[ordered_countries[3][0]]}: [bold]{ordered_countries[3][1]}[/bold]", f"σ [bold]{std_time}[/bold]", f"σ [bold]{std_bytes:.2f}[/bold]") table.add_row(f"{handler.countries[ordered_countries[4][0]]}: [bold]{ordered_countries[4][1]}[/bold]", f"↓ [bold]{min_time}[/bold]", f"↓ [bold]{min_bytes}[/bold]") console.print(table) if __name__ == "__main__": main(sys.argv[1])
[ "numpy.median", "numpy.std", "numpy.mean", "rich.console.Console", "re.search", "rich.table.Table", "ipinfo.getHandler" ]
[((515, 552), 're.search', 're.search', (['regex', 'line', 're.IGNORECASE'], {}), '(regex, line, re.IGNORECASE)\n', (524, 552), False, 'import re\n'), ((825, 856), 'ipinfo.getHandler', 'ipinfo.getHandler', (['IPINFO_TOKEN'], {}), '(IPINFO_TOKEN)\n', (842, 856), False, 'import ipinfo\n'), ((2220, 2241), 'numpy.median', 'np.median', (['sent_bytes'], {}), '(sent_bytes)\n', (2229, 2241), True, 'import numpy as np\n'), ((2259, 2278), 'numpy.mean', 'np.mean', (['sent_bytes'], {}), '(sent_bytes)\n', (2266, 2278), True, 'import numpy as np\n'), ((2295, 2313), 'numpy.std', 'np.std', (['sent_bytes'], {}), '(sent_bytes)\n', (2301, 2313), True, 'import numpy as np\n'), ((2333, 2342), 'rich.console.Console', 'Console', ([], {}), '()\n', (2340, 2342), False, 'from rich.console import Console\n'), ((2356, 2404), 'rich.table.Table', 'Table', ([], {'show_header': '(True)', 'header_style': '"""bold dim"""'}), "(show_header=True, header_style='bold dim')\n", (2361, 2404), False, 'from rich.table import Column, Table\n'), ((1957, 1973), 'numpy.median', 'np.median', (['times'], {}), '(times)\n', (1966, 1973), True, 'import numpy as np\n'), ((2038, 2052), 'numpy.mean', 'np.mean', (['times'], {}), '(times)\n', (2045, 2052), True, 'import numpy as np\n'), ((2116, 2129), 'numpy.std', 'np.std', (['times'], {}), '(times)\n', (2122, 2129), True, 'import numpy as np\n')]
import numpy as np from utils.distributions import bernoulli # ---------------------------------------------------------------------------------------------------------------------- class Recombination(object): def __init__(self): pass def recombination(self, x): pass # ---------------------------------------------------------------------------------------------------------------------- class DifferentialRecombination(Recombination): def __init__(self, type='de', bounds=(-np.infty, np.infty), params=None): super().__init__() self.type = type self.bounds = bounds assert (0. <= params['F'] <= 2.), 'F must be in [0, 2]' assert (0. < params['CR'] <= 1.), 'CR must be in (0, 1]' assert type in ['de', 'ade', 'revde', 'dex3'], 'type must be one in {de, dex3, ade, revde}' self.F = params['F'] self.CR = params['CR'] def recombination(self, x): indices_1 = np.arange(x.shape[0]) # take first parent x_1 = x[indices_1] # assign second parent (ensure) indices_2 = np.random.permutation(x.shape[0]) x_2 = x_1[indices_2] # assign third parent indices_3 = np.random.permutation(x.shape[0]) x_3 = x_2[indices_3] if self.type == 'de': y_1 = np.clip(x_1 + self.F * (x_2 - x_3), self.bounds[0], self.bounds[1]) # uniform crossover if self.CR < 1.: p_1 = bernoulli(self.CR, y_1.shape) y_1 = p_1 * y_1 + (1. - p_1) * x_1 return (y_1), (indices_1, indices_2, indices_3) elif self.type == 'revde': y_1 = np.clip(x_1 + self.F * (x_2 - x_3), self.bounds[0], self.bounds[1]) y_2 = np.clip(x_2 + self.F * (x_3 - y_1), self.bounds[0], self.bounds[1]) y_3 = np.clip(x_3 + self.F * (y_1 - y_2), self.bounds[0], self.bounds[1]) # uniform crossover if self.CR < 1.: p_1 = bernoulli(self.CR, y_1.shape) p_2 = bernoulli(self.CR, y_2.shape) p_3 = bernoulli(self.CR, y_3.shape) y_1 = p_1 * y_1 + (1. - p_1) * x_1 y_2 = p_2 * y_2 + (1. - p_2) * x_2 y_3 = p_3 * y_3 + (1. - p_3) * x_3 return (y_1, y_2, y_3), (indices_1, indices_2, indices_3) elif self.type == 'ade': y_1 = np.clip(x_1 + self.F * (x_2 - x_3), self.bounds[0], self.bounds[1]) y_2 = np.clip(x_2 + self.F * (x_3 - x_1), self.bounds[0], self.bounds[1]) y_3 = np.clip(x_3 + self.F * (x_1 - x_2), self.bounds[0], self.bounds[1]) # uniform crossover if self.CR < 1.: p_1 = bernoulli(self.CR, y_1.shape) p_2 = bernoulli(self.CR, y_2.shape) p_3 = bernoulli(self.CR, y_3.shape) y_1 = p_1 * y_1 + (1. - p_1) * x_1 y_2 = p_2 * y_2 + (1. - p_2) * x_2 y_3 = p_3 * y_3 + (1. - p_3) * x_3 return (y_1, y_2, y_3), (indices_1, indices_2, indices_3) if self.type == 'dex3': # y1 y_1 = np.clip(x_1 + self.F * (x_2 - x_3), self.bounds[0], self.bounds[1]) # uniform crossover if self.CR < 1.: p_1 = bernoulli(self.CR, y_1.shape) y_1 = p_1 * y_1 + (1. - p_1) * x_1 # y2 indices_1p = np.arange(x.shape[0]) # take first parent x_1 = x[indices_1p] # assign second parent (ensure) indices_2p = np.random.permutation(x.shape[0]) x_2 = x_1[indices_2p] # assign third parent indices_3p = np.random.permutation(x.shape[0]) x_3 = x_2[indices_3p] y_2 = np.clip(x_1 + self.F * (x_2 - x_3), self.bounds[0], self.bounds[1]) # uniform crossover if self.CR < 1.: p_2 = bernoulli(self.CR, y_2.shape) y_2 = p_2 * y_2 + (1. - p_2) * x_1 # y3 indices_1p = np.arange(x.shape[0]) # take first parent x_1 = x[indices_1p] # assign second parent (ensure) indices_2p = np.random.permutation(x.shape[0]) x_2 = x_1[indices_2p] # assign third parent indices_3p = np.random.permutation(x.shape[0]) x_3 = x_2[indices_3p] y_3 = np.clip(x_1 + self.F * (x_2 - x_3), self.bounds[0], self.bounds[1]) # uniform crossover if self.CR < 1.: p_3 = bernoulli(self.CR, y_3.shape) y_3 = p_3 * y_3 + (1. - p_3) * x_1 return (y_1, y_2, y_3), (indices_1, indices_2, indices_3) else: raise ValueError('Wrong name of the differential mutation!')
[ "numpy.random.permutation", "numpy.arange", "utils.distributions.bernoulli", "numpy.clip" ]
[((970, 991), 'numpy.arange', 'np.arange', (['x.shape[0]'], {}), '(x.shape[0])\n', (979, 991), True, 'import numpy as np\n'), ((1107, 1140), 'numpy.random.permutation', 'np.random.permutation', (['x.shape[0]'], {}), '(x.shape[0])\n', (1128, 1140), True, 'import numpy as np\n'), ((1220, 1253), 'numpy.random.permutation', 'np.random.permutation', (['x.shape[0]'], {}), '(x.shape[0])\n', (1241, 1253), True, 'import numpy as np\n'), ((1332, 1399), 'numpy.clip', 'np.clip', (['(x_1 + self.F * (x_2 - x_3))', 'self.bounds[0]', 'self.bounds[1]'], {}), '(x_1 + self.F * (x_2 - x_3), self.bounds[0], self.bounds[1])\n', (1339, 1399), True, 'import numpy as np\n'), ((3164, 3231), 'numpy.clip', 'np.clip', (['(x_1 + self.F * (x_2 - x_3))', 'self.bounds[0]', 'self.bounds[1]'], {}), '(x_1 + self.F * (x_2 - x_3), self.bounds[0], self.bounds[1])\n', (3171, 3231), True, 'import numpy as np\n'), ((3440, 3461), 'numpy.arange', 'np.arange', (['x.shape[0]'], {}), '(x.shape[0])\n', (3449, 3461), True, 'import numpy as np\n'), ((3595, 3628), 'numpy.random.permutation', 'np.random.permutation', (['x.shape[0]'], {}), '(x.shape[0])\n', (3616, 3628), True, 'import numpy as np\n'), ((3722, 3755), 'numpy.random.permutation', 'np.random.permutation', (['x.shape[0]'], {}), '(x.shape[0])\n', (3743, 3755), True, 'import numpy as np\n'), ((3809, 3876), 'numpy.clip', 'np.clip', (['(x_1 + self.F * (x_2 - x_3))', 'self.bounds[0]', 'self.bounds[1]'], {}), '(x_1 + self.F * (x_2 - x_3), self.bounds[0], self.bounds[1])\n', (3816, 3876), True, 'import numpy as np\n'), ((4085, 4106), 'numpy.arange', 'np.arange', (['x.shape[0]'], {}), '(x.shape[0])\n', (4094, 4106), True, 'import numpy as np\n'), ((4240, 4273), 'numpy.random.permutation', 'np.random.permutation', (['x.shape[0]'], {}), '(x.shape[0])\n', (4261, 4273), True, 'import numpy as np\n'), ((4367, 4400), 'numpy.random.permutation', 'np.random.permutation', (['x.shape[0]'], {}), '(x.shape[0])\n', (4388, 4400), True, 'import numpy as np\n'), ((4454, 4521), 'numpy.clip', 'np.clip', (['(x_1 + self.F * (x_2 - x_3))', 'self.bounds[0]', 'self.bounds[1]'], {}), '(x_1 + self.F * (x_2 - x_3), self.bounds[0], self.bounds[1])\n', (4461, 4521), True, 'import numpy as np\n'), ((1484, 1513), 'utils.distributions.bernoulli', 'bernoulli', (['self.CR', 'y_1.shape'], {}), '(self.CR, y_1.shape)\n', (1493, 1513), False, 'from utils.distributions import bernoulli\n'), ((1680, 1747), 'numpy.clip', 'np.clip', (['(x_1 + self.F * (x_2 - x_3))', 'self.bounds[0]', 'self.bounds[1]'], {}), '(x_1 + self.F * (x_2 - x_3), self.bounds[0], self.bounds[1])\n', (1687, 1747), True, 'import numpy as np\n'), ((1766, 1833), 'numpy.clip', 'np.clip', (['(x_2 + self.F * (x_3 - y_1))', 'self.bounds[0]', 'self.bounds[1]'], {}), '(x_2 + self.F * (x_3 - y_1), self.bounds[0], self.bounds[1])\n', (1773, 1833), True, 'import numpy as np\n'), ((1852, 1919), 'numpy.clip', 'np.clip', (['(x_3 + self.F * (y_1 - y_2))', 'self.bounds[0]', 'self.bounds[1]'], {}), '(x_3 + self.F * (y_1 - y_2), self.bounds[0], self.bounds[1])\n', (1859, 1919), True, 'import numpy as np\n'), ((3316, 3345), 'utils.distributions.bernoulli', 'bernoulli', (['self.CR', 'y_1.shape'], {}), '(self.CR, y_1.shape)\n', (3325, 3345), False, 'from utils.distributions import bernoulli\n'), ((3961, 3990), 'utils.distributions.bernoulli', 'bernoulli', (['self.CR', 'y_2.shape'], {}), '(self.CR, y_2.shape)\n', (3970, 3990), False, 'from utils.distributions import bernoulli\n'), ((4606, 4635), 'utils.distributions.bernoulli', 'bernoulli', (['self.CR', 'y_3.shape'], {}), '(self.CR, y_3.shape)\n', (4615, 4635), False, 'from utils.distributions import bernoulli\n'), ((2004, 2033), 'utils.distributions.bernoulli', 'bernoulli', (['self.CR', 'y_1.shape'], {}), '(self.CR, y_1.shape)\n', (2013, 2033), False, 'from utils.distributions import bernoulli\n'), ((2056, 2085), 'utils.distributions.bernoulli', 'bernoulli', (['self.CR', 'y_2.shape'], {}), '(self.CR, y_2.shape)\n', (2065, 2085), False, 'from utils.distributions import bernoulli\n'), ((2108, 2137), 'utils.distributions.bernoulli', 'bernoulli', (['self.CR', 'y_3.shape'], {}), '(self.CR, y_3.shape)\n', (2117, 2137), False, 'from utils.distributions import bernoulli\n'), ((2414, 2481), 'numpy.clip', 'np.clip', (['(x_1 + self.F * (x_2 - x_3))', 'self.bounds[0]', 'self.bounds[1]'], {}), '(x_1 + self.F * (x_2 - x_3), self.bounds[0], self.bounds[1])\n', (2421, 2481), True, 'import numpy as np\n'), ((2500, 2567), 'numpy.clip', 'np.clip', (['(x_2 + self.F * (x_3 - x_1))', 'self.bounds[0]', 'self.bounds[1]'], {}), '(x_2 + self.F * (x_3 - x_1), self.bounds[0], self.bounds[1])\n', (2507, 2567), True, 'import numpy as np\n'), ((2586, 2653), 'numpy.clip', 'np.clip', (['(x_3 + self.F * (x_1 - x_2))', 'self.bounds[0]', 'self.bounds[1]'], {}), '(x_3 + self.F * (x_1 - x_2), self.bounds[0], self.bounds[1])\n', (2593, 2653), True, 'import numpy as np\n'), ((2738, 2767), 'utils.distributions.bernoulli', 'bernoulli', (['self.CR', 'y_1.shape'], {}), '(self.CR, y_1.shape)\n', (2747, 2767), False, 'from utils.distributions import bernoulli\n'), ((2790, 2819), 'utils.distributions.bernoulli', 'bernoulli', (['self.CR', 'y_2.shape'], {}), '(self.CR, y_2.shape)\n', (2799, 2819), False, 'from utils.distributions import bernoulli\n'), ((2842, 2871), 'utils.distributions.bernoulli', 'bernoulli', (['self.CR', 'y_3.shape'], {}), '(self.CR, y_3.shape)\n', (2851, 2871), False, 'from utils.distributions import bernoulli\n')]
from __future__ import annotations from typing import Optional import numpy as np from .transformation import Transformation class TransformationWithCovariance(Transformation): """Light weight transformation class with added covariance propagation.""" def __init__(self, *, tran_w_cov: Optional[TransformationWithCovariance] = None, covariance: Optional[np.ndarray] = None, init_cov_to_zero: bool = False, **kwargs) -> None: """Constructor with several options Args: tran_w_cov (Optional[TransformationWithCovariance]): an existing instance of this class. (copy construction) covariance (np.ndarray): the covariance matrix init_cov_to_zero (bool): whether or not to initialize covariance to zero; defaults to False. """ # copy construction if tran_w_cov is not None: self._covariance = np.copy(tran_w_cov.cov()) self._covariance_set = tran_w_cov.covariance_set() super().__init__(transformation=tran_w_cov) return super().__init__(**kwargs) # construction from a given covariance matrix if covariance is not None: # TODO assert that the covariance shape is consistent with the underlying transformation self._covariance = covariance self._covariance_set = True return # default construction self._covariance = np.zeros((6, 6)) # TODO make this the same shape as the underlying transformation self._covariance_set = init_cov_to_zero def cov(self) -> np.ndarray: """Returns a reference to the covariance matrix.""" if not self._covariance_set: raise RuntimeError("Covariance accessed before being set.") return self._covariance def covariance_set(self) -> bool: """Returns whether the covariance has been set.""" return self._covariance_set def set_covariance(self, cov: np.ndarray) -> None: """Sets the 6x6 covariance matrix. Args: cov: the 6x6 covariance matrix """ assert cov.shape[:-2] == self._C_ba.shape[:-2] and cov.shape[-2:] == (6, 6) self._covariance = cov self._covariance_set = True def set_zero_covariance(self) -> None: """Sets the covariance to zero.""" self._covariance = np.zeros_like(*self._C_ba.shape[:-2], 6, 6) self._covariance_set = True def inverse(self) -> TransformationWithCovariance: """Returns the inverse of this transformation including the covariance.""" temp = TransformationWithCovariance(transformation=super().inverse()) adjoint_of_inverse = temp.adjoint() temp.set_covariance(adjoint_of_inverse @ self._covariance @ adjoint_of_inverse.swapaxes(-2, -1)) temp.covariance_set = self._covariance_set return temp
[ "numpy.zeros_like", "numpy.zeros" ]
[((1403, 1419), 'numpy.zeros', 'np.zeros', (['(6, 6)'], {}), '((6, 6))\n', (1411, 1419), True, 'import numpy as np\n'), ((2260, 2303), 'numpy.zeros_like', 'np.zeros_like', (['*self._C_ba.shape[:-2]', '(6)', '(6)'], {}), '(*self._C_ba.shape[:-2], 6, 6)\n', (2273, 2303), True, 'import numpy as np\n')]
# <NAME> # 17CS30033 # The functions are written in the order of the questions and solution to, for example 1a is named as _1a_plot import numpy as np import pandas as pd from matplotlib import pyplot as plt from copy import copy import json # loading training data try: train_data = pd.read_csv('train.csv') except FileNotFoundError: train_data = pd.read_csv(input('Enter path to training data: ')) train_data_feature = train_data['Feature'].to_numpy() train_data_label = train_data[' Label'].to_numpy() # loading testing data try: test_data = pd.read_csv('test.csv') except FileNotFoundError: test_data = pd.read_csv(input('Enter path to test data: ')) test_data_feature = test_data['Feature'].to_numpy() test_data_label = test_data[' Label'].to_numpy() # global variable to store training error, test error and predicted parameters # index 0 corresponds to polynomial of degree 1 and so on all_train_error = [] all_test_error = [] predicted_parameters = [] # highest degree polynomial to build starting from 0 till_n = 9 learning_rate = 0.05 # size of the training data m = train_data_feature.size # ====================== # Helper Functions Below # ====================== # calculates polynomial based on given values and coefficients def poly_calc(x, coeffs): o = len(coeffs) y = 0 for i in range(o): y += coeffs[i]*x**i return y # taking variables, returns the cost def cost_function(X, Y, m, coeffs): # calculates sigma of polynomial values over all X minus Y sum_ = sum([(poly_calc(X.iloc[ind], coeffs)-Y.iloc[ind])**2 for ind in range(m)]) return sum_ / (2*m) # returns best, worst curve based on training data error def get_extreme_curves(): # loading data from json files with open("test_error.json", 'r') as f: all_test_error = json.load(f) with open("train_error.json", 'r') as f: all_train_error = json.load(f) with open("parameters.json", 'r') as f: predicted_parameters = json.load(f) best_train_curve = None worst_train_curve = None min_train_error = min(all_train_error) max_train_error = max(all_train_error) for index, train_error in enumerate(all_train_error): if train_error == min_train_error: best_train_curve = predicted_parameters[index] if train_error == max_train_error: worst_train_curve = predicted_parameters[index] return np.array(best_train_curve), np.array(worst_train_curve) # ========================= # Solutions Functions Below # ========================= # plotting data, answer to 1a def _1a_plot(): training = True for data in [train_data, test_data]: # print(train_data.describe()) plt.scatter(data['Feature'], data[' Label']) plt.xlabel("Feature") plt.ylabel("Label") if training: plt.title("Training Data") training = False else: plt.title("Testing Data") plt.show() # fitting curve with learning rate 0.05, answer to 1b def _1b_fitting(): # varying n from 1 to 9 for n in range(1, till_n+1): print(f"=========== Polynomial Degree {n} ===========") # creating numpy vector with feature data X = np.zeros(shape=(m,n+1)) for i in range(m): for j in range(n+1): X[i][j] = np.power(train_data_feature[i], j) # setting initial value of the parameters as 1 coeff_vals = np.ones(n+1) # stores previous cost prev_jtheta = None # calculate loss loss = np.dot(X, coeff_vals) - train_data_label # current cost cur_jtheta = np.sum(loss ** 2) / (2 * m) # setting convergence when the difference between consecutive error is less than 0.00000001 while (prev_jtheta is None or abs(prev_jtheta - cur_jtheta) > 0.00000001): # gradient descent with vector notation, simultaneous calculation descent_vals = np.dot(X.transpose(), loss) * (learning_rate / m) # update all coefficients with descent coeff_vals = coeff_vals - descent_vals prev_jtheta = cur_jtheta # calculate new cost loss = np.dot(X, coeff_vals) - train_data_label cur_jtheta = np.sum(loss ** 2) / (2 * m) print(f"Difference between consecutive costs: {abs(prev_jtheta - cur_jtheta)}\t", end="\r", flush=True) predicted_parameters.append(coeff_vals.tolist()) all_train_error.append(cur_jtheta.tolist()) test_error = cost_function(test_data['Feature'], test_data[' Label'], len(test_data.index), coeff_vals) all_test_error.append(test_error) print(f"Parameters: {coeff_vals}\t\t") print(f"Squared Error on Test Data: {test_error}\n") # generating predicted values and saving as predicted_labels_n.csv where n is the degree of polynomial data = [[x, poly_calc(x, coeff_vals)] for x in test_data['Feature']] predicted_labels = pd.DataFrame(data, columns=["Feature", "Label"]) predicted_labels.to_csv(f'predicted_labels_{n}.csv', index=False) # storing all predicted polynomials in "predicted_parameters.txt" with open("predicted_parameters.txt", "w+") as f: for index, parameter in enumerate(predicted_parameters): f.write(f"Predicted Parameters for Degree {index+1}: {parameter}\n") # saving parameters to load in later functions with open("parameters.json", 'w+') as f: json.dump(predicted_parameters, f) # saving train errors to load in later functions with open("train_error.json", 'w+') as f: json.dump(all_train_error, f) # saving test errors to load in later functions with open("test_error.json", 'w+') as f: json.dump(all_test_error, f) # plotting the predicted polynomials, answer to 2a def _2a_plots(): # loading data from json file with open("parameters.json", 'r') as f: predicted_parameters = json.load(f) for index, coeffs in enumerate(predicted_parameters): plot_on = np.linspace(train_data['Feature'].min(), train_data['Feature'].max()) plt.plot(plot_on, poly_calc(plot_on, coeffs)) plt.xlabel("Feature") plt.ylabel("Label") plt.title(f"Polynomial of Degree {index+1}") # print(f"Plot for polynomial with coefficients {coeffs}") plt.show() # plotting the squared error for training and test data for the values of n def _2b_plots(): # loading data from json files with open("test_error.json", 'r') as f: all_test_error = json.load(f) with open("train_error.json", 'r') as f: all_train_error = json.load(f) labels = [str(x) for x in range(1,till_n+1)] x = np.arange(len(labels)) # the label locations width = 0.5 # the width of the bars fig, ax = plt.subplots() rects1 = ax.bar(x - width/2, all_train_error, width, label='Train Error') rects2 = ax.bar(x + width/2, all_test_error, width, label='Test Error') # Add some text for labels, title and custom x-axis tick labels, etc. ax.set_ylabel('Error') ax.set_xlabel('n -->') ax.set_title('Train and Test Errors For Varying n') ax.set_xticks(x) ax.set_xticklabels(labels) ax.legend() # Attach a text label above each bar in *rects*, displaying its height def autolabel(rects): for rect in rects: height = rect.get_height() ax.annotate('{0:.7f}'.format(height), xy=(rect.get_x() + rect.get_width() / 2, height), xytext=(0, 3), # 3 points vertical offset textcoords="offset points", ha='center', va='bottom') autolabel(rects1) autolabel(rects2) fig.tight_layout() plt.show() # solution to part 3a, lasso regularisation # the function is very similar to 2b fitting except that we do not start from all 1s # and used the improvised cost function def _3a_lasso(): best_curve, worst_curve = get_extreme_curves() result_curves = [] lasso_training_errors = [] lasso_test_errors = [] is_best = True for curve in [best_curve, worst_curve]: if is_best: curve_type = "Best Curve" is_best = False else: curve_type = "Worst Curve" n = len(curve) - 1 # create numpy vector from feature data X = np.zeros(shape=(m,n+1)) for i in range(m): for j in range(n+1): X[i][j] = np.power(train_data_feature[i], j) curves = [] train_errors = [] test_errors = [] for lambd in [.25, .5, .75, 1]: print(f"=========== Lasso Regularisation {curve_type}: Polynomial Degree {n} Lambda {lambd} ===========") print(f"Polynomial is: {curve}") coeff_vals = copy(curve) prev_jtheta = None loss = np.dot(X, coeff_vals) - train_data_label cur_jtheta = (np.sum(loss ** 2) + (lambd * sum([abs(x) for x in coeff_vals])))/ (2 * m) # setting convergence when the difference between consecutive error is less than 0.00000001 while (prev_jtheta is None or abs(prev_jtheta - cur_jtheta) > 0.00000001): descent_vals = np.dot(X.transpose(), loss) * (learning_rate / m) # using regularised descent values, saving zeroth term to put back as in later on. initial_coeff = coeff_vals[0] coeff_vals = (coeff_vals * (1-learning_rate *(lambd/m))) - descent_vals coeff_vals[0] = initial_coeff - descent_vals[0] prev_jtheta = cur_jtheta loss = np.dot(X, coeff_vals) - train_data_label cur_jtheta = (np.sum(loss ** 2) + (lambd * sum([abs(x) for x in coeff_vals])))/ (2 * m) print(f"Difference between consecutive costs: {abs(prev_jtheta - cur_jtheta)}\t", end="\r", flush=True) curves.append(coeff_vals) test_error = cost_function(test_data['Feature'], test_data[' Label'], len(test_data.index), coeff_vals) + ((lambd * sum([abs(x) for x in coeff_vals])) / (2 * len(test_data.index))) # storing squared (not lasso) train and test errors for later use in plotting train_errors.append(cur_jtheta - ((lambd * sum([abs(x) for x in coeff_vals])) / (2 * m))) test_errors.append(test_error - ((lambd * sum([abs(x) for x in coeff_vals])) / (2 * len(test_data.index)))) print(f"New Parameters: {coeff_vals}\t\t") print(f"Lasso Error on Test Data: {test_error}") print(f"Squared Error on Test Data: {test_error - ((lambd * sum([abs(x) for x in coeff_vals])) / (2 * len(test_data.index)))}\n") result_curves.append(curves) lasso_training_errors.append(train_errors) lasso_test_errors.append(test_errors) # creating the graphs for all lambda for each of the two curves for i in range(2): # plotting test and train error for varying lambda labels = [0.25, 0.5, 0.75, 1] x = np.arange(len(labels)) # the label locations width = 0.5 # the width of the bars fig, ax = plt.subplots() rects1 = ax.bar(x - width/2, lasso_training_errors[i], width, label='Lasso Train Error') rects2 = ax.bar(x + width/2, lasso_test_errors[i], width, label='Lasso Test Error') # Add some text for labels, title and custom x-axis tick labels, etc. ax.set_ylabel('Error') ax.set_xlabel('lambda -->') if i == 0: title = 'Best Curve: Train and Test Errors For Varying Lambda With Lasso' if i == 1: title = 'Worst Curve: Train and Test Errors For Varying Lambda With Lasso' ax.set_title(title) ax.set_xticks(x) ax.set_xticklabels(labels) ax.legend() # display height of reactange def autolabel(rects): for rect in rects: height = rect.get_height() ax.annotate('{0:.7f}'.format(height), xy=(rect.get_x() + rect.get_width() / 2, height), xytext=(0, 3), textcoords="offset points", ha='center', va='bottom') autolabel(rects1) autolabel(rects2) fig.tight_layout() plt.show() # solution to part 3b, ridge regularisation # the function is very similar to 2b fitting except that we do not start from all 1s # and used the improvised cost function def _3b_ridge(): best_curve, worst_curve = get_extreme_curves() result_curves = [] ridge_training_errors = [] ridge_test_errors = [] is_best = True for curve in [best_curve, worst_curve]: n = len(curve) - 1 X = np.zeros(shape=(m,n+1)) for i in range(m): for j in range(n+1): X[i][j] = np.power(train_data_feature[i], j) if is_best: curve_type = "Best Curve" is_best = False else: curve_type = "Worst Curve" curves = [] train_errors = [] test_errors = [] for lambd in [.25, .5, .75, 1]: print(f"=========== Ridge Regularisation {curve_type}: Polynomial Degree {n} Lambda {lambd} ===========") print(f"Polynomial is: {curve}") coeff_vals = copy(curve) prev_jtheta = None loss = np.dot(X, coeff_vals) - train_data_label cur_jtheta = (np.sum(loss ** 2) + (lambd * sum([x**2 for x in coeff_vals])))/ (2 * m) # setting convergence when the difference between consecutive error is less than 0.00000001 while (prev_jtheta is None or abs(prev_jtheta - cur_jtheta) > 0.00000001): descent_vals = np.dot(X.transpose(), loss) * (learning_rate / m) # using regularised descent values, saving zeroth term to put back as in later on. initial_coeff = coeff_vals[0] coeff_vals = (coeff_vals * (1-learning_rate * (lambd/m))) - descent_vals coeff_vals[0] = initial_coeff - descent_vals[0] prev_jtheta = cur_jtheta loss = np.dot(X, coeff_vals) - train_data_label cur_jtheta = (np.sum(loss ** 2) + (lambd * sum([x**2 for x in coeff_vals])))/ (2 * m) print(f"Difference between consecutive costs: {abs(prev_jtheta - cur_jtheta)}\t", end="\r", flush=True) test_error = cost_function(test_data['Feature'], test_data[' Label'], len(test_data.index), coeff_vals) + ((lambd * sum([x**2 for x in coeff_vals])) / (2 * len(test_data.index))) curves.append(coeff_vals) # storing squared train and test error for plotting train_errors.append(cur_jtheta - ((lambd * sum([x**2 for x in coeff_vals])) / (2 * m))) test_errors.append(test_error - ((lambd * sum([x**2 for x in coeff_vals])) / (2 * len(test_data.index)))) print(f"New Parameters: {coeff_vals}\t\t") print(f"Ridge Error on Test Data: {test_error}") print(f"Squared Error on Test Data: {test_error - ((lambd * sum([x**2 for x in coeff_vals])) / (2 * len(test_data.index)))}\n") result_curves.append(curves) ridge_training_errors.append(train_errors) ridge_test_errors.append(test_errors) # creating the graphs for all lambda for each of the two curves for i in range(2): # plotting test and train error for varying lambda labels = [0.25, 0.5, 0.75, 1] x = np.arange(len(labels)) # the label locations width = 0.5 # the width of the bars fig, ax = plt.subplots() rects1 = ax.bar(x - width/2, ridge_training_errors[i], width, label='Ridge Train Error') rects2 = ax.bar(x + width/2, ridge_test_errors[i], width, label='Ridge Test Error') # Add some text for labels, title and custom x-axis tick labels, etc. ax.set_ylabel('Error') ax.set_xlabel('lambda -->') if i == 0: title = 'Best Curve: Train and Test Errors For Varying Lambda With Ridge' if i == 1: title = 'Worst Curve: Train and Test Errors For Varying Lambda With Ridge' ax.set_title(title) ax.set_xticks(x) ax.set_xticklabels(labels) ax.legend() # display height of reactange def autolabel(rects): for rect in rects: height = rect.get_height() ax.annotate('{0:.7f}'.format(height), xy=(rect.get_x() + rect.get_width() / 2, height), xytext=(0, 3), textcoords="offset points", ha='center', va='bottom') autolabel(rects1) autolabel(rects2) fig.tight_layout() plt.show() # Comment parts which are not to be run. # Note: Parts 2a, 2b, 3a, 3b depend on part 1b and hence if they are run without part 1b, they'll load data from JSON files. _1a_plot() _1b_fitting() _2a_plots() _2b_plots() _3a_lasso() _3b_ridge()
[ "pandas.DataFrame", "json.dump", "matplotlib.pyplot.title", "json.load", "matplotlib.pyplot.show", "numpy.sum", "pandas.read_csv", "matplotlib.pyplot.scatter", "numpy.power", "numpy.zeros", "numpy.ones", "copy.copy", "numpy.array", "numpy.dot", "matplotlib.pyplot.ylabel", "matplotlib.pyplot.xlabel", "matplotlib.pyplot.subplots" ]
[((290, 314), 'pandas.read_csv', 'pd.read_csv', (['"""train.csv"""'], {}), "('train.csv')\n", (301, 314), True, 'import pandas as pd\n'), ((560, 583), 'pandas.read_csv', 'pd.read_csv', (['"""test.csv"""'], {}), "('test.csv')\n", (571, 583), True, 'import pandas as pd\n'), ((6868, 6882), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (6880, 6882), True, 'from matplotlib import pyplot as plt\n'), ((7791, 7801), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (7799, 7801), True, 'from matplotlib import pyplot as plt\n'), ((1820, 1832), 'json.load', 'json.load', (['f'], {}), '(f)\n', (1829, 1832), False, 'import json\n'), ((1904, 1916), 'json.load', 'json.load', (['f'], {}), '(f)\n', (1913, 1916), False, 'import json\n'), ((1992, 2004), 'json.load', 'json.load', (['f'], {}), '(f)\n', (2001, 2004), False, 'import json\n'), ((2422, 2448), 'numpy.array', 'np.array', (['best_train_curve'], {}), '(best_train_curve)\n', (2430, 2448), True, 'import numpy as np\n'), ((2450, 2477), 'numpy.array', 'np.array', (['worst_train_curve'], {}), '(worst_train_curve)\n', (2458, 2477), True, 'import numpy as np\n'), ((2718, 2762), 'matplotlib.pyplot.scatter', 'plt.scatter', (["data['Feature']", "data[' Label']"], {}), "(data['Feature'], data[' Label'])\n", (2729, 2762), True, 'from matplotlib import pyplot as plt\n'), ((2771, 2792), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Feature"""'], {}), "('Feature')\n", (2781, 2792), True, 'from matplotlib import pyplot as plt\n'), ((2801, 2820), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Label"""'], {}), "('Label')\n", (2811, 2820), True, 'from matplotlib import pyplot as plt\n'), ((2970, 2980), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (2978, 2980), True, 'from matplotlib import pyplot as plt\n'), ((3242, 3268), 'numpy.zeros', 'np.zeros', ([], {'shape': '(m, n + 1)'}), '(shape=(m, n + 1))\n', (3250, 3268), True, 'import numpy as np\n'), ((3463, 3477), 'numpy.ones', 'np.ones', (['(n + 1)'], {}), '(n + 1)\n', (3470, 3477), True, 'import numpy as np\n'), ((5013, 5061), 'pandas.DataFrame', 'pd.DataFrame', (['data'], {'columns': "['Feature', 'Label']"}), "(data, columns=['Feature', 'Label'])\n", (5025, 5061), True, 'import pandas as pd\n'), ((5510, 5544), 'json.dump', 'json.dump', (['predicted_parameters', 'f'], {}), '(predicted_parameters, f)\n', (5519, 5544), False, 'import json\n'), ((5652, 5681), 'json.dump', 'json.dump', (['all_train_error', 'f'], {}), '(all_train_error, f)\n', (5661, 5681), False, 'import json\n'), ((5787, 5815), 'json.dump', 'json.dump', (['all_test_error', 'f'], {}), '(all_test_error, f)\n', (5796, 5815), False, 'import json\n'), ((6003, 6015), 'json.load', 'json.load', (['f'], {}), '(f)\n', (6012, 6015), False, 'import json\n'), ((6224, 6245), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Feature"""'], {}), "('Feature')\n", (6234, 6245), True, 'from matplotlib import pyplot as plt\n'), ((6254, 6273), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Label"""'], {}), "('Label')\n", (6264, 6273), True, 'from matplotlib import pyplot as plt\n'), ((6282, 6328), 'matplotlib.pyplot.title', 'plt.title', (['f"""Polynomial of Degree {index + 1}"""'], {}), "(f'Polynomial of Degree {index + 1}')\n", (6291, 6328), True, 'from matplotlib import pyplot as plt\n'), ((6402, 6412), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (6410, 6412), True, 'from matplotlib import pyplot as plt\n'), ((6611, 6623), 'json.load', 'json.load', (['f'], {}), '(f)\n', (6620, 6623), False, 'import json\n'), ((6695, 6707), 'json.load', 'json.load', (['f'], {}), '(f)\n', (6704, 6707), False, 'import json\n'), ((8410, 8436), 'numpy.zeros', 'np.zeros', ([], {'shape': '(m, n + 1)'}), '(shape=(m, n + 1))\n', (8418, 8436), True, 'import numpy as np\n'), ((11206, 11220), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (11218, 11220), True, 'from matplotlib import pyplot as plt\n'), ((12359, 12369), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (12367, 12369), True, 'from matplotlib import pyplot as plt\n'), ((12791, 12817), 'numpy.zeros', 'np.zeros', ([], {'shape': '(m, n + 1)'}), '(shape=(m, n + 1))\n', (12799, 12817), True, 'import numpy as np\n'), ((15689, 15703), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (15701, 15703), True, 'from matplotlib import pyplot as plt\n'), ((16842, 16852), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (16850, 16852), True, 'from matplotlib import pyplot as plt\n'), ((2854, 2880), 'matplotlib.pyplot.title', 'plt.title', (['"""Training Data"""'], {}), "('Training Data')\n", (2863, 2880), True, 'from matplotlib import pyplot as plt\n'), ((2936, 2961), 'matplotlib.pyplot.title', 'plt.title', (['"""Testing Data"""'], {}), "('Testing Data')\n", (2945, 2961), True, 'from matplotlib import pyplot as plt\n'), ((3574, 3595), 'numpy.dot', 'np.dot', (['X', 'coeff_vals'], {}), '(X, coeff_vals)\n', (3580, 3595), True, 'import numpy as np\n'), ((3659, 3676), 'numpy.sum', 'np.sum', (['(loss ** 2)'], {}), '(loss ** 2)\n', (3665, 3676), True, 'import numpy as np\n'), ((8854, 8865), 'copy.copy', 'copy', (['curve'], {}), '(curve)\n', (8858, 8865), False, 'from copy import copy\n'), ((13374, 13385), 'copy.copy', 'copy', (['curve'], {}), '(curve)\n', (13378, 13385), False, 'from copy import copy\n'), ((3352, 3386), 'numpy.power', 'np.power', (['train_data_feature[i]', 'j'], {}), '(train_data_feature[i], j)\n', (3360, 3386), True, 'import numpy as np\n'), ((4216, 4237), 'numpy.dot', 'np.dot', (['X', 'coeff_vals'], {}), '(X, coeff_vals)\n', (4222, 4237), True, 'import numpy as np\n'), ((4282, 4299), 'numpy.sum', 'np.sum', (['(loss ** 2)'], {}), '(loss ** 2)\n', (4288, 4299), True, 'import numpy as np\n'), ((8520, 8554), 'numpy.power', 'np.power', (['train_data_feature[i]', 'j'], {}), '(train_data_feature[i], j)\n', (8528, 8554), True, 'import numpy as np\n'), ((8916, 8937), 'numpy.dot', 'np.dot', (['X', 'coeff_vals'], {}), '(X, coeff_vals)\n', (8922, 8937), True, 'import numpy as np\n'), ((12901, 12935), 'numpy.power', 'np.power', (['train_data_feature[i]', 'j'], {}), '(train_data_feature[i], j)\n', (12909, 12935), True, 'import numpy as np\n'), ((13436, 13457), 'numpy.dot', 'np.dot', (['X', 'coeff_vals'], {}), '(X, coeff_vals)\n', (13442, 13457), True, 'import numpy as np\n'), ((8983, 9000), 'numpy.sum', 'np.sum', (['(loss ** 2)'], {}), '(loss ** 2)\n', (8989, 9000), True, 'import numpy as np\n'), ((9690, 9711), 'numpy.dot', 'np.dot', (['X', 'coeff_vals'], {}), '(X, coeff_vals)\n', (9696, 9711), True, 'import numpy as np\n'), ((13503, 13520), 'numpy.sum', 'np.sum', (['(loss ** 2)'], {}), '(loss ** 2)\n', (13509, 13520), True, 'import numpy as np\n'), ((14209, 14230), 'numpy.dot', 'np.dot', (['X', 'coeff_vals'], {}), '(X, coeff_vals)\n', (14215, 14230), True, 'import numpy as np\n'), ((9761, 9778), 'numpy.sum', 'np.sum', (['(loss ** 2)'], {}), '(loss ** 2)\n', (9767, 9778), True, 'import numpy as np\n'), ((14280, 14297), 'numpy.sum', 'np.sum', (['(loss ** 2)'], {}), '(loss ** 2)\n', (14286, 14297), True, 'import numpy as np\n')]
import h5py from tqdm import tqdm import librosa import numpy as np from keras.utils.np_utils import to_categorical from sklearn.utils import shuffle import cv2 import torch germanBats = { "Rhinolophus ferrumequinum": 0, "Rhinolophus hipposideros": 1, "Myotis daubentonii": 2, "Myotis brandtii": 3, "Myotis mystacinus": 4, "Myotis emarginatus": 5, "Myotis nattereri": 6, #"Myotis bechsteinii": 7, "Myotis myotis": 7, "Myotis dasycneme": 8, "Nyctalus noctula": 9, "Nyctalus leisleri": 10, "Pipistrellus pipistrellus": 11, "Pipistrellus nathusii": 12, "Pipistrellus kuhlii": 13, "Eptesicus serotinus": 14, "Eptesicus nilssonii": 15, #"Plecotus auritus": 16, #"Plecotus austriacus": 16, #"Barbastella barbastellus": 16, #"Tadarida teniotis": 16, "Miniopterus schreibersii": 16, #"Hypsugo savii": 18, "Vespertilio murinus": 17, } def slideWindow(a, size, step, resize): b = [] i = 0 pos = 0 while pos + size < len(a): pos = int(i * step) tile = a[pos : pos + size] if resize is not None: tile = cv2.resize(tile, dsize=resize, interpolation=cv2.INTER_NEAREST) b.append(tile) i+=1 return b def peak_detect(spectrogram, threshold): env = np.mean(spectrogram, axis=1) env[env < threshold] = 0 peaks = librosa.util.peak_pick(env, pre_max=3, post_max=5, pre_avg=3, post_avg=5, delta=0.6, wait=20) return env, peaks def getIndividuals(spectrogram, patch_len, mode, resize, threshold): if mode == 'slide': individuals = slideWindow(spectrogram, patch_len, int(patch_len/2), resize)[:-1] # last one is not full return individuals elif mode == 'peak_detect': individuals = [] _, peaks = peak_detect(spectrogram, threshold) for p in peaks: pos = p - int(patch_len / 2) if (pos >= 0 and len(spectrogram) >= pos+patch_len): ind = spectrogram[pos:pos+patch_len] if resize is not None: ind = cv2.resize(ind, dsize=resize, interpolation=cv2.INTER_NEAREST) individuals.append(ind) return individuals def prepareSet(prepared_set, labels, patch_len, mode, scale_factor, resize, one_hot, threshold): X_ind = [] Y_ind = [] for species in tqdm(list(labels)): S_db = np.asarray(prepared_set.get(species)) new_size = (int(S_db.shape[1] * scale_factor), int(S_db.shape[0] * scale_factor)) S_db = cv2.resize(S_db, dsize=new_size, interpolation=cv2.INTER_NEAREST) label = to_categorical(labels[species], num_classes=len(labels)) if one_hot else labels[species] ind = getIndividuals(S_db, patch_len, mode, resize, threshold) X_ind.extend(ind) Y_ind.extend([label] * len(ind)) if not mode == 'slide': X_ind, Y_ind = shuffle(X_ind, Y_ind, random_state=42) return np.asarray(X_ind), np.asarray(Y_ind) def prepare(file, labels, patch_len, mode='peak_detect', scale_factor=1.0, resize=None, one_hot=False, threshold=0): prepared_hf = h5py.File(file, 'r') X_train, Y_train = prepareSet(prepared_hf.require_group("train"), labels, patch_len, mode, scale_factor, resize, one_hot, threshold) X_test, Y_test = prepareSet(prepared_hf.require_group("test"), labels, patch_len, mode, scale_factor, resize, one_hot, threshold) X_val, Y_val = prepareSet(prepared_hf.require_group("val"), labels, patch_len, mode, scale_factor, resize, one_hot, threshold) return X_train, Y_train, X_test, Y_test, X_val, Y_val
[ "h5py.File", "librosa.util.peak_pick", "numpy.asarray", "numpy.mean", "sklearn.utils.shuffle", "cv2.resize" ]
[((1306, 1334), 'numpy.mean', 'np.mean', (['spectrogram'], {'axis': '(1)'}), '(spectrogram, axis=1)\n', (1313, 1334), True, 'import numpy as np\n'), ((1376, 1473), 'librosa.util.peak_pick', 'librosa.util.peak_pick', (['env'], {'pre_max': '(3)', 'post_max': '(5)', 'pre_avg': '(3)', 'post_avg': '(5)', 'delta': '(0.6)', 'wait': '(20)'}), '(env, pre_max=3, post_max=5, pre_avg=3, post_avg=5,\n delta=0.6, wait=20)\n', (1398, 1473), False, 'import librosa\n'), ((3135, 3155), 'h5py.File', 'h5py.File', (['file', '"""r"""'], {}), "(file, 'r')\n", (3144, 3155), False, 'import h5py\n'), ((2546, 2611), 'cv2.resize', 'cv2.resize', (['S_db'], {'dsize': 'new_size', 'interpolation': 'cv2.INTER_NEAREST'}), '(S_db, dsize=new_size, interpolation=cv2.INTER_NEAREST)\n', (2556, 2611), False, 'import cv2\n'), ((2912, 2950), 'sklearn.utils.shuffle', 'shuffle', (['X_ind', 'Y_ind'], {'random_state': '(42)'}), '(X_ind, Y_ind, random_state=42)\n', (2919, 2950), False, 'from sklearn.utils import shuffle\n'), ((2962, 2979), 'numpy.asarray', 'np.asarray', (['X_ind'], {}), '(X_ind)\n', (2972, 2979), True, 'import numpy as np\n'), ((2981, 2998), 'numpy.asarray', 'np.asarray', (['Y_ind'], {}), '(Y_ind)\n', (2991, 2998), True, 'import numpy as np\n'), ((1141, 1204), 'cv2.resize', 'cv2.resize', (['tile'], {'dsize': 'resize', 'interpolation': 'cv2.INTER_NEAREST'}), '(tile, dsize=resize, interpolation=cv2.INTER_NEAREST)\n', (1151, 1204), False, 'import cv2\n'), ((2090, 2152), 'cv2.resize', 'cv2.resize', (['ind'], {'dsize': 'resize', 'interpolation': 'cv2.INTER_NEAREST'}), '(ind, dsize=resize, interpolation=cv2.INTER_NEAREST)\n', (2100, 2152), False, 'import cv2\n')]
# 隐马尔可夫模型 # 2020/09/27 import re import jieba import numpy as np def trainParameter(filename): """ 依据训练文本统计 PI, A, B :param filename: 训练文本 :return: 模型参数 """ statusDict = {'B': 0, 'M': 1, 'E': 2, 'S': 3} # 初始化模型参数 PI = np.zeros(4) A = np.zeros((4, 4)) B = np.zeros((4, 65536)) with open(filename, encoding='utf8') as f: for line in f.readlines(): line = jieba.cut(line, cut_all=True) line = ' '.join(line) line = line.strip().split() print(line) wordLabel = [] for i in range(len(list(line))): if len(line[i]) == 1: Label = 'S' else: Label = 'B' + 'M' * (len(line[i]) - 2) + 'E' if i == 0: PI[statusDict[Label[0]]] += 1 for j in range(len(Label)): B[statusDict[Label[j]]][ord(line[i][j])] += 1 wordLabel.extend(Label) # print(wordLabel) for i in range(1, len(wordLabel)): A[statusDict[wordLabel[i-1]]][statusDict[wordLabel[i]]] += 1 S = np.sum(PI) for i in range(len(PI)): if PI[i] == 0: PI[i] = -3.14e+100 else: PI[i] = np.log(PI[i]/S) for i in range(len(A)): S = np.sum(A[i]) for j in range(len(A[i])): if A[i][j] == 0: A[i][j] = -3.14e+100 else: A[i][j] = np.log(A[i][j]/S) for i in range(len(B)): S = np.sum(len(B[i])) for j in range(len(B[i])): if B[i][j] == 0: B[i][j] = -3.14e+100 else: B[i][j] = np.log(B[i][j]/S) return PI, A, B def loadArticle(filename): """ 加载文章 :param filename: 文件路径 :return: 文章内容 """ artical = [] with open(filename, encoding='utf8') as f: for line in f.readlines(): line = line.strip() if not line: continue # 将该行放入文章列表中 artical.append(line) return artical def participle(artical, PI, A, B): """ 分词 :param artical: 分词文本 :param PI: 初始状态概率向量PI :param A: 状态转移矩阵 :param B: 观测概率矩阵 :return: 分词后的文章 """ retActical = [] for line in artical: delta = [[0 for _ in range(4)] for _ in range(len(line))] for i in range(4): delta[0][i] = PI[i] + B[i][ord(line[0])] psi = [[0 for _ in range(4)] for _ in range(len(line))] for t in range(1, len(line)): for i in range(4): tmpDelta = [0] * 4 for j in range(4): tmpDelta[j] = delta[t-1][j] + A[j][i] maxDelta = max(tmpDelta) maxDeltaIndex = tmpDelta.index(maxDelta) delta[t][i] = maxDelta + B[i][ord(line[t])] psi[t][i] = maxDeltaIndex sequence = [] i_opt = delta[len(line)-1].index(max(delta[len(line)-1])) sequence.append(i_opt) for t in range(len(line)-1, 0, -1): i_opt = psi[t][i_opt] sequence.append(i_opt) sequence.reverse() curline = '' for i in range(len(line)): curline += line[i] if (sequence[i] == 3 or sequence[i] == 2) and i != (len(line)-1): curline += '|' retActical.append(curline) return retActical if __name__ == '__main__': PI, A, B = trainParameter('./data/HMMTrainSet.txt') # 读取测试文章 artical = loadArticle('./data/testArtical.txt') # 打印原文 print('-------------------原文----------------------') for line in artical: print(line) # 进行分词 print('-------------------分词后----------------------') ret_artical = participle(artical, PI, A, B) for line in ret_artical: print(line)
[ "jieba.cut", "numpy.log", "numpy.zeros", "numpy.sum" ]
[((269, 280), 'numpy.zeros', 'np.zeros', (['(4)'], {}), '(4)\n', (277, 280), True, 'import numpy as np\n'), ((290, 306), 'numpy.zeros', 'np.zeros', (['(4, 4)'], {}), '((4, 4))\n', (298, 306), True, 'import numpy as np\n'), ((316, 336), 'numpy.zeros', 'np.zeros', (['(4, 65536)'], {}), '((4, 65536))\n', (324, 336), True, 'import numpy as np\n'), ((1224, 1234), 'numpy.sum', 'np.sum', (['PI'], {}), '(PI)\n', (1230, 1234), True, 'import numpy as np\n'), ((445, 474), 'jieba.cut', 'jieba.cut', (['line'], {'cut_all': '(True)'}), '(line, cut_all=True)\n', (454, 474), False, 'import jieba\n'), ((1445, 1457), 'numpy.sum', 'np.sum', (['A[i]'], {}), '(A[i])\n', (1451, 1457), True, 'import numpy as np\n'), ((1377, 1394), 'numpy.log', 'np.log', (['(PI[i] / S)'], {}), '(PI[i] / S)\n', (1383, 1394), True, 'import numpy as np\n'), ((1628, 1647), 'numpy.log', 'np.log', (['(A[i][j] / S)'], {}), '(A[i][j] / S)\n', (1634, 1647), True, 'import numpy as np\n'), ((1886, 1905), 'numpy.log', 'np.log', (['(B[i][j] / S)'], {}), '(B[i][j] / S)\n', (1892, 1905), True, 'import numpy as np\n')]
import threading import tensorflow as tf from tensorflow import keras from tensorflow.keras import models import cv2 import numpy as np import matplotlib.pyplot as plt import math import random import tkinter as tk ##### Input trainned model ##### model = keras.models.load_model('mnist_model1.h5') model2 = keras.models.load_model('alpha_model.h5') def find_license(image_name): imagepath = str(image_name) image = cv2.imread(imagepath) RGB_image = image[:,:,::-1] gray = cv2.cvtColor(RGB_image, cv2.COLOR_RGB2GRAY) low_threshold = 100 high_threshold = 200 edges = cv2.Canny(gray, low_threshold, high_threshold) '''gaussianblur''' kernel_size = 3 img = cv2.GaussianBlur(edges,(kernel_size, kernel_size), 0) '''make the color of the image including only white and black''' for i in range (len(img)): for j in range (len(img[0])): if img[i][j] > 0: img[i][j] = 255 '''the kernal to dilate and erode''' element1 = cv2.getStructuringElement(cv2.MORPH_RECT, (9, 7)) element2 = cv2.getStructuringElement(cv2.MORPH_RECT, (5, 3)) element3 = cv2.getStructuringElement(cv2.MORPH_RECT, (15, 5)) element4 = cv2.getStructuringElement(cv2.MORPH_RECT, (5, 10)) element5 = cv2.getStructuringElement(cv2.MORPH_RECT, (5, 5)) '''use open and close''' img = cv2.dilate(img, element1, iterations = 2) img = cv2.erode(img, element1, iterations = 2) img = cv2.erode(img, element2, iterations = 10) img = cv2.erode(img, element5, iterations = 5) img = cv2.dilate(img, element5, iterations = 5) img = cv2.dilate(img, element2, iterations = 10) img = cv2.erode(img, element3, iterations = 10) img = cv2.dilate(img, element3, iterations = 10) img = cv2.erode(img, element4, iterations = 5) img = cv2.dilate(img, element4, iterations = 5) '''get the license plate''' img_final = np.zeros((len(gray),len(gray[0]),3),np.uint32) for i in range (len(img_final)): for j in range (len(img_final[0])): if img[i][j] == 255: img_final[i][j] = RGB_image[i][j] else: img_final[i][j] = 0 '''get the coordinate of license plate''' i_site = [] j_site = [] for i in range (len(img_final)): for j in range (len(img_final[0])): if img_final[i][j][0] != 0: i_site.append(i) j_site.append(j) i_first = i_site[0] j_first = j_site[0] i_last = i_site[-1] j_last = j_site[-1] '''print the license plate''' card = img_final[i_first:i_last,j_first:j_last] card_gray = cv2.cvtColor(np.float32(card), cv2.COLOR_RGB2GRAY) ret,card_bw = cv2.threshold(card_gray,127,255,cv2.THRESH_BINARY) element = cv2.getStructuringElement(cv2.MORPH_RECT, (2, 2)) card_bw = cv2.dilate(card_bw, element, iterations = 2) card_bw = cv2.erode(card_bw, element, iterations = 2) '''erase the part of all white above''' i_allzero = [] for i in range (len(card)): count = 0 for j in range (len(card_bw[0])): if card_bw[i][j] == 0: count += 1 i_allzero.append(count) i_probable = [] for i in range (len(i_allzero)): if (int(i_allzero[i])) == 0: i_probable.append(i) '''cut the white space''' i_min = 0 i_max = 0 max_count = 0 for i in range (len(i_probable)-1): count = i_probable[i+1] - i_probable[i] if count > max_count: max_count = count i_min = i_probable[i] i_max = i_probable[i+1] card_bw = card_bw[i_min:i_max,:] '''find the white part of all i''' j_allzero = [] for i in range (len(card_bw[0])): count = 0 for j in range (len(card_bw)): if card_bw[j][i] == 0: count += 1 j_allzero.append(count) j_probable = [] for i in range (len(j_allzero)): if (int(j_allzero[i])) == 0: j_probable.append(i) '''get the word of license plate''' j_final = [] for i in range (len(j_probable)-1): if j_probable[i+1] - j_probable[i] > 1: j_final.append(j_probable[i]) j_final.append(j_probable[-1]) '''find dash,english word,number''' value = [] for i in range (len(j_final)-1): value.append(j_final[i+1]-j_final[i]) dash = min(value) index = 0 for i in range (len(value)): if value[i] == dash: dash_index = j_final[i:i+2] index = i length1 = j_final[index] - j_final[0] length2 = j_final[-1] - j_final[index+1] if length2 > length1: if len(j_final) == 9: card_eng = card_bw[:,j_final[0]:j_final[3]] card_dash = card_bw[:,j_final[3]:j_final[4]] card_num = card_bw[:,j_final[4]:] '''get the number and word of license plate''' num_1 = card_num[:,0:int((1/4)*len(card_num[0]))] num_2 = card_num[:,int((1/4)*len(card_num[0])):int((2/4)*len(card_num[0]))] num_3 = card_num[:,int((2/4)*len(card_num[0])):int((3/4)*len(card_num[0]))] num_4 = card_num[:,int((3/4)*len(card_num[0])):len(card_num[0])] alphabet_1 = card_eng[:,0:int((1/3)*len(card_eng[0]))] alphabet_2 = card_eng[:,int((1/3)*len(card_eng[0])):int((2/3)*len(card_eng[0]))] alphabet_3 = card_eng[:,int((2/3)*len(card_eng[0])):len(card_eng[0])] ''' save the numbers and alphabet''' plt.imshow(num_1) cv2.imwrite('num_1.jpg', num_1) plt.imshow(num_2) cv2.imwrite('num_2.jpg', num_2) plt.imshow(num_3) cv2.imwrite('num_3.jpg', num_3) plt.imshow(num_4) cv2.imwrite('num_4.jpg', num_4) plt.imshow(alphabet_1) plt.savefig('alphabet_1.png') plt.imshow(alphabet_2) plt.savefig('alphabet_2.png') plt.imshow(alphabet_3) plt.savefig('alphabet_3.png') '''input the number into CNN to predict''' def test_img(imagepath): image = cv2.imread(imagepath) image = cv2.cvtColor(image,cv2.COLOR_BGR2RGB) image = cv2.cvtColor(image,cv2.COLOR_RGB2GRAY) ret,thresh1 = cv2.threshold(image,127,255,cv2.THRESH_BINARY) img = cv2.resize(image,(28,28)) img = 255 - img im_array = np.array(img) im_array = np.reshape(im_array, (1,28,28,1)) im_array = im_array.astype('float32')/255 predict = model.predict_classes(im_array) ans.append(predict[0]) def test_alphabet(imagepath): alphabet = ["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"] element1 = cv2.getStructuringElement(cv2.MORPH_RECT, (3, 3)) image = cv2.imread(imagepath) image = cv2.cvtColor(image,cv2.COLOR_BGR2RGB) image = cv2.cvtColor(image,cv2.COLOR_RGB2GRAY) image = cv2.dilate(image, element1, iterations = 5) img = cv2.resize(image,(28,28)) img = 255 - img for i in range(len(img)): for j in range(len(img[0])): if img[i][j] < 100: img[i][j] = 0 im_array = np.array(img) im_array = np.reshape(im_array, (1,28,28,1)) im_array = im_array.astype('float32')/255 predict = model2.predict_classes(im_array) ans.append(str(alphabet[predict[0]])) '''using thread to increase rcognition speed''' global ans ans = [] alps = ['alphabet_1.png','alphabet_2.png','alphabet_3.png'] nums = ['num_1.jpg','num_2.jpg','num_3.jpg','num_4.jpg'] threads = [] for i in range(7): if i <= 2: threads.append(threading.Thread(target = test_alphabet(alps[i]))) threads[i].start() else: threads.append(threading.Thread(target = test_img(nums[i-3]))) threads[i].start() for i in range(7): threads[i].join() final = "" for i in range(len(ans)): final += str(ans[i]) if i == 2: final += '-' return(final) def get_final(): name = var2.get() ans = find_license(name) t = tk.Text(root, width=22, height=4, font=("Helvetica", 15), selectforeground='red') t.place(x=27, y=180) t.insert('insert',ans) '''simple gui by tkinter''' root = tk.Tk() root.title('License plate recognition') root.geometry('300x300') line0 = tk.Label(root, bg = 'light cyan', text = "Image : ", font = ("Helvetica", 12)) line0.place(x=30, y=45) var2 = tk.StringVar() b2 = tk.Entry(root, textvariable = var2, font=("Helvetica", 12), show=None, width=20) b2.place(x=85, y=45) a = tk.Button(root, bg='light cyan', text="Get license!", width=25, height=2, command=get_final) a.place(x=60, y=95) root.mainloop()
[ "tkinter.StringVar", "cv2.GaussianBlur", "tkinter.Text", "cv2.erode", "tkinter.Label", "cv2.dilate", "tkinter.Button", "cv2.cvtColor", "matplotlib.pyplot.imshow", "tkinter.Entry", "cv2.imwrite", "numpy.reshape", "tkinter.Tk", "cv2.resize", "cv2.Canny", "tensorflow.keras.models.load_model", "cv2.getStructuringElement", "cv2.threshold", "numpy.float32", "cv2.imread", "numpy.array", "matplotlib.pyplot.savefig" ]
[((269, 311), 'tensorflow.keras.models.load_model', 'keras.models.load_model', (['"""mnist_model1.h5"""'], {}), "('mnist_model1.h5')\n", (292, 311), False, 'from tensorflow import keras\n'), ((322, 363), 'tensorflow.keras.models.load_model', 'keras.models.load_model', (['"""alpha_model.h5"""'], {}), "('alpha_model.h5')\n", (345, 363), False, 'from tensorflow import keras\n'), ((8504, 8511), 'tkinter.Tk', 'tk.Tk', ([], {}), '()\n', (8509, 8511), True, 'import tkinter as tk\n'), ((8590, 8662), 'tkinter.Label', 'tk.Label', (['root'], {'bg': '"""light cyan"""', 'text': '"""Image : """', 'font': "('Helvetica', 12)"}), "(root, bg='light cyan', text='Image : ', font=('Helvetica', 12))\n", (8598, 8662), True, 'import tkinter as tk\n'), ((8705, 8719), 'tkinter.StringVar', 'tk.StringVar', ([], {}), '()\n', (8717, 8719), True, 'import tkinter as tk\n'), ((8726, 8804), 'tkinter.Entry', 'tk.Entry', (['root'], {'textvariable': 'var2', 'font': "('Helvetica', 12)", 'show': 'None', 'width': '(20)'}), "(root, textvariable=var2, font=('Helvetica', 12), show=None, width=20)\n", (8734, 8804), True, 'import tkinter as tk\n'), ((8836, 8932), 'tkinter.Button', 'tk.Button', (['root'], {'bg': '"""light cyan"""', 'text': '"""Get license!"""', 'width': '(25)', 'height': '(2)', 'command': 'get_final'}), "(root, bg='light cyan', text='Get license!', width=25, height=2,\n command=get_final)\n", (8845, 8932), True, 'import tkinter as tk\n'), ((443, 464), 'cv2.imread', 'cv2.imread', (['imagepath'], {}), '(imagepath)\n', (453, 464), False, 'import cv2\n'), ((510, 553), 'cv2.cvtColor', 'cv2.cvtColor', (['RGB_image', 'cv2.COLOR_RGB2GRAY'], {}), '(RGB_image, cv2.COLOR_RGB2GRAY)\n', (522, 553), False, 'import cv2\n'), ((618, 664), 'cv2.Canny', 'cv2.Canny', (['gray', 'low_threshold', 'high_threshold'], {}), '(gray, low_threshold, high_threshold)\n', (627, 664), False, 'import cv2\n'), ((723, 777), 'cv2.GaussianBlur', 'cv2.GaussianBlur', (['edges', '(kernel_size, kernel_size)', '(0)'], {}), '(edges, (kernel_size, kernel_size), 0)\n', (739, 777), False, 'import cv2\n'), ((1044, 1093), 'cv2.getStructuringElement', 'cv2.getStructuringElement', (['cv2.MORPH_RECT', '(9, 7)'], {}), '(cv2.MORPH_RECT, (9, 7))\n', (1069, 1093), False, 'import cv2\n'), ((1110, 1159), 'cv2.getStructuringElement', 'cv2.getStructuringElement', (['cv2.MORPH_RECT', '(5, 3)'], {}), '(cv2.MORPH_RECT, (5, 3))\n', (1135, 1159), False, 'import cv2\n'), ((1176, 1226), 'cv2.getStructuringElement', 'cv2.getStructuringElement', (['cv2.MORPH_RECT', '(15, 5)'], {}), '(cv2.MORPH_RECT, (15, 5))\n', (1201, 1226), False, 'import cv2\n'), ((1243, 1293), 'cv2.getStructuringElement', 'cv2.getStructuringElement', (['cv2.MORPH_RECT', '(5, 10)'], {}), '(cv2.MORPH_RECT, (5, 10))\n', (1268, 1293), False, 'import cv2\n'), ((1310, 1359), 'cv2.getStructuringElement', 'cv2.getStructuringElement', (['cv2.MORPH_RECT', '(5, 5)'], {}), '(cv2.MORPH_RECT, (5, 5))\n', (1335, 1359), False, 'import cv2\n'), ((1403, 1442), 'cv2.dilate', 'cv2.dilate', (['img', 'element1'], {'iterations': '(2)'}), '(img, element1, iterations=2)\n', (1413, 1442), False, 'import cv2\n'), ((1456, 1494), 'cv2.erode', 'cv2.erode', (['img', 'element1'], {'iterations': '(2)'}), '(img, element1, iterations=2)\n', (1465, 1494), False, 'import cv2\n'), ((1508, 1547), 'cv2.erode', 'cv2.erode', (['img', 'element2'], {'iterations': '(10)'}), '(img, element2, iterations=10)\n', (1517, 1547), False, 'import cv2\n'), ((1561, 1599), 'cv2.erode', 'cv2.erode', (['img', 'element5'], {'iterations': '(5)'}), '(img, element5, iterations=5)\n', (1570, 1599), False, 'import cv2\n'), ((1613, 1652), 'cv2.dilate', 'cv2.dilate', (['img', 'element5'], {'iterations': '(5)'}), '(img, element5, iterations=5)\n', (1623, 1652), False, 'import cv2\n'), ((1666, 1706), 'cv2.dilate', 'cv2.dilate', (['img', 'element2'], {'iterations': '(10)'}), '(img, element2, iterations=10)\n', (1676, 1706), False, 'import cv2\n'), ((1720, 1759), 'cv2.erode', 'cv2.erode', (['img', 'element3'], {'iterations': '(10)'}), '(img, element3, iterations=10)\n', (1729, 1759), False, 'import cv2\n'), ((1773, 1813), 'cv2.dilate', 'cv2.dilate', (['img', 'element3'], {'iterations': '(10)'}), '(img, element3, iterations=10)\n', (1783, 1813), False, 'import cv2\n'), ((1827, 1865), 'cv2.erode', 'cv2.erode', (['img', 'element4'], {'iterations': '(5)'}), '(img, element4, iterations=5)\n', (1836, 1865), False, 'import cv2\n'), ((1879, 1918), 'cv2.dilate', 'cv2.dilate', (['img', 'element4'], {'iterations': '(5)'}), '(img, element4, iterations=5)\n', (1889, 1918), False, 'import cv2\n'), ((2796, 2849), 'cv2.threshold', 'cv2.threshold', (['card_gray', '(127)', '(255)', 'cv2.THRESH_BINARY'], {}), '(card_gray, 127, 255, cv2.THRESH_BINARY)\n', (2809, 2849), False, 'import cv2\n'), ((2862, 2911), 'cv2.getStructuringElement', 'cv2.getStructuringElement', (['cv2.MORPH_RECT', '(2, 2)'], {}), '(cv2.MORPH_RECT, (2, 2))\n', (2887, 2911), False, 'import cv2\n'), ((2927, 2969), 'cv2.dilate', 'cv2.dilate', (['card_bw', 'element'], {'iterations': '(2)'}), '(card_bw, element, iterations=2)\n', (2937, 2969), False, 'import cv2\n'), ((2987, 3028), 'cv2.erode', 'cv2.erode', (['card_bw', 'element'], {'iterations': '(2)'}), '(card_bw, element, iterations=2)\n', (2996, 3028), False, 'import cv2\n'), ((5631, 5648), 'matplotlib.pyplot.imshow', 'plt.imshow', (['num_1'], {}), '(num_1)\n', (5641, 5648), True, 'import matplotlib.pyplot as plt\n'), ((5654, 5685), 'cv2.imwrite', 'cv2.imwrite', (['"""num_1.jpg"""', 'num_1'], {}), "('num_1.jpg', num_1)\n", (5665, 5685), False, 'import cv2\n'), ((5691, 5708), 'matplotlib.pyplot.imshow', 'plt.imshow', (['num_2'], {}), '(num_2)\n', (5701, 5708), True, 'import matplotlib.pyplot as plt\n'), ((5714, 5745), 'cv2.imwrite', 'cv2.imwrite', (['"""num_2.jpg"""', 'num_2'], {}), "('num_2.jpg', num_2)\n", (5725, 5745), False, 'import cv2\n'), ((5751, 5768), 'matplotlib.pyplot.imshow', 'plt.imshow', (['num_3'], {}), '(num_3)\n', (5761, 5768), True, 'import matplotlib.pyplot as plt\n'), ((5774, 5805), 'cv2.imwrite', 'cv2.imwrite', (['"""num_3.jpg"""', 'num_3'], {}), "('num_3.jpg', num_3)\n", (5785, 5805), False, 'import cv2\n'), ((5811, 5828), 'matplotlib.pyplot.imshow', 'plt.imshow', (['num_4'], {}), '(num_4)\n', (5821, 5828), True, 'import matplotlib.pyplot as plt\n'), ((5834, 5865), 'cv2.imwrite', 'cv2.imwrite', (['"""num_4.jpg"""', 'num_4'], {}), "('num_4.jpg', num_4)\n", (5845, 5865), False, 'import cv2\n'), ((5871, 5893), 'matplotlib.pyplot.imshow', 'plt.imshow', (['alphabet_1'], {}), '(alphabet_1)\n', (5881, 5893), True, 'import matplotlib.pyplot as plt\n'), ((5899, 5928), 'matplotlib.pyplot.savefig', 'plt.savefig', (['"""alphabet_1.png"""'], {}), "('alphabet_1.png')\n", (5910, 5928), True, 'import matplotlib.pyplot as plt\n'), ((5934, 5956), 'matplotlib.pyplot.imshow', 'plt.imshow', (['alphabet_2'], {}), '(alphabet_2)\n', (5944, 5956), True, 'import matplotlib.pyplot as plt\n'), ((5962, 5991), 'matplotlib.pyplot.savefig', 'plt.savefig', (['"""alphabet_2.png"""'], {}), "('alphabet_2.png')\n", (5973, 5991), True, 'import matplotlib.pyplot as plt\n'), ((5997, 6019), 'matplotlib.pyplot.imshow', 'plt.imshow', (['alphabet_3'], {}), '(alphabet_3)\n', (6007, 6019), True, 'import matplotlib.pyplot as plt\n'), ((6025, 6054), 'matplotlib.pyplot.savefig', 'plt.savefig', (['"""alphabet_3.png"""'], {}), "('alphabet_3.png')\n", (6036, 6054), True, 'import matplotlib.pyplot as plt\n'), ((8329, 8415), 'tkinter.Text', 'tk.Text', (['root'], {'width': '(22)', 'height': '(4)', 'font': "('Helvetica', 15)", 'selectforeground': '"""red"""'}), "(root, width=22, height=4, font=('Helvetica', 15), selectforeground=\n 'red')\n", (8336, 8415), True, 'import tkinter as tk\n'), ((2739, 2755), 'numpy.float32', 'np.float32', (['card'], {}), '(card)\n', (2749, 2755), True, 'import numpy as np\n'), ((6152, 6173), 'cv2.imread', 'cv2.imread', (['imagepath'], {}), '(imagepath)\n', (6162, 6173), False, 'import cv2\n'), ((6191, 6229), 'cv2.cvtColor', 'cv2.cvtColor', (['image', 'cv2.COLOR_BGR2RGB'], {}), '(image, cv2.COLOR_BGR2RGB)\n', (6203, 6229), False, 'import cv2\n'), ((6246, 6285), 'cv2.cvtColor', 'cv2.cvtColor', (['image', 'cv2.COLOR_RGB2GRAY'], {}), '(image, cv2.COLOR_RGB2GRAY)\n', (6258, 6285), False, 'import cv2\n'), ((6308, 6357), 'cv2.threshold', 'cv2.threshold', (['image', '(127)', '(255)', 'cv2.THRESH_BINARY'], {}), '(image, 127, 255, cv2.THRESH_BINARY)\n', (6321, 6357), False, 'import cv2\n'), ((6370, 6397), 'cv2.resize', 'cv2.resize', (['image', '(28, 28)'], {}), '(image, (28, 28))\n', (6380, 6397), False, 'import cv2\n'), ((6441, 6454), 'numpy.array', 'np.array', (['img'], {}), '(img)\n', (6449, 6454), True, 'import numpy as np\n'), ((6475, 6511), 'numpy.reshape', 'np.reshape', (['im_array', '(1, 28, 28, 1)'], {}), '(im_array, (1, 28, 28, 1))\n', (6485, 6511), True, 'import numpy as np\n'), ((6826, 6875), 'cv2.getStructuringElement', 'cv2.getStructuringElement', (['cv2.MORPH_RECT', '(3, 3)'], {}), '(cv2.MORPH_RECT, (3, 3))\n', (6851, 6875), False, 'import cv2\n'), ((6893, 6914), 'cv2.imread', 'cv2.imread', (['imagepath'], {}), '(imagepath)\n', (6903, 6914), False, 'import cv2\n'), ((6932, 6970), 'cv2.cvtColor', 'cv2.cvtColor', (['image', 'cv2.COLOR_BGR2RGB'], {}), '(image, cv2.COLOR_BGR2RGB)\n', (6944, 6970), False, 'import cv2\n'), ((6987, 7026), 'cv2.cvtColor', 'cv2.cvtColor', (['image', 'cv2.COLOR_RGB2GRAY'], {}), '(image, cv2.COLOR_RGB2GRAY)\n', (6999, 7026), False, 'import cv2\n'), ((7043, 7084), 'cv2.dilate', 'cv2.dilate', (['image', 'element1'], {'iterations': '(5)'}), '(image, element1, iterations=5)\n', (7053, 7084), False, 'import cv2\n'), ((7102, 7129), 'cv2.resize', 'cv2.resize', (['image', '(28, 28)'], {}), '(image, (28, 28))\n', (7112, 7129), False, 'import cv2\n'), ((7322, 7335), 'numpy.array', 'np.array', (['img'], {}), '(img)\n', (7330, 7335), True, 'import numpy as np\n'), ((7356, 7392), 'numpy.reshape', 'np.reshape', (['im_array', '(1, 28, 28, 1)'], {}), '(im_array, (1, 28, 28, 1))\n', (7366, 7392), True, 'import numpy as np\n')]
# Copyright 2021 <NAME> # SPDX-License-Identifier: Apache-2.0 'colorex numpy' import numpy as np from colorex.cex_constants import ( REC_709_LUMA_WEIGHTS, MAX_COMPONENT_VALUE, SMALL_COMPONENT_VALUE, M_RGB_TO_XYZ_T, M_XYZ_TO_RGB_T, D50_TO_D65_T, ) def gamma_correct(values, gamma): 'apply a gamma power curve' #pylint: disable=assignment-from-no-return return np.power(values, gamma) def srgb_to_rgb_aprox_gamma_22(srgb_img): ''' approximate srgb conversion using a gamma correct with power 2.2 this approach is very common in vfx where srgb is used rarely ''' return gamma_correct(srgb_img, gamma=2.2) def rgb_to_srgb_aprox_gamma_22(rgb_img): ''' approximate inverse srgb conversion using a gamma correct with power 1.0/2.2 this approach is very common in vfx where srgb is used rarely ''' return gamma_correct(rgb_img, gamma=1.0 / 2.2) def srgb_to_rgb2(srgb_img): ''' 2.4 gamma and linear below .04045 very close to the approach taken internally to skimagewhen when converting: srgb > rgb > xyz skimage does not expose the srgb > rgb transform ''' arr = srgb_img.copy() mask = arr > 0.04045 arr[mask] = np.power((arr[mask] + 0.055) / 1.055, 2.4) arr[~mask] /= 12.92 return arr def srgb_to_rgb(srgb): ''' convert from a gamma 2.4 color space to linear rgb this code can be directly adapted to keras or another autodiff framework ''' srgb = np.clip(srgb, SMALL_COMPONENT_VALUE, MAX_COMPONENT_VALUE) linear_mask = (srgb <= 0.04045).astype(np.float32) exponential_mask = (srgb > 0.04045).astype(np.float32) linear_pixels = srgb / 12.92 exponential_pixels = np.power((srgb + 0.055) / 1.055, 2.4) return linear_pixels * linear_mask + exponential_pixels * exponential_mask def rgb_to_srgb(rgb): ''' convert from linear rgb to a gamma 2.4 color space this code can be directly adapted to keras or another autodiff framework ''' rgb = np.clip(rgb, SMALL_COMPONENT_VALUE, MAX_COMPONENT_VALUE) linear_mask = (rgb <= 0.0031308).astype(np.float32) exponential_mask = (rgb > 0.0031308).astype(np.float32) linear_pixels = rgb * 12.92 exponential_pixels = 1.055 * np.power(rgb, 1.0 / 2.4) - 0.055 return linear_pixels * linear_mask + exponential_pixels * exponential_mask def rgb_to_luminance(rgb, luma_weights=REC_709_LUMA_WEIGHTS): 'luminance of a color array, or higher dim color images' r, g, b = rgb[..., 0], rgb[..., 1], rgb[..., 2] return r * luma_weights[0] + g * luma_weights[1] + b * luma_weights[2] def xyz_to_xyy(XYZ): ''' convert from XYZ color space to xyY XYZ: consistent units for each component xyY: normalized chromaticity with xy in 0-1, Y in 0-inf https://en.wikipedia.org/wiki/CIE_1931_color_space http://www.brucelindbloom.com/index.html?Eqn_XYZ_to_xyY.html ''' X, Y, Z = XYZ[..., 0], XYZ[..., 1], XYZ[..., 2] XYZ_sum = X + Y + Z invalid_mask = (XYZ_sum < SMALL_COMPONENT_VALUE).astype(np.float32) valid_mask = 1.0 - invalid_mask # if xyz_sum == 0, set to 1.0 XYZ_sum = invalid_mask + valid_mask * XYZ_sum x = X / XYZ_sum y = Y / XYZ_sum x *= valid_mask y *= valid_mask Y *= valid_mask return np.stack([x, y, Y], axis=-1) def xyy_to_xyz(xyY): ''' convert from xyY color space to XYZ xyY: normalized chromaticity with xy in 0-1, Y in 0-inf XYZ: consistent units for each component https://en.wikipedia.org/wiki/CIE_1931_color_space http://www.brucelindbloom.com/index.html?Eqn_xyY_to_XYZ.html ''' x, y, Y = xyY[..., 0], xyY[..., 1], xyY[..., 2] invalid_mask = (y < SMALL_COMPONENT_VALUE).astype(np.float32) valid_mask = 1.0 - invalid_mask y = invalid_mask + valid_mask * y norm = Y / y X = x * norm Z = (1 - x - y) * norm X *= valid_mask Y *= valid_mask Z *= valid_mask return np.stack([X, Y, Z], axis=-1) def point_or_points_or_image_wrapper(func): ''' a decorated function will be called with reshaped input and output to support a single 3d point: pt.shape = (3,) an array of 3d points: pts.shape = (N,3) an image of 3d points: pts.shape = (H,W,3) wrapped functions should internally support the array of 3d points case (N,3) ''' def inner(point_or_points_or_image, *args, **kwargs): result_shape = list(point_or_points_or_image.shape) if len(result_shape) == 1: img_shape = [1, 1] + result_shape elif len(result_shape) == 2: img_shape = [1] + result_shape elif len(result_shape) == 3: img_shape = list(result_shape) assert img_shape[-1] == 3 points_shape = (img_shape[0] * img_shape[1], img_shape[2]) points = point_or_points_or_image.reshape(points_shape) result = func(points, *args, **kwargs) return result.reshape(result_shape) return inner @point_or_points_or_image_wrapper def D50_to_D65(points): 'matrix transformation from D50 whitepoint to D65' return np.matmul(points, D50_TO_D65_T) @point_or_points_or_image_wrapper def rgb_to_xyz(points): 'matrix transformation from linear RGB to XYZ color space' return np.matmul(points, M_RGB_TO_XYZ_T) @point_or_points_or_image_wrapper def xyz_to_rgb(points): 'matrix transformation from XYZ to linear RGB color space' return np.matmul(points, M_XYZ_TO_RGB_T)
[ "numpy.stack", "numpy.power", "numpy.matmul", "numpy.clip" ]
[((392, 415), 'numpy.power', 'np.power', (['values', 'gamma'], {}), '(values, gamma)\n', (400, 415), True, 'import numpy as np\n'), ((1184, 1226), 'numpy.power', 'np.power', (['((arr[mask] + 0.055) / 1.055)', '(2.4)'], {}), '((arr[mask] + 0.055) / 1.055, 2.4)\n', (1192, 1226), True, 'import numpy as np\n'), ((1437, 1494), 'numpy.clip', 'np.clip', (['srgb', 'SMALL_COMPONENT_VALUE', 'MAX_COMPONENT_VALUE'], {}), '(srgb, SMALL_COMPONENT_VALUE, MAX_COMPONENT_VALUE)\n', (1444, 1494), True, 'import numpy as np\n'), ((1663, 1700), 'numpy.power', 'np.power', (['((srgb + 0.055) / 1.055)', '(2.4)'], {}), '((srgb + 0.055) / 1.055, 2.4)\n', (1671, 1700), True, 'import numpy as np\n'), ((1952, 2008), 'numpy.clip', 'np.clip', (['rgb', 'SMALL_COMPONENT_VALUE', 'MAX_COMPONENT_VALUE'], {}), '(rgb, SMALL_COMPONENT_VALUE, MAX_COMPONENT_VALUE)\n', (1959, 2008), True, 'import numpy as np\n'), ((3201, 3229), 'numpy.stack', 'np.stack', (['[x, y, Y]'], {'axis': '(-1)'}), '([x, y, Y], axis=-1)\n', (3209, 3229), True, 'import numpy as np\n'), ((3832, 3860), 'numpy.stack', 'np.stack', (['[X, Y, Z]'], {'axis': '(-1)'}), '([X, Y, Z], axis=-1)\n', (3840, 3860), True, 'import numpy as np\n'), ((4916, 4947), 'numpy.matmul', 'np.matmul', (['points', 'D50_TO_D65_T'], {}), '(points, D50_TO_D65_T)\n', (4925, 4947), True, 'import numpy as np\n'), ((5078, 5111), 'numpy.matmul', 'np.matmul', (['points', 'M_RGB_TO_XYZ_T'], {}), '(points, M_RGB_TO_XYZ_T)\n', (5087, 5111), True, 'import numpy as np\n'), ((5242, 5275), 'numpy.matmul', 'np.matmul', (['points', 'M_XYZ_TO_RGB_T'], {}), '(points, M_XYZ_TO_RGB_T)\n', (5251, 5275), True, 'import numpy as np\n'), ((2186, 2210), 'numpy.power', 'np.power', (['rgb', '(1.0 / 2.4)'], {}), '(rgb, 1.0 / 2.4)\n', (2194, 2210), True, 'import numpy as np\n')]
#!/usr/bin/env python import sys from cvangysel import argparse_utils, logging_utils, sklearn_utils, trec_utils from sert import inference, math_utils, models import argparse import collections import io import logging import numpy as np import os import operator import pickle import scipy import scipy.spatial import sklearn.neighbors # # Main driver. # def main(): parser = argparse.ArgumentParser() parser.add_argument('--loglevel', type=str, default='INFO') parser.add_argument('--meta', type=argparse_utils.existing_file_path, required=True) parser.add_argument('--model', type=argparse_utils.existing_file_path, required=True) parser.add_argument('--topics', type=argparse_utils.existing_file_path, nargs='+') parser.add_argument('--top', type=argparse_utils.positive_int, default=None) parser.add_argument('--run_out', type=argparse_utils.nonexisting_file_path, required=True) args = parser.parse_args() try: logging_utils.configure_logging(args) except IOError: return -1 with open(args.model, 'rb') as f: # Load model arguments and learned mapping. model_args, predict_fn = (pickle.load(f) for _ in range(2)) # Load word representations. word_representations = pickle.load(f) try: entity_representations = pickle.load(f) except EOFError: entity_representations = None with open(args.meta, 'rb') as f: (data_args, words, tokens, entity_indices_inv, entity_assocs) = ( pickle.load(f) for _ in range(5)) # Parse topic files. topic_f = list(map(lambda filename: open(filename, 'r'), args.topics)) topics = trec_utils.parse_topics(topic_f) [f_.close() for f_ in topic_f] model_name = os.path.basename(args.model) # Entity profiling. topics_per_entity = collections.defaultdict(list) # Entity finding. entities_per_topic = collections.defaultdict(list) def ranker_callback(topic_id, top_ranked_indices, top_ranked_values): for rank, (entity_internal_id, relevance) in enumerate( zip(top_ranked_indices, top_ranked_values)): entity_id = entity_indices_inv[entity_internal_id] # Entity profiling. topics_per_entity[entity_id].append((relevance, topic_id)) # Entity finding. entities_per_topic[topic_id].append((relevance, entity_id)) with open('{0}_debug'.format(args.run_out), 'w') as f_debug_out: if model_args.type == models.LanguageModel: result_callback = LogLinearCallback( args, model_args, tokens, f_debug_out, ranker_callback) elif model_args.type == models.VectorSpaceLanguageModel: result_callback = VectorSpaceCallback( entity_representations, args, model_args, tokens, f_debug_out, ranker_callback) batcher = inference.create( predict_fn, word_representations, model_args.batch_size, data_args.window_size, len(words), result_callback) logging.info('Batching queries using %s.', batcher) for q_id, (topic_id, terms) in enumerate(topics.items()): if topic_id not in topics: logging.error('Topic "%s" not found in topic list.', topic_id) continue # Do not replace numeric tokens in queries. query_terms = trec_utils.parse_query(terms) query_tokens = [] logging.debug('Query (%d/%d) %s: %s (%s)', q_id + 1, len(topics), topic_id, query_terms, terms) for term in query_terms: if term not in words: logging.debug('Term "%s" is OOV.', term) continue term_token = words[term].id query_tokens.append(term_token) if not query_tokens: logging.warning('Skipping query with terms "%s".', terms) continue batcher.submit(query_tokens, topic_id=topic_id) batcher.process() # Entity profiling. with io.open('{0}_ep'.format(args.run_out), 'w', encoding='utf8') as out_ep_run: trec_utils.write_run(model_name, topics_per_entity, out_ep_run) # Entity finding. with io.open('{0}_ef'.format(args.run_out), 'w', encoding='utf8') as out_ef_run: trec_utils.write_run(model_name, entities_per_topic, out_ef_run) logging.info('Saved run to %s.', args.run_out) # # Ranker callbacks. # class Callback(object): def __init__(self, args, model_args, tokens, f_debug_out, rank_callback): self.args = args self.model_args = model_args self.tokens = tokens self.f_debug_out = f_debug_out self.rank_callback = rank_callback self.topic_projections = {} def __call__(self, payload, result, topic_id): assert topic_id not in self.topic_projections self.topic_projections[topic_id] = result.ravel() distribution = result logging.debug('Result of shape %s for topic "%s".', distribution.shape, topic_id) self.process(payload, distribution, topic_id) def process(self, payload, distribution, topic_id): raise NotImplementedError() def should_average_input(self): raise NotImplementedError() class LogLinearCallback(Callback): def __init__(self, *args, **kwargs): super(LogLinearCallback, self).__init__(*args, **kwargs) def process(self, payload, distribution, topic_id): terms = list(map(lambda id: self.tokens[id], payload)) term_entropies = compute_normalised_entropy( distribution, base=2) distribution = inference.aggregate_distribution( distribution, mode='product', axis=0) assert distribution.ndim == 1 distribution /= distribution.sum() if not np.isclose(distribution.sum(), 1.0): logging.error('Encountered non-normalized ' 'distribution for topic "%s" ' '(mass=%.10f).', topic_id, distribution.sum()) self.f_debug_out.write('Topic {0} {1}: {2}\n'.format( topic_id, math_utils.entropy( distribution, base=2, normalize=True), zip(terms, term_entropies))) ranked_indices = np.argsort(distribution) top_ranked_indices = ranked_indices[::-1] top_ranked_values = distribution[top_ranked_indices] self.rank_callback(topic_id, top_ranked_indices, top_ranked_values) def should_average_input(self): return False class VectorSpaceCallback(Callback): def __init__(self, entity_representations, *args, **kwargs): super(VectorSpaceCallback, self).__init__(*args, **kwargs) logging.info( 'Initializing k-NN for entity representations of shape %s.', entity_representations.shape) n_neighbors = self.args.top if n_neighbors is None: logging.warning( 'Parameter k not set; defaulting to all entities (k=%d).', entity_representations.shape[0]) elif n_neighbors > entity_representations.shape[0]: logging.warning( 'Parameter k exceeds number of entities; ' 'defaulting to all entities (k=%d).', entity_representations.shape[0]) n_neighbors = None self.entity_representation_distance = 'cosine' if self.entity_representation_distance == 'cosine': self.entity_representation_distance = 'euclidean' self.normalize_representations = True else: self.normalize_representations = False if self.normalize_representations: entity_repr_l2_norms = np.linalg.norm( entity_representations, axis=1)[:, np.newaxis] entity_representations /= entity_repr_l2_norms logging.debug('Term projections will be normalized.') self.entity_representations = entity_representations if n_neighbors: nn_impl = sklearn_utils.neighbors_algorithm( self.entity_representation_distance) logging.info('Using %s as distance metric in entity space ' 'with NearestNeighbors %s implementation.', self.entity_representation_distance, nn_impl) self.entity_neighbors = sklearn.neighbors.NearestNeighbors( n_neighbors=n_neighbors, algorithm=nn_impl, metric=self.entity_representation_distance) self.entity_neighbors.fit(entity_representations) self.entity_avg = entity_representations.mean(axis=1) logging.info('Entity k-NN params: %s', self.entity_neighbors.get_params()) else: logging.info('Using %s as distance metric in entity space.', self.entity_representation_distance) self.entity_neighbors = None def query(self, centroids): if self.entity_neighbors is not None: distances, indices = self.entity_neighbors.kneighbors(centroids) return distances, indices else: pairwise_distances = scipy.spatial.distance.cdist( centroids, self.entity_representations, metric=self.entity_representation_distance) distances = np.sort(pairwise_distances, axis=1) indices = pairwise_distances.argsort(axis=1)\ .argsort(axis=1).argsort(axis=1) return distances, indices def process(self, payload, result, topic_id): terms = list(map(lambda id: self.tokens[id], payload)) term_projections = inference.aggregate_distribution( result, mode='identity', axis=0) if term_projections.ndim == 1: term_projections = term_projections.reshape(1, -1) _, entity_representation_size = term_projections.shape assert(entity_representation_size == self.model_args.entity_representation_size) if self.normalize_representations: term_projections_l2_norm = \ np.linalg.norm(term_projections, axis=1)[:, np.newaxis] term_projections /= term_projections_l2_norm logging.debug('Querying kneighbors for %s.', terms) distances, indices = self.query(term_projections) assert indices.shape[0] == term_projections.shape[0] candidates = collections.defaultdict(float) assert indices.shape[0] == 1 for term in range(indices.shape[0]): term_indices = indices[term, :] for rank, candidate in enumerate(term_indices): matching_score = np.sum( self.entity_representations[candidate, :] * term_projections[term, :]) if self.normalize_representations: matching_score = (matching_score + 1.0) / 2.0 candidates[candidate] += matching_score top_ranked_indices, top_ranked_values = \ map(np.array, zip( *sorted(candidates.items(), reverse=True, key=operator.itemgetter(1)))) self.rank_callback(topic_id, top_ranked_indices, top_ranked_values) def should_average_input(self): return True def compute_normalised_entropy(distribution, base=2): assert distribution.ndim == 2 assert np.allclose(distribution.sum(axis=1), 1.0) entropies = [ math_utils.entropy(distribution[i, :], base=base, normalize=True) for i in range(distribution.shape[0])] return entropies if __name__ == "__main__": sys.exit(main())
[ "numpy.sum", "argparse.ArgumentParser", "collections.defaultdict", "numpy.argsort", "pickle.load", "numpy.linalg.norm", "logging.error", "logging.warning", "cvangysel.trec_utils.write_run", "cvangysel.sklearn_utils.neighbors_algorithm", "scipy.spatial.distance.cdist", "os.path.basename", "cvangysel.trec_utils.parse_topics", "numpy.sort", "logging.debug", "cvangysel.logging_utils.configure_logging", "logging.info", "cvangysel.trec_utils.parse_query", "sert.math_utils.entropy", "sert.inference.aggregate_distribution", "operator.itemgetter" ]
[((387, 412), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (410, 412), False, 'import argparse\n'), ((1883, 1915), 'cvangysel.trec_utils.parse_topics', 'trec_utils.parse_topics', (['topic_f'], {}), '(topic_f)\n', (1906, 1915), False, 'from cvangysel import argparse_utils, logging_utils, sklearn_utils, trec_utils\n'), ((1969, 1997), 'os.path.basename', 'os.path.basename', (['args.model'], {}), '(args.model)\n', (1985, 1997), False, 'import os\n'), ((2047, 2076), 'collections.defaultdict', 'collections.defaultdict', (['list'], {}), '(list)\n', (2070, 2076), False, 'import collections\n'), ((2125, 2154), 'collections.defaultdict', 'collections.defaultdict', (['list'], {}), '(list)\n', (2148, 2154), False, 'import collections\n'), ((4804, 4850), 'logging.info', 'logging.info', (['"""Saved run to %s."""', 'args.run_out'], {}), "('Saved run to %s.', args.run_out)\n", (4816, 4850), False, 'import logging\n'), ((1141, 1178), 'cvangysel.logging_utils.configure_logging', 'logging_utils.configure_logging', (['args'], {}), '(args)\n', (1172, 1178), False, 'from cvangysel import argparse_utils, logging_utils, sklearn_utils, trec_utils\n'), ((1445, 1459), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (1456, 1459), False, 'import pickle\n'), ((3351, 3402), 'logging.info', 'logging.info', (['"""Batching queries using %s."""', 'batcher'], {}), "('Batching queries using %s.', batcher)\n", (3363, 3402), False, 'import logging\n'), ((4537, 4600), 'cvangysel.trec_utils.write_run', 'trec_utils.write_run', (['model_name', 'topics_per_entity', 'out_ep_run'], {}), '(model_name, topics_per_entity, out_ep_run)\n', (4557, 4600), False, 'from cvangysel import argparse_utils, logging_utils, sklearn_utils, trec_utils\n'), ((4734, 4798), 'cvangysel.trec_utils.write_run', 'trec_utils.write_run', (['model_name', 'entities_per_topic', 'out_ef_run'], {}), '(model_name, entities_per_topic, out_ef_run)\n', (4754, 4798), False, 'from cvangysel import argparse_utils, logging_utils, sklearn_utils, trec_utils\n'), ((5432, 5517), 'logging.debug', 'logging.debug', (['"""Result of shape %s for topic "%s"."""', 'distribution.shape', 'topic_id'], {}), '(\'Result of shape %s for topic "%s".\', distribution.shape,\n topic_id)\n', (5445, 5517), False, 'import logging\n'), ((6132, 6202), 'sert.inference.aggregate_distribution', 'inference.aggregate_distribution', (['distribution'], {'mode': '"""product"""', 'axis': '(0)'}), "(distribution, mode='product', axis=0)\n", (6164, 6202), False, 'from sert import inference, math_utils, models\n'), ((6803, 6827), 'numpy.argsort', 'np.argsort', (['distribution'], {}), '(distribution)\n', (6813, 6827), True, 'import numpy as np\n'), ((7256, 7363), 'logging.info', 'logging.info', (['"""Initializing k-NN for entity representations of shape %s."""', 'entity_representations.shape'], {}), "('Initializing k-NN for entity representations of shape %s.',\n entity_representations.shape)\n", (7268, 7363), False, 'import logging\n'), ((10259, 10324), 'sert.inference.aggregate_distribution', 'inference.aggregate_distribution', (['result'], {'mode': '"""identity"""', 'axis': '(0)'}), "(result, mode='identity', axis=0)\n", (10291, 10324), False, 'from sert import inference, math_utils, models\n'), ((10832, 10883), 'logging.debug', 'logging.debug', (['"""Querying kneighbors for %s."""', 'terms'], {}), "('Querying kneighbors for %s.', terms)\n", (10845, 10883), False, 'import logging\n'), ((11027, 11057), 'collections.defaultdict', 'collections.defaultdict', (['float'], {}), '(float)\n', (11050, 11057), False, 'import collections\n'), ((12098, 12163), 'sert.math_utils.entropy', 'math_utils.entropy', (['distribution[i, :]'], {'base': 'base', 'normalize': '(True)'}), '(distribution[i, :], base=base, normalize=True)\n', (12116, 12163), False, 'from sert import inference, math_utils, models\n'), ((1342, 1356), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (1353, 1356), False, 'import pickle\n'), ((1511, 1525), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (1522, 1525), False, 'import pickle\n'), ((1735, 1749), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (1746, 1749), False, 'import pickle\n'), ((3697, 3726), 'cvangysel.trec_utils.parse_query', 'trec_utils.parse_query', (['terms'], {}), '(terms)\n', (3719, 3726), False, 'from cvangysel import argparse_utils, logging_utils, sklearn_utils, trec_utils\n'), ((7467, 7578), 'logging.warning', 'logging.warning', (['"""Parameter k not set; defaulting to all entities (k=%d)."""', 'entity_representations.shape[0]'], {}), "('Parameter k not set; defaulting to all entities (k=%d).',\n entity_representations.shape[0])\n", (7482, 7578), False, 'import logging\n'), ((8416, 8469), 'logging.debug', 'logging.debug', (['"""Term projections will be normalized."""'], {}), "('Term projections will be normalized.')\n", (8429, 8469), False, 'import logging\n'), ((8579, 8649), 'cvangysel.sklearn_utils.neighbors_algorithm', 'sklearn_utils.neighbors_algorithm', (['self.entity_representation_distance'], {}), '(self.entity_representation_distance)\n', (8612, 8649), False, 'from cvangysel import argparse_utils, logging_utils, sklearn_utils, trec_utils\n'), ((8680, 8836), 'logging.info', 'logging.info', (['"""Using %s as distance metric in entity space with NearestNeighbors %s implementation."""', 'self.entity_representation_distance', 'nn_impl'], {}), "(\n 'Using %s as distance metric in entity space with NearestNeighbors %s implementation.'\n , self.entity_representation_distance, nn_impl)\n", (8692, 8836), False, 'import logging\n'), ((9357, 9459), 'logging.info', 'logging.info', (['"""Using %s as distance metric in entity space."""', 'self.entity_representation_distance'], {}), "('Using %s as distance metric in entity space.', self.\n entity_representation_distance)\n", (9369, 9459), False, 'import logging\n'), ((9764, 9881), 'scipy.spatial.distance.cdist', 'scipy.spatial.distance.cdist', (['centroids', 'self.entity_representations'], {'metric': 'self.entity_representation_distance'}), '(centroids, self.entity_representations, metric\n =self.entity_representation_distance)\n', (9792, 9881), False, 'import scipy\n'), ((9935, 9970), 'numpy.sort', 'np.sort', (['pairwise_distances'], {'axis': '(1)'}), '(pairwise_distances, axis=1)\n', (9942, 9970), True, 'import numpy as np\n'), ((3525, 3587), 'logging.error', 'logging.error', (['"""Topic "%s" not found in topic list."""', 'topic_id'], {}), '(\'Topic "%s" not found in topic list.\', topic_id)\n', (3538, 3587), False, 'import logging\n'), ((4230, 4287), 'logging.warning', 'logging.warning', (['"""Skipping query with terms "%s"."""', 'terms'], {}), '(\'Skipping query with terms "%s".\', terms)\n', (4245, 4287), False, 'import logging\n'), ((6661, 6717), 'sert.math_utils.entropy', 'math_utils.entropy', (['distribution'], {'base': '(2)', 'normalize': '(True)'}), '(distribution, base=2, normalize=True)\n', (6679, 6717), False, 'from sert import inference, math_utils, models\n'), ((7680, 7816), 'logging.warning', 'logging.warning', (['"""Parameter k exceeds number of entities; defaulting to all entities (k=%d)."""', 'entity_representations.shape[0]'], {}), "(\n 'Parameter k exceeds number of entities; defaulting to all entities (k=%d).'\n , entity_representations.shape[0])\n", (7695, 7816), False, 'import logging\n'), ((8264, 8310), 'numpy.linalg.norm', 'np.linalg.norm', (['entity_representations'], {'axis': '(1)'}), '(entity_representations, axis=1)\n', (8278, 8310), True, 'import numpy as np\n'), ((10710, 10750), 'numpy.linalg.norm', 'np.linalg.norm', (['term_projections'], {'axis': '(1)'}), '(term_projections, axis=1)\n', (10724, 10750), True, 'import numpy as np\n'), ((11280, 11357), 'numpy.sum', 'np.sum', (['(self.entity_representations[candidate, :] * term_projections[term, :])'], {}), '(self.entity_representations[candidate, :] * term_projections[term, :])\n', (11286, 11357), True, 'import numpy as np\n'), ((4015, 4055), 'logging.debug', 'logging.debug', (['"""Term "%s" is OOV."""', 'term'], {}), '(\'Term "%s" is OOV.\', term)\n', (4028, 4055), False, 'import logging\n'), ((11766, 11788), 'operator.itemgetter', 'operator.itemgetter', (['(1)'], {}), '(1)\n', (11785, 11788), False, 'import operator\n')]
import numpy as np rslt_binomial_0 = np.array([0, 6.618737, 0.004032037, 0.01433665, 0.01265635, 0.006173346, 0.01067706]) rslt_binomial_1 = np.array([0, 1.029661, 0.02180239, 0.07769613, 0.06756466, 0.03156418, 0.05851878]) rslt_binomial_2 = np.array([0, 0.1601819, 0.07111087, 0.2544921, 0.2110318, 0.08577924, 0.1984383]) rslt_binomial_3 = np.array([0.5, 0.05343991, 0.004990061, 0.2838563, 0.2167881, 0.02370156, 0.2096612]) rslt_binomial_4 = np.array([0.5, 0.02313286, 0.0708914, 0.3791042, 0.2938332, 0.07506391, 0.2982251]) rslt_binomial_5 = np.array([0.5, 0.009124078, 0.106681, 0.4327268, 0.3362166, 0.1019452, 0.3479955]) rslt_binomial_6 = np.array([1, 0.02932512, 0, 0.3085764, 0.2300801, 0.01143652, 0.2291531]) rslt_binomial_7 = np.array([1, 0.01269414, 0.07022348, 0.396642, 0.3044255, 0.07151663, 0.31301]) rslt_binomial_8 = np.array([1, 0.005494992, 0.1049623, 0.4385186, 0.3391729, 0.09907393, 0.3527401]) rslt_poisson_0 = np.array([0, 23.5349, 0.009251658, 0.003730997, 0.01266164, 0.003439135, 0.0141719]) rslt_poisson_1 = np.array([0, 3.661269, 0.04842557, 0.02095708, 0.06550316, 0.02029514, 0.07300782]) rslt_poisson_2 = np.array([0, 0.5695749, 0.1440462, 0.07208017, 0.182649, 0.07511376, 0.2018242]) rslt_poisson_3 = np.array([0.5, 0.1577593, 0.1247603, 0.02857521, 0.185693, 0.03840622, 0.2200925]) rslt_poisson_4 = np.array([0.5, 0.05669575, 0.187629, 0.08842012, 0.2348627, 0.09736964, 0.2628845]) rslt_poisson_5 = np.array([0.5, 0.0185653, 0.2118078, 0.1121067, 0.2534181, 0.1204543, 0.2784761]) rslt_poisson_6 = np.array([1, 0.07887965, 0.1339927, 0.0322772, 0.1969884, 0.0439019, 0.2339252]) rslt_poisson_7 = np.array([1, 0.02834788, 0.1927163, 0.09160406, 0.2398164, 0.1010126, 0.2682158]) rslt_poisson_8 = np.array([1, 0.0101877, 0.2126847, 0.1123439, 0.2544153, 0.1208601, 0.2796794])
[ "numpy.array" ]
[((38, 128), 'numpy.array', 'np.array', (['[0, 6.618737, 0.004032037, 0.01433665, 0.01265635, 0.006173346, 0.01067706]'], {}), '([0, 6.618737, 0.004032037, 0.01433665, 0.01265635, 0.006173346, \n 0.01067706])\n', (46, 128), True, 'import numpy as np\n'), ((171, 259), 'numpy.array', 'np.array', (['[0, 1.029661, 0.02180239, 0.07769613, 0.06756466, 0.03156418, 0.05851878]'], {}), '([0, 1.029661, 0.02180239, 0.07769613, 0.06756466, 0.03156418, \n 0.05851878])\n', (179, 259), True, 'import numpy as np\n'), ((302, 388), 'numpy.array', 'np.array', (['[0, 0.1601819, 0.07111087, 0.2544921, 0.2110318, 0.08577924, 0.1984383]'], {}), '([0, 0.1601819, 0.07111087, 0.2544921, 0.2110318, 0.08577924, \n 0.1984383])\n', (310, 388), True, 'import numpy as np\n'), ((431, 521), 'numpy.array', 'np.array', (['[0.5, 0.05343991, 0.004990061, 0.2838563, 0.2167881, 0.02370156, 0.2096612]'], {}), '([0.5, 0.05343991, 0.004990061, 0.2838563, 0.2167881, 0.02370156, \n 0.2096612])\n', (439, 521), True, 'import numpy as np\n'), ((564, 652), 'numpy.array', 'np.array', (['[0.5, 0.02313286, 0.0708914, 0.3791042, 0.2938332, 0.07506391, 0.2982251]'], {}), '([0.5, 0.02313286, 0.0708914, 0.3791042, 0.2938332, 0.07506391, \n 0.2982251])\n', (572, 652), True, 'import numpy as np\n'), ((695, 782), 'numpy.array', 'np.array', (['[0.5, 0.009124078, 0.106681, 0.4327268, 0.3362166, 0.1019452, 0.3479955]'], {}), '([0.5, 0.009124078, 0.106681, 0.4327268, 0.3362166, 0.1019452, \n 0.3479955])\n', (703, 782), True, 'import numpy as np\n'), ((825, 898), 'numpy.array', 'np.array', (['[1, 0.02932512, 0, 0.3085764, 0.2300801, 0.01143652, 0.2291531]'], {}), '([1, 0.02932512, 0, 0.3085764, 0.2300801, 0.01143652, 0.2291531])\n', (833, 898), True, 'import numpy as np\n'), ((946, 1025), 'numpy.array', 'np.array', (['[1, 0.01269414, 0.07022348, 0.396642, 0.3044255, 0.07151663, 0.31301]'], {}), '([1, 0.01269414, 0.07022348, 0.396642, 0.3044255, 0.07151663, 0.31301])\n', (954, 1025), True, 'import numpy as np\n'), ((1073, 1160), 'numpy.array', 'np.array', (['[1, 0.005494992, 0.1049623, 0.4385186, 0.3391729, 0.09907393, 0.3527401]'], {}), '([1, 0.005494992, 0.1049623, 0.4385186, 0.3391729, 0.09907393, \n 0.3527401])\n', (1081, 1160), True, 'import numpy as np\n'), ((1202, 1291), 'numpy.array', 'np.array', (['[0, 23.5349, 0.009251658, 0.003730997, 0.01266164, 0.003439135, 0.0141719]'], {}), '([0, 23.5349, 0.009251658, 0.003730997, 0.01266164, 0.003439135, \n 0.0141719])\n', (1210, 1291), True, 'import numpy as np\n'), ((1332, 1420), 'numpy.array', 'np.array', (['[0, 3.661269, 0.04842557, 0.02095708, 0.06550316, 0.02029514, 0.07300782]'], {}), '([0, 3.661269, 0.04842557, 0.02095708, 0.06550316, 0.02029514, \n 0.07300782])\n', (1340, 1420), True, 'import numpy as np\n'), ((1461, 1546), 'numpy.array', 'np.array', (['[0, 0.5695749, 0.1440462, 0.07208017, 0.182649, 0.07511376, 0.2018242]'], {}), '([0, 0.5695749, 0.1440462, 0.07208017, 0.182649, 0.07511376, 0.2018242]\n )\n', (1469, 1546), True, 'import numpy as np\n'), ((1587, 1674), 'numpy.array', 'np.array', (['[0.5, 0.1577593, 0.1247603, 0.02857521, 0.185693, 0.03840622, 0.2200925]'], {}), '([0.5, 0.1577593, 0.1247603, 0.02857521, 0.185693, 0.03840622, \n 0.2200925])\n', (1595, 1674), True, 'import numpy as np\n'), ((1715, 1803), 'numpy.array', 'np.array', (['[0.5, 0.05669575, 0.187629, 0.08842012, 0.2348627, 0.09736964, 0.2628845]'], {}), '([0.5, 0.05669575, 0.187629, 0.08842012, 0.2348627, 0.09736964, \n 0.2628845])\n', (1723, 1803), True, 'import numpy as np\n'), ((1844, 1930), 'numpy.array', 'np.array', (['[0.5, 0.0185653, 0.2118078, 0.1121067, 0.2534181, 0.1204543, 0.2784761]'], {}), '([0.5, 0.0185653, 0.2118078, 0.1121067, 0.2534181, 0.1204543, \n 0.2784761])\n', (1852, 1930), True, 'import numpy as np\n'), ((1971, 2056), 'numpy.array', 'np.array', (['[1, 0.07887965, 0.1339927, 0.0322772, 0.1969884, 0.0439019, 0.2339252]'], {}), '([1, 0.07887965, 0.1339927, 0.0322772, 0.1969884, 0.0439019, 0.2339252]\n )\n', (1979, 2056), True, 'import numpy as np\n'), ((2097, 2183), 'numpy.array', 'np.array', (['[1, 0.02834788, 0.1927163, 0.09160406, 0.2398164, 0.1010126, 0.2682158]'], {}), '([1, 0.02834788, 0.1927163, 0.09160406, 0.2398164, 0.1010126, \n 0.2682158])\n', (2105, 2183), True, 'import numpy as np\n'), ((2224, 2303), 'numpy.array', 'np.array', (['[1, 0.0101877, 0.2126847, 0.1123439, 0.2544153, 0.1208601, 0.2796794]'], {}), '([1, 0.0101877, 0.2126847, 0.1123439, 0.2544153, 0.1208601, 0.2796794])\n', (2232, 2303), True, 'import numpy as np\n')]
import matplotlib.patches as mpatches from nilearn import plotting, image, datasets from nilearn.input_data import NiftiSpheresMasker from nilearn.connectome import ConnectivityMeasure import numpy as np import pandas as pd from common.paths import POWER POWER_NUM_NODES = 264 POWER_DATASET = datasets.fetch_coords_power_2011() POWER_COORDS = np.vstack((POWER_DATASET.rois['x'], POWER_DATASET.rois['y'], POWER_DATASET.rois['z'])).T POWER_LABELS = pd.read_csv(POWER, index_col='ROI') POWER_NODE_COLORS = POWER_LABELS['Color'].values.tolist() POWER_NETWORKS = { 'VIS': 'Visual', 'FPN': 'Fronto-parietal Task Control', 'DMN': 'Default mode', 'SMH': 'Sensory/somatomotor Hand', 'SMM': 'Sensory/somatomotor Mouth', 'CON': 'Cingulo-opercular Task Control', 'AUD': 'Auditory', 'SAL': 'Salience', 'MEM': 'Memory retrieval', 'VAN': 'Ventral attention', 'CBR': 'Cerebellar', 'SUB': 'Subcortical', 'DAN': 'Dorsal attention', } # The following legend has been changed from the default Power atlas legend # - Extrapolated uncertain ROIs using the label of the closest ROI # - Changed colors: Pale blue -> lightsteelblue, Black -> navy, Teal -> lime POWER_LEGEND = { 'Blue': POWER_NETWORKS['VIS'], 'Yellow': POWER_NETWORKS['FPN'], 'Red': POWER_NETWORKS['DMN'], 'Cyan': POWER_NETWORKS['SMH'], 'Orange': POWER_NETWORKS['SMM'], 'Purple': POWER_NETWORKS['CON'], 'Pink': POWER_NETWORKS['AUD'], 'navy': POWER_NETWORKS['SAL'], 'Gray': POWER_NETWORKS['MEM'], 'lime': POWER_NETWORKS['VAN'], 'lightsteelblue': POWER_NETWORKS['CBR'], 'Brown': POWER_NETWORKS['SUB'], 'Green': POWER_NETWORKS['DAN'], } def generate_power_fc_matrix(file): """ Generates a Power functional connectivity matrix from a set of fMRI (nifti) images. Assumes the Pearson correlation metric. """ spheres_masker = NiftiSpheresMasker(seeds=POWER_COORDS, smoothing_fwhm=6, radius=5., standardize=True) time_series = spheres_masker.fit_transform(file) correlation_measure = ConnectivityMeasure(kind='correlation') correlation_matrix = correlation_measure.fit_transform([time_series])[0] return correlation_matrix def to_power_fc_matrix(fc_vector): """ Converts a Power connectivity vector (34716 x 1) to a matrix (264 x 264). Sets the diagonal to zero and makes the matrix symmetric about the diagonal. """ fc_matrix = np.zeros((POWER_NUM_NODES, POWER_NUM_NODES)) fc_matrix[np.triu_indices_from(fc_matrix, k=1)] = fc_vector fc_matrix = fc_matrix + fc_matrix.T return fc_matrix def to_power_fc_vector(fc_matrix): """ Converts a Power connectivity matrix (264 x 264) to a vector (34716 x 1). Discards diagonal values and assumes a symmetric matrix. """ return fc_matrix[np.triu_indices(POWER_NUM_NODES, k=1)] def get_power_fc_matrix_labels(return_system=False): """ Gets a matrix (264 x 264) where each element is a pair representing the endpoints of that connection. The pair can either be ROI-to-ROI (1, 2) or Sytem-to-System ('Cerebellar', 'Cerebellar'). """ labels = POWER_LABELS['System'].values if return_system else POWER_LABELS.index label_matrix = [] for row_label in labels: row_labels = [] label_matrix.append([(row_label, col_label) for col_label in labels]) return np.array(label_matrix) def get_power_fc_vector_labels(return_system=False): """ Gets a vector (34716 x 1) where each element is a pair representing the endpoints of that connection. """ power_fc_matrix_labels = get_power_fc_matrix_labels(return_system) power_fc_vector_labels = to_power_fc_vector(power_fc_matrix_labels) return power_fc_vector_labels def get_power_mpl_legend(): """ Gets the Power legend as a list of Matplotlib legend patches mapping color to system/network. """ power_legend_patches = [] for color, system in POWER_LEGEND.items(): power_legend_patches.append(mpatches.Patch(color=color, label=system)) return power_legend_patches
[ "nilearn.connectome.ConnectivityMeasure", "pandas.read_csv", "nilearn.input_data.NiftiSpheresMasker", "nilearn.datasets.fetch_coords_power_2011", "numpy.zeros", "numpy.triu_indices", "numpy.array", "numpy.triu_indices_from", "matplotlib.patches.Patch", "numpy.vstack" ]
[((295, 329), 'nilearn.datasets.fetch_coords_power_2011', 'datasets.fetch_coords_power_2011', ([], {}), '()\n', (327, 329), False, 'from nilearn import plotting, image, datasets\n'), ((449, 484), 'pandas.read_csv', 'pd.read_csv', (['POWER'], {'index_col': '"""ROI"""'}), "(POWER, index_col='ROI')\n", (460, 484), True, 'import pandas as pd\n'), ((345, 436), 'numpy.vstack', 'np.vstack', (["(POWER_DATASET.rois['x'], POWER_DATASET.rois['y'], POWER_DATASET.rois['z'])"], {}), "((POWER_DATASET.rois['x'], POWER_DATASET.rois['y'], POWER_DATASET.\n rois['z']))\n", (354, 436), True, 'import numpy as np\n'), ((1895, 1985), 'nilearn.input_data.NiftiSpheresMasker', 'NiftiSpheresMasker', ([], {'seeds': 'POWER_COORDS', 'smoothing_fwhm': '(6)', 'radius': '(5.0)', 'standardize': '(True)'}), '(seeds=POWER_COORDS, smoothing_fwhm=6, radius=5.0,\n standardize=True)\n', (1913, 1985), False, 'from nilearn.input_data import NiftiSpheresMasker\n'), ((2065, 2104), 'nilearn.connectome.ConnectivityMeasure', 'ConnectivityMeasure', ([], {'kind': '"""correlation"""'}), "(kind='correlation')\n", (2084, 2104), False, 'from nilearn.connectome import ConnectivityMeasure\n'), ((2450, 2494), 'numpy.zeros', 'np.zeros', (['(POWER_NUM_NODES, POWER_NUM_NODES)'], {}), '((POWER_NUM_NODES, POWER_NUM_NODES))\n', (2458, 2494), True, 'import numpy as np\n'), ((3416, 3438), 'numpy.array', 'np.array', (['label_matrix'], {}), '(label_matrix)\n', (3424, 3438), True, 'import numpy as np\n'), ((2509, 2545), 'numpy.triu_indices_from', 'np.triu_indices_from', (['fc_matrix'], {'k': '(1)'}), '(fc_matrix, k=1)\n', (2529, 2545), True, 'import numpy as np\n'), ((2838, 2875), 'numpy.triu_indices', 'np.triu_indices', (['POWER_NUM_NODES'], {'k': '(1)'}), '(POWER_NUM_NODES, k=1)\n', (2853, 2875), True, 'import numpy as np\n'), ((4060, 4101), 'matplotlib.patches.Patch', 'mpatches.Patch', ([], {'color': 'color', 'label': 'system'}), '(color=color, label=system)\n', (4074, 4101), True, 'import matplotlib.patches as mpatches\n')]
""" Unit tests for PowerExpansion class """ __author__ = '<NAME>' import unittest import numpy as np from scipy.special import sph_harm import onsager.PowerExpansion as PE T3D = PE.Taylor3D T2D = PE.Taylor2D class PowerExpansionTests(unittest.TestCase): """Tests to make sure our power expansions are constructed correctly and behaving as advertised""" def setUp(self): """initial setup for testing""" self.phi = np.pi * 0.2234 self.theta = np.pi * 0.7261 self.c = T3D() self.basis = [(np.eye(2), np.array([0.5, -np.sqrt(0.75), 0.])), (np.eye(2), np.array([0.5, np.sqrt(0.75), 0.])), (np.eye(2), np.array([-1., 0., 0.])), (np.eye(2), np.array([-0.5, -np.sqrt(0.75), 0.])), (np.eye(2), np.array([-0.5, np.sqrt(0.75), 0.])), (np.eye(2), np.array([1., 0., 0.])), (np.eye(2) * 2, np.array([0., 0., 1.])), (np.eye(2) * 2, np.array([0., 0., -1.])), ] def testExpansionYlmpow(self): """Test the expansion of Ylm into powers""" for (phi, theta) in [(self.phi + dp, self.theta + dt) for dp in (0., 0.25 * np.pi, 0.5 * np.pi, 0.75 * np.pi) for dt in (0., 0.5 * np.pi, np.pi, 1.5 * np.pi)]: utest, umagn = T3D.powexp(np.array([np.sin(phi) * np.cos(theta), np.sin(phi) * np.sin(theta), np.cos(phi)])) self.assertAlmostEqual(umagn, 1) Ylm0 = np.zeros(T3D.NYlm, dtype=complex) # Ylm as power expansions for lm in range(T3D.NYlm): l, m = T3D.ind2Ylm[lm, 0], T3D.ind2Ylm[lm, 1] Ylm0[lm] = sph_harm(m, l, theta, phi) Ylmexp = np.dot(T3D.Ylmpow[lm], utest) self.assertAlmostEqual(Ylm0[lm], Ylmexp, msg="Failure for Ylmpow " "l={} m={}; theta={}, phi={}\n{} != {}".format(l, m, theta, phi, Ylm0[lm], Ylmexp)) # power expansions in Ylm's for p in range(T3D.NYlm): pYlm = np.dot(T3D.powYlm[p], Ylm0) self.assertAlmostEqual(utest[p], pYlm, msg="Failure for powYlm " "{}; theta={}, phi={}\n{} != {}".format(T3D.ind2pow[p], theta, phi, utest[p], pYlm)) # projection (note that Lproj is not symmetric): so this test ensures that v.u and (proj.v).u # give the same value uproj = np.tensordot(T3D.Lproj[-1], utest, axes=(0, 0)) for p in range(T3D.NYlm): self.assertAlmostEqual(utest[p], uproj[p], msg="Projection failure for " "{}\n{} != {}".format(T3D.ind2pow[p], uproj[p], utest[p])) def testProjection(self): """Test that the L-projections are correct""" # Try to do this sequentially for tup in [(0, 0, 0), (1, 0, 0), (0, 1, 0), (0, 0, 1)]: v = np.zeros(T3D.Npower) v[T3D.pow2ind[tup]] = 1. Pv = np.tensordot(T3D.Lproj[-1], v, axes=1) # now, try with multiplying by x^2+y^2+z^2: vxyz = np.zeros(T3D.Npower) vxyz[T3D.pow2ind[tup[0] + 2, tup[1], tup[2]]] = 1. vxyz[T3D.pow2ind[tup[0], tup[1] + 2, tup[2]]] = 1. vxyz[T3D.pow2ind[tup[0], tup[1], tup[2] + 2]] = 1. Pvxyz = np.tensordot(T3D.Lproj[-1], vxyz, axes=1) self.assertTrue(np.allclose(v, Pv)) self.assertTrue(np.allclose(v, Pvxyz)) for l in range(T3D.Lmax + 1): Pv = np.tensordot(T3D.Lproj[l], v, axes=1) Pvxyz = np.tensordot(T3D.Lproj[l], vxyz, axes=1) if l == sum(tup): self.assertTrue(np.allclose(v, Pv)) self.assertTrue(np.allclose(v, Pvxyz)) else: self.assertTrue(np.allclose(Pv, 0)) self.assertTrue(np.allclose(Pvxyz, 0)) def testEvaluation(self): """Test out the evaluation functions in an expansion, including with scalar multiply and addition""" def approxexp(u): """4th order expansion of exp(u)""" return 1 + u * (1 + u * (0.5 + u * (1 / 6 + u / 24))) def createExpansion(n): return lambda u: u ** n / PE.factorial(n, True) c = T3D() for coeff in c.constructexpansion(self.basis): c.addterms(coeff) for (n, l) in c.nl(): self.assertEqual(n, l) fnu = {(n, l): createExpansion(n) for (n, l) in c.nl()} # or could do this in previous loop # c2 = 2*c c2 = c.copy() c2 *= 2 c3 = c + c c4 = c2 - c ### NOTE! We have to do it *this way*; otherwise, it will try to use the sum in np.array, ### and that WILL NOT WORK with our expansion. c5 = c + np.eye(2) prod = np.array([[-4.2, 2.67], [1.3, 3.21]]) c6 = c.ldot(prod) c7 = c.copy() c7.irdot(prod) sum([c, c2, c3]) # tests whether we can use sum for u in [np.zeros(3), np.array([1., 0., 0.]), np.array([0., 1., 0.]), np.array([0., 0., 1.]), np.array([0.234, -0.85, 1.25]), np.array([1.24, 0.71, -0.98])]: umagn = np.sqrt(np.dot(u, u)) fval = {nl: f(umagn) for nl, f in fnu.items()} # comparison value: value = sum(pre * approxexp(np.dot(u, vec)) for pre, vec in self.basis) valsum = c(u, fval) funcsum = c(u, fnu) dictsum = sum(fval[k] * v for k, v in c(u).items()) self.assertTrue(np.allclose(value, valsum), msg="Failure for call with values for {}\n{} != {}".format(u, value, valsum)) self.assertTrue(np.allclose(value, funcsum), msg="Failure for call with function for {}\n{} != {}".format(u, value, funcsum)) self.assertTrue(np.allclose(value, dictsum), msg="Failure for call with dictionary for {}\n{} != {}".format(u, value, dictsum)) self.assertTrue(np.allclose(2 * value, c2(u, fval)), msg="Failure with scalar multiply?") self.assertTrue(np.allclose(2 * value, c3(u, fval)), msg="Failure with addition?") self.assertTrue(np.allclose(value, c4(u, fval)), msg="Failure with subtraction?") self.assertTrue(np.allclose(value + np.eye(2), c5(u, fval)), msg="Failure with scalar addition?") self.assertTrue(np.allclose(np.dot(prod, value), c6(u, fval)), msg="Failure with tensor dot product?") self.assertTrue(np.allclose(np.dot(value, prod), c7(u, fval)), msg="Failure with tensor dot product inplace?") def testProduct(self): """Test out the evaluation functions in an expansion, using coefficient products""" def approxexp(u): """2nd order expansion of exp(u)""" # return 1 + u*(1 + u*(0.5 + u*(1/6 + u/24))) return 1 + u * (1 + u * 0.5) def createExpansion(n): return lambda u: u ** n c = T3D() for coeff in c.constructexpansion(self.basis, N=2): c.addterms(coeff) c *= {(n, l): 1. / PE.factorial(n, True) for (n, l) in c.nl()} # scalar multiply to create a Taylor expansion for exp c2 = c * c for (n, l) in c2.nl(): self.assertEqual(n, l) fnu = {(n, l): createExpansion(n) for (n, l) in c2.nl()} # or could do this in previous loop for u in [np.zeros(3), np.array([1., 0., 0.]), np.array([0., 1., 0.]), np.array([0., 0., 1.]), np.array([0.234, -0.85, 1.25]), np.array([1.24, 0.71, -0.98])]: umagn = np.sqrt(np.dot(u, u)) fval = {nl: f(umagn) for nl, f in fnu.items()} # comparison value: value = sum(pre * approxexp(np.dot(u, vec)) for pre, vec in self.basis) valsum = c(u, fval) funcsum = c(u, fnu) dictsum = sum(fval[k] * v for k, v in c(u).items()) value2 = np.dot(value, value) valsum2 = c2(u, fval) funcsum2 = c2(u, fnu) dictsum2 = sum(fval[k] * v for k, v in c2(u).items()) self.assertTrue(np.allclose(value, valsum), msg="Failure for call with values for {}\n{} != {}".format(u, value, valsum)) self.assertTrue(np.allclose(value, funcsum), msg="Failure for call with function for {}\n{} != {}".format(u, value, funcsum)) self.assertTrue(np.allclose(value, dictsum), msg="Failure for call with dictionary for {}\n{} != {}".format(u, value, dictsum)) self.assertTrue(np.allclose(value2, valsum2), msg="Failure for call with values for {}\n{} != {}".format(u, value2, valsum2)) self.assertTrue(np.allclose(value2, funcsum2), msg="Failure for call with function for {}\n{} != {}".format(u, value2, funcsum2)) self.assertTrue(np.allclose(value2, dictsum2), msg="Failure for call with dictionary for {}\n{} != {}".format(u, value2, dictsum2)) def testReduceExpand(self): """Test our reduction and expansion operations""" def approxexp(u): """4th order expansion of exp(u)""" return 1 + u * (1 + u * (0.5 + u * (1 / 6 + u / 24))) def createExpansion(n): return lambda u: u ** n c = T3D([c[0] for c in T3D.constructexpansion(self.basis, N=4, pre=(0, 1, 1 / 2, 1 / 6, 1 / 24))]) self.assertEqual(len(c.coefflist), 5) # should have all n from 0 to 4 c2 = c.copy() c2.reduce() # check the reduction: should be just two terms remaining: n=2, n=4 self.assertEqual(len(c2.coefflist), 2) for n, l, coeff in c2.coefflist: self.assertTrue(n == 2 or n == 4) if n == 2: self.assertEqual(l, 2) else: self.assertEqual(l, 4) c3 = c2.copy() c3.separate() # print("c2:\n{}".format(c2)) # print("c3:\n{}".format(c3)) # now should have 2 + 3 = 5 terms self.assertEqual(len(c3.coefflist), 5) for n, l, coeff in c3.coefflist: self.assertTrue(n == 2 or n == 4) if n == 2: self.assertTrue(l == 0 or l == 2) else: self.assertTrue(l == 0 or l == 2 or l == 4) # also check that the only non-zero terms for a given l are value are those values if l == 0: lmin = 0 else: lmin = T3D.powlrange[l - 1] lmax = T3D.powlrange[l] # self.assertTrue(np.allclose(coeff[0:lmin], 0)) self.assertTrue(np.allclose(coeff[lmax:T3D.Npower], 0)) self.assertFalse(np.allclose(coeff[lmin:lmax], 0)) Ylmcoeff = np.tensordot(T3D.powYlm[:T3D.powlrange[l], :], coeff, axes=(0, 0)) # now in Ylm lmin = l ** 2 lmax = (l + 1) ** 2 self.assertTrue(np.allclose(Ylmcoeff[0:lmin], 0)) self.assertFalse(np.allclose(Ylmcoeff[lmin:lmax], 0)) self.assertTrue(np.allclose(Ylmcoeff[lmax:T3D.NYlm], 0)) # a little tricky to make sure we get ALL the functions (instead of making multiple dictionaries) fnu = {(n, l): createExpansion(n) for (n, l) in c.nl()} # or could do this in previous loop for (n, l) in c3.nl(): if (n, l) not in fnu: fnu[(n, l)] = createExpansion(n) for u in [np.zeros(3), np.array([1., 0., 0.]), np.array([0., 1., 0.]), np.array([0., 0., 1.]), np.array([0.234, -0.85, 1.25]), np.array([1.24, 0.71, -0.98])]: umagn = np.sqrt(np.dot(u, u)) # compare values: self.assertTrue(np.allclose(c(u, fnu), c2(u, fnu)), msg="Failure on reduce:\n{} != {}".format(c(u, fnu), c2(u, fnu))) self.assertTrue(np.allclose(c(u, fnu), c3(u, fnu)), msg="Failure on expand:\n{} != {}".format(c(u, fnu), c3(u, fnu))) # do a test of projection using some random coefficients coeffrand = np.random.uniform(-1, 1, T3D.Npower) coeffrand.shape = (T3D.Npower, 1, 1) crand = T3D([(0, T3D.Lmax, coeffrand)]) crand.separate() for (n, l, c) in crand.coefflist: Ylmcoeff = np.tensordot(T3D.powYlm[:T3D.powlrange[l], :], c, axes=(0, 0)) # now in Ylm lmin = l ** 2 lmax = (l + 1) ** 2 self.assertTrue(np.allclose(Ylmcoeff[0:lmin], 0)) self.assertFalse(np.allclose(Ylmcoeff[lmin:lmax], 0)) self.assertTrue(np.allclose(Ylmcoeff[lmax:T3D.NYlm], 0)) def testInverse(self): """Test our inverse expansion""" # This is *very tricky* because the inverse expansion is *strictly* a Taylor series; # it won't be exact. Should be up to order u^2 def approxexp(u): """4th order expansion of exp(u)""" return 1 + u * (1 + u * (0.5 + u * (1 / 6 + u / 24))) def createExpansion(n): return lambda u: u ** n cubicbasis = [(np.eye(2), np.array([1., 0., 0.])), (np.eye(2), np.array([-1., 0., 0.])), (np.eye(2), np.array([0., 1., 0.])), (np.eye(2), np.array([0., -1., 0.])), (np.eye(2), np.array([0., 0., 1.])), (np.eye(2), np.array([0., 0., -1.])) ] c = T3D([c[0] for c in T3D.constructexpansion(cubicbasis, N=4, pre=(0, 1, 1 / 2, 1 / 6, 1 / 24))]) c.reduce() cinv = c.inv(Nmax=0) # since c ~ x^2, cinv ~ 1/x^2, and L=4 should take us to x^0 fnu = {(n, l): createExpansion(n) for (n, l) in c.nl()} # or could do this in previous loop for (n, l) in cinv.nl(): if (n, l) not in fnu: fnu[(n, l)] = createExpansion(n) for u in [np.array([0.25, 0., 0.]), np.array([0., 0.1, 0.]), np.array([0., 0., 0.1]), np.array([0.0234, -0.085, 0.125]), np.array([0.124, 0.071, -0.098])]: umagn = np.sqrt(np.dot(u, u)) cval = c(u, fnu) cinvval = cinv(u, fnu) cval_inv = np.dot(cval, cinvval) - np.eye(2) # cval_directinv = np.linalg.inv(cval) self.assertTrue(np.all(abs(cval_inv) < (1 / 120) * umagn ** 4), msg="cinv * c != 1?\nc={}\ncinv={}\nc*cinv-1={}".format(cval, cinvval, cval_inv)) def testTruncation(self): """Make sure truncation works how we expect""" c = T3D([nlc[0] for nlc in T3D.constructexpansion(self.basis, N=4)]) c.reduce() self.assertEqual(max(n for n, l, c in c.coefflist), 4) c2 = c.truncate(2) self.assertEqual(max(n for n, l, c in c2.coefflist), 2) self.assertEqual(max(n for n, l, c in c.coefflist), 4) c.truncate(2, inplace=True) self.assertEqual(max(n for n, l, c in c.coefflist), 2) def testIndexingSlicing(self): """Can we index into our expansions to get a new expansion? Can we slice? Can we assign?""" def createExpansion(n): return lambda u: u ** n newbasis = [(np.array([[1., 6., 5.], [5., 2., 4.], [5., 4., 3.]]), np.array([2 / 3., 1 / 3, -1 / 2]))] c = T3D([nlc[0] for nlc in T3D.constructexpansion(newbasis, N=4)]) fnu = {(n, l): createExpansion(n) for n in range(5) for l in range(5)} # now we have something to work with. We should have a basis from n=0 up to n=4 of 3x3 matrices. c00 = c[0, 0] for u in [np.array([0.25, 0., 0.]), np.array([0., 0.1, 0.]), np.array([0., 0., 0.1]), np.array([0.0234, -0.085, 0.125]), np.array([0.124, 0.071, -0.098])]: cval = c(u, fnu) c00val = c00(u, fnu) self.assertEqual(cval[0, 0], c00val) # now, an assignment test. This will be funky; first, we do a "copy" operation so that # c00 is clean--it is no longer a "view" or slice of c, but it's own thing. c00 = c00.copy() # now, set the 0,0 value to be twice what it was before: c[0, 0] = 2. * c00 for u in [np.array([0.25, 0., 0.]), np.array([0., 0.1, 0.]), np.array([0., 0., 0.1]), np.array([0.0234, -0.085, 0.125]), np.array([0.124, 0.071, -0.098])]: cval = c(u, fnu) c00val = c00(u, fnu) self.assertEqual(cval[0, 0], 2. * c00val) c00inv = c00.inv(Nmax=4) c00inv.reduce() for u in [np.array([0.025, 0., 0.]), np.array([0., 0.025, 0.]), np.array([0., 0., 0.025]), np.array([0.0234, -0.05, 0.05]), np.array([-0.024, 0.041, -0.033])]: c00val = c00(u, fnu) c00invval = c00inv(u, fnu) self.assertAlmostEqual(c00val * c00invval, 1) def testRotation(self): """Set of tests for rotating directions""" def createExpansion(n): return lambda u: u ** n newbasis = [(0.89 * np.eye(1), np.array([2 / 3., 1 / 3, -1 / 2]))] c = T3D([nlc[0] for nlc in T3D.constructexpansion(newbasis, N=4)]) # does this still work if we do this? # c.reduce() fnu = {(n, l): createExpansion(n) for n in range(5) for l in range(5)} for rot in [np.eye(3), 2. * np.eye(3), 0.5 * np.eye(3), np.array([[1.25, 0.5, 0.25], [-0.25, 0.9, 0.5], [-0.75, -0.4, 0.6]]), np.array([[0., 1., 0.], [-1., 0., 0.], [0., 0., 1.]])]: rotbasis = [(newbasis[0][0], np.dot(newbasis[0][1], rot))] crotdirect = T3D([nlc[0] for nlc in T3D.constructexpansion(rotbasis, N=4)]) crot = c.rotate(c.rotatedirections(rot)) for u in [np.array([1.2, 0., 0.]), np.array([0., 1.2, 0.]), np.array([0., 0., 1.2]), np.array([0.234, -0.5, 0.5]), np.array([-0.24, 0.41, -1.3])]: self.assertAlmostEqual(crot(u, fnu)[0, 0], crotdirect(u, fnu)[0, 0], msg="Failed before reduce()") # now, a more detailed test: do a reduce. c2 = c.copy() c.reduce() for rot in [np.eye(3), 2. * np.eye(3), 0.5 * np.eye(3), np.array([[1.25, 0.5, 0.25], [-0.25, 0.9, 0.5], [-0.75, -0.4, 0.6]]), np.array([[0., 1., 0.], [-1., 0., 0.], [0., 0., 1.]])]: rotbasis = [(newbasis[0][0], np.dot(newbasis[0][1], rot))] crotdirect = T3D([nlc[0] for nlc in T3D.constructexpansion(rotbasis, N=4)]) crot = c.rotate(c.rotatedirections(rot)) for u in [np.array([1.2, 0., 0.]), np.array([0., 1.2, 0.]), np.array([0., 0., 1.2]), np.array([0.234, -0.5, 0.5]), np.array([-0.24, 0.41, -1.3])]: self.assertAlmostEqual(c(u, fnu)[0, 0], c2(u, fnu)[0, 0], msg="Failure in reduce() to produce equal function values?") self.assertAlmostEqual(crot(u, fnu)[0, 0], crotdirect(u, fnu)[0, 0], msg="Failed after reduce() for\n{}".format(rot)) def FourierCoeff(l, theta): """This is the equivalent of sph_harm for the two-dimensional case""" return np.exp(1j*l*theta) class PowerExpansion2DTests(unittest.TestCase): """Tests to make sure our power expansions are constructed correctly and behaving as advertised""" def setUp(self): """initial setup for testing""" self.theta = np.pi * 0.2234 self.c = T2D() self.basis = [(np.eye(2), np.array([0.5, -np.sqrt(0.75)])), (np.eye(2), np.array([0.5, np.sqrt(0.75)])), (2.*np.eye(2), np.array([-1., 0.])), (np.eye(2), np.array([-0.5, -np.sqrt(0.75)])), (np.eye(2), np.array([-0.5, np.sqrt(0.75)])), (2.*np.eye(2), np.array([1., 0.])) ] def testIndexing(self): for ind, l in enumerate(self.c.ind2FC): self.assertEqual(ind, self.c.FC2ind[l]) for l in range(-self.c.Lmax, self.c.Lmax+1): self.assertEqual(l, self.c.ind2FC[self.c.FC2ind[l]]) def testExpansionFCpow(self): """Test the expansion of FC into powers""" for theta in [self.theta + dt*np.pi for dt in np.linspace(0, 2, num=16, endpoint=False)]: utest, umagn = T2D.powexp(np.array([np.cos(theta), np.sin(theta)])) self.assertAlmostEqual(umagn, 1) FC0 = np.zeros(T2D.NFC, dtype=complex) # FC as power expansions for lind in range(T2D.NFC): l = T2D.ind2FC[lind] FC0[lind] = FourierCoeff(l, theta) FCexp = np.dot(T2D.FCpow[lind], utest) self.assertAlmostEqual(FC0[lind], FCexp, msg="Failure for FCpow " "l={}; theta={}\n{} != {}".format(l, theta, FC0[lind], FCexp)) # power expansions in FC's for p in range(T2D.NFC): pFC = np.dot(T2D.powFC[p], FC0) self.assertAlmostEqual(utest[p], pFC, msg="Failure for powFC " "{}; theta={}\n{} != {}".format(T2D.ind2pow[p], theta, utest[p], pFC)) # projection (note that Lproj is not symmetric): so this test ensures that v.u and (proj.v).u # give the same value uproj = np.tensordot(T2D.Lproj[-1], utest, axes=(0, 0)) for p in range(T2D.NFC): self.assertAlmostEqual(utest[p], uproj[p], msg="Projection failure for " "{}\n{} != {}".format(T2D.ind2pow[p], uproj[p], utest[p])) def testProjection(self): """Test that the L-projections are correct""" # Try to do this sequentially for tup in [(0, 0), (1, 0), (0, 1)]: v = np.zeros(T2D.Npower) v[T2D.pow2ind[tup]] = 1. Pv = np.tensordot(T2D.Lproj[-1], v, axes=1) # now, try with multiplying by x^2+y^2+z^2: vxy = np.zeros(T2D.Npower) vxy[T2D.pow2ind[tup[0] + 2, tup[1]]] = 1. vxy[T2D.pow2ind[tup[0], tup[1] + 2]] = 1. Pvxy = np.tensordot(T2D.Lproj[-1], vxy, axes=1) self.assertTrue(np.allclose(v, Pv)) self.assertTrue(np.allclose(v, Pvxy)) for l in range(T2D.Lmax + 1): Pv = np.tensordot(T2D.Lproj[l], v, axes=1) Pvxy = np.tensordot(T2D.Lproj[l], vxy, axes=1) if l == sum(tup): self.assertTrue(np.allclose(v, Pv)) self.assertTrue(np.allclose(v, Pvxy)) else: self.assertTrue(np.allclose(Pv, 0)) self.assertTrue(np.allclose(Pvxy, 0)) def testEvaluation(self): """Test out the evaluation functions in an expansion, including with scalar multiply and addition""" def approxexp(u): """4th order expansion of exp(u)""" return 1 + u * (1 + u * (0.5 + u * (1 / 6 + u / 24))) def createExpansion(n): return lambda u: u ** n / PE.factorial(n, True) c = T2D() for coeff in c.constructexpansion(self.basis): c.addterms(coeff) for (n, l) in c.nl(): self.assertEqual(n, l) fnu = {(n, l): createExpansion(n) for (n, l) in c.nl()} # or could do this in previous loop # c2 = 2*c c2 = c.copy() c2 *= 2 c3 = c + c c4 = c2 - c ### NOTE! We have to do it *this way*; otherwise, it will try to use the sum in np.array, ### and that WILL NOT WORK with our expansion. c5 = c + np.eye(2) prod = np.array([[-4.2, 2.67], [1.3, 3.21]]) c6 = c.ldot(prod) c7 = c.copy() c7.irdot(prod) sum([c, c2, c3]) # tests whether we can use sum for u in [np.zeros(2), np.array([1., 0.]), np.array([0., 1.]), np.array([0., 0.]), np.array([0.234, -0.85]), np.array([1.24, 0.71])]: umagn = np.sqrt(np.dot(u, u)) fval = {nl: f(umagn) for nl, f in fnu.items()} # comparison value: value = sum(pre * approxexp(np.dot(u, vec)) for pre, vec in self.basis) valsum = c(u, fval) funcsum = c(u, fnu) dictsum = sum(fval[k] * v for k, v in c(u).items()) self.assertTrue(np.allclose(value, valsum), msg="Failure for call with values for {}\n{} != {}".format(u, value, valsum)) self.assertTrue(np.allclose(value, funcsum), msg="Failure for call with function for {}\n{} != {}".format(u, value, funcsum)) self.assertTrue(np.allclose(value, dictsum), msg="Failure for call with dictionary for {}\n{} != {}".format(u, value, dictsum)) self.assertTrue(np.allclose(2 * value, c2(u, fval)), msg="Failure with scalar multiply?") self.assertTrue(np.allclose(2 * value, c3(u, fval)), msg="Failure with addition?") self.assertTrue(np.allclose(value, c4(u, fval)), msg="Failure with subtraction?") self.assertTrue(np.allclose(value + np.eye(2), c5(u, fval)), msg="Failure with scalar addition?") self.assertTrue(np.allclose(np.dot(prod, value), c6(u, fval)), msg="Failure with tensor dot product?") self.assertTrue(np.allclose(np.dot(value, prod), c7(u, fval)), msg="Failure with tensor dot product inplace?") def testProduct(self): """Test out the evaluation functions in an expansion, using coefficient products""" def approxexp(u): """2nd order expansion of exp(u)""" # return 1 + u*(1 + u*(0.5 + u*(1/6 + u/24))) return 1 + u * (1 + u * 0.5) def createExpansion(n): return lambda u: u ** n c = T2D() for coeff in c.constructexpansion(self.basis, N=2): c.addterms(coeff) c *= {(n, l): 1. / PE.factorial(n, True) for (n, l) in c.nl()} # scalar multiply to create a Taylor expansion for exp c2 = c * c for (n, l) in c2.nl(): self.assertEqual(n, l) fnu = {(n, l): createExpansion(n) for (n, l) in c2.nl()} # or could do this in previous loop for u in [np.zeros(2), np.array([1., 0.]), np.array([0., 1.]), np.array([0.234, -0.85]), np.array([1.24, 0.71])]: umagn = np.sqrt(np.dot(u, u)) fval = {nl: f(umagn) for nl, f in fnu.items()} # comparison value: value = sum(pre * approxexp(np.dot(u, vec)) for pre, vec in self.basis) valsum = c(u, fval) funcsum = c(u, fnu) dictsum = sum(fval[k] * v for k, v in c(u).items()) value2 = np.dot(value, value) valsum2 = c2(u, fval) funcsum2 = c2(u, fnu) dictsum2 = sum(fval[k] * v for k, v in c2(u).items()) self.assertTrue(np.allclose(value, valsum), msg="Failure for call with values for {}\n{} != {}".format(u, value, valsum)) self.assertTrue(np.allclose(value, funcsum), msg="Failure for call with function for {}\n{} != {}".format(u, value, funcsum)) self.assertTrue(np.allclose(value, dictsum), msg="Failure for call with dictionary for {}\n{} != {}".format(u, value, dictsum)) self.assertTrue(np.allclose(value2, valsum2), msg="Failure for call with values for {}\n{} != {}".format(u, value2, valsum2)) self.assertTrue(np.allclose(value2, funcsum2), msg="Failure for call with function for {}\n{} != {}".format(u, value2, funcsum2)) self.assertTrue(np.allclose(value2, dictsum2), msg="Failure for call with dictionary for {}\n{} != {}".format(u, value2, dictsum2)) def testReduceExpand(self): """Test our reduction and expansion operations""" def approxexp(u): """4th order expansion of exp(u)""" return 1 + u * (1 + u * (0.5 + u * (1 / 6 + u / 24))) def createExpansion(n): return lambda u: u ** n c = T2D([c[0] for c in T2D.constructexpansion(self.basis, N=4, pre=(0, 1, 1 / 2, 1 / 6, 1 / 24))]) self.assertEqual(len(c.coefflist), 5) # should have all n from 0 to 4 c2 = c.copy() c2.reduce() # check the reduction: should be just two terms remaining: n=2, n=4 self.assertEqual(len(c2.coefflist), 2) for n, l, coeff in c2.coefflist: self.assertTrue(n == 2 or n == 4) if n == 2: self.assertEqual(l, 2) else: self.assertEqual(l, 4) c3 = c2.copy() c3.separate() # print("c2:\n{}".format(c2)) # print("c3:\n{}".format(c3)) # now should have 2 + 3 = 5 terms self.assertEqual(len(c3.coefflist), 5) for n, l, coeff in c3.coefflist: self.assertTrue(n == 2 or n == 4) if n == 2: self.assertTrue(l == 0 or l == 2) else: self.assertTrue(l == 0 or l == 2 or l == 4) # also check that the only non-zero terms for a given l are value are those values lmin, lmax = T2D.powlrange[l-1], T2D.powlrange[l] self.assertTrue(np.allclose(coeff[0:lmin], 0)) self.assertTrue(np.allclose(coeff[lmax:T2D.Npower], 0)) self.assertFalse(np.allclose(coeff[lmin:lmax], 0)) # check directly the Fourier transform: FCcoeff = np.tensordot(T2D.powFC[:T2D.powlrange[l], :], coeff, axes=(0, 0)) # now in FC # only the lplus and lminus should be non-zero: lp, lm = T2D.FC2ind[l], T2D.FC2ind[-l] for lind in range(T2D.NFC): if lind != lp and lind != lm: self.assertAlmostEqual(np.sum(np.abs(FCcoeff[lind])), 0) self.assertNotAlmostEqual(np.sum(np.abs(FCcoeff[lp])+np.abs(FCcoeff[lm])), 0) # a little tricky to make sure we get ALL the functions (instead of making multiple dictionaries) fnu = {(n, l): createExpansion(n) for (n, l) in c.nl()} # or could do this in previous loop for (n, l) in c3.nl(): if (n, l) not in fnu: fnu[(n, l)] = createExpansion(n) for u in [np.zeros(2), np.array([1., 0.]), np.array([0., 1.]), np.array([0.234, -0.85]), np.array([1.24, 0.71])]: umagn = np.sqrt(np.dot(u, u)) # compare values: self.assertTrue(np.allclose(c(u, fnu), c2(u, fnu)), msg="Failure on reduce:\n{} != {}".format(c(u, fnu), c2(u, fnu))) self.assertTrue(np.allclose(c(u, fnu), c3(u, fnu)), msg="Failure on expand:\n{} != {}".format(c(u, fnu), c3(u, fnu))) # do a test of projection using some random coefficients coeffrand = np.random.uniform(-1, 1, T2D.Npower) coeffrand.shape = (T2D.Npower, 1, 1) crand = T2D([(0, T2D.Lmax, coeffrand)]) crand.separate() for (n, l, c) in crand.coefflist: FCcoeff = np.tensordot(T2D.powFC[:T2D.powlrange[l], :], c, axes=(0, 0)) # now in FC # only the lplus and lminus should be non-zero: lp, lm = T2D.FC2ind[l], T2D.FC2ind[-l] for lind in range(T2D.NFC): if lind != lp and lind != lm: self.assertAlmostEqual(np.sum(np.abs(FCcoeff[lind])), 0) self.assertNotAlmostEqual(np.sum(np.abs(FCcoeff[lp])+np.abs(FCcoeff[lm])), 0) def testInverse(self): """Test our inverse expansion""" # This is *very tricky* because the inverse expansion is *strictly* a Taylor series; # it won't be exact. Should be up to order u^2 def approxexp(u): """4th order expansion of exp(u)""" return 1 + u * (1 + u * (0.5 + u * (1 / 6 + u / 24))) def createExpansion(n): return lambda u: u ** n cubicbasis = [(np.eye(2), np.array([1., 0.])), (np.eye(2), np.array([-1., 0.])), (np.eye(2), np.array([0., 1.])), (np.eye(2), np.array([0., -1.])) ] c = T2D([c[0] for c in T2D.constructexpansion(cubicbasis, N=4, pre=(0, 1, 1 / 2, 1 / 6, 1 / 24))]) c.reduce() cinv = c.inv(Nmax=0) # since c ~ x^2, cinv ~ 1/x^2, and L=4 should take us to x^0 fnu = {(n, l): createExpansion(n) for (n, l) in c.nl()} # or could do this in previous loop for (n, l) in cinv.nl(): if (n, l) not in fnu: fnu[(n, l)] = createExpansion(n) for u in [np.array([0.25, 0.]), np.array([0., 0.1]), np.array([0.0234, -0.085]), np.array([0.124, 0.071])]: umagn = np.sqrt(np.dot(u, u)) cval = c(u, fnu) cinvval = cinv(u, fnu) cval_inv = np.dot(cval, cinvval) - np.eye(2) # cval_directinv = np.linalg.inv(cval) self.assertTrue(np.all(abs(cval_inv) < (1 / 120) * umagn ** 4), msg="cinv * c != 1?\nc={}\ncinv={}\nc*cinv-1={}".format(cval, cinvval, cval_inv)) def testTruncation(self): """Make sure truncation works how we expect""" c = T2D([nlc[0] for nlc in T2D.constructexpansion(self.basis, N=4)]) c.reduce() self.assertEqual(max(n for n, l, c in c.coefflist), 4) c2 = c.truncate(2) self.assertEqual(max(n for n, l, c in c2.coefflist), 2) self.assertEqual(max(n for n, l, c in c.coefflist), 4) c.truncate(2, inplace=True) self.assertEqual(max(n for n, l, c in c.coefflist), 2) def testIndexingSlicing(self): """Can we index into our expansions to get a new expansion? Can we slice? Can we assign?""" def createExpansion(n): return lambda u: u ** n newbasis = [(np.array([[1., -2.], [-2., 2.]]), np.array([2 / 3., 1 / 3]))] c = T2D([nlc[0] for nlc in T2D.constructexpansion(newbasis, N=4)]) fnu = {(n, l): createExpansion(n) for n in range(5) for l in range(5)} # now we have something to work with. We should have a basis from n=0 up to n=4 of 2x2 matrices. c00 = c[0, 0] for u in [np.array([0.25, 0.]), np.array([0., 0.1]), np.array([0.0234, -0.085]), np.array([0.124, 0.071])]: cval = c(u, fnu) c00val = c00(u, fnu) self.assertEqual(cval[0, 0], c00val) # now, an assignment test. This will be funky; first, we do a "copy" operation so that # c00 is clean--it is no longer a "view" or slice of c, but it's own thing. c00 = c00.copy() # now, set the 0,0 value to be twice what it was before: c[0, 0] = 2. * c00 for u in [np.array([0.25, 0.]), np.array([0., 0.1]), np.array([0.0234, -0.085]), np.array([0.124, 0.071])]: cval = c(u, fnu) c00val = c00(u, fnu) self.assertEqual(cval[0, 0], 2. * c00val) c00inv = c00.inv(Nmax=4) c00inv.reduce() for u in [np.array([0.025, 0.]), np.array([0., 0.01]), np.array([0.0234, -0.085]), np.array([0.0124, 0.071])]: c00val = c00(u, fnu) c00invval = c00inv(u, fnu) self.assertAlmostEqual(c00val * c00invval, 1) def testRotation(self): """Set of tests for rotating directions""" def createExpansion(n): return lambda u: u ** n newbasis = [(0.89 * np.eye(1), np.array([2 / 3., 1 / 3]))] c = T2D([nlc[0] for nlc in T2D.constructexpansion(newbasis, N=4)]) # does this still work if we do this? # c.reduce() fnu = {(n, l): createExpansion(n) for n in range(5) for l in range(5)} for rot in [np.eye(2), 2. * np.eye(2), 0.5 * np.eye(2), np.array([[1.25, 0.5], [-0.25, 0.9]]), np.array([[0., 1.], [-1., 0.]])]: rotbasis = [(newbasis[0][0], np.dot(newbasis[0][1], rot))] crotdirect = T2D([nlc[0] for nlc in T2D.constructexpansion(rotbasis, N=4)]) crot = c.rotate(c.rotatedirections(rot)) for u in [np.array([1.2, 0.]), np.array([0., 1.2]), np.array([0., 0.]), np.array([0.234, -0.5]), np.array([-0.24, 0.41])]: self.assertAlmostEqual(crot(u, fnu)[0, 0], crotdirect(u, fnu)[0, 0], msg="Failed before reduce()") # now, a more detailed test: do a reduce. c2 = c.copy() c.reduce() for rot in [np.eye(2), 2. * np.eye(2), 0.5 * np.eye(2), np.array([[1.25, 0.5], [-0.25, 0.9]]), np.array([[0., 1.], [-1., 0.]])]: rotbasis = [(newbasis[0][0], np.dot(newbasis[0][1], rot))] crotdirect = T2D([nlc[0] for nlc in T2D.constructexpansion(rotbasis, N=4)]) crot = c.rotate(c.rotatedirections(rot)) for u in [np.array([1.2, 0.]), np.array([0., 1.2]), np.array([0., 0.]), np.array([0.234, -0.5]), np.array([-0.24, 0.41])]: self.assertAlmostEqual(c(u, fnu)[0, 0], c2(u, fnu)[0, 0], msg="Failure in reduce() to produce equal function values?") self.assertAlmostEqual(crot(u, fnu)[0, 0], crotdirect(u, fnu)[0, 0], msg="Failed after reduce() for\n{}".format(rot))
[ "scipy.special.sph_harm", "numpy.random.uniform", "numpy.abs", "numpy.tensordot", "numpy.allclose", "numpy.zeros", "numpy.sin", "numpy.array", "numpy.exp", "numpy.linspace", "numpy.cos", "numpy.dot", "numpy.eye", "onsager.PowerExpansion.factorial", "numpy.sqrt" ]
[((20126, 20150), 'numpy.exp', 'np.exp', (['(1.0j * l * theta)'], {}), '(1.0j * l * theta)\n', (20132, 20150), True, 'import numpy as np\n'), ((5139, 5176), 'numpy.array', 'np.array', (['[[-4.2, 2.67], [1.3, 3.21]]'], {}), '([[-4.2, 2.67], [1.3, 3.21]])\n', (5147, 5176), True, 'import numpy as np\n'), ((12788, 12824), 'numpy.random.uniform', 'np.random.uniform', (['(-1)', '(1)', 'T3D.Npower'], {}), '(-1, 1, T3D.Npower)\n', (12805, 12824), True, 'import numpy as np\n'), ((24693, 24730), 'numpy.array', 'np.array', (['[[-4.2, 2.67], [1.3, 3.21]]'], {}), '([[-4.2, 2.67], [1.3, 3.21]])\n', (24701, 24730), True, 'import numpy as np\n'), ((32263, 32299), 'numpy.random.uniform', 'np.random.uniform', (['(-1)', '(1)', 'T2D.Npower'], {}), '(-1, 1, T2D.Npower)\n', (32280, 32299), True, 'import numpy as np\n'), ((1669, 1702), 'numpy.zeros', 'np.zeros', (['T3D.NYlm'], {'dtype': 'complex'}), '(T3D.NYlm, dtype=complex)\n', (1677, 1702), True, 'import numpy as np\n'), ((2693, 2740), 'numpy.tensordot', 'np.tensordot', (['T3D.Lproj[-1]', 'utest'], {'axes': '(0, 0)'}), '(T3D.Lproj[-1], utest, axes=(0, 0))\n', (2705, 2740), True, 'import numpy as np\n'), ((3191, 3211), 'numpy.zeros', 'np.zeros', (['T3D.Npower'], {}), '(T3D.Npower)\n', (3199, 3211), True, 'import numpy as np\n'), ((3266, 3304), 'numpy.tensordot', 'np.tensordot', (['T3D.Lproj[-1]', 'v'], {'axes': '(1)'}), '(T3D.Lproj[-1], v, axes=1)\n', (3278, 3304), True, 'import numpy as np\n'), ((3380, 3400), 'numpy.zeros', 'np.zeros', (['T3D.Npower'], {}), '(T3D.Npower)\n', (3388, 3400), True, 'import numpy as np\n'), ((3610, 3651), 'numpy.tensordot', 'np.tensordot', (['T3D.Lproj[-1]', 'vxyz'], {'axes': '(1)'}), '(T3D.Lproj[-1], vxyz, axes=1)\n', (3622, 3651), True, 'import numpy as np\n'), ((5114, 5123), 'numpy.eye', 'np.eye', (['(2)'], {}), '(2)\n', (5120, 5123), True, 'import numpy as np\n'), ((5324, 5335), 'numpy.zeros', 'np.zeros', (['(3)'], {}), '(3)\n', (5332, 5335), True, 'import numpy as np\n'), ((5337, 5362), 'numpy.array', 'np.array', (['[1.0, 0.0, 0.0]'], {}), '([1.0, 0.0, 0.0])\n', (5345, 5362), True, 'import numpy as np\n'), ((5361, 5386), 'numpy.array', 'np.array', (['[0.0, 1.0, 0.0]'], {}), '([0.0, 1.0, 0.0])\n', (5369, 5386), True, 'import numpy as np\n'), ((5385, 5410), 'numpy.array', 'np.array', (['[0.0, 0.0, 1.0]'], {}), '([0.0, 0.0, 1.0])\n', (5393, 5410), True, 'import numpy as np\n'), ((5427, 5457), 'numpy.array', 'np.array', (['[0.234, -0.85, 1.25]'], {}), '([0.234, -0.85, 1.25])\n', (5435, 5457), True, 'import numpy as np\n'), ((5477, 5506), 'numpy.array', 'np.array', (['[1.24, 0.71, -0.98]'], {}), '([1.24, 0.71, -0.98])\n', (5485, 5506), True, 'import numpy as np\n'), ((7977, 7988), 'numpy.zeros', 'np.zeros', (['(3)'], {}), '(3)\n', (7985, 7988), True, 'import numpy as np\n'), ((7990, 8015), 'numpy.array', 'np.array', (['[1.0, 0.0, 0.0]'], {}), '([1.0, 0.0, 0.0])\n', (7998, 8015), True, 'import numpy as np\n'), ((8014, 8039), 'numpy.array', 'np.array', (['[0.0, 1.0, 0.0]'], {}), '([0.0, 1.0, 0.0])\n', (8022, 8039), True, 'import numpy as np\n'), ((8038, 8063), 'numpy.array', 'np.array', (['[0.0, 0.0, 1.0]'], {}), '([0.0, 0.0, 1.0])\n', (8046, 8063), True, 'import numpy as np\n'), ((8080, 8110), 'numpy.array', 'np.array', (['[0.234, -0.85, 1.25]'], {}), '([0.234, -0.85, 1.25])\n', (8088, 8110), True, 'import numpy as np\n'), ((8130, 8159), 'numpy.array', 'np.array', (['[1.24, 0.71, -0.98]'], {}), '([1.24, 0.71, -0.98])\n', (8138, 8159), True, 'import numpy as np\n'), ((8529, 8549), 'numpy.dot', 'np.dot', (['value', 'value'], {}), '(value, value)\n', (8535, 8549), True, 'import numpy as np\n'), ((11453, 11519), 'numpy.tensordot', 'np.tensordot', (['T3D.powYlm[:T3D.powlrange[l], :]', 'coeff'], {'axes': '(0, 0)'}), '(T3D.powYlm[:T3D.powlrange[l], :], coeff, axes=(0, 0))\n', (11465, 11519), True, 'import numpy as np\n'), ((12130, 12141), 'numpy.zeros', 'np.zeros', (['(3)'], {}), '(3)\n', (12138, 12141), True, 'import numpy as np\n'), ((12143, 12168), 'numpy.array', 'np.array', (['[1.0, 0.0, 0.0]'], {}), '([1.0, 0.0, 0.0])\n', (12151, 12168), True, 'import numpy as np\n'), ((12167, 12192), 'numpy.array', 'np.array', (['[0.0, 1.0, 0.0]'], {}), '([0.0, 1.0, 0.0])\n', (12175, 12192), True, 'import numpy as np\n'), ((12191, 12216), 'numpy.array', 'np.array', (['[0.0, 0.0, 1.0]'], {}), '([0.0, 0.0, 1.0])\n', (12199, 12216), True, 'import numpy as np\n'), ((12233, 12263), 'numpy.array', 'np.array', (['[0.234, -0.85, 1.25]'], {}), '([0.234, -0.85, 1.25])\n', (12241, 12263), True, 'import numpy as np\n'), ((12283, 12312), 'numpy.array', 'np.array', (['[1.24, 0.71, -0.98]'], {}), '([1.24, 0.71, -0.98])\n', (12291, 12312), True, 'import numpy as np\n'), ((13008, 13070), 'numpy.tensordot', 'np.tensordot', (['T3D.powYlm[:T3D.powlrange[l], :]', 'c'], {'axes': '(0, 0)'}), '(T3D.powYlm[:T3D.powlrange[l], :], c, axes=(0, 0))\n', (13020, 13070), True, 'import numpy as np\n'), ((14603, 14629), 'numpy.array', 'np.array', (['[0.25, 0.0, 0.0]'], {}), '([0.25, 0.0, 0.0])\n', (14611, 14629), True, 'import numpy as np\n'), ((14629, 14654), 'numpy.array', 'np.array', (['[0.0, 0.1, 0.0]'], {}), '([0.0, 0.1, 0.0])\n', (14637, 14654), True, 'import numpy as np\n'), ((14654, 14679), 'numpy.array', 'np.array', (['[0.0, 0.0, 0.1]'], {}), '([0.0, 0.0, 0.1])\n', (14662, 14679), True, 'import numpy as np\n'), ((14697, 14730), 'numpy.array', 'np.array', (['[0.0234, -0.085, 0.125]'], {}), '([0.0234, -0.085, 0.125])\n', (14705, 14730), True, 'import numpy as np\n'), ((14750, 14782), 'numpy.array', 'np.array', (['[0.124, 0.071, -0.098]'], {}), '([0.124, 0.071, -0.098])\n', (14758, 14782), True, 'import numpy as np\n'), ((16299, 16325), 'numpy.array', 'np.array', (['[0.25, 0.0, 0.0]'], {}), '([0.25, 0.0, 0.0])\n', (16307, 16325), True, 'import numpy as np\n'), ((16325, 16350), 'numpy.array', 'np.array', (['[0.0, 0.1, 0.0]'], {}), '([0.0, 0.1, 0.0])\n', (16333, 16350), True, 'import numpy as np\n'), ((16350, 16375), 'numpy.array', 'np.array', (['[0.0, 0.0, 0.1]'], {}), '([0.0, 0.0, 0.1])\n', (16358, 16375), True, 'import numpy as np\n'), ((16393, 16426), 'numpy.array', 'np.array', (['[0.0234, -0.085, 0.125]'], {}), '([0.0234, -0.085, 0.125])\n', (16401, 16426), True, 'import numpy as np\n'), ((16446, 16478), 'numpy.array', 'np.array', (['[0.124, 0.071, -0.098]'], {}), '([0.124, 0.071, -0.098])\n', (16454, 16478), True, 'import numpy as np\n'), ((16906, 16932), 'numpy.array', 'np.array', (['[0.25, 0.0, 0.0]'], {}), '([0.25, 0.0, 0.0])\n', (16914, 16932), True, 'import numpy as np\n'), ((16932, 16957), 'numpy.array', 'np.array', (['[0.0, 0.1, 0.0]'], {}), '([0.0, 0.1, 0.0])\n', (16940, 16957), True, 'import numpy as np\n'), ((16957, 16982), 'numpy.array', 'np.array', (['[0.0, 0.0, 0.1]'], {}), '([0.0, 0.0, 0.1])\n', (16965, 16982), True, 'import numpy as np\n'), ((17000, 17033), 'numpy.array', 'np.array', (['[0.0234, -0.085, 0.125]'], {}), '([0.0234, -0.085, 0.125])\n', (17008, 17033), True, 'import numpy as np\n'), ((17053, 17085), 'numpy.array', 'np.array', (['[0.124, 0.071, -0.098]'], {}), '([0.124, 0.071, -0.098])\n', (17061, 17085), True, 'import numpy as np\n'), ((17279, 17306), 'numpy.array', 'np.array', (['[0.025, 0.0, 0.0]'], {}), '([0.025, 0.0, 0.0])\n', (17287, 17306), True, 'import numpy as np\n'), ((17306, 17333), 'numpy.array', 'np.array', (['[0.0, 0.025, 0.0]'], {}), '([0.0, 0.025, 0.0])\n', (17314, 17333), True, 'import numpy as np\n'), ((17333, 17360), 'numpy.array', 'np.array', (['[0.0, 0.0, 0.025]'], {}), '([0.0, 0.0, 0.025])\n', (17341, 17360), True, 'import numpy as np\n'), ((17378, 17409), 'numpy.array', 'np.array', (['[0.0234, -0.05, 0.05]'], {}), '([0.0234, -0.05, 0.05])\n', (17386, 17409), True, 'import numpy as np\n'), ((17429, 17462), 'numpy.array', 'np.array', (['[-0.024, 0.041, -0.033]'], {}), '([-0.024, 0.041, -0.033])\n', (17437, 17462), True, 'import numpy as np\n'), ((18061, 18070), 'numpy.eye', 'np.eye', (['(3)'], {}), '(3)\n', (18067, 18070), True, 'import numpy as np\n'), ((18125, 18193), 'numpy.array', 'np.array', (['[[1.25, 0.5, 0.25], [-0.25, 0.9, 0.5], [-0.75, -0.4, 0.6]]'], {}), '([[1.25, 0.5, 0.25], [-0.25, 0.9, 0.5], [-0.75, -0.4, 0.6]])\n', (18133, 18193), True, 'import numpy as np\n'), ((18215, 18277), 'numpy.array', 'np.array', (['[[0.0, 1.0, 0.0], [-1.0, 0.0, 0.0], [0.0, 0.0, 1.0]]'], {}), '([[0.0, 1.0, 0.0], [-1.0, 0.0, 0.0], [0.0, 0.0, 1.0]])\n', (18223, 18277), True, 'import numpy as np\n'), ((18995, 19004), 'numpy.eye', 'np.eye', (['(3)'], {}), '(3)\n', (19001, 19004), True, 'import numpy as np\n'), ((19059, 19127), 'numpy.array', 'np.array', (['[[1.25, 0.5, 0.25], [-0.25, 0.9, 0.5], [-0.75, -0.4, 0.6]]'], {}), '([[1.25, 0.5, 0.25], [-0.25, 0.9, 0.5], [-0.75, -0.4, 0.6]])\n', (19067, 19127), True, 'import numpy as np\n'), ((19149, 19211), 'numpy.array', 'np.array', (['[[0.0, 1.0, 0.0], [-1.0, 0.0, 0.0], [0.0, 0.0, 1.0]]'], {}), '([[0.0, 1.0, 0.0], [-1.0, 0.0, 0.0], [0.0, 0.0, 1.0]])\n', (19157, 19211), True, 'import numpy as np\n'), ((21405, 21437), 'numpy.zeros', 'np.zeros', (['T2D.NFC'], {'dtype': 'complex'}), '(T2D.NFC, dtype=complex)\n', (21413, 21437), True, 'import numpy as np\n'), ((22357, 22404), 'numpy.tensordot', 'np.tensordot', (['T2D.Lproj[-1]', 'utest'], {'axes': '(0, 0)'}), '(T2D.Lproj[-1], utest, axes=(0, 0))\n', (22369, 22404), True, 'import numpy as np\n'), ((22834, 22854), 'numpy.zeros', 'np.zeros', (['T2D.Npower'], {}), '(T2D.Npower)\n', (22842, 22854), True, 'import numpy as np\n'), ((22909, 22947), 'numpy.tensordot', 'np.tensordot', (['T2D.Lproj[-1]', 'v'], {'axes': '(1)'}), '(T2D.Lproj[-1], v, axes=1)\n', (22921, 22947), True, 'import numpy as np\n'), ((23022, 23042), 'numpy.zeros', 'np.zeros', (['T2D.Npower'], {}), '(T2D.Npower)\n', (23030, 23042), True, 'import numpy as np\n'), ((23170, 23210), 'numpy.tensordot', 'np.tensordot', (['T2D.Lproj[-1]', 'vxy'], {'axes': '(1)'}), '(T2D.Lproj[-1], vxy, axes=1)\n', (23182, 23210), True, 'import numpy as np\n'), ((24668, 24677), 'numpy.eye', 'np.eye', (['(2)'], {}), '(2)\n', (24674, 24677), True, 'import numpy as np\n'), ((24878, 24889), 'numpy.zeros', 'np.zeros', (['(2)'], {}), '(2)\n', (24886, 24889), True, 'import numpy as np\n'), ((24891, 24911), 'numpy.array', 'np.array', (['[1.0, 0.0]'], {}), '([1.0, 0.0])\n', (24899, 24911), True, 'import numpy as np\n'), ((24911, 24931), 'numpy.array', 'np.array', (['[0.0, 1.0]'], {}), '([0.0, 1.0])\n', (24919, 24931), True, 'import numpy as np\n'), ((24931, 24951), 'numpy.array', 'np.array', (['[0.0, 0.0]'], {}), '([0.0, 0.0])\n', (24939, 24951), True, 'import numpy as np\n'), ((24969, 24993), 'numpy.array', 'np.array', (['[0.234, -0.85]'], {}), '([0.234, -0.85])\n', (24977, 24993), True, 'import numpy as np\n'), ((25013, 25035), 'numpy.array', 'np.array', (['[1.24, 0.71]'], {}), '([1.24, 0.71])\n', (25021, 25035), True, 'import numpy as np\n'), ((27506, 27517), 'numpy.zeros', 'np.zeros', (['(2)'], {}), '(2)\n', (27514, 27517), True, 'import numpy as np\n'), ((27519, 27539), 'numpy.array', 'np.array', (['[1.0, 0.0]'], {}), '([1.0, 0.0])\n', (27527, 27539), True, 'import numpy as np\n'), ((27539, 27559), 'numpy.array', 'np.array', (['[0.0, 1.0]'], {}), '([0.0, 1.0])\n', (27547, 27559), True, 'import numpy as np\n'), ((27577, 27601), 'numpy.array', 'np.array', (['[0.234, -0.85]'], {}), '([0.234, -0.85])\n', (27585, 27601), True, 'import numpy as np\n'), ((27603, 27625), 'numpy.array', 'np.array', (['[1.24, 0.71]'], {}), '([1.24, 0.71])\n', (27611, 27625), True, 'import numpy as np\n'), ((27995, 28015), 'numpy.dot', 'np.dot', (['value', 'value'], {}), '(value, value)\n', (28001, 28015), True, 'import numpy as np\n'), ((30884, 30949), 'numpy.tensordot', 'np.tensordot', (['T2D.powFC[:T2D.powlrange[l], :]', 'coeff'], {'axes': '(0, 0)'}), '(T2D.powFC[:T2D.powlrange[l], :], coeff, axes=(0, 0))\n', (30896, 30949), True, 'import numpy as np\n'), ((31668, 31679), 'numpy.zeros', 'np.zeros', (['(2)'], {}), '(2)\n', (31676, 31679), True, 'import numpy as np\n'), ((31681, 31701), 'numpy.array', 'np.array', (['[1.0, 0.0]'], {}), '([1.0, 0.0])\n', (31689, 31701), True, 'import numpy as np\n'), ((31701, 31721), 'numpy.array', 'np.array', (['[0.0, 1.0]'], {}), '([0.0, 1.0])\n', (31709, 31721), True, 'import numpy as np\n'), ((31739, 31763), 'numpy.array', 'np.array', (['[0.234, -0.85]'], {}), '([0.234, -0.85])\n', (31747, 31763), True, 'import numpy as np\n'), ((31765, 31787), 'numpy.array', 'np.array', (['[1.24, 0.71]'], {}), '([1.24, 0.71])\n', (31773, 31787), True, 'import numpy as np\n'), ((32482, 32543), 'numpy.tensordot', 'np.tensordot', (['T2D.powFC[:T2D.powlrange[l], :]', 'c'], {'axes': '(0, 0)'}), '(T2D.powFC[:T2D.powlrange[l], :], c, axes=(0, 0))\n', (32494, 32543), True, 'import numpy as np\n'), ((34049, 34070), 'numpy.array', 'np.array', (['[0.25, 0.0]'], {}), '([0.25, 0.0])\n', (34057, 34070), True, 'import numpy as np\n'), ((34071, 34091), 'numpy.array', 'np.array', (['[0.0, 0.1]'], {}), '([0.0, 0.1])\n', (34079, 34091), True, 'import numpy as np\n'), ((34110, 34136), 'numpy.array', 'np.array', (['[0.0234, -0.085]'], {}), '([0.0234, -0.085])\n', (34118, 34136), True, 'import numpy as np\n'), ((34138, 34162), 'numpy.array', 'np.array', (['[0.124, 0.071]'], {}), '([0.124, 0.071])\n', (34146, 34162), True, 'import numpy as np\n'), ((35651, 35672), 'numpy.array', 'np.array', (['[0.25, 0.0]'], {}), '([0.25, 0.0])\n', (35659, 35672), True, 'import numpy as np\n'), ((35673, 35693), 'numpy.array', 'np.array', (['[0.0, 0.1]'], {}), '([0.0, 0.1])\n', (35681, 35693), True, 'import numpy as np\n'), ((35712, 35738), 'numpy.array', 'np.array', (['[0.0234, -0.085]'], {}), '([0.0234, -0.085])\n', (35720, 35738), True, 'import numpy as np\n'), ((35740, 35764), 'numpy.array', 'np.array', (['[0.124, 0.071]'], {}), '([0.124, 0.071])\n', (35748, 35764), True, 'import numpy as np\n'), ((36192, 36213), 'numpy.array', 'np.array', (['[0.25, 0.0]'], {}), '([0.25, 0.0])\n', (36200, 36213), True, 'import numpy as np\n'), ((36214, 36234), 'numpy.array', 'np.array', (['[0.0, 0.1]'], {}), '([0.0, 0.1])\n', (36222, 36234), True, 'import numpy as np\n'), ((36253, 36279), 'numpy.array', 'np.array', (['[0.0234, -0.085]'], {}), '([0.0234, -0.085])\n', (36261, 36279), True, 'import numpy as np\n'), ((36281, 36305), 'numpy.array', 'np.array', (['[0.124, 0.071]'], {}), '([0.124, 0.071])\n', (36289, 36305), True, 'import numpy as np\n'), ((36499, 36521), 'numpy.array', 'np.array', (['[0.025, 0.0]'], {}), '([0.025, 0.0])\n', (36507, 36521), True, 'import numpy as np\n'), ((36522, 36543), 'numpy.array', 'np.array', (['[0.0, 0.01]'], {}), '([0.0, 0.01])\n', (36530, 36543), True, 'import numpy as np\n'), ((36562, 36588), 'numpy.array', 'np.array', (['[0.0234, -0.085]'], {}), '([0.0234, -0.085])\n', (36570, 36588), True, 'import numpy as np\n'), ((36590, 36615), 'numpy.array', 'np.array', (['[0.0124, 0.071]'], {}), '([0.0124, 0.071])\n', (36598, 36615), True, 'import numpy as np\n'), ((37206, 37215), 'numpy.eye', 'np.eye', (['(2)'], {}), '(2)\n', (37212, 37215), True, 'import numpy as np\n'), ((37270, 37307), 'numpy.array', 'np.array', (['[[1.25, 0.5], [-0.25, 0.9]]'], {}), '([[1.25, 0.5], [-0.25, 0.9]])\n', (37278, 37307), True, 'import numpy as np\n'), ((37329, 37364), 'numpy.array', 'np.array', (['[[0.0, 1.0], [-1.0, 0.0]]'], {}), '([[0.0, 1.0], [-1.0, 0.0]])\n', (37337, 37364), True, 'import numpy as np\n'), ((38063, 38072), 'numpy.eye', 'np.eye', (['(2)'], {}), '(2)\n', (38069, 38072), True, 'import numpy as np\n'), ((38127, 38164), 'numpy.array', 'np.array', (['[[1.25, 0.5], [-0.25, 0.9]]'], {}), '([[1.25, 0.5], [-0.25, 0.9]])\n', (38135, 38164), True, 'import numpy as np\n'), ((38186, 38221), 'numpy.array', 'np.array', (['[[0.0, 1.0], [-1.0, 0.0]]'], {}), '([[0.0, 1.0], [-1.0, 0.0]])\n', (38194, 38221), True, 'import numpy as np\n'), ((539, 548), 'numpy.eye', 'np.eye', (['(2)'], {}), '(2)\n', (545, 548), True, 'import numpy as np\n'), ((611, 620), 'numpy.eye', 'np.eye', (['(2)'], {}), '(2)\n', (617, 620), True, 'import numpy as np\n'), ((682, 691), 'numpy.eye', 'np.eye', (['(2)'], {}), '(2)\n', (688, 691), True, 'import numpy as np\n'), ((693, 719), 'numpy.array', 'np.array', (['[-1.0, 0.0, 0.0]'], {}), '([-1.0, 0.0, 0.0])\n', (701, 719), True, 'import numpy as np\n'), ((742, 751), 'numpy.eye', 'np.eye', (['(2)'], {}), '(2)\n', (748, 751), True, 'import numpy as np\n'), ((815, 824), 'numpy.eye', 'np.eye', (['(2)'], {}), '(2)\n', (821, 824), True, 'import numpy as np\n'), ((887, 896), 'numpy.eye', 'np.eye', (['(2)'], {}), '(2)\n', (893, 896), True, 'import numpy as np\n'), ((898, 923), 'numpy.array', 'np.array', (['[1.0, 0.0, 0.0]'], {}), '([1.0, 0.0, 0.0])\n', (906, 923), True, 'import numpy as np\n'), ((961, 986), 'numpy.array', 'np.array', (['[0.0, 0.0, 1.0]'], {}), '([0.0, 0.0, 1.0])\n', (969, 986), True, 'import numpy as np\n'), ((1024, 1050), 'numpy.array', 'np.array', (['[0.0, 0.0, -1.0]'], {}), '([0.0, 0.0, -1.0])\n', (1032, 1050), True, 'import numpy as np\n'), ((1869, 1895), 'scipy.special.sph_harm', 'sph_harm', (['m', 'l', 'theta', 'phi'], {}), '(m, l, theta, phi)\n', (1877, 1895), False, 'from scipy.special import sph_harm\n'), ((1921, 1950), 'numpy.dot', 'np.dot', (['T3D.Ylmpow[lm]', 'utest'], {}), '(T3D.Ylmpow[lm], utest)\n', (1927, 1950), True, 'import numpy as np\n'), ((2279, 2306), 'numpy.dot', 'np.dot', (['T3D.powYlm[p]', 'Ylm0'], {}), '(T3D.powYlm[p], Ylm0)\n', (2285, 2306), True, 'import numpy as np\n'), ((3680, 3698), 'numpy.allclose', 'np.allclose', (['v', 'Pv'], {}), '(v, Pv)\n', (3691, 3698), True, 'import numpy as np\n'), ((3728, 3749), 'numpy.allclose', 'np.allclose', (['v', 'Pvxyz'], {}), '(v, Pvxyz)\n', (3739, 3749), True, 'import numpy as np\n'), ((3814, 3851), 'numpy.tensordot', 'np.tensordot', (['T3D.Lproj[l]', 'v'], {'axes': '(1)'}), '(T3D.Lproj[l], v, axes=1)\n', (3826, 3851), True, 'import numpy as np\n'), ((3876, 3916), 'numpy.tensordot', 'np.tensordot', (['T3D.Lproj[l]', 'vxyz'], {'axes': '(1)'}), '(T3D.Lproj[l], vxyz, axes=1)\n', (3888, 3916), True, 'import numpy as np\n'), ((5537, 5549), 'numpy.dot', 'np.dot', (['u', 'u'], {}), '(u, u)\n', (5543, 5549), True, 'import numpy as np\n'), ((5883, 5909), 'numpy.allclose', 'np.allclose', (['value', 'valsum'], {}), '(value, valsum)\n', (5894, 5909), True, 'import numpy as np\n'), ((6045, 6072), 'numpy.allclose', 'np.allclose', (['value', 'funcsum'], {}), '(value, funcsum)\n', (6056, 6072), True, 'import numpy as np\n'), ((6211, 6238), 'numpy.allclose', 'np.allclose', (['value', 'dictsum'], {}), '(value, dictsum)\n', (6222, 6238), True, 'import numpy as np\n'), ((7657, 7678), 'onsager.PowerExpansion.factorial', 'PE.factorial', (['n', '(True)'], {}), '(n, True)\n', (7669, 7678), True, 'import onsager.PowerExpansion as PE\n'), ((8190, 8202), 'numpy.dot', 'np.dot', (['u', 'u'], {}), '(u, u)\n', (8196, 8202), True, 'import numpy as np\n'), ((8713, 8739), 'numpy.allclose', 'np.allclose', (['value', 'valsum'], {}), '(value, valsum)\n', (8724, 8739), True, 'import numpy as np\n'), ((8875, 8902), 'numpy.allclose', 'np.allclose', (['value', 'funcsum'], {}), '(value, funcsum)\n', (8886, 8902), True, 'import numpy as np\n'), ((9041, 9068), 'numpy.allclose', 'np.allclose', (['value', 'dictsum'], {}), '(value, dictsum)\n', (9052, 9068), True, 'import numpy as np\n'), ((9210, 9238), 'numpy.allclose', 'np.allclose', (['value2', 'valsum2'], {}), '(value2, valsum2)\n', (9221, 9238), True, 'import numpy as np\n'), ((9376, 9405), 'numpy.allclose', 'np.allclose', (['value2', 'funcsum2'], {}), '(value2, funcsum2)\n', (9387, 9405), True, 'import numpy as np\n'), ((9546, 9575), 'numpy.allclose', 'np.allclose', (['value2', 'dictsum2'], {}), '(value2, dictsum2)\n', (9557, 9575), True, 'import numpy as np\n'), ((11327, 11365), 'numpy.allclose', 'np.allclose', (['coeff[lmax:T3D.Npower]', '(0)'], {}), '(coeff[lmax:T3D.Npower], 0)\n', (11338, 11365), True, 'import numpy as np\n'), ((11396, 11428), 'numpy.allclose', 'np.allclose', (['coeff[lmin:lmax]', '(0)'], {}), '(coeff[lmin:lmax], 0)\n', (11407, 11428), True, 'import numpy as np\n'), ((11620, 11652), 'numpy.allclose', 'np.allclose', (['Ylmcoeff[0:lmin]', '(0)'], {}), '(Ylmcoeff[0:lmin], 0)\n', (11631, 11652), True, 'import numpy as np\n'), ((11683, 11718), 'numpy.allclose', 'np.allclose', (['Ylmcoeff[lmin:lmax]', '(0)'], {}), '(Ylmcoeff[lmin:lmax], 0)\n', (11694, 11718), True, 'import numpy as np\n'), ((11748, 11787), 'numpy.allclose', 'np.allclose', (['Ylmcoeff[lmax:T3D.NYlm]', '(0)'], {}), '(Ylmcoeff[lmax:T3D.NYlm], 0)\n', (11759, 11787), True, 'import numpy as np\n'), ((12343, 12355), 'numpy.dot', 'np.dot', (['u', 'u'], {}), '(u, u)\n', (12349, 12355), True, 'import numpy as np\n'), ((13171, 13203), 'numpy.allclose', 'np.allclose', (['Ylmcoeff[0:lmin]', '(0)'], {}), '(Ylmcoeff[0:lmin], 0)\n', (13182, 13203), True, 'import numpy as np\n'), ((13234, 13269), 'numpy.allclose', 'np.allclose', (['Ylmcoeff[lmin:lmax]', '(0)'], {}), '(Ylmcoeff[lmin:lmax], 0)\n', (13245, 13269), True, 'import numpy as np\n'), ((13299, 13338), 'numpy.allclose', 'np.allclose', (['Ylmcoeff[lmax:T3D.NYlm]', '(0)'], {}), '(Ylmcoeff[lmax:T3D.NYlm], 0)\n', (13310, 13338), True, 'import numpy as np\n'), ((13791, 13800), 'numpy.eye', 'np.eye', (['(2)'], {}), '(2)\n', (13797, 13800), True, 'import numpy as np\n'), ((13802, 13827), 'numpy.array', 'np.array', (['[1.0, 0.0, 0.0]'], {}), '([1.0, 0.0, 0.0])\n', (13810, 13827), True, 'import numpy as np\n'), ((13850, 13859), 'numpy.eye', 'np.eye', (['(2)'], {}), '(2)\n', (13856, 13859), True, 'import numpy as np\n'), ((13861, 13887), 'numpy.array', 'np.array', (['[-1.0, 0.0, 0.0]'], {}), '([-1.0, 0.0, 0.0])\n', (13869, 13887), True, 'import numpy as np\n'), ((13910, 13919), 'numpy.eye', 'np.eye', (['(2)'], {}), '(2)\n', (13916, 13919), True, 'import numpy as np\n'), ((13921, 13946), 'numpy.array', 'np.array', (['[0.0, 1.0, 0.0]'], {}), '([0.0, 1.0, 0.0])\n', (13929, 13946), True, 'import numpy as np\n'), ((13969, 13978), 'numpy.eye', 'np.eye', (['(2)'], {}), '(2)\n', (13975, 13978), True, 'import numpy as np\n'), ((13980, 14006), 'numpy.array', 'np.array', (['[0.0, -1.0, 0.0]'], {}), '([0.0, -1.0, 0.0])\n', (13988, 14006), True, 'import numpy as np\n'), ((14029, 14038), 'numpy.eye', 'np.eye', (['(2)'], {}), '(2)\n', (14035, 14038), True, 'import numpy as np\n'), ((14040, 14065), 'numpy.array', 'np.array', (['[0.0, 0.0, 1.0]'], {}), '([0.0, 0.0, 1.0])\n', (14048, 14065), True, 'import numpy as np\n'), ((14088, 14097), 'numpy.eye', 'np.eye', (['(2)'], {}), '(2)\n', (14094, 14097), True, 'import numpy as np\n'), ((14099, 14125), 'numpy.array', 'np.array', (['[0.0, 0.0, -1.0]'], {}), '([0.0, 0.0, -1.0])\n', (14107, 14125), True, 'import numpy as np\n'), ((14813, 14825), 'numpy.dot', 'np.dot', (['u', 'u'], {}), '(u, u)\n', (14819, 14825), True, 'import numpy as np\n'), ((14914, 14935), 'numpy.dot', 'np.dot', (['cval', 'cinvval'], {}), '(cval, cinvval)\n', (14920, 14935), True, 'import numpy as np\n'), ((14938, 14947), 'numpy.eye', 'np.eye', (['(2)'], {}), '(2)\n', (14944, 14947), True, 'import numpy as np\n'), ((15910, 15971), 'numpy.array', 'np.array', (['[[1.0, 6.0, 5.0], [5.0, 2.0, 4.0], [5.0, 4.0, 3.0]]'], {}), '([[1.0, 6.0, 5.0], [5.0, 2.0, 4.0], [5.0, 4.0, 3.0]])\n', (15918, 15971), True, 'import numpy as np\n'), ((15964, 15998), 'numpy.array', 'np.array', (['[2 / 3.0, 1 / 3, -1 / 2]'], {}), '([2 / 3.0, 1 / 3, -1 / 2])\n', (15972, 15998), True, 'import numpy as np\n'), ((17784, 17818), 'numpy.array', 'np.array', (['[2 / 3.0, 1 / 3, -1 / 2]'], {}), '([2 / 3.0, 1 / 3, -1 / 2])\n', (17792, 17818), True, 'import numpy as np\n'), ((18077, 18086), 'numpy.eye', 'np.eye', (['(3)'], {}), '(3)\n', (18083, 18086), True, 'import numpy as np\n'), ((18094, 18103), 'numpy.eye', 'np.eye', (['(3)'], {}), '(3)\n', (18100, 18103), True, 'import numpy as np\n'), ((18505, 18530), 'numpy.array', 'np.array', (['[1.2, 0.0, 0.0]'], {}), '([1.2, 0.0, 0.0])\n', (18513, 18530), True, 'import numpy as np\n'), ((18552, 18577), 'numpy.array', 'np.array', (['[0.0, 1.2, 0.0]'], {}), '([0.0, 1.2, 0.0])\n', (18560, 18577), True, 'import numpy as np\n'), ((18599, 18624), 'numpy.array', 'np.array', (['[0.0, 0.0, 1.2]'], {}), '([0.0, 0.0, 1.2])\n', (18607, 18624), True, 'import numpy as np\n'), ((18646, 18674), 'numpy.array', 'np.array', (['[0.234, -0.5, 0.5]'], {}), '([0.234, -0.5, 0.5])\n', (18654, 18674), True, 'import numpy as np\n'), ((18698, 18727), 'numpy.array', 'np.array', (['[-0.24, 0.41, -1.3]'], {}), '([-0.24, 0.41, -1.3])\n', (18706, 18727), True, 'import numpy as np\n'), ((19011, 19020), 'numpy.eye', 'np.eye', (['(3)'], {}), '(3)\n', (19017, 19020), True, 'import numpy as np\n'), ((19028, 19037), 'numpy.eye', 'np.eye', (['(3)'], {}), '(3)\n', (19034, 19037), True, 'import numpy as np\n'), ((19439, 19464), 'numpy.array', 'np.array', (['[1.2, 0.0, 0.0]'], {}), '([1.2, 0.0, 0.0])\n', (19447, 19464), True, 'import numpy as np\n'), ((19486, 19511), 'numpy.array', 'np.array', (['[0.0, 1.2, 0.0]'], {}), '([0.0, 1.2, 0.0])\n', (19494, 19511), True, 'import numpy as np\n'), ((19533, 19558), 'numpy.array', 'np.array', (['[0.0, 0.0, 1.2]'], {}), '([0.0, 0.0, 1.2])\n', (19541, 19558), True, 'import numpy as np\n'), ((19580, 19608), 'numpy.array', 'np.array', (['[0.234, -0.5, 0.5]'], {}), '([0.234, -0.5, 0.5])\n', (19588, 19608), True, 'import numpy as np\n'), ((19632, 19661), 'numpy.array', 'np.array', (['[-0.24, 0.41, -1.3]'], {}), '([-0.24, 0.41, -1.3])\n', (19640, 19661), True, 'import numpy as np\n'), ((20442, 20451), 'numpy.eye', 'np.eye', (['(2)'], {}), '(2)\n', (20448, 20451), True, 'import numpy as np\n'), ((20510, 20519), 'numpy.eye', 'np.eye', (['(2)'], {}), '(2)\n', (20516, 20519), True, 'import numpy as np\n'), ((20591, 20612), 'numpy.array', 'np.array', (['[-1.0, 0.0]'], {}), '([-1.0, 0.0])\n', (20599, 20612), True, 'import numpy as np\n'), ((20636, 20645), 'numpy.eye', 'np.eye', (['(2)'], {}), '(2)\n', (20642, 20645), True, 'import numpy as np\n'), ((20705, 20714), 'numpy.eye', 'np.eye', (['(2)'], {}), '(2)\n', (20711, 20714), True, 'import numpy as np\n'), ((20787, 20807), 'numpy.array', 'np.array', (['[1.0, 0.0]'], {}), '([1.0, 0.0])\n', (20795, 20807), True, 'import numpy as np\n'), ((21218, 21259), 'numpy.linspace', 'np.linspace', (['(0)', '(2)'], {'num': '(16)', 'endpoint': '(False)'}), '(0, 2, num=16, endpoint=False)\n', (21229, 21259), True, 'import numpy as np\n'), ((21627, 21657), 'numpy.dot', 'np.dot', (['T2D.FCpow[lind]', 'utest'], {}), '(T2D.FCpow[lind], utest)\n', (21633, 21657), True, 'import numpy as np\n'), ((21961, 21986), 'numpy.dot', 'np.dot', (['T2D.powFC[p]', 'FC0'], {}), '(T2D.powFC[p], FC0)\n', (21967, 21986), True, 'import numpy as np\n'), ((23239, 23257), 'numpy.allclose', 'np.allclose', (['v', 'Pv'], {}), '(v, Pv)\n', (23250, 23257), True, 'import numpy as np\n'), ((23287, 23307), 'numpy.allclose', 'np.allclose', (['v', 'Pvxy'], {}), '(v, Pvxy)\n', (23298, 23307), True, 'import numpy as np\n'), ((23372, 23409), 'numpy.tensordot', 'np.tensordot', (['T2D.Lproj[l]', 'v'], {'axes': '(1)'}), '(T2D.Lproj[l], v, axes=1)\n', (23384, 23409), True, 'import numpy as np\n'), ((23433, 23472), 'numpy.tensordot', 'np.tensordot', (['T2D.Lproj[l]', 'vxy'], {'axes': '(1)'}), '(T2D.Lproj[l], vxy, axes=1)\n', (23445, 23472), True, 'import numpy as np\n'), ((25066, 25078), 'numpy.dot', 'np.dot', (['u', 'u'], {}), '(u, u)\n', (25072, 25078), True, 'import numpy as np\n'), ((25412, 25438), 'numpy.allclose', 'np.allclose', (['value', 'valsum'], {}), '(value, valsum)\n', (25423, 25438), True, 'import numpy as np\n'), ((25574, 25601), 'numpy.allclose', 'np.allclose', (['value', 'funcsum'], {}), '(value, funcsum)\n', (25585, 25601), True, 'import numpy as np\n'), ((25740, 25767), 'numpy.allclose', 'np.allclose', (['value', 'dictsum'], {}), '(value, dictsum)\n', (25751, 25767), True, 'import numpy as np\n'), ((27186, 27207), 'onsager.PowerExpansion.factorial', 'PE.factorial', (['n', '(True)'], {}), '(n, True)\n', (27198, 27207), True, 'import onsager.PowerExpansion as PE\n'), ((27656, 27668), 'numpy.dot', 'np.dot', (['u', 'u'], {}), '(u, u)\n', (27662, 27668), True, 'import numpy as np\n'), ((28179, 28205), 'numpy.allclose', 'np.allclose', (['value', 'valsum'], {}), '(value, valsum)\n', (28190, 28205), True, 'import numpy as np\n'), ((28341, 28368), 'numpy.allclose', 'np.allclose', (['value', 'funcsum'], {}), '(value, funcsum)\n', (28352, 28368), True, 'import numpy as np\n'), ((28507, 28534), 'numpy.allclose', 'np.allclose', (['value', 'dictsum'], {}), '(value, dictsum)\n', (28518, 28534), True, 'import numpy as np\n'), ((28676, 28704), 'numpy.allclose', 'np.allclose', (['value2', 'valsum2'], {}), '(value2, valsum2)\n', (28687, 28704), True, 'import numpy as np\n'), ((28842, 28871), 'numpy.allclose', 'np.allclose', (['value2', 'funcsum2'], {}), '(value2, funcsum2)\n', (28853, 28871), True, 'import numpy as np\n'), ((29012, 29041), 'numpy.allclose', 'np.allclose', (['value2', 'dictsum2'], {}), '(value2, dictsum2)\n', (29023, 29041), True, 'import numpy as np\n'), ((30648, 30677), 'numpy.allclose', 'np.allclose', (['coeff[0:lmin]', '(0)'], {}), '(coeff[0:lmin], 0)\n', (30659, 30677), True, 'import numpy as np\n'), ((30707, 30745), 'numpy.allclose', 'np.allclose', (['coeff[lmax:T2D.Npower]', '(0)'], {}), '(coeff[lmax:T2D.Npower], 0)\n', (30718, 30745), True, 'import numpy as np\n'), ((30776, 30808), 'numpy.allclose', 'np.allclose', (['coeff[lmin:lmax]', '(0)'], {}), '(coeff[lmin:lmax], 0)\n', (30787, 30808), True, 'import numpy as np\n'), ((31818, 31830), 'numpy.dot', 'np.dot', (['u', 'u'], {}), '(u, u)\n', (31824, 31830), True, 'import numpy as np\n'), ((33372, 33381), 'numpy.eye', 'np.eye', (['(2)'], {}), '(2)\n', (33378, 33381), True, 'import numpy as np\n'), ((33383, 33403), 'numpy.array', 'np.array', (['[1.0, 0.0]'], {}), '([1.0, 0.0])\n', (33391, 33403), True, 'import numpy as np\n'), ((33427, 33436), 'numpy.eye', 'np.eye', (['(2)'], {}), '(2)\n', (33433, 33436), True, 'import numpy as np\n'), ((33438, 33459), 'numpy.array', 'np.array', (['[-1.0, 0.0]'], {}), '([-1.0, 0.0])\n', (33446, 33459), True, 'import numpy as np\n'), ((33483, 33492), 'numpy.eye', 'np.eye', (['(2)'], {}), '(2)\n', (33489, 33492), True, 'import numpy as np\n'), ((33494, 33514), 'numpy.array', 'np.array', (['[0.0, 1.0]'], {}), '([0.0, 1.0])\n', (33502, 33514), True, 'import numpy as np\n'), ((33538, 33547), 'numpy.eye', 'np.eye', (['(2)'], {}), '(2)\n', (33544, 33547), True, 'import numpy as np\n'), ((33549, 33570), 'numpy.array', 'np.array', (['[0.0, -1.0]'], {}), '([0.0, -1.0])\n', (33557, 33570), True, 'import numpy as np\n'), ((34193, 34205), 'numpy.dot', 'np.dot', (['u', 'u'], {}), '(u, u)\n', (34199, 34205), True, 'import numpy as np\n'), ((34294, 34315), 'numpy.dot', 'np.dot', (['cval', 'cinvval'], {}), '(cval, cinvval)\n', (34300, 34315), True, 'import numpy as np\n'), ((34318, 34327), 'numpy.eye', 'np.eye', (['(2)'], {}), '(2)\n', (34324, 34327), True, 'import numpy as np\n'), ((35290, 35326), 'numpy.array', 'np.array', (['[[1.0, -2.0], [-2.0, 2.0]]'], {}), '([[1.0, -2.0], [-2.0, 2.0]])\n', (35298, 35326), True, 'import numpy as np\n'), ((35324, 35350), 'numpy.array', 'np.array', (['[2 / 3.0, 1 / 3]'], {}), '([2 / 3.0, 1 / 3])\n', (35332, 35350), True, 'import numpy as np\n'), ((36937, 36963), 'numpy.array', 'np.array', (['[2 / 3.0, 1 / 3]'], {}), '([2 / 3.0, 1 / 3])\n', (36945, 36963), True, 'import numpy as np\n'), ((37222, 37231), 'numpy.eye', 'np.eye', (['(2)'], {}), '(2)\n', (37228, 37231), True, 'import numpy as np\n'), ((37239, 37248), 'numpy.eye', 'np.eye', (['(2)'], {}), '(2)\n', (37245, 37248), True, 'import numpy as np\n'), ((37597, 37617), 'numpy.array', 'np.array', (['[1.2, 0.0]'], {}), '([1.2, 0.0])\n', (37605, 37617), True, 'import numpy as np\n'), ((37640, 37660), 'numpy.array', 'np.array', (['[0.0, 1.2]'], {}), '([0.0, 1.2])\n', (37648, 37660), True, 'import numpy as np\n'), ((37683, 37703), 'numpy.array', 'np.array', (['[0.0, 0.0]'], {}), '([0.0, 0.0])\n', (37691, 37703), True, 'import numpy as np\n'), ((37725, 37748), 'numpy.array', 'np.array', (['[0.234, -0.5]'], {}), '([0.234, -0.5])\n', (37733, 37748), True, 'import numpy as np\n'), ((37772, 37795), 'numpy.array', 'np.array', (['[-0.24, 0.41]'], {}), '([-0.24, 0.41])\n', (37780, 37795), True, 'import numpy as np\n'), ((38079, 38088), 'numpy.eye', 'np.eye', (['(2)'], {}), '(2)\n', (38085, 38088), True, 'import numpy as np\n'), ((38096, 38105), 'numpy.eye', 'np.eye', (['(2)'], {}), '(2)\n', (38102, 38105), True, 'import numpy as np\n'), ((38454, 38474), 'numpy.array', 'np.array', (['[1.2, 0.0]'], {}), '([1.2, 0.0])\n', (38462, 38474), True, 'import numpy as np\n'), ((38497, 38517), 'numpy.array', 'np.array', (['[0.0, 1.2]'], {}), '([0.0, 1.2])\n', (38505, 38517), True, 'import numpy as np\n'), ((38540, 38560), 'numpy.array', 'np.array', (['[0.0, 0.0]'], {}), '([0.0, 0.0])\n', (38548, 38560), True, 'import numpy as np\n'), ((38582, 38605), 'numpy.array', 'np.array', (['[0.234, -0.5]'], {}), '([0.234, -0.5])\n', (38590, 38605), True, 'import numpy as np\n'), ((38629, 38652), 'numpy.array', 'np.array', (['[-0.24, 0.41]'], {}), '([-0.24, 0.41])\n', (38637, 38652), True, 'import numpy as np\n'), ((946, 955), 'numpy.eye', 'np.eye', (['(2)'], {}), '(2)\n', (952, 955), True, 'import numpy as np\n'), ((1009, 1018), 'numpy.eye', 'np.eye', (['(2)'], {}), '(2)\n', (1015, 1018), True, 'import numpy as np\n'), ((4555, 4576), 'onsager.PowerExpansion.factorial', 'PE.factorial', (['n', '(True)'], {}), '(n, True)\n', (4567, 4576), True, 'import onsager.PowerExpansion as PE\n'), ((6904, 6923), 'numpy.dot', 'np.dot', (['prod', 'value'], {}), '(prod, value)\n', (6910, 6923), True, 'import numpy as np\n'), ((7047, 7066), 'numpy.dot', 'np.dot', (['value', 'prod'], {}), '(value, prod)\n', (7053, 7066), True, 'import numpy as np\n'), ((17773, 17782), 'numpy.eye', 'np.eye', (['(1)'], {}), '(1)\n', (17779, 17782), True, 'import numpy as np\n'), ((18312, 18339), 'numpy.dot', 'np.dot', (['newbasis[0][1]', 'rot'], {}), '(newbasis[0][1], rot)\n', (18318, 18339), True, 'import numpy as np\n'), ((19246, 19273), 'numpy.dot', 'np.dot', (['newbasis[0][1]', 'rot'], {}), '(newbasis[0][1], rot)\n', (19252, 19273), True, 'import numpy as np\n'), ((20580, 20589), 'numpy.eye', 'np.eye', (['(2)'], {}), '(2)\n', (20586, 20589), True, 'import numpy as np\n'), ((20776, 20785), 'numpy.eye', 'np.eye', (['(2)'], {}), '(2)\n', (20782, 20785), True, 'import numpy as np\n'), ((24109, 24130), 'onsager.PowerExpansion.factorial', 'PE.factorial', (['n', '(True)'], {}), '(n, True)\n', (24121, 24130), True, 'import onsager.PowerExpansion as PE\n'), ((26433, 26452), 'numpy.dot', 'np.dot', (['prod', 'value'], {}), '(prod, value)\n', (26439, 26452), True, 'import numpy as np\n'), ((26576, 26595), 'numpy.dot', 'np.dot', (['value', 'prod'], {}), '(value, prod)\n', (26582, 26595), True, 'import numpy as np\n'), ((36926, 36935), 'numpy.eye', 'np.eye', (['(1)'], {}), '(1)\n', (36932, 36935), True, 'import numpy as np\n'), ((37404, 37431), 'numpy.dot', 'np.dot', (['newbasis[0][1]', 'rot'], {}), '(newbasis[0][1], rot)\n', (37410, 37431), True, 'import numpy as np\n'), ((38261, 38288), 'numpy.dot', 'np.dot', (['newbasis[0][1]', 'rot'], {}), '(newbasis[0][1], rot)\n', (38267, 38288), True, 'import numpy as np\n'), ((637, 650), 'numpy.sqrt', 'np.sqrt', (['(0.75)'], {}), '(0.75)\n', (644, 650), True, 'import numpy as np\n'), ((842, 855), 'numpy.sqrt', 'np.sqrt', (['(0.75)'], {}), '(0.75)\n', (849, 855), True, 'import numpy as np\n'), ((1590, 1601), 'numpy.cos', 'np.cos', (['phi'], {}), '(phi)\n', (1596, 1601), True, 'import numpy as np\n'), ((3987, 4005), 'numpy.allclose', 'np.allclose', (['v', 'Pv'], {}), '(v, Pv)\n', (3998, 4005), True, 'import numpy as np\n'), ((4043, 4064), 'numpy.allclose', 'np.allclose', (['v', 'Pvxyz'], {}), '(v, Pvxyz)\n', (4054, 4064), True, 'import numpy as np\n'), ((4124, 4142), 'numpy.allclose', 'np.allclose', (['Pv', '(0)'], {}), '(Pv, 0)\n', (4135, 4142), True, 'import numpy as np\n'), ((4180, 4201), 'numpy.allclose', 'np.allclose', (['Pvxyz', '(0)'], {}), '(Pvxyz, 0)\n', (4191, 4201), True, 'import numpy as np\n'), ((6774, 6783), 'numpy.eye', 'np.eye', (['(2)'], {}), '(2)\n', (6780, 6783), True, 'import numpy as np\n'), ((20536, 20549), 'numpy.sqrt', 'np.sqrt', (['(0.75)'], {}), '(0.75)\n', (20543, 20549), True, 'import numpy as np\n'), ((20732, 20745), 'numpy.sqrt', 'np.sqrt', (['(0.75)'], {}), '(0.75)\n', (20739, 20745), True, 'import numpy as np\n'), ((21310, 21323), 'numpy.cos', 'np.cos', (['theta'], {}), '(theta)\n', (21316, 21323), True, 'import numpy as np\n'), ((21325, 21338), 'numpy.sin', 'np.sin', (['theta'], {}), '(theta)\n', (21331, 21338), True, 'import numpy as np\n'), ((23543, 23561), 'numpy.allclose', 'np.allclose', (['v', 'Pv'], {}), '(v, Pv)\n', (23554, 23561), True, 'import numpy as np\n'), ((23599, 23619), 'numpy.allclose', 'np.allclose', (['v', 'Pvxy'], {}), '(v, Pvxy)\n', (23610, 23619), True, 'import numpy as np\n'), ((23679, 23697), 'numpy.allclose', 'np.allclose', (['Pv', '(0)'], {}), '(Pv, 0)\n', (23690, 23697), True, 'import numpy as np\n'), ((23735, 23755), 'numpy.allclose', 'np.allclose', (['Pvxy', '(0)'], {}), '(Pvxy, 0)\n', (23746, 23755), True, 'import numpy as np\n'), ((26303, 26312), 'numpy.eye', 'np.eye', (['(2)'], {}), '(2)\n', (26309, 26312), True, 'import numpy as np\n'), ((31282, 31301), 'numpy.abs', 'np.abs', (['FCcoeff[lp]'], {}), '(FCcoeff[lp])\n', (31288, 31301), True, 'import numpy as np\n'), ((31302, 31321), 'numpy.abs', 'np.abs', (['FCcoeff[lm]'], {}), '(FCcoeff[lm])\n', (31308, 31321), True, 'import numpy as np\n'), ((32876, 32895), 'numpy.abs', 'np.abs', (['FCcoeff[lp]'], {}), '(FCcoeff[lp])\n', (32882, 32895), True, 'import numpy as np\n'), ((32896, 32915), 'numpy.abs', 'np.abs', (['FCcoeff[lm]'], {}), '(FCcoeff[lm])\n', (32902, 32915), True, 'import numpy as np\n'), ((566, 579), 'numpy.sqrt', 'np.sqrt', (['(0.75)'], {}), '(0.75)\n', (573, 579), True, 'import numpy as np\n'), ((770, 783), 'numpy.sqrt', 'np.sqrt', (['(0.75)'], {}), '(0.75)\n', (777, 783), True, 'import numpy as np\n'), ((1436, 1447), 'numpy.sin', 'np.sin', (['phi'], {}), '(phi)\n', (1442, 1447), True, 'import numpy as np\n'), ((1450, 1463), 'numpy.cos', 'np.cos', (['theta'], {}), '(theta)\n', (1456, 1463), True, 'import numpy as np\n'), ((1513, 1524), 'numpy.sin', 'np.sin', (['phi'], {}), '(phi)\n', (1519, 1524), True, 'import numpy as np\n'), ((1527, 1540), 'numpy.sin', 'np.sin', (['theta'], {}), '(theta)\n', (1533, 1540), True, 'import numpy as np\n'), ((5682, 5696), 'numpy.dot', 'np.dot', (['u', 'vec'], {}), '(u, vec)\n', (5688, 5696), True, 'import numpy as np\n'), ((8335, 8349), 'numpy.dot', 'np.dot', (['u', 'vec'], {}), '(u, vec)\n', (8341, 8349), True, 'import numpy as np\n'), ((20469, 20482), 'numpy.sqrt', 'np.sqrt', (['(0.75)'], {}), '(0.75)\n', (20476, 20482), True, 'import numpy as np\n'), ((20664, 20677), 'numpy.sqrt', 'np.sqrt', (['(0.75)'], {}), '(0.75)\n', (20671, 20677), True, 'import numpy as np\n'), ((25211, 25225), 'numpy.dot', 'np.dot', (['u', 'vec'], {}), '(u, vec)\n', (25217, 25225), True, 'import numpy as np\n'), ((27801, 27815), 'numpy.dot', 'np.dot', (['u', 'vec'], {}), '(u, vec)\n', (27807, 27815), True, 'import numpy as np\n'), ((31210, 31231), 'numpy.abs', 'np.abs', (['FCcoeff[lind]'], {}), '(FCcoeff[lind])\n', (31216, 31231), True, 'import numpy as np\n'), ((32804, 32825), 'numpy.abs', 'np.abs', (['FCcoeff[lind]'], {}), '(FCcoeff[lind])\n', (32810, 32825), True, 'import numpy as np\n')]
# -*- coding: utf-8 -*- """ author: <NAME> """ import numpy as np import imageio class MNISTImageReader(): """ brief: read image data from .idx3-ubyte file as numpy array use cases: # case 1 with MNISTImageReader('t10k-images.idx3-ubyte') as reader: # the reader was designed as an iterable object. for index, image in reader: ... # case 2 reader = MNISTImageReader('t10k-images.idx3-ubyte') reader.open() # read 10 images from source file. # there will be two returned value, the first one is an index list corresponding to returned images, # the second one is a multi-dimensional numpy array which hold the image data. index, images = reader.read(10) reader.close() # case 3 with MNISTImageReader('t10k-images.idx3-ubyte') as reader: index, images = reader.read(10) # Of course, you can access images using read() within 'with' context. """ _expected_magic = 2051 _current_index = 0 def __init__(self, path): if not path.endswith('.idx3-ubyte'): raise NameError("File must be a '.idx3-ubyte' extension") self.__path = path self.__file_object = None def __enter__(self): self.__file_object = open(self.__path, 'rb') magic_number = int.from_bytes(self.__file_object.read(4), byteorder='big') if magic_number != self._expected_magic: raise TypeError("The File is not a properly formatted .idx3-ubyte file!") self.__num_of_images = int.from_bytes(self.__file_object.read(4), byteorder='big') print(f'Total {self.__num_of_images} images ...') self.__num_of_rows = int.from_bytes(self.__file_object.read(4), byteorder='big') self.__num_of_cols = int.from_bytes(self.__file_object.read(4), byteorder='big') return self def __exit__(self, type, val, tb): self.__file_object.close() def __iter__(self): return self def __next__(self): raw_image_data = self.__file_object.read(self.__num_of_rows * self.__num_of_cols) if self.__file_object is None or raw_image_data == b'': raise StopIteration else: self._current_index += 1 return self._current_index, np.frombuffer(raw_image_data, dtype=np.uint8).reshape((self.__num_of_rows, self.__num_of_cols)) def read(self, num): feasible_num = num if self.__num_of_images - self._current_index >= num else self.__num_of_images - self._current_index raw_image_data = self.__file_object.read(self.__num_of_rows * self.__num_of_cols * feasible_num) index = range(self._current_index + 1, self._current_index + feasible_num + 1) return index, np.frombuffer(raw_image_data, dtype=np.uint8).reshape((feasible_num, self.__num_of_rows, self.__num_of_cols)) def open(self): self.__file_object = open(self.__path, 'rb') magic_number = int.from_bytes(self.__file_object.read(4), byteorder='big') if magic_number != self._expected_magic: raise TypeError("The File is not a properly formatted .idx3-ubyte file!") self.__num_of_images = int.from_bytes(self.__file_object.read(4), byteorder='big') print(f'Total {self.__num_of_images} images ...') self.__num_of_rows = int.from_bytes(self.__file_object.read(4), byteorder='big') self.__num_of_cols = int.from_bytes(self.__file_object.read(4), byteorder='big') def close(self): self.__file_object.close() class MNISTLabelReader(): """ brief: read label data from .idx1-ubyte file as integer (0, 1, ..., 9) use cases: # case 1 with MNISTLabelReader('t10k-labels.idx1-ubyte') as reader: # the reader was designed as an iterable object. for index, label in reader: ... # case 2 reader = MNISTLabelReader('t10k-labels.idx1-ubyte') reader.open() # read 10 labels from source file. # there will be two returned value, the first one is an index list corresponding to returned labels, # the second one is a numpy array which hold the label data. index, labels = reader.read(10) reader.close() # case 3 with MNISTImageReader('t10k-images.idx3-ubyte') as reader: index, labels = reader.read(10) # Of course, you can access labels using read() within 'with' context. """ _expected_magic = 2049 _current_index = 0 def __init__(self, path): if not path.endswith('.idx1-ubyte'): raise NameError("File must be a '.idx1-ubyte' extension") self.__file_path = path self.__file_object = None def __enter__(self): self.__file_object = open(self.__file_path, 'rb') magic_number = int.from_bytes(self.__file_object.read(4), byteorder='big') if magic_number != self._expected_magic: raise TypeError("The File is not a properly formatted .idx1-ubyte file!") self.__num_of_labels = int.from_bytes(self.__file_object.read(4), byteorder='big') print(f'Total {self.__num_of_labels} labels ...') return self def __exit__(self, *args, **kwargs): self.__file_object.close() def __iter__(self): return self def __next__(self): raw_label = self.__file_object.read(1) if self.__file_object is None or raw_label == b'': raise StopIteration else: self._current_index += 1 return self._current_index, int.from_bytes(raw_label, byteorder='big') def read(self, num): feasible_num = num if self.__num_of_labels - self._current_index >= num else self.__num_of_labels - self._current_index raw_label_data = self.__file_object.read(feasible_num) index = range(self._current_index + 1, self._current_index + feasible_num + 1) return index, np.frombuffer(raw_label_data, dtype=np.uint8).reshape((feasible_num,)) def open(self): self.__file_object = open(self.__file_path, 'rb') magic_number = int.from_bytes(self.__file_object.read(4), byteorder='big') if magic_number != self._expected_magic: raise TypeError("The File is not a properly formatted .idx1-ubyte file!") self.__num_of_labels = int.from_bytes(self.__file_object.read(4), byteorder='big') print(f'Total {self.__num_of_labels} labels ...') def close(self): self.__file_object.close()
[ "numpy.frombuffer" ]
[((2822, 2867), 'numpy.frombuffer', 'np.frombuffer', (['raw_image_data'], {'dtype': 'np.uint8'}), '(raw_image_data, dtype=np.uint8)\n', (2835, 2867), True, 'import numpy as np\n'), ((6043, 6088), 'numpy.frombuffer', 'np.frombuffer', (['raw_label_data'], {'dtype': 'np.uint8'}), '(raw_label_data, dtype=np.uint8)\n', (6056, 6088), True, 'import numpy as np\n'), ((2358, 2403), 'numpy.frombuffer', 'np.frombuffer', (['raw_image_data'], {'dtype': 'np.uint8'}), '(raw_image_data, dtype=np.uint8)\n', (2371, 2403), True, 'import numpy as np\n')]
""" MIT License Copyright (c) 2019 Chodera lab // Memorial Sloan Kettering Cancer Center, Weill Cornell Medical College, Nicea Research, and Authors Authors: <NAME> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ from sklearn import metrics import tensorflow as tf import gin import lime import time import pandas as pd import numpy as np import os N_EPOCH = 30 df = pd.read_csv('data/Lipophilicity.csv') df = df[~df['smiles'].str.contains('B')] df = df[~df['smiles'].str.contains('\%')] df = df[~df['smiles'].str.contains('\.')] df = df[~df['smiles'].str.contains('Se')] df = df[~df['smiles'].str.contains('Si')] df = df[~df['smiles'].str.contains('S@@')] df = df[~df['smiles'].str.contains('6')] df = df[~df['smiles'].str.contains('7')] df = df[~df['smiles'].str.contains('8')] df = df[~df['smiles'].str.contains('9')] df = df[~df['smiles'].str.contains('\+')] df = df[~df['smiles'].str.contains('\-')] x_array = df[['smiles']].values.flatten() y_array = df[['exp']].values.flatten() y_array = (y_array - np.mean(y_array) / np.std(y_array)) n_samples = y_array.shape[0] ds_all = gin.i_o.from_smiles.to_mols_with_attributes(x_array, y_array) ds_all = ds_all.shuffle(n_samples) ds_all = gin.probabilistic.gn.GraphNet.batch(ds_all, 256).cache( str(os.getcwd()) + '/temp') n_batched_samples_total = gin.probabilistic.gn.GraphNet.get_number_batches( ds_all) n_batched_samples_total = int(n_batched_samples_total) n_global_te = int(0.2 * n_batched_samples_total) ds_global_tr = ds_all.skip(n_global_te) ds_global_te = ds_all.take(n_global_te) config_space = { 'D_E': [32, 64, 128], 'D_V': [32, 64, 128], 'D_U': [32, 64, 128], 'phi_e_0': [32, 64, 128], 'phi_e_a_0': ['elu', 'relu', 'leaky_relu', 'tanh', 'sigmoid'], 'phi_e_1': [32, 64, 128], 'phi_e_a_1': ['elu', 'relu', 'leaky_relu', 'tanh', 'sigmoid'], 'phi_v_0': [32, 64, 128], 'phi_v_a_0': ['elu', 'relu', 'leaky_relu', 'tanh', 'sigmoid'], 'phi_v_1': [32, 64, 128], 'phi_v_a_1': ['elu', 'relu', 'leaky_relu', 'tanh', 'sigmoid'], 'phi_u_0': [32, 64, 128], 'phi_u_a_0': ['elu', 'relu', 'leaky_relu', 'tanh', 'sigmoid'], 'phi_u_1': [32, 64, 128], 'phi_u_a_1': ['elu', 'relu', 'leaky_relu', 'tanh', 'sigmoid'], 'f_r_0': [32, 64, 128], 'f_r_a_0': ['elu', 'relu', 'leaky_relu', 'tanh', 'sigmoid'], 'f_r_1': [32, 64, 128], 'f_r_a_1': ['elu', 'relu', 'leaky_relu', 'tanh', 'sigmoid'], 'gru_unit': [64, 128, 256, 512], 'learning_rate': [1e-5, 1e-4, 1e-3, 1e-2] } def init(point): global gn global optimizer class f_r(tf.keras.Model): def __init__( self, config=( point['f_r_0'], point['f_r_a_0'], point['f_r_1'], point['f_r_a_1'] )): super(f_r, self).__init__() self.d0 = tf.keras.layers.Dense(config[0], activation=config[1]) self.d1 = tf.keras.layers.Dense(config[2], activation=config[3]) @tf.function def call(self, h_e, h_v, h_u, h_e_history, h_v_history, h_u_history, atom_in_mol, bond_in_mol): x = self.d0(h_u) x = self.d1(x) return x class f_e(tf.keras.Model): """ Featurization of edges. Here we split the $\sigma$ and $\pi$ component of bonds into two channels, and featurize them seperately. """ def __init__( self, d_sigma_units=point['d_sigma_units'], d_pi_units=point['d_pi_units'], D_E=point['D_E']): super(f_e, self).__init__() self.D_E = D_E # sigma self.d_sigma_0 = tf.Variable( tf.zeros( shape=(1, d_sigma_units), dtype=tf.float32)) self.d_sigma_1 = tf.keras.layers.Dense( int(self.D_E // 2)) # pi self.d_pi_0 = tf.keras.layers.Dense( d_pi_units) self.d_pi_1 = tf.keras.layers.Dense( int(self.D_E // 2)) @tf.function def call(self, x): # determine whether there is $\pi$ component in the bond has_pi = tf.greater( x, tf.constant(1, dtype=tf.float32)) # calculate the sigma component of the bond x_sigma = tf.tile( self.d_sigma_1(self.d_sigma_0), [tf.shape(x, tf.int64)[0], 1]) # calculate the pi component of the bond x_pi = tf.where( has_pi, # if has pi: self.d_pi_1( self.d_pi_0( tf.math.subtract( x, tf.constant(1, dtype=tf.float32)))), # else: tf.zeros( shape=(self.D_E // 2, ), dtype=tf.float32)) x = tf.concat( [ x_sigma, x_pi ], axis=1) return x class f_v(tf.keras.Model): def __init__(self, units=point['D_V']): super(f_v, self).__init__() self.d = tf.keras.layers.Dense(units) @tf.function def call(self, x): x = tf.one_hot(x, 8) x.set_shape([None, 8]) return self.d(x) class phi_u(tf.keras.Model): def __init__( self, config=( point['phi_u_0'], point['phi_u_a_0'], point['phi_u_1'], point['phi_u_a_1'] ), gru_units=point['D_U']): super(phi_u, self).__init__() self.d = lime.nets.for_gn.ConcatenateThenFullyConnect(config) self.gru = tf.keras.layers.GRU( units=gru_units, stateful=True) @tf.function def call(self, h_u, h_u_0, h_e_bar, h_v_bar): x = self.d(h_u, h_u_0, h_e_bar, h_v_bar) if tf.equal( h_u, h_u_0): self.gru.reset_states() x = self.gru( tf.expand_dims( x, 1)) return x class phi_v(tf.keras.Model): def __init__( self, config=( point['phi_v_0'], point['phi_v_a_0'], point['phi_v_1'], point['phi_v_a_1'] ), gru_units=point['D_V']): super(phi_v, self).__init__() self.d = lime.nets.for_gn.ConcatenateThenFullyConnect(config) self.gru = tf.keras.layers.GRU( units=gru_units, stateful=True) @tf.function def call(self, h_v, h_v_0, h_e_bar_i, h_u_i): x = self.d(h_v, h_v_0, h_e_bar_i, h_u_i) if tf.equal( h_v, h_v_0): self.gru.reset_states() x = self.gru( tf.expand_dims( x, 1)) return x class phi_e(tf.keras.Model): def __init__( self, config=( point['phi_e_0'], point['phi_e_a_0'], point['phi_e_1'], point['phi_e_a_1'] ), gru_units=point['D_E']): super(phi_e, self).__init__() self.d = lime.nets.for_gn.ConcatenateThenFullyConnect(config) self.gru = tf.keras.layers.GRU( units=gru_units, stateful=True) @tf.function def call(self, h_e, h_e_0, h_left, h_right, h_u_i): x = self.d(h_e, h_e_0, h_left, h_right, h_u_i) if tf.equal( h_e, h_e_0): self.gru.reset_states() x = self.gru( tf.expand_dims( x, 1)) return x gn = gin.probabilistic.gn.GraphNet( f_e=f_e(), f_v=f_v(), f_u=(lambda atoms, adjacency_map, batched_attr_in_mol: \ tf.tile( tf.zeros((1, point['D_U'])), [ tf.math.count_nonzero(batched_attr_in_mol), 1 ] )), phi_e=phi_e(), phi_v=phi_v(), phi_u=phi_u(), f_r=f_r(), repeat=5) optimizer = tf.keras.optimizers.Adam(point['learning_rate']) def obj_fn(point): point = dict(zip(config_space.keys(), point)) n_te = int(0.2 * 0.8 * n_batched_samples_total) ds = ds_global_tr.shuffle(int(0.8 * n_batched_samples_total)) r2_train = [] r2_test = [] mse_train = [] mse_test = [] for idx in range(5): init(point) y_true_train = tf.constant([-1], dtype=tf.float32) y_pred_train = tf.constant([-1], dtype=tf.float32) y_true_test = tf.constant([-1], dtype=tf.float32) y_pred_test = tf.constant([-1], dtype=tf.float32) ds_tr = ds.take(idx * n_te).concatenate( ds.skip((idx + 1) * n_te).take((4 - idx) * n_te)) ds_te = ds.skip(idx * n_te).take(n_te) for dummy_idx in range(N_EPOCH): for atoms, adjacency_map, atom_in_mol, bond_in_mol, y, y_mask \ in ds_tr: with tf.GradientTape() as tape: y_hat = gn( atoms, adjacency_map, atom_in_mol=atom_in_mol, bond_in_mol=bond_in_mol, batched_attr_in_mol=y_mask) y = tf.boolean_mask( y, y_mask) loss = tf.losses.mean_squared_error(y, y_hat) variables = gn.variables grad = tape.gradient(loss, variables) optimizer.apply_gradients( zip(grad, variables)) gn.switch(True) for atoms, adjacency_map, atom_in_mol, bond_in_mol, y, y_mask \ in ds_te: y_hat = gn( atoms, adjacency_map, atom_in_mol=atom_in_mol, bond_in_mol=bond_in_mol, batched_attr_in_mol=y_mask) y = tf.boolean_mask( y, y_mask) y_true_test = tf.concat( [ y_true_test, tf.reshape(y, [-1]) ], axis=0) y_pred_test = tf.concat( [ y_pred_test, tf.reshape(y_hat, [-1]) ], axis=0) for atoms, adjacency_map, atom_in_mol, bond_in_mol, y, y_mask \ in ds_tr: y_hat = gn( atoms, adjacency_map, atom_in_mol=atom_in_mol, bond_in_mol=bond_in_mol, batched_attr_in_mol=y_mask) y = tf.boolean_mask( y, y_mask) y_true_train = tf.concat( [ y_true_train, tf.reshape(y, [-1]) ], axis=0) y_pred_train = tf.concat( [ y_pred_train, tf.reshape(y_hat, [-1]) ], axis=0) y_true_train = y_true_train[1:] y_pred_train = y_pred_train[1:] y_true_test = y_true_test[1:] y_pred_test = y_pred_test[1:] r2_train.append(metrics.r2_score(y_true_train, y_pred_train)) r2_test.append(metrics.r2_score(y_true_test, y_pred_test)) mse_train.append( tf.losses.mean_squared_error( y_true_train, y_pred_train).numpy()) mse_test.append( tf.losses.mean_squared_error( y_true_test, y_pred_test).numpy()) y_true_global_test = tf.constant([-1], dtype=tf.float32) y_pred_global_test = tf.constant([-1], dtype=tf.float32) init(point) time0 = time.time() for dummy_idx in range(N_EPOCH): for atoms, adjacency_map, atom_in_mol, bond_in_mol, y, y_mask \ in ds_global_tr: with tf.GradientTape() as tape: y_hat = gn.call( atoms, adjacency_map, atom_in_mol=atom_in_mol, bond_in_mol=bond_in_mol, batched_attr_in_mol=y_mask) y = tf.boolean_mask( y, y_mask) loss = tf.losses.mean_squared_error(y, y_hat) variables = gn.variables grad = tape.gradient(loss, variables) optimizer.apply_gradients( zip(grad, variables)) time1 = time.time() gn.switch(True) for atoms, adjacency_map, atom_in_mol, bond_in_mol, y, y_mask \ in ds_global_te: y_hat = gn( atoms, adjacency_map, atom_in_mol=atom_in_mol, bond_in_mol=bond_in_mol, batched_attr_in_mol=y_mask) y = tf.boolean_mask( y, y_mask) y_true_global_test = tf.concat( [ y_true_global_test, tf.reshape(y, [-1]) ], axis=0) y_pred_global_test = tf.concat( [ y_pred_global_test, tf.reshape(y_hat, [-1]) ], axis=0) y_true_global_test = y_true_global_test[1:] y_pred_global_test = y_pred_global_test[1:] mse_global_test = tf.losses.mean_squared_error(y_true_global_test, y_pred_global_test) r2_global_test = metrics.r2_score(y_true_global_test, y_pred_global_test) print(point, flush=True) print('training time %s ' % (time1 - time0), flush=True) print('mse_train %s +- %s' % (np.mean(mse_train), np.std(mse_train)), flush=True) print('r2_train %s +- %s' % (np.mean(r2_train), np.std(r2_train)), flush=True) print('mse_test %s +- %s' % (np.mean(mse_train), np.std(mse_train)), flush=True) print('r2_test %s +- %s' % (np.mean(r2_test), np.std(r2_test)), flush=True) print('mse_global_test %s' % mse_global_test.numpy(), flush=True) print('r2_global_test %s ' % r2_global_test, flush=True) return mse_test lime.optimize.dummy.optimize(obj_fn, config_space.values(), 1000)
[ "tensorflow.keras.layers.Dense", "pandas.read_csv", "sklearn.metrics.r2_score", "tensorflow.reshape", "gin.probabilistic.gn.GraphNet.batch", "numpy.mean", "lime.nets.for_gn.ConcatenateThenFullyConnect", "tensorflow.one_hot", "numpy.std", "tensorflow.concat", "tensorflow.keras.optimizers.Adam", "tensorflow.equal", "tensorflow.losses.mean_squared_error", "gin.i_o.from_smiles.to_mols_with_attributes", "tensorflow.keras.layers.GRU", "tensorflow.constant", "tensorflow.math.count_nonzero", "gin.probabilistic.gn.GraphNet.get_number_batches", "tensorflow.expand_dims", "os.getcwd", "time.time", "tensorflow.shape", "tensorflow.zeros", "tensorflow.boolean_mask", "tensorflow.GradientTape" ]
[((1353, 1390), 'pandas.read_csv', 'pd.read_csv', (['"""data/Lipophilicity.csv"""'], {}), "('data/Lipophilicity.csv')\n", (1364, 1390), True, 'import pandas as pd\n'), ((2069, 2130), 'gin.i_o.from_smiles.to_mols_with_attributes', 'gin.i_o.from_smiles.to_mols_with_attributes', (['x_array', 'y_array'], {}), '(x_array, y_array)\n', (2112, 2130), False, 'import gin\n'), ((2291, 2347), 'gin.probabilistic.gn.GraphNet.get_number_batches', 'gin.probabilistic.gn.GraphNet.get_number_batches', (['ds_all'], {}), '(ds_all)\n', (2339, 2347), False, 'import gin\n'), ((9715, 9763), 'tensorflow.keras.optimizers.Adam', 'tf.keras.optimizers.Adam', (["point['learning_rate']"], {}), "(point['learning_rate'])\n", (9739, 9763), True, 'import tensorflow as tf\n'), ((13333, 13368), 'tensorflow.constant', 'tf.constant', (['[-1]'], {'dtype': 'tf.float32'}), '([-1], dtype=tf.float32)\n', (13344, 13368), True, 'import tensorflow as tf\n'), ((13394, 13429), 'tensorflow.constant', 'tf.constant', (['[-1]'], {'dtype': 'tf.float32'}), '([-1], dtype=tf.float32)\n', (13405, 13429), True, 'import tensorflow as tf\n'), ((13460, 13471), 'time.time', 'time.time', ([], {}), '()\n', (13469, 13471), False, 'import time\n'), ((14218, 14229), 'time.time', 'time.time', ([], {}), '()\n', (14227, 14229), False, 'import time\n'), ((15039, 15107), 'tensorflow.losses.mean_squared_error', 'tf.losses.mean_squared_error', (['y_true_global_test', 'y_pred_global_test'], {}), '(y_true_global_test, y_pred_global_test)\n', (15067, 15107), True, 'import tensorflow as tf\n'), ((15137, 15193), 'sklearn.metrics.r2_score', 'metrics.r2_score', (['y_true_global_test', 'y_pred_global_test'], {}), '(y_true_global_test, y_pred_global_test)\n', (15153, 15193), False, 'from sklearn import metrics\n'), ((1994, 2010), 'numpy.mean', 'np.mean', (['y_array'], {}), '(y_array)\n', (2001, 2010), True, 'import numpy as np\n'), ((2013, 2028), 'numpy.std', 'np.std', (['y_array'], {}), '(y_array)\n', (2019, 2028), True, 'import numpy as np\n'), ((2176, 2224), 'gin.probabilistic.gn.GraphNet.batch', 'gin.probabilistic.gn.GraphNet.batch', (['ds_all', '(256)'], {}), '(ds_all, 256)\n', (2211, 2224), False, 'import gin\n'), ((10095, 10130), 'tensorflow.constant', 'tf.constant', (['[-1]'], {'dtype': 'tf.float32'}), '([-1], dtype=tf.float32)\n', (10106, 10130), True, 'import tensorflow as tf\n'), ((10154, 10189), 'tensorflow.constant', 'tf.constant', (['[-1]'], {'dtype': 'tf.float32'}), '([-1], dtype=tf.float32)\n', (10165, 10189), True, 'import tensorflow as tf\n'), ((10212, 10247), 'tensorflow.constant', 'tf.constant', (['[-1]'], {'dtype': 'tf.float32'}), '([-1], dtype=tf.float32)\n', (10223, 10247), True, 'import tensorflow as tf\n'), ((10270, 10305), 'tensorflow.constant', 'tf.constant', (['[-1]'], {'dtype': 'tf.float32'}), '([-1], dtype=tf.float32)\n', (10281, 10305), True, 'import tensorflow as tf\n'), ((14539, 14565), 'tensorflow.boolean_mask', 'tf.boolean_mask', (['y', 'y_mask'], {}), '(y, y_mask)\n', (14554, 14565), True, 'import tensorflow as tf\n'), ((2240, 2251), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (2249, 2251), False, 'import os\n'), ((3875, 3929), 'tensorflow.keras.layers.Dense', 'tf.keras.layers.Dense', (['config[0]'], {'activation': 'config[1]'}), '(config[0], activation=config[1])\n', (3896, 3929), True, 'import tensorflow as tf\n'), ((3952, 4006), 'tensorflow.keras.layers.Dense', 'tf.keras.layers.Dense', (['config[2]'], {'activation': 'config[3]'}), '(config[2], activation=config[3])\n', (3973, 4006), True, 'import tensorflow as tf\n'), ((5002, 5035), 'tensorflow.keras.layers.Dense', 'tf.keras.layers.Dense', (['d_pi_units'], {}), '(d_pi_units)\n', (5023, 5035), True, 'import tensorflow as tf\n'), ((6030, 6064), 'tensorflow.concat', 'tf.concat', (['[x_sigma, x_pi]'], {'axis': '(1)'}), '([x_sigma, x_pi], axis=1)\n', (6039, 6064), True, 'import tensorflow as tf\n'), ((6320, 6348), 'tensorflow.keras.layers.Dense', 'tf.keras.layers.Dense', (['units'], {}), '(units)\n', (6341, 6348), True, 'import tensorflow as tf\n'), ((6414, 6430), 'tensorflow.one_hot', 'tf.one_hot', (['x', '(8)'], {}), '(x, 8)\n', (6424, 6430), True, 'import tensorflow as tf\n'), ((6876, 6928), 'lime.nets.for_gn.ConcatenateThenFullyConnect', 'lime.nets.for_gn.ConcatenateThenFullyConnect', (['config'], {}), '(config)\n', (6920, 6928), False, 'import lime\n'), ((6952, 7003), 'tensorflow.keras.layers.GRU', 'tf.keras.layers.GRU', ([], {'units': 'gru_units', 'stateful': '(True)'}), '(units=gru_units, stateful=True)\n', (6971, 7003), True, 'import tensorflow as tf\n'), ((7181, 7201), 'tensorflow.equal', 'tf.equal', (['h_u', 'h_u_0'], {}), '(h_u, h_u_0)\n', (7189, 7201), True, 'import tensorflow as tf\n'), ((7785, 7837), 'lime.nets.for_gn.ConcatenateThenFullyConnect', 'lime.nets.for_gn.ConcatenateThenFullyConnect', (['config'], {}), '(config)\n', (7829, 7837), False, 'import lime\n'), ((7861, 7912), 'tensorflow.keras.layers.GRU', 'tf.keras.layers.GRU', ([], {'units': 'gru_units', 'stateful': '(True)'}), '(units=gru_units, stateful=True)\n', (7880, 7912), True, 'import tensorflow as tf\n'), ((8090, 8110), 'tensorflow.equal', 'tf.equal', (['h_v', 'h_v_0'], {}), '(h_v, h_v_0)\n', (8098, 8110), True, 'import tensorflow as tf\n'), ((8695, 8747), 'lime.nets.for_gn.ConcatenateThenFullyConnect', 'lime.nets.for_gn.ConcatenateThenFullyConnect', (['config'], {}), '(config)\n', (8739, 8747), False, 'import lime\n'), ((8771, 8822), 'tensorflow.keras.layers.GRU', 'tf.keras.layers.GRU', ([], {'units': 'gru_units', 'stateful': '(True)'}), '(units=gru_units, stateful=True)\n', (8790, 8822), True, 'import tensorflow as tf\n'), ((9012, 9032), 'tensorflow.equal', 'tf.equal', (['h_e', 'h_e_0'], {}), '(h_e, h_e_0)\n', (9020, 9032), True, 'import tensorflow as tf\n'), ((11602, 11628), 'tensorflow.boolean_mask', 'tf.boolean_mask', (['y', 'y_mask'], {}), '(y, y_mask)\n', (11617, 11628), True, 'import tensorflow as tf\n'), ((12327, 12353), 'tensorflow.boolean_mask', 'tf.boolean_mask', (['y', 'y_mask'], {}), '(y, y_mask)\n', (12342, 12353), True, 'import tensorflow as tf\n'), ((12921, 12965), 'sklearn.metrics.r2_score', 'metrics.r2_score', (['y_true_train', 'y_pred_train'], {}), '(y_true_train, y_pred_train)\n', (12937, 12965), False, 'from sklearn import metrics\n'), ((12990, 13032), 'sklearn.metrics.r2_score', 'metrics.r2_score', (['y_true_test', 'y_pred_test'], {}), '(y_true_test, y_pred_test)\n', (13006, 13032), False, 'from sklearn import metrics\n'), ((4775, 4827), 'tensorflow.zeros', 'tf.zeros', ([], {'shape': '(1, d_sigma_units)', 'dtype': 'tf.float32'}), '(shape=(1, d_sigma_units), dtype=tf.float32)\n', (4783, 4827), True, 'import tensorflow as tf\n'), ((5324, 5356), 'tensorflow.constant', 'tf.constant', (['(1)'], {'dtype': 'tf.float32'}), '(1, dtype=tf.float32)\n', (5335, 5356), True, 'import tensorflow as tf\n'), ((5919, 5969), 'tensorflow.zeros', 'tf.zeros', ([], {'shape': '(self.D_E // 2,)', 'dtype': 'tf.float32'}), '(shape=(self.D_E // 2,), dtype=tf.float32)\n', (5927, 5969), True, 'import tensorflow as tf\n'), ((7319, 7339), 'tensorflow.expand_dims', 'tf.expand_dims', (['x', '(1)'], {}), '(x, 1)\n', (7333, 7339), True, 'import tensorflow as tf\n'), ((8228, 8248), 'tensorflow.expand_dims', 'tf.expand_dims', (['x', '(1)'], {}), '(x, 1)\n', (8242, 8248), True, 'import tensorflow as tf\n'), ((9150, 9170), 'tensorflow.expand_dims', 'tf.expand_dims', (['x', '(1)'], {}), '(x, 1)\n', (9164, 9170), True, 'import tensorflow as tf\n'), ((13628, 13645), 'tensorflow.GradientTape', 'tf.GradientTape', ([], {}), '()\n', (13643, 13645), True, 'import tensorflow as tf\n'), ((13909, 13935), 'tensorflow.boolean_mask', 'tf.boolean_mask', (['y', 'y_mask'], {}), '(y, y_mask)\n', (13924, 13935), True, 'import tensorflow as tf\n'), ((14001, 14039), 'tensorflow.losses.mean_squared_error', 'tf.losses.mean_squared_error', (['y', 'y_hat'], {}), '(y, y_hat)\n', (14029, 14039), True, 'import tensorflow as tf\n'), ((14698, 14717), 'tensorflow.reshape', 'tf.reshape', (['y', '[-1]'], {}), '(y, [-1])\n', (14708, 14717), True, 'import tensorflow as tf\n'), ((14860, 14883), 'tensorflow.reshape', 'tf.reshape', (['y_hat', '[-1]'], {}), '(y_hat, [-1])\n', (14870, 14883), True, 'import tensorflow as tf\n'), ((15327, 15345), 'numpy.mean', 'np.mean', (['mse_train'], {}), '(mse_train)\n', (15334, 15345), True, 'import numpy as np\n'), ((15347, 15364), 'numpy.std', 'np.std', (['mse_train'], {}), '(mse_train)\n', (15353, 15364), True, 'import numpy as np\n'), ((15420, 15437), 'numpy.mean', 'np.mean', (['r2_train'], {}), '(r2_train)\n', (15427, 15437), True, 'import numpy as np\n'), ((15439, 15455), 'numpy.std', 'np.std', (['r2_train'], {}), '(r2_train)\n', (15445, 15455), True, 'import numpy as np\n'), ((15511, 15529), 'numpy.mean', 'np.mean', (['mse_train'], {}), '(mse_train)\n', (15518, 15529), True, 'import numpy as np\n'), ((15531, 15548), 'numpy.std', 'np.std', (['mse_train'], {}), '(mse_train)\n', (15537, 15548), True, 'import numpy as np\n'), ((15603, 15619), 'numpy.mean', 'np.mean', (['r2_test'], {}), '(r2_test)\n', (15610, 15619), True, 'import numpy as np\n'), ((15621, 15636), 'numpy.std', 'np.std', (['r2_test'], {}), '(r2_test)\n', (15627, 15636), True, 'import numpy as np\n'), ((9418, 9445), 'tensorflow.zeros', 'tf.zeros', (["(1, point['D_U'])"], {}), "((1, point['D_U']))\n", (9426, 9445), True, 'import tensorflow as tf\n'), ((10631, 10648), 'tensorflow.GradientTape', 'tf.GradientTape', ([], {}), '()\n', (10646, 10648), True, 'import tensorflow as tf\n'), ((10935, 10961), 'tensorflow.boolean_mask', 'tf.boolean_mask', (['y', 'y_mask'], {}), '(y, y_mask)\n', (10950, 10961), True, 'import tensorflow as tf\n'), ((11039, 11077), 'tensorflow.losses.mean_squared_error', 'tf.losses.mean_squared_error', (['y', 'y_hat'], {}), '(y, y_hat)\n', (11067, 11077), True, 'import tensorflow as tf\n'), ((11771, 11790), 'tensorflow.reshape', 'tf.reshape', (['y', '[-1]'], {}), '(y, [-1])\n', (11781, 11790), True, 'import tensorflow as tf\n'), ((11943, 11966), 'tensorflow.reshape', 'tf.reshape', (['y_hat', '[-1]'], {}), '(y_hat, [-1])\n', (11953, 11966), True, 'import tensorflow as tf\n'), ((12498, 12517), 'tensorflow.reshape', 'tf.reshape', (['y', '[-1]'], {}), '(y, [-1])\n', (12508, 12517), True, 'import tensorflow as tf\n'), ((12672, 12695), 'tensorflow.reshape', 'tf.reshape', (['y_hat', '[-1]'], {}), '(y_hat, [-1])\n', (12682, 12695), True, 'import tensorflow as tf\n'), ((13072, 13128), 'tensorflow.losses.mean_squared_error', 'tf.losses.mean_squared_error', (['y_true_train', 'y_pred_train'], {}), '(y_true_train, y_pred_train)\n', (13100, 13128), True, 'import tensorflow as tf\n'), ((13208, 13262), 'tensorflow.losses.mean_squared_error', 'tf.losses.mean_squared_error', (['y_true_test', 'y_pred_test'], {}), '(y_true_test, y_pred_test)\n', (13236, 13262), True, 'import tensorflow as tf\n'), ((5511, 5532), 'tensorflow.shape', 'tf.shape', (['x', 'tf.int64'], {}), '(x, tf.int64)\n', (5519, 5532), True, 'import tensorflow as tf\n'), ((9486, 9528), 'tensorflow.math.count_nonzero', 'tf.math.count_nonzero', (['batched_attr_in_mol'], {}), '(batched_attr_in_mol)\n', (9507, 9528), True, 'import tensorflow as tf\n'), ((5841, 5873), 'tensorflow.constant', 'tf.constant', (['(1)'], {'dtype': 'tf.float32'}), '(1, dtype=tf.float32)\n', (5852, 5873), True, 'import tensorflow as tf\n')]
import sys import os.path sys.path.append(os.path.abspath(os.path.join(os.path.dirname(sys.modules[__name__].__file__), ".."))) import matplotlib.pyplot as plt import numpy as np from sklearn.neighbors import KernelDensity from tensorflow.python.keras.datasets import mnist from data.data_handler import ProcessedNNHandler from definitions import DATA_PATH from evaluation.create_plot import save_plot def configure_plt(): plt.rc('font', size=14) plt.rc('axes', titlesize=14) plt.rc('axes', labelsize=14) plt.rc('xtick', labelsize=14) plt.rc('ytick', labelsize=14) plt.rc('legend', fontsize=14) plt.rc('figure', titlesize=14) def plot_mnist_samples(width: int = 6, height: int = 2): (x_train, y_train), (_, _) = mnist.load_data() fig, axs = plt.subplots(height, width, figsize=(width, height)) for i in range(height): for j in range(width): first_image = x_train[j + width * i + 120] first_image = np.array(first_image, dtype='float') pixels = first_image.reshape((28, 28)) axs[i, j].imshow(pixels, cmap='gray') for ax in axs.flat: ax.label_outer() plt.subplots_adjust(wspace=0.2, hspace=0.2) def plot_kernels(): fig, ax = plt.subplots(figsize=(8, 4), subplot_kw={'facecolor': '#F4F4F4', 'axisbelow': True}) ax.grid(color='white', linestyle='-', linewidth=2) for spine in ax.spines.values(): spine.set_color('#BBBBBB') X_src = np.zeros((1, 1)) x_grid = np.linspace(-3, 3, 1000) for kernel in ['gaussian', 'tophat', 'exponential', 'epanechnikov', 'linear', 'cosine']: log_dens = KernelDensity(kernel=kernel).fit(X_src).score_samples(x_grid[:, None]) if kernel is 'epanechnikov': ax.plot(x_grid, np.exp(log_dens), lw=6, alpha=0.8, label=kernel) else: ax.plot(x_grid, np.exp(log_dens), lw=3, alpha=0.5, label=kernel) ax.set_ylim(0, 1.05) ax.set_xlim(-2.9, 2.9) ax.legend() def plot_histogram(path: str): processed_nn: ProcessedNNHandler = ProcessedNNHandler(DATA_PATH + path) samples: np.array = processed_nn.get_all_samples() z_values: np.array = np.zeros(samples.shape[0]) for i, sample in enumerate(samples): z_values[i] = sample[2] z_values = z_values.reshape(-1, 1) slots: int = 50 x_grid = np.linspace(-1.2, 1.2, int(slots * 1.2 * 4.0)) fig, ax = plt.subplots() for bandwidth in [0.05, 0.18, 0.5]: pdf = KernelDensity(kernel='epanechnikov', bandwidth=bandwidth).fit(z_values).score_samples(x_grid[:, None]) ax.plot(x_grid, np.exp(pdf), linewidth=2, alpha=0.6, label='bandwidth=%.2f' % bandwidth) ax.hist(z_values, slots, facecolor='gray', histtype='stepfilled', alpha=0.4, density=True) ax.legend(loc='upper right') ax.set_xlim(-1.2, 1.2) configure_plt() plot_mnist_samples() save_plot('mnist') plt.show()
[ "data.data_handler.ProcessedNNHandler", "matplotlib.pyplot.show", "sklearn.neighbors.KernelDensity", "numpy.zeros", "numpy.array", "tensorflow.python.keras.datasets.mnist.load_data", "matplotlib.pyplot.rc", "numpy.linspace", "matplotlib.pyplot.subplots_adjust", "numpy.exp", "matplotlib.pyplot.subplots", "evaluation.create_plot.save_plot" ]
[((2940, 2958), 'evaluation.create_plot.save_plot', 'save_plot', (['"""mnist"""'], {}), "('mnist')\n", (2949, 2958), False, 'from evaluation.create_plot import save_plot\n'), ((2960, 2970), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (2968, 2970), True, 'import matplotlib.pyplot as plt\n'), ((431, 454), 'matplotlib.pyplot.rc', 'plt.rc', (['"""font"""'], {'size': '(14)'}), "('font', size=14)\n", (437, 454), True, 'import matplotlib.pyplot as plt\n'), ((459, 487), 'matplotlib.pyplot.rc', 'plt.rc', (['"""axes"""'], {'titlesize': '(14)'}), "('axes', titlesize=14)\n", (465, 487), True, 'import matplotlib.pyplot as plt\n'), ((492, 520), 'matplotlib.pyplot.rc', 'plt.rc', (['"""axes"""'], {'labelsize': '(14)'}), "('axes', labelsize=14)\n", (498, 520), True, 'import matplotlib.pyplot as plt\n'), ((525, 554), 'matplotlib.pyplot.rc', 'plt.rc', (['"""xtick"""'], {'labelsize': '(14)'}), "('xtick', labelsize=14)\n", (531, 554), True, 'import matplotlib.pyplot as plt\n'), ((559, 588), 'matplotlib.pyplot.rc', 'plt.rc', (['"""ytick"""'], {'labelsize': '(14)'}), "('ytick', labelsize=14)\n", (565, 588), True, 'import matplotlib.pyplot as plt\n'), ((593, 622), 'matplotlib.pyplot.rc', 'plt.rc', (['"""legend"""'], {'fontsize': '(14)'}), "('legend', fontsize=14)\n", (599, 622), True, 'import matplotlib.pyplot as plt\n'), ((627, 657), 'matplotlib.pyplot.rc', 'plt.rc', (['"""figure"""'], {'titlesize': '(14)'}), "('figure', titlesize=14)\n", (633, 657), True, 'import matplotlib.pyplot as plt\n'), ((750, 767), 'tensorflow.python.keras.datasets.mnist.load_data', 'mnist.load_data', ([], {}), '()\n', (765, 767), False, 'from tensorflow.python.keras.datasets import mnist\n'), ((783, 835), 'matplotlib.pyplot.subplots', 'plt.subplots', (['height', 'width'], {'figsize': '(width, height)'}), '(height, width, figsize=(width, height))\n', (795, 835), True, 'import matplotlib.pyplot as plt\n'), ((1169, 1212), 'matplotlib.pyplot.subplots_adjust', 'plt.subplots_adjust', ([], {'wspace': '(0.2)', 'hspace': '(0.2)'}), '(wspace=0.2, hspace=0.2)\n', (1188, 1212), True, 'import matplotlib.pyplot as plt\n'), ((1249, 1337), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {'figsize': '(8, 4)', 'subplot_kw': "{'facecolor': '#F4F4F4', 'axisbelow': True}"}), "(figsize=(8, 4), subplot_kw={'facecolor': '#F4F4F4',\n 'axisbelow': True})\n", (1261, 1337), True, 'import matplotlib.pyplot as plt\n'), ((1540, 1556), 'numpy.zeros', 'np.zeros', (['(1, 1)'], {}), '((1, 1))\n', (1548, 1556), True, 'import numpy as np\n'), ((1570, 1594), 'numpy.linspace', 'np.linspace', (['(-3)', '(3)', '(1000)'], {}), '(-3, 3, 1000)\n', (1581, 1594), True, 'import numpy as np\n'), ((2124, 2160), 'data.data_handler.ProcessedNNHandler', 'ProcessedNNHandler', (['(DATA_PATH + path)'], {}), '(DATA_PATH + path)\n', (2142, 2160), False, 'from data.data_handler import ProcessedNNHandler\n'), ((2241, 2267), 'numpy.zeros', 'np.zeros', (['samples.shape[0]'], {}), '(samples.shape[0])\n', (2249, 2267), True, 'import numpy as np\n'), ((2475, 2489), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (2487, 2489), True, 'import matplotlib.pyplot as plt\n'), ((976, 1012), 'numpy.array', 'np.array', (['first_image'], {'dtype': '"""float"""'}), "(first_image, dtype='float')\n", (984, 1012), True, 'import numpy as np\n'), ((2671, 2682), 'numpy.exp', 'np.exp', (['pdf'], {}), '(pdf)\n', (2677, 2682), True, 'import numpy as np\n'), ((1844, 1860), 'numpy.exp', 'np.exp', (['log_dens'], {}), '(log_dens)\n', (1850, 1860), True, 'import numpy as np\n'), ((1935, 1951), 'numpy.exp', 'np.exp', (['log_dens'], {}), '(log_dens)\n', (1941, 1951), True, 'import numpy as np\n'), ((1708, 1736), 'sklearn.neighbors.KernelDensity', 'KernelDensity', ([], {'kernel': 'kernel'}), '(kernel=kernel)\n', (1721, 1736), False, 'from sklearn.neighbors import KernelDensity\n'), ((2544, 2601), 'sklearn.neighbors.KernelDensity', 'KernelDensity', ([], {'kernel': '"""epanechnikov"""', 'bandwidth': 'bandwidth'}), "(kernel='epanechnikov', bandwidth=bandwidth)\n", (2557, 2601), False, 'from sklearn.neighbors import KernelDensity\n')]
import numpy as np import pysam import utils import pdb MIN_MAP_QUAL = 10 class Genome(): def __init__(self, fasta_filename, map_filename): self._seq_handle = pysam.FastaFile(fasta_filename) self._map_handles = [pysam.TabixFile(map_filename+'_%d.gz'%r) for r in utils.READ_LENGTHS] def get_sequence(self, transcripts): sequences = [] for transcript in transcripts: # get DNA sequence seq = self._seq_handle.fetch(transcript.chromosome, transcript.start, transcript.stop).upper() # get DNA sequence of transcript # reverse complement, if necessary if transcript.strand=="-": seq = seq[::-1] seq = ''.join(np.array(list(seq))[transcript.mask].tolist()) seq = utils.make_complement(seq) else: seq = ''.join(np.array(list(seq))[transcript.mask].tolist()) # get RNA sequence seq = ''.join(['U' if s=='T' else s for s in seq]) sequences.append(seq) return sequences def get_mappability(self, transcripts): mappabilities = [] for transcript in transcripts: # get mappable positions mappables = [np.zeros(transcript.mask.shape, dtype='bool') for r in utils.READ_LENGTHS] tbx_iters = [handle.fetch(transcript.chromosome, transcript.start, transcript.stop) for handle in self._map_handles] if transcript.strand=='+': offsets = [1,1,1,1] else: offsets = utils.READ_LENGTHS for tbx_iter,mappable,offset in zip(tbx_iters,mappables,offsets): for tbx in tbx_iter: row = tbx.split('\t') start = int(row[1]) - transcript.start + offset - 1 end = int(row[2]) - transcript.start + offset - 1 mappable[start:end] = True if transcript.strand=='+': mappables = np.array(mappables).T.astype('bool') else: mappables = np.array(mappables).T.astype('bool')[::-1] mappabilities.append(mappables[transcript.mask,:]) return mappabilities def close(self): self._seq_handle.close() ig = [handle.close() for handle in self._map_handles] class RiboSeq(): def __init__(self, file_prefix): self._fwd_handles = [pysam.TabixFile(file_prefix+'_fwd.%d.gz'%r) for r in utils.READ_LENGTHS] self._rev_handles = [pysam.TabixFile(file_prefix+'_rev.%d.gz'%r) for r in utils.READ_LENGTHS] def get_counts(self, transcripts): read_counts = [] for transcript in transcripts: rcounts = [np.zeros(transcript.mask.shape, dtype='int') for r in utils.READ_LENGTHS] if transcript.strand=='+': tbx_iters = [handle.fetch(transcript.chromosome, transcript.start, transcript.stop) \ for handle in self._fwd_handles] else: tbx_iters = [handle.fetch(transcript.chromosome, transcript.start, transcript.stop) \ for handle in self._rev_handles] for tbx_iter,counts in zip(tbx_iters,rcounts): for tbx in tbx_iter: row = tbx.split('\t') count = int(row[3]) asite = int(row[1]) - transcript.start counts[asite] = count if transcript.strand=='+': rcounts = np.array(rcounts).T.astype(np.uint64) else: rcounts = np.array(rcounts).T.astype(np.uint64)[::-1] read_counts.append(rcounts[transcript.mask,:]) return read_counts def get_total_counts(self, transcripts): read_counts = self.get_counts(transcripts) total_counts = np.array([counts.sum() for counts in read_counts]) return total_counts def get_exon_total_counts(self, transcripts): exon_counts = [] for transcript in transcripts: rcounts = [np.zeros(transcript.mask.shape, dtype='int') for r in utils.READ_LENGTHS] if transcript.strand=='+': tbx_iters = [handle.fetch(transcript.chromosome, transcript.start, transcript.stop) \ for handle in self._fwd_handles] else: tbx_iters = [handle.fetch(transcript.chromosome, transcript.start, transcript.stop) \ for handle in self._rev_handles] for tbx_iter,counts in zip(tbx_iters,rcounts): for tbx in tbx_iter: row = tbx.split('\t') count = int(row[3]) asite = int(row[1]) - transcript.start counts[asite] = count rcounts = np.array(rcounts).T.astype(np.uint64) exon_counts.append(np.array([rcounts[start:end,:].sum() for start,end in transcript.exons])) return exon_counts def close(self): ig = [handle.close() for handle in self._fwd_handles] ig = [handle.close() for handle in self._rev_handles] class RnaSeq(): def __init__(self, filename): self._handle = pysam.TabixFile(filename+'.gz') self.total = 0 for chrom in self._handle.contigs: self.total += reduce(lambda x,y: x+y, (int(tbx.split('\t')[3]) for tbx in self._handle.fetch(chrom))) def get_total_counts(self, transcripts): total_counts = [] for transcript in transcripts: tbx_iter = self._handle.fetch(transcript.chromosome, transcript.start, transcript.stop) if transcript.strand=='+': mask = transcript.mask else: mask = transcript.mask[::-1] counts = 0 for tbx in tbx_iter: row = tbx.split('\t') site = int(row[1])-transcript.start count = int(row[3]) if mask[site]: counts += 1 total_counts.append(max([1,counts])*1e6/float(transcript.L*self.total)) total_counts = np.array(total_counts) return total_counts def close(self): self._handle.close() class Transcript(): def __init__(self, line, attr): self.id = attr['transcript_id'] self.chromosome = line[0] self.start = int(line[3])-1 self.stop = int(line[4]) # if not specified, transcript is on positive strand if line[6] in ['+','-']: self.strand = line[6] else: self.strand = '+' self.cdstart = None self.cdstop = None self.exons = [] self.has_CDS = False self.proteinid = '' # add attribute fields that are available try: self.type = attr['transcript_type'] except KeyError: pass try: self.type = attr['gene_biotype'] except KeyError: pass try: self.geneid = attr['gene_id'] except KeyError: pass try: self.genename = attr['gene_name'] except KeyError: pass try: self.ref_transcript_id = attr['reference_id'] except KeyError: pass try: self.ref_gene_id = attr['ref_gene_id'] except KeyError: pass try: self.genename = attr['ref_gene_name'] except KeyError: pass def add_exon(self, line): exon = (int(line[3])-1, int(line[4])) self.exons.append(exon) def generate_transcript_model(self): if len(self.exons)>0: # order exons order = np.argsort(np.array([e[0] for e in self.exons])) self.exons = [[self.exons[o][0],self.exons[o][1]] for o in order] # extend transcript boundaries, if needed self.start = min([self.start, self.exons[0][0]]) self.stop = max([self.stop, self.exons[-1][-1]]) # set transcript model self.exons = [(e[0]-self.start, e[1]-self.start) for e in self.exons] self.mask = np.zeros((self.stop-self.start,),dtype='bool') ig = [self.mask.__setslice__(start,stop,True) for (start,stop) in self.exons] if self.strand=='-': self.mask = self.mask[::-1] self.L = self.mask.sum() else: # no exons for transcript; remove raise ValueError def load_gtf(filename): transcripts = dict() handle = open(filename, "r") for line in handle: # remove comments if line.startswith('#'): continue # read data data = line.strip().split("\t") attr = dict([(ln.split()[0],eval(ln.split()[1])) for ln in data[8].split(';')[:-1]]) # identify chromosome of the transcript if data[0].startswith('c'): chrom = data[0] else: chrom = 'chr%s'%data[0] data[0] = chrom transcript_id = attr['transcript_id'] try: # if transcript is in dictionary, only parse exons transcripts[transcript_id] if data[2]=='exon': transcripts[transcript_id].add_exon(data) else: pass except KeyError: if data[2]=='transcript': # initialize new transcript transcripts[transcript_id] = Transcript(data, attr) handle.close() # generate transcript models keys = transcripts.keys() for key in keys: try: transcripts[key].generate_transcript_model() except ValueError: del transcripts[key] return transcripts
[ "pysam.FastaFile", "pysam.TabixFile", "numpy.zeros", "utils.make_complement", "numpy.array" ]
[((175, 206), 'pysam.FastaFile', 'pysam.FastaFile', (['fasta_filename'], {}), '(fasta_filename)\n', (190, 206), False, 'import pysam\n'), ((5431, 5464), 'pysam.TabixFile', 'pysam.TabixFile', (["(filename + '.gz')"], {}), "(filename + '.gz')\n", (5446, 5464), False, 'import pysam\n'), ((6353, 6375), 'numpy.array', 'np.array', (['total_counts'], {}), '(total_counts)\n', (6361, 6375), True, 'import numpy as np\n'), ((236, 280), 'pysam.TabixFile', 'pysam.TabixFile', (["(map_filename + '_%d.gz' % r)"], {}), "(map_filename + '_%d.gz' % r)\n", (251, 280), False, 'import pysam\n'), ((2552, 2599), 'pysam.TabixFile', 'pysam.TabixFile', (["(file_prefix + '_fwd.%d.gz' % r)"], {}), "(file_prefix + '_fwd.%d.gz' % r)\n", (2567, 2599), False, 'import pysam\n'), ((2684, 2731), 'pysam.TabixFile', 'pysam.TabixFile', (["(file_prefix + '_rev.%d.gz' % r)"], {}), "(file_prefix + '_rev.%d.gz' % r)\n", (2699, 2731), False, 'import pysam\n'), ((8419, 8468), 'numpy.zeros', 'np.zeros', (['(self.stop - self.start,)'], {'dtype': '"""bool"""'}), "((self.stop - self.start,), dtype='bool')\n", (8427, 8468), True, 'import numpy as np\n'), ((842, 868), 'utils.make_complement', 'utils.make_complement', (['seq'], {}), '(seq)\n', (863, 868), False, 'import utils\n'), ((1306, 1351), 'numpy.zeros', 'np.zeros', (['transcript.mask.shape'], {'dtype': '"""bool"""'}), "(transcript.mask.shape, dtype='bool')\n", (1314, 1351), True, 'import numpy as np\n'), ((2916, 2960), 'numpy.zeros', 'np.zeros', (['transcript.mask.shape'], {'dtype': '"""int"""'}), "(transcript.mask.shape, dtype='int')\n", (2924, 2960), True, 'import numpy as np\n'), ((4259, 4303), 'numpy.zeros', 'np.zeros', (['transcript.mask.shape'], {'dtype': '"""int"""'}), "(transcript.mask.shape, dtype='int')\n", (4267, 4303), True, 'import numpy as np\n'), ((7984, 8020), 'numpy.array', 'np.array', (['[e[0] for e in self.exons]'], {}), '([e[0] for e in self.exons])\n', (7992, 8020), True, 'import numpy as np\n'), ((5005, 5022), 'numpy.array', 'np.array', (['rcounts'], {}), '(rcounts)\n', (5013, 5022), True, 'import numpy as np\n'), ((2116, 2135), 'numpy.array', 'np.array', (['mappables'], {}), '(mappables)\n', (2124, 2135), True, 'import numpy as np\n'), ((3705, 3722), 'numpy.array', 'np.array', (['rcounts'], {}), '(rcounts)\n', (3713, 3722), True, 'import numpy as np\n'), ((2199, 2218), 'numpy.array', 'np.array', (['mappables'], {}), '(mappables)\n', (2207, 2218), True, 'import numpy as np\n'), ((3787, 3804), 'numpy.array', 'np.array', (['rcounts'], {}), '(rcounts)\n', (3795, 3804), True, 'import numpy as np\n')]
import cv2 import numpy as np from nnga.inference.base_predictor import BasePredictor from nnga.utils.data_manipulation import adjust_image_shape, normalize_image class SegmentationPredictor(BasePredictor): """Image predictor to NNGA models Parameters ---------- model_dir : {str} Path to NNGA folder from model dir. cfg {yacs.config import CfgNode} Experiment config data """ def __init__(self, model_dir, cfg): super().__init__(model_dir, cfg) self._image_shape = tuple(cfg.MODEL.INPUT_SHAPE) self._preserve_ratio = cfg.DATASET.PRESERVE_IMG_RATIO def _preprocessing(self, inpt): """Apply preprocessing input to be batch and model compatible. Parameters ---------- inpt : {numpy.ndarray} Input to be pre-processed Returns ------- numpy.ndarray Input pre-processed """ return normalize_image( adjust_image_shape(inpt, self._image_shape,) ) def predict(self, inpts): """Make prediction and return class indexes. Parameters ---------- inpts : {list} List of {numpy.ndarray}, inputs for model Returns ------- type tuple -- List of {numpy.ndarray} with class probabilities, dict to translate class indexes to label name. """ batch = self._make_batch(inpts) pred = self._model.predict(batch) masks = [] for i in range(len(pred)): predcit_mask = pred[i] _, predcit_mask = cv2.threshold(predcit_mask, 0.5, 255, cv2.THRESH_BINARY) masks.append(predcit_mask.astype('uint8')) return self._posprocessing(np.array(masks)), self._decode
[ "cv2.threshold", "nnga.utils.data_manipulation.adjust_image_shape", "numpy.array" ]
[((1045, 1088), 'nnga.utils.data_manipulation.adjust_image_shape', 'adjust_image_shape', (['inpt', 'self._image_shape'], {}), '(inpt, self._image_shape)\n', (1063, 1088), False, 'from nnga.utils.data_manipulation import adjust_image_shape, normalize_image\n'), ((1738, 1794), 'cv2.threshold', 'cv2.threshold', (['predcit_mask', '(0.5)', '(255)', 'cv2.THRESH_BINARY'], {}), '(predcit_mask, 0.5, 255, cv2.THRESH_BINARY)\n', (1751, 1794), False, 'import cv2\n'), ((1886, 1901), 'numpy.array', 'np.array', (['masks'], {}), '(masks)\n', (1894, 1901), True, 'import numpy as np\n')]
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import numpy as np from scipy.interpolate import interp1d from scipy.signal import find_peaks, peak_widths ALLOWED_STATISTICS = ["n_spikes", "spike_rate", "latency_to_first_spike", "average_AP_overshoot", "average_AHP_depth", "average_AP_width", "accommodation_index"] class SpikeStats: """ threshold : :obj:`int` or :obj:`float`, optional Required height of spikes. If `None`, the value is retrived from the threshold attribute from the constructor (which defaults to `0`). Default: `None`. """ def __init__( self, t_stim_on, t_stim_off, threshold=0, rfp=12.2, stats=None, ): # check ALLOWED_STATISTIC self._stats_provided = False # error handling if isinstance(stats, (list, tuple, np.ndarray)): self._stats_provided = True self._stats = stats[:] for i, stat in enumerate(self._stats): if not stat in ALLOWED_STATISTICS: msg = (f"Unknown statistic '{stat}' provided. Refer to " "documentation for a list of available statistics.") raise ValueError(msg) self._stats[i] = "_" + stat self._t_stim_on = t_stim_on self._t_stim_off = t_stim_off self._duration = self._t_stim_off - self._t_stim_on self._threshold = threshold self._rfp = rfp def __call__(self, V, t): if not self._stats_provided: msg = ("keyword argument 'stats' must be provided as a list of " "statistic attributes in order to make the instance " "callable.") raise ValueError(msg) self._V = V self._t = t self._spikes = self.find_spikes(self._V, self._t) #self._n_spikes = self._spikes["n_spikes"] sum_stats = [getattr(self, stat) for stat in self._stats] return sum_stats def find_spikes(self, V, t): """Find spikes in voltage trace. Find spikes in voltage trace that are above a specified threshold height. Parameters ---------- V : :term:`array_like` The voltage array of the voltage trace. t : :term:`array_like` The time array of the voltage trace. Returns ------- spikes : :obj:`dict` Dictionary containing the: * spike heights, key: `'spike_heights'` * spike times, key: `'spike_times'` * number of spikes, key: `'n_spikes'` * spike widths, key: `'spike_widths'` * spike positions in terms of indicies in voltage array, key: `'spike_idxs'` * spike widths data in terms of indices in voltage array, key: `'spike_widths_data'` """ # set required distance between spikes based on refractory period d = np.abs(t - self._rfp).argmin() # find spikes in voltage trace spike_idxs, properties = find_peaks(V, height=self._threshold, distance=d ) # obtain data about width of spikes; note that returned widths will be # in terms of index positions in voltage array spike_widths_data = peak_widths(V, spike_idxs, rel_height=0.5) # retrieve left and right interpolated positions specifying horizontal # start and end positions of the found spike widths left_ips, right_ips = spike_widths_data[2:] # membrane potential as interpolation function V_interpolate = interp1d(x=np.linspace(0, len(V), len(V)), y=V ) # voltage spike width in terms of physical units (instead of position # in array) spike_widths = V_interpolate(right_ips) - V_interpolate(left_ips) # gather results in a dictionary spikes = {"spike_heights": properties["peak_heights"], "spike_times": t[spike_idxs], "n_spikes": len(spike_idxs), "spike_widths": spike_widths, "spike_idxs": spike_idxs, "spike_widths_data": spike_widths_data } return spikes def width_lines(self, V, t): """Data for contour lines at which the widths where calculated. The purpose of this function is to prepare spike width data for plotting in terms of physical units. Can be used for plotting the located spike widths via e.g.: >>> features = SpikingFeatures(V, t, stim_duration, t_stim_on) >>> plt.hlines(*features.width_lines) Returns ------- width_lines : 3-tuple of ndarrays Contour lines. """ spikes = self.find_spikes(V, t) spike_widths_data = spikes["spike_widths_data"] # retrieve left and right interpolated positions specifying horizontal # start and end positions of the found spike widths left_ips, right_ips = spike_widths_data[2:] # time as interpolation function time_interpolate = interp1d(x=np.linspace(0, len(t), len(t)), y=t) # interpolated width positions in terms of physical units left_ips_physical = time_interpolate(left_ips) right_ips_physical = time_interpolate(right_ips) # the height of the contour lines at which the widths where evaluated width_heights = spike_widths_data[1] # assemble data of contour lines at which the widths where calculated spike_widths_data_physical = (width_heights, left_ips_physical, right_ips_physical) return spike_widths_data_physical def AHP_depth_positions(self, V, t): """Array of positions of after hyperpolarization depths in terms of indices. Returns ------- AHP_depth_position : array_like The positions of the minimum voltage values between consecutive action potentials. """ ''' spikes = self.find_spikes(V, t) spike_idxs = spikes["spike_idxs"] ahp_depth_positions = [] for i in range(spikes["n_spikes"] - 1): # search for minimum value between two spikes spike1_idx = spike_idxs[i] spike2_idx = spike_idxs[i + 1] # slice out voltage trace between the spikes V_slice = V[spike1_idx:spike2_idx] # find index of min. value relative to first spike min_rel_pos = np.argmin(V_slice) # the position in total voltage trace min_pos = spike1_idx + min_rel_pos ahp_depth_positions.append(min_pos) return ahp_depth_positions ''' d = np.abs(t - self._rfp).argmin() # find spikes in voltage trace spike_idxs, _ = find_peaks(V, height=self._threshold, distance=d ) # find depths after first spike neg_spike_idxs, _ = find_peaks(-V[spike_idxs[0]:spike_idxs[-1]], height=self._threshold, distance=d ) # shift found positions to match indicies in voltage trace arrays ahp_depth_positions = neg_spike_idxs + spike_idxs[0] return ahp_depth_positions def isi(self, spike_times): """Interspike intervals (ISIs). ISI is the time between subsequent action potentials. Returns ------- ISIs : array_like Interspike intervals. """ isi = [spike_times[i + 1] - spike_times[i] for i in range(len(spike_times) - 1)] return np.array(isi) def n_spikes(self, V, t): """The number of spikes in voltage trace. Parameters ---------- V : :term:`array_like` The voltage array of the voltage trace. Returns ------- n_spikes : :obj:`int` Number of spikes. """ spikes = self.find_spikes(V, t) return spikes["n_spikes"] def spike_rate(self, V, t): """Compute the spike rate. The spike rate, or the action potential firing rate, is the number of action potentials (spikes) divided by stimulus duration. Parameters ---------- V : :term:`array_like` The voltage array of the voltage trace. Returns ------- spike_rate : :obj:`float` Spike rate. """ spikes = self.find_spikes(V, t) n_spikes = spikes["n_spikes"] if n_spikes < 1: return np.inf return n_spikes / self._duration def latency_to_first_spike(self, V, t): """ """ spikes = self.find_spikes(V, t) if spikes["n_spikes"] < 1: return np.inf return spikes["spike_times"][0] - self._t_stim_on def average_AP_overshoot(self, V, t): """ """ spikes = self.find_spikes(V, t) n_spikes = spikes["n_spikes"] if n_spikes < 1: return np.inf return np.sum(spikes["spike_heights"]) / n_spikes def average_AHP_depth(self, V, t): """ """ ''' spikes = self.find_spikes(V, t) n_spikes = spikes["n_spikes"] spike_idxs = spikes["spike_idxs"] if n_spikes < 3: return np.inf sum_ahp_depth = sum([np.min(V[spike_idxs[i]:spike_idxs[i + 1]]) for i in range(n_spikes - 1)]) avg_ahp_depth = sum_ahp_depth / n_spikes return avg_ahp_depth ''' spikes = self.find_spikes(V, t) n_spikes = spikes["n_spikes"] if n_spikes < 3: return np.inf ahp_depth_pos = self.AHP_depth_positions(V, t) avg_ahp_depth = np.mean(V[ahp_depth_pos]) return avg_ahp_depth def average_AP_width(self, V, t): """ """ spikes = self.find_spikes(V, t) n_spikes = spikes["n_spikes"] if n_spikes < 1: return np.inf return np.sum(spikes["spike_widths"]) / n_spikes def accommodation_index(self, V, t): """ Excerpt from Druckmann et al. (2007): k determines the number of ISIs that will be disregarded in order not to take into account possible transient behavior as observed in Markram et al. (2004). A reasonable value for k is either four ISIs or one-fifth of the total number of ISIs, whichever is the smaller of the two." """ spikes = self.find_spikes(V, t) n_spikes = spikes["n_spikes"] if n_spikes < 2: return np.inf isi = self.isi(spikes["spike_times"]) k = min(4, int(len(isi) / 5)) A = 0 for i in range(k + 1, n_spikes - 1): A += (isi[i] - isi[i - 1]) / (isi[i] + isi[i - 1]) return A / (n_spikes - k - 1) @property def _n_spikes(self): return self._spikes["n_spikes"] @property def _spike_rate(self): if self._n_spikes < 1: return np.inf return self._n_spikes / self._duration @property def _latency_to_first_spike(self): """ """ if self._n_spikes < 1: return np.inf return self._spikes["spike_times"][0] - self._t_stim_on @property def _average_AP_overshoot(self): """ """ if self._n_spikes < 1: return np.inf return np.sum(self._spikes["spike_heights"]) / self._n_spikes @property def _average_AHP_depth(self): """ """ spike_idxs = self._spikes["spike_idxs"] if self._n_spikes < 3: return np.inf ''' sum_ahp_depth = sum([np.min(self._V[spike_idxs[i]:spike_idxs[i + 1]]) for i in range(self._n_spikes - 1)]) avg_ahp_depth = sum_ahp_depth / self._n_spikes return avg_ahp_depth ''' ahp_depth_pos = self.AHP_depth_positions(self._V, self._t) avg_ahp_depth = np.mean(self._V[ahp_depth_pos]) return avg_ahp_depth @property def _average_AP_width(self): """ """ if self._n_spikes < 1: return np.inf return np.sum(self._spikes["spike_widths"]) / self._n_spikes @property def _accommodation_index(self): """ """ if self._n_spikes < 2: return np.inf isi = self.isi(self._spikes["spike_times"]) k = min(4, int(len(isi) / 5)) A = 0 for i in range(k + 1, self._n_spikes - 1): A += (isi[i] - isi[i - 1]) / (isi[i] + isi[i - 1]) return A / (self._n_spikes - k - 1) if __name__ == "__main__": import matplotlib as mpl import matplotlib.lines as mlines import matplotlib.pyplot as plt import neuromodels as nm import seaborn as sns from matplotlib import gridspec sns.set() sns.set_context("paper") sns.set_style("darkgrid", {"axes.facecolor": "0.96"}) # Set fontsizes in figures 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) # remove top and right axis from plots mpl.rcParams['axes.spines.right'] = False mpl.rcParams['axes.spines.top'] = False # HH simulation hh = nm.solvers.HodgkinHuxleySolver() # simulation parameters # simulation parameters T = 120. dt = 0.01 I_amp = 0.35 # 0.1 #0.31 t_stim_on = 10 t_stim_off = 110 r_soma = 40 # 15 # input stimulus stimulus = nm.stimulus.constant(I_amp=I_amp, T=T, dt=dt, t_stim_on=t_stim_on, t_stim_off=t_stim_off, r_soma=r_soma) # print(stimulus["info"]) I = stimulus["I"] I_stim = stimulus["I_stim"] hh.solve(I, T, dt) V = hh.V t = hh.t # Spike statistics, callable instance stats = ["spike_rate", "latency_to_first_spike", "average_AP_overshoot", "average_AHP_depth", "average_AP_width", "accommodation_index"] sps = SpikeStats(t_stim_on=t_stim_on, t_stim_off=t_stim_off, stats=stats) sum_stats = sps(V, t) print(sum_stats) # Spike statistics, class methods print("SPIKE STATS") sps = SpikeStats(t_stim_on=t_stim_on, t_stim_off=t_stim_off) # number of spikes n_spikes = sps.n_spikes(V, t) print(f"{n_spikes=}") # spike rate spike_rate = sps.spike_rate(V, t) print(f"{spike_rate=:.4f} mHz") # latency to first spike latency_to_first_spike = sps.latency_to_first_spike(V, t) print(f"{latency_to_first_spike=:.4f} ms") # average AP overshoot average_AP_overshoot = sps.average_AP_overshoot(V, t) print(f"{average_AP_overshoot=:.4f} mV") # average AHP depth average_AHP_depth = sps.average_AHP_depth(V, t) print(f"{average_AHP_depth=:.4f} mV") # average AP width average_AP_width = sps.average_AP_width(V, t) print(f"{average_AP_width=:.4f} mV") # accommodation index accommodation_index = sps.accommodation_index(V, t) print(f"{accommodation_index=:.4f}") # plot voltage trace with features spikes = sps.find_spikes(V, t) spike_idxs = spikes["spike_idxs"] spike_heights = spikes["spike_heights"] width_lines = sps.width_lines(V, t) ahp_depth_idxs = sps.AHP_depth_positions(V, t) fig = plt.figure(figsize=(8, 6), tight_layout=True, dpi=140) gs = gridspec.GridSpec(2, 1, height_ratios=[4, 1]) ax = plt.subplot(gs[0]) # voltage trace plt.plot(t, V, lw=1.5, label='Voltage trace') # AP overshoot plt.plot(t[spike_idxs], V[spike_idxs], "x", ms=7, color='black', label='AP overshoot') # AP widths plt.hlines(*width_lines, color="red", lw=2, label='AP width') # AHP depths plt.plot(t[ahp_depth_idxs], V[ahp_depth_idxs], 'o', ms=5, color='indianred', label='AHP depth') # latency to first spike plt.hlines(hh.V_rest, t_stim_on, t[spike_idxs[0]], color='black', lw=1.5, ls=":") plt.vlines(t[spike_idxs[0]], hh.V_rest, spike_heights[0], color='black', lw=1.5, ls=":", label="Latency to first spike") # the marked ISIs are used to compute the accommodation index # ISI arrow legend plt.plot([], [], color='g', marker=r'$\longleftrightarrow$', linestyle='None', markersize=15, label='ISIs') # ISI spike 1 -> 2 plt.vlines(t[spike_idxs[0]], V[spike_idxs[0]], 48, color='darkorange', ls='--', label='Spike rate') plt.annotate('', xy=(t[spike_idxs[0]], 48), xycoords='data', xytext=(t[spike_idxs[1]], 48), textcoords='data', arrowprops={'arrowstyle': '<->', 'color': 'g'}) # ISI spike 2 -> 3 plt.vlines(t[spike_idxs[1]], V[spike_idxs[1]], 48, color='darkorange', ls='--') plt.annotate('', xy=(t[spike_idxs[1]], 48), xycoords='data', xytext=(t[spike_idxs[2]], 48), textcoords='data', arrowprops={'arrowstyle': '<->', 'color': 'g'}) # ISI spike 3 -> 4 plt.vlines(t[spike_idxs[2]], V[spike_idxs[2]], 48, color='darkorange', lw=1.5, ls='--') plt.annotate('', xy=(t[spike_idxs[2]], 48), xycoords='data', xytext=(t[spike_idxs[3]], 48), textcoords='data', arrowprops={'arrowstyle': '<->', 'color': 'g'}) # ISI spike 4 -> 5 plt.vlines(t[spike_idxs[3]], V[spike_idxs[3]], 48, color='darkorange', lw=1.5, ls='--') plt.annotate('', xy=(t[spike_idxs[3]], 48), xycoords='data', xytext=(t[spike_idxs[4]], 48), textcoords='data', arrowprops={'arrowstyle': '<->', 'color': 'g'}) # ISI spike 5 -> 6 plt.vlines(t[spike_idxs[4]], V[spike_idxs[4]], 48, color='darkorange', lw=1.5, ls='--') plt.vlines(t[spike_idxs[5]], V[spike_idxs[5]], 48, color='darkorange', lw=1.5, ls='--') plt.annotate('', xy=(t[spike_idxs[4]], 48), xycoords='data', xytext=(t[spike_idxs[5]], 48), textcoords='data', arrowprops={'arrowstyle': '<->', 'color': 'g'}) plt.ylabel('Voltage (mV)') plt.ylim(-90, 60) ax.set_xticks([]) ax.set_yticks([-80, -20, 40]) handles, labels = ax.get_legend_handles_labels() plt.legend(handles, labels, loc='center left', bbox_to_anchor=(1.04, 0.5), fancybox=True, borderaxespad=0.1, ncol=1 ) ax = plt.subplot(gs[1]) plt.plot(t, I_stim, 'k', lw=2) plt.xlabel('Time (ms)') plt.ylabel('Stimulus (nA)') ax.set_xticks([0, np.max(t) / 2, np.max(t)]) ax.set_yticks([0, np.max(I_stim)]) ax.yaxis.set_major_formatter(mpl.ticker.FormatStrFormatter('%.2f')) fig.suptitle("Spike Statistics") plt.show()
[ "numpy.sum", "numpy.abs", "matplotlib.pyplot.figure", "scipy.signal.find_peaks", "numpy.mean", "matplotlib.pyplot.hlines", "scipy.signal.peak_widths", "numpy.max", "matplotlib.pyplot.rcParams.update", "matplotlib.pyplot.rc", "matplotlib.ticker.FormatStrFormatter", "seaborn.set", "seaborn.set_context", "seaborn.set_style", "matplotlib.pyplot.show", "matplotlib.pyplot.ylim", "matplotlib.pyplot.legend", "neuromodels.solvers.HodgkinHuxleySolver", "matplotlib.pyplot.ylabel", "matplotlib.pyplot.subplot", "matplotlib.pyplot.plot", "matplotlib.pyplot.annotate", "matplotlib.pyplot.vlines", "numpy.array", "neuromodels.stimulus.constant", "matplotlib.gridspec.GridSpec", "matplotlib.pyplot.xlabel" ]
[((13594, 13603), 'seaborn.set', 'sns.set', ([], {}), '()\n', (13601, 13603), True, 'import seaborn as sns\n'), ((13608, 13632), 'seaborn.set_context', 'sns.set_context', (['"""paper"""'], {}), "('paper')\n", (13623, 13632), True, 'import seaborn as sns\n'), ((13637, 13690), 'seaborn.set_style', 'sns.set_style', (['"""darkgrid"""', "{'axes.facecolor': '0.96'}"], {}), "('darkgrid', {'axes.facecolor': '0.96'})\n", (13650, 13690), True, 'import seaborn as sns\n'), ((14017, 14044), 'matplotlib.pyplot.rcParams.update', 'plt.rcParams.update', (['params'], {}), '(params)\n', (14036, 14044), True, 'import matplotlib.pyplot as plt\n'), ((14049, 14076), 'matplotlib.pyplot.rc', 'plt.rc', (['"""text"""'], {'usetex': '(True)'}), "('text', usetex=True)\n", (14055, 14076), True, 'import matplotlib.pyplot as plt\n'), ((14241, 14273), 'neuromodels.solvers.HodgkinHuxleySolver', 'nm.solvers.HodgkinHuxleySolver', ([], {}), '()\n', (14271, 14273), True, 'import neuromodels as nm\n'), ((14489, 14597), 'neuromodels.stimulus.constant', 'nm.stimulus.constant', ([], {'I_amp': 'I_amp', 'T': 'T', 'dt': 'dt', 't_stim_on': 't_stim_on', 't_stim_off': 't_stim_off', 'r_soma': 'r_soma'}), '(I_amp=I_amp, T=T, dt=dt, t_stim_on=t_stim_on,\n t_stim_off=t_stim_off, r_soma=r_soma)\n', (14509, 14597), True, 'import neuromodels as nm\n'), ((16475, 16529), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(8, 6)', 'tight_layout': '(True)', 'dpi': '(140)'}), '(figsize=(8, 6), tight_layout=True, dpi=140)\n', (16485, 16529), True, 'import matplotlib.pyplot as plt\n'), ((16539, 16584), 'matplotlib.gridspec.GridSpec', 'gridspec.GridSpec', (['(2)', '(1)'], {'height_ratios': '[4, 1]'}), '(2, 1, height_ratios=[4, 1])\n', (16556, 16584), False, 'from matplotlib import gridspec\n'), ((16594, 16612), 'matplotlib.pyplot.subplot', 'plt.subplot', (['gs[0]'], {}), '(gs[0])\n', (16605, 16612), True, 'import matplotlib.pyplot as plt\n'), ((16638, 16683), 'matplotlib.pyplot.plot', 'plt.plot', (['t', 'V'], {'lw': '(1.5)', 'label': '"""Voltage trace"""'}), "(t, V, lw=1.5, label='Voltage trace')\n", (16646, 16683), True, 'import matplotlib.pyplot as plt\n'), ((16708, 16799), 'matplotlib.pyplot.plot', 'plt.plot', (['t[spike_idxs]', 'V[spike_idxs]', '"""x"""'], {'ms': '(7)', 'color': '"""black"""', 'label': '"""AP overshoot"""'}), "(t[spike_idxs], V[spike_idxs], 'x', ms=7, color='black', label=\n 'AP overshoot')\n", (16716, 16799), True, 'import matplotlib.pyplot as plt\n'), ((16829, 16890), 'matplotlib.pyplot.hlines', 'plt.hlines', (['*width_lines'], {'color': '"""red"""', 'lw': '(2)', 'label': '"""AP width"""'}), "(*width_lines, color='red', lw=2, label='AP width')\n", (16839, 16890), True, 'import matplotlib.pyplot as plt\n'), ((16913, 17012), 'matplotlib.pyplot.plot', 'plt.plot', (['t[ahp_depth_idxs]', 'V[ahp_depth_idxs]', '"""o"""'], {'ms': '(5)', 'color': '"""indianred"""', 'label': '"""AHP depth"""'}), "(t[ahp_depth_idxs], V[ahp_depth_idxs], 'o', ms=5, color='indianred',\n label='AHP depth')\n", (16921, 17012), True, 'import matplotlib.pyplot as plt\n'), ((17056, 17141), 'matplotlib.pyplot.hlines', 'plt.hlines', (['hh.V_rest', 't_stim_on', 't[spike_idxs[0]]'], {'color': '"""black"""', 'lw': '(1.5)', 'ls': '""":"""'}), "(hh.V_rest, t_stim_on, t[spike_idxs[0]], color='black', lw=1.5,\n ls=':')\n", (17066, 17141), True, 'import matplotlib.pyplot as plt\n'), ((17157, 17282), 'matplotlib.pyplot.vlines', 'plt.vlines', (['t[spike_idxs[0]]', 'hh.V_rest', 'spike_heights[0]'], {'color': '"""black"""', 'lw': '(1.5)', 'ls': '""":"""', 'label': '"""Latency to first spike"""'}), "(t[spike_idxs[0]], hh.V_rest, spike_heights[0], color='black', lw\n =1.5, ls=':', label='Latency to first spike')\n", (17167, 17282), True, 'import matplotlib.pyplot as plt\n'), ((17387, 17499), 'matplotlib.pyplot.plot', 'plt.plot', (['[]', '[]'], {'color': '"""g"""', 'marker': '"""$\\\\longleftrightarrow$"""', 'linestyle': '"""None"""', 'markersize': '(15)', 'label': '"""ISIs"""'}), "([], [], color='g', marker='$\\\\longleftrightarrow$', linestyle=\n 'None', markersize=15, label='ISIs')\n", (17395, 17499), True, 'import matplotlib.pyplot as plt\n'), ((17536, 17640), 'matplotlib.pyplot.vlines', 'plt.vlines', (['t[spike_idxs[0]]', 'V[spike_idxs[0]]', '(48)'], {'color': '"""darkorange"""', 'ls': '"""--"""', 'label': '"""Spike rate"""'}), "(t[spike_idxs[0]], V[spike_idxs[0]], 48, color='darkorange', ls=\n '--', label='Spike rate')\n", (17546, 17640), True, 'import matplotlib.pyplot as plt\n'), ((17655, 17822), 'matplotlib.pyplot.annotate', 'plt.annotate', (['""""""'], {'xy': '(t[spike_idxs[0]], 48)', 'xycoords': '"""data"""', 'xytext': '(t[spike_idxs[1]], 48)', 'textcoords': '"""data"""', 'arrowprops': "{'arrowstyle': '<->', 'color': 'g'}"}), "('', xy=(t[spike_idxs[0]], 48), xycoords='data', xytext=(t[\n spike_idxs[1]], 48), textcoords='data', arrowprops={'arrowstyle': '<->',\n 'color': 'g'})\n", (17667, 17822), True, 'import matplotlib.pyplot as plt\n'), ((17876, 17955), 'matplotlib.pyplot.vlines', 'plt.vlines', (['t[spike_idxs[1]]', 'V[spike_idxs[1]]', '(48)'], {'color': '"""darkorange"""', 'ls': '"""--"""'}), "(t[spike_idxs[1]], V[spike_idxs[1]], 48, color='darkorange', ls='--')\n", (17886, 17955), True, 'import matplotlib.pyplot as plt\n'), ((17975, 18142), 'matplotlib.pyplot.annotate', 'plt.annotate', (['""""""'], {'xy': '(t[spike_idxs[1]], 48)', 'xycoords': '"""data"""', 'xytext': '(t[spike_idxs[2]], 48)', 'textcoords': '"""data"""', 'arrowprops': "{'arrowstyle': '<->', 'color': 'g'}"}), "('', xy=(t[spike_idxs[1]], 48), xycoords='data', xytext=(t[\n spike_idxs[2]], 48), textcoords='data', arrowprops={'arrowstyle': '<->',\n 'color': 'g'})\n", (17987, 18142), True, 'import matplotlib.pyplot as plt\n'), ((18196, 18288), 'matplotlib.pyplot.vlines', 'plt.vlines', (['t[spike_idxs[2]]', 'V[spike_idxs[2]]', '(48)'], {'color': '"""darkorange"""', 'lw': '(1.5)', 'ls': '"""--"""'}), "(t[spike_idxs[2]], V[spike_idxs[2]], 48, color='darkorange', lw=\n 1.5, ls='--')\n", (18206, 18288), True, 'import matplotlib.pyplot as plt\n'), ((18303, 18470), 'matplotlib.pyplot.annotate', 'plt.annotate', (['""""""'], {'xy': '(t[spike_idxs[2]], 48)', 'xycoords': '"""data"""', 'xytext': '(t[spike_idxs[3]], 48)', 'textcoords': '"""data"""', 'arrowprops': "{'arrowstyle': '<->', 'color': 'g'}"}), "('', xy=(t[spike_idxs[2]], 48), xycoords='data', xytext=(t[\n spike_idxs[3]], 48), textcoords='data', arrowprops={'arrowstyle': '<->',\n 'color': 'g'})\n", (18315, 18470), True, 'import matplotlib.pyplot as plt\n'), ((18523, 18615), 'matplotlib.pyplot.vlines', 'plt.vlines', (['t[spike_idxs[3]]', 'V[spike_idxs[3]]', '(48)'], {'color': '"""darkorange"""', 'lw': '(1.5)', 'ls': '"""--"""'}), "(t[spike_idxs[3]], V[spike_idxs[3]], 48, color='darkorange', lw=\n 1.5, ls='--')\n", (18533, 18615), True, 'import matplotlib.pyplot as plt\n'), ((18630, 18797), 'matplotlib.pyplot.annotate', 'plt.annotate', (['""""""'], {'xy': '(t[spike_idxs[3]], 48)', 'xycoords': '"""data"""', 'xytext': '(t[spike_idxs[4]], 48)', 'textcoords': '"""data"""', 'arrowprops': "{'arrowstyle': '<->', 'color': 'g'}"}), "('', xy=(t[spike_idxs[3]], 48), xycoords='data', xytext=(t[\n spike_idxs[4]], 48), textcoords='data', arrowprops={'arrowstyle': '<->',\n 'color': 'g'})\n", (18642, 18797), True, 'import matplotlib.pyplot as plt\n'), ((18850, 18942), 'matplotlib.pyplot.vlines', 'plt.vlines', (['t[spike_idxs[4]]', 'V[spike_idxs[4]]', '(48)'], {'color': '"""darkorange"""', 'lw': '(1.5)', 'ls': '"""--"""'}), "(t[spike_idxs[4]], V[spike_idxs[4]], 48, color='darkorange', lw=\n 1.5, ls='--')\n", (18860, 18942), True, 'import matplotlib.pyplot as plt\n'), ((18957, 19049), 'matplotlib.pyplot.vlines', 'plt.vlines', (['t[spike_idxs[5]]', 'V[spike_idxs[5]]', '(48)'], {'color': '"""darkorange"""', 'lw': '(1.5)', 'ls': '"""--"""'}), "(t[spike_idxs[5]], V[spike_idxs[5]], 48, color='darkorange', lw=\n 1.5, ls='--')\n", (18967, 19049), True, 'import matplotlib.pyplot as plt\n'), ((19064, 19231), 'matplotlib.pyplot.annotate', 'plt.annotate', (['""""""'], {'xy': '(t[spike_idxs[4]], 48)', 'xycoords': '"""data"""', 'xytext': '(t[spike_idxs[5]], 48)', 'textcoords': '"""data"""', 'arrowprops': "{'arrowstyle': '<->', 'color': 'g'}"}), "('', xy=(t[spike_idxs[4]], 48), xycoords='data', xytext=(t[\n spike_idxs[5]], 48), textcoords='data', arrowprops={'arrowstyle': '<->',\n 'color': 'g'})\n", (19076, 19231), True, 'import matplotlib.pyplot as plt\n'), ((19262, 19288), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Voltage (mV)"""'], {}), "('Voltage (mV)')\n", (19272, 19288), True, 'import matplotlib.pyplot as plt\n'), ((19293, 19310), 'matplotlib.pyplot.ylim', 'plt.ylim', (['(-90)', '(60)'], {}), '(-90, 60)\n', (19301, 19310), True, 'import matplotlib.pyplot as plt\n'), ((19424, 19544), 'matplotlib.pyplot.legend', 'plt.legend', (['handles', 'labels'], {'loc': '"""center left"""', 'bbox_to_anchor': '(1.04, 0.5)', 'fancybox': '(True)', 'borderaxespad': '(0.1)', 'ncol': '(1)'}), "(handles, labels, loc='center left', bbox_to_anchor=(1.04, 0.5),\n fancybox=True, borderaxespad=0.1, ncol=1)\n", (19434, 19544), True, 'import matplotlib.pyplot as plt\n'), ((19657, 19675), 'matplotlib.pyplot.subplot', 'plt.subplot', (['gs[1]'], {}), '(gs[1])\n', (19668, 19675), True, 'import matplotlib.pyplot as plt\n'), ((19680, 19710), 'matplotlib.pyplot.plot', 'plt.plot', (['t', 'I_stim', '"""k"""'], {'lw': '(2)'}), "(t, I_stim, 'k', lw=2)\n", (19688, 19710), True, 'import matplotlib.pyplot as plt\n'), ((19715, 19738), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Time (ms)"""'], {}), "('Time (ms)')\n", (19725, 19738), True, 'import matplotlib.pyplot as plt\n'), ((19743, 19770), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Stimulus (nA)"""'], {}), "('Stimulus (nA)')\n", (19753, 19770), True, 'import matplotlib.pyplot as plt\n'), ((19973, 19983), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (19981, 19983), True, 'import matplotlib.pyplot as plt\n'), ((3223, 3272), 'scipy.signal.find_peaks', 'find_peaks', (['V'], {'height': 'self._threshold', 'distance': 'd'}), '(V, height=self._threshold, distance=d)\n', (3233, 3272), False, 'from scipy.signal import find_peaks, peak_widths\n'), ((3569, 3611), 'scipy.signal.peak_widths', 'peak_widths', (['V', 'spike_idxs'], {'rel_height': '(0.5)'}), '(V, spike_idxs, rel_height=0.5)\n', (3580, 3611), False, 'from scipy.signal import find_peaks, peak_widths\n'), ((7290, 7339), 'scipy.signal.find_peaks', 'find_peaks', (['V'], {'height': 'self._threshold', 'distance': 'd'}), '(V, height=self._threshold, distance=d)\n', (7300, 7339), False, 'from scipy.signal import find_peaks, peak_widths\n'), ((7515, 7600), 'scipy.signal.find_peaks', 'find_peaks', (['(-V[spike_idxs[0]:spike_idxs[-1]])'], {'height': 'self._threshold', 'distance': 'd'}), '(-V[spike_idxs[0]:spike_idxs[-1]], height=self._threshold, distance=d\n )\n', (7525, 7600), False, 'from scipy.signal import find_peaks, peak_widths\n'), ((8248, 8261), 'numpy.array', 'np.array', (['isi'], {}), '(isi)\n', (8256, 8261), True, 'import numpy as np\n'), ((10426, 10451), 'numpy.mean', 'np.mean', (['V[ahp_depth_pos]'], {}), '(V[ahp_depth_pos])\n', (10433, 10451), True, 'import numpy as np\n'), ((12705, 12736), 'numpy.mean', 'np.mean', (['self._V[ahp_depth_pos]'], {}), '(self._V[ahp_depth_pos])\n', (12712, 12736), True, 'import numpy as np\n'), ((19892, 19929), 'matplotlib.ticker.FormatStrFormatter', 'mpl.ticker.FormatStrFormatter', (['"""%.2f"""'], {}), "('%.2f')\n", (19921, 19929), True, 'import matplotlib as mpl\n'), ((9698, 9729), 'numpy.sum', 'np.sum', (["spikes['spike_heights']"], {}), "(spikes['spike_heights'])\n", (9704, 9729), True, 'import numpy as np\n'), ((10691, 10721), 'numpy.sum', 'np.sum', (["spikes['spike_widths']"], {}), "(spikes['spike_widths'])\n", (10697, 10721), True, 'import numpy as np\n'), ((12122, 12159), 'numpy.sum', 'np.sum', (["self._spikes['spike_heights']"], {}), "(self._spikes['spike_heights'])\n", (12128, 12159), True, 'import numpy as np\n'), ((12913, 12949), 'numpy.sum', 'np.sum', (["self._spikes['spike_widths']"], {}), "(self._spikes['spike_widths'])\n", (12919, 12949), True, 'import numpy as np\n'), ((19808, 19817), 'numpy.max', 'np.max', (['t'], {}), '(t)\n', (19814, 19817), True, 'import numpy as np\n'), ((19842, 19856), 'numpy.max', 'np.max', (['I_stim'], {}), '(I_stim)\n', (19848, 19856), True, 'import numpy as np\n'), ((3119, 3140), 'numpy.abs', 'np.abs', (['(t - self._rfp)'], {}), '(t - self._rfp)\n', (3125, 3140), True, 'import numpy as np\n'), ((7195, 7216), 'numpy.abs', 'np.abs', (['(t - self._rfp)'], {}), '(t - self._rfp)\n', (7201, 7216), True, 'import numpy as np\n'), ((19793, 19802), 'numpy.max', 'np.max', (['t'], {}), '(t)\n', (19799, 19802), True, 'import numpy as np\n')]
import numpy as np lin = open("__21_d25.txt").read().splitlines(); gm = np.array([list(line) for line in lin]) def st(hN, gm): tM = gm == hN; gS = np.roll(gm, -1, 1 if hN == ">" else 0) tM[gS != '.'] = False; gm[tM] = '.'; tS = np.roll(tM, 1, 1 if hN == ">" else 0) gm[tS] = hN; return len(gm[tM]) count = 1 while st('>', gm) + st('v', gm) > 0: count += 1 print(count)
[ "numpy.roll" ]
[((150, 188), 'numpy.roll', 'np.roll', (['gm', '(-1)', "(1 if hN == '>' else 0)"], {}), "(gm, -1, 1 if hN == '>' else 0)\n", (157, 188), True, 'import numpy as np\n'), ((232, 269), 'numpy.roll', 'np.roll', (['tM', '(1)', "(1 if hN == '>' else 0)"], {}), "(tM, 1, 1 if hN == '>' else 0)\n", (239, 269), True, 'import numpy as np\n')]
"""A domain for real-world experiments.""" import time from itertools import combinations from pathlib import Path from typing import Tuple, Union from inquire.environments.gym_wrapper_environment import Environment from inquire.interactions.feedback import Trajectory from numba import jit import numpy as np import pandas as pd class Pizza(Environment): """Create a pepperoni pizza by placing toppings.""" def __init__( self, seed: int = None, max_topping_count: int = 25, topping_sample_count: int = 1500, optimization_iteration_count: int = 300, pizza_form: dict = None, basis_functions: list = None, output_path: str = str(Path.cwd()) + "/output/pizza_environment/", verbose: bool = False, ): """Initialize a domain for creating pizzas. ::inputs: ::topping_max: The total number of toppings a pizza can have; akin to a trajectory length. ::pizza_form: The high-level attributes of a pizza. """ self._seed = seed self._max_topping_count = max_topping_count self._topping_sample_count = topping_sample_count self._pizza_form = pizza_form self._optimization_iteration_count = optimization_iteration_count self._output_path = output_path self._verbose = verbose self._rng = np.random.default_rng(self._seed) crust_and_topping_factor = (self._pizza_form["crust_thickness"]) + ( self._pizza_form["topping_diam"] / 2.0 ) self._viable_surface_radius = ( self._pizza_form["diameter"] / 2.0 - crust_and_topping_factor ) self._viable_surface_area = np.pi * self._viable_surface_radius ** 2 self._area_per_topping = ( np.pi * (self._pizza_form["topping_diam"] / 2.0) ** 2 ) self._x_coordinate_range = np.linspace( -self._viable_surface_radius, self._viable_surface_radius, 1000, endpoint=True, ) self._y_coordinate_range = np.array( self._x_coordinate_range, copy=True ) self.w_dim = len(basis_functions) self._basis_functions = basis_functions basis_fn_memory_blocks = [] # Make a composition of basis functions: for b in basis_functions: if b == "approximate_coverage": basis_fn_memory_blocks.append( self.approximate_surface_coverage ) elif b == "approximate_overlap_last_to_all": basis_fn_memory_blocks.append(self.approximate_overlap_last) elif b == "avg_magnitude_last_to_all": basis_fn_memory_blocks.append(self.avg_magnitude_last_to_all) elif b == "last_point_x_variance": basis_fn_memory_blocks.append(self.last_point_x_variance) elif b == "last_point_y_variance": basis_fn_memory_blocks.append(self.last_point_y_variance) elif b == "markovian_magnitude": basis_fn_memory_blocks.append(self.markovian_magnitude) # The feature function is a composition of the basis functions: def feature_fn(topping_coords: np.ndarray) -> np.ndarray: """Compute the features of a set of topping placements.""" feature_values = np.array([]) # For each basis function in this feature function: for i, b in enumerate(basis_fn_memory_blocks): # Compute the feature value: feature_values = np.append(feature_values, b(topping_coords)) return feature_values self.compute_features = feature_fn @property def basis_functions(self) -> dict: """Return dictionary of high-level attributes.""" return self._basis_functions.copy() @property def pizza_form(self) -> dict: """Return dictionary of high-level attributes.""" return self._pizza_form.copy() @property def viable_surface_radius(self) -> float: """Return radius of surface upon which toppings can be placed.""" return self._viable_surface_radius @property def max_topping_count(self) -> int: """Return the maximum number of toppings to include on any pizza.""" return self._max_topping_count def generate_random_state(self, random_state) -> np.ndarray: """Generate a random set of toppings to put on a pizza. ::inputs: ::random_state: A number generator object; instead use self._rng """ pizza_topping_count = self._rng.integers( low=1, high=self._max_topping_count - 1 ) # Generate pizza_topping_count x,y coordinates: topping_coordinates = generate_2D_points( radius=self._viable_surface_radius, count=pizza_topping_count ) return topping_coordinates def generate_random_reward(self, random_state) -> int: """Generate a random vector of weights. ::inputs: ::random_state: A number generator object; instead use this class' rng instance attribute. """ weights = self._rng.random((self.w_dim,)) for i in range(weights.shape[0]): sign = self._rng.choice((-1, 1), 1) weights[i] = sign * weights[i] weights = weights / np.linalg.norm(weights) # weights = weights / np.sum(weights) return weights.squeeze() def optimal_trajectory_from_w( self, start_state: np.ndarray, w: Union[list, np.ndarray] ) -> np.ndarray: """Find placement of next topping which yields greatest reward. ::inputs: ::start_state: A set of (x,y) coordinates of topping placements. ::w: A vector of weights corresponding to the domain's features. """ start = time.perf_counter() toppings = np.array(start_state, copy=True) best_reward = None best_toppings = None best_features = None for i in range(self._optimization_iteration_count): # Generate a bunch of potential positions for the next slice: new_toppings = generate_2D_points( self._viable_surface_radius, self._topping_sample_count ) # See which of new_toppings yields the greatest reward: for j in range(new_toppings.shape[1]): temp_toppings = np.hstack( (toppings, new_toppings[:, j].reshape(-1, 1)) ) temp_features = self.features( new_toppings[:, j], temp_toppings ).squeeze() new_reward = w.dot(temp_features.T) if best_reward is None: best_reward = new_reward if new_reward > best_reward: best_reward = new_reward best_toppings = np.array(temp_toppings, copy=True) best_features = np.array(temp_features, copy=True) best_topping_placements = Trajectory(best_toppings, best_features) if self._verbose: elapsed = time.perf_counter() - start print( f"It took {elapsed:.2} seconds to find next topping placement." ) return best_topping_placements def features( self, action: Union[np.ndarray, list], state: Union[list, np.ndarray] ) -> np.ndarray: """Compute the features of state reached by action. ::inputs: ::action: The (x,y) coordinate of the topping that was most recently placed on the pizza. ::state: The (x, y) coordinates of all toppings. Shape: 2-by-n. """ # If there are no toppings or just one topping, we have no features # to compute: if state.shape[1] == 1: return np.zeros((self.w_dim,)) else: # Copy to avoid mutating: coords = np.array(state, copy=True) coords_features = self.compute_features(coords) return coords_features.squeeze() def available_actions(self, current_state: np.ndarray) -> list: """Return the possible topping placements given current_state.""" if self.is_terminal_state(current_state): return [] else: return [self._x_coordinate_range, self._y_coordinate_range] def next_state( self, current_state: np.ndarray, action: list ) -> np.ndarray: """Generate state after transition from current_state via action.""" next_topping = np.array(action, copy=True).reshape(-1, 1) new_state = np.append(current_state, next_topping, axis=1) return new_state def is_terminal_state(self, current_state: np.ndarray) -> bool: """Check if more toppings can be added.""" if current_state.shape[1] >= self._max_topping_count: return True else: return False def all_actions(self) -> list: """All possible topping placements.""" return [self._x_coordinate_range, self._y_coordinate_range] def state_space_dim(self): """Observation space is continuous; return None.""" return np.inf def state_space(self): """Observation space is continuous; return None.""" return np.inf def state_index(self, state): """Observation space is continuous; return None.""" return None def trajectory_from_states(self, states, features): return Trajectory(states, np.sum(features, axis=0)) def distance_between_trajectories(self, a, b): return None """ The proceeding code consists of domain-specific helper functions. No part of the Inquire framework should need to be modified to accommodate these functions. """ def approximate_surface_coverage( self, state: Union[list, np.ndarray] ) -> float: """Compute the approximate surface-area coverage.""" coords = np.array(state, copy=True) topping_diam = self._pizza_form["topping_diam"] # ID the toppings actually ON the viable surface via: # ||object - surface origin||_2: sq_sum = np.sqrt(coords[0, :] ** 2 + coords[1, :] ** 2) inds = np.argwhere(sq_sum <= self._viable_surface_radius)[:, 0] overlapping_area = 0 # If there's more than one topping, approximate their overlap: if coords.shape[1] > 1: xy_combos = np.array(list(combinations(coords[:, inds].T, 2))) x1 = xy_combos[:, 0, 0] x2 = xy_combos[:, 1, 0] y1 = xy_combos[:, 0, 1] y2 = xy_combos[:, 1, 1] xs = (x1 - x2) ** 2 ys = (y1 - y2) ** 2 topping_dists = np.sqrt(xs + ys) # Avoid division-by-zero errors: topping_dists = np.where( topping_dists == 0, 0.00001, topping_dists ) # Heuristically compute total overlap area: overlapping_area = np.where( topping_dists < topping_diam, self._area_per_topping * np.exp(-topping_dists), 0, ) overlapping_area = np.sum(overlapping_area) # Compute the coverage approximation: approx_absolute_coverage = ( self._area_per_topping * inds.shape[0] - overlapping_area ) coverage = approx_absolute_coverage / self._viable_surface_area return coverage def approximate_overlap_last( self, state: Union[list, np.ndarray] ) -> float: """Approximate area last topping overlaps others.""" coords = np.array(state, copy=True) # If there's more than one topping, approximate last topping's # overlap with each of the others: overlapping_area = 0 if coords.shape[1] > 1: # Vectorize the last topping for efficient operations: most_recent = ( coords[:, -1].reshape(2, 1).repeat(coords.shape[1], axis=1) ) dists = (most_recent - coords)[:, :-1] mags = np.sqrt((dists ** 2).sum(axis=0)) # Avoid division-by-zero errors: topping_dists = np.where(mags == 0, 0.00001, mags) # Heuristically compute total overlap area: overlapping_area = np.where( topping_dists < self._pizza_form["topping_diam"], self._area_per_topping * np.exp(-topping_dists), 0, ) overlapping_area = overlapping_area.sum() # return overlapping_area return -np.exp(-overlapping_area) def last_point_x_variance(self, state: Union[list, np.ndarray]) -> float: """Compute x variance of last point. Upper bound of discrete, uniform random variable is (b-a)**2 / 4 """ coords = np.array(state, copy=True) if coords.shape[1] <= 1: return 0 last_x = coords[0, -1].repeat(coords.shape[1]).reshape(1, -1) diffs = (last_x - coords[0, :])[0, :-1].reshape(1, -1) if diffs.shape[1] <= 1: var_x_to_last = np.sum(diffs ** 2) else: var_x_to_last = np.sum(diffs ** 2) / (diffs.shape[1] - 1) return var_x_to_last def last_point_y_variance(self, state: Union[list, np.ndarray]) -> float: """Compute y variance of last point.""" coords = np.array(state, copy=True) if coords.shape[1] <= 1: return 0 last_y = coords[1, -1].repeat(coords.shape[1]).reshape(1, -1) diffs = (last_y - coords[1, :])[0, :-1].reshape(1, -1) if diffs.shape[1] <= 1: var_y_to_last = np.sum(diffs ** 2) else: var_y_to_last = np.sum(diffs ** 2) / (diffs.shape[1] - 1) return var_y_to_last def markovian_magnitude(self, state: Union[list, np.ndarray]) -> float: """Compute magnitude between latest topping and one preceding it.""" coords = np.array(state, copy=True) if coords.shape[1] <= 1: return 0 x_dist = coords[0, -1] - coords[0, -2] y_dist = coords[1, -1] - coords[1, -2] mag = np.sqrt(x_dist ** 2 + y_dist ** 2) return mag def avg_magnitude_last_to_all( self, state: Union[list, np.ndarray] ) -> float: """Compute average magnitude between latest topping and all others.""" coords = np.array(state, copy=True) # If there are no toppings or just one, return 0: if coords.shape[1] <= 1: return 0 # Vectorize the last topping for efficient operations: most_recent = ( coords[:, -1].reshape(2, 1).repeat(coords.shape[1], axis=1) ) # Compute the distances; ignore the last distance which is the distance # from itself: dists = (most_recent - coords)[:, :-1] mags = np.sqrt((dists ** 2).sum(axis=0)) avg_mag = mags.sum() / mags.shape[0] return avg_mag """ The proceeding are Numba-optimized helper functions. No part of the Inquire framework should need to be modified to accommodate these functions. """ @jit(nopython=True) def generate_2D_points(radius: float, count: int) -> np.ndarray: """Uniformly sample points from a circle.""" pts = np.empty((2, count)) for i in range(count): r = radius * np.sqrt(np.random.uniform(0, 1)) theta = 2 * np.pi * np.random.uniform(0, 1) x = r * np.cos(theta) y = r * np.sin(theta) pts[:, i] = np.array([x, y]) return pts
[ "numpy.sum", "numpy.empty", "numpy.random.default_rng", "numpy.sin", "numpy.linalg.norm", "numpy.exp", "numpy.append", "numpy.linspace", "time.perf_counter", "itertools.combinations", "numpy.cos", "numpy.argwhere", "numpy.random.uniform", "numpy.zeros", "numpy.where", "numba.jit", "numpy.array", "pathlib.Path.cwd", "inquire.interactions.feedback.Trajectory", "numpy.sqrt" ]
[((15354, 15372), 'numba.jit', 'jit', ([], {'nopython': '(True)'}), '(nopython=True)\n', (15357, 15372), False, 'from numba import jit\n'), ((15497, 15517), 'numpy.empty', 'np.empty', (['(2, count)'], {}), '((2, count))\n', (15505, 15517), True, 'import numpy as np\n'), ((1407, 1440), 'numpy.random.default_rng', 'np.random.default_rng', (['self._seed'], {}), '(self._seed)\n', (1428, 1440), True, 'import numpy as np\n'), ((1926, 2021), 'numpy.linspace', 'np.linspace', (['(-self._viable_surface_radius)', 'self._viable_surface_radius', '(1000)'], {'endpoint': '(True)'}), '(-self._viable_surface_radius, self._viable_surface_radius, 1000,\n endpoint=True)\n', (1937, 2021), True, 'import numpy as np\n'), ((2112, 2157), 'numpy.array', 'np.array', (['self._x_coordinate_range'], {'copy': '(True)'}), '(self._x_coordinate_range, copy=True)\n', (2120, 2157), True, 'import numpy as np\n'), ((5987, 6006), 'time.perf_counter', 'time.perf_counter', ([], {}), '()\n', (6004, 6006), False, 'import time\n'), ((6026, 6058), 'numpy.array', 'np.array', (['start_state'], {'copy': '(True)'}), '(start_state, copy=True)\n', (6034, 6058), True, 'import numpy as np\n'), ((7189, 7229), 'inquire.interactions.feedback.Trajectory', 'Trajectory', (['best_toppings', 'best_features'], {}), '(best_toppings, best_features)\n', (7199, 7229), False, 'from inquire.interactions.feedback import Trajectory\n'), ((8805, 8851), 'numpy.append', 'np.append', (['current_state', 'next_topping'], {'axis': '(1)'}), '(current_state, next_topping, axis=1)\n', (8814, 8851), True, 'import numpy as np\n'), ((10168, 10194), 'numpy.array', 'np.array', (['state'], {'copy': '(True)'}), '(state, copy=True)\n', (10176, 10194), True, 'import numpy as np\n'), ((10371, 10417), 'numpy.sqrt', 'np.sqrt', (['(coords[0, :] ** 2 + coords[1, :] ** 2)'], {}), '(coords[0, :] ** 2 + coords[1, :] ** 2)\n', (10378, 10417), True, 'import numpy as np\n'), ((11838, 11864), 'numpy.array', 'np.array', (['state'], {'copy': '(True)'}), '(state, copy=True)\n', (11846, 11864), True, 'import numpy as np\n'), ((13055, 13081), 'numpy.array', 'np.array', (['state'], {'copy': '(True)'}), '(state, copy=True)\n', (13063, 13081), True, 'import numpy as np\n'), ((13605, 13631), 'numpy.array', 'np.array', (['state'], {'copy': '(True)'}), '(state, copy=True)\n', (13613, 13631), True, 'import numpy as np\n'), ((14182, 14208), 'numpy.array', 'np.array', (['state'], {'copy': '(True)'}), '(state, copy=True)\n', (14190, 14208), True, 'import numpy as np\n'), ((14371, 14405), 'numpy.sqrt', 'np.sqrt', (['(x_dist ** 2 + y_dist ** 2)'], {}), '(x_dist ** 2 + y_dist ** 2)\n', (14378, 14405), True, 'import numpy as np\n'), ((14619, 14645), 'numpy.array', 'np.array', (['state'], {'copy': '(True)'}), '(state, copy=True)\n', (14627, 14645), True, 'import numpy as np\n'), ((15731, 15747), 'numpy.array', 'np.array', (['[x, y]'], {}), '([x, y])\n', (15739, 15747), True, 'import numpy as np\n'), ((3415, 3427), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (3423, 3427), True, 'import numpy as np\n'), ((5487, 5510), 'numpy.linalg.norm', 'np.linalg.norm', (['weights'], {}), '(weights)\n', (5501, 5510), True, 'import numpy as np\n'), ((8016, 8039), 'numpy.zeros', 'np.zeros', (['(self.w_dim,)'], {}), '((self.w_dim,))\n', (8024, 8039), True, 'import numpy as np\n'), ((8113, 8139), 'numpy.array', 'np.array', (['state'], {'copy': '(True)'}), '(state, copy=True)\n', (8121, 8139), True, 'import numpy as np\n'), ((9703, 9727), 'numpy.sum', 'np.sum', (['features'], {'axis': '(0)'}), '(features, axis=0)\n', (9709, 9727), True, 'import numpy as np\n'), ((10433, 10483), 'numpy.argwhere', 'np.argwhere', (['(sq_sum <= self._viable_surface_radius)'], {}), '(sq_sum <= self._viable_surface_radius)\n', (10444, 10483), True, 'import numpy as np\n'), ((10934, 10950), 'numpy.sqrt', 'np.sqrt', (['(xs + ys)'], {}), '(xs + ys)\n', (10941, 10950), True, 'import numpy as np\n'), ((11024, 11074), 'numpy.where', 'np.where', (['(topping_dists == 0)', '(1e-05)', 'topping_dists'], {}), '(topping_dists == 0, 1e-05, topping_dists)\n', (11032, 11074), True, 'import numpy as np\n'), ((11379, 11403), 'numpy.sum', 'np.sum', (['overlapping_area'], {}), '(overlapping_area)\n', (11385, 11403), True, 'import numpy as np\n'), ((12402, 12434), 'numpy.where', 'np.where', (['(mags == 0)', '(1e-05)', 'mags'], {}), '(mags == 0, 1e-05, mags)\n', (12410, 12434), True, 'import numpy as np\n'), ((12802, 12827), 'numpy.exp', 'np.exp', (['(-overlapping_area)'], {}), '(-overlapping_area)\n', (12808, 12827), True, 'import numpy as np\n'), ((13329, 13347), 'numpy.sum', 'np.sum', (['(diffs ** 2)'], {}), '(diffs ** 2)\n', (13335, 13347), True, 'import numpy as np\n'), ((13879, 13897), 'numpy.sum', 'np.sum', (['(diffs ** 2)'], {}), '(diffs ** 2)\n', (13885, 13897), True, 'import numpy as np\n'), ((15627, 15650), 'numpy.random.uniform', 'np.random.uniform', (['(0)', '(1)'], {}), '(0, 1)\n', (15644, 15650), True, 'import numpy as np\n'), ((15667, 15680), 'numpy.cos', 'np.cos', (['theta'], {}), '(theta)\n', (15673, 15680), True, 'import numpy as np\n'), ((15697, 15710), 'numpy.sin', 'np.sin', (['theta'], {}), '(theta)\n', (15703, 15710), True, 'import numpy as np\n'), ((707, 717), 'pathlib.Path.cwd', 'Path.cwd', ([], {}), '()\n', (715, 717), False, 'from pathlib import Path\n'), ((7278, 7297), 'time.perf_counter', 'time.perf_counter', ([], {}), '()\n', (7295, 7297), False, 'import time\n'), ((8742, 8769), 'numpy.array', 'np.array', (['action'], {'copy': '(True)'}), '(action, copy=True)\n', (8750, 8769), True, 'import numpy as np\n'), ((13390, 13408), 'numpy.sum', 'np.sum', (['(diffs ** 2)'], {}), '(diffs ** 2)\n', (13396, 13408), True, 'import numpy as np\n'), ((13940, 13958), 'numpy.sum', 'np.sum', (['(diffs ** 2)'], {}), '(diffs ** 2)\n', (13946, 13958), True, 'import numpy as np\n'), ((15574, 15597), 'numpy.random.uniform', 'np.random.uniform', (['(0)', '(1)'], {}), '(0, 1)\n', (15591, 15597), True, 'import numpy as np\n'), ((7049, 7083), 'numpy.array', 'np.array', (['temp_toppings'], {'copy': '(True)'}), '(temp_toppings, copy=True)\n', (7057, 7083), True, 'import numpy as np\n'), ((7120, 7154), 'numpy.array', 'np.array', (['temp_features'], {'copy': '(True)'}), '(temp_features, copy=True)\n', (7128, 7154), True, 'import numpy as np\n'), ((10661, 10695), 'itertools.combinations', 'combinations', (['coords[:, inds].T', '(2)'], {}), '(coords[:, inds].T, 2)\n', (10673, 10695), False, 'from itertools import combinations\n'), ((11291, 11313), 'numpy.exp', 'np.exp', (['(-topping_dists)'], {}), '(-topping_dists)\n', (11297, 11313), True, 'import numpy as np\n'), ((12641, 12663), 'numpy.exp', 'np.exp', (['(-topping_dists)'], {}), '(-topping_dists)\n', (12647, 12663), True, 'import numpy as np\n')]
"""grid_world.py A simple grid world environment. Edges of the map are treated like obstacles Map must be a image file whose values represent free (255, white), occupied (0, black). """ from __future__ import print_function, absolute_import, division import cv2 import numpy as np from bc_exploration.mapping.costmap import Costmap from bc_exploration.utilities.util import wrap_angles, compute_connected_pixels from bc_exploration.utilities.util import xy_to_rc class GridWorld: """ A simple grid world environment. Edges of the map are treated like obstacles Map must be a image file whose values represent free (255, white), occupied (0, black). """ def __init__(self, map_filename, map_resolution, sensor, footprint, start_state=None, render_size=(500, 500), thicken_obstacles=True): """ Creates an interactive grid world environment structured similar to open ai gym. Allows for moving, sensing, and visualizing within the space. Map loaded is based off the map_filename. :param map_filename str: path of image file whose values represent free (255, white), occupied (0, black). :param map_resolution float: resolution of which to represent the map :param sensor Sensor: sensor to use to sense the environment :param footprint Footprint: footprint of the robot :param start_state bool: if None, will randomly sample a free space point as the starting point else it must be [row, column] of the position you want the robot to start. it must be a valid location (free space and footprint must fit) :param render_size Tuple(int): size of which to render the map (for visualization env.render() ) :param thicken_obstacles bool: thicken the obstacles in the map by 1 pixel, to avoid 1 pixel thick walls """ self.footprint = footprint self.footprint_no_inflation = footprint.no_inflation() self.map_resolution = map_resolution self.render_size = render_size assert render_size.shape[0] == 2 if isinstance(render_size, np.ndarray) else len(render_size) == 2 self.state = None self.map = None self.truth_free_coords = None self._load_map(map_filename, map_resolution, thicken_obstacles=thicken_obstacles) self.start_state = np.array(start_state).astype(np.float) \ if start_state is not None else self._get_random_start_state() assert self.start_state.shape[0] == 3 self.sensor = sensor assert self.map is not None self.sensor.set_map(occupancy_map=self.map) self.reset() assert self._is_state_valid(self.start_state) def _get_random_start_state(self): """ Samples a random valid state from the map :return array(3)[float]: state [x, y, theta] of the robot """ valid_points = self.map_resolution * np.argwhere(self.map.data == Costmap.FREE)[:, ::-1] choice = np.random.randint(valid_points.shape[0]) valid = False while not valid: choice = np.random.randint(valid_points.shape[0]) valid = self._is_state_valid(np.concatenate((valid_points[choice], [0]))) # todo add random angle return np.concatenate((valid_points[choice], [0])).astype(np.float) def _is_state_valid(self, state, use_inflation=True): """ Make sure state is not out of bounds or on an obstacle (footprint check) :param state array(3)[float]: [x, y, theta], the position/orientation of the robot :param use_inflation bool: whether to use the inflated footprint to collision check, or the normal footprint. usually the environment will need use the actual footprint of the robot (because thats the physical limitation we want to simulate) :return bool: whether it is valid or not """ return 0 <= state[0] < self.map.get_size()[0] and 0 <= state[1] < self.map.get_size()[1] \ and not (self.footprint.check_for_collision(state=state, occupancy_map=self.map) if use_inflation else self.footprint_no_inflation.check_for_collision(state=state, occupancy_map=self.map)) def _load_map(self, filename, map_resolution, thicken_obstacles=True): """ Loads map from file into costmap object :param filename str: location of the map file :param map_resolution float: desired resolution of the loaded map :param thicken_obstacles bool: thicken the obstacles in the map by 1 pixel, to avoid 1 pixel thick walls """ map_data = cv2.imread(filename) assert map_data is not None and "map file not able to be loaded. Does the file exist?" map_data = cv2.cvtColor(map_data, cv2.COLOR_RGB2GRAY) map_data = map_data.astype(np.uint8) assert np.max(map_data) == 255 if thicken_obstacles: occupied_coords = np.argwhere(map_data == Costmap.OCCUPIED) occupied_mask = np.zeros_like(map_data) occupied_mask[occupied_coords[:, 0], occupied_coords[:, 1]] = 1 occupied_mask = cv2.dilate(occupied_mask, cv2.getStructuringElement(cv2.MORPH_CROSS, (3, 3))) occupied_coords = np.argwhere(occupied_mask == 1) map_data[occupied_coords[:, 0], occupied_coords[:, 1]] = Costmap.OCCUPIED self.map = Costmap(data=map_data, resolution=map_resolution, origin=[0., 0.]) def compare_maps(self, occupancy_map): """ Does a comparison of the ground truth map with the input map, and will return a percentage completed :param occupancy_map Costmap: input map to be compared with ground truth :return float: percentage covered of the input map to the ground truth map """ if self.truth_free_coords is None: start_state_px = xy_to_rc(self.start_state, self.map) self.truth_free_coords = compute_connected_pixels(start_state_px, self.map.data) free_coords = np.argwhere(occupancy_map.data == Costmap.FREE) return free_coords.shape[0] / float(self.truth_free_coords.shape[0]) def step(self, desired_state): """ Execute the given action with the robot in the environment, return the next robot position, and the output of sensor.measure() (sensor data) :param desired_state array(3)[float]: desired next state of the robot :return array(3)[float]: new_state (new robot position), sensor_data (output from sensor) """ new_state = np.array(desired_state, dtype=np.float) new_state[2] = wrap_angles(desired_state[2]) # # todo maybe keep angle of desired state if not self._is_state_valid(new_state + self.start_state, use_inflation=False): new_state = self.state.copy() # compute sensor_data measure_state = new_state.copy() measure_state[:2] += self.start_state[:2] sensor_data = self.sensor.measure(measure_state) # set state self.state = new_state return new_state.copy(), sensor_data def reset(self): """ Resets the robot to the starting state in the environment :return array(3)[float]: robot position, sensor data from start state """ self.state = np.array((0, 0, self.start_state[2])) sensor_data = self.sensor.measure(self.start_state) return self.state.copy(), sensor_data def render(self, wait_key=0): """ Renders the environment and the robots position :param wait_key int: the opencv waitKey arg """ # convert to colored image map_vis = cv2.cvtColor(self.map.data.copy(), cv2.COLOR_GRAY2BGR) state_px = xy_to_rc(self.state + self.start_state, self.map)[:2].astype(np.int) map_vis[state_px[0], state_px[1]] = [127, 122, 10] # # todo figure out programmatic way to pick circle size (that works well) # cv2.circle(map_vis, tuple(self.state[:2][::-1].astype(int)), 1, [127, 122, 10], thickness=-1) # resize map map_vis = cv2.resize(map_vis, tuple(self.render_size), interpolation=cv2.INTER_NEAREST) # visualize map cv2.namedWindow('map', cv2.WINDOW_GUI_NORMAL) cv2.imshow('map', map_vis) cv2.resizeWindow('map', *self.render_size) cv2.waitKey(wait_key) def get_sensor(self): """ Gets the sensor object :return Sensor: the sensor used by the grid world """ return self.sensor def get_map_shape(self): """ Returns the shape of the map :return Tuple(int): map shape """ return self.map.get_shape() def get_map_size(self): """ Returns the size of the map (x, y) in meters :return Tuple(float): map size (meters) """ return self.map.get_size() def get_map_resolution(self): """ Returns the resolution of the map :return float: resolution """ return self.map_resolution def __del__(self): """ Destructor, delete opencv windows """ cv2.destroyAllWindows()
[ "numpy.zeros_like", "bc_exploration.utilities.util.xy_to_rc", "numpy.concatenate", "cv2.cvtColor", "cv2.waitKey", "cv2.destroyAllWindows", "cv2.getStructuringElement", "cv2.imread", "numpy.max", "numpy.random.randint", "numpy.array", "bc_exploration.utilities.util.compute_connected_pixels", "numpy.argwhere", "cv2.resizeWindow", "cv2.imshow", "bc_exploration.mapping.costmap.Costmap", "cv2.namedWindow", "bc_exploration.utilities.util.wrap_angles" ]
[((3156, 3196), 'numpy.random.randint', 'np.random.randint', (['valid_points.shape[0]'], {}), '(valid_points.shape[0])\n', (3173, 3196), True, 'import numpy as np\n'), ((4845, 4865), 'cv2.imread', 'cv2.imread', (['filename'], {}), '(filename)\n', (4855, 4865), False, 'import cv2\n'), ((4980, 5022), 'cv2.cvtColor', 'cv2.cvtColor', (['map_data', 'cv2.COLOR_RGB2GRAY'], {}), '(map_data, cv2.COLOR_RGB2GRAY)\n', (4992, 5022), False, 'import cv2\n'), ((5612, 5680), 'bc_exploration.mapping.costmap.Costmap', 'Costmap', ([], {'data': 'map_data', 'resolution': 'map_resolution', 'origin': '[0.0, 0.0]'}), '(data=map_data, resolution=map_resolution, origin=[0.0, 0.0])\n', (5619, 5680), False, 'from bc_exploration.mapping.costmap import Costmap\n'), ((6253, 6300), 'numpy.argwhere', 'np.argwhere', (['(occupancy_map.data == Costmap.FREE)'], {}), '(occupancy_map.data == Costmap.FREE)\n', (6264, 6300), True, 'import numpy as np\n'), ((6791, 6830), 'numpy.array', 'np.array', (['desired_state'], {'dtype': 'np.float'}), '(desired_state, dtype=np.float)\n', (6799, 6830), True, 'import numpy as np\n'), ((6854, 6883), 'bc_exploration.utilities.util.wrap_angles', 'wrap_angles', (['desired_state[2]'], {}), '(desired_state[2])\n', (6865, 6883), False, 'from bc_exploration.utilities.util import wrap_angles, compute_connected_pixels\n'), ((7554, 7591), 'numpy.array', 'np.array', (['(0, 0, self.start_state[2])'], {}), '((0, 0, self.start_state[2]))\n', (7562, 7591), True, 'import numpy as np\n'), ((8459, 8504), 'cv2.namedWindow', 'cv2.namedWindow', (['"""map"""', 'cv2.WINDOW_GUI_NORMAL'], {}), "('map', cv2.WINDOW_GUI_NORMAL)\n", (8474, 8504), False, 'import cv2\n'), ((8513, 8539), 'cv2.imshow', 'cv2.imshow', (['"""map"""', 'map_vis'], {}), "('map', map_vis)\n", (8523, 8539), False, 'import cv2\n'), ((8548, 8590), 'cv2.resizeWindow', 'cv2.resizeWindow', (['"""map"""', '*self.render_size'], {}), "('map', *self.render_size)\n", (8564, 8590), False, 'import cv2\n'), ((8599, 8620), 'cv2.waitKey', 'cv2.waitKey', (['wait_key'], {}), '(wait_key)\n', (8610, 8620), False, 'import cv2\n'), ((9410, 9433), 'cv2.destroyAllWindows', 'cv2.destroyAllWindows', ([], {}), '()\n', (9431, 9433), False, 'import cv2\n'), ((3266, 3306), 'numpy.random.randint', 'np.random.randint', (['valid_points.shape[0]'], {}), '(valid_points.shape[0])\n', (3283, 3306), True, 'import numpy as np\n'), ((5083, 5099), 'numpy.max', 'np.max', (['map_data'], {}), '(map_data)\n', (5089, 5099), True, 'import numpy as np\n'), ((5168, 5209), 'numpy.argwhere', 'np.argwhere', (['(map_data == Costmap.OCCUPIED)'], {}), '(map_data == Costmap.OCCUPIED)\n', (5179, 5209), True, 'import numpy as np\n'), ((5238, 5261), 'numpy.zeros_like', 'np.zeros_like', (['map_data'], {}), '(map_data)\n', (5251, 5261), True, 'import numpy as np\n'), ((5474, 5505), 'numpy.argwhere', 'np.argwhere', (['(occupied_mask == 1)'], {}), '(occupied_mask == 1)\n', (5485, 5505), True, 'import numpy as np\n'), ((6100, 6136), 'bc_exploration.utilities.util.xy_to_rc', 'xy_to_rc', (['self.start_state', 'self.map'], {}), '(self.start_state, self.map)\n', (6108, 6136), False, 'from bc_exploration.utilities.util import xy_to_rc\n'), ((6174, 6229), 'bc_exploration.utilities.util.compute_connected_pixels', 'compute_connected_pixels', (['start_state_px', 'self.map.data'], {}), '(start_state_px, self.map.data)\n', (6198, 6229), False, 'from bc_exploration.utilities.util import wrap_angles, compute_connected_pixels\n'), ((3087, 3129), 'numpy.argwhere', 'np.argwhere', (['(self.map.data == Costmap.FREE)'], {}), '(self.map.data == Costmap.FREE)\n', (3098, 3129), True, 'import numpy as np\n'), ((3348, 3391), 'numpy.concatenate', 'np.concatenate', (['(valid_points[choice], [0])'], {}), '((valid_points[choice], [0]))\n', (3362, 3391), True, 'import numpy as np\n'), ((3441, 3484), 'numpy.concatenate', 'np.concatenate', (['(valid_points[choice], [0])'], {}), '((valid_points[choice], [0]))\n', (3455, 3484), True, 'import numpy as np\n'), ((5392, 5442), 'cv2.getStructuringElement', 'cv2.getStructuringElement', (['cv2.MORPH_CROSS', '(3, 3)'], {}), '(cv2.MORPH_CROSS, (3, 3))\n', (5417, 5442), False, 'import cv2\n'), ((2506, 2527), 'numpy.array', 'np.array', (['start_state'], {}), '(start_state)\n', (2514, 2527), True, 'import numpy as np\n'), ((7993, 8042), 'bc_exploration.utilities.util.xy_to_rc', 'xy_to_rc', (['(self.state + self.start_state)', 'self.map'], {}), '(self.state + self.start_state, self.map)\n', (8001, 8042), False, 'from bc_exploration.utilities.util import xy_to_rc\n')]
from __future__ import print_function import save_novel import tensorflow as tf import os import sys import random import numpy as np import re import MeCab from glob import glob from keras.optimizers import RMSprop from keras.layers import LSTM from keras.layers import Dense from keras.models import Sequential from keras.callbacks import LambdaCallback physical_devices = tf.config.experimental.list_physical_devices('GPU') if len(physical_devices) > 0: for k in range(len(physical_devices)): tf.config.experimental.set_memory_growth(physical_devices[k], True) print('memory growth:', tf.config.experimental.get_memory_growth( physical_devices[k])) else: print("Not enough GPU hardware devices available") # ---------------------------------------------------------------- tagger = MeCab.Tagger("-Owakati") def make_wakati(sentence): sentence = tagger.parse(sentence) sentence = re.sub(r'[0-90-9a-zA-Za-zA-Z]+', " ", sentence) sentence = re.sub( r'[\._-―─!@#$%^&\-‐|\\*\“()_■×+α※÷⇒—●★☆〇◎◆▼◇△□(:〜~+=)/*&^%$#@!~`){}[]…\[\]\"\'\”\’:;<>?<>〔〕〈〉?、。・,\./『』【】「」→←○《》≪≫\n\u3000]+', "", sentence) wakati = sentence.split(" ") wakati = list(filter(("").__ne__, wakati)) return wakati bodies = '' url = input( 'Enter the URL of the novel.\n(ex:https://ncode.syosetu.com/n2267be)\n>') id = url[url.strip('/').rfind('/'):len(url)] if not os.path.exists(save_novel.save_folder+id): print('Path does not exist.') exit() for file in glob(save_novel.save_folder+id+'/*.txt'): with open(file, mode="r", encoding='utf-8') as f: bodies += f.read() text = make_wakati(bodies) print(len(text)) text = text[0:min(len(text), 25000)] chars = text count = 0 char_indices = {} indices_char = {} for word in chars: if not word in char_indices: char_indices[word] = count count += 1 indices_char = dict([(value, key) for (key, value) in char_indices.items()]) maxlen = 5 step = 1 sentences = [] next_chars = [] for i in range(0, len(text) - maxlen, step): sentences.append(text[i: i + maxlen]) next_chars.append(text[i + maxlen]) print('nb sequences:', len(sentences)) print('Vectorization...') x = np.zeros((len(sentences), maxlen, len(chars)), dtype=np.bool) y = np.zeros((len(sentences), len(chars)), dtype=np.bool) for i, sentence in enumerate(sentences): for t, char in enumerate(sentence): x[i, t, char_indices[char]] = 1 y[i, char_indices[next_chars[i]]] = 1 print('Build model...') model = Sequential() model.add(LSTM(128, input_shape=(maxlen, len(chars)))) model.add(Dense(len(chars), activation='softmax')) optimizer = RMSprop(lr=0.01) model.compile(loss='categorical_crossentropy', optimizer=optimizer) def sample(preds, temperature=1.0): preds = np.asarray(preds).astype('float64') preds = np.log(preds) / temperature exp_preds = np.exp(preds) preds = exp_preds / np.sum(exp_preds) probas = np.random.multinomial(1, preds, 1) return np.argmax(probas) def on_epoch_end(epoch, _): print() print('----- Generating text after Epoch: %d' % epoch) start_index = random.randint(0, len(text) - maxlen - 1) start_index = 0 for diversity in [0.2]: print('----- diversity:', diversity) generated = '' sentence = text[start_index: start_index + maxlen] generated += "".join(sentence) print(sentence) print('----- Generating with seed: "' + "".join(sentence) + '"') sys.stdout.write(generated) for i in range(400): x_pred = np.zeros((1, maxlen, len(chars))) for t, char in enumerate(sentence): x_pred[0, t, char_indices[char]] = 1. preds = model.predict(x_pred, verbose=0)[0] next_index = sample(preds, diversity) next_char = indices_char[next_index] generated += next_char sentence = sentence[1:] sentence.append(next_char) sys.stdout.write(next_char) sys.stdout.flush() print() print_callback = LambdaCallback(on_epoch_end=on_epoch_end) model.summary() model.fit(x, y, batch_size=128, epochs=30, callbacks=[print_callback])
[ "sys.stdout.write", "numpy.sum", "numpy.log", "tensorflow.config.experimental.get_memory_growth", "numpy.argmax", "numpy.random.multinomial", "numpy.asarray", "os.path.exists", "tensorflow.config.experimental.set_memory_growth", "keras.callbacks.LambdaCallback", "MeCab.Tagger", "numpy.exp", "sys.stdout.flush", "glob.glob", "keras.models.Sequential", "keras.optimizers.RMSprop", "tensorflow.config.experimental.list_physical_devices", "re.sub" ]
[((375, 426), 'tensorflow.config.experimental.list_physical_devices', 'tf.config.experimental.list_physical_devices', (['"""GPU"""'], {}), "('GPU')\n", (419, 426), True, 'import tensorflow as tf\n'), ((821, 845), 'MeCab.Tagger', 'MeCab.Tagger', (['"""-Owakati"""'], {}), "('-Owakati')\n", (833, 845), False, 'import MeCab\n'), ((1503, 1547), 'glob.glob', 'glob', (["(save_novel.save_folder + id + '/*.txt')"], {}), "(save_novel.save_folder + id + '/*.txt')\n", (1507, 1547), False, 'from glob import glob\n'), ((2514, 2526), 'keras.models.Sequential', 'Sequential', ([], {}), '()\n', (2524, 2526), False, 'from keras.models import Sequential\n'), ((2646, 2662), 'keras.optimizers.RMSprop', 'RMSprop', ([], {'lr': '(0.01)'}), '(lr=0.01)\n', (2653, 2662), False, 'from keras.optimizers import RMSprop\n'), ((4071, 4112), 'keras.callbacks.LambdaCallback', 'LambdaCallback', ([], {'on_epoch_end': 'on_epoch_end'}), '(on_epoch_end=on_epoch_end)\n', (4085, 4112), False, 'from keras.callbacks import LambdaCallback\n'), ((928, 974), 're.sub', 're.sub', (['"""[0-90-9a-zA-Za-zA-Z]+"""', '""" """', 'sentence'], {}), "('[0-90-9a-zA-Za-zA-Z]+', ' ', sentence)\n", (934, 974), False, 'import re\n'), ((991, 1162), 're.sub', 're.sub', (['"""[\\\\._-―─!@#$%^&\\\\-‐|\\\\\\\\*\\\\“()_■×+α※÷⇒—●★☆〇◎◆▼◇△□(:〜~+=)/*&^%$#@!~`){}[]…\\\\[\\\\]\\\\"\\\\\'\\\\”\\\\’:;<>?<>〔〕〈〉?、。・,\\\\./『』【】「」→←○《》≪≫\\\\n\\\\u3000]+"""', '""""""', 'sentence'], {}), '(\n \'[\\\\._-―─!@#$%^&\\\\-‐|\\\\\\\\*\\\\“()_■×+α※÷⇒—●★☆〇◎◆▼◇△□(:〜~+=)/*&^%$#@!~`){}[]…\\\\[\\\\]\\\\"\\\\\\\'\\\\”\\\\’:;<>?<>〔〕〈〉?、。・,\\\\./『』【】「」→←○《》≪≫\\\\n\\\\u3000]+\'\n , \'\', sentence)\n', (997, 1162), False, 'import re\n'), ((1403, 1446), 'os.path.exists', 'os.path.exists', (['(save_novel.save_folder + id)'], {}), '(save_novel.save_folder + id)\n', (1417, 1446), False, 'import os\n'), ((2873, 2886), 'numpy.exp', 'np.exp', (['preds'], {}), '(preds)\n', (2879, 2886), True, 'import numpy as np\n'), ((2942, 2976), 'numpy.random.multinomial', 'np.random.multinomial', (['(1)', 'preds', '(1)'], {}), '(1, preds, 1)\n', (2963, 2976), True, 'import numpy as np\n'), ((2988, 3005), 'numpy.argmax', 'np.argmax', (['probas'], {}), '(probas)\n', (2997, 3005), True, 'import numpy as np\n'), ((508, 575), 'tensorflow.config.experimental.set_memory_growth', 'tf.config.experimental.set_memory_growth', (['physical_devices[k]', '(True)'], {}), '(physical_devices[k], True)\n', (548, 575), True, 'import tensorflow as tf\n'), ((2829, 2842), 'numpy.log', 'np.log', (['preds'], {}), '(preds)\n', (2835, 2842), True, 'import numpy as np\n'), ((2911, 2928), 'numpy.sum', 'np.sum', (['exp_preds'], {}), '(exp_preds)\n', (2917, 2928), True, 'import numpy as np\n'), ((3486, 3513), 'sys.stdout.write', 'sys.stdout.write', (['generated'], {}), '(generated)\n', (3502, 3513), False, 'import sys\n'), ((608, 669), 'tensorflow.config.experimental.get_memory_growth', 'tf.config.experimental.get_memory_growth', (['physical_devices[k]'], {}), '(physical_devices[k])\n', (648, 669), True, 'import tensorflow as tf\n'), ((2781, 2798), 'numpy.asarray', 'np.asarray', (['preds'], {}), '(preds)\n', (2791, 2798), True, 'import numpy as np\n'), ((3977, 4004), 'sys.stdout.write', 'sys.stdout.write', (['next_char'], {}), '(next_char)\n', (3993, 4004), False, 'import sys\n'), ((4017, 4035), 'sys.stdout.flush', 'sys.stdout.flush', ([], {}), '()\n', (4033, 4035), False, 'import sys\n')]
import en_core_web_lg import json import pickle import numpy as np import rdflib class FoodEmbeddingSims: def run(self, *, spacy_savefile = '../data/out/spacy_ing_sim.pkl', w2v_savefile = '../data/out/w2v_ing_sim.pkl', substitution_data_file = '../data/in/foodsubs_data.json', w2v_file = '../data/in/r1m_word2vec/vocab.bin', food_link_files = ['../data/in/foodon-links-1.ttl']): g = rdflib.Graph() for file in food_link_files: g.parse(file, format='ttl') food_to_foodon = dict() unique_foodon = set() for subj, obj in g.subject_objects(predicate=rdflib.URIRef('http://idea.rpi.edu/heals/kb/equivalentFoodOnClass')): food_to_foodon[subj] = obj unique_foodon.add(obj) relevant_foods = set() with open(substitution_data_file, 'r') as f: scraped_subs_tups = json.load(f) for i in range(len(scraped_subs_tups)): scraped_subs_tups[i] = [rdflib.URIRef(scraped_subs_tups[i][0]), rdflib.URIRef(scraped_subs_tups[i][1])] if scraped_subs_tups[i][0] in food_to_foodon.keys(): relevant_foods.add(scraped_subs_tups[i][0]) if scraped_subs_tups[i][1] in food_to_foodon.keys(): relevant_foods.add(scraped_subs_tups[i][1]) print('relevant foods: ', len(relevant_foods)) print('ingredient names: ', len(food_to_foodon.keys())) print('foodon ingredients: ', len(unique_foodon)) def l2_norm(mat): return np.sqrt(np.sum(np.multiply(mat, mat), axis=1)) ###### SPACY ############### ############ print("starting spacy") nlp = en_core_web_lg.load() ing_to_vec = np.zeros(shape=(len(relevant_foods), 300)) print("getting vectors") ing_to_index = dict() ing_index = 0 use_ings = set() for fromt_ing in relevant_foods:#food_to_foodon.keys(): ing = fromt_ing[44:] ing_replaced = ing.replace("%20", " ") vec_parts = [] doskip = False for token in nlp(ing_replaced): if np.sum(token.vector) == 0 or np.sum(token.vector) is np.nan: print('ignoring ', ing) doskip = True vec_parts.append(token.vector) if doskip: continue ing_to_index[fromt_ing] = ing_index ing_to_vec[ing_index, :] = np.mean(vec_parts, axis=0).reshape(1, -1) ing_index += 1 use_ings.add(fromt_ing) if ing_index%1000 == 0: print(ing_index) l2n = l2_norm(ing_to_vec) print('getting sims for ', len(use_ings), ' ingreds') vec_ing_sim = dict() for ing in use_ings: index_1 = ing_to_index[ing] foodon_ing1 = food_to_foodon[ing] cosine_sim = np.dot(ing_to_vec[index_1].reshape(1, -1), ing_to_vec.T) / (l2_norm(ing_to_vec[index_1, :].reshape(1, -1))*(l2n)) res_dict = dict() dist_list = [] for ing2 in use_ings: index_2 = ing_to_index[ing2] foodon_ing2 = food_to_foodon[ing2] if ing == ing2: res_dict[ing2] = 1 elif ing2 in vec_ing_sim.keys(): res_dict[ing2] = vec_ing_sim[ing2][ing] else: sim = cosine_sim[0, index_2] res_dict[ing2] = sim vec_ing_sim[ing] = res_dict if len(vec_ing_sim.keys())%100 == 0: print(len(vec_ing_sim.keys())) print('finished setting up spacy sims, saving') with open(spacy_savefile, 'wb') as f: pickle.dump(vec_ing_sim, f) from gensim.models import KeyedVectors print("starting w2v") w2v_model = KeyedVectors.load_word2vec_format(w2v_file, binary=True) ing_to_vec = np.zeros(shape=(len(relevant_foods), 300)) print("getting vectors") ing_to_index = dict() ing_index = 0 use_ings = set() for fromt_ing in relevant_foods:#food_to_foodon.keys(): ing = fromt_ing[44:] ing_replaced = ing.replace("%20", "_") if ing_replaced in w2v_model.vocab: ing_to_vec[ing_index, :] = w2v_model[ing_replaced].reshape(1, -1) else: if ing_replaced.lower() in w2v_model.vocab: ing_to_vec[ing_index, :] = w2v_model[ing_replaced.lower()].reshape(1, -1) elif ing_replaced[0].upper()+ing_replaced[1:] in w2v_model.vocab: ing_to_vec[ing_index, :] = w2v_model[ing_replaced[0].upper()+ing_replaced[1:]].reshape(1, -1) else: vec_parts = [] ing_parts = ing_replaced.split("_") doskip = False for ing_part in ing_parts: if ing_part in w2v_model.vocab: vec_parts.append(w2v_model[ing_part]) else: if ing_part.lower() in w2v_model.vocab: vec_parts.append(w2v_model[ing_part.lower()]) #print(ing_part, " in ", ing, "! lower") elif ing_part[0].upper()+ing_part[1:] in w2v_model.vocab: vec_parts.append(w2v_model[ing_part[0].upper()+ing_part[1:]]) else: print('ignoring ', fromt_ing) doskip = True continue if doskip: continue if len(vec_parts) != 0: vec = np.array(vec_parts) vec = np.mean(vec_parts, axis=0) ing_to_vec[ing_index, :] = vec.reshape(1, -1) ing_to_index[fromt_ing] = ing_index ing_index += 1 use_ings.add(fromt_ing) if ing_index%1000 == 0: print(ing_index) l2n = l2_norm(ing_to_vec) print('getting sims for ', len(use_ings), ' ings') vec_ing_sim = dict() for ing in use_ings: index_1 = ing_to_index[ing] foodon_ing1 = food_to_foodon[ing] cosine_sim = np.dot(ing_to_vec[index_1].reshape(1, -1), ing_to_vec.T) / (l2_norm(ing_to_vec[index_1, :].reshape(1, -1))*(l2n)) res_dict = dict() dist_list = [] for ing2 in use_ings: index_2 = ing_to_index[ing2] foodon_ing2 = food_to_foodon[ing2] if ing == ing2: res_dict[ing2] = 1 elif ing2 in vec_ing_sim.keys(): res_dict[ing2] = vec_ing_sim[ing2][ing] else: sim = cosine_sim[0, index_2] res_dict[ing2] = sim vec_ing_sim[ing] = res_dict if len(vec_ing_sim.keys())%100 == 0: print(len(vec_ing_sim.keys())) print('finished setting up w2v sims, saving') with open(w2v_savefile, 'wb') as f: pickle.dump(vec_ing_sim, f)
[ "pickle.dump", "rdflib.Graph", "json.load", "numpy.multiply", "numpy.sum", "rdflib.URIRef", "en_core_web_lg.load", "numpy.mean", "numpy.array", "gensim.models.KeyedVectors.load_word2vec_format" ]
[((459, 473), 'rdflib.Graph', 'rdflib.Graph', ([], {}), '()\n', (471, 473), False, 'import rdflib\n'), ((1741, 1762), 'en_core_web_lg.load', 'en_core_web_lg.load', ([], {}), '()\n', (1760, 1762), False, 'import en_core_web_lg\n'), ((3939, 3995), 'gensim.models.KeyedVectors.load_word2vec_format', 'KeyedVectors.load_word2vec_format', (['w2v_file'], {'binary': '(True)'}), '(w2v_file, binary=True)\n', (3972, 3995), False, 'from gensim.models import KeyedVectors\n'), ((928, 940), 'json.load', 'json.load', (['f'], {}), '(f)\n', (937, 940), False, 'import json\n'), ((3812, 3839), 'pickle.dump', 'pickle.dump', (['vec_ing_sim', 'f'], {}), '(vec_ing_sim, f)\n', (3823, 3839), False, 'import pickle\n'), ((7317, 7344), 'pickle.dump', 'pickle.dump', (['vec_ing_sim', 'f'], {}), '(vec_ing_sim, f)\n', (7328, 7344), False, 'import pickle\n'), ((666, 733), 'rdflib.URIRef', 'rdflib.URIRef', (['"""http://idea.rpi.edu/heals/kb/equivalentFoodOnClass"""'], {}), "('http://idea.rpi.edu/heals/kb/equivalentFoodOnClass')\n", (679, 733), False, 'import rdflib\n'), ((1025, 1063), 'rdflib.URIRef', 'rdflib.URIRef', (['scraped_subs_tups[i][0]'], {}), '(scraped_subs_tups[i][0])\n', (1038, 1063), False, 'import rdflib\n'), ((1065, 1103), 'rdflib.URIRef', 'rdflib.URIRef', (['scraped_subs_tups[i][1]'], {}), '(scraped_subs_tups[i][1])\n', (1078, 1103), False, 'import rdflib\n'), ((1596, 1617), 'numpy.multiply', 'np.multiply', (['mat', 'mat'], {}), '(mat, mat)\n', (1607, 1617), True, 'import numpy as np\n'), ((2525, 2551), 'numpy.mean', 'np.mean', (['vec_parts'], {'axis': '(0)'}), '(vec_parts, axis=0)\n', (2532, 2551), True, 'import numpy as np\n'), ((2203, 2223), 'numpy.sum', 'np.sum', (['token.vector'], {}), '(token.vector)\n', (2209, 2223), True, 'import numpy as np\n'), ((2232, 2252), 'numpy.sum', 'np.sum', (['token.vector'], {}), '(token.vector)\n', (2238, 2252), True, 'import numpy as np\n'), ((5884, 5903), 'numpy.array', 'np.array', (['vec_parts'], {}), '(vec_parts)\n', (5892, 5903), True, 'import numpy as np\n'), ((5934, 5960), 'numpy.mean', 'np.mean', (['vec_parts'], {'axis': '(0)'}), '(vec_parts, axis=0)\n', (5941, 5960), True, 'import numpy as np\n')]
import os from numpy.testing import assert_allclose, assert_equal from astropy.io import fits import shutil import numpy as np def spectrum_answer_testing(spec, filename, answer_store, answer_dir): testfile = os.path.join(answer_dir, filename) if answer_store: spec.write_h5_file(testfile, overwrite=True) else: answer_spec = type(spec).from_file(testfile) assert_allclose(answer_spec.emid.value, spec.emid.value) assert_allclose(answer_spec.flux.value, spec.flux.value) assert answer_spec.flux.unit == spec.flux.unit def file_answer_testing(hdu, filename, answer_store, answer_dir): oldf = os.path.join(answer_dir, filename) if answer_store: shutil.copy(filename, answer_dir) else: f_old = fits.open(oldf) f_new = fits.open(filename) if hdu in ["IMAGE", "EXPMAP"]: for k in f_old[hdu].header: assert_equal(f_old[hdu].header[k], f_new[hdu].header[k]) dtype = f_old[hdu].data.dtype if np.issubdtype(dtype, np.float32): rtol = 1.0e-6 else: rtol = 1.0e-8 assert_allclose(f_old[hdu].data, f_new[hdu].data, rtol=rtol) else: old_cols = f_old[hdu].data.names new_cols = f_new[hdu].data.names assert old_cols == new_cols for name in old_cols: dtype = f_old[hdu].data[name].dtype if np.issubdtype(dtype, np.integer): assert_equal(f_old[hdu].data[name], f_new[hdu].data[name]) else: if np.issubdtype(dtype, np.float32): rtol = 1.0e-6 else: rtol = 1.0e-8 assert_allclose(f_old[hdu].data[name], f_new[hdu].data[name], rtol=rtol) f_old.close() f_new.close()
[ "astropy.io.fits.open", "numpy.testing.assert_equal", "shutil.copy", "numpy.testing.assert_allclose", "os.path.join", "numpy.issubdtype" ]
[((215, 249), 'os.path.join', 'os.path.join', (['answer_dir', 'filename'], {}), '(answer_dir, filename)\n', (227, 249), False, 'import os\n'), ((699, 733), 'os.path.join', 'os.path.join', (['answer_dir', 'filename'], {}), '(answer_dir, filename)\n', (711, 733), False, 'import os\n'), ((395, 451), 'numpy.testing.assert_allclose', 'assert_allclose', (['answer_spec.emid.value', 'spec.emid.value'], {}), '(answer_spec.emid.value, spec.emid.value)\n', (410, 451), False, 'from numpy.testing import assert_allclose, assert_equal\n'), ((484, 540), 'numpy.testing.assert_allclose', 'assert_allclose', (['answer_spec.flux.value', 'spec.flux.value'], {}), '(answer_spec.flux.value, spec.flux.value)\n', (499, 540), False, 'from numpy.testing import assert_allclose, assert_equal\n'), ((763, 796), 'shutil.copy', 'shutil.copy', (['filename', 'answer_dir'], {}), '(filename, answer_dir)\n', (774, 796), False, 'import shutil\n'), ((823, 838), 'astropy.io.fits.open', 'fits.open', (['oldf'], {}), '(oldf)\n', (832, 838), False, 'from astropy.io import fits\n'), ((855, 874), 'astropy.io.fits.open', 'fits.open', (['filename'], {}), '(filename)\n', (864, 874), False, 'from astropy.io import fits\n'), ((1084, 1116), 'numpy.issubdtype', 'np.issubdtype', (['dtype', 'np.float32'], {}), '(dtype, np.float32)\n', (1097, 1116), True, 'import numpy as np\n'), ((1208, 1268), 'numpy.testing.assert_allclose', 'assert_allclose', (['f_old[hdu].data', 'f_new[hdu].data'], {'rtol': 'rtol'}), '(f_old[hdu].data, f_new[hdu].data, rtol=rtol)\n', (1223, 1268), False, 'from numpy.testing import assert_allclose, assert_equal\n'), ((970, 1026), 'numpy.testing.assert_equal', 'assert_equal', (['f_old[hdu].header[k]', 'f_new[hdu].header[k]'], {}), '(f_old[hdu].header[k], f_new[hdu].header[k])\n', (982, 1026), False, 'from numpy.testing import assert_allclose, assert_equal\n'), ((1518, 1550), 'numpy.issubdtype', 'np.issubdtype', (['dtype', 'np.integer'], {}), '(dtype, np.integer)\n', (1531, 1550), True, 'import numpy as np\n'), ((1572, 1630), 'numpy.testing.assert_equal', 'assert_equal', (['f_old[hdu].data[name]', 'f_new[hdu].data[name]'], {}), '(f_old[hdu].data[name], f_new[hdu].data[name])\n', (1584, 1630), False, 'from numpy.testing import assert_allclose, assert_equal\n'), ((1676, 1708), 'numpy.issubdtype', 'np.issubdtype', (['dtype', 'np.float32'], {}), '(dtype, np.float32)\n', (1689, 1708), True, 'import numpy as np\n'), ((1832, 1904), 'numpy.testing.assert_allclose', 'assert_allclose', (['f_old[hdu].data[name]', 'f_new[hdu].data[name]'], {'rtol': 'rtol'}), '(f_old[hdu].data[name], f_new[hdu].data[name], rtol=rtol)\n', (1847, 1904), False, 'from numpy.testing import assert_allclose, assert_equal\n')]
# An example of using a tensorflow custom core estimator with contrib predictor for increased inference performance. # Attempts to use up-to-date best practice for tensorflow development and keep dependencies to a minimum. # Performs a regression using a deep neural network where the number of inputs and outputs can easily be tweaked by changing a couple of constants. # Initial version written by <NAME>, Spinning Owl AS in may 2018. # MIT license import tensorflow as tf import numpy as np import datetime import time FEATURES_RANK = 3 # The number of inputs LABELS_RANK = 2 # The number of outputs # Returns a numpy array of rank LABELS_RANK based on the features argument. # Can be used when creating a training dataset. def features_to_labels(features): sum_column = features.sum(1).reshape(features.shape[0], 1) labels = np.hstack((sum_column*i for i in range(1, LABELS_RANK+1))) return labels def serving_input_fn(): x = tf.placeholder(dtype=tf.float32, shape=[None, FEATURES_RANK], name='x') # match dtype in input_fn inputs = {'x': x } return tf.estimator.export.ServingInputReceiver(inputs, inputs) def model_fn(features, labels, mode): net = features["x"] # input for units in [4, 8, 4]: # hidden units net = tf.layers.dense(net, units=units, activation=tf.nn.relu) net = tf.layers.dropout(net, rate=0.1) output = tf.layers.dense(net, LABELS_RANK, activation=None) if mode == tf.estimator.ModeKeys.PREDICT: return tf.estimator.EstimatorSpec(mode, predictions=output, export_outputs={"out": tf.estimator.export.PredictOutput(output)}) loss = tf.losses.mean_squared_error(labels, output) if mode == tf.estimator.ModeKeys.EVAL: return tf.estimator.EstimatorSpec(mode, loss=loss) optimizer = tf.train.AdagradOptimizer(learning_rate=0.1) train_op = optimizer.minimize(loss, global_step=tf.train.get_global_step()) return tf.estimator.EstimatorSpec(mode, loss=loss, train_op=train_op) # expecting a numpy array of shape (1, FEATURE_RANK) for constant_feature argument def input_fn(num_samples, constant_feature = None, is_infinite = True): feature_values = np.full((num_samples, FEATURES_RANK), constant_feature) if isinstance(constant_feature, np.ndarray) else np.random.rand(num_samples, FEATURES_RANK) feature_values = np.float32(feature_values) # match dtype in serving_input_fn labels = features_to_labels(feature_values) dataset = tf.data.Dataset.from_tensors(({"x": feature_values}, labels)) if is_infinite: dataset = dataset.repeat() return dataset.make_one_shot_iterator().get_next() estimator = tf.estimator.Estimator( model_fn=model_fn, model_dir="model_dir\\estimator-predictor-test-{date:%Y-%m-%d %H.%M.%S}".format(date=datetime.datetime.now())) train = estimator.train(input_fn=lambda : input_fn(50), steps=500) evaluate = estimator.evaluate(input_fn=lambda : input_fn(20), steps=1) predictor = tf.contrib.predictor.from_estimator(estimator, serving_input_fn) consistency_check_features = np.random.rand(1, FEATURES_RANK) consistency_check_labels = features_to_labels(consistency_check_features) num_calls_predictor = 100 predictor_input = {"x": consistency_check_features} start_time_predictor = time.clock() for i in range(num_calls_predictor): predictor_prediction = predictor(predictor_input) delta_time_predictor = 1./num_calls_predictor*(time.clock() - start_time_predictor) num_calls_estimator_predict = 10 estimator_input = lambda : input_fn(1, consistency_check_features, False) start_time_estimator_predict = time.clock() for i in range(num_calls_estimator_predict): estimator_prediction = list(estimator.predict(input_fn=estimator_input)) delta_time_estimator = 1./num_calls_estimator_predict*(time.clock() - start_time_estimator_predict) print("{} --> {}\n predictor={}\n estimator={}.\n".format(consistency_check_features, consistency_check_labels, predictor_prediction, estimator_prediction)) print("Time used per estimator.predict() call: {:.5f}s, predictor(): {:.5f}s ==> predictor is {:.0f}x faster!".format(delta_time_estimator, delta_time_predictor, delta_time_estimator/delta_time_predictor))
[ "numpy.full", "tensorflow.estimator.export.PredictOutput", "tensorflow.train.get_global_step", "tensorflow.losses.mean_squared_error", "tensorflow.estimator.export.ServingInputReceiver", "tensorflow.layers.dense", "tensorflow.train.AdagradOptimizer", "numpy.float32", "time.clock", "tensorflow.layers.dropout", "tensorflow.placeholder", "tensorflow.contrib.predictor.from_estimator", "numpy.random.rand", "tensorflow.estimator.EstimatorSpec", "datetime.datetime.now", "tensorflow.data.Dataset.from_tensors" ]
[((2948, 3012), 'tensorflow.contrib.predictor.from_estimator', 'tf.contrib.predictor.from_estimator', (['estimator', 'serving_input_fn'], {}), '(estimator, serving_input_fn)\n', (2983, 3012), True, 'import tensorflow as tf\n'), ((3045, 3077), 'numpy.random.rand', 'np.random.rand', (['(1)', 'FEATURES_RANK'], {}), '(1, FEATURES_RANK)\n', (3059, 3077), True, 'import numpy as np\n'), ((3259, 3271), 'time.clock', 'time.clock', ([], {}), '()\n', (3269, 3271), False, 'import time\n'), ((3590, 3602), 'time.clock', 'time.clock', ([], {}), '()\n', (3600, 3602), False, 'import time\n'), ((964, 1035), 'tensorflow.placeholder', 'tf.placeholder', ([], {'dtype': 'tf.float32', 'shape': '[None, FEATURES_RANK]', 'name': '"""x"""'}), "(dtype=tf.float32, shape=[None, FEATURES_RANK], name='x')\n", (978, 1035), True, 'import tensorflow as tf\n'), ((1099, 1155), 'tensorflow.estimator.export.ServingInputReceiver', 'tf.estimator.export.ServingInputReceiver', (['inputs', 'inputs'], {}), '(inputs, inputs)\n', (1139, 1155), True, 'import tensorflow as tf\n'), ((1390, 1440), 'tensorflow.layers.dense', 'tf.layers.dense', (['net', 'LABELS_RANK'], {'activation': 'None'}), '(net, LABELS_RANK, activation=None)\n', (1405, 1440), True, 'import tensorflow as tf\n'), ((1630, 1674), 'tensorflow.losses.mean_squared_error', 'tf.losses.mean_squared_error', (['labels', 'output'], {}), '(labels, output)\n', (1658, 1674), True, 'import tensorflow as tf\n'), ((1789, 1833), 'tensorflow.train.AdagradOptimizer', 'tf.train.AdagradOptimizer', ([], {'learning_rate': '(0.1)'}), '(learning_rate=0.1)\n', (1814, 1833), True, 'import tensorflow as tf\n'), ((1921, 1983), 'tensorflow.estimator.EstimatorSpec', 'tf.estimator.EstimatorSpec', (['mode'], {'loss': 'loss', 'train_op': 'train_op'}), '(mode, loss=loss, train_op=train_op)\n', (1947, 1983), True, 'import tensorflow as tf\n'), ((2329, 2355), 'numpy.float32', 'np.float32', (['feature_values'], {}), '(feature_values)\n', (2339, 2355), True, 'import numpy as np\n'), ((2448, 2509), 'tensorflow.data.Dataset.from_tensors', 'tf.data.Dataset.from_tensors', (["({'x': feature_values}, labels)"], {}), "(({'x': feature_values}, labels))\n", (2476, 2509), True, 'import tensorflow as tf\n'), ((1280, 1336), 'tensorflow.layers.dense', 'tf.layers.dense', (['net'], {'units': 'units', 'activation': 'tf.nn.relu'}), '(net, units=units, activation=tf.nn.relu)\n', (1295, 1336), True, 'import tensorflow as tf\n'), ((1346, 1378), 'tensorflow.layers.dropout', 'tf.layers.dropout', (['net'], {'rate': '(0.1)'}), '(net, rate=0.1)\n', (1363, 1378), True, 'import tensorflow as tf\n'), ((1728, 1771), 'tensorflow.estimator.EstimatorSpec', 'tf.estimator.EstimatorSpec', (['mode'], {'loss': 'loss'}), '(mode, loss=loss)\n', (1754, 1771), True, 'import tensorflow as tf\n'), ((2162, 2217), 'numpy.full', 'np.full', (['(num_samples, FEATURES_RANK)', 'constant_feature'], {}), '((num_samples, FEATURES_RANK), constant_feature)\n', (2169, 2217), True, 'import numpy as np\n'), ((2267, 2309), 'numpy.random.rand', 'np.random.rand', (['num_samples', 'FEATURES_RANK'], {}), '(num_samples, FEATURES_RANK)\n', (2281, 2309), True, 'import numpy as np\n'), ((3410, 3422), 'time.clock', 'time.clock', ([], {}), '()\n', (3420, 3422), False, 'import time\n'), ((3780, 3792), 'time.clock', 'time.clock', ([], {}), '()\n', (3790, 3792), False, 'import time\n'), ((1884, 1910), 'tensorflow.train.get_global_step', 'tf.train.get_global_step', ([], {}), '()\n', (1908, 1910), True, 'import tensorflow as tf\n'), ((2765, 2788), 'datetime.datetime.now', 'datetime.datetime.now', ([], {}), '()\n', (2786, 2788), False, 'import datetime\n'), ((1574, 1615), 'tensorflow.estimator.export.PredictOutput', 'tf.estimator.export.PredictOutput', (['output'], {}), '(output)\n', (1607, 1615), True, 'import tensorflow as tf\n')]
from covariance import Covariance import numpy as np from scipy.special import gamma """Covariance run 1: COSMOS-like with no lensing fields""" # Generate non-fit parameters. # .. These values should be motivated to reflect actual data # .. Postage stamp size Nx = 150 Ny = 150 # .. Standard galaxy size (in pixels) a = 30. # .. I0 I0 = 5. # .. noise1 and noise2 noise1 = 1.3e-3 noise2 = 0. # .. Background background = 0. # Set lensing fields to zero psi2 = [0,0,0] psi3 = [0,0,0,0] # Shape parameters # .. Centroid (will be dithered within a pixel in Covariance) xc = 0 yc = 0 # .. ns ns = 2.5 # .. phi phi = np.pi/6 # .. q # .. .. We choose intrinsic ellipticity to have a magnitude of 0.2 (Schneider 1996) eps_s = 0.2 q = (1+abs(eps_s))/(1-abs(eps_s)) # .. rs rs = a/(np.sqrt(((1+q**2.)/2)))*np.sqrt(gamma(2.*ns)/gamma(4.*ns)) # Gather list of fiducial parameter values fid_params = np.array((0.5, 0.5, # Centroid dithered from 0 to 1, so the fiducial value is trivially 0.5 ns, rs, q, phi, psi111, psi112, psi122, psi222)) # Run Covariance Cov1 = Covariance(Nx=Nx, Ny=Ny, xc=xc, yc=yc, ns=ns, rs=rs, q=q, phi=phi, psi2=psi2, psi3=psi3, marg=np.array((1,1,1,1,1,1,0,0,0,1,1,1,1)), I0=I0, noise1=noise1, noise2=noise2, background=background, N_iter=1000, fid_params=fid_params, stamp_col_label='COSMOS-like_no_lensing_ns_2.5_a_50') # Simulate the stamp collection Cov1.simulateGals() # Run Lenser on this stamp collection Cov1.lenserRun() # Compute the covariance matrix for this stamp collection Cov1_mat = Cov1.computeCovMat() # Compute the 1-sigma uncertainty on each parameter print(np.round(Cov1.error(Cov1_mat),7)) # Plot Cov1.plot_error_matrix(Cov1_mat) """ # Create an instance of the Covariance class # We would like to keep all default values, expect we will # add a flat noisemap with a value of I0/1e4 Cov1=Covariance(noise1=0.1, marg=np.array((1,1,1,1,1,1,0,0,0,1,1,1,1)), catalogue_label='noise1_I0e-4') # Simulate the catalogue with this noise Cov1.simulateGals() # Run Lenser on this catalogue Cov1.lenserRun() # Compute the covariance matrix for this catalogue Cov1_mat = Cov1.computeCovMat() # Compute the 1-sigma uncertainty on each parameter print(np.round(Cov1.error(Cov1_mat),7)) # Plot Cov1.plot_error_matrix(Cov1_mat) # Now let us repeat this process but for a flat # noisemap with double the previous noise, # i.e. a value of 2*I0/1e4 Cov2=Covariance(noise1=0.2, marg=np.array((1,1,1,1,1,1,0,0,0,1,1,1,1)), catalogue_label='noise1_2I0e-4') # Simulate the catalogue with this noise Cov2.simulateGals() # Run Lenser on this catalogue Cov2.lenserRun() # Compute the covariance matrix for this catalogue Cov2_mat = Cov2.computeCovMat() # Compute the 1-sigma uncertainty on each parameter print(np.round(Cov2.error(Cov2_mat),7)) # Plot Cov2.plot_error_matrix(Cov2_mat) # Let's plot both of these covariance matrices # together for combined visualization Cov1_vs_Cov2=Covariance(marg=np.array((1,1,1,1,1,1,0,0,0,1,1,1,1))) Cov1_vs_Cov2_mats=Cov1_vs_Cov2.covariance_array(Cov1_mat,Cov2_mat) Cov1_vs_Cov2.plot_error_matrix_combined(Cov1_vs_Cov2_mats, filename='about/simulated_stamp_collections_noise1_I0e-4_and_noise1_2I0e-4_combined', labels=[r'$I_0/10^4$',r'$2I_0/10^4$']) # Create an instance of the Covariance class # We would like to keep all default values, expect we will # add a flat noisemap with a value of I0/1e4 Cov3=Covariance(noise1=0.1, q=2.5, phi=2., psi3=[0.001,0.002,0.003,0.004],marg=[1,1,1,1,1,1,0,0,0,1,1,1,1],catalogue_label='noise1_I0e-4_phi_2_q_2.5_psi3_0.001_0.002_0.003_0.004') #Cov3=Covariance(noise1=0.1, q=2.5, phi=0, psi3=[0,0,0,0],catalogue_label='noise1_I0e-4_phi_0_q_1_psiijk_0') # Simulate the catalogue with this noise Cov3.simulateGals(overwrite=True) # Run Lenser on this catalogue Cov3.lenserRun(overwrite=True) # Compute the covariance matrix for this catalogue Cov3_mat = Cov3.computeCovMat() # Compute the 1-sigma uncertainty on each parameter print(np.round(Cov3.error(Cov3_mat),7)) # Plot Cov3.plot_error_matrix(Cov3_mat) """
[ "scipy.special.gamma", "numpy.array", "numpy.sqrt" ]
[((891, 959), 'numpy.array', 'np.array', (['(0.5, 0.5, ns, rs, q, phi, psi111, psi112, psi122, psi222)'], {}), '((0.5, 0.5, ns, rs, q, phi, psi111, psi112, psi122, psi222))\n', (899, 959), True, 'import numpy as np\n'), ((775, 802), 'numpy.sqrt', 'np.sqrt', (['((1 + q ** 2.0) / 2)'], {}), '((1 + q ** 2.0) / 2)\n', (782, 802), True, 'import numpy as np\n'), ((1273, 1322), 'numpy.array', 'np.array', (['(1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1)'], {}), '((1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1))\n', (1281, 1322), True, 'import numpy as np\n'), ((807, 822), 'scipy.special.gamma', 'gamma', (['(2.0 * ns)'], {}), '(2.0 * ns)\n', (812, 822), False, 'from scipy.special import gamma\n'), ((820, 835), 'scipy.special.gamma', 'gamma', (['(4.0 * ns)'], {}), '(4.0 * ns)\n', (825, 835), False, 'from scipy.special import gamma\n')]
from behaviour_cloning import * import tensorflow as tf import pickle import mujoco_py import gym import numpy as np def main(): observations, actions = process_expert_data("Humanoid-v2") comp_returns= np.zeros(shape=(20,20)) comp_avg_return=[] for i in range (20): train_model(observations, actions) eval_observations, eval_actions, returns, avg_return = eval_model(observations, actions, "Humanoid-v2", 20) print("returns=", returns, "avg return=", avg_return) observations=np.concatenate((observations,eval_observations), axis=0) actions=np.concatenate((actions,eval_actions), axis=0) comp_returns[i]=returns comp_avg_return.append(avg_return) print("complete avg returns",comp_avg_return) if __name__ == '__main__': main()
[ "numpy.zeros", "numpy.concatenate" ]
[((211, 235), 'numpy.zeros', 'np.zeros', ([], {'shape': '(20, 20)'}), '(shape=(20, 20))\n', (219, 235), True, 'import numpy as np\n'), ((525, 582), 'numpy.concatenate', 'np.concatenate', (['(observations, eval_observations)'], {'axis': '(0)'}), '((observations, eval_observations), axis=0)\n', (539, 582), True, 'import numpy as np\n'), ((598, 645), 'numpy.concatenate', 'np.concatenate', (['(actions, eval_actions)'], {'axis': '(0)'}), '((actions, eval_actions), axis=0)\n', (612, 645), True, 'import numpy as np\n')]
#!/usr/bin/env python3 ''' <NAME>, <EMAIL> 2020/05/23 Python code to read the sensor data from the Silicon Labs Thunderboard Sense2 command-line input parameters: --time [seconds] --sensor outputs: CSV of all sensor data plot of all specific sensor v0.1 : inital version ''' import serial import datetime import time import numpy as np import matplotlib.pyplot as plt import appnope import glob import pandas as pd import platform import sys import argparse if __name__ == '__main__': now = datetime.datetime.now() # current date and time for saving files date_time = now.strftime("%Y_%m_%d_%H_%M_%S") os_platform = platform.system() appnope.nope() plt.style.use('ggplot') # temporary sensor keys for input arguments (no spaces) sensor_keys = ['TVOC', 'Pressure', 'SoundLevel', 'AmbLight', 'eCO2', 'HALL', 'Temp', 'Humidity', 'UVIndex'] sensor_list = ', '.join(sensor_keys) parser = argparse.ArgumentParser() parser.add_argument("--time", help="The time for data collection in seconds", default = 10) parser.add_argument("--sensor", help="The name of the sensor to plot and display (can be all)\nOptions are: {}".format(sensor_list), default = 'Humidity') args = parser.parse_args() run_time = float(args.time) # seconds [TODO: input] sensor_to_display = str(args.sensor) # 'Humidity' # [TODO: input] if sensor_to_display == 'AmbLight': sensor_to_display = 'Amb light' if sensor_to_display == 'HALL': sensor_to_display = 'HALL: Mag' if sensor_to_display == 'UVIndex': sensor_to_display = 'UV Index' # fix sensor keys to match the strings from the Thunderboard sensor_keys = ['TVOC', 'Pressure', 'SoundLevel', 'Amb light', 'eCO2', 'HALL: Mag', 'Temp', 'Humidity', 'UV Index'] def TimestampMillisec64(): return int((datetime.datetime.utcnow() - datetime.datetime(1970, 1, 1)).total_seconds() * 1000) # serial parameters and serial opening baudrate = 115200 import serial.tools.list_ports ports = list(serial.tools.list_ports.comports()) pid = '1366' hid = '1015' for p in ports: #print('Serial port found:') #print(p[1]) #print('Port pid and hid') #print(p.hwid) hwid_save = p.hwid if pid and hid in p.hwid: print('Found the Thunderboard device to open with PID = {} and HID = {}!'.format(pid, hid)) try: # ser_addr = [x for x in ports if x[1]=='J-Link OB'][0][0] ser_addr = [x for x in ports if pid and hid in x.hwid][0][0] except IndexError: print('No serial address found.\n Is the thunderboard connected using USB?') if os_platform in ['Darwin', 'Linux']: print('Check for /dev/tty.usbmodem by $ ls /dev/tty.*') elif os_platform in ['Windows']: print('Check for COM in Device Manager') sys.exit(1) ''' if os_platform == 'Darwin': # MAC print("Found these devices: " + glob.glob("/dev/tty.usbmodem*")[0]) ser_addr = glob.glob("/dev/tty.usbmodem*")[0] elif os_platform == 'Windows': print("Found these devices: " + glob.glob("/dev/tty.usbmodem*")[0]) ser_addr = glob.glob("/dev/tty.usbmodem*")[0] elif os_platform == 'Linux': print("Found these devices: " + glob.glob("/dev/tty.usbmodem*")[0]) ser_addr = glob.glob("/dev/tty.usbmodem*")[0] ''' ser = serial.Serial(ser_addr, baudrate = baudrate, timeout = 2) ser.is_open time.sleep(0.15) results = {} for k in sensor_keys: results[k] = {} results[k]['value'] = np.array([]) results[k]['time'] = np.array([]) results[k]['units'] = np.array([]) # flush serial buffer ser.read(ser.in_waiting) t_junk = ser.readline() t_start = TimestampMillisec64() elapsed_time = (TimestampMillisec64() - t_start)/1000 while(elapsed_time < run_time): t = str(ser.readline()) print(t) # add this # Remove for iOS # if len(t) == 3: # print('Serial read timeout. \n Is the bluetooth app connected AND diplaying Environmental data?') # # close serial port # ser.close() # sys.exit(2) elapsed_time = (TimestampMillisec64() - t_start) / 1000 for k in sensor_keys: if k in t: if k == 'UV Index': results[k]['value'] = np.append(results[k]['value'], float(t.split('=')[1].split(' ')[1].replace("\\r\\n'",''))) results[k]['units'] = np.append(results[k]['units'], 'index') else: results[k]['value'] = np.append(results[k]['value'], float(t.split('=')[1].split(' ')[1])) # fix units for TVOC and eCO2 if k == 'eCO2': results[k]['units'] = np.append(results[k]['units'], 'ppm') elif k == 'TVOC': results[k]['units'] = np.append(results[k]['units'], 'ppb') else: results[k]['units'] = np.append(results[k]['units'], t.split('=')[1].split(' ')[2].replace("\\r\\n'",'')) results[k]['time'] = np.append(results[k]['time'], elapsed_time) if ((k == sensor_to_display) or (sensor_to_display == 'all')): print('At {:2.2f} [s] Measured {} sensor: {:4.2f} {}'.format(elapsed_time, k, results[k]['value'][-1], results[k]['units'][-1])) # close serial port ser.close() # plot and save data if sensor_to_display == 'all': fig, axs = plt.subplots(3,3, figsize = (10, 10)) sensors_to_plot = sensor_keys for idx,k in enumerate(sensors_to_plot): axs[int(idx/3)][idx % 3].plot(results[k]['time'], results[k]['value'], marker='x', label = k) axs[int(idx/3)][idx % 3].legend() axs[int(idx/3)][idx % 3].set_ylabel(results[k]['units'][-1]) axs[int(idx/3)][idx % 3].set_xlabel('Time [s]') else: sensors_to_plot = [sensor_to_display] fig, axs = plt.subplots(figsize = (10, 10)) for idx,k in enumerate(sensors_to_plot): axs.plot(results[k]['time'], results[k]['value'], marker='x', label = k) axs.set_ylabel(results[k]['units'][-1]) axs.set_xlabel('Time [s]') axs.legend() fig.tight_layout() fig.savefig('measured_{}_{}.png'.format(sensor_to_display, date_time)) # blocking show plt.ioff() plt.show() # https://stackoverflow.com/questions/13575090/construct-pandas-dataframe-from-items-in-nested-dictionary # save dictionary to CSV file by first converting to a pandas dataframe df = pd.DataFrame.from_dict({i + '_' + j: results[i][j] for i in results.keys() for j in results[i].keys()}, orient='index') df = df.transpose() df.to_csv('data_{}.csv'.format(date_time), index=False)
[ "serial.Serial", "matplotlib.pyplot.show", "argparse.ArgumentParser", "matplotlib.pyplot.ioff", "serial.tools.list_ports.comports", "matplotlib.pyplot.subplots", "time.sleep", "datetime.datetime", "numpy.append", "matplotlib.pyplot.style.use", "datetime.datetime.utcnow", "numpy.array", "platform.system", "sys.exit", "datetime.datetime.now", "appnope.nope" ]
[((509, 532), 'datetime.datetime.now', 'datetime.datetime.now', ([], {}), '()\n', (530, 532), False, 'import datetime\n'), ((638, 655), 'platform.system', 'platform.system', ([], {}), '()\n', (653, 655), False, 'import platform\n'), ((657, 671), 'appnope.nope', 'appnope.nope', ([], {}), '()\n', (669, 671), False, 'import appnope\n'), ((673, 696), 'matplotlib.pyplot.style.use', 'plt.style.use', (['"""ggplot"""'], {}), "('ggplot')\n", (686, 696), True, 'import matplotlib.pyplot as plt\n'), ((922, 947), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (945, 947), False, 'import argparse\n'), ((3225, 3278), 'serial.Serial', 'serial.Serial', (['ser_addr'], {'baudrate': 'baudrate', 'timeout': '(2)'}), '(ser_addr, baudrate=baudrate, timeout=2)\n', (3238, 3278), False, 'import serial\n'), ((3297, 3313), 'time.sleep', 'time.sleep', (['(0.15)'], {}), '(0.15)\n', (3307, 3313), False, 'import time\n'), ((5890, 5900), 'matplotlib.pyplot.ioff', 'plt.ioff', ([], {}), '()\n', (5898, 5900), True, 'import matplotlib.pyplot as plt\n'), ((5902, 5912), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (5910, 5912), True, 'import matplotlib.pyplot as plt\n'), ((2007, 2041), 'serial.tools.list_ports.comports', 'serial.tools.list_ports.comports', ([], {}), '()\n', (2039, 2041), False, 'import serial\n'), ((3394, 3406), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (3402, 3406), True, 'import numpy as np\n'), ((3430, 3442), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (3438, 3442), True, 'import numpy as np\n'), ((3467, 3479), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (3475, 3479), True, 'import numpy as np\n'), ((5101, 5137), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(3)', '(3)'], {'figsize': '(10, 10)'}), '(3, 3, figsize=(10, 10))\n', (5113, 5137), True, 'import matplotlib.pyplot as plt\n'), ((5531, 5561), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {'figsize': '(10, 10)'}), '(figsize=(10, 10))\n', (5543, 5561), True, 'import matplotlib.pyplot as plt\n'), ((2739, 2750), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (2747, 2750), False, 'import sys\n'), ((4746, 4789), 'numpy.append', 'np.append', (["results[k]['time']", 'elapsed_time'], {}), "(results[k]['time'], elapsed_time)\n", (4755, 4789), True, 'import numpy as np\n'), ((4212, 4251), 'numpy.append', 'np.append', (["results[k]['units']", '"""index"""'], {}), "(results[k]['units'], 'index')\n", (4221, 4251), True, 'import numpy as np\n'), ((4456, 4493), 'numpy.append', 'np.append', (["results[k]['units']", '"""ppm"""'], {}), "(results[k]['units'], 'ppm')\n", (4465, 4493), True, 'import numpy as np\n'), ((1815, 1841), 'datetime.datetime.utcnow', 'datetime.datetime.utcnow', ([], {}), '()\n', (1839, 1841), False, 'import datetime\n'), ((1844, 1873), 'datetime.datetime', 'datetime.datetime', (['(1970)', '(1)', '(1)'], {}), '(1970, 1, 1)\n', (1861, 1873), False, 'import datetime\n'), ((4545, 4582), 'numpy.append', 'np.append', (["results[k]['units']", '"""ppb"""'], {}), "(results[k]['units'], 'ppb')\n", (4554, 4582), True, 'import numpy as np\n')]
import fridge.utilities.mcnpCreatorFunctions as MCF import numpy as np def test_getRCC(): surfaceCard = MCF.getRCC(0.5, 10, [0.0, 0.0, 0.5555555], 1, '$ Comment') surfaceCardKnown = '1 RCC 0.0 0.0 0.55556 0 0 10 0.5 $ Comment' assert surfaceCard == surfaceCardKnown def test_getRHP(): surfaceCard = MCF.getRHP(0.5, 10, [0.0, 0.0, 0.5555555], 1, '$ Comment') surfaceCardKnown = '1 RHP 0.0 0.0 0.55556 0 0 10 0.5 0 0 $ Comment' assert surfaceCard == surfaceCardKnown def test_getRHSRotated(): surfaceCard = MCF.getRHPRotated(0.5, 10, [0.0, 0.0, 0.5555555], 1, '$ Comment') surfaceCardKnown = '1 RHP 0.0 0.0 0.55556 0 0 10 0 0.5 0 $ Comment' assert surfaceCard == surfaceCardKnown def test_getSingleCell(): cellCard = MCF.getSingleCell(1, 2, 0.06, 3, 10, '$ Comment') cellCardKnown = '1 2 0.06 -3 u=10 imp:n=1 $ Comment' assert cellCard == cellCardKnown def test_getConcentricCell_Single(): cellCard = MCF.getConcentricCell(1, 2, 0.06, 4, 3, 10, '$ Comment') cellCardKnown = '1 2 0.06 4 -3 u=10 imp:n=1 $ Comment' assert cellCard == cellCardKnown def test_getConcentricCell_Multiple(): cellCard = MCF.getConcentricCell(1, 2, 0.06, [4, 5, 6], 3, 10, '$ Comment') cellCardKnown = '1 2 0.06 4 5 6 -3 u=10 imp:n=1 $ Comment' assert cellCard == cellCardKnown def test_getOutsideCell(): cellCard = MCF.getOutsideCell(1, 2, 0.06, 3, 10, '$ Comment') cellCardKnown = '1 2 0.06 3 u=10 imp:n=1 $ Comment' assert cellCard == cellCardKnown def test_getFuelLatticeCell(): cellCard = MCF.getFuelLatticeCell(1, 2, 20, 10, '$ Comment') cellCardKnown = '1 0 -2 u=20 fill=10 imp:n=1 $ Comment' assert cellCard == cellCardKnown def test_getAssemblyUniverseCell(): cellCard = MCF.getAssemblyUniverseCell(1, 2, 10, '$ Comment') cellCardKnown = '1 0 -2 fill=10 imp:n=1 $ Comment' assert cellCard == cellCardKnown def test_getEverythingElseCard(): cellCard = MCF.getEverythingElseCard(1, 2, '$ Comment') cellCardKnown = '1 0 2 imp:n=0 $ Comment' assert cellCard == cellCardKnown def test_smearedMaterial(): smearMaterialDict = {'LiquidNa': 0.5, 'Void': 0.5} smearedMaterial = MCF.getSmearedMaterial(smearMaterialDict) assert np.allclose(smearedMaterial.atomDensity, 0.01214, 5) assert smearedMaterial.name == "['LiquidNa', 'Void']" assert smearedMaterial.atomPercent[11023] == 1.0 def test_smearedMAterial_voided(): smearMaterialDict = {'LiquidNa': 0.5, 'Void': 0.5} smearedMaterial = MCF.getSmearedMaterial(smearMaterialDict, voidMaterial='LiquidNa', voidPercent=0.1) assert np.allclose(smearedMaterial.atomDensity, 0.001214, 5) assert smearedMaterial.name == "['LiquidNa', 'Void']" assert smearedMaterial.atomPercent[11023] == 1.0 def test_coolantWireWrapSmear(): info = [60, 0.53, 0.126, 2, 0.66144, 'LiquidNa', 'Void'] smearedDict = MCF.getCoolantWireWrapSmear(info) knownSmearDict = {'LiquidNa': 0.918819, 'Void': 0.081181} for k, v in knownSmearDict.items(): assert np.allclose(smearedDict[k], v, 5) def test_getPosition_02A01(): position = MCF.getPosition('02A01', 2, 10) knownAPosition = [-1.73205, 1.0, 10] for i, pos in enumerate(position): assert np.allclose(knownAPosition[i], pos) def test_getPosition_02B01(): position = MCF.getPosition('02B01', 2, 10) knownAPosition = [0.0, 2.0, 10] for i, pos in enumerate(position): assert np.allclose(knownAPosition[i], pos) def test_getPosition_02C01(): position = MCF.getPosition('02C01', 2, 10) knownAPosition = [1.73205, 1.0, 10] for i, pos in enumerate(position): assert np.allclose(knownAPosition[i], pos) def test_getPosition_02D01(): position = MCF.getPosition('02D01', 2, 10) knownAPosition = [1.73205, -1.0, 10] for i, pos in enumerate(position): assert np.allclose(knownAPosition[i], pos) def test_getPosition_02E01(): position = MCF.getPosition('02E01', 2, 10) knownAPosition = [0.0, -2.0, 10] for i, pos in enumerate(position): assert np.allclose(knownAPosition[i], pos) def test_getPosition_02F01(): position = MCF.getPosition('02F01', 2, 10) knownAPosition = [-1.73205, -1.0, 10] for i, pos in enumerate(position): assert np.allclose(knownAPosition[i], pos) def test_getPosition_01A01(): position = MCF.getPosition('01A01', 2, 10) knownPosition = [0, 0, 10] assert position == knownPosition def test_getPosition_03A02(): position = MCF.getPosition('03A02', 2, 10) knownAPosition = [-1.73205, 3.0, 10] for i, pos in enumerate(position): assert np.allclose(knownAPosition[i], pos) def test_getPosition_03B02(): position = MCF.getPosition('03B02', 2, 10) knownAPosition = [1.73205, 3.0, 10] for i, pos in enumerate(position): assert np.allclose(knownAPosition[i], pos) def test_getPosition_03C03(): position = MCF.getPosition('03C02', 2, 10) knownAPosition = [3.46410, 0.0, 10] for i, pos in enumerate(position): assert np.allclose(knownAPosition[i], pos) def test_getPosition_D03(): position = MCF.getPosition('03D02', 2, 10) knownAPosition = [1.73205, -3.0, 10] for i, pos in enumerate(position): assert np.allclose(knownAPosition[i], pos) def test_getPosition_E03(): position = MCF.getPosition('03E02', 2, 10) knownAPosition = [-1.73205, -3.0, 10] for i, pos in enumerate(position): assert np.allclose(knownAPosition[i], pos) def test_getPosition_03F03(): position = MCF.getPosition('03F02', 2, 10) knownAPosition = [-3.46410, 0.0, 10] for i, pos in enumerate(position): assert np.allclose(knownAPosition[i], pos) def test_getPosition_04B03(): position = MCF.getPosition('04B03', 2, 10) knownAPosition = [3.4641, 4.0, 10] for i, pos in enumerate(position): assert np.allclose(knownAPosition[i], pos) def test_getRCCVolume(): volume = MCF.getRCCVolume(0.2, 10) assert np.allclose(volume, 1.25664, 5) def test_getRHPVolume(): volume = MCF.getRCCVolume(5, 10) assert np.allclose(volume, 216.506, 5) def test_getToroidalVolume(): volume = MCF.getToroidalVolume(0.5, 0.05, 5, 10) assert np.allclose(volume, 1.03631, 5)
[ "fridge.utilities.mcnpCreatorFunctions.getCoolantWireWrapSmear", "fridge.utilities.mcnpCreatorFunctions.getRHP", "fridge.utilities.mcnpCreatorFunctions.getSmearedMaterial", "fridge.utilities.mcnpCreatorFunctions.getOutsideCell", "fridge.utilities.mcnpCreatorFunctions.getAssemblyUniverseCell", "fridge.utilities.mcnpCreatorFunctions.getEverythingElseCard", "fridge.utilities.mcnpCreatorFunctions.getPosition", "numpy.allclose", "fridge.utilities.mcnpCreatorFunctions.getFuelLatticeCell", "fridge.utilities.mcnpCreatorFunctions.getConcentricCell", "fridge.utilities.mcnpCreatorFunctions.getSingleCell", "fridge.utilities.mcnpCreatorFunctions.getToroidalVolume", "fridge.utilities.mcnpCreatorFunctions.getRHPRotated", "fridge.utilities.mcnpCreatorFunctions.getRCCVolume", "fridge.utilities.mcnpCreatorFunctions.getRCC" ]
[((110, 168), 'fridge.utilities.mcnpCreatorFunctions.getRCC', 'MCF.getRCC', (['(0.5)', '(10)', '[0.0, 0.0, 0.5555555]', '(1)', '"""$ Comment"""'], {}), "(0.5, 10, [0.0, 0.0, 0.5555555], 1, '$ Comment')\n", (120, 168), True, 'import fridge.utilities.mcnpCreatorFunctions as MCF\n'), ((319, 377), 'fridge.utilities.mcnpCreatorFunctions.getRHP', 'MCF.getRHP', (['(0.5)', '(10)', '[0.0, 0.0, 0.5555555]', '(1)', '"""$ Comment"""'], {}), "(0.5, 10, [0.0, 0.0, 0.5555555], 1, '$ Comment')\n", (329, 377), True, 'import fridge.utilities.mcnpCreatorFunctions as MCF\n'), ((539, 604), 'fridge.utilities.mcnpCreatorFunctions.getRHPRotated', 'MCF.getRHPRotated', (['(0.5)', '(10)', '[0.0, 0.0, 0.5555555]', '(1)', '"""$ Comment"""'], {}), "(0.5, 10, [0.0, 0.0, 0.5555555], 1, '$ Comment')\n", (556, 604), True, 'import fridge.utilities.mcnpCreatorFunctions as MCF\n'), ((763, 812), 'fridge.utilities.mcnpCreatorFunctions.getSingleCell', 'MCF.getSingleCell', (['(1)', '(2)', '(0.06)', '(3)', '(10)', '"""$ Comment"""'], {}), "(1, 2, 0.06, 3, 10, '$ Comment')\n", (780, 812), True, 'import fridge.utilities.mcnpCreatorFunctions as MCF\n'), ((961, 1017), 'fridge.utilities.mcnpCreatorFunctions.getConcentricCell', 'MCF.getConcentricCell', (['(1)', '(2)', '(0.06)', '(4)', '(3)', '(10)', '"""$ Comment"""'], {}), "(1, 2, 0.06, 4, 3, 10, '$ Comment')\n", (982, 1017), True, 'import fridge.utilities.mcnpCreatorFunctions as MCF\n'), ((1170, 1234), 'fridge.utilities.mcnpCreatorFunctions.getConcentricCell', 'MCF.getConcentricCell', (['(1)', '(2)', '(0.06)', '[4, 5, 6]', '(3)', '(10)', '"""$ Comment"""'], {}), "(1, 2, 0.06, [4, 5, 6], 3, 10, '$ Comment')\n", (1191, 1234), True, 'import fridge.utilities.mcnpCreatorFunctions as MCF\n'), ((1380, 1430), 'fridge.utilities.mcnpCreatorFunctions.getOutsideCell', 'MCF.getOutsideCell', (['(1)', '(2)', '(0.06)', '(3)', '(10)', '"""$ Comment"""'], {}), "(1, 2, 0.06, 3, 10, '$ Comment')\n", (1398, 1430), True, 'import fridge.utilities.mcnpCreatorFunctions as MCF\n'), ((1572, 1621), 'fridge.utilities.mcnpCreatorFunctions.getFuelLatticeCell', 'MCF.getFuelLatticeCell', (['(1)', '(2)', '(20)', '(10)', '"""$ Comment"""'], {}), "(1, 2, 20, 10, '$ Comment')\n", (1594, 1621), True, 'import fridge.utilities.mcnpCreatorFunctions as MCF\n'), ((1772, 1822), 'fridge.utilities.mcnpCreatorFunctions.getAssemblyUniverseCell', 'MCF.getAssemblyUniverseCell', (['(1)', '(2)', '(10)', '"""$ Comment"""'], {}), "(1, 2, 10, '$ Comment')\n", (1799, 1822), True, 'import fridge.utilities.mcnpCreatorFunctions as MCF\n'), ((1966, 2010), 'fridge.utilities.mcnpCreatorFunctions.getEverythingElseCard', 'MCF.getEverythingElseCard', (['(1)', '(2)', '"""$ Comment"""'], {}), "(1, 2, '$ Comment')\n", (1991, 2010), True, 'import fridge.utilities.mcnpCreatorFunctions as MCF\n'), ((2201, 2242), 'fridge.utilities.mcnpCreatorFunctions.getSmearedMaterial', 'MCF.getSmearedMaterial', (['smearMaterialDict'], {}), '(smearMaterialDict)\n', (2223, 2242), True, 'import fridge.utilities.mcnpCreatorFunctions as MCF\n'), ((2254, 2306), 'numpy.allclose', 'np.allclose', (['smearedMaterial.atomDensity', '(0.01214)', '(5)'], {}), '(smearedMaterial.atomDensity, 0.01214, 5)\n', (2265, 2306), True, 'import numpy as np\n'), ((2531, 2618), 'fridge.utilities.mcnpCreatorFunctions.getSmearedMaterial', 'MCF.getSmearedMaterial', (['smearMaterialDict'], {'voidMaterial': '"""LiquidNa"""', 'voidPercent': '(0.1)'}), "(smearMaterialDict, voidMaterial='LiquidNa',\n voidPercent=0.1)\n", (2553, 2618), True, 'import fridge.utilities.mcnpCreatorFunctions as MCF\n'), ((2626, 2679), 'numpy.allclose', 'np.allclose', (['smearedMaterial.atomDensity', '(0.001214)', '(5)'], {}), '(smearedMaterial.atomDensity, 0.001214, 5)\n', (2637, 2679), True, 'import numpy as np\n'), ((2904, 2937), 'fridge.utilities.mcnpCreatorFunctions.getCoolantWireWrapSmear', 'MCF.getCoolantWireWrapSmear', (['info'], {}), '(info)\n', (2931, 2937), True, 'import fridge.utilities.mcnpCreatorFunctions as MCF\n'), ((3136, 3167), 'fridge.utilities.mcnpCreatorFunctions.getPosition', 'MCF.getPosition', (['"""02A01"""', '(2)', '(10)'], {}), "('02A01', 2, 10)\n", (3151, 3167), True, 'import fridge.utilities.mcnpCreatorFunctions as MCF\n'), ((3346, 3377), 'fridge.utilities.mcnpCreatorFunctions.getPosition', 'MCF.getPosition', (['"""02B01"""', '(2)', '(10)'], {}), "('02B01', 2, 10)\n", (3361, 3377), True, 'import fridge.utilities.mcnpCreatorFunctions as MCF\n'), ((3551, 3582), 'fridge.utilities.mcnpCreatorFunctions.getPosition', 'MCF.getPosition', (['"""02C01"""', '(2)', '(10)'], {}), "('02C01', 2, 10)\n", (3566, 3582), True, 'import fridge.utilities.mcnpCreatorFunctions as MCF\n'), ((3760, 3791), 'fridge.utilities.mcnpCreatorFunctions.getPosition', 'MCF.getPosition', (['"""02D01"""', '(2)', '(10)'], {}), "('02D01', 2, 10)\n", (3775, 3791), True, 'import fridge.utilities.mcnpCreatorFunctions as MCF\n'), ((3970, 4001), 'fridge.utilities.mcnpCreatorFunctions.getPosition', 'MCF.getPosition', (['"""02E01"""', '(2)', '(10)'], {}), "('02E01', 2, 10)\n", (3985, 4001), True, 'import fridge.utilities.mcnpCreatorFunctions as MCF\n'), ((4176, 4207), 'fridge.utilities.mcnpCreatorFunctions.getPosition', 'MCF.getPosition', (['"""02F01"""', '(2)', '(10)'], {}), "('02F01', 2, 10)\n", (4191, 4207), True, 'import fridge.utilities.mcnpCreatorFunctions as MCF\n'), ((4387, 4418), 'fridge.utilities.mcnpCreatorFunctions.getPosition', 'MCF.getPosition', (['"""01A01"""', '(2)', '(10)'], {}), "('01A01', 2, 10)\n", (4402, 4418), True, 'import fridge.utilities.mcnpCreatorFunctions as MCF\n'), ((4534, 4565), 'fridge.utilities.mcnpCreatorFunctions.getPosition', 'MCF.getPosition', (['"""03A02"""', '(2)', '(10)'], {}), "('03A02', 2, 10)\n", (4549, 4565), True, 'import fridge.utilities.mcnpCreatorFunctions as MCF\n'), ((4744, 4775), 'fridge.utilities.mcnpCreatorFunctions.getPosition', 'MCF.getPosition', (['"""03B02"""', '(2)', '(10)'], {}), "('03B02', 2, 10)\n", (4759, 4775), True, 'import fridge.utilities.mcnpCreatorFunctions as MCF\n'), ((4953, 4984), 'fridge.utilities.mcnpCreatorFunctions.getPosition', 'MCF.getPosition', (['"""03C02"""', '(2)', '(10)'], {}), "('03C02', 2, 10)\n", (4968, 4984), True, 'import fridge.utilities.mcnpCreatorFunctions as MCF\n'), ((5160, 5191), 'fridge.utilities.mcnpCreatorFunctions.getPosition', 'MCF.getPosition', (['"""03D02"""', '(2)', '(10)'], {}), "('03D02', 2, 10)\n", (5175, 5191), True, 'import fridge.utilities.mcnpCreatorFunctions as MCF\n'), ((5368, 5399), 'fridge.utilities.mcnpCreatorFunctions.getPosition', 'MCF.getPosition', (['"""03E02"""', '(2)', '(10)'], {}), "('03E02', 2, 10)\n", (5383, 5399), True, 'import fridge.utilities.mcnpCreatorFunctions as MCF\n'), ((5579, 5610), 'fridge.utilities.mcnpCreatorFunctions.getPosition', 'MCF.getPosition', (['"""03F02"""', '(2)', '(10)'], {}), "('03F02', 2, 10)\n", (5594, 5610), True, 'import fridge.utilities.mcnpCreatorFunctions as MCF\n'), ((5789, 5820), 'fridge.utilities.mcnpCreatorFunctions.getPosition', 'MCF.getPosition', (['"""04B03"""', '(2)', '(10)'], {}), "('04B03', 2, 10)\n", (5804, 5820), True, 'import fridge.utilities.mcnpCreatorFunctions as MCF\n'), ((5990, 6015), 'fridge.utilities.mcnpCreatorFunctions.getRCCVolume', 'MCF.getRCCVolume', (['(0.2)', '(10)'], {}), '(0.2, 10)\n', (6006, 6015), True, 'import fridge.utilities.mcnpCreatorFunctions as MCF\n'), ((6027, 6058), 'numpy.allclose', 'np.allclose', (['volume', '(1.25664)', '(5)'], {}), '(volume, 1.25664, 5)\n', (6038, 6058), True, 'import numpy as np\n'), ((6099, 6122), 'fridge.utilities.mcnpCreatorFunctions.getRCCVolume', 'MCF.getRCCVolume', (['(5)', '(10)'], {}), '(5, 10)\n', (6115, 6122), True, 'import fridge.utilities.mcnpCreatorFunctions as MCF\n'), ((6134, 6165), 'numpy.allclose', 'np.allclose', (['volume', '(216.506)', '(5)'], {}), '(volume, 216.506, 5)\n', (6145, 6165), True, 'import numpy as np\n'), ((6211, 6250), 'fridge.utilities.mcnpCreatorFunctions.getToroidalVolume', 'MCF.getToroidalVolume', (['(0.5)', '(0.05)', '(5)', '(10)'], {}), '(0.5, 0.05, 5, 10)\n', (6232, 6250), True, 'import fridge.utilities.mcnpCreatorFunctions as MCF\n'), ((6262, 6293), 'numpy.allclose', 'np.allclose', (['volume', '(1.03631)', '(5)'], {}), '(volume, 1.03631, 5)\n', (6273, 6293), True, 'import numpy as np\n'), ((3055, 3088), 'numpy.allclose', 'np.allclose', (['smearedDict[k]', 'v', '(5)'], {}), '(smearedDict[k], v, 5)\n', (3066, 3088), True, 'import numpy as np\n'), ((3263, 3298), 'numpy.allclose', 'np.allclose', (['knownAPosition[i]', 'pos'], {}), '(knownAPosition[i], pos)\n', (3274, 3298), True, 'import numpy as np\n'), ((3468, 3503), 'numpy.allclose', 'np.allclose', (['knownAPosition[i]', 'pos'], {}), '(knownAPosition[i], pos)\n', (3479, 3503), True, 'import numpy as np\n'), ((3677, 3712), 'numpy.allclose', 'np.allclose', (['knownAPosition[i]', 'pos'], {}), '(knownAPosition[i], pos)\n', (3688, 3712), True, 'import numpy as np\n'), ((3887, 3922), 'numpy.allclose', 'np.allclose', (['knownAPosition[i]', 'pos'], {}), '(knownAPosition[i], pos)\n', (3898, 3922), True, 'import numpy as np\n'), ((4093, 4128), 'numpy.allclose', 'np.allclose', (['knownAPosition[i]', 'pos'], {}), '(knownAPosition[i], pos)\n', (4104, 4128), True, 'import numpy as np\n'), ((4304, 4339), 'numpy.allclose', 'np.allclose', (['knownAPosition[i]', 'pos'], {}), '(knownAPosition[i], pos)\n', (4315, 4339), True, 'import numpy as np\n'), ((4661, 4696), 'numpy.allclose', 'np.allclose', (['knownAPosition[i]', 'pos'], {}), '(knownAPosition[i], pos)\n', (4672, 4696), True, 'import numpy as np\n'), ((4870, 4905), 'numpy.allclose', 'np.allclose', (['knownAPosition[i]', 'pos'], {}), '(knownAPosition[i], pos)\n', (4881, 4905), True, 'import numpy as np\n'), ((5079, 5114), 'numpy.allclose', 'np.allclose', (['knownAPosition[i]', 'pos'], {}), '(knownAPosition[i], pos)\n', (5090, 5114), True, 'import numpy as np\n'), ((5287, 5322), 'numpy.allclose', 'np.allclose', (['knownAPosition[i]', 'pos'], {}), '(knownAPosition[i], pos)\n', (5298, 5322), True, 'import numpy as np\n'), ((5496, 5531), 'numpy.allclose', 'np.allclose', (['knownAPosition[i]', 'pos'], {}), '(knownAPosition[i], pos)\n', (5507, 5531), True, 'import numpy as np\n'), ((5706, 5741), 'numpy.allclose', 'np.allclose', (['knownAPosition[i]', 'pos'], {}), '(knownAPosition[i], pos)\n', (5717, 5741), True, 'import numpy as np\n'), ((5914, 5949), 'numpy.allclose', 'np.allclose', (['knownAPosition[i]', 'pos'], {}), '(knownAPosition[i], pos)\n', (5925, 5949), True, 'import numpy as np\n')]
import numpy as np import matplotlib.pyplot as plt def threshold_convolved_image(convolved_image): tci = np.copy(convolved_image) for i in range(3): m = np.mean(convolved_image[:, :, i]) s = np.std(convolved_image[:, :, i]) thr = m tci[convolved_image[:, :, i] < thr, i] = 0 plt.figure() plt.subplot(2, 2, 1) plt.imshow(tci[:, :, 0]) plt.subplot(2, 2, 2) plt.imshow(tci[:, :, 1]) plt.subplot(2, 2, 3) plt.imshow(tci[:, :, 2]) plt.subplot(2, 2, 4) plt.imshow(np.sum(tci, axis=2)) plt.figure() plt.subplot(2, 2, 1) plt.imshow(convolved_image[:, :, 0]) plt.subplot(2, 2, 2) plt.imshow(convolved_image[:, :, 1]) plt.subplot(2, 2, 3) plt.imshow(convolved_image[:, :, 2]) plt.subplot(2, 2, 4) plt.imshow(np.sum(convolved_image, axis=2)) plt.show() print() ci = np.load('../data/test/ci=0.npy') k = np.load('../data/kernels/kernel=0.npy') plt.figure() plt.subplot(2, 2, 1) plt.imshow(k[:, :, 0]) plt.subplot(2, 2, 2) plt.imshow(k[:, :, 1]) plt.subplot(2, 2, 3) plt.imshow(k[:, :, 2]) threshold_convolved_image(ci)
[ "matplotlib.pyplot.subplot", "numpy.load", "matplotlib.pyplot.show", "numpy.sum", "numpy.copy", "numpy.std", "matplotlib.pyplot.imshow", "matplotlib.pyplot.figure", "numpy.mean" ]
[((883, 915), 'numpy.load', 'np.load', (['"""../data/test/ci=0.npy"""'], {}), "('../data/test/ci=0.npy')\n", (890, 915), True, 'import numpy as np\n'), ((920, 959), 'numpy.load', 'np.load', (['"""../data/kernels/kernel=0.npy"""'], {}), "('../data/kernels/kernel=0.npy')\n", (927, 959), True, 'import numpy as np\n'), ((960, 972), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (970, 972), True, 'import matplotlib.pyplot as plt\n'), ((973, 993), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(2)', '(2)', '(1)'], {}), '(2, 2, 1)\n', (984, 993), True, 'import matplotlib.pyplot as plt\n'), ((994, 1016), 'matplotlib.pyplot.imshow', 'plt.imshow', (['k[:, :, 0]'], {}), '(k[:, :, 0])\n', (1004, 1016), True, 'import matplotlib.pyplot as plt\n'), ((1017, 1037), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(2)', '(2)', '(2)'], {}), '(2, 2, 2)\n', (1028, 1037), True, 'import matplotlib.pyplot as plt\n'), ((1038, 1060), 'matplotlib.pyplot.imshow', 'plt.imshow', (['k[:, :, 1]'], {}), '(k[:, :, 1])\n', (1048, 1060), True, 'import matplotlib.pyplot as plt\n'), ((1061, 1081), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(2)', '(2)', '(3)'], {}), '(2, 2, 3)\n', (1072, 1081), True, 'import matplotlib.pyplot as plt\n'), ((1082, 1104), 'matplotlib.pyplot.imshow', 'plt.imshow', (['k[:, :, 2]'], {}), '(k[:, :, 2])\n', (1092, 1104), True, 'import matplotlib.pyplot as plt\n'), ((112, 136), 'numpy.copy', 'np.copy', (['convolved_image'], {}), '(convolved_image)\n', (119, 136), True, 'import numpy as np\n'), ((325, 337), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (335, 337), True, 'import matplotlib.pyplot as plt\n'), ((342, 362), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(2)', '(2)', '(1)'], {}), '(2, 2, 1)\n', (353, 362), True, 'import matplotlib.pyplot as plt\n'), ((367, 391), 'matplotlib.pyplot.imshow', 'plt.imshow', (['tci[:, :, 0]'], {}), '(tci[:, :, 0])\n', (377, 391), True, 'import matplotlib.pyplot as plt\n'), ((396, 416), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(2)', '(2)', '(2)'], {}), '(2, 2, 2)\n', (407, 416), True, 'import matplotlib.pyplot as plt\n'), ((421, 445), 'matplotlib.pyplot.imshow', 'plt.imshow', (['tci[:, :, 1]'], {}), '(tci[:, :, 1])\n', (431, 445), True, 'import matplotlib.pyplot as plt\n'), ((450, 470), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(2)', '(2)', '(3)'], {}), '(2, 2, 3)\n', (461, 470), True, 'import matplotlib.pyplot as plt\n'), ((475, 499), 'matplotlib.pyplot.imshow', 'plt.imshow', (['tci[:, :, 2]'], {}), '(tci[:, :, 2])\n', (485, 499), True, 'import matplotlib.pyplot as plt\n'), ((504, 524), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(2)', '(2)', '(4)'], {}), '(2, 2, 4)\n', (515, 524), True, 'import matplotlib.pyplot as plt\n'), ((566, 578), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (576, 578), True, 'import matplotlib.pyplot as plt\n'), ((583, 603), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(2)', '(2)', '(1)'], {}), '(2, 2, 1)\n', (594, 603), True, 'import matplotlib.pyplot as plt\n'), ((608, 644), 'matplotlib.pyplot.imshow', 'plt.imshow', (['convolved_image[:, :, 0]'], {}), '(convolved_image[:, :, 0])\n', (618, 644), True, 'import matplotlib.pyplot as plt\n'), ((649, 669), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(2)', '(2)', '(2)'], {}), '(2, 2, 2)\n', (660, 669), True, 'import matplotlib.pyplot as plt\n'), ((674, 710), 'matplotlib.pyplot.imshow', 'plt.imshow', (['convolved_image[:, :, 1]'], {}), '(convolved_image[:, :, 1])\n', (684, 710), True, 'import matplotlib.pyplot as plt\n'), ((715, 735), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(2)', '(2)', '(3)'], {}), '(2, 2, 3)\n', (726, 735), True, 'import matplotlib.pyplot as plt\n'), ((740, 776), 'matplotlib.pyplot.imshow', 'plt.imshow', (['convolved_image[:, :, 2]'], {}), '(convolved_image[:, :, 2])\n', (750, 776), True, 'import matplotlib.pyplot as plt\n'), ((781, 801), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(2)', '(2)', '(4)'], {}), '(2, 2, 4)\n', (792, 801), True, 'import matplotlib.pyplot as plt\n'), ((854, 864), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (862, 864), True, 'import matplotlib.pyplot as plt\n'), ((173, 206), 'numpy.mean', 'np.mean', (['convolved_image[:, :, i]'], {}), '(convolved_image[:, :, i])\n', (180, 206), True, 'import numpy as np\n'), ((219, 251), 'numpy.std', 'np.std', (['convolved_image[:, :, i]'], {}), '(convolved_image[:, :, i])\n', (225, 251), True, 'import numpy as np\n'), ((540, 559), 'numpy.sum', 'np.sum', (['tci'], {'axis': '(2)'}), '(tci, axis=2)\n', (546, 559), True, 'import numpy as np\n'), ((817, 848), 'numpy.sum', 'np.sum', (['convolved_image'], {'axis': '(2)'}), '(convolved_image, axis=2)\n', (823, 848), True, 'import numpy as np\n')]
import copy import warnings from keras import backend as K from keras import activations, regularizers from keras.engine import InputSpec from keras.layers import Recurrent import numpy as np from ...data.instances.text_classification.logical_form_instance import SHIFT_OP, REDUCE2_OP, REDUCE3_OP class TreeCompositionLSTM(Recurrent): ''' Conceptual differences from LSTM: (1) Tree LSTM does not differentiate between x and h, because tree composition is not applied at every time step (it is applied when the input symbol is a reduce) and when it is applied, there is no "current input". (2) Input sequences are not the ones being composed, they are operations on the buffer containing elements corresponding to tokens. There isn't one token per timestep like LSTMs. (3) Single vectors h and c are replaced by a stack and buffer of h and c corresponding to the structure processed so far. (4) Gates are applied on two or three elements at a time depending on the type of reduce. Accordingly there are two classes of gates: G_2 (two elements) and G_3 (three elements) (5) G_2 has two forget gates, for each element that can be forgotten and G_3 has three. Notes ----- This is almost certainly broken. We haven't really used this since it was written, and the port to Keras 2 probably broke things, and we haven't had any motivation to fix it yet. You have been warned. ''' # pylint: disable=invalid-name def __init__(self, units, stack_limit, buffer_ops_limit, initializer='glorot_uniform', forget_bias_initializer='one', activation='tanh', inner_activation='hard_sigmoid', W_regularizer=None, U_regularizer=None, V_regularizer=None, b_regularizer=None, **kwargs): self.stack_limit = stack_limit # buffer_ops_limit is the max of buffer_limit and num_ops. This needs to be one value since # the initial buffer state and the list of operations need to be concatenated before passing # them to TreeCompositionLSTM self.buffer_ops_limit = buffer_ops_limit self.output_dim = units self.initializer = initializer self.forget_bias_initializer = forget_bias_initializer activation = kwargs.get("activation", "tanh") self.activation = activations.get(activation) self.inner_activation = activations.get(inner_activation) # Make two deep copies each of W, U and b since regularizers.get() method modifes them! W2_regularizer = copy.deepcopy(W_regularizer) W3_regularizer = copy.deepcopy(W_regularizer) U2_regularizer = copy.deepcopy(U_regularizer) U3_regularizer = copy.deepcopy(U_regularizer) b2_regularizer = copy.deepcopy(b_regularizer) b3_regularizer = copy.deepcopy(b_regularizer) # W, U and b get two copies of each corresponding regularizer self.W_regularizers = [regularizers.get(W2_regularizer), regularizers.get(W3_regularizer)] \ if W_regularizer else None self.U_regularizers = [regularizers.get(U2_regularizer), regularizers.get(U3_regularizer)] \ if U_regularizer else None self.V_regularizer = regularizers.get(V_regularizer) self.b_regularizers = [regularizers.get(b2_regularizer), regularizers.get(b3_regularizer)] \ if b_regularizer else None # TODO(pradeep): Ensure output_dim = input_dim - 1 self.dropout_W = kwargs["dropout_W"] if "dropout_W" in kwargs else 0. self.dropout_U = kwargs["dropout_U"] if "dropout_U" in kwargs else 0. self.dropout_V = kwargs["dropout_V"] if "dropout_V" in kwargs else 0. if self.dropout_W: self.uses_learning_phase = True # Pass any remaining arguments of the constructor to the super class' constructor super(TreeCompositionLSTM, self).__init__(**kwargs) if self.stateful: warnings.warn("Current implementation cannot be stateful. \ Ignoring stateful=True", RuntimeWarning) self.stateful = False if self.return_sequences: warnings.warn("Current implementation cannot return sequences.\ Ignoring return_sequences=True", RuntimeWarning) self.return_sequences = False def get_initial_states(self, inputs): # The initial buffer is sent into the TreeLSTM as a part of the input. # i.e., inputs is a concatenation of the transitions and the initial buffer. # (batch_size, buffer_limit, output_dim+1) # We will now separate the buffer and the transitions and initialize the # buffer state of the TreeLSTM with the initial buffer value. # The rest of the input is the transitions, which we do not need now. # Take the buffer out. init_h_for_buffer = inputs[:, :, 1:] # (batch_size, buffer_limit, output_dim) # Initializing all c as zeros. init_c_for_buffer = K.zeros_like(init_h_for_buffer) # Each element in the buffer is a concatenation of h and c for the corresponding # node init_buffer = K.concatenate([init_h_for_buffer, init_c_for_buffer], axis=-1) # We need a symbolic all zero tensor of size (samples, stack_limit, 2*output_dim) for # init_stack The problem is the first dim (samples) is a place holder and not an actual # value. So we'll use the following trick temp_state = K.zeros_like(inputs) # (samples, buffer_ops_limit, input_dim) temp_state = K.tile(K.sum(temp_state, axis=(1, 2)), (self.stack_limit, 2*self.output_dim, 1)) # (stack_limit, 2*output_dim, samples) init_stack = K.permute_dimensions(temp_state, (2, 0, 1)) # (samples, stack_limit, 2*output_dim) return [init_buffer, init_stack] def build(self, input_shape): # pylint: disable=attribute-defined-outside-init,redefined-variable-type # Defining two classes of parameters: # 1) predicate, one argument composition (*2_*) # 2) predicate, two arguments composition (*3_*) # # The naming scheme is an extension of the one used # in the LSTM code of Keras. W is a weight and b is a bias # *_i: input gate parameters # *_fp: predicate forget gate parameters # *_fa: argument forget gate parameters (one-arg only) # *_fa1: argument-1 forget gate parameters (two-arg only) # *_fa2: argument-2 forget gate parameters (two-arg only) # *_u: update gate parameters # *_o: output gate parameters # # Predicate, argument composition: # W2_i, W2_fp, W2_fa, W2_o, W2_u # U2_i, U2_fp, U2_fa, U2_o, U2_u # b2_i, b2_fp, b2_fa, b2_o, b2_u # # Predicate, two argument composition: # W3_i, W3_fp, W3_fa1, W3_fa2, W3_o, W3_u # U3_i, U3_fp, U3_fa1, U3_fa2, U3_o, U3_u # V3_i, V3_fp, V3_fa1, V3_fa2, V3_o, V3_u # b3_i, b3_fp, b3_fa1, b3_fa2, b3_o, b3_u self.input_spec = [InputSpec(shape=input_shape)] self.input_dim = input_shape[2] # initial states: buffer and stack. buffer has shape (samples, buff_limit, output_dim); # stack has shape (samples, stack_limit, 2*output_dim) self.states = [None, None] # The first dims in all weight matrices are k * output_dim because of the recursive nature # of treeLSTM if self.implementation == 1: # Input dimensionality for all W2s is output_dim, and there are 5 W2s: i, fp, fa, u, o self.W2 = self.add_weight((self.output_dim, 5 * self.output_dim), name='{}_W2'.format(self.name), initializer=self.initializer) # Input dimensionality for all U2s is output_dim, and there are 5 U2s: i, fp, fa, u, o self.U2 = self.add_weight((self.output_dim, 5 * self.output_dim), name='{}_U2'.format(self.name), initializer=self.initializer) # Input dimensionality for all W3s is output_dim, and there are 6 W2s: i, fp, fa1, fa2, u, o self.W3 = self.add_weight((self.output_dim, 6 * self.output_dim), name='{}_W3'.format(self.name), initializer=self.initializer) # Input dimensionality for all U3s is output_dim, and there are 6 U3s: i, fp, fa1, fa2, u, o self.U3 = self.add_weight((self.output_dim, 6 * self.output_dim), name='{}_U3'.format(self.name), initializer=self.initializer) # Input dimensionality for all V3s is output_dim, and there are 6 V3s: i, fp, fa1, fa2, u, o self.V3 = self.add_weight((self.output_dim, 6 * self.output_dim), name='{}_V3'.format(self.name), initializer=self.initializer) self.b2 = K.variable(np.hstack((np.zeros(self.output_dim), K.get_value(self.add_weight(self.output_dim, initializer=self.forget_bias_initializer)), K.get_value(self.add_weight(self.output_dim, initializer=self.forget_bias_initializer)), np.zeros(self.output_dim), np.zeros(self.output_dim))), name='{}_b2'.format(self.name)) self.b3 = K.variable(np.hstack((np.zeros(self.output_dim), K.get_value(self.add_weight(self.output_dim, initializer=self.forget_bias_initializer)), K.get_value(self.add_weight(self.output_dim, initializer=self.forget_bias_initializer)), K.get_value(self.add_weight(self.output_dim, initializer=self.forget_bias_initializer)), np.zeros(self.output_dim), np.zeros(self.output_dim))), name='{}_b3'.format(self.name)) self.trainable_weights = [self.W2, self.U2, self.W3, self.U3, self.V3, self.b2, self.b3] else: self.W2_i = self.add_weight((self.output_dim, self.output_dim), name='{}_W2_i'.format(self.name), initializer=self.initializer) self.U2_i = self.add_weight((self.output_dim, self.output_dim), name='{}_U2_i'.format(self.name), initializer=self.initializer) self.W3_i = self.add_weight((self.output_dim, self.output_dim), name='{}_W3_i'.format(self.name), initializer=self.initializer) self.U3_i = self.add_weight((self.output_dim, self.output_dim), name='{}_U3_i'.format(self.name), initializer=self.initializer) self.V3_i = self.add_weight((self.output_dim, self.output_dim), name='{}_V3_i'.format(self.name), initializer=self.initializer) self.b2_i = K.zeros((self.output_dim,), name='{}_b2_i'.format(self.name)) self.b3_i = K.zeros((self.output_dim,), name='{}_b3_i'.format(self.name)) self.W2_fp = self.add_weight((self.output_dim, self.output_dim), name='{}_W2_fp'.format(self.name), initializer=self.initializer) self.U2_fp = self.add_weight((self.output_dim, self.output_dim), name='{}_U2_fp'.format(self.name), initializer=self.initializer) self.W2_fa = self.add_weight((self.output_dim, self.output_dim), name='{}_W2_fa'.format(self.name), initializer=self.initializer) self.U2_fa = self.add_weight((self.output_dim, self.output_dim), name='{}_U2_fa'.format(self.name), initializer=self.initializer) self.W3_fp = self.add_weight((self.output_dim, self.output_dim), name='{}_W3_fp'.format(self.name), initializer=self.initializer) self.U3_fp = self.add_weight((self.output_dim, self.output_dim), name='{}_U3_fp'.format(self.name), initializer=self.initializer) self.V3_fp = self.add_weight((self.output_dim, self.output_dim), name='{}_V3_fp'.format(self.name), initializer=self.initializer) self.W3_fa1 = self.add_weight((self.output_dim, self.output_dim), name='{}_W3_fa1'.format(self.name), initializer=self.initializer) self.U3_fa1 = self.add_weight((self.output_dim, self.output_dim), name='{}_U3_fa1'.format(self.name), initializer=self.initializer) self.V3_fa1 = self.add_weight((self.output_dim, self.output_dim), name='{}_V3_fa1'.format(self.name), initializer=self.initializer) self.W3_fa2 = self.add_weight((self.output_dim, self.output_dim), name='{}_W3_fa2'.format(self.name), initializer=self.initializer) self.U3_fa2 = self.add_weight((self.output_dim, self.output_dim), name='{}_U3_fa2'.format(self.name), initializer=self.initializer) self.V3_fa2 = self.add_weight((self.output_dim, self.output_dim), name='{}_V3_fa2'.format(self.name), initializer=self.initializer) self.b2_fp = self.add_weight((self.output_dim,), name='{}_b2_fp'.format(self.name), initializer=self.forget_bias_initializer) self.b2_fa = self.add_weight((self.output_dim,), name='{}_b2_fa'.format(self.name), initializer=self.forget_bias_initializer) self.b3_fp = self.add_weight((self.output_dim,), name='{}_b3_fp'.format(self.name), initializer=self.forget_bias_initializer) self.b3_fa1 = self.add_weight((self.output_dim,), name='{}_b3_fa1'.format(self.name), initializer=self.forget_bias_initializer) self.b3_fa2 = self.add_weight((self.output_dim,), name='{}_b3_fa2'.format(self.name), initializer=self.forget_bias_initializer) self.W2_u = self.add_weight((self.output_dim, self.output_dim), name='{}_W2_u'.format(self.name), initializer=self.initializer) self.U2_u = self.add_weight((self.output_dim, self.output_dim), name='{}_U2_u'.format(self.name), initializer=self.initializer) self.W3_u = self.add_weight((self.output_dim, self.output_dim), name='{}_W3_u'.format(self.name), initializer=self.initializer) self.U3_u = self.add_weight((self.output_dim, self.output_dim), name='{}_U3_u'.format(self.name), initializer=self.initializer) self.V3_u = self.add_weight((self.output_dim, self.output_dim), name='{}_V3_u'.format(self.name), initializer=self.initializer) self.b2_u = K.zeros((self.output_dim,), name='{}_b2_u'.format(self.name)) self.b3_u = K.zeros((self.output_dim,), name='{}_b3_u'.format(self.name)) self.W2_o = self.add_weight((self.output_dim, self.output_dim), name='{}_W2_o'.format(self.name), initializer=self.initializer) self.U2_o = self.add_weight((self.output_dim, self.output_dim), name='{}_U2_o'.format(self.name), initializer=self.initializer) self.W3_o = self.add_weight((self.output_dim, self.output_dim), name='{}_W3_o'.format(self.name), initializer=self.initializer) self.U3_o = self.add_weight((self.output_dim, self.output_dim), name='{}_U3_o'.format(self.name), initializer=self.initializer) self.V3_o = self.add_weight((self.output_dim, self.output_dim), name='{}_V3_o'.format(self.name), initializer=self.initializer) self.b2_o = K.zeros((self.output_dim,), name='{}_b2_o'.format(self.name)) self.b3_o = K.zeros((self.output_dim,), name='{}_b3_o'.format(self.name)) self.W2 = K.concatenate([self.W2_i, self.W2_fp, self.W2_fa, self.W2_u, self.W2_o]) self.U2 = K.concatenate([self.U2_i, self.U2_fp, self.U2_fa, self.U2_u, self.U2_o]) self.W3 = K.concatenate([self.W3_i, self.W3_fp, self.W3_fa1, self.W3_fa2, self.W3_u, self.W3_o]) self.U3 = K.concatenate([self.U3_i, self.U3_fp, self.U3_fa1, self.U3_fa2, self.U3_u, self.U3_o]) self.V3 = K.concatenate([self.V3_i, self.V3_fp, self.V3_fa1, self.V3_fa2, self.V3_u, self.V3_o]) self.b2 = K.concatenate([self.b2_i, self.b2_fp, self.b2_fa, self.b2_u, self.b2_o]) self.b3 = K.concatenate([self.b3_i, self.b3_fp, self.b3_fa1, self.b3_fa2, self.b3_u, self.b3_o]) self.regularizers = [] if self.W_regularizers: self.W_regularizers[0].set_param(self.W2) self.W_regularizers[1].set_param(self.W3) self.regularizers.extend(self.W_regularizers) if self.U_regularizers: self.U_regularizers[0].set_param(self.U2) self.U_regularizers[1].set_param(self.U3) self.regularizers.extend(self.U_regularizers) if self.V_regularizer: self.V_regularizer.set_param(self.V3) self.regularizers.append(self.V_regularizer) if self.b_regularizers: self.b_regularizers[0].set_param(self.b2) self.b_regularizers[1].set_param(self.b3) self.regularizers.extend(self.b_regularizers) self.built = True def _one_arg_compose(self, pred_arg): # pred_arg: Tensors of size (batch_size, 2, dim) where # pred_arg[:,0,:] are arg vectors (h,c) of all samples # pred_arg[:,1,:] are pred vectors (h,c) of all samples pred_h = pred_arg[:, 1, :self.output_dim] pred_c = pred_arg[:, 1, self.output_dim:] arg_h = pred_arg[:, 0, :self.output_dim] arg_c = pred_arg[:, 0, self.output_dim:] if self.implementation == 1: # To optimize for GPU, we would want to make fewer # matrix multiplications, but with bigger matrices. # So we compute outputs of all gates simultaneously # using the concatenated operators W2, U2 abd b2 z_all_gates = K.dot(pred_h, self.W2) + K.dot(arg_h, self.U2) + self.b2 # (batch_size, 5*output_dim) # Now picking the appropriate parts for each gate. # All five zs are of shape (batch_size, output_dim) z_i = z_all_gates[:, :self.output_dim] z_fp = z_all_gates[:, self.output_dim: 2*self.output_dim] z_fa = z_all_gates[:, 2*self.output_dim: 3*self.output_dim] z_u = z_all_gates[:, 3*self.output_dim: 4*self.output_dim] z_o = z_all_gates[:, 4*self.output_dim: 5*self.output_dim] else: # We are optimizing for memory. Smaller matrices, and # more computations. So we use the non-concatenated # operators W2_i, U2_i, .. z_i = K.dot(pred_h, self.W2_i) + K.dot(arg_h, self.U2_i) + self.b2_i z_fp = K.dot(pred_h, self.W2_fp) + K.dot(arg_h, self.U2_fp) + self.b2_fp z_fa = K.dot(pred_h, self.W2_fa) + K.dot(arg_h, self.U2_fa) + self.b2_fa z_u = K.dot(pred_h, self.W2_u) + K.dot(arg_h, self.U2_u) + self.b2_u z_o = K.dot(pred_h, self.W2_o) + K.dot(arg_h, self.U2_o) + self.b2_o # Applying non-linearity to get outputs of each gate i = self.inner_activation(z_i) fp = self.inner_activation(z_fp) fa = self.inner_activation(z_fa) u = self.inner_activation(z_u) c = (i * u) + (fp * pred_c) + (fa * arg_c) o = self.inner_activation(z_o) # Calculate the composition output. SPINN does not have a non-linearity in the # following computation, but the original LSTM does. h = o * self.activation(c) # Finally return the composed representation for the stack, adding a time # dimension and make number of dimensions same as the input # to this function return K.expand_dims(K.concatenate([h, c]), 1) def _two_arg_compose(self, pred_args): # pred_args: Matrix of size (samples, 3, dim) where # pred_args[:,0,:] are arg2 vectors (h,c) of all samples # pred_args[:,1,:] are arg1 vectors (h,c) of all samples # pred_args[:,2,:] are pred vectors (h,c) of all samples # This function is analogous to _one_arg_compose, except that it operates on # two args instead of one. Accordingly, the operators are W3, U3, V3 and b3 # instead of W2, U2 and b2 pred_h = pred_args[:, 2, :self.output_dim] pred_c = pred_args[:, 2, self.output_dim:] arg1_h = pred_args[:, 1, :self.output_dim] arg1_c = pred_args[:, 1, self.output_dim:] arg2_h = pred_args[:, 0, :self.output_dim] arg2_c = pred_args[:, 0, self.output_dim:] if self.implementation == 1: z_all_gates = K.dot(pred_h, self.W3) + K.dot(arg1_h, self.U3) + \ K.dot(arg2_h, self.V3) + self.b3 # (batch_size, 6*output_dim) z_i = z_all_gates[:, :self.output_dim] z_fp = z_all_gates[:, self.output_dim: 2*self.output_dim] z_fa1 = z_all_gates[:, 2*self.output_dim: 3*self.output_dim] z_fa2 = z_all_gates[:, 3*self.output_dim: 4*self.output_dim] z_u = z_all_gates[:, 4*self.output_dim: 5*self.output_dim] z_o = z_all_gates[:, 5*self.output_dim: 6*self.output_dim] else: z_i = K.dot(pred_h, self.W3_i) + K.dot(arg1_h, self.U3_i) + \ K.dot(arg2_h, self.V3_i) + self.b3_i z_fp = K.dot(pred_h, self.W3_fp) + K.dot(arg1_h, self.U3_fp) + \ K.dot(arg2_h, self.V3_fp) + self.b3_fp z_fa1 = K.dot(pred_h, self.W3_fa1) + K.dot(arg1_h, self.U3_fa1) + \ K.dot(arg2_h, self.V3_fa1) + self.b3_fa1 z_fa2 = K.dot(pred_h, self.W3_fa2) + K.dot(arg1_h, self.U3_fa2) + \ K.dot(arg2_h, self.V3_fa2) + self.b3_fa2 z_u = K.dot(pred_h, self.W3_u) + K.dot(arg1_h, self.U3_u) + \ K.dot(arg2_h, self.V3_u) + self.b3_u z_o = K.dot(pred_h, self.W3_o) + K.dot(arg1_h, self.U3_o) + \ K.dot(arg2_h, self.V3_o) + self.b3_o i = self.inner_activation(z_i) fp = self.inner_activation(z_fp) fa1 = self.inner_activation(z_fa1) fa2 = self.inner_activation(z_fa2) u = self.inner_activation(z_u) c = (i * u) + (fp * pred_c) + (fa1 * arg1_c) + (fa2 * arg2_c) o = self.inner_activation(z_o) h = o * self.activation(c) return K.expand_dims(K.concatenate([h, c]), 1) def step(self, inputs, states): # This function is called at each timestep. Before calling this, Keras' rnn # dimshuffles the input to have time as the leading dimension, and iterates over # it So, # inputs: (samples, input_dim) = (samples, x_op + <current timestep's buffer input>) # # We do not need the current timestep's buffer input here, since the buffer # state is the one that's relevant. We just want the current op from inputs. buff = states[0] # Current state of buffer stack = states[1] # Current state of stack step_ops = inputs[:, 0] #(samples, 1), current ops for all samples. # We need to make tensors from the ops vectors, one to apply to all dimensions # of stack, and the other for the buffer. # For the stack: # Note stack's dimensionality is 2*output_dim because it holds both h and c stack_tiled_step_ops = K.permute_dimensions( K.tile(step_ops, (self.stack_limit, 2 * self.output_dim, 1)), (2, 0, 1)) # (samples, stack_limit, 2*dim) # For the buffer: buff_tiled_step_ops = K.permute_dimensions( K.tile(step_ops, (self.buffer_ops_limit, 2 * self.output_dim, 1)), (2, 0, 1)) # (samples, buff_len, 2*dim) shifted_stack = K.concatenate([buff[:, :1], stack], axis=1)[:, :self.stack_limit] one_reduced_stack = K.concatenate([self._one_arg_compose(stack[:, :2]), stack[:, 2:], K.zeros_like(stack)[:, :1]], axis=1) two_reduced_stack = K.concatenate([self._two_arg_compose(stack[:, :3]), stack[:, 3:], K.zeros_like(stack)[:, :2]], axis=1) shifted_buff = K.concatenate([buff[:, 1:], K.zeros_like(buff)[:, :1]], axis=1) stack = K.switch(K.equal(stack_tiled_step_ops, SHIFT_OP), shifted_stack, stack) stack = K.switch(K.equal(stack_tiled_step_ops, REDUCE2_OP), one_reduced_stack, stack) stack = K.switch(K.equal(stack_tiled_step_ops, REDUCE3_OP), two_reduced_stack, stack) buff = K.switch(K.equal(buff_tiled_step_ops, SHIFT_OP), shifted_buff, buff) stack_top_h = stack[:, 0, :self.output_dim] # first half of the top element for all samples return stack_top_h, [buff, stack] def get_constants(self, inputs, training=None): # TODO(pradeep): The function in the LSTM implementation produces dropout multipliers # to apply on the input if dropout is applied on the weights W and U. Ignoring # dropout for now. constants = [] if 0 < self.dropout_W < 1 or 0 < self.dropout_U < 1 or 0 < self.dropout_V < 1: warnings.warn("Weight dropout not implemented yet. Ignoring them.", RuntimeWarning) return constants def get_config(self): # This function is called to get the model configuration while serializing it # Essentially has all the arguments in the __init__ method as a dict. config = {'stack_limit': self.stack_limit, 'buffer_ops_limit': self.buffer_ops_limit, 'output_dim': self.output_dim, 'initializer': self.initializer, 'forget_bias_initializer': self.forget_bias_initializer, 'activation': self.activation.__name__, # pylint: disable=no-member 'inner_activation': self.inner_activation.__name__, # pylint: disable=no-member 'W_regularizer': self.W_regularizers[0].get_config() if self.W_regularizers else None, 'U_regularizer': self.U_regularizers[0].get_config() if self.U_regularizers else None, 'V_regularizer': self.V_regularizer.get_config() if self.V_regularizer else None, 'b_regularizer': self.b_regularizers[0].get_config() if self.b_regularizers else None, 'dropout_W': self.dropout_W, 'dropout_U': self.dropout_U, 'dropout_V': self.dropout_V} base_config = super(TreeCompositionLSTM, self).get_config() return dict(list(base_config.items()) + list(config.items()))
[ "keras.backend.dot", "copy.deepcopy", "keras.backend.concatenate", "keras.activations.get", "keras.regularizers.get", "keras.backend.zeros_like", "keras.backend.sum", "numpy.zeros", "keras.backend.equal", "keras.backend.tile", "keras.engine.InputSpec", "warnings.warn", "keras.backend.permute_dimensions" ]
[((2554, 2581), 'keras.activations.get', 'activations.get', (['activation'], {}), '(activation)\n', (2569, 2581), False, 'from keras import activations, regularizers\n'), ((2614, 2647), 'keras.activations.get', 'activations.get', (['inner_activation'], {}), '(inner_activation)\n', (2629, 2647), False, 'from keras import activations, regularizers\n'), ((2769, 2797), 'copy.deepcopy', 'copy.deepcopy', (['W_regularizer'], {}), '(W_regularizer)\n', (2782, 2797), False, 'import copy\n'), ((2823, 2851), 'copy.deepcopy', 'copy.deepcopy', (['W_regularizer'], {}), '(W_regularizer)\n', (2836, 2851), False, 'import copy\n'), ((2877, 2905), 'copy.deepcopy', 'copy.deepcopy', (['U_regularizer'], {}), '(U_regularizer)\n', (2890, 2905), False, 'import copy\n'), ((2931, 2959), 'copy.deepcopy', 'copy.deepcopy', (['U_regularizer'], {}), '(U_regularizer)\n', (2944, 2959), False, 'import copy\n'), ((2985, 3013), 'copy.deepcopy', 'copy.deepcopy', (['b_regularizer'], {}), '(b_regularizer)\n', (2998, 3013), False, 'import copy\n'), ((3039, 3067), 'copy.deepcopy', 'copy.deepcopy', (['b_regularizer'], {}), '(b_regularizer)\n', (3052, 3067), False, 'import copy\n'), ((3455, 3486), 'keras.regularizers.get', 'regularizers.get', (['V_regularizer'], {}), '(V_regularizer)\n', (3471, 3486), False, 'from keras import activations, regularizers\n'), ((5234, 5265), 'keras.backend.zeros_like', 'K.zeros_like', (['init_h_for_buffer'], {}), '(init_h_for_buffer)\n', (5246, 5265), True, 'from keras import backend as K\n'), ((5393, 5455), 'keras.backend.concatenate', 'K.concatenate', (['[init_h_for_buffer, init_c_for_buffer]'], {'axis': '(-1)'}), '([init_h_for_buffer, init_c_for_buffer], axis=-1)\n', (5406, 5455), True, 'from keras import backend as K\n'), ((5717, 5737), 'keras.backend.zeros_like', 'K.zeros_like', (['inputs'], {}), '(inputs)\n', (5729, 5737), True, 'from keras import backend as K\n'), ((5971, 6014), 'keras.backend.permute_dimensions', 'K.permute_dimensions', (['temp_state', '(2, 0, 1)'], {}), '(temp_state, (2, 0, 1))\n', (5991, 6014), True, 'from keras import backend as K\n'), ((4185, 4313), 'warnings.warn', 'warnings.warn', (['"""Current implementation cannot be stateful. Ignoring stateful=True"""', 'RuntimeWarning'], {}), "(\n 'Current implementation cannot be stateful. Ignoring stateful=True'\n , RuntimeWarning)\n", (4198, 4313), False, 'import warnings\n'), ((4386, 4526), 'warnings.warn', 'warnings.warn', (['"""Current implementation cannot return sequences. Ignoring return_sequences=True"""', 'RuntimeWarning'], {}), "(\n 'Current implementation cannot return sequences. Ignoring return_sequences=True'\n , RuntimeWarning)\n", (4399, 4526), False, 'import warnings\n'), ((5808, 5838), 'keras.backend.sum', 'K.sum', (['temp_state'], {'axis': '(1, 2)'}), '(temp_state, axis=(1, 2))\n', (5813, 5838), True, 'from keras import backend as K\n'), ((7326, 7354), 'keras.engine.InputSpec', 'InputSpec', ([], {'shape': 'input_shape'}), '(shape=input_shape)\n', (7335, 7354), False, 'from keras.engine import InputSpec\n'), ((18533, 18605), 'keras.backend.concatenate', 'K.concatenate', (['[self.W2_i, self.W2_fp, self.W2_fa, self.W2_u, self.W2_o]'], {}), '([self.W2_i, self.W2_fp, self.W2_fa, self.W2_u, self.W2_o])\n', (18546, 18605), True, 'from keras import backend as K\n'), ((18628, 18700), 'keras.backend.concatenate', 'K.concatenate', (['[self.U2_i, self.U2_fp, self.U2_fa, self.U2_u, self.U2_o]'], {}), '([self.U2_i, self.U2_fp, self.U2_fa, self.U2_u, self.U2_o])\n', (18641, 18700), True, 'from keras import backend as K\n'), ((18723, 18813), 'keras.backend.concatenate', 'K.concatenate', (['[self.W3_i, self.W3_fp, self.W3_fa1, self.W3_fa2, self.W3_u, self.W3_o]'], {}), '([self.W3_i, self.W3_fp, self.W3_fa1, self.W3_fa2, self.W3_u,\n self.W3_o])\n', (18736, 18813), True, 'from keras import backend as K\n'), ((18832, 18922), 'keras.backend.concatenate', 'K.concatenate', (['[self.U3_i, self.U3_fp, self.U3_fa1, self.U3_fa2, self.U3_u, self.U3_o]'], {}), '([self.U3_i, self.U3_fp, self.U3_fa1, self.U3_fa2, self.U3_u,\n self.U3_o])\n', (18845, 18922), True, 'from keras import backend as K\n'), ((18941, 19031), 'keras.backend.concatenate', 'K.concatenate', (['[self.V3_i, self.V3_fp, self.V3_fa1, self.V3_fa2, self.V3_u, self.V3_o]'], {}), '([self.V3_i, self.V3_fp, self.V3_fa1, self.V3_fa2, self.V3_u,\n self.V3_o])\n', (18954, 19031), True, 'from keras import backend as K\n'), ((19050, 19122), 'keras.backend.concatenate', 'K.concatenate', (['[self.b2_i, self.b2_fp, self.b2_fa, self.b2_u, self.b2_o]'], {}), '([self.b2_i, self.b2_fp, self.b2_fa, self.b2_u, self.b2_o])\n', (19063, 19122), True, 'from keras import backend as K\n'), ((19145, 19235), 'keras.backend.concatenate', 'K.concatenate', (['[self.b3_i, self.b3_fp, self.b3_fa1, self.b3_fa2, self.b3_u, self.b3_o]'], {}), '([self.b3_i, self.b3_fp, self.b3_fa1, self.b3_fa2, self.b3_u,\n self.b3_o])\n', (19158, 19235), True, 'from keras import backend as K\n'), ((22619, 22640), 'keras.backend.concatenate', 'K.concatenate', (['[h, c]'], {}), '([h, c])\n', (22632, 22640), True, 'from keras import backend as K\n'), ((25270, 25291), 'keras.backend.concatenate', 'K.concatenate', (['[h, c]'], {}), '([h, c])\n', (25283, 25291), True, 'from keras import backend as K\n'), ((26291, 26351), 'keras.backend.tile', 'K.tile', (['step_ops', '(self.stack_limit, 2 * self.output_dim, 1)'], {}), '(step_ops, (self.stack_limit, 2 * self.output_dim, 1))\n', (26297, 26351), True, 'from keras import backend as K\n'), ((26508, 26573), 'keras.backend.tile', 'K.tile', (['step_ops', '(self.buffer_ops_limit, 2 * self.output_dim, 1)'], {}), '(step_ops, (self.buffer_ops_limit, 2 * self.output_dim, 1))\n', (26514, 26573), True, 'from keras import backend as K\n'), ((26657, 26700), 'keras.backend.concatenate', 'K.concatenate', (['[buff[:, :1], stack]'], {'axis': '(1)'}), '([buff[:, :1], stack], axis=1)\n', (26670, 26700), True, 'from keras import backend as K\n'), ((27354, 27393), 'keras.backend.equal', 'K.equal', (['stack_tiled_step_ops', 'SHIFT_OP'], {}), '(stack_tiled_step_ops, SHIFT_OP)\n', (27361, 27393), True, 'from keras import backend as K\n'), ((27442, 27483), 'keras.backend.equal', 'K.equal', (['stack_tiled_step_ops', 'REDUCE2_OP'], {}), '(stack_tiled_step_ops, REDUCE2_OP)\n', (27449, 27483), True, 'from keras import backend as K\n'), ((27536, 27577), 'keras.backend.equal', 'K.equal', (['stack_tiled_step_ops', 'REDUCE3_OP'], {}), '(stack_tiled_step_ops, REDUCE3_OP)\n', (27543, 27577), True, 'from keras import backend as K\n'), ((27629, 27667), 'keras.backend.equal', 'K.equal', (['buff_tiled_step_ops', 'SHIFT_OP'], {}), '(buff_tiled_step_ops, SHIFT_OP)\n', (27636, 27667), True, 'from keras import backend as K\n'), ((28216, 28303), 'warnings.warn', 'warnings.warn', (['"""Weight dropout not implemented yet. Ignoring them."""', 'RuntimeWarning'], {}), "('Weight dropout not implemented yet. Ignoring them.',\n RuntimeWarning)\n", (28229, 28303), False, 'import warnings\n'), ((3169, 3201), 'keras.regularizers.get', 'regularizers.get', (['W2_regularizer'], {}), '(W2_regularizer)\n', (3185, 3201), False, 'from keras import activations, regularizers\n'), ((3203, 3235), 'keras.regularizers.get', 'regularizers.get', (['W3_regularizer'], {}), '(W3_regularizer)\n', (3219, 3235), False, 'from keras import activations, regularizers\n'), ((3313, 3345), 'keras.regularizers.get', 'regularizers.get', (['U2_regularizer'], {}), '(U2_regularizer)\n', (3329, 3345), False, 'from keras import activations, regularizers\n'), ((3347, 3379), 'keras.regularizers.get', 'regularizers.get', (['U3_regularizer'], {}), '(U3_regularizer)\n', (3363, 3379), False, 'from keras import activations, regularizers\n'), ((3518, 3550), 'keras.regularizers.get', 'regularizers.get', (['b2_regularizer'], {}), '(b2_regularizer)\n', (3534, 3550), False, 'from keras import activations, regularizers\n'), ((3552, 3584), 'keras.regularizers.get', 'regularizers.get', (['b3_regularizer'], {}), '(b3_regularizer)\n', (3568, 3584), False, 'from keras import activations, regularizers\n'), ((20769, 20791), 'keras.backend.dot', 'K.dot', (['pred_h', 'self.W2'], {}), '(pred_h, self.W2)\n', (20774, 20791), True, 'from keras import backend as K\n'), ((20794, 20815), 'keras.backend.dot', 'K.dot', (['arg_h', 'self.U2'], {}), '(arg_h, self.U2)\n', (20799, 20815), True, 'from keras import backend as K\n'), ((21521, 21545), 'keras.backend.dot', 'K.dot', (['pred_h', 'self.W2_i'], {}), '(pred_h, self.W2_i)\n', (21526, 21545), True, 'from keras import backend as K\n'), ((21548, 21571), 'keras.backend.dot', 'K.dot', (['arg_h', 'self.U2_i'], {}), '(arg_h, self.U2_i)\n', (21553, 21571), True, 'from keras import backend as K\n'), ((21603, 21628), 'keras.backend.dot', 'K.dot', (['pred_h', 'self.W2_fp'], {}), '(pred_h, self.W2_fp)\n', (21608, 21628), True, 'from keras import backend as K\n'), ((21631, 21655), 'keras.backend.dot', 'K.dot', (['arg_h', 'self.U2_fp'], {}), '(arg_h, self.U2_fp)\n', (21636, 21655), True, 'from keras import backend as K\n'), ((21688, 21713), 'keras.backend.dot', 'K.dot', (['pred_h', 'self.W2_fa'], {}), '(pred_h, self.W2_fa)\n', (21693, 21713), True, 'from keras import backend as K\n'), ((21716, 21740), 'keras.backend.dot', 'K.dot', (['arg_h', 'self.U2_fa'], {}), '(arg_h, self.U2_fa)\n', (21721, 21740), True, 'from keras import backend as K\n'), ((21772, 21796), 'keras.backend.dot', 'K.dot', (['pred_h', 'self.W2_u'], {}), '(pred_h, self.W2_u)\n', (21777, 21796), True, 'from keras import backend as K\n'), ((21799, 21822), 'keras.backend.dot', 'K.dot', (['arg_h', 'self.U2_u'], {}), '(arg_h, self.U2_u)\n', (21804, 21822), True, 'from keras import backend as K\n'), ((21853, 21877), 'keras.backend.dot', 'K.dot', (['pred_h', 'self.W2_o'], {}), '(pred_h, self.W2_o)\n', (21858, 21877), True, 'from keras import backend as K\n'), ((21880, 21903), 'keras.backend.dot', 'K.dot', (['arg_h', 'self.U2_o'], {}), '(arg_h, self.U2_o)\n', (21885, 21903), True, 'from keras import backend as K\n'), ((23590, 23612), 'keras.backend.dot', 'K.dot', (['arg2_h', 'self.V3'], {}), '(arg2_h, self.V3)\n', (23595, 23612), True, 'from keras import backend as K\n'), ((24172, 24196), 'keras.backend.dot', 'K.dot', (['arg2_h', 'self.V3_i'], {}), '(arg2_h, self.V3_i)\n', (24177, 24196), True, 'from keras import backend as K\n'), ((24306, 24331), 'keras.backend.dot', 'K.dot', (['arg2_h', 'self.V3_fp'], {}), '(arg2_h, self.V3_fp)\n', (24311, 24331), True, 'from keras import backend as K\n'), ((24445, 24471), 'keras.backend.dot', 'K.dot', (['arg2_h', 'self.V3_fa1'], {}), '(arg2_h, self.V3_fa1)\n', (24450, 24471), True, 'from keras import backend as K\n'), ((24586, 24612), 'keras.backend.dot', 'K.dot', (['arg2_h', 'self.V3_fa2'], {}), '(arg2_h, self.V3_fa2)\n', (24591, 24612), True, 'from keras import backend as K\n'), ((24721, 24745), 'keras.backend.dot', 'K.dot', (['arg2_h', 'self.V3_u'], {}), '(arg2_h, self.V3_u)\n', (24726, 24745), True, 'from keras import backend as K\n'), ((24852, 24876), 'keras.backend.dot', 'K.dot', (['arg2_h', 'self.V3_o'], {}), '(arg2_h, self.V3_o)\n', (24857, 24876), True, 'from keras import backend as K\n'), ((26903, 26922), 'keras.backend.zeros_like', 'K.zeros_like', (['stack'], {}), '(stack)\n', (26915, 26922), True, 'from keras import backend as K\n'), ((27162, 27181), 'keras.backend.zeros_like', 'K.zeros_like', (['stack'], {}), '(stack)\n', (27174, 27181), True, 'from keras import backend as K\n'), ((27292, 27310), 'keras.backend.zeros_like', 'K.zeros_like', (['buff'], {}), '(buff)\n', (27304, 27310), True, 'from keras import backend as K\n'), ((9198, 9223), 'numpy.zeros', 'np.zeros', (['self.output_dim'], {}), '(self.output_dim)\n', (9206, 9223), True, 'import numpy as np\n'), ((9679, 9704), 'numpy.zeros', 'np.zeros', (['self.output_dim'], {}), '(self.output_dim)\n', (9687, 9704), True, 'import numpy as np\n'), ((9750, 9775), 'numpy.zeros', 'np.zeros', (['self.output_dim'], {}), '(self.output_dim)\n', (9758, 9775), True, 'import numpy as np\n'), ((9888, 9913), 'numpy.zeros', 'np.zeros', (['self.output_dim'], {}), '(self.output_dim)\n', (9896, 9913), True, 'import numpy as np\n'), ((10574, 10599), 'numpy.zeros', 'np.zeros', (['self.output_dim'], {}), '(self.output_dim)\n', (10582, 10599), True, 'import numpy as np\n'), ((10645, 10670), 'numpy.zeros', 'np.zeros', (['self.output_dim'], {}), '(self.output_dim)\n', (10653, 10670), True, 'import numpy as np\n'), ((23518, 23540), 'keras.backend.dot', 'K.dot', (['pred_h', 'self.W3'], {}), '(pred_h, self.W3)\n', (23523, 23540), True, 'from keras import backend as K\n'), ((23543, 23565), 'keras.backend.dot', 'K.dot', (['arg1_h', 'self.U3'], {}), '(arg1_h, self.U3)\n', (23548, 23565), True, 'from keras import backend as K\n'), ((24096, 24120), 'keras.backend.dot', 'K.dot', (['pred_h', 'self.W3_i'], {}), '(pred_h, self.W3_i)\n', (24101, 24120), True, 'from keras import backend as K\n'), ((24123, 24147), 'keras.backend.dot', 'K.dot', (['arg1_h', 'self.U3_i'], {}), '(arg1_h, self.U3_i)\n', (24128, 24147), True, 'from keras import backend as K\n'), ((24228, 24253), 'keras.backend.dot', 'K.dot', (['pred_h', 'self.W3_fp'], {}), '(pred_h, self.W3_fp)\n', (24233, 24253), True, 'from keras import backend as K\n'), ((24256, 24281), 'keras.backend.dot', 'K.dot', (['arg1_h', 'self.U3_fp'], {}), '(arg1_h, self.U3_fp)\n', (24261, 24281), True, 'from keras import backend as K\n'), ((24365, 24391), 'keras.backend.dot', 'K.dot', (['pred_h', 'self.W3_fa1'], {}), '(pred_h, self.W3_fa1)\n', (24370, 24391), True, 'from keras import backend as K\n'), ((24394, 24420), 'keras.backend.dot', 'K.dot', (['arg1_h', 'self.U3_fa1'], {}), '(arg1_h, self.U3_fa1)\n', (24399, 24420), True, 'from keras import backend as K\n'), ((24506, 24532), 'keras.backend.dot', 'K.dot', (['pred_h', 'self.W3_fa2'], {}), '(pred_h, self.W3_fa2)\n', (24511, 24532), True, 'from keras import backend as K\n'), ((24535, 24561), 'keras.backend.dot', 'K.dot', (['arg1_h', 'self.U3_fa2'], {}), '(arg1_h, self.U3_fa2)\n', (24540, 24561), True, 'from keras import backend as K\n'), ((24645, 24669), 'keras.backend.dot', 'K.dot', (['pred_h', 'self.W3_u'], {}), '(pred_h, self.W3_u)\n', (24650, 24669), True, 'from keras import backend as K\n'), ((24672, 24696), 'keras.backend.dot', 'K.dot', (['arg1_h', 'self.U3_u'], {}), '(arg1_h, self.U3_u)\n', (24677, 24696), True, 'from keras import backend as K\n'), ((24776, 24800), 'keras.backend.dot', 'K.dot', (['pred_h', 'self.W3_o'], {}), '(pred_h, self.W3_o)\n', (24781, 24800), True, 'from keras import backend as K\n'), ((24803, 24827), 'keras.backend.dot', 'K.dot', (['arg1_h', 'self.U3_o'], {}), '(arg1_h, self.U3_o)\n', (24808, 24827), True, 'from keras import backend as K\n')]
#!/usr/bin/env python # -*- coding: utf-8 -*- '''checkplotserver_handlers.py - <NAME> (<EMAIL>) - Jan 2017 These are Tornado handlers for serving checkplots and operating on them. ''' #################### ## SYSTEM IMPORTS ## #################### import os import os.path import gzip try: import cPickle as pickle except: import pickle import base64 import hashlib import logging from datetime import time import time from functools import reduce try: from cStringIO import StringIO as strio except: from io import BytesIO as strio import numpy as np from numpy import ndarray ###################################### ## CUSTOM JSON ENCODER FOR FRONTEND ## ###################################### # we need this to send objects with the following types to the frontend: # - bytes # - ndarray import json class FrontendEncoder(json.JSONEncoder): def default(self, obj): if isinstance(obj, np.ndarray): return obj.tolist() elif isinstance(obj, bytes): return obj.decode() elif isinstance(obj, complex): return (obj.real, obj.imag) elif (isinstance(obj, (float, np.float64, np.float_)) and not np.isfinite(obj)): return None elif isinstance(obj, (np.int8, np.int16, np.int32, np.int64)): return int(obj) else: return json.JSONEncoder.default(self, obj) # this replaces the default encoder and makes it so Tornado will do the right # thing when it converts dicts to JSON when a # tornado.web.RequestHandler.write(dict) is called. json._default_encoder = FrontendEncoder() ############# ## LOGGING ## ############# # get a logger LOGGER = logging.getLogger(__name__) ##################### ## TORNADO IMPORTS ## ##################### import tornado.ioloop import tornado.httpserver import tornado.web from tornado.escape import xhtml_escape, xhtml_unescape, url_unescape from tornado import gen ################### ## LOCAL IMPORTS ## ################### from .. import lcmath lcmath.set_logger_parent(__name__) from .. import checkplot checkplot.set_logger_parent(__name__) from ..checkplot import checkplot_pickle_update, checkplot_pickle_to_png, \ _read_checkplot_picklefile, _base64_to_file, _write_checkplot_picklefile # import these for updating plots due to user input from ..checkplot import _pkl_finder_objectinfo, _pkl_periodogram, \ _pkl_magseries_plot, _pkl_phased_magseries_plot from ..varclass import varfeatures varfeatures.set_logger_parent(__name__) from ..varbase import lcfit lcfit.set_logger_parent(__name__) from ..varbase import signals signals.set_logger_parent(__name__) from ..periodbase import zgls zgls.set_logger_parent(__name__) from ..periodbase import saov saov.set_logger_parent(__name__) from ..periodbase import smav smav.set_logger_parent(__name__) from ..periodbase import spdm spdm.set_logger_parent(__name__) from ..periodbase import kbls kbls.set_logger_parent(__name__) from ..periodbase import macf macf.set_logger_parent(__name__) ####################### ## UTILITY FUNCTIONS ## ####################### # this is the function map for arguments CPTOOLMAP = { # this is a special tool to remove all unsaved lctool results from the # current checkplot pickle 'lctool-reset':{ 'args':(), 'argtypes':(), 'kwargs':(), 'kwargtypes':(), 'kwargdefs':(), 'func':None, 'resloc':[], }, # this is a special tool to get all unsaved lctool results from the # current checkplot pickle 'lctool-results':{ 'args':(), 'argtypes':(), 'kwargs':(), 'kwargtypes':(), 'kwargdefs':(), 'func':None, 'resloc':[], }, ## PERIOD SEARCH METHODS ## 'psearch-gls':{ 'args':('times','mags','errs'), 'argtypes':(ndarray, ndarray, ndarray), 'kwargs':('startp','endp','magsarefluxes', 'autofreq','stepsize','nbestpeaks', 'sigclip[]', 'lctimefilters', 'lcmagfilters','periodepsilon'), 'kwargtypes':(float, float, bool, bool, float, int, list, str, str, float), 'kwargdefs':(None, None, False, True, 1.0e-4, 10, None, None, None, 0.1), 'func':zgls.pgen_lsp, 'resloc':['gls'], }, 'psearch-bls':{ 'args':('times','mags','errs'), 'argtypes':(ndarray, ndarray, ndarray), 'kwargs':('startp','endp','magsarefluxes', 'autofreq','stepsize','nbestpeaks', 'sigclip[]','lctimefilters','lcmagfilters', 'periodepsilon','mintransitduration','maxtransitduration'), 'kwargtypes':(float, float, bool, bool, float, int, list, str, str, float, float, float), 'kwargdefs':(0.1, 100.0, False, True, 1.0e-4, 10, None, None, None, 0.1, 0.01, 0.08), 'func':kbls.bls_parallel_pfind, 'resloc':['bls'], }, 'psearch-pdm':{ 'args':('times','mags','errs'), 'argtypes':(ndarray, ndarray, ndarray), 'kwargs':('startp','endp','magsarefluxes', 'autofreq','stepsize','nbestpeaks', 'sigclip[]','lctimefilters','lcmagfilters', 'periodepsilon','phasebinsize','mindetperbin'), 'kwargtypes':(float, float, bool, bool, float, int, list, str, str, float, float, int), 'kwargdefs':(None, None, False, True, 1.0e-4, 10, None, None, None, 0.1, 0.05, 9), 'func':spdm.stellingwerf_pdm, 'resloc':['pdm'], }, 'psearch-aov':{ 'args':('times','mags','errs'), 'argtypes':(ndarray, ndarray, ndarray), 'kwargs':('startp','endp','magsarefluxes', 'autofreq','stepsize','nbestpeaks', 'sigclip[]','lctimefilters','lcmagfilters', 'periodepsilon','phasebinsize','mindetperbin'), 'kwargtypes':(float, float, bool, bool, float, int, list, str, str, float, float, int), 'kwargdefs':(None, None, False, True, 1.0e-4, 10, None, None, None, 0.1, 0.05, 9), 'func':saov.aov_periodfind, 'resloc':['aov'], }, 'psearch-mav':{ 'args':('times','mags','errs'), 'argtypes':(ndarray, ndarray, ndarray), 'kwargs':('startp','endp','magsarefluxes', 'autofreq','stepsize','nbestpeaks', 'sigclip[]','lctimefilters','lcmagfilters', 'periodepsilon','nharmonics'), 'kwargtypes':(float, float, bool, bool, float, int, list, str, str, float, int), 'kwargdefs':(None, None, False, True, 1.0e-4, 10, None, None, None, 0.1, 6), 'func':smav.aovhm_periodfind, 'resloc':['mav'], }, 'psearch-acf':{ 'args':('times','mags','errs'), 'argtypes':(ndarray, ndarray, ndarray), 'kwargs':('startp','endp','magsarefluxes', 'autofreq','stepsize','smoothacf', 'sigclip[]','lctimefilters', 'lcmagfilters', 'periodepsilon', 'fillgaps'), 'kwargtypes':(float, float, bool, bool, float, int, list, str, str, float, float), 'kwargdefs':(None, None, False, True, 1.0e-4, 721, None, None, None, 0.1, 0.0), 'func':macf.macf_period_find, 'resloc':['acf'], }, 'psearch-win':{ 'args':('times','mags','errs'), 'argtypes':(ndarray, ndarray, ndarray), 'kwargs':('startp','endp','magsarefluxes', 'autofreq','stepsize','nbestpeaks', 'sigclip[]','lctimefilters','lcmagfilters', 'periodepsilon'), 'kwargtypes':(float, float, bool, bool, float, int, list, str, str, float), 'kwargdefs':(None, None, False, True, 1.0e-4, 10, None, None, None, 0.1), 'func':zgls.specwindow_lsp, 'resloc':['win'], }, ## PLOTTING A NEW PHASED LC ## 'phasedlc-newplot':{ 'args':(None,'lspmethod','periodind', 'times','mags','errs','varperiod','varepoch'), 'argtypes':(None, str, int, ndarray, ndarray, ndarray, float, float), 'kwargs':('xliminsetmode','magsarefluxes', 'phasewrap','phasesort', 'phasebin','plotxlim[]', 'sigclip[]','lctimefilters','lcmagfilters'), 'kwargtypes':(bool, bool, bool, bool, float, list, list, str, str), 'kwargdefs':(False, False, True, True, 0.002, [-0.8,0.8], None, None, None), 'func':_pkl_phased_magseries_plot, 'resloc':[], }, # FIXME: add sigclip, lctimefilters, and lcmagfilters for all of these ## VARIABILITY TOOLS ## 'var-varfeatures':{ 'args':('times','mags','errs'), 'argtypes':(ndarray,ndarray,ndarray), 'kwargs':(), 'kwargtypes':(), 'kwargdefs':(), 'func':varfeatures.all_nonperiodic_features, 'resloc':['varinfo','features'], }, 'var-prewhiten':{ 'args':('times','mags','errs','whitenperiod', 'whitenparams[]'), 'argtypes':(ndarray, ndarray, ndarray, float, list), 'kwargs':('magsarefluxes',), 'kwargtypes':(bool,), 'kwargdefs':(False,), 'func':signals.prewhiten_magseries, 'resloc':['signals','prewhiten'], }, 'var-masksig':{ 'args':('times','mags','errs','signalperiod','signalepoch'), 'argtypes':(ndarray, ndarray, ndarray, float, float), 'kwargs':('magsarefluxes','maskphases[]','maskphaselength'), 'kwargtypes':(bool, list, float), 'kwargdefs':(False, [0.0,0.5,1.0], 0.1), 'func':signals.mask_signal, 'resloc':['signals','mask'], }, # FIXME: add sigclip, lctimefilters, and lcmagfilters for all of these ## FITTING FUNCTIONS TO LIGHT CURVES ## # this is a special call to just subtract an already fit function from the # current light curve 'lcfit-subtract':{ 'args':('fitmethod', 'periodind'), 'argtypes':(str, int), 'kwargs':(), 'kwargtypes':(), 'kwargdefs':(), 'func':None, 'resloc':[], }, 'lcfit-fourier':{ 'args':('times','mags','errs','period'), 'argtypes':(ndarray, ndarray, ndarray, float), 'kwargs':('fourierorder','magsarefluxes', 'fourierparams[]'), 'kwargtypes':(int, bool, list), 'kwargdefs':(6, False, []), 'func':lcfit.fourier_fit_magseries, 'resloc':['fitinfo','fourier'], }, 'lcfit-spline':{ 'args':('times','mags','errs','period'), 'argtypes':(ndarray, ndarray, ndarray, float), 'kwargs':('maxknots','knotfraction','magsarefluxes'), 'kwargtypes':(int, float, bool), 'kwargdefs':(30, 0.01, False), 'func':lcfit.spline_fit_magseries, 'resloc':['fitinfo','spline'], }, 'lcfit-legendre':{ 'args':('times','mags','errs','period'), 'argtypes':(ndarray, ndarray, ndarray, float), 'kwargs':('legendredeg','magsarefluxes'), 'kwargtypes':(int, bool), 'kwargdefs':(10, False), 'func':lcfit.legendre_fit_magseries, 'resloc':['fitinfo','legendre'], }, 'lcfit-savgol':{ 'args':('times','mags','errs','period'), 'argtypes':(ndarray, ndarray, ndarray, float), 'kwargs':('windowlength','magsarefluxes'), 'kwargtypes':(int, bool), 'kwargdefs':(None, False), 'func':lcfit.savgol_fit_magseries, 'resloc':['fitinfo','savgol'], }, } ############ ## CONFIG ## ############ PFMETHODS = ['gls','pdm','acf','aov','mav','bls','win'] ##################### ## HANDLER CLASSES ## ##################### class IndexHandler(tornado.web.RequestHandler): '''This handles the index page. This page shows the current project. ''' def initialize(self, currentdir, assetpath, cplist, cplistfile, executor, readonly): ''' handles initial setup. ''' self.currentdir = currentdir self.assetpath = assetpath self.currentproject = cplist self.cplistfile = cplistfile self.executor = executor self.readonly = readonly def get(self): '''This handles GET requests to the index page. TODO: fix this so it loads a modified version of the usual index.html template for readonly mode. This should replace all of the text boxes with readonly versions. TODO: maybe also provide the correct baseurl from the checkplotserver options dict, so the frontend JS can just read that off immediately. ''' # generate the project's list of checkplots project_checkplots = self.currentproject['checkplots'] project_checkplotbasenames = [os.path.basename(x) for x in project_checkplots] project_checkplotindices = range(len(project_checkplots)) # get the sortkey and order project_cpsortkey = self.currentproject['sortkey'] if self.currentproject['sortorder'] == 'asc': project_cpsortorder = 'ascending' elif self.currentproject['sortorder'] == 'desc': project_cpsortorder = 'descending' # get the filterkey and condition project_cpfilterstatements = self.currentproject['filterstatements'] self.render('cpindex.html', project_checkplots=project_checkplots, project_cpsortorder=project_cpsortorder, project_cpsortkey=project_cpsortkey, project_cpfilterstatements=project_cpfilterstatements, project_checkplotbasenames=project_checkplotbasenames, project_checkplotindices=project_checkplotindices, project_checkplotfile=self.cplistfile, readonly=self.readonly) class CheckplotHandler(tornado.web.RequestHandler): '''This handles loading and saving checkplots. This includes GET requests to get to and load a specific checkplot pickle file and POST requests to save the checkplot changes back to the file. ''' def initialize(self, currentdir, assetpath, cplist, cplistfile, executor, readonly): ''' handles initial setup. ''' self.currentdir = currentdir self.assetpath = assetpath self.currentproject = cplist self.cplistfile = cplistfile self.executor = executor self.readonly = readonly @gen.coroutine def get(self, checkplotfname): '''This handles GET requests. This is an AJAX endpoint; returns JSON that gets converted by the frontend into things to render. ''' if checkplotfname: # do the usual safing self.checkplotfname = xhtml_escape( base64.b64decode(checkplotfname) ) # see if this plot is in the current project if self.checkplotfname in self.currentproject['checkplots']: # make sure this file exists cpfpath = os.path.join( os.path.abspath(os.path.dirname(self.cplistfile)), self.checkplotfname ) LOGGER.info('loading %s...' % cpfpath) if not os.path.exists(cpfpath): msg = "couldn't find checkplot %s" % cpfpath LOGGER.error(msg) resultdict = {'status':'error', 'message':msg, 'result':None} self.write(resultdict) raise tornado.web.Finish() # this is the async call to the executor cpdict = yield self.executor.submit( _read_checkplot_picklefile, cpfpath ) ##################################### ## continue after we're good to go ## ##################################### LOGGER.info('loaded %s' % cpfpath) # break out the initial info objectid = cpdict['objectid'] objectinfo = cpdict['objectinfo'] varinfo = cpdict['varinfo'] if 'pfmethods' in cpdict: pfmethods = cpdict['pfmethods'] else: pfmethods = [] for pfm in PFMETHODS: if pfm in cpdict: pfmethods.append(pfm) # handle neighbors for this object neighbors = [] if ('neighbors' in cpdict and cpdict['neighbors'] is not None and len(cpdict['neighbors'])) > 0: nbrlist = cpdict['neighbors'] # get each neighbor, its info, and its phased LCs for nbr in nbrlist: thisnbrdict = { 'objectid':nbr['objectid'], 'objectinfo':{ 'ra':nbr['ra'], 'decl':nbr['decl'], 'xpix':nbr['xpix'], 'ypix':nbr['ypix'], 'distarcsec':nbr['dist'], } } try: nbr_magseries = nbr['magseries']['plot'] thisnbrdict['magseries'] = nbr_magseries except Exception as e: LOGGER.error( "could not load magseries plot for " "neighbor %s for object %s" % (nbr['objectid'], cpdict['objectid']) ) try: for pfm in pfmethods: if pfm in nbr: thisnbrdict[pfm] = { 'plot':nbr[pfm][0]['plot'], 'period':nbr[pfm][0]['period'], 'epoch':nbr[pfm][0]['epoch'] } except Exception as e: LOGGER.error( "could not load phased LC plots for " "neighbor %s for object %s" % (nbr['objectid'], cpdict['objectid']) ) neighbors.append(thisnbrdict) # load object comments if 'comments' in cpdict: objectcomments = cpdict['comments'] else: objectcomments = None # load the xmatch results, if any if 'xmatch' in cpdict: objectxmatch = cpdict['xmatch'] # get rid of those pesky nans for xmcat in objectxmatch: if isinstance(objectxmatch[xmcat]['info'], dict): xminfo = objectxmatch[xmcat]['info'] for xmek in xminfo: if (isinstance(xminfo[xmek], float) and (not np.isfinite(xminfo[xmek]))): xminfo[xmek] = None else: objectxmatch = None # load the colormagdiagram object if 'colormagdiagram' in cpdict: colormagdiagram = cpdict['colormagdiagram'] else: colormagdiagram = None # these are base64 which can be provided directly to JS to # generate images (neat!) finderchart = cpdict['finderchart'] magseries = cpdict['magseries']['plot'] cpstatus = cpdict['status'] # load the uifilters if present if 'uifilters' in cpdict: uifilters = cpdict['uifilters'] else: uifilters = {'psearch_magfilters':None, 'psearch_sigclip':None, 'psearch_timefilters':None} # FIXME: add in other stuff required by the frontend # - signals # FIXME: the frontend should load these other things as well # into the various elems on the period-search-tools and # variability-tools tabs # this is the initial dict resultdict = { 'status':'ok', 'message':'found checkplot %s' % self.checkplotfname, 'readonly':self.readonly, 'result':{ 'time0':'%.3f' % cpdict['magseries']['times'].min(), 'objectid':objectid, 'objectinfo':objectinfo, 'colormagdiagram':colormagdiagram, 'objectcomments':objectcomments, 'varinfo':varinfo, 'uifilters':uifilters, 'neighbors':neighbors, 'xmatch':objectxmatch, 'finderchart':finderchart, 'magseries':magseries, # fallback in case objectinfo doesn't have ndet 'magseries_ndet':cpdict['magseries']['times'].size, 'cpstatus':cpstatus, 'pfmethods':pfmethods } } # make sure to replace nans with Nones. frontend JS absolutely # hates NaNs and for some reason, the JSON encoder defined at # the top of this file doesn't deal with them even though it # should for key in resultdict['result']['objectinfo']: if (isinstance(resultdict['result']['objectinfo'][key], float) and (not np.isfinite(resultdict['result'][ 'objectinfo' ][key]))): resultdict['result']['objectinfo'][key] = None elif (isinstance(resultdict['result']['objectinfo'][key], ndarray)): thisval = resultdict['result']['objectinfo'][key] thisval = thisval.tolist() for i, v in enumerate(thisval): if isinstance(v,float) and (not(np.isfinite(v))): thisval[i] = None resultdict['result']['objectinfo'][key] = thisval # now get the periodograms and phased LCs for key in pfmethods: # get the periodogram for this method periodogram = cpdict[key]['periodogram'] # get the phased LC with best period phasedlc0plot = cpdict[key][0]['plot'] # get the associated fitinfo for this period if it # exists if ('lcfit' in cpdict[key][0] and isinstance(cpdict[key][0]['lcfit'], dict)): phasedlc0fit = { 'method':( cpdict[key][0]['lcfit']['fittype'] ), 'redchisq':( cpdict[key][0]['lcfit']['fitredchisq'] ), 'chisq':( cpdict[key][0]['lcfit']['fitchisq'] ), 'params':( cpdict[key][0][ 'lcfit' ]['fitinfo']['finalparams'] if 'finalparams' in cpdict[key][0]['lcfit']['fitinfo'] else None ) } else: phasedlc0fit = None # get the phased LC with 2nd best period phasedlc1plot = cpdict[key][1]['plot'] # get the associated fitinfo for this period if it # exists if ('lcfit' in cpdict[key][1] and isinstance(cpdict[key][1]['lcfit'], dict)): phasedlc1fit = { 'method':( cpdict[key][1]['lcfit']['fittype'] ), 'redchisq':( cpdict[key][1]['lcfit']['fitredchisq'] ), 'chisq':( cpdict[key][1]['lcfit']['fitchisq'] ), 'params':( cpdict[key][1][ 'lcfit' ]['fitinfo']['finalparams'] if 'finalparams' in cpdict[key][1]['lcfit']['fitinfo'] else None ) } else: phasedlc1fit = None # get the phased LC with 3rd best period phasedlc2plot = cpdict[key][2]['plot'] # get the associated fitinfo for this period if it # exists if ('lcfit' in cpdict[key][2] and isinstance(cpdict[key][2]['lcfit'], dict)): phasedlc2fit = { 'method':( cpdict[key][2]['lcfit']['fittype'] ), 'redchisq':( cpdict[key][2]['lcfit']['fitredchisq'] ), 'chisq':( cpdict[key][2]['lcfit']['fitchisq'] ), 'params':( cpdict[key][2][ 'lcfit' ]['fitinfo']['finalparams'] if 'finalparams' in cpdict[key][2]['lcfit']['fitinfo'] else None ) } else: phasedlc2fit = None resultdict['result'][key] = { 'nbestperiods':cpdict[key]['nbestperiods'], 'periodogram':periodogram, 'bestperiod':cpdict[key]['bestperiod'], 'phasedlc0':{ 'plot':phasedlc0plot, 'period':float(cpdict[key][0]['period']), 'epoch':float(cpdict[key][0]['epoch']), 'lcfit':phasedlc0fit, }, 'phasedlc1':{ 'plot':phasedlc1plot, 'period':float(cpdict[key][1]['period']), 'epoch':float(cpdict[key][1]['epoch']), 'lcfit':phasedlc1fit, }, 'phasedlc2':{ 'plot':phasedlc2plot, 'period':float(cpdict[key][2]['period']), 'epoch':float(cpdict[key][2]['epoch']), 'lcfit':phasedlc2fit, }, } # # end of processing per pfmethod # # return the checkplot via JSON self.write(resultdict) self.finish() else: LOGGER.error('could not find %s' % self.checkplotfname) resultdict = {'status':'error', 'message':"This checkplot doesn't exist.", 'readonly':self.readonly, 'result':None} self.write(resultdict) self.finish() else: resultdict = {'status':'error', 'message':'No checkplot provided to load.', 'readonly':self.readonly, 'result':None} self.write(resultdict) @gen.coroutine def post(self, cpfile): '''This handles POST requests. Also an AJAX endpoint. Updates the persistent checkplot dict using the changes from the UI, and then saves it back to disk. This could definitely be faster by just loading the checkplot into a server-wide shared dict or something. ''' # if self.readonly is set, then don't accept any changes # return immediately with a 400 if self.readonly: msg = "checkplotserver is in readonly mode. no updates allowed." resultdict = {'status':'error', 'message':msg, 'readonly':self.readonly, 'result':None} self.write(resultdict) raise tornado.web.Finish() # now try to update the contents try: self.cpfile = base64.b64decode(cpfile).decode() cpcontents = self.get_argument('cpcontents', default=None) savetopng = self.get_argument('savetopng', default=None) if not self.cpfile or not cpcontents: msg = "did not receive a checkplot update payload" resultdict = {'status':'error', 'message':msg, 'readonly':self.readonly, 'result':None} self.write(resultdict) raise tornado.web.Finish() cpcontents = json.loads(cpcontents) # the only keys in cpdict that can updated from the UI are from # varinfo, objectinfo (objecttags), uifilters, and comments updated = {'varinfo': cpcontents['varinfo'], 'objectinfo':cpcontents['objectinfo'], 'comments':cpcontents['comments'], 'uifilters':cpcontents['uifilters']} # we need to reform the self.cpfile so it points to the full path cpfpath = os.path.join( os.path.abspath(os.path.dirname(self.cplistfile)), self.cpfile ) LOGGER.info('loading %s...' % cpfpath) if not os.path.exists(cpfpath): msg = "couldn't find checkplot %s" % cpfpath LOGGER.error(msg) resultdict = {'status':'error', 'message':msg, 'readonly':self.readonly, 'result':None} self.write(resultdict) raise tornado.web.Finish() # dispatch the task updated = yield self.executor.submit(checkplot_pickle_update, cpfpath, updated) # continue processing after this is done if updated: LOGGER.info('updated checkplot %s successfully' % updated) resultdict = {'status':'success', 'message':'checkplot update successful', 'readonly':self.readonly, 'result':{'checkplot':updated, 'unixtime':time.time(), 'changes':cpcontents, 'cpfpng': None}} # handle a savetopng trigger if savetopng: cpfpng = os.path.abspath(cpfpath.replace('.pkl','.png')) pngdone = yield self.executor.submit( checkplot_pickle_to_png, cpfpath, cpfpng ) if os.path.exists(cpfpng): resultdict['result']['cpfpng'] = cpfpng else: resultdict['result']['cpfpng'] = 'png making failed' self.write(resultdict) self.finish() else: LOGGER.error('could not handle checkplot update for %s: %s' % (self.cpfile, cpcontents)) msg = "checkplot update failed because of a backend error" resultdict = {'status':'error', 'message':msg, 'readonly':self.readonly, 'result':None} self.write(resultdict) self.finish() # if something goes wrong, inform the user except Exception as e: LOGGER.exception('could not handle checkplot update for %s: %s' % (self.cpfile, cpcontents)) msg = "checkplot update failed because of an exception" resultdict = {'status':'error', 'message':msg, 'readonly':self.readonly, 'result':None} self.write(resultdict) self.finish() class CheckplotListHandler(tornado.web.RequestHandler): '''This handles loading and saving the checkplot-filelist.json file. GET requests just return the current contents of the checkplot-filelist.json file. POST requests will put in changes that the user made from the frontend. ''' def initialize(self, currentdir, assetpath, cplist, cplistfile, executor, readonly): ''' handles initial setup. ''' self.currentdir = currentdir self.assetpath = assetpath self.currentproject = cplist self.cplistfile = cplistfile self.executor = executor self.readonly = readonly def get(self): ''' This handles GET requests. Used with AJAX from frontend. ''' # add the reviewed key to the current dict if it doesn't exist # this will hold all the reviewed objects for the frontend if not 'reviewed' in self.currentproject: self.currentproject['reviewed'] = {} # just returns the current project as JSON self.write(self.currentproject) def post(self): ''' This handles POST requests. Saves the changes made by the user. ''' # if self.readonly is set, then don't accept any changes # return immediately with a 400 if self.readonly: msg = "checkplotserver is in readonly mode. no updates allowed." resultdict = {'status':'error', 'message':msg, 'readonly':self.readonly, 'result':None} self.write(resultdict) raise tornado.web.Finish() objectid = self.get_argument('objectid', None) changes = self.get_argument('changes',None) # if either of the above is invalid, return nothing if not objectid or not changes: msg = ("could not parse changes to the checkplot filelist " "from the frontend") LOGGER.error(msg) resultdict = {'status':'error', 'message':msg, 'readonly':self.readonly, 'result':None} self.write(resultdict) raise tornado.web.Finish() # otherwise, update the checkplot list JSON objectid = xhtml_escape(objectid) changes = json.loads(changes) # update the dictionary if 'reviewed' not in self.currentproject: self.currentproject['reviewed'] = {} self.currentproject['reviewed'][objectid] = changes # update the JSON file with open(self.cplistfile,'w') as outfd: json.dump(self.currentproject, outfd) # return status msg = ("wrote all changes to the checkplot filelist " "from the frontend for object: %s" % objectid) LOGGER.info(msg) resultdict = {'status':'success', 'message':msg, 'readonly':self.readonly, 'result':{'objectid':objectid, 'changes':changes}} self.write(resultdict) self.finish() class LCToolHandler(tornado.web.RequestHandler): '''This handles dispatching light curve analysis tasks. GET requests run the light curve tools specified in the URI with arguments as specified in the args to the URI. POST requests write the results to the JSON file. The frontend JS object is automatically updated by the frontend code. ''' def initialize(self, currentdir, assetpath, cplist, cplistfile, executor, readonly): ''' handles initial setup. ''' self.currentdir = currentdir self.assetpath = assetpath self.currentproject = cplist self.cplistfile = cplistfile self.executor = executor self.readonly = readonly @gen.coroutine def get(self, cpfile): '''This handles a GET request. The URI structure is: /tools/<cpfile>?[args] where args are: ?lctool=<lctool>&argkey1=argval1&argkey2=argval2&... &forcereload=true <- if this is present, then reload values from original checkplot. &objectid=<objectid> lctool is one of the functions below PERIODSEARCH FUNCTIONS ---------------------- psearch-gls: run Lomb-Scargle with given params psearch-bls: run BLS with given params psearch-pdm: run phase dispersion minimization with given params psearch-aov: run analysis-of-variance with given params psearch-mav: run analysis-of-variance (multi-harm) with given params psearch-acf: run ACF period search with given params psearch-win: run spectral window function search with given params arguments: startp=XX endp=XX magsarefluxes=True|False autofreq=True|False stepsize=XX VARIABILITY FUNCTIONS --------------------- var-varfeatures: gets the variability from the checkplot or recalculates if it's not present var-prewhiten: pre-whitens the light curve with a sinusoidal signal var-masksig: masks a given phase location with given width from the light curve LIGHT CURVE FUNCTIONS --------------------- phasedlc-newplot: make phased LC with new provided period/epoch lcfit-fourier: fit a Fourier function to the phased LC lcfit-spline: fit a spline function to the phased LC lcfit-legendre: fit a Legendre polynomial to the phased LC lcfit-savgol: fit a Savitsky-Golay polynomial to the phased LC FIXME: figure out how to cache the results of these functions temporarily and save them back to the checkplot after we click on save in the frontend. look for a checkplot-blah-blah.pkl-cps-processing file in the same place as the usual pickle file. if this exists and is newer than the pkl file, load it instead. OR have a checkplotdict['cpservertemp'] item. ''' if cpfile: self.cpfile = xhtml_escape(base64.b64decode(cpfile)) # see if this plot is in the current project if self.cpfile in self.currentproject['checkplots']: # make sure this file exists cpfpath = os.path.join( os.path.abspath(os.path.dirname(self.cplistfile)), self.cpfile ) # if we can't find the pickle, quit immediately if not os.path.exists(cpfpath): msg = "couldn't find checkplot %s" % cpfpath LOGGER.error(msg) resultdict = {'status':'error', 'message':msg, 'readonly':self.readonly, 'result':None} self.write(resultdict) raise tornado.web.Finish() ########################### # now parse the arguments # ########################### # check if we have to force-reload forcereload = self.get_argument('forcereload',False) if forcereload and xhtml_escape(forcereload): forcereload = True if forcereload == 'true' else False # get the objectid cpobjectid = self.get_argument('objectid',None) # get the light curve tool to use lctool = self.get_argument('lctool', None) # preemptive dict to fill out resultdict = {'status':None, 'message':None, 'readonly':self.readonly, 'result':None} # check if the lctool arg is provided if lctool: lctool = xhtml_escape(lctool) lctoolargs = [] lctoolkwargs = {} # check if this lctool is OK and has all the required args if lctool in CPTOOLMAP: try: # all args should have been parsed # successfully. parse the kwargs now for xkwarg, xkwargtype, xkwargdef in zip( CPTOOLMAP[lctool]['kwargs'], CPTOOLMAP[lctool]['kwargtypes'], CPTOOLMAP[lctool]['kwargdefs'] ): # get the kwarg if xkwargtype is list: wbkwarg = self.get_arguments(xkwarg) if len(wbkwarg) > 0: wbkwarg = [url_unescape(xhtml_escape(x)) for x in wbkwarg] else: wbkwarg = None else: wbkwarg = self.get_argument(xkwarg, None) if wbkwarg is not None: wbkwarg = url_unescape( xhtml_escape(wbkwarg) ) LOGGER.info('xkwarg = %s, wbkwarg = %s' % (xkwarg, repr(wbkwarg))) # if it's None, sub with the default if wbkwarg is None: wbkwarg = xkwargdef # otherwise, cast it to the required type else: # special handling for lists of floats if xkwargtype is list: wbkwarg = [float(x) for x in wbkwarg] # special handling for booleans elif xkwargtype is bool: if wbkwarg == 'false': wbkwarg = False elif wbkwarg == 'true': wbkwarg = True else: wbkwarg = xkwargdef # usual casting for other types else: wbkwarg = xkwargtype(wbkwarg) # update the lctools kwarg dict # make sure to remove any [] from the kwargs # this was needed to parse the input query # string correctly if xkwarg.endswith('[]'): xkwarg = xkwarg.rstrip('[]') lctoolkwargs.update({xkwarg:wbkwarg}) except Exception as e: LOGGER.exception('lctool %s, kwarg %s ' 'will not work' % (lctool, xkwarg)) resultdict['status'] = 'error' resultdict['message'] = ( 'lctool %s, kwarg %s ' 'will not work' % (lctool, xkwarg) ) resultdict['result'] = {'objectid':cpobjectid} self.write(resultdict) raise tornado.web.Finish() # if the tool is not in the CPTOOLSMAP else: LOGGER.error('lctool %s, does not exist' % lctool) resultdict['status'] = 'error' resultdict['message'] = ( 'lctool %s does not exist' % lctool ) resultdict['result'] = {'objectid':cpobjectid} self.write(resultdict) raise tornado.web.Finish() # if no lctool arg is provided else: LOGGER.error('lctool argument not provided') resultdict['status'] = 'error' resultdict['message'] = ( 'lctool argument not provided' ) resultdict['result'] = {'objectid':cpobjectid} self.write(resultdict) raise tornado.web.Finish() ############################################## ## NOW WE'RE READY TO ACTUALLY DO SOMETHING ## ############################################## LOGGER.info('loading %s...' % cpfpath) # this loads the actual checkplot pickle cpdict = yield self.executor.submit( _read_checkplot_picklefile, cpfpath ) # we check for the existence of a cpfpath + '-cpserver-temp' # file first. this is where we store stuff before we write it # back to the actual checkplot. tempfpath = cpfpath + '-cpserver-temp' # load the temp checkplot if it exists if os.path.exists(tempfpath): tempcpdict = yield self.executor.submit( _read_checkplot_picklefile, tempfpath ) # if it doesn't exist, read the times, mags, errs from the # actual checkplot in prep for working on it else: tempcpdict = { 'objectid':cpdict['objectid'], 'magseries':{ 'times':cpdict['magseries']['times'], 'mags':cpdict['magseries']['mags'], 'errs':cpdict['magseries']['errs'], } } # if we're not forcing a rerun from the original checkplot dict if not forcereload: cptimes, cpmags, cperrs = ( tempcpdict['magseries']['times'], tempcpdict['magseries']['mags'], tempcpdict['magseries']['errs'], ) LOGGER.info('forcereload = False') # otherwise, reload the original times, mags, errs else: cptimes, cpmags, cperrs = (cpdict['magseries']['times'], cpdict['magseries']['mags'], cpdict['magseries']['errs']) LOGGER.info('forcereload = True') # collect the args for xarg, xargtype in zip(CPTOOLMAP[lctool]['args'], CPTOOLMAP[lctool]['argtypes']): # handle special args if xarg is None: lctoolargs.append(None) elif xarg == 'times': lctoolargs.append(cptimes) elif xarg == 'mags': lctoolargs.append(cpmags) elif xarg == 'errs': lctoolargs.append(cperrs) # handle other args else: try: if xargtype is list: wbarg = self.get_arguments(xarg) else: wbarg = url_unescape( xhtml_escape( self.get_argument(xarg, None) ) ) # cast the arg to the required type # special handling for lists if xargtype is list: wbarg = [float(x) for x in wbarg] # special handling for epochs that can be optional elif xargtype is float and xarg == 'varepoch': try: wbarg = xargtype(wbarg) except: wbarg = None # usual casting for other types else: wbarg = xargtype(wbarg) lctoolargs.append(wbarg) except Exception as e: LOGGER.exception('lctool %s, arg %s ' 'will not work' % (lctool, xarg)) resultdict['status'] = 'error' resultdict['message'] = ( 'lctool %s, arg %s ' 'will not work' % (lctool, xarg) ) resultdict['result'] = {'objectid':cpobjectid} self.write(resultdict) raise tornado.web.Finish() LOGGER.info(lctool) LOGGER.info(lctoolargs) LOGGER.info(lctoolkwargs) ############################ ## handle the lctools now ## ############################ # make sure the results aren't there already. # if they are and force-reload is not True, # just return them instead. resloc = CPTOOLMAP[lctool]['resloc'] # TODO: figure out a way to make the dispatched tasks # cancellable. This can probably be done by having a global # TOOLQUEUE object that gets imported on initialize(). In this # object, we could put in key:vals like so: # # TOOLQUEUE['lctool-<toolname>-cpfpath'] = ( # yield self.executor.submit(blah, *blah_args, **blah_kwargs) # ) # # then we probably need some sort of frontend AJAX call that # enqueues things and can then cancel stuff from the queue. see # stuff we need to figure out: # - if the above scheme actually yields so we remain async # - if the Future object supports cancellation # - if the Future object that isn't resolved actually works # get the objectid. we'll send this along with every # result. this should handle the case of the current objectid # not being the same as the objectid being looked at by the # user. in effect, this will allow the user to launch a # long-running process and come back to it later since the # frontend will load the older results when they are complete. objectid = cpdict['objectid'] # if lctool is a periodogram method if lctool in ('psearch-gls', 'psearch-bls', 'psearch-pdm', 'psearch-aov', 'psearch-mav', 'psearch-acf', 'psearch-win'): lspmethod = resloc[0] # if we can return the results from a previous run if (lspmethod in tempcpdict and isinstance(tempcpdict[lspmethod], dict) and (not forcereload)): # for a periodogram method, we need the # following items bestperiod = ( tempcpdict[lspmethod]['bestperiod'] ) nbestperiods = ( tempcpdict[lspmethod]['nbestperiods'] ) nbestlspvals = ( tempcpdict[lspmethod]['nbestlspvals'] ) periodogram = ( tempcpdict[lspmethod]['periodogram'] ) # get the first phased LC plot and its period # and epoch phasedlc0plot = ( tempcpdict[lspmethod][0]['plot'] ) phasedlc0period = float( tempcpdict[lspmethod][0]['period'] ) phasedlc0epoch = float( tempcpdict[lspmethod][0]['epoch'] ) LOGGER.warning( 'returning previously unsaved ' 'results for lctool %s from %s' % (lctool, tempfpath) ) # # assemble the returndict # resultdict['status'] = 'warning' resultdict['message'] = ( 'previous ' 'unsaved results from %s' % lctool ) resultdict['result'] = { 'objectid':objectid, lspmethod:{ 'nbestperiods':nbestperiods, 'periodogram':periodogram, 'bestperiod':bestperiod, 'nbestpeaks':nbestlspvals, 'phasedlc0':{ 'plot':phasedlc0plot, 'period':phasedlc0period, 'epoch':phasedlc0epoch, } } } self.write(resultdict) self.finish() # otherwise, we have to rerun the periodogram method else: # see if sigclip is set. if so, then do the sigclip on # the times, mags, errs if lctoolkwargs['sigclip'] is not None: wtimes, wmags, werrs = lcmath.sigclip_magseries( lctoolargs[0], lctoolargs[1], lctoolargs[2], sigclip=lctoolkwargs['sigclip'], magsarefluxes=lctoolkwargs['magsarefluxes'] ) lctoolargs[0] = wtimes lctoolargs[1] = wmags lctoolargs[2] = werrs # # process the LC filters now # # see if the lctimefilters are set if lctoolkwargs['lctimefilters']: wtimes, wmags, werrs = (lctoolargs[0], lctoolargs[1], lctoolargs[2]) filtermasks = [ np.full_like(wtimes, False, dtype=np.bool_) ] # parse the time filter strings filterstr = lctoolkwargs['lctimefilters'] filters = filterstr.split(',') filters = [ x.strip().lstrip('(').rstrip(')').strip() for x in filters ] for filt in filters: try: thisfilt = filt.split(':') if len(thisfilt) == 2: filt_lo = float(thisfilt[0]) filt_hi = float(thisfilt[1]) filtermasks.append( ((wtimes - cptimes.min()) < filt_hi) & ((wtimes - cptimes.min()) > filt_lo) ) elif (len(thisfilt) == 3 and thisfilt[0].strip() == 'not'): filt_lo = float(thisfilt[1]) filt_hi = float(thisfilt[2]) filtermasks.append(np.logical_not( (((wtimes - cptimes.min()) < filt_hi) & ((wtimes - cptimes.min()) > filt_lo)) )) else: continue except: continue # finally, apply the filters if applicable if len(filtermasks) > 0: # apply the filters using an OR filterind = np.column_stack(filtermasks) filterind = np.any(filterind, axis=1) lctoolargs[0] = wtimes[filterind] lctoolargs[1] = wmags[filterind] lctoolargs[2] = werrs[filterind] # see if the lcmagfilters are set if lctoolkwargs['lcmagfilters']: wtimes, wmags, werrs = (lctoolargs[0], lctoolargs[1], lctoolargs[2]) filtermasks = [ np.full_like(wtimes, False, dtype=np.bool_) ] # parse the time filter strings filterstr = lctoolkwargs['lcmagfilters'] filters = filterstr.split(',') filters = [ x.strip().strip() for x in filters ] for filt in filters: try: thisfilt = filt.split(':') if len(thisfilt) == 2: filt_lo = float(thisfilt[0]) filt_hi = float(thisfilt[1]) filtermasks.append( (wmags < filt_hi) & (wmags > filt_lo) ) elif (len(thisfilt) == 3 and thisfilt[0].strip() == 'not'): filt_lo = float(thisfilt[1]) filt_hi = float(thisfilt[2]) filtermasks.append(np.logical_not( ((wmags < filt_hi) & (wmags > filt_lo)) )) else: continue except: continue # finally, apply the filters if applicable if len(filtermasks) > 0: # apply the filters using an OR filterind = np.column_stack(filtermasks) filterind = np.any(filterind, axis=1) lctoolargs[0] = wtimes[filterind] lctoolargs[1] = wmags[filterind] lctoolargs[2] = werrs[filterind] # at the end of processing, remove from lctookwargs # since the pfmethod doesn't know about this del lctoolkwargs['lctimefilters'] del lctoolkwargs['lcmagfilters'] # # now run the period finder and get results # # run the period finder lctoolfunction = CPTOOLMAP[lctool]['func'] funcresults = yield self.executor.submit( lctoolfunction, *lctoolargs, **lctoolkwargs, ) # get what we need out of funcresults when it # returns. nbestperiods = funcresults['nbestperiods'] nbestlspvals = funcresults['nbestlspvals'] bestperiod = funcresults['bestperiod'] # generate the periodogram png pgramres = yield self.executor.submit( _pkl_periodogram, funcresults, ) # generate the phased LCs. we show these in the frontend # along with the periodogram. phasedlcargs0 = (None, lspmethod, -1, lctoolargs[0], lctoolargs[1], lctoolargs[2], nbestperiods[0], 'min') phasedlcargs1 = (None, lspmethod, -1, lctoolargs[0], lctoolargs[1], lctoolargs[2], nbestperiods[1], 'min') phasedlcargs2 = (None, lspmethod, -1, lctoolargs[0], lctoolargs[1], lctoolargs[2], nbestperiods[2], 'min') # here, we set a bestperiodhighlight to distinguish this # plot from the ones existing in the checkplot already phasedlckwargs = { 'xliminsetmode':False, 'magsarefluxes':lctoolkwargs['magsarefluxes'], 'bestperiodhighlight':'#defa75', } # dispatch the plot functions phasedlc0 = yield self.executor.submit( _pkl_phased_magseries_plot, *phasedlcargs0, **phasedlckwargs ) phasedlc1 = yield self.executor.submit( _pkl_phased_magseries_plot, *phasedlcargs1, **phasedlckwargs ) phasedlc2 = yield self.executor.submit( _pkl_phased_magseries_plot, *phasedlcargs2, **phasedlckwargs ) # save these to the tempcpdict # save the pickle only if readonly is not true if not self.readonly: tempcpdict[lspmethod] = { 'periods':funcresults['periods'], 'lspvals':funcresults['lspvals'], 'bestperiod':funcresults['bestperiod'], 'nbestperiods':funcresults['nbestperiods'], 'nbestlspvals':funcresults['nbestlspvals'], 'periodogram':pgramres[lspmethod]['periodogram'], 0:phasedlc0, 1:phasedlc1, 2:phasedlc2, } savekwargs = { 'outfile':tempfpath, 'protocol':pickle.HIGHEST_PROTOCOL } savedcpf = yield self.executor.submit( _write_checkplot_picklefile, tempcpdict, **savekwargs ) LOGGER.info( 'saved temp results from ' '%s to checkplot: %s' % (lctool, savedcpf) ) else: LOGGER.warning( 'not saving temp results to checkplot ' ' because readonly = True' ) # # assemble the return dict # # the periodogram periodogram = pgramres[lspmethod]['periodogram'] # phasedlc plot, period, and epoch for best 3 peaks phasedlc0plot = phasedlc0['plot'] phasedlc0period = float(phasedlc0['period']) phasedlc0epoch = float(phasedlc0['epoch']) phasedlc1plot = phasedlc1['plot'] phasedlc1period = float(phasedlc1['period']) phasedlc1epoch = float(phasedlc1['epoch']) phasedlc2plot = phasedlc2['plot'] phasedlc2period = float(phasedlc2['period']) phasedlc2epoch = float(phasedlc2['epoch']) resultdict['status'] = 'success' resultdict['message'] = ( 'new results for %s' % lctool ) resultdict['result'] = { 'objectid':objectid, lspmethod:{ 'nbestperiods':nbestperiods, 'nbestpeaks':nbestlspvals, 'periodogram':periodogram, 'bestperiod':bestperiod, 'phasedlc0':{ 'plot':phasedlc0plot, 'period':phasedlc0period, 'epoch':phasedlc0epoch, }, 'phasedlc1':{ 'plot':phasedlc1plot, 'period':phasedlc1period, 'epoch':phasedlc1epoch, }, 'phasedlc2':{ 'plot':phasedlc2plot, 'period':phasedlc2period, 'epoch':phasedlc2epoch, } } } # return to frontend self.write(resultdict) self.finish() # if the lctool is a call to the phased LC plot itself # this requires lots of parameters # these should all be present in the frontend elif lctool == 'phasedlc-newplot': lspmethod = lctoolargs[1] periodind = lctoolargs[2] # if we can return the results from a previous run if (not forcereload and lspmethod in tempcpdict and isinstance(tempcpdict[lspmethod], dict) and periodind in tempcpdict[lspmethod] and isinstance(tempcpdict[lspmethod][periodind], dict)): # we get phased LC at periodind from a previous run phasedlc = tempcpdict[lspmethod][periodind] LOGGER.warning( 'returning previously unsaved ' 'results for lctool %s from %s' % (lctool, tempfpath) ) # # assemble the returndict # resultdict['status'] = 'warning' resultdict['message'] = ( 'previous ' 'unsaved results from %s' % lctool ) retkey = 'phasedlc%s' % periodind resultdict['result'] = { 'objectid':objectid, lspmethod:{ retkey:phasedlc } } self.write(resultdict) self.finish() # otherwise, we need to dispatch the function else: # add the highlight to distinguish this plot from usual # checkplot plots # full disclosure: http://c0ffee.surge.sh/ lctoolkwargs['bestperiodhighlight'] = '#defa75' # set the input periodind to -1 to make sure we still # have the highlight on the plot. we use the correct # periodind when returning lctoolargs[2] = -1 # see if sigclip is set. if so, then do the sigclip on # the times, mags, errs if lctoolkwargs['sigclip'] is not None: stimes, smags, serrs = lcmath.sigclip_magseries( lctoolargs[3], lctoolargs[4], lctoolargs[5], sigclip=lctoolkwargs['sigclip'], magsarefluxes=lctoolkwargs['magsarefluxes'] ) else: stimes, smags, serrs = (lctoolargs[3], lctoolargs[4], lctoolargs[5]) # # process the LC filters now # # see if the lctimefilters are set if lctoolkwargs['lctimefilters']: wtimes, wmags, werrs = stimes, smags, serrs filtermasks = [ np.full_like(wtimes, False, dtype=np.bool_) ] # parse the time filter strings filterstr = lctoolkwargs['lctimefilters'] filters = filterstr.split(',') filters = [ x.strip().lstrip('(').rstrip(')').strip() for x in filters ] for filt in filters: try: thisfilt = filt.split(':') if len(thisfilt) == 2: filt_lo = float(thisfilt[0]) filt_hi = float(thisfilt[1]) filtermasks.append( ((wtimes - cptimes.min()) < filt_hi) & ((wtimes - cptimes.min()) > filt_lo) ) elif (len(thisfilt) == 3 and thisfilt[0].strip() == 'not'): filt_lo = float(thisfilt[1]) filt_hi = float(thisfilt[2]) filtermasks.append(np.logical_not( (((wtimes - cptimes.min()) < filt_hi) & ((wtimes - cptimes.min()) > filt_lo)) )) else: continue except: continue # finally, apply the filters if applicable if len(filtermasks) > 0: # apply the filters using an OR filterind = np.column_stack(filtermasks) filterind = np.any(filterind, axis=1) stimes = wtimes[filterind] smags = wmags[filterind] serrs = werrs[filterind] # see if the lcmagfilters are set if lctoolkwargs['lcmagfilters']: wtimes, wmags, werrs = stimes, smags, serrs filtermasks = [ np.full_like(wtimes, False, dtype=np.bool_) ] # parse the time filter strings filterstr = lctoolkwargs['lcmagfilters'] filters = filterstr.split(',') filters = [ x.strip().strip() for x in filters ] for filt in filters: try: thisfilt = filt.split(':') if len(thisfilt) == 2: filt_lo = float(thisfilt[0]) filt_hi = float(thisfilt[1]) filtermasks.append( (wmags < filt_hi) & (wmags > filt_lo) ) elif (len(thisfilt) == 3 and thisfilt[0].strip() == 'not'): filt_lo = float(thisfilt[1]) filt_hi = float(thisfilt[2]) filtermasks.append(np.logical_not( ((wmags < filt_hi) & (wmags > filt_lo)) )) else: continue except: continue # finally, apply the filters if applicable if len(filtermasks) > 0: # apply the filters using an OR filterind = np.column_stack(filtermasks) filterind = np.any(filterind, axis=1) stimes = wtimes[filterind] smags = wmags[filterind] serrs = werrs[filterind] # at the end of processing, remove from lctookwargs # since the pfmethod doesn't know about this del lctoolkwargs['lctimefilters'] del lctoolkwargs['lcmagfilters'] # if the varepoch is set to None, try to get the # minimum-light epoch using a spline fit if lctoolargs[-1] is None: LOGGER.warning( 'automatically getting min epoch ' 'for phased LC plot' ) try: spfit = lcfit.spline_fit_magseries( stimes, # times smags, # mags serrs, # errs lctoolargs[6], # period magsarefluxes=lctoolkwargs['magsarefluxes'], sigclip=None, verbose=True ) # set the epoch correctly now for the plot lctoolargs[-1] = spfit['fitinfo']['fitepoch'] if len(spfit['fitinfo']['fitepoch']) != 1: lctoolargs[-1] = ( spfit['fitinfo']['fitepoch'][0] ) # if the spline fit fails, use the minimum of times as # epoch as usual except Exception as e: LOGGER.exception( 'spline fit failed, ' 'using min(times) as epoch' ) lctoolargs[-1] = np.min(stimes) # now run the phased LC function with provided args, # kwargs # final times, mags, errs lctoolargs[3] = stimes lctoolargs[4] = smags lctoolargs[5] = serrs # the sigclip kwarg isn't used here since we did this # already earlier del lctoolkwargs['sigclip'] lctoolfunction = CPTOOLMAP[lctool]['func'] funcresults = yield self.executor.submit( lctoolfunction, *lctoolargs, **lctoolkwargs, ) # save these to the tempcpdict # save the pickle only if readonly is not true if not self.readonly: if (lspmethod in tempcpdict and isinstance(tempcpdict[lspmethod], dict)): if periodind in tempcpdict[lspmethod]: tempcpdict[lspmethod][periodind] = ( funcresults ) else: tempcpdict[lspmethod].update( {periodind: funcresults} ) else: tempcpdict[lspmethod] = {periodind: funcresults} savekwargs = { 'outfile':tempfpath, 'protocol':pickle.HIGHEST_PROTOCOL } savedcpf = yield self.executor.submit( _write_checkplot_picklefile, tempcpdict, **savekwargs ) LOGGER.info( 'saved temp results from ' '%s to checkplot: %s' % (lctool, savedcpf) ) else: LOGGER.warning( 'not saving temp results to checkplot ' ' because readonly = True' ) # # assemble the return dict # resultdict['status'] = 'success' resultdict['message'] = ( 'new results for %s' % lctool ) retkey = 'phasedlc%s' % periodind resultdict['result'] = { 'objectid':objectid, lspmethod:{ retkey:funcresults } } self.write(resultdict) self.finish() # if the lctool is var-varfeatures elif lctool == 'var-varfeatures': # see if we can return results from a previous iteration of # this tool if (not forcereload and 'varinfo' in tempcpdict and isinstance(tempcpdict['varinfo'], dict) and 'varfeatures' in tempcpdict['varinfo'] and isinstance(tempcpdict['varinfo']['varfeatures'], dict)): LOGGER.warning( 'returning previously unsaved ' 'results for lctool %s from %s' % (lctool, tempfpath) ) # # assemble the returndict # resultdict['status'] = 'warning' resultdict['message'] = ( 'previous ' 'unsaved results from %s' % lctool ) resultdict['result'] = { 'objectid':objectid, 'varinfo': { 'varfeatures': ( tempcpdict['varinfo']['varfeatures'] ) } } self.write(resultdict) self.finish() # otherwise, we need to dispatch the function else: lctoolfunction = CPTOOLMAP[lctool]['func'] funcresults = yield self.executor.submit( lctoolfunction, *lctoolargs, **lctoolkwargs, ) # save these to the tempcpdict # save the pickle only if readonly is not true if not self.readonly: if ('varinfo' in tempcpdict and isinstance(tempcpdict['varinfo'], dict)): if 'varfeatures' in tempcpdict['varinfo']: tempcpdict['varinfo']['varfeatures'] = ( funcresults ) else: tempcpdict['varinfo'].update( {'varfeatures': funcresults} ) else: tempcpdict['varinfo'] = {'varfeatures': funcresults} savekwargs = { 'outfile':tempfpath, 'protocol':pickle.HIGHEST_PROTOCOL } savedcpf = yield self.executor.submit( _write_checkplot_picklefile, tempcpdict, **savekwargs ) LOGGER.info( 'saved temp results from ' '%s to checkplot: %s' % (lctool, savedcpf) ) else: LOGGER.warning( 'not saving temp results to checkplot ' ' because readonly = True' ) # # assemble the return dict # resultdict['status'] = 'success' resultdict['message'] = ( 'new results for %s' % lctool ) resultdict['result'] = { 'objectid':objectid, 'varinfo':{ 'varfeatures':funcresults } } self.write(resultdict) self.finish() # if the lctool is var-prewhiten or var-masksig elif lctool in ('var-prewhiten','var-masksig'): key1, key2 = resloc # see if we can return results from a previous iteration of # this tool if (not forcereload and key1 in tempcpdict and isinstance(tempcpdict[key1], dict) and key2 in tempcpdict[key1] and isinstance(tempcpdict[key1][key2], dict)): LOGGER.warning( 'returning previously unsaved ' 'results for lctool %s from %s' % (lctool, tempfpath) ) # # assemble the returndict # resultdict['status'] = 'warning' resultdict['message'] = ( 'previous ' 'unsaved results from %s' % lctool ) resultdict['result'] = { 'objectid':objectid, key1: { key2: ( tempcpdict[key1][key2] ) } } self.write(resultdict) self.finish() # otherwise, we need to dispatch the function else: lctoolfunction = CPTOOLMAP[lctool]['func'] # send in a stringio object for the fitplot kwarg lctoolkwargs['plotfit'] = strio() funcresults = yield self.executor.submit( lctoolfunction, *lctoolargs, **lctoolkwargs, ) # we turn the returned fitplotfile fd into a base64 # encoded string after reading it fitfd = funcresults['fitplotfile'] fitfd.seek(0) fitbin = fitfd.read() fitb64 = base64.b64encode(fitbin) fitfd.close() funcresults['fitplotfile'] = fitb64 # save these to the tempcpdict # save the pickle only if readonly is not true if not self.readonly: if (key1 in tempcpdict and isinstance(tempcpdict[key1], dict)): if key2 in tempcpdict[key1]: tempcpdict[key1][key2] = ( funcresults ) else: tempcpdict[key1].update( {key2: funcresults} ) else: tempcpdict[key1] = {key2: funcresults} savekwargs = { 'outfile':tempfpath, 'protocol':pickle.HIGHEST_PROTOCOL } savedcpf = yield self.executor.submit( _write_checkplot_picklefile, tempcpdict, **savekwargs ) LOGGER.info( 'saved temp results from ' '%s to checkplot: %s' % (lctool, savedcpf) ) else: LOGGER.warning( 'not saving temp results to checkplot ' ' because readonly = True' ) # # assemble the return dict # # for this operation, we'll return: # - fitplotfile fitreturndict = {'fitplotfile':fitb64} resultdict['status'] = 'success' resultdict['message'] = ( 'new results for %s' % lctool ) resultdict['result'] = { 'objectid':objectid, key1:{ key2:fitreturndict } } self.write(resultdict) self.finish() # if the lctool is a lcfit method elif lctool in ('lcfit-fourier', 'lcfit-spline', 'lcfit-legendre', 'lcfit-savgol'): key1, key2 = resloc # see if we can return results from a previous iteration of # this tool if (not forcereload and key1 in tempcpdict and isinstance(tempcpdict[key1], dict) and key2 in tempcpdict[key1] and isinstance(tempcpdict[key1][key2], dict)): LOGGER.warning( 'returning previously unsaved ' 'results for lctool %s from %s' % (lctool, tempfpath) ) # # assemble the returndict # resultdict['status'] = 'warning' resultdict['message'] = ( 'previous ' 'unsaved results from %s' % lctool ) # these are the full results phasedfitlc = tempcpdict[key1][key2] # we only want a few things from them fitresults = { 'method':phasedfitlc['lcfit']['fittype'], 'chisq':phasedfitlc['lcfit']['fitchisq'], 'redchisq':phasedfitlc['lcfit']['fitredchisq'], 'period':phasedfitlc['period'], 'epoch':phasedfitlc['epoch'], 'plot':phasedfitlc['plot'], } # add fitparams if there are any if ('finalparams' in phasedfitlc['lcfit']['fitinfo'] and phasedfitlc['lcfit']['fitinfo']['finalparams'] is not None): fitresults['fitparams'] = ( phasedfitlc['lcfit']['fitinfo']['finalparams'] ) # this is the final result object resultdict['result'] = { 'objectid':objectid, key1: { key2: ( fitresults ) } } self.write(resultdict) self.finish() # otherwise, we need to dispatch the function else: lctoolfunction = CPTOOLMAP[lctool]['func'] funcresults = yield self.executor.submit( lctoolfunction, *lctoolargs, **lctoolkwargs, ) # now that we have the fit results, generate a fitplot. # these args are for the special fitplot mode of # _pkl_phased_magseries_plot phasedlcargs = (None, 'lcfit', -1, cptimes, cpmags, cperrs, lctoolargs[3], # this is the fit period 'min') # here, we set a bestperiodhighlight to distinguish this # plot from the ones existing in the checkplot already # also add the overplotfit information phasedlckwargs = { 'xliminsetmode':False, 'magsarefluxes':lctoolkwargs['magsarefluxes'], 'bestperiodhighlight':'#defa75', 'overplotfit':funcresults } # dispatch the plot function phasedlc = yield self.executor.submit( _pkl_phased_magseries_plot, *phasedlcargs, **phasedlckwargs ) # save these to the tempcpdict # save the pickle only if readonly is not true if not self.readonly: if (key1 in tempcpdict and isinstance(tempcpdict[key1], dict)): if key2 in tempcpdict[key1]: tempcpdict[key1][key2] = ( phasedlc ) else: tempcpdict[key1].update( {key2: phasedlc} ) else: tempcpdict[key1] = {key2: phasedlc} savekwargs = { 'outfile':tempfpath, 'protocol':pickle.HIGHEST_PROTOCOL } savedcpf = yield self.executor.submit( _write_checkplot_picklefile, tempcpdict, **savekwargs ) LOGGER.info( 'saved temp results from ' '%s to checkplot: %s' % (lctool, savedcpf) ) else: LOGGER.warning( 'not saving temp results to checkplot ' ' because readonly = True' ) # # assemble the return dict # fitresults = { 'method':phasedlc['lcfit']['fittype'], 'chisq':phasedlc['lcfit']['fitchisq'], 'redchisq':phasedlc['lcfit']['fitredchisq'], 'period':phasedlc['period'], 'epoch':phasedlc['epoch'], 'plot':phasedlc['plot'], } # add fitparams if there are any if ('finalparams' in funcresults['fitinfo'] and funcresults['fitinfo']['finalparams'] is not None): fitresults['fitparams'] = ( funcresults['fitinfo']['finalparams'] ) resultdict['status'] = 'success' resultdict['message'] = ( 'new results for %s' % lctool ) resultdict['result'] = { 'objectid':objectid, key1:{ key2:fitresults } } self.write(resultdict) self.finish() # if this is the special lcfit subtract tool elif lctool == 'lcfit-subtract': fitmethod, periodind = lctoolargs # find the fit requested # subtract it from the cptimes, cpmags, cperrs # if not readonly, write back to cptimes, cpmags, cperrs # make a new phasedlc plot for the current periodind using # these new cptimes, cpmags, cperrs # return this plot # if this is the special full reset tool elif lctool == 'lctool-reset': if os.path.exists(tempfpath): os.remove(tempfpath) LOGWARNING('reset all LC tool results ' 'for %s by removing %s' % (tempfpath, cpfpath)) resultdict['status'] = 'success' else: resultdict['status'] = 'error' LOGWARNING('tried to reset LC tool results for %s, ' 'but temp checkplot result pickle %s ' 'does not exist' % (tempfpath, cpfpath)) resultdict['message'] = ( 'all unsynced results for this object have been purged' ) resultdict['result'] = {'objectid':cpobjectid} self.write(resultdict) self.finish() # if this is the special load results tool elif lctool == 'lctool-results': target = self.get_argument('resultsfor',None) if target is not None: target = xhtml_escape(target) # get rid of invalid targets if (target not in CPTOOL or target == 'lctool-reset' or target == 'lctool-results' or target == 'phasedlc-newplot' or target == 'lcfit-subtract'): LOGGER.error("can't get results for %s" % target) resultdict['status'] = 'error' resultdict['message'] = ( "can't get results for %s" % target ) resultdict['result'] = {'objectid':cpobjectid} self.write(resultdict) raise tornado.web.Finish() # if we're good to go, get the target location targetloc = CPTOOLS[target]['resloc'] # first, search the cptempdict for this target # if found, return it # second, search the actual cpdict for this target # if found, return it # otherwise, we're being asked for everything # return the whole else: pass # otherwise, this is an unrecognized lctool else: LOGGER.error('lctool %s, does not exist' % lctool) resultdict['status'] = 'error' resultdict['message'] = ( 'lctool %s does not exist' % lctool ) resultdict['result'] = {'objectid':cpobjectid} self.write(resultdict) raise tornado.web.Finish() # if the cpfile doesn't exist else: LOGGER.error('could not find %s' % self.cpfile) resultdict = {'status':'error', 'message':"This checkplot doesn't exist.", 'readonly':self.readonly, 'result':None} self.write(resultdict) raise tornado.web.Finish() # if no checkplot was provided to load else: resultdict = {'status':'error', 'message':'No checkplot provided to load.', 'readonly':self.readonly, 'result':None} self.write(resultdict) raise tornado.web.Finish() def post(self, cpfile): '''This handles a POST request. This will save the results of the previous tool run to the checkplot file and the JSON filelist. This is only called when the user explicitly clicks on the 'permanently update checkplot with results' button. If the server is in readonly mode, this has no effect. This will copy everything from the '.pkl-cpserver-temp' file to the actual checkplot pickle and then remove that file. '''
[ "os.remove", "base64.b64decode", "numpy.full_like", "json.loads", "os.path.dirname", "numpy.logical_not", "os.path.exists", "numpy.isfinite", "json.JSONEncoder.default", "json.dump", "io.BytesIO", "os.path.basename", "numpy.min", "tornado.escape.xhtml_escape", "time.time", "numpy.any", "base64.b64encode", "numpy.column_stack", "logging.getLogger" ]
[((1733, 1760), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (1750, 1760), False, 'import logging\n'), ((37454, 37476), 'tornado.escape.xhtml_escape', 'xhtml_escape', (['objectid'], {}), '(objectid)\n', (37466, 37476), False, 'from tornado.escape import xhtml_escape, xhtml_unescape, url_unescape\n'), ((37495, 37514), 'json.loads', 'json.loads', (['changes'], {}), '(changes)\n', (37505, 37514), False, 'import json\n'), ((13693, 13712), 'os.path.basename', 'os.path.basename', (['x'], {}), '(x)\n', (13709, 13712), False, 'import os\n'), ((31583, 31605), 'json.loads', 'json.loads', (['cpcontents'], {}), '(cpcontents)\n', (31593, 31605), False, 'import json\n'), ((37801, 37838), 'json.dump', 'json.dump', (['self.currentproject', 'outfd'], {}), '(self.currentproject, outfd)\n', (37810, 37838), False, 'import json\n'), ((15800, 15832), 'base64.b64decode', 'base64.b64decode', (['checkplotfname'], {}), '(checkplotfname)\n', (15816, 15832), False, 'import base64\n'), ((32288, 32311), 'os.path.exists', 'os.path.exists', (['cpfpath'], {}), '(cpfpath)\n', (32302, 32311), False, 'import os\n'), ((41390, 41414), 'base64.b64decode', 'base64.b64decode', (['cpfile'], {}), '(cpfile)\n', (41406, 41414), False, 'import base64\n'), ((48981, 49006), 'os.path.exists', 'os.path.exists', (['tempfpath'], {}), '(tempfpath)\n', (48995, 49006), False, 'import os\n'), ((16273, 16296), 'os.path.exists', 'os.path.exists', (['cpfpath'], {}), '(cpfpath)\n', (16287, 16296), False, 'import os\n'), ((30987, 31011), 'base64.b64decode', 'base64.b64decode', (['cpfile'], {}), '(cpfile)\n', (31003, 31011), False, 'import base64\n'), ((32139, 32171), 'os.path.dirname', 'os.path.dirname', (['self.cplistfile'], {}), '(self.cplistfile)\n', (32154, 32171), False, 'import os\n'), ((33784, 33806), 'os.path.exists', 'os.path.exists', (['cpfpng'], {}), '(cpfpng)\n', (33798, 33806), False, 'import os\n'), ((41834, 41857), 'os.path.exists', 'os.path.exists', (['cpfpath'], {}), '(cpfpath)\n', (41848, 41857), False, 'import os\n'), ((42553, 42578), 'tornado.escape.xhtml_escape', 'xhtml_escape', (['forcereload'], {}), '(forcereload)\n', (42565, 42578), False, 'from tornado.escape import xhtml_escape, xhtml_unescape, url_unescape\n'), ((43216, 43236), 'tornado.escape.xhtml_escape', 'xhtml_escape', (['lctool'], {}), '(lctool)\n', (43228, 43236), False, 'from tornado.escape import xhtml_escape, xhtml_unescape, url_unescape\n'), ((16100, 16132), 'os.path.dirname', 'os.path.dirname', (['self.cplistfile'], {}), '(self.cplistfile)\n', (16115, 16132), False, 'import os\n'), ((33304, 33315), 'time.time', 'time.time', ([], {}), '()\n', (33313, 33315), False, 'import time\n'), ((41661, 41693), 'os.path.dirname', 'os.path.dirname', (['self.cplistfile'], {}), '(self.cplistfile)\n', (41676, 41693), False, 'import os\n'), ((1235, 1251), 'numpy.isfinite', 'np.isfinite', (['obj'], {}), '(obj)\n', (1246, 1251), True, 'import numpy as np\n'), ((1410, 1445), 'json.JSONEncoder.default', 'json.JSONEncoder.default', (['self', 'obj'], {}), '(self, obj)\n', (1434, 1445), False, 'import json\n'), ((23350, 23402), 'numpy.isfinite', 'np.isfinite', (["resultdict['result']['objectinfo'][key]"], {}), "(resultdict['result']['objectinfo'][key])\n", (23361, 23402), True, 'import numpy as np\n'), ((59427, 59470), 'numpy.full_like', 'np.full_like', (['wtimes', '(False)'], {'dtype': 'np.bool_'}), '(wtimes, False, dtype=np.bool_)\n', (59439, 59470), True, 'import numpy as np\n'), ((61479, 61507), 'numpy.column_stack', 'np.column_stack', (['filtermasks'], {}), '(filtermasks)\n', (61494, 61507), True, 'import numpy as np\n'), ((61552, 61577), 'numpy.any', 'np.any', (['filterind'], {'axis': '(1)'}), '(filterind, axis=1)\n', (61558, 61577), True, 'import numpy as np\n'), ((62170, 62213), 'numpy.full_like', 'np.full_like', (['wtimes', '(False)'], {'dtype': 'np.bool_'}), '(wtimes, False, dtype=np.bool_)\n', (62182, 62213), True, 'import numpy as np\n'), ((64122, 64150), 'numpy.column_stack', 'np.column_stack', (['filtermasks'], {}), '(filtermasks)\n', (64137, 64150), True, 'import numpy as np\n'), ((64195, 64220), 'numpy.any', 'np.any', (['filterind'], {'axis': '(1)'}), '(filterind, axis=1)\n', (64201, 64220), True, 'import numpy as np\n'), ((76023, 76066), 'numpy.full_like', 'np.full_like', (['wtimes', '(False)'], {'dtype': 'np.bool_'}), '(wtimes, False, dtype=np.bool_)\n', (76035, 76066), True, 'import numpy as np\n'), ((78076, 78104), 'numpy.column_stack', 'np.column_stack', (['filtermasks'], {}), '(filtermasks)\n', (78091, 78104), True, 'import numpy as np\n'), ((78149, 78174), 'numpy.any', 'np.any', (['filterind'], {'axis': '(1)'}), '(filterind, axis=1)\n', (78155, 78174), True, 'import numpy as np\n'), ((78615, 78658), 'numpy.full_like', 'np.full_like', (['wtimes', '(False)'], {'dtype': 'np.bool_'}), '(wtimes, False, dtype=np.bool_)\n', (78627, 78658), True, 'import numpy as np\n'), ((80566, 80594), 'numpy.column_stack', 'np.column_stack', (['filtermasks'], {}), '(filtermasks)\n', (80581, 80594), True, 'import numpy as np\n'), ((80639, 80664), 'numpy.any', 'np.any', (['filterind'], {'axis': '(1)'}), '(filterind, axis=1)\n', (80645, 80664), True, 'import numpy as np\n'), ((92443, 92450), 'io.BytesIO', 'strio', ([], {}), '()\n', (92448, 92450), True, 'from io import BytesIO as strio\n'), ((92983, 93007), 'base64.b64encode', 'base64.b64encode', (['fitbin'], {}), '(fitbin)\n', (92999, 93007), False, 'import base64\n'), ((20486, 20511), 'numpy.isfinite', 'np.isfinite', (['xminfo[xmek]'], {}), '(xminfo[xmek])\n', (20497, 20511), True, 'import numpy as np\n'), ((23900, 23914), 'numpy.isfinite', 'np.isfinite', (['v'], {}), '(v)\n', (23911, 23914), True, 'import numpy as np\n'), ((82836, 82850), 'numpy.min', 'np.min', (['stimes'], {}), '(stimes)\n', (82842, 82850), True, 'import numpy as np\n'), ((44662, 44683), 'tornado.escape.xhtml_escape', 'xhtml_escape', (['wbkwarg'], {}), '(wbkwarg)\n', (44674, 44683), False, 'from tornado.escape import xhtml_escape, xhtml_unescape, url_unescape\n'), ((104113, 104138), 'os.path.exists', 'os.path.exists', (['tempfpath'], {}), '(tempfpath)\n', (104127, 104138), False, 'import os\n'), ((44194, 44209), 'tornado.escape.xhtml_escape', 'xhtml_escape', (['x'], {}), '(x)\n', (44206, 44209), False, 'from tornado.escape import xhtml_escape, xhtml_unescape, url_unescape\n'), ((63521, 63574), 'numpy.logical_not', 'np.logical_not', (['((wmags < filt_hi) & (wmags > filt_lo))'], {}), '((wmags < filt_hi) & (wmags > filt_lo))\n', (63535, 63574), True, 'import numpy as np\n'), ((104164, 104184), 'os.remove', 'os.remove', (['tempfpath'], {}), '(tempfpath)\n', (104173, 104184), False, 'import os\n'), ((79966, 80019), 'numpy.logical_not', 'np.logical_not', (['((wmags < filt_hi) & (wmags > filt_lo))'], {}), '((wmags < filt_hi) & (wmags > filt_lo))\n', (79980, 80019), True, 'import numpy as np\n'), ((105316, 105336), 'tornado.escape.xhtml_escape', 'xhtml_escape', (['target'], {}), '(target)\n', (105328, 105336), False, 'from tornado.escape import xhtml_escape, xhtml_unescape, url_unescape\n')]
# Newton-Raphson method for orbit calculations using numpy arrays; from numpy import linspace, abs, sqrt, sin, cos, arctan2, array, pi def orbit(m0, e, a, inclination, ascension, n, acc=1.e-2): m = linspace(m0, 2 * pi + m0, n) ecc_anom = m ecc_anom_old = 0 while acc < abs(ecc_anom - ecc_anom_old).max(): # Newton-Raphson solver for eccentric anomaly (E) ecc_anom_old = ecc_anom # assigning previous value for accuracy comparison ecc_anom -= (ecc_anom - m - e * sin(ecc_anom)) / (1. - e * cos(ecc_anom)) # function for E divided by its derivative w.r.t E theta = 2. * arctan2(sqrt(1. + e) * sin(ecc_anom / 2.), sqrt(1. - e) * cos(ecc_anom / 2.)) # true anomaly r = a * (1 - e * cos(ecc_anom)) # radius theasc = theta - ascension # conversion to cartesian coordinates: x = r * (cos(ascension) * cos(theasc) - sin(ascension) * sin(theasc) * cos(inclination)) z = r * (sin(ascension) * cos(theasc) + cos(ascension) * sin(theasc) * cos(inclination)) y = r * (sin(theta - ascension) * sin(inclination)) coord = array((x, y, z)) return coord # returning an array with the coordinates for one orbital period for a given celestial body
[ "numpy.abs", "numpy.sin", "numpy.array", "numpy.linspace", "numpy.cos", "numpy.sqrt" ]
[((204, 232), 'numpy.linspace', 'linspace', (['m0', '(2 * pi + m0)', 'n'], {}), '(m0, 2 * pi + m0, n)\n', (212, 232), False, 'from numpy import linspace, abs, sqrt, sin, cos, arctan2, array, pi\n'), ((1117, 1133), 'numpy.array', 'array', (['(x, y, z)'], {}), '((x, y, z))\n', (1122, 1133), False, 'from numpy import linspace, abs, sqrt, sin, cos, arctan2, array, pi\n'), ((1061, 1083), 'numpy.sin', 'sin', (['(theta - ascension)'], {}), '(theta - ascension)\n', (1064, 1083), False, 'from numpy import linspace, abs, sqrt, sin, cos, arctan2, array, pi\n'), ((1086, 1102), 'numpy.sin', 'sin', (['inclination'], {}), '(inclination)\n', (1089, 1102), False, 'from numpy import linspace, abs, sqrt, sin, cos, arctan2, array, pi\n'), ((287, 315), 'numpy.abs', 'abs', (['(ecc_anom - ecc_anom_old)'], {}), '(ecc_anom - ecc_anom_old)\n', (290, 315), False, 'from numpy import linspace, abs, sqrt, sin, cos, arctan2, array, pi\n'), ((625, 638), 'numpy.sqrt', 'sqrt', (['(1.0 + e)'], {}), '(1.0 + e)\n', (629, 638), False, 'from numpy import linspace, abs, sqrt, sin, cos, arctan2, array, pi\n'), ((640, 659), 'numpy.sin', 'sin', (['(ecc_anom / 2.0)'], {}), '(ecc_anom / 2.0)\n', (643, 659), False, 'from numpy import linspace, abs, sqrt, sin, cos, arctan2, array, pi\n'), ((685, 698), 'numpy.sqrt', 'sqrt', (['(1.0 - e)'], {}), '(1.0 - e)\n', (689, 698), False, 'from numpy import linspace, abs, sqrt, sin, cos, arctan2, array, pi\n'), ((700, 719), 'numpy.cos', 'cos', (['(ecc_anom / 2.0)'], {}), '(ecc_anom / 2.0)\n', (703, 719), False, 'from numpy import linspace, abs, sqrt, sin, cos, arctan2, array, pi\n'), ((758, 771), 'numpy.cos', 'cos', (['ecc_anom'], {}), '(ecc_anom)\n', (761, 771), False, 'from numpy import linspace, abs, sqrt, sin, cos, arctan2, array, pi\n'), ((873, 887), 'numpy.cos', 'cos', (['ascension'], {}), '(ascension)\n', (876, 887), False, 'from numpy import linspace, abs, sqrt, sin, cos, arctan2, array, pi\n'), ((890, 901), 'numpy.cos', 'cos', (['theasc'], {}), '(theasc)\n', (893, 901), False, 'from numpy import linspace, abs, sqrt, sin, cos, arctan2, array, pi\n'), ((935, 951), 'numpy.cos', 'cos', (['inclination'], {}), '(inclination)\n', (938, 951), False, 'from numpy import linspace, abs, sqrt, sin, cos, arctan2, array, pi\n'), ((967, 981), 'numpy.sin', 'sin', (['ascension'], {}), '(ascension)\n', (970, 981), False, 'from numpy import linspace, abs, sqrt, sin, cos, arctan2, array, pi\n'), ((984, 995), 'numpy.cos', 'cos', (['theasc'], {}), '(theasc)\n', (987, 995), False, 'from numpy import linspace, abs, sqrt, sin, cos, arctan2, array, pi\n'), ((1029, 1045), 'numpy.cos', 'cos', (['inclination'], {}), '(inclination)\n', (1032, 1045), False, 'from numpy import linspace, abs, sqrt, sin, cos, arctan2, array, pi\n'), ((498, 511), 'numpy.sin', 'sin', (['ecc_anom'], {}), '(ecc_anom)\n', (501, 511), False, 'from numpy import linspace, abs, sqrt, sin, cos, arctan2, array, pi\n'), ((525, 538), 'numpy.cos', 'cos', (['ecc_anom'], {}), '(ecc_anom)\n', (528, 538), False, 'from numpy import linspace, abs, sqrt, sin, cos, arctan2, array, pi\n'), ((904, 918), 'numpy.sin', 'sin', (['ascension'], {}), '(ascension)\n', (907, 918), False, 'from numpy import linspace, abs, sqrt, sin, cos, arctan2, array, pi\n'), ((921, 932), 'numpy.sin', 'sin', (['theasc'], {}), '(theasc)\n', (924, 932), False, 'from numpy import linspace, abs, sqrt, sin, cos, arctan2, array, pi\n'), ((998, 1012), 'numpy.cos', 'cos', (['ascension'], {}), '(ascension)\n', (1001, 1012), False, 'from numpy import linspace, abs, sqrt, sin, cos, arctan2, array, pi\n'), ((1015, 1026), 'numpy.sin', 'sin', (['theasc'], {}), '(theasc)\n', (1018, 1026), False, 'from numpy import linspace, abs, sqrt, sin, cos, arctan2, array, pi\n')]
# -*- encoding: utf-8 -*- # Copyright (c) 2020 <NAME> <<EMAIL>> # ISC License <https://choosealicense.com/licenses/isc> """Contains some common necessary frame transformation helper methods. These transformation methods are useful for optimizing face detection in frames. Typically face detection takes much longer the more pixels there are to consider. Therefore, using :func:`~scale` or :func:`~resize` will help you speed up detection. These helper transforms can be composed together to produce apply multiple operations on a single frame. For example, if we wanted to first downscale by half and then rotate a frame by 90 degrees, we could do something like the following: .. code-block:: python from facelift.transform import rotate, scale transformed_frame = rotate(scale(frame, 0.5), 90) Attributes: DEFAULT_INTERPOLATION (int): The default type of interpolation to use in transforms that require an interpolation method. Defaults to ``cv2.INTER_AREA``. """ import warnings from typing import Optional, Tuple import cv2 import numpy from .types import Frame DEFAULT_INTERPOLATION: int = cv2.INTER_AREA def copy(frame: Frame) -> Frame: """Copy the given frame to a new location in memory. Examples: >>> from facelift.transform import copy >>> copied_frame = copy(frame) >>> assert frame == copied_frame >>> assert frame is not copied_frame Args: frame (:attr:`~.types.Frame`): The frame to copy Returns: :attr:`~.types.Frame`: An exact copy of the given frame """ return frame.copy() def scale( frame: Frame, factor: float, interpolation: int = DEFAULT_INTERPOLATION ) -> Frame: """Scale a given frame down or up depending on the given scale factor. Examples: Downscaling a frame can be performed with a ``scale`` factor >0 and <1. For example, scaling a frame to half of its original size would require a scale factor of 0.5. >>> from facelift.transform import scale >>> assert frame.shape[:1] == [512, 512] >>> downscaled_frame = scale(frame, 0.5) >>> assert downscaled_frame.shape[:1] == [256, 256] Upscaling a frame with this method is **very** naive and suboptimal. However, any value >1 will result in a upscaled frame. For example, scaling a frame to double its original size would require a scale factor of 2. >>> from facelift.transform import scale >>> assert frame.shape[:1] == [512, 512] >>> upscaled_frame = scale(frame, 2) >>> assert upscaled_frame.shape[:1] == [1024, 1024] Following this logic, a scale factor of 1 would result in absolutely no change to the given frame. .. warning:: This transformation will return the **exact same frame instance** as the one provided through the ``frame`` parameter in the following cases: 1. If a factor of exactly ``1`` is given. In this case the scale operation would result in no change. 2. The given frame has factor less than ``1`` a width or height of 1px. In this case we are attempting to scale down the given frame and we cannot scale down the frame any further without producing a 0px frame. Args: frame (:attr:`~.types.Frame`): The frame to scale factor (float): The factor to scale the given frame interpolation (Optional[int], optional): The type of interpolation to use in the scale operation. Defaults to :attr:`~DEFAULT_INTERPOLATION`. Raises: ValueError: When the given scale factor is not positive Returns: :attr:`~.types.Frame`: The newly scaled frame """ if factor <= 0: raise ValueError( f"Factor should be a positive floating point, received {factor!r}" ) if factor == 1: return frame height, width, *_ = frame.shape if factor < 1 and (height == 1 or width == 1): return frame return cv2.resize( src=frame, dsize=None, fx=factor, fy=factor, interpolation=interpolation, ) def resize( frame: Frame, width: Optional[int] = None, height: Optional[int] = None, lock_aspect: bool = True, interpolation: int = DEFAULT_INTERPOLATION, ) -> Frame: """Resize a given frame to a given width and/or height. * If both width and height are given, the frame will be resized accordingly. * If only one of width or height is given, the frame will be resized according to the provided dimension (either width or height). * As long as ``lock_aspect`` is truthy, the unprovided dimension will be adjusted to maintain the original aspect-ratio of the frame. * If ``lock_aspect`` is falsy, the resize operation will only scale the provided dimension while keeping the original size of the unprovided dimension. Examples: Resize a frame's width while keeping the height relative: >>> from facelift.transform import resize >>> assert frame.shape[:1] == [512, 512] >>> resized_frame = resize(frame, width=256, lock_aspect=True) >>> assert resized_frame.shape[:1] == [256, 256] Resize a frame's width while keeping the original height: >>> from facelift.transform import resize >>> assert frame.shape[:1] == [512, 512] >>> resized_frame = resize(frame, width=256, lock_aspect=False) >>> assert resized_frame.shape[:1] == [512, 256] Resize both a frame's width and height: >>> from facelift.transform import resize >>> assert frame.shape[:1] == [512, 512] >>> resized_frame = resize(frame, width=256, height=128) >>> assert resized_frame.shape[:1] == [128, 256] Args: frame (:attr:`~.types.Frame`): The frame to resize width (Optional[int], optional): The exact width to resize the frame to. height (Optional[int], optional): The exact height to resize the frame to. lock_aspect (bool, optional): Whether to keep the width and height relative when only given one value. Defaults to True. interpolation (int, optional): The type of interpolation to use in the resize operation. Defaults to :attr:`~DEFAULT_INTERPOLATION`. Returns: :attr:`~.types.Frame`: The newly resized frame """ if width == 0 or height == 0: raise ValueError("Cannot resize frame to a width or height of 0") if width is None and height is None: return frame if width and height: return cv2.resize( src=frame, dsize=(width, height), fx=None, fy=None, interpolation=interpolation, ) frame_height, frame_width, *_ = frame.shape if not lock_aspect: return cv2.resize( src=frame, dsize=(width or frame_width, height or frame_height), fx=None, fy=None, interpolation=interpolation, ) if height is not None: relative_width = int(frame_width * (height / float(frame_height))) or 1 return cv2.resize( src=frame, dsize=(relative_width, height), fx=None, fy=None, interpolation=interpolation, ) elif width is not None: relative_height = int(frame_height * (width / float(frame_width))) or 1 return cv2.resize( src=frame, dsize=(width, relative_height), fx=None, fy=None, interpolation=interpolation, ) return frame # pragma: no cover def rotate( frame: Frame, degrees: int, interpolation: int = DEFAULT_INTERPOLATION ) -> Frame: """Rotate a frame while keeping the whole frame visible. Examples: >>> from facelift.transform import rotate >>> rotated_90 = rotate(frame, 90) >>> rotated_neg_90 = rotate(frame, -90) .. warning:: This transform typically will produce larger frames since we are producing a rotated frame while keeping the original frame completely visible. This means if we do a perfect 45 degree rotation on a 512x512 frame we will produce a 724x724 frame since the 512x512 frame is now on a angle that requires a larger container. Be cautious when using rotation. Most of the time you do not need to rotate on any angles other than 90, 180, and 270 for decent face detection. However, this isn't *always* true. Args: frame (:attr:`~.types.Frame`): The frame to rotate degrees (int): The number of degrees to rotate the given frame interpolation (int, optional): The type of interpolation to use in the produced rotation matrix. Defaults to :attr:`~DEFAULT_INTERPOLATION`. Returns: :attr:`~.types.Frame`: The newly rotated frame """ if abs(degrees) in (0, 360): return frame frame_height, frame_width, *_ = frame.shape center_x, center_y = frame_width / 2, frame_height / 2 rotation_matrix = cv2.getRotationMatrix2D( center=(center_x, center_y), angle=-degrees, scale=1.0 ) cos = numpy.abs(rotation_matrix[0, 0]) sin = numpy.abs(rotation_matrix[0, 1]) new_width = int((frame_height * sin) + (frame_width * cos)) new_height = int((frame_height * cos) + (frame_width * sin)) rotation_matrix[0, 2] += (new_width / 2) - center_x rotation_matrix[1, 2] += (new_height / 2) - center_y return cv2.warpAffine( src=frame, M=rotation_matrix, dsize=(new_width, new_height), flags=interpolation, ) def crop(frame: Frame, start: Tuple[int, int], end: Tuple[int, int]) -> Frame: """Crop the given frame between two top-left to bottom-right points. Examples: Crop a frame from the first pixel to the center pixel. >>> from facelift.transform import crop >>> assert frame.shape[:1] == [512, 512] >>> cropped_frame = crop(frame, (0, 0), (256, 256)) >>> assert cropped_frame.shape[:1] == [256, 256] Args: frame (:attr:`~.types.Frame`): The frame to crop start (Tuple[int, int]): The top-left point to start the crop at end (Tuple[int, int]): The bottom-right point to end the crop at Raises: ValueError: When the given starting crop point appears after the given ending crop point Returns: :attr:`~.types.Frame`: The newly cropped frame """ left, top = start right, bottom = end if right <= left or bottom <= top: raise ValueError( "Starting crop point cannot be greater than the ending crop point, " f"(start={start}, end={end})" ) width = right - left height = bottom - top return frame[top : top + height, left : left + width] def translate( frame: Frame, delta_x: Optional[int] = None, delta_y: Optional[int] = None, interpolation: int = DEFAULT_INTERPOLATION, ) -> Frame: """Translate the given frame a specific distance away from its origin. Examples: >>> from facelift.transform import translate >>> translated_neg_90_x_frame = translate(frame, delta_x=-90) .. important:: This translation retains the original size of the given frame. So a 512x512 frame translated 90px on the x-axis will still be 512x512 and space where the frame use to take up will be essentially nulled out. Args: frame (:attr:`~.types.Frame`): The frame to translate delta_x (Optional[int], optional): The pixel distance to translate the frame on the x-axis. delta_y (Optional[int], optional): The pixel distance to translate the frame on the y-axis. interpolation (int, optional): The type of interpolation to use during the translation. Defaults to :attr:`~DEFAULT_INTERPOLATION`. Returns: :attr:`~.types.Frame`: The newly translated frame """ if delta_x is None and delta_y is None: return frame translation_matrix = numpy.float32([[1, 0, delta_x or 0], [0, 1, delta_y or 0]]) frame_height, frame_width, *_ = frame.shape return cv2.warpAffine( src=frame, M=translation_matrix, dsize=(frame_width, frame_height), flags=interpolation, ) def flip(frame: Frame, x_axis: bool = False, y_axis: bool = False) -> Frame: """Flip the given frame over either or both the x and y axis. Examples: >>> from facelift.transform import flip >>> vertically_flipped_frame = flip(frame, x_axis=True) >>> horizontally_flipped_frame = flip(frame, y_axis=True) >>> inverted_frame = flip(frame, x_axis=True, y_axis=True) Args: frame (:attr:`~.types.Frame`): The frame to flip x_axis (bool, optional): Flag indicating the frame should be flipped vertically. Defaults to False. y_axis (bool, optional): Flag indicating the frame should be flipped horizontally. Defaults to False. Returns: :attr:`~.types.Frame`: The newly flipped frame """ if not x_axis and not y_axis: return frame if x_axis and y_axis: flip_code = -1 elif y_axis: flip_code = 0 else: flip_code = 1 return cv2.flip(src=frame, flipCode=flip_code) def adjust( frame: Frame, brightness: Optional[int] = None, sharpness: Optional[float] = None, ) -> Frame: """Adjust the brightness or sharpness of a frame. Examples: >>> from facelift.transform import adjust >>> sharper_frame = adjust(frame, sharpness=1.4) >>> brighter_frame = adjust(frame, brightness=10) >>> sharper_and_brighter_frame = adjust(frame, sharpness=1.4, brightness=10) Args: frame (:attr:`~.types.Frame`): The frame to adjust brightness (Optional[int], optional): The new brightness of the frame (can be negative, default is 0). Defaults to 0. sharpness (Optional[float], optional): The new sharpness of the frame (0.0 is black, default is 1.0). Defaults to 1.0. Returns: :attr:`~.types.Frame`: The newly adjusted frame """ if brightness is None and sharpness is None: return frame if brightness is None: brightness = 0 if sharpness is None: sharpness = 1.0 return cv2.convertScaleAbs(src=frame, alpha=sharpness, beta=brightness) def grayscale(frame: Frame) -> Frame: """Convert the given frame to grayscale. This helper is useful *sometimes* for classification as color doesn't matter as much during face encoding. Examples: >>> from facelift.transform import grayscale >>> grayscale_frame = grayscale(bgr_frame) Args: frame (:attr:`~.types.Frame`): The BGR frame to convert to grayscale Returns: :attr:`~.types.Frame`: The newly grayscaled frame """ return cv2.cvtColor(src=frame, code=cv2.COLOR_BGR2GRAY) def rgb(frame: Frame) -> Frame: """Convert the given frame to RGB. This helper transform is typically needed when working with other image processing libraries such as `pillow <https://pillow.readthedocs.io/en/stable/>`_ as they work in RGB coordinates while OpenCV works in BGR coordinates. Examples: >>> from facelift.transform import rgb >>> rgb_frame = rgb(bgr_frame) Args: frame (:attr:`~.types.Frame`): The BGR frame to convert to RGB Returns: :attr:`~.types.Frame`: The new RGB frame """ return cv2.cvtColor(src=frame, code=cv2.COLOR_BGR2RGB)
[ "numpy.abs", "cv2.cvtColor", "numpy.float32", "cv2.warpAffine", "cv2.convertScaleAbs", "cv2.flip", "cv2.getRotationMatrix2D", "cv2.resize" ]
[((4081, 4170), 'cv2.resize', 'cv2.resize', ([], {'src': 'frame', 'dsize': 'None', 'fx': 'factor', 'fy': 'factor', 'interpolation': 'interpolation'}), '(src=frame, dsize=None, fx=factor, fy=factor, interpolation=\n interpolation)\n', (4091, 4170), False, 'import cv2\n'), ((9345, 9424), 'cv2.getRotationMatrix2D', 'cv2.getRotationMatrix2D', ([], {'center': '(center_x, center_y)', 'angle': '(-degrees)', 'scale': '(1.0)'}), '(center=(center_x, center_y), angle=-degrees, scale=1.0)\n', (9368, 9424), False, 'import cv2\n'), ((9450, 9482), 'numpy.abs', 'numpy.abs', (['rotation_matrix[0, 0]'], {}), '(rotation_matrix[0, 0])\n', (9459, 9482), False, 'import numpy\n'), ((9493, 9525), 'numpy.abs', 'numpy.abs', (['rotation_matrix[0, 1]'], {}), '(rotation_matrix[0, 1])\n', (9502, 9525), False, 'import numpy\n'), ((9782, 9882), 'cv2.warpAffine', 'cv2.warpAffine', ([], {'src': 'frame', 'M': 'rotation_matrix', 'dsize': '(new_width, new_height)', 'flags': 'interpolation'}), '(src=frame, M=rotation_matrix, dsize=(new_width, new_height),\n flags=interpolation)\n', (9796, 9882), False, 'import cv2\n'), ((12444, 12503), 'numpy.float32', 'numpy.float32', (['[[1, 0, delta_x or 0], [0, 1, delta_y or 0]]'], {}), '([[1, 0, delta_x or 0], [0, 1, delta_y or 0]])\n', (12457, 12503), False, 'import numpy\n'), ((12564, 12671), 'cv2.warpAffine', 'cv2.warpAffine', ([], {'src': 'frame', 'M': 'translation_matrix', 'dsize': '(frame_width, frame_height)', 'flags': 'interpolation'}), '(src=frame, M=translation_matrix, dsize=(frame_width,\n frame_height), flags=interpolation)\n', (12578, 12671), False, 'import cv2\n'), ((13724, 13763), 'cv2.flip', 'cv2.flip', ([], {'src': 'frame', 'flipCode': 'flip_code'}), '(src=frame, flipCode=flip_code)\n', (13732, 13763), False, 'import cv2\n'), ((14837, 14901), 'cv2.convertScaleAbs', 'cv2.convertScaleAbs', ([], {'src': 'frame', 'alpha': 'sharpness', 'beta': 'brightness'}), '(src=frame, alpha=sharpness, beta=brightness)\n', (14856, 14901), False, 'import cv2\n'), ((15402, 15450), 'cv2.cvtColor', 'cv2.cvtColor', ([], {'src': 'frame', 'code': 'cv2.COLOR_BGR2GRAY'}), '(src=frame, code=cv2.COLOR_BGR2GRAY)\n', (15414, 15450), False, 'import cv2\n'), ((16028, 16075), 'cv2.cvtColor', 'cv2.cvtColor', ([], {'src': 'frame', 'code': 'cv2.COLOR_BGR2RGB'}), '(src=frame, code=cv2.COLOR_BGR2RGB)\n', (16040, 16075), False, 'import cv2\n'), ((6762, 6857), 'cv2.resize', 'cv2.resize', ([], {'src': 'frame', 'dsize': '(width, height)', 'fx': 'None', 'fy': 'None', 'interpolation': 'interpolation'}), '(src=frame, dsize=(width, height), fx=None, fy=None,\n interpolation=interpolation)\n', (6772, 6857), False, 'import cv2\n'), ((7013, 7139), 'cv2.resize', 'cv2.resize', ([], {'src': 'frame', 'dsize': '(width or frame_width, height or frame_height)', 'fx': 'None', 'fy': 'None', 'interpolation': 'interpolation'}), '(src=frame, dsize=(width or frame_width, height or frame_height),\n fx=None, fy=None, interpolation=interpolation)\n', (7023, 7139), False, 'import cv2\n'), ((7330, 7434), 'cv2.resize', 'cv2.resize', ([], {'src': 'frame', 'dsize': '(relative_width, height)', 'fx': 'None', 'fy': 'None', 'interpolation': 'interpolation'}), '(src=frame, dsize=(relative_width, height), fx=None, fy=None,\n interpolation=interpolation)\n', (7340, 7434), False, 'import cv2\n'), ((7625, 7729), 'cv2.resize', 'cv2.resize', ([], {'src': 'frame', 'dsize': '(width, relative_height)', 'fx': 'None', 'fy': 'None', 'interpolation': 'interpolation'}), '(src=frame, dsize=(width, relative_height), fx=None, fy=None,\n interpolation=interpolation)\n', (7635, 7729), False, 'import cv2\n')]
#This code comes from: https://github.com/becomequantum/kryon from PIL import Image,ImageDraw,ImageFont import numpy as np #This code is only about animation. 本代码只是和做演示动画相关. VideoSize = (1280, 720) DemoImageSize = (48, 36) 标题位置 = (60, 16) 注释1位置 = (1000, 76) 网格位置 = (32, 76) 比例 = 17 网格颜色 = (230, 230, 230) 网三位置 = (网格位置[0] + 比例 * DemoImageSize[0] + 比例 * 2, 网格位置[1]) 网三比例 = 比例 * 2 坐标位置 = (网三位置[0], 网三位置[1] + 网三比例 * 3 + 5) 注释2位置 = (坐标位置[0], 坐标位置[1] + 比例 + 18) 副标题位置 = (注释2位置[0],注释2位置[1] + 350) UnitTime = 0.1 ScanTime = 0.1 FinishTime = 0.1 frame_list = [] def 微软雅黑(Size): return ImageFont.truetype("msyh.ttf", Size) def 方框(x, y, 位置, 比例): 左上 = (位置[0] + x * 比例, 位置[1] + y * 比例) 右下 = (位置[0] + x * 比例 + 比例, 位置[1] + y * 比例 + 比例) return [左上, 右下] def 小方框(x, y, 位置, 比例): 左上 = (位置[0] + x * 比例 + 2, 位置[1] + y * 比例 + 2) 右下 = (位置[0] + x * 比例 + 比例 - 2, 位置[1] + y * 比例 + 比例 - 2) return [左上, 右下] def 方块(x, y, 位置, 比例): 左上 = (位置[0] + x * 比例 + 1, 位置[1] + y * 比例 + 1) 右下 = (位置[0] + x * 比例 + 比例 - 1, 位置[1] + y * 比例 + 比例 - 1) return [左上, 右下] def 完成框(ShapeInfo): 左上 = (网格位置[0] + ShapeInfo[2][0] * 比例 - 1, 网格位置[1] + ShapeInfo[2][1] * 比例 - 1) 右下 = (网格位置[0] + ShapeInfo[1][0] * 比例 + 比例 + 1, 网格位置[1] + ShapeInfo[1][1] * 比例 + 比例 + 1) return [左上, 右下] def 反色(color): rcolor = (255 - color[0], 255 - color[1], 255 - color[2]) return rcolor def InitBackGround(ExampleImage, Title, subtitle, textcolor = (0, 162, 232), subtitlecolor = "orange", BgColor = (255, 255, 255), FPGA = False): back_ground_image = Image.new("RGB", VideoSize, BgColor) 画 = ImageDraw.Draw(back_ground_image) 画.text(标题位置,Title, fill = textcolor, font = 微软雅黑(30)) 画.text(副标题位置, subtitle, fill = subtitlecolor, font=微软雅黑(25)) for y in range(DemoImageSize[1]): for x in range(DemoImageSize[0]): 画.rectangle(方框(x, y, 网格位置, 比例), outline = 网格颜色) #画大背景网格 if not(ExampleImage[y, x ,0] == ExampleImage[y, x ,1] == ExampleImage[y, x ,0] == 255): 画.rectangle(方块(x, y, 网格位置, 比例), fill = "black") #画示例图片中的黑点 ExampleImage[y, x] = [0, 0, 0] #不是白点的都变成黑点 if x<= 2 and y <= 2 : 画.rectangle(方框(x, y, 网三位置, 网三比例), outline = 网格颜色) #画右边3x3小邻域网格 if FPGA and (y == 1 or (y == 2 and x == 0)): 画.rectangle(方框(x, y - 1, 网三位置, 网三比例), outline = "blue") 画.rectangle(方框(1, 1, 网三位置, 网三比例), outline = "red") return back_ground_image def AddClip(bg_image, x, y, Neighbourhood3x3, LabelColor = None, diff = False, duration = UnitTime, Shape_info = None, 注释1 =" ", 注释2 =" "): 标记 = ImageDraw.Draw(bg_image) if LabelColor != None : 标记.rectangle(方块(x, y, 网格位置, 比例), fill = LabelColor, outline = None) #画标记色块 if diff: #周围有两个不同标号点时 标记.rectangle(小方框(x, y , 网格位置, 比例), outline = 反色(LabelColor)) temp_image = bg_image.copy() 画 = ImageDraw.Draw(temp_image) if Shape_info != None : 标记.rectangle(完成框(Shape_info), outline = "red") 画.rectangle(完成框(Shape_info), outline = "red") 画.rectangle(方框(x, y, 网格位置, 比例), outline = "red") #画小红框 画.text(注释1位置, 注释1, fill = "purple", font = 微软雅黑(25)) 画.text(注释2位置, 注释2, fill = LabelColor if (LabelColor != None) else "purple", font = 微软雅黑(25)) 画.text(坐标位置, str((x, y)), fill = "black", font = 微软雅黑(25)) for y in range(3): for x in range(3): 画.rectangle(方块(x, y, 网三位置, 网三比例), fill = tuple(Neighbourhood3x3[y, x])) [frame_list.append(np.array(temp_image)) for n in range (int(duration / UnitTime))]
[ "PIL.ImageFont.truetype", "PIL.ImageDraw.Draw", "PIL.Image.new", "numpy.array" ]
[((603, 639), 'PIL.ImageFont.truetype', 'ImageFont.truetype', (['"""msyh.ttf"""', 'Size'], {}), "('msyh.ttf', Size)\n", (621, 639), False, 'from PIL import Image, ImageDraw, ImageFont\n'), ((1592, 1628), 'PIL.Image.new', 'Image.new', (['"""RGB"""', 'VideoSize', 'BgColor'], {}), "('RGB', VideoSize, BgColor)\n", (1601, 1628), False, 'from PIL import Image, ImageDraw, ImageFont\n'), ((1640, 1673), 'PIL.ImageDraw.Draw', 'ImageDraw.Draw', (['back_ground_image'], {}), '(back_ground_image)\n', (1654, 1673), False, 'from PIL import Image, ImageDraw, ImageFont\n'), ((2732, 2756), 'PIL.ImageDraw.Draw', 'ImageDraw.Draw', (['bg_image'], {}), '(bg_image)\n', (2746, 2756), False, 'from PIL import Image, ImageDraw, ImageFont\n'), ((3083, 3109), 'PIL.ImageDraw.Draw', 'ImageDraw.Draw', (['temp_image'], {}), '(temp_image)\n', (3097, 3109), False, 'from PIL import Image, ImageDraw, ImageFont\n'), ((3714, 3734), 'numpy.array', 'np.array', (['temp_image'], {}), '(temp_image)\n', (3722, 3734), True, 'import numpy as np\n')]
import matplotlib.pyplot as plt import matplotlib.gridspec as gridspec import librosa import librosa.display import numpy as np def summary(x): if x.ndim == 1: SUM = ('\n{0:>10s}: {1:>15.4f}').format('min', np.amin(x)) SUM += ('\n{0:>10s}: {1:>15.4f}').format('1st Quar', np.percentile(x, 25)) SUM += ('\n{0:>10s}: {1:>15.4f}').format('median', np.median(x)) SUM += ('\n{0:>10s}: {1:>15.4f}').format('mean', np.mean(x)) SUM += ('\n{0:>10s}: {1:>15.4f}').format('3rd Quar', np.percentile(x, 75)) SUM += ('\n{0:>10s}: {1:>15.4f}').format('max', np.amax(x)) SUM += ('\n{0:>10s}: {1:>15.4f}').format('sigma', np.std(x)) elif x.ndim == 2: E = x[:,0] D = x[:,1] SUM = ('{0:>%ss} {1:>%ss}' % (27, 15)).format('L', 'R') SUM += ('\n{0:>10s}: {1:>15.4f} {2:>15.4f}').format('min', np.amin(E), np.amin(D)) SUM += ('\n{0:>10s}: {1:>15.4f} {2:>15.4f}').format('1st Quar', np.percentile(E, 25), np.percentile(D, 25)) SUM += ('\n{0:>10s}: {1:>15.4f} {2:>15.4f}').format('median', np.median(E), np.median(D)) SUM += ('\n{0:>10s}: {1:>15.4f} {2:>15.4f}').format('mean', np.mean(E), np.mean(D)) SUM += ('\n{0:>10s}: {1:>15.4f} {2:>15.4f}').format('3rd Quar', np.percentile(E, 75), np.percentile(D, 75)) SUM += ('\n{0:>10s}: {1:>15.4f} {2:>15.4f}').format('max', np.amax(E), np.amax(D)) SUM += ('\n{0:>10s}: {1:>15.4f} {2:>15.4f}').format('sigma', np.std(E), np.std(D)) else: raise ValueError('Invalid argument! It is not an audio..') print(SUM) def audiovis(x, fs=44100, **kwargs): dx, dy = (1536, 512) if 'dims' not in kwargs else kwargs['dims'] dpi = 72 if 'dpi' not in kwargs else kwargs['dpi'] text = '' if 'text' not in kwargs else kwargs['text'] samples = x.shape[0] time = samples/fs if 'time' not in kwargs: to, ti = [0, time] else: to, ti = kwargs['time'][[0, -1]] tmin, tmax = (to, ti) if 'tlim' not in kwargs else kwargs['tlim'] t = np.linspace(to, ti, samples) if x.ndim == 1: print('audio mono') fig = plt.figure(figsize=(dx/dpi, dy/dpi)) plt.plot(t, x) plt.xlim([tmin, tmax]) elif x.ndim == 2: print('audio stereo') fig = plt.figure(figsize=(dx/dpi, 2*dy/dpi)) plt.subplot(2, 1, 1) plt.plot(t, x[:, 0], color='#00ff88') plt.xlim([tmin, tmax]) plt.subplot(2, 1, 2) plt.plot(t, x[:, 1], color='#0088ff') plt.xlim([tmin, tmax]) else: raise ValueError('Invalid argument! It is not an audio..') plt.title(text) plt.show() def spectrogram(x, fs=44100, **kwargs): dx, dy = (1536, 512) if 'dims' not in kwargs else kwargs['dims'] dpi = 72 if 'dpi' not in kwargs else kwargs['dpi'] fmin, fmax = [0, 8000] if 'flim' not in kwargs else kwargs['flim'] text = '' if 'text' not in kwargs else kwargs['text'] x = x.astype(np.float32) if x.ndim == 1: print('audio mono') fig = plt.figure(figsize=(dx/dpi, dy/dpi)) X = np.abs(librosa.stft(x)) X = librosa.amplitude_to_db(X, ref=np.max) librosa.display.specshow(X, sr=fs, y_axis='linear') plt.ylim([fmin, fmax]) plt.colorbar(format='%+2.0f dB') elif x.ndim == 2: print('audio stereo') fig = plt.figure(figsize=(dx/dpi, 2*dy/dpi)) plt.subplot(2, 1, 1) X = np.abs(librosa.stft(x[:, 0])) X = librosa.amplitude_to_db(X, ref=np.max) librosa.display.specshow(X, sr=fs, y_axis='linear') plt.ylim([fmin, fmax]) plt.colorbar(format='%+2.0f dB') plt.subplot(2, 1, 2) X = np.abs(librosa.stft(x[:, 1])) X = librosa.amplitude_to_db(X, ref=np.max) librosa.display.specshow(X, sr=fs, y_axis='linear') plt.ylim([fmin, fmax]) plt.colorbar(format='%+2.0f dB') else: raise ValueError('Invalid argument! It is not an audio..') plt.title(text) plt.show()
[ "matplotlib.pyplot.title", "matplotlib.pyplot.xlim", "matplotlib.pyplot.subplot", "matplotlib.pyplot.show", "numpy.amin", "matplotlib.pyplot.plot", "matplotlib.pyplot.ylim", "numpy.median", "numpy.std", "matplotlib.pyplot.colorbar", "numpy.percentile", "numpy.amax", "matplotlib.pyplot.figure", "numpy.mean", "numpy.linspace", "librosa.amplitude_to_db", "librosa.display.specshow", "librosa.stft" ]
[((1882, 1910), 'numpy.linspace', 'np.linspace', (['to', 'ti', 'samples'], {}), '(to, ti, samples)\n', (1893, 1910), True, 'import numpy as np\n'), ((2373, 2388), 'matplotlib.pyplot.title', 'plt.title', (['text'], {}), '(text)\n', (2382, 2388), True, 'import matplotlib.pyplot as plt\n'), ((2390, 2400), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (2398, 2400), True, 'import matplotlib.pyplot as plt\n'), ((3579, 3594), 'matplotlib.pyplot.title', 'plt.title', (['text'], {}), '(text)\n', (3588, 3594), True, 'import matplotlib.pyplot as plt\n'), ((3596, 3606), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (3604, 3606), True, 'import matplotlib.pyplot as plt\n'), ((1959, 1999), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(dx / dpi, dy / dpi)'}), '(figsize=(dx / dpi, dy / dpi))\n', (1969, 1999), True, 'import matplotlib.pyplot as plt\n'), ((1998, 2012), 'matplotlib.pyplot.plot', 'plt.plot', (['t', 'x'], {}), '(t, x)\n', (2006, 2012), True, 'import matplotlib.pyplot as plt\n'), ((2015, 2037), 'matplotlib.pyplot.xlim', 'plt.xlim', (['[tmin, tmax]'], {}), '([tmin, tmax])\n', (2023, 2037), True, 'import matplotlib.pyplot as plt\n'), ((2758, 2798), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(dx / dpi, dy / dpi)'}), '(figsize=(dx / dpi, dy / dpi))\n', (2768, 2798), True, 'import matplotlib.pyplot as plt\n'), ((2831, 2869), 'librosa.amplitude_to_db', 'librosa.amplitude_to_db', (['X'], {'ref': 'np.max'}), '(X, ref=np.max)\n', (2854, 2869), False, 'import librosa\n'), ((2872, 2923), 'librosa.display.specshow', 'librosa.display.specshow', (['X'], {'sr': 'fs', 'y_axis': '"""linear"""'}), "(X, sr=fs, y_axis='linear')\n", (2896, 2923), False, 'import librosa\n'), ((2926, 2948), 'matplotlib.pyplot.ylim', 'plt.ylim', (['[fmin, fmax]'], {}), '([fmin, fmax])\n', (2934, 2948), True, 'import matplotlib.pyplot as plt\n'), ((2951, 2983), 'matplotlib.pyplot.colorbar', 'plt.colorbar', ([], {'format': '"""%+2.0f dB"""'}), "(format='%+2.0f dB')\n", (2963, 2983), True, 'import matplotlib.pyplot as plt\n'), ((211, 221), 'numpy.amin', 'np.amin', (['x'], {}), '(x)\n', (218, 221), True, 'import numpy as np\n'), ((278, 298), 'numpy.percentile', 'np.percentile', (['x', '(25)'], {}), '(x, 25)\n', (291, 298), True, 'import numpy as np\n'), ((353, 365), 'numpy.median', 'np.median', (['x'], {}), '(x)\n', (362, 365), True, 'import numpy as np\n'), ((418, 428), 'numpy.mean', 'np.mean', (['x'], {}), '(x)\n', (425, 428), True, 'import numpy as np\n'), ((485, 505), 'numpy.percentile', 'np.percentile', (['x', '(75)'], {}), '(x, 75)\n', (498, 505), True, 'import numpy as np\n'), ((557, 567), 'numpy.amax', 'np.amax', (['x'], {}), '(x)\n', (564, 567), True, 'import numpy as np\n'), ((621, 630), 'numpy.std', 'np.std', (['x'], {}), '(x)\n', (627, 630), True, 'import numpy as np\n'), ((2089, 2133), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(dx / dpi, 2 * dy / dpi)'}), '(figsize=(dx / dpi, 2 * dy / dpi))\n', (2099, 2133), True, 'import matplotlib.pyplot as plt\n'), ((2130, 2150), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(2)', '(1)', '(1)'], {}), '(2, 1, 1)\n', (2141, 2150), True, 'import matplotlib.pyplot as plt\n'), ((2153, 2190), 'matplotlib.pyplot.plot', 'plt.plot', (['t', 'x[:, 0]'], {'color': '"""#00ff88"""'}), "(t, x[:, 0], color='#00ff88')\n", (2161, 2190), True, 'import matplotlib.pyplot as plt\n'), ((2193, 2215), 'matplotlib.pyplot.xlim', 'plt.xlim', (['[tmin, tmax]'], {}), '([tmin, tmax])\n', (2201, 2215), True, 'import matplotlib.pyplot as plt\n'), ((2218, 2238), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(2)', '(1)', '(2)'], {}), '(2, 1, 2)\n', (2229, 2238), True, 'import matplotlib.pyplot as plt\n'), ((2241, 2278), 'matplotlib.pyplot.plot', 'plt.plot', (['t', 'x[:, 1]'], {'color': '"""#0088ff"""'}), "(t, x[:, 1], color='#0088ff')\n", (2249, 2278), True, 'import matplotlib.pyplot as plt\n'), ((2281, 2303), 'matplotlib.pyplot.xlim', 'plt.xlim', (['[tmin, tmax]'], {}), '([tmin, tmax])\n', (2289, 2303), True, 'import matplotlib.pyplot as plt\n'), ((2808, 2823), 'librosa.stft', 'librosa.stft', (['x'], {}), '(x)\n', (2820, 2823), False, 'import librosa\n'), ((3035, 3079), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(dx / dpi, 2 * dy / dpi)'}), '(figsize=(dx / dpi, 2 * dy / dpi))\n', (3045, 3079), True, 'import matplotlib.pyplot as plt\n'), ((3076, 3096), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(2)', '(1)', '(1)'], {}), '(2, 1, 1)\n', (3087, 3096), True, 'import matplotlib.pyplot as plt\n'), ((3139, 3177), 'librosa.amplitude_to_db', 'librosa.amplitude_to_db', (['X'], {'ref': 'np.max'}), '(X, ref=np.max)\n', (3162, 3177), False, 'import librosa\n'), ((3180, 3231), 'librosa.display.specshow', 'librosa.display.specshow', (['X'], {'sr': 'fs', 'y_axis': '"""linear"""'}), "(X, sr=fs, y_axis='linear')\n", (3204, 3231), False, 'import librosa\n'), ((3234, 3256), 'matplotlib.pyplot.ylim', 'plt.ylim', (['[fmin, fmax]'], {}), '([fmin, fmax])\n', (3242, 3256), True, 'import matplotlib.pyplot as plt\n'), ((3259, 3291), 'matplotlib.pyplot.colorbar', 'plt.colorbar', ([], {'format': '"""%+2.0f dB"""'}), "(format='%+2.0f dB')\n", (3271, 3291), True, 'import matplotlib.pyplot as plt\n'), ((3294, 3314), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(2)', '(1)', '(2)'], {}), '(2, 1, 2)\n', (3305, 3314), True, 'import matplotlib.pyplot as plt\n'), ((3357, 3395), 'librosa.amplitude_to_db', 'librosa.amplitude_to_db', (['X'], {'ref': 'np.max'}), '(X, ref=np.max)\n', (3380, 3395), False, 'import librosa\n'), ((3398, 3449), 'librosa.display.specshow', 'librosa.display.specshow', (['X'], {'sr': 'fs', 'y_axis': '"""linear"""'}), "(X, sr=fs, y_axis='linear')\n", (3422, 3449), False, 'import librosa\n'), ((3452, 3474), 'matplotlib.pyplot.ylim', 'plt.ylim', (['[fmin, fmax]'], {}), '([fmin, fmax])\n', (3460, 3474), True, 'import matplotlib.pyplot as plt\n'), ((3477, 3509), 'matplotlib.pyplot.colorbar', 'plt.colorbar', ([], {'format': '"""%+2.0f dB"""'}), "(format='%+2.0f dB')\n", (3489, 3509), True, 'import matplotlib.pyplot as plt\n'), ((796, 806), 'numpy.amin', 'np.amin', (['E'], {}), '(E)\n', (803, 806), True, 'import numpy as np\n'), ((808, 818), 'numpy.amin', 'np.amin', (['D'], {}), '(D)\n', (815, 818), True, 'import numpy as np\n'), ((886, 906), 'numpy.percentile', 'np.percentile', (['E', '(25)'], {}), '(E, 25)\n', (899, 906), True, 'import numpy as np\n'), ((908, 928), 'numpy.percentile', 'np.percentile', (['D', '(25)'], {}), '(D, 25)\n', (921, 928), True, 'import numpy as np\n'), ((994, 1006), 'numpy.median', 'np.median', (['E'], {}), '(E)\n', (1003, 1006), True, 'import numpy as np\n'), ((1008, 1020), 'numpy.median', 'np.median', (['D'], {}), '(D)\n', (1017, 1020), True, 'import numpy as np\n'), ((1084, 1094), 'numpy.mean', 'np.mean', (['E'], {}), '(E)\n', (1091, 1094), True, 'import numpy as np\n'), ((1096, 1106), 'numpy.mean', 'np.mean', (['D'], {}), '(D)\n', (1103, 1106), True, 'import numpy as np\n'), ((1174, 1194), 'numpy.percentile', 'np.percentile', (['E', '(75)'], {}), '(E, 75)\n', (1187, 1194), True, 'import numpy as np\n'), ((1196, 1216), 'numpy.percentile', 'np.percentile', (['D', '(75)'], {}), '(D, 75)\n', (1209, 1216), True, 'import numpy as np\n'), ((1279, 1289), 'numpy.amax', 'np.amax', (['E'], {}), '(E)\n', (1286, 1289), True, 'import numpy as np\n'), ((1291, 1301), 'numpy.amax', 'np.amax', (['D'], {}), '(D)\n', (1298, 1301), True, 'import numpy as np\n'), ((1366, 1375), 'numpy.std', 'np.std', (['E'], {}), '(E)\n', (1372, 1375), True, 'import numpy as np\n'), ((1377, 1386), 'numpy.std', 'np.std', (['D'], {}), '(D)\n', (1383, 1386), True, 'import numpy as np\n'), ((3110, 3131), 'librosa.stft', 'librosa.stft', (['x[:, 0]'], {}), '(x[:, 0])\n', (3122, 3131), False, 'import librosa\n'), ((3328, 3349), 'librosa.stft', 'librosa.stft', (['x[:, 1]'], {}), '(x[:, 1])\n', (3340, 3349), False, 'import librosa\n')]
import sys import os from datetime import datetime import traceback import time from pathlib import Path import h5py import pickle import nept import scipy import numpy as np import pandas as pd from fooof import FOOOF # cwd = Path(os.getcwd()) # pkg_dir = cwd.parent # sys.path.append(str(pkg_dir)) import Utils.robust_stats as rs import matplotlib.pyplot as plt import seaborn as sns sns.set(style='whitegrid', palette='muted') ######################################################################################################################## ######################################################################################################################## ############################################### Main Funcs ############################################################# ######################################################################################################################## ######################################################################################################################## def process_tetrode(task, save_format='npy', overwrite_flag=0): # things to be saved: processed signal, tetrode info chan_files = task['filenames'] session = task['session'] sp = Path(task['sp']) # save path # Unpack the probe information. tt_id = task['tt_id'] fn = 'tt_{}'.format(tt_id) fn_info = fn + '_info.pickle'.format(tt_id) if not ((sp / (fn + '.' + save_format)).exists() and (sp/fn_info).exists()) or overwrite_flag: tt_info = get_tt_info(task) # pre-allocate data fs = tt_info['fs'] n_chans = tt_info['n_chans'] sig, time_samps = get_csc(str(chan_files[0])) n_samps = len(sig) tt_info['n_samps'] = n_samps tt_info['tB'] = time_samps[0] tt_info['tE'] = time_samps[-1] del time_samps # time stamps can be recreated with gathered information. raw_signals = np.empty((n_chans, n_samps)) raw_signals[0] = sig for ch, chf in enumerate(chan_files[1:]): raw_signals[ch + 1], _ = get_csc(str(chf)) del sig tt_info['Raw'] = get_signal_info(raw_signals, tt_info, get_clipped_segs =True) chan_th = ~np.isnan(tt_info['Raw']['PSD_table']['th_pk'].values.astype(float)) chan_60 = ~np.isnan(tt_info['Raw']['PSD_table']['60_pk'].values.astype(float)) chan_clp = tt_info['Raw']['PctChanClipped'] > tt_info['bad_chan_thr'] chan_code = chan_th * 4 + chan_60 * 2 + chan_clp tt_info['chan_code'] = chan_code tt_info['bad_chans'] = np.logical_and(chan_code > 0, chan_code < 4) SOS, _ = get_sos_filter_bank(['HP', 'LP', 'Notch'], fs=fs) f_signals = np.zeros_like(raw_signals) t0 = time.time() for ch in range(n_chans): f_signals[ch] = scipy.signal.sosfiltfilt(SOS, raw_signals[ch]) print('', end='.') t1 = time.time() print('\nTime to filter tetrode {0:0.2f}s'.format(t1 - t0)) del raw_signals f_signals = f_signals.astype(np.float16) save_probe(f_signals, sp, fn, save_format) # save tetrode info with (sp/fn_info).open(mode='wb') as f_handle: pickle.dump(tt_info, f_handle, protocol=pickle.HIGHEST_PROTOCOL) def process_video(task, overwrite_flag=0): raw_vt_file = task['filenames'] sp = Path(task['sp']) vt_file = 'vt.h5' if not (sp / vt_file).exists() or overwrite_flag: t, x, y, ha = get_position(raw_vt_file) with h5py.File(str(sp / vt_file), 'w') as hf: hf.create_dataset("t", data=t) hf.create_dataset("x", data=x) hf.create_dataset("y", data=y) hf.create_dataset("ha", data=ha) else: print('File exists and overwrite = false ') def process_events(task, overwrite_flag=0): try: raw_ev_file = task['filenames'] sp = Path(task['sp']) ss = task['subSessionID'] evFile = 'ev.h5' if not (sp / evFile).exists() or overwrite_flag: ev = get_events(raw_ev_file) with h5py.File(str(sp / evFile), 'w') as hf: for k, v in ev.items(): hf.create_dataset(k, data=v) else: print('File exists and overwrite = false ') except: print("Error processing events. ", sys.exc_info()[0], sys.exc_info()[1], sys.exc_info()[2].tb_lineno) def post_process_channel_table(subject_id, task_table): # get mapping for session and task id session2task = {} dates = {} for k in task_table.keys(): session = Path(task_table[k]['session_name']).name session2task[session] = k session_list = list(session2task.keys()) # sort sessions by date session_dates = pd.DataFrame() for session in session_list: try: session_dates.at[session, 'date'] = datetime.strptime(session.split('_')[2], '%m%d%y') except: pass sorted_sessions = list(session_dates.sort_values(by='date').index) channel_table = pd.DataFrame(columns=range(1, 17)) # obtain results for each session for session_date in sorted_sessions: task_id = session2task[session_date] valid_session = task_table[task_id]['n_files'] >= 18 if valid_session: # processed data paths for subsession_id, subsession_path in task_table[task_id]['sp'].items(): session_name = Path(subsession_path).name channel_table.loc[session_name] = -1 for tt in range(1, 17): tt_info_file = Path(subsession_path, 'tt_{}_info.pickle'.format(tt)) if tt_info_file.exists(): with tt_info_file.open(mode='rb') as f: tt_info = pickle.load(f) channel_table.at[session_name, tt] = (~tt_info['bad_chans']).sum() channel_table = channel_table.apply(pd.to_numeric) save_path = Path(subsession_path).parent if save_path.exists(): channel_table.to_csv(str(save_path / ('chan_table_{}.csv'.format(subject_id)))) ######################################################################################################################## ######################################################################################################################## ############################################### Auxiliary Funcs ######################################################## ######################################################################################################################## ######################################################################################################################## def save_probe(data, save_path, fn, save_format): if save_format == 'h5': # h5 format with h5py.File(str(save_path / (fn + '.' + save_format)), 'w') as hf: hf.create_dataset("tetrode", data=data) elif save_format == 'npy': # numpy np.save(str(save_path / (fn + '.' + save_format)), data) elif save_format == 'csv': # comma separeted values np.savetxt(str(save_path / (fn + '.' + save_format)), data, delimiter=',') elif save_format == 'bin': # binary data.tofile(str(save_path / (fn + '.' + save_format))) else: print('Unsuported save method specified {}, saving as .npy array.'.format(save_format)) np.save(str(save_path / (fn + '.' + save_format)), data) print('{}: results saved to {}'.format(fn, str(save_path))) print('') def get_session_info(session): return session.split('_') def get_tt_info(task): """ Parameters ---------- files -> Path, directory for the data ttNum -> tetrode number. Returns ------- dictionary with tetrode header information for each channel """ n_chans = 4 ads = np.zeros(n_chans) ref_chan = np.zeros(n_chans) chan_ids = np.zeros(n_chans) input_range = np.zeros(n_chans) # get headers: try: headers = [] for chf in task['filenames']: headers.append(get_header(str(chf))) except: print('Header Files could not be loaded. Error reading files from') return [] data_dir = Path(chf).parent fs = headers[0]['fs'] for ch, header in enumerate(headers): ads[ch] = header['AD'] ref_chan[ch] = header['RefChan'] chan_ids[ch] = header['ChanID'] input_range[ch] = header['InputRange'] tt_geom = np.zeros([4, 2]) tt_geom[1] = [0, 20] tt_geom[2] = [20, 0] tt_geom[3] = [20, 20] return {'data_dir': str(data_dir), 'session': task['session'], 'fs': fs, 'tt_num': task['tt_id'], 'n_chans': n_chans, 'chan_files': task['filenames'], 'a_ds': ads, 'ref_chan': ref_chan, 'chan_ids': chan_ids, 'input_range': input_range, 'tt_geom': tt_geom, 'bad_chan_thr': 0.2} def get_amp_hist(signals, tt_info, bin_step=50): """ Parameters ---------- signals -> numpy array of nchans x nsamples tt_info -> dictionary containing the header information for the channels bin_step -> amplitude binning step, 50 uV as default Returns ------- amp_hist -> counts at each bin bin_centers -> center of amplitude bins """ n_chans = tt_info['n_chans'] max_amp = max(tt_info['input_range']) bins = np.arange(-max_amp, max_amp + 1, bin_step) bin_centers = bins[:-1] + bin_step / 2 amp_hist = np.zeros((n_chans, len(bin_centers))) for ch in range(n_chans): amp_hist[ch], _ = np.histogram(signals[ch], bins) return amp_hist, bin_centers def get_chans_psd(signals, fs, resamp=True): # find next power of 2 based on fs: e # for fs=32k, nperseg = 2**15 = 32768, # the operation belows computes this efficiently for arbitrary fs # assumes that sigs is nChans x nSamps if np.argmax(signals.shape) == 0: signals = signals.T transpose_flag = 1 else: transpose_flag = 0 fs = int(fs) nperseg = (1 << (fs - 1).bit_length()) noverlap = 1 << int(fs * 0.05 - 1).bit_length() # for at least 5% overlap. freqs, pxx = scipy.signal.welch(signals, fs=fs, nperseg=nperseg, noverlap=noverlap) if resamp: # resample log-linear samps = np.arange(100) maxExp = 4 for e in np.arange(2, maxExp): samps = np.concatenate((samps, np.arange(10 ** e, 10 ** (e + 1), 10 ** (e - 1)))) freqs = freqs[samps] if signals.ndim == 1: pxx = pxx[samps] else: pxx = pxx[:, samps] if transpose_flag: pxx = pxx.T return pxx, freqs def get_tt_psd_peaks(freqs, pxx, theta_range=None): if theta_range is None: theta_range = [4, 12] n_chans = pxx.shape[0] sixty_range = [58, 62] df = pd.DataFrame(columns=['th_pk', 'th_amp', '60_pk', '60_amp', '1/f_r2', 'rmse']) for ch in range(n_chans): fm = FOOOF(max_n_peaks=2, peak_threshold=2.0, peak_width_limits=[0.5, 6.0], verbose=False) fm.fit(freqs, pxx[ch], [2, 100]) pks = fm.peak_params_.flatten()[::3] amps = fm.peak_params_.flatten()[1::3] idx = (pks >= theta_range[0]) & (pks <= theta_range[1]) theta_pk = pks[idx] theta_amp = amps[idx] idx = (pks >= sixty_range[0]) & (pks <= sixty_range[1]) sixty_pk = pks[idx] sixty_amp = amps[idx] if len(theta_pk) == 1: df.at[ch, 'th_pk'] = np.around(theta_pk[0], decimals=2) df.at[ch, 'th_amp'] = np.around(theta_amp[0], decimals=2) elif len(theta_pk) > 1: df.at[ch, 'th_pk'] = np.around(np.mean(theta_pk), decimals=2) df.at[ch, 'th_amp'] = np.around(np.mean(theta_amp), decimals=2) if len(sixty_pk) == 1: df.at[ch, '60_pk'] = np.around(sixty_pk[0], decimals=2) df.at[ch, '60_amp'] = np.around(sixty_amp[0], decimals=2) elif len(sixty_pk) > 1: df.at[ch, '60_pk'] = np.around(np.mean(sixty_pk), decimals=2) df.at[ch, '60_amp'] = np.around(np.mean(sixty_amp), decimals=2) df.at[ch, 'rmse'] = np.around(fm.error_, decimals=3) df.at[ch, '1/f_r2'] = np.around(fm.r_squared_, decimals=3) return df def get_clipped_segments(signals, tt_info, thr=0.99, sec_buffer=0.5): """ function that takes signals and return segments of clipped signal buffered by fs*segBuffer. Inputs: signals -> nChans x nSamps np.array ttInfo -> dict, must contain nChans, fs, and InputRange (maxAmplitude) thr -> float, thr*InputRange is used threshold the signal segBuffer -> float, seconds to buffer the clipped signal, segments take the buffer into account Returns: Segs -> list of length nChans, each is a np.array of clipped segments for that channel (start and end indexes by # segments) in samples Durs -> list of length nChans, each element of the list is a np.array of length nSegs for that channel containing the durations in samples """ n_chans = tt_info['n_chans'] n_samps = tt_info['n_samps'] fs = tt_info['fs'] # binarize clipped segments samps_buffer = int(np.floor(fs * sec_buffer)) Durs = [np.array([], dtype=int)] * n_chans Segs = [np.array([], dtype=int)] * n_chans for ch in range(n_chans): durs = np.array([], dtype=int) segs = np.array([], dtype=int) try: signal_mask = (np.abs(signals[ch]) >= tt_info['input_range'][ch] * thr).astype(int) diff_sig = np.concatenate(([0], np.diff(signal_mask))) idx_start = np.argwhere(diff_sig > 0).flatten() idx_end = np.argwhere(diff_sig < 0).flatten() # if idxStart and end match (ends>starts, #ends==#starts) if len(idx_start) > 0: if len(idx_start) == len(idx_end): if np.all(idx_end > idx_start): pass else: # if some reason some starts > ends.. print('Some start/end masking indices mismatch for ch{}'.format(ch)) continue # channel loop # edge case of clipping near the end of the recording elif (len(idx_end) + 1) == len(idx_start): if np.all(idx_end > idx_start[:-1]): idx_end = np.concatenate((idx_end, np.array([n_samps]))) else: print('start/end masking indices mismatch for ch{}'.format(ch)) continue # channel loop # edge case of clipping at the beginning of recording elif (len(idx_start) + 1) == len(idx_end): if np.all(idx_end[1:] > idx_start): idx_start = np.concatenate(([0], idx_start)) else: print('start/end masking indices mismatch for ch{}'.format(ch)) continue # channel loop else: print('unknwon error in masks for ch{}, debug independently.'.format(ch)) print(len(idx_start), len(idx_end)) continue # channel loop # add seg_buffer for all segments idx_start = idx_start - samps_buffer idx_end = idx_end + samps_buffer # deal with start and end of recording ii = 0 while True: if idx_start[ii] - samps_buffer < 0: idx_start[ii] = 0 else: break # while ii += 1 ii = 1 while True: if idx_end[-ii] + samps_buffer > n_samps: idx_end[-ii] = n_samps else: break # while ii += 1 # consolidate segments after the buffering cnt = 0 seg_cnt = 0 n_sub_segs = len(idx_start) segs = [(idx_start[0], idx_end[0])] # check if start of the next sub segment is inside the previous, and join if so while cnt < (n_sub_segs - 1): while cnt < (n_sub_segs - 1): if idx_start[cnt + 1] <= idx_end[cnt]: segs[seg_cnt] = (segs[seg_cnt][0], idx_end[cnt + 1]) cnt += 1 else: cnt += 1 break # inner while segs.append((idx_start[cnt], idx_end[cnt])) seg_cnt += 1 # convert to np arrays durs = np.array(([j - i for i, j in segs])) segs = np.array(segs) except: print('Channel {} Error in getting clipped segments:'.format(ch)) print("Error", sys.exc_info()[0], sys.exc_info()[1], sys.exc_info()[2].tb_lineno) traceback.print_exc(file=sys.stdout) # add channel to lists Durs[ch] = durs Segs[ch] = segs return Segs, Durs def create_chan_masks(Segs, n_samps): n_chans = len(Segs) masks = np.ones((n_chans, n_samps), dtype=bool) for ch in range(n_chans): for seg in Segs[ch]: masks[ch][seg[0]:seg[1]] = False return masks def get_sos_filter_bank(f_types, fs=32000.0, hp_edge_freq=None, lp_edge_freq=None, sp_edge_freq=None, notch_freq=None, notch_harmonics=2, notch_q=20, gpass=0.2, gstop=60.0): """ Function that creates default filters fTypes -> list of filters that have to be ['HP', 'LP', 'Notch', 'Sp']. fs -> integer, sampling frequency in samps/s defualt to 32000 *_EdgeFreq -> edge frequencies for each filter type. Defaults are: HP-2Hz, LP-5000Hz, Sp->300Hz [High Pass], Notch->60Hz (3 Harmonics) Notch_Harmonics -> int, # of harmonics from Notch_Freq to filter [as default] gpass -> allowed oscillation gain in the pass bands [def. 0.2dB ~ to up to 1.03 multiplication of the pass band ] gstop -> required suppresion in the stopband [def. 60dB ~ at least to 0.001 multiplication of the stop band - ] returns SOS a N sections x 6 second order sections filter matrix. """ SOS = np.zeros((0, 6)) for f in f_types: if f not in ['HP', 'LP', 'Notch', 'Sp']: print('filter type {} not supported.'.format(f)) print('skipping filter.') # settings for low pass and bandpass if f in ['LP', 'HP']: if f is 'LP': if lp_edge_freq is None: cut_freq = 5000.0 cut_buffer = 5500.0 else: cut_freq = lp_edge_freq cut_buffer = lp_edge_freq + lp_edge_freq * 0.1 elif f is 'HP': if hp_edge_freq is None: cut_freq = 2.0 cut_buffer = 0.2 else: cut_freq = hp_edge_freq cut_buffer = hp_edge_freq * 0.1 sos = scipy.signal.iirdesign(cut_freq / (fs / 2), cut_buffer / (fs / 2), gpass, gstop, output='sos') SOS = np.vstack((SOS, sos)) if f is 'Notch': n_notches = notch_harmonics + 1 if notch_freq is None: cut_freq = np.arange(1, n_notches + 1) * 60.0 else: cut_freq = np.arange(1, n_notches + 1) * notch_freq if notch_q is None: q = np.array(cut_freq) # changing Quality factor to keep notch bandwidth constant. elif type(notch_q) is np.ndarray: if len(notch_q) >= n_notches: q = np.array(notch_q) # if length of quality factor array don't match the number of harmonics default to the first one elif len(notch_q) < n_notches: q = np.ones(n_notches) * notch_q[0] else: # Q = np.ones(nNotches)*Notch_Q q = np.arange(1, n_notches + 1) * notch_q for i, notch in enumerate(cut_freq): b, a = scipy.signal.iirnotch(notch, q[i], fs=fs) sos = scipy.signal.tf2sos(b, a) SOS = np.vstack((SOS, sos)) if f is 'Sp': if sp_edge_freq is None: cut_freq = 350.0 cut_buffer = 300.0 else: cut_freq = sp_edge_freq cut_buffer = sp_edge_freq - sp_edge_freq * 0.1 sos = scipy.signal.iirdesign(cut_freq / (fs / 2), cut_buffer / (fs / 2), gpass, gstop, output='sos') SOS = np.vstack((SOS, sos)) zi = scipy.signal.sosfilt_zi(SOS) return SOS, zi def get_signal_info(signals, tt_info, get_hist=True, get_psd=True, get_clipped_segs=False): out = {} t0 = time.time() if get_hist: out['AmpHist'], out['HistBins'] = get_amp_hist(signals, tt_info) print('Time to get amplitude histograms = {}s'.format(time.time() - t0)) t0 = time.time() if get_psd: out['PSD'], out['PSD_freqs'] = get_chans_psd(signals, tt_info['fs'], resamp=True) df = get_tt_psd_peaks(out['PSD_freqs'], out['PSD']) out['PSD_table'] = df print('Time to get compute power spectral densities = {}s'.format(time.time() - t0)) t0 = time.time() if get_clipped_segs: Segs, Durs = get_clipped_segments(signals, tt_info) out['ClippedSegs'] = Segs out['ClippedDurs'] = Durs out['PctChanClipped'] = np.array([np.sum(d) / tt_info['n_samps'] for d in Durs]) print('Time to get signal segment clips {}s'.format(time.time() - t0)) return out def get_signals_mad(signals, mask=None): if signals.ndim == 1: if mask is None: return rs.mad(signals) else: return rs.mad(signals[mask]) elif signals.ndim > 1: n_chans, n_samps = signals.shape sig_mad = np.zeros(n_chans) if mask is None: for ch in range(n_chans): sig_mad[ch] = rs.mad(signals[ch]) elif mask.shape[0] == n_chans: for ch in range(n_chans): sig_mad[ch] = rs.mad(signals[ch, mask[ch]]) elif mask.ndim == 1 and len(mask) == n_samps: for ch in range(n_chans): sig_mad[ch] = rs.mad(signals[ch], mask) else: print('Mask does not match the data. Ignoring,') for ch in range(n_chans): sig_mad[ch] = rs.mad(signals[ch]) return sig_mad ######################################################################################################################## ######################################################################################################################## ############################################### Neuralynx Read Funcs ################################################### ######################################################################################################################## ######################################################################################################################## def get_csc(fn): ''' returns signal in uV and time stamps''' temp = nept.load_lfp(fn) return np.float32(temp.data.flatten() * 1e6), temp.time def get_header(fn): h = nept.load_neuralynx_header(fn) for line in h.split(b'\n'): if line.strip().startswith(b'-ADBitVolts'): try: AD = np.array(float(line.split(b' ')[1].decode())) except ValueError: AD = 1 if line.strip().startswith(b'-ReferenceChannel'): try: RefChan = line.split(b' ')[3].decode() RefChan = int(RefChan[:-2]) except ValueError: RefChan = -1 if line.strip().startswith(b'-SamplingFrequency'): try: fs = int(line.split(b' ')[1].decode()) except ValueError: fs = 32000 if line.strip().startswith(b'-ADChannel'): try: ChanID = int(line.split(b' ')[1].decode()) except ValueError: ChanID = -1 if line.strip().startswith(b'-InputRange'): try: InputRange = int(line.split(b' ')[1].decode()) except ValueError: InputRange = -1 header = {'AD': AD, 'RefChan': RefChan, 'fs': fs, 'ChanID': ChanID, 'InputRange': InputRange} return header def get_position(fn): # Neuralynx files have a 16kbyte header # copy and modified from Nept Pckg. # f = open(fn, 'rb') header = f.read(2 ** 14).strip(b'\x00') # The format for .nvt files according the the neuralynx docs is # uint16 - beginning of the record # uint16 - ID for the system # uint16 - size of videorec in bytes # uint64 - timestamp in microseconds # uint32 x 400 - points with the color bitfield values # int16 - unused # int32 - extracted X location of target # int32 - extracted Y location of target # int32 - calculated head angle in degrees clockwise from the positive Y axis # int32 x 50 - colored targets using the same bitfield format used to extract colors earlier dt = np.dtype([('filler1', '<h', 3), ('time', '<Q'), ('points', '<i', 400), ('filler2', '<h'), ('x', '<i'), ('y', '<i'), ('head_angle', '<i'), ('targets', '<i', 50)]) data = np.fromfile(f, dt) t = data['time'] * 1e-6 x = np.array(data['x'], dtype=float) y = np.array(data['y'], dtype=float) ha = np.array(data['head_angle'], dtype=float) return t, x, y, ha def get_events(fn): events = {'DE1': 'DE1', 'DE2': 'DE2', 'DE3': 'DE3', 'DE4': 'DE4', 'DE5': 'DE5', 'DE6': 'DE6', 'L1': 'L1', 'L2': 'L2', 'L3': 'L3', 'L4': 'L4', 'L5': 'L5', 'L6': 'L6', 'RD': 'RD', 'CL': 'CL', 'CR': 'CR', 'Start': 'Starting Recording', 'Stop': 'Stopping Recording'} ev = nept.load_events(fn, events) return ev ######################################################################################################################## ######################################################################################################################## ######################################### Preprocessing Plottting Functions ####################################### ######################################################################################################################## ######################################################################################################################## def plot_test_sos_filter(SOS, fs, cos_f=None, cos_a=None, noise=None): if noise is None: noise = [0.1] if cos_a is None: cos_a = [0.2, 0.25] if cos_f is None: cos_f = [60, 8] n_samps = int(fs * 5) t = np.arange(n_samps) / fs x = (np.arange(n_samps) < fs / 3) + ((np.arange(n_samps) > 1.5 * fs) & (np.arange(n_samps) < 2 * fs)) for ii in range(len(cos_f)): x = x + cos_a[ii] * np.cos(2 * np.pi * cos_f[ii] * t) for jj in range(len(noise)): x = x + np.random.randn(n_samps) * noise[jj] x[x >= 1] = 1 x[x <= -1] = -1 xf = scipy.signal.sosfiltfilt(SOS, x) fig = plt.figure(figsize=(10, 8)) ax1 = plt.subplot2grid((2, 2), (0, 0), colspan=2) ax2 = plt.subplot2grid((2, 2), (1, 0)) ax3 = plt.subplot2grid((2, 2), (1, 1)) fig.tight_layout(pad=1.5) w, h = scipy.signal.sosfreqz(SOS, worN=np.concatenate((np.arange(0, 200, 1 / 2 ** 8), np.arange(200, 6000, 1 / 2 ** 8))), fs=fs) _ = plot_freq_response(w / fs * (2 * np.pi), h, fs, ax=ax2) ax1.plot(t, x, 'k-', label='x', alpha=0.5) ax1.plot(t, xf, alpha=0.75, linewidth=2, label='filtfilt') ax1.legend(loc='best', frameon=False) ax1.set_title('Test signal') ax1.set_xlabel(' time [s] ') pxx, freqs = get_chans_psd(x, fs, resamp=False) ax3.semilogx(freqs, 20 * np.log10(pxx)) pxx, freqs = get_chans_psd(xf, fs, resamp=False) ax3.semilogx(freqs, 20 * np.log10(pxx)) ax3.set_xlim([0.1, fs / 2]) ax3.set_ylim([-200, 20]) ax3.set_xlabel('Frequency Hz') def plot_freq_response(w, h, fs, ax=None): if ax is None: fig, ax = plt.subplots() else: fig = ax.get_figure() ax.set_title('Digital filter frequency response') ax.semilogx(w / np.pi * (fs / 2), 20 * np.log10(abs(h)), 'b') ax.set_ylabel('Amplitude [dB]', color='b') ax.set_xlabel('Frequency Hz') ax.set_ylim([-120, 20]) ax.set_xlim([0.1, fs / 2]) return fig, ax def plot_tt_psd(freqs, pxx, ax=None): if ax is None: fig, ax = plt.subplots(figsize=(5, 4)) ls = ['-', '--', ':', '-.'] n_chans = pxx.shape[0] for ch in range(n_chans): ax.semilogx(freqs, 20 * np.log10(pxx[ch]), alpha=0.75, linestyle=ls[ch], linewidth=3) ax.legend(['Ch{}'.format(ch) for ch in range(n_chans)], frameon=False) ax.set_xticks([1, 10, 100, 1000, 10000]) ax.set_xticklabels([1, 10, 100, 1000, 10000]) ax.set_xlabel('Frequency [Hz]') ax.set_ylabel(r"PSD $\frac{V^2}{Hz}$") ax.set_ylim(-100, ax.get_ylim()[1]) ax.set_title('Power Spectrum Density') return ax def plot_tt_psd_table(freqs, pxx, df, ax=None): if ax is None: f, ax = plt.subplots(2, 1, figsize=(5, 5)) ax[0] = plot_tt_psd(freqs, pxx, ax=ax[0]) ax[1].axis('off') prop_cycle = plt.rcParams['axes.prop_cycle'] cl = prop_cycle.by_key()['color'] t = pd.plotting.table(ax[1], df.round(2), loc='center', rowColours=cl) t.auto_set_font_size(False) t.set_fontsize(14) return ax def plot_amp_hist(hist, bins, ax=None, **kwags): if ax is None: fig, ax = plt.subplots() ax = ax.flatten() else: ax.bar(bins, np.log10(hist), width=(bins[1] - bins[0]), **kwags) ax.set_xlabel(r'Amplitude $\mu V$') ax.set_ylabel(r'$log_{10}(nSamps)$') return ax def plot_tt_amps_hists(hists, bin_centers, tt_info, ax=None): n_chans = tt_info['n_chans'] xlim = np.max(tt_info['input_range']) * 1.1 fs = tt_info['fs'] ax_flag = 0 if ax is None: fig, ax = plt.subplots(2, 2, figsize=(10, 8)) ax = ax.flatten() elif len(ax) != n_chans: print('Warning. # of signals mismatch # of given axes to plot historgrams, creating new figure.') fig, ax = plt.subplots((2, 2), figsize=(10, 8)) ax = ax.flatten() else: ax_flag = 1 prop_cycle = plt.rcParams['axes.prop_cycle'] cl = prop_cycle.by_key()['color'] for ch in range(n_chans): ax[ch] = plot_amp_hist(hists[ch], bin_centers, ax=ax[ch], color=cl[ch]) ax[ch].set_title('Channel {}'.format(ch)) if ax_flag == 0: if ch < 2: ax[ch].set_xlabel('') ax[ch].set_xlim(-xlim, xlim) ax[ch].axhline(np.log10(fs), color='k', linestyle='--', alpha=0.75) return ax def plot_tt_summary(tt_info, sig_type='Raw'): fig, ax = plt.subplots(2, 3, figsize=(16, 8)) ax = ax.flatten() _ = plot_tt_amps_hists(tt_info[sig_type]['AmpHist'], tt_info[sig_type]['HistBins'], tt_info, ax[[0, 1, 3, 4]]) ax[0].set_xlabel('') ax[1].set_xlabel('') for ch, ax_ii in enumerate([0, 1, 3, 4]): clp = tt_info['Raw']['PctChanClipped'][ch] * 100 if clp > 25: ax[ax_ii].text(x=0.65, y=0.75, s='Clipped %{0:0.1f}'.format(clp), color='r', transform=ax[ax_ii].transAxes) else: ax[ax_ii].text(x=0.65, y=0.75, s='Clipped %{0:0.1f}'.format(clp), transform=ax[ax_ii].transAxes) _ = plot_tt_psd_table(tt_info[sig_type]['PSD_freqs'], tt_info[sig_type]['PSD'], tt_info[sig_type]['PSD_table'], ax[[2, 5]]) fig.tight_layout(pad=1.0) ax[5].set_position([0.66, 0.05, 0.33, 0.5]) return fig, ax
[ "pickle.dump", "numpy.sum", "scipy.signal.welch", "numpy.abs", "numpy.argmax", "numpy.empty", "matplotlib.pyplot.subplot2grid", "numpy.floor", "numpy.ones", "numpy.around", "pathlib.Path", "matplotlib.pyplot.figure", "numpy.arange", "numpy.histogram", "sys.exc_info", "numpy.mean", "pickle.load", "pandas.DataFrame", "scipy.signal.tf2sos", "numpy.zeros_like", "traceback.print_exc", "numpy.random.randn", "nept.load_neuralynx_header", "scipy.signal.iirnotch", "nept.load_lfp", "Utils.robust_stats.mad", "numpy.max", "numpy.log10", "matplotlib.pyplot.subplots", "seaborn.set", "scipy.signal.sosfilt_zi", "nept.load_events", "numpy.cos", "numpy.argwhere", "numpy.vstack", "numpy.all", "numpy.concatenate", "numpy.logical_and", "numpy.fromfile", "scipy.signal.sosfiltfilt", "numpy.dtype", "numpy.zeros", "time.time", "scipy.signal.iirdesign", "numpy.array", "numpy.diff", "fooof.FOOOF" ]
[((391, 434), 'seaborn.set', 'sns.set', ([], {'style': '"""whitegrid"""', 'palette': '"""muted"""'}), "(style='whitegrid', palette='muted')\n", (398, 434), True, 'import seaborn as sns\n'), ((1238, 1254), 'pathlib.Path', 'Path', (["task['sp']"], {}), "(task['sp'])\n", (1242, 1254), False, 'from pathlib import Path\n'), ((3384, 3400), 'pathlib.Path', 'Path', (["task['sp']"], {}), "(task['sp'])\n", (3388, 3400), False, 'from pathlib import Path\n'), ((4793, 4807), 'pandas.DataFrame', 'pd.DataFrame', ([], {}), '()\n', (4805, 4807), True, 'import pandas as pd\n'), ((7908, 7925), 'numpy.zeros', 'np.zeros', (['n_chans'], {}), '(n_chans)\n', (7916, 7925), True, 'import numpy as np\n'), ((7941, 7958), 'numpy.zeros', 'np.zeros', (['n_chans'], {}), '(n_chans)\n', (7949, 7958), True, 'import numpy as np\n'), ((7974, 7991), 'numpy.zeros', 'np.zeros', (['n_chans'], {}), '(n_chans)\n', (7982, 7991), True, 'import numpy as np\n'), ((8010, 8027), 'numpy.zeros', 'np.zeros', (['n_chans'], {}), '(n_chans)\n', (8018, 8027), True, 'import numpy as np\n'), ((8546, 8562), 'numpy.zeros', 'np.zeros', (['[4, 2]'], {}), '([4, 2])\n', (8554, 8562), True, 'import numpy as np\n'), ((9429, 9471), 'numpy.arange', 'np.arange', (['(-max_amp)', '(max_amp + 1)', 'bin_step'], {}), '(-max_amp, max_amp + 1, bin_step)\n', (9438, 9471), True, 'import numpy as np\n'), ((10226, 10296), 'scipy.signal.welch', 'scipy.signal.welch', (['signals'], {'fs': 'fs', 'nperseg': 'nperseg', 'noverlap': 'noverlap'}), '(signals, fs=fs, nperseg=nperseg, noverlap=noverlap)\n', (10244, 10296), False, 'import scipy\n'), ((10913, 10991), 'pandas.DataFrame', 'pd.DataFrame', ([], {'columns': "['th_pk', 'th_amp', '60_pk', '60_amp', '1/f_r2', 'rmse']"}), "(columns=['th_pk', 'th_amp', '60_pk', '60_amp', '1/f_r2', 'rmse'])\n", (10925, 10991), True, 'import pandas as pd\n'), ((17380, 17419), 'numpy.ones', 'np.ones', (['(n_chans, n_samps)'], {'dtype': 'bool'}), '((n_chans, n_samps), dtype=bool)\n', (17387, 17419), True, 'import numpy as np\n'), ((18486, 18502), 'numpy.zeros', 'np.zeros', (['(0, 6)'], {}), '((0, 6))\n', (18494, 18502), True, 'import numpy as np\n'), ((20922, 20950), 'scipy.signal.sosfilt_zi', 'scipy.signal.sosfilt_zi', (['SOS'], {}), '(SOS)\n', (20945, 20950), False, 'import scipy\n'), ((21087, 21098), 'time.time', 'time.time', ([], {}), '()\n', (21096, 21098), False, 'import time\n'), ((21280, 21291), 'time.time', 'time.time', ([], {}), '()\n', (21289, 21291), False, 'import time\n'), ((21591, 21602), 'time.time', 'time.time', ([], {}), '()\n', (21600, 21602), False, 'import time\n'), ((22207, 22224), 'numpy.zeros', 'np.zeros', (['n_chans'], {}), '(n_chans)\n', (22215, 22224), True, 'import numpy as np\n'), ((23438, 23455), 'nept.load_lfp', 'nept.load_lfp', (['fn'], {}), '(fn)\n', (23451, 23455), False, 'import nept\n'), ((23546, 23576), 'nept.load_neuralynx_header', 'nept.load_neuralynx_header', (['fn'], {}), '(fn)\n', (23572, 23576), False, 'import nept\n'), ((25484, 25655), 'numpy.dtype', 'np.dtype', (["[('filler1', '<h', 3), ('time', '<Q'), ('points', '<i', 400), ('filler2',\n '<h'), ('x', '<i'), ('y', '<i'), ('head_angle', '<i'), ('targets', '<i',\n 50)]"], {}), "([('filler1', '<h', 3), ('time', '<Q'), ('points', '<i', 400), (\n 'filler2', '<h'), ('x', '<i'), ('y', '<i'), ('head_angle', '<i'), (\n 'targets', '<i', 50)])\n", (25492, 25655), True, 'import numpy as np\n'), ((25695, 25713), 'numpy.fromfile', 'np.fromfile', (['f', 'dt'], {}), '(f, dt)\n', (25706, 25713), True, 'import numpy as np\n'), ((25751, 25783), 'numpy.array', 'np.array', (["data['x']"], {'dtype': 'float'}), "(data['x'], dtype=float)\n", (25759, 25783), True, 'import numpy as np\n'), ((25792, 25824), 'numpy.array', 'np.array', (["data['y']"], {'dtype': 'float'}), "(data['y'], dtype=float)\n", (25800, 25824), True, 'import numpy as np\n'), ((25834, 25875), 'numpy.array', 'np.array', (["data['head_angle']"], {'dtype': 'float'}), "(data['head_angle'], dtype=float)\n", (25842, 25875), True, 'import numpy as np\n'), ((26226, 26254), 'nept.load_events', 'nept.load_events', (['fn', 'events'], {}), '(fn, events)\n', (26242, 26254), False, 'import nept\n'), ((27485, 27517), 'scipy.signal.sosfiltfilt', 'scipy.signal.sosfiltfilt', (['SOS', 'x'], {}), '(SOS, x)\n', (27509, 27517), False, 'import scipy\n'), ((27529, 27556), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(10, 8)'}), '(figsize=(10, 8))\n', (27539, 27556), True, 'import matplotlib.pyplot as plt\n'), ((27567, 27610), 'matplotlib.pyplot.subplot2grid', 'plt.subplot2grid', (['(2, 2)', '(0, 0)'], {'colspan': '(2)'}), '((2, 2), (0, 0), colspan=2)\n', (27583, 27610), True, 'import matplotlib.pyplot as plt\n'), ((27621, 27653), 'matplotlib.pyplot.subplot2grid', 'plt.subplot2grid', (['(2, 2)', '(1, 0)'], {}), '((2, 2), (1, 0))\n', (27637, 27653), True, 'import matplotlib.pyplot as plt\n'), ((27664, 27696), 'matplotlib.pyplot.subplot2grid', 'plt.subplot2grid', (['(2, 2)', '(1, 1)'], {}), '((2, 2), (1, 1))\n', (27680, 27696), True, 'import matplotlib.pyplot as plt\n'), ((31339, 31374), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(2)', '(3)'], {'figsize': '(16, 8)'}), '(2, 3, figsize=(16, 8))\n', (31351, 31374), True, 'import matplotlib.pyplot as plt\n'), ((1940, 1968), 'numpy.empty', 'np.empty', (['(n_chans, n_samps)'], {}), '((n_chans, n_samps))\n', (1948, 1968), True, 'import numpy as np\n'), ((2590, 2634), 'numpy.logical_and', 'np.logical_and', (['(chan_code > 0)', '(chan_code < 4)'], {}), '(chan_code > 0, chan_code < 4)\n', (2604, 2634), True, 'import numpy as np\n'), ((2723, 2749), 'numpy.zeros_like', 'np.zeros_like', (['raw_signals'], {}), '(raw_signals)\n', (2736, 2749), True, 'import numpy as np\n'), ((2763, 2774), 'time.time', 'time.time', ([], {}), '()\n', (2772, 2774), False, 'import time\n'), ((2928, 2939), 'time.time', 'time.time', ([], {}), '()\n', (2937, 2939), False, 'import time\n'), ((3924, 3940), 'pathlib.Path', 'Path', (["task['sp']"], {}), "(task['sp'])\n", (3928, 3940), False, 'from pathlib import Path\n'), ((6013, 6034), 'pathlib.Path', 'Path', (['subsession_path'], {}), '(subsession_path)\n', (6017, 6034), False, 'from pathlib import Path\n'), ((8286, 8295), 'pathlib.Path', 'Path', (['chf'], {}), '(chf)\n', (8290, 8295), False, 'from pathlib import Path\n'), ((9626, 9657), 'numpy.histogram', 'np.histogram', (['signals[ch]', 'bins'], {}), '(signals[ch], bins)\n', (9638, 9657), True, 'import numpy as np\n'), ((9945, 9969), 'numpy.argmax', 'np.argmax', (['signals.shape'], {}), '(signals.shape)\n', (9954, 9969), True, 'import numpy as np\n'), ((10359, 10373), 'numpy.arange', 'np.arange', (['(100)'], {}), '(100)\n', (10368, 10373), True, 'import numpy as np\n'), ((10411, 10431), 'numpy.arange', 'np.arange', (['(2)', 'maxExp'], {}), '(2, maxExp)\n', (10420, 10431), True, 'import numpy as np\n'), ((11035, 11124), 'fooof.FOOOF', 'FOOOF', ([], {'max_n_peaks': '(2)', 'peak_threshold': '(2.0)', 'peak_width_limits': '[0.5, 6.0]', 'verbose': '(False)'}), '(max_n_peaks=2, peak_threshold=2.0, peak_width_limits=[0.5, 6.0],\n verbose=False)\n', (11040, 11124), False, 'from fooof import FOOOF\n'), ((12234, 12266), 'numpy.around', 'np.around', (['fm.error_'], {'decimals': '(3)'}), '(fm.error_, decimals=3)\n', (12243, 12266), True, 'import numpy as np\n'), ((12297, 12333), 'numpy.around', 'np.around', (['fm.r_squared_'], {'decimals': '(3)'}), '(fm.r_squared_, decimals=3)\n', (12306, 12333), True, 'import numpy as np\n'), ((13289, 13314), 'numpy.floor', 'np.floor', (['(fs * sec_buffer)'], {}), '(fs * sec_buffer)\n', (13297, 13314), True, 'import numpy as np\n'), ((13456, 13479), 'numpy.array', 'np.array', (['[]'], {'dtype': 'int'}), '([], dtype=int)\n', (13464, 13479), True, 'import numpy as np\n'), ((13495, 13518), 'numpy.array', 'np.array', (['[]'], {'dtype': 'int'}), '([], dtype=int)\n', (13503, 13518), True, 'import numpy as np\n'), ((27123, 27141), 'numpy.arange', 'np.arange', (['n_samps'], {}), '(n_samps)\n', (27132, 27141), True, 'import numpy as np\n'), ((28582, 28596), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (28594, 28596), True, 'import matplotlib.pyplot as plt\n'), ((28995, 29023), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {'figsize': '(5, 4)'}), '(figsize=(5, 4))\n', (29007, 29023), True, 'import matplotlib.pyplot as plt\n'), ((29640, 29674), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(2)', '(1)'], {'figsize': '(5, 5)'}), '(2, 1, figsize=(5, 5))\n', (29652, 29674), True, 'import matplotlib.pyplot as plt\n'), ((30065, 30079), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (30077, 30079), True, 'import matplotlib.pyplot as plt\n'), ((30394, 30424), 'numpy.max', 'np.max', (["tt_info['input_range']"], {}), "(tt_info['input_range'])\n", (30400, 30424), True, 'import numpy as np\n'), ((30507, 30542), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(2)', '(2)'], {'figsize': '(10, 8)'}), '(2, 2, figsize=(10, 8))\n', (30519, 30542), True, 'import matplotlib.pyplot as plt\n'), ((2837, 2883), 'scipy.signal.sosfiltfilt', 'scipy.signal.sosfiltfilt', (['SOS', 'raw_signals[ch]'], {}), '(SOS, raw_signals[ch])\n', (2861, 2883), False, 'import scipy\n'), ((3229, 3293), 'pickle.dump', 'pickle.dump', (['tt_info', 'f_handle'], {'protocol': 'pickle.HIGHEST_PROTOCOL'}), '(tt_info, f_handle, protocol=pickle.HIGHEST_PROTOCOL)\n', (3240, 3293), False, 'import pickle\n'), ((4624, 4659), 'pathlib.Path', 'Path', (["task_table[k]['session_name']"], {}), "(task_table[k]['session_name'])\n", (4628, 4659), False, 'from pathlib import Path\n'), ((11566, 11600), 'numpy.around', 'np.around', (['theta_pk[0]'], {'decimals': '(2)'}), '(theta_pk[0], decimals=2)\n', (11575, 11600), True, 'import numpy as np\n'), ((11635, 11670), 'numpy.around', 'np.around', (['theta_amp[0]'], {'decimals': '(2)'}), '(theta_amp[0], decimals=2)\n', (11644, 11670), True, 'import numpy as np\n'), ((11918, 11952), 'numpy.around', 'np.around', (['sixty_pk[0]'], {'decimals': '(2)'}), '(sixty_pk[0], decimals=2)\n', (11927, 11952), True, 'import numpy as np\n'), ((11987, 12022), 'numpy.around', 'np.around', (['sixty_amp[0]'], {'decimals': '(2)'}), '(sixty_amp[0], decimals=2)\n', (11996, 12022), True, 'import numpy as np\n'), ((13329, 13352), 'numpy.array', 'np.array', (['[]'], {'dtype': 'int'}), '([], dtype=int)\n', (13337, 13352), True, 'import numpy as np\n'), ((13376, 13399), 'numpy.array', 'np.array', (['[]'], {'dtype': 'int'}), '([], dtype=int)\n', (13384, 13399), True, 'import numpy as np\n'), ((19305, 19403), 'scipy.signal.iirdesign', 'scipy.signal.iirdesign', (['(cut_freq / (fs / 2))', '(cut_buffer / (fs / 2))', 'gpass', 'gstop'], {'output': '"""sos"""'}), "(cut_freq / (fs / 2), cut_buffer / (fs / 2), gpass,\n gstop, output='sos')\n", (19327, 19403), False, 'import scipy\n'), ((19418, 19439), 'numpy.vstack', 'np.vstack', (['(SOS, sos)'], {}), '((SOS, sos))\n', (19427, 19439), True, 'import numpy as np\n'), ((20777, 20875), 'scipy.signal.iirdesign', 'scipy.signal.iirdesign', (['(cut_freq / (fs / 2))', '(cut_buffer / (fs / 2))', 'gpass', 'gstop'], {'output': '"""sos"""'}), "(cut_freq / (fs / 2), cut_buffer / (fs / 2), gpass,\n gstop, output='sos')\n", (20799, 20875), False, 'import scipy\n'), ((20890, 20911), 'numpy.vstack', 'np.vstack', (['(SOS, sos)'], {}), '((SOS, sos))\n', (20899, 20911), True, 'import numpy as np\n'), ((22053, 22068), 'Utils.robust_stats.mad', 'rs.mad', (['signals'], {}), '(signals)\n', (22059, 22068), True, 'import Utils.robust_stats as rs\n'), ((22102, 22123), 'Utils.robust_stats.mad', 'rs.mad', (['signals[mask]'], {}), '(signals[mask])\n', (22108, 22123), True, 'import Utils.robust_stats as rs\n'), ((22306, 22325), 'Utils.robust_stats.mad', 'rs.mad', (['signals[ch]'], {}), '(signals[ch])\n', (22312, 22325), True, 'import Utils.robust_stats as rs\n'), ((27157, 27175), 'numpy.arange', 'np.arange', (['n_samps'], {}), '(n_samps)\n', (27166, 27175), True, 'import numpy as np\n'), ((28292, 28305), 'numpy.log10', 'np.log10', (['pxx'], {}), '(pxx)\n', (28300, 28305), True, 'import numpy as np\n'), ((28389, 28402), 'numpy.log10', 'np.log10', (['pxx'], {}), '(pxx)\n', (28397, 28402), True, 'import numpy as np\n'), ((30137, 30151), 'numpy.log10', 'np.log10', (['hist'], {}), '(hist)\n', (30145, 30151), True, 'import numpy as np\n'), ((30722, 30759), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(2, 2)'], {'figsize': '(10, 8)'}), '((2, 2), figsize=(10, 8))\n', (30734, 30759), True, 'import matplotlib.pyplot as plt\n'), ((31210, 31222), 'numpy.log10', 'np.log10', (['fs'], {}), '(fs)\n', (31218, 31222), True, 'import numpy as np\n'), ((16888, 16924), 'numpy.array', 'np.array', (['[(j - i) for i, j in segs]'], {}), '([(j - i) for i, j in segs])\n', (16896, 16924), True, 'import numpy as np\n'), ((16948, 16962), 'numpy.array', 'np.array', (['segs'], {}), '(segs)\n', (16956, 16962), True, 'import numpy as np\n'), ((17164, 17200), 'traceback.print_exc', 'traceback.print_exc', ([], {'file': 'sys.stdout'}), '(file=sys.stdout)\n', (17183, 17200), False, 'import traceback\n'), ((19748, 19766), 'numpy.array', 'np.array', (['cut_freq'], {}), '(cut_freq)\n', (19756, 19766), True, 'import numpy as np\n'), ((20376, 20417), 'scipy.signal.iirnotch', 'scipy.signal.iirnotch', (['notch', 'q[i]'], {'fs': 'fs'}), '(notch, q[i], fs=fs)\n', (20397, 20417), False, 'import scipy\n'), ((20440, 20465), 'scipy.signal.tf2sos', 'scipy.signal.tf2sos', (['b', 'a'], {}), '(b, a)\n', (20459, 20465), False, 'import scipy\n'), ((20488, 20509), 'numpy.vstack', 'np.vstack', (['(SOS, sos)'], {}), '((SOS, sos))\n', (20497, 20509), True, 'import numpy as np\n'), ((22421, 22450), 'Utils.robust_stats.mad', 'rs.mad', (['signals[ch, mask[ch]]'], {}), '(signals[ch, mask[ch]])\n', (22427, 22450), True, 'import Utils.robust_stats as rs\n'), ((27190, 27208), 'numpy.arange', 'np.arange', (['n_samps'], {}), '(n_samps)\n', (27199, 27208), True, 'import numpy as np\n'), ((27224, 27242), 'numpy.arange', 'np.arange', (['n_samps'], {}), '(n_samps)\n', (27233, 27242), True, 'import numpy as np\n'), ((27315, 27348), 'numpy.cos', 'np.cos', (['(2 * np.pi * cos_f[ii] * t)'], {}), '(2 * np.pi * cos_f[ii] * t)\n', (27321, 27348), True, 'import numpy as np\n'), ((27399, 27423), 'numpy.random.randn', 'np.random.randn', (['n_samps'], {}), '(n_samps)\n', (27414, 27423), True, 'import numpy as np\n'), ((29146, 29163), 'numpy.log10', 'np.log10', (['pxx[ch]'], {}), '(pxx[ch])\n', (29154, 29163), True, 'import numpy as np\n'), ((4370, 4384), 'sys.exc_info', 'sys.exc_info', ([], {}), '()\n', (4382, 4384), False, 'import sys\n'), ((4389, 4403), 'sys.exc_info', 'sys.exc_info', ([], {}), '()\n', (4401, 4403), False, 'import sys\n'), ((5478, 5499), 'pathlib.Path', 'Path', (['subsession_path'], {}), '(subsession_path)\n', (5482, 5499), False, 'from pathlib import Path\n'), ((10476, 10524), 'numpy.arange', 'np.arange', (['(10 ** e)', '(10 ** (e + 1))', '(10 ** (e - 1))'], {}), '(10 ** e, 10 ** (e + 1), 10 ** (e - 1))\n', (10485, 10524), True, 'import numpy as np\n'), ((11746, 11763), 'numpy.mean', 'np.mean', (['theta_pk'], {}), '(theta_pk)\n', (11753, 11763), True, 'import numpy as np\n'), ((11821, 11839), 'numpy.mean', 'np.mean', (['theta_amp'], {}), '(theta_amp)\n', (11828, 11839), True, 'import numpy as np\n'), ((12098, 12115), 'numpy.mean', 'np.mean', (['sixty_pk'], {}), '(sixty_pk)\n', (12105, 12115), True, 'import numpy as np\n'), ((12173, 12191), 'numpy.mean', 'np.mean', (['sixty_amp'], {}), '(sixty_amp)\n', (12180, 12191), True, 'import numpy as np\n'), ((13672, 13692), 'numpy.diff', 'np.diff', (['signal_mask'], {}), '(signal_mask)\n', (13679, 13692), True, 'import numpy as np\n'), ((13719, 13744), 'numpy.argwhere', 'np.argwhere', (['(diff_sig > 0)'], {}), '(diff_sig > 0)\n', (13730, 13744), True, 'import numpy as np\n'), ((13777, 13802), 'numpy.argwhere', 'np.argwhere', (['(diff_sig < 0)'], {}), '(diff_sig < 0)\n', (13788, 13802), True, 'import numpy as np\n'), ((13993, 14020), 'numpy.all', 'np.all', (['(idx_end > idx_start)'], {}), '(idx_end > idx_start)\n', (13999, 14020), True, 'import numpy as np\n'), ((19574, 19601), 'numpy.arange', 'np.arange', (['(1)', '(n_notches + 1)'], {}), '(1, n_notches + 1)\n', (19583, 19601), True, 'import numpy as np\n'), ((19654, 19681), 'numpy.arange', 'np.arange', (['(1)', '(n_notches + 1)'], {}), '(1, n_notches + 1)\n', (19663, 19681), True, 'import numpy as np\n'), ((21251, 21262), 'time.time', 'time.time', ([], {}), '()\n', (21260, 21262), False, 'import time\n'), ((21562, 21573), 'time.time', 'time.time', ([], {}), '()\n', (21571, 21573), False, 'import time\n'), ((21798, 21807), 'numpy.sum', 'np.sum', (['d'], {}), '(d)\n', (21804, 21807), True, 'import numpy as np\n'), ((21905, 21916), 'time.time', 'time.time', ([], {}), '()\n', (21914, 21916), False, 'import time\n'), ((22561, 22586), 'Utils.robust_stats.mad', 'rs.mad', (['signals[ch]', 'mask'], {}), '(signals[ch], mask)\n', (22567, 22586), True, 'import Utils.robust_stats as rs\n'), ((22714, 22733), 'Utils.robust_stats.mad', 'rs.mad', (['signals[ch]'], {}), '(signals[ch])\n', (22720, 22733), True, 'import Utils.robust_stats as rs\n'), ((27820, 27849), 'numpy.arange', 'np.arange', (['(0)', '(200)', '(1 / 2 ** 8)'], {}), '(0, 200, 1 / 2 ** 8)\n', (27829, 27849), True, 'import numpy as np\n'), ((27851, 27883), 'numpy.arange', 'np.arange', (['(200)', '(6000)', '(1 / 2 ** 8)'], {}), '(200, 6000, 1 / 2 ** 8)\n', (27860, 27883), True, 'import numpy as np\n'), ((4408, 4422), 'sys.exc_info', 'sys.exc_info', ([], {}), '()\n', (4420, 4422), False, 'import sys\n'), ((13559, 13578), 'numpy.abs', 'np.abs', (['signals[ch]'], {}), '(signals[ch])\n', (13565, 13578), True, 'import numpy as np\n'), ((14411, 14443), 'numpy.all', 'np.all', (['(idx_end > idx_start[:-1])'], {}), '(idx_end > idx_start[:-1])\n', (14417, 14443), True, 'import numpy as np\n'), ((17085, 17099), 'sys.exc_info', 'sys.exc_info', ([], {}), '()\n', (17097, 17099), False, 'import sys\n'), ((17104, 17118), 'sys.exc_info', 'sys.exc_info', ([], {}), '()\n', (17116, 17118), False, 'import sys\n'), ((19945, 19962), 'numpy.array', 'np.array', (['notch_q'], {}), '(notch_q)\n', (19953, 19962), True, 'import numpy as np\n'), ((20265, 20292), 'numpy.arange', 'np.arange', (['(1)', '(n_notches + 1)'], {}), '(1, n_notches + 1)\n', (20274, 20292), True, 'import numpy as np\n'), ((5835, 5849), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (5846, 5849), False, 'import pickle\n'), ((14841, 14872), 'numpy.all', 'np.all', (['(idx_end[1:] > idx_start)'], {}), '(idx_end[1:] > idx_start)\n', (14847, 14872), True, 'import numpy as np\n'), ((17123, 17137), 'sys.exc_info', 'sys.exc_info', ([], {}), '()\n', (17135, 17137), False, 'import sys\n'), ((14910, 14942), 'numpy.concatenate', 'np.concatenate', (['([0], idx_start)'], {}), '(([0], idx_start))\n', (14924, 14942), True, 'import numpy as np\n'), ((20147, 20165), 'numpy.ones', 'np.ones', (['n_notches'], {}), '(n_notches)\n', (20154, 20165), True, 'import numpy as np\n'), ((14504, 14523), 'numpy.array', 'np.array', (['[n_samps]'], {}), '([n_samps])\n', (14512, 14523), True, 'import numpy as np\n')]
""" Wisconsin Autonomous - https://www.wisconsinautonomous.org Copyright (c) 2021 wisconsinautonomous.org All rights reserved. Use of this source code is governed by a BSD-style license that can be found in the LICENSE file at the top level of the repo """ from abc import abstractmethod # Abstract Base Class # WA Simulator from wa_simulator.core import WA_GRAVITY, WAVector, WAQuaternion from wa_simulator.base import WABase from wa_simulator.utils import _load_json, _WAStaticAttribute, get_wa_data_file # Other imports import numpy as np def load_properties_from_json(filename: str, prop: str) -> dict: """Load a specified property from a json specification file Will load a json file and extract the passed property field for use by the underyling vehicle object Args: filename (str): the filename location within the set WA data folder for the json file property (str): the property to get. Ex: "Vehicle Properties" Raises: ValueError: The property field isn't found Returns: dict: the property field extracted from the json file """ j = _load_json(filename) if prop not in j: raise ValueError(f"{prop} not found in json.") return j[prop] class WAVehicle(WABase): """Base class for a WAVehicle. To implement a new vehicle model, override this class. A WAVehicle should interact with the terrain/assets/world and take three inputs: steering, throttle, braking. Args: system (WASystem): the system used to run the simulation vehicle_inputs (WAVehicleInputs): The vehicle inputs filename (str, optional): Filename to be used for visualization properties """ def __init__(self, system: 'WASystem', vehicle_inputs: 'WAVehicleInputs', filename=None): self._system = system self._vehicle_inputs = vehicle_inputs self._vis_properties = ( dict() if filename is None else load_properties_from_json(filename, "Visualization Properties") ) def get_visual_properties(self) -> dict: """Get visual properties for visualizing the vehicle .. todo:: Define the visual properties required Returns: dict: the visual properties """ return self._vis_properties @abstractmethod def synchronize(self, time: float): pass @abstractmethod def advance(self, step: float): pass def is_ok(self) -> bool: return True @abstractmethod def get_pos(self) -> WAVector: """Get the center of mass (COM) position of the vehicle. Returns: WAVector: the position of the vehicle """ pass @abstractmethod def get_rot(self) -> WAQuaternion: """Get the rotation about the center of mass (COM) of the vehicle Returns: WAQuaternion: the vehicles orientation """ pass @abstractmethod def get_pos_dt(self) -> WAVector: """Get the instantaneous velocity of the vehicle Returns: WAVector: The velocity where X is forward, Z is up and Y is left (ISO standard) """ pass @abstractmethod def get_rot_dt(self) -> WAQuaternion: """Get the angular velocity of the vehicle Returns: WAQuaternion: The angular velocity """ pass @abstractmethod def get_pos_dtdt(self) -> WAVector: """Get the acceleration of the vehicle Returns: WAVector: The acceleration where X is forward, Z is up and Y is left (ISO standard) """ pass @abstractmethod def get_rot_dtdt(self) -> WAQuaternion: """Get the angular acceleration of the vehicle Returns: WAQuaternion: The angular acceleration """ pass class WALinearKinematicBicycle(WAVehicle): """A linear, kinematic bicycle model Args: system (WASystem): the system used to run the simulation vehicle_inputs (WAVehicleInputs): The vehicle inputs filename (str): json specification file used to describe the parameters for the vehicle init_pos (WAVector): initial position init_rot (WAQuaternion): initial rotation init_pos_dt (WAVector): initial velocity """ # Global filenames for vehicle models _GO_KART_MODEL_FILE = "vehicles/GoKart/GoKart_KinematicBicycle.json" GO_KART_MODEL_FILE = _WAStaticAttribute('_GO_KART_MODEL_FILE', get_wa_data_file) def __init__(self, system: 'WASystem', vehicle_inputs: 'WAVehicleInputs', filename: str, init_pos: WAVector = WAVector(), init_rot: WAQuaternion = WAQuaternion.from_z_rotation(0), init_pos_dt: WAVector = WAVector()): super().__init__(system, vehicle_inputs, filename) # Simple state variables self._x = init_pos.x self._y = init_pos.y self._yaw = init_rot.to_euler_yaw() self._v = init_pos_dt.length self._acc = 0.0 # Wheel angular velocity self._omega = 0.0 self._omega_dot = 0.0 self._yaw_dt = 0.0 self._yaw_dtdt = 0.0 self._last_yaw = 0.0 properties = load_properties_from_json(filename, "Vehicle Properties") self._initialize(properties) def _initialize(self, vp): """Initialize the vehicle parameters Expected properties: "Wheelbase" (float): distance between the front and back tire "Mass" (float): mass of the vehicle "Gear Ratio" (float): gear ratio of the simulated powertrain "Effective Radius" (float): "Inertia" (float): Effective inertia for the vehicle "Aerodynamic Coefficient" (float): "Friction Coefficient" (float): "C" (float) "Max Force" (float) "Torque Coefficients" (list) "Steering" ([min, max]): Min and max throttle values "Throttle" ([min, max]): Min and max throttle values "Braking" ([min, max]): Min and max braking values Args: vp (dict): Vehicle preoperties (see above for expected keys) """ # Initialize vehicle properties self._mass = vp["Mass"] # Torque coefficients self._a = vp["Torque Coefficients"] # Gear ratio, effective radius and inertia self._GR = vp["Gear Ratio"] self._r_eff = vp["Effective Radius"] self._J_e = vp["Inertia"] # Aerodynamic and friction coefficients self._c_a = vp["Aerodynamic Coefficient"] self._c_rl = vp["Friction Coefficient"] # Tire forces self._c = vp["C"] self._F_max = vp["Max Force"] self._L = vp["Wheelbase"] (self._min_steering, self._max_steering) = vp["Steering"] (self._min_throttle, self._max_throttle) = vp["Throttle"] (self._min_braking, self._max_braking) = vp["Braking"] def synchronize(self, time): s = self._vehicle_inputs.steering t = self._vehicle_inputs.throttle b = self._vehicle_inputs.braking self._steering = np.clip(s, self._min_steering, self._max_steering) self._throttle = np.clip(t, self._min_throttle, self._max_throttle) self._braking = np.clip(b, self._min_braking, self._max_braking) if self._braking > 1e-1: self._throttle = -self._braking def advance(self, step): # TODO: COMMENT! if self._v == 0 and self._throttle == 0: F_x = 0 F_load = 0 T_e = 0 else: if self._v == 0: # Remove possibity of divide by zero error self._v = 1e-8 self._omega = 1e-8 # Update engine and tire forces F_aero = self._c_a * self._v ** 2 R_x = self._c_rl * self._v F_g = self._mass * WA_GRAVITY * np.sin(0) F_load = F_aero + R_x + F_g T_e = self._throttle * ( self._a[0] + self._a[1] * self._omega + self._a[2] * self._omega ** 2 ) omega_w = self._GR * self._omega # Wheel angular velocity s = (omega_w * self._r_eff - self._v) / self._v # slip ratio cs = self._c * s if abs(s) < 1: F_x = cs else: F_x = self._F_max if self._throttle < 0: if self._v <= 0: F_x = 0 else: F_x = -abs(F_x) # Update state information self._x += self._v * np.cos(self._yaw) * step self._y += self._v * np.sin(self._yaw) * step self._yaw += self._v / self._L * np.tan(self._steering) * step self._v += self._acc * step self._acc = (F_x - F_load) / self._mass self._omega += self._omega_dot * step self._omega_dot = (T_e - self._GR * self._r_eff * F_load) / self._J_e v_epsilon = abs(self._v) > 0.1 self._yaw_dt = (self._last_yaw - self._yaw) / step if v_epsilon else 0 self._yaw_dtdt = (self._last_yaw - self._yaw) / step if v_epsilon else 0 # noqa self._last_yaw = self._yaw def get_pos(self) -> WAVector: return WAVector([self._x, self._y, 0.0]) def get_rot(self) -> WAQuaternion: return WAQuaternion.from_z_rotation(self._yaw) def get_pos_dt(self) -> WAVector: return WAVector([self._v * np.cos(self._yaw), self._v * np.sin(self._yaw), 0.0]) def get_rot_dt(self) -> WAQuaternion: return WAQuaternion.from_z_rotation(self._yaw_dt) def get_pos_dtdt(self) -> WAVector: angle = np.tan(np.interp(self._steering, [-1, 1], [self._min_steering, self._max_steering])) # noqa angle = angle if angle != 0 else 1e-3 tr = self._L / angle tr = tr if tr != 0 else 1e-3 return WAVector([self._acc, self._v ** 2 / tr, WA_GRAVITY]) def get_rot_dtdt(self) -> WAQuaternion: return WAQuaternion.from_z_rotation(self._yaw_dtdt)
[ "wa_simulator.utils._load_json", "wa_simulator.core.WAVector", "wa_simulator.utils._WAStaticAttribute", "wa_simulator.core.WAQuaternion.from_z_rotation", "numpy.clip", "numpy.sin", "numpy.tan", "numpy.cos", "numpy.interp" ]
[((1120, 1140), 'wa_simulator.utils._load_json', '_load_json', (['filename'], {}), '(filename)\n', (1130, 1140), False, 'from wa_simulator.utils import _load_json, _WAStaticAttribute, get_wa_data_file\n'), ((4498, 4557), 'wa_simulator.utils._WAStaticAttribute', '_WAStaticAttribute', (['"""_GO_KART_MODEL_FILE"""', 'get_wa_data_file'], {}), "('_GO_KART_MODEL_FILE', get_wa_data_file)\n", (4516, 4557), False, 'from wa_simulator.utils import _load_json, _WAStaticAttribute, get_wa_data_file\n'), ((4673, 4683), 'wa_simulator.core.WAVector', 'WAVector', ([], {}), '()\n', (4681, 4683), False, 'from wa_simulator.core import WA_GRAVITY, WAVector, WAQuaternion\n'), ((4710, 4741), 'wa_simulator.core.WAQuaternion.from_z_rotation', 'WAQuaternion.from_z_rotation', (['(0)'], {}), '(0)\n', (4738, 4741), False, 'from wa_simulator.core import WA_GRAVITY, WAVector, WAQuaternion\n'), ((4767, 4777), 'wa_simulator.core.WAVector', 'WAVector', ([], {}), '()\n', (4775, 4777), False, 'from wa_simulator.core import WA_GRAVITY, WAVector, WAQuaternion\n'), ((7182, 7232), 'numpy.clip', 'np.clip', (['s', 'self._min_steering', 'self._max_steering'], {}), '(s, self._min_steering, self._max_steering)\n', (7189, 7232), True, 'import numpy as np\n'), ((7258, 7308), 'numpy.clip', 'np.clip', (['t', 'self._min_throttle', 'self._max_throttle'], {}), '(t, self._min_throttle, self._max_throttle)\n', (7265, 7308), True, 'import numpy as np\n'), ((7333, 7381), 'numpy.clip', 'np.clip', (['b', 'self._min_braking', 'self._max_braking'], {}), '(b, self._min_braking, self._max_braking)\n', (7340, 7381), True, 'import numpy as np\n'), ((9303, 9336), 'wa_simulator.core.WAVector', 'WAVector', (['[self._x, self._y, 0.0]'], {}), '([self._x, self._y, 0.0])\n', (9311, 9336), False, 'from wa_simulator.core import WA_GRAVITY, WAVector, WAQuaternion\n'), ((9392, 9431), 'wa_simulator.core.WAQuaternion.from_z_rotation', 'WAQuaternion.from_z_rotation', (['self._yaw'], {}), '(self._yaw)\n', (9420, 9431), False, 'from wa_simulator.core import WA_GRAVITY, WAVector, WAQuaternion\n'), ((9618, 9660), 'wa_simulator.core.WAQuaternion.from_z_rotation', 'WAQuaternion.from_z_rotation', (['self._yaw_dt'], {}), '(self._yaw_dt)\n', (9646, 9660), False, 'from wa_simulator.core import WA_GRAVITY, WAVector, WAQuaternion\n'), ((9938, 9990), 'wa_simulator.core.WAVector', 'WAVector', (['[self._acc, self._v ** 2 / tr, WA_GRAVITY]'], {}), '([self._acc, self._v ** 2 / tr, WA_GRAVITY])\n', (9946, 9990), False, 'from wa_simulator.core import WA_GRAVITY, WAVector, WAQuaternion\n'), ((10051, 10095), 'wa_simulator.core.WAQuaternion.from_z_rotation', 'WAQuaternion.from_z_rotation', (['self._yaw_dtdt'], {}), '(self._yaw_dtdt)\n', (10079, 10095), False, 'from wa_simulator.core import WA_GRAVITY, WAVector, WAQuaternion\n'), ((9725, 9801), 'numpy.interp', 'np.interp', (['self._steering', '[-1, 1]', '[self._min_steering, self._max_steering]'], {}), '(self._steering, [-1, 1], [self._min_steering, self._max_steering])\n', (9734, 9801), True, 'import numpy as np\n'), ((7969, 7978), 'numpy.sin', 'np.sin', (['(0)'], {}), '(0)\n', (7975, 7978), True, 'import numpy as np\n'), ((8651, 8668), 'numpy.cos', 'np.cos', (['self._yaw'], {}), '(self._yaw)\n', (8657, 8668), True, 'import numpy as np\n'), ((8705, 8722), 'numpy.sin', 'np.sin', (['self._yaw'], {}), '(self._yaw)\n', (8711, 8722), True, 'import numpy as np\n'), ((8771, 8793), 'numpy.tan', 'np.tan', (['self._steering'], {}), '(self._steering)\n', (8777, 8793), True, 'import numpy as np\n'), ((9506, 9523), 'numpy.cos', 'np.cos', (['self._yaw'], {}), '(self._yaw)\n', (9512, 9523), True, 'import numpy as np\n'), ((9535, 9552), 'numpy.sin', 'np.sin', (['self._yaw'], {}), '(self._yaw)\n', (9541, 9552), True, 'import numpy as np\n')]
# Copyright 2021 The Petuum Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """This module tests for evaluation metrics.""" import unittest import torch import numpy as np from texar.torch.data.data.data_iterators import DataIterator from sklearn.metrics import roc_auc_score from config import transforms, pathologies from iu_xray_data import IU_XRay_Dataset from models.cv_model import MLCTrainer from evaluation_metrics import HammingLoss, MultiLabelConfusionMatrix, \ MultiLabelF1, MultiLabelPrecision, MultiLabelRecall, RocAuc def safe_divide(numerator: np.ndarray, denominator: np.ndarray) \ -> np.ndarray: # Credit: sklearn.metrics.classification._prf_divide if numerator.size == 1: if denominator == 0.0: return np.array(0.0) return numerator / denominator mask = denominator == 0.0 denominator = denominator.copy() denominator[mask] = 1.0 value = numerator / denominator return value class TestEvaluationMetrics(unittest.TestCase): r""" Unit test for Evaluation Metrics that are used for multi-label classification """ def setUp(self): self.batch_size = 2 self.num_label = len(pathologies) data_hparams = { "datasource":{ "img_root": "tests/test_iu_xray_data/iu_xray_images", "text_root": "tests/test_iu_xray_data/text_root", "vocab_path": "tests/test_iu_xray_data/test_vocab.txt", "transforms": transforms, "pathologies": pathologies, }, "batch_size": self.batch_size, "shuffle": False, } dataset = IU_XRay_Dataset(data_hparams) dataset.to(torch.device('cpu')) self.loader = DataIterator(dataset) mlc_hparam = { 'num_tags': len(pathologies), } self.mlc_trainer = MLCTrainer(mlc_hparam) def test_hamming_loss(self): r"""Test the HammingLoss implementations""" hm_loss = HammingLoss( num_label=self.num_label, pred_name='preds') simple_hm_loss = 0. num_sample = 0 correct = np.zeros(self.num_label) for batch in self.loader: result = self.mlc_trainer(batch) predicted = np.array(result['preds']) label = np.array(batch.label) batch_size = batch.batch_size num_sample += batch_size hm_loss.add(predicted, label) correct += np.sum(predicted == label, axis=0) simple_hm_loss = (num_sample - correct).mean() / num_sample self.assertEqual(simple_hm_loss, hm_loss.value()) def test_confusion_matrix_related(self): r"""Test the MultiLabelConfusionMatrix, MultiLabelPrecision MultiLabelRecall, and MultiLabelF1 implementation""" cf_matrix = MultiLabelConfusionMatrix( num_label=self.num_label, pred_name='preds') precision = MultiLabelPrecision( num_label=self.num_label, pred_name="preds") recall = MultiLabelRecall( num_label=self.num_label, pred_name="preds") f1 = MultiLabelF1( num_label=self.num_label, pred_name="preds") simple_cf_matrix = np.zeros([self.num_label, 2, 2]) for batch in self.loader: result = self.mlc_trainer(batch) predicted = np.array(result['preds']) label = np.array(batch.label) batch_size = batch.batch_size true_and_pred = predicted * label tp_sum = np.sum(true_and_pred, axis=0) pred_sum = np.sum(predicted, axis=0) true_sum = np.sum(label, axis=0) fp = pred_sum - tp_sum fn = true_sum - tp_sum tp = tp_sum tn = batch_size - tp - fp - fn simple_cf_matrix += np.array([tn, fp, fn, tp]).T.reshape(-1, 2, 2) cf_matrix.add(predicted, label) precision.add(predicted, label) recall.add(predicted, label) f1.add(predicted, label) tp = simple_cf_matrix[:, 1, 1] tp_fp = simple_cf_matrix[:, 1, 1] + simple_cf_matrix[:, 0, 1] tp_fn = simple_cf_matrix[:, 1, 1] + simple_cf_matrix[:, 1, 0] simple_cf_matrix = np.mean(simple_cf_matrix, axis=0) simple_precision = safe_divide(tp, tp_fp).mean() simple_recall = safe_divide(tp, tp_fn).mean() simple_f1 = safe_divide( 2 * simple_precision * simple_recall, simple_precision + simple_recall ) self.assertTrue(np.array_equal( simple_cf_matrix, cf_matrix.value() )) self.assertEqual(simple_precision, precision.value()) self.assertEqual(simple_recall, recall.value()) self.assertEqual(simple_f1, f1.value()) def test_roc_auc(self): r"""Test the RocAuc implementation NOTE: To test the ROC AUC, we have to modify the label to make sure there is at list one sample for one label is active/negative. The goal here is to make sure the calculation is correct, i.e., the results from our implementation should match some straight forward calculation. """ roc_auc = RocAuc(pred_name='preds') predicted_list = [] label_list = [] for batch in self.loader: result = self.mlc_trainer(batch) predicted = np.array(result['preds']) label = np.array(batch.label) label[0] = np.ones_like(label[0]) - label[1] label = label.astype(np.int) roc_auc.add(predicted, label) predicted_list.append(predicted) label_list.append(label) label = np.concatenate(label_list, axis=0) predicted = np.concatenate(predicted_list, axis=0) simple_roc_auc = roc_auc_score(label, predicted) self.assertEqual(simple_roc_auc, roc_auc.value()) if __name__ == "__main__": unittest.main()
[ "unittest.main", "texar.torch.data.data.data_iterators.DataIterator", "iu_xray_data.IU_XRay_Dataset", "numpy.sum", "numpy.ones_like", "evaluation_metrics.HammingLoss", "evaluation_metrics.MultiLabelF1", "numpy.zeros", "models.cv_model.MLCTrainer", "sklearn.metrics.roc_auc_score", "evaluation_metrics.MultiLabelConfusionMatrix", "numpy.mean", "evaluation_metrics.MultiLabelRecall", "evaluation_metrics.RocAuc", "numpy.array", "torch.device", "evaluation_metrics.MultiLabelPrecision", "numpy.concatenate" ]
[((6509, 6524), 'unittest.main', 'unittest.main', ([], {}), '()\n', (6522, 6524), False, 'import unittest\n'), ((2203, 2232), 'iu_xray_data.IU_XRay_Dataset', 'IU_XRay_Dataset', (['data_hparams'], {}), '(data_hparams)\n', (2218, 2232), False, 'from iu_xray_data import IU_XRay_Dataset\n'), ((2295, 2316), 'texar.torch.data.data.data_iterators.DataIterator', 'DataIterator', (['dataset'], {}), '(dataset)\n', (2307, 2316), False, 'from texar.torch.data.data.data_iterators import DataIterator\n'), ((2420, 2442), 'models.cv_model.MLCTrainer', 'MLCTrainer', (['mlc_hparam'], {}), '(mlc_hparam)\n', (2430, 2442), False, 'from models.cv_model import MLCTrainer\n'), ((2547, 2603), 'evaluation_metrics.HammingLoss', 'HammingLoss', ([], {'num_label': 'self.num_label', 'pred_name': '"""preds"""'}), "(num_label=self.num_label, pred_name='preds')\n", (2558, 2603), False, 'from evaluation_metrics import HammingLoss, MultiLabelConfusionMatrix, MultiLabelF1, MultiLabelPrecision, MultiLabelRecall, RocAuc\n'), ((2687, 2711), 'numpy.zeros', 'np.zeros', (['self.num_label'], {}), '(self.num_label)\n', (2695, 2711), True, 'import numpy as np\n'), ((3385, 3455), 'evaluation_metrics.MultiLabelConfusionMatrix', 'MultiLabelConfusionMatrix', ([], {'num_label': 'self.num_label', 'pred_name': '"""preds"""'}), "(num_label=self.num_label, pred_name='preds')\n", (3410, 3455), False, 'from evaluation_metrics import HammingLoss, MultiLabelConfusionMatrix, MultiLabelF1, MultiLabelPrecision, MultiLabelRecall, RocAuc\n'), ((3489, 3553), 'evaluation_metrics.MultiLabelPrecision', 'MultiLabelPrecision', ([], {'num_label': 'self.num_label', 'pred_name': '"""preds"""'}), "(num_label=self.num_label, pred_name='preds')\n", (3508, 3553), False, 'from evaluation_metrics import HammingLoss, MultiLabelConfusionMatrix, MultiLabelF1, MultiLabelPrecision, MultiLabelRecall, RocAuc\n'), ((3584, 3645), 'evaluation_metrics.MultiLabelRecall', 'MultiLabelRecall', ([], {'num_label': 'self.num_label', 'pred_name': '"""preds"""'}), "(num_label=self.num_label, pred_name='preds')\n", (3600, 3645), False, 'from evaluation_metrics import HammingLoss, MultiLabelConfusionMatrix, MultiLabelF1, MultiLabelPrecision, MultiLabelRecall, RocAuc\n'), ((3672, 3729), 'evaluation_metrics.MultiLabelF1', 'MultiLabelF1', ([], {'num_label': 'self.num_label', 'pred_name': '"""preds"""'}), "(num_label=self.num_label, pred_name='preds')\n", (3684, 3729), False, 'from evaluation_metrics import HammingLoss, MultiLabelConfusionMatrix, MultiLabelF1, MultiLabelPrecision, MultiLabelRecall, RocAuc\n'), ((3771, 3803), 'numpy.zeros', 'np.zeros', (['[self.num_label, 2, 2]'], {}), '([self.num_label, 2, 2])\n', (3779, 3803), True, 'import numpy as np\n'), ((4801, 4834), 'numpy.mean', 'np.mean', (['simple_cf_matrix'], {'axis': '(0)'}), '(simple_cf_matrix, axis=0)\n', (4808, 4834), True, 'import numpy as np\n'), ((5775, 5800), 'evaluation_metrics.RocAuc', 'RocAuc', ([], {'pred_name': '"""preds"""'}), "(pred_name='preds')\n", (5781, 5800), False, 'from evaluation_metrics import HammingLoss, MultiLabelConfusionMatrix, MultiLabelF1, MultiLabelPrecision, MultiLabelRecall, RocAuc\n'), ((6265, 6299), 'numpy.concatenate', 'np.concatenate', (['label_list'], {'axis': '(0)'}), '(label_list, axis=0)\n', (6279, 6299), True, 'import numpy as np\n'), ((6320, 6358), 'numpy.concatenate', 'np.concatenate', (['predicted_list'], {'axis': '(0)'}), '(predicted_list, axis=0)\n', (6334, 6358), True, 'import numpy as np\n'), ((6385, 6416), 'sklearn.metrics.roc_auc_score', 'roc_auc_score', (['label', 'predicted'], {}), '(label, predicted)\n', (6398, 6416), False, 'from sklearn.metrics import roc_auc_score\n'), ((1294, 1307), 'numpy.array', 'np.array', (['(0.0)'], {}), '(0.0)\n', (1302, 1307), True, 'import numpy as np\n'), ((2252, 2271), 'torch.device', 'torch.device', (['"""cpu"""'], {}), "('cpu')\n", (2264, 2271), False, 'import torch\n'), ((2815, 2840), 'numpy.array', 'np.array', (["result['preds']"], {}), "(result['preds'])\n", (2823, 2840), True, 'import numpy as np\n'), ((2861, 2882), 'numpy.array', 'np.array', (['batch.label'], {}), '(batch.label)\n', (2869, 2882), True, 'import numpy as np\n'), ((3028, 3062), 'numpy.sum', 'np.sum', (['(predicted == label)'], {'axis': '(0)'}), '(predicted == label, axis=0)\n', (3034, 3062), True, 'import numpy as np\n'), ((3907, 3932), 'numpy.array', 'np.array', (["result['preds']"], {}), "(result['preds'])\n", (3915, 3932), True, 'import numpy as np\n'), ((3953, 3974), 'numpy.array', 'np.array', (['batch.label'], {}), '(batch.label)\n', (3961, 3974), True, 'import numpy as np\n'), ((4085, 4114), 'numpy.sum', 'np.sum', (['true_and_pred'], {'axis': '(0)'}), '(true_and_pred, axis=0)\n', (4091, 4114), True, 'import numpy as np\n'), ((4138, 4163), 'numpy.sum', 'np.sum', (['predicted'], {'axis': '(0)'}), '(predicted, axis=0)\n', (4144, 4163), True, 'import numpy as np\n'), ((4187, 4208), 'numpy.sum', 'np.sum', (['label'], {'axis': '(0)'}), '(label, axis=0)\n', (4193, 4208), True, 'import numpy as np\n'), ((5957, 5982), 'numpy.array', 'np.array', (["result['preds']"], {}), "(result['preds'])\n", (5965, 5982), True, 'import numpy as np\n'), ((6003, 6024), 'numpy.array', 'np.array', (['batch.label'], {}), '(batch.label)\n', (6011, 6024), True, 'import numpy as np\n'), ((6048, 6070), 'numpy.ones_like', 'np.ones_like', (['label[0]'], {}), '(label[0])\n', (6060, 6070), True, 'import numpy as np\n'), ((4380, 4406), 'numpy.array', 'np.array', (['[tn, fp, fn, tp]'], {}), '([tn, fp, fn, tp])\n', (4388, 4406), True, 'import numpy as np\n')]
# -*- encoding:utf-8 -*- """ 选股示例因子:价格选股因子 """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np from .ABuPickStockBase import AbuPickStockBase, reversed_result from ..TLineBu.ABuTL import AbuTLine from ..CoreBu.ABuEnv import EMarketDataSplitMode from ..MarketBu import ABuSymbolPd from ..TradeBu import AbuBenchmark __author__ = '阿布' __weixin__ = 'abu_quant' class AbuPickStockShiftDistance(AbuPickStockBase): """位移路程比选股因子示例类""" def _init_self(self, **kwargs): """通过kwargs设置位移路程比选股条件,配置因子参数""" self.threshold_sd = kwargs.pop('threshold_sd', 2.0) self.threshold_max_cnt = kwargs.pop('threshold_max_cnt', 4) self.threshold_min_cnt = kwargs.pop('threshold_min_cnt', 1) @reversed_result def fit_pick(self, kl_pd, target_symbol): """开始根据位移路程比边际参数进行选股""" pick_line = AbuTLine(kl_pd.close, 'shift distance') shift_distance = pick_line.show_shift_distance(step_x=1.2, show_log=False, show=False) shift_distance = np.array(shift_distance) # show_shift_distance返回的参数为四组数据,最后一组是每个时间段的位移路程比值 sd_arr = shift_distance[:, -1] # 大于阀值的进行累加和计算 # noinspection PyUnresolvedReferences threshold_cnt = (sd_arr >= self.threshold_sd).sum() # 边际条件参数开始生效 if self.threshold_max_cnt > threshold_cnt >= self.threshold_min_cnt: return True return False def fit_first_choice(self, pick_worker, choice_symbols, *args, **kwargs): raise NotImplementedError('AbuPickStockShiftDistance fit_first_choice unsupported now!') class AbuPickStockNTop(AbuPickStockBase): """根据一段时间内的涨幅选取top N个""" def _init_self(self, **kwargs): """通过kwargs设置选股条件,配置因子参数""" # 选股参数symbol_pool:进行涨幅比较的top n个symbol self.symbol_pool = kwargs.pop('symbol_pool', []) # 选股参数n_top:选取前n_top个symbol, 默认3 self.n_top = kwargs.pop('n_top', 3) # 选股参数direction_top:选取前n_top个的方向,即选择涨的多的,还是选择跌的多的 self.direction_top = kwargs.pop('direction_top', 1) @reversed_result def fit_pick(self, kl_pd, target_symbol): """开始根据参数进行选股""" if len(self.symbol_pool) == 0: # 如果没有传递任何参照序列symbol,择默认为选中 return True # 定义lambda函数计算周期内change kl_change = lambda p_kl: \ p_kl.iloc[-1].close / p_kl.iloc[0].close if p_kl.iloc[0].close != 0 else 0 cmp_top_array = [] kl_pd.name = target_symbol # AbuBenchmark直接传递一个kl benchmark = AbuBenchmark(benchmark_kl_pd=kl_pd) for symbol in self.symbol_pool: if symbol != target_symbol: # 使用benchmark模式进行获取 kl = ABuSymbolPd.make_kl_df(symbol, data_mode=EMarketDataSplitMode.E_DATA_SPLIT_UNDO, benchmark=benchmark) # kl = ABuSymbolPd.make_kl_df(symbol, start=start, end=end) if kl is not None and kl.shape[0] > kl_pd.shape[0] * 0.75: # 需要获取实际交易日数量,避免停盘等错误信号 cmp_top_array.append(kl_change(kl)) if self.n_top > len(cmp_top_array): # 如果结果序列不足n_top个,直接认为选中 return True # 与选股方向相乘,即结果只去top cmp_top_array = np.array(cmp_top_array) * self.direction_top # 计算本源的周期内涨跌幅度 target_change = kl_change(kl_pd) * self.direction_top # sort排序小-》大, 非inplace cmp_top_array.sort() # [::-1]大-》小 # noinspection PyTypeChecker if target_change > cmp_top_array[::-1][self.n_top - 1]: # 如果比排序后的第self.n_top位置上的大就认为选中 return True return False def fit_first_choice(self, pick_worker, choice_symbols, *args, **kwargs): raise NotImplementedError('AbuPickStockNTop fit_first_choice unsupported now!')
[ "numpy.array" ]
[((1076, 1100), 'numpy.array', 'np.array', (['shift_distance'], {}), '(shift_distance)\n', (1084, 1100), True, 'import numpy as np\n'), ((3289, 3312), 'numpy.array', 'np.array', (['cmp_top_array'], {}), '(cmp_top_array)\n', (3297, 3312), True, 'import numpy as np\n')]
import matplotlib.pyplot as plt import numpy as np import cv2 from os import path from math import floor import os cwd = os.getcwd() dirname = path.join(cwd, path.dirname(__file__)) class DIP: def bilinear_insert(self, img, gain_x=1.5, gain_y=1.5): H, W, C = img.shape gain_h = round(H*gain_x) gain_w = round(W*gain_y) h_ind = np.floor(np.arange(gain_h) / gain_x).astype(np.int) w_ind = np.floor(np.arange(gain_w) / gain_y).astype(np.int) out = img[:, w_ind][h_ind, :] return out if __name__ == '__main__': dip = DIP() img = cv2.imread(path.join(dirname, '../imori.jpg')).astype(np.float) out = dip.bilinear_insert(img, gain_x=2, gain_y=2) cv2.imwrite(path.join(dirname, './imori_out25.jpg'), out)
[ "os.getcwd", "os.path.dirname", "os.path.join", "numpy.arange" ]
[((123, 134), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (132, 134), False, 'import os\n'), ((160, 182), 'os.path.dirname', 'path.dirname', (['__file__'], {}), '(__file__)\n', (172, 182), False, 'from os import path\n'), ((739, 778), 'os.path.join', 'path.join', (['dirname', '"""./imori_out25.jpg"""'], {}), "(dirname, './imori_out25.jpg')\n", (748, 778), False, 'from os import path\n'), ((614, 648), 'os.path.join', 'path.join', (['dirname', '"""../imori.jpg"""'], {}), "(dirname, '../imori.jpg')\n", (623, 648), False, 'from os import path\n'), ((378, 395), 'numpy.arange', 'np.arange', (['gain_h'], {}), '(gain_h)\n', (387, 395), True, 'import numpy as np\n'), ((446, 463), 'numpy.arange', 'np.arange', (['gain_w'], {}), '(gain_w)\n', (455, 463), True, 'import numpy as np\n')]
import os import cv2 import numpy as np from keras.utils import np_utils from keras.models import Sequential from keras.layers import Dense, Conv2D, MaxPooling2D, Flatten, Dropout from sklearn.model_selection import train_test_split X = [] y = [] data_path = "./data" for number in os.listdir(data_path): for img_name in os.listdir(os.path.join(data_path, number)): y.append(int(number)) img = cv2.imread(os.path.join(data_path, number, img_name)) img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) #_, img = cv2.threshold(img, 0, 255, cv2.THRESH_BINARY) X.append(img) X = np.asarray(X) X = X/255 X = X.reshape(X.shape[0], 28, 28, 1) y = np.asarray(y) y = np_utils.to_categorical(y) X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2) model = Sequential() num_classes = 10 model.add(Conv2D(32, kernel_size=(3, 3), activation='relu', input_shape=(28, 28, 1))) model.add(Conv2D(64, (3, 3), activation='relu')) model.add(MaxPooling2D(pool_size=(2, 2))) model.add(Dropout(0.25)) model.add(Flatten()) model.add(Dense(128, activation='relu')) model.add(Dropout(0.5)) model.add(Dense(num_classes, activation='softmax')) model.compile(loss='categorical_crossentropy', optimizer="adam", metrics=['accuracy']) print(model.summary()) batch_size = 32 epochs = 20 history = model.fit(X_train, y_train, batch_size=batch_size, epochs=epochs, verbose=1) print("\n\nTest metrics") print(model.metrics_names) print(model.evaluate(X_test, y_test)) model.save("./model", overwrite=True)
[ "cv2.cvtColor", "sklearn.model_selection.train_test_split", "numpy.asarray", "keras.layers.MaxPooling2D", "keras.layers.Dropout", "keras.layers.Flatten", "keras.utils.np_utils.to_categorical", "keras.layers.Dense", "keras.layers.Conv2D", "keras.models.Sequential", "os.path.join", "os.listdir" ]
[((284, 305), 'os.listdir', 'os.listdir', (['data_path'], {}), '(data_path)\n', (294, 305), False, 'import os\n'), ((613, 626), 'numpy.asarray', 'np.asarray', (['X'], {}), '(X)\n', (623, 626), True, 'import numpy as np\n'), ((678, 691), 'numpy.asarray', 'np.asarray', (['y'], {}), '(y)\n', (688, 691), True, 'import numpy as np\n'), ((696, 722), 'keras.utils.np_utils.to_categorical', 'np_utils.to_categorical', (['y'], {}), '(y)\n', (719, 722), False, 'from keras.utils import np_utils\n'), ((761, 798), 'sklearn.model_selection.train_test_split', 'train_test_split', (['X', 'y'], {'test_size': '(0.2)'}), '(X, y, test_size=0.2)\n', (777, 798), False, 'from sklearn.model_selection import train_test_split\n'), ((808, 820), 'keras.models.Sequential', 'Sequential', ([], {}), '()\n', (818, 820), False, 'from keras.models import Sequential\n'), ((849, 923), 'keras.layers.Conv2D', 'Conv2D', (['(32)'], {'kernel_size': '(3, 3)', 'activation': '"""relu"""', 'input_shape': '(28, 28, 1)'}), "(32, kernel_size=(3, 3), activation='relu', input_shape=(28, 28, 1))\n", (855, 923), False, 'from keras.layers import Dense, Conv2D, MaxPooling2D, Flatten, Dropout\n'), ((935, 972), 'keras.layers.Conv2D', 'Conv2D', (['(64)', '(3, 3)'], {'activation': '"""relu"""'}), "(64, (3, 3), activation='relu')\n", (941, 972), False, 'from keras.layers import Dense, Conv2D, MaxPooling2D, Flatten, Dropout\n'), ((984, 1014), 'keras.layers.MaxPooling2D', 'MaxPooling2D', ([], {'pool_size': '(2, 2)'}), '(pool_size=(2, 2))\n', (996, 1014), False, 'from keras.layers import Dense, Conv2D, MaxPooling2D, Flatten, Dropout\n'), ((1026, 1039), 'keras.layers.Dropout', 'Dropout', (['(0.25)'], {}), '(0.25)\n', (1033, 1039), False, 'from keras.layers import Dense, Conv2D, MaxPooling2D, Flatten, Dropout\n'), ((1051, 1060), 'keras.layers.Flatten', 'Flatten', ([], {}), '()\n', (1058, 1060), False, 'from keras.layers import Dense, Conv2D, MaxPooling2D, Flatten, Dropout\n'), ((1072, 1101), 'keras.layers.Dense', 'Dense', (['(128)'], {'activation': '"""relu"""'}), "(128, activation='relu')\n", (1077, 1101), False, 'from keras.layers import Dense, Conv2D, MaxPooling2D, Flatten, Dropout\n'), ((1113, 1125), 'keras.layers.Dropout', 'Dropout', (['(0.5)'], {}), '(0.5)\n', (1120, 1125), False, 'from keras.layers import Dense, Conv2D, MaxPooling2D, Flatten, Dropout\n'), ((1137, 1177), 'keras.layers.Dense', 'Dense', (['num_classes'], {'activation': '"""softmax"""'}), "(num_classes, activation='softmax')\n", (1142, 1177), False, 'from keras.layers import Dense, Conv2D, MaxPooling2D, Flatten, Dropout\n'), ((338, 369), 'os.path.join', 'os.path.join', (['data_path', 'number'], {}), '(data_path, number)\n', (350, 369), False, 'import os\n'), ((484, 521), 'cv2.cvtColor', 'cv2.cvtColor', (['img', 'cv2.COLOR_BGR2GRAY'], {}), '(img, cv2.COLOR_BGR2GRAY)\n', (496, 521), False, 'import cv2\n'), ((427, 468), 'os.path.join', 'os.path.join', (['data_path', 'number', 'img_name'], {}), '(data_path, number, img_name)\n', (439, 468), False, 'import os\n')]
from zenoh_service.core.zenoh_net import ZenohNet from zenoh_service.zenoh_net_publisher import ZenohNetPublisher import sys import time from datetime import datetime import numpy as np import cv2 import simplejson as json from enum import Enum import logging import argparse # from hurry.filesize import size as fsize from pycore.extras.functions import humanbytes as fsize try: import nanocamera as nano except: print("[WARNING] Unable to load `nanocamera` module") # Encoding parameter encode_param = [int(cv2.IMWRITE_JPEG_QUALITY), 70] # The default value for IMWRITE_JPEG_QUALITY is 95 # --- [START] Command line argument parsing --- --- --- --- --- --- parser = argparse.ArgumentParser( description='Zenoh Publisher example') parser.add_argument('--camera', '-m', dest='camera', # e.g. 172.16.17.32 (Little Boy) default=2, # `1`=JetsonNano; `2`=Normal Camera (PC/Laptop/etc) type=int, help='The name of the resource to publish.') parser.add_argument('--peer', '-e', dest='peer', # e.g. 172.16.17.32 (Little Boy) metavar='LOCATOR', action='append', type=str, help='Peer locators used to initiate the zenoh session.') parser.add_argument('--path', '-p', dest='path', default='/eaglestitch/svc/zenoh-python-pub', type=str, help='The name of the resource to publish.') parser.add_argument('--video', '-v', dest='video', default="0", type=str, help='The name of the resource to publish.') parser.add_argument('--cvout', dest='cvout', action='store_true', help="Use CV Out") parser.set_defaults(cvout=False) # parser.add_argument('--no-compress', dest='compress', action='store_false', help="Use CV Out") # parser.set_defaults(compress=True) args = parser.parse_args() # --- [END] Command line argument parsing --- --- --- --- --- --- ### L = logging.getLogger(__name__) ### def encrypt_str(str_val, byteorder="little"): encrypted_bytes = str_val.encode('utf-8') encrypted_val = int.from_bytes(encrypted_bytes, byteorder) # `byteorder` must be either 'little' or 'big' return encrypted_val # max 19 digit def get_capture_camera(capt, cam_mode): if cam_mode == 1: return capt.isReady() else: return cap.isOpened() peer = args.peer if peer is not None: peer = ",".join(args.peer) video_path = args.video if video_path == "0": video_path = int(video_path) # Enable / disable cvout _enable_cv_out = args.cvout # configure zenoh service path = args.path z_svc = ZenohNetPublisher( _path=path, _session_type="PUBLISHER", _peer=peer ) z_svc.init_connection() # register and collect publisher object z_svc.register() publisher = z_svc.get_publisher() ######################### # Zenoh related variables itype = 3 encoder_format = [ ('id', 'U10'), ('timestamp', 'f'), ('data', [('flatten', 'i')], (1, 6220800)), ('store_enabled', '?'), ] window_title = "output-raw" if args.camera == 1: try: cap = nano.Camera(camera_type=1) except: print("[ERROR] Unable to load `nano` package") exit(0) elif args.camera == 2: cap = cv2.VideoCapture(video_path) # cap = cv2.VideoCapture(0) # cap = cv2.VideoCapture("/home/ardi/devel/nctu/IBM-Lab/eaglestitch/data/videos/0312_2_CUT.mp4") # cap = cv2.VideoCapture("/home/tim/devel/eaglestitch/data/videos/samer/0312_1_LtoR_1.mp4") # cap = cv2.VideoCapture("/home/ardi/devel/nctu/IBM-Lab/eaglestitch/data/videos/samer/0312_1_LtoR_1.mp4") else: print("[ERROR] Unrecognized camera mode") exit(0) if _enable_cv_out: cv2.namedWindow(window_title, cv2.WND_PROP_FULLSCREEN) # cv2.resizeWindow("Image", 1920, 1080) # Enter your size cv2.resizeWindow(window_title, 800, 550) # Enter your size _frame_id = 0 _wt, _ht = 1080, 1920 # target width and height _w, _h = None, None # default detected width and height # IMPORTANT _is_compressed = True # it enables/disables image compression when sending image frames # Extra information (to be tagged into the frame) int_drone_id = encrypt_str("Drone 01") # contains 1 extra slot t0_array = str(time.time()).split(".") # contains 2 extra slots extra_len = 5 # contains 1 extra slot; another one slot is from `tagged_data_len` variable # while cap.isOpened(): while get_capture_camera(cap, args.camera): _frame_id += 1 # ret = a boolean return value from getting the frame, frame = the current frame being projected in the video try: if args.camera == 1: # jetson nano ret, frame = True, cap.read() else: ret, frame = cap.read() # do it ONCE # detect width and height if _w is None: _w, _h, _ = frame.shape t0_decoding = time.time() # resize the frame; Default VGA (640 x 480) for Laptop camera if _w != _wt: frame = cv2.resize(frame, (1920, 1080)) # print size print(" >>> FRAME Size BEFORE compression: {} or {}".format(frame.nbytes, fsize(frame.nbytes))) # compress image (if enabled) if _is_compressed: # NEW encoding method # print(" ### compress image (if enabled)") encoder_format = None # disable custom encoder itype = 4 # new type specially for compressed image t0_img_compression = time.time() _, compressed_img = cv2.imencode('.jpg', frame, encode_param) compressed_img_len, _ = compressed_img.shape t1_img_compression = (time.time() - t0_img_compression) * 1000 print(('[%s] Latency Image Compression (%.3f ms) ' % ( datetime.now().strftime("%H:%M:%S"), t1_img_compression))) tagged_data_len = compressed_img_len + extra_len # `tagged_data_len` itself contains 1 extra slot # cv2.imwrite("hasil.jpg", decimg) # print size print(" >>> FRAME Size AFTER compression: {} or {}".format(compressed_img.nbytes, fsize(compressed_img.nbytes))) # vertically tag this frame with an extra inforamtion t0_tag_extraction = time.time() tagged_info = [ [int_drone_id], [int(t0_array[0])], [int(t0_array[1])], [extra_len], [tagged_data_len], ] # print(" ----- OLD SHAPE compressed_img:", compressed_img.shape) val = np.vstack([compressed_img, tagged_info]) t1_tag_extraction = (time.time() - t0_tag_extraction) * 1000 print(('[%s] Latency Image Taging (%.3f ms) ' % (datetime.now().strftime("%H:%M:%S"), t1_tag_extraction))) else: # OLD enconding method val = [('Drone 1', time.time(), frame.tobytes())] t1_decoding = (time.time() - t0_decoding) * 1000 print(('\n[%s] Latency tagging (%.3f ms) \n' % (datetime.now().strftime("%H:%M:%S"), t1_decoding))) # OLD enconding method # # img_1d = frame.reshape(1, -1) # # val = [('Drone 1', time.time(), img_1d, False)] # # val = [('Drone 1', time.time(), imgencode, False)] # val = [('Drone 1', time.time(), imgencode.tobytes())] # t1_decoding = (time.time() - t0_decoding) * 1000 # print(('\n[%s] Latency tagging (%.3f ms) \n' % (datetime.now().strftime("%H:%M:%S"), t1_decoding))) # publish in every 2 frames if ret and _frame_id % 2 == 0: # publish data z_svc.publish( _val=val, _itype=itype, _encoder=encoder_format, ) # time.sleep(1) if _enable_cv_out: cv2.imshow(window_title, frame) print() except Exception as e: print("No more frame to show: `{}`".format(e)) break if _enable_cv_out: if cv2.waitKey(1) & 0xFF == ord('q'): break if _enable_cv_out: # The following frees up resources and closes all windows cap.release() cv2.destroyAllWindows() ######################### # n_epoch = 5 # total number of publication processes # # for i in range(n_epoch): # while True: # # publish data # z_svc.publish( # _val=val, # _itype=itype, # _encoder=encoder_format, # ) # # time.sleep(0.33) # closing Zenoh publisher & session z_svc.close_connection(publisher)
[ "cv2.resize", "argparse.ArgumentParser", "cv2.waitKey", "nanocamera.Camera", "cv2.imshow", "logging.getLogger", "time.time", "cv2.VideoCapture", "pycore.extras.functions.humanbytes", "cv2.imencode", "numpy.vstack", "cv2.resizeWindow", "cv2.destroyAllWindows", "datetime.datetime.now", "zenoh_service.zenoh_net_publisher.ZenohNetPublisher", "cv2.namedWindow" ]
[((674, 736), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Zenoh Publisher example"""'}), "(description='Zenoh Publisher example')\n", (697, 736), False, 'import argparse\n'), ((2016, 2043), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (2033, 2043), False, 'import logging\n'), ((2653, 2721), 'zenoh_service.zenoh_net_publisher.ZenohNetPublisher', 'ZenohNetPublisher', ([], {'_path': 'path', '_session_type': '"""PUBLISHER"""', '_peer': 'peer'}), "(_path=path, _session_type='PUBLISHER', _peer=peer)\n", (2670, 2721), False, 'from zenoh_service.zenoh_net_publisher import ZenohNetPublisher\n'), ((3656, 3710), 'cv2.namedWindow', 'cv2.namedWindow', (['window_title', 'cv2.WND_PROP_FULLSCREEN'], {}), '(window_title, cv2.WND_PROP_FULLSCREEN)\n', (3671, 3710), False, 'import cv2\n'), ((3772, 3812), 'cv2.resizeWindow', 'cv2.resizeWindow', (['window_title', '(800)', '(550)'], {}), '(window_title, 800, 550)\n', (3788, 3812), False, 'import cv2\n'), ((7477, 7500), 'cv2.destroyAllWindows', 'cv2.destroyAllWindows', ([], {}), '()\n', (7498, 7500), False, 'import cv2\n'), ((3096, 3122), 'nanocamera.Camera', 'nano.Camera', ([], {'camera_type': '(1)'}), '(camera_type=1)\n', (3107, 3122), True, 'import nanocamera as nano\n'), ((3221, 3249), 'cv2.VideoCapture', 'cv2.VideoCapture', (['video_path'], {}), '(video_path)\n', (3237, 3249), False, 'import cv2\n'), ((4740, 4751), 'time.time', 'time.time', ([], {}), '()\n', (4749, 4751), False, 'import time\n'), ((4185, 4196), 'time.time', 'time.time', ([], {}), '()\n', (4194, 4196), False, 'import time\n'), ((4843, 4874), 'cv2.resize', 'cv2.resize', (['frame', '(1920, 1080)'], {}), '(frame, (1920, 1080))\n', (4853, 4874), False, 'import cv2\n'), ((5246, 5257), 'time.time', 'time.time', ([], {}), '()\n', (5255, 5257), False, 'import time\n'), ((5281, 5322), 'cv2.imencode', 'cv2.imencode', (['""".jpg"""', 'frame', 'encode_param'], {}), "('.jpg', frame, encode_param)\n", (5293, 5322), False, 'import cv2\n'), ((5912, 5923), 'time.time', 'time.time', ([], {}), '()\n', (5921, 5923), False, 'import time\n'), ((6134, 6174), 'numpy.vstack', 'np.vstack', (['[compressed_img, tagged_info]'], {}), '([compressed_img, tagged_info])\n', (6143, 6174), True, 'import numpy as np\n'), ((7189, 7220), 'cv2.imshow', 'cv2.imshow', (['window_title', 'frame'], {}), '(window_title, frame)\n', (7199, 7220), False, 'import cv2\n'), ((4967, 4986), 'pycore.extras.functions.humanbytes', 'fsize', (['frame.nbytes'], {}), '(frame.nbytes)\n', (4972, 4986), True, 'from pycore.extras.functions import humanbytes as fsize\n'), ((7338, 7352), 'cv2.waitKey', 'cv2.waitKey', (['(1)'], {}), '(1)\n', (7349, 7352), False, 'import cv2\n'), ((5396, 5407), 'time.time', 'time.time', ([], {}), '()\n', (5405, 5407), False, 'import time\n'), ((5800, 5828), 'pycore.extras.functions.humanbytes', 'fsize', (['compressed_img.nbytes'], {}), '(compressed_img.nbytes)\n', (5805, 5828), True, 'from pycore.extras.functions import humanbytes as fsize\n'), ((6199, 6210), 'time.time', 'time.time', ([], {}), '()\n', (6208, 6210), False, 'import time\n'), ((6405, 6416), 'time.time', 'time.time', ([], {}), '()\n', (6414, 6416), False, 'import time\n'), ((6454, 6465), 'time.time', 'time.time', ([], {}), '()\n', (6463, 6465), False, 'import time\n'), ((5499, 5513), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (5511, 5513), False, 'from datetime import datetime\n'), ((6291, 6305), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (6303, 6305), False, 'from datetime import datetime\n'), ((6539, 6553), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (6551, 6553), False, 'from datetime import datetime\n')]
import numpy as np from vec_io import fvecs_read from sorter import parallel_sort from lsh import SRP from transform import spherical_transform, simple_lsh def intersect(gs, ids): rc = np.mean([ len(np.intersect1d(g, list(id))) for g, id in zip(gs, ids)]) return rc def recalls(index, q_, gt): ks = [20, 100] ts = [16, 128, 1024] print(" Probed \t Items \t", end="") for top_k in ks: print("top-%d\t" % (top_k), end="") print() for t in ts: ids = index.search(q_, t) items = np.mean([len(id) for id in ids]) print("%6d \t %6d \t" % (t, items), end="") for top_k in ks: rc = intersect(gt[:, :top_k], ids) print("%.4f \t" % (rc / float(top_k)), end="") print() def load_data(): dataset = "netflix" base = "/home/xinyan/program/data/" # dataset = "imagenet" # base = "/research/jcheng2/xinyan/data/" x_path = "{}{}/{}_base.fvecs".format(base, dataset, dataset) q_path = "{}{}/{}_query.fvecs".format(base, dataset, dataset) x = fvecs_read(x_path) q = fvecs_read(q_path)[:1000] return x, q def main(): x, q = load_data() n, d = x.shape np.random.seed(808) w = np.random.uniform(size=d) w = w / np.linalg.norm(w) gt = parallel_sort(x, q, w, metric="weighted") ks = 256 print("==================spherical_transform====================") x_, q_ = spherical_transform(x, q, w) n_, d_ = x_.shape np.random.seed(808) index = SRP(k=ks, d=d_) index.add(x_) recalls(index, q_, gt) if __name__ == "__main__": main()
[ "numpy.random.uniform", "numpy.random.seed", "sorter.parallel_sort", "vec_io.fvecs_read", "transform.spherical_transform", "numpy.linalg.norm", "lsh.SRP" ]
[((1078, 1096), 'vec_io.fvecs_read', 'fvecs_read', (['x_path'], {}), '(x_path)\n', (1088, 1096), False, 'from vec_io import fvecs_read\n'), ((1208, 1227), 'numpy.random.seed', 'np.random.seed', (['(808)'], {}), '(808)\n', (1222, 1227), True, 'import numpy as np\n'), ((1236, 1261), 'numpy.random.uniform', 'np.random.uniform', ([], {'size': 'd'}), '(size=d)\n', (1253, 1261), True, 'import numpy as np\n'), ((1302, 1343), 'sorter.parallel_sort', 'parallel_sort', (['x', 'q', 'w'], {'metric': '"""weighted"""'}), "(x, q, w, metric='weighted')\n", (1315, 1343), False, 'from sorter import parallel_sort\n'), ((1443, 1471), 'transform.spherical_transform', 'spherical_transform', (['x', 'q', 'w'], {}), '(x, q, w)\n', (1462, 1471), False, 'from transform import spherical_transform, simple_lsh\n'), ((1498, 1517), 'numpy.random.seed', 'np.random.seed', (['(808)'], {}), '(808)\n', (1512, 1517), True, 'import numpy as np\n'), ((1530, 1545), 'lsh.SRP', 'SRP', ([], {'k': 'ks', 'd': 'd_'}), '(k=ks, d=d_)\n', (1533, 1545), False, 'from lsh import SRP\n'), ((1105, 1123), 'vec_io.fvecs_read', 'fvecs_read', (['q_path'], {}), '(q_path)\n', (1115, 1123), False, 'from vec_io import fvecs_read\n'), ((1274, 1291), 'numpy.linalg.norm', 'np.linalg.norm', (['w'], {}), '(w)\n', (1288, 1291), True, 'import numpy as np\n')]
# -*- coding: utf-8 -*- """ Create my own style of colorbar """ __title__ = "Replace Hex Colors" __author__ = "<NAME>" __version__ = "1.1(19.02.2018)" __email__ = "<EMAIL>" #============================================================================== # modules import numpy as np import matplotlib as mpl from matplotlib.colors import LinearSegmentedColormap import matplotlib.colors as mpc # import webcolors as wc import ipdb #============================================================================== def ReplaceHexColor(cmaplist, cmin, cmax, color = '#FFFFFF', ticks=None, zeroR = None): """ Take a list of hex values, insert white in as a color, define some bounds args: cmapList """ # ========== Setup the parpmaters ========== # Get the size cmapsize = int(len(cmaplist)) # get the number of ticks tickinter = (cmax-cmin)/(float(cmapsize)) # ========== add the color to the list ========== cmaplist.insert(int(cmapsize/2), color) # =========== Remove the weak colors ========== # del cmaplist[cmapsize/2+1] # del cmaplist[cmapsize/2-1] # cmaplist.insert(0, cmaplist[0]) # cmaplist.insert(-1, cmaplist[-1]) # pdb.set_trace() if zeroR is None: if cmax < 0.01: zerob = 0.000001 else: zerob = 0.0001 else: zerob = zeroR # Set the tick values try: if ticks is None: ticks = np.round(np.arange(cmin, (cmax+0.00001), tickinter), decimals=6) spacing = 'proportional' bounds = np.hstack( ( ticks[:int(cmapsize/2)], np.array([-zerob, zerob]), ticks[int(cmapsize/2+1):] ) ) else: spacing = 'uniform' bounds = np.hstack( ( ticks[:int(cmapsize/2)], np.array([-zerob, zerob]), ticks[int(cmapsize/2+1):] ) ) ticks = np.hstack( (ticks[:int(cmapsize/2)], np.array([-zerob,ticks[int(cmapsize/2)], zerob]), ticks[int(cmapsize/2+1):])) except Exception as e: print(str(e)) ipdb.set_trace() # ========== create the colormap ========== cmap = mpl.colors.ListedColormap(cmaplist) cmap.set_over(cmaplist[-1]) cmap.set_under(cmaplist[0]) # ========== Define the bounds and norm ========== norm = mpl.colors.BoundaryNorm(bounds, cmap.N) # ========== Return cmap and infomation ========== return cmap, norm, ticks, bounds, spacing
[ "ipdb.set_trace", "matplotlib.colors.BoundaryNorm", "numpy.array", "numpy.arange", "matplotlib.colors.ListedColormap" ]
[((2074, 2109), 'matplotlib.colors.ListedColormap', 'mpl.colors.ListedColormap', (['cmaplist'], {}), '(cmaplist)\n', (2099, 2109), True, 'import matplotlib as mpl\n'), ((2243, 2282), 'matplotlib.colors.BoundaryNorm', 'mpl.colors.BoundaryNorm', (['bounds', 'cmap.N'], {}), '(bounds, cmap.N)\n', (2266, 2282), True, 'import matplotlib as mpl\n'), ((1994, 2010), 'ipdb.set_trace', 'ipdb.set_trace', ([], {}), '()\n', (2008, 2010), False, 'import ipdb\n'), ((1405, 1445), 'numpy.arange', 'np.arange', (['cmin', '(cmax + 1e-05)', 'tickinter'], {}), '(cmin, cmax + 1e-05, tickinter)\n', (1414, 1445), True, 'import numpy as np\n'), ((1557, 1582), 'numpy.array', 'np.array', (['[-zerob, zerob]'], {}), '([-zerob, zerob])\n', (1565, 1582), True, 'import numpy as np\n'), ((1730, 1755), 'numpy.array', 'np.array', (['[-zerob, zerob]'], {}), '([-zerob, zerob])\n', (1738, 1755), True, 'import numpy as np\n')]
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved import json import random from typing import List, Optional, Tuple import cv2 import numpy as np import torchvision.transforms as T from detectron2.config import CfgNode from detectron2.data.transforms import Transform, TransformGen, NoOpTransform from .build import TRANSFORM_OP_REGISTRY class AffineTransform(Transform): def __init__( self, M: np.ndarray, img_w: int, img_h: int, flags: Optional[int] = None, border_mode: Optional[int] = None, is_inversed_M: bool = False, ): """ Args: will transform img according to affine transform M """ super().__init__() self._set_attributes(locals()) self.warp_kwargs = {} if flags is not None: self.warp_kwargs["flags"] = flags if border_mode is not None: self.warp_kwargs["borderMode"] = border_mode def apply_image(self, img: np.ndarray) -> np.ndarray: M = self.M if self.is_inversed_M: M = M[:2] img = cv2.warpAffine( img, M, (int(self.img_w), (self.img_h)), **self.warp_kwargs, ) return img def apply_coords(self, coords: np.ndarray) -> np.ndarray: # Add row of ones to enable matrix multiplication coords = coords.T ones = np.ones((1, coords.shape[1])) coords = np.vstack((coords, ones)) M = self.M if self.is_inversed_M: M = np.linalg.inv(M) coords = (M @ coords)[:2, :].T return coords class RandomPivotScaling(TransformGen): """ Uniformly pick a random pivot point inside image frame, scaling the image around the pivot point using the scale factor sampled from a list of given scales. The pivot point's location is unchanged after the transform. Arguments: scales: List[float]: each element can be any positive float number, when larger than 1.0 objects become larger after transform and vice versa. """ def __init__(self, scales: List[int]): super().__init__() self._init(locals()) self.scales = scales def get_transform(self, img: np.ndarray) -> Transform: img_h, img_w, _ = img.shape img_h = float(img_h) img_w = float(img_w) pivot_y = self._rand_range(0.0, img_h) pivot_x = self._rand_range(0.0, img_w) def _interp(p1, p2, alpha): dx = p2[0] - p1[0] dy = p2[1] - p1[1] p_x = p1[0] + alpha * dx p_y = p1[1] + alpha * dy return (p_x, p_y) scale = np.random.choice(self.scales) lt = (0.0, 0.0) rb = (img_w, img_h) pivot = (pivot_x, pivot_y) pts1 = np.float32([lt, pivot, rb]) pts2 = np.float32( [_interp(pivot, lt, scale), pivot, _interp(pivot, rb, scale)], ) M = cv2.getAffineTransform(pts1, pts2) return AffineTransform(M, img_w, img_h) class RandomAffine(TransformGen): """ Apply random affine trasform to the image given probabilities and ranges in each dimension. """ def __init__( self, prob: float = 0.5, angle_range: Tuple[float, float] = (-90, 90), translation_range: Tuple[float, float] = (0, 0), scale_range: Tuple[float, float] = (1.0, 1.0), shear_range: Tuple[float, float] = (0, 0), ): """ Args: prob (float): probability of applying transform. angle_range (tuple of integers): min/max rotation angle in degrees between -180 and 180. translation_range (tuple of integers): min/max translation (post re-centered rotation). scale_range (tuple of floats): min/max scale (post re-centered rotation). shear_range (tuple of intgers): min/max shear angle value in degrees between -180 to 180. """ super().__init__() # Turn all locals into member variables. self._init(locals()) def get_transform(self, img: np.ndarray) -> Transform: im_h, im_w = img.shape[:2] max_size = max(im_w, im_h) center = [im_w / 2, im_h / 2] angle = random.uniform(self.angle_range[0], self.angle_range[1]) translation = [ random.uniform(self.translation_range[0], self.translation_range[1]), random.uniform(self.translation_range[0], self.translation_range[1]), ] scale = random.uniform(self.scale_range[0], self.scale_range[1]) shear = [ random.uniform(self.shear_range[0], self.shear_range[1]), random.uniform(self.shear_range[0], self.shear_range[1]), ] dummy_translation = [0.0, 0.0] dummy_scale = 1.0 M_inv = T.functional._get_inverse_affine_matrix( center, angle, dummy_translation, dummy_scale, shear ) M_inv.extend([0.0, 0.0, 1.0]) M_inv = np.array(M_inv).reshape((3, 3)) M = np.linalg.inv(M_inv) # Center in output patch img_corners = np.array( [ [0, 0, im_w, im_w], [0, im_h, 0, im_h], [1, 1, 1, 1], ] ) transformed_corners = M @ img_corners x_min = np.amin(transformed_corners[0]) x_max = np.amax(transformed_corners[0]) x_range = np.ceil(x_max - x_min) y_min = np.amin(transformed_corners[1]) y_max = np.amax(transformed_corners[1]) y_range = np.ceil(y_max - y_min) # Apply translation and scale after centering in output patch translation_adjustment = [(max_size - im_w) / 2, (max_size - im_h) / 2] translation[0] += translation_adjustment[0] translation[1] += translation_adjustment[1] scale_adjustment = min(max_size / x_range, max_size / y_range) scale *= scale_adjustment M_inv = T.functional._get_inverse_affine_matrix( center, angle, translation, scale, shear ) # Convert to Numpy matrix so it can be inverted M_inv.extend([0.0, 0.0, 1.0]) M_inv = np.array(M_inv).reshape((3, 3)) M = np.linalg.inv(M_inv) do = self._rand_range() < self.prob if do: return AffineTransform( M_inv, max_size, max_size, flags=cv2.WARP_INVERSE_MAP + cv2.INTER_LINEAR, border_mode=cv2.BORDER_REPLICATE, is_inversed_M=True, ) else: return NoOpTransform() # example repr: "RandomPivotScalingOp::[1.0, 0.75, 0.5]" @TRANSFORM_OP_REGISTRY.register() def RandomPivotScalingOp(cfg: CfgNode, arg_str: str, is_train: bool) -> List[Transform]: assert is_train scales = json.loads(arg_str) assert isinstance(scales, list) assert all(isinstance(scale, (float, int)) for scale in scales) return [RandomPivotScaling(scales=scales)] @TRANSFORM_OP_REGISTRY.register() def RandomAffineOp(cfg: CfgNode, arg_str: str, is_train: bool) -> List[Transform]: assert is_train kwargs = json.loads(arg_str) if arg_str is not None else {} assert isinstance(kwargs, dict) return [RandomAffine(**kwargs)]
[ "json.loads", "numpy.amin", "random.uniform", "numpy.ceil", "numpy.float32", "numpy.ones", "detectron2.data.transforms.NoOpTransform", "torchvision.transforms.functional._get_inverse_affine_matrix", "numpy.amax", "numpy.linalg.inv", "cv2.getAffineTransform", "numpy.array", "numpy.random.choice", "numpy.vstack" ]
[((6971, 6990), 'json.loads', 'json.loads', (['arg_str'], {}), '(arg_str)\n', (6981, 6990), False, 'import json\n'), ((1468, 1497), 'numpy.ones', 'np.ones', (['(1, coords.shape[1])'], {}), '((1, coords.shape[1]))\n', (1475, 1497), True, 'import numpy as np\n'), ((1515, 1540), 'numpy.vstack', 'np.vstack', (['(coords, ones)'], {}), '((coords, ones))\n', (1524, 1540), True, 'import numpy as np\n'), ((2761, 2790), 'numpy.random.choice', 'np.random.choice', (['self.scales'], {}), '(self.scales)\n', (2777, 2790), True, 'import numpy as np\n'), ((2893, 2920), 'numpy.float32', 'np.float32', (['[lt, pivot, rb]'], {}), '([lt, pivot, rb])\n', (2903, 2920), True, 'import numpy as np\n'), ((3046, 3080), 'cv2.getAffineTransform', 'cv2.getAffineTransform', (['pts1', 'pts2'], {}), '(pts1, pts2)\n', (3068, 3080), False, 'import cv2\n'), ((4378, 4434), 'random.uniform', 'random.uniform', (['self.angle_range[0]', 'self.angle_range[1]'], {}), '(self.angle_range[0], self.angle_range[1])\n', (4392, 4434), False, 'import random\n'), ((4649, 4705), 'random.uniform', 'random.uniform', (['self.scale_range[0]', 'self.scale_range[1]'], {}), '(self.scale_range[0], self.scale_range[1])\n', (4663, 4705), False, 'import random\n'), ((4956, 5053), 'torchvision.transforms.functional._get_inverse_affine_matrix', 'T.functional._get_inverse_affine_matrix', (['center', 'angle', 'dummy_translation', 'dummy_scale', 'shear'], {}), '(center, angle, dummy_translation,\n dummy_scale, shear)\n', (4995, 5053), True, 'import torchvision.transforms as T\n'), ((5170, 5190), 'numpy.linalg.inv', 'np.linalg.inv', (['M_inv'], {}), '(M_inv)\n', (5183, 5190), True, 'import numpy as np\n'), ((5247, 5311), 'numpy.array', 'np.array', (['[[0, 0, im_w, im_w], [0, im_h, 0, im_h], [1, 1, 1, 1]]'], {}), '([[0, 0, im_w, im_w], [0, im_h, 0, im_h], [1, 1, 1, 1]])\n', (5255, 5311), True, 'import numpy as np\n'), ((5459, 5490), 'numpy.amin', 'np.amin', (['transformed_corners[0]'], {}), '(transformed_corners[0])\n', (5466, 5490), True, 'import numpy as np\n'), ((5507, 5538), 'numpy.amax', 'np.amax', (['transformed_corners[0]'], {}), '(transformed_corners[0])\n', (5514, 5538), True, 'import numpy as np\n'), ((5557, 5579), 'numpy.ceil', 'np.ceil', (['(x_max - x_min)'], {}), '(x_max - x_min)\n', (5564, 5579), True, 'import numpy as np\n'), ((5596, 5627), 'numpy.amin', 'np.amin', (['transformed_corners[1]'], {}), '(transformed_corners[1])\n', (5603, 5627), True, 'import numpy as np\n'), ((5644, 5675), 'numpy.amax', 'np.amax', (['transformed_corners[1]'], {}), '(transformed_corners[1])\n', (5651, 5675), True, 'import numpy as np\n'), ((5694, 5716), 'numpy.ceil', 'np.ceil', (['(y_max - y_min)'], {}), '(y_max - y_min)\n', (5701, 5716), True, 'import numpy as np\n'), ((6094, 6179), 'torchvision.transforms.functional._get_inverse_affine_matrix', 'T.functional._get_inverse_affine_matrix', (['center', 'angle', 'translation', 'scale', 'shear'], {}), '(center, angle, translation, scale,\n shear)\n', (6133, 6179), True, 'import torchvision.transforms as T\n'), ((6352, 6372), 'numpy.linalg.inv', 'np.linalg.inv', (['M_inv'], {}), '(M_inv)\n', (6365, 6372), True, 'import numpy as np\n'), ((7294, 7313), 'json.loads', 'json.loads', (['arg_str'], {}), '(arg_str)\n', (7304, 7313), False, 'import json\n'), ((1607, 1623), 'numpy.linalg.inv', 'np.linalg.inv', (['M'], {}), '(M)\n', (1620, 1623), True, 'import numpy as np\n'), ((4471, 4539), 'random.uniform', 'random.uniform', (['self.translation_range[0]', 'self.translation_range[1]'], {}), '(self.translation_range[0], self.translation_range[1])\n', (4485, 4539), False, 'import random\n'), ((4553, 4621), 'random.uniform', 'random.uniform', (['self.translation_range[0]', 'self.translation_range[1]'], {}), '(self.translation_range[0], self.translation_range[1])\n', (4567, 4621), False, 'import random\n'), ((4736, 4792), 'random.uniform', 'random.uniform', (['self.shear_range[0]', 'self.shear_range[1]'], {}), '(self.shear_range[0], self.shear_range[1])\n', (4750, 4792), False, 'import random\n'), ((4806, 4862), 'random.uniform', 'random.uniform', (['self.shear_range[0]', 'self.shear_range[1]'], {}), '(self.shear_range[0], self.shear_range[1])\n', (4820, 4862), False, 'import random\n'), ((6740, 6755), 'detectron2.data.transforms.NoOpTransform', 'NoOpTransform', ([], {}), '()\n', (6753, 6755), False, 'from detectron2.data.transforms import Transform, TransformGen, NoOpTransform\n'), ((5126, 5141), 'numpy.array', 'np.array', (['M_inv'], {}), '(M_inv)\n', (5134, 5141), True, 'import numpy as np\n'), ((6308, 6323), 'numpy.array', 'np.array', (['M_inv'], {}), '(M_inv)\n', (6316, 6323), True, 'import numpy as np\n')]
import logging import warnings import numpy as np import pandas as pd from scipy import integrate, stats from scipy.interpolate import InterpolatedUnivariateSpline from .util import log_err_func def cal_chi_square(f_hat_array, f_array): chi_square = np.sum((f_hat_array - f_array) ** 2 / f_hat_array) return chi_square def smoothing(x, y): x = x[np.isfinite(y)] y = y[np.isfinite(y)] spl = InterpolatedUnivariateSpline(x, y) return spl def fx_r_from_gy_r(g, p, x, y_min, y_max): f_r = np.zeros_like(x, dtype=float) for i, x_i in enumerate(x): f_r[i] = integrate.quad(lambda y: g(y) * p(x_i, y), y_min, y_max)[0] return smoothing(x[f_r > 0], f_r[f_r > 0]) def gy_r1_from_fx_r(f_r, f_hat, g, p, y, x_min, x_max): g_r1 = np.zeros_like(y, dtype=float) for i, y_i in enumerate(y): g_r1[i] = ( g(y_i) * integrate.quad( lambda x: f_hat(x) / f_r(x) * p(x, y_i), x_min, x_max, limit=100 )[0] ) return smoothing(y[g_r1 > 0], g_r1[g_r1 > 0]) def fx_r_from_gy_r_bound(g, p, x, y_min, y_max): f_r = np.zeros_like(x, dtype=float) for i, x_i in enumerate(x): f_r[i] = integrate.quad( lambda y: g(y) * p(x_i, y), x_i, y_max, limit=100, points=[x_i] )[0] return smoothing(x[f_r > 0], f_r[f_r > 0]) def gy_r1_from_fx_r_bound(f_r, f_hat, g, p, y, x_min, x_max): g_r1 = np.zeros_like(y, dtype=float) for i, y_i in enumerate(y): g_r1[i] = ( g(y_i) * integrate.quad( lambda x: f_hat(x) / f_r(x) * p(x, y_i), x_min, y_i, limit=100, points=[x_min, y_i], )[0] ) return smoothing(y[g_r1 > 0], g_r1[g_r1 > 0]) def lucy(p, f_hat, x_array, y_array, limit_i=50, p_ratio=0.97): warnings.filterwarnings("ignore") g = smoothing(x_array, np.ones_like(x_array) * np.max(f_hat(x_array)) / 2) chi_square_p = +np.inf i = 0 for i in range(limit_i): f = fx_r_from_gy_r(g, p, x_array, y_min=min(y_array), y_max=max(y_array)) chi_square = cal_chi_square(f_hat(x_array), f(x_array)) if chi_square < chi_square_p * p_ratio: chi_square_p = chi_square g = gy_r1_from_fx_r( f, f_hat, g, p, y_array, x_min=min(x_array), x_max=max(x_array) ) else: break logging.info(f"{i} Lucy iterations") return g def lucy_bound(p, f_hat, x_array, y_array, limit_i=50, p_ratio=0.97): warnings.filterwarnings("ignore") g = smoothing(x_array, np.ones_like(x_array) * np.max(f_hat(x_array)) / 2) chi_square_p = +np.inf i = 0 for i in range(limit_i): f = fx_r_from_gy_r_bound(g, p, x_array, y_min=min(y_array), y_max=max(y_array)) chi_square = cal_chi_square(f_hat(x_array), f(x_array)) if chi_square < chi_square_p * p_ratio: chi_square_p = chi_square g = gy_r1_from_fx_r_bound( f, f_hat, g, p, y_array, x_min=min(x_array), x_max=max(x_array) ) else: break logging.info(f"{i} Lucy iterations") return g def cal_v_eq_dist(vsini, popt, only_f=False, limit_i=50): s = stats.gaussian_kde(vsini, "silverman") f_hat = stats.gaussian_kde(np.log(vsini), "silverman") def p(x, y): return ( 1 / (np.sqrt(2 * np.pi) * log_err_func(x, *popt)) * np.exp(-1 / 2 * ((x - y) / log_err_func(x, *popt)) ** 2) ) x = np.arange(2, 7, 0.05) g = lucy(p, f_hat, x, x, limit_i=limit_i) x = np.arange(10, 600, 5) f_hat = smoothing(x, g(np.log(x)) / x) x_output = np.arange(10, 600, 0.5) def p(x, y): if y > x: return x / np.sqrt(y ** 2 - x ** 2) / y else: return 0 if not only_f: g = lucy_bound(p, f_hat, x, x, limit_i=limit_i) df = pd.DataFrame( {"x": x_output, "s": s(x_output), "f": f_hat(x_output), "g": g(x_output)} ) else: df = pd.DataFrame({"x": x_output, "s": s(x_output), "f": f_hat(x_output)}) return df def cal_omega_dist(omega, popt, only_f=False, limit_i=50): s = stats.gaussian_kde(omega, "silverman") def p(x, y): return ( 1 / (np.sqrt(2 * np.pi) * np.polyval(popt, x)) * np.exp(-1 / 2 * ((x - y) / np.polyval(popt, x)) ** 2) ) x = np.arange(0, 1.1, 0.02) # g = lucy(p, s, x, x, limit_i=limit_i) g = s f = g def p(x, y): if y > x: return x / np.sqrt(y ** 2 - x ** 2) / y else: return 0 if not only_f: g = lucy_bound(p, g, x, x, limit_i=limit_i) df = pd.DataFrame({"x": x, "s": s(x), "f": f(x), "g": g(x)}) else: df = pd.DataFrame({"x": x, "s": s(x), "f": f(x)}) return df if __name__ == "__main__": pass
[ "numpy.zeros_like", "numpy.sum", "scipy.interpolate.InterpolatedUnivariateSpline", "numpy.log", "warnings.filterwarnings", "numpy.ones_like", "numpy.polyval", "scipy.stats.gaussian_kde", "numpy.isfinite", "logging.info", "numpy.arange", "numpy.sqrt" ]
[((259, 309), 'numpy.sum', 'np.sum', (['((f_hat_array - f_array) ** 2 / f_hat_array)'], {}), '((f_hat_array - f_array) ** 2 / f_hat_array)\n', (265, 309), True, 'import numpy as np\n'), ((417, 451), 'scipy.interpolate.InterpolatedUnivariateSpline', 'InterpolatedUnivariateSpline', (['x', 'y'], {}), '(x, y)\n', (445, 451), False, 'from scipy.interpolate import InterpolatedUnivariateSpline\n'), ((522, 551), 'numpy.zeros_like', 'np.zeros_like', (['x'], {'dtype': 'float'}), '(x, dtype=float)\n', (535, 551), True, 'import numpy as np\n'), ((777, 806), 'numpy.zeros_like', 'np.zeros_like', (['y'], {'dtype': 'float'}), '(y, dtype=float)\n', (790, 806), True, 'import numpy as np\n'), ((1127, 1156), 'numpy.zeros_like', 'np.zeros_like', (['x'], {'dtype': 'float'}), '(x, dtype=float)\n', (1140, 1156), True, 'import numpy as np\n'), ((1433, 1462), 'numpy.zeros_like', 'np.zeros_like', (['y'], {'dtype': 'float'}), '(y, dtype=float)\n', (1446, 1462), True, 'import numpy as np\n'), ((1876, 1909), 'warnings.filterwarnings', 'warnings.filterwarnings', (['"""ignore"""'], {}), "('ignore')\n", (1899, 1909), False, 'import warnings\n'), ((2450, 2486), 'logging.info', 'logging.info', (['f"""{i} Lucy iterations"""'], {}), "(f'{i} Lucy iterations')\n", (2462, 2486), False, 'import logging\n'), ((2576, 2609), 'warnings.filterwarnings', 'warnings.filterwarnings', (['"""ignore"""'], {}), "('ignore')\n", (2599, 2609), False, 'import warnings\n'), ((3162, 3198), 'logging.info', 'logging.info', (['f"""{i} Lucy iterations"""'], {}), "(f'{i} Lucy iterations')\n", (3174, 3198), False, 'import logging\n'), ((3280, 3318), 'scipy.stats.gaussian_kde', 'stats.gaussian_kde', (['vsini', '"""silverman"""'], {}), "(vsini, 'silverman')\n", (3298, 3318), False, 'from scipy import integrate, stats\n'), ((3578, 3599), 'numpy.arange', 'np.arange', (['(2)', '(7)', '(0.05)'], {}), '(2, 7, 0.05)\n', (3587, 3599), True, 'import numpy as np\n'), ((3655, 3676), 'numpy.arange', 'np.arange', (['(10)', '(600)', '(5)'], {}), '(10, 600, 5)\n', (3664, 3676), True, 'import numpy as np\n'), ((3735, 3758), 'numpy.arange', 'np.arange', (['(10)', '(600)', '(0.5)'], {}), '(10, 600, 0.5)\n', (3744, 3758), True, 'import numpy as np\n'), ((4257, 4295), 'scipy.stats.gaussian_kde', 'stats.gaussian_kde', (['omega', '"""silverman"""'], {}), "(omega, 'silverman')\n", (4275, 4295), False, 'from scipy import integrate, stats\n'), ((4489, 4512), 'numpy.arange', 'np.arange', (['(0)', '(1.1)', '(0.02)'], {}), '(0, 1.1, 0.02)\n', (4498, 4512), True, 'import numpy as np\n'), ((365, 379), 'numpy.isfinite', 'np.isfinite', (['y'], {}), '(y)\n', (376, 379), True, 'import numpy as np\n'), ((391, 405), 'numpy.isfinite', 'np.isfinite', (['y'], {}), '(y)\n', (402, 405), True, 'import numpy as np\n'), ((3351, 3364), 'numpy.log', 'np.log', (['vsini'], {}), '(vsini)\n', (3357, 3364), True, 'import numpy as np\n'), ((1937, 1958), 'numpy.ones_like', 'np.ones_like', (['x_array'], {}), '(x_array)\n', (1949, 1958), True, 'import numpy as np\n'), ((2637, 2658), 'numpy.ones_like', 'np.ones_like', (['x_array'], {}), '(x_array)\n', (2649, 2658), True, 'import numpy as np\n'), ((3704, 3713), 'numpy.log', 'np.log', (['x'], {}), '(x)\n', (3710, 3713), True, 'import numpy as np\n'), ((3443, 3461), 'numpy.sqrt', 'np.sqrt', (['(2 * np.pi)'], {}), '(2 * np.pi)\n', (3450, 3461), True, 'import numpy as np\n'), ((3818, 3842), 'numpy.sqrt', 'np.sqrt', (['(y ** 2 - x ** 2)'], {}), '(y ** 2 - x ** 2)\n', (3825, 3842), True, 'import numpy as np\n'), ((4360, 4378), 'numpy.sqrt', 'np.sqrt', (['(2 * np.pi)'], {}), '(2 * np.pi)\n', (4367, 4378), True, 'import numpy as np\n'), ((4381, 4400), 'numpy.polyval', 'np.polyval', (['popt', 'x'], {}), '(popt, x)\n', (4391, 4400), True, 'import numpy as np\n'), ((4636, 4660), 'numpy.sqrt', 'np.sqrt', (['(y ** 2 - x ** 2)'], {}), '(y ** 2 - x ** 2)\n', (4643, 4660), True, 'import numpy as np\n'), ((4443, 4462), 'numpy.polyval', 'np.polyval', (['popt', 'x'], {}), '(popt, x)\n', (4453, 4462), True, 'import numpy as np\n')]
#!/usr/bin/env python """ A simple python script for parsing CASTEP (http://www.castep.org/) output files especially for ELNES calculations. This includes some functions for reading .cell, .castep, .bands, and .eels_mat files, calculating excitation energy, and forming core-loss spectra with Gaussian smearing. Copyright (c) 2022 kiyou, nmdl-mizo This software is released under the MIT License, see LICENSE. Note ----- This script is tested on input and output files of CASTEP version 8 and may not be incompatible to other versions. In all papers using the CASTEP code, you should cite: "First principles methods using CASTEP", Zeitschrift fuer Kristallographie 220(5-6) pp. 567-570 (2005) <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME> If you use get_energies() for calculating excitation energy, please consider to cite: <NAME>.; <NAME>.; <NAME>.; <NAME>. "First-Principles Calculation of Spectral Features, Chemical Shift and Absolute Threshold of ELNES and XANES Using a Plane Wave Pseudopotential Method." \ J. Phys. Condens. Matter 2009, 21 (10), 104204. """ import os import re import struct import numpy as np import importlib.metadata __version__ = importlib.metadata.version('castep_elnes_parser') def split_castep(filename): """ Split .castep file into each calculation Running CASTEP several times yields a single .castep file with concatenated output. This function splits the outputs into a list of each calculation run. Parameters -------- filename : str path to the .castep file Returns -------- run_list : list list of lines of castep output for each run """ with open(filename, "rt") as f: lines = f.readlines() castep_header = [ ' +-------------------------------------------------+\n', ' | |\n', ' | CCC AA SSS TTTTT EEEEE PPPP |\n', ' | C A A S T E P P |\n', ' | C AAAA SS T EEE PPPP |\n', ' | C A A S T E P |\n', ' | CCC A A SSS T EEEEE P |\n', ' | |\n', ' +-------------------------------------------------+\n' ] header_position_list = list() for l in range(len(lines) - 9): if lines[l: l + 9] == castep_header: header_position_list.append(l) header_position_list.append(-1) run_list = [lines[l_s:l_e] for l_s, l_e in zip(header_position_list[:-1], header_position_list[1:])] return run_list def get_final_energy_castep(lines): """ get the final energy of the system from .castep output Parameters -------- lines : list of str Castep output for a calculation run. Can be obtained by split_castep Returns -------- final_energy: float final energy in eV """ for line in lines: if "Final energy" in line: final_energy = float(line.split()[-2]) break else: raise RuntimeError("Could not find Final energy") return final_energy def get_ae_energy_castep(lines, element="C", suffix=":ex"): """ get the atomic energy of the all-electron (ae) calculation from .castep output Parameters -------- lines : list of str Castep output for a calculation run. Can be obtained by split_castep element : str, default "C" element name. e.g. "C" suffix : str, default ":ex" suffix for the site name e.g. ":ex" Returns -------- ae_energy: float ae energy in eV """ re_ac = re.compile(f"Atomic calculation performed for {element}{suffix}") re_ae = re.compile("Converged in \d+ iterations to an ae energy of ([\d\.\-]+) eV") for i, line in enumerate(lines): if re_ac.search(line) is not None: break else: raise RuntimeError(f"Could not find atomic calculation for {element}{suffix}") ae_energy = float(re_ae.search(lines[i + 2]).group(1)) return ae_energy def get_pa_energy_castep(lines, element="C", suffix=":ex"): """ get the atomic energy of the pseudo atomic (pa) calculation from .castep output Parameters -------- lines : list of str Castep output for a calculation run. Can be obtained by split_castep element : str, default "C" element name. e.g. "C" suffix : str, default ":ex" suffix for the site name e.g. ":ex" Returns -------- pa_energy: float pseudo atomic energy in eV """ re_pac = re.compile(f"Pseudo atomic calculation performed for {element}{suffix}") re_pa = re.compile("Converged in \d+ iterations to a total energy of ([\d\.\-]+) eV") for i, line in enumerate(lines): if re_pac.search(line) is not None: break else: raise RuntimeError(f"Could not find pseudo atomic calculation for {element}{suffix}") pa_energy = float(re_pa.search(lines[i + 2]).group(1)) return pa_energy def get_energies(filename_gs, filename_ex, element="C", suffix=":ex", gs_split=-1, ex_split=-1): """ get energies from .castep outputs Parameters -------- filename_gs : str path to the .castep file of the ground state filename_ex : str path to the .castep file of the excited state element : str, default "C" element name. e.g. "C" suffix : str, default ":ex" suffix for the site name e.g. ":ex" gs_split : int, default -1 index of the split used for extracting energies from ground state calculation. -1 to latest. ex_split : int, default -1 index of the split used for extracting energies from excited state calculation. -1 to latest. Returns -------- energy_dict: dict a dictionary wiht str keys of labels and flot values of energies in eV gs_final: ground state final_energy, ex_final: excited state final energy, gs_ae: ground state atomic energy in the all-electron calculation, ex_ae: excited state atomic energy in the all-electron calculation, gs_pa: ground state atomic energy in the pseudo-atomic calculation, ex_pa: excited state atomic energy in the pseudo-atomic calculation, excitation_energy: excitation energy, Note ------- The calculation of excitation energy is based on the following paper: <NAME>.; <NAME>.; <NAME>.; <NAME>. \ "First-Principles Calculation of Spectral Features, Chemical Shift and Absolute Threshold of ELNES and XANES Using a Plane Wave Pseudopotential Method." \ J. Phys. Condens. Matter 2009, 21 (10), 104204. """ lines_gs = split_castep(filename_gs)[gs_split] lines_ex = split_castep(filename_ex)[ex_split] energy_dict = { "gs_final": get_final_energy_castep(lines_gs), "ex_final": get_final_energy_castep(lines_ex), "gs_ae": get_ae_energy_castep(lines_gs, element, suffix), "ex_ae": get_ae_energy_castep(lines_ex, element, suffix), "gs_pa": get_pa_energy_castep(lines_gs, element, suffix), "ex_pa": get_pa_energy_castep(lines_ex, element, suffix), } excitation_energy = (energy_dict["ex_final"] - energy_dict["gs_final"]) + ((energy_dict["ex_ae"] - energy_dict["ex_pa"]) - (energy_dict["gs_ae"] - energy_dict["gs_pa"])) energy_dict["excitation_energy"] = excitation_energy return energy_dict def get_coords_cell(filename): """ extract species and coordinates from .cell file Parameters -------- filename : str path to the .cell file Returns -------- coords_list : list a list of two elements - a list of species - a numpy array of coordinations """ with open(filename, "r") as f: while not "%BLOCK POSITIONS_FRAC" in f.readline(): pass lines = list() while True: line = f.readline() if "%ENDBLOCK POSITIONS_FRAC" in line: break lines.append(line) coords_list = [line.split()[0] for line in lines], np.array([line.split()[1:] for line in lines], dtype=np.float) return coords_list def read_bin_data(f, dtype, data_byte, header_byte=4, footer_byte=4): """ read data from binary file This function reads a binary chunk from current position. Parameters -------- f : file object a file object opened in read only mode. dtype : str dtype of the binary chunk data_byte : int length of the binary chunk to read in byte header_byte : int, default 4 length of the header before the binary chunk to read in byte footer_byte : int, default 4 length of the footer after the binary chunk to read in byte Returns -------- data : int, str, float, or list a data converted by struct.unpack """ f.seek(header_byte, 1) data = struct.unpack(dtype, f.read(data_byte)) f.seek(footer_byte, 1) return data def read_eels_mat(filename): """ extract data from .eels_mat file Parameters -------- filename : str path to the .eels_mat file Returns -------- eels_mat_dict : dict a dictionary of the extracted data - tot_core_projectors - max_eigenvalues - sum_num_kpoints - num_spins - core_orbital_species - core_orbital_ion - core_orbital_n - core_orbital_lm - transition_matrix """ params = [ "tot_core_projectors", "max_eigenvalues", "sum_num_kpoints", "num_spins", ] co = [ "core_orbital_species", "core_orbital_ion", "core_orbital_n", "core_orbital_lm", ] with open(filename, "rb") as f: param_chunk = {p: read_bin_data(f, ">i", 4)[0] for p in params} n_proj = param_chunk["tot_core_projectors"] if n_proj == 1: dt_proj = ">i" else: dt_proj = f">{n_proj}i" co_chunk = {p: read_bin_data(f, dt_proj, n_proj * 4) for p in co} mat = np.array([read_bin_data(f, '>6d', 3 * 8 * 2) for i in range(np.prod([param_chunk[p] for p in params]))]) mat.dtype = complex eels_mat_dict = dict() for p in params: eels_mat_dict[p] = param_chunk[p] for p in co: eels_mat_dict[p] = co_chunk[p] eels_mat_dict["transition_matrix"] = mat.reshape( eels_mat_dict["sum_num_kpoints"], eels_mat_dict["num_spins"], eels_mat_dict["tot_core_projectors"], eels_mat_dict["max_eigenvalues"], 3, ) return eels_mat_dict def read_bands(filename, output_eV=True): """ extract data from .bands file Parameters -------- filename : str path to the .bands file output_eV : bool, default True whether output energy in eV (True) or hartree (False) Returns -------- bands_dict : dict a dictionary of the extracted data """ with open(filename, "rt") as f: # start reading header nkpnt = int(f.readline().split()[-1]) nspin = int(f.readline().split()[-1]) nelectrons = list(map(float, f.readline().split()[-nspin:])) nbands = list(map(int, f.readline().split()[-nspin:])) efermi = list(map(float, f.readline().split()[-nspin:])) f.readline() a = list(map(float, f.readline().split())) b = list(map(float, f.readline().split())) c = list(map(float, f.readline().split())) # finish reading header nk = list() kpts = list() wk = list() spin = list() eigenvalues = list() for _ in range(nkpnt): line = f.readline().split() nk.append(int(line[1])) kpts.append(list(map(float, line[2:5]))) wk.append(float(line[5])) spin_k = list() eigenvalues_k = list() for nb in nbands: spin_k.append(int(f.readline().split()[-1])) eigenvalues_k.append(list(map(float, [f.readline() for _ in range(nb)]))) spin.append(spin_k) eigenvalues.append(eigenvalues_k) bands_dict = { "num_kponts": nkpnt, "num_spins": nspin, "num_electrons": nelectrons, "num_eigenvalues": nbands, "efermi": efermi, "lattice_vectors": np.array([a, b, c]), "nk": nk, "kpoint": kpts, "kpoint_weights": wk, "spin": spin, "eigenvalues": np.array(eigenvalues) } if output_eV: hart2eV = 27.211396132 bands_dict["efermi"] = np.array(bands_dict["efermi"]) * hart2eV bands_dict["eigenvalues"] = np.array(bands_dict["eigenvalues"]) * hart2eV return bands_dict def get_spectrum(calc_dir=".", seed_name="case_elnes", output_eV=True, atomic_unit=False): """ get primitive spectral data from a .bands file and a .eels_mat file Parameters -------- calc_dir : str, default "." path to the directory containing .bands and .eels_mat seed_name : str, default "case_elnes" seed name of the calculation output_eV : bool, default True whether output energy in eV (True) or hartree (False) atomic_unit : bool, default False whether output dynamical structure factor in the unit of Bohr radius^2 (True) or angstrom^2 (False). Returns -------- spectrum_dict : dict a dictionary of the spectral data """ eels_mat_dict = read_eels_mat(os.path.join(calc_dir, f"{seed_name}.eels_mat")) en = np.square(np.abs(eels_mat_dict["transition_matrix"])) if not atomic_unit: en *= 0.529177210903**2 # Bohr radius^-2 to Angstrom^-2 bands_dict = read_bands(os.path.join(calc_dir, f"{seed_name}.bands"), output_eV) spectrum_dict = { "eigenvalues": bands_dict["eigenvalues"], "efermi": bands_dict["efermi"], "num_electrons": bands_dict["num_electrons"], "kpoint_weights": bands_dict["kpoint_weights"], "num_spins": bands_dict["num_spins"], "tot_core_projectors": eels_mat_dict["tot_core_projectors"], "dsf":en } return spectrum_dict def gaussian(x, c, w, s): """ gaussian function for smearing Parameters -------- x : list or numpy array 1d list of energies c : float center position (=mu) w : float height scaling factor, weights s : float standard deviation of gaussian smearing (=sigma) Returns -------- numpy array numpy array of gaussian distribution """ return w / (np.sqrt(2. * np.pi) * s) * np.exp(-((x - c) / s)**2 / 2.) def get_smeared_spectrum(energies, sigma=0.3, calc_dir=".", seed_name="case_elnes", e_origin="eigen_value", output_eV=True, atomic_unit=False): """ get gaussian smeared spectra from a .bands file and a .eels_mat file Parameters -------- energies : list or numpy array 1d list of energies sigma : float, default 0.3 standard deviation of gaussian smearing calc_dir : str, default "." path to the directory containing .bands and .eels_mat seed_name : str, default "case_elnes" seed name of the calculation e_origin : str, default "eigen_value" set energy origin output_eV : bool, default True whether output energy in eV (True) or hartree (False) atomic_unit : bool, default False whether output dynamical structure factor in the unit of Bohr radius^2 (True) or angstrom^2 (False). Returns -------- spectrum : numpy array numpy array of smeared spectra Examples -------- >>> !ls . case_elnes.bands case_elnes.eels_mat >>> energies = np.arange(-4.999, 30.002, 0.001) # make an array for energies >>> sp = get_smeared_spectrum(energies, 0.3) # parse and make spectra >>> fig, ax = plt.subplots(1) >>> ax.set_xlabel("Energy (eV)") >>> ax.set_ylabel("Intensity (arb. u.)") >>> ax.plot(energies, sp[0, 0], label="x") # plot a spectrum for x component of the 1st core projection >>> ax.plot(energies, sp[0, 1], label="y") # plot a spectrum for y component of the 1st core projection >>> ax.plot(energies, sp[0, 2], label="z") # plot a spectrum for z component of the 1st core projection >>> ax.plot(energies, np.mean(sp[0], axis=0), label="total") # plot a total spectrum of the 1st core projection """ spectrum = get_spectrum(calc_dir, seed_name, output_eV, atomic_unit) if e_origin == "eigen_value": e_origin_value = np.min( [ [ ev[int(ne // (2 / spectrum["num_spins"]))] for ev, ne in zip(ev_k, spectrum["num_electrons"]) ] for ev_k in spectrum["eigenvalues"] ] ) elif e_origin == "efermi": e_origin_value = spectrum["efermi"] sp = [ [ [ [ kw * np.sum( [ gaussian(energies, en, w, sigma) for en, w in zip(spectrum["eigenvalues"][i_kp, i_spin] - e_origin_value, spectrum["dsf"][i_kp, i_spin, i_proj, :, i_ra]) if en >= 0. ], axis=0 ) for i_kp, kw in enumerate(spectrum["kpoint_weights"]) ] for i_spin in range(spectrum["num_spins"]) ] for i_ra in range(3) ] for i_proj in range(spectrum["tot_core_projectors"]) ] sp = np.sum(np.array(sp), axis=(2, 3)) sp *= 2. / spectrum["num_spins"] # consider spin multiplicity return sp
[ "numpy.abs", "numpy.array", "numpy.exp", "numpy.sqrt", "os.path.join", "numpy.prod", "re.compile" ]
[((3729, 3794), 're.compile', 're.compile', (['f"""Atomic calculation performed for {element}{suffix}"""'], {}), "(f'Atomic calculation performed for {element}{suffix}')\n", (3739, 3794), False, 'import re\n'), ((3807, 3886), 're.compile', 're.compile', (['"""Converged in \\\\d+ iterations to an ae energy of ([\\\\d\\\\.\\\\-]+) eV"""'], {}), "('Converged in \\\\d+ iterations to an ae energy of ([\\\\d\\\\.\\\\-]+) eV')\n", (3817, 3886), False, 'import re\n'), ((4691, 4763), 're.compile', 're.compile', (['f"""Pseudo atomic calculation performed for {element}{suffix}"""'], {}), "(f'Pseudo atomic calculation performed for {element}{suffix}')\n", (4701, 4763), False, 'import re\n'), ((4776, 4862), 're.compile', 're.compile', (['"""Converged in \\\\d+ iterations to a total energy of ([\\\\d\\\\.\\\\-]+) eV"""'], {}), "(\n 'Converged in \\\\d+ iterations to a total energy of ([\\\\d\\\\.\\\\-]+) eV')\n", (4786, 4862), False, 'import re\n'), ((12561, 12580), 'numpy.array', 'np.array', (['[a, b, c]'], {}), '([a, b, c])\n', (12569, 12580), True, 'import numpy as np\n'), ((12699, 12720), 'numpy.array', 'np.array', (['eigenvalues'], {}), '(eigenvalues)\n', (12707, 12720), True, 'import numpy as np\n'), ((13706, 13753), 'os.path.join', 'os.path.join', (['calc_dir', 'f"""{seed_name}.eels_mat"""'], {}), "(calc_dir, f'{seed_name}.eels_mat')\n", (13718, 13753), False, 'import os\n'), ((13774, 13816), 'numpy.abs', 'np.abs', (["eels_mat_dict['transition_matrix']"], {}), "(eels_mat_dict['transition_matrix'])\n", (13780, 13816), True, 'import numpy as np\n'), ((13934, 13978), 'os.path.join', 'os.path.join', (['calc_dir', 'f"""{seed_name}.bands"""'], {}), "(calc_dir, f'{seed_name}.bands')\n", (13946, 13978), False, 'import os\n'), ((14838, 14871), 'numpy.exp', 'np.exp', (['(-((x - c) / s) ** 2 / 2.0)'], {}), '(-((x - c) / s) ** 2 / 2.0)\n', (14844, 14871), True, 'import numpy as np\n'), ((17856, 17868), 'numpy.array', 'np.array', (['sp'], {}), '(sp)\n', (17864, 17868), True, 'import numpy as np\n'), ((12807, 12837), 'numpy.array', 'np.array', (["bands_dict['efermi']"], {}), "(bands_dict['efermi'])\n", (12815, 12837), True, 'import numpy as np\n'), ((12884, 12919), 'numpy.array', 'np.array', (["bands_dict['eigenvalues']"], {}), "(bands_dict['eigenvalues'])\n", (12892, 12919), True, 'import numpy as np\n'), ((14811, 14831), 'numpy.sqrt', 'np.sqrt', (['(2.0 * np.pi)'], {}), '(2.0 * np.pi)\n', (14818, 14831), True, 'import numpy as np\n'), ((10326, 10367), 'numpy.prod', 'np.prod', (['[param_chunk[p] for p in params]'], {}), '([param_chunk[p] for p in params])\n', (10333, 10367), True, 'import numpy as np\n')]
# Copyright The PyTorch Lightning team. # # 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 os from pathlib import Path import numpy as np import torch from PIL import Image from torchvision import transforms as T from flash.data.data_utils import labels_from_categorical_csv from flash.vision import ImageClassificationData def _dummy_image_loader(filepath): return torch.rand(3, 64, 64) def _rand_image(): return Image.fromarray(np.random.randint(0, 255, (64, 64, 3), dtype="uint8")) def test_from_filepaths(tmpdir): img_data = ImageClassificationData.from_filepaths( train_filepaths=["a", "b"], train_labels=[0, 1], train_transform=lambda x: x, # make sure transform works loader=_dummy_image_loader, batch_size=1, num_workers=0, ) data = next(iter(img_data.train_dataloader())) imgs, labels = data assert imgs.shape == (1, 3, 64, 64) assert labels.shape == (1, ) assert img_data.val_dataloader() is None assert img_data.test_dataloader() is None img_data = ImageClassificationData.from_filepaths( train_filepaths=["a", "b"], train_labels=[0, 1], train_transform=None, valid_filepaths=["c", "d"], valid_labels=[0, 1], valid_transform=None, test_filepaths=["e", "f"], test_labels=[0, 1], loader=_dummy_image_loader, batch_size=1, num_workers=0, ) data = next(iter(img_data.val_dataloader())) imgs, labels = data assert imgs.shape == (1, 3, 64, 64) assert labels.shape == (1, ) data = next(iter(img_data.test_dataloader())) imgs, labels = data assert imgs.shape == (1, 3, 64, 64) assert labels.shape == (1, ) def test_categorical_csv_labels(tmpdir): train_dir = Path(tmpdir / "some_dataset") train_dir.mkdir() (train_dir / "train").mkdir() _rand_image().save(train_dir / "train" / "train_1.png") _rand_image().save(train_dir / "train" / "train_2.png") (train_dir / "valid").mkdir() _rand_image().save(train_dir / "valid" / "valid_1.png") _rand_image().save(train_dir / "valid" / "valid_2.png") (train_dir / "test").mkdir() _rand_image().save(train_dir / "test" / "test_1.png") _rand_image().save(train_dir / "test" / "test_2.png") train_csv = os.path.join(tmpdir, 'some_dataset', 'train.csv') text_file = open(train_csv, 'w') text_file.write( 'my_id,label_a,label_b,label_c\n"train_1.png", 0, 1, 0\n"train_2.png", 0, 0, 1\n"train_2.png", 1, 0, 0\n' ) text_file.close() valid_csv = os.path.join(tmpdir, 'some_dataset', 'valid.csv') text_file = open(valid_csv, 'w') text_file.write( 'my_id,label_a,label_b,label_c\n"valid_1.png", 0, 1, 0\n"valid_2.png", 0, 0, 1\n"valid_3.png", 1, 0, 0\n' ) text_file.close() test_csv = os.path.join(tmpdir, 'some_dataset', 'test.csv') text_file = open(test_csv, 'w') text_file.write( 'my_id,label_a,label_b,label_c\n"test_1.png", 0, 1, 0\n"test_2.png", 0, 0, 1\n"test_3.png", 1, 0, 0\n' ) text_file.close() def index_col_collate_fn(x): return os.path.splitext(x)[0] train_labels = labels_from_categorical_csv( train_csv, 'my_id', feature_cols=['label_a', 'label_b', 'label_c'], index_col_collate_fn=index_col_collate_fn) valid_labels = labels_from_categorical_csv( valid_csv, 'my_id', feature_cols=['label_a', 'label_b', 'label_c'], index_col_collate_fn=index_col_collate_fn) test_labels = labels_from_categorical_csv( test_csv, 'my_id', feature_cols=['label_a', 'label_b', 'label_c'], index_col_collate_fn=index_col_collate_fn) data = ImageClassificationData.from_filepaths( batch_size=2, train_filepaths=os.path.join(tmpdir, 'some_dataset', 'train'), train_labels=train_labels, valid_filepaths=os.path.join(tmpdir, 'some_dataset', 'valid'), valid_labels=valid_labels, test_filepaths=os.path.join(tmpdir, 'some_dataset', 'test'), test_labels=test_labels, ) for (x, y) in data.train_dataloader(): assert len(x) == 2 for (x, y) in data.val_dataloader(): assert len(x) == 2 for (x, y) in data.test_dataloader(): assert len(x) == 2 data = ImageClassificationData.from_filepaths( batch_size=2, train_filepaths=os.path.join(tmpdir, 'some_dataset', 'train'), train_labels=train_labels, valid_split=0.5 ) for (x, y) in data.val_dataloader(): assert len(x) == 1 def test_from_folders(tmpdir): train_dir = Path(tmpdir / "train") train_dir.mkdir() (train_dir / "a").mkdir() _rand_image().save(train_dir / "a" / "1.png") _rand_image().save(train_dir / "a" / "2.png") (train_dir / "b").mkdir() _rand_image().save(train_dir / "b" / "1.png") _rand_image().save(train_dir / "b" / "2.png") img_data = ImageClassificationData.from_folders( train_dir, train_transform=None, loader=_dummy_image_loader, batch_size=1 ) data = next(iter(img_data.train_dataloader())) imgs, labels = data assert imgs.shape == (1, 3, 64, 64) assert labels.shape == (1, ) assert img_data.val_dataloader() is None assert img_data.test_dataloader() is None img_data = ImageClassificationData.from_folders( train_dir, train_transform=T.ToTensor(), valid_folder=train_dir, valid_transform=T.ToTensor(), test_folder=train_dir, batch_size=1, num_workers=0, ) data = next(iter(img_data.val_dataloader())) imgs, labels = data assert imgs.shape == (1, 3, 64, 64) assert labels.shape == (1, ) data = next(iter(img_data.test_dataloader())) imgs, labels = data assert imgs.shape == (1, 3, 64, 64) assert labels.shape == (1, )
[ "flash.data.data_utils.labels_from_categorical_csv", "pathlib.Path", "flash.vision.ImageClassificationData.from_folders", "numpy.random.randint", "os.path.splitext", "torch.rand", "flash.vision.ImageClassificationData.from_filepaths", "os.path.join", "torchvision.transforms.ToTensor" ]
[((876, 897), 'torch.rand', 'torch.rand', (['(3)', '(64)', '(64)'], {}), '(3, 64, 64)\n', (886, 897), False, 'import torch\n'), ((1051, 1233), 'flash.vision.ImageClassificationData.from_filepaths', 'ImageClassificationData.from_filepaths', ([], {'train_filepaths': "['a', 'b']", 'train_labels': '[0, 1]', 'train_transform': '(lambda x: x)', 'loader': '_dummy_image_loader', 'batch_size': '(1)', 'num_workers': '(0)'}), "(train_filepaths=['a', 'b'],\n train_labels=[0, 1], train_transform=lambda x: x, loader=\n _dummy_image_loader, batch_size=1, num_workers=0)\n", (1089, 1233), False, 'from flash.vision import ImageClassificationData\n'), ((1566, 1867), 'flash.vision.ImageClassificationData.from_filepaths', 'ImageClassificationData.from_filepaths', ([], {'train_filepaths': "['a', 'b']", 'train_labels': '[0, 1]', 'train_transform': 'None', 'valid_filepaths': "['c', 'd']", 'valid_labels': '[0, 1]', 'valid_transform': 'None', 'test_filepaths': "['e', 'f']", 'test_labels': '[0, 1]', 'loader': '_dummy_image_loader', 'batch_size': '(1)', 'num_workers': '(0)'}), "(train_filepaths=['a', 'b'],\n train_labels=[0, 1], train_transform=None, valid_filepaths=['c', 'd'],\n valid_labels=[0, 1], valid_transform=None, test_filepaths=['e', 'f'],\n test_labels=[0, 1], loader=_dummy_image_loader, batch_size=1, num_workers=0\n )\n", (1604, 1867), False, 'from flash.vision import ImageClassificationData\n'), ((2300, 2329), 'pathlib.Path', 'Path', (["(tmpdir / 'some_dataset')"], {}), "(tmpdir / 'some_dataset')\n", (2304, 2329), False, 'from pathlib import Path\n'), ((2829, 2878), 'os.path.join', 'os.path.join', (['tmpdir', '"""some_dataset"""', '"""train.csv"""'], {}), "(tmpdir, 'some_dataset', 'train.csv')\n", (2841, 2878), False, 'import os\n'), ((3096, 3145), 'os.path.join', 'os.path.join', (['tmpdir', '"""some_dataset"""', '"""valid.csv"""'], {}), "(tmpdir, 'some_dataset', 'valid.csv')\n", (3108, 3145), False, 'import os\n'), ((3362, 3410), 'os.path.join', 'os.path.join', (['tmpdir', '"""some_dataset"""', '"""test.csv"""'], {}), "(tmpdir, 'some_dataset', 'test.csv')\n", (3374, 3410), False, 'import os\n'), ((3699, 3841), 'flash.data.data_utils.labels_from_categorical_csv', 'labels_from_categorical_csv', (['train_csv', '"""my_id"""'], {'feature_cols': "['label_a', 'label_b', 'label_c']", 'index_col_collate_fn': 'index_col_collate_fn'}), "(train_csv, 'my_id', feature_cols=['label_a',\n 'label_b', 'label_c'], index_col_collate_fn=index_col_collate_fn)\n", (3726, 3841), False, 'from flash.data.data_utils import labels_from_categorical_csv\n'), ((3866, 4008), 'flash.data.data_utils.labels_from_categorical_csv', 'labels_from_categorical_csv', (['valid_csv', '"""my_id"""'], {'feature_cols': "['label_a', 'label_b', 'label_c']", 'index_col_collate_fn': 'index_col_collate_fn'}), "(valid_csv, 'my_id', feature_cols=['label_a',\n 'label_b', 'label_c'], index_col_collate_fn=index_col_collate_fn)\n", (3893, 4008), False, 'from flash.data.data_utils import labels_from_categorical_csv\n'), ((4032, 4173), 'flash.data.data_utils.labels_from_categorical_csv', 'labels_from_categorical_csv', (['test_csv', '"""my_id"""'], {'feature_cols': "['label_a', 'label_b', 'label_c']", 'index_col_collate_fn': 'index_col_collate_fn'}), "(test_csv, 'my_id', feature_cols=['label_a',\n 'label_b', 'label_c'], index_col_collate_fn=index_col_collate_fn)\n", (4059, 4173), False, 'from flash.data.data_utils import labels_from_categorical_csv\n'), ((5111, 5133), 'pathlib.Path', 'Path', (["(tmpdir / 'train')"], {}), "(tmpdir / 'train')\n", (5115, 5133), False, 'from pathlib import Path\n'), ((5434, 5549), 'flash.vision.ImageClassificationData.from_folders', 'ImageClassificationData.from_folders', (['train_dir'], {'train_transform': 'None', 'loader': '_dummy_image_loader', 'batch_size': '(1)'}), '(train_dir, train_transform=None,\n loader=_dummy_image_loader, batch_size=1)\n', (5470, 5549), False, 'from flash.vision import ImageClassificationData\n'), ((946, 999), 'numpy.random.randint', 'np.random.randint', (['(0)', '(255)', '(64, 64, 3)'], {'dtype': '"""uint8"""'}), "(0, 255, (64, 64, 3), dtype='uint8')\n", (963, 999), True, 'import numpy as np\n'), ((3656, 3675), 'os.path.splitext', 'os.path.splitext', (['x'], {}), '(x)\n', (3672, 3675), False, 'import os\n'), ((4277, 4322), 'os.path.join', 'os.path.join', (['tmpdir', '"""some_dataset"""', '"""train"""'], {}), "(tmpdir, 'some_dataset', 'train')\n", (4289, 4322), False, 'import os\n'), ((4383, 4428), 'os.path.join', 'os.path.join', (['tmpdir', '"""some_dataset"""', '"""valid"""'], {}), "(tmpdir, 'some_dataset', 'valid')\n", (4395, 4428), False, 'import os\n'), ((4488, 4532), 'os.path.join', 'os.path.join', (['tmpdir', '"""some_dataset"""', '"""test"""'], {}), "(tmpdir, 'some_dataset', 'test')\n", (4500, 4532), False, 'import os\n'), ((4881, 4926), 'os.path.join', 'os.path.join', (['tmpdir', '"""some_dataset"""', '"""train"""'], {}), "(tmpdir, 'some_dataset', 'train')\n", (4893, 4926), False, 'import os\n'), ((5897, 5909), 'torchvision.transforms.ToTensor', 'T.ToTensor', ([], {}), '()\n', (5907, 5909), True, 'from torchvision import transforms as T\n'), ((5967, 5979), 'torchvision.transforms.ToTensor', 'T.ToTensor', ([], {}), '()\n', (5977, 5979), True, 'from torchvision import transforms as T\n')]
# -*- coding: utf8 -*- # # Module ELEMENT # # Part of Nutils: open source numerical utilities for Python. Jointly developed # by HvZ Computational Engineering, TU/e Multiscale Engineering Fluid Dynamics, # and others. More info at http://nutils.org <<EMAIL>>. (c) 2014 """ The transform module. """ from __future__ import print_function, division from . import cache, numeric, core import numpy class TransformChain( tuple ): __slots__ = () def slicefrom( self, i ): return TransformChain( self[i:] ) def sliceto( self, j ): return TransformChain( self[:j] ) def fromtrans( self, trans ): # assuming self and trans both canonical mytrans = self.promote( trans.fromdims ) assert mytrans[:len(trans)] == trans return mytrans[len(trans):] @property def todims( self ): return self[0].todims @property def fromdims( self ): return self[-1].fromdims @property def isflipped( self ): return sum( trans.isflipped for trans in self ) % 2 == 1 @property def orientation( self ): return -1 if self.isflipped else +1 def lookup( self, transforms ): # to be replaced by bisection soon headtrans = self while headtrans: if headtrans in transforms: return headtrans headtrans = headtrans.sliceto(-1) return None def split( self, ndims, after=True ): # split before/after the first occurrence of .fromdims==ndims. For # after=True (default) the base part represents the coordinate system for # integration/gradients at the level specified. i = core.index( trans.fromdims == ndims for trans in self ) + after return self.sliceto(i), self.slicefrom(i) def __lshift__( self, other ): # self << other assert isinstance( other, TransformChain ) if not self: return other if not other: return self assert self.fromdims == other.todims return TransformChain( self + other ) def __rshift__( self, other ): # self >> other assert isinstance( other, TransformChain ) return other << self @property def flipped( self ): assert self.todims == self.fromdims+1 return TransformChain( trans.flipped if trans.todims == trans.fromdims+1 else trans for trans in self ) @property def det( self ): det = 1 for trans in self: det *= trans.det return det @property def ext( self ): ext = numeric.ext( self.linear ) return ext if not self.isflipped else -ext @property def offset( self ): offset = self[-1].offset for trans in self[-2::-1]: offset = trans.apply( offset ) return offset @property def linear( self ): linear = numpy.array( 1. ) for trans in self: linear = numpy.dot( linear, trans.linear ) if linear.ndim and trans.linear.ndim \ else linear * trans.linear return linear @property def invlinear( self ): invlinear = numpy.array( 1. ) for trans in self: invlinear = numpy.dot( trans.invlinear, invlinear ) if invlinear.ndim and trans.linear.ndim \ else trans.invlinear * invlinear return invlinear def apply( self, points ): for trans in reversed(self): points = trans.apply( points ) return points def solve( self, points ): return numeric.solve_exact( self.linear, (points - self.offset).T ).T def __str__( self ): return ' << '.join( str(trans) for trans in self ) if self else '=' def __repr__( self ): return '{}( {} )'.format( self.__class__.__name__, self ) @property def flat( self ): return self if len(self) == 1 \ else affine( self.linear, self.offset, isflipped=self.isflipped ) @property def canonical( self ): # Keep at lowest ndims possible. The reason is that in this form we can do # lookups of embedded elements. items = list( self ) for i in range(len(items)-1)[::-1]: trans1, trans2 = items[i:i+2] if mayswap( trans1, trans2 ): trans12 = TransformChain(( trans1, trans2 )).flat try: newlinear, newoffset = numeric.solve_exact( trans2.linear, trans12.linear, trans12.offset - trans2.offset ) except numpy.linalg.LinAlgError: pass else: trans21 = TransformChain( (trans2,) + affine( newlinear, newoffset ) ) assert trans21.flat == trans12 items[i:i+2] = trans21 return CanonicalTransformChain( items ) def promote( self, ndims ): raise Exception( 'promotion only possible from canonical form' ) class CanonicalTransformChain( TransformChain ): def slicefrom( self, i ): return CanonicalTransformChain( TransformChain.slicefrom( self, i ) ) def sliceto( self, j ): return CanonicalTransformChain( TransformChain.sliceto( self, j ) ) def __lshift__( self, other ): # self << other joint = TransformChain.__lshift__( self, other ) if self and other and isinstance( other, CanonicalTransformChain ) and not mayswap( self[-1], other[0] ): joint = CanonicalTransformChain( joint ) return joint @property def flipped( self ): return CanonicalTransformChain( TransformChain.flipped.fget( self ) ) @property def canonical( self ): return self def promote( self, ndims ): if ndims == self.fromdims: return self index = core.index( trans.fromdims == self.fromdims for trans in self ) uptrans = self[index] if index == len(self)-1 or not mayswap( self[index+1], uptrans ): A = self.sliceto(index) B = self.slicefrom(index) else: body = list( self[:index] ) for i in range( index+1, len(self) ): scale = self[i] if not mayswap( scale, uptrans ): break newscale = Scale( scale.linear, uptrans.apply(scale.offset) - scale.linear * uptrans.offset ) body.append( newscale ) else: i = len(self)+1 assert equivalent( body[index:]+[uptrans], self[index:i] ) A = CanonicalTransformChain( body ) B = CanonicalTransformChain( (uptrans,) + self[i:] ) return A.promote(ndims) << B mayswap = lambda trans1, trans2: isinstance( trans1, Scale ) and trans1.linear == .5 and trans2.todims == trans2.fromdims + 1 and trans2.fromdims > 0 ## TRANSFORM ITEMS class TransformItem( cache.Immutable ): def __init__( self, todims, fromdims ): self.todims = todims self.fromdims = fromdims __lt__ = lambda self, other: id(self) < id(other) __gt__ = lambda self, other: id(self) > id(other) __le__ = lambda self, other: id(self) <= id(other) __ge__ = lambda self, other: id(self) >= id(other) def __repr__( self ): return '{}( {} )'.format( self.__class__.__name__, self ) class Shift( TransformItem ): def __init__( self, offset ): self.linear = self.invlinear = self.det = numpy.array(1.) self.offset = offset self.isflipped = False assert offset.ndim == 1 TransformItem.__init__( self, offset.shape[0], offset.shape[0] ) def apply( self, points ): return points + self.offset def __str__( self ): return '{}+x'.format( numeric.fstr(self.offset) ) class Scale( TransformItem ): def __init__( self, linear, offset ): assert linear.ndim == 0 and offset.ndim == 1 self.linear = linear self.offset = offset self.isflipped = linear < 0 and len(offset)%2 == 1 TransformItem.__init__( self, offset.shape[0], offset.shape[0] ) def apply( self, points ): return self.linear * points + self.offset @property def det( self ): return self.linear**self.todims @property def invlinear( self ): return 1 / self.linear def __str__( self ): return '{}+{}*x'.format( numeric.fstr(self.offset), numeric.fstr(self.linear) ) class Matrix( TransformItem ): def __init__( self, linear, offset ): self.linear = linear self.offset = offset assert linear.ndim == 2 and offset.shape == linear.shape[:1] TransformItem.__init__( self, linear.shape[0], linear.shape[1] ) def apply( self, points ): assert points.shape[-1] == self.fromdims return numpy.dot( points, self.linear.T ) + self.offset def __str__( self ): return '{}{}{}'.format( '~' if self.isflipped else '', numeric.fstr(self.offset), ''.join( '+{}*x{}'.format( numeric.fstr(v), i ) for i, v in enumerate(self.linear.T) ) ) class Square( Matrix ): def __init__( self, linear, offset ): Matrix.__init__( self, linear, offset ) assert self.fromdims == self.todims @property def isflipped( self ): return self.det < 0 @cache.property def det( self ): return numeric.det_exact( self.linear ) @cache.property def invlinear( self ): return numpy.linalg.inv( self.linear ) class Updim( Matrix ): def __init__( self, linear, offset, isflipped ): assert isflipped in (True,False) self.isflipped = isflipped Matrix.__init__( self, linear, offset ) assert self.todims > self.fromdims @property def flipped( self ): return Updim( self.linear, self.offset, not self.isflipped ) class VertexTransform( TransformItem ): def __init__( self, fromdims ): TransformItem.__init__( self, None, fromdims ) self.isflipped = False class MapTrans( VertexTransform ): def __init__( self, coords, vertices ): self.coords = numpy.asarray(coords) assert numeric.isintarray( self.coords ) nverts, ndims = coords.shape assert len(vertices) == nverts self.vertices = tuple(vertices) VertexTransform.__init__( self, ndims ) def apply( self, coords ): assert coords.ndim == 2 coords = numpy.asarray( coords ) indices = map( self.coords.tolist().index, coords.tolist() ) return tuple( self.vertices[n] for n in indices ) def __str__( self ): return ','.join( str(v) for v in self.vertices ) class RootTrans( VertexTransform ): def __init__( self, name, shape ): VertexTransform.__init__( self, len(shape) ) self.I, = numpy.where( shape ) self.w = numpy.take( shape, self.I ) self.name = name def apply( self, coords ): coords = numpy.asarray(coords) assert coords.ndim == 2 if self.I.size: coords = coords.copy() coords[:,self.I] %= self.w return tuple( self.name + str(c) for c in coords.tolist() ) def __str__( self ): return repr( self.name + '[*]' ) class RootTransEdges( VertexTransform ): def __init__( self, name, shape ): VertexTransform.__init__( self, len(shape) ) self.shape = shape assert isinstance( name, numpy.ndarray ) assert name.shape == (3,)*len(shape) self.name = name.copy() def apply( self, coords ): assert coords.ndim == 2 labels = [] for coord in coords.T.frac.T: right = (coord[:,1]==1) & (coord[:,0]==self.shape) left = coord[:,0]==0 where = (1+right)-left s = self.name[tuple(where)] + '[%s]' % ','.join( str(n) if d == 1 else '%d/%d' % (n,d) for n, d in coord[where==1] ) labels.append( s ) return labels def __str__( self ): return repr( ','.join(self.name.flat)+'*' ) ## CONSTRUCTORS def affine( linear, offset, denom=1, isflipped=None ): r_offset = numpy.asarray( offset, dtype=float ) / denom r_linear = numpy.asarray( linear, dtype=float ) / denom n, = r_offset.shape if r_linear.ndim == 2: assert r_linear.shape[0] == n if r_linear.shape[1] != n: trans = Updim( r_linear, r_offset, isflipped ) elif n == 0: trans = Shift( r_offset ) elif n == 1 or r_linear[0,-1] == 0 and numpy.all( r_linear == r_linear[0,0] * numpy.eye(n) ): trans = Scale( r_linear[0,0], r_offset ) if r_linear[0,0] != 1 else Shift( r_offset ) else: trans = Square( r_linear, r_offset ) else: assert r_linear.ndim == 0 trans = Scale( r_linear, r_offset ) if r_linear != 1 else Shift( r_offset ) if isflipped is not None: assert trans.isflipped == isflipped return CanonicalTransformChain( [trans] ) def simplex( coords, isflipped=None ): coords = numpy.asarray(coords) offset = coords[0] return affine( (coords[1:]-offset).T, offset, isflipped=isflipped ) def roottrans( name, shape ): return CanonicalTransformChain(( RootTrans( name, shape ), )) def roottransedges( name, shape ): return CanonicalTransformChain(( RootTransEdges( name, shape ), )) def maptrans( coords, vertices ): return CanonicalTransformChain(( MapTrans( coords, vertices ), )) def equivalent( trans1, trans2, flipped=False ): trans1 = TransformChain( trans1 ) trans2 = TransformChain( trans2 ) if trans1 == trans2: return not flipped while trans1 and trans2 and trans1[0] == trans2[0]: trans1 = trans1.slicefrom(1) trans2 = trans2.slicefrom(1) return numpy.all( trans1.linear == trans2.linear ) and numpy.all( trans1.offset == trans2.offset ) and trans1.isflipped^trans2.isflipped == flipped ## INSTANCES identity = CanonicalTransformChain() def solve( T1, T2 ): # T1 << x == T2 assert isinstance( T1, TransformChain ) assert isinstance( T2, TransformChain ) while T1 and T2 and T1[0] == T2[0]: T1 = T1.slicefrom(1) T2 = T2.slicefrom(1) if not T1: return T2 # A1 * ( Ax * xi + bx ) + b1 == A2 * xi + b2 => A1 * Ax = A2, A1 * bx + b1 = b2 Ax, bx = numeric.solve_exact( T1.linear, T2.linear, T2.offset - T1.offset ) return affine( Ax, bx ) # vim:shiftwidth=2:softtabstop=2:expandtab:foldmethod=indent:foldnestmax=2
[ "numpy.eye", "numpy.asarray", "numpy.where", "numpy.take", "numpy.linalg.inv", "numpy.array", "numpy.dot", "numpy.all" ]
[((11918, 11939), 'numpy.asarray', 'numpy.asarray', (['coords'], {}), '(coords)\n', (11931, 11939), False, 'import numpy\n'), ((2660, 2676), 'numpy.array', 'numpy.array', (['(1.0)'], {}), '(1.0)\n', (2671, 2676), False, 'import numpy\n'), ((2898, 2914), 'numpy.array', 'numpy.array', (['(1.0)'], {}), '(1.0)\n', (2909, 2914), False, 'import numpy\n'), ((6770, 6786), 'numpy.array', 'numpy.array', (['(1.0)'], {}), '(1.0)\n', (6781, 6786), False, 'import numpy\n'), ((8627, 8656), 'numpy.linalg.inv', 'numpy.linalg.inv', (['self.linear'], {}), '(self.linear)\n', (8643, 8656), False, 'import numpy\n'), ((9238, 9259), 'numpy.asarray', 'numpy.asarray', (['coords'], {}), '(coords)\n', (9251, 9259), False, 'import numpy\n'), ((9524, 9545), 'numpy.asarray', 'numpy.asarray', (['coords'], {}), '(coords)\n', (9537, 9545), False, 'import numpy\n'), ((9882, 9900), 'numpy.where', 'numpy.where', (['shape'], {}), '(shape)\n', (9893, 9900), False, 'import numpy\n'), ((9916, 9941), 'numpy.take', 'numpy.take', (['shape', 'self.I'], {}), '(shape, self.I)\n', (9926, 9941), False, 'import numpy\n'), ((10008, 10029), 'numpy.asarray', 'numpy.asarray', (['coords'], {}), '(coords)\n', (10021, 10029), False, 'import numpy\n'), ((11077, 11111), 'numpy.asarray', 'numpy.asarray', (['offset'], {'dtype': 'float'}), '(offset, dtype=float)\n', (11090, 11111), False, 'import numpy\n'), ((11135, 11169), 'numpy.asarray', 'numpy.asarray', (['linear'], {'dtype': 'float'}), '(linear, dtype=float)\n', (11148, 11169), False, 'import numpy\n'), ((12631, 12672), 'numpy.all', 'numpy.all', (['(trans1.linear == trans2.linear)'], {}), '(trans1.linear == trans2.linear)\n', (12640, 12672), False, 'import numpy\n'), ((12679, 12720), 'numpy.all', 'numpy.all', (['(trans1.offset == trans2.offset)'], {}), '(trans1.offset == trans2.offset)\n', (12688, 12720), False, 'import numpy\n'), ((8030, 8062), 'numpy.dot', 'numpy.dot', (['points', 'self.linear.T'], {}), '(points, self.linear.T)\n', (8039, 8062), False, 'import numpy\n'), ((2716, 2747), 'numpy.dot', 'numpy.dot', (['linear', 'trans.linear'], {}), '(linear, trans.linear)\n', (2725, 2747), False, 'import numpy\n'), ((2957, 2994), 'numpy.dot', 'numpy.dot', (['trans.invlinear', 'invlinear'], {}), '(trans.invlinear, invlinear)\n', (2966, 2994), False, 'import numpy\n'), ((11476, 11488), 'numpy.eye', 'numpy.eye', (['n'], {}), '(n)\n', (11485, 11488), False, 'import numpy\n')]
#!/usr/bin/env python import argparse import numpy as np import pandas as pd from scipy import linalg from tqdm import tqdm import os import logging def get_args(): parser = argparse.ArgumentParser(description="calculate splicing scores per gene/cell") parser.add_argument("--input", help="Name of the input file from rijk_zscore") parser.add_argument("--svd_type", choices=["normgene","normdonor"], help="Method of calculating matrix before SVD") parser.add_argument("--grouping_level_2", help="column to group the data by (e.g. ontology, compartment, tissue)", default="ontology") parser.add_argument("--grouping_level_1", help="subset data by this column before checking for differences (e.g. tissue, compartment)", default="dummy") parser.add_argument("--outname_pq", help="Name of output file") parser.add_argument("--outname_tsv", help="Name of output File") parser.add_argument("--outname_log", help="Name of output File") args = parser.parse_args() return args def main(): args = get_args() logging.basicConfig( filename = args.outname_log, format='%(asctime)s %(levelname)-8s %(message)s', level=logging.INFO, datefmt='%Y-%m-%d %H:%M:%S') logging.info("Beginning calculation") logging.info("Read in parquet file") df = pd.read_parquet(args.input) ##### PERFORM SVD ZSCORE CALCULATION ##### logging.info("Perform SVD zscore calculation") letters = ["Start", "End"] if args.svd_type == "normgene": zcontrib_col = "zcontrib" elif args.svd_type == "normdonor": for let in letters: # find number of reads per donor (or acceptor) per cell df["cell_gene_pos" + let] = df["cell_gene"] + df["junc" + let].astype(str) df["n.g_pos" + let] = df.groupby("cell_gene_pos" + let)["numReads"].transform("sum") # normalize on a donor/acceptor rather than a gene basis # TRY OUT NOT SQRT-ING denominator as normalization df["zcontrib_posnorm" + let] = df["numReads"] * df["nSijk" + let] / df["n.g_pos" + let] zcontrib_col = "zcontrib_posnorm" for let in letters: # replace NANs with zeros df["zcontrib{}_rep".format(let)] = df[zcontrib_col + let].fillna(0) # create label for each junction + donor/acceptor df["str_junc" + let] = df["junc" + let].astype(int).astype(str) + "_" + let df["cell_gene_pos" + let] = df["cell"] + df["gene"] + df["junc" + let].astype(str) # get sum of zcontribs for the given cell and splice site df["summed_zcontrib" + let] = df.groupby("cell_gene_pos" + let)["zcontrib{}_rep".format(let)].transform('sum') k = 3 # number of components to include loads = {"f{}".format(i) : {} for i in range(k)} zs = {"svd_z{}".format(i) : {} for i in range(k)} logging.info("Iterate over each gene") for gene, gene_df in tqdm(df.groupby("gene")): # get zcontrib matrix gene_mats = [] for let in letters: gene_mat = gene_df.drop_duplicates("cell_gene_pos" + let).pivot_table(index="cell_gene",columns="str_junc{}".format(let),values="summed_zcontrib" + let,fill_value=0) gene_mats.append(gene_mat) gene_mat = gene_mats[0].merge(gene_mats[1],on="cell_gene") # mean-normalize the rows gene_mat = gene_mat.subtract(gene_mat.mean(axis=1),axis=0) # calculate svd u, s, vh = linalg.svd(gene_mat,check_finite=False,full_matrices=False) if len(s) >= k: # calculate new z scores based on svd new_zs = gene_mat.dot(np.transpose(vh[:k,:])) # calculate load on each component load = np.square(s)/sum(np.square(s)) # save new zs and fs in dictionaries to save later for i in range(k): loads["f{}".format(i)][gene] = load[i] zs["svd_z{}".format(i)].update(pd.Series(new_zs[i].values,index=new_zs.index).to_dict()) # save loadings v_out = pd.DataFrame(vh,columns=gene_mat.columns) #gene_mat_name = "{}_{}_{}.geneMat".format(gene, args.dataname, args.param_stem) gene_mat_name = "{}.geneMat".format(gene) v_out.to_csv(gene_mat_name, index=False, sep = "\t") for i in range(k): df["f{}".format(i)] = df["gene"].map(loads["f{}".format(i)]) df["svd_z{}".format(i)] = df["cell_gene"].map(zs["svd_z{}".format(i)]) df["svd_z_sumsq"] = (df[["svd_z{}".format(i) for i in range(k)]]**2).sum(axis=1) sub_cols = ["cell","gene","scZ","svd_z_sumsq","n.g_Start","n.g_End"] + ["f{}".format(i) for i in range(k)] + ["svd_z{}".format(i) for i in range(k)] #+ velocity_cols if "ontology" in df.columns: sub_cols = sub_cols + [args.grouping_level_1, args.grouping_level_2, "ontology"] logging.info("Write out files") df.drop_duplicates("cell_gene")[sub_cols].to_csv(args.outname_tsv, index=False, sep="\t") df.to_parquet(args.outname_pq) logging.info("Completed") try: exit(main()) except Exception: logging.exception("Exception in main(): ") exit(1)
[ "pandas.DataFrame", "logging.exception", "argparse.ArgumentParser", "logging.basicConfig", "numpy.square", "numpy.transpose", "logging.info", "scipy.linalg.svd", "pandas.read_parquet", "pandas.Series" ]
[((180, 258), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""calculate splicing scores per gene/cell"""'}), "(description='calculate splicing scores per gene/cell')\n", (203, 258), False, 'import argparse\n'), ((1029, 1184), 'logging.basicConfig', 'logging.basicConfig', ([], {'filename': 'args.outname_log', 'format': '"""%(asctime)s %(levelname)-8s %(message)s"""', 'level': 'logging.INFO', 'datefmt': '"""%Y-%m-%d %H:%M:%S"""'}), "(filename=args.outname_log, format=\n '%(asctime)s %(levelname)-8s %(message)s', level=logging.INFO, datefmt=\n '%Y-%m-%d %H:%M:%S')\n", (1048, 1184), False, 'import logging\n'), ((1198, 1235), 'logging.info', 'logging.info', (['"""Beginning calculation"""'], {}), "('Beginning calculation')\n", (1210, 1235), False, 'import logging\n'), ((1238, 1274), 'logging.info', 'logging.info', (['"""Read in parquet file"""'], {}), "('Read in parquet file')\n", (1250, 1274), False, 'import logging\n'), ((1283, 1310), 'pandas.read_parquet', 'pd.read_parquet', (['args.input'], {}), '(args.input)\n', (1298, 1310), True, 'import pandas as pd\n'), ((1360, 1406), 'logging.info', 'logging.info', (['"""Perform SVD zscore calculation"""'], {}), "('Perform SVD zscore calculation')\n", (1372, 1406), False, 'import logging\n'), ((2739, 2777), 'logging.info', 'logging.info', (['"""Iterate over each gene"""'], {}), "('Iterate over each gene')\n", (2751, 2777), False, 'import logging\n'), ((4621, 4652), 'logging.info', 'logging.info', (['"""Write out files"""'], {}), "('Write out files')\n", (4633, 4652), False, 'import logging\n'), ((4782, 4807), 'logging.info', 'logging.info', (['"""Completed"""'], {}), "('Completed')\n", (4794, 4807), False, 'import logging\n'), ((3304, 3365), 'scipy.linalg.svd', 'linalg.svd', (['gene_mat'], {'check_finite': '(False)', 'full_matrices': '(False)'}), '(gene_mat, check_finite=False, full_matrices=False)\n', (3314, 3365), False, 'from scipy import linalg\n'), ((4853, 4895), 'logging.exception', 'logging.exception', (['"""Exception in main(): """'], {}), "('Exception in main(): ')\n", (4870, 4895), False, 'import logging\n'), ((3841, 3883), 'pandas.DataFrame', 'pd.DataFrame', (['vh'], {'columns': 'gene_mat.columns'}), '(vh, columns=gene_mat.columns)\n', (3853, 3883), True, 'import pandas as pd\n'), ((3461, 3484), 'numpy.transpose', 'np.transpose', (['vh[:k, :]'], {}), '(vh[:k, :])\n', (3473, 3484), True, 'import numpy as np\n'), ((3542, 3554), 'numpy.square', 'np.square', (['s'], {}), '(s)\n', (3551, 3554), True, 'import numpy as np\n'), ((3559, 3571), 'numpy.square', 'np.square', (['s'], {}), '(s)\n', (3568, 3571), True, 'import numpy as np\n'), ((3744, 3791), 'pandas.Series', 'pd.Series', (['new_zs[i].values'], {'index': 'new_zs.index'}), '(new_zs[i].values, index=new_zs.index)\n', (3753, 3791), True, 'import pandas as pd\n')]
# -*- coding: utf-8 -*- import numpy as np from . import utils def bias(predicted, reference): """ Calculate the bias between PREDICTED and REFERENCE. B = mean(p) - mean(r) where p is the predicted values, and r is the reference values. Note that p & r must have the same number of values. Input: PREDICTED : predicted field REFERENCE : reference field Output: B : bias between predicted and reference Author: <NAME> Symplectic, LLC www.thesymplectic.com <EMAIL> Created on Dec 9, 2016 """ # Check that dimensions of predicted and reference fields match utils.check_arrays(predicted, reference) # Calculate bias in means b = np.mean(predicted) - np.mean(reference) return b
[ "numpy.mean" ]
[((727, 745), 'numpy.mean', 'np.mean', (['predicted'], {}), '(predicted)\n', (734, 745), True, 'import numpy as np\n'), ((748, 766), 'numpy.mean', 'np.mean', (['reference'], {}), '(reference)\n', (755, 766), True, 'import numpy as np\n')]
"""Module for base class of Circle and Sphere.""" import numpy as np from skspatial._functions import _contains_point from skspatial.objects._base_spatial import _BaseSpatial from skspatial.objects.point import Point from skspatial.objects.vector import Vector from skspatial.typing import array_like class _BaseSphere(_BaseSpatial): """Private parent class for Circle and Sphere.""" def __init__(self, point: array_like, radius: float): if radius <= 0: raise ValueError("The radius must be positive.") self.point = Point(point) self.radius = radius self.dimension = self.point.dimension def __repr__(self) -> str: name_class = type(self).__name__ repr_point = np.array_repr(self.point) return f"{name_class}(point={repr_point}, radius={self.radius})" def distance_point(self, point: array_like) -> np.float64: """Return the distance from a point to the circle/sphere.""" distance_to_center = self.point.distance_point(point) return abs(distance_to_center - self.radius) def contains_point(self, point: array_like, **kwargs: float) -> bool: """Check if the circle/sphere contains a point.""" return _contains_point(self, point, **kwargs) def project_point(self, point: array_like) -> Point: """ Project a point onto the circle or sphere. Parameters ---------- point : array_like Input point. Returns ------- Point Point projected onto the circle or sphere. Raises ------ ValueError If the input point is the center of the circle or sphere. Examples -------- >>> from skspatial.objects import Circle >>> circle = Circle([0, 0], 1) >>> circle.project_point([1, 1]).round(3) Point([0.707, 0.707]) >>> circle.project_point([-6, 3]).round(3) Point([-0.894, 0.447]) >>> circle.project_point([0, 0]) Traceback (most recent call last): ... ValueError: The point must not be the center of the circle or sphere. >>> from skspatial.objects import Sphere >>> Sphere([0, 0, 0], 2).project_point([1, 2, 3]).round(3) Point([0.535, 1.069, 1.604]) """ if self.point.is_equal(point): raise ValueError("The point must not be the center of the circle or sphere.") vector_to_point = Vector.from_points(self.point, point) return self.point + self.radius * vector_to_point.unit()
[ "numpy.array_repr", "skspatial.objects.point.Point", "skspatial._functions._contains_point", "skspatial.objects.vector.Vector.from_points" ]
[((558, 570), 'skspatial.objects.point.Point', 'Point', (['point'], {}), '(point)\n', (563, 570), False, 'from skspatial.objects.point import Point\n'), ((743, 768), 'numpy.array_repr', 'np.array_repr', (['self.point'], {}), '(self.point)\n', (756, 768), True, 'import numpy as np\n'), ((1241, 1279), 'skspatial._functions._contains_point', '_contains_point', (['self', 'point'], {}), '(self, point, **kwargs)\n', (1256, 1279), False, 'from skspatial._functions import _contains_point\n'), ((2502, 2539), 'skspatial.objects.vector.Vector.from_points', 'Vector.from_points', (['self.point', 'point'], {}), '(self.point, point)\n', (2520, 2539), False, 'from skspatial.objects.vector import Vector\n')]
import numpy import openmm import openmm.app import openmm.unit import qm3 import qm3.engines.openmm import qm3.engines.xtb import qm3.utils import qm3.utils.hessian import qm3.actions.minimize import sys import os cwd = os.path.abspath( os.path.dirname( sys.argv[0] ) ) + os.sep mol = qm3.molecule() mol.pdb_read( open( "node.25" ) ) mol.boxl = numpy.array( [ 40.0, 40.0, 40.0 ] ) mol.psf_read( open( cwd + "oxy-cope.psf" ) ) mol.guess_atomic_numbers() _psf = openmm.app.charmmpsffile.CharmmPsfFile( cwd + "oxy-cope.psf" ) _psf.setBox( mol.boxl[0] * openmm.unit.angstrom, mol.boxl[1] * openmm.unit.angstrom, mol.boxl[2] * openmm.unit.angstrom ) _prm = openmm.app.charmmparameterset.CharmmParameterSet( cwd + "oxy-cope.top", cwd + "oxy-cope.prm" ) _sys = _psf.createSystem( _prm, nonbondedMethod = openmm.app.CutoffPeriodic, nonbondedCutoff = 16.0 * openmm.unit.angstrom, switchDistance = 14.0 * openmm.unit.angstrom, rigidWater = False ) sqm = mol.resn == "COP" smm = mol.sph_sel( sqm, 14 ) print( sqm.sum(), smm.sum(), end = " " ) smm = numpy.logical_and( smm, numpy.logical_not( sqm ) ) print( smm.sum() ) emm = qm3.engines.openmm.run( _sys, _psf.topology, sel_QM = sqm, platform = "OpenCL" ) eqm = qm3.engines.xtb.run( mol, 0, 0, sel_QM = sqm, sel_MM = smm ) mol.engines["mm"] = emm mol.engines["qm"] = eqm mol.set_active( sqm ) log = open( "borra_log.mm", "wt" ) def calc_hess( self: object, step: int ): eqm.get_func( self ) self.set_active( smm ) self.engines["mm"].update_chrg( self ) self.engines.pop( "qm" ) qm3.actions.minimize.fire( self, gradient_tolerance = 0.5, log_file = log ) log.flush() self.chrg[sqm] = 0.0 self.engines["mm"].update_chrg( self ) self.engines["qm"] = eqm self.set_active( sqm ) if( step % 10 == 0 ): self.hess = qm3.utils.hessian.numerical( self ) qm3.utils.hessian.manage( self, self.hess ) self.get_grad() else: self.get_grad() qm3.utils.hessian.manage( self, self.hess, should_update = True ) return( qm3.utils.hessian.raise_RT( self.hess, qm3.utils.RT_modes( self ) ) ) qm3.actions.minimize.baker( mol, calc_hess, gradient_tolerance = 2.0, step_number = 100, print_frequency = 1, follow_mode = 0 ) with open( "saddle.pdb", "wt" ) as f: mol.pdb_write( f ) val, vec = qm3.utils.hessian.frequencies( mol, mol.hess ) print( val[0:10] ) qm3.utils.hessian.normal_mode( mol, val, vec, 0, afac = 8.0 )
[ "qm3.engines.xtb.run", "qm3.utils.hessian.numerical", "qm3.utils.hessian.frequencies", "qm3.utils.RT_modes", "os.path.dirname", "numpy.logical_not", "qm3.molecule", "qm3.utils.hessian.manage", "qm3.actions.minimize.baker", "openmm.app.charmmparameterset.CharmmParameterSet", "numpy.array", "openmm.app.charmmpsffile.CharmmPsfFile", "qm3.engines.openmm.run", "qm3.utils.hessian.normal_mode", "qm3.actions.minimize.fire" ]
[((300, 314), 'qm3.molecule', 'qm3.molecule', ([], {}), '()\n', (312, 314), False, 'import qm3\n'), ((360, 391), 'numpy.array', 'numpy.array', (['[40.0, 40.0, 40.0]'], {}), '([40.0, 40.0, 40.0])\n', (371, 391), False, 'import numpy\n'), ((476, 536), 'openmm.app.charmmpsffile.CharmmPsfFile', 'openmm.app.charmmpsffile.CharmmPsfFile', (["(cwd + 'oxy-cope.psf')"], {}), "(cwd + 'oxy-cope.psf')\n", (514, 536), False, 'import openmm\n'), ((684, 780), 'openmm.app.charmmparameterset.CharmmParameterSet', 'openmm.app.charmmparameterset.CharmmParameterSet', (["(cwd + 'oxy-cope.top')", "(cwd + 'oxy-cope.prm')"], {}), "(cwd + 'oxy-cope.top', cwd +\n 'oxy-cope.prm')\n", (732, 780), False, 'import openmm\n'), ((1164, 1238), 'qm3.engines.openmm.run', 'qm3.engines.openmm.run', (['_sys', '_psf.topology'], {'sel_QM': 'sqm', 'platform': '"""OpenCL"""'}), "(_sys, _psf.topology, sel_QM=sqm, platform='OpenCL')\n", (1186, 1238), False, 'import qm3\n'), ((1251, 1305), 'qm3.engines.xtb.run', 'qm3.engines.xtb.run', (['mol', '(0)', '(0)'], {'sel_QM': 'sqm', 'sel_MM': 'smm'}), '(mol, 0, 0, sel_QM=sqm, sel_MM=smm)\n', (1270, 1305), False, 'import qm3\n'), ((2158, 2279), 'qm3.actions.minimize.baker', 'qm3.actions.minimize.baker', (['mol', 'calc_hess'], {'gradient_tolerance': '(2.0)', 'step_number': '(100)', 'print_frequency': '(1)', 'follow_mode': '(0)'}), '(mol, calc_hess, gradient_tolerance=2.0,\n step_number=100, print_frequency=1, follow_mode=0)\n', (2184, 2279), False, 'import qm3\n'), ((2400, 2444), 'qm3.utils.hessian.frequencies', 'qm3.utils.hessian.frequencies', (['mol', 'mol.hess'], {}), '(mol, mol.hess)\n', (2429, 2444), False, 'import qm3\n'), ((2466, 2523), 'qm3.utils.hessian.normal_mode', 'qm3.utils.hessian.normal_mode', (['mol', 'val', 'vec', '(0)'], {'afac': '(8.0)'}), '(mol, val, vec, 0, afac=8.0)\n', (2495, 2523), False, 'import qm3\n'), ((1111, 1133), 'numpy.logical_not', 'numpy.logical_not', (['sqm'], {}), '(sqm)\n', (1128, 1133), False, 'import numpy\n'), ((1592, 1661), 'qm3.actions.minimize.fire', 'qm3.actions.minimize.fire', (['self'], {'gradient_tolerance': '(0.5)', 'log_file': 'log'}), '(self, gradient_tolerance=0.5, log_file=log)\n', (1617, 1661), False, 'import qm3\n'), ((251, 279), 'os.path.dirname', 'os.path.dirname', (['sys.argv[0]'], {}), '(sys.argv[0])\n', (266, 279), False, 'import os\n'), ((1854, 1887), 'qm3.utils.hessian.numerical', 'qm3.utils.hessian.numerical', (['self'], {}), '(self)\n', (1881, 1887), False, 'import qm3\n'), ((1898, 1939), 'qm3.utils.hessian.manage', 'qm3.utils.hessian.manage', (['self', 'self.hess'], {}), '(self, self.hess)\n', (1922, 1939), False, 'import qm3\n'), ((2008, 2069), 'qm3.utils.hessian.manage', 'qm3.utils.hessian.manage', (['self', 'self.hess'], {'should_update': '(True)'}), '(self, self.hess, should_update=True)\n', (2032, 2069), False, 'import qm3\n'), ((2125, 2149), 'qm3.utils.RT_modes', 'qm3.utils.RT_modes', (['self'], {}), '(self)\n', (2143, 2149), False, 'import qm3\n')]
import numpy as np import tensorflow as tf from tensorflow.keras import Input, Model from tensorflow.keras.layers import Dense units = 4 enc = np.random.rand(4, 16, 32).reshape(4, -1, 32).astype('float32') dec = np.random.rand(4, 32).reshape(4, 1, 32).astype('float32') enc_h = Input(shape=(None, 32)) dec_h = Input(shape=(1, 32)) w1 = Dense(units)(enc_h) w2 = Dense(units)(dec_h) v = Dense(1) score = tf.nn.tanh(w1 + w2) score = v(score) attention = tf.nn.softmax(score, axis=1) context = attention * enc_h context = tf.reduce_sum(context, axis=1) mdl = Model(inputs=[enc_h, dec_h], outputs=[score, attention, context]) score, attention, context = mdl([enc, dec]) print(f'score shape {score.shape}') print(f'attention shape {score.shape}') print(f'context shape {score.shape}') enc = np.random.rand(4, 8, 32).reshape(4, -1, 32).astype('float32') score, attention, context = mdl([enc, dec]) print(f'score shape {score.shape}') print(f'attention shape {score.shape}') print(f'context shape {score.shape}')
[ "tensorflow.nn.softmax", "tensorflow.reduce_sum", "tensorflow.nn.tanh", "tensorflow.keras.layers.Dense", "tensorflow.keras.Input", "tensorflow.keras.Model", "numpy.random.rand" ]
[((281, 304), 'tensorflow.keras.Input', 'Input', ([], {'shape': '(None, 32)'}), '(shape=(None, 32))\n', (286, 304), False, 'from tensorflow.keras import Input, Model\n'), ((313, 333), 'tensorflow.keras.Input', 'Input', ([], {'shape': '(1, 32)'}), '(shape=(1, 32))\n', (318, 333), False, 'from tensorflow.keras import Input, Model\n'), ((389, 397), 'tensorflow.keras.layers.Dense', 'Dense', (['(1)'], {}), '(1)\n', (394, 397), False, 'from tensorflow.keras.layers import Dense\n'), ((407, 426), 'tensorflow.nn.tanh', 'tf.nn.tanh', (['(w1 + w2)'], {}), '(w1 + w2)\n', (417, 426), True, 'import tensorflow as tf\n'), ((456, 484), 'tensorflow.nn.softmax', 'tf.nn.softmax', (['score'], {'axis': '(1)'}), '(score, axis=1)\n', (469, 484), True, 'import tensorflow as tf\n'), ((523, 553), 'tensorflow.reduce_sum', 'tf.reduce_sum', (['context'], {'axis': '(1)'}), '(context, axis=1)\n', (536, 553), True, 'import tensorflow as tf\n'), ((561, 626), 'tensorflow.keras.Model', 'Model', ([], {'inputs': '[enc_h, dec_h]', 'outputs': '[score, attention, context]'}), '(inputs=[enc_h, dec_h], outputs=[score, attention, context])\n', (566, 626), False, 'from tensorflow.keras import Input, Model\n'), ((340, 352), 'tensorflow.keras.layers.Dense', 'Dense', (['units'], {}), '(units)\n', (345, 352), False, 'from tensorflow.keras.layers import Dense\n'), ((365, 377), 'tensorflow.keras.layers.Dense', 'Dense', (['units'], {}), '(units)\n', (370, 377), False, 'from tensorflow.keras.layers import Dense\n'), ((145, 170), 'numpy.random.rand', 'np.random.rand', (['(4)', '(16)', '(32)'], {}), '(4, 16, 32)\n', (159, 170), True, 'import numpy as np\n'), ((214, 235), 'numpy.random.rand', 'np.random.rand', (['(4)', '(32)'], {}), '(4, 32)\n', (228, 235), True, 'import numpy as np\n'), ((792, 816), 'numpy.random.rand', 'np.random.rand', (['(4)', '(8)', '(32)'], {}), '(4, 8, 32)\n', (806, 816), True, 'import numpy as np\n')]
import numpy as np import matplotlib.pyplot as plt from scipy.interpolate import interp1d import scipy.integrate as integrate plt.close('all') # ------ defining constants ----- # # -- using mks for convenience -- # c = 2.998e8 # m / s h = 6.626e-34 # m^s * kg / s k = 1.31e-23 # J / K b = 2.898e-3 # m * K # ------ FUNCTIONS ----- # # ----- Wien's Law ----- # def wiens(T): return b / T # will be in meters # ---- Planck's Law ---- # def planck(x,T): return (2*h*c**2) / (x**5 * (np.exp((h*c)/(x*k*T))-1)) # ---- Integrate over Bandpass ---- # def integrated_flux(nu,filt,flux): return integrate.trapz(filt * flux / nu, nu) / integrate.trapz(filt / nu, nu) # ---------------------- # # reading in bandpass data filts = np.loadtxt('UBV_ma06.txt',skiprows=17) ufilt = [filts[:,0],filts[:,1]] # wavelength in A bfilt = [filts[:,2],filts[:,3]] vfilt = [filts[:,4],filts[:,5]] # -- calculating colors for BB -- # temp = [10000] lam = np.arange(1e-9,4e-6,1e-9) # in m flux = [] for filt in [ufilt,bfilt,vfilt]: f = interp1d(lam*1e10,planck(lam,temp)) indx = np.arange(len(filt[0])) indx = indx[filt[0] > 0] bb_match = f(filt[0][indx]) flux.append(integrated_flux(2.998e18/filt[0][indx],filt[1][indx],bb_match)) flux = np.asarray(flux) # plotting integrating example plt.figure(figsize=(9,3)) plt.plot(lam*1e10,planck(lam,temp)/max(planck(lam,temp)),color='k',lw=2.) plt.text(0.02,0.86,'Blackbody, T: 10$^4$ K',transform=plt.gca().transAxes,fontsize=15) x = [3600,4350,5470] nam = ['$U$','$B$','$V$'] count = 0 for filt in [ufilt,bfilt,vfilt]: indx = np.arange(len(filt[0])) indx = indx[filt[0] > 0] plt.plot(filt[0][indx],filt[1][indx]*1.2,color='k') plt.fill_between(filt[0][indx],filt[1][indx]*1.2,alpha=0.3,label=nam[count]) plt.scatter(x[count],flux[count]/max(planck(lam,temp)),s=200,\ edgecolor='k',color='C%s'%int(count)) count += 1 plt.legend(frameon=False,fontsize=15) plt.ylim(0.,1.5) plt.xlim(ufilt[0][0]-100,vfilt[0][-1]+100) plt.ylabel('flux') plt.xlabel('wavelength [$\AA$]') plt.gca().set_yticklabels([]) plt.tight_layout() plt.savefig('plots-data/hw1_prob2a.pdf',dpi=200) plt.close('all')
[ "matplotlib.pyplot.xlim", "matplotlib.pyplot.plot", "matplotlib.pyplot.ylim", "matplotlib.pyplot.gca", "matplotlib.pyplot.close", "numpy.asarray", "matplotlib.pyplot.legend", "matplotlib.pyplot.figure", "numpy.arange", "numpy.loadtxt", "numpy.exp", "scipy.integrate.trapz", "matplotlib.pyplot.ylabel", "matplotlib.pyplot.fill_between", "matplotlib.pyplot.xlabel", "matplotlib.pyplot.tight_layout", "matplotlib.pyplot.savefig" ]
[((127, 143), 'matplotlib.pyplot.close', 'plt.close', (['"""all"""'], {}), "('all')\n", (136, 143), True, 'import matplotlib.pyplot as plt\n'), ((732, 771), 'numpy.loadtxt', 'np.loadtxt', (['"""UBV_ma06.txt"""'], {'skiprows': '(17)'}), "('UBV_ma06.txt', skiprows=17)\n", (742, 771), True, 'import numpy as np\n'), ((944, 974), 'numpy.arange', 'np.arange', (['(1e-09)', '(4e-06)', '(1e-09)'], {}), '(1e-09, 4e-06, 1e-09)\n', (953, 974), True, 'import numpy as np\n'), ((1234, 1250), 'numpy.asarray', 'np.asarray', (['flux'], {}), '(flux)\n', (1244, 1250), True, 'import numpy as np\n'), ((1284, 1310), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(9, 3)'}), '(figsize=(9, 3))\n', (1294, 1310), True, 'import matplotlib.pyplot as plt\n'), ((1870, 1908), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'frameon': '(False)', 'fontsize': '(15)'}), '(frameon=False, fontsize=15)\n', (1880, 1908), True, 'import matplotlib.pyplot as plt\n'), ((1908, 1926), 'matplotlib.pyplot.ylim', 'plt.ylim', (['(0.0)', '(1.5)'], {}), '(0.0, 1.5)\n', (1916, 1926), True, 'import matplotlib.pyplot as plt\n'), ((1926, 1973), 'matplotlib.pyplot.xlim', 'plt.xlim', (['(ufilt[0][0] - 100)', '(vfilt[0][-1] + 100)'], {}), '(ufilt[0][0] - 100, vfilt[0][-1] + 100)\n', (1934, 1973), True, 'import matplotlib.pyplot as plt\n'), ((1969, 1987), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""flux"""'], {}), "('flux')\n", (1979, 1987), True, 'import matplotlib.pyplot as plt\n'), ((1988, 2021), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""wavelength [$\\\\AA$]"""'], {}), "('wavelength [$\\\\AA$]')\n", (1998, 2021), True, 'import matplotlib.pyplot as plt\n'), ((2052, 2070), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (2068, 2070), True, 'import matplotlib.pyplot as plt\n'), ((2071, 2120), 'matplotlib.pyplot.savefig', 'plt.savefig', (['"""plots-data/hw1_prob2a.pdf"""'], {'dpi': '(200)'}), "('plots-data/hw1_prob2a.pdf', dpi=200)\n", (2082, 2120), True, 'import matplotlib.pyplot as plt\n'), ((2120, 2136), 'matplotlib.pyplot.close', 'plt.close', (['"""all"""'], {}), "('all')\n", (2129, 2136), True, 'import matplotlib.pyplot as plt\n'), ((1621, 1676), 'matplotlib.pyplot.plot', 'plt.plot', (['filt[0][indx]', '(filt[1][indx] * 1.2)'], {'color': '"""k"""'}), "(filt[0][indx], filt[1][indx] * 1.2, color='k')\n", (1629, 1676), True, 'import matplotlib.pyplot as plt\n'), ((1674, 1760), 'matplotlib.pyplot.fill_between', 'plt.fill_between', (['filt[0][indx]', '(filt[1][indx] * 1.2)'], {'alpha': '(0.3)', 'label': 'nam[count]'}), '(filt[0][indx], filt[1][indx] * 1.2, alpha=0.3, label=nam[\n count])\n', (1690, 1760), True, 'import matplotlib.pyplot as plt\n'), ((597, 634), 'scipy.integrate.trapz', 'integrate.trapz', (['(filt * flux / nu)', 'nu'], {}), '(filt * flux / nu, nu)\n', (612, 634), True, 'import scipy.integrate as integrate\n'), ((637, 667), 'scipy.integrate.trapz', 'integrate.trapz', (['(filt / nu)', 'nu'], {}), '(filt / nu, nu)\n', (652, 667), True, 'import scipy.integrate as integrate\n'), ((2021, 2030), 'matplotlib.pyplot.gca', 'plt.gca', ([], {}), '()\n', (2028, 2030), True, 'import matplotlib.pyplot as plt\n'), ((1438, 1447), 'matplotlib.pyplot.gca', 'plt.gca', ([], {}), '()\n', (1445, 1447), True, 'import matplotlib.pyplot as plt\n'), ((486, 513), 'numpy.exp', 'np.exp', (['(h * c / (x * k * T))'], {}), '(h * c / (x * k * T))\n', (492, 513), True, 'import numpy as np\n')]
import numpy as np import matplotlib.pyplot as plt c = 0.2 g = lambda x: 1 if x > 1.0 else 0 R = 0.005 eta1 = lambda w, rho: -R*g(rho)*np.heaviside(w, 0) eta2 = lambda w, rho: -R*g(rho)*np.heaviside(w, 0) fa = lambda a, b, w1: w1*(a - a*b) fb = lambda a, b, w2: -w2*(b - a*b) def evolve( T, a0, b0, w1_0, w2_0 ): h = 0.01 N = int(T/h) t = np.zeros(N) a = np.zeros(N) b = np.zeros(N) w1 = np.zeros(N) w2 = np.zeros(N) t[0] = 0 a[0] = a0 b[0] = b0 w1[0] = w1_0 w2[0] = w2_0 for i in range(N-1): a[i+1] = a[i] + h*fa( a[i], b[i], w1[i] ) b[i+1] = b[i] + h*fb( a[i], b[i], w2[i] ) w1[i+1] = w1[i] + h*eta1( w1[i],a[i] ) w2[i+1] = w2[i] + h*eta2( w2[i], b[i] ) t[i+1] = t[i] + h return a, b, w1, w2, t a0 = 1.0 b0 = 0.1 w1_0 = 0.3 w2_0 = 0.4 a, b, w1, w2, t = evolve( 500, a0, b0, w1_0,w2_0 ) fig, ax = plt.subplots(1, 3) ax[0].plot( a, b, '.-' ) ax[0].set_xlabel('motivation1') ax[0].set_ylabel('motivation2') plt.grid() ax[1].plot(t, a) ax[1].plot(t, b) ax[1].set_xlabel('time') ax[1].set_ylabel('motivation') ax[2].plot(w1, w2) ax[2].set_xlabel('a') ax[2].set_ylabel('b') plt.show()
[ "numpy.heaviside", "matplotlib.pyplot.show", "numpy.zeros", "matplotlib.pyplot.subplots", "matplotlib.pyplot.grid" ]
[((920, 938), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(1)', '(3)'], {}), '(1, 3)\n', (932, 938), True, 'import matplotlib.pyplot as plt\n'), ((1029, 1039), 'matplotlib.pyplot.grid', 'plt.grid', ([], {}), '()\n', (1037, 1039), True, 'import matplotlib.pyplot as plt\n'), ((1193, 1203), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (1201, 1203), True, 'import matplotlib.pyplot as plt\n'), ((359, 370), 'numpy.zeros', 'np.zeros', (['N'], {}), '(N)\n', (367, 370), True, 'import numpy as np\n'), ((383, 394), 'numpy.zeros', 'np.zeros', (['N'], {}), '(N)\n', (391, 394), True, 'import numpy as np\n'), ((403, 414), 'numpy.zeros', 'np.zeros', (['N'], {}), '(N)\n', (411, 414), True, 'import numpy as np\n'), ((424, 435), 'numpy.zeros', 'np.zeros', (['N'], {}), '(N)\n', (432, 435), True, 'import numpy as np\n'), ((445, 456), 'numpy.zeros', 'np.zeros', (['N'], {}), '(N)\n', (453, 456), True, 'import numpy as np\n'), ((137, 155), 'numpy.heaviside', 'np.heaviside', (['w', '(0)'], {}), '(w, 0)\n', (149, 155), True, 'import numpy as np\n'), ((188, 206), 'numpy.heaviside', 'np.heaviside', (['w', '(0)'], {}), '(w, 0)\n', (200, 206), True, 'import numpy as np\n')]
# -*- coding: utf-8 -*- """ Created on Tue Aug 27 16:12:58 2019 @author: LKK """ import numpy as np from sys import getsizeof import time import copy def dominate (record1, record2) : result = record1.att - record2.att if np.all(result>=0) : return 1 #record dominate target if np.all(result< 0) : return 2 #target dominate record else : return 0 #incomparable def BNL_basic (origin_database) : start_time = time.time() database = copy.deepcopy(origin_database) #operating_setting = np.zeros.((database[0].att.shape),dtype='i2') ## 0 for min 1 for max 2 for distinct, basically for min w_size = 1024 // getsizeof(database[0]) window = [] temp = [] skylines = [] while database : for record in list(database) : if not window : window.append(record) database.remove(record) continue record_dominated = False for target in list(window) : if dominate(record, target) == 2 : database.remove(record) record_dominated = True break elif dominate(record, target) == 1 : window.remove(target) continue elif dominate(record, target) == 0 : continue if record_dominated : continue if len(window) < w_size : window.append(record) else : temp.append(record) database.remove(record) skylines = skylines + window database = temp temp.clear() cost_time = time.time() - start_time return [cost_time, skylines]
[ "copy.deepcopy", "sys.getsizeof", "numpy.all", "time.time" ]
[((239, 258), 'numpy.all', 'np.all', (['(result >= 0)'], {}), '(result >= 0)\n', (245, 258), True, 'import numpy as np\n'), ((307, 325), 'numpy.all', 'np.all', (['(result < 0)'], {}), '(result < 0)\n', (313, 325), True, 'import numpy as np\n'), ((465, 476), 'time.time', 'time.time', ([], {}), '()\n', (474, 476), False, 'import time\n'), ((492, 522), 'copy.deepcopy', 'copy.deepcopy', (['origin_database'], {}), '(origin_database)\n', (505, 522), False, 'import copy\n'), ((672, 694), 'sys.getsizeof', 'getsizeof', (['database[0]'], {}), '(database[0])\n', (681, 694), False, 'from sys import getsizeof\n'), ((1755, 1766), 'time.time', 'time.time', ([], {}), '()\n', (1764, 1766), False, 'import time\n')]
import multiprocessing import tensorflow as tf import numpy as np print("version de tensorflow:", tf.__version__) from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets('MNIST_data', one_hot=True) import matplotlib.pyplot as plt # Los Ejemplos de entrenamiento estan en: # mnist.train.images print("Numero de ejemplos de entrenamiento:", mnist.train.images.shape[0]) # El conjunto de validacion es: # mnist.validation print("Numero de ejemplos de validacion:", mnist.validation.images.shape[0]) # El conjunto de prueba es: # mnist.test print("Numero de ejemplos de prueba:", mnist.test.images.shape[0]) # Cada digito es un vector de dimension 784 . print("Tamanio de cada digito:", mnist.train.images.shape[1]) # Las etiquetas se encuentran en: # mnist.train.labels # mnist.validation.labels # mnist.test.labels print("Tamano de cada etiqueta:", mnist.train.labels.shape[1]) # Cada etiqueta es un one-hot-vector,ie. un vector con un solo uno, las demas entradas son cero # [1,0,0,0,0,0,0,0,0,0] representa el numero 0 # [0,1,0,0,0,0,0,0,0,0] representa el numero 1 # . # . # . # Cada digito se almacena como un vector de 784 dimensiones. Para visualizarlo, primero lo redimensionamos a una imagen de 28x28. def muestra_digito(x): """ x: vector 784 dimensiones Muestra el vector como una imagen de 28x28 """ plt.axis('off') plt.imshow(x.reshape((28, 28)), cmap=plt.cm.gray) plt.show() return def vis_imagen(i, conjunto="train"): """ i indice del conjunto especificado conjunto: cadena Cualquiera: train, validation, test Muestra el digito en el indice i y su etiqueta """ if(conjunto == "train"): muestra_digito(mnist.train.images[i, ]) label = np.argwhere(mnist.train.labels[i])[0][0] elif(conjunto == "test"): muestra_digito(mnist.test.images[i, ]) label = np.argwhere(mnist.test.labels[i])[0][0] else: muestra_digito(mnist.validation.images[i, ]) label = np.argwhere(mnist.validation.labels[i])[0][0] print("Etiqueta " + str(label)) return # # Para ver las imagenes # #vis_imagen(0, conjunto="train") #vis_imagen(132, conjunto="validation") #vis_imagen(32, conjunto="test") #vis_imagen(50000, conjunto="train") # # RED NEURONAL # # Placeholders para los datos de entrenamiento # En ellos se pasaran despues los datos de entrenamiento (x,y) # x imagen, y etiqueta x = tf.placeholder(tf.float32, shape=[None, 784]) y = tf.placeholder(tf.float32, shape=[None, 10]) # Variables del modelo # Capa 1 W_1 = tf.Variable(tf.truncated_normal(shape=[784, 512], stddev=0.2)) b_1 = tf.Variable(tf.zeros([512])) # Capa 2 de salida W_2 = tf.Variable(tf.truncated_normal(shape=[512, 10], stddev=0.2)) b_2 = tf.Variable(tf.zeros([10])) # Arquitectura de la red neural def NN(x): """ x: matriz su forma debe ser (m, 784) regresa la activacion de la capa de salida matriz de (m, 10) """ # Capa Escondida 1. z_1 = tf.matmul(x, W_1) + b_1 # Combinacion lineal a_1 = tf.nn.relu(z_1) # Activacion (funcion no lineal) # Capa 2. Esta es la capa de salida z_2 = tf.matmul(a_1, W_2) + b_2 # Combinacion lineal return z_2 # Funcion de costo y_ = NN(x) cross_entropy = tf.reduce_mean( tf.nn.softmax_cross_entropy_with_logits(logits=y_, labels=y)) # Predicciones train_pred = tf.nn.softmax(y_) # predicciones en el conjunto de entrenamiento # Nota: la funcion softmax calcula la probabilidad de cada etiqueta del 0 al 9. # Para obtener la prediccion necesitamos usar las funcion tf.argmax(y_,1) o su version en python np.argmax(y_,1) # Asi se elige el digito mas probable para la imagen # Esto lo hace la funcion precision y_valid = NN(mnist.validation.images) # predicciones en el conjunto de validacion valid_pred = tf.nn.softmax(y_valid) # Optimizador opt = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy) # Sesion e inicializacion de varables # ############################### # # Configuracion para multi corel # # ############################### CPUs = multiprocessing.cpu_count() config = tf.ConfigProto(device_count={"CPU": CPUs}, inter_op_parallelism_threads=1, intra_op_parallelism_threads=1) sess = tf.Session(config=config) print("CPUs", CPUs) # ############################## # sess = tf.Session() # Crea una session sess.run(tf.global_variables_initializer()) # Precision def precision(predicciones, etiquetas): return (100.0 * np.sum(np.argmax(predicciones, 1) == np.argmax(etiquetas, 1)) / predicciones.shape[0]) # Entrenamiento pasos = 5000 print("Entrenamiento:") for i in range(pasos): batch = mnist.train.next_batch(100) _, costo, predicciones = sess.run( [opt, cross_entropy, train_pred], feed_dict={x: batch[0], y: batch[1]}) if (i % 500 == 0): print("Costo del minibatch hasta el paso %d: %f" % (i, costo)) print("Precision en el conjunto de entrenamiento: %.1f%%" % precision(predicciones, batch[1])) print("Precision en el conjunto de validacion: %.1f%%" % precision( valid_pred.eval(session=sess), mnist.validation.labels)) print("\n") y_test = NN(mnist.test.images) test_prediction = tf.nn.softmax(y_test) print("Precision en el conjunto de PRUEBA: %.1f%%" % precision(test_prediction.eval(session=sess), mnist.test.labels)) indice = 251 p = tf.argmax(NN(mnist.test.images[indice:indice+1]).eval(session=sess), 1) print("Prediccion:", sess.run(p)[0]) vis_imagen(indice, conjunto="test") def remove_transparency(im, bg_colour=(255, 255, 255)): # Only process if image has transparency if im.mode in ('RGBA', 'LA') or (im.mode == 'P' and 'transparency' in im.info): # Need to convert to RGBA if LA format due to a bug in PIL alpha = im.convert('RGBA').split()[-1] # Create a new background image of our matt color. # Must be RGBA because paste requires both images have the same format bg = Image.new("RGBA", im.size, bg_colour + (255,)) bg.paste(im, mask=alpha) return bg else: return im ################################# # # Usa tu propia imagen # ################################ from PIL import Image imagen = "numero2.png" img = Image.open(imagen) img = remove_transparency(img).convert('L') if img.size != (28, 28): img.thumbnail((28, 28), Image.ANTIALIAS) entrada = np.array(img, dtype=np.float32) entrada = entrada.reshape((1, 784)) entrada = entrada/255.0 p = tf.argmax(NN(entrada).eval(session=sess), 1) print("Imagen:{}".format(imagen)) img.show() print("Prediccion:", sess.run(p)[0])
[ "PIL.Image.new", "numpy.argmax", "tensorflow.ConfigProto", "tensorflow.matmul", "tensorflow.truncated_normal", "multiprocessing.cpu_count", "tensorflow.nn.softmax", "tensorflow.nn.relu", "tensorflow.nn.softmax_cross_entropy_with_logits", "tensorflow.placeholder", "matplotlib.pyplot.show", "tensorflow.global_variables_initializer", "tensorflow.Session", "numpy.argwhere", "tensorflow.train.GradientDescentOptimizer", "matplotlib.pyplot.axis", "PIL.Image.open", "tensorflow.zeros", "numpy.array", "tensorflow.examples.tutorials.mnist.input_data.read_data_sets" ]
[((183, 236), 'tensorflow.examples.tutorials.mnist.input_data.read_data_sets', 'input_data.read_data_sets', (['"""MNIST_data"""'], {'one_hot': '(True)'}), "('MNIST_data', one_hot=True)\n", (208, 236), False, 'from tensorflow.examples.tutorials.mnist import input_data\n'), ((2504, 2549), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32'], {'shape': '[None, 784]'}), '(tf.float32, shape=[None, 784])\n', (2518, 2549), True, 'import tensorflow as tf\n'), ((2554, 2598), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32'], {'shape': '[None, 10]'}), '(tf.float32, shape=[None, 10])\n', (2568, 2598), True, 'import tensorflow as tf\n'), ((3471, 3488), 'tensorflow.nn.softmax', 'tf.nn.softmax', (['y_'], {}), '(y_)\n', (3484, 3488), True, 'import tensorflow as tf\n'), ((3915, 3937), 'tensorflow.nn.softmax', 'tf.nn.softmax', (['y_valid'], {}), '(y_valid)\n', (3928, 3937), True, 'import tensorflow as tf\n'), ((4175, 4202), 'multiprocessing.cpu_count', 'multiprocessing.cpu_count', ([], {}), '()\n', (4200, 4202), False, 'import multiprocessing\n'), ((4212, 4322), 'tensorflow.ConfigProto', 'tf.ConfigProto', ([], {'device_count': "{'CPU': CPUs}", 'inter_op_parallelism_threads': '(1)', 'intra_op_parallelism_threads': '(1)'}), "(device_count={'CPU': CPUs}, inter_op_parallelism_threads=1,\n intra_op_parallelism_threads=1)\n", (4226, 4322), True, 'import tensorflow as tf\n'), ((4374, 4399), 'tensorflow.Session', 'tf.Session', ([], {'config': 'config'}), '(config=config)\n', (4384, 4399), True, 'import tensorflow as tf\n'), ((5380, 5401), 'tensorflow.nn.softmax', 'tf.nn.softmax', (['y_test'], {}), '(y_test)\n', (5393, 5401), True, 'import tensorflow as tf\n'), ((6420, 6438), 'PIL.Image.open', 'Image.open', (['imagen'], {}), '(imagen)\n', (6430, 6438), False, 'from PIL import Image\n'), ((6565, 6596), 'numpy.array', 'np.array', (['img'], {'dtype': 'np.float32'}), '(img, dtype=np.float32)\n', (6573, 6596), True, 'import numpy as np\n'), ((1408, 1423), 'matplotlib.pyplot.axis', 'plt.axis', (['"""off"""'], {}), "('off')\n", (1416, 1423), True, 'import matplotlib.pyplot as plt\n'), ((1482, 1492), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (1490, 1492), True, 'import matplotlib.pyplot as plt\n'), ((2651, 2700), 'tensorflow.truncated_normal', 'tf.truncated_normal', ([], {'shape': '[784, 512]', 'stddev': '(0.2)'}), '(shape=[784, 512], stddev=0.2)\n', (2670, 2700), True, 'import tensorflow as tf\n'), ((2720, 2735), 'tensorflow.zeros', 'tf.zeros', (['[512]'], {}), '([512])\n', (2728, 2735), True, 'import tensorflow as tf\n'), ((2775, 2823), 'tensorflow.truncated_normal', 'tf.truncated_normal', ([], {'shape': '[512, 10]', 'stddev': '(0.2)'}), '(shape=[512, 10], stddev=0.2)\n', (2794, 2823), True, 'import tensorflow as tf\n'), ((2843, 2857), 'tensorflow.zeros', 'tf.zeros', (['[10]'], {}), '([10])\n', (2851, 2857), True, 'import tensorflow as tf\n'), ((3146, 3161), 'tensorflow.nn.relu', 'tf.nn.relu', (['z_1'], {}), '(z_1)\n', (3156, 3161), True, 'import tensorflow as tf\n'), ((3379, 3439), 'tensorflow.nn.softmax_cross_entropy_with_logits', 'tf.nn.softmax_cross_entropy_with_logits', ([], {'logits': 'y_', 'labels': 'y'}), '(logits=y_, labels=y)\n', (3418, 3439), True, 'import tensorflow as tf\n'), ((4505, 4538), 'tensorflow.global_variables_initializer', 'tf.global_variables_initializer', ([], {}), '()\n', (4536, 4538), True, 'import tensorflow as tf\n'), ((3090, 3107), 'tensorflow.matmul', 'tf.matmul', (['x', 'W_1'], {}), '(x, W_1)\n', (3099, 3107), True, 'import tensorflow as tf\n'), ((3247, 3266), 'tensorflow.matmul', 'tf.matmul', (['a_1', 'W_2'], {}), '(a_1, W_2)\n', (3256, 3266), True, 'import tensorflow as tf\n'), ((3960, 3998), 'tensorflow.train.GradientDescentOptimizer', 'tf.train.GradientDescentOptimizer', (['(0.5)'], {}), '(0.5)\n', (3993, 3998), True, 'import tensorflow as tf\n'), ((6146, 6192), 'PIL.Image.new', 'Image.new', (['"""RGBA"""', 'im.size', '(bg_colour + (255,))'], {}), "('RGBA', im.size, bg_colour + (255,))\n", (6155, 6192), False, 'from PIL import Image\n'), ((1825, 1859), 'numpy.argwhere', 'np.argwhere', (['mnist.train.labels[i]'], {}), '(mnist.train.labels[i])\n', (1836, 1859), True, 'import numpy as np\n'), ((1959, 1992), 'numpy.argwhere', 'np.argwhere', (['mnist.test.labels[i]'], {}), '(mnist.test.labels[i])\n', (1970, 1992), True, 'import numpy as np\n'), ((2078, 2117), 'numpy.argwhere', 'np.argwhere', (['mnist.validation.labels[i]'], {}), '(mnist.validation.labels[i])\n', (2089, 2117), True, 'import numpy as np\n'), ((4621, 4647), 'numpy.argmax', 'np.argmax', (['predicciones', '(1)'], {}), '(predicciones, 1)\n', (4630, 4647), True, 'import numpy as np\n'), ((4651, 4674), 'numpy.argmax', 'np.argmax', (['etiquetas', '(1)'], {}), '(etiquetas, 1)\n', (4660, 4674), True, 'import numpy as np\n')]
import pickle from typing import Dict, Union import numpy as np import pandas as pd from sklearn.tree import DecisionTreeClassifier from sklearn.linear_model import LogisticRegression from sklearn.metrics import accuracy_score, f1_score, roc_auc_score SklearnClassifierModel = Union[LogisticRegression, DecisionTreeClassifier] def train_model( features: pd.DataFrame, target: pd.Series, model: SklearnClassifierModel ) -> SklearnClassifierModel: model.fit(features, target) return model def predict_model( model: SklearnClassifierModel, features: pd.DataFrame, use_log_trick: bool = True ) -> np.ndarray: predicts = model.predict(features) if use_log_trick: predicts = np.exp(predicts) return predicts def evaluate_model( predicts: np.ndarray, target: pd.Series, use_log_trick: bool = False ) -> Dict[str, float]: if use_log_trick: target = np.exp(target) return { "accuracy": accuracy_score(target, predicts), "f1": f1_score(target, predicts), "roc_auc": roc_auc_score(target, predicts), } def serialize_model(model: SklearnClassifierModel, output: str) -> str: with open(output, "wb") as f: pickle.dump(model, f) return output
[ "pickle.dump", "sklearn.metrics.accuracy_score", "sklearn.metrics.roc_auc_score", "sklearn.metrics.f1_score", "numpy.exp" ]
[((708, 724), 'numpy.exp', 'np.exp', (['predicts'], {}), '(predicts)\n', (714, 724), True, 'import numpy as np\n'), ((902, 916), 'numpy.exp', 'np.exp', (['target'], {}), '(target)\n', (908, 916), True, 'import numpy as np\n'), ((950, 982), 'sklearn.metrics.accuracy_score', 'accuracy_score', (['target', 'predicts'], {}), '(target, predicts)\n', (964, 982), False, 'from sklearn.metrics import accuracy_score, f1_score, roc_auc_score\n'), ((998, 1024), 'sklearn.metrics.f1_score', 'f1_score', (['target', 'predicts'], {}), '(target, predicts)\n', (1006, 1024), False, 'from sklearn.metrics import accuracy_score, f1_score, roc_auc_score\n'), ((1045, 1076), 'sklearn.metrics.roc_auc_score', 'roc_auc_score', (['target', 'predicts'], {}), '(target, predicts)\n', (1058, 1076), False, 'from sklearn.metrics import accuracy_score, f1_score, roc_auc_score\n'), ((1200, 1221), 'pickle.dump', 'pickle.dump', (['model', 'f'], {}), '(model, f)\n', (1211, 1221), False, 'import pickle\n')]
import numpy as np import matplotlib.pyplot as plt cfs_to_tafd = 2.29568411*10**-5 * 86400 / 1000 # we'll use the "loadtxt" function from numpy to read the CSV # the delimiter is a comma (other options might be tab or space) # we want to skip the header row and the first (0th) column # In general it's better to use the pandas library for this, which we'll see later data = np.loadtxt('data/SHA.csv', delimiter=',', skiprows=1, usecols=[1,2,3,4]) inflow = data[:,0] * cfs_to_tafd # TAF/d outflow = data[:,1] * cfs_to_tafd # TAF/d storage = data[:,2] / 1000 # AF to TAF # first plot: time series of storage plt.plot(storage) plt.xlabel('Days since Oct 1 2000') plt.ylabel('Storage (TAF)') plt.ylim([0,4500]) plt.show() # # second plot: time series of inflow and outflow # plt.plot(inflow) # plt.plot(outflow) # plt.xlabel('Days since Oct 1 2000') # plt.ylabel('Flows (TAF/d)') # plt.legend(['Inflow', 'Outflow']) # plt.show() # # third plot: exceedance plot of inflow and outflow # T = len(inflow) # # before log-transforming, replace ~zeros with small values to avoid warning # inflow[inflow < 0.01] = 0.01 # outflow[outflow < 0.01] = 0.01 # log_inflow = np.log(inflow) # log_outflow = np.log(outflow) # plt.plot(np.arange(T)/T, np.sort(log_inflow)[::-1]) # plt.plot(np.arange(T)/T, np.sort(log_outflow)[::-1]) # plt.legend(['Inflow', 'Outflow']) # plt.ylabel('Log(Q)') # plt.xlabel('Exceedance') # plt.show() # # fourth plot: # # plot historical storage for folsom, oroville, and shasta # # on the same graph # reservoirs = ['FOL', 'ORO', 'SHA'] # for r in reservoirs: # data = np.loadtxt('data/' + r + '.csv', # delimiter=',', # skiprows=1, # usecols=[1,2,3]) # storage = data[:,2] / 1000 # AF to TAF # plt.plot(storage, linewidth=2) # plt.xlabel('Days since Oct 1 2000') # plt.ylabel('Storage (TAF)') # plt.legend(reservoirs) # plt.show() # optional - save to file # plt.savefig('whatever.pdf') # or .png, .svg, etc
[ "matplotlib.pyplot.show", "matplotlib.pyplot.plot", "matplotlib.pyplot.ylim", "numpy.loadtxt", "matplotlib.pyplot.ylabel", "matplotlib.pyplot.xlabel" ]
[((378, 453), 'numpy.loadtxt', 'np.loadtxt', (['"""data/SHA.csv"""'], {'delimiter': '""","""', 'skiprows': '(1)', 'usecols': '[1, 2, 3, 4]'}), "('data/SHA.csv', delimiter=',', skiprows=1, usecols=[1, 2, 3, 4])\n", (388, 453), True, 'import numpy as np\n'), ((615, 632), 'matplotlib.pyplot.plot', 'plt.plot', (['storage'], {}), '(storage)\n', (623, 632), True, 'import matplotlib.pyplot as plt\n'), ((633, 668), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Days since Oct 1 2000"""'], {}), "('Days since Oct 1 2000')\n", (643, 668), True, 'import matplotlib.pyplot as plt\n'), ((669, 696), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Storage (TAF)"""'], {}), "('Storage (TAF)')\n", (679, 696), True, 'import matplotlib.pyplot as plt\n'), ((697, 716), 'matplotlib.pyplot.ylim', 'plt.ylim', (['[0, 4500]'], {}), '([0, 4500])\n', (705, 716), True, 'import matplotlib.pyplot as plt\n'), ((716, 726), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (724, 726), True, 'import matplotlib.pyplot as plt\n')]
import numpy as np from future._greyreconstruct import reconstruction_loop from skimage.filters._rank_order import rank_order y, x = np.mgrid[:20:0.5, :20:0.5] bumps = np.sin(x) + np.sin(y) h = 0.3 seed = bumps - h mask = bumps assert tuple(seed.shape) == tuple(mask.shape) selem = np.ones([3] * seed.ndim, dtype=bool) offset = np.array([d // 2 for d in selem.shape]) # Cross out the center of the selem selem[tuple(slice(d, d + 1) for d in offset)] = False # Make padding for edges of reconstructed image so we can ignore boundaries dims = np.zeros(seed.ndim + 1, dtype=int) dims[1:] = np.array(seed.shape) + (np.array(selem.shape) - 1) dims[0] = 2 inside_slices = tuple(slice(o, o + s) for o, s in zip(offset, seed.shape)) # Set padded region to minimum image intensity and mask along first axis so # we can interleave image and mask pixels when sorting. pad_value = np.min(seed) images = np.full(dims, pad_value, dtype="float64") images[(0, *inside_slices)] = seed images[(1, *inside_slices)] = mask # Create a list of strides across the array to get the neighbors within # a flattened array value_stride = np.array(images.strides[1:]) // images.dtype.itemsize image_stride = np.int64(images.strides[0] // images.dtype.itemsize) selem_mgrid = np.mgrid[[slice(-o, d - o) for d, o in zip(selem.shape, offset)]] selem_offsets = selem_mgrid[:, selem].transpose() nb_strides = np.array( [np.sum(value_stride * selem_offset) for selem_offset in selem_offsets], np.int32, ) images = images.flatten() # Erosion goes smallest to largest; dilation goes largest to smallest. index_sorted = np.argsort(images).astype(np.int32) index_sorted = index_sorted[::-1] # Make a linked list of pixels sorted by value. -1 is the list terminator. prev = np.full(len(images), -1, np.int32) next_ = np.full(len(images), -1, np.int32) prev[index_sorted[1:]] = index_sorted[:-1] next_[index_sorted[:-1]] = index_sorted[1:] # Cython inner-loop compares the rank of pixel values. value_rank, value_map = rank_order(images) start = index_sorted[0] ranks = np.array(value_rank) strides = nb_strides current_idx = np.int64(start)
[ "numpy.full", "skimage.filters._rank_order.rank_order", "numpy.sum", "numpy.zeros", "numpy.ones", "numpy.argsort", "numpy.min", "numpy.sin", "numpy.array", "numpy.int64" ]
[((286, 322), 'numpy.ones', 'np.ones', (['([3] * seed.ndim)'], {'dtype': 'bool'}), '([3] * seed.ndim, dtype=bool)\n', (293, 322), True, 'import numpy as np\n'), ((332, 373), 'numpy.array', 'np.array', (['[(d // 2) for d in selem.shape]'], {}), '([(d // 2) for d in selem.shape])\n', (340, 373), True, 'import numpy as np\n'), ((547, 581), 'numpy.zeros', 'np.zeros', (['(seed.ndim + 1)'], {'dtype': 'int'}), '(seed.ndim + 1, dtype=int)\n', (555, 581), True, 'import numpy as np\n'), ((875, 887), 'numpy.min', 'np.min', (['seed'], {}), '(seed)\n', (881, 887), True, 'import numpy as np\n'), ((898, 939), 'numpy.full', 'np.full', (['dims', 'pad_value'], {'dtype': '"""float64"""'}), "(dims, pad_value, dtype='float64')\n", (905, 939), True, 'import numpy as np\n'), ((1187, 1239), 'numpy.int64', 'np.int64', (['(images.strides[0] // images.dtype.itemsize)'], {}), '(images.strides[0] // images.dtype.itemsize)\n', (1195, 1239), True, 'import numpy as np\n'), ((1998, 2016), 'skimage.filters._rank_order.rank_order', 'rank_order', (['images'], {}), '(images)\n', (2008, 2016), False, 'from skimage.filters._rank_order import rank_order\n'), ((2050, 2070), 'numpy.array', 'np.array', (['value_rank'], {}), '(value_rank)\n', (2058, 2070), True, 'import numpy as np\n'), ((2106, 2121), 'numpy.int64', 'np.int64', (['start'], {}), '(start)\n', (2114, 2121), True, 'import numpy as np\n'), ((170, 179), 'numpy.sin', 'np.sin', (['x'], {}), '(x)\n', (176, 179), True, 'import numpy as np\n'), ((182, 191), 'numpy.sin', 'np.sin', (['y'], {}), '(y)\n', (188, 191), True, 'import numpy as np\n'), ((593, 613), 'numpy.array', 'np.array', (['seed.shape'], {}), '(seed.shape)\n', (601, 613), True, 'import numpy as np\n'), ((1118, 1146), 'numpy.array', 'np.array', (['images.strides[1:]'], {}), '(images.strides[1:])\n', (1126, 1146), True, 'import numpy as np\n'), ((617, 638), 'numpy.array', 'np.array', (['selem.shape'], {}), '(selem.shape)\n', (625, 638), True, 'import numpy as np\n'), ((1398, 1433), 'numpy.sum', 'np.sum', (['(value_stride * selem_offset)'], {}), '(value_stride * selem_offset)\n', (1404, 1433), True, 'import numpy as np\n'), ((1600, 1618), 'numpy.argsort', 'np.argsort', (['images'], {}), '(images)\n', (1610, 1618), True, 'import numpy as np\n')]
# -*- coding: utf-8 -*- """ Created on Tue Jan 8 09:24:07 2019 @author: madsa """ from mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot as plt from matplotlib import cm from matplotlib.ticker import LinearLocator, FormatStrFormatter import numpy as np import matplotlib import pickle import matplotlib.tri as mtri path = "Saved/kernel pickles/" matrix="2_lin_val" with open(path+matrix, "rb") as pickleFile: results = pickle.load(pickleFile) A=results[len(results)-1] # Make data. x = results[len(results)-3] y = results[len(results)-2] hf = plt.figure() ha = hf.add_subplot(111, projection='3d') X, Y = np.meshgrid(x, y) # `plot_surface` expects `x` and `y` data to be 2D ha.plot_surface(X, Y, A) plt.show() # Plot the surface. #surf = ax.plot_surface(X, Y, Z, cmap=cm.coolwarm, """ linewidth=0, antialiased=False) triang = mtri.Triangulation(x, y) fig = plt.figure() ax = fig.add_subplot(1,1,1, projection='3d') ax.plot_trisurf(triang, z, cmap='jet') ax.scatter(x,y,z, marker='.', s=10, c="black", alpha=0.5) ax.view_init(elev=60, azim=-45) ax.set_xlabel('X') ax.set_ylabel('Y') ax.set_zlabel('Z') plt.show()""" """#%% Load training data matrix=".npy" ax.imshow(masked_array, interpolation='nearest', cmap=cmap) Axes3D.plot_surface(X, Y, Z, *args, **kwargs) A[A==-1]=np.nan where_are_NaNs = np.isnan(A) A[where_are_NaNs] = 100 index=np.unravel_index(A.argmin(), A.shape) print(matrix+" best result is:", A[index]) print("At index: " + str(index)) dimensions=[] for i in range(1,len(results)-1): dimensions.append(results[i]) Variables=[] for i in range(len(dimensions)): Variables.append(dimensions[i][index[i]]) print("Variables:", Variables) print("Lambda:", results[0][index[-1]]) """
[ "matplotlib.pyplot.figure", "pickle.load", "matplotlib.pyplot.show", "numpy.meshgrid" ]
[((436, 459), 'pickle.load', 'pickle.load', (['pickleFile'], {}), '(pickleFile)\n', (447, 459), False, 'import pickle\n'), ((582, 594), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (592, 594), True, 'import matplotlib.pyplot as plt\n'), ((653, 670), 'numpy.meshgrid', 'np.meshgrid', (['x', 'y'], {}), '(x, y)\n', (664, 670), True, 'import numpy as np\n'), ((757, 767), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (765, 767), True, 'import matplotlib.pyplot as plt\n')]
# Copyright (c) 2014 Evalf # # 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. from . import config, log, util, warnings import contextlib, numpy @contextlib.contextmanager @util.positional_only('name') def mplfigure(*args, **kwargs): '''Matplotlib figure context, convenience function. Returns a :class:`matplotlib.figure.Figure` object suitable for `object-oriented plotting`_. Upon exit the result is saved using the agg-backend in all formats configured via :attr:`nutils.config.imagetype`, and the resulting filenames written to log. .. _`object-oriented plotting`: https://matplotlib.org/gallery/api/agg_oo_sgskip.html Args ---- name : :class:`str` The filename (without extension) of the resulting figure(s) **kwargs : Keyword arguments are passed on unchanged to the constructor of the :class:`matplotlib.figure.Figure` object. ''' name, = args import matplotlib.backends.backend_agg fig = matplotlib.figure.Figure(**kwargs) matplotlib.backends.backend_agg.FigureCanvas(fig) # sets reference via fig.set_canvas with log.context(name): yield fig if '.' in name: names_formats = [(name, name.split('.')[-1])] else: warnings.deprecation('`config.imagetype` is deprecated. Please pass a filename with extension, e.g. {!r}.'.format(name+'.png')) names_formats = [(name+'.'+fmt, fmt) for fmt in config.imagetype.split(',')] for name, fmt in names_formats: with log.open(name, 'wb') as f: fig.savefig(f, format=fmt) fig.set_canvas(None) # break circular reference def triplot(name, points, values=None, *, tri=None, hull=None, cmap='jet', clim=None, linewidth=.1, linecolor='k'): if (tri is None) != (values is None): raise Exception('tri and values can only be specified jointly') with mplfigure(name) as fig: ax = fig.add_subplot(111) if points.shape[1] == 1: if tri is not None: import matplotlib.collections ax.add_collection(matplotlib.collections.LineCollection(numpy.array([points[:,0], values]).T[tri])) if hull is not None: for x in points[hull[:,0],0]: ax.axvline(x, color=linecolor, linewidth=linewidth) ax.autoscale(enable=True, axis='x', tight=True) if clim is None: ax.autoscale(enable=True, axis='y', tight=False) else: ax.set_ylim(clim) elif points.shape[1] == 2: ax.set_aspect('equal') if tri is not None: im = ax.tripcolor(points[:,0], points[:,1], tri, values, shading='gouraud', cmap=cmap, rasterized=True) if clim is not None: im.set_clim(clim) fig.colorbar(im) if hull is not None: import matplotlib.collections ax.add_collection(matplotlib.collections.LineCollection(points[hull], colors=linecolor, linewidths=linewidth, alpha=1 if tri is None else .5)) ax.autoscale(enable=True, axis='both', tight=True) else: raise Exception('invalid spatial dimension: {}'.format(points.shape[1])) @util.positional_only('name', 'tri', 'x') def vtk(*args, **kwargs): '''Export data to a VTK file. This method provides a simple interface to the `VTK file format`_ with a number of important restrictions: * Simplex-only. This makes it possible to define the mesh by a combination of vertex coordinates and a connectivity table. * Legacy mode. The newer XML based format is more complex and does not provide benefits within the constraints set by this method. * Binary mode. This allows for direct output of binary data, which aids speed, accuracy and file size. Beyond the mandatory file name, connectivity table, and vertex coordinates, any additional data sets can be provided as keyword arguments, where the keys are the names by which the arrays are stored. The data can be either vertex or point data, with the distinction made based on the length of the array. .. _`VTK file format`: https://www.vtk.org/VTK/img/file-formats.pdf Args ---- name : :class:`str` Destination file name (without vtk extension). tri : :class:`int` array Triangulation. x : :class:`float` array Vertex coordinates. **kwargs : Cell and/or point data ''' name, cells, points = args assert cells.ndim == points.ndim == 2 ndims = points.shape[1] assert cells.shape[1] == ndims + 1 if ndims == 2: points = numpy.concatenate([points, numpy.zeros_like(points[:,:1])], axis=1) celltype = 5 # VTK_TRIANGLE elif ndims == 3: celltype = 10 # VTK_TETRA else: raise Exception('invalid point dimension: {}'.format(ndims)) vtkdtype = { numpy.dtype('>i1'): 'char', numpy.dtype('>u1'): 'unsigned_char', numpy.dtype('>i2'): 'short', numpy.dtype('>u2'): 'unsigned_short', numpy.dtype('>i4'): 'int', numpy.dtype('>u4'): 'unsigned_int', numpy.dtype('>f4'): 'float', numpy.dtype('>f8'): 'double'} vtkndim = {1: 'SCALARS {} {} 1\nLOOKUP_TABLE default\n', 2: 'VECTORS {} {}\n', 3: 'TENSORS {} {}\n'} bigendian = lambda a: a.astype('>{0.kind}{0.itemsize}'.format(a.dtype)) points = bigendian(points) if points.dtype not in vtkdtype: raise Exception('invalid data type for points: {}'.format(points.dtype)) t_cells = numpy.empty((len(cells), ndims+2), dtype='>u4') t_cells[:,0] = ndims + 1 t_cells[:,1:] = cells gathered = util.gather((len(array), (name, bigendian(array))) for name, array in kwargs.items()) invalid_length = [name for n, arrays in gathered if n not in (len(points), len(cells)) for name, array in arrays] if invalid_length: raise Exception('data length matches neither points nor cells: {}'.format(', '.join(invalid_length))) invalid_dimension = [name for n, arrays in gathered for name, array in arrays if array.ndim not in vtkndim or any(n>3 for n in array.shape[1:])] if invalid_dimension: raise Exception('invalid array dimension: {}'.format(', '.join(invalid_dimension))) invalid_dtype = [name for n, arrays in gathered for name, array in arrays if array.dtype not in vtkdtype] if invalid_dtype: raise Exception('invalid array data type: {}'.format(', '.join(invalid_dtype))) name_vtk = name + '.vtk' with log.open(name_vtk, 'wb') as vtk: vtk.write(b'# vtk DataFile Version 3.0\nvtk output\nBINARY\nDATASET UNSTRUCTURED_GRID\n') vtk.write('POINTS {} {}\n'.format(len(points), vtkdtype[points.dtype]).encode('ascii')) vtk.write(points.tobytes()) vtk.write('CELLS {} {}\n'.format(len(t_cells), t_cells.size).encode('ascii')) vtk.write(t_cells.tobytes()) vtk.write('CELL_TYPES {}\n'.format(len(cells)).encode('ascii')) vtk.write(numpy.array(celltype, dtype='>u4').repeat(len(cells)).tobytes()) for n, arrays in gathered: vtk.write('{}_DATA {}\n'.format('POINT' if n == len(points) else 'CELL', n).encode('ascii')) for name, array in arrays: vtk.write(vtkndim[array.ndim].format(name, vtkdtype[array.dtype]).encode('ascii')) vtk.write(numpy.pad(array, [[0,0]] + [[0,3-n] for n in array.shape[1:]], mode='constant').tobytes()) # vim:sw=2:sts=2:et
[ "numpy.pad", "numpy.dtype", "numpy.array", "numpy.zeros_like" ]
[((5611, 5629), 'numpy.dtype', 'numpy.dtype', (['""">i1"""'], {}), "('>i1')\n", (5622, 5629), False, 'import contextlib, numpy\n'), ((5640, 5658), 'numpy.dtype', 'numpy.dtype', (['""">u1"""'], {}), "('>u1')\n", (5651, 5658), False, 'import contextlib, numpy\n'), ((5681, 5699), 'numpy.dtype', 'numpy.dtype', (['""">i2"""'], {}), "('>i2')\n", (5692, 5699), False, 'import contextlib, numpy\n'), ((5710, 5728), 'numpy.dtype', 'numpy.dtype', (['""">u2"""'], {}), "('>u2')\n", (5721, 5728), False, 'import contextlib, numpy\n'), ((5752, 5770), 'numpy.dtype', 'numpy.dtype', (['""">i4"""'], {}), "('>i4')\n", (5763, 5770), False, 'import contextlib, numpy\n'), ((5781, 5799), 'numpy.dtype', 'numpy.dtype', (['""">u4"""'], {}), "('>u4')\n", (5792, 5799), False, 'import contextlib, numpy\n'), ((5821, 5839), 'numpy.dtype', 'numpy.dtype', (['""">f4"""'], {}), "('>f4')\n", (5832, 5839), False, 'import contextlib, numpy\n'), ((5850, 5868), 'numpy.dtype', 'numpy.dtype', (['""">f8"""'], {}), "('>f8')\n", (5861, 5868), False, 'import contextlib, numpy\n'), ((5396, 5427), 'numpy.zeros_like', 'numpy.zeros_like', (['points[:, :1]'], {}), '(points[:, :1])\n', (5412, 5427), False, 'import contextlib, numpy\n'), ((7613, 7647), 'numpy.array', 'numpy.array', (['celltype'], {'dtype': '""">u4"""'}), "(celltype, dtype='>u4')\n", (7624, 7647), False, 'import contextlib, numpy\n'), ((7950, 8038), 'numpy.pad', 'numpy.pad', (['array', '([[0, 0]] + [[0, 3 - n] for n in array.shape[1:]])'], {'mode': '"""constant"""'}), "(array, [[0, 0]] + [[0, 3 - n] for n in array.shape[1:]], mode=\n 'constant')\n", (7959, 8038), False, 'import contextlib, numpy\n'), ((3003, 3038), 'numpy.array', 'numpy.array', (['[points[:, 0], values]'], {}), '([points[:, 0], values])\n', (3014, 3038), False, 'import contextlib, numpy\n')]
#!/usr/bin/env python # -*- coding:utf-8 -*- # @Filename: csvs_to_plots.py # @Author: <NAME> # @Time: 8/12/21 10:03 import re from os import walk import matplotlib.pyplot as plt import numpy as np import pandas as pd def main(): path = '../test_unlabeled/' dataset = 'titanic' files = next(walk(path), (None, None, []))[2] acc_df = [] mse_df = [] order_mse = [] order_acc = [] for file in files: if '.csv' in file: precision = float(re.findall(r"[-+]?\d*\.\d+|\d+", file)[0]) file = path + file if 'mse' in file: order_mse.append(precision) mse_df.append(pd.read_csv(file)) else: order_acc.append(precision) acc_df.append(pd.read_csv(file)) order_mse = list(enumerate(order_mse)) order_acc = list(enumerate(order_acc)) order_mse.sort(key=lambda x: x[1]) order_acc.sort(key=lambda x: x[1]) datasets = np.array(list(mse_df[0]['dataset'])) index = [idx for idx, elem in enumerate(datasets) if dataset in elem][0] acc_algorithms = np.array([list(df.iloc[index][1:]) for df in acc_df]) acc_algorithms = np.array([acc_algorithms[x] for x, _ in order_acc]) acc_algorithms = acc_algorithms.astype(float) mse_algorithms = np.array([list(df.iloc[index][1:]) for df in mse_df]) mse_algorithms = np.array([mse_algorithms[x] for x, _ in order_mse]) mse_algorithms = mse_algorithms.astype(float) precision = [x for _, x in order_mse] algorithms = ['ENN', 'CNN', 'RNN', 'ICF', 'MSS'] for i in range(len(acc_algorithms)): fig, (ax1, ax2) = plt.subplots(2) fig.suptitle(f'ACC and MSE for {algorithms[i]}') ax1.plot(precision, acc_algorithms[:, i]) ax1.set_title('ACC') ax2.plot(precision, mse_algorithms[:, i]) ax2.set_title('MSE') file_name = path + algorithms[i] + f'_{dataset}' + '.png' plt.savefig(file_name) plt.show() if __name__ == '__main__': main()
[ "matplotlib.pyplot.show", "pandas.read_csv", "os.walk", "re.findall", "numpy.array", "matplotlib.pyplot.subplots", "matplotlib.pyplot.savefig" ]
[((1234, 1285), 'numpy.array', 'np.array', (['[acc_algorithms[x] for x, _ in order_acc]'], {}), '([acc_algorithms[x] for x, _ in order_acc])\n', (1242, 1285), True, 'import numpy as np\n'), ((1464, 1515), 'numpy.array', 'np.array', (['[mse_algorithms[x] for x, _ in order_mse]'], {}), '([mse_algorithms[x] for x, _ in order_mse])\n', (1472, 1515), True, 'import numpy as np\n'), ((1729, 1744), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(2)'], {}), '(2)\n', (1741, 1744), True, 'import matplotlib.pyplot as plt\n'), ((2034, 2056), 'matplotlib.pyplot.savefig', 'plt.savefig', (['file_name'], {}), '(file_name)\n', (2045, 2056), True, 'import matplotlib.pyplot as plt\n'), ((2065, 2075), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (2073, 2075), True, 'import matplotlib.pyplot as plt\n'), ((320, 330), 'os.walk', 'walk', (['path'], {}), '(path)\n', (324, 330), False, 'from os import walk\n'), ((504, 545), 're.findall', 're.findall', (['"""[-+]?\\\\d*\\\\.\\\\d+|\\\\d+"""', 'file'], {}), "('[-+]?\\\\d*\\\\.\\\\d+|\\\\d+', file)\n", (514, 545), False, 'import re\n'), ((682, 699), 'pandas.read_csv', 'pd.read_csv', (['file'], {}), '(file)\n', (693, 699), True, 'import pandas as pd\n'), ((793, 810), 'pandas.read_csv', 'pd.read_csv', (['file'], {}), '(file)\n', (804, 810), True, 'import pandas as pd\n')]
# -*- coding: utf-8 -*- """Trains a convolutional neural network on the MNIST dataset, then attacks it with the FGSM attack.""" from __future__ import absolute_import, division, print_function, unicode_literals from os.path import abspath import sys sys.path.append(abspath('.')) import keras.backend as k import tensorflow as tf from keras.models import Sequential from keras.layers import Dense, Flatten, Conv2D, MaxPooling2D, Activation, Dropout import numpy as np from art.attacks.fast_gradient import FastGradientMethod from art.attacks.deepfool import DeepFool from art.classifiers import KerasClassifier from art.utils import load_dataset # Read MNIST dataset (x_train, y_train), (x_test, y_test), min_, max_ = load_dataset(str('mnist')) print(x_train.shape) # Create Keras convolutional neural network - basic architecture from Keras examples # Source here: https://github.com/keras-team/keras/blob/master/examples/mnist_cnn.py k.set_learning_phase(1) model = Sequential() conv1 = Conv2D(32, kernel_size=(2, 2), activation='relu', input_shape=x_train.shape[1:], name="conv1") model.add(conv1) conv2 = Conv2D(32, (2, 2), activation='relu', name="conv2") model.add(conv2) maxPool = MaxPooling2D(pool_size=(2, 2)) model.add(maxPool) model.add(Dropout(0.25)) model.add(Flatten()) model.add(Dense(1024, activation='relu')) model.add(Dropout(0.25)) model.add(Dense(10, activation='softmax')) model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy']) classifier = KerasClassifier((min_, max_), model=model) classifier.fit(x_train, y_train, nb_epochs=5, batch_size=128) # Evaluate the classifier on the test set preds = np.argmax(classifier.predict(x_test), axis=1) acc = np.sum(preds == np.argmax(y_test, axis=1)) / y_test.shape[0] print("\nTest accuracy: %.2f%%" % (acc * 100)) # untill here cnn # # Craft adversarial samples with FGSM epsilon = .1 # Maximum perturbation adv_crafter = FastGradientMethod(classifier) x_test_adv = adv_crafter.generate(x=x_test, eps=epsilon) print(x_test_adv.shape) local_path = "C:\\Users\\alonh\\Documents\\Thesis\\adversarial-robustness-toolbox\\My implementation\\cnn_data\\" np.save(local_path + "adv_img_list_FGSM.npy", x_test_adv) print("first") # reset and restore old variables model_yaml = model.to_yaml() with open(local_path + "model.yaml", "w") as yaml_file: yaml_file.write(model_yaml) # serialize weights to HDF5 model.save_weights(local_path + "model.h5") print("third")
[ "os.path.abspath", "numpy.save", "numpy.argmax", "keras.layers.Dropout", "art.classifiers.KerasClassifier", "keras.layers.Flatten", "keras.backend.set_learning_phase", "keras.layers.Dense", "keras.layers.Conv2D", "keras.models.Sequential", "art.attacks.fast_gradient.FastGradientMethod", "keras.layers.MaxPooling2D" ]
[((940, 963), 'keras.backend.set_learning_phase', 'k.set_learning_phase', (['(1)'], {}), '(1)\n', (960, 963), True, 'import keras.backend as k\n'), ((973, 985), 'keras.models.Sequential', 'Sequential', ([], {}), '()\n', (983, 985), False, 'from keras.models import Sequential\n'), ((994, 1093), 'keras.layers.Conv2D', 'Conv2D', (['(32)'], {'kernel_size': '(2, 2)', 'activation': '"""relu"""', 'input_shape': 'x_train.shape[1:]', 'name': '"""conv1"""'}), "(32, kernel_size=(2, 2), activation='relu', input_shape=x_train.shape\n [1:], name='conv1')\n", (1000, 1093), False, 'from keras.layers import Dense, Flatten, Conv2D, MaxPooling2D, Activation, Dropout\n'), ((1115, 1166), 'keras.layers.Conv2D', 'Conv2D', (['(32)', '(2, 2)'], {'activation': '"""relu"""', 'name': '"""conv2"""'}), "(32, (2, 2), activation='relu', name='conv2')\n", (1121, 1166), False, 'from keras.layers import Dense, Flatten, Conv2D, MaxPooling2D, Activation, Dropout\n'), ((1195, 1225), 'keras.layers.MaxPooling2D', 'MaxPooling2D', ([], {'pool_size': '(2, 2)'}), '(pool_size=(2, 2))\n', (1207, 1225), False, 'from keras.layers import Dense, Flatten, Conv2D, MaxPooling2D, Activation, Dropout\n'), ((1503, 1545), 'art.classifiers.KerasClassifier', 'KerasClassifier', (['(min_, max_)'], {'model': 'model'}), '((min_, max_), model=model)\n', (1518, 1545), False, 'from art.classifiers import KerasClassifier\n'), ((1933, 1963), 'art.attacks.fast_gradient.FastGradientMethod', 'FastGradientMethod', (['classifier'], {}), '(classifier)\n', (1951, 1963), False, 'from art.attacks.fast_gradient import FastGradientMethod\n'), ((2160, 2217), 'numpy.save', 'np.save', (["(local_path + 'adv_img_list_FGSM.npy')", 'x_test_adv'], {}), "(local_path + 'adv_img_list_FGSM.npy', x_test_adv)\n", (2167, 2217), True, 'import numpy as np\n'), ((267, 279), 'os.path.abspath', 'abspath', (['"""."""'], {}), "('.')\n", (274, 279), False, 'from os.path import abspath\n'), ((1255, 1268), 'keras.layers.Dropout', 'Dropout', (['(0.25)'], {}), '(0.25)\n', (1262, 1268), False, 'from keras.layers import Dense, Flatten, Conv2D, MaxPooling2D, Activation, Dropout\n'), ((1280, 1289), 'keras.layers.Flatten', 'Flatten', ([], {}), '()\n', (1287, 1289), False, 'from keras.layers import Dense, Flatten, Conv2D, MaxPooling2D, Activation, Dropout\n'), ((1301, 1331), 'keras.layers.Dense', 'Dense', (['(1024)'], {'activation': '"""relu"""'}), "(1024, activation='relu')\n", (1306, 1331), False, 'from keras.layers import Dense, Flatten, Conv2D, MaxPooling2D, Activation, Dropout\n'), ((1343, 1356), 'keras.layers.Dropout', 'Dropout', (['(0.25)'], {}), '(0.25)\n', (1350, 1356), False, 'from keras.layers import Dense, Flatten, Conv2D, MaxPooling2D, Activation, Dropout\n'), ((1368, 1399), 'keras.layers.Dense', 'Dense', (['(10)'], {'activation': '"""softmax"""'}), "(10, activation='softmax')\n", (1373, 1399), False, 'from keras.layers import Dense, Flatten, Conv2D, MaxPooling2D, Activation, Dropout\n'), ((1727, 1752), 'numpy.argmax', 'np.argmax', (['y_test'], {'axis': '(1)'}), '(y_test, axis=1)\n', (1736, 1752), True, 'import numpy as np\n')]
import numpy as np import cv2 import matplotlib.pyplot as plt from moviepy.editor import VideoFileClip from src.sliding_window import SlidingWindow from src.lane_line import LaneLine from src.image_reader import ImageReader from src.image_plotter import ImagePlotter from src.camera import Camera from src.threshold_applier import ThresholdApplier class LaneLineFinder(object): """Detects the lane lines in images or a video stream""" def __init__(self, threshold_applier, calibrated_camera, region_of_interest, first_frame, windows_cnt=9): self.threshold_applier = threshold_applier self.camera = calibrated_camera self.region_of_interest = region_of_interest self.height = first_frame.shape[0] self.width = first_frame.shape[1] self.windows_cnt = windows_cnt self.left_lane = None self.right_lane = None self.left_wins = [] self.right_wins = [] self._init_lanes(first_frame) self._sliding_window_frame = None self._overlay = None def _init_lanes(self, frame): thresholds_applied = self.threshold_applier.apply_combined_thresholds(frame) warped, unwrap_m = self.camera.perspective_transform(thresholds_applied, self.region_of_interest[0], self.region_of_interest[1]) frame_histogram = np.sum(warped[int(self.height / 2):, :], axis=0) nonzero = warped.nonzero() left_lane_indexes = np.empty([0], dtype=np.int) right_lane_indexes = np.empty([0], dtype=np.int) window_height = int(self.height / self.windows_cnt) for i in range(self.windows_cnt): if len(self.left_wins) > 0: l_x_center = self.left_wins[-1].x r_x_center = self.right_wins[-1].x else: l_x_center = np.argmax(frame_histogram[:self.width // 2]) r_x_center = np.argmax(frame_histogram[self.width // 2:]) + self.width // 2 left_win = SlidingWindow(y_low=self.height - i * window_height, y_high=self.height - (i + 1) * window_height, x_center=l_x_center) right_win = SlidingWindow(y_low=self.height - i * window_height, y_high=self.height - (i + 1) * window_height, x_center=r_x_center) left_lane_indexes = np.append(left_lane_indexes, left_win.nonzero_pixels_indices(nonzero), axis=0) right_lane_indexes = np.append(right_lane_indexes, right_win.nonzero_pixels_indices(nonzero), axis=0) self.left_wins.append(left_win) self.right_wins.append(right_win) self.left_lane = LaneLine(nonzero[1][left_lane_indexes], nonzero[0][left_lane_indexes], self.height, self.width) self.right_lane = LaneLine(nonzero[1][right_lane_indexes], nonzero[0][right_lane_indexes], self.height, self.width) def _find_lane_pixels_for_each_window(self, frame, windows): indices = np.empty([0], dtype=np.int) nonzero = frame.nonzero() win_x = None for win in windows: indices = np.append(indices, win.nonzero_pixels_indices(nonzero, win_x), axis=0) win_x = win.x_mean return (nonzero[1][indices], nonzero[0][indices]) def _lane_overlay(self, image, unwrap_m=None): overlay = np.zeros_like(image).astype(np.uint8) points = np.vstack((self.left_lane.generate_points(), np.flipud(self.right_lane.generate_points()))) cv2.fillPoly(overlay, [points], (0, 255, 0)) if unwrap_m is not None: overlay = cv2.warpPerspective(overlay, unwrap_m, (image.shape[1], image.shape[0])) alpha = 0.6 return cv2.addWeighted(image, alpha, overlay, 1 - alpha, 0) def _info_overlay(self, frame): if len(frame.shape) == 2: image = np.dstack((frame, frame, frame)) else: image = frame for win in self.left_wins: vertices = win.vertices() cv2.rectangle(image, vertices[0], vertices[1], (1.0, 1.0, 0), 2) for win in self.right_wins: vertices = win.vertices() cv2.rectangle(image, vertices[0], vertices[1], (1.0, 1.0, 0), 2) cv2.polylines(image, [self.left_lane.generate_points()], False, (1.0, 1.0, 0), 2) cv2.polylines(image, [self.right_lane.generate_points()], False, (1.0, 1.0, 0), 2) return image * 255 def _radius_of_curvature(self): radius = int(np.average([self.left_lane.radius_of_curvature(), self.right_lane.radius_of_curvature()])) return radius def _draw_text(self, frame, text, x, y): cv2.putText(frame, text, (x, y), cv2.FONT_HERSHEY_DUPLEX, 0.8, (255, 255, 255), 2) def run(self, frame): thresholds_applied = self.threshold_applier.apply_combined_thresholds(frame) warped, unwrap_m = self.camera.perspective_transform(thresholds_applied, self.region_of_interest[0], self.region_of_interest[1]) (left_x, left_y) = self._find_lane_pixels_for_each_window(warped, self.left_wins) self.left_lane.fit_points(left_x, left_y) (right_x, right_y) = self._find_lane_pixels_for_each_window(warped, self.right_wins) self.right_lane.fit_points(right_x, right_y) thresholds_applied = self.threshold_applier.apply_stacked_thresholds(frame) warped, unwrap_m = self.camera.perspective_transform(thresholds_applied, self.region_of_interest[0], self.region_of_interest[1]) info_overlay = self._info_overlay(warped) warped, unwrap_m = self.camera.perspective_transform(frame, self.region_of_interest[0], self.region_of_interest[1]) top_overlay = self._lane_overlay(warped) self._sliding_window_frame = info_overlay info_overlay = cv2.resize(info_overlay, (0, 0), fx=0.3, fy=0.3) top_overlay = cv2.resize(top_overlay, (0, 0), fx=0.3, fy=0.3) self._overlay = top_overlay frame[:250, :, :] = frame[:250, :, :] * 0.4 (height, width, _) = info_overlay.shape frame[25:25 + height, 25:25 + width, :] = info_overlay frame[25:25 + height, 25 + 25 + width:25 + 25 + width + width, :] = top_overlay text_x = 25 + 25 + width + width + 25 lane_width = self.left_lane.camera_distance() + self.right_lane.camera_distance() off_center = self.right_lane.camera_distance() - lane_width / 2 self._draw_text(frame, 'Radius of curvature: {} m'.format(self._radius_of_curvature()), text_x, 80) self._draw_text(frame, 'Distance of center: {:.1f} m'.format(off_center), text_x, 140) return self._lane_overlay(frame, unwrap_m) def create_video(): ir = ImageReader(read_mode='RGB') cc = Camera(ir, None) cc.calibrate() ta = ThresholdApplier() output_video_name = '../output_videos/project_video_result.mp4' input_video = VideoFileClip("../project_video.mp4") image = input_video.get_frame(0) undistorted = cc.undistort(image) llf = LaneLineFinder(ta, cc, (cc.get_region_of_interest(image)), undistorted) output_video = input_video.fl_image(llf.run) output_video.write_videofile(output_video_name, audio=False) def test_with_images(): ir = ImageReader(read_mode='RGB') ip = ImagePlotter(images_to_show_count=10) cc = Camera(ir, ip) cc.calibrate() ir.regex = '../test_images/test*.jpg' ir.set_image_names() ta = ThresholdApplier() for image_file in ir.images(): image = image_file.image ip.add_to_plot(image, image_file.name, 'out', False) undistorted = cc.undistort(image) llf = LaneLineFinder(ta, cc, (cc.get_region_of_interest(image)), image) result = llf.run(undistorted) # ip.add_to_plot(llf._sliding_window_frame, image_file.name + ' sliding windows', 'out', False) # ip.add_to_plot(result, image_file.name + 'result', 'out', False) ip.add_to_plot(llf._overlay, image_file.name + ' overlay', 'out', False) ip.plot('out', 2) if __name__ == "__main__": #test_with_images() create_video()
[ "numpy.dstack", "src.camera.Camera", "cv2.warpPerspective", "numpy.zeros_like", "cv2.putText", "moviepy.editor.VideoFileClip", "numpy.argmax", "src.threshold_applier.ThresholdApplier", "src.image_plotter.ImagePlotter", "numpy.empty", "src.sliding_window.SlidingWindow", "cv2.fillPoly", "src.image_reader.ImageReader", "cv2.addWeighted", "cv2.rectangle", "src.lane_line.LaneLine", "cv2.resize" ]
[((6900, 6928), 'src.image_reader.ImageReader', 'ImageReader', ([], {'read_mode': '"""RGB"""'}), "(read_mode='RGB')\n", (6911, 6928), False, 'from src.image_reader import ImageReader\n'), ((6938, 6954), 'src.camera.Camera', 'Camera', (['ir', 'None'], {}), '(ir, None)\n', (6944, 6954), False, 'from src.camera import Camera\n'), ((6983, 7001), 'src.threshold_applier.ThresholdApplier', 'ThresholdApplier', ([], {}), '()\n', (6999, 7001), False, 'from src.threshold_applier import ThresholdApplier\n'), ((7089, 7126), 'moviepy.editor.VideoFileClip', 'VideoFileClip', (['"""../project_video.mp4"""'], {}), "('../project_video.mp4')\n", (7102, 7126), False, 'from moviepy.editor import VideoFileClip\n'), ((7433, 7461), 'src.image_reader.ImageReader', 'ImageReader', ([], {'read_mode': '"""RGB"""'}), "(read_mode='RGB')\n", (7444, 7461), False, 'from src.image_reader import ImageReader\n'), ((7471, 7508), 'src.image_plotter.ImagePlotter', 'ImagePlotter', ([], {'images_to_show_count': '(10)'}), '(images_to_show_count=10)\n', (7483, 7508), False, 'from src.image_plotter import ImagePlotter\n'), ((7518, 7532), 'src.camera.Camera', 'Camera', (['ir', 'ip'], {}), '(ir, ip)\n', (7524, 7532), False, 'from src.camera import Camera\n'), ((7628, 7646), 'src.threshold_applier.ThresholdApplier', 'ThresholdApplier', ([], {}), '()\n', (7644, 7646), False, 'from src.threshold_applier import ThresholdApplier\n'), ((1445, 1472), 'numpy.empty', 'np.empty', (['[0]'], {'dtype': 'np.int'}), '([0], dtype=np.int)\n', (1453, 1472), True, 'import numpy as np\n'), ((1502, 1529), 'numpy.empty', 'np.empty', (['[0]'], {'dtype': 'np.int'}), '([0], dtype=np.int)\n', (1510, 1529), True, 'import numpy as np\n'), ((2739, 2839), 'src.lane_line.LaneLine', 'LaneLine', (['nonzero[1][left_lane_indexes]', 'nonzero[0][left_lane_indexes]', 'self.height', 'self.width'], {}), '(nonzero[1][left_lane_indexes], nonzero[0][left_lane_indexes], self\n .height, self.width)\n', (2747, 2839), False, 'from src.lane_line import LaneLine\n'), ((2895, 2996), 'src.lane_line.LaneLine', 'LaneLine', (['nonzero[1][right_lane_indexes]', 'nonzero[0][right_lane_indexes]', 'self.height', 'self.width'], {}), '(nonzero[1][right_lane_indexes], nonzero[0][right_lane_indexes],\n self.height, self.width)\n', (2903, 2996), False, 'from src.lane_line import LaneLine\n'), ((3112, 3139), 'numpy.empty', 'np.empty', (['[0]'], {'dtype': 'np.int'}), '([0], dtype=np.int)\n', (3120, 3139), True, 'import numpy as np\n'), ((3660, 3704), 'cv2.fillPoly', 'cv2.fillPoly', (['overlay', '[points]', '(0, 255, 0)'], {}), '(overlay, [points], (0, 255, 0))\n', (3672, 3704), False, 'import cv2\n'), ((3870, 3922), 'cv2.addWeighted', 'cv2.addWeighted', (['image', 'alpha', 'overlay', '(1 - alpha)', '(0)'], {}), '(image, alpha, overlay, 1 - alpha, 0)\n', (3885, 3922), False, 'import cv2\n'), ((4858, 4945), 'cv2.putText', 'cv2.putText', (['frame', 'text', '(x, y)', 'cv2.FONT_HERSHEY_DUPLEX', '(0.8)', '(255, 255, 255)', '(2)'], {}), '(frame, text, (x, y), cv2.FONT_HERSHEY_DUPLEX, 0.8, (255, 255, \n 255), 2)\n', (4869, 4945), False, 'import cv2\n'), ((5996, 6044), 'cv2.resize', 'cv2.resize', (['info_overlay', '(0, 0)'], {'fx': '(0.3)', 'fy': '(0.3)'}), '(info_overlay, (0, 0), fx=0.3, fy=0.3)\n', (6006, 6044), False, 'import cv2\n'), ((6067, 6114), 'cv2.resize', 'cv2.resize', (['top_overlay', '(0, 0)'], {'fx': '(0.3)', 'fy': '(0.3)'}), '(top_overlay, (0, 0), fx=0.3, fy=0.3)\n', (6077, 6114), False, 'import cv2\n'), ((1982, 2106), 'src.sliding_window.SlidingWindow', 'SlidingWindow', ([], {'y_low': '(self.height - i * window_height)', 'y_high': '(self.height - (i + 1) * window_height)', 'x_center': 'l_x_center'}), '(y_low=self.height - i * window_height, y_high=self.height - (\n i + 1) * window_height, x_center=l_x_center)\n', (1995, 2106), False, 'from src.sliding_window import SlidingWindow\n'), ((2201, 2325), 'src.sliding_window.SlidingWindow', 'SlidingWindow', ([], {'y_low': '(self.height - i * window_height)', 'y_high': '(self.height - (i + 1) * window_height)', 'x_center': 'r_x_center'}), '(y_low=self.height - i * window_height, y_high=self.height - (\n i + 1) * window_height, x_center=r_x_center)\n', (2214, 2325), False, 'from src.sliding_window import SlidingWindow\n'), ((3761, 3833), 'cv2.warpPerspective', 'cv2.warpPerspective', (['overlay', 'unwrap_m', '(image.shape[1], image.shape[0])'], {}), '(overlay, unwrap_m, (image.shape[1], image.shape[0]))\n', (3780, 3833), False, 'import cv2\n'), ((4014, 4046), 'numpy.dstack', 'np.dstack', (['(frame, frame, frame)'], {}), '((frame, frame, frame))\n', (4023, 4046), True, 'import numpy as np\n'), ((4173, 4237), 'cv2.rectangle', 'cv2.rectangle', (['image', 'vertices[0]', 'vertices[1]', '(1.0, 1.0, 0)', '(2)'], {}), '(image, vertices[0], vertices[1], (1.0, 1.0, 0), 2)\n', (4186, 4237), False, 'import cv2\n'), ((4325, 4389), 'cv2.rectangle', 'cv2.rectangle', (['image', 'vertices[0]', 'vertices[1]', '(1.0, 1.0, 0)', '(2)'], {}), '(image, vertices[0], vertices[1], (1.0, 1.0, 0), 2)\n', (4338, 4389), False, 'import cv2\n'), ((1821, 1865), 'numpy.argmax', 'np.argmax', (['frame_histogram[:self.width // 2]'], {}), '(frame_histogram[:self.width // 2])\n', (1830, 1865), True, 'import numpy as np\n'), ((3477, 3497), 'numpy.zeros_like', 'np.zeros_like', (['image'], {}), '(image)\n', (3490, 3497), True, 'import numpy as np\n'), ((1895, 1939), 'numpy.argmax', 'np.argmax', (['frame_histogram[self.width // 2:]'], {}), '(frame_histogram[self.width // 2:])\n', (1904, 1939), True, 'import numpy as np\n')]
import numpy as np import matplotlib.pyplot as plt import pickle # load data data_folder = "traffic-signs-data/" training_file = data_folder+"train.p" validation_file = data_folder+"valid.p" testing_file = data_folder+"test.p" with open(training_file, mode='rb') as f: train = pickle.load(f) with open(validation_file, mode='rb') as f: valid = pickle.load(f) with open(testing_file, mode='rb') as f: test = pickle.load(f) X_train, y_train = train['features'], train['labels'] X_valid, y_valid = valid['features'], valid['labels'] X_test, y_test = test['features'], test['labels'] import csv csv_path = "signnames.csv" reader = csv.reader(open(csv_path, "r")) signnames = [] for row in reader: if "ClassId" in row: continue signnames.append(row) n_train = len(X_train) n_validation = len(X_valid) n_test = len(X_test) image_shape = X_train[0].shape n_classes = len(signnames) print("Number of training examples =", n_train) print("Number of testing examples =", n_test) print("Number of validating examples =", n_validation) print("Image data shape =", image_shape) print("Number of classes =", n_classes) from pipeline_lib import * imgs = [] titles = [] for i in range(n_classes): img_num = np.where(y_valid == i) # return all labels of i class imgs.append(X_valid[img_num[0][0]]) titles.append(signnames[i][0] + ' ' + signnames[i][1]) show_imgs_together(imgs,titles) import cv2 for i in range(len(X_train)): cv2.normalize(X_train[i], X_train[i], 0, 255, norm_type=cv2.NORM_MINMAX) for i in range(len(X_valid)): cv2.normalize(X_valid[i], X_valid[i], 0, 255, norm_type=cv2.NORM_MINMAX) for i in range(len(X_test)): cv2.normalize(X_test[i], X_test[i], 0, 255, norm_type=cv2.NORM_MINMAX) imgs = [] titles = [] for i in range(n_classes): img_num = np.where(y_valid == i) # return all labels of i class imgs.append(X_valid[img_num[0][0]]) titles.append(signnames[i][0] + ' ' + signnames[i][1]) # show_imgs_together(imgs,titles) from Dataset import SignDataset from torch.utils.data import DataLoader train_dataset = SignDataset(X_train, y_train, n_classes) test_dataset = SignDataset(X_test, y_test, n_classes) valid_dataset = SignDataset(X_valid, y_valid, n_classes) # print(test_dataset.__len__()) print(len(train_dataset)) train_dataloader = DataLoader(train_dataset, batch_size=128, shuffle=True, num_workers=10) test_dataloader = DataLoader(test_dataset, batch_size=128, shuffle=True, num_workers=10) valid_dataloader = DataLoader(valid_dataset, batch_size=128, shuffle=True, num_workers=10) print(len(train_dataloader)) from LeNet import LeNet net = LeNet() print(net) # some example https://neurohive.io/ru/tutorial/cnn-na-pytorch/ from torch.nn import CrossEntropyLoss from torch.optim import SGD criterion = CrossEntropyLoss() optimizer = SGD(net.parameters(), lr=0.005, momentum=0.9) print(criterion) print(optimizer) # INIT_LR = 2*1e-3 # BS = 64 # Training from torch import device device = device("cuda:0" if torch.cuda.is_available() else "cpu") print(device) net.to(device) NUM_EPOCHS = 10 for epoch in range(NUM_EPOCHS): net.train() train_loss = 0 correct, total = 0, 0 correct_test, total_test = 0, 0 train_loss = 0.0 for batch_idx, (inputs, targets) in enumerate(train_dataloader): inputs, targets = inputs.to(device), targets.to(device) optimizer.zero_grad() outputs = net(inputs) loss = criterion(outputs, targets) loss.backward() optimizer.step() train_loss += loss.item() _, predicted = outputs.max(1) total += targets.size(0) correct += predicted.eq(targets).sum().item() # if batch_idx % 100 == 99: # print every 2000 mini-batches # print('[%d, %5d] loss: %.3f' % # (epoch + 1, i + 1, running_loss / 2000)) with torch.no_grad(): for batch_idx, (inputs, targets) in enumerate(test_dataloader): inputs, targets = inputs.to(device), targets.to(device) outputs = net(inputs) _, predicted = outputs.max(1) total_test += targets.size(0) correct_test += (predicted == targets).sum().item() print('Epoch: %d/%d' % (epoch+1,NUM_EPOCHS)) print('Loss: %.3f Acc: %.3f %%' % ((train_loss),(100.*correct/total))) correct, total = 0,0 print('Accuracy test images: %d %%' % ( 100 * correct_test / total_test)) # progress_bar(batch_idx, len(train_dataloader), 'Loss: %.3f | Acc: %.3f%% (%d/%d)' % # (train_loss/(batch_idx+1), 100.*correct/total, correct, total)) print("finifh training") # lets test with torch.no_grad(): for batch_idx, (inputs, targets) in enumerate(train_dataloader): inputs, targets = inputs.to(device), targets.to(device) outputs = net(inputs) _, predicted = torch.max(outputs.data, 1) total += targets.size(0) correct += (predicted == targets).sum().item() print('Accuracy of the network on train images: %d %%' % ( 100 * correct / total)) correct, total = 0,0 with torch.no_grad(): for batch_idx, (inputs, targets) in enumerate(test_dataloader): inputs, targets = inputs.to(device), targets.to(device) outputs = net(inputs) _, predicted = torch.max(outputs.data, 1) total += targets.size(0) correct += (predicted == targets).sum().item() print('Accuracy of the network on test images: %d %%' % ( 100 * correct / total)) correct, total = 0,0 with torch.no_grad(): for batch_idx, (inputs, targets) in enumerate(valid_dataloader): inputs, targets = inputs.to(device), targets.to(device) outputs = net(inputs) _, predicted = torch.max(outputs.data, 1) total += targets.size(0) correct += (predicted == targets).sum().item() print('Accuracy of the network valid images: %d %%' % ( 100 * correct / total)) print(correct) print(total) print(net)
[ "torch.utils.data.DataLoader", "torch.nn.CrossEntropyLoss", "LeNet.LeNet", "pickle.load", "numpy.where", "Dataset.SignDataset", "cv2.normalize" ]
[((2092, 2132), 'Dataset.SignDataset', 'SignDataset', (['X_train', 'y_train', 'n_classes'], {}), '(X_train, y_train, n_classes)\n', (2103, 2132), False, 'from Dataset import SignDataset\n'), ((2148, 2186), 'Dataset.SignDataset', 'SignDataset', (['X_test', 'y_test', 'n_classes'], {}), '(X_test, y_test, n_classes)\n', (2159, 2186), False, 'from Dataset import SignDataset\n'), ((2203, 2243), 'Dataset.SignDataset', 'SignDataset', (['X_valid', 'y_valid', 'n_classes'], {}), '(X_valid, y_valid, n_classes)\n', (2214, 2243), False, 'from Dataset import SignDataset\n'), ((2321, 2392), 'torch.utils.data.DataLoader', 'DataLoader', (['train_dataset'], {'batch_size': '(128)', 'shuffle': '(True)', 'num_workers': '(10)'}), '(train_dataset, batch_size=128, shuffle=True, num_workers=10)\n', (2331, 2392), False, 'from torch.utils.data import DataLoader\n'), ((2411, 2481), 'torch.utils.data.DataLoader', 'DataLoader', (['test_dataset'], {'batch_size': '(128)', 'shuffle': '(True)', 'num_workers': '(10)'}), '(test_dataset, batch_size=128, shuffle=True, num_workers=10)\n', (2421, 2481), False, 'from torch.utils.data import DataLoader\n'), ((2501, 2572), 'torch.utils.data.DataLoader', 'DataLoader', (['valid_dataset'], {'batch_size': '(128)', 'shuffle': '(True)', 'num_workers': '(10)'}), '(valid_dataset, batch_size=128, shuffle=True, num_workers=10)\n', (2511, 2572), False, 'from torch.utils.data import DataLoader\n'), ((2633, 2640), 'LeNet.LeNet', 'LeNet', ([], {}), '()\n', (2638, 2640), False, 'from LeNet import LeNet\n'), ((2795, 2813), 'torch.nn.CrossEntropyLoss', 'CrossEntropyLoss', ([], {}), '()\n', (2811, 2813), False, 'from torch.nn import CrossEntropyLoss\n'), ((284, 298), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (295, 298), False, 'import pickle\n'), ((355, 369), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (366, 369), False, 'import pickle\n'), ((422, 436), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (433, 436), False, 'import pickle\n'), ((1233, 1255), 'numpy.where', 'np.where', (['(y_valid == i)'], {}), '(y_valid == i)\n', (1241, 1255), True, 'import numpy as np\n'), ((1466, 1538), 'cv2.normalize', 'cv2.normalize', (['X_train[i]', 'X_train[i]', '(0)', '(255)'], {'norm_type': 'cv2.NORM_MINMAX'}), '(X_train[i], X_train[i], 0, 255, norm_type=cv2.NORM_MINMAX)\n', (1479, 1538), False, 'import cv2\n'), ((1573, 1645), 'cv2.normalize', 'cv2.normalize', (['X_valid[i]', 'X_valid[i]', '(0)', '(255)'], {'norm_type': 'cv2.NORM_MINMAX'}), '(X_valid[i], X_valid[i], 0, 255, norm_type=cv2.NORM_MINMAX)\n', (1586, 1645), False, 'import cv2\n'), ((1679, 1749), 'cv2.normalize', 'cv2.normalize', (['X_test[i]', 'X_test[i]', '(0)', '(255)'], {'norm_type': 'cv2.NORM_MINMAX'}), '(X_test[i], X_test[i], 0, 255, norm_type=cv2.NORM_MINMAX)\n', (1692, 1749), False, 'import cv2\n'), ((1814, 1836), 'numpy.where', 'np.where', (['(y_valid == i)'], {}), '(y_valid == i)\n', (1822, 1836), True, 'import numpy as np\n')]
# -*- coding: utf-8 -*- """img-grid-processing.ipynb Automatically generated by Colaboratory. Original file is located at https://colab.research.google.com/drive/1rrkKK1WGrbCC5TnJSGX8772RCMdavj-L """ from google.colab import drive drive.mount('/content/drive') import os import PIL img_dir = "/content/drive/MyDrive/....." img_list = os.listdir(img_dir) img_count = len(img_list) print('Images: ', img_list) print('Images Count: ', img_count) PIL.Image.open("/content/drive/MyDrive/...../00001.jpg") import numpy as np import matplotlib.pyplot as plt w = 35 h = 35 load_img = lambda filename: np.array(PIL.Image.open(f"/content/drive/MyDrive/....../{filename}").resize((100,100))) _, axes_list = plt.subplots(h, w, figsize=(w, h), gridspec_kw={'wspace':0, 'hspace':0}) for axes in axes_list: for ax in axes: ax.axis('off') img = np.random.choice(img_list) ax.imshow(load_img(img)) plt.savefig(f"{img_dir}/abcdef.jpg")
[ "PIL.Image.open", "numpy.random.choice", "google.colab.drive.mount", "matplotlib.pyplot.subplots", "os.listdir", "matplotlib.pyplot.savefig" ]
[((238, 267), 'google.colab.drive.mount', 'drive.mount', (['"""/content/drive"""'], {}), "('/content/drive')\n", (249, 267), False, 'from google.colab import drive\n'), ((345, 364), 'os.listdir', 'os.listdir', (['img_dir'], {}), '(img_dir)\n', (355, 364), False, 'import os\n'), ((455, 511), 'PIL.Image.open', 'PIL.Image.open', (['"""/content/drive/MyDrive/...../00001.jpg"""'], {}), "('/content/drive/MyDrive/...../00001.jpg')\n", (469, 511), False, 'import PIL\n'), ((713, 787), 'matplotlib.pyplot.subplots', 'plt.subplots', (['h', 'w'], {'figsize': '(w, h)', 'gridspec_kw': "{'wspace': 0, 'hspace': 0}"}), "(h, w, figsize=(w, h), gridspec_kw={'wspace': 0, 'hspace': 0})\n", (725, 787), True, 'import matplotlib.pyplot as plt\n'), ((919, 955), 'matplotlib.pyplot.savefig', 'plt.savefig', (['f"""{img_dir}/abcdef.jpg"""'], {}), "(f'{img_dir}/abcdef.jpg')\n", (930, 955), True, 'import matplotlib.pyplot as plt\n'), ((857, 883), 'numpy.random.choice', 'np.random.choice', (['img_list'], {}), '(img_list)\n', (873, 883), True, 'import numpy as np\n'), ((618, 677), 'PIL.Image.open', 'PIL.Image.open', (['f"""/content/drive/MyDrive/....../{filename}"""'], {}), "(f'/content/drive/MyDrive/....../{filename}')\n", (632, 677), False, 'import PIL\n')]
from typing import Dict import matplotlib.pyplot as plt import numpy as np from IPython.core.display import display from matplotlib.ticker import FormatStrFormatter, MaxNLocator from mpl_toolkits.mplot3d import Axes3D from plotly import offline as plotly, graph_objs as go, tools PLOT_TYPES = {'random', 'grid', 'exploration', 'exploitation', 'initialisation', 'default', 'user-defined'} class ChartPlotter: def __init__(self, plot_types_and_colours: Dict, minimise: bool = False, use_3d_plot: bool = False, plot_best_scores_on_left: bool = True): assert PLOT_TYPES <= set(plot_types_and_colours.keys()) self.plot_types_and_colours = plot_types_and_colours self.minimise = minimise self.use_3d_plot = use_3d_plot self.plot_best_scores_on_left = plot_best_scores_on_left self._2d_plot_column = 1 if plot_best_scores_on_left else 2 self._3d_plot_column = 2 if plot_best_scores_on_left else 1 def start_update(self): raise NotImplementedError() def update_display(self): raise NotImplementedError() def plot_best_scores(self, iterations, best_scores): raise NotImplementedError() def plot_scores_by_type(self, configuration_type: str, colour: str, iterations, scores): raise NotImplementedError() def plot_3d_scores_by_type(self, configuration_type: str, colour: str, x_values, y_values, z_values): raise NotImplementedError() def plot_3d_surface(self, X, Y, Z): raise NotImplementedError() def plot_3d_target(self, target_x, target_y, target_z): raise NotImplementedError() class PlotlyChartPlotter(ChartPlotter): def __init__(self, minimise: bool = None, use_3d_plot: bool = None, plot_best_scores_on_left: bool = None): plot_types_and_colours = { 'random': 'red', 'grid': 'black', 'exploration': 'orange', 'initialisation': 'orange', 'exploitation': 'blue', 'default': 'cyan', 'user-defined': 'black' } super().__init__(plot_types_and_colours, minimise, use_3d_plot, plot_best_scores_on_left) plotly.init_notebook_mode(connected=True) self.camera = dict( # up=dict(x=0, y=0, z=1), # center=dict(x=0, y=0, z=0), eye=dict(x=1.5, y=1.5, z=0.8) ) def start_update(self): is_3d_left = self.use_3d_plot and not self.plot_best_scores_on_left is_3d_right = self.use_3d_plot and self.plot_best_scores_on_left self.fig = tools.make_subplots(rows=1, cols=2, specs=[[{'is_3d': is_3d_left}, {'is_3d': is_3d_right}]], print_grid=False) def update_display(self): plotly.iplot(self.fig, filename='plotly/graphs') def plot_best_scores(self, iterations, best_scores): best_score_plot = go.Scatter( x=iterations, y=best_scores, name='Best so far', mode='lines', line=dict( color='green' ) ) self.add_2d_plot(best_score_plot) yaxis_config = {'title': 'Score'} if self.minimise: yaxis_config['autorange'] = 'reversed' if all(score >= 0 for score in best_scores): yaxis_config['type'] = 'log' self.fig['layout']['yaxis1'].update(yaxis_config) self.fig['layout']['xaxis1'].update({'title': 'Iterations'}) self.fig['layout']['legend'].update({'x': 0.45, 'y': 1}) def plot_scores_by_type(self, configuration_type: str, colour: str, iterations, scores): configuration_type_plot = go.Scatter( x=iterations, y=scores, mode='markers', name=configuration_type, marker=dict( color=colour ) ) self.add_2d_plot(configuration_type_plot) def add_2d_plot(self, plot): self.fig.append_trace(plot, 1, self._2d_plot_column) def add_3d_plot(self, plot): self.fig.append_trace(plot, 1, self._3d_plot_column) def plot_3d_scores_by_type(self, configuration_type: str, colour: str, x_values, y_values, z_values): surface_plot = go.Scatter3d( x=x_values, y=y_values, z=z_values, mode='markers', name=configuration_type.capitalize(), showlegend=False, marker=dict( color=colour, size=4 ) ) flat_plot = go.Scatter3d( x=x_values, y=y_values, z=[0] * len(z_values), mode='markers', name=configuration_type.capitalize(), showlegend=False, marker=dict( color=colour, size=4 ) ) self.add_3d_plot(surface_plot) self.add_3d_plot(flat_plot) def plot_3d_surface(self, X, Y, Z): surface_plot = dict(type='surface', x=X, y=Y, z=Z, colorscale='Jet', opacity=0.5, showscale=False) contour_plot = dict(type='surface', x=X, y=Y, z=np.zeros(Z.shape), colorscale='Jet', surfacecolor=Z, opacity=0.75, showscale=False) self.add_3d_plot(surface_plot) self.add_3d_plot(contour_plot) self.fig['layout']['scene1'].update({'camera': self.camera}) def plot_3d_target(self, target_x, target_y, target_z): target_score_plot = go.Scatter3d( x=[target_x], y=[target_y], z=[target_z], mode='markers', name='Target', marker=dict( color='green', size=6 ) ) self.add_3d_plot(target_score_plot) class MatPlotLibPlotter(ChartPlotter): def __init__(self, minimise: bool = None, use_3d_plot: bool = None, plot_best_scores_on_left: bool = None): plot_types_and_colours = { 'random': 'k', 'grid': 'k', 'exploration': 'm', 'initialisation': 'm', 'exploitation': 'b', 'default': 'c', 'user-defined': 'k' } super().__init__(plot_types_and_colours, minimise, use_3d_plot, plot_best_scores_on_left) def start_update(self): plt.clf() self.fig = plt.figure(figsize=(20, 10)) self.ax = self.fig.add_subplot(1, 2, self._2d_plot_column) def update_display(self): if self.use_3d_plot: self.ax3d.legend(loc='upper right', bbox_to_anchor=(0.11, 1)) else: self.ax.legend() display(plt.gcf()) plt.close('all') def plot_best_scores(self, iterations, best_scores): if self.minimise: self.ax.invert_yaxis() self.ax.yaxis.set_major_formatter(FormatStrFormatter('%d')) if all(score >= 0 for score in best_scores): self.ax.set_yscale('log') self.ax.set_ylabel('Score') self.ax.xaxis.set_major_locator(MaxNLocator(integer=True)) self.ax.set_xlabel('Iterations') self.ax.plot(best_scores, 'g', label='Best so far') def plot_scores_by_type(self, configuration_type: str, colour: str, iterations, scores): self.ax.plot(iterations, scores, 'o' + colour, label=configuration_type) def plot_3d_scores_by_type(self, configuration_type: str, colour: str, x_values, y_values, z_values): self.ax3d.scatter(x_values, y_values, z_values, c=colour, marker='o', zorder=10, label=configuration_type) self.ax3d.scatter(x_values, y_values, 0, c=colour, marker='o', zorder=10) def plot_3d_surface(self, X, Y, Z): self.ax3d = self.make_3d_axis() self.ax3d.view_init(15, 45) surface_plot = self.ax3d.plot_surface(X, Y, Z, cmap=plt.get_cmap('coolwarm'), zorder=2, rstride=1, cstride=1) surface_plot.set_alpha(0.25) self.ax3d.contourf(X, Y, Z, 50, zdir='z', offset=0, cmap=plt.get_cmap('coolwarm'), zorder=1) def plot_3d_target(self, target_x, target_y, target_z): self.ax3d.scatter([target_x], [target_y], [target_z], c='g', zorder=5, marker='o', label='Best') def make_3d_axis(self) -> Axes3D: return self.fig.add_subplot(1, 2, self._3d_plot_column, projection='3d')
[ "plotly.offline.iplot", "matplotlib.pyplot.get_cmap", "matplotlib.pyplot.clf", "matplotlib.pyplot.close", "matplotlib.ticker.MaxNLocator", "numpy.zeros", "matplotlib.pyplot.figure", "matplotlib.ticker.FormatStrFormatter", "plotly.tools.make_subplots", "plotly.offline.init_notebook_mode", "matplotlib.pyplot.gcf" ]
[((2187, 2228), 'plotly.offline.init_notebook_mode', 'plotly.init_notebook_mode', ([], {'connected': '(True)'}), '(connected=True)\n', (2212, 2228), True, 'from plotly import offline as plotly, graph_objs as go, tools\n'), ((2586, 2700), 'plotly.tools.make_subplots', 'tools.make_subplots', ([], {'rows': '(1)', 'cols': '(2)', 'specs': "[[{'is_3d': is_3d_left}, {'is_3d': is_3d_right}]]", 'print_grid': '(False)'}), "(rows=1, cols=2, specs=[[{'is_3d': is_3d_left}, {'is_3d':\n is_3d_right}]], print_grid=False)\n", (2605, 2700), False, 'from plotly import offline as plotly, graph_objs as go, tools\n'), ((2775, 2823), 'plotly.offline.iplot', 'plotly.iplot', (['self.fig'], {'filename': '"""plotly/graphs"""'}), "(self.fig, filename='plotly/graphs')\n", (2787, 2823), True, 'from plotly import offline as plotly, graph_objs as go, tools\n'), ((6383, 6392), 'matplotlib.pyplot.clf', 'plt.clf', ([], {}), '()\n', (6390, 6392), True, 'import matplotlib.pyplot as plt\n'), ((6412, 6440), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(20, 10)'}), '(figsize=(20, 10))\n', (6422, 6440), True, 'import matplotlib.pyplot as plt\n'), ((6721, 6737), 'matplotlib.pyplot.close', 'plt.close', (['"""all"""'], {}), "('all')\n", (6730, 6737), True, 'import matplotlib.pyplot as plt\n'), ((6702, 6711), 'matplotlib.pyplot.gcf', 'plt.gcf', ([], {}), '()\n', (6709, 6711), True, 'import matplotlib.pyplot as plt\n'), ((7106, 7131), 'matplotlib.ticker.MaxNLocator', 'MaxNLocator', ([], {'integer': '(True)'}), '(integer=True)\n', (7117, 7131), False, 'from matplotlib.ticker import FormatStrFormatter, MaxNLocator\n'), ((5196, 5213), 'numpy.zeros', 'np.zeros', (['Z.shape'], {}), '(Z.shape)\n', (5204, 5213), True, 'import numpy as np\n'), ((6903, 6927), 'matplotlib.ticker.FormatStrFormatter', 'FormatStrFormatter', (['"""%d"""'], {}), "('%d')\n", (6921, 6927), False, 'from matplotlib.ticker import FormatStrFormatter, MaxNLocator\n'), ((7891, 7915), 'matplotlib.pyplot.get_cmap', 'plt.get_cmap', (['"""coolwarm"""'], {}), "('coolwarm')\n", (7903, 7915), True, 'import matplotlib.pyplot as plt\n'), ((8051, 8075), 'matplotlib.pyplot.get_cmap', 'plt.get_cmap', (['"""coolwarm"""'], {}), "('coolwarm')\n", (8063, 8075), True, 'import matplotlib.pyplot as plt\n')]
from __future__ import absolute_import from __future__ import division from __future__ import print_function from six.moves import range import os import logging logging.basicConfig(level=logging.DEBUG) import sys #sys.stdout = sys.stderr # Prevent reaching to maximum recursion depth in `theano.tensor.grad` #sys.setrecursionlimit(2 ** 20) import numpy as np np.random.seed(2 ** 10) from tensorflow.keras.datasets import cifar10 from tensorflow.keras.models import Model from tensorflow.keras.layers import Conv2D, AveragePooling2D, BatchNormalization, Dropout, Input, Activation, Add, Dense, Flatten from tensorflow.keras.optimizers import SGD from tensorflow.keras.regularizers import l2 from tensorflow.keras.callbacks import LearningRateScheduler, ModelCheckpoint from tensorflow.keras.preprocessing.image import ImageDataGenerator from tensorflow.keras.utils import to_categorical from tensorflow.keras import backend as K from utils import mk_dir # ================================================ # DATA CONFIGURATION: logging.debug("Loading data...") nb_classes = 10 image_size = 32 (X_train, y_train), (X_test, y_test) = cifar10.load_data() X_train = X_train.astype('float32') X_test = X_test.astype('float32') # convert class vectors to binary class matrices Y_train = to_categorical(y_train, nb_classes) Y_test = to_categorical(y_test, nb_classes) # ================================================ # ================================================ # NETWORK/TRAINING CONFIGURATION: logging.debug("Loading network/training configuration...") depth = 28 # table 5 on page 8 indicates best value (4.17) CIFAR-10 k = 10 # 'widen_factor'; table 5 on page 8 indicates best value (4.17) CIFAR-10 dropout_probability = 0 # table 6 on page 10 indicates best value (4.17) CIFAR-10 weight_decay = 0.0005 # page 10: "Used in all experiments" batch_size = 128 # page 8: "Used in all experiments" # Regarding nb_epochs, lr_schedule and sgd, see bottom page 10: nb_epochs = 200 lr_schedule = [60, 120, 160] # epoch_step def schedule(epoch_idx): if (epoch_idx + 1) < lr_schedule[0]: return 0.1 elif (epoch_idx + 1) < lr_schedule[1]: return 0.02 # lr_decay_ratio = 0.2 elif (epoch_idx + 1) < lr_schedule[2]: return 0.004 return 0.0008 sgd = SGD(lr=0.1, momentum=0.9, nesterov=True) # Other config from code; throughtout all layer: use_bias = False # following functions 'FCinit(model)' and 'DisableBias(model)' in utils.lua weight_init="he_normal" # follows the 'MSRinit(model)' function in utils.lua # Keras specific if K.image_data_format() == "th": logging.debug("image_dim_ordering = 'th'") channel_axis = 1 input_shape = (3, image_size, image_size) else: logging.debug("image_dim_ordering = 'tf'") channel_axis = -1 input_shape = (image_size, image_size, 3) # ================================================ # ================================================ # OUTPUT CONFIGURATION: print_model_summary = True save_model = True save_model_plot = False MODEL_PATH = os.environ.get('MODEL_PATH', 'models/') CHECKPOINT_PATH = os.environ.get('CHECKPOINT_PATH', 'checkpoints/') # ================================================ # Wide residual network http://arxiv.org/abs/1605.07146 def _wide_basic(n_input_plane, n_output_plane, stride): def f(net): # format of conv_params: # [ [nb_col="kernel width", nb_row="kernel height", # subsample="(stride_vertical,stride_horizontal)", # border_mode="same" or "valid"] ] # B(3,3): orignal <<basic>> block conv_params = [ [3,3,stride,"same"], [3,3,(1,1),"same"] ] n_bottleneck_plane = n_output_plane # Residual block for i, v in enumerate(conv_params): if i == 0: if n_input_plane != n_output_plane: net = BatchNormalization(axis=channel_axis)(net) net = Activation("relu")(net) convs = net else: convs = BatchNormalization(axis=channel_axis)(net) convs = Activation("relu")(convs) convs = Conv2D(n_bottleneck_plane, (v[0],v[1]), strides=v[2], padding=v[3], kernel_initializer=weight_init, kernel_regularizer=l2(weight_decay), use_bias=use_bias)(convs) else: convs = BatchNormalization(axis=channel_axis)(convs) convs = Activation("relu")(convs) if dropout_probability > 0: convs = Dropout(dropout_probability)(convs) convs = Conv2D(n_bottleneck_plane, (v[0],v[1]), strides=v[2], padding=v[3], kernel_initializer=weight_init, kernel_regularizer=l2(weight_decay), use_bias=use_bias)(convs) # Shortcut Conntection: identity function or 1x1 convolutional # (depends on difference between input & output shape - this # corresponds to whether we are using the first block in each # group; see _layer() ). if n_input_plane != n_output_plane: shortcut = Conv2D(n_output_plane, (1,1), strides=stride, padding="same", kernel_initializer=weight_init, kernel_regularizer=l2(weight_decay), use_bias=use_bias)(net) else: shortcut = net return Add()([convs, shortcut]) return f # "Stacking Residual Units on the same stage" def _layer(block, n_input_plane, n_output_plane, count, stride): def f(net): net = block(n_input_plane, n_output_plane, stride)(net) for i in range(2,int(count+1)): net = block(n_output_plane, n_output_plane, stride=(1,1))(net) return net return f def create_model(): logging.debug("Creating model...") assert((depth - 4) % 6 == 0) n = (depth - 4) / 6 inputs = Input(shape=input_shape) n_stages=[16, 16*k, 32*k, 64*k] conv1 = Conv2D(n_stages[0], (3, 3), strides=1, padding="same", kernel_initializer=weight_init, kernel_regularizer=l2(weight_decay), use_bias=use_bias)(inputs) # "One conv at the beginning (spatial size: 32x32)" # Add wide residual blocks block_fn = _wide_basic conv2 = _layer(block_fn, n_input_plane=n_stages[0], n_output_plane=n_stages[1], count=n, stride=(1,1))(conv1)# "Stage 1 (spatial size: 32x32)" conv3 = _layer(block_fn, n_input_plane=n_stages[1], n_output_plane=n_stages[2], count=n, stride=(2,2))(conv2)# "Stage 2 (spatial size: 16x16)" conv4 = _layer(block_fn, n_input_plane=n_stages[2], n_output_plane=n_stages[3], count=n, stride=(2,2))(conv3)# "Stage 3 (spatial size: 8x8)" batch_norm = BatchNormalization(axis=channel_axis)(conv4) relu = Activation("relu")(batch_norm) # Classifier block pool = AveragePooling2D(pool_size=(8, 8), strides=(1, 1), padding="same")(relu) flatten = Flatten()(pool) predictions = Dense(units=nb_classes, kernel_initializer=weight_init, use_bias=use_bias, kernel_regularizer=l2(weight_decay), activation="softmax")(flatten) model = Model(inputs=inputs, outputs=predictions) return model if __name__ == '__main__': model = create_model() model.compile(optimizer=sgd, loss="categorical_crossentropy", metrics=['accuracy']) if print_model_summary: logging.debug("Model summary...") model.count_params() model.summary() if save_model_plot: logging.debug("Saving model plot...") mk_dir(MODEL_PATH) from tensorflow.keras.utils import plot_model plot_model(model, to_file=os.path.join(MODEL_PATH, 'WRN-{0}-{1}.png'.format(depth, k)), show_shapes=True) # Data Augmentation based on page 6 (see README for full details) logging.debug("Creating ImageDataGenerators...") train_datagen = ImageDataGenerator( featurewise_center=True, featurewise_std_normalization=True, zca_whitening=True, horizontal_flip=True) train_datagen.fit(X_train, augment=True, rounds=2) test_datagen = ImageDataGenerator( featurewise_center=True, featurewise_std_normalization=True, zca_whitening=True) test_datagen.fit(X_train) mk_dir(CHECKPOINT_PATH) callbacks = [ LearningRateScheduler(schedule=schedule), ModelCheckpoint(CHECKPOINT_PATH+'/weights.{epoch:02d}-{val_loss:.2f}.hdf5', monitor='val_loss', verbose=1, save_best_only=True, mode='auto') ] logging.debug("Running training...") # fit the model on the batches generated by train_datagen.flow() model.fit(train_datagen.flow(X_train, Y_train, batch_size=batch_size, shuffle=True), steps_per_epoch=X_train.shape[0]/batch_size, epochs=nb_epochs, validation_data=test_datagen.flow(X_test, Y_test, batch_size=batch_size), callbacks=callbacks) if save_model: logging.debug("Saving model...") mk_dir(MODEL_PATH) model.save(os.path.join(MODEL_PATH, 'WRN-{0}-{1}.h5'.format(depth, k)), overwrite=True)
[ "tensorflow.keras.preprocessing.image.ImageDataGenerator", "numpy.random.seed", "tensorflow.keras.optimizers.SGD", "tensorflow.keras.callbacks.ModelCheckpoint", "tensorflow.keras.layers.Flatten", "tensorflow.keras.regularizers.l2", "tensorflow.keras.layers.BatchNormalization", "tensorflow.keras.layers.Activation", "tensorflow.keras.layers.Input", "tensorflow.keras.utils.to_categorical", "tensorflow.keras.layers.AveragePooling2D", "tensorflow.keras.layers.Dropout", "tensorflow.keras.models.Model", "tensorflow.keras.callbacks.LearningRateScheduler", "utils.mk_dir", "tensorflow.keras.backend.image_data_format", "logging.debug", "logging.basicConfig", "tensorflow.keras.datasets.cifar10.load_data", "os.environ.get", "tensorflow.keras.layers.Add" ]
[((164, 204), 'logging.basicConfig', 'logging.basicConfig', ([], {'level': 'logging.DEBUG'}), '(level=logging.DEBUG)\n', (183, 204), False, 'import logging\n'), ((364, 387), 'numpy.random.seed', 'np.random.seed', (['(2 ** 10)'], {}), '(2 ** 10)\n', (378, 387), True, 'import numpy as np\n'), ((1034, 1066), 'logging.debug', 'logging.debug', (['"""Loading data..."""'], {}), "('Loading data...')\n", (1047, 1066), False, 'import logging\n'), ((1140, 1159), 'tensorflow.keras.datasets.cifar10.load_data', 'cifar10.load_data', ([], {}), '()\n', (1157, 1159), False, 'from tensorflow.keras.datasets import cifar10\n'), ((1290, 1325), 'tensorflow.keras.utils.to_categorical', 'to_categorical', (['y_train', 'nb_classes'], {}), '(y_train, nb_classes)\n', (1304, 1325), False, 'from tensorflow.keras.utils import to_categorical\n'), ((1335, 1369), 'tensorflow.keras.utils.to_categorical', 'to_categorical', (['y_test', 'nb_classes'], {}), '(y_test, nb_classes)\n', (1349, 1369), False, 'from tensorflow.keras.utils import to_categorical\n'), ((1507, 1565), 'logging.debug', 'logging.debug', (['"""Loading network/training configuration..."""'], {}), "('Loading network/training configuration...')\n", (1520, 1565), False, 'import logging\n'), ((2330, 2370), 'tensorflow.keras.optimizers.SGD', 'SGD', ([], {'lr': '(0.1)', 'momentum': '(0.9)', 'nesterov': '(True)'}), '(lr=0.1, momentum=0.9, nesterov=True)\n', (2333, 2370), False, 'from tensorflow.keras.optimizers import SGD\n'), ((3095, 3134), 'os.environ.get', 'os.environ.get', (['"""MODEL_PATH"""', '"""models/"""'], {}), "('MODEL_PATH', 'models/')\n", (3109, 3134), False, 'import os\n'), ((3153, 3202), 'os.environ.get', 'os.environ.get', (['"""CHECKPOINT_PATH"""', '"""checkpoints/"""'], {}), "('CHECKPOINT_PATH', 'checkpoints/')\n", (3167, 3202), False, 'import os\n'), ((2619, 2640), 'tensorflow.keras.backend.image_data_format', 'K.image_data_format', ([], {}), '()\n', (2638, 2640), True, 'from tensorflow.keras import backend as K\n'), ((2654, 2696), 'logging.debug', 'logging.debug', (['"""image_dim_ordering = \'th\'"""'], {}), '("image_dim_ordering = \'th\'")\n', (2667, 2696), False, 'import logging\n'), ((2774, 2816), 'logging.debug', 'logging.debug', (['"""image_dim_ordering = \'tf\'"""'], {}), '("image_dim_ordering = \'tf\'")\n', (2787, 2816), False, 'import logging\n'), ((6374, 6408), 'logging.debug', 'logging.debug', (['"""Creating model..."""'], {}), "('Creating model...')\n", (6387, 6408), False, 'import logging\n'), ((6489, 6513), 'tensorflow.keras.layers.Input', 'Input', ([], {'shape': 'input_shape'}), '(shape=input_shape)\n', (6494, 6513), False, 'from tensorflow.keras.layers import Conv2D, AveragePooling2D, BatchNormalization, Dropout, Input, Activation, Add, Dense, Flatten\n'), ((7873, 7914), 'tensorflow.keras.models.Model', 'Model', ([], {'inputs': 'inputs', 'outputs': 'predictions'}), '(inputs=inputs, outputs=predictions)\n', (7878, 7914), False, 'from tensorflow.keras.models import Model\n'), ((8549, 8597), 'logging.debug', 'logging.debug', (['"""Creating ImageDataGenerators..."""'], {}), "('Creating ImageDataGenerators...')\n", (8562, 8597), False, 'import logging\n'), ((8618, 8744), 'tensorflow.keras.preprocessing.image.ImageDataGenerator', 'ImageDataGenerator', ([], {'featurewise_center': '(True)', 'featurewise_std_normalization': '(True)', 'zca_whitening': '(True)', 'horizontal_flip': '(True)'}), '(featurewise_center=True, featurewise_std_normalization=\n True, zca_whitening=True, horizontal_flip=True)\n', (8636, 8744), False, 'from tensorflow.keras.preprocessing.image import ImageDataGenerator\n'), ((8944, 9048), 'tensorflow.keras.preprocessing.image.ImageDataGenerator', 'ImageDataGenerator', ([], {'featurewise_center': '(True)', 'featurewise_std_normalization': '(True)', 'zca_whitening': '(True)'}), '(featurewise_center=True, featurewise_std_normalization=\n True, zca_whitening=True)\n', (8962, 9048), False, 'from tensorflow.keras.preprocessing.image import ImageDataGenerator\n'), ((9143, 9166), 'utils.mk_dir', 'mk_dir', (['CHECKPOINT_PATH'], {}), '(CHECKPOINT_PATH)\n', (9149, 9166), False, 'from utils import mk_dir\n'), ((9510, 9546), 'logging.debug', 'logging.debug', (['"""Running training..."""'], {}), "('Running training...')\n", (9523, 9546), False, 'import logging\n'), ((7406, 7443), 'tensorflow.keras.layers.BatchNormalization', 'BatchNormalization', ([], {'axis': 'channel_axis'}), '(axis=channel_axis)\n', (7424, 7443), False, 'from tensorflow.keras.layers import Conv2D, AveragePooling2D, BatchNormalization, Dropout, Input, Activation, Add, Dense, Flatten\n'), ((7462, 7480), 'tensorflow.keras.layers.Activation', 'Activation', (['"""relu"""'], {}), "('relu')\n", (7472, 7480), False, 'from tensorflow.keras.layers import Conv2D, AveragePooling2D, BatchNormalization, Dropout, Input, Activation, Add, Dense, Flatten\n'), ((7572, 7638), 'tensorflow.keras.layers.AveragePooling2D', 'AveragePooling2D', ([], {'pool_size': '(8, 8)', 'strides': '(1, 1)', 'padding': '"""same"""'}), "(pool_size=(8, 8), strides=(1, 1), padding='same')\n", (7588, 7638), False, 'from tensorflow.keras.layers import Conv2D, AveragePooling2D, BatchNormalization, Dropout, Input, Activation, Add, Dense, Flatten\n'), ((7659, 7668), 'tensorflow.keras.layers.Flatten', 'Flatten', ([], {}), '()\n', (7666, 7668), False, 'from tensorflow.keras.layers import Conv2D, AveragePooling2D, BatchNormalization, Dropout, Input, Activation, Add, Dense, Flatten\n'), ((8113, 8146), 'logging.debug', 'logging.debug', (['"""Model summary..."""'], {}), "('Model summary...')\n", (8126, 8146), False, 'import logging\n'), ((8233, 8270), 'logging.debug', 'logging.debug', (['"""Saving model plot..."""'], {}), "('Saving model plot...')\n", (8246, 8270), False, 'import logging\n'), ((8279, 8297), 'utils.mk_dir', 'mk_dir', (['MODEL_PATH'], {}), '(MODEL_PATH)\n', (8285, 8297), False, 'from utils import mk_dir\n'), ((9185, 9225), 'tensorflow.keras.callbacks.LearningRateScheduler', 'LearningRateScheduler', ([], {'schedule': 'schedule'}), '(schedule=schedule)\n', (9206, 9225), False, 'from tensorflow.keras.callbacks import LearningRateScheduler, ModelCheckpoint\n'), ((9245, 9396), 'tensorflow.keras.callbacks.ModelCheckpoint', 'ModelCheckpoint', (["(CHECKPOINT_PATH + '/weights.{epoch:02d}-{val_loss:.2f}.hdf5')"], {'monitor': '"""val_loss"""', 'verbose': '(1)', 'save_best_only': '(True)', 'mode': '"""auto"""'}), "(CHECKPOINT_PATH +\n '/weights.{epoch:02d}-{val_loss:.2f}.hdf5', monitor='val_loss', verbose\n =1, save_best_only=True, mode='auto')\n", (9260, 9396), False, 'from tensorflow.keras.callbacks import LearningRateScheduler, ModelCheckpoint\n'), ((9994, 10026), 'logging.debug', 'logging.debug', (['"""Saving model..."""'], {}), "('Saving model...')\n", (10007, 10026), False, 'import logging\n'), ((10035, 10053), 'utils.mk_dir', 'mk_dir', (['MODEL_PATH'], {}), '(MODEL_PATH)\n', (10041, 10053), False, 'from utils import mk_dir\n'), ((5960, 5965), 'tensorflow.keras.layers.Add', 'Add', ([], {}), '()\n', (5963, 5965), False, 'from tensorflow.keras.layers import Conv2D, AveragePooling2D, BatchNormalization, Dropout, Input, Activation, Add, Dense, Flatten\n'), ((6773, 6789), 'tensorflow.keras.regularizers.l2', 'l2', (['weight_decay'], {}), '(weight_decay)\n', (6775, 6789), False, 'from tensorflow.keras.regularizers import l2\n'), ((7811, 7827), 'tensorflow.keras.regularizers.l2', 'l2', (['weight_decay'], {}), '(weight_decay)\n', (7813, 7827), False, 'from tensorflow.keras.regularizers import l2\n'), ((4670, 4707), 'tensorflow.keras.layers.BatchNormalization', 'BatchNormalization', ([], {'axis': 'channel_axis'}), '(axis=channel_axis)\n', (4688, 4707), False, 'from tensorflow.keras.layers import Conv2D, AveragePooling2D, BatchNormalization, Dropout, Input, Activation, Add, Dense, Flatten\n'), ((4739, 4757), 'tensorflow.keras.layers.Activation', 'Activation', (['"""relu"""'], {}), "('relu')\n", (4749, 4757), False, 'from tensorflow.keras.layers import Conv2D, AveragePooling2D, BatchNormalization, Dropout, Input, Activation, Add, Dense, Flatten\n'), ((3977, 4014), 'tensorflow.keras.layers.BatchNormalization', 'BatchNormalization', ([], {'axis': 'channel_axis'}), '(axis=channel_axis)\n', (3995, 4014), False, 'from tensorflow.keras.layers import Conv2D, AveragePooling2D, BatchNormalization, Dropout, Input, Activation, Add, Dense, Flatten\n'), ((4046, 4064), 'tensorflow.keras.layers.Activation', 'Activation', (['"""relu"""'], {}), "('relu')\n", (4056, 4064), False, 'from tensorflow.keras.layers import Conv2D, AveragePooling2D, BatchNormalization, Dropout, Input, Activation, Add, Dense, Flatten\n'), ((4152, 4189), 'tensorflow.keras.layers.BatchNormalization', 'BatchNormalization', ([], {'axis': 'channel_axis'}), '(axis=channel_axis)\n', (4170, 4189), False, 'from tensorflow.keras.layers import Conv2D, AveragePooling2D, BatchNormalization, Dropout, Input, Activation, Add, Dense, Flatten\n'), ((4223, 4241), 'tensorflow.keras.layers.Activation', 'Activation', (['"""relu"""'], {}), "('relu')\n", (4233, 4241), False, 'from tensorflow.keras.layers import Conv2D, AveragePooling2D, BatchNormalization, Dropout, Input, Activation, Add, Dense, Flatten\n'), ((4836, 4864), 'tensorflow.keras.layers.Dropout', 'Dropout', (['dropout_probability'], {}), '(dropout_probability)\n', (4843, 4864), False, 'from tensorflow.keras.layers import Conv2D, AveragePooling2D, BatchNormalization, Dropout, Input, Activation, Add, Dense, Flatten\n'), ((5831, 5847), 'tensorflow.keras.regularizers.l2', 'l2', (['weight_decay'], {}), '(weight_decay)\n', (5833, 5847), False, 'from tensorflow.keras.regularizers import l2\n'), ((4552, 4568), 'tensorflow.keras.regularizers.l2', 'l2', (['weight_decay'], {}), '(weight_decay)\n', (4554, 4568), False, 'from tensorflow.keras.regularizers import l2\n'), ((5175, 5191), 'tensorflow.keras.regularizers.l2', 'l2', (['weight_decay'], {}), '(weight_decay)\n', (5177, 5191), False, 'from tensorflow.keras.regularizers import l2\n')]
import numpy as np def _load_embeddings(fn): return np.load(fn) a = _load_embeddings('_embs/symptoms-en.npy') b = _load_embeddings('_output/paraphrase-MiniLM-L6-v2-symptoms-en.npy') for x, y in zip(a, b): for n, m in zip(x, y): if abs(n - m) > 1e-5: print(abs(n - m))
[ "numpy.load" ]
[((57, 68), 'numpy.load', 'np.load', (['fn'], {}), '(fn)\n', (64, 68), True, 'import numpy as np\n')]
from torch.utils.data import Dataset from torch.utils.data import DataLoader import os import torch import torch.nn.functional as F import torch.optim as optim from torchvision import transforms import torch.nn as nn import numpy as np import cv2 import os.path as osp from glob import glob from tqdm import tqdm class NucleusDataset(Dataset): def __init__(self, root_dir, train=True, transform=None, target_transform=None, mode ="train", do_reshuffle=True, keys=None,taskname = None,batch_size=16, num_batches=10000000, seed=None): self.root_dir = root_dir self.transform = transform self.target_transform = target_transform self.train = train self.taskname = taskname self.image_names = keys self.mode = mode self.data_len = len(self.image_names) self.batch_size = batch_size self.num_batches = min((self.data_len // self.batch_size)+10, num_batches) dataDir = "imagesTr" maskDir = "masksTr" suffix =".png" print("root_dir :",root_dir, " taskname : ",taskname,"self.mode :",self.mode) print(" path : ",osp.join(self.root_dir, taskname)) if not self._check_task_exists(): raise RuntimeError("Task does not exist") if self.mode=="train": #self.image_names = os.listdir(os.path.join(self.root_dir, "train",dataDir)) #print("train image_names :",self.image_names) self.train_data = [] self.train_labels = [] for image in self.image_names : train_img = cv2.imread(osp.join(self.root_dir,self.taskname,dataDir,image+suffix)) #print("image path: ",osp.join(self.root_dir,self.taskname,dataDir,image+suffix)) self.train_data.append(train_img) target_img = np.zeros(train_img.shape[:2], dtype=np.uint8) target_img_ = cv2.imread(osp.join(self.root_dir,taskname,maskDir,image+suffix),0) target_img = np.maximum(target_img, target_img_) self.train_labels.append(target_img) elif self.mode =="val": #self.image_names = os.listdir(osp.join(self.root_dir, "test",dataDir)) self.val_data = [] self.val_labels = [] for image in self.image_names: #print(" Val image_names :",self.image_names) val_img = cv2.imread(osp.join(self.root_dir,self.taskname,dataDir,image+suffix)) self.val_data.append(val_img) val_target_img = np.zeros(val_img.shape[:2], dtype=np.uint8) val_target_img_ = cv2.imread(osp.join(self.root_dir,self.taskname,maskDir,image+suffix),0) val_target_img = np.maximum(val_target_img, val_target_img_) self.val_labels.append(val_target_img) else : self.test_data = [] self.test_labels = [] for image in self.image_names: #print(" Test image_names :",self.image_names) test_img = cv2.imread(osp.join(self.root_dir,taskname,dataDir,image+suffix)) self.test_data.append(test_img) test_target_img = np.zeros(test_img.shape[:2], dtype=np.uint8) test_target_img_ = cv2.imread(osp.join(self.root_dir,taskname,maskDir,image+suffix),0) test_target_img = np.maximum(test_target_img, test_target_img_) self.test_labels.append(test_target_img) def __len__(self): return len(self.image_names) def __getitem__(self, item): if self.mode=="train": image, mask = self.train_data[item], self.train_labels[item] if self.transform: image = self.transform(image) if self.target_transform: mask = self.target_transform(mask) return image, mask elif self.mode=="val": image, mask = self.val_data[item], self.val_labels[item] if self.transform: image = self.transform(image) if self.target_transform: mask = self.target_transform(mask) return image, mask else: image, mask = self.test_data[item], self.test_labels[item] if self.transform: image = self.transform(image) if self.target_transform: mask = self.target_transform(mask) return image, mask def _check_exists(self): return osp.exists(osp.join(self.root_dir, "train")) and osp.exists(osp.join(self.root_dir, "test")) def _check_task_exists(self): return osp.exists(osp.join(self.root_dir, self.taskname))
[ "numpy.zeros", "os.path.join", "numpy.maximum" ]
[((1154, 1187), 'os.path.join', 'osp.join', (['self.root_dir', 'taskname'], {}), '(self.root_dir, taskname)\n', (1162, 1187), True, 'import os.path as osp\n'), ((4893, 4931), 'os.path.join', 'osp.join', (['self.root_dir', 'self.taskname'], {}), '(self.root_dir, self.taskname)\n', (4901, 4931), True, 'import os.path as osp\n'), ((1894, 1939), 'numpy.zeros', 'np.zeros', (['train_img.shape[:2]'], {'dtype': 'np.uint8'}), '(train_img.shape[:2], dtype=np.uint8)\n', (1902, 1939), True, 'import numpy as np\n'), ((2067, 2102), 'numpy.maximum', 'np.maximum', (['target_img', 'target_img_'], {}), '(target_img, target_img_)\n', (2077, 2102), True, 'import numpy as np\n'), ((4746, 4778), 'os.path.join', 'osp.join', (['self.root_dir', '"""train"""'], {}), "(self.root_dir, 'train')\n", (4754, 4778), True, 'import os.path as osp\n'), ((4795, 4826), 'os.path.join', 'osp.join', (['self.root_dir', '"""test"""'], {}), "(self.root_dir, 'test')\n", (4803, 4826), True, 'import os.path as osp\n'), ((1640, 1703), 'os.path.join', 'osp.join', (['self.root_dir', 'self.taskname', 'dataDir', '(image + suffix)'], {}), '(self.root_dir, self.taskname, dataDir, image + suffix)\n', (1648, 1703), True, 'import os.path as osp\n'), ((1981, 2039), 'os.path.join', 'osp.join', (['self.root_dir', 'taskname', 'maskDir', '(image + suffix)'], {}), '(self.root_dir, taskname, maskDir, image + suffix)\n', (1989, 2039), True, 'import os.path as osp\n'), ((2653, 2696), 'numpy.zeros', 'np.zeros', (['val_img.shape[:2]'], {'dtype': 'np.uint8'}), '(val_img.shape[:2], dtype=np.uint8)\n', (2661, 2696), True, 'import numpy as np\n'), ((2837, 2880), 'numpy.maximum', 'np.maximum', (['val_target_img', 'val_target_img_'], {}), '(val_target_img, val_target_img_)\n', (2847, 2880), True, 'import numpy as np\n'), ((3317, 3361), 'numpy.zeros', 'np.zeros', (['test_img.shape[:2]'], {'dtype': 'np.uint8'}), '(test_img.shape[:2], dtype=np.uint8)\n', (3325, 3361), True, 'import numpy as np\n'), ((3499, 3544), 'numpy.maximum', 'np.maximum', (['test_target_img', 'test_target_img_'], {}), '(test_target_img, test_target_img_)\n', (3509, 3544), True, 'import numpy as np\n'), ((2497, 2560), 'os.path.join', 'osp.join', (['self.root_dir', 'self.taskname', 'dataDir', '(image + suffix)'], {}), '(self.root_dir, self.taskname, dataDir, image + suffix)\n', (2505, 2560), True, 'import os.path as osp\n'), ((2742, 2805), 'os.path.join', 'osp.join', (['self.root_dir', 'self.taskname', 'maskDir', '(image + suffix)'], {}), '(self.root_dir, self.taskname, maskDir, image + suffix)\n', (2750, 2805), True, 'import os.path as osp\n'), ((3163, 3221), 'os.path.join', 'osp.join', (['self.root_dir', 'taskname', 'dataDir', '(image + suffix)'], {}), '(self.root_dir, taskname, dataDir, image + suffix)\n', (3171, 3221), True, 'import os.path as osp\n'), ((3408, 3466), 'os.path.join', 'osp.join', (['self.root_dir', 'taskname', 'maskDir', '(image + suffix)'], {}), '(self.root_dir, taskname, maskDir, image + suffix)\n', (3416, 3466), True, 'import os.path as osp\n')]
import argparse import os import sys import time import traceback import multiprocessing import numpy as np from PIL import Image import matplotlib.pyplot as plt import matplotlib.image as mpimg import matplotlib.animation as animation from collections import OrderedDict from pynput.keyboard import Listener, Key, KeyCode #Globals global g_keyboardStateArray g_keyboardStateArray = None global g_keyIndexes g_keyIndexes = None global g_inputBufferPath g_inputBufferPath = None g_keyArray = [ #lower case letters KeyCode.from_char("a"), KeyCode.from_char("b"), KeyCode.from_char("c"), KeyCode.from_char("d"), KeyCode.from_char("e"), KeyCode.from_char("f"), KeyCode.from_char("g"), KeyCode.from_char("h"), KeyCode.from_char("i"), KeyCode.from_char("j"), KeyCode.from_char("k"), KeyCode.from_char("l"), KeyCode.from_char("m"), KeyCode.from_char("n"), KeyCode.from_char("o"), KeyCode.from_char("p"), KeyCode.from_char("q"), KeyCode.from_char("r"), KeyCode.from_char("s"), KeyCode.from_char("t"), KeyCode.from_char("u"), KeyCode.from_char("v"), KeyCode.from_char("w"), KeyCode.from_char("x"), KeyCode.from_char("y"), KeyCode.from_char("z"), #uppder case letters KeyCode.from_char("A"), KeyCode.from_char("B"), KeyCode.from_char("C"), KeyCode.from_char("D"), KeyCode.from_char("E"), KeyCode.from_char("F"), KeyCode.from_char("G"), KeyCode.from_char("H"), KeyCode.from_char("I"), KeyCode.from_char("J"), KeyCode.from_char("K"), KeyCode.from_char("L"), KeyCode.from_char("M"), KeyCode.from_char("N"), KeyCode.from_char("O"), KeyCode.from_char("P"), KeyCode.from_char("Q"), KeyCode.from_char("R"), KeyCode.from_char("S"), KeyCode.from_char("T"), KeyCode.from_char("U"), KeyCode.from_char("V"), KeyCode.from_char("W"), KeyCode.from_char("X"), KeyCode.from_char("Y"), KeyCode.from_char("Z"), #numbers KeyCode.from_char("0"), KeyCode.from_char("1"), KeyCode.from_char("2"), KeyCode.from_char("3"), KeyCode.from_char("4"), KeyCode.from_char("5"), KeyCode.from_char("6"), KeyCode.from_char("7"), KeyCode.from_char("8"), KeyCode.from_char("9"), #symbols KeyCode.from_char("!"), KeyCode.from_char("@"), KeyCode.from_char("#"), KeyCode.from_char("$"), KeyCode.from_char("%"), KeyCode.from_char("^"), KeyCode.from_char("&"), KeyCode.from_char("*"), KeyCode.from_char("("), KeyCode.from_char(")"), KeyCode.from_char("-"), KeyCode.from_char("_"), KeyCode.from_char("+"), KeyCode.from_char("="), KeyCode.from_char("{"), KeyCode.from_char("["), KeyCode.from_char("}"), KeyCode.from_char("]"), KeyCode.from_char("|"), KeyCode.from_char("\\"),KeyCode.from_char(";"), KeyCode.from_char(":"), KeyCode.from_char("'"), KeyCode.from_char("\""), KeyCode.from_char(","), KeyCode.from_char("<"), KeyCode.from_char("."), KeyCode.from_char(">"), KeyCode.from_char("/"), KeyCode.from_char("?"), KeyCode.from_char("`"), KeyCode.from_char("~"), #function keys Key.f1, Key.f2, Key.f3, Key.f4, Key.f5, Key.f6, Key.f7, Key.f8, Key.f9, Key.f10, Key.f11, Key.f12, #Arrow keys Key.up, Key.down, Key.left, Key.right, #Modifier keys Key.ctrl, Key.ctrl_r, Key.cmd, Key.cmd_r, Key.alt, Key.alt_r, Key.num_lock, Key.caps_lock, Key.shift, Key.shift_r, #Macro keys Key.enter, Key.backspace, Key.delete, Key.home, Key.end, Key.insert, Key.page_up, Key.page_down, Key.esc ] class COLORS: DEFAULT = '\033[0m' HEADER = '\033[95m' OKBLUE = '\033[94m' OKGREEN = '\033[92m' WARNING = '\033[93m' ERROR = '\033[91m' BOLD = '\033[1m' UNDERLINE = '\033[4m' def printColor(text, color=COLORS.DEFAULT, resetColor=True): ''' Prints colored text to the terminal ''' if (resetColor): formattedText = "{}{}{}".format(color, text, COLORS.DEFAULT) print(formattedText) else: formattedText = "{}{}".format(color, text) print(formattedText) def displayFrameBuffer(displayWidth, displayHeight, frameBufferPath, workDir): fig = plt.figure() flatPixelArray = None flatByteArray = np.fromfile(frameBufferPath, dtype='>B') flatPixelArray = np.reshape(flatByteArray, (-1, 4)) pixelArray = np.zeros([displayHeight, displayWidth, 3], dtype=np.uint8) imagePath = os.path.join(workDir, "createdImage.png") def animate(i): #Update pixel array with values flatByteArray = np.fromfile(frameBufferPath, dtype='B') flatPixelArray = np.reshape(flatByteArray, (-1, 4)) for row in range(0, displayHeight): for column in range(0, displayWidth): pixelIndex = row*displayWidth + column if (len(flatPixelArray) > 0): try: pixelArray[row, column] = np.flip(flatPixelArray[pixelIndex][0:-1]) except Exception as e: pass else: break #Display updated pixel array img = Image.fromarray(pixelArray) img.save(imagePath) img = mpimg.imread(imagePath) plt.clf() plt.axis('off') imgplot = plt.imshow(img) #time.sleep(0.05) ani = animation.FuncAnimation(fig, animate, interval=20) plt.show() def updateInputBufferFile(filepath, keyboardStateArray): hexFile = open(filepath, "r+") iterator = 0 for byteIndex in range(0, len(g_keyboardStateArray)): byte = g_keyboardStateArray[byteIndex] fileAddress = 9*int((byteIndex/4)) + 7 - (2*(byteIndex%4)) #hex file is stored as big endian words, so we need to convert each byte index into the appropite file byte address hexFile.seek(fileAddress, 0) hexFile.write("{}".format(str(byte))) iterator += 1 hexFile.close() def initializeInputBufferFile(filepath, keyboardStateArray): hexFile = open(filepath, "w") iterator = 0 for byteIndex in range(0, len(g_keyboardStateArray)): byte = g_keyboardStateArray[byteIndex] if (iterator == 4): hexFile.write("\n") iterator = 0 hexFile.write("0{}".format(str(byte))) iterator += 1 hexFile.close() def onKeyPress(key): g_keyboardStateArray[g_keyIndexes[key]]= 1 updateInputBufferFile(g_inputBufferPath, g_keyboardStateArray) def onKeyRelease(key): g_keyboardStateArray[g_keyIndexes[key]] = 0 updateInputBufferFile(g_inputBufferPath, g_keyboardStateArray) if __name__ == '__main__': displayThread = None listenerThread = None try: #Read command line arguments helpdesc = ''' help yourself ''' parser = argparse.ArgumentParser(description = helpdesc) parser.add_argument("-bench", action="store", dest="testbenchPath", help="Filepath to verilog testbench") parser.add_argument("-prog", action="store", dest="programPath", help="Path to hex program to run, if supported by the testbench") parser.add_argument("-mem", action="store", dest="memorySize", default="4096", help="Size of main memory to allocate in bytes") parser.add_argument("-cycles", action="store", dest="maxSimCycles", help="If specified, simulation will end if total cycles exceed this limit") parser.add_argument("-display", action="store", dest="screenSize", help="If specified, simulation will define and display a frame buffer. Argument format: \"<BUFFER_ADDRESS>,<WIDTH_PIXELS>,<HEIGHT_PIXELS>\"") parser.add_argument("-input", action="store", dest="inputBufferSize", help="If specified, simulation will define and update a keyboard input buffer. Argument format: \"<BUFFER_ADDRESS>,<BUFFER_SIZE>\"") parser.add_argument("-dump", action="store_true", dest="dumpValues", help="If specified, will create an vcd dump file from simulation. Required to view waveforms in Gtkwave") args = parser.parse_args() testbenchPath = args.testbenchPath programPath = args.programPath memorySizeString = args.memorySize memorySize = None if ("K" in memorySizeString): memorySizeString = memorySizeString.replace("K", "") memorySize = int(memorySizeString) * 2**10 elif ("M" in memorySizeString): memorySizeString = memorySizeString.replace("M", "") memorySize = int(memorySizeString) * 2**20 elif ("G" in memorySizeString): memorySizeString = memorySizeString.replace("G", "") memorySize = int(memorySizeString) * 2**30 else: memorySize = int(4 * int(int(memorySizeString) / 4)) maxSimCycles = args.maxSimCycles dumpValues = args.dumpValues screenSizeString = args.screenSize inputBufferSizeString = args.inputBufferSize if (not testbenchPath): raise Exception("ERROR: -testbenchPath arg required") #Create output folders if they do not exist yet testbenchName = testbenchPath.split(".")[0].split("/")[-1] if (not os.path.exists("simulation")): os.mkdir("simulation") if (not os.path.exists("simulation/{}".format(testbenchName))): os.mkdir("simulation/{}".format(testbenchName)) if (programPath): #Program specified. Determine length of program programFile = open(programPath, "r") line = " " lineCount = 0 while(line): line = programFile.readline() if (len(line) > 0): if ("00000000" in line): break lineCount += 1 programFile.close() #Update testbench program inputs programInputsFile = open("{}_programInputs.v".format(testbenchPath.split(".")[0]), "w") programInputsFile.write("`define programLength {}\n".format(lineCount)) programInputsFile.write("`define programFilename \"{}\"\n".format(programPath)) programInputsFile.write("`define memorySize {}\n".format(memorySize)) if (maxSimCycles): programInputsFile.write("`define MAX_CYLCLES {}\n".format(int(maxSimCycles))) if (screenSizeString): #Determine frame buffer file path frameBufferPath = "simulation/{}/frameBuffer.b".format(testbenchName) #Determine size of frame buffer and frameBufferStart frameBufferStart, displayWidth, displayHeight = [int(i) for i in screenSizeString.replace(" ","").strip().rstrip().split(",")] frameBufferSize = displayHeight * displayWidth *4 if (frameBufferSize > memorySize-frameBufferStart): raise Exception("Allocated memory of {} bytes cannot fit frame buffer of size {}, location {}".format(memorySize, frameBufferSize, frameBufferStart)) #Add defines to program inputs programInputsFile.write("`define FRAME_BUFFER_ENABLE\n") programInputsFile.write("`define frameBufferPath \"{}\"\n".format(frameBufferPath)) programInputsFile.write("`define frameBufferSize {}\n".format(frameBufferSize)) programInputsFile.write("`define frameBufferStart {}\n".format(frameBufferStart)) #Initialize frame buffer file emptyByteArray = bytearray(frameBufferSize) bufferFile = open(frameBufferPath, "wb") bufferFile.write(emptyByteArray) bufferFile.close() #Initialize display viewer displayThread = multiprocessing.Process(target=displayFrameBuffer, args=(displayWidth, displayHeight, frameBufferPath, "simulation/{}".format(testbenchName))) displayThread.start() if (inputBufferSizeString): #Determine input buffer file path inputBufferPath = "simulation/{}/inputBuffer.hex".format(testbenchName) g_inputBufferPath = inputBufferPath #Determine size of input buffer and inputBufferStart inputBufferStart, inputBufferSize = [int(i) for i in inputBufferSizeString.replace(" ","").strip().rstrip().split(",")] if (inputBufferSize > memorySize-inputBufferStart): raise Exception("Allocated memory of {} bytes cannot fit frame buffer of size {}, location {}".format(memorySize, inputBufferSize, inputBufferStart)) #Add defines to program inputs programInputsFile.write("`define INPUT_BUFFER_ENABLE\n") programInputsFile.write("`define inputBufferPath \"{}\"\n".format(inputBufferPath)) programInputsFile.write("`define inputBufferSize {}\n".format(inputBufferSize)) programInputsFile.write("`define inputBufferStart {}\n".format(inputBufferStart)) #Initialize input buffer file g_keyIndexes = OrderedDict() for index in range(0, len(g_keyArray), 1): g_keyIndexes[g_keyArray[index]] = index stateArrayLength = len(g_keyIndexes) if (len(g_keyIndexes)%4): stateArrayLength += 4 - len(g_keyIndexes)%4 g_keyboardStateArray = np.zeros(stateArrayLength, dtype=np.uint8) initializeInputBufferFile(inputBufferPath, g_keyboardStateArray) #Initialize keyboard listener listenerThread = Listener(on_press=onKeyPress, on_release=onKeyRelease) listenerThread.start() programInputsFile.close() #Compile into vvp with icarus verilog print("Compiling verilog") command = "iverilog {} -I rtl -I testbenches -g2005-sv -o simulation/{}/{}.vvp | grep error".format(testbenchPath, testbenchName, testbenchName) print("+ {}{}".format(command, COLORS.ERROR)) os.system(command) print(COLORS.DEFAULT) #Run vvp dumpFlag = "" if (dumpValues): dumpFlag = "-vcd" print("Running simulation") startTime = time.time() command = "vvp simulation/{}/{}.vvp {}".format(testbenchName, testbenchName, dumpFlag) print("+ {}".format(command)) os.system(command) endTime = time.time() print("runtime = {} seconds".format(endTime-startTime)) #Move dump file if (dumpValues): command = "mv dump.vcd simulation/{}/{}_dump.vcd".format(testbenchName, testbenchName) print("+ {}".format(command)) os.system(command) #Kill display thread if (displayThread): time.sleep(2) displayThread.terminate() except Exception as e: printColor(traceback.format_exc(), color=COLORS.ERROR) if (displayThread): displayThread.terminate()
[ "pynput.keyboard.KeyCode.from_char", "os.mkdir", "argparse.ArgumentParser", "matplotlib.pyplot.clf", "matplotlib.animation.FuncAnimation", "matplotlib.pyplot.figure", "os.path.join", "matplotlib.pyplot.imshow", "os.path.exists", "numpy.reshape", "traceback.format_exc", "matplotlib.image.imread", "matplotlib.pyplot.show", "pynput.keyboard.Listener", "os.system", "time.sleep", "collections.OrderedDict", "numpy.flip", "numpy.fromfile", "numpy.zeros", "matplotlib.pyplot.axis", "time.time", "PIL.Image.fromarray" ]
[((517, 539), 'pynput.keyboard.KeyCode.from_char', 'KeyCode.from_char', (['"""a"""'], {}), "('a')\n", (534, 539), False, 'from pynput.keyboard import Listener, Key, KeyCode\n'), ((541, 563), 'pynput.keyboard.KeyCode.from_char', 'KeyCode.from_char', (['"""b"""'], {}), "('b')\n", (558, 563), False, 'from pynput.keyboard import Listener, Key, KeyCode\n'), ((565, 587), 'pynput.keyboard.KeyCode.from_char', 'KeyCode.from_char', (['"""c"""'], {}), "('c')\n", (582, 587), False, 'from pynput.keyboard import Listener, Key, KeyCode\n'), ((589, 611), 'pynput.keyboard.KeyCode.from_char', 'KeyCode.from_char', (['"""d"""'], {}), "('d')\n", (606, 611), False, 'from pynput.keyboard import Listener, Key, KeyCode\n'), ((613, 635), 'pynput.keyboard.KeyCode.from_char', 'KeyCode.from_char', (['"""e"""'], {}), "('e')\n", (630, 635), False, 'from pynput.keyboard import Listener, Key, KeyCode\n'), ((637, 659), 'pynput.keyboard.KeyCode.from_char', 'KeyCode.from_char', (['"""f"""'], {}), "('f')\n", (654, 659), False, 'from pynput.keyboard import Listener, Key, KeyCode\n'), ((662, 684), 'pynput.keyboard.KeyCode.from_char', 'KeyCode.from_char', (['"""g"""'], {}), "('g')\n", (679, 684), False, 'from pynput.keyboard import Listener, Key, KeyCode\n'), ((686, 708), 'pynput.keyboard.KeyCode.from_char', 'KeyCode.from_char', (['"""h"""'], {}), "('h')\n", (703, 708), False, 'from pynput.keyboard import Listener, Key, KeyCode\n'), ((710, 732), 'pynput.keyboard.KeyCode.from_char', 'KeyCode.from_char', (['"""i"""'], {}), "('i')\n", (727, 732), False, 'from pynput.keyboard import Listener, Key, KeyCode\n'), ((734, 756), 'pynput.keyboard.KeyCode.from_char', 'KeyCode.from_char', (['"""j"""'], {}), "('j')\n", (751, 756), False, 'from pynput.keyboard import Listener, Key, KeyCode\n'), ((758, 780), 'pynput.keyboard.KeyCode.from_char', 'KeyCode.from_char', (['"""k"""'], {}), "('k')\n", (775, 780), False, 'from pynput.keyboard import Listener, Key, KeyCode\n'), ((782, 804), 'pynput.keyboard.KeyCode.from_char', 'KeyCode.from_char', (['"""l"""'], {}), "('l')\n", (799, 804), False, 'from pynput.keyboard import Listener, Key, KeyCode\n'), ((807, 829), 'pynput.keyboard.KeyCode.from_char', 'KeyCode.from_char', (['"""m"""'], {}), "('m')\n", (824, 829), False, 'from pynput.keyboard import Listener, Key, KeyCode\n'), ((831, 853), 'pynput.keyboard.KeyCode.from_char', 'KeyCode.from_char', (['"""n"""'], {}), "('n')\n", (848, 853), False, 'from pynput.keyboard import Listener, Key, KeyCode\n'), ((855, 877), 'pynput.keyboard.KeyCode.from_char', 'KeyCode.from_char', (['"""o"""'], {}), "('o')\n", (872, 877), False, 'from pynput.keyboard import Listener, Key, KeyCode\n'), ((879, 901), 'pynput.keyboard.KeyCode.from_char', 'KeyCode.from_char', (['"""p"""'], {}), "('p')\n", (896, 901), False, 'from pynput.keyboard import Listener, Key, KeyCode\n'), ((903, 925), 'pynput.keyboard.KeyCode.from_char', 'KeyCode.from_char', (['"""q"""'], {}), "('q')\n", (920, 925), False, 'from pynput.keyboard import Listener, Key, KeyCode\n'), ((927, 949), 'pynput.keyboard.KeyCode.from_char', 'KeyCode.from_char', (['"""r"""'], {}), "('r')\n", (944, 949), False, 'from pynput.keyboard import Listener, Key, KeyCode\n'), ((952, 974), 'pynput.keyboard.KeyCode.from_char', 'KeyCode.from_char', (['"""s"""'], {}), "('s')\n", (969, 974), False, 'from pynput.keyboard import Listener, Key, KeyCode\n'), ((976, 998), 'pynput.keyboard.KeyCode.from_char', 'KeyCode.from_char', (['"""t"""'], {}), "('t')\n", (993, 998), False, 'from pynput.keyboard import Listener, Key, KeyCode\n'), ((1000, 1022), 'pynput.keyboard.KeyCode.from_char', 'KeyCode.from_char', (['"""u"""'], {}), "('u')\n", (1017, 1022), False, 'from pynput.keyboard import Listener, Key, KeyCode\n'), ((1024, 1046), 'pynput.keyboard.KeyCode.from_char', 'KeyCode.from_char', (['"""v"""'], {}), "('v')\n", (1041, 1046), False, 'from pynput.keyboard import Listener, Key, KeyCode\n'), ((1048, 1070), 'pynput.keyboard.KeyCode.from_char', 'KeyCode.from_char', (['"""w"""'], {}), "('w')\n", (1065, 1070), False, 'from pynput.keyboard import Listener, Key, KeyCode\n'), ((1072, 1094), 'pynput.keyboard.KeyCode.from_char', 'KeyCode.from_char', (['"""x"""'], {}), "('x')\n", (1089, 1094), False, 'from pynput.keyboard import Listener, Key, KeyCode\n'), ((1097, 1119), 'pynput.keyboard.KeyCode.from_char', 'KeyCode.from_char', (['"""y"""'], {}), "('y')\n", (1114, 1119), False, 'from pynput.keyboard import Listener, Key, KeyCode\n'), ((1121, 1143), 'pynput.keyboard.KeyCode.from_char', 'KeyCode.from_char', (['"""z"""'], {}), "('z')\n", (1138, 1143), False, 'from pynput.keyboard import Listener, Key, KeyCode\n'), ((1167, 1189), 'pynput.keyboard.KeyCode.from_char', 'KeyCode.from_char', (['"""A"""'], {}), "('A')\n", (1184, 1189), False, 'from pynput.keyboard import Listener, Key, KeyCode\n'), ((1191, 1213), 'pynput.keyboard.KeyCode.from_char', 'KeyCode.from_char', (['"""B"""'], {}), "('B')\n", (1208, 1213), False, 'from pynput.keyboard import Listener, Key, KeyCode\n'), ((1215, 1237), 'pynput.keyboard.KeyCode.from_char', 'KeyCode.from_char', (['"""C"""'], {}), "('C')\n", (1232, 1237), False, 'from pynput.keyboard import Listener, Key, KeyCode\n'), ((1239, 1261), 'pynput.keyboard.KeyCode.from_char', 'KeyCode.from_char', (['"""D"""'], {}), "('D')\n", (1256, 1261), False, 'from pynput.keyboard import Listener, Key, KeyCode\n'), ((1263, 1285), 'pynput.keyboard.KeyCode.from_char', 'KeyCode.from_char', (['"""E"""'], {}), "('E')\n", (1280, 1285), False, 'from pynput.keyboard import Listener, Key, KeyCode\n'), ((1287, 1309), 'pynput.keyboard.KeyCode.from_char', 'KeyCode.from_char', (['"""F"""'], {}), "('F')\n", (1304, 1309), False, 'from pynput.keyboard import Listener, Key, KeyCode\n'), ((1312, 1334), 'pynput.keyboard.KeyCode.from_char', 'KeyCode.from_char', (['"""G"""'], {}), "('G')\n", (1329, 1334), False, 'from pynput.keyboard import Listener, Key, KeyCode\n'), ((1336, 1358), 'pynput.keyboard.KeyCode.from_char', 'KeyCode.from_char', (['"""H"""'], {}), "('H')\n", (1353, 1358), False, 'from pynput.keyboard import Listener, Key, KeyCode\n'), ((1360, 1382), 'pynput.keyboard.KeyCode.from_char', 'KeyCode.from_char', (['"""I"""'], {}), "('I')\n", (1377, 1382), False, 'from pynput.keyboard import Listener, Key, KeyCode\n'), ((1384, 1406), 'pynput.keyboard.KeyCode.from_char', 'KeyCode.from_char', (['"""J"""'], {}), "('J')\n", (1401, 1406), False, 'from pynput.keyboard import Listener, Key, KeyCode\n'), ((1408, 1430), 'pynput.keyboard.KeyCode.from_char', 'KeyCode.from_char', (['"""K"""'], {}), "('K')\n", (1425, 1430), False, 'from pynput.keyboard import Listener, Key, KeyCode\n'), ((1432, 1454), 'pynput.keyboard.KeyCode.from_char', 'KeyCode.from_char', (['"""L"""'], {}), "('L')\n", (1449, 1454), False, 'from pynput.keyboard import Listener, Key, KeyCode\n'), ((1457, 1479), 'pynput.keyboard.KeyCode.from_char', 'KeyCode.from_char', (['"""M"""'], {}), "('M')\n", (1474, 1479), False, 'from pynput.keyboard import Listener, Key, KeyCode\n'), ((1481, 1503), 'pynput.keyboard.KeyCode.from_char', 'KeyCode.from_char', (['"""N"""'], {}), "('N')\n", (1498, 1503), False, 'from pynput.keyboard import Listener, Key, KeyCode\n'), ((1505, 1527), 'pynput.keyboard.KeyCode.from_char', 'KeyCode.from_char', (['"""O"""'], {}), "('O')\n", (1522, 1527), False, 'from pynput.keyboard import Listener, Key, KeyCode\n'), ((1529, 1551), 'pynput.keyboard.KeyCode.from_char', 'KeyCode.from_char', (['"""P"""'], {}), "('P')\n", (1546, 1551), False, 'from pynput.keyboard import Listener, Key, KeyCode\n'), ((1553, 1575), 'pynput.keyboard.KeyCode.from_char', 'KeyCode.from_char', (['"""Q"""'], {}), "('Q')\n", (1570, 1575), False, 'from pynput.keyboard import Listener, Key, KeyCode\n'), ((1577, 1599), 'pynput.keyboard.KeyCode.from_char', 'KeyCode.from_char', (['"""R"""'], {}), "('R')\n", (1594, 1599), False, 'from pynput.keyboard import Listener, Key, KeyCode\n'), ((1602, 1624), 'pynput.keyboard.KeyCode.from_char', 'KeyCode.from_char', (['"""S"""'], {}), "('S')\n", (1619, 1624), False, 'from pynput.keyboard import Listener, Key, KeyCode\n'), ((1626, 1648), 'pynput.keyboard.KeyCode.from_char', 'KeyCode.from_char', (['"""T"""'], {}), "('T')\n", (1643, 1648), False, 'from pynput.keyboard import Listener, Key, KeyCode\n'), ((1650, 1672), 'pynput.keyboard.KeyCode.from_char', 'KeyCode.from_char', (['"""U"""'], {}), "('U')\n", (1667, 1672), False, 'from pynput.keyboard import Listener, Key, KeyCode\n'), ((1674, 1696), 'pynput.keyboard.KeyCode.from_char', 'KeyCode.from_char', (['"""V"""'], {}), "('V')\n", (1691, 1696), False, 'from pynput.keyboard import Listener, Key, KeyCode\n'), ((1698, 1720), 'pynput.keyboard.KeyCode.from_char', 'KeyCode.from_char', (['"""W"""'], {}), "('W')\n", (1715, 1720), False, 'from pynput.keyboard import Listener, Key, KeyCode\n'), ((1722, 1744), 'pynput.keyboard.KeyCode.from_char', 'KeyCode.from_char', (['"""X"""'], {}), "('X')\n", (1739, 1744), False, 'from pynput.keyboard import Listener, Key, KeyCode\n'), ((1747, 1769), 'pynput.keyboard.KeyCode.from_char', 'KeyCode.from_char', (['"""Y"""'], {}), "('Y')\n", (1764, 1769), False, 'from pynput.keyboard import Listener, Key, KeyCode\n'), ((1771, 1793), 'pynput.keyboard.KeyCode.from_char', 'KeyCode.from_char', (['"""Z"""'], {}), "('Z')\n", (1788, 1793), False, 'from pynput.keyboard import Listener, Key, KeyCode\n'), ((1805, 1827), 'pynput.keyboard.KeyCode.from_char', 'KeyCode.from_char', (['"""0"""'], {}), "('0')\n", (1822, 1827), False, 'from pynput.keyboard import Listener, Key, KeyCode\n'), ((1829, 1851), 'pynput.keyboard.KeyCode.from_char', 'KeyCode.from_char', (['"""1"""'], {}), "('1')\n", (1846, 1851), False, 'from pynput.keyboard import Listener, Key, KeyCode\n'), ((1853, 1875), 'pynput.keyboard.KeyCode.from_char', 'KeyCode.from_char', (['"""2"""'], {}), "('2')\n", (1870, 1875), False, 'from pynput.keyboard import Listener, Key, KeyCode\n'), ((1877, 1899), 'pynput.keyboard.KeyCode.from_char', 'KeyCode.from_char', (['"""3"""'], {}), "('3')\n", (1894, 1899), False, 'from pynput.keyboard import Listener, Key, KeyCode\n'), ((1901, 1923), 'pynput.keyboard.KeyCode.from_char', 'KeyCode.from_char', (['"""4"""'], {}), "('4')\n", (1918, 1923), False, 'from pynput.keyboard import Listener, Key, KeyCode\n'), ((1925, 1947), 'pynput.keyboard.KeyCode.from_char', 'KeyCode.from_char', (['"""5"""'], {}), "('5')\n", (1942, 1947), False, 'from pynput.keyboard import Listener, Key, KeyCode\n'), ((1950, 1972), 'pynput.keyboard.KeyCode.from_char', 'KeyCode.from_char', (['"""6"""'], {}), "('6')\n", (1967, 1972), False, 'from pynput.keyboard import Listener, Key, KeyCode\n'), ((1974, 1996), 'pynput.keyboard.KeyCode.from_char', 'KeyCode.from_char', (['"""7"""'], {}), "('7')\n", (1991, 1996), False, 'from pynput.keyboard import Listener, Key, KeyCode\n'), ((1998, 2020), 'pynput.keyboard.KeyCode.from_char', 'KeyCode.from_char', (['"""8"""'], {}), "('8')\n", (2015, 2020), False, 'from pynput.keyboard import Listener, Key, KeyCode\n'), ((2022, 2044), 'pynput.keyboard.KeyCode.from_char', 'KeyCode.from_char', (['"""9"""'], {}), "('9')\n", (2039, 2044), False, 'from pynput.keyboard import Listener, Key, KeyCode\n'), ((2056, 2078), 'pynput.keyboard.KeyCode.from_char', 'KeyCode.from_char', (['"""!"""'], {}), "('!')\n", (2073, 2078), False, 'from pynput.keyboard import Listener, Key, KeyCode\n'), ((2080, 2102), 'pynput.keyboard.KeyCode.from_char', 'KeyCode.from_char', (['"""@"""'], {}), "('@')\n", (2097, 2102), False, 'from pynput.keyboard import Listener, Key, KeyCode\n'), ((2104, 2126), 'pynput.keyboard.KeyCode.from_char', 'KeyCode.from_char', (['"""#"""'], {}), "('#')\n", (2121, 2126), False, 'from pynput.keyboard import Listener, Key, KeyCode\n'), ((2128, 2150), 'pynput.keyboard.KeyCode.from_char', 'KeyCode.from_char', (['"""$"""'], {}), "('$')\n", (2145, 2150), False, 'from pynput.keyboard import Listener, Key, KeyCode\n'), ((2152, 2174), 'pynput.keyboard.KeyCode.from_char', 'KeyCode.from_char', (['"""%"""'], {}), "('%')\n", (2169, 2174), False, 'from pynput.keyboard import Listener, Key, KeyCode\n'), ((2176, 2198), 'pynput.keyboard.KeyCode.from_char', 'KeyCode.from_char', (['"""^"""'], {}), "('^')\n", (2193, 2198), False, 'from pynput.keyboard import Listener, Key, KeyCode\n'), ((2201, 2223), 'pynput.keyboard.KeyCode.from_char', 'KeyCode.from_char', (['"""&"""'], {}), "('&')\n", (2218, 2223), False, 'from pynput.keyboard import Listener, Key, KeyCode\n'), ((2225, 2247), 'pynput.keyboard.KeyCode.from_char', 'KeyCode.from_char', (['"""*"""'], {}), "('*')\n", (2242, 2247), False, 'from pynput.keyboard import Listener, Key, KeyCode\n'), ((2249, 2271), 'pynput.keyboard.KeyCode.from_char', 'KeyCode.from_char', (['"""("""'], {}), "('(')\n", (2266, 2271), False, 'from pynput.keyboard import Listener, Key, KeyCode\n'), ((2273, 2295), 'pynput.keyboard.KeyCode.from_char', 'KeyCode.from_char', (['""")"""'], {}), "(')')\n", (2290, 2295), False, 'from pynput.keyboard import Listener, Key, KeyCode\n'), ((2297, 2319), 'pynput.keyboard.KeyCode.from_char', 'KeyCode.from_char', (['"""-"""'], {}), "('-')\n", (2314, 2319), False, 'from pynput.keyboard import Listener, Key, KeyCode\n'), ((2321, 2343), 'pynput.keyboard.KeyCode.from_char', 'KeyCode.from_char', (['"""_"""'], {}), "('_')\n", (2338, 2343), False, 'from pynput.keyboard import Listener, Key, KeyCode\n'), ((2346, 2368), 'pynput.keyboard.KeyCode.from_char', 'KeyCode.from_char', (['"""+"""'], {}), "('+')\n", (2363, 2368), False, 'from pynput.keyboard import Listener, Key, KeyCode\n'), ((2370, 2392), 'pynput.keyboard.KeyCode.from_char', 'KeyCode.from_char', (['"""="""'], {}), "('=')\n", (2387, 2392), False, 'from pynput.keyboard import Listener, Key, KeyCode\n'), ((2394, 2416), 'pynput.keyboard.KeyCode.from_char', 'KeyCode.from_char', (['"""{"""'], {}), "('{')\n", (2411, 2416), False, 'from pynput.keyboard import Listener, Key, KeyCode\n'), ((2418, 2440), 'pynput.keyboard.KeyCode.from_char', 'KeyCode.from_char', (['"""["""'], {}), "('[')\n", (2435, 2440), False, 'from pynput.keyboard import Listener, Key, KeyCode\n'), ((2442, 2464), 'pynput.keyboard.KeyCode.from_char', 'KeyCode.from_char', (['"""}"""'], {}), "('}')\n", (2459, 2464), False, 'from pynput.keyboard import Listener, Key, KeyCode\n'), ((2466, 2488), 'pynput.keyboard.KeyCode.from_char', 'KeyCode.from_char', (['"""]"""'], {}), "(']')\n", (2483, 2488), False, 'from pynput.keyboard import Listener, Key, KeyCode\n'), ((2491, 2513), 'pynput.keyboard.KeyCode.from_char', 'KeyCode.from_char', (['"""|"""'], {}), "('|')\n", (2508, 2513), False, 'from pynput.keyboard import Listener, Key, KeyCode\n'), ((2515, 2538), 'pynput.keyboard.KeyCode.from_char', 'KeyCode.from_char', (['"""\\\\"""'], {}), "('\\\\')\n", (2532, 2538), False, 'from pynput.keyboard import Listener, Key, KeyCode\n'), ((2539, 2561), 'pynput.keyboard.KeyCode.from_char', 'KeyCode.from_char', (['""";"""'], {}), "(';')\n", (2556, 2561), False, 'from pynput.keyboard import Listener, Key, KeyCode\n'), ((2563, 2585), 'pynput.keyboard.KeyCode.from_char', 'KeyCode.from_char', (['""":"""'], {}), "(':')\n", (2580, 2585), False, 'from pynput.keyboard import Listener, Key, KeyCode\n'), ((2587, 2609), 'pynput.keyboard.KeyCode.from_char', 'KeyCode.from_char', (['"""\'"""'], {}), '("\'")\n', (2604, 2609), False, 'from pynput.keyboard import Listener, Key, KeyCode\n'), ((2611, 2633), 'pynput.keyboard.KeyCode.from_char', 'KeyCode.from_char', (['"""\\""""'], {}), '(\'"\')\n', (2628, 2633), False, 'from pynput.keyboard import Listener, Key, KeyCode\n'), ((2637, 2659), 'pynput.keyboard.KeyCode.from_char', 'KeyCode.from_char', (['""","""'], {}), "(',')\n", (2654, 2659), False, 'from pynput.keyboard import Listener, Key, KeyCode\n'), ((2661, 2683), 'pynput.keyboard.KeyCode.from_char', 'KeyCode.from_char', (['"""<"""'], {}), "('<')\n", (2678, 2683), False, 'from pynput.keyboard import Listener, Key, KeyCode\n'), ((2685, 2707), 'pynput.keyboard.KeyCode.from_char', 'KeyCode.from_char', (['"""."""'], {}), "('.')\n", (2702, 2707), False, 'from pynput.keyboard import Listener, Key, KeyCode\n'), ((2709, 2731), 'pynput.keyboard.KeyCode.from_char', 'KeyCode.from_char', (['""">"""'], {}), "('>')\n", (2726, 2731), False, 'from pynput.keyboard import Listener, Key, KeyCode\n'), ((2733, 2755), 'pynput.keyboard.KeyCode.from_char', 'KeyCode.from_char', (['"""/"""'], {}), "('/')\n", (2750, 2755), False, 'from pynput.keyboard import Listener, Key, KeyCode\n'), ((2757, 2779), 'pynput.keyboard.KeyCode.from_char', 'KeyCode.from_char', (['"""?"""'], {}), "('?')\n", (2774, 2779), False, 'from pynput.keyboard import Listener, Key, KeyCode\n'), ((2782, 2804), 'pynput.keyboard.KeyCode.from_char', 'KeyCode.from_char', (['"""`"""'], {}), "('`')\n", (2799, 2804), False, 'from pynput.keyboard import Listener, Key, KeyCode\n'), ((2806, 2828), 'pynput.keyboard.KeyCode.from_char', 'KeyCode.from_char', (['"""~"""'], {}), "('~')\n", (2823, 2828), False, 'from pynput.keyboard import Listener, Key, KeyCode\n'), ((3812, 3824), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (3822, 3824), True, 'import matplotlib.pyplot as plt\n'), ((3866, 3906), 'numpy.fromfile', 'np.fromfile', (['frameBufferPath'], {'dtype': '""">B"""'}), "(frameBufferPath, dtype='>B')\n", (3877, 3906), True, 'import numpy as np\n'), ((3925, 3959), 'numpy.reshape', 'np.reshape', (['flatByteArray', '(-1, 4)'], {}), '(flatByteArray, (-1, 4))\n', (3935, 3959), True, 'import numpy as np\n'), ((3975, 4033), 'numpy.zeros', 'np.zeros', (['[displayHeight, displayWidth, 3]'], {'dtype': 'np.uint8'}), '([displayHeight, displayWidth, 3], dtype=np.uint8)\n', (3983, 4033), True, 'import numpy as np\n'), ((4047, 4088), 'os.path.join', 'os.path.join', (['workDir', '"""createdImage.png"""'], {}), "(workDir, 'createdImage.png')\n", (4059, 4088), False, 'import os\n'), ((4766, 4816), 'matplotlib.animation.FuncAnimation', 'animation.FuncAnimation', (['fig', 'animate'], {'interval': '(20)'}), '(fig, animate, interval=20)\n', (4789, 4816), True, 'import matplotlib.animation as animation\n'), ((4818, 4828), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (4826, 4828), True, 'import matplotlib.pyplot as plt\n'), ((4159, 4198), 'numpy.fromfile', 'np.fromfile', (['frameBufferPath'], {'dtype': '"""B"""'}), "(frameBufferPath, dtype='B')\n", (4170, 4198), True, 'import numpy as np\n'), ((4218, 4252), 'numpy.reshape', 'np.reshape', (['flatByteArray', '(-1, 4)'], {}), '(flatByteArray, (-1, 4))\n', (4228, 4252), True, 'import numpy as np\n'), ((4594, 4621), 'PIL.Image.fromarray', 'Image.fromarray', (['pixelArray'], {}), '(pixelArray)\n', (4609, 4621), False, 'from PIL import Image\n'), ((4653, 4676), 'matplotlib.image.imread', 'mpimg.imread', (['imagePath'], {}), '(imagePath)\n', (4665, 4676), True, 'import matplotlib.image as mpimg\n'), ((4679, 4688), 'matplotlib.pyplot.clf', 'plt.clf', ([], {}), '()\n', (4686, 4688), True, 'import matplotlib.pyplot as plt\n'), ((4691, 4706), 'matplotlib.pyplot.axis', 'plt.axis', (['"""off"""'], {}), "('off')\n", (4699, 4706), True, 'import matplotlib.pyplot as plt\n'), ((4719, 4734), 'matplotlib.pyplot.imshow', 'plt.imshow', (['img'], {}), '(img)\n', (4729, 4734), True, 'import matplotlib.pyplot as plt\n'), ((6082, 6127), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': 'helpdesc'}), '(description=helpdesc)\n', (6105, 6127), False, 'import argparse\n'), ((12335, 12353), 'os.system', 'os.system', (['command'], {}), '(command)\n', (12344, 12353), False, 'import os\n'), ((12491, 12502), 'time.time', 'time.time', ([], {}), '()\n', (12500, 12502), False, 'import time\n'), ((12626, 12644), 'os.system', 'os.system', (['command'], {}), '(command)\n', (12635, 12644), False, 'import os\n'), ((12657, 12668), 'time.time', 'time.time', ([], {}), '()\n', (12666, 12668), False, 'import time\n'), ((8229, 8257), 'os.path.exists', 'os.path.exists', (['"""simulation"""'], {}), "('simulation')\n", (8243, 8257), False, 'import os\n'), ((8263, 8285), 'os.mkdir', 'os.mkdir', (['"""simulation"""'], {}), "('simulation')\n", (8271, 8285), False, 'import os\n'), ((12892, 12910), 'os.system', 'os.system', (['command'], {}), '(command)\n', (12901, 12910), False, 'import os\n'), ((12960, 12973), 'time.sleep', 'time.sleep', (['(2)'], {}), '(2)\n', (12970, 12973), False, 'import time\n'), ((11527, 11540), 'collections.OrderedDict', 'OrderedDict', ([], {}), '()\n', (11538, 11540), False, 'from collections import OrderedDict\n'), ((11787, 11829), 'numpy.zeros', 'np.zeros', (['stateArrayLength'], {'dtype': 'np.uint8'}), '(stateArrayLength, dtype=np.uint8)\n', (11795, 11829), True, 'import numpy as np\n'), ((11955, 12009), 'pynput.keyboard.Listener', 'Listener', ([], {'on_press': 'onKeyPress', 'on_release': 'onKeyRelease'}), '(on_press=onKeyPress, on_release=onKeyRelease)\n', (11963, 12009), False, 'from pynput.keyboard import Listener, Key, KeyCode\n'), ((13041, 13063), 'traceback.format_exc', 'traceback.format_exc', ([], {}), '()\n', (13061, 13063), False, 'import traceback\n'), ((4452, 4493), 'numpy.flip', 'np.flip', (['flatPixelArray[pixelIndex][0:-1]'], {}), '(flatPixelArray[pixelIndex][0:-1])\n', (4459, 4493), True, 'import numpy as np\n')]
from conway import conway import unittest import numpy as np class TestConway(unittest.TestCase): def test_still(self): """2x2 block""" A = np.zeros((10,10)) A[1:3,1:3] = 1 B = conway(A) assert (A == B).all() def test_scillator(self): """blinker""" A = np.zeros((10,10)) A[1:4,1] = 1 B = conway(A) assert (B[2, 0:3] == 1).all() B = conway(B) assert (A == B).all() def test_evolution(self): """test that something changes""" m, n = 10, 10 A = np.random.random(m*n).reshape((m, n)).round() B = conway(A) assert (B != A).any() if __name__ == '__main__': unittest.main()
[ "unittest.main", "conway.conway", "numpy.zeros", "numpy.random.random" ]
[((712, 727), 'unittest.main', 'unittest.main', ([], {}), '()\n', (725, 727), False, 'import unittest\n'), ((163, 181), 'numpy.zeros', 'np.zeros', (['(10, 10)'], {}), '((10, 10))\n', (171, 181), True, 'import numpy as np\n'), ((216, 225), 'conway.conway', 'conway', (['A'], {}), '(A)\n', (222, 225), False, 'from conway import conway\n'), ((321, 339), 'numpy.zeros', 'np.zeros', (['(10, 10)'], {}), '((10, 10))\n', (329, 339), True, 'import numpy as np\n'), ((372, 381), 'conway.conway', 'conway', (['A'], {}), '(A)\n', (378, 381), False, 'from conway import conway\n'), ((433, 442), 'conway.conway', 'conway', (['B'], {}), '(B)\n', (439, 442), False, 'from conway import conway\n'), ((638, 647), 'conway.conway', 'conway', (['A'], {}), '(A)\n', (644, 647), False, 'from conway import conway\n'), ((580, 603), 'numpy.random.random', 'np.random.random', (['(m * n)'], {}), '(m * n)\n', (596, 603), True, 'import numpy as np\n')]
import numpy as np import torch from pruning import RePruning class RePruningConvDet(RePruning): def __init__(self, softness, magnitude_threshold, metric_quantile, lr, sample, lb, scale): super().__init__() self.masks = {} self.strength = softness self.magnitude_threshold = magnitude_threshold self.metric_quantile = metric_quantile self.sample = sample self.lr = lr self.lb = lb self.scale = scale self.metrics = {} def compute_mask(self, model, acm_g, batch_idx): with torch.no_grad(): if (batch_idx+1) % self.lb == 0: self.metrics = {} for sample in range(self.sample): for i, (n, p) in enumerate(model.named_parameters()): if p.grad is not None and (not 'bias' in n) and ('conv' in n or 'features' in n): if len(p.shape) == 4: W = p G = acm_g[n] W0 = W - self.lr * G W = W / torch.norm(W) W0 = W0 / torch.norm(W0) sz_k = np.random.randint(int(p.shape[0] * self.scale)+1, p.shape[0]+1) #TODO ensure we can reach every filter sz_j = np.random.randint(int(p.shape[1] * self.scale)+1, p.shape[1]+1) for key in range(0, p.shape[0]-sz_k, sz_k): if p.shape[1] == 1: j = 0 if not "{}:{}:{}:{}:{}".format(n, key, j, sz_k, sz_j) in self.metrics: norm_w = torch.norm(W[key:key+sz_k, j, :, :]) if norm_w != 0: norm_w0 = torch.norm(W0[key:key + sz_k, j, :, :]) metric = norm_w / norm_w0 self.metrics["{}:{}:{}:{}:{}".format(n, key, j, sz_k, sz_j)] = metric.item() else: self.metrics["{}:{}:{}:{}:{}".format(n, key, j, sz_k, sz_j)] = float('inf') else: for j in range(0, p.shape[1]-sz_j, sz_j): if not "{}:{}:{}:{}:{}".format(n, key, j, sz_k, sz_j) in self.metrics: norm_w = torch.norm(W[key:key+sz_k, j+sz_j, :, :]) if norm_w != 0: norm_w0 = torch.norm(W0[key:key + sz_k, j:j + sz_j, :, :]) metric = norm_w / norm_w0 self.metrics["{}:{}:{}:{}:{}".format(n, key, j, sz_k, sz_j)] = metric.item() else: self.metrics["{}:{}:{}:{}:{}".format(n, key, j, sz_k, sz_j)] = float('inf') metric_vals = list(self.metrics.values()) if len(metric_vals) > 0: metric_threshold = np.quantile(list(self.metrics.values()), self.metric_quantile) candidates = {} for key in self.metrics: if self.metrics[key] <= metric_threshold and not np.isnan(self.metrics[key]) and not self.metrics[key] == float('inf'): idx = key.split(':') if idx[0] not in candidates: candidates[idx[0]] = [] candidates[idx[0]].append(key) #print(metric_threshold, flush=True) for n in candidates: #print(n, model.state_dict()[n].data.shape, len(candidates[n]), flush=True) mask = torch.ones_like(model.state_dict()[n].data) for key in candidates[n]: #print(key, flush=True) idx = key.split(':') mask[int(idx[1]):int(idx[1]) + int(idx[3])][int(idx[2]):int(idx[2]) + int(idx[4])] = mask[int( idx[1]):int(idx[1]) + int(idx[3])][int(idx[2]):int(idx[2]) + int(idx[4])] * 0.0 ''' mask = mask * torch.where( torch.abs(model.state_dict()[n].data) > self.magnitude_threshold, torch.ones_like(model.state_dict()[n].data), torch.zeros_like(model.state_dict()[n].data)) ''' if n in self.masks: self.masks[n] = self.masks[n] * mask else: self.masks[n] = mask def apply_mask(self, model): with torch.no_grad(): for i, (n, p) in enumerate(model.named_parameters()): if p.grad is not None and not 'bias' in n and ('conv' in n or 'features' in n): if n in self.masks: p.data = p.data * (self.masks[n] + (torch.ones_like(p.data) - self.masks[n]) * self.strength) if p.grad.data is not None: p.grad.data = p.grad.data * self.masks[n]#(self.masks[n] + (torch.ones_like(p.data) - self.masks[n]) * self.strength) def apply_threshold(self, model): with torch.no_grad(): for i, (n, p) in enumerate(model.named_parameters()): if p.grad is not None and not 'bias' in n and ('conv' in n or 'features' in n): p.data = torch.where(torch.abs(p.data) > self.magnitude_threshold, p.data, torch.zeros_like(p.data)) if p.data.grad is not None: # keep this or not? p.data.grad = torch.where(torch.abs(p.data.grad) > self.magnitude_threshold, p.data, torch.zeros_like(p.data.grad))
[ "torch.ones_like", "torch.zeros_like", "torch.norm", "numpy.isnan", "torch.no_grad", "torch.abs" ]
[((571, 586), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (584, 586), False, 'import torch\n'), ((5141, 5156), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (5154, 5156), False, 'import torch\n'), ((5728, 5743), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (5741, 5743), False, 'import torch\n'), ((6002, 6026), 'torch.zeros_like', 'torch.zeros_like', (['p.data'], {}), '(p.data)\n', (6018, 6026), False, 'import torch\n'), ((5948, 5965), 'torch.abs', 'torch.abs', (['p.data'], {}), '(p.data)\n', (5957, 5965), False, 'import torch\n'), ((6255, 6284), 'torch.zeros_like', 'torch.zeros_like', (['p.data.grad'], {}), '(p.data.grad)\n', (6271, 6284), False, 'import torch\n'), ((3607, 3634), 'numpy.isnan', 'np.isnan', (['self.metrics[key]'], {}), '(self.metrics[key])\n', (3615, 3634), True, 'import numpy as np\n'), ((6146, 6168), 'torch.abs', 'torch.abs', (['p.data.grad'], {}), '(p.data.grad)\n', (6155, 6168), False, 'import torch\n'), ((1123, 1136), 'torch.norm', 'torch.norm', (['W'], {}), '(W)\n', (1133, 1136), False, 'import torch\n'), ((1179, 1193), 'torch.norm', 'torch.norm', (['W0'], {}), '(W0)\n', (1189, 1193), False, 'import torch\n'), ((5420, 5443), 'torch.ones_like', 'torch.ones_like', (['p.data'], {}), '(p.data)\n', (5435, 5443), False, 'import torch\n'), ((1781, 1819), 'torch.norm', 'torch.norm', (['W[key:key + sz_k, j, :, :]'], {}), '(W[key:key + sz_k, j, :, :])\n', (1791, 1819), False, 'import torch\n'), ((1936, 1975), 'torch.norm', 'torch.norm', (['W0[key:key + sz_k, j, :, :]'], {}), '(W0[key:key + sz_k, j, :, :])\n', (1946, 1975), False, 'import torch\n'), ((2645, 2690), 'torch.norm', 'torch.norm', (['W[key:key + sz_k, j + sz_j, :, :]'], {}), '(W[key:key + sz_k, j + sz_j, :, :])\n', (2655, 2690), False, 'import torch\n'), ((2813, 2861), 'torch.norm', 'torch.norm', (['W0[key:key + sz_k, j:j + sz_j, :, :]'], {}), '(W0[key:key + sz_k, j:j + sz_j, :, :])\n', (2823, 2861), False, 'import torch\n')]
import numpy as np import pandas as pd import pytest from sklearn.model_selection import train_test_split from mercari.datasets_mx import prepare_vectorizer_1, prepare_vectorizer_2, prepare_vectorizer_3 from mercari.datasets_tf import prepare_vectorizer_1_tf, prepare_vectorizer_2_tf, prepare_vectorizer_3_tf from mercari.mercari_io import load_train from mercari.mx_sparse import MXRegression, MXRegressionClf from mercari.tf_sparse import RegressionHuber, RegressionClf from mercari.utils import rmsle @pytest.mark.parametrize('vectorizer', [ prepare_vectorizer_1(), prepare_vectorizer_2(), prepare_vectorizer_3(), prepare_vectorizer_1_tf(), prepare_vectorizer_2_tf(), prepare_vectorizer_3_tf(), ]) @pytest.mark.parametrize('model', [ MXRegression(n_epoch=3, loss='huber'), MXRegression(n_epoch=3, binary_X=True, loss='huber'), MXRegressionClf(n_epoch=3, n_hidden=(196, 64)), MXRegressionClf(n_epoch=3, n_hidden=(196, 64), binary_X=True), RegressionHuber(n_epoch=3), RegressionHuber(n_epoch=3, binary_X=True), RegressionClf(n_epoch=3, n_hidden=(196, 64)), RegressionClf(n_epoch=3, n_hidden=(196, 64), binary_X=True) ]) def test_end_to_end(vectorizer, model): _test(vectorizer, model, n_rows=None) @pytest.mark.parametrize('model', [ MXRegression(n_epoch=3, loss='huber'), MXRegressionClf(n_epoch=3, n_hidden=(196, 64)), RegressionHuber(n_epoch=3), RegressionClf(n_epoch=3, n_hidden=(196, 64)), ]) @pytest.mark.parametrize('vectorizer', [ prepare_vectorizer_1(), prepare_vectorizer_1_tf(), ]) @pytest.mark.parametrize('n_rows', [ None, 'random', 1, 2, 2**10, 2**13 - 1, 2**13, 2**13 + 1, 2**13 + 2**10, ]) def test_random_number_of_rows(vectorizer, model, n_rows): _test(vectorizer, model, n_rows) def _test(vectorizer, model, n_rows): tr = load_train('tests/train_10k.tsv') tr, va = train_test_split(tr) te = pd.read_csv('tests/test_10k_corrupted.tsv', sep="\t") if n_rows is not None: if n_rows == 'random': n_rows = np.random.randint(1, te.shape[0]) te = te.sample(n=n_rows) mat_tr = vectorizer.fit_transform(tr, tr.price) mat_te = vectorizer.transform(te.copy()) mat_va = vectorizer.transform(va) model.fit(mat_tr, np.log1p(tr.price)) assert rmsle(np.expm1(model.predict(mat_va)), va.price) < 0.85 te_preds = np.expm1(model.predict(mat_te)) assert te_preds.shape[0] == te.shape[0] assert np.all(np.isfinite(te_preds)) assert te_preds.min() >= -1, "min price is {}".format(te_preds.min()) assert te_preds.max() <= 3000, "max price is {}".format(te_preds.max())
[ "mercari.datasets_tf.prepare_vectorizer_3_tf", "mercari.mx_sparse.MXRegression", "mercari.datasets_mx.prepare_vectorizer_2", "mercari.mercari_io.load_train", "mercari.datasets_mx.prepare_vectorizer_3", "mercari.tf_sparse.RegressionClf", "pandas.read_csv", "sklearn.model_selection.train_test_split", "mercari.datasets_mx.prepare_vectorizer_1", "mercari.datasets_tf.prepare_vectorizer_2_tf", "numpy.isfinite", "mercari.tf_sparse.RegressionHuber", "numpy.random.randint", "mercari.mx_sparse.MXRegressionClf", "pytest.mark.parametrize", "mercari.datasets_tf.prepare_vectorizer_1_tf", "numpy.log1p" ]
[((1584, 1708), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""n_rows"""', "[None, 'random', 1, 2, 2 ** 10, 2 ** 13 - 1, 2 ** 13, 2 ** 13 + 1, 2 ** 13 +\n 2 ** 10]"], {}), "('n_rows', [None, 'random', 1, 2, 2 ** 10, 2 ** 13 -\n 1, 2 ** 13, 2 ** 13 + 1, 2 ** 13 + 2 ** 10])\n", (1607, 1708), False, 'import pytest\n'), ((1877, 1910), 'mercari.mercari_io.load_train', 'load_train', (['"""tests/train_10k.tsv"""'], {}), "('tests/train_10k.tsv')\n", (1887, 1910), False, 'from mercari.mercari_io import load_train\n'), ((1924, 1944), 'sklearn.model_selection.train_test_split', 'train_test_split', (['tr'], {}), '(tr)\n', (1940, 1944), False, 'from sklearn.model_selection import train_test_split\n'), ((1954, 2007), 'pandas.read_csv', 'pd.read_csv', (['"""tests/test_10k_corrupted.tsv"""'], {'sep': '"""\t"""'}), "('tests/test_10k_corrupted.tsv', sep='\\t')\n", (1965, 2007), True, 'import pandas as pd\n'), ((552, 574), 'mercari.datasets_mx.prepare_vectorizer_1', 'prepare_vectorizer_1', ([], {}), '()\n', (572, 574), False, 'from mercari.datasets_mx import prepare_vectorizer_1, prepare_vectorizer_2, prepare_vectorizer_3\n'), ((580, 602), 'mercari.datasets_mx.prepare_vectorizer_2', 'prepare_vectorizer_2', ([], {}), '()\n', (600, 602), False, 'from mercari.datasets_mx import prepare_vectorizer_1, prepare_vectorizer_2, prepare_vectorizer_3\n'), ((608, 630), 'mercari.datasets_mx.prepare_vectorizer_3', 'prepare_vectorizer_3', ([], {}), '()\n', (628, 630), False, 'from mercari.datasets_mx import prepare_vectorizer_1, prepare_vectorizer_2, prepare_vectorizer_3\n'), ((636, 661), 'mercari.datasets_tf.prepare_vectorizer_1_tf', 'prepare_vectorizer_1_tf', ([], {}), '()\n', (659, 661), False, 'from mercari.datasets_tf import prepare_vectorizer_1_tf, prepare_vectorizer_2_tf, prepare_vectorizer_3_tf\n'), ((667, 692), 'mercari.datasets_tf.prepare_vectorizer_2_tf', 'prepare_vectorizer_2_tf', ([], {}), '()\n', (690, 692), False, 'from mercari.datasets_tf import prepare_vectorizer_1_tf, prepare_vectorizer_2_tf, prepare_vectorizer_3_tf\n'), ((698, 723), 'mercari.datasets_tf.prepare_vectorizer_3_tf', 'prepare_vectorizer_3_tf', ([], {}), '()\n', (721, 723), False, 'from mercari.datasets_tf import prepare_vectorizer_1_tf, prepare_vectorizer_2_tf, prepare_vectorizer_3_tf\n'), ((768, 805), 'mercari.mx_sparse.MXRegression', 'MXRegression', ([], {'n_epoch': '(3)', 'loss': '"""huber"""'}), "(n_epoch=3, loss='huber')\n", (780, 805), False, 'from mercari.mx_sparse import MXRegression, MXRegressionClf\n'), ((811, 863), 'mercari.mx_sparse.MXRegression', 'MXRegression', ([], {'n_epoch': '(3)', 'binary_X': '(True)', 'loss': '"""huber"""'}), "(n_epoch=3, binary_X=True, loss='huber')\n", (823, 863), False, 'from mercari.mx_sparse import MXRegression, MXRegressionClf\n'), ((869, 915), 'mercari.mx_sparse.MXRegressionClf', 'MXRegressionClf', ([], {'n_epoch': '(3)', 'n_hidden': '(196, 64)'}), '(n_epoch=3, n_hidden=(196, 64))\n', (884, 915), False, 'from mercari.mx_sparse import MXRegression, MXRegressionClf\n'), ((921, 982), 'mercari.mx_sparse.MXRegressionClf', 'MXRegressionClf', ([], {'n_epoch': '(3)', 'n_hidden': '(196, 64)', 'binary_X': '(True)'}), '(n_epoch=3, n_hidden=(196, 64), binary_X=True)\n', (936, 982), False, 'from mercari.mx_sparse import MXRegression, MXRegressionClf\n'), ((988, 1014), 'mercari.tf_sparse.RegressionHuber', 'RegressionHuber', ([], {'n_epoch': '(3)'}), '(n_epoch=3)\n', (1003, 1014), False, 'from mercari.tf_sparse import RegressionHuber, RegressionClf\n'), ((1020, 1061), 'mercari.tf_sparse.RegressionHuber', 'RegressionHuber', ([], {'n_epoch': '(3)', 'binary_X': '(True)'}), '(n_epoch=3, binary_X=True)\n', (1035, 1061), False, 'from mercari.tf_sparse import RegressionHuber, RegressionClf\n'), ((1067, 1111), 'mercari.tf_sparse.RegressionClf', 'RegressionClf', ([], {'n_epoch': '(3)', 'n_hidden': '(196, 64)'}), '(n_epoch=3, n_hidden=(196, 64))\n', (1080, 1111), False, 'from mercari.tf_sparse import RegressionHuber, RegressionClf\n'), ((1117, 1176), 'mercari.tf_sparse.RegressionClf', 'RegressionClf', ([], {'n_epoch': '(3)', 'n_hidden': '(196, 64)', 'binary_X': '(True)'}), '(n_epoch=3, n_hidden=(196, 64), binary_X=True)\n', (1130, 1176), False, 'from mercari.tf_sparse import RegressionHuber, RegressionClf\n'), ((1304, 1341), 'mercari.mx_sparse.MXRegression', 'MXRegression', ([], {'n_epoch': '(3)', 'loss': '"""huber"""'}), "(n_epoch=3, loss='huber')\n", (1316, 1341), False, 'from mercari.mx_sparse import MXRegression, MXRegressionClf\n'), ((1347, 1393), 'mercari.mx_sparse.MXRegressionClf', 'MXRegressionClf', ([], {'n_epoch': '(3)', 'n_hidden': '(196, 64)'}), '(n_epoch=3, n_hidden=(196, 64))\n', (1362, 1393), False, 'from mercari.mx_sparse import MXRegression, MXRegressionClf\n'), ((1399, 1425), 'mercari.tf_sparse.RegressionHuber', 'RegressionHuber', ([], {'n_epoch': '(3)'}), '(n_epoch=3)\n', (1414, 1425), False, 'from mercari.tf_sparse import RegressionHuber, RegressionClf\n'), ((1431, 1475), 'mercari.tf_sparse.RegressionClf', 'RegressionClf', ([], {'n_epoch': '(3)', 'n_hidden': '(196, 64)'}), '(n_epoch=3, n_hidden=(196, 64))\n', (1444, 1475), False, 'from mercari.tf_sparse import RegressionHuber, RegressionClf\n'), ((1525, 1547), 'mercari.datasets_mx.prepare_vectorizer_1', 'prepare_vectorizer_1', ([], {}), '()\n', (1545, 1547), False, 'from mercari.datasets_mx import prepare_vectorizer_1, prepare_vectorizer_2, prepare_vectorizer_3\n'), ((1553, 1578), 'mercari.datasets_tf.prepare_vectorizer_1_tf', 'prepare_vectorizer_1_tf', ([], {}), '()\n', (1576, 1578), False, 'from mercari.datasets_tf import prepare_vectorizer_1_tf, prepare_vectorizer_2_tf, prepare_vectorizer_3_tf\n'), ((2315, 2333), 'numpy.log1p', 'np.log1p', (['tr.price'], {}), '(tr.price)\n', (2323, 2333), True, 'import numpy as np\n'), ((2511, 2532), 'numpy.isfinite', 'np.isfinite', (['te_preds'], {}), '(te_preds)\n', (2522, 2532), True, 'import numpy as np\n'), ((2087, 2120), 'numpy.random.randint', 'np.random.randint', (['(1)', 'te.shape[0]'], {}), '(1, te.shape[0])\n', (2104, 2120), True, 'import numpy as np\n')]
import argparse from source import tools from config import option import random from source import runtime from source import constants as C import json import numpy as np parser = argparse.ArgumentParser(description="Im2Latex Training Program") parser.add_argument("-m", "--mode", dest="mode", choices=("train", "test"), default="train", help="游戏模式") parser.add_argument("-d", "--difficulty", default="hard", help="游戏难度") parser.add_argument("-n", "--num", default=4, help="创建环境个数") args = parser.parse_args() class Player(): def __init__(self): self.cord = None def left(self): self.cord[1] -= 1 def right(self): self.cord[1] += 1 def up(self): self.cord[0] -= 1 def down(self): self.cord[0] += 1 class Target(): def __init__(self): self.cord = None self.history = [] self.oppo_dir = {'up': 'down', 'down': 'up', 'left': 'right', 'right': 'left'} class Game(): def __init__(self, mode=args.mode, difficulty=args.difficulty): self.mode = mode self.difficulty = difficulty self.restart = False self.init_game() def init_game(self): self.setup_env() self.setup_player() self.setup_target() self.setup_runtime() def setup_runtime(self): self.runtime.game_info = {'score': 100, 'round': 0, 'mode': self.mode, 'difficulty': self.difficulty} self.runtime.client_info = runtime.ClientInfo(option.init_score, (10, 10), len(self.maze), self.runtime.game_info['round'], self.runtime.maze_info['bonusValue'], 0, self.player.cord, self.target.cord) self.client_info = self.runtime.client_info def setup_env(self): self.runtime = runtime.RuntimeGlobalInfo() if self.mode.mode == 'train': self.runtime.maze_info = tools.get_blind_maze() else: with open(option.maze_file_path, 'r') as f: k = f.readlines() k = [eval(x.strip('\n')) for x in k] self.runtime.maze_info = random.choice(k) self.maze_info = self.runtime.maze_info self.maze = self.maze_info['maze'] def setup_player(self): self.player = Player() self.player.cord = [1, 1] def setup_target(self): self.target = Target() self.target.cord = [int(len(self.maze)-1/2)-1, int(len(self.maze)-1/2)-1] def player_move(self, type_): if self.restart: self.init_game() self.restart = False self.client_info.total_steps += 1 current_coordinate = self.player.cord candidate_cor = None if type_ == 'left': candidate_cor = [current_coordinate[0], current_coordinate[1] - 1] elif type_ == 'right': candidate_cor = [current_coordinate[0], current_coordinate[1] + 1] elif type_ == 'up': candidate_cor = [current_coordinate[0] - 1, current_coordinate[1]] elif type_ == 'down': candidate_cor = [current_coordinate[0] + 1, current_coordinate[1]] elif type_ == 'get': candidate_cor = current_coordinate item_type = self.check_move(candidate_cor) if item_type == 'road': current_coordinate = candidate_cor self.runtime.game_info['score'] -= 1 elif item_type == 'coin': current_coordinate = candidate_cor self.runtime.game_info['score'] += self.runtime.maze_info['bonusValue'] self.maze[current_coordinate[0]][current_coordinate[1]] = 0 elif item_type == 'brick': self.runtime.game_info['score'] -= 2 elif item_type == 'boom': self.runtime.game_info['score'] -= 1000 self.client_info.score = self.runtime.game_info['score'] if self.client_info.score <= 0: self.client_info.state = -1 self.restart = True elif current_coordinate == self.target.cord: self.client_info.state = 1 self.restart = True self.player.cord = current_coordinate self.process_neighbours() self.client_info.player_cord = self.player.cord self.move_target() self.client_info.target_cord = self.target.cord return self.get_client_info() def check_move(self, candidate): if self.maze[candidate[0]][candidate[1]] == 0: return 'road' elif self.maze[candidate[0]][candidate[1]] == 2: return 'coin' elif self.maze[candidate[0]][candidate[1]] == -1: return 'boom' elif self.maze[candidate[0]][candidate[1]] == 1: return 'brick' def get_local_range(self, range_): center = self.player.cord minY = max(center[0] - range_, 0) maxY = min(center[0] + range_, len(self.maze)-1) minX = max(center[1] - range_, 0) maxX = min(center[1] + range_, len(self.maze[0])-1) return (minX, minY, maxX, maxY) def process_neighbours(self): minX, minY, maxX, maxY = self.get_local_range(C.MODAL_RANGE) for i in range(minX, maxX+1): for j in range(minY, maxY+1): symbol = self.maze[j][i] self.client_info.maze[j][i] = symbol def get_client_info(self): return json.dumps(self.runtime.client_info, default=lambda obj: obj.__dict__, sort_keys=True, indent=4) def get_distance(self, x, y): return np.sqrt(np.square(x[0]-y[0]) + np.square(x[1]-y[1])) def move_target(self): difficulty = self.runtime.game_info['difficulty'] if difficulty == 'simple': if random.uniform(0, 1) >= 0.8: return if self.player.cord == self.target.cord: return target_candidate = {'up': [self.target.cord[0] - 1, self.target.cord[1]], 'down': [self.target.cord[0] + 1, self.target.cord[1]], 'left': [self.target.cord[0], self.target.cord[1] - 1], 'right': [self.target.cord[0], self.target.cord[1] + 1]} direct_cand = [] coor_cand = [] if abs(self.target.cord[0]-self.player.cord[0])>C.MODAL_RANGE or abs(self.target.cord[1]-self.player.cord[1])>C.MODAL_RANGE: for k,v in target_candidate.items(): if self.maze[v[0]][v[1]] in [0, 2]: if k in self.target.history[-3:]: if random.uniform(0,1) > 0.7: direct_cand.append(k) coor_cand.append(v) else: oppo_dir = self.target.oppo_dir[k] direct_cand.append(oppo_dir) coor_cand.append(v) if coor_cand != []: choosen_ind = random.randint(0, len(coor_cand)-1) self.target.cord = coor_cand[choosen_ind] self.target.history.append(direct_cand[choosen_ind]) else: self.target.history.append("nothing") else: current_distance = self.get_distance(self.target.cord, self.player.cord) back_cor_cand = [] back_dir_cand = [] for k,v in target_candidate.items(): if self.maze[v[0]][v[1]] in [0, 2]: candidate_distance = self.get_distance(self.player.cord, v) if candidate_distance >= current_distance: direct_cand.append(k) coor_cand.append(v) else: back_dir_cand.append(k) back_cor_cand.append(v) if coor_cand == []: coor_cand = back_cor_cand direct_cand = back_dir_cand if coor_cand != []: choosen_ind = random.randint(0, len(coor_cand) - 1) self.target.cord = coor_cand[choosen_ind] self.target.history.append(direct_cand[choosen_ind]) else: self.target.history.append("nothing") def step(self, action): return self.player_move(action) def showMaze(self, mazeMatrix): for x, row in enumerate(mazeMatrix): for y, ele in enumerate(row): if ele == 2: print(f'\033[1;32m $ \033[0m', end="") elif [x, y] in [self.target.cord, self.player.cord]: print('\033[0;32m' + "^ " + " " + '\033[0m', end="") elif ele == 1: print(f'\033[1;47m # \033[0m', end="") elif ele == 0: print(f'\033[1;40m * \033[0m', end="") elif ele == -1: print(f'\033[1;31;47m O \033[0m', end="") else: print(f'\033[1;31;48m 9 \033[0m', end="") print('') class Server(): def __init__(self, game_num=args.num): self.games = [Game(args) for _ in range(game_num)] def step(self, move_batch:list, verbose=False): assert len(move_batch) == len(self.games), ValueError(f"Batch size expected {self.games}, but got {len(move_batch)}") res = [] for ii in range(len(self.games)): res.append(json.loads(self.games[ii].step(move_batch[ii]))) if verbose: self.games[ii].showMaze(json.loads(self.games[ii].get_client_info())['maze']) print(">" * 40) print() return res if __name__ == '__main__': s = Server(1) # 环境个数 v = False for i in range(101): if i >= 99: v = True r = s.step(['right'], verbose=v) if v: print(r)
[ "source.tools.get_blind_maze", "argparse.ArgumentParser", "random.uniform", "numpy.square", "random.choice", "source.runtime.RuntimeGlobalInfo", "json.dumps" ]
[((183, 247), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Im2Latex Training Program"""'}), "(description='Im2Latex Training Program')\n", (206, 247), False, 'import argparse\n'), ((1888, 1915), 'source.runtime.RuntimeGlobalInfo', 'runtime.RuntimeGlobalInfo', ([], {}), '()\n', (1913, 1915), False, 'from source import runtime\n'), ((5457, 5557), 'json.dumps', 'json.dumps', (['self.runtime.client_info'], {'default': '(lambda obj: obj.__dict__)', 'sort_keys': '(True)', 'indent': '(4)'}), '(self.runtime.client_info, default=lambda obj: obj.__dict__,\n sort_keys=True, indent=4)\n', (5467, 5557), False, 'import json\n'), ((1991, 2013), 'source.tools.get_blind_maze', 'tools.get_blind_maze', ([], {}), '()\n', (2011, 2013), False, 'from source import tools\n'), ((2208, 2224), 'random.choice', 'random.choice', (['k'], {}), '(k)\n', (2221, 2224), False, 'import random\n'), ((5612, 5634), 'numpy.square', 'np.square', (['(x[0] - y[0])'], {}), '(x[0] - y[0])\n', (5621, 5634), True, 'import numpy as np\n'), ((5635, 5657), 'numpy.square', 'np.square', (['(x[1] - y[1])'], {}), '(x[1] - y[1])\n', (5644, 5657), True, 'import numpy as np\n'), ((5793, 5813), 'random.uniform', 'random.uniform', (['(0)', '(1)'], {}), '(0, 1)\n', (5807, 5813), False, 'import random\n'), ((6611, 6631), 'random.uniform', 'random.uniform', (['(0)', '(1)'], {}), '(0, 1)\n', (6625, 6631), False, 'import random\n')]
import os import random import torch import numpy as np from time import time from tqdm import tqdm from copy import deepcopy from pathlib import Path from prettytable import PrettyTable from common.test import test_v2 from common.utils import early_stopping, print_dict from common.config import parse_args from common.dataset import CKGData from common.dataset.build import build_loader from modules.sampler import KGPolicy from modules.recommender import MF def train_one_epoch( recommender, sampler, train_loader, recommender_optim, sampler_optim, adj_matrix, edge_matrix, train_data, cur_epoch, avg_reward, ): loss, base_loss, reg_loss = 0, 0, 0 epoch_reward = 0 """Train one epoch""" tbar = tqdm(train_loader, ascii=True) num_batch = len(train_loader) for batch_data in tbar: tbar.set_description("Epoch {}".format(cur_epoch)) if torch.cuda.is_available(): batch_data = {k: v.cuda(non_blocking=True) for k, v in batch_data.items()} """Train recommender using negtive item provided by sampler""" recommender_optim.zero_grad() neg = batch_data["neg_i_id"] pos = batch_data["pos_i_id"] users = batch_data["u_id"] selected_neg_items_list, _ = sampler(batch_data, adj_matrix, edge_matrix) selected_neg_items = selected_neg_items_list[-1, :] train_set = train_data[users] in_train = torch.sum( selected_neg_items.unsqueeze(1) == train_set.long(), dim=1 ).byte() selected_neg_items[in_train] = neg[in_train] base_loss_batch, reg_loss_batch = recommender(users, pos, selected_neg_items) loss_batch = base_loss_batch + reg_loss_batch loss_batch.backward() recommender_optim.step() """Train sampler network""" sampler_optim.zero_grad() selected_neg_items_list, selected_neg_prob_list = sampler( batch_data, adj_matrix, edge_matrix ) with torch.no_grad(): reward_batch = recommender.get_reward(users, pos, selected_neg_items_list) epoch_reward += torch.sum(reward_batch) reward_batch -= avg_reward batch_size = reward_batch.size(1) n = reward_batch.size(0) - 1 R = torch.zeros(batch_size, device=reward_batch.device) reward = torch.zeros(reward_batch.size(), device=reward_batch.device) gamma = args_config.gamma for i, r in enumerate(reward_batch.flip(0)): R = r + gamma * R reward[n - i] = R reinforce_loss = -1 * torch.sum(reward_batch * selected_neg_prob_list) reinforce_loss.backward() sampler_optim.step() """record loss in an epoch""" loss += loss_batch reg_loss += reg_loss_batch base_loss += base_loss_batch avg_reward = epoch_reward / num_batch train_res = PrettyTable() train_res.field_names = ["Epoch", "Loss", "BPR-Loss", "Regulation", "AVG-Reward"] train_res.add_row( [cur_epoch, loss.item(), base_loss.item(), reg_loss.item(), avg_reward.item()] ) print(train_res) return loss, base_loss, reg_loss, avg_reward def save_model(file_name, model, config): if not os.path.isdir(config.out_dir): os.mkdir(config.out_dir) model_file = Path(config.out_dir + file_name) model_file.touch(exist_ok=True) print("Saving model...") torch.save(model.state_dict(), model_file) def build_sampler_graph(n_nodes, edge_threshold, graph): adj_matrix = torch.zeros(n_nodes, edge_threshold * 2) edge_matrix = torch.zeros(n_nodes, edge_threshold) """sample neighbors for each node""" for node in tqdm(graph.nodes, ascii=True, desc="Build sampler matrix"): neighbors = list(graph.neighbors(node)) if len(neighbors) >= edge_threshold: sampled_edge = random.sample(neighbors, edge_threshold) edges = deepcopy(sampled_edge) else: neg_id = random.sample( range(CKG.item_range[0], CKG.item_range[1] + 1), edge_threshold - len(neighbors), ) node_id = [node] * (edge_threshold - len(neighbors)) sampled_edge = neighbors + neg_id edges = neighbors + node_id """concatenate sampled edge with random edge""" sampled_edge += random.sample( range(CKG.item_range[0], CKG.item_range[1] + 1), edge_threshold ) adj_matrix[node] = torch.tensor(sampled_edge, dtype=torch.long) edge_matrix[node] = torch.tensor(edges, dtype=torch.long) if torch.cuda.is_available(): adj_matrix = adj_matrix.cuda().long() edge_matrix = edge_matrix.cuda().long() return adj_matrix, edge_matrix def build_train_data(train_mat): num_user = max(train_mat.keys()) + 1 num_true = max([len(i) for i in train_mat.values()]) train_data = torch.zeros(num_user, num_true) for i in train_mat.keys(): true_list = train_mat[i] true_list += [-1] * (num_true - len(true_list)) train_data[i] = torch.tensor(true_list, dtype=torch.long) return train_data def train(train_loader, test_loader, graph, data_config, args_config): """build padded training set""" train_mat = graph.train_user_dict train_data = build_train_data(train_mat) if args_config.pretrain_r: print( "\nLoad model from {}".format( args_config.data_path + args_config.model_path ) ) paras = torch.load(args_config.data_path + args_config.model_path) all_embed = torch.cat((paras["user_para"], paras["item_para"])) data_config["all_embed"] = all_embed recommender = MF(data_config=data_config, args_config=args_config) sampler = KGPolicy(recommender, data_config, args_config) if torch.cuda.is_available(): train_data = train_data.long().cuda() sampler = sampler.cuda() recommender = recommender.cuda() print("\nSet sampler as: {}".format(str(sampler))) print("Set recommender as: {}\n".format(str(recommender))) recommender_optimer = torch.optim.Adam(recommender.parameters(), lr=args_config.rlr) sampler_optimer = torch.optim.Adam(sampler.parameters(), lr=args_config.slr) loss_loger, pre_loger, rec_loger, ndcg_loger, hit_loger = [], [], [], [], [] stopping_step, cur_best_pre_0, avg_reward = 0, 0.0, 0 t0 = time() for epoch in range(args_config.epoch): if epoch % args_config.adj_epoch == 0: """sample adjacency matrix""" adj_matrix, edge_matrix = build_sampler_graph( data_config["n_nodes"], args_config.edge_threshold, graph.ckg_graph ) cur_epoch = epoch + 1 loss, base_loss, reg_loss, avg_reward = train_one_epoch( recommender, sampler, train_loader, recommender_optimer, sampler_optimer, adj_matrix, edge_matrix, train_data, cur_epoch, avg_reward, ) """Test""" if cur_epoch % args_config.show_step == 0: with torch.no_grad(): ret = test_v2(recommender, args_config.Ks, graph) loss_loger.append(loss) rec_loger.append(ret["recall"]) pre_loger.append(ret["precision"]) ndcg_loger.append(ret["ndcg"]) hit_loger.append(ret["hit_ratio"]) print_dict(ret) cur_best_pre_0, stopping_step, should_stop = early_stopping( ret["recall"][0], cur_best_pre_0, stopping_step, expected_order="acc", flag_step=args_config.flag_step, ) if should_stop: break recs = np.array(rec_loger) pres = np.array(pre_loger) ndcgs = np.array(ndcg_loger) hit = np.array(hit_loger) best_rec_0 = max(recs[:, 0]) idx = list(recs[:, 0]).index(best_rec_0) final_perf = ( "Best Iter=[%d]@[%.1f]\n recall=[%s] \n precision=[%s] \n hit=[%s] \n ndcg=[%s]" % ( idx, time() - t0, "\t".join(["%.5f" % r for r in recs[idx]]), "\t".join(["%.5f" % r for r in pres[idx]]), "\t".join(["%.5f" % r for r in hit[idx]]), "\t".join(["%.5f" % r for r in ndcgs[idx]]), ) ) print(final_perf) if __name__ == "__main__": """fix the random seed""" seed = 2020 random.seed(seed) np.random.seed(seed) torch.manual_seed(seed) """initialize args and dataset""" args_config = parse_args() CKG = CKGData(args_config) """set the gpu id""" if torch.cuda.is_available(): torch.cuda.set_device(args_config.gpu_id) data_config = { "n_users": CKG.n_users, "n_items": CKG.n_items, "n_relations": CKG.n_relations + 2, "n_entities": CKG.n_entities, "n_nodes": CKG.entity_range[1] + 1, "item_range": CKG.item_range, } print("\ncopying CKG graph for data_loader.. it might take a few minutes") graph = deepcopy(CKG) train_loader, test_loader = build_loader(args_config=args_config, graph=graph) train( train_loader=train_loader, test_loader=test_loader, graph=CKG, data_config=data_config, args_config=args_config, )
[ "os.mkdir", "numpy.random.seed", "common.test.test_v2", "random.sample", "torch.cat", "common.dataset.CKGData", "pathlib.Path", "prettytable.PrettyTable", "common.utils.print_dict", "torch.no_grad", "common.utils.early_stopping", "torch.load", "random.seed", "torch.zeros", "torch.cuda.set_device", "tqdm.tqdm", "copy.deepcopy", "torch.manual_seed", "common.dataset.build.build_loader", "torch.cuda.is_available", "torch.sum", "modules.sampler.KGPolicy", "modules.recommender.MF", "os.path.isdir", "common.config.parse_args", "time.time", "numpy.array", "torch.tensor" ]
[((761, 791), 'tqdm.tqdm', 'tqdm', (['train_loader'], {'ascii': '(True)'}), '(train_loader, ascii=True)\n', (765, 791), False, 'from tqdm import tqdm\n'), ((2927, 2940), 'prettytable.PrettyTable', 'PrettyTable', ([], {}), '()\n', (2938, 2940), False, 'from prettytable import PrettyTable\n'), ((3351, 3383), 'pathlib.Path', 'Path', (['(config.out_dir + file_name)'], {}), '(config.out_dir + file_name)\n', (3355, 3383), False, 'from pathlib import Path\n'), ((3573, 3613), 'torch.zeros', 'torch.zeros', (['n_nodes', '(edge_threshold * 2)'], {}), '(n_nodes, edge_threshold * 2)\n', (3584, 3613), False, 'import torch\n'), ((3632, 3668), 'torch.zeros', 'torch.zeros', (['n_nodes', 'edge_threshold'], {}), '(n_nodes, edge_threshold)\n', (3643, 3668), False, 'import torch\n'), ((3727, 3785), 'tqdm.tqdm', 'tqdm', (['graph.nodes'], {'ascii': '(True)', 'desc': '"""Build sampler matrix"""'}), "(graph.nodes, ascii=True, desc='Build sampler matrix')\n", (3731, 3785), False, 'from tqdm import tqdm\n'), ((4649, 4674), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (4672, 4674), False, 'import torch\n'), ((4957, 4988), 'torch.zeros', 'torch.zeros', (['num_user', 'num_true'], {}), '(num_user, num_true)\n', (4968, 4988), False, 'import torch\n'), ((5779, 5831), 'modules.recommender.MF', 'MF', ([], {'data_config': 'data_config', 'args_config': 'args_config'}), '(data_config=data_config, args_config=args_config)\n', (5781, 5831), False, 'from modules.recommender import MF\n'), ((5846, 5893), 'modules.sampler.KGPolicy', 'KGPolicy', (['recommender', 'data_config', 'args_config'], {}), '(recommender, data_config, args_config)\n', (5854, 5893), False, 'from modules.sampler import KGPolicy\n'), ((5902, 5927), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (5925, 5927), False, 'import torch\n'), ((6496, 6502), 'time.time', 'time', ([], {}), '()\n', (6500, 6502), False, 'from time import time\n'), ((7906, 7925), 'numpy.array', 'np.array', (['rec_loger'], {}), '(rec_loger)\n', (7914, 7925), True, 'import numpy as np\n'), ((7937, 7956), 'numpy.array', 'np.array', (['pre_loger'], {}), '(pre_loger)\n', (7945, 7956), True, 'import numpy as np\n'), ((7969, 7989), 'numpy.array', 'np.array', (['ndcg_loger'], {}), '(ndcg_loger)\n', (7977, 7989), True, 'import numpy as np\n'), ((8000, 8019), 'numpy.array', 'np.array', (['hit_loger'], {}), '(hit_loger)\n', (8008, 8019), True, 'import numpy as np\n'), ((8603, 8620), 'random.seed', 'random.seed', (['seed'], {}), '(seed)\n', (8614, 8620), False, 'import random\n'), ((8625, 8645), 'numpy.random.seed', 'np.random.seed', (['seed'], {}), '(seed)\n', (8639, 8645), True, 'import numpy as np\n'), ((8650, 8673), 'torch.manual_seed', 'torch.manual_seed', (['seed'], {}), '(seed)\n', (8667, 8673), False, 'import torch\n'), ((8731, 8743), 'common.config.parse_args', 'parse_args', ([], {}), '()\n', (8741, 8743), False, 'from common.config import parse_args\n'), ((8754, 8774), 'common.dataset.CKGData', 'CKGData', (['args_config'], {}), '(args_config)\n', (8761, 8774), False, 'from common.dataset import CKGData\n'), ((8808, 8833), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (8831, 8833), False, 'import torch\n'), ((9232, 9245), 'copy.deepcopy', 'deepcopy', (['CKG'], {}), '(CKG)\n', (9240, 9245), False, 'from copy import deepcopy\n'), ((9278, 9328), 'common.dataset.build.build_loader', 'build_loader', ([], {'args_config': 'args_config', 'graph': 'graph'}), '(args_config=args_config, graph=graph)\n', (9290, 9328), False, 'from common.dataset.build import build_loader\n'), ((926, 951), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (949, 951), False, 'import torch\n'), ((2157, 2180), 'torch.sum', 'torch.sum', (['reward_batch'], {}), '(reward_batch)\n', (2166, 2180), False, 'import torch\n'), ((2308, 2359), 'torch.zeros', 'torch.zeros', (['batch_size'], {'device': 'reward_batch.device'}), '(batch_size, device=reward_batch.device)\n', (2319, 2359), False, 'import torch\n'), ((3269, 3298), 'os.path.isdir', 'os.path.isdir', (['config.out_dir'], {}), '(config.out_dir)\n', (3282, 3298), False, 'import os\n'), ((3308, 3332), 'os.mkdir', 'os.mkdir', (['config.out_dir'], {}), '(config.out_dir)\n', (3316, 3332), False, 'import os\n'), ((4530, 4574), 'torch.tensor', 'torch.tensor', (['sampled_edge'], {'dtype': 'torch.long'}), '(sampled_edge, dtype=torch.long)\n', (4542, 4574), False, 'import torch\n'), ((4603, 4640), 'torch.tensor', 'torch.tensor', (['edges'], {'dtype': 'torch.long'}), '(edges, dtype=torch.long)\n', (4615, 4640), False, 'import torch\n'), ((5134, 5175), 'torch.tensor', 'torch.tensor', (['true_list'], {'dtype': 'torch.long'}), '(true_list, dtype=torch.long)\n', (5146, 5175), False, 'import torch\n'), ((5584, 5642), 'torch.load', 'torch.load', (['(args_config.data_path + args_config.model_path)'], {}), '(args_config.data_path + args_config.model_path)\n', (5594, 5642), False, 'import torch\n'), ((5663, 5714), 'torch.cat', 'torch.cat', (["(paras['user_para'], paras['item_para'])"], {}), "((paras['user_para'], paras['item_para']))\n", (5672, 5714), False, 'import torch\n'), ((8843, 8884), 'torch.cuda.set_device', 'torch.cuda.set_device', (['args_config.gpu_id'], {}), '(args_config.gpu_id)\n', (8864, 8884), False, 'import torch\n'), ((2028, 2043), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (2041, 2043), False, 'import torch\n'), ((2618, 2666), 'torch.sum', 'torch.sum', (['(reward_batch * selected_neg_prob_list)'], {}), '(reward_batch * selected_neg_prob_list)\n', (2627, 2666), False, 'import torch\n'), ((3907, 3947), 'random.sample', 'random.sample', (['neighbors', 'edge_threshold'], {}), '(neighbors, edge_threshold)\n', (3920, 3947), False, 'import random\n'), ((3968, 3990), 'copy.deepcopy', 'deepcopy', (['sampled_edge'], {}), '(sampled_edge)\n', (3976, 3990), False, 'from copy import deepcopy\n'), ((7555, 7570), 'common.utils.print_dict', 'print_dict', (['ret'], {}), '(ret)\n', (7565, 7570), False, 'from common.utils import early_stopping, print_dict\n'), ((7629, 7751), 'common.utils.early_stopping', 'early_stopping', (["ret['recall'][0]", 'cur_best_pre_0', 'stopping_step'], {'expected_order': '"""acc"""', 'flag_step': 'args_config.flag_step'}), "(ret['recall'][0], cur_best_pre_0, stopping_step,\n expected_order='acc', flag_step=args_config.flag_step)\n", (7643, 7751), False, 'from common.utils import early_stopping, print_dict\n'), ((7241, 7256), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (7254, 7256), False, 'import torch\n'), ((7280, 7323), 'common.test.test_v2', 'test_v2', (['recommender', 'args_config.Ks', 'graph'], {}), '(recommender, args_config.Ks, graph)\n', (7287, 7323), False, 'from common.test import test_v2\n'), ((8249, 8255), 'time.time', 'time', ([], {}), '()\n', (8253, 8255), False, 'from time import time\n')]
import numpy as np import copy from scipy import optimize from astropy.stats import median_absolute_deviation from astropy.table import Column, Table, vstack from numpy.polynomial import legendre from scipy import interpolate from xwavecal.images import Image from xwavecal.stages import Stage, ApplyCalibration from xwavecal.utils.wavelength_utils import identify_lines, calc_residuals, restrict, Model, _sigma_clip from xwavecal.utils.wavelength_utils import estimate_global_scale, normalize_coordinates, pixel_order_as_array from xwavecal.utils.overlap_utils import flag_bad_overlaps, fit_overlaps, blank_overlap_table, flag_outlier_overlaps from xwavecal.utils.misc_utils import brute_local_min, find_nearest, minmax from xwavecal.utils.fiber_utils import lit_wavecal_fibers import logging logger = logging.getLogger(__name__) class WavelengthSolution(object): """ Class to evaluate, contain and update the wavelength solution. Notable attributes: WavelengthSolution.model gives the current model of the wavelength solution. WavelengthSolution.model_coefficients gives the coefficients for the current model, in the order of WavelengthSolution.model. """ def __init__(self, model=None, model_coefficients=None, measured_lines: dict = None, reference_lines=None, m0=30, max_pixel=100, max_order=2, min_order=0, min_pixel=0, overlap_range=(), grating_eq=True): if model is None: model = {1: [0, 1], 2: [0, 1]} self.max_order = max_order self.max_pixel = max_pixel self.min_pixel = min_pixel self.min_order = min_order self.model = Model(model) self.m0 = m0 self.overlap_range = overlap_range self.model_coefficients = model_coefficients self.reference_lines = reference_lines self.grating_eq = grating_eq # True to use a 1/(m0+i) prefactor. self._measured_lines = None self.measured_lines = measured_lines @property def measured_lines(self): return self._measured_lines @measured_lines.setter def measured_lines(self, lines): if lines is not None and lines.get('order', None) is not None and lines.get('pixel', None) is not None: lines['normed_pixel'] = normalize_coordinates(lines['pixel'], max_value=self.max_pixel, min_value=self.min_pixel) lines['normed_order'] = normalize_coordinates(lines['order'], max_value=self.max_order, min_value=self.min_order) self._measured_lines = lines def __call__(self, pixel, order): """ :param pixel: ndarray. array (any shape) of pixel coordinates of spectral features. :param order: ndarray. Same length as pixel. array of order indices of spectral features. :return: ndarray. array of wavelengths. Same shape as pixel and order. """ normed_pixel = normalize_coordinates(pixel, max_value=self.max_pixel, min_value=self.min_pixel) normed_order = normalize_coordinates(order, max_value=self.max_order, min_value=self.min_order) return self.wavelength_normed_input(normed_pixel, normed_order, order) def wavelength_normed_input(self, normed_pixel, normed_order, order, **kwargs): A, c = self._construct_wavelength_map_matrices(normed_pixel.flatten(), normed_order.flatten(), order.flatten()) wavelengths = self._map_to_wavelength(A, c, self.model_coefficients) return wavelengths.reshape(normed_pixel.shape) def update_model(self, new_model, grating_eq=True): pixel, order = np.meshgrid(np.linspace(self.min_pixel, self.max_pixel, 30), np.arange(self.min_order, self.max_order + 1)) coords = {'pixel': pixel.flatten(), 'order': order.flatten()} coords['normed_pixel'] = normalize_coordinates(coords['pixel'], self.max_pixel, self.min_pixel) coords['normed_order'] = normalize_coordinates(coords['order'], self.max_order, self.min_order) old_wavelengths = self.wavelength_normed_input(**coords) self.model = Model(new_model) self.grating_eq = grating_eq self.model_coefficients = self.solve(coords, old_wavelengths) def solve(self, line_coordinates, wavelengths_to_fit, weights=None): """ :param weights: array. A 1d array of weights. E.g. the square root of the inverse variance. :return: array: best fit coefficients """ weights = np.array([1]) if weights is None else weights A, c = self._construct_wavelength_map_matrices(**line_coordinates) c += np.array(wavelengths_to_fit).reshape(-1, 1) model_coefficients, residuals = np.linalg.lstsq(A * weights.reshape(-1, 1), c * weights.reshape(-1, 1), rcond=None)[:2] return model_coefficients.flatten() def solve_from_overlaps(self, overlaps): if 0 in self.model: logger.error('Model contains parameters independent of pixel coordinate x. ' 'Overlap fit will fail. Do not include 0: [...] terms in ' 'the initial wavelength model. The model is {0}'.format(self.model)) raise ValueError('0 in self.model.keys(). Not allowed for overlap fit.') coordinates = self._format_overlaps(overlaps, pixel_key='pixel', order_key='ref_id') matched_coordinates = self._format_overlaps(overlaps, pixel_key='matched_pixel', order_key='matched_ref_id') A1, c1 = self._construct_wavelength_map_matrices(**coordinates) A2, c2 = self._construct_wavelength_map_matrices(**matched_coordinates) A, c = A1 - A2, c1 - c2 model_coefficients = np.linalg.lstsq(A, c, rcond=None)[0] self.model_coefficients = model_coefficients.flatten() def apply_scale(self, scale): self.model_coefficients *= scale def _format_overlaps(self, overlaps, pixel_key='pixel', order_key='ref_id'): """ :param overlaps: An astropy table of overlaps with the 'pixel' and 'matched_pixel' columns giving 1d arrays of pixel points which must map to the same wavelength. :return: coordinates of overlaps. """ orders = (overlaps[order_key].data.reshape(-1, 1) * np.ones_like(overlaps[pixel_key].data)).flatten() pixels = overlaps[pixel_key].data.flatten() pixels, orders = pixels[np.isfinite(pixels)], orders[np.isfinite(pixels)] coordinates = {'normed_pixel': normalize_coordinates(pixels, self.max_pixel, self.min_pixel), 'pixel': pixels, 'normed_order': normalize_coordinates(orders, self.max_order, self.min_order), 'order': orders} return coordinates def _construct_wavelength_map_matrices(self, normed_pixel, normed_order, order, **kwargs): if self.grating_eq: m_divisor = 1 / np.add(order, self.m0).astype(np.float64) else: m_divisor = np.ones_like(normed_pixel, dtype=np.float64) columns = () for xpower in self.model: for orderpower in self.model[xpower]: coefficient_array = np.zeros((xpower+1, orderpower+1)) coefficient_array[xpower, orderpower] = 1 columns += (m_divisor * legendre.legval2d(normed_pixel, normed_order, coefficient_array),) A = np.column_stack(columns) if (0 not in self.model) or (0 not in self.model[0]): # we force 0,0 coefficient to 1 for the overlap fit. c = -1 * m_divisor.reshape(-1, 1) else: c = np.zeros_like(normed_pixel, dtype=np.float64).reshape(-1, 1) return A, c @staticmethod def _map_to_wavelength(A, c, coefficients): if coefficients is None: return np.ones_like(c.flatten(), dtype=float) * np.nan return np.dot(A, coefficients).flatten() + (-1) * c.flatten() class WavelengthStage(Stage): """ Base class for all wavelength stages """ def __init__(self, runtime_context=None): super(WavelengthStage, self).__init__(runtime_context=runtime_context) def do_stage(self, image): valid_fibers = self._valid_fibers(image) for fiber in valid_fibers: image = self.do_stage_fiber(image, fiber) if len(valid_fibers) < 1: self.on_no_valid_fibers(image) return image def do_stage_fiber(self, image, fiber): return image def on_no_valid_fibers(self, image): self.logger.warning('No fibers found with non None WavelengthSolution objects. Aborting this ' 'stage.') @staticmethod def _valid_fibers(image): return [fiber for fiber in lit_wavecal_fibers(image) if image.wavelength_solution[fiber] is not None] class Initialize(WavelengthStage): """ Stage 1/9 for the wavelength solution """ def __init__(self, runtime_context=None): super(Initialize, self).__init__(runtime_context=runtime_context) def do_stage_fiber(self, image, fiber): self.logger.info('Appending blank WavelengthSolution object to image for this fiber. ' 'fiber={0}'.format(str(fiber))) spectrum = image.data_tables[self.runtime_context.main_spectrum_name] single_fiber_spectrum = spectrum[spectrum['fiber'] == fiber] image.wavelength_solution[fiber] = WavelengthSolution(model=self.runtime_context.initial_wavelength_model, m0=self.runtime_context.principle_order_number, max_order=np.max(single_fiber_spectrum['ref_id']), min_order=np.min(single_fiber_spectrum['ref_id']), max_pixel=np.max(single_fiber_spectrum['pixel']), min_pixel=np.min(single_fiber_spectrum['pixel'])) return image def on_no_valid_fibers(self, image): for fiber in lit_wavecal_fibers(image): image.wavelength_solution[fiber] = None self.logger.error('Aborting wavelength calibration and setting wavelength solution to None.') def _valid_fibers(self, image): if image.data_tables.get(self.runtime_context.main_spectrum_name) is None: self.logger.error('No main spectrum on image.') return [] colnames_present = all([key in image.data_tables[self.runtime_context.main_spectrum_name].colnames for key in ['ref_id', 'fiber']]) if not colnames_present: self.logger.error('Main spectrum on image is missing ref_id and fiber columns') return [] return lit_wavecal_fibers(image) class LoadReferenceLineList(ApplyCalibration): """ Stage 2/8 for the wavelength solution """ def __init__(self, runtime_context=None): super(LoadReferenceLineList, self).__init__(runtime_context=runtime_context) def apply_master_calibration(self, image, reference_list_path): line_list = np.sort(np.genfromtxt(reference_list_path, usecols=[1]).flatten()) for fiber in [fiber for fiber in lit_wavecal_fibers(image) if image.wavelength_solution[fiber] is not None]: image.wavelength_solution[fiber].reference_lines = line_list image.set_header_val('IDLIST', (reference_list_path, 'ID of the reference line list')) return image def get_calibration_filename(self, image): return self.runtime_context.line_list_path class FitOverlaps(WavelengthStage): """ Stage 3/8 for the wavelength solution This should run on a blaze corrected calibration spectrum. """ def __init__(self, runtime_context=None): super(FitOverlaps, self).__init__(runtime_context=runtime_context) def do_stage(self, image): if image.data_tables.get(self.runtime_context.overlap_table_name, None) is None: image.data_tables[self.runtime_context.overlap_table_name] = blank_overlap_table(self.runtime_context.max_red_overlap) image = super(FitOverlaps, self).do_stage(image) name = self.runtime_context.overlap_table_name image.data_tables[name] = Table(image.data_tables[name]) return image def do_stage_fiber(self, image, fiber): self.logger.info('Fitting overlaps. fiber={0}'.format(str(fiber))) spectrum = image.data_tables[self.runtime_context.main_spectrum_name] single_fiber_spectrum = spectrum[spectrum['fiber'] == fiber] overlaps = fit_overlaps(spec=single_fiber_spectrum, lines=image.wavelength_solution[fiber].measured_lines, max_overlap_red=self.runtime_context.max_red_overlap, max_overlap_blue=self.runtime_context.max_blue_overlap, linear_scale_range=self.runtime_context.overlap_linear_scale_range, fiber=fiber, flux_tol=getattr(self.runtime_context, 'flux_tol', 0.2)) overlaps = flag_bad_overlaps(overlaps, getattr(self.runtime_context, 'min_num_matches', 6)) self.logger.info('{0} overlaps verified. fiber={1}'.format(np.count_nonzero(overlaps['good']), str(fiber))) overlaps = flag_outlier_overlaps(overlaps) self.logger.info('{0} overlaps will be used. fiber={1}'.format(np.count_nonzero(overlaps['good']), str(fiber))) image.data_tables[self.runtime_context.overlap_table_name] = vstack([overlaps, image.data_tables[self.runtime_context.overlap_table_name]]) if np.count_nonzero(overlaps['good']) < self.runtime_context.min_num_overlaps: self.logger.error('Less than {0} overlaps verified as good,' 'setting wavelength solution to None.' ' fiber={1}'.format(self.runtime_context.min_num_overlaps, str(fiber))) image.wavelength_solution[fiber] = None return image class SolveFromOverlaps(WavelengthStage): """ Stage 4/8. Solves for the coefficients of the wavelength solution from the overlaps. """ def __init__(self, runtime_context=None): super(SolveFromOverlaps, self).__init__(runtime_context=runtime_context) def do_stage_fiber(self, image, fiber): image.wavelength_solution[fiber].model = Model(self.runtime_context.initial_wavelength_model) overlaps = image.data_tables.get(self.runtime_context.overlap_table_name, blank_overlap_table(1)) overlaps = self._prune_overlaps(overlaps, fiber) self.logger.info('Initializing wavelength solution from overlaps. fiber={0}'.format(str(fiber))) image.wavelength_solution[fiber].overlap_range = minmax([overlaps['ref_id'], overlaps['matched_ref_id']]) image.wavelength_solution[fiber].solve_from_overlaps(overlaps) return image @staticmethod def _prune_overlaps(overlaps, fiber): overlaps = overlaps[overlaps['good']] overlaps = overlaps[overlaps['fiber'] == fiber] return overlaps class IdentifyArcEmissionLines(WavelengthStage): """ Stage 5/8 for the wavelength solution """ def __init__(self, runtime_context=None): super(IdentifyArcEmissionLines, self).__init__(runtime_context=runtime_context) self.min_peak_snr = self.runtime_context.min_peak_snr def do_stage_fiber(self, image, fiber): spectrum = image.data_tables[self.runtime_context.main_spectrum_name] single_fiber_spectrum = spectrum[spectrum['fiber'] == fiber] measured_lines = identify_lines(spectrum=single_fiber_spectrum, stderr=single_fiber_spectrum['stderr'], min_snr=self.min_peak_snr, order_key='ref_id') image.wavelength_solution[fiber].measured_lines = measured_lines self.logger.info('{0} emission lines identified from {1} unique ' 'diffraction orders. fiber={2}' ''.format(len(measured_lines['pixel']), len(set(measured_lines['order'])), str(fiber))) return image class BlazeCorrectArcEmissionLines(WavelengthStage): def __init__(self, runtime_context=None): super(BlazeCorrectArcEmissionLines, self).__init__(runtime_context=runtime_context) def do_stage_fiber(self, image, fiber): spectrum = image.data_tables.get(self.runtime_context.blaze_corrected_spectrum_name) lines = image.wavelength_solution[fiber].measured_lines if spectrum is None: image.wavelength_solution[fiber].measured_lines['corrected_flux'] = lines['flux'] else: spectrum = spectrum[spectrum['fiber'] == fiber] lines['corrected_flux'] = np.zeros_like(lines['flux'], dtype=float) for spec in spectrum: flux = interpolate.interp1d(spec['pixel'], spec['flux'], kind='nearest', bounds_error=False, fill_value=0) in_order = np.where(lines['order'] == spec['ref_id']) lines['corrected_flux'][in_order] = flux(lines['pixel'][in_order]) image.wavelength_solution[fiber].measured_lines = lines return image class IdentifyArcEmissionLinesLowSN(IdentifyArcEmissionLines): def __init__(self, runtime_context=None): super(IdentifyArcEmissionLinesLowSN, self).__init__(runtime_context=runtime_context) self.min_peak_snr = self.runtime_context.overlap_min_peak_snr class FindGlobalScale(WavelengthStage): """ Stage 6/8 for the wavelength solution """ def __init__(self, runtime_context=None): super(FindGlobalScale, self).__init__(runtime_context=runtime_context) self.step = getattr(self.runtime_context, 'global_scale_spacing', 10) def do_stage_fiber(self, image, fiber): scale_guess = estimate_global_scale(detector_range=self.runtime_context.approx_detector_range_angstroms, n=self.runtime_context.approx_num_orders, m0=image.wavelength_solution[fiber].m0) scale = self._find_scale(image.wavelength_solution[fiber], scale_guess, self.runtime_context.global_scale_range, step=self.step) image.wavelength_solution[fiber].update_model(self.runtime_context.intermediate_wavelength_model) image.wavelength_solution[fiber].apply_scale(scale) self.logger.info('The scale guess was {0:.6e} and the search yielded {1:.6e}. fiber={2}' ''.format(scale_guess, scale, str(fiber))) if not np.isclose(scale, scale_guess, rtol=2): self.logger.error('Global scale is more than a factor of two away from initial guess, ' 'an error in the wavelength solution for this fiber is likely. fiber={0}'.format(str(fiber))) return image @staticmethod def _find_scale(wcs, scale_guess, rrange=(0.1, 5), step=10): unscaled_wavelengths = wcs.wavelength_normed_input(**restrict(wcs.measured_lines, *wcs.overlap_range)) args = (unscaled_wavelengths, np.sort(wcs.reference_lines)) scale = optimize.minimize(fun=FindGlobalScale._chi_squared_safe, x0=scale_guess, args=args, method=brute_local_min, options={'step': step, 'rrange': rrange, 'filtw': 501, 'finish': 'Nelder-Mead'}).x[0] return scale @staticmethod def _chi_squared_safe(scales, unscaled_wavelengths, reference_wavelengths, mem_limit=1E8): chi2 = np.zeros_like(scales, dtype=np.float32) step = max(int(len(scales) * len(unscaled_wavelengths)) // int(mem_limit * 8 / 32), 1) # bits / bit_limit for i in range(step): chi2[i::step] = FindGlobalScale._chi_squared(scales[i::step], unscaled_wavelengths, reference_wavelengths) return chi2 @staticmethod def _chi_squared(scales, unscaled_wavelengths, reference_wavelengths): wavelengths = np.array(scales).reshape(-1, 1) * unscaled_wavelengths residuals = calc_residuals(wavelengths.flatten(), reference_wavelengths).reshape(wavelengths.shape) return np.sum(residuals ** 2, axis=1).flatten() #return np.sum(np.sort(residuals**2, axis=1)[:, :nmax], axis=1).flatten() class SolutionRefineInitial(WavelengthStage): """ Stage 7/8 for the wavelength solution """ def __init__(self, runtime_context=None): super(SolutionRefineInitial, self).__init__(runtime_context=runtime_context) self.kappa = getattr(runtime_context, 'initial_mad_clip', 6) def do_stage_fiber(self, image, fiber): image.wavelength_solution[fiber].update_model(new_model=self.runtime_context.intermediate_wavelength_model) image.wavelength_solution[fiber], rsd = self.constrain_solution_over_detector(image.wavelength_solution[fiber], self.kappa) mad, std = median_absolute_deviation(rsd), np.std(rsd) self.logger.info('median absolute deviation is {0} and the standard deviation is {1}.' ' fiber={2}'.format(mad, std, str(fiber))) self.logger.info('{0} lines within 4.5 median absolute deviations and {1} lines within 4.5 standard deviations' ''.format(np.count_nonzero(np.isclose(rsd, 0, atol=4.5*mad)), np.count_nonzero(np.isclose(rsd, 0, atol=4.5*std)))) return image @staticmethod def constrain_solution_over_detector(wcs, kappa=6): """ :param wcs: WavelengthSolution :param kappa: outliers with residuals exceeding kappa m.a.d. from 0 will not be used to constrain the solution. :return: (WavelengthSolution, array) wavelength solution, residuals. Each entry of residuals is the difference in wavelength between a measured line and its corresponding closest reference line. """ reference_lines = np.sort(wcs.reference_lines) residuals = [] for order_range in SolutionRefineInitial._ranges_to_evaluate(*wcs.overlap_range, wcs.min_order, wcs.max_order): wcs, residuals = refine_wcs(wcs, wcs.measured_lines, reference_lines, SolutionRefineInitial._converged_when_max_iter, SolutionRefineInitial._clip, kwargs={'sigma': kappa, 'stdfunc': median_absolute_deviation, 'order_range': order_range}, max_iter=5) return wcs, residuals @staticmethod def _converged_when_max_iter(*args, **kwargs): return False @staticmethod def _clip(wcs, lines, reference_lines, sigma=3, stdfunc=np.std, order_range=(), **kwargs): lines = restrict(lines, *order_range) residuals = calc_residuals(wcs.wavelength_normed_input(**lines), reference_lines) lines = _sigma_clip(residuals, lines, sigma=sigma, stdfunc=stdfunc) return lines @staticmethod def _ranges_to_evaluate(low, high, min_order, max_order): return [(low - i, high + i) for i in range(max(low - min_order, max_order - high) + 1)] def refine_wcs(wcs, measured_lines, reference_lines, converged, clip_fun, kwargs=None, max_iter=20): """ :param wcs: WavelengthSolution :param reference_lines: array. Wavelengths of reference calibration lines. :param measured_lines: dict: {'normed_pixel': array, 'normed_order': array}. Coordinates of measured lines. :param kwargs: keyword arguments to feed to clip_fun and converged. :param max_iter: the max number of iterations allowed to reach convergence. :param converged: function which accepts wcs, residuals, last_residuals, measured_lines and **kwargs and returns True or False. If True, the solve loop will stop. :param clip_fun: function which accepts residuals, measured_lines, reference_lines and **kwargs and returns a dict in the same format as measured_lines. :return: (WavelengthSolution, array) wavelength solution, residuals. Each entry of residuals is the difference in wavelength between a measured line and its corresponding closest reference line. """ if kwargs is None: kwargs = {} residuals, last_residuals = [], np.inf # note we could evaluate the find_nearest function out here instead of in the loop. for iteration in range(max_iter): clipped_lines = clip_fun(wcs, measured_lines, reference_lines, **kwargs) closest_ref_lines = find_nearest(wcs.wavelength_normed_input(**clipped_lines), array_b=reference_lines) wcs.model_coefficients = wcs.solve(clipped_lines, closest_ref_lines, clipped_lines.get('weight', None)) residuals = calc_residuals(wcs.wavelength_normed_input(**measured_lines), reference_lines) if converged(residuals, last_residuals, **kwargs): break last_residuals = np.copy(residuals) return wcs, residuals class SolutionRefineFinal(WavelengthStage): """ Stage 8/8 for the wavelength solution """ def __init__(self, runtime_context=None): super(SolutionRefineFinal, self).__init__(runtime_context=runtime_context) self.kappa = getattr(runtime_context, 'final_mad_clip', 4) def do_stage_fiber(self, image, fiber): image.wavelength_solution[fiber], rsd = self._refine(image.wavelength_solution[fiber], self.runtime_context.final_wavelength_model, self.kappa) mad, std = median_absolute_deviation(rsd), np.std(rsd) self.logger.info('median absolute deviation is {0} and the standard deviation is {1}.' ' fiber={2}'.format(mad, std, str(fiber))) self.logger.info('{0} lines within 4.5 median absolute deviations and {1} lines within 4.5 standard deviations' ''.format(np.count_nonzero(np.isclose(rsd, 0, atol=4.5*mad)), np.count_nonzero(np.isclose(rsd, 0, atol=4.5*std)))) return image @staticmethod def _refine(wavelength_solution, final_model, kappa=4): """ :param wavelength_solution: WavelengthSolution :param final_model: dict. The model which describes the form of the mapping from pixel and order to wavelength. See __init__ of WavelengthSolution. :param kappa: outliers with residuals exceeding kappa m.a.d. from 0 will not be used to constrain the solution. :return: (WavelengthSolution, array) wavelength solution, residuals. Each entry of residuals is the difference in wavelength between a measured line and its corresponding closest reference line. """ reference_lines = np.sort(wavelength_solution.reference_lines) measured_lines = wavelength_solution.measured_lines residuals = [] for x_degree in final_model: for i_degree in final_model[x_degree]: if wavelength_solution.model.is_missing_polynomial_term(x_degree, i_degree): # This will only refine if the model is missing the term, # which means this stage does nothing if you want to rerun a model. new_model = copy.deepcopy(wavelength_solution.model) new_model.add_polynomial_term(x_degree, i_degree) wavelength_solution.update_model(new_model=new_model) wavelength_solution, residuals = refine_wcs(wavelength_solution, measured_lines, reference_lines, SolutionRefineFinal._converged, SolutionRefineFinal._clip, max_iter=20, kwargs={'sigma': kappa, 'stdfunc': median_absolute_deviation}) return wavelength_solution, residuals @staticmethod def _converged(residuals, last_residuals, **kwargs): if np.allclose(residuals, last_residuals, atol=1E-3): return True return False @staticmethod def _clip(wcs, lines, reference_lines, sigma=3, stdfunc=np.std, **kwargs): residuals = calc_residuals(wcs.wavelength_normed_input(**lines), reference_lines) lines = _sigma_clip(residuals, lines, sigma=sigma, stdfunc=stdfunc) return lines class SolutionRefineOnce(SolutionRefineFinal): """ Single iteration of refining the wavelength solution. Useful if more lines have been added to the line list after final refine. """ def __init__(self, runtime_context=None): super(SolutionRefineOnce, self).__init__(runtime_context=runtime_context) def do_stage_fiber(self, image, fiber): image.wavelength_solution[fiber], rsd = refine_wcs(image.wavelength_solution[fiber], image.wavelength_solution[fiber].measured_lines, image.wavelength_solution[fiber].reference_lines, self._converged, self._clip, max_iter=20, kwargs={'sigma': 4, 'stdfunc': median_absolute_deviation}) mad, std = median_absolute_deviation(rsd), np.std(rsd) self.logger.info('median absolute deviation is {0} and the standard deviation is {1}.' ' fiber={2}'.format(mad, std, str(fiber))) self.logger.info('{0} lines within 4.5 median absolute deviations and {1} lines within 4.5 standard deviations' ''.format(np.count_nonzero(np.isclose(rsd, 0, atol=4.5*mad)), np.count_nonzero(np.isclose(rsd, 0, atol=4.5*std)))) return image class ApplyToSpectrum(WavelengthStage): """ Stage 8/9 for the wavelength solution """ def __init__(self, runtime_context=None): super(ApplyToSpectrum, self).__init__(runtime_context=runtime_context) def do_stage_fiber(self, image, fiber): spectrum = image.data_tables[self.runtime_context.main_spectrum_name] fiber_mask = np.where(spectrum['fiber'] == fiber) wcs = image.wavelength_solution[fiber] pixel_coordinates, order_coordinates = pixel_order_as_array(spectrum[fiber_mask]) spectrum['wavelength'][fiber_mask] = wcs(pixel=pixel_coordinates, order=order_coordinates) spectrum.meta['header'] = {'MODEL': str(wcs.model), 'MCOEFFS': str(list(wcs.model_coefficients))} image.data_tables[self.runtime_context.main_spectrum_name] = spectrum return image class TabulateArcEmissionLines(WavelengthStage): """ Optional stage which will create a table of all identified emission lines and their matches in the reference list. This is saved when the image reduction is completed, under the extension LINES. """ def __init__(self, runtime_context=None): super(TabulateArcEmissionLines, self).__init__(runtime_context=runtime_context) def do_stage(self, image): # TODO if wavelength solution fails, then the emission lines are not saved. Make it so that they are # always saved valid_fibers = self._valid_fibers(image) if len(valid_fibers) > 0: lines = self._format_lines(image, valid_fibers) for fiber in valid_fibers: wcs = image.wavelength_solution[fiber] fib = np.where(lines['fiber'] == fiber) lines['wavelength'][fib] = wcs(lines['pixel'][fib].data, lines['order'][fib].data) lines['reference_wavelength'][fib] = find_nearest(lines['wavelength'][fib], wcs.reference_lines) image.data_tables[self.runtime_context.emission_lines_table_name] = Table(lines) return image @staticmethod def _format_lines(image, fibers): all_lines = [] for fiber in fibers: lines = Table(image.wavelength_solution[fiber].measured_lines) lines.add_column(Column(fiber * np.ones_like(lines['pixel']), dtype=int), name='fiber') lines.add_column(Column(np.zeros_like(lines['pixel'], dtype=np.float64), unit='angstrom'), name='wavelength') lines.add_column(Column(np.zeros_like(lines['pixel'], dtype=np.float64), unit='angstrom'), name='reference_wavelength') lines['reference_wavelength'].description = 'wavelength of the nearest match in the reference line list' lines['wavelength'].description = 'wavelength of measured line from the calibration frame' all_lines.append(lines) return vstack(all_lines) class IdentifyPrincipleOrderNumber(WavelengthStage): """ Stage for identifying the principle order number m0. This should be run between IdentifyArcEmissionLines and SolveFromOverlaps. This stage is meant to be run once on a batch of stages to find the principle order number. The principle order number should then be fixed in the config.ini file for your instrument. """ def __init__(self, runtime_context=None): super(IdentifyPrincipleOrderNumber, self).__init__(runtime_context=runtime_context) self.STAGES_TODO = [SolveFromOverlaps, FindGlobalScale, SolutionRefineInitial, SolutionRefineFinal] def do_stage_fiber(self, image, fiber): self.logger.info('Looking for the principle order number between {0} and {1}.' ' fiber={2}'.format(*self.runtime_context.m0_range, str(fiber))) self.logger.disabled = True merits, m0_values = self.merit_per_m0(image, fiber, self.runtime_context.m0_range) self.logger.disabled = False best_m0, merit = m0_values[np.argmin(merits)], np.min(merits) if not merit < 1/10 * np.median(merits): self.logger.warning('A definitive principle order number was not found. Aborting wavelength solution.' ' fiber={0}'.format(str(fiber))) image.wavelength_solution[fiber] = None else: image.wavelength_solution[fiber].m0 = best_m0 self.logger.info('The best principle order number is {0}. fiber={1}'.format(best_m0, str(fiber))) return image def merit_per_m0(self, image, fiber, m0_range): m0_values = np.arange(*m0_range) merit = [] for m0 in m0_values: image.wavelength_solution[fiber].m0 = m0 for STAGE in self.STAGES_TODO: image = STAGE(self.runtime_context).do_stage_fiber(image, fiber) wcs = image.wavelength_solution[fiber] if wcs is not None: merit.append(median_absolute_deviation(calc_residuals(wcs.wavelength_normed_input(**wcs.measured_lines), wcs.reference_lines))) return np.array(merit), m0_values def find_feature_wavelengths(measured_lines, reference_lines, m0_range: tuple, max_pixel, min_pixel=0, wavelength_models: dict = None, overlap_settings: dict = None, scale_settings: dict = None, stages_todo: list = None): """ A convenience function for any users who want to be able to wavelength calibrate from a list of spectral feature (measured_lines) pixel and order positions and a reference line list (reference_lines). This is not used anywhere in xwavecal, nor the included pipeline, except in xwavecal.tests.test_wavelength. The measured_lines should be for one fiber only. This function should be looped over fibers to calibrate many fibers. This function was designed to be used in Banzai-NRES. It returns the wavelengths of the spectral features input in measured_lines. :param measured_lines: dict. dictionary of ndarrays of pixel and order positions of measured spectral features (e.g. emission lines). Example: measured_lines = {'pixel': np.array([1, 2.5, 6.1]), 'order': np.array([1, 1, 2])} If the principle order number is 52, then these measured_lines represents 3 spectral features, with (pixel, diffraction order) coordinates of (1, 53), (2.5, 53), (6.1, 54). respectively. The wavelength solution will calibrate each fiber separately. :param reference_lines: list or ndarray. List of reference wavelengths in Angstroms for what features you expect are in measured_lines. Example: reference_lines = [5000, 5001, 5002, 5003.1, 6001.2] :param m0_range: tuple. The range of integers possible for the principle order number: (low, high). low is an inclusive bound and high is exclusive. The principle order number gives the real diffraction order index of the i=0 labelled diffraction order. See the xwavecal README or Brandt et al. (2019) for more. :param max_pixel: int. Maximum pixel coordinate on the detector. Used for finding the overlaps. E.g. 4096 :param min_pixel: int. Minimum pixel coordinate on the detector. Used for finding the overlaps. E.g. 0 :param wavelength_models: dict. Dictionary of models. See the xwavecal README, or wavelength_models below. :param overlap_settings: dict. Dictionary of settings for the overlap fitting algorithms. See the xwavecal README, or overlap_settings below. :param scale_settings: dict. Dictionary of settings for the global scale fitting algorithms. See the xwavecal README, or scale_settings below. :param stages_todo: list. list of xwavecal.wavelength.WavelengthSolution stages to run on the input list of measured lines. If building a new wavelength solution from scratch, then leave the default stages_todo. :return: measured_line_wavelengths: ndarray. if return_all==False. measured_line_wavelengths are the wavelengths of the measured_lines under the calibrated model. measured_line_wavelengths is an array with the same length as measured_lines['pixel'] and measured_lines['order']. Notes ----- See xwavecal.tests.test_wavelength.TestOnSyntheticData.test_performance for a use example of this function. the test can be run from an ipython instance and can provide insight as to how to use this wrapper function. """ if stages_todo is None: stages_todo = [FitOverlaps, IdentifyPrincipleOrderNumber, SolveFromOverlaps, FindGlobalScale, SolutionRefineInitial, SolutionRefineFinal] if wavelength_models is None: wavelength_models = {'initial_wavelength_model': {1: [0, 1, 2], 2: [0, 1, 2]}, 'intermediate_wavelength_model': {0: [0, 1, 2], 1: [0, 1, 2], 2: [0, 1, 2]}, 'final_wavelength_model': {0: [0, 1, 2, 3, 4, 5], 1: [0, 1, 2, 3, 4, 5], 2: [0, 1, 2, 3, 4, 5], 3: [0, 1, 2, 3, 4, 5], 4: [0]}} if overlap_settings is None: # settings relevant to fitting the overlaps. overlap_settings = {'min_num_overlaps': 5, 'overlap_linear_scale_range': (0.5, 2), 'flux_tol': 0.2, 'max_red_overlap': 1000, 'max_blue_overlap': 2000} if scale_settings is None: # settings relevant to finding the global scale. scale_settings = {'global_scale_range': (0.8, 1.2), 'approx_detector_range_angstroms': 5000, 'approx_num_orders': 67} # instantiate the context which every WavelengthStage will use. context = type('context', (), {**wavelength_models, **overlap_settings, **scale_settings, 'm0_range': m0_range, 'main_spectrum_name': 'spectrum', 'overlap_table_name': 'overlap'}) # make dummy spectrum so that FitOverlaps will run. # TODO: the spectrum is only used in fit_overlaps to get the reference id's etc. It in principle is not # needed at all. Fix this deeper in the code so that we don't have to make a fake spectrum here. pixel = np.arange(min_pixel, max_pixel + 1) orders = np.arange(np.min(measured_lines['order']), np.max(measured_lines['order'])).astype(int) spectrum_shape = (len(orders), len(pixel)) spectrum = Table({'ref_id': orders, 'fiber': np.ones_like(orders), 'flux': np.zeros(spectrum_shape), 'pixel': pixel * np.ones(spectrum_shape)}) # Initialize the WavelengthSolution wavelength_solution = WavelengthSolution(model=wavelength_models.get('initial_wavelength_model'), min_order=np.min(orders), max_order=np.max(orders), min_pixel=np.min(pixel), max_pixel=np.max(pixel), measured_lines=measured_lines, reference_lines=np.sort(reference_lines)) # make a container (e.g. the Image object) for the spectrum and wavelength solution image = Image(header={'fiber_state': 'none&thar&none'}, wavelength_solution={1: wavelength_solution}, data_tables={context.main_spectrum_name: spectrum}) # run the wavelength calibration stages for stage in stages_todo: image = stage(context).do_stage(image) measured_lines['wavelength'] = np.zeros_like(measured_lines['pixel'], dtype=float) wavelengths = None if image.wavelength_solution[1] is not None: wavelengths = image.wavelength_solution[1](measured_lines['pixel'], measured_lines['order']) measured_lines['wavelength'] = wavelengths return measured_lines['wavelength']
[ "xwavecal.utils.wavelength_utils.pixel_order_as_array", "numpy.sum", "numpy.allclose", "xwavecal.utils.misc_utils.minmax", "xwavecal.utils.wavelength_utils._sigma_clip", "numpy.argmin", "numpy.ones", "numpy.isclose", "numpy.arange", "scipy.interpolate.interp1d", "xwavecal.utils.wavelength_utils.restrict", "scipy.optimize.minimize", "numpy.zeros_like", "numpy.copy", "numpy.std", "numpy.isfinite", "numpy.genfromtxt", "numpy.max", "numpy.linspace", "numpy.add", "xwavecal.utils.overlap_utils.flag_outlier_overlaps", "xwavecal.utils.overlap_utils.blank_overlap_table", "xwavecal.images.Image", "copy.deepcopy", "numpy.ones_like", "xwavecal.utils.misc_utils.find_nearest", "numpy.median", "xwavecal.utils.fiber_utils.lit_wavecal_fibers", "numpy.polynomial.legendre.legval2d", "numpy.sort", "numpy.min", "astropy.stats.median_absolute_deviation", "numpy.dot", "xwavecal.utils.wavelength_utils.estimate_global_scale", "xwavecal.utils.wavelength_utils.identify_lines", "astropy.table.Table", "numpy.linalg.lstsq", "numpy.count_nonzero", "numpy.zeros", "xwavecal.utils.wavelength_utils.normalize_coordinates", "astropy.table.vstack", "numpy.where", "xwavecal.utils.wavelength_utils.Model", "numpy.array", "numpy.column_stack", "logging.getLogger" ]
[((806, 833), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (823, 833), False, 'import logging\n'), ((41291, 41326), 'numpy.arange', 'np.arange', (['min_pixel', '(max_pixel + 1)'], {}), '(min_pixel, max_pixel + 1)\n', (41300, 41326), True, 'import numpy as np\n'), ((42242, 42393), 'xwavecal.images.Image', 'Image', ([], {'header': "{'fiber_state': 'none&thar&none'}", 'wavelength_solution': '{(1): wavelength_solution}', 'data_tables': '{context.main_spectrum_name: spectrum}'}), "(header={'fiber_state': 'none&thar&none'}, wavelength_solution={(1):\n wavelength_solution}, data_tables={context.main_spectrum_name: spectrum})\n", (42247, 42393), False, 'from xwavecal.images import Image\n'), ((42580, 42631), 'numpy.zeros_like', 'np.zeros_like', (["measured_lines['pixel']"], {'dtype': 'float'}), "(measured_lines['pixel'], dtype=float)\n", (42593, 42631), True, 'import numpy as np\n'), ((1698, 1710), 'xwavecal.utils.wavelength_utils.Model', 'Model', (['model'], {}), '(model)\n', (1703, 1710), False, 'from xwavecal.utils.wavelength_utils import identify_lines, calc_residuals, restrict, Model, _sigma_clip\n'), ((2932, 3017), 'xwavecal.utils.wavelength_utils.normalize_coordinates', 'normalize_coordinates', (['pixel'], {'max_value': 'self.max_pixel', 'min_value': 'self.min_pixel'}), '(pixel, max_value=self.max_pixel, min_value=self.min_pixel\n )\n', (2953, 3017), False, 'from xwavecal.utils.wavelength_utils import estimate_global_scale, normalize_coordinates, pixel_order_as_array\n'), ((3036, 3121), 'xwavecal.utils.wavelength_utils.normalize_coordinates', 'normalize_coordinates', (['order'], {'max_value': 'self.max_order', 'min_value': 'self.min_order'}), '(order, max_value=self.max_order, min_value=self.min_order\n )\n', (3057, 3121), False, 'from xwavecal.utils.wavelength_utils import estimate_global_scale, normalize_coordinates, pixel_order_as_array\n'), ((3859, 3929), 'xwavecal.utils.wavelength_utils.normalize_coordinates', 'normalize_coordinates', (["coords['pixel']", 'self.max_pixel', 'self.min_pixel'], {}), "(coords['pixel'], self.max_pixel, self.min_pixel)\n", (3880, 3929), False, 'from xwavecal.utils.wavelength_utils import estimate_global_scale, normalize_coordinates, pixel_order_as_array\n'), ((3963, 4033), 'xwavecal.utils.wavelength_utils.normalize_coordinates', 'normalize_coordinates', (["coords['order']", 'self.max_order', 'self.min_order'], {}), "(coords['order'], self.max_order, self.min_order)\n", (3984, 4033), False, 'from xwavecal.utils.wavelength_utils import estimate_global_scale, normalize_coordinates, pixel_order_as_array\n'), ((4120, 4136), 'xwavecal.utils.wavelength_utils.Model', 'Model', (['new_model'], {}), '(new_model)\n', (4125, 4136), False, 'from xwavecal.utils.wavelength_utils import identify_lines, calc_residuals, restrict, Model, _sigma_clip\n'), ((7427, 7451), 'numpy.column_stack', 'np.column_stack', (['columns'], {}), '(columns)\n', (7442, 7451), True, 'import numpy as np\n'), ((10197, 10222), 'xwavecal.utils.fiber_utils.lit_wavecal_fibers', 'lit_wavecal_fibers', (['image'], {}), '(image)\n', (10215, 10222), False, 'from xwavecal.utils.fiber_utils import lit_wavecal_fibers\n'), ((10915, 10940), 'xwavecal.utils.fiber_utils.lit_wavecal_fibers', 'lit_wavecal_fibers', (['image'], {}), '(image)\n', (10933, 10940), False, 'from xwavecal.utils.fiber_utils import lit_wavecal_fibers\n'), ((12442, 12472), 'astropy.table.Table', 'Table', (['image.data_tables[name]'], {}), '(image.data_tables[name])\n', (12447, 12472), False, 'from astropy.table import Column, Table, vstack\n'), ((13551, 13582), 'xwavecal.utils.overlap_utils.flag_outlier_overlaps', 'flag_outlier_overlaps', (['overlaps'], {}), '(overlaps)\n', (13572, 13582), False, 'from xwavecal.utils.overlap_utils import flag_bad_overlaps, fit_overlaps, blank_overlap_table, flag_outlier_overlaps\n'), ((13773, 13851), 'astropy.table.vstack', 'vstack', (['[overlaps, image.data_tables[self.runtime_context.overlap_table_name]]'], {}), '([overlaps, image.data_tables[self.runtime_context.overlap_table_name]])\n', (13779, 13851), False, 'from astropy.table import Column, Table, vstack\n'), ((14677, 14729), 'xwavecal.utils.wavelength_utils.Model', 'Model', (['self.runtime_context.initial_wavelength_model'], {}), '(self.runtime_context.initial_wavelength_model)\n', (14682, 14729), False, 'from xwavecal.utils.wavelength_utils import identify_lines, calc_residuals, restrict, Model, _sigma_clip\n'), ((15055, 15111), 'xwavecal.utils.misc_utils.minmax', 'minmax', (["[overlaps['ref_id'], overlaps['matched_ref_id']]"], {}), "([overlaps['ref_id'], overlaps['matched_ref_id']])\n", (15061, 15111), False, 'from xwavecal.utils.misc_utils import brute_local_min, find_nearest, minmax\n'), ((15913, 16051), 'xwavecal.utils.wavelength_utils.identify_lines', 'identify_lines', ([], {'spectrum': 'single_fiber_spectrum', 'stderr': "single_fiber_spectrum['stderr']", 'min_snr': 'self.min_peak_snr', 'order_key': '"""ref_id"""'}), "(spectrum=single_fiber_spectrum, stderr=single_fiber_spectrum\n ['stderr'], min_snr=self.min_peak_snr, order_key='ref_id')\n", (15927, 16051), False, 'from xwavecal.utils.wavelength_utils import identify_lines, calc_residuals, restrict, Model, _sigma_clip\n'), ((18210, 18392), 'xwavecal.utils.wavelength_utils.estimate_global_scale', 'estimate_global_scale', ([], {'detector_range': 'self.runtime_context.approx_detector_range_angstroms', 'n': 'self.runtime_context.approx_num_orders', 'm0': 'image.wavelength_solution[fiber].m0'}), '(detector_range=self.runtime_context.\n approx_detector_range_angstroms, n=self.runtime_context.\n approx_num_orders, m0=image.wavelength_solution[fiber].m0)\n', (18231, 18392), False, 'from xwavecal.utils.wavelength_utils import estimate_global_scale, normalize_coordinates, pixel_order_as_array\n'), ((19986, 20025), 'numpy.zeros_like', 'np.zeros_like', (['scales'], {'dtype': 'np.float32'}), '(scales, dtype=np.float32)\n', (19999, 20025), True, 'import numpy as np\n'), ((22447, 22475), 'numpy.sort', 'np.sort', (['wcs.reference_lines'], {}), '(wcs.reference_lines)\n', (22454, 22475), True, 'import numpy as np\n'), ((23388, 23417), 'xwavecal.utils.wavelength_utils.restrict', 'restrict', (['lines', '*order_range'], {}), '(lines, *order_range)\n', (23396, 23417), False, 'from xwavecal.utils.wavelength_utils import identify_lines, calc_residuals, restrict, Model, _sigma_clip\n'), ((23524, 23583), 'xwavecal.utils.wavelength_utils._sigma_clip', '_sigma_clip', (['residuals', 'lines'], {'sigma': 'sigma', 'stdfunc': 'stdfunc'}), '(residuals, lines, sigma=sigma, stdfunc=stdfunc)\n', (23535, 23583), False, 'from xwavecal.utils.wavelength_utils import identify_lines, calc_residuals, restrict, Model, _sigma_clip\n'), ((25558, 25576), 'numpy.copy', 'np.copy', (['residuals'], {}), '(residuals)\n', (25565, 25576), True, 'import numpy as np\n'), ((27400, 27444), 'numpy.sort', 'np.sort', (['wavelength_solution.reference_lines'], {}), '(wavelength_solution.reference_lines)\n', (27407, 27444), True, 'import numpy as np\n'), ((28871, 28921), 'numpy.allclose', 'np.allclose', (['residuals', 'last_residuals'], {'atol': '(0.001)'}), '(residuals, last_residuals, atol=0.001)\n', (28882, 28921), True, 'import numpy as np\n'), ((29171, 29230), 'xwavecal.utils.wavelength_utils._sigma_clip', '_sigma_clip', (['residuals', 'lines'], {'sigma': 'sigma', 'stdfunc': 'stdfunc'}), '(residuals, lines, sigma=sigma, stdfunc=stdfunc)\n', (29182, 29230), False, 'from xwavecal.utils.wavelength_utils import identify_lines, calc_residuals, restrict, Model, _sigma_clip\n'), ((31119, 31155), 'numpy.where', 'np.where', (["(spectrum['fiber'] == fiber)"], {}), "(spectrum['fiber'] == fiber)\n", (31127, 31155), True, 'import numpy as np\n'), ((31250, 31292), 'xwavecal.utils.wavelength_utils.pixel_order_as_array', 'pixel_order_as_array', (['spectrum[fiber_mask]'], {}), '(spectrum[fiber_mask])\n', (31270, 31292), False, 'from xwavecal.utils.wavelength_utils import estimate_global_scale, normalize_coordinates, pixel_order_as_array\n'), ((33595, 33612), 'astropy.table.vstack', 'vstack', (['all_lines'], {}), '(all_lines)\n', (33601, 33612), False, 'from astropy.table import Column, Table, vstack\n'), ((35263, 35283), 'numpy.arange', 'np.arange', (['*m0_range'], {}), '(*m0_range)\n', (35272, 35283), True, 'import numpy as np\n'), ((2324, 2418), 'xwavecal.utils.wavelength_utils.normalize_coordinates', 'normalize_coordinates', (["lines['pixel']"], {'max_value': 'self.max_pixel', 'min_value': 'self.min_pixel'}), "(lines['pixel'], max_value=self.max_pixel, min_value=\n self.min_pixel)\n", (2345, 2418), False, 'from xwavecal.utils.wavelength_utils import estimate_global_scale, normalize_coordinates, pixel_order_as_array\n'), ((2450, 2544), 'xwavecal.utils.wavelength_utils.normalize_coordinates', 'normalize_coordinates', (["lines['order']"], {'max_value': 'self.max_order', 'min_value': 'self.min_order'}), "(lines['order'], max_value=self.max_order, min_value=\n self.min_order)\n", (2471, 2544), False, 'from xwavecal.utils.wavelength_utils import estimate_global_scale, normalize_coordinates, pixel_order_as_array\n'), ((3625, 3672), 'numpy.linspace', 'np.linspace', (['self.min_pixel', 'self.max_pixel', '(30)'], {}), '(self.min_pixel, self.max_pixel, 30)\n', (3636, 3672), True, 'import numpy as np\n'), ((3709, 3754), 'numpy.arange', 'np.arange', (['self.min_order', '(self.max_order + 1)'], {}), '(self.min_order, self.max_order + 1)\n', (3718, 3754), True, 'import numpy as np\n'), ((4530, 4543), 'numpy.array', 'np.array', (['[1]'], {}), '([1])\n', (4538, 4543), True, 'import numpy as np\n'), ((5785, 5818), 'numpy.linalg.lstsq', 'np.linalg.lstsq', (['A', 'c'], {'rcond': 'None'}), '(A, c, rcond=None)\n', (5800, 5818), True, 'import numpy as np\n'), ((6571, 6632), 'xwavecal.utils.wavelength_utils.normalize_coordinates', 'normalize_coordinates', (['pixels', 'self.max_pixel', 'self.min_pixel'], {}), '(pixels, self.max_pixel, self.min_pixel)\n', (6592, 6632), False, 'from xwavecal.utils.wavelength_utils import estimate_global_scale, normalize_coordinates, pixel_order_as_array\n'), ((6690, 6751), 'xwavecal.utils.wavelength_utils.normalize_coordinates', 'normalize_coordinates', (['orders', 'self.max_order', 'self.min_order'], {}), '(orders, self.max_order, self.min_order)\n', (6711, 6751), False, 'from xwavecal.utils.wavelength_utils import estimate_global_scale, normalize_coordinates, pixel_order_as_array\n'), ((7029, 7073), 'numpy.ones_like', 'np.ones_like', (['normed_pixel'], {'dtype': 'np.float64'}), '(normed_pixel, dtype=np.float64)\n', (7041, 7073), True, 'import numpy as np\n'), ((12236, 12293), 'xwavecal.utils.overlap_utils.blank_overlap_table', 'blank_overlap_table', (['self.runtime_context.max_red_overlap'], {}), '(self.runtime_context.max_red_overlap)\n', (12255, 12293), False, 'from xwavecal.utils.overlap_utils import flag_bad_overlaps, fit_overlaps, blank_overlap_table, flag_outlier_overlaps\n'), ((13924, 13958), 'numpy.count_nonzero', 'np.count_nonzero', (["overlaps['good']"], {}), "(overlaps['good'])\n", (13940, 13958), True, 'import numpy as np\n'), ((14812, 14834), 'xwavecal.utils.overlap_utils.blank_overlap_table', 'blank_overlap_table', (['(1)'], {}), '(1)\n', (14831, 14834), False, 'from xwavecal.utils.overlap_utils import flag_bad_overlaps, fit_overlaps, blank_overlap_table, flag_outlier_overlaps\n'), ((17125, 17166), 'numpy.zeros_like', 'np.zeros_like', (["lines['flux']"], {'dtype': 'float'}), "(lines['flux'], dtype=float)\n", (17138, 17166), True, 'import numpy as np\n'), ((18982, 19020), 'numpy.isclose', 'np.isclose', (['scale', 'scale_guess'], {'rtol': '(2)'}), '(scale, scale_guess, rtol=2)\n', (18992, 19020), True, 'import numpy as np\n'), ((19495, 19523), 'numpy.sort', 'np.sort', (['wcs.reference_lines'], {}), '(wcs.reference_lines)\n', (19502, 19523), True, 'import numpy as np\n'), ((21432, 21462), 'astropy.stats.median_absolute_deviation', 'median_absolute_deviation', (['rsd'], {}), '(rsd)\n', (21457, 21462), False, 'from astropy.stats import median_absolute_deviation\n'), ((21464, 21475), 'numpy.std', 'np.std', (['rsd'], {}), '(rsd)\n', (21470, 21475), True, 'import numpy as np\n'), ((26181, 26211), 'astropy.stats.median_absolute_deviation', 'median_absolute_deviation', (['rsd'], {}), '(rsd)\n', (26206, 26211), False, 'from astropy.stats import median_absolute_deviation\n'), ((26213, 26224), 'numpy.std', 'np.std', (['rsd'], {}), '(rsd)\n', (26219, 26224), True, 'import numpy as np\n'), ((30242, 30272), 'astropy.stats.median_absolute_deviation', 'median_absolute_deviation', (['rsd'], {}), '(rsd)\n', (30267, 30272), False, 'from astropy.stats import median_absolute_deviation\n'), ((30274, 30285), 'numpy.std', 'np.std', (['rsd'], {}), '(rsd)\n', (30280, 30285), True, 'import numpy as np\n'), ((32752, 32764), 'astropy.table.Table', 'Table', (['lines'], {}), '(lines)\n', (32757, 32764), False, 'from astropy.table import Column, Table, vstack\n'), ((32915, 32969), 'astropy.table.Table', 'Table', (['image.wavelength_solution[fiber].measured_lines'], {}), '(image.wavelength_solution[fiber].measured_lines)\n', (32920, 32969), False, 'from astropy.table import Column, Table, vstack\n'), ((34695, 34709), 'numpy.min', 'np.min', (['merits'], {}), '(merits)\n', (34701, 34709), True, 'import numpy as np\n'), ((35813, 35828), 'numpy.array', 'np.array', (['merit'], {}), '(merit)\n', (35821, 35828), True, 'import numpy as np\n'), ((41524, 41544), 'numpy.ones_like', 'np.ones_like', (['orders'], {}), '(orders)\n', (41536, 41544), True, 'import numpy as np\n'), ((41576, 41600), 'numpy.zeros', 'np.zeros', (['spectrum_shape'], {}), '(spectrum_shape)\n', (41584, 41600), True, 'import numpy as np\n'), ((41842, 41856), 'numpy.min', 'np.min', (['orders'], {}), '(orders)\n', (41848, 41856), True, 'import numpy as np\n'), ((41868, 41882), 'numpy.max', 'np.max', (['orders'], {}), '(orders)\n', (41874, 41882), True, 'import numpy as np\n'), ((41939, 41952), 'numpy.min', 'np.min', (['pixel'], {}), '(pixel)\n', (41945, 41952), True, 'import numpy as np\n'), ((41964, 41977), 'numpy.max', 'np.max', (['pixel'], {}), '(pixel)\n', (41970, 41977), True, 'import numpy as np\n'), ((42116, 42140), 'numpy.sort', 'np.sort', (['reference_lines'], {}), '(reference_lines)\n', (42123, 42140), True, 'import numpy as np\n'), ((4664, 4692), 'numpy.array', 'np.array', (['wavelengths_to_fit'], {}), '(wavelengths_to_fit)\n', (4672, 4692), True, 'import numpy as np\n'), ((6482, 6501), 'numpy.isfinite', 'np.isfinite', (['pixels'], {}), '(pixels)\n', (6493, 6501), True, 'import numpy as np\n'), ((6511, 6530), 'numpy.isfinite', 'np.isfinite', (['pixels'], {}), '(pixels)\n', (6522, 6530), True, 'import numpy as np\n'), ((7215, 7253), 'numpy.zeros', 'np.zeros', (['(xpower + 1, orderpower + 1)'], {}), '((xpower + 1, orderpower + 1))\n', (7223, 7253), True, 'import numpy as np\n'), ((8788, 8813), 'xwavecal.utils.fiber_utils.lit_wavecal_fibers', 'lit_wavecal_fibers', (['image'], {}), '(image)\n', (8806, 8813), False, 'from xwavecal.utils.fiber_utils import lit_wavecal_fibers\n'), ((9735, 9774), 'numpy.max', 'np.max', (["single_fiber_spectrum['ref_id']"], {}), "(single_fiber_spectrum['ref_id'])\n", (9741, 9774), True, 'import numpy as np\n'), ((9848, 9887), 'numpy.min', 'np.min', (["single_fiber_spectrum['ref_id']"], {}), "(single_fiber_spectrum['ref_id'])\n", (9854, 9887), True, 'import numpy as np\n'), ((9961, 9999), 'numpy.max', 'np.max', (["single_fiber_spectrum['pixel']"], {}), "(single_fiber_spectrum['pixel'])\n", (9967, 9999), True, 'import numpy as np\n'), ((10073, 10111), 'numpy.min', 'np.min', (["single_fiber_spectrum['pixel']"], {}), "(single_fiber_spectrum['pixel'])\n", (10079, 10111), True, 'import numpy as np\n'), ((11376, 11401), 'xwavecal.utils.fiber_utils.lit_wavecal_fibers', 'lit_wavecal_fibers', (['image'], {}), '(image)\n', (11394, 11401), False, 'from xwavecal.utils.fiber_utils import lit_wavecal_fibers\n'), ((13483, 13517), 'numpy.count_nonzero', 'np.count_nonzero', (["overlaps['good']"], {}), "(overlaps['good'])\n", (13499, 13517), True, 'import numpy as np\n'), ((13654, 13688), 'numpy.count_nonzero', 'np.count_nonzero', (["overlaps['good']"], {}), "(overlaps['good'])\n", (13670, 13688), True, 'import numpy as np\n'), ((17224, 17327), 'scipy.interpolate.interp1d', 'interpolate.interp1d', (["spec['pixel']", "spec['flux']"], {'kind': '"""nearest"""', 'bounds_error': '(False)', 'fill_value': '(0)'}), "(spec['pixel'], spec['flux'], kind='nearest',\n bounds_error=False, fill_value=0)\n", (17244, 17327), False, 'from scipy import interpolate\n'), ((17351, 17393), 'numpy.where', 'np.where', (["(lines['order'] == spec['ref_id'])"], {}), "(lines['order'] == spec['ref_id'])\n", (17359, 17393), True, 'import numpy as np\n'), ((19407, 19455), 'xwavecal.utils.wavelength_utils.restrict', 'restrict', (['wcs.measured_lines', '*wcs.overlap_range'], {}), '(wcs.measured_lines, *wcs.overlap_range)\n', (19415, 19455), False, 'from xwavecal.utils.wavelength_utils import identify_lines, calc_residuals, restrict, Model, _sigma_clip\n'), ((19541, 19737), 'scipy.optimize.minimize', 'optimize.minimize', ([], {'fun': 'FindGlobalScale._chi_squared_safe', 'x0': 'scale_guess', 'args': 'args', 'method': 'brute_local_min', 'options': "{'step': step, 'rrange': rrange, 'filtw': 501, 'finish': 'Nelder-Mead'}"}), "(fun=FindGlobalScale._chi_squared_safe, x0=scale_guess,\n args=args, method=brute_local_min, options={'step': step, 'rrange':\n rrange, 'filtw': 501, 'finish': 'Nelder-Mead'})\n", (19558, 19737), False, 'from scipy import optimize\n'), ((20604, 20634), 'numpy.sum', 'np.sum', (['(residuals ** 2)'], {'axis': '(1)'}), '(residuals ** 2, axis=1)\n', (20610, 20634), True, 'import numpy as np\n'), ((32425, 32458), 'numpy.where', 'np.where', (["(lines['fiber'] == fiber)"], {}), "(lines['fiber'] == fiber)\n", (32433, 32458), True, 'import numpy as np\n'), ((32611, 32670), 'xwavecal.utils.misc_utils.find_nearest', 'find_nearest', (["lines['wavelength'][fib]", 'wcs.reference_lines'], {}), "(lines['wavelength'][fib], wcs.reference_lines)\n", (32623, 32670), False, 'from xwavecal.utils.misc_utils import brute_local_min, find_nearest, minmax\n'), ((34675, 34692), 'numpy.argmin', 'np.argmin', (['merits'], {}), '(merits)\n', (34684, 34692), True, 'import numpy as np\n'), ((41350, 41381), 'numpy.min', 'np.min', (["measured_lines['order']"], {}), "(measured_lines['order'])\n", (41356, 41381), True, 'import numpy as np\n'), ((41383, 41414), 'numpy.max', 'np.max', (["measured_lines['order']"], {}), "(measured_lines['order'])\n", (41389, 41414), True, 'import numpy as np\n'), ((41619, 41642), 'numpy.ones', 'np.ones', (['spectrum_shape'], {}), '(spectrum_shape)\n', (41626, 41642), True, 'import numpy as np\n'), ((6348, 6386), 'numpy.ones_like', 'np.ones_like', (['overlaps[pixel_key].data'], {}), '(overlaps[pixel_key].data)\n', (6360, 6386), True, 'import numpy as np\n'), ((7655, 7700), 'numpy.zeros_like', 'np.zeros_like', (['normed_pixel'], {'dtype': 'np.float64'}), '(normed_pixel, dtype=np.float64)\n', (7668, 7700), True, 'import numpy as np\n'), ((7918, 7941), 'numpy.dot', 'np.dot', (['A', 'coefficients'], {}), '(A, coefficients)\n', (7924, 7941), True, 'import numpy as np\n'), ((11276, 11323), 'numpy.genfromtxt', 'np.genfromtxt', (['reference_list_path'], {'usecols': '[1]'}), '(reference_list_path, usecols=[1])\n', (11289, 11323), True, 'import numpy as np\n'), ((20426, 20442), 'numpy.array', 'np.array', (['scales'], {}), '(scales)\n', (20434, 20442), True, 'import numpy as np\n'), ((21801, 21835), 'numpy.isclose', 'np.isclose', (['rsd', '(0)'], {'atol': '(4.5 * mad)'}), '(rsd, 0, atol=4.5 * mad)\n', (21811, 21835), True, 'import numpy as np\n'), ((21883, 21917), 'numpy.isclose', 'np.isclose', (['rsd', '(0)'], {'atol': '(4.5 * std)'}), '(rsd, 0, atol=4.5 * std)\n', (21893, 21917), True, 'import numpy as np\n'), ((26550, 26584), 'numpy.isclose', 'np.isclose', (['rsd', '(0)'], {'atol': '(4.5 * mad)'}), '(rsd, 0, atol=4.5 * mad)\n', (26560, 26584), True, 'import numpy as np\n'), ((26632, 26666), 'numpy.isclose', 'np.isclose', (['rsd', '(0)'], {'atol': '(4.5 * std)'}), '(rsd, 0, atol=4.5 * std)\n', (26642, 26666), True, 'import numpy as np\n'), ((27908, 27948), 'copy.deepcopy', 'copy.deepcopy', (['wavelength_solution.model'], {}), '(wavelength_solution.model)\n', (27921, 27948), False, 'import copy\n'), ((30611, 30645), 'numpy.isclose', 'np.isclose', (['rsd', '(0)'], {'atol': '(4.5 * mad)'}), '(rsd, 0, atol=4.5 * mad)\n', (30621, 30645), True, 'import numpy as np\n'), ((30693, 30727), 'numpy.isclose', 'np.isclose', (['rsd', '(0)'], {'atol': '(4.5 * std)'}), '(rsd, 0, atol=4.5 * std)\n', (30703, 30727), True, 'import numpy as np\n'), ((33106, 33153), 'numpy.zeros_like', 'np.zeros_like', (["lines['pixel']"], {'dtype': 'np.float64'}), "(lines['pixel'], dtype=np.float64)\n", (33119, 33153), True, 'import numpy as np\n'), ((33228, 33275), 'numpy.zeros_like', 'np.zeros_like', (["lines['pixel']"], {'dtype': 'np.float64'}), "(lines['pixel'], dtype=np.float64)\n", (33241, 33275), True, 'import numpy as np\n'), ((34741, 34758), 'numpy.median', 'np.median', (['merits'], {}), '(merits)\n', (34750, 34758), True, 'import numpy as np\n'), ((6949, 6971), 'numpy.add', 'np.add', (['order', 'self.m0'], {}), '(order, self.m0)\n', (6955, 6971), True, 'import numpy as np\n'), ((7348, 7412), 'numpy.polynomial.legendre.legval2d', 'legendre.legval2d', (['normed_pixel', 'normed_order', 'coefficient_array'], {}), '(normed_pixel, normed_order, coefficient_array)\n', (7365, 7412), False, 'from numpy.polynomial import legendre\n'), ((33014, 33042), 'numpy.ones_like', 'np.ones_like', (["lines['pixel']"], {}), "(lines['pixel'])\n", (33026, 33042), True, 'import numpy as np\n')]
import sys import numpy as np from vebio.Utilities import dict_to_yaml, yaml_to_dict from joblib import dump, load import matplotlib as mpl if len(sys.argv) > 1: params_filename = sys.argv[1] ve_params = yaml_to_dict(params_filename) else: ve_params = {} font={'family':'Helvetica', 'size':'15'} mpl.rc('font',**font) mpl.rc('xtick',labelsize=14) mpl.rc('ytick',labelsize=14) dt = 4 our_base = 100.0 # units? r = 0.75 # what is this parameter? gas_velocity = 0.08 column_height = 40. column_diameter = 5. bubble_diameter = 0.006 rho_g = ve_params['enzymatic_output']['rho_g'] rho_x = ve_params['enzymatic_output']['rho_x'] rho_f = ve_params['enzymatic_output']['rho_f'] # what is the source for this expression? our_max = our_base * np.exp(-rho_f/100.0) * (r + (1.0-r) * rho_g/(rho_g+rho_x)); T = ve_params['bioreactor_input']['t_final'] # these outputs should show units print('\nINPUTS') print('Gas velocity = %.2f' % (gas_velocity)) print('Column height = %.2f' % (column_height)) print('Column diameter = %.2f' % (column_diameter)) print('Bubble diameter = %.4f' % (bubble_diameter)) print('OUR_max = %.2f' % (our_max)) print('t_final = %.1f' % (T)) lb, ub = np.array([0.01, 10., 1., 5., 0.003]), np.array([0.1, 50., 6., 100., 0.008]) X = np.array([[gas_velocity, column_height, column_diameter, our_max, bubble_diameter]]) X = 2.*(X - lb)/(ub - lb) - 1. W1 = np.load('W1.npy') idx = T/dt if (idx%1 == 0): idx, s = int(idx), -1 else: idx, s = int(idx+1), idx%1 with open('gp_bub_col.pkl', 'rb') as f_id: for i in range(idx+1): gp = load(f_id) if (s > 0) and (i == idx-1): f_0 = gp.predict(X@W1, return_std=False)[0] if (s == -1): ff = np.power(10., gp.predict(X@W1, return_std=False)[0]) else: f_1 = gp.predict(X@W1, return_std=False)[0] ff = np.power(10., f_0*(1-s) + f_1*s) print('\nFINAL OUTPUTS (at t = %.1f seconds)' % (T)) print('OUR = %.4f' % (ff)) # units??? # Save the outputs into a dictionary output_dict = {'bioreactor_output': {}} output_dict['bioreactor_output']['our'] = float(ff) dict_to_yaml([ve_params, output_dict], params_filename)
[ "vebio.Utilities.dict_to_yaml", "matplotlib.rc", "numpy.load", "vebio.Utilities.yaml_to_dict", "numpy.power", "numpy.array", "numpy.exp", "joblib.load" ]
[((311, 333), 'matplotlib.rc', 'mpl.rc', (['"""font"""'], {}), "('font', **font)\n", (317, 333), True, 'import matplotlib as mpl\n'), ((333, 362), 'matplotlib.rc', 'mpl.rc', (['"""xtick"""'], {'labelsize': '(14)'}), "('xtick', labelsize=14)\n", (339, 362), True, 'import matplotlib as mpl\n'), ((362, 391), 'matplotlib.rc', 'mpl.rc', (['"""ytick"""'], {'labelsize': '(14)'}), "('ytick', labelsize=14)\n", (368, 391), True, 'import matplotlib as mpl\n'), ((1267, 1355), 'numpy.array', 'np.array', (['[[gas_velocity, column_height, column_diameter, our_max, bubble_diameter]]'], {}), '([[gas_velocity, column_height, column_diameter, our_max,\n bubble_diameter]])\n', (1275, 1355), True, 'import numpy as np\n'), ((1389, 1406), 'numpy.load', 'np.load', (['"""W1.npy"""'], {}), "('W1.npy')\n", (1396, 1406), True, 'import numpy as np\n'), ((2104, 2159), 'vebio.Utilities.dict_to_yaml', 'dict_to_yaml', (['[ve_params, output_dict]', 'params_filename'], {}), '([ve_params, output_dict], params_filename)\n', (2116, 2159), False, 'from vebio.Utilities import dict_to_yaml, yaml_to_dict\n'), ((213, 242), 'vebio.Utilities.yaml_to_dict', 'yaml_to_dict', (['params_filename'], {}), '(params_filename)\n', (225, 242), False, 'from vebio.Utilities import dict_to_yaml, yaml_to_dict\n'), ((1187, 1226), 'numpy.array', 'np.array', (['[0.01, 10.0, 1.0, 5.0, 0.003]'], {}), '([0.01, 10.0, 1.0, 5.0, 0.003])\n', (1195, 1226), True, 'import numpy as np\n'), ((1225, 1265), 'numpy.array', 'np.array', (['[0.1, 50.0, 6.0, 100.0, 0.008]'], {}), '([0.1, 50.0, 6.0, 100.0, 0.008])\n', (1233, 1265), True, 'import numpy as np\n'), ((753, 775), 'numpy.exp', 'np.exp', (['(-rho_f / 100.0)'], {}), '(-rho_f / 100.0)\n', (759, 775), True, 'import numpy as np\n'), ((1583, 1593), 'joblib.load', 'load', (['f_id'], {}), '(f_id)\n', (1587, 1593), False, 'from joblib import dump, load\n'), ((1847, 1886), 'numpy.power', 'np.power', (['(10.0)', '(f_0 * (1 - s) + f_1 * s)'], {}), '(10.0, f_0 * (1 - s) + f_1 * s)\n', (1855, 1886), True, 'import numpy as np\n')]
""" data_curation_functions.py Extract Kevin's functions for curation of public datasets Modify them to match Jonathan's curation methods in notebook 01/30/2020 """ import os import sys import numpy as np import pandas as pd import matplotlib.pyplot as plt from matplotlib_venn import venn3 import seaborn as sns import pdb from atomsci.ddm.utils.struct_utils import base_smiles_from_smiles import atomsci.ddm.utils.datastore_functions as dsf #from atomsci.ddm.utils import datastore_functions as dsf from atomsci.ddm.utils import curate_data as curate import atomsci.ddm.utils.struct_utils as struct_utils import atomsci.ddm.utils.curate_data as curate_data, imp def set_data_root(dir): '''Set global variables for data directories Creates paths for DTC and Excape given a root data directory. Global variables 'data_root' and 'data_dirs'. 'data_root' is the root data directory. 'data_dirs' is a dictionary that maps 'DTC' and 'Excape' to directores calcuated from 'data_root' Args: dir (str): root data directory containing folds 'dtc' and 'excape' Returns: None ''' global data_root, data_dirs data_root = dir #data_dirs = dict(ChEMBL = '%s/ChEMBL' % data_root, DTC = '%s/DTC' % data_root, # Excape = '%s/Excape' % data_root) data_dirs = dict(DTC = '%s/dtc' % data_root, Excape = '%s/excape' % data_root) log_var_map = { 'IC50': 'pIC50', 'AC50': 'pIC50', 'Solubility': 'logSolubility', 'CL': 'logCL' } pub_dsets = dict( CYP2D6 = dict(IC50='cyp2d6'), CYP3A4 = dict(IC50='cyp3a4'), JAK1 = dict(IC50="jak1"), JAK2 = dict(IC50="jak2"), JAK3 = dict(IC50="jak3"), ) # ---------------------------------------------------------------------------------------------------------------------- # Generic functions for all datasets # ---------------------------------------------------------------------------------------------------------------------- # Note: Functions freq_table and labeled_freq_table have been moved to ddm.utils.curate_data module. # ---------------------------------------------------------------------------------------------------------------------- def standardize_relations(dset_df, db='DTC'): """ Standardizes censoring operators Standardize the censoring operators to =, < or >, and remove any rows whose operators don't map to a standard one. There is a special case for db='ChEMBL' that strips the extra "'"s around relationship symbols. Assumes relationship columns are 'Standard Relation' and 'standard_relation' for ChEMBL and DTC respectively. This function makes the following mappings: ">" to ">", ">=" to ">", "<" to "<", "<=" to "<", and "=" to "=". All other relations are removed from the DataFrame. Args: dset_df (DataFrame): Input DataFrame. Must contain either 'Standard Relation' or 'standard_relation' db (str): Source database. Must be either 'DTC' or 'ChEMBL' Returns: DataFrame: Dataframe with the standardized relationship sybmols """ relation_cols = dict(ChEMBL='Standard Relation', DTC='standard_relation') rel_col = relation_cols[db] dset_df[rel_col].fillna('=', inplace=True) ops = dset_df[rel_col].values if db == 'ChEMBL': # Remove annoying quotes around operators ops = [op.lstrip("'").rstrip("'") for op in ops] op_dict = { ">": ">", ">=": ">", "<": "<", "<=": "<", "=": "=" } ops = np.array([op_dict.get(op, "@") for op in ops]) dset_df[rel_col] = ops dset_df = dset_df[dset_df[rel_col] != "@"] return dset_df # ---------------------------------------------------------------------------------------------------------------------- # DTC-specific curation functions # ---------------------------------------------------------------------------------------------------------------------- def upload_file_dtc_raw_data(dset_name, title, description, tags, functional_area, target, target_type, activity, assay_category,file_path, data_origin='journal', species='human', force_update=False): """Uploads raw DTC data to the datastore Upload a raw dataset to the datastore from the given DataFrame. Returns the datastore OID of the uploaded dataset. The dataset is uploaded to the public bucket and lists https://doi.org/10.1016/j.chembiol.2017.11.009' as the doi. This also assumes that the id_col is 'compound_id' Args: dset_name (str): Name of the dataset. Should not include a file extension. title (str): title of the file in (human friendly format) description (str): long text box to describe file (background/use notes) tags (list): Must be a list of strings. functional_area (str): The functional area. target (str): The target. target_type (str): The target type of the dataset. activity (str): The activity of the dataset. assay_category (str): The assay category of the dataset. file_path (str): The filepath of the dataset. data_origin (str): The origin of the dataset e.g. journal. species (str): The species of the dataset e.g. human, rat, dog. force_update (bool): Overwrite existing datasets in the datastore. Returns: str: datastore OID of the uploaded dataset. """ bucket = 'public' filename = '%s.csv' % dset_name dataset_key = 'dskey_' + filename kv = { 'file_category': 'experimental', 'activity': activity, 'assay_category':assay_category, 'assay_endpoint' : 'multiple values', 'curation_level': 'raw', 'data_origin' : data_origin, 'functional_area' : functional_area, 'matrix' : 'multiple values', 'journal_doi' : 'https://doi.org/10.1016/j.chembiol.2017.11.009', 'sample_type' : 'in_vitro', 'species' : species, 'target' : target, 'target_type' : target_type, 'id_col' : 'compound_id' } #uploaded_file = dsf.upload_file_to_DS(bucket=bucket, filepath=file_path, filename=filename, title = title, description=description, tags=tags, key_values=kv, client=None, dataset_key=dataset_key, override_check=False, return_metadata=True) ds_client = dsf.config_client() if force_update or not dsf.dataset_key_exists(dataset_key, bucket, ds_client): #uploaded_file = dsf.upload_df_to_DS(dset_df, bucket, filename=filename, title=title, # description=description, # tags=tags, key_values=kv, client=None, dataset_key=dataset_key, # override_check=True, return_metadata=True) uploaded_file = dsf.upload_file_to_DS(bucket=bucket, filepath=file_path, filename=filename, title = title, description=description, tags=tags, key_values=kv, client=None, dataset_key=dataset_key, override_check=False, return_metadata=True) print("Uploaded raw dataset with key %s" % dataset_key) else: uploaded_file = dsf.retrieve_dataset_by_datasetkey(dataset_key, bucket, ds_client, return_metadata=True) print("Raw dataset %s is already in datastore, skipping upload." % dataset_key) raw_dset_oid = uploaded_file['dataset_oid'] return raw_dset_oid def filter_dtc_data(orig_df,geneNames): """ Extracts and post processes JAK1, 2, and 3 datasets from DTC This is specific to the DTC database. Extract JAK1, 2 and 3 datasets from Drug Target Commons database, filtered for data usability. filter criteria: gene_names == JAK1 | JAK2 | JAK3 InChi key not missing standard_type IC50 units NM standard_relation mappable to =, < or > wildtype_or_mutant != 'mutated' valid SMILES maps to valid RDKit base SMILES standard_value not missing pIC50 > 3 Args: orig_df (DataFrame): Input DataFrame. Must contain the following columns: gene_names standard_inchi_key, standard_type, standard_units, standard_value, compound_id, wildtype_or_mutant. geneNames (list): A list of gene names to filter out of orig_df e.g. ['JAK1', 'JAK2']. Returns: DataFrame: The filtered rows of the orig_df """ dset_df = orig_df[orig_df.gene_names.isin(geneNames) & ~(orig_df.standard_inchi_key.isna()) & (orig_df.standard_type == 'IC50') & (orig_df.standard_units == 'NM') & ~orig_df.standard_value.isna() & ~orig_df.compound_id.isna() & (orig_df.wildtype_or_mutant != 'mutated') ] return dset_df def ic50topic50(x) : """Calculates pIC50 from IC50 Calculates pIC50 from IC50 Args: x (float): An IC50. Returns: float: The pIC50. """ print(x) return -np.log10((x/1000000000.0)) def down_select(df,kv_lst) : """Filters rows given a set of values Given a DataFrame and a list of tuples columns (k) to values (v), this function filters out all rows where df[k] == v. Args: df (DataFrame): An input DataFrame. kv_list (list): A list of tuples of (column, value) Returns: DataFrame: Rows where all df[k] == v """ for k,v in kv_lst : df=df[df[k]==v] return df def get_smiles_dtc_data(nm_df,targ_lst,save_smiles_df): """Returns SMILES strings from DTC data nm_df must be a DataFrame from DTC with the following columns: gene_names, standard_type, standard_value, 'standard_inchi_key', and standard_relation. This function selects all rows where nm_df['gene_names'] is in targ_lst, nm_df['standard_type']=='IC50', nm_df['standard_relation']=='=', and 'standard_value' > 0. Then pIC50 values are calculated and added to the 'PIC50' column, and smiles strings are merged in from save_smiles_df Args: nm_df (DataFrame): Input DataFrame. targ_lst (list): A list of targets. save_smiles_df (DataFrame): A DataFrame with the column 'standard_inchi_key' Returns: list, list: A list of smiles and a list of inchi keys shared between targets. """ save_df={} for targ in targ_lst : lst1= [ ('gene_names',targ),('standard_type','IC50'),('standard_relation','=') ] lst1_tmp= [ ('gene_names',targ),('standard_type','IC50')] jak1_df=down_select(nm_df,lst1) jak1_df_tmp=down_select(nm_df,lst1_tmp) print(targ,"distinct compounds = only",jak1_df['standard_inchi_key'].nunique()) print(targ,"distinct compounds <,>,=",jak1_df_tmp['standard_inchi_key'].nunique()) ## we convert to log values so make sure there are no 0 values save_df[targ]=jak1_df_tmp[jak1_df_tmp['standard_value']>0] prev_targ=targ_lst[0] shared_inchi_keys=save_df[prev_targ]['standard_inchi_key'] for it in range(1,len(targ_lst),1) : curr_targ=targ_lst[it] df=save_df[curr_targ] shared_inchi_keys=df[df['standard_inchi_key'].isin(shared_inchi_keys)]['standard_inchi_key'] print("num shared compounds",shared_inchi_keys.nunique()) lst=[] for targ in targ_lst : df=save_df[targ] #print(aurka_df.shape,aurkb_df.shape, shared_inchi_keys.shape) lst.append(df[df['standard_inchi_key'].isin(shared_inchi_keys)]) shared_df=pd.concat(lst) # Add pIC50 values print('Add pIC50 values.') print(shared_df['standard_value']) shared_df['PIC50']=shared_df['standard_value'].apply(ic50topic50) # Merge in SMILES strings print('Merge in SMILES strings.') smiles_lst=[] for targ in targ_lst : df=save_df[targ] df['PIC50']=df['standard_value'].apply(ic50topic50) smiles_df=df.merge(save_smiles_df,on='standard_inchi_key',suffixes=('_'+targ,'_')) #the file puts the SMILES string in quotes, which need to be removed smiles_df['smiles']=smiles_df['smiles'].str.replace('"','') smiles_df['rdkit_smiles']=smiles_df['smiles'].apply(struct_utils.base_smiles_from_smiles) smiles_df['smiles']=smiles_df['smiles'].str.replace('"','') print(smiles_df.shape) print(smiles_df['standard_inchi_key'].nunique()) smiles_lst.append(smiles_df) return smiles_lst, shared_inchi_keys def get_smiles_4dtc_data(nm_df,targ_lst,save_smiles_df): """Returns SMILES strings from DTC data nm_df must be a DataFrame from DTC with the following columns: gene_names, standard_type, standard_value, 'standard_inchi_key', and standard_relation. This function selects all rows where nm_df['gene_names'] is in targ_lst, nm_df['standard_type']=='IC50', nm_df['standard_relation']=='=', and 'standard_value' > 0. Then pIC50 values are calculated and added to the 'PIC50' column, and smiles strings are merged in from save_smiles_df Args: nm_df (DataFrame): Input DataFrame. targ_lst (list): A list of targets. save_smiles_df (DataFrame): A DataFrame with the column 'standard_inchi_key' Returns: list, list, str: A list of smiles. A list of inchi keys shared between targets. And a description of the targets """ save_df={} description_str = "" for targ in targ_lst : lst1= [ ('gene_names',targ),('standard_type','IC50'),('standard_relation','=') ] lst1_tmp= [ ('gene_names',targ),('standard_type','IC50')] jak1_df=down_select(nm_df,lst1) jak1_df_tmp=down_select(nm_df,lst1_tmp) print(targ,"distinct compounds = only",jak1_df['standard_inchi_key'].nunique()) print(targ,"distinct compounds <,>,=",jak1_df_tmp['standard_inchi_key'].nunique()) description = ''' # '''+targ+" distinct compounds = only: "+str(jak1_df['standard_inchi_key'].nunique())+''' # '''+targ+" distinct compounds <,>,=: "+str(jak1_df_tmp['standard_inchi_key'].nunique()) description_str += description #to ignore censored data #save_df[targ]=jak1_df #to include censored data save_df[targ]=jak1_df_tmp prev_targ=targ_lst[0] shared_inchi_keys=save_df[prev_targ]['standard_inchi_key'] for it in range(1,len(targ_lst),1) : curr_targ=targ_lst[it] df=save_df[curr_targ] shared_inchi_keys=df[df['standard_inchi_key'].isin(shared_inchi_keys)]['standard_inchi_key'] print("num shared compounds",shared_inchi_keys.nunique()) lst=[] for targ in targ_lst : df=save_df[targ] #print(aurka_df.shape,aurkb_df.shape, shared_inchi_keys.shape) lst.append(df[df['standard_inchi_key'].isin(shared_inchi_keys)]) shared_df=pd.concat(lst) # Add pIC50 values print('Add pIC50 values.') shared_df['PIC50']=shared_df['standard_value'].apply(ic50topic50) # Merge in SMILES strings print('Merge in SMILES strings.') smiles_lst=[] for targ in targ_lst : df=save_df[targ] df['PIC50']=df['standard_value'].apply(ic50topic50) smiles_df=df.merge(save_smiles_df,on='standard_inchi_key',suffixes=('_'+targ,'_')) #the file puts the SMILES string in quotes, which need to be removed smiles_df['smiles']=smiles_df['smiles'].str.replace('"','') smiles_df['rdkit_smiles']=smiles_df['smiles'].apply(struct_utils.base_smiles_from_smiles) smiles_df['smiles']=smiles_df['smiles'].str.replace('"','') print("Shape of dataframe:", smiles_df.shape) print("Number of unique standard_inchi_key:", smiles_df['standard_inchi_key'].nunique()) smiles_lst.append(smiles_df) return smiles_lst, shared_inchi_keys, description_str def upload_df_dtc_smiles(dset_name, title, description, tags, functional_area, target, target_type, activity, assay_category,smiles_df,orig_fileID, data_origin='journal', species='human', force_update=False): """Uploads DTC smiles data to the datastore Upload a raw dataset to the datastore from the given DataFrame. Returns the datastore OID of the uploaded dataset. The dataset is uploaded to the public bucket and lists https://doi.org/10.1016/j.chembiol.2017.11.009' as the doi. This also assumes that the id_col is 'compound_id' Args: dset_name (str): Name of the dataset. Should not include a file extension. title (str): title of the file in (human friendly format) description (str): long text box to describe file (background/use notes) tags (list): Must be a list of strings. functional_area (str): The functional area. target (str): The target. target_type (str): The target type of the dataset. activity (str): The activity of the dataset. assay_category (str): The assay category of the dataset. smiles_df (DataFrame): DataFrame containing SMILES to be uploaded. orig_fileID (str): Source file id used to generate smiles_df. data_origin (str): The origin of the dataset e.g. journal. species (str): The species of the dataset e.g. human, rat, dog. force_update (bool): Overwrite existing datasets in the datastore. Returns: str: datastore OID of the uploaded dataset. """ bucket = 'public' filename = '%s_dtc_smiles.csv' % dset_name dataset_key = 'dskey_' + filename kv = { 'file_category': 'experimental', 'activity': activity, 'assay_category': assay_category, ## seems like this should be called 'kinase_activity' 'assay_endpoint' : 'pic50', 'curation_level': 'raw', 'data_origin' : data_origin, 'functional_area' : functional_area, 'matrix' : 'multiple values', 'journal_doi' : 'https://doi.org/10.1016/j.chembiol.2017.11.009', 'sample_type' : 'in_vitro', 'species' : species, 'target' : target, 'target_type' : target_type, 'id_col' : 'compound_id', 'source_file_id' : orig_fileID } #uploaded_file = dsf.upload_file_to_DS(bucket=bucket, filepath=file_path, filename=filename, title = title, description=description, tags=tags, key_values=kv, client=None, dataset_key=dataset_key, override_check=False, return_metadata=True) ds_client = dsf.config_client() if force_update or not dsf.dataset_key_exists(dataset_key, bucket, ds_client): uploaded_file = dsf.upload_df_to_DS(bucket=bucket, filename=filename,df=smiles_df, title = title, description=description, tags=tags, key_values=kv, client=None, dataset_key=dataset_key, override_check=False, return_metadata=True) #uploaded_file = dsf.upload_file_to_DS(bucket=bucket, filepath=file_path, filename=filename, title = title, description=description, tags=tags, key_values=kv, client=None, dataset_key=dataset_key, override_check=False, return_metadata=True) print("Uploaded raw dataset with key %s" % dataset_key) else: uploaded_file = dsf.retrieve_dataset_by_datasetkey(dataset_key, bucket, ds_client, return_metadata=True) print("Raw dataset %s is already in datastore, skipping upload." % dataset_key) raw_dset_oid = uploaded_file['dataset_oid'] return raw_dset_oid def atom_curation(targ_lst, smiles_lst, shared_inchi_keys): """Apply ATOM standard 'curation' step to "shared_df" Apply ATOM standard 'curation' step to "shared_df": Average replicate assays, remove duplicates and drop cases with large variance between replicates. mleqonly Args: targ_lst (list): A list of targets. smiles_lst (list): A list of DataFrames. These DataFrames must contain the columns gene_names, standard_type, standard_relation, standard_inchi_key, PIC50, and rdkit_smiles shared_inchi_keys (list): A list of inchi keys used in this dataset. Returns: list, list:A list of curated DataFrames and a list of the number of compounds dropped during the curation process for each target. """ imp.reload(curate_data) tolerance=10 column='PIC50'; #'standard_value' list_bad_duplicates='No' max_std=1 curated_lst=[] num_dropped_lst=[] #print(targ_lst) #print(smiles_lst) for it in range(len(targ_lst)) : data=smiles_lst[it] data = data[data.standard_relation.str.strip() == '='] print("gene_names",data.gene_names.unique()) print("standard_type",data.standard_type.unique()) print("standard_relation",data.standard_relation.unique()) print("before",data.shape) curated_df=curate_data.average_and_remove_duplicates (column, tolerance, list_bad_duplicates, data, max_std, compound_id='standard_inchi_key',smiles_col='rdkit_smiles') # (Yaru) Remove inf in curated_df curated_df = curated_df[~curated_df.isin([np.inf]).any(1)] # (Yaru) Remove nan on rdkit_smiles curated_df = curated_df.dropna(subset=['rdkit_smiles']) curated_lst.append(curated_df) prev_cmpd_cnt=shared_inchi_keys.nunique() num_dropped=prev_cmpd_cnt-curated_df.shape[0] num_dropped_lst.append(num_dropped) print("After",curated_df.shape, "# of dropped compounds",num_dropped) return curated_lst,num_dropped_lst def upload_df_dtc_mleqonly(dset_name, title, description, tags, functional_area, target, target_type, activity, assay_category,data_df,dtc_smiles_fileID, data_origin='journal', species='human', force_update=False): """Uploads DTC mleqonly data to the datastore Upload mleqonly data to the datastore from the given DataFrame. The DataFrame must contain the column 'rdkit_smiles' and 'VALUE_NUM_mean'. This function is meant to upload data that has been aggregated using atomsci.ddm.utils.curate_data.average_and_remove_duplicates. Returns the datastore OID of the uploaded dataset. The dataset is uploaded to the public bucket and lists https://doi.org/10.1016/j.chembiol.2017.11.009' as the doi. This also assumes that the id_col is 'compound_id'. Args: dset_name (str): Name of the dataset. Should not include a file extension. title (str): title of the file in (human friendly format) description (str): long text box to describe file (background/use notes) tags (list): Must be a list of strings. functional_area (str): The functional area. target (str): The target. target_type (str): The target type of the dataset. activity (str): The activity of the dataset. assay_category (str): The assay category of the dataset. data_df (DataFrame): DataFrame to be uploaded. dtc_smiles_fileID (str): Source file id used to generate data_df. data_origin (str): The origin of the dataset e.g. journal. species (str): The species of the dataset e.g. human, rat, dog. force_update (bool): Overwrite existing datasets in the datastore. Returns: str: datastore OID of the uploaded dataset. """ bucket = 'public' filename = '%s_dtc_mleqonly.csv' % dset_name dataset_key = 'dskey_' + filename kv = { 'file_category': 'experimental', 'activity': activity, 'assay_category': assay_category, ## seems like this should be called 'kinase_activity' 'assay_endpoint' : 'pic50', 'curation_level': 'ml_ready', 'data_origin' : data_origin, 'functional_area' : functional_area, 'matrix' : 'multiple values', 'journal_doi' : 'https://doi.org/10.1016/j.chembiol.2017.11.009', 'sample_type' : 'in_vitro', 'species' : species, 'target' : target, 'target_type' : target_type, 'id_col' : 'compound_id', 'response_col' : 'VALUE_NUM_mean', 'prediction_type' : 'regression', 'smiles_col' : 'rdkit_smiles', 'units' : 'unitless', 'source_file_id' : dtc_smiles_fileID } #uploaded_file = dsf.upload_file_to_DS(bucket=bucket, filepath=file_path, filename=filename, title = title, description=description, tags=tags, key_values=kv, client=None, dataset_key=dataset_key, override_check=False, return_metadata=True) ds_client = dsf.config_client() if force_update or not dsf.dataset_key_exists(dataset_key, bucket, ds_client): uploaded_file = dsf.upload_df_to_DS(bucket=bucket, filename=filename,df=data_df, title = title, description=description, tags=tags, key_values=kv, client=None, dataset_key=dataset_key, override_check=False, return_metadata=True) #uploaded_file = dsf.upload_file_to_DS(bucket=bucket, filepath=file_path, filename=filename, title = title, description=description, tags=tags, key_values=kv, client=None, dataset_key=dataset_key, override_check=False, return_metadata=True) print("Uploaded raw dataset with key %s" % dataset_key) else: uploaded_file = dsf.retrieve_dataset_by_datasetkey(dataset_key, bucket, ds_client, return_metadata=True) print("Raw dataset %s is already in datastore, skipping upload." % dataset_key) raw_dset_oid = uploaded_file['dataset_oid'] return raw_dset_oid def upload_df_dtc_mleqonly_class(dset_name, title, description, tags, functional_area, target, target_type, activity, assay_category,data_df,dtc_mleqonly_fileID, data_origin='journal', species='human', force_update=False): """Uploads DTC mleqonly classification data to the datastore Upload mleqonly classification data to the datastore from the given DataFrame. The DataFrame must contain the column 'rdkit_smiles' and 'binary_class'. This function is meant to upload data that has been aggregated using atomsci.ddm.utils.curate_data.average_and_remove_duplicates and then thresholded to make a binary classification dataset. Returns the datastore OID of the uploaded dataset. The dataset is uploaded to the public bucket and lists https://doi.org/10.1016/j.chembiol.2017.11.009' as the doi. This also assumes that the id_col is 'compound_id'. Args: dset_name (str): Name of the dataset. Should not include a file extension. title (str): title of the file in (human friendly format) description (str): long text box to describe file (background/use notes) tags (list): Must be a list of strings. functional_area (str): The functional area. target (str): The target. target_type (str): The target type of the dataset. activity (str): The activity of the dataset. assay_category (str): The assay category of the dataset. data_df (DataFrame): DataFrame to be uploaded. dtc_mleqonly_fileID (str): Source file id used to generate data_df. data_origin (str): The origin of the dataset e.g. journal. species (str): The species of the dataset e.g. human, rat, dog. force_update (bool): Overwrite existing datasets in the datastore. Returns: str: datastore OID of the uploaded dataset. """ bucket = 'public' filename = '%s_dtc_mleqonly_class.csv' % dset_name dataset_key = 'dskey_' + filename kv = { 'file_category': 'experimental', 'activity': activity, 'assay_category': assay_category, ## seems like this should be called 'kinase_activity' 'assay_endpoint' : 'pic50', 'curation_level': 'ml_ready', 'data_origin' : data_origin, 'functional_area' : functional_area, 'matrix' : 'multiple values', 'journal_doi' : 'https://doi.org/10.1016/j.chembiol.2017.11.009', 'sample_type' : 'in_vitro', 'species' : species, 'target' : target, 'target_type' : target_type, 'id_col' : 'compound_id', 'response_col' : 'binary_class', 'prediction_type' : 'classification', 'num_classes' : 2, 'class_names' : ['inactive','active'], 'smiles_col' : 'rdkit_smiles', 'units' : 'unitless', 'source_file_id' : dtc_mleqonly_fileID } ds_client = dsf.config_client() if force_update or not dsf.dataset_key_exists(dataset_key, bucket, ds_client): uploaded_file = dsf.upload_df_to_DS(bucket=bucket, filename=filename,df=data_df, title = title, description=description, tags=tags, key_values=kv, client=None, dataset_key=dataset_key, override_check=False, return_metadata=True) print("Uploaded raw dataset with key %s" % dataset_key) else: uploaded_file = dsf.retrieve_dataset_by_datasetkey(dataset_key, bucket, ds_client, return_metadata=True) print("Raw dataset %s is already in datastore, skipping upload." % dataset_key) raw_dset_oid = uploaded_file['dataset_oid'] return raw_dset_oid def upload_df_dtc_base_smiles_all(dset_name, title, description, tags, functional_area, target, target_type, activity, assay_category,data_df,dtc_mleqonly_fileID, data_origin='journal', species='human', force_update=False): """Uploads DTC base smiles data to the datastore Uploads base SMILES string for the DTC dataset. Returns the datastore OID of the uploaded dataset. The dataset is uploaded to the public bucket and lists https://doi.org/10.1016/j.chembiol.2017.11.009' as the doi. This also assumes that the id_col is 'compound_id', the response column is set to PIC50, and the SMILES are assumed to be in 'base_rdkit_smiles'. Args: dset_name (str): Name of the dataset. Should not include a file extension. title (str): title of the file in (human friendly format) description (str): long text box to describe file (background/use notes) tags (list): Must be a list of strings. functional_area (str): The functional area. target (str): The target. target_type (str): The target type of the dataset. activity (str): The activity of the dataset. assay_category (str): The assay category of the dataset. data_df (DataFrame): DataFrame to be uploaded. dtc_mleqonly_fileID (str): Source file id used to generate data_df. data_origin (str): The origin of the dataset e.g. journal. species (str): The species of the dataset e.g. human, rat, dog. force_update (bool): Overwrite existing datasets in the datastore. Returns: str: datastore OID of the uploaded dataset. """ bucket = 'public' filename = '%s_dtc_base_smiles_all.csv' % dset_name dataset_key = 'dskey_' + filename kv = { 'file_category': 'experimental', 'activity': activity, 'assay_category': assay_category, ## seems like this should be called 'kinase_activity' 'assay_endpoint' : 'pic50', 'curation_level': 'ml_ready', 'data_origin' : data_origin, 'functional_area' : functional_area, 'matrix' : 'multiple values', 'journal_doi' : 'https://doi.org/10.1016/j.chembiol.2017.11.009', 'sample_type' : 'in_vitro', 'species' : species, 'target' : target, 'target_type' : target_type, 'id_col' : 'compound_id', 'response_col' : 'PIC50', 'prediction_type' : 'regression', 'smiles_col' : 'base_rdkit_smiles', 'units' : 'unitless', 'source_file_id' : dtc_mleqonly_fileID } ds_client = dsf.config_client() if force_update or not dsf.dataset_key_exists(dataset_key, bucket, ds_client): uploaded_file = dsf.upload_df_to_DS(bucket=bucket, filename=filename,df=data_df, title = title, description=description, tags=tags, key_values=kv, client=None, dataset_key=dataset_key, override_check=False, return_metadata=True) print("Uploaded raw dataset with key %s" % dataset_key) else: uploaded_file = dsf.retrieve_dataset_by_datasetkey(dataset_key, bucket, ds_client, return_metadata=True) print("Raw dataset %s is already in datastore, skipping upload." % dataset_key) raw_dset_oid = uploaded_file['dataset_oid'] return raw_dset_oid def upload_file_dtc_smiles_regr_all(dset_name, title, description, tags, functional_area, target, target_type, activity, assay_category,file_path,dtc_smiles_fileID, smiles_column, data_origin='journal', species='human', force_update=False): """Uploads regression DTC data to the datastore Uploads regression dataset for DTC dataset. Returns the datastore OID of the uploaded dataset. The dataset is uploaded to the public bucket and lists https://doi.org/10.1016/j.chembiol.2017.11.009' as the doi. This also assumes that the id_col is 'compound_id', the response column is set to PIC50. Args: dset_name (str): Name of the dataset. Should not include a file extension. title (str): title of the file in (human friendly format) description (str): long text box to describe file (background/use notes) tags (list): Must be a list of strings. functional_area (str): The functional area. target (str): The target. target_type (str): The target type of the dataset. activity (str): The activity of the dataset. assay_category (str): The assay category of the dataset. data_df (DataFrame): DataFrame to be uploaded. dtc_smiles_fileID(str): Source file id used to generate data_df. smiles_column (str): Column containing SMILES. data_origin (str): The origin of the dataset e.g. journal. species (str): The species of the dataset e.g. human, rat, dog. force_update (bool): Overwrite existing datasets in the datastore. Returns: str: datastore OID of the uploaded dataset. """ bucket = 'public' filename = '%s_dtc_smiles_regr_all.csv' % dset_name dataset_key = 'dskey_' + filename kv = { 'file_category': 'experimental', 'activity': activity, 'assay_category': assay_category, ## seems like this should be called 'kinase_activity' 'assay_endpoint' : 'pic50', 'curation_level': 'ml_ready', 'data_origin' : data_origin, 'functional_area' : functional_area, 'matrix' : 'multiple values', 'journal_doi' : 'https://doi.org/10.1016/j.chembiol.2017.11.009', 'sample_type' : 'in_vitro', 'species' : species, 'target' : target, 'target_type' : target_type, 'id_col' : 'compound_id', 'response_col' : 'PIC50', 'prediction_type' : 'regression', 'smiles_col' : smiles_column, 'units' : 'unitless', 'source_file_id' : dtc_smiles_fileID } #uploaded_file = dsf.upload_file_to_DS(bucket=bucket, filepath=file_path, filename=filename, title = title, description=description, tags=tags, key_values=kv, client=None, dataset_key=dataset_key, override_check=False, return_metadata=True) ds_client = dsf.config_client() if force_update or not dsf.dataset_key_exists(dataset_key, bucket, ds_client): #uploaded_file = dsf.upload_df_to_DS(bucket=bucket, filename=filename,df=data_df, title = title, description=description, tags=tags, key_values=kv, client=None, dataset_key=dataset_key, override_check=False, return_metadata=True) uploaded_file = dsf.upload_file_to_DS(bucket=bucket, filepath=file_path, filename=filename, title = title, description=description, tags=tags, key_values=kv, client=None, dataset_key=dataset_key, override_check=False, return_metadata=True) print("Uploaded raw dataset with key %s" % dataset_key) else: uploaded_file = dsf.retrieve_dataset_by_datasetkey(dataset_key, bucket, ds_client, return_metadata=True) print("Raw dataset %s is already in datastore, skipping upload." % dataset_key) raw_dset_oid = uploaded_file['dataset_oid'] return raw_dset_oid def upload_df_dtc_smiles_regr_all_class(dset_name, title, description, tags, functional_area, target, target_type, activity, assay_category,data_df,dtc_smiles_regr_all_fileID, smiles_column, data_origin='journal', species='human', force_update=False): """Uploads DTC classification data to the datastore Uploads binary classiciation data for the DTC dataset. Classnames are assumed to be 'active' and 'inactive' Returns the datastore OID of the uploaded dataset. The dataset is uploaded to the public bucket and lists https://doi.org/10.1016/j.chembiol.2017.11.009' as the doi. This also assumes that the id_col is 'compound_id', the response column is set to PIC50. Args: dset_name (str): Name of the dataset. Should not include a file extension. title (str): title of the file in (human friendly format) description (str): long text box to describe file (background/use notes) tags (list): Must be a list of strings. functional_area (str): The functional area. target (str): The target. target_type (str): The target type of the dataset. activity (str): The activity of the dataset. assay_category (str): The assay category of the dataset. data_df (DataFrame): DataFrame to be uploaded. dtc_smiles_regr_all_fileID(str): Source file id used to generate data_df. smiles_column (str): Column containing SMILES. data_origin (str): The origin of the dataset e.g. journal. species (str): The species of the dataset e.g. human, rat, dog. force_update (bool): Overwrite existing datasets in the datastore. Returns: str: datastore OID of the uploaded dataset. """ bucket = 'public' filename = '%s_dtc_smiles_regr_all_class.csv' % dset_name dataset_key = 'dskey_' + filename kv = { 'file_category': 'experimental', 'activity': activity, 'assay_category': assay_category, ## seems like this should be called 'kinase_activity' 'assay_endpoint' : 'pic50', 'curation_level': 'ml_ready', 'data_origin' : data_origin, 'functional_area' : functional_area, 'matrix' : 'multiple values', 'journal_doi' : 'https://doi.org/10.1016/j.chembiol.2017.11.009', 'sample_type' : 'in_vitro', 'species' : species, 'target' : target, 'target_type' : target_type, 'id_col' : 'compound_id', 'response_col' : 'PIC50', 'prediction_type' : 'classification', 'num_classes' : 2, 'smiles_col' : smiles_column, 'class_names' : ['inactive','active'], 'units' : 'unitless', 'source_file_id' : dtc_smiles_regr_all_fileID } #uploaded_file = dsf.upload_file_to_DS(bucket=bucket, filepath=file_path, filename=filename, title = title, description=description, tags=tags, key_values=kv, client=None, dataset_key=dataset_key, override_check=False, return_metadata=True) ds_client = dsf.config_client() if force_update or not dsf.dataset_key_exists(dataset_key, bucket, ds_client): uploaded_file = dsf.upload_df_to_DS(bucket=bucket, filename=filename,df=data_df, title = title, description=description, tags=tags, key_values=kv, client=None, dataset_key=dataset_key, override_check=False, return_metadata=True) #uploaded_file = dsf.upload_file_to_DS(bucket=bucket, filepath=file_path, filename=filename, title = title, description=description, tags=tags, key_values=kv, client=None, dataset_key=dataset_key, override_check=False, return_metadata=True) print("Uploaded raw dataset with key %s" % dataset_key) else: uploaded_file = dsf.retrieve_dataset_by_datasetkey(dataset_key, bucket, ds_client, return_metadata=True) print("Raw dataset %s is already in datastore, skipping upload." % dataset_key) raw_dset_oid = uploaded_file['dataset_oid'] return raw_dset_oid # ---------------------------------------------------------------------------------------------------------------------- # Excape-specific curation functions # ---------------------------------------------------------------------------------------------------------------------- def upload_file_excape_raw_data(dset_name, title, description, tags, functional_area, target, target_type, activity, assay_category,file_path, data_origin='journal', species='human', force_update=False): """Uploads raw Excape data to the datastore Upload a raw dataset to the datastore from the given DataFrame. Returns the datastore OID of the uploaded dataset. The dataset is uploaded to the public bucket and lists https://dx.doi.org/10.1186%2Fs13321-017-0203-5 as the doi. This also assumes that the id_col is 'Original_Entry_ID' Args: dset_name (str): Name of the dataset. Should not include a file extension. title (str): title of the file in (human friendly format) description (str): long text box to describe file (background/use notes) tags (list): Must be a list of strings. functional_area (str): The functional area. target (str): The target. target_type (str): The target type of the dataset. activity (str): The activity of the dataset. assay_category (str): The assay category of the dataset. file_path (str): The filepath of the dataset. data_origin (str): The origin of the dataset e.g. journal. species (str): The species of the dataset e.g. human, rat, dog. force_update (bool): Overwrite existing datasets in the datastore. Returns: str: datastore OID of the uploaded dataset. """ bucket = 'public' filename = '%s_excape.csv' % dset_name dataset_key = 'dskey_' + filename kv = { 'file_category': 'experimental', 'activity': activity, 'assay_category':assay_category, 'assay_endpoint' : 'multiple values', 'curation_level': 'raw', 'data_origin' : data_origin, 'functional_area' : functional_area, 'matrix' : 'multiple values', 'journal_doi' : 'https://dx.doi.org/10.1186%2Fs13321-017-0203-5', # ExCAPE-DB 'sample_type' : 'in_vitro', 'species' : species, 'target' : target, 'target_type' : target_type, 'id_col' : 'Original_Entry_ID' } #uploaded_file = dsf.upload_file_to_DS(bucket=bucket, filepath=file_path, filename=filename, title = title, description=description, tags=tags, key_values=kv, client=None, dataset_key=dataset_key, override_check=False, return_metadata=True) ds_client = dsf.config_client() if force_update or not dsf.dataset_key_exists(dataset_key, bucket, ds_client): #uploaded_file = dsf.upload_df_to_DS(dset_df, bucket, filename=filename, title=title, # description=description, # tags=tags, key_values=kv, client=None, dataset_key=dataset_key, # override_check=True, return_metadata=True) uploaded_file = dsf.upload_file_to_DS(bucket=bucket, filepath=file_path, filename=filename, title = title, description=description, tags=tags, key_values=kv, client=None, dataset_key=dataset_key, override_check=False, return_metadata=True) print("Uploaded raw dataset with key %s" % dataset_key) else: uploaded_file = dsf.retrieve_dataset_by_datasetkey(dataset_key, bucket, ds_client, return_metadata=True) print("Raw dataset %s is already in datastore, skipping upload." % dataset_key) raw_dset_oid = uploaded_file['dataset_oid'] return raw_dset_oid def get_smiles_excape_data(nm_df,targ_lst): """Calculate base rdkit smiles Divides up nm_df based on target and makes one DataFrame for each target. Rows with NaN pXC50 values are dropped. Base rdkit SMILES are calculated from the SMILES column using atomsci.ddm.utils.struct_utils.base_rdkit_smiles_from_smiles. A new column, 'rdkit_smiles, is added to each output DataFrame. Args: nm_df (DataFrame): DataFrame for Excape database. Should contain the columns, pXC50, SMILES, and Ambit_InchiKey targ_lst (list): A list of targets to filter out of nm_df Returns: list, list: A list of DataFrames, one for each target, and a list of all inchi keys used in the dataset. """ # Delete NaN nm_df = nm_df.dropna(subset=['pXC50']) # (Yaru) Use nm_df, which has removed nan's # Don't need to retrieve SMILES, since already in excape file # No filtering by censored save_df={} targ = targ_lst[0] save_df[targ_lst[0]] = nm_df print(targ,"distinct compounds = only",nm_df['Ambit_InchiKey'].nunique()) shared_inchi_keys = nm_df['Ambit_InchiKey'] # Merge in SMILES strings smiles_lst=[] save_df[targ_lst[0]] = nm_df for targ in targ_lst : df=save_df[targ] smiles_df = df #df['PIC50']=df['standard_value'].apply(ic50topic50) #smiles_df=df.merge(save_smiles_df,on='standard_inchi_key',suffixes=('_'+targ,'_')) #the file puts the SMILES string in quotes, which need to be removed #smiles_df['smiles']=smiles_df['smiles'].str.replace('"','') smiles_df['rdkit_smiles']=smiles_df['SMILES'].apply(struct_utils.base_smiles_from_smiles) #smiles_df['smiles']=smiles_df['smiles'].str.replace('"','') print(smiles_df.shape) print(smiles_df['Ambit_InchiKey'].nunique()) smiles_lst.append(smiles_df) return smiles_lst, shared_inchi_keys def upload_df_excape_smiles(dset_name, title, description, tags, functional_area, target, target_type, activity, assay_category,smiles_df,orig_fileID, data_origin='journal', species='human', force_update=False): """Uploads Excape SMILES data to the datastore Upload SMILES to the datastore from the given DataFrame. Returns the datastore OID of the uploaded dataset. The dataset is uploaded to the public bucket and lists https://dx.doi.org/10.1186%2Fs13321-017-0203-5 as the doi. This also assumes that the id_col is 'Original_Entry_ID' Args: dset_name (str): Name of the dataset. Should not include a file extension. title (str): title of the file in (human friendly format) description (str): long text box to describe file (background/use notes) tags (list): Must be a list of strings. functional_area (str): The functional area. target (str): The target. target_type (str): The target type of the dataset. activity (str): The activity of the dataset. assay_category (str): The assay category of the dataset. smiles_df (DataFrame): DataFrame containing SMILES to be uploaded. orig_fileID (str): Source file id used to generate smiles_df. data_origin (str): The origin of the dataset e.g. journal. species (str): The species of the dataset e.g. human, rat, dog. force_update (bool): Overwrite existing datasets in the datastore. Returns: str: datastore OID of the uploaded dataset. """ bucket = 'public' #he6: this used to say _dtc_smiles.csv filename = '%s_excape_smiles.csv' % dset_name dataset_key = 'dskey_' + filename kv = { 'file_category': 'experimental', 'activity': activity, 'assay_category': assay_category, ## seems like this should be called 'kinase_activity' 'assay_endpoint' : 'pic50', 'curation_level': 'raw', 'data_origin' : data_origin, 'functional_area' : functional_area, 'matrix' : 'multiple values', 'journal_doi' : 'https://dx.doi.org/10.1186%2Fs13321-017-0203-5', # ExCAPE-DB 'sample_type' : 'in_vitro', 'species' : species, 'target' : target, 'target_type' : target_type, 'id_col' : 'Original_Entry_ID', 'source_file_id' : orig_fileID } #uploaded_file = dsf.upload_file_to_DS(bucket=bucket, filepath=file_path, filename=filename, title = title, description=description, tags=tags, key_values=kv, client=None, dataset_key=dataset_key, override_check=False, return_metadata=True) ds_client = dsf.config_client() if force_update or not dsf.dataset_key_exists(dataset_key, bucket, ds_client): uploaded_file = dsf.upload_df_to_DS(bucket=bucket, filename=filename,df=smiles_df, title = title, description=description, tags=tags, key_values=kv, client=None, dataset_key=dataset_key, override_check=False, return_metadata=True) #uploaded_file = dsf.upload_file_to_DS(bucket=bucket, filepath=file_path, filename=filename, title = title, description=description, tags=tags, key_values=kv, client=None, dataset_key=dataset_key, override_check=False, return_metadata=True) print("Uploaded raw dataset with key %s" % dataset_key) else: uploaded_file = dsf.retrieve_dataset_by_datasetkey(dataset_key, bucket, ds_client, return_metadata=True) print("Raw dataset %s is already in datastore, skipping upload." % dataset_key) raw_dset_oid = uploaded_file['dataset_oid'] return raw_dset_oid def atom_curation_excape(targ_lst, smiles_lst, shared_inchi_keys): """Apply ATOM standard 'curation' step Apply ATOM standard 'curation' step: Average replicate assays, remove duplicates and drop cases with large variance between replicates. Rows with NaN values in rdkit_smiles, VALUE_NUM_mean, and pXC50 are dropped Args: targ_lst (list): A list of targets. smiles_lst (list): A of DataFrames. These DataFrames must contain the columns gene_names, standard_type, standard_relation, standard_inchi_key, pXC50, and rdkit_smiles shared_inchi_keys (list): A list of inchi keys used in this dataset. Returns: list:A list of curated DataFrames """ imp.reload(curate_data) tolerance=10 column='pXC50'; #'standard_value' list_bad_duplicates='No' max_std=1 curated_lst=[] #print(targ_lst) #print(smiles_lst) for it in range(len(targ_lst)) : data=smiles_lst[it] #data = data[data.standard_relation.str.strip() == '='] #print("gene_names",data.gene_names.unique()) #print("standard_type",data.standard_type.unique()) #print("standard_relation",data.standard_relation.unique()) print("before",data.shape) curated_df=curate_data.average_and_remove_duplicates (column, tolerance, list_bad_duplicates, data, max_std, compound_id='standard_inchi_key',smiles_col='rdkit_smiles') # (Yaru) Remove inf in curated_df curated_df = curated_df[~curated_df.isin([np.inf]).any(1)] # (Yaru) Remove nan on rdkit_smiles curated_df = curated_df.dropna(subset=['rdkit_smiles']) curated_df = curated_df.dropna(subset=['VALUE_NUM_mean']) curated_df = curated_df.dropna(subset=['pXC50']) # (Kevin) # Filter criteria: # pXC50 not missing # rdkit_smiles not blank # pXC50 > 3 #dset_df = dset_df[dset_df.pXC50 >= 3.0] curated_lst.append(curated_df) prev_cmpd_cnt=shared_inchi_keys.nunique() num_dropped=prev_cmpd_cnt-curated_df.shape[0] print("After",curated_df.shape, "# of dropped compounds",num_dropped) return curated_lst def upload_df_excape_mleqonly(dset_name, title, description, tags, functional_area, target, target_type, activity, assay_category,data_df,smiles_fileID, data_origin='journal', species='human', force_update=False): """Uploads Excape mleqonly data to the datastore Upload mleqonly to the datastore from the given DataFrame. Returns the datastore OID of the uploaded dataset. The dataset is uploaded to the public bucket and lists https://dx.doi.org/10.1186%2Fs13321-017-0203-5 as the doi. This also assumes that the id_col is 'Original_Entry_ID', smiles_col is 'rdkit_smiles' and response_col is 'VALUE_NUM_mean'. Args: dset_name (str): Name of the dataset. Should not include a file extension. title (str): title of the file in (human friendly format) description (str): long text box to describe file (background/use notes) tags (list): Must be a list of strings. functional_area (str): The functional area. target (str): The target. target_type (str): The target type of the dataset. activity (str): The activity of the dataset. assay_category (str): The assay category of the dataset. data_df (DataFrame): DataFrame containing SMILES to be uploaded. smiles_fileID (str): Source file id used to generate data_df. data_origin (str): The origin of the dataset e.g. journal. species (str): The species of the dataset e.g. human, rat, dog. force_update (bool): Overwrite existing datasets in the datastore. Returns: str: datastore OID of the uploaded dataset. """ bucket = 'public' #he6: this used to say _dtc_mleqonly.csv filename = '%s_excape_mleqonly.csv' % dset_name dataset_key = 'dskey_' + filename kv = { 'file_category': 'experimental', 'activity': activity, 'assay_category': assay_category, ## seems like this should be called 'kinase_activity' 'assay_endpoint' : 'pic50', 'curation_level': 'ml_ready', 'data_origin' : data_origin, 'functional_area' : functional_area, 'matrix' : 'multiple values', 'journal_doi' : 'https://dx.doi.org/10.1186%2Fs13321-017-0203-5', # ExCAPE-DB 'sample_type' : 'in_vitro', 'species' : species, 'target' : target, 'target_type' : target_type, 'id_col' : 'Original_Entry_ID', 'response_col' : 'VALUE_NUM_mean', 'prediction_type' : 'regression', 'smiles_col' : 'rdkit_smiles', 'units' : 'unitless', 'source_file_id' : smiles_fileID } #uploaded_file = dsf.upload_file_to_DS(bucket=bucket, filepath=file_path, filename=filename, title = title, description=description, tags=tags, key_values=kv, client=None, dataset_key=dataset_key, override_check=False, return_metadata=True) ds_client = dsf.config_client() if force_update or not dsf.dataset_key_exists(dataset_key, bucket, ds_client): uploaded_file = dsf.upload_df_to_DS(bucket=bucket, filename=filename,df=data_df, title = title, description=description, tags=tags, key_values=kv, client=None, dataset_key=dataset_key, override_check=False, return_metadata=True) #uploaded_file = dsf.upload_file_to_DS(bucket=bucket, filepath=file_path, filename=filename, title = title, description=description, tags=tags, key_values=kv, client=None, dataset_key=dataset_key, override_check=False, return_metadata=True) print("Uploaded raw dataset with key %s" % dataset_key) else: uploaded_file = dsf.retrieve_dataset_by_datasetkey(dataset_key, bucket, ds_client, return_metadata=True) print("Raw dataset %s is already in datastore, skipping upload." % dataset_key) raw_dset_oid = uploaded_file['dataset_oid'] return raw_dset_oid def upload_df_excape_mleqonly_class(dset_name, title, description, tags, functional_area, target, target_type, activity, assay_category,data_df,mleqonly_fileID, data_origin='journal', species='human', force_update=False): """Uploads Excape mleqonly classification data to the datastore data_df contains a binary classification dataset with 'active' and 'incative' classes. Upload mleqonly classification to the datastore from the given DataFrame. Returns the datastore OID of the uploaded dataset. The dataset is uploaded to the public bucket and lists https://dx.doi.org/10.1186%2Fs13321-017-0203-5 as the doi. This also assumes that the id_col is 'Original_Entry_ID', smiles_col is 'rdkit_smiles' and response_col is 'binary_class'. Args: dset_name (str): Name of the dataset. Should not include a file extension. title (str): title of the file in (human friendly format) description (str): long text box to describe file (background/use notes) tags (list): Must be a list of strings. functional_area (str): The functional area. target (str): The target. target_type (str): The target type of the dataset. activity (str): The activity of the dataset. assay_category (str): The assay category of the dataset. data_df (DataFrame): DataFrame containing SMILES to be uploaded. mleqonly_fileID (str): Source file id used to generate data_df. data_origin (str): The origin of the dataset e.g. journal. species (str): The species of the dataset e.g. human, rat, dog. force_update (bool): Overwrite existing datasets in the datastore. Returns: str: datastore OID of the uploaded dataset. """ bucket = 'public' #he6: this used to say _dtc_mleqonly.csv filename = '%s_excape_mleqonly_class.csv' % dset_name dataset_key = 'dskey_' + filename kv = { 'file_category': 'experimental', 'activity': activity, 'assay_category': assay_category, ## seems like this should be called 'kinase_activity' 'assay_endpoint' : 'pic50', 'curation_level': 'ml_ready', 'data_origin' : data_origin, 'functional_area' : functional_area, 'matrix' : 'multiple values', 'journal_doi' : 'https://dx.doi.org/10.1186%2Fs13321-017-0203-5', # ExCAPE-DB 'sample_type' : 'in_vitro', 'species' : species, 'target' : target, 'target_type' : target_type, 'id_col' : 'compound_id', 'response_col' : 'binary_class', 'prediction_type' : 'classification', 'num_classes' : 2, 'class_names' : ['inactive','active'], 'smiles_col' : 'rdkit_smiles', 'units' : 'unitless', 'source_file_id' : mleqonly_fileID } #uploaded_file = dsf.upload_file_to_DS(bucket=bucket, filepath=file_path, filename=filename, title = title, description=description, tags=tags, key_values=kv, client=None, dataset_key=dataset_key, override_check=False, return_metadata=True) ds_client = dsf.config_client() if force_update or not dsf.dataset_key_exists(dataset_key, bucket, ds_client): uploaded_file = dsf.upload_df_to_DS(bucket=bucket, filename=filename,df=data_df, title = title, description=description, tags=tags, key_values=kv, client=None, dataset_key=dataset_key, override_check=False, return_metadata=True) #uploaded_file = dsf.upload_file_to_DS(bucket=bucket, filepath=file_path, filename=filename, title = title, description=description, tags=tags, key_values=kv, client=None, dataset_key=dataset_key, override_check=False, return_metadata=True) print("Uploaded raw dataset with key %s" % dataset_key) else: uploaded_file = dsf.retrieve_dataset_by_datasetkey(dataset_key, bucket, ds_client, return_metadata=True) print("Raw dataset %s is already in datastore, skipping upload." % dataset_key) raw_dset_oid = uploaded_file['dataset_oid'] return raw_dset_oid
[ "imp.reload", "atomsci.ddm.utils.datastore_functions.dataset_key_exists", "atomsci.ddm.utils.datastore_functions.upload_df_to_DS", "atomsci.ddm.utils.datastore_functions.retrieve_dataset_by_datasetkey", "atomsci.ddm.utils.datastore_functions.config_client", "atomsci.ddm.utils.curate_data.average_and_remove_duplicates", "atomsci.ddm.utils.datastore_functions.upload_file_to_DS", "numpy.log10", "pandas.concat" ]
[((6452, 6471), 'atomsci.ddm.utils.datastore_functions.config_client', 'dsf.config_client', ([], {}), '()\n', (6469, 6471), True, 'import atomsci.ddm.utils.datastore_functions as dsf\n'), ((11650, 11664), 'pandas.concat', 'pd.concat', (['lst'], {}), '(lst)\n', (11659, 11664), True, 'import pandas as pd\n'), ((14964, 14978), 'pandas.concat', 'pd.concat', (['lst'], {}), '(lst)\n', (14973, 14978), True, 'import pandas as pd\n'), ((18625, 18644), 'atomsci.ddm.utils.datastore_functions.config_client', 'dsf.config_client', ([], {}), '()\n', (18642, 18644), True, 'import atomsci.ddm.utils.datastore_functions as dsf\n'), ((20383, 20406), 'imp.reload', 'imp.reload', (['curate_data'], {}), '(curate_data)\n', (20393, 20406), False, 'import atomsci.ddm.utils.curate_data as curate_data, imp\n'), ((24637, 24656), 'atomsci.ddm.utils.datastore_functions.config_client', 'dsf.config_client', ([], {}), '()\n', (24654, 24656), True, 'import atomsci.ddm.utils.datastore_functions as dsf\n'), ((28558, 28577), 'atomsci.ddm.utils.datastore_functions.config_client', 'dsf.config_client', ([], {}), '()\n', (28575, 28577), True, 'import atomsci.ddm.utils.datastore_functions as dsf\n'), ((31940, 31959), 'atomsci.ddm.utils.datastore_functions.config_client', 'dsf.config_client', ([], {}), '()\n', (31957, 31959), True, 'import atomsci.ddm.utils.datastore_functions as dsf\n'), ((35557, 35576), 'atomsci.ddm.utils.datastore_functions.config_client', 'dsf.config_client', ([], {}), '()\n', (35574, 35576), True, 'import atomsci.ddm.utils.datastore_functions as dsf\n'), ((39610, 39629), 'atomsci.ddm.utils.datastore_functions.config_client', 'dsf.config_client', ([], {}), '()\n', (39627, 39629), True, 'import atomsci.ddm.utils.datastore_functions as dsf\n'), ((43347, 43366), 'atomsci.ddm.utils.datastore_functions.config_client', 'dsf.config_client', ([], {}), '()\n', (43364, 43366), True, 'import atomsci.ddm.utils.datastore_functions as dsf\n'), ((49100, 49119), 'atomsci.ddm.utils.datastore_functions.config_client', 'dsf.config_client', ([], {}), '()\n', (49117, 49119), True, 'import atomsci.ddm.utils.datastore_functions as dsf\n'), ((50787, 50810), 'imp.reload', 'imp.reload', (['curate_data'], {}), '(curate_data)\n', (50797, 50810), False, 'import atomsci.ddm.utils.curate_data as curate_data, imp\n'), ((55183, 55202), 'atomsci.ddm.utils.datastore_functions.config_client', 'dsf.config_client', ([], {}), '()\n', (55200, 55202), True, 'import atomsci.ddm.utils.datastore_functions as dsf\n'), ((59312, 59331), 'atomsci.ddm.utils.datastore_functions.config_client', 'dsf.config_client', ([], {}), '()\n', (59329, 59331), True, 'import atomsci.ddm.utils.datastore_functions as dsf\n'), ((6925, 7155), 'atomsci.ddm.utils.datastore_functions.upload_file_to_DS', 'dsf.upload_file_to_DS', ([], {'bucket': 'bucket', 'filepath': 'file_path', 'filename': 'filename', 'title': 'title', 'description': 'description', 'tags': 'tags', 'key_values': 'kv', 'client': 'None', 'dataset_key': 'dataset_key', 'override_check': '(False)', 'return_metadata': '(True)'}), '(bucket=bucket, filepath=file_path, filename=filename,\n title=title, description=description, tags=tags, key_values=kv, client=\n None, dataset_key=dataset_key, override_check=False, return_metadata=True)\n', (6946, 7155), True, 'import atomsci.ddm.utils.datastore_functions as dsf\n'), ((7272, 7364), 'atomsci.ddm.utils.datastore_functions.retrieve_dataset_by_datasetkey', 'dsf.retrieve_dataset_by_datasetkey', (['dataset_key', 'bucket', 'ds_client'], {'return_metadata': '(True)'}), '(dataset_key, bucket, ds_client,\n return_metadata=True)\n', (7306, 7364), True, 'import atomsci.ddm.utils.datastore_functions as dsf\n'), ((9128, 9154), 'numpy.log10', 'np.log10', (['(x / 1000000000.0)'], {}), '(x / 1000000000.0)\n', (9136, 9154), True, 'import numpy as np\n'), ((18752, 18974), 'atomsci.ddm.utils.datastore_functions.upload_df_to_DS', 'dsf.upload_df_to_DS', ([], {'bucket': 'bucket', 'filename': 'filename', 'df': 'smiles_df', 'title': 'title', 'description': 'description', 'tags': 'tags', 'key_values': 'kv', 'client': 'None', 'dataset_key': 'dataset_key', 'override_check': '(False)', 'return_metadata': '(True)'}), '(bucket=bucket, filename=filename, df=smiles_df, title=\n title, description=description, tags=tags, key_values=kv, client=None,\n dataset_key=dataset_key, override_check=False, return_metadata=True)\n', (18771, 18974), True, 'import atomsci.ddm.utils.datastore_functions as dsf\n'), ((19323, 19415), 'atomsci.ddm.utils.datastore_functions.retrieve_dataset_by_datasetkey', 'dsf.retrieve_dataset_by_datasetkey', (['dataset_key', 'bucket', 'ds_client'], {'return_metadata': '(True)'}), '(dataset_key, bucket, ds_client,\n return_metadata=True)\n', (19357, 19415), True, 'import atomsci.ddm.utils.datastore_functions as dsf\n'), ((20931, 21096), 'atomsci.ddm.utils.curate_data.average_and_remove_duplicates', 'curate_data.average_and_remove_duplicates', (['column', 'tolerance', 'list_bad_duplicates', 'data', 'max_std'], {'compound_id': '"""standard_inchi_key"""', 'smiles_col': '"""rdkit_smiles"""'}), "(column, tolerance,\n list_bad_duplicates, data, max_std, compound_id='standard_inchi_key',\n smiles_col='rdkit_smiles')\n", (20972, 21096), True, 'import atomsci.ddm.utils.curate_data as curate_data, imp\n'), ((24764, 24984), 'atomsci.ddm.utils.datastore_functions.upload_df_to_DS', 'dsf.upload_df_to_DS', ([], {'bucket': 'bucket', 'filename': 'filename', 'df': 'data_df', 'title': 'title', 'description': 'description', 'tags': 'tags', 'key_values': 'kv', 'client': 'None', 'dataset_key': 'dataset_key', 'override_check': '(False)', 'return_metadata': '(True)'}), '(bucket=bucket, filename=filename, df=data_df, title=\n title, description=description, tags=tags, key_values=kv, client=None,\n dataset_key=dataset_key, override_check=False, return_metadata=True)\n', (24783, 24984), True, 'import atomsci.ddm.utils.datastore_functions as dsf\n'), ((25334, 25426), 'atomsci.ddm.utils.datastore_functions.retrieve_dataset_by_datasetkey', 'dsf.retrieve_dataset_by_datasetkey', (['dataset_key', 'bucket', 'ds_client'], {'return_metadata': '(True)'}), '(dataset_key, bucket, ds_client,\n return_metadata=True)\n', (25368, 25426), True, 'import atomsci.ddm.utils.datastore_functions as dsf\n'), ((28685, 28905), 'atomsci.ddm.utils.datastore_functions.upload_df_to_DS', 'dsf.upload_df_to_DS', ([], {'bucket': 'bucket', 'filename': 'filename', 'df': 'data_df', 'title': 'title', 'description': 'description', 'tags': 'tags', 'key_values': 'kv', 'client': 'None', 'dataset_key': 'dataset_key', 'override_check': '(False)', 'return_metadata': '(True)'}), '(bucket=bucket, filename=filename, df=data_df, title=\n title, description=description, tags=tags, key_values=kv, client=None,\n dataset_key=dataset_key, override_check=False, return_metadata=True)\n', (28704, 28905), True, 'import atomsci.ddm.utils.datastore_functions as dsf\n'), ((28997, 29089), 'atomsci.ddm.utils.datastore_functions.retrieve_dataset_by_datasetkey', 'dsf.retrieve_dataset_by_datasetkey', (['dataset_key', 'bucket', 'ds_client'], {'return_metadata': '(True)'}), '(dataset_key, bucket, ds_client,\n return_metadata=True)\n', (29031, 29089), True, 'import atomsci.ddm.utils.datastore_functions as dsf\n'), ((32067, 32287), 'atomsci.ddm.utils.datastore_functions.upload_df_to_DS', 'dsf.upload_df_to_DS', ([], {'bucket': 'bucket', 'filename': 'filename', 'df': 'data_df', 'title': 'title', 'description': 'description', 'tags': 'tags', 'key_values': 'kv', 'client': 'None', 'dataset_key': 'dataset_key', 'override_check': '(False)', 'return_metadata': '(True)'}), '(bucket=bucket, filename=filename, df=data_df, title=\n title, description=description, tags=tags, key_values=kv, client=None,\n dataset_key=dataset_key, override_check=False, return_metadata=True)\n', (32086, 32287), True, 'import atomsci.ddm.utils.datastore_functions as dsf\n'), ((32379, 32471), 'atomsci.ddm.utils.datastore_functions.retrieve_dataset_by_datasetkey', 'dsf.retrieve_dataset_by_datasetkey', (['dataset_key', 'bucket', 'ds_client'], {'return_metadata': '(True)'}), '(dataset_key, bucket, ds_client,\n return_metadata=True)\n', (32413, 32471), True, 'import atomsci.ddm.utils.datastore_functions as dsf\n'), ((35923, 36153), 'atomsci.ddm.utils.datastore_functions.upload_file_to_DS', 'dsf.upload_file_to_DS', ([], {'bucket': 'bucket', 'filepath': 'file_path', 'filename': 'filename', 'title': 'title', 'description': 'description', 'tags': 'tags', 'key_values': 'kv', 'client': 'None', 'dataset_key': 'dataset_key', 'override_check': '(False)', 'return_metadata': '(True)'}), '(bucket=bucket, filepath=file_path, filename=filename,\n title=title, description=description, tags=tags, key_values=kv, client=\n None, dataset_key=dataset_key, override_check=False, return_metadata=True)\n', (35944, 36153), True, 'import atomsci.ddm.utils.datastore_functions as dsf\n'), ((36254, 36346), 'atomsci.ddm.utils.datastore_functions.retrieve_dataset_by_datasetkey', 'dsf.retrieve_dataset_by_datasetkey', (['dataset_key', 'bucket', 'ds_client'], {'return_metadata': '(True)'}), '(dataset_key, bucket, ds_client,\n return_metadata=True)\n', (36288, 36346), True, 'import atomsci.ddm.utils.datastore_functions as dsf\n'), ((39737, 39957), 'atomsci.ddm.utils.datastore_functions.upload_df_to_DS', 'dsf.upload_df_to_DS', ([], {'bucket': 'bucket', 'filename': 'filename', 'df': 'data_df', 'title': 'title', 'description': 'description', 'tags': 'tags', 'key_values': 'kv', 'client': 'None', 'dataset_key': 'dataset_key', 'override_check': '(False)', 'return_metadata': '(True)'}), '(bucket=bucket, filename=filename, df=data_df, title=\n title, description=description, tags=tags, key_values=kv, client=None,\n dataset_key=dataset_key, override_check=False, return_metadata=True)\n', (39756, 39957), True, 'import atomsci.ddm.utils.datastore_functions as dsf\n'), ((40307, 40399), 'atomsci.ddm.utils.datastore_functions.retrieve_dataset_by_datasetkey', 'dsf.retrieve_dataset_by_datasetkey', (['dataset_key', 'bucket', 'ds_client'], {'return_metadata': '(True)'}), '(dataset_key, bucket, ds_client,\n return_metadata=True)\n', (40341, 40399), True, 'import atomsci.ddm.utils.datastore_functions as dsf\n'), ((43820, 44050), 'atomsci.ddm.utils.datastore_functions.upload_file_to_DS', 'dsf.upload_file_to_DS', ([], {'bucket': 'bucket', 'filepath': 'file_path', 'filename': 'filename', 'title': 'title', 'description': 'description', 'tags': 'tags', 'key_values': 'kv', 'client': 'None', 'dataset_key': 'dataset_key', 'override_check': '(False)', 'return_metadata': '(True)'}), '(bucket=bucket, filepath=file_path, filename=filename,\n title=title, description=description, tags=tags, key_values=kv, client=\n None, dataset_key=dataset_key, override_check=False, return_metadata=True)\n', (43841, 44050), True, 'import atomsci.ddm.utils.datastore_functions as dsf\n'), ((44151, 44243), 'atomsci.ddm.utils.datastore_functions.retrieve_dataset_by_datasetkey', 'dsf.retrieve_dataset_by_datasetkey', (['dataset_key', 'bucket', 'ds_client'], {'return_metadata': '(True)'}), '(dataset_key, bucket, ds_client,\n return_metadata=True)\n', (44185, 44243), True, 'import atomsci.ddm.utils.datastore_functions as dsf\n'), ((49227, 49449), 'atomsci.ddm.utils.datastore_functions.upload_df_to_DS', 'dsf.upload_df_to_DS', ([], {'bucket': 'bucket', 'filename': 'filename', 'df': 'smiles_df', 'title': 'title', 'description': 'description', 'tags': 'tags', 'key_values': 'kv', 'client': 'None', 'dataset_key': 'dataset_key', 'override_check': '(False)', 'return_metadata': '(True)'}), '(bucket=bucket, filename=filename, df=smiles_df, title=\n title, description=description, tags=tags, key_values=kv, client=None,\n dataset_key=dataset_key, override_check=False, return_metadata=True)\n', (49246, 49449), True, 'import atomsci.ddm.utils.datastore_functions as dsf\n'), ((49798, 49890), 'atomsci.ddm.utils.datastore_functions.retrieve_dataset_by_datasetkey', 'dsf.retrieve_dataset_by_datasetkey', (['dataset_key', 'bucket', 'ds_client'], {'return_metadata': '(True)'}), '(dataset_key, bucket, ds_client,\n return_metadata=True)\n', (49832, 49890), True, 'import atomsci.ddm.utils.datastore_functions as dsf\n'), ((51316, 51481), 'atomsci.ddm.utils.curate_data.average_and_remove_duplicates', 'curate_data.average_and_remove_duplicates', (['column', 'tolerance', 'list_bad_duplicates', 'data', 'max_std'], {'compound_id': '"""standard_inchi_key"""', 'smiles_col': '"""rdkit_smiles"""'}), "(column, tolerance,\n list_bad_duplicates, data, max_std, compound_id='standard_inchi_key',\n smiles_col='rdkit_smiles')\n", (51357, 51481), True, 'import atomsci.ddm.utils.curate_data as curate_data, imp\n'), ((55310, 55530), 'atomsci.ddm.utils.datastore_functions.upload_df_to_DS', 'dsf.upload_df_to_DS', ([], {'bucket': 'bucket', 'filename': 'filename', 'df': 'data_df', 'title': 'title', 'description': 'description', 'tags': 'tags', 'key_values': 'kv', 'client': 'None', 'dataset_key': 'dataset_key', 'override_check': '(False)', 'return_metadata': '(True)'}), '(bucket=bucket, filename=filename, df=data_df, title=\n title, description=description, tags=tags, key_values=kv, client=None,\n dataset_key=dataset_key, override_check=False, return_metadata=True)\n', (55329, 55530), True, 'import atomsci.ddm.utils.datastore_functions as dsf\n'), ((55880, 55972), 'atomsci.ddm.utils.datastore_functions.retrieve_dataset_by_datasetkey', 'dsf.retrieve_dataset_by_datasetkey', (['dataset_key', 'bucket', 'ds_client'], {'return_metadata': '(True)'}), '(dataset_key, bucket, ds_client,\n return_metadata=True)\n', (55914, 55972), True, 'import atomsci.ddm.utils.datastore_functions as dsf\n'), ((59439, 59659), 'atomsci.ddm.utils.datastore_functions.upload_df_to_DS', 'dsf.upload_df_to_DS', ([], {'bucket': 'bucket', 'filename': 'filename', 'df': 'data_df', 'title': 'title', 'description': 'description', 'tags': 'tags', 'key_values': 'kv', 'client': 'None', 'dataset_key': 'dataset_key', 'override_check': '(False)', 'return_metadata': '(True)'}), '(bucket=bucket, filename=filename, df=data_df, title=\n title, description=description, tags=tags, key_values=kv, client=None,\n dataset_key=dataset_key, override_check=False, return_metadata=True)\n', (59458, 59659), True, 'import atomsci.ddm.utils.datastore_functions as dsf\n'), ((60009, 60101), 'atomsci.ddm.utils.datastore_functions.retrieve_dataset_by_datasetkey', 'dsf.retrieve_dataset_by_datasetkey', (['dataset_key', 'bucket', 'ds_client'], {'return_metadata': '(True)'}), '(dataset_key, bucket, ds_client,\n return_metadata=True)\n', (60043, 60101), True, 'import atomsci.ddm.utils.datastore_functions as dsf\n'), ((6499, 6553), 'atomsci.ddm.utils.datastore_functions.dataset_key_exists', 'dsf.dataset_key_exists', (['dataset_key', 'bucket', 'ds_client'], {}), '(dataset_key, bucket, ds_client)\n', (6521, 6553), True, 'import atomsci.ddm.utils.datastore_functions as dsf\n'), ((18672, 18726), 'atomsci.ddm.utils.datastore_functions.dataset_key_exists', 'dsf.dataset_key_exists', (['dataset_key', 'bucket', 'ds_client'], {}), '(dataset_key, bucket, ds_client)\n', (18694, 18726), True, 'import atomsci.ddm.utils.datastore_functions as dsf\n'), ((24684, 24738), 'atomsci.ddm.utils.datastore_functions.dataset_key_exists', 'dsf.dataset_key_exists', (['dataset_key', 'bucket', 'ds_client'], {}), '(dataset_key, bucket, ds_client)\n', (24706, 24738), True, 'import atomsci.ddm.utils.datastore_functions as dsf\n'), ((28605, 28659), 'atomsci.ddm.utils.datastore_functions.dataset_key_exists', 'dsf.dataset_key_exists', (['dataset_key', 'bucket', 'ds_client'], {}), '(dataset_key, bucket, ds_client)\n', (28627, 28659), True, 'import atomsci.ddm.utils.datastore_functions as dsf\n'), ((31987, 32041), 'atomsci.ddm.utils.datastore_functions.dataset_key_exists', 'dsf.dataset_key_exists', (['dataset_key', 'bucket', 'ds_client'], {}), '(dataset_key, bucket, ds_client)\n', (32009, 32041), True, 'import atomsci.ddm.utils.datastore_functions as dsf\n'), ((35604, 35658), 'atomsci.ddm.utils.datastore_functions.dataset_key_exists', 'dsf.dataset_key_exists', (['dataset_key', 'bucket', 'ds_client'], {}), '(dataset_key, bucket, ds_client)\n', (35626, 35658), True, 'import atomsci.ddm.utils.datastore_functions as dsf\n'), ((39657, 39711), 'atomsci.ddm.utils.datastore_functions.dataset_key_exists', 'dsf.dataset_key_exists', (['dataset_key', 'bucket', 'ds_client'], {}), '(dataset_key, bucket, ds_client)\n', (39679, 39711), True, 'import atomsci.ddm.utils.datastore_functions as dsf\n'), ((43394, 43448), 'atomsci.ddm.utils.datastore_functions.dataset_key_exists', 'dsf.dataset_key_exists', (['dataset_key', 'bucket', 'ds_client'], {}), '(dataset_key, bucket, ds_client)\n', (43416, 43448), True, 'import atomsci.ddm.utils.datastore_functions as dsf\n'), ((49147, 49201), 'atomsci.ddm.utils.datastore_functions.dataset_key_exists', 'dsf.dataset_key_exists', (['dataset_key', 'bucket', 'ds_client'], {}), '(dataset_key, bucket, ds_client)\n', (49169, 49201), True, 'import atomsci.ddm.utils.datastore_functions as dsf\n'), ((55230, 55284), 'atomsci.ddm.utils.datastore_functions.dataset_key_exists', 'dsf.dataset_key_exists', (['dataset_key', 'bucket', 'ds_client'], {}), '(dataset_key, bucket, ds_client)\n', (55252, 55284), True, 'import atomsci.ddm.utils.datastore_functions as dsf\n'), ((59359, 59413), 'atomsci.ddm.utils.datastore_functions.dataset_key_exists', 'dsf.dataset_key_exists', (['dataset_key', 'bucket', 'ds_client'], {}), '(dataset_key, bucket, ds_client)\n', (59381, 59413), True, 'import atomsci.ddm.utils.datastore_functions as dsf\n')]
# Licensed under an MIT style license -- see LICENSE.md import numpy as np import os from pesummary.core.file.formats.base_read import ( Read, SingleAnalysisRead, MultiAnalysisRead ) __author__ = ["<NAME> <<EMAIL>>"] class SingleAnalysisDefault(SingleAnalysisRead): """Class to handle result files which only contain a single analysis Parameters ---------- path_to_results_file: str path to the results file you wish to load Attributes ---------- parameters: list list of parameters stored in the result file samples: 2d list list of samples stored in the result file samples_dict: dict dictionary of samples stored in the result file keyed by parameters input_version: str version of the result file passed. extra_kwargs: dict dictionary of kwargs that were extracted from the result file injection_parameters: dict dictionary of injection parameters extracted from the result file pe_algorithm: str name of the algorithm used to generate the posterior samples Methods ------- to_dat: save the posterior samples to a .dat file to_latex_table: convert the posterior samples to a latex table generate_latex_macros: generate a set of latex macros for the stored posterior samples """ def __init__(self, *args, _data=None, **kwargs): super(SingleAnalysisDefault, self).__init__(*args, **kwargs) if _data is not None: self.load(None, _data=_data, **kwargs) class MultiAnalysisDefault(MultiAnalysisRead): """Class to handle result files which contain multiple analyses Parameters ---------- path_to_results_file: str path to the results file you wish to load Attributes ---------- parameters: 2d list list of parameters stored in the result file for each analyses samples: 2d list list of samples stored in the result file for each analyses samples_dict: dict dictionary of samples stored in the result file keyed by analysis label input_version: str version of the result file passed. extra_kwargs: dict dictionary of kwargs that were extracted from the result file injection_parameters: dict dictionary of injection parameters extracted from the result file Methods ------- to_dat: save the posterior samples to a .dat file to_latex_table: convert the posterior samples to a latex table generate_latex_macros: generate a set of latex macros for the stored posterior samples """ def __init__(self, *args, _data=None, **kwargs): super(MultiAnalysisDefault, self).__init__(*args, **kwargs) if _data is not None: self.load(None, _data=_data, **kwargs) class Default(object): """Class to handle the default loading options. Attributes ---------- path_to_results_file: str path to the results file you wish to load Attributes ---------- parameters: list list of parameters stored in the result file samples: 2d list list of samples stored in the result file samples_dict: dict dictionary of samples stored in the result file keyed by parameters input_version: str version of the result file passed. extra_kwargs: dict dictionary of kwargs that were extracted from the result file injection_parameters: dict dictionary of injection parameters extracted from the result file Methods ------- to_dat: save the posterior samples to a .dat file to_latex_table: convert the posterior samples to a latex table generate_latex_macros: generate a set of latex macros for the stored posterior samples """ def load_map(self): return { "json": self._grab_data_from_json_file, "dat": self._grab_data_from_dat_file, "txt": self._grab_data_from_dat_file, "csv": self._grab_data_from_csv_file, "hdf5": self._grab_data_from_hdf5_file, "h5": self._grab_data_from_hdf5_file, "hdf": self._grab_data_from_hdf5_file, "db": self._grab_data_from_sql_database, "sql": self._grab_data_from_sql_database, "prior": self._grab_data_from_prior_file, "npy": self._grab_data_from_numpy_file } def __new__( self, path_to_results_file, _single_default=SingleAnalysisDefault, _multi_default=MultiAnalysisDefault, **kwargs ): self.module = "core" self.extension = Read.extension_from_path(path_to_results_file) self.load_function = self.load_map(self)[self.extension] try: self._load_data = self.load_function(path_to_results_file, **kwargs) except Exception as e: raise Exception( "Failed to read data for file %s because: %s" % ( path_to_results_file, e ) ) if np.array(self._load_data["parameters"]).ndim > 1: return _multi_default( path_to_results_file, _data=self._load_data, **kwargs ) else: return _single_default( path_to_results_file, _data=self._load_data, **kwargs ) @classmethod def load_file(cls, path, **kwargs): if not os.path.isfile(path): raise FileNotFoundError("%s does not exist" % (path)) return cls(path, **kwargs) @staticmethod def _default_injection(parameters): """Return a dictionary of nan's for each parameter Parameters ---------- parameters: tuple/list list of parameters you wish to have null injections for """ return {i: float("nan") for i in parameters} @staticmethod def _grab_data_from_dat_file(path, **kwargs): """Grab the data stored in a .dat file """ from pesummary.core.file.formats.dat import read_dat parameters, samples = read_dat(path) return { "parameters": parameters, "samples": samples, "injection": Default._default_injection(parameters) } @staticmethod def _grab_data_from_numpy_file(path, **kwargs): """Grab the data stored in a .npy file """ from pesummary.core.file.formats.numpy import read_numpy parameters, samples = read_numpy(path) return { "parameters": parameters, "samples": samples, "injection": Default._default_injection(parameters) } @staticmethod def _grab_data_from_csv_file(path, **kwargs): """Grab the data stored in a .csv file """ from pesummary.core.file.formats.csv import read_csv parameters, samples = read_csv(path) return { "parameters": parameters, "samples": samples, "injection": Default._default_injection(parameters) } @staticmethod def _grab_data_from_prior_file(path, module="core", **kwargs): """Grab the data stored in a .prior file """ import importlib module = importlib.import_module( "pesummary.{}.file.formats.bilby".format(module) ) func = getattr(module, "prior_samples_from_file") samples = func(path, **kwargs) parameters = samples.parameters analytic = samples.analytic return { "parameters": parameters, "samples": samples.samples.T.tolist(), "injection": Default._default_injection(parameters), "analytic": analytic } @staticmethod def _grab_data_from_sql_database(path, **kwargs): """Grab the data stored in a sql database """ from pesummary.core.file.formats.sql import read_sql parameters, samples, labels = read_sql(path, **kwargs) if len(labels) > 1: injection = { label: Default._default_injection(parameters[num]) for num, label in enumerate(labels) } else: injection = Default._default_injection(parameters) return { "parameters": parameters, "samples": samples, "injection": injection, "labels": labels } @staticmethod def _grab_data_from_json_file(path, path_to_samples=None, **kwargs): """Grab the data stored in a .json file """ from pesummary.core.file.formats.json import read_json parameters, samples = read_json(path, path_to_samples=path_to_samples) return { "parameters": parameters, "samples": samples, "injection": Default._default_injection(parameters) } @staticmethod def _grab_data_from_hdf5_file( path, remove_params=[], path_to_samples=None, **kwargs ): """Grab the data stored in an hdf5 file """ from pesummary.core.file.formats.hdf5 import read_hdf5 parameters, samples = read_hdf5( path, remove_params=remove_params, path_to_samples=path_to_samples ) return { "parameters": parameters, "samples": samples, "injection": Default._default_injection(parameters) } def add_marginalized_parameters_from_config_file(self, config_file): """Search the configuration file and add the marginalized parameters to the list of parameters and samples Parameters ---------- config_file: str path to the configuration file """ pass
[ "pesummary.core.file.formats.csv.read_csv", "pesummary.core.file.formats.numpy.read_numpy", "pesummary.core.file.formats.sql.read_sql", "pesummary.core.file.formats.hdf5.read_hdf5", "os.path.isfile", "numpy.array", "pesummary.core.file.formats.base_read.Read.extension_from_path", "pesummary.core.file.formats.json.read_json", "pesummary.core.file.formats.dat.read_dat" ]
[((4663, 4709), 'pesummary.core.file.formats.base_read.Read.extension_from_path', 'Read.extension_from_path', (['path_to_results_file'], {}), '(path_to_results_file)\n', (4687, 4709), False, 'from pesummary.core.file.formats.base_read import Read, SingleAnalysisRead, MultiAnalysisRead\n'), ((6122, 6136), 'pesummary.core.file.formats.dat.read_dat', 'read_dat', (['path'], {}), '(path)\n', (6130, 6136), False, 'from pesummary.core.file.formats.dat import read_dat\n'), ((6512, 6528), 'pesummary.core.file.formats.numpy.read_numpy', 'read_numpy', (['path'], {}), '(path)\n', (6522, 6528), False, 'from pesummary.core.file.formats.numpy import read_numpy\n'), ((6898, 6912), 'pesummary.core.file.formats.csv.read_csv', 'read_csv', (['path'], {}), '(path)\n', (6906, 6912), False, 'from pesummary.core.file.formats.csv import read_csv\n'), ((7959, 7983), 'pesummary.core.file.formats.sql.read_sql', 'read_sql', (['path'], {}), '(path, **kwargs)\n', (7967, 7983), False, 'from pesummary.core.file.formats.sql import read_sql\n'), ((8632, 8680), 'pesummary.core.file.formats.json.read_json', 'read_json', (['path'], {'path_to_samples': 'path_to_samples'}), '(path, path_to_samples=path_to_samples)\n', (8641, 8680), False, 'from pesummary.core.file.formats.json import read_json\n'), ((9108, 9185), 'pesummary.core.file.formats.hdf5.read_hdf5', 'read_hdf5', (['path'], {'remove_params': 'remove_params', 'path_to_samples': 'path_to_samples'}), '(path, remove_params=remove_params, path_to_samples=path_to_samples)\n', (9117, 9185), False, 'from pesummary.core.file.formats.hdf5 import read_hdf5\n'), ((5458, 5478), 'os.path.isfile', 'os.path.isfile', (['path'], {}), '(path)\n', (5472, 5478), False, 'import os\n'), ((5082, 5121), 'numpy.array', 'np.array', (["self._load_data['parameters']"], {}), "(self._load_data['parameters'])\n", (5090, 5121), True, 'import numpy as np\n')]
# Copyright 2021 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import time import sys, os sys.path.append(os.path.dirname(os.path.dirname(sys.path[0]))) sys.path.insert(0,'third_party') sys.path.insert(0,'./') import torch import torch.nn as nn from torch.autograd import Variable from ext_utils.badja_data import BADJAData from ext_utils.joint_catalog import SMALJointInfo import ext_utils.flowlib as flowlib import matplotlib.pyplot as plt import numpy as np import torch import cv2 import pdb import soft_renderer as sr import argparse import trimesh from nnutils.geom_utils import obj_to_cam, pinhole_cam, orthographic_cam, render_flow_soft_3 parser = argparse.ArgumentParser(description='BADJA') parser.add_argument('--testdir', default='', help='path to test dir') parser.add_argument('--seqname', default='camel', help='sequence to test') parser.add_argument('--type', default='mesh', help='load mesh data or flow or zero') parser.add_argument('--cam_type', default='perspective', help='camera model, orthographic or perspective') parser.add_argument('--vis', dest='vis', action='store_true', help='whether to draw visualization') args = parser.parse_args() renderer_softflf = sr.SoftRenderer(image_size=256,dist_func='hard' ,aggr_func_alpha='hard', camera_mode='look_at',perspective=False, aggr_func_rgb='hard', light_mode='vertex', light_intensity_ambient=1.,light_intensity_directionals=0.) def process_flow(model, imgL_o,imgR_o, mean_L, mean_R): testres=1 # for gray input images if len(imgL_o.shape) == 2: imgL_o = np.tile(imgL_o[:,:,np.newaxis],(1,1,3)) imgR_o = np.tile(imgR_o[:,:,np.newaxis],(1,1,3)) # resize maxh = imgL_o.shape[0]*testres maxw = imgL_o.shape[1]*testres max_h = int(maxh // 64 * 64) max_w = int(maxw // 64 * 64) if max_h < maxh: max_h += 64 if max_w < maxw: max_w += 64 input_size = imgL_o.shape imgL = cv2.resize(imgL_o,(max_w, max_h)) imgR = cv2.resize(imgR_o,(max_w, max_h)) imgL_noaug = torch.Tensor(imgL/255.)[np.newaxis].float().cuda() # flip channel, subtract mean imgL = imgL[:,:,::-1].copy() / 255. - np.asarray(mean_L).mean(0)[np.newaxis,np.newaxis,:] imgR = imgR[:,:,::-1].copy() / 255. - np.asarray(mean_R).mean(0)[np.newaxis,np.newaxis,:] imgL = np.transpose(imgL, [2,0,1])[np.newaxis] imgR = np.transpose(imgR, [2,0,1])[np.newaxis] # modify module according to inputs from models.VCN_exp import WarpModule, flow_reg for i in range(len(model.module.reg_modules)): model.module.reg_modules[i] = flow_reg([1,max_w//(2**(6-i)), max_h//(2**(6-i))], ent=getattr(model.module, 'flow_reg%d'%2**(6-i)).ent,\ maxdisp=getattr(model.module, 'flow_reg%d'%2**(6-i)).md,\ fac=getattr(model.module, 'flow_reg%d'%2**(6-i)).fac).cuda() for i in range(len(model.module.warp_modules)): model.module.warp_modules[i] = WarpModule([1,max_w//(2**(6-i)), max_h//(2**(6-i))]).cuda() # get intrinsics intr_list = [torch.Tensor(inxx).cuda() for inxx in [[1],[1],[1],[1],[1],[0],[0],[1],[0],[0]]] fl_next = 1 intr_list.append(torch.Tensor([fl_next]).cuda()) disc_aux = [None,None,None,intr_list,imgL_noaug,None] # forward imgL = Variable(torch.FloatTensor(imgL).cuda()) imgR = Variable(torch.FloatTensor(imgR).cuda()) with torch.no_grad(): imgLR = torch.cat([imgL,imgR],0) model.eval() torch.cuda.synchronize() start_time = time.time() rts = model(imgLR, disc_aux) torch.cuda.synchronize() ttime = (time.time() - start_time); print('time = %.2f' % (ttime*1000) ) flow, logmid, occ, biseg, objseg = rts # upsampling flow = torch.squeeze(flow).data.cpu().numpy() flow = np.concatenate( [cv2.resize(flow[0],(input_size[1],input_size[0]))[:,:,np.newaxis], cv2.resize(flow[1],(input_size[1],input_size[0]))[:,:,np.newaxis]],-1) flow[:,:,0] *= imgL_o.shape[1] / max_w flow[:,:,1] *= imgL_o.shape[0] / max_h flow = np.concatenate( (flow, np.ones([flow.shape[0],flow.shape[1],1])),-1) torch.cuda.empty_cache() flow = torch.Tensor(flow).cuda()[None] return flow def preprocess_image(img,mask,imgsize): if len(img.shape) == 2: img = np.repeat(np.expand_dims(img, 2), 3, axis=2) mask = mask[:,:,:1] # crop box indices = np.where(mask>0); xid = indices[1]; yid = indices[0] center = ( (xid.max()+xid.min())//2, (yid.max()+yid.min())//2) length = ( (xid.max()-xid.min())//2, (yid.max()-yid.min())//2) maxlength = int(1.2*max(length)) length = (maxlength,maxlength) alp = 2*length[0]/float(imgsize) refpp = np.asarray(center)/(imgsize/2.) - 1 return alp, refpp,center,length[0] def draw_joints_on_image(rgb_img, joints, visibility, region_colors, marker_types,pred=None,correct=None): joints = joints[:, ::-1] # OpenCV works in (x, y) rather than (i, j) disp_img = rgb_img.copy() i=0 for joint_coord, visible, color, marker_type in zip(joints, visibility, region_colors, marker_types): if visible: joint_coord = joint_coord.astype(int) cv2.circle(disp_img, tuple(joint_coord), radius=3, color=[255,0,0], thickness = 10) if pred is not None: if correct[i]: color=[0,255,0] else: color=[0,0,255] error = np.linalg.norm(joint_coord - pred[i,::-1],2,-1) cv2.circle(disp_img, tuple(joint_coord), radius=int(error), color=color, thickness = 3) cv2.line(disp_img, tuple(joint_coord), tuple(pred[i,::-1]),color , thickness = 3) i+=1 return disp_img def main(): smal_joint_info = SMALJointInfo() badja_data = BADJAData(args.seqname) data_loader = badja_data.get_loader() print(args.testdir) # store all the data all_anno = [] all_mesh = [] all_cam = [] all_fr = [] all_fl = [] #import pdb; pdb.set_trace() for anno in data_loader: all_anno.append(anno) rgb_img, sil_img, joints, visible, name = anno seqname = name.split('/')[-2] fr = int(name.split('/')[-1].split('.')[-2]) all_fr.append(fr) print('%s/%d'%(seqname, fr)) # load mesh data or flow if args.type=='mesh': mesh = trimesh.load('%s/pred%d.ply'%(args.testdir, fr),process=False) all_mesh.append(mesh) cam = np.loadtxt('%s/cam%d.txt'%(args.testdir,fr)) all_cam.append(cam) if args.type=='flow': from models.VCN_exp import VCN model = VCN([1, 256, 256], md=[int(4*(256/256)),4,4,4,4], fac=1) model = nn.DataParallel(model, device_ids=[0]) model.cuda() pretrained_dict = torch.load('/data/gengshay/vcn_weights/robexp.pth',map_location='cpu') mean_L=pretrained_dict['mean_L'] mean_R=pretrained_dict['mean_R'] model.load_state_dict(pretrained_dict['state_dict'],strict=False) # store all the results pck_all = [] for i in range(len(all_anno)): for j in range(len(all_anno)): if i!=j: # evaluate every two-frame refimg, refsil, refkp, refvis, refname = all_anno[i] tarimg, tarsil, tarkp, tarvis, tarname = all_anno[j] print('%s vs %s'%(refname, tarname)) if args.type=='mesh': refmesh, tarmesh = all_mesh[i], all_mesh[j] refcam, tarcam = all_cam[i], all_cam[j] img_size = max(refimg.shape) renderer_softflf.rasterizer.image_size = img_size # render flow between mesh 1 and 2 refface = torch.Tensor(refmesh.faces[None]).cuda() verts = torch.Tensor(np.concatenate([refmesh.vertices[None], tarmesh.vertices[None]],0)).cuda() Rmat = torch.Tensor(np.concatenate([refcam[None,:3,:3], tarcam[None,:3,:3]], 0)).cuda() Tmat = torch.Tensor(np.concatenate([refcam[None,:3,3], tarcam[None,:3,3]], 0)).cuda() ppoint = torch.Tensor(np.concatenate([refcam[None,3,2:], tarcam[None,3,2:]], 0)).cuda() scale = torch.Tensor(np.concatenate([refcam[None,3,:1], tarcam[None,3,:1]], 0)).cuda() scale = scale/img_size*2 ppoint = ppoint/img_size * 2 -1 verts_fl = obj_to_cam(verts, Rmat, Tmat[:,None],nmesh=1,n_hypo=1,skin=None) verts_fl = torch.cat([verts_fl,torch.ones_like(verts_fl[:, :, 0:1])], dim=-1) verts_pos = verts_fl.clone() verts_fl = pinhole_cam(verts_fl, ppoint, scale) flow_fw, bgmask_fw, fgmask_flowf = render_flow_soft_3(renderer_softflf, verts_fl[:1], verts_fl[1:], refface) flow_fw[bgmask_fw]=0. flow_fw = torch.cat([flow_fw, torch.zeros_like(flow_fw)[:,:,:,:1]],-1)[:,:refimg.shape[0],:refimg.shape[1]] elif args.type=='flow': flow_fw = process_flow(model, refimg, tarimg, mean_L, mean_R) flow_fw = (flow_fw)/(refimg.shape[0]/2.) elif args.type=='zero': flow_fw = torch.zeros(refimg.shape).cuda()[None] refkpx = torch.Tensor(refkp.astype(float)).cuda() x0,y0=np.meshgrid(range(refimg.shape[1]),range(refimg.shape[0])) x0 = torch.Tensor(x0).cuda() y0 = torch.Tensor(y0).cuda() idx = ( (flow_fw[:,:,:,:2].norm(2,-1)<1e-6).float().view(1,-1)*1e6+ torch.pow(refkpx[:,0:1]-y0.view(1,-1),2) + torch.pow(refkpx[:,1:2]-x0.view(1,-1),2)).argmin(-1) samp_flow = flow_fw.view(-1,3)[idx][:,:2] tarkp_pred = refkpx.clone() tarkp_pred[:,0] = tarkp_pred[:,0] +(samp_flow[:,1])*refimg.shape[0]/2 tarkp_pred[:,1] = tarkp_pred[:,1] +(samp_flow[:,0])*refimg.shape[1]/2 tarkp_pred = np.asarray(tarkp_pred.cpu()) diff = np.linalg.norm(tarkp_pred - tarkp, 2,-1) sqarea = np.sqrt((refsil[:,:,0]>0).sum()) correct = diff < sqarea * 0.2 correct = correct[np.logical_and(tarvis, refvis)] if args.vis: rgb_vis = draw_joints_on_image(refimg, refkp, refvis, smal_joint_info.joint_colors, smal_joint_info.annotated_markers) tarimg = draw_joints_on_image(tarimg, tarkp, tarvis, smal_joint_info.joint_colors, smal_joint_info.annotated_markers, pred=tarkp_pred,correct=diff < sqarea * 0.2) cv2.addWeighted(rgb_vis, 0.5, flowlib.flow_to_image(np.asarray(flow_fw[0].clamp(-1,1).detach().cpu())), 0.5,0.0,rgb_vis) cv2.imwrite('%s/%05d-%05d-flo.png'%(args.testdir,all_fr[i],all_fr[j]),rgb_vis[:,:,::-1]) cv2.imwrite('%s/%05d-%05d.png'%(args.testdir,all_fr[i],all_fr[j]),tarimg[:,:,::-1]) pck_all.append(correct) print('PCK %.02f'%(100*np.concatenate(pck_all).astype(float).mean())) if __name__ == '__main__': main()
[ "torch.cuda.synchronize", "trimesh.load", "argparse.ArgumentParser", "torch.cat", "numpy.ones", "numpy.linalg.norm", "numpy.tile", "torch.no_grad", "soft_renderer.SoftRenderer", "cv2.imwrite", "ext_utils.joint_catalog.SMALJointInfo", "os.path.dirname", "numpy.transpose", "torch.load", "torch.FloatTensor", "torch.squeeze", "torch.Tensor", "numpy.loadtxt", "torch.zeros", "cv2.resize", "models.VCN_exp.WarpModule", "torch.zeros_like", "numpy.asarray", "ext_utils.badja_data.BADJAData", "nnutils.geom_utils.render_flow_soft_3", "nnutils.geom_utils.pinhole_cam", "nnutils.geom_utils.obj_to_cam", "numpy.concatenate", "torch.ones_like", "numpy.logical_and", "sys.path.insert", "numpy.expand_dims", "time.time", "numpy.where", "torch.cuda.empty_cache", "torch.nn.DataParallel" ]
[((669, 702), 'sys.path.insert', 'sys.path.insert', (['(0)', '"""third_party"""'], {}), "(0, 'third_party')\n", (684, 702), False, 'import sys, os\n'), ((702, 726), 'sys.path.insert', 'sys.path.insert', (['(0)', '"""./"""'], {}), "(0, './')\n", (717, 726), False, 'import sys, os\n'), ((1174, 1218), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""BADJA"""'}), "(description='BADJA')\n", (1197, 1218), False, 'import argparse\n'), ((1803, 2036), 'soft_renderer.SoftRenderer', 'sr.SoftRenderer', ([], {'image_size': '(256)', 'dist_func': '"""hard"""', 'aggr_func_alpha': '"""hard"""', 'camera_mode': '"""look_at"""', 'perspective': '(False)', 'aggr_func_rgb': '"""hard"""', 'light_mode': '"""vertex"""', 'light_intensity_ambient': '(1.0)', 'light_intensity_directionals': '(0.0)'}), "(image_size=256, dist_func='hard', aggr_func_alpha='hard',\n camera_mode='look_at', perspective=False, aggr_func_rgb='hard',\n light_mode='vertex', light_intensity_ambient=1.0,\n light_intensity_directionals=0.0)\n", (1818, 2036), True, 'import soft_renderer as sr\n'), ((2553, 2587), 'cv2.resize', 'cv2.resize', (['imgL_o', '(max_w, max_h)'], {}), '(imgL_o, (max_w, max_h))\n', (2563, 2587), False, 'import cv2\n'), ((2598, 2632), 'cv2.resize', 'cv2.resize', (['imgR_o', '(max_w, max_h)'], {}), '(imgR_o, (max_w, max_h))\n', (2608, 2632), False, 'import cv2\n'), ((4815, 4839), 'torch.cuda.empty_cache', 'torch.cuda.empty_cache', ([], {}), '()\n', (4837, 4839), False, 'import torch\n'), ((5081, 5099), 'numpy.where', 'np.where', (['(mask > 0)'], {}), '(mask > 0)\n', (5089, 5099), True, 'import numpy as np\n'), ((6463, 6478), 'ext_utils.joint_catalog.SMALJointInfo', 'SMALJointInfo', ([], {}), '()\n', (6476, 6478), False, 'from ext_utils.joint_catalog import SMALJointInfo\n'), ((6496, 6519), 'ext_utils.badja_data.BADJAData', 'BADJAData', (['args.seqname'], {}), '(args.seqname)\n', (6505, 6519), False, 'from ext_utils.badja_data import BADJAData\n'), ((638, 666), 'os.path.dirname', 'os.path.dirname', (['sys.path[0]'], {}), '(sys.path[0])\n', (653, 666), False, 'import sys, os\n'), ((2198, 2242), 'numpy.tile', 'np.tile', (['imgL_o[:, :, np.newaxis]', '(1, 1, 3)'], {}), '(imgL_o[:, :, np.newaxis], (1, 1, 3))\n', (2205, 2242), True, 'import numpy as np\n'), ((2255, 2299), 'numpy.tile', 'np.tile', (['imgR_o[:, :, np.newaxis]', '(1, 1, 3)'], {}), '(imgR_o[:, :, np.newaxis], (1, 1, 3))\n', (2262, 2299), True, 'import numpy as np\n'), ((2934, 2963), 'numpy.transpose', 'np.transpose', (['imgL', '[2, 0, 1]'], {}), '(imgL, [2, 0, 1])\n', (2946, 2963), True, 'import numpy as np\n'), ((2985, 3014), 'numpy.transpose', 'np.transpose', (['imgR', '[2, 0, 1]'], {}), '(imgR, [2, 0, 1])\n', (2997, 3014), True, 'import numpy as np\n'), ((4040, 4055), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (4053, 4055), False, 'import torch\n'), ((4073, 4099), 'torch.cat', 'torch.cat', (['[imgL, imgR]', '(0)'], {}), '([imgL, imgR], 0)\n', (4082, 4099), False, 'import torch\n'), ((4127, 4151), 'torch.cuda.synchronize', 'torch.cuda.synchronize', ([], {}), '()\n', (4149, 4151), False, 'import torch\n'), ((4173, 4184), 'time.time', 'time.time', ([], {}), '()\n', (4182, 4184), False, 'import time\n'), ((4230, 4254), 'torch.cuda.synchronize', 'torch.cuda.synchronize', ([], {}), '()\n', (4252, 4254), False, 'import torch\n'), ((7446, 7484), 'torch.nn.DataParallel', 'nn.DataParallel', (['model'], {'device_ids': '[0]'}), '(model, device_ids=[0])\n', (7461, 7484), True, 'import torch.nn as nn\n'), ((7532, 7603), 'torch.load', 'torch.load', (['"""/data/gengshay/vcn_weights/robexp.pth"""'], {'map_location': '"""cpu"""'}), "('/data/gengshay/vcn_weights/robexp.pth', map_location='cpu')\n", (7542, 7603), False, 'import torch\n'), ((4272, 4283), 'time.time', 'time.time', ([], {}), '()\n', (4281, 4283), False, 'import time\n'), ((4765, 4807), 'numpy.ones', 'np.ones', (['[flow.shape[0], flow.shape[1], 1]'], {}), '([flow.shape[0], flow.shape[1], 1])\n', (4772, 4807), True, 'import numpy as np\n'), ((4993, 5015), 'numpy.expand_dims', 'np.expand_dims', (['img', '(2)'], {}), '(img, 2)\n', (5007, 5015), True, 'import numpy as np\n'), ((5390, 5408), 'numpy.asarray', 'np.asarray', (['center'], {}), '(center)\n', (5400, 5408), True, 'import numpy as np\n'), ((7093, 7158), 'trimesh.load', 'trimesh.load', (["('%s/pred%d.ply' % (args.testdir, fr))"], {'process': '(False)'}), "('%s/pred%d.ply' % (args.testdir, fr), process=False)\n", (7105, 7158), False, 'import trimesh\n'), ((7208, 7255), 'numpy.loadtxt', 'np.loadtxt', (["('%s/cam%d.txt' % (args.testdir, fr))"], {}), "('%s/cam%d.txt' % (args.testdir, fr))\n", (7218, 7255), True, 'import numpy as np\n'), ((3596, 3657), 'models.VCN_exp.WarpModule', 'WarpModule', (['[1, max_w // 2 ** (6 - i), max_h // 2 ** (6 - i)]'], {}), '([1, max_w // 2 ** (6 - i), max_h // 2 ** (6 - i)])\n', (3606, 3657), False, 'from models.VCN_exp import WarpModule, flow_reg\n'), ((3695, 3713), 'torch.Tensor', 'torch.Tensor', (['inxx'], {}), '(inxx)\n', (3707, 3713), False, 'import torch\n'), ((3813, 3836), 'torch.Tensor', 'torch.Tensor', (['[fl_next]'], {}), '([fl_next])\n', (3825, 3836), False, 'import torch\n'), ((3947, 3970), 'torch.FloatTensor', 'torch.FloatTensor', (['imgL'], {}), '(imgL)\n', (3964, 3970), False, 'import torch\n'), ((3999, 4022), 'torch.FloatTensor', 'torch.FloatTensor', (['imgR'], {}), '(imgR)\n', (4016, 4022), False, 'import torch\n'), ((4479, 4530), 'cv2.resize', 'cv2.resize', (['flow[0]', '(input_size[1], input_size[0])'], {}), '(flow[0], (input_size[1], input_size[0]))\n', (4489, 4530), False, 'import cv2\n'), ((4574, 4625), 'cv2.resize', 'cv2.resize', (['flow[1]', '(input_size[1], input_size[0])'], {}), '(flow[1], (input_size[1], input_size[0]))\n', (4584, 4625), False, 'import cv2\n'), ((4852, 4870), 'torch.Tensor', 'torch.Tensor', (['flow'], {}), '(flow)\n', (4864, 4870), False, 'import torch\n'), ((6144, 6194), 'numpy.linalg.norm', 'np.linalg.norm', (['(joint_coord - pred[i, ::-1])', '(2)', '(-1)'], {}), '(joint_coord - pred[i, ::-1], 2, -1)\n', (6158, 6194), True, 'import numpy as np\n'), ((10931, 10972), 'numpy.linalg.norm', 'np.linalg.norm', (['(tarkp_pred - tarkp)', '(2)', '(-1)'], {}), '(tarkp_pred - tarkp, 2, -1)\n', (10945, 10972), True, 'import numpy as np\n'), ((2777, 2795), 'numpy.asarray', 'np.asarray', (['mean_L'], {}), '(mean_L)\n', (2787, 2795), True, 'import numpy as np\n'), ((2871, 2889), 'numpy.asarray', 'np.asarray', (['mean_R'], {}), '(mean_R)\n', (2881, 2889), True, 'import numpy as np\n'), ((9266, 9334), 'nnutils.geom_utils.obj_to_cam', 'obj_to_cam', (['verts', 'Rmat', 'Tmat[:, None]'], {'nmesh': '(1)', 'n_hypo': '(1)', 'skin': 'None'}), '(verts, Rmat, Tmat[:, None], nmesh=1, n_hypo=1, skin=None)\n', (9276, 9334), False, 'from nnutils.geom_utils import obj_to_cam, pinhole_cam, orthographic_cam, render_flow_soft_3\n'), ((9530, 9566), 'nnutils.geom_utils.pinhole_cam', 'pinhole_cam', (['verts_fl', 'ppoint', 'scale'], {}), '(verts_fl, ppoint, scale)\n', (9541, 9566), False, 'from nnutils.geom_utils import obj_to_cam, pinhole_cam, orthographic_cam, render_flow_soft_3\n'), ((9622, 9695), 'nnutils.geom_utils.render_flow_soft_3', 'render_flow_soft_3', (['renderer_softflf', 'verts_fl[:1]', 'verts_fl[1:]', 'refface'], {}), '(renderer_softflf, verts_fl[:1], verts_fl[1:], refface)\n', (9640, 9695), False, 'from nnutils.geom_utils import obj_to_cam, pinhole_cam, orthographic_cam, render_flow_soft_3\n'), ((11110, 11140), 'numpy.logical_and', 'np.logical_and', (['tarvis', 'refvis'], {}), '(tarvis, refvis)\n', (11124, 11140), True, 'import numpy as np\n'), ((11654, 11753), 'cv2.imwrite', 'cv2.imwrite', (["('%s/%05d-%05d-flo.png' % (args.testdir, all_fr[i], all_fr[j]))", 'rgb_vis[:, :, ::-1]'], {}), "('%s/%05d-%05d-flo.png' % (args.testdir, all_fr[i], all_fr[j]),\n rgb_vis[:, :, ::-1])\n", (11665, 11753), False, 'import cv2\n'), ((11764, 11858), 'cv2.imwrite', 'cv2.imwrite', (["('%s/%05d-%05d.png' % (args.testdir, all_fr[i], all_fr[j]))", 'tarimg[:, :, ::-1]'], {}), "('%s/%05d-%05d.png' % (args.testdir, all_fr[i], all_fr[j]),\n tarimg[:, :, ::-1])\n", (11775, 11858), False, 'import cv2\n'), ((2649, 2675), 'torch.Tensor', 'torch.Tensor', (['(imgL / 255.0)'], {}), '(imgL / 255.0)\n', (2661, 2675), False, 'import torch\n'), ((4412, 4431), 'torch.squeeze', 'torch.squeeze', (['flow'], {}), '(flow)\n', (4425, 4431), False, 'import torch\n'), ((10326, 10342), 'torch.Tensor', 'torch.Tensor', (['x0'], {}), '(x0)\n', (10338, 10342), False, 'import torch\n'), ((10371, 10387), 'torch.Tensor', 'torch.Tensor', (['y0'], {}), '(y0)\n', (10383, 10387), False, 'import torch\n'), ((8548, 8581), 'torch.Tensor', 'torch.Tensor', (['refmesh.faces[None]'], {}), '(refmesh.faces[None])\n', (8560, 8581), False, 'import torch\n'), ((9382, 9418), 'torch.ones_like', 'torch.ones_like', (['verts_fl[:, :, 0:1]'], {}), '(verts_fl[:, :, 0:1])\n', (9397, 9418), False, 'import torch\n'), ((8630, 8697), 'numpy.concatenate', 'np.concatenate', (['[refmesh.vertices[None], tarmesh.vertices[None]]', '(0)'], {}), '([refmesh.vertices[None], tarmesh.vertices[None]], 0)\n', (8644, 8697), True, 'import numpy as np\n'), ((8746, 8809), 'numpy.concatenate', 'np.concatenate', (['[refcam[None, :3, :3], tarcam[None, :3, :3]]', '(0)'], {}), '([refcam[None, :3, :3], tarcam[None, :3, :3]], 0)\n', (8760, 8809), True, 'import numpy as np\n'), ((8855, 8916), 'numpy.concatenate', 'np.concatenate', (['[refcam[None, :3, 3], tarcam[None, :3, 3]]', '(0)'], {}), '([refcam[None, :3, 3], tarcam[None, :3, 3]], 0)\n', (8869, 8916), True, 'import numpy as np\n'), ((8964, 9025), 'numpy.concatenate', 'np.concatenate', (['[refcam[None, 3, 2:], tarcam[None, 3, 2:]]', '(0)'], {}), '([refcam[None, 3, 2:], tarcam[None, 3, 2:]], 0)\n', (8978, 9025), True, 'import numpy as np\n'), ((9072, 9133), 'numpy.concatenate', 'np.concatenate', (['[refcam[None, 3, :1], tarcam[None, 3, :1]]', '(0)'], {}), '([refcam[None, 3, :1], tarcam[None, 3, :1]], 0)\n', (9086, 9133), True, 'import numpy as np\n'), ((11937, 11960), 'numpy.concatenate', 'np.concatenate', (['pck_all'], {}), '(pck_all)\n', (11951, 11960), True, 'import numpy as np\n'), ((9788, 9813), 'torch.zeros_like', 'torch.zeros_like', (['flow_fw'], {}), '(flow_fw)\n', (9804, 9813), False, 'import torch\n'), ((10119, 10144), 'torch.zeros', 'torch.zeros', (['refimg.shape'], {}), '(refimg.shape)\n', (10130, 10144), False, 'import torch\n')]
import unittest import numpy as np class TestCase(unittest.TestCase): def test_approx_k(self): try: from task import k, U, Sigma, Vt, approx approx_test = U @ Sigma[:, :k] @ Vt[:k, :] np.testing.assert_array_equal(approx, approx_test, 'The approximation does not look right.') except ValueError: self.fail('You have to use only the first k columns of Sigma and the first k rows of Vt')
[ "numpy.testing.assert_array_equal" ]
[((235, 331), 'numpy.testing.assert_array_equal', 'np.testing.assert_array_equal', (['approx', 'approx_test', '"""The approximation does not look right."""'], {}), "(approx, approx_test,\n 'The approximation does not look right.')\n", (264, 331), True, 'import numpy as np\n')]
import numpy as np # Adapted from https://github.com/Hakuyume/chainer-ssd def decode_onnx(loc, priors, variances): """Decode locations from predictions using priors to undo the encoding we did for offset regression at train time. Args: loc (tensor): location predictions for loc layers, Shape: [num_priors,4] priors (tensor): Prior boxes in center-offset form. Shape: [num_priors,4]. variances: (list[float]) Variances of priorboxes Return: decoded bounding box predictions """ before_prior = priors[:, :2] after_prior = priors[:, 2:] print(priors[0]) print(loc[0]) before_loc = loc[:, :2] after_loc = loc[:, 2:] boxes = np.concatenate(( before_prior + before_loc * variances[0] * after_prior, after_prior * np.exp(after_loc * variances[1])), axis = 1) boxes[:, :2] -= boxes[:, 2:] / 2 boxes[:, 2:] += boxes[:, :2] print(boxes[0]) return boxes def decode_landm_onnx(pre, priors, variances): """Decode landm from predictions using priors to undo the encoding we did for offset regression at train time. Args: pre (tensor): landm predictions for loc layers, Shape: [num_priors,10] priors (tensor): Prior boxes in center-offset form. Shape: [num_priors,4]. variances: (list[float]) Variances of priorboxes Return: decoded landm predictions """ landms = np.concatenate((priors[:, :2] + pre[:, :2] * variances[0] * priors[:, 2:], priors[:, :2] + pre[:, 2:4] * variances[0] * priors[:, 2:], priors[:, :2] + pre[:, 4:6] * variances[0] * priors[:, 2:], priors[:, :2] + pre[:, 6:8] * variances[0] * priors[:, 2:], priors[:, :2] + pre[:, 8:10] * variances[0] * priors[:, 2:], ), axis=1) return landms
[ "numpy.exp", "numpy.concatenate" ]
[((1494, 1836), 'numpy.concatenate', 'np.concatenate', (['(priors[:, :2] + pre[:, :2] * variances[0] * priors[:, 2:], priors[:, :2] +\n pre[:, 2:4] * variances[0] * priors[:, 2:], priors[:, :2] + pre[:, 4:6] *\n variances[0] * priors[:, 2:], priors[:, :2] + pre[:, 6:8] * variances[0\n ] * priors[:, 2:], priors[:, :2] + pre[:, 8:10] * variances[0] * priors\n [:, 2:])'], {'axis': '(1)'}), '((priors[:, :2] + pre[:, :2] * variances[0] * priors[:, 2:], \n priors[:, :2] + pre[:, 2:4] * variances[0] * priors[:, 2:], priors[:, :\n 2] + pre[:, 4:6] * variances[0] * priors[:, 2:], priors[:, :2] + pre[:,\n 6:8] * variances[0] * priors[:, 2:], priors[:, :2] + pre[:, 8:10] *\n variances[0] * priors[:, 2:]), axis=1)\n', (1508, 1836), True, 'import numpy as np\n'), ((845, 877), 'numpy.exp', 'np.exp', (['(after_loc * variances[1])'], {}), '(after_loc * variances[1])\n', (851, 877), True, 'import numpy as np\n')]
#-*-coding:utf-8-*- # date:2020-03-28 # Author: X.L.Eric # function: image pixel - float (0.~1.) import cv2 # 加载 OpenCV 库 import numpy as np # 加载 numpy 库 if __name__ == "__main__": img_h = 480 img_w = 640 img = np.zeros([img_h,img_w], dtype = np.float) cv2.namedWindow('image_0', 1) cv2.imshow('image_0', img) cv2.waitKey(0) img.fill(0.5) cv2.namedWindow('image_05', 1) cv2.imshow('image_05', img) cv2.waitKey(0) img.fill(1.) cv2.namedWindow('image_1', 1) cv2.imshow('image_1', img) cv2.waitKey(0)
[ "cv2.waitKey", "cv2.imshow", "numpy.zeros", "cv2.namedWindow" ]
[((224, 264), 'numpy.zeros', 'np.zeros', (['[img_h, img_w]'], {'dtype': 'np.float'}), '([img_h, img_w], dtype=np.float)\n', (232, 264), True, 'import numpy as np\n'), ((271, 300), 'cv2.namedWindow', 'cv2.namedWindow', (['"""image_0"""', '(1)'], {}), "('image_0', 1)\n", (286, 300), False, 'import cv2\n'), ((305, 331), 'cv2.imshow', 'cv2.imshow', (['"""image_0"""', 'img'], {}), "('image_0', img)\n", (315, 331), False, 'import cv2\n'), ((336, 350), 'cv2.waitKey', 'cv2.waitKey', (['(0)'], {}), '(0)\n', (347, 350), False, 'import cv2\n'), ((374, 404), 'cv2.namedWindow', 'cv2.namedWindow', (['"""image_05"""', '(1)'], {}), "('image_05', 1)\n", (389, 404), False, 'import cv2\n'), ((409, 436), 'cv2.imshow', 'cv2.imshow', (['"""image_05"""', 'img'], {}), "('image_05', img)\n", (419, 436), False, 'import cv2\n'), ((441, 455), 'cv2.waitKey', 'cv2.waitKey', (['(0)'], {}), '(0)\n', (452, 455), False, 'import cv2\n'), ((478, 507), 'cv2.namedWindow', 'cv2.namedWindow', (['"""image_1"""', '(1)'], {}), "('image_1', 1)\n", (493, 507), False, 'import cv2\n'), ((512, 538), 'cv2.imshow', 'cv2.imshow', (['"""image_1"""', 'img'], {}), "('image_1', img)\n", (522, 538), False, 'import cv2\n'), ((543, 557), 'cv2.waitKey', 'cv2.waitKey', (['(0)'], {}), '(0)\n', (554, 557), False, 'import cv2\n')]
import numpy as np import matplotlib.pyplot as plt class House(): def __init__(self, K: float=0.5, C: float=0.3, Qhvac: float=9, hvacON: float=0, occupancy: float=1, Tin_initial: float=30): self.K = K # thermal conductivity self.C = C # thermal capacity self.Tin = Tin_initial # Inside Temperature self.Qhvac = Qhvac # Cooling capacity self.hvacON = hvacON # control action = 0 (OFF) or 1 (ON) self.occupancy = occupancy # 0 (no one in the room) or 1 (somebody in the room) self.Phvac = Qhvac # Electric power capacity plt.close() self.fig, self.ax = plt.subplots(1, 1) def setup_schedule(self, days: int=1, timestep: int=5, schedule_index: int=2, max_iterations: int=288): """ define the Tset_schedule, Tout_schedule, the length of schedule, timestep """ self.timestep = timestep # keep in minutes here to keep number of minutes for days consistent self.max_iterations = max_iterations #10 more steps incase we need to use forecast # randomize if schedule_index == 1: self.Tset_schedule = np.full(self.max_iterations, 25) self.Tout_schedule = np.full(self.max_iterations, 32) self.occupancy_schedule = np.full(self.max_iterations, 1) for d in range(days): a = time_to_index(d, 9) b = time_to_index(d, 17) self.Tset_schedule[a:b]= np.random.randint(low=18, high=25) c = time_to_index(d, 0) d = time_to_index(d, 24) self.Tout_schedule[c:d] = np.random.randint(low=28, high=35) # simpler if schedule_index == 2: self.Tset_schedule = np.full(self.max_iterations, 25) self.Tset_schedule[96:204] = 20 self.Tout_schedule = np.full(self.max_iterations, 32) self.occupancy_schedule = np.full(self.max_iterations, 1) self.Tset = self.Tset_schedule[0] # Set Temperature self.Tout = self.Tout_schedule[0] # Outside temperature self.Tset1 = self.Tset_schedule[1] # Set Temperature i+1 self.Tset2 = self.Tset_schedule[2] # Set Temperature i+2 self.Tset3 = self.Tset_schedule[3] # Set Temperature i+3 # For plotting only self.time_to_plot = [0] self.Tin_to_plot = [self.Tin] self.Tset_to_plot = [self.Tset] self.__iter__() def update_Tout(self, Tout_new): self.Tout = Tout_new # Update to new outside temperature def update_Tset(self, Tset_new): self.Tset = Tset_new # Update to new setpoint temperature def update_hvacON(self, hvacONnew): self.hvacON = hvacONnew # update to new hvacON def update_occupancy(self, occupancy_new): self.occupancy = occupancy_new # update to new occupancy def update_Tin(self): """Update inside temperation. Describes the inside temperature evolution as a function of all other variables. """ # Note timestep is converted to seconds here, in order to keep units consistent in SI for update. self.Tin = self.Tin - (self.timestep/60) / self.C * (self.K * (self.Tin - self.Tout) + self.Qhvac * self.hvacON) self.__next__() self.Tset_to_plot.append(self.Tset) self.Tin_to_plot.append(self.Tin) self.time_to_plot.append(self.iteration * 5) def get_Power(self): COP = 3 Power = self.Phvac * self.hvacON * COP return Power def show(self): self.ax.clear() self.ax.plot(self.time_to_plot, self.Tin_to_plot, label='Tin') self.ax.plot(self.time_to_plot, self.Tset_to_plot, label='Tset') self.ax.set_xlabel('Time [min]') self.ax.set_ylabel(r'Temperature [$^\circ$C]') plt.legend() plt.pause(np.finfo(np.float32).eps) # print the object nicely def __str__(self): string_to_print = [] for key in self.__dict__: string_to_print.append("{key}='{value}'".format(key=key, value=self.__dict__[key])) return ', '.join(string_to_print) def __repr__(self): return self.__str__() def __iter__(self): self.iteration = 0 return self def __next__(self): if self.iteration <= self.max_iterations - 5: self.iteration += 1 self.update_Tset(self.Tset_schedule[self.iteration]) self.Tset1 = self.Tset_schedule[self.iteration+1] self.Tset2 = self.Tset_schedule[self.iteration+2] self.Tset3 = self.Tset_schedule[self.iteration+3] self.update_Tout(self.Tout_schedule[self.iteration]) self.update_occupancy(self.occupancy_schedule[self.iteration]) else: StopIteration def time_to_index(days, hours, timestep=5): hours_index = int(hours * 60 / timestep) days_index = int(days * 24 * 60 / timestep) return hours_index + days_index if __name__ == '__main__': import random house = House() for episode in range(2): house.setup_schedule(days=1, timestep=5, schedule_index=2, max_iterations= 288) for i in range(288): house.update_hvacON(random.randint(0, 1)) house.update_Tin() print('Tin : {}'.format(house.Tin)) house.show()
[ "numpy.full", "random.randint", "matplotlib.pyplot.close", "matplotlib.pyplot.legend", "numpy.finfo", "numpy.random.randint", "matplotlib.pyplot.subplots" ]
[((592, 603), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (601, 603), True, 'import matplotlib.pyplot as plt\n'), ((632, 650), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(1)', '(1)'], {}), '(1, 1)\n', (644, 650), True, 'import matplotlib.pyplot as plt\n'), ((3837, 3849), 'matplotlib.pyplot.legend', 'plt.legend', ([], {}), '()\n', (3847, 3849), True, 'import matplotlib.pyplot as plt\n'), ((1137, 1169), 'numpy.full', 'np.full', (['self.max_iterations', '(25)'], {}), '(self.max_iterations, 25)\n', (1144, 1169), True, 'import numpy as np\n'), ((1203, 1235), 'numpy.full', 'np.full', (['self.max_iterations', '(32)'], {}), '(self.max_iterations, 32)\n', (1210, 1235), True, 'import numpy as np\n'), ((1274, 1305), 'numpy.full', 'np.full', (['self.max_iterations', '(1)'], {}), '(self.max_iterations, 1)\n', (1281, 1305), True, 'import numpy as np\n'), ((1738, 1770), 'numpy.full', 'np.full', (['self.max_iterations', '(25)'], {}), '(self.max_iterations, 25)\n', (1745, 1770), True, 'import numpy as np\n'), ((1848, 1880), 'numpy.full', 'np.full', (['self.max_iterations', '(32)'], {}), '(self.max_iterations, 32)\n', (1855, 1880), True, 'import numpy as np\n'), ((1919, 1950), 'numpy.full', 'np.full', (['self.max_iterations', '(1)'], {}), '(self.max_iterations, 1)\n', (1926, 1950), True, 'import numpy as np\n'), ((1462, 1496), 'numpy.random.randint', 'np.random.randint', ([], {'low': '(18)', 'high': '(25)'}), '(low=18, high=25)\n', (1479, 1496), True, 'import numpy as np\n'), ((1620, 1654), 'numpy.random.randint', 'np.random.randint', ([], {'low': '(28)', 'high': '(35)'}), '(low=28, high=35)\n', (1637, 1654), True, 'import numpy as np\n'), ((3868, 3888), 'numpy.finfo', 'np.finfo', (['np.float32'], {}), '(np.float32)\n', (3876, 3888), True, 'import numpy as np\n'), ((5346, 5366), 'random.randint', 'random.randint', (['(0)', '(1)'], {}), '(0, 1)\n', (5360, 5366), False, 'import random\n')]
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ @author: <NAME> """ #0. SET PARAMETERS ###Path to directory with models (one or several models to be tested) model_dir = '' ###DIRECTORY WITH IMAGES #Tumor base_dir_tu = '' #Benign base_dir_norm = '' ###OUTPUT DIRECTORY FOR RESULT FILES result_dir = '' ### #1. IMPORT LIBRARIES from keras.models import load_model import os from keras.preprocessing import image import numpy as np from PIL import Image, ImageOps import staintools from statistics import median #2. GENERATE LISTS AND NAMES ###GENERATE LIST OF MODELS (if several models are tested) model_names = sorted(os.listdir(model_dir)) ###MODEL PATCH SIZES: define the patch size to use within models #here for example two models in list, each working with 350px patches m_p_s_list = [350, 350] #3. INITIALIZE STAIN NORMALIZER #Standartization image st = staintools.read_image('standard_he_stain_small.jpg') #Inititate Brightness Standardizer standardizer = staintools.BrightnessStandardizer() #Inititate StainNormalizer "macenko" stain_norm = staintools.StainNormalizer(method='macenko') #Read Hematoxylin/Eosin staining schema from Standartization image stain_norm.fit(st) #4. FUNCTIONS #Implementation of the Strategy C8 (derivates of the main image, s. Methods) #as a function #As input: native version of the patch def gateway_median (patch): #native version of the patch (base) base = patch #1 #rotation derivates r90 = patch.rotate(90) #2 r180 = patch.rotate(180) #3 r270 = patch.rotate(270) #4 #flip/rotation derivates r90_VF = ImageOps.flip(r90) #5 r270_VF = ImageOps.flip(r270) #6 #flip derivates VF = ImageOps.flip(base) #7 HF = base.transpose(Image.FLIP_LEFT_RIGHT) #8 #calculate final predictions from predictions of individual derivates #pred() function refers to the generation of predictions for classes by model 1 #Tumor vs benign tissue #Median to generate final predictions pred_stack = np.vstack((pred(base),pred(r90),pred(r180),pred(r270),pred(r90_VF),pred(r270_VF),pred(VF),pred(HF))) pred_1 = median(pred_stack[0:8,0]) pred_2 = median(pred_stack[0:8,1]) pred_3 = median(pred_stack[0:8,2]) preds_med = np.array([pred_1, pred_2, pred_3]) #returns final predictions return preds_med #Function for generation of prediction for single patches (used in C8) def pred (patch): #IMAGE TO ARRAY, PREPROCESSING patch = image.img_to_array(patch) patch = np.expand_dims(patch, axis = 0) patch /= 255. #prediction from model preds = model.predict(patch) #return predictions return preds #Loop for analysis of patches from validation dataset with "tumor" label #as function def processor_tu (m_p_s): #define work directory work_dir = base_dir_tu #define output containers o_C1 = output_tu_C1 o_C8 = output_tu_C8 #read names from the directory fnames = sorted(os.listdir(work_dir)) #Analysis loop for fname in fnames: filename = os.path.join(work_dir, fname) im = image.load_img(filename) #preprocessing of the image im = im.resize((m_p_s,m_p_s), Image.ANTIALIAS) im = np.array(im) #stain normalization im = standardizer.transform(im) im = stain_norm.transform(im) #for eventual further C8 analysis im_sn = Image.fromarray(im) im = np.float32(im) x = image.img_to_array(im) x = np.expand_dims(x, axis = 0) x /= 255. #prediction preds = model.predict(x) #pred gland pr_1 = str(round(preds[0,0],3)) #pred non-gland pr_2 = str(round(preds[0,1],3)) #pred tumor pr_3 = str(round(preds[0,2],3)) #Output of C1 (analysis of naative version of the patch) output = fname + "\t" + pr_1 + "\t" + pr_2 + "\t" + pr_3 + "\n" #Write down output of C1 results = open (o_C1, "a+") results.write(output) results.close() #Additional analysis using C8 strategy (see Methods) if prediction #probability for tumor class in the gray zone 0.2-0.5 if preds[0,2] < 0.5: #Enter C8 pipeline if preds[0,2] > 0.2: print(fname, " was misclassified, but trying C8") # feedback #start C8 analysis (function) preds_C8 = gateway_median(im_sn) #Write down results of C8 analysis. output_C8 = fname + "\t" + str(preds_C8[0]) + "\t" + str(preds_C8[1]) + "\t" + str(preds_C8[2]) + "\n" results = open (o_C8, "a+") results.write(output_C8) results.close() if preds_C8[2] > 0.5: print(fname, " was reclassified") #feedback from analysis using C8 strategy else: print(fname, " was not reclassified") #feedback from analysis using C8 strategy else: print(fname, " was misclassified") #feedback from analysis using C8 strategy else: print(fname, " is a tumor") #feedback #Loop for analysis of patches from validation dataset with "benign" label #as function #Analogous to tumor processor above def processor_norm (m_p_s): work_dir = base_dir_norm o_C1 = output_n_C1 o_C8 = output_n_C8 fnames = sorted(os.listdir(work_dir)) for fname in fnames: filename = os.path.join(work_dir, fname) im = image.load_img(filename) im = im.resize((m_p_s,m_p_s), Image.ANTIALIAS) im = np.array(im) #stain normalization im = standardizer.transform(im) im = stain_norm.transform(im) #for C8 im_sn = Image.fromarray(im) im = np.float32(im) x = image.img_to_array(im) x = np.expand_dims(x, axis = 0) x /= 255. #prediction preds = model.predict(x) #pred gland pr_1 = str(round(preds[0,0],3)) #pred non-gland pr_2 = str(round(preds[0,1],3)) #pred tumor pr_3 = str(round(preds[0,2],3)) #Output of C1 output = fname + "\t" + pr_1 + "\t" + pr_2 + "\t" + pr_3 + "\n" #Write down output of C1 results = open (o_C1, "a+") results.write(output) results.close() if preds[0,2] > 0.5: #Enter C8 pipeline if preds[0,0] > 0.2 or preds[0,1] > 0.2: print(fname, " was misclassified, but trying C8") #start C8 program preds_C8 = gateway_median(im_sn) #Write down results of C8 independent of classification from function output. output_C8 = fname + "\t" + str(preds_C8[0]) + "\t" + str(preds_C8[1]) + "\t" + str(preds_C8[2]) + "\n" results = open (o_C8, "a+") results.write(output_C8) results.close() if preds_C8[2] < 0.5: print(fname, " was reclassified") else: print(fname, " was not reclassified") else: print(fname, " was misclassified") else: print(fname, " is normal") #MAIN LOOP i = 0 for model_name in model_names: #1. Load model from list (one or more) print("Loading model: ", model_name, " ...") path_model = os.path.join(model_dir, model_name) model = load_model(path_model) #Create path to results file output_tu_C1 = result_dir + model_name + "__C1__tu.txt" output_n_C1 = result_dir + model_name + "__C1__norm.txt" output_tu_C8 = result_dir + model_name + "__C8__tu.txt" output_n_C8 = result_dir + model_name + "__C8__norm.txt" #start analysis processor_tu(m_p_s_list[i]) processor_norm(m_p_s_list[i]) #Increment of i for m_p_s i = i+1 print("Ready! Going to the next model.") #feedback
[ "staintools.BrightnessStandardizer", "keras.models.load_model", "statistics.median", "numpy.float32", "staintools.StainNormalizer", "numpy.expand_dims", "staintools.read_image", "keras.preprocessing.image.img_to_array", "keras.preprocessing.image.load_img", "numpy.array", "PIL.ImageOps.flip", "PIL.Image.fromarray", "os.path.join", "os.listdir" ]
[((867, 919), 'staintools.read_image', 'staintools.read_image', (['"""standard_he_stain_small.jpg"""'], {}), "('standard_he_stain_small.jpg')\n", (888, 919), False, 'import staintools\n'), ((970, 1005), 'staintools.BrightnessStandardizer', 'staintools.BrightnessStandardizer', ([], {}), '()\n', (1003, 1005), False, 'import staintools\n'), ((1056, 1100), 'staintools.StainNormalizer', 'staintools.StainNormalizer', ([], {'method': '"""macenko"""'}), "(method='macenko')\n", (1082, 1100), False, 'import staintools\n'), ((624, 645), 'os.listdir', 'os.listdir', (['model_dir'], {}), '(model_dir)\n', (634, 645), False, 'import os\n'), ((1581, 1599), 'PIL.ImageOps.flip', 'ImageOps.flip', (['r90'], {}), '(r90)\n', (1594, 1599), False, 'from PIL import Image, ImageOps\n'), ((1617, 1636), 'PIL.ImageOps.flip', 'ImageOps.flip', (['r270'], {}), '(r270)\n', (1630, 1636), False, 'from PIL import Image, ImageOps\n'), ((1669, 1688), 'PIL.ImageOps.flip', 'ImageOps.flip', (['base'], {}), '(base)\n', (1682, 1688), False, 'from PIL import Image, ImageOps\n'), ((2102, 2128), 'statistics.median', 'median', (['pred_stack[0:8, 0]'], {}), '(pred_stack[0:8, 0])\n', (2108, 2128), False, 'from statistics import median\n'), ((2141, 2167), 'statistics.median', 'median', (['pred_stack[0:8, 1]'], {}), '(pred_stack[0:8, 1])\n', (2147, 2167), False, 'from statistics import median\n'), ((2180, 2206), 'statistics.median', 'median', (['pred_stack[0:8, 2]'], {}), '(pred_stack[0:8, 2])\n', (2186, 2206), False, 'from statistics import median\n'), ((2222, 2256), 'numpy.array', 'np.array', (['[pred_1, pred_2, pred_3]'], {}), '([pred_1, pred_2, pred_3])\n', (2230, 2256), True, 'import numpy as np\n'), ((2447, 2472), 'keras.preprocessing.image.img_to_array', 'image.img_to_array', (['patch'], {}), '(patch)\n', (2465, 2472), False, 'from keras.preprocessing import image\n'), ((2485, 2514), 'numpy.expand_dims', 'np.expand_dims', (['patch'], {'axis': '(0)'}), '(patch, axis=0)\n', (2499, 2514), True, 'import numpy as np\n'), ((7592, 7627), 'os.path.join', 'os.path.join', (['model_dir', 'model_name'], {}), '(model_dir, model_name)\n', (7604, 7627), False, 'import os\n'), ((7640, 7662), 'keras.models.load_model', 'load_model', (['path_model'], {}), '(path_model)\n', (7650, 7662), False, 'from keras.models import load_model\n'), ((2941, 2961), 'os.listdir', 'os.listdir', (['work_dir'], {}), '(work_dir)\n', (2951, 2961), False, 'import os\n'), ((3027, 3056), 'os.path.join', 'os.path.join', (['work_dir', 'fname'], {}), '(work_dir, fname)\n', (3039, 3056), False, 'import os\n'), ((3070, 3094), 'keras.preprocessing.image.load_img', 'image.load_img', (['filename'], {}), '(filename)\n', (3084, 3094), False, 'from keras.preprocessing import image\n'), ((3199, 3211), 'numpy.array', 'np.array', (['im'], {}), '(im)\n', (3207, 3211), True, 'import numpy as np\n'), ((3377, 3396), 'PIL.Image.fromarray', 'Image.fromarray', (['im'], {}), '(im)\n', (3392, 3396), False, 'from PIL import Image, ImageOps\n'), ((3419, 3433), 'numpy.float32', 'np.float32', (['im'], {}), '(im)\n', (3429, 3433), True, 'import numpy as np\n'), ((3446, 3468), 'keras.preprocessing.image.img_to_array', 'image.img_to_array', (['im'], {}), '(im)\n', (3464, 3468), False, 'from keras.preprocessing import image\n'), ((3481, 3506), 'numpy.expand_dims', 'np.expand_dims', (['x'], {'axis': '(0)'}), '(x, axis=0)\n', (3495, 3506), True, 'import numpy as np\n'), ((5489, 5509), 'os.listdir', 'os.listdir', (['work_dir'], {}), '(work_dir)\n', (5499, 5509), False, 'import os\n'), ((5560, 5589), 'os.path.join', 'os.path.join', (['work_dir', 'fname'], {}), '(work_dir, fname)\n', (5572, 5589), False, 'import os\n'), ((5603, 5627), 'keras.preprocessing.image.load_img', 'image.load_img', (['filename'], {}), '(filename)\n', (5617, 5627), False, 'from keras.preprocessing import image\n'), ((5696, 5708), 'numpy.array', 'np.array', (['im'], {}), '(im)\n', (5704, 5708), True, 'import numpy as np\n'), ((5848, 5867), 'PIL.Image.fromarray', 'Image.fromarray', (['im'], {}), '(im)\n', (5863, 5867), False, 'from PIL import Image, ImageOps\n'), ((5890, 5904), 'numpy.float32', 'np.float32', (['im'], {}), '(im)\n', (5900, 5904), True, 'import numpy as np\n'), ((5917, 5939), 'keras.preprocessing.image.img_to_array', 'image.img_to_array', (['im'], {}), '(im)\n', (5935, 5939), False, 'from keras.preprocessing import image\n'), ((5952, 5977), 'numpy.expand_dims', 'np.expand_dims', (['x'], {'axis': '(0)'}), '(x, axis=0)\n', (5966, 5977), True, 'import numpy as np\n')]
"""Functions to configure energy demand outputs for supply model """ import os import logging import numpy as np import pandas as pd from energy_demand.basic import date_prop, testing_functions, lookup_tables def constrained_results( results_constrained, results_unconstrained_no_heating, submodels_names, technologies, ): """Prepare results for energy supply model for constrained model running mode (no heat is provided but technology specific fuel use). The results for the supply model are provided aggregated as follows: { "submodel_fueltype_tech": np.array(regions, timesteps)} Because SMIF only takes results in the form of {key: np.array(regions, timesteps)}, the key needs to contain information about submodel, fueltype, and technology. Also these key must be defined in the `submodel_model` configuration file. Arguments ---------- results_constrained : dict Aggregated results in form {technology: np.array((sector, region, fueltype, timestep))} results_unconstrained_no_heating : dict Aggregated results without heating {technology: np.array((sector, region, fueltype, timestep))} submodels_names : list Names of sectors fur supply model technologies : dict Technologies Returns ------- supply_results : dict No technology specific delivery (heat is provided in form of a fueltype) {submodel_fueltype: np.array((region, intervals))} Note ----- For the fuel demand for CHP plants, the co-generated electricity is not included in the demand model. Additional electricity supply generated from CHP plants need to be calculated in the supply model based on the fuel demand for CHP. For CHP efficiency therefore not the overall efficiency is used but only the thermal efficiency """ supply_results = {} fueltypes = lookup_tables.basic_lookups()['fueltypes'] # ---------------------------------------- # Add all constrained results (technology specific results) # Aggregate according to submodel, fueltype, technology, region, timestep # ---------------------------------------- for submodel_nr, submodel in enumerate(submodels_names): for tech, fuel_tech in results_constrained.items(): # Technological simplifications because of different technology # definition and because not all technologies are used in supply model tech_simplified = model_tech_simplification(tech) fueltype_str = technologies[tech_simplified].fueltype_str fueltype_int = technologies[tech_simplified].fueltype_int key_name = "{}_{}_{}".format(submodel, fueltype_str, tech_simplified) if key_name not in supply_results: supply_results[key_name] = fuel_tech[submodel_nr][:, fueltype_int, :] else: supply_results[key_name] += fuel_tech[submodel_nr][:, fueltype_int, :] assert not testing_functions.test_if_minus_value_in_array(results_unconstrained_no_heating) # --------------------------------- # Add non_heating for all fueltypes # --------------------------------- for submodel_nr, submodel in enumerate(submodels_names): for fueltype_str, fueltype_int in fueltypes.items(): if fueltype_str == 'heat': pass #Do not add non_heating demand for fueltype heat else: key_name = "{}_{}_{}".format(submodel, fueltype_str, "non_heating") # Add fuel for all regions for specific fueltype supply_results[key_name] = results_unconstrained_no_heating[submodel_nr][:, fueltype_int, :] # -------------------------------------------- # Check whether any entry is smaller than zero # -------------------------------------------- for key_name, values in supply_results.items(): if testing_functions.test_if_minus_value_in_array(values): raise Exception("Error d: Negative entry in results {} {}".format(key_name, np.sum(values))) return supply_results def unconstrained_results( results_unconstrained, submodels_names ): """Prepare results for energy supply model for unconstrained model running mode (heat is provided). The results for the supply model are provided aggregated for every submodel, fueltype, region, timestep Note ----- Because SMIF only takes results in the form of {key: np.aray(regions, timesteps)}, the key needs to contain information about submodel and fueltype Also these key must be defined in the `submodel_model` configuration file Arguments ---------- results_unconstrained : array Results of unconstrained mode np.array((sector, regions, fueltype, timestep)) submodels_names : list Names of sectors for supply model Returns ------- supply_results : dict No technology specific delivery (heat is provided in form of a fueltype) {submodel_fueltype: np.array((region, intervals))} """ supply_results = {} fueltypes = lookup_tables.basic_lookups()['fueltypes'] for submodel_nr, submodel in enumerate(submodels_names): for fueltype_str, fueltype_int in fueltypes.items(): # Generate key name (must be defined in `sector_models`) key_name = "{}_{}".format(submodel, fueltype_str) # Add fueltype specific demand for all regions supply_results[key_name] = results_unconstrained[submodel_nr][:, fueltype_int, :] assert not testing_functions.test_if_minus_value_in_array(supply_results[key_name]) logging.info("... Prepared results for energy supply model in unconstrained mode") return supply_results def model_tech_simplification(tech): """This function aggregated different technologies which are not defined in supply model Arguments --------- tech : str Technology Returns ------- tech_newly_assigned : str Technology newly assigned """ if tech == 'boiler_condensing_gas': tech_newly_assigned = 'boiler_gas' elif tech == 'boiler_condensing_oil': tech_newly_assigned = 'boiler_oil' elif tech == 'storage_heater_electricity': tech_newly_assigned = 'boiler_electricity' elif tech == 'secondary_heater_electricity': tech_newly_assigned = 'boiler_electricity' else: tech_newly_assigned = tech if tech != tech_newly_assigned: logging.debug( "Assigned new technology '%s' for '%s' to provide for simplified supply output", tech_newly_assigned, tech) return tech_newly_assigned def write_national_results_amman( path_folder, results_unconstrained, regions, fueltype_str, fuelype_nr, year ): """Write national results of all fueltypes Inputs ------ results_unconstrained : array (submodel, region, fueltype, periods) """ logging.info("... writing file for amman") path = os.path.join(path_folder, "file_AMMAN_{}_{}.csv".format(fueltype_str, year)) # Sum across all sectors sum_across_submodels = results_unconstrained.sum(axis=0) # Change ot days nr_regs = len(regions) nr_fueltypes = sum_across_submodels.shape[1] sum_across_regions_days = sum_across_submodels.reshape(nr_regs, nr_fueltypes, 365, 24) # Iterate over every hour in year rows = [] for region_nr, region in enumerate(regions): for day in range(365): row = {'region': region} daysum = np.sum(sum_across_regions_days[region_nr][fuelype_nr][day]) row['day'] = day row['demand_GWh'] = daysum rows.append(row) # Create dataframe col_names = ['region', 'day', 'demand_GWh'] my_df = pd.DataFrame(rows, columns=col_names) my_df.to_csv(path, index=False) #Index prevents writing index rows def write_national_results( path_folder, results_unconstrained, enduse_specific_results, fueltype_str, fuelype_nr, year, submodels_names=['residential', 'service', 'industry'] ): """Write national results of all fueltypes Input ------ results_unconstrained : array (submodel, region, fueltype, periods) """ logging.info("... writing file for modassar") path = os.path.join(path_folder, "file_MODASSAR_{}_{}.csv".format(fueltype_str, year)) # Sum across all regions sum_across_regions = results_unconstrained.sum(axis=1) rows = [] for hour in range(8760): # Get day and hour day_year, hour_day_year = date_prop.convert_h_to_day_year_and_h(hour) row = {'year': year, 'hour': hour} for submodel_nr, submodel in enumerate(submodels_names): # Total energy demand ed_submodel_h = sum_across_regions[submodel_nr][fuelype_nr][hour] # Space heating related demand for sector if submodel_nr == 0: space_heating_demand = enduse_specific_results['rs_space_heating'][fuelype_nr][day_year][hour_day_year] elif submodel_nr == 1: space_heating_demand = enduse_specific_results['ss_space_heating'][fuelype_nr][day_year][hour_day_year] else: space_heating_demand = enduse_specific_results['is_space_heating'][fuelype_nr][day_year][hour_day_year] ed_submodel_heating_h = space_heating_demand str_name_heat = "{}_heat".format(submodel) row[str_name_heat] = ed_submodel_heating_h # Non-heating related demand ed_submodel_non_heating_h = ed_submodel_h - space_heating_demand str_name_non_heat = "{}_non_heat".format(submodel) row[str_name_non_heat] = ed_submodel_non_heating_h rows.append(row) # Create dataframe col_names = [ 'year', 'hour', 'residential_non_heat', 'residential_heat', 'service_non_heat', 'service_heat', 'industry_non_heat', 'industry_heat'] my_df = pd.DataFrame(rows, columns=col_names) my_df.to_csv(path, index=False) #Index prevents writing index rows # Plot national results '''validation_enduses.plot_dataframe_function( my_df, x_column_name='hour', y_column_names=['residential_non_heat', 'service_non_heat', 'industry_non_heat'], plot_kind='line')'''
[ "pandas.DataFrame", "energy_demand.basic.lookup_tables.basic_lookups", "logging.debug", "numpy.sum", "energy_demand.basic.date_prop.convert_h_to_day_year_and_h", "energy_demand.basic.testing_functions.test_if_minus_value_in_array", "logging.info" ]
[((5766, 5853), 'logging.info', 'logging.info', (['"""... Prepared results for energy supply model in unconstrained mode"""'], {}), "(\n '... Prepared results for energy supply model in unconstrained mode')\n", (5778, 5853), False, 'import logging\n'), ((7133, 7175), 'logging.info', 'logging.info', (['"""... writing file for amman"""'], {}), "('... writing file for amman')\n", (7145, 7175), False, 'import logging\n'), ((7979, 8016), 'pandas.DataFrame', 'pd.DataFrame', (['rows'], {'columns': 'col_names'}), '(rows, columns=col_names)\n', (7991, 8016), True, 'import pandas as pd\n'), ((8490, 8535), 'logging.info', 'logging.info', (['"""... writing file for modassar"""'], {}), "('... writing file for modassar')\n", (8502, 8535), False, 'import logging\n'), ((10285, 10322), 'pandas.DataFrame', 'pd.DataFrame', (['rows'], {'columns': 'col_names'}), '(rows, columns=col_names)\n', (10297, 10322), True, 'import pandas as pd\n'), ((1958, 1987), 'energy_demand.basic.lookup_tables.basic_lookups', 'lookup_tables.basic_lookups', ([], {}), '()\n', (1985, 1987), False, 'from energy_demand.basic import date_prop, testing_functions, lookup_tables\n'), ((3057, 3142), 'energy_demand.basic.testing_functions.test_if_minus_value_in_array', 'testing_functions.test_if_minus_value_in_array', (['results_unconstrained_no_heating'], {}), '(results_unconstrained_no_heating\n )\n', (3103, 3142), False, 'from energy_demand.basic import date_prop, testing_functions, lookup_tables\n'), ((3985, 4039), 'energy_demand.basic.testing_functions.test_if_minus_value_in_array', 'testing_functions.test_if_minus_value_in_array', (['values'], {}), '(values)\n', (4031, 4039), False, 'from energy_demand.basic import date_prop, testing_functions, lookup_tables\n'), ((5212, 5241), 'energy_demand.basic.lookup_tables.basic_lookups', 'lookup_tables.basic_lookups', ([], {}), '()\n', (5239, 5241), False, 'from energy_demand.basic import date_prop, testing_functions, lookup_tables\n'), ((6626, 6757), 'logging.debug', 'logging.debug', (['"""Assigned new technology \'%s\' for \'%s\' to provide for simplified supply output"""', 'tech_newly_assigned', 'tech'], {}), '(\n "Assigned new technology \'%s\' for \'%s\' to provide for simplified supply output"\n , tech_newly_assigned, tech)\n', (6639, 6757), False, 'import logging\n'), ((8823, 8866), 'energy_demand.basic.date_prop.convert_h_to_day_year_and_h', 'date_prop.convert_h_to_day_year_and_h', (['hour'], {}), '(hour)\n', (8860, 8866), False, 'from energy_demand.basic import date_prop, testing_functions, lookup_tables\n'), ((7737, 7796), 'numpy.sum', 'np.sum', (['sum_across_regions_days[region_nr][fuelype_nr][day]'], {}), '(sum_across_regions_days[region_nr][fuelype_nr][day])\n', (7743, 7796), True, 'import numpy as np\n'), ((5688, 5760), 'energy_demand.basic.testing_functions.test_if_minus_value_in_array', 'testing_functions.test_if_minus_value_in_array', (['supply_results[key_name]'], {}), '(supply_results[key_name])\n', (5734, 5760), False, 'from energy_demand.basic import date_prop, testing_functions, lookup_tables\n'), ((4129, 4143), 'numpy.sum', 'np.sum', (['values'], {}), '(values)\n', (4135, 4143), True, 'import numpy as np\n')]
#!/usr/bin/env python ###################################################################### # Software License Agreement (BSD License) # # Copyright (c) 2017, Rice University # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * 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. # * Neither the name of the Rice University 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 OWNER 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. ###################################################################### # Author: <NAME> # This is a helper program to visualize the output of the KinematicChainBenchmark.cpp. # Sample usage (when running from the OMPL build directory): # # ./bin/demo_KinematicChainBenchmark 10 1 # /path/to/KinematicChainPathPlot.py 10 # produces kinematic_10.pdf # /path/to/KinematicChainPathPlot.py 10 movie # produces kinematic_10.mp4 from sys import argv, exit import numpy as np import matplotlib.pyplot as plt from matplotlib.patches import PathPatch from matplotlib.path import Path from matplotlib import animation, cm, colors from matplotlib.backends.backend_pdf import PdfPages fig = plt.figure() plt.axis('equal') ax = plt.axes(xlim=(-1, 1), ylim=(-1, 1)) ln, = plt.plot([], [], animated=True) def getPositions(pose, linkLength, color = 'red'): angles = np.cumsum(pose) return PathPatch(Path( np.insert(linkLength * np.cumsum([np.cos(angles), np.sin(angles)], axis = 1), 0, 0., axis = 1).T), facecolor='none', edgecolor = color) def drawEnvironment(env): ax.clear() plt.gca().add_patch(env) def drawPose(index, env, poses, linkLength): drawEnvironment(env) if index == -1: cMap = cm.ScalarMappable( norm = colors.Normalize(vmin=0, vmax=poses.shape[0] - 1), cmap = plt.get_cmap('viridis') ) for (i,pose) in enumerate(poses): plt.gca().add_patch(getPositions(pose, linkLength, cMap.to_rgba(i))) else: plt.gca().add_patch(getPositions(poses[index,:], linkLength)) return ln, def makeMovie(fname, env, poses, linkLength): ani = animation.FuncAnimation(plt.gcf(), drawPose, fargs=(env, poses, linkLength), frames = poses.shape[0], blit = True) ani.save(fname, bitrate = 300, fps = 20) if __name__ == '__main__': if len(argv) < 2: print('Usage: %s num_links [movie]' % argv[0]) exit(1) dims = int(argv[1]) coords = np.loadtxt('environment_%d.dat' % dims) env = PathPatch(Path(coords), facecolor='none', edgecolor='black') poses = np.loadtxt('kinematic_path_%d.dat' % dims) linkLength = 1. / dims if len(argv) > 2: makeMovie('kinematic_%d.mp4' % dims, env, poses, linkLength) else: drawPose(-1, env, poses, linkLength) fig = plt.gcf() fig.savefig('kinematic_%d.pdf' % dims)
[ "matplotlib.pyplot.get_cmap", "matplotlib.pyplot.plot", "matplotlib.colors.Normalize", "matplotlib.pyplot.axes", "matplotlib.pyplot.axis", "numpy.cumsum", "matplotlib.pyplot.figure", "matplotlib.path.Path", "numpy.sin", "numpy.loadtxt", "numpy.cos", "matplotlib.pyplot.gca", "matplotlib.pyplot.gcf", "sys.exit" ]
[((2421, 2433), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (2431, 2433), True, 'import matplotlib.pyplot as plt\n'), ((2434, 2451), 'matplotlib.pyplot.axis', 'plt.axis', (['"""equal"""'], {}), "('equal')\n", (2442, 2451), True, 'import matplotlib.pyplot as plt\n'), ((2457, 2493), 'matplotlib.pyplot.axes', 'plt.axes', ([], {'xlim': '(-1, 1)', 'ylim': '(-1, 1)'}), '(xlim=(-1, 1), ylim=(-1, 1))\n', (2465, 2493), True, 'import matplotlib.pyplot as plt\n'), ((2500, 2531), 'matplotlib.pyplot.plot', 'plt.plot', (['[]', '[]'], {'animated': '(True)'}), '([], [], animated=True)\n', (2508, 2531), True, 'import matplotlib.pyplot as plt\n'), ((2597, 2612), 'numpy.cumsum', 'np.cumsum', (['pose'], {}), '(pose)\n', (2606, 2612), True, 'import numpy as np\n'), ((3737, 3776), 'numpy.loadtxt', 'np.loadtxt', (["('environment_%d.dat' % dims)"], {}), "('environment_%d.dat' % dims)\n", (3747, 3776), True, 'import numpy as np\n'), ((3860, 3902), 'numpy.loadtxt', 'np.loadtxt', (["('kinematic_path_%d.dat' % dims)"], {}), "('kinematic_path_%d.dat' % dims)\n", (3870, 3902), True, 'import numpy as np\n'), ((3426, 3435), 'matplotlib.pyplot.gcf', 'plt.gcf', ([], {}), '()\n', (3433, 3435), True, 'import matplotlib.pyplot as plt\n'), ((3691, 3698), 'sys.exit', 'exit', (['(1)'], {}), '(1)\n', (3695, 3698), False, 'from sys import argv, exit\n'), ((3797, 3809), 'matplotlib.path.Path', 'Path', (['coords'], {}), '(coords)\n', (3801, 3809), False, 'from matplotlib.path import Path\n'), ((4091, 4100), 'matplotlib.pyplot.gcf', 'plt.gcf', ([], {}), '()\n', (4098, 4100), True, 'import matplotlib.pyplot as plt\n'), ((2842, 2851), 'matplotlib.pyplot.gca', 'plt.gca', ([], {}), '()\n', (2849, 2851), True, 'import matplotlib.pyplot as plt\n'), ((3011, 3060), 'matplotlib.colors.Normalize', 'colors.Normalize', ([], {'vmin': '(0)', 'vmax': '(poses.shape[0] - 1)'}), '(vmin=0, vmax=poses.shape[0] - 1)\n', (3027, 3060), False, 'from matplotlib import animation, cm, colors\n'), ((3081, 3104), 'matplotlib.pyplot.get_cmap', 'plt.get_cmap', (['"""viridis"""'], {}), "('viridis')\n", (3093, 3104), True, 'import matplotlib.pyplot as plt\n'), ((3264, 3273), 'matplotlib.pyplot.gca', 'plt.gca', ([], {}), '()\n', (3271, 3273), True, 'import matplotlib.pyplot as plt\n'), ((3161, 3170), 'matplotlib.pyplot.gca', 'plt.gca', ([], {}), '()\n', (3168, 3170), True, 'import matplotlib.pyplot as plt\n'), ((2682, 2696), 'numpy.cos', 'np.cos', (['angles'], {}), '(angles)\n', (2688, 2696), True, 'import numpy as np\n'), ((2698, 2712), 'numpy.sin', 'np.sin', (['angles'], {}), '(angles)\n', (2704, 2712), True, 'import numpy as np\n')]