repo_name
stringlengths
6
130
hexsha
sequence
file_path
sequence
code
sequence
apis
sequence
possible_versions
list
cpsc532s-cc/CLVM_Test
[ "b814c47b3e5fbc053d083927dc00032530176745" ]
[ "multi_timescale_clvm.py" ]
[ "import numpy as np\nimport math\nimport pdb\nnp.cat = np.concatenate\nnp.random.seed(100)\nimport torch as t \nimport torch.nn as nn\nimport torch.nn.functional as f\nimport torch.optim as opt\nimport os.path\nfrom torch import FloatTensor as FT\nfrom variational_methods import *\nfrom gutenberg_data import *\nfrom decoders import * \nfrom mnist_data import *\nfrom viz import *\nimport time\nimport matplotlib.pyplot as plt\nimport torch as t\nimport pickle\nfrom torch import FloatTensor as FT \nfrom torch import LongTensor as LT \n\nfrom scipy.io import wavfile\nimport numpy as np\nfrom scipy.signal import butter, lfilter\n\nMODEL_PATH = \"model\"\n\ndef text_to_indices(text):\n indices = []\n for i in text:\n indices.append(ord(i))\n return indices\n \ndef shitty_text_to_indices(text):\n indices = []\n for i in text:\n x = ord(i)\n if (x == 8216 or x == 8217):\n x = 39\n if (x == 8220 or x == 8221):\n x = 34\n if (x > 255):\n continue\n indices.append(x)\n return indices\n\ndef indices_to_text(indicies):\n #TODO: Make more efficient\n text_array = []\n for i in indicies:\n text_array += chr(i)\n text = \"\".join(text_array)\n return text\n\ndef slice_tuple(x,sl):\n out = []\n for a in x:\n out.append(a[sl])\n return tuple(out)\n\nclass LatentVar(object):\n def __init__(self, dim, offset=0, optimizer=\"adam\", params={\"lr\":0.01, \"b1\":0.9, \"b2\":0.999, \"e\":1e-8}):\n self.optimizer = optimizer\n self.params = params\n self.offset = offset\n if optimizer == \"adam\":\n self.mean = np.zeros(dim,np.float32)\n self.log_var = np.zeros(dim,np.float32)\n\n self.mean_m0 = np.zeros(dim,np.float32)\n self.log_var_m0 = np.zeros(dim,np.float32)\n\n self.mean_m1 = np.zeros(dim,np.float32)\n self.log_var_m1 = np.zeros(dim,np.float32)\n \n #TODO: COme up with a less degenerate way of doing this\n self.parameters = [\"mean\", \"log_var\", \"mean_m0\", \"log_var_m0\", \"mean_m1\", \"log_var_m1\"]\n\n self.grad = False \n self.shape = self.mean.shape\n\n def __getitem__(self,x):\n mean = FT(self.mean[x]).cuda()\n log_var = FT(self.log_var[x]).cuda()\n mean.requires_grad=self.grad\n log_var.requires_grad=self.grad\n y = mean,log_var\n return y\n \n def __setitem__(self,x,grad):\n mean_grad,log_var_grad = grad \n lr = self.params[\"lr\"]\n b1 = self.params[\"b1\"]\n b2 = self.params[\"b2\"]\n e = self.params[\"e\"]\n\n self.mean_m0[x] = self.mean_m0[x]*b1+(1-b1)*mean_grad\n self.mean_m1[x] = self.mean_m1[x]*b2+(1-b2)*(mean_grad**2)\n mean_m0 = self.mean_m0[x]/(1-b1)\n mean_m1 = self.mean_m1[x]/(1-b2)\n self.mean[x] -= lr*mean_m0/(np.sqrt(mean_m1)+e)\n\n self.log_var_m0[x] = self.log_var_m0[x]*b1+(1-b1)*log_var_grad\n self.log_var_m1[x] = self.log_var_m1[x]*b2+(1-b2)*(log_var_grad**2)\n log_var_m0 = self.log_var_m0[x]/(1-b1)\n log_var_m1 = self.log_var_m1[x]/(1-b2)\n self.log_var[x] -= lr*log_var_m0/(np.sqrt(log_var_m1)+e)\n\n def save(self, name, directory):\n for i in range(len(self.parameters)):\n f = name + str(i) + \".npy\"\n path = os.path.join(directory,f)\n arr = self.__dict__[self.parameters[i]]\n np.save(path,arr)\n\n\n def load(self, name, directory):\n for i in range(len(self.parameters)):\n f = name + str(i) + \".npy\"\n path = os.path.join(directory,f)\n val = np.load(path)\n self.__dict__[self.parameters[i]] = val\n\n\ndef get_top_slice(true_offset, window, index, extra, ds):\n imputed_offset = window // ds\n delta = true_offset - imputed_offset\n offset = (index-window) % ds\n start = (index+offset) // ds + delta\n l = len(range((ds-offset)%ds,extra+2*window,ds))\n stop = start + l \n step = ds\n return slice(start,stop)\n\ndef get_bot_slice(true_offset, window, index, extra):\n start = index+true_offset-window\n stop = start + 2*window+extra+1\n return slice(start,stop)\n\nclass MTCLVMLayer(object):\n #TODO: Finish implementing\n def __init__(self, latent_var, downsampling, max_window, model, opt):\n self.max_window = max_window\n self.downsampling = downsampling \n self.latent_var = latent_var\n\nclass MTCLVMManager(object):\n def __init__(self, data_plural, embedding, layers, update_sizes):\n self.mtclvms = []\n self.layers = layers\n self.update_sizes = update_sizes\n self.embedding = embedding\n weights = [] \n for i,data in enumerate(data_plural):\n weights.append(data.shape[0]) #weight updates based on data size\n self.mtclvms.append(MultiTimescaleCLVM(data, embedding, layers))\n self.weights = np.array(weights,dtype=np.float32)\n\n def save(self, directory):\n for i in range(len(self.layers)):\n layer = self.layers[i]\n\n f = \"layer_param\" + str(i) + \".t\"\n path = os.path.join(directory,f)\n state_dict = layer[3].state_dict()\n torch.save(state_dict,path)\n\n f = \"layer_opt\" + str(i) + \".t\"\n path = os.path.join(directory,f)\n state_dict = layer[4].state_dict()\n torch.save(state_dict,path)\n\n for i in range(len(self.mtclvms)):\n name = \"mtclvm\" + str(i)\n self.mtclvms[i].save(name, directory)\n\n\n def load(self, directory):\n for i in range(len(self.layers)):\n try:\n layer = self.layers[i]\n\n f = \"layer_param\" + str(i) + \".t\"\n path = os.path.join(directory,f)\n state_dict = torch.load(path)\n layer[3].load_state_dict(state_dict)\n\n\n f = \"layer_opt\" + str(i) + \".t\"\n path = os.path.join(directory,f)\n state_dict = torch.load(path)\n layer[4].load_state_dict(state_dict)\n except:\n pass\n\n for i in range(len(self.mtclvms)):\n try:\n name = \"mtclvm\" + str(i)\n self.mtclvms[i].load(name, directory)\n except:\n pass\n\n def update_model(self,layer_index,latent_update_count,kl_lambda=1):\n extra = self.update_sizes[layer_index]\n total_weight = np.sum(self.weights)\n data_probs = self.weights / total_weight\n\n for i in range(latent_update_count):\n mtclvm_index = np.random.choice(np.arange(len(self.mtclvms)),p=data_probs)\n mtclvm = self.mtclvms[mtclvm_index]\n length = mtclvm.layers[layer_index][1]\n index = np.random.random_integers(0, length-extra-1)\n loss2 = mtclvm.update_latent(layer_index, index, extra, kl_lambda=kl_lambda)\n\n mtclvm_index = np.random.choice(np.arange(len(self.mtclvms)),p=data_probs)\n mtclvm = self.mtclvms[mtclvm_index]\n length = mtclvm.layers[layer_index][1]\n index = np.random.random_integers(0, length-extra-1)\n loss1 = mtclvm.update_layer(layer_index, index, extra)\n\n if latent_update_count == 0:\n return loss1\n else:\n return loss2\n\n def cheng_update_model(self,layer_index,latent_update_count,kl_lambda=1):\n total_weight = np.sum(self.weights)\n data_probs = self.weights / total_weight\n mtclvm_index = np.random.choice(np.arange(len(self.mtclvms)),p=data_probs)\n mtclvm = self.mtclvms[mtclvm_index]\n\n extra = self.update_sizes[layer_index]\n length = mtclvm.layers[layer_index][1]\n index = np.random.random_integers(0, length-extra-1)\n\n for i in range(latent_update_count):\n loss2 = mtclvm.update_latent(layer_index, index, extra, kl_lambda=kl_lambda)\n loss1= mtclvm.update_layer(layer_index, index, extra)\n\n if latent_update_count == 0:\n return loss1\n else:\n return loss2\n\n\n def generate(self, top_len):\n #initialize top layer\n top_model = self.layers[-1][3]\n top_window = self.layers[-1][2]\n top_size = self.layers[-1][1]\n top_ds = self.layers[-1][0]\n top_offset = top_window//top_ds\n top_latent_dist = t.zeros((top_len + top_offset,top_size)),t.zeros((top_len + top_offset,top_size))\n top_latent = gauss_samp(top_latent_dist)\n\n #generate_intermediate layers\n for i in list(range(len(self.layers)-1))[::-1]:\n bot_model = self.layers[i][3]\n bot_window = self.layers[i][2]\n bot_size = self.layers[i][1]\n bot_ds = self.layers[i][0]\n\n bot_offset = max(top_window, bot_window//bot_ds)\n bot_len = top_len * top_ds \n top_input = t.zeros((top_window+bot_len,top_size)).cuda()\n top_input[top_window % top_ds::top_ds,:] = top_latent[-(top_window // top_ds+top_len):]\n bot_latent = t.zeros((bot_len + bot_offset,bot_size)).cuda()\n bot_latent_offset_dist = t.zeros((bot_offset,bot_size)).cuda(),t.zeros((bot_offset,bot_size)).cuda()\n\n bot_latent[:bot_offset,:] = gauss_samp(bot_latent_offset_dist)\n\n bot_delta = bot_offset - top_window\n for j in range(bot_len):\n top_input_subset = top_input[j:j+top_window]\n bot_input_subset = bot_latent[bot_delta+j:bot_delta+j+top_window]\n\n model_input = t.cat((top_input_subset,bot_input_subset), 1).unsqueeze(0)\n model_output = top_model(model_input)\n bot_latent[j+bot_offset,:] = gauss_samp(model_output)\n\n top_len = bot_len\n top_model = bot_model\n top_window = bot_window\n top_offset = bot_offset\n top_ds = bot_ds\n top_latent = bot_latent\n top_size = bot_size\n\n #generate intermediate layers\n samp_len = top_len*top_ds\n padded_samp = t.zeros((samp_len + top_window,),dtype=t.int32)\n\n #TODO: Verify\n top_input = t.zeros(top_window+samp_len,top_size).cuda()\n top_input[top_window % top_ds::top_ds] = top_latent[-(top_window // top_ds+top_len):]\n\n for j in range(samp_len):\n top_input_subset = top_input[j:j+top_window]\n bot_input_subset = self.embedding(padded_samp[j:top_window+j])\n model_input = t.cat((top_input_subset,bot_input_subset), 1).unsqueeze(0)\n model_output = top_model(model_input)\n sample = t.multinomial(t.squeeze(f.softmax(model_output,1)),1)\n padded_samp[top_window+j] = sample\n\n output = padded_samp[top_window:]\n return output\n\n\n\n\nclass MultiTimescaleCLVM(object):\n def __init__(self, data, embedding, layers):\n self.data = data\n self.embedding = embedding\n self.layers = []\n curr_length = data.shape[0]\n #Generate latent variables\n for i, (downsampling, latent_size, window, model, opt) in enumerate(layers):\n curr_length = curr_length // downsampling\n if (i < len(layers)-1):\n next_window = layers[i+1][2]\n offset = max(window // downsampling, next_window)\n padding = max(window // downsampling, next_window)\n latent_length = offset + curr_length + padding\n else:\n offset = window // downsampling\n padding = window // downsampling\n latent_length = offset + curr_length + padding \n\n if i == 0:\n pad = np.zeros((window,),dtype=np.int32)\n self.data = np.cat((pad, data, pad))\n latent_var = LatentVar((latent_length,latent_size),offset=window)\n self.layers.append((offset, curr_length, latent_var, downsampling, window, model, opt))\n\n def save(self, name, directory):\n for i in range(len(self.layers)):\n f = name +\"layer\" + str(i) \n self.layers[i][2].save(f, directory)\n\n def load(self, name, directory):\n for i in range(len(self.layers)):\n f = name +\"layer\" + str(i) \n self.layers[i][2].load(f, directory)\n\n def lp_loss(self, layer, index, extra, compute_grad=True):\n self.val_index_extra(layer, index, extra)\n\n top_offset, _, top_latent, ds, window, model, opt = self.layers[layer] \n bot_index = index*ds\n bot_extra = (extra+1)*ds-1\n if compute_grad:\n top_latent.grad = True\n if layer != 0:\n bot_latent = self.layers[layer-1][2]\n bot_offset = self.layers[layer-1][0]\n sl_bot = get_bot_slice(bot_offset, window, bot_index, bot_extra)\n bot_dist = bot_latent[sl_bot]\n bot_vals = gauss_samp(bot_dist)\n bot_input = bot_vals[:-1]\n else:\n sl_bot = get_bot_slice(window, window, bot_index, bot_extra)\n bot_input = self.embedding(self.data[sl_bot.start:sl_bot.stop-1]).cuda()\n\n #Upsample and prepare top layer\n length = bot_input.shape[0]\n assert length == bot_extra+2*window\n width = top_latent.shape[1]\n\n sl_top = get_top_slice(top_offset ,window, bot_index, bot_extra, ds)\n top_dist = top_latent[sl_top]\n top_input = t.zeros(length,width).cuda()\n offset = (bot_index-window) % ds\n top_input[(ds-offset)%ds::ds,:] = gauss_samp((top_dist[0],top_dist[1]))\n\n #Prep input\n inputs = t.cat((top_input,bot_input),1).unsqueeze(0)\n\n prediction = model(inputs)\n #print(index,prediction[0,:2,:7],prediction[0,:2,:7])\n #print(prediction[0].shape[1],bot_extra+window+1)\n assert prediction[0].shape[1] == bot_extra+window+1\n #Compute loss\n if layer != 0:\n #targets = bot_vals[window:]\n #log_p = gauss_log_p(prediction,targets)\n #loss = -t.sum(log_p)\n \n targets = bot_dist[0][window:],bot_dist[1][window:]\n exp_neg_log_p = gauss_kl_div(targets,prediction)\n loss = t.sum(exp_neg_log_p)\n else:\n a = window+bot_index\n b = a+bot_extra+window+1\n targets = LT(self.data[a:b]).cuda().unsqueeze(0)\n log_p = -f.cross_entropy(prediction,targets,reduction=\"none\")\n\n loss = -t.sum(log_p)\n\n if compute_grad:\n loss.backward()\n sl_top.start\n a = window // ds\n b = a+extra+1\n top_grad = top_dist[0].grad[a:b],top_dist[1].grad[a:b]\n top_latent.grad = False \n return loss, top_grad\n\n return loss\n \n def kl_loss(self, layer, index, extra, compute_grad=True):\n self.val_index_extra(layer, index, extra)\n\n #when using the top layer, compute kl w.r.t unit variance zero mean gaussian\n mid_offset, _, mid_latent, mid_ds, mid_window, _, _ = self.layers[layer]\n if compute_grad:\n mid_latent.grad = True\n\n if layer == len(self.layers)-1:\n mid_dist = mid_latent[mid_offset+index:mid_offset+index+extra+1]\n length = mid_dist[0].shape[0]\n width = mid_dist[0].shape[1]\n prior = t.zeros(length,width).cuda(),t.zeros(length,width).cuda()\n kl_div = gauss_kl_div(mid_dist,prior)\n loss = t.sum(kl_div)\n\n if compute_grad:\n loss.backward()\n mid_grad = mid_dist[0].grad, mid_dist[1].grad\n\n else:\n top_offset, _, top_latent, top_ds, top_window, top_model, _ = self.layers[layer+1]\n\n #Upsample and prepare top layer\n mid_dist = mid_latent[get_bot_slice(mid_offset, top_window, index, extra)]\n mid_vals = gauss_samp(mid_dist)\n mid_input = mid_vals[:-1]\n\n length = mid_input.shape[0]\n assert length == extra+2*top_window\n width = top_latent.shape[1]\n offset = (index-top_window) % top_ds\n\n top_dist = top_latent[get_top_slice(top_offset ,top_window, index, extra, top_ds)]\n top_input = t.zeros(length, width).cuda()\n top_input[(top_ds-offset)%top_ds::top_ds,:] = gauss_samp(top_dist)\n\n #Compute prior\n prior_inputs = t.cat((top_input,mid_input),1).unsqueeze(0)\n prior = top_model(prior_inputs)\n\n #Compute log_kl term\n sub_mid_dist = mid_dist[0][top_window:],mid_dist[1][top_window:]\n kl_div = gauss_kl_div(sub_mid_dist,prior)\n #print(t.std(sub_mid_dist[0])/t.exp(t.mean(sub_mid_dist[1])/2))\n\n loss = t.sum(kl_div)\n\n if compute_grad:\n loss.backward()\n a = top_window\n b = a+extra+1\n mid_grad = mid_dist[0].grad[a:b],mid_dist[1].grad[a:b]\n\n if compute_grad:\n return loss, mid_grad\n else:\n return loss\n\n def val_index_extra(self, layer, index, extra):\n if layer < 0 or layer >= len(self.layers):\n msg = \"invalid layer, recived{} expected values between 0 and {}\"\n raise Exception(msg.format(layer,len(self.layers)-1))\n\n true_offset, length, latent, _, _, _, _ = self.layers[layer]\n if index < 0:\n msg = \"invalid index, recived {} index must be greater than 0\"\n raise Exception(msg.format(index))\n if index + extra + 1 > length:\n msg = \"invalid index and extra parameters, recived {} index + extra must be <= {}\"\n raise Exception(msg.format(index+extra,length - 1))\n\n def update_layer(self, layer, index, extra): \n opt = self.layers[layer][6]\n opt.zero_grad()\n loss = self.lp_loss(layer, index, extra, compute_grad=False)\n loss.backward()\n loss = loss.detach().cpu().numpy()\n opt.step()\n return loss\n \n\n def update_latent(self, layer, index, extra, kl_lambda=1):\n #print(\"LT\",layer,index,extra)\n offset, _, mid_latent, mid_ds, mid_window, mid_model, _ = self.layers[layer]\n\n kl_loss, mid_grad_kl = self.kl_loss(layer, index, extra)\n lp_loss, mid_grad_lp = self.lp_loss(layer, index, extra)\n kl_grad = mid_grad_kl[0].cpu().numpy(), mid_grad_kl[1].cpu().numpy()\n lp_grad = mid_grad_lp[0].cpu().numpy(), mid_grad_lp[1].cpu().numpy()\n\n mean_grad = kl_grad[0]*kl_lambda+lp_grad[0]\n log_var_grad = kl_grad[1]*kl_lambda+lp_grad[1]\n #mean_grad = kl_grad[0]\n #log_var_grad = kl_grad[1]\n #mean_grad = lp_grad[0]\n #log_var_grad = lp_grad[1]\n mid_latent[offset+index:offset+index+extra+1] = (mean_grad,log_var_grad)\n return kl_loss.detach().cpu().numpy(), lp_loss.detach().cpu().numpy()\n\n\nclass TopMiniConv(nn.Module):\n def __init__(self,top_ch,bot_ch,ar=True):\n self.ar = ar\n self.bot_ch = bot_ch\n int_ch = 512\n super(TopMiniConv, self).__init__()\n self.l1 = nn.Conv1d(top_ch+bot_ch,int_ch,5,dilation=2,)\n self.l2 = nn.Conv1d(int_ch,int_ch,2,dilation=1,)\n self.l3 = nn.Conv1d(int_ch,int_ch,1,dilation=1,)\n self.l4 = nn.Conv1d(int_ch,int_ch,1,dilation=1,)\n self.l5 = nn.Conv1d(int_ch,int_ch,1,dilation=1,)\n self.l6 = nn.Conv1d(int_ch,int_ch,1,dilation=1,)\n self.mean = nn.Conv1d(int_ch,bot_ch,5,dilation=1,)\n self.log_var = nn.Conv1d(int_ch,bot_ch,5,dilation=1,)\n\n def forward(self,x):\n if not self.ar:\n x[:,:,-self.bot_ch:] = 0\n x = x.permute(0,2,1)\n h1 = f.leaky_relu(self.l1(x))\n h2 = f.leaky_relu(self.l2(h1))\n h3 = f.leaky_relu(self.l4(h2))+h2\n h4 = f.leaky_relu(self.l4(h3))+h3\n h5 = f.leaky_relu(self.l5(h4))+h4\n h6 = f.leaky_relu(self.l6(h5))+h5\n mean = self.mean(h2).permute(0,2,1)\n log_var = self.log_var(h2).permute(0,2,1)\n #print(mean.shape)\n #print(mean)\n return mean,log_var\n\nclass BotMiniConv(nn.Module):\n def __init__(self,top_ch,bot_ch,bot_out,ar=True):\n self.ar = ar\n self.bot_ch = bot_ch\n int_ch = 512\n super(BotMiniConv, self).__init__()\n self.l1 = nn.Conv1d(top_ch+bot_ch,int_ch,4,dilation=1,)\n self.l2 = nn.Conv1d(int_ch,int_ch,4,dilation=1,)\n self.l3 = nn.Conv1d(int_ch,int_ch,4,dilation=1,)\n self.l4 = nn.Conv1d(int_ch,int_ch,1,dilation=1,)\n self.l5 = nn.Conv1d(int_ch,int_ch,1,dilation=1,)\n self.l6 = nn.Conv1d(int_ch,int_ch,1,dilation=1,)\n self.dist = nn.Conv1d(int_ch,bot_out,4,dilation=1,)\n\n def forward(self,x):\n if not self.ar:\n x[:,:,-self.bot_ch:] = 0\n x = x.permute(0,2,1)\n h1 = f.relu(self.l1(x))\n h2 = f.relu(self.l2(h1))\n h3 = f.relu(self.l3(h2))\n h4 = f.relu(self.l4(h3))+h3\n h5 = f.relu(self.l5(h4))+h4\n h6 = f.relu(self.l6(h5))+h5\n dist = self.dist(h6)\n #dist = dist.permute(0,2,1)\n return dist\n\n#https://stackoverflow.com/questions/48393608/pytorch-network-parameter-calculation\ndef count_parameters(model):\n total_param = 0\n for name, param in model.named_parameters():\n if param.requires_grad:\n num_param = np.prod(param.size())\n if param.dim() > 1:\n print(name, ':', 'x'.join(str(x) for x in list(param.size())), '=', num_param)\n else:\n print(name, ':', num_param)\n total_param += num_param\n return total_param\n\ndef main():\n pre_text = \"629256083683113848749365415435049699408567335747273975038007434615314954522374078191171949141418830801581429434637224555511728401165397825357655622115124820378852506676560199186630\"\n #text = \"\"\n #for x in pre_text:\n # text = \"\".join([text]+[x]*20)\n #text = str(text)\n #print(text)\n #text = get_moby_dick()\n\n #print(sorted(list(set(text))))\n #print(text_to_indices(sorted(list(set(text)))))\n books = get_texts(10)\n data = []\n total_characters = 0\n for text in books:\n if len(shitty_text_to_indices(text)) > 10000:\n data.append(np.array(shitty_text_to_indices(text)))\n total_characters += len(text)\n print(len(text))\n print(\"Total Characters:\", total_characters)\n mt = TopMiniConv(1,2,ar=False).cuda()\n mm = TopMiniConv(2,3,ar=False).cuda()\n mb = BotMiniConv(3,256,256,ar=False).cuda()\n\n print(\"MM Parameters:\", count_parameters(mm))\n\n print(\"MB Parameters:\", count_parameters(mb))\n\n l3 = (2, 1, 14, mt, optim.Adam(mt.parameters(),lr=0.0001))\n l2 = (2, 2, 14, mm, optim.Adam(mm.parameters(),lr=0.0001))\n\n l1 = (2, 3, 13, mb, optim.Adam(mb.parameters(),lr=0.0001))\n \n layers = [l1,l2,l3]\n embedding = lambda x: FT(np.eye(256)[x]).cuda()\n #embedding = lambda x: FT(np.arange(256)[x,np.newaxis]).cuda()\n update_sizes = [1024,1024,1024]\n\n\n\n #clvm = MultiTimescaleCLVM(data, embedding, layers)\n mtclvmm = MTCLVMManager(data, embedding, layers, update_sizes)\n\n mtclvmm.load(\"model\")\n losses0 = []\n losses1 = []\n losses2 = []\n losses3 = []\n for i in range(15000):\n if i < 40000:\n kl_lambda = 0.0\n #kl_lambda = math.cos(math.pi*i/15000)**2\n else:\n kl_lambda = 1\n\n kl_loss_0,lp_loss_0 = mtclvmm.cheng_update_model(0,5,kl_lambda=kl_lambda)\n kl_loss_1,lp_loss_1 = mtclvmm.cheng_update_model(1,5,kl_lambda=kl_lambda)\n kl_loss_2,lp_loss_2 = mtclvmm.cheng_update_model(2,3,kl_lambda=kl_lambda)\n\n\n string = \"{} {:15.2f} {:15.2f} {:15.2f} {:15.2f}\".format(i,lp_loss_0,kl_loss_0,kl_loss_1,kl_loss_2)\n #string = \"{} {:15.2f} {:15.2f} {:15.2f}\".format(i,lp_loss_0,kl_loss_0,kl_loss_1)\n #string = \"{} {:15.2f}\".format(i, kl_loss_1)\n #string = \"{} {:15.2f} {:15.2f}\".format(i,lp_loss_0,kl_loss_0)\n print(string)\n if i % 1 == 0:\n losses0.append(lp_loss_0)\n losses1.append(kl_loss_0)\n losses2.append(kl_loss_1)\n losses3.append(kl_loss_2)\n pass\n np.save(\"loss0.npy\", np.array(losses0,dtype=np.float32))\n np.save(\"loss1.npy\", np.array(losses1,dtype=np.float32))\n np.save(\"loss2.npy\", np.array(losses2,dtype=np.float32))\n np.save(\"loss3.npy\", np.array(losses3,dtype=np.float32))\n\n mtclvmm.save(\"model\")\n\n\n #print(\"##############################################\")\n #for i in range(20000):\n #mtclvmm.update_model(layer_index = 1)\n\n print(\"A\")\n for i in range(5):\n sample = indices_to_text(mtclvmm.generate(500).detach().cpu().numpy())\n print(sample)\n print(\"######################################################\")\n print(\"B\")\n\nif __name__ == \"__main__\":\n main()\n\n\n\n\n\n\n\n\n\n\n\n" ]
[ [ "torch.nn.functional.softmax", "numpy.sqrt", "torch.zeros", "torch.cat", "torch.sum", "torch.FloatTensor", "numpy.cat", "numpy.eye", "numpy.save", "numpy.load", "numpy.zeros", "torch.LongTensor", "numpy.random.random_integers", "torch.nn.Conv1d", "numpy.array", "numpy.sum", "torch.optim.zero_grad", "numpy.random.seed", "torch.nn.functional.cross_entropy", "torch.optim.step" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
sergioruiz/problemsolvingpython
[ "4620ac3bc09402415149840df14f051f1a44b682" ]
[ "Plot1.py" ]
[ "#https://matplotlib.org/users/pyplot_tutorial.html\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\n\r\n# evenly sampled time at 200ms intervals\r\nt = np.arange(0., 5., 0.2)\r\nprint(t)\r\n\r\n# red dashes, blue squares and green triangles\r\nplt.plot(t, t, 'r--', t, t**2, 'bs', t, t**3, 'g^')\r\nplt.plot(t, t**4, 'r*')\r\nplt.show()\r\n" ]
[ [ "matplotlib.pyplot.plot", "numpy.arange", "matplotlib.pyplot.show" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
owen1998-liu/deepdow
[ "a815fb8072015b79e90aef619c196ea9a9389e7f" ]
[ "examples/var_model.py" ]
[ "\"\"\"\n=====================\nVector autoregression\n=====================\n\nThis example demonstrates how one can validate :code:`deepdow` on synthetic data.\nWe choose to model our returns with the vector autoregression model (VAR).\nThis model links future returns to lagged returns with a linear\nmodel. See [Lütkepohl2005]_ for more details. We use a stable VAR\nprocess with 12 lags and 8 assets, that is\n\n.. math::\n\n r_t = A_1 r_{t-1} + ... + A_{12} r_{t-12}\n\n\nFor this specific task, we use the :code:`LinearNet` network. It is very similar to VAR since it tries to find a linear\nmodel of all lagged variables. However, it also has purely deep learning components like dropout, batch\nnormalization and softmax allocator.\n\nTo put the performance of our network into context, we create a benchmark **VARTrue** that has access to the true\nparameters of the VAR process. We create a simple investment rule of investing all resources into the asset with the\nhighest future returns. Additionally, we also consider other benchmarks\n\n- equally weighted portfolio\n- inverse volatility\n- random allocation\n\n\nReferences\n----------\n.. [Lütkepohl2005]\n Lütkepohl, Helmut. New introduction to multiple time series analysis. Springer Science & Business Media, 2005.\n\n\n.. warning::\n\n Note that we are using the :code:`statsmodels` package to simulate the VAR process.\n\n\"\"\"\n\nimport numpy as np\nimport torch\n\nimport matplotlib.pyplot as plt\nfrom statsmodels.tsa.vector_ar.var_model import VARProcess, forecast\n\nfrom deepdow.benchmarks import OneOverN, Benchmark, InverseVolatility, Random\nfrom deepdow.callbacks import EarlyStoppingCallback\nfrom deepdow.data import InRAMDataset, RigidDataLoader\nfrom deepdow.losses import MeanReturns, SquaredWeights\nfrom deepdow.nn import LinearNet\nfrom deepdow.experiments import Run\n\n\nclass VARTrue(Benchmark):\n \"\"\"Benchmark representing the ground truth return process.\n\n Parameters\n ----------\n process : statsmodels.tsa.vector_ar.var_model.VARProcess\n The ground truth VAR process that generates the returns.\n\n \"\"\"\n\n def __init__(self, process):\n self.process = process\n\n def __call__(self, x):\n \"\"\"Invest all money into the asset with the highest return over the horizon.\"\"\"\n n_samples, n_channels, lookback, n_assets = x.shape\n\n assert n_channels == 1\n\n x_np = x.detach().numpy() # (n_samples, n_channels, lookback, n_assets)\n weights_list = [forecast(x_np[i, 0], self.process.coefs, None, 1).argmax() for i in range(n_samples)]\n\n result = torch.zeros(n_samples, n_assets).to(x.dtype)\n\n for i, w_ix in enumerate(weights_list):\n result[i, w_ix] = 1\n\n return result\n\n\ncoefs = np.load('../examples/var_coefs.npy') # (lookback, n_assets, n_assets) = (12, 8, 8)\n\n# Parameters\nlookback, _, n_assets = coefs.shape\ngap, horizon = 0, 1\nbatch_size = 256\n\n# Simulate returns\nprocess = VARProcess(coefs, None, np.eye(n_assets) * 1e-5)\ndata = process.simulate_var(10000)\nn_timesteps = len(data)\n\n# Create features and targets\nX_list, y_list = [], []\n\nfor i in range(lookback, n_timesteps - horizon - gap + 1):\n X_list.append(data[i - lookback: i, :])\n y_list.append(data[i + gap: i + gap + horizon, :])\n\nX = np.stack(X_list, axis=0)[:, None, ...]\ny = np.stack(y_list, axis=0)[:, None, ...]\n\n# Setup deepdow framework\ndataset = InRAMDataset(X, y)\n\nnetwork = LinearNet(1, lookback, n_assets, p=0.5)\ndataloader = RigidDataLoader(dataset,\n indices=list(range(5000)),\n batch_size=batch_size,\n lookback=lookback)\nval_dataloaders = {'train': dataloader,\n 'val': RigidDataLoader(dataset,\n indices=list(range(5020, 9800)),\n batch_size=batch_size,\n lookback=lookback)}\n\nrun = Run(network,\n 100 * MeanReturns(),\n dataloader,\n val_dataloaders=val_dataloaders,\n metrics={'sqweights': SquaredWeights()},\n benchmarks={'1overN': OneOverN(),\n 'VAR': VARTrue(process),\n 'Random': Random(),\n 'InverseVol': InverseVolatility()},\n optimizer=torch.optim.Adam(network.parameters(), amsgrad=True),\n callbacks=[EarlyStoppingCallback('val', 'loss')]\n )\n\nhistory = run.launch(40)\n\nfig, ax = plt.subplots(1, 1)\nax.set_title('Validation loss')\n\nper_epoch_results = history.metrics.groupby(['dataloader', 'metric', 'model', 'epoch'])['value'].mean()['val']['loss']\nour = per_epoch_results['network']\nour.plot(ax=ax, label='network')\n\nax.hlines(y=per_epoch_results['VAR'], xmin=0, xmax=len(our), color='red', label='VAR')\nax.hlines(y=per_epoch_results['1overN'], xmin=0, xmax=len(our), color='green', label='1overN')\nax.hlines(y=per_epoch_results['Random'], xmin=0, xmax=len(our), color='yellow', label='Random')\nax.hlines(y=per_epoch_results['InverseVol'], xmin=0, xmax=len(our), color='black', label='InverseVol')\n\nplt.legend()\n" ]
[ [ "matplotlib.pyplot.legend", "torch.zeros", "numpy.eye", "matplotlib.pyplot.subplots", "numpy.stack", "numpy.load" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
udayagopi587/ArealRobotics_AutonomousDrone
[ "6bc10ee167076086abb3b2eef311ae43f457f21d" ]
[ "FaceTrackingDrone/utlis.py" ]
[ "# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Tue Feb 22 23:00:07 2022\r\n\r\n@author: udaya\r\n\"\"\"\r\n\r\nfrom djitellopy import Tello\r\nimport cv2\r\nimport numpy as np\r\n \r\n \r\ndef initializeTello():\r\n myDrone = Tello()\r\n myDrone.connect()\r\n myDrone.for_back_velocity = 0\r\n myDrone.left_right_velocity = 0\r\n myDrone.up_down_velocity = 0\r\n myDrone.yaw_velocity = 0\r\n myDrone.speed = 0\r\n print(myDrone.get_battery())\r\n myDrone.streamoff() #Turning off the streams, if any preious streams were on\r\n myDrone.streamon()\r\n return myDrone\r\n \r\ndef telloGetFrame(myDrone, w= 360,h=240):\r\n myFrame = myDrone.get_frame_read()\r\n myFrame = myFrame.frame\r\n img = cv2.resize(myFrame,(w,h))\r\n return img\r\n \r\ndef findFace(img):\r\n faceCascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')\r\n imgGray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)\r\n faces = faceCascade.detectMultiScale(imgGray,1.1,6) #These parameters are scale factor and minimum neighbours, can be altered based on the accuracy.\r\n \r\n myFaceListC = [] #This stores the center faces of all the detected faces in the frame.\r\n myFaceListArea = [] #Respective area of faces detected rectangle\r\n \r\n for (x,y,w,h) in faces:\r\n cv2.rectangle(img,(x,y),(x+w,y+h),(0,0,255),2)\r\n cx = x + w//2\r\n cy = y + h//2\r\n area = w*h\r\n myFaceListArea.append(area) #Appending the area to list\r\n myFaceListC.append([cx,cy]) #Appending centers of the detected faces\r\n \r\n if len(myFaceListArea) !=0: #Checking for prescence of face in the frame\r\n i = myFaceListArea.index(max(myFaceListArea)) #Finding the largest area of the face index, that gives the closest face details\r\n return img, [myFaceListC[i],myFaceListArea[i]] #Returning the image, area at index i, \r\n else:\r\n return img,[[0,0],0]\r\n \r\ndef trackFace(myDrone,info,w,pid,pError):\r\n \r\n ## PID\r\n error = info[0][0] - w//2 #Error = cx - width of frame/2\r\n #PID is used for smooth transition of speeds, and hence PID dives the speed of drone using kp*error + kd*(error - pError), here we are not using ki\r\n speed = pid[0]*error + pid[1]*(error-pError)\r\n # The abve function may yield bigger values so limiting the value using numpy clip method.\r\n speed = int(np.clip(speed,-100,100))\r\n \r\n \r\n print(speed)\r\n if info[0][0] !=0:\r\n myDrone.yaw_velocity = speed\r\n else:\r\n myDrone.for_back_velocity = 0\r\n myDrone.left_right_velocity = 0\r\n myDrone.up_down_velocity = 0\r\n myDrone.yaw_velocity = 0\r\n error = 0\r\n if myDrone.send_rc_control: #Sending back the updated velocities to drone for maneavur\r\n myDrone.send_rc_control(myDrone.left_right_velocity,\r\n myDrone.for_back_velocity,\r\n myDrone.up_down_velocity,\r\n myDrone.yaw_velocity)\r\n return error" ]
[ [ "numpy.clip" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
unimauro/Courses
[ "81e5b9c4cbc9b875eff82f96bda7d21ec4f258b2", "81e5b9c4cbc9b875eff82f96bda7d21ec4f258b2" ]
[ "DevOps/Data_Science_in_Production/cap01/LinearRegression.py", "DevOps/Data_Science_in_Production/cap01/LoadPandasDataFrame.py" ]
[ "from sklearn.linear_model import LinearRegression\nfrom sklearn.model_selection import train_test_split\n# See Section 1.4 (Boston Hosing data set)\nbostonDF = ...\nx_train, x_test, y_train, y_test = train_test_split(\nbostonDF.drop(['label'],axis=1),bostonDF['label'],test_size=0.3)\nmodel = LinearRegression()\nmodel.fit(x_train, y_train)\nprint(\"R^2: \" + str(model.score(x_test, y_test)))\nprint(\"Mean Error: \" + str(sum(\nabs(y_test - model.predict(x_test) ))/y_test.count()))\n\n\n", "import pandas as pd\ngame_df = pd.read_csv(\"game.csv\")\nplays_df = pd.read_csv(\"game_plays.csv\")\nplays_df = plays_df.drop(['secondaryType', 'periodType',\n'dateTime', 'rink_side'], axis=1).fillna(0)\n\nimport featuretools as ft\nfrom featuretools import Feature\nes = ft.EntitySet(id=\"plays\")\n\n\nes = es.entity_from_dataframe(entity_id=\"plays\",dataframe=plays_df\n,index=\"play_id\", variable_types = {\n\"event\": ft.variable_types.Categorical,\n\"description\": ft.variable_types.Categorical })\nf1 = Feature(es[\"plays\"][\"event\"])\nf2 = Feature(es[\"plays\"][\"description\"])\nencoded, defs = ft.encode_features(plays_df, [f1, f2], top_n=10)\nencoded.reset_index(inplace=True)\nencoded.head()\n\nes = ft.EntitySet(id=\"plays\")\nes = es.entity_from_dataframe(entity_id=\"plays\",\ndataframe=encoded, index=\"play_id\")\nes = es.normalize_entity(base_entity_id=\"plays\",\nnew_entity_id=\"games\", index=\"game_id\")\nfeatures,transform=ft.dfs(entityset=es,\ntarget_entity=\"games\",max_depth=2)\nfeatures.reset_index(inplace=True)\nfeatures.head()\n\n\n" ]
[ [ "sklearn.linear_model.LinearRegression" ], [ "pandas.read_csv" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [ "2.0", "1.4", "1.1", "1.5", "1.2", "1.3" ], "scipy": [], "tensorflow": [] } ]
vishwas1234567/tensor2tensor
[ "d62e2ee1b069d3d9b327d4d2dd6f9e50b7e62bb3", "d62e2ee1b069d3d9b327d4d2dd6f9e50b7e62bb3", "d62e2ee1b069d3d9b327d4d2dd6f9e50b7e62bb3", "d62e2ee1b069d3d9b327d4d2dd6f9e50b7e62bb3", "d62e2ee1b069d3d9b327d4d2dd6f9e50b7e62bb3" ]
[ "tensor2tensor/models/research/glow.py", "tensor2tensor/models/vanilla_gan.py", "tensor2tensor/data_generators/transduction_problems_test.py", "tensor2tensor/rl/envs/tf_atari_wrappers.py", "tensor2tensor/utils/rouge_test.py" ]
[ "# coding=utf-8\n# Copyright 2019 The Tensor2Tensor Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"Glow generative model.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport numpy as np\nfrom tensor2tensor.layers import common_hparams\nfrom tensor2tensor.layers import common_layers\nfrom tensor2tensor.models.research import glow_init_hook\nfrom tensor2tensor.models.research import glow_ops\nfrom tensor2tensor.utils import contrib\nfrom tensor2tensor.utils import registry\nfrom tensor2tensor.utils import t2t_model\nimport tensorflow as tf\n\narg_scope = contrib.framework().arg_scope\nadd_arg_scope = contrib.framework().add_arg_scope\n\nGLOW_DECODE_HPARAMS = (\"identity_output=True,log_results=False,\"\n \"decode_in_memory=True,display_decoded_images=True\")\n\n\[email protected]_hparams\ndef glow_hparams():\n \"\"\"Glow Hparams.\"\"\"\n hparams = common_hparams.basic_params1()\n hparams.clip_grad_norm = None\n hparams.weight_decay = 0.0\n hparams.learning_rate_constant = 3e-4\n hparams.batch_size = 32\n # can be prev_level, prev_step or normal.\n # see: glow_ops.merge_level_and_latent_dist\n hparams.add_hparam(\"level_scale\", \"prev_level\")\n hparams.add_hparam(\"n_levels\", 3)\n hparams.add_hparam(\"n_bits_x\", 8)\n hparams.add_hparam(\"depth\", 32)\n # Activation - Relu or Gatu\n hparams.add_hparam(\"activation\", \"relu\")\n # Coupling layer, additive or affine.\n hparams.add_hparam(\"coupling\", \"affine\")\n hparams.add_hparam(\"coupling_width\", 512)\n hparams.add_hparam(\"coupling_dropout\", 0.0)\n hparams.add_hparam(\"top_prior\", \"single_conv\")\n # init_batch_size denotes the number of examples used for data-dependent\n # initialization. A higher init_batch_size is required for training\n # stability especially when hparams.batch_size is low.\n hparams.add_hparam(\"init_batch_size\", 256)\n hparams.add_hparam(\"temperature\", 1.0)\n\n return hparams\n\n\[email protected]_model\nclass Glow(t2t_model.T2TModel):\n \"\"\"Glow generative model.\n\n Reference: https://arxiv.org/abs/1807.03039\"\"\"\n\n def init_preprocess(self, features):\n \"\"\"Preprocessing as per the input modality.\"\"\"\n return features\n\n def preprocess(self, x):\n \"\"\"Normalize x.\n\n Args:\n x: 4-D Tensor.\n\n Returns:\n x: Scaled such that x lies in-between -0.5 and 0.5\n \"\"\"\n n_bits_x = self.hparams.n_bits_x\n n_bins = 2**n_bits_x\n x = tf.cast(x, dtype=tf.float32)\n if n_bits_x < 8:\n x = tf.floor(x / 2 ** (8 - n_bits_x))\n x = x / n_bins - 0.5\n return x\n\n @property\n def temperature(self):\n if self.is_predicting:\n return self.hparams.temperature\n return 1.0\n\n @property\n def is_training(self):\n return self.hparams.mode == tf.estimator.ModeKeys.TRAIN\n\n def infer(self, features, *args, **kwargs): # pylint: disable=arguments-differ\n del args, kwargs\n x = features[\"inputs\"]\n batch_size = common_layers.shape_list(x)[0]\n features[\"targets\"] = tf.zeros(shape=(batch_size, 1, 1, 1))\n _, _ = self(features) # pylint: disable=not-callable\n\n ops = [glow_ops.get_variable_ddi, glow_ops.actnorm, glow_ops.get_dropout]\n var_scope = tf.variable_scope(\"glow/body\", reuse=True)\n # If eps=None, images are sampled from the prior.\n with arg_scope(ops, init=False), var_scope:\n predictions, _, _, _ = glow_ops.encoder_decoder(\n \"codec\", self.z_sample, self.hparams, eps=None, reverse=True,\n temperature=self.temperature)\n\n return glow_ops.postprocess(predictions, self.hparams.n_bits_x)\n\n def create_init_batch(self, features):\n \"\"\"Returns a batch of size \"hparams.init_batch_size\" for initialization.\n\n Args:\n features: input features.\n Returns:\n init_features: initialization features.\n \"\"\"\n train_dataset = self.hparams.problem.dataset(\n tf.estimator.ModeKeys.TRAIN, hparams=self.hparams)\n train_dataset = train_dataset.batch(self.hparams.init_batch_size)\n train_dataset = self.init_preprocess(train_dataset)\n return train_dataset.make_one_shot_iterator().get_next()\n\n @staticmethod\n def train_hooks(hook_context):\n del hook_context\n return [glow_init_hook.GlowInitHook()]\n\n def top_prior(self):\n \"\"\"Objective based on the prior over latent z.\n\n Returns:\n dist: instance of tfp.distributions.Normal, prior distribution.\n \"\"\"\n return glow_ops.top_prior(\n \"top_prior\", self.z_top_shape, learn_prior=self.hparams.top_prior,\n temperature=self.temperature)\n\n def body(self, features):\n exp_coupling = [\"affine\", \"additive\"]\n if self.hparams.coupling not in exp_coupling:\n raise ValueError(\"Expected hparams.coupling to be in %s, got %s\" %\n (exp_coupling, self.hparams.coupling))\n if self.is_training:\n init_features = self.create_init_batch(features)\n init_op = self.objective_tower(init_features, init=True)\n init_op = tf.Print(\n init_op, [init_op], message=\"Triggering data-dependent init.\",\n first_n=20)\n tf.add_to_collection(\"glow_init_op\", init_op)\n train_op = self.objective_tower(features, init=False)\n return tf.zeros_like(features[\"targets\"]), {\"training\": train_op}\n\n def objective_tower(self, features, init=True):\n \"\"\"Objective in terms of bits-per-pixel.\n\n Args:\n features: dict of tensors with \"features\" and \"targets\" keys.\n init: Whether or not to run data-dependent init.\n Returns:\n objective: float, bits-per-pixel.\n \"\"\"\n x = features[\"inputs\"]\n\n # Scale x such that the pixels lie in-between -0.5 and.0.5\n x = self.preprocess(x)\n x, objective = glow_ops.uniform_binning_correction(x)\n\n # The arg_scope call ensures that the actnorm parameters are set such that\n # the per-channel output activations have zero mean and unit variance\n # ONLY during the first step. After that the parameters are learned\n # through optimisation.\n ops = [glow_ops.get_variable_ddi, glow_ops.actnorm, glow_ops.get_dropout]\n with arg_scope(ops, init=init):\n encoder = glow_ops.encoder_decoder\n\n\n self.z, encoder_objective, self.eps, _, _ = encoder(\n \"codec\", x, self.hparams, eps=None, reverse=False)\n objective += encoder_objective\n\n self.z_top_shape = common_layers.shape_list(self.z)\n prior_dist = self.top_prior()\n prior_objective = tf.reduce_sum(\n prior_dist.log_prob(self.z), axis=[1, 2, 3])\n self.z_sample = prior_dist.sample()\n objective += prior_objective\n\n # bits per pixel\n _, h, w, c = common_layers.shape_list(x)\n objective = -objective / (np.log(2) * h * w * c)\n return objective\n", "# coding=utf-8\n# Copyright 2019 The Tensor2Tensor Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"Simple Generative Adversarial Model with two linear layers.\n\nExample of how to create a GAN in T2T.\n\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nfrom tensor2tensor.layers import common_hparams\nfrom tensor2tensor.layers import common_layers\nfrom tensor2tensor.utils import registry\nfrom tensor2tensor.utils import t2t_model\n\nimport tensorflow.compat.v1 as tf\n\n\ndef lrelu(input_, leak=0.2, name=\"lrelu\"):\n return tf.maximum(input_, leak * input_, name=name)\n\n\ndef deconv2d(\n input_, output_shape, k_h, k_w, d_h, d_w, stddev=0.02, name=\"deconv2d\"):\n \"\"\"Deconvolution layer.\"\"\"\n with tf.variable_scope(name):\n w = tf.get_variable(\n \"w\", [k_h, k_w, output_shape[-1], input_.get_shape()[-1]],\n initializer=tf.random_normal_initializer(stddev=stddev))\n deconv = tf.nn.conv2d_transpose(\n input_, w, output_shape=output_shape, strides=[1, d_h, d_w, 1])\n biases = tf.get_variable(\n \"biases\", [output_shape[-1]], initializer=tf.constant_initializer(0.0))\n return tf.reshape(tf.nn.bias_add(deconv, biases), deconv.get_shape())\n\n\ndef reverse_gradient(x):\n return -x + tf.stop_gradient(2 * x)\n\n\nclass AbstractGAN(t2t_model.T2TModel):\n \"\"\"Base class for all GANs.\"\"\"\n\n def discriminator(self, x, is_training, reuse=False):\n \"\"\"Discriminator architecture based on InfoGAN.\n\n Args:\n x: input images, shape [bs, h, w, channels]\n is_training: boolean, are we in train or eval model.\n reuse: boolean, should params be re-used.\n\n Returns:\n out_logit: the output logits (before sigmoid).\n \"\"\"\n hparams = self.hparams\n with tf.variable_scope(\n \"discriminator\", reuse=reuse,\n initializer=tf.random_normal_initializer(stddev=0.02)):\n batch_size, height, width = common_layers.shape_list(x)[:3]\n # Mapping x from [bs, h, w, c] to [bs, 1]\n net = tf.layers.conv2d(x, 64, (4, 4), strides=(2, 2),\n padding=\"SAME\", name=\"d_conv1\")\n # [bs, h/2, w/2, 64]\n net = lrelu(net)\n net = tf.layers.conv2d(net, 128, (4, 4), strides=(2, 2),\n padding=\"SAME\", name=\"d_conv2\")\n # [bs, h/4, w/4, 128]\n if hparams.discriminator_batchnorm:\n net = tf.layers.batch_normalization(net, training=is_training,\n momentum=0.999, name=\"d_bn2\")\n net = lrelu(net)\n size = height * width\n net = tf.reshape(net, [batch_size, size * 8]) # [bs, h * w * 8]\n net = tf.layers.dense(net, 1024, name=\"d_fc3\") # [bs, 1024]\n if hparams.discriminator_batchnorm:\n net = tf.layers.batch_normalization(net, training=is_training,\n momentum=0.999, name=\"d_bn3\")\n net = lrelu(net)\n return net\n\n def generator(self, z, is_training, out_shape):\n \"\"\"Generator outputting image in [0, 1].\"\"\"\n hparams = self.hparams\n height, width, c_dim = out_shape\n batch_size = hparams.batch_size\n with tf.variable_scope(\n \"generator\",\n initializer=tf.random_normal_initializer(stddev=0.02)):\n net = tf.layers.dense(z, 1024, name=\"g_fc1\")\n net = tf.layers.batch_normalization(net, training=is_training,\n momentum=0.999, name=\"g_bn1\")\n net = lrelu(net)\n net = tf.layers.dense(net, 128 * (height // 4) * (width // 4),\n name=\"g_fc2\")\n net = tf.layers.batch_normalization(net, training=is_training,\n momentum=0.999, name=\"g_bn2\")\n net = lrelu(net)\n net = tf.reshape(net, [batch_size, height // 4, width // 4, 128])\n net = deconv2d(net, [batch_size, height // 2, width // 2, 64],\n 4, 4, 2, 2, name=\"g_dc3\")\n net = tf.layers.batch_normalization(net, training=is_training,\n momentum=0.999, name=\"g_bn3\")\n net = lrelu(net)\n net = deconv2d(net, [batch_size, height, width, c_dim],\n 4, 4, 2, 2, name=\"g_dc4\")\n out = tf.nn.sigmoid(net)\n return common_layers.convert_real_to_rgb(out)\n\n def losses(self, inputs, generated):\n \"\"\"Return the losses dictionary.\"\"\"\n raise NotImplementedError\n\n def body(self, features):\n \"\"\"Body of the model.\n\n Args:\n features: a dictionary with the tensors.\n\n Returns:\n A pair (predictions, losses) where predictions is the generated image\n and losses is a dictionary of losses (that get added for the final loss).\n \"\"\"\n features[\"targets\"] = features[\"inputs\"]\n is_training = self.hparams.mode == tf.estimator.ModeKeys.TRAIN\n\n # Input images.\n inputs = tf.to_float(features[\"targets_raw\"])\n\n # Noise vector.\n z = tf.random_uniform([self.hparams.batch_size,\n self.hparams.bottleneck_bits],\n minval=-1, maxval=1, name=\"z\")\n\n # Generator output: fake images.\n out_shape = common_layers.shape_list(inputs)[1:4]\n g = self.generator(z, is_training, out_shape)\n\n losses = self.losses(inputs, g) # pylint: disable=not-callable\n\n summary_g_image = tf.reshape(\n g[0, :], [1] + common_layers.shape_list(inputs)[1:])\n tf.summary.image(\"generated\", summary_g_image, max_outputs=1)\n\n if is_training: # Returns an dummy output and the losses dictionary.\n return tf.zeros_like(inputs), losses\n return tf.reshape(g, tf.shape(inputs)), losses\n\n def top(self, body_output, features):\n \"\"\"Override the top function to not do anything.\"\"\"\n return body_output\n\n\[email protected]_model\nclass SlicedGan(AbstractGAN):\n \"\"\"Sliced GAN for demonstration.\"\"\"\n\n def losses(self, inputs, generated):\n \"\"\"Losses in the sliced case.\"\"\"\n is_training = self.hparams.mode == tf.estimator.ModeKeys.TRAIN\n def discriminate(x):\n return self.discriminator(x, is_training=is_training, reuse=False)\n generator_loss = common_layers.sliced_gan_loss(\n inputs, reverse_gradient(generated), discriminate,\n self.hparams.num_sliced_vecs)\n return {\"training\": - generator_loss}\n\n def infer(self, *args, **kwargs): # pylint: disable=arguments-differ\n del args, kwargs\n\n try:\n num_channels = self.hparams.problem.num_channels\n except AttributeError:\n num_channels = 1\n\n with tf.variable_scope(\"body/vanilla_gan\", reuse=tf.AUTO_REUSE):\n hparams = self.hparams\n z = tf.random_uniform([hparams.batch_size, hparams.bottleneck_bits],\n minval=-1, maxval=1, name=\"z\")\n out_shape = (hparams.sample_height, hparams.sample_width, num_channels)\n g_sample = self.generator(z, False, out_shape)\n return g_sample\n\n\[email protected]_hparams\ndef sliced_gan():\n \"\"\"Basic parameters for a vanilla_gan.\"\"\"\n hparams = common_hparams.basic_params1()\n hparams.optimizer = \"adam\"\n hparams.learning_rate_constant = 0.0002\n hparams.learning_rate_warmup_steps = 500\n hparams.learning_rate_schedule = \"constant * linear_warmup\"\n hparams.label_smoothing = 0.0\n hparams.batch_size = 128\n hparams.hidden_size = 128\n hparams.initializer = \"uniform_unit_scaling\"\n hparams.initializer_gain = 1.0\n hparams.weight_decay = 1e-6\n hparams.kernel_height = 4\n hparams.kernel_width = 4\n hparams.bottleneck_bits = 128\n hparams.add_hparam(\"discriminator_batchnorm\", True)\n hparams.add_hparam(\"num_sliced_vecs\", 4096)\n return hparams\n", "# coding=utf-8\n# Copyright 2019 The Tensor2Tensor Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"Tests for tensor2tensor.data_generators.transduction_problems.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport shutil\nimport tempfile\n\nfrom absl.testing import parameterized\n\nimport numpy as np\n\nfrom tensor2tensor.data_generators import problem\nfrom tensor2tensor.data_generators import transduction_problems\n\nimport tensorflow.compat.v1 as tf\n\n\nclass TransductionProblem(parameterized.TestCase):\n\n def setUp(self):\n super(TransductionProblem, self).setUp()\n # Create a temporary directory\n self.test_dir = tempfile.mkdtemp()\n\n def tearDown(self):\n super(TransductionProblem, self).tearDown()\n # Remove the directory after the test\n shutil.rmtree(self.test_dir)\n\n @parameterized.named_parameters(\n ('CopySequence',\n transduction_problems.CopySequence(),\n lambda x: x),\n ('CopySequenceSmall',\n transduction_problems.CopySequenceSmall(),\n lambda x: x),\n ('FlipBiGramSequence',\n transduction_problems.FlipBiGramSequence(),\n lambda x: [x[i+1] if i%2 == 0 else x[i-1] for i in range(len(x))]),\n ('ReverseSequence',\n transduction_problems.ReverseSequence(),\n lambda x: x[::-1]),\n ('ReverseSequenceSmall',\n transduction_problems.ReverseSequenceSmall(),\n lambda x: x[::-1]),\n )\n def testTransduction(self, p, transformation):\n data_dir = ''\n dataset_split = problem.DatasetSplit.TEST\n for sample in p.generate_samples(data_dir, self.test_dir, dataset_split):\n input_tokens = sample['inputs'].split(' ')\n target_tokens = sample['targets'].split(' ')\n self.assertBetween(len(input_tokens),\n p.min_sequence_length(dataset_split),\n p.max_sequence_length(dataset_split))\n self.assertBetween(len(target_tokens),\n p.min_sequence_length(dataset_split),\n p.max_sequence_length(dataset_split))\n\n transformed_inputs = np.array(transformation(input_tokens))\n\n np.testing.assert_equal(transformed_inputs, target_tokens)\n\n\nif __name__ == '__main__':\n tf.test.main()\n", "# coding=utf-8\n# Copyright 2019 The Tensor2Tensor Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"Batch of environments inside the TensorFlow graph.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nfrom six.moves import range # pylint: disable=redefined-builtin\n\nfrom tensor2tensor.rl.envs.in_graph_batch_env import InGraphBatchEnv\n\nimport tensorflow.compat.v1 as tf\n\n\nclass WrapperBase(InGraphBatchEnv):\n \"\"\"Base wrapper class.\"\"\"\n\n def __init__(self, batch_env):\n super(WrapperBase, self).__init__(\n batch_env.observ_space, batch_env.action_space)\n self._length = len(batch_env)\n self._batch_env = batch_env\n\n def initialize(self, sess):\n \"\"\"Initializations to be run once the tf.Session is available.\"\"\"\n pass\n\n @property\n def observ(self):\n \"\"\"Access the variable holding the current observation.\"\"\"\n return self._observ.read_value()\n\n @property\n def observ_shape(self):\n return self._batch_env.observ_shape\n\n def __len__(self):\n \"\"\"Number of combined environments.\"\"\"\n return self._length\n\n def _reset_non_empty(self, indices):\n # pylint: disable=protected-access\n new_values = self._batch_env._reset_non_empty(indices)\n # pylint: enable=protected-access\n assign_op = tf.scatter_update(self._observ, indices, new_values)\n with tf.control_dependencies([assign_op]):\n return tf.identity(new_values)\n\n def _transform_history_observations(self, frames):\n \"\"\"Applies a wrapper-specific transformation to the history observations.\n\n Overridden in wrappers that alter observations.\n\n Args:\n frames: A tensor of history frames to transform.\n\n Returns:\n a tensor of transformed frames.\n \"\"\"\n return frames\n\n @property\n def history_observations(self):\n \"\"\"Returns observations from the root simulated env's history_buffer.\n\n Transforms them with a wrapper-specific function if necessary.\n\n Raises:\n AttributeError: if root env doesn't have a history_buffer (i.e. is not\n simulated).\n \"\"\"\n return self._transform_history_observations(\n self._batch_env.history_observations\n )\n\n\nclass StackWrapper(WrapperBase):\n \"\"\"A wrapper which stacks previously seen frames.\"\"\"\n\n def __init__(self, batch_env, history=4):\n super(StackWrapper, self).__init__(batch_env)\n self.history = history\n self.old_shape = batch_env.observ_shape\n # TODO(afrozm): Make into tf.get_variable and use_resource=True\n self._observ = tf.Variable(\n tf.zeros((len(self),) + self.observ_shape, self.observ_dtype),\n trainable=False)\n\n def __str__(self):\n return \"StackWrapper(%s)\" % str(self._batch_env)\n\n @property\n def observ_shape(self):\n return (self.history,) + self.old_shape\n\n def simulate(self, action):\n reward, done = self._batch_env.simulate(action)\n with tf.control_dependencies([reward, done]):\n new_observ = tf.expand_dims(self._batch_env.observ, axis=1)\n\n # If we shouldn't stack, i.e. self.history == 1, then just assign\n # new_observ to self._observ and return from here.\n if self.history == 1:\n with tf.control_dependencies([self._observ.assign(new_observ)]):\n return tf.identity(reward), tf.identity(done)\n\n # If we should stack, then do the required work.\n old_observ = tf.gather(\n self._observ.read_value(),\n list(range(1, self.history)),\n axis=1)\n with tf.control_dependencies([new_observ, old_observ]):\n with tf.control_dependencies([self._observ.assign(\n tf.concat([old_observ, new_observ], axis=1))]):\n return tf.identity(reward), tf.identity(done)\n\n def _reset_non_empty(self, indices):\n # pylint: disable=protected-access\n new_values = self._batch_env._reset_non_empty(indices)\n # pylint: enable=protected-access\n initial_frames = getattr(self._batch_env, \"history_observations\", None)\n\n num_dimensions_in_env_observation = len(self.old_shape)\n\n if initial_frames is None:\n inx = [1, self.history] + ([1] * num_dimensions_in_env_observation)\n initial_frames = tf.tile(tf.expand_dims(new_values, axis=1), inx)\n with tf.control_dependencies([new_values]):\n assign_op = tf.scatter_update(self._observ, indices, initial_frames)\n with tf.control_dependencies([assign_op]):\n return tf.gather(self.observ, indices)\n\n def _transform_history_observations(self, frames):\n # Should be implemented if ever two StackWrappers are to be used together.\n raise NotImplementedError\n", "# coding=utf-8\n# Copyright 2019 The Tensor2Tensor Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"Tests for Rouge metric.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\nimport numpy as np\nfrom tensor2tensor.utils import rouge\n\nimport tensorflow.compat.v1 as tf\n\n\nclass TestRouge2Metric(tf.test.TestCase):\n \"\"\"Tests the rouge-2 metric.\"\"\"\n\n def testRouge2Identical(self):\n hypotheses = np.array([[1, 2, 3, 4, 5, 1, 6, 7, 0],\n [1, 2, 3, 4, 5, 1, 6, 8, 7]])\n references = np.array([[1, 2, 3, 4, 5, 1, 6, 7, 0],\n [1, 2, 3, 4, 5, 1, 6, 8, 7]])\n self.assertAllClose(rouge.rouge_n(hypotheses, references), 1.0, atol=1e-03)\n\n def testRouge2Disjoint(self):\n hypotheses = np.array([[1, 2, 3, 4, 5, 1, 6, 7, 0],\n [1, 2, 3, 4, 5, 1, 6, 8, 7]])\n references = np.array([[8, 9, 10, 11, 12, 13, 14, 15, 16, 17],\n [9, 10, 11, 12, 13, 14, 15, 16, 17, 0]])\n self.assertEqual(rouge.rouge_n(hypotheses, references), 0.0)\n\n def testRouge2PartialOverlap(self):\n hypotheses = np.array([[1, 2, 3, 4, 5, 1, 6, 7, 0],\n [1, 2, 3, 4, 5, 1, 6, 8, 7]])\n references = np.array([[1, 9, 2, 3, 4, 5, 1, 10, 6, 7],\n [1, 9, 2, 3, 4, 5, 1, 10, 6, 7]])\n self.assertAllClose(rouge.rouge_n(hypotheses, references), 0.53, atol=1e-03)\n\n\nclass TestRougeLMetric(tf.test.TestCase):\n \"\"\"Tests the rouge-l metric.\"\"\"\n\n def testRougeLIdentical(self):\n hypotheses = np.array([[1, 2, 3, 4, 5, 1, 6, 7, 0],\n [1, 2, 3, 4, 5, 1, 6, 8, 7]])\n references = np.array([[1, 2, 3, 4, 5, 1, 6, 7, 0],\n [1, 2, 3, 4, 5, 1, 6, 8, 7]])\n self.assertAllClose(\n rouge.rouge_l_sentence_level(hypotheses, references), 1.0, atol=1e-03)\n\n def testRougeLDisjoint(self):\n hypotheses = np.array([[1, 2, 3, 4, 5, 1, 6, 7, 0],\n [1, 2, 3, 4, 5, 1, 6, 8, 7]])\n references = np.array([[8, 9, 10, 11, 12, 13, 14, 15, 16, 17],\n [9, 10, 11, 12, 13, 14, 15, 16, 17, 0]])\n self.assertEqual(rouge.rouge_l_sentence_level(hypotheses, references), 0.0)\n\n def testRougeLPartialOverlap(self):\n hypotheses = np.array([[1, 2, 3, 4, 5, 1, 6, 7, 0],\n [1, 2, 3, 4, 5, 1, 6, 8, 7]])\n references = np.array([[1, 9, 2, 3, 4, 5, 1, 10, 6, 7],\n [1, 9, 2, 3, 4, 5, 1, 10, 6, 7]])\n self.assertAllClose(\n rouge.rouge_l_sentence_level(hypotheses, references), 0.837, atol=1e-03)\n\n\nclass TestRougeMetricsE2E(tf.test.TestCase):\n \"\"\"Tests the rouge metrics end-to-end.\"\"\"\n\n def testRouge2MetricE2E(self):\n vocab_size = 4\n batch_size = 12\n seq_length = 12\n predictions = tf.one_hot(\n np.random.randint(vocab_size, size=(batch_size, seq_length, 1, 1)),\n depth=4,\n dtype=tf.float32)\n targets = np.random.randint(4, size=(12, 12, 1, 1))\n with self.test_session() as session:\n scores, _ = rouge.rouge_2_fscore(predictions,\n tf.constant(targets, dtype=tf.int32))\n a = tf.reduce_mean(scores)\n session.run(tf.global_variables_initializer())\n session.run(a)\n\n def testRougeLMetricE2E(self):\n vocab_size = 4\n batch_size = 12\n seq_length = 12\n predictions = tf.one_hot(\n np.random.randint(vocab_size, size=(batch_size, seq_length, 1, 1)),\n depth=4,\n dtype=tf.float32)\n targets = np.random.randint(4, size=(12, 12, 1, 1))\n with self.test_session() as session:\n scores, _ = rouge.rouge_l_fscore(\n predictions,\n tf.constant(targets, dtype=tf.int32))\n a = tf.reduce_mean(scores)\n session.run(tf.global_variables_initializer())\n session.run(a)\n\n\nif __name__ == \"__main__\":\n tf.test.main()\n" ]
[ [ "numpy.log", "tensorflow.Print", "tensorflow.zeros", "tensorflow.cast", "tensorflow.floor", "tensorflow.zeros_like", "tensorflow.variable_scope", "tensorflow.add_to_collection" ], [ "tensorflow.compat.v1.random_normal_initializer", "tensorflow.compat.v1.nn.sigmoid", "tensorflow.compat.v1.layers.conv2d", "tensorflow.compat.v1.summary.image", "tensorflow.compat.v1.reshape", "tensorflow.compat.v1.to_float", "tensorflow.compat.v1.layers.batch_normalization", "tensorflow.compat.v1.maximum", "tensorflow.compat.v1.constant_initializer", "tensorflow.compat.v1.shape", "tensorflow.compat.v1.stop_gradient", "tensorflow.compat.v1.random_uniform", "tensorflow.compat.v1.zeros_like", "tensorflow.compat.v1.nn.bias_add", "tensorflow.compat.v1.variable_scope", "tensorflow.compat.v1.layers.dense", "tensorflow.compat.v1.nn.conv2d_transpose" ], [ "numpy.testing.assert_equal", "tensorflow.compat.v1.test.main" ], [ "tensorflow.compat.v1.expand_dims", "tensorflow.compat.v1.concat", "tensorflow.compat.v1.control_dependencies", "tensorflow.compat.v1.gather", "tensorflow.compat.v1.scatter_update", "tensorflow.compat.v1.identity" ], [ "tensorflow.compat.v1.test.main", "tensorflow.compat.v1.reduce_mean", "tensorflow.compat.v1.global_variables_initializer", "numpy.array", "tensorflow.compat.v1.constant", "numpy.random.randint" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.10", "1.12", "1.4", "1.13", "1.5", "1.7", "0.12", "1.0", "1.2" ] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
AliKhoda/DeepFish
[ "6769e83ab0b586e49f48e28f70607d33b5c36718" ]
[ "src/wrappers/clf_wrapper.py" ]
[ "import torch\nimport torch.nn.functional as F\nimport torchvision\nfrom torchvision import transforms\nimport os\nimport numpy as np\nimport time\nfrom src import utils as ut\nfrom sklearn.metrics import confusion_matrix\nimport skimage\nfrom src import wrappers\nfrom torchvision import transforms\n\nfrom haven import haven_utils as hu\n\nclass ClfWrapper(torch.nn.Module):\n def __init__(self, model, opt):\n super().__init__()\n self.model = model\n self.opt = opt\n\n def train_on_loader(self, train_loader):\n return wrappers.train_on_loader(self, train_loader)\n\n def val_on_loader(self, val_loader):\n val_monitor = ClfMonitor()\n return wrappers.val_on_loader(self, val_loader, val_monitor=val_monitor)\n\n def vis_on_loader(self, vis_loader, savedir):\n return wrappers.vis_on_loader(self, vis_loader, savedir=savedir)\n\n def train_on_batch(self, batch, **extras):\n self.opt.zero_grad()\n \n labels = batch[\"labels\"].cuda()\n logits = self.model.forward(batch[\"images\"].cuda())\n loss_clf = F.binary_cross_entropy_with_logits(logits.squeeze(),\n labels.squeeze().float(), reduction=\"mean\")\n loss_clf.backward()\n\n self.opt.step()\n\n return {\"loss_clf\":loss_clf.item()}\n\n def val_on_batch(self, batch, **extras):\n pred_clf = self.predict_on_batch(batch)\n return (pred_clf.cpu().numpy().ravel() != batch[\"labels\"].numpy().ravel())\n \n def predict_on_batch(self, batch):\n images = batch[\"images\"].cuda()\n n = images.shape[0]\n logits = self.model.forward(images)\n return (torch.sigmoid(logits) > 0.5).float()\n \n def vis_on_batch(self, batch, savedir_image):\n self.eval()\n # clf \n pred_labels = float(self.predict_on_batch(batch))\n img = hu.get_image(batch[\"image_original\"], denorm=\"rgb\")\n hu.save_image(savedir_image, np.array(img))\n hu.save_json(savedir_image.replace(\".png\",\".json\"), \n {\"pred_label\":float(pred_labels), \"gt_label\": float(batch[\"labels\"])})\n\n\nclass ClfMonitor:\n def __init__(self):\n self.corrects = 0\n self.n_samples = 0\n\n def add(self, corrects):\n self.corrects += corrects.sum()\n self.n_samples += corrects.shape[0]\n\n def get_avg_score(self):\n return {\"val_clf\": self.corrects/ self.n_samples}" ]
[ [ "torch.sigmoid", "numpy.array" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
lweasel/piquant
[ "d9e8a15fd152413e85c42c3c6bc6e6afec5e7811" ]
[ "test/test_statistics.py" ]
[ "import piquant.statistics as statistics\nimport piquant.tpms as t\nimport numpy as np\nimport pandas as pd\nimport scipy.stats as scistats\nimport test_tpms\n\n\ndef _get_test_tpms():\n tpms = pd.DataFrame.from_dict({\n t.REAL_TPM: test_tpms.REAL_TPMS_VALS,\n t.CALCULATED_TPM: test_tpms.CALC_TPMS_VALS,\n test_tpms.GROUP_TEST_COL: test_tpms.GROUPS\n })\n\n t.calculate_log_ratios(tpms)\n t.calculate_percent_error(tpms)\n t.mark_positives_and_negatives(0.1, tpms)\n\n return tpms, t.get_true_positives(tpms)\n\n\ndef __get_test_grouped_tpms():\n tpms, tp_tpms = _get_test_tpms()\n\n grouped = tpms.groupby(test_tpms.GROUP_TEST_COL)\n tp_grouped = tp_tpms.groupby(test_tpms.GROUP_TEST_COL)\n summary = grouped.describe()\n tp_summary = tp_grouped.describe()\n\n return grouped, summary, tp_grouped, tp_summary\n\n\ndef _tpm_pairs(filter=lambda r, c: True):\n return [(r, c) for r, c in zip(test_tpms.REAL_TPMS_VALS,\n test_tpms.CALC_TPMS_VALS)\n if filter(r, c)]\n\n\ndef _tp_tpm_pairs():\n return _tpm_pairs(lambda r, c: test_tpms._true_positive(r, c))\n\n\ndef _group_tpm_pairs(group_val, filter=lambda r, c: True):\n return [(r, c) for r, c, gv in\n zip(test_tpms.REAL_TPMS_VALS,\n test_tpms.CALC_TPMS_VALS,\n test_tpms.GROUPS) if\n (gv == group_val and filter(r, c))]\n\n\ndef _group_tp_tpm_pairs(group_val):\n return _group_tpm_pairs(\n group_val, lambda r, c: test_tpms._true_positive(r, c))\n\n\ndef _check_statistic_value(stat_class, calculator, pair_func):\n tpms, tp_tpms = _get_test_tpms()\n stat = stat_class()\n correct_value = calculator(pair_func())\n assert stat.calculate(tpms, tp_tpms) == correct_value\n\n\ndef _check_grouped_statistic_values(stat_class, calculator, grouped_pair_func):\n g, s, tp_g, tp_s = __get_test_grouped_tpms()\n stat = stat_class()\n grouped_stats = stat.calculate_grouped(g, s, tp_g, tp_s)\n correct_value_calculator = lambda x: calculator(grouped_pair_func(x))\n group_count_test = \\\n lambda x: grouped_stats.ix[x] == correct_value_calculator(x)\n assert all([group_count_test(gv) for gv in set(test_tpms.GROUPS)])\n\n\ndef test_get_statistics_returns_statistics_instances():\n stats = statistics.get_statistics()\n assert all([isinstance(s, statistics._BaseStatistic) for s in stats])\n\n\ndef test_get_graphable_statistics_returns_subset_of_statistics():\n stats = statistics.get_statistics()\n g_stats = statistics.get_graphable_statistics()\n assert g_stats <= stats\n\n\ndef test_get_graphable_statistics_returns_graphable_instances():\n g_stats = statistics.get_graphable_statistics()\n assert all([s.graphable for s in g_stats])\n\n\ndef _number_of_tpms(tpm_pairs):\n return len(tpm_pairs)\n\n\ndef test_number_of_tpms_statistic_calculates_correct_value():\n _check_statistic_value(\n statistics._NumberOfTPMs, _number_of_tpms, _tpm_pairs)\n\n\ndef test_number_of_tpms_statistic_calculates_correct_grouped_values():\n _check_grouped_statistic_values(\n statistics._NumberOfTPMs, _number_of_tpms, _group_tpm_pairs)\n\n\ndef test_number_of_true_positive_tpms_statistic_calculates_correct_value():\n _check_statistic_value(\n statistics._NumberOfTruePositiveTPMs,\n _number_of_tpms, _tp_tpm_pairs)\n\n\ndef test_number_of_true_positive_tpms_statistic_calculates_correct_grouped_values():\n _check_grouped_statistic_values(\n statistics._NumberOfTruePositiveTPMs,\n _number_of_tpms, _group_tp_tpm_pairs)\n\n\ndef _spearman(tpm_pairs):\n rs, cs = zip(*tpm_pairs)\n return scistats.spearmanr(np.array(rs), np.array(cs))[0]\n\n\ndef test_spearman_correlation_statistic_calculates_correct_value():\n _check_statistic_value(\n statistics._SpearmanCorrelation, _spearman, _tp_tpm_pairs)\n\n\ndef test_spearman_correlation_statistic_calculates_correct_grouped_values():\n _check_grouped_statistic_values(\n statistics._SpearmanCorrelation, _spearman, _group_tp_tpm_pairs)\n\n\ndef _error_fraction(tpm_pairs):\n error_percent = lambda r, c: abs(100 * (c - r) / float(r))\n above_threshold = \\\n [r for r, c in tpm_pairs if\n error_percent(r, c) >\n statistics._TruePositiveErrorFraction.ERROR_FRACTION_THRESHOLD]\n return len(above_threshold) / float(len(tpm_pairs))\n\n\ndef test_true_positive_error_fraction_statistic_calculates_correct_value():\n _check_statistic_value(\n statistics._TruePositiveErrorFraction,\n _error_fraction, _tp_tpm_pairs)\n\n\ndef test_true_positive_error_fraction_statistic_calculates_correct_grouped_values():\n _check_grouped_statistic_values(\n statistics._TruePositiveErrorFraction,\n _error_fraction, _group_tp_tpm_pairs)\n\n\ndef _median_percent_error(tpm_pairs):\n error_percent = lambda r, c: 100 * (c - r) / float(r)\n percent_errors = [error_percent(r, c) for r, c in tpm_pairs]\n return np.median(percent_errors)\n\n\ndef test_median_percent_error_statistic_calculates_correct_value():\n _check_statistic_value(\n statistics._MedianPercentError,\n _median_percent_error, _tp_tpm_pairs)\n\n\ndef test_median_percent_error_statistic_calculates_correct_grouped_values():\n _check_grouped_statistic_values(\n statistics._MedianPercentError,\n _median_percent_error, _group_tp_tpm_pairs)\n\n\ndef _sensitivity(tpm_pairs):\n num_tp = sum([test_tpms._true_positive(r, c) for r, c in tpm_pairs])\n num_fn = sum([test_tpms._false_negative(r, c) for r, c in tpm_pairs])\n return float(num_tp) / (num_tp + num_fn)\n\n\ndef test_sensitivity_statistic_calculates_correct_value():\n _check_statistic_value(\n statistics._Sensitivity, _sensitivity, _tpm_pairs)\n\n\ndef test_sensitivity_statistic_calculates_correct_grouped_values():\n _check_grouped_statistic_values(\n statistics._Sensitivity, _sensitivity, _group_tpm_pairs)\n\n\ndef _specificity(tpm_pairs):\n num_fp = sum([test_tpms._false_positive(r, c) for r, c in tpm_pairs])\n num_tn = sum([test_tpms._true_negative(r, c) for r, c in tpm_pairs])\n return float(num_tn) / (num_tn + num_fp)\n\n\ndef test_specificity_statistic_calculates_correct_value():\n _check_statistic_value(\n statistics._Specificity, _specificity, _tpm_pairs)\n\n\ndef test_specificity_statistic_calculates_correct_grouped_values():\n _check_grouped_statistic_values(\n statistics._Specificity, _specificity, _group_tpm_pairs)\n" ]
[ [ "numpy.median", "numpy.array", "pandas.DataFrame.from_dict" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "0.23", "0.21", "2.0", "1.4", "0.19", "1.1", "1.5", "1.2", "0.24", "0.20", "1.0", "0.25", "1.3" ], "scipy": [], "tensorflow": [] } ]
hi-paris/structured-predictions
[ "f28db05a1def9ce7aec59375235aa92dc0cc7bfc" ]
[ "stpredictions/models/DIOKR/estimator.py" ]
[ "import torch.optim as optim\nfrom scipy.linalg import block_diag\n\n# from stpredictions.models.DIOKR.cost import *\n# from stpredictions.models.DIOKR.kernel import *\nfrom stpredictions.models.DIOKR.IOKR import *\n\ndtype = torch.float\n\n\nclass DIOKREstimator(object):\n \"DIOKR Class with fitting procedure using pytorch\"\n\n def __init__(self, kernel_input, kernel_output, lbda, linear=False, iokr=None, Omega=None, cost=None, eps=None):\n self.kernel_input = kernel_input\n self.kernel_output = kernel_output\n self.lbda = lbda\n self.linear = linear\n self.iokr = iokr\n self.Omega = Omega\n self.cost = cost\n self.eps = eps\n\n def objective(self, x_batch, y_batch):\n \"Computes the objectif function to be minimized, sum of the cost +regularization\"\n\n self.iokr.fit(X_s=x_batch, Y_s=y_batch, L=self.lbda, input_kernel=self.kernel_input,\n output_kernel=self.kernel_output, input_gamma=self.kernel_input.gamma)\n K_x = self.kernel_input.compute_gram(x_batch)\n K_y = self.kernel_output.compute_gram(y_batch)\n obj = self.iokr.sloss(K_x, K_y) + self.lbda * self.iokr.get_vv_norm()\n\n return obj\n\n def train_kernel_input(self, x_batch, y_batch, solver: str, t0):\n \"\"\"\n One step of the gradient descent using Stochastic Gradient Descent during the fitting of the input kernel\n when using a learnable neural network kernel input\n \"\"\"\n if solver not in ('sgd', 'adam'):\n raise ValueError(f\"'solver' should be 'sgd' or 'adam',but not {solver}\")\n if type(t0) not in (int, float):\n raise TypeError(f\"'t0' should be an int, not a {type(t0)}\")\n if solver == 'sgd':\n optimizer_kernel = optim.SGD(\n self.kernel_input.model.parameters(),\n lr=self.kernel_input.optim_params['lr'],\n momentum=self.kernel_input.optim_params['momentum'],\n dampening=self.kernel_input.optim_params['dampening'],\n weight_decay=self.kernel_input.optim_params['weight_decay'],\n nesterov=self.kernel_input.optim_params['nesterov'])\n\n if solver == 'adam':\n optimizer_kernel = optim.Adam(\n self.kernel_input.model.parameters(),\n lr=self.kernel_input.optim_params['lr'],\n betas=(0.9, 0.999),\n eps=1e-08,\n weight_decay=0,\n amsgrad=False)\n\n def closure_kernel():\n loss = self.objective(x_batch, y_batch)\n optimizer_kernel.zero_grad()\n # torch.autograd.set_detect_anomaly(True)\n # loss.backward(retain_graph=True)\n loss.backward()\n return (loss)\n\n loss = closure_kernel()\n self.kernel_input.append_time(time() - t0)\n optimizer_kernel.step(closure_kernel)\n\n mse_train = loss - self.lbda * self.iokr.get_vv_norm()\n\n return mse_train.item()\n\n def fit_kernel_input(self, x_train, y_train, x_test, y_test, n_epochs=50, solver='sgd', batch_size_train=64,\n batch_size_test=None, verbose=True):\n \"\"\"\n Fits the input kernel when using a learnable neural network kernel input using the method train_kernel_input\n at each epoch.\n \"\"\"\n if solver not in ('sgd', 'adam'):\n raise ValueError(f\"'solver' should be 'sgd' or 'adam',but not {solver}\")\n if type(n_epochs) != int:\n raise TypeError(f\"'n_epochs' should be an int, not a {type(n_epochs)}\")\n if type(batch_size_train) != int:\n raise TypeError(f\"'batch_size_train' should be an int, not a {type(batch_size_train)}\")\n\n self.verbose = verbose\n\n if batch_size_train is None:\n batch_size_train = x_train.shape[0]\n\n if not hasattr(self.kernel_input, 'train_losses'):\n self.kernel_input.train_losses = []\n self.kernel_input.times = [0]\n\n if not hasattr(self.kernel_input, 'test_mse'):\n self.kernel_input.test_mse = []\n\n if not hasattr(self.kernel_input, 'test_f1'):\n self.kernel_input.test_f1 = []\n\n if batch_size_test is None:\n batch_size_test = x_test.shape[0]\n\n self.x_train = x_train\n self.y_train = y_train\n\n dataset_test = torch.utils.data.TensorDataset(x_test, y_test)\n\n loader_test = torch.utils.data.DataLoader(dataset_test, batch_size=batch_size_test)\n\n t0 = time()\n\n dataset_train = torch.utils.data.TensorDataset(x_train, y_train)\n\n loader_train = torch.utils.data.DataLoader(dataset_train, batch_size=batch_size_train)\n self.loader_train = loader_train\n\n for epoch in range(n_epochs):\n\n batch_losses_train = []\n\n len_trained = 0\n\n for batch_idx_train, (data_train, target_train) in enumerate(loader_train):\n\n batch_losses_train.append(self.train_kernel_input(data_train, target_train, solver, t0))\n\n len_trained += data_train.shape[0]\n\n if verbose:\n\n if batch_idx_train % 10 == 0:\n print('Train Epoch: {} [{}/{} ({:.0f}%)]\\tLoss: {:.6f}'.format(\n epoch, len_trained, x_train.size()[0],\n 100. * len_trained / x_train.size()[0], batch_losses_train[-1]))\n\n batch_idx_train += 1\n\n self.kernel_input.train_losses.append(np.mean(np.asarray(batch_losses_train)))\n\n # self.iokr.fit(X_s=x_train, Y_s=y_train, L=self.lbda, input_kernel=self.kernel_input,\n # output_kernel=self.kernel_output, input_gamma=self.kernel_input.gamma)\n\n batch_losses_test = []\n\n K_y = self.kernel_output.compute_gram(y_train, y_train)\n\n Omega_block_diag = np.empty((0, 0))\n\n for batch_idx_train, (data_train, target_train) in enumerate(loader_train):\n n_ba = data_train.shape[0]\n\n Omega = torch.inverse(\n self.kernel_input.compute_gram(data_train) + n_ba * self.lbda * torch.eye(n_ba)).data.numpy()\n\n Omega_block_diag = block_diag(Omega_block_diag, Omega)\n\n Omega_block_diag = torch.from_numpy(Omega_block_diag).float()\n\n print(Omega_block_diag.shape)\n\n n_b = len(loader_train)\n\n for batch_idx_test, (data_test, target_test) in enumerate(loader_test):\n K_x_tr_te = self.kernel_input.compute_gram(x_train, data_test)\n K_y_tr_te = self.kernel_output.compute_gram(y_train, target_test)\n K_y_te_te = self.kernel_output.compute_gram(target_test)\n\n mse_test, _ = self.cost(Omega_block_diag, K_x_tr_te, K_y_tr_te, K_y_te_te, K_y, n_b)\n\n batch_losses_test.append(mse_test.item())\n\n self.kernel_input.test_mse.append(np.mean(batch_losses_test))\n\n if verbose:\n print('\\nTest MSE of the whole model: {:.4f}\\n'.format(mse_test))\n\n \"\"\"\n if epoch % 25 == 0:\n \n K_x_tr_te = self.kernel_input.compute_gram(x_train, x_test) \n \n structured_loss, _ = F1_score(y_train, K_y, K_x_tr_te, y_test, y_train, self.kernel_output, Omega_block_diag, n_b)\n \n self.kernel_input.test_f1.append(structured_loss)\n \n if verbose:\n print('\\nTest F1 score of the whole model: {:.4f}\\n'.format(structured_loss))\n \"\"\"\n\n def predict(self, x_test, Y_candidates=None):\n \"\"\"\n Model Prediction\n \"\"\"\n if Y_candidates is None:\n Y_candidates = self.y_train\n\n t0 = time()\n\n K_y = self.kernel_output.compute_gram(self.y_train)\n\n Omega_block_diag = np.empty((0, 0))\n\n for batch_idx_train, (data_train, target_train) in enumerate(self.loader_train):\n n_ba = data_train.shape[0]\n\n Omega = torch.inverse(self.kernel_input.compute_gram(data_train)\n + n_ba * self.lbda * torch.eye(n_ba)).data.numpy()\n\n Omega_block_diag = block_diag(Omega_block_diag, Omega)\n\n Omega_block_diag = torch.from_numpy(Omega_block_diag).float()\n\n n_b = len(self.loader_train)\n\n K_x_tr_te = self.kernel_input.compute_gram(self.x_train, x_test)\n\n A = K_x_tr_te.T @ Omega_block_diag\n\n prod_h_c = A @ self.kernel_output.compute_gram(self.y_train, Y_candidates)\n norm_h = torch.diag(A @ K_y @ A.T)\n norm_c = torch.diag(self.kernel_output.compute_gram(Y_candidates))\n\n se = (1.0 / n_b ** 2) * norm_h.view(-1, 1) - (2.0 / n_b) * prod_h_c + norm_c.view(1, -1)\n scores = - se\n\n # Predict and compute Structured losses\n idx_pred = torch.argmax(scores, axis=1)\n Y_pred = Y_candidates[idx_pred]\n if self.verbose > 0:\n print(f'Decoding time: {time() - t0} in s')\n\n return Y_pred\n" ]
[ [ "scipy.linalg.block_diag" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [ "0.13", "0.14", "0.15", "0.12", "0.10" ], "tensorflow": [] } ]
acolombi/pymc3
[ "4e695f635b2ead24e2e647651eadd2505ab1fa63", "fde52a4a69be1b0887a2f7861801fb48c941bbe6", "3cb45700156b63e786eb70909d3e1d6e1f21703a", "3cb45700156b63e786eb70909d3e1d6e1f21703a" ]
[ "pymc3/glm/linear.py", "pymc3/tuning/scaling.py", "pymc3/util.py", "pymc3/parallel_sampling.py" ]
[ "import theano.tensor as tt\nimport numpy as np\nfrom ..distributions import Normal, Flat\nfrom . import families\nfrom ..model import Model, Deterministic\nfrom .utils import any_to_tensor_and_labels\n\n\n__all__ = [\n 'LinearComponent',\n 'GLM'\n]\n\n\nclass LinearComponent(Model):\n \"\"\"Creates linear component, y_est is accessible via attribute\n\n Parameters\n ----------\n name : str - name, associated with the linear component\n x : pd.DataFrame or np.ndarray\n y : pd.Series or np.array\n intercept : bool - fit with intercept or not?\n labels : list - replace variable names with these labels\n priors : dict - priors for coefficients\n use `Intercept` key for defining Intercept prior\n defaults to Flat.dist()\n use `Regressor` key for defining default prior for all regressors\n defaults to Normal.dist(mu=0, tau=1.0E-6)\n vars : dict - random variables instead of creating new ones\n offset : scalar, or numpy/theano array with the same shape as y\n this can be used to specify an a priori known component to be\n included in the linear predictor during fitting.\n \"\"\"\n default_regressor_prior = Normal.dist(mu=0, tau=1.0E-6)\n default_intercept_prior = Flat.dist()\n\n def __init__(self, x, y, intercept=True, labels=None,\n priors=None, vars=None, name='', model=None, offset=0.):\n super(LinearComponent, self).__init__(name, model)\n if priors is None:\n priors = {}\n if vars is None:\n vars = {}\n x, labels = any_to_tensor_and_labels(x, labels)\n # now we have x, shape and labels\n if intercept:\n x = tt.concatenate(\n [tt.ones((x.shape[0], 1), x.dtype), x],\n axis=1\n )\n labels = ['Intercept'] + labels\n coeffs = list()\n for name in labels:\n if name == 'Intercept':\n if name in vars:\n v = Deterministic(name, vars[name])\n else:\n v = self.Var(\n name=name,\n dist=priors.get(\n name,\n self.default_intercept_prior\n )\n )\n coeffs.append(v)\n else:\n if name in vars:\n v = Deterministic(name, vars[name])\n else:\n v = self.Var(\n name=name,\n dist=priors.get(\n name,\n priors.get(\n 'Regressor',\n self.default_regressor_prior\n )\n )\n )\n coeffs.append(v)\n self.coeffs = tt.stack(coeffs, axis=0)\n self.y_est = x.dot(self.coeffs) + offset\n\n @classmethod\n def from_formula(cls, formula, data, priors=None, vars=None,\n name='', model=None, offset=0.):\n import patsy\n y, x = patsy.dmatrices(formula, data)\n labels = x.design_info.column_names\n return cls(np.asarray(x), np.asarray(y)[:, -1], intercept=False,\n labels=labels, priors=priors, vars=vars, name=name,\n model=model, offset=offset)\n\n\nclass GLM(LinearComponent):\n \"\"\"Creates glm model, y_est is accessible via attribute\n\n Parameters\n ----------\n name : str - name, associated with the linear component\n x : pd.DataFrame or np.ndarray\n y : pd.Series or np.array\n intercept : bool - fit with intercept or not?\n labels : list - replace variable names with these labels\n priors : dict - priors for coefficients\n use `Intercept` key for defining Intercept prior\n defaults to Flat.dist()\n use `Regressor` key for defining default prior for all regressors\n defaults to Normal.dist(mu=0, tau=1.0E-6)\n init : dict - test_vals for coefficients\n vars : dict - random variables instead of creating new ones\n family : pymc3..families object\n offset : scalar, or numpy/theano array with the same shape as y\n this can be used to specify an a priori known component to be\n included in the linear predictor during fitting.\n \"\"\"\n def __init__(self, x, y, intercept=True, labels=None,\n priors=None, vars=None, family='normal', name='',\n model=None, offset=0.):\n super(GLM, self).__init__(\n x, y, intercept=intercept, labels=labels,\n priors=priors, vars=vars, name=name, \n model=model, offset=offset\n )\n\n _families = dict(\n normal=families.Normal,\n student=families.StudentT,\n binomial=families.Binomial,\n poisson=families.Poisson,\n negative_binomial=families.NegativeBinomial,\n )\n if isinstance(family, str):\n family = _families[family]()\n self.y_est = family.create_likelihood(\n name='', y_est=self.y_est,\n y_data=y, model=self)\n\n @classmethod\n def from_formula(cls, formula, data, priors=None,\n vars=None, family='normal', name='',\n model=None, offset=0.):\n import patsy\n y, x = patsy.dmatrices(formula, data)\n labels = x.design_info.column_names\n return cls(np.asarray(x), np.asarray(y)[:, -1], intercept=False,\n labels=labels, priors=priors, vars=vars, family=family,\n name=name, model=model, offset=offset)\n\n\nglm = GLM\n", "'''\nCreated on Mar 12, 2011\n\nfrom __future__ import division\n@author: johnsalvatier\n'''\nimport numpy as np\nfrom numpy import exp, log, sqrt\nfrom ..model import modelcontext, Point\nfrom ..theanof import hessian_diag, inputvars\nfrom ..blocking import DictToArrayBijection, ArrayOrdering\n\n__all__ = ['approx_hessian', 'find_hessian', 'trace_cov', 'guess_scaling']\n\n\ndef approx_hessian(point, vars=None, model=None):\n \"\"\"\n Returns an approximation of the Hessian at the current chain location.\n\n Parameters\n ----------\n model : Model (optional if in `with` context)\n point : dict\n vars : list\n Variables for which Hessian is to be calculated.\n \"\"\"\n from numdifftools import Jacobian\n\n model = modelcontext(model)\n if vars is None:\n vars = model.cont_vars\n vars = inputvars(vars)\n\n point = Point(point, model=model)\n\n bij = DictToArrayBijection(ArrayOrdering(vars), point)\n dlogp = bij.mapf(model.fastdlogp(vars))\n\n def grad_logp(point):\n return np.nan_to_num(dlogp(point))\n\n '''\n Find the jacobian of the gradient function at the current position\n this should be the Hessian; invert it to find the approximate\n covariance matrix.\n '''\n return -Jacobian(grad_logp)(bij.map(point))\n\n\ndef fixed_hessian(point, vars=None, model=None):\n \"\"\"\n Returns a fixed Hessian for any chain location.\n\n Parameters\n ----------\n model : Model (optional if in `with` context)\n point : dict\n vars : list\n Variables for which Hessian is to be calculated.\n \"\"\"\n\n model = modelcontext(model)\n if vars is None:\n vars = model.cont_vars\n vars = inputvars(vars)\n\n point = Point(point, model=model)\n\n bij = DictToArrayBijection(ArrayOrdering(vars), point)\n rval = np.ones(bij.map(point).size) / 10\n return rval\n\n\ndef find_hessian(point, vars=None, model=None):\n \"\"\"\n Returns Hessian of logp at the point passed.\n\n Parameters\n ----------\n model : Model (optional if in `with` context)\n point : dict\n vars : list\n Variables for which Hessian is to be calculated.\n \"\"\"\n model = modelcontext(model)\n H = model.fastd2logp(vars)\n return H(Point(point, model=model))\n\n\ndef find_hessian_diag(point, vars=None, model=None):\n \"\"\"\n Returns Hessian of logp at the point passed.\n\n Parameters\n ----------\n model : Model (optional if in `with` context)\n point : dict\n vars : list\n Variables for which Hessian is to be calculated.\n \"\"\"\n model = modelcontext(model)\n H = model.fastfn(hessian_diag(model.logpt, vars))\n return H(Point(point, model=model))\n\n\ndef guess_scaling(point, vars=None, model=None, scaling_bound=1e-8):\n model = modelcontext(model)\n try:\n h = find_hessian_diag(point, vars, model=model)\n except NotImplementedError:\n h = fixed_hessian(point, vars, model=model)\n return adjust_scaling(h, scaling_bound)\n\n\ndef adjust_scaling(s, scaling_bound):\n if s.ndim < 2:\n return adjust_precision(s, scaling_bound)\n else:\n val, vec = np.linalg.eigh(s)\n val = adjust_precision(val, scaling_bound)\n return eig_recompose(val, vec)\n\n\ndef adjust_precision(tau, scaling_bound=1e-8):\n mag = sqrt(abs(tau))\n\n bounded = bound(log(mag), log(scaling_bound), log(1./scaling_bound))\n return exp(bounded)**2\n\n\ndef bound(a, l, u):\n return np.maximum(np.minimum(a, u), l)\n\n\ndef eig_recompose(val, vec):\n return vec.dot(np.diag(val)).dot(vec.T)\n\n\ndef trace_cov(trace, vars=None, model=None):\n \"\"\"\n Calculate the flattened covariance matrix using a sample trace\n\n Useful if you want to base your covariance matrix for further sampling on some initial samples.\n\n Parameters\n ----------\n trace : Trace\n vars : list\n variables for which to calculate covariance matrix\n\n Returns\n -------\n r : array (n,n)\n covariance matrix\n \"\"\"\n model = modelcontext(model)\n\n if model is not None:\n vars = model.free_RVs\n elif vars is None:\n vars = trace.varnames\n\n def flat_t(var):\n x = trace[str(var)]\n return x.reshape((x.shape[0], np.prod(x.shape[1:], dtype=int)))\n\n return np.cov(np.concatenate(list(map(flat_t, vars)), 1).T)\n", "import re\nimport functools\nfrom numpy import asscalar\n\nLATEX_ESCAPE_RE = re.compile(r'(%|_|\\$|#|&)', re.MULTILINE)\n\n\ndef escape_latex(strng):\n \"\"\"Consistently escape LaTeX special characters for _repr_latex_ in IPython\n\n Implementation taken from the IPython magic `format_latex`\n\n Examples\n --------\n escape_latex('disease_rate') # 'disease\\_rate'\n\n Parameters\n ----------\n strng : str\n string to escape LaTeX characters\n\n Returns\n -------\n str\n A string with LaTeX escaped\n \"\"\"\n if strng is None:\n return u'None'\n return LATEX_ESCAPE_RE.sub(r'\\\\\\1', strng)\n\n\ndef get_transformed_name(name, transform):\n \"\"\"\n Consistent way of transforming names\n\n Parameters\n ----------\n name : str\n Name to transform\n transform : transforms.Transform\n Should be a subclass of `transforms.Transform`\n\n Returns\n -------\n str\n A string to use for the transformed variable\n \"\"\"\n return \"{}_{}__\".format(name, transform.name)\n\n\ndef is_transformed_name(name):\n \"\"\"\n Quickly check if a name was transformed with `get_transormed_name`\n\n Parameters\n ----------\n name : str\n Name to check\n\n Returns\n -------\n bool\n Boolean, whether the string could have been produced by `get_transormed_name`\n \"\"\"\n return name.endswith('__') and name.count('_') >= 3\n\n\ndef get_untransformed_name(name):\n \"\"\"\n Undo transformation in `get_transformed_name`. Throws ValueError if name wasn't transformed\n\n Parameters\n ----------\n name : str\n Name to untransform\n\n Returns\n -------\n str\n String with untransformed version of the name.\n \"\"\"\n if not is_transformed_name(name):\n raise ValueError(\n u'{} does not appear to be a transformed name'.format(name))\n return '_'.join(name.split('_')[:-3])\n\n\ndef get_default_varnames(var_iterator, include_transformed):\n \"\"\"Helper to extract default varnames from a trace.\n\n Parameters\n ----------\n varname_iterator : iterator\n Elements will be cast to string to check whether it is transformed, and optionally filtered\n include_transformed : boolean\n Should transformed variable names be included in return value\n\n Returns\n -------\n list\n List of variables, possibly filtered\n \"\"\"\n if include_transformed:\n return list(var_iterator)\n else:\n return [var for var in var_iterator if not is_transformed_name(str(var))]\n\n\ndef get_variable_name(variable):\n \"\"\"Returns the variable data type if it is a constant, otherwise\n returns the argument name.\n \"\"\"\n name = variable.name\n if name is None:\n if hasattr(variable, 'get_parents'):\n try:\n names = [get_variable_name(item)\n for item in variable.get_parents()[0].inputs]\n # do not escape_latex these, since it is not idempotent\n return 'f(%s)' % ',~'.join([n for n in names if isinstance(n, str)])\n except IndexError:\n pass\n value = variable.eval()\n if not value.shape:\n return asscalar(value)\n return 'array'\n return r'\\text{%s}' % name\n\n\ndef update_start_vals(a, b, model):\n \"\"\"Update a with b, without overwriting existing keys. Values specified for\n transformed variables on the original scale are also transformed and inserted.\n \"\"\"\n if model is not None:\n for free_RV in model.free_RVs:\n tname = free_RV.name\n for name in a:\n if is_transformed_name(tname) and get_untransformed_name(tname) == name:\n transform_func = [\n d.transformation for d in model.deterministics if d.name == name]\n if transform_func:\n b[tname] = transform_func[0].forward_val(\n a[name], point=b)\n\n a.update({k: v for k, v in b.items() if k not in a})\n\n\ndef get_transformed(z):\n if hasattr(z, 'transformed'):\n z = z.transformed\n return z\n\n\ndef biwrap(wrapper):\n @functools.wraps(wrapper)\n def enhanced(*args, **kwargs):\n is_bound_method = hasattr(args[0], wrapper.__name__) if args else False\n if is_bound_method:\n count = 1\n else:\n count = 0\n if len(args) > count:\n newfn = wrapper(*args, **kwargs)\n return newfn\n else:\n newwrapper = functools.partial(wrapper, *args, **kwargs)\n return newwrapper\n return enhanced\n", "import multiprocessing\nimport multiprocessing.sharedctypes\nimport ctypes\nimport time\nimport logging\nfrom collections import namedtuple\nimport traceback\n\nimport six\nimport numpy as np\n\nfrom . import theanof\n\nlogger = logging.getLogger('pymc3')\n\n\n# Taken from https://hg.python.org/cpython/rev/c4f92b597074\nclass RemoteTraceback(Exception):\n def __init__(self, tb):\n self.tb = tb\n\n def __str__(self):\n return self.tb\n\n\nclass ExceptionWithTraceback:\n def __init__(self, exc, tb):\n tb = traceback.format_exception(type(exc), exc, tb)\n tb = ''.join(tb)\n self.exc = exc\n self.tb = '\\n\"\"\"\\n%s\"\"\"' % tb\n\n def __reduce__(self):\n return rebuild_exc, (self.exc, self.tb)\n\n\ndef rebuild_exc(exc, tb):\n exc.__cause__ = RemoteTraceback(tb)\n return exc\n\n\n# Messages\n# ('writing_done', is_last, sample_idx, tuning, stats)\n# ('error', *exception_info)\n\n# ('abort', reason)\n# ('write_next',)\n# ('start',)\n\n\nclass _Process(multiprocessing.Process):\n \"\"\"Seperate process for each chain.\n\n We communicate with the main process using a pipe,\n and send finished samples using shared memory.\n \"\"\"\n def __init__(self, name, msg_pipe, step_method, shared_point,\n draws, tune, seed):\n super(_Process, self).__init__(daemon=True, name=name)\n self._msg_pipe = msg_pipe\n self._step_method = step_method\n self._shared_point = shared_point\n self._seed = seed\n self._tt_seed = seed + 1\n self._draws = draws\n self._tune = tune\n\n def run(self):\n try:\n # We do not create this in __init__, as pickling this\n # would destroy the shared memory.\n self._point = self._make_numpy_refs()\n self._start_loop()\n except KeyboardInterrupt:\n pass\n except BaseException as e:\n e = ExceptionWithTraceback(e, e.__traceback__)\n self._msg_pipe.send(('error', e))\n finally:\n self._msg_pipe.close()\n\n def _make_numpy_refs(self):\n shape_dtypes = self._step_method.vars_shape_dtype\n point = {}\n for name, (shape, dtype) in shape_dtypes.items():\n array = self._shared_point[name]\n self._shared_point[name] = array\n point[name] = np.frombuffer(array, dtype).reshape(shape)\n return point\n\n def _write_point(self, point):\n for name, vals in point.items():\n self._point[name][...] = vals\n\n def _recv_msg(self):\n return self._msg_pipe.recv()\n\n def _start_loop(self):\n np.random.seed(self._seed)\n theanof.set_tt_rng(self._tt_seed)\n\n draw = 0\n tuning = True\n\n msg = self._recv_msg()\n if msg[0] == 'abort':\n raise KeyboardInterrupt()\n if msg[0] != 'start':\n raise ValueError('Unexpected msg ' + msg[0])\n\n while True:\n if draw < self._draws + self._tune:\n point, stats = self._compute_point()\n else:\n return\n\n if draw == self._tune:\n self._step_method.stop_tuning()\n tuning = False\n\n msg = self._recv_msg()\n if msg[0] == 'abort':\n raise KeyboardInterrupt()\n elif msg[0] == 'write_next':\n self._write_point(point)\n is_last = draw + 1 == self._draws + self._tune\n if is_last:\n warns = self._collect_warnings()\n else:\n warns = None\n self._msg_pipe.send(\n ('writing_done', is_last, draw, tuning, stats, warns))\n draw += 1\n else:\n raise ValueError('Unknown message ' + msg[0])\n\n def _compute_point(self):\n if self._step_method.generates_stats:\n point, stats = self._step_method.step(self._point)\n else:\n point = self._step_method.step(self._point)\n stats = None\n return point, stats\n\n def _collect_warnings(self):\n if hasattr(self._step_method, 'warnings'):\n return self._step_method.warnings()\n else:\n return []\n\n\nclass ProcessAdapter(object):\n \"\"\"Control a Chain process from the main thread.\"\"\"\n def __init__(self, draws, tune, step_method, chain, seed, start):\n self.chain = chain\n process_name = \"worker_chain_%s\" % chain\n self._msg_pipe, remote_conn = multiprocessing.Pipe()\n\n self._shared_point = {}\n self._point = {}\n for name, (shape, dtype) in step_method.vars_shape_dtype.items():\n size = 1\n for dim in shape:\n size *= int(dim)\n size *= dtype.itemsize\n if size != ctypes.c_size_t(size).value:\n raise ValueError('Variable %s is too large' % name)\n\n array = multiprocessing.sharedctypes.RawArray('c', size)\n self._shared_point[name] = array\n array_np = np.frombuffer(array, dtype).reshape(shape)\n array_np[...] = start[name]\n self._point[name] = array_np\n\n self._readable = True\n self._num_samples = 0\n\n self._process = _Process(\n process_name, remote_conn, step_method, self._shared_point,\n draws, tune, seed)\n # We fork right away, so that the main process can start tqdm threads\n self._process.start()\n\n @property\n def shared_point_view(self):\n \"\"\"May only be written to or read between a `recv_draw`\n call from the process and a `write_next` or `abort` call.\n \"\"\"\n if not self._readable:\n raise RuntimeError()\n return self._point\n\n def start(self):\n self._msg_pipe.send(('start',))\n\n def write_next(self):\n self._readable = False\n self._msg_pipe.send(('write_next',))\n\n def abort(self):\n self._msg_pipe.send(('abort',))\n\n def join(self, timeout=None):\n self._process.join(timeout)\n\n def terminate(self):\n self._process.terminate()\n\n @staticmethod\n def recv_draw(processes, timeout=3600):\n if not processes:\n raise ValueError('No processes.')\n pipes = [proc._msg_pipe for proc in processes]\n ready = multiprocessing.connection.wait(pipes)\n if not ready:\n raise multiprocessing.TimeoutError('No message from samplers.')\n idxs = {id(proc._msg_pipe): proc for proc in processes}\n proc = idxs[id(ready[0])]\n msg = ready[0].recv()\n\n if msg[0] == 'error':\n old = msg[1]\n six.raise_from(RuntimeError('Chain %s failed.' % proc.chain), old)\n elif msg[0] == 'writing_done':\n proc._readable = True\n proc._num_samples += 1\n return (proc,) + msg[1:]\n else:\n raise ValueError('Sampler sent bad message.')\n\n @staticmethod\n def terminate_all(processes, patience=2):\n for process in processes:\n try:\n process.abort()\n except EOFError:\n pass\n\n start_time = time.time()\n try:\n for process in processes:\n timeout = time.time() + patience - start_time\n if timeout < 0:\n raise multiprocessing.TimeoutError()\n process.join(timeout)\n except multiprocessing.TimeoutError:\n logger.warn('Chain processes did not terminate as expected. '\n 'Terminating forcefully...')\n for process in processes:\n process.terminate()\n for process in processes:\n process.join()\n\n\nDraw = namedtuple(\n 'Draw',\n ['chain', 'is_last', 'draw_idx', 'tuning', 'stats', 'point', 'warnings']\n)\n\n\nclass ParallelSampler(object):\n def __init__(self, draws, tune, chains, cores, seeds, start_points,\n step_method, start_chain_num=0, progressbar=True):\n if progressbar:\n import tqdm\n tqdm_ = tqdm.tqdm\n\n if any(len(arg) != chains for arg in [seeds, start_points]):\n raise ValueError(\n 'Number of seeds and start_points must be %s.' % chains)\n\n self._samplers = [\n ProcessAdapter(draws, tune, step_method,\n chain + start_chain_num, seed, start)\n for chain, seed, start in zip(range(chains), seeds, start_points)\n ]\n\n self._inactive = self._samplers.copy()\n self._finished = []\n self._active = []\n self._max_active = cores\n\n self._in_context = False\n self._start_chain_num = start_chain_num\n\n self._progress = None\n if progressbar:\n self._progress = tqdm_(\n total=chains * (draws + tune), unit='draws',\n desc='Sampling %s chains' % chains)\n\n def _make_active(self):\n while self._inactive and len(self._active) < self._max_active:\n proc = self._inactive.pop(0)\n proc.start()\n proc.write_next()\n self._active.append(proc)\n\n def __iter__(self):\n if not self._in_context:\n raise ValueError('Use ParallelSampler as context manager.')\n self._make_active()\n\n while self._active:\n draw = ProcessAdapter.recv_draw(self._active)\n proc, is_last, draw, tuning, stats, warns = draw\n if self._progress is not None:\n self._progress.update()\n\n if is_last:\n proc.join()\n self._active.remove(proc)\n self._finished.append(proc)\n self._make_active()\n\n # We could also yield proc.shared_point_view directly,\n # and only call proc.write_next() after the yield returns.\n # This seems to be faster overally though, as the worker\n # loses less time waiting.\n point = {name: val.copy()\n for name, val in proc.shared_point_view.items()}\n\n # Already called for new proc in _make_active\n if not is_last:\n proc.write_next()\n\n yield Draw(proc.chain, is_last, draw, tuning, stats, point, warns)\n\n def __enter__(self):\n self._in_context = True\n return self\n\n def __exit__(self, *args):\n ProcessAdapter.terminate_all(self._samplers)\n if self._progress is not None:\n self._progress.close()\n" ]
[ [ "numpy.asarray" ], [ "numpy.diag", "numpy.log", "numpy.minimum", "numpy.linalg.eigh", "numpy.prod", "numpy.exp" ], [ "numpy.asscalar" ], [ "numpy.frombuffer", "numpy.random.seed" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
pkulwj1994/normalizing-flows
[ "326321c4aea4a3f6ab703f82e21277a79cd7d9e4", "326321c4aea4a3f6ab703f82e21277a79cd7d9e4" ]
[ "normflow/flows/glow.py", "normflow/flows/affine_coupling.py" ]
[ "import torch\nfrom torch import nn\n\nfrom .base import Flow\nfrom .affine_coupling import AffineCouplingBlock\nfrom .mixing import Invertible1x1Conv\nfrom .normalization import ActNorm\nfrom .. import nets\n\n\n\nclass GlowBlock(Flow):\n \"\"\"\n Glow: Generative Flow with Invertible 1×1 Convolutions, arXiv: 1807.03039\n One Block of the Glow model, comprised of\n MaskedAffineFlow (affine coupling layer\n Invertible1x1Conv (dropped if there is only one channel)\n ActNorm (first batch used for initialization)\n \"\"\"\n def __init__(self, channels, hidden_channels, scale=True, scale_map='sigmoid',\n split_mode='channel', leaky=0.0, init_zeros=True, use_lu=True,\n net_actnorm=False):\n \"\"\"\n Constructor\n :param channels: Number of channels of the data\n :param hidden_channels: number of channels in the hidden layer of the ConvNet\n :param scale: Flag, whether to include scale in affine coupling layer\n :param scale_map: Map to be applied to the scale parameter, can be 'exp' as in\n RealNVP or 'sigmoid' as in Glow\n :param split_mode: Splitting mode, for possible values see Split class\n :param leaky: Leaky parameter of LeakyReLUs of ConvNet2d\n :param init_zeros: Flag whether to initialize last conv layer with zeros\n :param use_lu: Flag whether to parametrize weights through the LU decomposition\n in invertible 1x1 convolution layers\n :param logscale_factor: Factor which can be used to control the scale of\n the log scale factor, see https://github.com/openai/glow\n \"\"\"\n super().__init__()\n self.flows = nn.ModuleList([])\n # Coupling layer\n kernel_size = (3, 1, 3)\n num_param = 2 if scale else 1\n if 'channel' == split_mode:\n channels_ = (channels // 2,) + 2 * (hidden_channels,)\n channels_ += (num_param * ((channels + 1) // 2),)\n elif 'channel_inv' == split_mode:\n channels_ = ((channels + 1) // 2,) + 2 * (hidden_channels,)\n channels_ += (num_param * (channels // 2),)\n elif 'checkerboard' in split_mode:\n channels_ = (channels,) + 2 * (hidden_channels,)\n channels_ += (num_param * channels,)\n else:\n raise NotImplementedError('Mode ' + split_mode + ' is not implemented.')\n param_map = nets.ConvNet2d(channels_, kernel_size, leaky, init_zeros,\n actnorm=net_actnorm)\n self.flows += [AffineCouplingBlock(param_map, scale, scale_map, split_mode)]\n # Invertible 1x1 convolution\n if channels > 1:\n self.flows += [Invertible1x1Conv(channels, use_lu)]\n # Activation normalization\n self.flows += [ActNorm((channels,) + (1, 1))]\n\n def forward(self, z):\n log_det_tot = torch.zeros(z.shape[0], dtype=z.dtype, device=z.device)\n for flow in self.flows:\n z, log_det = flow(z)\n log_det_tot += log_det\n return z, log_det_tot\n\n def inverse(self, z):\n log_det_tot = torch.zeros(z.shape[0], dtype=z.dtype, device=z.device)\n for i in range(len(self.flows) - 1, -1, -1):\n z, log_det = self.flows[i].inverse(z)\n log_det_tot += log_det\n return z, log_det_tot", "import numpy as np\nimport torch\nfrom torch import nn\n\nfrom .base import Flow\nfrom .reshape import Split, Merge\n\n\n\nclass AffineConstFlow(Flow):\n \"\"\"\n scales and shifts with learned constants per dimension. In the NICE paper there is a\n scaling layer which is a special case of this where t is None\n \"\"\"\n\n def __init__(self, shape, scale=True, shift=True):\n \"\"\"\n Constructor\n :param shape: Shape of the coupling layer\n :param scale: Flag whether to apply scaling\n :param shift: Flag whether to apply shift\n :param logscale_factor: Optional factor which can be used to control\n the scale of the log scale factor\n \"\"\"\n super().__init__()\n if scale:\n self.s = nn.Parameter(torch.zeros(shape)[None])\n else:\n self.register_buffer('s', torch.zeros(shape)[None])\n if shift:\n self.t = nn.Parameter(torch.zeros(shape)[None])\n else:\n self.register_buffer('t', torch.zeros(shape)[None])\n self.n_dim = self.s.dim()\n self.batch_dims = torch.nonzero(torch.tensor(self.s.shape) == 1, as_tuple=False)[:, 0].tolist()\n\n def forward(self, z):\n z_ = z * torch.exp(self.s) + self.t\n if len(self.batch_dims) > 1:\n prod_batch_dims = np.prod([z.size(i) for i in self.batch_dims[1:]])\n else:\n prod_batch_dims = 1\n log_det = prod_batch_dims * torch.sum(self.s)\n return z_, log_det\n\n def inverse(self, z):\n z_ = (z - self.t) * torch.exp(-self.s)\n if len(self.batch_dims) > 1:\n prod_batch_dims = np.prod([z.size(i) for i in self.batch_dims[1:]])\n else:\n prod_batch_dims = 1\n log_det = -prod_batch_dims * torch.sum(self.s)\n return z_, log_det\n\n\nclass CCAffineConst(Flow):\n \"\"\"\n Affine constant flow layer with class-conditional parameters\n \"\"\"\n\n def __init__(self, shape, num_classes):\n super().__init__()\n self.shape = shape\n self.s = nn.Parameter(torch.zeros(shape)[None])\n self.t = nn.Parameter(torch.zeros(shape)[None])\n self.s_cc = nn.Parameter(torch.zeros(num_classes, np.prod(shape)))\n self.t_cc = nn.Parameter(torch.zeros(num_classes, np.prod(shape)))\n self.n_dim = self.s.dim()\n self.batch_dims = torch.nonzero(torch.tensor(self.s.shape) == 1, as_tuple=False)[:, 0].tolist()\n\n def forward(self, z, y):\n s = self.s + (y @ self.s_cc).view(-1, *self.shape)\n t = self.t + (y @ self.t_cc).view(-1, *self.shape)\n z_ = z * torch.exp(s) + t\n if len(self.batch_dims) > 1:\n prod_batch_dims = np.prod([z.size(i) for i in self.batch_dims[1:]])\n else:\n prod_batch_dims = 1\n log_det = prod_batch_dims * torch.sum(s, dim=list(range(1, self.n_dim)))\n return z_, log_det\n\n def inverse(self, z, y):\n s = self.s + (y @ self.s_cc).view(-1, *self.shape)\n t = self.t + (y @ self.t_cc).view(-1, *self.shape)\n z_ = (z - t) * torch.exp(-s)\n if len(self.batch_dims) > 1:\n prod_batch_dims = np.prod([z.size(i) for i in self.batch_dims[1:]])\n else:\n prod_batch_dims = 1\n log_det = -prod_batch_dims * torch.sum(s, dim=list(range(1, self.n_dim)))\n return z_, log_det\n\n\nclass AffineCoupling(Flow):\n \"\"\"\n Affine Coupling layer as introduced RealNVP paper, see arXiv: 1605.08803\n \"\"\"\n\n def __init__(self, param_map, scale=True, scale_map='exp'):\n \"\"\"\n Constructor\n :param param_map: Maps features to shift and scale parameter (if applicable)\n :param scale: Flag whether scale shall be applied\n :param scale_map: Map to be applied to the scale parameter, can be 'exp' as in\n RealNVP or 'sigmoid' as in Glow, 'sigmoid_inv' uses multiplicative sigmoid\n scale when sampling from the model\n \"\"\"\n super().__init__()\n self.add_module('param_map', param_map)\n self.scale = scale\n self.scale_map = scale_map\n\n def forward(self, z):\n \"\"\"\n z is a list of z1 and z2; z = [z1, z2]\n z1 is left constant and affine map is applied to z2 with parameters depending\n on z1\n \"\"\"\n z1, z2 = z\n param = self.param_map(z1)\n if self.scale:\n shift = param[:, 0::2, ...]\n scale_ = param[:, 1::2, ...]\n if self.scale_map == 'exp':\n z2 = z2 * torch.exp(scale_) + shift\n log_det = torch.sum(scale_, dim=list(range(1, shift.dim())))\n elif self.scale_map == 'sigmoid':\n scale = torch.sigmoid(scale_ + 2)\n z2 = z2 / scale + shift\n log_det = -torch.sum(torch.log(scale),\n dim=list(range(1, shift.dim())))\n elif self.scale_map == 'sigmoid_inv':\n scale = torch.sigmoid(scale_ + 2)\n z2 = z2 * scale + shift\n log_det = torch.sum(torch.log(scale),\n dim=list(range(1, shift.dim())))\n else:\n raise NotImplementedError('This scale map is not implemented.')\n else:\n z2 += param\n log_det = 0\n return [z1, z2], log_det\n\n def inverse(self, z):\n z1, z2 = z\n param = self.param_map(z1)\n if self.scale:\n shift = param[:, 0::2, ...]\n scale_ = param[:, 1::2, ...]\n if self.scale_map == 'exp':\n z2 = (z2 - shift) * torch.exp(-scale_)\n log_det = -torch.sum(scale_, dim=list(range(1, shift.dim())))\n elif self.scale_map == 'sigmoid':\n scale = torch.sigmoid(scale_ + 2)\n z2 = (z2 - shift) * scale\n log_det = torch.sum(torch.log(scale),\n dim=list(range(1, shift.dim())))\n elif self.scale_map == 'sigmoid_inv':\n scale = torch.sigmoid(scale_ + 2)\n z2 = (z2 - shift) / scale\n log_det = -torch.sum(torch.log(scale),\n dim=list(range(1, shift.dim())))\n else:\n raise NotImplementedError('This scale map is not implemented.')\n else:\n z2 -= param\n log_det = 0\n return [z1, z2], log_det\n\n\nclass MaskedAffineFlow(Flow):\n \"\"\"\n RealNVP as introduced in arXiv: 1605.08803\n Masked affine flow f(z) = b * z + (1 - b) * (z * exp(s(b * z)) + t)\n class AffineHalfFlow(Flow): is MaskedAffineFlow with alternating bit mask\n NICE is AffineFlow with only shifts (volume preserving)\n \"\"\"\n\n def __init__(self, b, t=None, s=None):\n \"\"\"\n Constructor\n :param b: mask for features, i.e. tensor of same size as latent data point filled with 0s and 1s\n :param t: translation mapping, i.e. neural network, where first input dimension is batch dim,\n if None no translation is applied\n :param s: scale mapping, i.e. neural network, where first input dimension is batch dim,\n if None no scale is applied\n \"\"\"\n super().__init__()\n self.b_cpu = b.view(1, *b.size())\n self.register_buffer('b', self.b_cpu)\n\n if s is None:\n self.s = lambda x: torch.zeros_like(x)\n else:\n self.add_module('s', s)\n\n if t is None:\n self.t = lambda x: torch.zeros_like(x)\n else:\n self.add_module('t', t)\n\n def forward(self, z):\n z_masked = self.b * z\n scale = self.s(z_masked)\n nan = torch.tensor(np.nan, dtype=z.dtype, device=z.device)\n scale = torch.where(torch.isfinite(scale), scale, nan)\n trans = self.t(z_masked)\n trans = torch.where(torch.isfinite(trans), trans, nan)\n z_ = z_masked + (1 - self.b) * (z * torch.exp(scale) + trans)\n log_det = torch.sum((1 - self.b) * scale, dim=list(range(1, self.b.dim())))\n return z_, log_det\n\n def inverse(self, z):\n z_masked = self.b * z\n scale = self.s(z_masked)\n nan = torch.tensor(np.nan, dtype=z.dtype, device=z.device)\n scale = torch.where(torch.isfinite(scale), scale, nan)\n trans = self.t(z_masked)\n trans = torch.where(torch.isfinite(trans), trans, nan)\n z_ = z_masked + (1 - self.b) * (z - trans) * torch.exp(-scale)\n log_det = -torch.sum((1 - self.b) * scale, dim=list(range(1, self.b.dim())))\n return z_, log_det\n\n\nclass AffineCouplingBlock(Flow):\n \"\"\"\n Affine Coupling layer including split and merge operation\n \"\"\"\n def __init__(self, param_map, scale=True, scale_map='exp', split_mode='channel'):\n \"\"\"\n Constructor\n :param param_map: Maps features to shift and scale parameter (if applicable)\n :param scale: Flag whether scale shall be applied\n :param scale_map: Map to be applied to the scale parameter, can be 'exp' as in\n RealNVP or 'sigmoid' as in Glow\n :param split_mode: Splitting mode, for possible values see Split class\n \"\"\"\n super().__init__()\n self.flows = nn.ModuleList([])\n # Split layer\n self.flows += [Split(split_mode)]\n # Affine coupling layer\n self.flows += [AffineCoupling(param_map, scale, scale_map)]\n # Merge layer\n self.flows += [Merge(split_mode)]\n\n def forward(self, z):\n log_det_tot = torch.zeros(z.shape[0], dtype=z.dtype, device=z.device)\n for flow in self.flows:\n z, log_det = flow(z)\n log_det_tot += log_det\n return z, log_det_tot\n\n def inverse(self, z):\n log_det_tot = torch.zeros(z.shape[0], dtype=z.dtype, device=z.device)\n for i in range(len(self.flows) - 1, -1, -1):\n z, log_det = self.flows[i].inverse(z)\n log_det_tot += log_det\n return z, log_det_tot" ]
[ [ "torch.nn.ModuleList", "torch.zeros" ], [ "torch.sigmoid", "torch.zeros", "torch.nn.ModuleList", "torch.sum", "torch.zeros_like", "torch.tensor", "torch.exp", "torch.isfinite", "torch.log", "numpy.prod" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
AvisP/AVGN_Avishek
[ "78b5cfc49d90016f462c91e42499970217f073c9" ]
[ "avgn/vocalsegmentation/utils.py" ]
[ "from scipy.signal import butter, lfilter\nimport numpy as np\nimport librosa\nfrom scipy import signal\nimport warnings\nimport matplotlib.pyplot as plt\n\n### General\ndef int16tofloat32(data):\n return np.array(data / 32768).astype(\"float32\")\n\n\ndef norm(x, _type=\"zero_one\"):\n return (x - np.min(x)) / (np.max(x) - np.min(x))\n\n\n### Filtering\ndef butter_bandpass(lowcut, highcut, fs, order=5):\n nyq = 0.5 * fs\n low = lowcut / nyq\n high = highcut / nyq\n b, a = butter(order, [low, high], btype=\"band\")\n return b, a\n\n\ndef butter_bandpass_filter(data, lowcut, highcut, fs, order=5):\n if highcut > int(fs / 2):\n warnings.warn(\"Highcut is too high for bandpass filter. Setting to nyquist\")\n highcut = int(fs / 2)\n b, a = butter_bandpass(lowcut, highcut, fs, order=order)\n y = lfilter(b, a, data)\n return y\n\n\n### Spectrogramming\n\n\ndef spectrogram(\n y,\n fs,\n n_fft=1024,\n hop_length_ms=1,\n win_length_ms=5,\n ref_level_db=20,\n pre=0.97,\n min_level_db=-50,\n):\n return _normalize(\n spectrogram_nn(\n y,\n fs,\n n_fft=n_fft,\n hop_length_ms=hop_length_ms,\n win_length_ms=win_length_ms,\n ref_level_db=ref_level_db,\n pre=pre,\n ),\n min_level_db=min_level_db,\n )\n\n\ndef spectrogram_nn(y, fs, n_fft, hop_length_ms, win_length_ms, ref_level_db, pre):\n D = _stft(preemphasis(y, pre), fs, n_fft, hop_length_ms, win_length_ms)\n S = _amp_to_db(np.abs(D)) - ref_level_db\n return S\n# return(D,S)\n\n\ndef preemphasis(x, pre):\n return signal.lfilter([1, -pre], [1], x)\n\n\ndef _stft(y, fs, n_fft, hop_length_ms, win_length_ms):\n return librosa.stft(\n y=y,\n n_fft=n_fft,\n hop_length=int(hop_length_ms / 1000 * fs),\n win_length=int(win_length_ms / 1000 * fs),\n )\n\n\ndef _amp_to_db(x):\n return 20 * np.log10(np.maximum(1e-5, x))\n\n\ndef _normalize(S, min_level_db):\n return np.clip((S - min_level_db) / -min_level_db, 0, 1)\n\n\n### viz\n\nimport matplotlib.pyplot as plt\n\n# def frame_image(img, frame_width):\n# b = frame_width # border size in pixel\n# ny, nx = img.shape[0], img.shape[1] # resolution / number of pixels in x and y\n# if img.ndim == 3: # rgb or rgba array\n# framed_img = np.zeros((b+ny+b, b+nx+b, img.shape[2]))\n# elif img.ndim == 2: # grayscale image\n# framed_img = np.zeros((b+ny+b, b+nx+b))\n# framed_img[b:-b, b:-b] = img\n# return framed_img\n\n\n\ndef plot_spec(\n spec,\n fig=None,\n ax=None,\n rate=None,\n hop_len_ms=None,\n cmap=plt.cm.afmhot,\n show_cbar=True,\n figsize=(20, 6),\n):\n \"\"\"plot spectrogram\n \n [description]\n \n Arguments:\n spec {[type]} -- [description]\n fig {[type]} -- [description]\n ax {[type]} -- [description]\n \n Keyword Arguments:\n cmap {[type]} -- [description] (default: {plt.cm.afmhot})\n \"\"\"\n if ax is None:\n fig, ax = plt.subplots(figsize=figsize)\n\n extent = [0, np.shape(spec)[1], 0, np.shape(spec)[0]]\n if rate is not None:\n extent[3] = rate / 2\n if hop_len_ms is not None:\n extent[1] = (np.shape(spec)[1] * hop_len_ms) / 1000\n \n cmap.set_under(color='k', alpha=None)\n \n spec_ax = ax.matshow(\n spec,\n interpolation=None,\n aspect=\"auto\",\n cmap=cmap,\n origin=\"lower\",\n vmin = np.min(spec),\n vmax = np.max(spec),\n extent=extent,\n )\n # ax.grid(True)\n if show_cbar:\n cbar = fig.colorbar(spec_ax, ax=ax)\n return spec_ax, cbar\n else:\n return spec_ax\n" ]
[ [ "numpy.maximum", "numpy.abs", "numpy.clip", "numpy.min", "matplotlib.pyplot.subplots", "numpy.max", "scipy.signal.butter", "numpy.shape", "scipy.signal.lfilter", "numpy.array" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [ "0.13", "1.6", "0.14", "1.10", "0.15", "1.4", "1.3", "1.9", "0.19", "1.5", "0.18", "1.2", "1.7", "0.12", "1.0", "0.17", "0.16", "1.8" ], "tensorflow": [] } ]
Prakshal2607/pythonml
[ "f77752d714144e9412685f8bfceef10934a9c525" ]
[ "TFANN/TFANN.py" ]
[ "'''\nTFANN.py\nThis file contains classes implementing ANN using numpy \nand tensorflow. Presently, multi-layer perceptron (MLP) \nand convolutional neural networks (CNN) are supported.\n'''\nimport tensorflow as tf\nimport numpy as np\n\ndef _Accuracy(Y, YH):\n '''\n Return the classification accuracy\n given a vector of target labels and\n predicted labels\n y: The target labels\n yHat: The predicted labels\n return: The percentage correct\n '''\n return np.mean(Y == YH)\n \ndef _CreateANN(PM, NA, X):\n '''\n Sets up the graph for a convolutional neural network from \n a list of operation specifications like:\n \n [('C', [5, 5, 3, 64], [1, 1, 1, 1]), ('AF', 'tanh'), \n ('P', [1, 3, 3, 1], [1, 2, 2, 1]), ('F', 10)]\n \n Operation Types:\n \n AF: ('AF', <name>) Activation Function 'relu', 'tanh', etc\n C: ('C', [Filter Shape], [Stride]) 2d Convolution\n CT: 2d Convolution Transpose\n C1d: ('C1d', [Filter Shape], Stride) 1d Convolution\n C3d: ('C3d', [Filter Shape], [Stride]) 3d Convolution\n D: ('D', Probability) Dropout Layer\n F: ('F', Output Neurons) Fully-connected\n LRN: ('LRN') \n M: ('M', Dims) Average over Dims\n P: ('P', [Filter Shape], [Stride]) Max Pool\n P1d: ('P1d', [Filter Shape], Stride) 1d Max Pooling\n R: ('R', shape) Reshape\n S: ('S', Dims) Sum over Dims\n \n [Filter Shape]: (Height, Width, In Channels, Out Channels)\n [Stride]: (Batch, Height, Width, Channel)\n Stride: 1-D Stride (single value)\n \n PM: The padding method\n NA: The network architecture\n X: Input tensor\n '''\n WI = tf.contrib.layers.xavier_initializer() #Weight initializer\n W, B, O = [], [], [X]\n for i, NAi in enumerate(NA):\n if NAi[0] == 'AF': #Apply an activation function ('AF', 'name')\n AF = _GetActvFn(NAi[1])\n X = AF(X)\n elif NAi[0] == 'C': #2-D Convolutional layer\n W.append(tf.Variable(WI(NAi[1])))\n B.append(tf.Variable(tf.constant(0.0, shape = [NAi[1][-1]])))\n X = tf.nn.conv2d(X, W[-1], NAi[2], padding = PM)\n X = tf.nn.bias_add(X, B[-1])\n elif NAi[0] == 'CT': #2-D Convolutional Transpose layer\n W.append(tf.Variable(WI(NAi[1])))\n B.append(tf.Variable(tf.constant(0.0, shape = [NAi[1][-2]])))\n X = tf.nn.conv2d_transpose(X, W[-1], NAi[2], NAi[3], padding = PM)\n X = tf.nn.bias_add(X, B[-1])\n elif NAi[0] == 'C1d': #1-D Convolutional Layer\n W.append(tf.Variable(WI(NAi[1])))\n B.append(tf.Variable(tf.constant(0.0, shape = [NAi[1][-1]])))\n X = tf.nn.conv1d(X, W[-1], NAi[2], padding = PM)\n X = tf.nn.bias_add(X, B[-1])\n elif NAi[0] == 'C3d':\n W.append(tf.Variable(WI(NAi[1])))\n B.append(tf.Variable(tf.constant(0.0, shape = [NAi[1][-1]])))\n X = tf.nn.conv1d(X, W[-1], NAi[2], padding = PM)\n X = tf.nn.bias_add(X, B[-1])\n elif NAi[0] == 'D': #Dropout layer ('D', <probability>)\n X = tf.nn.dropout(X, NAi[1])\n elif NAi[0] == 'F': #Fully-connected layer\n if tf.rank(X) != 2:\n X = tf.contrib.layers.flatten(X)\n W.append(tf.Variable(WI([X.shape[1].value, NAi[1]])))\n B.append(tf.Variable(WI([NAi[1]])))\n X = tf.matmul(X, W[-1]) + B[-1]\n elif NAi[0] == 'LRN':\n X = tf.nn.lrn(X, 4, bias = 1.0, alpha = 0.001 / 9.0, beta = 0.75)\n elif NAi[0] == 'M':\n X = tf.reduce_mean(X, NAi[1])\n elif NAi[0] == 'P': #Pooling layer\n X = tf.nn.max_pool(X, ksize = NAi[1], strides = NAi[2], padding = PM)\n elif NAi[0] == 'P1d': #1-D Pooling layer\n X = tf.nn.pool(X, [NAi[1]], 'MAX', PM, strides = [NAi[2]])\n elif NAi[0] == 'R': #Reshape layer\n X = tf.reshape(X, NAi[1])\n elif NAi[0] == 'S':\n X = tf.reduce_sum(X, NAi[1])\n O.append(X)\n return O, W, B\n\ndef _CreateL2Reg(_W, _B):\n '''\n Add L2 regularizers for the weight and bias matrices\n _W: The weight matrices\n _B: The bias matrices\n return: tensorflow variable representing l2 regularization cost\n '''\n return sum(tf.nn.l2_loss(_Wi) + tf.nn.l2_loss(_Bi) for _Wi, _Bi in zip(_W, _B))\n\ndef _GetActvFn(name):\n '''\n Helper function for selecting an activation function\n name: The name of the activation function\n return: A handle for the tensorflow activation function\n '''\n return {'atanh': tf.atanh, 'elu': tf.nn.elu,\n 'ident': tf.identity,\n 'sig': tf.sigmoid, 'softplus': tf.nn.softplus, \n 'softsign': tf.nn.softsign, 'relu': tf.nn.relu,\n 'relu6': tf.nn.relu6, 'tanh': tf.tanh}.get(name)\n \ndef _GetBatchRange(bs, mIter):\n '''\n Gives a range from which to choose the batch size\n '''\n try:\n return np.linspace(*bs[0:2], num = mIter).round().astype(np.int)\n except TypeError:\n pass\n return np.repeat(bs, mIter)\n \ndef _GetLossFn(name):\n '''\n Helper function for selecting loss function\n name: The name of the loss function\n return: A handle for a loss function LF(YH, Y)\n '''\n return {'cos': lambda YH, Y : tf.losses.cosine_distance(Y, YH), 'hinge': lambda YH, Y : tf.losses.hinge_loss(Y, YH),\n 'l1': lambda YH, Y : tf.losses.absolute_difference(Y, YH), 'l2': lambda YH, Y : tf.squared_difference(Y, YH),\n 'log': lambda YH, Y : tf.losses.log_loss(Y, YH), \n 'sgce': lambda YH, Y : tf.nn.sigmoid_cross_entropy_with_logits(labels = Y, logits = YH), \n 'smce': lambda YH, Y : tf.nn.softmax_cross_entropy_with_logits_v2(labels = Y, logits = YH)}.get(name)\n\ndef _GetOptimizer(name, lr):\n '''\n Helper function for getting a tensorflow optimizer\n name: The name of the optimizer to use\n lr: The learning rate if applicable\n return; A the tensorflow optimization object\n '''\n return {'adam': tf.train.AdamOptimizer(learning_rate = lr),\n 'adagrad': tf.train.AdagradOptimizer(learning_rate = lr),\n 'ftrl': tf.train.FtrlOptimizer(learning_rate = lr),\n 'grad': tf.train.GradientDescentOptimizer(learning_rate = lr)}.get(name)\n\nclass ANN:\n sess = None #Class variable shared among all instances\n sessc = 0 #Number of active sessions\n '''\n TensorFlow Artificial Neural Network (Base Class)\n '''\n\n #Clean-up resources\n def __del__(self):\n ANN.sessc -= 1 #Decrement session counter\n if ANN.sessc == 0: #Close session only if not in use\n self.GetSes().close()\n ANN.sess = None\n\n def __init__(self, _IS, _NA, batchSize = None, learnRate = 1e-4, loss = 'l2', maxIter = 1024,\n name = 'tfann', optmzrn = 'adam', pad = 'SAME', reg = None, sesd = {}, \n tol = 1e-2, verbose = False, X = None, Y = None):\n '''\n Common arguments for all artificial neural network regression models\n _IS: Shape of a single input sample\n _NA: Network architecture (see _CreateANN)\n batchSize: Size of training batches to use (use all if None)\n learnRate: The learning rate parameter for the optimizer\n loss: The name of the loss function (l2, l1, smce, sgme, cos, log, hinge) \n name: The name of the model for variable scope, saving, and restoring\n maxIter: Maximum number of training iterations\n optmzrn: The optimizer method to use ('adam', 'grad', 'adagrad', or 'ftrl')\n reg: Weight of the regularization term (None for no regularization)\n sesd: Dictionary of arguments to be passed to tf.Session\n tol: Training ends if error falls below this tolerance\n verbose: Print training information\n X: Tensor that is used as input to model; if None a new\n placeholder is created and used. If specified a feed_dict\n must be passed to train, predict, and score calls!\n '''\n self.IS = list(_IS) #Input shape\n self.NA = _NA #Network architecture specification\n self.LF = _GetLossFn(loss) #Handle to loss function to use\n self.batSz = batchSize #Batch size\n self.init = None #Initializer operation\n self.lr = learnRate #Learning rate\n self.mIter = maxIter #Maximum number of iterations\n self.name = name #Name of model for variable scope\n self.optmzrn = optmzrn #Optimizer method name\n self.pad = pad #Default padding method\n self.reg = reg #Regularization strength\n self.sesD = sesd #Arguments for tf.Session\n self.stopIter = False #Flag for stopping training early\n self.tol = tol #Error tolerance\n self.vrbse = verbose #Verbose output\n self.X = X #TF Variable used as input to model\n self.Y = Y #TF Variable used as target for model\n #Data members to be populated in a subclass\n self.loss = None\n self.optmzr = None\n self.O = None\n self.TFVar = None\n with tf.variable_scope(self.name):\n self.TFVar = set(tf.global_variables()) #All variables before model\n self.CreateModel() #Populate TensorFlow graph\n self.TFVar = set(tf.global_variables()) - self.TFVar #Only variables in this model\n self.Initialize() #Start TF session and initialize vars \n \n def CreateModel(self):\n '''\n Builds TF graph for ANN model\n '''\n if self.X is None: #If no input variable was specified make a new placeholder\n self.X = tf.placeholder(\"float\", [None] + self.IS) #Input data matrix of samples\n self.O, self.W, self.B = _CreateANN(self.pad, self.NA, self.X)#Create graph; O is output from feedforward\n if self.Y is None:\n self.Y = tf.placeholder(\"float\", self.O[-1].shape) #Target matrix\n self.loss = tf.reduce_mean(self.LF(self.O[-1], self.Y)) #Loss term\n if self.reg is not None: #Regularization can prevent over-fitting\n self.loss += _CreateL2Reg(self.W, self.B) * self.reg\n self.optmzr = _GetOptimizer(self.optmzrn, self.lr).minimize(self.loss)\n \n def fit(self, A, Y, FD = None):\n '''\n Fit the ANN to the data\n A: numpy matrix where each row is a sample\n Y: numpy matrix of target values\n '''\n m = len(A)\n FD = {self.X:A, self.Y:Y} if FD is None else FD #Feed dictionary\n #Loop up to mIter times gradually scaling up the batch size (if range is provided)\n for i, BSi in enumerate(_GetBatchRange(self.batSz, self.mIter)):\n if BSi is None: #Compute loss and optimize simultaneously for all samples\n err, _ = self.GetSes().run([self.loss, self.optmzr], feed_dict = FD)\n else: #Train m samples using random batches of size self.bs\n err = 0.0\n for j in range(0, m, BSi): #Compute loss and optimize simultaneously for batch\n bi = np.random.choice(m, BSi, False) #Randomly chosen batch indices\n BFD = {k:v[bi] for k, v in FD.items()} #Feed dictionary for this batch\n l, _ = self.GetSes().run([self.loss, self.optmzr], feed_dict = BFD)\n err += l #Accumulate loss over all batches\n err /= len(range(0, m, BSi)) #Average over all batches\n if self.vrbse:\n print(\"Iter {:5d}\\t{:16.8f} (Batch Size: {:5d})\".format(i + 1, err, -1 if BSi is None else BSi))\n if err < self.tol or self.stopIter:\n break #Stop if tolerance was reached or flag was set\n \n def GetBias(self, i):\n '''\n Warning! Does not work with restored models currently.\n Gets the i-th bias vector from the model\n '''\n return self.B[i].eval(session = self.GetSes())\n \n def GetSes(self):\n if ANN.sess is None:\n config = tf.ConfigProto(**self.sesD)\n config.gpu_options.allow_growth = True #Only use GPU memory as needed\n ANN.sess = tf.Session(config = config) #instead of allocating all up-front\n return ANN.sess\n \n def GetWeightMatrix(self, i):\n '''\n Warning! Does not work with restored models currently.\n Gets the i-th weight matrix from the model.\n '''\n return self.W[i].eval(session = self.GetSes())\n\n def Initialize(self):\n '''\n Initialize variables and start the TensorFlow session\n '''\n ANN.sessc += 1 #Increment session counter\n sess = self.GetSes()\n self.init = tf.variables_initializer(self.TFVar)\n sess.run(self.init) #Initialize all variables for this model\n \n def predict(self, A, FD = None):\n '''\n Predict the output given the input (only run after calling fit)\n A: The input values for which to predict outputs\n return: The predicted output values (one row per input sample)\n '''\n FD = {self.X:A} if FD is None else FD\n return self.GetSes().run(self.O[-1], feed_dict = FD)\n \n def PredictFull(self, A, FD = None):\n '''\n Predict the output given the input (only run after calling fit)\n returning all intermediate results\n A: The input values for which to predict outputs\n return: The predicted output values with intermediate results\n (one row per input sample)\n '''\n FD = {self.X:A} if FD is None else FD\n return self.GetSes().run(self.O, feed_dict = FD)\n\n def Reinitialize(self):\n '''\n Reinitialize variables and start the TensorFlow session\n '''\n sess = self.GetSes()\n sess.run(self.init) #Re-Initialize all variables for this model\n \n def Reset():\n '''\n Performs a hard reset of the tensorflow graph and session\n '''\n ANN.sessc = 0\n if ANN.sess is not None:\n ANN.sess.close()\n ANN.sess = None\n tf.reset_default_graph()\n \n def RestoreModel(self, p, n):\n '''\n Restores a model that was previously created with SaveModel\n p: Path to model containing files like \"path/\"\n '''\n try:\n saver = tf.train.Saver()\n saver.restore(self.GetSes(), p + n)\n except Exception as e:\n print('Error restoring: ' + p + n, e)\n return False\n return True\n\n def SaveModel(self, p):\n '''\n Save model to file\n p: Path to save file like \"path/\"\n '''\n saver = tf.train.Saver()\n saver.save(self.GetSes(), p)\n \n def score(self, A, Y, FD = None):\n '''\n Predicts the loss function for given input and target matrices\n A: The input data matrix\n Y: The target matrix\n return: The loss\n '''\n FD = {self.X:A, self.Y:Y} if FD is None else FD\n return self.GetSes().run(self.loss, feed_dict = FD)\n \n def SetBias(self, i, _B):\n '''\n Warning! Does not work with restored models currently.\n Sets the i-th bias from the model.\n '''\n self.B[i].assign(_B).eval(session = self.GetSes())\n\n def SetWeightMatrix(self, i, _W):\n '''\n Warning! Does not work with restored models currently.\n Sets the i-th weight matrix from the model.\n '''\n self.W[i].assign(_W).eval(session = self.GetSes())\n \n def SetMaxIter(self, mi):\n '''\n Update the maximum number of iterations to run for fit\n '''\n self.mIter = mi\n \n def SetStopIter(self, si):\n '''\n Set the flag for stopping iteration early\n '''\n self.stopIter = si\n \n def Tx(self, Y):\n '''\n Map from {0, 1} -> {-0.9, .9} (for tanh activation)\n '''\n return (2 * Y - 1) * 0.9\n \n def TInvX(self, Y):\n '''\n Map from {-0.9, .9} -> {0, 1}\n '''\n return (Y / 0.9 + 1) / 2.0\n \n def YHatF(self, Y):\n '''\n Convert from prediction (YH) to original data type (integer 0 or 1)\n '''\n return Y.clip(0.0, 1.0).round().astype(np.int)\n\nclass ANNR(ANN):\n '''\n Artificial Neural Network for Regression (Base Class)\n '''\n pass\n \nclass MLPB(ANNR):\n '''\n Multi-Layer Perceptron for Binary Data\n '''\n \n def fit(self, A, Y, FD = None):\n '''\n Fit the MLP to the data\n A: numpy matrix where each row is a sample\n y: numpy matrix of target values\n '''\n A = self.Tx(A) #Transform data for better performance\n Y = self.Tx(Y) #with tanh activation\n super().fit(A, Y, FD)\n \n def predict(self, A):\n '''\n Predict the output given the input (only run after calling fit)\n A: The input values for which to predict outputs\n return: The predicted output values (one row per input sample)\n '''\n A = self.Tx(A)\n YH = super().predict(A)\n #Transform back to un-scaled data\n return self.YHatF(self.TInvX(YH))\n \nclass RFSANNR(ANNR):\n '''\n Rectangular Fully-Supervised Artificial Neural Network for Regression\n Requires targets for hidden layers.\n '''\n\n def CreateModel(self):\n if self.X is None: #If no input variable was specified make a new placeholder\n self.X = tf.placeholder(\"float\", [None, self.IS]) #Input data matrix\n self.O, self.W, self.B = _CreateANN(self.pad, self.NA, self.X)\n self.RO = tf.stack(self.O, axis = 1)\n if self.Y is None:\n self.Y = tf.placeholder(\"float\", self.O.shape) #Target value matrix\n self.loss = tf.reduce_mean(self.LF(self.RO, self.Y)) \n if self.reg is not None: #Regularization can prevent over-fitting\n self.loss += _CreateL2Reg(self.W, self.B) * self.reg\n self.optmzr = _GetOptimizer(self.optmzrn, self.lr).minimize(self.loss) #Get optimizer method to minimize the loss function\n\nclass ANNC(ANN):\n '''\n Artificial Neural Network for Classification (Base Class)\n '''\n \n def ClearClasses(self):\n '''\n Clears the class lookup for encoding 1-hot vectors so it will\n be rebuilt on the next call to RestoreClasses\n '''\n self._classes = None\n\n def fit(self, A, Y, FD = None):\n '''\n Fit the MLP to the data\n A: numpy matrix where each row is a sample\n y: numpy matrix of target values\n '''\n Y = self.To1Hot(Y)\n super().fit(A, Y, FD)\n\n def __init__(self, _IS, _NA, batchSize = None, learnRate = 1e-3, loss = 'smce', maxIter = 1024, \n name = 'tfann', optmzrn = 'adam', pad = 'SAME', reg = 1e-3, sesd = {}, tol = 1e-2, \n verbose = False, X = None, Y = None):\n super().__init__(_IS, _NA, batchSize, learnRate, loss, maxIter, name, optmzrn, pad, reg, sesd, tol, verbose, X, Y)\n a = len(self.O[-1].shape) - 1 #Class axis is last axis\n self.YHL = tf.argmax(self.O[-1], axis = a) #Index of label with max probability\n self._classes = None #Lookup table for class labels\n\n def predict(self, A, FD = None):\n '''\n Predict the output given the input (only run after calling fit)\n A: The input values for which to predict outputs\n return: The predicted output values (one row per input sample)\n '''\n #Return prediction labels recovered from 1-hot encoding\n FD = {self.X:A} if FD is None else FD\n return self._classes[self.GetSes().run(self.YHL, feed_dict = FD)]\n\n def RestoreClasses(self, Y):\n '''\n Restores the classes lookup table\n Y: An array that contains all the class labels\n '''\n if self._classes is None:\n self._classes = np.unique(Y)\n\n def score(self, A, Y):\n '''\n Predicts the ouputs for input A and then computes the classification error\n The predicted values and the actualy values\n A: The input values for which to predict outputs\n y: The actual target values\n return: The percent of outputs predicted correctly\n '''\n YH = self.predict(A)\n return _Accuracy(Y, YH)\n\n def To1Hot(self, Y):\n '''\n Creates an array of 1-hot vectors based on a vector of class labels.\n The class label axis for the encoding is the last axis.\n Y: The vector of class labels\n #return: The 1-Hot encoding of Y\n '''\n self._classes, inv = np.unique(Y.ravel(), return_inverse = True)\n b = np.zeros([len(inv), len(self._classes)])\n b[np.arange(b.shape[0]), inv] = 1\n return b.reshape(list(Y.shape) + [len(self._classes)])\n \nclass MLPMC():\n '''\n Multi-Layer Perceptron for Multi-Classification\n Uses n classifiers to solve a multi-classification problem with n output columns.\n '''\n \n def __init__(self, _IS, _NA, batchSize = None, learnRate = 1e-3, loss = 'smce', maxIter = 1024, \n name = 'tfann', optmzrn = 'adam', pad = 'SAME', reg = None, sesd = {}, tol = 1e-2, \n verbose = False, X = None, Y = None):\n '''\n layers: Only specify the input sizes and hidden layers sizes. Output layers are\n automatically inferred from the cl parameter\n cl: The lists of possible classes for each column (from left to right) \n '''\n self.M = [ANNC(_IS, _NAi, batchSize, learnRate, loss, maxIter, name, optmzrn, pad, reg, sesd, tol, verbose, X, Y) for _NAi in _NA]\n \n def fit(self, A, Y, FD = None):\n for i, Mi in enumerate(self.M): #Loop over all columns in output\n Mi.fit(A, Y[:, i], FD) #Fit model for i-th column\n \n def predict(self, A):\n return np.column_stack([Mi.predict(A) for Mi in self.M]) #Stack network predictions together\n \n def score(self, A, Y):\n '''\n The score is # correct / total across all rows and column\n '''\n YH = self.predict(A)\n return (YH == Y).sum() / np.prod(Y.shape)" ]
[ [ "numpy.linspace", "tensorflow.nn.max_pool", "tensorflow.stack", "tensorflow.reduce_sum", "tensorflow.global_variables", "tensorflow.variables_initializer", "tensorflow.nn.conv2d_transpose", "tensorflow.losses.absolute_difference", "tensorflow.nn.sigmoid_cross_entropy_with_logits", "tensorflow.nn.l2_loss", "tensorflow.contrib.layers.flatten", "numpy.mean", "tensorflow.losses.hinge_loss", "tensorflow.train.AdamOptimizer", "tensorflow.rank", "tensorflow.losses.log_loss", "tensorflow.nn.conv1d", "tensorflow.nn.conv2d", "numpy.unique", "numpy.arange", "tensorflow.ConfigProto", "tensorflow.reset_default_graph", "tensorflow.contrib.layers.xavier_initializer", "tensorflow.Session", "tensorflow.train.Saver", "tensorflow.train.FtrlOptimizer", "tensorflow.argmax", "numpy.repeat", "tensorflow.nn.dropout", "tensorflow.train.AdagradOptimizer", "tensorflow.matmul", "numpy.random.choice", "tensorflow.losses.cosine_distance", "tensorflow.placeholder", "tensorflow.train.GradientDescentOptimizer", "tensorflow.nn.bias_add", "tensorflow.constant", "tensorflow.nn.pool", "tensorflow.reduce_mean", "tensorflow.reshape", "tensorflow.nn.lrn", "numpy.prod", "tensorflow.nn.softmax_cross_entropy_with_logits_v2", "tensorflow.variable_scope", "tensorflow.squared_difference" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.10" ] } ]
hirotatsuya/deep-learning-python
[ "83b9da2b616f6b6b545b354b3c0c931b59add6f0" ]
[ "src/matplotlib_sample.py" ]
[ "# numpyとmatplotlibのpyplotというモジュールを使う\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n# データの作成\nx = np.arange(0, 6, 0.1) # 0から6まで0.1刻みで生成\ny1 = np.sin(x)\ny2 = np.cos(x)\n\n# グラフの描画\n# plt.plot(x, y)\n# plt.show()\n\n# 複雑なグラフの描画\nplt.plot(x, y1, label='sin')\nplt.plot(x, y2, linestyle = '--', label='cos') # 破線\nplt.xlabel('x')\nplt.ylabel('y')\nplt.title('sin & cos')\nplt.legend()\nplt.show()" ]
[ [ "matplotlib.pyplot.legend", "matplotlib.pyplot.title", "numpy.arange", "numpy.cos", "numpy.sin", "matplotlib.pyplot.plot", "matplotlib.pyplot.xlabel", "matplotlib.pyplot.show", "matplotlib.pyplot.ylabel" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
ZhenHengDong/bert4keras
[ "de66f9b66a57152816920a6b068a3f28648dd547", "de66f9b66a57152816920a6b068a3f28648dd547" ]
[ "bert4keras/layers.py", "bert4keras/backend.py" ]
[ "#! -*- coding: utf-8 -*-\n# 自定义层\n\nimport numpy as np\nimport tensorflow as tf\nfrom bert4keras.backend import keras, K\nfrom bert4keras.backend import sequence_masking\nfrom keras import initializers, activations\nfrom keras.layers import *\n\n\ndef integerize_shape(func):\n \"\"\"装饰器,保证input_shape一定是int或None\n \"\"\"\n def convert(item):\n if hasattr(item, '__iter__'):\n return [convert(i) for i in item]\n elif hasattr(item, 'value'):\n return item.value\n else:\n return item\n\n def new_func(self, input_shape):\n input_shape = convert(input_shape)\n return func(self, input_shape)\n\n return new_func\n\n\nif keras.__version__[-2:] != 'tf' and keras.__version__ < '2.3':\n\n class Layer(keras.layers.Layer):\n \"\"\"重新定义Layer,赋予“层中层”功能\n (仅keras 2.3以下版本需要)\n \"\"\"\n def __init__(self, **kwargs):\n super(Layer, self).__init__(**kwargs)\n self.supports_masking = True # 本项目的自定义层均可mask\n\n def __setattr__(self, name, value):\n if isinstance(value, keras.layers.Layer):\n if not hasattr(self, '_layers'):\n self._layers = []\n if value not in self._layers:\n self._layers.append(value)\n super(Layer, self).__setattr__(name, value)\n\n @property\n def trainable_weights(self):\n trainable = getattr(self, 'trainable', True)\n if trainable:\n trainable_weights = super(Layer, self).trainable_weights[:]\n for l in getattr(self, '_layers', []):\n trainable_weights += l.trainable_weights\n return trainable_weights\n else:\n return []\n\n @property\n def non_trainable_weights(self):\n trainable = getattr(self, 'trainable', True)\n non_trainable_weights = super(Layer, self).non_trainable_weights[:]\n for l in getattr(self, '_layers', []):\n if trainable:\n non_trainable_weights += l.non_trainable_weights\n else:\n non_trainable_weights += l.weights\n return non_trainable_weights\n\nelse:\n\n class Layer(keras.layers.Layer):\n def __init__(self, **kwargs):\n super(Layer, self).__init__(**kwargs)\n self.supports_masking = True # 本项目的自定义层均可mask\n\n\nclass Embedding(keras.layers.Embedding):\n \"\"\"拓展Embedding层\n \"\"\"\n def compute_mask(self, inputs, mask=None):\n \"\"\"为了适配T5,保证第一个token不被mask\n \"\"\"\n if self._current_mode == 'embedding':\n mask = super(Embedding, self).compute_mask(inputs, mask)\n if mask is not None:\n mask1 = K.ones_like(mask[:, :1], dtype='bool')\n mask2 = mask[:, 1:]\n return K.concatenate([mask1, mask2], 1)\n else:\n return mask\n\n def call(self, inputs, mode='embedding'):\n \"\"\"新增mode参数,可以为embedding或dense。如果为embedding,\n 则等价于普通Embedding层;如果为dense,则等价于无bias的Dense层。\n \"\"\"\n self._current_mode = mode\n if mode == 'embedding':\n return super(Embedding, self).call(inputs)\n else:\n kernel = K.transpose(self.embeddings)\n return K.dot(inputs, kernel)\n\n def compute_output_shape(self, input_shape):\n if self._current_mode == 'embedding':\n return super(Embedding, self).compute_output_shape(input_shape)\n else:\n return input_shape[:2] + (K.int_shape(self.embeddings)[0],)\n\n\nclass BiasAdd(Layer):\n \"\"\"加上偏置项\n \"\"\"\n @integerize_shape\n def build(self, input_shape):\n super(BiasAdd, self).build(input_shape)\n output_dim = input_shape[-1]\n self.bias = self.add_weight(\n name='bias',\n shape=(output_dim,),\n initializer='zeros',\n trainable=True\n )\n\n def call(self, inputs):\n return K.bias_add(inputs, self.bias)\n\n\nclass MultiHeadAttention(Layer):\n \"\"\"多头注意力机制\n \"\"\"\n def __init__(\n self,\n heads,\n head_size,\n key_size=None,\n use_bias=True,\n attention_scale=True,\n kernel_initializer='glorot_uniform',\n **kwargs\n ):\n super(MultiHeadAttention, self).__init__(**kwargs)\n self.heads = heads\n self.head_size = head_size\n self.out_dim = heads * head_size\n self.key_size = key_size or head_size\n self.use_bias = use_bias\n self.attention_scale = attention_scale\n self.kernel_initializer = initializers.get(kernel_initializer)\n\n def build(self, input_shape):\n super(MultiHeadAttention, self).build(input_shape)\n self.q_dense = Dense(\n units=self.key_size * self.heads,\n use_bias=self.use_bias,\n kernel_initializer=self.kernel_initializer\n )\n self.k_dense = Dense(\n units=self.key_size * self.heads,\n use_bias=self.use_bias,\n kernel_initializer=self.kernel_initializer\n )\n self.v_dense = Dense(\n units=self.out_dim,\n use_bias=self.use_bias,\n kernel_initializer=self.kernel_initializer\n )\n self.o_dense = Dense(\n units=self.out_dim,\n use_bias=self.use_bias,\n kernel_initializer=self.kernel_initializer\n )\n\n def call(self, inputs, mask=None, a_mask=None, p_bias=None):\n \"\"\"实现多头注意力\n q_mask: 对输入的query序列的mask。\n 主要是将输出结果的padding部分置0。\n v_mask: 对输入的value序列的mask。\n 主要是防止attention读取到padding信息。\n a_mask: 对attention矩阵的mask。\n 不同的attention mask对应不同的应用。\n p_bias: 在attention里的位置偏置。\n 一般用来指定相对位置编码的种类。\n \"\"\"\n q, k, v = inputs[:3]\n q_mask, v_mask, n = None, None, 3\n if mask is not None:\n if mask[0] is not None:\n q_mask = K.cast(mask[0], K.floatx())\n if mask[2] is not None:\n v_mask = K.cast(mask[2], K.floatx())\n if a_mask:\n a_mask = inputs[n]\n n += 1\n # 线性变换\n qw = self.q_dense(q)\n kw = self.k_dense(k)\n vw = self.v_dense(v)\n # 形状变换\n qw = K.reshape(qw, (-1, K.shape(q)[1], self.heads, self.key_size))\n kw = K.reshape(kw, (-1, K.shape(k)[1], self.heads, self.key_size))\n vw = K.reshape(vw, (-1, K.shape(v)[1], self.heads, self.head_size))\n # Attention\n a = tf.einsum('bjhd,bkhd->bhjk', qw, kw)\n # 处理位置编码\n if p_bias == 'typical_relative':\n pos_embeddings = inputs[n]\n a = a + tf.einsum('bjhd,jkd->bhjk', qw, pos_embeddings)\n elif p_bias == 't5_relative':\n pos_embeddings = K.permute_dimensions(inputs[n], (2, 0, 1))\n a = a + K.expand_dims(pos_embeddings, 0)\n # Attention(续)\n if self.attention_scale:\n a = a / self.key_size**0.5\n a = sequence_masking(a, v_mask, 1, -1)\n if a_mask is not None:\n a = a - (1 - a_mask) * 1e12\n a = K.softmax(a)\n # 完成输出\n o = tf.einsum('bhjk,bkhd->bjhd', a, vw)\n if p_bias == 'typical_relative':\n o = o + tf.einsum('bhjk,jkd->bjhd', a, pos_embeddings)\n o = K.reshape(o, (-1, K.shape(o)[1], self.out_dim))\n o = self.o_dense(o)\n # 返回结果\n o = sequence_masking(o, q_mask, 0)\n return o\n\n def compute_output_shape(self, input_shape):\n return (input_shape[0][0], input_shape[0][1], self.out_dim)\n\n def compute_mask(self, inputs, mask):\n return mask[0]\n\n def get_config(self):\n config = {\n 'heads': self.heads,\n 'head_size': self.head_size,\n 'key_size': self.key_size,\n 'use_bias': self.use_bias,\n 'attention_scale': self.attention_scale,\n 'kernel_initializer':\n initializers.serialize(self.kernel_initializer),\n }\n base_config = super(MultiHeadAttention, self).get_config()\n return dict(list(base_config.items()) + list(config.items()))\n\n\nclass LayerNormalization(Layer):\n \"\"\"(Conditional) Layer Normalization\n hidden_*系列参数仅为有条件输入时(conditional=True)使用\n \"\"\"\n def __init__(\n self,\n center=True,\n scale=True,\n epsilon=None,\n conditional=False,\n hidden_units=None,\n hidden_activation='linear',\n hidden_initializer='glorot_uniform',\n **kwargs\n ):\n super(LayerNormalization, self).__init__(**kwargs)\n self.center = center\n self.scale = scale\n self.conditional = conditional\n self.hidden_units = hidden_units\n self.hidden_activation = activations.get(hidden_activation)\n self.hidden_initializer = initializers.get(hidden_initializer)\n self.epsilon = epsilon or 1e-12\n\n def build(self, input_shape):\n super(LayerNormalization, self).build(input_shape)\n\n if self.conditional:\n shape = (input_shape[0][-1],)\n else:\n shape = (input_shape[-1],)\n\n if self.center:\n self.beta = self.add_weight(\n shape=shape, initializer='zeros', name='beta'\n )\n if self.scale:\n self.gamma = self.add_weight(\n shape=shape, initializer='ones', name='gamma'\n )\n\n if self.conditional:\n\n if self.hidden_units is not None:\n self.hidden_dense = Dense(\n units=self.hidden_units,\n activation=self.hidden_activation,\n use_bias=False,\n kernel_initializer=self.hidden_initializer\n )\n\n if self.center:\n self.beta_dense = Dense(\n units=shape[0], use_bias=False, kernel_initializer='zeros'\n )\n if self.scale:\n self.gamma_dense = Dense(\n units=shape[0], use_bias=False, kernel_initializer='zeros'\n )\n\n def call(self, inputs):\n \"\"\"如果是条件Layer Norm,则默认以list为输入,第二个是condition\n \"\"\"\n if self.conditional:\n inputs, cond = inputs\n if self.hidden_units is not None:\n cond = self.hidden_dense(cond)\n for _ in range(K.ndim(inputs) - K.ndim(cond)):\n cond = K.expand_dims(cond, 1)\n if self.center:\n beta = self.beta_dense(cond) + self.beta\n if self.scale:\n gamma = self.gamma_dense(cond) + self.gamma\n else:\n if self.center:\n beta = self.beta\n if self.scale:\n gamma = self.gamma\n\n outputs = inputs\n if self.center:\n mean = K.mean(outputs, axis=-1, keepdims=True)\n outputs = outputs - mean\n if self.scale:\n variance = K.mean(K.square(outputs), axis=-1, keepdims=True)\n std = K.sqrt(variance + self.epsilon)\n outputs = outputs / std\n outputs = outputs * gamma\n if self.center:\n outputs = outputs + beta\n\n return outputs\n\n def compute_output_shape(self, input_shape):\n if self.conditional:\n return input_shape[0]\n else:\n return input_shape\n\n def get_config(self):\n config = {\n 'center': self.center,\n 'scale': self.scale,\n 'epsilon': self.epsilon,\n 'conditional': self.conditional,\n 'hidden_units': self.hidden_units,\n 'hidden_activation': activations.serialize(self.hidden_activation),\n 'hidden_initializer':\n initializers.serialize(self.hidden_initializer),\n }\n base_config = super(LayerNormalization, self).get_config()\n return dict(list(base_config.items()) + list(config.items()))\n\n\nclass PositionEmbedding(Layer):\n \"\"\"定义位置Embedding,这里的Embedding是可训练的。\n \"\"\"\n def __init__(\n self,\n input_dim,\n output_dim,\n merge_mode='add',\n embeddings_initializer='zeros',\n custom_position_ids=False,\n **kwargs\n ):\n super(PositionEmbedding, self).__init__(**kwargs)\n self.input_dim = input_dim\n self.output_dim = output_dim\n self.merge_mode = merge_mode\n self.embeddings_initializer = initializers.get(embeddings_initializer)\n self.custom_position_ids = custom_position_ids\n\n def build(self, input_shape):\n super(PositionEmbedding, self).build(input_shape)\n self.embeddings = self.add_weight(\n name='embeddings',\n shape=(self.input_dim, self.output_dim),\n initializer=self.embeddings_initializer\n )\n\n def call(self, inputs):\n \"\"\"如果custom_position_ids,那么第二个输入为自定义的位置id\n \"\"\"\n if self.custom_position_ids:\n inputs, position_ids = inputs\n if K.dtype(position_ids) != 'int32':\n position_ids = K.cast(position_ids, 'int32')\n pos_embeddings = K.gather(self.embeddings, position_ids)\n else:\n input_shape = K.shape(inputs)\n batch_size, seq_len = input_shape[0], input_shape[1]\n pos_embeddings = self.embeddings[:seq_len]\n pos_embeddings = K.expand_dims(pos_embeddings, 0)\n if self.merge_mode != 'add':\n pos_embeddings = K.tile(pos_embeddings, [batch_size, 1, 1])\n\n if self.merge_mode == 'add':\n return inputs + pos_embeddings\n else:\n return K.concatenate([inputs, pos_embeddings])\n\n def compute_output_shape(self, input_shape):\n if self.custom_position_ids:\n input_shape = input_shape[0]\n\n if self.merge_mode == 'add':\n return input_shape\n else:\n return input_shape[:2] + (input_shape[2] + self.output_dim,)\n\n def get_config(self):\n config = {\n 'input_dim': self.input_dim,\n 'output_dim': self.output_dim,\n 'merge_mode': self.merge_mode,\n 'embeddings_initializer':\n initializers.serialize(self.embeddings_initializer),\n 'custom_position_ids': self.custom_position_ids,\n }\n base_config = super(PositionEmbedding, self).get_config()\n return dict(list(base_config.items()) + list(config.items()))\n\n\nclass RelativePositionEmbedding(Layer):\n \"\"\"相对位置编码\n 来自论文:https://arxiv.org/abs/1803.02155\n \"\"\"\n def __init__(\n self, input_dim, output_dim, embeddings_initializer='zeros', **kwargs\n ):\n super(RelativePositionEmbedding, self).__init__(**kwargs)\n self.input_dim = input_dim\n self.output_dim = output_dim\n self.embeddings_initializer = initializers.get(embeddings_initializer)\n\n def build(self, input_shape):\n super(RelativePositionEmbedding, self).build(input_shape)\n self.embeddings = self.add_weight(\n name='embeddings',\n shape=(self.input_dim, self.output_dim),\n initializer=self.embeddings_initializer,\n )\n\n def call(self, inputs):\n pos_ids = self.compute_position_ids(inputs)\n return K.gather(self.embeddings, pos_ids)\n\n def compute_position_ids(self, inputs):\n q, v = inputs\n # 计算位置差\n q_idxs = K.arange(0, K.shape(q)[1], dtype='int32')\n q_idxs = K.expand_dims(q_idxs, 1)\n v_idxs = K.arange(0, K.shape(v)[1], dtype='int32')\n v_idxs = K.expand_dims(v_idxs, 0)\n pos_ids = v_idxs - q_idxs\n # 后处理操作\n max_position = (self.input_dim - 1) // 2\n pos_ids = K.clip(pos_ids, -max_position, max_position)\n pos_ids = pos_ids + max_position\n return pos_ids\n\n def compute_output_shape(self, input_shape):\n return (None, None, self.output_dim)\n\n def compute_mask(self, inputs, mask):\n return mask[0]\n\n def get_config(self):\n config = {\n 'input_dim': self.input_dim,\n 'output_dim': self.output_dim,\n 'embeddings_initializer':\n initializers.serialize(self.embeddings_initializer),\n }\n base_config = super(RelativePositionEmbedding, self).get_config()\n return dict(list(base_config.items()) + list(config.items()))\n\n\nclass RelativePositionEmbeddingT5(RelativePositionEmbedding):\n \"\"\"Google T5的相对位置编码\n 来自论文:https://arxiv.org/abs/1910.10683\n \"\"\"\n def __init__(\n self,\n input_dim,\n output_dim,\n max_distance=128,\n bidirectional=True,\n embeddings_initializer='zeros',\n **kwargs\n ):\n super(RelativePositionEmbeddingT5,\n self).__init__(input_dim, output_dim, **kwargs)\n self.max_distance = max_distance\n self.bidirectional = bidirectional\n\n def compute_position_ids(self, inputs):\n \"\"\"T5的相对位置分桶(直接翻译自官方T5源码)\n \"\"\"\n q, v = inputs\n # 计算位置差\n q_idxs = K.arange(0, K.shape(q)[1], dtype='int32')\n q_idxs = K.expand_dims(q_idxs, 1)\n v_idxs = K.arange(0, K.shape(v)[1], dtype='int32')\n v_idxs = K.expand_dims(v_idxs, 0)\n pos_ids = v_idxs - q_idxs\n # 后处理操作\n num_buckets, max_distance = self.input_dim, self.max_distance\n ret = 0\n n = -pos_ids\n if self.bidirectional:\n num_buckets //= 2\n ret += K.cast(K.less(n, 0), 'int32') * num_buckets\n n = K.abs(n)\n else:\n n = K.maximum(n, 0)\n # now n is in the range [0, inf)\n max_exact = num_buckets // 2\n is_small = K.less(n, max_exact)\n val_if_large = max_exact + K.cast(\n K.log(K.cast(n, K.floatx()) / max_exact) /\n np.log(max_distance / max_exact) * (num_buckets - max_exact),\n 'int32',\n )\n val_if_large = K.minimum(val_if_large, num_buckets - 1)\n ret += K.switch(is_small, n, val_if_large)\n return ret\n\n def get_config(self):\n config = {\n 'max_distance': self.max_distance,\n 'bidirectional': self.bidirectional,\n }\n base_config = super(RelativePositionEmbeddingT5, self).get_config()\n return dict(list(base_config.items()) + list(config.items()))\n\n\nclass FeedForward(Layer):\n \"\"\"FeedForward层,其实就是两个Dense层的叠加\n \"\"\"\n def __init__(\n self,\n units,\n activation='relu',\n use_bias=True,\n kernel_initializer='glorot_uniform',\n **kwargs\n ):\n super(FeedForward, self).__init__(**kwargs)\n self.units = units\n self.activation = activations.get(activation)\n self.use_bias = use_bias\n self.kernel_initializer = initializers.get(kernel_initializer)\n\n @integerize_shape\n def build(self, input_shape):\n super(FeedForward, self).build(input_shape)\n output_dim = input_shape[-1]\n\n self.dense_1 = Dense(\n units=self.units,\n activation=self.activation,\n use_bias=self.use_bias,\n kernel_initializer=self.kernel_initializer\n )\n self.dense_2 = Dense(\n units=output_dim,\n use_bias=self.use_bias,\n kernel_initializer=self.kernel_initializer\n )\n\n def call(self, inputs):\n x = inputs\n x = self.dense_1(x)\n x = self.dense_2(x)\n return x\n\n def get_config(self):\n config = {\n 'units': self.units,\n 'activation': activations.serialize(self.activation),\n 'use_bias': self.use_bias,\n 'kernel_initializer':\n initializers.serialize(self.kernel_initializer),\n }\n base_config = super(FeedForward, self).get_config()\n return dict(list(base_config.items()) + list(config.items()))\n\n\nclass ConditionalRandomField(Layer):\n \"\"\"纯Keras实现CRF层\n CRF层本质上是一个带训练参数的loss计算层。\n \"\"\"\n def __init__(self, lr_multiplier=1, **kwargs):\n super(ConditionalRandomField, self).__init__(**kwargs)\n self.lr_multiplier = lr_multiplier # 当前层学习率的放大倍数\n\n @integerize_shape\n def build(self, input_shape):\n super(ConditionalRandomField, self).build(input_shape)\n output_dim = input_shape[-1]\n self.trans = self.add_weight(\n name='trans',\n shape=(output_dim, output_dim),\n initializer='glorot_uniform',\n trainable=True\n )\n if self.lr_multiplier != 1:\n K.set_value(self.trans, K.eval(self.trans) / self.lr_multiplier)\n self.trans = self.lr_multiplier * self.trans\n\n def compute_mask(self, inputs, mask=None):\n return None\n\n def call(self, inputs, mask=None):\n if mask is not None:\n mask = K.cast(mask, K.floatx())\n\n return sequence_masking(inputs, mask, 1, 1)\n\n def target_score(self, y_true, y_pred):\n \"\"\"计算目标路径的相对概率(还没有归一化)\n 要点:逐标签得分,加上转移概率得分。\n \"\"\"\n point_score = tf.einsum('bni,bni->b', y_true, y_pred) # 逐标签得分\n trans_score = tf.einsum(\n 'bni,ij,bnj->b', y_true[:, :-1], self.trans, y_true[:, 1:]\n ) # 标签转移得分\n return point_score + trans_score\n\n def log_norm_step(self, inputs, states):\n \"\"\"递归计算归一化因子\n 要点:1、递归计算;2、用logsumexp避免溢出。\n \"\"\"\n inputs, mask = inputs[:, :-1], inputs[:, -1:]\n states = K.expand_dims(states[0], 2) # (batch_size, output_dim, 1)\n trans = K.expand_dims(self.trans, 0) # (1, output_dim, output_dim)\n outputs = tf.reduce_logsumexp(\n states + trans, 1\n ) # (batch_size, output_dim)\n outputs = outputs + inputs\n outputs = mask * outputs + (1 - mask) * states[:, :, 0]\n return outputs, [outputs]\n\n def dense_loss(self, y_true, y_pred):\n \"\"\"y_true需要是one hot形式\n \"\"\"\n # 导出mask并转换数据类型\n mask = K.all(K.greater(y_pred, -1e6), axis=2, keepdims=True)\n mask = K.cast(mask, K.floatx())\n # 计算目标分数\n y_true, y_pred = y_true * mask, y_pred * mask\n target_score = self.target_score(y_true, y_pred)\n # 递归计算log Z\n init_states = [y_pred[:, 0]]\n y_pred = K.concatenate([y_pred, mask], axis=2)\n input_length = K.int_shape(y_pred[:, 1:])[1]\n log_norm, _, _ = K.rnn(\n self.log_norm_step,\n y_pred[:, 1:],\n init_states,\n input_length=input_length\n ) # 最后一步的log Z向量\n log_norm = tf.reduce_logsumexp(log_norm, 1) # logsumexp得标量\n # 计算损失 -log p\n return log_norm - target_score\n\n def sparse_loss(self, y_true, y_pred):\n \"\"\"y_true需要是整数形式(非one hot)\n \"\"\"\n # y_true需要重新明确一下shape和dtype\n y_true = K.reshape(y_true, K.shape(y_pred)[:-1])\n y_true = K.cast(y_true, 'int32')\n # 转为one hot\n y_true = K.one_hot(y_true, K.shape(self.trans)[0])\n return self.dense_loss(y_true, y_pred)\n\n def dense_accuracy(self, y_true, y_pred):\n \"\"\"训练过程中显示逐帧准确率的函数,排除了mask的影响\n 此处y_true需要是one hot形式\n \"\"\"\n y_true = K.argmax(y_true, 2)\n return self.sparse_accuracy(y_true, y_pred)\n\n def sparse_accuracy(self, y_true, y_pred):\n \"\"\"训练过程中显示逐帧准确率的函数,排除了mask的影响\n 此处y_true需要是整数形式(非one hot)\n \"\"\"\n # 导出mask并转换数据类型\n mask = K.all(K.greater(y_pred, -1e6), axis=2)\n mask = K.cast(mask, K.floatx())\n # y_true需要重新明确一下shape和dtype\n y_true = K.reshape(y_true, K.shape(y_pred)[:-1])\n y_true = K.cast(y_true, 'int32')\n # 逐标签取最大来粗略评测训练效果\n y_pred = K.cast(K.argmax(y_pred, 2), 'int32')\n isequal = K.cast(K.equal(y_true, y_pred), K.floatx())\n return K.sum(isequal * mask) / K.sum(mask)\n\n def get_config(self):\n config = {\n 'lr_multiplier': self.lr_multiplier,\n }\n base_config = super(ConditionalRandomField, self).get_config()\n return dict(list(base_config.items()) + list(config.items()))\n\n\nclass MaximumEntropyMarkovModel(Layer):\n \"\"\"(双向)最大熵隐马尔可夫模型\n 作用和用法都类似CRF,但是比CRF更快更简单。\n \"\"\"\n def __init__(self, lr_multiplier=1, hidden_dim=None, **kwargs):\n super(MaximumEntropyMarkovModel, self).__init__(**kwargs)\n self.lr_multiplier = lr_multiplier # 当前层学习率的放大倍数\n self.hidden_dim = hidden_dim # 如果非None,则将转移矩阵低秩分解\n\n @integerize_shape\n def build(self, input_shape):\n super(MaximumEntropyMarkovModel, self).build(input_shape)\n output_dim = input_shape[-1]\n\n if self.hidden_dim is None:\n self.trans = self.add_weight(\n name='trans',\n shape=(output_dim, output_dim),\n initializer='glorot_uniform',\n trainable=True\n )\n if self.lr_multiplier != 1:\n K.set_value(self.trans, K.eval(self.trans) / self.lr_multiplier)\n self.trans = self.lr_multiplier * self.trans\n else:\n self.l_trans = self.add_weight(\n name='l_trans',\n shape=(output_dim, self.hidden_dim),\n initializer='glorot_uniform',\n trainable=True\n )\n self.r_trans = self.add_weight(\n name='r_trans',\n shape=(output_dim, self.hidden_dim),\n initializer='glorot_uniform',\n trainable=True\n )\n\n if self.lr_multiplier != 1:\n K.set_value(\n self.l_trans,\n K.eval(self.l_trans) / self.lr_multiplier\n )\n self.l_trans = self.lr_multiplier * self.l_trans\n K.set_value(\n self.r_trans,\n K.eval(self.r_trans) / self.lr_multiplier\n )\n self.r_trans = self.lr_multiplier * self.r_trans\n\n def compute_mask(self, inputs, mask=None):\n return None\n\n def call(self, inputs, mask=None):\n if mask is not None:\n mask = K.cast(mask, K.floatx())\n\n return sequence_masking(inputs, mask, 1, 1)\n\n def reverse_sequence(self, inputs, mask=None):\n if mask is None:\n return [x[:, ::-1] for x in inputs]\n else:\n length = K.cast(K.sum(mask, 1), 'int32')\n return [tf.reverse_sequence(x, length, seq_axis=1) for x in inputs]\n\n def basic_loss(self, y_true, y_pred, go_backwards=False):\n \"\"\"y_true需要是整数形式(非one hot)\n \"\"\"\n # 导出mask并转换数据类型\n mask = K.all(K.greater(y_pred, -1e6), axis=2)\n mask = K.cast(mask, K.floatx())\n # y_true需要重新明确一下shape和dtype\n y_true = K.reshape(y_true, K.shape(y_pred)[:-1])\n y_true = K.cast(y_true, 'int32')\n # 反转相关\n if self.hidden_dim is None:\n if go_backwards: # 是否反转序列\n y_true, y_pred = self.reverse_sequence([y_true, y_pred], mask)\n trans = K.transpose(self.trans)\n else:\n trans = self.trans\n histoty = K.gather(trans, y_true)\n else:\n if go_backwards: # 是否反转序列\n y_true, y_pred = self.reverse_sequence([y_true, y_pred], mask)\n r_trans, l_trans = self.l_trans, self.r_trans\n else:\n l_trans, r_trans = self.l_trans, self.r_trans\n histoty = K.gather(l_trans, y_true)\n histoty = tf.einsum('bnd,kd->bnk', histoty, r_trans)\n # 计算loss\n histoty = K.concatenate([y_pred[:, :1], histoty[:, :-1]], 1)\n y_pred = (y_pred + histoty) / 2\n loss = K.sparse_categorical_crossentropy(\n y_true, y_pred, from_logits=True\n )\n return K.sum(loss * mask) / K.sum(mask)\n\n def sparse_loss(self, y_true, y_pred):\n \"\"\"y_true需要是整数形式(非one hot)\n \"\"\"\n loss = self.basic_loss(y_true, y_pred, False)\n loss = loss + self.basic_loss(y_true, y_pred, True)\n return loss / 2\n\n def dense_loss(self, y_true, y_pred):\n \"\"\"y_true需要是one hot形式\n \"\"\"\n y_true = K.argmax(y_true, 2)\n return self.sparse_loss(y_true, y_pred)\n\n def basic_accuracy(self, y_true, y_pred, go_backwards=False):\n \"\"\"训练过程中显示逐帧准确率的函数,排除了mask的影响\n 此处y_true需要是整数形式(非one hot)\n \"\"\"\n # 导出mask并转换数据类型\n mask = K.all(K.greater(y_pred, -1e6), axis=2)\n mask = K.cast(mask, K.floatx())\n # y_true需要重新明确一下shape和dtype\n y_true = K.reshape(y_true, K.shape(y_pred)[:-1])\n y_true = K.cast(y_true, 'int32')\n # 反转相关\n if self.hidden_dim is None:\n if go_backwards: # 是否反转序列\n y_true, y_pred = self.reverse_sequence([y_true, y_pred], mask)\n trans = K.transpose(self.trans)\n else:\n trans = self.trans\n histoty = K.gather(trans, y_true)\n else:\n if go_backwards: # 是否反转序列\n y_true, y_pred = self.reverse_sequence([y_true, y_pred], mask)\n r_trans, l_trans = self.l_trans, self.r_trans\n else:\n l_trans, r_trans = self.l_trans, self.r_trans\n histoty = K.gather(l_trans, y_true)\n histoty = tf.einsum('bnd,kd->bnk', histoty, r_trans)\n # 计算逐标签accuracy\n histoty = K.concatenate([y_pred[:, :1], histoty[:, :-1]], 1)\n y_pred = (y_pred + histoty) / 2\n y_pred = K.cast(K.argmax(y_pred, 2), 'int32')\n isequal = K.cast(K.equal(y_true, y_pred), K.floatx())\n return K.sum(isequal * mask) / K.sum(mask)\n\n def sparse_accuracy(self, y_true, y_pred):\n \"\"\"训练过程中显示逐帧准确率的函数,排除了mask的影响\n 此处y_true需要是整数形式(非one hot)\n \"\"\"\n accuracy = self.basic_accuracy(y_true, y_pred, False)\n accuracy = accuracy + self.basic_accuracy(y_true, y_pred, True)\n return accuracy / 2\n\n def dense_accuracy(self, y_true, y_pred):\n \"\"\"训练过程中显示逐帧准确率的函数,排除了mask的影响\n 此处y_true需要是one hot形式\n \"\"\"\n y_true = K.argmax(y_true, 2)\n return self.sparse_accuracy(y_true, y_pred)\n\n def get_config(self):\n config = {\n 'lr_multiplier': self.lr_multiplier,\n 'hidden_dim': self.hidden_dim,\n }\n base_config = super(MaximumEntropyMarkovModel, self).get_config()\n return dict(list(base_config.items()) + list(config.items()))\n\n\nclass Loss(Layer):\n \"\"\"特殊的层,用来定义复杂loss\n \"\"\"\n def __init__(self, output_axis=None, **kwargs):\n super(Loss, self).__init__(**kwargs)\n self.output_axis = output_axis\n\n def call(self, inputs, mask=None):\n loss = self.compute_loss(inputs, mask)\n self.add_loss(loss)\n if self.output_axis is None:\n return inputs\n elif isinstance(self.output_axis, list):\n return [inputs[i] for i in self.output_axis]\n else:\n return inputs[self.output_axis]\n\n def compute_loss(self, inputs, mask=None):\n raise NotImplementedError\n\n def compute_output_shape(self, input_shape):\n if self.output_axis is None:\n return input_shape\n elif isinstance(self.output_axis, list):\n return [input_shape[i] for i in self.output_axis]\n else:\n return input_shape[self.output_axis]\n\n def get_config(self):\n config = {\n 'output_axis': self.output_axis,\n }\n base_config = super(Loss, self).get_config()\n return dict(list(base_config.items()) + list(config.items()))\n\n\ncustom_objects = {\n 'Embedding': Embedding,\n 'BiasAdd': BiasAdd,\n 'MultiHeadAttention': MultiHeadAttention,\n 'LayerNormalization': LayerNormalization,\n 'PositionEmbedding': PositionEmbedding,\n 'RelativePositionEmbedding': RelativePositionEmbedding,\n 'RelativePositionEmbeddingT5': RelativePositionEmbeddingT5,\n 'FeedForward': FeedForward,\n 'ConditionalRandomField': ConditionalRandomField,\n 'MaximumEntropyMarkovModel': MaximumEntropyMarkovModel,\n 'Loss': Loss,\n}\n\nkeras.utils.get_custom_objects().update(custom_objects)\n", "# -*- coding: utf-8 -*-\n# 分离后端函数,主要是为了同时兼容原生keras和tf.keras\n# 通过设置环境变量TF_KERAS=1来切换tf.keras\n\nimport os, sys\nfrom distutils.util import strtobool\nimport numpy as np\nimport tensorflow as tf\n\n# 判断是tf.keras还是纯keras的标记\nis_tf_keras = strtobool(os.environ.get('TF_KERAS', '0'))\n\nif is_tf_keras:\n import tensorflow.keras as keras\n import tensorflow.keras.backend as K\n sys.modules['keras'] = keras\nelse:\n import keras\n import keras.backend as K\n\n# 判断是否启用动态图模式,仅在TF 2.x下可用。\n# 建议关闭。珍惜生命,远离eager。\nis_tf_eager = strtobool(os.environ.get('TF_EAGER', '0'))\n\nif tf.__version__.startswith('2.') and is_tf_keras:\n if not is_tf_eager:\n tf.compat.v1.disable_eager_execution()\n tf.compat.v1.experimental.output_all_intermediates(True)\n\n\ndef gelu_erf(x):\n \"\"\"基于Erf直接计算的gelu函数\n \"\"\"\n return 0.5 * x * (1.0 + tf.math.erf(x / np.sqrt(2.0)))\n\n\ndef gelu_tanh(x):\n \"\"\"基于Tanh近似计算的gelu函数\n \"\"\"\n cdf = 0.5 * (\n 1.0 + K.tanh((np.sqrt(2 / np.pi) * (x + 0.044715 * K.pow(x, 3))))\n )\n return x * cdf\n\n\ndef set_gelu(version):\n \"\"\"设置gelu版本\n \"\"\"\n version = version.lower()\n assert version in ['erf', 'tanh'], 'gelu version must be erf or tanh'\n if version == 'erf':\n keras.utils.get_custom_objects()['gelu'] = gelu_erf\n else:\n keras.utils.get_custom_objects()['gelu'] = gelu_tanh\n\n\ndef piecewise_linear(t, schedule):\n \"\"\"分段线性函数\n 其中schedule是形如{1000: 1, 2000: 0.1}的字典,\n 表示 t ∈ [0, 1000]时,输出从0均匀增加至1,而\n t ∈ [1000, 2000]时,输出从1均匀降低到0.1,最后\n t > 2000时,保持0.1不变。\n \"\"\"\n schedule = sorted(schedule.items())\n if schedule[0][0] != 0:\n schedule = [(0, 0.0)] + schedule\n\n x = K.constant(schedule[0][1], dtype=K.floatx())\n t = K.cast(t, K.floatx())\n for i in range(len(schedule)):\n t_begin = schedule[i][0]\n x_begin = x\n if i != len(schedule) - 1:\n dx = schedule[i + 1][1] - schedule[i][1]\n dt = schedule[i + 1][0] - schedule[i][0]\n slope = 1.0 * dx / dt\n x = schedule[i][1] + slope * (t - t_begin)\n else:\n x = K.constant(schedule[i][1], dtype=K.floatx())\n x = K.switch(t >= t_begin, x, x_begin)\n\n return x\n\n\ndef search_layer(inputs, name, exclude_from=None):\n \"\"\"根据inputs和name来搜索层\n 说明:inputs为某个层或某个层的输出;name为目标层的名字。\n 实现:根据inputs一直往上递归搜索,直到发现名字为name的层为止;\n 如果找不到,那就返回None。\n \"\"\"\n if exclude_from is None:\n exclude_from = set()\n\n if isinstance(inputs, keras.layers.Layer):\n layer = inputs\n else:\n layer = inputs._keras_history[0]\n\n if layer.name == name:\n return layer\n elif layer in exclude_from:\n return None\n else:\n exclude_from.add(layer)\n if isinstance(layer, keras.models.Model):\n model = layer\n for layer in model.layers:\n if layer.name == name:\n return layer\n inbound_layers = layer._inbound_nodes[0].inbound_layers\n if not isinstance(inbound_layers, list):\n inbound_layers = [inbound_layers]\n if len(inbound_layers) > 0:\n for layer in inbound_layers:\n layer = search_layer(layer, name, exclude_from)\n if layer is not None:\n return layer\n\n\ndef sequence_masking(x, mask, mode=0, axis=None):\n \"\"\"为序列条件mask的函数\n mask: 形如(batch_size, seq_len)的0-1矩阵;\n mode: 如果是0,则直接乘以mask;\n 如果是1,则在padding部分减去一个大正数。\n axis: 序列所在轴,默认为1;\n \"\"\"\n if mask is None or mode not in [0, 1]:\n return x\n else:\n if axis is None:\n axis = 1\n if axis == -1:\n axis = K.ndim(x) - 1\n assert axis > 0, 'axis muse be greater than 0'\n for _ in range(axis - 1):\n mask = K.expand_dims(mask, 1)\n for _ in range(K.ndim(x) - K.ndim(mask) - axis + 1):\n mask = K.expand_dims(mask, K.ndim(mask))\n if mode == 0:\n return x * mask\n else:\n return x - (1 - mask) * 1e12\n\n\ndef batch_gather(params, indices):\n \"\"\"同tf旧版本的batch_gather\n \"\"\"\n try:\n return tf.gather(params, indices, batch_dims=-1)\n except Exception as e1:\n try:\n return tf.batch_gather(params, indices)\n except Exception as e2:\n raise ValueError('%s\\n%s\\n' % (e1.message, e2.message))\n\n\ndef pool1d(\n x,\n pool_size,\n strides=1,\n padding='valid',\n data_format=None,\n pool_mode='max'\n):\n \"\"\"向量序列的pool函数\n \"\"\"\n x = K.expand_dims(x, 1)\n x = K.pool2d(\n x,\n pool_size=(1, pool_size),\n strides=(1, strides),\n padding=padding,\n data_format=data_format,\n pool_mode=pool_mode\n )\n return x[:, 0]\n\n\ndef divisible_temporal_padding(x, n):\n \"\"\"将一维向量序列右padding到长度能被n整除\n \"\"\"\n r_len = K.shape(x)[1] % n\n p_len = K.switch(r_len > 0, n - r_len, 0)\n return K.temporal_padding(x, (0, p_len))\n\n\ndef swish(x):\n \"\"\"swish函数(这样封装过后才有 __name__ 属性)\n \"\"\"\n return tf.nn.swish(x)\n\n\ndef leaky_relu(x, alpha=0.2):\n \"\"\"leaky relu函数(这样封装过后才有 __name__ 属性)\n \"\"\"\n return tf.nn.leaky_relu(x, alpha=alpha)\n\n\ndef symbolic(f):\n \"\"\"恒等装饰器(兼容旧版本keras用)\n \"\"\"\n return f\n\n\n# 给旧版本keras新增symbolic方法(装饰器),\n# 以便兼容optimizers.py中的代码\nK.symbolic = getattr(K, 'symbolic', None) or symbolic\n\ncustom_objects = {\n 'gelu_erf': gelu_erf,\n 'gelu_tanh': gelu_tanh,\n 'gelu': gelu_erf,\n 'swish': swish,\n 'leaky_relu': leaky_relu,\n}\n\nkeras.utils.get_custom_objects().update(custom_objects)\n" ]
[ [ "numpy.log", "tensorflow.reverse_sequence", "tensorflow.reduce_logsumexp", "tensorflow.einsum" ], [ "numpy.sqrt", "tensorflow.batch_gather", "tensorflow.gather", "tensorflow.nn.swish", "tensorflow.compat.v1.disable_eager_execution", "tensorflow.compat.v1.experimental.output_all_intermediates", "tensorflow.__version__.startswith", "tensorflow.nn.leaky_relu" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.10", "1.12", "1.4", "1.5", "1.7", "0.12", "1.0", "1.2" ] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.10" ] } ]
henighan/pandas
[ "45d8d77f27cf0dbc8cefe932f8fb64f6982b9527", "45d8d77f27cf0dbc8cefe932f8fb64f6982b9527" ]
[ "pandas/tests/indexes/datetimes/test_setops.py", "pandas/tests/series/methods/test_sort_values.py" ]
[ "from datetime import datetime\n\nimport numpy as np\nimport pytest\n\nimport pandas.util._test_decorators as td\n\nimport pandas as pd\nfrom pandas import (\n DataFrame,\n DatetimeIndex,\n Index,\n Int64Index,\n Series,\n bdate_range,\n date_range,\n to_datetime,\n)\nimport pandas._testing as tm\n\nfrom pandas.tseries.offsets import BMonthEnd, Minute, MonthEnd\n\nSTART, END = datetime(2009, 1, 1), datetime(2010, 1, 1)\n\n\nclass TestDatetimeIndexSetOps:\n tz = [\n None,\n \"UTC\",\n \"Asia/Tokyo\",\n \"US/Eastern\",\n \"dateutil/Asia/Singapore\",\n \"dateutil/US/Pacific\",\n ]\n\n # TODO: moved from test_datetimelike; dedup with version below\n @pytest.mark.parametrize(\"sort\", [None, False])\n def test_union2(self, sort):\n everything = tm.makeDateIndex(10)\n first = everything[:5]\n second = everything[5:]\n union = first.union(second, sort=sort)\n tm.assert_index_equal(union, everything)\n\n @pytest.mark.parametrize(\"box\", [np.array, Series, list])\n @pytest.mark.parametrize(\"sort\", [None, False])\n def test_union3(self, sort, box):\n everything = tm.makeDateIndex(10)\n first = everything[:5]\n second = everything[5:]\n\n # GH 10149\n expected = (\n first.astype(\"O\").union(pd.Index(second.values, dtype=\"O\")).astype(\"O\")\n )\n case = box(second.values)\n result = first.union(case, sort=sort)\n tm.assert_index_equal(result, expected)\n\n @pytest.mark.parametrize(\"tz\", tz)\n @pytest.mark.parametrize(\"sort\", [None, False])\n def test_union(self, tz, sort):\n rng1 = pd.date_range(\"1/1/2000\", freq=\"D\", periods=5, tz=tz)\n other1 = pd.date_range(\"1/6/2000\", freq=\"D\", periods=5, tz=tz)\n expected1 = pd.date_range(\"1/1/2000\", freq=\"D\", periods=10, tz=tz)\n expected1_notsorted = pd.DatetimeIndex(list(other1) + list(rng1))\n\n rng2 = pd.date_range(\"1/1/2000\", freq=\"D\", periods=5, tz=tz)\n other2 = pd.date_range(\"1/4/2000\", freq=\"D\", periods=5, tz=tz)\n expected2 = pd.date_range(\"1/1/2000\", freq=\"D\", periods=8, tz=tz)\n expected2_notsorted = pd.DatetimeIndex(list(other2) + list(rng2[:3]))\n\n rng3 = pd.date_range(\"1/1/2000\", freq=\"D\", periods=5, tz=tz)\n other3 = pd.DatetimeIndex([], tz=tz)\n expected3 = pd.date_range(\"1/1/2000\", freq=\"D\", periods=5, tz=tz)\n expected3_notsorted = rng3\n\n for rng, other, exp, exp_notsorted in [\n (rng1, other1, expected1, expected1_notsorted),\n (rng2, other2, expected2, expected2_notsorted),\n (rng3, other3, expected3, expected3_notsorted),\n ]:\n\n result_union = rng.union(other, sort=sort)\n tm.assert_index_equal(result_union, exp)\n\n result_union = other.union(rng, sort=sort)\n if sort is None:\n tm.assert_index_equal(result_union, exp)\n else:\n tm.assert_index_equal(result_union, exp_notsorted)\n\n @pytest.mark.parametrize(\"sort\", [None, False])\n def test_union_coverage(self, sort):\n idx = DatetimeIndex([\"2000-01-03\", \"2000-01-01\", \"2000-01-02\"])\n ordered = DatetimeIndex(idx.sort_values(), freq=\"infer\")\n result = ordered.union(idx, sort=sort)\n tm.assert_index_equal(result, ordered)\n\n result = ordered[:0].union(ordered, sort=sort)\n tm.assert_index_equal(result, ordered)\n assert result.freq == ordered.freq\n\n @pytest.mark.parametrize(\"sort\", [None, False])\n def test_union_bug_1730(self, sort):\n rng_a = date_range(\"1/1/2012\", periods=4, freq=\"3H\")\n rng_b = date_range(\"1/1/2012\", periods=4, freq=\"4H\")\n\n result = rng_a.union(rng_b, sort=sort)\n exp = list(rng_a) + list(rng_b[1:])\n if sort is None:\n exp = DatetimeIndex(sorted(exp))\n else:\n exp = DatetimeIndex(exp)\n tm.assert_index_equal(result, exp)\n\n @pytest.mark.parametrize(\"sort\", [None, False])\n def test_union_bug_1745(self, sort):\n left = DatetimeIndex([\"2012-05-11 15:19:49.695000\"])\n right = DatetimeIndex(\n [\n \"2012-05-29 13:04:21.322000\",\n \"2012-05-11 15:27:24.873000\",\n \"2012-05-11 15:31:05.350000\",\n ]\n )\n\n result = left.union(right, sort=sort)\n exp = DatetimeIndex(\n [\n \"2012-05-11 15:19:49.695000\",\n \"2012-05-29 13:04:21.322000\",\n \"2012-05-11 15:27:24.873000\",\n \"2012-05-11 15:31:05.350000\",\n ]\n )\n if sort is None:\n exp = exp.sort_values()\n tm.assert_index_equal(result, exp)\n\n @pytest.mark.parametrize(\"sort\", [None, False])\n def test_union_bug_4564(self, sort):\n from pandas import DateOffset\n\n left = date_range(\"2013-01-01\", \"2013-02-01\")\n right = left + DateOffset(minutes=15)\n\n result = left.union(right, sort=sort)\n exp = list(left) + list(right)\n if sort is None:\n exp = DatetimeIndex(sorted(exp))\n else:\n exp = DatetimeIndex(exp)\n tm.assert_index_equal(result, exp)\n\n @pytest.mark.parametrize(\"sort\", [None, False])\n def test_union_freq_both_none(self, sort):\n # GH11086\n expected = bdate_range(\"20150101\", periods=10)\n expected._data.freq = None\n\n result = expected.union(expected, sort=sort)\n tm.assert_index_equal(result, expected)\n assert result.freq is None\n\n def test_union_dataframe_index(self):\n rng1 = date_range(\"1/1/1999\", \"1/1/2012\", freq=\"MS\")\n s1 = Series(np.random.randn(len(rng1)), rng1)\n\n rng2 = date_range(\"1/1/1980\", \"12/1/2001\", freq=\"MS\")\n s2 = Series(np.random.randn(len(rng2)), rng2)\n df = DataFrame({\"s1\": s1, \"s2\": s2})\n\n exp = pd.date_range(\"1/1/1980\", \"1/1/2012\", freq=\"MS\")\n tm.assert_index_equal(df.index, exp)\n\n @pytest.mark.parametrize(\"sort\", [None, False])\n def test_union_with_DatetimeIndex(self, sort):\n i1 = Int64Index(np.arange(0, 20, 2))\n i2 = date_range(start=\"2012-01-03 00:00:00\", periods=10, freq=\"D\")\n # Works\n i1.union(i2, sort=sort)\n # Fails with \"AttributeError: can't set attribute\"\n i2.union(i1, sort=sort)\n\n # TODO: moved from test_datetimelike; de-duplicate with version below\n def test_intersection2(self):\n first = tm.makeDateIndex(10)\n second = first[5:]\n intersect = first.intersection(second)\n assert tm.equalContents(intersect, second)\n\n # GH 10149\n cases = [klass(second.values) for klass in [np.array, Series, list]]\n for case in cases:\n result = first.intersection(case)\n assert tm.equalContents(result, second)\n\n third = Index([\"a\", \"b\", \"c\"])\n result = first.intersection(third)\n expected = pd.Index([], dtype=object)\n tm.assert_index_equal(result, expected)\n\n @pytest.mark.parametrize(\n \"tz\", [None, \"Asia/Tokyo\", \"US/Eastern\", \"dateutil/US/Pacific\"]\n )\n @pytest.mark.parametrize(\"sort\", [None, False])\n def test_intersection(self, tz, sort):\n # GH 4690 (with tz)\n base = date_range(\"6/1/2000\", \"6/30/2000\", freq=\"D\", name=\"idx\")\n\n # if target has the same name, it is preserved\n rng2 = date_range(\"5/15/2000\", \"6/20/2000\", freq=\"D\", name=\"idx\")\n expected2 = date_range(\"6/1/2000\", \"6/20/2000\", freq=\"D\", name=\"idx\")\n\n # if target name is different, it will be reset\n rng3 = date_range(\"5/15/2000\", \"6/20/2000\", freq=\"D\", name=\"other\")\n expected3 = date_range(\"6/1/2000\", \"6/20/2000\", freq=\"D\", name=None)\n\n rng4 = date_range(\"7/1/2000\", \"7/31/2000\", freq=\"D\", name=\"idx\")\n expected4 = DatetimeIndex([], name=\"idx\")\n\n for (rng, expected) in [\n (rng2, expected2),\n (rng3, expected3),\n (rng4, expected4),\n ]:\n result = base.intersection(rng)\n tm.assert_index_equal(result, expected)\n assert result.name == expected.name\n assert result.freq == expected.freq\n assert result.tz == expected.tz\n\n # non-monotonic\n base = DatetimeIndex(\n [\"2011-01-05\", \"2011-01-04\", \"2011-01-02\", \"2011-01-03\"], tz=tz, name=\"idx\"\n )\n\n rng2 = DatetimeIndex(\n [\"2011-01-04\", \"2011-01-02\", \"2011-02-02\", \"2011-02-03\"], tz=tz, name=\"idx\"\n )\n expected2 = DatetimeIndex([\"2011-01-04\", \"2011-01-02\"], tz=tz, name=\"idx\")\n\n rng3 = DatetimeIndex(\n [\"2011-01-04\", \"2011-01-02\", \"2011-02-02\", \"2011-02-03\"],\n tz=tz,\n name=\"other\",\n )\n expected3 = DatetimeIndex([\"2011-01-04\", \"2011-01-02\"], tz=tz, name=None)\n\n # GH 7880\n rng4 = date_range(\"7/1/2000\", \"7/31/2000\", freq=\"D\", tz=tz, name=\"idx\")\n expected4 = DatetimeIndex([], tz=tz, name=\"idx\")\n\n for (rng, expected) in [\n (rng2, expected2),\n (rng3, expected3),\n (rng4, expected4),\n ]:\n result = base.intersection(rng, sort=sort)\n if sort is None:\n expected = expected.sort_values()\n tm.assert_index_equal(result, expected)\n assert result.name == expected.name\n assert result.freq is None\n assert result.tz == expected.tz\n\n def test_intersection_empty(self):\n # empty same freq GH2129\n rng = date_range(\"6/1/2000\", \"6/15/2000\", freq=\"T\")\n result = rng[0:0].intersection(rng)\n assert len(result) == 0\n\n result = rng.intersection(rng[0:0])\n assert len(result) == 0\n\n def test_intersection_bug_1708(self):\n from pandas import DateOffset\n\n index_1 = date_range(\"1/1/2012\", periods=4, freq=\"12H\")\n index_2 = index_1 + DateOffset(hours=1)\n\n result = index_1 & index_2\n assert len(result) == 0\n\n @pytest.mark.parametrize(\"tz\", tz)\n @pytest.mark.parametrize(\"sort\", [None, False])\n def test_difference(self, tz, sort):\n rng_dates = [\"1/2/2000\", \"1/3/2000\", \"1/1/2000\", \"1/4/2000\", \"1/5/2000\"]\n\n rng1 = pd.DatetimeIndex(rng_dates, tz=tz)\n other1 = pd.date_range(\"1/6/2000\", freq=\"D\", periods=5, tz=tz)\n expected1 = pd.DatetimeIndex(rng_dates, tz=tz)\n\n rng2 = pd.DatetimeIndex(rng_dates, tz=tz)\n other2 = pd.date_range(\"1/4/2000\", freq=\"D\", periods=5, tz=tz)\n expected2 = pd.DatetimeIndex(rng_dates[:3], tz=tz)\n\n rng3 = pd.DatetimeIndex(rng_dates, tz=tz)\n other3 = pd.DatetimeIndex([], tz=tz)\n expected3 = pd.DatetimeIndex(rng_dates, tz=tz)\n\n for rng, other, expected in [\n (rng1, other1, expected1),\n (rng2, other2, expected2),\n (rng3, other3, expected3),\n ]:\n result_diff = rng.difference(other, sort)\n if sort is None:\n expected = expected.sort_values()\n tm.assert_index_equal(result_diff, expected)\n\n @pytest.mark.parametrize(\"sort\", [None, False])\n def test_difference_freq(self, sort):\n # GH14323: difference of DatetimeIndex should not preserve frequency\n\n index = date_range(\"20160920\", \"20160925\", freq=\"D\")\n other = date_range(\"20160921\", \"20160924\", freq=\"D\")\n expected = DatetimeIndex([\"20160920\", \"20160925\"], freq=None)\n idx_diff = index.difference(other, sort)\n tm.assert_index_equal(idx_diff, expected)\n tm.assert_attr_equal(\"freq\", idx_diff, expected)\n\n other = date_range(\"20160922\", \"20160925\", freq=\"D\")\n idx_diff = index.difference(other, sort)\n expected = DatetimeIndex([\"20160920\", \"20160921\"], freq=None)\n tm.assert_index_equal(idx_diff, expected)\n tm.assert_attr_equal(\"freq\", idx_diff, expected)\n\n @pytest.mark.parametrize(\"sort\", [None, False])\n def test_datetimeindex_diff(self, sort):\n dti1 = date_range(freq=\"Q-JAN\", start=datetime(1997, 12, 31), periods=100)\n dti2 = date_range(freq=\"Q-JAN\", start=datetime(1997, 12, 31), periods=98)\n assert len(dti1.difference(dti2, sort)) == 2\n\n @pytest.mark.parametrize(\"sort\", [None, False])\n def test_datetimeindex_union_join_empty(self, sort):\n dti = date_range(start=\"1/1/2001\", end=\"2/1/2001\", freq=\"D\")\n empty = Index([])\n\n result = dti.union(empty, sort=sort)\n expected = dti.astype(\"O\")\n tm.assert_index_equal(result, expected)\n\n result = dti.join(empty)\n assert isinstance(result, DatetimeIndex)\n tm.assert_index_equal(result, dti)\n\n def test_join_nonunique(self):\n idx1 = to_datetime([\"2012-11-06 16:00:11.477563\", \"2012-11-06 16:00:11.477563\"])\n idx2 = to_datetime([\"2012-11-06 15:11:09.006507\", \"2012-11-06 15:11:09.006507\"])\n rs = idx1.join(idx2, how=\"outer\")\n assert rs.is_monotonic\n\n\nclass TestBusinessDatetimeIndex:\n def setup_method(self, method):\n self.rng = bdate_range(START, END)\n\n @pytest.mark.parametrize(\"sort\", [None, False])\n def test_union(self, sort):\n # overlapping\n left = self.rng[:10]\n right = self.rng[5:10]\n\n the_union = left.union(right, sort=sort)\n assert isinstance(the_union, DatetimeIndex)\n\n # non-overlapping, gap in middle\n left = self.rng[:5]\n right = self.rng[10:]\n\n the_union = left.union(right, sort=sort)\n assert isinstance(the_union, Index)\n\n # non-overlapping, no gap\n left = self.rng[:5]\n right = self.rng[5:10]\n\n the_union = left.union(right, sort=sort)\n assert isinstance(the_union, DatetimeIndex)\n\n # order does not matter\n if sort is None:\n tm.assert_index_equal(right.union(left, sort=sort), the_union)\n else:\n expected = pd.DatetimeIndex(list(right) + list(left))\n tm.assert_index_equal(right.union(left, sort=sort), expected)\n\n # overlapping, but different offset\n rng = date_range(START, END, freq=BMonthEnd())\n\n the_union = self.rng.union(rng, sort=sort)\n assert isinstance(the_union, DatetimeIndex)\n\n def test_outer_join(self):\n # should just behave as union\n\n # overlapping\n left = self.rng[:10]\n right = self.rng[5:10]\n\n the_join = left.join(right, how=\"outer\")\n assert isinstance(the_join, DatetimeIndex)\n\n # non-overlapping, gap in middle\n left = self.rng[:5]\n right = self.rng[10:]\n\n the_join = left.join(right, how=\"outer\")\n assert isinstance(the_join, DatetimeIndex)\n assert the_join.freq is None\n\n # non-overlapping, no gap\n left = self.rng[:5]\n right = self.rng[5:10]\n\n the_join = left.join(right, how=\"outer\")\n assert isinstance(the_join, DatetimeIndex)\n\n # overlapping, but different offset\n rng = date_range(START, END, freq=BMonthEnd())\n\n the_join = self.rng.join(rng, how=\"outer\")\n assert isinstance(the_join, DatetimeIndex)\n assert the_join.freq is None\n\n @pytest.mark.parametrize(\"sort\", [None, False])\n def test_union_not_cacheable(self, sort):\n rng = date_range(\"1/1/2000\", periods=50, freq=Minute())\n rng1 = rng[10:]\n rng2 = rng[:25]\n the_union = rng1.union(rng2, sort=sort)\n if sort is None:\n tm.assert_index_equal(the_union, rng)\n else:\n expected = pd.DatetimeIndex(list(rng[10:]) + list(rng[:10]))\n tm.assert_index_equal(the_union, expected)\n\n rng1 = rng[10:]\n rng2 = rng[15:35]\n the_union = rng1.union(rng2, sort=sort)\n expected = rng[10:]\n tm.assert_index_equal(the_union, expected)\n\n def test_intersection(self):\n rng = date_range(\"1/1/2000\", periods=50, freq=Minute())\n rng1 = rng[10:]\n rng2 = rng[:25]\n the_int = rng1.intersection(rng2)\n expected = rng[10:25]\n tm.assert_index_equal(the_int, expected)\n assert isinstance(the_int, DatetimeIndex)\n assert the_int.freq == rng.freq\n\n the_int = rng1.intersection(rng2.view(DatetimeIndex))\n tm.assert_index_equal(the_int, expected)\n\n # non-overlapping\n the_int = rng[:10].intersection(rng[10:])\n expected = DatetimeIndex([])\n tm.assert_index_equal(the_int, expected)\n\n def test_intersection_bug(self):\n # GH #771\n a = bdate_range(\"11/30/2011\", \"12/31/2011\")\n b = bdate_range(\"12/10/2011\", \"12/20/2011\")\n result = a.intersection(b)\n tm.assert_index_equal(result, b)\n\n @pytest.mark.parametrize(\"sort\", [None, False])\n def test_month_range_union_tz_pytz(self, sort):\n from pytz import timezone\n\n tz = timezone(\"US/Eastern\")\n\n early_start = datetime(2011, 1, 1)\n early_end = datetime(2011, 3, 1)\n\n late_start = datetime(2011, 3, 1)\n late_end = datetime(2011, 5, 1)\n\n early_dr = date_range(start=early_start, end=early_end, tz=tz, freq=MonthEnd())\n late_dr = date_range(start=late_start, end=late_end, tz=tz, freq=MonthEnd())\n\n early_dr.union(late_dr, sort=sort)\n\n @td.skip_if_windows_python_3\n @pytest.mark.parametrize(\"sort\", [None, False])\n def test_month_range_union_tz_dateutil(self, sort):\n from pandas._libs.tslibs.timezones import dateutil_gettz\n\n tz = dateutil_gettz(\"US/Eastern\")\n\n early_start = datetime(2011, 1, 1)\n early_end = datetime(2011, 3, 1)\n\n late_start = datetime(2011, 3, 1)\n late_end = datetime(2011, 5, 1)\n\n early_dr = date_range(start=early_start, end=early_end, tz=tz, freq=MonthEnd())\n late_dr = date_range(start=late_start, end=late_end, tz=tz, freq=MonthEnd())\n\n early_dr.union(late_dr, sort=sort)\n\n\nclass TestCustomDatetimeIndex:\n def setup_method(self, method):\n self.rng = bdate_range(START, END, freq=\"C\")\n\n @pytest.mark.parametrize(\"sort\", [None, False])\n def test_union(self, sort):\n # overlapping\n left = self.rng[:10]\n right = self.rng[5:10]\n\n the_union = left.union(right, sort=sort)\n assert isinstance(the_union, DatetimeIndex)\n\n # non-overlapping, gap in middle\n left = self.rng[:5]\n right = self.rng[10:]\n\n the_union = left.union(right, sort)\n assert isinstance(the_union, Index)\n\n # non-overlapping, no gap\n left = self.rng[:5]\n right = self.rng[5:10]\n\n the_union = left.union(right, sort=sort)\n assert isinstance(the_union, DatetimeIndex)\n\n # order does not matter\n if sort is None:\n tm.assert_index_equal(right.union(left, sort=sort), the_union)\n\n # overlapping, but different offset\n rng = date_range(START, END, freq=BMonthEnd())\n\n the_union = self.rng.union(rng, sort=sort)\n assert isinstance(the_union, DatetimeIndex)\n\n def test_outer_join(self):\n # should just behave as union\n\n # overlapping\n left = self.rng[:10]\n right = self.rng[5:10]\n\n the_join = left.join(right, how=\"outer\")\n assert isinstance(the_join, DatetimeIndex)\n\n # non-overlapping, gap in middle\n left = self.rng[:5]\n right = self.rng[10:]\n\n the_join = left.join(right, how=\"outer\")\n assert isinstance(the_join, DatetimeIndex)\n assert the_join.freq is None\n\n # non-overlapping, no gap\n left = self.rng[:5]\n right = self.rng[5:10]\n\n the_join = left.join(right, how=\"outer\")\n assert isinstance(the_join, DatetimeIndex)\n\n # overlapping, but different offset\n rng = date_range(START, END, freq=BMonthEnd())\n\n the_join = self.rng.join(rng, how=\"outer\")\n assert isinstance(the_join, DatetimeIndex)\n assert the_join.freq is None\n\n def test_intersection_bug(self):\n # GH #771\n a = bdate_range(\"11/30/2011\", \"12/31/2011\", freq=\"C\")\n b = bdate_range(\"12/10/2011\", \"12/20/2011\", freq=\"C\")\n result = a.intersection(b)\n tm.assert_index_equal(result, b)\n", "import numpy as np\nimport pytest\n\nfrom pandas import Categorical, DataFrame, Series\nimport pandas._testing as tm\n\n\nclass TestSeriesSortValues:\n def test_sort_values(self, datetime_series):\n\n # check indexes are reordered corresponding with the values\n ser = Series([3, 2, 4, 1], [\"A\", \"B\", \"C\", \"D\"])\n expected = Series([1, 2, 3, 4], [\"D\", \"B\", \"A\", \"C\"])\n result = ser.sort_values()\n tm.assert_series_equal(expected, result)\n\n ts = datetime_series.copy()\n ts[:5] = np.NaN\n vals = ts.values\n\n result = ts.sort_values()\n assert np.isnan(result[-5:]).all()\n tm.assert_numpy_array_equal(result[:-5].values, np.sort(vals[5:]))\n\n # na_position\n result = ts.sort_values(na_position=\"first\")\n assert np.isnan(result[:5]).all()\n tm.assert_numpy_array_equal(result[5:].values, np.sort(vals[5:]))\n\n # something object-type\n ser = Series([\"A\", \"B\"], [1, 2])\n # no failure\n ser.sort_values()\n\n # ascending=False\n ordered = ts.sort_values(ascending=False)\n expected = np.sort(ts.dropna().values)[::-1]\n tm.assert_almost_equal(expected, ordered.dropna().values)\n ordered = ts.sort_values(ascending=False, na_position=\"first\")\n tm.assert_almost_equal(expected, ordered.dropna().values)\n\n # ascending=[False] should behave the same as ascending=False\n ordered = ts.sort_values(ascending=[False])\n expected = ts.sort_values(ascending=False)\n tm.assert_series_equal(expected, ordered)\n ordered = ts.sort_values(ascending=[False], na_position=\"first\")\n expected = ts.sort_values(ascending=False, na_position=\"first\")\n tm.assert_series_equal(expected, ordered)\n\n msg = \"ascending must be boolean\"\n with pytest.raises(ValueError, match=msg):\n ts.sort_values(ascending=None)\n msg = r\"Length of ascending \\(0\\) must be 1 for Series\"\n with pytest.raises(ValueError, match=msg):\n ts.sort_values(ascending=[])\n msg = r\"Length of ascending \\(3\\) must be 1 for Series\"\n with pytest.raises(ValueError, match=msg):\n ts.sort_values(ascending=[1, 2, 3])\n msg = r\"Length of ascending \\(2\\) must be 1 for Series\"\n with pytest.raises(ValueError, match=msg):\n ts.sort_values(ascending=[False, False])\n msg = \"ascending must be boolean\"\n with pytest.raises(ValueError, match=msg):\n ts.sort_values(ascending=\"foobar\")\n\n # inplace=True\n ts = datetime_series.copy()\n ts.sort_values(ascending=False, inplace=True)\n tm.assert_series_equal(ts, datetime_series.sort_values(ascending=False))\n tm.assert_index_equal(\n ts.index, datetime_series.sort_values(ascending=False).index\n )\n\n # GH#5856/5853\n # Series.sort_values operating on a view\n df = DataFrame(np.random.randn(10, 4))\n s = df.iloc[:, 0]\n\n msg = (\n \"This Series is a view of some other array, to sort in-place\"\n \" you must create a copy\"\n )\n with pytest.raises(ValueError, match=msg):\n s.sort_values(inplace=True)\n\n def test_sort_values_categorical(self):\n\n c = Categorical([\"a\", \"b\", \"b\", \"a\"], ordered=False)\n cat = Series(c.copy())\n\n # sort in the categories order\n expected = Series(\n Categorical([\"a\", \"a\", \"b\", \"b\"], ordered=False), index=[0, 3, 1, 2]\n )\n result = cat.sort_values()\n tm.assert_series_equal(result, expected)\n\n cat = Series(Categorical([\"a\", \"c\", \"b\", \"d\"], ordered=True))\n res = cat.sort_values()\n exp = np.array([\"a\", \"b\", \"c\", \"d\"], dtype=np.object_)\n tm.assert_numpy_array_equal(res.__array__(), exp)\n\n cat = Series(\n Categorical(\n [\"a\", \"c\", \"b\", \"d\"], categories=[\"a\", \"b\", \"c\", \"d\"], ordered=True\n )\n )\n res = cat.sort_values()\n exp = np.array([\"a\", \"b\", \"c\", \"d\"], dtype=np.object_)\n tm.assert_numpy_array_equal(res.__array__(), exp)\n\n res = cat.sort_values(ascending=False)\n exp = np.array([\"d\", \"c\", \"b\", \"a\"], dtype=np.object_)\n tm.assert_numpy_array_equal(res.__array__(), exp)\n\n raw_cat1 = Categorical(\n [\"a\", \"b\", \"c\", \"d\"], categories=[\"a\", \"b\", \"c\", \"d\"], ordered=False\n )\n raw_cat2 = Categorical(\n [\"a\", \"b\", \"c\", \"d\"], categories=[\"d\", \"c\", \"b\", \"a\"], ordered=True\n )\n s = [\"a\", \"b\", \"c\", \"d\"]\n df = DataFrame(\n {\"unsort\": raw_cat1, \"sort\": raw_cat2, \"string\": s, \"values\": [1, 2, 3, 4]}\n )\n\n # Cats must be sorted in a dataframe\n res = df.sort_values(by=[\"string\"], ascending=False)\n exp = np.array([\"d\", \"c\", \"b\", \"a\"], dtype=np.object_)\n tm.assert_numpy_array_equal(res[\"sort\"].values.__array__(), exp)\n assert res[\"sort\"].dtype == \"category\"\n\n res = df.sort_values(by=[\"sort\"], ascending=False)\n exp = df.sort_values(by=[\"string\"], ascending=True)\n tm.assert_series_equal(res[\"values\"], exp[\"values\"])\n assert res[\"sort\"].dtype == \"category\"\n assert res[\"unsort\"].dtype == \"category\"\n\n # unordered cat, but we allow this\n df.sort_values(by=[\"unsort\"], ascending=False)\n\n # multi-columns sort\n # GH#7848\n df = DataFrame(\n {\"id\": [6, 5, 4, 3, 2, 1], \"raw_grade\": [\"a\", \"b\", \"b\", \"a\", \"a\", \"e\"]}\n )\n df[\"grade\"] = Categorical(df[\"raw_grade\"], ordered=True)\n df[\"grade\"] = df[\"grade\"].cat.set_categories([\"b\", \"e\", \"a\"])\n\n # sorts 'grade' according to the order of the categories\n result = df.sort_values(by=[\"grade\"])\n expected = df.iloc[[1, 2, 5, 0, 3, 4]]\n tm.assert_frame_equal(result, expected)\n\n # multi\n result = df.sort_values(by=[\"grade\", \"id\"])\n expected = df.iloc[[2, 1, 5, 4, 3, 0]]\n tm.assert_frame_equal(result, expected)\n\n @pytest.mark.parametrize(\n \"original_list, sorted_list, ignore_index, output_index\",\n [\n ([2, 3, 6, 1], [6, 3, 2, 1], True, [0, 1, 2, 3]),\n ([2, 3, 6, 1], [6, 3, 2, 1], False, [2, 1, 0, 3]),\n ],\n )\n def test_sort_values_ignore_index(\n self, original_list, sorted_list, ignore_index, output_index\n ):\n # GH 30114\n sr = Series(original_list)\n expected = Series(sorted_list, index=output_index)\n\n # Test when inplace is False\n sorted_sr = sr.sort_values(ascending=False, ignore_index=ignore_index)\n tm.assert_series_equal(sorted_sr, expected)\n\n tm.assert_series_equal(sr, Series(original_list))\n\n # Test when inplace is True\n copied_sr = sr.copy()\n copied_sr.sort_values(ascending=False, ignore_index=ignore_index, inplace=True)\n tm.assert_series_equal(copied_sr, expected)\n\n tm.assert_series_equal(sr, Series(original_list))\n" ]
[ [ "pandas._testing.equalContents", "pandas.to_datetime", "pandas.DateOffset", "pandas.bdate_range", "numpy.arange", "pandas.Index", "pandas.DatetimeIndex", "pandas.DataFrame", "pandas._libs.tslibs.timezones.dateutil_gettz", "pandas.tseries.offsets.BMonthEnd", "pandas._testing.assert_attr_equal", "pandas.tseries.offsets.Minute", "pandas.date_range", "pandas._testing.makeDateIndex", "pandas.tseries.offsets.MonthEnd", "pandas._testing.assert_index_equal" ], [ "pandas.Series", "numpy.isnan", "pandas.Categorical", "pandas.DataFrame", "numpy.sort", "pandas._testing.assert_frame_equal", "numpy.random.randn", "pandas._testing.assert_series_equal", "numpy.array" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
cicobalico/imgaug
[ "d2534903dea27f6e8836a2e627b3a0f075d959cf" ]
[ "imgaug/augmenters/color.py" ]
[ "\"\"\"\nAugmenters that apply color space oriented changes.\n\nDo not import directly from this file, as the categorization is not final.\nUse instead\n `from imgaug import augmenters as iaa`\nand then e.g. ::\n\n seq = iaa.Sequential([\n iaa.Grayscale((0.0, 1.0)),\n iaa.AddToHueAndSaturation((-10, 10))\n ])\n\nList of augmenters:\n * InColorspace (deprecated)\n * WithColorspace\n * AddToHueAndSaturation\n * ChangeColorspace\n * Grayscale\n\"\"\"\nfrom __future__ import print_function, division, absolute_import\nfrom .. import imgaug as ia\n# TODO replace these imports with iap.XYZ\nfrom ..parameters import StochasticParameter, Deterministic, Choice, Uniform\nimport numpy as np\nimport cv2\nimport six.moves as sm\nimport warnings\n\nfrom .meta import Augmenter, Sequential, WithChannels, handle_children_list\nfrom .arithmetic import Add\n\n# legacy support\ndef InColorspace(to_colorspace, from_colorspace=\"RGB\", children=None, name=None, deterministic=False, random_state=None):\n \"\"\"Deprecated. Use WithColorspace.\"\"\"\n warnings.warn('InColorspace is deprecated. Use WithColorspace.', DeprecationWarning)\n return WithColorspace(to_colorspace, from_colorspace, children, name, deterministic, random_state)\n\nclass WithColorspace(Augmenter):\n \"\"\"\n Apply child augmenters within a specific colorspace.\n\n This augumenter takes a source colorspace A and a target colorspace B\n as well as children C. It changes images from A to B, then applies the\n child augmenters C and finally changes the colorspace back from B to A.\n See also ChangeColorspace() for more.\n\n Parameters\n ----------\n to_colorspace : string\n See `ChangeColorspace.__init__()`\n\n from_colorspace : string, optional(default=\"RGB\")\n See `ChangeColorspace.__init__()`\n\n children : None or Augmenter or list of Augmenters, optional(default=None)\n See `ChangeColorspace.__init__()`\n\n name : string, optional(default=None)\n See `Augmenter.__init__()`\n\n deterministic : bool, optional(default=False)\n See `Augmenter.__init__()`\n\n random_state : int or np.random.RandomState or None, optional(default=None)\n See `Augmenter.__init__()`\n\n Examples\n --------\n >>> aug = iaa.WithColorspace(to_colorspace=\"HSV\", from_colorspace=\"RGB\",\n >>> children=iaa.WithChannels(0, iaa.Add(10)))\n\n This augmenter will add 10 to Hue value in HSV colorspace,\n then change the colorspace back to the original (RGB).\n\n \"\"\"\n\n def __init__(self, to_colorspace, from_colorspace=\"RGB\", children=None, name=None, deterministic=False, random_state=None):\n super(WithColorspace, self).__init__(name=name, deterministic=deterministic, random_state=random_state)\n\n self.to_colorspace = to_colorspace\n self.from_colorspace = from_colorspace\n self.children = handle_children_list(children, self.name, \"then\")\n\n def _augment_images(self, images, random_state, parents, hooks):\n result = images\n if hooks.is_propagating(images, augmenter=self, parents=parents, default=True):\n result = ChangeColorspace(\n to_colorspace=self.to_colorspace,\n from_colorspace=self.from_colorspace,\n ).augment_images(images=result)\n result = self.children.augment_images(\n images=result,\n parents=parents + [self],\n hooks=hooks,\n )\n result = ChangeColorspace(\n to_colorspace=self.from_colorspace,\n from_colorspace=self.to_colorspace,\n ).augment_images(images=result)\n return result\n\n def _augment_heatmaps(self, heatmaps, random_state, parents, hooks):\n result = heatmaps\n if hooks.is_propagating(heatmaps, augmenter=self, parents=parents, default=True):\n result = self.children.augment_heatmaps(\n result,\n parents=parents + [self],\n hooks=hooks,\n )\n return result\n\n def _augment_keypoints(self, keypoints_on_images, random_state, parents, hooks):\n result = keypoints_on_images\n if hooks.is_propagating(keypoints_on_images, augmenter=self, parents=parents, default=True):\n result = self.children.augment_keypoints(\n result,\n parents=parents + [self],\n hooks=hooks,\n )\n return result\n\n def _to_deterministic(self):\n aug = self.copy()\n aug.children = aug.children.to_deterministic()\n aug.deterministic = True\n aug.random_state = ia.new_random_state()\n return aug\n\n def get_parameters(self):\n return [self.channels]\n\n def get_children_lists(self):\n return [self.children]\n\n def __str__(self):\n return \"WithColorspace(from_colorspace=%s, to_colorspace=%s, name=%s, children=[%s], deterministic=%s)\" % (self.from_colorspace, self.to_colorspace, self.name, self.children, self.deterministic)\n\n# TODO removed deterministic and random_state here as parameters, because this\n# function creates multiple child augmenters. not sure if this is sensible\n# (give them all the same random state instead?)\ndef AddToHueAndSaturation(value=0, per_channel=False, from_colorspace=\"RGB\", channels=[0, 1], name=None): # pylint: disable=locally-disabled, dangerous-default-value, line-too-long\n \"\"\"\n Augmenter that transforms images into HSV space, selects the H and S\n channels and then adds a given range of values to these.\n\n Parameters\n ----------\n value : int or iterable of two ints or StochasticParameter, optional(default=0)\n See `Add.__init__()`\n\n per_channel : bool or float, optional(default=False)\n See `Add.__init__()`\n\n from_colorspace : string, optional(default=\"RGB\")\n See `ChangeColorspace.__init__()`\n\n channels : integer or list of integers or None, optional(default=[0, 1])\n See `WithChannels.__init__()`\n\n name : string, optional(default=None)\n See `Augmenter.__init__()`\n\n Examples\n --------\n >> aug = AddToHueAndSaturation((-20, 20), per_channel=True)\n\n Adds random values between -20 and 20 to the hue and saturation\n (independently per channel and the same value for all pixels within\n that channel).\n\n \"\"\"\n if name is None:\n name = \"Unnamed%s\" % (ia.caller_name(),)\n\n return WithColorspace(\n to_colorspace=\"HSV\",\n from_colorspace=from_colorspace,\n children=WithChannels(\n channels=channels,\n children=Add(value=value, per_channel=per_channel)\n ),\n name=name\n )\n\n# TODO tests\n# Note: Not clear whether this class will be kept (for anything aside from grayscale)\n# other colorspaces dont really make sense and they also might not work correctly\n# due to having no clearly limited range (like 0-255 or 0-1)\n# TODO rename to ChangeColorspace3D and then introduce ChangeColorspace, which\n# does not enforce 3d images?\nclass ChangeColorspace(Augmenter):\n \"\"\"\n Augmenter to change the colorspace of images.\n\n NOTE: This augmenter is not tested. Some colorspaces might work, others\n might not.\n\n NOTE: This augmenter tries to project the colorspace value range on 0-255.\n It outputs dtype=uint8 images.\n\n Parameters\n ----------\n to_colorspace : string or iterable or StochasticParameter\n The target colorspace.\n Allowed are: RGB, BGR, GRAY, CIE, YCrCb, HSV, HLS, Lab, Luv.\n * If a string, it must be among the allowed colorspaces.\n * If an iterable, it is expected to be a list of strings, each one\n being an allowed colorspace. A random element from the list\n will be chosen per image.\n * If a StochasticParameter, it is expected to return string. A new\n sample will be drawn per image.\n\n from_colorspace : string, optional(default=\"RGB\")\n The source colorspace (of the input images).\n Allowed are: RGB, BGR, GRAY, CIE, YCrCb, HSV, HLS, Lab, Luv.\n\n alpha : int or float or tuple of two ints/floats or StochasticParameter, optional(default=1.0)\n The alpha value of the new colorspace when overlayed over the\n old one. A value close to 1.0 means that mostly the new\n colorspace is visible. A value close to 0.0 means, that mostly the\n old image is visible. Use a tuple (a, b) to use a random value\n `x` with `a <= x <= b` as the alpha value per image.\n\n name : string, optional(default=None)\n See `Augmenter.__init__()`\n\n deterministic : bool, optional(default=False)\n See `Augmenter.__init__()`\n\n random_state : int or np.random.RandomState or None, optional(default=None)\n See `Augmenter.__init__()`\n\n \"\"\"\n\n RGB = \"RGB\"\n BGR = \"BGR\"\n GRAY = \"GRAY\"\n CIE = \"CIE\"\n YCrCb = \"YCrCb\"\n HSV = \"HSV\"\n HLS = \"HLS\"\n Lab = \"Lab\"\n Luv = \"Luv\"\n COLORSPACES = set([\n RGB,\n BGR,\n GRAY,\n CIE,\n YCrCb,\n HSV,\n HLS,\n Lab,\n Luv\n ])\n CV_VARS = {\n # RGB\n #\"RGB2RGB\": cv2.COLOR_RGB2RGB,\n \"RGB2BGR\": cv2.COLOR_RGB2BGR,\n \"RGB2GRAY\": cv2.COLOR_RGB2GRAY,\n \"RGB2CIE\": cv2.COLOR_RGB2XYZ,\n \"RGB2YCrCb\": cv2.COLOR_RGB2YCR_CB,\n \"RGB2HSV\": cv2.COLOR_RGB2HSV,\n \"RGB2HLS\": cv2.COLOR_RGB2HLS,\n \"RGB2LAB\": cv2.COLOR_RGB2LAB,\n \"RGB2LUV\": cv2.COLOR_RGB2LUV,\n # BGR\n \"BGR2RGB\": cv2.COLOR_BGR2RGB,\n #\"BGR2BGR\": cv2.COLOR_BGR2BGR,\n \"BGR2GRAY\": cv2.COLOR_BGR2GRAY,\n \"BGR2CIE\": cv2.COLOR_BGR2XYZ,\n \"BGR2YCrCb\": cv2.COLOR_BGR2YCR_CB,\n \"BGR2HSV\": cv2.COLOR_BGR2HSV,\n \"BGR2HLS\": cv2.COLOR_BGR2HLS,\n \"BGR2LAB\": cv2.COLOR_BGR2LAB,\n \"BGR2LUV\": cv2.COLOR_BGR2LUV,\n # HSV\n \"HSV2RGB\": cv2.COLOR_HSV2RGB,\n \"HSV2BGR\": cv2.COLOR_HSV2BGR,\n }\n\n def __init__(self, to_colorspace, from_colorspace=\"RGB\", alpha=1.0, name=None, deterministic=False, random_state=None):\n super(ChangeColorspace, self).__init__(name=name, deterministic=deterministic, random_state=random_state)\n\n if ia.is_single_number(alpha):\n self.alpha = Deterministic(alpha)\n elif ia.is_iterable(alpha):\n ia.do_assert(len(alpha) == 2, \"Expected tuple/list with 2 entries, got %d entries.\" % (len(alpha),))\n self.alpha = Uniform(alpha[0], alpha[1])\n elif isinstance(alpha, StochasticParameter):\n self.alpha = alpha\n else:\n raise Exception(\"Expected alpha to be int or float or tuple/list of ints/floats or StochasticParameter, got %s.\" % (type(alpha),))\n\n if ia.is_string(to_colorspace):\n ia.do_assert(to_colorspace in ChangeColorspace.COLORSPACES)\n self.to_colorspace = Deterministic(to_colorspace)\n elif ia.is_iterable(to_colorspace):\n ia.do_assert(all([ia.is_string(colorspace) for colorspace in to_colorspace]))\n ia.do_assert(all([(colorspace in ChangeColorspace.COLORSPACES) for colorspace in to_colorspace]))\n self.to_colorspace = Choice(to_colorspace)\n elif isinstance(to_colorspace, StochasticParameter):\n self.to_colorspace = to_colorspace\n else:\n raise Exception(\"Expected to_colorspace to be string, list of strings or StochasticParameter, got %s.\" % (type(to_colorspace),))\n\n self.from_colorspace = from_colorspace\n ia.do_assert(self.from_colorspace in ChangeColorspace.COLORSPACES)\n ia.do_assert(from_colorspace != ChangeColorspace.GRAY)\n\n self.eps = 0.001 # epsilon value to check if alpha is close to 1.0 or 0.0\n\n def _augment_images(self, images, random_state, parents, hooks):\n result = images\n nb_images = len(images)\n alphas = self.alpha.draw_samples((nb_images,), random_state=ia.copy_random_state(random_state))\n to_colorspaces = self.to_colorspace.draw_samples((nb_images,), random_state=ia.copy_random_state(random_state))\n for i in sm.xrange(nb_images):\n alpha = alphas[i]\n to_colorspace = to_colorspaces[i]\n image = images[i]\n\n ia.do_assert(0.0 <= alpha <= 1.0)\n ia.do_assert(to_colorspace in ChangeColorspace.COLORSPACES)\n\n if alpha == 0 or self.from_colorspace == to_colorspace:\n pass # no change necessary\n else:\n # some colorspaces here should use image/255.0 according to the docs,\n # but at least for conversion to grayscale that results in errors,\n # ie uint8 is expected\n\n if self.from_colorspace in [ChangeColorspace.RGB, ChangeColorspace.BGR]:\n from_to_var_name = \"%s2%s\" % (self.from_colorspace, to_colorspace)\n from_to_var = ChangeColorspace.CV_VARS[from_to_var_name]\n print(\"fromtovar {}\".format(from_to_var))\n print(\"image shape {}\".format(image.shape))\n img_to_cs = cv2.cvtColor(image, from_to_var)\n else:\n # convert to RGB\n from_to_var_name = \"%s2%s\" % (self.from_colorspace, ChangeColorspace.RGB)\n from_to_var = ChangeColorspace.CV_VARS[from_to_var_name]\n img_rgb = cv2.cvtColor(image, from_to_var)\n\n if to_colorspace == ChangeColorspace.RGB:\n img_to_cs = img_rgb\n else:\n # convert from RGB to desired target colorspace\n from_to_var_name = \"%s2%s\" % (ChangeColorspace.RGB, to_colorspace)\n from_to_var = ChangeColorspace.CV_VARS[from_to_var_name]\n img_to_cs = cv2.cvtColor(img_rgb, from_to_var)\n\n # this will break colorspaces that have values outside 0-255 or 0.0-1.0\n if ia.is_integer_array(img_to_cs):\n img_to_cs = np.clip(img_to_cs, 0, 255).astype(np.uint8)\n else:\n img_to_cs = np.clip(img_to_cs * 255, 0, 255).astype(np.uint8)\n\n # for grayscale: covnert from (H, W) to (H, W, 3)\n if len(img_to_cs.shape) == 2:\n img_to_cs = img_to_cs[:, :, np.newaxis]\n img_to_cs = np.tile(img_to_cs, (1, 1, 3))\n\n if alpha >= (1 - self.eps):\n result[i] = img_to_cs\n elif alpha <= self.eps:\n result[i] = image\n else:\n result[i] = (alpha * img_to_cs + (1 - alpha) * image).astype(np.uint8)\n\n return images\n\n def _augment_heatmaps(self, heatmaps, random_state, parents, hooks):\n return heatmaps\n\n def _augment_keypoints(self, keypoints_on_images, random_state, parents, hooks):\n return keypoints_on_images\n\n def get_parameters(self):\n return [self.to_colorspace, self.alpha]\n\n# TODO tests\n# TODO rename to Grayscale3D and add Grayscale that keeps the image at 1D\ndef Grayscale(alpha=0, from_colorspace=\"RGB\", name=None, deterministic=False, random_state=None):\n \"\"\"\n Augmenter to convert images to their grayscale versions.\n\n NOTE: Number of output channels is still 3, i.e. this augmenter just\n \"removes\" color.\n\n Parameters\n ----------\n alpha : int or float or tuple of two ints/floats or StochasticParameter, optional(default=0)\n The alpha value of the grayscale image when overlayed over the\n old image. A value close to 1.0 means, that mostly the new grayscale\n image is visible. A value close to 0.0 means, that mostly the\n old image is visible. Use a tuple (a, b) to sample per image a\n random value x with a <= x <= b as the alpha value.\n\n from_colorspace : string, optional(default=\"RGB\")\n The source colorspace (of the input images).\n Allowed are: RGB, BGR, GRAY, CIE, YCrCb, HSV, HLS, Lab, Luv.\n Only RGB is decently tested.\n\n name : string, optional(default=None)\n See `Augmenter.__init__()`\n\n deterministic : bool, optional(default=False)\n See `Augmenter.__init__()`\n\n random_state : int or np.random.RandomState or None, optional(default=None)\n See `Augmenter.__init__()`\n\n Examples\n --------\n >>> aug = iaa.Grayscale(alpha=1.0)\n\n creates an augmenter that turns images to their grayscale versions.\n\n >>> aug = iaa.Grayscale(alpha=(0.0, 1.0))\n\n creates an augmenter that turns images to their grayscale versions with\n an alpha value in the range 0 <= alpha <= 1. An alpha value of 0.5 would\n mean, that the output image is 50 percent of the input image and 50\n percent of the grayscale image (i.e. 50 percent of color removed).\n\n \"\"\"\n if name is None:\n name = \"Unnamed%s\" % (ia.caller_name(),)\n\n return ChangeColorspace(to_colorspace=ChangeColorspace.GRAY, alpha=alpha, from_colorspace=from_colorspace, name=name, deterministic=deterministic, random_state=random_state)\n" ]
[ [ "numpy.tile", "numpy.clip" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
OEP/volpy
[ "f49cae8b2e14b664dea26ccbcbdcadac31d80d5b" ]
[ "tests/test_geometry.py" ]
[ "import numpy.testing as npt\n\nimport volpy\n\nimport unittest\n\n\nclass BBoxTestCase(unittest.TestCase):\n\n def setUp(self):\n self.bbox = volpy.BBox([[1, 1, 1, 1],\n [5, 5, 5, 1]])\n\n def test_transform1(self):\n result = self.bbox.transform().dot(self.bbox.corners[0])\n expected = [-0.5, -0.5, -0.5, 1]\n npt.assert_almost_equal(expected, result)\n\n def test_transform2(self):\n result = self.bbox.transform().dot(self.bbox.corners[1])\n expected = [0.5, 0.5, 0.5, 1]\n npt.assert_almost_equal(expected, result)\n\n def test_transform3(self):\n result = self.bbox.transform().dot((self.bbox.corners[0] +\n self.bbox.corners[1]) / 2)\n expected = [0, 0, 0, 1]\n npt.assert_almost_equal(expected, result)\n\n def test_inverse_transform1(self):\n result = self.bbox.inverse_transform().dot([-0.5, -0.5, -0.5, 1])\n expected = self.bbox.corners[0]\n npt.assert_almost_equal(expected, result)\n\n def test_inverse_transform2(self):\n result = self.bbox.inverse_transform().dot([0.5, 0.5, 0.5, 1])\n expected = self.bbox.corners[1]\n npt.assert_almost_equal(expected, result)\n\n def test_inverse_transform3(self):\n result = self.bbox.inverse_transform().dot([0, 0, 0, 1])\n expected = (self.bbox.corners[0] + self.bbox.corners[1]) / 2\n npt.assert_almost_equal(expected, result)\n" ]
[ [ "numpy.testing.assert_almost_equal" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
WangFeng18/InvariancePropagation
[ "cad924ee2f7f311a805f8a4a9c3e8041e75ba002" ]
[ "downstream/linear_classification/eval_linear.py" ]
[ "\"\"\"\ncopied and modified from https://github.com/HobbitLong/CMC\n\n\"\"\"\nfrom __future__ import print_function\n\nimport os\nimport sys\nimport time\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nimport torch.backends.cudnn as cudnn\nimport torch.nn.functional as F\nimport argparse\nimport torch.multiprocessing as mp\nimport torch.distributed as dist\nimport numpy as np\nfrom tqdm import tqdm\nfrom utils import getLogger, colorful\nimport logging\nfrom models.shufflenetv2 import shufflenet_v2_x1_0\nimport tensorboard_logger as tb_logger\n\nfrom torchvision import transforms, datasets\n\nfrom models.preact_resnet import PreActResNet18, PreActResNet50\nfrom models.resnet import resnet50, resnet18\nfrom models.resnet_cifar import ResNet18 as resnet18_cifar\nfrom models.resnet_cifar import ResNet50 as resnet50_cifar\nfrom models.alexnet import AlexNet, AlexNet_cifar\nfrom models.LinearModel import LinearClassifierResNet, LinearClassifierAlexNet\nfrom PIL import ImageFile\nimport datasets.cifar as cifar\nimport datasets.wm811.loaders as wm811\nimport datasets.svhn as svhn\nImageFile.LOAD_TRUNCATED_IMAGES = True\nfrom datasets.ImageList import ImageList\nfrom metrics import MultiF1Score\n\ndef adjust_learning_rate(epoch, opt, optimizer):\n\t\"\"\"Sets the learning rate to the initial LR decayed by 0.2 every steep step\"\"\"\n\tsteps = np.sum(epoch > np.asarray(opt.lr_decay_epochs))\n\tif steps > 0:\n\t\tnew_lr = opt.learning_rate * (opt.lr_decay_rate ** steps)\n\t\tfor param_group in optimizer.param_groups:\n\t\t\tparam_group['lr'] = new_lr\n\t\t\tprint(new_lr)\n\n\nclass AverageMeter(object):\n\t\"\"\"Computes and stores the average and current value\"\"\"\n\tdef __init__(self):\n\t\tself.reset()\n\n\tdef reset(self):\n\t\tself.val = 0\n\t\tself.avg = 0\n\t\tself.sum = 0\n\t\tself.count = 0\n\n\tdef update(self, val, n=1):\n\t\tself.val = val\n\t\tself.sum += val * n\n\t\tself.count += n\n\t\tself.avg = self.sum / self.count\n\n\ndef parse_option():\n\tparser = argparse.ArgumentParser('argument for training')\n\n\tparser.add_argument('--save_freq', type=int, default=5)\n\tparser.add_argument('--batch_size', type=int, default=256)\n\tparser.add_argument('--n_workers', type=int, default=32)\n\tparser.add_argument('--epochs', type=int, default=100)\n\n\t# optimization\n\tparser.add_argument('--learning_rate', type=float, default=30)\n\tparser.add_argument('--lr_decay_epochs', type=str, default='40,60,80')\n\tparser.add_argument('--lr_decay_rate', type=float, default=0.2)\n\tparser.add_argument('--momentum', type=float, default=0.9)\n\tparser.add_argument('--weight_decay', type=float, default=0)\n\tparser.add_argument('--beta1', type=float, default=0.5, help='beta1 for Adam')\n\tparser.add_argument('--beta2', type=float, default=0.999, help='beta2 for Adam')\n\n\t# model definition\n\tparser.add_argument('--data_folder', type=str, default='/home/user/ILSVRC2012/')\n\tparser.add_argument('--model', type=str, default='resnet50')\n\tparser.add_argument('--save_folder', default='', type=str)\n\tparser.add_argument('--model_path', type=str, default='')\n\tparser.add_argument('--layer', type=int, default=6, help='which layer to evaluate')\n\n\t# crop\n\tparser.add_argument('--crop', type=float, default=0.08, help='minimum crop')\n\tparser.add_argument('--dataset', type=str, default='imagenet')\n\tparser.add_argument('--resume', default='', type=str, metavar='PATH')\n\tparser.add_argument('--aug', type=str, default='CJ', choices=['NULL', 'CJ'])\n\tparser.add_argument('--bn', action='store_true', help='use parameter-free BN')\n\tparser.add_argument('--moco', action='store_true', help='if using moco models')\n\tparser.add_argument('--adam', action='store_true', help='use adam optimizer')\n\tparser.add_argument('--gpu', default=None, type=int, help='GPU id to use.')\n\topt = parser.parse_args()\n\n\topt.tb_folder = os.path.join(opt.save_folder, 'runs')\n\tif not os.path.exists(opt.save_folder):\n\t\tos.makedirs(opt.save_folder)\n\tif not os.path.exists(opt.tb_folder):\n\t\tos.makedirs(opt.tb_folder)\n\tif not os.path.exists(os.path.join(opt.save_folder, 'logs')):\n\t\tos.makedirs(os.path.join(opt.save_folder, 'logs'))\n\tif opt.dataset == 'imagenet':\n\t\tif 'alexnet' not in opt.model:\n\t\t\topt.crop = 0.08\n\n\titerations = opt.lr_decay_epochs.split(',')\n\topt.lr_decay_epochs = list([])\n\tfor it in iterations:\n\t\topt.lr_decay_epochs.append(int(it))\n\n\topt.model_name = opt.model_path.split('/')[-2]\n\topt.model_name = '{}_bsz_{}_lr_{}_decay_{}_crop_{}'.format(opt.model_name, opt.batch_size, opt.learning_rate, opt.weight_decay, opt.crop)\n\topt.model_name = '{}_aug_{}'.format(opt.model_name, opt.aug)\n\tif opt.bn:\n\t\topt.model_name = '{}_useBN'.format(opt.model_name)\n\tif opt.adam:\n\t\topt.model_name = '{}_useAdam'.format(opt.model_name)\n\n\tif opt.dataset == 'imagenet100':\n\t\topt.n_label = 100\n\tif opt.dataset == 'places':\n\t\topt.n_label = 205\n\tif opt.dataset == 'imagenet':\n\t\topt.n_label = 1000\n\tif opt.dataset == 'cifar10':\n\t\topt.n_label = 10\n\tif opt.dataset == 'cifar100':\n\t\topt.n_label = 100\n\tif opt.dataset == 'svhn':\n\t\topt.n_label = 10\n\tif opt.dataset == 'wm811':\n\t\topt.n_label = 10\n\n\treturn opt\n\n\ndef main():\n\n\tglobal best_acc1\n\tbest_acc1 = 0\n\n\targs = parse_option()\n\n\tif args.gpu is not None:\n\t\tprint(\"Use GPU: {} for training\".format(args.gpu))\n\n\t# set the data loader\n\ttrain_folder = os.path.join(args.data_folder, 'train')\n\tval_folder = os.path.join(args.data_folder, 'val')\n\n\n\tlogger = getLogger(args.save_folder)\n\tif args.dataset.startswith('imagenet') or args.dataset.startswith('places'):\n\t\timage_size = 224\n\t\tcrop_padding = 32\n\t\tmean = [0.485, 0.456, 0.406]\n\t\tstd = [0.229, 0.224, 0.225]\n\t\tnormalize = transforms.Normalize(mean=mean, std=std)\n\t\tif args.aug == 'NULL':\n\t\t\ttrain_transform = transforms.Compose([\n\t\t\t\ttransforms.RandomResizedCrop(image_size, scale=(args.crop, 1.)),\n\t\t\t\ttransforms.RandomHorizontalFlip(),\n\t\t\t\ttransforms.ToTensor(),\n\t\t\t\tnormalize,\n\t\t\t])\n\t\telif args.aug == 'CJ':\n\t\t\ttrain_transform = transforms.Compose([\n\t\t\t\ttransforms.RandomResizedCrop(image_size, scale=(args.crop, 1.)),\n\t\t\t\ttransforms.RandomGrayscale(p=0.2),\n\t\t\t\ttransforms.ColorJitter(0.4, 0.4, 0.4, 0.4),\n\t\t\t\ttransforms.RandomHorizontalFlip(),\n\t\t\t\ttransforms.ToTensor(),\n\t\t\t\tnormalize,\n\t\t\t])\n\t\telse:\n\t\t\traise NotImplemented('augmentation not supported: {}'.format(args.aug))\n\t\t\n\t\tval_transform = transforms.Compose([\n\t\t\t\ttransforms.Resize(image_size + crop_padding),\n\t\t\t\ttransforms.CenterCrop(image_size),\n\t\t\t\ttransforms.ToTensor(),\n\t\t\t\tnormalize,\n\t\t\t])\n\t\tif args.dataset.startswith('imagenet'):\n\t\t\ttrain_dataset = datasets.ImageFolder(train_folder, train_transform)\n\t\t\tval_dataset = datasets.ImageFolder(\n\t\t\t\tval_folder,\n\t\t\t\tval_transform,\n\t\t\t)\n\n\t\tif args.dataset.startswith('places'):\n\t\t\ttrain_dataset = ImageList('/data/trainvalsplit_places205/train_places205.csv', '/data/data/vision/torralba/deeplearning/images256', transform=train_transform, symbol_split=' ')\n\t\t\tval_dataset = ImageList('/data/trainvalsplit_places205/val_places205.csv', '/data/data/vision/torralba/deeplearning/images256', transform=val_transform, symbol_split=' ')\n\n\t\tprint(len(train_dataset))\n\t\ttrain_sampler = None\n\n\t\ttrain_loader = torch.utils.data.DataLoader( train_dataset, batch_size=args.batch_size, shuffle=(train_sampler is None), num_workers=args.n_workers, pin_memory=False, sampler=train_sampler)\n\n\t\tval_loader = torch.utils.data.DataLoader( val_dataset, batch_size=args.batch_size, shuffle=False, num_workers=args.n_workers, pin_memory=False)\n\telif args.dataset.startswith('cifar'):\n\t\ttrain_loader, val_loader = cifar.get_linear_dataloader(args)\n\telif args.dataset.startswith('svhn'):\n\t\ttrain_loader, val_loader = svhn.get_linear_dataloader(args)\n\telif args.dataset == 'wm811':\n\t\ttrain_loader, val_loader = wm811.get_linear_dataloader(args)\n\n\t# create model and optimizer\n\tif args.model == 'alexnet':\n\t\tif args.layer == 6:\n\t\t\targs.layer = 5\n\t\tmodel = AlexNet(128)\n\t\tmodel = nn.DataParallel(model)\n\t\tclassifier = LinearClassifierAlexNet(args.layer, args.n_label, 'avg')\n\telif args.model == 'alexnet_cifar':\n\t\tif args.layer == 6:\n\t\t\targs.layer = 5\n\t\tmodel = AlexNet_cifar(128)\n\t\tmodel = nn.DataParallel(model)\n\t\tclassifier = LinearClassifierAlexNet(args.layer, args.n_label, 'avg', cifar=True)\n\telif args.model == 'resnet50':\n\t\tmodel = resnet50(non_linear_head=False)\n\t\tmodel = nn.DataParallel(model)\n\t\tclassifier = LinearClassifierResNet(args.layer, args.n_label, 'avg', 1)\n\telif args.model == 'resnet18':\n\t\tmodel = resnet18()\n\t\tmodel = nn.DataParallel(model)\n\t\tclassifier = LinearClassifierResNet(args.layer, args.n_label, 'avg', 1, bottleneck=False)\n\telif args.model == 'resnet18_cifar':\n\t\tmodel = resnet18_cifar(256, non_linear_head=True, mlpbn=True)\n\t\tmodel = nn.DataParallel(model)\n\t\tclassifier = LinearClassifierResNet(args.layer, args.n_label, 'avg', 1, bottleneck=False)\n\telif args.model == 'resnet18_wm811':\n\t\tmodel = resnet18_cifar(128, non_linear_head=True)\n\t\tmodel = nn.DataParallel(model)\n\t\tclassifier = LinearClassifierResNet(args.layer, args.n_label, 'avg', 1, bottleneck=False)\n\telif args.model == 'resnet50_cifar':\n\t\tmodel = resnet50_cifar()\n\t\tmodel = nn.DataParallel(model)\n\t\tclassifier = LinearClassifierResNet(args.layer, args.n_label, 'avg', 1)\n\telif args.model == 'resnet50x2':\n\t\tmodel = InsResNet50(width=2)\n\t\tclassifier = LinearClassifierResNet(args.layer, args.n_label, 'avg', 2)\n\telif args.model == 'resnet50x4':\n\t\tmodel = InsResNet50(width=4)\n\t\tclassifier = LinearClassifierResNet(args.layer, args.n_label, 'avg', 4)\n\telif args.model == 'shufflenet':\n\t\tmodel = shufflenet_v2_x1_0(num_classes=128, non_linear_head=False)\n\t\tmodel = nn.DataParallel(model)\n\t\tclassifier = LinearClassifierResNet(args.layer, args.n_label, 'avg', 0.5)\n\telse:\n\t\traise NotImplementedError('model not supported {}'.format(args.model))\n\n\tprint('==> loading pre-trained model')\n\tckpt = torch.load(args.model_path)\n\tif not args.moco:\n\t\tmodel.load_state_dict(ckpt['state_dict'])\n\telse:\n\t\ttry:\n\t\t\tstate_dict = ckpt['state_dict']\n\t\t\tfor k in list(state_dict.keys()):\n\t\t\t\t# retain only encoder_q up to before the embedding layer\n\t\t\t\tif k.startswith('module.encoder_q') and not k.startswith('module.encoder_q.fc'):\n\t\t\t\t\t# remove prefix\n\t\t\t\t\tstate_dict['module.'+k[len(\"module.encoder_q.\"):]] = state_dict[k]\n\t\t\t\t# delete renamed or unused k\n\t\t\t\tdel state_dict[k]\n\t\t\tmodel.load_state_dict(state_dict)\n\t\texcept:\n\t\t\tpass\n\tprint(\"==> loaded checkpoint '{}' (epoch {})\".format(args.model_path, ckpt['epoch']))\n\tprint('==> done')\n\n\tmodel = model.cuda()\n\tclassifier = classifier.cuda()\n\n\tcriterion = torch.nn.CrossEntropyLoss().cuda(args.gpu)\n\n\tif not args.adam:\n\t\toptimizer = torch.optim.SGD(classifier.parameters(),\n\t\t\t\t\t\t\t\t\tlr=args.learning_rate,\n\t\t\t\t\t\t\t\t\tmomentum=args.momentum,\n\t\t\t\t\t\t\t\t\tweight_decay=args.weight_decay)\n\telse:\n\t\toptimizer = torch.optim.Adam(classifier.parameters(),\n\t\t\t\t\t\t\t\t\t lr=args.learning_rate,\n\t\t\t\t\t\t\t\t\t betas=(args.beta1, args.beta2),\n\t\t\t\t\t\t\t\t\t weight_decay=args.weight_decay,\n\t\t\t\t\t\t\t\t\t eps=1e-8)\n\n\tmodel.eval()\n\tcudnn.benchmark = True\n\n\t# optionally resume from a checkpoint\n\targs.start_epoch = 1\n\tif args.resume:\n\t\tif os.path.isfile(args.resume):\n\t\t\tprint(\"=> loading checkpoint '{}'\".format(args.resume))\n\t\t\tcheckpoint = torch.load(args.resume, map_location='cpu')\n\t\t\t# checkpoint = torch.load(args.resume)\n\t\t\targs.start_epoch = checkpoint['epoch'] + 1\n\t\t\tclassifier.load_state_dict(checkpoint['classifier'])\n\t\t\toptimizer.load_state_dict(checkpoint['optimizer'])\n\t\t\tbest_acc1 = checkpoint['best_acc1']\n\t\t\tprint(best_acc1.item())\n\t\t\tbest_acc1 = best_acc1.cuda()\n\t\t\tprint(\"=> loaded checkpoint '{}' (epoch {})\"\n\t\t\t\t .format(args.resume, checkpoint['epoch']))\n\t\t\tif 'opt' in checkpoint.keys():\n\t\t\t\t# resume optimization hyper-parameters\n\t\t\t\tprint('=> resume hyper parameters')\n\t\t\t\tif 'bn' in vars(checkpoint['opt']):\n\t\t\t\t\tprint('using bn: ', checkpoint['opt'].bn)\n\t\t\t\tif 'adam' in vars(checkpoint['opt']):\n\t\t\t\t\tprint('using adam: ', checkpoint['opt'].adam)\n\t\t\t\t#args.learning_rate = checkpoint['opt'].learning_rate\n\t\t\t\t# args.lr_decay_epochs = checkpoint['opt'].lr_decay_epochs\n\t\t\t\targs.lr_decay_rate = checkpoint['opt'].lr_decay_rate\n\t\t\t\targs.momentum = checkpoint['opt'].momentum\n\t\t\t\targs.weight_decay = checkpoint['opt'].weight_decay\n\t\t\t\targs.beta1 = checkpoint['opt'].beta1\n\t\t\t\targs.beta2 = checkpoint['opt'].beta2\n\t\t\tdel checkpoint\n\t\t\ttorch.cuda.empty_cache()\n\t\telse:\n\t\t\tprint(\"=> no checkpoint found at '{}'\".format(args.resume))\n\n\t# tensorboard\n\ttblogger = tb_logger.Logger(logdir=args.tb_folder, flush_secs=2)\n\n\t# routine\n\tbest_acc = 0.0\n\tfor epoch in range(args.start_epoch, args.epochs + 1):\n\n\t\tadjust_learning_rate(epoch, args, optimizer)\n\t\tprint(\"==> training...\")\n\n\t\ttime1 = time.time()\n\t\ttrain_acc, train_acc5, train_loss = train(epoch, train_loader, model, classifier, criterion, optimizer, args)\n\t\ttime2 = time.time()\n\t\tlogging.info('train epoch {}, total time {:.2f}'.format(epoch, time2 - time1))\n\n\t\tlogging.info('Epoch: {}, lr:{} , train_loss: {:.4f}, train_acc: {:.4f}/{:.4f}'.format(epoch, optimizer.param_groups[0]['lr'], train_loss, train_acc, train_acc5))\n\n\t\ttblogger.log_value('train_acc', train_acc, epoch)\n\t\ttblogger.log_value('train_acc5', train_acc5, epoch)\n\t\ttblogger.log_value('train_loss', train_loss, epoch)\n\t\ttblogger.log_value('learning_rate', optimizer.param_groups[0]['lr'], epoch)\n\n\t\ttest_acc, test_acc5, test_loss, f1score = validate(val_loader, model, classifier, criterion, args)\n\n\t\tif test_acc >= best_acc:\n\t\t\tbest_acc = test_acc\n\n\t\tlogging.info(colorful('Epoch: {}, val_loss: {:.4f}, val_acc: {:.4f}/{:.4f}, best_acc: {:.4f}, f1score: {:.4f}'.format(epoch, test_loss, test_acc, test_acc5, best_acc, f1score)))\n\t\ttblogger.log_value('test_acc', test_acc, epoch)\n\t\ttblogger.log_value('test_acc5', test_acc5, epoch)\n\t\ttblogger.log_value('test_loss', test_loss, epoch)\n\t\ttblogger.log_value('f1score', f1score, epoch)\n\n\t\t# save the best model\n\t\tif test_acc > best_acc1:\n\t\t\tbest_acc1 = test_acc\n\t\t\tstate = {\n\t\t\t\t'opt': args,\n\t\t\t\t'epoch': epoch,\n\t\t\t\t'classifier': classifier.state_dict(),\n\t\t\t\t'best_acc1': best_acc1,\n\t\t\t\t'optimizer': optimizer.state_dict(),\n\t\t\t}\n\t\t\tsave_name = '{}_layer{}.pth'.format(args.model, args.layer)\n\t\t\tsave_name = os.path.join(args.save_folder, save_name)\n\t\t\tprint('saving best model!')\n\t\t\ttorch.save(state, save_name)\n\n\t\t# save model\n\t\tif epoch % args.save_freq == 0:\n\t\t\tprint('==> Saving...')\n\t\t\tstate = {\n\t\t\t\t'opt': args,\n\t\t\t\t'epoch': epoch,\n\t\t\t\t'classifier': classifier.state_dict(),\n\t\t\t\t'best_acc1': test_acc,\n\t\t\t\t'optimizer': optimizer.state_dict(),\n\t\t\t}\n\t\t\tsave_name = 'ckpt_epoch_{epoch}.pth'.format(epoch=epoch)\n\t\t\tsave_name = os.path.join(args.save_folder, save_name)\n\t\t\tprint('saving regular model!')\n\t\t\ttorch.save(state, save_name)\n\n\t\t# tensorboard logger\n\t\tpass\n\n\ndef set_lr(optimizer, lr):\n\t\"\"\"\n\tset the learning rate\n\t\"\"\"\n\tfor param_group in optimizer.param_groups:\n\t\tparam_group['lr'] = lr\n\n\ndef train(epoch, train_loader, model, classifier, criterion, optimizer, opt):\n\t\"\"\"\n\tone epoch training\n\t\"\"\"\n\n\tmodel.eval()\n\tclassifier.train()\n\n\tlosses = AverageMeter()\n\ttop1 = AverageMeter()\n\ttop5 = AverageMeter()\n\n\tend = time.time()\n\tpbar = tqdm(train_loader)\n\tfor idx, (input, target) in enumerate(pbar):\n\t\t# measure data loading time\n\t\tinput = input.cuda(opt.gpu, non_blocking=True).float()\n\t\ttarget = target.cuda(opt.gpu, non_blocking=True)\n\n\t\t# ===================forward=====================\n\t\twith torch.no_grad():\n\t\t\tfeat = model(input, opt.layer)\n\t\t\tfeat = feat.detach()\n\n\t\toutput = classifier(feat)\n\t\tloss = criterion(output, target)\n\n\t\tacc1, acc5 = accuracy(output, target, topk=(1, 5))\n\t\tlosses.update(loss.item(), input.size(0))\n\t\ttop1.update(acc1[0], input.size(0))\n\t\ttop5.update(acc5[0], input.size(0))\n\n\n\t\t# ===================backward=====================\n\t\toptimizer.zero_grad()\n\t\tloss.backward()\n\t\toptimizer.step()\n\t\t# ===================meters=====================\n\n\t\t# print info\n\t\tlr = optimizer.param_groups[0]['lr']\n\t\tpbar.set_description(\"Epoch:{} [lr:{}]\".format(epoch, lr))\n\n\t\tinfo = 'loss: {:.4f}, acc: {:.4f} ({:.4f})'.format(losses.avg, top1.avg, top5.avg)\n\t\tpbar.set_postfix(info=info)\n\n\treturn top1.avg, top5.avg, losses.avg\n\n\ndef validate(val_loader, model, classifier, criterion, opt):\n\tlosses = AverageMeter()\n\ttop1 = AverageMeter()\n\ttop5 = AverageMeter()\n\ttrue, preds = [],[]\n\t# switch to evaluate mode\n\tmodel.eval()\n\tclassifier.eval()\n\tf1metric = MultiF1Score(opt.n_labels)\n\twith torch.no_grad():\n\t\tend = time.time()\n\t\tpbar = tqdm(val_loader)\n\t\tfor idx, (input, target) in enumerate(pbar):\n\t\t\tinput = input.cuda(opt.gpu, non_blocking=True).float()\n\t\t\ttarget = target.cuda(opt.gpu, non_blocking=True)\n\n\t\t\t# compute output\n\t\t\tfeat = model(input, opt.layer)\n\t\t\tfeat = feat.detach()\n\t\t\toutput = classifier(feat)\n\t\t\tloss = criterion(output, target)\n\n\t\t\ttrues += [target.cpu().detach()]\n\t\t\tpreds += [output.cpu().detach()]\n\n\t\t\t# measure accuracy and record loss\n\t\t\tacc1, acc5 = accuracy(output, target, topk=(1, 5))\n\t\t\tlosses.update(loss.item(), input.size(0))\n\t\t\ttop1.update(acc1[0], input.size(0))\n\t\t\ttop5.update(acc5[0], input.size(0))\n\t\t\t\n\t\t\tinfo = 'loss: {:.4f}, acc: {:.4f} ({:.4f})'.format(losses.avg, top1.avg, top5.avg)\n\t\t\tpbar.set_postfix(info=info)\n\t\ttrues = torch.cat(trues, dim=0)\n\t\tpreds = torch.cat(preds, dim=0)\n\t\tf1score = f1metric(preds, trues).item()\n\treturn top1.avg, top5.avg, losses.avg, f1score\n\n\ndef accuracy(output, target, topk=(1,)):\n\t\"\"\"Computes the accuracy over the k top predictions for the specified values of k\"\"\"\n\twith torch.no_grad():\n\t\tmaxk = max(topk)\n\t\tbatch_size = target.size(0)\n\n\t\t_, pred = output.topk(maxk, 1, True, True)\n\t\tpred = pred.t()\n\t\tcorrect = pred.eq(target.view(1, -1).expand_as(pred))\n\n\t\tres = []\n\t\tfor k in topk:\n\t\t\tcorrect_k = correct[:k].view(-1).float().sum(0, keepdim=True)\n\t\t\tres.append(correct_k.mul_(100.0 / batch_size))\n\t\treturn res\n\n\nif __name__ == '__main__':\n\tbest_acc1 = 0\n\tmain()\n\n#CUDA_VISIBLE_DEVICES=0,1 python rotation_instance.py --dataset 'imagenet_100' --batch_size 64 --gpus '0,1' --weight_decay 1e-4 --max_epoch 400 --network 'pre-resnet50' --exp '/data/HierachicalAggregation_exp/ImageNet_100/rotation_instance_aug[preresnet50][lam3.0][AB]/' --n_workers 32 --t 0.07 --dist_t 0.07 --lam 3.0 --scheme 'AB' --infonce\n\n# CUDA_VISIBLE_DEVICES=1 python -m downstream.eval_linear --learning_rate 1.0 --model 'resnet18_cifar' --save_folder '/data/HierachicalAggregation_exp/cifar10/Ablation_EasyPos/linear/' --model_path '/data/HierachicalAggregation_exp/cifar10/Ablation_EasyPos/[mix=False][network=resnet18_cifar][lam_inv=0.6][lam_mix=1.0][diffusion_layer=3][K_nearst=4][n_pos=20][exclusive=0][max_epoch=200][ramp_up=binary][nonlinearhead=0]/models/best.pth' --dataset 'cifar10' --gpu '0'\n# CUDA_VISIBLE_DEVICES=0,1 python -m downstream.eval_linear --save_folder '/data/HierachicalAggregation_exp/ImageNet/InvariancePropagation_160190/[mix=False][network=resnet50][lam_inv=0.6][lam_mix=1.0][diffusion_layer=3][K_nearst=4][n_pos=50][exclusive=1][max_epoch=800][ramp_up=binary][nonlinearhead=0][t=0.07][weight_decay=0.0001]/linear/' --model_path '/data/HierachicalAggregation_exp/ImageNet/InvariancePropagation_160190/[mix=False][network=resnet50][lam_inv=0.6][lam_mix=1.0][diffusion_layer=3][K_nearst=4][n_pos=50][exclusive=1][max_epoch=800][ramp_up=binary][nonlinearhead=0][t=0.07][weight_decay=0.0001]/models/best.pth' --dataset 'imagenet' --gpu 0" ]
[ [ "torch.nn.CrossEntropyLoss", "torch.cat", "torch.load", "numpy.asarray", "torch.utils.data.DataLoader", "torch.cuda.empty_cache", "torch.no_grad", "torch.nn.DataParallel", "torch.save" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
savyovinicius/malicious_traffic_description
[ "599c36d16917ec627c77917abb4b0b7b8f6e5166" ]
[ "scripts/mud_to_openflow.py" ]
[ "import socket\nimport pandas as pd\n\ndef read_net_graph():\n\taux = pd.read_json(\"/tmp/mud_graph.json\")\n\treturn aux.drop_duplicates()\n\ndef read_nodes():\n\taux = pd.read_json(\"/tmp/mud_nodes.json\")\n\treturn aux.drop_duplicates()\n\ndef map_address(name):\n\tnodes = read_nodes()\n\ttry:\n\t\treturn nodes[nodes.name==name].ip.item()\n\texcept:\n\t\tprint(f\"[ERROR] Error locally resolving {name}\")\n\t\treturn None\n\ndef handle_tp(port):\n\ttry:\n\t\treturn int(port)\n\texcept:\n\t\treturn None\n\ndef default_rules(dhcp,dns):\n\tdef_rules = []\n\tdef_rules.append(\"priority=1,arp,action=normal\")\n\tdef_rules.append(\"priority=1,udp,nw_dst=255.255.255.255,tp_dst=67,action=normal\")\n\tdef_rules.append(f\"priority=1,udp,nw_src={dhcp},tp_src=67,action=normal\")\n\tdef_rules.append(f\"priority=1,udp,nw_dst={dns},tp_dst=53,action=normal\")\n\tdef_rules.append(f\"priority=1,udp,nw_src={dns},tp_src=53,action=normal\")\n\tdef_rules.append(\"priority=0,action=drop\")\n\n\treturn \"\\n\".join(def_rules)\n\ndef mount_rule(nw_src,nw_dst,transport,tp_src,tp_dst):\n\trule = f\"priority=100,{transport}\"\n\n\tif nw_src is not None:\n\t\trule += f\",nw_src={nw_src}\"\n\n\tif nw_dst is not None:\n\t\trule += f\",nw_dst={nw_dst}\"\n\n\tif tp_src is not None:\n\t\trule += f\",tp_src={tp_src}\"\n\n\tif tp_dst is not None:\n\t\trule += f\",tp_dst={tp_dst}\"\n\n\trule += \",action=normal\\n\"\n\n\treturn rule\n\ndef resolv_domains(graph):\n\tmask_in = (graph['remote_abstraction'] == 'internet') & (graph['incoming'] == True)\n\tmask_out = (graph['remote_abstraction'] == 'internet') & (graph['incoming'] == False)\n\n\tdom_in = graph[mask_in]['src'].drop_duplicates()\n\tdom_out = graph[mask_out]['dst'].drop_duplicates()\n\n\tdomains = pd.Series(dtype=str)\n\n\tdomains = domains.append(dom_in, ignore_index=True)\n\tdomains = domains.append(dom_out, ignore_index=True)\n\tdomains = domains.drop_duplicates()\n\t\n\tresolved = []\n\n\tfor dom in domains:\n\n\t\tmask_src = graph['src'] == dom\n\t\tmask_dst = graph['dst'] == dom\n\n\t\ttry:\n\t\t\taddr = socket.gethostbyname(dom)\n\t\t\t\n\t\t\tresolved.append((dom, addr))\n\n\t\t\tgraph.loc[mask_src,'src'] = addr\n\t\t\tgraph.loc[mask_dst,'dst'] = addr\n\t\texcept:\n\t\t\tgraph.drop(graph[mask_dst | mask_src].index, inplace=True)\n\t\t\tprint(f\"[ERROR] Error resolving {dom}\")\n\n\taux = pd.DataFrame(resolved, columns=['domain', 'address'])\n\twith open('/tmp/resolved_names.json', 'w') as file:\n\t\tfile.write(aux.to_json())\n\n\treturn graph\n\ndef local_map(graph):\n\tmask_in = (graph['remote_abstraction'] != 'internet') & (graph['incoming'] == True)\n\tmask_out = (graph['remote_abstraction'] != 'internet') & (graph['incoming'] == False)\n\n\tdom_in = graph[mask_in]['src'].drop_duplicates()\n\tdom_out = graph[mask_out]['dst'].drop_duplicates()\n\n\tnames = pd.Series(dtype=str)\n\n\tnames = names.append(dom_in, ignore_index=True)\n\tnames = names.append(dom_out, ignore_index=True)\n\tnames = names.drop_duplicates()\n\n\tfor name in names:\n\n\t\tmask_src = graph['src'] == name\n\t\tmask_dst = graph['dst'] == name\n\n\t\ttry:\n\t\t\taddr = map_address(name)\n\n\t\t\tgraph.loc[mask_src,'src'] = addr\n\t\t\tgraph.loc[mask_dst,'dst'] = addr\n\t\texcept:\n\t\t\tprint(f\"[ERROR] Error locally resolving {name}\")\n\n\treturn graph\n\n\n\ndef main():\n\tnet_graph = read_net_graph()\n\n\tnet_graph = resolv_domains(net_graph)\n\tnet_graph = local_map(net_graph)\n\n\trules = []\n\n\tfor index,edge in net_graph.iterrows():\n\n\t\tnw_src,nw_dst = (edge['src'],edge['dst'])\n\n\t\tif((nw_dst is not None) and (nw_src is not None)):\n\n\t\t\ttp_src = handle_tp(edge['t_src'])\n\t\t\ttp_dst = handle_tp(edge['t_dst'])\n\n\t\t\tif edge['transport'].lower() == 'any':\n\t\t\t\trules.append(mount_rule(nw_src,nw_dst,'tcp',tp_src,tp_dst))\n\t\t\t\trules.append(mount_rule(nw_src,nw_dst,'udp',tp_src,tp_dst))\n\t\t\telif (edge['transport'].lower() == 'tcp' or edge['transport'].lower() == 'udp'):\n\t\t\t\trules.append(mount_rule(nw_src,nw_dst,edge['transport'].lower(),tp_src,tp_dst))\n\n\trules = list(dict.fromkeys(rules))\n\n\trules.append(default_rules(\"192.168.5.1\",\"192.168.5.1\"))\n\n\twith open(\"/tmp/mud_ovs_rules.txt\",'w') as file:\n\t\tfile.write(''.join(rules))\n\n\nif __name__ == '__main__':\n\tmain()\n" ]
[ [ "pandas.Series", "pandas.read_json", "pandas.DataFrame" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "0.23", "0.21", "2.0", "1.4", "1.3", "0.19", "1.1", "1.5", "0.24", "0.20", "1.0", "0.25", "1.2" ], "scipy": [], "tensorflow": [] } ]
ESWZY/federated
[ "1693d5fdd25938dc9aadede8d103ed117d1d34c9", "1693d5fdd25938dc9aadede8d103ed117d1d34c9" ]
[ "tensorflow_federated/python/examples/remote_execution/remote_executor_example.py", "tensorflow_federated/python/simulation/sampling_utils_test.py" ]
[ "# Copyright 2018, The TensorFlow Federated Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"Example showing how to run a multi-machine simulation.\n\nIn order to run this example, you must have a running instance of the\nExecutor Service, either locally or on Kubernetes.\n\nThe model trains EMNIST for a small number of rounds, but uses a RemoteExecutor\nto distribute the work to the ExecutorService.\n\"\"\"\n\nimport collections\nimport warnings\n\nfrom absl import app\nfrom absl import flags\nimport grpc\nimport numpy as np\nimport tensorflow as tf\nimport tensorflow_federated as tff\n\nFLAGS = flags.FLAGS\n\nflags.DEFINE_string('host', None, 'The host to connect to.')\nflags.mark_flag_as_required('host')\nflags.DEFINE_string('port', '8000', 'The port to connect to.')\nflags.DEFINE_integer('n_clients', 10, 'Number of clients.')\nflags.DEFINE_integer('n_rounds', 3, 'Number of rounds.')\n\n\ndef preprocess(dataset):\n\n def element_fn(element):\n return collections.OrderedDict([\n ('x', tf.reshape(element['pixels'], [-1])),\n ('y', tf.reshape(element['label'], [1])),\n ])\n\n return dataset.repeat(NUM_EPOCHS).map(element_fn).batch(BATCH_SIZE)\n\n\ndef make_federated_data(client_data, client_ids):\n return [\n preprocess(client_data.create_tf_dataset_for_client(x))\n for x in client_ids\n ]\n\n\nNUM_EPOCHS = 10\nBATCH_SIZE = 20\n\n\ndef make_remote_executor(inferred_cardinalities):\n \"\"\"Make remote executor.\"\"\"\n\n def create_worker_stack(ex):\n ex = tff.framework.ThreadDelegatingExecutor(ex)\n return tff.framework.ReferenceResolvingExecutor(ex)\n\n client_ex = []\n num_clients = inferred_cardinalities.get(tff.CLIENTS, None)\n if num_clients:\n print('Inferred that there are {} clients'.format(num_clients))\n else:\n print('No CLIENTS placement provided')\n\n for _ in range(num_clients or 0):\n channel = grpc.insecure_channel('{}:{}'.format(FLAGS.host, FLAGS.port))\n remote_ex = tff.framework.RemoteExecutor(channel)\n worker_stack = create_worker_stack(remote_ex)\n client_ex.append(worker_stack)\n\n federating_strategy_factory = tff.framework.FederatedResolvingStrategy.factory(\n {\n tff.SERVER: create_worker_stack(tff.framework.EagerTFExecutor()),\n tff.CLIENTS: client_ex,\n })\n unplaced_ex = create_worker_stack(tff.framework.EagerTFExecutor())\n federating_ex = tff.framework.FederatingExecutor(federating_strategy_factory,\n unplaced_ex)\n return tff.framework.ReferenceResolvingExecutor(federating_ex)\n\n\ndef main(argv):\n if len(argv) > 1:\n raise app.UsageError('Too many command-line arguments.')\n\n warnings.simplefilter('ignore')\n\n np.random.seed(0)\n\n emnist_train, _ = tff.simulation.datasets.emnist.load_data()\n\n sample_clients = emnist_train.client_ids[0:FLAGS.n_clients]\n\n federated_train_data = make_federated_data(emnist_train, sample_clients)\n\n example_dataset = emnist_train.create_tf_dataset_for_client(\n emnist_train.client_ids[0])\n\n preprocessed_example_dataset = preprocess(example_dataset)\n input_spec = preprocessed_example_dataset.element_spec\n\n def model_fn():\n model = tf.keras.models.Sequential([\n tf.keras.layers.Input(shape=(784,)),\n tf.keras.layers.Dense(10, kernel_initializer='zeros'),\n tf.keras.layers.Softmax(),\n ])\n return tff.learning.from_keras_model(\n model,\n input_spec=input_spec,\n loss=tf.keras.losses.SparseCategoricalCrossentropy(),\n metrics=[tf.keras.metrics.SparseCategoricalAccuracy()])\n\n iterative_process = tff.learning.build_federated_averaging_process(\n model_fn,\n client_optimizer_fn=lambda: tf.keras.optimizers.SGD(learning_rate=0.02))\n\n factory = tff.framework.ResourceManagingExecutorFactory(make_remote_executor)\n context = tff.framework.ExecutionContext(factory)\n tff.framework.set_default_context(context)\n\n state = iterative_process.initialize()\n\n state, metrics = iterative_process.next(state, federated_train_data)\n print('round 1, metrics={}'.format(metrics))\n\n for round_num in range(2, FLAGS.n_rounds + 1):\n state, metrics = iterative_process.next(state, federated_train_data)\n print('round {:2d}, metrics={}'.format(round_num, metrics))\n\n\nif __name__ == '__main__':\n app.run(main)\n", "# Copyright 2019, The TensorFlow Federated Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom absl.testing import parameterized\nimport tensorflow as tf\n\nfrom tensorflow_federated.python.simulation import sampling_utils\nfrom tensorflow_federated.python.simulation.datasets import client_data\n\n\ndef create_tf_dataset_for_client(client_id):\n del client_id\n return tf.data.Dataset.range(1)\n\n\nclass SamplingTest(tf.test.TestCase, parameterized.TestCase):\n\n @parameterized.named_parameters(\n {\n 'testcase_name': '_int_no_replace',\n 'a': range(100),\n 'replace': False\n }, {\n 'testcase_name': '_int_replace',\n 'a': range(5),\n 'replace': True\n }, {\n 'testcase_name': '_sequence_no_replace',\n 'a': [str(i) for i in range(100)],\n 'replace': False\n }, {\n 'testcase_name': '_sequence_replace',\n 'a': [str(i) for i in range(5)],\n 'replace': True\n })\n def test_build_uniform_sampling_fn_with_random_seed(self, a, replace):\n size = 10\n random_seed = 1\n round_num = 5\n\n sample_fn_1 = sampling_utils.build_uniform_sampling_fn(\n a, size, replace=replace, random_seed=random_seed)\n sample_1 = sample_fn_1(round_num)\n\n sample_fn_2 = sampling_utils.build_uniform_sampling_fn(\n a, size, replace=replace, random_seed=random_seed)\n sample_2 = sample_fn_2(round_num)\n\n self.assertEqual(sample_1, sample_2)\n\n @parameterized.named_parameters(\n {\n 'testcase_name': '_int_no_replace',\n 'a': range(100),\n 'replace': False\n }, {\n 'testcase_name': '_int_replace',\n 'a': range(5),\n 'replace': True\n }, {\n 'testcase_name': '_sequence_no_replace',\n 'a': [str(i) for i in range(100)],\n 'replace': False\n }, {\n 'testcase_name': '_sequence_replace',\n 'a': [str(i) for i in range(5)],\n 'replace': True\n })\n def test_build_sampling_fn_without_random_seed(self, a, replace):\n size = 10\n round_num = 5\n\n sample_fn_1 = sampling_utils.build_uniform_sampling_fn(\n a, size, replace=replace)\n sample_1 = sample_fn_1(round_num)\n\n sample_fn_2 = sampling_utils.build_uniform_sampling_fn(\n a, size, replace=replace)\n sample_2 = sample_fn_2(round_num)\n\n self.assertNotEqual(sample_1, sample_2)\n\n def test_client_sampling_with_one_client(self):\n tff_dataset = client_data.ConcreteClientData([2],\n create_tf_dataset_for_client)\n client_sampling_fn = sampling_utils.build_uniform_client_sampling_fn(\n tff_dataset, clients_per_round=1)\n client_ids = client_sampling_fn(round_num=7)\n self.assertEqual(client_ids, [2])\n\n def test_client_sampling_fn_with_random_seed(self):\n tff_dataset = client_data.ConcreteClientData([0, 1, 2, 3, 4],\n create_tf_dataset_for_client)\n\n client_sampling_fn_1 = sampling_utils.build_uniform_client_sampling_fn(\n tff_dataset, clients_per_round=1, random_seed=363)\n client_ids_1 = client_sampling_fn_1(round_num=5)\n\n client_sampling_fn_2 = sampling_utils.build_uniform_client_sampling_fn(\n tff_dataset, clients_per_round=1, random_seed=363)\n client_ids_2 = client_sampling_fn_2(round_num=5)\n\n self.assertEqual(client_ids_1, client_ids_2)\n\n def test_different_random_seed_give_different_clients(self):\n tff_dataset = client_data.ConcreteClientData(\n list(range(100)), create_tf_dataset_for_client)\n\n client_sampling_fn_1 = sampling_utils.build_uniform_client_sampling_fn(\n tff_dataset, clients_per_round=50, random_seed=1)\n client_ids_1 = client_sampling_fn_1(round_num=1001)\n\n client_sampling_fn_2 = sampling_utils.build_uniform_client_sampling_fn(\n tff_dataset, clients_per_round=50, random_seed=2)\n client_ids_2 = client_sampling_fn_2(round_num=1001)\n\n self.assertNotEqual(client_ids_1, client_ids_2)\n\n def test_client_sampling_fn_without_random_seed(self):\n tff_dataset = client_data.ConcreteClientData(\n list(range(100)), create_tf_dataset_for_client)\n client_sampling_fn = sampling_utils.build_uniform_client_sampling_fn(\n tff_dataset, clients_per_round=50)\n client_ids_1 = client_sampling_fn(round_num=0)\n\n client_ids_2 = client_sampling_fn(round_num=0)\n self.assertNotEqual(client_ids_1, client_ids_2)\n\n\nif __name__ == '__main__':\n tf.test.main()\n" ]
[ [ "numpy.random.seed", "tensorflow.keras.losses.SparseCategoricalCrossentropy", "tensorflow.keras.layers.Dense", "tensorflow.reshape", "tensorflow.keras.optimizers.SGD", "tensorflow.keras.metrics.SparseCategoricalAccuracy", "tensorflow.keras.layers.Softmax", "tensorflow.keras.layers.Input" ], [ "tensorflow.test.main", "tensorflow.data.Dataset.range" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "2.7", "2.6", "2.4", "2.3", "2.5", "2.2" ] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.10" ] } ]
monash-emu/AuTuMN
[ "fa3b81ef54cf561e0e7364a48f4ff96585dc3310", "fa3b81ef54cf561e0e7364a48f4ff96585dc3310" ]
[ "autumn/tools/plots/utils.py", "autumn/tools/plots/plotter/streamlit_plotter.py" ]
[ "import datetime\nfrom typing import List, Dict\n\nimport matplotlib.ticker as ticker\nfrom matplotlib import colors\n\nPLOT_TEXT_DICT = {\n \"contact_rate\": \"infection risk per contact\",\n \"hospital_props_multiplier\": \"hospital risk multiplier\",\n \"compartment_periods.icu_early\": \"pre-ICU period\",\n \"testing_to_detection.assumed_cdr_parameter\": \"CDR at base testing rate\",\n \"microdistancing.parameters.max_effect\": \"max effect microdistancing\",\n \"icu_occupancy\": \"ICU beds occupied\",\n # TB model parameters\n \"start_population_size\": \"initial population size\",\n \"progression_multiplier\": \"progression multiplier\",\n \"time_variant_tb_screening_rate.shape\": \"screening profile (max gradient)\",\n \"time_variant_tb_screening_rate.inflection_time\": \"screening profile (inflection time), year\",\n \"time_variant_tb_screening_rate.upper_asymptote\": \"screening profile (final rate), per year\",\n \"user_defined_stratifications.location.adjustments.detection.ebeye\": \"rel. screening rate (Ebeye)\",\n \"user_defined_stratifications.location.adjustments.detection.other\": \"rel. screening rate (Other Isl.)\",\n \"extra_params.rr_progression_diabetes\": \"rel. progression rate (diabetes)\",\n \"rr_infection_recovered\": \"RR infection (recovered)\",\n \"pt_efficacy\": \"PT efficacy\",\n \"infect_death_rate_dict.smear_positive\": \"TB mortality (smear-pos)\",\n \"infect_death_rate_dict.smear_negative\": \"TB mortality (smear-neg)\",\n \"self_recovery_rate_dict.smear_positive\": \"Self cure rate (smear-pos)\",\n \"self_recovery_rate_dict.smear_negative\": \"Self cure rate (smear-neg)\",\n \"proportion_seropositive\": \"seropositive percentage\",\n \"infection_deaths\": \"deaths\",\n \"incidence\": \"incident episodes per day\",\n \"accum_deaths\": \"cumulative deaths\",\n \"new_hospital_admissions\": \"new hospitalisations per day\",\n \"new_icu_admissions\": \"new ICU admissions per day\",\n \"hospital_occupancy\": \"hospital beds occupied\",\n \"sojourn.compartment_periods_calculated.exposed.total_period\": \"incubation period\",\n \"sojourn.compartment_periods_calculated.active.total_period\": \"duration active\",\n \"mobility.microdistancing.behaviour.parameters.max_effect\": \"max effect microdistancing\",\n \"mobility.microdistancing.behaviour_adjuster.parameters.sigma\": \"microdist max wane\",\n \"mobility.microdistancing.behaviour_adjuster.parameters.c\": \"microdist wane time\",\n \"clinical_stratification.props.hospital.multiplier\": \"hospitalisation adjuster\",\n \"clinical_stratification.icu_prop\": \"ICU proportion\",\n \"sojourn.compartment_periods.icu_early\": \"pre-ICU period\",\n \"other_locations\": \"other locations\",\n \"manila\": \"national capital region\",\n \"victorian_clusters.intercluster_mixing\": \"inter-service mixing\",\n \"clinical_stratification.props.symptomatic.multiplier\": \"sympt prop adjuster\",\n \"clinical_stratification.non_sympt_infect_multiplier\": \"asympt infect multiplier\",\n \"infection_fatality.multiplier\": \"IFR adjuster\",\n \"victorian_clusters.metro.mobility.microdistancing.behaviour_adjuster.parameters.effect\": \"physical distancing\",\n \"victorian_clusters.metro.mobility.microdistancing.face_coverings_adjuster.parameters.effect\": \"face coverings\",\n \"cdr\": \"Proportion detected among symptomatic\",\n \"prevalence\": \"Prevalence of active disease\",\n \"prop_detected_traced\": \"Proportion traced among detected cases\",\n \"prop_contacts_with_detected_index\": \"Proportion of contacts whose index is detected\",\n \"prop_contacts_quarantined\": \"Proportion quarantined among all contacts\",\n \"infection_fatality.top_bracket_overwrite\": \"75 and above IFR\",\n \"victorian_clusters.contact_rate_multiplier_north_metro\": \"north and west metro\",\n \"victorian_clusters.contact_rate_multiplier_south_metro\": \"south and south east metro\",\n \"prop_incidence_strain_delta\": \"Proportion of Delta variant in new cases\",\n \"contact_tracing.assumed_trace_prop\": \"traced prop high prevalence\",\n \"victorian_clusters.metro.mobility.microdistancing.home_reduction.parameters.effect\": \"home contacts reduction\",\n \"unvaccinated_prop\": \"proportion unvaccinated (all ages)\",\n \"one_dose_only_prop\": \"proportion received only one dose (all ages)\",\n \"vaccinated_prop\": \"proportion fully vaccinated (all ages)\",\n \"at_least_one_dose_prop\": \"proportion received at least one dose (all ages)\",\n}\n\nSHORT_TEXT_DICT = {\n \"victorian_clusters.contact_rate_multiplier_north_metro\": \"nw metro\",\n \"victorian_clusters.contact_rate_multiplier_south_metro\": \"s se metro\",\n \"victorian_clusters.contact_rate_multiplier_barwon_south_west\": \"barwon sw\",\n \"victorian_clusters.contact_rate_multiplier_regional\": \"regional\",\n \"contact_rate\": \"contact rate\",\n}\n\nALPHAS = (1.0, 0.6, 0.4, 0.3, 0.2, 0.15, 0.1, 0.08, 0.05)\n# https://matplotlib.org/3.1.0/gallery/color/named_colors.html\nCOLORS = (\n # Blues\n [\"lightsteelblue\", \"cornflowerblue\", \"royalblue\", \"navy\"],\n # Purples\n [\"plum\", \"mediumorchid\", \"darkviolet\", \"rebeccapurple\"],\n # Greens\n [\"palegreen\", \"mediumspringgreen\", \"mediumseagreen\", \"darkgreen\"],\n # Yellows\n [\"lightgoldenrodyellow\", \"palegoldenrod\", \"gold\", \"darkgoldenrod\"],\n # Orangey-browns\n [\"papayawhip\", \"navajowhite\", \"burlywood\", \"saddlebrown\"],\n # Cyans\n [\"lightcyan\", \"paleturquoise\", \"darkcyan\", \"darkslategrey\"],\n # Greys\n [\"lightgrey\", \"darkgrey\", \"dimgrey\", \"black\"],\n # Reds\n [\"lightsalmon\", \"tomato\", \"indianred\", \"darkred\"],\n # Dark greens\n [\"mediumseagreen\", \"seagreen\", \"green\", \"darkgreen\"],\n)\nREF_DATE = datetime.date(2019, 12, 31)\n\n\ndef get_plot_text_dict(\n param_string, capitalise_first_letter=False, remove_underscore=True, remove_dot=True, get_short_text=False,\n):\n \"\"\"\n Get standard text for use in plotting as title, y-label, etc.\n \"\"\"\n\n if get_short_text:\n text = SHORT_TEXT_DICT[param_string] if param_string in SHORT_TEXT_DICT else param_string\n else:\n text = PLOT_TEXT_DICT[param_string] if param_string in PLOT_TEXT_DICT else param_string\n if \"victorian_clusters.contact_rate_multiplier_\" in param_string:\n text = text.replace(\"victorian_clusters.contact_rate_multiplier_\", \"\")\n if \"victorian_clusters.\" in param_string:\n text = text.replace(\"victorian_clusters.metro.mobility.microdistancing\", \"\")\n if \"upper_asymptote\" in param_string:\n text = text.replace(\"parameters.upper_asymptote\", \"\")\n if capitalise_first_letter:\n text = text[0].upper() + text[1:]\n if remove_underscore:\n text = text.replace(\"_\", \" \")\n if remove_dot:\n text = text.replace(\".\", \" \")\n return text\n\n\ndef change_xaxis_to_date(axis, ref_date, date_str_format=\"%#d-%b-%Y\", rotation=30):\n \"\"\"\n Change the format of a numerically formatted x-axis to date.\n \"\"\"\n\n def to_date(x_value, pos):\n date = ref_date + datetime.timedelta(days=int(x_value))\n return date.strftime(date_str_format)\n\n date_format = ticker.FuncFormatter(to_date)\n axis.xaxis.set_major_formatter(date_format)\n axis.xaxis.set_tick_params(rotation=rotation)\n\n\ndef add_vertical_lines_to_plot(axis, lines: Dict):\n \"\"\"\n Add labelled vertical lines to the plot axis according to a dictionary with standard attributes.\n All attributes of the line and text are currently hard-coded.\n \"\"\"\n\n for text, position in lines.items():\n\n # Add the line itself\n axis.axvline(x=position, linestyle=\"--\", alpha=0.7)\n\n # Add the text to accompany it\n upper_ylim = axis.get_ylim()[1]\n axis.text(x=position, y=upper_ylim * 0.97, s=text, rotation=90, ha=\"right\", va=\"top\")\n\n\ndef add_horizontal_lines_to_plot(axis, lines: Dict):\n \"\"\"\n Add labelled horizontal lines to the plot axis according to a dictionary with standard attributes.\n All attributes of the line and text are currently hard-coded.\n \"\"\"\n\n for text, position in lines.items():\n\n # Add the line itself\n axis.axhline(y=position, linestyle=\"--\", alpha=0.7)\n\n # Add the text to accompany it\n lower_xlim = axis.get_xlim()[0]\n axis.text(x=lower_xlim, y=position, s=text, ha=\"left\", va=\"bottom\")\n\n\ndef _apply_transparency(color_list: List[str], alphas: List[str]):\n \"\"\"Make a list of colours transparent, based on a list of alphas\"\"\"\n\n # +++FIXME\n # This will fail if len(color_list) > len(alphas)\n # Should move to generative colours rather than fixed lists\n\n out_colors = []\n\n for i in range(len(color_list)):\n out_colors.append([])\n for j in range(len(color_list[i])):\n rgb_color = list(colors.colorConverter.to_rgb(color_list[i][j]))\n out_colors[i].append(rgb_color + [alphas[i]])\n\n return out_colors\n\n\ndef _plot_targets_to_axis(axis, values: List[float], times: List[int], on_uncertainty_plot=False):\n \"\"\"\n Plot output value calibration targets as points on the axis.\n # TODO: add back ability to plot confidence interval\n x_vals = [time, time]\n axis.plot(x_vals, values[1:], \"m\", linewidth=1, color=\"red\")\n axis.scatter(time, values[0], marker=\"o\", color=\"red\", s=30)\n axis.scatter(time, values[0], marker=\"o\", color=\"white\", s=10)\n \"\"\"\n assert len(times) == len(values), \"Targets have inconsistent length\"\n # Plot a single point estimate\n if on_uncertainty_plot:\n axis.scatter(times, values, marker=\"o\", color=\"black\", s=10, zorder=999)\n else:\n axis.scatter(times, values, marker=\"o\", color=\"red\", s=30, zorder=999)\n axis.scatter(times, values, marker=\"o\", color=\"white\", s=10, zorder=999)\n\n\ndef split_mcmc_outputs_by_chain(mcmc_params, mcmc_tables):\n chain_ids = mcmc_params[0][\"chain\"].unique().tolist()\n mcmc_params_list, mcmc_tables_list = [], []\n for i_chain in chain_ids:\n mcmc_params_list.append(\n mcmc_params[0][mcmc_params[0][\"chain\"] == i_chain]\n )\n mcmc_tables_list.append(\n mcmc_tables[0][mcmc_tables[0][\"chain\"] == i_chain]\n )\n\n return mcmc_params_list, mcmc_tables_list\n", "import streamlit as st\nimport os\n\nfrom .base_plotter import BasePlotter\nfrom matplotlib import pyplot\n\n\nclass StreamlitPlotter(BasePlotter):\n \"\"\"\n Plots stuff in Streamlit.\n \"\"\"\n\n def __init__(self, targets: dict):\n self.translation_dict = {t[\"output_key\"]: t[\"title\"] for t in targets.values()}\n\n def save_figure(self, fig, filename: str, subdir=None, title_text=None, dpi_request=300):\n if title_text:\n pretty_title = self.get_plot_title(title_text).replace(\"X\", \" \")\n md = f\"<p style='text-align: center;padding-left: 80px'>{pretty_title}</p>\"\n st.markdown(md, unsafe_allow_html=True)\n\n st.pyplot(fig, dpi=dpi_request, bbox_inches=\"tight\")\n\n\nclass StreamlitSavingPlotter(StreamlitPlotter):\n def save_figure(self, fig, filename: str, subdir=None, title_text=None, dpi_request=300, output_dirname=\"vic_figures\"):\n if title_text:\n pretty_title = self.get_plot_title(title_text).replace(\"X\", \" \")\n md = f\"<p style='text-align: center;padding-left: 80px'>{pretty_title}</p>\"\n st.markdown(md, unsafe_allow_html=True)\n\n st.pyplot(fig, dpi=dpi_request, bbox_inches=\"tight\")\n\n if not os.path.isdir(output_dirname):\n os.makedirs(output_dirname)\n\n for extension in [\"png\", \"pdf\"]:\n dir_extension_name = os.path.join(output_dirname, extension)\n if not os.path.isdir(dir_extension_name):\n os.makedirs(dir_extension_name)\n path = os.path.join(dir_extension_name, f\"{filename}.{extension}\")\n pyplot.savefig(path)\n" ]
[ [ "matplotlib.ticker.FuncFormatter", "matplotlib.colors.colorConverter.to_rgb" ], [ "matplotlib.pyplot.savefig" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
1980744819/playing-mario-with-DQN
[ "f263e3615bf4439ad17d95a9f449c6145792402b" ]
[ "break_out/memory.py" ]
[ "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @File : memory.py\n# @Author: zixiao\n# @Date : 2019-04-07\n# @Desc :\nimport numpy as np\n\n\nclass Memory:\n def __init__(self, size, w, h, frame_len):\n self.size = size\n self.index = 0\n self.count = 0\n self.num_in_memory = 0\n self.frame_len = frame_len\n self.obs = np.zeros((size, w, h), dtype=np.uint8)\n self.actions = np.zeros((size,), dtype=np.uint8)\n self.rewards = np.zeros((size,), dtype=np.float32)\n self.obs_shape = [w, h]\n self.w = w\n self.h = h\n\n def store_transition(self, action, reward, obs_):\n index = int((self.index + 1) % self.size)\n\n self.actions[self.index] = action\n self.rewards[self.index] = reward\n self.obs[index] = obs_\n self.index = index\n self.count += 1\n self.num_in_memory = min(self.size, self.count)\n\n def get_memory(self, batch_size):\n nums = np.random.choice(self.num_in_memory, size=batch_size)\n obs_batch = np.zeros((batch_size, self.frame_len, self.w, self.h))\n obs_batch_ = np.zeros((batch_size, self.frame_len, self.w, self.h))\n for i in range(len(nums)):\n obs_start = nums[i] - self.frame_len + 1\n obs_end = nums[i]\n if obs_start < 0:\n obs_start += self.num_in_memory\n obs_batch[i] = np.concatenate((self.obs[obs_start:self.num_in_memory ], self.obs[0:obs_end + 1]))\n else:\n obs_batch[i] = self.obs[obs_start:obs_end + 1]\n obs_start_ = nums[i]\n obs_end_ = nums[i] + self.frame_len - 1\n if obs_end_ >=self.num_in_memory:\n obs_end_ -= self.num_in_memory\n obs_batch_[i] = np.concatenate((self.obs[obs_start_:self.num_in_memory ], self.obs[0:obs_end_ + 1]))\n else:\n obs_batch_[i] = self.obs[obs_start_:obs_end_ + 1]\n action_batch = self.actions[nums]\n reward_batch = self.rewards[nums]\n return obs_batch, action_batch, reward_batch, obs_batch_\n\n def get_last_frame(self):\n start = self.index - self.frame_len + 1\n end = self.index\n if start < 0:\n start += self.num_in_memory\n obs_frame = np.concatenate((self.obs[start:self.num_in_memory + 1], self.obs[0:end + 1]))\n else:\n obs_frame = self.obs[start:end + 1]\n return obs_frame\n\n def store_obs(self, obs):\n self.obs[self.index] = obs\n" ]
[ [ "numpy.concatenate", "numpy.zeros", "numpy.random.choice" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
muntasir2000/lingvo
[ "1555299b817288b5a6637ded416dbbdc9b00036d", "4c6405a3c8b29764918dbfb599212dd7620ccf9c", "1555299b817288b5a6637ded416dbbdc9b00036d", "1555299b817288b5a6637ded416dbbdc9b00036d", "1555299b817288b5a6637ded416dbbdc9b00036d" ]
[ "lingvo/core/base_layer_test.py", "lingvo/core/ops/random_ops_test.py", "lingvo/tasks/punctuator/input_generator.py", "lingvo/core/bfloat16_variables_test.py", "lingvo/core/task_scheduler.py" ]
[ "# Lint as: python2, python3\n# Copyright 2018 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"Tests for base_layer.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\nfrom lingvo.core import base_layer\nfrom lingvo.core import hyperparams\nfrom lingvo.core import py_utils\nfrom lingvo.core import test_utils\nimport tensorflow as tf\n\n\nclass AddingAccumulator(base_layer.Accumulator):\n\n def DefaultValue(self):\n return tf.convert_to_tensor(0.0)\n\n def Update(self, new_value):\n self.SetValue(self.GetValue() + new_value)\n\n\ndef EvalAndFlatten(nmap):\n return nmap.Transform(lambda x: x.eval()).FlattenItems()\n\n\nclass TestLayer(base_layer.BaseLayer):\n\n @base_layer.initializer\n def __init__(self, params):\n super(TestLayer, self).__init__(params)\n p = self.params\n with tf.variable_scope(p.name):\n self.CreateVariable(\n 'w',\n py_utils.WeightParams(\n shape=[4, 4],\n dtype=p.dtype,\n init=p.params_init,\n collections=[self.__class__.__name__ + '_vars']))\n self.CreateVariable(\n 'b',\n py_utils.WeightParams(\n shape=[4],\n dtype=p.dtype,\n init=py_utils.WeightInit.Constant(),\n collections=[\n self.__class__.__name__ + '_vars',\n py_utils.SKIP_LP_REGULARIZATION\n ]))\n\n\nclass BaseLayerTest(test_utils.TestCase):\n\n def testCopyBaseParams(self):\n # CopyBaseParams should only overwrite is_eval/vn setting when target use\n # default is_eval/vn config.\n layer_base_p = base_layer.BaseLayer.Params()\n from_param = layer_base_p.Copy()\n to_param = layer_base_p.Copy()\n from_param.is_eval = False\n from_param.vn.global_vn = True\n from_param.random_seed = 1234\n from_param.skip_lp_regularization = True\n # Target use default, overwrite.\n base_layer.BaseLayer.CopyBaseParams(from_param, to_param)\n self.assertEqual(False, to_param.is_eval)\n self.assertTrue(to_param.vn.global_vn)\n self.assertEqual(1234, to_param.random_seed)\n self.assertTrue(to_param.skip_lp_regularization)\n to_param = layer_base_p.Copy()\n to_param.is_eval = True\n to_param.vn.per_step_vn = True\n to_param.random_seed = 4321\n to_param.skip_lp_regularization = False\n # Target does not use default, should not overwrite.\n base_layer.BaseLayer.CopyBaseParams(from_param, to_param)\n self.assertEqual(True, to_param.is_eval)\n self.assertTrue(to_param.vn.per_step_vn)\n self.assertFalse(to_param.vn.global_vn)\n self.assertEqual(4321, to_param.random_seed)\n self.assertFalse(to_param.skip_lp_regularization)\n\n def testCreateChildren(self):\n layer_p = base_layer.BaseLayer.Params()\n layer_p.name = 'test'\n layer = layer_p.Instantiate()\n layer.CreateChildren('a', [layer_p, [layer_p, layer_p], layer_p])\n self.assertEqual(len(layer.a), 3)\n self.assertEqual(len(layer.a[1]), 2)\n self.assertEqual(len(layer.vars.a), 3)\n self.assertEqual(len(layer.vars.a[1]), 2)\n self.assertEqual(len(layer.theta.a), 3)\n self.assertEqual(len(layer.theta.a[1]), 2)\n\n def testCreateVariable(self):\n layer_p = TestLayer.Params().Set(name='test')\n layer = layer_p.Instantiate()\n self.assertEqual('test/w/var:0', layer.vars.w.name)\n self.assertEqual('test/b/var:0', layer.vars.b.name)\n self.assertNotIn(layer.vars.w,\n tf.get_collection(py_utils.SKIP_LP_REGULARIZATION))\n # 'b' always skips Lp regularization.\n self.assertIn(layer.vars.b,\n tf.get_collection(py_utils.SKIP_LP_REGULARIZATION))\n\n def testCreateVariableSkipLpRegularization(self):\n layer_p = TestLayer.Params().Set(name='test', skip_lp_regularization=True)\n layer = layer_p.Instantiate()\n self.assertIn(layer.vars.w,\n tf.get_collection(py_utils.SKIP_LP_REGULARIZATION))\n self.assertIn(layer.vars.b,\n tf.get_collection(py_utils.SKIP_LP_REGULARIZATION))\n\n def testGetDescendant(self):\n q = base_layer.BaseLayer.Params()\n q.name = 'test'\n l = q.Instantiate()\n p = base_layer.BaseLayer.Params()\n l.CreateChild('a', p)\n l.CreateChild('b', p)\n l.a.CreateChild('c', p)\n l.a.c.CreateChild('d', p)\n l.b.CreateChild('e', p)\n self.assertEqual(l, l.GetDescendant(''))\n self.assertEqual(l.a, l.GetDescendant('a'))\n self.assertEqual(l.b, l.GetDescendant('b'))\n self.assertEqual(l.a.c, l.GetDescendant('a.c'))\n self.assertEqual(l.a.c.d, l.GetDescendant('a.c.d'))\n self.assertEqual(l.b.e, l.GetDescendant('b.e'))\n\n def testCreateAccumulator(self):\n layer_p = base_layer.BaseLayer.Params()\n layer_p.name = 'test'\n layer = layer_p.Instantiate()\n layer.CreateChild('child', layer_p)\n\n # First accumulator should succeed.\n acc1 = AddingAccumulator()\n layer.RegisterAccumulator('acc1', acc1)\n\n # Name of existing child should fail.\n with self.assertRaises(AssertionError):\n layer.RegisterAccumulator('child', AddingAccumulator())\n\n # Duplicate should fail.\n with self.assertRaises(AssertionError):\n layer.RegisterAccumulator('acc1', AddingAccumulator())\n\n # Child with the same name should fail.\n with self.assertRaises(AssertionError):\n layer.CreateChild('acc1', layer_p)\n\n self.assertEqual(acc1, layer.accumulators.acc1)\n\n # Get of not created accumulator should fail.\n with self.assertRaises(AttributeError):\n layer.accumulators.notexist\n\n def testGetUpdateAccumulator(self):\n with self.session():\n layer_p = base_layer.BaseLayer.Params()\n layer_p.name = 'test'\n layer = layer_p.Instantiate()\n\n layer.RegisterAccumulator('acc1', AddingAccumulator())\n\n # Initial value.\n self.assertEqual(0.0, layer.accumulators.acc1.GetValue().eval())\n\n # Update/merge.\n layer.accumulators.acc1.Update(1.0)\n layer.accumulators.acc1.Update(1.0)\n self.assertEqual(2.0, layer.accumulators.acc1.GetValue().eval())\n\n # Reset.\n layer.accumulators.Transform(lambda acc: acc.Reset())\n self.assertEqual(0.0, layer.accumulators.acc1.GetValue().eval())\n\n def testAccumulatorDisableEnable(self):\n with self.session():\n layer_p = base_layer.BaseLayer.Params()\n layer_p.name = 'test'\n layer = layer_p.Instantiate()\n\n layer.RegisterAccumulator('acc1', AddingAccumulator())\n layer.accumulators.acc1.Update(1.0)\n\n # Disable should force value to 0 and reject updates.\n layer.accumulators.Transform(lambda acc: acc.Disable())\n self.assertEqual(0.0, layer.accumulators.acc1.GetValue().eval())\n layer.accumulators.acc1.Update(3.0)\n self.assertEqual(0.0, layer.accumulators.acc1.GetValue().eval())\n layer.accumulators.Transform(lambda acc: acc.Enable())\n\n # Should restore.\n self.assertEqual(1.0, layer.accumulators.acc1.GetValue().eval())\n\n def testGetSetAccumulatorValues(self):\n with self.session():\n layer_p = base_layer.BaseLayer.Params()\n layer_p.name = 'test'\n layer1 = layer_p.Instantiate()\n layer1.CreateChild('layer1a', layer_p)\n layer1.CreateChild('layer1b', layer_p)\n layer1.layer1b.CreateChild('layer1b1', layer_p)\n\n # Create nested accumulators:\n # acc1: layer1\n # acc2: layer1.layer1a\n # acc3: layer1.layer1b.layer1b1\n layer1.RegisterAccumulator('acc1', AddingAccumulator())\n layer1.layer1a.RegisterAccumulator('acc2', AddingAccumulator())\n layer1.layer1b.layer1b1.RegisterAccumulator('acc3', AddingAccumulator())\n\n # Pack with initial values.\n initial_pack = layer1.GetAccumulatorValues()\n initial_pack_eval = EvalAndFlatten(initial_pack)\n print('Initial values pack =', initial_pack_eval)\n self.assertEqual(initial_pack_eval, [('acc1', 0.0), ('layer1a.acc2', 0.0),\n ('layer1b.layer1b1.acc3', 0.0)])\n\n # Update to a new known state.\n layer1.accumulators.acc1.Update(1.0)\n layer1.layer1a.accumulators.acc2.Update(2.0)\n layer1.layer1b.layer1b1.accumulators.acc3.Update(3.0)\n updated_pack = layer1.GetAccumulatorValues()\n updated_pack_eval = EvalAndFlatten(updated_pack)\n print('Updated values pack =', updated_pack_eval)\n self.assertEqual(updated_pack_eval, [('acc1', 1.0), ('layer1a.acc2', 2.0),\n ('layer1b.layer1b1.acc3', 3.0)])\n\n # Save and reset.\n saved_pack = layer1.GetAccumulatorValues()\n layer1.accumulators.Transform(lambda acc: acc.Reset())\n self.assertEqual(0.0, layer1.accumulators.acc1.GetValue().eval())\n self.assertEqual(0.0, layer1.layer1a.accumulators.acc2.GetValue().eval())\n self.assertEqual(\n 0.0,\n layer1.layer1b.layer1b1.accumulators.acc3.GetValue().eval())\n\n # Set and check.\n layer1.SetAccumulatorValues(saved_pack)\n self.assertEqual(1.0, layer1.accumulators.acc1.GetValue().eval())\n self.assertEqual(2.0, layer1.layer1a.accumulators.acc2.GetValue().eval())\n self.assertEqual(\n 3.0,\n layer1.layer1b.layer1b1.accumulators.acc3.GetValue().eval())\n\n def testAddFunction(self):\n layer_p = base_layer.BaseLayer.Params()\n layer_p.name = 'test'\n layer = layer_p.Instantiate()\n\n layer.AddFunction('test1', lambda: 1)\n with self.assertRaises(AttributeError):\n layer.AddFunction('test1', lambda: 2)\n self.assertEquals(1, layer.fns.test1())\n\n def testAttributeErrorInPropertyGetter(self):\n\n class BadLayer(base_layer.BaseLayer):\n\n @classmethod\n def Params(cls):\n return super(BadLayer, cls).Params()\n\n @base_layer.initializer\n def __init__(self, params):\n super(BadLayer, self).__init__(params)\n\n @property\n def bad_property(self):\n raise AttributeError('INTERNAL')\n\n layer_p = BadLayer.Params()\n layer_p.name = 'test'\n layer = layer_p.Instantiate()\n\n with self.assertRaisesRegexp(AttributeError, 'bad_sub_layer'):\n _ = layer.bad_sub_layer\n\n with self.assertRaisesRegexp(AttributeError, 'INTERNAL'):\n _ = layer.bad_property\n\n def testIsLayerParams(self):\n self.assertTrue(base_layer.IsLayerParams(base_layer.BaseLayer.Params()))\n self.assertTrue(base_layer.IsLayerParams(TestLayer.Params()))\n self.assertFalse(base_layer.IsLayerParams(None))\n self.assertFalse(base_layer.IsLayerParams(hyperparams.Params()))\n self.assertFalse(\n base_layer.IsLayerParams(\n hyperparams.InstantiableParams(base_layer.Accumulator)))\n\n\nif __name__ == '__main__':\n tf.test.main()\n", "# Copyright 2018 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"Tests for random_ops.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\nfrom lingvo.core import test_utils\nfrom lingvo.core.ops import py_x_ops\nfrom six.moves import range\nimport tensorflow as tf\n\nFLAGS = tf.flags.FLAGS\n\n\nclass RandomOpsTest(test_utils.TestCase):\n\n def testRandomPermutationSequenceRepeat(self):\n with self.session() as sess:\n out = py_x_ops.random_permutation_sequence(num=20, batch=7, repeat=True)\n\n remaining = list(range(20))\n for _ in range(10):\n # Each epoch takes exactly 3 steps.\n vals = sess.run(out).tolist() + sess.run(out).tolist() + sess.run(\n out).tolist()\n self.assertEqual(len(vals), 21)\n\n # Contains all the remaining values from previous epoch.\n for x in remaining:\n vals.remove(x) # Raises exception if x is not in vals.\n\n # Remaining items have no duplicates.\n self.assertEqual(len(vals), len(set(vals)))\n\n remaining = list(set(range(20)) - set(vals))\n\n def testRandomPermutationSequenceNoRepeat(self):\n with self.session() as sess:\n out = py_x_ops.random_permutation_sequence(num=20, batch=7, repeat=False)\n\n # Each epoch takes exactly 3 steps.\n vals = sess.run(out).tolist() + sess.run(out).tolist() + sess.run(\n out).tolist()\n self.assertEqual(list(range(20)), sorted(vals))\n\n # repeat=False. We should see OutOfRange error.\n with self.assertRaises(tf.errors.OutOfRangeError):\n sess.run(out)\n\n\nif __name__ == '__main__':\n tf.test.main()\n", "# Lint as: python2, python3\n# Copyright 2018 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"Punctuator input generator.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport string\nfrom lingvo.core import base_input_generator\nfrom lingvo.core import base_layer\nfrom lingvo.core import generic_input\nfrom lingvo.core import py_utils\nfrom lingvo.core import tokenizers\nimport tensorflow as tf\n\n\nclass PunctuatorInput(base_input_generator.BaseSequenceInputGenerator):\n \"\"\"Reads text line by line and processes them for the punctuator task.\"\"\"\n\n @classmethod\n def Params(cls):\n \"\"\"Defaults params for PunctuatorInput.\"\"\"\n p = super(PunctuatorInput, cls).Params()\n p.tokenizer = tokenizers.WpmTokenizer.Params()\n return p\n\n def _ProcessLine(self, line):\n \"\"\"A single-text-line processor.\n\n Gets a string tensor representing a line of text that have been read from\n the input file, and splits it to graphemes (characters).\n We use original characters as the target labels, and the lowercased and\n punctuation-removed characters as the source labels.\n\n Args:\n line: a 1D string tensor.\n\n Returns:\n A list of tensors, in the expected order by __init__.\n \"\"\"\n # Tokenize the input into integer ids.\n # tgt_ids has the start-of-sentence token prepended, and tgt_labels has the\n # end-of-sentence token appended.\n tgt_ids, tgt_labels, tgt_paddings = self.StringsToIds(\n tf.convert_to_tensor([line]))\n\n def Normalize(line):\n # Lowercase and remove punctuation.\n line = line.lower().translate(None, string.punctuation.encode('utf-8'))\n # Convert multiple consecutive spaces to a single one.\n line = b' '.join(line.split())\n return line\n\n normalized_line = tf.py_func(Normalize, [line], tf.string, stateful=False)\n _, src_labels, src_paddings = self.StringsToIds(\n tf.convert_to_tensor([normalized_line]), is_source=True)\n # The model expects the source without a start-of-sentence token.\n src_ids = src_labels\n\n # Compute the length for bucketing.\n bucket_key = tf.to_int32(\n tf.maximum(\n tf.reduce_sum(1.0 - src_paddings),\n tf.reduce_sum(1.0 - tgt_paddings)))\n tgt_weights = 1.0 - tgt_paddings\n\n # Return tensors in an order consistent with __init__.\n out_tensors = [\n src_ids, src_paddings, tgt_ids, tgt_paddings, tgt_labels, tgt_weights\n ]\n return [tf.squeeze(t, axis=0) for t in out_tensors] + [bucket_key]\n\n def _DataSourceFromFilePattern(self, file_pattern):\n \"\"\"Create the input processing op.\n\n Args:\n file_pattern: The file pattern to use as input.\n\n Returns:\n an operation that when executed, calls `_ProcessLine` on a line read\n from `file_pattern`.\n \"\"\"\n return generic_input.GenericInput(\n file_pattern=file_pattern,\n processor=self._ProcessLine,\n # Pad dimension 0 to the same length.\n dynamic_padding_dimensions=[0] * 6,\n # The constant values to use for padding each of the outputs.\n dynamic_padding_constants=[0, 1, 0, 1, 0, 0],\n **self.CommonInputOpArgs())\n\n @base_layer.initializer\n def __init__(self, params):\n super(PunctuatorInput, self).__init__(params)\n\n # Build the input processing graph.\n (self._src_ids, self._src_paddings, self._tgt_ids, self._tgt_paddings,\n self._tgt_labels, self._tgt_weights) = self._BuildDataSource()\n\n self._input_batch_size = tf.shape(self._src_ids)[0]\n self._sample_ids = tf.range(0, self._input_batch_size, 1)\n\n def InputBatch(self):\n \"\"\"Returns a single batch as a `.NestedMap` to be passed to the model.\"\"\"\n ret = py_utils.NestedMap()\n\n ret.src = py_utils.NestedMap()\n ret.src.ids = tf.cast(self._src_ids, dtype=tf.int32)\n ret.src.paddings = self._src_paddings\n\n ret.tgt = py_utils.NestedMap()\n ret.tgt.ids = self._tgt_ids\n ret.tgt.labels = tf.cast(self._tgt_labels, dtype=tf.int32)\n ret.tgt.weights = self._tgt_weights\n ret.tgt.paddings = self._tgt_paddings\n\n return ret\n", "# Lint as: python2, python3\n# Copyright 2018 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"Tests for bfloat16_variables.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport os\nfrom lingvo.core import bfloat16_variables\nfrom lingvo.core import test_utils\nimport tensorflow as tf\n\n\nclass Bfloat16VariablesTest(test_utils.TestCase):\n\n def testBfloat16Reload(self):\n checkpoint_path = os.path.join(self.get_temp_dir(), \"bfloat16_restore\")\n\n # Create a resource variable of type tf.float32 and save them to disk.\n g_for_save_graph = tf.Graph()\n fl = 0.99\n with self.session(graph=g_for_save_graph) as sess:\n v0 = tf.Variable(fl, name=\"v0\", dtype=tf.float32, use_resource=True)\n tf.global_variables_initializer().run()\n self.assertAlmostEqual(fl, v0.eval())\n\n saver = tf.train.Saver({\n \"v0\": v0,\n }, restore_sequentially=True)\n val = saver.save(sess, checkpoint_path)\n self.assertEqual(checkpoint_path, val)\n\n # Restore the variable as bfloat16.\n g_for_restore_graph = tf.Graph()\n with self.session(graph=g_for_restore_graph) as sess:\n v0 = tf.Variable(0.0, name=\"v0\", dtype=tf.bfloat16, use_resource=True)\n tf.global_variables_initializer().run()\n self.assertAlmostEqual(0.0, v0.eval())\n saveable = bfloat16_variables.Bfloat16VariableSaveable(\n v0, tf.float32, \"\", \"v0\")\n saver = tf.train.Saver({\"v0\": saveable}, restore_sequentially=True)\n saver.restore(sess, checkpoint_path)\n self.assertAlmostEqual(fl, v0.eval())\n\n\nif __name__ == \"__main__\":\n tf.test.main()\n", "# Lint as: python2, python3\n# Copyright 2018 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"Multi-task task sampling schedules.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\nfrom lingvo.core import base_layer\nfrom lingvo.core import early_stop\nimport numpy as np\nimport tensorflow as tf\n\n\nclass TaskScheduler(base_layer.BaseLayer):\n \"\"\"Generic multi-task scheduler.\n\n Subclasses should override the `Sample` method to return a task string given\n a step. All of the task strings as well as additional hyperparameters needed\n by `Sample` should be exposed and stored in the params. `Sample` should also\n update `cur_probs`.\n \"\"\"\n\n @classmethod\n def Params(cls):\n \"\"\"Parameters for this task scheduler.\"\"\"\n p = super(TaskScheduler, cls).Params()\n p.name = 'task_scheduler'\n return p\n\n @base_layer.initializer\n def __init__(self, params):\n super(TaskScheduler, self).__init__(params)\n self.cur_probs = None\n\n def Sample(self, current_step):\n raise NotImplementedError('Abstract method')\n\n\nclass AdaptiveScheduler(TaskScheduler):\n \"\"\"Tasks with low scores will be sampled more often.\n\n Scores are expected to be non-negative. Larger scores are better.\"\"\"\n\n @classmethod\n def Params(cls):\n p = super(AdaptiveScheduler, cls).Params()\n p.Define('tasks', [], 'List of tasks')\n p.Define('expected', [], 'List of final expected scores')\n p.Define('mh_a', early_stop.MetricHistory.Params(), '')\n p.Define('mh_b', early_stop.MetricHistory.Params(), '')\n p.Define(\n 'epsilon', 0.05, 'Regularizarion term. A large epsilon will lead'\n 'to a more uniform task distribution.')\n p.Define('alpha', 1.0, 'Normalized task scores are raised to this power.')\n return p\n\n @base_layer.initializer\n def __init__(self, params):\n super(AdaptiveScheduler, self).__init__(params)\n if len(self.params.tasks) != 2 or len(self.params.expected) != 2:\n raise ValueError('Only two tasks are supported by this scheduler.')\n\n if self.params.epsilon < 0:\n raise ValueError('Epsilon should be positive.')\n\n self.tasks = self.params.tasks\n\n self.last_scores = [0.0] * 2\n\n self._metric_histories = [\n early_stop.MetricHistory(self.params.mh_a),\n early_stop.MetricHistory(self.params.mh_b)\n ]\n\n def getMetricHistories(self):\n # If too slow, consider another implementation.\n # TODO(sebjean) Time file reading and change behaviour if too long.\n for index, mh in enumerate(self._metric_histories):\n try:\n with tf.gfile.GFile(mh.hist_file) as f:\n lines = f.readlines()\n except tf.errors.NotFoundError:\n tf.logging.warning('File not found. '\n 'Expected at start of training only.')\n score, lines = 0.0, []\n if lines:\n try:\n score = lines[-1].split()[-1]\n except IndexError:\n tf.logging.warning('IndexError. Your history file may be corrupted.')\n score = 0.0\n self.last_scores[index] = float(score)\n\n\nclass SimpleAdaptiveScheduler(AdaptiveScheduler):\n \"\"\"Simple adaptive scheduler.\n\n A task with a normalized score of `s` is approximately weighted as `1 - s`.\n \"\"\"\n\n def Sample(self, current_step):\n \"\"\"Sample a task.\n\n The unnormalized probability of a task if given by\n 1 + epsilon - min(1, score / expected)**alpha.\n\n Args:\n current_step: Unused.\n\n Returns:\n str, the name of the sampled task.\n \"\"\"\n del current_step # Unused\n\n self.getMetricHistories()\n\n alpha, eps = self.params.alpha, self.params.epsilon\n probs = [\n 1 + eps - min(1, score / self.params.expected[index])**alpha\n for index, score in enumerate(self.last_scores)\n ]\n probs = tuple(probs / np.sum(probs))\n sampled_task = np.random.choice(self.params.tasks, p=probs)\n self.cur_probs = probs\n return sampled_task\n\n\nclass InverseRatioAdaptiveScheduler(AdaptiveScheduler):\n \"\"\"Inverse ratio adaptive scheduler.\n\n Tasks are approximately weighed as the inverse of their normalized scores.\n \"\"\"\n\n def Sample(self, current_step):\n \"\"\"Sample a task.\n\n The unnormalized probability of a task if given by\n 1 / (min(1, score / expected)**alpha + epsilon)\n\n Args:\n current_step: Unused.\n\n Returns:\n str, the name of the sampled task.\n \"\"\"\n del current_step # Unused\n\n self.getMetricHistories()\n\n alpha, eps = self.params.alpha, self.params.epsilon\n probs = [\n 1.0 / (min(1, score / self.params.expected[index])**alpha + eps)\n for index, score in enumerate(self.last_scores)\n ]\n probs = tuple(probs / np.sum(probs))\n sampled_task = np.random.choice(self.params.tasks, p=probs)\n self.cur_probs = probs\n return sampled_task\n\n\nclass ShiftedExponentialScheduler(TaskScheduler):\n \"\"\"The unnormalized score of each task follows a shifted exponential function.\n\n Generalizes the constant, exponential and sigmoid\n schedules described in \"Scheduled Multi-Task Learning: From Syntax to\n Translation\" (Kiperwasser and Ballesteros).\n https://arxiv.org/pdf/1804.08915.pdf\n \"\"\"\n\n @classmethod\n def Params(cls):\n p = super(ShiftedExponentialScheduler, cls).Params()\n p.Define(\n 'alpha', 0, 'Controls the rate at which the schedule changes. '\n 'A large alpha will lead to fast convergence toward final values.')\n p.Define(\n 'task_probs', [], 'List of 2-tuples (task, prob). For non-constant'\n 'schedulers, prob is a tuble of the form (init_prob, final_prob).')\n return p\n\n @base_layer.initializer\n def __init__(self, params):\n super(ShiftedExponentialScheduler, self).__init__(params)\n assert isinstance(self.params.task_probs, list)\n self.tasks = []\n self._descriptors = []\n\n def Sample(self, current_step):\n \"\"\"Sample a task.\n\n Given an input [a, b] and a rate `alpha`, the unnormalized\n score of eack task is a + b * exp(-alpha * t).\n\n Args:\n current_step: int. Current time step.\n\n Returns:\n str, the name of the sampled task.\n \"\"\"\n probs = [\n a + b * np.exp(-self.params.alpha * current_step)\n for a, b in self._descriptors\n ]\n probs = tuple(probs / np.sum(probs))\n sampled_task = np.random.choice(self.tasks, p=probs)\n self.cur_probs = probs\n return sampled_task\n\n\nclass ConstantScheduler(ShiftedExponentialScheduler):\n \"\"\"Constant schedule. Tasks are sampled from a fixed probability distribution.\n \"\"\"\n\n @base_layer.initializer\n def __init__(self, params):\n super(ConstantScheduler, self).__init__(params)\n\n for key, value in self.params.task_probs:\n self.tasks.append(key)\n self._descriptors.append((value, 0))\n\n\nclass ExponentialScheduler(ShiftedExponentialScheduler):\n \"\"\"Exponential schedule.\n\n For a task with initial and final probabilities p_0 and p_1 respectively,\n its unnormalized score is given by\n `p_1 + (p_0 - p_1) * exp(-alpha * current_step)`.\n \"\"\"\n\n @base_layer.initializer\n def __init__(self, params):\n super(ExponentialScheduler, self).__init__(params)\n\n for key, value in self.params.task_probs:\n self.tasks.append(key)\n self._descriptors.append((value[1], value[0] - value[1]))\n\n\nclass SigmoidScheduler(ShiftedExponentialScheduler):\n \"\"\"Sigmoid schedule.\n\n For a task with initial and final probabilities p_0 and p_1 respectively,\n its unnormalized score is given by\n `p_1 + (2 * p_0 - p_1) * exp(-alpha * current_step)`.\n \"\"\"\n\n @base_layer.initializer\n def __init__(self, params):\n super(SigmoidScheduler, self).__init__(params)\n\n for key, value in self.params.task_probs:\n self.tasks.append(key)\n self._descriptors.append((value[1], 2 * value[0] - value[1]))\n\n\nclass RoundRobinScheduler(TaskScheduler):\n \"\"\"Deterministic sequential schedule.\"\"\"\n\n @classmethod\n def Params(cls):\n p = super(RoundRobinScheduler, cls).Params()\n p.Define('tasks', [], 'List of task names. No repetitions allowed.')\n return p\n\n @base_layer.initializer\n def __init__(self, params):\n super(RoundRobinScheduler, self).__init__(params)\n assert isinstance(self.params.tasks, list)\n self.tasks = sorted(self.params.tasks)\n self.n_tasks = len(self.tasks)\n self.cur_probs = [1. / self.n_tasks] * self.n_tasks # For summary\n\n def Sample(self, current_step):\n \"\"\"Sample a task.\"\"\"\n sampled_task = self.tasks[current_step % self.n_tasks]\n return sampled_task\n" ]
[ [ "tensorflow.convert_to_tensor", "tensorflow.variable_scope", "tensorflow.test.main", "tensorflow.get_collection" ], [ "tensorflow.test.main" ], [ "tensorflow.convert_to_tensor", "tensorflow.range", "tensorflow.shape", "tensorflow.reduce_sum", "tensorflow.cast", "tensorflow.squeeze", "tensorflow.py_func" ], [ "tensorflow.Graph", "tensorflow.Variable", "tensorflow.test.main", "tensorflow.global_variables_initializer", "tensorflow.train.Saver" ], [ "tensorflow.logging.warning", "numpy.random.choice", "tensorflow.gfile.GFile", "numpy.exp", "numpy.sum" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.10", "1.12", "1.4", "1.13", "1.5", "1.7", "0.12", "1.0", "1.2" ] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.10", "1.12", "1.4", "1.5", "1.7", "0.12", "1.0", "1.2" ] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.10" ] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.10" ] } ]
xunhen/Deep-Feature-Flow
[ "9fc6e755169bfad4e25553507bf2a98d6f3ee2e0" ]
[ "lib/bbox/bbox_regression.py" ]
[ "# --------------------------------------------------------\n# Deep Feature Flow\n# Copyright (c) 2017 Microsoft\n# Licensed under The MIT License [see LICENSE for details]\n# Modified by Yuwen Xiong\n# --------------------------------------------------------\n# Based on:\n# py-faster-rcnn\n# Copyright (c) 2016 by Contributors\n# Licence under The MIT License\n# https://github.com/rbgirshick/py-faster-rcnn\n# --------------------------------------------------------\n\n\"\"\"\nThis file has functions about generating bounding box regression targets\n\"\"\"\n\nimport numpy as np\n\nfrom lib.bbox.bbox_transform import bbox_overlaps, bbox_transform\n\n\ndef compute_bbox_regression_targets(rois, overlaps, labels, cfg):\n \"\"\"\n given rois, overlaps, gt labels, compute bounding box regression targets\n :param rois: roidb[i]['boxes'] k * 4\n :param overlaps: roidb[i]['max_overlaps'] k * 1\n :param labels: roidb[i]['max_classes'] k * 1\n :return: targets[i][class, dx, dy, dw, dh] k * 5\n \"\"\"\n # Ensure ROIs are floats\n rois = rois.astype(np.float, copy=False)\n\n # Sanity check\n if len(rois) != len(overlaps):\n print('bbox regression: this should not happen')\n\n # Indices of ground-truth ROIs\n gt_inds = np.where(overlaps == 1)[0]\n if len(gt_inds) == 0:\n print('something wrong : zero ground truth rois')\n # Indices of examples for which we try to make predictions\n ex_inds = np.where(overlaps >= cfg.TRAIN.BBOX_REGRESSION_THRESH)[0]\n\n # Get IoU overlap between each ex ROI and gt ROI\n ex_gt_overlaps = bbox_overlaps(rois[ex_inds, :], rois[gt_inds, :])\n\n # Find which gt ROI each ex ROI has max overlap with:\n # this will be the ex ROI's gt target\n gt_assignment = ex_gt_overlaps.argmax(axis=1)\n gt_rois = rois[gt_inds[gt_assignment], :]\n ex_rois = rois[ex_inds, :]\n\n targets = np.zeros((rois.shape[0], 5), dtype=np.float32)\n targets[ex_inds, 0] = labels[ex_inds]\n targets[ex_inds, 1:] = bbox_transform(ex_rois, gt_rois)\n return targets\n\n\ndef add_bbox_regression_targets(roidb, cfg):\n \"\"\"\n given roidb, add ['bbox_targets'] and normalize bounding box regression targets\n :param roidb: roidb to be processed. must have gone through imdb.prepare_roidb\n :return: means, std variances of targets\n \"\"\"\n print('add bounding box regression targets')\n assert len(roidb) > 0\n assert 'max_classes' in roidb[0]\n\n num_images = len(roidb)\n num_classes = 2 if cfg.CLASS_AGNOSTIC else roidb[0]['gt_overlaps'].shape[1]\n\n for im_i in range(num_images):\n rois = roidb[im_i]['boxes']\n max_overlaps = roidb[im_i]['max_overlaps']\n max_classes = roidb[im_i]['max_classes']\n roidb[im_i]['bbox_targets'] = compute_bbox_regression_targets(rois, max_overlaps, max_classes, cfg)\n\n if cfg.TRAIN.BBOX_NORMALIZATION_PRECOMPUTED:\n # use fixed / precomputed means and stds instead of empirical values\n means = np.tile(np.array(cfg.TRAIN.BBOX_MEANS), (num_classes, 1))\n stds = np.tile(np.array(cfg.TRAIN.BBOX_STDS), (num_classes, 1))\n else:\n # compute mean, std values\n class_counts = np.zeros((num_classes, 1)) + 1e-14\n sums = np.zeros((num_classes, 4))\n squared_sums = np.zeros((num_classes, 4))\n for im_i in range(num_images):\n targets = roidb[im_i]['bbox_targets']\n for cls in range(1, num_classes):\n cls_indexes = np.where(targets[:, 0] > 0)[0] if cfg.CLASS_AGNOSTIC else np.where(targets[:, 0] == cls)[0]\n if cls_indexes.size > 0:\n class_counts[cls] += cls_indexes.size\n sums[cls, :] += targets[cls_indexes, 1:].sum(axis=0)\n squared_sums[cls, :] += (targets[cls_indexes, 1:] ** 2).sum(axis=0)\n\n means = sums / class_counts\n # var(x) = E(x^2) - E(x)^2\n stds = np.sqrt(squared_sums / class_counts - means ** 2)\n\n print('bbox target means:')\n print(means)\n print(means[1:, :].mean(axis=0)) # ignore bg class\n print('bbox target stdevs:')\n print(stds)\n print(stds[1:, :].mean(axis=0)) # ignore bg class\n\n\n # normalized targets\n for im_i in range(num_images):\n targets = roidb[im_i]['bbox_targets']\n for cls in range(1, num_classes):\n cls_indexes = np.where(targets[:, 0] > 0) if cfg.CLASS_AGNOSTIC else np.where(targets[:, 0] == cls)[0]\n roidb[im_i]['bbox_targets'][cls_indexes, 1:] -= means[cls, :]\n roidb[im_i]['bbox_targets'][cls_indexes, 1:] /= stds[cls, :]\n\n return means.ravel(), stds.ravel()\n\n\ndef expand_bbox_regression_targets(bbox_targets_data, num_classes, cfg):\n \"\"\"\n expand from 5 to 4 * num_classes; only the right class has non-zero bbox regression targets\n :param bbox_targets_data: [k * 5]\n :param num_classes: number of classes\n :return: bbox target processed [k * 4 num_classes]\n bbox_weights ! only foreground boxes have bbox regression computation!\n \"\"\"\n classes = bbox_targets_data[:, 0]\n if cfg.CLASS_AGNOSTIC:\n num_classes = 2\n bbox_targets = np.zeros((classes.size, 4 * num_classes), dtype=np.float32)\n bbox_weights = np.zeros(bbox_targets.shape, dtype=np.float32)\n indexes = np.where(classes > 0)[0]\n for index in indexes:\n cls = classes[index]\n start = int(4 * 1 if cls > 0 else 0) if cfg.CLASS_AGNOSTIC else int(4 * cls)\n end = start + 4\n bbox_targets[index, start:end] = bbox_targets_data[index, 1:]\n bbox_weights[index, start:end] = cfg.TRAIN.BBOX_WEIGHTS\n return bbox_targets, bbox_weights\n\n" ]
[ [ "numpy.sqrt", "numpy.array", "numpy.zeros", "numpy.where" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
egoliuk/ml_course
[ "4327f43a95112b1cd5a17456eda567068e497963" ]
[ "Exercise_1/Logistic_regression_as_a_neural_network/logistic_regression_with_NN.py" ]
[ "\n# coding: utf-8\n\n# # Logistic Regression with a Neural Network mindset\n# \n# Welcome to your first (required) programming assignment! You will build a logistic regression classifier to recognize cats. This assignment will step you through how to do this with a Neural Network mindset, and so will also hone your intuitions about deep learning.\n# \n# **Instructions:**\n# - Do not use loops (for/while) in your code, unless the instructions explicitly ask you to do so.\n# \n# **You will learn to:**\n# - Build the general architecture of a learning algorithm, including:\n# - Initializing parameters\n# - Calculating the cost function and its gradient\n# - Using an optimization algorithm (gradient descent) \n# - Gather all three functions above into a main model function, in the right order.\n\n# ## 1 - Packages ##\n# \n# First, let's run the cell below to import all the packages that you will need during this assignment. \n# - [numpy](www.numpy.org) is the fundamental package for scientific computing with Python.\n# - [h5py](http://www.h5py.org) is a common package to interact with a dataset that is stored on an H5 file.\n# - [matplotlib](http://matplotlib.org) is a famous library to plot graphs in Python.\n# - [PIL](http://www.pythonware.com/products/pil/) and [scipy](https://www.scipy.org/) are used here to test your model with your own picture at the end.\n\n# In[ ]:\n\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport h5py\nimport scipy\nfrom PIL import Image\nfrom scipy import ndimage\nfrom lr_utils import load_dataset\n\nget_ipython().run_line_magic('matplotlib', 'inline')\n\n\n# ## 2 - Overview of the Problem set ##\n# \n# **Problem Statement**: You are given a dataset (\"data.h5\") containing:\n# - a training set of m_train images labeled as cat (y=1) or non-cat (y=0)\n# - a test set of m_test images labeled as cat or non-cat\n# - each image is of shape (num_px, num_px, 3) where 3 is for the 3 channels (RGB). Thus, each image is square (height = num_px) and (width = num_px).\n# \n# You will build a simple image-recognition algorithm that can correctly classify pictures as cat or non-cat.\n# \n# Let's get more familiar with the dataset. Load the data by running the following code.\n\n# In[ ]:\n\n\n# Loading the data (cat/non-cat)\ntrain_set_x_orig, train_set_y, test_set_x_orig, test_set_y, classes = load_dataset()\n\n\n# We added \"_orig\" at the end of image datasets (train and test) because we are going to preprocess them. After preprocessing, we will end up with train_set_x and test_set_x (the labels train_set_y and test_set_y don't need any preprocessing).\n# \n# Each line of your train_set_x_orig and test_set_x_orig is an array representing an image. You can visualize an example by running the following code. Feel free also to change the `index` value and re-run to see other images. \n\n# In[ ]:\n\n\n# Example of a picture\nindex = 25\nplt.imshow(train_set_x_orig[index])\nprint (\"y = \" + str(train_set_y[:, index]) + \", it's a '\" + classes[np.squeeze(train_set_y[:, index])].decode(\"utf-8\") + \"' picture.\")\n\n\n# Many software bugs in deep learning come from having matrix/vector dimensions that don't fit. If you can keep your matrix/vector dimensions straight you will go a long way toward eliminating many bugs. \n# \n# **Exercise:** Find the values for:\n# - m_train (number of training examples)\n# - m_test (number of test examples)\n# - num_px (= height = width of a training image)\n# Remember that `train_set_x_orig` is a numpy-array of shape (m_train, num_px, num_px, 3). For instance, you can access `m_train` by writing `train_set_x_orig.shape[0]`.\n\n# In[ ]:\n\n\n### START CODE HERE ### (≈ 3 lines of code)\nm_train = train_set_x_orig.shape[0]\nm_test = test_set_x_orig.shape[0]\nnum_px = train_set_x_orig.shape[1]\n### END CODE HERE ###\n\nprint (\"Number of training examples: m_train = \" + str(m_train))\nprint (\"Number of testing examples: m_test = \" + str(m_test))\nprint (\"Height/Width of each image: num_px = \" + str(num_px))\nprint (\"Each image is of size: (\" + str(num_px) + \", \" + str(num_px) + \", 3)\")\nprint (\"train_set_x shape: \" + str(train_set_x_orig.shape))\nprint (\"train_set_y shape: \" + str(train_set_y.shape))\nprint (\"test_set_x shape: \" + str(test_set_x_orig.shape))\nprint (\"test_set_y shape: \" + str(test_set_y.shape))\n\n\n# **Expected Output for m_train, m_test and num_px**: \n# <table style=\"width:15%\">\n# <tr>\n# <td>**m_train**</td>\n# <td> 209 </td> \n# </tr>\n# \n# <tr>\n# <td>**m_test**</td>\n# <td> 50 </td> \n# </tr>\n# \n# <tr>\n# <td>**num_px**</td>\n# <td> 64 </td> \n# </tr>\n# \n# </table>\n# \n\n# For convenience, you should now reshape images of shape (num_px, num_px, 3) in a numpy-array of shape (num_px $*$ num_px $*$ 3, 1). After this, our training (and test) dataset is a numpy-array where each column represents a flattened image. There should be m_train (respectively m_test) columns.\n# \n# **Exercise:** Reshape the training and test data sets so that images of size (num_px, num_px, 3) are flattened into single vectors of shape (num\\_px $*$ num\\_px $*$ 3, 1).\n# \n# A trick when you want to flatten a matrix X of shape (a,b,c,d) to a matrix X_flatten of shape (b$*$c$*$d, a) is to use: \n# ```python\n# X_flatten = X.reshape(X.shape[0], -1).T # X.T is the transpose of X\n# ```\n\n# In[ ]:\n\n\n# Reshape the training and test examples\n\n### START CODE HERE ### (≈ 2 lines of code)\ntrain_set_x_flatten = train_set_x_orig.reshape(train_set_x_orig.shape[0], -1).T\n# train_set_x_flatten = train_set_x_orig.reshape(train_set_x_orig.shape[0], (train_set_x_orig.shape[1]*train_set_x_orig.shape[2]*train_set_x_orig.shape[3])).T\ntest_set_x_flatten = test_set_x_orig.reshape(test_set_x_orig.shape[0], -1).T\n# test_set_x_flatten = test_set_x_orig.reshape(test_set_x_orig.shape[0], (test_set_x_orig.shape[1]*test_set_x_orig.shape[2]*test_set_x_orig.shape[3])).T\n### END CODE HERE ###\n\nprint (\"train_set_x_flatten shape: \" + str(train_set_x_flatten.shape))\nprint (\"train_set_y shape: \" + str(train_set_y.shape))\nprint (\"test_set_x_flatten shape: \" + str(test_set_x_flatten.shape))\nprint (\"test_set_y shape: \" + str(test_set_y.shape))\nprint (\"sanity check after reshaping: \" + str(train_set_x_flatten[0:5,0]))\n\n\n# **Expected Output**: \n# \n# <table style=\"width:35%\">\n# <tr>\n# <td>**train_set_x_flatten shape**</td>\n# <td> (12288, 209)</td> \n# </tr>\n# <tr>\n# <td>**train_set_y shape**</td>\n# <td>(1, 209)</td> \n# </tr>\n# <tr>\n# <td>**test_set_x_flatten shape**</td>\n# <td>(12288, 50)</td> \n# </tr>\n# <tr>\n# <td>**test_set_y shape**</td>\n# <td>(1, 50)</td> \n# </tr>\n# <tr>\n# <td>**sanity check after reshaping**</td>\n# <td>[17 31 56 22 33]</td> \n# </tr>\n# </table>\n\n# To represent color images, the red, green and blue channels (RGB) must be specified for each pixel, and so the pixel value is actually a vector of three numbers ranging from 0 to 255.\n# \n# One common preprocessing step in machine learning is to center and standardize your dataset, meaning that you substract the mean of the whole numpy array from each example, and then divide each example by the standard deviation of the whole numpy array. But for picture datasets, it is simpler and more convenient and works almost as well to just divide every row of the dataset by 255 (the maximum value of a pixel channel).\n# \n# <!-- During the training of your model, you're going to multiply weights and add biases to some initial inputs in order to observe neuron activations. Then you backpropogate with the gradients to train the model. But, it is extremely important for each feature to have a similar range such that our gradients don't explode. You will see that more in detail later in the lectures. !--> \n# \n# Let's standardize our dataset.\n\n# In[ ]:\n\n\ntrain_set_x = train_set_x_flatten/255.\ntest_set_x = test_set_x_flatten/255.\n\n\n# <font color='blue'>\n# **What you need to remember:**\n# \n# Common steps for pre-processing a new dataset are:\n# - Figure out the dimensions and shapes of the problem (m_train, m_test, num_px, ...)\n# - Reshape the datasets such that each example is now a vector of size (num_px \\* num_px \\* 3, 1)\n# - \"Standardize\" the data\n\n# ## 3 - General Architecture of the learning algorithm ##\n# \n# It's time to design a simple algorithm to distinguish cat images from non-cat images.\n# \n# You will build a Logistic Regression, using a Neural Network mindset. The following Figure explains why **Logistic Regression is actually a very simple Neural Network!**\n# \n# <img src=\"images/LogReg_kiank.png\" style=\"width:650px;height:400px;\">\n# \n# **Mathematical expression of the algorithm**:\n# \n# For one example $x^{(i)}$:\n# $$z^{(i)} = w^T x^{(i)} + b \\tag{1}$$\n# $$\\hat{y}^{(i)} = a^{(i)} = sigmoid(z^{(i)})\\tag{2}$$ \n# $$ \\mathcal{L}(a^{(i)}, y^{(i)}) = - y^{(i)} \\log(a^{(i)}) - (1-y^{(i)} ) \\log(1-a^{(i)})\\tag{3}$$\n# \n# The cost is then computed by summing over all training examples:\n# $$ J = \\frac{1}{m} \\sum_{i=1}^m \\mathcal{L}(a^{(i)}, y^{(i)})\\tag{6}$$\n# \n# **Key steps**:\n# In this exercise, you will carry out the following steps: \n# - Initialize the parameters of the model\n# - Learn the parameters for the model by minimizing the cost \n# - Use the learned parameters to make predictions (on the test set)\n# - Analyse the results and conclude\n\n# ## 4 - Building the parts of our algorithm ## \n# \n# The main steps for building a Neural Network are:\n# 1. Define the model structure (such as number of input features) \n# 2. Initialize the model's parameters\n# 3. Loop:\n# - Calculate current loss (forward propagation)\n# - Calculate current gradient (backward propagation)\n# - Update parameters (gradient descent)\n# \n# You often build 1-3 separately and integrate them into one function we call `model()`.\n# \n# ### 4.1 - Helper functions\n# \n# **Exercise**: Using your code from \"Python Basics\", implement `sigmoid()`. As you've seen in the figure above, you need to compute $sigmoid( w^T x + b) = \\frac{1}{1 + e^{-(w^T x + b)}}$ to make predictions. Use np.exp().\n\n# In[ ]:\n\n\n# GRADED FUNCTION: sigmoid\n\ndef sigmoid(z):\n \"\"\"\n Compute the sigmoid of z\n\n Arguments:\n z -- A scalar or numpy array of any size.\n\n Return:\n s -- sigmoid(z)\n \"\"\"\n\n ### START CODE HERE ### (≈ 1 line of code)\n s = 1 / (1 + np.exp(-z))\n ### END CODE HERE ###\n \n return s\n\n\n# In[ ]:\n\n\nprint (\"sigmoid([0, 2]) = \" + str(sigmoid(np.array([0,2]))))\n\n\n# **Expected Output**: \n# \n# <table>\n# <tr>\n# <td>**sigmoid([0, 2])**</td>\n# <td> [ 0.5 0.88079708]</td> \n# </tr>\n# </table>\n\n# ### 4.2 - Initializing parameters\n# \n# **Exercise:** Implement parameter initialization in the cell below. You have to initialize w as a vector of zeros. If you don't know what numpy function to use, look up np.zeros() in the Numpy library's documentation.\n\n# In[ ]:\n\n\n# GRADED FUNCTION: initialize_with_zeros\n\ndef initialize_with_zeros(dim):\n \"\"\"\n This function creates a vector of zeros of shape (dim, 1) for w and initializes b to 0.\n \n Argument:\n dim -- size of the w vector we want (or number of parameters in this case)\n \n Returns:\n w -- initialized vector of shape (dim, 1)\n b -- initialized scalar (corresponds to the bias)\n \"\"\"\n \n ### START CODE HERE ### (≈ 1 line of code)\n w = np.zeros((dim, 1))\n b = 0\n ### END CODE HERE ###\n\n assert(w.shape == (dim, 1))\n assert(isinstance(b, float) or isinstance(b, int))\n \n return w, b\n\n\n# In[ ]:\n\n\ndim = 2\nw, b = initialize_with_zeros(dim)\nprint (\"w = \" + str(w))\nprint (\"b = \" + str(b))\n\n\n# **Expected Output**: \n# \n# \n# <table style=\"width:15%\">\n# <tr>\n# <td> ** w ** </td>\n# <td> [[ 0.]\n# [ 0.]] </td>\n# </tr>\n# <tr>\n# <td> ** b ** </td>\n# <td> 0 </td>\n# </tr>\n# </table>\n# \n# For image inputs, w will be of shape (num_px $\\times$ num_px $\\times$ 3, 1).\n\n# ### 4.3 - Forward and Backward propagation\n# \n# Now that your parameters are initialized, you can do the \"forward\" and \"backward\" propagation steps for learning the parameters.\n# \n# **Exercise:** Implement a function `propagate()` that computes the cost function and its gradient.\n# \n# **Hints**:\n# \n# Forward Propagation:\n# - You get X\n# - You compute $A = \\sigma(w^T X + b) = (a^{(1)}, a^{(2)}, ..., a^{(m-1)}, a^{(m)})$\n# - You calculate the cost function: $J = -\\frac{1}{m}\\sum_{i=1}^{m}y^{(i)}\\log(a^{(i)})+(1-y^{(i)})\\log(1-a^{(i)})$\n# \n# Here are the two formulas you will be using: \n# \n# $$ \\frac{\\partial J}{\\partial w} = \\frac{1}{m}X(A-Y)^T\\tag{7}$$\n# $$ \\frac{\\partial J}{\\partial b} = \\frac{1}{m} \\sum_{i=1}^m (a^{(i)}-y^{(i)})\\tag{8}$$\n\n# In[ ]:\n\n\n# GRADED FUNCTION: propagate\n\ndef propagate(w, b, X, Y):\n \"\"\"\n Implement the cost function and its gradient for the propagation explained above\n\n Arguments:\n w -- weights, a numpy array of size (num_px * num_px * 3, 1)\n b -- bias, a scalar\n X -- data of size (num_px * num_px * 3, number of examples)\n Y -- true \"label\" vector (containing 0 if non-cat, 1 if cat) of size (1, number of examples)\n\n Return:\n cost -- negative log-likelihood cost for logistic regression\n dw -- gradient of the loss with respect to w, thus same shape as w\n db -- gradient of the loss with respect to b, thus same shape as b\n \n Tips:\n - Write your code step by step for the propagation. np.log(), np.dot()\n \"\"\"\n \n m = X.shape[1]\n \n # FORWARD PROPAGATION (FROM X TO COST)\n ### START CODE HERE ### (≈ 2 lines of code)\n A = sigmoid(np.dot(w.T, X) + b) # compute activation\n cost = (-1/m) * np.sum(Y * np.log(A) + (1-Y) * np.log(1-A)) # compute cost\n ### END CODE HERE ###\n \n # BACKWARD PROPAGATION (TO FIND GRAD)\n ### START CODE HERE ### (≈ 2 lines of code)\n dw = (1/m) * np.dot(X, (A-Y).T)\n db = (1/m) * np.sum(A-Y)\n ### END CODE HERE ###\n\n assert(dw.shape == w.shape)\n assert(db.dtype == float)\n cost = np.squeeze(cost)\n assert(cost.shape == ())\n \n grads = {\"dw\": dw,\n \"db\": db}\n \n return grads, cost\n\n\n# In[ ]:\n\n\nw, b, X, Y = np.array([[1.],[2.]]), 2., np.array([[1.,2.,-1.],[3.,4.,-3.2]]), np.array([[1,0,1]])\ngrads, cost = propagate(w, b, X, Y)\nprint (\"dw = \" + str(grads[\"dw\"]))\nprint (\"db = \" + str(grads[\"db\"]))\nprint (\"cost = \" + str(cost))\n\n\n# **Expected Output**:\n# \n# <table style=\"width:50%\">\n# <tr>\n# <td> ** dw ** </td>\n# <td> [[ 0.99845601]\n# [ 2.39507239]]</td>\n# </tr>\n# <tr>\n# <td> ** db ** </td>\n# <td> 0.00145557813678 </td>\n# </tr>\n# <tr>\n# <td> ** cost ** </td>\n# <td> 5.801545319394553 </td>\n# </tr>\n# \n# </table>\n\n# ### 4.4 - Optimization\n# - You have initialized your parameters.\n# - You are also able to compute a cost function and its gradient.\n# - Now, you want to update the parameters using gradient descent.\n# \n# **Exercise:** Write down the optimization function. The goal is to learn $w$ and $b$ by minimizing the cost function $J$. For a parameter $\\theta$, the update rule is $ \\theta = \\theta - \\alpha \\text{ } d\\theta$, where $\\alpha$ is the learning rate.\n\n# In[ ]:\n\n\n# GRADED FUNCTION: optimize\n\ndef optimize(w, b, X, Y, num_iterations, learning_rate, print_cost = False):\n \"\"\"\n This function optimizes w and b by running a gradient descent algorithm\n \n Arguments:\n w -- weights, a numpy array of size (num_px * num_px * 3, 1)\n b -- bias, a scalar\n X -- data of shape (num_px * num_px * 3, number of examples)\n Y -- true \"label\" vector (containing 0 if non-cat, 1 if cat), of shape (1, number of examples)\n num_iterations -- number of iterations of the optimization loop\n learning_rate -- learning rate of the gradient descent update rule\n print_cost -- True to print the loss every 100 steps\n \n Returns:\n params -- dictionary containing the weights w and bias b\n grads -- dictionary containing the gradients of the weights and bias with respect to the cost function\n costs -- list of all the costs computed during the optimization, this will be used to plot the learning curve.\n \n Tips:\n You basically need to write down two steps and iterate through them:\n 1) Calculate the cost and the gradient for the current parameters. Use propagate().\n 2) Update the parameters using gradient descent rule for w and b.\n \"\"\"\n \n costs = []\n \n for i in range(num_iterations):\n \n \n # Cost and gradient calculation (≈ 1-4 lines of code)\n ### START CODE HERE ### \n grads, cost = propagate(w, b, X, Y)\n ### END CODE HERE ###\n \n # Retrieve derivatives from grads\n dw = grads[\"dw\"]\n db = grads[\"db\"]\n \n # update rule (≈ 2 lines of code)\n ### START CODE HERE ###\n w = w - learning_rate * dw\n b = b - learning_rate * db\n ### END CODE HERE ###\n \n # Record the costs\n if i % 100 == 0:\n costs.append(cost)\n \n # Print the cost every 100 training iterations\n if print_cost and i % 100 == 0:\n print (\"Cost after iteration %i: %f\" %(i, cost))\n \n params = {\"w\": w,\n \"b\": b}\n \n grads = {\"dw\": dw,\n \"db\": db}\n \n return params, grads, costs\n\n\n# In[ ]:\n\n\nparams, grads, costs = optimize(w, b, X, Y, num_iterations= 100, learning_rate = 0.009, print_cost = False)\n\nprint (\"w = \" + str(params[\"w\"]))\nprint (\"b = \" + str(params[\"b\"]))\nprint (\"dw = \" + str(grads[\"dw\"]))\nprint (\"db = \" + str(grads[\"db\"]))\n\n\n# **Expected Output**: \n# \n# <table style=\"width:40%\">\n# <tr>\n# <td> **w** </td>\n# <td>[[ 0.19033591]\n# [ 0.12259159]] </td>\n# </tr>\n# \n# <tr>\n# <td> **b** </td>\n# <td> 1.92535983008 </td>\n# </tr>\n# <tr>\n# <td> **dw** </td>\n# <td> [[ 0.67752042]\n# [ 1.41625495]] </td>\n# </tr>\n# <tr>\n# <td> **db** </td>\n# <td> 0.219194504541 </td>\n# </tr>\n# \n# </table>\n\n# **Exercise:** The previous function will output the learned w and b. We are able to use w and b to predict the labels for a dataset X. Implement the `predict()` function. There are two steps to computing predictions:\n# \n# 1. Calculate $\\hat{Y} = A = \\sigma(w^T X + b)$\n# \n# 2. Convert the entries of a into 0 (if activation <= 0.5) or 1 (if activation > 0.5), stores the predictions in a vector `Y_prediction`. If you wish, you can use an `if`/`else` statement in a `for` loop (though there is also a way to vectorize this). \n\n# In[ ]:\n\n\n# GRADED FUNCTION: predict\n\ndef predict(w, b, X):\n '''\n Predict whether the label is 0 or 1 using learned logistic regression parameters (w, b)\n \n Arguments:\n w -- weights, a numpy array of size (num_px * num_px * 3, 1)\n b -- bias, a scalar\n X -- data of size (num_px * num_px * 3, number of examples)\n \n Returns:\n Y_prediction -- a numpy array (vector) containing all predictions (0/1) for the examples in X\n '''\n \n m = X.shape[1]\n Y_prediction = np.zeros((1,m))\n w = w.reshape(X.shape[0], 1)\n \n # Compute vector \"A\" predicting the probabilities of a cat being present in the picture\n ### START CODE HERE ### (≈ 1 line of code)\n A = sigmoid(np.dot(w.T, X) + b)\n ### END CODE HERE ###\n\n # for i in range(A.shape[1]):\n \n # Convert probabilities A[0,i] to actual predictions p[0,i]\n ### START CODE HERE ### (≈ 4 lines of code)\n # Y_prediction[0, i] = 1 if A[0, i] > .5 else 0\n ### END CODE HERE ###\n\n # There is a way to vectorize this and avoid using loop\n Y_prediction = np.where(A > .5, 1, 0)\n\n assert(Y_prediction.shape == (1, m))\n \n return Y_prediction\n\n\n# In[ ]:\n\n\nw = np.array([[0.1124579],[0.23106775]])\nb = -0.3\nX = np.array([[1.,-1.1,-3.2],[1.2,2.,0.1]])\nprint (\"predictions = \" + str(predict(w, b, X)))\n\n\n# **Expected Output**: \n# \n# <table style=\"width:30%\">\n# <tr>\n# <td>\n# **predictions**\n# </td>\n# <td>\n# [[ 1. 1. 0.]]\n# </td> \n# </tr>\n# \n# </table>\n# \n\n# <font color='blue'>\n# **What to remember:**\n# You've implemented several functions that:\n# - Initialize (w,b)\n# - Optimize the loss iteratively to learn parameters (w,b):\n# - computing the cost and its gradient \n# - updating the parameters using gradient descent\n# - Use the learned (w,b) to predict the labels for a given set of examples\n\n# ## 5 - Merge all functions into a model ##\n# \n# You will now see how the overall model is structured by putting together all the building blocks (functions implemented in the previous parts) together, in the right order.\n# \n# **Exercise:** Implement the model function. Use the following notation:\n# - Y_prediction_test for your predictions on the test set\n# - Y_prediction_train for your predictions on the train set\n# - w, costs, grads for the outputs of optimize()\n\n# In[ ]:\n\n\n# GRADED FUNCTION: model\n\ndef model(X_train, Y_train, X_test, Y_test, num_iterations = 2000, learning_rate = 0.5, print_cost = False):\n \"\"\"\n Builds the logistic regression model by calling the function you've implemented previously\n \n Arguments:\n X_train -- training set represented by a numpy array of shape (num_px * num_px * 3, m_train)\n Y_train -- training labels represented by a numpy array (vector) of shape (1, m_train)\n X_test -- test set represented by a numpy array of shape (num_px * num_px * 3, m_test)\n Y_test -- test labels represented by a numpy array (vector) of shape (1, m_test)\n num_iterations -- hyperparameter representing the number of iterations to optimize the parameters\n learning_rate -- hyperparameter representing the learning rate used in the update rule of optimize()\n print_cost -- Set to true to print the cost every 100 iterations\n \n Returns:\n d -- dictionary containing information about the model.\n \"\"\"\n \n ### START CODE HERE ###\n \n # initialize parameters with zeros (≈ 1 line of code)\n w, b = initialize_with_zeros(X_train.shape[0])\n\n # Gradient descent (≈ 1 line of code)\n parameters, grads, costs = optimize(w, b, X_train, Y_train, num_iterations, learning_rate, print_cost)\n \n # Retrieve parameters w and b from dictionary \"parameters\"\n w = parameters[\"w\"]\n b = parameters[\"b\"]\n \n # Predict test/train set examples (≈ 2 lines of code)\n Y_prediction_test = predict(w, b, X_test)\n Y_prediction_train = predict(w, b, X_train)\n\n ### END CODE HERE ###\n\n # Print train/test Errors\n print(\"train accuracy: {} %\".format(100 - np.mean(np.abs(Y_prediction_train - Y_train)) * 100))\n print(\"test accuracy: {} %\".format(100 - np.mean(np.abs(Y_prediction_test - Y_test)) * 100))\n\n \n d = {\"costs\": costs,\n \"Y_prediction_test\": Y_prediction_test, \n \"Y_prediction_train\" : Y_prediction_train, \n \"w\" : w, \n \"b\" : b,\n \"learning_rate\" : learning_rate,\n \"num_iterations\": num_iterations}\n \n return d\n\n\n# Run the following cell to train your model.\n\n# In[ ]:\n\n\nd = model(train_set_x, train_set_y, test_set_x, test_set_y, num_iterations = 2000, learning_rate = 0.005, print_cost = True)\n\n\n# **Expected Output**: \n# \n# <table style=\"width:40%\"> \n# \n# <tr>\n# <td> **Cost after iteration 0 ** </td> \n# <td> 0.693147 </td>\n# </tr>\n# <tr>\n# <td> <center> $\\vdots$ </center> </td> \n# <td> <center> $\\vdots$ </center> </td> \n# </tr> \n# <tr>\n# <td> **Train Accuracy** </td> \n# <td> 99.04306220095694 % </td>\n# </tr>\n# \n# <tr>\n# <td>**Test Accuracy** </td> \n# <td> 70.0 % </td>\n# </tr>\n# </table> \n# \n# \n# \n\n# **Comment**: Training accuracy is close to 100%. This is a good sanity check: your model is working and has high enough capacity to fit the training data. Test error is 68%. It is actually not bad for this simple model, given the small dataset we used and that logistic regression is a linear classifier. But no worries, you'll build an even better classifier next week!\n# \n# Also, you see that the model is clearly overfitting the training data. Later in this specialization you will learn how to reduce overfitting, for example by using regularization. Using the code below (and changing the `index` variable) you can look at predictions on pictures of the test set.\n\n# In[ ]:\n\n\n# Example of a picture that was wrongly classified.\nindex = 1\nplt.imshow(test_set_x[:,index].reshape((num_px, num_px, 3)))\nprint (\"y = \" + str(test_set_y[0,index]) + \", you predicted that it is a \\\"\" + classes[d[\"Y_prediction_test\"][0,index]].decode(\"utf-8\") + \"\\\" picture.\")\n\n\n# Let's also plot the cost function and the gradients.\n\n# In[ ]:\n\n\n# Plot learning curve (with costs)\ncosts = np.squeeze(d['costs'])\nplt.plot(costs)\nplt.ylabel('cost')\nplt.xlabel('iterations (per hundreds)')\nplt.title(\"Learning rate =\" + str(d[\"learning_rate\"]))\nplt.show()\n\n\n# **Interpretation**:\n# You can see the cost decreasing. It shows that the parameters are being learned. However, you see that you could train the model even more on the training set. Try to increase the number of iterations in the cell above and rerun the cells. You might see that the training set accuracy goes up, but the test set accuracy goes down. This is called overfitting. \n\n# ## 6 - Further analysis (optional/ungraded exercise) ##\n# \n# Congratulations on building your first image classification model. Let's analyze it further, and examine possible choices for the learning rate $\\alpha$. \n\n# #### Choice of learning rate ####\n# \n# **Reminder**:\n# In order for Gradient Descent to work you must choose the learning rate wisely. The learning rate $\\alpha$ determines how rapidly we update the parameters. If the learning rate is too large we may \"overshoot\" the optimal value. Similarly, if it is too small we will need too many iterations to converge to the best values. That's why it is crucial to use a well-tuned learning rate.\n# \n# Let's compare the learning curve of our model with several choices of learning rates. Run the cell below. This should take about 1 minute. Feel free also to try different values than the three we have initialized the `learning_rates` variable to contain, and see what happens. \n\n# In[ ]:\n\n\nlearning_rates = [0.01, 0.001, 0.0001]\nmodels = {}\nfor i in learning_rates:\n print (\"learning rate is: \" + str(i))\n models[str(i)] = model(train_set_x, train_set_y, test_set_x, test_set_y, num_iterations = 1500, learning_rate = i, print_cost = False)\n print ('\\n' + \"-------------------------------------------------------\" + '\\n')\n\nfor i in learning_rates:\n plt.plot(np.squeeze(models[str(i)][\"costs\"]), label= str(models[str(i)][\"learning_rate\"]))\n\nplt.ylabel('cost')\nplt.xlabel('iterations (hundreds)')\n\nlegend = plt.legend(loc='upper center', shadow=True)\nframe = legend.get_frame()\nframe.set_facecolor('0.90')\nplt.show()\n\n\n# **Interpretation**: \n# - Different learning rates give different costs and thus different predictions results.\n# - If the learning rate is too large (0.01), the cost may oscillate up and down. It may even diverge (though in this example, using 0.01 still eventually ends up at a good value for the cost). \n# - A lower cost doesn't mean a better model. You have to check if there is possibly overfitting. It happens when the training accuracy is a lot higher than the test accuracy.\n# - In deep learning, we usually recommend that you: \n# - Choose the learning rate that better minimizes the cost function.\n# - If your model overfits, use other techniques to reduce overfitting. (We'll talk about this in later videos.) \n# \n\n# ## 7 - Test with your own image (optional/ungraded exercise) ##\n# \n# Congratulations on finishing this assignment. You can use your own image and see the output of your model. To do that:\n# 1. Click on \"File\" in the upper bar of this notebook, then click \"Open\" to go on your Coursera Hub.\n# 2. Add your image to this Jupyter Notebook's directory, in the \"images\" folder\n# 3. Change your image's name in the following code\n# 4. Run the code and check if the algorithm is right (1 = cat, 0 = non-cat)!\n\n# In[ ]:\n\n\n## START CODE HERE ## (PUT YOUR IMAGE NAME) \nmy_image = \"space_cat.jpg\" # change this to the name of your image file\n## END CODE HERE ##\n\n# We preprocess the image to fit your algorithm.\nfname = \"images/\" + my_image\nimage = np.array(ndimage.imread(fname, flatten=False))\nmy_image = scipy.misc.imresize(image, size=(num_px,num_px)).reshape((1, num_px*num_px*3)).T\nmy_predicted_image = predict(d[\"w\"], d[\"b\"], my_image)\n\nplt.imshow(image)\nprint(\"y = \" + str(np.squeeze(my_predicted_image)) + \", your algorithm predicts a \\\"\" + classes[int(np.squeeze(my_predicted_image)),].decode(\"utf-8\") + \"\\\" picture.\")\n\n\n# <font color='blue'>\n# **What to remember from this assignment:**\n# 1. Preprocessing the dataset is important.\n# 2. You implemented each function separately: initialize(), propagate(), optimize(). Then you built a model().\n# 3. Tuning the learning rate (which is an example of a \"hyperparameter\") can make a big difference to the algorithm. You will see more examples of this later in this course!\n\n# Finally, if you'd like, we invite you to try different things on this Notebook. Make sure you submit before trying anything. Once you submit, things you can play with include:\n# - Play with the learning rate and the number of iterations\n# - Try different initialization methods and compare the results\n# - Test other preprocessings (center the data, or divide each row by its standard deviation)\n\n# Bibliography:\n# - http://www.wildml.com/2015/09/implementing-a-neural-network-from-scratch/\n# - https://stats.stackexchange.com/questions/211436/why-do-we-normalize-images-by-subtracting-the-datasets-image-mean-and-not-the-c\n" ]
[ [ "matplotlib.pyplot.legend", "matplotlib.pyplot.imshow", "numpy.dot", "numpy.sum", "scipy.ndimage.imread", "scipy.misc.imresize", "numpy.log", "numpy.abs", "numpy.squeeze", "matplotlib.pyplot.plot", "numpy.exp", "matplotlib.pyplot.xlabel", "numpy.array", "numpy.zeros", "numpy.where", "matplotlib.pyplot.show", "matplotlib.pyplot.ylabel" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [ "0.13", "0.14", "0.15", "0.10", "0.16", "0.19", "0.18", "0.12", "1.0", "0.17", "1.2" ], "tensorflow": [] } ]
xiaqi516/video-content-description-VCD
[ "d442d6a7c4d6d8807de2177054e9d82e52005221" ]
[ "draw/vcd_draw_towncentre.py" ]
[ "\"\"\"\nVCD (Video Content Description) library v4.3.1\n\nProject website: http://vcd.vicomtech.org\n\nCopyright (C) 2021, Vicomtech (http://www.vicomtech.es/),\n(Spain) all rights reserved.\n\nVCD is a Python library to create and manage VCD content version 4.3.1.\nVCD is distributed under MIT License. See LICENSE.\n\n\"\"\"\n\n\nimport sys\nsys.path.insert(0, \"..\")\nimport screeninfo\nimport cv2 as cv\nimport numpy as np\nimport math\nfrom vcd import core\nfrom vcd import draw\nfrom vcd import scl\n\ndef draw_towncentre(record_video=False):\n # Get annotations\n # Run ../converters/towncenterConverter/converter.py to generate the json files\n vcd_file_name = \"../converters/towncenterConverter/etc/vcd430_towncenter.json\"\n vcd = core.VCD(vcd_file_name)\n scene = scl.Scene(vcd)\n\n drawerCamera = draw.Image(scene)\n #textDrawer = draw.TextDrawer()\n frameInfoDrawer = draw.FrameInfoDrawer(vcd)\n\n # Get the size of the screen\n screen = screeninfo.get_monitors()[0]\n\n # Get video\n video_file_name = \"../../../../data/TownCentre/TownCentreXVID.avi\"\n video_cap = cv.VideoCapture(video_file_name)\n video_width = int(video_cap.get(cv.CAP_PROP_FRAME_WIDTH))\n video_height = int(video_cap.get(cv.CAP_PROP_FRAME_HEIGHT))\n\n cv.namedWindow('TownCentre', cv.WINDOW_NORMAL)\n cv.moveWindow('TownCentre', screen.x + screen.width // 8, screen.y + screen.height // 8)\n cv.resizeWindow('TownCentre', (int(3 * screen.width / 4), int(3 * screen.height / 4)))\n\n # Prepare color map\n colorMap = {'Car': (0, 0, 255), 'Van': (255, 0, 0), 'Truck': (127, 127, 0),\n 'Pedestrian': (0, 255, 0), 'Person_sitting': (0, 127, 127),\n 'Tram': (127, 0, 127), 'Misc': (127, 127, 127), 'DontCare': (255, 255, 255)}\n imageParams = draw.Image.Params(_colorMap=colorMap,\n _draw_trajectory=True)\n ar = video_width/(video_height*2)\n\n # Video record\n if record_video:\n video_writer = cv.VideoWriter(\"towncentre_vcd.mp4\",\n cv.VideoWriter_fourcc(*'mp4v'), 30.0, (video_width + 400, video_height*3))\n\n # Loop over video\n f = 0\n while True:\n # Capture frame\n ret, img = video_cap.read()\n if ret is not True:\n break\n\n # Camera\n drawerCamera.draw(img, f, _params=imageParams)\n\n # VCD text viewer\n #textImg = textDrawer.draw(vcd.stringify_frame(f, pretty=False), cols=400, rows=video_height)\n textImg = frameInfoDrawer.draw(f, cols=400, rows=video_height, _params=imageParams)\n\n\n # Stack\n outImg = np.hstack((img, textImg))\n cv.imshow('TownCentre', outImg)\n cv.waitKey(1)\n\n if record_video:\n video_writer.write(outImg)\n\n # Update frame num\n f += 1\n\n video_cap.release()\n if record_video:\n video_writer.release()\n cv.destroyAllWindows()\n\n\nif __name__ == \"__main__\":\n draw_towncentre(record_video=False)\n\n\n" ]
[ [ "numpy.hstack" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
mythezone/ECOS
[ "339c9a5dcd5d05dacd21bc3646af35585b926e35" ]
[ "Algorithms/lstm/lstm.py" ]
[ "import random\nfrom time import sleep\n\nimport numpy as np\nimport math\n\ndef sigmoid(x): \n return 1. / (1 + np.exp(-x))\n\ndef sigmoid_derivative(values): \n return values*(1-values)\n\ndef tanh_derivative(values): \n return 1. - values ** 2\n\n# createst uniform random array w/ values in [a,b) and shape args\ndef rand_arr(a, b, *args): \n np.random.seed(0)\n return np.random.rand(*args) * (b - a) + a\n\nclass LstmParam:\n def __init__(self, mem_cell_ct, x_dim):\n self.mem_cell_ct = mem_cell_ct\n self.x_dim = x_dim\n concat_len = x_dim + mem_cell_ct\n # weight matrices\n self.wg = rand_arr(-0.1, 0.1, mem_cell_ct, concat_len)\n self.wi = rand_arr(-0.1, 0.1, mem_cell_ct, concat_len) \n self.wf = rand_arr(-0.1, 0.1, mem_cell_ct, concat_len)\n self.wo = rand_arr(-0.1, 0.1, mem_cell_ct, concat_len)\n # bias terms\n self.bg = rand_arr(-0.1, 0.1, mem_cell_ct) \n self.bi = rand_arr(-0.1, 0.1, mem_cell_ct) \n self.bf = rand_arr(-0.1, 0.1, mem_cell_ct) \n self.bo = rand_arr(-0.1, 0.1, mem_cell_ct) \n # diffs (derivative of loss function w.r.t. all parameters)\n self.wg_diff = np.zeros((mem_cell_ct, concat_len)) \n self.wi_diff = np.zeros((mem_cell_ct, concat_len)) \n self.wf_diff = np.zeros((mem_cell_ct, concat_len)) \n self.wo_diff = np.zeros((mem_cell_ct, concat_len)) \n self.bg_diff = np.zeros(mem_cell_ct) \n self.bi_diff = np.zeros(mem_cell_ct) \n self.bf_diff = np.zeros(mem_cell_ct) \n self.bo_diff = np.zeros(mem_cell_ct) \n\n def apply_diff(self, lr = 1):\n self.wg -= lr * self.wg_diff\n self.wi -= lr * self.wi_diff\n self.wf -= lr * self.wf_diff\n self.wo -= lr * self.wo_diff\n self.bg -= lr * self.bg_diff\n self.bi -= lr * self.bi_diff\n self.bf -= lr * self.bf_diff\n self.bo -= lr * self.bo_diff\n # reset diffs to zero\n self.wg_diff = np.zeros_like(self.wg)\n self.wi_diff = np.zeros_like(self.wi) \n self.wf_diff = np.zeros_like(self.wf) \n self.wo_diff = np.zeros_like(self.wo) \n self.bg_diff = np.zeros_like(self.bg)\n self.bi_diff = np.zeros_like(self.bi) \n self.bf_diff = np.zeros_like(self.bf) \n self.bo_diff = np.zeros_like(self.bo) \n\nclass LstmState:\n def __init__(self, mem_cell_ct, x_dim):\n self.g = np.zeros(mem_cell_ct)\n self.i = np.zeros(mem_cell_ct)\n self.f = np.zeros(mem_cell_ct)\n self.o = np.zeros(mem_cell_ct)\n self.s = np.zeros(mem_cell_ct)\n self.h = np.zeros(mem_cell_ct)\n self.bottom_diff_h = np.zeros_like(self.h)\n self.bottom_diff_s = np.zeros_like(self.s)\n \nclass LstmNode:\n def __init__(self, lstm_param, lstm_state):\n # store reference to parameters and to activations\n self.state = lstm_state\n self.param = lstm_param\n # non-recurrent input concatenated with recurrent input\n self.xc = None\n\n def bottom_data_is(self, x, s_prev = None, h_prev = None):\n # if this is the first lstm node in the network\n if s_prev is None: s_prev = np.zeros_like(self.state.s)\n if h_prev is None: h_prev = np.zeros_like(self.state.h)\n # save data for use in backprop\n self.s_prev = s_prev\n self.h_prev = h_prev\n\n # concatenate x(t) and h(t-1)\n xc = np.hstack((x, h_prev))\n self.state.g = np.tanh(np.dot(self.param.wg, xc) + self.param.bg)\n self.state.i = sigmoid(np.dot(self.param.wi, xc) + self.param.bi)\n self.state.f = sigmoid(np.dot(self.param.wf, xc) + self.param.bf)\n self.state.o = sigmoid(np.dot(self.param.wo, xc) + self.param.bo)\n self.state.s = self.state.g * self.state.i + s_prev * self.state.f\n self.state.h = self.state.s * self.state.o\n\n self.xc = xc\n \n def top_diff_is(self, top_diff_h, top_diff_s):\n # notice that top_diff_s is carried along the constant error carousel\n ds = self.state.o * top_diff_h + top_diff_s\n do = self.state.s * top_diff_h\n di = self.state.g * ds\n dg = self.state.i * ds\n df = self.s_prev * ds\n\n # diffs w.r.t. vector inside sigma / tanh function\n di_input = sigmoid_derivative(self.state.i) * di \n df_input = sigmoid_derivative(self.state.f) * df \n do_input = sigmoid_derivative(self.state.o) * do \n dg_input = tanh_derivative(self.state.g) * dg\n\n # diffs w.r.t. inputs\n self.param.wi_diff += np.outer(di_input, self.xc)\n self.param.wf_diff += np.outer(df_input, self.xc)\n self.param.wo_diff += np.outer(do_input, self.xc)\n self.param.wg_diff += np.outer(dg_input, self.xc)\n self.param.bi_diff += di_input\n self.param.bf_diff += df_input \n self.param.bo_diff += do_input\n self.param.bg_diff += dg_input \n\n # compute bottom diff\n dxc = np.zeros_like(self.xc)\n dxc += np.dot(self.param.wi.T, di_input)\n dxc += np.dot(self.param.wf.T, df_input)\n dxc += np.dot(self.param.wo.T, do_input)\n dxc += np.dot(self.param.wg.T, dg_input)\n\n # save bottom diffs\n self.state.bottom_diff_s = ds * self.state.f\n self.state.bottom_diff_h = dxc[self.param.x_dim:]\n\nclass LstmNetwork():\n def __init__(self, lstm_param):\n self.lstm_param = lstm_param\n self.lstm_node_list = []\n # input sequence\n self.x_list = []\n\n def y_list_is(self, y_list, loss_layer):\n \"\"\"\n Updates diffs by setting target sequence \n with corresponding loss layer. \n Will *NOT* update parameters. To update parameters,\n call self.lstm_param.apply_diff()\n \"\"\"\n assert len(y_list) == len(self.x_list)\n idx = len(self.x_list) - 1\n # first node only gets diffs from label ...\n loss = loss_layer.loss(self.lstm_node_list[idx].state.h, y_list[idx])\n diff_h = loss_layer.bottom_diff(self.lstm_node_list[idx].state.h, y_list[idx])\n # here s is not affecting loss due to h(t+1), hence we set equal to zero\n diff_s = np.zeros(self.lstm_param.mem_cell_ct)\n self.lstm_node_list[idx].top_diff_is(diff_h, diff_s)\n idx -= 1\n\n ### ... following nodes also get diffs from next nodes, hence we add diffs to diff_h\n ### we also propagate error along constant error carousel using diff_s\n while idx >= 0:\n loss += loss_layer.loss(self.lstm_node_list[idx].state.h, y_list[idx])\n diff_h = loss_layer.bottom_diff(self.lstm_node_list[idx].state.h, y_list[idx])\n diff_h += self.lstm_node_list[idx + 1].state.bottom_diff_h\n diff_s = self.lstm_node_list[idx + 1].state.bottom_diff_s\n self.lstm_node_list[idx].top_diff_is(diff_h, diff_s)\n idx -= 1 \n\n return loss\n\n def x_list_clear(self):\n self.x_list = []\n\n def x_list_add(self, x):\n self.x_list.append(x)\n if len(self.x_list) > len(self.lstm_node_list):\n # need to add new lstm node, create new state mem\n lstm_state = LstmState(self.lstm_param.mem_cell_ct, self.lstm_param.x_dim)\n self.lstm_node_list.append(LstmNode(self.lstm_param, lstm_state))\n\n # get index of most recent x input\n idx = len(self.x_list) - 1\n if idx == 0:\n # no recurrent inputs yet\n self.lstm_node_list[idx].bottom_data_is(x)\n else:\n s_prev = self.lstm_node_list[idx - 1].state.s\n h_prev = self.lstm_node_list[idx - 1].state.h\n self.lstm_node_list[idx].bottom_data_is(x, s_prev, h_prev)\n\n\nif __name__ == '__main__':\n LP = LstmParam(5,10)\n LS = LstmState(5,10)\n LN = LstmNode(LP,LS)\n LNW = LstmNetwork(LP)\n while(True):\n sleep(2)\n" ]
[ [ "numpy.hstack", "numpy.dot", "numpy.random.seed", "numpy.zeros_like", "numpy.random.rand", "numpy.outer", "numpy.exp", "numpy.zeros" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
t-zhong/DeepComplexCRN
[ "ecde09722d6ca441c3cc9ee57cf15cf4ae083750" ]
[ "denoise.py" ]
[ "# 输入一个音频,输出PSEQ值和声谱图\n\nimport glob\nimport os\nfrom argparse import ArgumentParser\n\nimport librosa\nimport pytorch_lightning as pl\nimport torch\nfrom asteroid.metrics import get_metrics\n\nimport dc_crn\nfrom dataset import WavDataset\nfrom train import LitModule\nfrom vis import showspec\nimport soundfile\n\n\ndef main(args):\n # datasets and dataloaders\n if args.ckpt == 'None':\n args.ckpt = sorted(glob.glob('lightning_logs/version_13/checkpoints/epoch=49-step=399.ckpt'), key=os.path.getmtime)[-1]\n model = LitModule.load_from_checkpoint(args.ckpt).model\n model.eval()\n mix, _ = librosa.load(args.noisy_wav, sr=16000)\n clean, _ = librosa.load(args.clean_wav, sr=16000)\n mix = torch.tensor(mix, dtype=torch.float32).unsqueeze(0)\n clean = torch.tensor(clean, dtype=torch.float32).unsqueeze(0)\n estimate = model(mix)[1]\n os.makedirs('outputs', exist_ok=True)\n soundfile.write(f'outputs/{os.path.basename(args.noisy_wav)[:-4]}_denoised.wav', estimate.detach().cpu().numpy().squeeze(), samplerate=16000)\n # pseq = get_metrics(mix[:estimate.shape[1]], clean[:estimate.shape[1]], estimate, metrics_list=['pseq'])['pseq']\n # print(pseq)\n showspec(mix.cpu().numpy().squeeze(), clean.cpu().numpy().squeeze(), estimate.detach().cpu().numpy().squeeze(), sr=16000, titles=['mix', 'clean', 'estimate'])\n\n\nif __name__ == '__main__':\n parser = ArgumentParser()\n parser.add_argument('--noisy_wav', type=str, required=True) # 噪声的wav路径\n parser.add_argument('--clean_wav', type=str, required=True) # 清晰的wav路径\n parser.add_argument('--ckpt', type=str, default='None') # 检查点路径,默认lightning_logs目录下最后一个version的最后一个检查点\n \n args = parser.parse_args()\n main(args)\n" ]
[ [ "torch.tensor" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
IsaacChanghau/DeepNaryECOC
[ "08981309e21cf4d7519a36b034d35741c7fe0bf5" ]
[ "models/cifar_cnn_ps.py" ]
[ "import os\nimport keras\nimport numpy as np\nimport tensorflow as tf\nimport tensorflow.contrib.slim as slim\nfrom sklearn import utils\nfrom utils.logger import get_logger, Progbar\nfrom keras.preprocessing.image import ImageDataGenerator\n\n\ndef batch_dataset(images, labels, batch_size):\n total = labels.shape[0]\n for start in range(0, total, batch_size):\n end = min(start + batch_size, total)\n yield images[start:end], labels[start:end]\n\n\ndef cifar_conv_block(inputs, filters, kernel_size, activation, pool_size, weight_decay, drop_rate,\n training=False, trainable=True, name=\"conv_block\"):\n with tf.variable_scope(name, dtype=tf.float32):\n conv1 = tf.layers.conv2d(inputs, filters=filters, kernel_size=(kernel_size, kernel_size), strides=(1, 1),\n padding=\"same\", use_bias=True, activation=activation, name=\"conv1\",\n kernel_regularizer=tf.contrib.layers.l2_regularizer(scale=weight_decay),\n trainable=trainable)\n bn1 = tf.layers.batch_normalization(conv1, name=\"bn1\", trainable=trainable)\n drop1 = tf.layers.dropout(bn1, rate=drop_rate, training=training, name=\"dropout\")\n conv2 = tf.layers.conv2d(drop1, filters=filters, kernel_size=(kernel_size, kernel_size), strides=(1, 1),\n padding=\"same\", use_bias=True, activation=activation, name=\"conv2\",\n kernel_regularizer=tf.contrib.layers.l2_regularizer(scale=weight_decay),\n trainable=trainable)\n bn2 = tf.layers.batch_normalization(conv2, name=\"bn2\", trainable=trainable)\n pool2 = tf.layers.max_pooling2d(bn2, pool_size=pool_size, strides=2, padding=\"valid\", name=\"max_pool2\")\n return pool2\n\n\ndef cifar_cnn(inputs, labels, label_size, training=False, name=\"cifar_cnn\"): # used for cifar-10 and cifar-100\n with tf.variable_scope(name, dtype=tf.float32):\n conv0 = cifar_conv_block(inputs, filters=32, kernel_size=3, activation=tf.nn.elu, pool_size=2, trainable=False,\n weight_decay=5e-4, drop_rate=0.3, training=training, name=\"conv_block0\")\n conv1 = cifar_conv_block(conv0, filters=64, kernel_size=3, activation=tf.nn.elu, pool_size=2, trainable=False,\n weight_decay=5e-4, drop_rate=0.4, training=training, name=\"conv_block1\")\n conv2 = cifar_conv_block(conv1, filters=128, kernel_size=3, activation=tf.nn.elu, pool_size=2, trainable=False,\n weight_decay=5e-4, drop_rate=0.4, training=training, name=\"conv_block2\")\n conv3 = cifar_conv_block(conv2, filters=256, kernel_size=3, activation=tf.nn.elu, pool_size=2,\n weight_decay=5e-4, drop_rate=0.4, training=training, name=\"conv_block3\")\n drop1 = tf.layers.dropout(conv3, rate=0.5, training=training, name=\"drop1\")\n features = tf.layers.flatten(drop1, name=\"flatten\")\n dense1 = tf.layers.dense(features, units=512, use_bias=True, activation=tf.nn.relu, name=\"dense1\",\n kernel_regularizer=tf.contrib.layers.l2_regularizer(scale=5e-4))\n bn1 = tf.layers.batch_normalization(dense1, name=\"bn1\")\n drop2 = tf.layers.dropout(bn1, rate=0.5, training=training, name=\"drop2\")\n logits = tf.layers.dense(drop2, units=label_size, use_bias=True, activation=None, name=\"output\",\n kernel_regularizer=tf.contrib.layers.l2_regularizer(scale=5e-4))\n pred_labels = tf.argmax(logits, axis=1)\n cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits_v2(logits=logits, labels=labels)) + tf.add_n(\n tf.losses.get_regularization_losses())\n accuracy = tf.reduce_mean(tf.cast(tf.equal(tf.argmax(logits, 1), tf.argmax(labels, 1)), dtype=tf.float32))\n return logits, pred_labels, cost, accuracy\n\n\nclass CifarCNN:\n def __init__(self, num_class, ckpt_path, pretrained_model):\n tf.set_random_seed(12345)\n tf.reset_default_graph()\n self.ckpt_path, self.num_class = ckpt_path, num_class\n if not os.path.exists(self.ckpt_path):\n os.makedirs(self.ckpt_path)\n self.logger = get_logger(self.ckpt_path + \"log.txt\")\n # self.batch_size, self.epochs = 200, epochs\n self.learning_rate, self.lr_decay, self.grad_clip = 0.002, 0.05, 5.0 # adam\n with tf.Graph().as_default():\n self._build_model()\n self.logger.info(\"total params: {}\".format(np.sum([np.prod(v.get_shape().as_list()) for v in\n tf.trainable_variables()])))\n self._init_session()\n self._restore_part_weights(pretrained_model)\n\n def _init_session(self):\n sess_config = tf.ConfigProto()\n sess_config.gpu_options.allow_growth = True\n self.sess = tf.Session(config=sess_config)\n self.saver = tf.train.Saver(max_to_keep=1)\n self.sess.run(tf.global_variables_initializer())\n\n def save_session(self, steps):\n self.saver.save(self.sess, self.ckpt_path + \"cifar_cnn\", global_step=steps)\n\n def _restore_part_weights(self, model_path):\n variables = slim.get_variables_to_restore()\n variables_to_restore = [v for v in variables if \"conv_block\" in v.name and \"conv_block3\" not in v.name]\n tf.train.Saver(variables_to_restore).restore(self.sess, model_path)\n\n def restore_last_session(self):\n ckpt = tf.train.get_checkpoint_state(self.ckpt_path)\n if ckpt and ckpt.model_checkpoint_path:\n self.saver.restore(self.sess, ckpt.model_checkpoint_path)\n else:\n raise ValueError(\"No pre-trained model at {}\".format(self.ckpt_path))\n\n def close_session(self):\n self.sess.close()\n\n @staticmethod\n def normalize(x_train, x_test):\n mean = np.mean(x_train, axis=(0, 1, 2, 3))\n std = np.std(x_train, axis=(0, 1, 2, 3))\n x_train = (x_train - mean) / (std + 1e-7)\n x_test = (x_test - mean) / (std + 1e-7)\n return x_train, x_test\n\n @staticmethod\n def normalize_10_production(x):\n mean, std = 120.707, 64.15 # statistics from training dataset\n return (x - mean) / (std + 1e-7)\n\n @staticmethod\n def normalize_100_production(x):\n mean, std = 121.936, 68.389\n return (x - mean) / (std + 1e-7)\n\n def _build_model(self):\n # add placeholders\n self.inputs = tf.placeholder(tf.float32, shape=(None, 32, 32, 3), name=\"inputs\")\n self.labels = tf.placeholder(tf.float32, shape=(None, self.num_class), name=\"labels\")\n self.lr = tf.placeholder(tf.float32, name=\"learning_rate\")\n self.training = tf.placeholder(tf.bool, shape=[], name=\"training\")\n # build model\n self.logits, self.pred_labels, self.cost, self.accuracy = cifar_cnn(self.inputs, self.labels, self.num_class,\n self.training, name=\"cifar_cnn\")\n # build optimizer and training operation\n optimizer = tf.train.AdamOptimizer(learning_rate=self.lr)\n grads, vs = zip(*optimizer.compute_gradients(self.cost))\n grads, _ = tf.clip_by_global_norm(grads, self.grad_clip)\n self.train_op = optimizer.apply_gradients(zip(grads, vs))\n\n def train(self, x_train, y_train, x_test, y_test, batch_size=200, epochs=10):\n x_train, x_test = self.normalize(x_train, x_test)\n y_train = keras.utils.to_categorical(y_train, self.num_class)\n y_test = keras.utils.to_categorical(y_test, self.num_class)\n\n self.logger.info(\"data augmentation...\")\n datagen = ImageDataGenerator(featurewise_center=True, samplewise_center=False, horizontal_flip=True, cval=0.0,\n featurewise_std_normalization=False, preprocessing_function=None, rescale=None,\n samplewise_std_normalization=False, zca_whitening=False, zca_epsilon=1e-06,\n rotation_range=15, width_shift_range=0.1, height_shift_range=0.1, shear_range=0.0,\n zoom_range=0.0, channel_shift_range=0.0, fill_mode='nearest', vertical_flip=False,\n data_format=\"channels_last\")\n datagen.fit(x_train)\n x_aug, y_aug = x_train.copy(), y_train.copy()\n x_aug = datagen.flow(x_aug, np.zeros(x_train.shape[0]), batch_size=x_train.shape[0], shuffle=False).next()[0]\n x_train, y_train = np.concatenate((x_train, x_aug)), np.concatenate((y_train, y_aug))\n self.logger.info(\"start training...\")\n global_step, lr, global_test_acc = 0, self.learning_rate, 0.0\n num_batches = x_train.shape[0] // batch_size\n for epoch in range(1, epochs + 1):\n self.logger.info(\"Epoch {}/{}:\".format(epoch, epochs))\n x_train, y_train = utils.shuffle(x_train, y_train, random_state=0) # shuffle training dataset\n prog = Progbar(target=num_batches)\n prog.update(0, [(\"Global Step\", 0), (\"Train Loss\", 0.0), (\"Train Acc\", 0.0), (\"Test Loss\", 0.0),\n (\"Test Acc\", 0.0)])\n for i, (batch_imgs, batch_labels) in enumerate(batch_dataset(x_train, y_train, batch_size)):\n global_step += 1\n feed_dict = {self.inputs: batch_imgs, self.labels: batch_labels, self.training: True, self.lr: lr}\n _, loss, acc = self.sess.run([self.train_op, self.cost, self.accuracy], feed_dict=feed_dict)\n if global_step % 200 == 0:\n feed_dict = {self.inputs: x_test, self.labels: y_test, self.training: False}\n test_loss, test_acc = self.sess.run([self.cost, self.accuracy], feed_dict=feed_dict)\n prog.update(i + 1, [(\"Global Step\", int(global_step)), (\"Train Loss\", loss), (\"Train Acc\", acc),\n (\"Test Loss\", test_loss), (\"Test Acc\", test_acc)])\n if test_acc > global_test_acc:\n global_test_acc = test_acc\n self.save_session(global_step)\n else:\n prog.update(i + 1, [(\"Global Step\", int(global_step)), (\"Train Loss\", loss), (\"Train Acc\", acc)])\n if epoch > 10:\n lr = self.learning_rate / (1 + (epoch - 10) * self.lr_decay)\n feed_dict = {self.inputs: x_test, self.labels: y_test, self.training: False}\n test_loss, test_acc = self.sess.run([self.cost, self.accuracy], feed_dict=feed_dict)\n self.logger.info(\"Epoch: {}, Global Step: {}, Test Loss: {}, Test Accuracy: {}\".format(\n epoch, global_step, test_loss, test_acc))\n\n def test(self, x_test, y_test, print_info=True):\n self.restore_last_session()\n if self.num_class > 10:\n x_test = self.normalize_100_production(x_test)\n else:\n x_test = self.normalize_10_production(x_test)\n if len(y_test.shape) == 1 or y_test.shape[1] == 1:\n y_test = keras.utils.to_categorical(y_test, self.num_class)\n feed_dict = {self.inputs: x_test, self.labels: y_test, self.training: False}\n pred_labels, test_loss, test_acc = self.sess.run([self.pred_labels, self.cost, self.accuracy],\n feed_dict=feed_dict)\n if print_info:\n self.logger.info(\" -- Test Loss: {}, Test Accuracy: {}\".format(test_loss, test_acc))\n return np.reshape(pred_labels, newshape=(pred_labels.shape[0], 1))\n" ]
[ [ "tensorflow.layers.dropout", "numpy.concatenate", "numpy.mean", "tensorflow.train.AdamOptimizer", "tensorflow.Graph", "tensorflow.layers.batch_normalization", "numpy.reshape", "tensorflow.ConfigProto", "numpy.std", "tensorflow.reset_default_graph", "tensorflow.Session", "tensorflow.train.Saver", "tensorflow.trainable_variables", "tensorflow.argmax", "numpy.zeros", "tensorflow.contrib.slim.get_variables_to_restore", "tensorflow.placeholder", "tensorflow.global_variables_initializer", "tensorflow.set_random_seed", "tensorflow.train.get_checkpoint_state", "tensorflow.losses.get_regularization_losses", "tensorflow.layers.flatten", "tensorflow.nn.softmax_cross_entropy_with_logits_v2", "sklearn.utils.shuffle", "tensorflow.layers.max_pooling2d", "tensorflow.clip_by_global_norm", "tensorflow.contrib.layers.l2_regularizer", "tensorflow.variable_scope" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.10" ] } ]
kevinlib/IOHMM
[ "08f3a45479c6ecf0f918a6dcbc13c5988f8827cc" ]
[ "IOHMM/family_wrapper.py" ]
[ "'''\nThe Wrapper of statsmodels one parameter exponential family distributions used by GLM,\nwith the added functionality for log likelihood per sample. Loglikelihood per sample is\ngoing to be used in IOHMM to estimate emission probability.\n'''\nfrom __future__ import division\n\nfrom past.utils import old_div\nfrom builtins import object\nimport numpy as np\nfrom scipy import special\nfrom statsmodels.genmod.families.family import (Poisson,\n Gaussian,\n Gamma,\n Binomial,\n InverseGaussian,\n NegativeBinomial)\nimport statsmodels.genmod.families.links as L\n\nEPS = np.finfo(float).eps\n\n\nclass FamilyWrapper(object):\n \"\"\"\n The parent class for the wrapper of one-parameter exponential families,\n with function for per sample loglikelihood.\n Parameters\n ----------\n link : a link function instance\n Link is the linear transformation function.\n See the individual families for available links.\n variance : a variance function\n Measures the variance as a function of the mean probabilities.\n See the individual families for the default variance function.\n Attributes\n ----------\n family : a statsmodels corresponding family object\n --------\n \"\"\"\n\n def __init__(self, link, variance):\n raise NotImplementedError\n\n def loglike_per_sample(self, endog, mu, scale=1.):\n \"\"\"\n The function to calculate log-likelihood per sample\n in terms of the fitted mean response.\n Parameters\n ----------\n endog : array-like.\n Endogenous response variable\n For binomial family, it could be of shape (n, ) or (n, k).\n where n is the number of samples and k is number of classes.abs\n For other families, it should be of shape (n, ).\n mu : array-like\n should be of shape (n, )\n Fitted mean response variable\n scale : float, optional\n The scale parameter, defaults to 1.\n Returns\n -------\n log_p : array-like\n The value of the loglikelihood function evaluated per sample.\n The shape should be (n, )\n \"\"\"\n raise NotImplementedError\n\n\nclass PoissonWrapper(FamilyWrapper):\n \"\"\"\n The wrapper for Poisson exponential family.\n Subclass of FamilyWrapper\n Parameters\n ----------\n link : a link instance, optional\n The default link for the Poisson family is the log link. Available\n links are log, identity, and sqrt. See statsmodels.family.links for\n more information.\n Attributes\n ----------\n family : a statsmodels Possion family object\n --------\n \"\"\"\n\n def __init__(self, link=L.log):\n # For now the statsmodels 0.8.0 still takes a link as an argument\n # will follow the changes in statsmodels whenever it happens\n self.family = Poisson(link=link)\n\n def loglike_per_sample(self, endog, mu, scale=1.):\n r\"\"\"\n The function to calculate log-likelihood per sample\n in terms of the fitted mean response.\n Parameters\n ----------\n endog : array-like of shape (n, )\n Endogenous response variable\n mu : array-like of shape (n, )\n Fitted mean response variable\n scale : float, optional\n Not used for in the Poisson loglike.\n Returns\n -------\n log_p : array-like of shape (n, )\n The value of the loglikelihood function evaluated per sample\n (endog,mu,scale) as defined below.\n Notes\n -----\n .. math::\n log_p_{i} = scale * (Y_i * \\log(\\mu_i) - \\mu_i -\n \\ln \\Gamma(Y_i + 1))\n \"\"\"\n return (endog * np.log(mu) - mu -\n special.gammaln(endog + 1)).reshape(-1,)\n\n\nclass GaussianWrapper(FamilyWrapper):\n \"\"\"\n The wrapper of Gaussian exponential family distribution,\n with function for per sample probability.\n Parameters\n ----------\n link : a link instance, optional\n The default link for the Gaussian family is the identity link.\n Available links are log, identity, and inverse.\n See statsmodels.family.links for more information.\n Attributes\n ----------\n family : a statsmodel Gaussian family object\n --------\n \"\"\"\n\n def __init__(self, link=L.identity):\n self.family = Gaussian(link=link)\n\n def loglike_per_sample(self, endog, mu, scale=1.):\n \"\"\"\n The function to calculate log-likelihood per sample\n in terms of the fitted mean response.\n Parameters\n ----------\n endog : array-like of shape (n, )\n Endogenous response variable\n mu : array-like of shape (n, )\n Fitted mean response variable\n scale : float, optional\n Scales the loglikelihood function. The default is 1.\n Returns\n -------\n log_p : array-like of shape (n, )\n The value of the loglikelihood function evaluated per sample\n (endog,mu,scale) as defined below.\n\n Notes\n -----\n log_p_{i} = - 1 / 2 * ((Y_i - mu_i)^2 / scale + log(2 * \\pi * scale))\n \"\"\"\n if scale > EPS:\n return (old_div((endog * mu - old_div(mu**2, 2.)), scale) -\n old_div(endog**2, (2 * scale)) - .5 * np.log(2 * np.pi * scale)).reshape(-1,)\n else:\n log_p = np.zeros(endog.shape[0])\n log_p[~np.isclose(endog, mu)] = - np.Infinity\n return log_p\n\n\nclass GammaWrapper(FamilyWrapper):\n \"\"\"\n The wrapper of Gaussian exponential family distribution,\n with function for per sample probability.\n Parameters\n ----------\n link : a link instance, optional\n The default link for the Gaussian family is the identity link.\n Available links are log, identity, and inverse.\n See statsmodels.family.links for more information.\n Attributes\n ----------\n family : a statsmodel Gaussian family object\n --------\n \"\"\"\n\n def __init__(self, link=L.inverse_power):\n self.family = Gamma(link=link)\n\n def loglike_per_sample(self, endog, mu, scale=1.):\n \"\"\"\n The function to calculate log-likelihood per sample\n in terms of the fitted mean response.\n Parameters\n ----------\n endog : array-like of shape (n, )\n Endogenous response variable\n mu : array-like of shape (n, )\n Fitted mean response variable\n scale : float, optional\n The default is 1.\n Returns\n -------\n log_p : array-like of shape (n, )\n The value of the loglikelihood function evaluated per sample\n (endog,mu,freq_weights,scale) as defined below.\n Notes\n --------\n log_p_{i} = -1 / scale * (Y_i / \\mu_i+ \\log(\\mu_i)+\n (scale -1) * \\log(Y) + \\log(scale) + scale *\n \\ln \\Gamma(1 / scale))\n \"\"\"\n if scale > EPS:\n endog_mu = self.family._clean(old_div(endog, mu))\n return (old_div(-(endog_mu - np.log(endog_mu) + scale *\n np.log(endog) + np.log(scale) + scale *\n special.gammaln(old_div(1., scale))), scale)).reshape(-1,)\n else:\n log_p = np.zeros(endog.shape[0])\n log_p[~np.isclose(endog, mu)] = - np.Infinity\n return log_p\n\n\nclass BinomialWrapper(FamilyWrapper):\n \"\"\"\n The wrapper of Binomial exponential family distribution,\n with function for per sample probability.\n Parameters\n ----------\n link : a link instance, optional\n The default link for the Binomial family is the logit link.\n Available links are logit, probit, cauchy, log, and cloglog.\n See statsmodels.family.links for more information.\n Attributes\n ----------\n family : a statsmodel Binomial family object\n --------\n \"\"\"\n\n def __init__(self, link=L.logit): # , n=1.):\n # TODO: it *should* work for a constant n>1 actually, if data_weights\n # is equal to n\n self.family = Binomial(link=link)\n\n def loglike_per_sample(self, endog, mu, scale=1.):\n \"\"\"\n The function to calculate log-likelihood per sample\n in terms of the fitted mean response.\n Parameters\n ----------\n endog : array-like of shape (n, k) or (n, )\n Endogenous response variable\n mu : array-like of shape (n, )\n Fitted mean response variable\n scale : float, optional\n Not used for the Binomial GLM.\n Returns\n -------\n log_p : array-like of shape (n, )\n The value of the loglikelihood function evaluated per sample\n (endog,mu,freq_weights,scale) as defined below.\n Notes\n --------\n If the endogenous variable is binary:\n .. math::\n log_p_{i} = (y_i * \\log(\\mu_i/(1-\\mu_i)) + \\log(1-\\mu_i))\n If the endogenous variable is binomial:\n .. math::\n log_p_{i} = (\\ln \\Gamma(n+1) -\n \\ln \\Gamma(y_i + 1) - \\ln \\Gamma(n_i - y_i +1) + y_i *\n \\log(\\mu_i / (n_i - \\mu_i)) + n * \\log(1 - \\mu_i/n_i))\n where :math:`y_i = Y_i * n_i` with :math:`Y_i` and :math:`n_i` as\n defined in Binomial initialize. This simply makes :math:`y_i` the\n original number of successes.\n \"\"\"\n # special setup\n # see _Setup_binomial(self) in generalized_linear_model.py\n tmp = self.family.initialize(endog, 1)\n endog = tmp[0]\n if np.shape(self.family.n) == () and self.family.n == 1:\n return scale * (endog * np.log(old_div(mu, (1 - mu)) + 1e-200) +\n np.log(1 - mu)).reshape(-1,)\n else:\n y = endog * self.family.n # convert back to successes\n return scale * (special.gammaln(self.family.n + 1) -\n special.gammaln(y + 1) -\n special.gammaln(self.family.n - y + 1) + y *\n np.log(old_div(mu, (1 - mu))) + self.family.n *\n np.log(1 - mu)).reshape(-1,)\n\n\nclass InverseGaussianWrapper(FamilyWrapper):\n \"\"\"\n The wrapper of InverseGaussian exponential family distribution,\n with function for per sample probability.\n Parameters\n ----------\n link : a link instance, optional\n The default link for the InverseGaussian family is the identity link.\n Available links are inverse_squared, inverse, log, and identity.\n See statsmodels.family.links for more information.\n Attributes\n ----------\n family : a statsmodel InverseGaussian family object\n --------\n \"\"\"\n\n def __init__(self, link=L.inverse_squared):\n self.family = InverseGaussian(link=link)\n\n def loglike_per_sample(self, endog, mu, scale=1.):\n \"\"\"\n The function to calculate log-likelihood per sample\n in terms of the fitted mean response.\n Parameters\n ----------\n endog : array-like of shape (n,)\n Endogenous response variable\n mu : array-like of shape (n,)\n Fitted mean response variable\n scale : float, optional\n The default is 1.\n Returns\n -------\n log_p : array-like of shape (n,)\n The value of the loglikelihood function evaluated per sample\n (endog,mu,scale) as defined below.\n Notes\n -----\n log_p_{i} = -1/2 * ((Y_i - \\mu_i)^2 / (Y_i *\n \\mu_i^2 * scale) + \\log(scale * Y_i^3) + \\log(2 * \\pi))\n \"\"\"\n if scale > EPS:\n return -.5 * (old_div((endog - mu)**2, (endog * mu**2 * scale)) +\n np.log(scale * endog**3) + np.log(2 * np.pi)).reshape(-1,)\n else:\n log_p = np.zeros(endog.shape[0])\n log_p[~np.isclose(endog, mu)] = - np.Infinity\n return log_p\n\n\nclass NegativeBinomialWrapper(FamilyWrapper):\n \"\"\"\n The wrapper of NegativeBinomial exponential family distribution,\n with function for per sample probability.\n Parameters\n ----------\n link : a link instance, optional\n The default link for the NegativeBinomial family is the identity link.\n Available links are log, cloglog, identity, nbinom and power.\n See statsmodels.family.links for more information.\n Attributes\n ----------\n family : a statsmodel NegativeBinomial family object\n --------\n \"\"\"\n\n def __init__(self, link=L.log, alpha=1.):\n # make it at least float\n self.family = NegativeBinomial(link=link, alpha=alpha)\n\n def loglike_per_sample(self, endog, mu, scale):\n \"\"\"\n The function to calculate log-likelihood per sample\n in terms of the fitted mean response.\n Parameters\n ----------\n endog : array-like of shape (n, )\n Endogenous response variable\n mu : array-like of shape (n, )\n The fitted mean response values\n scale : float\n The scale parameter\n Returns\n -------\n log_p : array-like of shape (n, )\n The value of the loglikelihood function evaluated per sample\n (endog,mu,freq_weights,scale) as defined below.\n Notes\n -----\n Defined as:\n .. math::\n log_p_{i} = (Y_i * \\log{(\\alpha * \\mu_i /\n (1 + \\alpha * \\mu_i))} - \\log{(1 + \\alpha * \\mu_i)}/\n \\alpha + Constant)\n where :math:`Constant` is defined as:\n .. math::\n Constant = \\ln \\Gamma{(Y_i + 1/ \\alpha )} - \\ln \\Gamma(Y_i + 1) -\n \\ln \\Gamma{(1/ \\alpha )}\n \"\"\"\n if scale > EPS:\n lin_pred = self.family._link(mu)\n constant = (special.gammaln(endog + old_div(1, self.family.alpha)) -\n special.gammaln(endog + 1) - special.gammaln(old_div(1, self.family.alpha)))\n exp_lin_pred = np.exp(lin_pred)\n return (endog * np.log(self.family.alpha * exp_lin_pred /\n (1 + self.family.alpha * exp_lin_pred)) -\n old_div(np.log(1 + self.family.alpha * exp_lin_pred),\n self.family.alpha) + constant).reshape(-1,)\n else:\n log_p = np.zeros(endog.shape[0])\n log_p[~np.isclose(endog, mu)] = - np.Infinity\n return log_p\n" ]
[ [ "numpy.log", "numpy.finfo", "numpy.shape", "scipy.special.gammaln", "numpy.exp", "numpy.zeros", "numpy.isclose" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [ "0.18", "0.19" ], "tensorflow": [] } ]
cwscx/attackToolBox
[ "8434b38626b927079085e35245d43f75362791ef" ]
[ "example/KNNtest.py" ]
[ "from attackToolBox import *\nfrom tensorflow.examples.tutorials.mnist import input_data\n\nmnist = input_data.read_data_sets(\"MNIST_data/\", one_hot=True)\n\natb = attackToolBox(mnist.train.images[:10000], mnist.train.labels[:10000])\nprint(\"finish initializing\")\natb.polluteByKNN(mnist.test.images[:100], mnist.test.labels[:100], 0.01)\nprint(\"finish polluting\")\natb.savePollutedImages()\natb.testKNN()\n\n" ]
[ [ "tensorflow.examples.tutorials.mnist.input_data.read_data_sets" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.10", "1.12", "1.4", "1.13", "1.5", "1.7", "0.12", "1.0", "1.2" ] } ]
waldemar-szostak/tensorflow-models
[ "8217cc6a4fe46445bdd4a0e820de5c4ef214587c" ]
[ "official/resnet/keras/keras_imagenet_main.py" ]
[ "# Copyright 2018 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"Runs a ResNet model on the ImageNet dataset.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nfrom absl import app as absl_app\nfrom absl import flags\nimport tensorflow as tf # pylint: disable=g-bad-import-order\n\nfrom official.resnet import imagenet_main\nfrom official.resnet.keras import keras_common\nfrom official.resnet.keras import resnet_model\nfrom official.utils.flags import core as flags_core\nfrom official.utils.logs import logger\nfrom official.utils.misc import distribution_utils\n\n\nLR_SCHEDULE = [ # (multiplier, epoch to start) tuples\n (1.0, 5), (0.1, 30), (0.01, 60), (0.001, 80)\n]\n\n\ndef learning_rate_schedule(current_epoch,\n current_batch,\n batches_per_epoch,\n batch_size):\n \"\"\"Handles linear scaling rule, gradual warmup, and LR decay.\n\n Scale learning rate at epoch boundaries provided in LR_SCHEDULE by the\n provided scaling factor.\n\n Args:\n current_epoch: integer, current epoch indexed from 0.\n current_batch: integer, current batch in the current epoch, indexed from 0.\n batches_per_epoch: integer, number of steps in an epoch.\n batch_size: integer, total batch sized.\n\n Returns:\n Adjusted learning rate.\n \"\"\"\n initial_lr = keras_common.BASE_LEARNING_RATE * batch_size / 256\n epoch = current_epoch + float(current_batch) / batches_per_epoch\n warmup_lr_multiplier, warmup_end_epoch = LR_SCHEDULE[0]\n if epoch < warmup_end_epoch:\n # Learning rate increases linearly per step.\n return initial_lr * warmup_lr_multiplier * epoch / warmup_end_epoch\n for mult, start_epoch in LR_SCHEDULE:\n if epoch >= start_epoch:\n learning_rate = initial_lr * mult\n else:\n break\n return learning_rate\n\n\ndef parse_record_keras(raw_record, is_training, dtype):\n \"\"\"Adjust the shape of label.\"\"\"\n image, label = imagenet_main.parse_record(raw_record, is_training, dtype)\n\n # Subtract one so that labels are in [0, 1000), and cast to float32 for\n # Keras model.\n label = tf.cast(tf.cast(tf.reshape(label, shape=[1]), dtype=tf.int32) - 1,\n dtype=tf.float32)\n return image, label\n\n\ndef run(flags_obj):\n \"\"\"Run ResNet ImageNet training and eval loop using native Keras APIs.\n\n Args:\n flags_obj: An object containing parsed flag values.\n\n Raises:\n ValueError: If fp16 is passed as it is not currently supported.\n \"\"\"\n if flags_obj.enable_eager:\n tf.compat.v1.enable_eager_execution()\n\n dtype = flags_core.get_tf_dtype(flags_obj)\n if dtype == 'fp16':\n raise ValueError('dtype fp16 is not supported in Keras. Use the default '\n 'value(fp32).')\n\n data_format = flags_obj.data_format\n if data_format is None:\n data_format = ('channels_first'\n if tf.test.is_built_with_cuda() else 'channels_last')\n tf.keras.backend.set_image_data_format(data_format)\n\n # pylint: disable=protected-access\n if flags_obj.use_synthetic_data:\n distribution_utils.set_up_synthetic_data()\n input_fn = keras_common.get_synth_input_fn(\n height=imagenet_main.DEFAULT_IMAGE_SIZE,\n width=imagenet_main.DEFAULT_IMAGE_SIZE,\n num_channels=imagenet_main.NUM_CHANNELS,\n num_classes=imagenet_main.NUM_CLASSES,\n dtype=flags_core.get_tf_dtype(flags_obj))\n else:\n distribution_utils.undo_set_up_synthetic_data()\n input_fn = imagenet_main.input_fn\n\n train_input_dataset = input_fn(is_training=True,\n data_dir=flags_obj.data_dir,\n batch_size=flags_obj.batch_size,\n num_epochs=flags_obj.train_epochs,\n parse_record_fn=parse_record_keras)\n\n eval_input_dataset = input_fn(is_training=False,\n data_dir=flags_obj.data_dir,\n batch_size=flags_obj.batch_size,\n num_epochs=flags_obj.train_epochs,\n parse_record_fn=parse_record_keras)\n\n strategy = distribution_utils.get_distribution_strategy(\n distribution_strategy=flags_obj.distribution_strategy,\n num_gpus=flags_obj.num_gpus)\n\n strategy_scope = keras_common.get_strategy_scope(strategy)\n\n with strategy_scope:\n optimizer = keras_common.get_optimizer()\n model = resnet_model.resnet50(num_classes=imagenet_main.NUM_CLASSES)\n\n model.compile(loss='sparse_categorical_crossentropy',\n optimizer=optimizer,\n metrics=['sparse_categorical_accuracy'])\n\n time_callback, tensorboard_callback, lr_callback = keras_common.get_callbacks(\n learning_rate_schedule, imagenet_main.NUM_IMAGES['train'])\n\n train_steps = imagenet_main.NUM_IMAGES['train'] // flags_obj.batch_size\n train_epochs = flags_obj.train_epochs\n\n if flags_obj.train_steps:\n train_steps = min(flags_obj.train_steps, train_steps)\n train_epochs = 1\n\n num_eval_steps = (imagenet_main.NUM_IMAGES['validation'] //\n flags_obj.batch_size)\n\n validation_data = eval_input_dataset\n if flags_obj.skip_eval:\n # Only build the training graph. This reduces memory usage introduced by\n # control flow ops in layers that have different implementations for\n # training and inference (e.g., batch norm).\n tf.keras.backend.set_learning_phase(1)\n num_eval_steps = None\n validation_data = None\n\n history = model.fit(train_input_dataset,\n epochs=train_epochs,\n steps_per_epoch=train_steps,\n callbacks=[\n time_callback,\n lr_callback,\n tensorboard_callback\n ],\n validation_steps=num_eval_steps,\n validation_data=validation_data,\n validation_freq=flags_obj.epochs_between_evals,\n verbose=2)\n\n eval_output = None\n if not flags_obj.skip_eval:\n eval_output = model.evaluate(eval_input_dataset,\n steps=num_eval_steps,\n verbose=2)\n stats = keras_common.build_stats(history, eval_output, time_callback)\n return stats\n\n\ndef main(_):\n with logger.benchmark_context(flags.FLAGS):\n return run(flags.FLAGS)\n\n\nif __name__ == '__main__':\n tf.compat.v1.logging.set_verbosity(tf.compat.v1.logging.INFO)\n imagenet_main.define_imagenet_flags()\n keras_common.define_keras_flags()\n absl_app.run(main)\n" ]
[ [ "tensorflow.test.is_built_with_cuda", "tensorflow.reshape", "tensorflow.compat.v1.enable_eager_execution", "tensorflow.compat.v1.logging.set_verbosity", "tensorflow.keras.backend.set_image_data_format", "tensorflow.keras.backend.set_learning_phase" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.10", "2.7", "2.6", "2.4", "2.3", "2.5", "2.2" ] } ]
JDonini/Stacking-Audio-Tagging
[ "a827a803dc140138d7a24ffc6fc8eda21672703e", "a827a803dc140138d7a24ffc6fc8eda21672703e" ]
[ "database/FMA/src/model-1/second_stage.py", "src/model_autoencoders_chromagram.py" ]
[ "import sys\nimport numpy as np\nimport pandas as pd\nimport tensorflow as tf\nimport datetime\nfrom keras.utils import plot_model\nfrom keras_preprocessing.image import ImageDataGenerator\nfrom keras import backend as k\nfrom keras.callbacks import TensorBoard, EarlyStopping, ReduceLROnPlateau, CSVLogger\nfrom keras.optimizers import RMSprop\nfrom model import cnn_cnn_model_1\nsys.path.append('src')\nfrom metrics import auc_roc, hamming_loss, ranking_loss, auc_pr\nfrom generate_graph import generate_acc_graph, generate_loss_graph, generate_auc_roc_graph, generate_auc_pr_graph, \\\n generate_hamming_loss_graph, generate_ranking_loss_graph\nfrom generate_structure import TRAIN_ANNOTATIONS, TEST_ANNOTATIONS, VALIDATION_ANNOTATIONS, AUDIO_MEL_SPECTROGRAM, \\\n MODEL_1_TENSOR, MODEL_1_WEIGHTS_FINAL, MODEL_1_OUT_SECOND_STAGE\nsys.path.append('config')\nfrom config_project import BATCH_SIZE, TARGET_SIZE, LR, NUM_EPOCHS, LR_DECAY, SEED, EARLY_STOPPING, REDUCE_LR\n\nstart_time = datetime.datetime.now()\nnp.random.seed(SEED)\ntf.set_random_seed(SEED)\n\ncolumns = pd.read_csv(VALIDATION_ANNOTATIONS).columns[1:].tolist()\ndatagen = ImageDataGenerator(rescale=1./255)\n\ntrain_generator = datagen.flow_from_dataframe(\n dataframe=pd.read_csv(TRAIN_ANNOTATIONS),\n directory=AUDIO_MEL_SPECTROGRAM,\n x_col='song_name',\n y_col=columns,\n batch_size=BATCH_SIZE,\n seed=SEED,\n shuffle=True,\n class_mode='other',\n target_size=TARGET_SIZE\n)\n\ntest_generator = datagen.flow_from_dataframe(\n dataframe=pd.read_csv(TEST_ANNOTATIONS),\n directory=AUDIO_MEL_SPECTROGRAM,\n x_col='song_name',\n y_col=columns,\n batch_size=BATCH_SIZE,\n seed=SEED,\n shuffle=True,\n class_mode='other',\n target_size=TARGET_SIZE\n)\n\nvalid_generator = datagen.flow_from_dataframe(\n dataframe=pd.read_csv(VALIDATION_ANNOTATIONS),\n directory=AUDIO_MEL_SPECTROGRAM,\n x_col='song_name',\n y_col=columns,\n batch_size=BATCH_SIZE,\n seed=SEED,\n shuffle=True,\n class_mode='other',\n target_size=TARGET_SIZE\n)\n\nSTEP_SIZE_TRAIN = train_generator.n/train_generator.batch_size\nSTEP_SIZE_VALID = valid_generator.n/valid_generator.batch_size\nSTEP_SIZE_TEST = test_generator.n/test_generator.batch_size\n\nmodel = cnn_cnn_model_1()\n\nmodel.load_weights(MODEL_1_WEIGHTS_FINAL + 'weights_first_stage.h5')\n\nmodel.compile(loss='binary_crossentropy', optimizer=RMSprop(\n lr=LR, decay=LR_DECAY), metrics=['accuracy', auc_roc, auc_pr, hamming_loss, ranking_loss])\n\ndatetime_str = ('{date:%Y-%m-%d-%H:%M:%S}'.format(date=datetime.datetime.now()))\n\ncallbacks_list = [\n EarlyStopping(monitor='val_loss', mode='min', verbose=1, patience=EARLY_STOPPING),\n EarlyStopping(monitor='val_acc', mode='max', patience=EARLY_STOPPING),\n TensorBoard(log_dir=MODEL_1_TENSOR + 'second_stage/' + datetime_str, histogram_freq=0, write_graph=True),\n ReduceLROnPlateau(monitor='val_loss', factor=0.2, patience=REDUCE_LR, min_lr=1e-10, mode='auto', verbose=1),\n CSVLogger(MODEL_1_OUT_SECOND_STAGE + 'training.csv', append=True, separator=',')\n]\n\nhistory = model.fit_generator(\n generator=train_generator,\n steps_per_epoch=STEP_SIZE_TRAIN,\n validation_data=valid_generator,\n validation_steps=STEP_SIZE_VALID,\n epochs=NUM_EPOCHS,\n callbacks=callbacks_list,\n verbose=1,\n max_queue_size=100\n)\n\nscore = model.evaluate_generator(\n test_generator, steps=STEP_SIZE_TEST, max_queue_size=100)\n\nend_time = datetime.datetime.now()\nresults_testing = pd.DataFrame()\nresults_testing.loc[0, 'Loss'] = float('{0:.4f}'.format(score[0]))\nresults_testing.loc[0, 'Accuracy'] = float('{0:.4f}'.format(score[1]))\nresults_testing.loc[0, 'AUC-ROC'] = float('{0:.4f}'.format(score[2]))\nresults_testing.loc[0, 'AUC-PR'] = float('{0:.4f}'.format(score[3]))\nresults_testing.loc[0, 'Hamming Loss'] = float('{0:.4f}'.format(score[4]))\nresults_testing.loc[0, 'Ranking Loss'] = float('{0:.4f}'.format(score[5]))\nresults_testing.loc[0, 'Duration'] = ('{}'.format(end_time - start_time))\nresults_testing.to_csv(MODEL_1_OUT_SECOND_STAGE + \"testing.csv\", index=False)\n\ntest_generator.reset()\npredictions = model.predict_generator(test_generator,\n steps=STEP_SIZE_TEST,\n max_queue_size=100)\n\nresults_proba = pd.DataFrame(data=predictions, columns=columns)\nresults_proba[\"song_name\"] = test_generator.filenames\nordered_cols = [\"song_name\"] + columns\nresults_proba = results_proba[ordered_cols]\nresults_proba.to_csv(MODEL_1_OUT_SECOND_STAGE + \"y_proba_stage_2.csv\", index=False)\n\nresults_pred = pd.DataFrame(data=(predictions > 0.5).astype(int), columns=columns)\nresults_pred[\"song_name\"] = test_generator.filenames\nordered_cols = [\"song_name\"] + columns\nresults_pred = results_pred[ordered_cols]\nresults_pred.to_csv(MODEL_1_OUT_SECOND_STAGE + \"y_pred_stage_2.csv\", index=False)\n\n\nif __name__ == '__main__':\n k.clear_session()\n generate_acc_graph(history, MODEL_1_OUT_SECOND_STAGE, 'model_accuracy_second_stage.png')\n generate_loss_graph(history, MODEL_1_OUT_SECOND_STAGE, 'model_loss_second_stage.png')\n generate_auc_roc_graph(history, MODEL_1_OUT_SECOND_STAGE, 'model_auc_roc_second_stage.png')\n generate_auc_pr_graph(history, MODEL_1_OUT_SECOND_STAGE, 'model_auc_pr_second_stage.png')\n generate_hamming_loss_graph(history, MODEL_1_OUT_SECOND_STAGE, 'model_hamming_loss_second_stage.png')\n generate_ranking_loss_graph(history, MODEL_1_OUT_SECOND_STAGE, 'model_ranking_loss_second_stage.png')\n plot_model(model, to_file=MODEL_1_OUT_SECOND_STAGE + 'cnn_model_second_stage.png')\n", "import sys\nimport os\nimport pandas as pd\nimport tensorflow as tf\nimport numpy as np\nfrom keras.utils import multi_gpu_model\nfrom keras.models import Model\nfrom keras.layers import Input, Activation\nfrom keras.layers.convolutional import Conv2D, MaxPooling2D, UpSampling2D\nfrom keras.layers.normalization import BatchNormalization\nfrom keras.callbacks import EarlyStopping, ReduceLROnPlateau\nfrom keras_preprocessing.image import ImageDataGenerator\nsys.path.append('src')\nfrom generate_structure import TRAIN_ANNOTATIONS, VALIDATION_ANNOTATIONS, AUDIO_CHROMAGRAM, MODEL_AUTOENCODERS\nsys.path.append('config')\nfrom config_project import SEED, BATCH_SIZE, TARGET_SIZE, NUM_EPOCHS, IMG_SIZE\n\nnp.random.seed(SEED)\ntf.set_random_seed(SEED)\n\ncolumns = pd.read_csv(VALIDATION_ANNOTATIONS).columns[1:].tolist()\ndatagen = ImageDataGenerator(rescale=1./255)\n\ntrain_generator = datagen.flow_from_dataframe(\n dataframe=pd.read_csv(TRAIN_ANNOTATIONS),\n directory=AUDIO_CHROMAGRAM,\n x_col='song_name',\n y_col=columns,\n batch_size=BATCH_SIZE,\n seed=SEED,\n shuffle=True,\n class_mode='input',\n target_size=TARGET_SIZE\n)\n\nvalid_generator = datagen.flow_from_dataframe(\n dataframe=pd.read_csv(VALIDATION_ANNOTATIONS),\n directory=AUDIO_CHROMAGRAM,\n x_col='song_name',\n y_col=columns,\n batch_size=BATCH_SIZE,\n seed=SEED,\n shuffle=True,\n class_mode='input',\n target_size=TARGET_SIZE\n)\n\n\ndef autoencoders():\n input_img = Input(shape=IMG_SIZE)\n\n encoded = Conv2D(128, (3, 3), padding='same')(input_img)\n encoded = BatchNormalization()(encoded)\n encoded = Activation('relu')(encoded)\n encoded = MaxPooling2D((2, 2), padding='same')(encoded)\n\n encoded = Conv2D(64, (3, 3), padding='same')(encoded)\n encoded = BatchNormalization()(encoded)\n encoded = Activation('relu')(encoded)\n encoded = MaxPooling2D((2, 2), padding='same')(encoded)\n\n encoded = Conv2D(32, (3, 3), padding='same')(encoded)\n encoded = BatchNormalization()(encoded)\n encoded = Activation('relu')(encoded)\n encoded = MaxPooling2D((2, 2), padding='same')(encoded)\n\n encoded = Conv2D(16, (3, 3), padding='same')(encoded)\n encoded = BatchNormalization()(encoded)\n encoded = Activation('relu')(encoded)\n encoded = MaxPooling2D((2, 2), padding='same')(encoded)\n\n decoded = Conv2D(16, (3, 3), padding='same')(encoded)\n decoded = BatchNormalization()(decoded)\n decoded = Activation('relu')(decoded)\n decoded = UpSampling2D((2, 2))(decoded)\n\n decoded = Conv2D(32, (3, 3), padding='same')(decoded)\n decoded = BatchNormalization()(decoded)\n decoded = Activation('relu')(decoded)\n decoded = UpSampling2D((2, 2))(decoded)\n\n decoded = Conv2D(64, (3, 3), padding='same')(decoded)\n decoded = BatchNormalization()(decoded)\n decoded = Activation('relu')(decoded)\n decoded = UpSampling2D((2, 2))(decoded)\n\n decoded = Conv2D(128, (3, 3), padding='same')(decoded)\n decoded = BatchNormalization()(decoded)\n decoded = Activation('relu')(decoded)\n decoded = UpSampling2D((2, 2))(decoded)\n\n decoded = Conv2D(3, (3, 3), padding='same')(decoded)\n decoded = BatchNormalization()(decoded)\n decoded = Activation('sigmoid')(decoded)\n\n return Model(input_img, decoded)\n\n\nSTEP_SIZE_TRAIN = train_generator.n/train_generator.batch_size\nSTEP_SIZE_VALID = valid_generator.n/valid_generator.batch_size\n\nmodel = autoencoders()\n\nmodel.compile(optimizer='adam', loss='mean_squared_error')\n\ncallbacks_list = [\n EarlyStopping(monitor='val_loss', mode='min', verbose=1, patience=20),\n ReduceLROnPlateau(monitor='val_loss', factor=0.2, patience=12, min_lr=1e-10, mode='auto', verbose=1),\n]\n\nhistory = model.fit_generator(\n generator=train_generator,\n steps_per_epoch=STEP_SIZE_TRAIN,\n validation_data=valid_generator,\n validation_steps=STEP_SIZE_VALID,\n epochs=NUM_EPOCHS,\n verbose=1,\n callbacks=callbacks_list\n)\n\nmodel.save(MODEL_AUTOENCODERS + 'model_chromagram.h5')\nprint(\"Saved model to disk\")\n" ]
[ [ "tensorflow.set_random_seed", "pandas.read_csv", "numpy.random.seed", "pandas.DataFrame" ], [ "tensorflow.set_random_seed", "pandas.read_csv", "numpy.random.seed" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "2.0", "1.4", "1.3", "1.1", "1.5", "1.2" ], "scipy": [], "tensorflow": [ "1.10", "1.12", "1.4", "1.13", "1.5", "1.7", "0.12", "1.0", "1.2" ] }, { "matplotlib": [], "numpy": [], "pandas": [ "2.0", "1.4", "1.1", "1.5", "1.2", "1.3" ], "scipy": [], "tensorflow": [ "1.10", "1.12", "1.4", "1.13", "1.5", "1.7", "0.12", "1.0", "1.2" ] } ]
cfierro94/numpy
[ "7b4a60f3f0559d33224da65f83eeeacb9bf22234" ]
[ "numpy/typing/tests/data/pass/scalars.py" ]
[ "import sys\nimport datetime as dt\n\nimport pytest\nimport numpy as np\n\n\n# Construction\nclass D:\n def __index__(self) -> int:\n return 0\n\n\nclass C:\n def __complex__(self) -> complex:\n return 3j\n\n\nclass B:\n def __int__(self) -> int:\n return 4\n\n\nclass A:\n def __float__(self) -> float:\n return 4.0\n\n\nnp.complex64(3j)\nnp.complex64(A())\nnp.complex64(C())\nnp.complex128(3j)\nnp.complex128(C())\nnp.complex128(None)\nnp.complex64(\"1.2\")\nnp.complex128(b\"2j\")\n\nnp.int8(4)\nnp.int16(3.4)\nnp.int32(4)\nnp.int64(-1)\nnp.uint8(B())\nnp.uint32()\nnp.int32(\"1\")\nnp.int64(b\"2\")\n\nnp.float16(A())\nnp.float32(16)\nnp.float64(3.0)\nnp.float64(None)\nnp.float32(\"1\")\nnp.float16(b\"2.5\")\n\nif sys.version_info >= (3, 8):\n np.uint64(D())\n np.float32(D())\n np.complex64(D())\n\nnp.bytes_(b\"hello\")\nnp.bytes_(\"hello\", 'utf-8')\nnp.bytes_(\"hello\", encoding='utf-8')\nnp.str_(\"hello\")\nnp.str_(b\"hello\", 'utf-8')\nnp.str_(b\"hello\", encoding='utf-8')\n\n# Array-ish semantics\nnp.int8().real\nnp.int16().imag\nnp.int32().data\nnp.int64().flags\n\nnp.uint8().itemsize * 2\nnp.uint16().ndim + 1\nnp.uint32().strides\nnp.uint64().shape\n\n# Time structures\nnp.datetime64()\nnp.datetime64(0, \"D\")\nnp.datetime64(0, b\"D\")\nnp.datetime64(0, ('ms', 3))\nnp.datetime64(\"2019\")\nnp.datetime64(b\"2019\")\nnp.datetime64(\"2019\", \"D\")\nnp.datetime64(np.datetime64())\nnp.datetime64(dt.datetime(2000, 5, 3))\nnp.datetime64(dt.date(2000, 5, 3))\nnp.datetime64(None)\nnp.datetime64(None, \"D\")\n\nnp.timedelta64()\nnp.timedelta64(0)\nnp.timedelta64(0, \"D\")\nnp.timedelta64(0, ('ms', 3))\nnp.timedelta64(0, b\"D\")\nnp.timedelta64(\"3\")\nnp.timedelta64(b\"5\")\nnp.timedelta64(np.timedelta64(2))\nnp.timedelta64(dt.timedelta(2))\nnp.timedelta64(None)\nnp.timedelta64(None, \"D\")\n\nnp.void(1)\nnp.void(np.int64(1))\nnp.void(True)\nnp.void(np.bool_(True))\nnp.void(b\"test\")\nnp.void(np.bytes_(\"test\"))\n\n# Protocols\ni8 = np.int64()\nu8 = np.uint64()\nf8 = np.float64()\nc16 = np.complex128()\nb_ = np.bool_()\ntd = np.timedelta64()\nU = np.str_(\"1\")\nS = np.bytes_(\"1\")\nAR = np.array(1, dtype=np.float64)\n\nint(i8)\nint(u8)\nint(f8)\nint(b_)\nint(td)\nint(U)\nint(S)\nint(AR)\nwith pytest.warns(np.ComplexWarning):\n int(c16)\n\nfloat(i8)\nfloat(u8)\nfloat(f8)\nfloat(b_)\nfloat(td)\nfloat(U)\nfloat(S)\nfloat(AR)\nwith pytest.warns(np.ComplexWarning):\n float(c16)\n\ncomplex(i8)\ncomplex(u8)\ncomplex(f8)\ncomplex(c16)\ncomplex(b_)\ncomplex(td)\ncomplex(U)\ncomplex(AR)\n\n\n# Misc\nc16.dtype\nc16.real\nc16.imag\nc16.real.real\nc16.real.imag\nc16.ndim\nc16.size\nc16.itemsize\nc16.shape\nc16.strides\nc16.squeeze()\nc16.byteswap()\nc16.transpose()\n\n# Aliases\nnp.str0()\nnp.bool8()\nnp.bytes0()\nnp.string_()\nnp.object0()\nnp.void0(0)\n\nnp.byte()\nnp.short()\nnp.intc()\nnp.intp()\nnp.int0()\nnp.int_()\nnp.longlong()\n\nnp.ubyte()\nnp.ushort()\nnp.uintc()\nnp.uintp()\nnp.uint0()\nnp.uint()\nnp.ulonglong()\n\nnp.half()\nnp.single()\nnp.double()\nnp.float_()\nnp.longdouble()\nnp.longfloat()\n\nnp.csingle()\nnp.singlecomplex()\nnp.cdouble()\nnp.complex_()\nnp.cfloat()\nnp.clongdouble()\nnp.clongfloat()\nnp.longcomplex()\n\nnp.bool_().item()\nnp.int_().item()\nnp.uint64().item()\nnp.float32().item()\nnp.complex128().item()\nnp.str_().item()\nnp.bytes_().item()\n\nnp.bool_().tolist()\nnp.int_().tolist()\nnp.uint64().tolist()\nnp.float32().tolist()\nnp.complex128().tolist()\nnp.str_().tolist()\nnp.bytes_().tolist()\n" ]
[ [ "numpy.complex128", "numpy.string_", "numpy.ubyte", "numpy.longdouble", "numpy.csingle", "numpy.complex_", "numpy.void0", "numpy.clongdouble", "numpy.str_", "numpy.uint0", "numpy.bool_", "numpy.double", "numpy.complex64", "numpy.intc", "numpy.uint32", "numpy.clongfloat", "numpy.float16", "numpy.ulonglong", "numpy.int8", "numpy.uint", "numpy.half", "numpy.cfloat", "numpy.uint8", "numpy.uint16", "numpy.uintp", "numpy.float32", "numpy.bytes_", "numpy.short", "numpy.int0", "numpy.byte", "numpy.int_", "numpy.timedelta64", "numpy.int64", "numpy.cdouble", "numpy.bool8", "numpy.array", "numpy.bytes0", "numpy.longfloat", "numpy.single", "numpy.longcomplex", "numpy.intp", "numpy.int32", "numpy.void", "numpy.int16", "numpy.datetime64", "numpy.ushort", "numpy.longlong", "numpy.uint64", "numpy.float64", "numpy.object0", "numpy.float_", "numpy.str0", "numpy.singlecomplex", "numpy.uintc" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
yannforget/landsat-sentinel-fusion
[ "13872d733f4b3958a479b6da9477a83dc6ab1369" ]
[ "src/raster.py" ]
[ "\"\"\"Raster data processing.\"\"\"\n\nimport numpy as np\nimport rasterio\nimport rasterio.warp\n\n\ndef histogram_cutting(raster, percent=2, nodata=None, mask=None):\n \"\"\"Perform histogram cutting on a 2D raster\n\n Parameters\n ----------\n raster : numpy 2d array\n Input raster.\n percent : int\n Percentile (default=2).\n nodata : int or float, optional\n Nodata value of the input raster.\n mask : numpy 2d array, optional\n Masked pixel values will be ignored.\n\n Returns\n -------\n output : numpy 2d array\n Output raster.\n \"\"\"\n output = raster.copy()\n if nodata:\n output[output == nodata] = np.nan\n if isinstance(mask, np.ndarray):\n output[mask] = np.nan\n vmin, vmax = np.percentile(\n output[~np.isnan(output)].ravel(), (percent, 100-percent))\n output[(output < vmin)] = vmin\n output[(output > vmax)] = vmax\n return output\n\n\ndef rescale(values, dst_min, dst_max):\n \"\"\"Rescale the values of an array to a new range.\n\n Parameters\n ----------\n values : numpy 1d array\n Input values.\n dst_min : int or float\n New min. value.\n dst_max : int or float\n New max. value.\n\n Returns\n -------\n values : numpy 1d array\n Output values.\n \"\"\"\n num = (dst_max - dst_min) * (values - values.min())\n den = values.max() - values.min()\n return (num / den) + dst_min\n\n\ndef rescale_raster(raster, dst_min, dst_max, nodata=None):\n \"\"\"Rescale the values of a 2D raster to a new range.\n\n Parameters\n ----------\n raster : numpy 2d array\n Input raster.\n dst_min : int or float\n Target min. value.\n dst_max : int or float\n Target max. value.\n nodata : int or float, optional\n Nodata value in the input raster.\n\n Returns\n -------\n output : numpy 2d array\n Output raster.\n \"\"\"\n if nodata:\n mask = (raster != nodata) & ~np.isnan(raster)\n else:\n mask = ~np.isnan(raster)\n output = raster.copy()\n values = raster[mask]\n values = rescale(values, dst_min, dst_max)\n output[mask] = values\n return output\n\n\ndef reproject(src_img, src_crs, src_affine, src_bounds, dst_crs, resampling):\n \"\"\"Reproject an image to a given CRS.\n\n Parameters\n ----------\n src_img : numpy 2d array\n Source image as a 2d numpy array.\n src_crs : dict\n Source CRS.\n src_affine : Affine\n Source affine.\n src_bounds : tuple\n Source bounds (left, bottom, right, top).\n dst_crs : dict\n Target EPSG.\n resampling : Resampling\n Resampling method provided with a rasterio.warp.Resampling object.\n\n Returns\n -------\n dst_img : numpy 2d array\n Output reprojected image.\n dst_affine : Affine\n Output updated affine.\n \"\"\"\n # If dst_crs or src_crs are provided as integer EPSG, convert to dict\n if isinstance(src_crs, int):\n src_crs = {'init': f'epsg:{src_crs}'}\n if isinstance(dst_crs, int):\n dst_crs = {'init': f'epsg:{dst_crs}'}\n\n # Caculate the new affine and shape\n src_height, src_width = src_img.shape\n dst_affine, dst_width, dst_height = rasterio.warp.calculate_default_transform(\n src_crs, dst_crs, src_width, src_height, *src_bounds\n )\n\n # Get the reprojected image\n dst_img = np.ndarray(shape=(dst_height, dst_width), dtype=src_img.dtype)\n rasterio.warp.reproject(\n source=src_img, destination=dst_img,\n src_transform=src_affine, dst_transform=dst_affine,\n src_crs=src_crs, dst_crs=dst_crs,\n resampling=resampling\n )\n\n return dst_img, dst_affine\n\n\ndef crop(src_img, src_affine, n):\n \"\"\"Crop a given image from each direction according to a given number of\n pixels. Also calculate a new Affine transformation.\n\n Parameters\n ----------\n src_img : numpy 2d array\n Source image as a 2d numpy array.\n src_affine : Affine\n Source Affine object.\n n : int\n Number of pixels cropped from each direction.\n\n Returns\n -------\n dst_img : numpy 2d array\n Output cropped image.\n dst_affine : Affine\n Updated affine.\n \"\"\"\n nrows, ncols = src_img.shape\n dst_img = src_img[n:nrows-n, n:ncols-n]\n a, b, c, d, e, f, _, _, _ = src_affine\n c += a * n\n f -= a * n\n dst_affine = rasterio.Affine(a, b, c, d, e, f)\n return dst_img, dst_affine\n" ]
[ [ "numpy.isnan", "numpy.ndarray" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
zktuong/scirpy
[ "f0599abecc93c7db9ae1b0db268018d534ffe6da" ]
[ "scirpy/_tools/_clonotypes.py" ]
[ "import itertools\nimport random\nfrom typing import List, Optional, Sequence, Tuple, Union\n\nimport igraph as ig\nimport numpy as np\nimport pandas as pd\nfrom anndata import AnnData\nfrom scanpy import logging\nimport scipy.sparse as sp\n\nfrom .._compat import Literal\nfrom .._preprocessing import ir_dist\nfrom ..ir_dist import MetricType, _get_metric_key\nfrom ..ir_dist._clonotype_neighbors import ClonotypeNeighbors\nfrom ..util import _doc_params\nfrom ..util.graph import igraph_from_sparse_matrix, layout_components\nfrom ..io._util import _check_upgrade_schema\n\n_common_doc = \"\"\"\\\nreceptor_arms\n One of the following options:\n * `\"VJ\"` - only consider :term:`VJ<V(D)J>` sequences\n * `\"VDJ\"` - only consider :term:`VDJ<V(D)J>` sequences\n * `\"all\"` - both VJ and VDJ need to match\n * `\"any\"` - either VJ or VDJ need to match\n\n If `\"any\"`, two distances are combined by taking their minimum. If `\"all\"`,\n two distances are combined by taking their maximum. This is motivated\n by the hypothesis that a receptor recognizes the same antigen if it\n has a distance smaller than a certain cutoff. If we require only one\n of the receptors to match (`\"any\"`) the smaller distance is relevant.\n If we require both receptors to match (`\"all\"`), the larger distance is\n relevant.\n\ndual_ir\n One of the following options:\n * `\"primary_only\"` - only consider most abundant pair of :term:`VJ/VDJ<V(D)J>` chains\n * `\"any\"` - consider both pairs of :term:`VJ/VDJ<V(D)J>` sequences. Distance must be below\n cutoff for any of the chains.\n * `\"all\"` - consider both pairs of :term:`VJ/VDJ<V(D)J>` sequences. Distance must be below\n cutoff for all of the chains.\n\n Distances are combined as for `receptor_arms`.\n\n See also :term:`Dual IR`.\n\nsame_v_gene\n Enforces clonotypes to have the same :term:`V-genes<V(D)J>`. This is useful\n as the CDR1 and CDR2 regions are fully encoded in this gene.\n See :term:`CDR` for more details.\n\n v genes are matched based on the behaviour defined with `receptor_arms` and\n `dual_ir`.\n\nwithin_group\n Enforces clonotypes to have the same group defined by one or multiple grouping\n variables. Per default, this is set to :term:`receptor_type<Receptor type>`,\n i.e. clonotypes cannot comprise both B cells and T cells. Set this to\n :term:`receptor_subtype<Receptor subtype>` if you don't want clonotypes to\n be shared across e.g. gamma-delta and alpha-beta T-cells.\n You can also set this to any other column in `adata.obs` that contains\n a grouping, or to `None`, if you want no constraints.\n\"\"\"\n\n_common_doc_parallelism = \"\"\"\\\nn_jobs\n Number of CPUs to use for clonotype cluster calculation. Default: use all cores.\n If the number of cells is smaller than `2 * chunksize` a single\n worker thread will be used to avoid overhead.\nchunksize\n Number of objects to process per chunk. Each worker thread receives\n data in chunks. Smaller chunks result in a more meaningful progressbar,\n but more overhead.\n\"\"\"\n\n_common_doc_return_values = \"\"\"\\\nReturns\n-------\nclonotype\n A Series containing the clonotype id for each cell. Will be stored in\n `adata.obs[key_added]` if `inplace` is `True`\nclonotype_size\n A Series containing the number of cells in the respective clonotype\n for each cell. Will be stored in `adata.obs[f\"{key_added}_size\"]` if `inplace`\n is `True`.\ndistance_result\n A dictionary containing\n * `distances`: A sparse, pairwise distance matrix between unique\n receptor configurations\n * `cell_indices`: A dict of arrays, containing the adata.obs_names\n (cell indices) for each row in the distance matrix.\n\n If `inplace` is `True`, this is added to `adata.uns[key_added]`.\n\"\"\"\n\n_doc_clonotype_definition = \"\"\"\\\nDefinition of clonotype(-clusters) follows roughly the following procedure:\n 1. Create a list of unique receptor configurations. This is useful to\n collapse heavily expanded clonotypes, leading to many cells with identical\n CDR3 sequences, to a single entry.\n 2. Compute a pairwise distance matrix of unique receptor configurations.\n Unique receptor configurations are matched based on the pre-computed\n VJ and VDJ distance matrices and the parameters of `receptor_arms`,\n `dual_ir`, `same_v_gene` and `within_group`.\n 3. Find connected modules in the graph defined by this distance matrix. Each\n connected module is considered a clonotype-cluster.\n\"\"\"\n\n_doc_clonotype_network = \"\"\"\\\nThe clonotype network usually consists of many disconnected components,\neach of them representing a clonotype. Each node represents cells with an identical\nreceptor configuration (i.e. identical CDR3 sequences, and identical\nv genes if `same_v_gene` was specified during clonotype definition).\nThe size of each dot refers to the number of cells with the same receptor\nconfigurations.\n\nFor more details on the clonotype definition, see\n:func:`scirpy.tl.define_clonotype_clusters` and the respective section\nin the tutorial.\n\"\"\"\n\n\ndef _validate_parameters(\n adata,\n receptor_arms,\n dual_ir,\n within_group,\n distance_key,\n sequence,\n metric,\n key_added,\n) -> Tuple[Optional[List[str]], str, str]:\n \"\"\"Validate an sanitze parameters for `define_clonotypes`\"\"\"\n if receptor_arms not in [\"VJ\", \"VDJ\", \"all\", \"any\"]:\n raise ValueError(\n \"Invalid value for `receptor_arms`. Note that starting with v0.5 \"\n \"`TRA` and `TRB` are not longer valid values.\"\n )\n\n if dual_ir not in [\"primary_only\", \"all\", \"any\"]:\n raise ValueError(\"Invalid value for `dual_ir\")\n\n if within_group is not None:\n if isinstance(within_group, str):\n within_group = [within_group]\n for group_col in within_group:\n if group_col not in adata.obs.columns:\n msg = f\"column `{within_group}` not found in `adata.obs`. \"\n if group_col in (\"receptor_type\", \"receptor_subtype\"):\n msg += \"Did you run `tl.chain_qc`? \"\n raise ValueError(msg)\n\n if distance_key is None:\n distance_key = f\"ir_dist_{sequence}_{_get_metric_key(metric)}\"\n if distance_key not in adata.uns:\n raise ValueError(\n \"Sequence distances were not found in `adata.uns`. Did you run `pp.ir_dist`?\"\n )\n\n if key_added is None:\n key_added = f\"cc_{sequence}_{_get_metric_key(metric)}\"\n\n return within_group, distance_key, key_added\n\n\n@_check_upgrade_schema()\n@_doc_params(\n common_doc=_common_doc,\n clonotype_definition=_doc_clonotype_definition,\n return_values=_common_doc_return_values,\n paralellism=_common_doc_parallelism,\n)\ndef define_clonotype_clusters(\n adata: AnnData,\n *,\n sequence: Literal[\"aa\", \"nt\"] = \"aa\",\n metric: MetricType = \"identity\",\n receptor_arms: Literal[\"VJ\", \"VDJ\", \"all\", \"any\"] = \"all\",\n dual_ir: Literal[\"primary_only\", \"all\", \"any\"] = \"any\",\n same_v_gene: bool = False,\n within_group: Union[Sequence[str], str, None] = \"receptor_type\",\n key_added: str = None,\n partitions: Literal[\"connected\", \"leiden\"] = \"connected\",\n resolution: float = 1,\n n_iterations: int = 5,\n distance_key: Union[str, None] = None,\n inplace: bool = True,\n n_jobs: Union[int, None] = None,\n chunksize: int = 2000,\n) -> Optional[Tuple[pd.Series, pd.Series, dict]]:\n \"\"\"\n Define :term:`clonotype clusters<Clonotype cluster>`.\n\n As opposed to :func:`~scirpy.tl.define_clonotypes()` which employs a more stringent\n definition of :term:`clonotypes <Clonotype>`, this function flexibly defines\n clonotype clusters based on amino acid or nucleic acid sequence identity or\n similarity.\n\n Requires running :func:`~scirpy.pp.ir_dist` with the same `sequence` and\n `metric` values first.\n\n {clonotype_definition}\n\n Parameters\n ----------\n adata\n Annotated data matrix\n sequence\n The sequence parameter used when running :func:scirpy.pp.ir_dist`\n metric\n The metric parameter used when running :func:`scirpy.pp.ir_dist`\n\n {common_doc}\n\n key_added\n The column name under which the clonotype clusters and cluster sizes\n will be stored in `adata.obs` and under which the clonotype network will be\n stored in `adata.uns`.\n\n * Defaults to `cc_{{sequence}}_{{metric}}`, e.g. `cc_aa_levenshtein`,\n where `cc` stands for \"clonotype cluster\".\n * The clonotype sizes will be stored in `{{key_added}}_size`,\n e.g. `cc_aa_levenshtein_size`.\n * The clonotype x clonotype network will be stored in `{{key_added}}_dist`,\n e.g. `cc_aa_levenshtein_dist`.\n\n partitions\n How to find graph partitions that define a clonotype.\n Possible values are `leiden`, for using the \"Leiden\" algorithm and\n `connected` to find fully connected sub-graphs.\n\n The difference is that the Leiden algorithm further divides\n fully connected subgraphs into highly-connected modules.\n\n resolution\n `resolution` parameter for the leiden algorithm.\n n_iterations\n `n_iterations` parameter for the leiden algorithm.\n distance_key\n Key in `adata.uns` where the sequence distances are stored. This defaults\n to `ir_dist_{{sequence}}_{{metric}}`.\n inplace\n If `True`, adds the results to anndata, otherwise returns them.\n {paralellism}\n\n {return_values}\n \"\"\"\n within_group, distance_key, key_added = _validate_parameters(\n adata,\n receptor_arms,\n dual_ir,\n within_group,\n distance_key,\n sequence,\n metric,\n key_added,\n )\n\n ctn = ClonotypeNeighbors(\n adata,\n receptor_arms=receptor_arms,\n dual_ir=dual_ir,\n same_v_gene=same_v_gene,\n within_group=within_group,\n distance_key=distance_key,\n sequence_key=\"junction_aa\" if sequence == \"aa\" else \"junction\",\n n_jobs=n_jobs,\n chunksize=chunksize,\n )\n clonotype_dist = ctn.compute_distances()\n g = igraph_from_sparse_matrix(clonotype_dist, matrix_type=\"distance\")\n\n if partitions == \"leiden\":\n part = g.community_leiden(\n objective_function=\"modularity\",\n resolution_parameter=resolution,\n n_iterations=n_iterations,\n )\n else:\n part = g.clusters(mode=\"weak\")\n\n clonotype_cluster_series = pd.Series(data=None, index=adata.obs_names, dtype=str)\n clonotype_cluster_size_series = pd.Series(\n data=None, index=adata.obs_names, dtype=int\n )\n\n # clonotype cluster = graph partition\n idx, values = zip(\n *itertools.chain.from_iterable(\n zip(ctn.cell_indices[str(ct_id)], itertools.repeat(str(clonotype_cluster)))\n for ct_id, clonotype_cluster in enumerate(part.membership)\n )\n )\n clonotype_cluster_series = pd.Series(values, index=idx).reindex(adata.obs_names)\n clonotype_cluster_size_series = clonotype_cluster_series.groupby(\n clonotype_cluster_series\n ).transform(\"count\")\n\n # Return or store results\n clonotype_distance_res = {\n \"distances\": clonotype_dist,\n \"cell_indices\": ctn.cell_indices,\n }\n if inplace:\n adata.obs[key_added] = clonotype_cluster_series\n adata.obs[key_added + \"_size\"] = clonotype_cluster_size_series\n adata.uns[key_added] = clonotype_distance_res\n logging.info(f'Stored clonal assignments in `adata.obs[\"{key_added}\"]`.')\n else:\n return (\n clonotype_cluster_series,\n clonotype_cluster_size_series,\n clonotype_distance_res,\n )\n\n\n@_check_upgrade_schema()\n@_doc_params(\n common_doc=_common_doc,\n clonotype_definition=_doc_clonotype_definition,\n return_values=_common_doc_return_values,\n paralellism=_common_doc_parallelism,\n)\ndef define_clonotypes(\n adata: AnnData,\n *,\n key_added: str = \"clone_id\",\n distance_key: Union[str, None] = None,\n **kwargs,\n) -> Optional[Tuple[pd.Series, pd.Series, dict]]:\n \"\"\"\n Define :term:`clonotypes <Clonotype>` based on :term:`CDR3` nucleic acid\n sequence identity.\n\n As opposed to :func:`~scirpy.tl.define_clonotype_clusters` which employs\n a more flexible definition of :term:`clonotype clusters <Clonotype cluster>`,\n this function stringently defines clonotypes based on nucleic acid sequence\n identity. Technically, this function is an alias to :func:`~scirpy.tl.define_clonotype_clusters`\n with different default parameters.\n\n {clonotype_definition}\n\n Parameters\n ----------\n adata\n Annotated data matrix\n {common_doc}\n key_added\n The column name under which the clonotype clusters and cluster sizes\n will be stored in `adata.obs` and under which the clonotype network will be\n stored in `adata.uns`\n inplace\n If `True`, adds the results to anndata, otherwise return them.\n {paralellism}\n\n {return_values}\n\n \"\"\"\n if distance_key is None and \"ir_dist_nt_identity\" not in adata.uns:\n # For the case of \"clonotypes\" we want to compute the distance automatically\n # if it doesn't exist yet. Since it's just a sparse ID matrix, this\n # should be instant.\n logging.info(\n \"ir_dist for sequence='nt' and metric='identity' not found. \"\n \"Computing with default parameters.\"\n ) # type: ignore\n ir_dist(adata, metric=\"identity\", sequence=\"nt\", key_added=distance_key)\n\n return define_clonotype_clusters(\n adata,\n key_added=key_added,\n sequence=\"nt\",\n metric=\"identity\",\n partitions=\"connected\",\n **kwargs,\n )\n\n\n@_check_upgrade_schema()\n@_doc_params(clonotype_network=_doc_clonotype_network)\ndef clonotype_network(\n adata: AnnData,\n *,\n sequence: Literal[\"aa\", \"nt\"] = \"nt\",\n metric: Literal[\n \"identity\", \"alignment\", \"levenshtein\", \"hamming\", \"custom\"\n ] = \"identity\",\n min_cells: int = 1,\n min_nodes: int = 1,\n layout: str = \"components\",\n size_aware: bool = True,\n base_size: Optional[float] = None,\n size_power: float = 1,\n layout_kwargs: Union[dict, None] = None,\n clonotype_key: Union[str, None] = None,\n key_added: str = \"clonotype_network\",\n inplace: bool = True,\n random_state=42,\n) -> Union[None, pd.DataFrame]:\n \"\"\"\n Computes the layout of the clonotype network.\n\n Requires running :func:`scirpy.tl.define_clonotypes` or\n :func:`scirpy.tl.define_clonotype_clusters` first.\n\n {clonotype_network}\n\n Singleton clonotypes can be filtered out with the `min_cells` and `min_nodes`\n parameters.\n\n The `components` layout algorithm takes node sizes into account, avoiding\n overlapping nodes. Therefore, we recommend specifying `base_size` and\n `size_power` already here instead of providing them to\n :func:`scirpy.pl.clonotype_network`.\n\n Stores coordinates of the clonotype network in `adata.obsm`.\n\n Parameters\n ----------\n adata\n annotated data matrix\n sequence\n The `sequence` parameter :func:`scirpy.tl.define_clonotypes` was ran with.\n metric\n The `metric` parameter :func:`scirpy.tl.define_clonotypes` was ran with.\n min_cells\n Only show clonotypes consisting of at least `min_cells` cells\n min_nodes\n Only show clonotypes consisting of at least `min_nodes` nodes (i.e.\n non-identical receptor configurations)\n layout\n The layout algorithm to use. Can be anything supported by\n `igraph.Graph.layout`, or \"components\" to layout all connected\n components individually.\n :func:`scirpy.util.graph.layout_components` for more details.\n size_aware\n If `True`, use a node-size aware layouting algorithm. This option is\n only compatible with `layout = 'components'`.\n base_size\n Size of a point respresenting 1 cell. Per default, this value is a\n automatically determined based on the number of nodes in the plot.\n size_power\n Sizes are raised to the power of this value. Set this to, e.g. 0.5 to\n dampen point size.\n layout_kwargs\n Will be passed to the layout function\n clonotype_key\n Key under which the result of :func:`scirpy.tl.define_clonotypes` or\n :func:`scirpy.tl.define_clonotype_clusters` is stored in `adata.uns`.\n Defaults to `clonotype` if `sequence == 'nt' and distance == 'identity'` or\n `cc_{{sequence}}_{{metric}}` otherwise.\n key_added\n Key under which the layout coordinates will be stored in `adata.obsm` and\n parameters will be stored in `adata.uns`.\n inplace\n If `True`, store the coordinates in `adata.obsm`, otherwise return them.\n random_state\n Random seed set before computing the layout.\n\n Returns\n -------\n Depending on the value of `inplace` returns either nothing or the computed\n coordinates.\n \"\"\"\n if size_aware and layout != \"components\":\n raise ValueError(\n \"The `size_aware` option is only compatible with the `components` layout.\"\n )\n params_dict = dict()\n random.seed(random_state)\n np.random.seed(random_state)\n\n if clonotype_key is None:\n if metric == \"identity\" and sequence == \"nt\":\n clonotype_key = \"clone_id\"\n else:\n clonotype_key = f\"cc_{sequence}_{metric}\"\n\n try:\n clonotype_res = adata.uns[clonotype_key]\n except KeyError:\n raise ValueError(\n \"Connectivity data not found. Did you run `tl.define_clonotypes` \"\n \"or `tl.define_clonotype_clusters`, respectively?\"\n )\n\n graph = igraph_from_sparse_matrix(\n clonotype_res[\"distances\"], matrix_type=\"distance\"\n )\n\n if base_size is None:\n base_size = 240000 / len(graph.vs)\n\n # explicitly annotate node ids to keep them after subsetting\n graph.vs[\"node_id\"] = np.arange(0, len(graph.vs))\n\n # store size in graph to be accessed by layout algorithms\n clonotype_size = np.array(\n [idx.size for idx in clonotype_res[\"cell_indices\"].values()]\n )\n graph.vs[\"size\"] = clonotype_size\n components = np.array(graph.decompose(\"weak\"))\n component_node_count = np.array([len(component.vs) for component in components])\n component_sizes = np.array([sum(component.vs[\"size\"]) for component in components])\n\n # Filter subgraph by `min_cells` and `min_nodes`\n subgraph_idx = list(\n itertools.chain.from_iterable(\n comp.vs[\"node_id\"]\n for comp in components[\n (component_node_count >= min_nodes) & (component_sizes >= min_cells)\n ]\n )\n )\n if len(subgraph_idx) == 0:\n raise ValueError(\"No subgraphs with size >= {} found.\".format(min_cells))\n graph = graph.subgraph(subgraph_idx)\n\n # Compute layout\n if layout_kwargs is None:\n layout_kwargs = dict()\n if layout == \"components\":\n tmp_layout_kwargs = dict()\n tmp_layout_kwargs[\"component_layout\"] = \"fr_size_aware\" if size_aware else \"fr\"\n if size_aware:\n # layout kwargs for the fr_size_aware layout used for each component\n tmp_layout_kwargs[\"layout_kwargs\"] = {\n \"base_node_size\": base_size / 2000,\n \"size_power\": size_power,\n }\n pad = 3\n tmp_layout_kwargs[\"pad_x\"] = pad\n tmp_layout_kwargs[\"pad_y\"] = pad\n\n tmp_layout_kwargs.update(layout_kwargs)\n coords = layout_components(graph, **tmp_layout_kwargs)\n else:\n tmp_layout_kwargs = {\"weights\": \"weight\"} if layout == \"fr\" else dict()\n tmp_layout_kwargs.update(layout_kwargs)\n coords = graph.layout(layout, **tmp_layout_kwargs).coords\n\n # Expand to cell coordinates to store in adata.obsm\n idx, coords = zip(\n *itertools.chain.from_iterable(\n zip(clonotype_res[\"cell_indices\"][str(node_id)], itertools.repeat(coord))\n for node_id, coord in zip(graph.vs[\"node_id\"], coords) # type: ignore\n )\n )\n coord_df = pd.DataFrame(data=coords, index=idx, columns=[\"x\", \"y\"]).reindex(\n adata.obs_names\n )\n\n # Store results or return\n if inplace:\n adata.obsm[f\"X_{key_added}\"] = coord_df\n params_dict[\"clonotype_key\"] = clonotype_key\n params_dict[\"base_size\"] = base_size\n params_dict[\"size_power\"] = size_power\n adata.uns[key_added] = params_dict\n else:\n return coord_df\n\n\ndef _graph_from_coordinates(\n adata: AnnData, clonotype_key: str\n) -> [pd.DataFrame, sp.spmatrix]:\n \"\"\"\n Given an AnnData object on which `tl.clonotype_network` was ran, and\n the corresponding `clonotype_key`, extract a data-frame\n with x and y coordinates for each node, and an aligned adjacency matrix.\n\n Combined, it can be used for plotting the layouted graph with igraph or networkx.\n \"\"\"\n clonotype_res = adata.uns[clonotype_key]\n # map the cell-id to the corresponding row/col in the clonotype distance matrix\n dist_idx, obs_names = zip(\n *itertools.chain.from_iterable(\n zip(itertools.repeat(i), obs_names)\n for i, obs_names in clonotype_res[\"cell_indices\"].items()\n )\n )\n dist_idx_lookup = pd.DataFrame(index=obs_names, data=dist_idx, columns=[\"dist_idx\"])\n clonotype_label_lookup = adata.obs.loc[:, [clonotype_key]].rename(\n columns={clonotype_key: \"label\"}\n )\n\n # Retrieve coordinates and reduce them to one coordinate per node\n coords = (\n adata.obsm[\"X_clonotype_network\"]\n .dropna(axis=0, how=\"any\")\n .join(dist_idx_lookup)\n .join(clonotype_label_lookup)\n .groupby(by=[\"label\", \"dist_idx\", \"x\", \"y\"], observed=True)\n .size()\n .reset_index(name=\"size\")\n )\n\n # Networkx graph object for plotting edges\n adj_mat = clonotype_res[\"distances\"][coords[\"dist_idx\"].values.astype(int), :][\n :, coords[\"dist_idx\"].values.astype(int)\n ]\n\n return coords, adj_mat\n\n\n@_check_upgrade_schema()\ndef clonotype_network_igraph(\n adata: AnnData, basis=\"clonotype_network\"\n) -> Tuple[ig.Graph, ig.Layout]:\n \"\"\"\n Get an `igraph` object representing the clonotype network.\n\n Requires running :func:`scirpy.tl.clonotype_network` before, to\n compute the layout.\n\n Parameters\n ----------\n adata\n Annotated data matrix.\n basis\n Key in `adata.obsm` where the network layout is stored.\n\n Returns\n -------\n graph\n igraph object\n layout\n corresponding igraph Layout object.\n \"\"\"\n from ..util.graph import igraph_from_sparse_matrix\n\n try:\n clonotype_key = adata.uns[basis][\"clonotype_key\"]\n except KeyError:\n raise KeyError(\n f\"{basis} not found in `adata.uns`. Did you run `tl.clonotype_network`?\"\n )\n if f\"X_{basis}\" not in adata.obsm_keys():\n raise KeyError(\n f\"X_{basis} not found in `adata.obsm`. Did you run `tl.clonotype_network`?\"\n )\n coords, adj_mat = _graph_from_coordinates(adata, clonotype_key)\n\n graph = igraph_from_sparse_matrix(adj_mat, matrix_type=\"distance\")\n # flip y axis to be consistent with networkx\n coords[\"y\"] = np.max(coords[\"y\"]) - coords[\"y\"]\n layout = ig.Layout(coords=coords.loc[:, [\"x\", \"y\"]].values.tolist())\n return graph, layout\n" ]
[ [ "numpy.max", "pandas.Series", "numpy.random.seed", "pandas.DataFrame" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "0.23", "0.21", "2.0", "1.4", "1.3", "0.19", "1.1", "1.5", "0.24", "0.20", "1.0", "0.25", "1.2" ], "scipy": [], "tensorflow": [] } ]
Guilospanck/RA-opencv
[ "18a7d340b850e01fa4686cd36057baa991002677" ]
[ "src/ra.py" ]
[ "import cv2\nimport sys\nimport numpy as np\nimport math\nimport os\nfrom objloader_simple import *\n\nimport argparse\n\n# Minimum number of matches that have to be found\n# to consider the recognition valid\nMIN_MATCHES = 60\n\n# Command line argument parsing\nparser = argparse.ArgumentParser(description='Augmented Reality')\n\nparser.add_argument('-r', '--rectangle', help= 'Draw rectangle delimiting target surface on frame.', action='store_true')\nparser.add_argument('-mk', '--model_keypoints', help= 'Draw model keypoints.', action='store_true')\nparser.add_argument('-fk', '--frame_keypoints', help= 'Draw frame keypoints.', action='store_true')\nparser.add_argument('-ma', '--matches', help= 'Draw matches between keypoints.', action='store_true')\n\nargs = parser.parse_args()\n\n\ndef drawKeypoints(figure, figure_kps):\n \"\"\"\n Draw keypoints over a figure.\n\n Parameters:\n - @figure: What image you want to plot the keypoints.\n - @figure_kps: Keypoints of this image.\n \"\"\"\n # draw only keypoints location, not size and orientation\n figure = cv2.drawKeypoints(figure, figure_kps, figure, color=(0,255,0), flags=0)\n\ndef findHomography(src_keypoints, dst_keypoints, matches):\n \"\"\"\n Calculates and returns the Homography matrix between two planes: the train image plane and the query image plane.\n Homography is a 3x3 matrix that correlates the points that exist in two planes.\n\n Parameters:\n - @src_keypoints: Keypoints from the train image.\n - @dst_keypoints: Keypoints from the destiny image.\n - @matches: Matches between the two sets (train and query images).\n \"\"\"\n\n # source points\n src_pts = np.float32([\n src_keypoints[m.queryIdx].pt for m in matches # points on source image in relation to the destination image (query image)\n ]).reshape(-1, 1, 2)\n\n # destination points\n dst_points = np.float32([\n dst_keypoints[m.trainIdx].pt for m in matches # points on the destination image in relation to the source image (train image)\n ]).reshape(-1, 1, 2)\n\n # compute Homography\n M, mask = cv2.findHomography(src_pts, dst_points, cv2.RANSAC, 5.0)\n\n return M\n\ndef drawRectangle(source, src_kps, dst_kps, matches, destiny):\n \"\"\"\n Uses the shape of the train image, along with the Homography previously calculated, to 'send' the points\n from one plane (train image plane) to another (query image plane).\n\n Parameters:\n - @source: it is the train image, to retrieve its shape (height and width).\n - @src_kps: Keypoints from the train image.\n - @dst_kps: Keypoints from the destiny image.\n - @matches: Matches found between the train and query images.\n - @destiny: it is the query image, in which the rectangle is going to be drawn.\n \"\"\"\n\n h, w = source.shape # height and width of the image that we are searching\n \n pts = np.float32([[0, 0], [0, h - 1], [w - 1, h - 1], [w - 1, 0]]).reshape(-1, 1, 2) # reshape(rows, cols, dimension)\n\n # get Homography\n M = findHomography(src_kps, dst_kps, matches)\n\n # project corners into the frame\n dst = cv2.perspectiveTransform(pts, M)\n\n # connect them with lines\n destiny = cv2.polylines(destiny, [np.int32(dst)], True, 255, 3, cv2.LINE_AA)\n\ndef intrinsic_camera(fu, fv, u0, v0):\n K = np.float32([fu, 0, u0, 0, fv, v0, 0, 0, 1])\n K = K.reshape(3, 3)\n return K\n\ndef projection_matrix(K, H):\n \"\"\"\n From the camera calibration matrix (intrinsic matrix) and the estimated Homography,\n compute the 3D projection matrix.\n\n Parameters:\n - @K: Intrinsics Matrix\n - @H: Homography Matrix\n\n - We have that H = K [R1 R2 t] where H = homography matrix and R3 is ommited because the Homography\n is between two planes (x, y, z=0).\n\n - So, to retrieve the [R1 R2 t], we can do: G = [G1 G2 G3] = K^-1 * H where G1 = R1, G2 = R2, G3 = t and K = calibration matrix\n\n - The external calibration matrix ( [R1 R2 R3 t] ) is a homogeneous transformation, so, [R1 R2 R3] have to\n be orthonormal (condition to be homogeneous). So, in theory, to discover R3 we might do R3 = R1 x R2. BUT...\n a) Since we obtained this values (R1 and R2) from an approximation (homography), we cannot guarantee that\n the vectors will be orthonormals.\n b) The problem, then, is to find two vectors R1' and R2' that are close to R1 and R2 and are orthonormals. By doing\n that, we will calculate the R3 by doing R3 = R1' x R2'.\n\n - So, first, to encounter 2 vectors that are orthonormal, we must normalize R1 and R2 ( G1 and G2 ):\n l = sqrt( ||G1|| * ||G2|| )\n R1 = G1/l R2 = G2/l t = G3/l\n\n and find a vector that are orthonormal to either R1 and R2:\n\n p = R1 x R2\n\n And then the new basis will be rotated approximately 45° clockwise, resulting in a new basis: c and d where:\n\n c = R1 + R2 and d = c x p = (R1 + R2) x (R1 x R2)\n\n Now, if this new basis (c, d) is transformed into unit vectors, that is to say c' = c/||c|| and d' = d/||d||,\n and rotated 45° counterclockwise, we will have a basis that is orthonormal and is pretty close to the \n real values of R1 and R2. So:\n\n R1' = 1/sqrt(2) * (c/||c|| + d/||d||) rotated 45° counterclockwise with values normalized\n R2' = 1/sqrt(2) * (c/||c|| - d/||d||) ||\n\n - Now that we have our orthonormal basis that is close to the real R1 and R2, we can calculate the value of R3:\n\n R3 = R1' x R2'\n \n - 3D projection matrix: K * [R1' R2' R3 t]\n\n - For detailed explanation, open the image 'understanding/projection_matrix.png'.\n\n \"\"\"\n\n # computes G = [G1 G2 G3] = K^-1 * H\n H = H * (-1) # If don't change this, the obj will render on the wrong axis. E.g.: if a change the book with a rotation forward, the correct was the obj go back, but, with normal H, the object actually shows the wrong face\n G = np.dot(np.linalg.inv(K), H)\n\n col1 = G[:,0]\n col2 = G[:,1]\n col3 = G[:,2]\n\n # normalize vectors\n l = math.sqrt(np.linalg.norm(col1, 2) * np.linalg.norm(col2, 2)) # l = sqrt( ||G1|| * ||G2|| )\n R1 = col1/l\n R2 = col2/l\n t = col3/l\n\n # compute the orthonormal basis 45° clockwise\n c = R1 + R2\n p = np.cross(R1, R2)\n d = np.cross(c, p)\n\n # compute the orthonormal basis 45° counterclockwise\n R1_line = np.dot(1 / math.sqrt(2), c / np.linalg.norm(c, 2) + d / np.linalg.norm(d, 2)) # R1' = 1/sqrt(2) * ( c/||c|| + d/||d|| )\n R2_line = np.dot(1 / math.sqrt(2), c / np.linalg.norm(c, 2) - d / np.linalg.norm(d, 2)) # R2' = 1/sqrt(2) * ( c/||c|| - d/||d|| )\n\n # compute R3\n R3 = np.cross(R1_line, R2_line)\n\n # compute the 3D projection matrix\n extrinsic = np.stack((R1_line, R2_line, R3, t)).T\n projection = np.dot(K, extrinsic)\n\n return projection\n\ndef hex_to_rgb(hex_color):\n \"\"\"\n Helper function to convert hex strings to RGB\n \"\"\"\n hex_color = hex_color.lstrip('#')\n h_len = len(hex_color)\n return tuple(int(hex_color[i:i + h_len // 3], 16) for i in range(0, h_len, h_len // 3))\n\ndef render(img, obj, projection, model, color=False):\n \"\"\"\n Render a simple Wavefront object (.obj) into the current video frame\n \"\"\"\n\n vertices = obj.vertices\n scale_matrix = np.eye(3) * 3 # allow us to scale the model\n h, w = model.shape\n\n for face in obj.faces:\n face_vertices = face[0]\n points = np.array([vertices[vertex - 1] for vertex in face_vertices])\n points = np.dot(points, scale_matrix)\n\n # render model in the middle of the reference surface. To do so, model points must be displaced.\n points = np.array([[p[0] + w / 2, p[1] + h / 2, p[2]] for p in points])\n dst = cv2.perspectiveTransform(points.reshape(-1, 1, 3), projection)\n imgpts = np.int32(dst)\n\n if color is False:\n cv2.fillConvexPoly(img, imgpts, (137, 27, 211))\n else:\n color = hex_to_rgb(face[-1])\n color = color[::-1] # reverse\n cv2.fillConvexPoly(img, imgpts, color)\n \n return img\n\ndef run():\n\n # gets the current directory\n dir_name = os.getcwd()\n dir_name = dir_name.split('\\\\')\n dir_name.pop()\n dir_name = '\\\\'.join(dir_name)\n print(dir_name)\n\n # gets the train image\n source = cv2.imread(os.path.join(dir_name,'references/marley_source.jpg'), 0)\n\n # init video capture\n cap = cv2.VideoCapture(0, cv2.CAP_DSHOW)\n if not cap.isOpened():\n raise IOError(\"Cannot open webcam\")\n\n # Gets the Intrinsic matrix\n K = intrinsic_camera(fu=800, fv=800, u0=320, v0=240)\n\n # loads the 3d .obj model using the objoader_simple.py helper\n obj = OBJ(os.path.join(dir_name, 'models/fox/fox.obj'), swapyz=True)\n\n # Initiate orb detector\n orb = cv2.ORB_create()\n\n # Create BFMatcher\n bf = cv2.BFMatcher_create(cv2.NORM_HAMMING, crossCheck=True)\n\n # Find the keypoints and descriptors of the train image with orb\n source_kps, source_des = orb.detectAndCompute(source, None) # keypoints = 500 ; descriptors = 500 with 32 integer values each\n\n while True:\n # read the current frame\n ok, frame = cap.read()\n if not ok:\n print('Cannot read video file')\n sys.exit()\n return\n\n # find the keypoints and descriptors of the frame\n frame_kps, frame_des = orb.detectAndCompute(frame, None)\n\n # match frame descriptors with source descriptors\n matches = bf.match(source_des, frame_des)\n\n # sort them in the order of their distance\n # the lower the distance, the better the match\n matches = sorted(matches, key=lambda x: x.distance)\n\n cv2.imshow('Frame', frame)\n\n # close\n if cv2.waitKey(1) & 0xFF == ord('q'):\n break\n\n # verify if enough matches are found. If yes, compute Homography\n if len(matches) > MIN_MATCHES:\n H = findHomography(source_kps, frame_kps, matches)\n\n # draw rectangle if there is this arg\n if args.rectangle:\n drawRectangle(source, source_kps, frame_kps, matches, frame)\n \n # if a valid homography was found, render the cube on model plane\n if H is not None:\n try:\n # obtain the projection matrix\n P = projection_matrix(K, H) \n # project cube or model\n frame = render(frame, obj, P, source, False) \n except:\n pass\n \n if args.matches:\n # draw the first MIN_MATCHES\n frame = cv2.drawMatches(source, source_kps, frame, frame_kps, matches[:MIN_MATCHES], 0, flags=2)\n \n # show the results\n cv2.imshow('Frame', frame)\n\n # close\n if cv2.waitKey(1) & 0xFF == ord('q'):\n break\n \n else:\n print(\"Not enough matches found - %d/%d \" % (len(matches), MIN_MATCHES))\n \n cap.release()\n cv2.destroyAllWindows()\n return 0\n \n\nif __name__ == '__main__':\n run()\n" ]
[ [ "numpy.dot", "numpy.linalg.inv", "numpy.eye", "numpy.int32", "numpy.linalg.norm", "numpy.stack", "numpy.float32", "numpy.cross", "numpy.array" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
franaudo/compas
[ "8b2982a1c31e87d1a6740864476d6242612dc3dd" ]
[ "src/compas_plotters/artists/vectorartist.py" ]
[ "from matplotlib.patches import FancyArrowPatch\nfrom matplotlib.patches import ArrowStyle\n\nfrom compas.geometry import Point\nfrom compas_plotters.artists import Artist\n\n__all__ = ['VectorArtist']\n\n\nclass VectorArtist(Artist):\n \"\"\"\"\"\"\n\n zorder = 3000\n\n def __init__(self, vector, point=None, draw_point=False, color=(0, 0, 0)):\n super(VectorArtist, self).__init__(vector)\n self._draw_point = draw_point\n self._mpl_vector = None\n self._point_artist = None\n self.point = point or Point(0.0, 0.0, 0.0)\n self.vector = vector\n self.color = color\n\n @property\n def data(self):\n return [self.point[:2], (self.point + self.vector)[:2]]\n\n def draw(self):\n style = ArrowStyle(\"Simple, head_length=.1, head_width=.1, tail_width=.02\")\n arrow = FancyArrowPatch(self.point[:2], (self.point + self.vector)[:2],\n arrowstyle=style,\n edgecolor=self.color,\n facecolor=self.color,\n zorder=self.zorder,\n mutation_scale=100)\n if self._draw_point:\n self._point_artist = self.plotter.add(self.point)\n self._mpl_vector = self.plotter.axes.add_patch(arrow)\n\n def redraw(self):\n self._mpl_vector.set_positions(self.point[:2], (self.point + self.vector)[:2])\n\n\n# ==============================================================================\n# Main\n# ==============================================================================\n\nif __name__ == '__main__':\n\n from math import radians\n\n from compas.geometry import Vector\n from compas.geometry import Line\n from compas.geometry import Rotation\n from compas.geometry import Translation\n from compas_plotters import GeometryPlotter\n\n plotter = GeometryPlotter()\n\n point = Point(0.0, 3.0, 0.0)\n vector = Vector(2.0, 0.0, 0.0)\n\n direction = vector.unitized()\n loa = Line(point, point + direction)\n\n R = Rotation.from_axis_and_angle(Vector(0.0, 0.0, 1.0), radians(3.6))\n T = Translation.from_vector(direction.scaled(0.1))\n\n plotter.add(vector, point=point, draw_point=True)\n plotter.add(loa)\n plotter.pause(1.0)\n\n for i in range(100):\n point.transform(T)\n vector.transform(R)\n plotter.redraw(pause=0.01)\n\n plotter.show()\n" ]
[ [ "matplotlib.patches.ArrowStyle", "matplotlib.patches.FancyArrowPatch" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
alanwang93/ATEC2018-NLP-PyTorch
[ "8e00c6af1d3e1db7ab4433a0587784e45f830347", "8e00c6af1d3e1db7ab4433a0587784e45f830347" ]
[ "models/sigmoid_siamese.py", "deep_models/sf_siamese.py" ]
[ "from torch import nn\nfrom torch.autograd import Variable\nimport torch\nfrom utils import score, BCELoss\nimport numpy as np\n\nUNK_IDX = 0\nEOS_IDX = 2\n\n\nclass SigmoidSiameseRNN(nn.Module):\n\n def __init__(self, config, data_config):\n super(SigmoidSiameseRNN, self).__init__()\n self.mode = config['mode']\n self.l = self.mode[0] + 'len'\n self.vocab_size = data_config[self.mode+'_size']\n self.embed_size = config['embed_size']\n self.hidden_size = config['hidden_size']\n self.num_layers = config['num_layers']\n self.bidirectional = config['bidirectional']\n self.pos_weight = config['pos_weight']\n self.config = config\n self.data_config = data_config\n\n self.embed = nn.Embedding(self.vocab_size, self.embed_size, padding_idx=EOS_IDX)\n\n self.rnn = nn.LSTM(input_size=self.embed_size, hidden_size=self.hidden_size, \\\n num_layers=self.num_layers, batch_first=True, dropout=0.2)\n self.rnn_rvs = nn.LSTM(input_size=self.embed_size, hidden_size=self.hidden_size, \\\n num_layers=self.num_layers, batch_first=True, dropout=0.2)\n\n self.dropout = nn.Dropout(config['dropout'])\n self.dropout2 = nn.Dropout(config['dropout2'])\n\n self.linear_in_size = self.hidden_size\n self.lstm_size = self.hidden_size\n if self.bidirectional:\n self.lstm_size *= 2\n self.linear_in_size *= 2\n if config['sim_fun'] == 'dense+':\n self.linear_in_size = config['plus_size']\n\n self.linear_in_size *= 2\n if config['sim_fun'] in ['dense', 'dense+']:\n self.linear_in_size = self.linear_in_size + 7 + 124 #similarity:5; len:4->2; word_bool:124\n self.linear2_in_size = config['l1_size']\n #self.linear3_in_size = config['l2_size']\n self.linear = nn.Linear(self.linear_in_size, self.linear2_in_size)\n self.linear2 = nn.Linear(self.linear2_in_size, 1)\n #self.linear3 = nn.Linear(self.linear3_in_size, 1)\n if config['sim_fun'] == 'dense+':\n self.dense_plus = nn.Linear(self.lstm_size, config['plus_size'])\n if self.config['sim_fun'] == 'dense+':\n self.bn = nn.BatchNorm1d(config['plus_size'])\n else:\n self.bn = nn.BatchNorm1d(self.lstm_size)\n\n self.bn_feats = nn.BatchNorm1d(self.linear_in_size)\n self.bn2 = nn.BatchNorm1d(self.linear2_in_size)\n self.softmax = nn.Softmax(dim=1)\n self.tanh = nn.Tanh()\n self.relu = nn.ReLU()\n self.selu = nn.SELU()\n self.prelu = nn.PReLU()\n self.BCELoss = BCELoss\n\n self.optimizer = torch.optim.Adam(filter(lambda p: p.requires_grad, self.parameters()), lr=0.001)\n\n self._init_weights()\n\n\n\n def _init_weights(self):\n nn.init.normal_(self.embed.weight[1:])\n nn.init.xavier_normal_(self.linear.weight)\n #nn.init.xavier_normal_(self.linear2.weight)\n init_fun = nn.init.orthogonal_\n for i in range(self.num_layers):\n for j in range(4):\n init_fun(getattr(self.rnn, 'weight_ih_l{0}'.format(i))[j*self.hidden_size:(j+1)*self.hidden_size])\n init_fun(getattr(self.rnn, 'weight_hh_l{0}'.format(i))[j*self.hidden_size:(j+1)*self.hidden_size])\n if self.bidirectional:\n init_fun(getattr(self.rnn_rvs, 'weight_ih_l{0}'.format(i))[j*self.hidden_size:(j+1)*self.hidden_size])\n init_fun(getattr(self.rnn_rvs, 'weight_hh_l{0}'.format(i))[j*self.hidden_size:(j+1)*self.hidden_size])\n\n getattr(self.rnn, 'bias_ih_l{0}'.format(i))[self.hidden_size:2*self.hidden_size].data.fill_(1.)\n getattr(self.rnn, 'bias_hh_l{0}'.format(i))[self.hidden_size:2*self.hidden_size].data.fill_(1.)\n if self.bidirectional:\n getattr(self.rnn_rvs, 'bias_ih_l{0}'.format(i))[self.hidden_size:2*self.hidden_size].data.fill_(1.)\n getattr(self.rnn_rvs, 'bias_hh_l{0}'.format(i))[self.hidden_size:2*self.hidden_size].data.fill_(1.)\n \n if self.config['sim_fun'] == 'dense+':\n nn.init.xavier_normal_(self.dense_plus.weight)\n\n\n def forward(self, data):\n batch_size = data['s1_char'].size()[0]\n row_idx = torch.arange(0, batch_size).long()\n s1_embed = self.embed(data['s1_'+self.mode])\n s2_embed = self.embed(data['s2_'+self.mode])\n s1_embed = self.dropout(s1_embed)\n s2_embed = self.dropout(s2_embed)\n\n s1_out, s1_hidden = self.rnn(s1_embed)\n s2_out, s2_hidden = self.rnn(s2_embed)\n if self.config['representation'] == 'last': # last hidden state\n s1_out = torch.squeeze(s1_out[row_idx, data['s1_'+self.l]-1, :], 1)\n s2_out = torch.squeeze(s2_out[row_idx, data['s2_'+self.l]-1, :], 1)\n elif self.config['representation'] == 'avg': # average of all hidden states\n s1_outs = []\n s2_outs = []\n for i in range(batch_size):\n s1_outs.append(torch.mean(s1_out[i][:data['s1_'+self.l][i]], dim=0))\n s2_outs.append(torch.mean(s2_out[i][:data['s2_'+self.l][i]], dim=0))\n s1_outs = torch.stack(s1_outs)\n s2_outs = torch.stack(s2_outs)\n elif self.config['representation'] == 'max':\n s1_out, _ = torch.max(s1_out, 1)\n s2_out, _ = torch.max(s2_out, 1)\n\n if self.bidirectional:\n s1_embed_rvs = self.embed(data['s1_'+self.mode+'_rvs'])\n s2_embed_rvs = self.embed(data['s2_'+self.mode+'_rvs'])\n s1_embed_rvs = self.dropout(s1_embed_rvs)\n s2_embed_rvs = self.dropout(s2_embed_rvs)\n s1_out_rvs, _ = self.rnn_rvs(s1_embed_rvs)\n s2_out_rvs, _ = self.rnn_rvs(s2_embed_rvs)\n if self.config['representation'] == 'last': # last hidden state\n s1_out_rvs = torch.squeeze(s1_out_rvs[row_idx, data['s1_'+self.l]-1, :], 1)\n s2_out_rvs = torch.squeeze(s2_out_rvs[row_idx, data['s2_'+self.l]-1, :], 1)\n s1_outs = torch.cat((s1_out, s1_out_rvs), dim=1)\n s2_outs = torch.cat((s2_out, s2_out_rvs), dim=1)\n elif self.config['representation'] == 'avg': # average of all hidden states\n s1_outs_rvs = []\n s2_outs_rvs = []\n for i in range(batch_size):\n s1_outs_rvs.append(torch.mean(s1_out_rvs[i][:data['s1_'+self.l][i]], dim=0))\n s2_outs_rvs.append(torch.mean(s2_out_rvs[i][:data['s2_'+self.l][i]], dim=0))\n s1_outs = torch.cat((torch.stack(s1_outs_rvs), s1_outs), dim=1)\n s2_outs = torch.cat((torch.stack(s2_outs_rvs), s2_outs), dim=1)\n elif self.config['representation'] == 'max':\n s1_out_rvs, _ = torch.max(s1_out_rvs, 1)\n s2_out_rvs, _ = torch.max(s2_out_rvs, 1)\n s1_outs = torch.cat((s1_out, s1_out_rvs), dim=1)\n s2_outs = torch.cat((s2_out, s2_out_rvs), dim=1)\n\n \n\n if self.config['sim_fun'] == 'cosine':\n out = nn.functional.cosine_similarity(s1_outs, s2_outs)\n elif self.config['sim_fun'] == 'cosine+':\n pass\n elif self.config['sim_fun'] == 'exp':\n out = torch.exp(torch.neg(torch.norm(s1_outs-s2_outs, p=1, dim=1)))\n elif self.config['sim_fun'] == 'gesd':\n out = torch.rsqrt(torch.norm(s1_outs-s2_outs, p=2, dim=1))\n out = out * (1./ (1.+torch.exp(-1*(torch.bmm(s1_outs.unsqueeze(1), s2_outs.unsqueeze(2)).squeeze()+1.))))\n elif self.config['sim_fun'] in ['dense', 'dense+']:\n if self.config['sim_fun'] == 'dense+':\n s1_outs = self.dropout2(s1_outs)\n s2_outs = self.dropout2(s2_outs)\n s1_outs = self.dense_plus(s1_outs)\n s2_outs = self.dense_plus(s2_outs)\n # BN\n #s1_outs = self.bn(s1_outs)\n #s2_outs = self.bn(s2_outs)\n s1_outs = self.tanh(s1_outs)\n s2_outs = self.tanh(s2_outs)\n sfeats = self.sfeats(data)\n pair_feats = self.pair_feats(data)\n \n #feats = torch.cat(((s1_outs-s2_outs)*(s1_outs-s2_outs), s1_outs * s2_outs, sfeats, pair_feats), dim=1)\n feats = torch.cat((s1_outs, s2_outs, (s1_outs-s2_outs)*(s1_outs-s2_outs), s1_outs * s2_outs, sfeats, pair_feats), dim=1)\n feats = self.bn_feats(feats)\n #feats = self.dropout2(feats)\n out1 = self.linear(feats)\n out1 = self.selu(out1)\n out1 = self.bn2(out1)\n out1 = self.dropout2(out1)\n #out2 = self.dropout2(self.prelu(self.linear2(out1)))\n out = torch.squeeze(self.linear2(out1), 1)\n\n return out\n \n def sfeats(self, data):\n \"\"\" Sentence level features \"\"\"\n s1_feats = data['s1_feats'].type(torch.FloatTensor)\n s2_feats = data['s2_feats'].type(torch.FloatTensor)\n feats = torch.abs(s1_feats-s2_feats).float()\n if self.config['use_cuda']:\n feats = feats.cuda(self.config['cuda_num'])\n return feats\n\n def pair_feats(self, data):\n feats = data['pair_feats']\n if self.config['use_cuda']:\n feats = feats.cuda(self.config['cuda_num'])\n return feats\n\n\n def contrastive_loss(self, sims, labels, margin=0.3):\n \"\"\"\n Args:\n sims: similarity between two sentences\n labels: 1D tensor of 0 or 1\n margin: max(sim-margin, 0)\n \"\"\"\n batch_size = labels.size()[0]\n if len(sims.size()) == 0:\n sims = torch.unsqueeze(sims, dim=0)\n loss = torch.tensor(0.)\n if self.config['use_cuda']:\n loss = loss.cuda(self.config['cuda_num'])\n for i, l in enumerate(labels):\n loss += l*(1-sims[i])*(1-sims[i])*self.config['pos_weight']\n if sims[i] > margin:\n loss += (1-l)*sims[i] * sims[i]\n loss = loss/batch_size\n return loss\n\n\n def load_vectors(self, char=None, word=None):\n print(\"Use pretrained embedding\")\n if char is not None:\n self.embed.weight = nn.Parameter(torch.FloatTensor(char))\n if word is not None:\n self.embed.weight = nn.Parameter(torch.FloatTensor(word))\n\n def get_proba(self, out):\n if self.config['sim_fun'] in ['dense', 'dense+']:\n sim = self.tanh(out)\n proba = self.sigmoid(out)\n elif self.config['sim_fun'] == 'gesd':\n sim = out\n proba = out\n else:\n sim = out\n proba = sim/2.+0.5\n return sim, proba\n\n\n def train_step(self, data):\n out = self.forward(data)\n sim, proba = self.get_proba(out)\n # constractive loss\n loss = 0.\n\n if 'ce' in self.config['loss']:\n loss += self.config['ce_alpha'] * self.BCELoss(proba, data['target'], [1., self.pos_weight])\n if 'cl' in self.config['loss']:\n loss += self.contrastive_loss(proba, data['target'], margin=self.config['cl_margin']) \n self.optimizer.zero_grad()\n loss.backward()\n self.optimizer.step()\n return loss.item()\n\n def evaluate(self, data):\n out = self.forward(data)\n sim, proba = self.get_proba(out)\n loss = 0.\n if 'ce' in self.config['loss']:\n loss += self.config['ce_alpha'] * self.BCELoss(proba, data['target'], [1., self.pos_weight])\n if 'cl' in self.config['loss']:\n loss += self.contrastive_loss(proba, data['target'], margin=self.config['cl_margin']) \n return proba.tolist(), data['label'].tolist(), loss.item()\n\n\n def test(self, data):\n out = self.forward(data)\n sim, proba = self.get_proba(out)\n pred = proba.item()\n return pred, data['sid'].item()\n", "from torch import nn\nfrom torch.autograd import Variable\nimport torch\nfrom utils import score, BCELoss\nimport numpy as np\n\nUNK_IDX = 0\nEOS_IDX = 2\n\n\nclass SFSiameseRNN(nn.Module):\n\n def __init__(self, config, data_config):\n super(SFSiameseRNN, self).__init__()\n self.mode = config['mode']\n self.sf_dim = 134 - 2\n self.l = self.mode[0] + 'len'\n self.vocab_size = data_config[self.mode+'_size']\n self.embed_size = config['embed_size']\n self.hidden_size = config['hidden_size']\n self.num_layers = config['num_layers']\n self.bidirectional = config['bidirectional']\n self.pos_weight = config['pos_weight']\n self.config = config\n self.data_config = data_config\n\n self.embed = nn.Embedding(self.vocab_size, self.embed_size, padding_idx=EOS_IDX)\n\n self.rnn = nn.LSTM(input_size=self.embed_size, hidden_size=self.hidden_size, \\\n num_layers=self.num_layers, batch_first=True, dropout=0.2)\n self.rnn_rvs = nn.LSTM(input_size=self.embed_size, hidden_size=self.hidden_size, \\\n num_layers=self.num_layers, batch_first=True, dropout=0.2)\n\n self.dropout = nn.Dropout(config['dropout'])\n self.dropout2 = nn.Dropout(config['dropout2'])\n\n self.linear1_in_size = self.hidden_size\n self.lstm_size = self.hidden_size\n if self.bidirectional:\n self.lstm_size *= 2\n self.linear1_in_size *= 2\n\n if config['sim_fun'] == 'dense+':\n self.linear1_in_size = config['sl1_size']\n\n self.linear1_in_size *= 4\n if config['sim_fun'] in ['dense', 'dense+']:\n self.linear1_in_size = self.linear1_in_size\n self.linear2_in_size = config['l1_size']\n self.linear1 = nn.Linear(self.linear1_in_size + self.sf_dim, self.linear2_in_size)\n self .linear2 = nn.Linear(self.linear2_in_size, 2)\n\n if config['sim_fun'] == 'dense+':\n self.slinear1 = nn.Linear(self.lstm_size, config['sl1_size'])\n #self.slinear2 = nn.Linear(config['sl1_size'], config['sl2_size'])\n self.sbn1 = nn.BatchNorm1d(self.config['sl1_size'])\n #self.sbn2 = nn.BatchNorm1d(self.config['sl2_size'])\n\n\n #self.bn_feats = nn.BatchNorm1d(self.linear1_in_size)\n self.bn1 = nn.BatchNorm1d(self.linear2_in_size)\n\n self.softmax = nn.Softmax(dim=1)\n self.sigmoid = nn.Sigmoid()\n self.tanh = nn.Tanh()\n self.relu = nn.ReLU()\n self.selu = nn.SELU()\n #self.prelu = nn.PReLU()\n self.loss = nn.CrossEntropyLoss(weight=torch.tensor([1., config['pos_weight']]))\n\n self.optimizer = torch.optim.Adam(filter(lambda p: p.requires_grad, self.parameters()), lr=0.001)\n\n self._init_weights()\n\n\n\n def _init_weights(self):\n nn.init.kaiming_uniform_(self.embed.weight[1:])\n nn.init.kaiming_uniform_(self.linear1.weight)\n nn.init.kaiming_uniform_(self.linear2.weight)\n \n init_fun = nn.init.orthogonal_\n for i in range(self.num_layers):\n for j in range(4):\n init_fun(getattr(self.rnn, 'weight_ih_l{0}'.format(i))[j*self.hidden_size:(j+1)*self.hidden_size])\n init_fun(getattr(self.rnn, 'weight_hh_l{0}'.format(i))[j*self.hidden_size:(j+1)*self.hidden_size])\n if self.bidirectional:\n init_fun(getattr(self.rnn_rvs, 'weight_ih_l{0}'.format(i))[j*self.hidden_size:(j+1)*self.hidden_size])\n init_fun(getattr(self.rnn_rvs, 'weight_hh_l{0}'.format(i))[j*self.hidden_size:(j+1)*self.hidden_size])\n\n getattr(self.rnn, 'bias_ih_l{0}'.format(i))[self.hidden_size:2*self.hidden_size].data.fill_(1.)\n getattr(self.rnn, 'bias_hh_l{0}'.format(i))[self.hidden_size:2*self.hidden_size].data.fill_(1.)\n if self.bidirectional:\n getattr(self.rnn_rvs, 'bias_ih_l{0}'.format(i))[self.hidden_size:2*self.hidden_size].data.fill_(1.)\n getattr(self.rnn_rvs, 'bias_hh_l{0}'.format(i))[self.hidden_size:2*self.hidden_size].data.fill_(1.)\n \n if self.config['sim_fun'] == 'dense+':\n nn.init.kaiming_uniform_(self.slinear1.weight)\n # nn.init.kaiming_uniform_(self.slinear2.weight)\n\n\n def forward(self, data):\n batch_size = data['s1_char'].size()[0]\n row_idx = torch.arange(0, batch_size).long()\n s1_embed = self.embed(data['s1_'+self.mode])\n s2_embed = self.embed(data['s2_'+self.mode])\n s1_embed = self.dropout(s1_embed)\n s2_embed = self.dropout(s2_embed)\n\n s1_out1, s1_hidden = self.rnn(s1_embed)\n s2_out1, s2_hidden = self.rnn(s2_embed)\n\n if self.config['representation'] == 'last': # last hidden state\n s1_out = torch.squeeze(s1_out1[row_idx, data['s1_'+self.l]-1, :], 1)\n s2_out = torch.squeeze(s2_out1[row_idx, data['s2_'+self.l]-1, :], 1)\n\n elif self.config['representation'] == 'avg': # average of all hidden states\n s1_outs = []\n s2_outs = []\n for i in range(batch_size):\n s1_outs.append(torch.mean(s1_out1[i][:data['s1_'+self.l][i]], dim=0))\n s2_outs.append(torch.mean(s2_out1[i][:data['s2_'+self.l][i]], dim=0))\n s1_outs = torch.stack(s1_outs)\n s2_outs = torch.stack(s2_outs)\n elif self.config['representation'] == 'max':\n s1_out, _ = torch.max(s1_out1, 1)\n s2_out, _ = torch.max(s2_out1, 1)\n s1_out += torch.squeeze(s1_out1[row_idx, data['s1_'+self.l]-1, :], 1)\n s2_out += torch.squeeze(s2_out1[row_idx, data['s2_'+self.l]-1, :], 1)\n\n\n if self.bidirectional:\n s1_embed_rvs = self.embed(data['s1_'+self.mode+'_rvs'])\n s2_embed_rvs = self.embed(data['s2_'+self.mode+'_rvs'])\n s1_embed_rvs = self.dropout(s1_embed_rvs)\n s2_embed_rvs = self.dropout(s2_embed_rvs)\n s1_out_rvs1, _ = self.rnn_rvs(s1_embed_rvs)\n s2_out_rvs1, _ = self.rnn_rvs(s2_embed_rvs)\n if self.config['representation'] == 'last': # last hidden state\n s1_out_rvs = torch.squeeze(s1_out_rvs1[row_idx, data['s1_'+self.l]-1, :], 1)\n s2_out_rvs = torch.squeeze(s2_out_rvs1[row_idx, data['s2_'+self.l]-1, :], 1)\n s1_outs = torch.cat((s1_out, s1_out_rvs), dim=1)\n s2_outs = torch.cat((s2_out, s2_out_rvs), dim=1)\n\n elif self.config['representation'] == 'avg': # average of all hidden states\n s1_outs_rvs = []\n s2_outs_rvs = []\n for i in range(batch_size):\n s1_outs_rvs.append(torch.mean(s1_out_rvs1[i][:data['s1_'+self.l][i]], dim=0))\n s2_outs_rvs.append(torch.mean(s2_out_rvs1[i][:data['s2_'+self.l][i]], dim=0))\n s1_outs = torch.cat((torch.stack(s1_outs_rvs), s1_outs), dim=1)\n s2_outs = torch.cat((torch.stack(s2_outs_rvs), s2_outs), dim=1)\n elif self.config['representation'] == 'max':\n s1_out_rvs, _ = torch.max(s1_out_rvs1, 1)\n s2_out_rvs, _ = torch.max(s2_out_rvs1, 1)\n\n s1_out_rvs += torch.squeeze(s1_out_rvs1[row_idx, data['s1_'+self.l]-1, :], 1)\n s2_out_rvs += torch.squeeze(s2_out_rvs1[row_idx, data['s2_'+self.l]-1, :], 1)\n s1_outs = torch.cat((s1_out, s1_out_rvs), dim=1)\n s2_outs = torch.cat((s2_out, s2_out_rvs), dim=1)\n\n\n if self.config['sim_fun'] == 'cosine':\n out = nn.functional.cosine_similarity(s1_outs, s2_outs)\n elif self.config['sim_fun'] == 'cosine+':\n pass\n elif self.config['sim_fun'] == 'exp':\n out = torch.exp(torch.neg(torch.norm(s1_outs-s2_outs, p=1, dim=1)))\n elif self.config['sim_fun'] == 'gesd':\n out = torch.rsqrt(torch.norm(s1_outs-s2_outs, p=2, dim=1))\n out = out * (1./ (1.+torch.exp(-1*(torch.bmm(s1_outs.unsqueeze(1), s2_outs.unsqueeze(2)).squeeze()+1.))))\n elif self.config['sim_fun'] in ['dense', 'dense+']:\n if self.config['sim_fun'] == 'dense+':\n #s1_outs = self.dropout2(s1_outs)\n #s2_outs = self.dropout2(s2_outs)\n s1_outs = self.slinear1(s1_outs)\n s2_outs = self.slinear1(s2_outs)\n\n s1_outs = self.sbn1(s1_outs)\n s2_outs = self.sbn1(s2_outs)\n \n s1_outs = self.tanh(s1_outs)\n s2_outs = self.tanh(s2_outs)\n #s1_outs = self.slinear2(s1_outs)\n #s2_outs = self.slinear2(s2_outs)\n #s1_outs = self.sbn2(s1_outs)\n #s2_outs = self.sbn2(s2_outs)\n #s1_outs = self.relu(s1_outs)\n #s2_outs = self.relu(s2_outs)\n\n sf = self.sf(data)\n feats = torch.cat((s1_outs, s2_outs, torch.abs(s1_outs-s2_outs), s1_outs * s2_outs, sf), dim=1)\n # feats = self.bn_feats(feats)\n feats = self.linear1(feats)\n feats = self.bn1(feats)\n out = self.tanh(feats)\n out = torch.squeeze(self.linear2(out), 1)\n\n return out\n\n def sf(self, data):\n sf = torch.cat((torch.abs(data['s1_wlen'].unsqueeze(1).float()-data['s2_wlen'].unsqueeze(1).float()),\n torch.abs(data['s1_clen'].unsqueeze(1).float()- data['s2_clen'].unsqueeze(1).float()), data['power_words'], \n data['jaccard_char_unigram'], data['jaccard_char_bigram'], data['jaccard_char_trigram'], \n data['jaccard_word_unigram'], data['jaccard_word_bigram'],\n data['LevenshteinDistance_word']), dim=1)\n return sf\n\n \n def score_layer(self, out):\n out = torch.squeeze(self.linear2(out), 1)\n return out\n\n def dice_loss(self, pred, target):\n p = pred[:,1]\n t = target.float()\n smooth = 1.\n prod = p * t\n inter = torch.sum(prod)\n coef = ( 2. * inter + smooth) / (torch.sum(p) + torch.sum(t) + smooth)\n loss = 1. - coef\n return loss\n\n def focal_loss(self, pred, target, gamma=2.):\n eps = 1e-6\n p = pred[:,1]\n t = target.float()\n loss = - self.pos_weight* torch.pow((1-p), gamma)*torch.log(p+eps)*t - torch.pow(p, gamma) * torch.log(1-p+eps) * (1-t)\n return loss.mean()\n\n\n def load_vectors(self, char=None, word=None):\n print(\"Use pretrained embedding\")\n if char is not None:\n self.embed.weight = nn.Parameter(torch.FloatTensor(char))\n if word is not None:\n self.embed.weight = nn.Parameter(torch.FloatTensor(word))\n\n def train_step(self, data):\n out = self.forward(data)\n proba = self.softmax(out) # (N,C)\n #loss = self.focal_loss(proba, data['label'])\n loss = self.loss(proba, data['label'])\n self.optimizer.zero_grad()\n loss.backward()\n torch.nn.utils.clip_grad_norm_(self.parameters(), self.config['max_grad_norm'])\n self.optimizer.step()\n return loss.item()\n\n def evaluate(self, data):\n out = self.forward(data)\n proba = self.softmax(out)\n loss = self.loss(proba, data['label'])\n #loss = self.focal_loss(proba, data['label'])\n v, pred = torch.max(proba, dim=1)\n return pred.tolist(), data['label'].tolist(), loss.item()\n\n\n def test(self, data):\n out = self.forward(data)\n proba = self.softmax(out)\n v, pred = torch.max(proba, dim=1)\n return pred.tolist(), data['sid'].tolist()\n\n def predict_proba(self, data):\n out = self.forward(data)\n proba = self.softmax(out)\n pred = proba[:,1]\n return pred.tolist(), data['sid'].tolist() \n" ]
[ [ "torch.nn.Softmax", "torch.abs", "torch.mean", "torch.max", "torch.cat", "torch.nn.Embedding", "torch.FloatTensor", "torch.nn.Dropout", "torch.norm", "torch.tensor", "torch.nn.SELU", "torch.arange", "torch.squeeze", "torch.nn.BatchNorm1d", "torch.nn.PReLU", "torch.nn.init.xavier_normal_", "torch.unsqueeze", "torch.nn.Linear", "torch.nn.init.normal_", "torch.nn.functional.cosine_similarity", "torch.stack", "torch.nn.LSTM", "torch.nn.Tanh", "torch.nn.ReLU" ], [ "torch.nn.Softmax", "torch.mean", "torch.abs", "torch.max", "torch.cat", "torch.sum", "torch.nn.Embedding", "torch.FloatTensor", "torch.pow", "torch.nn.Dropout", "torch.norm", "torch.nn.Sigmoid", "torch.tensor", "torch.nn.SELU", "torch.arange", "torch.squeeze", "torch.nn.BatchNorm1d", "torch.nn.Linear", "torch.nn.functional.cosine_similarity", "torch.log", "torch.stack", "torch.nn.LSTM", "torch.nn.Tanh", "torch.nn.init.kaiming_uniform_", "torch.nn.ReLU" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
jinyiyexing518/DAL
[ "994fedcdf8cbd8b18aeaaa26544bab4a9f046e3c" ]
[ "utils/nms_wrapper.py" ]
[ "# --------------------------------------------------------\n# Fast R-CNN\n# Copyright (c) 2015 Microsoft\n# Licensed under The MIT License [see LICENSE for details]\n# Written by Ross Girshick\n# Modified by Linjie Deng\n# --------------------------------------------------------\nimport torch\n\nfrom utils.nms.cpu_nms import cpu_nms, cpu_soft_nms\n\n\ndef nms(dets, thresh, use_gpu=True):\n \"\"\"Dispatch to either CPU or GPU NMS implementations.\"\"\"\n if dets.shape[0] == 0:\n return []\n if dets.shape[1] == 5:\n raise NotImplementedError\n elif dets.shape[1] == 6:\n if torch.is_tensor(dets):\n dets = dets.cpu().detach().numpy()\n return cpu_nms(dets, thresh)\n else:\n raise NotImplementedError\n" ]
[ [ "torch.is_tensor" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
jluastro/nirc2
[ "b42b064f2f850561f8afca16d732090de2fea231" ]
[ "nirc2/reduce/sky.py" ]
[ "from astropy.io import fits\nfrom astropy.table import Table\nfrom astropy import stats\nimport os, sys, shutil\nfrom nirc2.reduce import util\n#import util\nimport numpy as np\nfrom pyraf import iraf as ir\nfrom nirc2 import instruments\nfrom datetime import datetime\nimport pdb\nimport astropy\n\ndef makesky(files, nite,\n wave, skyscale=True,\n raw_dir=None,\n instrument=instruments.default_inst):\n \"\"\"\n Make short wavelength (not L-band or longer) skies.\n \n Parameters\n ----------\n files : list of int\n Integer list of the files. Does not require padded zeros.\n nite : str\n Name for night of observation (e.g.: \"nite1\"), used as suffix\n inside the reduce sub-directories.\n wave : str\n Name for the observation passband (e.g.: \"kp\")\n skyscale : bool, default=True\n Whether or not to scale the sky files to the common median.\n Turn on for scaling skies before subtraction.\n raw_dir : str, optional\n Directory where raw files are stored. By default,\n assumes that raw files are stored in '../raw'\n instrument : instruments object, optional\n Instrument of data. Default is `instruments.default_inst`\n \"\"\"\n # Make new directory for the current passband and switch into it\n util.mkdir(wave)\n os.chdir(wave)\n \n # Determine directory locatons\n waveDir = os.getcwd() + '/'\n redDir = util.trimdir(os.path.abspath(waveDir + '../') + '/')\n rootDir = util.trimdir(os.path.abspath(redDir + '../') + '/')\n skyDir = waveDir + 'sky_' + nite + '/'\n \n # Set location of raw data\n rawDir = rootDir + 'raw/'\n \n # Check if user has specified a specific raw directory\n if raw_dir is not None:\n rawDir = util.trimdir(os.path.abspath(raw_dir) + '/')\n \n util.mkdir(skyDir)\n print('sky dir: ',skyDir)\n print('wave dir: ',waveDir)\n\n skylist = skyDir + 'skies_to_combine.lis'\n output = skyDir + 'sky_' + wave + '.fits'\n\n util.rmall([skylist, output])\n\n nn = instrument.make_filenames(files, rootDir=skyDir)\n nsc = instrument.make_filenames(files, rootDir=skyDir, prefix='scale')\n skies = instrument.make_filenames(files, rootDir=rawDir)\n\n for ii in range(len(nn)):\n if os.path.exists(nn[ii]): os.remove(nn[ii])\n if os.path.exists(nsc[ii]): os.remove(nsc[ii])\n shutil.copy(skies[ii], nn[ii])\n \n # Write out the sources of the sky files\n data_sources_file = open(redDir + 'data_sources.txt', 'a')\n data_sources_file.write('---\\n# Sky Files ({0})\\n'.format(wave))\n \n for cur_file in skies:\n out_line = '{0} ({1})\\n'.format(cur_file, datetime.now())\n data_sources_file.write(out_line)\n \n data_sources_file.close()\n \n # scale skies to common median\n if skyscale:\n _skylog = skyDir + 'sky_scale.log'\n util.rmall([_skylog])\n f_skylog = open(_skylog, 'w')\n\n sky_mean = np.zeros([len(skies)], dtype=float)\n\n for i in range(len(skies)):\n # Get the sigma-clipped mean and stddev on the dark\n img_sky = fits.getdata(nn[i])\n if float(astropy.__version__) < 3.0:\n sky_stats = stats.sigma_clipped_stats(img_dk,\n sigma=3,\n iters=4)\n else:\n sky_stats = stats.sigma_clipped_stats(img_sky,\n sigma=10,\n maxiters=4)\n\n sky_mean[i] = sky_stats[0]\n\n sky_all = sky_mean.mean()\n sky_scale = sky_all/sky_mean\n\n for i in range(len(skies)):\n _nn = fits.open(nn[i], ignore_missing_end=True)\n _nn[0].data = _nn[0].data * sky_scale[i]\n _nn[0].writeto(nsc[i])\n\n skyf = nn[i].split('/')\n print(('%s skymean=%10.2f skyscale=%10.2f' % \n (skyf[len(skyf)-1], sky_mean[i],sky_scale[i])))\n f_skylog.write('%s %10.2f %10.2f\\n' % \n (nn[i], sky_mean[i], sky_scale[i]))\n\n # Make list for combinng\n f_on = open(skylist, 'w')\n f_on.write('\\n'.join(nsc) + '\\n')\n f_on.close()\n\n #skylist = skyDir + 'scale????.fits'\n f_skylog.close()\n else:\n # Make list for combinng\n f_on = open(skylist, 'w')\n f_on.write('\\n'.join(nn) + '\\n')\n f_on.close()\n\n #skylist = skyDir + 'n????.fits' \n\n if os.path.exists(output): os.remove(output)\n ir.unlearn('imcombine')\n ir.imcombine.combine = 'median'\n ir.imcombine.reject = 'none'\n ir.imcombine.nlow = 1\n ir.imcombine.nhigh = 1\n\n ir.imcombine('@' + skylist, output)\n \n # Change back to original directory\n os.chdir('../')\n\n\ndef makesky_lp(files, nite, wave, number=3, rejectHsigma=None,\n raw_dir=None,\n instrument=instruments.default_inst):\n \"\"\"\n Make L' skies by carefully treating the ROTPPOSN angle\n of the K-mirror. Uses 3 skies combined (set by number keyword).\n \n Parameters\n ----------\n files : list of int\n Integer list of the files. Does not require padded zeros.\n nite : str\n Name for night of observation (e.g.: \"nite1\"), used as suffix\n inside the reduce sub-directories.\n wave : str\n Name for the observation passband (e.g.: \"lp\")\n number : int, default=3\n Number of skies to be combined\n rejectHsigma : int, default:None\n Flag to pass for rejectHsigma for IRAF imcombine\n By default, no flags are passed\n raw_dir : str, optional\n Directory where raw files are stored. By default,\n assumes that raw files are stored in '../raw'\n instrument : instruments object, optional\n Instrument of data. Default is `instruments.default_inst`\n \"\"\"\n \n # Make new directory for the current passband and switch into it\n util.mkdir(wave)\n os.chdir(wave)\n \n # Determine directory locatons\n waveDir = os.getcwd() + '/'\n redDir = util.trimdir(os.path.abspath(waveDir + '../') + '/')\n rootDir = util.trimdir(os.path.abspath(redDir + '../') + '/')\n skyDir = waveDir + 'sky_' + nite + '/'\n \n rawDir = rootDir + 'raw/'\n \n # Check if user has specified a specific raw directory\n if raw_dir is not None:\n rawDir = util.trimdir(os.path.abspath(raw_dir) + '/')\n \n util.mkdir(skyDir)\n print('sky dir: ',skyDir)\n print('wave dir: ',waveDir)\n \n raw = instrument.make_filenames(files, rootDir=rawDir)\n skies = instrument.make_filenames(files, rootDir=skyDir)\n \n # Write out the sources of the sky files\n data_sources_file = open(redDir + 'data_sources.txt', 'a')\n data_sources_file.write('---\\n# Sky Files ({0})\\n'.format(wave))\n \n for cur_file in skies:\n out_line = '{0} ({1})\\n'.format(cur_file, datetime.now())\n data_sources_file.write(out_line)\n \n data_sources_file.close()\n \n \n _rawlis = skyDir + 'raw.lis'\n _nlis = skyDir + 'n.lis'\n _skyRot = skyDir + 'skyRot.txt'\n _txt = skyDir + 'rotpposn.txt'\n _out = skyDir + 'sky'\n _log = _out + '.log'\n util.rmall([_rawlis, _nlis, _skyRot, _txt, _out, _log])\n util.rmall([sky + '.fits' for sky in skies])\n\n open(_rawlis, 'w').write('\\n'.join(raw)+'\\n')\n open(_nlis, 'w').write('\\n'.join(skies)+'\\n')\n\n print('makesky_lp: Getting raw files')\n ir.imcopy('@' + _rawlis, '@' + _nlis, verbose='no')\n ir.hselect('@' + _nlis, \"$I,ROTPPOSN\", 'yes', Stdout=_skyRot) \n\n # Read in the list of files and rotation angles\n files, angles = read_sky_rot_file(_skyRot)\n\n # Fix angles to be between -180 and 180\n angles[angles > 180] -= 360.0\n angles[angles < -180] += 360.0\n \n sidx = np.argsort(angles)\n \n # Make sorted numarrays\n angles = angles[sidx]\n files = files[sidx]\n\n f_log = open(_log, 'w')\n f_txt = open(_txt, 'w')\n \n # Skip the first and last since we are going to \n # average every NN files.\n print('makesky_lp: Combining to make skies.')\n startIdx = number / 2\n stopIdx = len(sidx) - (number / 2)\n for i in range(startIdx, stopIdx):\n sky = 'sky%.1f' % (angles[i])\n skyFits = skyDir + sky + '.fits'\n util.rmall([skyFits])\n\n # Take NN images\n start = i - (number/2)\n stop = start + number\n list = [file for file in files[start:stop]]\n short = [file for file in files[start:stop]]\n angleTmp = angles[start:stop]\n\n # Make short names\n for j in range(len(list)):\n tmp = (short[j]).rsplit('/', 1)\n short[j] = tmp[len(tmp)-1]\n\n print('%s: %s' % (sky, \" \".join(short)))\n f_log.write('%s:' % sky)\n for j in range(len(short)):\n f_log.write(' %s' % short[j])\n for j in range(len(angleTmp)):\n f_log.write(' %6.1f' % angleTmp[j])\n f_log.write('\\n')\n\n ir.unlearn('imcombine')\n ir.imcombine.combine = 'median'\n\n if (rejectHsigma == None):\n ir.imcombine.reject = 'none'\n ir.imcombine.nlow = 1\n ir.imcombine.nhigh = 1\n else:\n ir.imcombine.reject = 'sigclip'\n ir.imcombine.lsigma = 100\n ir.imcombine.hsigma = rejectHsigma\n ir.imcombine.zero = 'median'\n\n ir.imcombine.logfile = ''\n ir.imcombine(','.join(list), skyFits)\n\n ir.hedit(skyFits, 'SKYCOMB', \n '%s: %s' % (sky, ' '.join(short)), \n add='yes', show='no', verify='no')\n\n f_txt.write('%13s %8.3f\\n' % (sky, angles[i]))\n\t\n f_txt.close()\n f_log.close()\n \n # Change back to original directory\n os.chdir('../')\n\n\ndef makesky_lp2(files, nite, wave):\n \"\"\"Make L' skies by carefully treating the ROTPPOSN angle\n of the K-mirror. Uses only 2 skies combined.\"\"\"\n\n # Start out in something like '06maylgs1/reduce/kp/'\n waveDir = os.getcwd() + '/'\n redDir = util.trimdir(os.path.abspath(waveDir + '../') + '/')\n rootDir = util.trimdir(os.path.abspath(redDir + '../') + '/')\n skyDir = waveDir + 'sky_' + nite + '/'\n rawDir = rootDir + 'raw/'\n\n util.mkdir(skyDir)\n\n raw = instrument.make_filenames(files, rootDir=rawDir)\n skies = instrument.make_filenames(files, rootDir=skyDir)\n \n _rawlis = skyDir + 'raw.lis'\n _nlis = skyDir + 'n.lis'\n _skyRot = skyDir + 'skyRot.txt'\n _txt = skyDir + 'rotpposn.txt'\n _out = skyDir + 'sky'\n _log = _out + '.log'\n util.rmall([_rawlis, _nlis, _skyRot, _txt, _out, _log])\n util.rmall([sky + '.fits' for sky in skies])\n\n open(_rawlis, 'w').write('\\n'.join(raw)+'\\n')\n open(_nlis, 'w').write('\\n'.join(skies)+'\\n')\n\n print('makesky_lp: Getting raw files')\n ir.imcopy('@' + _rawlis, '@' + _nlis, verbose='no')\n ir.hselect('@' + _nlis, \"$I,ROTPPOSN\", 'yes', Stdout=_skyRot) \n\n # Read in the list of files and rotation angles\n files, angles = read_sky_rot_file(_skyRot)\n\n # Fix angles to be between -180 and 180\n angles[angles > 180] -= 360.0\n angles[angles < -180] += 360.0\n \n sidx = np.argsort(angles)\n \n # Make sorted numarrays\n angles = angles[sidx]\n files = files[sidx]\n\n f_log = open(_log, 'w')\n f_txt = open(_txt, 'w')\n\n # Skip the first and last since we are going to \n # average every 3 files.\n print('makesky_lp: Combining to make skies.')\n for i in range(1, len(sidx)):\n angav = (angles[i] + angles[i-1])/2.\n sky = 'sky%.1f' % (angav)\n skyFits = skyDir + sky + '.fits'\n util.rmall([skyFits])\n\n # Average 2 images\n list = [file for file in files[i-1:i+1]]\n short = [file for file in files[i-1:i+1]]\n\n # Make short names\n for j in range(len(list)):\n tmp = (short[j]).rsplit('/', 1)\n short[j] = tmp[len(tmp)-1]\n\n print('%s: %s %s' % (sky, short[0], short[1]))\n f_log.write('%s: %s %s %6.1f %6.1f\\n' %\n (sky, short[0], short[1], \n angles[i-1], angles[i]))\n\n ir.unlearn('imcombine')\n ir.imcombine.combine = 'average'\n ir.imcombine.reject = 'none'\n ir.imcombine.nlow = 1\n ir.imcombine.nhigh = 1\n ir.imcombine.logfile = ''\n ir.imcombine(list[1]+','+list[0], skyFits)\n\n ir.hedit(skyFits, 'SKYCOMB', \n '%s: %s %s' % (sky, short[0], short[1]), \n add='yes', show='no', verify='no')\n\n f_txt.write('%13s %8.3f\\n' % (sky, angav))\n\t\n f_txt.close()\n f_log.close()\n\n #ir.imdelete('@' + _nlis)\n\ndef makesky_fromsci(files, nite, wave):\n \"\"\"Make short wavelength (not L-band or longer) skies.\"\"\"\n\n # Start out in something like '06maylgs1/reduce/kp/'\n waveDir = os.getcwd() + '/'\n redDir = util.trimdir(os.path.abspath(waveDir + '../') + '/')\n rootDir = util.trimdir(os.path.abspath(redDir + '../') + '/')\n skyDir = waveDir + 'sky_' + nite + '/'\n rawDir = rootDir + 'raw/'\n\n util.mkdir(skyDir)\n print('sky dir: ',skyDir)\n print('wave dir: ',waveDir)\n\n skylist = skyDir + 'skies_to_combine.lis'\n output = skyDir + 'sky_' + wave + '.fits'\n\n util.rmall([skylist, output])\n\n nn = instrument.make_filenames(files, rootDir=skyDir)\n nsc = instrument.make_filenames(files, rootDir=skyDir, prefix='scale')\n skies = instrument.make_filenames(files, rootDir=rawDir)\n\n for ii in range(len(nn)):\n ir.imdelete(nn[ii])\n ir.imdelete(nsc[ii])\n ir.imcopy(skies[ii], nn[ii], verbose=\"no\")\n\n # Make list for combinng. Reset the skyDir to an IRAF variable.\n ir.set(skydir=skyDir)\n f_on = open(skylist, 'w')\n for ii in range(len(nn)):\n nn_new = nn[ii].replace(skyDir, \"skydir$\")\n f_on.write(nn_new + '\\n')\n f_on.close()\n\n # Calculate some sky statistics, but reject high (star-like) pixels\n sky_mean = np.zeros([len(skies)], dtype=float)\n sky_std = np.zeros([len(skies)], dtype=float)\n\n for ii in range(len(nn)):\n img_sky = fits.getdata(nn[i])\n if float(astropy.__version__) < 3.0:\n sky_stats = stats.sigma_clipped_stats(img_sky,\n sigma_lower=10, sigma_upper=3,\n iters=10)\n else:\n sky_stats = stats.sigma_clipped_stats(img_sky,\n sigma_lower=10, sigma_upper=3,\n maxiters=10)\n sky_mean[ii] = sky_stats[0]\n sky_std[ii] = sky_stats[2]\n\n sky_mean_all = sky_mean.mean()\n sky_std_all = sky_std.mean()\n\n # Upper threshold above which we will ignore pixels when combining.\n hthreshold = sky_mean_all + 3.0 * sky_std_all\n\n ir.imdelete(output)\n ir.unlearn('imcombine')\n ir.imcombine.combine = 'median'\n ir.imcombine.reject = 'sigclip'\n ir.imcombine.mclip = 'yes'\n ir.imcombine.hsigma = 2\n ir.imcombine.lsigma = 10\n ir.imcombine.hthreshold = hthreshold\n\n ir.imcombine('@' + skylist, output)\n\ndef makesky_lp_fromsci(files, nite, wave, number=3, rejectHsigma=None):\n \"\"\"Make L' skies by carefully treating the ROTPPOSN angle\n of the K-mirror. Uses 3 skies combined (set by number keyword).\"\"\"\n\n # Start out in something like '06maylgs1/reduce/kp/'\n waveDir = os.getcwd() + '/'\n redDir = util.trimdir(os.path.abspath(waveDir + '../') + '/')\n rootDir = util.trimdir(os.path.abspath(redDir + '../') + '/')\n skyDir = waveDir + 'sky_' + nite + '/'\n rawDir = rootDir + 'raw/'\n\n util.mkdir(skyDir)\n\n raw = instrument.make_filenames(files, rootDir=rawDir)\n skies = instrument.make_filenames(files, rootDir=skyDir)\n\n flatDir = redDir + 'calib/flats/'\n flat = flatDir + 'flat_' + wave + '.fits'\n if not os.access(flat, os.F_OK): \n flat = flatDir + 'flat.fits'\n \n _rawlis = skyDir + 'raw.lis'\n _nlis = skyDir + 'n.lis'\n _skyRot = skyDir + 'skyRot.txt'\n _txt = skyDir + 'rotpposn.txt'\n _out = skyDir + 'sky'\n _log = _out + '.log'\n util.rmall([_rawlis, _nlis, _skyRot, _txt, _out, _log])\n util.rmall([sky + '.fits' for sky in skies])\n\n open(_rawlis, 'w').write('\\n'.join(raw)+'\\n')\n open(_nlis, 'w').write('\\n'.join(skies)+'\\n')\n\n print('makesky_lp: Getting raw files')\n ir.imarith('@'+_rawlis, '/', flat, '@'+_nlis)\n #ir.imcopy('@' + _rawlis, '@' + _nlis, verbose='no')\n ir.hselect('@' + _nlis, \"$I,ROTPPOSN\", 'yes', Stdout=_skyRot) \n\n # Read in the list of files and rotation angles\n files, angles = read_sky_rot_file(_skyRot)\n\n # Fix angles to be between -180 and 180\n angles[angles > 180] -= 360.0\n angles[angles < -180] += 360.0\n \n sidx = np.argsort(angles)\n \n # Make sorted numarrays\n angles = angles[sidx]\n files = files[sidx]\n\n f_log = open(_log, 'w')\n f_txt = open(_txt, 'w')\n\n # Skip the first and last since we are going to \n # average every NN files.\n print('makesky_lp: Combining to make skies.')\n startIdx = number / 2\n stopIdx = len(sidx) - (number / 2)\n for i in range(startIdx, stopIdx):\n sky = 'sky%.1f' % (angles[i])\n skyFitsTmp = skyDir + sky + '_tmp.fits'\n skyFits = skyDir + sky + '.fits'\n util.rmall([skyFitsTmp, skyFits])\n\n # Take NN images\n start = i - (number/2)\n stop = start + number\n list = [file for file in files[start:stop]]\n short = [file for file in files[start:stop]]\n angleTmp = angles[start:stop]\n\n # Make short names\n for j in range(len(list)):\n tmp = (short[j]).rsplit('/', 1)\n short[j] = tmp[len(tmp)-1]\n\n print('%s: %s' % (sky, \" \".join(short)))\n f_log.write('%s:' % sky)\n for j in range(len(short)):\n f_log.write(' %s' % short[j])\n for j in range(len(angleTmp)):\n f_log.write(' %6.1f' % angleTmp[j])\n f_log.write('\\n')\n\n ir.unlearn('imcombine')\n ir.imcombine.combine = 'median'\n\n if (rejectHsigma == None):\n ir.imcombine.reject = 'none'\n ir.imcombine.nlow = 1\n ir.imcombine.nhigh = 1\n else:\n ir.imcombine.reject = 'sigclip'\n ir.imcombine.lsigma = 100\n ir.imcombine.hsigma = rejectHsigma\n ir.imcombine.zero = 'median'\n\n ir.imcombine.logfile = ''\n ir.imcombine(','.join(list), skyFitsTmp)\n\n ir.imarith(skyFitsTmp, '*', flat, skyFits)\n\n ir.hedit(skyFits, 'SKYCOMB', \n '%s: %s' % (sky, ' '.join(short)), \n add='yes', show='no', verify='no')\n\n f_txt.write('%13s %8.3f\\n' % (sky, angles[i]))\n\t\n f_txt.close()\n f_log.close()\n\n\ndef read_sky_rot_file(sky_rot_file):\n \"\"\"Read in the list of files and rotation angles.\"\"\"\n \n rotTab = Table.read(sky_rot_file, format='ascii', header_start=None)\n cols = list(rotTab.columns.keys())\n files = rotTab[cols[0]]\n angles = rotTab[cols[1]]\n\n return files, angles\n \n" ]
[ [ "numpy.argsort" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
MikeTrizna/lightning-flash
[ "8d68c32a20d5910a255b6fc9ef6851b091cb6ed6", "8d68c32a20d5910a255b6fc9ef6851b091cb6ed6" ]
[ "flash/audio/classification/input_transform.py", "tests/core/data/test_transforms.py" ]
[ "# Copyright The PyTorch Lightning team.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\nfrom dataclasses import dataclass\nfrom typing import Callable, Dict, Optional, Tuple\n\nimport torch\nfrom torch import nn\nfrom torch.utils.data._utils.collate import default_collate\n\nfrom flash.core.data.io.input import DataKeys\nfrom flash.core.data.io.input_transform import InputTransform\nfrom flash.core.data.transforms import ApplyToKeys, merge_transforms\nfrom flash.core.utilities.imports import _TORCHAUDIO_AVAILABLE, _TORCHVISION_AVAILABLE\n\nif _TORCHVISION_AVAILABLE:\n from torchvision import transforms as T\n\nif _TORCHAUDIO_AVAILABLE:\n from torchaudio import transforms as TAudio\n\n\ndef default_transforms(spectrogram_size: Tuple[int, int]) -> Dict[str, Callable]:\n \"\"\"The default transforms for audio classification for spectrograms: resize the spectrogram, convert the\n spectrogram and target to a tensor, and collate the batch.\"\"\"\n return {\n \"per_sample_transform\": nn.Sequential(\n ApplyToKeys(DataKeys.INPUT, T.Compose([T.ToTensor(), T.Resize(spectrogram_size)])),\n ApplyToKeys(DataKeys.TARGET, torch.as_tensor),\n ),\n \"collate\": default_collate,\n }\n\n\ndef train_default_transforms(\n spectrogram_size: Tuple[int, int], time_mask_param: Optional[int], freq_mask_param: Optional[int]\n) -> Dict[str, Callable]:\n \"\"\"During training we apply the default transforms with optional ``TimeMasking`` and ``Frequency Masking``.\"\"\"\n augs = []\n\n if time_mask_param is not None:\n augs.append(ApplyToKeys(DataKeys.INPUT, TAudio.TimeMasking(time_mask_param=time_mask_param)))\n\n if freq_mask_param is not None:\n augs.append(ApplyToKeys(DataKeys.INPUT, TAudio.FrequencyMasking(freq_mask_param=freq_mask_param)))\n\n if len(augs) > 0:\n return merge_transforms(default_transforms(spectrogram_size), {\"per_sample_transform\": nn.Sequential(*augs)})\n return default_transforms(spectrogram_size)\n\n\n@dataclass\nclass AudioClassificationInputTransform(InputTransform):\n\n spectrogram_size: Tuple[int, int] = (128, 128)\n time_mask_param: Optional[int] = None\n freq_mask_param: Optional[int] = None\n\n def train_input_per_sample_transform(self) -> Callable:\n transforms = []\n if self.time_mask_param is not None:\n transforms.append(TAudio.TimeMasking(time_mask_param=self.time_mask_param))\n\n if self.freq_mask_param is not None:\n transforms.append(TAudio.FrequencyMasking(freq_mask_param=self.freq_mask_param))\n\n transforms += [T.ToTensor(), T.Resize(self.spectrogram_size)]\n return T.Compose(transforms)\n\n def input_per_sample_transform(self) -> Callable:\n return T.Compose([T.ToTensor(), T.Resize(self.spectrogram_size)])\n\n def target_per_sample_transform(self) -> Callable:\n return torch.as_tensor\n", "# Copyright The PyTorch Lightning team.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\nfrom unittest.mock import Mock\n\nimport pytest\nimport torch\nfrom torch import nn\n\nfrom flash.core.data.io.input import DataKeys\nfrom flash.core.data.transforms import ApplyToKeys, kornia_collate, KorniaParallelTransforms, merge_transforms\nfrom flash.core.data.utils import convert_to_modules\n\n\nclass TestApplyToKeys:\n @pytest.mark.parametrize(\n \"sample, keys, expected\",\n [\n ({DataKeys.INPUT: \"test\"}, DataKeys.INPUT, \"test\"),\n (\n {DataKeys.INPUT: \"test_a\", DataKeys.TARGET: \"test_b\"},\n [DataKeys.INPUT, DataKeys.TARGET],\n [\"test_a\", \"test_b\"],\n ),\n ({\"input\": \"test\"}, \"input\", \"test\"),\n ({\"input\": \"test_a\", \"target\": \"test_b\"}, [\"input\", \"target\"], [\"test_a\", \"test_b\"]),\n ({\"input\": \"test_a\", \"target\": \"test_b\", \"extra\": \"...\"}, [\"input\", \"target\"], [\"test_a\", \"test_b\"]),\n ({\"input\": \"test_a\", \"target\": \"test_b\"}, [\"input\", \"target\", \"extra\"], [\"test_a\", \"test_b\"]),\n ({\"target\": \"...\"}, \"input\", None),\n ],\n )\n def test_forward(self, sample, keys, expected):\n transform = Mock(return_value=[\"out\"] * len(keys))\n ApplyToKeys(keys, transform)(sample)\n if expected is not None:\n transform.assert_called_once_with(expected)\n else:\n transform.assert_not_called()\n\n @pytest.mark.parametrize(\n \"transform, expected\",\n [\n (\n ApplyToKeys(DataKeys.INPUT, torch.nn.ReLU()),\n \"ApplyToKeys(keys=<DataKeys.INPUT: 'input'>, transform=ReLU())\",\n ),\n (\n ApplyToKeys([DataKeys.INPUT, DataKeys.TARGET], torch.nn.ReLU()),\n \"ApplyToKeys(keys=[<DataKeys.INPUT: 'input'>, \" \"<DataKeys.TARGET: 'target'>], transform=ReLU())\",\n ),\n (ApplyToKeys(\"input\", torch.nn.ReLU()), \"ApplyToKeys(keys='input', transform=ReLU())\"),\n (\n ApplyToKeys([\"input\", \"target\"], torch.nn.ReLU()),\n \"ApplyToKeys(keys=['input', 'target'], transform=ReLU())\",\n ),\n ],\n )\n def test_repr(self, transform, expected):\n assert repr(transform) == expected\n\n\[email protected](\"with_params\", [True, False])\ndef test_kornia_parallel_transforms(with_params):\n samples = [torch.rand(1, 3, 10, 10), torch.rand(1, 3, 10, 10)]\n transformed_sample = torch.rand(1, 3, 10, 10)\n\n transform_a = Mock(spec=torch.nn.Module, return_value=transformed_sample)\n transform_b = Mock(spec=torch.nn.Module)\n\n if with_params:\n transform_a._params = \"test\" # initialize params with some value\n\n parallel_transforms = KorniaParallelTransforms(transform_a, transform_b)\n parallel_transforms(samples)\n\n assert transform_a.call_count == 2\n assert transform_b.call_count == 2\n\n if with_params:\n assert transform_a.call_args_list[1][0][1] == \"test\"\n # check that after the forward `_params` is set to None\n assert transform_a._params == transform_a._params is None\n\n assert torch.allclose(transform_a.call_args_list[0][0][0], samples[0])\n assert torch.allclose(transform_a.call_args_list[1][0][0], samples[1])\n assert torch.allclose(transform_b.call_args_list[0][0][0], transformed_sample)\n assert torch.allclose(transform_b.call_args_list[1][0][0], transformed_sample)\n\n\ndef test_kornia_collate():\n samples = [\n {DataKeys.INPUT: torch.zeros(1, 3, 10, 10), DataKeys.TARGET: 1},\n {DataKeys.INPUT: torch.zeros(1, 3, 10, 10), DataKeys.TARGET: 2},\n {DataKeys.INPUT: torch.zeros(1, 3, 10, 10), DataKeys.TARGET: 3},\n ]\n\n result = kornia_collate(samples)\n assert torch.all(result[DataKeys.TARGET] == torch.tensor([1, 2, 3]))\n assert list(result[DataKeys.INPUT].shape) == [3, 3, 10, 10]\n assert torch.allclose(result[DataKeys.INPUT], torch.zeros(1))\n\n\n_MOCK_TRANSFORM = Mock()\n\n\[email protected](\n \"base_transforms, additional_transforms, expected_result\",\n [\n (\n {\"per_sample_transform\": _MOCK_TRANSFORM},\n {\"per_batch_transform\": _MOCK_TRANSFORM},\n {\"per_sample_transform\": _MOCK_TRANSFORM, \"per_batch_transform\": _MOCK_TRANSFORM},\n ),\n (\n {\"per_sample_transform\": _MOCK_TRANSFORM},\n {\"per_sample_transform\": _MOCK_TRANSFORM},\n {\n \"per_sample_transform\": nn.Sequential(\n convert_to_modules(_MOCK_TRANSFORM), convert_to_modules(_MOCK_TRANSFORM)\n )\n },\n ),\n (\n {\"per_sample_transform\": _MOCK_TRANSFORM},\n {\"per_sample_transform\": _MOCK_TRANSFORM, \"per_batch_transform\": _MOCK_TRANSFORM},\n {\n \"per_sample_transform\": nn.Sequential(\n convert_to_modules(_MOCK_TRANSFORM), convert_to_modules(_MOCK_TRANSFORM)\n ),\n \"per_batch_transform\": _MOCK_TRANSFORM,\n },\n ),\n (\n {\"per_sample_transform\": _MOCK_TRANSFORM, \"per_batch_transform\": _MOCK_TRANSFORM},\n {\"per_sample_transform\": _MOCK_TRANSFORM},\n {\n \"per_sample_transform\": nn.Sequential(\n convert_to_modules(_MOCK_TRANSFORM), convert_to_modules(_MOCK_TRANSFORM)\n ),\n \"per_batch_transform\": _MOCK_TRANSFORM,\n },\n ),\n ],\n)\ndef test_merge_transforms(base_transforms, additional_transforms, expected_result):\n result = merge_transforms(base_transforms, additional_transforms)\n assert result.keys() == expected_result.keys()\n for key in result:\n if result[key] == _MOCK_TRANSFORM:\n assert expected_result[key] == _MOCK_TRANSFORM\n elif isinstance(result[key], nn.Sequential):\n assert isinstance(expected_result[key], nn.Sequential)\n assert len(result[key]) == len(expected_result[key])\n for module, expected_module in zip(result[key], expected_result[key]):\n assert module.func == expected_module.func\n" ]
[ [ "torch.nn.Sequential" ], [ "torch.zeros", "torch.tensor", "torch.rand", "torch.allclose", "torch.nn.ReLU" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
hhzb123/UWSOD
[ "e3a708463734752597d8523b68338e35c6777575", "e3a708463734752597d8523b68338e35c6777575" ]
[ "projects/WSL/wsl/modeling/proposal_generator/proposal_utils.py", "projects/WSL/tools/proposal_convert.py" ]
[ "# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved\nimport logging\nimport math\nfrom typing import List, Tuple\nimport torch\n\nfrom detectron2.layers import batched_nms, cat\nfrom detectron2.structures import Boxes, Instances\nfrom detectron2.utils.events import get_event_storage\n\nlogger = logging.getLogger(__name__)\n\n\ndef find_top_rpn_proposals(\n proposals: List[torch.Tensor],\n pred_objectness_logits: List[torch.Tensor],\n image_sizes: List[Tuple[int, int]],\n nms_thresh: float,\n pre_nms_topk: int,\n post_nms_topk: int,\n min_box_size: float,\n training: bool,\n):\n \"\"\"\n For each feature map, select the `pre_nms_topk` highest scoring proposals,\n apply NMS, clip proposals, and remove small boxes. Return the `post_nms_topk`\n highest scoring proposals among all the feature maps for each image.\n\n Args:\n proposals (list[Tensor]): A list of L tensors. Tensor i has shape (N, Hi*Wi*A, 4).\n All proposal predictions on the feature maps.\n pred_objectness_logits (list[Tensor]): A list of L tensors. Tensor i has shape (N, Hi*Wi*A).\n image_sizes (list[tuple]): sizes (h, w) for each image\n nms_thresh (float): IoU threshold to use for NMS\n pre_nms_topk (int): number of top k scoring proposals to keep before applying NMS.\n When RPN is run on multiple feature maps (as in FPN) this number is per\n feature map.\n post_nms_topk (int): number of top k scoring proposals to keep after applying NMS.\n When RPN is run on multiple feature maps (as in FPN) this number is total,\n over all feature maps.\n min_box_size (float): minimum proposal box side length in pixels (absolute units\n wrt input images).\n training (bool): True if proposals are to be used in training, otherwise False.\n This arg exists only to support a legacy bug; look for the \"NB: Legacy bug ...\"\n comment.\n\n Returns:\n list[Instances]: list of N Instances. The i-th Instances\n stores post_nms_topk object proposals for image i, sorted by their\n objectness score in descending order.\n \"\"\"\n num_images = len(image_sizes)\n device = proposals[0].device\n\n # 1. Select top-k anchor for every level and every image\n topk_scores = [] # #lvl Tensor, each of shape N x topk\n topk_proposals = []\n level_ids = [] # #lvl Tensor, each of shape (topk,)\n batch_idx = torch.arange(num_images, device=device)\n for level_id, (proposals_i, logits_i) in enumerate(zip(proposals, pred_objectness_logits)):\n Hi_Wi_A = logits_i.shape[1]\n num_proposals_i = min(pre_nms_topk, Hi_Wi_A)\n\n # sort is faster than topk (https://github.com/pytorch/pytorch/issues/22812)\n # topk_scores_i, topk_idx = logits_i.topk(num_proposals_i, dim=1)\n logits_i, idx = logits_i.sort(descending=True, dim=1)\n topk_scores_i = logits_i[batch_idx, :num_proposals_i]\n topk_idx = idx[batch_idx, :num_proposals_i]\n\n # each is N x topk\n topk_proposals_i = proposals_i[batch_idx[:, None], topk_idx] # N x topk x 4\n\n topk_proposals.append(topk_proposals_i)\n topk_scores.append(topk_scores_i)\n level_ids.append(torch.full((num_proposals_i,), level_id, dtype=torch.int64, device=device))\n\n # 2. Concat all levels together\n topk_scores = cat(topk_scores, dim=1)\n topk_proposals = cat(topk_proposals, dim=1)\n level_ids = cat(level_ids, dim=0)\n\n # 3. For each image, run a per-level NMS, and choose topk results.\n results: List[Instances] = []\n for n, image_size in enumerate(image_sizes):\n boxes = Boxes(topk_proposals[n])\n scores_per_img = topk_scores[n]\n lvl = level_ids\n\n valid_mask = torch.isfinite(boxes.tensor).all(dim=1) & torch.isfinite(scores_per_img)\n if not valid_mask.all():\n if training:\n raise FloatingPointError(\n \"Predicted boxes or scores contain Inf/NaN. Training has diverged.\"\n )\n boxes = boxes[valid_mask]\n scores_per_img = scores_per_img[valid_mask]\n lvl = lvl[valid_mask]\n boxes.clip(image_size)\n\n # filter empty boxes\n keep = boxes.nonempty(threshold=min_box_size)\n if keep.sum().item() != len(boxes):\n boxes, scores_per_img, lvl = boxes[keep], scores_per_img[keep], lvl[keep]\n\n keep = batched_nms(boxes.tensor, scores_per_img, lvl, nms_thresh)\n # In Detectron1, there was different behavior during training vs. testing.\n # (https://github.com/facebookresearch/Detectron/issues/459)\n # During training, topk is over the proposals from *all* images in the training batch.\n # During testing, it is over the proposals for each image separately.\n # As a result, the training behavior becomes batch-dependent,\n # and the configuration \"POST_NMS_TOPK_TRAIN\" end up relying on the batch size.\n # This bug is addressed in Detectron2 to make the behavior independent of batch size.\n keep = keep[:post_nms_topk] # keep is already sorted\n\n res = Instances(image_size)\n res.proposal_boxes = boxes[keep]\n res.objectness_logits = scores_per_img[keep]\n res.level_ids = lvl[keep]\n results.append(res)\n return results\n\n\ndef find_top_rpn_proposals_group(\n proposals: List[torch.Tensor],\n pred_objectness_logits: List[torch.Tensor],\n image_sizes: List[Tuple[int, int]],\n num_anchors: List[int],\n nms_thresh: float,\n pre_nms_topk: int,\n post_nms_topk: int,\n min_box_size: float,\n training: bool,\n):\n \"\"\"\n For each feature map, select the `pre_nms_topk` highest scoring proposals,\n apply NMS, clip proposals, and remove small boxes. Return the `post_nms_topk`\n highest scoring proposals among all the feature maps for each image.\n\n Args:\n proposals (list[Tensor]): A list of L tensors. Tensor i has shape (N, Hi*Wi*A, 4).\n All proposal predictions on the feature maps.\n pred_objectness_logits (list[Tensor]): A list of L tensors. Tensor i has shape (N, Hi*Wi*A).\n image_sizes (list[tuple]): sizes (h, w) for each image\n nms_thresh (float): IoU threshold to use for NMS\n pre_nms_topk (int): number of top k scoring proposals to keep before applying NMS.\n When RPN is run on multiple feature maps (as in FPN) this number is per\n feature map.\n post_nms_topk (int): number of top k scoring proposals to keep after applying NMS.\n When RPN is run on multiple feature maps (as in FPN) this number is total,\n over all feature maps.\n min_box_size (float): minimum proposal box side length in pixels (absolute units\n wrt input images).\n training (bool): True if proposals are to be used in training, otherwise False.\n This arg exists only to support a legacy bug; look for the \"NB: Legacy bug ...\"\n comment.\n\n Returns:\n list[Instances]: list of N Instances. The i-th Instances\n stores post_nms_topk object proposals for image i, sorted by their\n objectness score in descending order.\n \"\"\"\n num_images = len(image_sizes)\n device = proposals[0].device\n num_preprepre_nms = 0\n num_prepre_nms = 0\n num_pre_nms = 0\n num_post_nms = 0\n\n # 1. Select top-k anchor for every level and every image\n topk_scores = [] # #lvl Tensor, each of shape N x topk\n topk_proposals = []\n level_ids = [] # #lvl Tensor, each of shape (topk,)\n batch_idx = torch.arange(num_images, device=device)\n for level_id, (proposals_i, logits_i) in enumerate(zip(proposals, pred_objectness_logits)):\n Hi_Wi_A = logits_i.shape[1]\n Hi_Wi = int(Hi_Wi_A / num_anchors[level_id])\n logits_i = logits_i.view(-1, Hi_Wi, num_anchors[level_id])\n proposals_i = proposals_i.view(-1, Hi_Wi, num_anchors[level_id], 4)\n num_preprepre_nms += Hi_Wi_A\n for anchor_id in range(num_anchors[level_id]):\n num_proposals_i_a = min(pre_nms_topk, Hi_Wi)\n\n logits_i_a = logits_i[:, :, anchor_id]\n proposals_i_a = proposals_i[:, :, anchor_id, :]\n\n if True and False:\n width_i_a = proposals_i_a[..., 2] - proposals_i_a[..., 0]\n height_i_a = proposals_i_a[..., 3] - proposals_i_a[..., 1]\n size_i_a = width_i_a * height_i_a\n aspect_i_a = width_i_a / height_i_a\n print(device, size_i_a.sqrt().mean(), size_i_a.mean().sqrt(), aspect_i_a.mean())\n\n # sort is faster than topk (https://github.com/pytorch/pytorch/issues/22812)\n # topk_scores_i, topk_idx = logits_i.topk(num_proposals_i, dim=1)\n logits_i_a, idx = logits_i_a.sort(descending=True, dim=1)\n topk_scores_i_a = logits_i_a[batch_idx, :num_proposals_i_a]\n topk_idx = idx[batch_idx, :num_proposals_i_a]\n\n # each is N x topk\n topk_proposals_i_a = proposals_i_a[batch_idx[:, None], topk_idx] # N x topk x 4\n\n topk_proposals.append(topk_proposals_i_a)\n topk_scores.append(topk_scores_i_a)\n level_ids.append(\n torch.full(\n (num_proposals_i_a,),\n level_id * 1000 + anchor_id,\n dtype=torch.int64,\n device=device,\n )\n )\n\n # 2. Concat all levels together\n topk_scores = cat(topk_scores, dim=1)\n topk_proposals = cat(topk_proposals, dim=1)\n level_ids = cat(level_ids, dim=0)\n\n # 3. For each image, run a per-level NMS, and choose topk results.\n results: List[Instances] = []\n for n, image_size in enumerate(image_sizes):\n boxes = Boxes(topk_proposals[n])\n scores_per_img = topk_scores[n]\n lvl = level_ids\n\n num_prepre_nms += len(boxes)\n\n valid_mask = torch.isfinite(boxes.tensor).all(dim=1) & torch.isfinite(scores_per_img)\n if not valid_mask.all():\n if training:\n raise FloatingPointError(\n \"Predicted boxes or scores contain Inf/NaN. Training has diverged.\"\n )\n boxes = boxes[valid_mask]\n scores_per_img = scores_per_img[valid_mask]\n lvl = lvl[valid_mask]\n boxes.clip(image_size)\n\n # filter empty boxes\n keep = boxes.nonempty(threshold=min_box_size)\n if keep.sum().item() != len(boxes):\n boxes, scores_per_img, lvl = boxes[keep], scores_per_img[keep], lvl[keep]\n\n num_pre_nms += keep.sum().item()\n keep = batched_nms(boxes.tensor, scores_per_img, lvl, nms_thresh)\n num_post_nms += keep.numel()\n # In Detectron1, there was different behavior during training vs. testing.\n # (https://github.com/facebookresearch/Detectron/issues/459)\n # During training, topk is over the proposals from *all* images in the training batch.\n # During testing, it is over the proposals for each image separately.\n # As a result, the training behavior becomes batch-dependent,\n # and the configuration \"POST_NMS_TOPK_TRAIN\" end up relying on the batch size.\n # This bug is addressed in Detectron2 to make the behavior independent of batch size.\n keep = keep[:post_nms_topk] # keep is already sorted\n # if keep.numel() > post_nms_topk:\n # keep = torch.multinomial(scores_per_img[keep] - scores_per_img[keep].min(), post_nms_topk)\n\n res = Instances(image_size)\n res.proposal_boxes = boxes[keep]\n res.objectness_logits = scores_per_img[keep]\n res.level_ids = lvl[keep]\n results.append(res)\n\n if training:\n storage = get_event_storage()\n storage.put_scalar(\"rpn/num_proposals_preprepre_nms\", num_preprepre_nms / num_images)\n storage.put_scalar(\"rpn/num_proposals_prepre_nms\", num_prepre_nms / num_images)\n storage.put_scalar(\"rpn/num_proposals_pre_nms\", num_pre_nms / num_images)\n storage.put_scalar(\"rpn/num_proposals_post_nms\", num_post_nms / num_images)\n\n return results\n\n\ndef add_ground_truth_to_proposals(gt_boxes, proposals):\n \"\"\"\n Call `add_ground_truth_to_proposals_single_image` for all images.\n\n Args:\n gt_boxes(list[Boxes]): list of N elements. Element i is a Boxes\n representing the gound-truth for image i.\n proposals (list[Instances]): list of N elements. Element i is a Instances\n representing the proposals for image i.\n\n Returns:\n list[Instances]: list of N Instances. Each is the proposals for the image,\n with field \"proposal_boxes\" and \"objectness_logits\".\n \"\"\"\n assert gt_boxes is not None\n\n assert len(proposals) == len(gt_boxes)\n if len(proposals) == 0:\n return proposals\n\n return [\n add_ground_truth_to_proposals_single_image(gt_boxes_i, proposals_i)\n for gt_boxes_i, proposals_i in zip(gt_boxes, proposals)\n ]\n\n\ndef add_ground_truth_to_proposals_single_image(gt_boxes, proposals):\n \"\"\"\n Augment `proposals` with ground-truth boxes from `gt_boxes`.\n\n Args:\n Same as `add_ground_truth_to_proposals`, but with gt_boxes and proposals\n per image.\n\n Returns:\n Same as `add_ground_truth_to_proposals`, but for only one image.\n \"\"\"\n device = proposals.objectness_logits.device\n # Assign all ground-truth boxes an objectness logit corresponding to\n # P(object) = sigmoid(logit) =~ 1.\n gt_logit_value = math.log((1.0 - 1e-10) / (1 - (1.0 - 1e-10)))\n gt_logits = gt_logit_value * torch.ones(len(gt_boxes), device=device)\n\n # Concatenating gt_boxes with proposals requires them to have the same fields\n gt_proposal = Instances(proposals.image_size)\n gt_proposal.proposal_boxes = gt_boxes\n gt_proposal.objectness_logits = gt_logits\n new_proposals = Instances.cat([proposals, gt_proposal])\n\n return new_proposals\n", "from __future__ import absolute_import, division, print_function, unicode_literals\nimport numpy as np\nimport os\nimport sys\nfrom multiprocessing import Pool\nfrom pathlib import Path\nimport cv2\nimport scipy.io as sio\nfrom six.moves import cPickle as pickle\nfrom tqdm import tqdm\n\nfrom detectron2.data.catalog import DatasetCatalog\n\nimport wsl.data.datasets\n\n\ndef convert_ss_box():\n dataset_name = sys.argv[1]\n file_in = sys.argv[2]\n file_out = sys.argv[3]\n\n dataset_dicts = DatasetCatalog.get(dataset_name)\n raw_data = sio.loadmat(file_in)[\"boxes\"].ravel()\n assert raw_data.shape[0] == len(dataset_dicts)\n\n boxes = []\n scores = []\n ids = []\n for i in range(len(dataset_dicts)):\n if i % 1000 == 0:\n print(\"{}/{}\".format(i + 1, len(dataset_dicts)))\n\n if \"flickr\" in dataset_name:\n index = os.path.basename(dataset_dicts[i][\"file_name\"])[:-4]\n elif \"coco\" in dataset_name:\n index = os.path.basename(dataset_dicts[i][\"file_name\"])[:-4]\n else:\n index = dataset_dicts[i][\"image_id\"]\n # selective search boxes are 1-indexed and (y1, x1, y2, x2)\n i_boxes = raw_data[i][:, (1, 0, 3, 2)] - 1\n # i_scores = np.zeros((i_boxes.shape[0]), dtype=np.float32)\n i_scores = np.ones((i_boxes.shape[0]), dtype=np.float32)\n\n boxes.append(i_boxes.astype(np.int16))\n scores.append(np.squeeze(i_scores.astype(np.float32)))\n index = dataset_dicts[i][\"image_id\"]\n ids.append(index)\n\n with open(file_out, \"wb\") as f:\n pickle.dump(dict(boxes=boxes, scores=scores, indexes=ids), f, pickle.HIGHEST_PROTOCOL)\n\n\ndef convert_mcg_box():\n dataset_name = sys.argv[1]\n dir_in = sys.argv[2]\n file_out = sys.argv[3]\n\n dataset_dicts = DatasetCatalog.get(dataset_name)\n\n boxes = []\n scores = []\n ids = []\n for i in range(len(dataset_dicts)):\n if i % 1000 == 0:\n print(\"{}/{}\".format(i + 1, len(dataset_dicts)))\n\n if \"flickr\" in dataset_name:\n index = os.path.basename(dataset_dicts[i][\"file_name\"])[:-4]\n elif \"coco\" in dataset_name:\n index = os.path.basename(dataset_dicts[i][\"file_name\"])[:-4]\n else:\n index = dataset_dicts[i][\"image_id\"]\n box_file = os.path.join(dir_in, \"{}.mat\".format(index))\n mat_data = sio.loadmat(box_file)\n if i == 0:\n print(mat_data.keys())\n if \"flickr\" in dataset_name:\n boxes_data = mat_data[\"bboxes\"]\n scores_data = mat_data[\"bboxes_scores\"]\n else:\n boxes_data = mat_data[\"boxes\"]\n scores_data = mat_data[\"scores\"]\n # selective search boxes are 1-indexed and (y1, x1, y2, x2)\n # Boxes from the MCG website are in (y1, x1, y2, x2) order\n boxes_data = boxes_data[:, (1, 0, 3, 2)] - 1\n # boxes_data_ = boxes_data.astype(np.uint16) - 1\n # boxes_data = boxes_data_[:, (1, 0, 3, 2)]\n\n boxes.append(boxes_data.astype(np.int16))\n scores.append(np.squeeze(scores_data.astype(np.float32)))\n index = dataset_dicts[i][\"image_id\"]\n ids.append(index)\n\n with open(file_out, \"wb\") as f:\n pickle.dump(dict(boxes=boxes, scores=scores, indexes=ids), f, pickle.HIGHEST_PROTOCOL)\n\n\n# for i in tqdm(range(len(dataset_dicts)), position=0):\ndef convert_mcg_seg_i(dataset_dict, dataset_name, dir_in, dir_out):\n\n if \"flickr\" in dataset_name:\n index = os.path.basename(dataset_dict[\"file_name\"])[:-4]\n elif \"coco\" in dataset_name:\n index = os.path.basename(dataset_dict[\"file_name\"])[:-4]\n else:\n index = dataset_dict[\"image_id\"]\n segm_file = os.path.join(dir_in, \"{}.mat\".format(index))\n print(segm_file)\n\n index = dataset_dict[\"image_id\"]\n save_path = os.path.join(dir_out, str(index) + \".pkl\")\n if os.path.isfile(save_path):\n return\n\n mat_data = sio.loadmat(segm_file)\n # print(mat_data.keys())\n # print('labels: ', mat_data['labels'])\n # print('scores: ', mat_data['scores'])\n # print('superpixels_i: ', mat_data['superpixels_i'])\n # print('labels: ',mat_data['labels'].shape)\n # print('scores: ', mat_data['scores'].shape)\n # print('superpixels_i: ', mat_data['superpixels_i'].shape)\n # print('superpixels_i: ', mat_data['superpixels_i'].max())\n # print('superpixels_i: ', mat_data['superpixels_i'].min())\n\n superpixels_i = mat_data[\"superpixels\"]\n labels_i = mat_data[\"labels\"]\n scores_i = mat_data[\"scores\"]\n\n # 1-based to 0-based\n superpixels_i = superpixels_i - 1\n\n mask_h, mask_w = superpixels_i.shape\n num_proposals = labels_i.shape[0]\n num_superpixels = superpixels_i.max() + 1\n\n boxes_i = np.zeros((num_proposals, 4), dtype=np.int16)\n oh_labels_i = np.zeros((num_proposals, num_superpixels), dtype=np.bool)\n\n poses = []\n for l in range(num_superpixels):\n pos = np.where(superpixels_i == l)\n poses.append(pos)\n\n # for j in tqdm(range(num_proposals), position=int(dataset_dict['image_id'])%20):\n for j in range(num_proposals):\n x1 = mask_w - 1\n y1 = mask_h - 1\n x2 = 0\n y2 = 0\n for label in labels_i[j]:\n for l in np.nditer(label):\n # 1-based to 0-based\n l = l - 1\n oh_labels_i[j, l] = 1\n\n pos = poses[l]\n\n y1 = min(y1, pos[0].min())\n x1 = min(x1, pos[1].min())\n y2 = max(y2, pos[0].max())\n x2 = max(x2, pos[1].max())\n\n boxes_i[j, 0] = x1\n boxes_i[j, 1] = y1\n boxes_i[j, 2] = x2\n boxes_i[j, 3] = y2\n\n if False:\n index = dataset_dict[\"image_id\"]\n home = str(Path.home())\n # for j in tqdm(range(num_proposals), position=1):\n for j in range(num_proposals):\n img = cv2.imread(dataset_dict[\"file_name\"])\n\n for l, v in enumerate(oh_labels_i[j]):\n if v == 0:\n continue\n pos = np.where(superpixels_i == l)\n\n img[pos] = 0\n\n cv2.rectangle(\n img,\n (boxes_i[j, 0], boxes_i[j, 1]),\n (boxes_i[j, 2], boxes_i[j, 3]),\n (0, 0, 255),\n thickness=4,\n )\n\n save_path = os.path.join(home, \"tmp\", str(index) + \"_\" + str(j) + \".png\")\n cv2.imwrite(save_path, img)\n\n index = dataset_dict[\"image_id\"]\n\n save_path = os.path.join(dir_out, str(index) + \".pkl\")\n with open(save_path, \"wb\") as f:\n pickle.dump(\n dict(\n superpixels=superpixels_i.astype(np.int16),\n oh_labels=oh_labels_i.astype(np.bool),\n scores=np.squeeze(scores_i.astype(np.float32)),\n boxes=boxes_i.astype(np.int16),\n indexes=index,\n ),\n f,\n pickle.HIGHEST_PROTOCOL,\n )\n\n\ndef convert_mcg_seg():\n dataset_name = sys.argv[1]\n dir_in = sys.argv[2]\n dir_out = sys.argv[3]\n\n if not os.path.isdir(dir_out):\n os.makedirs(dir_out)\n\n dataset_dicts = DatasetCatalog.get(dataset_name)\n\n process_pool = Pool(processes=32)\n\n arg_process = []\n for i in range(len(dataset_dicts)):\n arg_process.append((dataset_dicts[i], dataset_name, dir_in, dir_out))\n\n results = process_pool.starmap_async(convert_mcg_seg_i, arg_process)\n results = results.get()\n\n\ndef convert_mcg_seg2():\n dataset_name = sys.argv[1]\n dir_in = sys.argv[2]\n dir_out = sys.argv[3]\n\n if not os.path.isdir(dir_out):\n os.makedirs(dir_out)\n\n dataset_dicts = DatasetCatalog.get(dataset_name)\n\n for i in tqdm(range(len(dataset_dicts)), position=0):\n if \"flickr\" in dataset_name:\n index = os.path.basename(dataset_dicts[i][\"file_name\"])[:-4]\n elif \"coco\" in dataset_name:\n index = os.path.basename(dataset_dicts[i][\"file_name\"])[:-4]\n else:\n index = dataset_dicts[i][\"image_id\"]\n segm_file = os.path.join(dir_in, \"{}.mat\".format(index))\n mat_data = sio.loadmat(segm_file)\n # print(mat_data.keys())\n # print('labels: ', mat_data['labels'])\n # print('scores: ', mat_data['scores'])\n # print('superpixels: ', mat_data['superpixels'])\n # print('labels: ',mat_data['labels'].shape)\n # print('scores: ', mat_data['scores'].shape)\n # print('superpixels: ', mat_data['superpixels'].shape)\n # print('superpixels: ', mat_data['superpixels'].max())\n # print('superpixels: ', mat_data['superpixels'].min())\n\n superpixels = mat_data[\"superpixels\"]\n labels = mat_data[\"labels\"]\n scores = mat_data[\"scores\"]\n\n # 1-based to 0-based\n superpixels = superpixels - 1\n\n mask_h, mask_w = superpixels.shape\n num_proposals = labels.shape[0]\n num_superpixels = superpixels.max() + 1\n\n proposals = np.zeros((num_proposals, mask_h, mask_w), dtype=np.bool)\n boxes = np.zeros((num_proposals, 4), dtype=np.int16)\n oh_labels_i = np.zeros((num_proposals, num_superpixels), dtype=np.bool)\n\n poses = []\n for l in range(num_superpixels):\n pos = np.where(superpixels == l)\n poses.append(pos)\n\n for j in tqdm(range(num_proposals), position=1):\n x1 = mask_w - 1\n y1 = mask_h - 1\n x2 = 0\n y2 = 0\n for label in labels[j]:\n for l in np.nditer(label):\n # 1-based to 0-based\n l = l - 1\n oh_labels_i[j, l] = 1\n\n pos = poses[l]\n\n y1 = min(y1, pos[0].min())\n x1 = min(x1, pos[1].min())\n y2 = max(y2, pos[0].max())\n x2 = max(x2, pos[1].max())\n\n proposals[j][pos] = True\n\n boxes[j, 0] = x1\n boxes[j, 1] = y1\n boxes[j, 2] = x2\n boxes[j, 3] = y2\n\n if False:\n index = dataset_dicts[i][\"image_id\"]\n home = str(Path.home())\n for j in tqdm(range(num_proposals), position=1):\n img = cv2.imread(dataset_dicts[i][\"file_name\"])\n\n for l, v in enumerate(oh_labels_i[j]):\n if v == 0:\n continue\n pos = np.where(superpixels == l)\n\n img[pos] = 0\n\n cv2.rectangle(\n img,\n (boxes[j, 0], boxes[j, 1]),\n (boxes[j, 2], boxes[j, 3]),\n (0, 0, 255),\n thickness=4,\n )\n\n save_path = os.path.join(home, \"tmp\", str(index) + \"_\" + str(j) + \".png\")\n cv2.imwrite(save_path, img)\n\n index = dataset_dicts[i][\"image_id\"]\n\n save_path = os.path.join(dir_out, str(index) + \".pkl\")\n with open(save_path, \"wb\") as f:\n pickle.dump(\n dict(\n # proposals=np.packbits(proposals, axis=None),\n proposals=proposals.astype(np.bool),\n scores=scores.astype(np.float32),\n boxes=boxes.astype(np.int16),\n indexes=index,\n ),\n f,\n pickle.HIGHEST_PROTOCOL,\n )\n\n\nif __name__ == \"__main__\":\n if \"-proposals\" in sys.argv[2].lower():\n if \"mcg\" in sys.argv[3].lower():\n convert_mcg_seg()\n else:\n if \"ss\" in sys.argv[3].lower():\n convert_ss_box()\n elif \"mcg\" in sys.argv[3].lower():\n convert_mcg_box()\n" ]
[ [ "torch.isfinite", "torch.full", "torch.arange" ], [ "numpy.nditer", "scipy.io.loadmat", "numpy.ones", "numpy.where", "numpy.zeros" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [ "1.7", "1.0", "0.10", "1.2", "0.14", "0.19", "1.5", "0.12", "0.17", "0.13", "1.6", "1.4", "1.9", "1.3", "1.10", "0.15", "0.18", "0.16", "1.8" ], "tensorflow": [] } ]
jplauri/vaex
[ "e8cdd3a4a26a31aebfbacfba7e255ff16a8098fa", "e8cdd3a4a26a31aebfbacfba7e255ff16a8098fa" ]
[ "packages/vaex-hdf5/vaex/hdf5/export.py", "tests/isin_test.py" ]
[ "from __future__ import division, print_function\n__author__ = 'maartenbreddels'\nimport os\nimport sys\nimport collections\nimport numpy as np\nimport logging\nimport vaex\nimport vaex.utils\nimport vaex.execution\nimport vaex.export\nimport vaex.hdf5.dataset\nfrom vaex.column import ColumnStringArrow, str_type\n\nmax_length = int(1e5)\n\non_rtd = os.environ.get('READTHEDOCS', None) == 'True'\ntry:\n import h5py\nexcept:\n if not on_rtd:\n raise\n\nlogger = logging.getLogger(\"vaex.hdf5.export\")\n\nmax_int32 = 2**31-1\n\ndef export_hdf5_v1(dataset, path, column_names=None, byteorder=\"=\", shuffle=False, selection=False, progress=None, virtual=True):\n \"\"\"\n :param DatasetLocal dataset: dataset to export\n :param str path: path for file\n :param lis[str] column_names: list of column names to export or None for all columns\n :param str byteorder: = for native, < for little endian and > for big endian\n :param bool shuffle: export rows in random order\n :param bool selection: export selection or not\n :param progress: progress callback that gets a progress fraction as argument and should return True to continue,\n or a default progress bar when progress=True\n :param: bool virtual: When True, export virtual columns\n :return:\n \"\"\"\n\n if selection:\n if selection == True: # easier to work with the name\n selection = \"default\"\n # first open file using h5py api\n with h5py.File(path, \"w\") as h5file_output:\n\n h5data_output = h5file_output.require_group(\"data\")\n # i1, i2 = dataset.current_slice\n N = len(dataset) if not selection else dataset.selected_length(selection)\n if N == 0:\n raise ValueError(\"Cannot export empty table\")\n logger.debug(\"virtual=%r\", virtual)\n logger.debug(\"exporting %d rows to file %s\" % (N, path))\n # column_names = column_names or (dataset.get_column_names() + (list(dataset.virtual_columns.keys()) if virtual else []))\n column_names = column_names or dataset.get_column_names(virtual=virtual, strings=True)\n\n logger.debug(\"exporting columns(hdf5): %r\" % column_names)\n for column_name in column_names:\n dtype = dataset.dtype(column_name)\n if column_name in dataset.get_column_names(strings=True):\n column = dataset.columns[column_name]\n shape = (N,) + column.shape[1:]\n else:\n shape = (N,)\n if dtype.type == np.datetime64:\n array = h5file_output.require_dataset(\"/data/%s\" % column_name, shape=shape, dtype=np.int64)\n array.attrs[\"dtype\"] = dtype.name\n else:\n try:\n array = h5file_output.require_dataset(\"/data/%s\" % column_name, shape=shape, dtype=dtype.newbyteorder(byteorder))\n except:\n logging.exception(\"error creating dataset for %r, with type %r \" % (column_name, dtype))\n array[0] = array[0] # make sure the array really exists\n random_index_name = None\n column_order = list(column_names) # copy\n if shuffle:\n random_index_name = \"random_index\"\n while random_index_name in dataset.get_column_names():\n random_index_name += \"_new\"\n shuffle_array = h5file_output.require_dataset(\"/data/\" + random_index_name, shape=(N,), dtype=byteorder + \"i8\")\n shuffle_array[0] = shuffle_array[0]\n column_order.append(random_index_name) # last item\n h5data_output.attrs[\"column_order\"] = \",\".join(column_order) # keep track or the ordering of columns\n\n # after this the file is closed,, and reopen it using out class\n dataset_output = vaex.hdf5.dataset.Hdf5MemoryMapped(path, write=True)\n\n column_names = vaex.export._export(dataset_input=dataset, dataset_output=dataset_output, path=path, random_index_column=random_index_name,\n column_names=column_names, selection=selection, shuffle=shuffle, byteorder=byteorder,\n progress=progress)\n import getpass\n import datetime\n user = getpass.getuser()\n date = str(datetime.datetime.now())\n source = dataset.path\n description = \"file exported by vaex, by user %s, on date %s, from source %s\" % (user, date, source)\n if dataset.description:\n description += \"previous description:\\n\" + dataset.description\n dataset_output.copy_metadata(dataset)\n dataset_output.description = description\n logger.debug(\"writing meta information\")\n dataset_output.write_meta()\n dataset_output.close_files()\n return\n\n\ndef export_hdf5(dataset, path, column_names=None, byteorder=\"=\", shuffle=False, selection=False, progress=None, virtual=True, sort=None, ascending=True):\n \"\"\"\n :param DatasetLocal dataset: dataset to export\n :param str path: path for file\n :param lis[str] column_names: list of column names to export or None for all columns\n :param str byteorder: = for native, < for little endian and > for big endian\n :param bool shuffle: export rows in random order\n :param bool selection: export selection or not\n :param progress: progress callback that gets a progress fraction as argument and should return True to continue,\n or a default progress bar when progress=True\n :param: bool virtual: When True, export virtual columns\n :return:\n \"\"\"\n\n if selection:\n if selection == True: # easier to work with the name\n selection = \"default\"\n # first open file using h5py api\n with h5py.File(path, \"w\") as h5file_output:\n\n h5table_output = h5file_output.require_group(\"/table\")\n h5table_output.attrs[\"type\"] = \"table\"\n h5columns_output = h5file_output.require_group(\"/table/columns\")\n # i1, i2 = dataset.current_slice\n N = len(dataset) if not selection else dataset.selected_length(selection)\n if N == 0:\n raise ValueError(\"Cannot export empty table\")\n logger.debug(\"virtual=%r\", virtual)\n logger.debug(\"exporting %d rows to file %s\" % (N, path))\n # column_names = column_names or (dataset.get_column_names() + (list(dataset.virtual_columns.keys()) if virtual else []))\n column_names = column_names or dataset.get_column_names(virtual=virtual, strings=True, alias=False)\n\n logger.debug(\"exporting columns(hdf5): %r\" % column_names)\n sparse_groups = collections.defaultdict(list)\n sparse_matrices = {} # alternative to a set of matrices, since they are not hashable\n for column_name in list(column_names):\n sparse_matrix = dataset._sparse_matrix(column_name)\n if sparse_matrix is not None:\n # sparse columns are stored differently\n sparse_groups[id(sparse_matrix)].append(column_name)\n sparse_matrices[id(sparse_matrix)] = sparse_matrix\n continue\n dtype = dataset.dtype(column_name)\n if column_name in dataset.get_column_names(virtual=False, alias=False):\n column = dataset.columns[column_name]\n shape = (N,) + column.shape[1:]\n else:\n shape = (N,)\n h5column_output = h5columns_output.require_group(column_name)\n if dtype == str_type:\n # TODO: if no selection or filter, we could do this\n # if isinstance(column, ColumnStringArrow):\n # data_shape = column.bytes.shape\n # indices_shape = column.indices.shape\n # else:\n\n byte_length = dataset[column_name].str.byte_length().sum(selection=selection)\n if byte_length > max_int32:\n dtype_indices = 'i8'\n else:\n dtype_indices = 'i4'\n\n data_shape = (byte_length, )\n indices_shape = (N+1, )\n\n array = h5column_output.require_dataset('data', shape=data_shape, dtype='S1')\n if byte_length > 0:\n array[0] = array[0] # make sure the array really exists\n\n index_array = h5column_output.require_dataset('indices', shape=indices_shape, dtype=dtype_indices)\n index_array[0] = index_array[0] # make sure the array really exists\n\n null_value_count = N - dataset.count(column_name, selection=selection)\n if null_value_count > 0:\n null_shape = ((N + 7) // 8, ) # TODO: arrow requires padding right?\n null_bitmap_array = h5column_output.require_dataset('null_bitmap', shape=null_shape, dtype='u1')\n null_bitmap_array[0] = null_bitmap_array[0] # make sure the array really exists\n\n array.attrs[\"dtype\"] = 'str'\n # TODO: masked support ala arrow?\n else:\n if dtype.kind in 'mM':\n array = h5column_output.require_dataset('data', shape=shape, dtype=np.int64)\n array.attrs[\"dtype\"] = dtype.name\n elif dtype.kind == 'U':\n # numpy uses utf32 for unicode\n char_length = dtype.itemsize // 4\n shape = (N, char_length)\n array = h5column_output.require_dataset('data', shape=shape, dtype=np.uint8)\n array.attrs[\"dtype\"] = 'utf32'\n array.attrs[\"dlength\"] = char_length\n else:\n try:\n array = h5column_output.require_dataset('data', shape=shape, dtype=dtype.newbyteorder(byteorder))\n except:\n logging.exception(\"error creating dataset for %r, with type %r \" % (column_name, dtype))\n del h5columns_output[column_name]\n column_names.remove(column_name)\n array[0] = array[0] # make sure the array really exists\n\n data = dataset.evaluate(column_name, 0, 1, parallel=False)\n if np.ma.isMaskedArray(data):\n mask = h5column_output.require_dataset('mask', shape=shape, dtype=np.bool)\n mask[0] = mask[0] # make sure the array really exists\n random_index_name = None\n column_order = list(column_names) # copy\n if shuffle:\n random_index_name = \"random_index\"\n while random_index_name in dataset.get_column_names():\n random_index_name += \"_new\"\n shuffle_array = h5columns_output.require_dataset(random_index_name + \"/data\", shape=(N,), dtype=byteorder + \"i8\")\n shuffle_array[0] = shuffle_array[0]\n column_order.append(random_index_name) # last item\n h5columns_output.attrs[\"column_order\"] = \",\".join(column_order) # keep track or the ordering of columns\n\n sparse_index = 0\n for sparse_matrix in sparse_matrices.values():\n columns = sorted(sparse_groups[id(sparse_matrix)], key=lambda col: dataset.columns[col].column_index)\n name = \"sparse\" + str(sparse_index)\n sparse_index += 1\n # TODO: slice columns\n # sparse_matrix = sparse_matrix[:,]\n sparse_group = h5columns_output.require_group(name)\n sparse_group.attrs['type'] = 'csr_matrix'\n ar = sparse_group.require_dataset('data', shape=(len(sparse_matrix.data), ), dtype=sparse_matrix.dtype)\n ar[0] = ar[0]\n ar = sparse_group.require_dataset('indptr', shape=(len(sparse_matrix.indptr), ), dtype=sparse_matrix.indptr.dtype)\n ar[0] = ar[0]\n ar = sparse_group.require_dataset('indices', shape=(len(sparse_matrix.indices), ), dtype=sparse_matrix.indices.dtype)\n ar[0] = ar[0]\n for i, column_name in enumerate(columns):\n h5column = sparse_group.require_group(column_name)\n h5column.attrs['column_index'] = i\n\n # after this the file is closed,, and reopen it using out class\n dataset_output = vaex.hdf5.dataset.Hdf5MemoryMapped(path, write=True)\n\n column_names = vaex.export._export(dataset_input=dataset, dataset_output=dataset_output, path=path, random_index_column=random_index_name,\n column_names=column_names, selection=selection, shuffle=shuffle, byteorder=byteorder,\n progress=progress, sort=sort, ascending=ascending)\n import getpass\n import datetime\n user = getpass.getuser()\n date = str(datetime.datetime.now())\n source = dataset.path\n description = \"file exported by vaex, by user %s, on date %s, from source %s\" % (user, date, source)\n if dataset.description:\n description += \"previous description:\\n\" + dataset.description\n dataset_output.copy_metadata(dataset)\n dataset_output.description = description\n logger.debug(\"writing meta information\")\n dataset_output.write_meta()\n dataset_output.close_files()\n return\n", "import numpy as np\nimport vaex\n\n\ndef test_isin():\n x = np.array([1.01, 2.02, 3.03])\n y = np.array([1, 3, 5])\n z = np.array(['dog', 'cat', 'mouse'])\n w = np.array([2, '1.1', None])\n m = np.ma.MaskedArray(data=[np.nan, 1, 1], mask=[True, True, False])\n n = np.array([-5, np.nan, 1])\n df = vaex.from_arrays(x=x, y=y, z=z, w=w, m=m, n=n)\n\n assert df.x.isin([1, 2.02, 5, 6]).tolist() == [False, True, False]\n assert df.y.isin([5, -1, 0]).tolist() == [False, False, True]\n assert df.z.isin(['elephant', 'dog']).tolist() == [True, False, False]\n assert df.w.isin([2, None]) == [True, False, True]\n assert df.m.isin([1, 2, 3]) == [False, False, True]\n assert df.n.isin([2, np.nan]) == [False, True, False]\n\n\ndef test_isin_object():\n df = vaex.from_arrays(x=np.array(['a', 'b', 'c'], dtype='O'),\n y=np.array([1, 2, 3], dtype='O'))\n\n expr_x = df.x.isin(['a'])\n expr_y = df.y.isin([2])\n\n assert expr_x.tolist() == [True, False, False]\n assert expr_y.tolist() == [False, True, False]\n" ]
[ [ "numpy.ma.isMaskedArray" ], [ "numpy.array", "numpy.ma.MaskedArray" ] ]
[ { "matplotlib": [], "numpy": [ "1.10", "1.12", "1.11", "1.19", "1.13", "1.16", "1.9", "1.18", "1.20", "1.7", "1.15", "1.14", "1.17", "1.8" ], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [ "1.10", "1.12", "1.11", "1.19", "1.13", "1.16", "1.9", "1.18", "1.20", "1.7", "1.15", "1.14", "1.17", "1.8" ], "pandas": [], "scipy": [], "tensorflow": [] } ]
Lanxiaozhi/tianshou
[ "0fa3f4b7a256780448b7dcdbdbeb9daf7944f1d5" ]
[ "tianshou/policy/modelfree/a2c.py" ]
[ "import torch\nimport numpy as np\nfrom torch import nn\nimport torch.nn.functional as F\nfrom typing import Any, Dict, List, Type, Union, Optional\n\nfrom tianshou.policy import PGPolicy\nfrom tianshou.data import Batch, ReplayBuffer, to_torch_as, to_numpy\n\n\nclass A2CPolicy(PGPolicy):\n \"\"\"Implementation of Synchronous Advantage Actor-Critic. arXiv:1602.01783.\n\n :param torch.nn.Module actor: the actor network following the rules in\n :class:`~tianshou.policy.BasePolicy`. (s -> logits)\n :param torch.nn.Module critic: the critic network. (s -> V(s))\n :param torch.optim.Optimizer optim: the optimizer for actor and critic\n network.\n :param dist_fn: distribution class for computing the action.\n :type dist_fn: Type[torch.distributions.Distribution]\n :param float discount_factor: in [0, 1]. Default to 0.99.\n :param float vf_coef: weight for value loss. Default to 0.5.\n :param float ent_coef: weight for entropy loss. Default to 0.01.\n :param float max_grad_norm: clipping gradients in back propagation.\n Default to None.\n :param float gae_lambda: in [0, 1], param for Generalized Advantage\n Estimation. Default to 0.95.\n :param bool reward_normalization: normalize the reward to Normal(0, 1).\n Default to False.\n :param int max_batchsize: the maximum size of the batch when computing GAE,\n depends on the size of available memory and the memory cost of the\n model; should be as large as possible within the memory constraint.\n Default to 256.\n\n .. seealso::\n\n Please refer to :class:`~tianshou.policy.BasePolicy` for more detailed\n explanation.\n \"\"\"\n\n def __init__(\n self,\n actor: torch.nn.Module,\n critic: torch.nn.Module,\n optim: torch.optim.Optimizer,\n dist_fn: Type[torch.distributions.Distribution],\n discount_factor: float = 0.99,\n vf_coef: float = 0.5,\n ent_coef: float = 0.01,\n max_grad_norm: Optional[float] = None,\n gae_lambda: float = 0.95,\n reward_normalization: bool = False,\n max_batchsize: int = 256,\n **kwargs: Any\n ) -> None:\n super().__init__(None, optim, dist_fn, discount_factor, **kwargs)\n self.actor = actor\n self.critic = critic\n assert 0.0 <= gae_lambda <= 1.0, \"GAE lambda should be in [0, 1].\"\n self._lambda = gae_lambda\n self._weight_vf = vf_coef\n self._weight_ent = ent_coef\n self._grad_norm = max_grad_norm\n self._batch = max_batchsize\n self._rew_norm = reward_normalization\n\n def process_fn(\n self, batch: Batch, buffer: ReplayBuffer, indice: np.ndarray\n ) -> Batch:\n if self._lambda in [0.0, 1.0]:\n return self.compute_episodic_return(\n batch, buffer, indice,\n None, gamma=self._gamma, gae_lambda=self._lambda)\n v_ = []\n with torch.no_grad():\n for b in batch.split(self._batch, shuffle=False, merge_last=True):\n v_.append(to_numpy(self.critic(b.obs_next)))\n v_ = np.concatenate(v_, axis=0)\n return self.compute_episodic_return(\n batch, buffer, indice, v_,\n gamma=self._gamma, gae_lambda=self._lambda, rew_norm=self._rew_norm)\n\n def forward(\n self,\n batch: Batch,\n state: Optional[Union[dict, Batch, np.ndarray]] = None,\n **kwargs: Any\n ) -> Batch:\n \"\"\"Compute action over the given batch data.\n\n :return: A :class:`~tianshou.data.Batch` which has 4 keys:\n\n * ``act`` the action.\n * ``logits`` the network's raw output.\n * ``dist`` the action distribution.\n * ``state`` the hidden state.\n\n .. seealso::\n\n Please refer to :meth:`~tianshou.policy.BasePolicy.forward` for\n more detailed explanation.\n \"\"\"\n logits, h = self.actor(batch.obs, state=state, info=batch.info)\n if isinstance(logits, tuple):\n dist = self.dist_fn(*logits)\n else:\n dist = self.dist_fn(logits)\n act = dist.sample()\n return Batch(logits=logits, act=act, state=h, dist=dist)\n\n def learn( # type: ignore\n self, batch: Batch, batch_size: int, repeat: int, **kwargs: Any\n ) -> Dict[str, List[float]]:\n losses, actor_losses, vf_losses, ent_losses = [], [], [], []\n for _ in range(repeat):\n for b in batch.split(batch_size, merge_last=True):\n self.optim.zero_grad()\n dist = self(b).dist\n v = self.critic(b.obs).flatten()\n a = to_torch_as(b.act, v)\n r = to_torch_as(b.returns, v)\n log_prob = dist.log_prob(a).reshape(len(r), -1).transpose(0, 1)\n a_loss = -(log_prob * (r - v).detach()).mean()\n vf_loss = F.mse_loss(r, v) # type: ignore\n ent_loss = dist.entropy().mean()\n loss = a_loss + self._weight_vf * vf_loss - self._weight_ent * ent_loss\n loss.backward()\n if self._grad_norm is not None:\n nn.utils.clip_grad_norm_(\n list(self.actor.parameters()) + list(self.critic.parameters()),\n max_norm=self._grad_norm,\n )\n self.optim.step()\n actor_losses.append(a_loss.item())\n vf_losses.append(vf_loss.item())\n ent_losses.append(ent_loss.item())\n losses.append(loss.item())\n return {\n \"loss\": losses,\n \"loss/actor\": actor_losses,\n \"loss/vf\": vf_losses,\n \"loss/ent\": ent_losses,\n }\n" ]
[ [ "numpy.concatenate", "torch.nn.functional.mse_loss", "torch.no_grad" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
smithsophia1688/rm-cooperative-marl
[ "e9c782fa50957095dc025e16ff714e2fd19ee39e", "e9c782fa50957095dc025e16ff714e2fd19ee39e" ]
[ "src/experiments/iql.py", "src/Environments/rendezvous/gridworld_env.py" ]
[ "import numpy as np\nimport random, time\n\nfrom tester.tester import Tester\nfrom Agent.iqAgent import iqAgent\nfrom Environments.rendezvous.multi_agent_gridworld_env import MultiAgentGridWorldEnv\nfrom Environments.coop_buttons.multi_agent_buttons_env import MultiAgentButtonsEnv\nimport matplotlib.pyplot as plt\n\ndef run_iql_training(epsilon,\n tester,\n agent_list,\n show_print=True):\n \"\"\"\n This code runs one q-learning episode. q-functions, and accumulated reward values of agents\n are updated accordingly. If the appropriate number of steps have elapsed, this function will\n additionally run a test episode.\n\n Parameters\n ----------\n epsilon : float\n Numerical value in (0,1) representing likelihood of choosing a random action.\n tester : Tester object\n Object containing necessary information for current experiment.\n agent_list : list of Agent objects\n Agent objects to be trained and tested.\n show_print : bool\n Optional flag indicating whether or not to print output statements to terminal.\n \"\"\"\n # Initializing parameters and the game\n learning_params = tester.learning_params\n testing_params = tester.testing_params\n \n num_agents = len(agent_list)\n if tester.experiment == 'rendezvous':\n training_env = MultiAgentGridWorldEnv(tester.rm_test_file, num_agents, tester.env_settings)\n if tester.experiment == 'buttons':\n training_env = MultiAgentButtonsEnv(tester.rm_test_file, num_agents, tester.env_settings)\n\n for i in range(num_agents):\n agent_list[i].reset_state()\n\n s_team = np.full(num_agents, -1, dtype=int)\n a_team = np.full(num_agents, -1, dtype=int)\n testing_reward = 0\n\n num_steps = learning_params.max_timesteps_per_task\n\n for t in range(num_steps):\n # Update step count\n tester.add_step()\n\n # Perform a team step\n for i in range(num_agents):\n s = agent_list[i].s\n s_team[i] = s\n a_team[i] = agent_list[i].get_next_action(epsilon, learning_params)\n\n r, _, s_team_next = training_env.environment_step(s_team, a_team)\n\n for i in range(num_agents):\n # a = training_env.get_last_action(i)\n current_meta_state = training_env.get_meta_state(i)\n agent_list[i].update_agent(s_team_next[i], current_meta_state, a_team[i], r, learning_params, update_q_function=True)\n\n # If enough steps have elapsed, test and save the performance of the agents.\n if testing_params.test and tester.get_current_step() % testing_params.test_freq == 0:\n t_init = time.time()\n step = tester.get_current_step()\n\n agent_list_copy = []\n\n # Need to create a copy of the agent for testing. If we pass the agent directly\n # mid-episode to the test function, the test will reset the world-state and reward machine \n # state before the training episode has been completed.\n for i in range(num_agents):\n s_i = agent_list[i].s_i\n num_states = agent_list[i].num_states\n num_meta_states = agent_list[i].num_meta_states\n meta_state_i = agent_list[i].meta_state_i\n actions = agent_list[i].actions\n agent_id = agent_list[i].agent_id\n agent_copy = iqAgent(s_i, meta_state_i, num_states, num_meta_states, actions, agent_id)\n # Pass only the q-functions by reference so that the testing updates the original agent's q-function.\n agent_copy.q = agent_list[i].q\n\n agent_list_copy.append(agent_copy)\n\n # Run a test of the performance of the agents\n testing_reward, trajectory, testing_steps = run_iql_test(agent_list_copy,\n tester,\n learning_params,\n testing_params,\n show_print=show_print)\n \n if 0 not in tester.results.keys():\n tester.results[0] = {}\n if step not in tester.results[0]:\n tester.results[0][step] = []\n tester.results[0][step].append(testing_reward)\n\n # Save the testing trace\n if 'trajectories' not in tester.results.keys():\n tester.results['trajectories'] = {}\n if step not in tester.results['trajectories']:\n tester.results['trajectories'][step] = []\n tester.results['trajectories'][step].append(trajectory)\n\n # Save how many steps it took to complete the task\n if 'testing_steps' not in tester.results.keys():\n tester.results['testing_steps'] = {}\n if step not in tester.results['testing_steps']:\n tester.results['testing_steps'][step] = []\n tester.results['testing_steps'][step].append(testing_steps)\n\n if len(tester.steps) == 0 or tester.steps[-1] < step:\n tester.steps.append(step)\n\n # If the task is complete, update the meta controllers and stop trying to complete it.\n env_rm_state = training_env.u\n if training_env.reward_machine.is_terminal_state(env_rm_state):\n # Make sure we've run at least the minimum number of training steps before breaking the loop\n if tester.stop_task(t):\n break\n\n # checking the steps time-out\n if tester.stop_learning():\n break\n\ndef run_iql_test(agent_list,\n tester,\n learning_params,\n testing_params,\n show_print=True):\n \"\"\"\n Run a test of the hrl method with the current q-function. \n\n Parameters\n ----------\n agent_list : list of Agent objects\n Agent objects to be trained and tested.\n learning_params : LearningParameters object\n Object storing parameters to be used in learning.\n Testing_params : TestingParameters object\n Object storing parameters to be used in testing.\n\n Ouputs\n ------\n testing_reard : float\n Reward achieved by agent during this test episode.\n trajectory : list\n List of dictionaries containing information on current step of test.\n step : int\n Number of testing steps required to complete the task.\n \"\"\"\n num_agents = len(agent_list)\n if tester.experiment == 'rendezvous':\n testing_env = MultiAgentGridWorldEnv(tester.rm_test_file, num_agents, tester.env_settings)\n if tester.experiment == 'buttons':\n testing_env = MultiAgentButtonsEnv(tester.rm_test_file, num_agents, tester.env_settings)\n\n for i in range(num_agents):\n agent_list[i].reset_state()\n\n s_team = np.full(num_agents, -1, dtype=int)\n a_team = np.full(num_agents, -1, dtype=int)\n testing_reward = 0\n\n trajectory = []\n step = 0\n\n # Starting interaction with the environment\n for t in range(testing_params.num_steps):\n step = step + 1\n\n # Perform a team step\n for i in range(num_agents):\n s = agent_list[i].s\n s_team[i] = s\n a_team[i] = agent_list[i].get_next_action(-1.0, learning_params)\n\n # trajectory.append({'s' : np.array(s_team, dtype=int), 'a' : np.array(a_team, dtype=int), 'meta_state': testing_env.get_meta_state(i)})\n\n r, _, s_team_next = testing_env.environment_step(s_team, a_team)\n testing_reward = testing_reward + r\n\n for i in range(num_agents):\n # a = testing_env.get_last_action(i)\n current_meta_state = testing_env.get_meta_state(i)\n agent_list[i].update_agent(s_team_next[i], current_meta_state, a_team[i], r, learning_params, update_q_function=False)\n\n # If the task is complete, update all meta controllers and stop trying to complete it.\n env_rm_state = testing_env.u\n if testing_env.reward_machine.is_terminal_state(env_rm_state):\n break\n\n if show_print:\n print('Reward of {} achieved in {} steps. Current step: {} of {}'.format(testing_reward, step, tester.current_step, tester.total_steps))\n\n return testing_reward, trajectory, step\n\ndef run_iql_experiment(tester,\n num_agents,\n num_times,\n show_print=True):\n \"\"\"\n Run the entire q-learning with reward machines experiment a number of times specified by num_times.\n\n Inputs\n ------\n tester : Tester object\n Test object holding true reward machine and all information relating\n to the particular tasks, world, learning parameters, and experimental results.\n num_agents : int\n Number of agents in this experiment.\n num_times : int\n Number of times to run the entire experiment (restarting training from scratch).\n show_print : bool\n Flag indicating whether or not to output text to the terminal.\n \"\"\"\n \n learning_params = tester.learning_params\n\n for t in range(num_times):\n # Reseting default step values\n tester.restart()\n\n rm_test_file = tester.rm_test_file\n rm_learning_file_list = tester.rm_learning_file_list\n\n # Verify that the number of local reward machines matches the number of agents in the experiment.\n assertion_string = \"Number of specified local reward machines must match specified number of agents.\"\n assert (len(rm_learning_file_list) == num_agents), assertion_string\n\n if tester.experiment == 'rendezvous':\n testing_env = MultiAgentGridWorldEnv(rm_test_file, num_agents, tester.env_settings)\n if tester.experiment == 'buttons':\n testing_env = MultiAgentButtonsEnv(rm_test_file, num_agents, tester.env_settings)\n\n num_states = testing_env.num_states\n\n # Create the a list of agents for this experiment\n agent_list = [] \n for i in range(num_agents):\n # The actions available to individual agents should be specified by the TRUE multi-agent environment.\n actions = testing_env.get_actions(i)\n s_i = testing_env.get_initial_state(i)\n num_meta_states = testing_env.get_num_meta_states(i)\n meta_state_i = testing_env.get_meta_state(i)\n agent_list.append(iqAgent(s_i, meta_state_i, num_states, num_meta_states, actions, i))\n\n num_episodes = 0\n\n # Task loop\n epsilon = learning_params.initial_epsilon\n\n while not tester.stop_learning():\n num_episodes += 1\n\n epsilon = epsilon*0.99\n\n run_iql_training(epsilon,\n tester,\n agent_list,\n show_print=show_print)\n\n # Backing up the results\n print('Finished iteration ',t)\n\n tester.agent_list = agent_list\n\n plot_multi_agent_results(tester, num_agents)\n\ndef plot_multi_agent_results(tester, num_agents):\n \"\"\"\n Plot the results stored in tester.results for each of the agents.\n \"\"\"\n\n prc_25 = list()\n prc_50 = list()\n prc_75 = list()\n\n # Buffers for plots\n current_step = list()\n current_25 = list()\n current_50 = list()\n current_75 = list()\n steps = list()\n\n plot_dict = tester.results['testing_steps']\n\n for step in plot_dict.keys():\n if len(current_step) < 10:\n current_25.append(np.percentile(np.array(plot_dict[step]),25))\n current_50.append(np.percentile(np.array(plot_dict[step]),50))\n current_75.append(np.percentile(np.array(plot_dict[step]),75))\n current_step.append(sum(plot_dict[step])/len(plot_dict[step]))\n else:\n current_step.pop(0)\n current_25.pop(0)\n current_50.pop(0)\n current_75.pop(0)\n current_25.append(np.percentile(np.array(plot_dict[step]),25))\n current_50.append(np.percentile(np.array(plot_dict[step]),50))\n current_75.append(np.percentile(np.array(plot_dict[step]),75))\n current_step.append(sum(plot_dict[step])/len(plot_dict[step]))\n\n prc_25.append(sum(current_25)/len(current_25))\n prc_50.append(sum(current_50)/len(current_50))\n prc_75.append(sum(current_75)/len(current_75))\n steps.append(step)\n\n plt.plot(steps, prc_25, alpha=0)\n plt.plot(steps, prc_50, color='red')\n plt.plot(steps, prc_75, alpha=0)\n plt.grid()\n plt.fill_between(steps, prc_50, prc_25, color='red', alpha=0.25)\n plt.fill_between(steps, prc_50, prc_75, color='red', alpha=0.25)\n plt.ylabel('Testing Steps to Task Completion', fontsize=15)\n plt.xlabel('Training Steps', fontsize=15)\n plt.locator_params(axis='x', nbins=5)\n plt.show()", "import random, math, os\nimport numpy as np\nfrom enum import Enum\n\nimport sys\nsys.path.append('../')\nsys.path.append('../../')\nfrom reward_machines.sparse_reward_machine import SparseRewardMachine\n\n\"\"\"\nEnum with the actions that the agent can execute\n\"\"\"\nclass Actions(Enum):\n up = 0 # move up\n right = 1 # move right\n down = 2 # move down\n left = 3 # move left\n none = 4 # none \n\nclass GridWorldEnv:\n\n def __init__(self, rm_file, agent_id, env_settings):\n \"\"\"\n Initialize gridworld environment.\n\n Parameters\n ----------\n rm_file : string\n File path leading to the text file containing the reward machine\n encoding this environment's reward function.\n agent_id : int\n Index {0,1} indicating which agent\n env_settings : dict\n Dictionary of environment settings\n \"\"\"\n self.env_settings = env_settings\n self.agent_id = agent_id\n self._load_map()\n self.reward_machine = SparseRewardMachine(rm_file)\n\n self.u = self.reward_machine.get_initial_state()\n self.last_action = -1 # Initialize last action to garbage value\n\n def _load_map(self):\n \"\"\"\n Initialize the environment.\n \"\"\"\n self.Nr = self.env_settings['Nr']\n self.Nc = self.env_settings['Nc']\n\n initial_states = self.env_settings['initial_states']\n\n self.s_i = initial_states[self.agent_id-1]\n self.objects = {}\n self.objects[self.env_settings['rendezvous_loc']] = \"w\" # rendezvous location\n goal_locations = self.env_settings['goal_locations']\n self.objects[goal_locations[self.agent_id-1]] = \"g\" # goal location\n\n self.p = self.env_settings['p']\n \n self.num_states = self.Nr * self.Nc\n\n self.actions = [Actions.up.value, Actions.right.value, Actions.left.value, Actions.down.value, Actions.none.value]\n \n # Define forbidden transitions corresponding to map edges\n self.forbidden_transitions = set()\n \n for row in range(self.Nr):\n self.forbidden_transitions.add((row, 0, Actions.left)) # If in left-most column, can't move left.\n self.forbidden_transitions.add((row, self.Nc - 1, Actions.right)) # If in right-most column, can't move right.\n for col in range(self.Nc):\n self.forbidden_transitions.add((0, col, Actions.up)) # If in top row, can't move up\n self.forbidden_transitions.add((self.Nr - 1, col, Actions.down)) # If in bottom row, can't move down\n\n def environment_step(self, s, a):\n \"\"\"\n Execute action a from state s.\n\n Parameters\n ----------\n s : int\n Index representing the current environment state.\n a : int\n Index representing the action being taken.\n\n Outputs\n -------\n r : float\n Reward achieved by taking action a from state s.\n l : list\n List of events occuring at this step.\n s_next : int\n Index of next state.\n \"\"\"\n s_next, last_action = self.get_next_state(s,a)\n self.last_action = last_action\n\n l = self.get_mdp_label(s, s_next, self.u)\n r = 0\n\n for e in l:\n # Get the new reward machine state and the reward of this step\n u2 = self.reward_machine.get_next_state(self.u, e)\n r = r + self.reward_machine.get_reward(self.u, u2)\n # Update the reward machine state\n self.u = u2\n\n return r, l, s_next\n\n def get_mdp_label(self, s, s_next, u):\n \"\"\"\n \"\"\"\n row, col = self.get_state_description(s)\n row_next, col_next = self.get_state_description(s_next)\n\n l = []\n\n thresh = 0.3\n \n if u == 0 and (row_next, col_next) in self.objects:\n if self.objects[(row_next, col_next)] == 'w':\n l.append('r{}'.format(self.agent_id))\n elif u == 1:\n if not((row_next, col_next) in self.objects):\n l.append('l{}'.format(self.agent_id))\n elif self.objects[(row_next,col_next)] == 'w' and (row,col) in self.objects:\n if self.objects[(row,col)] == 'w' and np.random.random() <= thresh:\n l.append('r')\n elif u == 2:\n if (row_next, col_next) in self.objects:\n if self.objects[(row_next,col_next)] == 'g':\n l.append('g{}'.format(self.agent_id))\n return l\n\n def get_next_state(self, s, a):\n \"\"\"\n Get the next state in the environment given action a is taken from state s.\n Update the last action that was truly taken due to MDP slip.\n\n Parameters\n ----------\n s : int\n Index of the current state.\n a : int\n Action to be taken from state s.\n\n Outputs\n -------\n s_next : int\n Index of the next state.\n last_action :int\n Last action taken by agent due to slip proability.\n \"\"\"\n slip_p = [self.p, (1-self.p)/2, (1-self.p)/2]\n check = random.random()\n\n row, col = self.get_state_description(s)\n\n # up = 0\n # right = 1 \n # down = 2 \n # left = 3 \n\n if (check<=slip_p[0]) or (a == Actions.none.value):\n a_ = a\n\n elif (check>slip_p[0]) & (check<=(slip_p[0]+slip_p[1])):\n if a == 0: \n a_ = 3\n elif a == 2: \n a_ = 1\n elif a == 3: \n a_ = 2\n elif a == 1: \n a_ = 0\n\n else:\n if a == 0: \n a_ = 1\n elif a == 2: \n a_ = 3\n elif a == 3: \n a_ = 0\n elif a == 1: \n a_ = 2\n\n action_ = Actions(a_)\n if (row, col, action_) not in self.forbidden_transitions:\n if action_ == Actions.up:\n row -= 1\n if action_ == Actions.down:\n row += 1\n if action_ == Actions.left:\n col -= 1\n if action_ == Actions.right:\n col += 1\n\n s_next = self.get_state_from_description(row, col)\n\n last_action = a_\n return s_next, last_action\n\n def get_state_from_description(self, row, col):\n \"\"\"\n Given a (row, column) index description of gridworld location, return\n index of corresponding state.\n\n Parameters\n ----------\n row : int\n Index corresponding to the row location of the state in the gridworld.\n col : int\n Index corresponding to the column location of the state in the gridworld.\n \n Outputs\n -------\n s : int\n The index of the gridworld state corresponding to location (row, col).\n \"\"\"\n return self.Nc * row + col\n\n def get_state_description(self, s):\n \"\"\"\n Return the row and column indeces of state s in the gridworld.\n\n Parameters\n ----------\n s : int\n Index of the gridworld state.\n\n Outputs\n -------\n row : int\n The row index of state s in the gridworld.\n col : int\n The column index of state s in the gridworld.\n \"\"\"\n row = np.floor_divide(s, self.Nr)\n col = np.mod(s, self.Nc)\n\n return (row, col)\n\n def get_actions(self):\n \"\"\"\n Returns the list with the actions that the agent can perform\n \"\"\"\n return self.actions\n\n def get_last_action(self):\n \"\"\"\n Returns agent's last action\n \"\"\"\n return self.last_action\n\n def get_initial_state(self):\n \"\"\"\n Outputs\n -------\n s_i : int\n Index of agent's initial state.\n \"\"\"\n return self.s_i\n\n def show(self, s):\n \"\"\"\n Create a visual representation of the current state of the gridworld.\n\n Parameters\n ----------\n s : int\n Index of the current state\n \"\"\"\n display = np.zeros((self.Nr, self.Nc))\n \n # Display the location of key points in world\n for loc in self.objects.keys():\n display[loc] = 1\n\n # Display the location of the agent in the world\n row, col = self.get_state_description(s)\n display[row,col] = np.nan\n\n print(display)\n\ndef play():\n agent_id = 1\n\n # Set the environment settings for the experiment\n env_settings = dict()\n env_settings['Nr'] = 10\n env_settings['Nc'] = 10\n env_settings['initial_states'] = [0, 3, 20, 8, 90, 40, 70, 49, 96, 69]\n env_settings['rendezvous_loc'] = (3,4)\n env_settings['goal_locations'] = [(9,7), (7,9), (2,9), (9,9), (0,9), (7,0), (4,0), (5,0), (6,9), (8,0)]\n env_settings['p'] = 1.0\n\n base_file_dir = os.path.abspath(os.path.join(os.getcwd(), '../../..'))\n rm_string = os.path.join(base_file_dir, 'experiments', 'gridworld_many_agent_rendezvous', 'coordination_experiment_agent{}.txt'.format(agent_id))\n game = GridWorldEnv(rm_string, agent_id, env_settings)\n\n # User inputs\n str_to_action = {\"w\":Actions.up.value,\"d\":Actions.right.value,\"s\":Actions.down.value,\"a\":Actions.left.value,\"x\":Actions.none.value}\n\n s = game.get_initial_state()\n\n while True:\n # Showing game\n game.show(s)\n\n # Getting action\n print(\"\\nAction? \", end=\"\")\n a = input()\n print()\n # Executing action\n if a in str_to_action:\n r, l, s = game.environment_step(s, str_to_action[a])\n \n print(\"---------------------\")\n print(\"Next States: \", s)\n print(\"Label: \", l)\n print(\"Reward: \", r)\n print(\"RM state: \", game.u)\n print(\"---------------------\")\n\n if game.reward_machine.is_terminal_state(game.u): # Game Over\n break \n \n else:\n print(\"Forbidden action\")\n game.show(s)\n \n# This code allow to play a game (for debugging purposes)\nif __name__ == '__main__':\n play()" ]
[ [ "matplotlib.pyplot.locator_params", "numpy.full", "matplotlib.pyplot.plot", "matplotlib.pyplot.fill_between", "matplotlib.pyplot.grid", "matplotlib.pyplot.xlabel", "numpy.array", "matplotlib.pyplot.show", "matplotlib.pyplot.ylabel" ], [ "numpy.mod", "numpy.floor_divide", "numpy.random.random", "numpy.zeros" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
icoxfog417/cartpole-q-learning
[ "54ae9de6c488cbbff9bda1be11fd0ecd1e681049" ]
[ "agent.py" ]
[ "import random\nimport copy\nfrom collections import defaultdict\nfrom collections import deque\nfrom collections import namedtuple\nimport numpy as np\n\n\nclass Q():\n\n def __init__(self, n_actions, observation_space, bin_size, low_bound=None, high_bound=None, initial_mean=0.0, initial_std=0.0):\n self.n_actions = n_actions\n self._observation_dimension = 1\n for d in observation_space.shape:\n self._observation_dimension *= d\n\n self._bin_sizes = bin_size if isinstance(bin_size, list) else [bin_size] * self._observation_dimension\n self._dimension_bins = []\n for i, low, high in self._low_high_iter(observation_space, low_bound, high_bound):\n b_size = self._bin_sizes[i]\n bins = self._make_bins(low, high, b_size)\n self._dimension_bins.append(bins)\n\n # if we encounter the new observation, we initialize action evaluations\n self.table = defaultdict(lambda: initial_std * np.random.randn(self.n_actions) + initial_mean)\n \n @classmethod\n def _make_bins(cls, low, high, bin_size):\n bins = np.arange(low, high, (float(high) - float(low)) / (bin_size - 2)) # exclude both ends\n if min(bins) < 0 and 0 not in bins:\n bins = np.sort(np.append(bins, [0])) # 0 centric bins\n return bins\n \n @classmethod\n def _low_high_iter(cls, observation_space, low_bound, high_bound):\n lows = observation_space.low\n highs = observation_space.high\n for i in range(len(lows)):\n low = lows[i]\n if low_bound is not None:\n _low_bound = low_bound if not isinstance(low_bound, list) else low_bound[i]\n low = low if _low_bound is None else max(low, _low_bound)\n \n high = highs[i]\n if high_bound is not None:\n _high_bound = high_bound if not isinstance(high_bound, list) else high_bound[i]\n high = high if _high_bound is None else min(high, _high_bound)\n \n yield i, low, high\n\n def observation_to_state(self, observation):\n state = 0\n # caution: bin_size over 10 will not work accurately\n unit = max(self._bin_sizes)\n for d, o in enumerate(observation.flatten()):\n state = state + np.digitize(o, self._dimension_bins[d]) * pow(unit, d) # bin_size numeral system\n return state\n \n def values(self, observation):\n state = self.observation_to_state(observation)\n return self.table[state]\n\n\nclass Agent():\n\n def __init__(self, q, epsilon=0.05):\n self.q = q\n self.epsilon = epsilon\n \n def act(self, observation):\n action = -1\n if np.random.random() < self.epsilon:\n action = np.random.choice(self.q.n_actions)\n else:\n action = np.argmax(self.q.values(observation))\n \n return action\n\n\nclass Trainer():\n\n def __init__(self, agent, gamma=0.95, learning_rate=0.1, learning_rate_decay=None, epsilon=0.05, epsilon_decay=None, max_step=-1):\n self.agent = agent\n self.gamma = gamma\n self.learning_rate = learning_rate\n self.learning_rate_decay = learning_rate_decay\n self.epsilon = epsilon\n self.epsilon_decay = epsilon_decay\n self.max_step = max_step\n\n def train(self, env, episode_count, render=False):\n default_epsilon = self.agent.epsilon\n self.agent.epsilon = self.epsilon\n values = []\n steps = deque(maxlen=100)\n lr = self.learning_rate\n for i in range(episode_count):\n obs = env.reset()\n step = 0\n done = False\n while not done:\n if render:\n env.render()\n\n action = self.agent.act(obs)\n next_obs, reward, done, _ = env.step(action)\n\n state = self.agent.q.observation_to_state(obs)\n future = 0 if done else np.max(self.agent.q.values(next_obs))\n value = self.agent.q.table[state][action]\n self.agent.q.table[state][action] += lr * (reward + self.gamma * future - value)\n\n obs = next_obs\n values.append(value)\n step += 1\n if self.max_step > 0 and step > self.max_step:\n done = True\n else:\n mean = np.mean(values)\n steps.append(step)\n mean_step = np.mean(steps)\n print(\"Episode {}: {}steps(avg{}). epsilon={:.3f}, lr={:.3f}, mean q value={:.2f}\".format(\n i, step, mean_step, self.agent.epsilon, lr, mean)\n )\n \n if self.epsilon_decay is not None: \n self.agent.epsilon = self.epsilon_decay(self.agent.epsilon, i)\n if self.learning_rate_decay is not None:\n lr = self.learning_rate_decay(lr, i)\n" ]
[ [ "numpy.random.random", "numpy.random.choice", "numpy.append", "numpy.mean", "numpy.random.randn", "numpy.digitize" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
jinliangwei/tensor2tensor
[ "c42797065738504d7f032d0a13f2dd5190bfb20f", "c42797065738504d7f032d0a13f2dd5190bfb20f" ]
[ "tensor2tensor/utils/trainer_lib.py", "tensor2tensor/rl/trainer_model_free.py" ]
[ "# coding=utf-8\n# Copyright 2018 The Tensor2Tensor Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"Library for training. See t2t_trainer.py.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport json\nimport os\nimport random\nimport numpy as np\n\nfrom tensor2tensor.utils import decoding\nfrom tensor2tensor.utils import devices\nfrom tensor2tensor.utils import metrics_hook\nfrom tensor2tensor.utils import registry\nfrom tensor2tensor.utils import t2t_model\n\nimport tensorflow as tf\n\nfrom tensorflow.core.protobuf import rewriter_config_pb2\nfrom tensorflow.python import debug\n\n\ndef next_checkpoint(model_dir, timeout_mins=120):\n \"\"\"Yields successive checkpoints from model_dir.\"\"\"\n last_ckpt = None\n while True:\n last_ckpt = tf.contrib.training.wait_for_new_checkpoint(\n model_dir, last_ckpt, seconds_to_sleep=60, timeout=60 * timeout_mins)\n\n if last_ckpt is None:\n tf.logging.info(\n \"Eval timeout: no new checkpoints within %dm\" % timeout_mins)\n break\n\n yield last_ckpt\n\n\ndef create_session_config(log_device_placement=False,\n enable_graph_rewriter=False,\n gpu_mem_fraction=0.95,\n use_tpu=False,\n inter_op_parallelism_threads=0,\n intra_op_parallelism_threads=0):\n \"\"\"The TensorFlow Session config to use.\"\"\"\n if use_tpu:\n graph_options = tf.GraphOptions()\n else:\n if enable_graph_rewriter:\n rewrite_options = rewriter_config_pb2.RewriterConfig()\n rewrite_options.layout_optimizer = rewriter_config_pb2.RewriterConfig.ON\n graph_options = tf.GraphOptions(rewrite_options=rewrite_options)\n else:\n graph_options = tf.GraphOptions(\n optimizer_options=tf.OptimizerOptions(\n opt_level=tf.OptimizerOptions.L1, do_function_inlining=False))\n\n gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=gpu_mem_fraction)\n\n config = tf.ConfigProto(\n allow_soft_placement=True,\n graph_options=graph_options,\n gpu_options=gpu_options,\n log_device_placement=log_device_placement,\n inter_op_parallelism_threads=inter_op_parallelism_threads,\n intra_op_parallelism_threads=intra_op_parallelism_threads)\n return config\n\n\ndef create_hparams(hparams_set,\n hparams_overrides_str=\"\",\n data_dir=None,\n problem_name=None):\n \"\"\"Create HParams with data_dir and problem hparams, if kwargs provided.\"\"\"\n print(\"create_hparams called, hparams_set = \", hparams_set)\n\n hparams = registry.hparams(hparams_set)\n if data_dir:\n hparams.add_hparam(\"data_dir\", data_dir)\n if problem_name:\n add_problem_hparams(hparams, problem_name)\n if hparams_overrides_str:\n tf.logging.info(\"Overriding hparams in %s with %s\", hparams_set,\n hparams_overrides_str)\n hparams = hparams.parse(hparams_overrides_str)\n return hparams\n\n\ndef is_cloud_async_distributed():\n return (\"chief\" in\n json.loads(os.environ.get(\"TF_CONFIG\", \"{}\")).get(\"cluster\", {}))\n\n\ndef create_run_config(master=\"\",\n model_dir=None,\n iterations_per_loop=1000,\n num_shards=8,\n log_device_placement=False,\n save_checkpoints_steps=1000,\n save_checkpoints_secs=None,\n keep_checkpoint_max=20,\n keep_checkpoint_every_n_hours=10000,\n num_gpus=1,\n gpu_order=\"\",\n shard_to_cpu=False,\n num_async_replicas=1,\n enable_graph_rewriter=False,\n gpu_mem_fraction=0.95,\n no_data_parallelism=False,\n daisy_chain_variables=True,\n schedule=\"continuous_train_and_eval\",\n worker_job=\"/job:localhost\",\n worker_id=0,\n ps_replicas=0,\n ps_job=\"/job:ps\",\n ps_gpu=0,\n random_seed=None,\n sync=False,\n tpu_infeed_sleep_secs=None,\n use_tpu=False,\n use_tpu_estimator=False,\n inter_op_parallelism_threads=0,\n log_step_count_steps=100,\n intra_op_parallelism_threads=0,\n tpu_config_extra_kwargs=None,\n cloud_tpu_name=\"\"):\n \"\"\"Create RunConfig, TPUConfig, and Parallelism object.\"\"\"\n session_config = create_session_config(\n log_device_placement=log_device_placement,\n enable_graph_rewriter=enable_graph_rewriter,\n gpu_mem_fraction=gpu_mem_fraction,\n use_tpu=use_tpu,\n inter_op_parallelism_threads=inter_op_parallelism_threads,\n intra_op_parallelism_threads=intra_op_parallelism_threads)\n run_config_args = {\n \"master\": master,\n \"evaluation_master\": master,\n \"model_dir\": model_dir,\n \"session_config\": session_config,\n \"save_summary_steps\": 100,\n \"save_checkpoints_steps\": save_checkpoints_steps,\n \"save_checkpoints_secs\": save_checkpoints_secs,\n \"keep_checkpoint_max\": keep_checkpoint_max,\n \"keep_checkpoint_every_n_hours\": keep_checkpoint_every_n_hours,\n \"tf_random_seed\": random_seed,\n \"log_step_count_steps\": log_step_count_steps\n }\n if save_checkpoints_secs:\n del run_config_args[\"save_checkpoints_steps\"]\n run_config_cls = tf.contrib.learn.RunConfig\n\n if use_tpu or use_tpu_estimator:\n # If using TPUEstimator, use TPU RunConfig, add TPUConfig, and add\n # additional args.\n tpu_config_kwargs = {\n \"iterations_per_loop\": iterations_per_loop,\n \"num_shards\": num_shards,\n \"per_host_input_for_training\": True,\n \"initial_infeed_sleep_secs\": tpu_infeed_sleep_secs,\n }\n if tpu_config_extra_kwargs is not None:\n tpu_config_kwargs.update(tpu_config_extra_kwargs)\n run_config_cls = tf.contrib.tpu.RunConfig\n tpu_config = tf.contrib.tpu.TPUConfig(\n **tpu_config_kwargs)\n run_config_args[\"tpu_config\"] = tpu_config\n if not master and \"KUBE_GOOGLE_CLOUD_TPU_ENDPOINTS\" in os.environ:\n # If running on TPU but no master is set and the KUBE env var is present\n # then we're running on ML Engine. Set the master.\n run_config_args[\"master\"] = os.environ[\n \"KUBE_GOOGLE_CLOUD_TPU_ENDPOINTS\"]\n run_config_args[\"evaluation_master\"] = run_config_args[\"master\"]\n elif not master and cloud_tpu_name:\n # Update run_config to use cluster instead of master/evaluation_master\n # as we need the cluster spec to use Cloud Pods\n tpu_cluster_resolver = tf.contrib.cluster_resolver.TPUClusterResolver(\n cloud_tpu_name)\n run_config_args[\"cluster\"] = tpu_cluster_resolver\n del run_config_args[\"master\"]\n del run_config_args[\"evaluation_master\"]\n elif is_cloud_async_distributed():\n run_config_cls = tf.estimator.RunConfig\n del run_config_args[\"master\"]\n del run_config_args[\"evaluation_master\"]\n\n config = run_config_cls(**run_config_args)\n\n # If not using TPU, add device info for data_parallelism\n config.use_tpu = use_tpu\n if not use_tpu:\n config.t2t_device_info = {\n \"num_async_replicas\": num_async_replicas,\n }\n config.data_parallelism = devices.data_parallelism(\n daisy_chain_variables=daisy_chain_variables,\n ps_replicas=ps_replicas,\n ps_job=ps_job,\n ps_gpu=ps_gpu,\n schedule=schedule,\n sync=sync,\n worker_gpu=num_gpus,\n worker_replicas=num_async_replicas,\n worker_id=worker_id,\n gpu_order=gpu_order,\n locally_shard_to_cpu=shard_to_cpu,\n worker_job=worker_job,\n no_data_parallelism=no_data_parallelism)\n\n return config\n\n\ndef create_estimator(model_name,\n hparams,\n run_config,\n schedule=\"train_and_evaluate\",\n decode_hparams=None,\n use_tpu=False,\n use_tpu_estimator=False,\n use_xla=False):\n \"\"\"Create a T2T Estimator.\"\"\"\n tf.logging.info(\"create_estimator, model_name = %s\" % model_name)\n model_fn = t2t_model.T2TModel.make_estimator_model_fn(\n model_name, hparams, decode_hparams=decode_hparams)\n\n del use_xla\n if use_tpu or use_tpu_estimator:\n problem = hparams.problem\n batch_size = (\n problem.tpu_batch_size_per_shard(hparams) *\n run_config.tpu_config.num_shards)\n if getattr(hparams, \"mtf_mode\", False):\n batch_size = problem.tpu_batch_size_per_shard(hparams)\n predict_batch_size = batch_size\n if decode_hparams and decode_hparams.batch_size:\n predict_batch_size = decode_hparams.batch_size\n estimator = tf.contrib.tpu.TPUEstimator(\n model_fn=model_fn,\n model_dir=run_config.model_dir,\n config=run_config,\n use_tpu=use_tpu,\n train_batch_size=batch_size,\n eval_batch_size=batch_size if \"eval\" in schedule else None,\n predict_batch_size=predict_batch_size)\n else:\n estimator = tf.estimator.Estimator(\n model_fn=model_fn,\n model_dir=run_config.model_dir,\n config=run_config,\n )\n return estimator\n\n\ndef create_hooks(use_tfdbg=False,\n use_dbgprofile=False,\n dbgprofile_kwargs=None,\n use_validation_monitor=False,\n validation_monitor_kwargs=None,\n use_early_stopping=False,\n early_stopping_kwargs=None):\n \"\"\"Create train and eval hooks for Experiment.\"\"\"\n train_hooks = []\n eval_hooks = []\n\n if use_tfdbg:\n hook = debug.LocalCLIDebugHook()\n train_hooks.append(hook)\n eval_hooks.append(hook)\n\n if use_dbgprofile:\n # Recorded traces can be visualized with chrome://tracing/\n # The memory/tensor lifetime is also profiled\n tf.logging.info(\"Using ProfilerHook\")\n defaults = dict(save_steps=10, show_dataflow=True, show_memory=True)\n defaults.update(dbgprofile_kwargs)\n train_hooks.append(tf.train.ProfilerHook(**defaults))\n\n if use_validation_monitor:\n tf.logging.info(\"Using ValidationMonitor\")\n train_hooks.append(\n tf.contrib.learn.monitors.ValidationMonitor(\n hooks=eval_hooks, **validation_monitor_kwargs))\n\n if use_early_stopping:\n tf.logging.info(\"Using EarlyStoppingHook\")\n hook = metrics_hook.EarlyStoppingHook(**early_stopping_kwargs)\n # Adding to both training and eval so that eval aborts as well\n train_hooks.append(hook)\n eval_hooks.append(hook)\n\n return train_hooks, eval_hooks\n\n\nclass T2TExperiment(object):\n \"\"\"Custom Experiment class for running distributed experiments.\"\"\"\n\n def __init__(self, estimator, hparams, train_spec, eval_spec,\n use_validation_monitor, decode_hparams=None, server=None):\n self._train_spec = train_spec\n self._eval_spec = eval_spec\n self._hparams = hparams\n self._decode_hparams = decode_hparams\n self._estimator = estimator\n self._use_validation_monitor = use_validation_monitor\n self._server = server\n\n @property\n def estimator(self):\n return self._estimator\n\n @property\n def train_steps(self):\n return self._train_spec.max_steps\n\n @property\n def eval_steps(self):\n return self._eval_spec.steps\n\n def continuous_train_and_eval(self, continuous_eval_predicate_fn=None):\n del continuous_eval_predicate_fn\n tf.estimator.train_and_evaluate(self._estimator, self._train_spec,\n self._eval_spec)\n return self.evaluate()\n\n def train_and_evaluate(self):\n if self._use_validation_monitor:\n tf.logging.warning(\"EvalSpec not provided. Estimator will not manage \"\n \"model evaluation. Assuming ValidationMonitor present \"\n \"in train_hooks.\")\n self.train()\n\n def train(self, max_steps=None):\n self._estimator.train(\n self._train_spec.input_fn,\n hooks=self._train_spec.hooks,\n max_steps=max_steps or self._train_spec.max_steps)\n\n def evaluate(self):\n return self._estimator.evaluate(\n self._eval_spec.input_fn,\n steps=self._eval_spec.steps,\n hooks=self._eval_spec.hooks)\n\n def evaluate_on_train_data(self):\n self._estimator.evaluate(\n self._train_spec.input_fn,\n steps=self._eval_spec.steps,\n hooks=self._eval_spec.hooks,\n name=\"eval_train\")\n\n def continuous_eval(self):\n \"\"\"Evaluate until checkpoints stop being produced.\"\"\"\n for _ in next_checkpoint(self._hparams.model_dir):\n self.evaluate()\n\n def continuous_eval_on_train_data(self):\n \"\"\"Evaluate on train data until checkpoints stop being produced.\"\"\"\n for _ in next_checkpoint(self._hparams.model_dir):\n self.evaluate_on_train_data()\n\n def test(self):\n \"\"\"Perform 1 step of train and 2 step of eval.\"\"\"\n if self._use_validation_monitor:\n return self.train_and_evaluate()\n\n self._estimator.train(\n self._train_spec.input_fn, hooks=self._train_spec.hooks, max_steps=1)\n\n self._estimator.evaluate(\n self._eval_spec.input_fn, steps=1, hooks=self._eval_spec.hooks)\n\n def run_std_server(self):\n \"\"\"Starts a TensorFlow server and joins the serving thread.\n\n Typically used for parameter servers.\n\n Raises:\n ValueError: if not enough information is available in the estimator's\n config to create a server.\n \"\"\"\n tf.logging.info(\"run_std_server called\")\n config = tf.estimator.RunConfig()\n server = tf.train.Server(\n config.cluster_spec,\n job_name=config.task_type,\n task_index=config.task_id,\n protocol=self._hparams.std_server_protocol)\n server.join()\n\n def decode(self, dataset_split=None, decode_from_file=False):\n \"\"\"Decodes from dataset or file.\"\"\"\n if decode_from_file:\n decoding.decode_from_file(self._estimator,\n self._decode_hparams.decode_from_file,\n self._hparams,\n self._decode_hparams,\n self._decode_hparams.decode_to_file)\n else:\n decoding.decode_from_dataset(self._estimator,\n self._hparams.problem.name,\n self._hparams,\n self._decode_hparams,\n dataset_split=dataset_split)\n\n def continuous_decode(self):\n \"\"\"Decode from dataset on new checkpoint.\"\"\"\n for _ in next_checkpoint(self._hparams.model_dir):\n self.decode()\n\n def continuous_decode_on_train_data(self):\n \"\"\"Decode from dataset on new checkpoint.\"\"\"\n for _ in next_checkpoint(self._hparams.model_dir):\n self.decode(dataset_split=tf.estimator.ModeKeys.TRAIN)\n\n def continuous_decode_on_eval_data(self):\n \"\"\"Decode from dataset on new checkpoint.\"\"\"\n for _ in next_checkpoint(self._hparams.model_dir):\n self.decode(dataset_split=tf.estimator.ModeKeys.EVAL)\n\n def continuous_decode_from_file(self):\n \"\"\"Decode from file on new checkpoint.\"\"\"\n for _ in next_checkpoint(self._hparams.model_dir):\n self.decode(decode_from_file=True)\n\n\ndef create_tf_server(config):\n #tf.logging.info(\"task_type=%s\", config.task_type,\n # \"task_id=%d\", config.task_id)\n server = tf.train.Server(\n config.cluster_spec,\n job_name=config.task_type,\n task_index=config.task_id,\n config=config.tf_config,\n start=True)\n return server\n\ndef create_experiment(\n run_config,\n hparams,\n model_name,\n problem_name,\n data_dir,\n train_steps,\n eval_steps,\n min_eval_frequency=2000,\n eval_throttle_seconds=600,\n schedule=\"train_and_evaluate\",\n export=False,\n decode_hparams=None,\n use_tfdbg=False,\n use_dbgprofile=False,\n eval_early_stopping_steps=None,\n eval_early_stopping_metric=None,\n eval_early_stopping_metric_delta=None,\n eval_early_stopping_metric_minimize=True,\n use_tpu=False,\n use_tpu_estimator=False,\n use_xla=False,\n additional_train_hooks=None,\n additional_eval_hooks=None,\n warm_start_from=None,\n decode_from_file=None,\n decode_to_file=None,\n decode_reference=None,\n std_server_protocol=None):\n \"\"\"Create Experiment.\"\"\"\n # HParams\n hparams.add_hparam(\"model_dir\", run_config.model_dir)\n hparams.add_hparam(\"data_dir\", data_dir)\n hparams.add_hparam(\"train_steps\", train_steps)\n hparams.add_hparam(\"eval_steps\", eval_steps)\n hparams.add_hparam(\"schedule\", schedule)\n hparams.add_hparam(\"warm_start_from\", warm_start_from)\n hparams.add_hparam(\"std_server_protocol\", std_server_protocol)\n if decode_hparams is not None:\n decode_hparams.add_hparam(\"decode_from_file\", decode_from_file)\n decode_hparams.add_hparam(\"decode_to_file\", decode_to_file)\n decode_hparams.add_hparam(\"decode_reference\", decode_reference)\n add_problem_hparams(hparams, problem_name)\n\n server = None\n if getattr(run_config, \"cluster_spec\") and \\\n schedule != \"run_std_server\":\n server = create_tf_server(run_config)\n\n # Estimator\n estimator = create_estimator(\n model_name,\n hparams,\n run_config,\n schedule=schedule,\n decode_hparams=decode_hparams,\n use_tpu=use_tpu,\n use_tpu_estimator=use_tpu_estimator,\n use_xla=use_xla)\n\n # Input fns from Problem\n problem = hparams.problem\n train_input_fn = problem.make_estimator_input_fn(tf.estimator.ModeKeys.TRAIN,\n hparams)\n eval_input_fn = problem.make_estimator_input_fn(tf.estimator.ModeKeys.EVAL,\n hparams)\n\n # Export\n exporter = None\n if export:\n def compare_fn(best_eval_result, current_eval_result):\n metric = eval_early_stopping_metric or \"loss\"\n return current_eval_result[metric] < best_eval_result[metric]\n\n exporter = tf.estimator.BestExporter(\n name=\"best\",\n serving_input_receiver_fn=lambda: problem.serving_input_fn(hparams),\n compare_fn=compare_fn,\n assets_extra=problem.export_assets)\n\n # Hooks\n validation_monitor_kwargs = dict(\n input_fn=eval_input_fn,\n eval_steps=eval_steps,\n every_n_steps=min_eval_frequency,\n early_stopping_rounds=eval_early_stopping_steps,\n early_stopping_metric=eval_early_stopping_metric,\n early_stopping_metric_minimize=eval_early_stopping_metric_minimize)\n dbgprofile_kwargs = {\"output_dir\": run_config.model_dir}\n early_stopping_kwargs = dict(\n events_dir=os.path.join(run_config.model_dir, \"eval_continuous\"),\n tag=eval_early_stopping_metric,\n num_plateau_steps=eval_early_stopping_steps,\n plateau_decrease=eval_early_stopping_metric_minimize,\n plateau_delta=eval_early_stopping_metric_delta,\n every_n_steps=min_eval_frequency)\n\n # Eval on TPU Pods is not supported yet\n if use_tpu and run_config.tpu_config.num_shards > 8 and \"eval\" in schedule:\n raise ValueError(\"Eval is not currently supported on a TPU Pod\")\n\n # In-process eval (and possible early stopping)\n if schedule == \"continuous_train_and_eval\" and min_eval_frequency:\n tf.logging.warn(\"ValidationMonitor only works with \"\n \"--schedule=train_and_evaluate\")\n use_validation_monitor = (\n schedule == \"train_and_evaluate\" and min_eval_frequency)\n # Distributed early stopping\n local_schedules = [\"train_and_evaluate\", \"continuous_train_and_eval\"]\n use_early_stopping = (\n schedule not in local_schedules and eval_early_stopping_steps)\n train_hooks, eval_hooks = create_hooks(\n use_tfdbg=use_tfdbg,\n use_dbgprofile=use_dbgprofile,\n dbgprofile_kwargs=dbgprofile_kwargs,\n use_validation_monitor=use_validation_monitor,\n validation_monitor_kwargs=validation_monitor_kwargs,\n use_early_stopping=use_early_stopping,\n early_stopping_kwargs=early_stopping_kwargs\n )\n train_hooks += t2t_model.T2TModel.get_train_hooks(model_name)\n eval_hooks += t2t_model.T2TModel.get_eval_hooks(model_name)\n if additional_train_hooks:\n train_hooks += additional_train_hooks\n if additional_eval_hooks:\n eval_hooks += additional_eval_hooks\n\n train_hooks = tf.contrib.learn.monitors.replace_monitors_with_hooks(\n train_hooks, estimator)\n eval_hooks = tf.contrib.learn.monitors.replace_monitors_with_hooks(\n eval_hooks, estimator)\n\n train_spec = tf.estimator.TrainSpec(\n train_input_fn, max_steps=train_steps, hooks=train_hooks)\n eval_spec = tf.estimator.EvalSpec(\n eval_input_fn,\n steps=eval_steps,\n hooks=eval_hooks,\n start_delay_secs=0 if hparams.schedule == \"evaluate\" else 120,\n throttle_secs=eval_throttle_seconds,\n exporters=exporter)\n\n return T2TExperiment(estimator, hparams, train_spec, eval_spec,\n use_validation_monitor, decode_hparams,\n server)\n\n\ndef create_experiment_fn(*args, **kwargs):\n \"\"\"Wrapper for canonical experiment_fn. See create_experiment.\"\"\"\n\n def experiment_fn(run_config, hparams):\n return create_experiment(run_config, hparams, *args, **kwargs)\n\n return experiment_fn\n\n\ndef add_problem_hparams(hparams, problem_name):\n \"\"\"Add problem hparams for the problems.\"\"\"\n problem = registry.problem(problem_name)\n p_hparams = problem.get_hparams(hparams)\n\n hparams.problem = problem\n hparams.problem_hparams = p_hparams\n\n\ndef set_random_seed(seed):\n tf.set_random_seed(seed)\n random.seed(seed)\n np.random.seed(seed)\n\n\ndef restore_checkpoint(ckpt_dir, saver, sess, must_restore=False):\n \"\"\"Restore from a checkpoint.\"\"\"\n ckpt = tf.train.get_checkpoint_state(ckpt_dir)\n if must_restore and not ckpt:\n raise ValueError(\"No checkpoint found in %s\" % ckpt_dir)\n if not ckpt:\n return 0\n\n path = ckpt.model_checkpoint_path\n tf.logging.info(\"Restoring checkpoint %s\", path)\n saver.restore(sess, path)\n step = int(path.split(\"-\")[-1])\n return step\n", "# coding=utf-8\n# Copyright 2018 The Tensor2Tensor Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nr\"\"\"Training of RL agent with PPO algorithm.\n\nExample invocation:\n\npython -m tensor2tensor.rl.trainer_model_free \\\n --output_dir=$HOME/t2t/rl_v1 \\\n --hparams_set=pong_model_free \\\n --loop_hparams='num_agents=15'\n\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\nfrom tensor2tensor.rl import rl_trainer_lib\nfrom tensor2tensor.utils import flags as t2t_flags # pylint: disable=unused-import\nfrom tensor2tensor.utils import trainer_lib\n\nimport tensorflow as tf\n\nflags = tf.flags\nFLAGS = flags.FLAGS\n\n# To maintain compatibility with some internal libs, we guard against these flag\n# definitions possibly erring. Apologies for the ugliness.\ntry:\n flags.DEFINE_string(\"output_dir\", \"\", \"Base output directory for run.\")\nexcept: # pylint: disable=bare-except\n pass\n\n\ndef main(_):\n hparams = trainer_lib.create_hparams(FLAGS.hparams_set, FLAGS.hparams)\n rl_trainer_lib.train(hparams, FLAGS.output_dir, FLAGS.output_dir)\n\n\nif __name__ == \"__main__\":\n tf.app.run()\n" ]
[ [ "tensorflow.contrib.cluster_resolver.TPUClusterResolver", "tensorflow.logging.warning", "tensorflow.GPUOptions", "tensorflow.estimator.RunConfig", "tensorflow.contrib.training.wait_for_new_checkpoint", "tensorflow.contrib.learn.monitors.ValidationMonitor", "tensorflow.estimator.train_and_evaluate", "tensorflow.contrib.tpu.TPUEstimator", "tensorflow.OptimizerOptions", "tensorflow.logging.warn", "tensorflow.ConfigProto", "tensorflow.estimator.EvalSpec", "tensorflow.train.ProfilerHook", "tensorflow.contrib.learn.monitors.replace_monitors_with_hooks", "tensorflow.python.debug.LocalCLIDebugHook", "tensorflow.train.Server", "tensorflow.estimator.Estimator", "tensorflow.estimator.TrainSpec", "tensorflow.logging.info", "tensorflow.contrib.tpu.TPUConfig", "tensorflow.set_random_seed", "tensorflow.train.get_checkpoint_state", "tensorflow.core.protobuf.rewriter_config_pb2.RewriterConfig", "numpy.random.seed", "tensorflow.GraphOptions" ], [ "tensorflow.app.run" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.10" ] } ]
alek5k/pytransform3d
[ "c6fb10b1d17713bd8a2d6becb928c4f6dcf611f9", "c6fb10b1d17713bd8a2d6becb928c4f6dcf611f9" ]
[ "examples/plots/plot_camera_trajectory.py", "examples/visualizations/vis_moving_trajectory.py" ]
[ "\"\"\"\n=================\nCamera Trajectory\n=================\n\nThe following illustration shows a camera's trajectory that has has been\nestimated from odometry. This specific trajectory has been used to reconstruct\na colored mesh from a depth camera and an RGB camera.\n\"\"\"\nprint(__doc__)\n\n\nimport os\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport pytransform3d.transformations as pt\nimport pytransform3d.trajectories as ptr\nimport pytransform3d.rotations as pr\nimport pytransform3d.camera as pc\nfrom cycler import cycle\n\n\nBASE_DIR = \"test/test_data/\"\ndata_dir = BASE_DIR\nsearch_path = \".\"\nwhile (not os.path.exists(data_dir) and\n os.path.dirname(search_path) != \"pytransform3d\"):\n search_path = os.path.join(search_path, \"..\")\n data_dir = os.path.join(search_path, BASE_DIR)\n\nintrinsic_matrix = np.loadtxt(os.path.join(\n data_dir, \"reconstruction_camera_matrix.csv\"), delimiter=\",\")\n\nP = np.loadtxt(os.path.join(data_dir, \"reconstruction_odometry.csv\"),\n delimiter=\",\", skiprows=1)\nfor t in range(len(P)):\n P[t, 3:] = pr.quaternion_wxyz_from_xyzw(P[t, 3:])\ncam2world_trajectory = ptr.transforms_from_pqs(P)\n\nplt.figure(figsize=(5, 5))\nax = pt.plot_transform(s=0.3)\nax = ptr.plot_trajectory(ax, P=P, s=0.1, n_frames=10)\n\nimage_size = np.array([1920, 1440])\n\nkey_frames_indices = np.linspace(0, len(P) - 1, 10, dtype=int)\ncolors = cycle(\"rgb\")\nfor i, c in zip(key_frames_indices, colors):\n pc.plot_camera(ax, intrinsic_matrix, cam2world_trajectory[i],\n sensor_size=image_size, virtual_image_distance=0.2, c=c)\n\npos_min = np.min(P[:, :3], axis=0)\npos_max = np.max(P[:, :3], axis=0)\ncenter = (pos_max + pos_min) / 2.0\nmax_half_extent = max(pos_max - pos_min) / 2.0\nax.set_xlim((center[0] - max_half_extent, center[0] + max_half_extent))\nax.set_ylim((center[1] - max_half_extent, center[1] + max_half_extent))\nax.set_zlim((center[2] - max_half_extent, center[2] + max_half_extent))\n\nax.view_init(azim=110, elev=40)\n\nplt.show()\n", "\"\"\"\n==================\nAnimate Trajectory\n==================\n\nAnimates a trajectory.\n\"\"\"\nprint(__doc__)\n\n\nimport numpy as np\nimport pytransform3d.visualizer as pv\nfrom pytransform3d.rotations import matrix_from_angle, R_id\nfrom pytransform3d.transformations import transform_from, concat\n\n\ndef update_trajectory(step, n_frames, trajectory):\n progress = 1 - float(step + 1) / float(n_frames)\n H = np.zeros((100, 4, 4))\n H0 = transform_from(R_id, np.zeros(3))\n H_mod = np.eye(4)\n for i, t in enumerate(np.linspace(0, progress, len(H))):\n H0[:3, 3] = np.array([t, 0, t])\n H_mod[:3, :3] = matrix_from_angle(2, 8 * np.pi * t)\n H[i] = concat(H0, H_mod)\n\n trajectory.set_data(H)\n return trajectory\n\n\nn_frames = 200\n\nfig = pv.figure()\n\nH = np.empty((100, 4, 4))\nH[:] = np.eye(4)\n# set initial trajectory to extend view box\nH[:, 0, 3] = np.linspace(-2, 2, len(H))\nH[:, 1, 3] = np.linspace(-2, 2, len(H))\nH[:, 2, 3] = np.linspace(0, 4, len(H))\ntrajectory = pv.Trajectory(H, s=0.2, c=[0, 0, 0])\ntrajectory.add_artist(fig)\nfig.view_init()\nfig.set_zoom(0.5)\n\nif \"__file__\" in globals():\n fig.animate(\n update_trajectory, n_frames, fargs=(n_frames, trajectory), loop=True)\n fig.show()\nelse:\n fig.save_image(\"__open3d_rendered_image.jpg\")\n" ]
[ [ "numpy.min", "numpy.max", "numpy.array", "matplotlib.pyplot.show", "matplotlib.pyplot.figure" ], [ "numpy.eye", "numpy.array", "numpy.zeros", "numpy.empty" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
tvorogme/recommendation_system
[ "e8ca0216293c0ad2951518a12709d913016e9e07" ]
[ "models/hybrid_model.py" ]
[ "from collections import Counter\nimport datetime\n\nimport numpy as np\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.utils import shuffle\n\nfrom models.features.topics import topics_similarity\nfrom models.features.cosine import cosine_similarity_features\n\nclf = RandomForestClassifier()\nclf_one = RandomForestClassifier()\nclf_two = RandomForestClassifier()\n\ndef generate_features(data, val=None):\n features = []\n for raw in data:\n features.extend(topics_similarity(raw))\n features.extend(cosine_similarity_features(data[:-1], data[-1]))\n\n if val is None:\n return features\n else:\n return features, val\n\n\ndef generate_data(data):\n x_true = []\n y_true = []\n x_false = []\n y_false = []\n print('Start generate features.')\n for urls in data.sequences.find():\n features = generate_features(data.get_articles_data(urls['urls']), 1)\n x_true.append(features[0])\n y_true.append(features[1])\n\n print('Start generate random data.')\n while len(x_true) != len(x_false):\n features = generate_features(data.get_random_articles(4), 0)\n x_false.append(features[0])\n y_false.append(features[1])\n\n return x_true + x_false, y_true + y_false\n\n\ndef init(data):\n try:\n x = np.load(open('train_x.np', 'rb'))\n y = np.load(open('train_y.np', 'rb'))\n except FileNotFoundError:\n x, y = generate_data(data)\n np.save(open('train_x.np', 'wb'), x)\n np.save(open('train_y.np', 'wb'), y)\n x, y = shuffle(x, y)\n x_one = list(map(lambda a: a[:81], x))\n x_two = list(map(lambda a: a[:122], x))\n\n print('Train model for 3 articles.')\n clf.fit(x, y)\n\n print('Train model for 1 article.')\n clf_one.fit(x_one, y)\n\n print('Train model for 2 articles.')\n clf_two.fit(x_two, y)\n\n\ndef predict(input_articles, input_ids,tvrain_data, recommends_num):\n result_counter = Counter()\n min_time = input_articles[0]['time'] - datetime.timedelta(hours=5)\n max_time = input_articles[-1]['time'] + datetime.timedelta(hours=5)\n mongo_query = {'time': {'$gt': min_time, '$lt': max_time}}\n len_articles = len(input_articles)\n # Gen for articles in Mongo\n for article in tvrain_data.iterate_articles(except_articles=input_ids, query=mongo_query):\n new_features = generate_features(input_articles + [article])\n if len_articles == 3:\n result = clf.predict_proba([new_features])\n elif len_articles == 2:\n result = clf_two.predict_proba([new_features])\n elif len_articles == 1:\n result = clf_one.predict_proba([new_features])\n result_counter[article['_id']] = result[0][1]\n return list(result_counter.most_common(recommends_num))\n" ]
[ [ "sklearn.utils.shuffle", "sklearn.ensemble.RandomForestClassifier" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
wdobbels/CAAPR
[ "50d0b32642a61af614c22f1c6dc3c4a00a1e71a3", "50d0b32642a61af614c22f1c6dc3c4a00a1e71a3", "50d0b32642a61af614c22f1c6dc3c4a00a1e71a3" ]
[ "CAAPR/CAAPR_AstroMagic/PTS/pts/magic/plot/imagegrid.py", "CAAPR/CAAPR_AstroMagic/PTS/pts/magic/tools/masks.py", "CAAPR/CAAPR_AstroMagic/PTS/pts/core/plot/attenuation.py" ]
[ "#!/usr/bin/env python\n# -*- coding: utf8 -*-\n# *****************************************************************\n# ** PTS -- Python Toolkit for working with SKIRT **\n# ** © Astronomical Observatory, Ghent University **\n# *****************************************************************\n\n## \\package pts.magic.plot.imagegrid Contains the ImageGridPlotter class.\n\n# -----------------------------------------------------------------\n\n# Ensure Python 3 compatibility\nfrom __future__ import absolute_import, division, print_function\n\n# Import standard modules\nimport math\nfrom scipy import ndimage\nimport copy\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom mpl_toolkits.axes_grid1 import AxesGrid\nimport matplotlib.gridspec as gridspec\nimport glob\nfrom matplotlib import colors\nfrom matplotlib import cm\nfrom matplotlib.colors import LogNorm\nimport pyfits\nfrom collections import OrderedDict\nfrom textwrap import wrap\n\nfrom astropy.io import fits\nfrom pyfits import PrimaryHDU, Header\nfrom astropy.visualization import SqrtStretch, LogStretch\nfrom astropy.visualization.mpl_normalize import ImageNormalize\n\nimport aplpy\nimport wcsaxes\nimport matplotlib.colors as mpl_colors\nimport matplotlib.colorbar as mpl_colorbar\n\n# Import the relevant PTS classes and modules\nfrom ...core.tools.logging import log\n\n# -----------------------------------------------------------------\n\nclass ImageGridPlotter(object):\n\n \"\"\"\n This class ...\n \"\"\"\n\n def __init__(self, title=None):\n\n \"\"\"\n The constructor ...\n :param title:\n \"\"\"\n\n # Set the title\n self.title = title\n\n # Figure and grid\n self._figure = None\n self._grid = None\n\n # Properties\n self.style = \"dark\" # \"dark\" or \"light\"\n self.transparent = True\n self.format = None\n self.colormap = \"viridis\"\n self.vmin = None\n\n # -----------------------------------------------------------------\n\n def set_title(self, title):\n\n \"\"\"\n This function ...\n :param title:\n :return:\n \"\"\"\n\n self.title = title\n\n# -----------------------------------------------------------------\n\nclass StandardImageGridPlotter(ImageGridPlotter):\n\n \"\"\"\n This class ...\n \"\"\"\n\n def __init__(self, title=None):\n\n \"\"\"\n The constructor ...\n :param title:\n \"\"\"\n\n # Call the constructor of the base class\n super(StandardImageGridPlotter, self).__init__(title)\n\n # -- Attributes --\n\n # The images to be plotted\n self.images = OrderedDict()\n\n # Masks to be overlayed on the images\n self.masks = dict()\n\n # Regions to be overlayed on the images\n self.regions = dict()\n\n # Properties\n self.ncols = 7\n self.width = 16\n\n # -----------------------------------------------------------------\n\n def run(self, output_path):\n\n \"\"\"\n This function ...\n :param output_path:\n :return:\n \"\"\"\n\n # Make the plot\n self.plot(output_path)\n\n # -----------------------------------------------------------------\n\n def add_image(self, image, label, mask=None, region=None):\n\n \"\"\"\n This function ...\n :param image:\n :param label:\n :param mask:\n :param region:\n :return:\n \"\"\"\n\n self.images[label] = image\n if mask is not None: self.masks[label] = mask\n if region is not None: self.regions[label] = region\n\n # -----------------------------------------------------------------\n\n @property\n def nimages(self):\n\n \"\"\"\n This function ...\n :return:\n \"\"\"\n\n return len(self.images)\n\n # -----------------------------------------------------------------\n\n def plot(self, path):\n\n \"\"\"\n This function ...\n :param path:\n :return:\n \"\"\"\n\n # Determine the necessary number of rows\n nrows = int(math.ceil(self.nimages / self.ncols))\n\n ratio = float(nrows) / float(self.ncols)\n height = ratio * self.width\n\n # Create the figure\n self._figure = plt.figure(figsize=(self.width, height))\n\n self._figure.subplots_adjust(hspace=0.0, wspace=0.0)\n\n #self._figure.text(0.385, 0.97, \"Offset from centre (degrees)\", color='black', size='16', weight='bold')\n #self._figure.text(0.02, 0.615, \"Offset from centre (degrees)\", color='black', size='16', weight='bold', rotation='vertical')\n\n def standard_setup(sp):\n sp.set_frame_color('black')\n sp.set_tick_labels_font(size='10')\n sp.set_axis_labels_font(size='12')\n # sp.set_tick_labels_format(xformat='hh:mm',yformat='dd:mm')\n sp.set_xaxis_coord_type('scalar')\n sp.set_yaxis_coord_type('scalar')\n sp.set_tick_color('black')\n sp.recenter(x=0.0, y=0.0, width=3., height=0.6)\n sp.set_tick_xspacing(0.4)\n sp.set_tick_yspacing(0.25)\n sp.set_system_latex(True)\n sp.tick_labels.hide()\n sp.axis_labels.hide()\n\n # Create grid\n #self._grid = AxesGrid(self._figure, 111,\n # nrows_ncols=(nrows, self.ncols),\n # axes_pad=0.0,\n # label_mode=\"L\",\n # #share_all=True,\n # share_all=False,\n # cbar_location=\"right\",\n # cbar_mode=\"single\",\n # cbar_size=\"0.5%\",\n # cbar_pad=\"0.5%\") # cbar_mode=\"single\"\n\n gs = gridspec.GridSpec(nrows, self.ncols, wspace=0.0, hspace=0.0)\n\n # Loop over the images\n counter = 0\n ax = None\n for label in self.images:\n\n row = int(counter / self.ncols)\n col = counter % self.ncols\n\n frame = self.images[label]\n\n #ax = self._grid[counter]\n\n subplotspec = gs[row, col]\n\n #points = subplotspec.get_position(self._figure).get_points()\n #print(points)\n #x_min = points[0, 0]\n #x_max = points[1, 0]\n #y_min = points[0, 1]\n #y_max = points[1, 1]\n # width = x_max - x_min\n # height = y_max - y_min\n # ax = self._figure.add_axes([x_min, y_min, width, height])\n\n #ax = plt.subplot(subplotspec)\n #shareax = ax if ax is not None else None\n #ax = plt.subplot(subplotspec, projection=frame.wcs.to_astropy(), sharex=shareax, sharey=shareax)\n ax = plt.subplot(subplotspec, projection=frame.wcs.to_astropy())\n\n #lon = ax.coords[0]\n #lat = ax.coords[1]\n\n #overlay = ax.get_coords_overlay('fk5')\n #overlay.grid(color='white', linestyle='solid', alpha=0.5)\n\n # Determine the maximum value in the box and the mimimum value for plotting\n norm = ImageNormalize(stretch=LogStretch())\n #min_value = np.nanmin(frame)\n min_value = self.vmin if self.vmin is not None else np.nanmin(frame)\n max_value = 0.5 * (np.nanmax(frame) + min_value)\n\n #f1.show_colorscale(vmin=min_value, vmax=max_value, cmap=\"viridis\")\n #f1.show_beam(major=0.01, minor=0.01, angle=0, fill=True, color='white')\n ## f1.axis_labels.show_y()\n #f1.tick_labels.set_xposition('top')\n #f1.tick_labels.show()\n\n ax.set_xticks([])\n ax.set_yticks([])\n ax.xaxis.set_ticklabels([])\n ax.yaxis.set_ticklabels([])\n\n #ax.spines['bottom'].set_color(\"white\")\n #ax.spines['top'].set_color(\"white\")\n #ax.spines['left'].set_color(\"white\")\n #ax.spines['right'].set_color(\"white\")\n ax.xaxis.label.set_color(\"white\")\n ax.yaxis.label.set_color(\"white\")\n ax.tick_params(axis='x', colors=\"white\")\n ax.tick_params(axis='y', colors=\"white\")\n\n # Get the color map\n cmap = cm.get_cmap(self.colormap)\n\n # Set background color\n background_color = cmap(0.0)\n ax.set_axis_bgcolor(background_color)\n\n # Plot\n frame[np.isnan(frame)] = 0.0\n\n # Add mask if present\n if label in self.masks: frame[self.masks[label]] = float('nan')\n\n ax.imshow(frame, vmin=min_value, vmax=max_value, cmap=cmap, origin='lower', norm=norm, interpolation=\"nearest\", aspect=1)\n\n # Add region if present\n if label in self.regions:\n for patch in self.regions[label].to_mpl_patches():\n ax.add_patch(patch)\n\n # Add the label\n ax.text(0.95, 0.95, label, color='white', transform=ax.transAxes, fontsize=10, va=\"top\", ha=\"right\") # fontweight='bold'\n\n #ax.coords.grid(color='white')\n\n counter += 1\n\n all_axes = self._figure.get_axes()\n # show only the outside spines\n for ax in all_axes:\n for sp in ax.spines.values():\n sp.set_visible(False)\n #if ax.is_first_row():\n # ax.spines['top'].set_visible(True)\n #if ax.is_last_row():\n # ax.spines['bottom'].set_visible(True)\n #if ax.is_first_col():\n # ax.spines['left'].set_visible(True)\n #if ax.is_last_col():\n # ax.spines['right'].set_visible(True)\n\n # Add a colourbar\n\n #axisf3 = self._figure.add_axes(gs[row, col+1:])\n\n subplotspec = gs[row, col+1:]\n points = subplotspec.get_position(self._figure).get_points()\n #print(\"colorbar points:\", points)\n\n x_min = points[0,0]\n x_max = points[1,0]\n y_min = points[0,1]\n y_max = points[1,1]\n\n #print((x_min, x_max), (y_min, y_max))\n\n #points_flattened = points.flatten()\n #print(\"colorbar:\", points_flattened)\n\n x_center = 0.5 * (x_min + x_max)\n y_center = 0.5 * (y_min + y_max)\n\n width = 0.9* (x_max - x_min)\n height = 0.2 * (y_max - y_min)\n\n x_min = x_center - 0.5 * width\n x_max = x_center + 0.5 * width\n y_min = y_center - 0.5 * height\n y_max = y_center + 0.5 * height\n\n #ax_cm = plt.subplot(points)\n\n #ax_cm = plt.axes(points_flattened)\n\n ax_cm = self._figure.add_axes([x_min, y_min, width, height])\n\n cm_cm = cm.get_cmap(self.colormap)\n norm_cm = mpl_colors.Normalize(vmin=0, vmax=1)\n cb = mpl_colorbar.ColorbarBase(ax_cm, cmap=cm_cm, norm=norm_cm, orientation='horizontal')\n cb.set_label('Flux (arbitrary units)')\n\n # Set the title\n if self.title is not None: self._figure.suptitle(\"\\n\".join(wrap(self.title, 60)))\n\n #plt.tight_layout()\n\n # Debugging\n if type(path).__name__ == \"BytesIO\": log.debug(\"Saving the SED plot to a buffer ...\")\n elif path is None: log.debug(\"Showing the SED plot ...\")\n else: log.debug(\"Saving the SED plot to \" + str(path) + \" ...\")\n\n if path is not None:\n # Save the figure\n plt.savefig(path, bbox_inches='tight', pad_inches=0.25, transparent=self.transparent, format=self.format)\n else: plt.show()\n plt.close()\n\n# -----------------------------------------------------------------\n\n# TODO: add option to plot histograms of the residuals (DL14)\n\nclass ResidualImageGridPlotter(ImageGridPlotter):\n\n \"\"\"\n This class ...\n \"\"\"\n\n def __init__(self, title=None):\n\n \"\"\"\n The constructor ...\n \"\"\"\n\n # Call the constructor of the base class\n super(ResidualImageGridPlotter, self).__init__(title)\n\n # -- Attributes --\n\n # Set the title\n self.title = title\n\n # The rows of the grid\n self.rows = OrderedDict()\n self.plot_residuals = []\n\n # The names of the columns\n self.column_names = [\"Observation\", \"Model\", \"Residual\"]\n\n # Box (SkyRectangle) where to cut off the maps\n self.box = None\n\n self._plotted_rows = 0\n\n self.absolute = False\n\n # -----------------------------------------------------------------\n\n def set_bounding_box(self, box):\n\n \"\"\"\n This function ...\n :param box:\n :return:\n \"\"\"\n\n self.box = box\n\n # -----------------------------------------------------------------\n\n def add_row(self, image_a, image_b, label, residuals=True):\n\n \"\"\"\n This function ...\n :param image_a:\n :param image_b:\n :param label:\n :param residuals:\n :return:\n \"\"\"\n\n self.rows[label] = (image_a, image_b)\n if residuals: self.plot_residuals.append(label)\n\n # -----------------------------------------------------------------\n\n def set_column_names(self, name_a, name_b, name_residual=\"Residual\"):\n\n \"\"\"\n This function ...\n :param name_a:\n :param name_b:\n :param name_residual:\n :return:\n \"\"\"\n\n self.column_names = [name_a, name_b, name_residual]\n\n # -----------------------------------------------------------------\n\n def run(self, output_path):\n\n \"\"\"\n This function ...\n :param output_path:\n :return:\n \"\"\"\n\n # Make the plot\n self.plot(output_path)\n\n # -----------------------------------------------------------------\n\n def clear(self):\n\n \"\"\"\n This function ...\n :return:\n \"\"\"\n\n # Set default values for all attributes\n self.title = None\n self.rows = OrderedDict()\n self.plot_residuals = []\n self.column_names = [\"Observation\", \"Model\", \"Residual\"]\n self._figure = None\n self._grid = None\n self._plotted_rows = 0\n\n # -----------------------------------------------------------------\n\n def plot(self, path):\n\n \"\"\"\n This function ...\n :param path:\n :return:\n \"\"\"\n\n # Determine the wcs with the smallest pixelscale\n reference_wcs = None\n for label in self.rows:\n if reference_wcs is None or reference_wcs.average_pixelscale > self.rows[label][0].average_pixelscale: reference_wcs = copy.deepcopy(self.rows[label][0].wcs)\n\n number_of_rows = len(self.rows)\n axisratio = float(self.rows[self.rows.keys()[0]][0].xsize) / float(self.rows[self.rows.keys()[0]][0].ysize)\n #print(\"axisratio\", axisratio)\n\n one_frame_x_size = 3.\n fig_x_size = 3. * one_frame_x_size\n #fig_y_size = number_of_rows * one_frame_x_size / axisratio\n fig_y_size = one_frame_x_size * number_of_rows * 0.7\n\n # Create a figure\n self._figure = plt.figure(figsize=(fig_x_size, fig_y_size))\n self._figure.subplots_adjust(left=0.05, right=0.95)\n\n # Create grid\n self._grid = AxesGrid(self._figure, 111,\n nrows_ncols=(len(self.rows), 3),\n axes_pad=0.02,\n label_mode=\"L\",\n share_all=True,\n cbar_location=\"right\",\n cbar_mode=\"single\",\n cbar_size=\"0.5%\",\n cbar_pad=\"0.5%\",\n ) # cbar_mode=\"single\"\n\n for cax in self._grid.cbar_axes:\n cax.toggle_label(False)\n\n #rectangle_reference_wcs = self.box.to_pixel(reference_wcs)\n\n data = OrderedDict()\n\n greatest_shape = None\n\n if self.box is not None:\n\n for label in self.rows:\n wcs = self.rows[label][0].wcs\n\n rectangle = self.box.to_pixel(wcs)\n\n y_min = rectangle.lower_left.y\n y_max = rectangle.upper_right.y\n x_min = rectangle.lower_left.x\n x_max = rectangle.upper_right.x\n\n reference = self.rows[label][0][y_min:y_max, x_min:x_max]\n model = self.rows[label][1][y_min:y_max, x_min:x_max]\n data[label] = (reference, model)\n\n print(label, \"box height/width ratio:\", float(reference.shape[0])/float(reference.shape[1]))\n\n if greatest_shape is None or greatest_shape[0] < reference.shape[0]: greatest_shape = reference.shape\n\n else:\n\n for label in self.rows:\n reference = self.rows[label][0]\n model = self.rows[label][1]\n data[label] = (reference, model)\n if greatest_shape is None or greatest_shape[0] < reference.shape[0]: greatest_shape = reference.shape\n\n # Loop over the rows\n for label in self.rows:\n\n #wcs = self.rows[label][0].wcs\n\n if data[label][0].shape == greatest_shape:\n reference = data[label][0]\n model = data[label][1]\n else:\n factor = float(greatest_shape[0]) / float(data[label][0].shape[0])\n order = 0\n reference = ndimage.zoom(data[label][0], factor, order=order)\n model = ndimage.zoom(data[label][1], factor, order=order)\n\n if self.absolute: residual = model - reference\n else: residual = (model - reference)/model\n\n # Plot the reference image\n x0, x1, y0, y1, vmin, vmax = self.plot_frame(reference, label, 0)\n\n # Plot the model image\n x0, x1, y0, y1, vmin, vmax = self.plot_frame(model, label, 1, vlimits=(vmin,vmax))\n\n # Plot the residual image\n x0, x1, y0, y1, vmin, vmax = self.plot_frame(residual, label, 2, vlimits=(vmin,vmax))\n\n self._plotted_rows += 3\n\n #self._grid.axes_llc.set_xlim(x0, x1)\n #self._grid.axes_llc.set_ylim(y0, y1)\n\n self._grid.axes_llc.set_xticklabels([])\n self._grid.axes_llc.set_yticklabels([])\n self._grid.axes_llc.get_xaxis().set_ticks([]) # To remove ticks\n self._grid.axes_llc.get_yaxis().set_ticks([]) # To remove ticks\n\n # Add title if requested\n #if self.title is not None: self._figure.suptitle(self.title, fontsize=12, fontweight='bold')\n\n plt.tight_layout()\n\n # Debugging\n log.debug(\"Saving the SED plot to \" + path + \" ...\")\n\n # Save the figure\n plt.savefig(path, bbox_inches='tight', pad_inches=0.25, format=self.format, transparent=self.transparent)\n plt.close()\n\n # -----------------------------------------------------------------\n\n def plot_frame(self, frame, row_label, column_index, borders=(0,0,0,0), vlimits=None):\n\n \"\"\"\n This function ...\n :param frame:\n :param column_index:\n :param row_label:\n :param borders:\n :param vlimits:\n :return:\n \"\"\"\n\n grid_index = self._plotted_rows + column_index\n\n x0 = borders[0]\n y0 = borders[1]\n\n #x1 = frame.xsize\n #y1 = frame.ysize\n x1 = frame.shape[1]\n y1 = frame.shape[0]\n\n #vmax = np.max(frame) # np.mean([np.max(data_ski),np.max(data_ref)])\n #vmin = np.min(frame) # np.mean([np.min(data_ski),np.min(data_ref)])\n #if min_int == 0.: min_int = vmin\n #else: vmin = min_int\n #if max_int == 0.: max_int = vmax\n #else: vmax = max_int\n\n if vlimits is None:\n min_value = self.vmin if self.vmin is not None else np.nanmin(frame)\n max_value = 0.5 * (np.nanmax(frame) + min_value)\n else:\n min_value = vlimits[0]\n max_value = vlimits[1]\n\n aspect = \"equal\"\n if column_index != 2:\n\n # Get the color map\n cmap = cm.get_cmap(self.colormap)\n\n # Set background color\n background_color = cmap(0.0)\n self._grid[grid_index].set_axis_bgcolor(background_color)\n\n # Plot\n frame[np.isnan(frame)] = 0.0\n norm = ImageNormalize(stretch=LogStretch())\n im = self._grid[grid_index].imshow(frame, cmap=cmap, vmin=min_value, vmax=max_value, interpolation=\"nearest\", origin=\"lower\", aspect=aspect, norm=norm) # 'nipy_spectral_r', 'gist_ncar_r'\n\n else:\n\n if self.absolute:\n # Get the color map\n cmap = cm.get_cmap(self.colormap)\n norm = ImageNormalize(stretch=LogStretch())\n else:\n cmap = discrete_cmap()\n min_value = 0.001\n max_value = 1.\n norm = None\n\n print(min_value, max_value)\n\n im = self._grid[grid_index].imshow(frame, cmap=cmap, vmin=min_value, vmax=max_value, interpolation=\"nearest\", origin=\"lower\", aspect=aspect, norm=norm)\n cb = self._grid[grid_index].cax.colorbar(im)\n\n # cb.set_xticklabels(labelsize=1)\n # grid[number+numb_of_grid].cax.toggle_label(True)\n for cax in self._grid.cbar_axes:\n cax.toggle_label(True)\n cax.axis[cax.orientation].set_label(' ')\n # cax.axis[cax.orientation].set_fontsize(3)\n cax.tick_params(labelsize=3)\n cax.set_ylim(min_value, max_value)\n # cax.set_yticklabels([0, 0.5, 1])\n\n if column_index == 0:\n self._grid[grid_index].text(0.03, 0.95, row_label, color='black', transform=self._grid[grid_index].transAxes, fontsize=fsize + 2, fontweight='bold', va='top')\n\n # if numb_of_grid==0:\n # crea_scale_bar(grid[number+numb_of_grid],x0,x1,y0,y1,pix2sec)\n # crea_scale_bar(grid[number+numb_of_grid],x0,x1,y0,y1,pix2sec)\n\n return x0, x1, y0, y1, min_value, max_value\n\n# -----------------------------------------------------------------\n\nfsize = 2\n\ndef sort_numbs(arr):\n numbers = []\n for k in range(len(arr)): \n numb = str(arr[k].split('/')[-1].split('_')[-1].split('.fits'))\n #print numb\n numbers.append(numb)\n a = sorted(numbers)\n new_arr = []\n for k in range(len(a)):\n ind = numbers.index(a[k])\n new_arr.append(arr[ind])\n return new_arr\n\ndef line_reg(header1):\n ima_pix2sec = float(header1['PIXSCALE_NEW'])\n nx = int(header1['NAXIS1'])\n ny = int(header1['NAXIS2'])\n scale = int(round(nx/8.*ima_pix2sec,-1))\n x2 = nx*9.8/10.\n x1 = x2 - scale/ima_pix2sec\n y1 = ny/7.\n y2 = y1\n \n return x1,y1,x2,y2,scale\n\n# Define new colormap for residuals\ndef discrete_cmap(N=8):\n # define individual colors as hex values\n cpool = [ '#000000', '#00EE00', '#0000EE', '#00EEEE', '#EE0000','#FFFF00', '#EE00EE', '#FFFFFF']\n cmap_i8 = colors.ListedColormap(cpool[0:N], 'i8')\n cm.register_cmap(cmap=cmap_i8)\n return cmap_i8\n\n\ndef define_scale_bar_length(x_extent,pix2sec):\n scale_bar = round((x_extent * pix2sec) / 6.,0)\n return int(5. * round(float(scale_bar)/5.)) # Length of the bar in arcsec\n \n\ndef crea_scale_bar(ax, x0, x1, y0, y1, pix2sec):\n offset_x_factor = 0.98\n offset_y_factor = 0.1 \n x_extent = x1 - x0\n\n scale_bar_length = define_scale_bar_length(x_extent, pix2sec) / 2. #### divide by 2 !!!\n\n xc = fabs(x1)-scale_bar_length/pix2sec - (1.-offset_x_factor)*(x1-x0)\n yc = fabs(y0) + (y1-y0)* offset_y_factor\n ax.errorbar(xc, yc, xerr=scale_bar_length/pix2sec,color='black',capsize=1,c='black')\n ax.text(xc, yc, str(int(scale_bar_length*2.))+'\\\"', color='black',fontsize=fsize+1, horizontalalignment='center', verticalalignment='bottom')\n\n# -----------------------------------------------------------------\n", "#!/usr/bin/env python\n# -*- coding: utf8 -*-\n# *****************************************************************\n# ** PTS -- Python Toolkit for working with SKIRT **\n# ** © Astronomical Observatory, Ghent University **\n# *****************************************************************\n\n## \\package pts.magic.tools.masks Contains functions for dealing with two-dimensional masks.\n\n# -----------------------------------------------------------------\n\n# Ensure Python 3 functionality\nfrom __future__ import absolute_import, division, print_function\n\n# Import standard modules\nimport numpy as np\n\n# Import the relevant PTS classes and modules\nfrom . import regions\n\n# -----------------------------------------------------------------\n\ndef annuli_around(region, inner_factor, outer_factor, header, x_size, y_size):\n\n \"\"\"\n This function ...\n :param region:\n :param inner_factor:\n :param outer_factor:\n :param header:\n :param x_size:\n :param y_size:\n :return:\n \"\"\"\n\n # Create new regions for the background estimation around the stars\n inner_region = regions.expand(region, inner_factor)\n outer_region = regions.expand(region, outer_factor)\n\n # Create inner and outer masks\n inner_mask = regions.create_mask(inner_region, header, x_size, y_size)\n outer_mask = regions.create_mask(outer_region, header, x_size, y_size)\n\n # Create the mask\n mask = inner_mask | np.logical_not(outer_mask)\n\n # Return the mask\n return mask\n\n# -----------------------------------------------------------------\n\ndef masked_outside(region, header, x_size, y_size, expand_factor=1.0):\n\n \"\"\"\n This function ...\n :param region:\n :param header:\n :param x_size:\n :param y_size:\n :param expand_factor:\n :return:\n \"\"\"\n\n # Create a new region ...\n region = regions.expand(region, factor=expand_factor)\n\n # Create a mask from the region\n mask = np.logical_not(regions.create_mask(region, header, x_size, y_size))\n\n # Return the mask\n return mask\n\n# -----------------------------------------------------------------\n\ndef create_disk_mask(x_size, y_size, x_center, y_center, radius):\n\n \"\"\"\n This function ...\n :param x_size:\n :param y_size:\n :param x_center:\n :param y_center:\n :param radius:\n :return:\n \"\"\"\n\n # Calculate which pixels should be masked\n y,x = np.ogrid[-y_center:y_size-y_center, -x_center:x_size-x_center]\n mask = x*x + y*y <= radius*radius\n\n # Return the mask\n return mask\n\n# -----------------------------------------------------------------\n\n#def union(*args): # i wanted to do it this way, but didn't succeed ...\ndef union(mask_a, mask_b):\n\n \"\"\"\n This function ...\n :param args:\n :return:\n \"\"\"\n\n return mask_a + mask_b\n\n# -----------------------------------------------------------------\n\n#def intersection(*args): i wanted to do it this way, but didn't succeed ...\ndef intersection(mask_a, mask_b):\n\n \"\"\"\n This function ...\n :param args:\n :return:\n \"\"\"\n\n return mask_a * mask_b\n\n# -----------------------------------------------------------------\n\ndef overlap(mask_a, mask_b):\n\n \"\"\"\n This function ...\n :param mask_a:\n :param mask_b:\n :return:\n \"\"\"\n\n return np.any(intersection(mask_a, mask_b))\n\n# -----------------------------------------------------------------\n\ndef split_overlap(base_mask, test_mask, return_segments=False):\n\n \"\"\"\n This function takes all blobs in the base_mask and checks whether they overlap with the test_mask.\n The function returns two new masks, one mask with all the blobs that overlapped, and another with the blobs\n that did not overlap.\n :param base_mask:\n :param test_mask:\n :return:\n \"\"\"\n\n overlapping = np.zeros_like(base_mask, dtype=bool)\n not_overlapping = np.copy(base_mask)\n\n from photutils import detect_sources\n segments = detect_sources(base_mask.astype('float'), 0.5, 1).data\n overlap = intersection(segments, test_mask)\n\n # Check which indices are present in the overlap map\n possible = np.array(range(1, np.max(overlap) + 1))\n present = np.in1d(possible, overlap)\n indices = possible[present]\n\n overlapping_segments = np.zeros_like(base_mask, dtype=int)\n not_overlapping_segments = np.copy(segments)\n\n # Remove the galaxies from the segmentation map\n for index in indices:\n blob = segments == index\n overlapping[blob] = True\n not_overlapping[blob] = False\n\n overlapping_segments[blob] = index\n not_overlapping_segments[blob] = 0\n\n if return_segments: return overlapping, not_overlapping, overlapping_segments, not_overlapping_segments\n else: return overlapping, not_overlapping\n\n# -----------------------------------------------------------------\n", "#!/usr/bin/env python\n# -*- coding: utf8 -*-\n# *****************************************************************\n# ** PTS -- Python Toolkit for working with SKIRT **\n# ** © Astronomical Observatory, Ghent University **\n# *****************************************************************\n\n## \\package pts.modeling.plotting.attenuation Contains the AttenuationPlotter class.\n\n# -----------------------------------------------------------------\n\n# Ensure Python 3 compatibility\nfrom __future__ import absolute_import, division, print_function\n\n# Import standard modules\nimport matplotlib.pyplot as plt\nfrom collections import OrderedDict\n\n# Import the relevant PTS classes and modules\nfrom ..tools.logging import log\nfrom ...magic.tools.plotting import pretty_colours, line_styles, filled_markers\n\n# -----------------------------------------------------------------\n\nclass AttenuationPlotter(object):\n \n \"\"\"\n This class ...\n \"\"\"\n\n def __init__(self, title=None):\n\n \"\"\"\n This function ...\n :return:\n \"\"\"\n\n # Set the title\n self.title = title\n\n # The different curves\n self.curves = OrderedDict()\n\n # The axis limits\n self.min_wavelength = None\n self.max_wavelength = None\n self.min_attenuation = None\n self.max_attenuation = None\n\n # Properties\n self.transparent = False\n\n # -----------------------------------------------------------------\n\n def set_title(self, title):\n\n \"\"\"\n This function ...\n :param title:\n :return:\n \"\"\"\n\n self.title = title\n\n # -----------------------------------------------------------------\n\n def add_attenuation_curve(self, attenuation_curve, label):\n\n \"\"\"\n This function ...\n :param attenuation_curve:\n :param label:\n :return:\n \"\"\"\n\n self.curves[label] = attenuation_curve\n\n # -----------------------------------------------------------------\n\n def run(self, output_path, min_wavelength=None, max_wavelength=None, min_attenuation=None, max_attenuation=None):\n\n \"\"\"\n This function ...\n :param output_path:\n :param min_wavelength:\n :param max_wavelength:\n :param min_attenuation:\n :param max_attenuation:\n :return:\n \"\"\"\n\n # Set the axis limits\n self.min_wavelength = min_wavelength\n self.max_wavelength = max_wavelength\n self.min_attenuation = min_attenuation\n self.max_attenuation = max_attenuation\n\n # Make the plot\n self.plot(output_path)\n\n # -----------------------------------------------------------------\n\n def clear(self):\n\n \"\"\"\n This function ...\n :return:\n \"\"\"\n\n # Inform the user\n log.info(\"Clearing the attenuation plotter ...\")\n\n # Set default values for all attributes\n self.title = None\n self.curves = OrderedDict()\n self.min_wavelength = None\n self.max_wavelength = None\n self.min_attenuation = None\n self.max_attenuation = None\n self.transparent = False\n\n # -----------------------------------------------------------------\n\n def plot(self, path):\n\n \"\"\"\n This function ...\n :param path:\n :return:\n \"\"\"\n\n # Inform the user\n log.info(\"Making the attenuation plot ...\")\n\n # Plot the attenuation curves\n plt.figure(figsize=(10, 10))\n plt.ylabel('$A_\\lambda/A_V$', fontsize=28)\n plt.xlabel('$\\lambda/\\mu$m', fontsize=28)\n plt.xlim(0.1, 2)\n plt.ylim(0, 8)\n #plt.ylim(0, 1)\n plt.xscale('log')\n x = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1, 2]\n plt.xticks(x, x)\n # plt.yscale('log')\n plt.tick_params(labelsize=17)\n # plt.subplots_adjust(bottom=0.1)\n\n #plt.plot(wl_MW, n_atts_MW, 'r-', label=\"MW\", linewidth=2)\n #plt.plot(wl_SMC, n_atts_SMC, 'b--', label=\"SMC\", linewidth=2)\n #plt.plot(wl_B16, Qfit_B16 + 1, 'g-.', label=\"Battisti+16\", linewidth=3)\n ## plt.plot(wl_Calzetti,n_atts_Calzetti, 'g-', label=\"Cal+94\",linewidth=2)\n\n #plt.plot(modWls, n_atts_tot, 'k-', label=\"M31 tot\", linewidth=2)\n #plt.plot(modWls, n_atts_diff, 'k--', label=\"M31 diffuse\", linewidth=2)\n #plt.plot(modWls, n_atts_mappings, 'k:', label=\"M31 SF regions\", linewidth=2)\n\n colors = iter(pretty_colours)\n\n for label in self.curves:\n\n curve = self.curves[label]\n\n wavelengths = curve.wavelengths(unit=\"micron\", add_unit=False)\n attenuations = curve.attenuations()\n\n # Plot the curve\n plt.plot(wavelengths, attenuations, label=label, linewidth=2, color=next(colors))\n\n #plt.errorbar(wl_M31, n_atts_M31, yerr=err_att_M31, color='m', fmt='ko', markersize=8, label=\"M31- Dong+14\")\n ## plt.plot(1./wl_MWRv5,n_atts_MWRv5, 'm-', label=\"MW Rv=5\")\n ## plt.plot([1./0.55,1./0.55],[0,15], 'k-')\n\n plt.tight_layout()\n plt.legend(loc='upper right', numpoints=1, markerscale=1.5, fontsize=24)\n\n # Debugging\n log.debug(\"Saving the attenuation plot to \" + path + \" ...\")\n\n # Save the figure\n plt.savefig(path, bbox_inches='tight', pad_inches=0.25, transparent=self.transparent)\n plt.close()\n\n# -----------------------------------------------------------------\n" ]
[ [ "numpy.nanmax", "matplotlib.pyplot.tight_layout", "numpy.isnan", "scipy.ndimage.zoom", "numpy.nanmin", "matplotlib.colors.Normalize", "matplotlib.pyplot.savefig", "matplotlib.colorbar.ColorbarBase", "matplotlib.colors.ListedColormap", "matplotlib.gridspec.GridSpec", "matplotlib.pyplot.close", "matplotlib.cm.get_cmap", "matplotlib.cm.register_cmap", "matplotlib.pyplot.show", "matplotlib.pyplot.figure" ], [ "numpy.logical_not", "numpy.in1d", "numpy.max", "numpy.copy", "numpy.zeros_like" ], [ "matplotlib.pyplot.legend", "matplotlib.pyplot.tight_layout", "matplotlib.pyplot.ylim", "matplotlib.pyplot.figure", "matplotlib.pyplot.xscale", "matplotlib.pyplot.savefig", "matplotlib.pyplot.xlim", "matplotlib.pyplot.close", "matplotlib.pyplot.xlabel", "matplotlib.pyplot.xticks", "matplotlib.pyplot.tick_params", "matplotlib.pyplot.ylabel" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [ "1.7", "1.0", "0.10", "1.2", "0.14", "0.19", "1.5", "0.12", "0.17", "0.13", "1.6", "1.4", "1.9", "1.3", "1.10", "0.15", "0.18", "0.16", "1.8" ], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
snosov1/opencv
[ "ce05d6cb89450a5778f4c0169b5da5589798192a", "ce05d6cb89450a5778f4c0169b5da5589798192a", "ce05d6cb89450a5778f4c0169b5da5589798192a" ]
[ "modules/python/test/test_dft.py", "samples/python/gabor_threads.py", "samples/python/digits_adjust.py" ]
[ "#!/usr/bin/env python\n\n'''\nTest for disctrete fourier transform (dft)\n'''\n\n# Python 2/3 compatibility\nfrom __future__ import print_function\n\nimport cv2\nimport numpy as np\nimport sys\n\nfrom tests_common import NewOpenCVTests\n\nclass dft_test(NewOpenCVTests):\n def test_dft(self):\n\n img = self.get_sample('samples/data/rubberwhale1.png', 0)\n eps = 0.001\n\n #test direct transform\n refDft = np.fft.fft2(img)\n refDftShift = np.fft.fftshift(refDft)\n refMagnitide = np.log(1.0 + np.abs(refDftShift))\n\n testDft = cv2.dft(np.float32(img),flags = cv2.DFT_COMPLEX_OUTPUT)\n testDftShift = np.fft.fftshift(testDft)\n testMagnitude = np.log(1.0 + cv2.magnitude(testDftShift[:,:,0], testDftShift[:,:,1]))\n\n refMagnitide = cv2.normalize(refMagnitide, 0.0, 1.0, cv2.NORM_MINMAX)\n testMagnitude = cv2.normalize(testMagnitude, 0.0, 1.0, cv2.NORM_MINMAX)\n\n self.assertLess(cv2.norm(refMagnitide - testMagnitude), eps)\n\n #test inverse transform\n img_back = np.fft.ifft2(refDft)\n img_back = np.abs(img_back)\n\n img_backTest = cv2.idft(testDft)\n img_backTest = cv2.magnitude(img_backTest[:,:,0], img_backTest[:,:,1])\n\n img_backTest = cv2.normalize(img_backTest, 0.0, 1.0, cv2.NORM_MINMAX)\n img_back = cv2.normalize(img_back, 0.0, 1.0, cv2.NORM_MINMAX)\n\n self.assertLess(cv2.norm(img_back - img_backTest), eps)", "#!/usr/bin/env python\n\n'''\ngabor_threads.py\n=========\n\nSample demonstrates:\n- use of multiple Gabor filter convolutions to get Fractalius-like image effect (http://www.redfieldplugins.com/filterFractalius.htm)\n- use of python threading to accelerate the computation\n\nUsage\n-----\ngabor_threads.py [image filename]\n\n'''\n\n# Python 2/3 compatibility\nfrom __future__ import print_function\n\nimport numpy as np\nimport cv2\nfrom multiprocessing.pool import ThreadPool\n\n\ndef build_filters():\n filters = []\n ksize = 31\n for theta in np.arange(0, np.pi, np.pi / 16):\n kern = cv2.getGaborKernel((ksize, ksize), 4.0, theta, 10.0, 0.5, 0, ktype=cv2.CV_32F)\n kern /= 1.5*kern.sum()\n filters.append(kern)\n return filters\n\ndef process(img, filters):\n accum = np.zeros_like(img)\n for kern in filters:\n fimg = cv2.filter2D(img, cv2.CV_8UC3, kern)\n np.maximum(accum, fimg, accum)\n return accum\n\ndef process_threaded(img, filters, threadn = 8):\n accum = np.zeros_like(img)\n def f(kern):\n return cv2.filter2D(img, cv2.CV_8UC3, kern)\n pool = ThreadPool(processes=threadn)\n for fimg in pool.imap_unordered(f, filters):\n np.maximum(accum, fimg, accum)\n return accum\n\nif __name__ == '__main__':\n import sys\n from common import Timer\n\n print(__doc__)\n try:\n img_fn = sys.argv[1]\n except:\n img_fn = '../data/baboon.jpg'\n\n img = cv2.imread(img_fn)\n if img is None:\n print('Failed to load image file:', img_fn)\n sys.exit(1)\n\n filters = build_filters()\n\n with Timer('running single-threaded'):\n res1 = process(img, filters)\n with Timer('running multi-threaded'):\n res2 = process_threaded(img, filters)\n\n print('res1 == res2: ', (res1 == res2).all())\n cv2.imshow('img', img)\n cv2.imshow('result', res2)\n cv2.waitKey()\n cv2.destroyAllWindows()\n", "#!/usr/bin/env python\n\n'''\nDigit recognition adjustment.\nGrid search is used to find the best parameters for SVM and KNearest classifiers.\nSVM adjustment follows the guidelines given in\nhttp://www.csie.ntu.edu.tw/~cjlin/papers/guide/guide.pdf\n\nUsage:\n digits_adjust.py [--model {svm|knearest}]\n\n --model {svm|knearest} - select the classifier (SVM is the default)\n\n'''\n\n# Python 2/3 compatibility\nfrom __future__ import print_function\nimport sys\nPY3 = sys.version_info[0] == 3\n\nif PY3:\n xrange = range\n\nimport numpy as np\nimport cv2\nfrom multiprocessing.pool import ThreadPool\n\nfrom digits import *\n\ndef cross_validate(model_class, params, samples, labels, kfold = 3, pool = None):\n n = len(samples)\n folds = np.array_split(np.arange(n), kfold)\n def f(i):\n model = model_class(**params)\n test_idx = folds[i]\n train_idx = list(folds)\n train_idx.pop(i)\n train_idx = np.hstack(train_idx)\n train_samples, train_labels = samples[train_idx], labels[train_idx]\n test_samples, test_labels = samples[test_idx], labels[test_idx]\n model.train(train_samples, train_labels)\n resp = model.predict(test_samples)\n score = (resp != test_labels).mean()\n print(\".\", end='')\n return score\n if pool is None:\n scores = list(map(f, xrange(kfold)))\n else:\n scores = pool.map(f, xrange(kfold))\n return np.mean(scores)\n\n\nclass App(object):\n def __init__(self):\n self._samples, self._labels = self.preprocess()\n\n def preprocess(self):\n digits, labels = load_digits(DIGITS_FN)\n shuffle = np.random.permutation(len(digits))\n digits, labels = digits[shuffle], labels[shuffle]\n digits2 = list(map(deskew, digits))\n samples = preprocess_hog(digits2)\n return samples, labels\n\n def get_dataset(self):\n return self._samples, self._labels\n\n def run_jobs(self, f, jobs):\n pool = ThreadPool(processes=cv2.getNumberOfCPUs())\n ires = pool.imap_unordered(f, jobs)\n return ires\n\n def adjust_SVM(self):\n Cs = np.logspace(0, 10, 15, base=2)\n gammas = np.logspace(-7, 4, 15, base=2)\n scores = np.zeros((len(Cs), len(gammas)))\n scores[:] = np.nan\n\n print('adjusting SVM (may take a long time) ...')\n def f(job):\n i, j = job\n samples, labels = self.get_dataset()\n params = dict(C = Cs[i], gamma=gammas[j])\n score = cross_validate(SVM, params, samples, labels)\n return i, j, score\n\n ires = self.run_jobs(f, np.ndindex(*scores.shape))\n for count, (i, j, score) in enumerate(ires):\n scores[i, j] = score\n print('%d / %d (best error: %.2f %%, last: %.2f %%)' %\n (count+1, scores.size, np.nanmin(scores)*100, score*100))\n print(scores)\n\n print('writing score table to \"svm_scores.npz\"')\n np.savez('svm_scores.npz', scores=scores, Cs=Cs, gammas=gammas)\n\n i, j = np.unravel_index(scores.argmin(), scores.shape)\n best_params = dict(C = Cs[i], gamma=gammas[j])\n print('best params:', best_params)\n print('best error: %.2f %%' % (scores.min()*100))\n return best_params\n\n def adjust_KNearest(self):\n print('adjusting KNearest ...')\n def f(k):\n samples, labels = self.get_dataset()\n err = cross_validate(KNearest, dict(k=k), samples, labels)\n return k, err\n best_err, best_k = np.inf, -1\n for k, err in self.run_jobs(f, xrange(1, 9)):\n if err < best_err:\n best_err, best_k = err, k\n print('k = %d, error: %.2f %%' % (k, err*100))\n best_params = dict(k=best_k)\n print('best params:', best_params, 'err: %.2f' % (best_err*100))\n return best_params\n\n\nif __name__ == '__main__':\n import getopt\n import sys\n\n print(__doc__)\n\n args, _ = getopt.getopt(sys.argv[1:], '', ['model='])\n args = dict(args)\n args.setdefault('--model', 'svm')\n args.setdefault('--env', '')\n if args['--model'] not in ['svm', 'knearest']:\n print('unknown model \"%s\"' % args['--model'])\n sys.exit(1)\n\n t = clock()\n app = App()\n if args['--model'] == 'knearest':\n app.adjust_KNearest()\n else:\n app.adjust_SVM()\n print('work time: %f s' % (clock() - t))\n" ]
[ [ "numpy.fft.fft2", "numpy.fft.ifft2", "numpy.abs", "numpy.fft.fftshift", "numpy.float32" ], [ "numpy.arange", "numpy.maximum", "numpy.zeros_like" ], [ "numpy.hstack", "numpy.savez", "numpy.logspace", "numpy.arange", "numpy.nanmin", "numpy.mean", "numpy.ndindex" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
Ollie-Hooper/IdeaStreams
[ "26a220e961f68b7239901979ea010ec222cc2c81" ]
[ "8 - Reducing Portfolio Political Risk Using Trump Beta.py" ]
[ "import math\nimport pandas as pd\n\nfrom io import StringIO\n\n\ndata_url = \"https://www.dropbox.com/s/pwm8wlncayp1clh/trump_beta.csv?dl=1\"\n\n\nclass MultidimensionalCalibratedAtmosphericScrubbers(QCAlgorithm):\n\n def Initialize(self):\n self.SetStartDate(2020, 6, 1) # Set Start Date\n self.SetCash(100000) # Set Strategy Cash\n \n symbols = self.get_symbols()\n self.AddUniverseSelection( ManualUniverseSelectionModel(symbols) )\n \n self.AddAlpha( TrumpBetaAlphaModel() )\n \n self.SetPortfolioConstruction( EqualWeightingPortfolioConstructionModel() )\n \n self.SetExecution( ImmediateExecutionModel() )\n\n def get_symbols(self):\n constituents = pd.read_csv(StringIO(self.Download(data_url)), index_col='Date').columns\n return [Symbol.Create(c, SecurityType.Equity, Market.USA) for c in constituents]\n\n\nclass TrumpBetaAlphaModel:\n \n def __init__(self):\n self.thresh = 1/4\n\n def Update(self, algorithm, slice):\n insights = []\n \n trump_beta = pd.Series({k: v.Value for k, v in slice.Get[TrumpBeta]().items()})\n \n low_trump_beta = abs(trump_beta).sort_values()[-math.floor(self.thresh*len(trump_beta)):]\n \n for security in low_trump_beta.keys():\n if algorithm.Securities.ContainsKey(security):\n insight = Insight.Price(security, timedelta(days = 7), InsightDirection.Up)\n insights.append(insight)\n \n return insights\n\n def OnSecuritiesChanged(self, algorithm, changes):\n for added in changes.AddedSecurities:\n algorithm.AddData(TrumpBeta, added.Symbol)\n \n for removed in changes.RemovedSecurities:\n algorithm.RemoveSecurity(removed.Symbol)\n\n\n\nclass TrumpBeta(PythonData):\n\n def GetSource(self, config, date, isLive):\n return SubscriptionDataSource(data_url, SubscriptionTransportMedium.RemoteFile);\n\n\n def Reader(self, config, line, date, isLive):\n data = line.split(',')\n \n if not (line.strip() and line[0].isdigit()):\n self.columns = {data[i]: i for i in range(len(data))}\n return None\n \n ticker = config.Symbol.Value\n \n trump_beta = TrumpBeta()\n trump_beta.Symbol = Symbol.Create(ticker, SecurityType.Equity, Market.USA)\n trump_beta.EndTime = pd.to_datetime(data[self.columns['Date']]) + timedelta(days=1) # Make sure we only get this data AFTER trading day - don't want forward bias.\n \n value = data[self.columns[ticker]]\n \n if not value: return None\n \n trump_beta.Value = float(value)\n\n return trump_beta\n" ]
[ [ "pandas.to_datetime" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "0.23", "0.21", "2.0", "1.4", "0.19", "1.1", "1.5", "1.2", "0.24", "0.20", "1.0", "0.25", "1.3" ], "scipy": [], "tensorflow": [] } ]
dylkot/EbolaSC
[ "d363f9d2c10911f01c7b1d22fec2b192df2569b1" ]
[ "Code/cNMF/cnmf.py" ]
[ "import numpy as np\nimport pandas as pd\nimport os, errno\nimport datetime\nimport uuid\nimport itertools\nimport yaml\nimport subprocess\nimport scipy.sparse as sp\n\n\nfrom scipy.spatial.distance import squareform\nfrom sklearn.decomposition.nmf import non_negative_factorization\nfrom sklearn.cluster import KMeans\nfrom sklearn.metrics import silhouette_score\nfrom sklearn.utils import sparsefuncs\n\n\nfrom fastcluster import linkage\nfrom scipy.cluster.hierarchy import leaves_list\n\nimport matplotlib.pyplot as plt\n\nimport scanpy as sc\n\ndef save_df_to_npz(obj, filename):\n np.savez_compressed(filename, data=obj.values, index=obj.index.values, columns=obj.columns.values)\n\ndef save_df_to_text(obj, filename):\n obj.to_csv(filename, sep='\\t')\n\ndef load_df_from_npz(filename):\n with np.load(filename, allow_pickle=True) as f:\n obj = pd.DataFrame(**f)\n return obj\n\ndef check_dir_exists(path):\n \"\"\"\n Checks if directory already exists or not and creates it if it doesn't\n \"\"\"\n try:\n os.makedirs(path)\n except OSError as exception:\n if exception.errno != errno.EEXIST:\n raise\n\ndef worker_filter(iterable, worker_index, total_workers):\n return (p for i,p in enumerate(iterable) if (i-worker_index)%total_workers==0)\n\ndef fast_euclidean(mat):\n D = mat.dot(mat.T)\n squared_norms = np.diag(D).copy()\n D *= -2.0\n D += squared_norms.reshape((-1,1))\n D += squared_norms.reshape((1,-1))\n D = np.sqrt(D)\n D[D < 0] = 0\n return squareform(D, checks=False)\n\ndef fast_ols_all_cols(X, Y):\n pinv = np.linalg.pinv(X)\n beta = np.dot(pinv, Y)\n return(beta)\n\ndef fast_ols_all_cols_df(X,Y):\n beta = fast_ols_all_cols(X, Y)\n beta = pd.DataFrame(beta, index=X.columns, columns=Y.columns)\n return(beta)\n\ndef var_sparse_matrix(X):\n mean = np.array(X.mean(axis=0)).reshape(-1)\n Xcopy = X.copy()\n Xcopy.data **= 2\n var = np.array(Xcopy.mean(axis=0)).reshape(-1) - (mean**2)\n return(var)\n\n\ndef get_highvar_genes_sparse(expression, expected_fano_threshold=None,\n minimal_mean=0.01, numgenes=None):\n # Find high variance genes within those cells\n gene_mean = np.array(expression.mean(axis=0)).astype(float).reshape(-1)\n E2 = expression.copy(); E2.data **= 2; gene2_mean = np.array(E2.mean(axis=0)).reshape(-1)\n gene_var = pd.Series(gene2_mean - (gene_mean**2))\n del(E2)\n gene_mean = pd.Series(gene_mean)\n gene_fano = gene_var / gene_mean\n\n # Find parameters for expected fano line\n top_genes = gene_mean.sort_values(ascending=False)[:20].index\n A = (np.sqrt(gene_var)/gene_mean)[top_genes].min()\n \n w_mean_low, w_mean_high = gene_mean.quantile([0.10, 0.90])\n w_fano_low, w_fano_high = gene_fano.quantile([0.10, 0.90])\n winsor_box = ((gene_fano > w_fano_low) &\n (gene_fano < w_fano_high) &\n (gene_mean > w_mean_low) &\n (gene_mean < w_mean_high))\n fano_median = gene_fano[winsor_box].median()\n B = np.sqrt(fano_median)\n\n gene_expected_fano = (A**2)*gene_mean + (B**2)\n fano_ratio = (gene_fano/gene_expected_fano)\n\n # Identify high var genes\n if numgenes is not None:\n highvargenes = fano_ratio.sort_values(ascending=False).index[:numgenes]\n high_var_genes_ind = fano_ratio.index.isin(highvargenes)\n T=None\n\n\n else:\n if not expected_fano_threshold:\n T = (1. + gene_counts_fano[winsor_box].std())\n else:\n T = expected_fano_threshold\n\n high_var_genes_ind = (fano_ratio > T) & (gene_counts_mean > minimal_mean)\n\n gene_counts_stats = pd.DataFrame({\n 'mean': gene_mean,\n 'var': gene_var,\n 'fano': gene_fano,\n 'expected_fano': gene_expected_fano,\n 'high_var': high_var_genes_ind,\n 'fano_ratio': fano_ratio\n })\n gene_fano_parameters = {\n 'A': A, 'B': B, 'T':T, 'minimal_mean': minimal_mean,\n }\n return(gene_counts_stats, gene_fano_parameters)\n\n\n\ndef get_highvar_genes(input_counts, expected_fano_threshold=None,\n minimal_mean=0.01, numgenes=None):\n # Find high variance genes within those cells\n gene_counts_mean = pd.Series(input_counts.mean(axis=0).astype(float))\n gene_counts_var = pd.Series(input_counts.var(ddof=0, axis=0).astype(float))\n gene_counts_fano = pd.Series(gene_counts_var/gene_counts_mean)\n\n # Find parameters for expected fano line\n top_genes = gene_counts_mean.sort_values(ascending=False)[:20].index\n A = (np.sqrt(gene_counts_var)/gene_counts_mean)[top_genes].min()\n\n w_mean_low, w_mean_high = gene_counts_mean.quantile([0.10, 0.90])\n w_fano_low, w_fano_high = gene_counts_fano.quantile([0.10, 0.90])\n winsor_box = ((gene_counts_fano > w_fano_low) &\n (gene_counts_fano < w_fano_high) &\n (gene_counts_mean > w_mean_low) &\n (gene_counts_mean < w_mean_high))\n fano_median = gene_counts_fano[winsor_box].median()\n B = np.sqrt(fano_median)\n\n gene_expected_fano = (A**2)*gene_counts_mean + (B**2)\n\n fano_ratio = (gene_counts_fano/gene_expected_fano)\n\n # Identify high var genes\n if numgenes is not None:\n highvargenes = fano_ratio.sort_values(ascending=False).index[:numgenes]\n high_var_genes_ind = fano_ratio.index.isin(highvargenes)\n T=None\n\n\n else:\n if not expected_fano_threshold:\n T = (1. + gene_counts_fano[winsor_box].std())\n else:\n T = expected_fano_threshold\n\n high_var_genes_ind = (fano_ratio > T) & (gene_counts_mean > minimal_mean)\n\n gene_counts_stats = pd.DataFrame({\n 'mean': gene_counts_mean,\n 'var': gene_counts_var,\n 'fano': gene_counts_fano,\n 'expected_fano': gene_expected_fano,\n 'high_var': high_var_genes_ind,\n 'fano_ratio': fano_ratio\n })\n gene_fano_parameters = {\n 'A': A, 'B': B, 'T':T, 'minimal_mean': minimal_mean,\n }\n return(gene_counts_stats, gene_fano_parameters)\n\n\ndef compute_tpm(input_counts):\n \"\"\"\n Default TPM normalization\n \"\"\"\n tpm = input_counts.copy()\n sc.pp.normalize_per_cell(tpm, counts_per_cell_after=1e6)\n return(tpm)\n\n\nclass cNMF():\n\n\n def __init__(self, output_dir=\".\", name=None):\n \"\"\"\n Parameters\n ----------\n\n output_dir : path, optional (default=\".\")\n Output directory for analysis files.\n\n name : string, optional (default=None)\n A name for this analysis. Will be prefixed to all output files.\n If set to None, will be automatically generated from date (and random string).\n \"\"\"\n\n self.output_dir = output_dir\n if name is None:\n now = datetime.datetime.now()\n rand_hash = uuid.uuid4().hex[:6]\n name = '%s_%s' % (now.strftime(\"%Y_%m_%d\"), rand_hash)\n self.name = name\n self.paths = None\n\n\n def _initialize_dirs(self):\n if self.paths is None:\n # Check that output directory exists, create it if needed.\n check_dir_exists(self.output_dir)\n check_dir_exists(os.path.join(self.output_dir, self.name))\n check_dir_exists(os.path.join(self.output_dir, self.name, 'cnmf_tmp'))\n\n self.paths = {\n 'normalized_counts' : os.path.join(self.output_dir, self.name, 'cnmf_tmp', self.name+'.norm_counts.h5ad'),\n 'nmf_replicate_parameters' : os.path.join(self.output_dir, self.name, 'cnmf_tmp', self.name+'.nmf_params.df.npz'),\n 'nmf_run_parameters' : os.path.join(self.output_dir, self.name, 'cnmf_tmp', self.name+'.nmf_idvrun_params.yaml'),\n 'nmf_genes_list' : os.path.join(self.output_dir, self.name, self.name+'.overdispersed_genes.txt'),\n\n 'tpm' : os.path.join(self.output_dir, self.name, 'cnmf_tmp', self.name+'.tpm.h5ad'),\n 'tpm_stats' : os.path.join(self.output_dir, self.name, 'cnmf_tmp', self.name+'.tpm_stats.df.npz'),\n\n 'iter_spectra' : os.path.join(self.output_dir, self.name, 'cnmf_tmp', self.name+'.spectra.k_%d.iter_%d.df.npz'),\n 'iter_usages' : os.path.join(self.output_dir, self.name, 'cnmf_tmp', self.name+'.usages.k_%d.iter_%d.df.npz'),\n 'merged_spectra': os.path.join(self.output_dir, self.name, 'cnmf_tmp', self.name+'.spectra.k_%d.merged.df.npz'),\n\n 'local_density_cache': os.path.join(self.output_dir, self.name, 'cnmf_tmp', self.name+'.local_density_cache.k_%d.merged.df.npz'),\n 'consensus_spectra': os.path.join(self.output_dir, self.name, 'cnmf_tmp', self.name+'.spectra.k_%d.dt_%s.consensus.df.npz'),\n 'consensus_spectra__txt': os.path.join(self.output_dir, self.name, self.name+'.spectra.k_%d.dt_%s.consensus.txt'),\n 'consensus_usages': os.path.join(self.output_dir, self.name, 'cnmf_tmp',self.name+'.usages.k_%d.dt_%s.consensus.df.npz'),\n 'consensus_usages__txt': os.path.join(self.output_dir, self.name, self.name+'.usages.k_%d.dt_%s.consensus.txt'),\n\n 'consensus_stats': os.path.join(self.output_dir, self.name, 'cnmf_tmp', self.name+'.stats.k_%d.dt_%s.df.npz'),\n\n 'clustering_plot': os.path.join(self.output_dir, self.name, self.name+'.clustering.k_%d.dt_%s.png'),\n 'gene_spectra_score': os.path.join(self.output_dir, self.name, 'cnmf_tmp', self.name+'.gene_spectra_score.k_%d.dt_%s.df.npz'),\n 'gene_spectra_score__txt': os.path.join(self.output_dir, self.name, self.name+'.gene_spectra_score.k_%d.dt_%s.txt'),\n 'gene_spectra_tpm': os.path.join(self.output_dir, self.name, 'cnmf_tmp', self.name+'.gene_spectra_tpm.k_%d.dt_%s.df.npz'),\n 'gene_spectra_tpm__txt': os.path.join(self.output_dir, self.name, self.name+'.gene_spectra_tpm.k_%d.dt_%s.txt'),\n\n 'k_selection_plot' : os.path.join(self.output_dir, self.name, self.name+'.k_selection.png'),\n 'k_selection_stats' : os.path.join(self.output_dir, self.name, self.name+'.k_selection_stats.df.npz'),\n }\n\n\n def get_norm_counts(self, counts, tpm,\n high_variance_genes_filter = None,\n num_highvar_genes = None\n ):\n \"\"\"\n Parameters\n ----------\n\n counts : anndata.AnnData\n Scanpy AnnData object (cells x genes) containing raw counts. Filtered such that\n no genes or cells with 0 counts\n \n tpm : anndata.AnnData\n Scanpy AnnData object (cells x genes) containing tpm normalized data matching\n counts\n\n high_variance_genes_filter : np.array, optional (default=None)\n A pre-specified list of genes considered to be high-variance.\n Only these genes will be used during factorization of the counts matrix.\n Must match the .var index of counts and tpm.\n If set to None, high-variance genes will be automatically computed, using the\n parameters below.\n\n num_highvar_genes : int, optional (default=None)\n Instead of providing an array of high-variance genes, identify this many most overdispersed genes\n for filtering\n\n Returns\n -------\n\n normcounts : anndata.AnnData, shape (cells, num_highvar_genes)\n A counts matrix containing only the high variance genes and with columns (genes)normalized to unit\n variance\n\n \"\"\"\n\n if high_variance_genes_filter is None:\n ## Get list of high-var genes if one wasn't provided\n if sp.issparse(tpm.X):\n (gene_counts_stats, gene_fano_params) = get_highvar_genes_sparse(tpm.X, numgenes=num_highvar_genes) \n else:\n (gene_counts_stats, gene_fano_params) = get_highvar_genes(np.array(tpm.X), numgenes=num_highvar_genes)\n \n high_variance_genes_filter = list(tpm.var.index[gene_counts_stats.high_var.values])\n \n ## Subset out high-variance genes\n norm_counts = counts[:, high_variance_genes_filter]\n\n ## Scale genes to unit variance\n if sp.issparse(tpm.X):\n sc.pp.scale(norm_counts, zero_center=False)\n if np.isnan(norm_counts.X.data).sum() > 0:\n print('Warning NaNs in normalized counts matrix') \n else:\n norm_counts.X /= norm_counts.X.std(axis=0, ddof=1)\n if np.isnan(norm_counts.X).sum().sum() > 0:\n print('Warning NaNs in normalized counts matrix') \n \n ## Save a \\n-delimited list of the high-variance genes used for factorization\n open(self.paths['nmf_genes_list'], 'w').write('\\n'.join(high_variance_genes_filter))\n\n ## Check for any cells that have 0 counts of the overdispersed genes\n zerocells = norm_counts.X.sum(axis=1)==0\n if zerocells.sum()>0:\n examples = norm_counts.obs.index[zerocells]\n print('Warning: %d cells have zero counts of overdispersed genes. E.g. %s' % (zerocells.sum(), examples[0]))\n print('Consensus step may not run when this is the case')\n \n return(norm_counts)\n\n \n def save_norm_counts(self, norm_counts):\n self._initialize_dirs()\n sc.write(self.paths['normalized_counts'], norm_counts)\n\n \n def get_nmf_iter_params(self, ks, n_iter = 100,\n random_state_seed = None,\n beta_loss = 'kullback-leibler'):\n \"\"\"\n Create a DataFrame with parameters for NMF iterations.\n\n\n Parameters\n ----------\n ks : integer, or list-like.\n Number of topics (components) for factorization.\n Several values can be specified at the same time, which will be run independently.\n\n n_iter : integer, optional (defailt=100)\n Number of iterations for factorization. If several ``k`` are specified, this many\n iterations will be run for each value of ``k``.\n\n random_state_seed : int or None, optional (default=None)\n Seed for sklearn random state.\n\n \"\"\"\n\n if type(ks) is int:\n ks = [ks]\n\n # Remove any repeated k values, and order.\n k_list = sorted(set(list(ks)))\n\n n_runs = len(ks)* n_iter\n\n np.random.seed(seed=random_state_seed)\n nmf_seeds = np.random.randint(low=1, high=(2**32)-1, size=n_runs)\n\n replicate_params = []\n for i, (k, r) in enumerate(itertools.product(k_list, range(n_iter))):\n replicate_params.append([k, r, nmf_seeds[i]])\n replicate_params = pd.DataFrame(replicate_params, columns = ['n_components', 'iter', 'nmf_seed'])\n\n _nmf_kwargs = dict(\n alpha=0.0,\n l1_ratio=0.0,\n beta_loss=beta_loss,\n solver='mu',\n tol=1e-4,\n max_iter=400,\n regularization=None,\n init='random'\n )\n \n ## Coordinate descent is faster than multiplicative update but only works for frobenius\n if beta_loss == 'frobenius':\n _nmf_kwargs['solver'] = 'cd'\n\n return(replicate_params, _nmf_kwargs)\n\n\n def save_nmf_iter_params(self, replicate_params, run_params):\n self._initialize_dirs()\n save_df_to_npz(replicate_params, self.paths['nmf_replicate_parameters'])\n with open(self.paths['nmf_run_parameters'], 'w') as F:\n yaml.dump(run_params, F)\n\n\n def _nmf(self, X, nmf_kwargs):\n \"\"\"\n Parameters\n ----------\n X : pandas.DataFrame,\n Normalized counts dataFrame to be factorized.\n\n nmf_kwargs : dict,\n Arguments to be passed to ``non_negative_factorization``\n\n \"\"\"\n (usages, spectra, niter) = non_negative_factorization(X, **nmf_kwargs)\n\n return(spectra, usages)\n\n\n def run_nmf(self,\n worker_i=1, total_workers=1,\n ):\n \"\"\"\n Iteratively run NMF with prespecified parameters.\n\n Use the `worker_i` and `total_workers` parameters for parallelization.\n\n Generic kwargs for NMF are loaded from self.paths['nmf_run_parameters'], defaults below::\n\n ``non_negative_factorization`` default arguments:\n alpha=0.0\n l1_ratio=0.0\n beta_loss='kullback-leibler'\n solver='mu'\n tol=1e-4,\n max_iter=200\n regularization=None\n init='random'\n random_state, n_components are both set by the prespecified self.paths['nmf_replicate_parameters'].\n\n\n Parameters\n ----------\n norm_counts : pandas.DataFrame,\n Normalized counts dataFrame to be factorized.\n (Output of ``normalize_counts``)\n\n run_params : pandas.DataFrame,\n Parameters for NMF iterations.\n (Output of ``prepare_nmf_iter_params``)\n\n \"\"\"\n self._initialize_dirs()\n run_params = load_df_from_npz(self.paths['nmf_replicate_parameters'])\n norm_counts = sc.read(self.paths['normalized_counts'])\n _nmf_kwargs = yaml.load(open(self.paths['nmf_run_parameters']), Loader=yaml.FullLoader)\n\n jobs_for_this_worker = worker_filter(range(len(run_params)), worker_i, total_workers)\n for idx in jobs_for_this_worker:\n\n p = run_params.iloc[idx, :]\n print('[Worker %d]. Starting task %d.' % (worker_i, idx))\n _nmf_kwargs['random_state'] = p['nmf_seed']\n _nmf_kwargs['n_components'] = p['n_components']\n\n (spectra, usages) = self._nmf(norm_counts.X, _nmf_kwargs)\n spectra = pd.DataFrame(spectra,\n index=np.arange(1, _nmf_kwargs['n_components']+1),\n columns=norm_counts.var.index)\n save_df_to_npz(spectra, self.paths['iter_spectra'] % (p['n_components'], p['iter']))\n\n\n def combine_nmf(self, k, remove_individual_iterations=False):\n run_params = load_df_from_npz(self.paths['nmf_replicate_parameters'])\n print('Combining factorizations for k=%d.'%k)\n\n self._initialize_dirs()\n\n combined_spectra = None\n n_iter = sum(run_params.n_components==k)\n\n run_params_subset = run_params[run_params.n_components==k].sort_values('iter')\n spectra_labels = []\n\n for i,p in run_params_subset.iterrows():\n\n spectra = load_df_from_npz(self.paths['iter_spectra'] % (p['n_components'], p['iter']))\n if combined_spectra is None:\n combined_spectra = np.zeros((n_iter, k, spectra.shape[1]))\n combined_spectra[p['iter'], :, :] = spectra.values\n\n for t in range(k):\n spectra_labels.append('iter%d_topic%d'%(p['iter'], t+1))\n\n combined_spectra = combined_spectra.reshape(-1, combined_spectra.shape[-1])\n combined_spectra = pd.DataFrame(combined_spectra, columns=spectra.columns, index=spectra_labels)\n\n save_df_to_npz(combined_spectra, self.paths['merged_spectra']%k)\n return combined_spectra\n\n\n def consensus(self, k, density_threshold_str='0.5', local_neighborhood_size = 0.30,show_clustering = False,\n skip_density_and_return_after_stats = False, close_clustergram_fig=True):\n merged_spectra = load_df_from_npz(self.paths['merged_spectra']%k)\n norm_counts = sc.read(self.paths['normalized_counts'])\n\n if skip_density_and_return_after_stats:\n density_threshold_str = '2'\n density_threshold_repl = density_threshold_str.replace('.', '_')\n density_threshold = float(density_threshold_str)\n n_neighbors = int(local_neighborhood_size * merged_spectra.shape[0]/k)\n\n # Rescale topics such to length of 1.\n l2_spectra = (merged_spectra.T/np.sqrt((merged_spectra**2).sum(axis=1))).T\n\n\n if not skip_density_and_return_after_stats:\n # Compute the local density matrix (if not previously cached)\n topics_dist = None\n if os.path.isfile(self.paths['local_density_cache'] % k):\n local_density = load_df_from_npz(self.paths['local_density_cache'] % k)\n else:\n # first find the full distance matrix\n topics_dist = squareform(fast_euclidean(l2_spectra.values))\n # partition based on the first n neighbors\n partitioning_order = np.argpartition(topics_dist, n_neighbors+1)[:, :n_neighbors+1]\n # find the mean over those n_neighbors (excluding self, which has a distance of 0)\n distance_to_nearest_neighbors = topics_dist[np.arange(topics_dist.shape[0])[:, None], partitioning_order]\n local_density = pd.DataFrame(distance_to_nearest_neighbors.sum(1)/(n_neighbors),\n columns=['local_density'],\n index=l2_spectra.index)\n save_df_to_npz(local_density, self.paths['local_density_cache'] % k)\n del(partitioning_order)\n del(distance_to_nearest_neighbors)\n\n density_filter = local_density.iloc[:, 0] < density_threshold\n l2_spectra = l2_spectra.loc[density_filter, :]\n\n kmeans_model = KMeans(n_clusters=k, n_init=10, random_state=1)\n kmeans_model.fit(l2_spectra)\n kmeans_cluster_labels = pd.Series(kmeans_model.labels_+1, index=l2_spectra.index)\n\n # Find median usage for each gene across cluster\n median_spectra = l2_spectra.groupby(kmeans_cluster_labels).median()\n\n # Normalize median spectra to probability distributions.\n median_spectra = (median_spectra.T/median_spectra.sum(1)).T\n\n # Compute the silhouette score\n stability = silhouette_score(l2_spectra.values, kmeans_cluster_labels, metric='euclidean')\n\n # Obtain the reconstructed count matrix by re-fitting the usage matrix and computing the dot product: usage.dot(spectra)\n refit_nmf_kwargs = yaml.load(open(self.paths['nmf_run_parameters']), Loader=yaml.FullLoader)\n refit_nmf_kwargs.update(dict(\n n_components = k,\n H = median_spectra.values,\n update_H = False\n ))\n \n _, rf_usages = self._nmf(norm_counts.X,\n nmf_kwargs=refit_nmf_kwargs)\n rf_usages = pd.DataFrame(rf_usages, index=norm_counts.obs.index, columns=median_spectra.index)\n rf_pred_norm_counts = rf_usages.dot(median_spectra)\n\n # Compute prediction error as a frobenius norm\n if sp.issparse(norm_counts.X):\n prediction_error = ((norm_counts.X.todense() - rf_pred_norm_counts)**2).sum().sum()\n else:\n prediction_error = ((norm_counts.X - rf_pred_norm_counts)**2).sum().sum()\n \n consensus_stats = pd.DataFrame([k, density_threshold, stability, prediction_error],\n index = ['k', 'local_density_threshold', 'stability', 'prediction_error'],\n columns = ['stats'])\n\n if skip_density_and_return_after_stats:\n return consensus_stats\n \n save_df_to_npz(median_spectra, self.paths['consensus_spectra']%(k, density_threshold_repl))\n save_df_to_npz(rf_usages, self.paths['consensus_usages']%(k, density_threshold_repl))\n save_df_to_npz(consensus_stats, self.paths['consensus_stats']%(k, density_threshold_repl))\n save_df_to_text(median_spectra, self.paths['consensus_spectra__txt']%(k, density_threshold_repl))\n save_df_to_text(rf_usages, self.paths['consensus_usages__txt']%(k, density_threshold_repl))\n\n # Compute gene-scores for each GEP by regressing usage on Z-scores of TPM\n tpm = sc.read(self.paths['tpm'])\n tpm_stats = load_df_from_npz(self.paths['tpm_stats'])\n \n if sp.issparse(tpm.X):\n norm_tpm = (np.array(tpm.X.todense()) - tpm_stats['__mean'].values) / tpm_stats['__std'].values\n else:\n norm_tpm = (tpm.X - tpm_stats['__mean'].values) / tpm_stats['__std'].values\n \n usage_coef = fast_ols_all_cols(rf_usages.values, norm_tpm)\n usage_coef = pd.DataFrame(usage_coef, index=rf_usages.columns, columns=tpm.var.index)\n\n save_df_to_npz(usage_coef, self.paths['gene_spectra_score']%(k, density_threshold_repl))\n save_df_to_text(usage_coef, self.paths['gene_spectra_score__txt']%(k, density_threshold_repl))\n\n # Convert spectra to TPM units, and obtain results for all genes by running last step of NMF\n # with usages fixed and TPM as the input matrix\n norm_usages = rf_usages.div(rf_usages.sum(axis=1), axis=0)\n refit_nmf_kwargs.update(dict(\n H = norm_usages.T.values,\n ))\n \n _, spectra_tpm = self._nmf(tpm.X.T, nmf_kwargs=refit_nmf_kwargs)\n spectra_tpm = pd.DataFrame(spectra_tpm.T, index=rf_usages.columns, columns=tpm.var.index)\n save_df_to_npz(spectra_tpm, self.paths['gene_spectra_tpm']%(k, density_threshold_repl))\n save_df_to_text(spectra_tpm, self.paths['gene_spectra_tpm__txt']%(k, density_threshold_repl))\n\n if show_clustering:\n if topics_dist is None:\n topics_dist = squareform(fast_euclidean(l2_spectra.values))\n # (l2_spectra was already filtered using the density filter)\n else:\n # (but the previously computed topics_dist was not!)\n topics_dist = topics_dist[density_filter.values, :][:, density_filter.values]\n\n\n spectra_order = []\n for cl in sorted(set(kmeans_cluster_labels)):\n\n cl_filter = kmeans_cluster_labels==cl\n\n if cl_filter.sum() > 1:\n cl_dist = squareform(topics_dist[cl_filter, :][:, cl_filter])\n cl_dist[cl_dist < 0] = 0 #Rarely get floating point arithmetic issues\n cl_link = linkage(cl_dist, 'average')\n cl_leaves_order = leaves_list(cl_link)\n\n spectra_order += list(np.where(cl_filter)[0][cl_leaves_order])\n else:\n ## Corner case where a component only has one element\n spectra_order += list(np.where(cl_filter)[0])\n\n\n from matplotlib import gridspec\n import matplotlib.pyplot as plt\n\n width_ratios = [0.5, 9, 0.5, 4, 1]\n height_ratios = [0.5, 9]\n fig = plt.figure(figsize=(sum(width_ratios), sum(height_ratios)))\n gs = gridspec.GridSpec(len(height_ratios), len(width_ratios), fig,\n 0.01, 0.01, 0.98, 0.98,\n height_ratios=height_ratios,\n width_ratios=width_ratios,\n wspace=0, hspace=0)\n\n dist_ax = fig.add_subplot(gs[1,1], xscale='linear', yscale='linear',\n xticks=[], yticks=[],xlabel='', ylabel='',\n frameon=True)\n\n D = topics_dist[spectra_order, :][:, spectra_order]\n dist_im = dist_ax.imshow(D, interpolation='none', cmap='viridis', aspect='auto',\n rasterized=True)\n\n left_ax = fig.add_subplot(gs[1,0], xscale='linear', yscale='linear', xticks=[], yticks=[],\n xlabel='', ylabel='', frameon=True)\n left_ax.imshow(kmeans_cluster_labels.values[spectra_order].reshape(-1, 1),\n interpolation='none', cmap='Spectral', aspect='auto',\n rasterized=True)\n\n\n top_ax = fig.add_subplot(gs[0,1], xscale='linear', yscale='linear', xticks=[], yticks=[],\n xlabel='', ylabel='', frameon=True)\n top_ax.imshow(kmeans_cluster_labels.values[spectra_order].reshape(1, -1),\n interpolation='none', cmap='Spectral', aspect='auto',\n rasterized=True)\n\n\n hist_gs = gridspec.GridSpecFromSubplotSpec(3, 1, subplot_spec=gs[1, 3],\n wspace=0, hspace=0)\n\n hist_ax = fig.add_subplot(hist_gs[0,0], xscale='linear', yscale='linear',\n xlabel='', ylabel='', frameon=True, title='Local density histogram')\n hist_ax.hist(local_density.values, bins=np.linspace(0, 1, 50))\n hist_ax.yaxis.tick_right()\n\n xlim = hist_ax.get_xlim()\n ylim = hist_ax.get_ylim()\n if density_threshold < xlim[1]:\n hist_ax.axvline(density_threshold, linestyle='--', color='k')\n hist_ax.text(density_threshold + 0.02, ylim[1] * 0.95, 'filtering\\nthreshold\\n\\n', va='top')\n hist_ax.set_xlim(xlim)\n hist_ax.set_xlabel('Mean distance to k nearest neighbors\\n\\n%d/%d (%.0f%%) spectra above threshold\\nwere removed prior to clustering'%(sum(~density_filter), len(density_filter), 100*(~density_filter).mean()))\n\n fig.savefig(self.paths['clustering_plot']%(k, density_threshold_repl), dpi=250)\n if close_clustergram_fig:\n plt.close(fig)\n\n\n def k_selection_plot(self, close_fig=True):\n '''\n Borrowed from Alexandrov Et Al. 2013 Deciphering Mutational Signatures\n publication in Cell Reports\n '''\n run_params = load_df_from_npz(self.paths['nmf_replicate_parameters'])\n stats = []\n for k in sorted(set(run_params.n_components)):\n\n stats.append(self.consensus(k, skip_density_and_return_after_stats=True).stats)\n\n stats = pd.DataFrame(stats)\n stats.reset_index(drop = True, inplace = True)\n\n save_df_to_npz(stats, self.paths['k_selection_stats'])\n\n fig = plt.figure(figsize=(6, 4))\n ax1 = fig.add_subplot(111)\n ax2 = ax1.twinx()\n\n\n ax1.plot(stats.k, stats.stability, 'o-', color='b')\n ax1.set_ylabel('Stability', color='b', fontsize=15)\n for tl in ax1.get_yticklabels():\n tl.set_color('b')\n #ax1.set_xlabel('K', fontsize=15)\n\n ax2.plot(stats.k, stats.prediction_error, 'o-', color='r')\n ax2.set_ylabel('Error', color='r', fontsize=15)\n for tl in ax2.get_yticklabels():\n tl.set_color('r')\n\n ax1.set_xlabel('Number of Components', fontsize=15)\n ax1.grid('on')\n plt.tight_layout()\n fig.savefig(self.paths['k_selection_plot'], dpi=250)\n if close_fig:\n plt.close(fig)\n\n\n\nif __name__==\"__main__\":\n \"\"\"\n Example commands for now:\n\n output_dir=\"/Users/averes/Projects/Melton/Notebooks/2018/07-2018/cnmf_test/\"\n\n\n python cnmf.py prepare --output-dir $output_dir \\\n --name test --counts /Users/averes/Projects/Melton/Notebooks/2018/07-2018/cnmf_test/test_data.df.npz \\\n -k 6 7 8 9 --n-iter 5\n\n python cnmf.py factorize --name test --output-dir $output_dir\n\n THis can be parallelized as such:\n\n python cnmf.py factorize --name test --output-dir $output_dir --total-workers 2 --worker-index WORKER_INDEX (where worker_index starts with 0)\n\n python cnmf.py combine --name test --output-dir $output_dir\n\n python cnmf.py consensus --name test --output-dir $output_dir\n\n \"\"\"\n\n import sys, argparse\n parser = argparse.ArgumentParser()\n\n parser.add_argument('command', type=str, choices=['prepare', 'factorize', 'combine', 'consensus', 'k_selection_plot'])\n parser.add_argument('--name', type=str, help='[all] Name for analysis. All output will be placed in [output-dir]/[name]/...', nargs='?', default='cNMF')\n parser.add_argument('--output-dir', type=str, help='[all] Output directory. All output will be placed in [output-dir]/[name]/...', nargs='?', default='.')\n\n parser.add_argument('-c', '--counts', type=str, help='[prepare] Input (cell x gene) counts matrix as df.npz or tab delimited text file')\n parser.add_argument('-k', '--components', type=int, help='[prepare] Numper of components (k) for matrix factorization. Several can be specified with \"-k 8 9 10\"', nargs='+')\n parser.add_argument('-n', '--n-iter', type=int, help='[prepare] Numper of factorization replicates', default=100)\n parser.add_argument('--total-workers', type=int, help='[all] Total number of workers to distribute jobs to', default=1)\n parser.add_argument('--seed', type=int, help='[prepare] Seed for pseudorandom number generation', default=None)\n parser.add_argument('--genes-file', type=str, help='[prepare] File containing a list of genes to include, one gene per line. Must match column labels of counts matrix.', default=None)\n parser.add_argument('--numgenes', type=int, help='[prepare] Number of high variance genes to use for matrix factorization.', default=2000)\n parser.add_argument('--tpm', type=str, help='[prepare] Pre-computed (cell x gene) TPM values as df.npz or tab separated txt file. If not provided TPM will be calculated automatically', default=None)\n parser.add_argument('--beta-loss', type=str, choices=['frobenius', 'kullback-leibler', 'itakura-saito'], help='[prepare] Loss function for NMF.', default='frobenius')\n parser.add_argument('--densify', dest='densify', help='[prepare] Treat the input data as non-sparse', action='store_true', default=False)\n\n \n parser.add_argument('--worker-index', type=int, help='[factorize] Index of current worker (the first worker should have index 0)', default=0)\n \n parser.add_argument('--local-density-threshold', type=str, help='[consensus] Threshold for the local density filtering. This string must convert to a float >0 and <=2', default='0.5')\n parser.add_argument('--local-neighborhood-size', type=float, help='[consensus] Fraction of the number of replicates to use as nearest neighbors for local density filtering', default=0.30)\n parser.add_argument('--show-clustering', dest='show_clustering', help='[consensus] Produce a clustergram figure summarizing the spectra clustering', action='store_true')\n\n args = parser.parse_args()\n\n cnmf_obj = cNMF(output_dir=args.output_dir, name=args.name)\n cnmf_obj._initialize_dirs()\n \n if args.command == 'prepare':\n\n if args.counts.endswith('.h5ad'):\n input_counts = sc.read(args.counts)\n else:\n ## Load txt or compressed dataframe and convert to scanpy object\n if args.counts.endswith('.npz'):\n input_counts = load_df_from_npz(args.counts)\n else:\n input_counts = pd.read_csv(args.counts, sep='\\t', index_col=0)\n \n if args.densify:\n input_counts = sc.AnnData(X=input_counts.values,\n obs=pd.DataFrame(index=input_counts.index),\n var=pd.DataFrame(index=input_counts.columns))\n else:\n input_counts = sc.AnnData(X=sp.csr_matrix(input_counts.values),\n obs=pd.DataFrame(index=input_counts.index),\n var=pd.DataFrame(index=input_counts.columns))\n\n \n if sp.issparse(input_counts.X) & args.densify:\n input_counts.X = np.array(input_counts.X.todense())\n \n if args.tpm is None:\n tpm = compute_tpm(input_counts)\n sc.write(cnmf_obj.paths['tpm'], tpm)\n elif args.tpm.endswith('.h5ad'):\n subprocess.call('cp %s %s' % (args.tpm, cnmf_obj.paths['tpm']), shell=True)\n tpm = sc.read(cnmf_obj.paths['tpm'])\n else:\n if args.tpm.endswith('.npz'):\n tpm = load_df_from_npz(args.tpm)\n else:\n tpm = pd.read_csv(args.tpm, sep='\\t', index_col=0)\n \n if args.densify:\n tpm = sc.AnnData(X=tpm.values,\n obs=pd.DataFrame(index=tpm.index),\n var=pd.DataFrame(index=tpm.columns)) \n else:\n tpm = sc.AnnData(X=sp.csr_matrix(tpm.values),\n obs=pd.DataFrame(index=tpm.index),\n var=pd.DataFrame(index=tpm.columns)) \n\n sc.write(cnmf_obj.paths['tpm'], tpm)\n \n if sp.issparse(tpm.X):\n gene_tpm_mean = np.array(tpm.X.mean(axis=0)).reshape(-1)\n gene_tpm_stddev = var_sparse_matrix(tpm.X)**.5\n else:\n gene_tpm_mean = np.array(tpm.X.mean(axis=0)).reshape(-1)\n gene_tpm_stddev = np.array(tpm.X.std(axis=0, ddof=0)).reshape(-1)\n \n \n input_tpm_stats = pd.DataFrame([gene_tpm_mean, gene_tpm_stddev],\n index = ['__mean', '__std']).T\n save_df_to_npz(input_tpm_stats, cnmf_obj.paths['tpm_stats'])\n \n if args.genes_file is not None:\n highvargenes = open(args.genes_file).read().rstrip().split('\\n')\n else:\n highvargenes = None\n\n norm_counts = cnmf_obj.get_norm_counts(input_counts, tpm, num_highvar_genes=args.numgenes,\n high_variance_genes_filter=highvargenes)\n cnmf_obj.save_norm_counts(norm_counts)\n (replicate_params, run_params) = cnmf_obj.get_nmf_iter_params(ks=args.components, n_iter=args.n_iter, random_state_seed=args.seed, beta_loss=args.beta_loss)\n cnmf_obj.save_nmf_iter_params(replicate_params, run_params)\n\n\n elif args.command == 'factorize':\n cnmf_obj.run_nmf(worker_i=args.worker_index, total_workers=args.total_workers)\n\n elif args.command == 'combine':\n run_params = load_df_from_npz(cnmf_obj.paths['nmf_replicate_parameters'])\n\n if type(args.components) is int:\n ks = [args.components]\n elif args.components is None:\n ks = sorted(set(run_params.n_components))\n else:\n ks = args.components\n\n for k in ks:\n cnmf_obj.combine_nmf(k)\n\n elif args.command == 'consensus':\n run_params = load_df_from_npz(cnmf_obj.paths['nmf_replicate_parameters'])\n\n if type(args.components) is int:\n ks = [args.components]\n elif args.components is None:\n ks = sorted(set(run_params.n_components))\n else:\n ks = args.components\n\n for k in ks:\n merged_spectra = load_df_from_npz(cnmf_obj.paths['merged_spectra']%k)\n cnmf_obj.consensus(k, args.local_density_threshold, args.local_neighborhood_size, args.show_clustering)\n\n elif args.command == 'k_selection_plot':\n cnmf_obj.k_selection_plot()\n" ]
[ [ "numpy.diag", "numpy.dot", "scipy.cluster.hierarchy.leaves_list", "numpy.sqrt", "pandas.Series", "sklearn.cluster.KMeans", "sklearn.metrics.silhouette_score", "numpy.linspace", "pandas.DataFrame", "scipy.spatial.distance.squareform", "numpy.where", "numpy.random.randint", "matplotlib.pyplot.tight_layout", "pandas.read_csv", "scipy.sparse.issparse", "numpy.arange", "numpy.argpartition", "matplotlib.pyplot.close", "numpy.load", "numpy.zeros", "sklearn.decomposition.nmf.non_negative_factorization", "matplotlib.pyplot.figure", "numpy.isnan", "scipy.sparse.csr_matrix", "numpy.array", "matplotlib.gridspec.GridSpecFromSubplotSpec", "numpy.random.seed", "numpy.linalg.pinv", "numpy.savez_compressed" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "2.0", "1.4", "1.3", "1.1", "1.5", "1.2" ], "scipy": [ "0.13", "1.6", "0.14", "1.10", "0.15", "1.4", "1.3", "1.9", "0.19", "1.5", "0.18", "1.2", "1.7", "0.12", "1.0", "0.17", "0.16", "1.8" ], "tensorflow": [] } ]
konabuta/fta-azure-machine-learning
[ "70da95e7a4c9b3e42db61bb0f69eda8e07c28eee" ]
[ "fundamentals/src/notebooks/030_scripts/train_with_azureml_workspace.py" ]
[ "import argparse\nimport os\nimport joblib\nimport mlflow\nfrom sklearn.pipeline import make_pipeline\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.linear_model import LassoLars\nfrom azureml.core import Workspace\nfrom azureml.core.run import Run, _OfflineRun\n\n# This script can run locally using\n# python <name>.py --alpha 0.9\nparser = argparse.ArgumentParser()\nparser.add_argument(\"--alpha\", type=float, dest=\"alpha\", help=\"The alpha parameter\")\nargs, unknown_args = parser.parse_known_args()\n\n# This code could have been much simpler if we were only planning\n# to run on a remote compute passing the dataset as a named input.\n# This code allows you to run the same script in a local terminal.\n\n# Get access to the workspace\nrun = Run.get_context()\nws = None\nif type(run) == _OfflineRun:\n # If running locally\n ws = Workspace.from_config()\nelse:\n # If running on remote cluster\n ws = run.experiment.workspace\n\n# Prepare the training dataset\ndiabetes_ds = None\nif type(run) != _OfflineRun and \"diabetes_dataset\" in run.input_datasets:\n # If we passed the dataset as_named_input\n diabetes_ds = run.input_datasets[\"diabetes_dataset\"]\n print(\"Loading dataset from input\")\nelse:\n # If we are offline, or we didn't pass the dataset as input,\n # get the latest dataset, registered in 010_basic_sdk.ipynb\n diabetes_ds = ws.datasets[\"diabetes-tabular\"]\n print(\"Loading dataset from workspace\")\n\nX = diabetes_ds.drop_columns(\"target\").to_pandas_dataframe()\ny = diabetes_ds.keep_columns(\"target\").to_pandas_dataframe()\n\n# Tracking with mlflow\nmlflow.sklearn.autolog()\n\npipe = make_pipeline(StandardScaler(), LassoLars(alpha=args.alpha))\npipe.fit(X, y)\n\nos.makedirs(\"./outputs\", exist_ok=True)\njoblib.dump(value=pipe, filename=\"./outputs/custom_serialization.pkl\")\n\nprint(os.environ.get(\"MY_VAR\", \"MY_VAR is not set\"))\n" ]
[ [ "sklearn.preprocessing.StandardScaler", "sklearn.linear_model.LassoLars" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
BaldLee/tvm
[ "b53472c7b6afa34260afeffc5f088591352c58c3", "b53472c7b6afa34260afeffc5f088591352c58c3" ]
[ "tests/python/relay/test_op_level10.py", "tutorials/dev/bring_your_own_datatypes.py" ]
[ "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements. See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership. The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License. You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied. See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\" Support level10 operator test cases.\n\"\"\"\nimport numpy as np\nimport pytest\nimport tvm\nimport tvm.testing\nimport tvm.topi.testing\nfrom tvm import relay, te, topi\nfrom tvm.relay import transform\nfrom tvm.relay.testing import run_infer_type\n\n\[email protected]_gpu\ndef test_checkpoint():\n dtype = \"float32\"\n xs = [relay.var(\"x{}\".format(i), dtype) for i in range(4)]\n f = relay.multiply(relay.add(xs[0], xs[1]), relay.add(xs[2], xs[3]))\n f_checkpoint = relay.annotation.checkpoint(f)\n\n func, func_checkpoint = relay.Function(xs, f), relay.Function(xs, f_checkpoint)\n f, f_checkpoint = run_infer_type(func), run_infer_type(func_checkpoint)\n assert f.checked_type == f_checkpoint.checked_type\n\n inputs = [np.random.uniform() for _ in range(len(xs))]\n for target, dev in tvm.testing.enabled_targets():\n for kind in [\"graph\", \"debug\"]:\n f_res = relay.create_executor(kind, device=dev, target=target).evaluate(f)(*inputs)\n f_checkpoint_res = relay.create_executor(kind, device=dev, target=target).evaluate(\n f_checkpoint\n )(*inputs)\n tvm.testing.assert_allclose(f_res.numpy(), f_checkpoint_res.numpy(), 0, 0)\n\n\ndef test_checkpoint_alpha_equal():\n xs = [relay.var(\"x{}\".format(i), relay.TensorType((1,), \"float32\")) for i in range(4)]\n f = relay.Function(\n xs,\n relay.annotation.checkpoint(\n relay.multiply(relay.add(xs[0], xs[1]), relay.add(xs[2], xs[3]))\n ),\n )\n df = transform.gradient(run_infer_type(f))\n\n # run PE and DCE\n with tvm.transform.PassContext(opt_level=3):\n passes = [transform.PartialEvaluate(), transform.DeadCodeElimination(inline_once=True)]\n mod = tvm.transform.Sequential(passes)(tvm.IRModule.from_expr(df))\n df = mod[\"main\"]\n\n df_parsed = tvm.parser.parse_expr(\n \"\"\"\n #[version = \"0.0.5\"]\n fn (%x: Tensor[(1), float32], %y: Tensor[(1), float32],\n %z: Tensor[(1), float32], %w: Tensor[(1), float32])\n -> (Tensor[(1), float32],\n (Tensor[(1), float32], Tensor[(1), float32],\n Tensor[(1), float32], Tensor[(1), float32])) {\n %0 = add(%x, %y);\n %1 = add(%z, %w);\n let %x1: Tensor[(1), float32] = multiply(%0, %1);\n let %x2: Tensor[(1), float32] = ones_like(%x1);\n let %x3: Tensor[(1), float32] = add(%x, %y);\n let %x4: Tensor[(1), float32] = add(%z, %w);\n %2 = zeros_like(%x3);\n %3 = multiply(%x2, %x4);\n %4 = collapse_sum_like(%3, %x3);\n let %x5: Tensor[(1), float32] = add(%2, %4);\n %5 = zeros_like(%x4);\n %6 = multiply(%x2, %x3);\n %7 = collapse_sum_like(%6, %x4);\n let %x6: Tensor[(1), float32] = add(%5, %7);\n %8 = zeros_like(%x);\n %9 = collapse_sum_like(%x5, %x);\n %10 = add(%8, %9);\n %11 = zeros_like(%y);\n %12 = collapse_sum_like(%x5, %y);\n %13 = add(%11, %12);\n %14 = zeros_like(%z);\n %15 = collapse_sum_like(%x6, %z);\n %16 = add(%14, %15);\n %17 = zeros_like(%w);\n %18 = collapse_sum_like(%x6, %w);\n %19 = add(%17, %18);\n %20 = (%10, %13, %16, %19);\n (%x1, %20)\n }\n \"\"\"\n )\n\n tvm.ir.assert_structural_equal(df, df_parsed)\n\n\ndef test_checkpoint_alpha_equal_tuple():\n xs = [relay.var(\"x{}\".format(i), relay.TensorType((1,), \"float32\")) for i in range(4)]\n f = relay.Function(\n xs,\n relay.annotation.checkpoint(\n relay.Tuple([relay.add(xs[0], xs[1]), relay.add(xs[2], xs[3])])\n ),\n )\n df = transform.gradient(run_infer_type(f))\n\n # run PE and DCE\n with tvm.transform.PassContext(opt_level=3):\n passes = [transform.PartialEvaluate(), transform.DeadCodeElimination(inline_once=True)]\n mod = tvm.transform.Sequential(passes)(tvm.IRModule.from_expr(df))\n df = mod[\"main\"]\n\n df_parsed = tvm.parser.parse_expr(\n \"\"\"\n #[version = \"0.0.5\"]\n fn (%x: Tensor[(1), float32], %y: Tensor[(1), float32],\n %z: Tensor[(1), float32], %w: Tensor[(1), float32])\n -> ((Tensor[(1), float32], Tensor[(1), float32]),\n (Tensor[(1), float32], Tensor[(1), float32],\n Tensor[(1), float32], Tensor[(1), float32])) {\n let %x1: Tensor[(1), float32] = add(%x, %y) /* ty=Tensor[(1), float32] */;\n let %x2: Tensor[(1), float32] = add(%z, %w) /* ty=Tensor[(1), float32] */;\n let %x3: Tensor[(1), float32] = zeros_like(%x2) /* ty=Tensor[(1), float32] */;\n let %x4: Tensor[(1), float32] = ones_like(%x1) /* ty=Tensor[(1), float32] */;\n %0 = (%x1, %x2);\n %1 = zeros_like(%x) /* ty=Tensor[(1), float32] */;\n %2 = collapse_sum_like(%x4, %x) /* ty=Tensor[(1), float32] */;\n %3 = add(%1, %2) /* ty=Tensor[(1), float32] */;\n %4 = zeros_like(%y) /* ty=Tensor[(1), float32] */;\n %5 = collapse_sum_like(%x4, %y) /* ty=Tensor[(1), float32] */;\n %6 = add(%4, %5) /* ty=Tensor[(1), float32] */;\n %7 = zeros_like(%z) /* ty=Tensor[(1), float32] */;\n %8 = collapse_sum_like(%x3, %z) /* ty=Tensor[(1), float32] */;\n %9 = add(%7, %8) /* ty=Tensor[(1), float32] */;\n %10 = zeros_like(%w) /* ty=Tensor[(1), float32] */;\n %11 = collapse_sum_like(%x3, %w) /* ty=Tensor[(1), float32] */;\n %12 = add(%10, %11) /* ty=Tensor[(1), float32] */;\n %13 = (%3, %6, %9, %12);\n (%0, %13)\n }\n \"\"\"\n )\n\n tvm.ir.assert_structural_equal(df, df_parsed)\n\n\[email protected]_gpu\ndef test_collapse_sum_like():\n shape = (3, 4, 5, 6)\n shape_like = (4, 5, 6)\n dtype = \"float32\"\n x = relay.Var(\"x\", relay.ty.TensorType(shape, dtype))\n y = relay.Var(\"y\", relay.ty.TensorType(shape_like, dtype))\n z = relay.collapse_sum_like(x, y)\n zz = run_infer_type(z)\n assert zz.checked_type == relay.ty.TensorType(shape_like, dtype)\n\n func = relay.Function([x, y], z)\n x = np.random.uniform(size=shape).astype(dtype)\n y = np.random.uniform(size=shape_like).astype(dtype)\n ref_res = np.sum(x, 0)\n for target, dev in tvm.testing.enabled_targets():\n for kind in [\"graph\", \"debug\"]:\n op_res = relay.create_executor(kind, device=dev, target=target).evaluate(func)(x, y)\n tvm.testing.assert_allclose(op_res.numpy(), ref_res, rtol=1e-5)\n\n\[email protected]_gpu\ndef test_collapse_sum_to():\n shape = (3, 4, 5, 6)\n shape_to = (4, 5, 6)\n dtype = \"float32\"\n x = relay.Var(\"x\", relay.ty.TensorType(shape, dtype))\n z = relay.collapse_sum_to(x, shape_to)\n zz = run_infer_type(z)\n assert zz.checked_type == relay.ty.TensorType(shape_to, dtype)\n\n func = relay.Function([x], z)\n x = np.random.uniform(size=shape).astype(dtype)\n ref_res = np.sum(x, 0)\n for target, dev in tvm.testing.enabled_targets():\n for kind in [\"graph\", \"debug\"]:\n op_res = relay.create_executor(kind, device=dev, target=target).evaluate(func)(x)\n tvm.testing.assert_allclose(op_res.numpy(), ref_res, rtol=1e-5)\n\n\[email protected]_gpu\ndef test_broadcast_to():\n shape = (4, 1, 6)\n shape_like = (3, 4, 5, 6)\n dtype = \"float32\"\n x = relay.Var(\"x\", relay.ty.TensorType(shape, dtype))\n z = relay.broadcast_to(x, shape=shape_like)\n zz = run_infer_type(z)\n assert zz.checked_type == relay.ty.TensorType(shape_like, dtype)\n\n func = relay.Function([x], z)\n x = np.random.uniform(size=shape).astype(dtype)\n ref_res = np.broadcast_to(x, shape_like)\n for target, dev in tvm.testing.enabled_targets():\n for kind in [\"graph\", \"debug\"]:\n op_res = relay.create_executor(kind, device=dev, target=target).evaluate(func)(x)\n tvm.testing.assert_allclose(op_res.numpy(), ref_res, rtol=1e-5)\n\n\[email protected]_gpu\ndef test_broadcast_to_like():\n shape = (4, 1, 6)\n shape_like = (3, 4, 5, 6)\n dtype = \"float32\"\n x = relay.Var(\"x\", relay.ty.TensorType(shape, dtype))\n y = relay.Var(\"y\", relay.ty.TensorType(shape_like, dtype))\n z = relay.broadcast_to_like(x, y)\n\n zz = run_infer_type(z)\n assert zz.checked_type == relay.ty.TensorType(shape_like, dtype)\n\n func = relay.Function([x, y], z)\n x = np.random.uniform(size=shape).astype(dtype)\n y = np.random.uniform(size=shape_like).astype(dtype)\n ref_res = np.broadcast_to(x, shape_like)\n\n for target, dev in tvm.testing.enabled_targets():\n for kind in [\"graph\", \"debug\"]:\n op_res = relay.create_executor(kind, device=dev, target=target).evaluate(func)(x, y)\n tvm.testing.assert_allclose(op_res.numpy(), ref_res, rtol=1e-5)\n\n\ndef np_slice_like(np_data, np_shape_like, axis=None):\n begin_idx = [0 for _ in np_data.shape]\n end_idx = list(np_data.shape)\n if axis:\n for i in axis:\n if i < 0:\n i = len(np_data.shape) + i\n end_idx[i] = np_shape_like.shape[i]\n else:\n for i in range(len(np_data.shape)):\n if i < len(np_shape_like.shape):\n end_idx[i] = np_shape_like.shape[i]\n slice_idx = []\n for b, e in zip(begin_idx, end_idx):\n slice_idx.append(slice(b, e))\n np_result = np_data[tuple(slice_idx)]\n return np_result\n\n\ndef verify_slice_like(data, slice_like, axes, output, dtype=\"float32\"):\n x = relay.var(\"data\", relay.TensorType(data, dtype))\n y = relay.var(\"slice_like\", relay.TensorType(slice_like, dtype))\n z = relay.slice_like(x, y, axes)\n zz = run_infer_type(z)\n if axes:\n assert \"axes\" in z.astext()\n assert zz.checked_type == relay.ty.TensorType(output, dtype)\n\n if all(isinstance(v, int) == 0 for v in data) or all(\n isinstance(v, int) == 0 for v in slice_like\n ):\n return\n\n func = relay.Function([x, y], z)\n x_data = np.random.uniform(size=data).astype(dtype)\n y_data = np.random.uniform(size=slice_like).astype(dtype)\n ref_res = np_slice_like(x_data, y_data, axes)\n\n for target, dev in tvm.testing.enabled_targets():\n for kind in [\"graph\", \"debug\"]:\n op_res = relay.create_executor(kind, device=dev, target=target).evaluate(func)(\n x_data, y_data\n )\n tvm.testing.assert_allclose(op_res.numpy(), ref_res, rtol=1e-5)\n\n\[email protected]_gpu\ndef test_slice_like():\n d1, d2, d3, d4 = te.var(\"d1\"), te.var(\"d2\"), te.var(\"d3\"), te.var(\"d4\")\n verify_slice_like(data=(d1, d2, d3), slice_like=(1, 2, 3), axes=None, output=(1, 2, 3))\n verify_slice_like(data=(1, 2, 3), slice_like=(d1, d2, d3), axes=None, output=(d1, d2, d3))\n verify_slice_like(data=(d2, d3, d4), slice_like=(d1, d2, d3), axes=(1, 2), output=(d2, d2, d3))\n verify_slice_like(data=(3, 4, 5), slice_like=(1, 2, 3), axes=None, output=(1, 2, 3))\n verify_slice_like(data=(3, 4, 5), slice_like=(1, 2), axes=None, output=(1, 2, 5))\n verify_slice_like(data=(3, 4, 5), slice_like=(1, 2, 3), axes=(1, 2), output=(3, 2, 3))\n verify_slice_like(data=(3, 4, 5), slice_like=(1, 2, 3), axes=(-1, -3), output=(1, 4, 3))\n verify_slice_like(\n data=(1, 3, 224, 224), slice_like=(1, 3, 112, 112), axes=(2, 3), output=(1, 3, 112, 112)\n )\n\n\[email protected]_gpu\ndef test_reverse_reshape():\n def verify_reverse_reshape(shape, newshape, oshape):\n x = relay.var(\"x\", relay.TensorType(shape, \"float32\"))\n z = relay.reverse_reshape(x, newshape=newshape)\n zz = run_infer_type(z)\n assert \"newshape=\" in z.astext()\n assert zz.checked_type == relay.ty.TensorType(oshape, \"float32\")\n\n func = relay.Function([x], z)\n x_data = np.random.uniform(low=-1, high=1, size=shape).astype(\"float32\")\n ref_res = np.reshape(x_data, oshape)\n for target, dev in tvm.testing.enabled_targets():\n for kind in [\"graph\", \"debug\"]:\n op_res = relay.create_executor(kind, device=dev, target=target).evaluate(func)(\n x_data\n )\n tvm.testing.assert_allclose(op_res.numpy(), ref_res, rtol=1e-5)\n\n verify_reverse_reshape((2, 3, 4), (4, 0, 2), (4, 3, 2))\n verify_reverse_reshape((2, 3, 4), (2, 0, 0), (2, 3, 4))\n verify_reverse_reshape((2, 3, 4), (0, -1), (3, 8))\n verify_reverse_reshape((2, 3, 4), (-1, 0), (6, 4))\n verify_reverse_reshape((2, 3, 4), (0, -3), (2, 12))\n\n\ndef verify_batch_matmul(x_shape, y_shape, out_shape, dtype=\"float32\", trans_x=False, trans_y=True):\n x = relay.var(\"x\", relay.TensorType(x_shape, dtype))\n y = relay.var(\"y\", relay.TensorType(y_shape, dtype))\n z = relay.nn.batch_matmul(x, y, transpose_a=trans_x, transpose_b=trans_y)\n zz = run_infer_type(z)\n assert zz.checked_type == relay.ty.TensorType(out_shape, dtype)\n\n func = relay.Function([x, y], z)\n x_np = np.random.uniform(size=x_shape).astype(dtype)\n y_np = np.random.uniform(size=y_shape).astype(dtype)\n z_np = tvm.topi.testing.batch_matmul(x_np, y_np, trans_x=trans_x, trans_y=trans_y)\n\n for target, dev in tvm.testing.enabled_targets():\n for kind in [\"graph\", \"debug\"]:\n z = relay.create_executor(kind, device=dev, target=target).evaluate(func)(x_np, y_np)\n tvm.testing.assert_allclose(z.numpy(), z_np, rtol=1e-5)\n\n\[email protected]_gpu\ndef test_batch_matmul():\n b, m, n, k = te.size_var(\"b\"), te.size_var(\"m\"), te.size_var(\"n\"), te.size_var(\"k\")\n x = relay.var(\"x\", relay.TensorType((b, m, k), \"float32\"))\n y = relay.var(\"y\", relay.TensorType((b, n, k), \"float32\"))\n z = relay.nn.batch_matmul(x, y)\n zz = run_infer_type(z)\n assert zz.checked_type == relay.TensorType((b, m, n), \"float32\")\n\n verify_batch_matmul((1, 16, 32), (1, 16, 32), (1, 16, 16), trans_x=False, trans_y=True)\n verify_batch_matmul((5, 16, 32), (5, 16, 32), (5, 16, 16), trans_x=False, trans_y=True)\n verify_batch_matmul((5, 16, 32), (5, 20, 32), (5, 16, 20), trans_x=False, trans_y=True)\n verify_batch_matmul((30, 16, 32), (30, 20, 32), (30, 16, 20), trans_x=False, trans_y=True)\n verify_batch_matmul((1, 32, 16), (1, 16, 32), (1, 16, 16), trans_x=True, trans_y=True)\n verify_batch_matmul((5, 16, 32), (5, 32, 16), (5, 16, 16), trans_x=False, trans_y=False)\n verify_batch_matmul((5, 32, 16), (5, 32, 20), (5, 16, 20), trans_x=True, trans_y=False)\n\n\[email protected]_gpu\ndef test_shape_of():\n shape = (10, 5, 12)\n x = relay.var(\"x\", shape=shape)\n func = relay.Function([x], relay.op.shape_of(x))\n func = run_infer_type(func)\n x_data = np.random.rand(*shape).astype(\"float32\")\n for target, dev in tvm.testing.enabled_targets():\n # Because using graph executor, this op will be optimized after\n # constant folding pass, here we only test with interpreter\n for kind in [\"debug\"]:\n op_res = relay.create_executor(kind, device=dev, target=target).evaluate(func)(x_data)\n tvm.testing.assert_allclose(op_res.numpy(), np.array(shape).astype(\"int32\"))\n\n\[email protected]_gpu\ndef test_ndarray_size():\n def verify_ndarray_size(shape):\n x = relay.var(\"x\", shape=shape)\n func = relay.Function([x], relay.op.ndarray_size(x))\n func = run_infer_type(func)\n\n x_data = np.random.uniform(size=shape).astype(\"float32\")\n ref_res = np.size(x_data)\n for target, dev in tvm.testing.enabled_targets():\n for kind in [\"graph\", \"debug\"]:\n op_res = relay.create_executor(kind, device=dev, target=target).evaluate(func)(\n x_data\n )\n tvm.testing.assert_allclose(op_res.numpy(), ref_res)\n\n verify_ndarray_size((2, 3, 5))\n verify_ndarray_size((2, 3, 5, 7))\n\n\ndef verify_adaptive_pool(dshape, out_size, pool_type, layout, dtype, opfunc):\n for shape_dtype in [\"int32\", \"int64\"]:\n x = relay.var(\"x\", shape=[tvm.tir.IntImm(shape_dtype, x) for x in dshape], dtype=dtype)\n y = opfunc(x, out_size, layout)\n func = relay.Function([x], y)\n\n np_data = np.random.uniform(low=0, high=255, size=dshape).astype(dtype)\n np_out = tvm.topi.testing.adaptive_pool(np_data, out_size, pool_type, layout)\n\n for target, dev in tvm.testing.enabled_targets():\n relay_out = relay.create_executor(\"graph\", device=dev, target=target).evaluate(func)(\n np_data\n )\n tvm.testing.assert_allclose(relay_out.numpy(), np_out, rtol=1e-5, atol=1e-5)\n\n\ndef verify_adaptive_pool1d(dshape, out_size, pool_type, layout=\"NCW\", dtype=\"float32\"):\n opfunc = relay.nn.adaptive_avg_pool1d if pool_type == \"avg\" else relay.nn.adaptive_max_pool1d\n verify_adaptive_pool(dshape, out_size, pool_type, layout, dtype, opfunc)\n\n\ndef verify_adaptive_pool2d(dshape, out_size, pool_type, layout=\"NCHW\", dtype=\"float32\"):\n opfunc = relay.nn.adaptive_avg_pool2d if pool_type == \"avg\" else relay.nn.adaptive_max_pool2d\n verify_adaptive_pool(dshape, out_size, pool_type, layout, dtype, opfunc)\n\n\ndef verify_adaptive_pool3d(dshape, out_size, pool_type, layout=\"NCDHW\", dtype=\"float32\"):\n opfunc = relay.nn.adaptive_avg_pool3d if pool_type == \"avg\" else relay.nn.adaptive_max_pool3d\n verify_adaptive_pool(dshape, out_size, pool_type, layout, dtype, opfunc)\n\n\[email protected]_gpu\ndef test_adaptive_pool():\n verify_adaptive_pool1d((1, 9, 224), (1), \"max\")\n verify_adaptive_pool1d((1, 3, 224), (3), \"avg\")\n verify_adaptive_pool1d((1, 3, 224), (3), \"avg\", dtype=\"int32\")\n verify_adaptive_pool1d((1, 14, 78), (13), \"max\")\n verify_adaptive_pool1d((1, 5, 97), (96), \"avg\")\n verify_adaptive_pool1d((1, 224, 3), (1), \"max\", layout=\"NWC\")\n verify_adaptive_pool1d((1, 3, 224), (3), \"avg\", layout=\"NWC\")\n verify_adaptive_pool2d((1, 9, 224, 224), (1, 1), \"max\")\n verify_adaptive_pool2d((1, 3, 224, 224), (2, 3), \"avg\")\n verify_adaptive_pool2d((1, 3, 224, 224), (2, 3), \"avg\", dtype=\"int32\")\n verify_adaptive_pool2d((1, 14, 56, 78), (34, 13), \"max\")\n verify_adaptive_pool2d((1, 5, 46, 97), (4, 96), \"avg\")\n verify_adaptive_pool2d((1, 224, 224, 3), (1, 1), \"max\", layout=\"NHWC\")\n verify_adaptive_pool2d((1, 3, 224, 224), (2, 3), \"avg\", layout=\"NHWC\")\n verify_adaptive_pool3d((1, 16, 32, 32, 32), (1, 1, 1), \"max\", layout=\"NCDHW\")\n verify_adaptive_pool3d((1, 16, 32, 32, 32), (1, 1, 1), \"avg\", layout=\"NCDHW\")\n verify_adaptive_pool3d((1, 16, 32, 32, 32), (1, 1, 1), \"avg\", layout=\"NDHWC\")\n verify_adaptive_pool3d((1, 16, 32, 32, 32), (1, 1, 1), \"avg\", layout=\"NCDHW\", dtype=\"int32\")\n verify_adaptive_pool3d((1, 16, 32, 32, 32), (1, 1, 1), \"avg\", layout=\"NDHWC\", dtype=\"int32\")\n verify_adaptive_pool3d((1, 16, 32, 32, 32), (2, 4, 4), \"max\", layout=\"NDHWC\")\n\n\[email protected]_gpu\ndef test_sequence_mask():\n def _verify(data_shape, mask_value, axis, dtype, itype):\n max_length = data_shape[axis]\n nbatch = data_shape[1 - axis]\n data = relay.var(\"data\", relay.TensorType(data_shape, dtype))\n valid_length = relay.var(\"valid_length\", relay.TensorType((nbatch,), itype))\n out = relay.sequence_mask(data, valid_length, mask_value, axis)\n checked = run_infer_type(out)\n assert checked.checked_type == relay.ty.TensorType(data_shape, dtype)\n func = relay.Function([data, valid_length], out)\n data_np = np.random.uniform(size=data_shape).astype(dtype)\n valid_length_np = np.random.randint(0, max_length, size=nbatch).astype(itype)\n gt_out_np = tvm.topi.testing.sequence_mask(data_np, valid_length_np, mask_value, axis)\n\n for target, dev in tvm.testing.enabled_targets():\n for kind in [\"graph\", \"debug\"]:\n out_relay = relay.create_executor(kind, device=dev, target=target).evaluate(func)(\n data_np, valid_length_np\n )\n tvm.testing.assert_allclose(out_relay.numpy(), gt_out_np)\n\n _verify((5, 10), 0.0, 1, \"float32\", \"int32\")\n _verify((2, 3, 5, 3), 0.0, 0, \"float32\", \"int64\")\n _verify((5, 8, 3), 0.1, 1, \"float64\", \"float32\")\n\n\[email protected]_gpu\ndef test_one_hot():\n def _get_oshape(indices_shape, depth, axis):\n oshape = []\n true_axis = len(indices_shape) if axis == -1 else axis\n ndim = len(indices_shape) + 1\n indices_index = 0\n for i in range(0, ndim):\n if i == true_axis:\n oshape.append(depth)\n else:\n oshape.append(indices_shape[indices_index])\n indices_index += 1\n\n return oshape\n\n def _verify(indices_shape, depth, on_value, off_value, axis, dtype):\n indices = relay.var(\"indices\", relay.TensorType(indices_shape, \"int32\"))\n on_value_const = relay.const(on_value)\n off_value_const = relay.const(off_value)\n out = relay.one_hot(indices, on_value_const, off_value_const, depth, axis, dtype)\n checked = run_infer_type(out)\n assert checked.checked_type == relay.ty.TensorType(\n _get_oshape(indices_shape, depth, axis), dtype\n )\n func = relay.Function([indices], out)\n indices_np = np.random.randint(0, depth, size=indices_shape).astype(\"int32\")\n out_np = tvm.topi.testing.one_hot(indices_np, on_value, off_value, depth, axis, dtype)\n\n for target, dev in tvm.testing.enabled_targets():\n for kind in [\"graph\", \"debug\"]:\n out_relay = relay.create_executor(kind, device=dev, target=target).evaluate(func)(\n indices_np\n )\n tvm.testing.assert_allclose(out_relay.numpy(), out_np)\n\n _verify((3,), 3, 1, 0, -1, \"int32\")\n _verify((3,), 3, 1.0, 0.0, -1, \"float32\")\n _verify((2, 2), 5, 2, -2, 0, \"int32\")\n _verify((2, 2), 5, 0.5, -0.5, 1, \"float32\")\n _verify((3, 2, 4, 5), 6, 1, 0, 1, \"int32\")\n _verify((3, 2, 4, 5), 6, 1.0, 0.0, 0, \"float32\")\n\n\[email protected]_gpu\ndef test_matrix_set_diag():\n def _verify(input_shape, diagonal_shape, dtype, k=0, align=\"RIGHT_LEFT\"):\n input = relay.var(\"input\", relay.TensorType(input_shape, dtype))\n diagonal = relay.var(\"diagonal\", relay.TensorType(diagonal_shape, dtype))\n out = relay.matrix_set_diag(input, diagonal, k, align)\n\n in_type = run_infer_type(input)\n out_type = run_infer_type(out)\n assert in_type.checked_type == out_type.checked_type\n\n func = relay.Function([input, diagonal], out)\n input_np = np.random.randint(-100, 100, size=input_shape).astype(dtype)\n diagonal_np = np.random.randint(-100, 100, size=diagonal_shape).astype(dtype)\n out_np = tvm.topi.testing.matrix_set_diag(input_np, diagonal_np, k, align)\n\n for target, dev in tvm.testing.enabled_targets():\n for kind in [\"graph\", \"debug\"]:\n out_relay = relay.create_executor(kind, device=dev, target=target).evaluate(func)(\n input_np, diagonal_np\n )\n tvm.testing.assert_allclose(out_relay.numpy(), out_np)\n\n _verify((2, 2), (2,), \"float32\")\n _verify((4, 3, 3), (4, 3), \"int32\")\n _verify((2, 3, 4), (2, 3), \"float32\", 1)\n _verify((2, 3, 4), (2, 4, 3), \"int32\", (-1, 2), \"LEFT_RIGHT\")\n _verify((2, 3, 4), (2, 4, 3), \"int32\", (-1, 2), \"LEFT_LEFT\")\n _verify((2, 3, 4), (2, 4, 3), \"int32\", (-1, 2), \"RIGHT_RIGHT\")\n\n\[email protected]_targets\ndef test_nll_loss(dev, target):\n def _get_oshape(target_shape, reduction):\n if reduction == \"none\":\n return target_shape\n else:\n return []\n\n def _verify(prediction_shape, reduction=\"mean\", ignore_index=-100, dtype=\"float32\"):\n C = prediction_shape[1]\n target_shape = prediction_shape[:1] + prediction_shape[2:]\n\n predictions = relay.var(\"predictions\", relay.TensorType(prediction_shape, dtype))\n targets = relay.var(\"targets\", relay.TensorType(target_shape, \"int32\"))\n weights = relay.var(\"weights\", relay.TensorType((C,), dtype))\n out = relay.nn.nll_loss(predictions, targets, weights, reduction, ignore_index)\n checked = run_infer_type(out)\n assert checked.checked_type == relay.ty.TensorType(\n _get_oshape(target_shape, reduction), dtype\n )\n func = relay.Function([predictions, targets, weights], out)\n predictions_np = np.random.uniform(size=prediction_shape).astype(dtype)\n targets_np = np.random.randint(0, C, target_shape).astype(\"int32\")\n weights_np = np.random.uniform(size=(C,)).astype(dtype)\n out_np = tvm.topi.testing.nll_loss(\n predictions_np, targets_np, weights_np, reduction, ignore_index\n )\n\n for kind in [\"graph\", \"debug\"]:\n out_relay = relay.create_executor(kind, device=dev, target=target).evaluate(func)(\n predictions_np, targets_np, weights_np\n )\n tvm.testing.assert_allclose(out_relay.numpy(), out_np, rtol=1e-6, atol=1e-6)\n\n _verify((10, 5))\n _verify((10, 5, 2, 2))\n _verify((10, 5), reduction=\"sum\")\n _verify((10, 5), reduction=\"none\")\n _verify((10, 5), ignore_index=3)\n _verify((10, 5), dtype=\"float64\")\n\n\nif __name__ == \"__main__\":\n pytest.main([__file__])\n", "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements. See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership. The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License. You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied. See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\"\"\"\nBring Your Own Datatypes to TVM\n===============================\n**Authors**: `Gus Smith <https://github.com/gussmith23>`_, `Andrew Liu <https://github.com/hypercubestart>`_\n\nIn this tutorial, we will show you how to utilize the Bring Your Own Datatypes framework to use your own custom datatypes in TVM.\nNote that the Bring Your Own Datatypes framework currently only handles **software emulated versions of datatypes**.\nThe framework does not support compiling for custom accelerator datatypes out-of-the-box.\n\nDatatype Libraries\n------------------\n\nThe Bring Your Own Datatypes allows users to register their own datatype implementations alongside TVM's native datatypes (such as ``float``).\nIn the wild, these datatype implementations often appear as libraries.\nFor example:\n\n- `libposit <https://github.com/cjdelisle/libposit>`_, a posit library\n- `Stillwater Universal <https://github.com/stillwater-sc/universal>`_, a library with posits, fixed-point numbers, and other types\n- `SoftFloat <https://github.com/ucb-bar/berkeley-softfloat-3>`_, Berkeley's software implementation of IEEE 754 floating-point\n\nThe Bring Your Own Datatypes enables users to plug these datatype implementations into TVM!\n\nIn this section, we will use an example library we have already implemented, located at ``3rdparty/byodt/myfloat.cc``.\nThis datatype, which we dubbed \"myfloat\", is really just a IEE-754 float under-the-hood, but it serves a useful example\nto show that any datatype can be used in the BYODT framework.\n\nSetup\n-----\n\nSince we do not use any 3rdparty library, there is no setup needed.\n\nIf you would like to try this with your own datatype library, first bring the library's functions into the process space with ``CDLL``:\n\n.. code-block :: python\n\n ctypes.CDLL('my-datatype-lib.so', ctypes.RTLD_GLOBAL)\n\"\"\"\n\n######################\n# A Simple TVM Program\n# --------------------\n#\n# We'll begin by writing a simple program in TVM; afterwards, we will re-write it to use custom datatypes.\nimport tvm\nfrom tvm import relay\n\n# Our basic program: Z = X + Y\nx = relay.var(\"x\", shape=(3,), dtype=\"float32\")\ny = relay.var(\"y\", shape=(3,), dtype=\"float32\")\nz = x + y\nprogram = relay.Function([x, y], z)\nmodule = tvm.IRModule.from_expr(program)\n\n######################################################################\n# Now, we create random inputs to feed into this program using numpy:\n\nimport numpy as np\n\nnp.random.seed(23) # for reproducibility\n\nx_input = np.random.rand(3).astype(\"float32\")\ny_input = np.random.rand(3).astype(\"float32\")\nprint(\"x: {}\".format(x_input))\nprint(\"y: {}\".format(y_input))\n\n######################################################################\n# Finally, we're ready to run the program:\n\nz_output = relay.create_executor(mod=module).evaluate()(x_input, y_input)\nprint(\"z: {}\".format(z_output))\n\n######################################################################\n# Adding Custom Datatypes\n# -----------------------\n# Now, we will do the same, but we will use a custom datatype for our intermediate computation.\n#\n# We use the same input variables ``x`` and ``y`` as above, but before adding ``x + y``, we first cast both ``x`` and ``y`` to a custom datatype via the ``relay.cast(...)`` call.\n#\n# Note how we specify the custom datatype: we indicate it using the special ``custom[...]`` syntax.\n# Additionally, note the \"32\" after the datatype: this is the bitwidth of the custom datatype. This tells TVM that each instance of ``myfloat`` is 32 bits wide.\n\ntry:\n with tvm.transform.PassContext(config={\"tir.disable_vectorize\": True}):\n x_myfloat = relay.cast(x, dtype=\"custom[myfloat]32\")\n y_myfloat = relay.cast(y, dtype=\"custom[myfloat]32\")\n z_myfloat = x_myfloat + y_myfloat\n z = relay.cast(z_myfloat, dtype=\"float32\")\nexcept tvm.TVMError as e:\n # Print last line of error\n print(str(e).split(\"\\n\")[-1])\n\n######################################################################\n# Trying to generate this program throws an error from TVM.\n# TVM does not know how to handle any custom datatype out of the box!\n# We first have to register the custom type with TVM, giving it a name and a type code:\n\ntvm.target.datatype.register(\"myfloat\", 150)\n\n######################################################################\n# Note that the type code, 150, is currently chosen manually by the user.\n# See ``TVMTypeCode::kCustomBegin`` in `include/tvm/runtime/c_runtime_api.h <https://github.com/apache/tvm/blob/main/include/tvm/runtime/data_type.h>`_.\n# Now we can generate our program again:\n\nx_myfloat = relay.cast(x, dtype=\"custom[myfloat]32\")\ny_myfloat = relay.cast(y, dtype=\"custom[myfloat]32\")\nz_myfloat = x_myfloat + y_myfloat\nz = relay.cast(z_myfloat, dtype=\"float32\")\nprogram = relay.Function([x, y], z)\nmodule = tvm.IRModule.from_expr(program)\nmodule = relay.transform.InferType()(module)\n\n######################################################################\n# Now we have a Relay program that uses myfloat!\nprint(program)\n\n######################################################################\n# Now that we can express our program without errors, let's try running it!\ntry:\n with tvm.transform.PassContext(config={\"tir.disable_vectorize\": True}):\n z_output_myfloat = relay.create_executor(\"graph\", mod=module).evaluate()(x_input, y_input)\n print(\"z: {}\".format(y_myfloat))\nexcept tvm.TVMError as e:\n # Print last line of error\n print(str(e).split(\"\\n\")[-1])\n\n######################################################################\n# Now, trying to compile this program throws an error.\n# Let's dissect this error.\n#\n# The error is occurring during the process of lowering the custom datatype code to code that TVM can compile and run.\n# TVM is telling us that it cannot find a *lowering function* for the ``Cast`` operation, when casting from source type 2 (``float``, in TVM), to destination type 150 (our custom datatype).\n# When lowering custom datatypes, if TVM encounters an operation over a custom datatype, it looks for a user-registered *lowering function*, which tells it how to lower the operation to an operation over datatypes it understands.\n# We have not told TVM how to lower ``Cast`` operations for our custom datatypes; thus, the source of this error.\n#\n# To fix this error, we simply need to specify a lowering function:\n\ntvm.target.datatype.register_op(\n tvm.target.datatype.create_lower_func(\n {\n (32, 32): \"FloatToCustom32\", # cast from float32 to myfloat32\n }\n ),\n \"Cast\",\n \"llvm\",\n \"float\",\n \"myfloat\",\n)\n\n######################################################################\n# The ``register_op(...)`` call takes a lowering function, and a number of parameters which specify exactly the operation which should be lowered with the provided lowering function.\n# In this case, the arguments we pass specify that this lowering function is for lowering a ``Cast`` from ``float`` to ``myfloat`` for target ``\"llvm\"``.\n#\n# The lowering function passed into this call is very general: it should take an operation of the specified type (in this case, `Cast`) and return another operation which only uses datatypes which TVM understands.\n#\n# In the general case, we expect users to implement operations over their custom datatypes using calls to an external library.\n# In our example, our ``myfloat`` library implements a ``Cast`` from ``float`` to 32-bit ``myfloat`` in the function ``FloatToCustom32``.\n# To provide for the general case, we have made a helper function, ``create_lower_func(...)``,\n# which does just this: given a dictionary, it replaces the given operation with a ``Call`` to the appropriate function name provided based on the op and the bit widths.\n# It additionally removes usages of the custom datatype by storing the custom datatype in an opaque ``uint`` of the appropriate width; in our case, a ``uint32_t``.\n# For more information, see `the source code <https://github.com/apache/tvm/blob/main/python/tvm/target/datatype.py>`_.\n\n# We can now re-try running the program:\ntry:\n with tvm.transform.PassContext(config={\"tir.disable_vectorize\": True}):\n z_output_myfloat = relay.create_executor(\"graph\", mod=module).evaluate()(x_input, y_input)\n print(\"z: {}\".format(z_output_myfloat))\nexcept tvm.TVMError as e:\n # Print last line of error\n print(str(e).split(\"\\n\")[-1])\n\n######################################################################\n# This new error tells us that the ``Add`` lowering function is not found, which is good news, as it's no longer complaining about the ``Cast``!\n# We know what to do from here: we just need to register the lowering functions for the other operations in our program.\n#\n# Note that for ``Add``, ``create_lower_func`` takes in a dict where the key is an integer.\n# For ``Cast`` operations, we require a 2-tuple to specify the ``src_bit_length`` and the ``dest_bit_length``,\n# while for all other operations, the bit length is the same between the operands so we only require one integer to specify ``bit_length``.\ntvm.target.datatype.register_op(\n tvm.target.datatype.create_lower_func({32: \"Custom32Add\"}),\n \"Add\",\n \"llvm\",\n \"myfloat\",\n)\ntvm.target.datatype.register_op(\n tvm.target.datatype.create_lower_func({(32, 32): \"Custom32ToFloat\"}),\n \"Cast\",\n \"llvm\",\n \"myfloat\",\n \"float\",\n)\n\n# Now, we can run our program without errors.\nwith tvm.transform.PassContext(config={\"tir.disable_vectorize\": True}):\n z_output_myfloat = relay.create_executor(mod=module).evaluate()(x_input, y_input)\nprint(\"z: {}\".format(z_output_myfloat))\n\nprint(\"x:\\t\\t{}\".format(x_input))\nprint(\"y:\\t\\t{}\".format(y_input))\nprint(\"z (float32):\\t{}\".format(z_output))\nprint(\"z (myfloat32):\\t{}\".format(z_output_myfloat))\n\n# Perhaps as expected, the ``myfloat32`` results and ``float32`` are exactly the same!\n\n######################################################################\n# Running Models With Custom Datatypes\n# ------------------------------------\n#\n# We will first choose the model which we would like to run with myfloat.\n# In this case we use `Mobilenet <https://arxiv.org/abs/1704.04861>`_.\n# We choose Mobilenet due to its small size.\n# In this alpha state of the Bring Your Own Datatypes framework, we have not implemented any software optimizations for running software emulations of custom datatypes; the result is poor performance due to many calls into our datatype emulation library.\n#\n# First let us define two helper functions to get the mobilenet model and a cat image.\n\n\ndef get_mobilenet():\n dshape = (1, 3, 224, 224)\n from mxnet.gluon.model_zoo.vision import get_model\n\n block = get_model(\"mobilenet0.25\", pretrained=True)\n shape_dict = {\"data\": dshape}\n return relay.frontend.from_mxnet(block, shape_dict)\n\n\ndef get_cat_image():\n from tvm.contrib.download import download_testdata\n from PIL import Image\n\n url = \"https://gist.githubusercontent.com/zhreshold/bcda4716699ac97ea44f791c24310193/raw/fa7ef0e9c9a5daea686d6473a62aacd1a5885849/cat.png\"\n dst = \"cat.png\"\n real_dst = download_testdata(url, dst, module=\"data\")\n img = Image.open(real_dst).resize((224, 224))\n # CoreML's standard model image format is BGR\n img_bgr = np.array(img)[:, :, ::-1]\n img = np.transpose(img_bgr, (2, 0, 1))[np.newaxis, :]\n return np.asarray(img, dtype=\"float32\")\n\n\nmodule, params = get_mobilenet()\n\n######################################################################\n# It's easy to execute MobileNet with native TVM:\n\nex = tvm.relay.create_executor(\"graph\", mod=module, params=params)\ninput = get_cat_image()\nresult = ex.evaluate()(input).numpy()\n# print first 10 elements\nprint(result.flatten()[:10])\n\n######################################################################\n# Now, we would like to change the model to use myfloat internally. To do so, we need to convert the network. To do this, we first define a function which will help us convert tensors:\n\n\ndef convert_ndarray(dst_dtype, array):\n \"\"\"Converts an NDArray into the specified datatype\"\"\"\n x = relay.var(\"x\", shape=array.shape, dtype=str(array.dtype))\n cast = relay.Function([x], x.astype(dst_dtype))\n with tvm.transform.PassContext(config={\"tir.disable_vectorize\": True}):\n return relay.create_executor(\"graph\").evaluate(cast)(array)\n\n\n######################################################################\n# Now, to actually convert the entire network, we have written `a pass in Relay <https://github.com/gussmith23/tvm/blob/ea174c01c54a2529e19ca71e125f5884e728da6e/python/tvm/relay/frontend/change_datatype.py#L21>`_ which simply converts all nodes within the model to use the new datatype.\n\nfrom tvm.relay.frontend.change_datatype import ChangeDatatype\n\nsrc_dtype = \"float32\"\ndst_dtype = \"custom[myfloat]32\"\n\nmodule = relay.transform.InferType()(module)\n\n# Currently, custom datatypes only work if you run simplify_inference beforehand\nmodule = tvm.relay.transform.SimplifyInference()(module)\n\n# Run type inference before changing datatype\nmodule = tvm.relay.transform.InferType()(module)\n\n# Change datatype from float to myfloat and re-infer types\ncdtype = ChangeDatatype(src_dtype, dst_dtype)\nexpr = cdtype.visit(module[\"main\"])\nmodule = tvm.relay.transform.InferType()(module)\n\n# We also convert the parameters:\nparams = {k: convert_ndarray(dst_dtype, v) for k, v in params.items()}\n\n# We also need to convert our input:\ninput = convert_ndarray(dst_dtype, input)\n\n# Finally, we can try to run the converted model:\ntry:\n # Vectorization is not implemented with custom datatypes.\n with tvm.transform.PassContext(config={\"tir.disable_vectorize\": True}):\n result_myfloat = tvm.relay.create_executor(\"graph\", mod=module).evaluate(expr)(\n input, **params\n )\nexcept tvm.TVMError as e:\n print(str(e).split(\"\\n\")[-1])\n\n######################################################################\n# When we attempt to run the model, we get a familiar error telling us that more funcions need to be registerd for myfloat.\n#\n# Because this is a neural network, many more operations are required.\n# Here, we register all the needed functions:\n\ntvm.target.datatype.register_op(\n tvm.target.datatype.create_lower_func({32: \"FloatToCustom32\"}),\n \"FloatImm\",\n \"llvm\",\n \"myfloat\",\n)\n\ntvm.target.datatype.register_op(\n tvm.target.datatype.lower_ite, \"Call\", \"llvm\", \"myfloat\", intrinsic_name=\"tir.if_then_else\"\n)\n\ntvm.target.datatype.register_op(\n tvm.target.datatype.lower_call_pure_extern,\n \"Call\",\n \"llvm\",\n \"myfloat\",\n intrinsic_name=\"tir.call_pure_extern\",\n)\n\ntvm.target.datatype.register_op(\n tvm.target.datatype.create_lower_func({32: \"Custom32Mul\"}),\n \"Mul\",\n \"llvm\",\n \"myfloat\",\n)\ntvm.target.datatype.register_op(\n tvm.target.datatype.create_lower_func({32: \"Custom32Div\"}),\n \"Div\",\n \"llvm\",\n \"myfloat\",\n)\n\ntvm.target.datatype.register_op(\n tvm.target.datatype.create_lower_func({32: \"Custom32Sqrt\"}),\n \"Call\",\n \"llvm\",\n \"myfloat\",\n intrinsic_name=\"tir.sqrt\",\n)\n\ntvm.target.datatype.register_op(\n tvm.target.datatype.create_lower_func({32: \"Custom32Sub\"}),\n \"Sub\",\n \"llvm\",\n \"myfloat\",\n)\n\ntvm.target.datatype.register_op(\n tvm.target.datatype.create_lower_func({32: \"Custom32Exp\"}),\n \"Call\",\n \"llvm\",\n \"myfloat\",\n intrinsic_name=\"tir.exp\",\n)\n\ntvm.target.datatype.register_op(\n tvm.target.datatype.create_lower_func({32: \"Custom32Max\"}),\n \"Max\",\n \"llvm\",\n \"myfloat\",\n)\n\ntvm.target.datatype.register_min_func(\n tvm.target.datatype.create_min_lower_func({32: \"MinCustom32\"}, \"myfloat\"),\n \"myfloat\",\n)\n\n######################################################################\n# Note we are making use of two new functions: ``register_min_func`` and ``create_min_lower_func``.\n#\n# ``register_min_func`` takes in an integer ``num_bits`` for the bit length, and should return an operation\n# representing the minimum finite representable value for the custom data type with the specified bit length.\n#\n# Similar to ``register_op`` and ``create_lower_func``, the ``create_min_lower_func`` handles the general case\n# where the minimum representable custom datatype value is implemented using calls to an external library.\n#\n# Now we can finally run the model:\n\n# Vectorization is not implemented with custom datatypes.\nwith tvm.transform.PassContext(config={\"tir.disable_vectorize\": True}):\n result_myfloat = relay.create_executor(mod=module).evaluate(expr)(input, **params)\n result_myfloat = convert_ndarray(src_dtype, result_myfloat).numpy()\n # print first 10 elements\n print(result_myfloat.flatten()[:10])\n\n# Again, note that the output using 32-bit myfloat exactly the same as 32-bit floats,\n# because myfloat is exactly a float!\nnp.testing.assert_array_equal(result, result_myfloat)\n" ]
[ [ "numpy.reshape", "numpy.size", "numpy.broadcast_to", "numpy.random.rand", "numpy.random.uniform", "numpy.array", "numpy.sum", "numpy.random.randint" ], [ "numpy.random.seed", "numpy.asarray", "numpy.testing.assert_array_equal", "numpy.random.rand", "numpy.transpose", "numpy.array" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
DynamicGravitySystems/DGP
[ "5bb8a30895365eccdd452970c45e248903fca8af" ]
[ "dgp/lib/transform/etc.py" ]
[ "# coding: utf-8\n\nimport pandas as pd\n\n\ndef named_series(*args, **kwargs):\n def wrapper(*args, **kwargs):\n return pd.Series(*args, **kwargs)\n return wrapper\n\n" ]
[ [ "pandas.Series" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "0.23", "0.21", "2.0", "1.4", "0.19", "1.1", "1.5", "1.2", "0.24", "0.20", "1.0", "0.25", "1.3" ], "scipy": [], "tensorflow": [] } ]
megasanjay/soda-app-update
[ "1e368072f2191f194530b2d914848400d55f8690" ]
[ "src/pysoda/validator_soda.py" ]
[ "'''\nThis code validates the proposed folder structure and files\nagainst the schema required by the SPARC curation team.\nNote that since this code is separate from the code used\nthe the SPARC curation team that automatically checks similar\nitems, code passing this validator may not pass the official\nSPARC validator code. The converse is not true however.\nTo get a list of items that are checked, visit our dedicated page:\nhttps://github.com/bvhpatel/SODA/wiki/Validate-dataset/_edit#about-the-validator\n\nBhavesh Patel\nCalifornia Medical Innovations Institute\[email protected]\n\nKarl G. Helmer\nMartinos Center for Biomedical Imaging\nMassachusetts General Hospital\[email protected]\n'''\n\nimport os\nimport chardet #utf8 check for csv\nimport pandas as pd\nimport numpy as np\nfrom os.path import getsize\n\nclass DictValidator:\n\n #High level folder\n reqFolderNames = ['primary']\n optFolderNames = [ 'code', 'derivative', 'docs', 'protocol', 'source']\n\n # High level metadata files\n reqMetadataFileNames = ['submission', 'dataset_description', 'subjects', 'README']\n optMetadataFileNames = ['samples', 'CHANGES']\n manifestFileName = 'manifest'\n metadataFileFormats1 = ['.xlsx','.csv', '.json']\n metadataFileFormats2 = ['.txt']\n\n # submission file\n reqSubmissionHeaders = ['Submission Item', 'Value']\n optSubmissionHeaders = ['Definition']\n submissionCol0 = ['SPARC Award number', 'Milestone achieved', 'Milestone completion date']\n\n #dataset_description file\n # note: the capitalizations below are inconsistent, but are what is given in SPARC_FAIR-Folder_Structure V1.2.pdf\n reqddHeaders = ['Metadata element', 'Value']\n optddHeaders = ['Description', 'Example']\n for i in range(2,101):\n el = 'Value '+ str(i)\n optddHeaders.append(el)\n\n ddCol0 = ['Name', 'Description', 'Keywords', 'Contributors', 'Contributor ORCID ID',\n 'Contributor Affiliation', 'Contributor Role',\n 'Is Contact Person', 'Acknowledgements', 'Funding', 'Originating Article DOI',\n 'Protocol URL or DOI', 'Additional Links', 'Link Description', 'Number of subjects',\n 'Number of samples', 'Completeness of data set', 'Parent dataset ID', 'Title for complete data set',\n 'Metadata Version DO NOT CHANGE']\n\n ddCol0Req = ['Name', 'Description', 'Keywords', 'Contributors', 'Contributor ORCID ID',\n 'Contributor Affiliation', 'Contributor Role',\n 'Is Contact Person', 'Funding',\n 'Protocol URL or DOI', 'Number of subjects',\n 'Number of samples', 'Metadata Version DO NOT CHANGE']\n\n ddCol0Opt = ['Acknowledgements', 'Originating Article DOI', 'Additional Links', 'Link Description',\n 'Completeness of data set', 'Parent dataset ID', 'Title for complete data set']\n\n\n contributorRoles = ['PrincipleInvestigator', 'Creator', 'CoInvestigator', 'ContactPerson', 'DataCollector',\n 'DataCurator', 'DataManager', 'Distributor', 'Editor', 'Producer', 'ProjectLeader',\n 'ProjectManager', 'ProjectMember', 'RelatedPerson', 'Researcher', 'ResearchGroup',\n 'Sponsor', 'Supervisor', 'WorkPackageLeader', 'Other']\n\n contactPersonOptions = [\"Yes\", \"No\"]\n\n completnessInfo = ['hasNext', 'hasChildren']\n\n #subjects file\n subjCols = ['subject_id', 'pool_id', 'experimental group', 'age', 'sex', 'species', 'strain', 'Organism RRID']\n\n #samples file\n samCols = ['subject_id', 'sample_id', 'wasDerivedFromSample', 'pool_id', 'experimental group']\n\n #none terms\n noneTerms = ['None', 'NONE', 'none', 'N/A', 'n/a', 'NA', 'na', 'Not applicable', 'Not Applicable']\n\n empty = 'empty'\n\n metadataVersion = '1.2.3'\n\n def __init__(self):\n self.fatal = []\n self.warnings = []\n self.passes = []\n\n def check_high_level_folder_structure(self, jsonStruct):\n primaryf = 0\n sparcf = 0\n emptyf = 0\n nonstandardf = 0\n nonStandardFolders = \"\"\n emptyFolders = \"\"\n\n # get all high-level files/folders\n allContents = jsonStruct.keys()\n allContents = [ x for x in allContents if x!='main' ]\n for c in allContents:\n if c == self.reqFolderNames[0]: #primary folder\n primaryf = 1\n pContents = jsonStruct[c]\n if len(pContents) == 0: #check primary empty\n emptyf = 1\n emptyFolders += \" \" + c + \",\"\n elif c in self.optFolderNames: #check for optional folders\n sparcf = 1\n pContents = jsonStruct[c]\n if len(pContents) == 0: #check optional folder empty\n emptyf = 1\n emptyFolders += \" \" + c + \",\"\n else:\n nonstandardf = 1\n nonStandardFolders += \" \" + c + \",\"\n\n check1 = \"All folders are SPARC standard folders\"\n check1f = \"Only SPARC standard folders ('code', 'derivative', 'docs', 'primary', 'protocol', and/or 'source', all lowercase) are allowed. The following folder(s) must be removed:\"\n\n check2 = \"A 'primary' folder is included\"\n check2f = \"A non-empty 'primary' folder is required in all datasets, make sure it is included\"\n\n check3 = \"All SPARC folders are non-empty\"\n check3f = \"No empty SPARC folder should be included. Populate or remove the following folder(s):\"\n\n if nonstandardf == 1:\n self.fatal.append(check1 + \"--\" + check1f + nonStandardFolders[:-1])\n else:\n if primaryf == 1 and sparcf == 1:\n self.passes.append(check1)\n\n if not primaryf:\n self.fatal.append(check2 + \"--\" + check2f)\n else:\n self.passes.append(check2)\n\n if emptyf == 1:\n self.fatal.append(check3 + \"--\" + check3f + emptyFolders[:-1])\n else:\n if primaryf == 1 and sparcf == 1:\n self.passes.append(check3)\n\n def check_high_level_metadata_files(self, jsonStruct):\n nofiles = 0\n subm = 0\n subm0kb = 0\n dd = 0\n dd0kb = 0\n subj = 0\n subj0kb = 0\n sam = 0\n sam0kb = 0\n rm = 0\n rm0kb = 0\n chg = 0\n csvf = 0\n nonstand = 0\n nonStandardFiles = \"\"\n nonUTF8 = 0\n nonUTF8Files = \"\"\n nonu = 0\n nonUniqueFiles = \"\"\n\n #check for req files at the root level\n allFiles = jsonStruct['main']\n if len(allFiles) == 0:\n nofiles = 1\n else:\n for c in allFiles:\n filePath = c\n fullFileName = os.path.basename(c)\n cname = os.path.splitext(fullFileName)[0]\n extension = os.path.splitext(fullFileName)[1]\n\n if cname == self.reqMetadataFileNames[0]: #submission file\n if extension in self.metadataFileFormats1: #if in xlsx, csv, or json format\n subm += 1\n if getsize(filePath)>0:\n print('Size sub', getsize(filePath))\n if extension in self.metadataFileFormats1[1]:#if csv\n csvf = 1\n UTF8status = self.check_csv_utf8(filePath)\n if UTF8status == 0:\n nonUTF8 = 1\n nonUTF8Files = \" \" + c + \",\"\n else:\n subm0kb = 1 \n else:\n nonstand = 1\n nonStandardFiles += \" \" + c + \",\"\n\n elif cname == self.reqMetadataFileNames[1]: #dataset_description file\n if extension in self.metadataFileFormats1: #if in xlsx, csv, or json format\n dd += 1\n if getsize(filePath)>0:\n print('Size dd', getsize(filePath))\n if extension in self.metadataFileFormats1[1]: #if csv\n csvf = 1\n UTF8status = self.check_csv_utf8(filePath)\n if UTF8status == 0:\n nonUTF8 = 1\n nonUTF8Files = \" \" + c + \",\"\n else:\n dd0kb = 1\n else:\n nonstand = 1\n nonStandardFiles += \" \" + c + \",\"\n\n elif cname == self.reqMetadataFileNames[2]: #subjects file\n if extension in self.metadataFileFormats1: #if in xlsx, csv, or json format\n subj += 1\n if getsize(filePath)>0:\n print('Size subj', getsize(filePath))\n if extension in self.metadataFileFormats1[1]: #if csv\n csvf = 1\n UTF8status = self.check_csv_utf8(filePath)\n if UTF8status == 0:\n nonUTF8 = 1\n nonUTF8Files = \" \" + c + \",\"\n else:\n subj0kb = 1\n else: #if not in xlsx, csv, or json format\n nonstand = 1\n nonStandardFiles += \" \" + c + \",\"\n\n elif cname == self.optMetadataFileNames[0]: #samples file\n if extension in self.metadataFileFormats1: #if in xlsx, csv, or json format\n sam += 1\n if getsize(filePath)>0:\n print('Size sam', getsize(filePath))\n if extension in self.metadataFileFormats1[1]: #if csv\n csvf = 1\n UTF8status = self.check_csv_utf8(filePath)\n if UTF8status == 0:\n nonUTF8 = 1\n nonUTF8Files = \" \" + c + \",\"\n else:\n sam0kb = 1\n else:\n nonstand = 1\n nonStandardFiles += \" \" + c + \",\"\n\n elif (fullFileName == self.reqMetadataFileNames[3] + self.metadataFileFormats2[0]): #README.txt file\n if getsize(filePath)>0:\n rm = 1\n else:\n rm0kb = 1\n\n elif (fullFileName == self.optMetadataFileNames[1] + self.metadataFileFormats2[0]): #CHANGES.txt file\n chg = 1\n\n else:\n nonstand = 1\n nonStandardFiles += \" \" + c + \",\"\n\n #check for uniqueness\n if subm>1:\n cname = self.reqMetadataFileNames[0]\n nonu = 1\n nonUniqueFiles = \" \" + cname + \",\"\n if dd>1:\n cname = self.reqMetadataFileNames[1]\n nonu = 1\n nonUniqueFiles = \" \" + cname + \",\"\n if subj>1:\n cname = self.reqMetadataFileNames[2]\n nonu = 1\n nonUniqueFiles = \" \" + cname + \",\"\n if sam>1:\n cname = self.reqMetadataFileNames[3]\n nonu = 1\n nonUniqueFiles = \" \" + cname + \",\"\n\n\n check1 = \"All files are SPARC metadata files\"\n check1f = \"Only SPARC metadata files are allowed in the high-level dataset folder. The following file(s) must be removed:\"\n\n check2 = \"A non-empty 'submission' metadata file is included in either xlsx, csv, or json format\"\n check2f = \"This is a mandatory file for ALL SPARC datasets. It must be included and be in the correct format. You can prepare it in the 'Prepare Metadata' section of SODA.\"\n check2f2 = \"Your file is empty (0 kb). Ensure that the required content is included in the file. You can prepare it in the 'Prepare Metadata' section of SODA.\"\n \n check3 = \"A 'dataset_description' metadata file is included in either xlsx, csv, or json format\"\n check3f = \"This is a mandatory file for ALL SPARC datasets. It must be included and be in the correct format. You can prepare it in the 'Prepare Metadata' section of SODA.\"\n check3f2 = \"Your file is empty (0 kb). Ensure that the required content is included in the file. You can prepare it in the 'Prepare Metadata' section of SODA.\"\n \n check4 = \"A 'subjects' metadata file is included in either xlsx, csv, or json format\"\n check4f = \"This is a mandatory file for ALL SPARC datasets. It must be included and be in the correct format.\"\n check4f2 = \"Your file is empty (0 kb). Ensure that the required content is included in the file.\"\n \n check5 = \"A 'samples' metadata file is included in either xlsx, csv, or json format\"\n check5f = \"This is NOT a mandatory file but must be included (and be in the correct format) if your study includes samples (e.g., tissue slices). \"\n check5f2 = \"Your file is empty (0 kb). Ensure that the required content is included in the file.\"\n \n check6 = \"A 'README' (all uppercase) metadata file is included in txt format\"\n check6f = \"This is NOT a mandatory file but suggested for all SPARC datasets. If included, it must be in the txt format.\"\n check6f2 = \"Your file is empty (0 kb). This is not a mandatory file but if included, ensure that the required content is included in the file.\"\n \n check7 = \"All csv metadata files are UTF-8 encoded\"\n check7f = \"As per requirement from the SPARC Curation Team, please change the csv encoding format to UTF-8 for the following metadata files: \"\n\n check8 = \"All metadata files are unique\"\n check8f = \"Each metadata file should only be included once. The following metadata files are included more than once:\"\n\n if nofiles == 0:\n if nonstand == 1:\n self.fatal.append(check1 + \"--\" + check1f + nonStandardFiles[:-1])\n else:\n self.passes.append(check1)\n\n if subm == 1:\n if subm0kb == 1:\n subm = 0\n self.fatal.append(check2 + \"--\" + check2f2)\n else:\n self.passes.append(check2) \n elif subm == 0:\n self.fatal.append(check2 + \"--\" + check2f)\n \n if dd == 1:\n if dd0kb == 1:\n dd = 0\n self.fatal.append(check3 + \"--\" + check3f2)\n else:\n self.passes.append(check3) \n elif dd == 0:\n self.fatal.append(check3 + \"--\" + check3f)\n \n if subj == 1:\n if subj0kb == 1:\n subj = 0\n self.fatal.append(check4 + \"--\" + check4f2)\n else:\n self.passes.append(check4) \n elif subj == 0:\n self.fatal.append(check4 + \"--\" + check4f)\n \n if sam == 1:\n if sam0kb == 1:\n sam = 0\n self.fatal.append(check5 + \"--\" + check5f2)\n else:\n self.passes.append(check5) \n elif sam == 0:\n self.fatal.append(check5 + \"--\" + check5f)\n \n if not rm:\n if rm0kb == 1:\n self.fatal.append(check6 + \"--\" + check6f2)\n else:\n self.warnings.append(check6 + \"--\" + check6f)\n else:\n self.passes.append(check6)\n\n if csvf == 1:\n if nonUTF8 == 1:\n self.fatal.append(check7 + \"--\" + check7f + nonUTF8Files[:-1])\n else:\n self.passes.append(check7)\n\n if nofiles == 0:\n if nonu == 1:\n self.fatal.append(check8 + \"--\" + check8f + nonUniqueFiles[:-1])\n else:\n self.passes.append(check8)\n \n print('SUBM', subm)\n\n return subm, dd, subj, sam\n\n\n def check_empty_folders(self, jsonStruct):\n # detects empty folders if they exist, return a flag\n emptyFolderSearch = 0\n emptyFolderList = \"\"\n nonExistFolderSearch = 0\n nonExistFolderList = \"\"\n\n for folders in jsonStruct.keys():\n if len(jsonStruct[folders]) != 0:\n for mainPath in jsonStruct[folders]:\n if os.path.exists(mainPath):\n if os.path.isdir(mainPath):\n pathContent = os.listdir(mainPath)\n if len(pathContent) == 0:\n emptyFolderSearch = 1\n emptyFolderList += \" \" + mainPath + \",\"\n else:\n for root, dirs, files in os.walk(mainPath):\n for d in dirs:\n dp = os.path.join(root,d)\n pathContent = os.listdir(dp)\n if len(pathContent) == 0:\n emptyFolderSearch = 1\n emptyFolderList += \" \" + dp + \",\"\n else:\n nonExistFolderSearch = 1\n nonExistFolderList += \" \" + mainPath + \",\"\n\n check1 = \"All sub-folders are non-empty\"\n check1f = \"Empty folders MUST not be included in your dataset. The following empty folder(s) must be removed:\"\n\n check2 = \"All folder paths exist\"\n check2f = \"The following folder path(s) are non-existent and must be removed: \"\n\n if emptyFolderSearch == 0:\n self.passes.append(check1)\n else:\n self.fatal.append(check1 + '--' + check1f + emptyFolderList[:-1])\n\n if nonExistFolderSearch == 1:\n self.fatal.append(check2 + '--' + check2f + nonExistFolderList[:-1])\n\n\n def check_empty_files(self, jsonStruct):\n # detects empty files if they exist, return a flag\n emptyFileSearch = 0\n emptyFileList = \"\"\n nonExistFileSearch = 0\n nonExistFileList = \"\"\n\n for folders in jsonStruct.keys():\n if len(jsonStruct[folders]) != 0:\n for mainPath in jsonStruct[folders]:\n if os.path.exists(mainPath):\n if os.path.isfile(mainPath):\n fileSize = os.path.getsize(mainPath)\n if fileSize == 0:\n emptyFileSearch = 1\n emptyFileList += \" \" + mainPath + \",\"\n else:\n for root, dirs, files in os.walk(mainPath):\n for f in files:\n fp = os.path.join(root,f)\n fileSize = os.path.getsize(fp)\n if fileSize == 0:\n emptyFileSearch = 1\n emptyFileList += \" \" + fp + \",\"\n else:\n nonExistFileSearch = 1\n nonExistFileList += \" \" + mainPath + \",\"\n\n check1 = \"No empty files are included\"\n check1f = \"The following empty file(s) must be removed or corrected:\"\n\n check2 = \"All file paths exist\"\n check2f = \"The following file path(s) are non-existent and must be removed: \"\n\n if emptyFileSearch == 0:\n self.passes.append(check1)\n else:\n self.fatal.append(check1 + '--' + check1f + emptyFileList[:-1])\n\n if nonExistFileSearch == 1:\n self.fatal.append(check2 + '--' + check2f + nonExistFolderList[:-1])\n\n def check_ds_store(self, jsonStruct):\n # detects the presence of a DS.STORE file, \"1\" means the file exists\n # detects empty files if they exist, return a flag\n DS_STORESearch = 0\n DS_STOREList = \"\"\n\n for folders in jsonStruct.keys():\n if len(jsonStruct[folders]) != 0:\n for mainPath in jsonStruct[folders]:\n if os.path.exists(mainPath):\n if os.path.isfile(mainPath):\n fullName = os.path.basename(mainPath)\n if fullName == 'DS.STORE':\n DS_STORESearch = 1\n DS_STOREList += \" \" + mainPath + \",\"\n else:\n for root, dirs, files in os.walk(mainPath):\n for f in files:\n fp = os.path.join(root,f)\n fullName = os.path.basename(mainPath)\n if fullName == 'DS.STORE':\n DS_STORESearch = 1\n DS_STOREList += \" \" + fp + \",\"\n\n check1 = \"No DS.STORE files are included\"\n check1f = \"The following DS.STORE file(s) must be removed:\"\n\n if DS_STORESearch == 0:\n self.passes.append(check1)\n else:\n self.fatal.append(check1 + '--' + check1f + DS_STOREList[:-1])\n\n\n def check_csv_utf8(self, fPathList):\n # checks that all csv files are UTF-8 encoded\n # since looping through the files a \"0\" means that at least\n # one file was not UTF-8, and which one(s) is/are recorded\n # in the warnings.\n utf8Check = 1\n\n f = fPathList\n fileNamePath, fileExtension = os.path.splitext(f)\n\n if fileExtension == \".csv\":\n # this is another way to do it, but it passes test files\n # that chardet says are ascii, rather than utf-8\n #try:\n # fd=open(f, encoding='utf-8', errors='strict')\n #except UnicodeDecodeError:\n # utf8Check = 0\n # warnings.append(\"The file {} is not encoded using UTF-8\".format(f))\n\n # open the file as binary; join some lines together and pass to chardet\n # chardet returns a dictionary with the key <encoding> giving what we want\n with open(f, 'rb') as fd:\n # Join binary lines for specified number of lines;\n rawdata = b''.join([fd.readline() for _ in range(3)])\n if 'UTF-8' not in chardet.detect(rawdata)['encoding']:\n utf8Check = 0\n\n #if utf8Check == 1:\n # self.passes.append(\"All .csv files in this dataset are UTF-8 encoded.\")\n\n return utf8Check\n\n def check_manifest_file_included(self, jsonStruct):\n # checks if a manifest file is included in all folders with files or in all high-level SPARC folders\n mnf_style = 0 # 0 = none; 1 if manifest file is included in all folders with files; 2 if manifest file is included in all high-level SPARC folders\n\n mnf_hlf = 0\n mnf_slf = 0\n\n msng_hlf = 0\n missingHLF = \"\"\n msng_slf = 0\n missingSLF = \"\"\n\n not_req_slf = 0\n notRequiredSLF = \"\"\n\n multiple_mnf_hlf = 0\n multipleListHLF = \"\"\n multiple_mnf_slf = 0\n multipleListSLF = \"\"\n\n manifest_allowed_name = []\n for extension in self.metadataFileFormats1:\n manifest_allowed_name.append(self.manifestFileName + extension)\n\n # check for manifest files in any of the allowable format\n allContents = jsonStruct.keys()\n allContents = [ x for x in allContents if x!='main' ]\n for folder in allContents:\n if len(jsonStruct[folder]) != 0:\n hl_file = 0\n num_manifest_hlf = 0\n for mainPath in jsonStruct[folder]:\n if os.path.exists(mainPath):\n if os.path.isdir(mainPath):\n pathContent = os.listdir(mainPath)\n if len(pathContent) != 0:\n # check manifest file in sub-level folders\n for root, dirs, files in os.walk(mainPath):\n if len(files) > 0 :\n num_manifest = 0\n num_file = 0\n for f in files:\n if f in manifest_allowed_name:\n mnf_slf += 1\n num_manifest += 1\n else:\n fname = os.path.splitext(f)[0]\n if fname != 'README':\n num_file += 1\n if num_file == 0:\n if num_manifest>0:\n notRequiredSLF = \" \" + str(root) + \",\"\n if num_file > 0:\n if num_manifest == 0:\n missingSLF += \" \" + str(root) + \",\"\n elif num_manifest > 1:\n multiple_mnf_slf += 1\n multipleListSLF += \" \" + str(root) + \",\"\n else:\n # check for manifest file in high-level SPARC folder\n fullFileName = os.path.basename(mainPath)\n if fullFileName in manifest_allowed_name:\n mnf_hlf += 1\n num_manifest_hlf += 1\n else:\n fname = os.path.splitext(fullFileName)[0]\n if fname != 'README':\n hl_file += 1\n\n if num_manifest_hlf == 0:\n msng_hlf += 1\n missingHLF += \" \" + str(folder) + \",\"\n if hl_file>0:\n msng_slf += 1\n missingSLF += \" \" + str(folder) + \",\"\n elif num_manifest_hlf == 1:\n if hl_file == 0:\n not_req_slf += 1\n notRequiredSLF += \" \" + str(folder) + \",\"\n elif num_manifest_hlf > 1:\n multiple_mnf_hlf += 1\n multipleListHLF += \" \" + str(folder) + \",\"\n if hl_file>0:\n multiple_mnf_slf += 1\n multipleListSLF += \" \" + str(folder) + \",\"\n\n\n check1 = \"Manifest files in xlsx, csv, or json format are included in EITHER all folders with at least one file or all high-level SPARC folders only\"\n\n check1f = \"Please include manifest files according to one of the two allowable configurations. They can be generated automatically from the 'Prepare Dataset' section of SODA.\"\n\n check1c1 = \"It is likely you chose the 'all folders with at least one file' option\"\n check1c2 = \"It is likely you chose the 'all high-level SPARC folders only' option\"\n\n check1f2 = \"A manifest is missing in the following folders: \"\n\n check1f3 = \"The manifest must be removed from the following folder(s) since they contain only folders or a 'README' file: \"\n check1f4 = \"Multiple manifest files are included in the following folder(s): \"\n\n user_msg = check1\n if mnf_hlf == 0 and mnf_slf == 0:\n user_msg += '--' + check1f\n self.fatal.append(user_msg)\n\n elif mnf_slf>0:\n mnf_style = 1\n user_msg += '--' + check1c1\n if msng_slf == 0 and not_req_slf == 0 and multiple_mnf_slf == 0:\n self.passes.append(user_msg)\n else:\n if msng_slf>0:\n user_msg += '--' + check1f2 + missingSLF[:-1]\n if not_req_slf > 0:\n user_msg += '--' + check1f3 + notRequiredSLF[:-1]\n if multiple_mnf_slf > 0:\n user_msg += '--' + check1f4 + multipleListSLF[:-1]\n self.fatal.append(user_msg)\n\n elif mnf_hlf>0:\n mnf_style = 2\n user_msg += '--' + check1c2\n if msng_hlf == 0 and multiple_mnf_hlf == 0:\n self.passes.append(user_msg)\n else:\n if msng_hlf>0:\n user_msg += '--' + check1f2 + missingHLF[:-1]\n if multiple_mnf_hlf > 0:\n user_msg += '--' + check1f4 + multipleListHLF[:-1]\n self.fatal.append(user_msg)\n\n return mnf_style\n\n def check_submission_file(self, submFilePath):\n firsth = 0\n valueh = 0\n nonstandardh = 0\n nonStandardHeaders = \"\"\n c0 = 0\n v = 1\n\n fullName = os.path.basename(submFilePath)\n\n submissionName = self.reqMetadataFileNames[0]\n expectedSubmissionFullName = [(submissionName + i) for i in self.metadataFileFormats1]\n\n if fullName not in expectedSubmissionFullName:\n raise Exception(\"Please select a valid submission file\")\n\n if os.path.isfile(submFilePath):\n extension = os.path.splitext(fullName)[1]\n if extension == '.csv':\n\n df = pd.read_csv(submFilePath)\n elif extension == '.xlsx':\n df = pd.read_excel(submFilePath)\n elif extension == '.json':\n self.warnings.append(\"The SODA validator currently doesn't support the json format so your file cannot be validated. This will be implemented in a future release.\")\n return\n\n # check that first header is \"Submission item\"\n fileHeaders = list(df)\n if fileHeaders[0] == self.reqSubmissionHeaders[0]:\n firsth = 1\n\n #check that first column matches with template\n if df[self.reqSubmissionHeaders[0]].tolist() == self.submissionCol0:\n c0 = 1\n\n # check that 'Value' header is included\n if self.reqSubmissionHeaders[1] in fileHeaders:\n valueh = 1\n\n #check that the value column does't contain any NaN or empty elements\n if df[self.reqSubmissionHeaders[1]].isnull().any():\n v = 0\n\n valueCol = df[self.reqSubmissionHeaders[1]].values\n valueColMod = []\n for x in valueCol:\n if type(x) == str:\n valueColMod.append(x.strip())\n else:\n valueColMod.append(x)\n if \"\" in valueCol:\n v = 0\n\n #check that the only other header is \"Definition\"\n for header in fileHeaders:\n if header not in (self.reqSubmissionHeaders + self.optSubmissionHeaders):\n nonstandardh = 1\n nonStandardHeaders += \" \" + header + \",\"\n\n check1 = \"The submission file format matches with the template provided by the SPARC Curation Team\"\n check1f0 = \"The above format error(s) must be corrected before further check of the file\"\n check1f = \"The first header (in cell A1) MUST be \" + self.reqSubmissionHeaders[0]\n check1f2 = \"The first column items do not match exactly with the template, please correct them.\"\n\n check1f3 = \"A \" + self.reqSubmissionHeaders[1] + \" header must be included\"\n\n check1f4 = \"Only the following headers are expected: \" + str(self.reqSubmissionHeaders[0]) + \\\n str(self.reqSubmissionHeaders[1]) + \",\" + str(self.optSubmissionHeaders[0]) + \\\n \". Remove the following non-standard headers: \"\n\n check2 = \"All cells in the 'Value' column are populated\"\n check2f = \"One or multiple cells from the 'Value' column are empty. All three of them must be populated.\"\n\n if firsth==1 and c0==1 and valueh==1 and nonstandardh==0:\n self.passes.append(check1)\n if v == 1:\n self.passes.append(check2)\n else:\n self.fatal.append(check2 + '--' + check2f)\n else:\n user_msg = check1\n if firsth == 0:\n user_msg += '--' + check1f\n else:\n if c0 == 0:\n user_msg += '--' + check1f2\n if valueh == 0:\n user_msg += '--' + check1f3\n if nonstandardh == 1:\n user_msg += '--' + check1f4\n user_msg += '--' + check1f0\n self.fatal.append(user_msg)\n if valueh == 1:\n if v == 1:\n self.passes.append(check2)\n else:\n self.fatal.append(check2 + '--' + check2f)\n\n def check_dataset_description_file(self, ddFilePath):\n # Check that\n # - The dataset description file follows the format provided by the Curation Team\n # - All mandatory \"Value\" fields are populated\n # - No negative statements ('None', 'N/A', etc.) are providedf for optional fields\n # - All populated fields follow required format (when applicable)\n\n columnfail = 0\n firsthnotstd = 0\n c0empt = 0\n c0emptList = \"\"\n c0duplicate = 0\n c0duplicateList = \"\"\n c0mandmissing = 0\n c0mandmissingList = \"\"\n c0optremove = 0\n c0optremoveList = \"\"\n\n cempty = 0\n cemptyList = \"\"\n\n headersfail = 0\n hvaluemissing = 0\n hempty = 0\n hemptyList = \"\"\n hnotallowed = 0\n hnotallowedList = \"\"\n hnotunq = 0\n hnotunqList = \"\"\n hvaluesequencewrong = 0\n\n valuemandempty = 0\n valuemandemptyList = \"\"\n valuemandnoneterm = 0\n valuemandnonetermList = \"\"\n valueoptnoneterm = 0\n valueoptnonetermList = \"\"\n valuefail = 0\n\n keywordsfail = 0\n contributorsnameunqfail = 0\n contributorsnameunqfailList = \"\"\n contributorsnameformatfail = 0\n contributorsnameformatfailList = \"\"\n contributorinfofail = 0\n contributorinfofailList = \"\"\n orcidformatfail = 0\n orcidformatfailList = \"\"\n rolefail = 0\n rolefailList = \"\"\n contactpersonformatfail = 0\n contactpersonformatfailList = \"\"\n contactpersonfail = 0\n fundingsourcefail = 0\n fundingsourcefailList = \"\"\n linksnumfail = 0\n linksnumfailList = \"\"\n articleformatfail = 0\n articleformatfailList = \"\"\n protocolformatfail = 0\n protocolformatfailList = \"\"\n numsubjectsformatfail = 0\n numsamplesformatfail = 0\n completenessformatfail = 0\n parentidvaluefail = 0\n parentidvaluefailList = \"\"\n parentidformatfail = 0\n parentidformatfailList = \"\"\n metadataversionfail = 0\n\n fullName = os.path.basename(ddFilePath)\n dDName = self.reqMetadataFileNames[1]\n expectedDDFullName = [(dDName + i) for i in self.metadataFileFormats1]\n\n if fullName not in expectedDDFullName:\n raise Exception(\"Please select a valid dataset_description file\")\n\n if not os.path.isfile(ddFilePath):\n raise Exception(\"File path not found, please select a valid file\")\n else:\n extension = os.path.splitext(ddFilePath)[1]\n if extension == '.csv':\n UTF8status = self.check_csv_utf8(ddFilePath)\n if UTF8status == 0:\n self.fatal.append(\"You csv format file must be UTF-8 encoded\")\n return\n df = pd.read_csv(ddFilePath, header=None) # headers ignored here since pandas modify duplicat headers\n elif extension == '.xlsx':\n df = pd.read_excel(ddFilePath, header=None)\n elif extension == '.json':\n self.warnings.append(\"The SODA validator currently doesn't support the json format so your file cannot be validated. This will be implemented in a future release.\")\n return\n df = cleanDataFrame(df)\n # Column headers of the cleaned up df\n fileHeaders = list(df)\n\n #check that first hearder is \"Metadata element\"\n if fileHeaders[0] != self.reqddHeaders[0]:\n firsthnotstd = 1\n else:\n\n #FIRST COLUMN CHECK\n\n #check for empty first column elements\n valueCol = df[self.reqddHeaders[0]].values\n index_empty = [i for i, e in enumerate(valueCol) if e == \"empty\"]\n if len(index_empty)>0:\n c0empt = 1\n index_empty.sort()\n for i in index_empty:\n c0emptList += str(i+2) + \",\"\n\n #check for duplicates first column elements\n dfnoEmpt = df.drop(index_empty)\n valueColnoEmpt = dfnoEmpt[self.reqddHeaders[0]].values\n if len(set(valueColnoEmpt)) != len(valueColnoEmpt):\n c0duplicate = 1\n #list of non unique items:\n item = []\n duplicate_list = []\n for x in valueColnoEmpt:\n if x in self.ddCol0Req or x in self.ddCol0Opt:\n if x not in item:\n item.append(x)\n else:\n if x not in duplicate_list:\n duplicate_list.append(x)\n c0duplicateList += \" \" + x + \",\"\n\n #check that mandatory column elements are present\n valueColUnq = set(valueColnoEmpt)\n for el in self.ddCol0Req:\n if el not in valueColUnq:\n c0mandmissing = 1\n c0mandmissingList += \" \" + el + \",\"\n\n #check that other column elements are within allowable optional elements\n for el in valueColUnq:\n if el not in self.ddCol0Req:\n if el not in self.ddCol0Opt:\n c0optremove = 1\n c0optremoveList += \" \" + el + \",\"\n\n #empty column check:\n listh = list(df)\n for i, header in enumerate(listh):\n if len(set(df.iloc[:,i].values))==1 and df.iloc[0, i]=='empty':\n cempty = 1\n cemptyList += \" \" + str(i+1) + \",\"\n\n # HEADERS CHECK\n\n # check that Value header is included\n if self.reqddHeaders[1] not in fileHeaders:\n hvaluemissing = 1\n\n # check that there are no empty headers\n index_unnamed = [i for i, e in enumerate(fileHeaders) if \"Empty.\" in e]\n if len(index_unnamed)>0:\n hempty = 1\n index_unnamed.sort()\n for i in index_unnamed:\n hemptyList += \" \" + str(i+1) + \",\"\n\n # check that only allowable hearders are used\n fileHeadersnonEmpty = list(fileHeaders)\n for index in sorted(index_unnamed, reverse=True):\n del fileHeadersnonEmpty[index]\n fileHeadersnonEmpty = set(fileHeadersnonEmpty)\n for item in fileHeadersnonEmpty:\n if item not in self.reqddHeaders and item not in self.optddHeaders:\n hnotallowed = 1\n hnotallowedList += \" \" + item + \",\"\n\n # check that all headers are unique\n if len(set(fileHeadersnonEmpty)) != len(fileHeadersnonEmpty):\n hnotunq = 1\n #list of non unique headers:\n item = []\n notunqval = []\n for x in fileHeadersnonEmpty:\n if x not in item:\n item.append(x)\n else:\n if x not in notunqval:\n notunqval.append(x)\n hnotunqList += \" \" + x + \",\"\n\n # Value must be the first column (besides Metadata element, Description, and Example) and all subsequent must be Value 2, Value 3, etc.\n removeHeadersList = [self.reqddHeaders[0], self.optddHeaders[0], self.optddHeaders[1]]\n fileHeadersVal = list(fileHeaders)\n for item in removeHeadersList:\n if item in fileHeadersVal: fileHeadersVal.remove(item)\n if len(fileHeadersVal) == 0:\n hvaluesequencewrong = 1\n elif fileHeadersVal[0] != self.reqddHeaders[1]:\n hvaluesequencewrong = 1\n else:\n if len(fileHeadersVal)>1:\n count = 2\n for item in fileHeadersVal[1:]:\n if item != 'Value ' + str(count):\n hvaluesequencewrong = 1\n break\n else:\n count += 1\n\n # If column pass and headers pass continue\n if c0empt == 0 and c0duplicate == 0 and c0mandmissing == 0 and c0optremove == 0 and cempty == 0:\n columnfail = 0\n else:\n columnfail = 1\n\n if hvaluemissing == 0 and hempty == 0 and hnotallowed == 0 and hnotunq == 0 and hvaluesequencewrong == 0:\n headersfail = 0\n else:\n headersfail = 1\n\n if columnfail == 0 and headersfail == 0:\n\n #check for empty \"Value\" for mandatory fields\n dfMand = df.loc[df[self.reqddHeaders[0]].isin(self.ddCol0Req)]\n valueColMod = []\n for x in valueCol:\n if type(x) == str:\n valueColMod.append(x.strip())\n else:\n valueColMod.append(x)\n index_empty = [i for i, e in enumerate(valueColMod) if e == \"empty\"]\n if len(index_empty)>0:\n valuemandempty = 1\n for i in index_empty:\n valuemandemptyList += \" \" + dfMand[self.reqddHeaders[0]].iloc[i] + \",\"\n\n #check for non terms for \"Value\" for mandatory fields\n index_none = [i for i, e in enumerate(valueColMod) if e in self.noneTerms]\n if len(index_none)>0:\n valuemandnoneterm = 1\n for i in index_none:\n valuemandnonetermList += \" \" + dfMand[self.reqddHeaders[0]].iloc[i] + \",\"\n\n #check in optional fields for none terms\n dfOpt = df.loc[df[self.reqddHeaders[0]].isin(self.ddCol0Opt)]\n valueCol = dfOpt[self.reqddHeaders[1]].values\n valueColMod = []\n for x in valueCol:\n if type(x) == str:\n valueColMod.append(x.strip())\n else:\n valueColMod.append(x)\n index_none = [i for i, e in enumerate(valueColMod) if e in self.noneTerms]\n if len(index_none)>0:\n valueoptnoneterm = 1\n for i in index_none:\n valueoptnonetermList += \" \" + dfMand[self.reqddHeaders[0]].iloc[i] + \",\"\n\n # CHECK PROVIDED VALUES\n if valuemandempty == 0 and valuemandnoneterm == 0 and valueoptnoneterm == 0:\n valuefail = 0\n else:\n valuefail = 1\n\n if valuefail == 0:\n dfv = df\n dropColumn = [self.optddHeaders[0], self.optddHeaders[1]]\n for item in dropColumn:\n if item in fileHeaders:\n dfv = dfv.drop(item, axis=1)\n\n metadataEl = self.reqddHeaders[0]\n valueEl = self.reqddHeaders[1]\n\n # 3-5 unique keywords are provided and they are each in a separate column\n selectedEl = self.ddCol0Req[2]\n keywordsList = dfv.loc[dfv[metadataEl] == selectedEl].iloc[0].values\n keywordsList = np.delete(keywordsList, np.argwhere(keywordsList == selectedEl))\n keywordsList = np.delete(keywordsList, np.argwhere(keywordsList == self.empty))\n keywordsListUnq = np.unique(keywordsList)\n\n if len(keywordsListUnq)>2 and len(keywordsListUnq)<6:\n keywordsfail = 0\n else:\n keywordsfail = 1\n\n # Contributors Names are unique and in the Format Last, First Middle\n selectedEl = self.ddCol0Req[3]\n contributorsList = dfv.loc[dfv[metadataEl] == selectedEl].iloc[0].values\n contributorsList = np.delete(contributorsList, np.argwhere(contributorsList == selectedEl))\n contributorsList = np.delete(contributorsList, np.argwhere(contributorsList == self.empty))\n contributorsListUnq = np.unique(contributorsList)\n\n if len(contributorsListUnq) != len(contributorsList):\n contributorsnameunqfail = 1\n #list of non unique names:\n item = []\n notunqval = []\n for x in contributorsList:\n if x not in item:\n item.append(x)\n else:\n if x not in notunqval:\n notunqval.append(x)\n contributorsnameunqfailList += \" \" + x + \",\"\n\n for item in contributorsList:\n #number of comma\n countcomma = 0\n for i in item:\n if i == \",\":\n countcomma += 1\n if countcomma != 1:\n contributorsnameformatfail = 1\n contributorsnameformatfailList += \" \" + item + \",\"\n\n # For each Contributor there must be at least one affiliation, only one ORCID, at least one role\n if contributorsnameunqfail == 0 and contributorsnameformatfail == 0:\n selectedEl1 = self.ddCol0Req[3]\n selectedEl2 = self.ddCol0Req[4]\n selectedEl3 = self.ddCol0Req[5]\n selectedEl4 = self.ddCol0Req[6]\n selectedEl5 = self.ddCol0Req[7]\n\n nameList = dfv.loc[dfv[metadataEl] == selectedEl1].iloc[0].values\n nameList = np.delete(nameList, np.argwhere(nameList == selectedEl1))\n orcidList = dfv.loc[dfv[metadataEl] == selectedEl2].iloc[0].values\n orcidList = np.delete(orcidList, np.argwhere(orcidList == selectedEl2))\n affiliationList = dfv.loc[dfv[metadataEl] == selectedEl3].iloc[0].values\n affiliationList = np.delete(affiliationList, np.argwhere(affiliationList == selectedEl3))\n roleList = dfv.loc[dfv[metadataEl] == selectedEl4].iloc[0].values\n roleList = np.delete(roleList, np.argwhere(roleList == selectedEl4))\n contactpersonList = dfv.loc[dfv[metadataEl] == selectedEl5].iloc[0].values\n contactpersonList = np.delete(contactpersonList, np.argwhere(contactpersonList == selectedEl5))\n\n for name, orcid, affiliation, role, contactperson in zip(nameList, orcidList, affiliationList, roleList, contactpersonList):\n if name != self.empty:\n if orcid == self.empty or affiliation == self.empty or role == self.empty or contactperson == self.empty:\n contributorinfofail = 1\n contributorinfofailList += \" \" + name + \";\"\n\n # ORCID in the format https://orcid.org/0000-0002-5497-0243\n for orcid in orcidList:\n if orcid != self.empty:\n if 'https://orcid.org/' not in orcid:\n orcidformatfail = 1\n orcidformatfailList += \" \" + orcid + \",\"\n\n # There must be only one contributor role per column and each of them must be from the Data Cite list of roles\n for role in roleList:\n if role != self.empty:\n if role not in self.contributorRoles:\n rolefail = 1\n rolefailList += \" \" + role + \",\"\n\n # Contact person must be 'Yes' or 'No' and there must one and only one 'Yes'\n countYes = 0\n for contactperson in contactpersonList:\n if contactperson != self.empty:\n if contactperson not in self.contactPersonOptions:\n contactpersonformatfail = 1\n contactpersonformatfailList += \" \" + contactperson + \",\"\n elif contactperson == self.contactPersonOptions[0]:\n countYes += 1\n if countYes != 1:\n contactpersonfail = 1\n\n # One funding source listed per column\n selectedEl = self.ddCol0Req[8]\n fundingList = dfv.loc[dfv[metadataEl] == selectedEl].iloc[0].values\n fundingList = np.delete(fundingList, np.argwhere(fundingList == selectedEl))\n fundingList = np.delete(fundingList, np.argwhere(fundingList == self.empty))\n for fundingsource in fundingList:\n if \",\" in fundingsource or \";\" in fundingsource:\n fundingsourcefail = 1\n fundingsourcefailList += \" \" + fundingsource + \",\"\n\n # There must be only one of DOI of articles, DOI/URL of protocol or Additional link per column\n selectedEl1 = self.ddCol0Req[9]\n selectedEl2 = self.ddCol0Opt[1]\n selectedEl3 = self.ddCol0Opt[2]\n selectedElList = [selectedEl1, selectedEl2, selectedEl3]\n dfc = dfv.loc[dfv[metadataEl].isin(selectedElList)]\n\n linkHeaders = list(dfc)\n for header in linkHeaders:\n if header != metadataEl:\n linkList = dfc[header].values\n numempty = list(linkList).count(self.empty)\n if numempty == 0 or numempty == 1:\n linksnumfail = 0\n linksnumfailList += \" \" + header + \",\"\n\n # DOI articles format follows https://doi.org/xxxx\n articleList = dfv.loc[dfv[metadataEl] == selectedEl1].iloc[0].values\n articleList = np.delete(articleList, np.argwhere(articleList == selectedEl1))\n for article in articleList:\n if article != self.empty:\n if 'https://doi.org/' not in article:\n articleformatfail = 1\n articleformatfailList += \" \" + str(article) + \",\"\n\n # URL/DOI format follows https://protocol.io/xxxx or https://doi.org/xxxx\n protocolList = dfv.loc[dfv[metadataEl] == selectedEl2].iloc[0].values\n protocolList = np.delete(protocolList, np.argwhere(protocolList == selectedEl2))\n for protocol in protocolList:\n if protocol != 'empty':\n if 'https://doi.org/' not in protocol or 'https://www.protocols.io/' not in protocol:\n protocolformatfail = 1\n protocolformatfailList += \" \" + protocol + \",\"\n\n # Number of subjects must be an integer\n selectedEl = self.ddCol0Req[10]\n selectedElList = [selectedEl]\n dfc = dfv.loc[dfv[metadataEl].isin(selectedElList)]\n numSubjects = dfc[valueEl].values[0]\n try:\n numSubjects = int(numSubjects)\n except ValueError:\n numsubjectsformatfail = 1\n print(f\"Number of subjects: {numSubjects} is not a valid integer.\")\n # if not numSubjects.isdigit():\n # numsubjectsformatfail = 1\n\n # Number of samples must be an integer\n selectedEl = self.ddCol0Req[11]\n selectedElList = [selectedEl]\n dfc = dfv.loc[dfv[metadataEl].isin(selectedElList)]\n numSamples = dfc[valueEl].values[0]\n try:\n numSamples = int(numSamples)\n except ValueError:\n numsamplesformatfail = 1\n print(f\"Number of samples: {numSamples} is not a valid integer.\")\n # if not numSamples.isdigit():\n # numsamplesformatfail = 1\n\n # Completeness of data must be \"empty\", \"hasNext\", or \"hasChildren\"\n selectedEl = self.ddCol0Opt[4]\n selectedElList = [selectedEl]\n dfc = dfv.loc[dfv[metadataEl].isin(selectedElList)]\n completeness = dfc[valueEl].values[0]\n if completeness not in self.completnessInfo and completeness != self.empty:\n completenessformatfail = 1\n\n # Parent dataset ID must be comma seperated list and each ID must be of the format N:dataset:xxxx\n selectedEl = self.ddCol0Opt[5]\n selectedElList = [selectedEl]\n dfc = dfv.loc[dfv[metadataEl].isin(selectedElList)]\n\n for header in list(dfc):\n if header != metadataEl and header != valueEl:\n item = dfc[header].values[0]\n if item != self.empty:\n parentidvaluefail = 1\n parentidvaluefailList += \" \" + header + \",\"\n\n\n parentIDList = dfc[valueEl].values[0]\n if parentIDList != self.empty:\n if ',' in parentIDList:\n parentIDList = [parentID for parentID in parentIDList.split(',')]\n parentIDList = [parentID.strip() for parentID in parentIDList]\n for parentID in parentIDList:\n\n if \"N:dataset:\" not in parentID:\n parentidformatfail = 1\n parentidformatfailList += \" \" + parentID + \",\"\n\n else:\n if \"N:dataset:\" not in parentIDList:\n parentidformatfail = 1\n parentidformatfailList += \" \" + parentIDList + \",\"\n\n # Metadata version must be 1.2.3 as of 06/2020\n selectedEl = self.ddCol0Req[12]\n selectedElList = [selectedEl]\n dfc = dfv.loc[dfv[metadataEl].isin(selectedElList)]\n metadataV = dfc[valueEl].values[0]\n metadataV.strip()\n if metadataV != self.metadataVersion:\n metadataversionfail = 1\n\n\n check1= \"The first column header is 'Metadata element' and is located in the top left corner\"\n check1f = \"The header of the first column MUST be 'Metadata element' and must be located in cell A1. Rectify it.\"\n check1f0 = \"The above format error(s) must be corrected before further check of the file\"\n\n check1_c = \"The content of the first column 'Metadata element' match exactly with the template version 1.2.3 provided by the Curation Team and there are no empty columns.\"\n check1_c1 = \"In the first column, the following row number element(s) is/are empty and must be populated or removed: \"\n check1_c2 = \"All elements in the first column must be unique. The following element(s) is/are duplicated: \"\n check1_c3 = \"The following standard element(s) is/are missing in the first column and MUST be included: \"\n check1_c4 = \"The following element(s) is/are not standard in the first column and MUST be removed: \"\n check1_c5 = \"The following column number is/are empty and must be deleted or populated: \"\n\n check1_h = \"The names of the column headers meet all requirements\"\n check1_h1 = \"The following mandatory header is missing: 'Value'\"\n check1_h2 = \"All columns must have a header. The following column number do not have a header: \"\n check1_h3 = \"Only the following hearders are expected: 'Metadata element', 'Description', 'Example', and \\\n 'Value', 'Value 2', 'Value 3', etc. The following headers should be removed/corrected: \"\n check1_h4 = \"All headers must be unique. The following header(s) is/are duplicated: \"\n check1_h5 = \"'Value' must be the first column header after 'Metadata element' (and the optional 'Description' and 'Example' columns) followed by the sequence Value 2, Value 3, etc. as applicable\"\n\n check2 = \"There is an element in the 'Value' column for all mandatory fields of the first column 'Metadata element'\"\n check2_1 = \"The following mandatory element(s) of the first column MUST be provived an element in the 'Value' column: \"\n check2_2 = \"Negative statements ('None', 'N/A', etc.) are not allowed for mandatory element(s). Rectify the 'Value' element for the folowing 'Metadata element': \"\n\n check3 = \"There is an acceptable element in the 'Value' column for optional fields of the first column 'Metadata element' elements or it is left empty\"\n check3_1 = \"Negative statements ('None', 'N/A', etc.) are not allowed for optional element(s). Rectify/detele the 'Value' element for the folowing optional 'Metadata element': \"\n\n check_keywords = \"3 to 5 unique keywords are provided for the 'Keywords' field\"\n check_keywords_f = \"Ensure that 3 to 5 unique keywords are provided, each one in a seperate column\"\n\n check_contributorsname = \"Contributors names are unique and in the format 'Last, First Middle'\"\n check_contributorsname_f1 = \"The following contributor name(s) may have been included more than once: \"\n check_contributorsname_f2 = \"The following contributor name(s) may not follow the expected 'Last, First Middle' format: \"\n\n check_contributorinfo = \"For each 'Contributors' listed there is at least only one 'Contributor ORCID ID', at least one 'Contributor Affiliation', at least one 'Contributor Role', and one 'Is Contact Person' specified\"\n check_contributorinfo_f = \"Check that above requirements are met for the following 'Contributors': \"\n\n check_orcid = \" 'Contributor ORCID ID' are in the format 'https://orcid.org/xxxx-xxxx-xxxx-xxxx\"\n check_orcid_f = \"The following ORCID element is/are not in the required format and must be corrected: \"\n\n check_contributorrole = \"There must be only one contributor role per column and each of them must be from the Data Cite list of roles\"\n check_contributorrole_f = \"The following role(s) do(es) not fit the requirements and must be corrected: \"\n\n check_contactperson = \"'Is Contact Person' is either 'Yes' or 'No' and there is one and only one 'Yes' across all contributors\"\n check_contactperson_f1 = \"The following 'Is Contact Person' element is not 'Yes' or 'No': \"\n check_contactperson_f2 = \"There must be one and only one 'Yes' for the 'Is Contact Person' field. Currently there is either none or more than one\"\n\n check_fundingsource = \"Each funding source is mentioned in a seperate column\"\n check_fundingsource_f = \"Make sure the following refers to a single funding source: \"\n\n check_links = \"There is only one of the following in each Value column: Originating Article DOI, Protocol URL or DOI, or Additional Links\"\n check_links_f = \"Make sure the above condition is met in the following column(s): \"\n\n check_articles = \"'Originating Article DOI' is in the format https://doi.org/xxxx\"\n check_articles_f = \"Make sure the above condition is for the following DOI article(s): \"\n\n check_protocols = \"'Protocol URL or DOI' is in the format https://protocol.io/xxxx or https://doi.org/xxxx\"\n check_protocols_f = \"Make sure the above condition is met for the following Protocol URL or DOI: \"\n\n check_numsubjects = \"'Number of subjects' is provided an integer number as 'Value'\"\n check_numsubjects_f = \"Ensure that an integer number is provided for the 'Number of subjects' field in the 'Value' column\"\n\n check_numsamples = \"'Number of samples' is provided an integer number as 'Value'\"\n check_numsamples_f = \"Ensure that an integer number is provided for the 'Number of samples' field in the 'Value' column\"\n\n check_completness = \"'Completeness of data set' is provided an allowable 'Value'\"\n check_completness_f = \"Ensure that the 'Value' for 'Completeness of data set' is either empty, 'hasNext', or 'hasChildren'\"\n\n check_parentID = \"'Parent dataset ID' is only provided in the 'Value' column and is in the correct format or left empty\"\n check_parentID_f1 = \"'Parent dataset ID' must be only provided in the 'Value' column. Delete values in the following column: \"\n check_parentID_f2 = \"'Parent dataset ID' must be of the format 'N:dataset:xxxx' (Blackfynn dataset ID). Correct the following ID or delete it: \"\n\n check_metadatav = \"The 'Value' for 'Metadata Version DO NOT CHANGE' is '1.2.3'\"\n check_metadatav_f = \"The 'Value' for 'Metadata Version DO NOT CHANGE' must be '1.2.3'. Correct it.\"\n\n if firsthnotstd == 1:\n self.fatal.append(check1 + '--' + check1f + '--' + check1f0)\n else:\n self.passes.append(check1)\n\n msg = check1_c\n if columnfail == 1:\n if c0empt == 1:\n msg += '--' + check1_c1 + c0emptList[:-1]\n if c0duplicate == 1 :\n msg += '--' + check1_c2 + c0duplicateList[:-1]\n if c0mandmissing == 1:\n msg += '--' + check1_c3 + c0mandmissingList[:-1]\n if c0optremove == 1:\n msg += '--' + check1_c4 + c0optremoveList[:-1]\n if cempty == 1:\n msg += '--' + check1_c5 + cemptyList[:-1]\n msg += '--' + check1f0\n self.fatal.append(msg)\n else:\n self.passes.append(msg)\n\n msg = check1_h\n if headersfail == 1:\n if hvaluemissing == 1:\n msg += '--' + check1_h1\n if hempty == 1:\n msg += '--' + check1_h2 + hemptyList[:-1]\n if hnotallowed == 1:\n msg += '--' + check1_h3 + hnotallowedList[:-1]\n if hnotunq == 1:\n msg += '--' + check1_h4 + hnotunqList[:-1]\n if hvaluesequencewrong == 1:\n msg += '--' + check1_h5\n msg += '--' + check1f0\n self.fatal.append(msg)\n else:\n self.passes.append(msg)\n\n if columnfail == 0 and headersfail == 0:\n msg = check2\n if valuemandempty == 0 and valuemandnoneterm == 0:\n self.passes.append(msg)\n else:\n if valuemandempty ==1:\n msg += '--' + check2_1 + valuemandemptyList[:-1]\n if valuemandnoneterm == 1:\n msg += '--' + check2_2 + valuemandnonetermList[:-1]\n self.fatal.append(msg)\n\n msg = check3\n if valueoptnoneterm == 0:\n self.passes.append(msg)\n else:\n msg += '--' + check3_1 + valueoptnonetermList[:-1]\n self.fatal.append(msg)\n\n if valuefail == 0:\n\n msg = check_keywords\n if keywordsfail == 0:\n self.passes.append(msg)\n else:\n self.fatal.append(msg + '--' + check_keywords_f)\n\n msg = check_contributorsname\n if contributorsnameunqfail == 0 and contributorsnameformatfail == 0:\n self.passes.append(msg)\n\n msg = check_contributorinfo\n if contributorinfofail == 0:\n self.passes.append(msg)\n else:\n msg += '--' + check_contributorinfo_f + contributorinfofailList[:-1]\n self.fatal.append(msg)\n else:\n if contributorsnameunqfail == 1:\n msg += '--' + check_contributorsname_f1 + contributorsnameunqfailList[:-1]\n\n if contributorsnameformatfail == 1:\n msg += '--' + check_contributorsname_f2 + contributorsnameformatfailList[:-1]\n self.warnings.append(msg)\n\n msg = check_orcid\n if orcidformatfail == 0:\n self.passes.append(msg)\n else:\n msg += '--' + check_orcid_f + orcidformatfailList[:-1]\n self.fatal.append(msg)\n\n msg = check_contributorrole\n if rolefail == 0:\n self.passes.append(msg)\n else:\n msg += '--' + check_contributorrole_f + rolefailList[:-1]\n self.fatal.append(msg)\n\n msg = check_contactperson\n if contactpersonformatfail == 0 and contactpersonfail == 0:\n self.passes.append(msg)\n else:\n if contactpersonformatfail == 1:\n msg += '--' + check_contactperson_f1 + contactpersonformatfailList[:-1]\n if contactpersonfail == 1:\n msg += '--' + check_contactperson_f2\n self.fatal.append(msg)\n\n msg = check_fundingsource\n if fundingsourcefail == 0:\n self.passes.append(msg)\n else:\n msg += '--' + check_fundingsource_f + fundingsourcefailList[:-1]\n self.warnings.append(msg)\n\n msg = check_links\n if linksnumfail == 0:\n self.passes.append(msg)\n else:\n msg += '--' + check_links_f + linksnumfailList[:-1]\n self.fatal.append(msg)\n\n msg = check_articles\n if articleformatfail == 0:\n self.passes.append(msg)\n else:\n msg += '--' + check_articles_f + articleformatfailList[:-1]\n self.fatal.append(msg)\n\n msg = check_protocols\n if protocolformatfail == 0:\n self.passes.append(msg)\n else:\n msg += '--' + check_protocols_f + protocolformatfailList[:-1]\n self.fatal.append(msg)\n\n msg = check_numsubjects\n if numsubjectsformatfail == 0:\n self.passes.append(msg)\n else:\n msg += '--' + check_numsubjects_f\n self.fatal.append(msg)\n\n msg = check_numsamples\n if numsamplesformatfail == 0:\n self.passes.append(msg)\n else:\n msg += '--' + check_numsamples_f\n self.fatal.append(msg)\n\n msg = check_completness\n if completenessformatfail == 0:\n self.passes.append(msg)\n else:\n msg += '--' + check_completness_f\n self.fatal.append(msg)\n\n msg = check_parentID\n if parentidvaluefail == 0 and parentidformatfail == 0:\n self.passes.append(msg)\n else:\n if parentidvaluefail == 1:\n msg += '--' + check_parentID_f1 + parentidvaluefailList[:-1]\n if parentidformatfail == 1:\n msg += '--' + check_parentID_f2 + parentidformatfailList[:-1]\n self.fatal.append(msg)\n\n msg = check_metadatav\n if metadataversionfail == 0:\n self.passes.append(msg)\n else:\n msg += '--' + check_metadatav_f\n self.fatal.append(msg)\n\n\ndef cleanDataFrame(df):\n #Replace nan and empty first row cells by \"Empty.n\"\n empty_count = 0\n for column in list(df):\n element = df[column].iloc[0]\n if type(element) == str:\n if not element.strip():\n df[column].iloc[0] = \"Empty.\" + str(empty_count)\n empty_count += 1\n elif np.isnan(df[column].iloc[0]):\n df[column].iloc[0] = \"Empty.\" + str(empty_count)\n empty_count += 1\n\n #Change all empty and nan cells to \"empty\" to handle them more easily\n for rownum in df.index.values[1:]:\n element = df[column].iloc[rownum]\n if type(element) == str:\n if not element.strip():\n df[column].iloc[rownum] = \"empty\"\n elif np.isnan(df[column].iloc[rownum]):\n df[column].iloc[rownum] = \"empty\"\n\n #Trim last empty columns if imported (e.g. if user accidently include space)\n for header in list(df)[::-1]:\n if \"Empty.\" in df[header].iloc[0] and len(set(df[header].values[1:]))==1 and df[header].iloc[1]=='empty':\n df = df.drop(header, 1)\n else:\n break\n\n #Trim last empty rows if imported (e.g. if user accidently include space)\n for rownum in df.index.values[::-1]:\n if len(set(df.iloc[rownum].values))==1 and df[list(df)[0]].iloc[rownum] == 'empty':\n df = df.drop(rownum)\n else:\n break\n\n #Set first row as headers\n df = df.rename(columns=df.iloc[0], copy=False).iloc[1:].reset_index(drop=True)\n # df.to_excel('testfile.xlsx')\n return df\n\n######## Main validation functions called in pysoda #######################\ndef pathToJsonStruct(vPath): #create a jsonStruct convenient for SODA's workflow\n jsonvar = {}\n contentDataset = os.listdir(vPath)\n listPathFilesinDataset = []\n for i in range(len(contentDataset)):\n contentName = contentDataset[i]\n contentPath = os.path.join(vPath, contentName)\n if (os.path.isdir(contentPath)):\n filesInFolder = os.listdir(contentPath)\n listPathFilesinFolder = []\n for j in range(len(filesInFolder)):\n fileNameInFolder = filesInFolder[j]\n listPathFilesinFolder.append(os.path.join(contentPath, fileNameInFolder))\n jsonvar[contentName] = listPathFilesinFolder\n else:\n listPathFilesinDataset.append(contentPath)\n jsonvar['main'] = listPathFilesinDataset\n return jsonvar\n\ndef validate_high_level_folder_structure(jsonStruct):\n validator = DictValidator()\n\n # check the root folder for required and optional folders\n validator.check_high_level_folder_structure(jsonStruct)\n\n return(validator)\n\ndef validate_high_level_metadata_files(jsonStruct):\n validator = DictValidator()\n\n # check the root folder for required metadata files\n isSubmission, isDatasetDescription, isSubjects, isSamples = validator.check_high_level_metadata_files(jsonStruct)\n\n return(validator, isSubmission, isDatasetDescription, isSubjects, isSamples)\n\ndef validate_sub_level_organization(jsonStruct):\n validator = DictValidator()\n\n #check sub level structure for empty folders\n validator.check_empty_folders(jsonStruct)\n\n #check sub level structure for empty files\n validator.check_empty_files(jsonStruct)\n\n #check sub level structure for DS.STORE\n validator.check_ds_store(jsonStruct)\n\n #check sub level structure for DS.STORE\n mnf_style = validator.check_manifest_file_included(jsonStruct)\n\n return(validator)\n\ndef validate_submission_file(submFilePath):\n validator = DictValidator()\n\n #check sub level structure for empty folders\n validator.check_submission_file(submFilePath)\n\n return(validator)\n\n\ndef validate_dataset_description_file(ddFilePath):\n validator = DictValidator()\n\n #check sub level structure for empty folders\n validator.check_dataset_description_file(ddFilePath)\n\n return(validator)\n" ]
[ [ "pandas.read_excel", "pandas.read_csv", "numpy.unique", "numpy.isnan", "numpy.argwhere" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "2.0", "1.4", "1.3", "1.1", "1.5", "1.2" ], "scipy": [], "tensorflow": [] } ]
zsz00/Graphormer
[ "838f239a41dfd861b483cefa824e2dd57ae6ab1a" ]
[ "graphormer/pretrain/__init__.py" ]
[ "from torch.hub import load_state_dict_from_url\nimport torch.distributed as dist\n\nPRETRAINED_MODEL_URLS = {\n \"pcqm4mv1_graphormer_base\": \"https://szheng.blob.core.windows.net/graphormer/modelzoo/pcqm4mv1/checkpoint_best_pcqm4mv1_full.pt\",\n \"pcqm4mv2_graphormer_base\": \"https://szheng.blob.core.windows.net/graphormer/modelzoo/pcqm4mv2/checkpoint_best_pcqm4mv2_full.pt\",\n}\n\n\ndef load_pretrained_model(pretrained_model_name):\n if pretrained_model_name not in PRETRAINED_MODEL_URLS:\n raise ValueError(\"Unknown pretrained model name %s\", pretrained_model_name)\n if not dist.is_initialized():\n return load_state_dict_from_url(PRETRAINED_MODEL_URLS[pretrained_model_name], progress=True)[\"model\"]\n else:\n pretrained_model = load_state_dict_from_url(PRETRAINED_MODEL_URLS[pretrained_model_name], progress=True,\n file_name=f\"{pretrained_model_name}_{dist.get_rank()}\")[\"model\"]\n dist.barrier()\n return pretrained_model\n" ]
[ [ "torch.distributed.get_rank", "torch.distributed.is_initialized", "torch.hub.load_state_dict_from_url", "torch.distributed.barrier" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
kyuhyoung/PINTO_model_zoo
[ "c3759b9a6ef35704daba1964ee75db979cf8e118", "c3759b9a6ef35704daba1964ee75db979cf8e118" ]
[ "07_mobilenetv2-poseestimation/01_float32/02_weight_quantization.py", "07_mobilenetv2-poseestimation/01_float32/01_freeze_the_saved_model_v1.py" ]
[ "import tensorflow as tf\n\ntf.compat.v1.enable_eager_execution()\n\n# Weight Quantization - Input/Output=float32\nconverter = tf.lite.TFLiteConverter.from_saved_model('./saved_model')\nconverter.optimizations = [tf.lite.Optimize.OPTIMIZE_FOR_SIZE]\ntflite_quant_model = converter.convert()\nwith open('./mobilenet_v2_pose_368_432_weight_quant.tflite', 'wb') as w:\n w.write(tflite_quant_model)\nprint(\"Weight Quantization complete! - mobilenet_v2_pose_368_432_weight_quant.tflite\")\n\n", "import tensorflow as tf\nimport os\nimport shutil\nfrom tensorflow.python.saved_model import tag_constants\nfrom tensorflow.python import ops\n\ndef get_graph_def_from_file(graph_filepath):\n tf.compat.v1.reset_default_graph()\n with ops.Graph().as_default():\n with tf.compat.v1.gfile.GFile(graph_filepath, 'rb') as f:\n graph_def = tf.compat.v1.GraphDef()\n graph_def.ParseFromString(f.read())\n return graph_def\n\ndef convert_graph_def_to_saved_model(export_dir, graph_filepath, input_name, outputs):\n graph_def = get_graph_def_from_file(graph_filepath)\n with tf.compat.v1.Session(graph=tf.Graph()) as session:\n tf.import_graph_def(graph_def, name='')\n tf.compat.v1.saved_model.simple_save(\n session,\n export_dir,# change input_image to node.name if you know the name\n inputs={input_name: session.graph.get_tensor_by_name('{}:0'.format(node.name))\n for node in graph_def.node if node.op=='Placeholder'},\n outputs={t.rstrip(\":0\"):session.graph.get_tensor_by_name(t) for t in outputs}\n )\n print('Optimized graph converted to SavedModel!')\n\ntf.compat.v1.enable_eager_execution()\n\n# convert this to a TF Serving compatible mode\nshutil.rmtree('./saved_model', ignore_errors=True)\nconvert_graph_def_to_saved_model('./saved_model', './frozen-model.pb', 'image', ['Openpose/concat_stage7:0'])\n" ]
[ [ "tensorflow.lite.TFLiteConverter.from_saved_model", "tensorflow.compat.v1.enable_eager_execution" ], [ "tensorflow.Graph", "tensorflow.import_graph_def", "tensorflow.compat.v1.enable_eager_execution", "tensorflow.compat.v1.GraphDef", "tensorflow.compat.v1.gfile.GFile", "tensorflow.python.ops.Graph", "tensorflow.compat.v1.reset_default_graph" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
koliaok/RNN_javaSourceCodeLearningModel
[ "35d072eea65f605e2208da2a534a4b2bc4d955d4" ]
[ "train.py" ]
[ "from __future__ import print_function\nimport tensorflow as tf\n\nimport argparse\nimport time\nimport os\nfrom six.moves import cPickle\n\nfrom utils import TextLoader\nfrom model import Model\n\n\nimport csv\nimport itertools\nimport operator\nimport numpy as np\nimport math as math\nimport sys\nimport os\nimport time\nimport tensorflow as tf\n\n\ndef main():\n parser = argparse.ArgumentParser(\n formatter_class=argparse.ArgumentDefaultsHelpFormatter)#포맷지\n parser.add_argument('--data_dir', type=str, default='data/tinyshakespeare', ## 데이터 저장 장소\n help='data directory containing input.txt')\n parser.add_argument('--save_dir', type=str, default='save',\n help='directory to store checkpointed models') ##모델 저장소\n parser.add_argument('--log_dir', type=str, default='logs', ## log데이터 저장소\n help='directory to store tensorboard logs')\n parser.add_argument('--rnn_size', type=int, default=128,## RNN hidden 사이즈 DF = 128\n help='size of RNN hidden state')\n parser.add_argument('--num_layers', type=int, default=10, ## RNN Layers 지정 DF =2\n help='number of layers in the RNN')\n parser.add_argument('--model', type=str, default='lstm', ## RNN model 정의\n help='rnn, gru, lstm, or nas')\n parser.add_argument('--batch_size', type=int, default=50, ## batch_size 지정\n help='minibatch size')\n parser.add_argument('--seq_length', type=int, default=50, ## 문자열 길이 지정\n help='RNN sequence length')\n parser.add_argument('--num_epochs', type=int, default=100, ## epochs Number 지정\n help='number of epochs')\n parser.add_argument('--save_every', type=int, default=1000, ## 결과 저장??\n help='save frequency')\n parser.add_argument('--grad_clip', type=float, default=5., ## gradient를 깎는 정도 ??\n help='clip gradients at this value')\n parser.add_argument('--learning_rate', type=float, default=0.002,## learning rate 지정\n help='learning rate')\n parser.add_argument('--decay_rate', type=float, default=0.97, ##부패되는 정\n help='decay rate for rmsprop')\n parser.add_argument('--output_keep_prob', type=float, default=0.7, ## keeping weight output 확률\n help='probability of keeping weights in the hidden layer')\n parser.add_argument('--input_keep_prob', type=float, default=0.7, ## keeping weight input 확률\n help='probability of keeping weights in the input layer')\n parser.add_argument('--init_from', type=str, default=None, ##초기화 -> pkl 파일형 파이썬 객체를 저장하고, 읽어 들ㅇ\n help=\"\"\"continue training from saved model at this path. Path must contain files saved by previous training process:\n 'config.pkl' : configuration; \n 'chars_vocab.pkl' : vocabulary definitions;\n 'checkpoint' : paths to model file(s) (created by tf).\n Note: this file contains absolute paths, be careful when moving files around;\n 'model.ckpt-*' : file(s) with model definition (created by tf)\n \"\"\")\n args = parser.parse_args()\n train(args)\n\n\ndef train(args):\n\n data_loader = TextLoader(args.data_dir, args.batch_size, args.seq_length)## data Proprocessing 하는 부분 -> utils.py(TextLoader Class)\n args.vocab_size = data_loader.vocab_size\n\n # check compatibility if training is continued from previously saved model\n if args.init_from is not None:\n # check if all necessary files exist\n assert os.path.isdir(args.init_from),\" %s must be a a path\" % args.init_from\n assert os.path.isfile(os.path.join(args.init_from,\"config.pkl\")),\"config.pkl file does not exist in path %s\"%args.init_from\n assert os.path.isfile(os.path.join(args.init_from,\"chars_vocab.pkl\")),\"chars_vocab.pkl.pkl file does not exist in path %s\" % args.init_from\n ckpt = tf.train.get_checkpoint_state(args.init_from)\n assert ckpt, \"No checkpoint found\"\n assert ckpt.model_checkpoint_path, \"No model path found in checkpoint\"\n\n # open old config and check if models are compatible\n with open(os.path.join(args.init_from, 'config.pkl'), 'rb') as f: ##init_from이 설정이 안되어 있을 경우\n saved_model_args = cPickle.load(f)\n need_be_same = [\"model\", \"rnn_size\", \"num_layers\", \"seq_length\"]\n for checkme in need_be_same:\n assert vars(saved_model_args)[checkme]==vars(args)[checkme],\"Command line argument and saved model disagree on '%s' \"%checkme\n\n # open saved vocab/dict and check if vocabs/dicts are compatible\n with open(os.path.join(args.init_from, 'chars_vocab.pkl'), 'rb') as f:\n saved_chars, saved_vocab = cPickle.load(f)\n assert saved_chars==data_loader.chars, \"Data and loaded model disagree on character set!\"\n assert saved_vocab==data_loader.vocab, \"Data and loaded model disagree on dictionary mappings!\"\n\n if not os.path.isdir(args.save_dir):\n os.makedirs(args.save_dir)\n with open(os.path.join(args.save_dir, 'config.pkl'), 'wb') as f:\n cPickle.dump(args, f)\n with open(os.path.join(args.save_dir, 'chars_vocab.pkl'), 'wb') as f:\n cPickle.dump((data_loader.chars, data_loader.vocab), f)\n\n model = Model(args)#--> model.py 에 model class로 진입 RNN의 모델링 과정을 Process\n\n with tf.Session() as sess:\n # instrument for tensorboard\n summaries = tf.summary.merge_all()\n writer = tf.summary.FileWriter(\n os.path.join(args.log_dir, time.strftime(\"%Y-%m-%d-%H-%M-%S\")))\n writer.add_graph(sess.graph)\n\n sess.run(tf.global_variables_initializer()) ## TF 초기화\n saver = tf.train.Saver(tf.global_variables())## TF.variables() 저장\n # restore model\n if args.init_from is not None:\n saver.restore(sess, ckpt.model_checkpoint_path)\n for e in range(args.num_epochs):\n sess.run(tf.assign(model.lr,\n args.learning_rate * (args.decay_rate ** e)))\n data_loader.reset_batch_pointer()\n state = sess.run(model.initial_state)##0으로 초기화된 Shape(50,128)\n\n for b in range(data_loader.num_batches): #0~ 446번을 돈다\n start = time.time()\n x, y = data_loader.next_batch()\n feed = {model.input_data: x, model.targets: y} ## x,y shape(50,50)\n for i, (c, h) in enumerate(model.initial_state): ## 초기 스테이트 값과 feed 의 x, y를 받는다\n feed[c] = state[i].c\n feed[h] = state[i].h\n train_loss, state, _ = sess.run([model.cost, model.final_state, model.train_op], feed)\n\n # instrument for tensorboard\n summ, train_loss, state, _ = sess.run([summaries, model.cost, model.final_state, model.train_op], feed)\n writer.add_summary(summ, e * data_loader.num_batches + b)\n\n end = time.time()\n print(\"{}/{} (epoch {}), train_loss = {:.3f}, time/batch = {:.3f}\"\n .format(e * data_loader.num_batches + b,\n args.num_epochs * data_loader.num_batches,\n e, train_loss, end - start))\n if (e * data_loader.num_batches + b) % args.save_every == 0\\\n or (e == args.num_epochs-1 and\n b == data_loader.num_batches-1):\n # save for the last result\n checkpoint_path = os.path.join(args.save_dir, 'model.ckpt')\n saver.save(sess, checkpoint_path,\n global_step=e * data_loader.num_batches + b)\n print(\"model saved to {}\".format(checkpoint_path))\n\n\nif __name__ == '__main__':\n main()\n" ]
[ [ "tensorflow.train.get_checkpoint_state", "tensorflow.global_variables", "tensorflow.assign", "tensorflow.global_variables_initializer", "tensorflow.summary.merge_all", "tensorflow.Session" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.10" ] } ]
haijohn/mars
[ "2805241ac55b50c4f6319baa41113fbf8c723832", "2805241ac55b50c4f6319baa41113fbf8c723832", "2805241ac55b50c4f6319baa41113fbf8c723832", "2805241ac55b50c4f6319baa41113fbf8c723832", "2805241ac55b50c4f6319baa41113fbf8c723832", "2805241ac55b50c4f6319baa41113fbf8c723832" ]
[ "mars/tensor/random/randn.py", "mars/tensor/fft/irfft2.py", "mars/dataframe/tests/test_initializer.py", "mars/dataframe/groupby/tests/test_groupby_execution.py", "mars/tests/core.py", "mars/learn/datasets/tests/test_samples_generator.py" ]
[ "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# Copyright 1999-2020 Alibaba Group Holding Ltd.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport numpy as np\n\nfrom ... import opcodes as OperandDef\nfrom ..utils import gen_random_seeds\nfrom .core import TensorRandomOperandMixin, TensorSimpleRandomData\n\n\nclass TensorRandn(TensorSimpleRandomData, TensorRandomOperandMixin):\n _op_type_ = OperandDef.RAND_RANDN\n _func_name = 'randn'\n\n def __init__(self, size=None, dtype=None, **kw):\n dtype = np.dtype(dtype) if dtype is not None else dtype\n super().__init__(_size=size, dtype=dtype, **kw)\n\n def __call__(self, chunk_size=None):\n return self.new_tensor(None, None, raw_chunk_size=chunk_size)\n\n\ndef randn(random_state, *dn, **kw):\n r\"\"\"\n Return a sample (or samples) from the \"standard normal\" distribution.\n\n If positive, int_like or int-convertible arguments are provided,\n `randn` generates an array of shape ``(d0, d1, ..., dn)``, filled\n with random floats sampled from a univariate \"normal\" (Gaussian)\n distribution of mean 0 and variance 1 (if any of the :math:`d_i` are\n floats, they are first converted to integers by truncation). A single\n float randomly sampled from the distribution is returned if no\n argument is provided.\n\n This is a convenience function. If you want an interface that takes a\n tuple as the first argument, use `numpy.random.standard_normal` instead.\n\n Parameters\n ----------\n d0, d1, ..., dn : int, optional\n The dimensions of the returned tensor, should be all positive.\n If no argument is given a single Python float is returned.\n\n Returns\n -------\n Z : Tensor or float\n A ``(d0, d1, ..., dn)``-shaped array of floating-point samples from\n the standard normal distribution, or a single such float if\n no parameters were supplied.\n\n See Also\n --------\n random.standard_normal : Similar, but takes a tuple as its argument.\n\n Notes\n -----\n For random samples from :math:`N(\\mu, \\sigma^2)`, use:\n\n ``sigma * mt.random.randn(...) + mu``\n\n Examples\n --------\n >>> import mars.tensor as mt\n\n >>> mt.random.randn().execute()\n 2.1923875335537315 #random\n\n Two-by-four tensor of samples from N(3, 6.25):\n\n >>> (2.5 * mt.random.randn(2, 4) + 3).execute()\n array([[-4.49401501, 4.00950034, -1.81814867, 7.29718677], #random\n [ 0.39924804, 4.68456316, 4.99394529, 4.84057254]]) #random\n \"\"\"\n if len(dn) == 1 and isinstance(dn[0], (tuple, list)):\n raise TypeError(\"'tuple' object cannot be interpreted as an integer\")\n if 'dtype' not in kw:\n kw['dtype'] = np.dtype('f8')\n chunk_size = kw.pop('chunk_size', None)\n\n seed = gen_random_seeds(1, random_state.to_numpy())[0]\n op = TensorRandn(seed=seed, size=dn, **kw)\n\n for key in op.extra_params:\n if not key.startswith('_'):\n raise ValueError(f'randn got unexpected key arguments {key}')\n\n return op(chunk_size=chunk_size)\n", "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# Copyright 1999-2020 Alibaba Group Holding Ltd.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport numpy as np\n\nfrom ... import opcodes as OperandDef\nfrom ..datasource import tensor as astensor\nfrom .core import TensorRealIFFTNMixin, validate_fftn, TensorRealFFTN\n\n\nclass TensorIRFFT2(TensorRealFFTN, TensorRealIFFTNMixin):\n _op_type_ = OperandDef.IRFFT2\n\n def __init__(self, shape=None, axes=None, norm=None, **kw):\n super().__init__(_shape=shape, _axes=axes, _norm=norm, **kw)\n\n\ndef irfft2(a, s=None, axes=(-2, -1), norm=None):\n \"\"\"\n Compute the 2-dimensional inverse FFT of a real array.\n\n Parameters\n ----------\n a : array_like\n The input tensor\n s : sequence of ints, optional\n Shape of the inverse FFT.\n axes : sequence of ints, optional\n The axes over which to compute the inverse fft.\n Default is the last two axes.\n norm : {None, \"ortho\"}, optional\n Normalization mode (see `mt.fft`). Default is None.\n\n Returns\n -------\n out : Tensor\n The result of the inverse real 2-D FFT.\n\n See Also\n --------\n irfftn : Compute the inverse of the N-dimensional FFT of real input.\n\n Notes\n -----\n This is really `irfftn` with different defaults.\n For more details see `irfftn`.\n\n \"\"\"\n if len(axes) != 2:\n raise ValueError(\"axes length should be 2\")\n a = astensor(a)\n axes = validate_fftn(a, s=s, axes=axes, norm=norm)\n op = TensorIRFFT2(shape=s, axes=axes, norm=norm, dtype=np.dtype(np.float_))\n return op(a)\n", "# Copyright 1999-2020 Alibaba Group Holding Ltd.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport numpy as np\nimport pandas as pd\n\nimport mars.dataframe as md\nimport mars.tensor as mt\nfrom mars.tests import setup\n\n\nsetup = setup\n\n \ndef test_dataframe_initializer(setup):\n # from tensor\n raw = np.random.rand(100, 10)\n tensor = mt.tensor(raw, chunk_size=7)\n r = md.DataFrame(tensor)\n result = r.execute().fetch()\n pd.testing.assert_frame_equal(result, pd.DataFrame(raw))\n\n r = md.DataFrame(tensor, chunk_size=13)\n result = r.execute().fetch()\n pd.testing.assert_frame_equal(result, pd.DataFrame(raw))\n\n # from Mars dataframe\n raw = pd.DataFrame(np.random.rand(100, 10), columns=list('ABCDEFGHIJ'))\n df = md.DataFrame(raw, chunk_size=15) * 2\n r = md.DataFrame(df, num_partitions=11)\n result = r.execute().fetch()\n pd.testing.assert_frame_equal(result, raw * 2)\n\n # from tileable dict\n raw_dict = {\n 'C': np.random.choice(['u', 'v', 'w'], size=(100,)),\n 'A': pd.Series(np.random.rand(100)),\n 'B': np.random.randint(0, 10, size=(100,)),\n }\n m_dict = raw_dict.copy()\n m_dict['A'] = md.Series(m_dict['A'])\n m_dict['B'] = mt.tensor(m_dict['B'])\n r = md.DataFrame(m_dict, columns=list('ABC'))\n result = r.execute().fetch()\n pd.testing.assert_frame_equal(result, pd.DataFrame(raw_dict, columns=list('ABC')))\n\n # from tileable list\n raw_list = [\n np.random.choice(['u', 'v', 'w'], size=(3,)),\n pd.Series(np.random.rand(3)),\n np.random.randint(0, 10, size=(3,))\n ]\n m_list = raw_list.copy()\n m_list[1] = md.Series(m_list[1])\n m_list[2] = mt.tensor(m_list[2])\n r = md.DataFrame(m_list, columns=list('ABC'))\n result = r.execute(extra_config={'check_dtypes': False}).fetch()\n pd.testing.assert_frame_equal(result, pd.DataFrame(raw_list, columns=list('ABC')))\n\n # from raw pandas initializer\n raw = pd.DataFrame(np.random.rand(100, 10), columns=list('ABCDEFGHIJ'))\n r = md.DataFrame(raw, num_partitions=10)\n result = r.execute().fetch()\n pd.testing.assert_frame_equal(result, raw)\n\n # from mars series\n raw_s = np.random.rand(100)\n s = md.Series(raw_s, chunk_size=20)\n r = md.DataFrame(s, num_partitions=10)\n result = r.execute().fetch()\n pd.testing.assert_frame_equal(result, pd.DataFrame(raw_s))\n\n # test check instance\n r = r * 2\n assert isinstance(r, md.DataFrame)\n\n\ndef test_series_initializer(setup):\n # from tensor\n raw = np.random.rand(100)\n tensor = mt.tensor(raw, chunk_size=7)\n r = md.Series(tensor)\n result = r.execute().fetch()\n pd.testing.assert_series_equal(result, pd.Series(raw))\n\n r = md.Series(tensor, chunk_size=13)\n result = r.execute().fetch()\n pd.testing.assert_series_equal(result, pd.Series(raw))\n\n # from index\n raw = np.arange(100)\n np.random.shuffle(raw)\n raw = pd.Index(raw, name='idx_name')\n idx = md.Index(raw, chunk_size=7)\n r = md.Series(idx)\n result = r.execute().fetch()\n pd.testing.assert_series_equal(result, pd.Series(raw))\n\n # from Mars series\n raw = pd.Series(np.random.rand(100), name='series_name')\n ms = md.Series(raw, chunk_size=15) * 2\n r = md.Series(ms, num_partitions=11)\n result = r.execute().fetch()\n pd.testing.assert_series_equal(result, raw * 2)\n\n # from raw pandas initializer\n raw = pd.Series(np.random.rand(100), name='series_name')\n r = md.Series(raw, num_partitions=10)\n result = r.execute().fetch()\n pd.testing.assert_series_equal(result, raw)\n\n # test check instance\n r = r * 2\n assert isinstance(r, md.Series)\n\n\ndef test_index_initializer(setup):\n # from tensor\n raw = np.arange(100)\n np.random.shuffle(raw)\n tensor = mt.tensor(raw)\n r = md.Index(tensor, chunk_size=7)\n result = r.execute().fetch()\n pd.testing.assert_index_equal(result, pd.Index(raw))\n\n # from Mars index\n raw = np.arange(100)\n np.random.shuffle(raw)\n idx = md.Index(raw, chunk_size=7)\n r = md.Index(idx, num_partitions=11)\n result = r.execute().fetch()\n pd.testing.assert_index_equal(result, pd.Index(raw))\n\n # from pandas initializer\n raw = np.arange(100)\n np.random.shuffle(raw)\n raw_ser = pd.Series(raw, name='series_name')\n r = md.Index(raw_ser, chunk_size=7)\n result = r.execute().fetch()\n pd.testing.assert_index_equal(result, pd.Index(raw_ser))\n\n raw_idx = pd.Index(raw, name='idx_name')\n r = md.Index(raw_idx, num_partitions=10)\n result = r.execute().fetch()\n pd.testing.assert_index_equal(result, pd.Index(raw_idx))\n", "# Copyright 1999-2020 Alibaba Group Holding Ltd.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom collections import OrderedDict\n\nimport numpy as np\nimport pandas as pd\nimport pytest\n\ntry:\n import pyarrow as pa\nexcept ImportError: # pragma: no cover\n pa = None\n\nimport mars.dataframe as md\nfrom mars.tests import setup\nfrom mars.tests.core import assert_groupby_equal, require_cudf\nfrom mars.utils import arrow_array_to_objects\n\n\nsetup = setup\n\n\nclass MockReduction1(md.CustomReduction):\n def agg(self, v1):\n return v1.sum()\n\n\nclass MockReduction2(md.CustomReduction):\n def pre(self, value):\n return value + 1, value * 2\n\n def agg(self, v1, v2):\n return v1.sum(), v2.min()\n\n def post(self, v1, v2):\n return v1 + v2\n\n\ndef test_groupby(setup):\n rs = np.random.RandomState(0)\n data_size = 100\n data_dict = {'a': rs.randint(0, 10, size=(data_size,)),\n 'b': rs.randint(0, 10, size=(data_size,)),\n 'c': rs.choice(list('abcd'), size=(data_size,))}\n\n df1 = pd.DataFrame(data_dict)\n mdf = md.DataFrame(df1, chunk_size=13)\n grouped = mdf.groupby('b')\n assert_groupby_equal(grouped.execute().fetch(),\n df1.groupby('b'))\n\n df2 = pd.DataFrame(data_dict, index=['i' + str(i) for i in range(data_size)])\n mdf = md.DataFrame(df2, chunk_size=13)\n grouped = mdf.groupby('b')\n assert_groupby_equal(grouped.execute().fetch(),\n df2.groupby('b'))\n\n # test groupby series\n grouped = mdf.groupby(mdf['b'])\n assert_groupby_equal(grouped.execute().fetch(),\n df2.groupby(df2['b']))\n\n # test groupby multiple series\n grouped = mdf.groupby(by=[mdf['b'], mdf['c']])\n assert_groupby_equal(grouped.execute().fetch(),\n df2.groupby(by=[df2['b'], df2['c']]))\n\n df3 = pd.DataFrame(data_dict,\n index=pd.MultiIndex.from_tuples(\n [(i % 3, 'i' + str(i)) for i in range(data_size)]))\n mdf = md.DataFrame(df3, chunk_size=13)\n grouped = mdf.groupby(level=0)\n assert_groupby_equal(grouped.execute().fetch(),\n df3.groupby(level=0))\n\n # test groupby with integer columns\n df4 = pd.DataFrame(list(data_dict.values())).T\n mdf = md.DataFrame(df4, chunk_size=13)\n grouped = mdf.groupby(0)\n assert_groupby_equal(grouped.execute().fetch(),\n df4.groupby(0))\n\n series1 = pd.Series(data_dict['a'])\n ms1 = md.Series(series1, chunk_size=13)\n grouped = ms1.groupby(lambda x: x % 3)\n assert_groupby_equal(grouped.execute().fetch(),\n series1.groupby(lambda x: x % 3))\n\n # test groupby series\n grouped = ms1.groupby(ms1)\n assert_groupby_equal(grouped.execute().fetch(),\n series1.groupby(series1))\n\n series2 = pd.Series(data_dict['a'],\n index=['i' + str(i) for i in range(data_size)])\n ms2 = md.Series(series2, chunk_size=13)\n grouped = ms2.groupby(lambda x: int(x[1:]) % 3)\n assert_groupby_equal(grouped.execute().fetch(),\n series2.groupby(lambda x: int(x[1:]) % 3))\n\n\ndef test_groupby_getitem(setup):\n rs = np.random.RandomState(0)\n data_size = 100\n raw = pd.DataFrame({'a': rs.randint(0, 10, size=(data_size,)),\n 'b': rs.randint(0, 10, size=(data_size,)),\n 'c': rs.choice(list('abcd'), size=(data_size,))},\n index=pd.MultiIndex.from_tuples([(i % 3, 'i' + str(i)) for i in range(data_size)]))\n mdf = md.DataFrame(raw, chunk_size=13)\n\n r = mdf.groupby(level=0)[['a', 'b']]\n assert_groupby_equal(r.execute().fetch(),\n raw.groupby(level=0)[['a', 'b']], with_selection=True)\n\n for method in ('tree', 'shuffle'):\n r = mdf.groupby(level=0)[['a', 'b']].sum(method=method)\n pd.testing.assert_frame_equal(r.execute().fetch().sort_index(),\n raw.groupby(level=0)[['a', 'b']].sum().sort_index())\n\n r = mdf.groupby(level=0)[['a', 'b']].apply(lambda x: x + 1)\n pd.testing.assert_frame_equal(r.execute().fetch().sort_index(),\n raw.groupby(level=0)[['a', 'b']].apply(lambda x: x + 1).sort_index())\n\n r = mdf.groupby('b')[['a', 'b']]\n assert_groupby_equal(r.execute().fetch(),\n raw.groupby('b')[['a', 'b']], with_selection=True)\n\n r = mdf.groupby('b')[['a', 'c']]\n assert_groupby_equal(r.execute().fetch(),\n raw.groupby('b')[['a', 'c']], with_selection=True)\n\n for method in ('tree', 'shuffle'):\n r = mdf.groupby('b')[['a', 'b']].sum(method=method)\n pd.testing.assert_frame_equal(r.execute().fetch().sort_index(),\n raw.groupby('b')[['a', 'b']].sum().sort_index())\n\n r = mdf.groupby('b')[['a', 'b']].agg(['sum', 'count'], method=method)\n pd.testing.assert_frame_equal(r.execute().fetch().sort_index(),\n raw.groupby('b')[['a', 'b']].agg(['sum', 'count']).sort_index())\n\n r = mdf.groupby('b')[['a', 'c']].agg(['sum', 'count'], method=method)\n pd.testing.assert_frame_equal(r.execute().fetch().sort_index(),\n raw.groupby('b')[['a', 'c']].agg(['sum', 'count']).sort_index())\n\n r = mdf.groupby('b')[['a', 'b']].apply(lambda x: x + 1)\n pd.testing.assert_frame_equal(r.execute().fetch().sort_index(),\n raw.groupby('b')[['a', 'b']].apply(lambda x: x + 1).sort_index())\n\n r = mdf.groupby('b')[['a', 'b']].transform(lambda x: x + 1)\n pd.testing.assert_frame_equal(r.execute().fetch().sort_index(),\n raw.groupby('b')[['a', 'b']].transform(lambda x: x + 1).sort_index())\n\n r = mdf.groupby('b')[['a', 'b']].cumsum()\n pd.testing.assert_frame_equal(r.execute().fetch().sort_index(),\n raw.groupby('b')[['a', 'b']].cumsum().sort_index())\n\n r = mdf.groupby('b').a\n assert_groupby_equal(r.execute().fetch(),\n raw.groupby('b').a, with_selection=True)\n\n for method in ('shuffle', 'tree'):\n r = mdf.groupby('b').a.sum(method=method)\n pd.testing.assert_series_equal(r.execute().fetch().sort_index(),\n raw.groupby('b').a.sum().sort_index())\n\n r = mdf.groupby('b').a.agg(['sum', 'mean', 'var'], method=method)\n pd.testing.assert_frame_equal(r.execute().fetch().sort_index(),\n raw.groupby('b').a.agg(['sum', 'mean', 'var']).sort_index())\n\n r = mdf.groupby('b', as_index=False).a.sum(method=method)\n pd.testing.assert_frame_equal(\n r.execute().fetch().sort_values('b', ignore_index=True),\n raw.groupby('b', as_index=False).a.sum().sort_values('b', ignore_index=True))\n\n r = mdf.groupby('b', as_index=False).b.count(method=method)\n pd.testing.assert_frame_equal(\n r.execute().fetch().sort_values('b', ignore_index=True),\n raw.groupby('b', as_index=False).b.count().sort_values('b', ignore_index=True))\n\n r = mdf.groupby('b', as_index=False).b.agg({'cnt': 'count'}, method=method)\n pd.testing.assert_frame_equal(\n r.execute().fetch().sort_values('b', ignore_index=True),\n raw.groupby('b', as_index=False).b.agg({'cnt': 'count'}).sort_values('b', ignore_index=True))\n\n r = mdf.groupby('b').a.apply(lambda x: x + 1)\n pd.testing.assert_series_equal(r.execute().fetch().sort_index(),\n raw.groupby('b').a.apply(lambda x: x + 1).sort_index())\n\n r = mdf.groupby('b').a.transform(lambda x: x + 1)\n pd.testing.assert_series_equal(r.execute().fetch().sort_index(),\n raw.groupby('b').a.transform(lambda x: x + 1).sort_index())\n\n r = mdf.groupby('b').a.cumsum()\n pd.testing.assert_series_equal(r.execute().fetch().sort_index(),\n raw.groupby('b').a.cumsum().sort_index())\n\n # special test for selection key == 0\n raw = pd.DataFrame(rs.rand(data_size, 10))\n raw[0] = 0\n mdf = md.DataFrame(raw, chunk_size=13)\n r = mdf.groupby(0, as_index=False)[0].agg({'cnt': 'count'})\n pd.testing.assert_frame_equal(r.execute().fetch().sort_index(),\n raw.groupby(0, as_index=False)[0].agg({'cnt': 'count'}))\n\n\ndef test_dataframe_groupby_agg(setup):\n agg_funs = ['std', 'mean', 'var', 'max', 'count', 'size', 'all', 'any', 'skew', 'kurt', 'sem']\n\n rs = np.random.RandomState(0)\n raw = pd.DataFrame({'c1': np.arange(100).astype(np.int64),\n 'c2': rs.choice(['a', 'b', 'c'], (100,)),\n 'c3': rs.rand(100)})\n mdf = md.DataFrame(raw, chunk_size=13)\n\n for method in ['tree', 'shuffle']:\n r = mdf.groupby('c2').agg('size', method=method)\n pd.testing.assert_series_equal(r.execute().fetch().sort_index(),\n raw.groupby('c2').agg('size').sort_index())\n\n for agg_fun in agg_funs:\n if agg_fun == 'size':\n continue\n r = mdf.groupby('c2').agg(agg_fun, method=method)\n pd.testing.assert_frame_equal(r.execute().fetch().sort_index(),\n raw.groupby('c2').agg(agg_fun).sort_index())\n\n r = mdf.groupby('c2').agg(agg_funs, method=method)\n pd.testing.assert_frame_equal(r.execute().fetch().sort_index(),\n raw.groupby('c2').agg(agg_funs).sort_index())\n\n agg = OrderedDict([('c1', ['min', 'mean']), ('c3', 'std')])\n r = mdf.groupby('c2').agg(agg, method=method)\n pd.testing.assert_frame_equal(r.execute().fetch().sort_index(),\n raw.groupby('c2').agg(agg).sort_index())\n\n agg = OrderedDict([('c1', 'min'), ('c3', 'sum')])\n r = mdf.groupby('c2').agg(agg, method=method)\n pd.testing.assert_frame_equal(r.execute().fetch().sort_index(),\n raw.groupby('c2').agg(agg).sort_index())\n\n r = mdf.groupby('c2').agg({'c1': 'min'}, method=method)\n pd.testing.assert_frame_equal(r.execute().fetch().sort_index(),\n raw.groupby('c2').agg({'c1': 'min'}).sort_index())\n\n # test groupby series\n r = mdf.groupby(mdf['c2']).sum(method=method)\n pd.testing.assert_frame_equal(r.execute().fetch().sort_index(),\n raw.groupby(raw['c2']).sum().sort_index())\n\n r = mdf.groupby('c2').size(method='tree')\n pd.testing.assert_series_equal(r.execute().fetch(),\n raw.groupby('c2').size())\n\n # test inserted kurt method\n r = mdf.groupby('c2').kurtosis(method='tree')\n pd.testing.assert_frame_equal(r.execute().fetch(),\n raw.groupby('c2').kurtosis())\n\n for agg_fun in agg_funs:\n if agg_fun == 'size' or callable(agg_fun):\n continue\n r = getattr(mdf.groupby('c2'), agg_fun)(method='tree')\n pd.testing.assert_frame_equal(r.execute().fetch(),\n getattr(raw.groupby('c2'), agg_fun)())\n\n for method in ['tree', 'shuffle']:\n # test as_index=False\n r = mdf.groupby('c2', as_index=False).agg('mean', method=method)\n pd.testing.assert_frame_equal(\n r.execute().fetch().sort_values('c2', ignore_index=True),\n raw.groupby('c2', as_index=False).agg('mean').sort_values('c2', ignore_index=True))\n assert r.op.groupby_params['as_index'] is False\n\n # test as_index=False takes no effect\n r = mdf.groupby(['c1', 'c2'], as_index=False).agg(['mean', 'count'], method='tree')\n pd.testing.assert_frame_equal(r.execute().fetch(),\n raw.groupby(['c1', 'c2'], as_index=False).agg(['mean', 'count']))\n assert r.op.groupby_params['as_index'] is True\n\n r = mdf.groupby('c2').agg(['cumsum', 'cumcount'], method='tree')\n pd.testing.assert_frame_equal(r.execute().fetch().sort_index(),\n raw.groupby('c2').agg(['cumsum', 'cumcount']).sort_index())\n\n r = mdf[['c1', 'c3']].groupby(mdf['c2']).agg(MockReduction2())\n pd.testing.assert_frame_equal(r.execute().fetch(),\n raw[['c1', 'c3']].groupby(raw['c2']).agg(MockReduction2()))\n\n r = mdf.groupby('c2').agg(sum_c1=md.NamedAgg('c1', 'sum'), min_c1=md.NamedAgg('c1', 'min'),\n mean_c3=md.NamedAgg('c3', 'mean'))\n pd.testing.assert_frame_equal(r.execute().fetch(),\n raw.groupby('c2').agg(sum_c1=md.NamedAgg('c1', 'sum'),\n min_c1=md.NamedAgg('c1', 'min'),\n mean_c3=md.NamedAgg('c3', 'mean')))\n\n\ndef test_series_groupby_agg(setup):\n rs = np.random.RandomState(0)\n series1 = pd.Series(rs.rand(10))\n ms1 = md.Series(series1, chunk_size=3)\n\n agg_funs = ['std', 'mean', 'var', 'max', 'count', 'size', 'all', 'any', 'skew', 'kurt', 'sem']\n\n for method in ['tree', 'shuffle']:\n for agg_fun in agg_funs:\n r = ms1.groupby(lambda x: x % 2).agg(agg_fun, method=method)\n pd.testing.assert_series_equal(r.execute().fetch(),\n series1.groupby(lambda x: x % 2).agg(agg_fun))\n\n r = ms1.groupby(lambda x: x % 2).agg(agg_funs, method=method)\n pd.testing.assert_frame_equal(r.execute().fetch(),\n series1.groupby(lambda x: x % 2).agg(agg_funs))\n\n # test groupby series\n r = ms1.groupby(ms1).sum(method=method)\n pd.testing.assert_series_equal(r.execute().fetch().sort_index(),\n series1.groupby(series1).sum().sort_index())\n\n r = ms1.groupby(ms1).sum(method=method)\n pd.testing.assert_series_equal(r.execute().fetch().sort_index(),\n series1.groupby(series1).sum().sort_index())\n\n # test inserted kurt method\n r = ms1.groupby(ms1).kurtosis()\n pd.testing.assert_series_equal(r.execute().fetch(),\n series1.groupby(series1).kurtosis())\n\n for agg_fun in agg_funs:\n r = getattr(ms1.groupby(lambda x: x % 2), agg_fun)(method='tree')\n pd.testing.assert_series_equal(r.execute().fetch(),\n getattr(series1.groupby(lambda x: x % 2), agg_fun)())\n\n r = ms1.groupby(lambda x: x % 2).agg(['cumsum', 'cumcount'], method='tree')\n pd.testing.assert_frame_equal(r.execute().fetch().sort_index(),\n series1.groupby(lambda x: x % 2).agg(['cumsum', 'cumcount']).sort_index())\n\n r = ms1.groupby(lambda x: x % 2).agg(MockReduction2(name='custom_r'))\n pd.testing.assert_series_equal(r.execute().fetch(),\n series1.groupby(lambda x: x % 2).agg(MockReduction2(name='custom_r')))\n\n r = ms1.groupby(lambda x: x % 2).agg(col_var='var', col_skew='skew')\n pd.testing.assert_frame_equal(r.execute().fetch(),\n series1.groupby(lambda x: x % 2).agg(col_var='var', col_skew='skew'))\n\n\ndef test_groupby_agg_str_cat(setup):\n agg_fun = lambda x: x.str.cat(sep='_', na_rep='NA')\n\n rs = np.random.RandomState(0)\n raw_df = pd.DataFrame({'a': rs.choice(['A', 'B', 'C'], size=(100,)),\n 'b': rs.choice([None, 'alfa', 'bravo', 'charlie'], size=(100,))})\n\n mdf = md.DataFrame(raw_df, chunk_size=13)\n\n r = mdf.groupby('a').agg(agg_fun)\n pd.testing.assert_frame_equal(r.execute().fetch(),\n raw_df.groupby('a').agg(agg_fun))\n\n raw_series = pd.Series(rs.choice([None, 'alfa', 'bravo', 'charlie'], size=(100,)))\n\n ms = md.Series(raw_series, chunk_size=13)\n\n r = ms.groupby(lambda x: x % 2).agg(agg_fun)\n pd.testing.assert_series_equal(r.execute().fetch(),\n raw_series.groupby(lambda x: x % 2).agg(agg_fun))\n\n\n@require_cudf\ndef test_gpu_groupby_agg(setup):\n rs = np.random.RandomState(0)\n df1 = pd.DataFrame({'a': rs.choice([2, 3, 4], size=(100,)),\n 'b': rs.choice([2, 3, 4], size=(100,))})\n mdf = md.DataFrame(df1, chunk_size=13).to_gpu()\n\n r = mdf.groupby('a').sum()\n pd.testing.assert_frame_equal(r.execute().fetch().to_pandas(),\n df1.groupby('a').sum())\n\n r = mdf.groupby('a').kurt()\n pd.testing.assert_frame_equal(r.execute().fetch().to_pandas(),\n df1.groupby('a').kurt())\n\n r = mdf.groupby('a').agg(['sum', 'var'])\n pd.testing.assert_frame_equal(r.execute().fetch().to_pandas(),\n df1.groupby('a').agg(['sum', 'var']))\n\n rs = np.random.RandomState(0)\n idx = pd.Index(np.where(rs.rand(10) > 0.5, 'A', 'B'))\n series1 = pd.Series(rs.rand(10), index=idx)\n ms = md.Series(series1, index=idx, chunk_size=3).to_gpu().to_gpu()\n\n r = ms.groupby(level=0).sum()\n pd.testing.assert_series_equal(r.execute().fetch().to_pandas(),\n series1.groupby(level=0).sum())\n\n r = ms.groupby(level=0).kurt()\n pd.testing.assert_series_equal(r.execute().fetch().to_pandas(),\n series1.groupby(level=0).kurt())\n\n r = ms.groupby(level=0).agg(['sum', 'var'])\n pd.testing.assert_frame_equal(r.execute().fetch().to_pandas(),\n series1.groupby(level=0).agg(['sum', 'var']))\n\n\ndef test_groupby_apply(setup):\n df1 = pd.DataFrame({'a': [3, 4, 5, 3, 5, 4, 1, 2, 3],\n 'b': [1, 3, 4, 5, 6, 5, 4, 4, 4],\n 'c': list('aabaaddce')})\n\n def apply_df(df, ret_series=False):\n df = df.sort_index()\n df.a += df.b\n if len(df.index) > 0:\n if not ret_series:\n df = df.iloc[:-1, :]\n else:\n df = df.iloc[-1, :]\n return df\n\n def apply_series(s, truncate=True):\n s = s.sort_index()\n if truncate and len(s.index) > 0:\n s = s.iloc[:-1]\n return s\n\n mdf = md.DataFrame(df1, chunk_size=3)\n\n applied = mdf.groupby('b').apply(lambda df: None)\n pd.testing.assert_frame_equal(applied.execute().fetch(),\n df1.groupby('b').apply(lambda df: None))\n\n applied = mdf.groupby('b').apply(apply_df)\n pd.testing.assert_frame_equal(applied.execute().fetch().sort_index(),\n df1.groupby('b').apply(apply_df).sort_index())\n\n applied = mdf.groupby('b').apply(apply_df, ret_series=True)\n pd.testing.assert_frame_equal(applied.execute().fetch().sort_index(),\n df1.groupby('b').apply(apply_df, ret_series=True).sort_index())\n\n applied = mdf.groupby('b').apply(lambda df: df.a, output_type='series')\n pd.testing.assert_series_equal(applied.execute().fetch().sort_index(),\n df1.groupby('b').apply(lambda df: df.a).sort_index())\n\n applied = mdf.groupby('b').apply(lambda df: df.a.sum())\n pd.testing.assert_series_equal(applied.execute().fetch().sort_index(),\n df1.groupby('b').apply(lambda df: df.a.sum()).sort_index())\n\n series1 = pd.Series([3, 4, 5, 3, 5, 4, 1, 2, 3])\n ms1 = md.Series(series1, chunk_size=3)\n\n applied = ms1.groupby(lambda x: x % 3).apply(lambda df: None)\n pd.testing.assert_series_equal(applied.execute().fetch(),\n series1.groupby(lambda x: x % 3).apply(lambda df: None))\n\n applied = ms1.groupby(lambda x: x % 3).apply(apply_series)\n pd.testing.assert_series_equal(applied.execute().fetch().sort_index(),\n series1.groupby(lambda x: x % 3).apply(apply_series).sort_index())\n\n sindex2 = pd.MultiIndex.from_arrays([list(range(9)), list('ABCDEFGHI')])\n series2 = pd.Series(list('CDECEDABC'), index=sindex2)\n ms2 = md.Series(series2, chunk_size=3)\n\n applied = ms2.groupby(lambda x: x[0] % 3).apply(apply_series)\n pd.testing.assert_series_equal(applied.execute().fetch().sort_index(),\n series2.groupby(lambda x: x[0] % 3).apply(apply_series).sort_index())\n\n\ndef test_groupby_transform(setup):\n df1 = pd.DataFrame({\n 'a': [3, 4, 5, 3, 5, 4, 1, 2, 3],\n 'b': [1, 3, 4, 5, 6, 5, 4, 4, 4],\n 'c': list('aabaaddce'),\n 'd': [3, 4, 5, 3, 5, 4, 1, 2, 3],\n 'e': [1, 3, 4, 5, 6, 5, 4, 4, 4],\n 'f': list('aabaaddce'),\n })\n\n def transform_series(s, truncate=True):\n s = s.sort_index()\n if truncate and len(s.index) > 1:\n s = s.iloc[:-1].reset_index(drop=True)\n return s\n\n mdf = md.DataFrame(df1, chunk_size=3)\n\n r = mdf.groupby('b').transform(transform_series, truncate=False)\n pd.testing.assert_frame_equal(r.execute().fetch().sort_index(),\n df1.groupby('b').transform(transform_series, truncate=False).sort_index())\n\n if pd.__version__ != '1.1.0':\n r = mdf.groupby('b').transform(['cummax', 'cumsum'], _call_agg=True)\n pd.testing.assert_frame_equal(r.execute().fetch().sort_index(),\n df1.groupby('b').agg(['cummax', 'cumsum']).sort_index())\n\n agg_list = ['cummax', 'cumsum']\n r = mdf.groupby('b').transform(agg_list, _call_agg=True)\n pd.testing.assert_frame_equal(r.execute().fetch().sort_index(),\n df1.groupby('b').agg(agg_list).sort_index())\n\n agg_dict = OrderedDict([('d', 'cummax'), ('b', 'cumsum')])\n r = mdf.groupby('b').transform(agg_dict, _call_agg=True)\n pd.testing.assert_frame_equal(r.execute().fetch().sort_index(),\n df1.groupby('b').agg(agg_dict).sort_index())\n\n agg_list = ['sum', lambda s: s.sum()]\n r = mdf.groupby('b').transform(agg_list, _call_agg=True)\n pd.testing.assert_frame_equal(r.execute().fetch().sort_index(),\n df1.groupby('b').agg(agg_list).sort_index())\n\n series1 = pd.Series([3, 4, 5, 3, 5, 4, 1, 2, 3])\n ms1 = md.Series(series1, chunk_size=3)\n\n r = ms1.groupby(lambda x: x % 3).transform(lambda x: x + 1)\n pd.testing.assert_series_equal(r.execute().fetch().sort_index(),\n series1.groupby(lambda x: x % 3).transform(lambda x: x + 1).sort_index())\n\n r = ms1.groupby(lambda x: x % 3).transform('cummax', _call_agg=True)\n pd.testing.assert_series_equal(r.execute().fetch().sort_index(),\n series1.groupby(lambda x: x % 3).agg('cummax').sort_index())\n\n agg_list = ['cummax', 'cumcount']\n r = ms1.groupby(lambda x: x % 3).transform(agg_list, _call_agg=True)\n pd.testing.assert_frame_equal(r.execute().fetch().sort_index(),\n series1.groupby(lambda x: x % 3).agg(agg_list).sort_index())\n\n\ndef test_groupby_cum(setup):\n df1 = pd.DataFrame({'a': [3, 5, 2, 7, 1, 2, 4, 6, 2, 4],\n 'b': [8, 3, 4, 1, 8, 2, 2, 2, 2, 3],\n 'c': [1, 8, 8, 5, 3, 5, 0, 0, 5, 4]})\n mdf = md.DataFrame(df1, chunk_size=3)\n\n for fun in ['cummin', 'cummax', 'cumprod', 'cumsum']:\n r1 = getattr(mdf.groupby('b'), fun)()\n pd.testing.assert_frame_equal(r1.execute().fetch().sort_index(),\n getattr(df1.groupby('b'), fun)().sort_index())\n\n r2 = getattr(mdf.groupby('b'), fun)(axis=1)\n pd.testing.assert_frame_equal(r2.execute().fetch().sort_index(),\n getattr(df1.groupby('b'), fun)(axis=1).sort_index())\n\n r3 = mdf.groupby('b').cumcount()\n pd.testing.assert_series_equal(r3.execute().fetch().sort_index(),\n df1.groupby('b').cumcount().sort_index())\n\n series1 = pd.Series([3, 4, 5, 3, 5, 4, 1, 2, 3])\n ms1 = md.Series(series1, chunk_size=3)\n\n for fun in ['cummin', 'cummax', 'cumprod', 'cumsum', 'cumcount']:\n r1 = getattr(ms1.groupby(lambda x: x % 2), fun)()\n pd.testing.assert_series_equal(r1.execute().fetch().sort_index(),\n getattr(series1.groupby(lambda x: x % 2), fun)().sort_index())\n\n\ndef test_groupby_head(setup):\n df1 = pd.DataFrame({'a': [3, 5, 2, 7, 1, 2, 4, 6, 2, 4],\n 'b': [8, 3, 4, 1, 8, 2, 2, 2, 2, 3],\n 'c': [1, 8, 8, 5, 3, 5, 0, 0, 5, 4],\n 'd': [9, 7, 6, 3, 6, 3, 2, 1, 5, 8]})\n # test single chunk\n mdf = md.DataFrame(df1)\n\n r = mdf.groupby('b').head(1)\n pd.testing.assert_frame_equal(r.execute().fetch().sort_index(),\n df1.groupby('b').head(1))\n r = mdf.groupby('b').head(-1)\n pd.testing.assert_frame_equal(r.execute().fetch().sort_index(),\n df1.groupby('b').head(-1))\n r = mdf.groupby('b')['a', 'c'].head(1)\n pd.testing.assert_frame_equal(r.execute().fetch().sort_index(),\n df1.groupby('b')['a', 'c'].head(1))\n\n # test multiple chunks\n mdf = md.DataFrame(df1, chunk_size=3)\n\n r = mdf.groupby('b').head(1)\n pd.testing.assert_frame_equal(r.execute().fetch().sort_index(),\n df1.groupby('b').head(1))\n\n # test head with selection\n r = mdf.groupby('b')['a', 'd'].head(1)\n pd.testing.assert_frame_equal(r.execute().fetch().sort_index(),\n df1.groupby('b')['a', 'd'].head(1))\n r = mdf.groupby('b')['c', 'a', 'd'].head(1)\n pd.testing.assert_frame_equal(r.execute().fetch().sort_index(),\n df1.groupby('b')['c', 'a', 'd'].head(1))\n r = mdf.groupby('b')['c'].head(1)\n pd.testing.assert_series_equal(r.execute().fetch().sort_index(),\n df1.groupby('b')['c'].head(1))\n\n # test single chunk\n series1 = pd.Series([3, 4, 5, 3, 5, 4, 1, 2, 3])\n ms = md.Series(series1)\n\n r = ms.groupby(lambda x: x % 2).head(1)\n pd.testing.assert_series_equal(r.execute().fetch().sort_index(),\n series1.groupby(lambda x: x % 2).head(1))\n r = ms.groupby(lambda x: x % 2).head(-1)\n pd.testing.assert_series_equal(r.execute().fetch().sort_index(),\n series1.groupby(lambda x: x % 2).head(-1))\n\n # test multiple chunk\n ms = md.Series(series1, chunk_size=3)\n\n r = ms.groupby(lambda x: x % 2).head(1)\n pd.testing.assert_series_equal(r.execute().fetch().sort_index(),\n series1.groupby(lambda x: x % 2).head(1))\n\n # test with special index\n series1 = pd.Series([3, 4, 5, 3, 5, 4, 1, 2, 3], index=[4, 1, 2, 3, 5, 8, 6, 7, 9])\n ms = md.Series(series1, chunk_size=3)\n\n r = ms.groupby(lambda x: x % 2).head(1)\n pd.testing.assert_series_equal(r.execute().fetch().sort_index(),\n series1.groupby(lambda x: x % 2).head(1).sort_index())\n\n\ndef test_groupby_sample(setup):\n rs = np.random.RandomState(0)\n sample_count = 10\n src_data_list = []\n for b in range(5):\n data_count = int(np.random.randint(20, 100))\n src_data_list.append(pd.DataFrame({\n 'a': np.random.randint(0, 100, size=data_count),\n 'b': np.array([b] * data_count),\n 'c': np.random.randint(0, 100, size=data_count),\n 'd': np.random.randint(0, 100, size=data_count),\n }))\n df1 = pd.concat(src_data_list)\n shuffle_idx = np.arange(len(df1))\n np.random.shuffle(shuffle_idx)\n df1 = df1.iloc[shuffle_idx].reset_index(drop=True)\n\n # test single chunk\n mdf = md.DataFrame(df1)\n\n r1 = mdf.groupby('b').sample(sample_count, random_state=rs)\n result1 = r1.execute().fetch()\n r2 = mdf.groupby('b').sample(sample_count, random_state=rs)\n result2 = r2.execute().fetch()\n pd.testing.assert_frame_equal(result1, result2)\n assert not (result1.groupby('b').count() - sample_count).any()[0]\n\n r1 = mdf.groupby('b').sample(sample_count, weights=df1['c'] / df1['c'].sum(), random_state=rs)\n result1 = r1.execute().fetch()\n r2 = mdf.groupby('b').sample(sample_count, weights=df1['c'] / df1['c'].sum(), random_state=rs)\n result2 = r2.execute().fetch()\n pd.testing.assert_frame_equal(result1, result2)\n assert not (result1.groupby('b').count() - sample_count).any()[0]\n\n r1 = mdf.groupby('b')[['b', 'c']].sample(sample_count, random_state=rs)\n result1 = r1.execute().fetch()\n r2 = mdf.groupby('b')[['b', 'c']].sample(sample_count, random_state=rs)\n result2 = r2.execute().fetch()\n pd.testing.assert_frame_equal(result1, result2)\n assert len(result1.columns) == 2\n assert not (result1.groupby('b').count() - sample_count).any()[0]\n\n r1 = mdf.groupby('b').c.sample(sample_count, random_state=rs)\n result1 = r1.execute().fetch()\n r2 = mdf.groupby('b').c.sample(sample_count, random_state=rs)\n result2 = r2.execute().fetch()\n pd.testing.assert_series_equal(result1, result2)\n\n r1 = mdf.groupby('b').c.sample(len(df1), random_state=rs)\n result1 = r1.execute().fetch()\n assert len(result1) == len(df1)\n\n with pytest.raises(ValueError):\n r1 = mdf.groupby('b').c.sample(len(df1), random_state=rs, errors='raises')\n r1.execute().fetch()\n\n # test multiple chunks\n mdf = md.DataFrame(df1, chunk_size=47)\n\n r1 = mdf.groupby('b').sample(sample_count, random_state=rs)\n result1 = r1.execute().fetch()\n r2 = mdf.groupby('b').sample(sample_count, random_state=rs)\n result2 = r2.execute().fetch()\n pd.testing.assert_frame_equal(result1, result2)\n assert not (result1.groupby('b').count() - sample_count).any()[0]\n\n r1 = mdf.groupby('b').sample(sample_count, weights=df1['c'] / df1['c'].sum(), random_state=rs)\n result1 = r1.execute().fetch()\n r2 = mdf.groupby('b').sample(sample_count, weights=df1['c'] / df1['c'].sum(), random_state=rs)\n result2 = r2.execute().fetch()\n pd.testing.assert_frame_equal(result1, result2)\n assert not (result1.groupby('b').count() - sample_count).any()[0]\n\n r1 = mdf.groupby('b')[['b', 'c']].sample(sample_count, random_state=rs)\n result1 = r1.execute().fetch()\n r2 = mdf.groupby('b')[['b', 'c']].sample(sample_count, random_state=rs)\n result2 = r2.execute().fetch()\n pd.testing.assert_frame_equal(result1, result2)\n assert len(result1.columns) == 2\n assert not (result1.groupby('b').count() - sample_count).any()[0]\n\n r1 = mdf.groupby('b').c.sample(sample_count, random_state=rs)\n result1 = r1.execute().fetch()\n r2 = mdf.groupby('b').c.sample(sample_count, random_state=rs)\n result2 = r2.execute().fetch()\n pd.testing.assert_series_equal(result1, result2)\n\n r1 = mdf.groupby('b').c.sample(len(df1), random_state=rs)\n result1 = r1.execute().fetch()\n assert len(result1) == len(df1)\n\n with pytest.raises(ValueError):\n r1 = mdf.groupby('b').c.sample(len(df1), random_state=rs, errors='raises')\n r1.execute().fetch()\n\n\[email protected](pa is None, reason='pyarrow not installed')\ndef test_groupby_agg_with_arrow_dtype(setup):\n df1 = pd.DataFrame({'a': [1, 2, 1],\n 'b': ['a', 'b', 'a']})\n mdf = md.DataFrame(df1)\n mdf['b'] = mdf['b'].astype('Arrow[string]')\n\n r = mdf.groupby('a').count()\n result = r.execute().fetch()\n expected = df1.groupby('a').count()\n pd.testing.assert_frame_equal(result, expected)\n\n r = mdf.groupby('b').count()\n result = r.execute().fetch()\n expected = df1.groupby('b').count()\n pd.testing.assert_frame_equal(result, expected)\n\n series1 = df1['b']\n mseries = md.Series(series1).astype('Arrow[string]')\n\n r = mseries.groupby(mseries).count()\n result = r.execute().fetch()\n expected = series1.groupby(series1).count()\n pd.testing.assert_series_equal(result, expected)\n\n series2 = series1.copy()\n series2.index = pd.MultiIndex.from_tuples([(0, 1), (2, 3), (4, 5)])\n mseries = md.Series(series2).astype('Arrow[string]')\n\n r = mseries.groupby(mseries).count()\n result = r.execute().fetch()\n expected = series2.groupby(series2).count()\n pd.testing.assert_series_equal(result, expected)\n\n\[email protected](pa is None, reason='pyarrow not installed')\ndef test_groupby_apply_with_arrow_dtype(setup):\n df1 = pd.DataFrame({'a': [1, 2, 1],\n 'b': ['a', 'b', 'a']})\n mdf = md.DataFrame(df1)\n mdf['b'] = mdf['b'].astype('Arrow[string]')\n\n applied = mdf.groupby('b').apply(lambda df: df.a.sum())\n result = applied.execute().fetch()\n expected = df1.groupby('b').apply(lambda df: df.a.sum())\n pd.testing.assert_series_equal(result, expected)\n\n series1 = df1['b']\n mseries = md.Series(series1).astype('Arrow[string]')\n\n applied = mseries.groupby(mseries).apply(lambda s: s)\n result = applied.execute().fetch()\n expected = series1.groupby(series1).apply(lambda s: s)\n pd.testing.assert_series_equal(arrow_array_to_objects(result), expected)\n", "# -*- coding: utf-8 -*-\n# Copyright 1999-2020 Alibaba Group Holding Ltd.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport functools\nimport os\nimport logging\nimport sys\nfrom typing import Dict\n\nimport numpy as np\nimport pandas as pd\nimport pytest\ntry:\n from flaky import flaky as _raw_flaky\nexcept ImportError:\n _raw_flaky = None\ntry:\n import mock\nexcept ImportError:\n from unittest import mock\n_mock = mock\n\nfrom ..config import option_context\nfrom ..utils import lazy_import\n\n\ncupy = lazy_import('cupy', globals=globals())\ncudf = lazy_import('cudf', globals=globals())\nray = lazy_import('ray', globals=globals())\n\nlogger = logging.getLogger(__name__)\n\n\[email protected](scope='module')\ndef setup():\n from ..deploy.oscar.tests.session import new_test_session\n\n sess = new_test_session(address='test://127.0.0.1',\n init_local=True,\n default=True)\n with option_context({'show_progress': False}):\n try:\n yield sess\n finally:\n sess.stop_server()\n\n\ndef flaky(o=None, *args, **kwargs):\n platform = kwargs.pop('platform', '')\n if _raw_flaky is None or not sys.platform.startswith(platform):\n if o is not None:\n return o\n\n def ident(x):\n return x\n\n return ident\n elif o is not None:\n return _raw_flaky(o, *args, **kwargs)\n else:\n return _raw_flaky(*args, **kwargs)\n\n\ndef patch_method(method, *args, **kwargs):\n if hasattr(method, '__qualname__'):\n return mock.patch(method.__module__ + '.' + method.__qualname__, *args, **kwargs)\n elif hasattr(method, 'im_class'):\n return mock.patch('.'.join([method.im_class.__module__, method.im_class.__name__, method.__name__]),\n *args, **kwargs)\n else:\n return mock.patch(method.__module__ + '.' + method.__name__, *args, **kwargs)\n\n\ndef print_entrance(func):\n @functools.wraps(func)\n def wrapper(*args, **kwargs):\n try:\n print(f\"Start to execute function {func} with args {args} and kwargs {kwargs}\")\n result = func(*args, **kwargs)\n print(f\"Finished executing function {func} with args {args} and kwargs {kwargs}\")\n return result\n except NotImplementedError:\n return NotImplemented\n\n return wrapper\n\n\ndef print_async_entrance(func):\n @functools.wraps(func)\n async def wrapper(*args, **kwargs):\n try:\n print(f\"Start to execute function {func} with args {args} and kwargs {kwargs}\")\n result = await func(*args, **kwargs)\n print(f\"Finished executing function {func} with args {args} and kwargs {kwargs}\")\n return result\n except NotImplementedError:\n return NotImplemented\n\n return wrapper\n\n\ndef require_cupy(func):\n if pytest:\n func = pytest.mark.cuda(func)\n func = pytest.mark.skipif(cupy is None, reason='cupy not installed')(func)\n return func\n\n\ndef require_cudf(func):\n if pytest:\n func = pytest.mark.cuda(func)\n func = pytest.mark.skipif(cudf is None, reason='cudf not installed')(func)\n return func\n\n\ndef require_ray(func):\n if pytest:\n func = pytest.mark.ray(func)\n func = pytest.mark.skipif(ray is None, reason='ray not installed')(func)\n return func\n\n\ndef require_hadoop(func):\n if pytest:\n func = pytest.mark.hadoop(func)\n func = pytest.mark.skipif(not os.environ.get('WITH_HADOOP'),\n reason='Only run when hadoop is installed')(func)\n return func\n\n\ndef assert_groupby_equal(left, right, sort_keys=False, sort_index=True, with_selection=False):\n if hasattr(left, 'groupby_obj'):\n left = left.groupby_obj\n if hasattr(right, 'groupby_obj'):\n right = right.groupby_obj\n\n if type(left) is not type(right):\n raise AssertionError(f'Type of groupby not consistent: {type(left)} != {type(right)}')\n\n left_selection = getattr(left, '_selection', None)\n right_selection = getattr(right, '_selection', None)\n if sort_keys:\n left = sorted(left, key=lambda p: p[0])\n right = sorted(right, key=lambda p: p[0])\n else:\n left, right = list(left), list(right)\n if sort_index:\n left = [(k, v.sort_index()) for k, v in left]\n right = [(k, v.sort_index()) for k, v in right]\n\n if len(left) != len(right):\n raise AssertionError(f'Count of groupby keys not consistent: {len(left)} != {len(right)}')\n\n left_keys = [p[0] for p in left]\n right_keys = [p[0] for p in right]\n if left_keys != right_keys:\n raise AssertionError(f'Group keys not consistent: {left_keys!r} != {right_keys!r}')\n for (left_key, left_frame), (right_key, right_frame) in zip(left, right):\n if with_selection:\n if left_selection and isinstance(left_frame, pd.DataFrame):\n left_frame = left_frame[left_selection]\n if right_selection and isinstance(right_frame, pd.DataFrame):\n right_frame = right_frame[right_selection]\n\n if isinstance(left_frame, pd.DataFrame):\n pd.testing.assert_frame_equal(left_frame, right_frame)\n else:\n pd.testing.assert_series_equal(left_frame, right_frame)\n\n\n_check_options = dict()\n_check_args = ['check_all', 'check_series_name', 'check_index_name', 'check_dtypes',\n 'check_dtype', 'check_shape', 'check_nsplits',\n 'check_index_value', 'check_columns_value']\n\n\nclass ObjectCheckMixin:\n _check_options: Dict\n\n @staticmethod\n def adapt_index_value(value):\n if hasattr(value, 'to_pandas'):\n return value.to_pandas()\n return value\n\n def assert_shape_consistent(self, expected_shape, real_shape):\n if not self._check_options['check_shape']:\n return\n\n if len(expected_shape) != len(real_shape):\n raise AssertionError('ndim in metadata %r is not consistent with real ndim %r'\n % (len(expected_shape), len(real_shape)))\n for e, r in zip(expected_shape, real_shape):\n if not np.isnan(e) and e != r:\n raise AssertionError('shape in metadata %r is not consistent with real shape %r'\n % (expected_shape, real_shape))\n\n @staticmethod\n def assert_dtype_consistent(expected_dtype, real_dtype):\n if isinstance(real_dtype, pd.DatetimeTZDtype):\n real_dtype = real_dtype.base\n if expected_dtype != real_dtype:\n if expected_dtype == np.dtype('O') and real_dtype.type is np.str_:\n # real dtype is string, this matches expectation\n return\n if expected_dtype is None:\n raise AssertionError('Expected dtype cannot be None')\n if not np.can_cast(real_dtype, expected_dtype) and not np.can_cast(expected_dtype, real_dtype):\n raise AssertionError('cannot cast between dtype of real dtype %r and dtype %r defined in metadata'\n % (real_dtype, expected_dtype))\n\n def assert_tensor_consistent(self, expected, real):\n from mars.lib.sparse import SparseNDArray\n np_types = (np.generic, np.ndarray, pd.Timestamp, SparseNDArray)\n if cupy is not None:\n np_types += (cupy.ndarray,)\n\n if isinstance(real, (str, int, bool, float, complex)):\n real = np.array([real])[0]\n if not isinstance(real, np_types):\n raise AssertionError(f'Type of real value ({type(real)}) not one of {np_types!r}')\n if not hasattr(expected, 'dtype'):\n return\n if self._check_options['check_dtypes']:\n self.assert_dtype_consistent(expected.dtype, real.dtype)\n if self._check_options['check_shape']:\n self.assert_shape_consistent(expected.shape, real.shape)\n\n @classmethod\n def assert_index_value_consistent(cls, expected_index_value, real_index):\n if expected_index_value.has_value():\n expected_index = expected_index_value.to_pandas()\n try:\n pd.testing.assert_index_equal(expected_index, cls.adapt_index_value(real_index))\n except AssertionError as e:\n raise AssertionError(\n f'Index of real value ({real_index}) not equal to ({expected_index})') from e\n\n def assert_dataframe_consistent(self, expected, real):\n dataframe_types = (pd.DataFrame,)\n if cudf is not None:\n dataframe_types += (cudf.DataFrame,)\n\n if not isinstance(real, dataframe_types):\n raise AssertionError(f'Type of real value ({type(real)}) not DataFrame')\n self.assert_shape_consistent(expected.shape, real.shape)\n if not np.isnan(expected.shape[1]): # ignore when columns length is nan\n pd.testing.assert_index_equal(expected.dtypes.index,\n self.adapt_index_value(real.dtypes.index))\n\n if self._check_options['check_dtypes']:\n try:\n for expected_dtype, real_dtype in zip(expected.dtypes, real.dtypes):\n self.assert_dtype_consistent(expected_dtype, real_dtype)\n except AssertionError:\n raise AssertionError('dtypes in metadata %r cannot cast to real dtype %r'\n % (expected.dtypes, real.dtypes))\n\n if self._check_options['check_columns_value'] and not np.isnan(expected.shape[1]):\n self.assert_index_value_consistent(expected.columns_value, real.columns)\n if self._check_options['check_index_value'] and not np.isnan(expected.shape[0]):\n self.assert_index_value_consistent(expected.index_value, real.index)\n\n def assert_series_consistent(self, expected, real):\n series_types = (pd.Series,)\n if cudf is not None:\n series_types += (cudf.Series,)\n\n if not isinstance(real, series_types):\n raise AssertionError(f'Type of real value ({type(real)}) not Series')\n self.assert_shape_consistent(expected.shape, real.shape)\n\n if self._check_options['check_series_name'] and expected.name != real.name:\n raise AssertionError(f'series name in metadata {expected.name} '\n f'is not equal to real name {real.name}')\n\n self.assert_dtype_consistent(expected.dtype, real.dtype)\n if self._check_options['check_index_value']:\n self.assert_index_value_consistent(expected.index_value, real.index)\n\n def assert_groupby_consistent(self, expected, real):\n from pandas.core.groupby import DataFrameGroupBy, SeriesGroupBy\n from mars.lib.groupby_wrapper import GroupByWrapper\n from mars.dataframe.core import DATAFRAME_GROUPBY_TYPE, SERIES_GROUPBY_TYPE\n from mars.dataframe.core import DATAFRAME_GROUPBY_CHUNK_TYPE, SERIES_GROUPBY_CHUNK_TYPE\n\n df_groupby_types = (DataFrameGroupBy,)\n series_groupby_types = (SeriesGroupBy,)\n\n try:\n from cudf.core.groupby.groupby import DataFrameGroupBy as CUDataFrameGroupBy, \\\n SeriesGroupBy as CUSeriesGroupBy\n df_groupby_types += (CUDataFrameGroupBy,)\n series_groupby_types += (CUSeriesGroupBy,)\n except ImportError:\n pass\n\n if isinstance(real, GroupByWrapper):\n real = real.groupby_obj\n\n if isinstance(expected, (DATAFRAME_GROUPBY_TYPE, DATAFRAME_GROUPBY_CHUNK_TYPE)) \\\n and isinstance(real, df_groupby_types):\n selection = getattr(real, '_selection', None)\n if not selection:\n self.assert_dataframe_consistent(expected, real.obj)\n else:\n self.assert_dataframe_consistent(expected, real.obj[selection])\n elif isinstance(expected, (SERIES_GROUPBY_TYPE, SERIES_GROUPBY_CHUNK_TYPE)) \\\n and isinstance(real, series_groupby_types):\n self.assert_series_consistent(expected, real.obj)\n else:\n raise AssertionError('GroupBy type not consistent. Expecting %r but receive %r'\n % (type(expected), type(real)))\n\n def assert_index_consistent(self, expected, real):\n index_types = (pd.Index,)\n if cudf is not None:\n index_types += (cudf.Index,)\n\n if not isinstance(real, index_types):\n raise AssertionError(f'Type of real value ({type(real)}) not Index')\n self.assert_shape_consistent(expected.shape, real.shape)\n\n if self._check_options['check_series_name'] and expected.name != real.name:\n raise AssertionError('series name in metadata %r is not equal to real name %r'\n % (expected.name, real.name))\n\n self.assert_dtype_consistent(expected.dtype, real.dtype)\n self.assert_index_value_consistent(expected.index_value, real)\n\n def assert_categorical_consistent(self, expected, real):\n if not isinstance(real, pd.Categorical):\n raise AssertionError(f'Type of real value ({type(real)}) not Categorical')\n self.assert_dtype_consistent(expected.dtype, real.dtype)\n self.assert_shape_consistent(expected.shape, real.shape)\n self.assert_index_value_consistent(expected.categories_value, real.categories)\n\n def assert_object_consistent(self, expected, real):\n from mars.tensor.core import TENSOR_TYPE\n from mars.dataframe.core import DATAFRAME_TYPE, SERIES_TYPE, GROUPBY_TYPE, \\\n INDEX_TYPE, CATEGORICAL_TYPE\n\n from mars.tensor.core import TENSOR_CHUNK_TYPE\n from mars.dataframe.core import DATAFRAME_CHUNK_TYPE, SERIES_CHUNK_TYPE, \\\n GROUPBY_CHUNK_TYPE, INDEX_CHUNK_TYPE, CATEGORICAL_CHUNK_TYPE\n\n if isinstance(expected, (TENSOR_TYPE, TENSOR_CHUNK_TYPE)):\n self.assert_tensor_consistent(expected, real)\n elif isinstance(expected, (DATAFRAME_TYPE, DATAFRAME_CHUNK_TYPE)):\n self.assert_dataframe_consistent(expected, real)\n elif isinstance(expected, (SERIES_TYPE, SERIES_CHUNK_TYPE)):\n self.assert_series_consistent(expected, real)\n elif isinstance(expected, (GROUPBY_TYPE, GROUPBY_CHUNK_TYPE)):\n self.assert_groupby_consistent(expected, real)\n elif isinstance(expected, (INDEX_TYPE, INDEX_CHUNK_TYPE)):\n self.assert_index_consistent(expected, real)\n elif isinstance(expected, (CATEGORICAL_TYPE, CATEGORICAL_CHUNK_TYPE)):\n self.assert_categorical_consistent(expected, real)\n", "# Copyright 1999-2020 Alibaba Group Holding Ltd.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom functools import partial\nfrom collections import defaultdict\n\nimport numpy as np\nimport pytest\n\ntry:\n import sklearn\n from sklearn.utils._testing import assert_array_almost_equal, assert_raises, \\\n assert_almost_equal, assert_raise_message\nexcept ImportError: # pragma: no cover\n sklearn = None\n\nfrom mars import tensor as mt\nfrom mars.learn.datasets.samples_generator import make_low_rank_matrix, \\\n make_classification, make_blobs\nfrom mars.tensor.linalg import svd\nfrom mars.tests import setup\n\n\nsetup = setup\n\n\[email protected](sklearn is None, reason='sklearn not installed')\ndef test_make_classification(setup):\n weights = [0.1, 0.25]\n X, y = make_classification(n_samples=100, n_features=20, n_informative=5,\n n_redundant=1, n_repeated=1, n_classes=3,\n n_clusters_per_class=1, hypercube=False,\n shift=None, scale=None, weights=weights,\n random_state=0, flip_y=-1)\n\n assert weights == [0.1, 0.25]\n assert X.shape == (100, 20)\n assert y.shape == (100,)\n assert mt.unique(y).to_numpy().shape == (3,)\n assert (y == 0).sum().to_numpy() == 10\n assert (y == 1).sum().to_numpy() == 25\n assert (y == 2).sum().to_numpy() == 65\n\n # Test for n_features > 30\n X, y = make_classification(n_samples=2000, n_features=31, n_informative=31,\n n_redundant=0, n_repeated=0, hypercube=True,\n scale=0.5, random_state=0)\n\n X = X.to_numpy()\n assert X.shape == (2000, 31)\n assert y.shape == (2000,)\n assert np.unique(\n X.view([('', X.dtype)] * X.shape[1])).view(X.dtype).reshape(\n -1, X.shape[1]).shape[0] == 2000\n\n\[email protected](sklearn is None, reason='sklearn not installed')\ndef test_make_classification_informative_features(setup):\n \"\"\"Test the construction of informative features in make_classification\n\n Also tests `n_clusters_per_class`, `n_classes`, `hypercube` and\n fully-specified `weights`.\n \"\"\"\n # Create very separate clusters; check that vertices are unique and\n # correspond to classes\n class_sep = 1e6\n make = partial(make_classification, class_sep=class_sep, n_redundant=0,\n n_repeated=0, flip_y=0, shift=0, scale=1, shuffle=False)\n\n for n_informative, weights, n_clusters_per_class in [(2, [1], 1),\n (2, [1/3] * 3, 1),\n (2, [1/4] * 4, 1),\n (2, [1/2] * 2, 2),\n (2, [3/4, 1/4], 2),\n (10, [1/3] * 3, 10),\n (np.int(64), [1], 1)\n ]:\n n_classes = len(weights)\n n_clusters = n_classes * n_clusters_per_class\n n_samples = n_clusters * 50\n\n for hypercube in (False, True):\n generated = make(n_samples=n_samples, n_classes=n_classes,\n weights=weights, n_features=n_informative,\n n_informative=n_informative,\n n_clusters_per_class=n_clusters_per_class,\n hypercube=hypercube, random_state=0)\n\n X, y = mt.ExecutableTuple(generated).execute().fetch()\n assert X.shape == (n_samples, n_informative)\n assert y.shape == (n_samples,)\n\n # Cluster by sign, viewed as strings to allow uniquing\n signs = np.sign(X)\n signs = signs.view(dtype=f'|S{signs.strides[0]}')\n unique_signs, cluster_index = np.unique(signs,\n return_inverse=True)\n\n assert len(unique_signs) == n_clusters\n\n clusters_by_class = defaultdict(set)\n for cluster, cls in zip(cluster_index, y):\n clusters_by_class[cls].add(cluster)\n for clusters in clusters_by_class.values():\n assert len(clusters) == n_clusters_per_class\n assert len(clusters_by_class) == n_classes\n\n assert_array_almost_equal(np.bincount(y) / len(y) // weights,\n [1] * n_classes,\n err_msg=\"Wrong number of samples \"\n \"per class\")\n\n # Ensure on vertices of hypercube\n for cluster in range(len(unique_signs)):\n centroid = X[cluster_index == cluster].mean(axis=0)\n if hypercube:\n assert_array_almost_equal(np.abs(centroid) / class_sep,\n np.ones(n_informative),\n decimal=5,\n err_msg=\"Clusters are not \"\n \"centered on hypercube \"\n \"vertices\")\n else:\n assert_raises(AssertionError,\n assert_array_almost_equal,\n np.abs(centroid) / class_sep,\n np.ones(n_informative),\n decimal=5,\n err_msg=\"Clusters should not be centered \"\n \"on hypercube vertices\")\n\n assert_raises(ValueError, make, n_features=2, n_informative=2, n_classes=5,\n n_clusters_per_class=1)\n assert_raises(ValueError, make, n_features=2, n_informative=2, n_classes=3,\n n_clusters_per_class=2)\n\n\[email protected](sklearn is None, reason='sklearn not installed')\ndef test_make_blobs(setup):\n cluster_stds = np.array([0.05, 0.2, 0.4])\n cluster_centers = np.array([[0.0, 0.0], [1.0, 1.0], [0.0, 1.0]])\n X, y = make_blobs(random_state=0, n_samples=50, n_features=2,\n centers=cluster_centers, cluster_std=cluster_stds)\n X, y = mt.ExecutableTuple((X, y)).execute().fetch()\n assert X.shape == (50, 2)\n assert y.shape == (50,)\n assert np.unique(y).shape == (3,)\n for i, (ctr, std) in enumerate(zip(cluster_centers, cluster_stds)):\n assert_almost_equal((X[y == i] - ctr).std(), std, 1, \"Unexpected std\")\n\n\ndef test_make_blobs_n_samples_list(setup):\n n_samples = [50, 30, 20]\n X, y = make_blobs(n_samples=n_samples, n_features=2, random_state=0)\n X, y = mt.ExecutableTuple((X, y)).execute().fetch()\n\n assert X.shape == (sum(n_samples), 2)\n assert all(np.bincount(y, minlength=len(n_samples)) == n_samples) is True\n\n\[email protected](sklearn is None, reason='sklearn not installed')\ndef test_make_blobs_n_samples_list_with_centers(setup):\n n_samples = [20, 20, 20]\n centers = np.array([[0.0, 0.0], [1.0, 1.0], [0.0, 1.0]])\n cluster_stds = np.array([0.05, 0.2, 0.4])\n X, y = make_blobs(n_samples=n_samples, centers=centers,\n cluster_std=cluster_stds, random_state=0)\n X, y = mt.ExecutableTuple((X, y)).execute().fetch()\n\n assert X.shape == (sum(n_samples), 2)\n assert all(np.bincount(y, minlength=len(n_samples)) == n_samples) is True\n for i, (ctr, std) in enumerate(zip(centers, cluster_stds)):\n assert_almost_equal((X[y == i] - ctr).std(), std, 1, \"Unexpected std\")\n\n\ndef test_make_blobs_n_samples_centers_none(setup):\n for n_samples in [[5, 3, 0], np.array([5, 3, 0]), tuple([5, 3, 0])]:\n centers = None\n X, y = make_blobs(n_samples=n_samples, centers=centers, random_state=0)\n X, y = mt.ExecutableTuple((X, y)).execute().fetch()\n\n assert X.shape == (sum(n_samples), 2)\n assert all(np.bincount(y, minlength=len(n_samples)) == n_samples) is True\n\n\[email protected](sklearn is None, reason='sklearn not installed')\ndef test_make_blobs_error(setup):\n n_samples = [20, 20, 20]\n centers = np.array([[0.0, 0.0], [1.0, 1.0], [0.0, 1.0]])\n cluster_stds = np.array([0.05, 0.2, 0.4])\n wrong_centers_msg = (\"Length of `n_samples` not consistent \"\n f\"with number of centers. Got n_samples = {n_samples} \"\n f\"and centers = {centers[:-1]}\")\n assert_raise_message(ValueError, wrong_centers_msg,\n make_blobs, n_samples, centers=centers[:-1])\n wrong_std_msg = (\"Length of `clusters_std` not consistent with \"\n f\"number of centers. Got centers = {mt.tensor(centers)} \"\n f\"and cluster_std = {cluster_stds[:-1]}\")\n assert_raise_message(ValueError, wrong_std_msg,\n make_blobs, n_samples,\n centers=centers, cluster_std=cluster_stds[:-1])\n wrong_type_msg = (\"Parameter `centers` must be array-like. \"\n f\"Got {3!r} instead\")\n assert_raise_message(ValueError, wrong_type_msg,\n make_blobs, n_samples, centers=3)\n\n\ndef test_make_low_rank_matrix(setup):\n X = make_low_rank_matrix(n_samples=50, n_features=25, effective_rank=5,\n tail_strength=0.01, random_state=0)\n\n assert X.shape == (50, 25)\n\n _, s, _ = svd(X)\n assert (s.sum() - 5).to_numpy() < 0.1\n" ]
[ [ "numpy.dtype" ], [ "numpy.dtype" ], [ "pandas.testing.assert_series_equal", "pandas.Series", "numpy.random.choice", "numpy.arange", "pandas.Index", "numpy.random.shuffle", "pandas.DataFrame", "pandas.testing.assert_frame_equal", "numpy.random.rand", "numpy.random.randint" ], [ "pandas.concat", "pandas.testing.assert_series_equal", "pandas.Series", "numpy.arange", "pandas.MultiIndex.from_tuples", "numpy.random.shuffle", "pandas.DataFrame", "pandas.testing.assert_frame_equal", "numpy.array", "numpy.random.RandomState", "numpy.random.randint" ], [ "numpy.can_cast", "pandas.testing.assert_series_equal", "numpy.isnan", "numpy.dtype", "pandas.testing.assert_frame_equal", "numpy.array" ], [ "numpy.abs", "numpy.unique", "numpy.ones", "numpy.sign", "numpy.int", "numpy.bincount", "numpy.array", "sklearn.utils._testing.assert_raise_message", "sklearn.utils._testing.assert_raises" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [ "0.23", "0.21", "2.0", "1.4", "1.3", "1.1", "1.5", "0.24", "0.20", "1.0", "0.25", "1.2" ], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [ "0.23", "0.21", "2.0", "1.4", "1.3", "1.1", "1.5", "0.24", "0.20", "1.0", "0.25", "1.2" ], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [ "0.23", "0.21", "2.0", "1.4", "1.3", "1.1", "1.5", "0.24", "0.20", "1.0", "0.25", "1.2" ], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
Gedeon-m-gedus/FinalYear_2018_2019_UR
[ "bf82c3640bf0ef854ae173e542535e9a8d697059" ]
[ "garelly_functions.py" ]
[ "#_________MATH AND PLOT LIBRAY__________\r\nimport numpy as np\r\nfrom matplotlib.lines import Line2D\r\nimport matplotlib.pyplot as plt\r\nimport matplotlib.animation as animation\r\n\r\n\r\nimport numpy\r\nfrom matplotlib.pylab import *\r\nfrom mpl_toolkits.axes_grid1 import host_subplot \r\nimport matplotlib.animation as animation\r\n\r\n#_______________________________________\r\n#______________CLASS GARELLY OF FUNCTIONS PLOT_____________\r\n\r\n##############################_______OSCILLATION DECAY_______#############################################\r\ndef dumping_oscillation():\r\n def data_gen(t=0):\r\n cnt = 0\r\n while cnt < 1000:\r\n cnt += 1\r\n t += 0.1\r\n yield t, np.sin(2*np.pi*t) * np.exp(-t/10.)\r\n\r\n\r\n def init():\r\n ax.set_ylim(-1.1, 1.1)\r\n ax.set_xlim(0, 10)\r\n del xdata[:]\r\n del ydata[:]\r\n line.set_data(xdata, ydata)\r\n return line,\r\n\r\n fig, ax = plt.subplots()\r\n line, = ax.plot([], [], lw=2)\r\n ax.grid()\r\n xdata, ydata = [], []\r\n\r\n\r\n def run(data):\r\n # update the data\r\n t, y = data\r\n xdata.append(t)\r\n ydata.append(y)\r\n xmin, xmax = ax.get_xlim()\r\n\r\n if t >= xmax:\r\n ax.set_xlim(xmin, 2*xmax)\r\n ax.figure.canvas.draw()\r\n line.set_data(xdata, ydata)\r\n\r\n return line,\r\n plt.title('dumping oscillation')\r\n\r\n ani = animation.FuncAnimation(fig, run, data_gen, blit=False, interval=10,\r\n repeat=False, init_func=init)\r\n plt.show()\r\n\r\n\r\n#################################___PULSE GENERATION_____#################################################\r\ndef pulse_generation():\r\n class Scope(object):\r\n def __init__(self, ax, maxt=2, dt=0.02):\r\n self.ax = ax\r\n self.dt = dt\r\n self.maxt = maxt\r\n self.tdata = [0]\r\n self.ydata = [0]\r\n self.line = Line2D(self.tdata, self.ydata)\r\n self.ax.add_line(self.line)\r\n self.ax.set_ylim(-.1, 1.1)\r\n self.ax.set_xlim(0, self.maxt)\r\n\r\n def update(self, y):\r\n lastt = self.tdata[-1]\r\n if lastt > self.tdata[0] + self.maxt: # reset the arrays\r\n self.tdata = [self.tdata[-1]]\r\n self.ydata = [self.ydata[-1]]\r\n self.ax.set_xlim(self.tdata[0], self.tdata[0] + self.maxt)\r\n self.ax.figure.canvas.draw()\r\n\r\n t = self.tdata[-1] + self.dt\r\n self.tdata.append(t)\r\n self.ydata.append(y)\r\n self.line.set_data(self.tdata, self.ydata)\r\n return self.line,\r\n\r\n\r\n def emitter(p=0.03):\r\n 'return a random value with probability p, else 0'\r\n while True:\r\n v = np.random.rand(1)\r\n if v > p:\r\n yield 0.\r\n else:\r\n yield np.random.rand(1)\r\n\r\n # Fixing random state for reproducibility\r\n np.random.seed(19680801)\r\n\r\n\r\n fig, ax = plt.subplots()\r\n scope = Scope(ax)\r\n\r\n # pass a generator in \"emitter\" to produce data for the update func\r\n ani = animation.FuncAnimation(fig, scope.update, emitter, interval=10,\r\n blit=True)\r\n\r\n plt.show()\r\n\r\n###############################_______COSINE WAVE ______________##############################################################3\r\n\r\ndef cosine_wave():\r\n plt.title('cosine wave signal')\r\n ax = plt.subplot(111)\r\n t = np.arange(0.0, 5.0 , 0.01)\r\n s = np.cos(2*np.pi*t)\r\n line, = plt.plot(t,s, lw=2)\r\n plt.annotate('local max', xy=(2, 1), xytext=(3, 1.5),\r\n arrowprops=dict(facecolor ='black', shrink=0.05),)\r\n plt.annotate('local min', xy=(0.5, -1), xytext=(2, -1.5),\r\n arrowprops=dict(facecolor ='black', shrink=1),)\r\n\r\n plt.ylim(-3 ,3)\r\n plt.show()\r\n#k= cosine_wave() \r\n\r\n################################________SINE WAVE ______________########################################\r\ndef sine_wave():\r\n plt.title('sine wave signal')\r\n ax = plt.subplot(111)\r\n t = np.arange(0.0, 5.0 , 0.01)\r\n s = np.sin(2*np.pi*t)\r\n line, = plt.plot(t,s, lw=2)\r\n plt.annotate('local max', xy=(2.25, 1), xytext=(3, 1.5),\r\n arrowprops=dict(facecolor ='black', shrink=0.05),)\r\n plt.annotate('local min', xy=(0.75, -1), xytext=(2, -1.5),\r\n arrowprops=dict(facecolor ='black', shrink=1),)\r\n\r\n plt.ylim(-3 ,3)\r\n plt.show()\r\n#k= sine_wave() \r\n\r\n#############################___THREE PHASE SIGNAL_________#############################################\r\ndef three_phase_wave():\r\n plt.title('three phase signal')\r\n\r\n ax = plt.subplot(111)\r\n t = np.arange(0.0, 5.0 , 0.01)\r\n s = np.sin(2*np.pi*t)\r\n ss = np.sin(2*np.pi*t+120)\r\n sss = np.sin(2*np.pi*t+240)\r\n line, = plt.plot(t,s, lw=2)\r\n line, = plt.plot(t,ss, lw=2)\r\n line, = plt.plot(t,sss, lw=2)\r\n plt.ylim(-3 ,3)\r\n plt.show()\r\n#k=three_phase_wave()\r\n\r\n###############################____second order equations_____#############################################\r\ndef second_order():\r\n a=int(input(\"first coeficient\"))\r\n b=int(input(\"second coeficient\"))\r\n c=int(input(\"constant\"))\r\n x = np.linspace(-20,20,20)\r\n y = a*x**2 + b*x + c\r\n #plt.ylim(-3 ,3)\r\n plt.plot(x,y)\r\n plt.show()\r\n#k=second_order()\r\n########################______sinc_function__________#################################################\r\ndef sinc_function():\r\n X = np.linspace(-6,6, 1024)\r\n Y = np.sinc(X)\r\n plt.title('sinc_function') # a little notation\r\n plt.xlabel('array variables') #adding xlabel\r\n plt.ylabel('random variables') #adding ylabel\r\n #plt.text(-5, 0.4, 'Matplotlib') # -5 is the x value and 0.4 is y value\r\n plt.plot(X,Y, color='r', marker ='o',markersize =3,markevery = 30, markerfacecolor='w',linewidth= 3.0,markeredgecolor = 'b')\r\n plt.show()\r\n\r\n######################____distribution function______#################\r\ndef distrubution_function():\r\n def gf(X, mu, sigma):\r\n a = 1. /(sigma*np.sqrt(2. * np.pi))\r\n b = -1. /(2. * sigma **2)\r\n return a * np.exp(b * (X - mu)**2)\r\n\r\n X = np.linspace(-6, 6, 1024)\r\n for i in range(64):\r\n samples = np.random.standard_normal(50)\r\n mu,sigma = np.mean(samples), np.std(samples)\r\n plt.plot(X, gf(X, mu, sigma),color = '.75',linewidth='.5')\r\n\r\n plt.plot(X,gf(X, 0., 1.),color ='.00',linewidth=3.)\r\n plt.show()\r\n\r\n##########################_____integral finding area under the curve_____########\r\ndef area_area_under_curve():\r\n def func(x):\r\n return (x - 3) * (x - 5) * (x - 7) + 85\r\n\r\n\r\n a, b = 2, 9 # integral limits\r\n x = np.linspace(0, 10)\r\n y = func(x)\r\n\r\n fig, ax = plt.subplots()\r\n plt.plot(x, y, 'r', linewidth=2)\r\n plt.ylim(ymin=0)\r\n\r\n # Make the shaded region\r\n ix = np.linspace(a, b)\r\n iy = func(ix)\r\n verts = [(a, 0)] + list(zip(ix, iy)) + [(b, 0)]\r\n poly = Polygon(verts, facecolor='0.9', edgecolor='0.5')\r\n ax.add_patch(poly)\r\n\r\n plt.text(0.5 * (a + b), 30, r\"$\\int_a^b f(x)\\mathrm{d}x$\",\r\n horizontalalignment='center', fontsize=20)\r\n\r\n plt.figtext(0.9, 0.05, '$x$')\r\n plt.figtext(0.1, 0.9, '$y$')\r\n\r\n ax.spines['right'].set_visible(False)\r\n ax.spines['top'].set_visible(False)\r\n ax.xaxis.set_ticks_position('bottom')\r\n\r\n ax.set_xticks((a, b))\r\n ax.set_xticklabels(('$a$', '$b$'))\r\n ax.set_yticks([])\r\n\r\n plt.show()\r\n\r\n#################################____oscillationdecay___################################################\r\ndef oscillation_decay():\r\n # Sent for figure\r\n font = {'size' : 9}\r\n matplotlib.rc('font', **font)\r\n\r\n # Setup figure and subplots\r\n f0 = figure(num = 0, figsize = (12, 8))#, dpi = 100)\r\n f0.suptitle(\"Oscillation decay\", fontsize=12)\r\n ax01 = subplot2grid((2, 2), (0, 0))\r\n ax02 = subplot2grid((2, 2), (0, 1))\r\n ax03 = subplot2grid((2, 2), (1, 0), colspan=2, rowspan=1)\r\n ax04 = ax03.twinx()\r\n #tight_layout()\r\n\r\n # Set titles of subplots\r\n ax01.set_title('Position vs Time')\r\n ax02.set_title('Velocity vs Time')\r\n ax03.set_title('Position and Velocity vs Time')\r\n\r\n # set y-limits\r\n ax01.set_ylim(0,2)\r\n ax02.set_ylim(-6,6)\r\n ax03.set_ylim(-0,5)\r\n ax04.set_ylim(-10,10)\r\n\r\n # set x-limits\r\n ax01.set_xlim(0,5.0)\r\n ax02.set_xlim(0,5.0)\r\n ax03.set_xlim(0,5.0)\r\n ax04.set_xlim(0,5.0)\r\n\r\n # Turn on grids\r\n ax01.grid(True)\r\n ax02.grid(True)\r\n ax03.grid(True) \r\n\r\n # set label names\r\n ax01.set_xlabel(\"x\")\r\n ax01.set_ylabel(\"py\")\r\n ax02.set_xlabel(\"t\")\r\n ax02.set_ylabel(\"vy\")\r\n ax03.set_xlabel(\"t\")\r\n ax03.set_ylabel(\"py\")\r\n ax04.set_ylabel(\"vy\")\r\n\r\n # Data Placeholders\r\n yp1=zeros(0)\r\n yv1=zeros(0)\r\n yp2=zeros(0)\r\n yv2=zeros(0)\r\n t=zeros(0)\r\n\r\n # set plots\r\n p011, = ax01.plot(t,yp1,'b-', label=\"yp1\")\r\n p012, = ax01.plot(t,yp2,'g-', label=\"yp2\") \r\n\r\n p021, = ax02.plot(t,yv1,'b-', label=\"yv1\")\r\n p022, = ax02.plot(t,yv2,'g-', label=\"yv2\")\r\n\r\n p031, = ax03.plot(t,yp1,'b-', label=\"yp1\")\r\n p032, = ax04.plot(t,yv1,'g-', label=\"yv1\")\r\n\r\n # set lagends\r\n ax01.legend([p011,p012], [p011.get_label(),p012.get_label()])\r\n ax02.legend([p021,p022], [p021.get_label(),p022.get_label()])\r\n ax03.legend([p031,p032], [p031.get_label(),p032.get_label()])\r\n\r\n # Data Update\r\n xmin = 0.0\r\n xmax = 5.0\r\n x = 0.0\r\n\r\n def updateData(self):\r\n global x\r\n global yp1\r\n global yv1\r\n global yp2\r\n global yv2\r\n global t\r\n\r\n tmpp1 = 1 + exp(-x) *sin(2 * pi * x)\r\n tmpv1 = - exp(-x) * sin(2 * pi * x) + exp(-x) * cos(2 * pi * x) * 2 * pi\r\n yp1=append(yp1,tmpp1)\r\n yv1=append(yv1,tmpv1)\r\n yp2=append(yp2,0.5*tmpp1)\r\n yv2=append(yv2,0.5*tmpv1)\r\n t=append(t,x)\r\n\r\n x += 0.05\r\n\r\n p011.set_data(t,yp1)\r\n p012.set_data(t,yp2)\r\n\r\n p021.set_data(t,yv1)\r\n p022.set_data(t,yv2)\r\n\r\n p031.set_data(t,yp1)\r\n p032.set_data(t,yv1)\r\n\r\n if x >= xmax-1.00:\r\n p011.axes.set_xlim(x-xmax+1.0,x+1.0)\r\n p021.axes.set_xlim(x-xmax+1.0,x+1.0)\r\n p031.axes.set_xlim(x-xmax+1.0,x+1.0)\r\n p032.axes.set_xlim(x-xmax+1.0,x+1.0)\r\n\r\n return p011, p012, p021, p022, p031, p032\r\n\r\n # interval: draw new frame every 'interval' ms\r\n # frames: number of frames to draw\r\n simulation = animation.FuncAnimation(f0, updateData, blit=False, frames=200, interval=20, repeat=False)\r\n\r\n # Uncomment the next line if you want to save the animation\r\n #simulation.save(filename='sim.mp4',fps=30,dpi=300)\r\n\r\n plt.show()\r\n\r\n" ]
[ [ "numpy.sqrt", "numpy.linspace", "matplotlib.pyplot.plot", "numpy.mean", "numpy.exp", "numpy.sinc", "numpy.arange", "numpy.sin", "numpy.std", "matplotlib.pyplot.subplot", "matplotlib.pyplot.text", "matplotlib.pyplot.title", "matplotlib.pyplot.ylim", "matplotlib.animation.FuncAnimation", "numpy.random.rand", "matplotlib.pyplot.show", "matplotlib.pyplot.ylabel", "numpy.random.seed", "numpy.random.standard_normal", "matplotlib.lines.Line2D", "matplotlib.pyplot.subplots", "numpy.cos", "matplotlib.pyplot.xlabel", "matplotlib.pyplot.figtext" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
xqgex/CrazyFlie
[ "a7f613f41734db12bbbffe4714b5b1df91dbb2ea" ]
[ "Managers/joystick.py" ]
[ "import pygame\nimport numpy as np\nimport logger\n\ncp_logger = logger.get_logger(__name__)\n\n\nclass Joystick:\n def __init__(self, control_board_api):\n self._control_board_api = control_board_api\n if self._control_board_api:\n self._non_normalize_function = self._control_board_api.get_joystick_direction\n self._click_func = self._control_board_api.get_button\n else:\n self._non_normalize_function = _get_keyboard_direction\n self._click_func = _get_keyboard_click\n\n def get_normalize_direction(self):\n ax, ay = self._non_normalize_function()\n if ax == 0 and ay == 0:\n return None\n vector = np.array([ax, ay])\n normalized_vector = vector / np.linalg.norm(vector)\n return normalized_vector.tolist()\n\n def get_click(self):\n return self._click_func()\n\n\ndef _get_keyboard_click():\n keys = pygame.key.get_pressed()\n return keys[pygame.K_c]\n\n\ndef _get_keyboard_direction():\n keys = pygame.key.get_pressed()\n ax, ay = 0, 0\n if keys[pygame.K_UP]:\n ay -= 1\n if keys[pygame.K_DOWN]:\n ay += 1\n if keys[pygame.K_LEFT]:\n ax += 1\n if keys[pygame.K_RIGHT]:\n ax -= 1\n return ax, ay" ]
[ [ "numpy.array", "numpy.linalg.norm" ] ]
[ { "matplotlib": [], "numpy": [ "1.10", "1.12", "1.11", "1.19", "1.24", "1.13", "1.16", "1.9", "1.18", "1.23", "1.21", "1.22", "1.20", "1.7", "1.15", "1.14", "1.17", "1.8" ], "pandas": [], "scipy": [], "tensorflow": [] } ]
Mohammad-Chowdhury-31/svmbir
[ "05665eb2a65b7aa951e26dd3691955e737f16c06" ]
[ "demo/demo_multires_comparison.py" ]
[ "import os\nimport numpy as np\nfrom demo_utils import plot_image\nimport svmbir\n\n\"\"\"\nThis file demonstrates the generation of a 3D microscopy phantom followed by sinogram projection and reconstruction using MBIR. \nThe phantom, sinogram, and reconstruction are then displayed. \n\"\"\"\n\n# Simulated image parameters\nnum_rows = 256\nnum_cols = 64\nnum_slices = 33\ndisplay_slice = 16 # Display slice at z=-0.0\n\n# Simulated sinogram parameters\nnum_views = 64\ntilt_angle = np.pi/3 # Tilt range of +-60deg\n\n# Reconstruction parameters\nsharpness = 2.0\nT = 0.25\nsnr_db = 30.0\np = 1.2\n\n# Multi-resolution works much better for limited and sparse view reconstruction\nmax_resolutions=2 # Use 2 additional resolutions to do reconstruction\n\n# Display parameters\nvmin = 0.0\nvmax = 1.1\n\n# Generate phantom\nphantom = svmbir.phantom.gen_microscopy_sample_3d(num_rows,num_cols,num_slices)\n\n# Generate the array of view angles\nangles = np.linspace(-tilt_angle, tilt_angle, num_views)\n\n# Generate sinogram by projecting phantom\nsino = svmbir.project(phantom, angles, max(num_rows, num_cols))\n\n# Determine resulting number of views, slices, and channels\n(num_views, num_slices, num_channels) = sino.shape\n\n# Perform fixed resolution MBIR reconstruction\nrecon = svmbir.recon(sino, angles, num_rows=num_rows, num_cols=num_cols, T=T, p=p, sharpness=sharpness, snr_db=snr_db )\n\n# Perform multi-resolution MBIR reconstruction\nmr_recon = svmbir.recon(sino, angles, num_rows=num_rows, num_cols=num_cols, T=T, p=p, max_resolutions=max_resolutions, sharpness=sharpness, snr_db=snr_db )\n\n# Compute Normalized Root Mean Squared Error\nnrmse = svmbir.phantom.nrmse(recon, phantom)\nmr_nrmse = svmbir.phantom.nrmse(mr_recon, phantom)\n\n# create output folder\nos.makedirs('output', exist_ok=True)\n\n# display phantom\nplot_image(phantom[display_slice], title='Shepp Logan Phantom', filename='output/3D_microscopy_phantom.png', vmin=vmin, vmax=vmax)\n\n# display fixed resolution reconstruction\ntitle = f'Slice {display_slice:d} of Fixed Res Recon with NRMSE={nrmse:.3f}.'\nplot_image(recon[display_slice], title=title, filename='output/mr_3D_microscopy_recon.png', vmin=vmin, vmax=vmax)\n\n# display multi-resolution reconstruction\ntitle = f'Slice {display_slice:d} of Multi-Res Recon with NRMSE={mr_nrmse:.3f}.'\nplot_image(recon[display_slice], title=title, filename='output/mr_3D_microscopy_recon.png', vmin=vmin, vmax=vmax)\n\ninput(\"press Enter\")\n" ]
[ [ "numpy.linspace" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
hoslo/ocr
[ "4f78ae7013beb2cab8fb9391ba25ba5e6e78967c", "7a5464895f455df6ddf61989a4173ea1999e1507" ]
[ "direction_detection/SkewDetect.py", "pan/utils/cal_recall/rrc_evaluation_funcs.py" ]
[ "\"\"\" Calculates skew angle \"\"\"\nimport os\nos.environ[\"CUDA_VISIBLE_DEVICES\"] = \"-1\"\nimport time\n\nimport cv2\nfrom math import fabs, sin, cos, radians\nimport numpy as np\nimport scipy\nfrom PIL import Image\nfrom skimage.transform import hough_line, hough_line_peaks\n\n\nclass SkewDetect:\n\n piby4 = np.pi / 4\n\n def __init__(\n self,\n input_file=None,\n batch_path=None,\n output_file=None,\n sigma=3.0,\n display_output=None,\n num_peaks=20,\n plot_hough=None\n ):\n\n self.sigma = sigma\n self.input_file = input_file\n self.batch_path = batch_path\n self.output_file = output_file\n self.display_output = display_output\n self.num_peaks = num_peaks\n self.plot_hough = plot_hough\n self.angleNet = cv2.dnn.readNetFromTensorflow(os.path.join(os.getcwd(), \"models\", \"Angle-model.pb\"),\n os.path.join(os.getcwd(), \"models\", \"Angle-model.pbtxt\"))\n\n def rotate_img(self, image, degree):\n img1 = np.array(image.convert('RGB'))\n height, width = img1.shape[:2]\n\n # 旋转后的尺寸\n heightNew = int(width * fabs(sin(radians(degree))) + height * fabs(cos(radians(degree)))) # 这个公式参考之前内容\n widthNew = int(height * fabs(sin(radians(degree))) + width * fabs(cos(radians(degree))))\n\n matRotation = cv2.getRotationMatrix2D((width / 2, height / 2), degree, 1)\n\n matRotation[0, 2] += (widthNew - width) / 2 # 因为旋转之后,坐标系原点是新图像的左上角,所以需要根据原图做转化\n matRotation[1, 2] += (heightNew - height) / 2\n\n imgRotation = cv2.warpAffine(img1, matRotation, (widthNew, heightNew), borderValue=(255, 255, 255))\n return Image.fromarray(imgRotation)\n\n def get_rotated_img(self, origin_img):\n # 定义文本旋转处理类对象\n # origin_img = Image.open(jpg_path) # 读取图像数据\n res = self.determine_skew(origin_img)\n angle = res['Estimated Angle']\n\n if (angle >= 0) and (angle <= 90):\n rot_angle = angle - 90\n if (angle >= -45) and (angle < 0):\n rot_angle = angle - 90\n if (angle >= -90) and (angle < -45):\n rot_angle = 90 + angle\n # print(rot_angle)\n # 根据检测出来的旋转角度进行旋转操作\n rotated = self.rotate_img(origin_img, rot_angle)\n angle = self.detect_angle_90(rotated)\n final_img = self.rotate_img(origin_img, rot_angle+angle)\n return final_img\n\n def get_max_freq_elem(self, arr):\n max_arr = []\n freqs = {}\n for i in arr:\n if i in freqs:\n freqs[i] += 1\n else:\n freqs[i] = 1\n\n sorted_keys = sorted(freqs, key=freqs.get, reverse=True)\n max_freq = freqs[sorted_keys[0]]\n\n for k in sorted_keys:\n if freqs[k] == max_freq:\n max_arr.append(k)\n\n return max_arr\n\n def compare_sum(self, value):\n if 43 <= value <= 47:\n return True\n else:\n return False\n\n def calculate_deviation(self, angle):\n\n angle_in_degrees = np.abs(angle)\n deviation = np.abs(SkewDetect.piby4 - angle_in_degrees)\n\n return deviation\n\n def determine_skew(self, origin_img):\n # img = io.imread(img_file, as_gray=True)\n # edges = canny(img, sigma=self.sigma)\n img = origin_img.convert('RGB')\n img = np.array(img)\n img = cv2.cvtColor(img, cv2.COLOR_RGB2BGR)\n B_channel, G_channel, R_channel = cv2.split(img)\n _, img = cv2.threshold(R_channel, 160, 255, cv2.THRESH_BINARY)\n img_h, img_w = img.shape\n img = img[int(img_h*0.2):int(img_h*0.8), int(img_w*0.2):int(img_w*0.8)]\n kernel = np.ones((15, 15), np.uint8)\n img = cv2.GaussianBlur(img, (3, 3), 0)\n img = cv2.erode(img, kernel)\n # img = cv2.dilate(img, kernel)\n # Image.fromarray(img).show()\n edges = cv2.Canny(img, 40, 255)\n Image.fromarray(edges).show()\n edges = edges.astype(np.float32)\n edges /= 255\n\n h, a, d = hough_line(edges)\n _, ap, _ = hough_line_peaks(h, a, d, num_peaks=self.num_peaks)\n if len(ap) == 0:\n return {\"Estimated Angle\": 0}\n\n absolute_deviations = [self.calculate_deviation(k) for k in ap]\n average_deviation = np.mean(np.rad2deg(absolute_deviations))\n ap_deg = [np.rad2deg(x) for x in ap]\n\n bin_0_45 = []\n bin_45_90 = []\n bin_0_45n = []\n bin_45_90n = []\n\n for ang in ap_deg:\n\n deviation_sum = int(90 - ang + average_deviation)\n if self.compare_sum(deviation_sum):\n bin_45_90.append(ang)\n continue\n\n deviation_sum = int(ang + average_deviation)\n if self.compare_sum(deviation_sum):\n bin_0_45.append(ang)\n continue\n\n deviation_sum = int(-ang + average_deviation)\n if self.compare_sum(deviation_sum):\n bin_0_45n.append(ang)\n continue\n\n deviation_sum = int(90 + ang + average_deviation)\n if self.compare_sum(deviation_sum):\n bin_45_90n.append(ang)\n\n angles = [bin_0_45, bin_45_90, bin_0_45n, bin_45_90n]\n # print(angles)\n maxi = np.argmax([len(i) for i in angles])\n\n # print(angles, maxi)\n if len(angles[maxi]) > 0:\n if len(angles[maxi]) >= 5:\n angles = sorted(angles[maxi])\n angles = angles[1:-1]\n elif len(angles[maxi]) <= 2:\n angles = [0]\n else:\n angles = angles[maxi]\n # print(angles)\n ans_arr = self.get_max_freq_elem(angles)\n ans_res = np.mean(ans_arr)\n\n else:\n try:\n ap_deg_5 = [int(i//5) for i in ap_deg]\n mode = scipy.stats.mode(ap_deg_5)[0][0]*5\n ap_deg = [i for i in ap_deg if abs(i - mode) < 10]\n ans_arr = self.get_max_freq_elem(ap_deg)\n ans_res = np.mean(ans_arr)\n # print(11111111111111111111111111111)\n except:\n ans_res = 0\n\n data = {\n # \"Image File\": img_file,\n \"Average Deviation from pi/4\": average_deviation,\n \"Estimated Angle\": ans_res,\n \"Angle bins\": angles}\n return data\n\n def detect_angle_90(self, img, adjust=True):\n \"\"\"\n 文字方向检测\n \"\"\"\n img = np.array(img)\n h, w = img.shape[:2]\n ROTATE = [0, 90, 180, 270]\n if adjust:\n thesh = 0.05\n xmin, ymin, xmax, ymax = int(thesh * w), int(thesh * h), w - int(thesh * w), h - int(thesh * h)\n img = img[ymin:ymax, xmin:xmax] # # 剪切图片边缘\n\n inputBlob = cv2.dnn.blobFromImage(img,\n scalefactor=1.0,\n size=(224, 224),\n swapRB=True,\n mean=[103.939, 116.779, 123.68], crop=False)\n self.angleNet.setInput(inputBlob)\n pred = self.angleNet.forward()\n index = np.argmax(pred, axis=1)[0]\n return ROTATE[index]\n\n\nskew_detect = SkewDetect()\n\n\n# main函数\nif __name__ == '__main__':\n skew_detect = SkewDetect()\n for name in os.listdir('images'):\n if '2010 股权转让协议-领庆创投-领锐创投-松芝投资-祥禾投资_117.jpg' not in name:\n continue\n st_time = time.time()\n img = skew_detect.get_rotated_img(f'images/{name}')\n img.save(f'rotated_imgs1/{name}')\n print(f'{name} use time:', time.time() - st_time)\n img.show()\n", "#!/usr/bin/env python2\n#encoding: UTF-8\nimport json\nimport sys;sys.path.append('./')\nimport zipfile\nimport re\nimport sys\nimport os\nimport codecs\nimport traceback\nimport importlib\nfrom io import StringIO\n\ndef print_help():\n sys.stdout.write('Usage: python %s.py -g=<gtFile> -s=<submFile> [-o=<outputFolder> -p=<jsonParams>]' %sys.argv[0])\n sys.exit(2)\n \n\ndef load_zip_file_keys(file,fileNameRegExp=''):\n \"\"\"\n Returns an array with the entries of the ZIP file that match with the regular expression.\n The key's are the names or the file or the capturing group definied in the fileNameRegExp\n \"\"\"\n try:\n archive=zipfile.ZipFile(file, mode='r', allowZip64=True)\n except :\n raise Exception('Error loading the ZIP archive.')\n\n pairs = []\n \n for name in archive.namelist():\n addFile = True\n keyName = name\n if fileNameRegExp!=\"\":\n m = re.match(fileNameRegExp,name)\n if m == None:\n addFile = False\n else:\n if len(m.groups())>0:\n keyName = m.group(1)\n \n if addFile:\n pairs.append( keyName )\n \n return pairs\n \n\ndef load_zip_file(file,fileNameRegExp='',allEntries=False):\n \"\"\"\n Returns an array with the contents (filtered by fileNameRegExp) of a ZIP file.\n The key's are the names or the file or the capturing group definied in the fileNameRegExp\n allEntries validates that all entries in the ZIP file pass the fileNameRegExp\n \"\"\"\n try:\n archive=zipfile.ZipFile(file, mode='r', allowZip64=True)\n except :\n raise Exception('Error loading the ZIP archive') \n\n pairs = []\n for name in archive.namelist():\n addFile = True\n keyName = name\n if fileNameRegExp!=\"\":\n m = re.match(fileNameRegExp,name)\n if m == None:\n addFile = False\n else:\n if len(m.groups())>0:\n keyName = m.group(1)\n \n if addFile:\n pairs.append( [ keyName , archive.read(name)] )\n else:\n if allEntries:\n raise Exception('ZIP entry not valid: %s' %name) \n\n return dict(pairs)\n\n\ndef load_folder_file(file, fileNameRegExp='', allEntries=False):\n \"\"\"\n Returns an array with the contents (filtered by fileNameRegExp) of a ZIP file.\n The key's are the names or the file or the capturing group definied in the fileNameRegExp\n allEntries validates that all entries in the ZIP file pass the fileNameRegExp\n \"\"\"\n pairs = []\n for name in os.listdir(file):\n addFile = True\n keyName = name\n if fileNameRegExp != \"\":\n m = re.match(fileNameRegExp, name)\n if m == None:\n addFile = False\n else:\n if len(m.groups()) > 0:\n keyName = m.group(1)\n\n if addFile:\n pairs.append([keyName, open(os.path.join(file,name)).read()])\n else:\n if allEntries:\n raise Exception('ZIP entry not valid: %s' % name)\n\n return dict(pairs)\n\n\ndef decode_utf8(raw):\n \"\"\"\n Returns a Unicode object on success, or None on failure\n \"\"\"\n try:\n raw = codecs.decode(raw,'utf-8', 'replace')\n #extracts BOM if exists\n raw = raw.encode('utf8')\n if raw.startswith(codecs.BOM_UTF8):\n raw = raw.replace(codecs.BOM_UTF8, '', 1)\n return raw.decode('utf-8')\n except:\n return None\n \ndef validate_lines_in_file(fileName,file_contents,CRLF=True,LTRB=True,withTranscription=False,withConfidence=False,imWidth=0,imHeight=0):\n \"\"\"\n This function validates that all lines of the file calling the Line validation function for each line\n \"\"\"\n utf8File = decode_utf8(file_contents)\n if (utf8File is None) :\n raise Exception(\"The file %s is not UTF-8\" %fileName)\n\n lines = utf8File.split( \"\\r\\n\" if CRLF else \"\\n\" )\n for line in lines:\n line = line.replace(\"\\r\",\"\").replace(\"\\n\",\"\")\n if(line != \"\"):\n try:\n validate_tl_line(line,LTRB,withTranscription,withConfidence,imWidth,imHeight)\n except Exception as e:\n raise Exception((\"Line in sample not valid. Sample: %s Line: %s Error: %s\" %(fileName,line,str(e))).encode('utf-8', 'replace'))\n \n \n \ndef validate_tl_line(line,LTRB=True,withTranscription=True,withConfidence=True,imWidth=0,imHeight=0):\n \"\"\"\n Validate the format of the line. If the line is not valid an exception will be raised.\n If maxWidth and maxHeight are specified, all points must be inside the imgage bounds.\n Posible values are:\n LTRB=True: xmin,ymin,xmax,ymax[,confidence][,transcription] \n LTRB=False: x1,y1,x2,y2,x3,y3,x4,y4[,confidence][,transcription] \n \"\"\"\n get_tl_line_values(line,LTRB,withTranscription,withConfidence,imWidth,imHeight)\n \n \ndef get_tl_line_values(line,LTRB=True,withTranscription=False,withConfidence=False,imWidth=0,imHeight=0):\n \"\"\"\n Validate the format of the line. If the line is not valid an exception will be raised.\n If maxWidth and maxHeight are specified, all points must be inside the imgage bounds.\n Posible values are:\n LTRB=True: xmin,ymin,xmax,ymax[,confidence][,transcription] \n LTRB=False: x1,y1,x2,y2,x3,y3,x4,y4[,confidence][,transcription] \n Returns values from a textline. Points , [Confidences], [Transcriptions]\n \"\"\"\n confidence = 0.0\n transcription = \"\";\n points = []\n \n numPoints = 4;\n \n if LTRB:\n \n numPoints = 4;\n \n if withTranscription and withConfidence:\n m = re.match(r'^\\s*(-?[0-9]+)\\s*,\\s*(-?[0-9]+)\\s*,\\s*([0-9]+)\\s*,\\s*([0-9]+)\\s*,\\s*([0-1].?[0-9]*)\\s*,(.*)$',line)\n if m == None :\n m = re.match(r'^\\s*(-?[0-9]+)\\s*,\\s*(-?[0-9]+)\\s*,\\s*([0-9]+)\\s*,\\s*([0-9]+)\\s*,\\s*([0-1].?[0-9]*)\\s*,(.*)$',line)\n raise Exception(\"Format incorrect. Should be: xmin,ymin,xmax,ymax,confidence,transcription\")\n elif withConfidence:\n m = re.match(r'^\\s*(-?[0-9]+)\\s*,\\s*(-?[0-9]+)\\s*,\\s*([0-9]+)\\s*,\\s*([0-9]+)\\s*,\\s*([0-1].?[0-9]*)\\s*$',line)\n if m == None :\n raise Exception(\"Format incorrect. Should be: xmin,ymin,xmax,ymax,confidence\")\n elif withTranscription:\n m = re.match(r'^\\s*(-?[0-9]+)\\s*,\\s*(-?[0-9]+)\\s*,\\s*([0-9]+)\\s*,\\s*([0-9]+)\\s*,(.*)$',line)\n if m == None :\n raise Exception(\"Format incorrect. Should be: xmin,ymin,xmax,ymax,transcription\")\n else:\n m = re.match(r'^\\s*(-?[0-9]+)\\s*,\\s*(-?[0-9]+)\\s*,\\s*([0-9]+)\\s*,\\s*([0-9]+)\\s*,?\\s*$',line)\n if m == None :\n raise Exception(\"Format incorrect. Should be: xmin,ymin,xmax,ymax\")\n \n xmin = int(m.group(1))\n ymin = int(m.group(2))\n xmax = int(m.group(3))\n ymax = int(m.group(4))\n if(xmax<xmin):\n raise Exception(\"Xmax value (%s) not valid (Xmax < Xmin).\" %(xmax))\n if(ymax<ymin):\n raise Exception(\"Ymax value (%s) not valid (Ymax < Ymin).\" %(ymax)) \n\n points = [ float(m.group(i)) for i in range(1, (numPoints+1) ) ]\n \n if (imWidth>0 and imHeight>0):\n validate_point_inside_bounds(xmin,ymin,imWidth,imHeight);\n validate_point_inside_bounds(xmax,ymax,imWidth,imHeight);\n\n else:\n \n numPoints = 8;\n \n if withTranscription and withConfidence:\n m = re.match(r'^\\s*(-?[0-9]+)\\s*,\\s*(-?[0-9]+)\\s*,\\s*(-?[0-9]+)\\s*,\\s*(-?[0-9]+)\\s*,\\s*(-?[0-9]+)\\s*,\\s*(-?[0-9]+)\\s*,\\s*(-?[0-9]+)\\s*,\\s*(-?[0-9]+)\\s*,\\s*([0-1].?[0-9]*)\\s*,(.*)$',line)\n if m == None :\n raise Exception(\"Format incorrect. Should be: x1,y1,x2,y2,x3,y3,x4,y4,confidence,transcription\")\n elif withConfidence:\n m = re.match(r'^\\s*(-?[0-9]+)\\s*,\\s*(-?[0-9]+)\\s*,\\s*(-?[0-9]+)\\s*,\\s*(-?[0-9]+)\\s*,\\s*(-?[0-9]+)\\s*,\\s*(-?[0-9]+)\\s*,\\s*(-?[0-9]+)\\s*,\\s*(-?[0-9]+)\\s*,\\s*([0-1].?[0-9]*)\\s*$',line)\n if m == None :\n raise Exception(\"Format incorrect. Should be: x1,y1,x2,y2,x3,y3,x4,y4,confidence\")\n elif withTranscription:\n m = re.match(r'^\\s*(-?[0-9]+)\\s*,\\s*(-?[0-9]+)\\s*,\\s*(-?[0-9]+)\\s*,\\s*(-?[0-9]+)\\s*,\\s*(-?[0-9]+)\\s*,\\s*(-?[0-9]+)\\s*,\\s*(-?[0-9]+)\\s*,\\s*(-?[0-9]+)\\s*,(.*)$',line)\n if m == None :\n raise Exception(\"Format incorrect. Should be: x1,y1,x2,y2,x3,y3,x4,y4,transcription\")\n else:\n m = re.match(r'^\\s*(-?[0-9]+)\\s*,\\s*(-?[0-9]+)\\s*,\\s*(-?[0-9]+)\\s*,\\s*(-?[0-9]+)\\s*,\\s*(-?[0-9]+)\\s*,\\s*(-?[0-9]+)\\s*,\\s*(-?[0-9]+)\\s*,\\s*(-?[0-9]+)\\s*$',line)\n if m == None :\n raise Exception(\"Format incorrect. Should be: x1,y1,x2,y2,x3,y3,x4,y4\")\n \n points = [ float(m.group(i)) for i in range(1, (numPoints+1) ) ]\n \n validate_clockwise_points(points)\n \n if (imWidth>0 and imHeight>0):\n validate_point_inside_bounds(points[0],points[1],imWidth,imHeight);\n validate_point_inside_bounds(points[2],points[3],imWidth,imHeight);\n validate_point_inside_bounds(points[4],points[5],imWidth,imHeight);\n validate_point_inside_bounds(points[6],points[7],imWidth,imHeight);\n \n \n if withConfidence:\n try:\n confidence = float(m.group(numPoints+1))\n except ValueError:\n raise Exception(\"Confidence value must be a float\") \n \n if withTranscription:\n posTranscription = numPoints + (2 if withConfidence else 1)\n transcription = m.group(posTranscription)\n m2 = re.match(r'^\\s*\\\"(.*)\\\"\\s*$',transcription)\n if m2 != None : #Transcription with double quotes, we extract the value and replace escaped characters\n transcription = m2.group(1).replace(\"\\\\\\\\\", \"\\\\\").replace(\"\\\\\\\"\", \"\\\"\")\n \n return points,confidence,transcription\n \n \ndef validate_point_inside_bounds(x,y,imWidth,imHeight):\n if(x<0 or x>imWidth):\n raise Exception(\"X value (%s) not valid. Image dimensions: (%s,%s)\" %(xmin,imWidth,imHeight))\n if(y<0 or y>imHeight):\n raise Exception(\"Y value (%s) not valid. Image dimensions: (%s,%s) Sample: %s Line:%s\" %(ymin,imWidth,imHeight))\n\ndef validate_clockwise_points(points):\n \"\"\"\n Validates that the points that the 4 points that dlimite a polygon are in clockwise order.\n \"\"\"\n \n if len(points) != 8:\n raise Exception(\"Points list not valid.\" + str(len(points)))\n \n point = [\n [int(points[0]) , int(points[1])],\n [int(points[2]) , int(points[3])],\n [int(points[4]) , int(points[5])],\n [int(points[6]) , int(points[7])]\n ]\n edge = [\n ( point[1][0] - point[0][0])*( point[1][1] + point[0][1]),\n ( point[2][0] - point[1][0])*( point[2][1] + point[1][1]),\n ( point[3][0] - point[2][0])*( point[3][1] + point[2][1]),\n ( point[0][0] - point[3][0])*( point[0][1] + point[3][1])\n ]\n \n summatory = edge[0] + edge[1] + edge[2] + edge[3];\n if summatory>0:\n raise Exception(\"Points are not clockwise. The coordinates of bounding quadrilaterals have to be given in clockwise order. Regarding the correct interpretation of 'clockwise' remember that the image coordinate system used is the standard one, with the image origin at the upper left, the X axis extending to the right and Y axis extending downwards.\")\n\ndef get_tl_line_values_from_file_contents(content,CRLF=True,LTRB=True,withTranscription=False,withConfidence=False,imWidth=0,imHeight=0,sort_by_confidences=True):\n \"\"\"\n Returns all points, confindences and transcriptions of a file in lists. Valid line formats:\n xmin,ymin,xmax,ymax,[confidence],[transcription]\n x1,y1,x2,y2,x3,y3,x4,y4,[confidence],[transcription]\n \"\"\"\n pointsList = []\n transcriptionsList = []\n confidencesList = []\n \n lines = content.split( \"\\r\\n\" if CRLF else \"\\n\" )\n for line in lines:\n line = line.replace(\"\\r\",\"\").replace(\"\\n\",\"\")\n if(line != \"\") :\n points, confidence, transcription = get_tl_line_values(line,LTRB,withTranscription,withConfidence,imWidth,imHeight);\n pointsList.append(points)\n transcriptionsList.append(transcription)\n confidencesList.append(confidence)\n\n if withConfidence and len(confidencesList)>0 and sort_by_confidences:\n import numpy as np\n sorted_ind = np.argsort(-np.array(confidencesList))\n confidencesList = [confidencesList[i] for i in sorted_ind]\n pointsList = [pointsList[i] for i in sorted_ind]\n transcriptionsList = [transcriptionsList[i] for i in sorted_ind] \n \n return pointsList,confidencesList,transcriptionsList\n\ndef main_evaluation(p,default_evaluation_params_fn,validate_data_fn,evaluate_method_fn,show_result=True,per_sample=True):\n \"\"\"\n This process validates a method, evaluates it and if it succed generates a ZIP file with a JSON entry for each sample.\n Params:\n p: Dictionary of parmeters with the GT/submission locations. If None is passed, the parameters send by the system are used.\n default_evaluation_params_fn: points to a function that returns a dictionary with the default parameters used for the evaluation\n validate_data_fn: points to a method that validates the corrct format of the submission\n evaluate_method_fn: points to a function that evaluated the submission and return a Dictionary with the results\n \"\"\"\n evalParams = default_evaluation_params_fn()\n if 'p' in p.keys():\n evalParams.update( p['p'] if isinstance(p['p'], dict) else json.loads(p['p'][1:-1]) )\n\n resDict={'calculated':True,'Message':'','method':'{}','per_sample':'{}'} \n try:\n # validate_data_fn(p['g'], p['s'], evalParams)\n evalData = evaluate_method_fn(p['g'], p['s'], evalParams)\n resDict.update(evalData)\n \n except Exception as e:\n traceback.print_exc()\n resDict['Message']= str(e)\n resDict['calculated']=False\n\n if 'o' in p:\n if not os.path.exists(p['o']):\n os.makedirs(p['o'])\n\n resultsOutputname = p['o'] + '/results.zip'\n outZip = zipfile.ZipFile(resultsOutputname, mode='w', allowZip64=True)\n\n del resDict['per_sample']\n if 'output_items' in resDict.keys():\n del resDict['output_items']\n\n outZip.writestr('method.json',json.dumps(resDict))\n \n if not resDict['calculated']:\n if show_result:\n sys.stderr.write('Error!\\n'+ resDict['Message']+'\\n\\n')\n if 'o' in p:\n outZip.close()\n return resDict\n \n if 'o' in p:\n if per_sample == True:\n for k,v in evalData['per_sample'].iteritems():\n outZip.writestr( k + '.json',json.dumps(v)) \n\n if 'output_items' in evalData.keys():\n for k, v in evalData['output_items'].iteritems():\n outZip.writestr( k,v) \n\n outZip.close()\n\n if show_result:\n sys.stdout.write(\"Calculated!\")\n sys.stdout.write(json.dumps(resDict['method']))\n \n return resDict\n\n\ndef main_validation(default_evaluation_params_fn,validate_data_fn):\n \"\"\"\n This process validates a method\n Params:\n default_evaluation_params_fn: points to a function that returns a dictionary with the default parameters used for the evaluation\n validate_data_fn: points to a method that validates the corrct format of the submission\n \"\"\" \n try:\n p = dict([s[1:].split('=') for s in sys.argv[1:]])\n evalParams = default_evaluation_params_fn()\n if 'p' in p.keys():\n evalParams.update( p['p'] if isinstance(p['p'], dict) else json.loads(p['p'][1:-1]) )\n\n validate_data_fn(p['g'], p['s'], evalParams) \n print('SUCCESS')\n sys.exit(0)\n except Exception as e:\n print(str(e))\n sys.exit(101)" ]
[ [ "numpy.abs", "numpy.rad2deg", "numpy.ones", "numpy.argmax", "numpy.mean", "scipy.stats.mode", "numpy.array" ], [ "numpy.array" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [ "0.13", "1.6", "0.14", "1.10", "0.15", "1.4", "0.16", "1.9", "0.19", "1.5", "0.18", "1.2", "1.7", "0.12", "1.0", "0.17", "1.3", "1.8" ], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
CHEN-Zhaohui/geoist
[ "06a00db3e0ed3d92abf3e45b7b3bfbef6a858a5b", "06a00db3e0ed3d92abf3e45b7b3bfbef6a858a5b", "06a00db3e0ed3d92abf3e45b7b3bfbef6a858a5b", "06a00db3e0ed3d92abf3e45b7b3bfbef6a858a5b", "06a00db3e0ed3d92abf3e45b7b3bfbef6a858a5b", "06a00db3e0ed3d92abf3e45b7b3bfbef6a858a5b", "06a00db3e0ed3d92abf3e45b7b3bfbef6a858a5b" ]
[ "geoist/gridder/interpolation.py", "examples/vis_giplt_2d.py", "geoist/gridder/tests/test_slicing.py", "geoist/catalog/Seismicity.py", "examples/pfm_transform_deriv.py", "examples/forward_modeling_sphere_gravity.py", "geoist/inversion/grawavelet.py" ]
[ "# -*- coding: utf-8 -*-\n\"\"\"\n Name : interpolation.py\n Created on : 2018/11/24 08:57\n Author : Steve Chen <[email protected]>\n Affiliation : Institute of Geophysics, CEA.\n Version : 0.1.0\n Copyright : Copyright (C) 2018-2020 GEOIST Development Team. All Rights Reserved.\n License : Distributed under the MIT License. See LICENSE.txt for more info.\n Github : https://igp-gravity.github.io/\n Description : 2D interpolation, griding, and profile extraction.\n\n\"\"\"\n\nimport numpy as np\nimport scipy.interpolate\n\nfrom .genpnt import regular\n\n\ndef fill_nans(x, y, v, xp, yp, vp):\n \"\"\"\"\n Fill in the NaNs or masked values on interpolated points using nearest\n neighbors.\n\n .. warning::\n\n Operation is performed in place. Replaces the NaN or masked values of\n the original array!\n\n Parameters:\n\n * x, y : 1D arrays\n Arrays with the x and y coordinates of the original data points (not\n interpolated).\n * v : 1D array\n Array with the scalar value assigned to the data points (not\n interpolated).\n * xp, yp : 1D arrays\n Points where the data values were interpolated.\n * vp : 1D array\n Interpolated data values (the one that has NaNs or masked values to\n replace).\n\n \"\"\"\n if np.ma.is_masked(vp):\n nans = vp.mask\n else:\n nans = np.isnan(vp)\n vp[nans] = scipy.interpolate.griddata((x, y), v, (xp[nans], yp[nans]),\n method='nearest').ravel()\n\n\ndef interp_at(x, y, v, xp, yp, algorithm='cubic', extrapolate=False):\n \"\"\"\n Interpolate spacial data onto specified points.\n\n Wraps ``scipy.interpolate.griddata``.\n\n Parameters:\n\n * x, y : 1D arrays\n Arrays with the x and y coordinates of the data points.\n * v : 1D array\n Array with the scalar value assigned to the data points.\n * xp, yp : 1D arrays\n Points where the data values will be interpolated\n * algorithm : string\n Interpolation algorithm. Either ``'cubic'``, ``'nearest'``,\n ``'linear'`` (see scipy.interpolate.griddata)\n * extrapolate : True or False\n If True, will extrapolate values outside of the convex hull of the data\n points.\n\n Returns:\n\n * v : 1D array\n 1D array with the interpolated v values.\n\n \"\"\"\n vp = scipy.interpolate.griddata((x, y), v, (xp, yp),\n method=algorithm).ravel()\n if extrapolate and algorithm != 'nearest' and np.any(np.isnan(vp)):\n fill_nans(x, y, v, xp, yp, vp)\n return vp\n\n\ndef interp(x, y, v, shape, area=None, algorithm='cubic', extrapolate=False):\n \"\"\"\n Interpolate spacial data onto a regular grid.\n\n Utility function that generates a regular grid with\n :func:`~fatiando.gridder.regular` and calls\n :func:`~fatiando.gridder.interp_at` on the generated points.\n\n Parameters:\n\n * x, y : 1D arrays\n Arrays with the x and y coordinates of the data points.\n * v : 1D array\n Array with the scalar value assigned to the data points.\n * shape : tuple = (nx, ny)\n Shape of the interpolated regular grid, ie (nx, ny).\n * area : tuple = (x1, x2, y1, y2)\n The are where the data will be interpolated. If None, then will get the\n area from *x* and *y*.\n * algorithm : string\n Interpolation algorithm. Either ``'cubic'``, ``'nearest'``,\n ``'linear'`` (see scipy.interpolate.griddata).\n * extrapolate : True or False\n If True, will extrapolate values outside of the convex hull of the data\n points.\n\n Returns:\n\n * ``[x, y, v]``\n Three 1D arrays with the interpolated x, y, and v\n\n \"\"\"\n if area is None:\n area = (x.min(), x.max(), y.min(), y.max())\n x1, x2, y1, y2 = area\n xp, yp = regular(area, shape)\n vp = interp_at(x, y, v, xp, yp, algorithm=algorithm,\n extrapolate=extrapolate)\n return xp, yp, vp\n\n\ndef profile(x, y, v, point1, point2, size, algorithm='cubic'):\n \"\"\"\n Extract a profile between 2 points from spacial data.\n\n Uses interpolation to calculate the data values at the profile points.\n\n Parameters:\n\n * x, y : 1D arrays\n Arrays with the x and y coordinates of the data points.\n * v : 1D array\n Array with the scalar value assigned to the data points.\n * point1, point2 : lists = [x, y]\n Lists the x, y coordinates of the 2 points between which the profile\n will be extracted.\n * size : int\n Number of points along the profile.\n * algorithm : string\n Interpolation algorithm. Either ``'cubic'``, ``'nearest'``,\n ``'linear'`` (see scipy.interpolate.griddata).\n\n Returns:\n\n * [xp, yp, distances, vp] : 1d arrays\n ``xp`` and ``yp`` are the x, y coordinates of the points along the\n profile. ``distances`` are the distances of the profile points from\n ``point1``. ``vp`` are the data points along the profile.\n\n \"\"\"\n x1, y1 = point1\n x2, y2 = point2\n maxdist = np.sqrt((x1 - x2)**2 + (y1 - y2)**2)\n distances = np.linspace(0, maxdist, size)\n angle = np.arctan2(y2 - y1, x2 - x1)\n xp = x1 + distances*np.cos(angle)\n yp = y1 + distances*np.sin(angle)\n vp = interp_at(x, y, v, xp, yp, algorithm=algorithm, extrapolate=True)\n return xp, yp, distances, vp\n", "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Dec 2 11:36:59 2018\n使用giplt画等值线图\n@author: chens\n\"\"\"\nfrom geoist import gridder\nimport matplotlib.pyplot as plt\nfrom geoist.vis import giplt\n\narea = [-20, 20, -50, 50]\nx, y = gridder.scatter(area, n=100)\ndata = x**2 + y**2\nplt.figure()\nplt.axis('scaled')\ngiplt.contourf(y, x, data, shape=(50, 50), levels=30, interp=True)\nplt.colorbar(orientation='horizontal')\nplt.plot(y, x, '.k')\nplt.xlabel('y (East-West)')\nplt.ylabel('x (North-South)')\nplt.show()\n", "import numpy.testing as npt\nimport numpy as np\n\nfrom ... import gridder\n\n\ndef test_inside():\n \"gridder.inside returns correct results for simple input\"\n x = np.array([1, 2, 3, 4, 5, 6])\n y = np.array([10, 11, 12, 13, 14, 15])\n area = [2.5, 5.5, 12, 15]\n is_inside = gridder.inside(x, y, area)\n assert np.all(is_inside == [False, False, True, True, True, False])\n # Test 2D arrays as well\n x = np.array([[1, 1, 1],\n [2, 2, 2],\n [3, 3, 3]])\n y = np.array([[5, 7, 9],\n [5, 7, 9],\n [5, 7, 9]])\n area = [0.5, 2.5, 7, 9]\n is_inside = gridder.inside(x, y, area)\n truth = [[False, True, True], [False, True, True], [False, False, False]]\n assert np.all(is_inside == truth)\n # Test some large arrays of random points inside an area\n area = (-1035, 255, 0.2345, 23355)\n x, y = gridder.scatter((-1035, 255, 0.2345, 23355), n=10000, seed=0)\n assert np.all(gridder.inside(x, y, area))\n\n\ndef test_cut():\n \"Cutting a grid works for simple grids\"\n x = np.array([1, 2, 3, 4, 5, 6])\n y = np.array([10, 11, 12, 13, 14, 15])\n data = np.array([42, 65, 92, 24, 135, 456])\n area = [2.5, 5.5, 12, 15]\n xs, ys, [datas] = gridder.cut(x, y, [data], area)\n npt.assert_allclose(xs, [3, 4, 5])\n npt.assert_allclose(ys, [12, 13, 14])\n npt.assert_allclose(datas, [92, 24, 135])\n # Test on 2D arrays\n x = np.array([[1, 1, 1],\n [2, 2, 2],\n [3, 3, 3]])\n y = np.array([[5, 7, 9],\n [5, 7, 9],\n [5, 7, 9]])\n data = np.array([[12, 84, 53],\n [43, 79, 29],\n [45, 27, 10]])\n area = [0.5, 2.5, 7, 9]\n xs, ys, [datas] = gridder.cut(x, y, [data], area)\n npt.assert_allclose(xs, [1, 1, 2, 2])\n npt.assert_allclose(ys, [7, 9, 7, 9])\n npt.assert_allclose(datas, [84, 53, 79, 29])\n", "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport numpy as np\nimport scipy.optimize as spo\nimport matplotlib.pyplot as plt\n\nfrom . import Selection as Sel\n\n#-----------------------------------------------------------------------------------------\n\ndef TableMerge(M0, M1, Y0, Y1):\n \"\"\"\n Utility to assemble a completeness table from arrays\n \"\"\"\n\n CompTable = []\n\n for m0, m1, y0, y1 in zip(M0, M1, Y0, Y1):\n CompTable.append([m0, m1, y0, y1])\n\n return CompTable\n\n\ndef TableSplit(CompTable):\n \"\"\"\n Utility to split a completeness table into arrays\n \"\"\"\n\n M0 = [m[0] for m in CompTable]\n M1 = [m[1] for m in CompTable]\n Y0 = [m[2] for m in CompTable]\n Y1 = [m[3] for m in CompTable]\n\n return M0, M1, Y0, Y1\n\n#-----------------------------------------------------------------------------------------\n\ndef GetEventRates(Db, CompTable, Area=1.):\n \"\"\"\n Method to compute observed annual rates (incremental and cumulative) from a given\n completeness table. In this implementation, completeness is one window per\n magnitude bin in M. Example:\n CompTable = [[4.50, 0.25, 2000., 2013.],\n [4.75, 0.25, 1980., 2013.],\n [5.00, 0.25, 1970., 2013.],\n [5.25, 0.25, 1960., 2013.],\n [5.50, 0.50, 1950., 2013.],\n [6.00, 1.50, 1901., 2013.]]\n \"\"\"\n\n Enum = []\n Data = [[],[]]\n\n for CT in CompTable:\n\n MinM = CT[0]\n MaxM = CT[0]+CT[1]\n MinY = CT[2]\n MaxY = CT[3]\n\n # Catalogue selection (Magnitude-Year)\n DbM = Sel.MagRangeSelect(Db, MinM, MaxM)\n DbY = Sel.TimeSelect(DbM, MinY, MaxY)\n\n # Computing incremental rates\n RY = float(DbY.Size())/float(MaxY-MinY)\n Enum.append(RY/float(Area))\n\n # Data per magnitude bin\n Data[0].append(DbY.Extract(Key='Year'))\n Data[1].append(DbY.Extract(Key='MagSize'))\n\n # Cumulative distribution\n Ecum = np.cumsum(Enum[::-1])[::-1]\n\n return Enum, Ecum, Data\n\n#-----------------------------------------------------------------------------------------\n\ndef MfdCum(a, b, Mbin, Mmax):\n \"\"\"\n Cumulative MFD (Truncated Gutenberg-Richter)\n \"\"\"\n\n Mbin = np.array(Mbin)\n\n Enum = (10.**a)*(10.**(-b*Mbin)-10.**(-b*Mmax))\n\n # If M > Mmax, remove negative rates\n Enum[Enum < 0] = 0\n\n return Enum\n\n#-----------------------------------------------------------------------------------------\n\ndef MfdInc(a, b, Mbin, Minc, Mmax):\n \"\"\"\n Incremental MFD (for discrete magnitude intervals).\n \"\"\"\n\n Mbin = np.array(Mbin)\n Minc = np.array(Minc)\n\n Enum0 = MfdCum(a, b, Mbin, Mmax)\n Enum1 = MfdCum(a, b, Mbin+Minc, Mmax)\n\n return (Enum0-Enum1)\n\n#-----------------------------------------------------------------------------------------\n\ndef MfdFit(ab, Enum, Mbin, Minc, Mmax, Merr, bfix=[]):\n \"\"\"\n Misfit function (log normal)\n \"\"\"\n\n # Target coefficients\n a = ab[0]\n\n if not bfix:\n b = ab[1]\n else:\n b = bfix\n\n # Analytical distribution\n Esyn = MfdInc(a, b, Mbin, Minc, Mmax)\n\n # Avoid log of 0\n Esyn[Esyn <= 0] = 1e-300\n\n Eres = np.log10(Enum/Esyn)\n\n # L2-norm\n Mfit = np.sum((Eres/Merr)**2.)\n\n return Mfit\n\n#-----------------------------------------------------------------------------------------\n\ndef MfdOptimize(Enum, Mbin, Minc, Mmax, Merr=[], a0=[], b0=[], bfix=[]):\n \"\"\"\n Optimisation function\n Note: Minc and Merr can be single (constant) values or array\n \"\"\"\n\n # Convert to numpy array\n Enum = np.array(Enum)\n Mbin = np.array(Mbin)\n Minc = np.array(Minc)\n Merr = np.array(Merr)\n\n # Setting initial values for the search\n if not a0: a0 = 10.\n if not b0: b0 = 1.\n\n if Merr.size == 0:\n Merr = np.ones_like(Enum)\n if Merr.size == 1:\n Merr = Merr * np.ones_like(Enum)\n if Minc.size == 1:\n Minc = Minc * np.ones_like(Enum)\n\n # Remove zero rate bins\n idx = (Enum > 0.0)\n Enum = Enum[idx]\n Mbin = Mbin[idx]\n Minc = Minc[idx]\n Merr = Merr[idx]\n\n # Optimization of GR coefficients\n Out = spo.minimize(MfdFit, [a0, b0], args=(Enum, Mbin, Minc, Mmax, Merr, bfix))\n\n a = Out.x[0]\n b = Out.x[1]\n\n if bfix:\n b = bfix\n\n return a, b\n\n#-------------------------------------------\n# Plot results\n\ndef MfdPlot(a, b, Mmax, Enum=[], Ecum=[], Mbin=[], Minc=[], OutFile=[]):\n\n # Convert to numpy array\n Enum = np.array(Enum)\n Mbin = np.array(Mbin)\n Minc = np.array(Minc)\n\n # Plot\n plt.figure(figsize=(6,4))\n\n # Observed Incremental rates\n if any(Enum) and any(Mbin) and any(Minc):\n plt.bar(Mbin, Enum, Minc, edgecolor=[[0,0,0] for i in range(0,len(Mbin))],\n color=[0.9,0.9,0.9],\n linewidth=1,\n label='Observed Incremental',\n align='edge',\n log=True,\n zorder=1)\n\n # Observed Cumulative rates\n if any(Enum) and any(Mbin):\n plt.plot(Mbin, Ecum, 'o', color=[1,0,0],\n markersize=6,\n markeredgecolor=[0,0,0],\n linewidth=2,\n label='Observed Cumulative',\n zorder=4)\n\n # Inverted Incremental rates\n Ninc = MfdInc(a, b, Mbin, Minc, Mmax)\n plt.plot(Mbin+Minc/2., Ninc, 's', color=[1,1,1],\n markersize=8,\n markeredgecolor=[0,0,0],\n linewidth=2,\n label='Inverted Incremental',\n zorder=3)\n\n # Inverted Cumulative rates\n Maxs = np.arange(min(Mbin), Mmax, 0.0001)\n Ncum = MfdCum(a, b, Maxs, Mmax)\n plt.plot(Maxs, Ncum, color=[1,0,0],\n linewidth=2,\n label='Inverted Cumulative',\n zorder=2)\n\n plt.title('Truncated G-R Distribution')\n plt.legend(loc=1, borderaxespad=0., numpoints=1)\n\n plt.xlabel('Magnitude')\n plt.ylabel('Occurrence Rate (Event/Year)')\n\n plt.gca().yaxis.grid(color='0.65',linestyle='--')\n plt.tight_layout()\n\n plt.xlim((min(Mbin)-0.5, Mmax+0.5))\n plt.ylim((0.01*min(Enum), 10*max(Ncum)))\n\n plt.show(block=False)\n\n if OutFile:\n plt.savefig(OutFile, bbox_inches='tight', dpi=150)\n\n", "\"\"\"\nGravMag: Calculating the derivatives of the gravity anomaly using FFT\n\"\"\"\nimport matplotlib.pyplot as plt\nfrom geoist import gridder\nfrom geoist.inversion import geometry\nfrom geoist.pfm import prism, pftrans, giutils\nfrom geoist.vis import giplt\n\nmodel = [geometry.Prism(-1000, 1000, -1000, 1000, 0, 2000, {'density': 100})]\narea = (-5000, 5000, -5000, 5000)\nshape = (51, 51)\nz0 = -500\nxp, yp, zp = gridder.regular(area, shape, z=z0)\ngz = giutils.contaminate(prism.gz(xp, yp, zp, model), 0.001)\n\n# Need to convert gz to SI units so that the result can be converted to Eotvos\ngxz = giutils.si2eotvos(pftrans.derivx(xp, yp, giutils.mgal2si(gz), shape))\ngyz = giutils.si2eotvos(pftrans.derivy(xp, yp, giutils.mgal2si(gz), shape))\ngzz = giutils.si2eotvos(pftrans.derivz(xp, yp, giutils.mgal2si(gz), shape))\n\ngxz_true = prism.gxz(xp, yp, zp, model)\ngyz_true = prism.gyz(xp, yp, zp, model)\ngzz_true = prism.gzz(xp, yp, zp, model)\n\nplt.figure()\nplt.title(\"Original gravity anomaly\")\nplt.axis('scaled')\ngiplt.contourf(xp, yp, gz, shape, 15)\nplt.colorbar(shrink=0.7)\ngiplt.m2km()\n\nplt.figure(figsize=(14, 10))\nplt.subplots_adjust(top=0.95, left=0.05, right=0.95)\nplt.subplot(2, 3, 1)\nplt.title(\"x deriv (contour) + true (color map)\")\nplt.axis('scaled')\nlevels = giplt.contourf(yp, xp, gxz_true, shape, 12)\nplt.colorbar(shrink=0.7)\ngiplt.contour(yp, xp, gxz, shape, 12, color='k')\ngiplt.m2km()\nplt.subplot(2, 3, 2)\nplt.title(\"y deriv (contour) + true (color map)\")\nplt.axis('scaled')\nlevels = giplt.contourf(yp, xp, gyz_true, shape, 12)\nplt.colorbar(shrink=0.7)\ngiplt.contour(yp, xp, gyz, shape, 12, color='k')\ngiplt.m2km()\nplt.subplot(2, 3, 3)\nplt.title(\"z deriv (contour) + true (color map)\")\nplt.axis('scaled')\nlevels = giplt.contourf(yp, xp, gzz_true, shape, 8)\nplt.colorbar(shrink=0.7)\ngiplt.contour(yp, xp, gzz, shape, levels, color='k')\ngiplt.m2km()\nplt.subplot(2, 3, 4)\nplt.title(\"Difference x deriv\")\nplt.axis('scaled')\ngiplt.pcolor(yp, xp, (gxz_true - gxz), shape)\nplt.colorbar(shrink=0.7)\ngiplt.m2km()\nplt.subplot(2, 3, 5)\nplt.title(\"Difference y deriv\")\nplt.axis('scaled')\ngiplt.pcolor(yp, xp, (gyz_true - gyz), shape)\nplt.colorbar(shrink=0.7)\ngiplt.m2km()\nplt.subplot(2, 3, 6)\nplt.title(\"Difference z deriv\")\nplt.axis('scaled')\ngiplt.pcolor(yp, xp, (gzz_true - gzz), shape)\nplt.colorbar(shrink=0.7)\ngiplt.m2km()\nplt.show()\n", "\"\"\"\nForward modeling gravity data using spheres in Cartesian coordinates\n--------------------------------------------------------------------\n\nThe :mod:`fatiando.gravmag` has many functions for forward modeling gravity and\nmagnetic data. Here we'll show how to build a model out of spheres and\ncalculate the gravitational attraction and it's gradients in Cartesian\ncoordinates.\n\n\"\"\"\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nfrom geoist.pfm import sphere, giutils\nfrom geoist import gridder\nfrom geoist.inversion import geometry\nfrom geoist.vis import giplt\n\n# Create a model using geometric objects from fatiando.mesher\n# Each model element has a dictionary with its physical properties.\n# We'll use two spheres with opposite density contrast values.\nmodel = [geometry.Sphere(x=10e3, y=10e3, z=1.5e3, radius=1.5e3,\n props={'density': 500}),\n geometry.Sphere(x=20e3, y=20e3, z=1.5e3, radius=1.5e3,\n props={'density': -500})]\n\n# Create a regular grid at a constant height\nshape = (300, 300)\narea = [0, 30e3, 0, 30e3]\nx, y, z = gridder.regular(area, shape, z=-100)\n\nfields = [\n ['Gravity (mGal)', sphere.gz(x, y, z, model)],\n ['gxx (Eotvos)', sphere.gxx(x, y, z, model)],\n ['gyy (Eotvos)', sphere.gyy(x, y, z, model)],\n ['gzz (Eotvos)', sphere.gzz(x, y, z, model)],\n ['gxy (Eotvos)', sphere.gxy(x, y, z, model)],\n ['gxz (Eotvos)', sphere.gxz(x, y, z, model)],\n ['gyz (Eotvos)', sphere.gyz(x, y, z, model)],\n]\n\n# Make maps of all fields calculated\nfig = plt.figure(figsize=(10, 8))\nplt.rcParams['font.size'] = 10\nX, Y = x.reshape(shape)/1000, y.reshape(shape)/1000\nfor i, tmp in enumerate(fields):\n ax = plt.subplot(3, 3, i + 3)\n field, data = tmp\n scale = np.abs([data.min(), data.max()]).max()\n ax.set_title(field)\n plot = ax.pcolormesh(Y, X, data.reshape(shape), cmap='RdBu_r',\n vmin=-scale, vmax=scale)\n plt.colorbar(plot, ax=ax, aspect=30, pad=0)\n ax.set_xlabel('y (km)')\n ax.set_ylabel('x (km)')\nplt.tight_layout(pad=0.5)\nplt.show()\n", "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Mar 10 20:49:28 2019\n\n@author: chens\n\"\"\"\nimport numpy as np\n\ndef walshMatrix(n, normalized=False):\n # Allow only size n of power 2\n n = 2**np.ceil(np.log2(n))\n n = int(n)\n h = np.zeros((n,n))\n j = 0\n for i in range(n):\n if i <= n/2 - 1:\n h[i,j] = 0.5\n h[i,j+1] = 0.5\n j = j + 2\n else:\n if i == n/2:\n j = 0\n h[i,j] = 0.5\n h[i,j+1] = -0.5 \n j = j + 2\n if normalized: \n h = np.mat(np.sqrt(2)*h)\n else:\n h = np.mat(h)\n h0 = np.mat(np.eye(n))\n for k in range(int(np.log2(n))):\n h0 = h0*h\n return h0, h\n\nif __name__ == '__main__':\n from scipy import sparse\n nn = 512\n ax, ax0 = walshMatrix(nn, normalized=True)\n sax0 = sparse.csr_matrix(ax0)\n #ax, ax0 = np.mat(walshMatrix(nn, normalized=True))\n \n# wm = []\n# for k in range(1,9):\n# wm = np.hstack((wm,k*np.ones(64))) \n# wm = np.mat(np.diag(wm))\n# mref = wm*np.eye(nn, dtype=int)\n# ggz0 = np.mat(np.loadtxt('d:\\\\ggz888.dat'))\n# ggz = np.vstack((ggz0,mref))\n# d2 = ax*ggz.T*ggz*ax.T\n# gz0 = np.mat(np.loadtxt('d:\\\\gz888.dat')).T\n# obsref = np.mat(np.zeros(nn))\n# gz = np.vstack((gz0,obsref.T))\n# gzw = ax*ggz.T*gz\n# d3 = np.where(np.abs(d2) > 1.0e-10, d2, 0)\n# print(len(np.nonzero(d3)[0])) #非零元素\n# if np.allclose(d3, d3.T, atol=1e-8):\n# print('压缩后的矩阵对称')\n# g4 = np.where(np.abs(gzw) > 1.0e-10, gzw, 0)\n# print(len(np.nonzero(g4)[0]))\n# m1 = np.linalg.solve(d3, g4)\n# m2 = ax*m1\n# np.savetxt(\"d:\\\\walshinv\\\\m2.txt\", m2)\n# if np.allclose(ggz0*m2, gz0, atol=1e-2):\n# print('Result is right')\n# x1 = ggz0*m2-gz0\n# print(np.sqrt(x1.T*x1))\n# else:\n# x1 = ggz0*m2-gz0\n# print(np.sqrt(x1.T*x1))\n# m3 = np.linalg.lstsq(ggz, gz, rcond=None)\n# np.savetxt(\"d:\\\\walshinv\\\\m3.txt\", m3[0])\n# print(np.allclose(ggz*m3[0], gz)) " ]
[ [ "numpy.sqrt", "numpy.linspace", "numpy.isnan", "numpy.cos", "numpy.sin", "numpy.arctan2", "numpy.ma.is_masked" ], [ "matplotlib.pyplot.plot", "matplotlib.pyplot.colorbar", "matplotlib.pyplot.ylabel", "matplotlib.pyplot.axis", "matplotlib.pyplot.xlabel", "matplotlib.pyplot.show", "matplotlib.pyplot.figure" ], [ "numpy.all", "numpy.array", "numpy.testing.assert_allclose" ], [ "matplotlib.pyplot.legend", "matplotlib.pyplot.gca", "matplotlib.pyplot.tight_layout", "numpy.ones_like", "matplotlib.pyplot.title", "numpy.cumsum", "matplotlib.pyplot.savefig", "matplotlib.pyplot.plot", "matplotlib.pyplot.ylabel", "numpy.log10", "scipy.optimize.minimize", "matplotlib.pyplot.xlabel", "numpy.array", "numpy.sum", "matplotlib.pyplot.show", "matplotlib.pyplot.figure" ], [ "matplotlib.pyplot.title", "matplotlib.pyplot.colorbar", "matplotlib.pyplot.subplot", "matplotlib.pyplot.axis", "matplotlib.pyplot.subplots_adjust", "matplotlib.pyplot.show", "matplotlib.pyplot.figure" ], [ "matplotlib.pyplot.tight_layout", "matplotlib.pyplot.colorbar", "matplotlib.pyplot.subplot", "matplotlib.pyplot.show", "matplotlib.pyplot.figure" ], [ "numpy.log2", "numpy.sqrt", "numpy.eye", "scipy.sparse.csr_matrix", "numpy.mat", "numpy.zeros" ] ]
[ { "matplotlib": [], "numpy": [ "1.10", "1.12", "1.11", "1.19", "1.13", "1.16", "1.9", "1.18", "1.20", "1.7", "1.15", "1.14", "1.17", "1.8" ], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [ "0.13", "1.6", "0.14", "1.10", "0.15", "1.4", "0.16", "1.9", "0.19", "1.5", "0.18", "1.2", "1.7", "0.12", "1.0", "0.17", "1.3", "1.8" ], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [ "1.7", "1.0", "0.10", "1.2", "0.14", "0.19", "1.5", "0.12", "0.17", "0.13", "1.6", "1.4", "1.9", "1.3", "1.10", "0.15", "0.18", "0.16", "1.8" ], "tensorflow": [] } ]
hillarypan/pymatgen
[ "6b14109d59867331a48cd0986200094fd36dcfbb" ]
[ "pymatgen/io/vasp/outputs.py" ]
[ "# coding: utf-8\n# Copyright (c) Pymatgen Development Team.\n# Distributed under the terms of the MIT License.\n\nfrom __future__ import division, unicode_literals, print_function\n\nimport json\nimport glob\nimport itertools\nimport logging\nimport math\nimport os\nimport re\nimport warnings\nimport xml.etree.cElementTree as ET\nfrom collections import defaultdict\nfrom io import StringIO\n\nimport numpy as np\nfrom monty.io import zopen, reverse_readfile\nfrom monty.json import MSONable\nfrom monty.json import jsanitize\nfrom monty.re import regrep\nfrom six import string_types\nfrom six.moves import map, zip\n\nfrom pymatgen.core.composition import Composition\nfrom pymatgen.core.lattice import Lattice\nfrom pymatgen.core.periodic_table import Element\nfrom pymatgen.core.structure import Structure\nfrom pymatgen.core.units import unitized\nfrom pymatgen.electronic_structure.bandstructure import BandStructure, \\\n BandStructureSymmLine, get_reconstructed_band_structure\nfrom pymatgen.electronic_structure.core import Spin, Orbital, OrbitalType, Magmom\nfrom pymatgen.electronic_structure.dos import CompleteDos, Dos\nfrom pymatgen.entries.computed_entries import \\\n ComputedEntry, ComputedStructureEntry\nfrom pymatgen.io.vasp.inputs import Incar, Kpoints, Poscar, Potcar\nfrom pymatgen.util.io_utils import clean_lines, micro_pyawk\nfrom pymatgen.util.num import make_symmetric_matrix_from_upper_tri\n\n\"\"\"\nClasses for reading/manipulating/writing VASP ouput files.\n\"\"\"\n\n__author__ = \"Shyue Ping Ong, Geoffroy Hautier, Rickard Armiento, \" + \\\n \"Vincent L Chevrier, Ioannis Petousis, Stephen Dacek, Mark Turiansky\"\n__credits__ = \"Anubhav Jain\"\n__copyright__ = \"Copyright 2011, The Materials Project\"\n__version__ = \"1.2\"\n__maintainer__ = \"Shyue Ping Ong\"\n__email__ = \"[email protected]\"\n__status__ = \"Production\"\n__date__ = \"Nov 30, 2012\"\n\nlogger = logging.getLogger(__name__)\n\n\ndef _parse_parameters(val_type, val):\n \"\"\"\n Helper function to convert a Vasprun parameter into the proper type.\n Boolean, int and float types are converted.\n\n Args:\n val_type: Value type parsed from vasprun.xml.\n val: Actual string value parsed for vasprun.xml.\n \"\"\"\n if val_type == \"logical\":\n return val == \"T\"\n elif val_type == \"int\":\n return int(val)\n elif val_type == \"string\":\n return val.strip()\n else:\n return float(val)\n\n\ndef _parse_v_parameters(val_type, val, filename, param_name):\n \"\"\"\n Helper function to convert a Vasprun array-type parameter into the proper\n type. Boolean, int and float types are converted.\n\n Args:\n val_type: Value type parsed from vasprun.xml.\n val: Actual string value parsed for vasprun.xml.\n filename: Fullpath of vasprun.xml. Used for robust error handling.\n E.g., if vasprun.xml contains \\\\*\\\\*\\\\* for some Incar parameters,\n the code will try to read from an INCAR file present in the same\n directory.\n param_name: Name of parameter.\n\n Returns:\n Parsed value.\n \"\"\"\n if val_type == \"logical\":\n val = [i == \"T\" for i in val.split()]\n elif val_type == \"int\":\n try:\n val = [int(i) for i in val.split()]\n except ValueError:\n # Fix for stupid error in vasprun sometimes which displays\n # LDAUL/J as 2****\n val = _parse_from_incar(filename, param_name)\n if val is None:\n raise IOError(\"Error in parsing vasprun.xml\")\n elif val_type == \"string\":\n val = val.split()\n else:\n try:\n val = [float(i) for i in val.split()]\n except ValueError:\n # Fix for stupid error in vasprun sometimes which displays\n # MAGMOM as 2****\n val = _parse_from_incar(filename, param_name)\n if val is None:\n raise IOError(\"Error in parsing vasprun.xml\")\n return val\n\n\ndef _parse_varray(elem):\n if elem.get(\"type\", None) == 'logical':\n m = [[True if i == 'T' else False for i in v.text.split()] for v in elem]\n else:\n m = [[_vasprun_float(i) for i in v.text.split()] for v in elem]\n return m\n\n\ndef _parse_from_incar(filename, key):\n \"\"\"\n Helper function to parse a parameter from the INCAR.\n \"\"\"\n dirname = os.path.dirname(filename)\n for f in os.listdir(dirname):\n if re.search(r\"INCAR\", f):\n warnings.warn(\"INCAR found. Using \" + key + \" from INCAR.\")\n incar = Incar.from_file(os.path.join(dirname, f))\n if key in incar:\n return incar[key]\n else:\n return None\n return None\n\n\ndef _vasprun_float(f):\n \"\"\"\n Large numbers are often represented as ********* in the vasprun.\n This function parses these values as np.nan\n \"\"\"\n try:\n return float(f)\n except ValueError as e:\n f = f.strip()\n if f == '*' * len(f):\n warnings.warn('Float overflow (*******) encountered in vasprun')\n return np.nan\n raise e\n\n\nclass Vasprun(MSONable):\n \"\"\"\n Vastly improved cElementTree-based parser for vasprun.xml files. Uses\n iterparse to support incremental parsing of large files.\n Speedup over Dom is at least 2x for smallish files (~1Mb) to orders of\n magnitude for larger files (~10Mb).\n\n Args:\n filename (str): Filename to parse\n ionic_step_skip (int): If ionic_step_skip is a number > 1,\n only every ionic_step_skip ionic steps will be read for\n structure and energies. This is very useful if you are parsing\n very large vasprun.xml files and you are not interested in every\n single ionic step. Note that the final energies may not be the\n actual final energy in the vasprun.\n ionic_step_offset (int): Used together with ionic_step_skip. If set,\n the first ionic step read will be offset by the amount of\n ionic_step_offset. For example, if you want to start reading\n every 10th structure but only from the 3rd structure onwards,\n set ionic_step_skip to 10 and ionic_step_offset to 3. Main use\n case is when doing statistical structure analysis with\n extremely long time scale multiple VASP calculations of\n varying numbers of steps.\n parse_dos (bool): Whether to parse the dos. Defaults to True. Set\n to False to shave off significant time from the parsing if you\n are not interested in getting those data.\n parse_eigen (bool): Whether to parse the eigenvalues. Defaults to\n True. Set to False to shave off significant time from the\n parsing if you are not interested in getting those data.\n parse_projected_eigen (bool): Whether to parse the projected\n eigenvalues. Defaults to False. Set to True to obtain projected\n eigenvalues. **Note that this can take an extreme amount of time\n and memory.** So use this wisely.\n parse_potcar_file (bool/str): Whether to parse the potcar file to read\n the potcar hashes for the potcar_spec attribute. Defaults to True,\n where no hashes will be determined and the potcar_spec dictionaries\n will read {\"symbol\": ElSymbol, \"hash\": None}. By Default, looks in\n the same directory as the vasprun.xml, with same extensions as\n Vasprun.xml. If a string is provided, looks at that filepath.\n occu_tol (float): Sets the minimum tol for the determination of the\n vbm and cbm. Usually the default of 1e-8 works well enough,\n but there may be pathological cases.\n exception_on_bad_xml (bool): Whether to throw a ParseException if a\n malformed XML is detected. Default to True, which ensures only\n proper vasprun.xml are parsed. You can set to False if you want\n partial results (e.g., if you are monitoring a calculation during a\n run), but use the results with care. A warning is issued.\n\n **Vasp results**\n\n .. attribute:: ionic_steps\n\n All ionic steps in the run as a list of\n {\"structure\": structure at end of run,\n \"electronic_steps\": {All electronic step data in vasprun file},\n \"stresses\": stress matrix}\n\n .. attribute:: structures\n\n List of Structure objects for the structure at each ionic step.\n\n .. attribute:: tdos\n\n Total dos calculated at the end of run.\n\n .. attribute:: idos\n\n Integrated dos calculated at the end of run.\n\n .. attribute:: pdos\n\n List of list of PDos objects. Access as pdos[atomindex][orbitalindex]\n\n .. attribute:: efermi\n\n Fermi energy\n\n .. attribute:: eigenvalues\n\n Available only if parse_eigen=True. Final eigenvalues as a dict of\n {(spin, kpoint index):[[eigenvalue, occu]]}.\n This representation is based on actual ordering in VASP and is meant as\n an intermediate representation to be converted into proper objects. The\n kpoint index is 0-based (unlike the 1-based indexing in VASP).\n\n .. attribute:: projected_eigenvalues\n\n Final projected eigenvalues as a dict of {spin: nd-array}. To access\n a particular value, you need to do\n Vasprun.projected_eigenvalues[spin][kpoint index][band index][atom index][orbital_index]\n This representation is based on actual ordering in VASP and is meant as\n an intermediate representation to be converted into proper objects. The\n kpoint, band and atom indices are 0-based (unlike the 1-based indexing\n in VASP).\n\n .. attribute:: dielectric\n\n The real and imaginary part of the dielectric constant (e.g., computed\n by RPA) in function of the energy (frequency). Optical properties (e.g.\n absorption coefficient) can be obtained through this.\n The data is given as a tuple of 3 values containing each of them\n the energy, the real part tensor, and the imaginary part tensor\n ([energies],[[real_partxx,real_partyy,real_partzz,real_partxy,\n real_partyz,real_partxz]],[[imag_partxx,imag_partyy,imag_partzz,\n imag_partxy, imag_partyz, imag_partxz]])\n\n .. attribute:: other_dielectric\n\n Dictionary, with the tag comment as key, containing other variants of\n the real and imaginary part of the dielectric constant (e.g., computed\n by RPA) in function of the energy (frequency). Optical properties (e.g.\n absorption coefficient) can be obtained through this.\n The data is given as a tuple of 3 values containing each of them\n the energy, the real part tensor, and the imaginary part tensor\n ([energies],[[real_partxx,real_partyy,real_partzz,real_partxy,\n real_partyz,real_partxz]],[[imag_partxx,imag_partyy,imag_partzz,\n imag_partxy, imag_partyz, imag_partxz]])\n\n .. attribute:: epsilon_static\n\n The static part of the dielectric constant. Present when it's a DFPT run\n (LEPSILON=TRUE)\n\n .. attribute:: epsilon_static_wolfe\n\n The static part of the dielectric constant without any local field\n effects. Present when it's a DFPT run (LEPSILON=TRUE)\n\n .. attribute:: epsilon_ionic\n\n The ionic part of the static dielectric constant. Present when it's a\n DFPT run (LEPSILON=TRUE) and IBRION=5, 6, 7 or 8\n\n .. attribute:: nionic_steps\n\n The total number of ionic steps. This number is always equal\n to the total number of steps in the actual run even if\n ionic_step_skip is used.\n\n .. attribute:: force_constants\n\n Force constants computed in phonon DFPT run(IBRION = 8).\n The data is a 4D numpy array of shape (natoms, natoms, 3, 3).\n\n .. attribute:: normalmode_eigenvals\n\n Normal mode frequencies.\n 1D numpy array of size 3*natoms.\n\n .. attribute:: normalmode_eigenvecs\n\n Normal mode eigen vectors.\n 3D numpy array of shape (3*natoms, natoms, 3).\n\n **Vasp inputs**\n\n .. attribute:: incar\n\n Incar object for parameters specified in INCAR file.\n\n .. attribute:: parameters\n\n Incar object with parameters that vasp actually used, including all\n defaults.\n\n .. attribute:: kpoints\n\n Kpoints object for KPOINTS specified in run.\n\n .. attribute:: actual_kpoints\n\n List of actual kpoints, e.g.,\n [[0.25, 0.125, 0.08333333], [-0.25, 0.125, 0.08333333],\n [0.25, 0.375, 0.08333333], ....]\n\n .. attribute:: actual_kpoints_weights\n\n List of kpoint weights, E.g.,\n [0.04166667, 0.04166667, 0.04166667, 0.04166667, 0.04166667, ....]\n\n .. attribute:: atomic_symbols\n\n List of atomic symbols, e.g., [\"Li\", \"Fe\", \"Fe\", \"P\", \"P\", \"P\"]\n\n .. attribute:: potcar_symbols\n\n List of POTCAR symbols. e.g.,\n [\"PAW_PBE Li 17Jan2003\", \"PAW_PBE Fe 06Sep2000\", ..]\n\n Author: Shyue Ping Ong\n \"\"\"\n\n def __init__(self, filename, ionic_step_skip=None,\n ionic_step_offset=0, parse_dos=True,\n parse_eigen=True, parse_projected_eigen=False,\n parse_potcar_file=True, occu_tol=1e-8,\n exception_on_bad_xml=True):\n self.filename = filename\n self.ionic_step_skip = ionic_step_skip\n self.ionic_step_offset = ionic_step_offset\n self.occu_tol = occu_tol\n self.exception_on_bad_xml = exception_on_bad_xml\n\n with zopen(filename, \"rt\") as f:\n if ionic_step_skip or ionic_step_offset:\n # remove parts of the xml file and parse the string\n run = f.read()\n steps = run.split(\"<calculation>\")\n # The text before the first <calculation> is the preamble!\n preamble = steps.pop(0)\n self.nionic_steps = len(steps)\n new_steps = steps[ionic_step_offset::int(ionic_step_skip)]\n # add the tailing informat in the last step from the run\n to_parse = \"<calculation>\".join(new_steps)\n if steps[-1] != new_steps[-1]:\n to_parse = \"{}<calculation>{}{}\".format(\n preamble, to_parse,\n steps[-1].split(\"</calculation>\")[-1])\n else:\n to_parse = \"{}<calculation>{}\".format(preamble, to_parse)\n self._parse(StringIO(to_parse), parse_dos=parse_dos,\n parse_eigen=parse_eigen,\n parse_projected_eigen=parse_projected_eigen)\n else:\n self._parse(f, parse_dos=parse_dos, parse_eigen=parse_eigen,\n parse_projected_eigen=parse_projected_eigen)\n self.nionic_steps = len(self.ionic_steps)\n\n if parse_potcar_file:\n self.update_potcar_spec(parse_potcar_file)\n self.update_charge_from_potcar(parse_potcar_file)\n\n if self.incar.get(\"ALGO\", \"\") != \"BSE\" and (not self.converged):\n msg = \"%s is an unconverged VASP run.\\n\" % filename\n msg += \"Electronic convergence reached: %s.\\n\" % \\\n self.converged_electronic\n msg += \"Ionic convergence reached: %s.\" % self.converged_ionic\n warnings.warn(msg, UnconvergedVASPWarning)\n\n def _parse(self, stream, parse_dos, parse_eigen, parse_projected_eigen):\n self.efermi = None\n self.eigenvalues = None\n self.projected_eigenvalues = None\n self.dielectric_data = {}\n self.other_dielectric = {}\n ionic_steps = []\n parsed_header = False\n try:\n for event, elem in ET.iterparse(stream):\n tag = elem.tag\n if not parsed_header:\n if tag == \"generator\":\n self.generator = self._parse_params(elem)\n elif tag == \"incar\":\n self.incar = self._parse_params(elem)\n elif tag == \"kpoints\":\n self.kpoints, self.actual_kpoints, \\\n self.actual_kpoints_weights = self._parse_kpoints(\n elem)\n elif tag == \"parameters\":\n self.parameters = self._parse_params(elem)\n elif tag == \"structure\" and elem.attrib.get(\"name\") == \\\n \"initialpos\":\n self.initial_structure = self._parse_structure(elem)\n elif tag == \"atominfo\":\n self.atomic_symbols, self.potcar_symbols = \\\n self._parse_atominfo(elem)\n self.potcar_spec = [{\"titel\": p,\n \"hash\": None} for\n p in self.potcar_symbols]\n if tag == \"calculation\":\n parsed_header = True\n if not self.parameters.get(\"LCHIMAG\", False):\n ionic_steps.append(self._parse_calculation(elem))\n else:\n ionic_steps.extend(self._parse_chemical_shielding_calculation(elem))\n elif parse_dos and tag == \"dos\":\n try:\n self.tdos, self.idos, self.pdos = self._parse_dos(elem)\n self.efermi = self.tdos.efermi\n self.dos_has_errors = False\n except Exception as ex:\n self.dos_has_errors = True\n elif parse_eigen and tag == \"eigenvalues\":\n self.eigenvalues = self._parse_eigen(elem)\n elif parse_projected_eigen and tag == \"projected\":\n self.projected_eigenvalues = self._parse_projected_eigen(\n elem)\n elif tag == \"dielectricfunction\":\n if (\"comment\" not in elem.attrib) or \\\n elem.attrib[\"comment\"] == \"INVERSE MACROSCOPIC DIELECTRIC TENSOR (including local field effects in RPA (Hartree))\":\n if not 'density' in self.dielectric_data:\n self.dielectric_data['density'] = self._parse_diel(elem)\n # \"velocity-velocity\" is also named \"current-current\"\n # in OUTCAR\n elif not 'velocity' in self.dielectric_data:\n self.dielectric_data['velocity'] = self._parse_diel(elem)\n else:\n raise NotImplementedError('This vasprun.xml has >2 unlabelled dielectric functions')\n else:\n comment = elem.attrib[\"comment\"]\n self.other_dielectric[comment] = self._parse_diel(elem)\n elif tag == \"varray\" and elem.attrib.get(\"name\") == 'opticaltransitions':\n self.optical_transition = np.array(_parse_varray(elem))\n elif tag == \"structure\" and elem.attrib.get(\"name\") == \\\n \"finalpos\":\n self.final_structure = self._parse_structure(elem)\n elif tag == \"dynmat\":\n hessian, eigenvalues, eigenvectors = self._parse_dynmat(elem)\n natoms = len(self.atomic_symbols)\n hessian = np.array(hessian)\n self.force_constants = np.zeros((natoms, natoms, 3, 3), dtype='double')\n for i in range(natoms):\n for j in range(natoms):\n self.force_constants[i, j] = hessian[i * 3:(i + 1) * 3, j * 3:(j + 1) * 3]\n phonon_eigenvectors = []\n for ev in eigenvectors:\n phonon_eigenvectors.append(np.array(ev).reshape(natoms, 3))\n self.normalmode_eigenvals = np.array(eigenvalues)\n self.normalmode_eigenvecs = np.array(phonon_eigenvectors)\n except ET.ParseError as ex:\n if self.exception_on_bad_xml:\n raise ex\n else:\n warnings.warn(\n \"XML is malformed. Parsing has stopped but partial data\"\n \"is available.\", UserWarning)\n self.ionic_steps = ionic_steps\n self.vasp_version = self.generator[\"version\"]\n\n @property\n def structures(self):\n return [step[\"structure\"] for step in self.ionic_steps]\n\n @property\n def epsilon_static(self):\n \"\"\"\n Property only available for DFPT calculations.\n \"\"\"\n return self.ionic_steps[-1].get(\"epsilon\", [])\n\n @property\n def epsilon_static_wolfe(self):\n \"\"\"\n Property only available for DFPT calculations.\n \"\"\"\n return self.ionic_steps[-1].get(\"epsilon_rpa\", [])\n\n @property\n def epsilon_ionic(self):\n \"\"\"\n Property only available for DFPT calculations and when IBRION=5, 6, 7 or 8.\n \"\"\"\n return self.ionic_steps[-1].get(\"epsilon_ion\", [])\n\n @property\n def dielectric(self):\n return self.dielectric_data['density']\n\n @property\n def optical_absorption_coeff(self):\n \"\"\"\n Calculate the optical absorption coefficient\n from the dielectric constants. Note that this method is only\n implemented for optical properties calculated with GGA and BSE.\n Returns:\n optical absorption coefficient in list\n \"\"\"\n if self.dielectric_data[\"density\"]:\n real_avg = [sum(self.dielectric_data[\"density\"][1][i][0:3]) / 3\n for i in range(len(self.dielectric_data[\"density\"][0]))]\n imag_avg = [sum(self.dielectric_data[\"density\"][2][i][0:3]) / 3\n for i in range(len(self.dielectric_data[\"density\"][0]))]\n\n def f(freq, real, imag):\n \"\"\"\n The optical absorption coefficient calculated in terms of\n \u0004\u0001equation\n \"\"\"\n hbar = 6.582119514e-16 # eV/K\n coeff = np.sqrt(\n np.sqrt(real ** 2 + imag ** 2) - real) * \\\n np.sqrt(2) / hbar * freq\n return coeff\n\n absorption_coeff = [f(freq, real, imag) for freq, real, imag in\n zip(self.dielectric_data[\"density\"][0],\n real_avg, imag_avg)]\n return absorption_coeff\n\n @property\n def lattice(self):\n return self.final_structure.lattice\n\n @property\n def lattice_rec(self):\n return self.final_structure.lattice.reciprocal_lattice\n\n @property\n def converged_electronic(self):\n \"\"\"\n Checks that electronic step convergence has been reached in the final\n ionic step\n \"\"\"\n final_esteps = self.ionic_steps[-1][\"electronic_steps\"]\n if 'LEPSILON' in self.incar and self.incar['LEPSILON']:\n i = 1\n to_check = set(['e_wo_entrp', 'e_fr_energy', 'e_0_energy'])\n while set(final_esteps[i].keys()) == to_check:\n i += 1\n return i + 1 != self.parameters[\"NELM\"]\n return len(final_esteps) < self.parameters[\"NELM\"]\n\n @property\n def converged_ionic(self):\n \"\"\"\n Checks that ionic step convergence has been reached, i.e. that vasp\n exited before reaching the max ionic steps for a relaxation run\n \"\"\"\n nsw = self.parameters.get(\"NSW\", 0)\n return nsw <= 1 or len(self.ionic_steps) < nsw\n\n @property\n def converged(self):\n \"\"\"\n Returns true if a relaxation run is converged.\n \"\"\"\n return self.converged_electronic and self.converged_ionic\n\n @property\n @unitized(\"eV\")\n def final_energy(self):\n \"\"\"\n Final energy from the vasp run.\n \"\"\"\n try:\n final_istep = self.ionic_steps[-1]\n if final_istep[\"e_wo_entrp\"] != final_istep[\n 'electronic_steps'][-1][\"e_0_energy\"]:\n warnings.warn(\"Final e_wo_entrp differs from the final \"\n \"electronic step. VASP may have included some \"\n \"corrections, e.g., vdw. Vasprun will return \"\n \"the final e_wo_entrp, i.e., including \"\n \"corrections in such instances.\")\n return final_istep[\"e_wo_entrp\"]\n return final_istep['electronic_steps'][-1][\"e_0_energy\"]\n except (IndexError, KeyError):\n warnings.warn(\"Calculation does not have a total energy. \"\n \"Possibly a GW or similar kind of run. A value of \"\n \"infinity is returned.\")\n return float('inf')\n\n @property\n def complete_dos(self):\n \"\"\"\n A complete dos object which incorporates the total dos and all\n projected dos.\n \"\"\"\n final_struct = self.final_structure\n pdoss = {final_struct[i]: pdos for i, pdos in enumerate(self.pdos)}\n return CompleteDos(self.final_structure, self.tdos, pdoss)\n\n @property\n def hubbards(self):\n \"\"\"\n Hubbard U values used if a vasprun is a GGA+U run. {} otherwise.\n \"\"\"\n symbols = [s.split()[1] for s in self.potcar_symbols]\n symbols = [re.split(r\"_\", s)[0] for s in symbols]\n if not self.incar.get(\"LDAU\", False):\n return {}\n us = self.incar.get(\"LDAUU\", self.parameters.get(\"LDAUU\"))\n js = self.incar.get(\"LDAUJ\", self.parameters.get(\"LDAUJ\"))\n if len(js) != len(us):\n js = [0] * len(us)\n if len(us) == len(symbols):\n return {symbols[i]: us[i] - js[i] for i in range(len(symbols))}\n elif sum(us) == 0 and sum(js) == 0:\n return {}\n else:\n raise VaspParserError(\"Length of U value parameters and atomic \"\n \"symbols are mismatched\")\n\n @property\n def run_type(self):\n \"\"\"\n Returns the run type. Currently supports LDA, GGA, vdW-DF and HF calcs.\n\n TODO: Fix for other functional types like PW91, other vdW types, etc.\n \"\"\"\n if self.parameters.get(\"LHFCALC\", False):\n rt = \"HF\"\n elif self.parameters.get(\"LUSE_VDW\", False):\n vdw_gga = {\"RE\": \"DF\", \"OR\": \"optPBE\", \"BO\": \"optB88\",\n \"MK\": \"optB86b\", \"ML\": \"DF2\"}\n gga = self.parameters.get(\"GGA\").upper()\n rt = \"vdW-\" + vdw_gga[gga]\n elif self.potcar_symbols[0].split()[0] == 'PAW':\n rt = \"LDA\"\n else:\n rt = \"GGA\"\n if self.is_hubbard:\n rt += \"+U\"\n return rt\n\n @property\n def is_hubbard(self):\n \"\"\"\n True if run is a DFT+U run.\n \"\"\"\n if len(self.hubbards) == 0:\n return False\n return sum(self.hubbards.values()) > 1e-8\n\n @property\n def is_spin(self):\n \"\"\"\n True if run is spin-polarized.\n \"\"\"\n return self.parameters.get(\"ISPIN\", 1) == 2\n\n def get_computed_entry(self, inc_structure=True, parameters=None,\n data=None):\n \"\"\"\n Returns a ComputedStructureEntry from the vasprun.\n\n Args:\n inc_structure (bool): Set to True if you want\n ComputedStructureEntries to be returned instead of\n ComputedEntries.\n parameters (list): Input parameters to include. It has to be one of\n the properties supported by the Vasprun object. If\n parameters is None, a default set of parameters that are\n necessary for typical post-processing will be set.\n data (list): Output data to include. Has to be one of the properties\n supported by the Vasprun object.\n\n Returns:\n ComputedStructureEntry/ComputedEntry\n \"\"\"\n param_names = {\"is_hubbard\", \"hubbards\", \"potcar_symbols\",\n \"potcar_spec\", \"run_type\"}\n if parameters:\n param_names.update(parameters)\n params = {p: getattr(self, p) for p in param_names}\n data = {p: getattr(self, p) for p in data} if data is not None else {}\n\n if inc_structure:\n return ComputedStructureEntry(self.final_structure,\n self.final_energy, parameters=params,\n data=data)\n else:\n return ComputedEntry(self.final_structure.composition,\n self.final_energy, parameters=params,\n data=data)\n\n def get_band_structure(self, kpoints_filename=None, efermi=None,\n line_mode=False):\n \"\"\"\n Returns the band structure as a BandStructure object\n\n Args:\n kpoints_filename (str): Full path of the KPOINTS file from which\n the band structure is generated.\n If none is provided, the code will try to intelligently\n determine the appropriate KPOINTS file by substituting the\n filename of the vasprun.xml with KPOINTS.\n The latter is the default behavior.\n efermi (float): If you want to specify manually the fermi energy\n this is where you should do it. By default, the None value\n means the code will get it from the vasprun.\n line_mode (bool): Force the band structure to be considered as\n a run along symmetry lines.\n\n Returns:\n a BandStructure object (or more specifically a\n BandStructureSymmLine object if the run is detected to be a run\n along symmetry lines)\n\n Two types of runs along symmetry lines are accepted: non-sc with\n Line-Mode in the KPOINT file or hybrid, self-consistent with a\n uniform grid+a few kpoints along symmetry lines (explicit KPOINTS\n file) (it's not possible to run a non-sc band structure with hybrid\n functionals). The explicit KPOINTS file needs to have data on the\n kpoint label as commentary.\n \"\"\"\n\n if not kpoints_filename:\n kpoints_filename = self.filename.replace('vasprun.xml', 'KPOINTS')\n if not os.path.exists(kpoints_filename) and line_mode is True:\n raise VaspParserError('KPOINTS needed to obtain band structure '\n 'along symmetry lines.')\n\n if efermi is None:\n efermi = self.efermi\n\n kpoint_file = None\n if os.path.exists(kpoints_filename):\n kpoint_file = Kpoints.from_file(kpoints_filename)\n lattice_new = Lattice(self.lattice_rec.matrix)\n\n kpoints = [np.array(self.actual_kpoints[i])\n for i in range(len(self.actual_kpoints))]\n\n p_eigenvals = defaultdict(list)\n eigenvals = defaultdict(list)\n\n nkpts = len(kpoints)\n\n neigenvalues = [len(v) for v in self.eigenvalues[Spin.up]]\n min_eigenvalues = min(neigenvalues)\n\n for spin, v in self.eigenvalues.items():\n v = np.swapaxes(v, 0, 1)\n eigenvals[spin] = v[:, :, 0]\n\n if self.projected_eigenvalues:\n peigen = self.projected_eigenvalues[spin]\n # Original axes for self.projected_eigenvalues are kpoints,\n # band, ion, orb.\n # For BS input, we need band, kpoints, orb, ion.\n peigen = np.swapaxes(peigen, 0, 1) # Swap kpoint and band axes\n peigen = np.swapaxes(peigen, 2, 3) # Swap ion and orb axes\n\n p_eigenvals[spin] = peigen\n # for b in range(min_eigenvalues):\n # p_eigenvals[spin].append(\n # [{Orbital(orb): v for orb, v in enumerate(peigen[b, k])}\n # for k in range(nkpts)])\n\n # check if we have an hybrid band structure computation\n # for this we look at the presence of the LHFCALC tag\n hybrid_band = False\n if self.parameters.get('LHFCALC', False):\n hybrid_band = True\n\n if kpoint_file is not None:\n if kpoint_file.style == Kpoints.supported_modes.Line_mode:\n line_mode = True\n\n if line_mode:\n labels_dict = {}\n if hybrid_band:\n start_bs_index = 0\n for i in range(len(self.actual_kpoints)):\n if self.actual_kpoints_weights[i] == 0.0:\n start_bs_index = i\n break\n for i in range(start_bs_index, len(kpoint_file.kpts)):\n if kpoint_file.labels[i] is not None:\n labels_dict[kpoint_file.labels[i]] = \\\n kpoint_file.kpts[i]\n # remake the data only considering line band structure k-points\n # (weight = 0.0 kpoints)\n nbands = len(eigenvals[Spin.up])\n kpoints = kpoints[start_bs_index:nkpts]\n up_eigen = [eigenvals[Spin.up][i][start_bs_index:nkpts]\n for i in range(nbands)]\n if self.projected_eigenvalues:\n p_eigenvals[Spin.up] = [p_eigenvals[Spin.up][i][\n start_bs_index:nkpts]\n for i in range(nbands)]\n if self.is_spin:\n down_eigen = [eigenvals[Spin.down][i][start_bs_index:nkpts]\n for i in range(nbands)]\n eigenvals = {Spin.up: up_eigen, Spin.down: down_eigen}\n if self.projected_eigenvalues:\n p_eigenvals[Spin.down] = [p_eigenvals[Spin.down][i][\n start_bs_index:nkpts]\n for i in range(nbands)]\n else:\n eigenvals = {Spin.up: up_eigen}\n else:\n if '' in kpoint_file.labels:\n raise Exception(\"A band structure along symmetry lines \"\n \"requires a label for each kpoint. \"\n \"Check your KPOINTS file\")\n labels_dict = dict(zip(kpoint_file.labels, kpoint_file.kpts))\n labels_dict.pop(None, None)\n return BandStructureSymmLine(kpoints, eigenvals, lattice_new,\n efermi, labels_dict,\n structure=self.final_structure,\n projections=p_eigenvals)\n else:\n return BandStructure(kpoints, eigenvals, lattice_new, efermi,\n structure=self.final_structure,\n projections=p_eigenvals)\n\n @property\n def eigenvalue_band_properties(self):\n \"\"\"\n Band properties from the eigenvalues as a tuple,\n (band gap, cbm, vbm, is_band_gap_direct).\n \"\"\"\n vbm = -float(\"inf\")\n vbm_kpoint = None\n cbm = float(\"inf\")\n cbm_kpoint = None\n for spin, d in self.eigenvalues.items():\n for k, val in enumerate(d):\n for (eigenval, occu) in val:\n if occu > self.occu_tol and eigenval > vbm:\n vbm = eigenval\n vbm_kpoint = k\n elif occu <= self.occu_tol and eigenval < cbm:\n cbm = eigenval\n cbm_kpoint = k\n return max(cbm - vbm, 0), cbm, vbm, vbm_kpoint == cbm_kpoint\n\n def get_potcars(self, path):\n def get_potcar_in_path(p):\n for fn in os.listdir(os.path.abspath(p)):\n if fn.startswith('POTCAR'):\n pc = Potcar.from_file(os.path.join(p, fn))\n if {d.header for d in pc} == \\\n {sym for sym in self.potcar_symbols}:\n return pc\n warnings.warn(\"No POTCAR file with matching TITEL fields\"\n \" was found in {}\".format(os.path.abspath(p)))\n\n if isinstance(path, string_types):\n if \"POTCAR\" in path:\n potcar = Potcar.from_file(path)\n if {d.TITEL for d in potcar} != \\\n {sym for sym in self.potcar_symbols}:\n raise ValueError(\"Potcar TITELs do not match Vasprun\")\n else:\n potcar = get_potcar_in_path(path)\n elif isinstance(path, bool) and path:\n potcar = get_potcar_in_path(os.path.split(self.filename)[0])\n else:\n potcar = None\n\n return potcar\n\n def update_potcar_spec(self, path):\n potcar = self.get_potcars(path)\n if potcar:\n self.potcar_spec = [{\"titel\": sym, \"hash\": ps.get_potcar_hash()}\n for sym in self.potcar_symbols\n for ps in potcar if\n ps.symbol == sym.split()[1]]\n\n def update_charge_from_potcar(self, path):\n potcar = self.get_potcars(path)\n\n if potcar and self.incar.get(\"ALGO\", \"\") not in [\"GW0\", \"G0W0\", \"GW\", \"BSE\"]:\n nelect = self.parameters[\"NELECT\"]\n potcar_nelect = int(round(sum([self.initial_structure.composition.element_composition[\n ps.element] * ps.ZVAL for ps in potcar])))\n charge = nelect - potcar_nelect\n\n if charge:\n for s in self.structures:\n s._charge = charge\n\n def as_dict(self):\n \"\"\"\n Json-serializable dict representation.\n \"\"\"\n d = {\"vasp_version\": self.vasp_version,\n \"has_vasp_completed\": self.converged,\n \"nsites\": len(self.final_structure)}\n comp = self.final_structure.composition\n d[\"unit_cell_formula\"] = comp.as_dict()\n d[\"reduced_cell_formula\"] = Composition(comp.reduced_formula).as_dict()\n d[\"pretty_formula\"] = comp.reduced_formula\n symbols = [s.split()[1] for s in self.potcar_symbols]\n symbols = [re.split(r\"_\", s)[0] for s in symbols]\n d[\"is_hubbard\"] = self.is_hubbard\n d[\"hubbards\"] = self.hubbards\n\n unique_symbols = sorted(list(set(self.atomic_symbols)))\n d[\"elements\"] = unique_symbols\n d[\"nelements\"] = len(unique_symbols)\n\n d[\"run_type\"] = self.run_type\n\n vin = {\"incar\": {k: v for k, v in self.incar.items()},\n \"crystal\": self.initial_structure.as_dict(),\n \"kpoints\": self.kpoints.as_dict()}\n actual_kpts = [{\"abc\": list(self.actual_kpoints[i]),\n \"weight\": self.actual_kpoints_weights[i]}\n for i in range(len(self.actual_kpoints))]\n vin[\"kpoints\"][\"actual_points\"] = actual_kpts\n vin[\"potcar\"] = [s.split(\" \")[1] for s in self.potcar_symbols]\n vin[\"potcar_spec\"] = self.potcar_spec\n vin[\"potcar_type\"] = [s.split(\" \")[0] for s in self.potcar_symbols]\n vin[\"parameters\"] = {k: v for k, v in self.parameters.items()}\n vin[\"lattice_rec\"] = self.lattice_rec.as_dict()\n d[\"input\"] = vin\n\n nsites = len(self.final_structure)\n\n try:\n vout = {\"ionic_steps\": self.ionic_steps,\n \"final_energy\": self.final_energy,\n \"final_energy_per_atom\": self.final_energy / nsites,\n \"crystal\": self.final_structure.as_dict(),\n \"efermi\": self.efermi}\n except (ArithmeticError, TypeError):\n vout = {\"ionic_steps\": self.ionic_steps,\n \"final_energy\": self.final_energy,\n \"final_energy_per_atom\": None,\n \"crystal\": self.final_structure.as_dict(),\n \"efermi\": self.efermi}\n\n if self.eigenvalues:\n eigen = {str(spin): v.tolist()\n for spin, v in self.eigenvalues.items()}\n vout[\"eigenvalues\"] = eigen\n (gap, cbm, vbm, is_direct) = self.eigenvalue_band_properties\n vout.update(dict(bandgap=gap, cbm=cbm, vbm=vbm,\n is_gap_direct=is_direct))\n\n if self.projected_eigenvalues:\n vout['projected_eigenvalues'] = {\n str(spin): v.tolist()\n for spin, v in self.projected_eigenvalues.items()}\n\n vout['epsilon_static'] = self.epsilon_static\n vout['epsilon_static_wolfe'] = self.epsilon_static_wolfe\n vout['epsilon_ionic'] = self.epsilon_ionic\n d['output'] = vout\n return jsanitize(d, strict=True)\n\n def _parse_params(self, elem):\n params = {}\n for c in elem:\n name = c.attrib.get(\"name\")\n if c.tag not in (\"i\", \"v\"):\n p = self._parse_params(c)\n if name == \"response functions\":\n # Delete duplicate fields from \"response functions\",\n # which overrides the values in the root params.\n p = {k: v for k, v in p.items() if k not in params}\n params.update(p)\n else:\n ptype = c.attrib.get(\"type\")\n val = c.text.strip() if c.text else \"\"\n if c.tag == \"i\":\n params[name] = _parse_parameters(ptype, val)\n else:\n params[name] = _parse_v_parameters(ptype, val,\n self.filename, name)\n elem.clear()\n return Incar(params)\n\n def _parse_atominfo(self, elem):\n for a in elem.findall(\"array\"):\n if a.attrib[\"name\"] == \"atoms\":\n atomic_symbols = [rc.find(\"c\").text.strip()\n for rc in a.find(\"set\")]\n elif a.attrib[\"name\"] == \"atomtypes\":\n potcar_symbols = [rc.findall(\"c\")[4].text.strip()\n for rc in a.find(\"set\")]\n\n # ensure atomic symbols are valid elements\n def parse_atomic_symbol(symbol):\n try:\n return str(Element(symbol))\n # vasprun.xml uses X instead of Xe for xenon\n except ValueError as e:\n if symbol == \"X\":\n return \"Xe\"\n elif symbol == \"r\":\n return \"Zr\"\n raise e\n\n elem.clear()\n return [parse_atomic_symbol(sym) for\n sym in atomic_symbols], potcar_symbols\n\n def _parse_kpoints(self, elem):\n e = elem\n if elem.find(\"generation\"):\n e = elem.find(\"generation\")\n k = Kpoints(\"Kpoints from vasprun.xml\")\n k.style = Kpoints.supported_modes.from_string(\n e.attrib[\"param\"] if \"param\" in e.attrib else \"Reciprocal\")\n for v in e.findall(\"v\"):\n name = v.attrib.get(\"name\")\n toks = v.text.split()\n if name == \"divisions\":\n k.kpts = [[int(i) for i in toks]]\n elif name == \"usershift\":\n k.kpts_shift = [float(i) for i in toks]\n elif name in {\"genvec1\", \"genvec2\", \"genvec3\", \"shift\"}:\n setattr(k, name, [float(i) for i in toks])\n for va in elem.findall(\"varray\"):\n name = va.attrib[\"name\"]\n if name == \"kpointlist\":\n actual_kpoints = _parse_varray(va)\n elif name == \"weights\":\n weights = [i[0] for i in _parse_varray(va)]\n elem.clear()\n if k.style == Kpoints.supported_modes.Reciprocal:\n k = Kpoints(comment=\"Kpoints from vasprun.xml\",\n style=Kpoints.supported_modes.Reciprocal,\n num_kpts=len(k.kpts),\n kpts=actual_kpoints, kpts_weights=weights)\n return k, actual_kpoints, weights\n\n def _parse_structure(self, elem):\n latt = _parse_varray(elem.find(\"crystal\").find(\"varray\"))\n pos = _parse_varray(elem.find(\"varray\"))\n struct = Structure(latt, self.atomic_symbols, pos)\n sdyn = elem.find(\"varray/[@name='selective']\")\n if sdyn:\n struct.add_site_property('selective_dynamics',\n _parse_varray(sdyn))\n return struct\n\n def _parse_diel(self, elem):\n imag = [[_vasprun_float(l) for l in r.text.split()]\n for r in elem.find(\"imag\").find(\"array\")\n .find(\"set\").findall(\"r\")]\n real = [[_vasprun_float(l) for l in r.text.split()]\n for r in elem.find(\"real\")\n .find(\"array\").find(\"set\").findall(\"r\")]\n elem.clear()\n return [e[0] for e in imag], \\\n [e[1:] for e in real], [e[1:] for e in imag]\n\n def _parse_optical_transition(self, elem):\n for va in elem.findall(\"varray\"):\n if va.attrib.get(\"name\") == \"opticaltransitions\":\n # opticaltransitions array contains oscillator strength and probability of transition\n oscillator_strength = np.array(_parse_varray(va))[0:, ]\n probability_transition = np.array(_parse_varray(va))[0:, 1]\n return oscillator_strength, probability_transition\n\n def _parse_chemical_shielding_calculation(self, elem):\n calculation = []\n istep = {}\n try:\n s = self._parse_structure(elem.find(\"structure\"))\n except AttributeError: # not all calculations have a structure\n s = None\n pass\n for va in elem.findall(\"varray\"):\n istep[va.attrib[\"name\"]] = _parse_varray(va)\n istep[\"structure\"] = s\n istep[\"electronic_steps\"] = []\n calculation.append(istep)\n for scstep in elem.findall(\"scstep\"):\n try:\n d = {i.attrib[\"name\"]: _vasprun_float(i.text)\n for i in scstep.find(\"energy\").findall(\"i\")}\n cur_ene = d['e_fr_energy']\n min_steps = 1 if len(calculation) >= 1 else self.parameters.get(\"NELMIN\", 5)\n if len(calculation[-1][\"electronic_steps\"]) <= min_steps:\n calculation[-1][\"electronic_steps\"].append(d)\n else:\n last_ene = calculation[-1][\"electronic_steps\"][-1][\"e_fr_energy\"]\n if abs(cur_ene - last_ene) < 1.0:\n calculation[-1][\"electronic_steps\"].append(d)\n else:\n calculation.append({\"electronic_steps\": [d]})\n except AttributeError: # not all calculations have an energy\n pass\n calculation[-1].update(calculation[-1][\"electronic_steps\"][-1])\n return calculation\n\n def _parse_calculation(self, elem):\n try:\n istep = {i.attrib[\"name\"]: float(i.text)\n for i in elem.find(\"energy\").findall(\"i\")}\n except AttributeError: # not all calculations have an energy\n istep = {}\n pass\n esteps = []\n for scstep in elem.findall(\"scstep\"):\n try:\n d = {i.attrib[\"name\"]: _vasprun_float(i.text)\n for i in scstep.find(\"energy\").findall(\"i\")}\n esteps.append(d)\n except AttributeError: # not all calculations have an energy\n pass\n try:\n s = self._parse_structure(elem.find(\"structure\"))\n except AttributeError: # not all calculations have a structure\n s = None\n pass\n for va in elem.findall(\"varray\"):\n istep[va.attrib[\"name\"]] = _parse_varray(va)\n istep[\"electronic_steps\"] = esteps\n istep[\"structure\"] = s\n elem.clear()\n return istep\n\n def _parse_dos(self, elem):\n efermi = float(elem.find(\"i\").text)\n energies = None\n tdensities = {}\n idensities = {}\n\n for s in elem.find(\"total\").find(\"array\").find(\"set\").findall(\"set\"):\n data = np.array(_parse_varray(s))\n energies = data[:, 0]\n spin = Spin.up if s.attrib[\"comment\"] == \"spin 1\" else Spin.down\n tdensities[spin] = data[:, 1]\n idensities[spin] = data[:, 2]\n\n pdoss = []\n partial = elem.find(\"partial\")\n if partial is not None:\n orbs = [ss.text for ss in partial.find(\"array\").findall(\"field\")]\n orbs.pop(0)\n lm = any([\"x\" in s for s in orbs])\n for s in partial.find(\"array\").find(\"set\").findall(\"set\"):\n pdos = defaultdict(dict)\n\n for ss in s.findall(\"set\"):\n spin = Spin.up if ss.attrib[\"comment\"] == \"spin 1\" else \\\n Spin.down\n data = np.array(_parse_varray(ss))\n nrow, ncol = data.shape\n for j in range(1, ncol):\n if lm:\n orb = Orbital(j - 1)\n else:\n orb = OrbitalType(j - 1)\n pdos[orb][spin] = data[:, j]\n pdoss.append(pdos)\n elem.clear()\n return Dos(efermi, energies, tdensities), \\\n Dos(efermi, energies, idensities), pdoss\n\n def _parse_eigen(self, elem):\n eigenvalues = defaultdict(list)\n for s in elem.find(\"array\").find(\"set\").findall(\"set\"):\n spin = Spin.up if s.attrib[\"comment\"] == \"spin 1\" else Spin.down\n for ss in s.findall(\"set\"):\n eigenvalues[spin].append(_parse_varray(ss))\n eigenvalues = {spin: np.array(v) for spin, v in eigenvalues.items()}\n elem.clear()\n return eigenvalues\n\n def _parse_projected_eigen(self, elem):\n root = elem.find(\"array\").find(\"set\")\n proj_eigen = defaultdict(list)\n for s in root.findall(\"set\"):\n spin = int(re.match(r\"spin(\\d+)\", s.attrib[\"comment\"]).group(1))\n\n # Force spin to be +1 or -1\n spin = Spin.up if spin == 1 else Spin.down\n for kpt, ss in enumerate(s.findall(\"set\")):\n dk = []\n for band, sss in enumerate(ss.findall(\"set\")):\n db = _parse_varray(sss)\n dk.append(db)\n proj_eigen[spin].append(dk)\n proj_eigen = {spin: np.array(v) for spin, v in proj_eigen.items()}\n elem.clear()\n return proj_eigen\n\n def _parse_dynmat(self, elem):\n hessian = []\n eigenvalues = []\n eigenvectors = []\n for v in elem.findall(\"v\"):\n if v.attrib[\"name\"] == \"eigenvalues\":\n eigenvalues = [float(i) for i in v.text.split()]\n for va in elem.findall(\"varray\"):\n if va.attrib[\"name\"] == \"hessian\":\n for v in va.findall(\"v\"):\n hessian.append([float(i) for i in v.text.split()])\n elif va.attrib[\"name\"] == \"eigenvectors\":\n for v in va.findall(\"v\"):\n eigenvectors.append([float(i) for i in v.text.split()])\n return hessian, eigenvalues, eigenvectors\n\n\nclass BSVasprun(Vasprun):\n \"\"\"\n A highly optimized version of Vasprun that parses only eigenvalues for\n bandstructures. All other properties like structures, parameters,\n etc. are ignored.\n \"\"\"\n\n def __init__(self, filename, parse_projected_eigen=False,\n parse_potcar_file=False, occu_tol=1e-8):\n self.filename = filename\n self.occu_tol = occu_tol\n\n with zopen(filename, \"rt\") as f:\n self.efermi = None\n parsed_header = False\n self.eigenvalues = None\n self.projected_eigenvalues = None\n for event, elem in ET.iterparse(f):\n tag = elem.tag\n if not parsed_header:\n if tag == \"generator\":\n self.generator = self._parse_params(elem)\n elif tag == \"incar\":\n self.incar = self._parse_params(elem)\n elif tag == \"kpoints\":\n self.kpoints, self.actual_kpoints, \\\n self.actual_kpoints_weights = self._parse_kpoints(\n elem)\n elif tag == \"parameters\":\n self.parameters = self._parse_params(elem)\n elif tag == \"atominfo\":\n self.atomic_symbols, self.potcar_symbols = \\\n self._parse_atominfo(elem)\n self.potcar_spec = [{\"titel\": p,\n \"hash\": None} for\n p in self.potcar_symbols]\n parsed_header = True\n elif tag == \"i\" and elem.attrib.get(\"name\") == \"efermi\":\n self.efermi = float(elem.text)\n elif tag == \"eigenvalues\":\n self.eigenvalues = self._parse_eigen(elem)\n elif parse_projected_eigen and tag == \"projected\":\n self.projected_eigenvalues = self._parse_projected_eigen(\n elem)\n elif tag == \"structure\" and elem.attrib.get(\"name\") == \\\n \"finalpos\":\n self.final_structure = self._parse_structure(elem)\n self.vasp_version = self.generator[\"version\"]\n if parse_potcar_file:\n self.update_potcar_spec(parse_potcar_file)\n\n def as_dict(self):\n \"\"\"\n Json-serializable dict representation.\n \"\"\"\n d = {\"vasp_version\": self.vasp_version,\n \"has_vasp_completed\": True,\n \"nsites\": len(self.final_structure)}\n comp = self.final_structure.composition\n d[\"unit_cell_formula\"] = comp.as_dict()\n d[\"reduced_cell_formula\"] = Composition(comp.reduced_formula).as_dict()\n d[\"pretty_formula\"] = comp.reduced_formula\n symbols = [s.split()[1] for s in self.potcar_symbols]\n symbols = [re.split(r\"_\", s)[0] for s in symbols]\n d[\"is_hubbard\"] = self.is_hubbard\n d[\"hubbards\"] = self.hubbards\n\n unique_symbols = sorted(list(set(self.atomic_symbols)))\n d[\"elements\"] = unique_symbols\n d[\"nelements\"] = len(unique_symbols)\n\n d[\"run_type\"] = self.run_type\n\n vin = {\"incar\": {k: v for k, v in self.incar.items()},\n \"crystal\": self.final_structure.as_dict(),\n \"kpoints\": self.kpoints.as_dict()}\n actual_kpts = [{\"abc\": list(self.actual_kpoints[i]),\n \"weight\": self.actual_kpoints_weights[i]}\n for i in range(len(self.actual_kpoints))]\n vin[\"kpoints\"][\"actual_points\"] = actual_kpts\n vin[\"potcar\"] = [s.split(\" \")[1] for s in self.potcar_symbols]\n vin[\"potcar_spec\"] = self.potcar_spec\n vin[\"potcar_type\"] = [s.split(\" \")[0] for s in self.potcar_symbols]\n vin[\"parameters\"] = {k: v for k, v in self.parameters.items()}\n vin[\"lattice_rec\"] = self.lattice_rec.as_dict()\n d[\"input\"] = vin\n\n vout = {\"crystal\": self.final_structure.as_dict(),\n \"efermi\": self.efermi}\n\n if self.eigenvalues:\n eigen = defaultdict(dict)\n for spin, values in self.eigenvalues.items():\n for i, v in enumerate(values):\n eigen[i][str(spin)] = v\n vout[\"eigenvalues\"] = eigen\n (gap, cbm, vbm, is_direct) = self.eigenvalue_band_properties\n vout.update(dict(bandgap=gap, cbm=cbm, vbm=vbm,\n is_gap_direct=is_direct))\n\n if self.projected_eigenvalues:\n peigen = []\n for i in range(len(eigen)):\n peigen.append({})\n for spin, v in self.projected_eigenvalues.items():\n for kpoint_index, vv in enumerate(v):\n if str(spin) not in peigen[kpoint_index]:\n peigen[kpoint_index][str(spin)] = vv\n vout['projected_eigenvalues'] = peigen\n\n d['output'] = vout\n return jsanitize(d, strict=True)\n\n\nclass Outcar(MSONable):\n \"\"\"\n Parser for data in OUTCAR that is not available in Vasprun.xml\n\n Note, this class works a bit differently than most of the other\n VaspObjects, since the OUTCAR can be very different depending on which\n \"type of run\" performed.\n\n Creating the OUTCAR class with a filename reads \"regular parameters\" that\n are always present.\n\n Args:\n filename (str): OUTCAR filename to parse.\n\n .. attribute:: magnetization\n\n Magnetization on each ion as a tuple of dict, e.g.,\n ({\"d\": 0.0, \"p\": 0.003, \"s\": 0.002, \"tot\": 0.005}, ... )\n Note that this data is not always present. LORBIT must be set to some\n other value than the default.\n\n .. attribute:: chemical_shielding\n\n chemical shielding on each ion as a dictionary with core and valence contributions\n\n .. attribute:: unsym_cs_tensor\n\n Unsymmetrized chemical shielding tensor matrixes on each ion as a list.\n e.g.,\n [[[sigma11, sigma12, sigma13],\n [sigma21, sigma22, sigma23],\n [sigma31, sigma32, sigma33]],\n ...\n [[sigma11, sigma12, sigma13],\n [sigma21, sigma22, sigma23],\n [sigma31, sigma32, sigma33]]]\n\n .. attribute:: unsym_cs_tensor \n G=0 contribution to chemical shielding. 2D rank 3 matrix\n\n .. attribute:: cs_core_contribution\n Core contribution to chemical shielding. dict. e.g.,\n {'Mg': -412.8, 'C': -200.5, 'O': -271.1}\n\n .. attribute:: efg\n\n Electric Field Gradient (EFG) tensor on each ion as a tuple of dict, e.g.,\n ({\"cq\": 0.1, \"eta\", 0.2, \"nuclear_quadrupole_moment\": 0.3},\n {\"cq\": 0.7, \"eta\", 0.8, \"nuclear_quadrupole_moment\": 0.9},\n ...)\n\n .. attribute:: charge\n\n Charge on each ion as a tuple of dict, e.g.,\n ({\"p\": 0.154, \"s\": 0.078, \"d\": 0.0, \"tot\": 0.232}, ...)\n Note that this data is not always present. LORBIT must be set to some\n other value than the default.\n\n .. attribute:: is_stopped\n\n True if OUTCAR is from a stopped run (using STOPCAR, see Vasp Manual).\n\n .. attribute:: run_stats\n\n Various useful run stats as a dict including \"System time (sec)\",\n \"Total CPU time used (sec)\", \"Elapsed time (sec)\",\n \"Maximum memory used (kb)\", \"Average memory used (kb)\",\n \"User time (sec)\".\n\n .. attribute:: elastic_tensor\n Total elastic moduli (Kbar) is given in a 6x6 array matrix.\n\n .. attribute:: drift\n Total drift for each step in eV/Atom\n\n .. attribute:: ngf\n Dimensions for the Augementation grid\n\n .. attribute: sampling_radii\n Size of the sampling radii in VASP for the test charges for \n the electrostatic potential at each atom. Total array size is the number\n of elements present in the calculation\n\n .. attribute: electrostatic_potential\n Average electrostatic potential at each atomic position in order\n of the atoms in POSCAR.\n\n One can then call a specific reader depending on the type of run being\n performed. These are currently: read_igpar(), read_lepsilon() and\n read_lcalcpol(), read_core_state_eign(), read_avg_core_pot().\n\n See the documentation of those methods for more documentation.\n\n Authors: Rickard Armiento, Shyue Ping Ong\n \"\"\"\n\n def __init__(self, filename):\n self.filename = filename\n self.is_stopped = False\n\n # data from end of OUTCAR\n charge = []\n mag_x = []\n mag_y = []\n mag_z = []\n header = []\n run_stats = {}\n total_mag = None\n nelect = None\n efermi = None\n total_energy = None\n\n time_patt = re.compile(r\"\\((sec|kb)\\)\")\n efermi_patt = re.compile(r\"E-fermi\\s*:\\s*(\\S+)\")\n nelect_patt = re.compile(r\"number of electron\\s+(\\S+)\\s+magnetization\")\n mag_patt = re.compile(r\"number of electron\\s+\\S+\\s+magnetization\\s+(\"\n r\"\\S+)\")\n toten_pattern = re.compile(r\"free energy TOTEN\\s+=\\s+([\\d\\-\\.]+)\")\n\n all_lines = []\n for line in reverse_readfile(self.filename):\n clean = line.strip()\n all_lines.append(clean)\n if clean.find(\"soft stop encountered! aborting job\") != -1:\n self.is_stopped = True\n else:\n if time_patt.search(line):\n tok = line.strip().split(\":\")\n run_stats[tok[0].strip()] = float(tok[1].strip())\n continue\n m = efermi_patt.search(clean)\n if m:\n try:\n # try-catch because VASP sometimes prints\n # 'E-fermi: ******** XC(G=0): -6.1327\n # alpha+bet : -1.8238'\n efermi = float(m.group(1))\n continue\n except ValueError:\n efermi = None\n continue\n m = nelect_patt.search(clean)\n if m:\n nelect = float(m.group(1))\n m = mag_patt.search(clean)\n if m:\n total_mag = float(m.group(1))\n if total_energy is None:\n m = toten_pattern.search(clean)\n if m:\n total_energy = float(m.group(1))\n if all([nelect, total_mag is not None, efermi is not None,\n run_stats]):\n break\n\n # For single atom systems, VASP doesn't print a total line, so\n # reverse parsing is very difficult\n read_charge = False\n read_mag_x = False\n read_mag_y = False # for SOC calculations only\n read_mag_z = False\n all_lines.reverse()\n for clean in all_lines:\n if read_charge or read_mag_x or read_mag_y or read_mag_z:\n if clean.startswith(\"# of ion\"):\n header = re.split(r\"\\s{2,}\", clean.strip())\n header.pop(0)\n else:\n m = re.match(r\"\\s*(\\d+)\\s+(([\\d\\.\\-]+)\\s+)+\", clean)\n if m:\n toks = [float(i)\n for i in re.findall(r\"[\\d\\.\\-]+\", clean)]\n toks.pop(0)\n if read_charge:\n charge.append(dict(zip(header, toks)))\n elif read_mag_x:\n mag_x.append(dict(zip(header, toks)))\n elif read_mag_y:\n mag_y.append(dict(zip(header, toks)))\n elif read_mag_z:\n mag_z.append(dict(zip(header, toks)))\n elif clean.startswith('tot'):\n read_charge = False\n read_mag_x = False\n read_mag_y = False\n read_mag_z = False\n if clean == \"total charge\":\n charge = []\n read_charge = True\n read_mag_x, read_mag_y, read_mag_z = False, False, False\n elif clean == \"magnetization (x)\":\n mag_x = []\n read_mag_x = True\n read_charge, read_mag_y, read_mag_z = False, False, False\n elif clean == \"magnetization (y)\":\n mag_y = []\n read_mag_y = True\n read_charge, read_mag_x, read_mag_z = False, False, False\n elif clean == \"magnetization (z)\":\n mag_z = []\n read_mag_z = True\n read_charge, read_mag_x, read_mag_y = False, False, False\n\n # merge x, y and z components of magmoms if present (SOC calculation)\n if mag_y and mag_z:\n # TODO: detect spin axis\n mag = []\n for idx in range(len(mag_x)):\n mag.append({\n key: Magmom([mag_x[idx][key], mag_y[idx][key], mag_z[idx][key]])\n for key in mag_x[0].keys()\n })\n else:\n mag = mag_x\n\n # data from beginning of OUTCAR\n run_stats['cores'] = 0\n with zopen(filename, \"rt\") as f:\n for line in f:\n if \"running\" in line:\n run_stats['cores'] = line.split()[2]\n break\n\n self.run_stats = run_stats\n self.magnetization = tuple(mag)\n self.charge = tuple(charge)\n self.efermi = efermi\n self.nelect = nelect\n self.total_mag = total_mag\n self.final_energy = total_energy\n self.data = {}\n\n # Read the drift:\n self.read_pattern({\n \"drift\": r\"total drift:\\s+([\\.\\-\\d]+)\\s+([\\.\\-\\d]+)\\s+([\\.\\-\\d]+)\"},\n terminate_on_match=False,\n postprocess=float)\n self.drift = self.data.get('drift', [])\n\n # Check if calculation is spin polarized\n self.spin = False\n self.read_pattern({'spin': 'ISPIN = 2'})\n if self.data.get('spin', []):\n self.spin = True\n\n # Check if calculation is noncollinear\n self.noncollinear = False\n self.read_pattern({'noncollinear': 'LNONCOLLINEAR = T'})\n if self.data.get('noncollinear', []):\n self.noncollinear = False\n\n # Check to see if LEPSILON is true and read piezo data if so\n self.lepsilon = False\n self.read_pattern({'epsilon': 'LEPSILON= T'})\n if self.data.get('epsilon', []):\n self.lepsilon = True\n self.read_lepsilon()\n self.read_lepsilon_ionic()\n\n # Check to see if LCALCPOL is true and read polarization data if so\n self.lcalcpol = False\n self.read_pattern({'calcpol': 'LCALCPOL = T'})\n if self.data.get('calcpol', []):\n self.lcalcpol = True\n self.read_lcalcpol()\n self.read_pseudo_zval()\n\n # Read electrostatic potential\n self.read_pattern({\n 'electrostatic': r\"average \\(electrostatic\\) potential at core\"})\n if self.data.get('electrostatic', []):\n self.read_electrostatic_potential()\n\n self.nmr_cs = False\n self.read_pattern({\"nmr_cs\": r\"LCHIMAG = (T)\"})\n if self.data.get(\"nmr_cs\", None):\n self.nmr_cs = True\n self.read_chemical_shielding()\n self.read_cs_g0_contribution()\n self.read_cs_core_contribution()\n self.read_cs_raw_symmetrized_tensors()\n\n self.nmr_efg = False\n self.read_pattern({\"nmr_efg\": r\"NMR quadrupolar parameters\"})\n if self.data.get(\"nmr_efg\", None):\n self.nmr_efg = True\n self.read_nmr_efg()\n self.read_nmr_efg_tensor()\n\n def read_pattern(self, patterns, reverse=False, terminate_on_match=False,\n postprocess=str):\n \"\"\"\n General pattern reading. Uses monty's regrep method. Takes the same\n arguments.\n\n Args:\n patterns (dict): A dict of patterns, e.g.,\n {\"energy\": r\"energy\\\\(sigma->0\\\\)\\\\s+=\\\\s+([\\\\d\\\\-.]+)\"}.\n reverse (bool): Read files in reverse. Defaults to false. Useful for\n large files, esp OUTCARs, especially when used with\n terminate_on_match.\n terminate_on_match (bool): Whether to terminate when there is at\n least one match in each key in pattern.\n postprocess (callable): A post processing function to convert all\n matches. Defaults to str, i.e., no change.\n\n Renders accessible:\n Any attribute in patterns. For example,\n {\"energy\": r\"energy\\\\(sigma->0\\\\)\\\\s+=\\\\s+([\\\\d\\\\-.]+)\"} will set the\n value of self.data[\"energy\"] = [[-1234], [-3453], ...], to the\n results from regex and postprocess. Note that the returned values\n are lists of lists, because you can grep multiple items on one line.\n \"\"\"\n matches = regrep(self.filename, patterns, reverse=reverse,\n terminate_on_match=terminate_on_match,\n postprocess=postprocess)\n for k in patterns.keys():\n self.data[k] = [i[0] for i in matches.get(k, [])]\n\n def read_table_pattern(self, header_pattern, row_pattern, footer_pattern,\n postprocess=str, attribute_name=None,\n last_one_only=True):\n \"\"\"\n Parse table-like data. A table composes of three parts: header,\n main body, footer. All the data matches \"row pattern\" in the main body\n will be returned.\n\n Args:\n header_pattern (str): The regular expression pattern matches the\n table header. This pattern should match all the text\n immediately before the main body of the table. For multiple\n sections table match the text until the section of\n interest. MULTILINE and DOTALL options are enforced, as a\n result, the \".\" meta-character will also match \"\\n\" in this\n section.\n row_pattern (str): The regular expression matches a single line in\n the table. Capture interested field using regular expression\n groups.\n footer_pattern (str): The regular expression matches the end of the\n table. E.g. a long dash line.\n postprocess (callable): A post processing function to convert all\n matches. Defaults to str, i.e., no change.\n attribute_name (str): Name of this table. If present the parsed data\n will be attached to \"data. e.g. self.data[\"efg\"] = [...]\n last_one_only (bool): All the tables will be parsed, if this option\n is set to True, only the last table will be returned. The\n enclosing list will be removed. i.e. Only a single table will\n be returned. Default to be True.\n\n Returns:\n List of tables. 1) A table is a list of rows. 2) A row if either a list of\n attribute values in case the the capturing group is defined without name in\n row_pattern, or a dict in case that named capturing groups are defined by\n row_pattern.\n \"\"\"\n with zopen(self.filename, 'rt') as f:\n text = f.read()\n table_pattern_text = header_pattern + r\"\\s*^(?P<table_body>(?:\\s+\" + \\\n row_pattern + r\")+)\\s+\" + footer_pattern\n table_pattern = re.compile(table_pattern_text, re.MULTILINE | re.DOTALL)\n rp = re.compile(row_pattern)\n tables = []\n for mt in table_pattern.finditer(text):\n table_body_text = mt.group(\"table_body\")\n table_contents = []\n for line in table_body_text.split(\"\\n\"):\n ml = rp.search(line)\n d = ml.groupdict()\n if len(d) > 0:\n processed_line = {k: postprocess(v) for k, v in d.items()}\n else:\n processed_line = [postprocess(v) for v in ml.groups()]\n table_contents.append(processed_line)\n tables.append(table_contents)\n if last_one_only:\n retained_data = tables[-1]\n else:\n retained_data = tables\n if attribute_name is not None:\n self.data[attribute_name] = retained_data\n return retained_data\n\n def read_electrostatic_potential(self):\n \"\"\"\n Parses the eletrostatic potential for the last ionic step\n \"\"\"\n pattern = {\"ngf\": r\"\\s+dimension x,y,z NGXF=\\s+([\\.\\-\\d]+)\\sNGYF=\\s+([\\.\\-\\d]+)\\sNGZF=\\s+([\\.\\-\\d]+)\"}\n self.read_pattern(pattern, postprocess=int)\n self.ngf = self.data.get(\"ngf\", [[]])[0]\n\n pattern = {\"radii\": r\"the test charge radii are((?:\\s+[\\.\\-\\d]+)+)\"}\n self.read_pattern(pattern, reverse=True, terminate_on_match=True, postprocess=str)\n self.sampling_radii = [float(f) for f in self.data[\"radii\"][0][0].split()]\n\n header_pattern = r\"\\(the norm of the test charge is\\s+[\\.\\-\\d]+\\)\"\n table_pattern = r\"((?:\\s+\\d+\\s?[\\.\\-\\d]+)+)\"\n footer_pattern = r\"\\s+E-fermi :\"\n\n pots = self.read_table_pattern(header_pattern, table_pattern, footer_pattern)\n pots = \"\".join(itertools.chain.from_iterable(pots))\n\n pots = re.findall(r\"\\s+\\d+\\s?([\\.\\-\\d]+)+\", pots)\n pots = [float(f) for f in pots]\n\n self.electrostatic_potential = pots\n\n def read_freq_dielectric(self):\n \"\"\"\n Parses the frequency dependent dielectric function (obtained with\n LOPTICS). Frequencies (in eV) are in self.frequencies, and dielectric\n tensor function is given as self.dielectric_tensor_function.\n \"\"\"\n header_pattern = r\"\\s+frequency dependent\\s+IMAGINARY \" \\\n r\"DIELECTRIC FUNCTION \\(independent particle, \" \\\n r\"no local field effects\\)(\\sdensity-density)*$\"\n row_pattern = r\"\\s+\".join([r\"([\\.\\-\\d]+)\"] * 7)\n\n lines = []\n for l in reverse_readfile(self.filename):\n lines.append(l)\n if re.match(header_pattern, l):\n break\n\n freq = []\n data = {\"REAL\": [], \"IMAGINARY\": []}\n lines.reverse()\n count = 0\n component = \"IMAGINARY\"\n for l in lines[3:]: # Skip the preamble.\n if re.match(row_pattern, l.strip()):\n toks = l.strip().split()\n if component == \"IMAGINARY\":\n freq.append(float(toks[0]))\n xx, yy, zz, xy, yz, xz = [float(t) for t in toks[1:]]\n matrix = [[xx, xy, xz], [xy, yy, yz], [xz, yz, zz]]\n data[component].append(matrix)\n elif re.match(r\"\\s*-+\\s*\", l):\n count += 1\n if count == 1:\n component = \"REAL\"\n elif count == 2:\n break\n self.frequencies = np.array(freq)\n self.dielectric_tensor_function = np.array(data[\"REAL\"]) + \\\n 1j * np.array(data[\"IMAGINARY\"])\n\n def read_chemical_shielding(self):\n \"\"\"\n Parse the NMR chemical shieldings data. Only the second part \"absolute, valence and core\"\n will be parsed. And only the three right most field (ISO_SHIELDING, SPAN, SKEW) will be retrieved.\n\n Returns:\n List of chemical shieldings in the order of atoms from the OUTCAR. Maryland notation is adopted.\n \"\"\"\n header_pattern = r\"\\s+CSA tensor \\(J\\. Mason, Solid State Nucl\\. Magn\\. Reson\\. 2, \" \\\n r\"285 \\(1993\\)\\)\\s+\" \\\n r\"\\s+-{50,}\\s+\" \\\n r\"\\s+EXCLUDING G=0 CONTRIBUTION\\s+INCLUDING G=0 CONTRIBUTION\\s+\" \\\n r\"\\s+-{20,}\\s+-{20,}\\s+\" \\\n r\"\\s+ATOM\\s+ISO_SHIFT\\s+SPAN\\s+SKEW\\s+ISO_SHIFT\\s+SPAN\\s+SKEW\\s+\" \\\n r\"-{50,}\\s*$\"\n first_part_pattern = r\"\\s+\\(absolute, valence only\\)\\s+$\"\n swallon_valence_body_pattern = r\".+?\\(absolute, valence and core\\)\\s+$\"\n row_pattern = r\"\\d+(?:\\s+[-]?\\d+\\.\\d+){3}\\s+\" + r'\\s+'.join(\n [r\"([-]?\\d+\\.\\d+)\"] * 3)\n footer_pattern = r\"-{50,}\\s*$\"\n h1 = header_pattern + first_part_pattern\n cs_valence_only = self.read_table_pattern(\n h1, row_pattern, footer_pattern, postprocess=float,\n last_one_only=True)\n h2 = header_pattern + swallon_valence_body_pattern\n cs_valence_and_core = self.read_table_pattern(\n h2, row_pattern, footer_pattern, postprocess=float,\n last_one_only=True)\n all_cs = {}\n for name, cs_table in [[\"valence_only\", cs_valence_only],\n [\"valence_and_core\", cs_valence_and_core]]:\n all_cs[name] = cs_table\n self.data[\"chemical_shielding\"] = all_cs\n\n def read_cs_g0_contribution(self):\n \"\"\"\n Parse the G0 contribution of NMR chemical shielding.\n\n Returns:\n G0 contribution matrix as list of list. \n \"\"\"\n header_pattern = r'^\\s+G\\=0 CONTRIBUTION TO CHEMICAL SHIFT \\(field along BDIR\\)\\s+$\\n' \\\n r'^\\s+-{50,}$\\n' \\\n r'^\\s+BDIR\\s+X\\s+Y\\s+Z\\s*$\\n' \\\n r'^\\s+-{50,}\\s*$\\n'\n row_pattern = r'(?:\\d+)\\s+' + r'\\s+'.join([r'([-]?\\d+\\.\\d+)'] * 3)\n footer_pattern = r'\\s+-{50,}\\s*$'\n self.read_table_pattern(header_pattern, row_pattern, footer_pattern, postprocess=float,\n last_one_only=True, attribute_name=\"cs_g0_contribution\")\n\n def read_cs_core_contribution(self):\n \"\"\"\n Parse the core contribution of NMR chemical shielding.\n\n Returns:\n G0 contribution matrix as list of list. \n \"\"\"\n header_pattern = r'^\\s+Core NMR properties\\s*$\\n' \\\n r'\\n' \\\n r'^\\s+typ\\s+El\\s+Core shift \\(ppm\\)\\s*$\\n' \\\n r'^\\s+-{20,}$\\n'\n row_pattern = r'\\d+\\s+(?P<element>[A-Z][a-z]?\\w?)\\s+(?P<shift>[-]?\\d+\\.\\d+)'\n footer_pattern = r'\\s+-{20,}\\s*$'\n self.read_table_pattern(header_pattern, row_pattern, footer_pattern, postprocess=str,\n last_one_only=True, attribute_name=\"cs_core_contribution\")\n core_contrib = {d['element']: float(d['shift'])\n for d in self.data[\"cs_core_contribution\"]}\n self.data[\"cs_core_contribution\"] = core_contrib\n\n def read_cs_raw_symmetrized_tensors(self):\n \"\"\"\n Parse the matrix form of NMR tensor before corrected to table.\n\n Returns:\n nsymmetrized tensors list in the order of atoms. \n \"\"\"\n header_pattern = r\"\\s+-{50,}\\s+\" \\\n r\"\\s+Absolute Chemical Shift tensors\\s+\" \\\n r\"\\s+-{50,}$\"\n first_part_pattern = r\"\\s+UNSYMMETRIZED TENSORS\\s+$\"\n row_pattern = r\"\\s+\".join([r\"([-]?\\d+\\.\\d+)\"] * 3)\n unsym_footer_pattern = r\"^\\s+SYMMETRIZED TENSORS\\s+$\"\n\n with zopen(self.filename, 'rt') as f:\n text = f.read()\n unsym_table_pattern_text = header_pattern + first_part_pattern + \\\n r\"(?P<table_body>.+)\" + unsym_footer_pattern\n table_pattern = re.compile(unsym_table_pattern_text,\n re.MULTILINE | re.DOTALL)\n rp = re.compile(row_pattern)\n m = table_pattern.search(text)\n if m:\n table_text = m.group(\"table_body\")\n micro_header_pattern = r\"ion\\s+\\d+\"\n micro_table_pattern_text = micro_header_pattern + \\\n r\"\\s*^(?P<table_body>(?:\\s*\" + \\\n row_pattern + r\")+)\\s+\"\n micro_table_pattern = re.compile(micro_table_pattern_text,\n re.MULTILINE | re.DOTALL)\n unsym_tensors = []\n for mt in micro_table_pattern.finditer(table_text):\n table_body_text = mt.group(\"table_body\")\n tensor_matrix = []\n for line in table_body_text.rstrip().split(\"\\n\"):\n ml = rp.search(line)\n processed_line = [float(v) for v in ml.groups()]\n tensor_matrix.append(processed_line)\n unsym_tensors.append(tensor_matrix)\n self.data[\"unsym_cs_tensor\"] = unsym_tensors\n else:\n raise ValueError(\"NMR UNSYMMETRIZED TENSORS is not found\")\n\n def read_nmr_efg_tensor(self):\n \"\"\"\n Parses the NMR Electric Field Gradient Raw Tensors\n\n Returns:\n A list of Electric Field Gradient Tensors in the order of Atoms from OUTCAR\n \"\"\"\n\n header_pattern = r'Electric field gradients \\(V/A\\^2\\)\\n' \\\n r'-*\\n' \\\n r' ion\\s+V_xx\\s+V_yy\\s+V_zz\\s+V_xy\\s+V_xz\\s+V_yz\\n'\\\n r'-*\\n'\n\n row_pattern = r'\\d+\\s+([-\\d\\.]+)\\s+([-\\d\\.]+)\\s+([-\\d\\.]+)\\s+([-\\d\\.]+)\\s+([-\\d\\.]+)\\s+([-\\d\\.]+)'\n footer_pattern = r'-*\\n'\n\n data = self.read_table_pattern(header_pattern, row_pattern, footer_pattern, postprocess=float)\n tensors = [make_symmetric_matrix_from_upper_tri(d) for d in data]\n self.data[\"unsym_efg_tensor\"] = tensors\n return tensors\n\n def read_nmr_efg(self):\n \"\"\"\n Parse the NMR Electric Field Gradient interpretted values.\n\n Returns:\n Electric Field Gradient tensors as a list of dict in the order of atoms from OUTCAR.\n Each dict key/value pair corresponds to a component of the tensors.\n \"\"\"\n header_pattern = r'^\\s+NMR quadrupolar parameters\\s+$\\n' \\\n r'^\\s+Cq : quadrupolar parameter\\s+Cq=e[*]Q[*]V_zz/h$\\n' \\\n r'^\\s+eta: asymmetry parameters\\s+\\(V_yy - V_xx\\)/ V_zz$\\n' \\\n r'^\\s+Q : nuclear electric quadrupole moment in mb \\(millibarn\\)$\\n' \\\n r'^-{50,}$\\n' \\\n r'^\\s+ion\\s+Cq\\(MHz\\)\\s+eta\\s+Q \\(mb\\)\\s+$\\n' \\\n r'^-{50,}\\s*$\\n'\n row_pattern = r'\\d+\\s+(?P<cq>[-]?\\d+\\.\\d+)\\s+(?P<eta>[-]?\\d+\\.\\d+)\\s+' \\\n r'(?P<nuclear_quadrupole_moment>[-]?\\d+\\.\\d+)'\n footer_pattern = r'-{50,}\\s*$'\n self.read_table_pattern(header_pattern, row_pattern, footer_pattern, postprocess=float,\n last_one_only=True, attribute_name=\"efg\")\n\n def read_elastic_tensor(self):\n \"\"\"\n Parse the elastic tensor data.\n\n Returns:\n 6x6 array corresponding to the elastic tensor from the OUTCAR.\n \"\"\"\n header_pattern = r\"TOTAL ELASTIC MODULI \\(kBar\\)\\s+\"\\\n r\"Direction\\s+([X-Z][X-Z]\\s+)+\"\\\n r\"\\-+\"\n row_pattern = r\"[X-Z][X-Z]\\s+\" + r\"\\s+\".join([r\"(\\-*[\\.\\d]+)\"] * 6)\n footer_pattern = r\"\\-+\"\n et_table = self.read_table_pattern(header_pattern, row_pattern,\n footer_pattern, postprocess=float)\n self.data[\"elastic_tensor\"] = et_table\n\n def read_piezo_tensor(self):\n \"\"\"\n Parse the piezo tensor data\n \"\"\"\n header_pattern = r\"PIEZOELECTRIC TENSOR for field in x, y, \" \\\n r\"z\\s+\\(C/m\\^2\\)\\s+([X-Z][X-Z]\\s+)+\\-+\"\n row_pattern = r\"[x-z]\\s+\" + r\"\\s+\".join([r\"(\\-*[\\.\\d]+)\"] * 6)\n footer_pattern = r\"BORN EFFECTIVE\"\n pt_table = self.read_table_pattern(header_pattern, row_pattern,\n footer_pattern, postprocess=float)\n self.data[\"piezo_tensor\"] = pt_table\n\n def read_corrections(self, reverse=True, terminate_on_match=True):\n patterns = {\n \"dipol_quadrupol_correction\": r\"dipol\\+quadrupol energy \"\n r\"correction\\s+([\\d\\-\\.]+)\"\n }\n self.read_pattern(patterns, reverse=reverse,\n terminate_on_match=terminate_on_match,\n postprocess=float)\n self.data[\"dipol_quadrupol_correction\"] = self.data[\"dipol_quadrupol_correction\"][0][0]\n\n def read_neb(self, reverse=True, terminate_on_match=True):\n \"\"\"\n Reads NEB data. This only works with OUTCARs from both normal\n VASP NEB calculations or from the CI NEB method implemented by\n Henkelman et al.\n\n Args:\n reverse (bool): Read files in reverse. Defaults to false. Useful for\n large files, esp OUTCARs, especially when used with\n terminate_on_match. Defaults to True here since we usually\n want only the final value.\n terminate_on_match (bool): Whether to terminate when there is at\n least one match in each key in pattern. Defaults to True here\n since we usually want only the final value.\n\n Renders accessible:\n tangent_force - Final tangent force.\n energy - Final energy.\n These can be accessed under Outcar.data[key]\n \"\"\"\n patterns = {\n \"energy\": r\"energy\\(sigma->0\\)\\s+=\\s+([\\d\\-\\.]+)\",\n \"tangent_force\": r\"(NEB: projections on to tangent \\(spring, REAL\\)\\s+\\S+|tangential force \\(eV/A\\))\\s+([\\d\\-\\.]+)\"\n }\n self.read_pattern(patterns, reverse=reverse,\n terminate_on_match=terminate_on_match,\n postprocess=str)\n self.data[\"energy\"] = float(self.data[\"energy\"][0][0])\n if self.data.get(\"tangent_force\"):\n self.data[\"tangent_force\"] = float(\n self.data[\"tangent_force\"][0][1])\n\n def read_igpar(self):\n \"\"\"\n Renders accessible:\n er_ev = e<r>_ev (dictionary with Spin.up/Spin.down as keys)\n er_bp = e<r>_bp (dictionary with Spin.up/Spin.down as keys)\n er_ev_tot = spin up + spin down summed\n er_bp_tot = spin up + spin down summed\n p_elc = spin up + spin down summed\n p_ion = spin up + spin down summed\n\n (See VASP section \"LBERRY, IGPAR, NPPSTR, DIPOL tags\" for info on\n what these are).\n \"\"\"\n\n # variables to be filled\n self.er_ev = {} # will be dict (Spin.up/down) of array(3*float)\n self.er_bp = {} # will be dics (Spin.up/down) of array(3*float)\n self.er_ev_tot = None # will be array(3*float)\n self.er_bp_tot = None # will be array(3*float)\n self.p_elec = None\n self.p_ion = None\n try:\n search = []\n\n # Nonspin cases\n def er_ev(results, match):\n results.er_ev[Spin.up] = np.array(map(float,\n match.groups()[1:4])) / 2\n results.er_ev[Spin.down] = results.er_ev[Spin.up]\n results.context = 2\n\n search.append([r\"^ *e<r>_ev=\\( *([-0-9.Ee+]*) *([-0-9.Ee+]*) \"\n r\"*([-0-9.Ee+]*) *\\)\",\n None, er_ev])\n\n def er_bp(results, match):\n results.er_bp[Spin.up] = np.array([float(match.group(i))\n for i in range(1, 4)]) / 2\n results.er_bp[Spin.down] = results.er_bp[Spin.up]\n\n search.append([r\"^ *e<r>_bp=\\( *([-0-9.Ee+]*) *([-0-9.Ee+]*) \"\n r\"*([-0-9.Ee+]*) *\\)\",\n lambda results, line: results.context == 2, er_bp])\n\n # Spin cases\n def er_ev_up(results, match):\n results.er_ev[Spin.up] = np.array([float(match.group(i))\n for i in range(1, 4)])\n results.context = Spin.up\n\n search.append([r\"^.*Spin component 1 *e<r>_ev=\\( *([-0-9.Ee+]*) \"\n r\"*([-0-9.Ee+]*) *([-0-9.Ee+]*) *\\)\",\n None, er_ev_up])\n\n def er_bp_up(results, match):\n results.er_bp[Spin.up] = np.array([float(match.group(1)),\n float(match.group(2)),\n float(match.group(3))])\n\n search.append([r\"^ *e<r>_bp=\\( *([-0-9.Ee+]*) *([-0-9.Ee+]*) \"\n r\"*([-0-9.Ee+]*) *\\)\",\n lambda results,\n line: results.context == Spin.up, er_bp_up])\n\n def er_ev_dn(results, match):\n results.er_ev[Spin.down] = np.array([float(match.group(1)),\n float(match.group(2)),\n float(match.group(3))])\n results.context = Spin.down\n search.append([r\"^.*Spin component 2 *e<r>_ev=\\( *([-0-9.Ee+]*) \"\n r\"*([-0-9.Ee+]*) *([-0-9.Ee+]*) *\\)\",\n None, er_ev_dn])\n\n def er_bp_dn(results, match):\n results.er_bp[Spin.down] = np.array([float(match.group(i))\n for i in range(1, 4)])\n search.append([r\"^ *e<r>_bp=\\( *([-0-9.Ee+]*) *([-0-9.Ee+]*) \"\n r\"*([-0-9.Ee+]*) *\\)\",\n lambda results,\n line: results.context == Spin.down, er_bp_dn])\n\n # Always present spin/non-spin\n def p_elc(results, match):\n results.p_elc = np.array([float(match.group(i))\n for i in range(1, 4)])\n\n search.append([r\"^.*Total electronic dipole moment: \"\n r\"*p\\[elc\\]=\\( *([-0-9.Ee+]*) *([-0-9.Ee+]*) \"\n r\"*([-0-9.Ee+]*) *\\)\", None, p_elc])\n\n def p_ion(results, match):\n results.p_ion = np.array([float(match.group(i))\n for i in range(1, 4)])\n\n search.append([r\"^.*ionic dipole moment: \"\n r\"*p\\[ion\\]=\\( *([-0-9.Ee+]*) *([-0-9.Ee+]*) \"\n r\"*([-0-9.Ee+]*) *\\)\", None, p_ion])\n\n self.context = None\n self.er_ev = {Spin.up: None, Spin.down: None}\n self.er_bp = {Spin.up: None, Spin.down: None}\n\n micro_pyawk(self.filename, search, self)\n\n if self.er_ev[Spin.up] is not None and \\\n self.er_ev[Spin.down] is not None:\n self.er_ev_tot = self.er_ev[Spin.up] + self.er_ev[Spin.down]\n\n if self.er_bp[Spin.up] is not None and \\\n self.er_bp[Spin.down] is not None:\n self.er_bp_tot = self.er_bp[Spin.up] + self.er_bp[Spin.down]\n\n except:\n self.er_ev_tot = None\n self.er_bp_tot = None\n raise Exception(\"IGPAR OUTCAR could not be parsed.\")\n\n def read_lepsilon(self):\n # variables to be filled\n try:\n search = []\n\n def dielectric_section_start(results, match):\n results.dielectric_index = -1\n\n search.append([r\"MACROSCOPIC STATIC DIELECTRIC TENSOR \\(\", None,\n dielectric_section_start])\n\n def dielectric_section_start2(results, match):\n results.dielectric_index = 0\n\n search.append(\n [r\"-------------------------------------\",\n lambda results, line: results.dielectric_index == -1,\n dielectric_section_start2])\n\n def dielectric_data(results, match):\n results.dielectric_tensor[results.dielectric_index, :] = \\\n np.array([float(match.group(i)) for i in range(1, 4)])\n results.dielectric_index += 1\n\n search.append(\n [r\"^ *([-0-9.Ee+]+) +([-0-9.Ee+]+) +([-0-9.Ee+]+) *$\",\n lambda results, line: results.dielectric_index >= 0\n if results.dielectric_index is not None\n else None,\n dielectric_data])\n\n def dielectric_section_stop(results, match):\n results.dielectric_index = None\n\n search.append(\n [r\"-------------------------------------\",\n lambda results, line: results.dielectric_index >= 1\n if results.dielectric_index is not None\n else None,\n dielectric_section_stop])\n\n self.dielectric_index = None\n self.dielectric_tensor = np.zeros((3, 3))\n\n def piezo_section_start(results, match):\n results.piezo_index = 0\n\n search.append([r\"PIEZOELECTRIC TENSOR for field in x, y, z \"\n r\"\\(C/m\\^2\\)\",\n None, piezo_section_start])\n\n def piezo_data(results, match):\n results.piezo_tensor[results.piezo_index, :] = \\\n np.array([float(match.group(i)) for i in range(1, 7)])\n results.piezo_index += 1\n\n search.append(\n [r\"^ *[xyz] +([-0-9.Ee+]+) +([-0-9.Ee+]+)\" +\n r\" +([-0-9.Ee+]+) *([-0-9.Ee+]+) +([-0-9.Ee+]+)\" +\n r\" +([-0-9.Ee+]+)*$\",\n lambda results, line: results.piezo_index >= 0\n if results.piezo_index is not None\n else None,\n piezo_data])\n\n def piezo_section_stop(results, match):\n results.piezo_index = None\n\n search.append(\n [r\"-------------------------------------\",\n lambda results, line: results.piezo_index >= 1\n if results.piezo_index is not None\n else None,\n piezo_section_stop])\n\n self.piezo_index = None\n self.piezo_tensor = np.zeros((3, 6))\n\n def born_section_start(results, match):\n results.born_ion = -1\n\n search.append([r\"BORN EFFECTIVE CHARGES \" +\n r\"\\(in e, cummulative output\\)\",\n None, born_section_start])\n\n def born_ion(results, match):\n results.born_ion = int(match.group(1)) - 1\n results.born.append(np.zeros((3, 3)))\n\n search.append([r\"ion +([0-9]+)\", lambda results,\n line: results.born_ion is not None, born_ion])\n\n def born_data(results, match):\n results.born[results.born_ion][int(match.group(1)) - 1, :] = \\\n np.array([float(match.group(i)) for i in range(2, 5)])\n\n search.append(\n [r\"^ *([1-3]+) +([-0-9.Ee+]+) +([-0-9.Ee+]+) +([-0-9.Ee+]+)$\",\n lambda results, line: results.born_ion >= 0\n if results.born_ion is not None\n else results.born_ion,\n born_data])\n\n def born_section_stop(results, match):\n results.born_ion = None\n\n search.append(\n [r\"-------------------------------------\",\n lambda results, line: results.born_ion >= 1\n if results.born_ion is not None\n else results.born_ion,\n born_section_stop])\n\n self.born_ion = None\n self.born = []\n\n micro_pyawk(self.filename, search, self)\n\n self.born = np.array(self.born)\n\n self.dielectric_tensor = self.dielectric_tensor.tolist()\n self.piezo_tensor = self.piezo_tensor.tolist()\n\n except:\n raise Exception(\"LEPSILON OUTCAR could not be parsed.\")\n\n def read_lepsilon_ionic(self):\n # variables to be filled\n try:\n search = []\n\n def dielectric_section_start(results, match):\n results.dielectric_ionic_index = -1\n\n search.append([r\"MACROSCOPIC STATIC DIELECTRIC TENSOR IONIC\", None,\n dielectric_section_start])\n\n def dielectric_section_start2(results, match):\n results.dielectric_ionic_index = 0\n\n search.append(\n [r\"-------------------------------------\",\n lambda results, line: results.dielectric_ionic_index == -1\n if results.dielectric_ionic_index is not None\n else results.dielectric_ionic_index,\n dielectric_section_start2])\n\n def dielectric_data(results, match):\n results.dielectric_ionic_tensor[results.dielectric_ionic_index, :] = \\\n np.array([float(match.group(i)) for i in range(1, 4)])\n results.dielectric_ionic_index += 1\n\n search.append(\n [r\"^ *([-0-9.Ee+]+) +([-0-9.Ee+]+) +([-0-9.Ee+]+) *$\",\n lambda results, line: results.dielectric_ionic_index >= 0\n if results.dielectric_ionic_index is not None\n else results.dielectric_ionic_index,\n dielectric_data])\n\n def dielectric_section_stop(results, match):\n results.dielectric_ionic_index = None\n\n search.append(\n [r\"-------------------------------------\",\n lambda results, line: results.dielectric_ionic_index >= 1\n if results.dielectric_ionic_index is not None\n else results.dielectric_ionic_index,\n dielectric_section_stop])\n\n self.dielectric_ionic_index = None\n self.dielectric_ionic_tensor = np.zeros((3, 3))\n\n def piezo_section_start(results, match):\n results.piezo_ionic_index = 0\n\n search.append([r\"PIEZOELECTRIC TENSOR IONIC CONTR for field in \"\n r\"x, y, z \",\n None, piezo_section_start])\n\n def piezo_data(results, match):\n results.piezo_ionic_tensor[results.piezo_ionic_index, :] = \\\n np.array([float(match.group(i)) for i in range(1, 7)])\n results.piezo_ionic_index += 1\n\n search.append(\n [r\"^ *[xyz] +([-0-9.Ee+]+) +([-0-9.Ee+]+)\" +\n r\" +([-0-9.Ee+]+) *([-0-9.Ee+]+) +([-0-9.Ee+]+)\" +\n r\" +([-0-9.Ee+]+)*$\",\n lambda results, line: results.piezo_ionic_index >= 0\n if results.piezo_ionic_index is not None\n else results.piezo_ionic_index,\n piezo_data])\n\n def piezo_section_stop(results, match):\n results.piezo_ionic_index = None\n\n search.append(\n [\"-------------------------------------\",\n lambda results, line: results.piezo_ionic_index >= 1\n if results.piezo_ionic_index is not None\n else results.piezo_ionic_index,\n piezo_section_stop])\n\n self.piezo_ionic_index = None\n self.piezo_ionic_tensor = np.zeros((3, 6))\n\n micro_pyawk(self.filename, search, self)\n\n self.dielectric_ionic_tensor = self.dielectric_ionic_tensor.tolist()\n self.piezo_ionic_tensor = self.piezo_ionic_tensor.tolist()\n\n except:\n raise Exception(\n \"ionic part of LEPSILON OUTCAR could not be parsed.\")\n\n def read_lcalcpol(self):\n # variables to be filled\n self.p_elec = None\n self.p_sp1 = None\n self.p_sp2 = None\n self.p_ion = None\n try:\n search = []\n\n # Always present spin/non-spin\n def p_elec(results, match):\n results.p_elec = np.array([float(match.group(1)),\n float(match.group(2)),\n float(match.group(3))])\n\n search.append([r\"^.*Total electronic dipole moment: \"\n r\"*p\\[elc\\]=\\( *([-0-9.Ee+]*) *([-0-9.Ee+]*) \"\n r\"*([-0-9.Ee+]*) *\\)\",\n None, p_elec])\n\n # If spin-polarized (and not noncollinear)\n # save spin-polarized electronic values\n if self.spin and not self.noncollinear:\n def p_sp1(results, match):\n results.p_sp1 = np.array([float(match.group(1)),\n float(match.group(2)),\n float(match.group(3))])\n\n search.append([r\"^.*p\\[sp1\\]=\\( *([-0-9.Ee+]*) *([-0-9.Ee+]*) \"\n r\"*([-0-9.Ee+]*) *\\)\",\n None, p_sp1])\n\n def p_sp2(results, match):\n results.p_sp2 = np.array([float(match.group(1)),\n float(match.group(2)),\n float(match.group(3))])\n\n search.append([r\"^.*p\\[sp2\\]=\\( *([-0-9.Ee+]*) *([-0-9.Ee+]*) \"\n r\"*([-0-9.Ee+]*) *\\)\",\n None, p_sp2])\n\n def p_ion(results, match):\n results.p_ion = np.array([float(match.group(1)),\n float(match.group(2)),\n float(match.group(3))])\n search.append([r\"^.*Ionic dipole moment: *p\\[ion\\]=\"\n r\"\\( *([-0-9.Ee+]*)\"\n r\" *([-0-9.Ee+]*) *([-0-9.Ee+]*) *\\)\",\n None, p_ion])\n\n micro_pyawk(self.filename, search, self)\n\n except:\n raise Exception(\"LCALCPOL OUTCAR could not be parsed.\")\n\n def read_pseudo_zval(self):\n \"\"\"\n Create pseudopotential ZVAL dictionary.\n \"\"\"\n try:\n def poscar_line(results, match):\n poscar_line = match.group(1)\n results.poscar_line = re.findall(r'[A-Z][a-z]?', poscar_line)\n\n def zvals(results, match):\n zvals = match.group(1)\n results.zvals = map(float, re.findall(r'-?\\d+\\.\\d*', zvals))\n\n search = []\n search.append([r'^.*POSCAR.*=(.*)', None, poscar_line])\n search.append([r'^\\s+ZVAL.*=(.*)', None, zvals])\n\n micro_pyawk(self.filename, search, self)\n\n zval_dict = {}\n for x, y in zip(self.poscar_line, self.zvals):\n zval_dict.update({x: y})\n self.zval_dict = zval_dict\n\n # Clean-up\n del(self.poscar_line)\n del(self.zvals)\n except:\n raise Exception(\"ZVAL dict could not be parsed.\")\n\n def read_core_state_eigen(self):\n \"\"\"\n Read the core state eigenenergies at each ionic step.\n\n Returns:\n A list of dict over the atom such as [{\"AO\":[core state eig]}].\n The core state eigenenergie list for each AO is over all ionic\n step.\n\n Example:\n The core state eigenenergie of the 2s AO of the 6th atom of the\n structure at the last ionic step is [5][\"2s\"][-1]\n \"\"\"\n\n with zopen(self.filename, \"rt\") as foutcar:\n line = foutcar.readline()\n while line != \"\":\n line = foutcar.readline()\n if \"NIONS =\" in line:\n natom = int(line.split(\"NIONS =\")[1])\n cl = [defaultdict(list) for i in range(natom)]\n if \"the core state eigen\" in line:\n iat = -1\n while line != \"\":\n line = foutcar.readline()\n # don't know number of lines to parse without knowing\n # specific species, so stop parsing when we reach\n # \"E-fermi\" instead\n if \"E-fermi\" in line:\n break\n data = line.split()\n # data will contain odd number of elements if it is\n # the start of a new entry, or even number of elements\n # if it continues the previous entry\n if len(data) % 2 == 1:\n iat += 1 # started parsing a new ion\n data = data[1:] # remove element with ion number\n for i in range(0, len(data), 2):\n cl[iat][data[i]].append(float(data[i + 1]))\n return cl\n\n def read_avg_core_poten(self):\n \"\"\"\n Read the core potential at each ionic step.\n\n Returns:\n A list for each ionic step containing a list of the average core\n potentials for each atom: [[avg core pot]].\n\n Example:\n The average core potential of the 2nd atom of the structure at the\n last ionic step is: [-1][1]\n \"\"\"\n\n def pairwise(iterable):\n \"s -> (s0,s1), (s1,s2), (s2, s3), ...\"\n a = iter(iterable)\n return zip(a, a)\n\n with zopen(self.filename, \"rt\") as foutcar:\n line = foutcar.readline()\n aps = []\n while line != \"\":\n line = foutcar.readline()\n if \"the norm of the test charge is\" in line:\n ap = []\n while line != \"\":\n line = foutcar.readline()\n # don't know number of lines to parse without knowing\n # specific species, so stop parsing when we reach\n # \"E-fermi\" instead\n if \"E-fermi\" in line:\n aps.append(ap)\n break\n data = line.split()\n # the average core potentials of up to 5 elements are\n # given per line\n for i, pot in pairwise(data):\n ap.append(float(pot))\n return aps\n\n def as_dict(self):\n d = {\"@module\": self.__class__.__module__,\n \"@class\": self.__class__.__name__, \"efermi\": self.efermi,\n \"run_stats\": self.run_stats, \"magnetization\": self.magnetization,\n \"charge\": self.charge, \"total_magnetization\": self.total_mag,\n \"nelect\": self.nelect, \"is_stopped\": self.is_stopped,\n \"drift\": self.drift, \"ngf\": self.ngf,\n \"sampling_radii\": self.sampling_radii,\n \"electrostatic_potential\": self.electrostatic_potential}\n\n if self.lepsilon:\n d.update({'piezo_tensor': self.piezo_tensor,\n 'piezo_ionic_tensor': self.piezo_ionic_tensor,\n 'dielectric_tensor': self.dielectric_tensor,\n 'dielectric_ionic_tensor': self.dielectric_ionic_tensor,\n 'born_ion': self.born_ion,\n 'born': self.born})\n\n if self.lcalcpol:\n d.update({'p_elec': self.p_elec,\n 'p_ion': self.p_ion})\n if self.spin and not self.noncollinear:\n d.update({'p_sp1': self.p_sp1,\n 'p_sp2': self.p_sp2})\n d.update({'zval_dict': self.zval_dict})\n\n if self.nmr_cs:\n d.update({\"nmr_cs\": {\"valence and core\": self.data[\"chemical_shielding\"][\"valence_and_core\"],\n \"valence_only\": self.data[\"chemical_shielding\"][\"valence_only\"],\n \"g0\": self.data[\"cs_g0_contribution\"],\n \"core\": self.data[\"cs_core_contribution\"],\n \"raw\": self.data[\"unsym_cs_tensor\"]}})\n\n if self.nmr_efg:\n d.update({\"nmr_efg\": {\"raw\": self.data[\"unsym_efg_tensor\"],\n \"parameters\": self.data[\"efg\"]}})\n\n return d\n\n def read_fermi_contact_shift(self):\n '''\n output example:\n Fermi contact (isotropic) hyperfine coupling parameter (MHz)\n -------------------------------------------------------------\n ion A_pw A_1PS A_1AE A_1c A_tot\n -------------------------------------------------------------\n 1 -0.002 -0.002 -0.051 0.000 -0.052\n 2 -0.002 -0.002 -0.051 0.000 -0.052\n 3 0.056 0.056 0.321 -0.048 0.321\n -------------------------------------------------------------\n , which corresponds to\n [[-0.002, -0.002, -0.051, 0.0, -0.052],\n [-0.002, -0.002, -0.051, 0.0, -0.052],\n [0.056, 0.056, 0.321, -0.048, 0.321]] from 'fch' data\n '''\n\n # Fermi contact (isotropic) hyperfine coupling parameter (MHz)\n header_pattern1 = r\"\\s*Fermi contact \\(isotropic\\) hyperfine coupling parameter \\(MHz\\)\\s+\" \\\n r\"\\s*\\-+\" \\\n r\"\\s*ion\\s+A_pw\\s+A_1PS\\s+A_1AE\\s+A_1c\\s+A_tot\\s+\" \\\n r\"\\s*\\-+\"\n row_pattern1 = r'(?:\\d+)\\s+' + r'\\s+'.join([r'([-]?\\d+\\.\\d+)'] * 5)\n footer_pattern = r\"\\-+\"\n fch_table = self.read_table_pattern(header_pattern1, row_pattern1,\n footer_pattern, postprocess=float,\n last_one_only=True)\n\n # Dipolar hyperfine coupling parameters (MHz)\n header_pattern2 = r\"\\s*Dipolar hyperfine coupling parameters \\(MHz\\)\\s+\" \\\n r\"\\s*\\-+\" \\\n r\"\\s*ion\\s+A_xx\\s+A_yy\\s+A_zz\\s+A_xy\\s+A_xz\\s+A_yz\\s+\" \\\n r\"\\s*\\-+\"\n row_pattern2 = r'(?:\\d+)\\s+' + r'\\s+'.join([r'([-]?\\d+\\.\\d+)'] * 6)\n dh_table = self.read_table_pattern(header_pattern2, row_pattern2,\n footer_pattern, postprocess=float,\n last_one_only=True)\n\n # Total hyperfine coupling parameters after diagonalization (MHz)\n header_pattern3 = r\"\\s*Total hyperfine coupling parameters after diagonalization \\(MHz\\)\\s+\" \\\n r\"\\s*\\(convention: \\|A_zz\\| > \\|A_xx\\| > \\|A_yy\\|\\)\\s+\" \\\n r\"\\s*\\-+\" \\\n r\"\\s*ion\\s+A_xx\\s+A_yy\\s+A_zz\\s+asymmetry \\(A_yy - A_xx\\)/ A_zz\\s+\" \\\n r\"\\s*\\-+\"\n row_pattern3 = r'(?:\\d+)\\s+' + r'\\s+'.join([r'([-]?\\d+\\.\\d+)'] * 4)\n th_table = self.read_table_pattern(header_pattern3, row_pattern3,\n footer_pattern, postprocess=float,\n last_one_only=True)\n\n fc_shift_table = {'fch': fch_table, 'dh': dh_table, 'th': th_table}\n\n self.data[\"fermi_contact_shift\"] = fc_shift_table\n\n\nclass VolumetricData(object):\n \"\"\"\n Simple volumetric object for reading LOCPOT and CHGCAR type files.\n\n .. attribute:: structure\n\n Structure associated with the Volumetric Data object\n\n ..attribute:: is_spin_polarized\n\n True if run is spin polarized\n\n ..attribute:: dim\n\n Tuple of dimensions of volumetric grid in each direction (nx, ny, nz).\n\n ..attribute:: data\n\n Actual data as a dict of {string: np.array}. The string are \"total\"\n and \"diff\", in accordance to the output format of vasp LOCPOT and\n CHGCAR files where the total spin density is written first, followed\n by the difference spin density.\n\n .. attribute:: ngridpts\n\n Total number of grid points in volumetric data.\n \"\"\"\n\n def __init__(self, structure, data, distance_matrix=None, data_aug=None):\n \"\"\"\n Typically, this constructor is not used directly and the static\n from_file constructor is used. This constructor is designed to allow\n summation and other operations between VolumetricData objects.\n\n Args:\n structure: Structure associated with the volumetric data\n data: Actual volumetric data.\n data_aug: Any extra information associated with volumetric data\n (typically augmentation charges)\n distance_matrix: A pre-computed distance matrix if available.\n Useful so pass distance_matrices between sums,\n shortcircuiting an otherwise expensive operation.\n \"\"\"\n self.structure = structure\n self.is_spin_polarized = len(data) >= 2\n self.is_soc = len(data) >= 4\n self.dim = data[\"total\"].shape\n self.data = data\n self.data_aug = data_aug if data_aug else {}\n self.ngridpts = self.dim[0] * self.dim[1] * self.dim[2]\n # lazy init the spin data since this is not always needed.\n self._spin_data = {}\n self._distance_matrix = {} if not distance_matrix else distance_matrix\n\n @property\n def spin_data(self):\n \"\"\"\n The data decomposed into actual spin data as {spin: data}.\n Essentially, this provides the actual Spin.up and Spin.down data\n instead of the total and diff. Note that by definition, a\n non-spin-polarized run would have Spin.up data == Spin.down data.\n \"\"\"\n if not self._spin_data:\n spin_data = dict()\n spin_data[Spin.up] = 0.5 * (self.data[\"total\"] +\n self.data.get(\"diff\", 0))\n spin_data[Spin.down] = 0.5 * (self.data[\"total\"] -\n self.data.get(\"diff\", 0))\n self._spin_data = spin_data\n return self._spin_data\n\n def get_axis_grid(self, ind):\n \"\"\"\n Returns the grid for a particular axis.\n\n Args:\n ind (int): Axis index.\n \"\"\"\n ng = self.dim\n num_pts = ng[ind]\n lengths = self.structure.lattice.abc\n return [i / num_pts * lengths[ind] for i in range(num_pts)]\n\n def __add__(self, other):\n return self.linear_add(other, 1.0)\n\n def __sub__(self, other):\n return self.linear_add(other, -1.0)\n\n def linear_add(self, other, scale_factor=1.0):\n \"\"\"\n Method to do a linear sum of volumetric objects. Used by + and -\n operators as well. Returns a VolumetricData object containing the\n linear sum.\n\n Args:\n other (VolumetricData): Another VolumetricData object\n scale_factor (float): Factor to scale the other data by.\n\n Returns:\n VolumetricData corresponding to self + scale_factor * other.\n \"\"\"\n if self.structure != other.structure:\n raise ValueError(\"Adding or subtraction operations can only be \"\n \"performed for volumetric data with the exact \"\n \"same structure.\")\n # To add checks\n data = {}\n for k in self.data.keys():\n data[k] = self.data[k] + scale_factor * other.data[k]\n return VolumetricData(self.structure, data, self._distance_matrix)\n\n @staticmethod\n def parse_file(filename):\n \"\"\"\n Convenience method to parse a generic volumetric data file in the vasp\n like format. Used by subclasses for parsing file.\n\n Args:\n filename (str): Path of file to parse\n\n Returns:\n (poscar, data)\n \"\"\"\n poscar_read = False\n poscar_string = []\n dataset = []\n all_dataset = []\n # for holding any strings in input that are not Poscar\n # or VolumetricData (typically augmentation charges)\n all_dataset_aug = {}\n dim = None\n dimline = None\n read_dataset = False\n ngrid_pts = 0\n data_count = 0\n poscar = None\n with zopen(filename, \"rt\") as f:\n for line in f:\n original_line = line\n line = line.strip()\n if read_dataset:\n toks = line.split()\n for tok in toks:\n if data_count < ngrid_pts:\n # This complicated procedure is necessary because\n # vasp outputs x as the fastest index, followed by y\n # then z.\n x = data_count % dim[0]\n y = int(math.floor(data_count / dim[0])) % dim[1]\n z = int(math.floor(data_count / dim[0] / dim[1]))\n dataset[x, y, z] = float(tok)\n data_count += 1\n if data_count >= ngrid_pts:\n read_dataset = False\n data_count = 0\n all_dataset.append(dataset)\n elif not poscar_read:\n if line != \"\" or len(poscar_string) == 0:\n poscar_string.append(line)\n elif line == \"\":\n poscar = Poscar.from_string(\"\\n\".join(poscar_string))\n poscar_read = True\n elif not dim:\n dim = [int(i) for i in line.split()]\n ngrid_pts = dim[0] * dim[1] * dim[2]\n dimline = line\n read_dataset = True\n dataset = np.zeros(dim)\n elif line == dimline:\n # when line == dimline, expect volumetric data to follow\n # so set read_dataset to True\n read_dataset = True\n dataset = np.zeros(dim)\n else:\n # store any extra lines that were not part of the\n # volumetric data so we know which set of data the extra\n # lines are associated with\n key = len(all_dataset) - 1\n if key not in all_dataset_aug:\n all_dataset_aug[key] = []\n all_dataset_aug[key].append(original_line)\n if len(all_dataset) == 4:\n\n data = {\"total\": all_dataset[0], \"diff_x\": all_dataset[1],\n \"diff_y\": all_dataset[2], \"diff_z\": all_dataset[3]}\n data_aug = {\"total\": all_dataset_aug.get(0, None),\n \"diff_x\": all_dataset_aug.get(1, None),\n \"diff_y\": all_dataset_aug.get(2, None),\n \"diff_z\": all_dataset_aug.get(3, None)}\n\n # construct a \"diff\" dict for scalar-like magnetization density,\n # referenced to an arbitrary direction (using same method as\n # pymatgen.electronic_structure.core.Magmom, see\n # Magmom documentation for justification for this)\n # TODO: re-examine this, and also similar behavior in\n # Magmom - @mkhorton\n # TODO: does CHGCAR change with different SAXIS?\n diff_xyz = np.array([data[\"diff_x\"], data[\"diff_y\"],\n data[\"diff_z\"]])\n diff_xyz = diff_xyz.reshape((3, dim[0] * dim[1] * dim[2]))\n ref_direction = np.array([1.01, 1.02, 1.03])\n ref_sign = np.sign(np.dot(ref_direction, diff_xyz))\n diff = np.multiply(np.linalg.norm(diff_xyz, axis=0), ref_sign)\n data[\"diff\"] = diff.reshape((dim[0], dim[1], dim[2]))\n\n elif len(all_dataset) == 2:\n data = {\"total\": all_dataset[0], \"diff\": all_dataset[1]}\n data_aug = {\"total\": all_dataset_aug.get(0, None),\n \"diff\": all_dataset_aug.get(1, None)}\n else:\n data = {\"total\": all_dataset[0]}\n data_aug = {\"total\": all_dataset_aug.get(0, None)}\n return poscar, data, data_aug\n\n def write_file(self, file_name, vasp4_compatible=False):\n \"\"\"\n Write the VolumetricData object to a vasp compatible file.\n\n Args:\n file_name (str): Path to a file\n vasp4_compatible (bool): True if the format is vasp4 compatible\n \"\"\"\n\n def _print_fortran_float(f):\n \"\"\"\n Fortran codes print floats with a leading zero in scientific\n notation. When writing CHGCAR files, we adopt this convention\n to ensure written CHGCAR files are byte-to-byte identical to\n their input files as far as possible.\n :param f: float\n :return: str\n \"\"\"\n s = \"{:.10E}\".format(f)\n if f >= 0:\n return \"0.\" + s[0] + s[2:12] + 'E' + \"{:+03}\".format(int(s[13:]) + 1)\n else:\n return \"-.\" + s[1] + s[3:13] + 'E' + \"{:+03}\".format(int(s[14:]) + 1)\n\n with zopen(file_name, \"wt\") as f:\n p = Poscar(self.structure)\n\n # use original name if it's been set (e.g. from Chgcar)\n comment = getattr(self, 'name', p.comment)\n\n lines = comment + \"\\n\"\n lines += \" 1.00000000000000\\n\"\n latt = self.structure.lattice.matrix\n lines += \" %12.6f%12.6f%12.6f\\n\" % tuple(latt[0, :])\n lines += \" %12.6f%12.6f%12.6f\\n\" % tuple(latt[1, :])\n lines += \" %12.6f%12.6f%12.6f\\n\" % tuple(latt[2, :])\n if not vasp4_compatible:\n lines += \"\".join([\"%5s\" % s for s in p.site_symbols]) + \"\\n\"\n lines += \"\".join([\"%6d\" % x for x in p.natoms]) + \"\\n\"\n lines += \"Direct\\n\"\n for site in self.structure:\n lines += \"%10.6f%10.6f%10.6f\\n\" % tuple(site.frac_coords)\n lines += \" \\n\"\n f.write(lines)\n a = self.dim\n\n def write_spin(data_type):\n lines = []\n count = 0\n f.write(\" {} {} {}\\n\".format(a[0], a[1], a[2]))\n for (k, j, i) in itertools.product(list(range(a[2])),\n list(range(a[1])),\n list(range(a[0]))):\n lines.append(_print_fortran_float(self.data[data_type][i, j, k]))\n count += 1\n if count % 5 == 0:\n f.write(\" \" + \"\".join(lines) + \"\\n\")\n lines = []\n else:\n lines.append(\" \")\n f.write(\" \" + \"\".join(lines) + \" \\n\")\n f.write(\"\".join(self.data_aug.get(data_type, [])))\n\n write_spin(\"total\")\n if self.is_spin_polarized and self.is_soc:\n write_spin(\"diff_x\")\n write_spin(\"diff_y\")\n write_spin(\"diff_z\")\n elif self.is_spin_polarized:\n write_spin(\"diff\")\n\n def get_integrated_diff(self, ind, radius, nbins=1):\n \"\"\"\n Get integrated difference of atom index ind up to radius. This can be\n an extremely computationally intensive process, depending on how many\n grid points are in the VolumetricData.\n\n Args:\n ind (int): Index of atom.\n radius (float): Radius of integration.\n nbins (int): Number of bins. Defaults to 1. This allows one to\n obtain the charge integration up to a list of the cumulative\n charge integration values for radii for [radius/nbins,\n 2 * radius/nbins, ....].\n\n Returns:\n Differential integrated charge as a np array of [[radius, value],\n ...]. Format is for ease of plotting. E.g., plt.plot(data[:,0],\n data[:,1])\n \"\"\"\n # For non-spin-polarized runs, this is zero by definition.\n if not self.is_spin_polarized:\n radii = [radius / nbins * (i + 1) for i in range(nbins)]\n data = np.zeros((nbins, 2))\n data[:, 0] = radii\n return data\n\n struct = self.structure\n a = self.dim\n if ind not in self._distance_matrix or\\\n self._distance_matrix[ind][\"max_radius\"] < radius:\n coords = []\n for (x, y, z) in itertools.product(*[list(range(i)) for i in a]):\n coords.append([x / a[0], y / a[1], z / a[2]])\n sites_dist = struct.lattice.get_points_in_sphere(\n coords, struct[ind].coords, radius)\n self._distance_matrix[ind] = {\"max_radius\": radius,\n \"data\": np.array(sites_dist)}\n\n data = self._distance_matrix[ind][\"data\"]\n\n # Use boolean indexing to find all charges within the desired distance.\n inds = data[:, 1] <= radius\n dists = data[inds, 1]\n data_inds = np.rint(np.mod(list(data[inds, 0]), 1) *\n np.tile(a, (len(dists), 1))).astype(int)\n vals = [self.data[\"diff\"][x, y, z] for x, y, z in data_inds]\n\n hist, edges = np.histogram(dists, bins=nbins,\n range=[0, radius],\n weights=vals)\n data = np.zeros((nbins, 2))\n data[:, 0] = edges[1:]\n data[:, 1] = [sum(hist[0:i + 1]) / self.ngridpts\n for i in range(nbins)]\n return data\n\n def get_average_along_axis(self, ind):\n \"\"\"\n Get the averaged total of the volumetric data a certain axis direction.\n For example, useful for visualizing Hartree Potentials from a LOCPOT\n file.\n\n Args:\n ind (int): Index of axis.\n\n Returns:\n Average total along axis\n \"\"\"\n m = self.data[\"total\"]\n ng = self.dim\n if ind == 0:\n total = np.sum(np.sum(m, axis=1), 1)\n elif ind == 1:\n total = np.sum(np.sum(m, axis=0), 1)\n else:\n total = np.sum(np.sum(m, axis=0), 0)\n return total / ng[(ind + 1) % 3] / ng[(ind + 2) % 3]\n\n def to_hdf5(self, filename):\n \"\"\"\n Writes the VolumetricData to a HDF5 format, which is a highly optimized\n format for reading storing large data. The mapping of the VolumetricData\n to this file format is as follows:\n\n VolumetricData.data -> f[\"vdata\"]\n VolumetricData.structure ->\n f[\"Z\"]: Sequence of atomic numbers\n f[\"fcoords\"]: Fractional coords\n f[\"lattice\"]: Lattice in the pymatgen.core.lattice.Lattice matrix\n format\n f.attrs[\"structure_json\"]: String of json representation\n\n Args:\n filename (str): Filename to output to.\n \"\"\"\n import h5py\n with h5py.File(filename, \"w\") as f:\n ds = f.create_dataset(\"lattice\", (3, 3), dtype='float')\n ds[...] = self.structure.lattice.matrix\n ds = f.create_dataset(\"Z\", (len(self.structure.species), ),\n dtype=\"i\")\n ds[...] = np.array([sp.Z for sp in self.structure.species])\n ds = f.create_dataset(\"fcoords\", self.structure.frac_coords.shape,\n dtype='float')\n ds[...] = self.structure.frac_coords\n dt = h5py.special_dtype(vlen=str)\n ds = f.create_dataset(\"species\", (len(self.structure.species), ),\n dtype=dt)\n ds[...] = [str(sp) for sp in self.structure.species]\n grp = f.create_group(\"vdata\")\n for k, v in self.data.items():\n ds = grp.create_dataset(k, self.data[k].shape, dtype='float')\n ds[...] = self.data[k]\n f.attrs[\"name\"] = self.name\n f.attrs[\"structure_json\"] = json.dumps(self.structure.as_dict())\n\n @classmethod\n def from_hdf5(cls, filename):\n import h5py\n with h5py.File(filename, \"r\") as f:\n data = {k: np.array(v) for k, v in f[\"vdata\"].items()}\n structure = Structure.from_dict(json.loads(f.attrs[\"structure_json\"]))\n return VolumetricData(structure, data)\n\n\nclass Locpot(VolumetricData):\n \"\"\"\n Simple object for reading a LOCPOT file.\n\n Args:\n poscar (Poscar): Poscar object containing structure.\n data: Actual data.\n \"\"\"\n\n def __init__(self, poscar, data):\n super(Locpot, self).__init__(poscar.structure, data)\n self.name = poscar.comment\n\n @staticmethod\n def from_file(filename):\n (poscar, data, data_aug) = VolumetricData.parse_file(filename)\n return Locpot(poscar, data)\n\n\nclass Chgcar(VolumetricData):\n \"\"\"\n Simple object for reading a CHGCAR file.\n\n Args:\n poscar (Poscar): Poscar object containing structure.\n data: Actual data.\n \"\"\"\n\n def __init__(self, poscar, data, data_aug=None):\n super(Chgcar, self).__init__(poscar.structure, data, data_aug=data_aug)\n self.poscar = poscar\n self.name = poscar.comment\n self._distance_matrix = {}\n\n @staticmethod\n def from_file(filename):\n (poscar, data, data_aug) = VolumetricData.parse_file(filename)\n return Chgcar(poscar, data, data_aug=data_aug)\n\n @property\n def net_magnetization(self):\n if self.is_spin_polarized:\n return np.sum(self.data['diff'])\n else:\n return None\n\n\nclass Procar(object):\n \"\"\"\n Object for reading a PROCAR file.\n\n Args:\n filename: Name of file containing PROCAR.\n\n .. attribute:: data\n\n The PROCAR data of the form below. It should VASP uses 1-based indexing,\n but all indices are converted to 0-based here.::\n\n {\n spin: nd.array accessed with (k-point index, band index,\n ion index, orbital index)\n }\n\n .. attribute:: weights\n\n The weights associated with each k-point as an nd.array of lenght\n nkpoints.\n\n ..attribute:: phase_factors\n\n Phase factors, where present (e.g. LORBIT = 12). A dict of the form:\n {\n spin: complex nd.array accessed with (k-point index, band index,\n ion index, orbital index)\n }\n\n ..attribute:: nbands\n\n Number of bands\n\n ..attribute:: nkpoints\n\n Number of k-points\n\n ..attribute:: nions\n\n Number of ions\n \"\"\"\n\n def __init__(self, filename):\n headers = None\n\n with zopen(filename, \"rt\") as f:\n preambleexpr = re.compile(\n r\"# of k-points:\\s*(\\d+)\\s+# of bands:\\s*(\\d+)\\s+# of \"\n r\"ions:\\s*(\\d+)\")\n kpointexpr = re.compile(r\"^k-point\\s+(\\d+).*weight = ([0-9\\.]+)\")\n bandexpr = re.compile(r\"^band\\s+(\\d+)\")\n ionexpr = re.compile(r\"^ion.*\")\n expr = re.compile(r\"^([0-9]+)\\s+\")\n current_kpoint = 0\n current_band = 0\n done = False\n spin = Spin.down\n\n for l in f:\n l = l.strip()\n if bandexpr.match(l):\n m = bandexpr.match(l)\n current_band = int(m.group(1)) - 1\n done = False\n elif kpointexpr.match(l):\n m = kpointexpr.match(l)\n current_kpoint = int(m.group(1)) - 1\n weights[current_kpoint] = float(m.group(2))\n if current_kpoint == 0:\n spin = Spin.up if spin == Spin.down else Spin.down\n done = False\n elif headers is None and ionexpr.match(l):\n headers = l.split()\n headers.pop(0)\n headers.pop(-1)\n\n def f():\n return np.zeros((nkpoints, nbands, nions, len(headers)))\n\n data = defaultdict(f)\n\n def f2():\n return np.full((nkpoints, nbands, nions, len(headers)),\n np.NaN, dtype=np.complex128)\n phase_factors = defaultdict(f2)\n elif expr.match(l):\n toks = l.split()\n index = int(toks.pop(0)) - 1\n num_data = np.array([float(t)\n for t in toks[:len(headers)]])\n if not done:\n data[spin][current_kpoint, current_band,\n index, :] = num_data\n else:\n if np.isnan(phase_factors[spin][\n current_kpoint, current_band, index, 0]):\n phase_factors[spin][current_kpoint, current_band,\n index, :] = num_data\n else:\n phase_factors[spin][current_kpoint, current_band,\n index, :] += 1j * num_data\n elif l.startswith(\"tot\"):\n done = True\n elif preambleexpr.match(l):\n m = preambleexpr.match(l)\n nkpoints = int(m.group(1))\n nbands = int(m.group(2))\n nions = int(m.group(3))\n weights = np.zeros(nkpoints)\n\n self.nkpoints = nkpoints\n self.nbands = nbands\n self.nions = nions\n self.weights = weights\n self.orbitals = headers\n self.data = data\n self.phase_factors = phase_factors\n\n def get_projection_on_elements(self, structure):\n \"\"\"\n Method returning a dictionary of projections on elements.\n\n Args:\n structure (Structure): Input structure.\n\n Returns:\n a dictionary in the {Spin.up:[k index][b index][{Element:values}]]\n \"\"\"\n dico = {}\n for spin in self.data.keys():\n dico[spin] = [[defaultdict(float)\n for i in range(self.nkpoints)]\n for j in range(self.nbands)]\n\n for iat in range(self.nions):\n name = structure.species[iat].symbol\n for spin, d in self.data.items():\n for k, b in itertools.product(range(self.nkpoints),\n range(self.nbands)):\n dico[spin][b][k][name] = np.sum(d[k, b, iat, :])\n\n return dico\n\n def get_occupation(self, atom_index, orbital):\n \"\"\"\n Returns the occupation for a particular orbital of a particular atom.\n\n Args:\n atom_num (int): Index of atom in the PROCAR. It should be noted\n that VASP uses 1-based indexing for atoms, but this is\n converted to 0-based indexing in this parser to be\n consistent with representation of structures in pymatgen.\n orbital (str): An orbital. If it is a single character, e.g., s,\n p, d or f, the sum of all s-type, p-type, d-type or f-type\n orbitals occupations are returned respectively. If it is a\n specific orbital, e.g., px, dxy, etc., only the occupation\n of that orbital is returned.\n\n Returns:\n Sum occupation of orbital of atom.\n \"\"\"\n\n orbital_index = self.orbitals.index(orbital)\n return {spin: np.sum(d[:, :, atom_index, orbital_index] * self.weights[:, None])\n for spin, d in self.data.items()}\n\n\nclass Oszicar(object):\n \"\"\"\n A basic parser for an OSZICAR output from VASP. In general, while the\n OSZICAR is useful for a quick look at the output from a VASP run, we\n recommend that you use the Vasprun parser instead, which gives far richer\n information about a run.\n\n Args:\n filename (str): Filename of file to parse\n\n .. attribute:: electronic_steps\n\n All electronic steps as a list of list of dict. e.g.,\n [[{\"rms\": 160.0, \"E\": 4507.24605593, \"dE\": 4507.2, \"N\": 1,\n \"deps\": -17777.0, \"ncg\": 16576}, ...], [....]\n where electronic_steps[index] refers the list of electronic steps\n in one ionic_step, electronic_steps[index][subindex] refers to a\n particular electronic step at subindex in ionic step at index. The\n dict of properties depends on the type of VASP run, but in general,\n \"E\", \"dE\" and \"rms\" should be present in almost all runs.\n\n .. attribute:: ionic_steps:\n\n All ionic_steps as a list of dict, e.g.,\n [{\"dE\": -526.36, \"E0\": -526.36024, \"mag\": 0.0, \"F\": -526.36024},\n ...]\n This is the typical output from VASP at the end of each ionic step.\n \"\"\"\n\n def __init__(self, filename):\n electronic_steps = []\n ionic_steps = []\n ionic_pattern = re.compile(r\"(\\d+)\\s+F=\\s*([\\d\\-\\.E\\+]+)\\s+\"\n r\"E0=\\s*([\\d\\-\\.E\\+]+)\\s+\"\n r\"d\\s*E\\s*=\\s*([\\d\\-\\.E\\+]+)$\")\n ionic_mag_pattern = re.compile(r\"(\\d+)\\s+F=\\s*([\\d\\-\\.E\\+]+)\\s+\"\n r\"E0=\\s*([\\d\\-\\.E\\+]+)\\s+\"\n r\"d\\s*E\\s*=\\s*([\\d\\-\\.E\\+]+)\\s+\"\n r\"mag=\\s*([\\d\\-\\.E\\+]+)\")\n ionic_MD_pattern = re.compile(r\"(\\d+)\\s+T=\\s*([\\d\\-\\.E\\+]+)\\s+\"\n r\"E=\\s*([\\d\\-\\.E\\+]+)\\s+\"\n r\"F=\\s*([\\d\\-\\.E\\+]+)\\s+\"\n r\"E0=\\s*([\\d\\-\\.E\\+]+)\\s+\"\n r\"EK=\\s*([\\d\\-\\.E\\+]+)\\s+\"\n r\"SP=\\s*([\\d\\-\\.E\\+]+)\\s+\"\n r\"SK=\\s*([\\d\\-\\.E\\+]+)\")\n electronic_pattern = re.compile(r\"\\s*\\w+\\s*:(.*)\")\n\n def smart_convert(header, num):\n try:\n if header == \"N\" or header == \"ncg\":\n v = int(num)\n return v\n v = float(num)\n return v\n except ValueError:\n return \"--\"\n\n header = []\n with zopen(filename, \"rt\") as fid:\n for line in fid:\n line = line.strip()\n m = electronic_pattern.match(line)\n if m:\n toks = m.group(1).split()\n data = {header[i]: smart_convert(header[i], toks[i])\n for i in range(len(toks))}\n if toks[0] == \"1\":\n electronic_steps.append([data])\n else:\n electronic_steps[-1].append(data)\n elif ionic_pattern.match(line.strip()):\n m = ionic_pattern.match(line.strip())\n ionic_steps.append({\"F\": float(m.group(2)),\n \"E0\": float(m.group(3)),\n \"dE\": float(m.group(4))})\n elif ionic_mag_pattern.match(line.strip()):\n m = ionic_mag_pattern.match(line.strip())\n ionic_steps.append({\"F\": float(m.group(2)),\n \"E0\": float(m.group(3)),\n \"dE\": float(m.group(4)),\n \"mag\": float(m.group(5))})\n elif ionic_MD_pattern.match(line.strip()):\n m = ionic_MD_pattern.match(line.strip())\n ionic_steps.append({\"T\": float(m.group(2)),\n \"E\": float(m.group(3)),\n \"F\": float(m.group(4)),\n \"E0\": float(m.group(5)),\n \"EK\": float(m.group(6)),\n \"SP\": float(m.group(7)),\n \"SK\": float(m.group(8))})\n elif re.match(r\"^\\s*N\\s+E\\s*\", line):\n header = line.strip().replace(\"d eps\", \"deps\").split()\n self.electronic_steps = electronic_steps\n self.ionic_steps = ionic_steps\n\n @property\n def all_energies(self):\n \"\"\"\n Compilation of all energies from all electronic steps and ionic steps\n as a tuple of list of energies, e.g.,\n ((4507.24605593, 143.824705755, -512.073149912, ...), ...)\n \"\"\"\n all_energies = []\n for i in range(len(self.electronic_steps)):\n energies = [step[\"E\"] for step in self.electronic_steps[i]]\n energies.append(self.ionic_steps[i][\"F\"])\n all_energies.append(tuple(energies))\n return tuple(all_energies)\n\n @property\n @unitized(\"eV\")\n def final_energy(self):\n \"\"\"\n Final energy from run.\n \"\"\"\n return self.ionic_steps[-1][\"E0\"]\n\n def as_dict(self):\n return {\"electronic_steps\": self.electronic_steps,\n \"ionic_steps\": self.ionic_steps}\n\n\nclass VaspParserError(Exception):\n \"\"\"\n Exception class for VASP parsing.\n \"\"\"\n pass\n\n\ndef get_band_structure_from_vasp_multiple_branches(dir_name, efermi=None,\n projections=False):\n \"\"\"\n This method is used to get band structure info from a VASP directory. It\n takes into account that the run can be divided in several branches named\n \"branch_x\". If the run has not been divided in branches the method will\n turn to parsing vasprun.xml directly.\n\n The method returns None is there\"s a parsing error\n\n Args:\n dir_name: Directory containing all bandstructure runs.\n efermi: Efermi for bandstructure.\n projections: True if you want to get the data on site projections if\n any. Note that this is sometimes very large\n\n Returns:\n A BandStructure Object\n \"\"\"\n # TODO: Add better error handling!!!\n if os.path.exists(os.path.join(dir_name, \"branch_0\")):\n # get all branch dir names\n branch_dir_names = [os.path.abspath(d)\n for d in glob.glob(\"{i}/branch_*\"\n .format(i=dir_name))\n if os.path.isdir(d)]\n\n # sort by the directory name (e.g, branch_10)\n sort_by = lambda x: int(x.split(\"_\")[-1])\n sorted_branch_dir_names = sorted(branch_dir_names, key=sort_by)\n\n # populate branches with Bandstructure instances\n branches = []\n for dir_name in sorted_branch_dir_names:\n xml_file = os.path.join(dir_name, \"vasprun.xml\")\n if os.path.exists(xml_file):\n run = Vasprun(xml_file, parse_projected_eigen=projections)\n branches.append(run.get_band_structure(efermi=efermi))\n else:\n # It might be better to throw an exception\n warnings.warn(\"Skipping {}. Unable to find {}\"\n .format(d=dir_name, f=xml_file))\n\n return get_reconstructed_band_structure(branches, efermi)\n else:\n xml_file = os.path.join(dir_name, \"vasprun.xml\")\n # Better handling of Errors\n if os.path.exists(xml_file):\n return Vasprun(xml_file, parse_projected_eigen=projections)\\\n .get_band_structure(kpoints_filename=None, efermi=efermi)\n else:\n return None\n\n\nclass Xdatcar(object):\n \"\"\"\n Class representing an XDATCAR file. Only tested with VASP 5.x files.\n\n .. attribute:: structures\n\n List of structures parsed from XDATCAR.\n .. attribute:: comment\n\n Optional comment string.\n Authors: Ram Balachandran\n \"\"\"\n\n def __init__(self, filename, ionicstep_start=1,\n ionicstep_end=None, comment=None):\n \"\"\"\n Init a Xdatcar.\n\n Args:\n filename (str): Filename of input XDATCAR file.\n ionicstep_start (int): Starting number of ionic step.\n ionicstep_end (int): Ending number of ionic step.\n \"\"\"\n preamble = None\n coords_str = []\n structures = []\n preamble_done = False\n if (ionicstep_start < 1):\n raise Exception('Start ionic step cannot be less than 1')\n if (ionicstep_end is not None and\n ionicstep_start < 1):\n raise Exception('End ionic step cannot be less than 1')\n\n ionicstep_cnt = 1\n with zopen(filename, \"rt\") as f:\n for l in f:\n l = l.strip()\n if preamble is None:\n preamble = [l]\n elif not preamble_done:\n if l == \"\" or \"Direct configuration=\" in l:\n preamble_done = True\n tmp_preamble = [preamble[0]]\n for i in range(1, len(preamble)):\n if preamble[0] != preamble[i]:\n tmp_preamble.append(preamble[i])\n else:\n break\n preamble = tmp_preamble\n else:\n preamble.append(l)\n elif l == \"\" or \"Direct configuration=\" in l:\n p = Poscar.from_string(\"\\n\".join(preamble +\n [\"Direct\"] + coords_str))\n if ionicstep_end is None:\n if (ionicstep_cnt >= ionicstep_start):\n structures.append(p.structure)\n else:\n if ionicstep_start <= ionicstep_cnt < ionicstep_end:\n structures.append(p.structure)\n ionicstep_cnt += 1\n coords_str = []\n else:\n coords_str.append(l)\n p = Poscar.from_string(\"\\n\".join(preamble +\n [\"Direct\"] + coords_str))\n if ionicstep_end is None:\n if ionicstep_cnt >= ionicstep_start:\n structures.append(p.structure)\n else:\n if ionicstep_start <= ionicstep_cnt < ionicstep_end:\n structures.append(p.structure)\n self.structures = structures\n self.comment = comment or self.structures[0].formula\n\n @property\n def site_symbols(self):\n \"\"\"\n Sequence of symbols associated with the Xdatcar. Similar to 6th line in\n vasp 5+ Xdatcar.\n \"\"\"\n syms = [site.specie.symbol for site in self.structures[0]]\n return [a[0] for a in itertools.groupby(syms)]\n\n @property\n def natoms(self):\n \"\"\"\n Sequence of number of sites of each type associated with the Poscar.\n Similar to 7th line in vasp 5+ Xdatcar.\n \"\"\"\n syms = [site.specie.symbol for site in self.structures[0]]\n return [len(tuple(a[1])) for a in itertools.groupby(syms)]\n\n def concatenate(self, filename, ionicstep_start=1,\n ionicstep_end=None):\n \"\"\"\n Concatenate structures in file to Xdatcar.\n\n Args:\n filename (str): Filename of XDATCAR file to be concatenated.\n ionicstep_start (int): Starting number of ionic step.\n ionicstep_end (int): Ending number of ionic step.\n TODO(rambalachandran):\n Requires a check to ensure if the new concatenating file has the\n same lattice structure and atoms as the Xdatcar class.\n \"\"\"\n preamble = None\n coords_str = []\n structures = self.structures\n preamble_done = False\n if ionicstep_start < 1:\n raise Exception('Start ionic step cannot be less than 1')\n if (ionicstep_end is not None and\n ionicstep_start < 1):\n raise Exception('End ionic step cannot be less than 1')\n ionicstep_cnt = 1\n with zopen(filename, \"rt\") as f:\n for l in f:\n l = l.strip()\n if preamble is None:\n preamble = [l]\n elif not preamble_done:\n if l == \"\" or \"Direct configuration=\" in l:\n preamble_done = True\n tmp_preamble = [preamble[0]]\n for i in range(1, len(preamble)):\n if preamble[0] != preamble[i]:\n tmp_preamble.append(preamble[i])\n else:\n break\n preamble = tmp_preamble\n else:\n preamble.append(l)\n elif l == \"\" or \"Direct configuration=\" in l:\n p = Poscar.from_string(\"\\n\".join(preamble +\n [\"Direct\"] + coords_str))\n if ionicstep_end is None:\n if (ionicstep_cnt >= ionicstep_start):\n structures.append(p.structure)\n else:\n if ionicstep_start <= ionicstep_cnt < ionicstep_end:\n structures.append(p.structure)\n ionicstep_cnt += 1\n coords_str = []\n else:\n coords_str.append(l)\n p = Poscar.from_string(\"\\n\".join(preamble +\n [\"Direct\"] + coords_str))\n if ionicstep_end is None:\n if ionicstep_cnt >= ionicstep_start:\n structures.append(p.structure)\n else:\n if ionicstep_start <= ionicstep_cnt < ionicstep_end:\n structures.append(p.structure)\n self.structures = structures\n\n def get_string(self, ionicstep_start=1,\n ionicstep_end=None,\n significant_figures=8):\n \"\"\"\n Write Xdatcar class into a file\n Args:\n filename (str): Filename of output XDATCAR file.\n ionicstep_start (int): Starting number of ionic step.\n ionicstep_end (int): Ending number of ionic step.\n \"\"\"\n from pymatgen.io.vasp import Poscar\n if (ionicstep_start < 1):\n raise Exception('Start ionic step cannot be less than 1')\n if (ionicstep_end is not None and\n ionicstep_start < 1):\n raise Exception('End ionic step cannot be less than 1')\n latt = self.structures[0].lattice\n if np.linalg.det(latt.matrix) < 0:\n latt = Lattice(-latt.matrix)\n lines = [self.comment, \"1.0\", str(latt)]\n lines.append(\" \".join(self.site_symbols))\n lines.append(\" \".join([str(x) for x in self.natoms]))\n format_str = \"{{:.{0}f}}\".format(significant_figures)\n ionicstep_cnt = 1\n output_cnt = 1\n for cnt, structure in enumerate(self.structures):\n ionicstep_cnt = cnt + 1\n if ionicstep_end is None:\n if (ionicstep_cnt >= ionicstep_start):\n lines.append(\"Direct configuration=\" +\n ' ' * (7 - len(str(output_cnt))) + str(output_cnt))\n for (i, site) in enumerate(structure):\n coords = site.frac_coords\n line = \" \".join([format_str.format(c) for c in coords])\n lines.append(line)\n output_cnt += 1\n else:\n if ionicstep_start <= ionicstep_cnt < ionicstep_end:\n lines.append(\"Direct configuration=\" +\n ' ' * (7 - len(str(output_cnt))) + str(output_cnt))\n for (i, site) in enumerate(structure):\n coords = site.frac_coords\n line = \" \".join([format_str.format(c) for c in coords])\n lines.append(line)\n output_cnt += 1\n return \"\\n\".join(lines) + \"\\n\"\n\n def write_file(self, filename, **kwargs):\n \"\"\"\n Write Xdatcar class into a file.\n Args:\n filename (str): Filename of output XDATCAR file.\n The supported kwargs are the same as those for the\n Xdatcar.get_string method and are passed through directly.\n \"\"\"\n with zopen(filename, \"wt\") as f:\n f.write(self.get_string(**kwargs))\n\n def __str__(self):\n return self.get_string()\n\n\nclass Dynmat(object):\n \"\"\"\n Object for reading a DYNMAT file.\n\n Args:\n filename: Name of file containing DYNMAT.\n\n .. attribute:: data\n\n A nested dict containing the DYNMAT data of the form::\n [atom <int>][disp <int>]['dispvec'] =\n displacement vector (part of first line in dynmat block, e.g. \"0.01 0 0\")\n [atom <int>][disp <int>]['dynmat'] =\n <list> list of dynmat lines for this atom and this displacement\n\n Authors: Patrick Huck\n \"\"\"\n\n def __init__(self, filename):\n with zopen(filename, \"rt\") as f:\n lines = list(clean_lines(f.readlines()))\n self._nspecs, self._natoms, self._ndisps = map(int, lines[\n 0].split())\n self._masses = map(float, lines[1].split())\n self.data = defaultdict(dict)\n atom, disp = None, None\n for i, l in enumerate(lines[2:]):\n v = list(map(float, l.split()))\n if not i % (self._natoms + 1):\n atom, disp = map(int, v[:2])\n if atom not in self.data:\n self.data[atom] = {}\n if disp not in self.data[atom]:\n self.data[atom][disp] = {}\n self.data[atom][disp]['dispvec'] = v[2:]\n else:\n if 'dynmat' not in self.data[atom][disp]:\n self.data[atom][disp]['dynmat'] = []\n self.data[atom][disp]['dynmat'].append(v)\n\n def get_phonon_frequencies(self):\n \"\"\"calculate phonon frequencies\"\"\"\n # TODO: the following is most likely not correct or suboptimal\n # hence for demonstration purposes only\n frequencies = []\n for k, v0 in self.data.iteritems():\n for v1 in v0.itervalues():\n vec = map(abs, v1['dynmat'][k - 1])\n frequency = math.sqrt(sum(vec)) * 2. * \\\n math.pi * 15.633302 # THz\n frequencies.append(frequency)\n return frequencies\n\n @property\n def nspecs(self):\n \"\"\"returns the number of species\"\"\"\n return self._nspecs\n\n @property\n def natoms(self):\n \"\"\"returns the number of atoms\"\"\"\n return self._natoms\n\n @property\n def ndisps(self):\n \"\"\"returns the number of displacements\"\"\"\n return self._ndisps\n\n @property\n def masses(self):\n \"\"\"returns the list of atomic masses\"\"\"\n return list(self._masses)\n\n\ndef get_adjusted_fermi_level(efermi, cbm, band_structure):\n \"\"\"\n When running a band structure computations the fermi level needs to be\n take from the static run that gave the charge density used for the non-self\n consistent band structure run. Sometimes this fermi level is however a\n little too low because of the mismatch between the uniform grid used in\n the static run and the band structure k-points (e.g., the VBM is on Gamma\n and the Gamma point is not in the uniform mesh). Here we use a procedure\n consisting in looking for energy levels higher than the static fermi level\n (but lower than the LUMO) if any of these levels make the band structure\n appears insulating and not metallic anymore, we keep this adjusted fermi\n level. This procedure has shown to detect correctly most insulators.\n\n Args:\n efermi (float): Fermi energy of the static run\n cbm (float): Conduction band minimum of the static run\n run_bandstructure: a band_structure object\n\n Returns:\n a new adjusted fermi level\n \"\"\"\n # make a working copy of band_structure\n bs_working = BandStructureSymmLine.from_dict(band_structure.as_dict())\n if bs_working.is_metal():\n e = efermi\n while e < cbm:\n e += 0.01\n bs_working._efermi = e\n if not bs_working.is_metal():\n return e\n return efermi\n\n\nclass Wavecar:\n \"\"\"\n This is a class that contains the (pseudo-) wavefunctions from VASP.\n\n Coefficients are read from the given WAVECAR file and the corresponding\n G-vectors are generated using the algorithm developed in WaveTrans (see\n acknowledgments below). To understand how the wavefunctions are evaluated,\n please see the evaluate_wavefunc docstring.\n\n It should be noted that the pseudopotential augmentation is not included in\n the WAVECAR file. As a result, some caution should be exercised when\n deriving value from this information.\n\n The usefulness of this class is to allow the user to do projections or band\n unfolding style manipulations of the wavefunction. An example of this can\n be seen in the work of Shen et al. 2017\n (https://doi.org/10.1103/PhysRevMaterials.1.065001).\n\n .. attribute:: filename\n\n String of the input file (usually WAVECAR)\n\n .. attribute:: nk\n\n Number of k-points from the WAVECAR\n\n .. attribute:: nb\n\n Number of bands per k-point\n\n .. attribute:: encut\n\n Energy cutoff (used to define G_{cut})\n\n .. attribute:: efermi\n\n Fermi energy\n\n .. attribute:: a\n\n Primitive lattice vectors of the cell (e.g. a_1 = self.a[0, :])\n\n .. attribute:: b\n\n Reciprocal lattice vectors of the cell (e.g. b_1 = self.b[0, :])\n\n .. attribute:: vol\n\n The volume of the unit cell in real space\n\n .. attribute:: kpoints\n\n The list of k-points read from the WAVECAR file\n\n .. attribute:: band_energy\n\n The list of band eigenenergies (and corresponding occupancies) for\n each kpoint, where the first index corresponds to the index of the\n k-point (e.g. self.band_energy[kp])\n\n .. attribute:: Gpoints\n\n The list of generated G-points for each k-point (a double list), which\n are used with the coefficients for each k-point and band to recreate\n the wavefunction (e.g. self.Gpoints[kp] is the list of G-points for\n k-point kp). The G-points depend on the k-point and reciprocal lattice\n and therefore are identical for each band at the same k-point. Each\n G-point is represented by integer multipliers (e.g. assuming\n Gpoints[kp][n] == [n_1, n_2, n_3], then\n G_n = n_1*b_1 + n_2*b_2 + n_3*b_3)\n\n .. attribute:: coeffs\n\n The list of coefficients for each k-point and band for reconstructing\n the wavefunction. The first index corresponds to the kpoint and the\n second corresponds to the band (e.g. self.coeffs[kp][b] corresponds\n to k-point kp and band b).\n\n Acknowledgments:\n This code is based upon the Fortran program, WaveTrans, written by\n R. M. Feenstra and M. Widom from the Dept. of Physics at Carnegie\n Mellon University. To see the original work, please visit:\n https://www.andrew.cmu.edu/user/feenstra/wavetrans/\n\n Author: Mark Turiansky\n \"\"\"\n\n def __init__(self, filename='WAVECAR', verbose=False, precision='normal'):\n \"\"\"\n Information is extracted from the given WAVECAR\n\n Args:\n filename (str): input file (default: WAVECAR)\n verbose (bool): determines whether processing information is shown\n precision (str): determines how fine the fft mesh is (normal or\n accurate), only the first letter matters\n \"\"\"\n self.filename = filename\n\n # c = 0.26246582250210965422\n # 2m/hbar^2 in agreement with VASP\n self._C = 0.262465831\n with open(self.filename, 'rb') as f:\n # read the header information\n recl, spin, rtag = np.fromfile(f, dtype=np.float64, count=3) \\\n .astype(np.int)\n if verbose:\n print('recl={}, spin={}, rtag={}'.format(recl, spin, rtag))\n recl8 = int(recl / 8)\n\n # check that ISPIN wasn't set to 2\n if spin == 2:\n raise ValueError('spin polarization not currently supported')\n\n # check to make sure we have precision correct\n if rtag != 45200 and rtag != 45210:\n raise ValueError('invalid rtag of {}'.format(rtag))\n\n # padding\n np.fromfile(f, dtype=np.float64, count=(recl8 - 3))\n\n # extract kpoint, bands, energy, and lattice information\n self.nk, self.nb, self.encut = np.fromfile(f, dtype=np.float64,\n count=3).astype(np.int)\n self.a = np.fromfile(f, dtype=np.float64, count=9).reshape((3, 3))\n self.efermi = np.fromfile(f, dtype=np.float64, count=1)[0]\n if verbose:\n print('kpoints = {}, bands = {}, energy cutoff = {}, fermi '\n 'energy= {:.04f}\\n'.format(self.nk, self.nb, self.encut,\n self.efermi))\n print('primitive lattice vectors = \\n{}'.format(self.a))\n\n self.vol = np.dot(self.a[0, :],\n np.cross(self.a[1, :], self.a[2, :]))\n if verbose:\n print('volume = {}\\n'.format(self.vol))\n\n # calculate reciprocal lattice\n b = np.array([np.cross(self.a[1, :], self.a[2, :]),\n np.cross(self.a[2, :], self.a[0, :]),\n np.cross(self.a[0, :], self.a[1, :])])\n b = 2 * np.pi * b / self.vol\n self.b = b\n if verbose:\n print('reciprocal lattice vectors = \\n{}'.format(b))\n print('reciprocal lattice vector magnitudes = \\n{}\\n'\n .format(np.linalg.norm(b, axis=1)))\n\n # calculate maximum number of b vectors in each direction\n self._generate_nbmax()\n if verbose:\n print('max number of G values = {}\\n\\n'.format(self._nbmax))\n self.ng = self._nbmax * 3 if precision.lower()[0] == 'n' else \\\n self._nbmax * 4\n\n # padding\n np.fromfile(f, dtype=np.float64, count=recl8 - 13)\n\n # reading records\n # np.set_printoptions(precision=7, suppress=True)\n self.Gpoints = [None for _ in range(self.nk)]\n self.coeffs = [[None for i in range(self.nb)]\n for j in range(self.nk)]\n self.kpoints = []\n self.band_energy = []\n for ispin in range(spin):\n if verbose:\n print('reading spin {}'.format(ispin))\n for ink in range(self.nk):\n # information for this kpoint\n nplane = int(np.fromfile(f, dtype=np.float64, count=1)[0])\n kpoint = np.fromfile(f, dtype=np.float64, count=3)\n self.kpoints.append(kpoint)\n if verbose:\n print('kpoint {: 4} with {: 5} plane waves at {}'\n .format(ink, nplane, kpoint))\n\n # energy and occupation information\n enocc = np.fromfile(f, dtype=np.float64,\n count=3 * self.nb).reshape((self.nb, 3))\n self.band_energy.append(enocc)\n if verbose:\n print(enocc[:, [0, 2]])\n\n # padding\n np.fromfile(f, dtype=np.float64, count=(recl8 - 4 - 3 * self.nb))\n\n # generate G integers\n self.Gpoints[ink] = self._generate_G_points(kpoint)\n if len(self.Gpoints[ink]) != nplane:\n raise ValueError('failed to generate the correct '\n 'number of G points')\n\n # extract coefficients\n for inb in range(self.nb):\n if rtag == 45200:\n self.coeffs[ink][inb] = \\\n np.fromfile(f, dtype=np.complex64,\n count=nplane)\n np.fromfile(f, dtype=np.float64,\n count=recl8 - nplane)\n elif rtag == 45210:\n # this should handle double precision coefficients\n # but I don't have a WAVECAR to test it with\n self.coeffs[ink][inb] = \\\n np.fromfile(f, dtype=np.complex128,\n count=nplane)\n np.fromfile(f, dtype=np.float64,\n count=recl8 - 2 * nplane)\n\n def _generate_nbmax(self):\n \"\"\"\n Helper function that determines maximum number of b vectors for\n each direction.\n\n This algorithm is adapted from WaveTrans (see Class docstring). There\n should be no reason for this function to be called outside of\n initialization.\n \"\"\"\n bmag = np.linalg.norm(self.b, axis=1)\n b = self.b\n\n # calculate maximum integers in each direction for G\n phi12 = np.arccos(np.dot(b[0, :], b[1, :]) / (bmag[0] * bmag[1]))\n sphi123 = np.dot(b[2, :], np.cross(b[0, :], b[1, :])) / \\\n (bmag[2] * np.linalg.norm(np.cross(b[0, :], b[1, :])))\n nbmaxA = np.sqrt(self.encut * self._C) / bmag\n nbmaxA[0] /= np.abs(np.sin(phi12))\n nbmaxA[1] /= np.abs(np.sin(phi12))\n nbmaxA[2] /= np.abs(sphi123)\n nbmaxA += 1\n\n phi13 = np.arccos(np.dot(b[0, :], b[2, :]) / (bmag[0] * bmag[2]))\n sphi123 = np.dot(b[1, :], np.cross(b[0, :], b[2, :])) / \\\n (bmag[1] * np.linalg.norm(np.cross(b[0, :], b[2, :])))\n nbmaxB = np.sqrt(self.encut * self._C) / bmag\n nbmaxB[0] /= np.abs(np.sin(phi13))\n nbmaxB[1] /= np.abs(sphi123)\n nbmaxB[2] /= np.abs(np.sin(phi13))\n nbmaxB += 1\n\n phi23 = np.arccos(np.dot(b[1, :], b[2, :]) / (bmag[1] * bmag[2]))\n sphi123 = np.dot(b[0, :], np.cross(b[1, :], b[2, :])) / \\\n (bmag[0] * np.linalg.norm(np.cross(b[1, :], b[2, :])))\n nbmaxC = np.sqrt(self.encut * self._C) / bmag\n nbmaxC[0] /= np.abs(sphi123)\n nbmaxC[1] /= np.abs(np.sin(phi23))\n nbmaxC[2] /= np.abs(np.sin(phi23))\n nbmaxC += 1\n\n self._nbmax = np.max([nbmaxA, nbmaxB, nbmaxC], axis=0) \\\n .astype(np.int)\n\n def _generate_G_points(self, kpoint):\n \"\"\"\n Helper function to generate G-points based on nbmax.\n\n This function iterates over possible G-point values and determines\n if the energy is less than G_{cut}. Valid values are appended to\n the output array. This function should not be called outside of\n initialization.\n\n Args:\n kpoint (np.array): the array containing the current k-point value\n\n Returns:\n a list containing valid G-points\n \"\"\"\n gpoints = []\n for i in range(2 * self._nbmax[2] + 1):\n i3 = i - 2 * self._nbmax[2] - 1 if i > self._nbmax[2] else i\n for j in range(2 * self._nbmax[1] + 1):\n j2 = j - 2 * self._nbmax[1] - 1 if j > self._nbmax[1] else j\n for k in range(2 * self._nbmax[0] + 1):\n k1 = k - 2 * self._nbmax[0] - 1 if k > self._nbmax[0] else k\n G = np.array([k1, j2, i3])\n v = kpoint + G\n g = np.linalg.norm(np.dot(v, self.b))\n E = g**2 / self._C\n if E < self.encut:\n gpoints.append(G)\n return np.array(gpoints, dtype=np.float64)\n\n def evaluate_wavefunc(self, kpoint, band, r):\n r\"\"\"\n Evaluates the wavefunction for a given position, r.\n\n The wavefunction is given by the k-point and band. It is evaluated\n at the given position by summing over the components. Formally,\n\n \\psi_n^k (r) = \\sum_{i=1}^N c_i^{n,k} \\exp (i (k + G_i^{n,k}) \\cdot r)\n\n where \\psi_n^k is the wavefunction for the nth band at k-point k, N is\n the number of plane waves, c_i^{n,k} is the ith coefficient that\n corresponds to the nth band and k-point k, and G_i^{n,k} is the ith\n G-point corresponding to k-point k.\n\n NOTE: This function is very slow; a discrete fourier transform is the\n preferred method of evaluation (see Wavecar.fft_mesh).\n\n Args:\n kpoint (int): the index of the kpoint where the wavefunction\n will be evaluated\n band (int): the index of the band where the wavefunction will be\n evaluated\n r (np.array): the position where the wavefunction will be evaluated\n Returns:\n a complex value corresponding to the evaluation of the wavefunction\n \"\"\"\n v = self.Gpoints[kpoint] + self.kpoints[kpoint]\n u = np.dot(np.dot(v, self.b), r)\n c = self.coeffs[kpoint][band]\n return np.sum(np.dot(c, np.exp(1j * u, dtype=np.complex64))) / \\\n np.sqrt(self.vol)\n\n def fft_mesh(self, kpoint, band, shift=True):\n \"\"\"\n Places the coefficients of a wavefunction onto an fft mesh.\n\n Once the mesh has been obtained, a discrete fourier transform can be\n used to obtain real-space evaluation of the wavefunction. The output\n of this function can be passed directly to numpy's fft function. For\n example:\n\n mesh = Wavecar().fft_mesh(kpoint, band)\n evals = np.fft.fft(mesh)\n\n Args:\n kpoint (int): the index of the kpoint where the wavefunction\n will be evaluated\n band (int): the index of the band where the wavefunction will be\n evaluated\n shift (bool): determines if the zero frequency coefficient is\n placed at index (0, 0, 0) or centered\n Returns:\n a numpy ndarray representing the 3D mesh of coefficients\n \"\"\"\n mesh = np.zeros(tuple(self.ng), dtype=np.complex)\n for gp, coeff in zip(self.Gpoints[kpoint], self.coeffs[kpoint][band]):\n t = tuple(gp.astype(np.int) + (self.ng / 2).astype(np.int))\n mesh[t] = coeff\n if shift:\n return np.fft.ifftshift(mesh)\n else:\n return mesh\n\n\nclass Wavederf(object):\n \"\"\"\n Object for reading a WAVEDERF file.\n\n Note: This file is only produced when LOPTICS is true AND vasp has been\n recompiled after uncommenting the line that calls\n WRT_CDER_BETWEEN_STATES_FORMATTED in linear_optics.F\n\n Args:\n filename: Name of file containing WAVEDERF.\n\n .. attribute:: data\n\n A numpy array containing the WAVEDERF data of the form below. It should\n be noted that VASP uses 1-based indexing for bands, but this is\n converted to 0-based numpy array indexing.\n\n For each kpoint (in the same order as in IBZKPT), and for each pair of\n bands:\n\n [ #kpoint index\n [ #band 1 index\n [ #band 2 index\n [cdum_x_real, cdum_x_imag, cdum_y_real, cdum_y_imag, cdum_z_real, cdum_z_imag]\n ]\n ]\n ]\n\n This structure follows the file format. Numpy array methods can be used\n to fetch data in a more useful way (e.g., get matrix elements between\n wo specific bands at each kpoint, fetch x/y/z components,\n real/imaginary parts, abs/phase, etc. )\n\n Author: Miguel Dias Costa\n \"\"\"\n\n def __init__(self, filename):\n with zopen(filename, \"rt\") as f:\n header = f.readline().split()\n ispin = int(header[0])\n nb_kpoints = int(header[1])\n nb_bands = int(header[2])\n data = np.zeros((nb_kpoints, nb_bands, nb_bands, 6))\n for ik in range(nb_kpoints):\n for ib1 in range(nb_bands):\n for ib2 in range(nb_bands):\n # each line in the file includes besides the band\n # indexes, which are redundant, each band's energy\n # and occupation, which are already available elsewhere,\n # so we store only the 6 matrix elements after this 6\n # redundant values\n data[ik][ib1][ib2] = [\n float(element)\n for element in f.readline().split()[6:]]\n\n self.data = data\n self._nb_kpoints = nb_kpoints\n self._nb_bands = nb_bands\n\n @property\n def nb_bands(self):\n \"\"\"\n returns the number of bands in the band structure\n \"\"\"\n return self._nb_bands\n\n @property\n def nb_kpoints(self):\n \"\"\"\n Returns the number of k-points in the band structure calculation\n \"\"\"\n return self._nb_kpoints\n\n def get_elements_between_bands(self, band_i, band_j):\n \"\"\"\n Method returning a numpy array with elements\n\n [cdum_x_real, cdum_x_imag, cdum_y_real, cdum_y_imag, cdum_z_real, cdum_z_imag]\n\n between bands band_i and band_j (vasp 1-based indexing) for all kpoints.\n\n Args:\n band_i (Integer): Index of band i\n band_j (Integer): Index of band j\n\n Returns:\n a numpy list of elements for each kpoint\n \"\"\"\n if band_i < 1 or band_i > self.nb_bands or band_j < 1 or band_j > self.nb_bands:\n raise ValueError(\"Band index out of bounds\")\n\n return self.data[:, band_i - 1, band_j - 1, :]\n\n\nclass UnconvergedVASPWarning(Warning):\n \"\"\"\n Warning for unconverged vasp run.\n \"\"\"\n pass\n" ]
[ [ "numpy.dot", "numpy.swapaxes", "numpy.fromfile", "numpy.abs", "numpy.sqrt", "numpy.isnan", "numpy.linalg.norm", "numpy.sin", "numpy.linalg.det", "numpy.max", "numpy.fft.ifftshift", "numpy.cross", "numpy.exp", "numpy.array", "numpy.histogram", "numpy.sum", "numpy.zeros" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
plr21/PENet_ICRA2021
[ "869a10d2f14858faca38f5d50e121769ad142cf1" ]
[ "sparse_to_dense.py" ]
[ "import argparse\nimport typing\nimport logging\nimport torch\n\n# Use GPU only if GPU is available and memory is more than 8GB\nif torch.cuda.is_available() and torch.cuda.get_device_properties(0).total_memory > 8e9:\n import torch.backends.cudnn as cudnn\n\n cudnn.benchmark = True\n device = torch.device(\"cuda\")\nelse:\n device = torch.device(\"cpu\")\nfrom pathlib import Path\n\nfrom os import makedirs\nfrom penet import vis_utils\nfrom penet.s2d_predictor import PENetSparseToDensePredictor, get_model, INPUT_DIMS\n\nLOGGER = logging.getLogger(__file__)\n\ndef _validate_file_path(file_path: Path) -> None:\n assert file_path.is_file(), f\"{file_path} is not a valid file.\"\n\ndef _validate_folder_path(folder_path: Path) -> None:\n assert folder_path.is_dir(), f\"{folder_path} is not a valid directory.\"\n\ndef _validate_img_depth_pair(color_img_path: Path, depth_img_path: Path) ->None:\n assert color_img_path.stem == depth_img_path.stem, (\n f\"Inconsistent image {color_img_path} and depth {depth_img_path}\")\n\ndef _image_depth_content_consistent(color_images: list, depth_images: list) -> bool:\n return len(color_images) == len(depth_images)\n\ndef _get_preprocess_crop_fcn(preprocess_crop_type: str):\n if preprocess_crop_type == \"center\":\n preprocess_crop = vis_utils.centercrop(INPUT_DIMS)\n else:\n preprocess_crop = vis_utils.bottomcrop(INPUT_DIMS)\n return preprocess_crop\n\ndef sparse_to_dense(\n checkpoint_path: Path,\n color_image_path: Path,\n sparse_depth_image_path: Path,\n dense_depth_image_path: typing.Optional[Path],\n network_model: str,\n dilation_rate: int,\n conv_layer_encoding: str,\n preprocess_crop_type: str\n) -> None:\n _validate_file_path(checkpoint_path)\n _validate_file_path(color_image_path)\n _validate_file_path(sparse_depth_image_path)\n\n if dense_depth_image_path is None:\n dense_depth_image_path = (\n sparse_depth_image_path.stem + \"_dense\" + sparse_depth_image_path.suffix\n )\n\n # Preprocess transform\n preprocess_transform = _get_preprocess_crop_fcn(preprocess_crop_type)\n\n penet_model = get_model(\n network_model, dilation_rate, conv_layer_encoding, checkpoint_path\n )\n s2d_predictor = PENetSparseToDensePredictor(penet_model)\n\n rgb = preprocess_transform(vis_utils.rgb_read(str(color_image_path)))\n sparse_depth = preprocess_transform(vis_utils.depth_read(str(sparse_depth_image_path)))\n\n dense_depth_image = s2d_predictor.predict(rgb, sparse_depth)\n\n # Save the depth image to disk\n vis_utils.save_depth_as_uint8colored(dense_depth_image, dense_depth_image_path)\n\ndef sparse_to_dense_dataset(\n checkpoint_path: Path,\n color_images_dir: Path,\n sparse_depths_dir: Path,\n dense_depths_dir: typing.Optional[Path],\n network_model: str,\n dilation_rate: int,\n conv_layer_encoding: str,\n preprocess_crop_type: str,\n) -> None:\n _validate_folder_path(color_images_dir)\n _validate_folder_path(sparse_depths_dir)\n\n if dense_depths_dir is None:\n dense_depths_dir = sparse_depths_dir.parent / \"DenseDepthPEnet\"\n if not dense_depths_dir.is_dir():\n makedirs(dense_depths_dir)\n else:\n _validate_folder_path(dense_depths_dir)\n\n # Preprocess transform\n preprocess_transform = _get_preprocess_crop_fcn(preprocess_crop_type)\n\n # Obtaining images and depths\n supported_img_formats = [\".png\"]\n supported_depth_formats = [\".png\", \".tiff\"]\n for img_format in supported_img_formats:\n img_files = sorted(color_images_dir.glob(\"*\"+img_format))\n if len(img_files) > 0:\n break\n for depth_format in supported_depth_formats:\n depth_files = sorted(sparse_depths_dir.glob(\"*\"+depth_format))\n if len(depth_files) > 0:\n break\n assert len(img_files) == len(depth_files), (\n f\"Number of color images and depth images is different. {len(img_files)}!={len(depth_files)}\")\n\n # Loading PENet\n torch.cuda.empty_cache()\n penet_model = get_model(\n network_model, dilation_rate, conv_layer_encoding, checkpoint_path\n )\n s2d_predictor = PENetSparseToDensePredictor(penet_model)\n\n for img_file, depth_file in zip(img_files, depth_files):\n _validate_img_depth_pair(img_file, depth_file)\n dense_depth_file_f = dense_depths_dir / (img_file.stem+\".tiff\")\n dense_depth_file_i = dense_depths_dir / (img_file.stem+\".png\")\n\n # Evaluate PENET\n rgb = preprocess_transform(vis_utils.rgb_read(str(img_file)))\n sparse_depth = preprocess_transform(vis_utils.depth_read(str(depth_file)))\n dense_depth_image = s2d_predictor.predict(rgb, sparse_depth)\n\n # Save the depth image to disk\n vis_utils.save_depth_as_uint8colored(dense_depth_image, str(dense_depth_file_i))\n vis_utils.save_depth_as_floattiff(dense_depth_image, str(dense_depth_file_f))\n\n print(f\"Instance read: {img_file.stem}\")\n print(f\"\\tImage: {img_file}\")\n print(f\"\\tDepth: {depth_file}\")\n print(f\"Output:\")\n print(f\"\\tDense_f: {dense_depth_file_f}\")\n print(f\"\\tDense_rgb: {dense_depth_file_i}\")\n\ndef _parse_args() -> argparse.Namespace:\n parser = argparse.ArgumentParser(\n description=\"\"\"\n Generate a dense depth map from a color image and a sparse depth map.\n \"\"\",\n formatter_class=argparse.RawDescriptionHelpFormatter,\n )\n\n parser.add_argument(\n \"-rgb\",\n \"--color-image\",\n required=True,\n type=lambda p: Path(p).expanduser().resolve(),\n help=\"Color image file path / Color images directory.\",\n )\n\n parser.add_argument(\n \"-pc\",\n \"--sparse-depth-image\",\n required=True,\n type=lambda p: Path(p).expanduser().resolve(),\n help=\"Sparse depth map file path / Sparse depth images directory.\",\n )\n\n parser.add_argument(\n \"-c\",\n \"--checkpoint\",\n required=True,\n type=lambda p: Path(p).expanduser().resolve(),\n help=\"Path to the pytorch checkpoint file.\",\n )\n\n parser.add_argument(\n \"-o\",\n \"--dense-depth-image\",\n type=lambda p: Path(p).expanduser().resolve(),\n default=None,\n help=\"Output dense depth map file path / Ouput dense depth maps directory.\",\n )\n\n parser.add_argument(\n \"-n\",\n \"--network_model\",\n type=str,\n choices=[\"e\", \"pe\"],\n default=[\"pe\"],\n help=\"Choose between ENet and PENet\",\n )\n\n parser.add_argument(\n \"-dr\",\n \"--dilation-rate\",\n type=int,\n choices=[1, 2, 4],\n default=2,\n help=\"Dilation rate used for depth prediction\",\n )\n\n parser.add_argument(\n \"-co\",\n \"--conv-layer-encoding\",\n default=\"xyz\",\n type=str,\n choices=[\"std\", \"z\", \"uv\", \"xyz\"],\n help=\"information concatenated in encoder convolutional layers\",\n )\n\n parser.add_argument(\n \"-cr\",\n \"--preprocess-crop\",\n default = \"bottom\",\n type=str,\n choices=[\"center\", \"bottom\"],\n help=\"resizing typeto match network size input\"\n )\n\n parser.add_argument(\n \"-sd\",\n \"--sparse-dataset\",\n dest='sparse_dataset',\n action='store_true',\n help = \"Run on sparse-depth dataset\",\n )\n\n parser.add_argument(\n \"-v\",\n \"--verbosity-level\",\n type=int,\n choices=[logging.DEBUG, logging.INFO, logging.WARNING, logging.ERROR],\n default=logging.INFO,\n help=\"\"\"Verbosity level:\n 10 -> Debug\n 20 -> Info\n 30 -> Warning\n 40 -> Error\n \"\"\",\n )\n\n return parser.parse_args()\n\n\nif __name__ == \"__main__\":\n args = _parse_args()\n\n logging.basicConfig(level=args.verbosity_level)\n\n if args.sparse_dataset:\n sparse_to_dense_dataset(\n checkpoint_path = args.checkpoint,\n color_images_dir = args.color_image,\n sparse_depths_dir = args.sparse_depth_image,\n dense_depths_dir = args.dense_depth_image,\n network_model = args.network_model,\n dilation_rate = args.dilation_rate,\n conv_layer_encoding = args.conv_layer_encoding,\n preprocess_crop_type=args.preprocess_crop\n )\n print(\"Finished predictions on dataset\")\n else:\n sparse_to_dense(\n checkpoint_path=args.checkpoint,\n color_image_path=args.color_image,\n sparse_depth_image_path=args.sparse_depth_image,\n dense_depth_image_path=args.dense_depth_image,\n network_model=args.network_model,\n dilation_rate=args.dilation_rate,\n conv_layer_encoding=args.conv_layer_encoding,\n preprocess_crop_type=args.preprocess_crop\n )\n print(\"Finished prediction on image\")\n" ]
[ [ "torch.device", "torch.cuda.get_device_properties", "torch.cuda.empty_cache", "torch.cuda.is_available" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
Baccega/smartphone-based-rti
[ "8f34ad13ccb67ff1442169e31e36050361986496" ]
[ "utils.py" ]
[ "import os\nimport cv2 as cv\nimport numpy as np\nimport math\nfrom constants import constants\n\n\ndef outerContour(contour, gray, margin=10):\n \"\"\"\n Given a contour and an image, returns the mean of the pixels around the contour.\n This is used to detect the rectangle fiducial pattern.\n \"\"\"\n # We create two masks, one with the poly and one with the poly eroded\n kernel = np.ones((margin, margin), np.uint8)\n mask = np.zeros(gray.shape[:2], dtype=np.uint8)\n cv.fillConvexPoly(mask, contour, 255)\n eroded = cv.erode(mask, kernel)\n mask = cv.bitwise_xor(eroded, mask)\n\n # We calculate the mean with the two XORed mask\n mean = cv.mean(gray, mask)\n return mean[0]\n\n\ndef sortCorners(corners):\n \"\"\"\n Sorts an array of corners clockwise\n \"\"\"\n center = np.sum(corners, axis=0) / len(corners)\n\n # Returns the point rotation angle in radians from the center\n def rot(point):\n return math.atan2(point[0][0] - center[0][0], point[0][1] - center[0][1])\n\n sortedCorners = sorted(corners, key=rot, reverse=True)\n return np.roll(sortedCorners, 2, axis=0)\n\n\ndef loadIntrinsics(path=constants[\"CALIBRATION_INTRINSICS_CAMERA_STATIC_PATH\"]):\n \"\"\"\n Loads camera intrinsics from an xml file. Uses a default path if not provided (intrinsics.xml).\n \"\"\"\n intrinsics = cv.FileStorage(path, cv.FILE_STORAGE_READ)\n K = intrinsics.getNode(\"K\").mat()\n dist = intrinsics.getNode(\"dist\").mat()\n return K, dist\n\n\ndef getChoosenCoinVideosPaths(coin, interpolation_mode):\n \"\"\"\n Get constants based on the coin and interpolation mode\n \"\"\"\n mode_str = \"RBF\" if interpolation_mode == 1 else \"PTM\"\n return (\n constants[\"COIN_{}_VIDEO_CAMERA_STATIC_PATH\".format(coin)],\n constants[\"COIN_{}_VIDEO_CAMERA_MOVING_PATH\".format(coin)],\n constants[\"FILE_{}_MOVING_CAMERA_DELAY\".format(coin)],\n constants[\"COIN_{}_ALIGNED_VIDEO_STATIC_PATH\".format(coin)],\n constants[\"COIN_{}_ALIGNED_VIDEO_MOVING_PATH\".format(coin)],\n constants[\"COIN_{}_EXTRACTED_DATA_FILE_PATH\".format(coin)],\n constants[\"COIN_{}_INTERPOLATED_DATA_{}_FILE_PATH\".format(coin, mode_str)],\n )\n\n\ndef findPixelIntensities(static_frame):\n \"\"\"\n Get pixel intensities from static_frame frame using an ad-hoc roi\n \"\"\"\n roi = static_frame[\n 720 : 720 + 460,\n 320 : 320 + 460,\n ]\n roi_full_size = cv.cvtColor(roi, cv.COLOR_BGR2HSV)\n\n roi = cv.resize(\n roi_full_size,\n (constants[\"SQAURE_GRID_DIMENSION\"], constants[\"SQAURE_GRID_DIMENSION\"]),\n )\n\n return roi[:, :, 2]\n\n\ndef findLightDirection(static_frame, moving_frame, static_corners, moving_corners):\n \"\"\"\n Get light direction from static_frame and moving frame\n \"\"\"\n moving_frame = cv.cvtColor(moving_frame, cv.COLOR_BGR2GRAY)\n image_size = moving_frame.shape[::-1]\n\n M, D = getCameraIntrinsics(constants[\"CALIBRATION_INTRINSICS_CAMERA_MOVING_PATH\"])\n z_axis = 1\n flags = cv.CALIB_USE_INTRINSIC_GUESS\n\n points_3d = np.float32(\n [\n (static_corners[point][0][0], static_corners[point][0][1], z_axis)\n for point in range(0, len(static_corners))\n ]\n )\n points_2d = np.float32(\n [\n (moving_corners[point][0][0], moving_corners[point][0][1])\n for point in range(0, len(moving_corners))\n ]\n )\n\n # perform a camera calibration to get R and T\n (_, _, _, r_vectors, t_vectors) = cv.calibrateCamera(\n [points_3d], [points_2d], image_size, cameraMatrix=M, distCoeffs=D, flags=flags\n )\n R = cv.Rodrigues(r_vectors[0])[0]\n T = t_vectors[0]\n\n pose = -np.matrix(R).T * np.matrix(T)\n pose = np.array(pose).flatten()\n\n h2, w2 = int(static_frame.shape[0] / 2), int(static_frame.shape[1] / 2)\n p = (h2, w2, 0)\n l = (pose - p) / np.linalg.norm(pose - p)\n\n # -1 ≤ l[0] ≤ +1\n # -1 ≤ l[1] ≤ +1\n return l\n\n\ndef getCameraIntrinsics(calibration_file_path):\n \"\"\"\n Get camera intrinsic matrix and distorsion\n \"\"\"\n Kfile = cv.FileStorage(calibration_file_path, cv.FILE_STORAGE_READ)\n intrinsics_matrix = Kfile.getNode(\"K\").mat()\n distortion_matrix = Kfile.getNode(\"distortion\").mat()\n\n return intrinsics_matrix, distortion_matrix\n\n\ndef createLightDirectionFrame(light_direction):\n \"\"\"\n Create a frame to show light direction to user\n \"\"\"\n blank_image = np.zeros(\n shape=[\n constants[\"LIGHT_DIRECTION_WINDOW_SIZE\"],\n constants[\"LIGHT_DIRECTION_WINDOW_SIZE\"],\n 3,\n ],\n dtype=np.uint8,\n )\n\n half_size = int(constants[\"LIGHT_DIRECTION_WINDOW_SIZE\"] / 2)\n\n cv.line(\n blank_image,\n (half_size, half_size),\n (light_direction[0], light_direction[1]),\n (255, 255, 255),\n )\n cv.circle(\n blank_image,\n (half_size, half_size),\n half_size,\n (255, 255, 255),\n )\n return blank_image\n\n\ndef boundXY(x, y):\n \"\"\"\n Force X and Y to be within the light directions bounds\n \"\"\"\n half_size = int(constants[\"LIGHT_DIRECTION_WINDOW_SIZE\"] / 2)\n if (x - half_size) * (x - half_size) + (y - half_size) * (y - half_size) <= (\n half_size * half_size\n ):\n return (x, y)\n else:\n print(\"OUTSIDE!\")\n return (half_size, half_size)\n\n\ndef fromLightDirToIndex(lightDir):\n \"\"\"\n Transform light direction [-1.0, ..., +1.0] to positive indexes (0, ..., 200)\n \"\"\"\n return int(np.around(lightDir, decimals=2) * 100) + 100\n\n\ndef writeDataFile(extracted_data_file_path, extracted_data):\n \"\"\"\n Write data file to os\n \"\"\"\n print(\"Saving extracted data into '{}'...\".format(extracted_data_file_path))\n np.savez_compressed(extracted_data_file_path, extracted_data)\n print(\"Saved!\")\n\n\ndef loadDataFile(extracted_data_file_path):\n \"\"\"\n Load data file from os\n \"\"\"\n print(\"Loading extracted data file '{}'...\".format(extracted_data_file_path))\n loaded_data = np.load(extracted_data_file_path, allow_pickle=True)[\"arr_0\"]\n print(\"Loaded!\")\n return loaded_data\n" ]
[ [ "numpy.matrix", "numpy.around", "numpy.linalg.norm", "numpy.ones", "numpy.savez_compressed", "numpy.load", "numpy.roll", "numpy.array", "numpy.zeros", "numpy.sum" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
paulf81/FLORIS
[ "f1bfee1f22834109e1f3478cdf2b468e19dc584f", "ef4934ec7feb7afd2615772d364a1eaa28db93e9" ]
[ "examples/optimization/scipy/co-design_optimizations/optimize_power_density.py", "examples/_getting_started/example_00_open_and_vis_floris.py" ]
[ "# Copyright 2021 NREL\n\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may not\n# use this file except in compliance with the License. You may obtain a copy of\n# the License at http://www.apache.org/licenses/LICENSE-2.0\n\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations under\n# the License.\n\n# See https://floris.readthedocs.io for documentation\n\n\n# This example optimization takes a 2x2 array of turbines and works to reduce\n# the wind farm footprint area (measured as a convex hull), while working to\n# maintain the original energy output by leveraging wake steering. It is meant\n# to be an illustrative example of some of the benefits of wake steering.\n\nimport os\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nimport floris.tools as wfct\nimport floris.tools.visualization as vis\nfrom floris.tools.optimization.scipy.power_density import PowerDensityOptimization\n\n\n# Instantiate the FLORIS object\nfile_dir = os.path.dirname(os.path.abspath(__file__))\nfi = wfct.floris_interface.FlorisInterface(\n os.path.join(file_dir, \"../../../example_input.json\")\n)\n\n# Set turbine locations to 3 turbines in a triangle\nD = fi.floris.farm.turbines[0].rotor_diameter\nlayout_x = [10, 10, 10 + 7 * D, 10 + 7 * D]\nlayout_y = [200, 1000, 200, 1000]\nfi.reinitialize_flow_field(layout_array=(layout_x, layout_y))\n\n# Define the boundary for the wind farm\nboundaries = [[1000.0, 1200.0], [1000.0, 0.1], [0.0, 0.0], [0.0, 1200.0]]\n\n# Generate random wind rose data\nwd = np.arange(0.0, 360.0, 45.0)\nnp.random.seed(1)\nws = 8.0 + np.random.randn(len(wd)) * 0.5\nfreq = np.abs(np.sort(np.random.randn(len(wd))))\nfreq = freq / freq.sum()\n\n# Set optimization options\nopt_options = {\"maxiter\": 10, \"disp\": True, \"iprint\": 2, \"ftol\": 1e-9}\n\n# Compute initial AEP for optimization normalization\nAEP_initial = fi.get_farm_AEP(wd, ws, freq)\n\n# Instantiate the layout otpimization object\npowdens_opt = PowerDensityOptimization(\n fi=fi,\n boundaries=boundaries,\n wd=wd,\n ws=ws,\n freq=freq,\n AEP_initial=AEP_initial,\n opt_options=opt_options,\n)\n\n# Perform layout optimization\npowdens_results = powdens_opt.optimize()\n\nprint(\"=====================================================\")\nprint(\n \"Area relative to baseline: = %.1f%%\"\n % (\n 100\n * (\n powdens_opt.find_layout_area(powdens_results[0] + powdens_results[1])\n / powdens_opt.initial_area\n )\n )\n)\n\nprint(\"=====================================================\")\nprint(\"Layout coordinates: \")\nfor i in range(len(powdens_results[0])):\n print(\n \"Turbine\",\n i,\n \": \\tx = \",\n \"{:.1f}\".format(powdens_results[0][i]),\n \"\\ty = \",\n \"{:.1f}\".format(powdens_results[1][i]),\n )\n\n# Calculate new AEP results\nfi.reinitialize_flow_field(layout_array=(powdens_results[0], powdens_results[1]))\nAEP_optimized = fi.get_farm_AEP(wd, ws, freq)\n\nprint(\"=====================================================\")\nprint(\"AEP Ratio = %.1f%%\" % (100.0 * (AEP_optimized / AEP_initial)))\nprint(\"=====================================================\")\n\n# Plot the new layout vs the old layout\npowdens_opt.plot_opt_results()\nplt.show()\n", "# Copyright 2021 NREL\n\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may not\n# use this file except in compliance with the License. You may obtain a copy of\n# the License at http://www.apache.org/licenses/LICENSE-2.0\n\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations under\n# the License.\n\n# See https://floris.readthedocs.io for documentation\n\n\nimport matplotlib.pyplot as plt\n\nimport floris.tools as wfct\n\n\n# Initialize the FLORIS interface fi\n# For basic usage, the florice interface provides a simplified interface to\n# the underlying classes\nfi = wfct.floris_interface.FlorisInterface(\"../example_input.json\")\n\n# Calculate wake\nfi.calculate_wake()\n\n# Get horizontal plane at default height (hub-height)\nhor_plane = fi.get_hor_plane()\n\n# Plot and show\nfig, ax = plt.subplots()\nwfct.visualization.visualize_cut_plane(hor_plane, ax=ax)\nplt.show()\n" ]
[ [ "numpy.arange", "matplotlib.pyplot.show", "numpy.random.seed" ], [ "matplotlib.pyplot.show", "matplotlib.pyplot.subplots" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
lvzhaoyang/liegroups
[ "b3ccad280a3b615ad33c5f15c35d9325b8d3a5be", "b3ccad280a3b615ad33c5f15c35d9325b8d3a5be" ]
[ "liegroups/torch/so2.py", "liegroups/torch/se3.py" ]
[ "import torch\n\nfrom liegroups.torch import _base\nfrom liegroups.torch import utils\n\n\nclass SO2(_base.SpecialOrthogonalBase):\n \"\"\"See :mod:`liegroups.SO2`\"\"\"\n dim = 2\n dof = 1\n\n def adjoint(self):\n if self.mat.dim() < 3:\n return self.mat.__class__([1.])\n else:\n return self.mat.__class__(self.mat.shape[0]).fill_(1.)\n\n @classmethod\n def exp(cls, phi):\n s = phi.sin()\n c = phi.cos()\n\n mat = phi.__class__(phi.shape[0], cls.dim, cls.dim)\n mat[:, 0, 0] = c\n mat[:, 0, 1] = -s\n mat[:, 1, 0] = s\n mat[:, 1, 1] = c\n\n return cls(mat.squeeze_())\n\n @classmethod\n def from_angle(cls, angle_in_radians):\n \"\"\"Form a rotation matrix given an angle in rad.\"\"\"\n return cls.exp(angle_in_radians)\n\n @classmethod\n def inv_left_jacobian(cls, phi):\n \"\"\"(see Barfoot/Eade).\"\"\"\n jac = phi.__class__(phi.shape[0], cls.dim, cls.dim)\n\n # Near phi==0, use first order Taylor expansion\n small_angle_mask = utils.isclose(phi, 0.)\n small_angle_inds = small_angle_mask.nonzero().squeeze_(dim=1)\n\n if len(small_angle_inds) > 0:\n jac[small_angle_inds] = torch.eye(cls.dim).expand(\n len(small_angle_inds), cls.dim, cls.dim) \\\n - 0.5 * cls.wedge(phi[small_angle_inds])\n\n # Otherwise...\n large_angle_mask = 1 - small_angle_mask # element-wise not\n large_angle_inds = large_angle_mask.nonzero().squeeze_(dim=1)\n\n if len(large_angle_inds) > 0:\n angle = phi[large_angle_inds]\n ha = 0.5 * angle # half angle\n hacha = ha / ha.tan() # half angle * cot(half angle)\n\n ha.unsqueeze_(dim=1).unsqueeze_(\n dim=2).expand_as(jac[large_angle_inds])\n hacha.unsqueeze_(dim=1).unsqueeze_(\n dim=2).expand_as(jac[large_angle_inds])\n\n A = hacha * \\\n torch.eye(cls.dim).unsqueeze_(\n dim=0).expand_as(jac[large_angle_inds])\n B = -ha * cls.wedge(phi.__class__([1.]))\n\n jac[large_angle_inds] = A + B\n\n return jac.squeeze_()\n\n @classmethod\n def left_jacobian(cls, phi):\n \"\"\"(see Barfoot/Eade).\"\"\"\n jac = phi.__class__(phi.shape[0], cls.dim, cls.dim)\n\n # Near phi==0, use first order Taylor expansion\n small_angle_mask = utils.isclose(phi, 0.)\n small_angle_inds = small_angle_mask.nonzero().squeeze_(dim=1)\n\n if len(small_angle_inds) > 0:\n jac[small_angle_inds] = torch.eye(cls.dim).expand(\n len(small_angle_inds), cls.dim, cls.dim) \\\n + 0.5 * cls.wedge(phi[small_angle_inds])\n\n # Otherwise...\n large_angle_mask = 1 - small_angle_mask # element-wise not\n large_angle_inds = large_angle_mask.nonzero().squeeze_(dim=1)\n\n if len(large_angle_inds) > 0:\n angle = phi[large_angle_inds]\n s = angle.sin()\n c = angle.cos()\n\n A = (s / angle).unsqueeze_(dim=1).unsqueeze_(\n dim=2).expand_as(jac[large_angle_inds]) * \\\n torch.eye(cls.dim).unsqueeze_(dim=0).expand_as(\n jac[large_angle_inds])\n B = ((1. - c) / angle).unsqueeze_(dim=1).unsqueeze_(\n dim=2).expand_as(jac[large_angle_inds]) * \\\n cls.wedge(phi.__class__([1.]))\n\n jac[large_angle_inds] = A + B\n\n return jac.squeeze_()\n\n def log(self):\n if self.mat.dim() < 3:\n mat = self.mat.unsqueeze(dim=0)\n else:\n mat = self.mat\n\n s = mat[:, 1, 0]\n c = mat[:, 0, 0]\n\n return torch.atan2(s, c).squeeze_()\n\n def to_angle(self):\n \"\"\"Recover the rotation angle in rad from the rotation matrix.\"\"\"\n return self.log()\n\n @classmethod\n def vee(cls, Phi):\n if Phi.dim() < 3:\n Phi = Phi.unsqueeze(dim=0)\n\n if Phi.shape[1:3] != (cls.dim, cls.dim):\n raise ValueError(\n \"Phi must have shape ({},{}) or (N,{},{})\".format(cls.dim, cls.dim, cls.dim, cls.dim))\n\n return Phi[:, 1, 0].squeeze_()\n\n @classmethod\n def wedge(cls, phi):\n if phi.dim() < 2:\n phi = phi.unsqueeze(dim=1) # vector --> matrix (N --> Nx1)\n\n if phi.shape[1] != cls.dof:\n raise ValueError(\n \"phi must have shape ({},) or (N,{})\".format(cls.dof, cls.dof))\n\n Phi = phi.new_zeros(phi.shape[0], cls.dim, cls.dim)\n Phi[:, 0, 1] = -phi\n Phi[:, 1, 0] = phi\n return Phi\n", "import torch\n\nfrom liegroups.torch import _base\nfrom liegroups.torch import utils\nfrom liegroups.torch.so3 import SO3\n\n\nclass SE3(_base.SpecialEuclideanBase):\n \"\"\"See :mod:`liegroups.SE3` \"\"\"\n dim = 4\n dof = 6\n RotationType = SO3\n\n def adjoint(self):\n rot = self.rot.as_matrix()\n if rot.dim() < 3:\n rot = rot.unsqueeze(dim=0) # matrix --> batch\n\n trans = self.trans\n if trans.dim() < 2:\n # vector --> vectorbatch\n trans = trans.unsqueeze(dim=0)\n\n trans_wedge = self.RotationType.wedge(trans)\n if trans_wedge.dim() < 3:\n trans_wedge.unsqueeze_(dim=0) # matrix --> batch\n\n trans_wedge_bmm_rot = torch.bmm(trans_wedge, rot)\n\n zero_block = trans.new_empty(rot.shape).zero_()\n\n return torch.cat([torch.cat([rot, trans_wedge_bmm_rot], dim=2),\n torch.cat([zero_block, rot], dim=2)], dim=1\n ).squeeze_()\n\n @classmethod\n def curlyvee(cls, Psi):\n if Psi.dim() < 3:\n Psi = Psi.unsqueeze(dim=0)\n\n if Psi.shape[1:] != (cls.dof, cls.dof):\n raise ValueError(\"Psi must have shape ({},{}) or (N,{},{})\".format(\n cls.dof, cls.dof, cls.dof, cls.dof))\n\n xi = Psi.new_empty(Psi.shape[0], cls.dof)\n xi[:, :3] = cls.RotationType.vee(Psi[:, :3, 3:])\n xi[:, 3:] = cls.RotationType.vee(Psi[:, :3, :3])\n\n return xi.squeeze_()\n\n @classmethod\n def curlywedge(cls, xi):\n if xi.dim() < 2:\n xi = xi.unsqueeze(dim=0)\n\n if xi.shape[1] != cls.dof:\n raise ValueError(\n \"phi must have shape ({},) or (N,{})\".format(cls.dof, cls.dof))\n\n Psi = xi.new_empty(xi.shape[0], cls.dof, cls.dof).zero_()\n Psi[:, :3, :3] = cls.RotationType.wedge(xi[:, 3:])\n Psi[:, :3, 3:] = cls.RotationType.wedge(xi[:, :3])\n Psi[:, 3:, 3:] = Psi[:, :3, :3]\n\n return Psi.squeeze_()\n\n @classmethod\n def exp(cls, xi):\n if xi.dim() < 2:\n xi = xi.unsqueeze(dim=0)\n\n if xi.shape[1] != cls.dof:\n raise ValueError(\n \"xi must have shape ({},) or (N,{})\".format(cls.dof, cls.dof))\n\n rho = xi[:, :3]\n phi = xi[:, 3:]\n\n rot = cls.RotationType.exp(phi)\n rot_jac = cls.RotationType.left_jacobian(phi)\n\n if rot_jac.dim() < 3:\n rot_jac.unsqueeze_(dim=0)\n if rho.dim() < 3:\n rho.unsqueeze_(dim=2)\n\n trans = torch.bmm(rot_jac, rho).squeeze_()\n\n return cls(rot, trans)\n\n @classmethod\n def left_jacobian_Q_matrix(cls, xi):\n if xi.dim() < 2:\n xi = xi.unsqueeze(dim=0)\n\n if xi.shape[1] != cls.dof:\n raise ValueError(\n \"xi must have shape ({},) or (N,{})\".format(cls.dof, cls.dof))\n\n rho = xi[:, :3] # translation part\n phi = xi[:, 3:] # rotation part\n\n rx = SO3.wedge(rho)\n if rx.dim() < 3:\n rx.unsqueeze_(dim=0)\n\n px = SO3.wedge(phi)\n if px.dim() < 3:\n px.unsqueeze_(dim=0)\n\n ph = phi.norm(p=2, dim=1)\n ph2 = ph * ph\n ph3 = ph2 * ph\n ph4 = ph3 * ph\n ph5 = ph4 * ph\n\n cph = ph.cos()\n sph = ph.sin()\n\n m1 = 0.5\n m2 = (ph - sph) / ph3\n m3 = (0.5 * ph2 + cph - 1.) / ph4\n m4 = (ph - 1.5 * sph + 0.5 * ph * cph) / ph5\n\n m2 = m2.unsqueeze_(dim=1).unsqueeze_(dim=2).expand_as(rx)\n m3 = m3.unsqueeze_(dim=1).unsqueeze_(dim=2).expand_as(rx)\n m4 = m4.unsqueeze_(dim=1).unsqueeze_(dim=2).expand_as(rx)\n\n t1 = rx\n t2 = px.bmm(rx) + rx.bmm(px) + px.bmm(rx).bmm(px)\n t3 = px.bmm(px).bmm(rx) + rx.bmm(px).bmm(px) - 3. * px.bmm(rx).bmm(px)\n t4 = px.bmm(rx).bmm(px).bmm(px) + px.bmm(px).bmm(rx).bmm(px)\n\n Q = m1 * t1 + m2 * t2 + m3 * t3 + m4 * t4\n\n return Q.squeeze_()\n\n @classmethod\n def inv_left_jacobian(cls, xi):\n if xi.dim() < 2:\n xi = xi.unsqueeze(dim=0)\n\n if xi.shape[1] != cls.dof:\n raise ValueError(\n \"xi must have shape ({},) or (N,{})\".format(cls.dof, cls.dof))\n\n rho = xi[:, :3] # translation part\n phi = xi[:, 3:] # rotation part\n\n jac = phi.new_empty(phi.shape[0], cls.dof, cls.dof)\n angle = phi.norm(p=2, dim=1)\n\n # Near phi==0, use first order Taylor expansion\n small_angle_mask = utils.isclose(angle, 0.)\n small_angle_inds = small_angle_mask.nonzero().squeeze_(dim=1)\n if len(small_angle_inds) > 0:\n \n #Create an identity matrix with a tensor type that matches the input\n I = phi.new_empty(cls.dof, cls.dof)\n torch.eye(cls.dof, out=I)\n\n jac[small_angle_inds] = \\\n I.expand_as(jac[small_angle_inds]) - \\\n 0.5 * cls.curlywedge(xi[small_angle_inds])\n\n # Otherwise...\n large_angle_mask = 1 - small_angle_mask # element-wise not\n large_angle_inds = large_angle_mask.nonzero().squeeze_(dim=1)\n\n if len(large_angle_inds) > 0:\n so3_inv_jac = SO3.inv_left_jacobian(phi[large_angle_inds])\n if so3_inv_jac.dim() < 3:\n so3_inv_jac.unsqueeze_(dim=0)\n\n Q_mat = cls.left_jacobian_Q_matrix(xi[large_angle_inds])\n if Q_mat.dim() < 3:\n Q_mat.unsqueeze_(dim=0)\n\n zero_block = phi.new_empty(Q_mat.shape).zero_()\n inv_jac_Q_inv_jac = so3_inv_jac.bmm(Q_mat).bmm(so3_inv_jac)\n\n jac[large_angle_inds] = torch.cat(\n [torch.cat([so3_inv_jac, -inv_jac_Q_inv_jac], dim=2),\n torch.cat([zero_block, so3_inv_jac], dim=2)], dim=1)\n\n return jac.squeeze_()\n\n @classmethod\n def left_jacobian(cls, xi):\n if xi.dim() < 2:\n xi = xi.unsqueeze(dim=0)\n\n if xi.shape[1] != cls.dof:\n raise ValueError(\n \"xi must have shape ({},) or (N,{})\".format(cls.dof, cls.dof))\n\n rho = xi[:, :3] # translation part\n phi = xi[:, 3:] # rotation part\n\n jac = phi.new_empty(phi.shape[0], cls.dof, cls.dof)\n angle = phi.norm(p=2, dim=1)\n\n # Near phi==0, use first order Taylor expansion\n small_angle_mask = utils.isclose(angle, 0.)\n small_angle_inds = small_angle_mask.nonzero().squeeze_(dim=1)\n if len(small_angle_inds) > 0:\n #Create an identity matrix with a tensor type that matches the input\n I = phi.new_empty(cls.dof, cls.dof)\n torch.eye(cls.dof, out=I)\n\n jac[small_angle_inds] = \\\n I.expand_as(jac[small_angle_inds]) + \\\n 0.5 * cls.curlywedge(xi[small_angle_inds])\n\n # Otherwise...\n large_angle_mask = 1 - small_angle_mask # element-wise not\n large_angle_inds = large_angle_mask.nonzero().squeeze_(dim=1)\n\n if len(large_angle_inds) > 0:\n so3_jac = SO3.left_jacobian(phi[large_angle_inds])\n if so3_jac.dim() < 3:\n so3_jac.unsqueeze_(dim=0)\n\n Q_mat = cls.left_jacobian_Q_matrix(xi[large_angle_inds])\n if Q_mat.dim() < 3:\n Q_mat.unsqueeze_(dim=0)\n\n zero_block = phi.new_empty(Q_mat.shape).zero_()\n\n jac[large_angle_inds] = torch.cat(\n [torch.cat([so3_jac, Q_mat], dim=2),\n torch.cat([zero_block, so3_jac], dim=2)], dim=1)\n\n return jac.squeeze_()\n\n def log(self):\n phi = self.rot.log()\n inv_rot_jac = self.RotationType.inv_left_jacobian(phi)\n\n if self.trans.dim() < 2:\n trans = self.trans.unsqueeze(dim=0)\n else:\n trans = self.trans\n\n if inv_rot_jac.dim() < 3:\n inv_rot_jac.unsqueeze_(dim=0)\n if trans.dim() < 3:\n trans = trans.unsqueeze(dim=2)\n\n rho = torch.bmm(inv_rot_jac, trans).squeeze_()\n if rho.dim() < 2:\n rho.unsqueeze_(dim=0)\n if phi.dim() < 2:\n phi.unsqueeze_(dim=0)\n\n return torch.cat([rho, phi], dim=1).squeeze_()\n\n @classmethod\n def odot(cls, p, directional=False):\n if p.dim() < 2:\n p = p.unsqueeze(dim=0) # vector --> vectorbatch\n\n result = p.new_empty(p.shape[0], p.shape[1], cls.dof).zero_()\n\n # Got euclidean coordinates\n if p.shape[1] == cls.dim - 1:\n # Assume scale parameter is 1 unless p is a direction\n # vector, in which case the scale is 0\n if not directional:\n result[:, :3, :3] = torch.eye(3, dtype=p.dtype).unsqueeze_(dim=0).expand(\n p.shape[0], 3, 3)\n\n result[:, :3, 3:] = cls.RotationType.wedge(-p)\n\n # Got homogeneous coordinates\n elif p.shape[1] == cls.dim:\n result[:, :3, :3] = \\\n p[:, 3].unsqueeze_(dim=1).unsqueeze_(dim=2) * \\\n torch.eye(3, dtype=p.dtype).unsqueeze_(dim=0).repeat(\n p.shape[0], 1, 1)\n\n result[:, :3, 3:] = cls.RotationType.wedge(-p[:, :3])\n\n # Got wrong dimension\n else:\n raise ValueError(\"p must have shape ({},), ({},), (N,{}) or (N,{})\".format(\n cls.dim - 1, cls.dim, cls.dim - 1, cls.dim))\n\n return result.squeeze_()\n\n @classmethod\n def vee(cls, Xi):\n if Xi.dim() < 3:\n Xi = Xi.unsqueeze(dim=0)\n\n if Xi.shape[1:3] != (cls.dim, cls.dim):\n raise ValueError(\"Xi must have shape ({},{}) or (N,{},{})\".format(\n cls.dim, cls.dim, cls.dim, cls.dim))\n\n xi = Xi.new_empty(Xi.shape[0], cls.dof)\n xi[:, :3] = Xi[:, :3, 3]\n xi[:, 3:] = cls.RotationType.vee(Xi[:, :3, :3])\n\n return xi.squeeze_()\n\n @classmethod\n def wedge(cls, xi):\n if xi.dim() < 2:\n xi = xi.unsqueeze(dim=0)\n\n if xi.shape[1] != cls.dof:\n raise ValueError(\n \"phi must have shape ({},) or (N,{})\".format(cls.dof, cls.dof))\n\n Xi = xi.new_empty(xi.shape[0], cls.dim, cls.dim).zero_()\n Xi[:, :3, :3] = cls.RotationType.wedge(xi[:, 3:])\n Xi[:, :3, 3] = xi[:, :3]\n\n return Xi.squeeze_()\n" ]
[ [ "torch.eye", "torch.atan2" ], [ "torch.eye", "torch.bmm", "torch.cat" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
zhoubenjia/RAAR3DNet
[ "b5f6486a9f1cbf9fdd2de6a141ad81354f39ee51", "b5f6486a9f1cbf9fdd2de6a141ad81354f39ee51" ]
[ "Network_Search/lib/model/model_search.py", "Network_Train/lib/datasets/DSADataset.py" ]
[ "\"\"\"RAAR3DNet architecture.\n The model is introduced in:\n Regional Attention with Architecture-Rebuilt 3D Network for RGB-D Gesture Recognition\n Benjia Zhou, Yunan Li, Jun Wan\n https://arxiv.org/pdf/2102.05348.pdf\n \"\"\"\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch.autograd import Variable\n\nimport numpy as np\n\nimport os\nimport sys\nfrom collections import OrderedDict\nimport pdb\nfrom .Operations import *\nfrom .Genotypes import PRIMITIVES_INCEPTION\nfrom .Genotypes import Genotype\n\nPRIMITIVES = PRIMITIVES_INCEPTION\n\n\n\nclass MaxPool3dSamePadding(nn.MaxPool3d):\n\n def compute_pad(self, dim, s):\n if s % self.stride[dim] == 0:\n return max(self.kernel_size[dim] - self.stride[dim], 0)\n else:\n return max(self.kernel_size[dim] - (s % self.stride[dim]), 0)\n\n def forward(self, x):\n # compute 'same' padding\n (batch, channel, t, h, w) = x.size()\n # print t,h,w\n out_t = np.ceil(float(t) / float(self.stride[0]))\n out_h = np.ceil(float(h) / float(self.stride[1]))\n out_w = np.ceil(float(w) / float(self.stride[2]))\n # print out_t, out_h, out_w\n pad_t = self.compute_pad(0, t)\n pad_h = self.compute_pad(1, h)\n pad_w = self.compute_pad(2, w)\n # print pad_t, pad_h, pad_w\n\n pad_t_f = pad_t // 2\n pad_t_b = pad_t - pad_t_f\n pad_h_f = pad_h // 2\n pad_h_b = pad_h - pad_h_f\n pad_w_f = pad_w // 2\n pad_w_b = pad_w - pad_w_f\n\n pad = (pad_w_f, pad_w_b, pad_h_f, pad_h_b, pad_t_f, pad_t_b)\n # print x.size()\n # print pad\n x = F.pad(x, pad)\n return super(MaxPool3dSamePadding, self).forward(x)\n\n\nclass Unit3D(nn.Module):\n\n def __init__(self, in_channels,\n output_channels,\n kernel_shape=(1, 1, 1),\n stride=(1, 1, 1),\n padding=0,\n activation_fn=F.relu,\n use_batch_norm=True,\n use_bias=False,\n name='unit_3d'):\n\n \"\"\"Initializes Unit3D module.\"\"\"\n super(Unit3D, self).__init__()\n\n self._output_channels = output_channels\n self._kernel_shape = kernel_shape\n self._stride = stride\n self._use_batch_norm = use_batch_norm\n self._activation_fn = activation_fn\n self._use_bias = use_bias\n self.name = name\n self.padding = padding\n\n self.conv3d = nn.Conv3d(in_channels=in_channels,\n out_channels=self._output_channels,\n kernel_size=self._kernel_shape,\n stride=self._stride,\n padding=0,\n # we always want padding to be 0 here. We will dynamically pad based on input size in forward function\n bias=self._use_bias)\n\n if self._use_batch_norm:\n self.bn = nn.BatchNorm3d(self._output_channels, eps=0.001, momentum=0.01)\n\n def compute_pad(self, dim, s):\n if s % self._stride[dim] == 0:\n return max(self._kernel_shape[dim] - self._stride[dim], 0)\n else:\n return max(self._kernel_shape[dim] - (s % self._stride[dim]), 0)\n\n def forward(self, x):\n # compute 'same' padding\n (batch, channel, t, h, w) = x.size()\n # print t,h,w\n out_t = np.ceil(float(t) / float(self._stride[0]))\n out_h = np.ceil(float(h) / float(self._stride[1]))\n out_w = np.ceil(float(w) / float(self._stride[2]))\n # print out_t, out_h, out_w\n pad_t = self.compute_pad(0, t)\n pad_h = self.compute_pad(1, h)\n pad_w = self.compute_pad(2, w)\n # print pad_t, pad_h, pad_w\n\n pad_t_f = pad_t // 2\n pad_t_b = pad_t - pad_t_f\n pad_h_f = pad_h // 2\n pad_h_b = pad_h - pad_h_f\n pad_w_f = pad_w // 2\n pad_w_b = pad_w - pad_w_f\n\n pad = (pad_w_f, pad_w_b, pad_h_f, pad_h_b, pad_t_f, pad_t_b)\n # print x.size()\n # print pad\n x = F.pad(x, pad)\n # print x.size()\n\n x = self.conv3d(x)\n if self._use_batch_norm:\n x = self.bn(x)\n if self._activation_fn is not None:\n x = self._activation_fn(x)\n return x\n\n\nclass InceptionModule(nn.Module):\n def __init__(self, in_channels, out_channels, name):\n super(InceptionModule, self).__init__()\n\n self.b0 = Unit3D(in_channels=in_channels, output_channels=out_channels[0], kernel_shape=[1, 1, 1], padding=0,\n name=name + '/Branch_0/Conv3d_0a_1x1')\n self.b1a = Unit3D(in_channels=in_channels, output_channels=out_channels[1], kernel_shape=[1, 1, 1], padding=0,\n name=name + '/Branch_1/Conv3d_0a_1x1')\n self.b1b = Unit3D(in_channels=out_channels[1], output_channels=out_channels[2], kernel_shape=[3, 3, 3],\n name=name + '/Branch_1/Conv3d_0b_3x3')\n self.b2a = Unit3D(in_channels=in_channels, output_channels=out_channels[3], kernel_shape=[1, 1, 1], padding=0,\n name=name + '/Branch_2/Conv3d_0a_1x1')\n self.b2b = Unit3D(in_channels=out_channels[3], output_channels=out_channels[4], kernel_shape=[3, 3, 3],\n name=name + '/Branch_2/Conv3d_0b_3x3')\n self.b3a = MaxPool3dSamePadding(kernel_size=[3, 3, 3],\n stride=(1, 1, 1), padding=0)\n self.b3b = Unit3D(in_channels=in_channels, output_channels=out_channels[5], kernel_shape=[1, 1, 1], padding=0,\n name=name + '/Branch_3/Conv3d_0b_1x1')\n self.name = name\n\n def forward(self, x):\n b0 = self.b0(x)\n b1 = self.b1b(self.b1a(x))\n b2 = self.b2b(self.b2a(x))\n b3 = self.b3b(self.b3a(x))\n return torch.cat([b0, b1, b2, b3], dim=1)\n\n\ndef channel_shuffle(x, groups):\n batchsize, num_channels, length, height, width = x.data.size()\n channels_per_group = num_channels // groups\n # reshape\n # ([2, 32, 4, 28, 28])--> ([2, 4, 8, 4, 28, 28])\n x = x.view(batchsize, groups, channels_per_group, length, height, width)\n # -->([2, 8, 4, 4, 28, 28])\n x = torch.transpose(x, 1, 2).contiguous() # not change x dim\n # flatten\n x = x.view(batchsize, -1, length, height, width)\n return x\nclass MixedOp(nn.Module):\n\n def __init__(self, C, stride):\n super(MixedOp, self).__init__()\n self._ops = nn.ModuleList()\n self._k = 2\n for primitive in PRIMITIVES:\n op = OPS[primitive](C // self._k, stride, False)\n self._ops.append(op)\n\n def forward(self, x, weights):\n # channel proportion k=4\n dim_2 = x.shape[1]\n xtemp = x[:, : dim_2 // self._k, :, :].cuda() # [2, 8, 4, 28, 28]\n xtemp2 = x[:, dim_2 // self._k:, :, :].cuda() # [2, 24, 4, 28, 28]\n temp1 = sum(w.cuda() * op(xtemp).cuda() for w, op in zip(weights, self._ops))\n\n ans = torch.cat([temp1, xtemp2], dim=1)\n\n ans = channel_shuffle(ans.cuda(), self._k)\n # ans = torch.cat([ans[ : , dim_2//4:, :, :],ans[ : , : dim_2//4, :, :]],dim=1)\n # except channe shuffle, channel shift also works\n return ans\n\n\nclass Cell(nn.Module):\n\n def __init__(self, steps, multiplier, C_prev_prev, C_prev, C, reduction_prev):\n super(Cell, self).__init__()\n # cell的输出为各层输出的拼接,维度很高,所以在输入加了两个预处理preprocess0和preprocess1。\n if reduction_prev:\n self.preprocess0 = VaniConv3d(C_prev_prev, C, 1, [1, 2, 2], 0, affine=False)\n else:\n self.preprocess0 = VaniConv3d(C_prev_prev, C, 1, 1, 0, affine=False)\n self.preprocess1 = VaniConv3d(C_prev, C, 1, 1, 0, affine=False)\n\n self._steps = steps\n self._multiplier = multiplier\n\n self._ops = nn.ModuleList()\n self._bns = nn.ModuleList()\n for i in range(self._steps):\n for j in range(2 + i):\n stride = 1\n op = MixedOp(C, stride)\n self._ops.append(op)\n\n def forward(self, s0, s1, weights, weights2):\n\n s0 = self.preprocess0(s0)\n s1 = self.preprocess1(s1)\n states = [s0, s1]\n offset = 0\n for i in range(self._steps):\n # weights[offset + j]=([0.1429, 0.1426, 0.1429, 0.1428, 0.1429, 0.1429, 0.1429], weights2[offset + j]=0.49999\n s_temp = sum(weights2[offset + j].cuda() * self._ops[offset + j](h, weights[offset + j]).cuda() for j, h in\n enumerate(states))\n offset += len(states)\n states.append(s_temp)\n\n return torch.cat(states[-self._multiplier:], dim=1)\n\n\nclass InceptionI3d(nn.Module):\n \"\"\"Inception-v1 I3D architecture.\n The model is introduced in:\n Quo Vadis, Action Recognition? A New Model and the Kinetics Dataset\n Joao Carreira, Andrew Zisserman\n https://arxiv.org/pdf/1705.07750v1.pdf.\n See also the Inception architecture, introduced in:\n Going deeper with convolutions\n Christian Szegedy, Wei Liu, Yangqing Jia, Pierre Sermanet, Scott Reed,\n Dragomir Anguelov, Dumitru Erhan, Vincent Vanhoucke, Andrew Rabinovich.\n http://arxiv.org/pdf/1409.4842v1.pdf.\n \"\"\"\n\n # Endpoints of the model in order. During construction, all the endpoints up\n # to a designated `final_endpoint` are returned in a dictionary as the\n # second return value.\n VALID_ENDPOINTS = (\n 'Conv3d_1a_7x7',\n 'MaxPool3d_2a_3x3',\n 'Conv3d_2b_1x1',\n 'Conv3d_2c_3x3',\n 'MaxPool3d_3a_3x3',\n 'cell1',\n 'MaxPool3d_4a_3x3',\n 'cell2',\n 'MaxPool3d_5a_2x2',\n 'cell3',\n 'Logits',\n 'Predictions',\n )\n\n def __init__(self, num_classes, criterion, local_rank, steps=4, multiplier=4, spatial_squeeze=True,\n final_endpoint='Logits', name='inception_i3d', in_channels=3, dropout_keep_prob=0.5):\n \"\"\"Initializes I3D model instance.\n Args:\n num_classes: The number of outputs in the logit layer (default 400, which\n matches the Kinetics dataset).\n spatial_squeeze: Whether to squeeze the spatial dimensions for the logits\n before returning (default True).\n final_endpoint: The model contains many possible endpoints.\n `final_endpoint` specifies the last endpoint for the model to be built\n up to. In addition to the output at `final_endpoint`, all the outputs\n at endpoints up to `final_endpoint` will also be returned, in a\n dictionary. `final_endpoint` must be one of\n InceptionI3d.VALID_ENDPOINTS (default 'Logits').\n name: A string (optional). The name of this module.\n Raises:\n ValueError: if `final_endpoint` is not recognized.\n \"\"\"\n\n if final_endpoint not in self.VALID_ENDPOINTS:\n raise ValueError('Unknown final endpoint %s' % final_endpoint)\n\n super(InceptionI3d, self).__init__()\n self._num_classes = num_classes\n self._spatial_squeeze = spatial_squeeze\n self._final_endpoint = final_endpoint\n self.logits = None\n self._criterion = criterion\n self._steps = steps\n self._multiplier = multiplier\n\n if self._final_endpoint not in self.VALID_ENDPOINTS:\n raise ValueError('Unknown final endpoint %s' % self._final_endpoint)\n self.MaxpoolSpa = nn.MaxPool3d(kernel_size=[1, 3, 3], padding=[0, 1, 1], stride=[1, 2, 2])\n\n self.end_points = {}\n end_point = 'Conv3d_1a_7x7'\n self.end_points[end_point] = Unit3D(in_channels=in_channels, output_channels=64, kernel_shape=[7, 7, 7],\n stride=(2, 2, 2), padding=(3, 3, 3), name=name + end_point)\n if self._final_endpoint == end_point: return\n\n end_point = 'MaxPool3d_2a_3x3'\n self.end_points[end_point] = MaxPool3dSamePadding(kernel_size=[1, 3, 3], stride=(1, 2, 2),\n padding=0)\n if self._final_endpoint == end_point: return\n\n end_point = 'Conv3d_2b_1x1'\n self.end_points[end_point] = Unit3D(in_channels=64, output_channels=64, kernel_shape=[1, 1, 1], padding=0,\n name=name + end_point)\n if self._final_endpoint == end_point: return\n\n end_point = 'Conv3d_2c_3x3'\n self.end_points[end_point] = Unit3D(in_channels=64, output_channels=192, kernel_shape=[3, 3, 3], padding=1,\n name=name + end_point)\n if self._final_endpoint == end_point: return\n\n end_point = 'MaxPool3d_3a_3x3'\n self.end_points[end_point] = MaxPool3dSamePadding(kernel_size=[1, 3, 3], stride=(1, 2, 2),\n padding=0)\n if self._final_endpoint == end_point: return\n\n end_point = 'cell1'\n self.end_points[end_point] = nn.ModuleList()\n C_curr = 64\n C_prev_prev, C_prev, C_curr = C_curr * 3, C_curr * 3, C_curr\n reduction_prev = False\n for i in range(2):\n cell = Cell(steps, multiplier, C_prev_prev, C_prev, C_curr, reduction_prev)\n self.end_points[end_point] += [cell]\n C_prev_prev, C_prev = C_prev, multiplier * C_curr\n if self._final_endpoint == end_point: return\n\n end_point = 'MaxPool3d_4a_3x3'\n self.end_points[end_point] = MaxPool3dSamePadding(kernel_size=[3, 3, 3], stride=(2, 2, 2), padding=0)\n if self._final_endpoint == end_point: return\n\n end_point = 'cell2'\n self.end_points[end_point] = nn.ModuleList()\n C_prev_prev, C_prev, C_curr = C_prev, C_prev, C_curr\n for i in range(5):\n if i == 2:\n C_curr *= 2\n reduction_prev = False\n else:\n reduction_prev = False\n cell = Cell(steps, multiplier, C_prev_prev, C_prev, C_curr, reduction_prev)\n self.end_points[end_point] += [cell]\n C_prev_prev, C_prev = C_prev, multiplier * C_curr\n\n end_point = 'MaxPool3d_5a_2x2'\n self.end_points[end_point] = MaxPool3dSamePadding(kernel_size=[2, 2, 2], stride=(2, 2, 2), padding=0)\n if self._final_endpoint == end_point: return\n\n end_point = 'cell3'\n self.end_points[end_point] = nn.ModuleList()\n C_prev_prev, C_prev, C_curr = C_prev, C_prev, C_curr\n reduction_prev = False\n for i in range(2):\n if i == 1:\n C_curr *= 2\n cell = Cell(steps, multiplier, C_prev_prev, C_prev, C_curr, reduction_prev)\n self.end_points[end_point] += [cell]\n C_prev_prev, C_prev = C_prev, multiplier * C_curr\n if self._final_endpoint == end_point: return\n\n end_point = 'Logits'\n # self.avg_pool = nn.AvgPool3d(kernel_size=[2, 7, 7],\n # stride=(1, 1, 1))\n self.avg_pool = nn.AdaptiveAvgPool3d(1)\n self.dropout = nn.Dropout(dropout_keep_prob)\n self.logits = Unit3D(in_channels=384 + 384 + 128 + 128, output_channels=self._num_classes,\n kernel_shape=[1, 1, 1],\n padding=0,\n activation_fn=None,\n use_batch_norm=False,\n use_bias=True,\n name='logits')\n\n self.build()\n self._initialize_alphas(local_rank)\n\n def replace_logits(self, num_classes):\n self._num_classes = num_classes\n self.logits = Unit3D(in_channels=384 + 384 + 128 + 128, output_channels=self._num_classes,\n kernel_shape=[1, 1, 1],\n padding=0,\n activation_fn=None,\n use_batch_norm=False,\n use_bias=True,\n name='logits')\n\n def build(self):\n for k in self.end_points.keys():\n self.add_module(k, self.end_points[k])\n\n def forward(self, x):\n for end_point in self.VALID_ENDPOINTS:\n if end_point in self.end_points:\n if end_point == 'cell1':\n s0 = s1 = x\n for ii, cell in enumerate(self._modules[end_point]):\n weights = F.softmax(self.alphas_normal1, dim=-1) # 14x7(edge x operations)\n n = 3\n start = 2\n weights2 = F.softmax(self.betas_normal1[0:2], dim=-1) # self.betas_normal16: 14x1\n for i in range(self._steps - 1):\n end = start + n\n tw2 = F.softmax(self.betas_normal1[start:end], dim=-1) # 2-5, 5-9, 9-14\n start = end\n n += 1\n weights2 = torch.cat([weights2, tw2], dim=0)\n\n s0, s1 = s1, cell(s0, s1, weights, weights2)\n x = s1\n\n elif end_point == 'cell2':\n s0 = s1 = x\n for ii, cell in enumerate(self._modules[end_point]):\n weights = F.softmax(self.alphas_normal2, dim=-1) # 14x7(edge x operations)\n n = 3\n start = 2\n weights2 = F.softmax(self.betas_normal2[0:2], dim=-1) # self.betas_normal16: 14x1\n for i in range(self._steps - 1):\n end = start + n\n tw2 = F.softmax(self.betas_normal2[start:end], dim=-1) # 2-5, 5-9, 9-14\n start = end\n n += 1\n weights2 = torch.cat([weights2, tw2], dim=0)\n s0, s1 = s1, cell(s0, s1, weights, weights2)\n x = s1\n elif end_point == 'cell3':\n s0 = s1 = x\n for ii, cell in enumerate(self._modules[end_point]):\n weights = F.softmax(self.alphas_normal3, dim=-1) # 14x7(edge x operations)\n n = 3\n start = 2\n weights2 = F.softmax(self.betas_normal3[0:2], dim=-1) # self.betas_normal16: 14x1\n for i in range(self._steps - 1):\n end = start + n\n tw3 = F.softmax(self.betas_normal3[start:end], dim=-1) # 2-5, 5-9, 9-14\n start = end\n n += 1\n weights2 = torch.cat([weights2, tw3], dim=0)\n s0, s1 = s1, cell(s0, s1, weights, weights2)\n\n x = s1\n else:\n x = self._modules[end_point](x) # use _modules to work with dataparallel\n\n x = self.logits(self.dropout(self.avg_pool(x)))\n if self._spatial_squeeze:\n logits = x.squeeze(3).squeeze(3)\n # logits is batch X time X classes, which is what we want to work with\n return logits.squeeze()\n\n def _loss(self, inputs, target):\n logits = self(inputs)\n return self._criterion(logits, target)\n\n def _initialize_alphas(self, local_rank):\n k = sum(1 for i in range(self._steps) for n in range(2 + i))\n num_ops = len(PRIMITIVES)\n\n self.alphas_normal1 = Variable(1e-3 * torch.randn(k, num_ops).cuda(local_rank), requires_grad=True) # net normal\n self.betas_normal1 = Variable(1e-3 * torch.randn(k).cuda(local_rank), requires_grad=True) # edge normal\n self.alphas_normal2 = Variable(1e-3 * torch.randn(k, num_ops).cuda(local_rank), requires_grad=True) # net normal\n self.betas_normal2 = Variable(1e-3 * torch.randn(k).cuda(local_rank), requires_grad=True) # edge normal\n self.alphas_normal3 = Variable(1e-3 * torch.randn(k, num_ops).cuda(local_rank), requires_grad=True) # net normal\n self.betas_normal3 = Variable(1e-3 * torch.randn(k).cuda(local_rank), requires_grad=True) # edge normal\n self._arch_parameters = [\n self.alphas_normal1,\n self.betas_normal1,\n self.alphas_normal2,\n self.betas_normal2,\n self.alphas_normal3,\n self.betas_normal3\n ]\n def resume_arch_parameters(self, parames, local_rank):\n self.alphas_normal1 = Variable(parames[0].cuda(local_rank), requires_grad=True) # net normal\n self.betas_normal1 = Variable(parames[1].cuda(local_rank), requires_grad=True) # edge normal\n self.alphas_normal2 = Variable(parames[2].cuda(local_rank), requires_grad=True) # net normal\n self.betas_normal2 = Variable(parames[3].cuda(local_rank), requires_grad=True) # edge normal\n self.alphas_normal3 = Variable(parames[4].cuda(local_rank), requires_grad=True) # net normal\n self.betas_normal3 = Variable(parames[5].cuda(local_rank), requires_grad=True) # edge normal\n\n def arch_parameters(self):\n return self._arch_parameters\n\n def extract_features(self, x):\n for end_point in self.VALID_ENDPOINTS:\n if end_point in self.end_points:\n x = self._modules[end_point](x)\n return self.avg_pool(x)\n\n def genotype(self):\n def _parse(weights, weights2):\n gene = []\n n = 2\n start = 0\n # 对于每层,由归一化后的参数乘积排序,取最大的两个非空操作为边。每条边再确定最佳操作。\n for i in range(self._steps):\n end = start + n\n # W: [[0.14320895 0.14271285 0.14264019 0.14287315 0.14279652 0.14292398, 0.14284438]\n # [0.1430605 0.14276284 0.14267652 0.14286381 0.1430042 0.14296356, 0.14266858]]\n W = weights[start:end].copy()\n W2 = weights2[start:end].copy() # [0.4998488 0.5001512]\n\n for j in range(n):\n W[j, :] = W[j, :] * W2[j] # each operation * weights2\n\n edges = sorted(range(i + 2),\n key=lambda x: -max(W[x][k] for k in range(len(W[x])) if k != PRIMITIVES.index('none')))[\n :2]\n # edges=1, 0\n\n # edges = sorted(range(i + 2), key=lambda x: -W2[x])[:2]\n for j in edges:\n k_best = None\n for k in range(len(W[j])):\n if k != PRIMITIVES.index('none'):\n if k_best is None or W[j][k] > W[j][k_best]:\n k_best = k\n gene.append((PRIMITIVES[k_best], j))\n start = end\n n += 1\n return gene\n\n # start = 2跳过两个输入节点, 循环处理3个中间节点, 统一将同层betas_normal16送 Softmax 归一化\n n = 3\n start = 2\n weightsn1 = F.softmax(self.betas_normal1[0:2], dim=-1)\n weightsn2 = F.softmax(self.betas_normal2[0:2], dim=-1)\n weightsn3 = F.softmax(self.betas_normal3[0:2], dim=-1)\n\n for i in range(self._steps - 1):\n end = start + n\n # print(self.betas_reduce[start:end])\n tn1 = F.softmax(self.betas_normal1[start:end], dim=-1)\n tn2 = F.softmax(self.betas_normal2[start:end], dim=-1)\n tn3 = F.softmax(self.betas_normal3[start:end], dim=-1)\n start = end\n n += 1\n weightsn1 = torch.cat([weightsn1, tn1], dim=0)\n weightsn2 = torch.cat([weightsn2, tn2], dim=0)\n weightsn3 = torch.cat([weightsn3, tn3], dim=0)\n\n gene_normal1 = _parse(F.softmax(self.alphas_normal1, dim=-1).data.cpu().numpy(),\n weightsn1.data.cpu().numpy())\n gene_normal2 = _parse(F.softmax(self.alphas_normal2, dim=-1).data.cpu().numpy(),\n weightsn2.data.cpu().numpy())\n gene_normal3 = _parse(F.softmax(self.alphas_normal3, dim=-1).data.cpu().numpy(),\n weightsn3.data.cpu().numpy())\n\n concat = range(2 + self._steps - self._multiplier, self._steps + 2)\n genotype = Genotype(\n normal1=gene_normal1, normal_concat1=concat,\n normal2=gene_normal2, normal_concat2=concat,\n normal3=gene_normal3, normal_concat3=concat,\n )\n return genotype\n\n\nif __name__ == '__main__':\n import os, torch\n\n sample_size = 224\n sample_duration = 32\n num_classes = 40\n resnet_shortcut = 'A'\n os.environ[\"CUDA_VISIBLE_DEVICES\"] = '1'\n\n model = InceptionI3d(num_classes, torch.nn.CrossEntropyLoss(), in_channels=3).cuda()\n\n inputs = torch.randn(2, 3, 64, 112, 112).cuda() # shape (C x T x H x W)\n outputs = model(inputs)\n print(outputs.shape)\n", "import torch\r\nfrom .base import Datasets as dataset\r\nfrom torchvision import transforms, set_image_backend\r\nimport random, os\r\nfrom PIL import Image\r\nimport numpy as np\r\nimport accimage\r\nset_image_backend('accimage')\r\nfrom scipy.ndimage.filters import gaussian_filter\r\nimport json\r\nimport matplotlib.pyplot as plt\r\nmycmap = plt.cm.get_cmap('jet')\r\n\r\nclass DSAttDatasets(dataset):\r\n def __init__(self, args, dataset_root, ground_truth, typ, sample_duration=16, sample_size=224, phase='train'):\r\n super(DSAttDatasets, self).__init__(args, dataset_root, ground_truth, typ, sample_duration, sample_size, phase)\r\n\r\n def image_propose(self, data_path, sl):\r\n sample_size = self.sample_size\r\n if self.phase == 'train':\r\n resize = eval(self.args.resize)\r\n else:\r\n resize = (256, 256)\r\n crop_rect, is_flip = self.transform_params(resize=resize, flip=self.args.flip) # no flip\r\n\r\n if random.uniform(0, 1) < self.args.rotated and self.phase == 'train':\r\n rotated = random.randint(0, 10)\r\n else:\r\n rotated = 0\r\n def image_to_np(image):\r\n \"\"\"\r\n Returns:\r\n np.ndarray: Image converted to array with shape (width, height, channels)\r\n \"\"\"\r\n image_np = np.empty([image.channels, image.height, image.width], dtype=np.uint8)\r\n image.copyto(image_np)\r\n image_np = np.transpose(image_np, (1, 2, 0))\r\n return image_np\r\n\r\n def transform(img):\r\n img = self.rotate(img, rotated)\r\n img = Image.fromarray(img)\r\n img = img.resize(resize)\r\n img = img.crop(crop_rect)\r\n if is_flip:\r\n img = img.transpose(Image.FLIP_LEFT_RIGHT)\r\n return np.array(img.resize((sample_size, sample_size)))\r\n # return image_to_np(img.resize((sample_size, sample_size)))\r\n def get_gmap(kp_path, img, a):\r\n with open(os.path.join(kp_path, '%06d_keypoints.json' % a), 'r') as f:\r\n kps = json.loads(f.read())\r\n pose = kps['people'][0]['pose_keypoints_2d']\r\n r_hand = kps['people'][0]['hand_right_keypoints_2d']\r\n l_hand = kps['people'][0]['hand_left_keypoints_2d']\r\n arr_x = pose[0::3] + r_hand[0::3] + l_hand[0::3]\r\n arr_y = pose[1::3] + r_hand[1::3] + l_hand[1::3]\r\n if not any(arr_x) or not any(arr_y):\r\n return np.ones((sample_size, sample_size))\r\n h, w, c = img.shape\r\n mp = np.zeros((h, w))\r\n for x, y in zip(arr_x, arr_y):\r\n x, y = round(x), round(y)\r\n if x < w and x > 0 and y < h and y > 0:\r\n mp[y, x] = 1\r\n mp = gaussian_filter(mp, sigma=20)\r\n mp = (mp - np.min(mp)) / (np.max(mp) - np.min(mp) + 0.0000001)\r\n mp = Image.fromarray(self.rotate(np.asarray(mp), rotated))\r\n mp = mp.resize(resize).crop(crop_rect).resize((sample_size, sample_size))\r\n if is_flip:\r\n mp = mp.transpose(Image.FLIP_LEFT_RIGHT)\r\n\r\n mp = np.array(mp)\r\n # plt.matshow(mp)\r\n # plt.imsave('vis.png', img, cmap=mycmap, vmin=.1)\r\n # plt.savefig('res.png')\r\n return mp\r\n\r\n def getskg_tensor(skgmap):\r\n a = torch.from_numpy(skgmap.astype(np.float32))\r\n return a.view(1, 1, sample_size, sample_size)\r\n def Sample_Image(imgs_path, sl):\r\n frams = []\r\n skgmaparr = []\r\n for a in sl:\r\n # img = Image.open(os.path.join(imgs_path, \"%06d.jpg\" % a))\r\n img = image_to_np(accimage.Image(os.path.join(imgs_path, \"%06d.jpg\" % a)))\r\n imgs = transform(img)\r\n frams.append(self.transform(imgs).view(3, sample_size, sample_size, 1))\r\n kp_path = imgs_path.replace('Image', 'keypoints')\r\n gmap = get_gmap(kp_path, np.asarray(img), a)\r\n skgmaparr.append(gmap)\r\n return torch.cat(frams, dim=3).type(torch.FloatTensor), torch.cat([getskg_tensor(a) for a in skgmaparr], dim=1)\r\n return Sample_Image(data_path, sl)\r\n def __getitem__(self, index):\r\n \"\"\"\r\n Args:\r\n index (int): Index\r\n Returns:\r\n tuple: (image, target) where target is class_index of the target class.\r\n \"\"\"\r\n sl = self.get_sl(self.inputs[index][1])\r\n self.data_path = os.path.join(self.dataset_root, self.inputs[index][0])\r\n self.clip, skgmaparr = self.image_propose(self.data_path, sl)\r\n\r\n return self.clip.permute(0, 3, 1, 2), self.inputs[index][2], skgmaparr\r\n\r\n def __len__(self):\r\n return len(self.inputs)\r\n" ]
[ [ "torch.nn.Dropout", "torch.nn.functional.softmax", "torch.transpose", "torch.nn.CrossEntropyLoss", "torch.cat", "torch.randn", "torch.nn.ModuleList", "torch.nn.AdaptiveAvgPool3d", "torch.nn.MaxPool3d", "torch.nn.Conv3d", "torch.nn.BatchNorm3d", "torch.nn.functional.pad" ], [ "matplotlib.pyplot.cm.get_cmap", "numpy.min", "numpy.asarray", "torch.cat", "numpy.ones", "numpy.max", "scipy.ndimage.filters.gaussian_filter", "numpy.transpose", "numpy.array", "numpy.zeros", "numpy.empty" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [ "0.13", "1.6", "0.14", "0.15", "1.4", "0.16", "1.0", "0.19", "1.5", "0.18", "1.2", "1.7", "0.12", "0.10", "0.17", "1.3" ], "tensorflow": [] } ]
aesqgr/har-fbc
[ "69a2ca42edaf6b7c5db7b10cce2dc85d7f8d0473" ]
[ "src/dashboard_pages/model_dash.py" ]
[ "import sys\nprint(sys.path)\nsys.path.append(\"..\")\nsys.path.append(\"../src\")\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport streamlit as st\nimport seaborn as sns\nfrom keras.models import load_model, Sequential\nfrom keras.layers import LSTM, Dense, Flatten, Dropout\nimport numpy as np\nimport tensorflow as tf\nfrom sklearn.model_selection import train_test_split\n\n\n\nmodel = load_model('src/model_fld/model.h5')\n\n\n#build dataframe\ncolumns = ['user','activity','timestamp', 'x-axis', 'y-axis', 'z-axis']\ndf_har = pd.read_csv('./src/WISDM_ar_v1.1/WISDM_ar_v1.1_raw.txt', header = None, names = columns)\ndf_har = df_har.dropna()\ndf_har.shape\ndf_har['z-axis'] = df_har['z-axis'].str.replace(';', '')\ndf_har['z-axis'] = df_har['z-axis'].apply(lambda x:float(x))\ndf = df_har[df_har['timestamp'] != 0]\ndf = df.sort_values(by = ['user', 'timestamp'], ignore_index=True)\n\n#misc\nhistory = pd.read_csv('./src/model_fld/history_test.csv', header = [0])\n\n\ndef app():\n st.set_option('deprecation.showPyplotGlobalUse', False)\n st.title('Data Cleaning & Model architecture')\n st.write('Echemos un vistazo a los datos...')\n st.write(\"**Original shape:** \", df_har.shape)\n st.write(\"**Final shape:** \", df.shape)\n st.write(\"**DataFrame reduction:** \", \"{:.0%}\".format((df.shape[0]/df_har.shape[0] - 1)))\n st.write(df.head())\n\n st.write(\"Veamos como se reparten las muestras por cada actividad\")\n sns.set_style(\"whitegrid\")\n st.write(sns.countplot(x = \"activity\", data = df))\n plt.title(\"Number of samples by activity\")\n st.pyplot(plt.show())\n\n st.write(\"Cada actividad tiene una forma característica\")\n data36 = df[(df[\"user\"] == 36) & (df[\"activity\"] == \"Jogging\")][:400]\n columns_select = st.beta_columns(2)\n with columns_select[0]:\n data36 = df[(df[\"user\"] == 36) & (df[\"activity\"] == \"Jogging\")][:400]\n sns.lineplot(y = \"x-axis\", x = \"timestamp\", data = data36)\n sns.lineplot(y = \"y-axis\", x = \"timestamp\", data = data36)\n sns.lineplot(y = \"z-axis\", x = \"timestamp\", data = data36)\n plt.legend([\"x-axis\", \"y-axis\", \"z-axis\"])\n plt.ylabel(\"Jogging\")\n plt.title(\"Jogging\", fontsize = 15)\n st.pyplot()\n data36 = df[(df[\"user\"] == 36) & (df[\"activity\"] == \"Walking\")][:400]\n sns.lineplot(y = \"x-axis\", x = \"timestamp\", data = data36)\n sns.lineplot(y = \"y-axis\", x = \"timestamp\", data = data36)\n sns.lineplot(y = \"z-axis\", x = \"timestamp\", data = data36)\n plt.legend([\"x-axis\", \"y-axis\", \"z-axis\"])\n plt.ylabel(\"Walking\")\n plt.title(\"Walking\", fontsize = 15)\n st.pyplot()\n data36 = df[(df[\"user\"] == 36) & (df[\"activity\"] == \"Upstairs\")][:400]\n sns.lineplot(y = \"x-axis\", x = \"timestamp\", data = data36)\n sns.lineplot(y = \"y-axis\", x = \"timestamp\", data = data36)\n sns.lineplot(y = \"z-axis\", x = \"timestamp\", data = data36)\n plt.legend([\"x-axis\", \"y-axis\", \"z-axis\"])\n plt.ylabel(\"Upstairs\")\n plt.title(\"Upstairs\", fontsize = 15)\n st.pyplot()\n with columns_select[1]:\n data36 = df[(df[\"user\"] == 36) & (df[\"activity\"] == \"Downstairs\")][:400]\n sns.lineplot(y = \"x-axis\", x = \"timestamp\", data = data36)\n sns.lineplot(y = \"y-axis\", x = \"timestamp\", data = data36)\n sns.lineplot(y = \"z-axis\", x = \"timestamp\", data = data36)\n plt.legend([\"x-axis\", \"y-axis\", \"z-axis\"])\n plt.ylabel(\"Downstairs\")\n plt.title(\"Downstairs\", fontsize = 15)\n st.pyplot()\n data36 = df[(df[\"user\"] == 36) & (df[\"activity\"] == \"Standing\")][:400]\n sns.lineplot(y = \"x-axis\", x = \"timestamp\", data = data36)\n sns.lineplot(y = \"y-axis\", x = \"timestamp\", data = data36)\n sns.lineplot(y = \"z-axis\", x = \"timestamp\", data = data36)\n plt.legend([\"x-axis\", \"y-axis\", \"z-axis\"])\n plt.ylabel(\"Standing\")\n plt.title(\"Standing\", fontsize = 15)\n st.pyplot()\n data36 = df[(df[\"user\"] == 36) & (df[\"activity\"] == \"Sitting\")][:400]\n sns.lineplot(y = \"x-axis\", x = \"timestamp\", data = data36)\n sns.lineplot(y = \"y-axis\", x = \"timestamp\", data = data36)\n sns.lineplot(y = \"z-axis\", x = \"timestamp\", data = data36)\n plt.legend([\"x-axis\", \"y-axis\", \"z-axis\"])\n plt.ylabel(\"Sitting\")\n plt.title(\"Sitting\", fontsize = 15)\n st.pyplot()\n \n st.image('src/dashboard_pages/imgs/model_summary.png')\n\n plt.plot(np.array(history['loss']), \"r--\", label = \"Train loss\")\n plt.plot(np.array(history['accuracy']), \"g--\", label = \"Train accuracy\")\n plt.plot(np.array(history['val_loss']), \"r-\", label = \"Validation loss\")\n plt.plot(np.array(history['val_accuracy']), \"g-\", label = \"Validation accuracy\")\n plt.title(\"Training session's progress over iterations\")\n plt.legend(loc='lower left')\n plt.ylabel('Training Progress (Loss/Accuracy)')\n plt.xlabel('Training Epoch')\n plt.ylim(0) \n st.pyplot()\n \n st.image('src/dashboard_pages/imgs/conf_matrix.png')\n\n\n " ]
[ [ "matplotlib.pyplot.legend", "pandas.read_csv", "matplotlib.pyplot.title", "matplotlib.pyplot.ylim", "matplotlib.pyplot.xlabel", "numpy.array", "matplotlib.pyplot.show", "matplotlib.pyplot.ylabel" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "2.0", "1.4", "1.1", "1.5", "1.2", "1.3" ], "scipy": [], "tensorflow": [] } ]
damicoedoardo/NNMF
[ "69fff4848b3243a2d3347bec3e1c9a01ae40e51a" ]
[ "RecSysFramework/Experiments/performance_user_pop.py" ]
[ "from RecSysFramework.Evaluation.Evaluator import EvaluatorMetrics\nfrom RecSysFramework.Utils.get_holdout import retrieve_train_validation_test_holdhout_dataset\nfrom RecSysFramework.Recommender.NonPersonalized import TopPop\nfrom RecSysFramework.Experiments.utils_experiments import get_results_latex_from_dict, round_all_digits\nfrom RecSysFramework.Utils.get_model_from_best_models import get_model\nimport matplotlib.pyplot as plt\nfrom RecSysFramework.Evaluation.Evaluator import EvaluatorHoldout\nfrom RecSysFramework.Utils.compute_popularity import *\nimport numpy as np\n\ndef comp_perc(mf, nnmf):\n return 100*(nnmf-mf)/min(mf, nnmf)\n\ndef get_result_list(urm_train, urm_test, cutoff_list, metric_list, models_objects, cut_list, disjoint=True):\n pop = compute_popularity_user(urm_train)\n users, interactions = zip(*pop)\n users = np.array(users)\n interactions = np.array(interactions)\n cum_sum_interactions = np.cumsum(interactions)\n tot_interactions = np.sum(interactions)\n evalh = EvaluatorHoldout(cutoff_list, metric_list, minRatingsPerUser=0)\n evalh.global_setup(urm_test)\n results_list = [evalh.evaluateRecommender(\n m).get_results_dictionary(per_user=True) for m in models_objects]\n for t in zip(cut_list, cut_list[1:]):\n if disjoint:\n users_to_cons = users[(cum_sum_interactions >= t[0]*tot_interactions) & (cum_sum_interactions <= t[1]*tot_interactions)]\n else:\n users_to_cons = users[cum_sum_interactions <= t[1]*tot_interactions]\n perc_bpr.append(comp_perc(np.average(np.array(results_list[0][5]['MAP'])[users_to_cons]), np.average(np.array(results_list[1][5]['MAP'])[users_to_cons])))\n perc_funk.append(comp_perc(np.average(np.array(results_list[2][5]['MAP'])[users_to_cons]), np.average(np.array(results_list[3][5]['MAP'])[users_to_cons])))\n perc_prob.append(comp_perc(np.average(np.array(results_list[4][5]['MAP'])[users_to_cons]), np.average(np.array(results_list[5][5]['MAP'])[users_to_cons])))\n return perc_bpr, perc_funk, perc_prob\n\ncutoff_list = [5, ]\nmetrics_list = [EvaluatorMetrics.MAP,]\ndisjoint = False\n\nl = ['LastFMHetrec2011Reader', 'Movielens1MReader', 'BookCrossingReader', 'CiteULike_aReader', 'PinterestReader']\nfor name in l:\n train, test, validation, dataset_name = retrieve_train_validation_test_holdhout_dataset(name)\n\n\n models_objects = []\n models_names = []\n m1, model_name = get_model(train, dataset_name, 'BPRMF')\n models_objects.append(m1)\n models_names.append(model_name)\n m1, model_name = get_model(train, dataset_name, 'BPR_NNMF')\n models_objects.append(m1)\n models_names.append(model_name)\n m1, model_name = get_model(train, dataset_name, 'FunkSVD')\n models_objects.append(m1)\n models_names.append(model_name)\n m1, model_name = get_model(train, dataset_name, 'FUNK_NNMF')\n models_objects.append(m1)\n models_names.append(model_name)\n m1, model_name = get_model(train, dataset_name, 'probmf')\n models_objects.append(m1)\n models_names.append(model_name)\n m1, model_name = get_model(train, dataset_name, 'nnprobmf')\n models_objects.append(m1)\n models_names.append(model_name)\n\n perc_bpr = []\n perc_funk = []\n perc_prob = []\n cut_list = [0.0, 0.2, 0.4, 0.6, 0.8, 1]\n perc_bpr, perc_funk, perc_prob = get_result_list(train.get_URM(), validation.get_URM(), cutoff_list, metrics_list, models_objects, cut_list, disjoint=disjoint)\n\n plt.plot(cut_list[1:], perc_bpr, label='bpr')\n plt.plot(cut_list[1:], perc_funk, label='funk')\n plt.plot(cut_list[1:], perc_prob, label='prob')\n plt.axhline(y=0, color='gray', linestyle='--')\n axes = plt.gca()\n axes.set_ylim([-100,100])\n plt.legend()\n if disjoint:\n plt.savefig('{}_performance_varying_user_pop_disjoint.png'.format(dataset_name))\n else:\n plt.savefig('{}_performance_varying_user_pop_joint.png'.format(dataset_name))\n plt.close()\n" ]
[ [ "matplotlib.pyplot.gca", "matplotlib.pyplot.legend", "matplotlib.pyplot.axhline", "numpy.cumsum", "matplotlib.pyplot.plot", "matplotlib.pyplot.close", "numpy.array", "numpy.sum" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
DanyangSu/linkalman
[ "3be320f36cca2795f1380d0d9b4ef6831247a601", "3be320f36cca2795f1380d0d9b4ef6831247a601" ]
[ "linkalman/test/core/deprecated_test_Constant_M.py", "linkalman/test/core/conftest.py" ]
[ "import pytest\nimport pandas as pd\nimport numpy as np\nfrom linkalman.core.utils import Constant_M\nfrom copy import deepcopy\n\n\n# Test __init__\ndef test_wrong_M_type():\n \"\"\"\n Test if raise exception if M is not a numpy array\n \"\"\"\n M = 2.1\n T = 5\n with pytest.raises(TypeError):\n Mt = Constant_M(M, T)\n\n\n# Test __getitem__\ndef test_getitem():\n \"\"\"\n Test getitem\n \"\"\"\n M = np.array([2, 3])\n T = 5\n Mt = Constant_M(M, T)\n assert(np.array_equal(Mt[0], M))\n\n\n# Test __setitem__\ndef test_setitem():\n \"\"\"\n Test setitem\n \"\"\"\n M = np.array([2, 3])\n T = 5\n Mt = Constant_M(M, T)\n M_modify = np.array([4, 5])\n Mt[1] = M_modify\n assert(np.array_equal(Mt[1], M_modify))\n\n\ndef test_setitem_other_index():\n \"\"\"\n Test if setitem affect other index\n \"\"\"\n M = np.array([2, 3])\n T = 5\n Mt = Constant_M(M, T)\n M_modify = np.array([4, 5])\n Mt[1] = M_modify\n assert(np.array_equal(Mt[2], np.array([2, 3])))\n\n\ndef test_setitem_partial_update():\n \"\"\"\n Test whether correctly modify indexed array\n \"\"\"\n M = np.array([[5, 3], [3, 4]])\n T = 10\n Mt = Constant_M(M, T)\n Mt[0][1, :] = 0\n expected_result = np.array([[5, 3], [0, 0]])\n result = Mt[0]\n np.testing.assert_array_equal(expected_result, result)\n\n\ndef test_setitem_partial_update_other_index():\n \"\"\"\n Test whether partially updating array affect other arrays\n \"\"\"\n M = np.array([[5, 3], [3, 4]])\n T = 10\n Mt = Constant_M(M, T)\n Mt[0][1, :] = 0\n expected_result = np.array([[5, 3], [3, 4]])\n result = Mt[1]\n np.testing.assert_array_equal(expected_result, result)\n\n\ndef test_setitem_comprehensive():\n \"\"\"\n Test multiple operations involving setitem\n \"\"\"\n M = np.array([[5, 3], [3, 4]])\n T = 10\n Mt = Constant_M(M, T)\n expected_result_1 = np.array([[5, 2], [1, 5]]) # full update\n expected_result_2 = np.array([[5, 3], [0, 0]]) # partial update\n expected_result_default = np.array([[5, 3], [3, 4]])\n expected_result = [expected_result_2, expected_result_default, \n expected_result_default, expected_result_1,\n expected_result_1, expected_result_default,\n expected_result_default, expected_result_default,\n expected_result_1]\n\n # Partial Update\n Mt[0][1, :] = 0\n\n # Full update \n Mt[3] = deepcopy(expected_result_1)\n\n # Update twice\n Mt[4] = deepcopy(expected_result_2)\n Mt[4] = deepcopy(expected_result_1)\n\n # Update twice, second time same as M\n Mt[5] = deepcopy(expected_result_1)\n Mt[5] = deepcopy(expected_result_default)\n\n # Partially update twice, second time same as M\n Mt[6][1, :] = 0\n Mt[6][1, :] = np.array([3, 4])\n\n # Partially update then full update, second time same as M\n Mt[7][1, :] = 0\n Mt[7] = deepcopy(expected_result_default)\n\n # Partially update then full update\n Mt[8][1, :] = 0\n Mt[8] = deepcopy(expected_result_1)\n match = True\n for i in range(9):\n match = match and np.array_equal(Mt[i], expected_result[i])\n assert(match)\n", "import pytest\nimport numpy as np\nfrom linkalman.core.utils import *\nimport pandas as pd\n\n\n# Generate input data\[email protected]()\ndef Mt():\n Mt = {'Ft': build_tensor(np.ones((3, 3)), 10),\n 'Bt': build_tensor(np.ones((3, 2)), 10),\n 'Ht': build_tensor(np.ones((4, 3)), 10),\n 'Dt': build_tensor(np.ones((4, 2)), 10),\n 'Qt': build_tensor(np.ones((3, 3)), 10),\n 'Rt': build_tensor(np.ones((4, 4)), 10),\n 'xi_1_0': np.ones((3, 1)),\n 'P_1_0': np.ones((3, 3))}\n return Mt\n\n\[email protected]()\ndef df1():\n df = pd.DataFrame({'a': [1, 2, 3], 'b': [4, 5, 6]})\n return df\n\n\[email protected]()\ndef Yt():\n Yt = np.ones((1, 4, 1))\n return Yt\n\n\[email protected]()\ndef Xt():\n Xt = np.ones((1, 2, 1))\n return Xt\n\n\[email protected]()\ndef perm_mat():\n mat = np.array([[1, 2, 3, 4],\n [2, 5, 6, 7],\n [3, 6, 8, 9],\n [4, 7, 9, 0]])\n return mat\n\n\[email protected]()\ndef perm_vector():\n vec = np.array([[1], [2], [3], [4]])\n return vec\n\n\[email protected]()\ndef ft_ar1():\n \"\"\"\n Standard ar1 process\n \"\"\"\n def ft_(theta, T):\n def f(theta):\n phi_1 = 1 / (np.exp(theta[0])+1)\n sigma_Q = np.exp(theta[1])\n sigma_R = np.exp(theta[2])\n F = np.array([[phi_1]])\n Q = np.array([[sigma_Q]])\n R = np.array([[sigma_R]])\n H = np.array([[1]])\n B = np.array([[0.1]])\n M = {'F': F, 'Q': Q, 'H': H, 'R': R, 'B': B} \n return M\n ft(theta, f, T)\n return ft_\n\n\[email protected]()\ndef Yt_1d():\n \"\"\"\n 1d Yt\n \"\"\"\n y = np.array([[[1]], [[np.nan]], [[2.5]]])\n return y\n\n\[email protected]()\ndef Xt_1d():\n \"\"\"\n 1d Xt\n \"\"\"\n x = np.array([[[0.1]], [[0.2]], [[0.3]]])\n return x\n\n\[email protected]()\ndef theta_ar1():\n \"\"\"\n theta for AR1 process\n \"\"\"\n theta = [-0.1, -0.2, -0.3]\n return theta\n\n\[email protected]()\ndef theta_mvar():\n theta_ = [0, 0.3, -0.1, -0.2, 0.1, 0.2, 0.15, 0.25]\n return theta_\n\n\[email protected]()\ndef theta_mvar_diffuse():\n theta_ = [-30, 0.3]\n return theta_\n\n\[email protected]()\ndef ft_mvar():\n \"\"\"\n Multi-measurement ar1 process\n \"\"\"\n def ft_(theta, T):\n def f(theta):\n phi_1 = 1 / (np.exp(theta[0])+1)\n if phi_1 > 1 - 0.001:\n phi_1 = 1\n sigma_Q = np.exp(theta[1])\n\n F = np.array([[phi_1]])\n Q = np.array([[sigma_Q]])\n R = np.array([[3, 2, 1], \n [2, 4, 3],\n [1, 3, 6]])\n H = np.array([[1], [2], [2.4]])\n B = np.array([[0.1]])\n D = np.array([[-0.1], [-0.2], [0.1]])\n M = {'F': F, 'Q': Q, 'H': H, 'R': R, 'B': B, 'D': D} \n return M\n\n Mt = ft(theta, f, T)\n return Mt\n\n return ft_\n\n\[email protected]()\ndef Yt_mvar():\n \"\"\"\n Contain missing measurements\n \"\"\"\n Yt = np.zeros((4, 3, 1))\n Yt[0] = np.array([1, 2, 2.1]).reshape(-1, 1)\n Yt[1] = np.array([np.nan, 2.2, 3]).reshape(-1, 1)\n Yt[2] = np.array([np.nan, np.nan, np.nan]).reshape(-1, 1)\n Yt[3] = np.array([2, np.nan, 3.2]).reshape(-1, 1)\n return Yt\n\n\[email protected]()\ndef Xt_mvar():\n Xt = np.array([[[0.2]], [[0.3]], [[0.4]], [[0.1]]])\n return Xt\n\n\[email protected]()\ndef ft_rw_1():\n \"\"\"\n Random walk process with one measurements\n \"\"\"\n def ft_(theta, T):\n xi_1_0 = np.array([[0.2]])\n P_1_0 = np.array([[2]])\n def f(theta):\n phi_1 = 1\n sigma_Q = np.exp(theta[0])\n sigma_R = np.exp(theta[1])\n F = np.array([[phi_1]])\n Q = np.array([[sigma_Q]])\n R = np.array([[sigma_R]])\n H = np.array([[1]])\n B = np.array([[0.1]])\n M = {'F': F, 'Q': Q, 'H': H, 'R': R, 'B': B} \n return M\n Mt = ft(theta, f, T, xi_1_0=xi_1_0, P_1_0=P_1_0)\n return Mt\n return ft_\n\n\[email protected]()\ndef theta_rw():\n theta_ = [0.2, 0.1]\n return theta_\n\n\[email protected]()\ndef theta_ar2_mvar():\n theta = [0.2, 0.3, 1, 1, 2]\n return theta\n\n\[email protected]()\ndef ft_ar2_mvar():\n \"\"\"\n ft for ar2 process \n \"\"\"\n def ft_(theta, T):\n def f(theta):\n F = np.array([[theta[0], theta[1]], [1, 0]])\n B = np.array([[0.2], [0]])\n Q = np.array([[theta[2], 0], [0, 0]])\n H = np.array([[2, 0], [3, 0], [4, 1]])\n D = np.array([[0.1], [2], [3]])\n R = np.array([[4, 2, 1], \n [2, 5, 3],\n [1, 3, 6]])\n M = {'F': F, 'Q': Q, 'H': H, 'R': R, 'B': B, 'D': D} \n return M\n x_0 = np.array([[1]])\n Mt = ft(theta, f, T, x_0=x_0)\n return Mt\n\n return ft_\n\n\[email protected]()\ndef ft_ar2_mvar_kw():\n \"\"\"\n ft for ar2 process with special x_0 through kwargs\n \"\"\"\n def ft_(theta, T, **kwargs):\n def f(theta):\n F = np.array([[theta[0], theta[1]], [1, 0]])\n B = np.array([[0.2], [0]])\n Q = np.array([[theta[2], 0], [0, 0]])\n H = np.array([[2, 0], [3, 0], [4, 1]])\n D = np.array([[0.1], [2], [3]])\n R = np.array([[4, 2, 1], \n [2, 5, 3],\n [1, 3, 6]])\n M = {'F': F, 'Q': Q, 'H': H, 'R': R, 'B': B, 'D': D} \n return M\n x_0 = np.array([[1]])\n Mt = ft(theta, f, T, **kwargs)\n return Mt\n\n return ft_\n\n\[email protected]()\ndef Yt_ar2_mvar():\n Yt = np.zeros((4, 3, 1))\n Yt[0] = np.array([1, 2, 3]).reshape(-1, 1)\n Yt[1] = np.array([2, np.nan, 4]).reshape(-1, 1)\n Yt[2] = np.array([np.nan, np.nan, np.nan]).reshape(-1, 1)\n Yt[3] = np.array([np.nan, 2.5, 3.5]).reshape(-1, 1)\n return Yt\n\n\[email protected]()\ndef Xt_ar2_mvar():\n Xt = np.array([[[1]], [[2]], [[1.5]], [[0.8]]])\n return Xt\n\n\[email protected]()\ndef ft_rw_1_diffuse():\n \"\"\"\n Random walk process with one measurements and diffuse state\n \"\"\"\n def ft_(theta, T):\n def f(theta):\n phi_1 = 1\n sigma_Q = theta[0]\n sigma_R = theta[1]\n F = np.array([[phi_1]])\n Q = np.array([[sigma_Q]])\n R = np.array([[sigma_R]])\n H = np.array([[1]])\n M = {'F': F, 'Q': Q, 'H': H, 'R': R} \n return M\n Mt = ft(theta, f, T)\n return Mt\n return ft_\n\n\[email protected]()\ndef Yt_1d_missing():\n \"\"\"\n 1d Yt\n \"\"\"\n y = np.array([[[np.nan]], [[1]], [[2.5]]])\n return y\n\n\[email protected]()\ndef theta_ll_1d_diffuse():\n theta = [0.2, 0.3, 0.8]\n return theta\n\n\[email protected]()\ndef ft_ll_1d_diffuse():\n \"\"\"\n Local linear model with 1 measurements\n \"\"\"\n def ft_(theta, T):\n def f(theta):\n F = np.array([[1, 1], [0, 1]])\n Q = np.array([[theta[0], 0], [0, theta[1]]])\n R = np.array([[theta[2]]])\n H = np.array([[1, 0]])\n M = {'F': F, 'Q': Q, 'H': H, 'R': R} \n return M\n Mt = ft(theta, f, T)\n return Mt\n return ft_\n\n \[email protected]()\ndef Yt_1d_full():\n \"\"\"\n 1d Yt fully observed\n \"\"\"\n y = np.array([[[2]], [[1.3]], [[2.5]], [[3.1]]])\n return y\n\n\[email protected]()\ndef ft_ll_mvar_diffuse():\n \"\"\"\n Local linear model with 2 measurements\n \"\"\"\n def ft_(theta, T):\n def f(theta):\n F = np.array([[1, 1], [0, 1]])\n Q = np.array([[theta[0], 0], [0, theta[1]]])\n R = np.array([[theta[2], theta[3]], [theta[3], theta[4]]])\n H = np.array([[1, 0], [2, 0]])\n D = np.array([[2, 0], [1, 0]])\n M = {'F': F, 'Q': Q, 'H': H, 'R': R, 'D': D} \n return M\n Mt = ft(theta, f, T)\n return Mt\n return ft_\n\n\[email protected]()\ndef Yt_mvar_diffuse():\n \"\"\"\n Local linear model with complete yt, refer Chapter 5 of Koopman and Durbin (2012)\n \"\"\"\n y = np.zeros((4, 2, 1))\n y[0] = np.array([1, 2]).reshape(-1, 1)\n y[1] = np.array([2, np.nan]).reshape(-1, 1)\n y[2] = np.array([np.nan, 3.5]).reshape(-1, 1)\n y[3] = np.array([3, 5]).reshape(-1, 1)\n return y\n\n\[email protected]()\ndef theta_ll_mvar_diffuse():\n theta = [0.3, 0.8, 0.5, 0.4, 0.6]\n return theta\n\n\[email protected]()\ndef Yt_mvar_diffuse_smooth():\n \"\"\"\n Local linear model with complete yt, refer to Chapter 5 of Koopman and Durbin (2012)\n \"\"\"\n y = np.zeros((4, 2, 1))\n y[0] = np.array([1, 2]).reshape(-1, 1)\n y[1] = np.array([np.nan, np.nan]).reshape(-1, 1)\n y[2] = np.array([np.nan, 3.5]).reshape(-1, 1)\n y[3] = np.array([3, 5]).reshape(-1, 1)\n return y\n\n\[email protected]()\ndef Yt_mvar_diffuse_smooth_vec():\n \"\"\"\n Local linear model with complete yt, refer to Koopman (1997)\n \"\"\"\n y = np.zeros((3, 2, 1))\n y[0] = np.array([1, 2]).reshape(-1, 1)\n y[1] = np.array([2.4, 3.2]).reshape(-1, 1)\n y[2] = np.array([3, 5]).reshape(-1, 1)\n return y\n\n\[email protected]()\ndef Yt_mvar_diffuse_missing():\n \"\"\"\n Yt with missing measurements at t\n \"\"\"\n y = np.zeros((4, 2, 1))\n y[0] = np.array([np.nan, 2]).reshape(-1, 1)\n y[1] = np.array([np.nan, np.nan]).reshape(-1, 1)\n y[2] = np.array([2.5, np.nan]).reshape(-1, 1)\n y[3] = np.array([3, 5]).reshape(-1, 1)\n return y\n\n\[email protected]()\ndef ft_ll_mvar_1d():\n \"\"\"\n Create a 1d equivalence of mvar with missing measurements.\n Refer to ft_ll_mvar_diffuse().\n \"\"\"\n def ft_(theta, T):\n F = np.array([[1, 1], [0, 1]])\n Ft = build_tensor(F, T)\n Q = np.array([[theta[0], 0], [0, theta[1]]])\n Qt = build_tensor(Q, T)\n Rt = np.array([[[theta[4]]], [[1]], [[theta[2]]], [[1]]])\n Ht = np.array([[[2, 0]], \n [[1.5, 0]],\n [[1, 0]],\n [[4, 0]]])\n\n B = np.array([[0, 0]]).reshape(-1, 1) \n Bt = build_tensor(B, T)\n D = np.array([[0]])\n Dt = build_tensor(D, T)\n xi_1_0 = np.array([[0], [0]])\n P_1_0 = np.diag([np.nan, np.nan])\n\n Mt = {'Ft': Ft, 'Qt': Qt, 'Bt': Bt, 'Ht': Ht, 'Dt': Dt, \n 'Rt': Rt, 'xi_1_0': xi_1_0, 'P_1_0': P_1_0} \n return Mt\n return ft_\n\n\[email protected]()\ndef Yt_mvar_1d():\n y = np.zeros((4, 1, 1))\n y[0] = np.array([[2]])\n y[1] = np.array([[np.nan]])\n y[2] = np.array([[2.5]])\n y[3] = np.array([[7]])\n return y\n\[email protected]()\ndef ft_q():\n \"\"\"\n Test update q\n \"\"\"\n def ft_(theta, T):\n F = np.array([[1, 0, 0, 0, 0]] * 5)\n Ft = build_tensor(F, T)\n Q = np.eye(5)\n Qt = build_tensor(F, T)\n R = np.eye(2)\n Rt = build_tensor(R, T)\n H = np.array([[2, 0, 0, 0, 0], [1, 0, 0, 0, 0]])\n Ht = build_tensor(H, T)\n\n B = np.zeros([5, 1])\n Bt = build_tensor(B, T)\n D = np.zeros([2, 1])\n Dt = build_tensor(D, T)\n xi_1_0 = np.zeros([5, 1])\n P_1_0 = np.diag([np.nan] * 5)\n\n Mt = {'Ft': Ft, 'Qt': Qt, 'Bt': Bt, 'Ht': Ht, 'Dt': Dt, \n 'Rt': Rt, 'xi_1_0': xi_1_0, 'P_1_0': P_1_0} \n return Mt\n return ft_\n\n\[email protected]()\ndef Yt_q():\n y = np.array([[[2], [1.1]], [[2.2], [1.14]]])\n return y\n" ]
[ [ "numpy.testing.assert_array_equal", "numpy.array", "numpy.array_equal" ], [ "numpy.diag", "numpy.eye", "pandas.DataFrame", "numpy.ones", "numpy.exp", "numpy.array", "numpy.zeros" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [ "0.23", "0.21", "2.0", "1.4", "0.19", "1.1", "1.5", "1.2", "0.24", "0.20", "1.0", "0.25", "1.3" ], "scipy": [], "tensorflow": [] } ]
brechtmann/ray
[ "0c76ebd676f794847ea990aecced22b88717d09e" ]
[ "python/ray/utils.py" ]
[ "import binascii\nimport errno\nimport hashlib\nimport inspect\nimport logging\nimport numpy as np\nimport os\nimport six\nimport subprocess\nimport sys\nimport tempfile\nimport threading\nimport time\nimport uuid\n\nimport ray\nimport ray.gcs_utils\nimport ray.ray_constants as ray_constants\nimport psutil\n\nlogger = logging.getLogger(__name__)\n\n# Linux can bind child processes' lifetimes to that of their parents via prctl.\n# prctl support is detected dynamically once, and assumed thereafter.\nlinux_prctl = None\n\n# Windows can bind processes' lifetimes to that of kernel-level \"job objects\".\n# We keep a global job object to tie its lifetime to that of our own process.\nwin32_job = None\nwin32_AssignProcessToJobObject = None\n\n\ndef get_user_temp_dir():\n if sys.platform.startswith(\"darwin\") or sys.platform.startswith(\"linux\"):\n # Ideally we wouldn't need this fallback, but keep it for now for\n # for compatibility\n tempdir = os.path.join(os.sep, \"tmp\")\n else:\n tempdir = tempfile.gettempdir()\n return tempdir\n\n\ndef get_ray_temp_dir():\n return os.path.join(get_user_temp_dir(), \"ray\")\n\n\ndef _random_string():\n id_hash = hashlib.sha1()\n id_hash.update(uuid.uuid4().bytes)\n id_bytes = id_hash.digest()\n assert len(id_bytes) == ray_constants.ID_SIZE\n return id_bytes\n\n\ndef format_error_message(exception_message, task_exception=False):\n \"\"\"Improve the formatting of an exception thrown by a remote function.\n\n This method takes a traceback from an exception and makes it nicer by\n removing a few uninformative lines and adding some space to indent the\n remaining lines nicely.\n\n Args:\n exception_message (str): A message generated by traceback.format_exc().\n\n Returns:\n A string of the formatted exception message.\n \"\"\"\n lines = exception_message.split(\"\\n\")\n if task_exception:\n # For errors that occur inside of tasks, remove lines 1 and 2 which are\n # always the same, they just contain information about the worker code.\n lines = lines[0:1] + lines[3:]\n pass\n return \"\\n\".join(lines)\n\n\ndef push_error_to_driver(worker, error_type, message, job_id=None):\n \"\"\"Push an error message to the driver to be printed in the background.\n\n Args:\n worker: The worker to use.\n error_type (str): The type of the error.\n message (str): The message that will be printed in the background\n on the driver.\n job_id: The ID of the driver to push the error message to. If this\n is None, then the message will be pushed to all drivers.\n \"\"\"\n if job_id is None:\n job_id = ray.JobID.nil()\n assert isinstance(job_id, ray.JobID)\n worker.core_worker.push_error(job_id, error_type, message, time.time())\n\n\ndef push_error_to_driver_through_redis(redis_client,\n error_type,\n message,\n job_id=None):\n \"\"\"Push an error message to the driver to be printed in the background.\n\n Normally the push_error_to_driver function should be used. However, in some\n instances, the raylet client is not available, e.g., because the\n error happens in Python before the driver or worker has connected to the\n backend processes.\n\n Args:\n redis_client: The redis client to use.\n error_type (str): The type of the error.\n message (str): The message that will be printed in the background\n on the driver.\n job_id: The ID of the driver to push the error message to. If this\n is None, then the message will be pushed to all drivers.\n \"\"\"\n if job_id is None:\n job_id = ray.JobID.nil()\n assert isinstance(job_id, ray.JobID)\n # Do everything in Python and through the Python Redis client instead\n # of through the raylet.\n error_data = ray.gcs_utils.construct_error_message(job_id, error_type,\n message, time.time())\n redis_client.execute_command(\n \"RAY.TABLE_APPEND\", ray.gcs_utils.TablePrefix.Value(\"ERROR_INFO\"),\n ray.gcs_utils.TablePubsub.Value(\"ERROR_INFO_PUBSUB\"), job_id.binary(),\n error_data)\n\n\ndef is_cython(obj):\n \"\"\"Check if an object is a Cython function or method\"\"\"\n\n # TODO(suo): We could split these into two functions, one for Cython\n # functions and another for Cython methods.\n # TODO(suo): There doesn't appear to be a Cython function 'type' we can\n # check against via isinstance. Please correct me if I'm wrong.\n def check_cython(x):\n return type(x).__name__ == \"cython_function_or_method\"\n\n # Check if function or method, respectively\n return check_cython(obj) or \\\n (hasattr(obj, \"__func__\") and check_cython(obj.__func__))\n\n\ndef is_function_or_method(obj):\n \"\"\"Check if an object is a function or method.\n\n Args:\n obj: The Python object in question.\n\n Returns:\n True if the object is an function or method.\n \"\"\"\n return inspect.isfunction(obj) or inspect.ismethod(obj) or is_cython(obj)\n\n\ndef is_class_method(f):\n \"\"\"Returns whether the given method is a class_method.\"\"\"\n return hasattr(f, \"__self__\") and f.__self__ is not None\n\n\ndef is_static_method(cls, f_name):\n \"\"\"Returns whether the class has a static method with the given name.\n\n Args:\n cls: The Python class (i.e. object of type `type`) to\n search for the method in.\n f_name: The name of the method to look up in this class\n and check whether or not it is static.\n \"\"\"\n for cls in inspect.getmro(cls):\n if f_name in cls.__dict__:\n return isinstance(cls.__dict__[f_name], staticmethod)\n return False\n\n\ndef random_string():\n \"\"\"Generate a random string to use as an ID.\n\n Note that users may seed numpy, which could cause this function to generate\n duplicate IDs. Therefore, we need to seed numpy ourselves, but we can't\n interfere with the state of the user's random number generator, so we\n extract the state of the random number generator and reset it after we are\n done.\n\n TODO(rkn): If we want to later guarantee that these are generated in a\n deterministic manner, then we will need to make some changes here.\n\n Returns:\n A random byte string of length ray_constants.ID_SIZE.\n \"\"\"\n # Get the state of the numpy random number generator.\n numpy_state = np.random.get_state()\n # Try to use true randomness.\n np.random.seed(None)\n # Generate the random ID.\n random_id = np.random.bytes(ray_constants.ID_SIZE)\n # Reset the state of the numpy random number generator.\n np.random.set_state(numpy_state)\n return random_id\n\n\ndef decode(byte_str, allow_none=False):\n \"\"\"Make this unicode in Python 3, otherwise leave it as bytes.\n\n Args:\n byte_str: The byte string to decode.\n allow_none: If true, then we will allow byte_str to be None in which\n case we will return an empty string. TODO(rkn): Remove this flag.\n This is only here to simplify upgrading to flatbuffers 1.10.0.\n\n Returns:\n A byte string in Python 2 and a unicode string in Python 3.\n \"\"\"\n if byte_str is None and allow_none:\n return \"\"\n\n if not isinstance(byte_str, bytes):\n raise ValueError(\n \"The argument {} must be a bytes object.\".format(byte_str))\n if sys.version_info >= (3, 0):\n return byte_str.decode(\"ascii\")\n else:\n return byte_str\n\n\ndef ensure_str(s, encoding=\"utf-8\", errors=\"strict\"):\n \"\"\"Coerce *s* to `str`.\n\n To keep six with lower version, see Issue 4169, we copy this function\n from six == 1.12.0.\n\n TODO(yuhguo): remove this function when six >= 1.12.0.\n\n For Python 2:\n - `unicode` -> encoded to `str`\n - `str` -> `str`\n\n For Python 3:\n - `str` -> `str`\n - `bytes` -> decoded to `str`\n \"\"\"\n if six.PY3:\n text_type = str\n binary_type = bytes\n else:\n text_type = unicode # noqa: F821\n binary_type = str\n if not isinstance(s, (text_type, binary_type)):\n raise TypeError(\"not expecting type '%s'\" % type(s))\n if six.PY2 and isinstance(s, text_type):\n s = s.encode(encoding, errors)\n elif six.PY3 and isinstance(s, binary_type):\n s = s.decode(encoding, errors)\n return s\n\n\ndef binary_to_object_id(binary_object_id):\n return ray.ObjectID(binary_object_id)\n\n\ndef binary_to_task_id(binary_task_id):\n return ray.TaskID(binary_task_id)\n\n\ndef binary_to_hex(identifier):\n hex_identifier = binascii.hexlify(identifier)\n if sys.version_info >= (3, 0):\n hex_identifier = hex_identifier.decode()\n return hex_identifier\n\n\ndef hex_to_binary(hex_identifier):\n return binascii.unhexlify(hex_identifier)\n\n\n# TODO(qwang): Remove these hepler functions\n# once we separate `WorkerID` from `UniqueID`.\ndef compute_job_id_from_driver(driver_id):\n assert isinstance(driver_id, ray.WorkerID)\n return ray.JobID(driver_id.binary()[0:ray.JobID.size()])\n\n\ndef compute_driver_id_from_job(job_id):\n assert isinstance(job_id, ray.JobID)\n rest_length = ray_constants.ID_SIZE - job_id.size()\n driver_id_str = job_id.binary() + (rest_length * b\"\\xff\")\n return ray.WorkerID(driver_id_str)\n\n\ndef get_cuda_visible_devices():\n \"\"\"Get the device IDs in the CUDA_VISIBLE_DEVICES environment variable.\n\n Returns:\n if CUDA_VISIBLE_DEVICES is set, this returns a list of integers with\n the IDs of the GPUs. If it is not set or is set to NoDevFiles,\n this returns None.\n \"\"\"\n gpu_ids_str = os.environ.get(\"CUDA_VISIBLE_DEVICES\", None)\n\n if gpu_ids_str is None:\n return None\n\n if gpu_ids_str == \"\":\n return []\n\n if gpu_ids_str == \"NoDevFiles\":\n return []\n\n return [int(i) for i in gpu_ids_str.split(\",\")]\n\n\nlast_set_gpu_ids = None\n\n\ndef set_cuda_visible_devices(gpu_ids):\n \"\"\"Set the CUDA_VISIBLE_DEVICES environment variable.\n\n Args:\n gpu_ids: This is a list of integers representing GPU IDs.\n \"\"\"\n\n global last_set_gpu_ids\n if last_set_gpu_ids == gpu_ids:\n return # optimization: already set\n\n os.environ[\"CUDA_VISIBLE_DEVICES\"] = \",\".join([str(i) for i in gpu_ids])\n last_set_gpu_ids = gpu_ids\n\n\ndef resources_from_resource_arguments(\n default_num_cpus, default_num_gpus, default_memory,\n default_object_store_memory, default_resources, runtime_num_cpus,\n runtime_num_gpus, runtime_memory, runtime_object_store_memory,\n runtime_resources):\n \"\"\"Determine a task's resource requirements.\n\n Args:\n default_num_cpus: The default number of CPUs required by this function\n or actor method.\n default_num_gpus: The default number of GPUs required by this function\n or actor method.\n default_memory: The default heap memory required by this function\n or actor method.\n default_object_store_memory: The default object store memory required\n by this function or actor method.\n default_resources: The default custom resources required by this\n function or actor method.\n runtime_num_cpus: The number of CPUs requested when the task was\n invoked.\n runtime_num_gpus: The number of GPUs requested when the task was\n invoked.\n runtime_memory: The heap memory requested when the task was invoked.\n runtime_object_store_memory: The object store memory requested when\n the task was invoked.\n runtime_resources: The custom resources requested when the task was\n invoked.\n\n Returns:\n A dictionary of the resource requirements for the task.\n \"\"\"\n if runtime_resources is not None:\n resources = runtime_resources.copy()\n elif default_resources is not None:\n resources = default_resources.copy()\n else:\n resources = {}\n\n if \"CPU\" in resources or \"GPU\" in resources:\n raise ValueError(\"The resources dictionary must not \"\n \"contain the key 'CPU' or 'GPU'\")\n elif \"memory\" in resources or \"object_store_memory\" in resources:\n raise ValueError(\"The resources dictionary must not \"\n \"contain the key 'memory' or 'object_store_memory'\")\n\n assert default_num_cpus is not None\n resources[\"CPU\"] = (default_num_cpus\n if runtime_num_cpus is None else runtime_num_cpus)\n\n if runtime_num_gpus is not None:\n resources[\"GPU\"] = runtime_num_gpus\n elif default_num_gpus is not None:\n resources[\"GPU\"] = default_num_gpus\n\n memory = default_memory or runtime_memory\n object_store_memory = (default_object_store_memory\n or runtime_object_store_memory)\n if memory is not None:\n resources[\"memory\"] = ray_constants.to_memory_units(\n memory, round_up=True)\n if object_store_memory is not None:\n resources[\"object_store_memory\"] = ray_constants.to_memory_units(\n object_store_memory, round_up=True)\n\n return resources\n\n\n_default_handler = None\n\n\ndef setup_logger(logging_level, logging_format):\n \"\"\"Setup default logging for ray.\"\"\"\n logger = logging.getLogger(\"ray\")\n if type(logging_level) is str:\n logging_level = logging.getLevelName(logging_level.upper())\n logger.setLevel(logging_level)\n global _default_handler\n if _default_handler is None:\n _default_handler = logging.StreamHandler()\n logger.addHandler(_default_handler)\n _default_handler.setFormatter(logging.Formatter(logging_format))\n logger.propagate = False\n\n\ndef get_system_memory():\n \"\"\"Return the total amount of system memory in bytes.\n\n Returns:\n The total amount of system memory in bytes.\n \"\"\"\n # Try to accurately figure out the memory limit if we are in a docker\n # container. Note that this file is not specific to Docker and its value is\n # often much larger than the actual amount of memory.\n docker_limit = None\n memory_limit_filename = \"/sys/fs/cgroup/memory/memory.limit_in_bytes\"\n if os.path.exists(memory_limit_filename):\n with open(memory_limit_filename, \"r\") as f:\n docker_limit = int(f.read())\n\n # Use psutil if it is available.\n psutil_memory_in_bytes = psutil.virtual_memory().total\n\n if docker_limit is not None:\n # We take the min because the cgroup limit is very large if we aren't\n # in Docker.\n return min(docker_limit, psutil_memory_in_bytes)\n\n return psutil_memory_in_bytes\n\n\ndef get_used_memory():\n \"\"\"Return the currently used system memory in bytes\n\n Returns:\n The total amount of used memory\n \"\"\"\n # Try to accurately figure out the memory usage if we are in a docker\n # container.\n docker_usage = None\n memory_usage_filename = \"/sys/fs/cgroup/memory/memory.usage_in_bytes\"\n if os.path.exists(memory_usage_filename):\n with open(memory_usage_filename, \"r\") as f:\n docker_usage = int(f.read())\n\n # Use psutil if it is available.\n psutil_memory_in_bytes = psutil.virtual_memory().used\n\n if docker_usage is not None:\n # We take the min because the cgroup limit is very large if we aren't\n # in Docker.\n return min(docker_usage, psutil_memory_in_bytes)\n\n return psutil_memory_in_bytes\n\n\ndef estimate_available_memory():\n \"\"\"Return the currently available amount of system memory in bytes.\n\n Returns:\n The total amount of available memory in bytes. Based on the used\n and total memory.\n\n \"\"\"\n return get_system_memory() - get_used_memory()\n\n\ndef get_shared_memory_bytes():\n \"\"\"Get the size of the shared memory file system.\n\n Returns:\n The size of the shared memory file system in bytes.\n \"\"\"\n # Make sure this is only called on Linux.\n assert sys.platform == \"linux\" or sys.platform == \"linux2\"\n\n shm_fd = os.open(\"/dev/shm\", os.O_RDONLY)\n try:\n shm_fs_stats = os.fstatvfs(shm_fd)\n # The value shm_fs_stats.f_bsize is the block size and the\n # value shm_fs_stats.f_bavail is the number of available\n # blocks.\n shm_avail = shm_fs_stats.f_bsize * shm_fs_stats.f_bavail\n finally:\n os.close(shm_fd)\n\n return shm_avail\n\n\ndef check_oversized_pickle(pickled, name, obj_type, worker):\n \"\"\"Send a warning message if the pickled object is too large.\n\n Args:\n pickled: the pickled object.\n name: name of the pickled object.\n obj_type: type of the pickled object, can be 'function',\n 'remote function', 'actor', or 'object'.\n worker: the worker used to send warning message.\n \"\"\"\n length = len(pickled)\n if length <= ray_constants.PICKLE_OBJECT_WARNING_SIZE:\n return\n warning_message = (\n \"Warning: The {} {} has size {} when pickled. \"\n \"It will be stored in Redis, which could cause memory issues. \"\n \"This may mean that its definition uses a large array or other object.\"\n ).format(obj_type, name, length)\n push_error_to_driver(\n worker,\n ray_constants.PICKLING_LARGE_OBJECT_PUSH_ERROR,\n warning_message,\n job_id=worker.current_job_id)\n\n\ndef is_main_thread():\n return threading.current_thread().getName() == \"MainThread\"\n\n\ndef detect_fate_sharing_support_win32():\n global win32_job, win32_AssignProcessToJobObject\n if win32_job is None and sys.platform == \"win32\":\n import ctypes\n try:\n from ctypes.wintypes import BOOL, DWORD, HANDLE, LPVOID, LPCWSTR\n kernel32 = ctypes.WinDLL(\"kernel32\")\n kernel32.CreateJobObjectW.argtypes = (LPVOID, LPCWSTR)\n kernel32.CreateJobObjectW.restype = HANDLE\n sijo_argtypes = (HANDLE, ctypes.c_int, LPVOID, DWORD)\n kernel32.SetInformationJobObject.argtypes = sijo_argtypes\n kernel32.SetInformationJobObject.restype = BOOL\n kernel32.AssignProcessToJobObject.argtypes = (HANDLE, HANDLE)\n kernel32.AssignProcessToJobObject.restype = BOOL\n except (AttributeError, TypeError, ImportError):\n kernel32 = None\n job = kernel32.CreateJobObjectW(None, None) if kernel32 else None\n job = subprocess.Handle(job) if job else job\n if job:\n from ctypes.wintypes import DWORD, LARGE_INTEGER, ULARGE_INTEGER\n\n class JOBOBJECT_BASIC_LIMIT_INFORMATION(ctypes.Structure):\n _fields_ = [\n (\"PerProcessUserTimeLimit\", LARGE_INTEGER),\n (\"PerJobUserTimeLimit\", LARGE_INTEGER),\n (\"LimitFlags\", DWORD),\n (\"MinimumWorkingSetSize\", ctypes.c_size_t),\n (\"MaximumWorkingSetSize\", ctypes.c_size_t),\n (\"ActiveProcessLimit\", DWORD),\n (\"Affinity\", ctypes.c_size_t),\n (\"PriorityClass\", DWORD),\n (\"SchedulingClass\", DWORD),\n ]\n\n class IO_COUNTERS(ctypes.Structure):\n _fields_ = [\n (\"ReadOperationCount\", ULARGE_INTEGER),\n (\"WriteOperationCount\", ULARGE_INTEGER),\n (\"OtherOperationCount\", ULARGE_INTEGER),\n (\"ReadTransferCount\", ULARGE_INTEGER),\n (\"WriteTransferCount\", ULARGE_INTEGER),\n (\"OtherTransferCount\", ULARGE_INTEGER),\n ]\n\n class JOBOBJECT_EXTENDED_LIMIT_INFORMATION(ctypes.Structure):\n _fields_ = [\n (\"BasicLimitInformation\",\n JOBOBJECT_BASIC_LIMIT_INFORMATION),\n (\"IoInfo\", IO_COUNTERS),\n (\"ProcessMemoryLimit\", ctypes.c_size_t),\n (\"JobMemoryLimit\", ctypes.c_size_t),\n (\"PeakProcessMemoryUsed\", ctypes.c_size_t),\n (\"PeakJobMemoryUsed\", ctypes.c_size_t),\n ]\n\n # Defined in <WinNT.h>; also available here:\n # https://docs.microsoft.com/en-us/windows/win32/api/jobapi2/nf-jobapi2-setinformationjobobject\n JobObjectExtendedLimitInformation = 9\n JOB_OBJECT_LIMIT_BREAKAWAY_OK = 0x00000800\n JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE = 0x00002000\n buf = JOBOBJECT_EXTENDED_LIMIT_INFORMATION()\n buf.BasicLimitInformation.LimitFlags = (\n JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE\n | JOB_OBJECT_LIMIT_BREAKAWAY_OK)\n infoclass = JobObjectExtendedLimitInformation\n if not kernel32.SetInformationJobObject(\n job, infoclass, ctypes.byref(buf), ctypes.sizeof(buf)):\n job = None\n win32_AssignProcessToJobObject = (kernel32.AssignProcessToJobObject\n if kernel32 is not None else False)\n win32_job = job if job else False\n return bool(win32_job)\n\n\ndef detect_fate_sharing_support_linux():\n global linux_prctl\n if linux_prctl is None and sys.platform.startswith(\"linux\"):\n try:\n from ctypes import c_int, c_ulong, CDLL\n prctl = CDLL(None).prctl\n prctl.restype = c_int\n prctl.argtypes = [c_int, c_ulong, c_ulong, c_ulong, c_ulong]\n except (AttributeError, TypeError):\n prctl = None\n linux_prctl = prctl if prctl else False\n return bool(linux_prctl)\n\n\ndef detect_fate_sharing_support():\n result = None\n if sys.platform == \"win32\":\n result = detect_fate_sharing_support_win32()\n elif sys.platform.startswith(\"linux\"):\n result = detect_fate_sharing_support_linux()\n return result\n\n\ndef set_kill_on_parent_death_linux():\n \"\"\"Ensures this process dies if its parent dies (fate-sharing).\n\n Linux-only. Must be called in preexec_fn (i.e. by the child).\n \"\"\"\n if detect_fate_sharing_support_linux():\n import signal\n PR_SET_PDEATHSIG = 1\n if linux_prctl(PR_SET_PDEATHSIG, signal.SIGKILL, 0, 0, 0) != 0:\n import ctypes\n raise OSError(ctypes.get_errno(), \"prctl(PR_SET_PDEATHSIG) failed\")\n else:\n assert False, \"PR_SET_PDEATHSIG used despite being unavailable\"\n\n\ndef set_kill_child_on_death_win32(child_proc):\n \"\"\"Ensures the child process dies if this process dies (fate-sharing).\n\n Windows-only. Must be called by the parent, after spawning the child.\n\n Args:\n child_proc: The subprocess.Popen or subprocess.Handle object.\n \"\"\"\n\n if isinstance(child_proc, subprocess.Popen):\n child_proc = child_proc._handle\n assert isinstance(child_proc, subprocess.Handle)\n\n if detect_fate_sharing_support_win32():\n if not win32_AssignProcessToJobObject(win32_job, int(child_proc)):\n import ctypes\n raise OSError(ctypes.get_last_error(),\n \"AssignProcessToJobObject() failed\")\n else:\n assert False, \"AssignProcessToJobObject used despite being unavailable\"\n\n\ndef try_make_directory_shared(directory_path):\n try:\n os.chmod(directory_path, 0o0777)\n except OSError as e:\n # Silently suppress the PermissionError that is thrown by the chmod.\n # This is done because the user attempting to change the permissions\n # on a directory may not own it. The chmod is attempted whether the\n # directory is new or not to avoid race conditions.\n # ray-project/ray/#3591\n if e.errno in [errno.EACCES, errno.EPERM]:\n pass\n else:\n raise\n\n\ndef try_to_create_directory(directory_path):\n \"\"\"Attempt to create a directory that is globally readable/writable.\n\n Args:\n directory_path: The path of the directory to create.\n \"\"\"\n directory_path = os.path.expanduser(directory_path)\n os.makedirs(directory_path, exist_ok=True)\n # Change the log directory permissions so others can use it. This is\n # important when multiple people are using the same machine.\n try_make_directory_shared(directory_path)\n\n\ndef try_to_symlink(symlink_path, target_path):\n \"\"\"Attempt to create a symlink.\n\n If the symlink path exists and isn't a symlink, the symlink will not be\n created. If a symlink exists in the path, it will be attempted to be\n removed and replaced.\n\n Args:\n symlink_path: The path at which to create the symlink.\n target_path: The path the symlink should point to.\n \"\"\"\n symlink_path = os.path.expanduser(symlink_path)\n target_path = os.path.expanduser(target_path)\n\n if os.path.exists(symlink_path):\n if os.path.islink(symlink_path):\n # Try to remove existing symlink.\n try:\n os.remove(symlink_path)\n except OSError:\n return\n else:\n # There's an existing non-symlink file, don't overwrite it.\n return\n\n try:\n os.symlink(target_path, symlink_path)\n except OSError:\n return\n" ]
[ [ "numpy.random.bytes", "numpy.random.get_state", "numpy.random.set_state", "numpy.random.seed" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
atbolsh/BNN_alternate_SOTA
[ "691fed93cf8b6911ec4d9dcd212f869dd5c9c7b9" ]
[ "remadeQuicknet.py" ]
[ "from typing import Optional, Sequence\n\n# The point of this one is to remove ALL the batchnorms.\n\n\nimport larq as lq\nimport numpy as np\nimport tensorflow as tf\nfrom zookeeper import Field, factory\n\nfrom larq_zoo.core import utils\nfrom larq_zoo.core.model_factory import ModelFactory\n\nfrom customRenorm import ReluNormalRenorm, MaxpoolRenorm#, BlurpoolRenorm\n\nfrom tensorflow.keras import initializers\n\n@factory\nclass RemadeQuickNetFactory(ModelFactory):\n name = \"quicknet\"\n section_blocks: Sequence[int] = Field((4, 4, 4, 4))\n section_filters: Sequence[int] = Field((64, 128, 256, 512))\n\n @property\n def imagenet_weights_path(self):\n return utils.download_pretrained_model(\n model=\"quicknet\",\n version=\"v1.0\",\n file=\"quicknet_weights.h5\",\n file_hash=\"8aba9e4e5f8d342faef04a0b2ae8e562da57dbb7d15162e8b3e091c951ba756c\",# Not correct filepath; from original QuickNet\n )\n\n @property\n def imagenet_no_top_weights_path(self):\n return utils.download_pretrained_model(\n model=\"quicknet\",\n version=\"v1.0\",\n file=\"quicknet_weights_notop.h5\",\n file_hash=\"204414e438373f14f6056a1c098249f505a87dd238e18d3a47a9bd8b66227881\",# Not correct filepath; from original QuickNet\n )\n\n @property\n def input_quantizer(self):\n return lq.quantizers.SteSign(clip_value=1.25)\n\n @property\n def kernel_quantizer(self):\n return lq.quantizers.SteSign(clip_value=1.25)\n\n @property\n def kernel_constraint(self):\n return lq.constraints.WeightClip(clip_value=1.25)\n\n def __post_configure__(self):\n assert len(self.section_blocks) == len(self.section_filters)\n\n def stem_module(self, filters: int, x: tf.Tensor) -> tf.Tensor:\n \"\"\"Start of network.\"\"\"\n assert filters % 4 == 0\n # mu = 0, sigma = 1, if the preprocessor did its job\n x = lq.layers.QuantConv2D(\n filters // 4,\n (3, 3),\n kernel_initializer=initializers.RandomNormal(stddev=(1/np.sqrt(27))), # 27 = fan_in for 3-channel image and 3x3 convolutions\n padding=\"same\",\n strides=2,\n use_bias=False,\n )(x)\n # mu = 0, sigma = 1.0, roughly normal\n x = tf.keras.layers.Activation(\"relu\")(x)\n # Now, we need a correction for the relu \n x = ReluNormalRenorm(N = 1, origSig = 1.0)(x)\n # mu = 0, sigma = 1, NOT normal\n x = lq.layers.QuantDepthwiseConv2D(\n (3, 3),\n depthwise_initializer=initializers.RandomNormal(stddev=(1.0/3)), # 9 = fan_in for 3x3 depthwise convolution, sqrt(9) = 3\n padding=\"same\",\n strides=2,\n use_bias=False,\n )(x) \n # mu = 0, sigma = 1.0, roughly normal\n x = lq.layers.QuantConv2D(\n filters,\n 1,\n kernel_initializer=initializers.RandomNormal(stddev=(1/(np.sqrt(filters // 4)))), # It's a 1x1 convolution, fan_in = input_channels = filters // 4\n use_bias=False,\n )(x)\n # mu = 0, sigma = 1.0, roughly normal\n return x # mu = 0, sigma = 1\n\n def residual_block(self, x: tf.Tensor) -> tf.Tensor:\n \"\"\"Standard residual block, without strides or filter changes.\"\"\"\n # mu = 0, sig = origSig\n residual = x\n x = lq.layers.QuantConv2D(\n int(x.shape[-1]),\n (3, 3),\n activation=\"relu\",\n input_quantizer=self.input_quantizer,\n kernel_constraint=self.kernel_constraint,\n kernel_quantizer=self.kernel_quantizer,\n kernel_initializer=\"glorot_normal\",\n padding=\"same\",\n pad_values=1.0,\n use_bias=False,\n )(x)\n x = ReluNormalRenorm(N = 3*3*int(x.shape[-1]))(x)\n # mu = 0, sigma = 1, NOT normal\n return x + residual # mu = 0, sig = sqrt(1 + origSig**2). At the end of 3 blocks, its sqrt(4) = 2.0. NOT normal\n\n def transition_block(\n self,\n x: tf.Tensor,\n filters: int,\n strides: int,\n prev_blocks: int,\n ) -> tf.Tensor:\n \"\"\"Pointwise transition block.\"\"\"\n # Input is after 3 residual blocks, so mu = 0, sig = np.sqrt(prev_blocks). NOT normal.\n x = lq.layers.QuantDepthwiseConv2D(\n (3, 3),\n depthwise_initializer=initializers.RandomNormal(stddev=(1.0/(3*np.sqrt(prev_blocks + 1)))), # fan_in for 3x3 depthwiseConv is 9, 9^0.5 = 3. Divide out initial sigma\n padding=\"same\",\n strides=2,\n use_bias=False,\n )(x)\n # mu = 0, sig = 1, roughly normal. Must be normal for MaxpoolRenorm to work correctly.\n x = tf.keras.layers.MaxPool2D(pool_size=strides, strides=strides)(x)\n x = MaxpoolRenorm(N = 1, M = strides*strides)(x) # N is always 1 for well-initialized full-precision layers.\n # mu = 0, sig = 1, NOT normal\n x = lq.layers.QuantConv2D(\n filters,\n (1, 1),\n kernel_initializer=initializers.RandomNormal(stddev=(1/np.sqrt(x.shape[-1]))),\n use_bias=False,\n )(x)\n # Both initialized correctly, should have mu = 0, sig = 1, roughly normal.\n return x\n\n def build(self) -> tf.keras.models.Model:\n x = self.stem_module(self.section_filters[0], self.image_input)\n prev_blocks = 0\n for block, (layers, filters) in enumerate(\n zip(self.section_blocks, self.section_filters)\n ):\n for layer in range(layers):\n if filters != x.shape[-1]:\n x = self.transition_block(x, filters, strides=2, prev_blocks=prev_blocks)\n prev_blocks = 0\n x = self.residual_block(x)\n prev_blocks += 1\n\n if self.include_top:\n x = tf.keras.layers.Activation(\"relu\")(x)\n x = utils.global_pool(x)\n x = lq.layers.QuantDense(\n self.num_classes,\n kernel_initializer=\"glorot_normal\",\n )(x)\n x = tf.keras.layers.Activation(\"softmax\", dtype=\"float32\")(x)\n\n model = tf.keras.Model(inputs=self.image_input, outputs=x, name=self.name)\n\n # Load weights.\n if self.weights == \"imagenet\":\n weights_path = (\n self.imagenet_weights_path\n if self.include_top\n else self.imagenet_no_top_weights_path\n )\n model.load_weights(weights_path)\n elif self.weights is not None:\n model.load_weights(self.weights)\n return model\n\n\n@factory\nclass RemadeQuickNetSmallFactory(RemadeQuickNetFactory):\n name = \"quicknet_small\"\n section_filters = Field((32, 64, 256, 512))\n\n @property\n def imagenet_weights_path(self):\n return utils.download_pretrained_model(\n model=\"quicknet\",\n version=\"v1.0\",\n file=\"quicknet_small_weights.h5\",\n file_hash=\"1ac3b07df7f5a911dd0b49febb2486428ddf1ca130297c403815dfae5a1c71a2\",# Not correct filepath; from original QuickNet\n )\n\n @property\n def imagenet_no_top_weights_path(self):\n return utils.download_pretrained_model(\n model=\"quicknet\",\n version=\"v1.0\",\n file=\"quicknet_small_weights_notop.h5\",\n file_hash=\"be8ba657155846be355c5580d1ea56eaf8282616de065ffc39257202f9f164ea\",# Not correct filepath; from original QuickNet\n )\n\n\n@factory\nclass RemadeQuickNetLargeFactory(RemadeQuickNetFactory):\n name = \"quicknet_large\"\n section_blocks = Field((6, 8, 12, 6))\n\n @property\n def imagenet_weights_path(self):\n return utils.download_pretrained_model(\n model=\"quicknet\",\n version=\"v1.0\",\n file=\"quicknet_large_weights.h5\",\n file_hash=\"c5158e8a59147b31370becd937825f4db8a5cdf308314874f678f596629be45c\",# Not correct filepath; from original QuickNet\n )\n\n @property\n def imagenet_no_top_weights_path(self):\n return utils.download_pretrained_model(\n model=\"quicknet\",\n version=\"v1.0\",\n file=\"quicknet_large_weights_notop.h5\",\n file_hash=\"adcf154a2a8007e81bd6af77c035ffbf54cd6413b89a0ba294e23e76a82a1b78\",# Not correct filepath; from original QuickNet\n )\n\n\ndef RemadeQuickNet(\n *, # Keyword arguments only\n input_shape: Optional[Sequence[Optional[int]]] = None,\n input_tensor: Optional[utils.TensorType] = None,\n weights: Optional[str] = \"imagenet\",\n include_top: bool = True,\n num_classes: int = 1000,\n) -> tf.keras.models.Model:\n \"\"\"Instantiates the RemadeQuickNet architecture.\n Optionally loads weights pre-trained on ImageNet.\n ```netron\n quicknet-v1.0/quicknet.json\n ```\n ```summary\n sota.RemadeQuickNet\n ```\n ```plot-altair\n /plots/quicknet.vg.json\n ```\n # ImageNet Metrics\n | Top-1 Accuracy | Top-5 Accuracy | Parameters | Memory |\n | -------------- | -------------- | ---------- | ------- |\n | 63.3 % | 84.6 % | 13 234 088 | 4.17 MB |\n # Arguments\n input_shape: Optional shape tuple, to be specified if you would like to use a\n model with an input image resolution that is not (224, 224, 3).\n It should have exactly 3 inputs channels.\n input_tensor: optional Keras tensor (i.e. output of `layers.Input()`) to use as\n image input for the model.\n weights: one of `None` (random initialization), \"imagenet\" (pre-training on\n ImageNet), or the path to the weights file to be loaded.\n include_top: whether to include the fully-connected layer at the top of the\n network.\n num_classes: optional number of classes to classify images into, only to be\n specified if `include_top` is True, and if no `weights` argument is\n specified.\n # Returns\n A Keras model instance.\n # Raises\n ValueError: in case of invalid argument for `weights`, or invalid input shape.\n \"\"\"\n return RemadeQuickNetFactory(\n input_shape=input_shape,\n input_tensor=input_tensor,\n weights=weights,\n include_top=include_top,\n num_classes=num_classes,\n ).build()\n\n\ndef RemadeQuickNetLarge(\n *, # Keyword arguments only\n input_shape: Optional[Sequence[Optional[int]]] = None,\n input_tensor: Optional[utils.TensorType] = None,\n weights: Optional[str] = \"imagenet\",\n include_top: bool = True,\n num_classes: int = 1000,\n) -> tf.keras.models.Model:\n \"\"\"Instantiates the RemadeQuickNetLarge architecture.\n Optionally loads weights pre-trained on ImageNet.\n ```netron\n quicknet-v1.0/quicknet_large.json\n ```\n ```summary\n sota.RemadeQuickNetLarge\n ```\n ```plot-altair\n /plots/quicknet_large.vg.json\n ```\n # ImageNet Metrics\n | Top-1 Accuracy | Top-5 Accuracy | Parameters | Memory |\n | -------------- | -------------- | ---------- | ------- |\n | 66.9 % | 87.0 % | 23 342 248 | 5.40 MB |\n # Arguments\n input_shape: Optional shape tuple, to be specified if you would like to use a\n model with an input image resolution that is not (224, 224, 3).\n It should have exactly 3 inputs channels.\n input_tensor: optional Keras tensor (i.e. output of `layers.Input()`) to use as\n image input for the model.\n weights: one of `None` (random initialization), \"imagenet\" (pre-training on\n ImageNet), or the path to the weights file to be loaded.\n include_top: whether to include the fully-connected layer at the top of the\n network.\n num_classes: optional number of classes to classify images into, only to be\n specified if `include_top` is True, and if no `weights` argument is\n specified.\n # Returns\n A Keras model instance.\n # Raises\n ValueError: in case of invalid argument for `weights`, or invalid input shape.\n \"\"\"\n return RemadeQuickNetLargeFactory(\n input_shape=input_shape,\n input_tensor=input_tensor,\n weights=weights,\n include_top=include_top,\n num_classes=num_classes,\n ).build()\n\n\ndef RemadeQuickNetSmall(\n *, # Keyword arguments only\n input_shape: Optional[Sequence[Optional[int]]] = None,\n input_tensor: Optional[utils.TensorType] = None,\n weights: Optional[str] = \"imagenet\",\n include_top: bool = True,\n num_classes: int = 1000,\n) -> tf.keras.models.Model:\n \"\"\"Instantiates the RemadeQuickNetSmall architecture.\n Optionally loads weights pre-trained on ImageNet.\n ```netron\n quicknet-v1.0/quicknet_small.json\n ```\n ```summary\n sota.RemadeQuickNetSmall\n ```\n ```plot-altair\n /plots/quicknet_small.vg.json\n ```\n # ImageNet Metrics\n | Top-1 Accuracy | Top-5 Accuracy | Parameters | Memory |\n | -------------- | -------------- | ---------- | ------- |\n | 59.4 % | 81.8 % | 12 655 688 | 4.00 MB |\n # Arguments\n input_shape: Optional shape tuple, to be specified if you would like to use a\n model with an input image resolution that is not (224, 224, 3).\n It should have exactly 3 inputs channels.\n input_tensor: optional Keras tensor (i.e. output of `layers.Input()`) to use as\n image input for the model.\n weights: one of `None` (random initialization), \"imagenet\" (pre-training on\n ImageNet), or the path to the weights file to be loaded.\n include_top: whether to include the fully-connected layer at the top of the\n network.\n num_classes: optional number of classes to classify images into, only to be\n specified if `include_top` is True, and if no `weights` argument is\n specified.\n # Returns\n A Keras model instance.\n # Raises\n ValueError: in case of invalid argument for `weights`, or invalid input shape.\n \"\"\"\n return RemadeQuickNetSmallFactory(\n input_shape=input_shape,\n input_tensor=input_tensor,\n weights=weights,\n include_top=include_top,\n num_classes=num_classes,\n ).build()\n\n" ]
[ [ "tensorflow.keras.layers.Activation", "numpy.sqrt", "tensorflow.keras.layers.MaxPool2D", "tensorflow.keras.Model", "tensorflow.keras.initializers.RandomNormal" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "2.7", "2.6", "2.4", "2.3", "2.5", "2.2" ] } ]
matchRos/simulation_multirobots
[ "286c5add84d521ad371b2c8961dea872c34e7da2" ]
[ "src/simu/scripts/task_space_control.py" ]
[ "#!/usr/bin/env python3\n\n# /***************************************************************************\n\n# \n# @package: panda_siimulator_examples\n# @metapackage: panda_simulator\n# @author: Saif Sidhik <[email protected]>\n# \n\n# **************************************************************************/\n\n# /***************************************************************************\n# Copyright (c) 2019-2021, Saif Sidhik\n \n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n\n# http://www.apache.org/licenses/LICENSE-2.0\n\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# **************************************************************************/\n\n\"\"\"\n This is a demo showing task-space control on the \n simulator robot using the ROS topics and messages directly \n from panda_simulator. The task-space force for the desired\n pose is computed using a simple PD law, and the corresponding\n joint torques are computed and sent to the robot. \n \n By using this file you can set a equilibrium pose by using interactive marker. You can also set the target \n By publishing the topic \"panda_simulator/equili_pose\" .\n\n\"\"\"\n\nimport copy\nimport rospy\nimport threading\nimport quaternion\nimport numpy as np\nfrom geometry_msgs.msg import Point, TransformStamped,PoseStamped\nfrom visualization_msgs.msg import *\nfrom interactive_markers.interactive_marker_server import *\nfrom franka_core_msgs.msg import EndPointState, JointCommand, RobotState\n\n# -- add to pythonpath for finding rviz_markers.py \nimport sys, os\nsys.path.append(os.path.dirname(os.path.abspath(__file__)))\n# -------------------------------------------------\n\nfrom multi_rviz_markers import RvizMarkers\n\n# --------- Modify as required ------------\n# Task-space controller parameters\n# stiffness gains\nP_pos = 50\nP_ori = 0\n# damping gains\nD_pos = 1\nD_ori = 0\n# -----------------------------------------\npublish_rate = 100\n\nJACOBIAN = None\nCARTESIAN_POSE = None\nCARTESIAN_VEL = None\n\ndestination_marker = RvizMarkers()\n\n\ndef _on_robot_state(msg):\n \"\"\"\n Callback function for updating jacobian and EE velocity from robot state\n \"\"\"\n global JACOBIAN, CARTESIAN_VEL\n JACOBIAN = np.asarray(msg.O_Jac_EE).reshape(6,7,order = 'F')\n CARTESIAN_VEL = {\n 'linear': np.asarray([msg.O_dP_EE[0], msg.O_dP_EE[1], msg.O_dP_EE[2]]),\n 'angular': np.asarray([msg.O_dP_EE[3], msg.O_dP_EE[4], msg.O_dP_EE[5]]) }\n\ndef _on_endpoint_state(msg):\n \"\"\"\n Callback function to get current end-point state\n \"\"\"\n # pose message received is a vectorised column major transformation matrix\n global CARTESIAN_POSE\n cart_pose_trans_mat = np.asarray(msg.O_T_EE).reshape(4,4,order='F')\n\n CARTESIAN_POSE = {\n 'position': cart_pose_trans_mat[:3,3],\n 'orientation': quaternion.from_rotation_matrix(cart_pose_trans_mat[:3,:3]) }\n\ndef quatdiff_in_euler(quat_curr, quat_des):\n \"\"\"\n Compute difference between quaternions and return \n Euler angles as difference\n \"\"\"\n curr_mat = quaternion.as_rotation_matrix(quat_curr)\n des_mat = quaternion.as_rotation_matrix(quat_des)\n rel_mat = des_mat.T.dot(curr_mat)\n rel_quat = quaternion.from_rotation_matrix(rel_mat)\n vec = quaternion.as_float_array(rel_quat)[1:]\n if rel_quat.w < 0.0:\n vec = -vec\n \n return -des_mat.dot(vec)\n\ndef control_thread(rate):\n \"\"\"\n Actual control loop. Uses goal pose from the feedback thread\n and current robot states from the subscribed messages to compute\n task-space force, and then the corresponding joint torques.\n \"\"\"\n while not rospy.is_shutdown():\n error = 100.\n while error > 0.005:\n curr_pose = copy.deepcopy(CARTESIAN_POSE)\n curr_pos, curr_ori = curr_pose['position'],curr_pose['orientation']\n\n curr_vel = (CARTESIAN_VEL['linear']).reshape([3,1])\n curr_omg = CARTESIAN_VEL['angular'].reshape([3,1])\n delta_pos = (goal_pos - curr_pos).reshape([3,1])\n delta_ori = quatdiff_in_euler(curr_ori, goal_ori).reshape([3,1])\n # Desired task-space force using PD law\n F = np.vstack([P_pos*(delta_pos), P_ori*(delta_ori)]) + \\\n np.vstack([D_pos*(curr_vel), D_ori*(curr_omg)])\n error = np.linalg.norm(delta_pos) + np.linalg.norm(delta_ori)\n \n J = copy.deepcopy(JACOBIAN)\n\n # joint torques to be commanded\n tau = np.dot(J.T,F)\n # publish joint commands\n command_msg.effort = tau.flatten()\n joint_command_publisher.publish(command_msg)\n rate.sleep()\n\ndef process_feedback(feedback):\n \"\"\"\n InteractiveMarker callback function. Update target pose.\n \"\"\"\n global goal_pos, goal_ori\n '''\n if feedback.event_type == InteractiveMarkerFeedback.MOUSE_UP:\n '''\n p = feedback.pose.position\n q = feedback.pose.orientation\n goal_pos = np.array([p.x,p.y,p.z])\n goal_ori = np.quaternion(q.w, q.x,q.y,q.z)\n\ndef _on_shutdown():\n \"\"\"\n Clean shutdown controller thread when rosnode dies.\n \"\"\"\n global ctrl_thread, cartesian_state_sub, \\\n robot_state_sub, joint_command_publisher\n if ctrl_thread.is_alive():\n ctrl_thread.join()\n\n robot_state_sub.unregister()\n cartesian_state_sub.unregister()\n joint_command_publisher.unregister()\n \nif __name__ == \"__main__\":\n # global goal_pos, goal_ori, ctrl_thread\n\n rospy.init_node(\"ts_control_sim_only\")\n\n # if not using franka_ros_interface, you have to subscribe to the right topics\n # to obtain the current end-effector state and robot jacobian for computing \n # commands\n cartesian_state_sub = rospy.Subscriber(\n 'panda_simulator/custom_franka_state_controller/tip_state',\n EndPointState,\n _on_endpoint_state,\n queue_size=1,\n tcp_nodelay=True)\n\n robot_state_sub = rospy.Subscriber(\n 'panda_simulator/custom_franka_state_controller/robot_state',\n RobotState,\n _on_robot_state,\n queue_size=1,\n tcp_nodelay=True)\n \n # create joint command message and fix its type to joint torque mode\n command_msg = JointCommand()\n command_msg.names = ['panda_joint1','panda_joint2','panda_joint3',\\\n 'panda_joint4','panda_joint5','panda_joint6','panda_joint7']\n command_msg.mode = JointCommand.TORQUE_MODE\n \n # Also create a publisher to publish joint commands\n joint_command_publisher = rospy.Publisher(\n 'panda_simulator/motion_controller/arm/joint_commands',\n JointCommand,\n tcp_nodelay=True,\n queue_size=1)\n\n # wait for messages to be populated before proceeding\n rospy.loginfo(\"Subscribing to robot state topics...\")\n while (True):\n if not (JACOBIAN is None or CARTESIAN_POSE is None):\n break\n rospy.loginfo(\"Recieved messages; Starting Demo.\")\n\n\n pose = copy.deepcopy(CARTESIAN_POSE)\n start_pos, start_ori = pose['position'],pose['orientation']\n goal_pos, goal_ori = start_pos, start_ori # set goal pose a starting pose in the beginning\n \n\n # start controller thread\n rospy.on_shutdown(_on_shutdown)\n rate = rospy.Rate(publish_rate)\n ctrl_thread = threading.Thread(target=control_thread, args = [rate])\n ctrl_thread.start()\n\n # ------------------------------------------------------------------------------------\n end_target_sub = rospy.Subscriber(\"panda_simulator/equili_pose\",PoseStamped,process_feedback,queue_size=1)\n server = InteractiveMarkerServer(\"basic_control\")\n\n position = Point( start_pos[0], start_pos[1], start_pos[2])\n marker = destination_marker.makeMarker( False, InteractiveMarkerControl.MOVE_ROTATE_3D, \\\n position, quaternion.as_float_array(start_ori), True)\n server.insert(marker, process_feedback)\n \n server.applyChanges()\n\n rospy.spin() \n # ------------------------------------------------------------------------------------" ]
[ [ "numpy.dot", "numpy.asarray", "numpy.linalg.norm", "numpy.quaternion", "numpy.array", "numpy.vstack" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
cgranade/QC-App-Oriented-Benchmarks
[ "4b935dae35486c29477830e90f777e54763499d4", "4b935dae35486c29477830e90f777e54763499d4" ]
[ "hidden-shift/qiskit/hs_benchmark.py", "_common/metrics.py" ]
[ "\"\"\"\nHidden Shift Benchmark Program - Qiskit\n\"\"\"\n\nimport sys\nimport time\n\nimport numpy as np\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\n\nsys.path[1:1] = [ \"_common\", \"_common/qiskit\" ]\nsys.path[1:1] = [ \"../../_common\", \"../../_common/qiskit\" ]\nimport execute as ex\nimport metrics as metrics\n\nnp.random.seed(0)\n\nverbose = False\n\n# saved circuits for display\nQC_ = None\nUf_ = None\nUg_ = None\n############### Circuit Definition\n\n# Uf oracle where Uf|x> = f(x)|x>, f(x) = {-1,1}\ndef Uf_oracle(num_qubits, secret_int):\n # Initialize qubits qubits\n qr = QuantumRegister(num_qubits)\n qc = QuantumCircuit(qr, name=f\"Uf\")\n\n # Perform X on each qubit that matches a bit in secret string\n s = ('{0:0'+str(num_qubits)+'b}').format(secret_int)\n for i_qubit in range(num_qubits):\n if s[num_qubits-1-i_qubit]=='1':\n qc.x(qr[i_qubit])\n\n for i_qubit in range(0,num_qubits-1,2):\n qc.cz(qr[i_qubit], qr[i_qubit+1])\n\n # Perform X on each qubit that matches a bit in secret string\n s = ('{0:0'+str(num_qubits)+'b}').format(secret_int)\n for i_qubit in range(num_qubits):\n if s[num_qubits-1-i_qubit]=='1':\n qc.x(qr[i_qubit])\n\n return qc\n\n# Generate Ug oracle where Ug|x> = g(x)|x>, g(x) = f(x+s)\ndef Ug_oracle(num_qubits):\n # Initialize first n qubits\n qr = QuantumRegister(num_qubits)\n qc = QuantumCircuit(qr, name=f\"Ug\")\n\n for i_qubit in range(0,num_qubits-1,2):\n qc.cz(qr[i_qubit], qr[i_qubit+1])\n\n return qc\n\ndef HiddenShift (num_qubits, secret_int):\n \n # allocate qubits\n qr = QuantumRegister(num_qubits); cr = ClassicalRegister(num_qubits); qc = QuantumCircuit(qr, cr, name=\"main\")\n \n # Start with Hadamard on all input qubits\n for i_qubit in range(num_qubits):\n qc.h(qr[i_qubit])\n\n qc.barrier()\n\n # Generate Uf oracle where Uf|x> = f(x)|x>, f(x) = {-1,1}\n Uf = Uf_oracle(num_qubits, secret_int)\n qc.append(Uf,qr)\n\n qc.barrier()\n \n # Again do Hadamard on all qubits\n for i_qubit in range(num_qubits):\n qc.h(qr[i_qubit])\n\n qc.barrier()\n\n # Generate Ug oracle where Ug|x> = g(x)|x>, g(x) = f(x+s)\n Ug = Ug_oracle(num_qubits)\n qc.append(Ug,qr)\n\n qc.barrier()\n\n # End with Hadamard on all qubits\n for i_qubit in range(num_qubits):\n qc.h(qr[i_qubit])\n \n qc.barrier()\n \n # measure all qubits\n qc.measure(qr, cr)\n\n # save smaller circuit example for display\n global QC_, Uf_, Ug_\n if QC_ == None or num_qubits <= 6:\n if num_qubits < 9: QC_ = qc\n if Uf_ == None or num_qubits <= 6:\n if num_qubits < 9: Uf_ = Uf\n if Ug_ == None or num_qubits <= 6:\n if num_qubits < 9: Ug_ = Ug\n \n # return a handle on the circuit\n return qc\n\n############### Circuit end\n\n# Analyze and print measured results\n# Expected result is always the secret_int, so fidelity calc is simple\ndef analyze_and_print_result (qc, result, num_qubits, secret_int, num_shots):\n \n # obtain counts from the result object\n counts = result.get_counts(qc)\n if verbose: print(f\"For secret int {secret_int} measured: {counts}\")\n \n # create the key that is expected to have all the measurements (for this circuit)\n key = format(secret_int, f\"0{num_qubits}b\")\n \n # correct distribution is measuring the key 100% of the time\n correct_dist = {key: 1.0}\n\n # use our polarization fidelity rescaling\n fidelity = metrics.polarization_fidelity(counts, correct_dist)\n \n return counts, fidelity\n\n################ Benchmark Loop\n\n# Execute program with default parameters\ndef run (min_qubits=2, max_qubits=6, max_circuits=3, num_shots=100,\n backend_id='qasm_simulator', provider_backend=None,\n hub=\"ibm-q\", group=\"open\", project=\"main\"):\n\n print(\"Hidden Shift Benchmark Program - Qiskit\")\n\n # validate parameters (smallest circuit is 2 qubits)\n max_qubits = max(2, max_qubits)\n min_qubits = min(max(2, min_qubits), max_qubits)\n if min_qubits % 2 == 1: min_qubits += 1 # min_qubits must be even\n #print(f\"min, max qubits = {min_qubits} {max_qubits}\")\n \n # Initialize metrics module\n metrics.init_metrics()\n\n # Define custom result handler\n def execution_handler (qc, result, num_qubits, s_int, num_shots): \n \n # determine fidelity of result set\n num_qubits = int(num_qubits)\n counts, fidelity = analyze_and_print_result(qc, result, num_qubits, int(s_int), num_shots)\n metrics.store_metric(num_qubits, s_int, 'fidelity', fidelity)\n\n # Initialize execution module using the execution result handler above and specified backend_id\n ex.init_execution(execution_handler)\n ex.set_execution_target(backend_id, provider_backend=provider_backend,\n hub=hub, group=group, project=project)\n\n # Execute Benchmark Program N times for multiple circuit sizes\n # Accumulate metrics asynchronously as circuits complete\n for num_qubits in range(min_qubits, max_qubits + 1, 2):\n\n # determine number of circuits to execute for this group\n num_circuits = min(2 ** (num_qubits), max_circuits)\n \n print(f\"************\\nExecuting [{num_circuits}] circuits with num_qubits = {num_qubits}\")\n \n # determine range of secret strings to loop over\n if 2**(num_qubits) <= max_circuits:\n s_range = list(range(num_circuits))\n else:\n s_range = np.random.choice(2**(num_qubits), num_circuits, False)\n \n # loop over limited # of secret strings for this\n for s_int in s_range:\n \n # create the circuit for given qubit size and secret string, store time metric\n ts = time.time()\n qc = HiddenShift(num_qubits, s_int)\n metrics.store_metric(num_qubits, s_int, 'create_time', time.time()-ts)\n\n # collapse the sub-circuit levels used in this benchmark (for qiskit)\n qc2 = qc.decompose()\n\n # submit circuit for execution on target (simulator, cloud simulator, or hardware)\n ex.submit_circuit(qc2, num_qubits, s_int, shots=num_shots)\n \n # Wait for some active circuits to complete; report metrics when groups complete\n ex.throttle_execution(metrics.finalize_group)\n \n # Wait for all active circuits to complete; report metrics when groups complete\n ex.finalize_execution(metrics.finalize_group)\n\n # print a sample circuit\n print(\"Sample Circuit:\"); print(QC_ if QC_ != None else \" ... too large!\")\n print(\"\\nQuantum Oracle 'Uf' =\"); print(Uf_ if Uf_ != None else \" ... too large!\")\n print(\"\\nQuantum Oracle 'Ug' =\"); print(Ug_ if Ug_ != None else \" ... too large!\")\n\n # Plot metrics for all circuit sizes\n metrics.plot_metrics(\"Benchmark Results - Hidden Shift - Qiskit\")\n\n# if main, execute method\nif __name__ == '__main__': run()\n", "###############################################################################\n# (C) Quantum Economic Development Consortium (QED-C) 2021.\n# Technical Advisory Committee on Standards and Benchmarks (TAC)\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http:#www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n##########################\n# Metrics Module\n#\n# This module contains methods to initialize, store, aggregate and\n# plot metrics collected in the benchmark programs\n#\n# Metrics are indexed by group id (e.g. circuit size), circuit id (e.g. secret string)\n# and metric name.\n# Multiple metrics with different names may be stored, each with a single value.\n#\n# The 'aggregate' method accumulates all circuit-specific metrics for each group\n# and creates an average that may be reported and plotted across all groups\n#\n\nimport os\nimport json\nimport time\nfrom time import gmtime, strftime\nfrom datetime import datetime\n\n# Raw and aggregate circuit metrics\ncircuit_metrics = { }\ngroup_metrics = { \"groups\": [],\n \"avg_create_times\": [], \"avg_elapsed_times\": [], \"avg_exec_times\": [], \"avg_fidelities\": [],\n \"avg_depths\": [], \"avg_xis\": [], \"avg_tr_depths\": [], \"avg_tr_xis\": [],\n \"avg_exec_creating_times\": [], \"avg_exec_validating_times\": [], \"avg_exec_running_times\": []\n}\n\n# Additional properties\n_properties = { \"api\":\"unknown\", \"backend_id\":\"unknown\"}\n\n# times relevant to an application run\nstart_time = 0 \nend_time = 0\n\n##### Options\n\n# Print more detailed metrics info\nverbose = False\n\n# Option to save metrics to data file\nsave_metrics = True \n\n# Option to save plot images (all of them)\nsave_plot_images = True\n\n# Option to generate volumetric positioning charts\ndo_volumetric_plots = True\n\n# Option to include all app charts with vplots at end\ndo_app_charts_with_all_metrics = False\n\n# Number of ticks on volumetric depth axis\nmax_depth_log = 22\n\n# Quantum Volume to display on volumetric background\nQV = 32\n\n# average transpile factor between base QV depth and our depth based on results from QV notebook\nQV_transpile_factor = 12.7 \n\n# Base for volumetric plot logarithmic axes\n#depth_base = 1.66 # this stretches depth axis out, but other values have issues:\n#1) need to round to avoid duplicates, and 2) trailing zeros are getting removed \ndepth_base = 2\n\n\n##### Initialize methods\n\n# Set a subtitle for the Chart\ndef set_plot_subtitle (subtitle=None):\n circuit_metrics[\"subtitle\"] = subtitle\n \n# Set properties context for this set of metrics\ndef set_properties ( properties=None ):\n global _properties\n \n if properties == None:\n _properties = { \"api\":\"unknown\", \"backend_id\":\"unknown\" }\n else:\n _properties = properties\n \n# Initialize the metrics module, creating an empty table of metrics\ndef init_metrics ():\n global start_time\n \n # create empty dictionary for circuit metrics\n circuit_metrics.clear()\n \n # create empty arrays for group metrics\n group_metrics[\"groups\"] = []\n \n group_metrics[\"avg_create_times\"] = []\n group_metrics[\"avg_elapsed_times\"] = []\n group_metrics[\"avg_exec_times\"] = []\n group_metrics[\"avg_fidelities\"] = []\n \n group_metrics[\"avg_depths\"] = []\n group_metrics[\"avg_xis\"] = []\n group_metrics[\"avg_tr_depths\"] = []\n group_metrics[\"avg_tr_xis\"] = []\n \n group_metrics[\"avg_exec_creating_times\"] = []\n group_metrics[\"avg_exec_validating_times\"] = []\n group_metrics[\"avg_exec_running_times\"] = []\n \n # store the start of execution for the current app\n start_time = time.time()\n print(f'... execution starting at {strftime(\"%Y-%m-%d %H:%M:%S\", gmtime())}')\n\n# End metrics collection for an application\ndef end_metrics():\n global end_time\n\n end_time = time.time()\n print(f'... execution complete at {strftime(\"%Y-%m-%d %H:%M:%S\", gmtime())}')\n print(\"\")\n \n \n##### Metrics methods\n\n# Store an individual metric associate with a group and circuit in the group\ndef store_metric (group, circuit, metric, value):\n group = str(group)\n circuit = str(circuit)\n if group not in circuit_metrics:\n circuit_metrics[group] = { }\n if circuit not in circuit_metrics[group]:\n circuit_metrics[group][circuit] = { }\n circuit_metrics[group][circuit][metric] = value\n #print(f'{group} {circuit} {metric} -> {value}')\n\n\n# Aggregate metrics for a specific group, creating average across circuits in group\ndef aggregate_metrics_for_group (group):\n group = str(group)\n \n # generate totals, then divide by number of circuits to calculate averages \n if group in circuit_metrics:\n num_circuits = 0\n group_create_time = 0\n group_elapsed_time = 0\n group_exec_time = 0\n group_fidelity = 0\n group_depth = 0\n group_xi = 0\n group_tr_depth = 0\n group_tr_xi = 0\n group_exec_creating_time = 0\n group_exec_validating_time = 0\n group_exec_running_time = 0\n\n # loop over circuits in group to generate totals\n for circuit in circuit_metrics[group]:\n num_circuits += 1\n for metric in circuit_metrics[group][circuit]:\n value = circuit_metrics[group][circuit][metric]\n #print(f'{group} {circuit} {metric} -> {value}')\n if metric == \"create_time\": group_create_time += value\n if metric == \"elapsed_time\": group_elapsed_time += value\n if metric == \"exec_time\": group_exec_time += value\n if metric == \"fidelity\": group_fidelity += value\n \n if metric == \"depth\": group_depth += value\n if metric == \"xi\": group_xi += value\n if metric == \"tr_depth\": group_tr_depth += value\n if metric == \"tr_xi\": group_tr_xi += value\n \n if metric == \"exec_creating_time\": group_exec_creating_time += value\n if metric == \"exec_validating_time\": group_exec_validating_time += value\n if metric == \"exec_running_time\": group_exec_running_time += value\n\n # calculate averages\n avg_create_time = round(group_create_time / num_circuits, 3)\n avg_elapsed_time = round(group_elapsed_time / num_circuits, 3)\n avg_exec_time = round(group_exec_time / num_circuits, 3)\n avg_fidelity = round(group_fidelity / num_circuits, 3)\n \n avg_depth = round(group_depth / num_circuits, 0)\n avg_xi = round(group_xi / num_circuits, 3)\n avg_tr_depth = round(group_tr_depth / num_circuits, 0)\n avg_tr_xi = round(group_tr_xi / num_circuits, 3)\n \n avg_exec_creating_time = round(group_exec_creating_time / num_circuits, 3)\n avg_exec_validating_time = round(group_exec_validating_time / num_circuits, 3)\n avg_exec_running_time = round(group_exec_running_time / num_circuits, 3)\n \n # store averages in arrays structured for reporting and plotting by group\n group_metrics[\"groups\"].append(group)\n \n group_metrics[\"avg_create_times\"].append(avg_create_time)\n group_metrics[\"avg_elapsed_times\"].append(avg_elapsed_time)\n group_metrics[\"avg_exec_times\"].append(avg_exec_time)\n group_metrics[\"avg_fidelities\"].append(avg_fidelity)\n \n if avg_depth > 0:\n group_metrics[\"avg_depths\"].append(avg_depth)\n if avg_xi > 0:\n group_metrics[\"avg_xis\"].append(avg_xi)\n if avg_tr_depth > 0:\n group_metrics[\"avg_tr_depths\"].append(avg_tr_depth)\n if avg_tr_xi > 0:\n group_metrics[\"avg_tr_xis\"].append(avg_tr_xi)\n \n if avg_exec_creating_time > 0:\n group_metrics[\"avg_exec_creating_times\"].append(avg_exec_creating_time)\n if avg_exec_validating_time > 0:\n group_metrics[\"avg_exec_validating_times\"].append(avg_exec_validating_time)\n if avg_exec_running_time > 0:\n group_metrics[\"avg_exec_running_times\"].append(avg_exec_running_time)\n\n \n# Aggregate all metrics by group\ndef aggregate_metrics ():\n for group in circuit_metrics:\n aggregate_metrics_for_group(group)\n\n\n# Report metrics for a specific group\ndef report_metrics_for_group (group):\n group = str(group)\n if group in group_metrics[\"groups\"]:\n group_index = group_metrics[\"groups\"].index(group)\n if group_index >= 0:\n avg_xi = 0\n if len(group_metrics[\"avg_xis\"]) > 0:\n avg_xi = group_metrics[\"avg_xis\"][group_index]\n\n if len(group_metrics[\"avg_depths\"]) > 0:\n avg_depth = group_metrics[\"avg_depths\"][group_index]\n if avg_depth > 0:\n print(f\"Average Depth, \\u03BE (xi) for the {group} qubit group = {int(avg_depth)}, {avg_xi}\")\n \n avg_tr_xi = 0\n if len(group_metrics[\"avg_tr_xis\"]) > 0:\n avg_tr_xi = group_metrics[\"avg_tr_xis\"][group_index]\n \n if len(group_metrics[\"avg_tr_depths\"]) > 0:\n avg_tr_depth = group_metrics[\"avg_tr_depths\"][group_index]\n if avg_tr_depth > 0:\n print(f\"Average Transpiled Depth, \\u03BE (xi) for the {group} qubit group = {int(avg_tr_depth)}, {avg_tr_xi}\")\n \n avg_create_time = group_metrics[\"avg_create_times\"][group_index]\n print(f\"Average Creation Time for the {group} qubit group = {avg_create_time} secs\")\n avg_elapsed_time = group_metrics[\"avg_elapsed_times\"][group_index]\n print(f\"Average Elapsed Time for the {group} qubit group = {avg_elapsed_time} secs\")\n avg_exec_time = group_metrics[\"avg_exec_times\"][group_index]\n print(f\"Average Execution Time for the {group} qubit group = {avg_exec_time} secs\")\n \n #if verbose:\n if len(group_metrics[\"avg_exec_creating_times\"]) > 0:\n avg_exec_creating_time = group_metrics[\"avg_exec_creating_times\"][group_index]\n #if avg_exec_creating_time > 0:\n #print(f\"Average Creating Time for group {group} = {avg_exec_creating_time}\")\n \n if len(group_metrics[\"avg_exec_validating_times\"]) > 0:\n avg_exec_validating_time = group_metrics[\"avg_exec_validating_times\"][group_index]\n #if avg_exec_validating_time > 0:\n #print(f\"Average Validating Time for group {group} = {avg_exec_validating_time}\")\n \n if len(group_metrics[\"avg_exec_running_times\"]) > 0:\n avg_exec_running_time = group_metrics[\"avg_exec_running_times\"][group_index]\n #if avg_exec_running_time > 0:\n #print(f\"Average Running Time for group {group} = {avg_exec_running_time}\")\n \n print(f\"Average Transpiling, Validating, Running Times for group {group} = {avg_exec_creating_time}, {avg_exec_validating_time}, {avg_exec_running_time} secs\")\n \n avg_fidelity = group_metrics[\"avg_fidelities\"][group_index]\n print(f\"Average Fidelity for the {group} qubit group = {avg_fidelity}\")\n \n print(\"\")\n return\n \n # if group metrics not found \n print(\"\")\n print(f\"no metrics for group: {group}\")\n \n# Report all metrics for all groups\ndef report_metrics (): \n # loop over all groups and print metrics for that group\n for group in circuit_metrics:\n report_metrics_for_group(group)\n \n# Aggregate and report on metrics for the given groups, if all circuits in group are complete\ndef finalize_group(group):\n\n #print(f\"... finalize group={group}\")\n\n # loop over circuits in group to generate totals\n group_done = True\n for circuit in circuit_metrics[group]:\n #print(f\" ... metrics = {group} {circuit} {circuit_metrics[group][circuit]}\")\n \n if \"elapsed_time\" not in circuit_metrics[group][circuit]:\n group_done = False\n break\n \n #print(f\" ... group_done = {group} {group_done}\")\n if group_done:\n aggregate_metrics_for_group(group)\n print(\"************\")\n report_metrics_for_group(group)\n \n # sort the group metrics (sometimes they come back out of order)\n sort_group_metrics()\n \n \n# sort the group array as integers, then all metrics relative to it\ndef sort_group_metrics():\n\n # get groups as integer, then sort each metric with it\n igroups = [int(group) for group in group_metrics[\"groups\"]]\n for key in group_metrics:\n if key == \"groups\": continue\n xy = sorted(zip(igroups, group_metrics[key]))\n group_metrics[key] = [y for x, y in xy]\n \n # save the sorted group names when all done \n xy = sorted(zip(igroups, group_metrics[\"groups\"])) \n group_metrics[\"groups\"] = [y for x, y in xy]\n \n\n##########################################\n# ANALYSIS AND VISUALIZATION\n\nimport matplotlib.pyplot as plt\n \n# Plot bar charts for each metric over all groups\ndef plot_metrics (suptitle=\"Circuit Width (Number of Qubits)\", transform_qubit_group = False, new_qubit_group = None, filters=None, suffix=\"\"):\n \n subtitle = circuit_metrics[\"subtitle\"]\n \n # Extract shorter app name from the title passed in by user\n appname = suptitle[len('Benchmark Results - '):len(suptitle)]\n appname = appname[:appname.index(' - ')]\n \n # for creating plot image filenames replace spaces\n appname = appname.replace(' ', '-')\n \n backend_id = subtitle[9:] \n\n # save the metrics for current application to the DATA file, one file per device\n if save_metrics:\n #data = group_metrics\n #filename = f\"DATA-{subtitle[9:]}.json\"\n #title = suptitle\n\n # If using mid-circuit transformation, convert old qubit group to new qubit group\n if transform_qubit_group:\n original_data = group_metrics[\"groups\"]\n group_metrics[\"groups\"] = new_qubit_group\n store_app_metrics(backend_id, circuit_metrics, group_metrics, suptitle,\n start_time=start_time, end_time=end_time)\n group_metrics[\"groups\"] = original_data\n else:\n store_app_metrics(backend_id, circuit_metrics, group_metrics, suptitle,\n start_time=start_time, end_time=end_time)\n\n \n if len(group_metrics[\"groups\"]) == 0:\n print(f\"\\n{suptitle}\")\n print(f\" ****** NO RESULTS ****** \")\n return\n \n # sort the group metrics (in case they weren't sorted when collected)\n sort_group_metrics()\n \n # flags for charts to show\n do_creates = True\n do_executes = True\n do_fidelities = True\n do_depths = True\n do_vbplot = True\n \n # check if we have depth metrics to show\n do_depths = len(group_metrics[\"avg_depths\"]) > 0\n \n # if filters set, adjust these flags\n if filters != None:\n if \"create\" not in filters: do_creates = False\n if \"execute\" not in filters: do_executes = False\n if \"fidelity\" not in filters: do_fidelities = False\n if \"depth\" not in filters: do_depths = False\n if \"vbplot\" not in filters: do_vbplot = False\n \n # generate one-column figure with multiple bar charts, with shared X axis\n cols = 1\n fig_w = 6.0\n \n numplots = 0\n if do_creates: numplots += 1\n if do_executes: numplots += 1\n if do_fidelities: numplots += 1\n if do_depths: numplots += 1\n \n rows = numplots\n \n # DEVNOTE: this calculation is based on visual assessment of results and could be refined\n # compute height needed to draw same height plots, no matter how many there are\n fig_h = 3.5 + 2.0 * (rows - 1) + 0.25 * (rows - 1)\n #print(fig_h)\n \n # create the figure into which plots will be placed\n fig, axs = plt.subplots(rows, cols, sharex=True, figsize=(fig_w, fig_h))\n \n # append the circuit metrics subtitle to the title\n timestr = strftime(\"%Y-%m-%d %H:%M:%S\", gmtime())\n realtitle = suptitle + f\"\\nDevice={backend_id} {timestr} UTC\"\n '''\n realtitle = suptitle\n if subtitle != None:\n realtitle += (\"\\n\" + subtitle)\n ''' \n plt.suptitle(realtitle)\n \n axi = 0\n xaxis_set = False\n \n if rows == 1:\n ax = axs\n axs = [ax]\n \n if do_creates:\n if max(group_metrics[\"avg_create_times\"]) < 0.01:\n axs[axi].set_ylim([0, 0.01])\n axs[axi].bar(group_metrics[\"groups\"], group_metrics[\"avg_create_times\"])\n axs[axi].set_ylabel('Avg Creation Time (sec)')\n \n if rows > 0 and not xaxis_set:\n axs[axi].sharex(axs[rows-1])\n xaxis_set = True\n \n plt.setp(axs[axi].get_xticklabels(), visible=False)\n axi += 1\n \n if do_executes:\n if max(group_metrics[\"avg_exec_times\"]) < 0.1:\n axs[axi].set_ylim([0, 0.1])\n axs[axi].bar(group_metrics[\"groups\"], group_metrics[\"avg_exec_times\"])\n axs[axi].set_ylabel('Avg Execution Time (sec)')\n \n if rows > 0 and not xaxis_set:\n axs[axi].sharex(axs[rows-1])\n xaxis_set = True\n \n # none of these methods of sharing the x axis gives proper effect; makes extra white space\n #axs[axi].sharex(axs[2])\n #plt.setp(axs[axi].get_xticklabels(), visible=False)\n #axs[axi].set_xticklabels([])\n axi += 1\n \n if do_fidelities:\n axs[axi].set_ylim([0, 1.0])\n axs[axi].bar(group_metrics[\"groups\"], group_metrics[\"avg_fidelities\"]) \n axs[axi].set_ylabel('Avg Result Fidelity')\n \n if rows > 0 and not xaxis_set:\n axs[axi].sharex(axs[rows-1])\n xaxis_set = True\n \n axi += 1\n \n if do_depths:\n if max(group_metrics[\"avg_tr_depths\"]) < 20:\n axs[axi].set_ylim([0, 20]) \n axs[axi].bar(group_metrics[\"groups\"], group_metrics[\"avg_depths\"], 0.8)\n axs[axi].bar(group_metrics[\"groups\"], group_metrics[\"avg_tr_depths\"], 0.5, color='C9') \n axs[axi].set_ylabel('Circuit Depth')\n \n if rows > 0 and not xaxis_set:\n axs[axi].sharex(axs[rows-1])\n xaxis_set = True\n \n axs[axi].legend(['Circuit Depth', 'Transpiled Depth'], loc='upper left')\n axi += 1\n \n # shared x axis label\n axs[rows - 1].set_xlabel('Circuit Width (Number of Qubits)')\n \n fig.tight_layout() \n \n # save plot image to file\n if save_plot_images:\n save_plot_image(plt, f\"{appname}-metrics\" + suffix, backend_id) \n \n # show the plot for user to see\n plt.show()\n \n ###################### Volumetric Plot\n \n timestr = strftime(\"%Y-%m-%d %H:%M:%S\", gmtime())\n \n suptitle = f\"Volumetric Positioning - {appname}\\nDevice={backend_id} {timestr} UTC\"\n \n global cmap \n \n # note: if using filters, both \"depth\" and \"vbplot\" must be set for this to draw\n \n # generate separate figure for volumetric positioning chart of depth metrics\n # found it difficult to share the x axis with first 3, but have diff axis for this one\n if do_depths and do_volumetric_plots and do_vbplot:\n \n w_data = group_metrics[\"groups\"]\n d_tr_data = group_metrics[\"avg_tr_depths\"]\n f_data = group_metrics[\"avg_fidelities\"]\n \n try:\n #print(f\"... {d_data} {d_tr_data}\")\n \n vplot_anno_init()\n \n max_qubits = max([int(group) for group in w_data])\n \n ax = plot_volumetric_background(max_qubits, QV, depth_base, suptitle=suptitle)\n \n # determine width for circuit\n w_max = 0\n for i in range(len(w_data)):\n y = float(w_data[i])\n w_max = max(w_max, y)\n\n cmap = cmap_spectral\n\n # If using mid-circuit transformation, convert width data to singular circuit width value\n if transform_qubit_group:\n w_data = new_qubit_group\n group_metrics[\"groups\"] = w_data\n\n plot_volumetric_data(ax, w_data, d_tr_data, f_data, depth_base, fill=True,\n label=appname, labelpos=(0.4, 0.6), labelrot=15, type=1, w_max=w_max) \n \n anno_volumetric_data(ax, depth_base,\n label=appname, labelpos=(0.4, 0.6), labelrot=15, type=1, fill=False)\n \n except Exception as e:\n print(f'ERROR: failure when creating volumetric positioning chart')\n print(f\"... exception = {e}\")\n \n # save plot image to file\n if save_plot_images:\n save_plot_image(plt, f\"{appname}-vplot\", backend_id) \n \n #display plot\n plt.show() \n\n \n# Plot metrics over all groups (2)\ndef plot_metrics_all_overlaid (shared_data, backend_id, suptitle=None, imagename=\"_ALL-vplot-1\"): \n \n global circuit_metrics\n global group_metrics\n \n subtitle = circuit_metrics[\"subtitle\"]\n \n print(\"Overlaid Results From All Applications\")\n \n # generate separate figure for volumetric positioning chart of depth metrics\n # found it difficult to share the x axis with first 3, but have diff axis for this one\n \n try:\n #print(f\"... {d_data} {d_tr_data}\")\n \n # determine largest width for all apps\n w_max = 0\n for app in shared_data:\n group_metrics = shared_data[app][\"group_metrics\"]\n w_data = group_metrics[\"groups\"]\n for i in range(len(w_data)):\n y = float(w_data[i])\n w_max = max(w_max, y)\n \n # allow one more in width to accommodate the merge values below\n max_qubits = int(w_max) + 1 \n #print(f\"... {w_max} {max_qubits}\")\n \n ax = plot_volumetric_background(max_qubits, QV, depth_base, suptitle=suptitle)\n \n vplot_anno_init()\n \n for app in shared_data:\n #print(shared_data[app])\n\n # Extract shorter app name from the title passed in by user\n appname = app[len('Benchmark Results - '):len(app)]\n appname = appname[:appname.index(' - ')]\n \n group_metrics = shared_data[app][\"group_metrics\"]\n #print(group_metrics)\n \n if len(group_metrics[\"groups\"]) == 0:\n print(f\"****** NO RESULTS for {appname} ****** \")\n continue\n\n # check if we have depth metrics\n do_depths = len(group_metrics[\"avg_depths\"]) > 0\n if not do_depths:\n continue\n \n w_data = group_metrics[\"groups\"]\n d_data = group_metrics[\"avg_depths\"]\n d_tr_data = group_metrics[\"avg_tr_depths\"]\n f_data = group_metrics[\"avg_fidelities\"]\n \n plot_volumetric_data(ax, w_data, d_tr_data, f_data, depth_base, fill=True,\n label=appname, labelpos=(0.4, 0.6), labelrot=15, type=1, w_max=w_max) \n\n # do annotation separately, spreading labels for readability\n anno_volumetric_data(ax, depth_base,\n label=appname, labelpos=(0.4, 0.6), labelrot=15, type=1, fill=False)\n \n except Exception as e:\n print(f'ERROR: failure when creating volumetric positioning chart')\n print(f\"... exception = {e}\")\n \n # save plot image file\n if save_plot_images:\n save_plot_image(plt, imagename, backend_id) \n \n #display plot\n plt.show() \n\n\n# Plot metrics over all groups (2), merging data from all apps into smaller cells\ndef plot_metrics_all_merged (shared_data, backend_id, suptitle=None, imagename=\"_ALL-vplot-2\", avail_qubits=0): \n \n global circuit_metrics\n global group_metrics\n \n # generate separate figure for volumetric positioning chart of depth metrics\n # found it difficult to share the x axis with first 3, but have diff axis for this one\n \n #print(f\"... {max_depth_log}\")\n \n #if True:\n try:\n #print(f\"... {d_data} {d_tr_data}\")\n \n # determine largest width for all apps\n w_max = 0\n for app in shared_data:\n group_metrics = shared_data[app][\"group_metrics\"]\n w_data = group_metrics[\"groups\"]\n for i in range(len(w_data)):\n y = float(w_data[i])\n w_max = max(w_max, y)\n \n # allow one more in width to accommodate the merge values below\n max_qubits = int(w_max) + 1 \n #print(f\"... {w_max} {max_qubits}\")\n \n ax = plot_volumetric_background(max_qubits, QV, depth_base, suptitle=suptitle, avail_qubits=avail_qubits)\n \n # create 2D array to hold merged value arrays with gradations, one array for each qubit size\n num_grads = 4\n depth_values_merged = []\n for w in range(max_qubits):\n depth_values_merged.append([ None ] * (num_grads * max_depth_log))\n \n #print(depth_values_merged)\n \n # run through depth metrics for all apps, splitting cells into gradations\n for app in shared_data:\n #print(shared_data[app])\n \n # Extract shorter app name from the title passed in by user\n appname = app[len('Benchmark Results - '):len(app)]\n appname = appname[:appname.index(' - ')]\n \n group_metrics = shared_data[app][\"group_metrics\"]\n #print(group_metrics)\n \n if len(group_metrics[\"groups\"]) == 0:\n print(f\"****** NO RESULTS for {appname} ****** \")\n continue\n\n # check if we have depth metrics\n do_depths = len(group_metrics[\"avg_depths\"]) > 0\n if not do_depths:\n continue\n \n w_data = group_metrics[\"groups\"]\n d_data = group_metrics[\"avg_depths\"]\n d_tr_data = group_metrics[\"avg_tr_depths\"]\n f_data = group_metrics[\"avg_fidelities\"]\n \n #plot_volumetric_data(ax, w_data, d_tr_data, f_data, depth_base,\n #label=appname, labelpos=(0.4, 0.6), labelrot=50, type=1) \n\n # aggregate value metrics for each depth cell over all apps\n for i in range(len(d_data)):\n x = depth_index(d_tr_data[i], depth_base)\n y = float(w_data[i])\n f = f_data[i]\n \n # accumulate largest width for all apps\n w_max = max(w_max, y)\n \n xp = x * 4\n \n if x > max_depth_log - 1:\n print(f\"... data out of chart range, skipped; w={y} d={d_tr_data[i]}\")\n continue;\n \n for grad in range(num_grads):\n e = depth_values_merged[int(w_data[i])][int(xp + grad)]\n if e == None: \n e = { \"value\": 0.0, \"count\": 0 }\n e[\"count\"] += 1\n e[\"value\"] += f\n depth_values_merged[int(w_data[i])][int(xp + grad)] = e\n \n #print(depth_values_merged)\n \n # compute and plot the average fidelity at each width / depth gradation with narrow filled rects \n for wi in range(len(depth_values_merged)):\n w = depth_values_merged[wi]\n #print(f\"... w = {w}\")\n \n for di in range(len(w)):\n \n e = w[di]\n \n if e != None:\n e[\"value\"] /= e[\"count\"]\n e[\"count\"] = 1\n \n x = di / 4\n \n # move half cell to left, to account for num grads\n x -= 0.25\n \n y = float(wi)\n f = e[\"value\"]\n \n ax.add_patch(box4_at(x, y, f, type=1, fill=True))\n \n #print(\"**** merged...\")\n #print(depth_values_merged)\n \n # Now overlay depth metrics for each app with unfilled rects, to outline each circuit\n \n vplot_anno_init()\n \n for app in shared_data:\n \n # Extract shorter app name from the title passed in by user\n appname = app[len('Benchmark Results - '):len(app)]\n appname = appname[:appname.index(' - ')]\n \n group_metrics = shared_data[app][\"group_metrics\"]\n \n # check if we have depth metrics for group\n if len(group_metrics[\"groups\"]) == 0:\n continue\n if len(group_metrics[\"avg_depths\"]) == 0:\n continue\n \n w_data = group_metrics[\"groups\"]\n d_data = group_metrics[\"avg_depths\"]\n d_tr_data = group_metrics[\"avg_tr_depths\"]\n f_data = group_metrics[\"avg_fidelities\"] \n\n # plot data rectangles\n '''\n for i in range(len(d_data)):\n x = depth_index(d_tr_data[i], depth_base)\n y = float(w_data[i])\n f = f_data[i]\n ax.add_patch(box_at(x, y, f, type=1, fill=False))\n '''\n \n #print(f\"... plotting {appname}\")\n \n plot_volumetric_data(ax, w_data, d_tr_data, f_data, depth_base,\n label=appname, labelpos=(0.4, 0.6), labelrot=15, type=1, fill=False, w_max=w_max)\n \n # do annotation separately, spreading labels for readability\n anno_volumetric_data(ax, depth_base,\n label=appname, labelpos=(0.4, 0.6), labelrot=15, type=1, fill=False)\n \n #Final pass to overlay unfilled rects for each cell (this is incorrect, should be removed)\n #plot_volumetric_data(ax, w_data, d_tr_data, f_data, depth_base, fill=False,\n #label=appname, labelpos=(0.4, 0.6), labelrot=15, type=1, w_max=w_max)\n \n except Exception as e:\n print(f'ERROR: failure when creating volumetric positioning chart')\n print(f\"... exception = {e}\")\n \n # save plot image file\n if save_plot_images:\n save_plot_image(plt, imagename, backend_id)\n\n #display plot\n plt.show()\n\n\n### plot metrics across all apps for a backend_id\n\ndef plot_all_app_metrics(backend_id, do_all_plots=False,\n include_apps=None, exclude_apps=None, suffix=\"\", avail_qubits=0):\n\n global circuit_metrics\n global group_metrics\n global cmap\n\n # load saved data from file\n api = \"qiskit\"\n shared_data = load_app_metrics(api, backend_id)\n \n # apply include / exclude lists\n if include_apps != None:\n new_shared_data = {}\n for app in shared_data:\n \n # Extract shorter app name from the title passed in by user\n appname = app[len('Benchmark Results - '):len(app)]\n appname = appname[:appname.index(' - ')]\n \n if appname in include_apps:\n new_shared_data[app] = shared_data[app]\n \n shared_data = new_shared_data\n \n if exclude_apps != None:\n new_shared_data = {}\n for app in shared_data:\n \n # Extract shorter app name from the title passed in by user\n appname = app[len('Benchmark Results - '):len(app)]\n appname = appname[:appname.index(' - ')]\n \n if appname not in exclude_apps:\n new_shared_data[app] = shared_data[app]\n \n shared_data = new_shared_data \n \n #print(shared_data)\n \n # since the bar plots use the subtitle field, set it here\n circuit_metrics[\"subtitle\"] = f\"device = {backend_id}\"\n \n timestr = strftime(\"%Y-%m-%d %H:%M:%S\", gmtime())\n\n # show vplots if enabled\n if do_volumetric_plots:\n \n # this is an overlay plot, not very useful; better to merge\n '''\n cmap = cmap_spectral\n suptitle = f\"Volumetric Positioning - All Applications (Combined)\\nDevice={backend_id} {timestr} UTC\"\n plot_metrics_all_overlaid(shared_data, backend_id, suptitle=suptitle, imagename=\"_ALL-vplot-2\")\n '''\n \n # draw the volumetric plots with two different colormaps, for comparison purposes\n \n #suptitle = f\"Volumetric Positioning - All Applications (Merged)\\nDevice={backend_id} {timestr} UTC\"\n #cmap = cmap_blues\n #plot_metrics_all_merged(shared_data, backend_id, suptitle=suptitle, imagename=\"_ALL-vplot-1\"+suffix, avail_qubits=avail_qubits)\n \n cmap = cmap_spectral\n suptitle = f\"Volumetric Positioning - All Applications (Merged)\\nDevice={backend_id} {timestr} UTC\"\n plot_metrics_all_merged(shared_data, backend_id, suptitle=suptitle, imagename=\"_ALL-vplot-2\"+suffix, avail_qubits=avail_qubits)\n \n # show all app metrics charts if enabled\n if do_app_charts_with_all_metrics or do_all_plots:\n for app in shared_data:\n #print(\"\")\n #print(app)\n group_metrics = shared_data[app][\"group_metrics\"]\n plot_metrics(app)\n \n### Plot Metrics for a specific application\n\ndef plot_metrics_for_app(backend_id, appname, apiname=\"Qiskit\", filters=None, suffix=\"\"):\n global circuit_metrics\n global group_metrics\n \n # load saved data from file\n api = \"qiskit\"\n shared_data = load_app_metrics(api, backend_id)\n \n # since the bar plots use the subtitle field, set it here\n circuit_metrics[\"subtitle\"] = f\"device = {backend_id}\"\n \n timestr = strftime(\"%Y-%m-%d %H:%M:%S\", gmtime())\n \n app = \"Benchmark Results - \" + appname + \" - \" + apiname\n \n group_metrics = shared_data[app][\"group_metrics\"]\n plot_metrics(app, filters=filters, suffix=suffix)\n\n \n##### Data File Methods \n \n# Save the application metrics data to a shared file for the current device\ndef store_app_metrics (backend_id, circuit_metrics, group_metrics, app, start_time=None, end_time=None):\n # print(f\"... storing {title} {group_metrics}\")\n \n # don't leave slashes in the filename\n backend_id = backend_id.replace(\"/\", \"_\")\n \n # load the current data file of all apps\n api = \"qiskit\"\n shared_data = load_app_metrics(api, backend_id)\n \n # if there are no previous data for this app, init empty dict \n if app not in shared_data:\n shared_data[app] = { \"circuit_metrics\":None, \"group_metrics\":None }\n \n shared_data[app][\"backend_id\"] = backend_id\n shared_data[app][\"start_time\"] = start_time\n shared_data[app][\"end_time\"] = end_time\n \n shared_data[app][\"group_metrics\"] = group_metrics\n \n # if saving raw circuit data, add it too\n #shared_data[app][\"circuit_metrics\"] =circuit_metrics\n \n # be sure we have a __data directory\n if not os.path.exists('__data'): os.makedirs('__data')\n \n # create filename based on the backend_id\n filename = f\"__data/DATA-{backend_id}.json\"\n \n # overwrite the existing file with the merged data\n with open(filename, 'w+') as f:\n json.dump(shared_data, f, indent=2, sort_keys=True)\n f.close()\n \n# Load the application metrics from the given data file\n# Returns a dict containing circuit and group metrics\ndef load_app_metrics (api, backend_id):\n\n # don't leave slashes in the filename\n backend_id = backend_id.replace(\"/\", \"_\")\n\n filename = f\"__data/DATA-{backend_id}.json\"\n \n shared_data = None\n \n # attempt to load shared_data from file\n if os.path.exists(filename) and os.path.isfile(filename):\n with open(filename, 'r') as f:\n \n # attempt to load shared_data dict as json\n try:\n shared_data = json.load(f)\n \n except:\n pass\n \n # create empty shared_data dict if not read from file\n if shared_data == None:\n shared_data = {}\n \n # temporary: to read older format files ... \n for app in shared_data:\n if \"group_metrics\" not in shared_data[app]:\n print(f\"... upgrading version of app data {app}\")\n shared_data[app] = { \"circuit_metrics\":None, \"group_metrics\":shared_data[app] }\n \n return shared_data\n \n \n# save plot as image\ndef save_plot_image(plt, imagename, backend_id):\n\n # don't leave slashes in the filename\n backend_id = backend_id.replace(\"/\", \"_\")\n \n # not used currently\n date_of_file = datetime.now().strftime(\"%d%m%Y_%H%M%S\")\n \n if not os.path.exists('__images'): os.makedirs('__images')\n if not os.path.exists(f'__images/{backend_id}'): os.makedirs(f'__images/{backend_id}')\n \n pngfilename = f\"{backend_id}/{imagename}\"\n pngfilepath = os.path.join(os.getcwd(),\"__images\", pngfilename + \".jpg\")\n \n plt.savefig(pngfilepath)\n \n #print(f\"... saving (plot) image file:{pngfilename}.jpg\") \n \n pdffilepath = os.path.join(os.getcwd(),\"__images\", pngfilename + \".pdf\")\n \n plt.savefig(pdffilepath)\n\n## Uniform distribution function commonly used\n\ndef uniform_dist(num_state_qubits):\n dist = {}\n for i in range(2**num_state_qubits):\n key = bin(i)[2:].zfill(num_state_qubits)\n dist[key] = 1/(2**num_state_qubits)\n return dist \n\n### Analysis methods to be expanded and eventually compiled into a separate analysis.py file\nimport math, functools\nimport numpy as np\n\n# Compute the fidelity based on Hellinger distance between two discrete probability distributions\ndef hellinger_fidelity_with_expected(p, q):\n \"\"\" p: result distribution, may be passed as a counts distribution\n q: the expected distribution to be compared against\n\n References:\n `Hellinger Distance @ wikipedia <https://en.wikipedia.org/wiki/Hellinger_distance>`_\n Qiskit Hellinger Fidelity Function\n \"\"\"\n p_sum = sum(p.values())\n q_sum = sum(q.values())\n\n p_normed = {}\n for key, val in p.items():\n p_normed[key] = val/p_sum\n\n q_normed = {}\n for key, val in q.items():\n q_normed[key] = val/q_sum\n\n total = 0\n for key, val in p_normed.items():\n if key in q_normed.keys():\n total += (np.sqrt(val) - np.sqrt(q_normed[key]))**2\n del q_normed[key]\n else:\n total += val\n total += sum(q_normed.values())\n dist = np.sqrt(total)/np.sqrt(2)\n fidelity = (1-dist**2)**2\n\n return fidelity\n \ndef rescale_fidelity(fidelity, floor_fidelity, new_floor_fidelity):\n \"\"\"\n Linearly rescales our fidelities to allow comparisons of fidelities across benchmarks\n \n fidelity: raw fidelity to rescale\n floor_fidelity: threshold fidelity which is equivalent to random guessing\n new_floor_fidelity: what we rescale the floor_fidelity to \n\n Ex, with floor_fidelity = 0.25, new_floor_fidelity = 0.0:\n 1 -> 1;\n 0.25 -> 0;\n 0.5 -> 0.3333;\n \"\"\"\n rescaled_fidelity = (1-new_floor_fidelity)/(1-floor_fidelity) * (fidelity - 1) + 1\n \n # ensure fidelity is within bounds (0, 1)\n if rescaled_fidelity < 0:\n rescaled_fidelity = 0.0\n if rescaled_fidelity > 1:\n rescaled_fidelity = 1.0\n \n return rescaled_fidelity\n\ndef polarization_fidelity(counts, correct_dist, thermal_dist=None):\n \"\"\"\n Combines Hellinger fidelity and polarization rescaling into fidelity calculation\n used in every benchmark\n\n counts: the measurement outcomes after `num_shots` algorithm runs\n correct_dist: the distribution we expect to get for the algorithm running perfectly\n thermal_dist: optional distribution to pass in distribution from a uniform\n superposition over all states. If `None`: generated as \n `uniform_dist` with the same qubits as in `counts`\n\n Polarization from: `https://arxiv.org/abs/2008.11294v1`\n \"\"\"\n # calculate fidelity via hellinger fidelity between correct distribution and our measured expectation values\n fidelity = hellinger_fidelity_with_expected(counts, correct_dist)\n\n if thermal_dist == None:\n # get length of random key in counts to find how many qubits measured\n num_measured_qubits = len(list(counts.keys())[0])\n \n # generate thermal dist based on number of qubits\n thermal_dist = uniform_dist(num_measured_qubits)\n\n # set our fidelity rescaling value as the hellinger fidelity for a depolarized state\n floor_fidelity = hellinger_fidelity_with_expected(thermal_dist, correct_dist)\n\n # rescale fidelity result so uniform superposition (random guessing) returns fidelity\n # rescaled to 0 to provide a better measure of success of the algorithm (polarization)\n new_floor_fidelity = 0\n fidelity = rescale_fidelity(fidelity, floor_fidelity, new_floor_fidelity)\n\n return fidelity\n\n##############################################\n# VOLUMETRIC PLOT\n \nimport math\nimport matplotlib.pyplot as plt\nfrom matplotlib.patches import Rectangle\n\nimport matplotlib.cm as cm\n\n############### Helper functions\n\n# get a color from selected colormap\ncmap_spectral = plt.get_cmap('Spectral')\ncmap_blues = plt.get_cmap('Blues')\ncmap = cmap_spectral\n\ndef get_color(value):\n\n if cmap == cmap_spectral:\n value = 0.05 + value*0.9\n elif cmap == cmap_blues:\n value = 0.05 + value*0.8\n \n return cmap(value)\n \n \n# return the base index for a circuit depth value\n# take the log in the depth base, and add 1\ndef depth_index(d, depth_base):\n return math.log(d, depth_base) + 1\n\n\n# draw a box at x,y with various attributes \ndef box_at(x, y, value, type=1, fill=True):\n size = 1.0\n \n value = min(value, 1.0)\n value = max(value, 0.0)\n\n fc = get_color(value)\n ec = (0.5,0.5,0.5)\n \n return Rectangle((x - size/2, y - size/2), size, size,\n edgecolor = ec,\n facecolor = fc,\n fill=fill,\n lw=0.5)\n \ndef box4_at(x, y, value, type=1, fill=True):\n size = 1.0\n \n value = min(value, 1.0)\n value = max(value, 0.0)\n\n fc = get_color(value)\n ec = (0.3,0.3,0.3)\n ec = fc\n \n return Rectangle((x - size/8, y - size/2), size/4, size,\n edgecolor = ec,\n facecolor = fc,\n fill=fill,\n lw=0.1)\n\ndef bkg_box_at(x, y, value):\n size = 0.6\n return Rectangle((x - size/2, y - size/2), size, size,\n edgecolor = (.75,.75,.75),\n facecolor = (.9,.9,.9),\n fill=True,\n lw=0.5)\n \ndef bkg_empty_box_at(x, y, value):\n size = 0.6\n return Rectangle((x - size/2, y - size/2), size, size,\n edgecolor = (.75,.75,.75),\n facecolor = (1.0,1.0,1.0),\n fill=True,\n lw=0.5)\n\n# Draw a Quantum Volume rectangle with specified width and depth, and grey-scale value \ndef qv_box_at(x, y, qv_width, qv_depth, value, depth_base):\n #print(f\"{qv_width} {qv_depth} {depth_index(qv_depth, depth_base)}\")\n return Rectangle((x - 0.5, y - 0.5), depth_index(qv_depth, depth_base), qv_width,\n edgecolor = (value,value,value),\n facecolor = (value,value,value),\n fill=True,\n lw=1)\n\n# format a number using K,M,B,T for large numbers\n# (sign handling may be incorrect)\ndef format_number(num):\n if isinstance(num, str): num = float(num)\n num = float('{:.3g}'.format(abs(num)))\n sign = ''\n metric = {'T': 1000000000000, 'B': 1000000000, 'M': 1000000, 'K': 1000, '': 1}\n for index in metric:\n num_check = num / metric[index]\n if num_check >= 1:\n num = round(num_check)\n sign = index\n break\n numstr = f\"{str(num)}\"\n if '.' in numstr:\n numstr = numstr.rstrip('0').rstrip('.')\n return f\"{numstr}{sign}\"\n\n##### Volumetric Plots\n\n# Plot the background for the volumetric analysis \ndef plot_volumetric_background(max_qubits=11, QV=32, depth_base=2, suptitle=None, avail_qubits=0):\n \n if suptitle == None:\n suptitle = f\"Volumetric Positioning\\nCircuit Dimensions and Fidelity Overlaid on Quantum Volume = {QV}\"\n\n qv_estimate = False\n est_str = \"\"\n if QV < 0:\n QV = -QV\n qv_estimate = True\n est_str = \" (est.)\"\n \n max_width = 13\n if max_qubits > 11: max_width = 18\n if max_qubits > 14: max_width = 20\n #print(f\"... {max_qubits} {max_width}\")\n \n plot_width = 6.8\n plot_height = 0.5 + plot_width * (max_width / max_depth_log)\n #print(f\"... {plot_width} {plot_height}\")\n \n # define matplotlib figure and axis; use constrained layout to fit colorbar to right\n fig, ax = plt.subplots(figsize=(plot_width, plot_height), constrained_layout=True)\n\n plt.suptitle(suptitle)\n\n plt.xlim(0, max_depth_log)\n plt.ylim(0, max_width)\n\n # circuit depth axis (x axis)\n xbasis = [x for x in range(1,max_depth_log)]\n xround = [depth_base**(x-1) for x in xbasis]\n xlabels = [format_number(x) for x in xround]\n ax.set_xlabel('Circuit Depth')\n ax.set_xticks(xbasis) \n plt.xticks(xbasis, xlabels, color='black', rotation=45, ha='right', va='top', rotation_mode=\"anchor\")\n \n # other label options\n #plt.xticks(xbasis, xlabels, color='black', rotation=-60, ha='left')\n #plt.xticks(xbasis, xlabels, color='black', rotation=-45, ha='left', va='center', rotation_mode=\"anchor\")\n\n # circuit width axis (y axis)\n ybasis = [y for y in range(1,max_width)]\n yround = [1,2,3,4,5,6,7,8,10,12,15] # not used now\n ylabels = [str(y) for y in yround] # not used now \n #ax.set_ylabel('Circuit Width (Number of Qubits)')\n ax.set_ylabel('Circuit Width')\n ax.set_yticks(ybasis)\n\n #create simple line plot (not used right now)\n #ax.plot([0, 10],[0, 10])\n \n log2QV = math.log2(QV)\n QV_width = log2QV\n QV_depth = log2QV * QV_transpile_factor\n \n # show a quantum volume rectangle of QV = 64 e.g. (6 x 6)\n ax.add_patch(qv_box_at(1, 1, QV_width, QV_depth, 0.87, depth_base))\n \n # the untranspiled version is commented out - we do not show this by default\n # also show a quantum volume rectangle un-transpiled\n # ax.add_patch(qv_box_at(1, 1, QV_width, QV_width, 0.80, depth_base))\n\n # show 2D array of volumetric cells based on this QV_transpiled\n # DEVNOTE: we use +1 only to make the visuals work; s/b without\n # Also, the second arg of the min( below seems incorrect, needs correction\n maxprod = (QV_width + 1) * (QV_depth + 1)\n for w in range(1, min(max_width, round(QV) + 1)):\n \n # don't show VB squares if width greater than known available qubits\n if avail_qubits != 0 and w > avail_qubits:\n continue\n \n i_success = 0\n for d in xround:\n \n # polarization factor for low circuit widths\n maxtest = maxprod / ( 1 - 1 / (2**w) )\n \n # if circuit would fail here, don't draw box\n if d > maxtest: continue\n if w * d > maxtest: continue\n \n # guess for how to capture how hardware decays with width, not entirely correct\n\n # # reduce maxtext by a factor of number of qubits > QV_width\n # # just an approximation to account for qubit distances\n # if w > QV_width:\n # over = w - QV_width \n # maxtest = maxtest / (1 + (over/QV_width))\n\n # draw a box at this width and depth\n id = depth_index(d, depth_base) \n ax.add_patch(bkg_box_at(id, w, 0.5))\n \n # save index of last successful depth\n i_success += 1\n \n # plot empty rectangle after others \n d = xround[i_success]\n id = depth_index(d, depth_base) \n ax.add_patch(bkg_empty_box_at(id, w, 0.5))\n \n \n # Add annotation showing quantum volume\n t = ax.text(max_depth_log - 2.0, 1.5, f\"QV{est_str}={QV}\", size=12,\n horizontalalignment='right', verticalalignment='center', color=(0.2,0.2,0.2),\n bbox=dict(boxstyle=\"square,pad=0.3\", fc=(.9,.9,.9), ec=\"grey\", lw=1))\n \n # add colorbar to right of plot\n plt.colorbar(cm.ScalarMappable(cmap=cmap), shrink=0.6, label=\"Avg Result Fidelity\", panchor=(0.0, 0.7))\n \n return ax\n\nx_annos = []\ny_annos = []\nx_anno_offs = []\ny_anno_offs = []\nanno_labels = []\n \n# init arrays to hold annotation points for label spreading\ndef vplot_anno_init ():\n\n global x_annos, y_annos, x_anno_offs, y_anno_offs, anno_labels\n \n x_annos = []\n y_annos = []\n x_anno_offs = []\n y_anno_offs = []\n anno_labels = []\n \n\n# Plot one group of data for volumetric presentation \ndef plot_volumetric_data(ax, w_data, d_data, f_data, depth_base=2, label='Depth',\n labelpos=(0.2, 0.7), labelrot=0, type=1, fill=True, w_max=18, do_label=False):\n\n # since data may come back out of order, save point at max y for annotation\n i_anno = 0\n x_anno = 0 \n y_anno = 0\n \n # plot data rectangles\n for i in range(len(d_data)):\n x = depth_index(d_data[i], depth_base)\n y = float(w_data[i])\n f = f_data[i]\n ax.add_patch(box_at(x, y, f, type=type, fill=fill))\n\n if y >= y_anno:\n x_anno = x\n y_anno = y\n i_anno = i\n \n x_annos.append(x_anno)\n y_annos.append(y_anno)\n \n anno_dist = math.sqrt( (y_anno - 1)**2 + (x_anno - 1)**2 )\n \n # adjust radius of annotation circle based on maximum width of apps\n anno_max = 10\n if w_max > 10:\n anno_max = 14\n if w_max > 14:\n anno_max = 18\n \n scale = anno_max / anno_dist\n\n # offset of text from end of arrow\n if scale > 1:\n x_anno_off = scale * x_anno - x_anno - 0.5\n y_anno_off = scale * y_anno - y_anno\n else:\n x_anno_off = 0.7\n y_anno_off = 0.5\n \n x_anno_off += x_anno\n y_anno_off += y_anno\n \n # print(f\"... {xx} {yy} {anno_dist}\")\n x_anno_offs.append(x_anno_off)\n y_anno_offs.append(y_anno_off)\n \n anno_labels.append(label)\n \n if do_label:\n ax.annotate(label, xy=(x_anno+labelpos[0], y_anno+labelpos[1]), rotation=labelrot,\n horizontalalignment='left', verticalalignment='bottom', color=(0.2,0.2,0.2))\n\n\n# Arrange the stored annotations optimally and add to plot \ndef anno_volumetric_data(ax, depth_base=2, label='Depth',\n labelpos=(0.2, 0.7), labelrot=0, type=1, fill=True):\n \n # sort all arrays by the x point of the text (anno_offs)\n global x_anno_offs, y_anno_offs, anno_labels, x_annos, y_annos\n all_annos = sorted(zip(x_anno_offs, y_anno_offs, anno_labels, x_annos, y_annos))\n x_anno_offs = [a for a,b,c,d,e in all_annos]\n y_anno_offs = [b for a,b,c,d,e in all_annos]\n anno_labels = [c for a,b,c,d,e in all_annos]\n x_annos = [d for a,b,c,d,e in all_annos]\n y_annos = [e for a,b,c,d,e in all_annos]\n \n #print(f\"{x_anno_offs}\")\n #print(f\"{y_anno_offs}\")\n #print(f\"{anno_labels}\")\n \n for i in range(len(anno_labels)):\n x_anno = x_annos[i]\n y_anno = y_annos[i]\n x_anno_off = x_anno_offs[i]\n y_anno_off = y_anno_offs[i]\n label = anno_labels[i]\n \n if i > 0:\n x_delta = abs(x_anno_off - x_anno_offs[i - 1])\n y_delta = abs(y_anno_off - y_anno_offs[i - 1])\n \n if y_delta < 0.7 and x_delta < 2:\n y_anno_off = y_anno_offs[i] = y_anno_offs[i - 1] - 0.6\n #x_anno_off = x_anno_offs[i] = x_anno_offs[i - 1] + 0.1\n \n ax.annotate(label,\n xy=(x_anno+0.0, y_anno+0.1),\n arrowprops=dict(facecolor='black', shrink=0.0,\n width=0.5, headwidth=4, headlength=5, edgecolor=(0.8,0.8,0.8)),\n xytext=(x_anno_off + labelpos[0], y_anno_off + labelpos[1]),\n rotation=labelrot,\n horizontalalignment='left', verticalalignment='baseline',\n color=(0.2,0.2,0.2),\n clip_on=True)\n \n \n####################################\n# TEST METHODS \n \n# Test metrics module, with simple test data\ndef test_metrics ():\n init_metrics()\n \n store_metric('group1', 'circuit1', 'create_time', 123)\n store_metric('group1', 'circuit2', 'create_time', 234)\n store_metric('group2', 'circuit1', 'create_time', 156)\n store_metric('group2', 'circuit2', 'create_time', 278)\n \n store_metric('group1', 'circuit1', 'exec_time', 223)\n store_metric('group1', 'circuit2', 'exec_time', 334)\n store_metric('group2', 'circuit1', 'exec_time', 256)\n store_metric('group2', 'circuit2', 'exec_time', 378)\n \n store_metric('group1', 'circuit1', 'fidelity', 1.0)\n store_metric('group1', 'circuit2', 'fidelity', 0.8)\n store_metric('group2', 'circuit1', 'fidelity', 0.9)\n store_metric('group2', 'circuit2', 'fidelity', 0.7)\n \n aggregate_metrics()\n \n report_metrics()\n #report_metrics_for_group(\"badgroup\")\n \n plot_metrics()\n\n#test_metrics()\n" ]
[ [ "numpy.random.seed", "numpy.random.choice" ], [ "numpy.sqrt", "matplotlib.pyplot.ylim", "matplotlib.patches.Rectangle", "matplotlib.pyplot.subplots", "matplotlib.pyplot.get_cmap", "matplotlib.pyplot.savefig", "matplotlib.pyplot.xlim", "matplotlib.cm.ScalarMappable", "matplotlib.pyplot.xticks", "matplotlib.pyplot.suptitle", "matplotlib.pyplot.show" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
chrisjdavie/ws_cross_project
[ "10ffd6d0df1aeea0e5d2d6c5dfddab907a2cd439" ]
[ "generic_plotting/linplots_cjd/semilog_plot.py" ]
[ "'''Plots a semi-log x axis against a linear y-axis.\n\nIt is, I think, only used for perturbation size, as it reflects\nthe underlying physics of that behaviour, but I've split it up\nfor clarity. Both bits do quite a lot of stuff.'''\n\nfrom linear_plot import linear_plot\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nclass semilog_plot(linear_plot):\n \n def __init__(self,x,y):\n super(semilog_plot,self).__init__(x,y)\n \n #if you were trying to pass title as a keyword argument, this is now included in plot_init_kwa\n def plot_init(self,xlabel='',i_end_buffer=0,bit_of_label_on_axis_centre='center',x_out = 1.0,linear_plot_init_kwargs={}):\n #print plot_init_kwa\n# linear_plot_init_kwargs = { 'fig_i':1, 'ylabel':'dr','plot_loc':111,'sci_limits':(-1,1) }\n super(semilog_plot,self).plot_init(xlabel=xlabel,**linear_plot_init_kwargs)\n self.ax.spines['bottom'].set_position('zero')\n \n # making the graph run from x_in to x_out in prep for a log plot which doesn't like zeroes\n x_out = x_out\n self.i_x_end = np.argmin(self.x)-i_end_buffer\n x_in = self.x[self.i_x_end]\n #print 'x_in = ', x_in, 'x_out', x_out\n plt.xlim(x_in, x_out)\n plt.xlim(plt.xlim()[::-1]) \n \n # horizontal alignment is the horizontal alignment of the label relative to the centre of the axis. This seems absurd. \n # Found options are 'left', 'right', 'centre'\n if (xlabel != None) and (xlabel != ''): xlabel = '\\\\boldmath \\\\bf ' + xlabel + ''\n plt.xlabel( xlabel, horizontalalignment = bit_of_label_on_axis_centre)\n \n def plot(self,ax=None,y=None,colour='b',linestyle='-',label='',linewidth=2):\n if ax is None:\n ax = self.ax\n if y is None:\n y = self.y\n super(linear_plot,self).plot()\n if (label != None) and (label != ''): label = '\\\\boldmath \\\\bf ' + label + ''\n self.p = ax.semilogx(self.x,self.y,label=label,color=colour,linestyle=linestyle,linewidth=linewidth) \n self.__line_i__ += 1\n" ]
[ [ "matplotlib.pyplot.xlabel", "matplotlib.pyplot.xlim", "numpy.argmin" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
kj87au/Panda-Grasping
[ "54e35aee6e9c13358401b23e5584211418670657", "54e35aee6e9c13358401b23e5584211418670657" ]
[ "nets/GIGA-main/src/vgn/utils/implicit.py", "nets/contact_graspnet-main/pointnet2/models/frustrum_pontnets_v2.py" ]
[ "import os\nimport trimesh\nimport numpy as np\nfrom urdfpy import URDF\ntry:\n from vgn.ConvONets.utils.libmesh import check_mesh_contains\nexcept:\n print('import libmesh failed!')\n\nn_iou_points = 100000\nn_iou_points_files = 10\n\n## occupancy related code\ndef as_mesh(scene_or_mesh):\n \"\"\"\n Convert a possible scene to a mesh.\n\n The returned mesh has only vertex and face data.\n \"\"\"\n if isinstance(scene_or_mesh, trimesh.Scene):\n if len(scene_or_mesh.geometry) == 0:\n mesh = None # empty scene\n else:\n # we lose texture information here\n mesh = trimesh.util.concatenate(\n tuple(trimesh.Trimesh(vertices=g.vertices, faces=g.faces, visual=g.visual)\n for g in scene_or_mesh.geometry.values()))\n else:\n assert(isinstance(scene_or_mesh, trimesh.Trimesh))\n mesh = scene_or_mesh\n return mesh\n\ndef get_mesh_pose_list_from_world(world, object_set, exclude_plane=True):\n mesh_pose_list = []\n # collect object mesh paths and poses\n for uid in world.bodies.keys():\n _, name = world.p.getBodyInfo(uid)\n name = name.decode('utf8')\n if name == 'plane' and exclude_plane:\n continue\n body = world.bodies[uid]\n pose = body.get_pose().as_matrix()\n scale = body.scale\n visuals = world.p.getVisualShapeData(uid)\n assert len(visuals) == 1\n _, _, _, _, mesh_path, _, _, _ = visuals[0]\n mesh_path = mesh_path.decode('utf8')\n if mesh_path == '':\n mesh_path = os.path.join('./data/urdfs', object_set, name + '.urdf')\n mesh_pose_list.append((mesh_path, scale, pose))\n return mesh_pose_list\n\ndef get_scene_from_mesh_pose_list(mesh_pose_list, scene_as_mesh=True, return_list=False):\n # create scene from meshes\n scene = trimesh.Scene()\n mesh_list = []\n for mesh_path, scale, pose in mesh_pose_list:\n if os.path.splitext(mesh_path)[1] == '.urdf':\n obj = URDF.load(mesh_path)\n assert len(obj.links) == 1\n assert len(obj.links[0].visuals) == 1\n assert len(obj.links[0].visuals[0].geometry.meshes) == 1\n mesh = obj.links[0].visuals[0].geometry.meshes[0].copy()\n else:\n mesh = trimesh.load(mesh_path)\n\n mesh.apply_scale(scale)\n mesh.apply_transform(pose)\n scene.add_geometry(mesh)\n mesh_list.append(mesh)\n if scene_as_mesh:\n scene = as_mesh(scene)\n if return_list:\n return scene, mesh_list\n else:\n return scene\n\ndef sample_iou_points(mesh_list, bounds, num_point, padding=0.02, uniform=False, size=0.3):\n points = np.random.rand(num_point, 3).astype(np.float32)\n if uniform:\n points *= size + 2 * padding\n points -= padding\n else:\n points = points * (bounds[[1]] + 2 * padding - bounds[[0]]) + bounds[[0]] - padding\n occ = np.zeros(num_point).astype(bool)\n for mesh in mesh_list:\n occi = check_mesh_contains(mesh, points)\n occ = occ | occi\n\n return points, occ\n\ndef get_occ_from_world(world, object_set):\n mesh_pose_list = get_mesh_pose_list_from_world(world, object_set)\n scene, mesh_list = get_scene_from_mesh_pose_list(mesh_pose_list, return_list=True)\n points, occ = sample_iou_points(mesh_list, scene.bounds, n_iou_points * n_iou_points_files)\n return points, occ\n\n\n# def get_occ_from_mesh(scene_mesh, world_size, object_count, voxel_resolution=120):\n# # voxelize scene\n# voxel_length = world_size / voxel_resolution\n# scene_voxel = scene_mesh.voxelized(voxel_length)\n\n# # collect near surface points occupancy\n# surface_points, _ = trimesh.sample.sample_surface(scene_mesh, object_count * 2048)\n# surface_points += np.random.randn(*surface_points.shape) * 0.002\n# occ_surface = scene_voxel.is_filled(surface_points)\n# # collect randomly distributed points occupancy\n# random_points = np.random.rand(object_count * 2048, 3)\n# random_points = random_points * (scene_voxel.bounds[[1]] - scene_voxel.bounds[[0]]) + scene_voxel.bounds[[0]]\n# occ_random = scene_voxel.is_filled(random_points)\n# surface_p_occ = np.concatenate((surface_points, occ_surface[:, np.newaxis]), axis=-1)\n# random_p_occ = np.concatenate((random_points, occ_random[:, np.newaxis]), axis=-1)\n# return surface_p_occ, random_p_occ\n", "''' Frustum PointNets v2 Model.\n'''\nfrom __future__ import print_function\n\nimport sys\nimport os\nimport tensorflow as tf\nimport numpy as np\nBASE_DIR = os.path.dirname(os.path.abspath(__file__))\nROOT_DIR = os.path.dirname(BASE_DIR)\nsys.path.append(BASE_DIR)\nsys.path.append(os.path.join(ROOT_DIR, 'utils'))\nimport tf_util\nfrom pointnet_util import pointnet_sa_module, pointnet_sa_module_msg, pointnet_fp_module\nfrom model_util import NUM_HEADING_BIN, NUM_SIZE_CLUSTER, NUM_OBJECT_POINT\nfrom model_util import point_cloud_masking, get_center_regression_net\nfrom model_util import placeholder_inputs, parse_output_to_tensors, get_loss\n\n\ndef get_instance_seg_v2_net(point_cloud, one_hot_vec,\n is_training, bn_decay, end_points):\n ''' 3D instance segmentation PointNet v2 network.\n Input:\n point_cloud: TF tensor in shape (B,N,4)\n frustum point clouds with XYZ and intensity in point channels\n XYZs are in frustum coordinate\n one_hot_vec: TF tensor in shape (B,3)\n length-3 vectors indicating predicted object type\n is_training: TF boolean scalar\n bn_decay: TF float scalar\n end_points: dict\n Output:\n logits: TF tensor in shape (B,N,2), scores for bkg/clutter and object\n end_points: dict\n '''\n\n l0_xyz = tf.slice(point_cloud, [0,0,0], [-1,-1,3])\n l0_points = tf.slice(point_cloud, [0,0,3], [-1,-1,1])\n\n # Set abstraction layers\n l1_xyz, l1_points = pointnet_sa_module_msg(l0_xyz, l0_points,\n 128, [0.2,0.4,0.8], [32,64,128],\n [[32,32,64], [64,64,128], [64,96,128]],\n is_training, bn_decay, scope='layer1')\n l2_xyz, l2_points = pointnet_sa_module_msg(l1_xyz, l1_points,\n 32, [0.4,0.8,1.6], [64,64,128],\n [[64,64,128], [128,128,256], [128,128,256]],\n is_training, bn_decay, scope='layer2')\n l3_xyz, l3_points, _ = pointnet_sa_module(l2_xyz, l2_points,\n npoint=None, radius=None, nsample=None, mlp=[128,256,1024],\n mlp2=None, group_all=True, is_training=is_training,\n bn_decay=bn_decay, scope='layer3')\n\n # Feature Propagation layers\n l3_points = tf.concat([l3_points, tf.expand_dims(one_hot_vec, 1)], axis=2)\n l2_points = pointnet_fp_module(l2_xyz, l3_xyz, l2_points, l3_points,\n [128,128], is_training, bn_decay, scope='fa_layer1')\n l1_points = pointnet_fp_module(l1_xyz, l2_xyz, l1_points, l2_points,\n [128,128], is_training, bn_decay, scope='fa_layer2')\n l0_points = pointnet_fp_module(l0_xyz, l1_xyz,\n tf.concat([l0_xyz,l0_points],axis=-1), l1_points,\n [128,128], is_training, bn_decay, scope='fa_layer3')\n\n # FC layers\n net = tf_util.conv1d(l0_points, 128, 1, padding='VALID', bn=True,\n is_training=is_training, scope='conv1d-fc1', bn_decay=bn_decay)\n end_points['feats'] = net \n net = tf_util.dropout(net, keep_prob=0.7,\n is_training=is_training, scope='dp1')\n logits = tf_util.conv1d(net, 2, 1,\n padding='VALID', activation_fn=None, scope='conv1d-fc2')\n\n return logits, end_points\n\ndef get_3d_box_estimation_v2_net(object_point_cloud, one_hot_vec,\n is_training, bn_decay, end_points):\n ''' 3D Box Estimation PointNet v2 network.\n Input:\n object_point_cloud: TF tensor in shape (B,M,C)\n masked point clouds in object coordinate\n one_hot_vec: TF tensor in shape (B,3)\n length-3 vectors indicating predicted object type\n Output:\n output: TF tensor in shape (B,3+NUM_HEADING_BIN*2+NUM_SIZE_CLUSTER*4)\n including box centers, heading bin class scores and residuals,\n and size cluster scores and residuals\n ''' \n # Gather object points\n batch_size = object_point_cloud.get_shape()[0]\n\n l0_xyz = object_point_cloud\n l0_points = None\n # Set abstraction layers\n l1_xyz, l1_points, l1_indices = pointnet_sa_module(l0_xyz, l0_points,\n npoint=128, radius=0.2, nsample=64, mlp=[64,64,128],\n mlp2=None, group_all=False,\n is_training=is_training, bn_decay=bn_decay, scope='ssg-layer1')\n l2_xyz, l2_points, l2_indices = pointnet_sa_module(l1_xyz, l1_points,\n npoint=32, radius=0.4, nsample=64, mlp=[128,128,256],\n mlp2=None, group_all=False,\n is_training=is_training, bn_decay=bn_decay, scope='ssg-layer2')\n l3_xyz, l3_points, l3_indices = pointnet_sa_module(l2_xyz, l2_points,\n npoint=None, radius=None, nsample=None, mlp=[256,256,512],\n mlp2=None, group_all=True,\n is_training=is_training, bn_decay=bn_decay, scope='ssg-layer3')\n\n # Fully connected layers\n net = tf.reshape(l3_points, [batch_size, -1])\n net = tf.concat([net, one_hot_vec], axis=1)\n net = tf_util.fully_connected(net, 512, bn=True,\n is_training=is_training, scope='fc1', bn_decay=bn_decay)\n net = tf_util.fully_connected(net, 256, bn=True,\n is_training=is_training, scope='fc2', bn_decay=bn_decay)\n\n # The first 3 numbers: box center coordinates (cx,cy,cz),\n # the next NUM_HEADING_BIN*2: heading bin class scores and bin residuals\n # next NUM_SIZE_CLUSTER*4: box cluster scores and residuals\n output = tf_util.fully_connected(net,\n 3+NUM_HEADING_BIN*2+NUM_SIZE_CLUSTER*4, activation_fn=None, scope='fc3')\n return output, end_points\n\n\ndef get_model(point_cloud, one_hot_vec, is_training, bn_decay=None):\n ''' Frustum PointNets model. The model predict 3D object masks and\n amodel bounding boxes for objects in frustum point clouds.\n\n Input:\n point_cloud: TF tensor in shape (B,N,4)\n frustum point clouds with XYZ and intensity in point channels\n XYZs are in frustum coordinate\n one_hot_vec: TF tensor in shape (B,3)\n length-3 vectors indicating predicted object type\n is_training: TF boolean scalar\n bn_decay: TF float scalar\n Output:\n end_points: dict (map from name strings to TF tensors)\n '''\n end_points = {}\n \n # 3D Instance Segmentation PointNet\n logits, end_points = get_instance_seg_v2_net(\\\n point_cloud, one_hot_vec,\n is_training, bn_decay, end_points)\n end_points['mask_logits'] = logits\n\n # Masking\n # select masked points and translate to masked points' centroid\n object_point_cloud_xyz, mask_xyz_mean, end_points = \\\n point_cloud_masking(point_cloud, logits, end_points)\n\n # T-Net and coordinate translation\n center_delta, end_points = get_center_regression_net(\\\n object_point_cloud_xyz, one_hot_vec,\n is_training, bn_decay, end_points)\n stage1_center = center_delta + mask_xyz_mean # Bx3\n end_points['stage1_center'] = stage1_center\n # Get object point cloud in object coordinate\n object_point_cloud_xyz_new = \\\n object_point_cloud_xyz - tf.expand_dims(center_delta, 1)\n\n # Amodel Box Estimation PointNet\n output, end_points = get_3d_box_estimation_v2_net(\\\n object_point_cloud_xyz_new, one_hot_vec,\n is_training, bn_decay, end_points)\n\n # Parse output to 3D box parameters\n end_points = parse_output_to_tensors(output, end_points)\n end_points['center'] = end_points['center_boxnet'] + stage1_center # Bx3\n\n return end_points\n\nif __name__=='__main__':\n with tf.Graph().as_default():\n inputs = tf.zeros((32,1024,4))\n outputs = get_model(inputs, tf.ones((32,3)), tf.constant(True))\n for key in outputs:\n print((key, outputs[key]))\n loss = get_loss(tf.zeros((32,1024),dtype=tf.int32),\n tf.zeros((32,3)), tf.zeros((32,),dtype=tf.int32),\n tf.zeros((32,)), tf.zeros((32,),dtype=tf.int32),\n tf.zeros((32,3)), outputs)\n print(loss)" ]
[ [ "numpy.zeros", "numpy.random.rand" ], [ "tensorflow.Graph", "tensorflow.concat", "tensorflow.constant", "tensorflow.zeros", "tensorflow.slice", "tensorflow.reshape", "tensorflow.expand_dims", "tensorflow.ones" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.10", "1.12", "1.4", "1.5", "1.7", "0.12", "1.0", "1.2" ] } ]
n0whereRuoxi/aima-python
[ "777fa52b73830a534e27b33abf535933ace32a95" ]
[ "agents.py" ]
[ "'''\nThis file holds the agents.\n\n'''\n\nimport random, copy, collections\nfrom objects import Object\nfrom perception import *\nfrom comms import *\nimport numpy as np\nfrom scipy import spatial\nimport uuid\n# ______________________________________________________________________________\n\nclass Agent(Object):\n '''\n An Agent is a subclass of Object with one required slot, .program, which should hold a function that takes one\n argument, the percept, and returns an action. (What counts as a percept or action will depend on the specific\n environment in which the agent exists.) Note that 'program' is a slot, not a method. If it were a method, then\n the program could 'cheat' and look at aspects of the agent. It's not supposed to do that: the program can only\n look at the percepts. An agent program that needs a model of the world (and of the agent itself) will have to\n build and maintain its own model. There is an optional slots, .performance, which is a number giving the\n performance measure of the agent in its environment.\n '''\n def __init__(self):\n def program(percept):\n return raw_input('Percept=%s; action? ' % percept)\n\n self.program = program\n self.alive = True\n self.perceptorTypes = [BasicPerceptor]\n self.holding = []\n\n self.performance = 0\n\n if program is None or not isinstance(program, collections.Callable):\n print(\"Can't find a valid program for {}, falling back to default.\".format(\n self.__class__.__name__))\n\n def program(percept):\n return eval(input('Percept={}; action? '.format(percept)))\n\n blocker = True\n\ndef DebugAgent(agent):\n '''\n Wrap the agent's program to print its input and output. This will let you see what the agent is doing in the\n environment.\n '''\n\n # Mark: Do we just replace the agent parent class with DebugAgent to enable printing?\n old_program = agent.program\n def new_program(percept):\n action = old_program(percept)\n print('%s perceives %s and does %s' % (agent, percept, action))\n return action\n agent.program = new_program\n return agent\n#______________________________________________________________________________\n\nclass XYAgent(Agent):\n holding = []\n heading = (1, 0)\n\nclass RandomXYAgent(XYAgent):\n \"An agent that chooses an action at random, ignoring all percepts.\"\n\n def __init__(self, actions):\n Agent.__init__(self)\n self.program = lambda percept: random.choice(actions)\n\ndef NewRandomXYAgent(debug=False):\n \"Randomly choose one of the actions from the vaccum environment.\"\n # the extra forwards are just to alter the probabilities\n if debug:\n return DebugAgent(RandomXYAgent(['TurnRight', 'TurnLeft', 'Forward', 'Forward', 'Forward', 'Forward', 'Forward', 'Forward']))\n else:\n return RandomXYAgent(['TurnRight', 'TurnLeft', 'Forward', 'Forward', 'Forward', 'Forward', 'Forward', 'Forward'])\n #return RandomXYAgent(['TurnRight', 'TurnLeft', 'Forward', 'Grab', 'Release'])\n\nclass RandomReflexAgent(XYAgent):\n '''This agent takes action based solely on the percept. [Fig. 2.13]'''\n def __init__(self, actions):\n Agent.__init__(self)\n self.actions = actions\n self.perceptorTypes = [DirtyPerceptor, BumpPerceptor]\n def program(percept):\n if percept['Dirty']:\n return \"Grab\"\n elif percept['Bump']:\n return random.choice(['TurnRight','TurnLeft'])\n else:\n return random.choice(actions)\n self.program = program\n\ndef find_nearest(agent_location, dirts):\n if len(dirts) == 1:\n return dirts[0]\n return dirts[spatial.KDTree(np.asarray(dirts)).query(np.asarray(agent_location))[1]]\n\ndef go_to(agent_location, agent_heading, nearest_dirt, bump):\n if agent_heading[0] == 0:\n '''up or down'''\n if (nearest_dirt[1] - agent_location[1]) * agent_heading[1] > 0 and not bump:\n return 'Forward'\n else:\n if nearest_dirt[0] - agent_location[0] > 0:\n '''dirt to right'''\n if agent_heading[1] == 1:\n return 'TurnRight'\n else:\n return 'TurnLeft'\n else:\n if agent_heading[1] == 1:\n return 'TurnLeft'\n else:\n return 'TurnRight'\n else:\n '''left or right'''\n if (nearest_dirt[0] - agent_location[0]) * agent_heading[0] > 0 and not bump:\n return 'Forward'\n else:\n if nearest_dirt[1] - agent_location[1] > 0:\n '''dirt to down'''\n if agent_heading[0] == 1:\n return 'TurnLeft'\n else:\n return 'TurnRight'\n else:\n if agent_heading[0] == 1:\n return 'TurnRight'\n else:\n return 'TurnLeft'\n\nclass GreedyAgentWithRangePerception(XYAgent):\n '''This agent takes action based solely on the percept. [Fig. 2.13]'''\n\n def __init__(self, sensor_radius=10, communication=False):\n Agent.__init__(self)\n self.perceptorTypes = [GPSPerceptor, DirtyPerceptor, BumpPerceptor, CompassPerceptor, RangePerceptor]\n self.communicator = Communicator if communication else None\n self.sensor_r = sensor_radius\n self.comms = {}\n # orientation = {(1,0): 'right', (-1,0): 'left', (0,-1): 'up', (0,1): 'down'}\n # def turn_heading(heading, inc, headings=[(1, 0), (0, 1), (-1, 0), (0, -1)]):\n # \"Return the heading to the left (inc=+1) or right (inc=-1) in headings.\"\n # return headings[(headings.index(heading) + inc) % len(headings)]\n self.dirts = []\n def program(percepts):\n if percepts['Dirty']:\n return 'Grab'\n else:\n # collect percept data\n dirts = [o[1] for o in percepts['Objects'] if o[0]=='Dirt']\n agent_location = (0, 0)\n agent_heading = percepts['Compass']\n # collect communication data\n for comm in self.comms.values():\n dirts += [(o[1][0] + comm['GPS'][0] - percepts['GPS'][0], o[1][1] + comm['GPS'][1] - percepts['GPS'][1]) for o in comm['Objects'] if o[0] == 'Dirt']\n if dirts:\n self.dirts = dirts\n nearest_dirt = find_nearest(agent_location, dirts)\n command = go_to(agent_location, agent_heading, nearest_dirt, percepts['Bump'])\n return command\n return random.choice(['TurnRight', 'TurnLeft', 'Forward', 'Forward', 'Forward', 'Forward'])\n self.program = program\n\ndef NewGreedyAgentWithRangePerception(debug=False, sensor_radius=10):\n \"Randomly choose one of the actions from the vaccum environment.\"\n # the extra forwards are just to alter the probabilities\n if debug:\n return DebugAgent(GreedyAgentWithRangePerception(sensor_radius=sensor_radius))\n else:\n return GreedyAgentWithRangePerception(sensor_radius=sensor_radius)\n\n\nclass GreedyAgent(XYAgent):\n '''This agent takes action based solely on the percept. [Fig. 2.13]'''\n def __init__(self):\n Agent.__init__(self)\n # orientation = {(1,0): 'right', (-1,0): 'left', (0,-1): 'up', (0,1): 'down'}\n # def turn_heading(heading, inc, headings=[(1, 0), (0, 1), (-1, 0), (0, -1)]):\n # \"Return the heading to the left (inc=+1) or right (inc=-1) in headings.\"\n # return headings[(headings.index(heading) + inc) % len(headings)]\n self.perceptorTypes = [DirtyPerceptor, BumpPerceptor, GPSPerceptor, CompassPerceptor, PerfectPerceptor]\n def program(percepts):\n if percepts['Dirty']:\n return \"Grab\"\n else:\n dirts = [o[1] for o in percepts['Objects'] if o[0]=='Dirt']\n agent_location = percepts['GPS']\n agent_heading = percepts['Compass']\n if dirts:\n nearest_dirt = find_nearest(agent_location, dirts)\n command = go_to(agent_location, agent_heading, nearest_dirt, percepts['Bump'])\n return command\n return ''\n self.program = program\n\n\ndef NewRandomReflexAgent(debug=False):\n \"If the cell is dirty, Grab the dirt; otherwise, randomly choose one of the actions from the vaccum environment.\"\n # the extra forwards are just to alter the probabilities\n if debug:\n return DebugAgent(RandomReflexAgent(['TurnRight', 'TurnLeft', 'Forward', 'Forward', 'Forward', 'Forward', 'Forward', 'Forward']))\n else:\n return RandomReflexAgent(['TurnRight', 'TurnLeft', 'Forward', 'Forward', 'Forward', 'Forward', 'Forward', 'Forward'])\n\nclass SimpleReflexAgent(XYAgent):\n '''This agent takes action based solely on the percept. [Fig. 2.13]'''\n\n def __init__(self, rules, interpret_input):\n Agent.__init__(self)\n def program(percept):\n state = interpret_input(percept)\n rule = rule_match(state, rules)\n action = rule.action\n return action\n self.program = program\n\nclass ReflexAgentWithState(XYAgent):\n '''This agent takes action based on the percept and state. [Fig. 2.16]'''\n\n def __init__(self, rules, udpate_state):\n Agent.__init__(self)\n state, action = None, None\n def program(percept):\n state = update_state(state, action, percept)\n rule = rule_match(state, rules)\n action = rule.action\n return action\n self.program = program\n\n#______________________________________________________________________________\n" ]
[ [ "numpy.asarray" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
MSchauperl/propertyestimator
[ "9a67cb61498024c511f9bbe55536ac8e1a3c93be" ]
[ "propertyestimator/utils/serialization.py" ]
[ "\"\"\"\nA collection of classes which aid in serializing data types.\n\"\"\"\n\nimport importlib\nimport inspect\nimport json\nfrom abc import ABC, abstractmethod\nfrom enum import Enum\n\nimport numpy as np\n\nfrom propertyestimator import unit\nfrom propertyestimator.utils.quantities import EstimatedQuantity\n\n\ndef _type_string_to_object(type_string):\n\n if type_string == 'propertyestimator.unit.Unit':\n return unit.Unit\n if type_string == 'propertyestimator.unit.Quantity':\n return unit.Quantity\n\n last_period_index = type_string.rfind('.')\n\n if last_period_index < 0 or last_period_index == len(type_string) - 1:\n raise ValueError('The type string is invalid - it should be of the form '\n 'module_path.class_name: {}'.format(type_string))\n\n module_name = type_string[0:last_period_index]\n module = importlib.import_module(module_name)\n\n class_name = type_string[last_period_index + 1:]\n\n if class_name == 'NoneType':\n return None\n\n class_name_split = class_name.split('->')\n class_object = module\n\n while len(class_name_split) > 0:\n class_name_current = class_name_split.pop(0)\n class_object = getattr(class_object, class_name_current)\n\n return class_object\n\n\ndef _type_to_type_string(object_type):\n \"\"\"Converts a type to a serializable string.\n\n Parameters\n ----------\n object_type: type\n The type to convert.\n\n Returns\n -------\n str\n The converted type.\n \"\"\"\n\n if (issubclass(object_type, unit.Unit) or\n f'{object_type.__module__}.{object_type.__qualname__}' ==\n 'pint.quantity.build_quantity_class.<locals>.Unit'):\n\n return 'propertyestimator.unit.Unit'\n if (issubclass(object_type, unit.Quantity) or\n f'{object_type.__module__}.{object_type.__qualname__}' ==\n 'pint.quantity.build_quantity_class.<locals>.Quantity'):\n\n return 'propertyestimator.unit.Quantity'\n\n qualified_name = object_type.__qualname__\n qualified_name = qualified_name.replace('.', '->')\n\n return_value = '{}.{}'.format(object_type.__module__, qualified_name)\n return return_value\n\n\ndef serialize_quantity(quantity):\n \"\"\"Serializes a propertyestimator.unit.Quantity into a dictionary of the form\n `{'value': quantity.value_in_unit(quantity.unit), 'unit': quantity.unit}`\n\n Parameters\n ----------\n quantity : unit.Quantity\n The quantity to serialize\n\n Returns\n -------\n dict of str and str\n A dictionary representation of a propertyestimator.unit.Quantity\n with keys of {\"value\", \"unit\"}\n \"\"\"\n\n value = quantity.magnitude\n return {'value': value, 'unit': str(quantity.units)}\n\n\ndef deserialize_quantity(serialized):\n \"\"\"Deserialize a propertyestimator.unit.Quantity from a dictionary.\n\n Parameters\n ----------\n serialized : dict of str and str\n A dictionary representation of a propertyestimator.unit.Quantity\n which must have keys {\"value\", \"unit\"}\n\n Returns\n -------\n propertyestimator.unit.Quantity\n The deserialized quantity.\n \"\"\"\n\n if '@type' in serialized:\n serialized.pop('@type')\n\n value_unit = unit.dimensionless\n\n if serialized['unit'] is not None:\n value_unit = unit(serialized['unit'])\n\n return serialized['value'] * value_unit\n\n\ndef deserialize_estimated_quantity(quantity_dictionary):\n \"\"\"\n Deserializes an EstimatedQuantity.\n\n Parameters\n ----------\n quantity_dictionary : dict of str and Any\n Serialized representation of an EstimatedQuantity, generated by the\n `EstimatedQuantity.__getstate__` method\n\n Returns\n -------\n EstimatedQuantity\n \"\"\"\n\n if '@type' in quantity_dictionary:\n quantity_dictionary.pop('@type')\n\n return_object = EstimatedQuantity(unit.Quantity(0.0), unit.Quantity(0.0), 'empty_source')\n return_object.__setstate__(quantity_dictionary)\n\n return return_object\n\n\ndef serialize_enum(enum):\n\n if not isinstance(enum, Enum):\n raise ValueError('{} is not an Enum'.format(type(enum)))\n\n return {\n 'value': enum.value\n }\n\n\ndef deserialize_enum(enum_dictionary):\n\n if '@type' not in enum_dictionary:\n\n raise ValueError('The serialized enum dictionary must include'\n 'which type the enum is.')\n\n if 'value' not in enum_dictionary:\n\n raise ValueError('The serialized enum dictionary must include'\n 'the enum value.')\n\n enum_type_string = enum_dictionary['@type']\n enum_value = enum_dictionary['value']\n\n enum_class = _type_string_to_object(enum_type_string)\n\n if not issubclass(enum_class, Enum):\n raise ValueError('<{}> is not an Enum'.format(enum_class))\n\n return enum_class(enum_value)\n\n\ndef serialize_set(set_object):\n\n if not isinstance(set_object, set):\n raise ValueError('{} is not a set'.format(type(set)))\n\n return {\n 'value': list(set_object)\n }\n\n\ndef deserialize_set(set_dictionary):\n\n if 'value' not in set_dictionary:\n\n raise ValueError('The serialized set dictionary must include'\n 'the value of the set.')\n\n set_value = set_dictionary['value']\n\n if not isinstance(set_value, list):\n\n raise ValueError('The value of the serialized set must be a list.')\n\n return set(set_value)\n\n\ndef serialize_frozen_set(set_object):\n\n if not isinstance(set_object, frozenset):\n raise ValueError('{} is not a frozenset'.format(type(frozenset)))\n\n return {\n 'value': list(set_object)\n }\n\n\ndef deserialize_frozen_set(set_dictionary):\n\n if 'value' not in set_dictionary:\n\n raise ValueError('The serialized frozenset dictionary must include'\n 'the value of the set.')\n\n set_value = set_dictionary['value']\n\n if not isinstance(set_value, list):\n raise ValueError('The value of the serialized set must be a list.')\n\n return frozenset(set_value)\n\n\nclass TypedJSONEncoder(json.JSONEncoder):\n\n _natively_supported_types = [\n dict, list, tuple, str, int, float, bool\n ]\n\n _custom_supported_types = {\n Enum: serialize_enum,\n unit.Quantity: serialize_quantity,\n set: serialize_set,\n frozenset: serialize_frozen_set,\n np.float16: lambda x: {'value': float(x)},\n np.float32: lambda x: {'value': float(x)},\n np.float64: lambda x: {'value': float(x)},\n np.int32: lambda x: {'value': int(x)},\n np.int64: lambda x: {'value': int(x)},\n np.ndarray: lambda x: {'value': x.tolist()}\n }\n\n def default(self, value_to_serialize):\n\n if value_to_serialize is None:\n return None\n\n type_to_serialize = type(value_to_serialize)\n\n if type_to_serialize in TypedJSONEncoder._natively_supported_types:\n # If the value is a native type, then let the default serializer\n # handle it.\n return super(TypedJSONEncoder, self).default(value_to_serialize)\n\n # Otherwise, we need to add a @type attribute to it.\n type_tag = _type_to_type_string(type_to_serialize)\n serializable_dictionary = {}\n\n if type_tag == 'propertyestimator.unit.Unit':\n type_to_serialize = unit.Unit\n if type_tag == 'propertyestimator.unit.Quantity':\n type_to_serialize = unit.Quantity\n\n custom_encoder = None\n\n for encoder_type in TypedJSONEncoder._custom_supported_types:\n\n if isinstance(encoder_type, str):\n\n qualified_name = type_to_serialize.__qualname__\n qualified_name = qualified_name.replace('.', '->')\n\n if encoder_type != qualified_name:\n continue\n\n elif not issubclass(type_to_serialize, encoder_type):\n continue\n\n custom_encoder = TypedJSONEncoder._custom_supported_types[encoder_type]\n break\n\n if custom_encoder is not None:\n\n try:\n serializable_dictionary = custom_encoder(value_to_serialize)\n\n except Exception as e:\n\n raise ValueError('{} ({}) could not be serialized '\n 'using a specialized custom encoder: {}'.format(value_to_serialize,\n type_to_serialize, e))\n\n elif hasattr(value_to_serialize, '__getstate__'):\n\n try:\n serializable_dictionary = value_to_serialize.__getstate__()\n\n except Exception as e:\n\n raise ValueError('{} ({}) could not be serialized '\n 'using its __getstate__ method: {}'.format(value_to_serialize,\n type_to_serialize, e))\n\n else:\n\n raise ValueError('Objects of type {} are not serializable, please either'\n 'add a __getstate__ method, or add the object to the list'\n 'of custom supported types.'.format(type_to_serialize))\n\n serializable_dictionary['@type'] = type_tag\n return serializable_dictionary\n\n\nclass TypedJSONDecoder(json.JSONDecoder):\n\n def __init__(self, *args, **kwargs):\n json.JSONDecoder.__init__(self, object_hook=self.object_hook, *args, **kwargs)\n\n _custom_supported_types = {\n Enum: deserialize_enum,\n unit.Quantity: deserialize_quantity,\n EstimatedQuantity: deserialize_estimated_quantity,\n set: deserialize_set,\n frozenset: deserialize_frozen_set,\n np.float16: lambda x: np.float16(x['value']),\n np.float32: lambda x: np.float32(x['value']),\n np.float64: lambda x: np.float64(x['value']),\n np.int32: lambda x: np.int32(x['value']),\n np.int64: lambda x: np.int64(x['value']),\n np.ndarray: lambda x: np.array(x['value'])\n }\n\n @staticmethod\n def object_hook(object_dictionary):\n\n if '@type' not in object_dictionary:\n return object_dictionary\n\n type_string = object_dictionary['@type']\n class_type = _type_string_to_object(type_string)\n\n deserialized_object = None\n\n custom_decoder = None\n\n for decoder_type in TypedJSONDecoder._custom_supported_types:\n\n if isinstance(decoder_type, str):\n\n if decoder_type != class_type.__qualname__:\n continue\n\n elif not issubclass(class_type, decoder_type):\n continue\n\n custom_decoder = TypedJSONDecoder._custom_supported_types[decoder_type]\n break\n\n if custom_decoder is not None:\n\n try:\n deserialized_object = custom_decoder(object_dictionary)\n\n except Exception as e:\n\n raise ValueError('{} ({}) could not be deserialized '\n 'using a specialized custom decoder: {}'.format(object_dictionary,\n type(class_type), e))\n\n elif hasattr(class_type, '__setstate__'):\n\n try:\n\n class_init_signature = inspect.signature(class_type)\n\n for parameter in class_init_signature.parameters.values():\n\n if (parameter.default != inspect.Parameter.empty or\n parameter.kind == inspect.Parameter.VAR_KEYWORD or\n parameter.kind == inspect.Parameter.VAR_POSITIONAL):\n\n continue\n\n raise ValueError('Cannot deserialize objects which have '\n 'non-optional arguments {} in the constructor: {}.'.format(parameter.name,\n class_type))\n\n deserialized_object = class_type()\n deserialized_object.__setstate__(object_dictionary)\n\n except Exception as e:\n\n raise ValueError('{} ({}) could not be deserialized '\n 'using its __setstate__ method: {}'.format(object_dictionary,\n type(class_type), e))\n\n else:\n\n raise ValueError('Objects of type {} are not deserializable, please either'\n 'add a __setstate__ method, or add the object to the list'\n 'of custom supported types.'.format(type(class_type)))\n\n return deserialized_object\n\n\nclass TypedBaseModel(ABC):\n \"\"\"An abstract base class which represents any object which\n can be serialized to JSON.\n\n JSON produced using this class will include extra @type tags\n for any non-primitive typed values (e.g not a str, int...),\n which ensure that the correct class structure is correctly\n reproduced on deserialization.\n\n EXAMPLE\n\n It is a requirement that any classes inheriting from this one\n must implement a valid `__getstate__` and `__setstate__` method,\n as these are what determines the structure of the serialized\n output.\n \"\"\"\n\n def json(self):\n \"\"\"Creates a JSON representation of this class.\n\n Returns\n -------\n str\n The JSON representation of this class.\n \"\"\"\n json_string = json.dumps(self, cls=TypedJSONEncoder)\n return json_string\n\n @classmethod\n def parse_json(cls, string_contents, encoding='utf8'):\n \"\"\"Parses a typed json string into the corresponding class\n structure.\n\n Parameters\n ----------\n string_contents: str or bytes\n The typed json string.\n encoding: str\n The encoding of the `string_contents`.\n\n Returns\n -------\n Any\n The parsed class.\n \"\"\"\n return_object = json.loads(string_contents, encoding=encoding, cls=TypedJSONDecoder)\n return return_object\n\n @abstractmethod\n def __getstate__(self):\n \"\"\"Returns a dictionary representation of this object.\n\n Returns\n -------\n dict of str, Any\n The dictionary representation of this object.\n \"\"\"\n pass\n\n @abstractmethod\n def __setstate__(self, state):\n \"\"\"Sets the fields of this object from its dictionary representation.\n\n Parameters\n ----------\n state: dict of str, Any\n The dictionary representation of the object.\n \"\"\"\n pass\n" ]
[ [ "numpy.float16", "numpy.int32", "numpy.int64", "numpy.float64", "numpy.float32", "numpy.array" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
eric-kaufmann/ood_approach
[ "0ffff5e0cfc298557ddb7f1d773e0c4ebd21df48" ]
[ "train.py" ]
[ "import torch\nfrom torch.utils.tensorboard import SummaryWriter\nimport sys\nimport os\nsys.path.append(os.getcwd())\n\nfrom loss_functions import RBFClassifier, AAML, CircleLoss, Model, ModelArc\nfrom data_load import get_loader, get_channels, get_num_classes\n\nimport numpy as np\nimport torch.optim as optim\nimport torch\nimport torch.nn as nn\nfrom pytorchcv.model_provider import get_model\nimport matplotlib.pyplot as plt\nimport timeit\nimport argparse\n\ndef main():\n # parsing arguments\n args = argParser()\n model = args.model.replace(\"'\", \"\")\n dataset = args.dataset.replace(\"'\", \"\")\n loss_func_string = args.loss.replace(\"'\", \"\")\n opti_name = args.opti.replace(\"'\", \"\")\n name = args.name.replace(\"'\", \"\")\n batch_size= args.batch_size\n embs = args.embs\n epochs = args.epochs\n learning_rate = args.lr\n\n sched_name = \"ca\"\n\n # setting paths\n fullname = loss_func_string + \"_\" + model + \"_\" + dataset + \"_\" + str(embs) + \"embs_\" + opti_name + \"_\" + str(epochs) + \"ep_\" + str(batch_size) + \"bs_\" + str(learning_rate) + \"lr_\" + name\n\n PATH = \"./model/\" + fullname + \".pth\"\n RUN_PATH = \"./runs/\" + fullname\n\n \n # print props\n print(f\"model: {model}\")\n print(f\"dataset: {dataset}\")\n print(f\"loss function: {loss_func_string}\")\n print(f\"path: {PATH}\")\n print(f\"batch size: {batch_size}\")\n print(f\"# embeddings: {embs}\")\n print(f\"# epochs: {epochs}\")\n print(f\"optimizer: {opti_name}\")\n \n\n # define device\n use_cuda = torch.cuda.is_available()\n device = torch.device(\"cuda\" if use_cuda else \"cpu\")\n\n # get dataloader\n trainloader, testloader = get_loader(dataset, bs=batch_size)\n in_channels = get_channels(dataset)\n num_classes = get_num_classes(dataset)\n \n # define model\n pretrain = get_model(model, num_classes=embs,\n in_channels=in_channels)\n pretrain.output = nn.BatchNorm1d(512)\n if loss_func_string == \"softmax\":\n classifier = nn.Linear(embs, num_classes, bias=False)\n net = Model(pretrain, classifier)\n elif loss_func_string == \"arcface\":\n pretrain = get_pretrain()\n classifier = AAML(in_features=embs, out_features=num_classes, margin=0.5, scale=64)\n net = ModelArc(pretrain, classifier)\n elif loss_func_string == \"rbf\":\n classifier = RBFClassifier(embs, num_classes, scale=4, gamma=1.6, cos_sim=True)\n net = Model(pretrain, classifier)\n elif loss_func_string == \"circle\":\n pretrain = get_pretrain()\n classifier = CircleLoss(embs, num_classes, margin=0.7, scale=64)\n net = ModelArc(pretrain, classifier)\n else:\n raise ValueError(\"Loss function not found!\")\n net.to(device)\n\n # define optimizer and scheduler\n if opti_name == \"adam\":\n opti = optim.Adam(net.parameters(), lr=learning_rate)\n elif opti_name == \"sgd\":\n opti = optim.SGD(net.parameters(), learning_rate, momentum=0.9, weight_decay=5e-4)\n else:\n raise ValueError(\"Optimizer not found!\")\n\n # sched1 -> warmup\n sched1 = torch.optim.lr_scheduler.OneCycleLR(\n opti, \n max_lr=learning_rate*10, \n steps_per_epoch=10, \n epochs=10,\n anneal_strategy='linear'\n )\n \n # sched2 -> real scheduler (ms = multi step; ca = cosine annealing)\n if sched_name == \"ms\":\n sched2 = torch.optim.lr_scheduler.MultiStepLR(\n opti, \n [30,50],\n gamma=0.1\n )\n elif sched_name == \"ca\":\n sched2 = torch.optim.lr_scheduler.CosineAnnealingLR(opti, T_max=epochs-10)\n\n # define loss function\n loss_func = nn.CrossEntropyLoss()\n\n # train and test network\n save_epoch_acc = np.array([])\n save_epoch_loss = np.array([])\n tb = SummaryWriter(RUN_PATH)\n temp_acc = 0\n\n\n for epoch in range(epochs):\n start = timeit.default_timer()\n ep_acc = 0\n ep_loss = 0\n for idx, data in enumerate(trainloader):\n inp, label = data\n inp, label = inp.to(device), label.to(device)\n\n if (loss_func_string==\"arcface\") | (loss_func_string==\"circle\"):\n pred = net(inp, label) \n else:\n pred = net(inp)\n \n opti.zero_grad()\n loss = loss_func(pred, label)\n loss.backward()\n opti.step()\n\n ep_loss += loss.item()\n ep_acc += torch.sum(torch.argmax(pred, dim=1)\n == label).cpu()/len(label)\n \n stop = stop = timeit.default_timer()\n print(\"Epoch: {} | Loss: {:.5f} | Acc: {:.4} | Time: {:.5f}\".format(epoch+1 ,ep_loss/len(trainloader), ep_acc/len(trainloader), stop-start))\n save_epoch_acc = np.append(save_epoch_acc, ep_acc/len(trainloader))\n save_epoch_loss = np.append(save_epoch_loss, ep_loss/len(trainloader))\n \n tb.add_scalar(\"Loss/Train\", ep_loss/len(trainloader), epoch)\n tb.add_scalar(\"Accuracy/Train\", ep_acc/len(trainloader), epoch)\n\n # test on testdata\n with torch.no_grad():\n net.eval()\n ep_test_acc = 0\n ep_test_loss = 0\n for idx, data in enumerate(testloader):\n inp, label = data\n inp, label = inp.to(device), label.to(device)\n\n if (loss_func_string==\"arcface\") | (loss_func_string==\"circle\"):\n pred = net(inp, label)\n else:\n pred = net(inp)\n\n loss = loss_func(pred, label)\n ep_test_loss += loss.item()\n\n # Berechne die Accuracy des Batches\n ep_test_acc += torch.sum(torch.argmax(pred, dim=1)\n == label).cpu()/len(label)\n\n loss_res = ep_test_loss/len(testloader)\n acc_res = ep_test_acc/len(testloader)\n print(\n \" Results on Test-Data: loss: {:.5f} acc: {:.4}\".format(loss_res, acc_res))\n tb.add_scalar(\"Loss/Test\", loss_res, epoch)\n tb.add_scalar(\"Accuracy/Test\", acc_res, epoch)\n \n if(acc_res>temp_acc):\n print(\" New Best!\")\n torch.save({\n 'epoch': epoch,\n 'model_state_dict': net.state_dict(),\n 'optimizer_state_dict': opti.state_dict(),\n 'loss': loss_res,\n 'acc': acc_res,\n }, PATH)\n temp_acc = acc_res\n\n net.train()\n\n lr = get_lr(opti)\n tb.add_scalar(\"LearningRate\", lr, epoch) \n if epoch<10:\n sched1.step()\n else:\n sched2.step()\n tb.close()\n\n print(f\"Best Accuracy on test data: {temp_acc}\")\n\n\n#########################\n### SUPPORT FUNCTIONS ###\n#########################\n\ndef argParser():\n parser = argparse.ArgumentParser(description='PyTorch Trainer')\n parser.add_argument('--batch-size', type=int, default=64,\n help='input batch size (default: 64)')\n parser.add_argument('--epochs', type=int, default=3,\n help='number of epochs to train (default: 3)')\n parser.add_argument('--embs', type=int, default=128,\n help='number of embeddings (default: 128)')\n parser.add_argument('--lr', type=float, default=0.000035,\n help='learning rate (default: 0.000035)')\n parser.add_argument('--model', type=ascii, default=\"resnet10\",\n help='select pytorchcv model (default: \"resnet10\")')\n parser.add_argument('--loss', type=ascii, default=\"softmax\",\n help='select loss function model (default: \"softmax\")')\n parser.add_argument('--dataset', type=ascii, default=\"mnist\",\n help='select dataset (cifar10, mnist) (default: \"mnist\")')\n parser.add_argument('--name', type=ascii, default=\"\",\n help='adding a specific description (default: \"\")')\n parser.add_argument('--opti', type=ascii, default=\"adam\",\n help='optimizer (default: adam)')\n return parser.parse_args()\n\n\ndef get_lr(optimizer):\n \"\"\"get learning rate from optimizer\n\n Args:\n optimizer (torch.optim.Optimizer): the optimizer\n\n Returns:\n float: the learning rate\n \"\"\"\n for param_group in optimizer.param_groups:\n return param_group['lr']\n\ndef plot_training_progress(epochs, loss, accuracy, name):\n \"\"\"create training progress plots for accuracy and loss if tensorboard ins't available.\n\n Args:\n epochs (int): number of epochs\n loss (array): array of losses from error function from every epoch\n accuracy (array): array of accuracys for every epoch\n name (str): name your files\n \"\"\"\n epochs = range(epochs)\n\n # accuracy\n plt.plot(epochs, accuracy, 'r-')\n plt.title('Accuracy')\n plt.xlabel('Epochs')\n plt.ylabel('Accuracy')\n plt.savefig(\"./pics/\"+name+\"_acc.png\")\n plt.clf()\n\n # loss\n plt.plot(epochs, loss, 'b-')\n plt.title('Loss')\n plt.xlabel('Epochs')\n plt.ylabel('MSE')\n plt.savefig(\"./pics/\"+name+\"_loss.png\")\n plt.clf()\n\ndef get_pretrain():\n \"\"\"get pretrain own trained pretrain\n\n Returns:\n torch.nn.Module: pretrained model\n \"\"\"\n pretrain = get_model(\"resnet18\", num_classes=512, in_channels=3)\n pretrain.output = nn.BatchNorm1d(512)\n classifier = nn.Linear(512,10, bias=False)\n model = Model(pretrain=pretrain, classifier=classifier)\n path=\"./model/softmax_resnet18_mnist_512embs_sgd_20ep_64bs_0.01lr.pt\"\n model.load_state_dict(torch.load(path)[\"model_state_dict\"])\n return model.pretrain\n\n\nif __name__ == \"__main__\":\n main()" ]
[ [ "torch.optim.lr_scheduler.CosineAnnealingLR", "torch.load", "matplotlib.pyplot.plot", "torch.no_grad", "torch.utils.tensorboard.SummaryWriter", "torch.cuda.is_available", "torch.device", "torch.optim.lr_scheduler.MultiStepLR", "torch.nn.CrossEntropyLoss", "torch.optim.lr_scheduler.OneCycleLR", "torch.nn.BatchNorm1d", "matplotlib.pyplot.title", "matplotlib.pyplot.savefig", "torch.nn.Linear", "numpy.array", "matplotlib.pyplot.ylabel", "matplotlib.pyplot.clf", "matplotlib.pyplot.xlabel", "torch.argmax" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
rdgozum/dexpression-pytorch
[ "6aac1fffee31062afda5fb1403f328d9c2502137" ]
[ "dexpression_pytorch/pipelines/network.py" ]
[ "import torch\nfrom dexpression_pytorch.cnn_model.dexpression import Dexpression\n\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n\n\ndef initialize():\n \"\"\"\n Loads model parameters into cuda.\n\n Returns\n -------\n model : object\n The convolutional neural network to be trained.\n \"\"\"\n\n model = Dexpression()\n model = model.to(device)\n\n return model\n" ]
[ [ "torch.cuda.is_available" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
caodoanh2001/uit-mmf
[ "60359f6083b89b442c383dc7eee888e7fbf0c65f" ]
[ "pythia/utils/objects_to_byte_tensor.py" ]
[ "\n# Adopted from\n# https://github.com/pytorch/fairseq/blob/master/fairseq/distributed_utils.py\n\nimport pickle\nimport torch\n\nMAX_SIZE_LIMIT = 65533\nBYTE_SIZE = 256\n\n\ndef enc_obj2bytes(obj, max_size=4094):\n \"\"\"\n Encode Python objects to PyTorch byte tensors\n \"\"\"\n assert max_size <= MAX_SIZE_LIMIT\n byte_tensor = torch.zeros(max_size, dtype=torch.uint8)\n\n obj_enc = pickle.dumps(obj)\n obj_size = len(obj_enc)\n if obj_size > max_size:\n raise Exception(\n 'objects too large: object size {}, max size {}'.format(\n obj_size, max_size\n )\n )\n\n byte_tensor[0] = obj_size // 256\n byte_tensor[1] = obj_size % 256\n byte_tensor[2:2+obj_size] = torch.ByteTensor(list(obj_enc))\n return byte_tensor\n\n\ndef dec_bytes2obj(byte_tensor, max_size=4094):\n \"\"\"\n Decode PyTorch byte tensors to Python objects\n \"\"\"\n assert max_size <= MAX_SIZE_LIMIT\n\n obj_size = byte_tensor[0].item() * 256 + byte_tensor[1].item()\n obj_enc = bytes(byte_tensor[2:2+obj_size].tolist())\n obj = pickle.loads(obj_enc)\n return obj\n\n\nif __name__ == '__main__':\n test_obj = [1, '2', {3: 4}, [5]]\n test_obj_bytes = enc_obj2bytes(test_obj)\n test_obj_dec = dec_bytes2obj(test_obj_bytes)\n print(test_obj_dec == test_obj)\n" ]
[ [ "torch.zeros" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
timchiu9781/Tomofun
[ "3f7abcb7fc1cc8200ec3fdff62bd51fbaada4126" ]
[ "01-byoc/code/workflow.py" ]
[ "import os\nimport time\nimport copy\nimport datetime\nimport json\nfrom argparse import ArgumentParser\nfrom pprint import pformat\nimport logging\n\nimport shutil\nimport torch\nimport numpy as np\nfrom torch.utils.tensorboard import SummaryWriter\n\nfrom utils import plot_confusion_matrix\nfrom dataset import SoundDataset\nfrom dataloader import SoundDataLoader\nfrom config import ParameterSetting\nfrom models import VGGish, EfficientNet_model\nfrom metrics import accuracy, f1, roc_auc, cfm, classification_report\nfrom losses import CrossEntropyLoss\nfrom ops import Adam, StepLR\nfrom tqdm import tqdm\nfrom sklearn.preprocessing import label_binarize\n\nimport pkbar\n\nlogger = logging.getLogger(__file__)\n\n\ndef get_optim_scheduler(params, model):\n # optimizer\n if params.optimizer == \"adam\":\n optimizer = Adam(model.parameters(), lr=params.lr)\n # scheduler\n if params.scheduler == \"steplr\":\n scheduler = StepLR(optimizer, step_size=int(params.epochs*0.8), gamma=0.1)\n return optimizer, scheduler\n\n\ndef get_folder_name(params):\n # description of model and folder name\n now = datetime.datetime.now()\n folder_name = now.strftime(\"%Y-%m-%d-%H_%M\")\n model_name = \"{0:}_lr-{1:.0e}_optim-{2:}_scheduler-{3:}\".format(\n folder_name, params.lr,\n params.optimizer, params.scheduler)\n save_model_path = os.path.join(params.save_root, \"snapshots\", model_name)\n return save_model_path, model_name\n\n\ndef train_model(model, params, dataloaders, dataset_sizes, all_params):\n ####################\n # training setting #\n ####################\n\n optimizer, scheduler = get_optim_scheduler(params, model)\n save_model_path, model_name = get_folder_name(params)\n\n if not os.path.exists(save_model_path):\n os.mkdir(save_model_path)\n print(\"create folder: {}\".format(save_model_path))\n\n log_path = os.path.join(params.save_root, \"log\", model_name)\n if not os.path.exists(log_path):\n os.mkdir(log_path)\n\n writer = SummaryWriter(log_path)\n\n device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n\n print('Now using device = ', device)\n # print('params = ', all_params)\n\n since = time.time()\n\n best_f1 = 0.0\n best_auc = 0.0\n best_true, best_pred, best_prob = [], [], []\n\n\n\n print('Calculating mean and std')\n\n i = 0\n\n for data in tqdm(dataloaders['train']):\n # Get the input features and target labels, and put them on the GPU\n inputs, labels = data[0].to(device), data[1].to(device)\n inputs_stack = inputs.cpu() if i == 0 else torch.vstack((inputs_stack, inputs.cpu()))\n i += 1\n\n\n mean_train, std_train = torch.mean(inputs_stack, dim=0), torch.std(inputs_stack, dim=0)\n\n np.savez(os.path.join(save_model_path, 'mean_std.npz'), mean=mean_train, std=std_train)\n\n print('Tensorboard log: ' + 'tensorboard --logdir=/' + str(log_path) + '/--port 6099')\n\n \n \n\n ####################\n # start training #\n ####################\n\n last_model_path = None \n for epoch in range(params.epochs):\n print('Epoch {}/{}'.format(epoch+1, params.epochs))\n print('-' * 10)\n # Each epoch has a training and validation phase\n for phase in ['train', 'val']:\n # set model to train/eval model\n model.train() if phase == 'train' else model.eval()\n # set progress bar\n kbar = pkbar.Kbar(target=(dataset_sizes[phase]//params.batch_size)+1, width=8)\n\n running_loss = 0.0\n # prediction and groundtruth label\n y_true, y_pred, y_prob = [], [], []\n start_time = time.time()\n # iterative training\n for batch_idx, (inputs, labels) in enumerate(dataloaders[phase]):\n inputs = inputs.to(device)\n labels = labels.to(device)\n\n inputs = (inputs - mean_train.to(device)) / std_train.to(device)\n\n optimizer.zero_grad()\n\n with torch.set_grad_enabled(phase == 'train'):\n outputs = model(inputs)\n _, preds = torch.max(outputs, 1)\n # compute loss\n loss = CrossEntropyLoss(outputs, labels)\n # backpropagation\n if phase == 'train':\n loss.backward()\n optimizer.step()\n else:\n Binarize_Y_test = label_binarize(labels.cpu().numpy(), classes=list(range(params.num_class)))\n n_classes = Binarize_Y_test.shape[1]\n if batch_idx == 0:\n stacked_outputs = outputs.cpu().numpy()\n stacked_Binarize_Y_test = Binarize_Y_test\n else:\n stacked_outputs = np.vstack((stacked_outputs, outputs.cpu().numpy()))\n stacked_Binarize_Y_test = np.vstack((stacked_Binarize_Y_test, Binarize_Y_test))\n\n gt_label_in_batch = labels.data.cpu().detach().numpy()\n running_loss += loss.item() * inputs.size(0)\n\n y_true.extend(gt_label_in_batch)\n y_pred.extend(preds.cpu().detach().numpy())\n outputs = torch.nn.functional.softmax(outputs, dim=1)\n y_prob.extend(outputs.cpu().detach().numpy())\n\n if phase == 'train':\n kbar.update(batch_idx, values=[(\"train loss in batch\", loss)])\n writer.add_scalar('train loss', loss, epoch*len(dataloaders[phase]) + batch_idx)\n else:\n kbar.update(batch_idx, values=[(\"val loss in batch\", loss)])\n writer.add_scalar('val loss', loss, epoch*len(dataloaders[phase]) + batch_idx)\n \n \n # finish an epoch\n time_elapsed = time.time() - start_time\n print()\n print(\"finish this epoch in {:.0f}m {:.0f}s\".format(time_elapsed // 60, time_elapsed % 60))\n # compute classification results in an epoch\n epoch_loss = running_loss / dataset_sizes[phase]\n epoch_acc = accuracy(y_true, y_pred)\n epoch_f1 = f1(y_true, y_pred)\n# epoch_roc_auc = roc_auc(y_true, y_prob) # remove to avoid error occurrs in sparse input \n\n if phase == 'train':\n scheduler.step()\n kbar.add(1, values=[(\"train epoch loss\", epoch_loss), (\"train acc\", epoch_acc), (\"train f1\", epoch_f1)])\n writer.add_scalar('train accuracy', epoch_acc, epoch)\n writer.add_scalar('train f1 score', epoch_f1, epoch)\n else:\n kbar.add(1, values=[(\"val epoch loss\", epoch_loss), (\"val acc\", epoch_acc), (\"val f1\", epoch_f1)])\n writer.add_scalar('val accuracy', epoch_acc, epoch)\n writer.add_scalar('val f1 score', epoch_f1, epoch)\n\n # save model if f1 and precision are all the best\n if epoch_f1 > best_f1 :\n best_f1 = epoch_f1 if epoch_f1 > best_f1 else best_f1\n best_true = y_true\n best_pred = y_pred\n best_prob = y_prob\n wpath = os.path.join(save_model_path, 'epoch_{:03d}_valloss_{:.4f}_valacc_{:.4f}_f1_{:.4f}.pkl'.format(epoch+1, epoch_loss, epoch_acc, epoch_f1))\n #torch.save(model.state_dict(), wpath)\n torch.save(model, wpath)\n last_model_path = wpath\n print(\"=== save weight \" + wpath + \" ===\")\n print()\n\n ######################################AUC Calculate############################\n from sklearn.metrics import roc_auc_score\n from sklearn.metrics import roc_curve, auc\n # Compute ROC curve and ROC area for each class\n\n fpr = dict()\n tpr = dict()\n roc_auc = dict()\n for class_i in range(n_classes):\n fpr[class_i], tpr[class_i], _ = roc_curve(stacked_Binarize_Y_test[:, class_i], stacked_outputs[:, class_i])\n roc_auc[class_i] = auc(fpr[class_i], tpr[class_i])\n\n # Compute micro-average ROC curve and ROC area\n fpr[\"micro\"], tpr[\"micro\"], _ = roc_curve(stacked_Binarize_Y_test.ravel(), stacked_outputs.ravel())\n roc_auc[\"micro\"] = auc(fpr[\"micro\"], tpr[\"micro\"])\n \n ######################################AUC Calculate############################\n\n if epoch == 0:\n roc_auc_all = roc_auc\n \n else:\n for roc_auc_i in roc_auc.keys():\n temp_list = [roc_auc_all[roc_auc_i]]\n temp_list.append(roc_auc[roc_auc_i])\n roc_auc_all[roc_auc_i] = temp_list\n\n for print_i in list(range(params.num_class)):\n print('class ' + str(print_i) + ': ', str(roc_auc[print_i]))\n\n print('Average:', roc_auc['micro'])\n\n if roc_auc['micro'] > best_auc :\n best_auc = roc_auc['micro']\n \n writer.add_scalar('val Auc score', roc_auc['micro'], epoch)\n \n \n\n model_file = params.model_file\n shutil.move(last_model_path, model_file)\n ##############\n # evaluation #\n ##############\n\n # finish training\n \n target_names = [\"Barking\", \"Howling\", \"Crying\", \"COSmoke\",\"GlassBreaking\",\"Other\"]\n time_elapsed = time.time() - since\n cfmatrix = cfm(best_true, best_pred)\n print('Training complete in {:.0f}m {:.0f}s'.format(time_elapsed // 60, time_elapsed % 60))\n print('Best val Acc: {:4f}'.format(accuracy(best_true, best_pred)))\n print('Best val F1: {:4f}'.format(f1(best_true, best_pred)))\n print('Best val Auc: {:4f}'.format(best_auc))\n\n print(cfmatrix)\n\n with open(os.path.join(log_path, \"classification_report.txt\"), \"w\") as f:\n f.write('Training complete in {:.0f}m {:.0f}s'.format(time_elapsed // 60, time_elapsed % 60)+\"\\n\")\n f.write('Best val Acc: {:4f}'.format(accuracy(best_true, best_pred))+\"\\n\")\n f.write('Best val F1: {:4f}'.format(f1(best_true, best_pred))+\"\\n\")\n f.write('Best val Auc: {:4f}'.format(best_auc)+\"\\n\")\n f.write(str(cfmatrix)+\"\\n\")\n f.write('All Parameters :' + str(all_params))\n\n plot_confusion_matrix(cfmatrix, target_names, log_path)\n\ndef prepare_model(params):\n device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n print(params)\n print(\"build model...\")\n model = None\n if params.resume:\n model = torch.load(params.resume)\n elif params.model_name == 'VGGish':\n model = VGGish(params)\n elif params.model_name == 'Efficientnet':\n model = EfficientNet_model(params).return_model()\n\n model = model.to(device)\n return model" ]
[ [ "torch.mean", "torch.nn.functional.softmax", "torch.max", "torch.load", "sklearn.metrics.roc_curve", "torch.std", "torch.set_grad_enabled", "torch.utils.tensorboard.SummaryWriter", "torch.cuda.is_available", "sklearn.metrics.auc", "numpy.vstack", "torch.save" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
ZhitingHu/texar-pytorch
[ "72ea115013ced8a5a2b004eacf6271184d3572a8", "72ea115013ced8a5a2b004eacf6271184d3572a8" ]
[ "examples/xlnet/xlnet_generation_main.py", "texar/torch/utils/utils.py" ]
[ "# Copyright 2019 The Texar Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"Example of building XLNet language model for sample generation.\n\"\"\"\n\nimport argparse\nimport torch\n\nimport texar.torch as tx\n\nparser = argparse.ArgumentParser()\nparser.add_argument('--checkpoint', type=str, default=None,\n help=\"Checkpoint to load model weights from.\")\nparser.add_argument(\"--pretrained-model-name\", type=str,\n default=\"xlnet-large-cased\",\n help=\"The pre-trained model to load selected in the list \"\n \"of: `xlnet-base-cased`, `xlnet-large-cased`.\")\nparser.add_argument('--seed', type=int, default=None, help=\"Random seed.\")\nparser.add_argument('--nsamples', type=int, default=1,\n help=\"Total number of samples to generate. Used in \"\n \"non-interactive mode.\")\nparser.add_argument('--batch-size', type=int, default=1,\n help=\"The batch size of input.\")\nparser.add_argument('--max-decoding-length', type=int, default=100,\n help=\"The maximun length of generated text.\")\nparser.add_argument('--temperature', type=float, default=0.7,\n help=\"Softmax temperature for top-k sample decoding. Must \"\n \"be strictly greater than 0. Defaults to 0.7.\")\nparser.add_argument('--top-k', type=int, default=40,\n help=\"The number of top most likely candidates to choose \"\n \"from at each step. This is use \"\n \"TopKSampleEmbeddingHelper for decoding. Ignored if \"\n \"'p' is given.\")\nparser.add_argument('--top-p', type=float, default=None,\n help=\"Select tokens with cumulative probability of at most \"\n \"'top-p' when arranged in decreasing order. This \"\n \"will use TopPSampleEmbeddingHelper for decoding.\")\nparser.add_argument('--interactive', action='store_true',\n help=\"Interactive mode or not.\")\n\nargs = parser.parse_args()\n\n\ndef main() -> None:\n device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n\n model = tx.modules.XLNetDecoder(\n pretrained_model_name=args.pretrained_model_name)\n if args.checkpoint is not None:\n model.load_state_dict(torch.load(args.checkpoint, map_location=device))\n print(f\"Loaded checkpoint from {args.checkpoint}\")\n model = model.to(device)\n\n tokenizer = tx.data.XLNetTokenizer(\n pretrained_model_name=args.pretrained_model_name)\n\n # A lengthy padding text used to workaround lack of context for short\n # prompts. Refer to https://github.com/rusiaaman/XLNet-gen for the rationale\n # behind this.\n pad_txt = \"\"\"\n Texar-PyTorch is an open-source toolkit based on PyTorch, aiming to\n support a broad set of machine learning, especially text generation\n tasks, such as machine translation, dialog, summarization, content\n manipulation, language modeling, and so on. Texar is designed for both\n researchers and practitioners for fast prototyping and\n experimentation.\n With the design goals of modularity, versatility, and extensibility in\n mind, Texar extracts the common patterns underlying the diverse tasks\n and methodologies, creates a library of highly reusable modules and\n functionalities, and facilitates arbitrary model architectures and\n algorithmic paradigms. \"\"\"\n pad_ids = tokenizer.map_text_to_id(pad_txt)\n eod_id = tokenizer.map_token_to_id(\"<eod>\")\n pad_ids.append(eod_id)\n\n def split_by(xs, y):\n p = 0\n for idx, x in enumerate(xs):\n if x == y:\n if idx - p > 0:\n yield xs[p:idx]\n p = idx + 1\n if len(xs) - p > 0:\n yield xs[p:]\n\n @torch.no_grad()\n def sample(text: str, length: int = 100, n_samples=3, **kwargs):\n model.eval()\n text = text.replace(\"\\n\", \"<eop>\")\n tokens = pad_ids + tokenizer.map_text_to_id(text)\n tokens = torch.tensor(tokens, device=device).expand(n_samples, -1)\n if args.top_p:\n kwargs[\"p\"] = args.top_p\n decode_output, _ = model(\n start_tokens=tokens,\n end_token=eod_id,\n max_decoding_length=length,\n print_steps=True,\n helper_type=tx.modules.TopPSampleEmbeddingHelper,\n **kwargs)\n else:\n kwargs[\"top_k\"] = args.top_k\n decode_output, _ = model(\n start_tokens=tokens,\n end_token=eod_id,\n max_decoding_length=length,\n print_steps=True,\n helper_type=tx.modules.TopKSampleEmbeddingHelper,\n **kwargs)\n decode_samples = decode_output.sample_id.tolist()\n for idx, sample_tokens in enumerate(decode_samples):\n print(f\"=== Sample {idx} ===\")\n output = \"\\n\".join(tokenizer.map_id_to_text(xs) for xs in split_by(\n sample_tokens, tokenizer.map_token_to_id(\"<eop>\")))\n print(output)\n\n nsamples = args.nsamples\n batch_size = args.batch_size\n max_decoding_length = args.max_decoding_length\n assert nsamples % batch_size == 0, (\n \"nsamples must be dividable by batch_size\")\n\n if args.interactive:\n while True:\n try:\n raw_text = input(\"Model input >>> \")\n while not raw_text:\n print('Input should not be empty!')\n raw_text = input(\"Model input >>> \")\n sample(text=raw_text, length=max_decoding_length,\n n_samples=batch_size)\n except EOFError:\n print(\"EOF entered, quitting.\")\n exit(0)\n else:\n # Generate samples from scratch\n for _ in range(nsamples // batch_size):\n for _ in range(args.batch_size):\n sample(text=\"<BOS>\", length=max_decoding_length,\n n_samples=batch_size)\n\n\nif __name__ == '__main__':\n main()\n", "# Copyright 2019 The Texar Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"\nMiscellaneous Utility functions.\n\"\"\"\n\nimport collections\nimport copy\nimport inspect\nfrom functools import lru_cache\nfrom pydoc import locate\nfrom typing import (\n Any, Callable, Collection, Dict, List, MutableMapping, Optional, Sequence,\n Tuple, Type, TypeVar, Union, cast, no_type_check, overload)\n\nimport funcsigs\nimport numpy as np\nimport torch\nimport torch.nn as nn\nfrom torch.nn.modules.conv import _ConvNd\n\nfrom texar.torch.hyperparams import HParams\nfrom texar.torch.utils.dtypes import _maybe_list_to_array\nfrom texar.torch.utils.types import MaybeSeq, MaybeTuple\n\nMAX_SEQ_LENGTH = np.iinfo(np.int32).max\n\n__all__ = [\n 'no_map',\n 'map_structure',\n 'map_structure_zip',\n 'get_first_in_structure',\n 'sequence_mask',\n 'get_args',\n 'get_default_arg_values',\n 'check_or_get_class',\n 'get_class',\n 'check_or_get_instance',\n 'get_instance',\n 'check_or_get_instance_with_redundant_kwargs',\n 'get_instance_with_redundant_kwargs',\n 'get_function',\n 'call_function_with_redundant_kwargs',\n 'get_instance_kwargs',\n 'dict_patch',\n 'dict_lookup',\n 'dict_fetch',\n 'dict_pop',\n 'flatten_dict',\n 'strip_token',\n 'strip_eos',\n 'strip_bos',\n 'strip_special_tokens',\n 'str_join',\n 'default_str',\n 'uniquify_str',\n 'ceildiv',\n 'sum_tensors',\n]\n\nT = TypeVar('T') # type argument\nR = TypeVar('R') # return type\nK = TypeVar('K') # key type\nV = TypeVar('V') # value type\nKwargs = Dict[str, Any]\nAnyDict = MutableMapping[str, Any]\nParamDict = Union[HParams, AnyDict]\n\nType_size_lambda_map = {\n nn.Linear: lambda x: x.out_features,\n nn.Bilinear: lambda x: x.out_features,\n _ConvNd: lambda x: x.out_channels * len(x.kernel_size),\n nn.Embedding: lambda x: x.embedding_dim,\n nn.EmbeddingBag: lambda x: x.embedding_dim,\n nn.RNNCellBase: lambda x: x.hidden_size,\n}\n\nType_size_keeper = [\n nn.ELU, nn.Hardshrink, nn.Hardtanh, nn.LeakyReLU, nn.LogSigmoid,\n nn.PReLU, nn.ReLU, nn.RReLU, nn.SELU, nn.CELU, nn.Sigmoid, nn.Softplus,\n nn.Softshrink, nn.Softsign, nn.Tanh, nn.Tanhshrink, nn.Threshold,\n nn.Softmin, nn.Softmax, nn.LogSoftmax, nn.Dropout, nn.AlphaDropout,\n]\n\n# NestedCollection = Union[T, Collection['NestedCollection']]\n\n\n@lru_cache(maxsize=None)\ndef _no_map_type(container_type: Type[T]) -> Type[T]:\n # Create a subtype of the container type that sets an normally inaccessible\n # special attribute on instances.\n # This is necessary because `setattr` does not work on built-in types\n # (e.g. `list`).\n new_type = type(\"_no_map\" + container_type.__name__,\n (container_type,), {'--no-map--': True})\n return new_type\n\n\ndef no_map(container_type: Type[T], *args, **kwargs) -> T:\n r\"\"\"Create a \"`non-mappable`\" container type, i.e. it will be treated as a\n singleton object in :meth:`map_structure` and :meth:`map_structure_zip`,\n its contents will not be traversed.\n\n This is implemented by dynamically creating a subclass of the required type,\n and overriding the :attr:`__subclasscheck__` class method to always return\n `False`.\n\n Args:\n container_type: The type of the container to create,\n e.g. `list`, `dict`.\n args: Arguments to the constructor.\n kwargs: Keyword arguments to the constructor\n\n Returns:\n The `non-mappable` container type.\n \"\"\"\n return _no_map_type(container_type)(*args, **kwargs) # type: ignore\n\n\n@no_type_check\ndef map_structure(fn: Callable[[T], R], obj: Collection[T]) -> Collection[R]:\n r\"\"\"Map a function over all elements in a (possibly nested) collection.\n\n Args:\n fn (callable): The function to call on elements.\n obj: The collection to map function over.\n\n Returns:\n The collection in the same structure, with elements mapped.\n \"\"\"\n if hasattr(obj, \"--no-map--\"):\n return fn(obj)\n if isinstance(obj, list):\n return [map_structure(fn, x) for x in obj]\n if isinstance(obj, tuple):\n if isinstance(obj, torch.Size):\n return fn(obj)\n if hasattr(obj, '_fields'): # namedtuple\n return type(obj)(*[map_structure(fn, x) for x in obj])\n else:\n return tuple(map_structure(fn, x) for x in obj)\n if isinstance(obj, dict):\n return {k: map_structure(fn, v) for k, v in obj.items()}\n if isinstance(obj, set):\n return {map_structure(fn, x) for x in obj}\n return fn(obj)\n\n\n@no_type_check\ndef map_structure_zip(fn: Callable[..., R],\n objs: Sequence[Collection[T]]) -> Collection[R]:\n r\"\"\"Map a function over tuples formed by taking one elements from each\n (possibly nested) collection. Each collection must have identical\n structures.\n\n .. note::\n Although identical structures are required, it is not enforced by\n assertions. The structure of the first collection is assumed to be\n the structure for all collections.\n\n For rare cases where collections need to have different structures,\n refer to :meth:`no_map`.\n\n Args:\n fn (callable): The function to call on elements.\n objs: The list of collections to map function over.\n\n Returns:\n A collection with the same structure, with elements mapped.\n \"\"\"\n obj = objs[0]\n if hasattr(obj, \"--no-map--\"):\n return fn(*objs)\n if isinstance(obj, list):\n return [map_structure_zip(fn, xs) for xs in zip(*objs)]\n if isinstance(obj, tuple):\n if isinstance(obj, torch.Size):\n return fn(obj)\n if hasattr(obj, '_fields'): # namedtuple\n return type(obj)(*[map_structure_zip(fn, xs) for xs in zip(*objs)])\n else:\n return tuple(map_structure_zip(fn, xs) for xs in zip(*objs))\n if isinstance(obj, dict):\n return {k: map_structure_zip(fn, [o[k] for o in objs])\n for k in obj.keys()}\n if isinstance(obj, set):\n return {map_structure_zip(fn, xs) for xs in zip(*objs)}\n return fn(*objs)\n\n\ndef get_first_in_structure(obj: Collection[T]) -> Optional[T]:\n r\"\"\"Return the first not-`None` element within a (possibly nested)\n collection.\n\n Args:\n obj: The collection to pick the element from.\n\n Returns:\n The first non-`None` element from the collection, or `None` if the\n collection is empty or contains only `None` elements.\n \"\"\"\n item = None\n\n def _get_first(x):\n nonlocal item\n if item is None:\n item = x\n\n map_structure(_get_first, obj)\n return item\n\n\ndef sequence_mask(lengths: Union[torch.LongTensor, List[int]],\n max_len: Optional[int] = None,\n dtype: Optional[torch.dtype] = None,\n device: Optional[torch.device] = None) -> torch.ByteTensor:\n r\"\"\"Return a mask tensor representing the first N positions of each cell.\n\n If ``lengths`` has shape ``[d_1, d_2, ..., d_n]`` the resulting tensor\n ``mask`` has dtype ``dtype`` and shape ``[d_1, d_2, ..., d_n, maxlen]``,\n with\n\n ```\n mask[i_1, i_2, ..., i_n, j] = (j < lengths[i_1, i_2, ..., i_n])\n ```\n\n Examples:\n\n ```python\n sequence_mask([1, 3, 2], 5) # [[True, False, False, False, False],\n # [True, True, True, False, False],\n # [True, True, False, False, False]]\n\n sequence_mask([[1, 3],[2,0]]) # [[[ True, False, False],\n # [ True, True, True]],\n # [[ True, True, False],\n # [False, False, False]]]\n ```\n\n Args:\n lengths: integer tensor or list of int, all its values <= max_len.\n max_len: scalar integer tensor, size of last dimension of returned\n tensor. Default is the maximum value in ``lengths``.\n dtype: the desired data type of returned tensor. Default: if None,\n returns :torch:`ByteTensor`.\n device: the desired device of returned tensor. Default: if None, uses\n the current device for the default tensor type.\n Returns:\n A mask tensor of shape :python:`lengths.shape + (max_len,)`, cast to\n specified dtype.\n Raises:\n ValueError: if ``max_len`` is not a scalar.\n \"\"\"\n if not isinstance(lengths, torch.Tensor):\n lengths = torch.tensor(lengths, device=device)\n elif device is None:\n device = lengths.device\n lengths: torch.LongTensor\n if max_len is None:\n max_len = torch.max(lengths).item()\n\n size = lengths.size()\n row_vector = torch.arange(max_len, device=device, dtype=lengths.dtype).view(\n *([1] * len(size)), -1).expand(*size, max_len)\n row_vector = row_vector\n mask = (row_vector < lengths.unsqueeze(-1)).to(device=device)\n if dtype is not None:\n mask = mask.to(dtype=dtype)\n\n return mask\n\n\ndef get_args(fn: Callable) -> List[str]:\n r\"\"\"Gets the arguments of a function.\n\n Args:\n fn (callable): The function to inspect.\n\n Returns:\n list: A list of argument names (``str``) of the function.\n \"\"\"\n argspec = inspect.getfullargspec(fn)\n args = argspec.args\n\n # Empty args can be because `fn` is decorated. Use `funcsigs.signature`\n # to re-do the inspect\n if len(args) == 0:\n args = funcsigs.signature(fn).parameters.keys()\n args = list(args)\n\n return args\n\n\ndef get_default_arg_values(fn: Callable) -> Dict[str, Any]:\n r\"\"\"Gets the arguments and respective default values of a function.\n\n Only arguments with default values are included in the output dictionary.\n\n Args:\n fn (callable): The function to inspect.\n\n Returns:\n dict: A dictionary that maps argument names (``str``) to their default\n values. The dictionary is empty if no arguments have default values.\n \"\"\"\n argspec = inspect.getfullargspec(fn)\n if argspec.defaults is None:\n return {}\n num_defaults = len(argspec.defaults)\n return dict(zip(argspec.args[-num_defaults:], argspec.defaults))\n\n\ndef check_or_get_class(class_or_name: Union[Type[T], str],\n module_paths: Optional[List[str]] = None,\n superclass: Optional[MaybeTuple[type]] = None) \\\n -> Type[T]:\n r\"\"\"Returns the class and checks if the class inherits :attr:`superclass`.\n\n Args:\n class_or_name: Name or full path to the class, or the class itself.\n module_paths (list, optional): Paths to candidate modules to search\n for the class. This is used if :attr:`class_or_name` is a string and\n the class cannot be located solely based on :attr:`class_or_name`.\n The first module in the list that contains the class\n is used.\n superclass (optional): A (list of) classes that the target class\n must inherit.\n\n Returns:\n The target class.\n\n Raises:\n ValueError: If class is not found based on :attr:`class_or_name` and\n :attr:`module_paths`.\n TypeError: If class does not inherits :attr:`superclass`.\n \"\"\"\n class_ = class_or_name\n if isinstance(class_, str):\n class_ = get_class(class_, module_paths)\n if superclass is not None:\n if not issubclass(class_, superclass):\n raise TypeError(\n \"A subclass of {} is expected. Got: {}\".format(\n superclass, class_))\n return class_\n\n\ndef get_class(class_name: str,\n module_paths: Optional[List[str]] = None) -> type:\n r\"\"\"Returns the class based on class name.\n\n Args:\n class_name (str): Name or full path to the class.\n module_paths (list): Paths to candidate modules to search for the\n class. This is used if the class cannot be located solely based on\n ``class_name``. The first module in the list that contains the class\n is used.\n\n Returns:\n The target class.\n\n Raises:\n ValueError: If class is not found based on :attr:`class_name` and\n :attr:`module_paths`.\n \"\"\"\n class_ = locate(class_name)\n if (class_ is None) and (module_paths is not None):\n for module_path in module_paths:\n class_ = locate('.'.join([module_path, class_name]))\n if class_ is not None:\n break\n\n if class_ is None:\n raise ValueError(\n \"Class not found in {}: {}\".format(module_paths, class_name))\n\n return class_ # type: ignore\n\n\ndef check_or_get_instance(ins_or_class_or_name: Union[Type[T], T, str],\n kwargs: Kwargs,\n module_paths: Optional[List[str]] = None,\n classtype: Optional[MaybeTuple[type]] = None) -> T:\n r\"\"\"Returns a class instance and checks types.\n\n Args:\n ins_or_class_or_name: Can be of 3 types:\n\n - A class to instantiate.\n - A string of the name or full path to a class to instantiate.\n - The class instance to check types.\n\n kwargs (dict): Keyword arguments for the class constructor. Ignored\n if ``ins_or_class_or_name`` is a class instance.\n module_paths (list, optional): Paths to candidate modules to\n search for the class. This is used if the class cannot be\n located solely based on :attr:`class_name`. The first module\n in the list that contains the class is used.\n classtype (optional): A (list of) class of which the instance must\n be an instantiation.\n\n Raises:\n ValueError: If class is not found based on :attr:`class_name` and\n :attr:`module_paths`.\n ValueError: If :attr:`kwargs` contains arguments that are invalid\n for the class construction.\n TypeError: If the instance is not an instantiation of\n :attr:`classtype`.\n \"\"\"\n ret = ins_or_class_or_name\n if isinstance(ret, (str, type)):\n ret = get_instance(ret, kwargs, module_paths)\n if classtype is not None:\n if not isinstance(ret, classtype):\n raise TypeError(\n \"An instance of {} is expected. Got: {}\".format(classtype, ret))\n return ret\n\n\ndef get_instance(class_or_name: Union[Type[T], str], kwargs: Optional[Kwargs],\n module_paths: Optional[List[str]] = None) -> T:\n r\"\"\"Creates a class instance.\n\n Args:\n class_or_name: A class, or its name or full path to a class to\n instantiate.\n kwargs (dict): Keyword arguments for the class constructor.\n module_paths (list, optional): Paths to candidate modules to\n search for the class. This is used if the class cannot be\n located solely based on :attr:`class_name`. The first module\n in the list that contains the class is used.\n\n Returns:\n A class instance.\n\n Raises:\n ValueError: If class is not found based on :attr:`class_or_name` and\n :attr:`module_paths`.\n ValueError: If :attr:`kwargs` contains arguments that are invalid\n for the class construction.\n \"\"\"\n # Locate the class\n class_ = class_or_name\n if isinstance(class_, str):\n class_ = get_class(class_, module_paths)\n\n # Check validity of arguments\n class_args = set(get_args(class_.__init__))\n\n if kwargs is None:\n kwargs = {}\n for key in kwargs.keys():\n if key not in class_args:\n raise ValueError(\n \"Invalid argument for class %s.%s: %s, valid args: %s\" %\n (class_.__module__, class_.__name__, key, list(class_args)))\n\n return class_(**kwargs) # type: ignore\n\n\ndef check_or_get_instance_with_redundant_kwargs(\n ins_or_class_or_name: Union[Type[T], T, str], kwargs: Kwargs,\n module_paths: Optional[List[str]] = None,\n classtype: Optional[Type[T]] = None) -> T:\n r\"\"\"Returns a class instance and checks types.\n\n Only those keyword arguments in :attr:`kwargs` that are included in the\n class construction method are used.\n\n Args:\n ins_or_class_or_name: Can be of 3 types:\n\n - A class to instantiate.\n - A string of the name or module path to a class to instantiate.\n - The class instance to check types.\n\n kwargs (dict): Keyword arguments for the class constructor.\n module_paths (list, optional): Paths to candidate modules to\n search for the class. This is used if the class cannot be\n located solely based on :attr:`class_name`. The first module\n in the list that contains the class is used.\n classtype (optional): A (list of) classes of which the instance must\n be an instantiation.\n\n Raises:\n ValueError: If class is not found based on :attr:`class_name` and\n :attr:`module_paths`.\n ValueError: If :attr:`kwargs` contains arguments that are invalid\n for the class construction.\n TypeError: If the instance is not an instantiation of\n :attr:`classtype`.\n \"\"\"\n ret = ins_or_class_or_name\n if isinstance(ret, (str, type)):\n ret = get_instance_with_redundant_kwargs(ret, kwargs, module_paths)\n if classtype is not None:\n if not isinstance(ret, classtype):\n raise TypeError(\n \"An instance of {} is expected. Got: {}\".format(classtype, ret))\n return ret\n\n\ndef get_instance_with_redundant_kwargs(\n class_name: Union[Type[T], str], kwargs: Kwargs,\n module_paths: Optional[List[str]] = None) -> T:\n r\"\"\"Creates a class instance.\n\n Only those keyword arguments in :attr:`kwargs` that are included in the\n class construction method are used.\n\n Args:\n class_name (str): A class or its name or module path.\n kwargs (dict): A dictionary of arguments for the class constructor. It\n may include invalid arguments which will be ignored.\n module_paths (list of str): A list of paths to candidate modules to\n search for the class. This is used if the class cannot be located\n solely based on :attr:`class_name`. The first module in the list\n that contains the class is used.\n\n Returns:\n A class instance.\n\n Raises:\n ValueError: If class is not found based on :attr:`class_name` and\n :attr:`module_paths`.\n \"\"\"\n # Locate the class\n if isinstance(class_name, str):\n class_ = get_class(class_name, module_paths)\n else:\n class_ = class_name\n\n # Select valid arguments\n selected_kwargs = {}\n class_args = set(get_args(class_.__init__)) # type: ignore\n if kwargs is None:\n kwargs = {}\n for key, value in kwargs.items():\n if key in class_args:\n selected_kwargs[key] = value\n\n return class_(**selected_kwargs)\n\n\ndef get_function(fn_or_name: Union[str, Callable[[torch.Tensor], torch.Tensor]],\n module_paths: Optional[List[str]] = None) \\\n -> Callable[[torch.Tensor], torch.Tensor]:\n r\"\"\"Returns the function of specified name and module.\n\n Args:\n fn_or_name (str or callable): Name or full path to a function, or the\n function itself.\n module_paths (list, optional): A list of paths to candidate modules to\n search for the function. This is used only when the function\n cannot be located solely based on :attr:`fn_or_name`. The first\n module in the list that contains the function is used.\n\n Returns:\n A function.\n\n Raises:\n ValueError: If method with name as :attr:`fn_or_name` is not found.\n \"\"\"\n if callable(fn_or_name):\n return fn_or_name\n\n fn = locate(fn_or_name)\n if (fn is None) and (module_paths is not None):\n for module_path in module_paths:\n fn = locate('.'.join([module_path, fn_or_name]))\n if fn is not None:\n break\n\n if fn is None:\n raise ValueError(\n \"Method not found in {}: {}\".format(module_paths, fn_or_name))\n\n return fn # type: ignore\n\n\ndef call_function_with_redundant_kwargs(fn: Callable[..., R],\n kwargs: Dict[str, Any]) -> R:\n r\"\"\"Calls a function and returns the results.\n\n Only those keyword arguments in :attr:`kwargs` that are included in the\n function's argument list are used to call the function.\n\n Args:\n fn (function): A callable. If :attr:`fn` is not a python function,\n :attr:`fn.__call__` is called.\n kwargs (dict): A ``dict`` of arguments for the callable. It\n may include invalid arguments which will be ignored.\n\n Returns:\n The returned results by calling :attr:`fn`.\n \"\"\"\n try:\n fn_args = set(get_args(fn))\n except TypeError:\n fn_args = set(get_args(fn.__call__)) # type: ignore\n\n if kwargs is None:\n kwargs = {}\n\n # Select valid arguments\n selected_kwargs = {}\n for key, value in kwargs.items():\n if key in fn_args:\n selected_kwargs[key] = value\n\n return fn(**selected_kwargs)\n\n\ndef get_instance_kwargs(kwargs: Kwargs, hparams: ParamDict) -> Kwargs:\n r\"\"\"Makes a dictionary of keyword arguments with the following structure:\n\n ``kwargs_ = {'hparams': dict(hparams), **kwargs}``.\n\n This is typically used for constructing a module which takes a set of\n arguments as well as a argument named ``\"hparams\"``.\n\n Args:\n kwargs (dict): A ``dict`` of keyword arguments. Can be `None`.\n hparams: A ``dict`` or an instance of :class:`~texar.torch.HParams`.\n Can be `None`.\n\n Returns:\n A ``dict`` that contains the keyword arguments in :attr:`kwargs`, and\n an additional keyword argument named ``\"hparams\"``.\n \"\"\"\n if hparams is None or isinstance(hparams, dict):\n kwargs_ = {'hparams': hparams}\n elif isinstance(hparams, HParams):\n kwargs_ = {'hparams': hparams.todict()}\n else:\n raise ValueError(\n '`hparams` must be a dict, an instance of HParams, or a `None`.')\n kwargs_.update(kwargs or {})\n return kwargs_\n\n\ndef get_output_size(input_instance: nn.Module) -> Optional[int]:\n r\"\"\"Return the final dimension size of :attr:`input_instance` output.\n\n If type of :attr:`input_instance` is among the common types, the final\n dimension size will be computed.\n\n Args:\n input_instance: A :class:`~torch.nn.Module` instance from\n which to compute the final dimension size.\n\n Returns:\n int (optional): The final dimension size of the output.\n If output size is determined by input, returns ``-1``,\n otherwise if output size is not computable, return `None`.\n \"\"\"\n\n for t, l in Type_size_lambda_map.items():\n if isinstance(input_instance, t):\n return l(input_instance)\n for t in Type_size_keeper:\n if isinstance(input_instance, t):\n return -1\n return None\n\n\ndef dict_patch(tgt_dict: AnyDict, src_dict: AnyDict) -> AnyDict:\n r\"\"\"Recursively patch :attr:`tgt_dict` by adding items from :attr:`src_dict`\n that do not exist in :attr:`tgt_dict`.\n\n If respective items in :attr:`src_dict` and :attr:`tgt_dict` are both\n ``dict``, the :attr:`tgt_dict` item is patched recursively.\n\n Args:\n tgt_dict (dict): Target dictionary to patch.\n src_dict (dict): Source dictionary.\n\n Returns:\n dict: The new :attr:`tgt_dict` that is patched.\n \"\"\"\n if src_dict is None:\n return tgt_dict\n\n for key, value in src_dict.items():\n if key not in tgt_dict:\n tgt_dict[key] = copy.deepcopy(value)\n elif isinstance(value, dict) and isinstance(tgt_dict[key], dict):\n tgt_dict[key] = dict_patch(tgt_dict[key], value)\n return tgt_dict\n\n\ndef dict_lookup(dict_: MutableMapping[K, V], keys: Union[List[K], np.ndarray],\n default: Optional[V] = None) -> np.ndarray:\n r\"\"\"Looks up :attr:`keys` in the dictionary, returns the corresponding\n values.\n\n The :attr:`default` is used for keys not present in the dictionary.\n\n Args:\n dict\\_ (dict): A dictionary for lookup.\n keys: A numpy array or a (possibly nested) list of keys.\n default (optional): Value to be returned when a key is not in\n :attr:`dict_`. Error is raised if :attr:`default` is not given and\n key is not in the dictionary.\n\n Returns:\n A numpy array of values with the same structure as :attr:`keys`.\n\n Raises:\n TypeError: If key is not in :attr:`dict_` and :attr:`default` is\n `None`.\n \"\"\"\n return np.vectorize(lambda x: dict_.get(x, default))(keys) # type: ignore\n\n\n# TODO: Remove these once pylint supports function stubs.\n# pylint: disable=unused-argument,function-redefined,multiple-statements\n\n@overload\ndef dict_fetch(src_dict: ParamDict,\n tgt_dict_or_keys: Union[ParamDict, List[str]]) -> AnyDict: ...\n\n\n@overload\ndef dict_fetch(src_dict: None, tgt_dict_or_keys: Any) -> None: ...\n\n\ndef dict_fetch(src_dict: Optional[ParamDict],\n tgt_dict_or_keys: Union[ParamDict, List[str]]) \\\n -> Optional[AnyDict]:\n r\"\"\"Fetches a sub-dictionary of :attr:`src_dict` with the keys in\n :attr:`tgt_dict_or_keys`.\n\n Args:\n src_dict: A dictionary or instance of :class:`~texar.torch.HParams`.\n The source dictionary to fetch values from.\n tgt_dict_or_keys: A dictionary, instance of\n :class:`~texar.torch.HParams`, or a list (or a\n ``dict_keys``/``KeysView``) of keys to be included in the output\n dictionary.\n\n Returns:\n A new dictionary that is a sub-dictionary of :attr:`src_dict`.\n \"\"\"\n if src_dict is None:\n return src_dict\n\n if isinstance(tgt_dict_or_keys, HParams):\n tgt_dict_or_keys = tgt_dict_or_keys.todict()\n if isinstance(tgt_dict_or_keys, MutableMapping):\n tgt_dict_or_keys = tgt_dict_or_keys.keys() # type: ignore\n keys = list(tgt_dict_or_keys)\n\n if isinstance(src_dict, HParams):\n src_dict = src_dict.todict()\n\n return {k: src_dict[k] for k in keys if k in src_dict}\n\n\n# pylint: enable=unused-argument,function-redefined,multiple-statements\n\n\ndef dict_pop(dict_: MutableMapping[T, Any], pop_keys: MaybeSeq[T],\n default: Optional[Any] = None) -> Dict[T, Any]:\n r\"\"\"Removes keys from a dictionary and returns their values.\n\n Args:\n dict\\_ (dict): A dictionary from which items are removed.\n pop_keys: A key or a list of keys to remove and return respective\n values or :attr:`default`.\n default (optional): Value to be returned when a key is not in\n :attr:`dict_`. The default value is `None`.\n\n Returns:\n A ``dict`` of the items removed from :attr:`dict_`.\n \"\"\"\n if not isinstance(pop_keys, (list, tuple)):\n pop_keys = cast(List[T], [pop_keys])\n ret_dict = {key: dict_.pop(key, default) for key in pop_keys}\n return ret_dict\n\n\ndef flatten_dict(dict_: AnyDict, parent_key: str = \"\", sep: str = \".\"):\n r\"\"\"Flattens a nested dictionary. Namedtuples within the dictionary are\n also converted to dictionaries.\n\n Adapted from:\n https://github.com/google/seq2seq/blob/master/seq2seq/models/model_base.py\n\n Args:\n dict\\_ (dict): The dictionary to flatten.\n parent_key (str): A prefix to prepend to each key.\n sep (str): Separator that intervenes between parent and child keys.\n For example, if :attr:`sep` == ``\".\"``, then ``{ \"a\": { \"b\": 3 } }``\n is converted into ``{ \"a.b\": 3 }``.\n\n Returns:\n A new flattened ``dict``.\n \"\"\"\n items: List[Tuple[str, Any]] = []\n for key, value in dict_.items():\n key_ = parent_key + sep + key if parent_key else key\n if isinstance(value, MutableMapping):\n items.extend(flatten_dict(value, key_, sep=sep).items())\n elif isinstance(value, tuple) and hasattr(value, '_asdict'):\n # namedtuple\n dict_items = collections.OrderedDict(\n zip(value._fields, value)) # type: ignore\n items.extend(flatten_dict(dict_items, key_, sep=sep).items())\n else:\n items.append((key_, value))\n return dict(items)\n\n\ndef default_str(str_: Optional[str], default: str) -> str:\n r\"\"\"Returns :attr:`str_` if it is not `None` or empty, otherwise returns\n :attr:`default_str`.\n\n Args:\n str\\_: A string.\n default: A string.\n\n Returns:\n Either :attr:`str_` or :attr:`default_str`.\n \"\"\"\n if str_ is not None and str_ != \"\":\n return str_\n else:\n return default\n\n\ndef uniquify_str(str_: str, str_set: Collection[str]) -> str:\n r\"\"\"Uniquifies :attr:`str_` if :attr:`str_` is included in :attr:`str_set`.\n\n This is done by appending a number to :attr:`str_`. Returns\n :attr:`str_` directly if it is not included in :attr:`str_set`.\n\n Args:\n str\\_ (string): A string to uniquify.\n str_set (set, dict, or list): A collection of strings. The returned\n string is guaranteed to be different from the elements in the\n collection.\n\n Returns:\n The uniquified string. Returns :attr:`str_` directly if it is\n already unique.\n\n Example:\n\n .. code-block:: python\n\n print(uniquify_str('name', ['name', 'name_1']))\n # 'name_2'\n\n \"\"\"\n if str_ not in str_set:\n return str_\n else:\n for i in range(1, len(str_set) + 1):\n unique_str = str_ + \"_%d\" % i\n if unique_str not in str_set:\n return unique_str\n raise ValueError(\"Failed to uniquify string: \" + str_)\n\n\ndef _recur_split(s: MaybeSeq[str],\n dtype_as: Collection[str]) -> MaybeSeq[str]:\n r\"\"\"Splits (possibly nested list of) strings recursively.\n \"\"\"\n if isinstance(s, str):\n return _maybe_list_to_array(s.split(), dtype_as)\n else:\n s_ = [_recur_split(si, dtype_as) for si in s]\n return _maybe_list_to_array(s_, s)\n\n\ndef strip_token(str_: MaybeSeq[str], token: str,\n is_token_list: bool = False) -> MaybeSeq[str]:\n r\"\"\"Returns a copy of strings with leading and trailing tokens removed.\n\n Note that besides :attr:`token`, all leading and trailing whitespace\n characters are also removed.\n\n If :attr:`is_token_list` is False, then the function assumes tokens in\n :attr:`str_` are separated with whitespace character.\n\n Args:\n str\\_: A ``str``, or an ``n``-D numpy array or (possibly nested)\n list of ``str``.\n token (str): The token to strip, e.g., the ``\"<PAD>\"`` token defined in\n :class:`~texar.torch.data.SpecialTokens`.\n is_token_list (bool): Whether each sentence in :attr:`str_` is a list\n of tokens. If False, each sentence in :attr:`str_` is assumed to\n contain tokens separated with space character.\n\n Returns:\n The stripped strings of the same structure/shape as :attr:`str_`.\n\n Example:\n\n .. code-block:: python\n\n str_ = '<PAD> a sentence <PAD> <PAD> '\n str_stripped = strip_token(str_, '<PAD>')\n # str_stripped == 'a sentence'\n\n str_ = ['<PAD>', 'a', 'sentence', '<PAD>', '<PAD>', '', '']\n str_stripped = strip_token(str_, '<PAD>', is_token_list=True)\n # str_stripped == 'a sentence'\n \"\"\"\n\n def _recur_strip(s):\n if isinstance(s, str):\n if token == \"\":\n return ' '.join(s.strip().split())\n else:\n return (' '.join(s.strip().split())\n .replace(' ' + token, '').replace(token + ' ', ''))\n else:\n s_ = [_recur_strip(si) for si in s]\n return _maybe_list_to_array(s_, s)\n\n s = str_\n\n if is_token_list:\n s = str_join(s) # type: ignore\n\n strp_str = _recur_strip(s)\n\n if is_token_list:\n strp_str = _recur_split(strp_str, str_)\n\n return strp_str\n\n\ndef strip_eos(str_: MaybeSeq[str], eos_token: str = '<EOS>',\n is_token_list: bool = False) -> MaybeSeq[str]:\n r\"\"\"Remove the EOS token and all subsequent tokens.\n\n If :attr:`is_token_list` is False, then the function assumes tokens in\n :attr:`str_` are separated with whitespace character.\n\n Args:\n str\\_: A ``str``, or an ``n``-D numpy array or (possibly nested)\n list of ``str``.\n eos_token (str): The EOS token. Default is ``\"<EOS>\"`` as defined in\n :class:`~texar.torch.data.SpecialTokens`.EOS\n is_token_list (bool): Whether each sentence in :attr:`str_` is a list\n of tokens. If False, each sentence in :attr:`str_` is assumed to\n contain tokens separated with space character.\n\n Returns:\n Strings of the same structure/shape as :attr:`str_`.\n \"\"\"\n\n def _recur_strip(s):\n if isinstance(s, str):\n s_tokens = s.split()\n if eos_token in s_tokens:\n return ' '.join(s_tokens[:s_tokens.index(eos_token)])\n else:\n return s\n else:\n s_ = [_recur_strip(si) for si in s]\n return _maybe_list_to_array(s_, s)\n\n s = str_\n\n if is_token_list:\n s = str_join(s) # type: ignore\n\n strp_str = _recur_strip(s)\n\n if is_token_list:\n strp_str = _recur_split(strp_str, str_)\n\n return strp_str\n\n\n_strip_eos_ = strip_eos\n\n\ndef strip_bos(str_: MaybeSeq[str], bos_token: str = '<BOS>',\n is_token_list: bool = False) -> MaybeSeq[str]:\n r\"\"\"Remove all leading BOS tokens.\n\n Note that besides :attr:`bos_token`, all leading and trailing whitespace\n characters are also removed.\n\n If :attr:`is_token_list` is False, then the function assumes tokens in\n :attr:`str_` are separated with whitespace character.\n\n Args:\n str_: A ``str``, or an ``n``-D numpy array or (possibly nested)\n list of ``str``.\n bos_token (str): The BOS token. Default is ``\"<BOS>\"`` as defined in\n :class:`~texar.torch.data.SpecialTokens`.BOS\n is_token_list (bool): Whether each sentence in :attr:`str_` is a list\n of tokens. If False, each sentence in :attr:`str_` is assumed to\n contain tokens separated with space character.\n\n Returns:\n Strings of the same structure/shape as :attr:`str_`.\n \"\"\"\n\n def _recur_strip(s):\n if isinstance(s, str):\n if bos_token == '':\n return ' '.join(s.strip().split())\n else:\n return ' '.join(s.strip().split()).replace(bos_token + ' ', '')\n else:\n s_ = [_recur_strip(si) for si in s]\n return _maybe_list_to_array(s_, s)\n\n s = str_\n\n if is_token_list:\n s = str_join(s) # type: ignore\n\n strp_str = _recur_strip(s)\n\n if is_token_list:\n strp_str = _recur_split(strp_str, str_)\n\n return strp_str\n\n\n_strip_bos_ = strip_bos\n\n\n# pylint: disable=redefined-outer-name\n\ndef strip_special_tokens(str_: MaybeSeq[str],\n strip_pad: Optional[str] = '<PAD>',\n strip_bos: Optional[str] = '<BOS>',\n strip_eos: Optional[str] = '<EOS>',\n is_token_list: bool = False) -> MaybeSeq[str]:\n r\"\"\"Removes special tokens in strings, including:\n\n - Removes EOS and all subsequent tokens\n - Removes leading and and trailing PAD tokens\n - Removes leading BOS tokens\n\n Note that besides the special tokens, all leading and trailing whitespace\n characters are also removed.\n\n This is a joint function of :func:`strip_eos`, :func:`strip_pad`, and\n :func:`strip_bos`\n\n Args:\n str\\_: A ``str``, or an ``n``-D numpy array or (possibly nested)\n list of ``str``.\n strip_pad (str): The PAD token to strip from the strings (i.e., remove\n the leading and trailing PAD tokens of the strings). Default\n is ``\"<PAD>\"`` as defined in\n :class:`~texar.torch.data.SpecialTokens`.PAD.\n Set to `None` or `False` to disable the stripping.\n strip_bos (str): The BOS token to strip from the strings (i.e., remove\n the leading BOS tokens of the strings).\n Default is ``\"<BOS>\"`` as defined in\n :class:`~texar.torch.data.SpecialTokens`.BOS.\n Set to `None` or `False` to disable the stripping.\n strip_eos (str): The EOS token to strip from the strings (i.e., remove\n the EOS tokens and all subsequent tokens of the strings).\n Default is ``\"<EOS>\"`` as defined in\n :class:`~texar.torch.data.SpecialTokens`.EOS.\n Set to `None` or `False` to disable the stripping.\n is_token_list (bool): Whether each sentence in :attr:`str_` is a list\n of tokens. If `False`, each sentence in :attr:`str_` is assumed to\n contain tokens separated with space character.\n\n Returns:\n Strings of the same shape of :attr:`str_` with special tokens stripped.\n \"\"\"\n s = str_\n\n if is_token_list:\n s = str_join(s) # type: ignore\n\n if strip_eos is not None and strip_eos is not False:\n s = _strip_eos_(s, strip_eos, is_token_list=False)\n\n if strip_pad is not None and strip_pad is not False:\n s = strip_token(s, strip_pad, is_token_list=False)\n\n if strip_bos is not None and strip_bos is not False:\n s = _strip_bos_(s, strip_bos, is_token_list=False)\n\n if is_token_list:\n s = _recur_split(s, str_)\n\n return s\n\n\ndef str_join(tokens: Sequence[List], sep: str = ' ') -> Sequence[str]:\n r\"\"\"Concatenates :attr:`tokens` along the last dimension with intervening\n occurrences of :attr:`sep`.\n\n Args:\n tokens: An ``n``-D numpy array or (possibly nested) list of ``str``.\n sep (str): The string intervening between the tokens.\n\n Returns:\n An ``(n-1)``-D numpy array (or list) of ``str``.\n \"\"\"\n\n def _recur_join(s):\n if len(s) == 0:\n return ''\n elif isinstance(s[0], str):\n return sep.join(s)\n else:\n s_ = [_recur_join(si) for si in s]\n return _maybe_list_to_array(s_, s)\n\n str_ = _recur_join(tokens)\n\n return str_\n\n\n# pylint: enable=redefined-outer-name\n\ndef ceildiv(a: int, b: int) -> int:\n r\"\"\"Compute division with results rounding up.\n\n For example, ``5 / 2 = 2.5``, ``ceildiv(5, 2) = 3``.\n\n Args:\n a (int): The dividend.\n b (int): The divisor.\n\n Returns:\n int: The quotient, rounded up.\n \"\"\"\n return -(-a // b)\n\n\ndef sum_tensors(xs: List[Optional[torch.Tensor]]) -> Optional[torch.Tensor]:\n r\"\"\"Sum a list of tensors with possible `None` values.\n\n Args:\n xs: A list of tensors.\n\n Returns:\n The summation of all the elements in the list.\n \"\"\"\n idx = next((idx for idx, tensor in enumerate(xs) if tensor is not None), -1)\n if idx == -1:\n return None\n ret = xs[idx]\n for tensor in xs[(idx + 1):]:\n if tensor is not None:\n ret = ret + tensor\n return ret\n\n\ndef truncate_seq_pair(tokens_a: Union[List[int], List[str]],\n tokens_b: Union[List[int], List[str]],\n max_length: int):\n r\"\"\"Truncates a sequence pair in place to the maximum length.\n\n This is a simple heuristic which will always truncate the longer sequence\n one token at a time. This makes more sense than truncating an equal\n percent of tokens from each, since if one sequence is very short then\n each token that's truncated likely contains more information than a\n longer sequence.\n\n Example:\n tokens_a = [1, 2, 3, 4, 5]\n tokens_b = [6, 7]\n truncate_seq_pair(tokens_a, tokens_b, 5)\n tokens_a # [1, 2, 3]\n tokens_b # [6, 7]\n\n Args:\n tokens_a: A list of tokens or token ids.\n tokens_b: A list of tokens or token ids.\n max_length: maximum sequence length.\n \"\"\"\n while True:\n total_length = len(tokens_a) + len(tokens_b)\n if total_length <= max_length:\n break\n if len(tokens_a) > len(tokens_b):\n tokens_a.pop()\n else:\n tokens_b.pop()\n" ]
[ [ "torch.tensor", "torch.no_grad", "torch.cuda.is_available", "torch.load" ], [ "torch.max", "torch.arange", "numpy.iinfo", "torch.tensor" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
Tauranis/tf-explain
[ "5a5a183d601bd8bdda41291ca4a76b132b3185a9" ]
[ "tf_explain/core/activations.py" ]
[ "\"\"\"\nCore Module for Activations Visualizations\n\"\"\"\nimport numpy as np\nimport tensorflow as tf\n\nfrom tf_explain.utils.display import filter_display\nfrom tf_explain.utils.saver import save_grayscale\n\n\nclass ExtractActivations:\n\n \"\"\" Draw activations of a specific layer for a given input \"\"\"\n\n def __init__(self, batch_size=None):\n self.batch_size = batch_size\n\n def explain(self, validation_data, model, layers_name):\n \"\"\"\n Compute activations at targeted layers.\n\n Args:\n validation_data (Tuple[np.ndarray, Optional[np.ndarray]]): Validation data\n to perform the method on. Tuple containing (x, y).\n model (tf.keras.Model): tf.keras model to inspect\n layers_name (List[str]): List of layer names to inspect\n\n Returns:\n np.ndarray: Grid of all the activations\n \"\"\"\n activations_model = self.generate_activations_graph(model, layers_name)\n\n predictions = activations_model.predict(\n validation_data[0], batch_size=self.batch_size\n )\n grid = filter_display(predictions)\n\n grid = (grid - grid.min()) / (grid.max() - grid.min())\n\n return (np.clip(grid, 0, 1) * 255).astype(\"uint8\")\n\n @staticmethod\n def generate_activations_graph(model, layers_name):\n \"\"\"\n Generate a graph between inputs and targeted layers.\n\n Args:\n model (tf.keras.Model): tf.keras model to inspect\n layers_name (List[str]): List of layer names to inspect\n\n Returns:\n tf.keras.Model: Subgraph to the targeted layers\n \"\"\"\n outputs = [layer.output for layer in model.layers if layer.name in layers_name]\n activations_model = tf.keras.models.Model(model.inputs, outputs=outputs)\n activations_model.compile(optimizer=\"sgd\", loss=\"categorical_crossentropy\")\n\n return activations_model\n\n def save(self, grid, output_dir, output_name):\n \"\"\"\n Save the output to a specific dir.\n\n Args:\n grid (numpy.ndarray): Grid of all the activations\n output_dir (str): Output directory path\n output_name (str): Output name\n \"\"\"\n save_grayscale(grid, output_dir, output_name)\n" ]
[ [ "numpy.clip", "tensorflow.keras.models.Model" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "2.7", "2.2", "2.3", "2.4", "2.5", "2.6" ] } ]
alshenoudy/ddpmMed
[ "b00a8d06a46ee5d49dbe1a391891a3c62b780b25", "b00a8d06a46ee5d49dbe1a391891a3c62b780b25" ]
[ "ddpmMed/utils/data.py", "ddpmMed/data/datasets.py" ]
[ "import os.path\n\nimport torch\nimport numpy as np\nfrom PIL import Image\nimport blobfile as bf\nimport tifffile as tiff\nfrom typing import Union, Any, List, Callable\nfrom torch.nn.functional import interpolate\nfrom matplotlib import pyplot as plt\nfrom torch.utils.data import DataLoader, Dataset\n\n\ndef imread(path: str):\n \"\"\"\n A Generic imread for our use-cases, returns a PIL image for normal images\n and a torch tensor for multi-page tiff images\n \"\"\"\n if not bf.exists(path):\n raise FileExistsError(f\"file ({path}) does not exist\")\n\n extension = path.split('.')[-1].lower()\n if extension in ['tif', 'tiff']:\n image = _read_tiff(path)\n elif extension in ['jpeg', 'jpg', 'png']:\n image = Image.open(path)\n else:\n raise RuntimeError(f\"unknown image format ({extension})\")\n return image\n\n\ndef _read_tiff(path: str):\n \"\"\"\n reads tiff images and multi-page tiff images, returns a torch tensor\n with a shape of [channels, height, width]\n \"\"\"\n image = tiff.imread(path)\n if image.ndim > 2:\n # format is (C, H, W)\n channels = image.shape[-1]\n if channels >= 4:\n _images = list()\n for i in range(0, channels):\n _images.append(torch.from_numpy(image[:, :, i]))\n image = torch.stack(_images, dim=0).squeeze()\n else:\n # format is (H, W)\n image = torch.from_numpy(image).unsqueeze(0)\n return image\n\n\ndef torch2np(x: torch.Tensor, squeeze: bool = False) -> np.ndarray:\n \"\"\"\n Converts a PyTorch tensor from (BATCH, CHANNELS, H, W) to (W, H, CHANNELS, BATCH)\n\n :param x: Input tensor\n :param squeeze: Boolean to squeeze single dimensions in output\n :return: numpy tensor in requested format\n \"\"\"\n if isinstance(x, torch.Tensor):\n if x.device != 'cpu':\n x = x.detach().cpu()\n x = x.numpy()\n\n if x.ndim == 4:\n # x has shape (b, c, rows, cols)\n x = np.transpose(x, (2, 3, 1, 0))\n elif x.ndim == 3:\n # x has shape (c, rows, cols)\n x = np.transpose(x, (1, 2, 0))\n\n if squeeze:\n x = x.squeeze()\n return x\n\n\ndef normalize(x: Union[np.ndarray, torch.Tensor]) -> Union[np.ndarray, torch.Tensor]:\n \"\"\"\n Normalizes an input x using zi = (xi - min(x))/(max(x) - min(x))\n\n :param x: input image\n :return: Returns normalized data with the same type\n \"\"\"\n if isinstance(x, np.ndarray):\n x_min, x_max = np.min(x), np.max(x)\n x = (x - x_min) / ((x_max - x_min) + 1e-12)\n elif isinstance(x, torch.Tensor):\n x_min, x_max = torch.min(x), torch.max(x)\n x = (x - x_min) / ((x_max - x_min) + 1e-12)\n else:\n raise NotImplementedError(\"Unsupported type: {}\".format(type(x)))\n\n return x\n\n\ndef dump_brats_dataset(dataset: Dataset, dump_folder: str):\n \"\"\" Brats Specific dataset dump \"\"\"\n\n dump_folder = os.path.join(dump_folder, \"dataset\")\n if not os.path.exists(dump_folder):\n os.makedirs(dump_folder, exist_ok=True)\n\n for i, (image, mask) in enumerate(dataset):\n fig, ax = plt.subplots(1, 5)\n ax[0].imshow(torch2np(image)[:, :, 0], cmap=\"gray\")\n ax[1].imshow(torch2np(image)[:, :, 1], cmap=\"gray\")\n ax[2].imshow(torch2np(image)[:, :, 2], cmap=\"gray\")\n ax[3].imshow(torch2np(image)[:, :, 3], cmap=\"gray\")\n ax[4].imshow(torch2np(mask), cmap=\"gray\")\n\n ax[0].set_title(\"T1\")\n ax[1].set_title(\"T1ce\")\n ax[2].set_title(\"T2\")\n ax[3].set_title(\"Flair\")\n ax[4].set_title(\"Ground Truth\")\n\n ax[0].set_axis_off()\n ax[1].set_axis_off()\n ax[2].set_axis_off()\n ax[3].set_axis_off()\n ax[4].set_axis_off()\n plt.savefig(os.path.join(dump_folder, f\"sample_{i}.jpeg\"))\n plt.close()\n\n\ndef scale_features(activations: List[torch.Tensor], size: int):\n \"\"\" Scales a list of activations to a given size \"\"\"\n assert all([isinstance(act, torch.Tensor) for act in activations])\n resized = []\n for features in activations:\n resized.append(\n interpolate(features, size, mode='bilinear', align_corners=False)[0]\n )\n return torch.cat(resized, dim=0)\n\n\ndef prepare_brats_pixels(data: Any,\n feature_extractor: Callable,\n image_size: int,\n num_features: int):\n\n image_size = (image_size, image_size)\n x = torch.zeros((len(data), num_features, *image_size), dtype=torch.float32)\n y = torch.zeros((len(data), *image_size), dtype=torch.uint8)\n\n for i in range(0, len(data)):\n image, mask = data[i]\n\n # dimensions, and create a features list\n c, h, w = image.shape\n features = feature_extractor(image)\n features = scale_features(features, h)\n x[i] = features\n y[i] = mask\n x = x.permute(1, 0, 2, 3).reshape(num_features, -1).permute(1, 0)\n y = y.flatten()\n y = brats_labels(y)\n\n return x, y\n\n\ndef balance_labels(x: torch.Tensor, y: torch.Tensor):\n\n # balance all labels\n labels, counts = torch.unique(y, return_counts=True)\n mean = int(torch.mean(counts.float()).item())\n\n base = torch.ones_like(counts) * mean\n size = base - counts\n\n sampled_x = []\n sampled_y = []\n for label in labels:\n label = label.item()\n if size[label] != 0 and label != 0:\n # new size for this label\n new_size = counts[label] + size[label].item()\n new_size = new_size.item()\n if size[label] < 0:\n new_x, new_y = x[y == label], y[y == label]\n new_y = new_y.unsqueeze(-1)\n total_length = len(new_y)\n idxs = torch.randint(low=0, high=total_length, size=(new_size, 1)).squeeze()\n new_x = torch.index_select(input=new_x, dim=0, index=idxs)\n new_y = torch.index_select(input=new_y, dim=0, index=idxs)\n else:\n new_x, new_y = x[y == label], y[y == label]\n new_y = new_y.unsqueeze(-1)\n total_length = len(new_y)\n tile = int(np.ceil(new_size/total_length)) + 1\n new_x = torch.tile(new_x, (tile, 1))[0:new_size, :]\n new_y = torch.tile(new_y, (tile, 1))[0:new_size, :]\n sampled_x.append(new_x)\n sampled_y.append(new_y)\n sampled_x = torch.concat(sampled_x, dim=0)\n sampled_y = torch.concat(sampled_y)\n return sampled_x, sampled_y.squeeze()\n\n\ndef brats_labels(mask: torch.Tensor) -> torch.Tensor:\n \"\"\" map brats labels \"\"\"\n mask[mask == 4] = 3\n return mask\n\n\ndef binary_brats(mask: torch.Tensor) -> torch.Tensor:\n \"\"\" whole tumor for brats \"\"\"\n mask[mask > 0] = 1\n return mask\n\n\ndef brats_tumor_core(mask: torch.Tensor) -> torch.Tensor:\n \"\"\"tumor core for brats \"\"\"\n mask[mask == 4] = 3\n mask[mask == 2] = 0\n mask[mask > 1] = 1\n return mask\n\n\ndef brats_ET(mask: torch.Tensor) -> torch.Tensor:\n \"\"\" Enhancing Tumor for brats\"\"\"\n mask[mask == 4] = 3\n mask[mask < 3] = 0\n mask[mask > 1] = 1\n return mask\n", "import torch\nimport blobfile as bf\nfrom typing import Tuple, Union, Callable\nimport torchvision.transforms as Tr\nfrom torch.utils.data import Dataset\nimport ddpmMed.data.transforms as t\nfrom ddpmMed.utils.data import imread, brats_labels\n\n\nclass SegmentationDataset(Dataset):\n \"\"\"\n A dataset object for semantic segmentation in Pytorch, requires path to images and\n masks folders\n\n :param images_dir: directory pointing to image data as a string\n :param masks_dir: directory pointing to mask data as a string\n :param image_size: final image/mask size after transformations\n :param seed: random seed\n :param device: a string representing which device either cpu/cuda\n \"\"\"\n\n def __init__(self,\n images_dir: str,\n masks_dir: str,\n image_size: int = 128,\n transforms: Union[t.Compose, Tr.Compose] = None,\n seed: int = 42,\n device: str = 'cpu',\n process_labels: Callable = None,\n train: bool = True) -> None:\n\n self.images_dir = images_dir\n self.masks_dir = masks_dir\n self.image_size = image_size\n self.seed = seed\n self.device = device\n self.transforms = transforms\n\n # labels processing\n if process_labels is None:\n self.map_labels = brats_labels\n else:\n self.map_labels = process_labels\n\n self.dataset = []\n self.train = train\n self._ext = ['jpg', 'jpeg', 'tif', 'tiff', 'png']\n\n # set seed manually\n torch.manual_seed(self.seed)\n\n # define transforms\n if self.transforms is None:\n self.transforms = t.Compose([\n t.Resize(self.image_size),\n t.CenterCrop(self.image_size),\n t.RandomHorizontalFlip(0.5),\n t.PILToTensor(),\n t.Lambda(lambda v: (v * 2) - 1)\n ])\n\n # validate directories\n if not bf.exists(self.images_dir):\n raise FileExistsError(\"images directory does not exits\")\n if not bf.exists(self.masks_dir):\n raise FileExistsError(\"masks directory does not exits\")\n\n all_images = bf.listdir(self.images_dir)\n all_images = [bf.join(self.images_dir, img) for img in all_images if img.split('.')[-1].lower() in self._ext]\n if self.train:\n all_masks = bf.listdir(self.masks_dir)\n all_masks = [bf.join(self.masks_dir, msk) for msk in all_masks if msk.split('.')[-1].lower() in self._ext]\n\n if len(all_images) != len(all_masks):\n raise RuntimeError(f\"total images ({len(all_images)}) does not match total masks ({len(all_masks)})\")\n i = 0\n image_name, mask_name = \"\", \"\"\n try:\n # attempt to create a dataset of images and masks\n for i in range(0, len(all_images)):\n\n # get image and mask names\n image_name = bf.basename(all_images[i]).split('.')[0].lower()\n if self.train:\n mask_name = bf.basename(all_masks[i]).split('.')[0].lower()\n\n # image name and mask name should be equivalent\n if image_name != mask_name:\n raise NameError(f\"image ({image_name}) and mask ({mask_name}) names are not matching\")\n\n if self.train:\n # add items to dataset\n self.dataset.append({\n 'image': all_images[i],\n 'mask': all_masks[i]\n })\n else:\n self.dataset.append({\n 'image': all_images[i]\n })\n\n print(f\"\\rCreating segmentation dataset [{i + 1}/{len(all_images)}]\", end='', flush=True)\n print(f\"\\rCreated segmentation dataset with {len(all_images)} items\\n\\n\")\n\n except Exception as ex:\n raise RuntimeError(f\"error occurred while creating dataset at index ({i})\\n\"\n f\"Image name {image_name}\\n\"\n f\"Mask name {mask_name}\\n\"\n f\"Error: {ex}\")\n\n def __len__(self):\n return len(self.dataset)\n\n def __getitem__(self, item) -> Tuple[torch.Tensor, torch.Tensor]:\n\n # get data at given index\n data = self.dataset[item]\n image_path, mask_path = data['image'], data['mask']\n\n # read image and mask\n image = imread(image_path)\n if self.train:\n mask = imread(mask_path)\n else:\n mask = None\n\n # apply transforms\n image, mask = self.transforms(image, mask)\n mask = self.map_labels(mask)\n\n return image.to(self.device), mask.to(self.device)\n\n\nclass PixelDataset(Dataset):\n \"\"\"\n Dataset class containing all pixel representations/features and\n their corresponding labels\n\n :param x_data: a flattened tensor with all pixels activations with a shape of (num_pixels, num_features)\n :param y_data: a flattened tensor with all pixel labels with a shape of (num_pixels)\n \"\"\"\n\n def __init__(self,\n x_data: torch.Tensor,\n y_data: torch.Tensor,\n device: str = 'cuda') -> None:\n self.x_data = x_data\n self.y_data = y_data\n self.device = device\n\n def __len__(self) -> int:\n return len(self.x_data)\n\n def __getitem__(self, item) -> Tuple[torch.Tensor, torch.Tensor]:\n \"\"\" returns a single pixel representation and it's target label \"\"\"\n return self.x_data[item].to(self.device), self.y_data[item].to(self.device)\n\n\nclass ImageDataset(Dataset):\n def __init__(self,\n images_dir: str,\n image_size: int = 128,\n transforms: Union[t.Compose, Tr.Compose] = None,\n seed: int = 42,\n device: str = 'cpu'\n ):\n self.images_dir = images_dir\n self.image_size = image_size\n self.transforms = transforms\n self.seed = seed\n self.device = device\n\n self.extensions = ['tiff', 'tif', 'jpeg', 'jpg', 'png']\n self.dataset = []\n\n # set seed\n torch.manual_seed(self.seed)\n\n # check path\n if not bf.exists(self.images_dir):\n raise FileExistsError(f\"given directory ({self.images_dir}) does not exist\")\n\n if not bf.isdir(self.images_dir):\n raise NotADirectoryError(f\"given path ({self.images_dir}) is not a directory\")\n\n if self.transforms is None:\n self.transforms = Tr.Compose([\n Tr.Resize(self.image_size),\n Tr.RandomHorizontalFlip(0.5),\n Tr.CenterCrop(self.image_size),\n # Tr.ToTensor(), # our imread directly returns a tensor\n Tr.Lambda(lambda v: (v * 2) - 1)\n ])\n try:\n self.dataset = [bf.join(self.images_dir, img) for img in bf.listdir(self.images_dir)\n if img.split('.')[-1].lower() in self.extensions]\n except Exception as ex:\n raise RuntimeError(\"Unable to create image dataset.\\n\"\n f\"Error: {ex}\")\n\n def __len__(self):\n return len(self.dataset)\n\n def __getitem__(self, index):\n image_path = self.dataset[index]\n image = imread(image_path)\n image = self.transforms(image)\n return image, {}\n" ]
[ [ "torch.concat", "torch.randint", "torch.max", "torch.cat", "numpy.min", "torch.tile", "torch.min", "matplotlib.pyplot.subplots", "torch.from_numpy", "numpy.max", "numpy.ceil", "torch.unique", "matplotlib.pyplot.close", "numpy.transpose", "torch.nn.functional.interpolate", "torch.index_select", "torch.ones_like", "torch.stack" ], [ "torch.manual_seed" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
chen-zhan/stDrosophila-release-1
[ "1b128eb81ff4d076f7271abb1298639be6d08310", "1b128eb81ff4d076f7271abb1298639be6d08310" ]
[ "stDrosophila/tools/cluster/cluster_spagcn.py", "stDrosophila/plot/three_d_plots.py" ]
[ "import random\n\nimport numpy as np\nimport pandas as pd\nimport SpaGCN as spg\nimport torch\n\nfrom anndata import AnnData\nfrom typing import Optional\n\ntry:\n from typing import Literal\nexcept ImportError:\n from typing_extensions import Literal\n\nfrom .utils import compute_pca_components\n\n\ndef cluster_spagcn(\n adata: AnnData,\n spatial_key: str = \"spatial\",\n key_added: Optional[str] = \"spagcn_pred\",\n n_pca_components: Optional[int] = None,\n e_neigh: int = 10,\n resolution: float = 0.4,\n n_clusters: Optional[int] = None,\n refine_shape: Literal[\"hexagon\", \"square\"] = \"hexagon\",\n p: float = 0.5,\n seed: int = 100,\n numIterMaxSpa: int = 2000,\n copy: bool = False,\n verbose: bool = True,\n) -> Optional[AnnData]:\n \"\"\"\n Integrating gene expression and spatial location to identify spatial domains via SpaGCN.\n Original Code Repository: https://github.com/jianhuupenn/SpaGCN\n\n Args:\n adata: An Anndata object after normalization.\n spatial_key: the key in `.obsm` that corresponds to the spatial coordinate of each bucket.\n key_added: adata.obs key under which to add the cluster labels.\n The initial clustering results of SpaGCN are under `key_added`,\n and the refined clustering results are under `f'{key_added}_refined'`.\n n_pca_components: Number of principal components to compute.\n If `n_pca_components` == None, the value at the inflection point of the PCA curve is\n automatically calculated as n_comps.\n e_neigh: Number of nearest neighbor in gene expression space.Used in sc.pp.neighbors(adata, n_neighbors=e_neigh).\n resolution: Resolution in the Louvain's Clustering method. Used when `n_clusters`==None.\n n_clusters: Number of spatial domains wanted.\n If `n_clusters` != None, the suitable resolution in the initial Louvain's\n Clustering methods will be automatically searched based on n_clusters.\n refine_shape: Smooth the spatial domains with given spatial topology, \"hexagon\" for Visium data, \"square\" for ST data. Defaults to None.\n p: Percentage of total expression contributed by neighborhoods.\n seed: Global seed for `random`, `torch`, `numpy`. Defaults to 100.\n numIterMaxSpa: SpaGCN maximum number of training iterations.\n copy: Whether to copy `adata` or modify it inplace.\n verbose: Print information about clustering.\n\n Returns:\n Updates adata with the field ``adata.obs[key_added]`` and ``adata.obs[f'{key_added}_refined']``,\n containing the cluster result based on SpaGCN.\n \"\"\"\n\n adata = adata.copy() if copy else adata\n\n # Spatial coordinates.\n coords_x = adata.obsm[spatial_key][:, 0]\n coords_y = adata.obsm[spatial_key][:, 1]\n\n # Calculate the adjacent matrix.\n adj = spg.calculate_adj_matrix(x=coords_x, y=coords_y, histology=False)\n\n # Find the l value given p to control p.\n l = spg.search_l(p, adj, start=0.01, end=1000, tol=0.01, max_run=100)\n\n # Set seed.\n r_seed = t_seed = n_seed = seed\n\n # Set the resolution in the initial Louvain's Clustering methods.\n if n_clusters is None:\n res = resolution\n else:\n # Search for suitable resolution based on n_clusters.\n res = spg.search_res(\n adata,\n adj,\n l,\n n_clusters,\n start=resolution,\n step=0.1,\n tol=5e-3,\n lr=0.05,\n max_epochs=200,\n r_seed=r_seed,\n t_seed=t_seed,\n n_seed=n_seed,\n )\n\n # Run SpaGCN\n clf = spg.SpaGCN()\n clf.set_l(l)\n\n random.seed(r_seed)\n torch.manual_seed(t_seed)\n np.random.seed(n_seed)\n\n if n_pca_components is None:\n n_pca_components, _ = compute_pca_components(adata.X, save_curve_img=None)\n clf.train(\n adata,\n adj,\n num_pcs=n_pca_components,\n n_neighbors=e_neigh,\n init_spa=True,\n init=\"louvain\",\n res=res,\n tol=5e-3,\n lr=0.05,\n max_epochs=numIterMaxSpa,\n )\n\n # SpaGCN Cluster result.\n y_pred, prob = clf.predict()\n adata.obs[key_added] = y_pred\n adata.obs[key_added] = adata.obs[key_added].astype(\"category\")\n\n # Do cluster refinement\n adj_2d = spg.calculate_adj_matrix(x=coords_x, y=coords_y, histology=False)\n refined_pred = spg.refine(\n sample_id=adata.obs.index.tolist(),\n pred=adata.obs[key_added].tolist(),\n dis=adj_2d,\n shape=refine_shape,\n )\n adata.obs[f\"{key_added}_refined\"] = refined_pred\n adata.obs[f\"{key_added}_refined\"] = adata.obs[f\"{key_added}_refined\"].astype(\n \"category\"\n )\n\n return adata if copy else None\n", "import math\n\nimport matplotlib as mpl\nimport pandas as pd\nimport pyvista as pv\n\nfrom pyvista import MultiBlock, Plotter, PolyData, UnstructuredGrid\nfrom typing import Optional, Union\n\ntry:\n from typing import Literal\nexcept ImportError:\n from typing_extensions import Literal\n\n\ndef create_plotter(\n jupyter: bool = False,\n off_screen: bool = False,\n window_size: tuple = (1024, 768),\n background: str = \"white\",\n initial_cpo: Union[str, tuple, list] = \"iso\",\n) -> Plotter:\n \"\"\"\n Create a plotting object to display pyvista/vtk mesh.\n\n Args:\n jupyter: Whether to plot in jupyter notebook.\n off_screen: Renders off screen when True. Useful for automated screenshots.\n window_size: Window size in pixels. The default window_size is `[1024, 768]`.\n background: The background color of the window.\n initial_cpo: Camera position of the window. Available `initial_cpo` are:\n * `'xy'`, `'xz'`, `'yz'`, `'yx'`, `'zx'`, `'zy'`, `'iso'`\n * Customize a tuple. E.g.: (7, 0, 20.).\n Returns:\n plotter: The plotting object to display pyvista/vtk mesh.\n \"\"\"\n\n # Create an initial plotting object.\n notebook = True if jupyter is True else False\n plotter = pv.Plotter(\n off_screen=off_screen,\n window_size=window_size,\n notebook=notebook,\n lighting=\"light_kit\",\n )\n\n # Set camera position of the active render window.\n plotter.camera_position = initial_cpo\n\n # Set the background color of the active render window.\n plotter.background_color = background\n\n # Contrasting color of the background color.\n bg_rgb = mpl.colors.to_rgb(background)\n cbg_rgb = (1 - bg_rgb[0], 1 - bg_rgb[1], 1 - bg_rgb[2])\n\n # Add an interactive axes widget in the bottom left corner.\n plotter.add_axes(color=cbg_rgb)\n\n if jupyter is True:\n # Description of control 3D images in jupyter notebook.\n plotter.add_text(\n \"The method to control 3D images in jupyter notebook is as follows:\"\n \"CTRL Left Mouse spins the camera around its view plane normal;\"\n \"SHIFT Left Mouse pans the camera; \"\n \"CTRL SHIFT Left Mouse dollies (a positional zoom) the camera;\"\n \"Left mouse button dollies the camera.\",\n font_size=12,\n color=cbg_rgb,\n font=\"arial\",\n )\n else:\n # Add a camera orientation widget to the active renderer (This Widget cannot be used in jupyter notebook).\n plotter.add_camera_orientation_widget()\n\n return plotter\n\n\ndef add_plotter(\n plotter: Plotter,\n mesh: Union[PolyData, UnstructuredGrid, MultiBlock],\n key: str = None,\n ambient: float = 0.2,\n opacity: float = 1.0,\n style: Literal[\"points\", \"surface\", \"volume\"] = \"surface\",\n point_size: float = 5.0,\n legend_loc: Literal[\n \"upper right\",\n \"upper left\",\n \"lower left\",\n \"lower right\",\n \"center left\",\n \"lower center\",\n \"upper center\",\n \"center\",\n ] = \"lower right\",\n legend_size: tuple = (0.1, 0.1),\n):\n \"\"\"\n Add mesh(es) to the plotter.\n\n Args:\n plotter: The plotting object to display pyvista/vtk mesh.\n mesh: A reconstructed mesh.\n key: The key under which are the labels.\n ambient: When lighting is enabled, this is the amount of light in the range of 0 to 1 (default 0.0) that reaches\n the actor when not directed at the light source emitted from the viewer.\n opacity: Opacity of the mesh. If a single float value is given, it will be the global opacity of the mesh and\n uniformly applied everywhere - should be between 0 and 1.\n A string can also be specified to map the scalars range to a predefined opacity transfer function\n (options include: 'linear', 'linear_r', 'geom', 'geom_r').\n style: Visualization style of the mesh. One of the following: style='surface', style='volume', style='points'.\n point_size: Point size of any nodes in the dataset plotted.\n legend_loc: The location of the legend in the window. Available `legend_loc` are:\n * `'upper right'`\n * `'upper left'`\n * `'lower left'`\n * `'lower right'`\n * `'center left'`\n * `'lower center'`\n * `'upper center'`\n * `'center'`\n legend_size: The size of the legend in the window. Two float sequence, each float between 0 and 1.\n E.g.: (0.1, 0.1) would make the legend 10% the size of the entire figure window.\n Returns:\n plotter: The plotting object to display pyvista/vtk mesh.\n \"\"\"\n\n def _add_mesh(_p, _mesh):\n \"\"\"Add any PyVista/VTK mesh to the scene.\"\"\"\n\n mesh_style = \"points\" if style == \"points\" else None\n _p.add_mesh(\n _mesh,\n scalars=f\"{key}_rgba\",\n rgba=True,\n render_points_as_spheres=True,\n style=mesh_style,\n point_size=point_size,\n ambient=ambient,\n opacity=opacity,\n )\n\n # Add mesh(es) to the plotter.\n if isinstance(mesh, MultiBlock):\n for sub_mesh in mesh:\n _add_mesh(_p=plotter, _mesh=sub_mesh)\n else:\n _add_mesh(_p=plotter, _mesh=mesh)\n\n # Add a legend to the plotter.\n if key is not None:\n if isinstance(mesh, MultiBlock):\n legends = pd.DataFrame()\n for sub_mesh in mesh:\n sub_labels = pd.Series(sub_mesh[key])\n sub_labels_hex = pd.Series(\n [mpl.colors.to_hex(i) for i in sub_mesh[f\"{key}_rgba\"]]\n )\n sub_legends = pd.concat([sub_labels, sub_labels_hex], axis=1)\n legends = pd.concat([legends, sub_legends])\n else:\n labels = pd.Series(mesh[key])\n labels_hex = pd.Series([mpl.colors.to_hex(i) for i in mesh[f\"{key}_rgba\"]])\n legends = pd.concat([labels, labels_hex], axis=1)\n\n legends.columns = [\"label\", \"hex\"]\n legends.drop_duplicates(inplace=True)\n\n legends = legends[legends[\"label\"] != \"mask\"]\n if len(legends.index) != 0:\n legends.sort_values(by=[\"label\", \"hex\"], inplace=True)\n legends.index = range(len(legends.index))\n legends = legends.astype(str)\n\n try:\n _try = legends[\"label\"].copy()\n _try = _try.astype(float)\n label_type = \"float\"\n except:\n label_type = \"str\"\n\n gap = math.ceil(len(legends.index) / 5) if label_type == \"float\" else 1\n legend_entries = [\n [legends[\"label\"].iloc[i], legends[\"hex\"].iloc[i]]\n for i in range(0, len(legends.index), gap)\n ]\n if label_type == \"float\":\n legend_entries.append(\n [legends[\"label\"].iloc[-1], legends[\"hex\"].iloc[-1]]\n )\n\n plotter.add_legend(\n legend_entries,\n face=\"circle\",\n bcolor=None,\n loc=legend_loc,\n size=legend_size,\n )\n\n\ndef output_plotter(\n p: Plotter,\n filename: str,\n view_up: tuple = (0.5, 0.5, 1),\n framerate: int = 15,\n):\n \"\"\"\n Output plotter as image, gif file or mp4 file.\n\n Args:\n p: The plotting object to display pyvista/vtk mesh.\n filename: Filename of output file. Writer type is inferred from the extension of the filename.\n * Output an image file,\n please enter a filename ending with `.png`, `.tif`, `.tiff`, `.bmp`, `.jpeg`, `.jpg`.\n * Output a gif file, please enter a filename ending with `.gif`.\n * Output a mp4 file, please enter a filename ending with `.mp4`.\n view_up: The normal to the orbital plane. Only available when filename ending with `.mp4` or `.gif`.\n framerate: Frames per second. Only available when filename ending with `.mp4` or `.gif`.\n Returns:\n img: Numpy array of the last image.\n Returned only if filename ending with `.png`, `.tif`, `.tiff`, `.bmp`, `.jpeg`, `.jpg`.\n \"\"\"\n\n def _to_gif(_filename, _view_up):\n \"\"\"Output plotter to gif file.\"\"\"\n path = p.generate_orbital_path(\n factor=2.0, shift=0, viewup=_view_up, n_points=20\n )\n p.open_gif(_filename)\n p.orbit_on_path(path, write_frames=True, viewup=(0, 0, 1), step=0.1)\n p.close()\n\n def _to_mp4(_filename, _view_up, _framerate):\n \"\"\"Output plotter to mp4 file.\"\"\"\n path = p.generate_orbital_path(\n factor=2.0, shift=0, viewup=_view_up, n_points=20\n )\n p.open_movie(_filename, framerate=_framerate, quality=5)\n p.orbit_on_path(path, write_frames=True, viewup=(0, 0, 1), step=0.1)\n p.close()\n\n # The format of the output file.\n filename_format = filename.split(\".\")[-1]\n\n # Output the plotter in the format of the output file.\n if filename_format in [\"png\", \"tif\", \"tiff\", \"bmp\", \"jpeg\", \"jpg\"]:\n _, img = p.show(\n screenshot=filename,\n return_img=True,\n return_cpos=True,\n )\n return img\n elif filename_format == \"gif\":\n _to_gif(_filename=filename, _view_up=view_up)\n return None\n elif filename_format == \"mp4\":\n _to_mp4(_filename=filename, _view_up=view_up, _framerate=framerate)\n return None\n else:\n raise ValueError(\n \"\\nFilename is wrong.\"\n \"\\nIf outputting an image file, \"\n \"please enter a filename ending with `.png`, `.tif`, `.tiff`, `.bmp`, `.jpeg`, `.jpg`.\"\n \"\\nIf outputting a gif file, please enter a filename ending with `.gif`.\"\n \"\\nIf outputting a mp4 file, please enter a filename ending with `.mp4`.\"\n )\n\n\ndef save_plotter(\n p: Plotter,\n filename: str,\n):\n \"\"\"Save plotter as gltf file, html file, obj file or vtkjs file.\n\n Args:\n p: The plotting object to display pyvista/vtk mesh.\n filename: The filename of the file where the plotter is saved.\n Writer type is inferred from the extension of the filename.\n * Output a gltf file, please enter a filename ending with `.gltf`.\n * Output a html file, please enter a filename ending with `.html`.\n * Output an obj file, please enter a filename ending with `.obj`.\n * Output a vtkjs file, please enter a filename without format.\n \"\"\"\n\n # The format of the save file.\n filename_format = filename.split(\".\")[-1]\n\n # Save the plotter in the format of the output file.\n if filename_format == \"gltf\":\n p.export_gltf(filename)\n elif filename_format == \"html\":\n p.export_html(filename)\n elif filename_format == \"obj\":\n p.export_obj(filename)\n else:\n p.export_vtkjs(filename)\n\n\ndef three_d_plot(\n mesh: Union[PolyData, UnstructuredGrid, MultiBlock],\n key: str = None,\n filename: Optional[str] = None,\n jupyter: bool = False,\n off_screen: bool = False,\n window_size: tuple = (1024, 768),\n background: str = \"white\",\n ambient: float = 0.2,\n opacity: float = 1.0,\n style: Literal[\"points\", \"surface\", \"volume\"] = \"surface\",\n point_size: float = 5.0,\n initial_cpo: Union[str, tuple] = \"iso\",\n legend_loc: Literal[\n \"upper right\",\n \"upper left\",\n \"lower left\",\n \"lower right\",\n \"center left\",\n \"lower center\",\n \"upper center\",\n \"center\",\n ] = \"lower right\",\n legend_size: tuple = (0.1, 0.1),\n view_up: tuple = (0.5, 0.5, 1),\n framerate: int = 15,\n plotter_filename: Optional[str] = None,\n):\n \"\"\"\n Visualize reconstructed 3D meshes.\n\n Args:\n mesh: A reconstructed mesh.\n key: The key under which are the labels.\n filename: Filename of output file. Writer type is inferred from the extension of the filename.\n * Output an image file,\n please enter a filename ending with `.png`, `.tif`, `.tiff`, `.bmp`, `.jpeg`, `.jpg`.\n * Output a gif file, please enter a filename ending with `.gif`.\n * Output a mp4 file, please enter a filename ending with `.mp4`.\n jupyter: Whether to plot in jupyter notebook.\n off_screen: Renders off-screen when True. Useful for automated screenshots.\n window_size: Window size in pixels. The default window_size is `[1024, 768]`.\n background: The background color of the window.\n ambient: When lighting is enabled, this is the amount of light in the range of 0 to 1 (default 0.0) that reaches\n the actor when not directed at the light source emitted from the viewer.\n opacity: Opacity of the mesh. If a single float value is given, it will be the global opacity of the mesh and\n uniformly applied everywhere - should be between 0 and 1.\n A string can also be specified to map the scalars range to a predefined opacity transfer function\n (options include: 'linear', 'linear_r', 'geom', 'geom_r').\n style: Visualization style of the mesh. One of the following: style='surface', style='volume', style='points'.\n point_size: Point size of any nodes in the dataset plotted.\n initial_cpo: Camera position of the window. Available `initial_cpo` are:\n * `'xy'`, `'xz'`, `'yz'`, `'yx'`, `'zx'`, `'zy'`, `'iso'`\n * Customize a tuple. E.g.: (7, 0, 20.).\n legend_loc: The location of the legend in the window. Available `legend_loc` are:\n * `'upper right'`\n * `'upper left'`\n * `'lower left'`\n * `'lower right'`\n * `'center left'`\n * `'lower center'`\n * `'upper center'`\n * `'center'`\n legend_size: The size of the legend in the window. Two float sequence, each float between 0 and 1.\n E.g.: (0.1, 0.1) would make the legend 10% the size of the entire figure window.\n view_up: The normal to the orbital plane. Only available when filename ending with `.mp4` or `.gif`.\n framerate: Frames per second. Only available when filename ending with `.mp4` or `.gif`.\n plotter_filename: The filename of the file where the plotter is saved.\n Writer type is inferred from the extension of the filename.\n * Output a gltf file, please enter a filename ending with `.gltf`.\n * Output a html file, please enter a filename ending with `.html`.\n * Output an obj file, please enter a filename ending with `.obj`.\n * Output a vtkjs file, please enter a filename without format.\n Returns:\n img: Numpy array of the last image.\n Returned only if filename ending with `.png`, `.tif`, `.tiff`, `.bmp`, `.jpeg`, `.jpg`.\n \"\"\"\n\n # Create a plotting object to display pyvista/vtk mesh.\n p1 = create_plotter(\n jupyter=jupyter,\n off_screen=off_screen,\n window_size=window_size,\n background=background,\n initial_cpo=initial_cpo,\n )\n add_plotter(\n plotter=p1,\n mesh=mesh,\n key=key,\n ambient=ambient,\n opacity=opacity,\n style=style,\n point_size=point_size,\n legend_loc=legend_loc,\n legend_size=legend_size,\n )\n jupyter_backend = \"panel\" if jupyter is True else None\n cpo = p1.show(return_cpos=True, jupyter_backend=jupyter_backend)\n\n # Create another plotting object to save pyvista/vtk mesh.\n p2 = create_plotter(\n jupyter=jupyter,\n off_screen=True,\n window_size=window_size,\n background=background,\n initial_cpo=cpo,\n )\n p2 = add_plotter(\n plotter=p2,\n mesh=mesh,\n key=key,\n ambient=ambient,\n opacity=opacity,\n style=style,\n point_size=point_size,\n legend_loc=legend_loc,\n legend_size=legend_size,\n )\n\n # Save the plotting object.\n if plotter_filename is not None:\n save_plotter(p2, filename=plotter_filename)\n\n # Output the plotting object.\n if filename is not None:\n return output_plotter(\n p=p2, filename=filename, view_up=view_up, framerate=framerate\n )\n else:\n return None\n" ]
[ [ "torch.manual_seed", "numpy.random.seed" ], [ "pandas.concat", "pandas.Series", "matplotlib.colors.to_rgb", "matplotlib.colors.to_hex", "pandas.DataFrame" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [ "0.23", "0.21", "2.0", "1.4", "1.3", "0.19", "1.1", "1.5", "0.24", "0.20", "1.0", "0.25", "1.2" ], "scipy": [], "tensorflow": [] } ]
ZFhuang/DiveIntoDLSketches
[ "cf0654d06ab6eeaefc35fa3bebd4937f1cbbb165", "cf0654d06ab6eeaefc35fa3bebd4937f1cbbb165" ]
[ "Networks/LapSRN/LapSRN.py", "Networks/DBPN/DBPN.py" ]
[ "import torch\nfrom torch import nn\n\n# LapSRN, 拉普拉斯金字塔结构, 2017\n\n\nclass LapSRN(nn.Module):\n def __init__(self, fea_chan=64, scale=2, conv_num=3):\n super(LapSRN, self).__init__()\n self.level_num = int(scale/2)\n self.share_ski_upsample = nn.ConvTranspose2d(\n 1, 1, 4, stride=scale, padding=1)\n self.input_conv = nn.Conv2d(1, fea_chan, 3, padding=1)\n seq = []\n for _ in range(conv_num):\n seq.append(nn.Conv2d(fea_chan, fea_chan, 3, padding=1))\n seq.append(nn.LeakyReLU(0.2, True))\n self.share_embedding = nn.Sequential(*seq)\n self.share_fea_upsample = nn.ConvTranspose2d(\n fea_chan, fea_chan, 4, stride=scale, padding=1)\n self.share_output_conv = nn.Conv2d(fea_chan, 1, 3, padding=1)\n\n def forward(self, img):\n tmp = self.input_conv(img)\n for _ in range(self.level_num):\n skip = self.share_ski_upsample(img)\n img = self.share_embedding(tmp)\n img = self.share_fea_upsample(img)\n tmp = img\n img = self.share_output_conv(img)\n img = img+skip\n return img\n\n\nclass L1_Charbonnier_loss(torch.nn.Module):\n \"\"\"L1 Charbonnierloss.\"\"\"\n\n def __init__(self):\n super(L1_Charbonnier_loss, self).__init__()\n self.eps = 1e-6\n\n def forward(self, X, Y):\n diff = torch.add(X, -Y)\n error = torch.sqrt(diff * diff + self.eps)\n loss = torch.mean(error)\n return loss\n", "import torch\nimport logging\nfrom torch import nn\n\n# DBPN, 带反馈结构的超分辨, 2018\n\n\nclass Dense_DBPN(nn.Module):\n def __init__(self, in_channel=1, scale=2, num_pair=2, num_filter=18, grow_rate=18):\n super(Dense_DBPN, self).__init__()\n logging.debug('in_channel: '+str(in_channel))\n logging.debug('scale: '+str(scale))\n logging.debug('num_pair: '+str(num_pair))\n logging.debug('num_filter: '+str(num_filter))\n logging.debug('grow_rate: '+str(grow_rate))\n self.num_pair = num_pair\n self.feature_extraction = nn.Sequential(\n nn.Conv2d(in_channel, 64, 3, padding=1),\n nn.Conv2d(64, num_filter, 1, padding=0)\n )\n\n # pair+1个上采样块, 需要数量比下采样多一个\n seq = []\n seq.append(Up_projection(num_filter, grow_rate, scale))\n for i in range(num_pair):\n seq.append(Up_projection((i+1)*grow_rate, grow_rate, scale))\n self.up_proj = nn.Sequential(*seq)\n\n # pair个下采样块\n seq = []\n for i in range(num_pair):\n seq.append(Down_projection(\n (i+1)*grow_rate, grow_rate, scale))\n self.down_proj = nn.Sequential(*seq)\n\n self.reconstruction = nn.Conv2d(\n (num_pair+1)*grow_rate, 1, 3, padding=1)\n\n def forward(self, x):\n x = self.feature_extraction(x)\n up_skip = self.up_proj[0](x)\n down_skip = []\n for i in range(self.num_pair):\n if i == 0:\n down_skip = self.down_proj[i](up_skip)\n else:\n down_skip = torch.cat(\n (self.down_proj[i](up_skip), down_skip), dim=1)\n up_skip = torch.cat((self.up_proj[i+1](down_skip), up_skip), dim=1)\n x = self.reconstruction(up_skip)\n return x\n\n\nclass Up_projection(nn.Module):\n # 每导入一次块就x2\n def __init__(self, in_channel, out_channel=28, scale=2, deconv_size=8):\n super(Up_projection, self).__init__()\n self.input_conv = nn.Conv2d(in_channel, out_channel, 1, padding=0)\n self.deconv_base = nn.Sequential(\n nn.ConvTranspose2d(out_channel, out_channel,\n deconv_size, stride=scale, padding=deconv_size//2-1),\n nn.PReLU()\n )\n self.conv = nn.Sequential(\n nn.Conv2d(out_channel, out_channel, 6, stride=scale, padding=2),\n nn.PReLU()\n )\n self.deconv_fea = nn.Sequential(\n nn.ConvTranspose2d(out_channel, out_channel,\n deconv_size, stride=scale, padding=deconv_size//2-1),\n nn.PReLU()\n )\n\n def forward(self, x):\n x = self.input_conv(x)\n skip_fea = x\n x = self.deconv_base(x)\n skip_base = x\n x = self.conv(x)\n x = self.deconv_fea(x-skip_fea)\n return x+skip_base\n\n\nclass Down_projection(nn.Module):\n # 每导入一次块就x2\n def __init__(self, in_channel, out_channel=28, scale=2, deconv_size=8):\n super(Down_projection, self).__init__()\n self.input_conv = nn.Conv2d(in_channel, out_channel, 1, padding=0)\n self.conv_base = nn.Sequential(\n nn.Conv2d(out_channel, out_channel, 6, stride=2, padding=2),\n nn.PReLU()\n )\n self.deconv = nn.Sequential(\n nn.ConvTranspose2d(out_channel, out_channel,\n deconv_size, stride=scale, padding=deconv_size//2-1),\n nn.PReLU()\n )\n self.conv_fea = nn.Sequential(\n nn.Conv2d(out_channel, out_channel, 6, stride=2, padding=2),\n nn.PReLU()\n )\n\n def forward(self, x):\n x = self.input_conv(x)\n skip_fea = x\n x = self.conv_base(x)\n skip_base = x\n x = self.deconv(x)\n x = self.conv_fea(x-skip_fea)\n return x+skip_base\n" ]
[ [ "torch.nn.Sequential", "torch.mean", "torch.add", "torch.nn.ConvTranspose2d", "torch.sqrt", "torch.nn.Conv2d", "torch.nn.LeakyReLU" ], [ "torch.nn.Sequential", "torch.nn.Conv2d", "torch.nn.PReLU", "torch.nn.ConvTranspose2d" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
codeballet/image-classifier-flowers
[ "95263d2c482b4dd68e51994175f3703b28d86fdd" ]
[ "get_device.py" ]
[ "import torch\n\n\n# Make code device agnostic with respect to user input\ndef get_device(gpu):\n if gpu == 'on':\n device = torch.device(\"cuda:0\" if torch.cuda.is_available() \n else \"cpu\")\n \n else:\n device = torch.device(\"cpu\")\n \n return device" ]
[ [ "torch.device", "torch.cuda.is_available" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
dachr8/Exercise
[ "2e567f9edcf0d06ca4ed99cb65a0264546a36d63" ]
[ "BUPT/Machine-Learning-I/Assignment1/ml4_6.py" ]
[ "# TODO 机器学习 4.6.sp 试选择2个UCI数据集,对上述2种算法所产生的未剪枝、预剪枝、后剪枝决策树进行实验比较。\n\nfrom ml4_3 import ID3_tree\nfrom ml4_4 import CART_tree\nfrom sklearn.datasets import load_iris, load_wine\nfrom sklearn.model_selection import train_test_split # Import train_test_split function\n\n\ndef run_4_6(dataset, criterion):\n x_train, x_test, y_train, y_test = train_test_split(dataset.data,\n dataset.target_names[dataset.target],\n test_size=0.3,\n random_state=1) # 70% training and 30% test\n\n # Process data first\n train_target = list(y_train)\n test_target = list(y_test)\n\n train_data = []\n for melon in x_train:\n a_dict = {}\n dim = len(melon)\n for i in range(dim):\n a_dict[dataset.feature_names[i]] = melon[i]\n train_data.append(a_dict)\n\n test_data = []\n for melon in x_test:\n a_dict = {}\n dim = len(melon)\n for i in range(dim):\n a_dict[dataset.feature_names[i]] = melon[i]\n test_data.append(a_dict)\n\n if criterion == 'ID3':\n decision_tree = ID3_tree(train_data, dataset.feature_names, train_target)\n else:\n decision_tree = CART_tree(train_data, dataset.feature_names, train_target)\n\n print('未剪枝' + criterion + '决策树:')\n decision_tree.print()\n print('未剪枝' + criterion + '决策树在测试数据集上的分类正确率为:' + str(\n decision_tree.accuracy(test_data, test_target) * 100)[:5] + \"%\\n\\n\")\n\n decision_tree.post_pruning(test_data, test_target, train_target)\n print('后剪枝' + criterion + '决策树:')\n decision_tree.print()\n print('后剪枝' + criterion + '决策树在测试数据集上的分类正确率为:' + str(\n decision_tree.accuracy(test_data, test_target) * 100)[:5] + \"%\\n\\n\")\n\n if criterion == 'ID3':\n pre_pruning_decision_tree = ID3_tree(train_data, dataset.feature_names, train_target, test_data, test_target)\n else:\n pre_pruning_decision_tree = CART_tree(train_data, dataset.feature_names, train_target, test_data, test_target)\n print('预剪枝' + criterion + '决策树:')\n pre_pruning_decision_tree.print()\n print('预剪枝' + criterion + '决策树在测试数据集上的分类正确率为:' + str(\n pre_pruning_decision_tree.accuracy(test_data, test_target) * 100)[:5] + \"%\")\n\n\nif __name__ == '__main__':\n print('--------------------------------IRIS--------------------------------')\n iris = load_iris()\n print(iris.DESCR)\n run_4_6(iris, 'ID3')\n print('\\n')\n run_4_6(iris, 'CART')\n print('\\n\\n--------------------------------WINE--------------------------------')\n wine = load_wine()\n print(wine.DESCR)\n run_4_6(wine, 'ID3')\n print('\\n')\n run_4_6(wine, 'CART')\n" ]
[ [ "sklearn.datasets.load_wine", "sklearn.datasets.load_iris", "sklearn.model_selection.train_test_split" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
CristopherNim/student_performance
[ "f1ec90329e91c44a8155d83c0ac1569eb038954e" ]
[ "ml_model.py" ]
[ "import numpy as np\r\nimport pandas as pd\r\nfrom sklearn.linear_model import Ridge\r\nfrom sklearn.model_selection import cross_val_score, train_test_split\r\nfrom sklearn.model_selection import RepeatedKFold\r\nfrom sklearn.preprocessing import OneHotEncoder\r\nimport pickle\r\nfrom flask import Flask, request\r\n\r\nnp.random.seed(42)\r\n\r\ndf = pd.read_csv('StudentsPerformance.csv')\r\ndf.rename(columns={'race/ethnicity': 'race', 'parental level of education': 'parent_level_of_education',\r\n 'test preparation course': 'test_prep_course', 'math score': 'math_score',\r\n 'reading score': 'reading_score', 'writing score': 'writing_score'}, inplace=True)\r\n# creating a categorical boolean mask\r\n\r\ncategorical_feature_mask = df.dtypes == object\r\n\r\n# filtering out the categorical columns\r\n\r\ncategorical_cols = df.columns[categorical_feature_mask].tolist()\r\n\r\n# instantiate the OneHotEncoder Object\r\n\r\none_hot = OneHotEncoder(handle_unknown='ignore', sparse=False)\r\n\r\n# applying data\r\none_hot.fit(df[categorical_cols])\r\ncat_one_hot = one_hot.transform(df[categorical_cols])\r\n\r\n# creating Dataframe of the hot encoded columns\r\n\r\nhot_df = pd.DataFrame(cat_one_hot, columns=one_hot.get_feature_names(input_features=categorical_cols))\r\ndf_OneHotEncoder = pd.concat([df, hot_df], axis=1).drop(columns=categorical_cols, axis=1)\r\n\r\nX = df_OneHotEncoder.drop('math_score', axis=1)\r\ny = df_OneHotEncoder['math_score']\r\n\r\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=.2)\r\nmodel = Ridge(alpha=.99).fit(X_train, y_train)\r\n\r\nmodel_scores = cross_val_score(estimator=model, X=X_test, y=y_test, cv=5)\r\n\r\nprint('accuracy for ridge model: %.1f' % (model_scores.mean() * 100))\r\n\r\n\r\ndef row_pred(row):\r\n row = np.column_stack(row)\r\n cols = ['gender', 'race', 'parent_level_of_education', 'lunch', 'test_prep_course', 'reading_score',\r\n 'writing_score']\r\n\r\n newdf = pd.DataFrame(row, columns=cols)\r\n cat_ohe_new = one_hot.transform(newdf[categorical_cols])\r\n\r\n ohe_new_df = pd.DataFrame(cat_ohe_new, columns=one_hot.get_feature_names(input_features=categorical_cols))\r\n\r\n df_ohe_new = pd.concat([newdf, ohe_new_df], axis=1).drop(columns=categorical_cols, axis=1)\r\n\r\n pred_score = model.predict(df_ohe_new)\r\n a = pred_score.tolist()\r\n print(f'predicted math score: {a[0]:.0f}')\r\n # print(f'{a[0]:.0f}')\r\n return f'{a[0]:.1f}'\r\n\r\n\r\npickle.dump(model, open('model.pkl', 'wb'))\r\nrow = ['male', 'group_a', 'some high school', 'standard', 'none', 80, 80]\r\nresult = row_pred(row)\r\nprint(result)\r\n\r\n" ]
[ [ "pandas.concat", "pandas.read_csv", "sklearn.model_selection.cross_val_score", "numpy.random.seed", "sklearn.preprocessing.OneHotEncoder", "sklearn.model_selection.train_test_split", "pandas.DataFrame", "sklearn.linear_model.Ridge", "numpy.column_stack" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "2.0", "1.4", "1.1", "1.5", "1.2", "1.3" ], "scipy": [], "tensorflow": [] } ]
yehonatanHarmatz/HandwritingGAN
[ "186aad6278ed91a7e3f8dcbcab32a19dbbfc3f09" ]
[ "util/train_extractor.py" ]
[ "#TODO- for loop with 16bit that trains a vgg19bn to recognize writers\nfrom torch import optim\nfrom torch.cuda.amp import GradScaler, autocast\n\nfrom models.StyleEncoder_model import StyleEncoder\n\n\ndef freeze_conv(model):\n for param in model.features:\n param.requires_grad = False\n\ndef train_vgg_extractor():\n\n # Creates model and optimizer in default precision\n #model = StyleEncoder()\n #create a new encoder\n #replace the last layer with a writers number\n\n #freeze some of the layers\n\n model = StyleEncoder(False)\n #)\n optimizer = optim.Adam(filter(lambda p: p.requires_grad, model.parameters()), ...)\n\n # Creates a GradScaler once at the beginning of training.\n scaler = GradScaler()\n epochs=20\n #TODO- put harmatz dataset here\n data=None\n loss_fn=None\n #argmax()==label\n for epoch in epochs:\n for input, target in data:\n optimizer.zero_grad()\n\n # Runs the forward pass with autocasting.\n with autocast():\n # size of height 32 * K , width , channel=3\n output = model(input['image'])\n loss = loss_fn(output, target)\n\n # Scales loss. Calls backward() on scaled loss to create scaled gradients.\n # Backward passes under autocast are not recommended.\n # Backward ops run in the same dtype autocast chose for corresponding forward ops.\n scaler.scale(loss).backward()\n\n # scaler.step() first unscales the gradients of the optimizer's assigned params.\n # If these gradients do not contain infs or NaNs, optimizer.step() is then called,\n # otherwise, optimizer.step() is skipped.\n scaler.step(optimizer)\n\n # Updates the scale for next iteration.\n scaler.update()" ]
[ [ "torch.cuda.amp.GradScaler", "torch.cuda.amp.autocast" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
avostryakov/nlpaug
[ "f75770c230fe586cf21d11ad3342c2f160560d6a", "f75770c230fe586cf21d11ad3342c2f160560d6a" ]
[ "nlpaug/model/lang_models/xlnet.py", "test/augmenter/audio/test_mask.py" ]
[ "# Source: https://arxiv.org/abs/1906.08237\n\ntry:\n import torch\n from transformers import XLNetTokenizer, XLNetLMHeadModel\nexcept ImportError:\n # No installation required if not using this function\n pass\n\nfrom nlpaug.model.lang_models import LanguageModels\nfrom nlpaug.util.selection.filtering import *\n\n\nclass XlNet(LanguageModels):\n # Since XLNet is not good on short inputs, Aman Rusia proposed to add padding text to overcome this limitation.\n # https://github.com/rusiaaman/XLNet-gen#methodology and https://github.com/huggingface/pytorch-transformers/issues/846\n PADDING_TEXT = \"\"\"\n The quick brown fox jumps over the lazy dog. A horrible, messy split second presents\n itself to the heart-shaped version as Scott is moved. The upcoming movie benefits at \n the mental cost of ages 14 to 12. Nothing substantial is happened for almost 48 days. \n When that happens, we lose our heart. <eod>\n \"\"\"\n\n MASK_TOKEN = '<mask>'\n MASK_TOKEN_ID = 6\n SUBWORD_PREFIX = '▁'\n NEW_PARAGRAPH_TOKEN = '<eop>'\n\n def __init__(self, model_path='xlnet-base-cased', temperature=1.0, top_k=None, top_p=None, padding_text=None,\n device=None):\n super().__init__(device, temperature=temperature, top_k=top_k, top_p=top_p)\n self.model_path = model_path\n\n self.tokenizer = XLNetTokenizer.from_pretrained(model_path)\n self.model = XLNetLMHeadModel.from_pretrained(model_path)\n\n self.padding_text_idxes = self.tokenizer.encode(padding_text or self.PADDING_TEXT)\n\n self.model.to(self.device)\n self.model.eval()\n\n def id2token(self, _id):\n return self.tokenizer.decode(_id, clean_up_tokenization_spaces=True).strip()\n\n def clean(self, text):\n return text.replace(self.NEW_PARAGRAPH_TOKEN, '').strip()\n\n def predict(self, text, target_word=None, n=1):\n # Convert feature\n input_idxes = self.tokenizer.encode(text)\n concatenated_idxes = self.padding_text_idxes + input_idxes\n target_pos = len(self.padding_text_idxes) + input_idxes.index(self.MASK_TOKEN_ID)\n\n input_idxes = torch.tensor(concatenated_idxes).unsqueeze(0)\n perm_masks = torch.zeros((1, input_idxes.shape[1], input_idxes.shape[1]), dtype=torch.float)\n perm_masks[:, :, target_pos] = 1.0 # Mask the target word\n target_mappings = torch.zeros((1, 1, input_idxes.shape[1]), dtype=torch.float)\n target_mappings[0, 0, target_pos] = 1.0\n\n input_idxes = input_idxes.to(self.device)\n perm_masks = perm_masks.to(self.device)\n target_mappings = target_mappings.to(self.device)\n\n # Prediction\n with torch.no_grad():\n outputs = self.model(input_idxes, perm_mask=perm_masks, target_mapping=target_mappings)\n target_token_logits = outputs[0][0][0] # XLNet return masked token only\n\n # Selection\n seed = {'temperature': self.temperature, 'top_k': self.top_k, 'top_p': self.top_p}\n target_token_logits = self.control_randomness(target_token_logits, seed)\n target_token_logits, target_token_idxes = self.filtering(target_token_logits, seed)\n\n results = self.pick(target_token_logits, target_word=target_word, n=n)\n return results", "import unittest\nimport os\nimport librosa\nimport numpy as np\nfrom dotenv import load_dotenv\n\nimport nlpaug.augmenter.audio as naa\n\n\nclass TestMask(unittest.TestCase):\n @classmethod\n def setUpClass(cls):\n env_config_path = os.path.abspath(os.path.join(\n os.path.dirname(__file__), '..', '..', '..', '.env'))\n load_dotenv(env_config_path)\n # https://freewavesamples.com/yamaha-v50-rock-beat-120-bpm\n cls.sample_wav_file = os.environ.get(\"DATA_DIR\") + 'Yamaha-V50-Rock-Beat-120bpm.wav'\n\n def test_empty_input(self):\n audio = np.array([])\n aug = naa.MaskAug(sampling_rate=44100)\n augmented_audio = aug.augment(audio)\n\n self.assertTrue(np.array_equal(audio, augmented_audio))\n\n def test_with_noise(self):\n audio, sampling_rate = librosa.load(self.sample_wav_file)\n\n aug = naa.MaskAug(sampling_rate=sampling_rate, mask_with_noise=True)\n augmented_audio = aug.augment(audio)\n\n self.assertFalse(np.array_equal(audio, augmented_audio))\n self.assertEqual(len(audio), len(augmented_audio))\n\n def test_without_noise(self):\n audio, sampling_rate = librosa.load(self.sample_wav_file)\n\n aug = naa.MaskAug(sampling_rate=sampling_rate, mask_with_noise=False)\n augmented_audio = aug.augment(audio)\n\n self.assertFalse(np.array_equal(audio, augmented_audio))\n self.assertEqual(len(audio), len(augmented_audio))" ]
[ [ "torch.tensor", "torch.no_grad", "torch.zeros" ], [ "numpy.array", "numpy.array_equal" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
saitejamahadev/Experts-Hub-
[ "d29ff5d466c6403d156fdb6d9cc9a74191b77e3a" ]
[ "Random_Forest_Regression.py" ]
[ "# Random Forest Regression\n\n# Importing the libraries\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd\n\n# Importing the dataset\ndataset = pd.read_csv('Position_Salaries.csv')\nX = dataset.iloc[:, 1:2].values\ny = dataset.iloc[:, 2].values\n\n# Splitting the dataset into the Training set and Test set\n\"\"\"from sklearn.model_selection import train_test_split\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, random_state = 0)\"\"\"\n\n# Feature Scaling\n\"\"\"from sklearn.preprocessing import StandardScaler\nsc_X = StandardScaler()\nX_train = sc_X.fit_transform(X_train)\nX_test = sc_X.transform(X_test)\nsc_y = StandardScaler()\ny_train = sc_y.fit_transform(y_train)\"\"\"\n\n# Fitting Random Forest Regression to the dataset\nfrom sklearn.ensemble import RandomForestRegressor\nregressor = RandomForestRegressor(n_estimators = 10, random_state = 0)\nregressor.fit(X, y)\n\n# Predicting a new result\ny_pred = regressor.predict([[6.5]])\n\n# Visualising the Random Forest Regression results (higher resolution)\nX_grid = np.arange(min(X), max(X), 0.01)\nX_grid = X_grid.reshape((len(X_grid), 1))\nplt.scatter(X, y, color = 'red')\nplt.plot(X_grid, regressor.predict(X_grid), color = 'blue')\nplt.title('Truth or Bluff (Random Forest Regression)')\nplt.xlabel('Position level')\nplt.ylabel('Salary')\nplt.show()\n" ]
[ [ "sklearn.ensemble.RandomForestRegressor", "pandas.read_csv", "matplotlib.pyplot.title", "matplotlib.pyplot.scatter", "matplotlib.pyplot.xlabel", "matplotlib.pyplot.show", "matplotlib.pyplot.ylabel" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "2.0", "1.4", "1.1", "1.5", "1.2", "1.3" ], "scipy": [], "tensorflow": [] } ]