repo_name
stringlengths 6
130
| hexsha
sequence | file_path
sequence | code
sequence | apis
sequence |
---|---|---|---|---|
bcaitech1/p4-mod-model_diet | [
"36d8a747e12c375b07d132ed4d08f9fc77126a8b"
] | [
"src/modules/invertedresidual.py"
] | [
"\"\"\"Inverted Residual v3 block.\n\nReference:\n https://github.com/d-li14/mobilenetv3.pytorch/blob/master/mobilenetv3.py\n- Author: Junghoon Kim\n- Contact: [email protected]\n\"\"\"\nimport torch\nimport torch.nn as nn\nfrom torch.nn import functional as F\n\nfrom src.modules.activations import HardSigmoid, HardSwish\nfrom src.modules.base_generator import GeneratorAbstract\nfrom src.utils.torch_utils import make_divisible\n\n\ndef channel_shuffle(x: torch.Tensor, groups: int) -> torch.Tensor:\n batchsize, num_channels, height, width = x.size()\n channels_per_group = num_channels // groups\n\n # reshape\n x = x.view(batchsize, groups,\n channels_per_group, height, width)\n\n x = torch.transpose(x, 1, 2).contiguous()\n\n # flatten\n x = x.view(batchsize, -1, height, width)\n\n return x\n\nclass InvertedResidual(nn.Module):\n \"\"\"Inverted Residual block ShuffleNetV2.\n Reference:\n https://github.com/pytorch/vision/blob/master/torchvision/models/shufflenetv2.py\n \"\"\"\n\n def __init__(self, inp, oup, stride):\n super().__init__()\n\n if not (1 <= stride <= 3):\n raise ValueError('illegal stride value')\n self.stride = stride\n\n branch_features = oup // 2\n assert (self.stride != 0) or (inp == branch_features << 1)\n\n if self.stride > 1:\n self.branch1 = nn.Sequential(\n self.depthwise_conv(inp, inp, kernel_size=3, stride=self.stride, padding=1),\n nn.BatchNorm2d(inp),\n nn.Conv2d(inp, branch_features, kernel_size=1, stride=1, padding=0, bias=False),\n nn.BatchNorm2d(branch_features),\n nn.ReLU(inplace=True),\n )\n else:\n self.branch1 = nn.Sequential()\n\n self.branch2 = nn.Sequential(\n nn.Conv2d(inp if (self.stride > 1) else branch_features,\n branch_features, kernel_size=1, stride=1, padding=0, bias=False),\n nn.BatchNorm2d(branch_features),\n nn.ReLU(inplace=True),\n self.depthwise_conv(branch_features, branch_features, kernel_size=3, stride=self.stride, padding=1),\n nn.BatchNorm2d(branch_features),\n nn.Conv2d(branch_features, branch_features, kernel_size=1, stride=1, padding=0, bias=False),\n nn.BatchNorm2d(branch_features),\n nn.ReLU(inplace=True),\n )\n\n @staticmethod\n def depthwise_conv(\n i: int,\n o: int,\n kernel_size: int,\n stride: int = 1,\n padding: int = 0,\n bias: bool = False\n ) -> nn.Conv2d:\n return nn.Conv2d(i, o, kernel_size, stride, padding, bias=bias, groups=i)\n\n def forward(self, x: torch.Tensor) -> torch.Tensor:\n if self.stride == 1:\n x1, x2 = x.chunk(2, dim=1)\n out = torch.cat((x1, self.branch2(x2)), dim=1)\n else:\n out = torch.cat((self.branch1(x), self.branch2(x)), dim=1)\n\n out = channel_shuffle(out, 2)\n\n return out\n\n def forward(self, x: torch.Tensor) -> torch.Tensor:\n if self.stride == 1:\n x1, x2 = x.chunk(2, dim=1)\n out = torch.cat((x1, self.branch2(x2)), dim=1)\n else:\n out = torch.cat((self.branch1(x), self.branch2(x)), dim=1)\n\n out = channel_shuffle(out, 2)\n\n return out\n\n\nclass SqueezeExcitation(nn.Module):\n def __init__(self, input_channels: int, squeeze_factor: int = 4):\n super().__init__()\n squeeze_channels = make_divisible(input_channels // squeeze_factor, 8)\n self.fc1 = nn.Conv2d(input_channels, squeeze_channels, 1)\n self.relu = nn.ReLU(inplace=True)\n self.fc2 = nn.Conv2d(squeeze_channels, input_channels, 1)\n self.hardsigmoid = HardSigmoid()\n\n def _scale(self, input: torch.Tensor, inplace: bool) -> torch.Tensor:\n scale = F.adaptive_avg_pool2d(input, 1)\n scale = self.fc1(scale)\n scale = self.relu(scale)\n scale = self.fc2(scale)\n return self.hardsigmoid(scale)\n\n def forward(self, input: torch.Tensor) -> torch.Tensor:\n scale = self._scale(input, True)\n return scale * input\n\n\nclass InvertedResidualGenerator(GeneratorAbstract):\n \"\"\"Bottleneck block generator.\"\"\"\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n\n @property\n def out_channel(self) -> int:\n \"\"\"Get out channel size.\"\"\"\n return self._get_divisible_channel(self.args[2] * self.width_multiply)\n\n @property\n def base_module(self) -> nn.Module:\n \"\"\"Returns module class from src.common_modules based on the class name.\"\"\"\n return getattr(__import__(\"src.modules\", fromlist=[\"\"]), self.name)\n\n def __call__(self, repeat: int = 1):\n \"\"\"call method.\n\n InvertedResidual args consists,\n repeat(=n), [kernel, exp_ratio, out, SE, NL, s] //\n note original notation from paper is [exp_size, out, SE, NL, s]\n \"\"\"\n module = []\n k, t, _, s = self.args # c is equivalent as self.out_channel\n inp, oup = self.in_channel, self.out_channel\n for i in range(repeat):\n stride = s if i == 0 else 1\n exp_size = self._get_divisible_channel(inp * t)\n module.append(\n self.base_module(\n inp=inp,\n oup=oup,\n stride=stride,\n )\n )\n inp = oup\n return self._get_module(module)\n"
] | [
[
"torch.nn.Sequential",
"torch.transpose",
"torch.nn.Conv2d",
"torch.nn.functional.adaptive_avg_pool2d",
"torch.nn.BatchNorm2d",
"torch.nn.ReLU"
]
] |
harviu/pointnet_vae | [
"fad09f888212fc9c571584e27cd68bdcd589ae38"
] | [
"h_search.py"
] | [
"from utils.process_data import all_file_loader, PointData, collate_ball, collect_file\nfrom torch.utils.data import DataLoader\nimport torch\nimport os, math, time\n\ntry:\n data_path = os.environ['data']\nexcept KeyError:\n data_path = './data/'\n\n\n\ndef get_error (r,data):\n eps = 1e-15\n sample_size = 10000\n batch_size = sample_size\n ri = r/2\n ro = r\n # choice = np.random.choice(len(data),sample_size)\n pd = PointData(data ,256 ,r , False, sample_size)\n summed_error = 0\n loader = DataLoader(pd, batch_size=batch_size, shuffle=False, drop_last=False, collate_fn=collate_ball)\n for d in loader:\n data, mask = d\n sq_dist = torch.sum(data[...,:3]**2,axis=-1,keepdim=True)\n weight = 1 - (sq_dist - ri **2) / (ro**2 -ri ** 2)\n weight[weight < 0] = 1e-10 # avoid devided by zero\n weight[sq_dist< eps] = eps # remove center\n weight[torch.logical_not(mask)] = eps\n weight /= torch.sum(weight,axis=1,keepdim=True)\n est = (data[...,3:] * weight).sum(1)\n error = ((est - data[:,0,3:]) ** 2).mean(1).sum()\n summed_error += error.item()\n summed_error /= len(pd)\n return summed_error\n \ndef error_helper(args):\n d = args[0]\n r = args[1]\n return get_error(r,d)\n\ndef all_file_error(r,data):\n # pool = Pool(4)\n # summed = sum(pool.map(error_helper,zip(data,[r]*len(data))))\n summed = 0\n for d in data:\n summed += get_error(r,d)\n return summed / len(data)\n\ndef gss(data, a, b, tol=1e-5):\n \"\"\"Golden-section search\n to find the minimum of f on [a,b]\n f: a strictly unimodal function on [a,b]\n \"\"\"\n gr = (math.sqrt(5) + 1) / 2\n c = b - (b - a) / gr\n d = a + (b - a) / gr\n while abs(b - a) > tol:\n if all_file_error(c,data) < all_file_error(d,data):\n b = d\n else:\n a = c\n print(\"r =\",(b + a) / 2)\n # We recompute both c and d here to avoid loss of precision which may lead to incorrect results or infinite loop\n c = b - (b - a) / gr\n d = a + (b - a) / gr\n\n return (b + a) / 2\n\n\n\n\nif __name__ == \"__main__\":\n data_type = 'fpm_h'\n\n if data_type == 'jet3b':\n test_data = data_path + \"/jet3b/run3g_50Am_jet3b_sph.3400\"\n file_list = collect_file(os.path.join(data_path,\"jet3b\"), data_type, shuffle=False)\n elif data_type == 'fpm':\n test_data = data_path + \"/2016_scivis_fpm/0.44/run03/025.vtu\"\n file_list = collect_file(os.path.join(data_path,\"2016_scivis_fpm/0.44/run41\"), data_type, shuffle=False)\n elif data_type == 'cos':\n test_data = data_path + '/ds14_scivis_0128/raw/ds14_scivis_0128_e4_dt04_0.3500'\n file_list = collect_file(os.path.join(data_path,\"ds14_scivis_0128/raw\"), data_type, shuffle=False)\n elif data_type == 'fpm_h':\n test_data = data_path + '/2016_scivis_fpm/0.20/run03/025.vtu'\n data_type = 'fpm'\n file_list = collect_file(os.path.join(data_path,'2016_scivis_fpm/0.20/run03'), data_type, shuffle=False)\n\n data = all_file_loader(file_list,data_type)\n \n t1 = time.time()\n val = gss(data,0.01,0.05,tol=0.001)\n print(\"final r =\", val)\n print(\"time used: \", time.time()-t1)\n"
] | [
[
"torch.sum",
"torch.utils.data.DataLoader",
"torch.logical_not"
]
] |
zjucx/GAN | [
"641a92aff6695a1046a340038d8b013b2cc2f5bd"
] | [
"cyclegan.py"
] | [
"import tensorflow as tf\nfrom generator import *\nfrom discriminator import *\n\nimg_height = 256\nimg_width = 256\nimg_layer = 3\nbatch_size = 1\nimg_size = img_height * img_width\n\nclass CycleGAN():\n\n def init_model(self):\n self.input_A = tf.placeholder(tf.float32, [batch_size, img_width, img_height, img_layer], name=\"input_A\")\n self.input_B = tf.placeholder(tf.float32, [batch_size, img_width, img_height, img_layer], name=\"input_B\")\n\n self.pool_fake_b = tf.placeholder(tf.float32, [None, img_width, img_height, img_layer], name=\"pool_fake_b\")\n self.pool_fake_a = tf.placeholder(tf.float32, [None, img_width, img_height, img_layer], name=\"pool_fake_a\")\n\n with tf.variable_scope(\"model\") as scope:\n\n self.G_A = Generator(\"g_A\")\n self.G_B = Generator(\"g_B\")\n self.D_A = Discriminator(\"d_A\")\n self.D_B = Discriminator(\"d_B\")\n\n self.fake_a = self.G_A(self.input_A)\n self.fake_b = self.G_B(self.input_B)\n self.dis_a = self.D_A(self.input_A)\n self.dis_b = self.D_B(self.input_B)\n\n scope.reuse_variables()\n\n self.dis_fake_b = self.D_A(self.fake_b)\n self.dis_fake_a = self.D_B(self.fake_a)\n self.cyc_a = self.G_B(self.fake_a)\n self.cyc_b = self.G_A(self.fake_b)\n\n scope.reuse_variables()\n\n self.disc_pool_fake_b = self.D_A(self.pool_fake_b)\n self.disc_pool_gen_B = self.D_B(self.pool_fake_a)\n\n def init_loss(self):\n cyc_loss = tf.reduce_mean(tf.abs(self.input_A - self.cyc_a)) + tf.reduce_mean(tf.abs(self.input_B - self.cyc_b))\n\n self.loss_g_a = cyc_loss*10 + tf.reduce_mean(tf.squared_difference(self.dis_fake_b, 1))\n self.loss_g_b = cyc_loss*10 + tf.reduce_mean(tf.squared_difference(self.dis_fake_a, 1))\n\n self.loss_d_a = (tf.reduce_mean(tf.square(self.disc_pool_fake_b)) + tf.reduce_mean(tf.squared_difference(self.dis_a,1)))/2.0\n self.loss_d_b = (tf.reduce_mean(tf.square(self.disc_pool_gen_B)) + tf.reduce_mean(tf.squared_difference(self.dis_b,1)))/2.0\n\n optimizer = tf.train.AdamOptimizer(0.0002, beta1=0.5)\n\n model_vars = tf.trainable_variables()\n d_A_vars = [var for var in model_vars if 'd_A' in var.name]\n g_A_vars = [var for var in model_vars if 'g_A' in var.name]\n d_B_vars = [var for var in model_vars if 'd_B' in var.name]\n g_B_vars = [var for var in model_vars if 'g_B' in var.name]\n\n d_A_trainer = optimizer.minimize(self.loss_d_a, var_list=d_A_vars)\n d_B_trainer = optimizer.minimize(self.loss_d_b, var_list=d_B_vars)\n g_A_trainer = optimizer.minimize(self.loss_g_a, var_list=g_A_vars)\n g_B_trainer = optimizer.minimize(self.loss_g_b, var_list=g_B_vars)\n\n tf.summary.histogram('D_Y/true', self.dis_b)\n tf.summary.histogram('D_Y/fake', self.dis_fake_a)\n tf.summary.histogram('D_X/true', self.dis_a)\n tf.summary.histogram('D_X/fake', self.dis_fake_b)\n\n tf.summary.scalar(\"g_A_loss\", self.loss_g_a)\n tf.summary.scalar(\"g_B_loss\", self.loss_g_b)\n tf.summary.scalar(\"d_A_loss\", self.loss_d_a)\n tf.summary.scalar(\"d_B_loss\", self.loss_d_b)\n\n tf.summary.image('input_a', tf.image.convert_image_dtype((self.input_A+1.0)/2.0, tf.uint8))\n tf.summary.image('input_b', tf.image.convert_image_dtype((self.input_B+1.0)/2.0, tf.uint8))\n tf.summary.image('fake_a', tf.image.convert_image_dtype((self.fake_a+1.0)/2.0, tf.uint8))\n tf.summary.image('fake_b', tf.image.convert_image_dtype((self.fake_b+1.0)/2.0, tf.uint8))\n\n\n with tf.control_dependencies([g_A_trainer, d_B_trainer, g_B_trainer, d_A_trainer]):\n self.optimizers = tf.no_op(name='optimizers')\n #Summary variables for tensorboard\n"
] | [
[
"tensorflow.control_dependencies",
"tensorflow.placeholder",
"tensorflow.variable_scope",
"tensorflow.no_op",
"tensorflow.train.AdamOptimizer",
"tensorflow.image.convert_image_dtype",
"tensorflow.trainable_variables",
"tensorflow.squared_difference",
"tensorflow.square",
"tensorflow.summary.scalar",
"tensorflow.abs",
"tensorflow.summary.histogram"
]
] |
matejgrcic/Confident_classifier | [
"99ea815c53dde5d45ef958387ab49c6fe834d5b0"
] | [
"src/data_loader.py"
] | [
"# original code is from https://github.com/aaron-xichen/pytorch-playground\n# modified by Kimin Lee\nimport torch\nfrom torchvision import datasets, transforms\nfrom torch.utils.data import DataLoader\nimport os\nimport numpy.random as nr\nimport numpy as np\nfrom torch.utils.data.sampler import SubsetRandomSampler\n\ndef getSVHN(batch_size, img_size=32, data_root='/tmp/public_dataset/pytorch', train=True, val=True, **kwargs):\n data_root = os.path.expanduser(os.path.join(data_root, 'svhn-data'))\n num_workers = kwargs.setdefault('num_workers', 1)\n kwargs.pop('input_size', None)\n print(\"Building SVHN data loader with {} workers\".format(num_workers))\n\n # def target_transform(target):\n # new_target = target - 1\n # if new_target == -1:\n # new_target = 9\n # return new_target\n\n ds = []\n if train:\n train_loader = torch.utils.data.DataLoader(\n datasets.SVHN(\n root=data_root, split='train', download=True,\n transform=transforms.Compose([\n transforms.Scale(img_size),\n transforms.ToTensor(),\n ]),\n # target_transform=target_transform,\n ),\n batch_size=batch_size, shuffle=True, **kwargs)\n ds.append(train_loader)\n\n if val:\n test_loader = torch.utils.data.DataLoader(\n datasets.SVHN(\n root=data_root, split='test', download=True,\n transform=transforms.Compose([\n transforms.Scale(img_size),\n transforms.ToTensor(),\n ]),\n # target_transform=target_transform\n ),\n batch_size=batch_size, shuffle=False, **kwargs)\n ds.append(test_loader)\n ds = ds[0] if len(ds) == 1 else ds\n return ds\n\ndef getCIFAR10(batch_size, img_size=32, data_root='/tmp/public_dataset/pytorch', train=True, val=True, **kwargs):\n data_root = os.path.expanduser(os.path.join(data_root, 'cifar10-data'))\n num_workers = kwargs.setdefault('num_workers', 1)\n kwargs.pop('input_size', None)\n print(\"Building CIFAR-10 data loader with {} workers\".format(num_workers))\n ds = []\n if train:\n train_loader = torch.utils.data.DataLoader(\n datasets.CIFAR10(\n root=data_root, train=True, download=True,\n transform=transforms.Compose([\n transforms.Scale(img_size),\n transforms.ToTensor(),\n ])),\n batch_size=batch_size, shuffle=True, **kwargs)\n ds.append(train_loader)\n if val:\n test_loader = torch.utils.data.DataLoader(\n datasets.CIFAR10(\n root=data_root, train=False, download=True,\n transform=transforms.Compose([\n transforms.Scale(img_size),\n transforms.ToTensor(),\n ])),\n batch_size=batch_size, shuffle=False, **kwargs)\n ds.append(test_loader)\n ds = ds[0] if len(ds) == 1 else ds\n return ds\n\ndef getCIFAR100(batch_size, img_size=32, data_root='/tmp/public_dataset/pytorch', train=True, val=True, **kwargs):\n data_root = os.path.expanduser(os.path.join(data_root, 'cifar100-data'))\n num_workers = kwargs.setdefault('num_workers', 1)\n kwargs.pop('input_size', None)\n print(\"Building CIFAR-100 data loader with {} workers\".format(num_workers))\n ds = []\n if train:\n train_loader = torch.utils.data.DataLoader(\n datasets.CIFAR100(\n root=data_root, train=True, download=True,\n transform=transforms.Compose([\n transforms.Scale(img_size),\n transforms.ToTensor(),\n ])),\n batch_size=batch_size, shuffle=True, **kwargs)\n ds.append(train_loader)\n if val:\n test_loader = torch.utils.data.DataLoader(\n datasets.CIFAR100(\n root=data_root, train=False, download=True,\n transform=transforms.Compose([\n transforms.Scale(img_size),\n transforms.ToTensor(),\n ])),\n batch_size=batch_size, shuffle=False, **kwargs)\n ds.append(test_loader)\n ds = ds[0] if len(ds) == 1 else ds\n return ds\n\ndef getTargetDataSet(data_type, batch_size, imageSize, dataroot):\n if data_type == 'cifar10':\n train_loader, test_loader = getCIFAR10(batch_size=batch_size, img_size=imageSize, data_root=dataroot, num_workers=1)\n elif data_type == 'cifar100':\n train_loader, test_loader = getCIFAR100(batch_size=batch_size, img_size=imageSize, data_root=dataroot, num_workers=1)\n elif data_type == 'svhn':\n train_loader, test_loader = getSVHN(batch_size=batch_size, img_size=imageSize, data_root=dataroot, num_workers=1)\n\n return train_loader, test_loader\n\ndef getNonTargetDataSet(data_type, batch_size, imageSize, dataroot):\n if data_type == 'cifar10':\n _, test_loader = getCIFAR10(batch_size=batch_size, img_size=imageSize, data_root=dataroot, num_workers=1)\n elif data_type == 'svhn':\n _, test_loader = getSVHN(batch_size=batch_size, img_size=imageSize, data_root=dataroot, num_workers=1)\n elif data_type == 'imagenet':\n testsetout = datasets.ImageFolder(dataroot+\"/Imagenet_resize\", transform=transforms.Compose([transforms.Scale(imageSize),transforms.ToTensor()]))\n test_loader = torch.utils.data.DataLoader(testsetout, batch_size=batch_size, shuffle=False, num_workers=1)\n elif data_type == 'lsun':\n testsetout = datasets.ImageFolder(dataroot+\"/LSUN_resize\", transform=transforms.Compose([transforms.Scale(imageSize),transforms.ToTensor()]))\n test_loader = torch.utils.data.DataLoader(testsetout, batch_size=batch_size, shuffle=False, num_workers=1)\n elif data_type == 'traffic-sign':\n testsetout = datasets.ImageFolder(dataroot+\"/GTSRB/Training\", transform=transforms.Compose([transforms.Scale((imageSize, imageSize)),transforms.ToTensor()]))\n test_loader = torch.utils.data.DataLoader(testsetout, batch_size=batch_size, shuffle=False, num_workers=1)\n return test_loader\n"
] | [
[
"torch.utils.data.DataLoader"
]
] |
leontl/hyperframe | [
"ba6f5faa0759d3cfb498e9cc5946b77cb73ed7af"
] | [
"hyperframe.py"
] | [
"import numpy as np\nimport pandas as pd\nfrom collections import OrderedDict\nimport os\nimport json\nimport shutil\nimport warnings\nimport subprocess\n\n\ndef nest(l, depth=1, reps=1):\n \"\"\"create a nested list of depth 'depth' and with 'reps' repititions\"\"\"\n if depth == 0:\n return(None)\n elif depth == 1:\n return(l)\n else:\n return([nest(l, depth-1, reps)] * reps)\n\ndef unnest(l):\n \"\"\"unnest a nested list l\"\"\"\n return([x for y in l for x in mlist(y)])\n\n\n\ndef constant_array(constant, *args):\n \"\"\"create an array filled with the 'constant' of shape *args\"\"\"\n if len(args) == 0:\n return(constant)\n else:\n return(np.array([constant_array(constant, *args[1:])]*args[0]))\n\n\ndef zeros(*args):\n \"\"\"create a constant array of shape *args\"\"\"\n return(constant_array(0.0, *args))\n\n\ndef ones(*args):\n \"\"\"create a constant array of shape *args\"\"\"\n return(constant_array(1.0, *args))\n\n\ndef mlist(x):\n \"\"\"make sure x is a list\"\"\"\n if isinstance(x, list):\n return(x)\n else:\n return([x])\n\n\ndef idict(list_):\n \"\"\"create an ordered dict of i -> 'list_'[i]\"\"\"\n return(OrderedDict(zip(range(len(list_)), list_)))\n\n\ndef ridict(list_):\n \"\"\"create an ordered dict of 'list_'[i] -> i\"\"\"\n return(OrderedDict({v:k for k, v in idict(list_).items()}))\n\n\ndef ilist(dict_):\n return(list(dict_.values()))\n\n\ndef rilist(dict_):\n return(list(dict_.keys()))\n\n\ndef sort_dict(dict_):\n return([(k, v) for k, v in sorted(list(dict_.items()), key= lambda x: x[0])])\n\n\nclass HyperFrame:\n \"\"\"\n A numpy array with dimension labels and named indices of each dimension for\n storage and access to high-dimensional data.\n\n Attributes:\n dimension_labels (list[string]): dimension labels\n index_labels (OrderedDict[string, list[string]]): dimension label -> index labels\n dim_labels (OrderedDict[int, string]): index -> dimension label\n rdim_labels (OrderedDict[string, int]): dimension label -> index\n val_labels (OrderedDict[string, OrderedDict[int, string]]): dimension label -> index -> index label\n rval_labels (OrderedDict[string, OrderedDict[string, int]]): dimension label -> index label -> index\n data (np.array): data\n shape (set): shape of the data\n \"\"\"\n def __init__(self, dimension_labels, index_labels, data=None):\n \"\"\"\n The constructor of the HyperFrame class.\n\n Parameters:\n dimension_labels (list[string]): dimension labels\n index_labels (dict[string, list[int | string]]): dimension_label -> index labels\n data (np.array): data\n \"\"\"\n\n index_labels = OrderedDict(index_labels)\n\n self.dimension_labels = dimension_labels\n self.dim_labels = idict(dimension_labels)\n self.rdim_labels = ridict(dimension_labels)\n\n self.index_labels = index_labels\n self.val_labels = OrderedDict({k: idict(v) for k, v in index_labels.items()}) \n self.rval_labels = OrderedDict({k: ridict(v) for k, v in index_labels.items()})\n \n\n if data is None:\n data = zeros(*[len(self.val_labels[dim_label]) for _, dim_label in self.dim_labels.items()])\n\n self.data = data\n\n self.shape = data.shape\n\n HyperFrame._validate_hyperframe(self)\n\n def len(self, *args):\n return([self.shape[self.rdim_labels[a]] for a in args])\n\n def sum(self, *args):\n return(self.apply_f1(np.sum, *args))\n\n def mean(self, *args):\n return(self.apply_f1(np.mean, *args))\n\n def min(self, *args):\n return(self.apply_f1(np.min, *args))\n\n def max(self, *args):\n return(self.apply_f1(np.max, *args))\n\n def apply_f1(self, f, *args):\n if len(args) == 0:\n args = self.dimension_labels\n \n assert np.all([a in self.dimension_labels for a in args])\n dims = sorted([self.rdim_labels[a] for a in args])\n\n ndata = self.data\n for i, dim in enumerate(dims):\n ndata = f(ndata, dim-i)\n\n if isinstance(ndata, type(np.array([0]))):\n new_dimension_labels = [d for d in self.dimension_labels if d not in args]\n new_index_labels = OrderedDict([(k, v) for k, v in self.index_labels.items() if k not in args])\n\n return(HyperFrame(new_dimension_labels, new_index_labels, ndata))\n else:\n assert np.issubdtype(type(ndata), np.number)\n\n return(ndata)\n\n def copy(self):\n \"\"\"\n copy this HyperFrame\n\n Returns:\n HyperFrame: a new HyperFrame with the same data\n \"\"\"\n return(HyperFrame( self.dimension_labels, OrderedDict(self.index_labels) , self.data.copy()))\n\n\n def iget(self, *args, **kwargs):\n \"\"\"\n Get a subset of the dataframe by EITHER args or kwargs\n\n Parameters:\n *args (list[string]): values on each dimension by which the data should be subset, dimensions that should\n not be subset should have a value not in the dimension index\n **kwargs (dict[string, int | string | list[int] | list[string]]): dimension labels -> value or values \n to subset by\n return_type (string) (in kwargs): in [\"hyperframe\", \"pandas\", \"numpy\"]\n\n Returns:\n HyperFrame | pd.DataFrame | pd.Series | np.array: subset of original data\n \"\"\"\n\n return_type = kwargs.pop(\"return_type\", \"hyperframe\")\n\n kwargs = self._build_kwargs(args, kwargs)\n \n ndim_labels = [(i, v)\n for i, v in self.dim_labels.items()\n if v not in kwargs.keys() or len(kwargs[v]) > 1]\n\n ndim_labels = [x[1] for x in sorted(ndim_labels, key=lambda y: y[0])]\n \n nval_labels = {k: kwargs.get(k, v) for k, v in self.val_labels.items() if len(kwargs.get(k, v)) > 1}\n nval_labels = {k: (mlist(v) if not isinstance(v, dict) else list(v.values())) for k, v in nval_labels.items()}\n\n\n indices = self._construct_indices(kwargs, self.data.shape)\n ndata = self.data[np.ix_(*indices)]\n ndata = ndata.reshape(*[x for x in ndata.shape if x > 1]) \n\n subset = HyperFrame(ndim_labels, nval_labels, ndata)\n\n return(HyperFrame._cast_return_value(subset, return_type))\n\n\n @staticmethod\n def _cast_return_value(hyperframe, return_type):\n \"\"\"'cast' a hyperframe to a pandas or numpy object, or return unaltered\"\"\"\n if return_type == \"pandas\":\n return(HyperFrame._get_pandas_object(hyperframe))\n elif return_type == \"numpy\":\n return(hyperframe.data)\n elif return_type == \"hyperframe\":\n return(hyperframe)\n else:\n warnings.warn(\"return_type must be in ['hyperframe', 'pandas', 'numpy']\")\n\n\n @staticmethod\n def _get_pandas_object(hyperframe):\n \"\"\"\n Turn a HyperFrame of dimensionality <= into a pandas object\n\n Paramters:\n hyperframe (HyperFrame)\n\n Returns:\n pd.DataFrame | pd.Series\n \"\"\"\n indices = [[v2 for k2, v2 in sort_dict(hyperframe.val_labels[v])] \n for k, v in sort_dict(hyperframe.dim_labels)]\n\n assert len(indices) > 0, \"pandas objects must have at least one dimension\"\n assert len(indices) <= 2, \"pandas objects cannot have {} dimensions\".format(len(indices))\n\n if len(indices) == 1:\n return(pd.Series(hyperframe.data, index=indices[0]))\n else:\n return(pd.DataFrame(hyperframe.data, index=indices[0], columns = indices[1]))\n\n\n def iget0(self, *args, return_type=None):\n \"\"\"\n Return data for the dimensions in *args by subsetting the other dimensions to the first index label\n\n Parameters:\n *args (list[string]): the dimensions to be preserved in full\n return_type (string) (in kwargs): in [\"hyperframe\", \"pandas\", \"numpy\"]\n\n Returns:\n HyperFrame | pd.DataFrame | pd.Series | np.array: subset of original data\n \"\"\"\n assert len(args) > 0 and len(args) <= 2\n assert np.all([a in self.dimension_labels for a in args])\n\n kwargs = {v: self.val_labels[v][0] for i, v in self.dim_labels.items() if v not in args}\n print(kwargs)\n subset = self.iget(**kwargs)\n\n return(HyperFrame._cast_return_value(subset, return_type))\n\n\n def iset(self, new_data, *args, **kwargs):\n \"\"\"\n Replace a subset of the data with 'new_data'\n\n Parameters:\n new_data (np.array): new data\n *args (list[string]): values on each dimension by which the data should be subset, dimensions that should\n not be subset should have a value not in the dimension index\n **kwargs (dict[string, int | string | list[int] | list[string]]): dimension labels -> value or values\n to subset by\n\n Returns:\n HyperFrame: HyperFrame with changed data\n \"\"\"\n kwargs = self._build_kwargs(args, kwargs)\n\n assert np.issubdtype(type(new_data), np.number) or ( isinstance(new_data, type(np.array([0]))) and new_data.shape)\n \n indices = self._construct_indices(kwargs, self.data.shape)\n self.data[np.ix_(*indices)] = new_data.reshape([len(x) for x in indices])\n \n return(self)\n\n def _validate_other(self, other, expand):\n\n self_dimension_labels_subset = [label for label in self.dimension_labels if label in other.dimension_labels]\n\n assert (len(self_dimension_labels_subset) + int(expand)) == len(self.dimension_labels)\n\n for i, label in enumerate(self_dimension_labels_subset):\n assert label == other.dim_labels[i], \"the dimension labels of self and other must be identical\" \n\n dims_identical = [np.all(np.array(self.rval_labels[label].keys()) == \n np.array(other.rval_labels[label].keys()))\n for label in self_dimension_labels_subset]\n\n assert np.all(dims_identical)\n\n\n def expand(self, other, on_dimension, new_index_label):\n \"\"\"\n Expand this HyperFrame along one dimension with another HyperFrame\n\n Parameters:\n other (HyperFrame): another HyperFrame with identical 'dimension_labels' and identical 'index_labels'\n except for on one dimension: On that dimension, the 'index_labels' of other do\n not overlap with those of self\n on_dimension (string): dimension label on which other is \"tacked on\"\n new_index_label (string): index label for other within the new HyperFrame\n\n Returns:\n HyperFrame: A new HyperFrame with additional index labels and data on one dimension\n\n \"\"\"\n\n HyperFrame._validate_hyperframe(other)\n self._validate_other(other, True)\n\n dim_to_expand_on = [(i, label) for i, label in self.dim_labels.items() if label not in other.dimension_labels]\n\n assert len(dim_to_expand_on) == 1\n\n dim_different, dim_label_different = dim_to_expand_on[0]\n\n assert dim_label_different == on_dimension\n\n assert new_index_label not in self.index_labels[dim_label_different], \\\n \"the dimension with different val_labels cannot have overlapping val_labels\"\n\n new_index_labels = OrderedDict(self.index_labels)\n new_index_labels[dim_label_different] += [new_index_label]\n\n new_data = np.concatenate([self.data, np.expand_dims(other.data, dim_different)], axis=dim_different)\n\n return(HyperFrame(self.dimension_labels, new_index_labels, new_data))\n\n\n def merge(self, other, new_dimension, new_dimension_index_labels):\n \"\"\"\n Merge self and other to create a new HyperFrame with one additional dimension\n\n Paramters:\n other (HyperFrame | list[HyperFrame]): other HyperFrame(s) with the same dimension_labels and\n index_labels as self\n new_dimension (string): name of the new dimension\n new_dimension_index_labels (list[string]): labels on the new dimension\n\n Returns:\n HyperFrame\n \"\"\"\n\n other = mlist(other)\n\n assert new_dimension not in self.dimension_labels\n assert len(new_dimension_index_labels) == (len(mlist(other)) + 1), \\\n \"there must be as many new_dimension_index_labels as there are objects to merge\"\n\n assert len(new_dimension_index_labels) == len(set(new_dimension_index_labels)), \\\n \"new_dimension_index_labels must be unique\"\n\n for other_ in other:\n self._validate_other(other_, False)\n\n new_dimension_labels = self.dimension_labels + [new_dimension]\n\n new_index_labels = OrderedDict(self.index_labels)\n new_index_labels[new_dimension] = new_dimension_index_labels\n\n reshaped_data = [np.expand_dims(hf.data, -1) for hf in [self] + other]\n new_data = np.concatenate(reshaped_data, axis= len(self.data.shape))\n\n return(HyperFrame(new_dimension_labels, new_index_labels, new_data))\n\n\n def _construct_indices(self, kwargs, shape):\n\n numpy_indices = [list(range(x)) for x in shape]\n\n for dim_label, target_labels in kwargs.items():\n dim = self.rdim_labels[dim_label]\n target_indices = {dim:[self.rval_labels[dim_label][target] for target in target_labels]}\n\n for k, v in target_indices.items():\n v2 = v if len(v) > 1 else v[0]\n numpy_indices[k] = v\n\n return(numpy_indices)\n\n\n def _build_kwargs(self, args, kwargs):\n\n assert (len(args) == 0 and len(kwargs) > 0) or (len(args) == len(self.dim_labels) and len(kwargs)==0)\n\n for i, arg in enumerate(args):\n if arg not in self.index_labels[self.dim_labels[i]] and arg != \"\":\n raise ValueError(\"{} is not a valid index_label for {}\".format(arg, self.dim_labels[i]))\n\n assert len(kwargs) == 0 or np.all([k in self.dimension_labels and\n np.all([v_ in self.index_labels[k] for v_ in mlist(v)])\n for k, v in kwargs.items()])\n\n kwargs = [(k, mlist(v)) for k, v in kwargs.items()]\n\n args_to_kwargs = [(self.dim_labels[i], mlist(v) if v in self.index_labels[self.dim_labels[i]]\n else self.index_labels[self.dim_labels[i]])\n for i, v in enumerate(args)]\n\n kwargs = OrderedDict(kwargs + args_to_kwargs)\n self._validate_kwargs(kwargs)\n\n return(kwargs) \n \n\n def _validate_kwargs(self, kwargs):\n\n for key, value in kwargs.items():\n try:\n assert key in self.dim_labels.values()\n \n assert(len(value) > 0)\n for v in value:\n assert(v in self.val_labels[key].values())\n except:\n print(\"{}\\n{}\\n\\n{}\\n{}\\n\".format(key,\n self.dim_labels.values(),\n value,\n self.val_labels[key].values()))\n\n raise Exception(\"illegal argument provided\")\n \n \n @staticmethod\n def _validate_hyperframe(hyperframe):\n\n assert isinstance(hyperframe.dimension_labels, list)\n assert len(hyperframe.dimension_labels) > 0\n\n assert isinstance(hyperframe.index_labels, OrderedDict)\n assert len(hyperframe.index_labels) > 0\n assert np.all([isinstance(v, list) for k, v in hyperframe.index_labels.items()])\n\n assert len(hyperframe.dimension_labels) == len(hyperframe.index_labels)\n\n HyperFrame._validate_dict(hyperframe.dim_labels, len(hyperframe.data.shape))\n \n for dim, dim_label in hyperframe.dim_labels.items():\n assert dim_label in hyperframe.val_labels.keys()\n HyperFrame._validate_dict(hyperframe.val_labels[dim_label], hyperframe.data.shape[dim])\n\n assert isinstance(hyperframe.data, type(np.array([0])))\n\n \n @staticmethod\n def _validate_dict(dict_, dims):\n\n assert len(dict_) == dims\n assert HyperFrame._dense_keys(dict_)\n \n @staticmethod\n def _dense_keys(dict_):\n return np.all([x in dict_.keys() for x in range(len(dict_))])\n\n @staticmethod\n def _strip_path(path):\n\n filename = path.split(\"/\")[-1]\n if \".\" in filename and filename.split(\".\")[:-1] in [\"csv\", \"txt\", \"hyperframe\"]:\n path = \".\".join(path.split(\".\")[:-1]) \n warnings.warn(\"path changed to: {}\".format(path))\n\n return(path)\n\n\n def write_file(self, path):\n \"\"\"write file to path\"\"\"\n\n path = self._strip_path(path)\n\n dir_ = os.path.join(path + str(np.random.uniform())[2:], \"\")\n\n assert not os.path.exists(dir_)\n assert not os.path.exists(path + \".zip\")\n\n os.mkdir(dir_)\n\n try:\n with open(os.path.join(dir_, \"labels.json\"), \"w\") as f:\n f.write(json.dumps({\"dim_labels\": self.dim_labels,\n \"rdim_labels\": self.rdim_labels,\n \"val_labels\": self.val_labels,\n \"rval_labels\": self.rval_labels}))\n\n np.save(os.path.join(dir_, \"data\"), self.data)\n\n shutil.make_archive(path, 'zip', dir_)\n except Exception as e:\n raise e\n finally:\n shutil.rmtree(dir_)\n\n @staticmethod\n def read_file(path):\n \"\"\"read file from path\"\"\"\n\n path = HyperFrame._strip_path(path)\n\n dir_ = os.path.join(path + str(np.random.uniform())[2:], \"\")\n\n shutil.unpack_archive(path+\".zip\", dir_)\n\n try:\n data = np.load(os.path.join(dir_, \"data.npy\"))\n\n with open(os.path.join(dir_, \"labels.json\"), \"r\") as f:\n labels = json.loads(f.read())\n except Exception as e:\n raise e\n finally:\n shutil.rmtree(dir_)\n\n return(HyperFrame(ilist(labels[\"dim_labels\"]), {k: ilist(v) for k, v in labels[\"val_labels\"].items()}, data))\n\n\n @staticmethod\n def old_read_file(path):\n\n path = HyperFrame._strip_path(path)\n\n dir_ = path+\"/\"\n\n subprocess.run([\"mv\", path + \".hyperframe\", path + \".zip\" ])\n subprocess.run([\"unzip\", path + \".zip\", \"-d\", dir_])\n subprocess.run([\"mv\", path + \".zip\", path + \".hyperframe\" ])\n\n data = np.load(os.path.join(dir_, \"data.npy\"))\n\n with open(os.path.join(dir_, \"labels.json\"), \"r\") as f:\n labels = json.loads(f.read())\n\n subprocess.run([\"rm\", \"-r\", dir_ ])\n\n return(HyperFrame(ilist(labels[\"dim_labels\"]), {k: ilist(v) for k, v in labels[\"val_labels\"].items()}, data))"
] | [
[
"numpy.ix_",
"numpy.expand_dims",
"pandas.Series",
"pandas.DataFrame",
"numpy.all",
"numpy.random.uniform",
"numpy.array"
]
] |
ToshuuMilia/scikit-mine | [
"dcfa1e65dcf835f908c71f6dc3045d3251e855dd"
] | [
"setup.py"
] | [
"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\nfrom setuptools import find_packages, setup\nimport numpy\nimport codecs\n\nimport skmine\n\nDISTNAME = 'scikit-mine-alt'\nDESCRIPTION = 'Pattern mining in Python'\nMAINTAINER = 'N/A'\nMAINTAINER_EMAIL = 'N/A'\nURL = 'https://github.com/ToshuuMilia/scikit-mine'\nLICENSE = 'new BSD'\nDOWNLOAD_URL = 'https://github.com/ToshuuMilia/scikit-mine'\nVERSION = skmine.__version__\nCLASSIFIERS = ['Intended Audience :: Science/Research',\n 'Intended Audience :: Developers',\n 'License :: OSI Approved',\n 'Programming Language :: Python',\n 'Topic :: Software Development',\n 'Topic :: Scientific/Engineering',\n 'Operating System :: Microsoft :: Windows',\n 'Operating System :: POSIX',\n 'Operating System :: Unix',\n 'Operating System :: MacOS',\n 'Programming Language :: Python :: 3.6',\n 'Programming Language :: Python :: 3.7']\n\nEXTRAS_REQUIRE = {\n 'tests': [\n 'pytest',\n 'pytest-cov'],\n 'docs': [\n 'sphinx',\n 'sphinx-gallery',\n 'sphinx_rtd_theme',\n 'numpydoc',\n 'matplotlib'\n ]\n}\n\n\n# try replacing with `codecs.open('README.rst', encoding='utf-8-sig') as f:` if error\nwith codecs.open('README.rst', encoding='utf-8-sig') as readme_file:\n LONG_DESCRIPTION = readme_file.read()\n\nwith open('requirements.txt') as req_fd:\n INSTALL_REQUIRES = req_fd.read().splitlines()\n\n\nsetup(name=DISTNAME,\n maintainer=MAINTAINER,\n maintainer_email=MAINTAINER_EMAIL,\n description=DESCRIPTION,\n license=LICENSE,\n url=URL,\n version=VERSION,\n download_url=DOWNLOAD_URL,\n long_description=LONG_DESCRIPTION,\n long_description_content_type='text/x-rst',\n zip_safe=False, # the package can run out of an .egg file\n classifiers=CLASSIFIERS,\n packages=find_packages(exclude=[\"*.tests\", \"*.tests.*\", \"tests.*\", \"tests\"]),\n install_requires=INSTALL_REQUIRES,\n extras_require=EXTRAS_REQUIRE,\n include_dirs=[numpy.get_include()],\n)\n"
] | [
[
"numpy.get_include"
]
] |
kingaza/DLCA | [
"2b29d5cce3e4fee13ab4e45270e6b37c4e22b734"
] | [
"utils/preprocess_adam2020.py"
] | [
"\nimport os \nimport argparse\nimport zipfile as zf\n\nimport numpy as np \nfrom scipy.ndimage.measurements import center_of_mass, label, find_objects\nfrom scipy.ndimage import rotate, zoom, grey_closing\nfrom skimage import io, measure\n\nimport SimpleITK as sitk\nimport nibabel as nib\n\n\n# x y z -> z, y, z\ndef read_image(path):\n # Note: scale image intensity\n image = nib.load(path).get_fdata() / 100.0\n spacing = sitk.ReadImage(path).GetSpacing()\n return image.transpose(2, 1, 0), spacing[::-1]\n\n# x y z -> z, y, z\ndef read_label(path):\n label = nib.load(path).get_fdata().astype(np.int8).clip(0, 1)\n return label.transpose(2, 1, 0)\n\n\ndef rescale(image, label, input_space, output_space = (0.39, 0.39, 0.39)):\n assert image.shape == label.shape, \"image shape:{} != label shape{}\".format(image.shape, label.shape)\n zoom_factor = tuple([input_space[i] / output_space[i] for i in range(3)])\n # image cubic interpolation\n image_rescale = zoom(image, zoom_factor, order=3)\n # label nearest interpolation\n label_rescale = zoom(label, zoom_factor, order=0)\n label_rescale = grey_closing(label_rescale, size=(5,5,5))\n\n return image_rescale, label_rescale\n\n\n\ndef find_shift(shape, shape_s, center, top):\n to_min_z = max(shape[0] - top, 0)\n from_min_z = max(top - shape[0], 0)\n to_max_z = shape[0]\n from_max_z = top\n \n to_min_y = max(int(shape[1] / 2) - center[1], 0)\n from_min_y = max(center[1] - int(shape[1] / 2), 0)\n to_max_y = min(shape_s[1] - center[1], int(shape[1] / 2) - 1) + int(shape[1]/2)\n from_max_y = min(shape_s[1] - center[1], int(shape[1] / 2) - 1) + center[1]\n \n to_min_x = max(int(shape[2] / 2) - center[2], 0)\n from_min_x = max(center[2] - int(shape[2] / 2), 0)\n to_max_x = min(shape_s[2] - center[2], int(shape[2] / 2) - 1) + int(shape[2] / 2)\n from_max_x = min(shape_s[2] - center[2], int(shape[2] / 2) - 1) + center[2]\n\n coord_s = [from_min_z, from_max_z, from_min_y, from_max_y, from_min_x, from_max_x]\n coord_t = [to_min_z, to_max_z, to_min_y, to_max_y, to_min_x, to_max_x]\n\n coord_s = np.array(coord_s).astype(np.int16)\n coord_t = np.array(coord_t).astype(np.int16)\n\n return coord_s, coord_t\n\n\ndef crop(image, label, shape=(512, 512, 512)):\n np.clip(label, 0, 1, out = label)\n if shape is None:\n return image, label\n\n mask = image > 0\n center = tuple(map(int, center_of_mass(mask)))\n max_region = find_objects(mask)[0]\n top_slice = max_region[0].stop\n source_shape = image.shape\n\n coord_s, coord_t = find_shift(shape, source_shape, center, top_slice)\n\n # TODO\n image_crop = np.ones(shape, dtype = np.int16) * image.min()\n label_crop = np.zeros(shape, dtype = np.uint8)\n \n image_crop[coord_t[0]:coord_t[1], coord_t[2]:coord_t[3], coord_t[4]:coord_t[5]] = \\\n image[coord_s[0]:coord_s[1], coord_s[2]:coord_s[3], coord_s[4]:coord_s[5]]\n \n label_crop[coord_t[0]:coord_t[1], coord_t[2]:coord_t[3], coord_t[4]:coord_t[5]]= \\\n label[coord_s[0]:coord_s[1], coord_s[2]:coord_s[3], coord_s[4]:coord_s[5]]\n\n return image_crop, label_crop\n\n\n\ndef rotate_center(image, label, angle=15, ax=0):\n\n assert image.shape == label.shape\n\n if angle < 1:\n return image, label\n\n axes = tuple({0,1,2}.difference({ax}))\n # image cubic interpolation\n img = rotate(image, angle, axes=axes, reshape=False, order=3)\n # label nearest interpolation\n lbl = rotate(label, angle, axes=axes, reshape=False, order=0)\n lbl = grey_closing(lbl, size=(5,5,5))\n\n return img, lbl\n \n\n\ndef write_image(image, path):\n # SimpleITK save data in the format Z-H-W\n image_array = sitk.GetImageFromArray(image.transpose(2, 1, 0))\n sitk.WriteImage(image_array, path)\n\n\ndef draw_bbox(image, boxes, data_name, path):\n for i, box in enumerate(boxes):\n z, h, w, r = int(box[0]), int(box[1]), int(box[2]), int(box[3]/2)\n img_slice = image[z,:,:]\n img_slice = (img_slice - img_slice.min()) * 255 / (img_slice.max()-img_slice.min())\n img_slice = img_slice.astype(np.uint8)\n img_slice = np.repeat(img_slice[..., None], 3, axis=-1)\n\n shp = img_slice.shape\n if (h-r)>0 and (h+r)<shp[0] and (w-r)>0 and (w+r)<shp[1]:\n line = np.repeat([[255, 0, 0]],2*r,axis=0)\n img_slice[h-r:h+r,w-r,:] = line\n img_slice[h-r:h+r,w+r,:] = line\n img_slice[h-r,w-r:w+r,:] = line\n img_slice[h+r,w-r:w+r,:] = line\n save_path = os.path.join(path, '{}_bbox{}.png'.format(data_name, i+1))\n io.imsave(save_path, img_slice)\n\n\ndef gen_bbox(seg_label):\n label_region, label_num = label(seg_label)\n object_regions = find_objects(label_region)\n boxes = []\n for object_region in object_regions:\n box = []\n max_length = 0\n for i in range(3):\n min_coord = object_region[i].start \n max_coord = object_region[i].stop \n center = int(0.5 * (min_coord + max_coord))\n box.append(center)\n length = max_coord - min_coord\n if length > max_length:\n max_length = length\n if i == 2:\n box.append(max_length)\n boxes.append(box)\n\n return boxes \n\n\ndef save_result(image, label, image_name, save_root):\n boxes = gen_bbox(label)\n write_image(image, os.path.join(save_root, \"{}.nii.gz\".format(image_name)))\n write_image(label, os.path.join(save_root, \"{}_label.nii.gz\".format(image_name)))\n draw_bbox(image, boxes, image_name,save_root)\n np.save(os.path.join(save_root, \"{}_bbox.npy\".format(image_name)), boxes)\n np.savetxt(os.path.join(save_root, \"{}_bbox.txt\".format(image_name)), boxes, delimiter=',', fmt='%d')\n\n\ndef preprocess(rotate_type, zoom_type, in_dir, data_file, out_dir):\n\n if data_file.split('.')[-1] != 'zip':\n return\n \n data_path = os.path.join(in_dir, data_file)\n\n z = zf.ZipFile(data_path)\n for name in z.namelist():\n if 'pre/TOF.nii.gz' in name:\n z.extract(name, out_dir) \n if 'aneurysms.nii.gz' in name:\n z.extract(name, out_dir) \n if 'location.txt' in name:\n z.extract(name, out_dir) \n z.close() \n\n data_name = data_file.split('.')[0]\n tof_path = os.path.join(out_dir, data_name, 'pre/TOF.nii.gz')\n label_path = os.path.join(out_dir, data_name, 'aneurysms.nii.gz')\n\n image, spacing = read_image(tof_path)\n label = read_label(label_path)\n\n output_spacing = (0.39, 0.39, 0.39)\n if zoom_type == 1:\n output_spacing = tuple(np.asarray(output_spacing) * 1.11)\n elif zoom_type == 2:\n output_spacing = tuple(np.asarray(output_spacing) * 0.9)\n image_rescale, label_rescale = rescale(image, label, input_space=spacing, output_space=output_spacing)\n\n ax = (rotate_type+1) // 2\n angle = ((rotate_type+1) % 2 * 2 - 1) * 15\n image_rotate, label_rotate = rotate_center(image_rescale, label_rescale, angle=angle, ax=ax)\n\n image_crop, label_crop = crop(image_rotate, label_rotate, shape=None)\n \n np.set_printoptions(formatter={'float': '{: 0.3f}'.format})\n print(data_file, spacing)\n print(image.shape, '->', image_rescale.shape, '->', image_rotate.shape, '->', image_crop.shape)\n\n # save\n save_result(image_crop, label_crop, data_name, out_dir)\n\n \n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(description='ca detection')\n parser.add_argument('--input', default='', type=str, metavar='SAVE',\n help='directory to ADAM 2020 data (default: none)')\n parser.add_argument('--output', default='', type=str, metavar='SAVE',\n help='directory to save nii.gz data (default: none)')\n parser.add_argument('--rotate-type', default='0', type=int, metavar='S',\n help='0:None, 1:ax1/15, 2: ax1/-15, 3:ax2/15, 4:ax2/-15')\n parser.add_argument('--zoom-type', default='0', type=int, metavar='S',\n help='0:None, 1:ZoomOut/10%, 2:ZoomIn/10%') \n \n global args\n args = parser.parse_args()\n\n rotate_type = args.rotate_type\n zoom_type = args.zoom_type\n input_dir = args.input\n output_dir = args.output + '_{}{}'.format(rotate_type, zoom_type)\n\n if os.path.exists(output_dir) == False:\n os.makedirs(output_dir)\n\n data_list = os.listdir(input_dir)\n\n for data_file in data_list:\n preprocess(rotate_type, zoom_type, input_dir, data_file, output_dir)"
] | [
[
"numpy.clip",
"scipy.ndimage.grey_closing",
"numpy.asarray",
"scipy.ndimage.zoom",
"numpy.set_printoptions",
"scipy.ndimage.rotate",
"numpy.ones",
"scipy.ndimage.measurements.center_of_mass",
"scipy.ndimage.measurements.find_objects",
"numpy.repeat",
"numpy.array",
"numpy.zeros"
]
] |
cburik/machine-learning-engineering-for-production-public | [
"119e093cd52481ebeab0f26b993357812bf0c1b8"
] | [
"course4/week3-ungraded-labs/C4_W3_Lab_4_Github_Actions/app/main.py"
] | [
"import pickle\nimport numpy as np\nfrom typing import List\nfrom fastapi import FastAPI\nfrom pydantic import BaseModel, conlist\n\n\n\napp = FastAPI(title=\"Predicting Wine Class with batching\")\n\n# Open classifier in global scope\nwith open(\"models/wine-95-fixed.pkl\", \"rb\") as file:\n clf = pickle.load(file)\n\nclass Wine(BaseModel):\n batches: List[conlist(item_type=float, min_items=13, max_items=13)]\n\n\[email protected](\"/predict\")\ndef predict(wine: Wine):\n batches = wine.batches\n np_batches = np.array(batches)\n pred = clf.predict(np_batches).tolist()\n return {\"Prediction\": pred}\n"
] | [
[
"numpy.array"
]
] |
StoneYeY/Beat-Detection | [
"969619fe04b3e96428e560d604406a3d0cdfcc74"
] | [
"src/dataprocess.py"
] | [
"import os\r\n\r\nimport librosa\r\nimport numpy as np\r\nimport yaml\r\nfrom tqdm import tqdm\r\n\r\ndef create_spectrogram(\r\n file_path,\r\n n_fft,\r\n hop_length,\r\n n_mels):\r\n x, sr = librosa.load(file_path)\r\n hop_length_in_samples = int(np.floor(hop_length * sr))\r\n spec = librosa.feature.melspectrogram(\r\n x,\r\n sr=sr,\r\n n_fft=n_fft,\r\n hop_length=hop_length_in_samples,\r\n n_mels=n_mels)\r\n mag_spec = np.abs(spec)\r\n\r\n return mag_spec\r\n\r\ndef create_spectrograms(\r\n audio_dir,\r\n spectrogram_dir,\r\n n_fft,\r\n hop_length,\r\n n_mels):\r\n # print(os.listdir(audio_dir))\r\n for folder in os.listdir(audio_dir):\r\n print('=========> Processing {}.'.format(folder))\r\n out_folder = '/'.join([spectrogram_dir, folder])\r\n folder_path = '/'.join([audio_dir, folder])\r\n os.makedirs(out_folder, exist_ok=True)\r\n if os.path.isdir(folder_path):\r\n for file in tqdm(os.listdir(folder_path)):\r\n if file.endswith('.wav'):\r\n # print(file)\r\n file_path = '/'.join([audio_dir, folder, file])\r\n file_name = file[:-4] # cut-off '.wav'\r\n\r\n # create spec for each file\r\n spec = create_spectrogram(file_path, n_fft, hop_length, n_mels)\r\n np.save('/'.join([out_folder, file_name]), spec)\r\n\r\n\r\ndef trim_spectrogram(spectrogram, trim_size):\r\n output = np.zeros(trim_size)\r\n dim0_range = min(trim_size[0], spectrogram.shape[0])\r\n dim1_range = min(trim_size[1], spectrogram.shape[1])\r\n\r\n output[:dim0_range, :dim1_range] = spectrogram[:dim0_range, :dim1_range]\r\n return output\r\n\r\n\r\nif __name__ == '__main__':\r\n with open('config.yaml', 'r') as f:\r\n config = yaml.load(f, Loader=yaml.FullLoader)\r\n\r\n print('=========> process train data')\r\n create_spectrograms(\r\n audio_dir=config['dataset_folder_train'],\r\n spectrogram_dir=config['spec_folder_train'],\r\n n_fft=config['fft_size'],\r\n hop_length=config['hop_length'],\r\n n_mels=config['n_mels']\r\n )\r\n\r\n print('=========> process validation data')\r\n create_spectrograms(\r\n audio_dir=config['dataset_folder_val'],\r\n spectrogram_dir=config['spec_folder_val'],\r\n n_fft=config['fft_size'],\r\n hop_length=config['hop_length'],\r\n n_mels=config['n_mels']\r\n )\r\n"
] | [
[
"numpy.zeros",
"numpy.abs",
"numpy.floor"
]
] |
starsky2021/Watermark-Removal | [
"7d9747dea3cea4a563b574cdca91169ea7cae77f"
] | [
"src/networks/segmentation.py"
] | [
"import torch\nimport torchvision\n\nfrom torch.nn import functional as F\n\nfrom pytorch_lightning.core.lightning import LightningModule\n\n\nclass WMIDNet(LightningModule):\n\t\"\"\"\n\tWaterMark IDentification Network\n\n\tIdentifies watermarks on an input image. Returns a mask of pixels that show the location of the watermark.\n\n\tWraps a DeepLabV3 model to perform this task.\n\t\"\"\"\n\n\tdef __init__(self, lr=0.005):\n\t\tsuper().__init__()\n\t\tself.lr = lr\n\t\tself.wrap = torchvision.models.segmentation.deeplabv3_resnet50(pretrained=False, num_classes=2)\n\n\tdef forward(self, image_wm):\n\t\treturn self.wrap(image_wm)[\"out\"]\n\n\tdef training_step(self, batch, batch_idx):\n\t\tx, y = batch\n\t\ty_hat = self(x)\n\n\t\tloss = F.cross_entropy(y_hat, y)\n\n\t\treturn {\"loss\": loss}\n\n\tdef configure_optimizers(self):\n\t\treturn torch.optim.Adam(\n\t\t\tself.parameters(),\n\t\t\tlr=self.lr\n\t\t)\n\n\tdef validation_step(self, batch, batch_idx):\n\t\tx, y = batch\n\t\ty_hat = self(x)\n\t\treturn {\"val_loss\": F.cross_entropy(y_hat, y)}\n\n\tdef validation_epoch_end(self, outputs):\n\t\tval_loss_mean = torch.stack([x[\"val_loss\"] for x in outputs]).mean()\n\n\t\treturn {\"val_loss\": val_loss_mean}\n\n\n"
] | [
[
"torch.stack",
"torch.nn.functional.cross_entropy"
]
] |
Wiggler123/Poker_probability | [
"dc4418e2d5e5308cb8437bde77a3d6e64182c4d9"
] | [
"test2.py"
] | [
"#Importera nödvändiga bibliotek \r\nimport random\r\nimport matplotlib as mpl\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt;plt.rcdefaults()\r\nfrom alive_progress import alive_bar\r\nfrom timeit import default_timer as timer\r\nimport logging\r\nimport threading\r\nimport time\r\n\r\n#Skapar klass kort\r\nclass kort:\r\n def __init__(self,color,value):\r\n self.color = color\r\n self.value = value\r\n\r\n \r\n def View(self):\r\n return print(self.color + ' ' + self.value)\r\n \r\n def GetColor(self):\r\n return self.color\r\n \r\n def GetValue(self):\r\n return self.value\r\n\r\n#Klass kort tar emot två parametrar, färg och värde. Vi kan få tag på färg,värde samt visa kortet. \r\n\r\n\r\n#Skapar klass lek\r\nclass lek:\r\n def __init__(self):\r\n self.leken = []\r\n self.hoga = ['Knekt','Dam','Kung','Ess']\r\n self.farg = ['Hjärter','Spader','Ruter','Klöver']\r\n for i in range(len(self.farg)):\r\n for s in range(2,11):\r\n self.leken.append(kort(self.farg[i], str(s)))\r\n for v in self.hoga:\r\n self.leken.append(kort(self.farg[i],v))\r\n \r\n def View_lek(self):\r\n [i.View() for i in self.leken]\r\n\r\n def GetCardFromDeck(self, num:int):\r\n a = kort(self.leken[num].GetColor(), self.leken[num].GetValue())\r\n del self.leken[num]\r\n return a\r\n#I lek skapar vi själva leken som består av 52st kort från klass kort. Sedan kan vi använda oss \r\n# av kort egenskaperna för att visa hela leken. Vi kan även ta ett kort från leken.\r\n\r\n#Skapar klass hand\r\nclass hand:\r\n start = timer()\r\n def __init__(self):\r\n self.lek = lek()\r\n self.hand = []\r\n num = 5\r\n for i in range(num):\r\n rint = random.randint(0, len(self.lek.leken)-1)\r\n self.hand.append(self.lek.GetCardFromDeck(rint))\r\n\r\n#Här skapar vi en hand med 5 kort. Där vi slumpar ett tal från 0-52, eftersom listor går från 0-51 måste vi ta -1\r\n\r\n def ViewHand(self):\r\n [i.View() for i in self.hand]\r\n\r\n #Här visar vi alla kort på handen, vi använder View() från kort klassen.\r\n\r\n def GotPar(self):\r\n par = 0\r\n pars = [i.GetValue() for i in self.hand]\r\n if len(set(pars)) == 4:\r\n par = 1\r\n return par\r\n\r\n #Här börjar vi med att sätta par till 0(inget par) och en lista pars.\r\n #Sedan loopar vi igenom handen och lägger till värdet på kortet till pars.\r\n #Sen kollar vi helt enkelt om längden på set() av listan är 4. Set tar sammar värde och slår ihop\r\n # Tex print(set([2,2,1,4,5])) då kommer {1,2,4,5} att visas\r\n\r\n def GotSet(self):\r\n triss = 0\r\n sets = [i.GetValue() for i in self.hand]\r\n d = {}\r\n for i in sets:\r\n if i not in d.keys():\r\n d[i] = 1\r\n else:\r\n d[i] += 1\r\n if set(list(d.values())) == set([3,1]):\r\n triss = 1\r\n return triss\r\n \r\n #Här börjar vi med att sätta par till 0(inget par),en lista (pars) och en dictionary.\r\n #Sedan loopar vi igenom handen och lägger till värdet på kortet till pars.\r\n #Sedan loopar vi igenom listan par och kollar om värdet är med i dict.keys() Är det inte det lägger vi till det\r\n #Finns värdet redan i dict adderar vi 1 till värdet.i\r\n #Sen omvandlar vi värdena på dictionaryn till en lista och räknar antalet 2 som finns. Om det finns exakt 1 har vi par\r\n \r\n\r\n def GotKok(self):\r\n full_house = 0\r\n kok = {}\r\n kokar = [i.GetValue() for i in self.hand]\r\n for s in kokar:\r\n if s not in kok.keys():\r\n kok[s] = 1\r\n else:\r\n kok[s] += 1\r\n if sorted(kok.values()) == [2,3]:\r\n full_house = 1\r\n #self.view_hand()\r\n return full_house\r\n \r\n #Här gör vi ungefär samma som för triss, Men vi vet att räknaren måste vara 2,3 för kåk.\r\n #Så vi kan sortera värdena och kolla om de är lika med [2,3]\r\n\r\n def DictVal(self):\r\n #Lista val med värden från handen\r\n val = [i.GetValue() for i in self.hand]\r\n #Loopar varje element i hand\r\n #Här byter vi ut sträng mot digit.\r\n word = [w.replace('Knekt', '11').replace('Dam', '12').replace('Kung', '13').replace('Ess', '14') for w in val]\r\n #Onödigt gjort menmen\r\n val = word\r\n return val\r\n\r\n #Inför Stege skapar jag en lista med de riktiga värderna. Byter alltså ut ordet mot värdet.\r\n \r\n def GotStraight(self): #Kollar stege\r\n straights = 0 #sätter stege till 0\r\n straight = {} #gör en dict som sedan ska innehålla kortet och antalet\r\n val = self.DictVal() #hämtar en lista från funktionen dict_val() (felbenämnd!)\r\n for i in range (0, len(val)): #Kör igenom varje sträng i listan och omvandlar till int\r\n val[i] = int(val[i])\r\n val = sorted(val) #Detta för att kunna sortera listan från lägst till högst\r\n for i in val: \r\n if i not in straight.keys(): #Kollar om elementet finns i nycklarna av dict ({keys:values})\r\n straight[i] = 1#Om det inte finns i nyckelen lägger vi till den som nyckel med värde 1\r\n else:\r\n #Om den finns vill vi lägga till 1. då har vi tex ({'Ess': 2})\r\n straight[i] += 1\r\n #Värde av lista för att se om högsta värdet - minsta i listan blir 4.\r\n val_lista = val[4] - val[0]\r\n #Här räknar vi hur många 1or som finns i straight. Om det finns 5 så finns ju inget par\r\n #Vi behöver även veta att högsta - minsta i listan blir 4. Eftersom det blir så i stegar. tex 2 3 4 5 6, 6-2 = 4\r\n if list(straight.values()).count(1) == 5 and val_lista == 4:\r\n straights = 1\r\n else:\r\n #Här tittar vi på hela listan val och om den är lika med 14,2,3,4,5 så har vi en stege.\r\n #Vi kollar alltså med Ess som lägst istället för högst.\r\n if set(val) == set([14,2,3,4,5]):\r\n straights = 1\r\n else:\r\n pass\r\n return straights\r\n \r\n def GotFarg(self):\r\n farger = [i.GetColor() for i in self.hand]\r\n flush = 0\r\n farg = {}\r\n for s in farger:\r\n if s not in farg.keys():\r\n farg[s] = 1\r\n else:\r\n farg[s] += 1\r\n if len(set(farg.values())) == 1:\r\n if self.GotStraight() != 1:\r\n flush = 1\r\n #self.view_hand()\r\n return flush\r\n #Samma princip som triss fast med färg istället. Vi behöver även se till så att vi inte har stege samtidigt\r\n #För då är det ju en färgstege och inte en färg\r\n\r\n#Här kör vi Själva programmet\r\ndef main():\r\n n = int(input(\"Hur många simuleringar vill du göra: \"))\r\n sumpar = 0\r\n sumtriss = 0\r\n sumkok = 0\r\n sumfarg = 0\r\n ant_sim = []\r\n san_par = []\r\n san_triss = []\r\n san_kok = []\r\n san_farg = []\r\n with alive_bar(n, bar='bubbles', spinner='waves2') as bar:\r\n for i in range(n):\r\n s = hand()\r\n ant_sim.append(i)\r\n sumpar += s.GotPar()\r\n sumtriss += s.GotSet()\r\n sumkok += s.GotKok()\r\n sumfarg += s.GotFarg()\r\n san_par.append(100*sumpar/(i+1))\r\n san_triss.append(100*sumtriss/(i+1))\r\n san_kok.append(100*sumkok/(i+1))\r\n san_farg.append(100*sumfarg/(i+1))\r\n bar()\r\n #Här skapar vi listor och intar som ska summera och lägga till i listan\r\n #Har även importerat en progressbar som visar hur lång tid det ska ta.\r\n\r\n p = input(\"Vilken typ av graf vill du plotta(cirkel(1)/stapel(2): \").lower()\r\n if p == '1' or p == 'cirkel':\r\n annat = 100 - san_par[-1] - san_triss[-1] - san_farg[-1] - san_kok[-1]\r\n labels = ['Annat','Par','Triss','Färg','Kåk']\r\n sizes = [annat,san_par[-1],san_triss[-1],san_farg[-1],san_kok[-1]]\r\n colors = ['#ff9999','#66b3ff','#99ff99','#ffcc99','#66ffff']\r\n fig1, ax1 = plt.subplots(figsize=(5,5))\r\n porcent = sizes\r\n patches, texts = plt.pie(sizes, colors=colors, startangle=90, radius=1.2)\r\n labeld = ['{0} - {1:1.2f} %'.format(i,j) for i,j in zip(labels, porcent)]\r\n sort_legend = True\r\n if sort_legend:\r\n patches,labeld, dummy = zip(*sorted(zip(patches,labeld,sizes),key=lambda x:x[2],reverse=True))\r\n\r\n plt.legend(patches,labeld,loc='best', bbox_to_anchor=(-0.1,1.),fontsize=8)\r\n centre_circle = plt.Circle((0,0),0.70,fc='white')\r\n fig = plt.gcf()\r\n fig.gca().add_artist(centre_circle)\r\n ax1.axis('equal') \r\n plt.tight_layout()\r\n plt.show()\r\n\r\n #Vet knappt vad detta gör! Men ville ha en snygg graf så grävde lite och hittade en fin!\r\n #Förstår delvis vad sakerna gör men långt ifrån allt!\r\n\r\n elif p =='2' or p == 'stapel':\r\n objects = 'Annat','Par','Triss','Färg','Kåk'\r\n annat = 100 - san_par[-1] - san_triss[-1] - san_farg[-1] - san_kok[-1]\r\n performance = annat,san_par[-1],san_triss[-1],san_farg[-1],san_kok[-1]\r\n colors = ['#ff9999','#66b3ff','#99ff99','#ffcc99','#66ffff']\r\n font_title = mpl.font_manager.FontProperties(fname='C:/Users/danne/Downloads/Opensans/Opensans-Semibold.ttf')\r\n font_axis = mpl.font_manager.FontProperties(fname='C:/Users/danne/Downloads/Opensans/Opensans-Regular.ttf')\r\n y_pos = np.arange(len(objects))\r\n fig,ax = plt.subplots()\r\n bars = plt.bar(y_pos, performance, align='center', alpha=0.7,color=colors)\r\n\r\n #Tar bort onödiga linjer\r\n ax.spines['right'].set_visible(False)\r\n #ax.spines['left'].set_visible(False)\r\n #ax.spines['bottom'].set_visible(False)\r\n ax.spines['top'].set_visible(False)\r\n ax.tick_params(bottom=False, left=False)\r\n ax.set_axisbelow(True)\r\n ax.yaxis.grid(True, color='#EEEEEE')\r\n ax.xaxis.grid(False)\r\n ax.set_ylabel('Sannolikhet i procent', labelpad=15, color='#333333',fontproperties=font_axis)\r\n ax.set_title('Poker - Sannolikhet och kombinationer ',fontproperties=font_title,pad=15,color='#333333')\r\n plt.xticks(y_pos, objects)\r\n for bar in bars.patches:\r\n txt = np.round(bar.get_height(), decimals=2)\r\n anot = txt.astype('str')\r\n plt.annotate(anot+'%', \r\n (bar.get_x() + bar.get_width() / 2, \r\n bar.get_height()), ha='center', va='center', xytext=(0, 10),\r\n textcoords='offset points',fontsize = 10)\r\n plt.show()\r\n\r\n #Vet knappt vad detta gör! Men ville ha en snygg graf så grävde lite och hittade en fin\r\n #Förstår delvis vad sakerna gör men långt ifrån allt!\r\n\r\n\r\nkora_igen = True\r\nwhile kora_igen:\r\n main()\r\n while True:\r\n ask = input(\"Köra igen? (j/n)\")\r\n ask = ask.lower()\r\n if ask == 'j':\r\n break\r\n else:\r\n kora_igen = False\r\n print(\"Okej, hejdå!\")\r\n break\r\n\r\n#Här tittar vi om vi kör programmet direkt från sidan, ibland när man importerar klasser osv så vill man \r\n#inte att de ska köras. Därför har man denna if sats\r\n\r\n\r\n"
] | [
[
"matplotlib.pyplot.legend",
"matplotlib.pyplot.tight_layout",
"matplotlib.font_manager.FontProperties",
"matplotlib.pyplot.subplots",
"matplotlib.pyplot.gcf",
"matplotlib.pyplot.Circle",
"matplotlib.pyplot.xticks",
"matplotlib.pyplot.bar",
"matplotlib.pyplot.rcdefaults",
"matplotlib.pyplot.pie",
"matplotlib.pyplot.show"
]
] |
mcgillmrl/robot_learning | [
"4b9e387524cc6a6058055a7e26bc761c81eb5597"
] | [
"src/robot_learning/ros_plant.py"
] | [
"#!/usr/bin/env python\nimport gym\nimport numpy as np\nimport rospy\n\nfrom gym import spaces\nfrom collections import deque\n\nfrom std_srvs.srv import Empty as EmptySrv\nfrom robot_learning.msg import ExperienceData\nfrom robot_learning.srv import T2VInfo\n\n\nclass ROSPlant(gym.Env):\n '''\n Class for collecting msg and executing policies on a ROS-enabled robot\n '''\n\n reset_srv_name = '/rl/reset_robot'\n stop_srv_name = '/rl/stop_robot'\n\n command_dims_srv_name = '/rl/command_dims'\n state_dims_srv_name = '/rl/state_dims'\n\n def __init__(self, state0_dist=None, reward_func=None, dt=0.5,\n noise_dist=None, angle_dims=[], name='ROSPlant',\n init_ros_node=False, max_experience_queue_size=2000,\n command_topic='/rl/command_data',\n experience_topic='/rl/experience_data',\n gazebo_synchronous=False,\n reset_callback=None,\n *args, **kwargs):\n # init queue. This is to ensure that we collect experience at every dt\n # seconds\n self.t = rospy.get_time()\n self.experience_queue = deque(maxlen=max_experience_queue_size)\n\n # if gazebo sim synchronous\n self.gazebo_synchronous = gazebo_synchronous\n if gazebo_synchronous:\n rospy.loginfo(\n '%s: waiting for /gazebo/pause_physics...' % name)\n rospy.wait_for_service('/gazebo/pause_physics')\n self.pause = rospy.ServiceProxy(\n '/gazebo/pause_physics', EmptySrv)\n self.unpause = rospy.ServiceProxy(\n '/gazebo/unpause_physics', EmptySrv)\n self.reset_callback = reset_callback\n\n # initalize internal plant parameteers\n self.init_params(state0_dist, reward_func, dt, noise_dist, angle_dims,\n name, *args, **kwargs)\n\n # initialize ros node, publishers and subscribers\n self.ros_init(init_ros_node)\n\n # Observation and action spaces will be populated by reading from the\n # appropriate topics\n self.init_obs_act_spaces()\n\n # initialize publishers and subscribers\n self.command_pub = rospy.Publisher(\n command_topic, ExperienceData, queue_size=-1)\n self.experience_sub = rospy.Subscriber(\n experience_topic, ExperienceData, self.experience_callback,\n queue_size=1000)\n\n # get initial state\n rospy.loginfo(\n '[%s] waiting for first experience data msg...' % (self.name))\n self.t, self.state = self.wait_for_state(self.dt)\n rospy.loginfo('[%s] Ready.' % (self.name))\n\n def init_params(self, state0_dist=None, reward_func=None, dt=0.5,\n noise_dist=None, angle_dims=[], name='ROSPlant',\n *args, **kwargs):\n self.name = name\n self.dt = dt\n self.noise_dist = noise_dist\n self.angle_dims = angle_dims\n\n # initial state. only needed for gazebo environments, or in cases\n # where we know how to reset to an initial state, (e.g. a robotic arm)\n self.state0_dist = state0_dist\n\n # user specified reward/loss function. takes as input state vector,\n # produces as output scalar reward/cost. If not specified, the step\n # function will return None for the reward/loss function\n self.reward_func = reward_func\n\n def ros_init(self, init_ros_node=False):\n # init plant ros node\n if init_ros_node:\n rospy.init_node(self.name, anonymous=True, disable_signals=True)\n # start service proxies\n rospy.loginfo(\n '[%s] waiting for %s...' % (self.name, ROSPlant.reset_srv_name))\n rospy.wait_for_service(ROSPlant.reset_srv_name)\n self.reset_srv = rospy.ServiceProxy(ROSPlant.reset_srv_name, EmptySrv)\n rospy.loginfo(\n '[%s] waiting for %s...' % (self.name, ROSPlant.stop_srv_name))\n rospy.wait_for_service(ROSPlant.stop_srv_name)\n self.stop_srv = rospy.ServiceProxy(ROSPlant.stop_srv_name, EmptySrv)\n\n # init time\n self.t0 = rospy.get_time()\n self.t = self.t0\n\n def init_obs_act_spaces(self):\n rospy.loginfo(\n '[%s] waiting for %s...' % (self.name,\n ROSPlant.command_dims_srv_name))\n rospy.wait_for_service(ROSPlant.command_dims_srv_name)\n cdims = rospy.ServiceProxy(ROSPlant.command_dims_srv_name, T2VInfo)\n rospy.loginfo(\n '[%s] waiting for %s...' % (self.name,\n ROSPlant.state_dims_srv_name))\n rospy.wait_for_service(ROSPlant.state_dims_srv_name)\n sdims = rospy.ServiceProxy(ROSPlant.state_dims_srv_name, T2VInfo)\n\n # TODO get min max ranges from config file or from service\n o_lims = np.array([1e3 for i in range(sdims().value)])\n self.observation_space = spaces.Box(-o_lims, o_lims, dtype=np.double)\n a_lims = np.array([1e3 for i in range(cdims().value)])\n self.action_space = spaces.Box(-a_lims, a_lims, dtype=np.double)\n\n def experience_callback(self, msg):\n # put incoming messages into experience queue\n q = self.experience_queue\n\n t = (msg.header.stamp.secs - self.t0) + msg.header.stamp.nsecs*1e-9 \n state = msg.state_data\n q.append((t, state))\n # print_with_stamp(\"%s, %s\" % (str(self.t), str(t)), same_line=False)\n\n def wait_for_state(self, dt=None, slop=1.0e-3):\n if dt is None:\n dt = self.dt\n\n if self.gazebo_synchronous:\n self.unpause()\n\n t1 = self.t + dt\n t = self.t\n\n q = self.experience_queue\n state = None\n while t < t1:\n if len(q) == 0:\n # sleep for a short time\n rospy.sleep(0.01*dt)\n else:\n t, state = q.popleft()\n t += self.t0\n if t1 - t < slop:\n # we process messages that are a little bit early as if\n # they were on the clock at the desired rate, to avoid\n # accumulating delays\n t = t1\n if self.gazebo_synchronous:\n self.pause()\n break\n return t, state\n\n def apply_control(self, u):\n '''\n publish control message. We send the\n '''\n if type(u) is np.ndarray:\n if u.ndim < 1:\n u = u[None]\n u = u.tolist() \n self.cmd = u\n msg = ExperienceData()\n msg.header.stamp = rospy.Time.now()\n # we fill the state msg for logging purposes, the topics to vector\n # node ignores this information.\n msg.state_data = self.state\n msg.command_data = u\n self.command_pub.publish(msg)\n\n def step(self, action):\n # apply action and return state dt seconds after sending command\n # For control tasks, the robot driver should be responsible to decide\n # whether to use zero-order hold (constant command during dt) or\n # any other scheme.\n info = {}\n\n # first apply control\n self.apply_control(action)\n\n # step for dt seconds\n t, state = self.wait_for_state(self.dt)\n\n # save latest measurement info\n self.state = np.array(state)\n self.t = t\n info['t'] = self.t\n info['action'] = action\n\n # evaluate reward, if given\n reward = None\n if self.reward_func is not None:\n reward = self.reward_func(self.state, action)\n\n # return output following the openai gym convention\n return self.state, reward, False, info\n\n def reset(self):\n '''\n calls the registered reset service with the desired state.\n '''\n rospy.loginfo(\"[%s] Resetting robot...\" % (self.name))\n self.reset_srv()\n rospy.loginfo(\"[%s] Done! Waiting for state update...\" % (self.name))\n # init time\n self.t = rospy.get_time()\n self.t0 = self.t\n self.t, self.state = self.wait_for_state(dt=0.1*self.dt)\n self.t0 = self.t\n rospy.loginfo(\"[%s] Robot ready\" % (self.name))\n\n if callable(self.reset_callback):\n self.reset_callback\n\n return self.state\n\n def close(self):\n '''\n class any registered service with empty messages\n '''\n pass\n\n def stop(self):\n '''\n calls the registered reset service with the desired state.\n '''\n self.stop_srv()\n"
] | [
[
"numpy.array"
]
] |
vtsuperdarn/clustering_superdarn_data | [
"02bc31dd85f66319bb46b632e0e7ac51ed98c432"
] | [
"utilities/classification_utils.py"
] | [
"import numpy as np\n\ndef blanchard_gs_flg(vel, wid, type='code'):\n med_vel = np.median(np.abs(vel))\n med_wid = np.median(np.abs(wid))\n if type == 'paper':\n return med_vel < 33.1 + 0.139 * med_wid - 0.00133 * (med_wid ** 2) # Found in 2009 paper\n if type == 'code':\n return med_vel < 30 - med_wid * 1.0 / 3.0 # Found in RST code\n\ndef ribiero_gs_flg(vel, time):\n L = np.abs(time[-1] - time[0]) * 24\n high = np.sum(np.abs(vel) > 15.0)\n low = np.sum(np.abs(vel) <= 15.0)\n if low == 0:\n R = 1.0 # TODO hmm... this works right?\n else:\n R = high / low # High vel / low vel ratio\n # See Figure 4 in Ribiero 2011\n if L > 14.0:\n # Addition by us\n if R > 0.15:\n return False # IS\n else:\n return True # GS\n # Classic Ribiero 2011\n #return True # GS\n elif L > 3:\n if R > 0.2:\n return False\n else:\n return True\n elif L > 2:\n if R > 0.33:\n return False\n else:\n return True\n elif L > 1:\n if R > 0.475:\n return False\n else:\n return True\n # Addition by Burrell 2018 \"Solar influences...\"\n else:\n if R > 0.5:\n return False\n else:\n return True\n # Classic Ribiero 2011\n # else:\n # return False\n"
] | [
[
"numpy.abs"
]
] |
laurenmm/simmate-1 | [
"c06b94c46919b01cda50f78221ad14f75c100a14"
] | [
"src/simmate/toolkit/transformations/heredity_mutation_ase.py"
] | [
"# -*- coding: utf-8 -*-\n\nimport numpy\n\nfrom simmate.toolkit.transformations.base import Transformation\n\n\n#!!! I need to figure out how to implement more than two structures\n\n\nclass HeredityASE(Transformation):\n\n # known as CutAndSplicePairing in ase.ga\n # https://gitlab.com/ase/ase/-/blob/master/ase/ga/cutandsplicepairing.py\n\n # might be useful for a pymatgen rewrite:\n # pymatgen.transformations.advanced_transformations.SlabTransformation\n\n io_scale = \"many_to_one\"\n ninput = 2\n use_multiprocessing = False\n\n def __init__(\n self,\n composition,\n ratio_of_covalent_radii=0.1,\n ):\n\n # we can assume the user has ASE installed because it is a dependency of PyMatgen\n #!!! it looks like the ase.ga module is actively changing so version may introduce errors\n from ase.ga.utilities import closest_distances_generator\n\n # the slab variable is there to specify dimensionality. The code really just uses the pbc setting\n #!!! I need to doublecheck this\n from ase import Atoms\n\n self.slab = Atoms(\n pbc=True\n ) #!!! I assume 3D structure for now. I could do things like pbc=[1,1,0] for 2D in the future though\n\n # the closest_distances_generator is exactly the same as an element-dependent distance matrix\n # expect ASE puts this in dictionary form\n # the function requires a list of element integers\n element_ints = [element.number for element in composition]\n # the default of the ratio of covalent radii (0.1) is based on the ASE tutorial of this function\n self.element_distance_matrix = closest_distances_generator(\n element_ints, ratio_of_covalent_radii\n )\n\n # boundry limits on the lattice\n # I only do angle limits for now but I should introduce vector length limits\n from ase.ga.utilities import CellBounds\n\n self.cellbounds = CellBounds(\n bounds={\n \"phi\": [35, 145],\n \"chi\": [35, 145],\n \"psi\": [35, 145],\n }\n )\n #'a': [3, 50], 'b': [3, 50], 'c': [3, 50]})\n\n # we also need to convert pymatgen Structures to ase Atoms below\n #!!! is it faster and more memory efficient to import below?\n from pymatgen.io.ase import AseAtomsAdaptor\n\n self.adaptor = AseAtomsAdaptor\n\n def apply_transformation(self, structures): #!!! takes two structures!\n\n # split the structures into independent variables\n structure1, structure2 = [\n s.copy() for s in structures\n ] # copy because we may edit these into supercells below\n\n ### CHECK FOR BUGS\n\n # ASE requires the structures to be the same size but doesn't try\n # them to scale themselves. If we have two structures have the same\n # composition, we can just make supercells to make them the same size.\n if structure1.num_sites != structure2.num_sites:\n # get the least common multiple\n lcm = numpy.lcm(structure1.num_sites, structure2.num_sites)\n\n # scale each structure to that lcm\n # we don't care about the shape, just that the sites come out the same size\n #!!! THIS CAN GIVE A STRUCTURE WITH TOO LARGE OF A COMPOSITION!! NEED TO FIX THIS -----------------------------------------------------------------------\n structure1.make_supercell([int(lcm / structure1.num_sites), 1, 1])\n structure2.make_supercell([int(lcm / structure2.num_sites), 1, 1])\n\n # if the structures each only have one site, the mutation will fail\n if structure1.num_sites == 1:\n # print('You cannot perform a heredity mutation on structures that only have one site!! You can make this a supercell and try again though.')\n return False\n\n ### RUN\n\n # !!! This was moved below because composition isn't known right away -- the number of sites varies\n # now we can make the generator\n from ase.ga.cutandsplicepairing import CutAndSplicePairing\n\n self.casp = CutAndSplicePairing(\n slab=self.slab, # indicated dimensionality\n n_top=int(\n structure1.composition.num_atoms\n ), # number of atoms to optimize. I set this to all\n blmin=self.element_distance_matrix, # distance cutoff matrix\n number_of_variable_cell_vectors=3, #!!! I understand this as number of unique vectors. Is that right?\n # p1=1, # probablitiy of shifting\n # p2=0.05, # probablitiy of shifting\n # minfrac=None, # minimum fraction of atoms that a parent must contribute. None is one atom.\n cellbounds=self.cellbounds,\n # test_dist_to_slab=True,\n # use_tags=False,\n # rng=np.random,verbose=False\n )\n\n # first I need to convert the structures to an ASE atoms object\n structure1_ase = self.adaptor.get_atoms(structure1)\n structure2_ase = self.adaptor.get_atoms(structure2)\n\n #!!! Their code suggests the use of .get_new_individual() but I think .cross() is what we'd like\n new_structure_ase = self.casp.cross(structure1_ase, structure2_ase)\n\n # if the mutation fails, None is returned\n if not new_structure_ase:\n return False\n\n # if it was successful, we have a new Atoms object\n # now convert back to a pymatgen object\n new_structure = self.adaptor.get_structure(new_structure_ase)\n\n return new_structure\n"
] | [
[
"numpy.lcm"
]
] |
komoto48g/wxpj | [
"58152a7a26397b48cff3accedbea31f47be3d93e"
] | [
"plugins/lctf.py"
] | [
"#! python\n# -*- coding: utf-8 -*-\nimport cv2\nimport numpy as np\nfrom numpy import pi\nfrom numpy.fft import fft,ifft,fft2,ifft2,fftshift,fftfreq\nfrom scipy import signal\nfrom matplotlib import patches\nfrom mwx.controls import LParam\nfrom mwx.graphman import Layer\nfrom plugins.lcrf import Model\nfrom wxpyJemacs import wait\nimport editor as edi\n\n\ndef logpolar(src, r0, r1, center=None):\n \"\"\"Log-Polar transform\n The area radii [r0:r1] of radius N/2 mapsto the same size of src image\n \n cf. cv2.logPolar(src, (nx,ny), M, cv2.INTER_CUBIC)\n \"\"\"\n h, w = src.shape\n if center is None:\n xc, yc = w//2, h//2\n else:\n xc, yc = center\n \n x = np.arange(w, dtype=np.float32) /w\n y = np.arange(h, dtype=np.float32) * 2*pi /h\n xx, yy = np.meshgrid(x, y)\n \n rh0 = np.log(r0) if r0>0 else 0\n rh1 = np.log(r1)\n r = np.exp(rh0 + (rh1 - rh0) * xx)\n map_x = xc + r * np.cos(yy)\n map_y = yc + r * np.sin(yy)\n dst = cv2.remap(src.astype(np.float32), map_x, map_y, cv2.INTER_CUBIC)\n return dst\n\n\ndef find_ring_center(src, lo, hi, N=256, tol=0.01):\n \"\"\"find ring pattern in buffer with fixed center\n \n Polar 変換した後,角度セグメントに分割して相互相関をとる.\n center 固定,楕円を計測するために log-polar を使用する.\n theta = 0 を基準として,相対変位 [pixels] を計算する.\n \n src : source buffer (typ. log(abs(fft)))\n lo-hi : masking size of radial axis\n N : resizing of angular axis (total step in angle [0:2pi])\n tol : remove peaks that leap greater than N * tol\n retval ->\n dst(log-polar-transformed image) and fitting model\n \"\"\"\n h, w = src.shape\n \n dst = logpolar(src, lo, hi)\n \n ## Resize Y (angular) axis (計算を軽くするためリサイズ)\n rdst = cv2.resize(dst.astype(np.float32), (w, N), interpolation=cv2.INTER_AREA)\n \n rdst -= rdst.mean()\n rdst = cv2.GaussianBlur(rdst, (1,11), 0)\n \n temp = rdst[0][::-1] # template of corr; distr at theta=0(=2pi)\n data = []\n for fr in rdst:\n p = signal.fftconvolve(fr, temp, mode='same')\n data.append(p.argmax())\n \n ## 相関の計算は上から行うので,2pi --> 0 の並びのリストになる\n ## 最終的に返す計算結果は逆転させて,0 --> 2pi の並びにする\n Y = np.array(data[::-1]) - w/2\n X = np.arange(0, 1, 1/len(Y)) * 2*pi\n \n ## remove leaps(2): tol より小さいとびを許容する (画素サイズに比例)\n tolr = max(5, tol * w/2)\n xx, yy = [0.], [0.]\n for x,y in zip(X[1:], Y[1:]):\n if abs(y - yy[-1]) < tolr:\n xx.append(x)\n yy.append(y)\n \n fitting_curve = Model(xx, yy)\n \n ## edi.plot(xx, yy, '+', X, fitting_curve(X))\n \n fitting_curve.params[0] = 0 # :a=0 として(平均を基準とする)全体のオフセット量を評価する\n fitting_curve.params[1] = 0\n fitting_curve.params[2] = 0\n \n return dst, fitting_curve\n\n\ndef smooth1d(data, tol=0.01):\n w = len(data)\n lw = int(max(3, tol * w/2))\n if lw % 2 == 0:\n lw += 1\n return signal.savgol_filter(data, lw, polyorder=3)\n\n\ndef blur1d(data, tol=0.01):\n w = len(data)\n lw = int(max(3, tol * w/2))\n ## window = np.hanning(lw)\n window = signal.windows.gaussian(lw, std=lw)\n \n ## padding dumy data at both edge\n data = np.concatenate((data[:lw][::-1], data, data[-lw:][::-1]))\n ys = np.convolve(window/window.sum(), data, mode='same') # ならし\n ## ys = signal.lfilter(window/window.sum(), 1, data) # 短周期は苦手?NG\n return ys[lw:-lw]\n\n\ndef find_radial_peaks(data, tol=0.01):\n \"\"\"find local maxima/minim's\n smoothing with Gaussian window (signal.windows.gaussian)\n \"\"\"\n w = len(data)\n lw = int(max(3, tol * w/2))\n \n ys = blur1d(data, tol)\n \n ## maxima = signal.find_peaks_cwt(ys, np.arange(3,4))\n ## minima = signal.find_peaks_cwt(-ys, np.arange(3,4))\n maxima,_attr = signal.find_peaks(ys, width=lw/3)\n minima,_attr = signal.find_peaks(-ys, width=lw/3)\n \n ## maxima = signal.argrelmax(ys)\n ## minima = signal.argrelmin(ys)\n \n ## remove near-edge peaks\n def _edge(x):\n return x[(lw/2 < x) & (x < w-lw/2)]\n maxima = _edge(maxima)\n minima = _edge(minima)\n \n return ys, maxima, minima # np.sort(np.append(maxima, minima))\n\n\nclass Plugin(Layer):\n \"\"\"CTF finder ver 1.0\n \"\"\"\n menu = \"Test\"\n \n debug = 0\n \n def Init(self):\n self.rmin = LParam(\"rmin\", (0.01, 0.1, 0.001), 0.05,\n updater=lambda p: self.calc_ring(),\n tip=\"Ratio to the radius\")\n \n self.tol = LParam(\"tol\", (0, 0.1, 0.001), 0.01,\n updater=lambda p: self.calc_peak(),\n tip=\"Ratio to the radius of blurring pixels\")\n \n self.layout((\n self.rmin,\n self.tol,\n ),\n title=\"FFT Cond.\",\n type='vspin', style='button', lw=28, tw=50,\n )\n \n def init_session(self, session):\n self.reset_params(session.get('params'))\n \n if self.debug:\n print(\"$(session) = {!r}\".format((session)))\n self.__dict__.update(session)\n \n def save_session(self, session):\n session['params'] = self.parameters\n \n if self.debug:\n session.update({\n 'axis': self.axis,\n 'data': self.data,\n 'stig': self.stig,\n })\n \n @property\n def selected_frame(self):\n return self.graph.frame\n \n @property\n def selected_roi(self):\n src = self.selected_frame.buffer\n h, w = src.shape\n n = pow(2, int(np.log2(min(h,w)))-1) # resize to 2^n squared ROI\n i, j = h//2, w//2\n return src[i-n:i+n,j-n:j+n]\n \n @wait\n def calc_ring(self, show=True):\n \"\"\"Calc log-polar of ring pattern\n \"\"\"\n frame = self.selected_frame\n src = self.selected_roi\n h, w = src.shape\n \n buf = fftshift(fft2(src))\n buf = np.log(1 + abs(buf))\n buf -= buf.mean()\n \n self.message(\"Calculating CTF ring...\")\n r0 = w * self.rmin.value\n r1 = w * 0.5\n dst, self.fitting_curve = find_ring_center(buf, r0, r1, N=256, tol=0.05)\n \n m = w / np.log(r1/r0)\n \n self.axis = r0 / w * np.exp(np.arange(w) / m) # [R0:R1] <= [0:1/2]\n self.data = self.fitting_curve.mod1d(dst)\n \n if show:\n self.message(\"\\b Loading log-polar image...\")\n dst = self.fitting_curve.mod2d(dst)\n self.output.load(dst, \"*log-polar*\", pos=0)\n self.output.load(buf, \"*fft-of-{}*\".format(frame.name),\n localunit=1/w/frame.unit)\n del self.Arts\n self.message(\"\\b done.\")\n \n ## 拡張 log-polar 変換は振幅が m 倍だけ引き延ばされている\n eps, phi = self.fitting_curve.params[3:5]\n self.stig = eps / m * np.exp(phi * 1j)\n print(\"$result(eps, phi) = {!r}\".format((eps, phi)))\n \n @wait\n def calc_peak(self, show=True):\n \"\"\"Calc min/max peak detection\n \"\"\"\n N = self.data.size\n R0 = self.rmin.value\n R1 = 0.5\n tol = self.tol.value\n \n ## r2:data の一定間隔補間データを作ってゼロ点を求める\n newaxis = np.linspace(R0**2, R1**2, N)\n orgdata = np.interp(newaxis, self.axis**2, self.data)\n newdata = smooth1d(orgdata, tol)\n ## if show:\n ## edi.plot(newaxis, newdata, '-', lw=1) # original smoothing data\n \n newdata, maxima, minima = find_radial_peaks(newdata, tol)\n \n ## Check validity of zero-points spacing\n hx, hy = newaxis[maxima], newdata[maxima]\n lx, ly = newaxis[minima], newdata[minima]\n \n self.lxy = np.vstack((lx, ly))\n self.hxy = np.vstack((hx, hy))\n ## lp = np.vstack((lx, ly))\n \n ## --------------------------------\n ## filter low peaks\n ## --------------------------------\n threshold = tol/10 * R1**2\n print(\"$(threshold) = {!r}\".format((threshold)))\n lxx = []\n lyy = []\n for i, (x, y) in enumerate(zip(lx, ly)):\n ## Eliminate if near one of high peaks\n if min(abs(x - hx)) < threshold:\n continue\n ## Stop if two low pakes are continuous\n if i < len(lx)-1:\n if not np.any((x < hx) & (hx < lx[i+1])):\n break\n lxx.append(x)\n lyy.append(y)\n lp = np.vstack((lxx, lyy))\n \n self.lpoints = lp[:,:20] # max N low peaks\n self.newaxis = newaxis\n self.newdata = newdata\n \n ## --------------------------------\n ## output results to verify it\n ## --------------------------------\n \n print(\"+ {} low peaks found\".format(lp.shape[1]))\n if show:\n edi.plot(self.axis**2, self.data, '--', lw=0.5) # raw data\n ## edi.plot(newaxis, orgdata, '--', lw=1) # original data\n edi.plot(newaxis, newdata, '-', lw=1) # interpolated\n edi.plot(lx, ly, 'v') # low peaks\n edi.plot(hx, hy, '^') # high peaks\n edi.plot(*self.lpoints, 'o') # filtered peaks\n \n try:\n u = self.output.frame.unit\n eps = np.abs(self.stig)\n ang = np.angle(self.stig) * 180/pi\n \n ## 不特定多数の円を描画する (最大 N まで)\n del self.Arts\n for x in self.lpoints[0,:10]:\n r = N * np.sqrt(x)\n art = patches.Circle((0,0), 0, color='r', ls='--', lw=0.5, fill=0, alpha=0.5)\n art.width = 2 * r * (1 + eps) * u\n art.height = 2 * r * (1 - eps) * u\n art.angle = ang / 2\n self.attach_artists(self.output.axes, art)\n self.output.draw()\n except Exception:\n self.message(\"- no data.\")\n"
] | [
[
"scipy.signal.find_peaks",
"numpy.sqrt",
"numpy.linspace",
"numpy.concatenate",
"numpy.any",
"numpy.exp",
"scipy.signal.savgol_filter",
"numpy.arange",
"scipy.signal.windows.gaussian",
"numpy.sin",
"numpy.interp",
"numpy.fft.fft2",
"numpy.log",
"scipy.signal.fftconvolve",
"matplotlib.patches.Circle",
"numpy.meshgrid",
"numpy.array",
"numpy.abs",
"numpy.cos",
"numpy.angle",
"numpy.vstack"
]
] |
sebpadilla09/computer-vision-dojo | [
"4c55081c7ec37278d45f649e1f5109031f776a04"
] | [
"python/class-challenges/scripts/working_pixels_chall_1.py"
] | [
"# Built-int imports \nimport os\nimport sys\nimport argparse\n\n# External imports\nimport cv2 as cv\nimport numpy as np\n\n# My own imports \nimport get_path_assests_folder as gpaf\n\n# Get assets folder in repo for the samples\nASSETS_FOLDER = gpaf.get_assets_folder_path()\n\n\nclass DolphinPlayingWithPixels:\n \"\"\"\n Python class that has all the necessary methods to solve the first challenge\n of the EIA University's class of computer vision, the chanllenges was just some\n exercises to play with the pixels of an image.\n \"\"\"\n def __init__(self):\n self.__delfin_path = self.get_image_path()\n self.image = cv.imread(self.__delfin_path, 1)\n self.__rows, self.__cols, self.__channels = self.image.shape\n\n\n def get_image_path(self):\n image_relative_path = os.path.join(\n ASSETS_FOLDER, \"imgs\", \"delfin.jpg\")\n return image_relative_path\n\n def dolphin_separated(self, channel):\n new_image = cv.imread(self.__delfin_path, 1)\n for (i,j,c), _ in np.ndenumerate(new_image):\n if c == channel:\n new_image[i,j,c] = 255\n cv.imshow(f\"New dolphin channel: {channel}\", new_image)\n \n def dolphin_channels(self):\n \"\"\"\n Method to show an image in its tree channels (Red, Green, Blue).\n \"\"\"\n cv.imshow(\"Original dolphin\", self.image)\n for i in iter(range(3)):\n self.dolphin_separated(i)\n cv.waitKey(0)\n cv.destroyAllWindows()\n\n def dolphin_y_reverse(self):\n \"\"\"\n Method for creating a mirror image on the y-axis.\n \"\"\"\n new_image = cv.imread(self.__delfin_path, 1)\n\n for i in iter(range(self.__rows)):\n for c in iter(range(self.__channels)):\n for j in iter(range(self.__cols)):\n new_image[i,j,c] = self.image[i,(self.__cols-1)-j, c]\n cv.imshow(\"Original dolphin\", self.image)\n cv.imshow(\"y reverse dolphin\", new_image)\n cv.waitKey(0)\n cv.destroyAllWindows()\n\n def dolphin_x_reverse(self):\n \"\"\"\n Method for creating a mirror image on the x-axis.\n \"\"\"\n new_image = cv.imread(self.__delfin_path, 1)\n\n for j in iter(range(self.__cols)):\n for c in iter(range(self.__channels)):\n for i in iter(range(self.__rows)):\n new_image[i,j,c] = self.image[(self.__rows-1)-i, j, c]\n cv.imshow(\"Original dolphin\", self.image)\n cv.imshow(\"x reverse dolphin\", new_image)\n cv.waitKey(0)\n cv.destroyAllWindows()\n\n def dolphin_colorfull(self):\n \"\"\"\n Method to created an image in a RBG mosaic with 4 squares.\n \"\"\"\n new_image = cv.imread(self.__delfin_path, 1)\n\n for (i,j,c), _ in np.ndenumerate(new_image):\n if (i < self.__rows/2 and j >= self.__cols/2 and c == 0): \n new_image[i,j,c] = 255\n if (i >= self.__rows/2 and j < self.__cols/2 and c == 1): \n new_image[i,j,c] = 255\n if (i >= self.__rows/2 and j >= self.__cols/2 and c == 2): \n new_image[i,j,c] = 255\n cv.imshow(\"Original dolphin\", self.image)\n cv.imshow(\"Colorfull dolphin\", new_image)\n cv.waitKey(0)\n cv.destroyAllWindows()\n\n def dolphin_colorfull_by_user(self, px, py):\n \"\"\"\n Method to create an image in an RGB mosaic, considering the width and the \n height values entered by the user.\n\n :param px: height of the squares of the mosaic\n :para, py: weidth of the squares of the mosaic\n \"\"\"\n new_image = cv.imread(self.__delfin_path, 1)\n print(f\"px: {px} and py: {py}\")\n x_count , y_count, c_count = (0,0,0)\n x_refe, y_refe, c_refe = (0,0,0)\n x_number = int(self.__rows/px)\n y_number = int(self.__cols/py)\n print(f\"x_number: {x_number} y_number: {y_number}\")\n\n def validated_limits(count, limit):\n if (count == limit):\n return 0\n return (count + 1)\n\n for i in iter(range(self.__rows)):\n x_count = i - x_refe\n for j in iter(range(self.__cols)):\n y_count = j - y_refe\n if (x_count <= px and y_count <= py):\n new_image[i,j,c_count] = 255\n if (j == self.__cols - 1):\n y_refe, c_count = (0,c_refe)\n if (y_count > py):\n y_refe = j\n c_count = validated_limits(c_count,2)\n if (x_count > px):\n c_refe = validated_limits(c_refe,2)\n x_refe = i \n\n cv.imshow(\"Original dolphin\", self.image)\n cv.imshow(\"Colorfull by user dolphin\", new_image)\n cv.waitKey(0)\n cv.destroyAllWindows()\n\n\n\n\ndef main():\n \"\"\"COMPUTER VISION - EIA UNIVERSITY\n First challenge of the EIA University's computer vision class.\n Run this scripts in order to see Elkin Guerra's solucion \n of this test. \n \"\"\"\n epilog = \"\"\"\n Related examples:\n More to come...\n \"\"\"\n arg_fmt = argparse.RawDescriptionHelpFormatter\n parser = argparse.ArgumentParser(formatter_class=arg_fmt,\n description=main.__doc__,\n epilog=epilog\n )\n required = parser.add_argument_group('required arguments')\n required.add_argument(\n '-s', '--stage', dest='stage', required=True, choices=[\n \"one\",\"two\",\"tree\",\"four\",\"five\"\n ],\n help='The stage of the challenge you want to execute'\n )\n\n parser.add_argument(\n '-d', '--dimensions', dest='dimensions', required=False, nargs='+',\n help='Height and Weidth for the squares of the mosaic'\n )\n\n\n args = parser.parse_args()\n\n if args.dimensions != None:\n dimen = [int(x) for x in args.dimensions]\n\n print(\"Initializing program... \")\n dolphin = DolphinPlayingWithPixels()\n\n try:\n act = args.stage\n if act == \"one\":\n dolphin.dolphin_channels()\n elif act == \"two\":\n dolphin.dolphin_y_reverse()\n elif act == \"tree\":\n dolphin.dolphin_x_reverse()\n elif act == \"four\":\n dolphin.dolphin_colorfull()\n elif act == \"five\":\n dolphin.dolphin_colorfull_by_user(dimen[0],dimen[1])\n \n except:\n print(\"ERROR JUST HAPPEND\")\n\n return 0\n\n\nif __name__=='__main__':\n sys.exit(main())"
] | [
[
"numpy.ndenumerate"
]
] |
steven0129/yolact_edge | [
"748e1595a50987d85932ee4ad4fbb3fadf0d3fbb"
] | [
"data/config.py"
] | [
"from backbone import ResNetBackbone, VGGBackbone, ResNetBackboneGN, DarkNetBackbone, MobileNetV2Backbone\nfrom math import sqrt\nimport torch\n\n# for making bounding boxes pretty\nCOLORS = ((244, 67, 54),\n (233, 30, 99),\n (156, 39, 176),\n (103, 58, 183),\n ( 63, 81, 181),\n ( 33, 150, 243),\n ( 3, 169, 244),\n ( 0, 188, 212),\n ( 0, 150, 136),\n ( 76, 175, 80),\n (139, 195, 74),\n (205, 220, 57),\n (255, 235, 59),\n (255, 193, 7),\n (255, 152, 0),\n (255, 87, 34),\n (121, 85, 72),\n (158, 158, 158),\n ( 96, 125, 139))\n\n\n# These are in BGR and are for ImageNet\nMEANS = (103.94, 116.78, 123.68)\nSTD = (57.38, 57.12, 58.40)\n\nCOCO_CLASSES = ('person', 'bicycle', 'car', 'motorcycle', 'airplane', 'bus',\n 'train', 'truck', 'boat', 'traffic light', 'fire hydrant',\n 'stop sign', 'parking meter', 'bench', 'bird', 'cat', 'dog',\n 'horse', 'sheep', 'cow', 'elephant', 'bear', 'zebra', 'giraffe',\n 'backpack', 'umbrella', 'handbag', 'tie', 'suitcase', 'frisbee',\n 'skis', 'snowboard', 'sports ball', 'kite', 'baseball bat',\n 'baseball glove', 'skateboard', 'surfboard', 'tennis racket',\n 'bottle', 'wine glass', 'cup', 'fork', 'knife', 'spoon', 'bowl',\n 'banana', 'apple', 'sandwich', 'orange', 'broccoli', 'carrot',\n 'hot dog', 'pizza', 'donut', 'cake', 'chair', 'couch',\n 'potted plant', 'bed', 'dining table', 'toilet', 'tv', 'laptop',\n 'mouse', 'remote', 'keyboard', 'cell phone', 'microwave', 'oven',\n 'toaster', 'sink', 'refrigerator', 'book', 'clock', 'vase',\n 'scissors', 'teddy bear', 'hair drier', 'toothbrush')\n\nCOCO_LABEL_MAP = { 1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 7, 8: 8,\n 9: 9, 10: 10, 11: 11, 13: 12, 14: 13, 15: 14, 16: 15, 17: 16,\n 18: 17, 19: 18, 20: 19, 21: 20, 22: 21, 23: 22, 24: 23, 25: 24,\n 27: 25, 28: 26, 31: 27, 32: 28, 33: 29, 34: 30, 35: 31, 36: 32,\n 37: 33, 38: 34, 39: 35, 40: 36, 41: 37, 42: 38, 43: 39, 44: 40,\n 46: 41, 47: 42, 48: 43, 49: 44, 50: 45, 51: 46, 52: 47, 53: 48,\n 54: 49, 55: 50, 56: 51, 57: 52, 58: 53, 59: 54, 60: 55, 61: 56,\n 62: 57, 63: 58, 64: 59, 65: 60, 67: 61, 70: 62, 72: 63, 73: 64,\n 74: 65, 75: 66, 76: 67, 77: 68, 78: 69, 79: 70, 80: 71, 81: 72,\n 82: 73, 84: 74, 85: 75, 86: 76, 87: 77, 88: 78, 89: 79, 90: 80}\n\nYOUTUBE_VIS_CLASSES = ('person', 'giant_panda', 'lizard', 'parrot', 'skateboard',\n 'sedan', 'ape', 'dog', 'snake', 'monkey', 'hand', 'rabbit',\n 'duck', 'cat', 'cow', 'fish', 'train', 'horse', 'turtle',\n 'bear', 'motorbike', 'giraffe', 'leopard', 'fox', 'deer',\n 'owl', 'surfboard', 'airplane', 'truck', 'zebra', 'tiger',\n 'elephant', 'snowboard', 'boat', 'shark', 'mouse', 'frog',\n 'eagle', 'earless_seal', 'tennis_racket')\n\nYOUTUBE_VIS_LABEL_MAP = { 1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 7,\n 8: 8, 9: 9, 10: 10, 11: 11, 12: 12, 13: 13, 14: 14,\n 15: 15, 16: 16, 17: 17, 18: 18, 19: 19, 20: 20, 21: 21,\n 22: 22, 23: 23, 24: 24, 25: 25, 26: 26, 27: 27, 28: 28,\n 29: 29, 30: 30, 31: 31, 32: 32, 33: 33, 34: 34, 35: 35,\n 36: 36, 37: 37, 38: 38, 39: 39, 40: 40}\n\nCOCO_INV_LABEL_MAP = {t: s for s, t in COCO_LABEL_MAP.items()}\n\nYTVIS_COCO_CLASS_MAP = {'person': 'person', 'skateboard': 'skateboard', 'sedan': 'car',\n 'dog': 'dog', 'cat': 'cat', 'cow': 'cow', 'train': 'train',\n 'horse': 'horse', 'bear': 'bear', 'motorbike': 'motorcycle',\n 'giraffe': 'giraffe', 'surfboard': 'surfboard', 'airplane': 'airplane',\n 'truck': 'truck', 'zebra': 'zebra', 'elephant': 'elephant',\n 'snowboard': 'snowboard', 'boat': 'boat', 'tennis_racket': 'tennis racket'}\n\nCOCO_YTVIS_CLASS_MAP = {coco: ytvis for ytvis, coco in YTVIS_COCO_CLASS_MAP.items()}\nCOCO_YTVIS_LABEL_MAP = {COCO_INV_LABEL_MAP[COCO_CLASSES.index(coco) + 1]: YOUTUBE_VIS_CLASSES.index(ytvis) + 1 for coco, ytvis in COCO_YTVIS_CLASS_MAP.items()}\nCOCO_INTER_LABEL_MAP = {COCO_INV_LABEL_MAP[COCO_CLASSES.index(coco) + 1]: COCO_CLASSES.index(coco) + 1 for coco in COCO_YTVIS_CLASS_MAP}\n\nMOTS_CLASSES = ('car', 'pedestrian')\nMOTS_LABEL_MAP = {1: 1, 2: 2}\n\n# ----------------------- CONFIG CLASS ----------------------- #\n\nclass Config(object):\n \"\"\"\n Holds the configuration for anything you want it to.\n To get the currently active config, call get_cfg().\n\n To use, just do cfg.x instead of cfg['x'].\n I made this because doing cfg['x'] all the time is dumb.\n \"\"\"\n\n def __init__(self, config_dict):\n for key, val in config_dict.items():\n self.__setattr__(key, val)\n\n def copy(self, new_config_dict={}):\n \"\"\"\n Copies this config into a new config object, making\n the changes given by new_config_dict.\n \"\"\"\n\n ret = Config(vars(self))\n \n for key, val in new_config_dict.items():\n ret.__setattr__(key, val)\n\n return ret\n\n def replace(self, new_config_dict):\n \"\"\"\n Copies new_config_dict into this config object.\n Note: new_config_dict can also be a config object.\n \"\"\"\n if isinstance(new_config_dict, Config):\n new_config_dict = vars(new_config_dict)\n\n for key, val in new_config_dict.items():\n self.__setattr__(key, val)\n \n def print(self):\n for k, v in vars(self).items():\n print(k, ' = ', v)\n\n\n\n\n\n# ----------------------- DATASETS ----------------------- #\n\ndataset_base = Config({\n 'name': 'Base Dataset',\n\n # Training images and annotations\n 'train_images': './data/coco/images/',\n 'train_info': 'path_to_annotation_file',\n\n # Calibration image folder for TensorRT INT8 conversion.\n 'calib_images': './data/coco/calib_images/',\n \n # Validation images and annotations.\n 'valid_images': './data/coco/images/',\n 'valid_info': 'path_to_annotation_file',\n\n # Whether or not to load GT. If this is False, eval.py quantitative evaluation won't work.\n 'has_gt': True,\n\n # Whether the dataset is a video dataset\n 'is_video': False,\n\n # A list of names for each of you classes.\n 'class_names': COCO_CLASSES,\n\n # COCO class ids aren't sequential, so this is a bandage fix. If your ids aren't sequential,\n # provide a map from category_id -> index in class_names + 1 (the +1 is there because it's 1-indexed).\n # If not specified, this just assumes category ids start at 1 and increase sequentially.\n 'label_map': None,\n\n # Dataset Map\n 'dataset_map': None,\n\n # Joint training\n 'joint': None\n})\n\ncoco2014_dataset = dataset_base.copy({\n 'name': 'COCO 2014',\n \n 'train_info': './data/coco/annotations/instances_train2014.json',\n 'valid_info': './data/coco/annotations/instances_val2014.json',\n\n 'label_map': COCO_LABEL_MAP\n})\n\ncoco2017_dataset = dataset_base.copy({\n 'name': 'COCO 2017',\n \n 'train_info': './data/coco/annotations/instances_train2017.json',\n 'valid_info': './data/coco/annotations/instances_val2017.json',\n\n 'label_map': COCO_LABEL_MAP\n})\n\ncoco2017_testdev_dataset = dataset_base.copy({\n 'name': 'COCO 2017 Test-Dev',\n\n 'valid_info': './data/coco/annotations/image_info_test-dev2017.json',\n 'has_gt': False,\n\n 'label_map': COCO_LABEL_MAP\n})\n\nflying_chairs_dataset = dataset_base.copy({\n 'name': 'FlyingChairs',\n\n 'trainval_info': './data/FlyingChairs/train_val.txt',\n 'trainval_images': './data/FlyingChairs/data/',\n})\n\nyoutube_vis_dataset = dataset_base.copy({\n 'name': 'YouTube VIS',\n\n 'class_names': YOUTUBE_VIS_CLASSES,\n 'label_map': YOUTUBE_VIS_LABEL_MAP,\n\n 'train_info': './data/YoutubeVIS/annotations/train.v4.json',\n 'train_images': './data/YoutubeVIS/train_all_frames/JPEGImages/',\n 'use_all_frames': False,\n\n # Calibration image folder for TensorRT INT8 conversion.\n # Because we need two frames (prev, next) to estimate flows and calibrate the warping module, we need to specify a parent folder for calibration images, and two sub-folders for previous and next frames correspondingly.\n # Use colon(:) to split folder (sub-folders).\n 'calib_images': './data/YoutubeVIS/calib_images/:prev:next',\n\n 'frame_offset_lb': 1,\n 'frame_offset_ub': 4,\n 'frame_offset_multiplier': 1,\n 'all_frame_direction': 'allway',\n\n 'valid_info': './data/YoutubeVIS/annotations/valid.v4.json',\n 'valid_images': './data/YoutubeVIS/valid_all_frames/v4/',\n\n 'images_per_video': 5,\n 'is_video': True\n})\n\n\n\n\n\n\n# ----------------------- TRANSFORMS ----------------------- #\n\nresnet_transform = Config({\n 'channel_order': 'RGB',\n 'normalize': True,\n 'subtract_means': False,\n 'to_float': False,\n})\n\nvgg_transform = Config({\n # Note that though vgg is traditionally BGR,\n # the channel order of vgg_reducedfc.pth is RGB.\n 'channel_order': 'RGB',\n 'normalize': False,\n 'subtract_means': True,\n 'to_float': False,\n})\n\ndarknet_transform = Config({\n 'channel_order': 'RGB',\n 'normalize': False,\n 'subtract_means': False,\n 'to_float': True,\n})\n\nmobilenetv2_transform = Config({\n 'channel_order': 'RGB',\n 'normalize': True,\n 'subtract_means': False,\n 'to_float': False,\n})\n\n\n\n# ----------------------- BACKBONES ----------------------- #\n\nbackbone_base = Config({\n 'name': 'Base Backbone',\n 'path': 'path/to/pretrained/weights',\n 'type': object,\n 'args': tuple(),\n 'transform': resnet_transform,\n\n 'selected_layers': list(),\n 'pred_scales': list(),\n 'pred_aspect_ratios': list(),\n\n 'use_pixel_scales': False,\n 'preapply_sqrt': True,\n 'use_square_anchors': False,\n})\n\nresnet101_backbone = backbone_base.copy({\n 'name': 'ResNet101',\n 'path': 'resnet101_reducedfc.pth',\n 'type': ResNetBackbone,\n 'args': ([3, 4, 23, 3],),\n 'transform': resnet_transform,\n\n 'selected_layers': list(range(2, 8)),\n 'pred_scales': [[1]]*6,\n 'pred_aspect_ratios': [ [[0.66685089, 1.7073535, 0.87508774, 1.16524493, 0.49059086]] ] * 6,\n})\n\nresnet101_gn_backbone = backbone_base.copy({\n 'name': 'ResNet101_GN',\n 'path': 'R-101-GN.pkl',\n 'type': ResNetBackboneGN,\n 'args': ([3, 4, 23, 3],),\n 'transform': resnet_transform,\n\n 'selected_layers': list(range(2, 8)),\n 'pred_scales': [[1]]*6,\n 'pred_aspect_ratios': [ [[0.66685089, 1.7073535, 0.87508774, 1.16524493, 0.49059086]] ] * 6,\n})\n\nresnet152_backbone = resnet101_backbone.copy({\n 'name': 'ResNet152',\n 'path': 'resnet152-b121ed2d.pth',\n 'type': ResNetBackbone,\n 'args': ([3, 8, 36, 3],),\n 'transform': resnet_transform,\n})\n\nresnet50_backbone = resnet101_backbone.copy({\n 'name': 'ResNet50',\n 'path': 'resnet50-19c8e357.pth',\n 'type': ResNetBackbone,\n 'args': ([3, 4, 6, 3],),\n 'transform': resnet_transform,\n})\n\ndarknet53_backbone = backbone_base.copy({\n 'name': 'DarkNet53',\n 'path': 'darknet53.pth',\n 'type': DarkNetBackbone,\n 'args': ([1, 2, 8, 8, 4],),\n 'transform': darknet_transform,\n\n 'selected_layers': list(range(3, 9)),\n 'pred_scales': [[3.5, 4.95], [3.6, 4.90], [3.3, 4.02], [2.7, 3.10], [2.1, 2.37], [1.8, 1.92]],\n 'pred_aspect_ratios': [ [[1, sqrt(2), 1/sqrt(2), sqrt(3), 1/sqrt(3)][:n], [1]] for n in [3, 5, 5, 5, 3, 3] ],\n})\n\nvgg16_arch = [[64, 64],\n [ 'M', 128, 128],\n [ 'M', 256, 256, 256],\n [('M', {'kernel_size': 2, 'stride': 2, 'ceil_mode': True}), 512, 512, 512],\n [ 'M', 512, 512, 512],\n [('M', {'kernel_size': 3, 'stride': 1, 'padding': 1}),\n (1024, {'kernel_size': 3, 'padding': 6, 'dilation': 6}),\n (1024, {'kernel_size': 1})]]\n\nvgg16_backbone = backbone_base.copy({\n 'name': 'VGG16',\n 'path': 'vgg16_reducedfc.pth',\n 'type': VGGBackbone,\n 'args': (vgg16_arch, [(256, 2), (128, 2), (128, 1), (128, 1)], [3]),\n 'transform': vgg_transform,\n\n 'selected_layers': [3] + list(range(5, 10)),\n 'pred_scales': [[5, 4]]*6,\n 'pred_aspect_ratios': [ [[1], [1, sqrt(2), 1/sqrt(2), sqrt(3), 1/sqrt(3)][:n]] for n in [3, 5, 5, 5, 3, 3] ],\n})\n\nmobilenetv2_arch = [\n # t, c, n, s\n [1, 16, 1, 1],\n [6, 24, 2, 2],\n [6, 32, 3, 2],\n [6, 64, 4, 2],\n [6, 96, 3, 1],\n [6, 160, 3, 2],\n [6, 320, 1, 1],\n]\n\nmobilenetv2_backbone = backbone_base.copy({\n 'name': 'MobileNetV2',\n 'path': 'mobilenet_v2-b0353104.pth',\n 'type': MobileNetV2Backbone,\n 'args': (1.0, mobilenetv2_arch, 8),\n 'transform': mobilenetv2_transform,\n\n 'selected_layers': [3, 4, 6],\n \n 'pred_aspect_ratios': [ [[1, 1/2, 2]] ]*5,\n 'pred_scales': [[24], [48], [96], [192], [384]],\n\n 'use_pixel_scales': True,\n 'preapply_sqrt': False,\n 'use_square_anchors': True,\n})\n\n\n\n# ----------------------- MASK BRANCH TYPES ----------------------- #\n\nmask_type = Config({\n # Direct produces masks directly as the output of each pred module.\n # This is denoted as fc-mask in the paper.\n # Parameters: mask_size, use_gt_bboxes\n 'direct': 0,\n\n # Lincomb produces coefficients as the output of each pred module then uses those coefficients\n # to linearly combine features from a prototype network to create image-sized masks.\n # Parameters:\n # - masks_to_train (int): Since we're producing (near) full image masks, it'd take too much\n # vram to backprop on every single mask. Thus we select only a subset.\n # - mask_proto_src (int): The input layer to the mask prototype generation network. This is an\n # index in backbone.layers. Use to use the image itself instead.\n # - mask_proto_net (list<tuple>): A list of layers in the mask proto network with the last one\n # being where the masks are taken from. Each conv layer is in\n # the form (num_features, kernel_size, **kwdargs). An empty\n # list means to use the source for prototype masks. If the\n # kernel_size is negative, this creates a deconv layer instead.\n # If the kernel_size is negative and the num_features is None,\n # this creates a simple bilinear interpolation layer instead.\n # - mask_proto_bias (bool): Whether to include an extra coefficient that corresponds to a proto\n # mask of all ones.\n # - mask_proto_prototype_activation (func): The activation to apply to each prototype mask.\n # - mask_proto_mask_activation (func): After summing the prototype masks with the predicted\n # coeffs, what activation to apply to the final mask.\n # - mask_proto_coeff_activation (func): The activation to apply to the mask coefficients.\n # - mask_proto_crop (bool): If True, crop the mask with the predicted bbox during training.\n # - mask_proto_crop_expand (float): If cropping, the percent to expand the cropping bbox by\n # in each direction. This is to make the model less reliant\n # on perfect bbox predictions.\n # - mask_proto_loss (str [l1|disj]): If not None, apply an l1 or disjunctive regularization\n # loss directly to the prototype masks.\n # - mask_proto_binarize_downsampled_gt (bool): Binarize GT after dowsnampling during training?\n # - mask_proto_normalize_mask_loss_by_sqrt_area (bool): Whether to normalize mask loss by sqrt(sum(gt))\n # - mask_proto_reweight_mask_loss (bool): Reweight mask loss such that background is divided by\n # #background and foreground is divided by #foreground.\n # - mask_proto_grid_file (str): The path to the grid file to use with the next option.\n # This should be a numpy.dump file with shape [numgrids, h, w]\n # where h and w are w.r.t. the mask_proto_src convout.\n # - mask_proto_use_grid (bool): Whether to add extra grid features to the proto_net input.\n # - mask_proto_coeff_gate (bool): Add an extra set of sigmoided coefficients that is multiplied\n # into the predicted coefficients in order to \"gate\" them.\n # - mask_proto_prototypes_as_features (bool): For each prediction module, downsample the prototypes\n # to the convout size of that module and supply the prototypes as input\n # in addition to the already supplied backbone features.\n # - mask_proto_prototypes_as_features_no_grad (bool): If the above is set, don't backprop gradients to\n # to the prototypes from the network head.\n # - mask_proto_remove_empty_masks (bool): Remove masks that are downsampled to 0 during loss calculations.\n # - mask_proto_reweight_coeff (float): The coefficient to multiple the forground pixels with if reweighting.\n # - mask_proto_coeff_diversity_loss (bool): Apply coefficient diversity loss on the coefficients so that the same\n # instance has similar coefficients.\n # - mask_proto_coeff_diversity_alpha (float): The weight to use for the coefficient diversity loss.\n # - mask_proto_normalize_emulate_roi_pooling (bool): Normalize the mask loss to emulate roi pooling's affect on loss.\n # - mask_proto_double_loss (bool): Whether to use the old loss in addition to any special new losses.\n # - mask_proto_double_loss_alpha (float): The alpha to weight the above loss.\n 'lincomb': 1,\n})\n\n\n\n\n\n# ----------------------- ACTIVATION FUNCTIONS ----------------------- #\n\nactivation_func = Config({\n 'tanh': torch.tanh,\n 'sigmoid': torch.sigmoid,\n 'softmax': lambda x: torch.nn.functional.softmax(x, dim=-1),\n 'relu': lambda x: torch.nn.functional.relu(x, inplace=True),\n 'none': lambda x: x,\n})\n\n\n\n\n\n# ----------------------- FPN DEFAULTS ----------------------- #\n\nfpn_base = Config({\n # The number of features to have in each FPN layer\n 'num_features': 256,\n\n # The upsampling mode used\n 'interpolation_mode': 'bilinear',\n\n # The number of extra layers to be produced by downsampling starting at P5\n 'num_downsample': 1,\n\n # Whether to down sample with a 3x3 stride 2 conv layer instead of just a stride 2 selection\n 'use_conv_downsample': False,\n\n # Whether to pad the pred layers with 1 on each side (I forgot to add this at the start)\n # This is just here for backwards compatibility\n 'pad': True,\n})\n\n\n\n# ------------------------ FLOW DEFAULTS ------------------------ #\nflow_base = Config({\n 'selected_backbone': 0,\n 'layer_features': [128, 128, 96, 64, 32],\n 'patch_size': 3,\n 'encode_layers': [[4, 1], [2], [4]],\n 'encode_channels': 256,\n 'fine_tune_layers': None,\n 'interpolate_upsample': False,\n 'use_computed_P3': True,\n 'warp_layers': \"P4P5\",\n 'flow_direct_downsample': False,\n 'use_spa': False,\n 'use_spa_both': False,\n 'use_normalized_spa': False,\n 'use_shuffle_cat': False,\n 'num_groups': 1,\n 'use_scale_factor': True,\n 'use_scale_bias': True,\n 'reduce_channels': [],\n 'warp_mode': 'none',\n 'flow_layer': 'each',\n 'warp_target': 'feature',\n 'pred_heads_no_conflict': False,\n 'proto_net_no_conflict': False,\n 'fpn_no_conflict': False,\n 'warp_flow_layer': 'top',\n 'correlation': 'external',\n 'base_backward': True,\n 'feature_matching_loss': None,\n 'fm_loss_loc': 'L',\n 'fm_loss_alpha': 1.0,\n 'train_flow': False,\n 'model': 'none',\n})\n\n\n# ----------------------- CONFIG DEFAULTS ----------------------- #\n\ncoco_base_config = Config({\n 'dataset': coco2014_dataset,\n 'joint_dataset': None,\n 'num_classes': 81, # This should include the background class\n\n 'max_iter': 400000,\n\n # The maximum number of detections for evaluation\n 'max_num_detections': 100,\n\n # dw' = momentum * dw - lr * (grad + decay * w)\n 'lr': 1e-3,\n 'momentum': 0.9,\n 'decay': 5e-4,\n\n # For each lr step, what to multiply the lr with\n 'gamma': 0.1,\n 'lr_steps': (280000, 360000, 400000),\n\n # Initial learning rate to linearly warmup from (if until > 0)\n 'lr_warmup_init': 1e-4,\n\n # If > 0 then increase the lr linearly from warmup_init to lr each iter for until iters\n 'lr_warmup_until': 500,\n\n # The terms to scale the respective loss by\n 'conf_alpha': 1,\n 'bbox_alpha': 1.5,\n 'mask_alpha': 0.4 / 256 * 140 * 140, # Some funky equation. Don't worry about it.\n\n # Eval.py sets this if you just want to run YOLACT as a detector\n 'eval_mask_branch': True,\n\n # See mask_type for details.\n 'mask_type': mask_type.direct,\n 'mask_size': 16,\n 'masks_to_train': 100,\n 'mask_proto_src': None,\n 'mask_proto_net': [(256, 3, {}), (256, 3, {})],\n 'mask_proto_bias': False,\n 'mask_proto_prototype_activation': activation_func.relu,\n 'mask_proto_mask_activation': activation_func.sigmoid,\n 'mask_proto_coeff_activation': activation_func.tanh,\n 'mask_proto_crop': True,\n 'mask_proto_crop_expand': 0,\n 'mask_proto_loss': None,\n 'mask_proto_binarize_downsampled_gt': True,\n 'mask_proto_normalize_mask_loss_by_sqrt_area': False,\n 'mask_proto_reweight_mask_loss': False,\n 'mask_proto_grid_file': 'data/grid.npy',\n 'mask_proto_use_grid': False,\n 'mask_proto_coeff_gate': False,\n 'mask_proto_prototypes_as_features': False,\n 'mask_proto_prototypes_as_features_no_grad': False,\n 'mask_proto_remove_empty_masks': False,\n 'mask_proto_reweight_coeff': 1,\n 'mask_proto_coeff_diversity_loss': False,\n 'mask_proto_coeff_diversity_alpha': 1,\n 'mask_proto_normalize_emulate_roi_pooling': False,\n 'mask_proto_double_loss': False,\n 'mask_proto_double_loss_alpha': 1,\n\n # SSD data augmentation parameters\n # Randomize hue, vibrance, etc.\n 'augment_photometric_distort': True,\n # Have a chance to scale down the image and pad (to emulate smaller detections)\n 'augment_expand': True,\n # Potentialy sample a random crop from the image and put it in a random place\n 'augment_random_sample_crop': True,\n # Mirror the image with a probability of 1/2\n 'augment_random_mirror': True,\n # Flip the image vertically with a probability of 1/2\n 'augment_random_flip': False,\n # With uniform probability, rotate the image [0,90,180,270] degrees\n 'augment_random_rot90': False,\n\n # Discard detections with width and height smaller than this (in absolute width and height)\n 'discard_box_width': 4 / 550,\n 'discard_box_height': 4 / 550,\n\n # If using batchnorm anywhere in the backbone, freeze the batchnorm layer during training.\n # Note: any additional batch norm layers after the backbone will not be frozen.\n 'freeze_bn': False,\n\n # Set this to a config object if you want an FPN (inherit from fpn_base). See fpn_base for details.\n 'fpn': None,\n\n # Use the same weights for each network head\n 'share_prediction_module': False,\n\n # For hard negative mining, instead of using the negatives that are leastl confidently background,\n # use negatives that are most confidently not background.\n 'ohem_use_most_confident': False,\n\n # Use focal loss as described in https://arxiv.org/pdf/1708.02002.pdf instead of OHEM\n 'use_focal_loss': False,\n 'focal_loss_alpha': 0.25,\n 'focal_loss_gamma': 2,\n \n # The initial bias toward forground objects, as specified in the focal loss paper\n 'focal_loss_init_pi': 0.01,\n\n # Whether to use sigmoid focal loss instead of softmax, all else being the same.\n 'use_sigmoid_focal_loss': False,\n\n # Use class[0] to be the objectness score and class[1:] to be the softmax predicted class.\n # Note: at the moment this is only implemented if use_focal_loss is on.\n 'use_objectness_score': False,\n\n # Adds a global pool + fc layer to the smallest selected layer that predicts the existence of each of the 80 classes.\n # This branch is only evaluated during training time and is just there for multitask learning.\n 'use_class_existence_loss': False,\n 'class_existence_alpha': 1,\n\n # Adds a 1x1 convolution directly to the biggest selected layer that predicts a semantic segmentations for each of the 80 classes.\n # This branch is only evaluated during training time and is just there for multitask learning.\n 'use_semantic_segmentation_loss': False,\n 'semantic_segmentation_alpha': 1,\n\n # Match gt boxes using the Box2Pix change metric instead of the standard IoU metric.\n # Note that the threshold you set for iou_threshold should be negative with this setting on.\n 'use_change_matching': False,\n\n # Uses the same network format as mask_proto_net, except this time it's for adding extra head layers before the final\n # prediction in prediction modules. If this is none, no extra layers will be added.\n 'extra_head_net': None,\n\n # What params should the final head layers have (the ones that predict box, confidence, and mask coeffs)\n 'head_layer_params': {'kernel_size': 3, 'padding': 1},\n\n # Add extra layers between the backbone and the network heads\n # The order is (bbox, conf, mask)\n 'extra_layers': (0, 0, 0),\n\n # During training, to match detections with gt, first compute the maximum gt IoU for each prior.\n # Then, any of those priors whose maximum overlap is over the positive threshold, mark as positive.\n # For any priors whose maximum is less than the negative iou threshold, mark them as negative.\n # The rest are neutral and not used in calculating the loss.\n 'positive_iou_threshold': 0.5,\n 'negative_iou_threshold': 0.5,\n\n # If less than 1, anchors treated as a negative that have a crowd iou over this threshold with\n # the crowd boxes will be treated as a neutral.\n 'crowd_iou_threshold': 1,\n\n # This is filled in at runtime by Yolact's __init__, so don't touch it\n 'mask_dim': None,\n\n # Input image size. If preserve_aspect_ratio is False, min_size is ignored.\n 'min_size': 200,\n 'max_size': 300,\n \n # Whether or not to do post processing on the cpu at test time\n 'force_cpu_nms': True,\n\n # Whether to use mask coefficient cosine similarity nms instead of bbox iou nms\n 'use_coeff_nms': False,\n\n # Whether or not to have a separate branch whose sole purpose is to act as the coefficients for coeff_diversity_loss\n # Remember to turn on coeff_diversity_loss, or these extra coefficients won't do anything!\n # To see their effect, also remember to turn on use_coeff_nms.\n 'use_instance_coeff': False,\n 'num_instance_coeffs': 64,\n\n # Whether or not to tie the mask loss / box loss to 0\n 'train_masks': True,\n 'train_boxes': True,\n # If enabled, the gt masks will be cropped using the gt bboxes instead of the predicted ones.\n # This speeds up training time considerably but results in much worse mAP at test time.\n 'use_gt_bboxes': False,\n\n # Whether or not to preserve aspect ratio when resizing the image.\n # If True, uses the faster r-cnn resizing scheme.\n # If False, all images are resized to max_size x max_size\n 'preserve_aspect_ratio': False,\n\n # Whether or not to use the prediction module (c) from DSSD\n 'use_prediction_module': False,\n\n # Whether or not to use the predicted coordinate scheme from Yolo v2\n 'use_yolo_regressors': False,\n \n # For training, bboxes are considered \"positive\" if their anchors have a 0.5 IoU overlap\n # or greater with a ground truth box. If this is true, instead of using the anchor boxes\n # for this IoU computation, the matching function will use the predicted bbox coordinates.\n # Don't turn this on if you're not using yolo regressors!\n 'use_prediction_matching': False,\n\n # A list of settings to apply after the specified iteration. Each element of the list should look like\n # (iteration, config_dict) where config_dict is a dictionary you'd pass into a config object's init.\n 'delayed_settings': [],\n\n # Use command-line arguments to set this.\n 'no_jit': False,\n\n 'backbone': None,\n 'name': 'base_config',\n})\n\n\n\n\n\n# ----------------------- YOLACT v1.0 CONFIGS ----------------------- #\n\nyolact_base_config = coco_base_config.copy({\n 'name': 'yolact_base',\n\n # Dataset stuff\n 'dataset': coco2017_dataset,\n 'num_classes': len(coco2017_dataset.class_names) + 1,\n\n # Image Size\n 'max_size': 550,\n \n # Training params\n 'lr_schedule': 'step',\n 'lr_steps': (280000, 600000, 700000, 750000),\n 'max_iter': 800000,\n\n 'flow': flow_base,\n \n # Backbone Settings\n 'backbone': resnet101_backbone.copy({\n 'selected_layers': list(range(1, 4)),\n 'use_pixel_scales': True,\n 'preapply_sqrt': False,\n 'use_square_anchors': True, # This is for backward compatability with a bug\n\n 'pred_aspect_ratios': [ [[1, 1/2, 2]] ]*5,\n 'pred_scales': [[24], [48], [96], [192], [384]],\n }),\n\n # FPN Settings\n 'fpn': fpn_base.copy({\n 'use_conv_downsample': True,\n 'num_downsample': 2,\n }),\n\n # Mask Settings\n 'mask_type': mask_type.lincomb,\n 'mask_alpha': 6.125,\n 'mask_proto_src': 0,\n 'mask_proto_net': [(256, 3, {'padding': 1})] * 3 + [(None, -2, {}), (256, 3, {'padding': 1})] + [(32, 1, {})],\n 'mask_proto_normalize_emulate_roi_pooling': True,\n\n # Other stuff\n 'share_prediction_module': True,\n 'extra_head_net': [(256, 3, {'padding': 1})],\n\n 'positive_iou_threshold': 0.5,\n 'negative_iou_threshold': 0.4,\n\n 'crowd_iou_threshold': 0.7,\n\n 'use_semantic_segmentation_loss': True,\n\n 'torch2trt_backbone': False,\n 'torch2trt_backbone_int8': False,\n 'torch2trt_protonet': False,\n 'torch2trt_protonet_int8': False,\n 'torch2trt_fpn': False,\n 'torch2trt_fpn_int8': False,\n 'torch2trt_prediction_module': False,\n 'torch2trt_prediction_module_int8': False,\n 'torch2trt_spa': False,\n 'torch2trt_spa_int8': False,\n 'torch2trt_flow_net': False,\n 'torch2trt_flow_net_int8': False,\n})\n\nyolact_edge_config = yolact_base_config.copy({\n 'name': 'yolact_edge',\n 'torch2trt_max_calibration_images': 100,\n 'torch2trt_backbone_int8': True,\n 'torch2trt_protonet_int8': True,\n 'torch2trt_fpn': True,\n 'torch2trt_prediction_module': True,\n})\n\nyolact_edge_fp16_config = yolact_edge_config.copy({\n 'name': 'yolact_edge_fp16',\n\n 'torch2trt_backbone': True,\n 'torch2trt_backbone_int8': False,\n 'torch2trt_protonet': True,\n 'torch2trt_protonet_int8': False,\n})\n\nyolact_edge_pytorch_config = yolact_edge_config.copy({\n 'name': 'yolact_edge_pytorch',\n\n 'torch2trt_backbone': False,\n 'torch2trt_backbone_int8': False,\n 'torch2trt_protonet': False,\n 'torch2trt_protonet_int8': False,\n 'torch2trt_fpn': False,\n 'torch2trt_fpn_int8': False,\n 'torch2trt_prediction_module': False,\n 'torch2trt_prediction_module_int8': False,\n})\n\nyolact_edge_mobilenetv2_config = yolact_edge_config.copy({\n 'name': 'yolact_edge_mobilenetv2',\n\n 'backbone': mobilenetv2_backbone\n})\n\nyolact_edge_mobilenetv2_pytorch_config = yolact_edge_config.copy({\n 'name': 'yolact_edge_mobilenetv2_pytorch',\n 'backbone': mobilenetv2_backbone,\n\n 'torch2trt_backbone': False,\n 'torch2trt_backbone_int8': False,\n 'torch2trt_protonet': False,\n 'torch2trt_protonet_int8': False,\n 'torch2trt_fpn': False,\n 'torch2trt_fpn_int8': False,\n 'torch2trt_prediction_module': False,\n 'torch2trt_prediction_module_int8': False\n})\n\nyolact_edge_vid_config = yolact_edge_config.copy({\n 'name': 'yolact_edge_vid',\n 'dataset': youtube_vis_dataset.copy({\n 'joint': 'coco',\n 'use_all_frames': True,\n 'images_per_video': 1,\n 'frame_offset_lb': 2,\n 'frame_offset_ub': 5,\n 'frame_offset_multiplier': 1,\n 'all_frame_direction': 'forward',\n }),\n\n 'torch2trt_spa': True,\n 'torch2trt_spa_int8': False,\n 'torch2trt_flow_net': False,\n 'torch2trt_flow_net_int8': True,\n\n 'joint_dataset': yolact_edge_config.dataset.copy({\n 'dataset_map': 'ytvis'\n }),\n 'lr': 2e-4,\n 'lr_warmup_init': 0,\n 'lr_schedule': 'cosine',\n 'max_iter': 200000,\n 'num_classes': len(youtube_vis_dataset.class_names) + 1,\n 'augment_expand': False,\n 'flow': flow_base.copy({\n 'encode_layers': [[1], [2], [4]],\n 'reduce_channels': [64],\n 'encode_channels': 64,\n 'num_groups': 1,\n 'use_shuffle_cat': False,\n 'base_backward': True,\n 'fine_tune_layers': 'flow_net,flow_net_pre_convs,spa,fpn_phase_2,proto_net,prediction_layers,semantic_seg_conv',\n 'selected_layers': [1, 2],\n 'warp_mode': 'flow',\n 'model': 'mini',\n 'use_pseudo_gt_flow_loss': False,\n 'feature_matching_loss': 'cosine',\n 'use_computed_P3': True,\n 'use_spa': True,\n 'fm_loss_loc': 'L+P',\n })\n})\n\nyolact_edge_vid_fp16_config = yolact_edge_vid_config.copy({\n 'name': 'yolact_edge_vid_fp16',\n\n 'torch2trt_backbone': True,\n 'torch2trt_backbone_int8': False,\n 'torch2trt_protonet': True,\n 'torch2trt_protonet_int8': False,\n 'torch2trt_flow_net': True,\n 'torch2trt_flow_net_int8': False,\n})\n\nyolact_edge_vid_pytorch_config = yolact_edge_vid_config.copy({\n 'name': 'yolact_edge_vid_pytorch',\n\n 'torch2trt_backbone': False,\n 'torch2trt_backbone_int8': False,\n 'torch2trt_protonet': False,\n 'torch2trt_protonet_int8': False,\n 'torch2trt_fpn': False,\n 'torch2trt_fpn_int8': False,\n 'torch2trt_prediction_module': False,\n 'torch2trt_prediction_module_int8': False,\n 'torch2trt_spa': False,\n 'torch2trt_spa_int8': False,\n 'torch2trt_flow_net': False,\n 'torch2trt_flow_net_int8': False,\n})\n\nyolact_edge_vid_minimal_config = yolact_edge_vid_config.copy({\n 'name': 'yolact_edge_vid_minimal',\n 'torch2trt_spa': False,\n 'flow': yolact_edge_vid_config.flow.copy({\n 'fine_tune_layers': 'flow_net,flow_net_pre_convs,fpn_phase_2,proto_net,prediction_layers,semantic_seg_conv',\n 'use_spa': False,\n 'feature_matching_loss': None,\n })\n})\n\nyolact_edge_vid_trainflow_config = yolact_edge_vid_config.copy({\n 'name': 'yolact_edge_vid_trainflow',\n 'dataset': flying_chairs_dataset,\n 'lr': 2e-4,\n 'max_iter': 400000,\n 'flow': yolact_edge_vid_config.flow.copy({\n 'train_flow': True,\n 'base_backward': False,\n 'fine_tune_layers': 'flow_net,flow_net_pre_convs'\n })\n})\n\nyolact_edge_youtubevis_config = yolact_edge_vid_config.copy({\n 'name': 'yolact_edge_youtubevis',\n 'dataset': yolact_edge_vid_config.dataset.copy({\n 'use_all_frames': False,\n 'images_per_video': 1,\n }),\n\n 'torch2trt_spa': False,\n 'torch2trt_flow_net_int8': False,\n\n 'lr': 5e-4,\n 'lr_schedule': 'cosine',\n 'max_iter': 500000,\n 'flow': yolact_edge_vid_config.flow.copy({\n 'warp_mode': 'none',\n 'fine_tune_layers': None,\n 'use_spa': False\n })\n})\n\nyolact_resnet50_config = yolact_base_config.copy({\n 'name': 'yolact_resnet50',\n\n 'backbone': resnet50_backbone.copy({\n 'selected_layers': list(range(1, 4)),\n\n 'pred_scales': yolact_base_config.backbone.pred_scales,\n 'pred_aspect_ratios': yolact_base_config.backbone.pred_aspect_ratios,\n 'use_pixel_scales': True,\n 'preapply_sqrt': False,\n 'use_square_anchors': True, # This is for backward compatability with a bug\n }),\n})\n\nyolact_resnet152_config = yolact_base_config.copy({\n 'name': 'yolact_resnet152',\n\n 'backbone': resnet152_backbone.copy({\n 'selected_layers': list(range(1, 4)),\n\n 'pred_scales': yolact_base_config.backbone.pred_scales,\n 'pred_aspect_ratios': yolact_base_config.backbone.pred_aspect_ratios,\n 'use_pixel_scales': True,\n 'preapply_sqrt': False,\n 'use_square_anchors': True, # This is for backward compatability with a bug\n }),\n})\n\nyolact_edge_resnet50_config = yolact_edge_config.copy({\n 'name': 'yolact_edge_resnet50',\n 'backbone': yolact_resnet50_config.backbone\n})\n\nyolact_edge_resnet50_pytorch_config = yolact_edge_config.copy({\n 'name': 'yolact_edge_resnet50',\n 'backbone': yolact_resnet50_config.backbone,\n\n 'torch2trt_backbone': False,\n 'torch2trt_backbone_int8': False,\n 'torch2trt_protonet': False,\n 'torch2trt_protonet_int8': False,\n 'torch2trt_fpn': False,\n 'torch2trt_fpn_int8': False,\n 'torch2trt_prediction_module': False,\n 'torch2trt_prediction_module_int8': False\n})\n\nyolact_edge_vid_resnet50_config = yolact_edge_vid_config.copy({\n 'name': 'yolact_edge_vid_resnet50',\n 'backbone': yolact_resnet50_config.backbone\n})\n\nyolact_edge_vid_trainflow_resnet50_config = yolact_edge_vid_trainflow_config.copy({\n 'name': 'yolact_edge_vid_trainflow_resnet50',\n 'backbone': yolact_resnet50_config.backbone\n})\n\nyolact_edge_youtubevis_resnet50_config = yolact_edge_youtubevis_config.copy({\n 'name': 'yolact_edge_youtubevis_resnet50',\n 'backbone': yolact_resnet50_config.backbone\n})\n\n# Default config\ncfg = yolact_edge_config.copy()\n\ndef set_cfg(config_name:str):\n \"\"\" Sets the active config. Works even if cfg is already imported! \"\"\"\n global cfg\n\n # Note this is not just an eval because I'm lazy, but also because it can\n # be used like ssd300_config.copy({'max_size': 400}) for extreme fine-tuning\n cfg.replace(eval(config_name))\n\ndef set_dataset(dataset_name:str):\n \"\"\" Sets the dataset of the current config. \"\"\"\n cfg.dataset = eval(dataset_name)\n \n"
] | [
[
"torch.nn.functional.softmax",
"torch.nn.functional.relu"
]
] |
damiandraxler/ghlestimator | [
"83f3929e22cba48e61ffd164c380c026ff6dddac"
] | [
"ghlestimator/ghlestimator.py"
] | [
"import numpy as np\r\nfrom scipy.optimize import minimize\r\n\r\ndef sgn(x):\r\n sig = np.sign(x)\r\n sig[sig == 0] = 1\r\n return sig\r\n\r\ndef _log(x): \r\n return sgn(x) * np.log(1 + np.abs(x))\r\n\r\ndef _loginv(x):\r\n return sgn(x) * (np.exp(np.abs(x)) - 1)\r\n\r\ndef _loginvp(x): \r\n return np.exp(np.abs(x))\r\n\r\ndef _generalized_huber_loss_and_gradient(w, X, y, epsilon, link_dict):\r\n \"\"\"Returns the generalized Huber loss and the gradient.\r\n Parameters\r\n ----------\r\n w : ndarray, shape (n_features,) or (n_features + 1,)\r\n Feature vector.\r\n w[:n_features] gives the coefficients if the intercept is not fit\r\n w[1:1+n_features] gives the coefficients and w[0] gives the intercept \r\n if the intercept is fit.\r\n X : ndarray, shape (n_samples, n_features)\r\n Input data.\r\n y : ndarray, shape (n_samples,)\r\n Target vector.\r\n epsilon : float\r\n Parameter of the generalized Huber estimator.\r\n link_dict : dictionary\r\n Dictionary containing a link function 'g', it's inverse function 'ginv'\r\n and the derivative of the latter 'ginvp'. All three are callables of \r\n the form fun(x) -> ndarray where both x and ndarray are 1-D arrays with\r\n shape (n_samples,). \r\n Returns\r\n -------\r\n loss : float\r\n Generalized Huber loss.\r\n gradient : ndarray, shape (len(w))\r\n Returns the derivative of the generalized Huber loss with respect to \r\n each coefficient and the intercept as a vector.\r\n \"\"\"\r\n n_features = X.shape[1]\r\n fit_intercept = (n_features + 1 == w.shape[0])\r\n \r\n if fit_intercept:\r\n X = np.append(np.ones(len(y)).reshape(-1,1),X,axis=1)\r\n\r\n yhat = np.dot(X,w)\r\n \r\n # Define the link function (g), it's inverse (ginv) and the derivative of \r\n # the latter (ginvp).\r\n g = link_dict['g']\r\n ginv = link_dict['ginv']\r\n ginvp = link_dict['ginvp']\r\n\r\n # Distinguish between values of abolut error smaller or larger than epsilon.\r\n # The distinction is done on the \"link scale\" defined by g(y). \r\n diff = g(y) - yhat\r\n absdiff = np.abs(diff)\r\n\r\n bool1_l = ((absdiff <= epsilon) & (diff < 0))\r\n bool1_r = ((absdiff <= epsilon) & (diff >= 0))\r\n bool2_l = ((absdiff > epsilon) & (diff < 0))\r\n bool2_r = ((absdiff > epsilon) & (diff >= 0))\r\n\r\n # Compute the gradient and the loss.\r\n grad = np.zeros(len(y))\r\n loss = np.zeros(len(y))\r\n\r\n # Calculation of terms repeatedly needed in the loss and gradient computation.\r\n A = np.zeros(len(y))\r\n Ap = np.zeros(len(y))\r\n B = np.zeros(len(y))\r\n\r\n A[bool1_l] = ginv(yhat[bool1_l] - epsilon) - ginv(yhat[bool1_l])\r\n A[bool1_r] = ginv(yhat[bool1_r] + epsilon) - ginv(yhat[bool1_r])\r\n Ap[bool1_l] = ginvp(yhat[bool1_l] - epsilon) - ginvp(yhat[bool1_l])\r\n Ap[bool1_r] = ginvp(yhat[bool1_r] + epsilon) - ginvp(yhat[bool1_r])\r\n\r\n A[bool2_l] = ginv(yhat[bool2_l] - epsilon) - ginv(yhat[bool2_l])\r\n A[bool2_r] = ginv(yhat[bool2_r] + epsilon) - ginv(yhat[bool2_r])\r\n Ap[bool2_l] = ginvp(yhat[bool2_l] - epsilon) - ginvp(yhat[bool2_l])\r\n Ap[bool2_r] = ginvp(yhat[bool2_r] + epsilon) - ginvp(yhat[bool2_r])\r\n\r\n B[bool1_l] = y[bool1_l] - ginv(g(y[bool1_l]) + epsilon)\r\n B[bool1_r] = y[bool1_r] - ginv(g(y[bool1_r]) - epsilon)\r\n \r\n B[bool2_l] = y[bool2_l] - ginv(g(y[bool2_l]) + epsilon)\r\n B[bool2_r] = y[bool2_r] - ginv(g(y[bool2_r]) - epsilon) \r\n\r\n # loss calculation \r\n loss[bool1_l] = (y[bool1_l]-ginv(yhat[bool1_l]))**2 * \\\r\n (1/np.abs(A[bool1_l]) + 1/np.abs(B[bool1_l]))\r\n loss[bool1_r] = (y[bool1_r]-ginv(yhat[bool1_r]))**2 * \\\r\n (1/np.abs(A[bool1_r]) + 1/np.abs(B[bool1_r]))\r\n \r\n loss[bool2_l] = 4*np.abs(y[bool2_l] - ginv(yhat[bool2_l])) - \\\r\n (np.abs(A[bool2_l]) + np.abs(B[bool2_l]))\r\n loss[bool2_r] = 4*np.abs(y[bool2_r] - ginv(yhat[bool2_r])) - \\\r\n (np.abs(A[bool2_r]) + np.abs(B[bool2_r]))\r\n \r\n loss = np.sum(loss)\r\n \r\n # gradient calculation \r\n grad[bool1_l] = -2*(y[bool1_l]-ginv(yhat[bool1_l]))*ginvp(yhat[bool1_l]) * \\\r\n (1/np.abs(A[bool1_l]) + 1/np.abs(B[bool1_l])) - \\\r\n (y[bool1_l]-ginv(yhat[bool1_l]))**2 * \\\r\n (1/(np.abs(A[bool1_l])**2))*sgn(A[bool1_l])*Ap[bool1_l]\r\n\r\n grad[bool1_r] = -2*(y[bool1_r]-ginv(yhat[bool1_r]))*ginvp(yhat[bool1_r]) * \\\r\n (1/np.abs(A[bool1_r]) + 1/np.abs(B[bool1_r])) - \\\r\n (y[bool1_r]-ginv(yhat[bool1_r]))**2 * \\\r\n (1/(np.abs(A[bool1_r])**2))*sgn(A[bool1_r])*Ap[bool1_r] \r\n\r\n grad[bool2_l] = -4 * sgn(y[bool2_l] - ginv(yhat[bool2_l])) * ginvp(\r\n yhat[bool2_l]) - sgn(A[bool2_l]) * Ap[bool2_l]\r\n\r\n grad[bool2_r] = -4 * sgn(y[bool2_r] - ginv(yhat[bool2_r])) * ginvp(\r\n yhat[bool2_r]) - sgn(A[bool2_r]) * Ap[bool2_r] \r\n \r\n grad = np.dot(grad.reshape(1,-1),X)\r\n\r\n del A ,Ap ,B ,bool1_l ,bool1_r ,bool2_l ,bool2_r \r\n \r\n return loss , grad\r\n\r\nclass GeneralizedHuberRegressor():\r\n \"\"\"Linear regression model that is robust to outliers and allows for a \r\n link function.\r\n The Generalized Huber Regressor optimizes a term proportional to \r\n ``(y - ginv(X'w/scale))**2`` for the samples where \r\n ``|g(y) - (X'w/scale)| <= epsilon`` and a term proportional to \r\n `|y - ginv(X'w/scale)|`` for the samples where \r\n ``|g(y) - (X'w/scale)| > epsilon``, where w is to be optimized. \r\n The parameter scale simply serves as a preconditioner to achieve numerical\r\n stability. Note that this does not take into account the fact that \r\n the different features of X may be of different scales.\r\n Parameters\r\n ----------\r\n epsilon : float, default 1.0\r\n The parameter epsilon controls the number of samples that should be\r\n classified as outliers. \r\n max_iter : int, default 100\r\n Maximum number of iterations that\r\n ``scipy.optimize.minimize(method=\"L-BFGS-B\")`` should run for.\r\n fit_intercept : bool, default True\r\n Whether or not to fit the intercept.\r\n tol : float, default 1e-5\r\n The iteration will stop when\r\n ``max{|proj g_i | i = 1, ..., n}`` <= ``tol``\r\n where pg_i is the i-th component of the projected gradient.\r\n scale : float, default 10.0\r\n Preconditioner for better numerical stability.\r\n link_dict : dictionary, default {'g':_log,'ginv':_loginv,'ginvp':_loginvp} \r\n Attributes\r\n ----------\r\n coef_ : array, shape (n_features,)\r\n Features got by optimizing the generalized Huber loss.\r\n intercept_ : float\r\n Bias.\r\n n_iter_ : int\r\n Number of iterations that\r\n ``scipy.optimize.minimize(method=\"L-BFGS-B\")`` has run for.\r\n .. versionchanged:: 0.20\r\n In SciPy <= 1.0.0 the number of lbfgs iterations may exceed\r\n ``max_iter``. ``n_iter_`` will now report at most ``max_iter``.\r\n Examples\r\n --------\r\n >>> import numpy as np\r\n >>> from sklearn.linear_model import HuberRegressor\r\n >>> from sklearn.datasets import make_regression\r\n >>> rng = np.random.RandomState(0)\r\n >>> X, y, coef = make_regression(\r\n ... n_samples=200, n_features=2, noise=4.0, coef=True, random_state=0)\r\n >>> X[:4] = rng.uniform(10, 20, (4, 2))\r\n >>> y[:4] = rng.uniform(10, 20, 4)\r\n >>> ghuber = GeneralizedHuberRegressor().fit(X, y)\r\n >>> ghuber.score(X, y)\r\n 0.094...\r\n >>> ghuber.predict(X[:1,])\r\n array([38.0325...])\r\n >>> huber = HuberRegressor().fit(X, y)\r\n >>> huber.score(X, y)\r\n -7.2846...\r\n >>> huber.predict(X[:1,])\r\n array([806.7200...])\r\n >>> print(\"True coefficients:\", coef)\r\n True coefficients: [20.4923... 34.1698...]\r\n >>> print(\"Generalized Huber coefficients:\", ghuber.coef_)\r\n Generalized Huber coefficients: [0.0468... 0.3324...]\r\n >>> print(\"Huber Regression coefficients:\", huber.coef_)\r\n Huber Regression coefficients: [17.7906... 31.0106...]\r\n References\r\n ----------\r\n .. [1] Damian Draxler, \r\n https://towardsdatascience.com/generalized-huber-regression-505afaff24c\r\n \"\"\" \r\n def __init__(self,epsilon=1.0,max_iter=100,tol=1e-5, scale=10,\r\n fit_intercept=True, link_dict={'g':_log,'ginv':_loginv,'ginvp':_loginvp}):\r\n self.epsilon = epsilon\r\n self.max_iter = max_iter\r\n self.tol = tol\r\n self.scale = scale \r\n self.fit_intercept = fit_intercept\r\n self.link_dict = link_dict\r\n\r\n def fit(self, X, y):\r\n \r\n if self.epsilon < 0.0:\r\n raise ValueError(\r\n \"epsilon should be greater than or equal to 0.0, got %f\"\r\n % self.epsilon)\r\n \r\n if len(X.shape)==1:\r\n raise ValueError(\"Expected 2D array, got 1D array instead:%s \\n\" \r\n \"Reshape your data either using array.reshape(-1, 1) if your \"\r\n \"data has a single feature or array.reshape(1, -1) if it \" \r\n \"contains a single sample.\"% X)\r\n \r\n if len(y.shape)==2:\r\n print(\"DataConversionWarning: A column-vector y was passed when \"\r\n \"a 1d array was expected. Please change the shape of y to \"\r\n \"(n_samples, ), for example using ravel().\")\r\n y = y.ravel()\r\n \r\n if self.fit_intercept:\r\n parameters = np.zeros(X.shape[1] + 1)\r\n else:\r\n parameters = np.zeros(X.shape[1])\r\n \r\n opt_res = minimize(\r\n _generalized_huber_loss_and_gradient,parameters, method=\"L-BFGS-B\", jac=True,\r\n args=(X/self.scale, y, self.epsilon, self.link_dict),\r\n options={\"maxiter\": self.max_iter, \"gtol\": self.tol, \"iprint\": -1})\r\n\r\n parameters = opt_res.x\r\n \r\n if opt_res.status == 2:\r\n raise ValueError(\"HuberRegressor convergence failed:\"\r\n \" l-BFGS-b solver terminated with %s\"\r\n % opt_res.message)\r\n \r\n self.n_iter_ = opt_res.nit \r\n if self.fit_intercept:\r\n self.intercept_ = parameters[0]\r\n self.coef_ = parameters[1:1+X.shape[1]]/self.scale \r\n else: \r\n self.intercept_ = 0.0 \r\n self.coef_ = parameters[0:X.shape[1]]/self.scale\r\n return self\r\n \r\n def predict(self, X, y=None):\r\n return self.link_dict['ginv'](np.dot(X,self.coef_) + self.intercept_)\r\n\r\n def score(self, X, y):\r\n if len(y.shape)==2:\r\n y = y.ravel() \r\n y_pred = self.predict(X,y)\r\n u = ((y - y_pred)**2).sum()\r\n v = ((y - y.mean())**2).sum()\r\n return (1 - u/v)"
] | [
[
"numpy.dot",
"numpy.abs",
"numpy.sign",
"scipy.optimize.minimize",
"numpy.zeros",
"numpy.sum"
]
] |
thomasgilgenast/hic3defdr | [
"7498ac468ccc21fa530d584944c1b12c73926755"
] | [
"hic3defdr/plotting/heatmap.py"
] | [
"import matplotlib.pyplot as plt\n\nfrom lib5c.util.plotting import plotter\n\n\n@plotter\ndef plot_heatmap(matrix, cmap='Reds', vmin=0, vmax=100, despine=False,\n **kwargs):\n \"\"\"\n Plots a simple heatmap of a dense matrix.\n\n Parameters\n ----------\n matrix : np.ndarray\n The dense matrix to visualize.\n cmap : matplotlib colormap\n The colormap to use for the heatmap.\n vmin, vmax : float\n The vmin and vmax to use for the heatmap colorscale.\n kwargs : kwargs\n Typical plotter kwargs.\n\n Returns\n -------\n pyplot axis\n The axis plotted on.\n \"\"\"\n plt.imshow(matrix, cmap=cmap, vmin=vmin, vmax=vmax, interpolation='none')\n plt.xticks([])\n plt.yticks([])\n"
] | [
[
"matplotlib.pyplot.imshow",
"matplotlib.pyplot.yticks",
"matplotlib.pyplot.xticks"
]
] |
mGalarnyk/Blueprints | [
"02c46234cad36e159ea26d2fcb864454ca229cc2"
] | [
"Object Detection/Object Detection Retrain/val.py"
] | [
"# YOLOv5 🚀 by Ultralytics, GPL-3.0 license\n\"\"\"\nValidate a trained YOLOv5 model accuracy on a custom dataset\n\nUsage:\n $ python path/to/val.py --weights yolov5s.pt --data coco128.yaml --img 640\n\nUsage - formats:\n $ python path/to/val.py --weights yolov5s.pt # PyTorch\n yolov5s.torchscript # TorchScript\n yolov5s.onnx # ONNX Runtime or OpenCV DNN with --dnn\n yolov5s.xml # OpenVINO\n yolov5s.engine # TensorRT\n yolov5s.mlmodel # CoreML (MacOS-only)\n yolov5s_saved_model # TensorFlow SavedModel\n yolov5s.pb # TensorFlow GraphDef\n yolov5s.tflite # TensorFlow Lite\n yolov5s_edgetpu.tflite # TensorFlow Edge TPU\n\"\"\"\n\nfrom utils.torch_utils import select_device, time_sync\nfrom utils.plots import output_to_target, plot_images, plot_val_study\nfrom utils.metrics import ConfusionMatrix, ap_per_class\nfrom utils.general import (LOGGER, box_iou, check_dataset, check_img_size, check_requirements, check_yaml,\n coco80_to_coco91_class, colorstr, increment_path, non_max_suppression, print_args,\n scale_coords, xywh2xyxy, xyxy2xywh)\nfrom utils.datasets import create_dataloader\nfrom utils.callbacks import Callbacks\nfrom models.common import DetectMultiBackend\nimport argparse\nimport json\nimport os\nimport sys\nfrom pathlib import Path\nfrom threading import Thread\nimport pandas as pd\nimport numpy as np\nimport torch\nfrom tqdm import tqdm\n\nFILE = Path(__file__).resolve()\nROOT = FILE.parents[0] # YOLOv5 root directory\nif str(ROOT) not in sys.path:\n sys.path.append(str(ROOT)) # add ROOT to PATH\nROOT = Path(os.path.relpath(ROOT, Path.cwd())) # relative\n\n\ndef save_one_txt(predn, save_conf, shape, file):\n # Save one txt result\n gn = torch.tensor(shape)[[1, 0, 1, 0]] # normalization gain whwh\n for *xyxy, conf, cls in predn.tolist():\n xywh = (xyxy2xywh(torch.tensor(xyxy).view(1, 4)) /\n gn).view(-1).tolist() # normalized xywh\n line = (cls, *xywh, conf) if save_conf else (cls, *xywh) # label format\n with open(file, 'a') as f:\n f.write(('%g ' * len(line)).rstrip() % line + '\\n')\n\n\ndef save_one_json(predn, jdict, path, class_map):\n # Save one JSON result {\"image_id\": 42, \"category_id\": 18, \"bbox\": [258.15, 41.29, 348.26, 243.78], \"score\": 0.236}\n image_id = int(path.stem) if path.stem.isnumeric() else path.stem\n box = xyxy2xywh(predn[:, :4]) # xywh\n box[:, :2] -= box[:, 2:] / 2 # xy center to top-left corner\n for p, b in zip(predn.tolist(), box.tolist()):\n jdict.append({'image_id': image_id,\n 'category_id': class_map[int(p[5])],\n 'bbox': [round(x, 3) for x in b],\n 'score': round(p[4], 5)})\n\n\ndef process_batch(detections, labels, iouv):\n \"\"\"\n Return correct predictions matrix. Both sets of boxes are in (x1, y1, x2, y2) format.\n Arguments:\n detections (Array[N, 6]), x1, y1, x2, y2, conf, class\n labels (Array[M, 5]), class, x1, y1, x2, y2\n Returns:\n correct (Array[N, 10]), for 10 IoU levels\n \"\"\"\n correct = torch.zeros(\n detections.shape[0], iouv.shape[0], dtype=torch.bool, device=iouv.device)\n iou = box_iou(labels[:, 1:], detections[:, :4])\n # IoU above threshold and classes match\n x = torch.where((iou >= iouv[0]) & (labels[:, 0:1] == detections[:, 5]))\n if x[0].shape[0]:\n matches = torch.cat((torch.stack(x, 1), iou[x[0], x[1]][:, None]), 1).cpu(\n ).numpy() # [label, detection, iou]\n if x[0].shape[0] > 1:\n matches = matches[matches[:, 2].argsort()[::-1]]\n matches = matches[np.unique(matches[:, 1], return_index=True)[1]]\n # matches = matches[matches[:, 2].argsort()[::-1]]\n matches = matches[np.unique(matches[:, 0], return_index=True)[1]]\n matches = torch.Tensor(matches).to(iouv.device)\n correct[matches[:, 1].long()] = matches[:, 2:3] >= iouv\n return correct\n\n\[email protected]_grad()\ndef run(locationcsv,\n data,\n weights=None, # model.pt path(s)\n batch_size=32, # batch size\n imgsz=640, # inference size (pixels)\n conf_thres=0.001, # confidence threshold\n iou_thres=0.6, # NMS IoU threshold\n task='val', # train, val, test, speed or study\n device='', # cuda device, i.e. 0 or 0,1,2,3 or cpu\n workers=8, # max dataloader workers (per RANK in DDP mode)\n single_cls=False, # treat as single-class dataset\n augment=False, # augmented inference\n verbose=False, # verbose output\n save_txt=False, # save results to *.txt\n save_hybrid=False, # save label+prediction hybrid results to *.txt\n save_conf=False, # save confidences in --save-txt labels\n save_json=False, # save a COCO-JSON results file\n project=ROOT / 'runs/val', # save to project/name\n name='exp', # save to project/name\n exist_ok=False, # existing project/name ok, do not increment\n half=True, # use FP16 half-precision inference\n dnn=False, # use OpenCV DNN for ONNX inference\n model=None,\n dataloader=None,\n save_dir=Path(''),\n plots=True,\n callbacks=Callbacks(),\n compute_loss=None,\n ):\n # Initialize/load model and set device\n training = model is not None\n if training: # called by train.py\n # get model device, PyTorch model\n device, pt, jit, engine = next(\n model.parameters()).device, True, False, False\n\n half &= device.type != 'cpu' # half precision only supported on CUDA\n model.half() if half else model.float()\n else: # called directly\n device = select_device(device, batch_size=batch_size)\n\n # Directories\n save_dir = increment_path(\n Path(project) / name, exist_ok=exist_ok) # increment run\n (save_dir / 'labels' if save_txt else save_dir).mkdir(parents=True,\n exist_ok=True) # make dir\n\n # Load model\n model = DetectMultiBackend(weights, device=device, dnn=dnn, data=data)\n stride, pt, jit, onnx, engine = model.stride, model.pt, model.jit, model.onnx, model.engine\n imgsz = check_img_size(imgsz, s=stride) # check image size\n # FP16 supported on limited backends with CUDA\n half &= (pt or jit or onnx or engine) and device.type != 'cpu'\n if pt or jit:\n model.model.half() if half else model.model.float()\n elif engine:\n batch_size = model.batch_size\n else:\n half = False\n batch_size = 1 # export.py models default to batch-size 1\n device = torch.device('cpu')\n LOGGER.info(\n f'Forcing --batch-size 1 square inference shape(1,3,{imgsz},{imgsz}) for non-PyTorch backends')\n\n # Data\n data = check_dataset(data) # check\n\n # Configure\n model.eval()\n is_coco = isinstance(data.get('val'), str) and data['val'].endswith(\n 'coco/val2017.txt') # COCO dataset\n nc = 1 if single_cls else int(data['nc']) # number of classes\n iouv = torch.linspace(0.5, 0.95, 10).to(\n device) # iou vector for [email protected]:0.95\n niou = iouv.numel()\n\n # Dataloader\n if not training:\n model.warmup(imgsz=(1, 3, imgsz, imgsz), half=half) # warmup\n pad = 0.0 if task == 'speed' else 0.5\n # path to train/val/test images\n task = task if task in ('train', 'val', 'test') else 'val'\n dataloader = create_dataloader(data[task], imgsz, batch_size, stride, single_cls, pad=pad, rect=pt,\n workers=workers, prefix=colorstr(f'{task}: '))[0]\n\n seen = 0\n confusion_matrix = ConfusionMatrix(nc=nc)\n names = {k: v for k, v in enumerate(\n model.names if hasattr(model, 'names') else model.module.names)}\n class_map = coco80_to_coco91_class() if is_coco else list(range(1000))\n s = ('%20s' + '%11s' * 6) % ('Class', 'Images',\n 'Labels', 'P', 'R', '[email protected]', '[email protected]:.95')\n dt, p, r, f1, mp, mr, map50, map = [\n 0.0, 0.0, 0.0], 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0\n loss = torch.zeros(3, device=device)\n jdict, stats, ap, ap_class = [], [], [], []\n pbar = tqdm(dataloader, desc=s,\n bar_format='{l_bar}{bar:10}{r_bar}{bar:-10b}') # progress bar\n for batch_i, (im, targets, paths, shapes) in enumerate(pbar):\n t1 = time_sync()\n if pt or jit or engine:\n im = im.to(device, non_blocking=True)\n targets = targets.to(device)\n im = im.half() if half else im.float() # uint8 to fp16/32\n im /= 255 # 0 - 255 to 0.0 - 1.0\n nb, _, height, width = im.shape # batch size, channels, height, width\n t2 = time_sync()\n dt[0] += t2 - t1\n\n # Inference\n out, train_out = model(im) if training else model(\n im, augment=augment, val=True) # inference, loss outputs\n dt[1] += time_sync() - t2\n\n # Loss\n if compute_loss:\n loss += compute_loss([x.float()\n for x in train_out], targets)[1] # box, obj, cls\n\n # NMS\n # to pixels\n targets[:, 2:] *= torch.Tensor([width,\n height, width, height]).to(device)\n lb = [targets[targets[:, 0] == i, 1:]\n for i in range(nb)] if save_hybrid else [] # for autolabelling\n t3 = time_sync()\n out = non_max_suppression(\n out, conf_thres, iou_thres, labels=lb, multi_label=True, agnostic=single_cls)\n dt[2] += time_sync() - t3\n\n # Metrics\n for si, pred in enumerate(out):\n labels = targets[targets[:, 0] == si, 1:]\n nl = len(labels)\n tcls = labels[:, 0].tolist() if nl else [] # target class\n path, shape = Path(paths[si]), shapes[si][0]\n seen += 1\n\n if len(pred) == 0:\n if nl:\n stats.append(\n (torch.zeros(0, niou, dtype=torch.bool), torch.Tensor(), torch.Tensor(), tcls))\n continue\n\n # Predictions\n if single_cls:\n pred[:, 5] = 0\n predn = pred.clone()\n scale_coords(im[si].shape[1:], predn[:, :4], shape,\n shapes[si][1]) # native-space pred\n\n # Evaluate\n if nl:\n tbox = xywh2xyxy(labels[:, 1:5]) # target boxes\n scale_coords(im[si].shape[1:], tbox, shape,\n shapes[si][1]) # native-space labels\n # native-space labels\n labelsn = torch.cat((labels[:, 0:1], tbox), 1)\n correct = process_batch(predn, labelsn, iouv)\n if plots:\n confusion_matrix.process_batch(predn, labelsn)\n else:\n correct = torch.zeros(pred.shape[0], niou, dtype=torch.bool)\n # (correct, conf, pcls, tcls)\n stats.append(\n (correct.cpu(), pred[:, 4].cpu(), pred[:, 5].cpu(), tcls))\n\n # Save/log\n if save_txt:\n save_one_txt(predn, save_conf, shape,\n file=save_dir / 'labels' / (path.stem + '.txt'))\n if save_json:\n # append to COCO-JSON dictionary\n save_one_json(predn, jdict, path, class_map)\n callbacks.run('on_val_image_end', pred, predn, path, names, im[si])\n\n # Plot images\n if plots and batch_i < 3:\n f = save_dir / f'val_batch{batch_i}_labels.jpg' # labels\n Thread(target=plot_images, args=(im, targets,\n paths, f, names), daemon=True).start()\n f = save_dir / f'val_batch{batch_i}_pred.jpg' # predictions\n Thread(target=plot_images, args=(im, output_to_target(\n out), paths, f, names), daemon=True).start()\n\n # Compute metrics\n stats = [np.concatenate(x, 0) for x in zip(*stats)] # to numpy\n if len(stats) and stats[0].any():\n tp, fp, p, r, f1, ap, ap_class = ap_per_class(\n *stats, plot=plots, save_dir=save_dir, names=names)\n ap50, ap = ap[:, 0], ap.mean(1) # [email protected], [email protected]:0.95\n mp, mr, map50, map = p.mean(), r.mean(), ap50.mean(), ap.mean()\n # number of targets per class\n nt = np.bincount(stats[3].astype(np.int64), minlength=nc)\n else:\n nt = torch.zeros(1)\n\n # Print results\n pf = '%20s' + '%11i' * 2 + '%11.3g' * 4 # print format\n datadict = {'classes': [], 'Images Overall': [], 'Labels': [],\n 'Precision': [], 'Recall': [], '[email protected]': [], '[email protected]:.95': []}\n LOGGER.info(pf % ('all', seen, nt.sum(), mp, mr, map50, map))\n datadict['classes'].append(\"all\")\n datadict['Images Overall'].append(seen)\n datadict['Labels'].append(nt.sum())\n datadict['Precision'].append(round(mp, 3))\n datadict['Recall'].append(round(mr, 3))\n datadict['[email protected]'].append(round(map50, 3))\n datadict['[email protected]:.95'].append(round(map, 3))\n # Print results per class\n if (verbose or (nc < 50 and not training)) and nc > 1 and len(stats):\n\n for i, c in enumerate(ap_class):\n LOGGER.info(pf % (names[c], seen, nt[c],\n p[i], r[i], ap50[i], ap[i]))\n datadict['classes'].append(names[c])\n datadict['Images Overall'].append(seen)\n datadict['Labels'].append(nt[c])\n datadict['Precision'].append(round(p[i], 3))\n datadict['Recall'].append(round(r[i], 3))\n datadict['[email protected]'].append(round(ap50[i], 3))\n datadict['[email protected]:.95'].append(round(ap[i], 3))\n df = pd.DataFrame(datadict)\n df.to_csv(\"../../cnvrg/\"+locationcsv, index=False)\n # Save csv results\n # Print speeds\n t = tuple(x / seen * 1E3 for x in dt) # speeds per image\n if not training:\n shape = (batch_size, 3, imgsz, imgsz)\n LOGGER.info(\n f'Speed: %.1fms pre-process, %.1fms inference, %.1fms NMS per image at shape {shape}' % t)\n\n # Plots\n if plots:\n confusion_matrix.plot(save_dir=save_dir, names=list(names.values()))\n callbacks.run('on_val_end')\n\n # Save JSON\n if save_json and len(jdict):\n w = Path(weights[0] if isinstance(\n weights, list) else weights).stem if weights is not None else '' # weights\n anno_json = str(Path(data.get('path', '../coco')) /\n 'annotations/instances_val2017.json') # annotations json\n pred_json = str(save_dir / f\"{w}_predictions.json\") # predictions json\n LOGGER.info(f'\\nEvaluating pycocotools mAP... saving {pred_json}...')\n with open(pred_json, 'w') as f:\n json.dump(jdict, f)\n\n try: # https://github.com/cocodataset/cocoapi/blob/master/PythonAPI/pycocoEvalDemo.ipynb\n check_requirements(['pycocotools'])\n from pycocotools.coco import COCO\n from pycocotools.cocoeval import COCOeval\n\n anno = COCO(anno_json) # init annotations api\n pred = anno.loadRes(pred_json) # init predictions api\n eval = COCOeval(anno, pred, 'bbox')\n if is_coco:\n # image IDs to evaluate\n eval.params.imgIds = [int(Path(x).stem)\n for x in dataloader.dataset.img_files]\n eval.evaluate()\n eval.accumulate()\n eval.summarize()\n # update results ([email protected]:0.95, [email protected])\n map, map50 = eval.stats[:2]\n except Exception as e:\n LOGGER.info(f'pycocotools unable to run: {e}')\n\n # Return results\n model.float() # for training\n if not training:\n s = f\"\\n{len(list(save_dir.glob('labels/*.txt')))} labels saved to {save_dir / 'labels'}\" if save_txt else ''\n LOGGER.info(f\"Results saved to {colorstr('bold', save_dir)}{s}\")\n maps = np.zeros(nc) + map\n for i, c in enumerate(ap_class):\n maps[c] = ap[i]\n return (mp, mr, map50, map, *(loss.cpu() / len(dataloader)).tolist()), maps, t\n\n\ndef parse_opt():\n parser = argparse.ArgumentParser()\n parser.add_argument('--data', type=str, default=ROOT /\n 'data/coco128.yaml', help='dataset.yaml path')\n parser.add_argument('--weights', nargs='+', type=str,\n default=ROOT / 'yolov5s.pt', help='model.pt path(s)')\n parser.add_argument('--batch-size', type=int,\n default=32, help='batch size')\n parser.add_argument('--imgsz', '--img', '--img-size',\n type=int, default=640, help='inference size (pixels)')\n parser.add_argument('--conf-thres', type=float,\n default=0.001, help='confidence threshold')\n parser.add_argument('--iou-thres', type=float,\n default=0.6, help='NMS IoU threshold')\n parser.add_argument('--task', default='val',\n help='train, val, test, speed or study')\n parser.add_argument('--device', default='',\n help='cuda device, i.e. 0 or 0,1,2,3 or cpu')\n parser.add_argument('--workers', type=int, default=8,\n help='max dataloader workers (per RANK in DDP mode)')\n parser.add_argument('--single-cls', action='store_true',\n help='treat as single-class dataset')\n parser.add_argument('--augment', action='store_true',\n help='augmented inference')\n parser.add_argument('--verbose', action='store_true',\n help='report mAP by class')\n parser.add_argument('--save-txt', action='store_true',\n help='save results to *.txt')\n parser.add_argument('--save-hybrid', action='store_true',\n help='save label+prediction hybrid results to *.txt')\n parser.add_argument('--save-conf', action='store_true',\n help='save confidences in --save-txt labels')\n parser.add_argument('--save-json', action='store_true',\n help='save a COCO-JSON results file')\n parser.add_argument('--project', default=ROOT /\n 'runs/val', help='save to project/name')\n parser.add_argument('--name', default='exp', help='save to project/name')\n parser.add_argument('--exist-ok', action='store_true',\n help='existing project/name ok, do not increment')\n parser.add_argument('--half', action='store_true',\n help='use FP16 half-precision inference')\n parser.add_argument('--dnn', action='store_true',\n help='use OpenCV DNN for ONNX inference')\n opt = parser.parse_args()\n opt.data = check_yaml(opt.data) # check YAML\n opt.save_json |= opt.data.endswith('coco.yaml')\n opt.save_txt |= opt.save_hybrid\n print_args(FILE.stem, opt)\n return opt\n\n\ndef main(opt):\n check_requirements(requirements=ROOT / 'requirements.txt',\n exclude=('tensorboard', 'thop'))\n\n if opt.task in ('train', 'val', 'test'): # run normally\n if opt.conf_thres > 0.001: # https://github.com/ultralytics/yolov5/issues/1466\n LOGGER.info(\n f'WARNING: confidence threshold {opt.conf_thres} >> 0.001 will produce invalid mAP values.')\n run(**vars(opt))\n\n else:\n weights = opt.weights if isinstance(\n opt.weights, list) else [opt.weights]\n opt.half = True # FP16 for fastest results\n if opt.task == 'speed': # speed benchmarks\n # python val.py --task speed --data coco.yaml --batch 1 --weights yolov5n.pt yolov5s.pt...\n opt.conf_thres, opt.iou_thres, opt.save_json = 0.25, 0.45, False\n for opt.weights in weights:\n run(**vars(opt), plots=False)\n\n elif opt.task == 'study': # speed vs mAP benchmarks\n # python val.py --task study --data coco.yaml --iou 0.7 --weights yolov5n.pt yolov5s.pt...\n for opt.weights in weights:\n # filename to save to\n f = f'study_{Path(opt.data).stem}_{Path(opt.weights).stem}.txt'\n # x axis (image sizes), y axis\n x, y = list(range(256, 1536 + 128, 128)), []\n for opt.imgsz in x: # img-size\n LOGGER.info(f'\\nRunning {f} --imgsz {opt.imgsz}...')\n r, _, t = run(**vars(opt), plots=False)\n y.append(r + t) # results and times\n np.savetxt(f, y, fmt='%10.4g') # save\n os.system('zip -r study.zip study_*.txt')\n plot_val_study(x=x) # plot\n\n\nif __name__ == \"__main__\":\n opt = parse_opt()\n main(opt)\n"
] | [
[
"torch.linspace",
"torch.Tensor",
"torch.zeros",
"torch.cat",
"numpy.unique",
"torch.stack",
"pandas.DataFrame",
"torch.tensor",
"numpy.concatenate",
"torch.no_grad",
"torch.where",
"torch.device",
"numpy.zeros",
"numpy.savetxt"
]
] |
BreakingBytes/simkit | [
"c247b6ecf46d727703c03cb0d987e35fd054eaa6"
] | [
"examples/PVPower/pvpower/formulas/irradiance.py"
] | [
"# -*- coding: utf-8 -*-\n\n\"\"\"\nThis module contains formulas for calculating PV power.\n\"\"\"\n\nimport pvlib\nimport pandas as pd\n\n\ndef f_linketurbidity(times, latitude, longitude):\n times = pd.DatetimeIndex(times)\n # latitude and longitude must be scalar or else linke turbidity lookup fails\n latitude, longitude = latitude.item(), longitude.item()\n tl = pvlib.clearsky.lookup_linke_turbidity(times, latitude, longitude)\n return tl.values.reshape(1, -1)\n\n\ndef f_clearsky(solar_zenith, am_abs, tl, dni_extra, altitude):\n cs = pvlib.clearsky.ineichen(solar_zenith, am_abs, tl, dni_extra=dni_extra,\n altitude=altitude)\n return cs['dni'], cs['ghi'], cs['dhi']\n\n\ndef f_solpos(times, latitude, longitude):\n \"\"\"\n Calculate solar position for lat/long at times.\n\n :param times: Python :class:`datetime.datetime` object.\n :type times: list\n :param latitude: latitude [degrees]\n :type latitude: float\n :param longitude: longitude [degrees]\n :type longitude: float\n :returns: apparent zenith, azimuth\n \"\"\"\n # pvlib converts Python datetime objects to pandas DatetimeIndex\n solpos = pvlib.solarposition.get_solarposition(times, latitude, longitude)\n # solpos is a pandas DataFrame, so unpack the desired values\n # return shape is (2, NOBS), so unc_wrapper sees 2 dependent variables\n return solpos['apparent_zenith'].values, solpos['azimuth'].values\n\n\ndef f_dni_extra(times):\n times = pd.DatetimeIndex(times)\n return pvlib.irradiance.get_extra_radiation(times)\n\n\ndef f_airmass(solar_zenith):\n # resize output so uncertainty wrapper can determine observations\n return pvlib.atmosphere.get_relative_airmass(solar_zenith).reshape(1, -1)\n\n\ndef f_pressure(altitude):\n return pvlib.atmosphere.alt2pres(altitude)\n\n\ndef f_am_abs(airmass, pressure):\n am = airmass.squeeze()\n return pvlib.atmosphere.get_absolute_airmass(am, pressure).reshape(1, -1)\n\n\ndef f_total_irrad(times, surface_tilt, surface_azimuth, solar_zenith,\n solar_azimuth, dni, ghi, dhi, dni_extra, am_abs,\n model='haydavies'):\n \"\"\"\n Calculate total irradiance\n\n :param times: timestamps\n :param surface_tilt: panel tilt from horizontal [deg]\n :param surface_azimuth: panel azimuth from north [deg]\n :param solar_zenith: refracted solar zenith angle [deg]\n :param solar_azimuth: solar azimuth [deg]\n :param dni: direct normal irradiance [W/m**2]\n :param ghi: global horizonal irradiance [W/m**2]\n :param dhi: diffuse horizontal irradiance [W/m**2]\n :param dni_extra: extraterrestrial irradiance [W/m**2]\n :param am_abs: absolute airmass [dimensionless]\n :param model: irradiance model name, default is ``'haydavies'``\n :type model: str\n :return: global, direct and diffuse plane of array irradiance [W/m**2]\n \"\"\"\n am_abs = am_abs.squeeze()\n # make a DataFrame for time series arguments\n df = pd.DataFrame(\n {'solar_zenith': solar_zenith, 'solar_azimuth': solar_azimuth,\n 'dni': dni, 'ghi': ghi, 'dhi': dhi, 'dni_extra': dni_extra,\n 'am_abs': am_abs},\n index=times\n )\n # calculate total irradiance using PVLIB\n total_irrad = pvlib.irradiance.get_total_irradiance(\n surface_tilt, surface_azimuth, df['solar_zenith'], df['solar_azimuth'],\n df['dni'], df['ghi'], df['dhi'], dni_extra=df['dni_extra'],\n airmass=df['am_abs'], model=model\n ).fillna(0.0)\n # convert to ndarrays\n poa_global = total_irrad['poa_global'].values\n poa_direct = total_irrad['poa_direct'].values\n poa_diffuse = total_irrad['poa_diffuse'].values\n return poa_global, poa_direct, poa_diffuse\n"
] | [
[
"pandas.DatetimeIndex",
"pandas.DataFrame"
]
] |
stefantaubert/textgrid-ipa | [
"7227e3afa7d711a64f0d911e33b7ce822087f23f"
] | [
"src/textgrid_tools/app/main.py"
] | [
"import re\nfrom logging import getLogger\nfrom pathlib import Path\nfrom shutil import copy, rmtree\nfrom typing import Optional\n\nfrom scipy.io.wavfile import read, write\nfrom text_utils.language import Language\nfrom text_utils.pronunciation.main import EngToIPAMode\nfrom textgrid.textgrid import TextGrid\nfrom textgrid_tools.core.extract_audio import (extract_words_to_audio,\n get_extracts_df)\nfrom textgrid_tools.core.main import (add_ipa_tier, add_pause_tier,\n add_words_tier, export_csv,\n get_template_textgrid, log_tier_stats)\nfrom textgrid_tools.core.to_dataset import Entry, convert_textgrid2dataset\nfrom textgrid_tools.utils import save_dataclasses\nfrom tqdm import tqdm\n\nAUDIO_FILE = \"audio.wav\"\n\nDATA_CSV_NAME = \"data.csv\"\nAUDIO_FOLDER_NAME = \"audio\"\n\n\ndef get_recording_dir(base_dir: Path, recording_name: str) -> Path:\n return base_dir / recording_name\n\n\ndef get_audio_extraction_dir(recording_dir: Path, step_name: str) -> Path:\n return recording_dir / step_name\n\n\ndef get_step_path(recording_dir: Path, step_name: str) -> Path:\n return recording_dir / f\"{step_name}.TextGrid\"\n\n\ndef get_audio_path(recording_dir: Path) -> Path:\n return recording_dir / AUDIO_FILE\n\n\ndef add_recording(base_dir: Path, recording_name: str, audio_path: Path, out_step_name: str, overwrite_recording: bool):\n logger = getLogger(__name__)\n logger.info(\"Adding recording...\")\n recording_dir = get_recording_dir(base_dir, recording_name)\n if not audio_path.exists():\n logger.error(\"Audio file does not exist.\")\n return\n if recording_dir.exists():\n if overwrite_recording:\n rmtree(recording_dir)\n logger.info(\"Removed existing recording.\")\n else:\n logger.error(\"Recording already exists.\")\n return\n\n sr, wav = read(audio_path)\n\n logger.info(\"Creating folder...\")\n recording_dir.mkdir(parents=True, exist_ok=False)\n logger.info(\"Adding wav...\")\n dest_audio_path = get_audio_path(recording_dir)\n write(dest_audio_path, rate=sr, data=wav)\n logger.info(\"Adding textgrid...\")\n out_step_path = get_step_path(recording_dir, out_step_name)\n grid = get_template_textgrid(wav, sr)\n grid.write(out_step_path)\n\n logger.info(\"Done.\")\n\n\ndef clone(base_dir: Path, recording_name: str, in_step_name: str, out_step_name: str, overwrite_step: bool):\n logger = getLogger(__name__)\n logger.info(\"Cloning recording step...\")\n recording_dir = get_recording_dir(base_dir, recording_name)\n\n in_step_path = get_step_path(recording_dir, in_step_name)\n out_step_path = get_step_path(recording_dir, out_step_name)\n if not in_step_path.exists():\n logger.error(f\"Step {in_step_name} does not exist.\")\n return\n if out_step_path.exists():\n if overwrite_step:\n rmtree(recording_dir)\n logger.info(f\"Removed step {out_step_name} recording.\")\n else:\n logger.error(f\"Step {out_step_name} already exists.\")\n return\n\n logger.info(\"Copying TextGrid file...\")\n copy(in_step_path, out_step_path)\n\n logger.info(\"Done.\")\n\n\ndef detect_silence(base_dir: Path, recording_name: str, in_step_name: str, out_step_name: str, out_tier_name: str, silence_boundary: float, chunk_size_ms: int, min_silence_duration_ms: int, min_content_duration_ms: int, content_buffer_start_ms: int, content_buffer_end_ms: int, silence_mark: str, content_mark: str, overwrite_step: bool, overwrite_tier: bool):\n logger = getLogger(__name__)\n logger.info(\"Detecting silence...\")\n recording_dir = get_recording_dir(base_dir, recording_name)\n\n in_step_path = get_step_path(recording_dir, in_step_name)\n out_step_path = get_step_path(recording_dir, out_step_name)\n audio_path = get_audio_path(recording_dir)\n assert audio_path.exists()\n\n if not in_step_path.exists():\n logger.error(f\"Step {in_step_name} does not exist.\")\n return\n if out_step_path.exists():\n if overwrite_step:\n rmtree(recording_dir)\n logger.info(f\"Removed step {out_step_name} recording.\")\n else:\n logger.error(f\"Step {out_step_name} already exists.\")\n return\n\n logger.info(\"Reading data...\")\n sr, wav = read(audio_path)\n grid = TextGrid()\n grid.read(in_step_path)\n\n logger.info(\"Detecting silence parts...\")\n\n add_pause_tier(\n grid=grid,\n chunk_size_ms=chunk_size_ms,\n content_buffer_start_ms=content_buffer_start_ms,\n content_buffer_end_ms=content_buffer_end_ms,\n content_mark=content_mark,\n silence_mark=silence_mark,\n silence_boundary=silence_boundary,\n min_content_duration_ms=min_content_duration_ms,\n min_silence_duration_ms=min_silence_duration_ms,\n out_tier_name=out_tier_name,\n sr=sr,\n wav=wav,\n overwrite_tier=overwrite_tier,\n )\n\n grid.write(out_step_path)\n logger.info(\"Done.\")\n\n\ndef extract_words(base_dir: Path, recording_name: str, in_step_name: str, out_step_name: str, in_tier_name: str, out_tier_name: str, overwrite_step: bool, overwrite_tier: bool):\n logger = getLogger(__name__)\n logger.info(\"Extracting words...\")\n recording_dir = get_recording_dir(base_dir, recording_name)\n\n in_step_path = get_step_path(recording_dir, in_step_name)\n out_step_path = get_step_path(recording_dir, out_step_name)\n audio_path = get_audio_path(recording_dir)\n assert audio_path.exists()\n\n if not in_step_path.exists():\n logger.error(f\"Step {in_step_name} does not exist.\")\n return\n if out_step_path.exists():\n if overwrite_step:\n rmtree(recording_dir)\n logger.info(f\"Removed step {out_step_name} recording.\")\n else:\n logger.error(f\"Step {out_step_name} already exists.\")\n return\n\n logger.info(\"Reading data...\")\n grid = TextGrid()\n grid.read(in_step_path)\n\n logger.info(\"Extracting words...\")\n add_words_tier(\n grid=grid,\n in_tier_name=in_tier_name,\n out_tier_name=out_tier_name,\n overwrite_tier=overwrite_tier,\n )\n\n grid.write(out_step_path)\n logger.info(\"Done.\")\n\n\ndef convert_to_ipa(base_dir: Path, recording_name: str, in_step_name: str, out_step_name: str, in_tier_name: str, out_tier_name: str, mode: Optional[EngToIPAMode], replace_unknown_with: str, consider_ipa_annotations: bool, in_tier_lang: Language, overwrite_step: bool, overwrite_tier: bool):\n logger = getLogger(__name__)\n logger.info(\"Converting to IPA...\")\n recording_dir = get_recording_dir(base_dir, recording_name)\n\n in_step_path = get_step_path(recording_dir, in_step_name)\n out_step_path = get_step_path(recording_dir, out_step_name)\n audio_path = get_audio_path(recording_dir)\n assert audio_path.exists()\n\n if not in_step_path.exists():\n logger.error(f\"Step {in_step_name} does not exist.\")\n return\n if out_step_path.exists():\n if overwrite_step:\n rmtree(recording_dir)\n logger.info(f\"Removed step {out_step_name} recording.\")\n else:\n logger.error(f\"Step {out_step_name} already exists.\")\n return\n\n logger.info(\"Reading data...\")\n grid = TextGrid()\n grid.read(in_step_path)\n\n logger.info(\"Converting to IPA...\")\n\n add_ipa_tier(\n grid=grid,\n in_tier_name=in_tier_name,\n out_tier_name=out_tier_name,\n overwrite_tier=overwrite_tier,\n consider_ipa_annotations=consider_ipa_annotations,\n mode=mode,\n in_tier_lang=in_tier_lang,\n replace_unknown_with=replace_unknown_with,\n )\n\n grid.write(out_step_path)\n logger.info(\"Done.\")\n\n\ndef log_stats(base_dir: Path, recording_name: str, step_name: str, tier_name: str, tier_lang: Language, ignore_arcs: Optional[bool], ignore_tones: Optional[bool], replace_unknown_ipa_by: Optional[str]):\n logger = getLogger(__name__)\n logger.info(f\"Stats for recording: {recording_name}\")\n recording_dir = get_recording_dir(base_dir, recording_name)\n\n step_path = get_step_path(recording_dir, step_name)\n\n if not step_path.exists():\n logger.error(f\"Step {step_path} does not exist.\")\n return\n\n grid = TextGrid()\n grid.read(step_path)\n\n ipa_settings = None\n # ipa_settings = IPAExtractionSettings(\n # ignore_arcs=ignore_arcs,\n # ignore_tones=ignore_tones,\n # replace_unknown_ipa_by=replace_unknown_ipa_by,\n # )\n\n log_tier_stats(grid, tier_name, tier_lang, ipa_settings)\n\n\ndef to_dataset(base_dir: Path, recording_name: str, step_name: str, tier_name: str, tier_lang: Language, duration_s_max: float, ignore_empty_marks: bool, output_dir: Path, speaker_name: str, speaker_gender: str, speaker_accent: str, overwrite_output: bool):\n logger = getLogger(__name__)\n logger.info(f\"Converting recording {recording_name} on tier {tier_name} to dataset...\")\n recording_dir = get_recording_dir(base_dir, recording_name)\n\n step_path = get_step_path(recording_dir, step_name)\n audio_path = get_audio_path(recording_dir)\n assert audio_path.exists()\n\n if not step_path.exists():\n logger.error(f\"Step {step_name} does not exist.\")\n return\n if output_dir.exists():\n if overwrite_output:\n rmtree(output_dir)\n logger.info(f\"Removed: {output_dir}.\")\n else:\n logger.error(f\"Folder {output_dir} already exists.\")\n return\n\n logger.info(\"Reading data...\")\n sr, wav = read(audio_path)\n grid = TextGrid()\n grid.read(step_path)\n\n logger.info(\"Converting to dataset...\")\n res = convert_textgrid2dataset(\n grid=grid,\n tier_name=tier_name,\n tier_lang=tier_lang,\n wav=wav,\n sr=sr,\n duration_s_max=duration_s_max,\n speaker_accent=speaker_accent,\n speaker_gender=speaker_gender,\n speaker_name=speaker_name,\n ignore_empty_marks=ignore_empty_marks,\n )\n\n logger.info(\"Writing output files...\")\n entry: Entry\n output_dir.mkdir(parents=True, exist_ok=False)\n audio_dir = output_dir / AUDIO_FOLDER_NAME\n audio_dir.mkdir(parents=False, exist_ok=False)\n\n for entry, out_wav in tqdm(res):\n wav_path = audio_dir / entry.wav\n write(wav_path, sr, out_wav)\n\n data_path = output_dir / DATA_CSV_NAME\n save_dataclasses([x for x, _ in res], data_path)\n\n logger.info(\"Done.\")\n\n\ndef export_to_csv(base_dir: Path, recording_name: str, step_name: str, graphemes_tier_name: str, graphemes_tier_lang: Language, phonemes_tier_name: str, phones_tier_name: str, overwrite: bool):\n logger = getLogger(__name__)\n logger.info(f\"Stats for recording: {recording_name}\")\n recording_dir = get_recording_dir(base_dir, recording_name)\n\n step_path = get_step_path(recording_dir, step_name)\n output_path = recording_dir / f\"{step_name}.csv\"\n\n if not step_path.exists():\n logger.error(f\"Step {step_path} does not exist.\")\n return\n\n if output_path.exists() and not overwrite:\n logger.error(\"Already exported!\")\n return\n\n grid = TextGrid()\n grid.read(step_path)\n\n df = export_csv(\n grid=grid,\n graphemes_tier_name=graphemes_tier_name,\n graphemes_tier_lang=graphemes_tier_lang,\n phonemes_tier_name=phonemes_tier_name,\n phones_tier_name=phones_tier_name,\n )\n\n df.to_csv(output_path, header=True, sep=\"\\t\")\n logger.info(f\"Written output to: {output_path}\")\n logger.info(\"Done.\")\n\n\ndef extract_audios(base_dir: Path, recording_name: str, step_name: str, graphemes_tier_name: str, phonemes_tier_name: str, phones_tier_name: str, overwrite: bool):\n logger = getLogger(__name__)\n logger.info(f\"Stats for recording: {recording_name}\")\n recording_dir = get_recording_dir(base_dir, recording_name)\n\n step_path = get_step_path(recording_dir, step_name)\n\n if not step_path.exists():\n logger.error(f\"Step {step_path} does not exist.\")\n return\n\n audio_extraction_dir = get_audio_extraction_dir(recording_dir, step_name)\n\n if audio_extraction_dir.exists():\n if overwrite:\n rmtree(audio_extraction_dir)\n logger.info(\"Removed existing export.\")\n else:\n logger.error(\"Already exported!\")\n return\n\n audio_path = get_audio_path(recording_dir)\n assert audio_path.exists()\n\n logger.info(\"Reading data...\")\n sr, wav = read(audio_path)\n grid = TextGrid()\n grid.read(step_path)\n\n result = extract_words_to_audio(\n grid=grid,\n graphemes_tier_name=graphemes_tier_name,\n phonemes_tier_name=phonemes_tier_name,\n phones_tier_name=phones_tier_name,\n wav=wav,\n sr=sr,\n )\n\n audio_extraction_dir.mkdir(parents=False, exist_ok=False)\n logger.info(\"Saving audios...\")\n for i, ((graphemes, phonemes), extracts) in enumerate(tqdm(result.items())):\n dir_name = f\"{i+1}_{graphemes.replace('/', '_')}_{phonemes}_({len(extracts)})\"\n current_folder = audio_extraction_dir / dir_name\n assert not current_folder.exists()\n current_folder.mkdir(parents=False, exist_ok=False)\n df = get_extracts_df(extracts)\n df_path = current_folder / \"details.csv\"\n df.to_csv(df_path, sep=\"\\t\", header=True, index=False)\n\n for j, extract in enumerate(extracts):\n wav_file_path = current_folder / f\"{j+1}_{extract.phones}.wav\"\n write(wav_file_path, sr, extract.audio)\n\n logger.info(f\"Written output to: {audio_extraction_dir}\")\n logger.info(\"Done.\")\n"
] | [
[
"scipy.io.wavfile.write",
"scipy.io.wavfile.read"
]
] |
doinalangille/DS-Unit-3-Sprint-2-SQL-and-Databases | [
"393f3e0f7e20893b66d0a825a0f2b856b77b6d3e"
] | [
"module1-introduction-to-sql/buddymove_holidayiq.py"
] | [
"import pandas as pd\nimport sqlite3\n\n# Load the data\ndf = pd.read_csv('buddymove_holidayiq.csv')\n\n# Open a connection to a new (blank) database file\nconnection = sqlite3.connect('buddymove_holidayiq.sqlite3')\n\n# Insert the data into a new table review in the SQLite3 database\ndf.to_sql('review', con=connection)\n\n# Count how many rows we have - it should be 249!\nresult = connection.execute(\"SELECT COUNT(*) FROM review;\").fetchall()\nprint(\"---------------\")\nprint(\"TOTAL ROWS:\", result[0][0])\nprint(\"---------------\")\n\n# How many users who reviewed at least 100 Nature in the category\n# also reviewed at least 100 in the Shopping category?\nquery = \"\"\"\n SELECT COUNT(\"User Id\")\n FROM review\n WHERE Nature >= 100 AND Shopping >= 100\n \"\"\"\nresult = connection.execute(query).fetchall()\nprint(\"Total number of users who reviewed\")\nprint(\"at least 100 in Nature and at least 100 in Shopping:\")\nprint(result[0][0])\nprint(\"---------------\")\n\n# What are the average number of reviews for each category?\nquery = \"\"\"\n SELECT ROUND(AVG(Sports),2) as Sports,\n ROUND(AVG(Religious),2) as Religious,\n ROUND(AVG(Nature),2) as Nature,\n ROUND(AVG(Theatre),2) as Theatre,\n ROUND(AVG(Shopping),2) as Shopping,\n ROUND(AVG(Picnic),2) as Picnic\n FROM review\n \"\"\"\nresult = connection.execute(query).fetchall()\nprint(\"The average number of reviews for each category\")\nprint(f'Sports: {result[0][0]}')\nprint(f'Religious: {result[0][1]}')\nprint(f'Nature: {result[0][2]}')\nprint(f'Theatre: {result[0][3]}')\nprint(f'Shopping: {result[0][4]}')\nprint(f'Picnic: {result[0][5]}')\n"
] | [
[
"pandas.read_csv"
]
] |
mahgadalla/pysph-1 | [
"5b504ebc364d58d2fa877b778e198674139461da"
] | [
"pysph/sph/tests/test_acceleration_eval.py"
] | [
"# Standard library imports.\ntry:\n # This is for Python-2.6.x\n import unittest2 as unittest\nexcept ImportError:\n import unittest\n\n# Library imports.\nimport pytest\nimport numpy as np\n\n# Local imports.\nfrom pysph.base.config import get_config\nfrom pysph.base.utils import get_particle_array\nfrom pysph.base.cython_generator import declare\nfrom pysph.sph.equation import Equation, Group\nfrom pysph.sph.acceleration_eval import (AccelerationEval,\n check_equation_array_properties)\nfrom pysph.sph.basic_equations import SummationDensity\nfrom pysph.base.kernels import CubicSpline\nfrom pysph.base.nnps import LinkedListNNPS as NNPS\nfrom pysph.sph.sph_compiler import SPHCompiler\n\nfrom pysph.base.reduce_array import serial_reduce_array\n\n\nclass DummyEquation(Equation):\n def initialize(self, d_idx, d_rho, d_V):\n d_rho[d_idx] = d_V[d_idx]\n\n def loop(self, d_idx, d_rho, s_idx, s_m, s_u, WIJ):\n d_rho[d_idx] += s_m[s_idx]*WIJ\n\n def post_loop(self, d_idx, d_rho, s_idx, s_m, s_V):\n d_rho[d_idx] += s_m[d_idx]\n\n\nclass FindTotalMass(Equation):\n def initialize(self, d_idx, d_m, d_total_mass):\n # FIXME: This is stupid and should be fixed if we add a separate\n # initialize_once function or so.\n d_total_mass[0] = 0.0\n\n def post_loop(self, d_idx, d_m, d_total_mass):\n d_total_mass[0] += d_m[d_idx]\n\n\nclass TestCheckEquationArrayProps(unittest.TestCase):\n\n def test_should_raise_runtime_error_when_invalid_dest_source(self):\n # Given\n f = get_particle_array(name='f')\n\n # When\n eq = SummationDensity(dest='fluid', sources=['f'])\n\n # Then\n self.assertRaises(\n RuntimeError,\n check_equation_array_properties,\n eq, [f]\n )\n\n # When\n eq = SummationDensity(dest='f', sources=['fluid'])\n\n # Then\n self.assertRaises(\n RuntimeError,\n check_equation_array_properties,\n eq, [f]\n )\n\n def test_should_pass_when_properties_exist(self):\n # Given\n f = get_particle_array(name='f')\n\n # When\n eq = SummationDensity(dest='f', sources=['f'])\n\n # Then\n check_equation_array_properties(eq, [f])\n\n def test_should_fail_when_props_dont_exist(self):\n # Given\n f = get_particle_array(name='f')\n\n # When\n eq = DummyEquation(dest='f', sources=['f'])\n\n # Then\n self.assertRaises(RuntimeError,\n check_equation_array_properties, eq, [f])\n\n def test_should_fail_when_src_props_dont_exist(self):\n # Given\n f = get_particle_array(name='f')\n f.add_property('V')\n s = get_particle_array(name='s')\n\n # When\n eq = DummyEquation(dest='f', sources=['f', 's'])\n\n # Then\n self.assertRaises(RuntimeError,\n check_equation_array_properties, eq, [f, s])\n\n def test_should_pass_when_src_props_exist(self):\n # Given\n f = get_particle_array(name='f')\n f.add_property('V')\n s = get_particle_array(name='s')\n s.add_property('V')\n\n # When\n eq = DummyEquation(dest='f', sources=['f', 's'])\n\n # Then\n check_equation_array_properties(eq, [f, s])\n\n def test_should_check_constants(self):\n # Given\n f = get_particle_array(name='f')\n\n # When\n eq = FindTotalMass(dest='f', sources=['f'])\n\n # Then.\n self.assertRaises(RuntimeError,\n check_equation_array_properties, eq, [f])\n\n # When.\n f.add_constant('total_mass', 0.0)\n\n # Then.\n check_equation_array_properties(eq, [f])\n\n\nclass SimpleEquation(Equation):\n def __init__(self, dest, sources):\n super(SimpleEquation, self).__init__(dest, sources)\n self.count = 0\n\n def initialize(self, d_idx, d_u, d_au):\n d_u[d_idx] = 0.0\n d_au[d_idx] = 0.0\n\n def loop(self, d_idx, d_au, s_idx, s_m):\n d_au[d_idx] += s_m[s_idx]\n\n def post_loop(self, d_idx, d_u, d_au):\n d_u[d_idx] = d_au[d_idx]\n\n def converged(self):\n self.count += 1\n result = self.count - 1\n if result > 0:\n # Reset the count for the next loop.\n self.count = 0\n return result\n\n\nclass MixedTypeEquation(Equation):\n def initialize(self, d_idx, d_u, d_au, d_pid, d_tag):\n d_u[d_idx] = 0.0 + d_pid[d_idx]\n d_au[d_idx] = 0.0 + d_tag[d_idx]\n\n def loop(self, d_idx, d_au, s_idx, s_m, s_pid, s_tag):\n d_au[d_idx] += s_m[s_idx] + s_pid[s_idx] + s_tag[s_idx]\n\n def post_loop(self, d_idx, d_u, d_au, d_pid):\n d_u[d_idx] = d_au[d_idx] + d_pid[d_idx]\n\n\nclass SimpleReduction(Equation):\n def initialize(self, d_idx, d_au):\n d_au[d_idx] = 0.0\n\n def reduce(self, dst):\n dst.total_mass[0] = serial_reduce_array(dst.m, op='sum')\n if dst.gpu is not None:\n dst.gpu.push('total_mass')\n\n\nclass LoopAllEquation(Equation):\n def initialize(self, d_idx, d_rho):\n d_rho[d_idx] = 0.0\n\n def loop(self, d_idx, d_rho, s_m, s_idx, WIJ):\n d_rho[d_idx] += s_m[s_idx]*WIJ\n\n def loop_all(self, d_idx, d_x, d_rho, s_m, s_x, s_h, KERNEL, NBRS, N_NBRS):\n i = declare('int')\n s_idx = declare('long')\n xij = declare('matrix((3,))')\n rij = 0.0\n sum = 0.0\n xij[1] = 0.0\n xij[2] = 0.0\n for i in range(N_NBRS):\n s_idx = NBRS[i]\n xij[0] = d_x[d_idx] - s_x[s_idx]\n rij = fabs(xij[0])\n sum += s_m[s_idx]*KERNEL.kernel(xij, rij, s_h[s_idx])\n d_rho[d_idx] += sum\n\n\nclass TestAccelerationEval1D(unittest.TestCase):\n def setUp(self):\n self.dim = 1\n n = 10\n dx = 1.0/(n-1)\n x = np.linspace(0, 1, n)\n m = np.ones_like(x)\n h = np.ones_like(x)*dx*1.05\n pa = get_particle_array(name='fluid', x=x, h=h, m=m)\n self.pa = pa\n\n def _make_accel_eval(self, equations, cache_nnps=False):\n arrays = [self.pa]\n kernel = CubicSpline(dim=self.dim)\n a_eval = AccelerationEval(\n particle_arrays=arrays, equations=equations, kernel=kernel\n )\n comp = SPHCompiler(a_eval, integrator=None)\n comp.compile()\n nnps = NNPS(dim=kernel.dim, particles=arrays, cache=cache_nnps)\n nnps.update()\n a_eval.set_nnps(nnps)\n return a_eval\n\n def test_should_support_constants(self):\n # Given\n pa = self.pa\n pa.add_constant('total_mass', 0.0)\n equations = [FindTotalMass(dest='fluid', sources=['fluid'])]\n a_eval = self._make_accel_eval(equations)\n\n # When\n a_eval.compute(0.1, 0.1)\n\n # Then\n self.assertEqual(pa.total_mass, 10.0)\n\n def test_should_not_iterate_normal_group(self):\n # Given\n pa = self.pa\n equations = [SimpleEquation(dest='fluid', sources=['fluid'])]\n a_eval = self._make_accel_eval(equations)\n\n # When\n a_eval.compute(0.1, 0.1)\n\n # Then\n expect = np.asarray([3., 4., 5., 5., 5., 5., 5., 5., 4., 3.])\n self.assertListEqual(list(pa.u), list(expect))\n\n def test_should_work_with_cached_nnps(self):\n # Given\n pa = self.pa\n equations = [SimpleEquation(dest='fluid', sources=['fluid'])]\n a_eval = self._make_accel_eval(equations, cache_nnps=True)\n\n # When\n a_eval.compute(0.1, 0.1)\n\n # Then\n expect = np.asarray([3., 4., 5., 5., 5., 5., 5., 5., 4., 3.])\n self.assertListEqual(list(pa.u), list(expect))\n\n def test_should_iterate_iterated_group(self):\n # Given\n pa = self.pa\n equations = [Group(\n equations=[\n SimpleEquation(dest='fluid', sources=['fluid']),\n SimpleEquation(dest='fluid', sources=['fluid']),\n ],\n iterate=True\n )]\n a_eval = self._make_accel_eval(equations)\n\n # When\n a_eval.compute(0.1, 0.1)\n\n # Then\n expect = np.asarray([3., 4., 5., 5., 5., 5., 5., 5., 4., 3.])*2\n self.assertListEqual(list(pa.u), list(expect))\n\n def test_should_iterate_nested_groups(self):\n pa = self.pa\n equations = [Group(\n equations=[\n Group(\n equations=[SimpleEquation(dest='fluid', sources=['fluid'])]\n ),\n Group(\n equations=[SimpleEquation(dest='fluid', sources=['fluid'])]\n ),\n ],\n iterate=True,\n )]\n a_eval = self._make_accel_eval(equations)\n\n # When\n a_eval.compute(0.1, 0.1)\n\n # Then\n expect = np.asarray([3., 4., 5., 5., 5., 5., 5., 5., 4., 3.])\n self.assertListEqual(list(pa.u), list(expect))\n\n def test_should_run_reduce(self):\n # Given.\n pa = self.pa\n pa.add_constant('total_mass', 0.0)\n equations = [SimpleReduction(dest='fluid', sources=['fluid'])]\n a_eval = self._make_accel_eval(equations)\n\n # When\n a_eval.compute(0.1, 0.1)\n\n # Then\n expect = np.sum(pa.m)\n self.assertAlmostEqual(pa.total_mass[0], expect, 14)\n\n def test_should_work_with_non_double_arrays(self):\n # Given\n pa = self.pa\n equations = [MixedTypeEquation(dest='fluid', sources=['fluid'])]\n a_eval = self._make_accel_eval(equations)\n\n # When\n a_eval.compute(0.1, 0.1)\n\n # Then\n expect = np.asarray([3., 4., 5., 5., 5., 5., 5., 5., 4., 3.])\n self.assertListEqual(list(pa.u), list(expect))\n\n def test_should_support_loop_all_and_loop(self):\n # Given\n pa = self.pa\n equations = [SummationDensity(dest='fluid', sources=['fluid'])]\n a_eval = self._make_accel_eval(equations)\n a_eval.compute(0.1, 0.1)\n ref_rho = pa.rho.copy()\n\n # When\n pa.rho[:] = 0.0\n equations = [LoopAllEquation(dest='fluid', sources=['fluid'])]\n a_eval = self._make_accel_eval(equations)\n a_eval.compute(0.1, 0.1)\n\n # Then\n # 2*ref_rho as we are doing both the loop and loop_all to test if\n # both are called.\n self.assertTrue(np.allclose(pa.rho, 2.0*ref_rho))\n\n\nclass EqWithTime(Equation):\n def initialize(self, d_idx, d_au, t, dt):\n d_au[d_idx] = t + dt\n\n def loop(self, d_idx, d_au, s_idx, s_m, t, dt):\n d_au[d_idx] += t + dt\n\n\nclass TestAccelerationEval1DGPU(unittest.TestCase):\n # Fix this to be a subclass of TestAccelerationEval1D\n\n def setUp(self):\n self.dim = 1\n n = 10\n dx = 1.0/(n-1)\n x = np.linspace(0, 1, n)\n m = np.ones_like(x)\n h = np.ones_like(x)*dx*1.05\n pa = get_particle_array(name='fluid', x=x, h=h, m=m)\n self.pa = pa\n\n def _make_accel_eval(self, equations, cache_nnps=True):\n pytest.importorskip('pysph.base.gpu_nnps')\n from pysph.base.gpu_nnps import ZOrderGPUNNPS as GPUNNPS\n arrays = [self.pa]\n kernel = CubicSpline(dim=self.dim)\n a_eval = AccelerationEval(\n particle_arrays=arrays, equations=equations, kernel=kernel,\n backend='opencl'\n )\n comp = SPHCompiler(a_eval, integrator=None)\n comp.compile()\n self.sph_compiler = comp\n nnps = GPUNNPS(dim=kernel.dim, particles=arrays, cache=cache_nnps)\n nnps.update()\n a_eval.set_nnps(nnps)\n return a_eval\n\n def test_accel_eval_should_work_on_gpu(self):\n # Given\n pa = self.pa\n equations = [SimpleEquation(dest='fluid', sources=['fluid'])]\n a_eval = self._make_accel_eval(equations)\n\n # When\n a_eval.compute(0.1, 0.1)\n\n # Then\n expect = np.asarray([3., 4., 5., 5., 5., 5., 5., 5., 4., 3.])\n pa.gpu.pull('u')\n self.assertListEqual(list(pa.u), list(expect))\n\n def test_precomputed_should_work_on_gpu(self):\n # Given\n pa = self.pa\n equations = [SummationDensity(dest='fluid', sources=['fluid'])]\n a_eval = self._make_accel_eval(equations)\n\n # When\n a_eval.compute(0.1, 0.1)\n\n # Then\n expect = np.asarray([7.357, 9.0, 9., 9., 9., 9., 9., 9., 9., 7.357])\n pa.gpu.pull('rho')\n\n print(pa.rho, pa.gpu.rho)\n self.assertTrue(np.allclose(expect, pa.rho, atol=1e-2))\n\n def test_precomputed_should_work_on_gpu_with_double(self):\n orig = get_config().use_double\n\n def _cleanup():\n get_config().use_double = orig\n get_config().use_double = True\n self.addCleanup(_cleanup)\n # Given\n pa = self.pa\n equations = [SummationDensity(dest='fluid', sources=['fluid'])]\n a_eval = self._make_accel_eval(equations)\n\n # When\n a_eval.compute(0.1, 0.1)\n\n # Then\n expect = np.asarray([7.357, 9.0, 9., 9., 9., 9., 9., 9., 9., 7.357])\n pa.gpu.pull('rho')\n\n print(pa.rho, pa.gpu.rho)\n self.assertTrue(np.allclose(expect, pa.rho, atol=1e-2))\n\n def test_equation_with_time_should_work_on_gpu(self):\n # Given\n pa = self.pa\n equations = [EqWithTime(dest='fluid', sources=['fluid'])]\n a_eval = self._make_accel_eval(equations)\n\n # When\n a_eval.compute(0.2, 0.1)\n\n # Then\n expect = np.asarray([4., 5., 6., 6., 6., 6., 6., 6., 5., 4.])*0.3\n pa.gpu.pull('au')\n print(pa.au, expect)\n self.assertTrue(np.allclose(expect, pa.au))\n\n def test_update_nnps_is_called_for_opencl(self):\n # Given\n equations = [\n Group(\n equations=[\n SummationDensity(dest='fluid', sources=['fluid']),\n ],\n update_nnps=True\n ),\n Group(\n equations=[EqWithTime(dest='fluid', sources=['fluid'])]\n ),\n ]\n\n # When\n a_eval = self._make_accel_eval(equations)\n\n # Then\n h = a_eval.c_acceleration_eval.helper\n assert len(h.calls) == 5\n call = h.calls[0]\n assert call['type'] == 'kernel'\n assert call['method'].function_name == 'g0_fluid_initialize'\n assert call['loop'] is False\n\n call = h.calls[1]\n assert call['type'] == 'kernel'\n assert call['method'].function_name == 'g0_fluid_on_fluid_loop'\n assert call['loop'] is True\n\n call = h.calls[2]\n assert call['type'] == 'method'\n assert call['method'] == 'update_nnps'\n\n call = h.calls[3]\n assert call['type'] == 'kernel'\n assert call['method'].function_name == 'g1_fluid_initialize'\n assert call['loop'] is False\n\n call = h.calls[4]\n assert call['type'] == 'kernel'\n assert call['method'].function_name == 'g1_fluid_on_fluid_loop'\n assert call['loop'] is True\n\n def test_should_stop_iteration_with_max_iteration_on_gpu(self):\n pa = self.pa\n\n class SillyEquation(Equation):\n def loop(self, d_idx, d_au, s_idx, s_m):\n d_au[d_idx] += s_m[s_idx]\n\n def converged(self):\n return 0\n\n equations = [Group(\n equations=[\n Group(\n equations=[SillyEquation(dest='fluid', sources=['fluid'])]\n ),\n Group(\n equations=[SillyEquation(dest='fluid', sources=['fluid'])]\n ),\n ],\n iterate=True, max_iterations=2,\n )]\n a_eval = self._make_accel_eval(equations)\n\n # When\n a_eval.compute(0.1, 0.1)\n\n # Then\n expect = np.asarray([3., 4., 5., 5., 5., 5., 5., 5., 4., 3.])*4.0\n pa.gpu.pull('au')\n self.assertListEqual(list(pa.au), list(expect))\n\n def test_should_stop_iteration_with_converged_on_gpu(self):\n pa = self.pa\n\n class SillyEquation1(Equation):\n def __init__(self, dest, sources):\n super(SillyEquation1, self).__init__(dest, sources)\n self.conv = 0\n\n def loop(self, d_idx, d_au, s_idx, s_m):\n d_au[d_idx] += s_m[s_idx]\n\n def post_loop(self, d_idx, d_au):\n if d_au[d_idx] > 19.0:\n self.conv = 1\n\n def converged(self):\n return self.conv\n\n equations = [Group(\n equations=[\n Group(\n equations=[SillyEquation1(dest='fluid', sources=['fluid'])]\n ),\n Group(\n equations=[SillyEquation1(dest='fluid', sources=['fluid'])]\n ),\n ],\n iterate=True, max_iterations=10,\n )]\n a_eval = self._make_accel_eval(equations)\n\n # When\n a_eval.compute(0.1, 0.1)\n\n # Then\n expect = np.asarray([3., 4., 5., 5., 5., 5., 5., 5., 4., 3.])*6.0\n pa.gpu.pull('au')\n self.assertListEqual(list(pa.au), list(expect))\n\n def test_should_handle_helper_functions_on_gpu(self):\n pa = self.pa\n\n def helper(x=1.0):\n return x*1.5\n\n class SillyEquation2(Equation):\n def initialize(self, d_idx, d_au, d_m):\n d_au[d_idx] += helper(d_m[d_idx])\n\n def _get_helpers_(self):\n return [helper]\n\n equations = [SillyEquation2(dest='fluid', sources=['fluid'])]\n\n a_eval = self._make_accel_eval(equations)\n\n # When\n a_eval.compute(0.1, 0.1)\n\n # Then\n expect = np.ones(10)*1.5\n pa.gpu.pull('au')\n self.assertListEqual(list(pa.au), list(expect))\n\n def test_should_run_reduce_when_using_gpu(self):\n # Given.\n pa = self.pa\n pa.add_constant('total_mass', 0.0)\n equations = [SimpleReduction(dest='fluid', sources=['fluid'])]\n a_eval = self._make_accel_eval(equations)\n\n # When\n a_eval.compute(0.1, 0.1)\n\n # Then\n expect = np.sum(pa.m)\n pa.gpu.pull('total_mass')\n self.assertAlmostEqual(pa.total_mass[0], expect, 14)\n\n def test_get_equations_with_converged(self):\n pytest.importorskip('pysph.base.gpu_nnps')\n from pysph.sph.acceleration_eval_opencl_helper import \\\n get_equations_with_converged\n # Given\n se = SimpleEquation(dest='fluid', sources=['fluid'])\n se1 = SimpleEquation(dest='fluid', sources=['fluid'])\n sd = SummationDensity(dest='fluid', sources=['fluid'])\n me = MixedTypeEquation(dest='fluid', sources=['fluid'])\n eq_t = EqWithTime(dest='fluid', sources=['fluid'])\n g = Group(\n equations=[\n Group(equations=[Group(equations=[se, sd])],\n iterate=True, max_iterations=10),\n Group(equations=[me, eq_t, se1]),\n ],\n )\n\n # When\n eqs = get_equations_with_converged(g)\n\n # Then\n assert eqs == [se, se1]\n\n def test_should_support_loop_all_and_loop_on_gpu(self):\n # Given\n pa = self.pa\n equations = [SummationDensity(dest='fluid', sources=['fluid'])]\n a_eval = self._make_accel_eval(equations)\n a_eval.compute(0.1, 0.1)\n pa.gpu.pull('rho')\n ref_rho = pa.rho.copy()\n\n # When\n pa.rho[:] = 0.0\n pa.gpu.push('rho')\n equations = [LoopAllEquation(dest='fluid', sources=['fluid'])]\n a_eval = self._make_accel_eval(equations)\n a_eval.compute(0.1, 0.1)\n\n # Then\n # 2*ref_rho as we are doing both the loop and loop_all to test if\n # both are called.\n pa.gpu.pull('rho')\n self.assertTrue(np.allclose(pa.rho, 2.0*ref_rho))\n"
] | [
[
"numpy.ones_like",
"numpy.allclose",
"numpy.linspace",
"numpy.asarray",
"numpy.ones",
"numpy.sum"
]
] |
AndrewBeers/dreamin | [
"d51a41fe5b85f1af1a13a0eb2ab2aa5466014d01"
] | [
"lucid_experiment.py"
] | [
"import numpy as np\nimport tensorflow as tf\nimport keras\nimport os\n\nimport lucid.modelzoo.vision_models as models\nimport lucid.modelzoo.vision_base as vision_base\nfrom lucid.misc.io import show\nimport lucid.optvis.objectives as objectives\nimport lucid.optvis.param as param\nimport lucid.optvis.render as render\nimport lucid.optvis.transform as transform\n\nfrom lucid.modelzoo.util import load_text_labels, load_graphdef, forget_xy\nfrom custom_layers import PoolHelper, LRN\n\nos.environ[\"CUDA_VISIBLE_DEVICES\"] = str(0)\n\nconfig = tf.ConfigProto()\nconfig.gpu_options.allow_growth = True\n\ngraph = tf.Graph()\nsess = tf.InteractiveSession(graph=graph)\n\nkeras_model = '/mnt/jk489/James/plus_classification/results_with_200_excluded/tf_resnet_test/classification/Split0_Model_128features/model_arch.json'\nkeras_weights = '/mnt/jk489/James/plus_classification/results_with_200_excluded/tf_resnet_test/classification/Split0_Model_128features/best_weights.h5'\ntf_model = 'rop_classification_model.pb'\n\n# json_file = open(keras_model, 'r')\n# loaded_model_json = json_file.read()\n# json_file.close()\n# model = keras.models.model_from_json(loaded_model_json, custom_objects={'PoolHelper':PoolHelper, 'LRN':LRN})\n# model.load_weights(keras_weights)\n\ntf.saved_model.loader.load(sess, ['rop_masks'], '/home/local/PARTNERS/azb22/Github/dreamTexts/saved_pages/9')\n\n# for name in graph.get_operations():\n# try:\n# print(name.name)\n# except:\n# continue\n\n# fd = dg\n\ninit = tf.global_variables_initializer()\nsess.run(init)\n\nclass PbModel(vision_base.Model):\n model_path = '/home/local/PARTNERS/azb22/Github/dreamTexts/saved_rop_masks/8/'\n labels_path = None\n image_shape = [1024,1024,4]\n image_value_range = (-117, 255-117)\n input_name = 'discriminator/discriminator_input:0'\n\n def __init__(self):\n self.graph_def = None\n if self.labels_path is not None:\n self.labels = load_text_labels(self.labels_path)\n\n def load_graphdef(self):\n self.graph_def = graph.as_graph_def()\n\n def post_import(self, scope):\n pass\n\n def create_input(self, t_input=None, forget_xy_shape=True):\n \"\"\"Create input tensor.\"\"\"\n if t_input is None:\n t_input = tf.placeholder(tf.float32, self.image_shape)\n t_prep_input = t_input\n if len(t_prep_input.shape) == 3:\n t_prep_input = tf.expand_dims(t_prep_input, 0)\n if forget_xy_shape:\n t_prep_input = forget_xy(t_prep_input)\n lo, hi = self.image_value_range\n t_prep_input = lo + t_prep_input * (hi-lo)\n return t_input, t_prep_input\n\n def import_graph(self, t_input=None, scope='import', forget_xy_shape=True):\n \"\"\"Import model GraphDef into the current graph.\"\"\"\n graph = tf.get_default_graph()\n assert graph.unique_name(scope, False) == scope, (\n 'Scope \"%s\" already exists. Provide explicit scope names when '\n 'importing multiple instances of the model.') % scope\n t_input, t_prep_input = self.create_input(t_input, forget_xy_shape)\n print(t_input, t_prep_input)\n tf.import_graph_def(self.graph_def, {self.input_name: t_prep_input}, name=scope)\n self.post_import(scope)\n\n# lucid_model = vision_base.Model()\n# lucid_model.model_path = tf_model\nlucid_model = PbModel()\nlucid_model.load_graphdef()\n\n\ntemp_graph_def = graph.as_graph_def()\n\n# fd = dg\n\n# print(lucid_model.graph_def)\n\n# model = models.InceptionV1().load_graphdef()\n# print(model)\n# print(dir(model))\n\nobj = objectives.channel(\"discriminator/dis_n_conv_1_4/Conv2D\", 2)\nparam_f = lambda: tf.concat([\n param.rgb_sigmoid(param.naive([1, 128, 128, 3])),\n param.fancy_colors(param.naive([1, 128, 128, 8])/1.3),\n param.rgb_sigmoid(param.laplacian_pyramid([1, 128, 128, 3])/2.),\n param.fancy_colors(param.laplacian_pyramid([1, 128, 128, 8])/2./1.3),\n], 0)\nrender.render_vis(lucid_model, obj, param_f)\n\n# _ = render.render_vis(lucid_model, \"discriminator/dis_n_conv_1_4/Conv2D:0\")"
] | [
[
"tensorflow.Graph",
"tensorflow.import_graph_def",
"tensorflow.InteractiveSession",
"tensorflow.placeholder",
"tensorflow.expand_dims",
"tensorflow.ConfigProto",
"tensorflow.global_variables_initializer",
"tensorflow.get_default_graph",
"tensorflow.saved_model.loader.load"
]
] |
Arihant25/beginner-python-projects | [
"43c6489b6973522246073f2187a682487f1684c1"
] | [
"birthday_wisher/main.py"
] | [
"import pandas\nimport smtplib\nimport datetime as dt\nimport random\n\n# Enter the number of letter templates in the folder\nLETTER_TEMPLATES = 3\n\n# Enter your email, password and SMTP Server\nEMAIL = \"[email protected]\"\nPASSWORD = \"password0\"\nSMTP_SERVER = \"smtp.office365.com\"\n\nnow = dt.datetime.now()\ntoday = (now.month, now.day)\n\n# Read the CSV file containing everyone's birthdays\nbirthdays = pandas.read_csv('birthdays.csv')\n\n# Convert it to a dictionary\nbirthdays_dict = {(row['month'], row['day']): row for (index, row) in birthdays.iterrows()}\n\n# Check if today matches a birthday in birthdays.csv\nif today in birthdays_dict:\n # Pick a random letter from letter templates\n letter_number = random.randint(1, LETTER_TEMPLATES - 1)\n with open(f\"letter_templates/letter_{letter_number}.txt\") as letter:\n # Write the receiver's name in the template\n letter = letter.read().replace('[NAME]', birthdays_dict[today]['name'])\n # Send an email\n with smtplib.SMTP(host=SMTP_SERVER, port=587) as connection:\n connection.starttls()\n connection.login(user=EMAIL, password=PASSWORD)\n connection.sendmail(from_addr=EMAIL,\n to_addrs=birthdays_dict[today]['email'],\n msg=f\"Subject:Happy Birthday!\\n\\n{letter}\")\n"
] | [
[
"pandas.read_csv"
]
] |
mnschmit/conan | [
"31df764de3af462e9cbe8c8bfe981c49334e37e8"
] | [
"src/train/n_k_loop.py"
] | [
"from typing import Callable\nimport pytorch_lightning as pl\nfrom pytorch_lightning import LightningModule\nimport torch\nfrom pathlib import Path\nimport os\nimport argparse\nfrom ..models.multnat_model import MultNatModel\nfrom .utils import add_generic_args\n\n\ndef train(\n model_cls: Callable[[argparse.Namespace], LightningModule],\n args: argparse.Namespace,\n iteration: int\n):\n pl.seed_everything(args.seed)\n\n # init model\n model = model_cls(args)\n\n cdir = Path(os.path.join(\n model.hparams.checkpoint_dir, args.experiment_name,\n \"version_{}\".format(iteration)))\n cdir.mkdir(exist_ok=True, parents=True)\n\n checkpoint_callback = pl.callbacks.ModelCheckpoint(\n dirpath=cdir,\n filename=str(args.num_patterns)+'-'+str(\n args.num_tokens_per_pattern)+'-{epoch}-{val_loss:.2f}-{AUC:.2f}',\n monitor=\"AUC\", mode=\"max\", save_top_k=1\n )\n\n trainer = pl.Trainer.from_argparse_args(\n args,\n weights_summary=None,\n logger=False,\n callbacks=checkpoint_callback,\n deterministic=True,\n distributed_backend=\"ddp\" if args.gpus > 1 else None\n )\n\n trainer.fit(model)\n\n return trainer, model\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n add_generic_args(parser)\n MultNatModel.add_model_specific_args(parser)\n parser.add_argument('--start_num_patterns', default=100, type=int)\n parser.add_argument('--start_num_tokens_per_pattern', default=10, type=int)\n parser.add_argument('--start_version', default=0, type=int)\n args = parser.parse_args()\n\n out_file = \"{}.tsv\".format(args.experiment_name)\n if os.path.exists(out_file):\n print(\"Out file already exists!\")\n exit(1)\n\n with open(out_file, 'w') as fout:\n iteration = args.start_version\n for num_patterns in [100, 75, 50, 25, 10, 5, 1]:\n if num_patterns > args.start_num_patterns:\n continue\n\n args.num_patterns = num_patterns\n for num_tokens_per_pattern in [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]:\n if num_patterns == args.start_num_patterns and\\\n num_tokens_per_pattern > args.start_num_tokens_per_pattern:\n continue\n\n print('!!! {} --- {} !!!'.format(num_patterns, num_tokens_per_pattern))\n args.num_tokens_per_pattern = num_tokens_per_pattern\n trainer, model = train(MultNatModel, args, iteration)\n metrics = trainer.test(test_dataloaders=model.val_dataloader())\n val_auc = metrics[0]['AUC']\n print(num_patterns, num_tokens_per_pattern,\n val_auc, sep='\\t', file=fout)\n iteration += 1\n fout.flush()\n del trainer\n del model\n torch.cuda.empty_cache()\n"
] | [
[
"torch.cuda.empty_cache"
]
] |
sernst/track-outline-comparison | [
"5a0fb5ac03f1edcbd11ad3fd49f8a62f93f08774"
] | [
"steps/load_data.py"
] | [
"import pandas as pd\n\nimport measurement_stats as mstats\n\nfrom cauldron import project\n\ndf = pd.read_csv('../Measurements.csv')\n\nmeasurements = []\n\nmeasurement_keys = []\n\nfor toe in ['Left', 'Center', 'Right']:\n measurement_keys.append({\n 'label': '{} Digit Length'.format(toe),\n 'type': 'length',\n 'keys': [\n '{}-Length'.format(toe),\n '{}-Length-Unc'.format(toe)\n ],\n 'sources': [\n 'Length-Small-{}'.format(toe),\n 'Length-Large-{}'.format(toe)\n ]\n })\n\nfor side in ['Left', 'Right']:\n measurement_keys.append({\n 'label': '{} Angle'.format(side),\n 'type': 'angle',\n 'keys': [\n '{}-Angle'.format(side),\n '{}-Angle-Unc'.format(side)\n ],\n 'sources': [\n 'Angle-Small-{}'.format(side),\n 'Angle-Large-{}'.format(side)\n ]\n })\n\nfor index, row in df.iterrows():\n entry = {'drawing': index}\n\n for key_data in measurement_keys:\n small = row[key_data['sources'][0]]\n large = row[key_data['sources'][1]]\n\n value = mstats.ValueUncertainty(\n 0.5 * (small + large),\n max(0.5, 0.5 * abs(large - small))\n )\n\n entry[key_data['keys'][0]] = value.raw\n entry[key_data['keys'][1]] = value.raw_uncertainty\n\n entry['Width-Box'] = row['W-Box']\n entry['Height-Box'] = row['H-Box']\n measurements.append(entry)\n\ndf = pd.DataFrame(measurements)\nproject.shared.measurement_keys = measurement_keys\nproject.shared.measurements = df\nproject.shared.normalized_values = []\n# project.display.table(df, scale=0.5)\n"
] | [
[
"pandas.read_csv",
"pandas.DataFrame"
]
] |
SiqiTao/Collision_Prediction | [
"5ba99b884f7ccf64483e3acd83eb0b49dafd1aba"
] | [
"src/eda.py"
] | [
"# author: Linh Giang Nguyen\n# date: 2021-11-28\n\n\"\"\"Creates eda plots for the pre-processed training data from the \nNational Collision Database (NCDB) 2017 data (from https://open.canada.ca/data/en/\ndataset/1eb9eba7-71d1-4b30-9fb1-30cbdab7e63a/resource/01426d41-529c-443f-a901-6bc2f94f3d73).\nSaves the plots as png files.\n\nUsage: src/eda.py --train=<train> --out_dir=<out_dir>\n\nOptions:\n--train=<train> Path (including filename) to training data\n--out_dir=<out_dir> Path to directory where the plots should be saved\n\"\"\"\n\nfrom docopt import docopt\nimport pandas as pd\nimport altair as alt\nimport os\n\nalt.data_transformers.enable(\"data_server\")\nalt.renderers.enable(\"mimetype\")\n\nopt = docopt(__doc__)\n\n\ndef main():\n\n train_path = opt[\"--train\"]\n save_path = opt[\"--out_dir\"]\n\n # Check if input file is a .csv file\n assert train_path.endswith(\n \".csv\"\n ), \"Input file is not a .csv file, please enter a .csv file as the <in_file>\"\n \n train_df = (\n pd.read_csv(train_path, low_memory=False).set_index(\"index\").rename_axis(None)\n )\n\n # Check if the required columns exists in the train file\n assert set(train_df.columns) == {\n \"C_MNTH\",\n \"C_WDAY\",\n \"C_HOUR\",\n \"C_VEHS\",\n \"C_CONF\",\n \"C_RCFG\",\n \"C_WTHR\",\n \"C_RSUR\",\n \"C_RALN\",\n \"C_TRAF\",\n \"V_TYPE\",\n \"V_YEAR\",\n \"P_SEX\",\n \"P_AGE\",\n \"P_PSN\",\n \"P_SAFE\",\n \"P_USER\",\n \"FATALITY\"\n }, \"Required Columns not found in input .csv file\"\n \n # Converts values of P_SEX column into numeric\n sex = {\"M\": 1, \"F\": 0, \"missing\": \"missing\"}\n train_df[\"P_SEX\"] = [sex[item] for item in train_df[\"P_SEX\"]]\n \n # Creates the list of features to feed into distribution plots\n features = list(set(train_df.columns.values) - set([\"index\", \"FATALITY\"]))\n\n # Creates distribution plots when Fatality = 0\n Chart_False = (\n alt.Chart(train_df)\n .mark_bar(opacity=0.7)\n .encode(\n x=alt.X(alt.repeat(\"row\"),\n type=\"quantitative\",\n bin=alt.Bin(maxbins=20),\n axis=alt.Axis(format='.0f')),\n y=alt.Y(\"count()\", title=\"Number of collisions\"),\n color=alt.Color(\"FATALITY\", scale=alt.Scale(scheme=\"category20c\"), legend=None))\n .properties(width=150, height=100)\n .repeat(\n row=features,\n title=\"No fatality\")\n .resolve_scale(y=\"independent\")\n .transform_filter(alt.FieldOneOfPredicate(field=\"FATALITY\", oneOf=[0]))\n )\n \n # Creates distribution plots when Fatality = 1\n Chart_True = (\n alt.Chart(train_df)\n .mark_bar(opacity=0.7)\n .encode(\n x=alt.X(alt.repeat(\"row\"),\n type=\"quantitative\",\n bin=alt.Bin(maxbins=20),\n axis=alt.Axis(format='.0f')),\n y=alt.Y(\"count()\", title=\"Number of collisions\"),\n color=alt.Color(\"FATALITY\", scale=alt.Scale(scheme=\"category20b\"), legend=None))\n .properties(width=150, height=100)\n .repeat(\n row=features,\n title=\"Fatality\")\n .resolve_scale(y=\"independent\")\n .transform_filter(alt.FieldOneOfPredicate(field=\"FATALITY\", oneOf=[1]))\n )\n\n # Save distribution plots\n # Test if we have the given filepath in the directory, if not, create one.\n try:\n Chart_False.save(f\"{save_path}Distribution_of_no_fatality.png\")\n Chart_True.save(f\"{save_path}Distribution_of_fatality.png\")\n except:\n os.makedirs(os.path.dirname(save_path))\n Chart_False.save(f\"{save_path}Distribution_of_no_fatality.png\")\n Chart_True.save(f\"{save_path}Distribution_of_fatality.png\")\n\n \nif __name__ == \"__main__\":\n main()"
] | [
[
"pandas.read_csv"
]
] |
177arc/fpl-data | [
"cfa9d8a93a8878ca5be1ff4946c4d9f0f1643197"
] | [
"fpldata/s3store.py"
] | [
"import boto3\nimport pandas as pd\nfrom io import StringIO, BytesIO\nfrom zipfile import ZipFile, ZIP_DEFLATED\nfrom gzip import GzipFile\nimport os\nfrom typing import Dict\nimport shutil\n\n# Define type aliases\nDF = pd.DataFrame\nS = pd.Series\n\n\nclass S3Store:\n def_s3_bucket = 'fpl.177arc.net'\n\n def __is_zip(self, file_name: str) -> bool:\n return file_name.endswith('.zip')\n\n def __is_csv(self, file_name: str) -> bool:\n return file_name.endswith('.csv')\n\n def __init__(self, s3_bucket: str = None, s3: boto3.client = None):\n \"\"\"\n Initialise the S3 store.\n\n Args:\n s3: The S3 resource. If not provided, defaults to the standard S3 resource.\n s3_bucket: The name of the S3 bucket. If not provided, default to 'fpl.177arc.net'.\n \"\"\"\n self.s3 = s3 if s3 is not None else boto3.client('s3')\n self.s3_bucket = s3_bucket if s3_bucket is not None else self.def_s3_bucket\n\n def save_df(self, df: DF, key_name: str) -> None:\n \"\"\"\n Saves the given data frame to the S3 bucket.\n\n Args:\n df: The data frame to be saved.\n key_name: The name of the S3 object. If the key name ends in '.zip', it will generate a zip archive in S3.\n \"\"\"\n if not self.__is_zip(key_name) and not self.__is_csv(key_name):\n raise ValueError(f'The key name {key_name} does not end in \\'.zip\\' or \\'.csv\\'. Please use one of these extension to indicate how the data frame should be saved.')\n\n self.save_dfs({key_name.replace('.zip', '').replace('.csv', ''): df}, key_name)\n\n def save_dfs(self, dfs: Dict[str, DF], key_name: str) -> None:\n \"\"\"\n Saves the given data frames map to the S3 bucket as a zip archive.\n\n Args:\n dfs: A map of data frame names to the data frames to save.\n key_name: The name of the S3 object. If dfs contains more than on entry, the key name must end in '.zip'.\n \"\"\"\n if len(dfs) > 1 and not self.__is_zip(key_name):\n raise ValueError(f'The key name {key_name} does not end in \\'.zip\\'. It needs to because all the data frames will be save to one zip archive.')\n\n buffer = BytesIO()\n if self.__is_zip(key_name):\n with ZipFile(buffer, mode='w', compression=ZIP_DEFLATED) as zf:\n for df_name, df in dfs.items():\n csv_buffer = StringIO()\n df.to_csv(csv_buffer)\n zf.writestr(df_name+'.csv', csv_buffer.getvalue())\n else:\n buffer = BytesIO()\n with GzipFile(None, 'wb', 9, buffer) as gz:\n gz.write(list(dfs.values())[0].to_csv().encode())\n\n self.s3.put_object(Body=buffer.getvalue(), Bucket=self.s3_bucket, Key=key_name, ContentEncoding='gzip')\n\n def save_file(self, source_file: str, key_name: str, content_encoding: str = '') -> None:\n \"\"\"\n Saves the given file to the S3 bucket.\n\n Args:\n source_file: The file to be uploaded.\n key_name: The name of the S3 object.\n content_encoding: The content encoding in S3. If this is set to gzip, the file will be compressed before upload.\n \"\"\"\n with open(source_file, 'rb') as fp:\n if content_encoding == 'gzip':\n gz_buffer = BytesIO()\n with GzipFile(None, 'wb', 9, gz_buffer) as gz:\n shutil.copyfileobj(fp, gz)\n\n self.s3.put_object(Body=gz_buffer.getvalue(), Bucket=self.s3_bucket, Key=key_name, ContentEncoding=content_encoding)\n else:\n self.s3.put_object(Body=fp.read(), Bucket=self.s3_bucket, Key=key_name, ContentEncoding=content_encoding)\n\n def save_dir(self, source_dir: str, key_name: str = '') -> None:\n \"\"\"\n Saves the given directory to the S3 bucket either as a zip archive or as separate gzipped files.\n\n Args:\n source_dir: The directory that contains the files to save.\n key_name: The name of the S3 object. If the key name ends in '.zip', the directory will be uploaded as a zip archive.\n Otherwise, the files will be uploaded as separate gzip files and the key name will be treated as pre-fix for the uploaded files.\n \"\"\"\n if self.__is_zip(key_name):\n zip_buffer = BytesIO()\n with ZipFile(zip_buffer, mode='w', compression=ZIP_DEFLATED) as zf:\n for root, dirs, files in os.walk(source_dir):\n for file in files:\n zf.write(f'{root}/{file}', arcname=file)\n\n self.s3.put_object(Body=zip_buffer.getvalue(), Bucket=self.s3_bucket, Key=key_name)\n else:\n for root, dirs, files in os.walk(source_dir):\n for file in files:\n self.save_file(f'{root}/{file}', f'{key_name}{file}', content_encoding='gzip')\n\n def load_df(self, key_name: str) -> DF:\n \"\"\"\n Loads the data frame from the object with the given key name. If the name of the object ends in .zip,\n it will unzip the object on the fly use the first file the zip archive to load the data frame.\n\n Args:\n key_name: The name of the S3 object. If the key name ends in '.zip', it will extract the first file in the zip archive.\n\n Returns:\n The data frame.\n \"\"\"\n\n obj = self.s3.get_object(Bucket=self.s3_bucket, Key=key_name)\n buffer = BytesIO(obj[\"Body\"].read())\n\n if self.__is_zip(key_name):\n zf = ZipFile(buffer)\n\n if len(zf.namelist()) == 0:\n raise Exception(f'Could not load data frame because zip file {key_name} is empty.')\n\n buffer = BytesIO(zf.read(zf.namelist()[0]))\n\n return pd.read_csv(buffer)\n\n def load_dfs(self, key_name: str) -> Dict[str, DF]:\n \"\"\"\n Loads the data frames with the given key name. If the name of the object ends in .zip,\n it will unzip the object on the fly load the data frames from the files in the zip archive.\n\n Args:\n key_name: The name of the S3 object. If the key name ends in '.zip', it will extract the first file in the zip archive.\n\n Returns:\n A map of data frame names to the data frames that have been loaded.\n \"\"\"\n\n obj = self.s3.get_object(Bucket=self.s3_bucket, Key=key_name)\n buffer = BytesIO(obj[\"Body\"].read())\n\n dfs = {}\n if self.__is_zip(key_name):\n zf = ZipFile(buffer)\n\n if len(zf.namelist()) == 0:\n raise Exception(f'Could not load data frame because zip file {key_name} is empty.')\n\n zf = ZipFile(buffer)\n for file_name in zf.namelist():\n dfs[file_name.replace('.csv', '')] = pd.read_csv(BytesIO(zf.read(file_name)))\n else:\n dfs[key_name.replace('.csv', '')] = pd.read_csv(buffer)\n\n return dfs\n"
] | [
[
"pandas.read_csv"
]
] |
tevang/chemprop | [
"357cbd12039f97a9f58ce6493211cc49bfb8db1d"
] | [
"chemprop/data/utils.py"
] | [
"from collections import OrderedDict, defaultdict\nimport csv\nfrom logging import Logger\nimport pickle\nfrom random import Random\nfrom typing import List, Set, Tuple, Union\nimport os\n\nfrom rdkit import Chem\nimport numpy as np\nfrom tqdm import tqdm\n\nfrom .data import MoleculeDatapoint, MoleculeDataset, make_mols\nfrom .scaffold import log_scaffold_stats, scaffold_split\nfrom chemprop.args import PredictArgs, TrainArgs\nfrom chemprop.features import load_features, load_valid_atom_or_bond_features, is_mol\n\ndef get_header(path: str) -> List[str]:\n \"\"\"\n Returns the header of a data CSV file.\n\n :param path: Path to a CSV file.\n :return: A list of strings containing the strings in the comma-separated header.\n \"\"\"\n with open(path) as f:\n header = next(csv.reader(f))\n\n return header\n\n\ndef preprocess_smiles_columns(path: str,\n smiles_columns: Union[str, List[str]] = None,\n number_of_molecules: int = 1) -> List[str]:\n \"\"\"\n Preprocesses the :code:`smiles_columns` variable to ensure that it is a list of column\n headings corresponding to the columns in the data file holding SMILES. Assumes file has a header.\n\n :param path: Path to a CSV file.\n :param smiles_columns: The names of the columns containing SMILES.\n By default, uses the first :code:`number_of_molecules` columns.\n :param number_of_molecules: The number of molecules with associated SMILES for each\n data point.\n :return: The preprocessed version of :code:`smiles_columns` which is guaranteed to be a list.\n \"\"\"\n\n if smiles_columns is None:\n if os.path.isfile(path):\n columns = get_header(path)\n smiles_columns = columns[:number_of_molecules]\n else:\n smiles_columns = [None]*number_of_molecules\n else:\n if not isinstance(smiles_columns,list):\n smiles_columns=[smiles_columns]\n if os.path.isfile(path):\n columns = get_header(path)\n if len(smiles_columns) != number_of_molecules:\n raise ValueError('Length of smiles_columns must match number_of_molecules.')\n if any([smiles not in columns for smiles in smiles_columns]):\n raise ValueError('Provided smiles_columns do not match the header of data file.')\n\n return smiles_columns\n\n\ndef get_task_names(path: str,\n smiles_columns: Union[str, List[str]] = None,\n target_columns: List[str] = None,\n ignore_columns: List[str] = None) -> List[str]:\n \"\"\"\n Gets the task names from a data CSV file.\n\n If :code:`target_columns` is provided, returns `target_columns`.\n Otherwise, returns all columns except the :code:`smiles_columns`\n (or the first column, if the :code:`smiles_columns` is None) and\n the :code:`ignore_columns`.\n\n :param path: Path to a CSV file.\n :param smiles_columns: The names of the columns containing SMILES.\n By default, uses the first :code:`number_of_molecules` columns.\n :param target_columns: Name of the columns containing target values. By default, uses all columns\n except the :code:`smiles_columns` and the :code:`ignore_columns`.\n :param ignore_columns: Name of the columns to ignore when :code:`target_columns` is not provided.\n :return: A list of task names.\n \"\"\"\n if target_columns is not None:\n return target_columns\n\n columns = get_header(path)\n\n if not isinstance(smiles_columns, list):\n smiles_columns = preprocess_smiles_columns(path=path, smiles_columns=smiles_columns)\n\n ignore_columns = set(smiles_columns + ([] if ignore_columns is None else ignore_columns))\n\n target_names = [column for column in columns if column not in ignore_columns]\n\n return target_names\n\n\ndef get_data_weights(path: str) -> List[float]:\n \"\"\"\n Returns the list of data weights for the loss function as stored in a CSV file.\n\n :param path: Path to a CSV file.\n :return: A list of floats containing the data weights.\n \"\"\"\n weights = []\n with open(path) as f:\n reader=csv.reader(f)\n next(reader) #skip header row\n for line in reader:\n weights.append(float(line[0]))\n # normalize the data weights\n avg_weight=sum(weights)/len(weights)\n weights = [w/avg_weight for w in weights]\n if min(weights) < 0:\n raise ValueError('Data weights must be non-negative for each datapoint.')\n return weights\n\n\ndef get_smiles(path: str,\n smiles_columns: Union[str, List[str]] = None,\n number_of_molecules: int = 1,\n header: bool = True,\n flatten: bool = False\n ) -> Union[List[str], List[List[str]]]:\n \"\"\"\n Returns the SMILES from a data CSV file.\n\n :param path: Path to a CSV file.\n :param smiles_columns: A list of the names of the columns containing SMILES.\n By default, uses the first :code:`number_of_molecules` columns.\n :param number_of_molecules: The number of molecules for each data point. Not necessary if\n the names of smiles columns are previously processed.\n :param header: Whether the CSV file contains a header.\n :param flatten: Whether to flatten the returned SMILES to a list instead of a list of lists.\n :return: A list of SMILES or a list of lists of SMILES, depending on :code:`flatten`.\n \"\"\"\n if smiles_columns is not None and not header:\n raise ValueError('If smiles_column is provided, the CSV file must have a header.')\n\n if not isinstance(smiles_columns, list) and header:\n smiles_columns = preprocess_smiles_columns(path=path, smiles_columns=smiles_columns, number_of_molecules=number_of_molecules)\n\n with open(path) as f:\n if header:\n reader = csv.DictReader(f)\n else:\n reader = csv.reader(f)\n smiles_columns = list(range(number_of_molecules))\n\n smiles = [[row[c] for c in smiles_columns] for row in reader]\n\n if flatten:\n smiles = [smile for smiles_list in smiles for smile in smiles_list]\n\n return smiles\n\n\ndef filter_invalid_smiles(data: MoleculeDataset) -> MoleculeDataset:\n \"\"\"\n Filters out invalid SMILES.\n\n :param data: A :class:`~chemprop.data.MoleculeDataset`.\n :return: A :class:`~chemprop.data.MoleculeDataset` with only the valid molecules.\n \"\"\"\n return MoleculeDataset([datapoint for datapoint in tqdm(data)\n if all(s != '' for s in datapoint.smiles) and all(m is not None for m in datapoint.mol)\n and all(m.GetNumHeavyAtoms() > 0 for m in datapoint.mol if not isinstance(m, tuple))\n and all(m[0].GetNumHeavyAtoms() + m[1].GetNumHeavyAtoms() > 0 for m in datapoint.mol if isinstance(m, tuple))])\n\n\ndef get_invalid_smiles_from_file(path: str = None,\n smiles_columns: Union[str, List[str]] = None,\n header: bool = True,\n reaction: bool = False,\n ) -> Union[List[str], List[List[str]]]:\n \"\"\"\n Returns the invalid SMILES from a data CSV file.\n\n :param path: Path to a CSV file.\n :param smiles_columns: A list of the names of the columns containing SMILES.\n By default, uses the first :code:`number_of_molecules` columns.\n :param header: Whether the CSV file contains a header.\n :param reaction: Boolean whether the SMILES strings are to be treated as a reaction.\n :return: A list of lists of SMILES, for the invalid SMILES in the file.\n \"\"\"\n smiles = get_smiles(path=path, smiles_columns=smiles_columns, header=header)\n\n invalid_smiles = get_invalid_smiles_from_list(smiles=smiles, reaction=reaction)\n\n return invalid_smiles\n\n\ndef get_invalid_smiles_from_list(smiles: List[List[str]], reaction: bool = False) -> List[List[str]]:\n \"\"\"\n Returns the invalid SMILES from a list of lists of SMILES strings.\n\n :param smiles: A list of list of SMILES.\n :param reaction: Boolean whether the SMILES strings are to be treated as a reaction.\n :return: A list of lists of SMILES, for the invalid SMILES among the lists provided.\n \"\"\"\n invalid_smiles = []\n\n # If the first SMILES in the column is a molecule, the remaining SMILES in the same column should all be a molecule.\n # Similarly, if the first SMILES in the column is a reaction, the remaining SMILES in the same column should all\n # correspond to reaction. Therefore, get `is_mol_list` only using the first element in smiles.\n is_mol_list = [is_mol(s) for s in smiles[0]]\n is_reaction_list = [True if not x and reaction else False for x in is_mol_list]\n is_explicit_h_list = [False for x in is_mol_list] # set this to False as it is not needed for invalid SMILES check\n is_adding_hs_list = [False for x in is_mol_list] # set this to False as it is not needed for invalid SMILES check\n\n for mol_smiles in smiles:\n mols = make_mols(smiles=mol_smiles, reaction_list=is_reaction_list, keep_h_list=is_explicit_h_list,\n add_h_list=is_adding_hs_list)\n if any(s == '' for s in mol_smiles) or \\\n any(m is None for m in mols) or \\\n any(m.GetNumHeavyAtoms() == 0 for m in mols if not isinstance(m, tuple)) or \\\n any(m[0].GetNumHeavyAtoms() + m[1].GetNumHeavyAtoms() == 0 for m in mols if isinstance(m, tuple)):\n\n invalid_smiles.append(mol_smiles)\n\n return invalid_smiles\n\n\ndef get_data(path: str,\n smiles_columns: Union[str, List[str]] = None,\n target_columns: List[str] = None,\n ignore_columns: List[str] = None,\n skip_invalid_smiles: bool = True,\n args: Union[TrainArgs, PredictArgs] = None,\n data_weights_path: str = None,\n features_path: List[str] = None,\n features_generator: List[str] = None,\n phase_features_path: str = None,\n atom_descriptors_path: str = None,\n bond_features_path: str = None,\n max_data_size: int = None,\n store_row: bool = False,\n logger: Logger = None,\n loss_function: str = None,\n skip_none_targets: bool = False) -> MoleculeDataset:\n \"\"\"\n Gets SMILES and target values from a CSV file.\n\n :param path: Path to a CSV file.\n :param smiles_columns: The names of the columns containing SMILES.\n By default, uses the first :code:`number_of_molecules` columns.\n :param target_columns: Name of the columns containing target values. By default, uses all columns\n except the :code:`smiles_column` and the :code:`ignore_columns`.\n :param ignore_columns: Name of the columns to ignore when :code:`target_columns` is not provided.\n :param skip_invalid_smiles: Whether to skip and filter out invalid smiles using :func:`filter_invalid_smiles`.\n :param args: Arguments, either :class:`~chemprop.args.TrainArgs` or :class:`~chemprop.args.PredictArgs`.\n :param data_weights_path: A path to a file containing weights for each molecule in the loss function.\n :param features_path: A list of paths to files containing features. If provided, it is used\n in place of :code:`args.features_path`.\n :param features_generator: A list of features generators to use. If provided, it is used\n in place of :code:`args.features_generator`.\n :param phase_features_path: A path to a file containing phase features as applicable to spectra.\n :param atom_descriptors_path: The path to the file containing the custom atom descriptors.\n :param bond_features_path: The path to the file containing the custom bond features.\n :param max_data_size: The maximum number of data points to load.\n :param logger: A logger for recording output.\n :param store_row: Whether to store the raw CSV row in each :class:`~chemprop.data.data.MoleculeDatapoint`.\n :param skip_none_targets: Whether to skip targets that are all 'None'. This is mostly relevant when --target_columns\n are passed in, so only a subset of tasks are examined.\n :param loss_function: The loss function to be used in training.\n :return: A :class:`~chemprop.data.MoleculeDataset` containing SMILES and target values along\n with other info such as additional features when desired.\n \"\"\"\n debug = logger.debug if logger is not None else print\n\n if args is not None:\n # Prefer explicit function arguments but default to args if not provided\n smiles_columns = smiles_columns if smiles_columns is not None else args.smiles_columns\n target_columns = target_columns if target_columns is not None else args.target_columns\n ignore_columns = ignore_columns if ignore_columns is not None else args.ignore_columns\n features_path = features_path if features_path is not None else args.features_path\n features_generator = features_generator if features_generator is not None else args.features_generator\n phase_features_path = phase_features_path if phase_features_path is not None else args.phase_features_path\n atom_descriptors_path = atom_descriptors_path if atom_descriptors_path is not None \\\n else args.atom_descriptors_path\n bond_features_path = bond_features_path if bond_features_path is not None \\\n else args.bond_features_path\n max_data_size = max_data_size if max_data_size is not None else args.max_data_size\n loss_function = loss_function if loss_function is not None else args.loss_function\n\n if not isinstance(smiles_columns, list):\n smiles_columns = preprocess_smiles_columns(path=path, smiles_columns=smiles_columns)\n\n max_data_size = max_data_size or float('inf')\n\n # Load features\n if features_path is not None:\n features_data = []\n for feat_path in features_path:\n features_data.append(load_features(feat_path)) # each is num_data x num_features\n features_data = np.concatenate(features_data, axis=1)\n else:\n features_data = None\n \n if phase_features_path is not None:\n phase_features = load_features(phase_features_path)\n for d_phase in phase_features:\n if not (d_phase.sum() == 1 and np.count_nonzero(d_phase) == 1):\n raise ValueError('Phase features must be one-hot encoded.')\n if features_data is not None:\n features_data = np.concatenate((features_data,phase_features), axis=1)\n else: # if there are no other molecular features, phase features become the only molecular features\n features_data = np.array(phase_features)\n else:\n phase_features = None\n\n # Load data weights\n if data_weights_path is not None:\n data_weights = get_data_weights(data_weights_path)\n else:\n data_weights = None\n\n # By default, the targets columns are all the columns except the SMILES column\n if target_columns is None:\n target_columns = get_task_names(\n path=path,\n smiles_columns=smiles_columns,\n target_columns=target_columns,\n ignore_columns=ignore_columns,\n )\n\n # Find targets provided as inequalities\n if loss_function == 'bounded_mse':\n gt_targets, lt_targets = get_inequality_targets(path=path, target_columns=target_columns)\n else:\n gt_targets, lt_targets = None, None\n\n # Load data\n with open(path) as f:\n reader = csv.DictReader(f)\n fieldnames = reader.fieldnames\n if any([c not in fieldnames for c in smiles_columns]):\n raise ValueError(f'Data file did not contain all provided smiles columns: {smiles_columns}. Data file field names are: {fieldnames}')\n if any([c not in fieldnames for c in target_columns]):\n raise ValueError(f'Data file did not contain all provided target columns: {target_columns}. Data file field names are: {fieldnames}')\n\n all_smiles, all_targets, all_rows, all_features, all_phase_features, all_weights, all_gt, all_lt = [], [], [], [], [], [], [], []\n for i, row in enumerate(tqdm(reader)):\n smiles = [row[c] for c in smiles_columns]\n\n targets = []\n for column in target_columns:\n value = row[column]\n if value in ['','nan']:\n targets.append(None)\n elif '>' in value or '<' in value:\n if loss_function == 'bounded_mse':\n targets.append(float(value.strip('<>')))\n else:\n raise ValueError('Inequality found in target data. To use inequality targets (> or <), the regression loss function bounded_mse must be used.')\n else:\n targets.append(float(value))\n\n # Check whether all targets are None and skip if so\n if skip_none_targets and all(x is None for x in targets):\n continue\n\n all_smiles.append(smiles)\n all_targets.append(targets)\n\n if features_data is not None:\n all_features.append(features_data[i])\n \n if phase_features is not None:\n all_phase_features.append(phase_features[i])\n\n if data_weights is not None:\n all_weights.append(data_weights[i])\n\n if gt_targets is not None:\n all_gt.append(gt_targets[i])\n\n if lt_targets is not None:\n all_lt.append(lt_targets[i])\n\n if store_row:\n all_rows.append(row)\n\n if len(all_smiles) >= max_data_size:\n break\n\n atom_features = None\n atom_descriptors = None\n if args is not None and args.atom_descriptors is not None:\n try:\n descriptors = load_valid_atom_or_bond_features(atom_descriptors_path, [x[0] for x in all_smiles])\n except Exception as e:\n raise ValueError(f'Failed to load or validate custom atomic descriptors or features: {e}')\n\n if args.atom_descriptors == 'feature':\n atom_features = descriptors\n elif args.atom_descriptors == 'descriptor':\n atom_descriptors = descriptors\n\n bond_features = None\n if args is not None and args.bond_features_path is not None:\n try:\n bond_features = load_valid_atom_or_bond_features(bond_features_path, [x[0] for x in all_smiles])\n except Exception as e:\n raise ValueError(f'Failed to load or validate custom bond features: {e}')\n\n data = MoleculeDataset([\n MoleculeDatapoint(\n smiles=smiles,\n targets=targets,\n row=all_rows[i] if store_row else None,\n data_weight=all_weights[i] if data_weights is not None else None,\n gt_targets=all_gt[i] if gt_targets is not None else None,\n lt_targets=all_lt[i] if lt_targets is not None else None,\n features_generator=features_generator,\n features=all_features[i] if features_data is not None else None,\n phase_features=all_phase_features[i] if phase_features is not None else None,\n atom_features=atom_features[i] if atom_features is not None else None,\n atom_descriptors=atom_descriptors[i] if atom_descriptors is not None else None,\n bond_features=bond_features[i] if bond_features is not None else None,\n overwrite_default_atom_features=args.overwrite_default_atom_features if args is not None else False,\n overwrite_default_bond_features=args.overwrite_default_bond_features if args is not None else False\n ) for i, (smiles, targets) in tqdm(enumerate(zip(all_smiles, all_targets)),\n total=len(all_smiles))\n ])\n\n # Filter out invalid SMILES\n if skip_invalid_smiles:\n original_data_len = len(data)\n data = filter_invalid_smiles(data)\n\n if len(data) < original_data_len:\n debug(f'Warning: {original_data_len - len(data)} SMILES are invalid.')\n\n return data\n\n\ndef get_data_from_smiles(smiles: List[List[str]],\n skip_invalid_smiles: bool = True,\n logger: Logger = None,\n features_generator: List[str] = None) -> MoleculeDataset:\n \"\"\"\n Converts a list of SMILES to a :class:`~chemprop.data.MoleculeDataset`.\n\n :param smiles: A list of lists of SMILES with length depending on the number of molecules.\n :param skip_invalid_smiles: Whether to skip and filter out invalid smiles using :func:`filter_invalid_smiles`\n :param logger: A logger for recording output.\n :param features_generator: List of features generators.\n :return: A :class:`~chemprop.data.MoleculeDataset` with all of the provided SMILES.\n \"\"\"\n debug = logger.debug if logger is not None else print\n\n data = MoleculeDataset([\n MoleculeDatapoint(\n smiles=smile,\n row=OrderedDict({'smiles': smile}),\n features_generator=features_generator\n ) for smile in smiles\n ])\n\n # Filter out invalid SMILES\n if skip_invalid_smiles:\n original_data_len = len(data)\n data = filter_invalid_smiles(data)\n\n if len(data) < original_data_len:\n debug(f'Warning: {original_data_len - len(data)} SMILES are invalid.')\n\n return data\n\n\ndef get_inequality_targets(path: str, target_columns: List[str] = None) -> List[str]:\n \"\"\"\n\n \"\"\"\n gt_targets = []\n lt_targets = []\n\n with open(path) as f:\n reader = csv.DictReader(f)\n for line in reader:\n values = [line[col] for col in target_columns]\n gt_targets.append(['>' in val for val in values])\n lt_targets.append(['<' in val for val in values])\n if any(['<' in val and '>' in val for val in values]):\n raise ValueError(f'A target value in csv file {path} contains both \">\" and \"<\" symbols. Inequality targets must be on one edge and not express a range.')\n\n return gt_targets, lt_targets\n\n\ndef split_data(data: MoleculeDataset,\n split_type: str = 'random',\n sizes: Tuple[float, float, float] = (0.8, 0.1, 0.1),\n key_molecule_index: int = 0,\n seed: int = 0,\n num_folds: int = 1,\n args: TrainArgs = None,\n logger: Logger = None) -> Tuple[MoleculeDataset,\n MoleculeDataset,\n MoleculeDataset]:\n r\"\"\"\n Splits data into training, validation, and test splits.\n\n :param data: A :class:`~chemprop.data.MoleculeDataset`.\n :param split_type: Split type.\n :param sizes: A length-3 tuple with the proportions of data in the train, validation, and test sets.\n :param key_molecule_index: For data with multiple molecules, this sets which molecule will be considered during splitting.\n :param seed: The random seed to use before shuffling data.\n :param num_folds: Number of folds to create (only needed for \"cv\" split type).\n :param args: A :class:`~chemprop.args.TrainArgs` object.\n :param logger: A logger for recording output.\n :return: A tuple of :class:`~chemprop.data.MoleculeDataset`\\ s containing the train,\n validation, and test splits of the data.\n \"\"\"\n if not (len(sizes) == 3 and np.isclose(sum(sizes), 1)):\n raise ValueError(f\"Split sizes do not sum to 1. Received train/val/test splits: {sizes}\")\n if any([size < 0 for size in sizes]):\n raise ValueError(f\"Split sizes must be non-negative. Received train/val/test splits: {sizes}\")\n\n random = Random(seed)\n\n if args is not None:\n folds_file, val_fold_index, test_fold_index = \\\n args.folds_file, args.val_fold_index, args.test_fold_index\n else:\n folds_file = val_fold_index = test_fold_index = None\n \n if split_type == 'crossval':\n index_set = args.crossval_index_sets[args.seed]\n data_split = []\n for split in range(3):\n split_indices = []\n for index in index_set[split]:\n with open(os.path.join(args.crossval_index_dir, f'{index}.pkl'), 'rb') as rf:\n split_indices.extend(pickle.load(rf))\n data_split.append([data[i] for i in split_indices])\n train, val, test = tuple(data_split)\n return MoleculeDataset(train), MoleculeDataset(val), MoleculeDataset(test)\n\n elif split_type in {'cv', 'cv-no-test'}:\n if num_folds <= 1 or num_folds > len(data):\n raise ValueError(f'Number of folds for cross-validation must be between 2 and the number of valid datapoints ({len(data)}), inclusive.')\n\n random = Random(0)\n\n indices = np.tile(np.arange(num_folds), 1 + len(data) // num_folds)[:len(data)]\n random.shuffle(indices)\n test_index = seed % num_folds\n val_index = (seed + 1) % num_folds\n\n train, val, test = [], [], []\n for d, index in zip(data, indices):\n if index == test_index and split_type != 'cv-no-test':\n test.append(d)\n elif index == val_index:\n val.append(d)\n else:\n train.append(d)\n\n return MoleculeDataset(train), MoleculeDataset(val), MoleculeDataset(test)\n\n elif split_type == 'index_predetermined':\n split_indices = args.crossval_index_sets[args.seed]\n\n if len(split_indices) != 3:\n raise ValueError('Split indices must have three splits: train, validation, and test')\n\n data_split = []\n for split in range(3):\n data_split.append([data[i] for i in split_indices[split]])\n train, val, test = tuple(data_split)\n return MoleculeDataset(train), MoleculeDataset(val), MoleculeDataset(test)\n\n elif split_type == 'predetermined':\n if not val_fold_index and sizes[2] != 0:\n raise ValueError('Test size must be zero since test set is created separately '\n 'and we want to put all other data in train and validation')\n\n if folds_file is None:\n raise ValueError('arg \"folds_file\" can not be None!')\n if test_fold_index is None:\n raise ValueError('arg \"test_fold_index\" can not be None!')\n\n try:\n with open(folds_file, 'rb') as f:\n all_fold_indices = pickle.load(f)\n except UnicodeDecodeError:\n with open(folds_file, 'rb') as f:\n all_fold_indices = pickle.load(f, encoding='latin1') # in case we're loading indices from python2\n\n log_scaffold_stats(data, all_fold_indices, logger=logger)\n\n folds = [[data[i] for i in fold_indices] for fold_indices in all_fold_indices]\n\n test = folds[test_fold_index]\n if val_fold_index is not None:\n val = folds[val_fold_index]\n\n train_val = []\n for i in range(len(folds)):\n if i != test_fold_index and (val_fold_index is None or i != val_fold_index):\n train_val.extend(folds[i])\n\n if val_fold_index is not None:\n train = train_val\n else:\n random.shuffle(train_val)\n train_size = int(sizes[0] * len(train_val))\n train = train_val[:train_size]\n val = train_val[train_size:]\n\n return MoleculeDataset(train), MoleculeDataset(val), MoleculeDataset(test)\n\n elif split_type == 'scaffold_balanced':\n return scaffold_split(data, sizes=sizes, balanced=True, key_molecule_index=key_molecule_index, seed=seed, logger=logger)\n\n elif split_type == 'random_with_repeated_smiles': # Use to constrain data with the same smiles go in the same split.\n smiles_dict=defaultdict(set)\n for i,smiles in enumerate(data.smiles()):\n smiles_dict[smiles[key_molecule_index]].add(i)\n index_sets=list(smiles_dict.values())\n random.seed(seed)\n random.shuffle(index_sets)\n train,val,test=[],[],[]\n train_size = int(sizes[0] * len(data))\n val_size = int(sizes[1] * len(data))\n for index_set in index_sets:\n if len(train)+len(index_set) <= train_size:\n train += index_set\n elif len(val) + len(index_set) <= val_size:\n val += index_set\n else:\n test += index_set\n train = [data[i] for i in train]\n val = [data[i] for i in val]\n test = [data[i] for i in test]\n\n return MoleculeDataset(train), MoleculeDataset(val), MoleculeDataset(test)\n\n elif split_type == 'random':\n indices = list(range(len(data)))\n random.shuffle(indices)\n\n train_size = int(sizes[0] * len(data))\n train_val_size = int((sizes[0] + sizes[1]) * len(data))\n\n train = [data[i] for i in indices[:train_size]]\n val = [data[i] for i in indices[train_size:train_val_size]]\n test = [data[i] for i in indices[train_val_size:]]\n\n return MoleculeDataset(train), MoleculeDataset(val), MoleculeDataset(test)\n\n else:\n raise ValueError(f'split_type \"{split_type}\" not supported.')\n\n\ndef get_class_sizes(data: MoleculeDataset, proportion: bool = True) -> List[List[float]]:\n \"\"\"\n Determines the proportions of the different classes in a classification dataset.\n\n :param data: A classification :class:`~chemprop.data.MoleculeDataset`.\n :param proportion: Choice of whether to return proportions for class size or counts.\n :return: A list of lists of class proportions. Each inner list contains the class proportions for a task.\n \"\"\"\n targets = data.targets()\n\n # Filter out Nones\n valid_targets = [[] for _ in range(data.num_tasks())]\n for i in range(len(targets)):\n for task_num in range(len(targets[i])):\n if targets[i][task_num] is not None:\n valid_targets[task_num].append(targets[i][task_num])\n\n class_sizes = []\n for task_targets in valid_targets:\n if set(np.unique(task_targets)) > {0, 1}:\n raise ValueError('Classification dataset must only contains 0s and 1s.')\n if proportion:\n try:\n ones = np.count_nonzero(task_targets) / len(task_targets)\n except ZeroDivisionError:\n ones = float('nan')\n print('Warning: class has no targets')\n class_sizes.append([1 - ones, ones])\n else: # counts\n ones = np.count_nonzero(task_targets)\n class_sizes.append([len(task_targets) - ones, ones])\n\n return class_sizes\n\n\n# TODO: Validate multiclass dataset type.\ndef validate_dataset_type(data: MoleculeDataset, dataset_type: str) -> None:\n \"\"\"\n Validates the dataset type to ensure the data matches the provided type.\n\n :param data: A :class:`~chemprop.data.MoleculeDataset`.\n :param dataset_type: The dataset type to check.\n \"\"\"\n target_set = {target for targets in data.targets() for target in targets} - {None}\n classification_target_set = {0, 1}\n\n if dataset_type == 'classification' and not (target_set <= classification_target_set):\n raise ValueError('Classification data targets must only be 0 or 1 (or None). '\n 'Please switch to regression.')\n elif dataset_type == 'regression' and target_set <= classification_target_set:\n raise ValueError('Regression data targets must be more than just 0 or 1 (or None). '\n 'Please switch to classification.')\n\n\ndef validate_data(data_path: str) -> Set[str]:\n \"\"\"\n Validates a data CSV file, returning a set of errors.\n\n :param data_path: Path to a data CSV file.\n :return: A set of error messages.\n \"\"\"\n errors = set()\n\n header = get_header(data_path)\n\n with open(data_path) as f:\n reader = csv.reader(f)\n next(reader) # Skip header\n\n smiles, targets = [], []\n for line in reader:\n smiles.append(line[0])\n targets.append(line[1:])\n\n # Validate header\n if len(header) == 0:\n errors.add('Empty header')\n elif len(header) < 2:\n errors.add('Header must include task names.')\n\n mol = Chem.MolFromSmiles(header[0])\n if mol is not None:\n errors.add('First row is a SMILES string instead of a header.')\n\n # Validate smiles\n for smile in tqdm(smiles, total=len(smiles)):\n mol = Chem.MolFromSmiles(smile)\n if mol is None:\n errors.add('Data includes an invalid SMILES.')\n\n # Validate targets\n num_tasks_set = set(len(mol_targets) for mol_targets in targets)\n if len(num_tasks_set) != 1:\n errors.add('Inconsistent number of tasks for each molecule.')\n\n if len(num_tasks_set) == 1:\n num_tasks = num_tasks_set.pop()\n if num_tasks != len(header) - 1:\n errors.add('Number of tasks for each molecule doesn\\'t match number of tasks in header.')\n\n unique_targets = set(np.unique([target for mol_targets in targets for target in mol_targets]))\n\n if unique_targets <= {''}:\n errors.add('All targets are missing.')\n\n for target in unique_targets - {''}:\n try:\n float(target)\n except ValueError:\n errors.add('Found a target which is not a number.')\n\n return errors\n"
] | [
[
"numpy.unique",
"numpy.arange",
"numpy.concatenate",
"numpy.count_nonzero",
"numpy.array"
]
] |
Ewpratten/colourscale | [
"d5d3090b4d154980ff8de76ea30fbfe721ad80e2"
] | [
"colourscale/imsort.py"
] | [
"import argparse\nfrom PIL import Image\nimport numpy as np\n\n## Keys ##\nclass Keys(object):\n overall = lambda x: (int(x[0]) + int(x[1]) + int(x[2]))\n red = lambda x: (int(x[0]))\n green = lambda x: (int(x[1]))\n blue = lambda x: (int(x[2]))\n avg = lambda x: (int(x[0]) + int(x[1]) + int(x[2])) / 3\n lum = lambda x: round(int(x[0]) * 299 / 1000 + int(x[1]) * 587 / 1000 + int(x[2]) * 114 / 1000)\n\n\ndef avg(li):\n output = 0\n for i in li:\n x = i\n output += round(int(x[0]) * 299 / 1000 + int(x[1]) * 587 / 1000 + int(x[2]) * 114 / 1000)\n return output / len(li)\n\ndef write(im, name, imname):\n arr = np.array(im, dtype=np.uint8)\n im2 = Image.fromarray(arr)\n\n im2.save(imname[0] + name + imname[len(imname) - 1])\n\ndef csort(inp):\n return sorted(inp, key=Keys.lum)\n\ndef clsort(img):\n output = []\n # for row in img:\n return sorted(img, key=lambda x: (avg(x)))\n\n# def \n\n\n\n\n## Create an args parser ##\nparser = argparse.ArgumentParser()\nparser.add_argument(\"img\", help=\"Path to desired image\")\nargs = parser.parse_args()\n\n## Load the image ##\ntry:\n im = Image.open(args.img)\nexcept FileNotFoundError:\n print(\"Invalid file\")\n exit(1)\nprint(f\"Loaded {args.img}\")\n\n## Build colour map ##\nraw_im = np.asarray(im)\n\n## Detect spacing ##\n# spac = 0\n# while True:\n# if raw_im[spac][spac][2] == 255:\n# break\n# else:\n# spac += 1\n# spac += 1\n\n# print(spac)\n\n## Build squash_im ##\nsr_im = []\n\nfor i, row in enumerate(raw_im):\n # sr_cl = []\n\n sr_im.append(csort(row))\n\n # for j, col in enumerate(row):\n\n # # Build squash\n # if (i % spac) + (j % spac) == (spac * 2) - 2:\n\n # # Check bounds\n # if j <= spac:\n # sr_cl.append((col[0], col[1], col[2]))\n # else:\n # # Expand\n # prev = row[j - spac]\n # curr = col\n\n # for k in range(spac):\n # val = [0, 0, 0]\n # val[0] = scl(prev[0], curr[0], spac, k)\n # val[1] = scl(prev[1], curr[1], spac, k)\n # val[2] = scl(prev[2], curr[2], spac, k)\n\n # itp = (val[0], val[1], val[2])\n # lv = clrz(row[j-k][0])\n # # itp = (0,0,0)\n # sr_cl.append(cbn(itp, lv))\n\n # # sr_cl.append(clrz(curr[0]))\n\n # if sr_cl != []:\n # sr_im.append(sr_cl)\n\nsr_im = clsort(sr_im)\n\n## Output image ##\nimname = args.img.split(\".\")\n\nwrite(sr_im, \".sr.\", imname)\n"
] | [
[
"numpy.asarray",
"numpy.array"
]
] |
seanyen/eigenpy | [
"e164f03eb13b5fc531dd6b5e7e0f28560f405464"
] | [
"unittest/python/test_LDLT.py"
] | [
"import eigenpy\n\nimport numpy as np\nimport numpy.linalg as la\n\ndim = 100\nA = np.random.rand(dim,dim)\n\nA = (A + A.T)*0.5 + np.diag(10. + np.random.rand(dim))\n\nldlt = eigenpy.LDLT(A)\n\nL = ldlt.matrixL() \nD = ldlt.vectorD() \nP = ldlt.transpositionsP() \n\nassert eigenpy.is_approx(np.transpose(P).dot(L.dot(np.diag(D).dot(np.transpose(L).dot(P)))),A)\n\nX = np.random.rand(dim,20)\nB = A.dot(X)\nX_est = ldlt.solve(B)\nassert eigenpy.is_approx(X,X_est)\nassert eigenpy.is_approx(A.dot(X_est),B)\n"
] | [
[
"numpy.diag",
"numpy.random.rand",
"numpy.transpose"
]
] |
YuMao1993/HumanRecognition | [
"5043a03a3904a3710030221c4f71c7416edc9c82"
] | [
"pyHumanRecog/CRF_opt.py"
] | [
"\"\"\" CRF_opt\nThis module contains code for post-processing the\nprediction result by incorporating photo-level\ncontext using CRF via loopy belief propagation(LBP).\n@Yu\n\"\"\"\nimport sklearn.preprocessing\nimport numpy as np\nimport CRF_opt_config as config\n\n\nclass CRFOptimizer:\n\n def __init__(self):\n self._compat_mat = None\n\n def build_compat_func(self, photos, lbl_map):\n \"\"\"\n construct compatibility function for all identities within photos\n :return:\n \"\"\"\n num_identity = len(lbl_map)\n # print(num_identity)\n compat_mat = np.empty((num_identity, num_identity))\n compat_mat.fill(config.compat_label_not_co_occur_val)\n for i in range(num_identity):\n compat_mat[i][i] = config.compat_label_equal_val\n\n for photo in photos:\n for i in range(len(photo.human_detections)):\n for j in range(i + 1, len(photo.human_detections)):\n id1 = lbl_map[photo.human_detections[i].identity_id]\n id2 = lbl_map[photo.human_detections[j].identity_id]\n assert(id1 != id2)\n compat_mat[id1][id2] = config.compat_label_co_occur_val\n compat_mat[id2][id1] = config.compat_label_co_occur_val\n self._compat_mat = compat_mat\n return\n\n def run_LBP(self, scores):\n \"\"\"\n Running Loopy Belief Propagation(LBP)\n :param scores: class prediction scores of shape (N,M) where N is the number of instances and M is the number of identities\n :return: refined labels after LBP, shape is (N,)\n \"\"\"\n\n num_hidden_nodes = len(scores)\n num_labels = len(scores[0])\n\n # print('num_instances: {0}'.format(num_hidden_nodes))\n\n # message initialization\n messages_on_fly = np.empty((num_hidden_nodes, num_hidden_nodes, num_labels))\n messages_on_fly.fill(0.00001)\n for i in range(num_hidden_nodes):\n messages_on_fly[i, i, :] = 0\n\n new_message_on_fly = np.zeros((num_hidden_nodes, num_hidden_nodes, num_labels))\n\n # message passing\n for iter in range(config.num_iteration):\n # print('({1})iteration {0}...'.format(iter, num_hidden_nodes))\n for i in range(num_hidden_nodes):\n # at each iteration, every node will send messages to all of its neighboring nodes\n for j in range(num_hidden_nodes):\n if i == j:\n continue\n neighbor_contribs = messages_on_fly[:, i].sum(axis=0)\n msg = np.empty(num_labels)\n for kk in range(num_labels): # over recipient's label\n for k in range(num_labels): # over sender's label\n msg[kk] = max(msg[kk], scores[i, k] + self._compat_mat[kk, k] + neighbor_contribs[k])\n msg = sklearn.preprocessing.normalize(msg.reshape((1, -1)))\n new_message_on_fly[i, j] = msg\n messages_on_fly[:, :, :] = new_message_on_fly\n\n # get final belief\n belief = np.zeros((num_hidden_nodes, num_labels))\n for i in range(num_hidden_nodes):\n for j in range(num_labels):\n belief[i, j] = scores[i, j] + messages_on_fly[:, i, j].sum()\n predicts = np.argmax(belief, axis=1)\n predicts_before_refine = np.argmax(scores, axis=1)\n\n return predicts, predicts_before_refine\n"
] | [
[
"numpy.argmax",
"numpy.zeros",
"numpy.empty"
]
] |
larioandr/pyqumo | [
"67f3866004bddcc9b2246ad7983fc8561fc39301"
] | [
"tests/statistical_tests/test_distributions_from_pyqunet.py"
] | [
"import pyqumo.distributions as cd\n\nimport unittest\nimport numpy\n\n\nclass TestBase(unittest.TestCase):\n \"\"\"Base class for all distributions unit tests. Provides an array of\n descriptors and a number of test methods, each of which inspects a part\n of each descriptor.\n\n Each descriptor is a dictionary containing the following fields:\n\n - 'distribution': an object of pyqumo.distributions.Distribution,\n which is to be inspected\n\n Additionally a descriptor may contain other fields (e.g. 'rate', 'pmf' etc.)\n which are specific to a particular distribution.\n \"\"\"\n tests = [] # list of descriptors\n\n DEFAULT_GENERATE_SIZE = 10000\n DEFAULT_GENERATE_PRECISION = 1\n DEFAULT_PRECISION = 8\n DEFAULT_GRID_FUNCTION_VECTORIZED = False\n\n def assertAllClose(self, lvalue, rvalue,\n places=DEFAULT_PRECISION, msg=None):\n lv = numpy.asarray(lvalue)\n rv = numpy.asarray(rvalue)\n try:\n self.assertAlmostEqual(lv.item(), rv.item(), places, msg)\n except ValueError:\n tol = pow(10.0, -places)\n try:\n self.assertTrue(numpy.allclose(lv, rv, tol, tol),\n msg + \" (tol={})\".format(tol))\n except TypeError as err:\n raise TypeError(\"{}: {}\".format(repr(err), msg))\n except Exception as err:\n raise RuntimeError(\"{} -- {}\".format(repr(err), msg))\n\n def _check_test_descriptor(self, test_descriptor):\n\n def test_property(dist, descriptor):\n name = descriptor['name']\n expected = descriptor['value']\n precision = descriptor.get('precision', self.DEFAULT_PRECISION)\n try:\n value = getattr(dist, name)\n except Exception as err:\n raise RuntimeError(\"{} when testing {}.{}\".format(\n repr(err), dist, name))\n self.assertAllClose(\n value, expected, precision, \"{}.{}={}, expected={}\".format(\n dist, name, value, expected))\n\n def test_simple_function(dist, descriptor):\n name = descriptor['name']\n expected = descriptor['value']\n precision = descriptor.get('precision', self.DEFAULT_PRECISION)\n try:\n value = getattr(dist, name)()\n except Exception as err:\n raise RuntimeError(\"{} when testing {}.{}()\".format(\n repr(err), dist, name))\n self.assertAllClose(\n value, expected, precision, \"{}.{}()={}, expected={}\".format(\n dist, name, value, expected))\n\n def test_grid_function(dist, descriptor):\n name = descriptor['name']\n grid = descriptor['grid']\n precision = descriptor.get('precision', self.DEFAULT_PRECISION)\n vectorized = descriptor.get('vectorized',\n self.DEFAULT_GRID_FUNCTION_VECTORIZED)\n f = getattr(dist, name)\n\n # Check point-by-point (scalar style)\n for point in grid:\n args, expected = point[:-1], point[-1]\n try:\n value = f(*args)\n except Exception as err:\n raise RuntimeError(\"{} when testing {}.{}({})\".format(\n repr(err), dist, name, args))\n self.assertAllClose(value, expected, precision,\n \"{}.{}({})={}, expected={}\".format(\n dist, name, args, value, expected))\n\n if vectorized:\n arg = numpy.asarray([point[:-1] for point in grid])\n expected = numpy.asarray([[point[-1]]for point in grid])\n try:\n value = f(arg)\n except Exception as err:\n raise RuntimeError(\"{} when testing {}.{}({})\".format(\n repr(err), dist, name, arg))\n self.assertAllClose(value, expected, precision,\n \"{}.{}({})={}, expected={}\".format(\n dist, name, arg, value, expected))\n\n def test_complex_function(dist, descriptor):\n name = descriptor['name']\n args = descriptor.get('args', ())\n kwargs = descriptor.get('kwargs', {})\n calls = descriptor['calls']\n generator = descriptor.get('generator', False)\n default_precision = descriptor.get(\n 'precision', self.DEFAULT_PRECISION)\n\n try:\n ret = getattr(dist, name)(*args, **kwargs)\n except Exception as err:\n raise RuntimeError(\n \"{} when testing {}.{}(...) with args={}, kwargs={}\".format(\n repr(err), dist, name, args, kwargs))\n\n value = list(ret) if generator else ret\n for call_descriptor in calls:\n call_value = call_descriptor['call'](value)\n precision = call_descriptor.get('precision', default_precision)\n if 'as_value' in call_descriptor:\n expected = call_descriptor['as_value']\n elif 'as_property' in call_descriptor:\n property_name = call_descriptor['as_property']\n expected = getattr(dist, property_name)\n elif 'as_function' in call_descriptor:\n function_name = call_descriptor['as_function']\n expected = getattr(dist, function_name)()\n elif 'as_call' in call_descriptor:\n expected = call_descriptor['as_call'](dist)\n else:\n print(call_descriptor)\n raise KeyError\n self.assertAllClose(\n call_value, expected, precision,\n \"{}({}.{}({}))={}, expected={}\".format(\n str(call_descriptor['call']), dist, name, args,\n call_value, expected))\n\n def test_like_property(dist, alias, descriptor):\n name = descriptor['name']\n alias_name = descriptor.get('alias', name)\n precision = descriptor.get('precision', self.DEFAULT_PRECISION)\n try:\n value = getattr(dist, name)\n except Exception as err:\n raise RuntimeError(\"{} when testing {}.{}\".format(\n repr(err), dist, name))\n expected = getattr(alias, alias_name)\n self.assertAlmostEqual(\n value, expected, precision,\n \"{}.{}={}, expected={} [alias: {}.{}]\".format(\n dist, name, value, expected, alias, alias_name))\n\n def test_like_simple_function(dist, alias, descriptor):\n name = descriptor['name']\n alias_name = descriptor.get('alias', name)\n precision = descriptor.get('precision', self.DEFAULT_PRECISION)\n value = getattr(dist, name)()\n expected = getattr(alias, alias_name)()\n self.assertAllClose(\n value, expected, precision,\n \"{}.{}()={}, expected={} [alias: {}.{}()]\".format(\n dist, name, value, expected, alias, alias_name))\n\n def test_like_grid_function(dist, alias, descriptor):\n name = descriptor['name']\n alias_name = descriptor.get('alias', name)\n grid = descriptor['grid']\n precision = descriptor.get('precision', self.DEFAULT_PRECISION)\n vectorized = descriptor.get('vectorized',\n self.DEFAULT_GRID_FUNCTION_VECTORIZED)\n f = getattr(dist, name)\n alias_f = getattr(alias, alias_name)\n\n # Check point-by-point (scalar style)\n for point in grid:\n arg = numpy.asarray(point)\n try:\n value = f(*arg)\n except TypeError:\n arg = point\n try:\n value = f(arg)\n except Exception as err:\n raise RuntimeError(\"{} when testing {}.{}({})\".format(\n repr(err), dist, name, arg))\n else:\n expected = alias_f(arg)\n except Exception as err:\n raise RuntimeError(\"{} when testing {}.{}({})\".format(\n repr(err), dist, name, arg))\n else:\n expected = alias_f(*arg)\n self.assertAllClose(\n value, expected, precision,\n \"{}.{}({})={}, expected={} [alias: {}.{}(...)]\".format(\n dist, name, arg, value, expected, alias, alias_name))\n\n if vectorized:\n value = f(grid)\n expected = alias_f(grid)\n self.assertAllClose(\n value, expected, precision,\n \"{}.{}({})={}, expected={} [alias: {}.{}(...)]\".format(\n dist, name, grid, value, expected, alias, alias_name))\n\n def test_like(dist, descriptor):\n for alias in descriptor['alias']:\n for prop in descriptor.get('properties', []):\n test_like_property(dist, alias, prop)\n for fun in descriptor.get('functions', []):\n try:\n test_like_grid_function(dist, alias, fun)\n except KeyError:\n test_like_simple_function(dist, alias, fun)\n\n distribution = test_descriptor['distribution']\n for each in test_descriptor.get('properties', []):\n test_property(distribution, each)\n for each in test_descriptor.get('functions', []):\n try:\n test_grid_function(distribution, each)\n except KeyError:\n try:\n test_simple_function(distribution, each)\n except KeyError:\n test_complex_function(distribution, each)\n for each in test_descriptor.get('like', []):\n test_like(distribution, each)\n\n def test_descriptors(self):\n for descriptor in self.tests:\n self._check_test_descriptor(descriptor)\n\n\nclass TestExp(TestBase):\n def setUp(self):\n self.tests = [{\n 'distribution': cd.Exp(1.0),\n 'properties': [\n {'name': 'rate', 'value': 1.0},\n ],\n 'functions': [\n {'name': 'mean', 'value': 1.0},\n {'name': 'std', 'value': 1.0},\n {'name': 'var', 'value': 1.0},\n {'name': 'moment', 'grid': [(1, 1.0), (2, 2.0)]},\n {'name': 'pdf', 'precision': 4,\n 'grid': [(0.0, 1.0), (1.0, 0.36788), (2.0, 0.13533),\n (numpy.inf, 0.0)]},\n {'name': 'cdf', 'precision': 4,\n 'grid': [(0.0, 0.0), (1.0, 0.63212), (2.0, 0.86466),\n (numpy.inf, 1.0)]},\n {'name': 'generate', 'args': (25000,), 'precision': 1,\n 'generator': True,\n 'calls': [\n {'call': numpy.mean, 'as_value': 1.0, 'precision': 1},\n {'call': numpy.std, 'as_value': 1.0},\n {'call': numpy.var, 'as_function': 'mean'},\n {'call': lambda x: 1./numpy.mean(x), 'as_property': 'rate'},\n {'call': numpy.mean, 'as_call': lambda d: d.mean()}\n ]},\n {'name': 'sample', 'kwargs': {'shape': (25000,)},\n 'precision': 1, 'calls': [\n {'call': numpy.mean, 'as_function': 'mean'},\n {'call': numpy.std, 'as_function': 'std'},\n {'call': lambda x: x.shape, 'as_value': (25000,)}\n ]},\n {'name': 'sample', 'kwargs': {'shape': (2, 1)},\n 'precision': 1, 'calls': [\n {'call': lambda x: x.shape, 'as_value': (2, 1)}\n ]},\n {'name': 'sample', 'kwargs': {'shape': (5, 6, 7)},\n 'precision': 1, 'calls': [\n {'call': lambda x: x.shape, 'as_value': (5, 6, 7)}\n ]},\n ]\n }, {\n 'distribution': cd.Exp(2.0),\n 'properties': [\n {'name': 'rate', 'value': 2.0},\n ],\n 'functions': [\n {'name': 'mean', 'value': 0.5}, {'name': 'std', 'value': 0.5},\n {'name': 'var', 'value': 0.25},\n {'name': 'moment', 'grid': [(1, 0.5), (2, 0.5)]},\n {'name': 'pdf', 'precision': 4,\n 'grid': [(0.0, 2.0), (1.0, 0.27067), (2.0, 0.03663),\n (numpy.inf, 0.0)]},\n {'name': 'cdf', 'precision': 4,\n 'grid': [(0.0, 0.0), (1.0, 0.86467), (2.0, 0.98168),\n (numpy.inf, 1.0)]},\n {'name': 'generate', 'args': (25000,), 'precision': 1,\n 'generator': True,\n 'calls': [\n {'call': numpy.mean, 'as_function': 'mean'},\n {'call': numpy.std, 'as_function': 'std'},\n {'call': numpy.var, 'as_function': 'var'},\n ]},\n ]\n }]\n\n def test_fail_creation_with_zero_or_negative_rate(self):\n rates = [0, -1, -2, -numpy.inf]\n for rate in rates:\n with self.assertRaises(ValueError):\n cd.Exp(rate)\n\n\nclass TestErlang(TestBase):\n def setUp(self):\n self.tests = [{\n 'distribution': cd.Erlang(shape=1, rate=1.0),\n 'like': [{\n 'alias': [cd.Exp(1.0)],\n 'functions': [\n {'name': 'mean'}, {'name': 'var'}, {'name': 'std'},\n {'name': 'moment', 'grid': [1, 2, 3]},\n {'name': 'pdf', 'grid': [0.0, 1.0, 2.0, numpy.inf]},\n {'name': 'cdf', 'grid': [0.0, 1.0, 2.0, numpy.inf]}\n ]\n }],\n 'properties': [\n {'name': 'shape', 'value': 1},\n {'name': 'rate', 'value': 1.0}\n ],\n 'functions': [\n {'name': 'generate', 'args': (25000,), 'precision': 1,\n 'generator': True,\n 'calls': [\n {'call': numpy.mean, 'as_function': 'mean'},\n {'call': numpy.std, 'as_function': 'std'},\n {'call': numpy.var, 'as_function': 'var'},\n ]},\n {'name': 'sample', 'kwargs': {'shape': (25000,)},\n 'precision': 1, 'calls': [\n {'call': numpy.mean, 'as_function': 'mean'},\n {'call': numpy.std, 'as_function': 'std'},\n {'call': lambda x: x.shape, 'as_value': (25000,)}\n ]},\n {'name': 'sample', 'kwargs': {'shape': (5, 1)},\n 'precision': 1, 'calls': [\n {'call': lambda x: x.shape, 'as_value': (5, 1)}\n ]},\n {'name': 'sample', 'kwargs': {'shape': (3, 4, 5)},\n 'precision': 1, 'calls': [\n {'call': lambda x: x.shape, 'as_value': (3, 4, 5)}\n ]},\n ]\n }, {\n 'distribution': cd.Erlang(shape=1, rate=2.0),\n 'like': [{\n 'alias': [cd.Exp(2.0)],\n 'functions': [\n {'name': 'mean'}, {'name': 'var'}, {'name': 'std'},\n {'name': 'moment', 'grid': [1, 2, 3]},\n {'name': 'pdf', 'grid': [0.0, 1.0, 2.0, numpy.inf]},\n {'name': 'cdf', 'grid': [0.0, 1.0, 2.0, numpy.inf]},\n ]\n }],\n 'properties': [\n {'name': 'shape', 'value': 1},\n {'name': 'rate', 'value': 2.0},\n ]\n }, {\n 'distribution': cd.Erlang(shape=2, rate=4.0),\n 'properties': [\n {'name': 'shape', 'value': 2},\n {'name': 'rate', 'value': 4.0},\n ],\n 'functions': [\n {'name': 'mean', 'value': 0.5},\n {'name': 'std', 'value': 0.125 ** 0.5},\n {'name': 'var', 'value': 0.125},\n {'name': 'moment', 'grid': [(1, 0.5), (2, 0.375)]},\n {'name': 'pdf', 'precision': 4,\n 'grid': [(0.0, 0.0), (1.0, 0.29305), (2.0, 0.01073),\n (numpy.inf, 0)],\n },\n {'name': 'cdf', 'precision': 4,\n 'grid': [(0.0, 0.0), (1.0, 0.90842), (2.0, 0.99698),\n (numpy.inf, 1.0)]},\n {'name': 'generate', 'args': (25000,), 'precision': 1,\n 'generator': True,\n 'calls': [\n {'call': numpy.mean, 'as_function': 'mean'},\n {'call': numpy.std, 'as_function': 'std'},\n {'call': numpy.var, 'as_function': 'var'},\n ]},\n ],\n }]\n\n def test_fail_creation_wht_zero_or_negative_shape(self):\n shapes = [0, -1, -2, -numpy.inf]\n for shape in shapes:\n with self.assertRaises(ValueError):\n cd.Erlang(shape=shape, rate=1.0)\n\n def test_fail_creation_with_non_integer_shape(self):\n shapes = [1.5, 2.5, numpy.inf]\n for shape in shapes:\n with self.assertRaises(ValueError):\n cd.Erlang(shape=shape, rate=1.0)\n\n def test_fail_creation_with_zero_or_negative_rate(self):\n rates = [0.0, -1.0, -2.0, -numpy.inf]\n for rate in rates:\n with self.assertRaises(ValueError):\n cd.Erlang(shape=1, rate=rate)\n\n\nclass TestHyperExp(TestBase):\n def setUp(self):\n self.tests = [{\n 'distribution': cd.HyperExp([1.0], [1.0]),\n 'like': [{\n 'alias': [cd.HyperExp([1.0, 1.0], [0.5, 0.5]),\n cd.HyperExp([1.0] * 4, [0.25] * 4),\n cd.Exp(1.0),\n cd.Erlang(1, 1.0)],\n 'functions': [\n {'name': 'mean'}, {'name': 'var'}, {'name': 'std'},\n {'name': 'moment', 'grid': [1, 2, 3]},\n {'name': 'pdf', 'grid': [0.0, 1.0, 2.0, numpy.inf]},\n {'name': 'cdf', 'grid': [0.0, 1.0, 2.0, numpy.inf]},\n ]\n }],\n 'properties': [\n {'name': 'rates', 'value': [1.0]},\n {'name': 'pmf0', 'value': [1.0]},\n ],\n 'functions': [\n {'name': 'generate', 'args': (25000,), 'precision': 1,\n 'generator': True,\n 'calls': [\n {'call': numpy.mean, 'as_function': 'mean'},\n {'call': numpy.std, 'as_function': 'std'},\n {'call': numpy.var, 'as_function': 'var'},\n ]},\n {'name': 'sample', 'kwargs': {'shape': (25000,)},\n 'precision': 1, 'calls': [\n {'call': numpy.mean, 'as_function': 'mean'},\n {'call': numpy.std, 'as_function': 'std'},\n {'call': lambda x: x.shape, 'as_value': (25000,)}\n ]},\n {'name': 'sample', 'kwargs': {'shape': (4, 1)},\n 'precision': 1, 'calls': [\n {'call': lambda x: x.shape, 'as_value': (4, 1)}\n ]},\n {'name': 'sample', 'kwargs': {'shape': (3, 4, 5)},\n 'precision': 1, 'calls': [\n {'call': lambda x: x.shape, 'as_value': (3, 4, 5)}\n ]},\n ]\n }, {\n 'distribution': cd.HyperExp([2.0], [1.0]),\n 'like': [{\n 'alias': [cd.HyperExp([2.0, 2.0], [0.5, 0.5]),\n cd.HyperExp([2.0] * 4, [0.25] * 4),\n cd.Exp(2.0),\n cd.Erlang(1, 2.0)],\n 'functions': [\n {'name': 'mean'}, {'name': 'var'}, {'name': 'std'},\n {'name': 'moment', 'grid': [1, 2, 3], 'vectorized': False},\n {'name': 'pdf', 'grid': [0.0, 1.0, 2.0, numpy.inf]},\n {'name': 'cdf', 'grid': [0.0, 1.0, 2.0, numpy.inf]},\n ]\n }],\n 'properties': [\n {'name': 'rates', 'value': [2.0]},\n {'name': 'pmf0', 'value': [1.0]},\n ],\n 'functions': [\n {'name': 'generate', 'args': (10000,), 'precision': 1,\n 'generator': True,\n 'calls': [\n {'call': numpy.mean, 'as_function': 'mean'},\n {'call': numpy.std, 'as_function': 'std'},\n {'call': numpy.var, 'as_function': 'var'},\n ]},\n ]\n },\n ]\n\n\nclass TestPhaseType(TestBase):\n def setUp(self):\n self.tests = [{\n 'distribution': cd.PhaseType([[-1.0]], [1.0]),\n 'like': [{\n 'alias': [cd.HyperExp([1.0, 1.0], [0.5, 0.5]),\n cd.HyperExp([1.0] * 4, [0.25] * 4),\n cd.Exp(1.0),\n cd.Erlang(1, 1.0)],\n 'functions': [\n {'name': 'mean'}, {'name': 'var'}, {'name': 'std'},\n {'name': 'moment', 'grid': [1, 2, 3], 'vectorized': False},\n {'name': 'pdf', 'grid': [0.0, 1.0, 2.0, numpy.inf]},\n {'name': 'cdf', 'grid': [0.0, 1.0, 2.0, numpy.inf]},\n ]\n }],\n 'properties': [\n {'name': 'S', 'value': [[-1.0]]},\n {'name': 'subgenerator', 'value': [[-1.0]]},\n {'name': 'pmf0', 'value': [1.0]},\n {'name': 'order', 'value': 1},\n ],\n 'functions': [\n # {'name': 'generate', 'args': (10000,), 'precision': 1,\n # 'generator': True,\n # 'calls': [\n # {'call': numpy.mean, 'as_function': 'mean'},\n # {'call': numpy.std, 'as_function': 'std'},\n # {'call': numpy.var, 'as_function': 'var'},\n # ]},\n # {'name': 'sample', 'kwargs': {'shape': (20000,)},\n # 'precision': 1, 'calls': [\n # {'call': numpy.mean, 'as_function': 'mean'},\n # {'call': numpy.std, 'as_function': 'std'},\n # {'call': lambda x: x.shape, 'as_value': (20000,)}\n # ]},\n # {'name': 'sample', 'kwargs': {'shape': (4, 1)},\n # 'precision': 1, 'calls': [\n # {'call': lambda x: x.shape, 'as_value': (4, 1)}\n # ]},\n # {'name': 'sample', 'kwargs': {'shape': (3, 4, 5)},\n # 'precision': 1, 'calls': [\n # {'call': lambda x: x.shape, 'as_value': (3, 4, 5)}\n # ]},\n ],\n }, {\n 'distribution': cd.PhaseType([[-1.0, 1.0], [0.0, -1.0]], [1.0, 0]),\n 'like': [{\n 'alias': [cd.Erlang(2, 1.0)],\n 'functions': [\n {'name': 'mean'}, {'name': 'var'}, {'name': 'std'},\n {'name': 'moment', 'grid': [1, 2, 3], 'vectorized': False},\n {'name': 'pdf', 'grid': [0.0, 1.0, 2.0, numpy.inf]},\n {'name': 'cdf', 'grid': [0.0, 1.0, 2.0, numpy.inf]},\n ]\n }],\n 'properties': [\n {'name': 'S', 'value': [[-1.0, 1.0], [0.0, -1.0]]},\n {'name': 'subgenerator', 'value': [[-1.0, 1.0], [0.0, -1.0]]},\n {'name': 'pmf0', 'value': [1.0, 0]},\n {'name': 'order', 'value': 2},\n ],\n },\n ]\n"
] | [
[
"numpy.asarray",
"numpy.mean",
"numpy.allclose"
]
] |
meck93/intro_ml | [
"903710b13e9eed8b45fdbd9957c2fb49b2981f62"
] | [
"task2/task2_mlp_lbfgs.py"
] | [
"from sklearn.metrics import accuracy_score\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.neural_network import MLPClassifier\nfrom sklearn.preprocessing import StandardScaler\n\nimport numpy as np\nimport pandas as pd\nimport math\nimport sys\n\n# personal csv reader module\nimport reader\n\nFILE_PATH_TRAIN = \"./input/train.csv\"\nFILE_PATH_TEST = \"./input/test.csv\"\nTEST_SIZE = 0.225\n\n# read training file\ntest_data = reader.read_csv(FILE_PATH_TEST, show_info=False)\ntraining_data = reader.read_csv(FILE_PATH_TRAIN, show_info=False)\n\n# splitting the training data set into x and y components\ndata_columns = ['x1', 'x2', 'x3', 'x4', 'x5', 'x6', 'x7', 'x8', 'x9', 'x10', 'x11', 'x12', 'x13', 'x14', 'x15', 'x16']\n\n# test data\n# extracting the x-values\nx_values_test = test_data[data_columns]\nx_values_test = x_values_test.values\n\n# training data\n# extracting the x-values \nx_values_training = training_data[data_columns]\nx_component_training = x_values_training.values\n\n# extracting the y-values\ny_component_training = training_data['y'].values\n\n# training the scaler\nscaler = StandardScaler(with_mean=True, with_std=True)\nscaler = scaler.fit(x_component_training)\n\n# scaling the training and test data\nx_train_scaled = scaler.transform(x_component_training)\nx_test_scaled = scaler.transform(x_values_test)\n\n# create the classification model\nmlp = MLPClassifier(activation='relu', alpha=1.0, batch_size='auto', beta_1=0.9, beta_2=0.999, early_stopping=False, epsilon=1e-08, hidden_layer_sizes=100, \n learning_rate='constant', learning_rate_init=0.001, max_iter=250, momentum=0.9, nesterovs_momentum=True, power_t=0.5, random_state=None, \n shuffle=True, solver='lbfgs', tol=1e-07, validation_fraction=0.25, verbose=False, warm_start=False)\n\n# initial training accuracy \nacc = 0.1\n\nwhile acc < 0.895:\n # splitting the training set into a training & validation set\n x_train, x_val, y_train, y_val = train_test_split(x_train_scaled, y_component_training, test_size=TEST_SIZE)\n\n # fit the training data\n mlp.fit(x_train, y_train)\n\n # predicting the y-values of x_val\n y_pred = mlp.predict(x_val)\n\n # compare real vs prediction\n print(\"The first 5 real y-values:\", y_val[0:5])\n print(\"The first 5 y-value predictions\", y_pred[0:5])\n\n # computing error metrics\n acc = accuracy_score(y_val, y_pred)\n print(\"Accuracy Score\", acc)\n\n# get prediction on validation set\ntest_pred = mlp.predict(x_test_scaled)\n\n# preparing to write the coefficients to file\nout = {\"Id\" : test_data['Id'], \"y\": test_pred}\n\n# output data frame\nout = pd.DataFrame(data=out, dtype=np.int16)\n\n# printing test output\nprint()\nprint(\"Result Written To File:\")\nprint(out.head(5))\n\n# write to csv-file\n# out.to_csv(\"./output/mlp_lbgfs/task2_mlp_lbgfs_[6].csv\", sep=',', index=False, header=True)\n"
] | [
[
"sklearn.neural_network.MLPClassifier",
"sklearn.model_selection.train_test_split",
"pandas.DataFrame",
"sklearn.preprocessing.StandardScaler",
"sklearn.metrics.accuracy_score"
]
] |
MateusRoder/fourier-rbm_avc | [
"90a2f3a9f94ec63e5fe7a9da0f66bb8865f818f7"
] | [
"statistics.py"
] | [
"import torch\nimport numpy as np\nimport matplotlib.pyplot as plt\n\ndy, dx = 50, 50\nrep = 15\nepochs = 50\nsave = True\n\nacc = np.zeros((epochs, rep, 4))\nx = np.arange(epochs)\n# 00 for 75/25 split\n# 0 for 50/50 split\n\nfor r in range(rep):\n acc[:, r, 0] = np.loadtxt(\"02test_acc\"+str(r)+\".txt\")*100 #phase\n acc[:, r, 1] = np.loadtxt(\"rbm_test_acc\"+str(r)+\".txt\")*100 #gauss\n acc[:, r, 2] = np.loadtxt(\"01test_acc\"+str(r)+\".txt\")*100 #mag\n acc[:, r, 3] = np.loadtxt(\"00test_acc\"+str(r)+\".txt\")*100 #mag+phase+gauss\n\n\nif save:\n dsvp1 = np.std(acc[epochs-1,:,0])\n dsvp2 = np.std(acc[epochs-1,:,1])\n dsvp3 = np.std(acc[epochs-1,:,2])\n dsvp4 = np.std(acc[epochs-1,:,3])\n\n dsp = np.zeros((2, 4))\n dsp[1, 0] = dsvp1\n dsp[1, 1] = dsvp2\n dsp[1, 2] = dsvp3\n dsp[1, 3] = dsvp4\n\n dsp[0, 0] = acc[epochs-1,:,0].mean(-1)\n dsp[0, 1] = acc[epochs-1,:,1].mean(-1)\n dsp[0, 2] = acc[epochs-1,:,2].mean(-1)\n dsp[0, 3] = acc[epochs-1,:,3].mean(-1)\n\n np.savetxt('res_75.txt', dsp)\n np.savetxt('wil_75.txt', acc[epochs-1,:,:].reshape((rep, 4)))\n\nacc = np.mean(acc, axis=1)\n\nprint(\"Acc\", np.round(acc[epochs-1, 0],2), np.round(acc[epochs-1, 1],2), np.round(acc[epochs-1, 2],2), np.round(acc[epochs-1, 3],2))\n\n\nfor _ in range(2):\n fig, ax = plt.subplots()\n #ax.errorbar(x, acc, dsvp, linestyle='-', linewidth=.5, label='MultFRRBM', marker='.', color='red', ecolor='black')\n ax.plot(x, acc[:,0], linestyle='-', linewidth=1, label='MultFRRBM-P',color='red') \n ax.plot(x, acc[:,1], linestyle=':', linewidth=1, label='GaussianRBM',color='blue')\n ax.plot(x, acc[:,2], linestyle='--', linewidth=1, label='MultFRRBM-M', color='green')\n ax.plot(x, acc[:,3], linestyle='-.', linewidth=1, label='MultFRRBM-PM', color='black') #, marker='+'\n\n plt.rcParams['xtick.labelsize'] = 14\n plt.rcParams['ytick.labelsize'] = 14\n ax.set_xlabel(\"Epochs\", fontsize=14)\n ax.set_ylabel(\"Mean Accuracy\", fontsize=14)\n ax.legend(loc='lower right', fontsize=14)\n ax.grid(True)\n\n axins=ax.inset_axes([0.2, 0.2, .3, .3])\n axins.plot(x[47:], acc[47:,0], linestyle='-', linewidth=.75, color='red')\n axins.plot(x[47:], acc[47:,1], linestyle=':', linewidth=.75, color='blue')\n axins.plot(x[47:], acc[47:,2], linestyle='--', linewidth=.75, color='green')\n axins.plot(x[47:], acc[47:,3], linestyle='-.', linewidth=.75, color='black')\n axins.set_xticklabels('')\n #axins.set_yticklabels('')\n ax.indicate_inset_zoom(axins, linewidth=0.75)\n\n plt.savefig(\"mean_acc_75.eps\", bbox_inches='tight')\n #plt.savefig(\"mean_acc_50.eps\", bbox_inches='tight')\n plt.show()\n\n"
] | [
[
"numpy.arange",
"matplotlib.pyplot.subplots",
"matplotlib.pyplot.savefig",
"numpy.round",
"numpy.std",
"numpy.mean",
"numpy.savetxt",
"matplotlib.pyplot.show",
"numpy.zeros"
]
] |
sgmoorthy/Deepword-rnn-tensorflow | [
"99a00800f5f5ed63593e262969cf75db28d87f34"
] | [
"train.py"
] | [
"from __future__ import print_function\nimport numpy as np\nimport tensorflow as tf\n\nimport argparse\nimport time\nimport os\nfrom six.moves import cPickle\n\nfrom utils import TextLoader\nfrom model import Model\n\ndef main():\n parser = argparse.ArgumentParser()\n parser.add_argument('--data_dir', type=str, default='data/Input',\n help='data directory containing input.txt')\n parser.add_argument('--input_encoding', type=str, default=None,\n help='character encoding of input.txt, from https://docs.python.org/3/library/codecs.html#standard-encodings')\n parser.add_argument('--log_dir', type=str, default='logs',\n help='directory containing tensorboard logs')\n parser.add_argument('--save_dir', type=str, default='save',\n help='directory to store checkpointed models')\n parser.add_argument('--rnn_size', type=int, default=256,\n help='size of RNN hidden state')\n parser.add_argument('--num_layers', type=int, default=2,\n help='number of layers in the RNN')\n parser.add_argument('--model', type=str, default='lstm',\n help='rnn, gru, or lstm')\n parser.add_argument('--batch_size', type=int, default=50,\n help='minibatch size')\n parser.add_argument('--seq_length', type=int, default=25,\n help='RNN sequence length')\n parser.add_argument('--num_epochs', type=int, default=50,\n help='number of epochs')\n parser.add_argument('--save_every', type=int, default=1000,\n help='save frequency')\n parser.add_argument('--grad_clip', type=float, default=5.,\n help='clip gradients at this value')\n parser.add_argument('--learning_rate', type=float, default=0.002,\n help='learning rate')\n parser.add_argument('--decay_rate', type=float, default=0.97,\n help='decay rate for rmsprop')\n parser.add_argument('--gpu_mem', type=float, default=0.666,\n help='%% of gpu memory to be allocated to this process. Default is 66.6%%')\n parser.add_argument('--init_from', type=str, default=None,\n help=\"\"\"continue training from saved model at this path. Path must contain files saved by previous training process:\n 'config.pkl' : configuration;\n 'words_vocab.pkl' : vocabulary definitions;\n 'checkpoint' : paths to model file(s) (created by tf).\n Note: this file contains absolute paths, be careful when moving files around;\n 'model.ckpt-*' : file(s) with model definition (created by tf)\n \"\"\")\n args = parser.parse_args()\n train(args)\n\ndef train(args):\n data_loader = TextLoader(args.data_dir, args.batch_size, args.seq_length, args.input_encoding)\n args.vocab_size = data_loader.vocab_size\n\n # check compatibility if training is continued from previously saved model\n if args.init_from is not None:\n # check if all necessary files exist\n assert os.path.isdir(args.init_from),\" %s must be a path\" % args.init_from\n assert os.path.isfile(os.path.join(args.init_from,\"config.pkl\")),\"config.pkl file does not exist in path %s\"%args.init_from\n assert os.path.isfile(os.path.join(args.init_from,\"words_vocab.pkl\")),\"words_vocab.pkl.pkl file does not exist in path %s\" % args.init_from\n ckpt = tf.train.get_checkpoint_state(args.init_from)\n assert ckpt,\"No checkpoint found\"\n assert ckpt.model_checkpoint_path,\"No model path found in checkpoint\"\n\n # open old config and check if models are compatible\n with open(os.path.join(args.init_from, 'config.pkl'), 'rb') as f:\n saved_model_args = cPickle.load(f)\n need_be_same=[\"model\",\"rnn_size\",\"num_layers\",\"seq_length\"]\n for checkme in need_be_same:\n assert vars(saved_model_args)[checkme]==vars(args)[checkme],\"Command line argument and saved model disagree on '%s' \"%checkme\n\n # open saved vocab/dict and check if vocabs/dicts are compatible\n with open(os.path.join(args.init_from, 'words_vocab.pkl'), 'rb') as f:\n saved_words, saved_vocab = cPickle.load(f)\n assert saved_words==data_loader.words, \"Data and loaded model disagree on word set!\"\n assert saved_vocab==data_loader.vocab, \"Data and loaded model disagree on dictionary mappings!\"\n\n with open(os.path.join(args.save_dir, 'config.pkl'), 'wb') as f:\n cPickle.dump(args, f)\n with open(os.path.join(args.save_dir, 'words_vocab.pkl'), 'wb') as f:\n cPickle.dump((data_loader.words, data_loader.vocab), f)\n\n model = Model(args)\n\n merged = tf.summary.merge_all()\n train_writer = tf.summary.FileWriter(args.log_dir)\n gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=args.gpu_mem)\n\n with tf.Session(config=tf.ConfigProto(gpu_options=gpu_options)) as sess:\n train_writer.add_graph(sess.graph)\n tf.global_variables_initializer().run()\n saver = tf.train.Saver(tf.global_variables())\n # restore model\n if args.init_from is not None:\n saver.restore(sess, ckpt.model_checkpoint_path)\n for e in range(model.epoch_pointer.eval(), args.num_epochs):\n sess.run(tf.assign(model.lr, args.learning_rate * (args.decay_rate ** e)))\n data_loader.reset_batch_pointer()\n state = sess.run(model.initial_state)\n speed = 0\n if args.init_from is None:\n assign_op = model.epoch_pointer.assign(e)\n sess.run(assign_op)\n if args.init_from is not None:\n data_loader.pointer = model.batch_pointer.eval()\n args.init_from = None\n for b in range(data_loader.pointer, data_loader.num_batches):\n start = time.time()\n x, y = data_loader.next_batch()\n feed = {model.input_data: x, model.targets: y, model.initial_state: state,\n model.batch_time: speed}\n summary, train_loss, state, _, _ = sess.run([merged, model.cost, model.final_state,\n model.train_op, model.inc_batch_pointer_op], feed)\n train_writer.add_summary(summary, e * data_loader.num_batches + b)\n speed = time.time() - start\n if (e * data_loader.num_batches + b) % args.batch_size == 0:\n print(\"{}/{} (epoch {}), train_loss = {:.3f}, time/batch = {:.3f}\" \\\n .format(e * data_loader.num_batches + b,\n args.num_epochs * data_loader.num_batches,\n e, train_loss, speed))\n if (e * data_loader.num_batches + b) % args.save_every == 0 \\\n or (e==args.num_epochs-1 and b == data_loader.num_batches-1): # save for the last result\n checkpoint_path = os.path.join(args.save_dir, 'model.ckpt')\n saver.save(sess, checkpoint_path, global_step = e * data_loader.num_batches + b)\n print(\"model saved to {}\".format(checkpoint_path))\n train_writer.close()\n\nif __name__ == '__main__':\n main()\n"
] | [
[
"tensorflow.train.get_checkpoint_state",
"tensorflow.summary.FileWriter",
"tensorflow.global_variables",
"tensorflow.assign",
"tensorflow.ConfigProto",
"tensorflow.global_variables_initializer",
"tensorflow.summary.merge_all",
"tensorflow.GPUOptions"
]
] |
AnthonyRaimondo/pandaSuit | [
"cff601e86d062f7c6ef0be14b358faba09137b4a"
] | [
"src/main/python/pandaSuit/stats/classification.py"
] | [
"from sklearn.tree import DecisionTreeClassifier\nfrom pandas import Series, DataFrame\n\n\nclass ClassificationTree:\n def __init__(self, dependent: Series, independent: Series or DataFrame):\n self.dependent = dependent\n self.independent = independent\n self.model = self._fit()\n\n def _fit(self) -> DecisionTreeClassifier:\n y = self.dependent.to_list()\n if isinstance(self.independent, Series):\n x = self.independent.to_numpy().reshape(-1, 1)\n else:\n x = self.independent\n return DecisionTreeClassifier(random_state=0).fit(X=x, y=y)\n\n def predict(self, input: Series or dict or int or float):\n if isinstance(input, (Series, dict)):\n return self.model.predict(DataFrame([input]).values)[0]\n else:\n return self.model.predict(input)[0]\n"
] | [
[
"sklearn.tree.DecisionTreeClassifier",
"pandas.DataFrame"
]
] |
TEE-AI/SAI | [
"f2a43d704078057c8f957f4751317e8fea75a07f"
] | [
"train/caffe/convert_tool/convt_cnnsvic.py"
] | [
"#\n# this module converts a floating point caffe model to the model conv.dat and fc.dat\n# conv.dat -- run on TEE comput stick.\n# fc.dat -- runs on host device\n# Note: the input model has to be trained as 1bit/3bits network.\n#\n# Run:\n# python convt_cnnsvic.py teeNet1.caffemodel teeNet1.prototxt teeNet1.json test.jpg ./output\n# Result is saved as conv.dat and fc.dat\n#\n\n# import modules:\nimport numpy as np\nimport sys\nimport struct\n\nimport os\nos.environ['GLOG_minloglevel'] = '2'\n\nimport caffe\nimport cv2\nimport argparse\nimport os\n\ndef NetworkSurgery(net_module, net_weights, net_config, output_model_file):\n print(\"Load caffe model:\")\n net = caffe.Net(net_module, net_weights, caffe.TEST)\n\n print(\"Parse JSON file\")\n # parse JSON file\n with open(net_config, 'r') as f:\n inlines = f.readlines()\n \n # find sublayer numbers and coef bits\n sublayer_bits = np.zeros(100, int) # upto 100 sublayers \n sub = '\"sublayer'\n coef = '\"coef'\n cnt_sub = 0\n for line in inlines:\n ln = line.split()\n if any(sub in string for string in ln):\n sub_char = line[line.index(':')+1:line.index(',')]\n sublayers = int(sub_char)\n if any(coef in string for string in ln):\n coef_char = line[line.index(':')+1:line.index('\\n')]\n for kk in range(sublayers):\n sublayer_bits[cnt_sub] = int(coef_char)\n cnt_sub += 1\n\n print('parsed layer bits:'+ str(sublayer_bits[0:cnt_sub]) )\n\n count = -1\n for layer in net.params.keys(): \n if (layer.find('conv') == 0 or layer.find('conv') == 1) and count < cnt_sub-1:\n count += 1\n coef = net.params[layer][0].data\n for output_channel in range(coef.shape[0]):\n for input_channel in range(coef.shape[1]): \n coef3x3 = coef[output_channel][input_channel][...]\n var = np.sum(abs(coef3x3))/9.0\n \n QFactor = 4.0/(var+0.0001)\n \n if sublayer_bits[count] == 3:\n for i in range(0,3):\n for j in range(0,3):\n abs_coefInt = int(abs(coef3x3[i,j]) * QFactor)\n if abs_coefInt > 2:\n abs_coefInt = 4\n abs_coef = abs_coefInt/QFactor;\n if coef3x3[i,j] >= 0:\n coef3x3[i,j] = abs_coef\n else:\n coef3x3[i,j] = -abs_coef\n else:\n coef3x3[coef3x3>=0] = var\n coef3x3[coef3x3<0] = -var\n\n net.save(output_model_file)\n\ndef outputNetworkWithoutBackbone(net_model, net_weights, output_fc_Coef):\n # create net\n caffe.set_mode_cpu()\n net = caffe.Net(net_model, net_weights, caffe.TEST)\n \n # create output file\n fpout = open(output_fc_Coef, 'wb')\n # write headers\n \n fclayers = []\n for layer in net._layer_names:\n if layer[:2] == 'fc':\n fclayers.append(layer)\n print('Layer list:'+ str(fclayers) )\n \n for fcname in fclayers:\n inlen = net.params[fcname][0].data.shape[1]\n outlen = net.params[fcname][1].data.shape[0]\n fpout.write(struct.pack('<i', inlen))\n fpout.write(struct.pack('<i', outlen))\n \n for fcname in fclayers:\n fpout.write(net.params[fcname][0].data)\n fpout.write(net.params[fcname][1].data)\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n\n parser.add_argument(\"--weights\", \\\n\t default='teeNet1.caffemodel', \\\n\t help=\".caffemodel file\")\n\t\t\t\t\t\t\n parser.add_argument(\"--network\", \\\n\t default='teeNet1.prototxt', \\\n\t help=\".prototxt file\")\n\n parser.add_argument(\"--config\", \\\n\t default=\"teeNet1.json\", \\\n\t help=\".prototxt file\")\n\n parser.add_argument(\"--testdata\", \\\n\t default=\"test.jpg\", \\\n\t help=\"an image file for test\")\n\n parser.add_argument(\"--output\", \\\n\t default=\".\", \\\n\t help=\"conversion output direction\")\n args = parser.parse_args()\n\n img = cv2.imread(args.testdata)\n if img is None:\n print(\"Error: input image \" + args.testdata + \" not exist!\")\n sys.exit()\n \n image = cv2.resize(img, (224, 224))\n with open('test.bin','wb') as f:\n f.write(image)\n f.close()\n\n if os.path.isfile(\"test.bin\") == False:\n print(\"Error: File test.bin does not exist!\")\n sys.exit()\n\n #step 1: get the sliced model\n output_sliced_model = args.output + '/network_sliced.caffemodel'\n \n NetworkSurgery(args.network, args.weights, args.config, output_sliced_model)\n\n #step 2: get the output_conv.dat\n if os.path.isfile(output_sliced_model) == False:\n print(\"Error: File %s does not exist!\" % (output_sliced_model))\n sys.exit()\n\n command = './cnnconvt '\n command_param = args.network + ' ' + output_sliced_model + ' ' + args.config + ' test.bin ' + args.output\n print(command + command_param)\n os.system(command + command_param)\n\n #step 3: get the weight part without backbone network weights\n outputNetworkWithoutBackbone(args.network, args.weights, 'fc.dat')\n os.remove(output_sliced_model)\n os.remove(\"test.bin\")\n print(\"Convert quantizated caffemodel to conv.dat and fc.dat sucessful!\")\n\n\n\n\n\n"
] | [
[
"numpy.zeros"
]
] |
sunggg/relax | [
"22f80434838379c46211c292d5211a84eb1d096b"
] | [
"tests/python/relax/test_relay_translator.py"
] | [
"# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements. See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership. The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License. You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied. See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\nimport tvm\nfrom tvm.runtime import vm\nimport tvm.testing\nfrom tvm.relay import testing\nfrom tvm import relax, relay\nfrom tvm.relax.testing import relay_translator\nfrom tvm import meta_schedule as ms\nfrom tvm.target import Target\nimport numpy as np\nimport pytest\nimport os, shutil\nfrom tvm.meta_schedule.database import JSONDatabase\nimport tempfile\nfrom tvm.meta_schedule.task_scheduler import RoundRobin\n\n\ndef get_resnet(batch_size, dtype, layout, image_shape):\n relay_mod, params = testing.resnet.get_workload(\n num_layers=18,\n batch_size=batch_size,\n dtype=dtype,\n layout=layout,\n image_shape=image_shape,\n )\n\n return relay_mod, params\n\n\ndef create_database(workload_file, tuning_record_file):\n os.makedirs(os.path.dirname(workload_file), exist_ok=True)\n database = JSONDatabase(\n path_workload=workload_file,\n path_tuning_record=tuning_record_file,\n )\n return database\n\n\ndef relay_build_and_run(mod, target, dev, params, data):\n dirpath = \"relay_tmp\"\n db = create_database(f\"{dirpath}/workload.json\", f\"{dirpath}/record.json\")\n with tempfile.TemporaryDirectory() as work_dir:\n ex = ms.tune_relay(\n mod=mod,\n params=params,\n target=target,\n config=ms.EvolutionarySearchConfig(\n num_trials_per_iter=32,\n max_trials_per_task=3,\n max_trials_global=300,\n ),\n # TODO: commented out for now due to the error\n # task_scheduler=RoundRobin,\n work_dir=work_dir,\n database=db,\n )\n\n rt_mod = tvm.contrib.graph_executor.GraphModule(ex[\"default\"](dev))\n rt_mod.set_input(\"data\", data)\n rt_mod.run()\n out = rt_mod.get_output(0).asnumpy()\n\n # cleanup\n shutil.rmtree(dirpath)\n return ex, rt_mod, out\n\n\ndef relax_build_and_run(mod, target, dev, params, data):\n dirpath = \"relax_tmp\"\n db = create_database(f\"{dirpath}/workload.json\", f\"{dirpath}/record.json\")\n mod = relax.transform.BindParams(\"main\", params)(mod)\n\n with tempfile.TemporaryDirectory() as work_dir:\n ex = ms.tune_relax(\n mod=mod,\n target=target,\n config=ms.EvolutionarySearchConfig(\n num_trials_per_iter=32,\n max_trials_per_task=3,\n max_trials_global=300,\n ),\n # TODO: commented out for now due to the error\n # task_scheduler=RoundRobin,\n work_dir=work_dir,\n database=db,\n )\n vm = relax.VirtualMachine(ex, dev)\n res = vm[\"main\"](data)\n out = res.numpy()\n # cleanup\n shutil.rmtree(dirpath)\n return ex, vm, out\n\n\ndef verify_e2e_translation(target_str, layout, batch_size, image_shape):\n target = Target(target_str)\n dev = tvm.device(str(target), dev_id=0)\n relay_mod, params = get_resnet(batch_size, \"float32\", layout, image_shape)\n input_shape = (1, *image_shape)\n data = tvm.nd.array(np.random.rand(*input_shape).astype(np.float32), dev)\n\n relax_mod = relay_translator.from_relay(relay_mod[\"main\"], target, params)\n\n relay_ex, relay_rt_mod, relay_out = relay_build_and_run(relay_mod, target, dev, params, data)\n relax_ex, relax_rt_mod, relax_out = relax_build_and_run(relax_mod, target, dev, params, data)\n\n tvm.testing.assert_allclose(relay_out, relax_out, atol=1e-5, rtol=1e-5)\n\n\[email protected](reason=\"take too much time\")\[email protected](\n \"layout, batch_size, image_shape\", [(\"NCHW\", 1, (3, 224, 224)), (\"NHWC\", 1, (224, 224, 3))]\n)\ndef test_verify_e2e_translation_cpu(layout, batch_size, image_shape):\n verify_e2e_translation(\"llvm --num-cores=16\", layout, batch_size, image_shape)\n\n\[email protected](reason=\"take too much time\")\[email protected]_gpu\[email protected](\n \"layout, batch_size, image_shape\", [(\"NCHW\", 1, (3, 224, 224)), (\"NHWC\", 1, (224, 224, 3))]\n)\ndef test_verify_e2e_translation_gpu(layout, batch_size, image_shape):\n verify_e2e_translation(\"cuda\", layout, batch_size, image_shape)\n\n\ndef verify_extracted_tasks(target_str, layout, batch_size, image_shape):\n target = Target(target_str)\n relay_mod, params = get_resnet(batch_size, \"float32\", layout, image_shape)\n\n relax_mod = relay_translator.from_relay(\n relay_mod[\"main\"],\n target,\n params,\n pass_config={\n \"relay.backend.use_meta_schedule\": True,\n \"relay.FuseOps.max_depth\": 1, # Disable relay fusion\n },\n )\n\n relay_tasks = ms.extract_task_from_relay(\n relay_mod,\n target=target,\n params=params,\n pass_config={\n \"relay.backend.use_meta_schedule\": True,\n \"relay.FuseOps.max_depth\": 1, # Disable relay fusion\n },\n )\n\n relax_tasks = ms.extract_task_from_relax(relax_mod, target=target, params=params)\n assert len(relay_tasks) == len(relax_tasks)\n # TODO: Can we compare extracted tasks as well?\n\n\[email protected](\n \"layout, batch_size, image_shape\",\n [\n (\"NCHW\", 1, (3, 224, 224)),\n (\"NHWC\", 1, (224, 224, 3)),\n ],\n)\ndef test_verify_extracted_tasks_cpu(layout, batch_size, image_shape):\n verify_extracted_tasks(\"llvm --num-cores=16\", layout, batch_size, image_shape)\n\n\[email protected]_gpu\[email protected](\n \"layout, batch_size, image_shape\", [(\"NCHW\", 1, (3, 224, 224)), (\"NHWC\", 1, (224, 224, 3))]\n)\ndef test_verify_extracted_tasks_gpu(layout, batch_size, image_shape):\n verify_extracted_tasks(\"cuda\", layout, batch_size, image_shape)\n\n\ndef translate_and_build_vms(relay_mod, target_str=\"llvm\"):\n target = tvm.target.Target(target_str)\n\n # build the relay IRModule and create relay vm\n relay_ex = relay.vm.compile(relay_mod, target)\n relay_vm = vm.VirtualMachine(relay_ex, tvm.cpu())\n\n # build the relax IRModule and create relax vm\n relax_mod = relay_translator.from_relay(relay_mod[\"main\"], target)\n relax_ex = relax.vm.build(relax_mod, target)\n relax_vm = relax.VirtualMachine(relax_ex, tvm.cpu())\n\n return relay_vm, relax_vm\n\n\ndef verify_vm_outputs(\n input_shape,\n relay_vm,\n relax_vm,\n extra_args=[],\n):\n input = tvm.nd.array(np.random.rand(*input_shape).astype(np.float32))\n\n # check correctness by comparing relax and relay result\n args = [input] + extra_args\n relax_output = relax_vm[\"main\"](*args)\n relay_output = relay_vm.run(*args)\n tvm.testing.assert_allclose(relay_output.numpy(), relax_output.numpy())\n\n\ndef test_single_dynamic_dim():\n wx, wy = 64, 128\n # create relay module: y = data * weights + bias with dynamic batch dimension\n data = relay.var(\"data\", shape=(relay.Any(), wx))\n weights = relay.var(\"weights\", shape=(wx, wy))\n bias = relay.var(\"bias\", shape=(wy,))\n y = relay.nn.matmul(data, weights)\n relay_mod = tvm.IRModule.from_expr(relay.Function([data, weights, bias], y + bias))\n\n relay_vm, relax_vm = translate_and_build_vms(relay_mod)\n weights = tvm.nd.array(np.random.rand(wx, wy).astype(np.float32))\n bias = tvm.nd.array(np.random.rand(wy).astype(np.float32))\n # verify for different batch sizes\n verify_vm_outputs([10, wx], relay_vm, relax_vm, [weights, bias])\n verify_vm_outputs([32, wx], relay_vm, relax_vm, [weights, bias])\n\n\ndef test_multiple_dynamic_dims():\n # create relay module: y = a + a, where a has shape = (?, 5, ?)\n shape = (relay.Any(), 5, relay.Any())\n a = relay.var(\"a\", shape=shape)\n\n relay_mod = tvm.IRModule.from_expr(relay.Function([a], a + a))\n relay_vm, relax_vm = translate_and_build_vms(relay_mod)\n # verify for different shapes\n verify_vm_outputs([2, 5, 10], relay_vm, relax_vm)\n verify_vm_outputs([12, 5, 24], relay_vm, relax_vm)\n\n\nif __name__ == \"__main__\":\n pytest.main([__file__])\n"
] | [
[
"numpy.random.rand"
]
] |
uc-eqgeo/rsqsim-python-tools | [
"35d65629809b7edc10053a464c212ea03616c8df"
] | [
"src/rsqsim_api/rsqsim_api/catalogue/event.py"
] | [
"from typing import Union, List\nfrom collections import defaultdict\nimport pickle\n\nimport xml.etree.ElementTree as ElemTree\nfrom xml.dom import minidom\n\nfrom matplotlib import pyplot as plt\nfrom matplotlib import cm, colors\nfrom matplotlib.animation import FuncAnimation, PillowWriter, FFMpegWriter\nfrom matplotlib.widgets import Slider\nfrom mpl_toolkits.axes_grid1 import make_axes_locatable\nimport operator\nimport numpy as np\nfrom shapely.geometry import Point,Polygon\nfrom shapely.ops import unary_union\nfrom pyproj import Transformer\nimport geopandas as gpd\nimport math\n\nfrom rsqsim_api.fault.multifault import RsqSimMultiFault\nfrom rsqsim_api.visualisation.utilities import plot_coast, plot_background\nfrom rsqsim_api.io.bruce_shaw_utilities import bruce_subduction\nfrom rsqsim_api.io.mesh_utils import array_to_mesh\nfrom rsqsim_api.fault.patch import OpenQuakeRectangularPatch\n\ntransformer_nztm2wgs = Transformer.from_crs(2193, 4326, always_xy=True)\n\n\nclass RsqSimEvent:\n def __init__(self):\n # Event ID\n self.event_id = None\n # Origin time\n self.t0 = None\n # Seismic moment and mw\n self.m0 = None\n self.mw = None\n # Hypocentre location\n self.x, self.y, self.z = (None,) * 3\n # Rupture area\n self.area = None\n # Rupture duration\n self.dt = None\n\n # Parameters for slip distributions\n self.patches = None\n self.patch_slip = None\n self.faults = None\n self.patch_time = None\n self.patch_numbers = None\n self._mean_slip = None\n self.length = None\n self._mean_strike = None\n self._mean_dip = None\n self._mean_rake = None\n\n @property\n def num_faults(self):\n return len(self.faults)\n\n @property\n def bounds(self):\n x1 = min([min(fault.vertices[:, 0]) for fault in self.faults])\n y1 = min([min(fault.vertices[:, 1]) for fault in self.faults])\n x2 = max([max(fault.vertices[:, 0]) for fault in self.faults])\n y2 = max([max(fault.vertices[:, 1]) for fault in self.faults])\n return [x1, y1, x2, y2]\n\n @property\n def exterior(self):\n return unary_union([patch.as_polygon() for patch in self.patches])\n\n @property\n def mean_slip(self):\n if self._mean_slip is None:\n self.find_mean_slip()\n return self._mean_slip\n\n @property\n def mean_strike(self):\n if self._mean_strike is None:\n self.find_mean_strike()\n return self._mean_strike\n\n @property\n def mean_dip(self):\n if self._mean_dip is None:\n self.find_mean_dip()\n return self._mean_dip\n\n @property\n def mean_rake(self):\n if self._mean_rake is None:\n self.find_mean_rake()\n return self._mean_rake\n\n\n @classmethod\n def from_catalogue_array(cls, t0: float, m0: float, mw: float, x: float,\n y: float, z: float, area: float, dt: float, event_id: int = None):\n \"\"\"\n\n :param t0:\n :param m0:\n :param mw:\n :param x:\n :param y:\n :param z:\n :param area:\n :param dt:\n :param event_id:\n :return:\n \"\"\"\n\n event = cls()\n event.t0, event.m0, event.mw, event.x, event.y, event.z = [t0, m0, mw, x, y, z]\n event.area, event.dt = [area, dt]\n event.event_id = event_id\n\n return event\n\n @property\n def patch_outline_gs(self):\n return gpd.GeoSeries([patch.as_polygon() for patch in self.patches], crs=2193)\n\n @classmethod\n def from_earthquake_list(cls, t0: float, m0: float, mw: float, x: float,\n y: float, z: float, area: float, dt: float,\n patch_numbers: Union[list, np.ndarray, tuple],\n patch_slip: Union[list, np.ndarray, tuple],\n patch_time: Union[list, np.ndarray, tuple],\n fault_model: RsqSimMultiFault, filter_single_patches: bool = True,\n min_patches: int = 10, min_slip: Union[float, int] = 1, event_id: int = None):\n event = cls.from_catalogue_array(\n t0, m0, mw, x, y, z, area, dt, event_id=event_id)\n\n faults_with_patches = fault_model.faults_with_patches\n patches_on_fault = defaultdict(list)\n [ patches_on_fault[faults_with_patches[i]].append(i) for i in patch_numbers ]\n\n mask = np.full(len(patch_numbers), True)\n for fault in patches_on_fault.keys():\n patches_on_this_fault = patches_on_fault[fault]\n if len(patches_on_this_fault) < min_patches:\n # Finds the indices of values in patches_on_this_fault in patch_numbers\n patch_on_fault_indices = np.searchsorted(patch_numbers, patches_on_this_fault)\n mask[patch_on_fault_indices] = False\n\n event.patch_numbers = patch_numbers[mask]\n event.patch_slip = patch_slip[mask]\n event.patch_time = patch_time[mask]\n\n\n if event.patch_numbers.size > 1:\n patchnum_lookup = operator.itemgetter(*(event.patch_numbers))\n event.patches = list(patchnum_lookup(fault_model.patch_dic))\n event.faults = list(set(patchnum_lookup(fault_model.faults_with_patches)))\n\n elif event.patch_numbers.size == 1:\n event.patches = [fault_model.patch_dic[event.patch_numbers[0]]]\n event.faults = [fault_model.faults_with_patches[event.patch_numbers[0]]]\n\n else:\n event.patches = []\n event.faults = []\n\n return event\n\n @classmethod\n def from_multiprocessing(cls, t0: float, m0: float, mw: float, x: float,\n y: float, z: float, area: float, dt: float,\n patch_numbers: Union[list, np.ndarray, tuple],\n patch_slip: Union[list, np.ndarray, tuple],\n patch_time: Union[list, np.ndarray, tuple],\n fault_model: RsqSimMultiFault, mask: list, event_id: int = None):\n event = cls.from_catalogue_array(\n t0, m0, mw, x, y, z, area, dt, event_id=event_id)\n event.patch_numbers = patch_numbers[mask]\n event.patch_slip = patch_slip[mask]\n event.patch_time = patch_time[mask]\n\n if event.patch_numbers.size > 0:\n patchnum_lookup = operator.itemgetter(*(event.patch_numbers))\n event.patches = list(patchnum_lookup(fault_model.patch_dic))\n event.faults = list(set(patchnum_lookup(fault_model.faults_with_patches)))\n\n else:\n event.patches = []\n event.faults = []\n\n return event\n\n def find_mean_slip(self):\n if self.patches:\n total_slip = np.sum(self.patch_slip)\n npatches = len(self.patches)\n if all([total_slip > 0., npatches > 0]):\n self._mean_slip = total_slip/npatches\n\n def find_mean_strike(self):\n if self.patches:\n cumstrike=0.\n for patch in self.patches:\n cumstrike += patch.strike\n npatches = len(self.patches)\n if npatches > 0:\n self._mean_strike = cumstrike/npatches\n\n def find_mean_dip(self):\n if self.patches:\n cumdip=0.\n for patch in self.patches:\n cumdip += patch.dip\n npatches = len(self.patches)\n if npatches > 0:\n self._mean_dip = cumdip/npatches\n\n def find_mean_rake(self):\n if self.patches:\n cumrake=0.\n for patch in self.patches:\n cumrake += patch.rake\n npatches = len(self.patches)\n if npatches > 0:\n self._mean_rake = cumrake/npatches\n\n def find_length(self,min_slip_percentile: float | None =None):\n if self.patches:\n rupture_length=0.\n for fault in self.faults:\n fault_trace=fault.trace\n patch_locs=[]\n for patch in self.patches:\n centroid = Point(patch.centre[:2])\n\n patch_dist = fault_trace.project(centroid)\n patch_locs.append(patch_dist)\n rupture_length += np.ptp(patch_locs)\n\n self.length=rupture_length\n\n\n def plot_slip_2d(self, subduction_cmap: str = \"plasma\", crustal_cmap: str = \"viridis\", show: bool = True,\n write: str = None, subplots = None, global_max_sub_slip: int = 0, global_max_slip: int = 0,\n figsize: tuple = (6.4, 4.8), hillshading_intensity: float = 0.0, bounds: tuple = None,\n plot_rivers: bool = True, plot_lakes: bool = True,\n plot_highways: bool = True, plot_boundaries: bool = False, create_background: bool = False,\n coast_only: bool = True, hillshade_cmap: colors.LinearSegmentedColormap = cm.terrain,\n plot_log_scale: bool = False, log_cmap: str = \"magma\", log_min: float = 1.0,\n log_max: float = 100., plot_traces: bool = True, trace_colour: str = \"pink\",\n min_slip_percentile: float = None, min_slip_value: float = None, plot_zeros: bool = True):\n # TODO: Plot coast (and major rivers?)\n assert self.patches is not None, \"Need to populate object with patches!\"\n\n if all([bounds is None, self.bounds is not None]):\n bounds = self.bounds\n\n if all([min_slip_percentile is not None, min_slip_value is None]):\n min_slip = np.percentile(self.patch_slip, min_slip_percentile)\n else:\n min_slip = min_slip_value\n\n if subplots is not None:\n if isinstance(subplots, str):\n # Assume pickled figure\n with open(subplots, \"rb\") as pfile:\n loaded_subplots = pickle.load(pfile)\n fig, ax = loaded_subplots\n else:\n # Assume matplotlib objects\n fig, ax = subplots\n elif create_background:\n fig, ax = plot_background(figsize=figsize, hillshading_intensity=hillshading_intensity,\n bounds=bounds, plot_rivers=plot_rivers, plot_lakes=plot_lakes,\n plot_highways=plot_highways, plot_boundaries=plot_boundaries,\n hillshade_cmap=hillshade_cmap)\n elif coast_only:\n fig, ax = plot_background(figsize=figsize, hillshading_intensity=hillshading_intensity,\n bounds=bounds, plot_rivers=False, plot_lakes=False, plot_highways=False,\n plot_boundaries=False, hillshade_cmap=hillshade_cmap)\n\n\n else:\n fig, ax = plt.subplots()\n fig.set_size_inches(figsize)\n\n # Find maximum slip for subduction interface\n\n # Find maximum slip to scale colourbar\n max_slip = 0\n\n colour_dic = {}\n for f_i, fault in enumerate(self.faults):\n if fault.name in bruce_subduction:\n if plot_zeros:\n colours = np.zeros(fault.patch_numbers.shape)\n else:\n colours = np.nan * np.ones(fault.patch_numbers.shape)\n for local_id, patch_id in enumerate(fault.patch_numbers):\n if patch_id in self.patch_numbers:\n slip_index = np.argwhere(self.patch_numbers == patch_id)[0]\n if min_slip is not None:\n if self.patch_slip[slip_index] >= min_slip:\n colours[local_id] = self.patch_slip[slip_index]\n else:\n if self.patch_slip[slip_index] > 0.:\n colours[local_id] = self.patch_slip[slip_index]\n\n colour_dic[f_i] = colours\n if np.nanmax(colours) > max_slip:\n max_slip = np.nanmax(colours)\n max_slip = global_max_sub_slip if global_max_sub_slip > 0 else max_slip\n\n plots = []\n\n # Plot subduction interface\n subduction_list = []\n subduction_plot = None\n for f_i, fault in enumerate(self.faults):\n if fault.name in bruce_subduction:\n subduction_list.append(fault.name)\n if plot_log_scale:\n subduction_plot = ax.tripcolor(fault.vertices[:, 0], fault.vertices[:, 1], fault.triangles,\n facecolors=colour_dic[f_i],\n cmap=log_cmap, norm=colors.LogNorm(vmin=log_min, vmax=log_max))\n else:\n subduction_plot = ax.tripcolor(fault.vertices[:, 0], fault.vertices[:, 1], fault.triangles,\n facecolors=colour_dic[f_i],\n cmap=subduction_cmap, vmin=0., vmax=max_slip)\n plots.append(subduction_plot)\n\n max_slip = 0\n colour_dic = {}\n for f_i, fault in enumerate(self.faults):\n if fault.name not in bruce_subduction:\n if plot_zeros:\n colours = np.zeros(fault.patch_numbers.shape)\n else:\n colours = np.nan * np.ones(fault.patch_numbers.shape)\n for local_id, patch_id in enumerate(fault.patch_numbers):\n if patch_id in self.patch_numbers:\n slip_index = np.argwhere(self.patch_numbers == patch_id)[0]\n if min_slip is not None:\n if self.patch_slip[slip_index] >= min_slip:\n colours[local_id] = self.patch_slip[slip_index]\n else:\n if self.patch_slip[slip_index] > 0.:\n colours[local_id] = self.patch_slip[slip_index]\n colour_dic[f_i] = colours\n if np.nanmax(colours) > max_slip:\n max_slip = np.nanmax(colours)\n max_slip = global_max_slip if global_max_slip > 0 else max_slip\n\n crustal_plot = None\n for f_i, fault in enumerate(self.faults):\n if fault.name not in bruce_subduction:\n if plot_log_scale:\n crustal_plot = ax.tripcolor(fault.vertices[:, 0], fault.vertices[:, 1], fault.triangles,\n facecolors=colour_dic[f_i],\n cmap=log_cmap, norm=colors.LogNorm(vmin=log_min, vmax=log_max))\n else:\n crustal_plot = ax.tripcolor(fault.vertices[:, 0], fault.vertices[:, 1], fault.triangles,\n facecolors=colour_dic[f_i],\n cmap=crustal_cmap, vmin=0., vmax=max_slip)\n plots.append(crustal_plot)\n\n if any([subplots is None, isinstance(subplots,str)]):\n if plot_log_scale:\n if subduction_list:\n sub_cbar = fig.colorbar(subduction_plot, ax=ax)\n sub_cbar.set_label(\"Slip (m)\")\n elif crustal_plot is not None:\n crust_cbar = fig.colorbar(crustal_plot, ax=ax)\n crust_cbar.set_label(\"Slip (m)\")\n else:\n if subduction_list:\n sub_cbar = fig.colorbar(subduction_plot, ax=ax)\n sub_cbar.set_label(\"Subduction slip (m)\")\n if crustal_plot is not None:\n crust_cbar = fig.colorbar(crustal_plot, ax=ax)\n crust_cbar.set_label(\"Slip (m)\")\n\n\n\n plot_coast(ax=ax)\n\n\n if write is not None:\n fig.savefig(write, dpi=300)\n if show:\n plt.show()\n else:\n plt.close(fig)\n\n if show and subplots is None:\n plt.show()\n\n return plots\n\n def plot_slip_evolution(self, subduction_cmap: str = \"plasma\", crustal_cmap: str = \"viridis\", show: bool = True,\n step_size: int = 1, write: str = None, fps: int = 20, file_format: str = \"gif\",\n figsize: tuple = (6.4, 4.8)):\n\n assert file_format in (\"gif\", \"mov\", \"avi\", \"mp4\")\n\n fig, ax = plt.subplots()\n fig.set_size_inches(figsize)\n plot_coast(ax, clip_boundary=self.bounds)\n ax.set_aspect(\"equal\")\n ax.get_xaxis().set_visible(False)\n ax.get_yaxis().set_visible(False)\n\n colour_dic = {}\n timestamps = defaultdict(set)\n subduction_max_slip = 0\n crustal_max_slip = 0\n subduction_list = []\n for f_i, fault in enumerate(self.faults):\n colours = np.zeros(fault.patch_numbers.shape)\n times = np.zeros(fault.patch_numbers.shape)\n\n for local_id, patch_id in enumerate(fault.patch_numbers):\n if patch_id in self.patch_numbers:\n slip_index = np.searchsorted(self.patch_numbers, patch_id)\n times[local_id] = step_size * np.rint((self.patch_time[slip_index] - self.t0) / step_size)\n colours[local_id] = self.patch_slip[slip_index]\n timestamps[times[local_id]].add(f_i)\n\n colour_dic[f_i] = (colours, times)\n if fault.name in bruce_subduction:\n subduction_list.append(fault.name)\n if max(colours) > subduction_max_slip:\n subduction_max_slip = max(colours)\n else:\n if max(colours) > crustal_max_slip:\n crustal_max_slip = max(colours)\n\n plots = {}\n subduction_plot = None\n for f_i, fault in enumerate(self.faults):\n init_colours = np.zeros(fault.patch_numbers.shape)\n if fault.name in bruce_subduction:\n subduction_plot = ax.tripcolor(fault.vertices[:, 0], fault.vertices[:, 1], fault.triangles,\n facecolors=init_colours,\n cmap=subduction_cmap, vmin=0, vmax=subduction_max_slip)\n plots[f_i] = (subduction_plot, init_colours)\n\n crustal_plot = None\n for f_i, fault in enumerate(self.faults):\n init_colours = np.zeros(fault.patch_numbers.shape)\n if fault.name not in bruce_subduction:\n crustal_plot = ax.tripcolor(fault.vertices[:, 0], fault.vertices[:, 1], fault.triangles,\n facecolors=init_colours,\n cmap=crustal_cmap, vmin=0, vmax=crustal_max_slip)\n plots[f_i] = (crustal_plot, init_colours)\n\n\n ax_divider = make_axes_locatable(ax)\n ax_time = ax_divider.append_axes(\"bottom\", size=\"3%\", pad=0.5)\n time_slider = Slider(ax_time, 'Time (s)', 0, step_size * round(self.dt / step_size) + step_size,\n valinit=0, valstep=step_size)\n\n # Build colorbars\n padding = 0.25\n if subduction_list:\n sub_ax = ax_divider.append_axes(\"right\", size=\"5%\", pad=padding)\n sub_cbar = fig.colorbar(\n subduction_plot, cax=sub_ax)\n sub_cbar.set_label(\"Subduction slip (m)\")\n padding += 0.25\n\n if crustal_plot is not None:\n crust_ax = ax_divider.append_axes(\"right\", size=\"5%\", pad=padding)\n crust_cbar = fig.colorbar(\n crustal_plot, cax=crust_ax)\n crust_cbar.set_label(\"Slip (m)\")\n\n def update_plot(num):\n time = time_slider.valmin + num * step_size\n time_slider.set_val(time)\n\n if time in timestamps:\n for f_i in timestamps[time]:\n plot, curr_colours = plots[f_i]\n fault_times = colour_dic[f_i][1]\n filter_time_indices = np.argwhere(fault_times == time).flatten()\n curr_colours[filter_time_indices] = colour_dic[f_i][0][filter_time_indices]\n plot.update({'array': curr_colours})\n elif time == time_slider.valmax:\n for f_i, fault in enumerate(self.faults):\n plot, curr_colours = plots[f_i]\n init_colors = np.zeros(fault.patch_numbers.shape)\n curr_colours[:] = init_colors[:]\n plot.update({'array': curr_colours})\n\n fig.canvas.draw_idle()\n\n frames = int((time_slider.valmax - time_slider.valmin) / step_size) + 1\n animation = FuncAnimation(fig, update_plot, interval=50, frames=frames)\n\n if write is not None:\n writer = PillowWriter(fps=fps) if file_format == \"gif\" else FFMpegWriter(fps=fps)\n animation.save(f\"{write}.{file_format}\", writer)\n\n if show:\n plt.show()\n\n def slip_dist_array(self, include_zeros: bool = True, min_slip_percentile: float = None,\n min_slip_value: float = None, nztm_to_lonlat: bool = False):\n all_patches = []\n if all([min_slip_percentile is not None, min_slip_value is None]):\n min_slip = np.percentile(self.patch_slip, min_slip_percentile)\n else:\n min_slip = min_slip_value\n\n for fault in self.faults:\n for patch_id in fault.patch_numbers:\n if patch_id in self.patch_numbers:\n patch = fault.patch_dic[patch_id]\n if nztm_to_lonlat:\n triangle_corners = patch.vertices_lonlat.flatten()\n else:\n triangle_corners = patch.vertices.flatten()\n slip_index = np.searchsorted(self.patch_numbers, patch_id)\n time = self.patch_time[slip_index] - self.t0\n slip_mag = self.patch_slip[slip_index]\n if min_slip is not None:\n if slip_mag >= min_slip:\n patch_line = np.hstack([triangle_corners, np.array([slip_mag, patch.rake, time])])\n all_patches.append(patch_line)\n elif include_zeros:\n patch = fault.patch_dic[patch_id]\n patch_line = np.hstack([triangle_corners, np.array([0., 0., 0.])])\n all_patches.append(patch_line)\n else:\n patch_line = np.hstack([triangle_corners, np.array([slip_mag, patch.rake, time])])\n all_patches.append(patch_line)\n elif include_zeros:\n patch = fault.patch_dic[patch_id]\n if nztm_to_lonlat:\n triangle_corners = patch.vertices_lonlat.flatten()\n else:\n triangle_corners = patch.vertices.flatten()\n patch_line = np.hstack([triangle_corners, np.array([0., 0., 0.])])\n all_patches.append(patch_line)\n return np.array(all_patches)\n\n def slip_dist_to_mesh(self, include_zeros: bool = True, min_slip_percentile: float = None,\n min_slip_value: float = None, nztm_to_lonlat: bool = False):\n\n slip_dist_array = self.slip_dist_array(include_zeros=include_zeros, min_slip_percentile=min_slip_percentile,\n min_slip_value=min_slip_value)\n mesh = array_to_mesh(slip_dist_array[:, :9])\n data_dic = {}\n for label, index in zip([\"slip\", \"rake\", \"time\"], [9, 10, 11]):\n data_dic[label] = slip_dist_array[:, index]\n mesh.cell_data = data_dic\n\n return mesh\n\n def slip_dist_to_vtk(self, vtk_file: str, include_zeros: bool = True, min_slip_percentile: float = None,\n min_slip_value: float = None):\n mesh = self.slip_dist_to_mesh(include_zeros=include_zeros, min_slip_percentile=min_slip_percentile,\n min_slip_value=min_slip_value)\n mesh.write(vtk_file, file_format=\"vtk\")\n\n def slip_dist_to_obj(self, obj_file: str, include_zeros: bool = True, min_slip_percentile: float = None,\n min_slip_value: float = None):\n mesh = self.slip_dist_to_mesh(include_zeros=include_zeros, min_slip_percentile=min_slip_percentile,\n min_slip_value=min_slip_value)\n mesh.write(obj_file, file_format=\"obj\")\n\n def slip_dist_to_txt(self, txt_file, include_zeros: bool = True, min_slip_percentile: float = None,\n min_slip_value: float = None, nztm_to_lonlat: bool = False):\n if nztm_to_lonlat:\n header=\"lon1 lat1 z1 lon2 lat2 z2 lon3 lat3 z3 slip_m rake_deg time_s\"\n else:\n header = \"x1 y1 z1 x2 y2 z2 x3 y3 z3 slip_m rake_deg time_s\"\n slip_dist_array = self.slip_dist_array(include_zeros=include_zeros, min_slip_percentile=min_slip_percentile,\n min_slip_value=min_slip_value, nztm_to_lonlat=nztm_to_lonlat)\n np.savetxt(txt_file, slip_dist_array, fmt=\"%.6f\", delimiter=\" \", header=header)\n\n def discretize_tiles(self, tile_list: List[Polygon], probability: float, rake: float):\n included_tiles = []\n\n for tile in tile_list:\n overlapping = tile.intersects(self.exterior)\n if overlapping:\n intersection = tile.intersection(self.exterior)\n if intersection.area >= 0.5 * tile.area:\n included_tiles.append(tile)\n\n out_gs = gpd.GeoSeries(included_tiles, crs=2193)\n return out_gs\n\n def discretize_openquake(self, tile_list: List[Polygon], probability: float, rake: float):\n included_tiles = []\n\n for tile in tile_list:\n overlapping = tile.intersects(self.exterior)\n if overlapping:\n intersection = tile.intersection(self.exterior)\n if intersection.area >= 0.5 * tile.area:\n included_tiles.append(tile)\n\n out_gs = gpd.GeoSeries(included_tiles, crs=2193)\n out_gs_wgs = out_gs.to_crs(epsg=4326)\n if out_gs_wgs.size > 0:\n oq_rup = OpenQuakeMultiSquareRupture(list(out_gs.geometry), magnitude=self.mw, rake=rake,\n hypocentre=np.array([self.x, self.y, self.z]),\n event_id=self.event_id, probability=probability)\n return oq_rup\n\n else:\n return\n\n\n\n\nclass OpenQuakeMultiSquareRupture:\n def __init__(self, tile_list: List[Polygon], probability: float, magnitude: float, rake: float,\n hypocentre: np.ndarray, event_id: int, name: str = \"Subduction earthquake\",\n tectonic_region: str = \"subduction\"):\n self.patches = [OpenQuakeRectangularPatch.from_polygon(tile) for tile in tile_list]\n self.prob = probability\n self.magnitude = magnitude\n self.rake = rake\n self.hypocentre = hypocentre\n self.inv_prob = 1. - probability\n\n self.hyp_depth = -1.e-3 * hypocentre[-1]\n self.hyp_lon, self.hyp_lat = transformer_nztm2wgs.transform(hypocentre[0], hypocentre[1])\n self.event_id = event_id\n self.name = name\n self.tectonic_region = tectonic_region\n\n def to_oq_xml(self, write: str = None):\n source_element = ElemTree.Element(\"nrml\",\n attrib={\"xmlns\": \"http://openquake.org/xmlns/nrml/0.4\",\n \"xmlns:gml\": \"http://www.opengis.net/gml\"\n })\n multi_patch_elem = ElemTree.Element(\"multiPlanesRupture\",\n attrib={\"probs_occur\": f\"{self.inv_prob:.4f} {self.prob:.4f}\"})\n mag_elem = ElemTree.Element(\"magnitude\")\n mag_elem.text = f\"{self.magnitude:.2f}\"\n\n multi_patch_elem.append(mag_elem)\n rake_elem = ElemTree.Element(\"rake\")\n rake_elem.text = f\"{self.rake:.1f}\"\n multi_patch_elem.append(rake_elem)\n\n hyp_element = ElemTree.Element(\"hypocenter\", attrib={\"depth\": f\"{self.hyp_depth:.3f}\",\n \"lat\": f\"{self.hyp_lat:.4f}\",\n \"lon\": f\"{self.hyp_lon:.4f}\"})\n multi_patch_elem.append(hyp_element)\n for patch in self.patches:\n multi_patch_elem.append(patch.to_oq_xml())\n\n source_element.append(multi_patch_elem)\n\n if write is not None:\n assert isinstance(write, str)\n if write[-4:] != \".xml\":\n write += \".xml\"\n\n elmstr = ElemTree.tostring(source_element, encoding=\"UTF-8\", method=\"xml\")\n xml_dom = minidom.parseString(elmstr)\n pretty_xml_str = xml_dom.toprettyxml(indent=\" \", encoding=\"utf-8\")\n with open(write, \"wb\") as xml:\n xml.write(pretty_xml_str)\n\n\n return source_element\n\n\n\n\n\n\n"
] | [
[
"numpy.nanmax",
"matplotlib.animation.PillowWriter",
"matplotlib.colors.LogNorm",
"numpy.rint",
"matplotlib.pyplot.subplots",
"numpy.percentile",
"numpy.ptp",
"matplotlib.animation.FFMpegWriter",
"numpy.ones",
"numpy.argwhere",
"matplotlib.animation.FuncAnimation",
"numpy.searchsorted",
"matplotlib.pyplot.close",
"numpy.savetxt",
"numpy.array",
"numpy.zeros",
"numpy.sum",
"matplotlib.pyplot.show"
]
] |
ramomar1992/ass-1 | [
"a1b5e67b87a05ecffdcd2811ae2e916b7b296ef1"
] | [
"index.py"
] | [
"from pandas import read_csv\nimport numpy as np\n\n# Open the csv as a data frame in python using the pandas package. Inspect the data frame to get an idea of the metrics reported and the format of the table.\ntable = read_csv(\"phi_data.csv\")\nprint(table)\n\n# Create a list that contains the following elements: Type, Filter, TRUTH.TP, TRUTH.FN, QUERY.FP, METRIC.Precision.\nsubset = [\"Type\", \"Filter\", \"TRUTH.TP\", \"TRUTH.FN\", \"QUERY.FP\", \"METRIC.Precision\"]\n\n# Use the list to subset the data frame and keep the desired columns.\nsubset_table = table[subset]\n\n# Create two numpy arrays, one with the TRUTH.TP numbers and another with the QUERY.FP numbers\ntrue_pos = np.array(subset_table[\"TRUTH.TP\"])\nfalse_pos = np.array(subset_table[\"QUERY.FP\"])\n\n# Calculate precision using your numpy arrays. Hint: Precision = True Positives / (True Positives + False Positives)\nprecision = true_pos / (true_pos + false_pos)\n\n#Compare your values to the values in “METRIC.Precision”\ncompare = abs(precision - subset_table[\"METRIC.Precision\"])\nprint(compare)\n\n\"\"\"_summary_\n0 0.000556\n1 0.000785\n2 0.000008\n3 0.000001\n\"\"\"\n\n# Provide your python script, and precision values to 2 decimal places for INDEL ALL variants, INDEL PASS variants, SNP ALL variants and SNP PASS variants.\ntype_filter_precision = subset_table[[\"Type\", \"Filter\"]]\ntype_filter_precision[\"Precision\"] = precision.round(2)\nprint(type_filter_precision)\n\n\"\"\"_summary_\n Type Filter Precision\n0 INDEL ALL 0.96\n1 INDEL PASS 0.96\n2 SNP ALL 0.99\n3 SNP PASS 1.00\n\"\"\"\n"
] | [
[
"numpy.array",
"pandas.read_csv"
]
] |
jayleicn/mmf-1 | [
"4f0f0ca9563e035e2f82329d1db83364c47d3c58"
] | [
"mmf/modules/metrics.py"
] | [
"# Copyright (c) Facebook, Inc. and its affiliates.\n\"\"\"\nThe metrics module contains implementations of various metrics used commonly to\nunderstand how well our models are performing. For e.g. accuracy, vqa_accuracy,\nr@1 etc.\n\nFor implementing your own metric, you need to follow these steps:\n\n1. Create your own metric class and inherit ``BaseMetric`` class.\n2. In the ``__init__`` function of your class, make sure to call\n ``super().__init__('name')`` where 'name' is the name of your metric. If\n you require any parameters in your ``__init__`` function, you can use\n keyword arguments to represent them and metric constructor will take care of\n providing them to your class from config.\n3. Implement a ``calculate`` function which takes in ``SampleList`` and\n `model_output` as input and return back a float tensor/number.\n4. Register your metric with a key 'name' by using decorator,\n ``@registry.register_metric('name')``.\n\nExample::\n\n import torch\n\n from mmf.common.registry import registry\n from mmf.modules.metrics import BaseMetric\n\n @registry.register_metric(\"some\")\n class SomeMetric(BaseMetric):\n def __init__(self, some_param=None):\n super().__init__(\"some\")\n ....\n\n def calculate(self, sample_list, model_output):\n metric = torch.tensor(2, dtype=torch.float)\n return metric\n\nExample config for above metric::\n\n model_config:\n pythia:\n metrics:\n - type: some\n params:\n some_param: a\n\"\"\"\n\nimport collections\nimport warnings\nfrom typing import Dict\n\nimport torch\nfrom mmf.common.registry import registry\nfrom mmf.datasets.processors.processors import EvalAIAnswerProcessor\nfrom mmf.utils.logger import log_class_usage\nfrom sklearn.metrics import (\n average_precision_score,\n f1_score,\n precision_recall_curve,\n roc_auc_score,\n)\nfrom torch import Tensor\n\n\ndef _convert_to_one_hot(expected, output):\n # This won't get called in case of multilabel, only multiclass or binary\n # as multilabel will anyways be multi hot vector\n if output.squeeze().dim() != expected.squeeze().dim() and expected.dim() == 1:\n expected = torch.nn.functional.one_hot(\n expected.long(), num_classes=output.size(-1)\n ).float()\n return expected\n\n\nclass Metrics:\n \"\"\"Internally used by MMF, Metrics acts as wrapper for handling\n calculation of metrics over various metrics specified by the model in\n the config. It initializes all of the metrics and when called it runs\n calculate on each of them one by one and returns back a dict with proper\n naming back. For e.g. an example dict returned by Metrics class:\n ``{'val/vqa_accuracy': 0.3, 'val/r@1': 0.8}``\n\n Args:\n metric_list (ListConfig): List of DictConfigs where each DictConfig\n specifies name and parameters of the\n metrics used.\n \"\"\"\n\n def __init__(self, metric_list):\n if not isinstance(metric_list, collections.abc.Sequence):\n metric_list = [metric_list]\n\n self.metrics = self._init_metrics(metric_list)\n\n def _init_metrics(self, metric_list):\n metrics = {}\n self.required_params = {\"dataset_name\", \"dataset_type\"}\n for metric in metric_list:\n params = {}\n dataset_names = []\n if isinstance(metric, collections.abc.Mapping):\n if \"type\" not in metric:\n raise ValueError(\n f\"Metric {metric} needs to have 'type' attribute \"\n + \"or should be a string\"\n )\n metric_type = key = metric.type\n params = getattr(metric, \"params\", {})\n # Support cases where uses need to give custom metric name\n if \"key\" in metric:\n key = metric.key\n\n # One key should only be used once\n if key in metrics:\n raise RuntimeError(\n f\"Metric with type/key '{metric_type}' has been defined more \"\n + \"than once in metric list.\"\n )\n\n # a custom list of dataset where this metric will be applied\n if \"datasets\" in metric:\n dataset_names = metric.datasets\n else:\n if not isinstance(metric, str):\n raise TypeError(\n \"Metric {} has inappropriate type\"\n \"'dict' or 'str' allowed\".format(metric)\n )\n metric_type = key = metric\n\n metric_cls = registry.get_metric_class(metric_type)\n if metric_cls is None:\n raise ValueError(\n f\"No metric named {metric_type} registered to registry\"\n )\n\n metric_instance = metric_cls(**params)\n metric_instance.name = key\n metric_instance.set_applicable_datasets(dataset_names)\n\n metrics[key] = metric_instance\n self.required_params.update(metrics[key].required_params)\n\n return metrics\n\n def __call__(self, sample_list, model_output, *args, **kwargs):\n values = {}\n\n dataset_type = sample_list.dataset_type\n dataset_name = sample_list.dataset_name\n\n with torch.no_grad():\n for metric_name, metric_object in self.metrics.items():\n if not metric_object.is_dataset_applicable(dataset_name):\n continue\n key = f\"{dataset_type}/{dataset_name}/{metric_name}\"\n values[key] = metric_object._calculate_with_checks(\n sample_list, model_output, *args, **kwargs\n )\n\n if not isinstance(values[key], torch.Tensor):\n values[key] = torch.tensor(values[key], dtype=torch.float)\n else:\n values[key] = values[key].float()\n\n if values[key].dim() == 0:\n values[key] = values[key].view(1)\n\n registry.register(\n \"{}.{}.{}\".format(\"metrics\", sample_list.dataset_name, dataset_type), values\n )\n\n return values\n\n\nclass BaseMetric:\n \"\"\"Base class to be inherited by all metrics registered to MMF. See\n the description on top of the file for more information. Child class must\n implement ``calculate`` function.\n\n Args:\n name (str): Name of the metric.\n\n \"\"\"\n\n def __init__(self, name, *args, **kwargs):\n self.name = name\n self.required_params = [\"scores\", \"targets\"]\n # the set of datasets where this metric will be applied\n # an empty set means it will be applied on *all* datasets\n self._dataset_names = set()\n log_class_usage(\"Metric\", self.__class__)\n\n @property\n def name(self):\n return self._name\n\n @name.setter\n def name(self, name):\n self._name = name\n\n def calculate(self, sample_list, model_output, *args, **kwargs):\n \"\"\"Abstract method to be implemented by the child class. Takes\n in a ``SampleList`` and a dict returned by model as output and\n returns back a float tensor/number indicating value for this metric.\n\n Args:\n sample_list (SampleList): SampleList provided by the dataloader for the\n current iteration.\n model_output (Dict): Output dict from the model for the current\n SampleList\n\n Returns:\n torch.Tensor|float: Value of the metric.\n\n \"\"\"\n # Override in your child class\n raise NotImplementedError(\"'calculate' must be implemented in the child class\")\n\n def __call__(self, *args, **kwargs):\n return self.calculate(*args, **kwargs)\n\n def _calculate_with_checks(self, *args, **kwargs):\n value = self.calculate(*args, **kwargs)\n return value\n\n def set_applicable_datasets(self, dataset_names):\n self._dataset_names = set(dataset_names)\n\n def is_dataset_applicable(self, dataset_name):\n return len(self._dataset_names) == 0 or dataset_name in self._dataset_names\n\n\[email protected]_metric(\"accuracy\")\nclass Accuracy(BaseMetric):\n \"\"\"Metric for calculating accuracy.\n\n **Key:** ``accuracy``\n \"\"\"\n\n def __init__(self):\n super().__init__(\"accuracy\")\n\n def calculate(self, sample_list, model_output, *args, **kwargs):\n \"\"\"Calculate accuracy and return it back.\n\n Args:\n sample_list (SampleList): SampleList provided by DataLoader for\n current iteration\n model_output (Dict): Dict returned by model.\n\n Returns:\n torch.FloatTensor: accuracy.\n\n \"\"\"\n output = model_output[\"scores\"]\n expected = sample_list[\"targets\"]\n\n assert (\n output.dim() <= 2\n ), \"Output from model shouldn't have more than dim 2 for accuracy\"\n assert (\n expected.dim() <= 2\n ), \"Expected target shouldn't have more than dim 2 for accuracy\"\n\n if output.dim() == 2:\n output = torch.max(output, 1)[1]\n\n # If more than 1\n # If last dim is 1, we directly have class indices\n if expected.dim() == 2 and expected.size(-1) != 1:\n expected = torch.max(expected, 1)[1]\n\n correct = (expected == output.squeeze()).sum().float()\n total = len(expected)\n\n value = correct / total\n return value\n\n\[email protected]_metric(\"caption_bleu4\")\nclass CaptionBleu4Metric(BaseMetric):\n \"\"\"Metric for calculating caption accuracy using BLEU4 Score.\n\n **Key:** ``caption_bleu4``\n \"\"\"\n\n def __init__(self):\n import nltk.translate.bleu_score as bleu_score\n\n self._bleu_score = bleu_score\n super().__init__(\"caption_bleu4\")\n self.caption_processor = registry.get(\"coco_caption_processor\")\n self.required_params = [\"scores\", \"answers\", \"captions\"]\n\n def calculate(self, sample_list, model_output, *args, **kwargs):\n \"\"\"Calculate accuracy and return it back.\n\n Args:\n sample_list (SampleList): SampleList provided by DataLoader for\n current iteration\n model_output (Dict): Dict returned by model.\n\n Returns:\n torch.FloatTensor: bleu4 score.\n\n \"\"\"\n # Create reference and hypotheses captions.\n references = []\n hypotheses = []\n\n # References\n targets = sample_list.answers\n for j, _ in enumerate(targets):\n img_captions = [\n self.caption_processor(c)[\"tokens\"] for c in targets[j].tolist()\n ]\n references.append(img_captions)\n\n # Hypotheses\n if \"captions\" in model_output:\n scores = model_output[\"captions\"]\n else:\n scores = torch.max(model_output[\"scores\"], dim=-1)[1]\n scores = scores.tolist()\n predictions = []\n for j, _ in enumerate(scores):\n caption = self.caption_processor(scores[j])[\"tokens\"]\n predictions.append(caption)\n hypotheses.extend(predictions)\n\n assert len(references) == len(hypotheses)\n\n bleu4 = self._bleu_score.corpus_bleu(references, hypotheses)\n\n return targets.new_tensor(bleu4, dtype=torch.float)\n\n\[email protected]_metric(\"vqa_accuracy\")\nclass VQAAccuracy(BaseMetric):\n \"\"\"\n Calculate VQAAccuracy. Find more information here_\n\n **Key**: ``vqa_accuracy``.\n\n .. _here: https://visualqa.org/evaluation.html\n \"\"\"\n\n def __init__(self):\n super().__init__(\"vqa_accuracy\")\n\n def _masked_unk_softmax(self, x, dim, mask_idx):\n x1 = torch.nn.functional.softmax(x, dim=dim)\n x1[:, mask_idx] = 0\n x1_sum = torch.sum(x1, dim=1, keepdim=True)\n y = x1 / x1_sum\n return y\n\n def calculate(self, sample_list, model_output, *args, **kwargs):\n \"\"\"Calculate vqa accuracy and return it back.\n\n Args:\n sample_list (SampleList): SampleList provided by DataLoader for\n current iteration\n model_output (Dict): Dict returned by model.\n\n Returns:\n torch.FloatTensor: VQA Accuracy\n\n \"\"\"\n output = model_output[\"scores\"]\n # for three branch movie+mcan model\n if output.dim() == 3:\n output = output[:, 0]\n expected = sample_list[\"targets\"]\n\n output = self._masked_unk_softmax(output, 1, 0)\n output = output.argmax(dim=1) # argmax\n\n one_hots = expected.new_zeros(*expected.size())\n one_hots.scatter_(1, output.view(-1, 1), 1)\n scores = one_hots * expected\n accuracy = torch.sum(scores) / expected.size(0)\n\n return accuracy\n\n\[email protected]_metric(\"vqa_evalai_accuracy\")\nclass VQAEvalAIAccuracy(BaseMetric):\n \"\"\"\n Calculate Eval AI VQAAccuracy. Find more information here_\n This is more accurate and similar comparision to Eval AI\n but is slower compared to vqa_accuracy.\n\n **Key**: ``vqa_evalai_accuracy``.\n\n .. _here: https://visualqa.org/evaluation.html\n \"\"\"\n\n def __init__(self):\n super().__init__(\"vqa_evalai_accuracy\")\n self.evalai_answer_processor = EvalAIAnswerProcessor()\n self.required_params = [\"scores\", \"answers\", \"context_tokens\"]\n\n def _masked_unk_softmax(self, x, dim, mask_idx):\n x1 = torch.nn.functional.softmax(x, dim=dim)\n x1[:, mask_idx] = 0\n x1_sum = torch.sum(x1, dim=1, keepdim=True)\n y = x1 / x1_sum\n return y\n\n def calculate(self, sample_list, model_output, *args, **kwargs):\n \"\"\"Calculate vqa accuracy and return it back.\n\n Args:\n sample_list (SampleList): SampleList provided by DataLoader for\n current iteration\n model_output (Dict): Dict returned by model.\n\n Returns:\n torch.FloatTensor: VQA Accuracy\n\n \"\"\"\n output = model_output[\"scores\"]\n expected = sample_list[\"answers\"]\n\n answer_processor = registry.get(sample_list.dataset_name + \"_answer_processor\")\n answer_space_size = answer_processor.get_true_vocab_size()\n\n output = self._masked_unk_softmax(output, 1, 0)\n output = output.argmax(dim=1).clone().tolist()\n accuracy = []\n\n for idx, answer_id in enumerate(output):\n if answer_id >= answer_space_size:\n answer_id -= answer_space_size\n answer = sample_list[\"context_tokens\"][idx][answer_id]\n else:\n answer = answer_processor.idx2word(answer_id)\n\n answer = self.evalai_answer_processor(answer)\n\n gt_answers = [self.evalai_answer_processor(x) for x in expected[idx]]\n gt_answers = list(enumerate(gt_answers))\n\n gt_acc = []\n for gt_answer in gt_answers:\n other_answers = [item for item in gt_answers if item != gt_answer]\n matching_answers = [item for item in other_answers if item[1] == answer]\n acc = min(1, float(len(matching_answers)) / 3)\n gt_acc.append(acc)\n avgGTAcc = float(sum(gt_acc)) / len(gt_acc)\n accuracy.append(avgGTAcc)\n\n accuracy = float(sum(accuracy)) / len(accuracy)\n\n return model_output[\"scores\"].new_tensor(accuracy, dtype=torch.float)\n\n\nclass RecallAtK(BaseMetric):\n def __init__(self, name=\"recall@k\"):\n super().__init__(name)\n\n def score_to_ranks(self, scores):\n # sort in descending order - largest score gets highest rank\n sorted_ranks, ranked_idx = scores.sort(1, descending=True)\n\n # convert from ranked_idx to ranks\n ranks = ranked_idx.clone().fill_(0)\n for i in range(ranked_idx.size(0)):\n for j in range(100):\n ranks[i][ranked_idx[i][j]] = j\n ranks += 1\n return ranks\n\n def get_gt_ranks(self, ranks, ans_ind):\n _, ans_ind = ans_ind.max(dim=1)\n ans_ind = ans_ind.view(-1)\n gt_ranks = torch.LongTensor(ans_ind.size(0))\n\n for i in range(ans_ind.size(0)):\n gt_ranks[i] = int(ranks[i, ans_ind[i].long()])\n return gt_ranks\n\n def process_ranks(self, ranks):\n num_opts = 100\n\n # none of the values should be 0, there is gt in options\n if torch.sum(ranks.le(0)) > 0:\n num_zero = torch.sum(ranks.le(0))\n warnings.warn(f\"Some of ranks are zero: {num_zero}\")\n ranks = ranks[ranks.gt(0)]\n\n # rank should not exceed the number of options\n if torch.sum(ranks.ge(num_opts + 1)) > 0:\n num_ge = torch.sum(ranks.ge(num_opts + 1))\n warnings.warn(f\"Some of ranks > 100: {num_ge}\")\n ranks = ranks[ranks.le(num_opts + 1)]\n return ranks\n\n def get_ranks(self, sample_list, model_output, *args, **kwargs):\n output = model_output[\"scores\"]\n expected = sample_list[\"targets\"]\n\n ranks = self.score_to_ranks(output)\n gt_ranks = self.get_gt_ranks(ranks, expected)\n\n ranks = self.process_ranks(gt_ranks)\n return ranks.float()\n\n def calculate(self, sample_list, model_output, k, *args, **kwargs):\n ranks = self.get_ranks(sample_list, model_output)\n recall = float(torch.sum(torch.le(ranks, k))) / ranks.size(0)\n return recall\n\n\[email protected]_metric(\"r@1\")\nclass RecallAt1(RecallAtK):\n \"\"\"\n Calculate Recall@1 which specifies how many time the chosen candidate\n was rank 1.\n\n **Key**: ``r@1``.\n \"\"\"\n\n def __init__(self):\n super().__init__(\"r@1\")\n\n def calculate(self, sample_list, model_output, *args, **kwargs):\n \"\"\"Calculate Recall@1 and return it back.\n\n Args:\n sample_list (SampleList): SampleList provided by DataLoader for\n current iteration\n model_output (Dict): Dict returned by model.\n\n Returns:\n torch.FloatTensor: Recall@1\n\n \"\"\"\n return super().calculate(sample_list, model_output, k=1)\n\n\[email protected]_metric(\"r@5\")\nclass RecallAt5(RecallAtK):\n \"\"\"\n Calculate Recall@5 which specifies how many time the chosen candidate\n was among first 5 rank.\n\n **Key**: ``r@5``.\n \"\"\"\n\n def __init__(self):\n super().__init__(\"r@5\")\n\n def calculate(self, sample_list, model_output, *args, **kwargs):\n \"\"\"Calculate Recall@5 and return it back.\n\n Args:\n sample_list (SampleList): SampleList provided by DataLoader for\n current iteration\n model_output (Dict): Dict returned by model.\n\n Returns:\n torch.FloatTensor: Recall@5\n\n \"\"\"\n return super().calculate(sample_list, model_output, k=5)\n\n\[email protected]_metric(\"r@10\")\nclass RecallAt10(RecallAtK):\n \"\"\"\n Calculate Recall@10 which specifies how many time the chosen candidate\n was among first 10 ranks.\n\n **Key**: ``r@10``.\n \"\"\"\n\n def __init__(self):\n super().__init__(\"r@10\")\n\n def calculate(self, sample_list, model_output, *args, **kwargs):\n \"\"\"Calculate Recall@10 and return it back.\n\n Args:\n sample_list (SampleList): SampleList provided by DataLoader for\n current iteration\n model_output (Dict): Dict returned by model.\n\n Returns:\n torch.FloatTensor: Recall@10\n\n \"\"\"\n return super().calculate(sample_list, model_output, k=10)\n\n\[email protected]_metric(\"mean_r\")\nclass MeanRank(RecallAtK):\n \"\"\"\n Calculate MeanRank which specifies what was the average rank of the chosen\n candidate.\n\n **Key**: ``mean_r``.\n \"\"\"\n\n def __init__(self):\n super().__init__(\"mean_r\")\n\n def calculate(self, sample_list, model_output, *args, **kwargs):\n \"\"\"Calculate Mean Rank and return it back.\n\n Args:\n sample_list (SampleList): SampleList provided by DataLoader for\n current iteration\n model_output (Dict): Dict returned by model.\n\n Returns:\n torch.FloatTensor: mean rank\n\n \"\"\"\n ranks = self.get_ranks(sample_list, model_output)\n return torch.mean(ranks)\n\n\[email protected]_metric(\"mean_rr\")\nclass MeanReciprocalRank(RecallAtK):\n \"\"\"\n Calculate reciprocal of mean rank..\n\n **Key**: ``mean_rr``.\n \"\"\"\n\n def __init__(self):\n super().__init__(\"mean_rr\")\n\n def calculate(self, sample_list, model_output, *args, **kwargs):\n \"\"\"Calculate Mean Reciprocal Rank and return it back.\n\n Args:\n sample_list (SampleList): SampleList provided by DataLoader for\n current iteration\n model_output (Dict): Dict returned by model.\n\n Returns:\n torch.FloatTensor: Mean Reciprocal Rank\n\n \"\"\"\n ranks = self.get_ranks(sample_list, model_output)\n return torch.mean(ranks.reciprocal())\n\n\[email protected]_metric(\"textvqa_accuracy\")\nclass TextVQAAccuracy(BaseMetric):\n def __init__(self):\n super().__init__(\"textvqa_accuracy\")\n import mmf.utils.m4c_evaluators as evaluators\n\n self.evaluator = evaluators.TextVQAAccuracyEvaluator()\n self.required_params = [\"scores\", \"answers\", \"context_tokens\"]\n self.gt_key = \"answers\"\n\n def calculate(self, sample_list, model_output, *args, **kwargs):\n answer_processor = registry.get(sample_list.dataset_name + \"_answer_processor\")\n\n batch_size = sample_list.context_tokens.size(0)\n pred_answers = model_output[\"scores\"].argmax(dim=-1)\n context_tokens = sample_list.context_tokens.cpu().numpy()\n answers = sample_list.get(self.gt_key).cpu().numpy()\n answer_space_size = answer_processor.get_true_vocab_size()\n\n predictions = []\n from mmf.utils.distributed import byte_tensor_to_object\n from mmf.utils.text import word_tokenize\n\n for idx in range(batch_size):\n tokens = byte_tensor_to_object(context_tokens[idx])\n answer_words = []\n for answer_id in pred_answers[idx].tolist():\n if answer_id >= answer_space_size:\n answer_id -= answer_space_size\n answer_words.append(word_tokenize(tokens[answer_id]))\n else:\n if answer_id == answer_processor.EOS_IDX:\n break\n answer_words.append(\n answer_processor.answer_vocab.idx2word(answer_id)\n )\n\n pred_answer = \" \".join(answer_words).replace(\" 's\", \"'s\")\n gt_answers = byte_tensor_to_object(answers[idx])\n predictions.append({\"pred_answer\": pred_answer, \"gt_answers\": gt_answers})\n\n accuracy = self.evaluator.eval_pred_list(predictions)\n accuracy = torch.tensor(accuracy).to(sample_list.context_tokens.device)\n\n return accuracy\n\n\[email protected]_metric(\"stvqa_anls\")\nclass STVQAANLS(TextVQAAccuracy):\n def __init__(self):\n super().__init__()\n self.name = \"stvqa_anls\"\n import mmf.utils.m4c_evaluators as evaluators\n\n self.evaluator = evaluators.STVQAANLSEvaluator()\n\n\[email protected]_metric(\"stvqa_accuracy\")\nclass STVQAAccuracy(TextVQAAccuracy):\n def __init__(self):\n super().__init__()\n self.name = \"stvqa_accuracy\"\n import mmf.utils.m4c_evaluators as evaluators\n\n self.evaluator = evaluators.STVQAAccuracyEvaluator()\n\n\[email protected]_metric(\"ocrvqa_accuracy\")\nclass OCRVQAAccuracy(STVQAAccuracy):\n def __init__(self):\n super().__init__()\n # same as STVQAAccuracy except for the name\n self.name = \"ocrvqa_accuracy\"\n\n\[email protected]_metric(\"textcaps_bleu4\")\nclass TextCapsBleu4(TextVQAAccuracy):\n def __init__(self):\n super().__init__()\n self.name = \"textcaps_bleu4\"\n self.required_params = [\"scores\", \"ref_strs\", \"context_tokens\"]\n self.gt_key = \"ref_strs\"\n import mmf.utils.m4c_evaluators as evaluators\n\n self.evaluator = evaluators.TextCapsBleu4Evaluator()\n\n\[email protected]_metric(\"f1\")\nclass F1(BaseMetric):\n \"\"\"Metric for calculating F1. Can be used with type and params\n argument for customization. params will be directly passed to sklearn\n f1 function.\n **Key:** ``f1``\n \"\"\"\n\n def __init__(self, *args, **kwargs):\n super().__init__(\"f1\")\n self._multilabel = kwargs.pop(\"multilabel\", False)\n self._sk_kwargs = kwargs\n\n def calculate(self, sample_list, model_output, *args, **kwargs):\n \"\"\"Calculate f1 and return it back.\n\n Args:\n sample_list (SampleList): SampleList provided by DataLoader for\n current iteration\n model_output (Dict): Dict returned by model.\n\n Returns:\n torch.FloatTensor: f1.\n \"\"\"\n scores = model_output[\"scores\"]\n expected = sample_list[\"targets\"]\n\n if self._multilabel:\n output = torch.sigmoid(scores)\n output = torch.round(output)\n expected = _convert_to_one_hot(expected, output)\n else:\n # Multiclass, or binary case\n output = scores.argmax(dim=-1)\n if expected.dim() != 1:\n # Probably one-hot, convert back to class indices array\n expected = expected.argmax(dim=-1)\n\n value = f1_score(expected.cpu(), output.cpu(), **self._sk_kwargs)\n\n return expected.new_tensor(value, dtype=torch.float)\n\n\[email protected]_metric(\"macro_f1\")\nclass MacroF1(F1):\n \"\"\"Metric for calculating Macro F1.\n\n **Key:** ``macro_f1``\n \"\"\"\n\n def __init__(self, *args, **kwargs):\n super().__init__(average=\"macro\", **kwargs)\n self.name = \"macro_f1\"\n\n\[email protected]_metric(\"micro_f1\")\nclass MicroF1(F1):\n \"\"\"Metric for calculating Micro F1.\n\n **Key:** ``micro_f1``\n \"\"\"\n\n def __init__(self, *args, **kwargs):\n super().__init__(average=\"micro\", **kwargs)\n self.name = \"micro_f1\"\n\n\[email protected]_metric(\"binary_f1\")\nclass BinaryF1(F1):\n \"\"\"Metric for calculating Binary F1.\n\n **Key:** ``binary_f1``\n \"\"\"\n\n def __init__(self, *args, **kwargs):\n super().__init__(average=\"micro\", labels=[1], **kwargs)\n self.name = \"binary_f1\"\n\n\[email protected]_metric(\"multilabel_f1\")\nclass MultiLabelF1(F1):\n \"\"\"Metric for calculating Multilabel F1.\n\n **Key:** ``multilabel_f1``\n \"\"\"\n\n def __init__(self, *args, **kwargs):\n super().__init__(multilabel=True, **kwargs)\n self.name = \"multilabel_f1\"\n\n\[email protected]_metric(\"multilabel_micro_f1\")\nclass MultiLabelMicroF1(MultiLabelF1):\n \"\"\"Metric for calculating Multilabel Micro F1.\n\n **Key:** ``multilabel_micro_f1``\n \"\"\"\n\n def __init__(self, *args, **kwargs):\n super().__init__(average=\"micro\", **kwargs)\n self.name = \"multilabel_micro_f1\"\n\n\[email protected]_metric(\"multilabel_macro_f1\")\nclass MultiLabelMacroF1(MultiLabelF1):\n \"\"\"Metric for calculating Multilabel Macro F1.\n\n **Key:** ``multilabel_macro_f1``\n \"\"\"\n\n def __init__(self, *args, **kwargs):\n super().__init__(average=\"macro\", **kwargs)\n self.name = \"multilabel_macro_f1\"\n\n\[email protected]_metric(\"roc_auc\")\nclass ROC_AUC(BaseMetric):\n \"\"\"Metric for calculating ROC_AUC.\n See more details at `sklearn.metrics.roc_auc_score <http://scikit-learn.org/stable/modules/generated/sklearn.metrics.roc_auc_score.html#sklearn.metrics.roc_auc_score>`_ # noqa\n\n **Note**: ROC_AUC is not defined when expected tensor only contains one\n label. Make sure you have both labels always or use it on full val only\n\n **Key:** ``roc_auc``\n \"\"\"\n\n def __init__(self, *args, **kwargs):\n super().__init__(\"roc_auc\")\n self._sk_kwargs = kwargs\n\n def calculate(self, sample_list, model_output, *args, **kwargs):\n \"\"\"Calculate ROC_AUC and returns it back. The function performs softmax\n on the logits provided and then calculated the ROC_AUC.\n\n Args:\n sample_list (SampleList): SampleList provided by DataLoader for\n current iteration.\n model_output (Dict): Dict returned by model. This should contain \"scores\"\n field pointing to logits returned from the model.\n\n Returns:\n torch.FloatTensor: ROC_AUC.\n\n \"\"\"\n\n output = torch.nn.functional.softmax(model_output[\"scores\"], dim=-1)\n expected = sample_list[\"targets\"]\n expected = _convert_to_one_hot(expected, output)\n value = roc_auc_score(expected.cpu(), output.cpu(), **self._sk_kwargs)\n return expected.new_tensor(value, dtype=torch.float)\n\n\[email protected]_metric(\"micro_roc_auc\")\nclass MicroROC_AUC(ROC_AUC):\n \"\"\"Metric for calculating Micro ROC_AUC.\n\n **Key:** ``micro_roc_auc``\n \"\"\"\n\n def __init__(self, *args, **kwargs):\n super().__init__(average=\"micro\", **kwargs)\n self.name = \"micro_roc_auc\"\n\n\[email protected]_metric(\"macro_roc_auc\")\nclass MacroROC_AUC(ROC_AUC):\n \"\"\"Metric for calculating Macro ROC_AUC.\n\n **Key:** ``macro_roc_auc``\n \"\"\"\n\n def __init__(self, *args, **kwargs):\n super().__init__(average=\"macro\", **kwargs)\n self.name = \"macro_roc_auc\"\n\n\[email protected]_metric(\"ap\")\nclass AveragePrecision(BaseMetric):\n \"\"\"Metric for calculating Average Precision.\n See more details at `sklearn.metrics.average_precision_score <http://scikit-learn.org/stable/modules/generated/sklearn.metrics.average_precision_score.html#sklearn.metrics.average_precision_score>`_ # noqa\n If you are looking for binary case, please take a look at binary_ap\n **Key:** ``ap``\n \"\"\"\n\n def __init__(self, *args, **kwargs):\n super().__init__(\"ap\")\n self._sk_kwargs = kwargs\n\n def calculate(self, sample_list, model_output, *args, **kwargs):\n \"\"\"Calculate AP and returns it back. The function performs softmax\n on the logits provided and then calculated the AP.\n\n Args:\n sample_list (SampleList): SampleList provided by DataLoader for\n current iteration.\n model_output (Dict): Dict returned by model. This should contain \"scores\"\n field pointing to logits returned from the model.\n\n Returns:\n torch.FloatTensor: AP.\n\n \"\"\"\n\n output = torch.nn.functional.softmax(model_output[\"scores\"], dim=-1)\n expected = sample_list[\"targets\"]\n expected = _convert_to_one_hot(expected, output)\n value = average_precision_score(expected.cpu(), output.cpu(), **self._sk_kwargs)\n return expected.new_tensor(value, dtype=torch.float)\n\n\[email protected]_metric(\"binary_ap\")\nclass BinaryAP(AveragePrecision):\n \"\"\"Metric for calculating Binary Average Precision.\n See more details at `sklearn.metrics.average_precision_score <http://scikit-learn.org/stable/modules/generated/sklearn.metrics.average_precision_score.html#sklearn.metrics.average_precision_score>`_ # noqa\n **Key:** ``binary_ap``\n \"\"\"\n\n def __init__(self, *args, **kwargs):\n super().__init__(**kwargs)\n self.name = \"binary_ap\"\n\n def calculate(self, sample_list, model_output, *args, **kwargs):\n \"\"\"Calculate Binary AP and returns it back. The function performs softmax\n on the logits provided and then calculated the binary AP.\n\n Args:\n sample_list (SampleList): SampleList provided by DataLoader for\n current iteration.\n model_output (Dict): Dict returned by model. This should contain \"scores\"\n field pointing to logits returned from the model.\n\n Returns:\n torch.FloatTensor: AP.\n\n \"\"\"\n\n output = torch.nn.functional.softmax(model_output[\"scores\"], dim=-1)\n # Take the score for positive (1) label\n output = output[:, 1]\n expected = sample_list[\"targets\"]\n\n # One hot format -> Labels\n if expected.dim() == 2:\n expected = expected.argmax(dim=1)\n\n value = average_precision_score(expected.cpu(), output.cpu(), **self._sk_kwargs)\n return expected.new_tensor(value, dtype=torch.float)\n\n\[email protected]_metric(\"micro_ap\")\nclass MicroAP(AveragePrecision):\n \"\"\"Metric for calculating Micro Average Precision.\n\n **Key:** ``micro_ap``\n \"\"\"\n\n def __init__(self, *args, **kwargs):\n super().__init__(average=\"micro\", **kwargs)\n self.name = \"micro_ap\"\n\n\[email protected]_metric(\"macro_ap\")\nclass MacroAP(AveragePrecision):\n \"\"\"Metric for calculating Macro Average Precision.\n\n **Key:** ``macro_ap``\n \"\"\"\n\n def __init__(self, *args, **kwargs):\n super().__init__(average=\"macro\", **kwargs)\n self.name = \"macro_ap\"\n\n\[email protected]_metric(\"r@pk\")\nclass RecallAtPrecisionK(BaseMetric):\n \"\"\"Metric for calculating recall when precision is above a\n particular threshold. Use `p_threshold` param to specify the\n precision threshold i.e. k. Accepts precision in both 0-1\n and 1-100 format.\n\n **Key:** ``r@pk``\n \"\"\"\n\n def __init__(self, p_threshold, *args, **kwargs):\n \"\"\"Initialization function recall @ precision k\n\n Args:\n p_threshold (float): Precision threshold\n \"\"\"\n super().__init__(name=\"r@pk\")\n self.name = \"r@pk\"\n self.p_threshold = p_threshold if p_threshold < 1 else p_threshold / 100\n\n def calculate(self, sample_list, model_output, *args, **kwargs):\n \"\"\"Calculate Recall at precision k and returns it back. The function\n performs softmax on the logits provided and then calculated the metric.\n\n Args:\n sample_list (SampleList): SampleList provided by DataLoader for\n current iteration.\n model_output (Dict): Dict returned by model. This should contain \"scores\"\n field pointing to logits returned from the model.\n\n Returns:\n torch.FloatTensor: Recall @ precision k.\n\n \"\"\"\n output = torch.nn.functional.softmax(model_output[\"scores\"], dim=-1)[:, 1]\n expected = sample_list[\"targets\"]\n\n # One hot format -> Labels\n if expected.dim() == 2:\n expected = expected.argmax(dim=1)\n\n precision, recall, thresh = precision_recall_curve(expected.cpu(), output.cpu())\n\n try:\n value, _ = max(\n (r, p) for p, r in zip(precision, recall) if p >= self.p_threshold\n )\n except ValueError:\n value = 0\n\n return expected.new_tensor(value, dtype=torch.float)\n\n\[email protected]_metric(\"r@k_retrieval\")\nclass RecallAtK_ret(BaseMetric):\n def __init__(self, name=\"recall@k\"):\n super().__init__(name)\n\n def _get_RatK_multi(\n self, correlations: Tensor, labels: Tensor, k: int, factor: int\n ):\n _, top_k_ids = torch.topk(correlations, k, dim=1)\n hits = (\n torch.logical_and(\n labels[:, None] <= top_k_ids, top_k_ids < labels[:, None] + factor\n )\n .long()\n .max(dim=1)[0]\n )\n return hits\n\n def calculate(\n self,\n sample_list: Dict[str, Tensor],\n model_output: Dict[str, Tensor],\n k: int,\n flip=False,\n *args,\n **kwargs,\n ):\n # calculate image to text retrieval recalls\n # correlations shape is either BxB or Bx(5B)\n # when flip=True, calculate text to image\n image_embeddings = model_output[\"scores\"]\n text_embeddings = model_output[\"targets\"]\n\n correlations = image_embeddings @ text_embeddings.t() # B x B or Bx5B\n assert correlations.shape[1] % correlations.shape[0] == 0\n batch_size = correlations.shape[0]\n factor = correlations.shape[1] // correlations.shape[0]\n labels = torch.arange(batch_size, device=image_embeddings.device) * factor\n if flip:\n correlations = correlations.t() # 5B x B\n labels = torch.arange(batch_size, device=image_embeddings.device)\n labels = labels[:, None].expand(-1, factor).flatten()\n factor = 1\n hits = self._get_RatK_multi(correlations, labels, k, factor)\n ratk = hits.sum().float() / hits.shape[0]\n return ratk\n\n\[email protected]_metric(\"r@1_retrieval\")\nclass RecallAt1_ret(RecallAtK_ret):\n def __init__(self):\n super().__init__(\"r@1\")\n\n def calculate(\n self,\n sample_list: Dict[str, Tensor],\n model_output: Dict[str, Tensor],\n *args,\n **kwargs,\n ):\n ratk = super().calculate(sample_list, model_output, 1)\n return ratk\n\n\[email protected]_metric(\"r@1_rev_retrieval\")\nclass RecallAt1_rev_ret(RecallAtK_ret):\n def __init__(self):\n super().__init__(\"r@1_rev\")\n\n def calculate(\n self,\n sample_list: Dict[str, Tensor],\n model_output: Dict[str, Tensor],\n *args,\n **kwargs,\n ):\n ratk = super().calculate(sample_list, model_output, 1, flip=True)\n return ratk\n\n\[email protected]_metric(\"r@5_retrieval\")\nclass RecallAt5_ret(RecallAtK_ret):\n def __init__(self):\n super().__init__(\"r@5\")\n\n def calculate(\n self,\n sample_list: Dict[str, Tensor],\n model_output: Dict[str, Tensor],\n *args,\n **kwargs,\n ):\n ratk = super().calculate(sample_list, model_output, 5)\n return ratk\n\n\[email protected]_metric(\"r@5_rev_retrieval\")\nclass RecallAt5_rev_ret(RecallAtK_ret):\n def __init__(self):\n super().__init__(\"r@5_rev\")\n\n def calculate(\n self,\n sample_list: Dict[str, Tensor],\n model_output: Dict[str, Tensor],\n *args,\n **kwargs,\n ):\n ratk = super().calculate(sample_list, model_output, 5, flip=True)\n return ratk\n\n\[email protected]_metric(\"r@10_retrieval\")\nclass RecallAt10_ret(RecallAtK_ret):\n def __init__(self):\n super().__init__(\"r@10\")\n\n def calculate(\n self,\n sample_list: Dict[str, Tensor],\n model_output: Dict[str, Tensor],\n *args,\n **kwargs,\n ):\n ratk = super().calculate(sample_list, model_output, 10)\n return ratk\n\n\[email protected]_metric(\"r@10_rev_retrieval\")\nclass RecallAt10_rev_ret(RecallAtK_ret):\n def __init__(self):\n super().__init__(\"r@10_rev\")\n\n def calculate(\n self,\n sample_list: Dict[str, Tensor],\n model_output: Dict[str, Tensor],\n *args,\n **kwargs,\n ):\n ratk = super().calculate(sample_list, model_output, 10, flip=True)\n return ratk\n\n\[email protected]_metric(\"detection_mean_ap\")\nclass DetectionMeanAP(BaseMetric):\n \"\"\"Metric for calculating the detection mean average precision (mAP) using the COCO\n evaluation toolkit, returning the default COCO-style mAP@IoU=0.50:0.95\n\n **Key:** ``detection_mean_ap``\n \"\"\"\n\n def __init__(self, dataset_json_files, *args, **kwargs):\n \"\"\"Initialization function detection mean AP (mAP)\n\n Args:\n dataset_json_files (Dict): paths to the dataset (instance) json files\n for each dataset type and dataset name in the following format:\n ``{'val/detection_coco': '/path/to/instances_val2017.json', ...}``\n\n \"\"\"\n super().__init__(\"detection_mean_ap\")\n self.required_params = [\"__prediction_report__\"]\n self.dataset_json_files = dataset_json_files\n\n def calculate(\n self, sample_list, model_output, execute_on_master_only=True, *args, **kwargs\n ):\n \"\"\"Calculate detection mean AP (mAP) from the prediction list and the dataset\n annotations. The function returns COCO-style mAP@IoU=0.50:0.95.\n\n Args:\n sample_list (SampleList): SampleList provided by DataLoader for\n current iteration.\n model_output (Dict): Dict returned by model. This should contain\n \"prediction_report\" field, which is a list of\n detection predictions from the model.\n execute_on_master_only (bool): Whether to only run mAP evaluation on the\n master node over the gathered detection prediction\n (to avoid wasting computation and CPU OOM).\n Default: True (only run mAP evaluation on master).\n\n Returns:\n torch.FloatTensor: COCO-style mAP@IoU=0.50:0.95.\n\n \"\"\"\n\n # as the detection mAP metric is run on the entire dataset-level predictions,\n # which are *already* gathered from all notes, the evaluation should only happen\n # in one node and broadcasted to other nodes (to avoid CPU OOM due to concurrent\n # mAP evaluation)\n from pycocotools.coco import COCO\n from pycocotools.cocoeval import COCOeval\n from mmf.utils.distributed import is_master, broadcast_tensor\n from mmf.utils.general import get_current_device\n\n device = get_current_device()\n if execute_on_master_only and not is_master():\n # dummy mAP to be override in boardcasting\n mAP = torch.tensor(-1, dtype=torch.float, device=device)\n else:\n predictions = model_output.prediction_report\n\n cocoGt = COCO(\n self.dataset_json_files[sample_list.dataset_name][\n sample_list.dataset_type\n ]\n )\n cocoDt = cocoGt.loadRes(predictions)\n cocoEval = COCOeval(cocoGt, cocoDt, \"bbox\")\n cocoEval.evaluate()\n cocoEval.accumulate()\n cocoEval.summarize()\n mAP = torch.tensor(cocoEval.stats[0], dtype=torch.float, device=device)\n\n if execute_on_master_only:\n mAP = broadcast_tensor(mAP, src=0)\n return mAP\n"
] | [
[
"torch.mean",
"torch.nn.functional.softmax",
"torch.sigmoid",
"torch.max",
"torch.round",
"torch.sum",
"torch.tensor",
"torch.le",
"torch.no_grad",
"torch.arange",
"torch.topk",
"torch.logical_and"
]
] |
mori97/dgl | [
"ed1948b5555106dee133cef91ed9ecfd3bd4310d"
] | [
"tests/backend/pytorch/__init__.py"
] | [
"from __future__ import absolute_import\n\nimport torch as th\n\ndef cuda():\n return th.device('cuda')\n\ndef array_equal(a, b):\n return th.equal(a, b)\n\ndef allclose(a, b):\n return th.allclose(a.float(), b.float(), rtol=1e-4, atol=1e-4)\n\ndef randn(shape):\n return th.randn(*shape)\n\ndef attach_grad(x):\n if x.grad is not None:\n x.grad.zero_()\n return x\n else:\n return x.requires_grad_()\n\ndef backward(x, head_gradient=None):\n x.backward(head_gradient)\n\ndef grad(x):\n return x.grad\n\ndef is_no_grad(x):\n return x.grad is None or (x.grad == 0).all()\n\ndef full(shape, fill_value, dtype, ctx):\n return th.full(shape, fill_value, dtype=dtype, device=ctx)\n\ndef narrow_row_set(x, start, stop, new):\n x[start:stop] = new\n\ndef sparse_to_numpy(x):\n return x.to_dense().numpy()\n\ndef clone(x):\n return x.clone()\n\ndef reduce_sum(x):\n return x.sum()\n\n\nclass record_grad(object):\n def __init__(self):\n pass\n\n def __enter__(self):\n pass\n\n def __exit__(self, exc_type, exc_value, exc_traceback):\n pass\n\nno_grad = th.no_grad\n"
] | [
[
"torch.device",
"torch.randn",
"torch.full",
"torch.equal"
]
] |
sizumita/restaurants_viewer | [
"eae056893941cf39fa87640bffea72a8aed47c4a"
] | [
"arview.py"
] | [
"# coding: utf-8\n\nimport json\nimport time\nfrom enum import IntFlag\nfrom math import pi\nimport location\nimport numpy\nimport requests\nimport ui\nfrom numpy import sin, cos\nfrom objc_util import *\n\n\nclass SCNVector3(Structure):\n _fields_ = [('x', c_float), ('y', c_float), ('z', c_float)]\n\n\nload_framework('SceneKit')\nload_framework('ARKit')\nwith open('token.txt') as f:\n API_KEY = f.read().replace('\\n', '')\n\nURL = 'http://webservice.recruit.co.jp/hotpepper/gourmet/v1/?key={0}&lat={1}&lng={2}&range=5&format=json'\n\nbyou = 25.2\nscale = 40\nW = 4\nL = 100\nH = 4\n\n\nclass_list = [\n 'NSError', 'SCNScene', 'ARSCNView',\n 'ARWorldTrackingConfiguration',\n 'ARSession', 'UIViewController',\n 'ARPlaneAnchor', 'SCNView', 'SCNBox',\n 'SCNText', 'SCNNode',\n 'SCNLight', 'SCNCamera',\n 'SCNAction',\n 'SCNTransaction',\n 'UIFont',\n 'SCNSphere', 'SCNFloor',\n 'SCNLookAtConstraint',\n 'SCNPhysicsShape',\n 'SCNPhysicsBody',\n 'UIColor', 'NSObject'\n]\n\nNSError, SCNScene, ARSCNView, ARWorldTrackingConfiguration, \\\nARSession, UIViewController, ARPlaneAnchor, SCNView, SCNBox, \\\nSCNText, SCNNode, SCNLight, SCNCamera, SCNAction, SCNTransaction, \\\nUIFont, SCNSphere, SCNFloor, SCNLookAtConstraint, \\\nSCNPhysicsShape, SCNPhysicsBody, UIColor, NSObject = map(ObjCClass, class_list)\ndeepskyblue = UIColor.color(red=0.0, green=191.0, blue=255.0, alpha=1.0)\n\nrotate_action = SCNAction.rotateByX_y_z_duration_(0, pi * 2, 0, 10)\nup = SCNAction.moveByX_y_z_duration_(0, 30, 0, 3)\ndown = SCNAction.moveByX_y_z_duration_(0, -30, 0, 3)\nup_down = SCNAction.sequence_([up, down])\n\nscene_view = None\n\n\nclass ARWorldAlignment(IntFlag):\n ARWorldAlignmentGravity = 0\n ARWorldAlignmentGravityAndHeading = 1\n ARWorldAlignmentCamera = 2\n\n\nclass ARPlaneDetection(IntFlag):\n ARPlaneDetectionNone = 0\n ARPlaneDetectionHorizontal = 1 << 0\n ARPlaneDetectionVertical = 1 << 1\n\n\nclass ARSessionRunOptions(IntFlag):\n ARSessionRunOptionsNone = 0\n ARSessionRunOptionResetTracking = 1 << 0\n ARSessionRunOptionRemoveExistingAnchors = 1 << 1\n\n\ndef get_location():\n location.start_updates() # GPSデータ更新を開始\n gps_data = location.get_location() # GPSデータを取得する\n location.stop_updates() # GPSデータ更新を終了\n\n return gps_data['latitude'], gps_data['longitude']\n\n\ndef get_restaurants(_lat, _lng):\n \"\"\"緯度: lat 経度: lng\"\"\"\n response = requests.get(URL.format(API_KEY, _lat, _lng))\n result = json.loads(response.text)\n lat_lng = []\n for restaurant in result['results']['shop']:\n lat = float(restaurant['lat'])\n lng = float(restaurant['lng'])\n lat_lng.append((lat, lng, restaurant['name']))\n r = []\n for lat, lng, name in lat_lng:\n r2 = []\n\n difference = (_lat - lat) * 3600\n r2.append(int(difference * byou))\n\n difference = (lng - _lng) * 3600\n r2.append(int(difference * byou))\n r2.append(name)\n\n r.append(r2)\n\n return r\n\n\ndef createARSceneView(x, y, w, h, debug=True):\n v = ARSCNView.alloc().initWithFrame_((CGRect(CGPoint(x, y), CGSize(w, h))))\n v.setShowsStatistics_(debug)\n return v\n\n\n@on_main_thread\ndef run(ar_session):\n ar_configuration = ARWorldTrackingConfiguration.alloc().init()\n ar_configuration.setPlaneDetection_(ARPlaneDetection.ARPlaneDetectionHorizontal)\n ar_configuration.setWorldAlignment_(\n ARWorldAlignment.ARWorldAlignmentGravity)\n\n ar_session.runWithConfiguration_options_(ar_configuration,\n ARSessionRunOptions.ARSessionRunOptionResetTracking | ARSessionRunOptions.ARSessionRunOptionRemoveExistingAnchors)\n\n time.sleep(0.5)\n\n\ndef CustomViewController_viewWillAppear_(_self, _cmd, animated):\n return\n\n\ndef CustomViewController_viewWillDisappear_(_self, _cmd, animated):\n session = scene_view.session()\n session.pause()\n\n\ndef MyARSCNViewDelegate_renderer_didAdd_for_(_self, _cmd, scenerenderer, node, anchor):\n if not isinstance(anchor, ARPlaneAnchor):\n return\n\n\ndef MyARSCNViewDelegate_session_didFailWithError_(_self, _cmd, _session, _error):\n print('error', _error, _cmd, _session)\n err_obj = ObjCInstance(_error)\n print(err_obj)\n\n\ndef convert_round(x, z, r):\n cosr = cos(r)\n sinr = sin(r)\n X = cosr * x - sinr * z\n Z = sinr * x + cosr * z\n return X, Z\n\n\ndef get_text(text, x, y, z):\n text_mesh = SCNText.textWithString_extrusionDepth_(text, 3.0)\n text_mesh.setFlatness_(0.2)\n text_mesh.setChamferRadius_(0.4)\n text_mesh.setFont_(UIFont.fontWithName_size_('HoeflerText-Black', 15))\n bbox_min, bbox_max = SCNVector3(), SCNVector3()\n text_mesh.getBoundingBoxMin_max_(byref(bbox_min), byref(bbox_max), restype=None,\n argtypes=[POINTER(SCNVector3), POINTER(SCNVector3)])\n text_width = bbox_max.x - bbox_min.x\n text_node = SCNNode.nodeWithGeometry_(text_mesh)\n text_node.setCastsShadow_(True)\n text_container = SCNNode.node()\n text_container.addChildNode_(text_node)\n text_container.setPosition_((x, y, z))\n text_container.runAction(SCNAction.repeatActionForever(SCNAction.group([rotate_action, up_down])))\n text_node.setPosition_((-text_width / 2, 0, 0))\n return text_container\n\n\ndef add_restaurants(root_node, round_num):\n restaurants = get_restaurants(*get_location())\n if round_num == 90.0 or round_num == 0:\n r = 0\n elif round_num < 90:\n if round_num < 45:\n r = round_num + (45 - round_num)\n else:\n r = 45 + round_num * 2\n else:\n r = round_num\n for restaurant in restaurants:\n box = SCNBox.boxWithWidth_height_length_chamferRadius_(W, L, H, 0)\n box_node = SCNNode.nodeWithGeometry_(box)\n x, z = restaurant[1], restaurant[0]\n\n if r:\n x, z = convert_round(x, z, r)\n box_node.setPosition_((x, 25, z))\n box_node.runAction(SCNAction.repeatActionForever(rotate_action))\n\n a = numpy.array([0, 0])\n b = numpy.array(restaurant[:2])\n u = b - a\n length = numpy.linalg.norm(u)\n\n if length < 100:\n box.material().setColor_(deepskyblue.CGColor())\n else:\n box.material().setColor_(UIColor.blueColor().CGColor())\n name = str(restaurant[2])\n metal = '{}メートル'.format(int(length))\n root_node.addChildNode_(\n get_text('{0}\\n{1}'.format(name, metal.center(len(name))), x - 6, 25, z - 6))\n root_node.addChildNode_(box_node)\n\n\nclass MyARView(ui.View):\n def __init__(self):\n super().__init__(self)\n self.flex = 'WH'\n\n @on_main_thread\n def initialize(self, round_num):\n global scene_view\n\n screen = ui.get_screen_size()\n\n # シーンのセットアップ\n scene = SCNScene.scene()\n\n # view delegateのセットアップ\n methods = [MyARSCNViewDelegate_renderer_didAdd_for_, MyARSCNViewDelegate_session_didFailWithError_]\n protocols = ['ARSCNViewDelegate']\n MyARSCNViewDelegate = create_objc_class('MyARSCNViewDelegate', NSObject, methods=methods, protocols=protocols)\n delegate = MyARSCNViewDelegate.alloc().init()\n\n # シーンviewのセットアップ\n scene_view = createARSceneView(0, 0, screen.width, screen.height)\n scene_view.scene = scene\n scene_view.setDelegate_(delegate)\n\n # コントローラーのセットアップ\n methods = [CustomViewController_viewWillAppear_, CustomViewController_viewWillDisappear_]\n protocols = []\n CustomViewController = create_objc_class('CustomViewController', UIViewController, methods=methods,\n protocols=protocols)\n cvc = CustomViewController.alloc().init()\n cvc.view = scene_view\n\n # 初期設定\n self_objc = ObjCInstance(self)\n self_objc.nextResponder().addChildViewController_(cvc)\n self_objc.addSubview_(scene_view)\n cvc.didMoveToParentViewController_(self_objc)\n\n # ARのセッションを開始\n run(scene_view.session())\n\n root_node = scene.rootNode()\n\n scene_view = SCNView.alloc().initWithFrame_options_(((0, 0), (400, 400)), None).autorelease()\n scene_view.setAutoresizingMask_(18)\n scene_view.setAllowsCameraControl_(True)\n\n # 光源設定\n light_node = SCNNode.node()\n light_node.setPosition_((1.5, 1.5, 1.5))\n light = SCNLight.light()\n light.setType_('omni')\n light.setCastsShadow_(True)\n light_node.setLight_(light)\n\n # カメラ設定\n camera = SCNCamera.camera()\n camera_node = SCNNode.node()\n camera_node.setCamera(camera)\n camera_node.setPosition((0, 2, 0))\n\n # メインノードに子ノードを追加\n root_node.addChildNode_(camera_node)\n root_node.addChildNode_(light_node)\n add_restaurants(root_node, round_num)\n\n def will_close(self):\n session = scene_view.session()\n session.pause()\n\n\nif __name__ == '__main__':\n v = MyARView()\n v.present('full_screen', hide_title_bar=True, orientations=['portrait'])\n v.initialize(0)\n"
] | [
[
"numpy.array",
"numpy.linalg.norm",
"numpy.cos",
"numpy.sin"
]
] |
williamdjones/moses | [
"bbea6b06bdb9ca0dc0d4550c52ac40beef8dae0b"
] | [
"scripts/eval.py"
] | [
"import argparse\nimport numpy as np\nimport rdkit\n\nfrom moses.metrics.metrics import get_all_metrics\nfrom moses.script_utils import read_smiles_csv\n\nlg = rdkit.RDLogger.logger()\nlg.setLevel(rdkit.RDLogger.CRITICAL)\n\n\ndef main(config, print_metrics=True):\n test = None\n test_scaffolds = None\n ptest = None\n ptest_scaffolds = None\n train = None\n if config.test_path:\n test = read_smiles_csv(config.test_path)\n if config.test_scaffolds_path is not None:\n test_scaffolds = read_smiles_csv(config.test_scaffolds_path)\n if config.train_path is not None:\n train = read_smiles_csv(config.train_path)\n if config.ptest_path is not None:\n ptest = np.load(\n config.ptest_path,\n allow_pickle=True)['stats'].item()\n if config.ptest_scaffolds_path is not None:\n ptest_scaffolds = np.load(\n config.ptest_scaffolds_path,\n allow_pickle=True)['stats'].item()\n gen = read_smiles_csv(config.gen_path)\n metrics = get_all_metrics(gen=gen, k=config.ks, n_jobs=config.n_jobs,\n device=config.device,\n test_scaffolds=test_scaffolds,\n ptest=ptest, ptest_scaffolds=ptest_scaffolds,\n test=test, train=train)\n\n if print_metrics:\n for name, value in metrics.items():\n print('{},{}'.format(name, value))\n else:\n return metrics\n\n\ndef get_parser():\n parser = argparse.ArgumentParser()\n parser.add_argument('--test_path',\n type=str, required=False,\n help='Path to test molecules csv')\n parser.add_argument('--test_scaffolds_path',\n type=str, required=False,\n help='Path to scaffold test molecules csv')\n parser.add_argument('--train_path',\n type=str, required=False,\n help='Path to train molecules csv')\n parser.add_argument('--ptest_path',\n type=str, required=False,\n help='Path to precalculated test npz')\n parser.add_argument('--ptest_scaffolds_path',\n type=str, required=False,\n help='Path to precalculated scaffold test npz')\n parser.add_argument('--gen_path',\n type=str, required=True,\n help='Path to generated molecules csv')\n parser.add_argument('--ks', '--unique_k',\n nargs='+', default=[1000, 10000],\n type=int,\n help='Number of molecules to calculate uniqueness at.'\n 'Multiple values are possible. Defaults to '\n '--unique_k 1000 10000')\n parser.add_argument('--n_jobs',\n type=int, default=1,\n help='Number of processes to run metrics')\n parser.add_argument('--device',\n type=str, default='cpu',\n help='GPU device id (`cpu` or `cuda:n`)')\n\n return parser\n\n\nif __name__ == \"__main__\":\n parser = get_parser()\n config = parser.parse_known_args()[0]\n main(config)\n"
] | [
[
"numpy.load"
]
] |
zchu-hit-scir/SG-Bert-reproduced | [
"792e61a90947e6e02db646dce422ba558d579cb4"
] | [
"myModule.py"
] | [
"from re import template\nfrom torch.nn.modules.activation import GELU\nfrom transformers import (\n AutoModel, \n AutoTokenizer\n)\nimport numpy as np\nimport random\nimport torch\nfrom torch import nn, utils, optim\nfrom torch.utils.data import DataLoader\nfrom torch.nn import functional as F\nimport os\nfrom os import path as osp\nfrom mylib.utils import (\n get_device\n)\n\"\"\"\nSelf-Guided Contrastive Learning for BERT Sentence Representations\nhttps://arxiv.org/abs/2106.07345\n\"\"\"\ndevice = get_device()\nclass UniformSampler(nn.Module):\n \"\"\"\n Uniformly sample the hidden states of each layer, in other words, average the hidden states of all layers\n \"\"\"\n def __init__(self):\n super().__init__()\n \n def forward(self, hidden_states):\n \"\"\"\n hidden_states: the hiddens states of all layers after poolings. [batch_size, layer_num, hidden_dim]\n return: hiddens states after uniform sample. [batch_size, hidden_dim]\n \"\"\"\n if hidden_states.ndim != 3:\n raise NotImplementedError('hidden_states\\' dimensions shoule be 3, including(batch, layer, hidden)')\n \n return torch.mean(hidden_states, dim=1, keepdim=False)\n\nclass WeightedSampler(nn.Module):\n \"\"\"\n Weighted Average over the hidden_states of all layers. \n \"\"\"\n def __init__(self, weights:torch.FloatTensor):\n super().__init__()\n self.weights = weights\n \n def forward(self, hidden_states, weights:torch.FloatTensor =None):\n if weights is not None:\n w = self.weights\n else:\n w = weights\n \n if hidden_states.ndim != 3:\n raise NotImplementedError('hidden_states\\' dimensions shoule be 3, including(batch, layer, hidden)')\n\n batch_size, layer_num, hidden_dim = hidden_states.shape\n if layer_num != len(w):\n raise NotImplementedError('layer_num should have same length with weights')\n \n #sum over w == 1, [layer_num]\n w = w / w.sum()\n\n return torch.sum(\n hidden_states * w.unsqueeze(0).unsqueeze(-1)\n )\n\nclass SGLossOpt2(nn.Module):\n \"\"\"\n Exactly the same loss func with Unsupervised SimCSE\n \"\"\"\n def __init__(self, temp):\n super().__init__()\n self.temp = temp\n \n def forward(self, cls, hidden):\n \"\"\"\n both cls and hidden are in same dimension [batch_size, hidden], cls is [cls_token] from BERT_T, hidden is [sampler_out] from BERT_F\n return loss, sim\n \"\"\"\n # using broadcast to calculate similarities, sim[batch_size, batch_size]\n sim = F.cosine_similarity(cls.unsqueeze(1), hidden.unsqueeze(0), dim=-1) / self.temp\n label = torch.arange(sim.shape[0]).long().to(sim.device)\n\n return F.cross_entropy(sim, label)\n\nclass SGLossOpt3(nn.Module):\n \"\"\"\n Opt3 loss(SG-opt loss) in \"Self-Guided Contrastive Learning for BERT Sentence Representations\"\n in this optimize objectives, Sampler is not used \n \"\"\"\n def __init__(self, temp):\n super().__init__()\n self.temp = temp\n \n def forward(self, cls, hidden):\n \"\"\"\n cls:[batch_size, hidden_dim]\n hidden:[batch_size, layer_num, hidden_dim]\n return loss, sim\n \"\"\" \n\n if hidden.ndim != 3:\n raise NotImplementedError('hidden_states\\' dimensions shoule be 3, including(batch, layer, hidden)')\n\n batch_size, layer_num, hidden_dim = hidden.shape\n\n #sim_ci_hik [batch_size, layers]\n #sim_ci_hmn [batch_size, batch_size, layers]\n sim_ci_hik = torch.exp(F.cosine_similarity(cls.unsqueeze(1), hidden, dim=-1) / self.temp) \n sim_ci_hmn = torch.exp(torch.stack([\n F.cosine_similarity(c_i, hidden, -1) / self.temp for c_i in cls\n ], dim=0)) \n\n\n #hmn_mask [batch, batch*layers] \n #sim_ci_hmn reshape [batch, batch*layers]\n hmn_mask = (torch.ones(batch_size, batch_size) - torch.eye(batch_size)).repeat(1, layer_num).to(device)\n sim_ci_hmn = sim_ci_hmn.reshape(batch_size, batch_size * layer_num)\n \n sim_after_mask = sim_ci_hmn * hmn_mask\n\n loss_list = []\n for i in range(batch_size):\n for k in range(layer_num):\n loss_list.append(\n - torch.log(sim_ci_hik[i, k]) \\\n + torch.log(sim_ci_hik[i, k] + sim_after_mask[i].sum())\n )\n return torch.stack(loss_list).mean()\n \n\nclass SGLossOpt3Simplified(nn.Module):\n \"\"\"\n Simplified Opt3 loss(SG-opt loss) in \"Self-Guided Contrastive Learning for BERT Sentence Representations\"\n simplified the denominator, not reconmended.\n SGLossOpt3 and SGLossOpt2 is recommended \n \"\"\"\n def __init__(self, temp):\n super().__init__()\n self.temp = temp\n \n def forward(self, cls, hidden):\n \"\"\"\n cls:[batch_size, hidden_dim]\n hidden:[batch_size, layer_num, hidden_dim]\n return loss, sim\n \"\"\"\n\n if hidden.ndim != 3:\n raise NotImplementedError('hidden_states\\' dimensions shoule be 3, including(batch, layer, hidden)')\n\n batch_size, layer_num, hidden_dim = hidden.shape\n #这个损失要如何写成矩阵运算的形式?\n #How do I write this loss in terms of matrix operations? Not the for loop.\n\n #step1 计算损失函数的分子\n #sim_ci_hik [batch_size, layers], \n #sim_ci_hik[i] 代表第i个句子中,c_i和h_i0 ~ h_il的相似度\n sim_ci_hik = torch.exp(F.cosine_similarity(cls.unsqueeze(1), hidden, dim=-1) / self.temp) \n\n #step2 计算损失的分母\n #sim_ci_hmn [batch_size, batch_size, layers]\n #sim_ci_hmn[i] 代表第i个句子和其他所有句子所有层的相似度矩阵\n sim_ci_hmn = torch.exp(torch.stack([\n F.cosine_similarity(c_i, hidden, -1) / self.temp for c_i in cls\n ], dim=0)) \n\n #log(a) + log(b) = log(a*b)\n #对分子而言, sum over batch and layers: sim_ci_hik所有元素相乘\n #对分母而言,分两个步骤,由于简化过,sum over layers = sim_ci_hmn[i].sum() ^ k, 其中i是固定的\n #分母的第二个步骤, sum over batch, 对i进行遍历, prod over (sim_ci_hmn[i].sum() ^ k), i为遍历变量,\n #之后对上述结果做-log即可\n\n\n #[batch_size * layers]\n sim_ci_hik = sim_ci_hik.reshape(-1)\n loss1 = - torch.log(sim_ci_hik).sum()\n\n #[batch_size]\n sum_over_mn = sim_ci_hmn.sum(dim=[1, 2])\n loss2 = torch.log(sum_over_mn).sum()\n\n return loss1 + loss2\n\nclass RegHiddenLoss(nn.Module):\n \"\"\"\n Impose L2-norm between the hidden_states of the two models as punishment\n not implemented.\n \"\"\"\n def __init__(self):\n super().__init__()\n \n def forward(self, hidden1, hidden2):\n #input: hidden_states(tuple of tensor)\n #output: loss\n param_list = []\n for h1, h2 in zip(hidden1, hidden2):\n h = (h1 - h2).reshape(-1).pow(2).sum()\n param_list.append(h)\n \n return torch.sum(torch.stack(param_list)).sqrt()\n\nclass RegLoss(nn.Module):\n \"\"\"\n Impose L2-norm between the parameters of encoder part of the two models as punishment\n recommended.\n \"\"\"\n def __init__(self):\n super().__init__()\n self.epsilon = 1e-8\n\n def forward(self, param1, param2):\n #input: model.encoder.parameters()\n #output: loss\n param_list = []\n for part1, part2 in zip(param1, param2):\n param = (part1 - part2).reshape(-1).pow(2).sum()\n param_list.append(param)\n\n #derivatives of sqrt(x) is 1/2 * (1 / sqrt(x)), if x == 0, the denominator of the derivative will become 0, resulting in nan\n return torch.sqrt(sum(param_list) + self.epsilon)\n return sum(param_list).sqrt()\n \n\nclass TotalLoss(nn.Module):\n \"\"\"\n merge (self-guided contrastive loss), (layer sampler), and (regularization loss)\n \"\"\"\n def __init__(self, sgloss, sampler, regloss, lamb=0.1):\n super().__init__()\n self.sgloss = sgloss\n self.sampler = sampler\n self.regloss = regloss\n self.lamb = lamb\n \n def forward(self, cls, hiddens, p1, p2):\n \"\"\"\n cls: [batch, hidden]\n hiddens: [batch, layers, hidden]\n \"\"\"\n if not isinstance(self.sgloss, (SGLossOpt3, SGLossOpt3Simplified)):\n hiddens = self.sampler(hiddens)\n \n return self.sgloss(cls, hiddens) + self.lamb * self.regloss(p1, p2)\n\n\nclass SelfGuidedContraModel(nn.Module):\n def __init__(self, model_name, total_loss, hidden):\n super().__init__()\n self.bertF = AutoModel.from_pretrained(model_name, output_hidden_states=True)\n self.bertT = AutoModel.from_pretrained(model_name)\n self.proj = nn.Sequential(\n nn.Linear(hidden, 4096),\n nn.GELU(),\n nn.Linear(4096, hidden),\n nn.GELU()\n )\n self.loss_fn = total_loss\n self._freeze_param()\n\n\n def _freeze_param(self):\n \"\"\"\n freeze the embedding layers\n \"\"\"\n for name, param in self.bertT.named_parameters():\n if 'embeddings' in name:\n param.requires_grad_(False)\n \n for name, param in self.bertF.named_parameters():\n param.requires_grad_(False)\n\n for name, param in self.bertT.named_parameters():\n print(f'bertT.{name}', param.requires_grad)\n \n for name, param in self.bertF.named_parameters():\n print(f'bertF.{name}', param.requires_grad)\n\n def forward(self, input_ids, attention_mask, token_type_ids=None, labels=None, inputs_embeds=None):\n \n #[batch_size, hidden_dim]\n pooler_output = self.bertT(\n input_ids=input_ids,\n attention_mask=attention_mask,\n token_type_ids=token_type_ids\n ).last_hidden_state[:,0,:]\n pooler_output = self.proj(pooler_output)\n\n #tuple of [batch, seqlen, hidden]\n hiddens = self.bertF(\n input_ids=input_ids,\n attention_mask=attention_mask,\n token_type_ids=token_type_ids\n ).hidden_states\n\n #apply mean pooling on seqlen dimension [layer, batch, seqlen, hidden] -> [batch, layer, hidden]\n hiddens = torch.stack(hiddens, dim=0).mean(-2).transpose(0, 1)\n hiddens = self.proj(hiddens)\n\n\n if isinstance(self.loss_fn.regloss, RegLoss):\n return self.loss_fn(\n pooler_output,\n hiddens,\n self.bertF.encoder.parameters(),\n self.bertT.encoder.parameters()\n )\n\n elif isinstance(self.loss_fn.regloss, RegHiddenLoss):\n #It is not stated in this paper whether regularization term is relative to model parameter or hidden state\n #I guess it is relative to model parameter, So I didn't implement this method\n raise NotImplementedError()\n\n\n\n\n\n"
] | [
[
"torch.mean",
"torch.nn.GELU",
"torch.ones",
"torch.nn.functional.cross_entropy",
"torch.eye",
"torch.nn.Linear",
"torch.log",
"torch.nn.functional.cosine_similarity",
"torch.arange",
"torch.stack"
]
] |
pyroll-project/pyroll-core | [
"f59094d58c2f7493ddc6345b3afc4700ca259681"
] | [
"tests/grooves/test_constricted_swedish_oval.py"
] | [
"from numpy import pi, isclose\n\nfrom pyroll.core import ConstrictedSwedishOvalGroove\n\n\ndef check(g):\n assert isclose(g.even_ground_width, 14.81966011 * 2)\n assert isclose(g.alpha1, 63.434949 / 180 * pi)\n assert isclose(g.alpha2, 100.304846 / 180 * pi)\n assert isclose(g.alpha4, 36.869898 / 180 * pi)\n assert isclose(g.z1, 42.09016994)\n\n\ndef test_constricted_swedish_oval_usable_width_ground_width():\n g = ConstrictedSwedishOvalGroove(depth=18, r1=5, r2=10, r4=5, usable_width=39 * 2, ground_width=30 * 2, indent=3)\n check(g)\n\n\ndef test_constricted_swedish_oval_usable_width_flank_angle():\n g = ConstrictedSwedishOvalGroove(depth=18, r1=5, r2=10, r4=5, usable_width=39 * 2, flank_angle=63.434949 / 180 * pi,\n indent=3)\n check(g)\n\n\ndef test_constricted_swedish_oval_ground_width_flank_angle():\n g = ConstrictedSwedishOvalGroove(depth=18, r1=5, r2=10, r4=5, ground_width=30 * 2, flank_angle=63.434949 / 180 * pi,\n indent=3)\n check(g)\n"
] | [
[
"numpy.isclose"
]
] |
Coslate/Machine_Learning | [
"fd1e51cfdb02e1249819aa7d54a18b91fcd4225e"
] | [
"HW7/python/t_SNE/hw7.py"
] | [
"#! /usr/bin/env python3\n'''\n Author : BCC\n Date : 2022/05/02\n'''\n\nimport argparse\nimport math\nimport sys\nimport re\nimport os\nimport glob\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport numba as nb\nimport pylab\nimport io\nfrom scipy.spatial import distance\nfrom PIL import Image\nfrom matplotlib.pyplot import MultipleLocator #for setting of scale of separating along with x-axis & y-axis.\nfrom matplotlib.colors import ListedColormap\n\n#########################\n# Class-Definition #\n#########################\n\nclass color:\n PURPLE = '\\033[1;35;48m'\n CYAN = '\\033[1;36;48m'\n BOLD = '\\033[1;37;48m'\n BLUE = '\\033[1;34;48m'\n GREEN = '\\033[1;32;48m'\n YELLOW = '\\033[1;33;48m'\n RED = '\\033[1;31;48m'\n BLACK = '\\033[1;30;48m'\n UNDERLINE = '\\033[4;37;48m'\n END = '\\033[1;37;0m'\n\n#########################\n# Main-Routine #\n#########################\ndef main():\n #Process the argument\n print(f\"> ArgumentParser...\")\n (input_img_file, input_label_file, mode, perplexity, directory, early_termin, early_termin_epsilon, is_debug) = ArgumentParser()\n\n print(f\"> Load Training Data...\")\n X = np.loadtxt(input_img_file)\n labels = np.loadtxt(input_label_file)\n\n print(f\"> Perform t-SNE/s-SNE...\")\n Y, proc_img, proc_img_fixed, P, Q_fin, C_optimized = PerformSNE(X, labels, 2, 50, mode, perplexity, early_termin, early_termin_epsilon)\n\n print(f\"> Show Result...\")\n OutputGIF(proc_img, proc_img_fixed, directory, mode, perplexity)\n OutputError(C_optimized, directory, mode, perplexity)\n DisplaySimilarity(P, labels, mode, perplexity, directory, 1)\n DisplaySimilarity(Q_fin, labels, mode, perplexity, directory, 0)\n\n if(is_debug):\n pass\n #print(f\"im_data1.type = {img_data1.shape}\")\n #print(f\"im_data2.type = {img_data2.shape}\")\n #img1 = Image.fromarray(img_data1)\n #img2 = Image.fromarray(img_data2)\n #img1.save(f'{directory}/test_img1.png')\n #img2.save(f'{directory}/test_img2.png')\n #fig, ax = plt.subplots(1,2)\n #ax[0].imshow(img1)\n #ax[1].imshow(img2)\n #plt.show()\n# display(img1)\n# display(img2)\n\n#########################\n# Sub-Routine #\n#########################\ndef ArgumentParser():\n input_img_file = None\n input_label_file = None\n mode = 1\n perplexity = 20.0\n directory = \"./output\"\n early_termin = 0\n early_termin_epsilon= 0.000001\n is_debug = 0\n\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--input_img_file\", \"-img\", help=\"The file name of the input image.\")\n parser.add_argument(\"--input_label_file\", \"-ilb\", help=\"The file name of the input label.\")\n parser.add_argument(\"--mode\", \"-mode\", help=\"Set 1 to perform t-SNE algorithm. Set 0 to perform Symmetric-SNE algorithm. Default is 1\")\n parser.add_argument(\"--perplexity\", \"-perp\", help=\"The perplexity used in SNE algorithm. Default is 20.0\")\n parser.add_argument(\"--directory\", \"-dir\", help=\"The output directory of the result. Default is './output'\")\n parser.add_argument(\"--early_termin\", \"-et\", help=\"Set 0 to wait 1000 iteration fo t-SNE/Symmetric-SNE algoruthm. Set 1 to early terminate when error is smaller than 'eraly_termin_epsilon'. Default is 0.\")\n parser.add_argument(\"--early_termin_epsilon\", \"-et_eps\", help=\"The early terminate error that can be tolerated. Default is 1e-6.\")\n parser.add_argument(\"--is_debug\", \"-isd\", help=\"1 for debug mode; 0 for normal mode.\")\n\n args = parser.parse_args()\n\n if(args.input_img_file):\n input_img_file = args.input_img_file\n if(args.input_label_file):\n input_label_file = args.input_label_file\n if(args.mode):\n mode = int(args.mode)\n if(args.perplexity):\n perplexity = float(args.perplexity)\n if(args.directory):\n directory = args.directory\n if(args.early_termin):\n early_termin = int(args.early_termin)\n if(args.early_termin_epsilon):\n early_termin_epsilon = float(args.early_termin_epsilon)\n if(args.is_debug):\n is_debug = int(args.is_debug)\n\n if(input_img_file == None):\n print(f\"Error: You should set '--input_img_file' or '-img' for the file name of the input image.\")\n sys.exit()\n\n if(input_label_file == None):\n print(f\"Error: You should set '--input_label_file' or '-ilb' for the file name of the input label.\")\n sys.exit()\n\n if(is_debug):\n print(f\"input_img_file = {input_img_file}\")\n print(f\"input_label_file = {input_label_file}\")\n print(f\"mode = {mode}\")\n print(f\"perplexity = {perplexity}\")\n print(f\"directory = {directory}\")\n print(f\"early_termin = {early_termin}\")\n print(f\"early_termin_epsilon = {early_termin_epsilon}\")\n print(f\"is_debug = {is_debug}\")\n\n return (input_img_file, input_label_file, mode, perplexity, directory, early_termin, early_termin_epsilon, is_debug)\n\ndef Hbeta(D=np.array([]), beta=1.0):\n \"\"\"\n Compute the perplexity and the P-row for a specific value of the\n precision of a Gaussian distribution.\n \"\"\"\n\n # Compute P-row and corresponding perplexity\n P = np.exp(-D.copy() * beta)\n sumP = sum(P)\n H = np.log(sumP) + beta * np.sum(D * P) / sumP\n P = P / sumP\n return H, P\n\n\ndef x2p(X=np.array([]), tol=1e-5, perplexity=30.0):\n \"\"\"\n Performs a binary search to get P-values in such a way that each\n conditional Gaussian has the same perplexity.\n \"\"\"\n\n # Initialize some variables\n print(\"Computing pairwise distances...\")\n (n, d) = X.shape\n sum_X = np.sum(np.square(X), 1)\n D = np.add(np.add(-2 * np.dot(X, X.T), sum_X).T, sum_X)\n P = np.zeros((n, n))\n beta = np.ones((n, 1))\n logU = np.log(perplexity)\n\n # Loop over all datapoints\n for i in range(n):\n\n # Print progress\n if i % 500 == 0:\n print(\"Computing P-values for point %d of %d...\" % (i, n))\n\n # Compute the Gaussian kernel and entropy for the current precision\n betamin = -np.inf\n betamax = np.inf\n Di = D[i, np.concatenate((np.r_[0:i], np.r_[i+1:n]))]\n (H, thisP) = Hbeta(Di, beta[i])\n\n # Evaluate whether the perplexity is within tolerance\n Hdiff = H - logU\n tries = 0\n while np.abs(Hdiff) > tol and tries < 50:\n\n # If not, increase or decrease precision\n if Hdiff > 0:\n betamin = beta[i].copy()\n if betamax == np.inf or betamax == -np.inf:\n beta[i] = beta[i] * 2.\n else:\n beta[i] = (beta[i] + betamax) / 2.\n else:\n betamax = beta[i].copy()\n if betamin == np.inf or betamin == -np.inf:\n beta[i] = beta[i] / 2.\n else:\n beta[i] = (beta[i] + betamin) / 2.\n\n # Recompute the values\n (H, thisP) = Hbeta(Di, beta[i])\n Hdiff = H - logU\n tries += 1\n\n # Set the final row of P\n P[i, np.concatenate((np.r_[0:i], np.r_[i+1:n]))] = thisP\n\n # Return final P-matrix\n print(\"Mean value of sigma: %f\" % np.mean(np.sqrt(1 / beta)))\n return P\n\n\ndef pca(X=np.array([]), no_dims=50):\n \"\"\"\n Runs PCA on the NxD array X in order to reduce its dimensionality to\n no_dims dimensions.\n \"\"\"\n\n print(\"Preprocessing the data using PCA...\")\n (n, d) = X.shape\n X = X - np.tile(np.mean(X, 0), (n, 1))\n (l, M) = np.linalg.eig(np.dot(X.T, X))\n Y = np.dot(X, M[:, 0:no_dims])\n return Y\n\n\ndef PerformSNE(X=np.array([]), labels=np.array([]), no_dims=2, initial_dims=50, mode=1, perplexity=30.0, early_termin=0, early_termin_epsilon=0.000001):\n \"\"\"\n Runs t-SNE/s-SNE on the dataset in the NxD array X to reduce its\n dimensionality to no_dims dimensions. The syntaxis of the function is\n `Y = tsne.tsne(X, no_dims, perplexity), where X is an NxD NumPy array.\n \"\"\"\n\n # Check inputs\n if isinstance(no_dims, float):\n print(\"Error: array X should have type float.\")\n return -1\n if round(no_dims) != no_dims:\n print(\"Error: number of dimensions should be an integer.\")\n return -1\n\n # Initialize variables\n X = pca(X, initial_dims).real\n (n, d) = X.shape\n max_iter = 1000\n initial_momentum = 0.5\n final_momentum = 0.8\n eta = 500\n min_gain = 0.01\n Y = np.random.randn(n, no_dims)\n dY = np.zeros((n, no_dims))\n iY = np.zeros((n, no_dims))\n gains = np.ones((n, no_dims))\n\n # For early terminating\n C_prev = 0.\n C_optimized = 0.\n\n # For displaying\n Q_fin = np.zeros((n, n), dtype=np.float64)\n\n # GIF of the procedure\n proc_img = []\n proc_img_fixed = []\n\n # Compute P-values\n P = x2p(X, 1e-5, perplexity)\n P = P + np.transpose(P)\n P = P / np.sum(P)\n P = P * 4.\t\t\t\t\t\t\t\t\t# early exaggeration\n P = np.maximum(P, 1e-12)\n\n # Run iterations\n for iter in range(max_iter):\n\n # Compute pairwise affinities\n sum_Y = np.sum(np.square(Y), 1)\n num = -2. * np.dot(Y, Y.T)\n if(mode == 1):\n #t-SNE\n num = 1. / (1. + np.add(np.add(num, sum_Y).T, sum_Y))\n else:\n #s-SNE\n num = np.exp(-1. * np.add(np.add(num, sum_Y).T, sum_Y))\n\n num[range(n), range(n)] = 0.\n Q = num / np.sum(num)\n Q = np.maximum(Q, 1e-12)\n\n # Compute gradient\n PQ = P - Q\n if(mode == 1):\n #t-SNE\n for i in range(n):\n dY[i, :] = np.sum(np.tile(PQ[:, i] * num[:, i], (no_dims, 1)).T * (Y[i, :] - Y), 0)\n else:\n #s-SNE\n for i in range(n):\n dY[i, :] = np.sum(np.tile(PQ[:, i], (no_dims, 1)).T * (Y[i, :] - Y), 0)\n\n # Perform the update\n if iter < 20:\n momentum = initial_momentum\n else:\n momentum = final_momentum\n gains = (gains + 0.2) * ((dY > 0.) != (iY > 0.)) + \\\n (gains * 0.8) * ((dY > 0.) == (iY > 0.))\n gains[gains < min_gain] = min_gain\n iY = momentum * iY - eta * (gains * dY)\n Y = Y + iY\n Y = Y - np.tile(np.mean(Y, 0), (n, 1))\n\n # Recrd the procedure\n proc_img.append(TransformToImg(Y, labels, mode, perplexity, 0, None))\n if(mode == 1):\n proc_img_fixed.append(TransformToImg(Y, labels, mode, perplexity, 1, [-150, 150]))\n else:\n proc_img_fixed.append(TransformToImg(Y, labels, mode, perplexity, 1, [-10, 10]))\n\n # Compute current value of cost function\n if (iter + 1) % 10 == 0:\n C = np.sum(P * np.log(P / Q))\n C_optimized = C\n print(\"Iteration %d: error is %f\" % (iter + 1, C))\n\n if(early_termin == 1):\n if(abs(C - C_prev) < early_termin_epsilon):\n P = P / 4.\n Q_fin = Q.copy()\n break\n\n C_prev = C\n\n # Stop lying about P-values\n if iter == 100:\n P = P / 4.\n\n # For displaying\n Q_fin = Q.copy()\n\n # Return solution\n return Y, proc_img, proc_img_fixed, P, Q_fin, C_optimized\n\ndef TransformToImg(Y, labels, mode, perplexity, fixed_range, range_to_plot):\n plt.clf()\n\n if(fixed_range == 1):\n plt.xlim(range_to_plot)\n plt.ylim(range_to_plot)\n\n plt.scatter(Y[:, 0], Y[:, 1], 20, labels)\n if(mode == 1):\n title_str = f\"t-SNE with perplexity = {perplexity}\"\n else:\n title_str = f\"Symmetric-SNE with perplexity = {perplexity}\"\n\n plt.title(f'{title_str}')\n plt.tight_layout()\n\n img_buf = io.BytesIO()\n plt.savefig(img_buf, format='png')\n img_buf.seek(0)\n im = Image.open(img_buf)\n return im\n\ndef OutputError(C_optimized, directory, mode, perplexity):\n if(mode == 1):\n title_str = f\"t-SNE_perplexity_{perplexity}\"\n else:\n title_str = f\"Symmetric-SNE_perplexity_{perplexity}\"\n\n file_name = title_str+\"_final_error_\"+str(C_optimized)+\".txt\"\n\n if not os.path.exists(directory):\n os.makedirs(directory)\n else:\n #clean all gif and png files\n for zippath in glob.iglob(os.path.join(directory, file_name)):\n os.remove(zippath)\n\n output_file_name = directory+\"/\"+file_name\n if(mode == 1):\n lines = [f\"t-SNE, perplexity = {perplexity}, \", f\"final error of objective function C = {C_optimized}\"]\n else:\n lines = [f\"Symmetric-SNE, perplexity = {perplexity}, \", f\"final error of objective function C = {C_optimized}\"]\n\n with open(output_file_name, 'w') as f:\n for line in lines:\n f.write(line)\n f.write('\\n')\n\ndef OutputGIF(proc_img, proc_img_fixed, directory, mode, perplexity):\n if(mode == 1):\n title_str = f\"t-SNE_perplexity_{perplexity}\"\n fixed_range = \"-150_to_150\"\n else:\n title_str = f\"Symmetric-SNE_perplexity_{perplexity}\"\n fixed_range = \"-10_to_10\"\n\n if not os.path.exists(directory):\n os.makedirs(directory)\n else:\n #clean all gif and png files\n for zippath in glob.iglob(os.path.join(directory, title_str+'.gif')):\n os.remove(zippath)\n for zippath in glob.iglob(os.path.join(directory, title_str+'_result.png')):\n os.remove(zippath)\n\n #Output GIF files & resulted image file\n out_gif_file_name = directory+\"/\"+title_str+\".gif\"\n proc_img[0].save(out_gif_file_name, save_all=True, append_images=proc_img[1:], optimize=False, duration=100, loop=0)\n proc_img[-1].save(f\"{directory}/{title_str}_result.png\")\n proc_img_fixed[-1].save(f\"{directory}/{title_str}_fixed_range_{fixed_range}_result.png\")\n\ndef DisplaySimilarity(prob_matrix, labels, mode, perplexity, directory, h_dim):\n if(mode == 1):\n if(h_dim == 1):\n title_str = f\"t-SNE, perplexity = {perplexity}, High-D Similarity\"\n else:\n title_str = f\"t-SNE, perplexity = {perplexity}, Low-D Similarity\"\n else:\n if(h_dim == 1):\n title_str = f\"Symmetric-SNE, perplexity = {perplexity}, High-D Similarity\"\n else:\n title_str = f\"Symmetric-SNE, perplexity = {perplexity}, Low-D Similarity\"\n\n #Re-arranging the P and Q matrix according to labels\n index = np.argsort(labels)\n scaled_p = np.log(prob_matrix)\n re_arranged_p = scaled_p[index][:, index]\n\n #Plot the similarity matrix according to Pij and Qij\n plt.clf()\n plt.figure(1)\n\n #img = plt.imshow(re_arranged_p, cmap='RdYlBu_r', vmin=re_arranged_p.min(), vmax=re_arranged_p.max())\n img = plt.imshow(re_arranged_p, cmap='RdYlBu_r')\n plt.colorbar(img)\n plt.title(f\"{title_str}\")\n\n #Output the image of the similarity matrix of Pij and Qij\n img_buf = io.BytesIO()\n plt.savefig(img_buf, format='png')\n img_buf.seek(0)\n im = Image.open(img_buf)\n\n if(mode==1):\n if(h_dim == 1):\n file_str = \"t-SNE_perplexity_\"+str(perplexity)+\"_high_D_similarity.png\"\n else:\n file_str = \"t-SNE_perplexity_\"+str(perplexity)+\"_low_D_similarity.png\"\n out_img_file_name = directory + \"/\"+file_str\n else:\n if(h_dim == 1):\n file_str = \"Symmetric-SNE_perplexity_\"+str(perplexity)+\"_high_D_similarity.png\"\n else:\n file_str = \"Symmetric-SNE_perplexity_\"+str(perplexity)+\"_low_D_similarity.png\"\n out_img_file_name = directory + \"/\"+file_str\n\n if not os.path.exists(directory):\n os.makedirs(directory)\n else:\n #clean all gif and png files\n for zippath in glob.iglob(os.path.join(directory, file_str+'.png')):\n os.remove(zippath)\n\n im.save(out_img_file_name)\n\n#---------------Execution---------------#\nif __name__ == '__main__':\n main()\n"
] | [
[
"numpy.dot",
"matplotlib.pyplot.imshow",
"numpy.sqrt",
"numpy.concatenate",
"numpy.random.randn",
"numpy.mean",
"numpy.square",
"matplotlib.pyplot.tight_layout",
"numpy.zeros",
"matplotlib.pyplot.figure",
"numpy.log",
"matplotlib.pyplot.title",
"matplotlib.pyplot.ylim",
"matplotlib.pyplot.savefig",
"numpy.transpose",
"numpy.argsort",
"numpy.array",
"numpy.sum",
"numpy.maximum",
"numpy.abs",
"matplotlib.pyplot.scatter",
"numpy.tile",
"numpy.ones",
"matplotlib.pyplot.colorbar",
"matplotlib.pyplot.xlim",
"matplotlib.pyplot.clf",
"numpy.add",
"numpy.loadtxt"
]
] |
aachong/fairseq | [
"1d720f20cf1f37255c0e2b1dd449905f3fec9778"
] | [
"fairseq/models/transformer.py"
] | [
"# Copyright (c) Facebook, Inc. and its affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nimport math\nfrom typing import Any, Dict, List, Optional, Tuple\n\nimport torch\nimport torch.nn as nn\nfrom fairseq import utils\nfrom fairseq.models import (\n FairseqEncoder,\n FairseqEncoderDecoderModel,\n FairseqIncrementalDecoder,\n register_model,\n register_model_architecture,\n)\nfrom fairseq.modules import (\n AdaptiveSoftmax,\n FairseqDropout,\n LayerDropModuleList,\n LayerNorm,\n PositionalEmbedding,\n SinusoidalPositionalEmbedding,\n TransformerDecoderLayer,\n TransformerEncoderLayer,\n)\nfrom fairseq.modules.checkpoint_activations import checkpoint_wrapper\nfrom fairseq.modules.quant_noise import quant_noise as apply_quant_noise_\nfrom torch import Tensor\n\n\nDEFAULT_MAX_SOURCE_POSITIONS = 1024\nDEFAULT_MAX_TARGET_POSITIONS = 1024\n\n\n@register_model(\"transformer\")\nclass TransformerModel(FairseqEncoderDecoderModel):\n \"\"\"\n Transformer model from `\"Attention Is All You Need\" (Vaswani, et al, 2017)\n <https://arxiv.org/abs/1706.03762>`_.\n Args:\n encoder (TransformerEncoder): the encoder\n decoder (TransformerDecoder): the decoder\n The Transformer model provides the following named architectures and\n command-line arguments:\n .. argparse::\n :ref: fairseq.models.transformer_parser\n :prog:\n \"\"\"\n\n @classmethod\n def hub_models(cls):\n # fmt: off\n\n def moses_subword(path):\n return {\n 'path': path,\n 'tokenizer': 'moses',\n 'bpe': 'subword_nmt',\n }\n\n def moses_fastbpe(path):\n return {\n 'path': path,\n 'tokenizer': 'moses',\n 'bpe': 'fastbpe',\n }\n\n def spm(path):\n return {\n 'path': path,\n 'bpe': 'sentencepiece',\n 'tokenizer': 'space',\n }\n\n return {\n 'transformer.wmt14.en-fr': moses_subword('https://dl.fbaipublicfiles.com/fairseq/models/wmt14.en-fr.joined-dict.transformer.tar.bz2'),\n 'transformer.wmt16.en-de': 'https://dl.fbaipublicfiles.com/fairseq/models/wmt16.en-de.joined-dict.transformer.tar.bz2',\n 'transformer.wmt18.en-de': moses_subword('https://dl.fbaipublicfiles.com/fairseq/models/wmt18.en-de.ensemble.tar.gz'),\n 'transformer.wmt19.en-de': moses_fastbpe('https://dl.fbaipublicfiles.com/fairseq/models/wmt19.en-de.joined-dict.ensemble.tar.gz'),\n 'transformer.wmt19.en-ru': moses_fastbpe('https://dl.fbaipublicfiles.com/fairseq/models/wmt19.en-ru.ensemble.tar.gz'),\n 'transformer.wmt19.de-en': moses_fastbpe('https://dl.fbaipublicfiles.com/fairseq/models/wmt19.de-en.joined-dict.ensemble.tar.gz'),\n 'transformer.wmt19.ru-en': moses_fastbpe('https://dl.fbaipublicfiles.com/fairseq/models/wmt19.ru-en.ensemble.tar.gz'),\n 'transformer.wmt19.en-de.single_model': moses_fastbpe('https://dl.fbaipublicfiles.com/fairseq/models/wmt19.en-de.joined-dict.single_model.tar.gz'),\n 'transformer.wmt19.en-ru.single_model': moses_fastbpe('https://dl.fbaipublicfiles.com/fairseq/models/wmt19.en-ru.single_model.tar.gz'),\n 'transformer.wmt19.de-en.single_model': moses_fastbpe('https://dl.fbaipublicfiles.com/fairseq/models/wmt19.de-en.joined-dict.single_model.tar.gz'),\n 'transformer.wmt19.ru-en.single_model': moses_fastbpe('https://dl.fbaipublicfiles.com/fairseq/models/wmt19.ru-en.single_model.tar.gz'),\n 'transformer.wmt20.en-ta': spm('https://dl.fbaipublicfiles.com/fairseq/models/wmt20.en-ta.single.tar.gz'),\n 'transformer.wmt20.en-iu.news': spm('https://dl.fbaipublicfiles.com/fairseq/models/wmt20.en-iu.news.single.tar.gz'),\n 'transformer.wmt20.en-iu.nh': spm('https://dl.fbaipublicfiles.com/fairseq/models/wmt20.en-iu.nh.single.tar.gz'),\n 'transformer.wmt20.ta-en': spm('https://dl.fbaipublicfiles.com/fairseq/models/wmt20.ta-en.single.tar.gz'),\n 'transformer.wmt20.iu-en.news': spm('https://dl.fbaipublicfiles.com/fairseq/models/wmt20.iu-en.news.single.tar.gz'),\n 'transformer.wmt20.iu-en.nh': spm('https://dl.fbaipublicfiles.com/fairseq/models/wmt20.iu-en.nh.single.tar.gz'),\n }\n # fmt: on\n\n def __init__(self, args, encoder, decoder):\n super().__init__(encoder, decoder)\n self.args = args\n self.supports_align_args = True\n\n def change_all_p(self,p):\n self.encoder.change_p(p)\n self.decoder.change_p(p)\n\n def print_all_p(self):\n print('encoder',self.encoder.dropout_module.p)\n print('decoder',self.decoder.dropout_module.p)\n\n @staticmethod\n def add_args(parser):\n \"\"\"Add model-specific arguments to the parser.\"\"\"\n # fmt: off\n parser.add_argument('--activation-fn',\n choices=utils.get_available_activation_fns(),\n help='activation function to use')\n parser.add_argument('--dropout', type=float, metavar='D',\n help='dropout probability')\n parser.add_argument('--attention-dropout', type=float, metavar='D',\n help='dropout probability for attention weights')\n parser.add_argument('--activation-dropout', '--relu-dropout', type=float, metavar='D',\n help='dropout probability after activation in FFN.')\n parser.add_argument('--encoder-embed-path', type=str, metavar='STR',\n help='path to pre-trained encoder embedding')\n parser.add_argument('--encoder-embed-dim', type=int, metavar='N',\n help='encoder embedding dimension')\n parser.add_argument('--encoder-ffn-embed-dim', type=int, metavar='N',\n help='encoder embedding dimension for FFN')\n parser.add_argument('--encoder-layers', type=int, metavar='N',\n help='num encoder layers')\n parser.add_argument('--encoder-attention-heads', type=int, metavar='N',\n help='num encoder attention heads')\n parser.add_argument('--encoder-normalize-before', action='store_true',\n help='apply layernorm before each encoder block')\n parser.add_argument('--encoder-learned-pos', action='store_true',\n help='use learned positional embeddings in the encoder')\n parser.add_argument('--decoder-embed-path', type=str, metavar='STR',\n help='path to pre-trained decoder embedding')\n parser.add_argument('--decoder-embed-dim', type=int, metavar='N',\n help='decoder embedding dimension')\n parser.add_argument('--decoder-ffn-embed-dim', type=int, metavar='N',\n help='decoder embedding dimension for FFN')\n parser.add_argument('--decoder-layers', type=int, metavar='N',\n help='num decoder layers')\n parser.add_argument('--decoder-attention-heads', type=int, metavar='N',\n help='num decoder attention heads')\n parser.add_argument('--decoder-learned-pos', action='store_true',\n help='use learned positional embeddings in the decoder')\n parser.add_argument('--decoder-normalize-before', action='store_true',\n help='apply layernorm before each decoder block')\n parser.add_argument('--decoder-output-dim', type=int, metavar='N',\n help='decoder output dimension (extra linear layer '\n 'if different from decoder embed dim')\n parser.add_argument('--share-decoder-input-output-embed', action='store_true',\n help='share decoder input and output embeddings')\n parser.add_argument('--share-all-embeddings', action='store_true',\n help='share encoder, decoder and output embeddings'\n ' (requires shared dictionary and embed dim)')\n parser.add_argument('--no-token-positional-embeddings', default=False, action='store_true',\n help='if set, disables positional embeddings (outside self attention)')\n parser.add_argument('--adaptive-softmax-cutoff', metavar='EXPR',\n help='comma separated list of adaptive softmax cutoff points. '\n 'Must be used with adaptive_loss criterion'),\n parser.add_argument('--adaptive-softmax-dropout', type=float, metavar='D',\n help='sets adaptive softmax dropout for the tail projections')\n parser.add_argument('--layernorm-embedding', action='store_true',\n help='add layernorm to embedding')\n parser.add_argument('--no-scale-embedding', action='store_true',\n help='if True, dont scale embeddings')\n parser.add_argument('--checkpoint-activations', action='store_true',\n help='checkpoint activations at each layer, which saves GPU '\n 'memory usage at the cost of some additional compute')\n # args for \"Cross+Self-Attention for Transformer Models\" (Peitz et al., 2019)\n parser.add_argument('--no-cross-attention', default=False, action='store_true',\n help='do not perform cross-attention')\n parser.add_argument('--cross-self-attention', default=False, action='store_true',\n help='perform cross+self-attention')\n # args for \"Reducing Transformer Depth on Demand with Structured Dropout\" (Fan et al., 2019)\n parser.add_argument('--encoder-layerdrop', type=float, metavar='D', default=0,\n help='LayerDrop probability for encoder')\n parser.add_argument('--decoder-layerdrop', type=float, metavar='D', default=0,\n help='LayerDrop probability for decoder')\n parser.add_argument('--encoder-layers-to-keep', default=None,\n help='which layers to *keep* when pruning as a comma-separated list')\n parser.add_argument('--decoder-layers-to-keep', default=None,\n help='which layers to *keep* when pruning as a comma-separated list')\n # args for Training with Quantization Noise for Extreme Model Compression ({Fan*, Stock*} et al., 2020)\n parser.add_argument('--quant-noise-pq', type=float, metavar='D', default=0,\n help='iterative PQ quantization noise at training time')\n parser.add_argument('--quant-noise-pq-block-size', type=int, metavar='D', default=8,\n help='block size of quantization noise at training time')\n parser.add_argument('--quant-noise-scalar', type=float, metavar='D', default=0,\n help='scalar quantization noise and scalar quantization at training time')\n parser.add_argument('--need-drc-head', action='store_true',\n help='use drc_head_fused_layernorm in the encoder and decoder')\n parser.add_argument('--need-drc-residual', action='store_true',\n help='use drc_head_fused_layernorm in the encoder and decoder')\n # fmt: on\n\n @classmethod\n def build_model(cls, args, task):\n \"\"\"Build a new model instance.\"\"\"\n\n # make sure all arguments are present in older models\n base_architecture(args)\n\n if args.encoder_layers_to_keep:\n args.encoder_layers = len(args.encoder_layers_to_keep.split(\",\"))\n if args.decoder_layers_to_keep:\n args.decoder_layers = len(args.decoder_layers_to_keep.split(\",\"))\n\n if getattr(args, \"max_source_positions\", None) is None:\n args.max_source_positions = DEFAULT_MAX_SOURCE_POSITIONS\n if getattr(args, \"max_target_positions\", None) is None:\n args.max_target_positions = DEFAULT_MAX_TARGET_POSITIONS\n\n src_dict, tgt_dict = task.source_dictionary, task.target_dictionary\n\n if args.share_all_embeddings:\n if src_dict != tgt_dict:\n raise ValueError(\"--share-all-embeddings requires a joined dictionary\")\n if args.encoder_embed_dim != args.decoder_embed_dim:\n raise ValueError(\n \"--share-all-embeddings requires --encoder-embed-dim to match --decoder-embed-dim\"\n )\n if args.decoder_embed_path and (\n args.decoder_embed_path != args.encoder_embed_path\n ):\n raise ValueError(\n \"--share-all-embeddings not compatible with --decoder-embed-path\"\n )\n encoder_embed_tokens = cls.build_embedding(\n args, src_dict, args.encoder_embed_dim, args.encoder_embed_path\n )\n decoder_embed_tokens = encoder_embed_tokens\n args.share_decoder_input_output_embed = True\n else:\n encoder_embed_tokens = cls.build_embedding(\n args, src_dict, args.encoder_embed_dim, args.encoder_embed_path\n )\n decoder_embed_tokens = cls.build_embedding(\n args, tgt_dict, args.decoder_embed_dim, args.decoder_embed_path\n )\n\n encoder = cls.build_encoder(args, src_dict, encoder_embed_tokens)\n decoder = cls.build_decoder(args, tgt_dict, decoder_embed_tokens)\n return cls(args, encoder, decoder)\n\n @classmethod\n def build_embedding(cls, args, dictionary, embed_dim, path=None):\n num_embeddings = len(dictionary)\n padding_idx = dictionary.pad()\n\n emb = Embedding(num_embeddings, embed_dim, padding_idx)\n # if provided, load from preloaded dictionaries\n if path:\n embed_dict = utils.parse_embedding(path)\n utils.load_embedding(embed_dict, dictionary, emb)\n return emb\n\n @classmethod\n def build_encoder(cls, args, src_dict, embed_tokens):\n return TransformerEncoder(args, src_dict, embed_tokens)\n\n @classmethod\n def build_decoder(cls, args, tgt_dict, embed_tokens):\n return TransformerDecoder(\n args,\n tgt_dict,\n embed_tokens,\n no_encoder_attn=getattr(args, \"no_cross_attention\", False),\n )\n\n # TorchScript doesn't support optional arguments with variable length (**kwargs).\n # Current workaround is to add union of all arguments in child classes.\n def forward(\n self,\n src_tokens,\n src_lengths,\n prev_output_tokens,\n return_all_hiddens: bool = True,\n features_only: bool = False,\n alignment_layer: Optional[int] = None,\n alignment_heads: Optional[int] = None,\n token_embeddings = None,\n noised_inputs = None,\n ):\n \"\"\"\n Run the forward pass for an encoder-decoder model.\n Copied from the base class, but without ``**kwargs``,\n which are not supported by TorchScript.\n \"\"\"\n encoder_out = self.encoder(\n src_tokens, src_lengths=src_lengths, return_all_hiddens=return_all_hiddens,token_embeddings=token_embeddings\n )\n decoder_out = self.decoder(\n prev_output_tokens,\n encoder_out=encoder_out,\n features_only=features_only,\n alignment_layer=alignment_layer,\n alignment_heads=alignment_heads,\n src_lengths=src_lengths,\n return_all_hiddens=return_all_hiddens,\n noised_inputs = noised_inputs,\n )\n return decoder_out\n\n # Since get_normalized_probs is in the Fairseq Model which is not scriptable,\n # I rewrite the get_normalized_probs from Base Class to call the\n # helper function in the Base Class.\n @torch.jit.export\n def get_normalized_probs(\n self,\n net_output: Tuple[Tensor, Optional[Dict[str, List[Optional[Tensor]]]]],\n log_probs: bool,\n sample: Optional[Dict[str, Tensor]] = None,\n ):\n \"\"\"Get normalized probabilities (or log probs) from a net's output.\"\"\"\n return self.get_normalized_probs_scriptable(net_output, log_probs, sample)\n\n\nclass TransformerEncoder(FairseqEncoder):\n \"\"\"\n Transformer encoder consisting of *args.encoder_layers* layers. Each layer \n is a :class:`TransformerEncoderLayer`.\n Args:\n args (argparse.Namespace): parsed command-line arguments\n dictionary (~fairseq.data.Dictionary): encoding dictionary\n embed_tokens (torch.nn.Embedding): input embedding\n \"\"\"\n\n def __init__(self, args, dictionary, embed_tokens):\n super().__init__(dictionary)\n self.register_buffer(\"version\", torch.Tensor([3]))\n\n self.dropout_module = FairseqDropout(\n args.dropout, module_name=self.__class__.__name__\n )\n self.encoder_layerdrop = args.encoder_layerdrop\n\n embed_dim = embed_tokens.embedding_dim\n self.padding_idx = embed_tokens.padding_idx\n self.max_source_positions = args.max_source_positions\n\n self.embed_tokens = embed_tokens\n\n self.embed_scale = 1.0 if args.no_scale_embedding else math.sqrt(embed_dim)\n\n self.embed_positions = (\n PositionalEmbedding(\n args.max_source_positions,\n embed_dim,\n self.padding_idx,\n learned=args.encoder_learned_pos,\n )\n if not args.no_token_positional_embeddings\n else None \n )\n\n if getattr(args, \"layernorm_embedding\", False):\n self.layernorm_embedding = LayerNorm(embed_dim)\n else:\n self.layernorm_embedding = None\n\n if not args.adaptive_input and args.quant_noise_pq > 0:\n self.quant_noise = apply_quant_noise_(\n nn.Linear(embed_dim, embed_dim, bias=False),\n args.quant_noise_pq,\n args.quant_noise_pq_block_size,\n )\n else:\n self.quant_noise = None\n\n if self.encoder_layerdrop > 0.0:\n self.layers = LayerDropModuleList(p=self.encoder_layerdrop)\n else:\n self.layers = nn.ModuleList([])\n self.layers.extend(\n [self.build_encoder_layer(args) for i in range(args.encoder_layers)]\n )\n self.num_layers = len(self.layers)\n\n if args.encoder_normalize_before:\n self.layer_norm = LayerNorm(embed_dim)\n else:\n self.layer_norm = None\n\n ##drc\n def change_p(self,p):\n self.dropout_module.change_p(p)\n\n def build_encoder_layer(self, args):\n layer = TransformerEncoderLayer(args)\n if getattr(args, \"checkpoint_activations\", False):\n layer = checkpoint_wrapper(layer)\n return layer\n\n def forward_embedding(\n self, src_tokens, token_embedding: Optional[torch.Tensor] = None\n ):\n # embed tokens and positions\n if token_embedding is None:\n token_embedding = self.embed_tokens(src_tokens)\n x = embed = self.embed_scale * token_embedding\n if self.embed_positions is not None:\n x = embed + self.embed_positions(src_tokens)\n if self.layernorm_embedding is not None:\n x = self.layernorm_embedding(x)\n x = self.dropout_module(x)\n if self.quant_noise is not None:\n x = self.quant_noise(x)\n return x, embed\n\n def forward(\n self,\n src_tokens,\n src_lengths,\n return_all_hiddens: bool = False,\n token_embeddings: Optional[torch.Tensor] = None,\n ):\n \"\"\"\n Args:\n src_tokens (LongTensor): tokens in the source language of shape\n `(batch, src_len)`\n src_lengths (torch.LongTensor): lengths of each source sentence of\n shape `(batch)`\n return_all_hiddens (bool, optional): also return all of the\n intermediate hidden states (default: False).\n token_embeddings (torch.Tensor, optional): precomputed embeddings\n default `None` will recompute embeddings\n Returns:\n namedtuple:\n - **encoder_out** (Tensor): the last encoder layer's output of\n shape `(src_len, batch, embed_dim)`\n - **encoder_padding_mask** (ByteTensor): the positions of\n padding elements of shape `(batch, src_len)`\n - **encoder_embedding** (Tensor): the (scaled) embedding lookup\n of shape `(batch, src_len, embed_dim)`\n - **encoder_states** (List[Tensor]): all intermediate\n hidden states of shape `(src_len, batch, embed_dim)`.\n Only populated if *return_all_hiddens* is True.\n \"\"\"\n x, encoder_embedding = self.forward_embedding(src_tokens, token_embeddings)\n\n # B x T x C -> T x B x C\n x = x.transpose(0, 1)\n\n # compute padding mask\n encoder_padding_mask = src_tokens.eq(self.padding_idx)\n\n encoder_states = []\n\n # encoder layers\n for layer in self.layers:\n x = layer(x, encoder_padding_mask)\n if return_all_hiddens:\n assert encoder_states is not None\n encoder_states.append(x)\n\n if self.layer_norm is not None:\n x = self.layer_norm(x)\n\n # The Pytorch Mobile lite interpreter does not supports returning NamedTuple in\n # `foward` so we use a dictionary instead.\n # TorchScript does not support mixed values so the values are all lists.\n # The empty list is equivalent to None.\n return {\n \"encoder_out\": [x], # T x B x C\n \"encoder_padding_mask\": [encoder_padding_mask], # B x T\n \"encoder_embedding\": [encoder_embedding], # B x T x C\n \"encoder_states\": encoder_states, # List[T x B x C]\n \"src_tokens\": [],\n \"src_lengths\": [],\n }\n\n @torch.jit.export\n def reorder_encoder_out(self, encoder_out: Dict[str, List[Tensor]], new_order):\n \"\"\"\n Reorder encoder output according to *new_order*.\n Args:\n encoder_out: output from the ``forward()`` method\n new_order (LongTensor): desired order\n Returns:\n *encoder_out* rearranged according to *new_order*\n \"\"\"\n if len(encoder_out[\"encoder_out\"]) == 0:\n new_encoder_out = []\n else:\n new_encoder_out = [encoder_out[\"encoder_out\"][0].index_select(1, new_order)]\n if len(encoder_out[\"encoder_padding_mask\"]) == 0:\n new_encoder_padding_mask = []\n else:\n new_encoder_padding_mask = [\n encoder_out[\"encoder_padding_mask\"][0].index_select(0, new_order)\n ]\n if len(encoder_out[\"encoder_embedding\"]) == 0:\n new_encoder_embedding = []\n else:\n new_encoder_embedding = [\n encoder_out[\"encoder_embedding\"][0].index_select(0, new_order)\n ]\n\n if len(encoder_out[\"src_tokens\"]) == 0:\n src_tokens = []\n else:\n src_tokens = [(encoder_out[\"src_tokens\"][0]).index_select(0, new_order)]\n\n if len(encoder_out[\"src_lengths\"]) == 0:\n src_lengths = []\n else:\n src_lengths = [(encoder_out[\"src_lengths\"][0]).index_select(0, new_order)]\n\n encoder_states = encoder_out[\"encoder_states\"]\n if len(encoder_states) > 0:\n for idx, state in enumerate(encoder_states):\n encoder_states[idx] = state.index_select(1, new_order)\n\n return {\n \"encoder_out\": new_encoder_out, # T x B x C\n \"encoder_padding_mask\": new_encoder_padding_mask, # B x T\n \"encoder_embedding\": new_encoder_embedding, # B x T x C\n \"encoder_states\": encoder_states, # List[T x B x C]\n \"src_tokens\": src_tokens, # B x T\n \"src_lengths\": src_lengths, # B x 1\n }\n\n def max_positions(self):\n \"\"\"Maximum input length supported by the encoder.\"\"\"\n if self.embed_positions is None:\n return self.max_source_positions\n return min(self.max_source_positions, self.embed_positions.max_positions)\n\n def upgrade_state_dict_named(self, state_dict, name):\n \"\"\"Upgrade a (possibly old) state dict for new versions of fairseq.\"\"\"\n if isinstance(self.embed_positions, SinusoidalPositionalEmbedding):\n weights_key = \"{}.embed_positions.weights\".format(name)\n if weights_key in state_dict:\n print(\"deleting {0}\".format(weights_key))\n del state_dict[weights_key]\n state_dict[\n \"{}.embed_positions._float_tensor\".format(name)\n ] = torch.FloatTensor(1)\n for i in range(self.num_layers):\n # update layer norms\n self.layers[i].upgrade_state_dict_named(\n state_dict, \"{}.layers.{}\".format(name, i)\n )\n\n version_key = \"{}.version\".format(name)\n if utils.item(state_dict.get(version_key, torch.Tensor([1]))[0]) < 2:\n # earlier checkpoints did not normalize after the stack of layers\n self.layer_norm = None\n self.normalize = False\n state_dict[version_key] = torch.Tensor([1])\n return state_dict\n\n\nclass TransformerDecoder(FairseqIncrementalDecoder):\n \"\"\"\n Transformer decoder consisting of *args.decoder_layers* layers. Each layer\n is a :class:`TransformerDecoderLayer`.\n Args:\n args (argparse.Namespace): parsed command-line arguments\n dictionary (~fairseq.data.Dictionary): decoding dictionary\n embed_tokens (torch.nn.Embedding): output embedding\n no_encoder_attn (bool, optional): whether to attend to encoder outputs\n (default: False).\n \"\"\"\n\n def __init__(self, args, dictionary, embed_tokens, no_encoder_attn=False):\n self.args = args\n super().__init__(dictionary)\n self.register_buffer(\"version\", torch.Tensor([3]))\n self._future_mask = torch.empty(0)\n\n self.dropout_module = FairseqDropout(\n args.dropout, module_name=self.__class__.__name__\n )\n self.decoder_layerdrop = args.decoder_layerdrop\n self.share_input_output_embed = args.share_decoder_input_output_embed\n\n input_embed_dim = embed_tokens.embedding_dim\n embed_dim = args.decoder_embed_dim\n self.embed_dim = embed_dim\n self.output_embed_dim = args.decoder_output_dim\n\n self.padding_idx = embed_tokens.padding_idx\n self.max_target_positions = args.max_target_positions\n\n self.embed_tokens = embed_tokens\n\n self.embed_scale = 1.0 if args.no_scale_embedding else math.sqrt(embed_dim)\n\n if not args.adaptive_input and args.quant_noise_pq > 0:\n self.quant_noise = apply_quant_noise_(\n nn.Linear(embed_dim, embed_dim, bias=False),\n args.quant_noise_pq,\n args.quant_noise_pq_block_size,\n )\n else:\n self.quant_noise = None\n\n self.project_in_dim = (\n Linear(input_embed_dim, embed_dim, bias=False)\n if embed_dim != input_embed_dim\n else None\n )\n self.embed_positions = (\n PositionalEmbedding(\n self.max_target_positions,\n embed_dim,\n self.padding_idx,\n learned=args.decoder_learned_pos,\n )\n if not args.no_token_positional_embeddings\n else None\n )\n\n if getattr(args, \"layernorm_embedding\", False):\n self.layernorm_embedding = LayerNorm(embed_dim)\n else:\n self.layernorm_embedding = None\n\n self.cross_self_attention = getattr(args, \"cross_self_attention\", False)\n\n if self.decoder_layerdrop > 0.0:\n self.layers = LayerDropModuleList(p=self.decoder_layerdrop)\n else:\n self.layers = nn.ModuleList([])\n self.layers.extend(\n [\n self.build_decoder_layer(args, no_encoder_attn)\n for _ in range(args.decoder_layers)\n ]\n )\n self.num_layers = len(self.layers)\n\n if args.decoder_normalize_before and not getattr(\n args, \"no_decoder_final_norm\", False\n ):\n self.layer_norm = LayerNorm(embed_dim)\n else:\n self.layer_norm = None\n\n self.project_out_dim = (\n Linear(embed_dim, self.output_embed_dim, bias=False)\n if embed_dim != self.output_embed_dim and not args.tie_adaptive_weights\n else None\n )\n\n self.adaptive_softmax = None\n self.output_projection = None\n if args.adaptive_softmax_cutoff is not None:\n self.adaptive_softmax = AdaptiveSoftmax(\n len(dictionary),\n self.output_embed_dim,\n utils.eval_str_list(args.adaptive_softmax_cutoff, type=int),\n dropout=args.adaptive_softmax_dropout,\n adaptive_inputs=embed_tokens if args.tie_adaptive_weights else None,\n factor=args.adaptive_softmax_factor,\n tie_proj=args.tie_adaptive_proj,\n )\n elif self.share_input_output_embed:\n self.output_projection = nn.Linear(\n self.embed_tokens.weight.shape[1],\n self.embed_tokens.weight.shape[0],\n bias=False,\n )\n self.output_projection.weight = self.embed_tokens.weight\n else:\n self.output_projection = nn.Linear(\n self.output_embed_dim, len(dictionary), bias=False\n )\n nn.init.normal_(\n self.output_projection.weight, mean=0, std=self.output_embed_dim ** -0.5\n )\n\n def change_p(self,p):\n self.dropout_module.change_p(p)\n\n def build_decoder_layer(self, args, no_encoder_attn=False):\n layer = TransformerDecoderLayer(args, no_encoder_attn)\n if getattr(args, \"checkpoint_activations\", False):\n layer = checkpoint_wrapper(layer)\n return layer\n\n def forward(\n self,\n prev_output_tokens,\n encoder_out: Optional[Dict[str, List[Tensor]]] = None,\n incremental_state: Optional[Dict[str, Dict[str, Optional[Tensor]]]] = None,\n features_only: bool = False,\n full_context_alignment: bool = False,\n alignment_layer: Optional[int] = None,\n alignment_heads: Optional[int] = None,\n src_lengths: Optional[Any] = None,\n return_all_hiddens: bool = False,\n noised_inputs = None,\n ):\n \"\"\"\n Args:\n prev_output_tokens (LongTensor): previous decoder outputs of shape\n `(batch, tgt_len)`, for teacher forcing\n encoder_out (optional): output from the encoder, used for\n encoder-side attention\n incremental_state (dict): dictionary used for storing state during\n :ref:`Incremental decoding`\n features_only (bool, optional): only return features without\n applying output layer (default: False).\n full_context_alignment (bool, optional): don't apply\n auto-regressive mask to self-attention (default: False).\n Returns:\n tuple:\n - the decoder's output of shape `(batch, tgt_len, vocab)`\n - a dictionary with any model-specific outputs\n \"\"\"\n x, extra = self.extract_features(\n prev_output_tokens,\n encoder_out=encoder_out,\n incremental_state=incremental_state,\n full_context_alignment=full_context_alignment,\n alignment_layer=alignment_layer,\n alignment_heads=alignment_heads,\n noised_inputs = noised_inputs,\n )\n if not features_only:\n x = self.output_layer(x)\n return x, extra\n\n def extract_features(\n self,\n prev_output_tokens,\n encoder_out: Optional[Dict[str, List[Tensor]]],\n incremental_state: Optional[Dict[str, Dict[str, Optional[Tensor]]]] = None,\n full_context_alignment: bool = False,\n alignment_layer: Optional[int] = None,\n alignment_heads: Optional[int] = None,\n noised_inputs = None,\n ):\n return self.extract_features_scriptable(\n prev_output_tokens,\n encoder_out,\n incremental_state,\n full_context_alignment,\n alignment_layer,\n alignment_heads,\n noised_inputs,\n )\n\n \"\"\"\n A scriptable subclass of this class has an extract_features method and calls\n super().extract_features, but super() is not supported in torchscript. A copy of\n this function is made to be used in the subclass instead.\n \"\"\"\n\n def extract_features_scriptable(\n self,\n prev_output_tokens,\n encoder_out: Optional[Dict[str, List[Tensor]]],\n incremental_state: Optional[Dict[str, Dict[str, Optional[Tensor]]]] = None,\n full_context_alignment: bool = False,\n alignment_layer: Optional[int] = None,\n alignment_heads: Optional[int] = None,\n noised_inputs = None,\n ):\n \"\"\"\n Similar to *forward* but only return features.\n Includes several features from \"Jointly Learning to Align and\n Translate with Transformer Models\" (Garg et al., EMNLP 2019).\n Args:\n full_context_alignment (bool, optional): don't apply\n auto-regressive mask to self-attention (default: False).\n alignment_layer (int, optional): return mean alignment over\n heads at this layer (default: last layer).\n alignment_heads (int, optional): only average alignment over\n this many heads (default: all heads).\n Returns:\n tuple:\n - the decoder's features of shape `(batch, tgt_len, embed_dim)`\n - a dictionary with any model-specific outputs\n \"\"\"\n if alignment_layer is None:\n alignment_layer = self.num_layers - 1\n\n # embed positions\n positions = (\n self.embed_positions(\n prev_output_tokens, incremental_state=incremental_state\n )\n if self.embed_positions is not None\n else None\n )\n\n if incremental_state is not None:\n prev_output_tokens = prev_output_tokens[:, -1:]\n if positions is not None:\n positions = positions[:, -1:]\n\n # embed tokens and positions\n x = self.embed_scale * self.embed_tokens(prev_output_tokens)\n\n # print(x.shape,2)\n # assert False\n if noised_inputs is not None:\n x += noised_inputs\n\n if self.quant_noise is not None:\n x = self.quant_noise(x)\n\n if self.project_in_dim is not None:\n x = self.project_in_dim(x)\n\n if positions is not None:\n x += positions\n\n if self.layernorm_embedding is not None:\n x = self.layernorm_embedding(x)\n\n x = self.dropout_module(x)\n\n # B x T x C -> T x B x C\n x = x.transpose(0, 1)\n\n self_attn_padding_mask: Optional[Tensor] = None\n if self.cross_self_attention or prev_output_tokens.eq(self.padding_idx).any():\n self_attn_padding_mask = prev_output_tokens.eq(self.padding_idx)\n\n # decoder layers\n attn: Optional[Tensor] = None\n inner_states: List[Optional[Tensor]] = [x]\n for idx, layer in enumerate(self.layers):\n if incremental_state is None and not full_context_alignment:\n self_attn_mask = self.buffered_future_mask(x)\n else:\n self_attn_mask = None\n\n x, layer_attn, _ = layer(\n x,\n encoder_out[\"encoder_out\"][0]\n if (encoder_out is not None and len(encoder_out[\"encoder_out\"]) > 0)\n else None,\n encoder_out[\"encoder_padding_mask\"][0]\n if (\n encoder_out is not None\n and len(encoder_out[\"encoder_padding_mask\"]) > 0\n )\n else None,\n incremental_state,\n self_attn_mask=self_attn_mask,\n self_attn_padding_mask=self_attn_padding_mask,\n need_attn=bool((idx == alignment_layer)),\n need_head_weights=bool((idx == alignment_layer)),\n )\n inner_states.append(x)\n if layer_attn is not None and idx == alignment_layer:\n attn = layer_attn.float().to(x)\n\n if attn is not None:\n if alignment_heads is not None:\n attn = attn[:alignment_heads]\n\n # average probabilities over heads\n attn = attn.mean(dim=0)\n\n if self.layer_norm is not None:\n x = self.layer_norm(x)\n\n # T x B x C -> B x T x C\n x = x.transpose(0, 1)\n\n if self.project_out_dim is not None:\n x = self.project_out_dim(x)\n\n return x, {\"attn\": [attn], \"inner_states\": inner_states}\n\n def output_layer(self, features):\n \"\"\"Project features to the vocabulary size.\"\"\"\n if self.adaptive_softmax is None:\n # project back to size of vocabulary\n return self.output_projection(features)\n else:\n return features\n\n def max_positions(self):\n \"\"\"Maximum output length supported by the decoder.\"\"\"\n if self.embed_positions is None:\n return self.max_target_positions\n return min(self.max_target_positions, self.embed_positions.max_positions)\n\n def buffered_future_mask(self, tensor):\n dim = tensor.size(0)\n # self._future_mask.device != tensor.device is not working in TorchScript. This is a workaround.\n if (\n self._future_mask.size(0) == 0\n or (not self._future_mask.device == tensor.device)\n or self._future_mask.size(0) < dim\n ):\n self._future_mask = torch.triu(\n utils.fill_with_neg_inf(torch.zeros([dim, dim])), 1\n )\n self._future_mask = self._future_mask.to(tensor)\n return self._future_mask[:dim, :dim]\n\n def upgrade_state_dict_named(self, state_dict, name):\n \"\"\"Upgrade a (possibly old) state dict for new versions of fairseq.\"\"\"\n if isinstance(self.embed_positions, SinusoidalPositionalEmbedding):\n weights_key = \"{}.embed_positions.weights\".format(name)\n if weights_key in state_dict:\n del state_dict[weights_key]\n state_dict[\n \"{}.embed_positions._float_tensor\".format(name)\n ] = torch.FloatTensor(1)\n\n if f\"{name}.output_projection.weight\" not in state_dict:\n if self.share_input_output_embed:\n embed_out_key = f\"{name}.embed_tokens.weight\"\n else:\n embed_out_key = f\"{name}.embed_out\"\n if embed_out_key in state_dict:\n state_dict[f\"{name}.output_projection.weight\"] = state_dict[\n embed_out_key\n ]\n if not self.share_input_output_embed:\n del state_dict[embed_out_key]\n\n for i in range(self.num_layers):\n # update layer norms\n layer_norm_map = {\n \"0\": \"self_attn_layer_norm\",\n \"1\": \"encoder_attn_layer_norm\",\n \"2\": \"final_layer_norm\",\n }\n for old, new in layer_norm_map.items():\n for m in (\"weight\", \"bias\"):\n k = \"{}.layers.{}.layer_norms.{}.{}\".format(name, i, old, m)\n if k in state_dict:\n state_dict[\n \"{}.layers.{}.{}.{}\".format(name, i, new, m)\n ] = state_dict[k]\n del state_dict[k]\n\n version_key = \"{}.version\".format(name)\n if utils.item(state_dict.get(version_key, torch.Tensor([1]))[0]) <= 2:\n # earlier checkpoints did not normalize after the stack of layers\n self.layer_norm = None\n self.normalize = False\n state_dict[version_key] = torch.Tensor([1])\n\n return state_dict\n\n\ndef Embedding(num_embeddings, embedding_dim, padding_idx):\n m = nn.Embedding(num_embeddings, embedding_dim, padding_idx=padding_idx)\n nn.init.normal_(m.weight, mean=0, std=embedding_dim ** -0.5)\n nn.init.constant_(m.weight[padding_idx], 0)\n return m\n\n\ndef Linear(in_features, out_features, bias=True):\n m = nn.Linear(in_features, out_features, bias)\n nn.init.xavier_uniform_(m.weight)\n if bias:\n nn.init.constant_(m.bias, 0.0)\n return m\n\n\n@register_model_architecture(\"transformer\", \"transformer\")\ndef base_architecture(args):\n args.encoder_embed_path = getattr(args, \"encoder_embed_path\", None)\n args.encoder_embed_dim = getattr(args, \"encoder_embed_dim\", 512)\n args.encoder_ffn_embed_dim = getattr(args, \"encoder_ffn_embed_dim\", 2048)\n args.encoder_layers = getattr(args, \"encoder_layers\", 6)\n args.encoder_attention_heads = getattr(args, \"encoder_attention_heads\", 8)\n args.encoder_normalize_before = getattr(args, \"encoder_normalize_before\", False)\n args.encoder_learned_pos = getattr(args, \"encoder_learned_pos\", False)\n args.decoder_embed_path = getattr(args, \"decoder_embed_path\", None)\n args.decoder_embed_dim = getattr(args, \"decoder_embed_dim\", args.encoder_embed_dim)\n args.decoder_ffn_embed_dim = getattr(\n args, \"decoder_ffn_embed_dim\", args.encoder_ffn_embed_dim\n )\n args.decoder_layers = getattr(args, \"decoder_layers\", 6)\n args.decoder_attention_heads = getattr(args, \"decoder_attention_heads\", 8)\n args.decoder_normalize_before = getattr(args, \"decoder_normalize_before\", False)\n args.decoder_learned_pos = getattr(args, \"decoder_learned_pos\", False)\n args.attention_dropout = getattr(args, \"attention_dropout\", 0.0)\n args.activation_dropout = getattr(args, \"activation_dropout\", 0.0)\n args.activation_fn = getattr(args, \"activation_fn\", \"relu\")\n args.dropout = getattr(args, \"dropout\", 0.1)\n args.adaptive_softmax_cutoff = getattr(args, \"adaptive_softmax_cutoff\", None)\n args.adaptive_softmax_dropout = getattr(args, \"adaptive_softmax_dropout\", 0)\n args.share_decoder_input_output_embed = getattr(\n args, \"share_decoder_input_output_embed\", False\n )\n args.share_all_embeddings = getattr(args, \"share_all_embeddings\", False)\n args.no_token_positional_embeddings = getattr(\n args, \"no_token_positional_embeddings\", False\n )\n args.adaptive_input = getattr(args, \"adaptive_input\", False)\n args.no_cross_attention = getattr(args, \"no_cross_attention\", False)\n args.cross_self_attention = getattr(args, \"cross_self_attention\", False)\n\n args.decoder_output_dim = getattr(\n args, \"decoder_output_dim\", args.decoder_embed_dim\n )\n args.decoder_input_dim = getattr(args, \"decoder_input_dim\", args.decoder_embed_dim)\n\n args.no_scale_embedding = getattr(args, \"no_scale_embedding\", False)\n args.layernorm_embedding = getattr(args, \"layernorm_embedding\", False)\n args.tie_adaptive_weights = getattr(args, \"tie_adaptive_weights\", False)\n args.checkpoint_activations = getattr(args, \"checkpoint_activations\", False)\n\n args.encoder_layers_to_keep = getattr(args, \"encoder_layers_to_keep\", None)\n args.decoder_layers_to_keep = getattr(args, \"decoder_layers_to_keep\", None)\n args.encoder_layerdrop = getattr(args, \"encoder_layerdrop\", 0)\n args.decoder_layerdrop = getattr(args, \"decoder_layerdrop\", 0)\n args.quant_noise_pq = getattr(args, \"quant_noise_pq\", 0)\n args.quant_noise_pq_block_size = getattr(args, \"quant_noise_pq_block_size\", 8)\n args.quant_noise_scalar = getattr(args, \"quant_noise_scalar\", 0)\n\n\n@register_model_architecture(\"transformer\", \"transformer_iwslt_de_en\")\ndef transformer_iwslt_de_en(args):\n args.encoder_embed_dim = getattr(args, \"encoder_embed_dim\", 512)\n args.encoder_ffn_embed_dim = getattr(args, \"encoder_ffn_embed_dim\", 1024)\n args.encoder_attention_heads = getattr(args, \"encoder_attention_heads\", 4)\n args.encoder_layers = getattr(args, \"encoder_layers\", 6)\n args.decoder_embed_dim = getattr(args, \"decoder_embed_dim\", 512)\n args.decoder_ffn_embed_dim = getattr(args, \"decoder_ffn_embed_dim\", 1024)\n args.decoder_attention_heads = getattr(args, \"decoder_attention_heads\", 4)\n args.decoder_layers = getattr(args, \"decoder_layers\", 6)\n base_architecture(args)\n\n\n@register_model_architecture(\"transformer\", \"transformer_wmt_en_de\")\ndef transformer_wmt_en_de(args):\n base_architecture(args)\n\n\n# parameters used in the \"Attention Is All You Need\" paper (Vaswani et al., 2017)\n@register_model_architecture(\"transformer\", \"transformer_vaswani_wmt_en_de_big\")\ndef transformer_vaswani_wmt_en_de_big(args):\n args.encoder_embed_dim = getattr(args, \"encoder_embed_dim\", 1024)\n args.encoder_ffn_embed_dim = getattr(args, \"encoder_ffn_embed_dim\", 4096)\n args.encoder_attention_heads = getattr(args, \"encoder_attention_heads\", 16)\n args.encoder_normalize_before = getattr(args, \"encoder_normalize_before\", False)\n args.decoder_embed_dim = getattr(args, \"decoder_embed_dim\", 1024)\n args.decoder_ffn_embed_dim = getattr(args, \"decoder_ffn_embed_dim\", 4096)\n args.decoder_attention_heads = getattr(args, \"decoder_attention_heads\", 16)\n args.dropout = getattr(args, \"dropout\", 0.3)\n base_architecture(args)\n\n\n@register_model_architecture(\"transformer\", \"transformer_vaswani_wmt_en_fr_big\")\ndef transformer_vaswani_wmt_en_fr_big(args):\n args.dropout = getattr(args, \"dropout\", 0.1)\n transformer_vaswani_wmt_en_de_big(args)\n\n\n@register_model_architecture(\"transformer\", \"transformer_wmt_en_de_big\")\ndef transformer_wmt_en_de_big(args):\n args.attention_dropout = getattr(args, \"attention_dropout\", 0.1)\n transformer_vaswani_wmt_en_de_big(args)\n\n\n# default parameters used in tensor2tensor implementation\n@register_model_architecture(\"transformer\", \"transformer_wmt_en_de_big_t2t\")\ndef transformer_wmt_en_de_big_t2t(args):\n args.encoder_normalize_before = getattr(args, \"encoder_normalize_before\", True)\n args.decoder_normalize_before = getattr(args, \"decoder_normalize_before\", True)\n args.attention_dropout = getattr(args, \"attention_dropout\", 0.1)\n args.activation_dropout = getattr(args, \"activation_dropout\", 0.1)\n transformer_vaswani_wmt_en_de_big(args)"
] | [
[
"torch.empty",
"torch.Tensor",
"torch.zeros",
"torch.nn.init.constant_",
"torch.nn.ModuleList",
"torch.nn.Embedding",
"torch.nn.Linear",
"torch.nn.init.normal_",
"torch.FloatTensor",
"torch.nn.init.xavier_uniform_"
]
] |
industrial-optimization-group/offline_data_driven_moea | [
"4e454694f444ff44f86da24dc33672eb23561bfa"
] | [
"Other_files/All_analyses/plot_parallel_coord.py"
] | [
"import dash\nimport plotly.graph_objs as go\nfrom dash.dependencies import Input, Output\nimport dash_table\nimport dash_core_components as dcc\nimport dash_html_components as html\nimport pandas as pd\nimport numpy as np\n\n\ndef plot_parallel_coord_interactive(names, stdnames, means, std, col):\n names = [\"x1\", \"x2\", \"x3\"]\n stdnames = [name + \"_std\" for name in names]\n means = pd.DataFrame(np.random.rand(10, 3), columns=names)\n std = pd.DataFrame(np.random.rand(10, 3) * 0.1, columns=stdnames)\n\n df = means.join(std)\n app = dash.Dash(__name__)\n app.layout = html.Div(\n [\n dash_table.DataTable(\n id=\"datatable-interactivity\",\n columns=[\n {\"name\": i, \"id\": i, \"deletable\": True, \"selectable\": True}\n for i in df.columns\n ],\n data=df.to_dict(\"records\"),\n editable=True,\n filter_action=\"native\",\n sort_action=\"native\",\n sort_mode=\"multi\",\n column_selectable=\"single\",\n row_selectable=\"multi\",\n row_deletable=True,\n selected_columns=[],\n selected_rows=[],\n page_action=\"native\",\n page_current=0,\n page_size=10,\n ),\n html.Div(id=\"datatable-interactivity-container\"),\n ]\n )\n\n\n @app.callback(\n Output(\"datatable-interactivity\", \"style_data_conditional\"),\n [Input(\"datatable-interactivity\", \"selected_columns\")],\n )\n def update_styles(selected_columns):\n return [\n {\"if\": {\"column_id\": i}, \"background_color\": \"#D2F3FF\"}\n for i in selected_columns\n ]\n\n\n @app.callback(\n Output(\"datatable-interactivity-container\", \"children\"),\n [\n Input(\"datatable-interactivity\", \"derived_virtual_data\"),\n Input(\"datatable-interactivity\", \"derived_virtual_selected_rows\"),\n ],\n )\n def update_graphs(rows, derived_virtual_selected_rows):\n # When the table is first rendered, `derived_virtual_data` and\n # `derived_virtual_selected_rows` will be `None`. This is due to an\n # idiosyncracy in Dash (unsupplied properties are always None and Dash\n # calls the dependent callbacks when the component is first rendered).\n # So, if `rows` is `None`, then the component was just rendered\n # and its value will be the same as the component's dataframe.\n # Instead of setting `None` in here, you could also set\n # `derived_virtual_data=df.to_rows('dict')` when you initialize\n # the component.\n if derived_virtual_selected_rows is None:\n derived_virtual_selected_rows = []\n\n dff = df if rows is None else pd.DataFrame(rows)\n\n colors = [\n \"#7FDBFF\" if i in derived_virtual_selected_rows else \"#A9A9A9\"\n for i in range(len(dff))\n ]\n fig = go.Figure()\n for i in range(len(dff)):\n fig.add_scatter(\n x=[1, 2, 3],\n y=dff[names].loc[i].values,\n error_y=dict(\n type=\"data\", # value of error bar given in data coordinates\n array=dff[stdnames].loc[i].values,\n visible=True,\n ),\n line = dict(color=colors[i]),\n )\n\n return [dcc.Graph(id='plot', figure=fig)]\n\n\n if __name__ == \"__main__\":\n app.run_server(debug=True)\n"
] | [
[
"numpy.random.rand",
"pandas.DataFrame"
]
] |
SimonScapan/AuntElisa | [
"5ce6aa1feabdee0244fa270db6e796ec1b0dc857"
] | [
"backend/chatbot/model_1/training.py"
] | [
"import tensorflow as tf\nimport tensorlayer as tl\nimport numpy as np\nfrom tensorlayer.cost import cross_entropy_seq, cross_entropy_seq_with_mask\nfrom tqdm import tqdm\nfrom sklearn.utils import shuffle\nfrom tensorlayer.models.seq2seq import Seq2seq\nfrom tensorlayer.models.seq2seq_with_attention import Seq2seqLuongAttention\nimport os\nimport pickle\nfrom functions import split_dataset\n\ndef load_data():\n # read data control dictionaries\n with open('metadata.pkl', 'rb') as f:\n metadata = pickle.load(f)\n # read numpy arrays\n idx_q = np.load('idxm.npy')\n idx_a = np.load('idxr.npy')\n return metadata, idx_q, idx_a\n\nmetadata, idx_q, idx_a = load_data()\n(trainX, trainY), (testX, testY), (validX, validY) = split_dataset(idx_q, idx_a)\ntrainX = tl.prepro.remove_pad_sequences(trainX.tolist())\ntrainY = tl.prepro.remove_pad_sequences(trainY.tolist())\ntestX = tl.prepro.remove_pad_sequences(testX.tolist())\ntestY = tl.prepro.remove_pad_sequences(testY.tolist())\nvalidX = tl.prepro.remove_pad_sequences(validX.tolist())\nvalidY = tl.prepro.remove_pad_sequences(validY.tolist())\n\n# Parameters\nsrc_len = len(trainX)\ntgt_len = len(trainY)\n\n#Define Hyperparameters\nbatch_size = 32 #Choose batch size\nemb_dim = 1024 #Choss embedding size for word vectors\nn_step = src_len // batch_size\nsrc_vocab_size = len(metadata['index2word'])\nlast_stopped = 0 #0 if you are training the model from scratch\nnum_epochs = 50 - last_stopped #Number of training epoches\nn_layer = 3 #Choose number of Layers\nn_units=256 #Choose number of units\n\n#Add start and end tokens in sentences for training\nword2idx = metadata['wordindex'] # dict word 2 index\nidx2word = metadata['index2word'] # list index 2 word\n\nunk_id = idx2word.index('unk') # 1\npad_id = idx2word.index('_') # 0\n\nstart_id = src_vocab_size # 8002\nend_id = src_vocab_size + 1 # 8003\n\nword2idx.update({'start_id': start_id})\nword2idx.update({'end_id': end_id})\nidx2word = idx2word + ['start_id', 'end_id']\n\nsrc_vocab_size = tgt_vocab_size = src_vocab_size + 2\n\nvocabulary_size = src_vocab_size\n\n#Define length of sentences\ndecoder_seq_length = 20\n\n#Define model\nmodel_ = Seq2seq(\n decoder_seq_length = decoder_seq_length,\n cell_enc=tf.keras.layers.GRUCell,\n cell_dec=tf.keras.layers.GRUCell,\n n_layer=n_layer,\n n_units=n_units,\n embedding_layer=tl.layers.Embedding(vocabulary_size=vocabulary_size, embedding_size=emb_dim),\n )\n\n# Try to load model to continue training\ntry:\n load_weights = tl.files.load_npz(name=f'model_epoche{last_stopped}.npz')\n tl.files.assign_weights(load_weights, model_)\n print(f'Loaded Epoche {last_stopped} successfully!')\nexcept:\n pass\n\n#Define optimizer and learning rate\noptimizer = tf.optimizers.Adam(learning_rate=0.001)\nmodel_.train()\n\nfor epoch in range(num_epochs):\n model_.train()\n trainX, trainY = shuffle(trainX, trainY, random_state=0)\n total_loss, n_iter = 0, 0\n for X, Y in tqdm(tl.iterate.minibatches(inputs=trainX, targets=trainY, batch_size=batch_size, shuffle=False), \n total=n_step, desc='Epoch[{}/{}]'.format(epoch + 1, num_epochs), leave=False):\n\n #Recreate the padding and start and end tokens\n X = tl.prepro.pad_sequences(X)\n _target_seqs = tl.prepro.sequences_add_end_id(Y, end_id=end_id)\n _target_seqs = tl.prepro.pad_sequences(_target_seqs, maxlen=decoder_seq_length)\n _decode_seqs = tl.prepro.sequences_add_start_id(Y, start_id=start_id, remove_last=False)\n _decode_seqs = tl.prepro.pad_sequences(_decode_seqs, maxlen=decoder_seq_length)\n _target_mask = tl.prepro.sequences_get_mask(_target_seqs)\n\n with tf.GradientTape() as tape:\n #Compute outputs\n output = model_(inputs = [X, _decode_seqs])\n \n output = tf.reshape(output, [-1, vocabulary_size])\n #Compute loss and update model\n loss = cross_entropy_seq_with_mask(logits=output, target_seqs=_target_seqs, input_mask=_target_mask)\n\n grad = tape.gradient(loss, model_.all_weights)\n optimizer.apply_gradients(zip(grad, model_.all_weights))\n \n total_loss += loss\n n_iter += 1\n\n #Save the current model to load again if algorithem was interrupted\n tl.files.save_npz(model_.all_weights, name=f'model_epoche{epoch+1+last_stopped}.npz')\n os.remove(f'model_epoche{epoch+last_stopped}.npz', dir_fd=None) \n\n#Save the final model\nos.remove(f'model_epoche{epoch+last_stopped}.npz', dir_fd=None) \ntl.files.save_npz(model_.all_weights, name='model_final.npz')"
] | [
[
"sklearn.utils.shuffle",
"tensorflow.reshape",
"tensorflow.optimizers.Adam",
"numpy.load",
"tensorflow.GradientTape"
]
] |
jbenjoseph/GitGeo | [
"205e0e3b8e0cd38e69d15d2386ee0e9e79effdc0"
] | [
"test_gitgeo.py"
] | [
"\"\"\"Unit tests and integration tests for GitGeo.\"\"\"\n\n# pylint: disable=no-self-use, too-many-locals\n\nimport csv\nimport glob\nimport os\nimport textwrap\n\nimport pandas as pd\nimport pytest\n\nfrom custom_csv import create_csv, add_committer_to_csv\nfrom geolocation import get_country_from_location\nfrom github import (\n get_contributors,\n get_contributor_location,\n get_github_tokens,\n read_in_github_token_list,\n)\nfrom main import scan_single_package, scan_single_repo\nfrom mapping import (\n get_dataframe_from_csv,\n get_dataframe_from_repo,\n add_contributor_count_to_json,\n make_map,\n)\nfrom multi_repo_scan import scan_multiple_repos\nfrom printers import print_by_contributor, print_by_country\nfrom pypi import get_pypi_data, extract_github_owner_and_repo\n\n\nclass TestPypiFunctionality: # pragma: no cover\n \"\"\"Unit tests related to PyPI functionality.\"\"\"\n\n def test_get_github_url_owner_and_repo(self):\n \"\"\"Unit tests for get_github_URL_owner_and_repo().\"\"\"\n # tests for packages with standard location of GitHub link on PyPI page\n requests_pypi_data = get_pypi_data(\"requests\")\n assert requests_pypi_data[\"github_owner_and_repo\"] == \"psf/requests\"\n networkml_pypi_data = get_pypi_data(\"networkml\")\n assert networkml_pypi_data[\"github_owner_and_repo\"] == \"IQTLabs/NetworkML\"\n pandas_pypi_data = get_pypi_data(\"pandas\")\n assert pandas_pypi_data[\"github_owner_and_repo\"] == \"pandas-dev/pandas\"\n awscli_pypi_data = get_pypi_data(\"awscli\")\n assert awscli_pypi_data[\"github_owner_and_repo\"] == \"aws/aws-cli\"\n protobuf_pypi_data = get_pypi_data(\"protobuf\")\n assert protobuf_pypi_data[\"github_owner_and_repo\"] == \"protocolbuffers/protobuf\"\n pillow_pypi_data = get_pypi_data(\"pillow\")\n assert pillow_pypi_data[\"github_owner_and_repo\"] == \"python-pillow/Pillow\"\n tornado_pypi_data = get_pypi_data(\"tornado\")\n assert tornado_pypi_data[\"github_owner_and_repo\"] == \"tornadoweb/tornado\"\n typingextensions_pypi_data = get_pypi_data(\"typing-extensions\")\n assert typingextensions_pypi_data[\"github_owner_and_repo\"] == \"python/typing\"\n tensorflow_pypi_data = get_pypi_data(\"tensorflow\")\n assert tensorflow_pypi_data[\"github_owner_and_repo\"] == \"tensorflow/tensorflow\"\n\n # tests for packages with no GitHub link on PyPI page\n reportlab_pypi_data = get_pypi_data(\"reportlab\")\n assert reportlab_pypi_data[\"github_owner_and_repo\"] == \"\"\n bfengine_pypi_data = get_pypi_data(\"bfengine\")\n assert bfengine_pypi_data[\"github_owner_and_repo\"] == \"\"\n docutils_pypi_data = get_pypi_data(\"docutils\")\n assert docutils_pypi_data[\"github_owner_and_repo\"] == \"\"\n\n # test for package names that are not on PyPI\n with pytest.raises(Exception):\n get_pypi_data(\"googlemooglegoogle\")\n\n def test_get_github_url_owner_and_repo_with_link_in_description(self):\n \"\"\"Unit test for get_github_URL_owner_and_repo functionality.\"\"\"\n pythondateutil_pypi_data = get_pypi_data(\"python-dateutil\")\n assert pythondateutil_pypi_data[\"github_owner_and_repo\"] == \"dateutil/dateutil\"\n rsa_pypi_data = get_pypi_data(\"rsa\")\n assert rsa_pypi_data[\"github_owner_and_repo\"] == \"sybrenstuvel/python-rsa\"\n py_pypi_data = get_pypi_data(\"py\")\n assert py_pypi_data[\"github_owner_and_repo\"] == \"pytest-dev/py\"\n\n @pytest.mark.xfail # known bug, don't know how to fix without breaking other code\n def test_get_github_url_owner_and_repo_with_link_in_description_hyperlinked(self):\n \"\"\"\n Unit test for get_github_URL_owner_and_repo functionality where URL is\n embedded in hypertext\n \"\"\"\n uritemplate_pypi_data = get_pypi_data(\"uritemplate\")\n assert (\n uritemplate_pypi_data[\"github_owner_and_repo\"] == \"python-hyper/uritemplate\"\n )\n\n def test_get_pypi_maintainers(self):\n \"\"\"Unit test for get_pypi_maintainers().\"\"\"\n requests_pypi_data = get_pypi_data(\"pcap2map\")\n assert requests_pypi_data[\"pypi_maintainers\"] == [\"jspeed-meyers\"]\n\n\nclass TestGitHubFunctionality: # pragma: no cover\n \"\"\"Unit tests related to GitHub functionality\"\"\"\n\n def test_get_contributors(self):\n \"\"\"Unit test for get_contributors().\"\"\"\n assert get_contributors(\"jspeed-meyers/pcap2map\") == [\"jspeed-meyers\"]\n\n def test_get_contributor_location(self):\n \"\"\"Unit test for get_contributor_location().\"\"\"\n assert get_contributor_location(\"anarkiwi\") == \"Wellington, New Zealand\"\n\n def test_get_country_from_location_standard_order_with_comma(self):\n \"\"\"test get_country_from_location on standard order pairs with comma.\"\"\"\n assert get_country_from_location(\"Wellington, New Zealand\") == \"New Zealand\"\n assert get_country_from_location(\"Jordan, Minnesota\") == \"United States\"\n assert get_country_from_location(\"Jordan, MN\") == \"United States\"\n assert get_country_from_location(\"Atlanta, Georgia\") == \"United States\"\n assert get_country_from_location(\"Atlanta, Ga\") == \"United States\"\n assert get_country_from_location(\"London, England\") == \"United Kingdom\"\n assert get_country_from_location(\"Prague, Czech Republic\") == \"Czech Republic\"\n assert get_country_from_location(\"Virginia, USA\") == \"United States\"\n assert get_country_from_location(\"Naperville, IL\") == \"United States\"\n assert get_country_from_location(\"Toronto, Ontario, Canada\") == \"Canada\"\n assert get_country_from_location(\"Berlin, DE\") == \"Germany\"\n assert get_country_from_location(\"CSU Sacramento\") == \"United States\"\n assert get_country_from_location(\"Philadelphia, PA\") == \"United States\"\n\n def test_get_country_from_location_nonstandard_order(self):\n \"\"\"test get_country_from_location on non-standard order pairs.\"\"\"\n assert get_country_from_location(\"Russia, Moscow\") == \"Russia\"\n assert get_country_from_location(\"Russia, Nizhny Novgorod\") == \"Russia\"\n\n def test_get_country_from_location_standard_order_no_comma(self):\n \"\"\"test get_country_from_location on standard order pairs without comma.\"\"\"\n assert get_country_from_location(\"Menlo Park CA\") == \"United States\"\n\n def test_get_country_from_location_world_cities(self):\n \"\"\"test get_country_from_location on world city names.\"\"\"\n assert get_country_from_location(\"Tokyo\") == \"Japan\"\n assert get_country_from_location(\"London\") == \"United Kingdom\"\n assert get_country_from_location(\"Jakarta\") == \"Indonesia\"\n assert get_country_from_location(\"Beijing\") == \"China\"\n assert get_country_from_location(\"Washington D.C.\") == \"United States\"\n assert get_country_from_location(\"Toronto, ON\") == \"Canada\"\n\n def test_get_country_from_location_country_abbreviations(self):\n \"\"\"test get_country_from_location on country abbreviations.\"\"\"\n assert get_country_from_location(\"USA\") == \"United States\"\n assert get_country_from_location(\"Cambridge, UK\") == \"United Kingdom\"\n assert get_country_from_location(\"UK\") == \"United Kingdom\"\n\n def test_get_country_from_location_corner_case_geographies(self):\n \"\"\"test get_country_from_location on unusual geographies.\"\"\"\n assert get_country_from_location(\"Palestine\") == \"Palestine\"\n assert get_country_from_location(\"San Francisco Bay Area\") == \"United States\"\n assert get_country_from_location(\"EU\") == \"None\"\n assert get_country_from_location(\"Canary Islands\") == \"Spain\"\n assert get_country_from_location(\"Earth\") == \"None\"\n assert get_country_from_location(\"Sydney\") == \"Australia\"\n assert get_country_from_location(\"Amsterdam\") == \"Netherlands\"\n assert get_country_from_location(\"NYC\") == \"United States\"\n assert get_country_from_location(\"Barcelona\") == \"Spain\"\n assert get_country_from_location(\"Kerala\") == \"India\"\n assert get_country_from_location(\"Hyderabad\") == \"India\"\n assert get_country_from_location(\"Vancouver\") == \"Canada\"\n assert get_country_from_location(\"Jiangxi\") == \"China\"\n assert get_country_from_location(\"San Francisco\") == \"United States\"\n assert get_country_from_location(\"New York\") == \"United States\"\n assert get_country_from_location(\"Saint Petersburg\") == \"Russia\"\n assert get_country_from_location(\"England\") == \"United Kingdom\"\n assert get_country_from_location(\"Athens\") == \"Greece\"\n assert get_country_from_location(\"Europe\") == \"None\"\n assert get_country_from_location(\"Lima\") == \"Peru\"\n assert get_country_from_location(\"Bay Area\") == \"United States\"\n assert get_country_from_location(\"EU\") == \"None\"\n assert get_country_from_location(\"Canary Islands\") == \"Spain\"\n assert get_country_from_location(\"waterloo\") == \"United Kingdom\"\n assert get_country_from_location(\"Europe/Berlin\") == \"None\"\n assert get_country_from_location(\"York\") == \"United Kingdom\"\n assert get_country_from_location(\"München\") == \"Germany\"\n assert get_country_from_location(\"Montreal, CA\") == \"Canada\"\n assert get_country_from_location(\"Florianópolis\") == \"Brazil\"\n assert get_country_from_location(\"Montréal\") == \"Canada\"\n assert get_country_from_location(\"Bangalore\") == \"India\"\n assert get_country_from_location(\"Dublin\") == \"Ireland\"\n assert get_country_from_location(\"Santiago de Querétaro, México\") == \"Mexico\"\n assert get_country_from_location(\"Jülich\") == \"Germany\"\n assert get_country_from_location(\"Victoria, BC\") == \"Canada\"\n assert get_country_from_location(\"Waterloo, ON\") == \"Canada\"\n assert get_country_from_location(\"Falls Church, Virginia\") == \"United States\"\n assert get_country_from_location(\"Amsterdam, the Netherlands\") == \"Netherlands\"\n assert get_country_from_location(\"BeiJing\") == \"China\"\n assert get_country_from_location(\"Edinburgh, Scotland\") == \"United Kingdom\"\n assert get_country_from_location(\"Medellín, Colombia\") == \"Colombia\"\n assert get_country_from_location(\"La Jolla, CA.\") == \"United States\"\n assert get_country_from_location(\"beijing\") == \"China\"\n assert get_country_from_location(\"Pemberton, British Columbia\") == \"Canada\"\n assert get_country_from_location(\"Timișoara\") == \"Romania\"\n assert get_country_from_location(\"PRC\") == \"China\"\n assert get_country_from_location(\"Amsterdam, The Netherlands\") == \"Netherlands\"\n assert get_country_from_location(\"Oxford\") == \"United Kingdom\"\n assert get_country_from_location(\"São Paulo\") == \"Brazil\"\n assert get_country_from_location(\"Kyiv\") == \"Ukraine\"\n assert get_country_from_location(\"Vancouver, BC\") == \"Canada\"\n assert get_country_from_location(\"N.H.\") == \"United States\"\n assert get_country_from_location(\"Sri-City, Andhra Pradesh\") == \"India\"\n assert get_country_from_location(\"Scotland\") == \"United Kingdom\"\n assert get_country_from_location(\"Geneva\") == \"Switzerland\"\n assert get_country_from_location(\"Rotterdam, the Netherlands\") == \"Netherlands\"\n assert get_country_from_location(\"Milan\") == \"Italy\"\n assert get_country_from_location(\"Republic of Korea\") == \"South Korea\"\n assert get_country_from_location(\"Brasília, Brazil.\") == \"Brazil\"\n assert get_country_from_location(\"beijing\") == \"China\"\n assert get_country_from_location(\"Zürich\") == \"Switzerland\"\n assert get_country_from_location(\"Kitchener, Ontario\") == \"Canada\"\n assert get_country_from_location(\"Montréal, QC\") == \"Canada\"\n assert get_country_from_location(\"Glasgow, Scotland\") == \"United Kingdom\"\n assert (\n get_country_from_location(\"28 rue du Dr Roux 75015 Paris, FRANCE\")\n == \"France\"\n )\n assert get_country_from_location(\"Kraków\") == \"Poland\"\n assert get_country_from_location(\"İstanbul\") == \"Turkey\"\n assert get_country_from_location(\"Russian Federation\") == \"Russia\"\n assert get_country_from_location(\"Newcastle, NSW\") == \"Australia\"\n assert get_country_from_location(\"Australia, Victoria\") == \"Australia\"\n assert get_country_from_location(\"Perth, Western Australia \") == \"Australia\"\n assert get_country_from_location(\"Gdańsk\") == \"Poland\"\n assert get_country_from_location(\"SF\") == \"United States\"\n assert get_country_from_location(\"Hyderabad (India)\") == \"India\"\n assert get_country_from_location(\"BITS Pilani, Rajasthan\") == \"India\"\n assert get_country_from_location(\"Sri-City, Andhra Pradesh\") == \"India\"\n\n @pytest.mark.xfail # known bug, unknown origin\n def test_get_country_from_location_dataset_pull_geographies(self):\n \"\"\"tests of get_gountry_from_location() that fail as of 2/14/2021\"\"\"\n assert get_country_from_location(\"Saclay\") == \"France\"\n assert get_country_from_location(\"Warszawa\") == \"Poland\"\n assert get_country_from_location(\"brookline, ma\") == \"United States\"\n assert get_country_from_location(\"Greater Los Angeles Area\") == \"United States\"\n assert get_country_from_location(\"Forschungszentrum\") == \"Germany\"\n assert get_country_from_location(\"Montigny-lès-Metz\") == \"France\"\n assert get_country_from_location(\"roudnice nad labem, czech republic\") == \"Czech Republic\"\n assert get_country_from_location(\"Berlin/Florence\") == \"Germany\"\n assert get_country_from_location(\"Greater Seattle Area\") == \"United States\"\n assert get_country_from_location(\"Flanders, Europe, Earth\") == \"Belgium\"\n assert get_country_from_location(\"Wrocław\") == \"Poland\"\n\n def test_extract_github_owner_and_repo(self):\n \"\"\"Unit test for extract_github_owner_and_repo().\"\"\"\n owner_and_repo = extract_github_owner_and_repo(\"www.github.com/psf/requests\")\n assert owner_and_repo == \"psf/requests\"\n\n def test_get_github_tokens(self):\n \"\"\"Unit test for get_github_tokens(). Check proper cycling.\"\"\"\n tokens = get_github_tokens(\"test_tokens.txt\")\n token1 = next(tokens)\n assert token1 == \"test_token_1\"\n token2 = next(tokens)\n assert token2 == \"test_token_2\"\n\n def test_read_in_github_token_list(self):\n \"\"\"Unit test for read_in_github_token_list().\"\"\"\n tokens = read_in_github_token_list(\"test_tokens.txt\")\n assert tokens[0] == \"test_token_1\"\n assert tokens[1] == \"test_token_2\"\n\n\nclass TestCsvFunctionality: # pragma: no cover\n \"\"\"Unit tests related to CSV functionality\"\"\"\n\n def test_create_csv(self):\n \"\"\"Unit test for create_csv().\"\"\"\n create_csv(\"contributors\", \"1\")\n assert os.path.exists(os.path.join(\"results\", \"contributors_1.csv\"))\n\n def test_add_committer_to_csv(self):\n \"\"\"Unit test fpr add_co0mmitter_to_csv.\"\"\"\n add_committer_to_csv(\n \"contributors\", \"test\", \"1\", \"googlemoogle\", \"eschmidt\", \"innovation-island\"\n )\n os.remove(os.path.join(\"results\", \"contributors_1.csv\")) # remove file\n\n\nclass TestMultiRepoScan: # pragma: no cover\n \"\"\"Tests related to multi-repo scanning capability.\"\"\"\n\n # pylint: disable=too-few-public-methods\n\n def test_multi_repo_scan(self):\n \"\"\"Unit test for scan_multiple_repos().\"\"\"\n scan_multiple_repos(\"test_repos.txt\")\n # identify file created for test\n files = glob.glob(\"results/*.csv\")\n test_file = max(files, key=os.path.getctime)\n # check that csv rows are as expected\n with open(test_file, newline=\"\") as test_output:\n for index, row in enumerate(csv.reader(test_output)):\n if index == 0:\n assert row == [\"software_name\", \"username\", \"location\", \"country\"]\n elif index == 1:\n assert row == [\n \"jspeed-meyers_pcap2map\",\n \"jspeed-meyers\",\n \"\",\n \"None\",\n ]\n elif index == 4:\n assert row == [\n \"iqtlabs_portunus\",\n \"anarkiwi\",\n \"Wellington, New Zealand\",\n \"New Zealand\",\n ]\n os.remove(test_file)\n\n\nclass TestMapping:\n \"\"\"Tests related to mapping capability.\"\"\"\n\n # pylint: disable=invalid-name\n\n def test_get_dataframe_from_repo(self):\n \"\"\"Unit test for get_dataframe_from_repo().\"\"\"\n output = get_dataframe_from_repo(\"www.github.com/iqtlabs/pypi-scan\")\n expected_ouput = pd.DataFrame(\n {\"country\": [\"None\", \"New Zealand\"], \"contributor_count\": [2, 1]}\n )\n assert output[0].equals(expected_ouput)\n assert output[1] >= 3\n\n def test_get_dataframe_from_csv(self):\n \"\"\"Unit test for get_dataframe_from_csv().\"\"\"\n output = get_dataframe_from_csv(\"test_multirepo.csv\")\n expected_ouput = pd.DataFrame(\n {\"country\": [\"None\", \"Portugal\"], \"contributor_count\": [3, 1]}\n )\n assert output[0].equals(expected_ouput)\n assert output[1] >= 4\n\n def test_add_contributor_count_to_json(self):\n \"\"\"Unit test for add_contributor_count_to_json().\"\"\"\n df = pd.DataFrame(\n {\"country\": [\"None\", \"Portugal\"], \"contributor_count\": [3, 1]}\n )\n output = add_contributor_count_to_json(df)\n assert isinstance(output, str)\n\n def test_make_map_from_repo(self):\n \"\"\"Unit test for make_map() with a number greater than 100 of contributors\n and using a repo URL.\"\"\"\n make_map(repo=\"www.github.com/iqtlabs/gitgeo\", num=200)\n # identify and delete map file created for test\n files = glob.glob(\"results/*.html\")\n test_file = max(files, key=os.path.getctime)\n os.remove(test_file)\n\n def test_make_map_from_csv(self):\n \"\"\"Unit test for make_map() using a csv created by multirepo_scan.\"\"\"\n make_map(csv=\"test_multirepo.csv\")\n files = glob.glob(\"results/*.html\")\n test_file = max(files, key=os.path.getctime)\n os.remove(test_file)\n\n\ndef test_print_by_contributor_repo(capsys):\n \"\"\"Unit test for print by contributors for GitHub repo.\"\"\"\n repo = \"jspeed-meyers/pcap2map\"\n contributors = get_contributors(repo)\n print_by_contributor(repo, contributors)\n captured = capsys.readouterr() # capture output printed\n # dedent removes spacing, using the spacing width from the first line\n output_text = textwrap.dedent(\n \"\"\" CONTRIBUTOR, LOCATION\n ---------------------\n jspeed-meyers | None | None\\n\"\"\"\n )\n assert captured.out == output_text\n\n\ndef test_print_by_contributor_package(capsys):\n \"\"\"Unit test for print_by_contributor() for networml python package.\"\"\"\n pkg = \"networkml\"\n pypi_data = get_pypi_data(pkg)\n contributors = get_contributors(pypi_data[\"github_owner_and_repo\"])\n print_by_contributor(pkg, contributors, pypi_data=pypi_data)\n captured = capsys.readouterr() # capture output\n # dedent removes spacing, using the spacing width from the first line\n output_text = textwrap.dedent(\n \"\"\" CONTRIBUTOR, LOCATION\n * indicates PyPI maintainer\n ---------------------\n cglewis * | USA | United States\n anarkiwi | Wellington, New Zealand | New Zealand\n CStephenson970 | None | None\n renovate-bot | None | None\n lilchurro | None | None\n jspeed-meyers * | None | None\n rashley-iqt | None | None\n pyup-bot | None | None\n alshaboti | Wellington, New Zealand | New Zealand\n jseparovic | Mountain View, CA | United States\n squeeve | None | None\n gregs5 | Washington DC | United States\n krb1997 | None | None\n toddstavish | None | None\n sneakyoctopus12 | None | None\n Hax7 | Palestine | Palestine\n paulgowdy | Menlo Park CA | United States\\n\"\"\"\n )\n assert captured.out == output_text\n\n\ndef test_print_by_country(capsys):\n \"\"\"Unit test for print_by_country() for networml python package.\"\"\"\n repo = \"https://www.github.com/iqtlabs/networkml\"\n repo_ending_string = extract_github_owner_and_repo(repo)\n contributors = get_contributors(repo_ending_string)\n print_by_country(contributors)\n captured = capsys.readouterr() # capture output printed to date\n # dedent removes spacing, using the spacing width from the first line\n output_text = textwrap.dedent(\n \"\"\" COUNTRY | # OF CONTRIBUTORS\n ---------------------------\n None 10\n United States 4\n New Zealand 2\n Palestine 1\\n\"\"\"\n )\n assert captured.out == output_text\n\n\ndef test_scan_single_package_no_summary(capsys):\n \"\"\"Integration test for scan_single_package with no summary.\"\"\"\n pkg = \"pcap2map\"\n scan_single_package(pkg, False) # False indicates no summary\n captured = capsys.readouterr() # capture output printed\n # dedent removes spacing, using the spacing width from the first line\n output_text = textwrap.dedent(\n \"\"\" -----------------\n PACKAGE: pcap2map\n GITHUB REPO: jspeed-meyers/pcap2map\n -----------------\n CONTRIBUTOR, LOCATION\n * indicates PyPI maintainer\n ---------------------\n jspeed-meyers * | None | None\\n\"\"\"\n )\n assert captured.out == output_text\n\n\[email protected] # known bug, unknown origin\ndef test_scan_single_package_with_summary(capsys):\n \"\"\"Integration test for scan_single_package with summary.\"\"\"\n pkg = \"networkml\"\n scan_single_package(pkg, True) # True indicates do summary\n captured = capsys.readouterr() # capture output printed\n # dedent removes spacing, using the spacing width from the first line\n output_text = textwrap.dedent(\n \"\"\" -----------------\n PACKAGE: networkml\n GITHUB REPO: IQTLabs/NetworkML\n -----------------\n COUNTRY | # OF CONTRIBUTORS\n ---------------------------\n None 10\n United States 4\n New Zealand 2\n Palestine 1\\n\"\"\"\n )\n assert captured.out == output_text\n\n\[email protected] # known bug, likely with capsys and pytest, test fails in actions\ndef test_scan_single_repo_no_summary(capsys):\n \"\"\"Integration test for scan_single_repo with no summary.\"\"\"\n repo = \"https://www.github.com/jspeed-meyers/pcap2map\"\n scan_single_repo(repo, summary=False, output_csv=False)\n captured = capsys.readouterr() # capture output printed\n # dedent removes spacing, using the spacing width from the first line\n output_text = textwrap.dedent(\n \"\"\" -----------------\n GITHUB REPO: jspeed-meyers/pcap2map\n -----------------\n CONTRIBUTOR, LOCATION\n ---------------------\n jspeed-meyers | None | None\\n\"\"\"\n )\n assert captured.out == output_text\n\n\[email protected] # known bug, likely with capsys and pytest, test fails in actions\ndef test_scan_single_repo_with_summary(capsys):\n \"\"\"Integration test for scan_single_repo with summary.\"\"\"\n repo = \"https://www.github.com/IQTLabs/NetworkML\"\n scan_single_repo(repo, summary=True, output_csv=False)\n captured = capsys.readouterr() # capture output printed\n # dedent removes spacing, using the spacing width from the first line\n output_text = textwrap.dedent(\n \"\"\" -----------------\n GITHUB REPO: IQTLabs/NetworkML\n -----------------\n COUNTRY | # OF CONTRIBUTORS\n ---------------------------\n None 11\n United States 4\n New Zealand 2\\n\"\"\"\n )\n assert captured.out == output_text\n"
] | [
[
"pandas.DataFrame"
]
] |
chxy95/SRCNN | [
"b2d43e3d605b751cd6cd0290047f24932d159185"
] | [
"train.py"
] | [
"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Jun 25 16:50:16 2019\n\n@author: chxy\n\"\"\"\n\nimport torch\nimport torch.nn as nn\nfrom model import SRCNN_net\nimport torch.optim as optim\nfrom data_loader import loadtraindata, loadtestdata\nfrom torch.autograd import Variable\n\nfrom math import ceil\ndef train(num_channels=1, learning_rate=1e-3, epochs=1000):\n trainloader = loadtraindata()\n testloader = loadtestdata()\n net = SRCNN_net(num_channels=num_channels).cuda()\n\n conv3_params = list(map(id, net.conv3.parameters()))\n base_params = filter(lambda p: id(p) not in conv3_params, net.parameters())\n optimizer = torch.optim.Adam([\n {'params': base_params},\n {'params': net.conv3.parameters(), 'lr': learning_rate * 0.1}\n ], lr=learning_rate)\n\n #optimizer = optim.Adam(net.parameters(), lr=learning_rate) \n loss_fn = nn.MSELoss().cuda()\n train_loss_list = []\n test_loss_list = []\n\t\n for epoch in range(epochs):\n\t\n train_loss = 0.0\n test_loss = 0.0\n\t\t\n for i, data in enumerate(trainloader):\n imgLR, label = data\n imgLR, label = imgLR.cuda(), label.cuda()\n imgLR, label = Variable(imgLR), Variable(label)\n imgHR = net(imgLR)\n loss = loss_fn(imgHR, label)\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n train_loss += loss.item()\n train_loss = train_loss / (i+1)\n\t\t\n for i, data in enumerate(testloader):\n imgLR, label = data\n imgLR, label = imgLR.cuda(), label.cuda()\n imgLR, label = Variable(imgLR), Variable(label)\n imgHR = net(imgLR)\n loss = loss_fn(imgHR, label)\n test_loss += loss.item()\n test_loss = test_loss / (i+1)\n\t\t\n print(\"epoch : {}, train_loss : {:.6f}, test_loss : {:.6f}\".format(epoch+1, train_loss, test_loss))\n \n torch.save(net.state_dict(), './ckpt/epoch_{}_train_loss_{}_test_loss_{}_net_params.pkl'.format(epoch+1, train_loss, test_loss))\n train_loss_list.append(train_loss)\n test_loss_list.append(test_loss)\n with open('loss.txt', 'w') as f:\n for i in range(epochs):\n f.write(\"{} {}\\n\".format(train_loss_list[i], test_loss_list[i]))\n\ntrain()\n"
] | [
[
"torch.nn.MSELoss",
"torch.autograd.Variable"
]
] |
yinchi/simpy-examples | [
"bb9f2d8ab009f7089d50d63aa699aebfce29ace3"
] | [
"ex07_mmkk_mdkk.py"
] | [
"# 07 M/M/k/k vs M/D/k/k\n\n'''\nBecause of insensitivity, the request blocking probability of the\nM/G/k/k queue, of which the M/M/k/k and M/D/k/k queues are subtypes,\nis insensitive to the shape of the service time distribution apart\nfrom the mean.\n\nHere, we use confidence intervals to demonstrate this for different\narrival rates. We will plot the results in Example 8.\n'''\n\nimport simpy\nimport numpy as np\nimport ex04_mmkk as mmkk\nimport ex06_mdkk as mdkk\nfrom ex05_confidence_intervals import ci\n\ndef mean_err(ci):\n # convert confidence interval from (min,max) to (mean,error_bound)\n return (np.mean(ci), np.max(ci) - np.mean(ci))\n\ndef sim_mmkk(lambd, tau = 1):\n mmkk_results = np.empty(10)\n for i in range(10):\n mmkk_env = simpy.Environment()\n mmkk_stats = mmkk.SimStats()\n mmkk_q = simpy.Resource(mmkk_env, capacity = 10)\n mmkk_env.process(mmkk.generator(mmkk_env, mmkk_stats, mmkk_q, lambd, tau))\n mmkk_env.run(until=100_000.0/lambd)\n mmkk_results[i] = mmkk_stats.nBlocked/mmkk_stats.nArrived\n return mean_err(ci(mmkk_results))\n\ndef sim_mdkk(lambd, tau = 1):\n mdkk_results = np.empty(10)\n for i in range(10):\n mdkk_env = simpy.Environment()\n mdkk_stats = mdkk.SimStats()\n mdkk_q = simpy.Resource(mdkk_env, capacity = 10)\n mdkk_env.process(mdkk.generator(mdkk_env, mdkk_stats, mdkk_q, lambd, tau))\n mdkk_env.run(until=100_000.0/lambd)\n mdkk_results[i] = mdkk_stats.nBlocked/mdkk_stats.nArrived\n return mean_err(ci(mdkk_results))\n\n# lambd = 3 to 15.1 by 1 (we make the endpoint a bit bigger than 15 to ensure 15 is included in the range)\nfor lambd in np.arange(3,15.1,1):\n print(lambd, *sim_mmkk(lambd), *sim_mdkk(lambd))\n"
] | [
[
"numpy.arange",
"numpy.max",
"numpy.mean",
"numpy.empty"
]
] |
johnlees/mandrake | [
"f34deb1aeed730041398923c1c0d6e6d5ccb9611"
] | [
"mandrake/dists.py"
] | [
"# vim: set fileencoding=<utf-8> :\n# Copyright 2020 John Lees and Gerry Tonkin-Hill\n\n'''Methods for calculating distances from sequence input'''\n\nimport re\nimport numpy as np\nimport pandas as pd\nfrom sklearn.neighbors import kneighbors_graph\n\n# C++ extensions\nimport pp_sketchlib\n\nfrom .pairsnp import runPairsnp\nfrom .sketchlib import get_kmer_sizes, get_seqs_in_db\n\n\ndef accessoryDists(accessory_file, kNN, threshold, cpus):\n acc_mat = pd.read_csv(accessory_file, sep=\"\\t\", header=0, index_col=0)\n names = list(acc_mat.columns)\n\n if kNN <= 0:\n kNN = len(names) - 1\n\n sp = kneighbors_graph(X=acc_mat.T, n_neighbors=kNN,\n metric='jaccard', mode='distance',\n include_self=False, n_jobs=cpus).tocoo()\n\n if threshold > 0:\n index = []\n for i, d in enumerate(sp.data):\n if d < threshold:\n index.append(i)\n index = np.array(index)\n sp.row = sp.row[index]\n sp.col = sp.col[index]\n sp.data = sp.data[index]\n\n return sp.row, sp.col, sp.data, names\n\n\ndef pairSnpDists(alignment, threshold, kNN, cpus):\n I, J, dists, names = runPairsnp(alignment,\n kNN=kNN,\n threshold=threshold,\n threads=cpus)\n return I, J, dists, names\n\n\ndef sketchlibDists(sketch_db, dist_col, kNN, threshold, cpus, use_gpu, device_id):\n names = get_seqs_in_db(sketch_db + \".h5\")\n kmers = get_kmer_sizes(sketch_db + \".h5\")\n\n sketchlib_version = re.search(r\"(\\d+)\\.(\\d+)\\.(\\d+)\", pp_sketchlib.version)\n if sketchlib_version and int(sketchlib_version.group(1)) >= 2:\n # v2 of sketchlib supports 'true' sparse query which reduces distance\n # matrix on the fly\n if (len(kmers) == 1):\n jaccard = True\n else:\n jaccard = False\n if threshold > 0:\n raise ValueError(\"Use kNN with --sketches\")\n I, J, dists = pp_sketchlib.querySelfSparse(ref_db_name=sketch_db,\n rList=names,\n klist=kmers,\n random_correct=True,\n jaccard=jaccard,\n kNN=kNN,\n dist_cutoff=0,\n dist_col=dist_col,\n num_threads=cpus,\n use_gpu=use_gpu,\n device_id=device_id)\n else:\n # older versions of sketchlib do a dense query then sparsify the\n # return. Ok for smaller data, but runs out of memory on big datasets\n # sketchlib API needs positive int for kNN\n if kNN < 0:\n kNN = 0\n if threshold <= 0:\n threshold = 0.0\n I, J, dists = pp_sketchlib.queryDatabaseSparse(ref_db_name=sketch_db,\n query_db_name=sketch_db,\n rList=names,\n qList=names,\n klist=kmers,\n random_correct=True,\n dist_cutoff=threshold,\n kNN=kNN,\n core=(dist_col == 0),\n num_threads=cpus,\n use_gpu=use_gpu,\n device_id=device_id)\n\n return I, J, dists, names\n"
] | [
[
"sklearn.neighbors.kneighbors_graph",
"numpy.array",
"pandas.read_csv"
]
] |
joao-aveiro/OOPAO | [
"213a447cd6a154683a7339f35d80b3cd36d9063a"
] | [
"AO_modules/SPRINT.py"
] | [
"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Wed Jun 2 13:30:51 2021\r\n\r\n@author: cheritie\r\n\"\"\"\r\n\r\nfrom AO_modules.mis_registration_identification_algorithm.estimateMisRegistration import estimateMisRegistration\r\nfrom AO_modules.mis_registration_identification_algorithm.computeMetaSensitivyMatrix import computeMetaSensitivityMatrix\r\nfrom AO_modules.MisRegistration import MisRegistration\r\nfrom AO_modules.calibration.CalibrationVault import calibrationVault\r\nimport numpy as np\r\n\r\nclass SPRINT:\r\n def __init__(self,obj, basis, nameFolder = None, nameSystem = None, mis_registration_zero_point = None, wfs_mis_registered= None, fast_algorithm = False, n_iteration = 3):\r\n print('Setting up SPRINT..')\r\n # modal basis considered\r\n self.basis = basis\r\n # consider the case when only one signal is used\r\n if len(basis.indexModes)==1:\r\n self.basis.indexModes = [basis.indexModes,basis.indexModes]\r\n self.basis.modes = np.asarray([basis.modes,basis.modes]).T \r\n \r\n # Case where the shifts are applied in the WFS space \r\n self.wfs_mis_registered = wfs_mis_registered\r\n # fast version of the algorithm (WARNING: not stable)\r\n self.fast_algorithm = fast_algorithm\r\n \r\n # zero point for the sensitivity matrices\r\n if mis_registration_zero_point is None:\r\n self.mis_registration_zero_point = MisRegistration()\r\n else:\r\n self.mis_registration_zero_point = mis_registration_zero_point\r\n\r\n # epsilon mis-registration for the computation of the directional gradients\r\n self.epsilonMisRegistration = MisRegistration()\r\n self.epsilonMisRegistration.shiftX = np.round(obj.dm.pitch /10,4)\r\n self.epsilonMisRegistration.shiftY = np.round(obj.dm.pitch /10,4)\r\n self.epsilonMisRegistration.rotationAngle = np.round(np.rad2deg(np.arctan(self.epsilonMisRegistration.shiftX)/(obj.tel.D/2)),4)\r\n \r\n # folder name to save the sensitivity matrices\r\n if nameFolder is None:\r\n self.nameFolder_sensitivity_matrice = obj.param['pathInput'] +'/'+ obj.param['name']+'/s_mat/'\r\n else:\r\n self.nameFolder_sensitivity_matrice = nameFolder\r\n \r\n # name of the system considered\r\n if nameSystem is None:\r\n self.name_system = ''\r\n else:\r\n self.name_system = nameSystem\r\n\r\n # pre-compute the sensitivity matrices\r\n [self.metaMatrix,self.calib_0] = computeMetaSensitivityMatrix(nameFolder = self.nameFolder_sensitivity_matrice,\\\r\n nameSystem = self.name_system,\\\r\n tel = obj.tel,\\\r\n atm = obj.atm,\\\r\n ngs = obj.ngs,\\\r\n dm_0 = obj.dm,\\\r\n pitch = obj.dm.pitch,\\\r\n wfs = obj.wfs,\\\r\n basis = basis,\\\r\n misRegistrationZeroPoint = self.mis_registration_zero_point,\\\r\n epsilonMisRegistration = self.epsilonMisRegistration,\\\r\n param = obj.param,\\\r\n wfs_mis_registrated = wfs_mis_registered)\r\n \r\n \r\n print('Done!')\r\n\r\n def estimate(self,obj,on_sky_slopes, n_iteration = 3):\r\n \"\"\"\r\n Method of SPRINT to estimate the mis-registrations parameters\r\n - obj : a class containing the different objects, tel, dm, atm, ngs and wfs\r\n _ on_sky_slopes : the wfs signal used to identify the mis-registration parameters\r\n _ n_iteration : the number of iterations to consider\r\n \r\n exemple: \r\n Sprint.estimate(obj, my_wfs_signal, n_iteration = 3)\r\n The estimation are available using:\r\n Sprint.mis_registration_out.shift_x ---- shift in m\r\n Sprint.mis_registration_out.shift_y ---- shift in m \r\n Sprint.mis_registration_out.rotation ---- rotation in degree\r\n \"\"\"\r\n if np.ndim(on_sky_slopes)==1:\r\n calib_misReg_in = calibrationVault(np.squeeze(np.asarray([on_sky_slopes.T,on_sky_slopes.T]).T))\r\n else:\r\n calib_misReg_in = calibrationVault(on_sky_slopes)\r\n \r\n\r\n [self.mis_registration_out ,self.scaling_factor ,self.mis_registration_buffer] = estimateMisRegistration( nameFolder = self.nameFolder_sensitivity_matrice,\\\r\n nameSystem = self.name_system,\\\r\n tel = obj.tel,\\\r\n atm = obj.atm,\\\r\n ngs = obj.ngs,\\\r\n dm_0 = obj.dm,\\\r\n calib_in = calib_misReg_in,\\\r\n wfs = obj.wfs,\\\r\n basis = self.basis,\\\r\n misRegistrationZeroPoint = self.mis_registration_zero_point,\\\r\n epsilonMisRegistration = self.epsilonMisRegistration,\\\r\n param = obj.param,\\\r\n precision = 5,\\\r\n return_all = True,\\\r\n nIteration = n_iteration,\\\r\n fast = self.fast_algorithm,\\\r\n wfs_mis_registrated = self.wfs_mis_registered,\\\r\n sensitivity_matrices = self.metaMatrix )\r\n "
] | [
[
"numpy.round",
"numpy.asarray",
"numpy.arctan",
"numpy.ndim"
]
] |
snc2/tequila | [
"6767ced9215408f7d055c22df7a66ccd610b00fb"
] | [
"src/tequila/hamiltonian/paulis.py"
] | [
"\"\"\"\nConvenience initialization\nof Pauli Operators. Resulting structures can be added and multiplied together.\nCurrently uses OpenFermion as backend (QubitOperators)\n\"\"\"\nimport typing\nfrom tequila.hamiltonian import QubitHamiltonian\nfrom tequila import BitString, TequilaException\nfrom tequila.wavefunction.qubit_wavefunction import QubitWaveFunction\nfrom tequila.tools import list_assignement\nimport numpy\n\n\ndef pauli(qubit, type) -> QubitHamiltonian:\n \"\"\"\n Parameters\n ----------\n qubit: int or list of ints\n\n type: str or int or list of string or int:\n define if X, Y or Z (0,1,2)\n\n Returns\n -------\n QubitHamiltonian\n \"\"\"\n\n def assign_axis(axis):\n if axis in QubitHamiltonian.axis_to_string:\n return QubitHamiltonian.axis_to_string[axis]\n elif hasattr(axis, \"upper\"):\n return axis.upper()\n else:\n raise TequilaException(\"unknown initialization for pauli operator: {}\".format(axis))\n\n if not isinstance(qubit, typing.Iterable):\n qubit = [qubit]\n type = [type]\n\n type = [assign_axis(x) for x in type]\n\n init_string = \"\".join(\"{}{} \".format(t, q) for t, q in zip(type, qubit))\n\n return QubitHamiltonian.from_string(string=init_string, openfermion_format=True)\n\n\ndef X(qubit) -> QubitHamiltonian:\n \"\"\"\n Initialize a single Pauli X Operator\n\n Parameters\n ----------\n qubit: int or list of ints\n qubit(s) on which the operator should act\n\n Returns\n -------\n QubitHamiltonian\n\n \"\"\"\n qubit = list_assignement(qubit)\n return pauli(qubit=qubit, type=[\"X\"] * len(qubit))\n\n\ndef Y(qubit) -> QubitHamiltonian:\n \"\"\"\n Initialize a single Pauli Y Operator\n\n Parameters\n ----------\n qubit: int or list of ints\n qubit(s) on which the operator should act\n\n Returns\n -------\n QubitHamiltonian\n\n \"\"\"\n qubit = list_assignement(qubit)\n return pauli(qubit=qubit, type=[\"Y\"] * len(qubit))\n\n\ndef Z(qubit) -> QubitHamiltonian:\n \"\"\"\n Initialize a single Pauli Z Operator\n\n Parameters\n ----------\n qubit: int or list of ints\n qubit(s) on which the operator should act\n\n Returns\n -------\n QubitHamiltonian\n\n \"\"\"\n qubit = list_assignement(qubit)\n return pauli(qubit=qubit, type=[\"Z\"] * len(qubit))\n\n\ndef I(*args, **kwargs) -> QubitHamiltonian:\n \"\"\"\n Initialize unit Operator\n\n Returns\n -------\n QubitHamiltonian\n\n \"\"\"\n return QubitHamiltonian.unit()\n\n\ndef Zero(*args, **kwargs) -> QubitHamiltonian:\n \"\"\"\n Initialize 0 Operator\n\n Returns\n -------\n QubitHamiltonian\n\n \"\"\"\n return QubitHamiltonian.zero()\n\n\ndef Qp(qubit) -> QubitHamiltonian:\n \"\"\"\n Notes\n ----------\n Initialize\n\n .. math::\n \\\\frac{1}{2} \\\\left( 1 - \\\\sigma_z \\\\right)\n\n Parameters\n ----------\n qubit: int or list of ints\n qubit(s) on which the operator should act\n\n Returns\n -------\n QubitHamiltonian\n\n \"\"\"\n qubit = list_assignement(qubit)\n result = I()\n for q in qubit:\n result *= 0.5 * (I(qubit=q) + Z(qubit=q))\n return result\n\n\ndef Qm(qubit) -> QubitHamiltonian:\n \"\"\"\n Notes\n ----------\n Initialize\n\n .. math::\n \\\\frac{1}{2} \\\\left( 1 + \\\\sigma_z \\\\right)\n\n Parameters\n ----------\n qubit: int or list of ints\n qubit(s) on which the operator should act\n\n Returns\n -------\n QubitHamiltonian\n\n \"\"\"\n qubit = list_assignement(qubit)\n result = I()\n for q in qubit:\n result *= 0.5 * (I(qubit=q) - Z(qubit=q))\n return result\n\n\ndef Sp(qubit) -> QubitHamiltonian:\n \"\"\"\n Notes\n ----------\n Initialize\n\n .. math::\n \\\\frac{1}{2} \\\\left( \\\\sigma_x + i\\\\sigma_y \\\\right)\n\n Parameters\n ----------\n qubit: int or list of ints\n qubit(s) on which the operator should act\n\n Returns\n -------\n QubitHamiltonian\n\n \"\"\"\n qubit = list_assignement(qubit)\n result = I()\n for q in qubit:\n result *= 0.5 * (X(qubit=q) + 1.j * Y(qubit=q))\n return result\n\n\ndef Sm(qubit) -> QubitHamiltonian:\n \"\"\"\n Notes\n ----------\n Initialize\n\n .. math::\n \\\\frac{1}{2} \\\\left( \\\\sigma_x + i \\\\sigma_y \\\\right)\n\n Parameters\n ----------\n qubit: int or list of ints\n qubit(s) on which the operator should act\n\n Returns\n -------\n QubitHamiltonian\n\n \"\"\"\n qubit = list_assignement(qubit)\n result = I()\n for q in qubit:\n result *= 0.5 * (X(qubit=q) - 1.j * Y(qubit=q))\n return result\n\n\ndef Projector(wfn, threshold=0.0, n_qubits=None) -> QubitHamiltonian:\n \"\"\"\n Notes\n ----------\n Initialize a projector given by\n\n .. math::\n H = \\\\lvert \\\\Psi \\\\rangle \\\\langle \\\\Psi \\\\rvert\n\n Parameters\n ----------\n wfn: QubitWaveFunction or int, or string, or array :\n The wavefunction onto which the projector projects\n Needs to be passed down as tequilas QubitWaveFunction type\n See the documentation on how to initialize a QubitWaveFunction from\n integer, string or array (can also be passed down diretly as one of those types)\n\n\n threshold: float: (Default value = 0.0)\n neglect small parts of the operator\n\n n_qubits: only needed when an integer is given as wavefunction\n\n Returns\n -------\n\n \"\"\"\n\n wfn = QubitWaveFunction(state=wfn, n_qubits=n_qubits)\n\n H = QubitHamiltonian.zero()\n for k1, v1 in wfn.items():\n for k2, v2 in wfn.items():\n c = v1.conjugate() * v2\n if not numpy.isclose(c, 0.0, atol=threshold):\n H += c * decompose_transfer_operator(bra=k1, ket=k2)\n assert (H.is_hermitian())\n return H\n\n\ndef KetBra(ket: QubitWaveFunction, bra: QubitWaveFunction, hermitian: bool = False, threshold: float = 1.e-6,\n n_qubits=None):\n \"\"\"\n Notes\n ----------\n Initialize the general KetBra operator\n .. math::\n H = \\\\lvert ket \\\\rangle \\\\langle bra \\\\rvert\n\n e.g.\n wfn1 = tq.QubitWaveFunction.from_string(\"1.0*|00> + 1.0*|11>\").normalize()\n wfn2 = tq.QubitWaveFunction.from_string(\"1.0*|00>\")\n operator = tq.paulis.KetBra(ket=wfn1, bra=wfn1)\n initializes the transfer operator from the all-zero state to a Bell state\n\n Parameters\n ----------\n ket: QubitWaveFunction:\n QubitWaveFunction which defines the ket element\n can also be given as string or array or integer\n bra: QubitWaveFunction:\n QubitWaveFunction which defines the bra element\n can also be given as string or array or integer\n hermitian: bool: (Default False)\n if True the hermitian version H + H^\\dagger is returned\n threshold: float: (Default 1.e-6)\n elements smaller than the threshold will be ignored\n n_qubits: only needed if ket and/or bra are passed down as integers\n\n Returns\n -------\n a tequila QubitHamiltonian (not necessarily hermitian)\n\n \"\"\"\n H = QubitHamiltonian.zero()\n ket = QubitWaveFunction(state=ket, n_qubits=n_qubits)\n bra = QubitWaveFunction(state=bra, n_qubits=n_qubits)\n\n for k1, v1 in bra.items():\n for k2, v2 in ket.items():\n c = v1.conjugate() * v2\n if not numpy.isclose(c, 0.0, atol=threshold):\n H += c * decompose_transfer_operator(bra=k1, ket=k2)\n if hermitian:\n return H.split()[0]\n else:\n return H.simplify(threshold=threshold)\n\n\ndef decompose_transfer_operator(ket: BitString, bra: BitString, qubits: typing.List[int] = None) -> QubitHamiltonian:\n \"\"\"\n Notes\n ----------\n Create the operator\n\n Note that this is operator is not necessarily hermitian\n So be careful when using it as a generator for gates\n\n e.g.\n decompose_transfer_operator(ket=\"01\", bra=\"10\", qubits=[2,3])\n gives the operator\n\n .. math::\n \\\\lvert 01 \\\\rangle \\\\langle 10 \\\\rvert_{2,3}\n\n acting on qubits 2 and 3\n\n Parameters\n ----------\n ket: pass an integer, string, or tequila BitString\n bra: pass an integer, string, or tequila BitString\n qubits: pass the qubits onto which the operator acts\n\n Returns\n -------\n\n \"\"\"\n\n opmap = {\n (0, 0): Qp,\n (0, 1): Sp,\n (1, 0): Sm,\n (1, 1): Qm\n }\n\n nbits = None\n if qubits is not None:\n nbits = len(qubits)\n\n if isinstance(bra, int):\n bra = BitString.from_int(integer=bra, nbits=nbits)\n if isinstance(ket, int):\n ket = BitString.from_int(integer=ket, nbits=nbits)\n\n b_arr = bra.array\n k_arr = ket.array\n assert (len(b_arr) == len(k_arr))\n n_qubits = len(k_arr)\n\n if qubits is None:\n qubits = range(n_qubits)\n\n assert (n_qubits <= len(qubits))\n\n result = QubitHamiltonian.unit()\n for q, b in enumerate(b_arr):\n k = k_arr[q]\n result *= opmap[(k, b)](qubit=qubits[q])\n\n return result\n"
] | [
[
"numpy.isclose"
]
] |
Ricky-Wilson/Python | [
"9896d7a9901dabea4b3d555af471577a624d1b95"
] | [
"Lib/test/test_buffer.py"
] | [
"#\n# The ndarray object from _testbuffer.c is a complete implementation of\n# a PEP-3118 buffer provider. It is independent from NumPy's ndarray\n# and the tests don't require NumPy.\n#\n# If NumPy is present, some tests check both ndarray implementations\n# against each other.\n#\n# Most ndarray tests also check that memoryview(ndarray) behaves in\n# the same way as the original. Thus, a substantial part of the\n# memoryview tests is now in this module.\n#\n\nimport unittest\nfrom test import support\nfrom itertools import permutations, product\nfrom random import randrange, sample, choice\nfrom sysconfig import get_config_var\nimport warnings\nimport sys, array, io\nfrom decimal import Decimal\nfrom fractions import Fraction\n\ntry:\n from _testbuffer import *\nexcept ImportError:\n ndarray = None\n\ntry:\n import struct\nexcept ImportError:\n struct = None\n\ntry:\n import ctypes\nexcept ImportError:\n ctypes = None\n\ntry:\n with warnings.catch_warnings():\n from numpy import ndarray as numpy_array\nexcept ImportError:\n numpy_array = None\n\n\nSHORT_TEST = True\n\n\n# ======================================================================\n# Random lists by format specifier\n# ======================================================================\n\n# Native format chars and their ranges.\nNATIVE = {\n '?':0, 'c':0, 'b':0, 'B':0,\n 'h':0, 'H':0, 'i':0, 'I':0,\n 'l':0, 'L':0, 'n':0, 'N':0,\n 'f':0, 'd':0, 'P':0\n}\n\n# NumPy does not have 'n' or 'N':\nif numpy_array:\n del NATIVE['n']\n del NATIVE['N']\n\nif struct:\n try:\n # Add \"qQ\" if present in native mode.\n struct.pack('Q', 2**64-1)\n NATIVE['q'] = 0\n NATIVE['Q'] = 0\n except struct.error:\n pass\n\n# Standard format chars and their ranges.\nSTANDARD = {\n '?':(0, 2), 'c':(0, 1<<8),\n 'b':(-(1<<7), 1<<7), 'B':(0, 1<<8),\n 'h':(-(1<<15), 1<<15), 'H':(0, 1<<16),\n 'i':(-(1<<31), 1<<31), 'I':(0, 1<<32),\n 'l':(-(1<<31), 1<<31), 'L':(0, 1<<32),\n 'q':(-(1<<63), 1<<63), 'Q':(0, 1<<64),\n 'f':(-(1<<63), 1<<63), 'd':(-(1<<1023), 1<<1023)\n}\n\ndef native_type_range(fmt):\n \"\"\"Return range of a native type.\"\"\"\n if fmt == 'c':\n lh = (0, 256)\n elif fmt == '?':\n lh = (0, 2)\n elif fmt == 'f':\n lh = (-(1<<63), 1<<63)\n elif fmt == 'd':\n lh = (-(1<<1023), 1<<1023)\n else:\n for exp in (128, 127, 64, 63, 32, 31, 16, 15, 8, 7):\n try:\n struct.pack(fmt, (1<<exp)-1)\n break\n except struct.error:\n pass\n lh = (-(1<<exp), 1<<exp) if exp & 1 else (0, 1<<exp)\n return lh\n\nfmtdict = {\n '':NATIVE,\n '@':NATIVE,\n '<':STANDARD,\n '>':STANDARD,\n '=':STANDARD,\n '!':STANDARD\n}\n\nif struct:\n for fmt in fmtdict['@']:\n fmtdict['@'][fmt] = native_type_range(fmt)\n\nMEMORYVIEW = NATIVE.copy()\nARRAY = NATIVE.copy()\nfor k in NATIVE:\n if not k in \"bBhHiIlLfd\":\n del ARRAY[k]\n\nBYTEFMT = NATIVE.copy()\nfor k in NATIVE:\n if not k in \"Bbc\":\n del BYTEFMT[k]\n\nfmtdict['m'] = MEMORYVIEW\nfmtdict['@m'] = MEMORYVIEW\nfmtdict['a'] = ARRAY\nfmtdict['b'] = BYTEFMT\nfmtdict['@b'] = BYTEFMT\n\n# Capabilities of the test objects:\nMODE = 0\nMULT = 1\ncap = { # format chars # multiplier\n 'ndarray': (['', '@', '<', '>', '=', '!'], ['', '1', '2', '3']),\n 'array': (['a'], ['']),\n 'numpy': ([''], ['']),\n 'memoryview': (['@m', 'm'], ['']),\n 'bytefmt': (['@b', 'b'], ['']),\n}\n\ndef randrange_fmt(mode, char, obj):\n \"\"\"Return random item for a type specified by a mode and a single\n format character.\"\"\"\n x = randrange(*fmtdict[mode][char])\n if char == 'c':\n x = bytes(chr(x), 'latin1')\n if char == '?':\n x = bool(x)\n if char == 'f' or char == 'd':\n x = struct.pack(char, x)\n x = struct.unpack(char, x)[0]\n if obj == 'numpy' and x == b'\\x00':\n # http://projects.scipy.org/numpy/ticket/1925\n x = b'\\x01'\n return x\n\ndef gen_item(fmt, obj):\n \"\"\"Return single random item.\"\"\"\n mode, chars = fmt.split('#')\n x = []\n for c in chars:\n x.append(randrange_fmt(mode, c, obj))\n return x[0] if len(x) == 1 else tuple(x)\n\ndef gen_items(n, fmt, obj):\n \"\"\"Return a list of random items (or a scalar).\"\"\"\n if n == 0:\n return gen_item(fmt, obj)\n lst = [0] * n\n for i in range(n):\n lst[i] = gen_item(fmt, obj)\n return lst\n\ndef struct_items(n, obj):\n mode = choice(cap[obj][MODE])\n xfmt = mode + '#'\n fmt = mode.strip('amb')\n nmemb = randrange(2, 10) # number of struct members\n for _ in range(nmemb):\n char = choice(tuple(fmtdict[mode]))\n multiplier = choice(cap[obj][MULT])\n xfmt += (char * int(multiplier if multiplier else 1))\n fmt += (multiplier + char)\n items = gen_items(n, xfmt, obj)\n item = gen_item(xfmt, obj)\n return fmt, items, item\n\ndef randitems(n, obj='ndarray', mode=None, char=None):\n \"\"\"Return random format, items, item.\"\"\"\n if mode is None:\n mode = choice(cap[obj][MODE])\n if char is None:\n char = choice(tuple(fmtdict[mode]))\n multiplier = choice(cap[obj][MULT])\n fmt = mode + '#' + char * int(multiplier if multiplier else 1)\n items = gen_items(n, fmt, obj)\n item = gen_item(fmt, obj)\n fmt = mode.strip('amb') + multiplier + char\n return fmt, items, item\n\ndef iter_mode(n, obj='ndarray'):\n \"\"\"Iterate through supported mode/char combinations.\"\"\"\n for mode in cap[obj][MODE]:\n for char in fmtdict[mode]:\n yield randitems(n, obj, mode, char)\n\ndef iter_format(nitems, testobj='ndarray'):\n \"\"\"Yield (format, items, item) for all possible modes and format\n characters plus one random compound format string.\"\"\"\n for t in iter_mode(nitems, testobj):\n yield t\n if testobj != 'ndarray':\n return\n yield struct_items(nitems, testobj)\n\n\ndef is_byte_format(fmt):\n return 'c' in fmt or 'b' in fmt or 'B' in fmt\n\ndef is_memoryview_format(fmt):\n \"\"\"format suitable for memoryview\"\"\"\n x = len(fmt)\n return ((x == 1 or (x == 2 and fmt[0] == '@')) and\n fmt[x-1] in MEMORYVIEW)\n\nNON_BYTE_FORMAT = [c for c in fmtdict['@'] if not is_byte_format(c)]\n\n\n# ======================================================================\n# Multi-dimensional tolist(), slicing and slice assignments\n# ======================================================================\n\ndef atomp(lst):\n \"\"\"Tuple items (representing structs) are regarded as atoms.\"\"\"\n return not isinstance(lst, list)\n\ndef listp(lst):\n return isinstance(lst, list)\n\ndef prod(lst):\n \"\"\"Product of list elements.\"\"\"\n if len(lst) == 0:\n return 0\n x = lst[0]\n for v in lst[1:]:\n x *= v\n return x\n\ndef strides_from_shape(ndim, shape, itemsize, layout):\n \"\"\"Calculate strides of a contiguous array. Layout is 'C' or\n 'F' (Fortran).\"\"\"\n if ndim == 0:\n return ()\n if layout == 'C':\n strides = list(shape[1:]) + [itemsize]\n for i in range(ndim-2, -1, -1):\n strides[i] *= strides[i+1]\n else:\n strides = [itemsize] + list(shape[:-1])\n for i in range(1, ndim):\n strides[i] *= strides[i-1]\n return strides\n\ndef _ca(items, s):\n \"\"\"Convert flat item list to the nested list representation of a\n multidimensional C array with shape 's'.\"\"\"\n if atomp(items):\n return items\n if len(s) == 0:\n return items[0]\n lst = [0] * s[0]\n stride = len(items) // s[0] if s[0] else 0\n for i in range(s[0]):\n start = i*stride\n lst[i] = _ca(items[start:start+stride], s[1:])\n return lst\n\ndef _fa(items, s):\n \"\"\"Convert flat item list to the nested list representation of a\n multidimensional Fortran array with shape 's'.\"\"\"\n if atomp(items):\n return items\n if len(s) == 0:\n return items[0]\n lst = [0] * s[0]\n stride = s[0]\n for i in range(s[0]):\n lst[i] = _fa(items[i::stride], s[1:])\n return lst\n\ndef carray(items, shape):\n if listp(items) and not 0 in shape and prod(shape) != len(items):\n raise ValueError(\"prod(shape) != len(items)\")\n return _ca(items, shape)\n\ndef farray(items, shape):\n if listp(items) and not 0 in shape and prod(shape) != len(items):\n raise ValueError(\"prod(shape) != len(items)\")\n return _fa(items, shape)\n\ndef indices(shape):\n \"\"\"Generate all possible tuples of indices.\"\"\"\n iterables = [range(v) for v in shape]\n return product(*iterables)\n\ndef getindex(ndim, ind, strides):\n \"\"\"Convert multi-dimensional index to the position in the flat list.\"\"\"\n ret = 0\n for i in range(ndim):\n ret += strides[i] * ind[i]\n return ret\n\ndef transpose(src, shape):\n \"\"\"Transpose flat item list that is regarded as a multi-dimensional\n matrix defined by shape: dest...[k][j][i] = src[i][j][k]... \"\"\"\n if not shape:\n return src\n ndim = len(shape)\n sstrides = strides_from_shape(ndim, shape, 1, 'C')\n dstrides = strides_from_shape(ndim, shape[::-1], 1, 'C')\n dest = [0] * len(src)\n for ind in indices(shape):\n fr = getindex(ndim, ind, sstrides)\n to = getindex(ndim, ind[::-1], dstrides)\n dest[to] = src[fr]\n return dest\n\ndef _flatten(lst):\n \"\"\"flatten list\"\"\"\n if lst == []:\n return lst\n if atomp(lst):\n return [lst]\n return _flatten(lst[0]) + _flatten(lst[1:])\n\ndef flatten(lst):\n \"\"\"flatten list or return scalar\"\"\"\n if atomp(lst): # scalar\n return lst\n return _flatten(lst)\n\ndef slice_shape(lst, slices):\n \"\"\"Get the shape of lst after slicing: slices is a list of slice\n objects.\"\"\"\n if atomp(lst):\n return []\n return [len(lst[slices[0]])] + slice_shape(lst[0], slices[1:])\n\ndef multislice(lst, slices):\n \"\"\"Multi-dimensional slicing: slices is a list of slice objects.\"\"\"\n if atomp(lst):\n return lst\n return [multislice(sublst, slices[1:]) for sublst in lst[slices[0]]]\n\ndef m_assign(llst, rlst, lslices, rslices):\n \"\"\"Multi-dimensional slice assignment: llst and rlst are the operands,\n lslices and rslices are lists of slice objects. llst and rlst must\n have the same structure.\n\n For a two-dimensional example, this is not implemented in Python:\n\n llst[0:3:2, 0:3:2] = rlst[1:3:1, 1:3:1]\n\n Instead we write:\n\n lslices = [slice(0,3,2), slice(0,3,2)]\n rslices = [slice(1,3,1), slice(1,3,1)]\n multislice_assign(llst, rlst, lslices, rslices)\n \"\"\"\n if atomp(rlst):\n return rlst\n rlst = [m_assign(l, r, lslices[1:], rslices[1:])\n for l, r in zip(llst[lslices[0]], rlst[rslices[0]])]\n llst[lslices[0]] = rlst\n return llst\n\ndef cmp_structure(llst, rlst, lslices, rslices):\n \"\"\"Compare the structure of llst[lslices] and rlst[rslices].\"\"\"\n lshape = slice_shape(llst, lslices)\n rshape = slice_shape(rlst, rslices)\n if (len(lshape) != len(rshape)):\n return -1\n for i in range(len(lshape)):\n if lshape[i] != rshape[i]:\n return -1\n if lshape[i] == 0:\n return 0\n return 0\n\ndef multislice_assign(llst, rlst, lslices, rslices):\n \"\"\"Return llst after assigning: llst[lslices] = rlst[rslices]\"\"\"\n if cmp_structure(llst, rlst, lslices, rslices) < 0:\n raise ValueError(\"lvalue and rvalue have different structures\")\n return m_assign(llst, rlst, lslices, rslices)\n\n\n# ======================================================================\n# Random structures\n# ======================================================================\n\n#\n# PEP-3118 is very permissive with respect to the contents of a\n# Py_buffer. In particular:\n#\n# - shape can be zero\n# - strides can be any integer, including zero\n# - offset can point to any location in the underlying\n# memory block, provided that it is a multiple of\n# itemsize.\n#\n# The functions in this section test and verify random structures\n# in full generality. A structure is valid iff it fits in the\n# underlying memory block.\n#\n# The structure 't' (short for 'tuple') is fully defined by:\n#\n# t = (memlen, itemsize, ndim, shape, strides, offset)\n#\n\ndef verify_structure(memlen, itemsize, ndim, shape, strides, offset):\n \"\"\"Verify that the parameters represent a valid array within\n the bounds of the allocated memory:\n char *mem: start of the physical memory block\n memlen: length of the physical memory block\n offset: (char *)buf - mem\n \"\"\"\n if offset % itemsize:\n return False\n if offset < 0 or offset+itemsize > memlen:\n return False\n if any(v % itemsize for v in strides):\n return False\n\n if ndim <= 0:\n return ndim == 0 and not shape and not strides\n if 0 in shape:\n return True\n\n imin = sum(strides[j]*(shape[j]-1) for j in range(ndim)\n if strides[j] <= 0)\n imax = sum(strides[j]*(shape[j]-1) for j in range(ndim)\n if strides[j] > 0)\n\n return 0 <= offset+imin and offset+imax+itemsize <= memlen\n\ndef get_item(lst, indices):\n for i in indices:\n lst = lst[i]\n return lst\n\ndef memory_index(indices, t):\n \"\"\"Location of an item in the underlying memory.\"\"\"\n memlen, itemsize, ndim, shape, strides, offset = t\n p = offset\n for i in range(ndim):\n p += strides[i]*indices[i]\n return p\n\ndef is_overlapping(t):\n \"\"\"The structure 't' is overlapping if at least one memory location\n is visited twice while iterating through all possible tuples of\n indices.\"\"\"\n memlen, itemsize, ndim, shape, strides, offset = t\n visited = 1<<memlen\n for ind in indices(shape):\n i = memory_index(ind, t)\n bit = 1<<i\n if visited & bit:\n return True\n visited |= bit\n return False\n\ndef rand_structure(itemsize, valid, maxdim=5, maxshape=16, shape=()):\n \"\"\"Return random structure:\n (memlen, itemsize, ndim, shape, strides, offset)\n If 'valid' is true, the returned structure is valid, otherwise invalid.\n If 'shape' is given, use that instead of creating a random shape.\n \"\"\"\n if not shape:\n ndim = randrange(maxdim+1)\n if (ndim == 0):\n if valid:\n return itemsize, itemsize, ndim, (), (), 0\n else:\n nitems = randrange(1, 16+1)\n memlen = nitems * itemsize\n offset = -itemsize if randrange(2) == 0 else memlen\n return memlen, itemsize, ndim, (), (), offset\n\n minshape = 2\n n = randrange(100)\n if n >= 95 and valid:\n minshape = 0\n elif n >= 90:\n minshape = 1\n shape = [0] * ndim\n\n for i in range(ndim):\n shape[i] = randrange(minshape, maxshape+1)\n else:\n ndim = len(shape)\n\n maxstride = 5\n n = randrange(100)\n zero_stride = True if n >= 95 and n & 1 else False\n\n strides = [0] * ndim\n strides[ndim-1] = itemsize * randrange(-maxstride, maxstride+1)\n if not zero_stride and strides[ndim-1] == 0:\n strides[ndim-1] = itemsize\n\n for i in range(ndim-2, -1, -1):\n maxstride *= shape[i+1] if shape[i+1] else 1\n if zero_stride:\n strides[i] = itemsize * randrange(-maxstride, maxstride+1)\n else:\n strides[i] = ((1,-1)[randrange(2)] *\n itemsize * randrange(1, maxstride+1))\n\n imin = imax = 0\n if not 0 in shape:\n imin = sum(strides[j]*(shape[j]-1) for j in range(ndim)\n if strides[j] <= 0)\n imax = sum(strides[j]*(shape[j]-1) for j in range(ndim)\n if strides[j] > 0)\n\n nitems = imax - imin\n if valid:\n offset = -imin * itemsize\n memlen = offset + (imax+1) * itemsize\n else:\n memlen = (-imin + imax) * itemsize\n offset = -imin-itemsize if randrange(2) == 0 else memlen\n return memlen, itemsize, ndim, shape, strides, offset\n\ndef randslice_from_slicelen(slicelen, listlen):\n \"\"\"Create a random slice of len slicelen that fits into listlen.\"\"\"\n maxstart = listlen - slicelen\n start = randrange(maxstart+1)\n maxstep = (listlen - start) // slicelen if slicelen else 1\n step = randrange(1, maxstep+1)\n stop = start + slicelen * step\n s = slice(start, stop, step)\n _, _, _, control = slice_indices(s, listlen)\n if control != slicelen:\n raise RuntimeError\n return s\n\ndef randslice_from_shape(ndim, shape):\n \"\"\"Create two sets of slices for an array x with shape 'shape'\n such that shapeof(x[lslices]) == shapeof(x[rslices]).\"\"\"\n lslices = [0] * ndim\n rslices = [0] * ndim\n for n in range(ndim):\n l = shape[n]\n slicelen = randrange(1, l+1) if l > 0 else 0\n lslices[n] = randslice_from_slicelen(slicelen, l)\n rslices[n] = randslice_from_slicelen(slicelen, l)\n return tuple(lslices), tuple(rslices)\n\ndef rand_aligned_slices(maxdim=5, maxshape=16):\n \"\"\"Create (lshape, rshape, tuple(lslices), tuple(rslices)) such that\n shapeof(x[lslices]) == shapeof(y[rslices]), where x is an array\n with shape 'lshape' and y is an array with shape 'rshape'.\"\"\"\n ndim = randrange(1, maxdim+1)\n minshape = 2\n n = randrange(100)\n if n >= 95:\n minshape = 0\n elif n >= 90:\n minshape = 1\n all_random = True if randrange(100) >= 80 else False\n lshape = [0]*ndim; rshape = [0]*ndim\n lslices = [0]*ndim; rslices = [0]*ndim\n\n for n in range(ndim):\n small = randrange(minshape, maxshape+1)\n big = randrange(minshape, maxshape+1)\n if big < small:\n big, small = small, big\n\n # Create a slice that fits the smaller value.\n if all_random:\n start = randrange(-small, small+1)\n stop = randrange(-small, small+1)\n step = (1,-1)[randrange(2)] * randrange(1, small+2)\n s_small = slice(start, stop, step)\n _, _, _, slicelen = slice_indices(s_small, small)\n else:\n slicelen = randrange(1, small+1) if small > 0 else 0\n s_small = randslice_from_slicelen(slicelen, small)\n\n # Create a slice of the same length for the bigger value.\n s_big = randslice_from_slicelen(slicelen, big)\n if randrange(2) == 0:\n rshape[n], lshape[n] = big, small\n rslices[n], lslices[n] = s_big, s_small\n else:\n rshape[n], lshape[n] = small, big\n rslices[n], lslices[n] = s_small, s_big\n\n return lshape, rshape, tuple(lslices), tuple(rslices)\n\ndef randitems_from_structure(fmt, t):\n \"\"\"Return a list of random items for structure 't' with format\n 'fmtchar'.\"\"\"\n memlen, itemsize, _, _, _, _ = t\n return gen_items(memlen//itemsize, '#'+fmt, 'numpy')\n\ndef ndarray_from_structure(items, fmt, t, flags=0):\n \"\"\"Return ndarray from the tuple returned by rand_structure()\"\"\"\n memlen, itemsize, ndim, shape, strides, offset = t\n return ndarray(items, shape=shape, strides=strides, format=fmt,\n offset=offset, flags=ND_WRITABLE|flags)\n\ndef numpy_array_from_structure(items, fmt, t):\n \"\"\"Return numpy_array from the tuple returned by rand_structure()\"\"\"\n memlen, itemsize, ndim, shape, strides, offset = t\n buf = bytearray(memlen)\n for j, v in enumerate(items):\n struct.pack_into(fmt, buf, j*itemsize, v)\n return numpy_array(buffer=buf, shape=shape, strides=strides,\n dtype=fmt, offset=offset)\n\n\n# ======================================================================\n# memoryview casts\n# ======================================================================\n\ndef cast_items(exporter, fmt, itemsize, shape=None):\n \"\"\"Interpret the raw memory of 'exporter' as a list of items with\n size 'itemsize'. If shape=None, the new structure is assumed to\n be 1-D with n * itemsize = bytelen. If shape is given, the usual\n constraint for contiguous arrays prod(shape) * itemsize = bytelen\n applies. On success, return (items, shape). If the constraints\n cannot be met, return (None, None). If a chunk of bytes is interpreted\n as NaN as a result of float conversion, return ('nan', None).\"\"\"\n bytelen = exporter.nbytes\n if shape:\n if prod(shape) * itemsize != bytelen:\n return None, shape\n elif shape == []:\n if exporter.ndim == 0 or itemsize != bytelen:\n return None, shape\n else:\n n, r = divmod(bytelen, itemsize)\n shape = [n]\n if r != 0:\n return None, shape\n\n mem = exporter.tobytes()\n byteitems = [mem[i:i+itemsize] for i in range(0, len(mem), itemsize)]\n\n items = []\n for v in byteitems:\n item = struct.unpack(fmt, v)[0]\n if item != item:\n return 'nan', shape\n items.append(item)\n\n return (items, shape) if shape != [] else (items[0], shape)\n\ndef gencastshapes():\n \"\"\"Generate shapes to test casting.\"\"\"\n for n in range(32):\n yield [n]\n ndim = randrange(4, 6)\n minshape = 1 if randrange(100) > 80 else 2\n yield [randrange(minshape, 5) for _ in range(ndim)]\n ndim = randrange(2, 4)\n minshape = 1 if randrange(100) > 80 else 2\n yield [randrange(minshape, 5) for _ in range(ndim)]\n\n\n# ======================================================================\n# Actual tests\n# ======================================================================\n\ndef genslices(n):\n \"\"\"Generate all possible slices for a single dimension.\"\"\"\n return product(range(-n, n+1), range(-n, n+1), range(-n, n+1))\n\ndef genslices_ndim(ndim, shape):\n \"\"\"Generate all possible slice tuples for 'shape'.\"\"\"\n iterables = [genslices(shape[n]) for n in range(ndim)]\n return product(*iterables)\n\ndef rslice(n, allow_empty=False):\n \"\"\"Generate random slice for a single dimension of length n.\n If zero=True, the slices may be empty, otherwise they will\n be non-empty.\"\"\"\n minlen = 0 if allow_empty or n == 0 else 1\n slicelen = randrange(minlen, n+1)\n return randslice_from_slicelen(slicelen, n)\n\ndef rslices(n, allow_empty=False):\n \"\"\"Generate random slices for a single dimension.\"\"\"\n for _ in range(5):\n yield rslice(n, allow_empty)\n\ndef rslices_ndim(ndim, shape, iterations=5):\n \"\"\"Generate random slice tuples for 'shape'.\"\"\"\n # non-empty slices\n for _ in range(iterations):\n yield tuple(rslice(shape[n]) for n in range(ndim))\n # possibly empty slices\n for _ in range(iterations):\n yield tuple(rslice(shape[n], allow_empty=True) for n in range(ndim))\n # invalid slices\n yield tuple(slice(0,1,0) for _ in range(ndim))\n\ndef rpermutation(iterable, r=None):\n pool = tuple(iterable)\n r = len(pool) if r is None else r\n yield tuple(sample(pool, r))\n\ndef ndarray_print(nd):\n \"\"\"Print ndarray for debugging.\"\"\"\n try:\n x = nd.tolist()\n except (TypeError, NotImplementedError):\n x = nd.tobytes()\n if isinstance(nd, ndarray):\n offset = nd.offset\n flags = nd.flags\n else:\n offset = 'unknown'\n flags = 'unknown'\n print(\"ndarray(%s, shape=%s, strides=%s, suboffsets=%s, offset=%s, \"\n \"format='%s', itemsize=%s, flags=%s)\" %\n (x, nd.shape, nd.strides, nd.suboffsets, offset,\n nd.format, nd.itemsize, flags))\n sys.stdout.flush()\n\n\nITERATIONS = 100\nMAXDIM = 5\nMAXSHAPE = 10\n\nif SHORT_TEST:\n ITERATIONS = 10\n MAXDIM = 3\n MAXSHAPE = 4\n genslices = rslices\n genslices_ndim = rslices_ndim\n permutations = rpermutation\n\n\[email protected](struct, 'struct module required for this test.')\[email protected](ndarray, 'ndarray object required for this test')\nclass TestBufferProtocol(unittest.TestCase):\n\n def setUp(self):\n # The suboffsets tests need sizeof(void *).\n self.sizeof_void_p = get_sizeof_void_p()\n\n def verify(self, result, obj=-1,\n itemsize={1}, fmt=-1, readonly={1},\n ndim={1}, shape=-1, strides=-1,\n lst=-1, sliced=False, cast=False):\n # Verify buffer contents against expected values. Default values\n # are deliberately initialized to invalid types.\n if shape:\n expected_len = prod(shape)*itemsize\n else:\n if not fmt: # array has been implicitly cast to unsigned bytes\n expected_len = len(lst)\n else: # ndim = 0\n expected_len = itemsize\n\n # Reconstruct suboffsets from strides. Support for slicing\n # could be added, but is currently only needed for test_getbuf().\n suboffsets = ()\n if result.suboffsets:\n self.assertGreater(ndim, 0)\n\n suboffset0 = 0\n for n in range(1, ndim):\n if shape[n] == 0:\n break\n if strides[n] <= 0:\n suboffset0 += -strides[n] * (shape[n]-1)\n\n suboffsets = [suboffset0] + [-1 for v in range(ndim-1)]\n\n # Not correct if slicing has occurred in the first dimension.\n stride0 = self.sizeof_void_p\n if strides[0] < 0:\n stride0 = -stride0\n strides = [stride0] + list(strides[1:])\n\n self.assertIs(result.obj, obj)\n self.assertEqual(result.nbytes, expected_len)\n self.assertEqual(result.itemsize, itemsize)\n self.assertEqual(result.format, fmt)\n self.assertEqual(result.readonly, readonly)\n self.assertEqual(result.ndim, ndim)\n self.assertEqual(result.shape, tuple(shape))\n if not (sliced and suboffsets):\n self.assertEqual(result.strides, tuple(strides))\n self.assertEqual(result.suboffsets, tuple(suboffsets))\n\n if isinstance(result, ndarray) or is_memoryview_format(fmt):\n rep = result.tolist() if fmt else result.tobytes()\n self.assertEqual(rep, lst)\n\n if not fmt: # array has been cast to unsigned bytes,\n return # the remaining tests won't work.\n\n # PyBuffer_GetPointer() is the definition how to access an item.\n # If PyBuffer_GetPointer(indices) is correct for all possible\n # combinations of indices, the buffer is correct.\n #\n # Also test tobytes() against the flattened 'lst', with all items\n # packed to bytes.\n if not cast: # casts chop up 'lst' in different ways\n b = bytearray()\n buf_err = None\n for ind in indices(shape):\n try:\n item1 = get_pointer(result, ind)\n item2 = get_item(lst, ind)\n if isinstance(item2, tuple):\n x = struct.pack(fmt, *item2)\n else:\n x = struct.pack(fmt, item2)\n b.extend(x)\n except BufferError:\n buf_err = True # re-exporter does not provide full buffer\n break\n self.assertEqual(item1, item2)\n\n if not buf_err:\n # test tobytes()\n self.assertEqual(result.tobytes(), b)\n\n # lst := expected multi-dimensional logical representation\n # flatten(lst) := elements in C-order\n ff = fmt if fmt else 'B'\n flattened = flatten(lst)\n\n # Rules for 'A': if the array is already contiguous, return\n # the array unaltered. Otherwise, return a contiguous 'C'\n # representation.\n for order in ['C', 'F', 'A']:\n expected = result\n if order == 'F':\n if not is_contiguous(result, 'A') or \\\n is_contiguous(result, 'C'):\n # For constructing the ndarray, convert the\n # flattened logical representation to Fortran order.\n trans = transpose(flattened, shape)\n expected = ndarray(trans, shape=shape, format=ff,\n flags=ND_FORTRAN)\n else: # 'C', 'A'\n if not is_contiguous(result, 'A') or \\\n is_contiguous(result, 'F') and order == 'C':\n # The flattened list is already in C-order.\n expected = ndarray(flattened, shape=shape, format=ff)\n\n contig = get_contiguous(result, PyBUF_READ, order)\n self.assertEqual(contig.tobytes(), b)\n self.assertTrue(cmp_contig(contig, expected))\n\n if ndim == 0:\n continue\n\n nmemb = len(flattened)\n ro = 0 if readonly else ND_WRITABLE\n\n ### See comment in test_py_buffer_to_contiguous for an\n ### explanation why these tests are valid.\n\n # To 'C'\n contig = py_buffer_to_contiguous(result, 'C', PyBUF_FULL_RO)\n self.assertEqual(len(contig), nmemb * itemsize)\n initlst = [struct.unpack_from(fmt, contig, n*itemsize)\n for n in range(nmemb)]\n if len(initlst[0]) == 1:\n initlst = [v[0] for v in initlst]\n\n y = ndarray(initlst, shape=shape, flags=ro, format=fmt)\n self.assertEqual(memoryview(y), memoryview(result))\n\n # To 'F'\n contig = py_buffer_to_contiguous(result, 'F', PyBUF_FULL_RO)\n self.assertEqual(len(contig), nmemb * itemsize)\n initlst = [struct.unpack_from(fmt, contig, n*itemsize)\n for n in range(nmemb)]\n if len(initlst[0]) == 1:\n initlst = [v[0] for v in initlst]\n\n y = ndarray(initlst, shape=shape, flags=ro|ND_FORTRAN,\n format=fmt)\n self.assertEqual(memoryview(y), memoryview(result))\n\n # To 'A'\n contig = py_buffer_to_contiguous(result, 'A', PyBUF_FULL_RO)\n self.assertEqual(len(contig), nmemb * itemsize)\n initlst = [struct.unpack_from(fmt, contig, n*itemsize)\n for n in range(nmemb)]\n if len(initlst[0]) == 1:\n initlst = [v[0] for v in initlst]\n\n f = ND_FORTRAN if is_contiguous(result, 'F') else 0\n y = ndarray(initlst, shape=shape, flags=f|ro, format=fmt)\n self.assertEqual(memoryview(y), memoryview(result))\n\n if is_memoryview_format(fmt):\n try:\n m = memoryview(result)\n except BufferError: # re-exporter does not provide full information\n return\n ex = result.obj if isinstance(result, memoryview) else result\n self.assertIs(m.obj, ex)\n self.assertEqual(m.nbytes, expected_len)\n self.assertEqual(m.itemsize, itemsize)\n self.assertEqual(m.format, fmt)\n self.assertEqual(m.readonly, readonly)\n self.assertEqual(m.ndim, ndim)\n self.assertEqual(m.shape, tuple(shape))\n if not (sliced and suboffsets):\n self.assertEqual(m.strides, tuple(strides))\n self.assertEqual(m.suboffsets, tuple(suboffsets))\n\n n = 1 if ndim == 0 else len(lst)\n self.assertEqual(len(m), n)\n\n rep = result.tolist() if fmt else result.tobytes()\n self.assertEqual(rep, lst)\n self.assertEqual(m, result)\n\n def verify_getbuf(self, orig_ex, ex, req, sliced=False):\n def simple_fmt(ex):\n return ex.format == '' or ex.format == 'B'\n def match(req, flag):\n return ((req&flag) == flag)\n\n if (# writable request to read-only exporter\n (ex.readonly and match(req, PyBUF_WRITABLE)) or\n # cannot match explicit contiguity request\n (match(req, PyBUF_C_CONTIGUOUS) and not ex.c_contiguous) or\n (match(req, PyBUF_F_CONTIGUOUS) and not ex.f_contiguous) or\n (match(req, PyBUF_ANY_CONTIGUOUS) and not ex.contiguous) or\n # buffer needs suboffsets\n (not match(req, PyBUF_INDIRECT) and ex.suboffsets) or\n # buffer without strides must be C-contiguous\n (not match(req, PyBUF_STRIDES) and not ex.c_contiguous) or\n # PyBUF_SIMPLE|PyBUF_FORMAT and PyBUF_WRITABLE|PyBUF_FORMAT\n (not match(req, PyBUF_ND) and match(req, PyBUF_FORMAT))):\n\n self.assertRaises(BufferError, ndarray, ex, getbuf=req)\n return\n\n if isinstance(ex, ndarray) or is_memoryview_format(ex.format):\n lst = ex.tolist()\n else:\n nd = ndarray(ex, getbuf=PyBUF_FULL_RO)\n lst = nd.tolist()\n\n # The consumer may have requested default values or a NULL format.\n ro = 0 if match(req, PyBUF_WRITABLE) else ex.readonly\n fmt = ex.format\n itemsize = ex.itemsize\n ndim = ex.ndim\n if not match(req, PyBUF_FORMAT):\n # itemsize refers to the original itemsize before the cast.\n # The equality product(shape) * itemsize = len still holds.\n # The equality calcsize(format) = itemsize does _not_ hold.\n fmt = ''\n lst = orig_ex.tobytes() # Issue 12834\n if not match(req, PyBUF_ND):\n ndim = 1\n shape = orig_ex.shape if match(req, PyBUF_ND) else ()\n strides = orig_ex.strides if match(req, PyBUF_STRIDES) else ()\n\n nd = ndarray(ex, getbuf=req)\n self.verify(nd, obj=ex,\n itemsize=itemsize, fmt=fmt, readonly=ro,\n ndim=ndim, shape=shape, strides=strides,\n lst=lst, sliced=sliced)\n\n def test_ndarray_getbuf(self):\n requests = (\n # distinct flags\n PyBUF_INDIRECT, PyBUF_STRIDES, PyBUF_ND, PyBUF_SIMPLE,\n PyBUF_C_CONTIGUOUS, PyBUF_F_CONTIGUOUS, PyBUF_ANY_CONTIGUOUS,\n # compound requests\n PyBUF_FULL, PyBUF_FULL_RO,\n PyBUF_RECORDS, PyBUF_RECORDS_RO,\n PyBUF_STRIDED, PyBUF_STRIDED_RO,\n PyBUF_CONTIG, PyBUF_CONTIG_RO,\n )\n # items and format\n items_fmt = (\n ([True if x % 2 else False for x in range(12)], '?'),\n ([1,2,3,4,5,6,7,8,9,10,11,12], 'b'),\n ([1,2,3,4,5,6,7,8,9,10,11,12], 'B'),\n ([(2**31-x) if x % 2 else (-2**31+x) for x in range(12)], 'l')\n )\n # shape, strides, offset\n structure = (\n ([], [], 0),\n ([12], [], 0),\n ([12], [-1], 11),\n ([6], [2], 0),\n ([6], [-2], 11),\n ([3, 4], [], 0),\n ([3, 4], [-4, -1], 11),\n ([2, 2], [4, 1], 4),\n ([2, 2], [-4, -1], 8)\n )\n # ndarray creation flags\n ndflags = (\n 0, ND_WRITABLE, ND_FORTRAN, ND_FORTRAN|ND_WRITABLE,\n ND_PIL, ND_PIL|ND_WRITABLE\n )\n # flags that can actually be used as flags\n real_flags = (0, PyBUF_WRITABLE, PyBUF_FORMAT,\n PyBUF_WRITABLE|PyBUF_FORMAT)\n\n for items, fmt in items_fmt:\n itemsize = struct.calcsize(fmt)\n for shape, strides, offset in structure:\n strides = [v * itemsize for v in strides]\n offset *= itemsize\n for flags in ndflags:\n\n if strides and (flags&ND_FORTRAN):\n continue\n if not shape and (flags&ND_PIL):\n continue\n\n _items = items if shape else items[0]\n ex1 = ndarray(_items, format=fmt, flags=flags,\n shape=shape, strides=strides, offset=offset)\n ex2 = ex1[::-2] if shape else None\n\n m1 = memoryview(ex1)\n if ex2:\n m2 = memoryview(ex2)\n if ex1.ndim == 0 or (ex1.ndim == 1 and shape and strides):\n self.assertEqual(m1, ex1)\n if ex2 and ex2.ndim == 1 and shape and strides:\n self.assertEqual(m2, ex2)\n\n for req in requests:\n for bits in real_flags:\n self.verify_getbuf(ex1, ex1, req|bits)\n self.verify_getbuf(ex1, m1, req|bits)\n if ex2:\n self.verify_getbuf(ex2, ex2, req|bits,\n sliced=True)\n self.verify_getbuf(ex2, m2, req|bits,\n sliced=True)\n\n items = [1,2,3,4,5,6,7,8,9,10,11,12]\n\n # ND_GETBUF_FAIL\n ex = ndarray(items, shape=[12], flags=ND_GETBUF_FAIL)\n self.assertRaises(BufferError, ndarray, ex)\n\n # Request complex structure from a simple exporter. In this\n # particular case the test object is not PEP-3118 compliant.\n base = ndarray([9], [1])\n ex = ndarray(base, getbuf=PyBUF_SIMPLE)\n self.assertRaises(BufferError, ndarray, ex, getbuf=PyBUF_WRITABLE)\n self.assertRaises(BufferError, ndarray, ex, getbuf=PyBUF_ND)\n self.assertRaises(BufferError, ndarray, ex, getbuf=PyBUF_STRIDES)\n self.assertRaises(BufferError, ndarray, ex, getbuf=PyBUF_C_CONTIGUOUS)\n self.assertRaises(BufferError, ndarray, ex, getbuf=PyBUF_F_CONTIGUOUS)\n self.assertRaises(BufferError, ndarray, ex, getbuf=PyBUF_ANY_CONTIGUOUS)\n nd = ndarray(ex, getbuf=PyBUF_SIMPLE)\n\n def test_ndarray_exceptions(self):\n nd = ndarray([9], [1])\n ndm = ndarray([9], [1], flags=ND_VAREXPORT)\n\n # Initialization of a new ndarray or mutation of an existing array.\n for c in (ndarray, nd.push, ndm.push):\n # Invalid types.\n self.assertRaises(TypeError, c, {1,2,3})\n self.assertRaises(TypeError, c, [1,2,'3'])\n self.assertRaises(TypeError, c, [1,2,(3,4)])\n self.assertRaises(TypeError, c, [1,2,3], shape={3})\n self.assertRaises(TypeError, c, [1,2,3], shape=[3], strides={1})\n self.assertRaises(TypeError, c, [1,2,3], shape=[3], offset=[])\n self.assertRaises(TypeError, c, [1], shape=[1], format={})\n self.assertRaises(TypeError, c, [1], shape=[1], flags={})\n self.assertRaises(TypeError, c, [1], shape=[1], getbuf={})\n\n # ND_FORTRAN flag is only valid without strides.\n self.assertRaises(TypeError, c, [1], shape=[1], strides=[1],\n flags=ND_FORTRAN)\n\n # ND_PIL flag is only valid with ndim > 0.\n self.assertRaises(TypeError, c, [1], shape=[], flags=ND_PIL)\n\n # Invalid items.\n self.assertRaises(ValueError, c, [], shape=[1])\n self.assertRaises(ValueError, c, ['XXX'], shape=[1], format=\"L\")\n # Invalid combination of items and format.\n self.assertRaises(struct.error, c, [1000], shape=[1], format=\"B\")\n self.assertRaises(ValueError, c, [1,(2,3)], shape=[2], format=\"B\")\n self.assertRaises(ValueError, c, [1,2,3], shape=[3], format=\"QL\")\n\n # Invalid ndim.\n n = ND_MAX_NDIM+1\n self.assertRaises(ValueError, c, [1]*n, shape=[1]*n)\n\n # Invalid shape.\n self.assertRaises(ValueError, c, [1], shape=[-1])\n self.assertRaises(ValueError, c, [1,2,3], shape=['3'])\n self.assertRaises(OverflowError, c, [1], shape=[2**128])\n # prod(shape) * itemsize != len(items)\n self.assertRaises(ValueError, c, [1,2,3,4,5], shape=[2,2], offset=3)\n\n # Invalid strides.\n self.assertRaises(ValueError, c, [1,2,3], shape=[3], strides=['1'])\n self.assertRaises(OverflowError, c, [1], shape=[1],\n strides=[2**128])\n\n # Invalid combination of strides and shape.\n self.assertRaises(ValueError, c, [1,2], shape=[2,1], strides=[1])\n # Invalid combination of strides and format.\n self.assertRaises(ValueError, c, [1,2,3,4], shape=[2], strides=[3],\n format=\"L\")\n\n # Invalid offset.\n self.assertRaises(ValueError, c, [1,2,3], shape=[3], offset=4)\n self.assertRaises(ValueError, c, [1,2,3], shape=[1], offset=3,\n format=\"L\")\n\n # Invalid format.\n self.assertRaises(ValueError, c, [1,2,3], shape=[3], format=\"\")\n self.assertRaises(struct.error, c, [(1,2,3)], shape=[1],\n format=\"@#$\")\n\n # Striding out of the memory bounds.\n items = [1,2,3,4,5,6,7,8,9,10]\n self.assertRaises(ValueError, c, items, shape=[2,3],\n strides=[-3, -2], offset=5)\n\n # Constructing consumer: format argument invalid.\n self.assertRaises(TypeError, c, bytearray(), format=\"Q\")\n\n # Constructing original base object: getbuf argument invalid.\n self.assertRaises(TypeError, c, [1], shape=[1], getbuf=PyBUF_FULL)\n\n # Shape argument is mandatory for original base objects.\n self.assertRaises(TypeError, c, [1])\n\n\n # PyBUF_WRITABLE request to read-only provider.\n self.assertRaises(BufferError, ndarray, b'123', getbuf=PyBUF_WRITABLE)\n\n # ND_VAREXPORT can only be specified during construction.\n nd = ndarray([9], [1], flags=ND_VAREXPORT)\n self.assertRaises(ValueError, nd.push, [1], [1], flags=ND_VAREXPORT)\n\n # Invalid operation for consumers: push/pop\n nd = ndarray(b'123')\n self.assertRaises(BufferError, nd.push, [1], [1])\n self.assertRaises(BufferError, nd.pop)\n\n # ND_VAREXPORT not set: push/pop fail with exported buffers\n nd = ndarray([9], [1])\n nd.push([1], [1])\n m = memoryview(nd)\n self.assertRaises(BufferError, nd.push, [1], [1])\n self.assertRaises(BufferError, nd.pop)\n m.release()\n nd.pop()\n\n # Single remaining buffer: pop fails\n self.assertRaises(BufferError, nd.pop)\n del nd\n\n # get_pointer()\n self.assertRaises(TypeError, get_pointer, {}, [1,2,3])\n self.assertRaises(TypeError, get_pointer, b'123', {})\n\n nd = ndarray(list(range(100)), shape=[1]*100)\n self.assertRaises(ValueError, get_pointer, nd, [5])\n\n nd = ndarray(list(range(12)), shape=[3,4])\n self.assertRaises(ValueError, get_pointer, nd, [2,3,4])\n self.assertRaises(ValueError, get_pointer, nd, [3,3])\n self.assertRaises(ValueError, get_pointer, nd, [-3,3])\n self.assertRaises(OverflowError, get_pointer, nd, [1<<64,3])\n\n # tolist() needs format\n ex = ndarray([1,2,3], shape=[3], format='L')\n nd = ndarray(ex, getbuf=PyBUF_SIMPLE)\n self.assertRaises(ValueError, nd.tolist)\n\n # memoryview_from_buffer()\n ex1 = ndarray([1,2,3], shape=[3], format='L')\n ex2 = ndarray(ex1)\n nd = ndarray(ex2)\n self.assertRaises(TypeError, nd.memoryview_from_buffer)\n\n nd = ndarray([(1,)*200], shape=[1], format='L'*200)\n self.assertRaises(TypeError, nd.memoryview_from_buffer)\n\n n = ND_MAX_NDIM\n nd = ndarray(list(range(n)), shape=[1]*n)\n self.assertRaises(ValueError, nd.memoryview_from_buffer)\n\n # get_contiguous()\n nd = ndarray([1], shape=[1])\n self.assertRaises(TypeError, get_contiguous, 1, 2, 3, 4, 5)\n self.assertRaises(TypeError, get_contiguous, nd, \"xyz\", 'C')\n self.assertRaises(OverflowError, get_contiguous, nd, 2**64, 'C')\n self.assertRaises(TypeError, get_contiguous, nd, PyBUF_READ, 961)\n self.assertRaises(UnicodeEncodeError, get_contiguous, nd, PyBUF_READ,\n '\\u2007')\n self.assertRaises(ValueError, get_contiguous, nd, PyBUF_READ, 'Z')\n self.assertRaises(ValueError, get_contiguous, nd, 255, 'A')\n\n # cmp_contig()\n nd = ndarray([1], shape=[1])\n self.assertRaises(TypeError, cmp_contig, 1, 2, 3, 4, 5)\n self.assertRaises(TypeError, cmp_contig, {}, nd)\n self.assertRaises(TypeError, cmp_contig, nd, {})\n\n # is_contiguous()\n nd = ndarray([1], shape=[1])\n self.assertRaises(TypeError, is_contiguous, 1, 2, 3, 4, 5)\n self.assertRaises(TypeError, is_contiguous, {}, 'A')\n self.assertRaises(TypeError, is_contiguous, nd, 201)\n\n def test_ndarray_linked_list(self):\n for perm in permutations(range(5)):\n m = [0]*5\n nd = ndarray([1,2,3], shape=[3], flags=ND_VAREXPORT)\n m[0] = memoryview(nd)\n\n for i in range(1, 5):\n nd.push([1,2,3], shape=[3])\n m[i] = memoryview(nd)\n\n for i in range(5):\n m[perm[i]].release()\n\n self.assertRaises(BufferError, nd.pop)\n del nd\n\n def test_ndarray_format_scalar(self):\n # ndim = 0: scalar\n for fmt, scalar, _ in iter_format(0):\n itemsize = struct.calcsize(fmt)\n nd = ndarray(scalar, shape=(), format=fmt)\n self.verify(nd, obj=None,\n itemsize=itemsize, fmt=fmt, readonly=1,\n ndim=0, shape=(), strides=(),\n lst=scalar)\n\n def test_ndarray_format_shape(self):\n # ndim = 1, shape = [n]\n nitems = randrange(1, 10)\n for fmt, items, _ in iter_format(nitems):\n itemsize = struct.calcsize(fmt)\n for flags in (0, ND_PIL):\n nd = ndarray(items, shape=[nitems], format=fmt, flags=flags)\n self.verify(nd, obj=None,\n itemsize=itemsize, fmt=fmt, readonly=1,\n ndim=1, shape=(nitems,), strides=(itemsize,),\n lst=items)\n\n def test_ndarray_format_strides(self):\n # ndim = 1, strides\n nitems = randrange(1, 30)\n for fmt, items, _ in iter_format(nitems):\n itemsize = struct.calcsize(fmt)\n for step in range(-5, 5):\n if step == 0:\n continue\n\n shape = [len(items[::step])]\n strides = [step*itemsize]\n offset = itemsize*(nitems-1) if step < 0 else 0\n\n for flags in (0, ND_PIL):\n nd = ndarray(items, shape=shape, strides=strides,\n format=fmt, offset=offset, flags=flags)\n self.verify(nd, obj=None,\n itemsize=itemsize, fmt=fmt, readonly=1,\n ndim=1, shape=shape, strides=strides,\n lst=items[::step])\n\n def test_ndarray_fortran(self):\n items = [1,2,3,4,5,6,7,8,9,10,11,12]\n ex = ndarray(items, shape=(3, 4), strides=(1, 3))\n nd = ndarray(ex, getbuf=PyBUF_F_CONTIGUOUS|PyBUF_FORMAT)\n self.assertEqual(nd.tolist(), farray(items, (3, 4)))\n\n def test_ndarray_multidim(self):\n for ndim in range(5):\n shape_t = [randrange(2, 10) for _ in range(ndim)]\n nitems = prod(shape_t)\n for shape in permutations(shape_t):\n\n fmt, items, _ = randitems(nitems)\n itemsize = struct.calcsize(fmt)\n\n for flags in (0, ND_PIL):\n if ndim == 0 and flags == ND_PIL:\n continue\n\n # C array\n nd = ndarray(items, shape=shape, format=fmt, flags=flags)\n\n strides = strides_from_shape(ndim, shape, itemsize, 'C')\n lst = carray(items, shape)\n self.verify(nd, obj=None,\n itemsize=itemsize, fmt=fmt, readonly=1,\n ndim=ndim, shape=shape, strides=strides,\n lst=lst)\n\n if is_memoryview_format(fmt):\n # memoryview: reconstruct strides\n ex = ndarray(items, shape=shape, format=fmt)\n nd = ndarray(ex, getbuf=PyBUF_CONTIG_RO|PyBUF_FORMAT)\n self.assertTrue(nd.strides == ())\n mv = nd.memoryview_from_buffer()\n self.verify(mv, obj=None,\n itemsize=itemsize, fmt=fmt, readonly=1,\n ndim=ndim, shape=shape, strides=strides,\n lst=lst)\n\n # Fortran array\n nd = ndarray(items, shape=shape, format=fmt,\n flags=flags|ND_FORTRAN)\n\n strides = strides_from_shape(ndim, shape, itemsize, 'F')\n lst = farray(items, shape)\n self.verify(nd, obj=None,\n itemsize=itemsize, fmt=fmt, readonly=1,\n ndim=ndim, shape=shape, strides=strides,\n lst=lst)\n\n def test_ndarray_index_invalid(self):\n # not writable\n nd = ndarray([1], shape=[1])\n self.assertRaises(TypeError, nd.__setitem__, 1, 8)\n mv = memoryview(nd)\n self.assertEqual(mv, nd)\n self.assertRaises(TypeError, mv.__setitem__, 1, 8)\n\n # cannot be deleted\n nd = ndarray([1], shape=[1], flags=ND_WRITABLE)\n self.assertRaises(TypeError, nd.__delitem__, 1)\n mv = memoryview(nd)\n self.assertEqual(mv, nd)\n self.assertRaises(TypeError, mv.__delitem__, 1)\n\n # overflow\n nd = ndarray([1], shape=[1], flags=ND_WRITABLE)\n self.assertRaises(OverflowError, nd.__getitem__, 1<<64)\n self.assertRaises(OverflowError, nd.__setitem__, 1<<64, 8)\n mv = memoryview(nd)\n self.assertEqual(mv, nd)\n self.assertRaises(IndexError, mv.__getitem__, 1<<64)\n self.assertRaises(IndexError, mv.__setitem__, 1<<64, 8)\n\n # format\n items = [1,2,3,4,5,6,7,8]\n nd = ndarray(items, shape=[len(items)], format=\"B\", flags=ND_WRITABLE)\n self.assertRaises(struct.error, nd.__setitem__, 2, 300)\n self.assertRaises(ValueError, nd.__setitem__, 1, (100, 200))\n mv = memoryview(nd)\n self.assertEqual(mv, nd)\n self.assertRaises(ValueError, mv.__setitem__, 2, 300)\n self.assertRaises(TypeError, mv.__setitem__, 1, (100, 200))\n\n items = [(1,2), (3,4), (5,6)]\n nd = ndarray(items, shape=[len(items)], format=\"LQ\", flags=ND_WRITABLE)\n self.assertRaises(ValueError, nd.__setitem__, 2, 300)\n self.assertRaises(struct.error, nd.__setitem__, 1, (b'\\x001', 200))\n\n def test_ndarray_index_scalar(self):\n # scalar\n nd = ndarray(1, shape=(), flags=ND_WRITABLE)\n mv = memoryview(nd)\n self.assertEqual(mv, nd)\n\n x = nd[()]; self.assertEqual(x, 1)\n x = nd[...]; self.assertEqual(x.tolist(), nd.tolist())\n\n x = mv[()]; self.assertEqual(x, 1)\n x = mv[...]; self.assertEqual(x.tolist(), nd.tolist())\n\n self.assertRaises(TypeError, nd.__getitem__, 0)\n self.assertRaises(TypeError, mv.__getitem__, 0)\n self.assertRaises(TypeError, nd.__setitem__, 0, 8)\n self.assertRaises(TypeError, mv.__setitem__, 0, 8)\n\n self.assertEqual(nd.tolist(), 1)\n self.assertEqual(mv.tolist(), 1)\n\n nd[()] = 9; self.assertEqual(nd.tolist(), 9)\n mv[()] = 9; self.assertEqual(mv.tolist(), 9)\n\n nd[...] = 5; self.assertEqual(nd.tolist(), 5)\n mv[...] = 5; self.assertEqual(mv.tolist(), 5)\n\n def test_ndarray_index_null_strides(self):\n ex = ndarray(list(range(2*4)), shape=[2, 4], flags=ND_WRITABLE)\n nd = ndarray(ex, getbuf=PyBUF_CONTIG)\n\n # Sub-views are only possible for full exporters.\n self.assertRaises(BufferError, nd.__getitem__, 1)\n # Same for slices.\n self.assertRaises(BufferError, nd.__getitem__, slice(3,5,1))\n\n def test_ndarray_index_getitem_single(self):\n # getitem\n for fmt, items, _ in iter_format(5):\n nd = ndarray(items, shape=[5], format=fmt)\n for i in range(-5, 5):\n self.assertEqual(nd[i], items[i])\n\n self.assertRaises(IndexError, nd.__getitem__, -6)\n self.assertRaises(IndexError, nd.__getitem__, 5)\n\n if is_memoryview_format(fmt):\n mv = memoryview(nd)\n self.assertEqual(mv, nd)\n for i in range(-5, 5):\n self.assertEqual(mv[i], items[i])\n\n self.assertRaises(IndexError, mv.__getitem__, -6)\n self.assertRaises(IndexError, mv.__getitem__, 5)\n\n # getitem with null strides\n for fmt, items, _ in iter_format(5):\n ex = ndarray(items, shape=[5], flags=ND_WRITABLE, format=fmt)\n nd = ndarray(ex, getbuf=PyBUF_CONTIG|PyBUF_FORMAT)\n\n for i in range(-5, 5):\n self.assertEqual(nd[i], items[i])\n\n if is_memoryview_format(fmt):\n mv = nd.memoryview_from_buffer()\n self.assertIs(mv.__eq__(nd), NotImplemented)\n for i in range(-5, 5):\n self.assertEqual(mv[i], items[i])\n\n # getitem with null format\n items = [1,2,3,4,5]\n ex = ndarray(items, shape=[5])\n nd = ndarray(ex, getbuf=PyBUF_CONTIG_RO)\n for i in range(-5, 5):\n self.assertEqual(nd[i], items[i])\n\n # getitem with null shape/strides/format\n items = [1,2,3,4,5]\n ex = ndarray(items, shape=[5])\n nd = ndarray(ex, getbuf=PyBUF_SIMPLE)\n\n for i in range(-5, 5):\n self.assertEqual(nd[i], items[i])\n\n def test_ndarray_index_setitem_single(self):\n # assign single value\n for fmt, items, single_item in iter_format(5):\n nd = ndarray(items, shape=[5], format=fmt, flags=ND_WRITABLE)\n for i in range(5):\n items[i] = single_item\n nd[i] = single_item\n self.assertEqual(nd.tolist(), items)\n\n self.assertRaises(IndexError, nd.__setitem__, -6, single_item)\n self.assertRaises(IndexError, nd.__setitem__, 5, single_item)\n\n if not is_memoryview_format(fmt):\n continue\n\n nd = ndarray(items, shape=[5], format=fmt, flags=ND_WRITABLE)\n mv = memoryview(nd)\n self.assertEqual(mv, nd)\n for i in range(5):\n items[i] = single_item\n mv[i] = single_item\n self.assertEqual(mv.tolist(), items)\n\n self.assertRaises(IndexError, mv.__setitem__, -6, single_item)\n self.assertRaises(IndexError, mv.__setitem__, 5, single_item)\n\n\n # assign single value: lobject = robject\n for fmt, items, single_item in iter_format(5):\n nd = ndarray(items, shape=[5], format=fmt, flags=ND_WRITABLE)\n for i in range(-5, 4):\n items[i] = items[i+1]\n nd[i] = nd[i+1]\n self.assertEqual(nd.tolist(), items)\n\n if not is_memoryview_format(fmt):\n continue\n\n nd = ndarray(items, shape=[5], format=fmt, flags=ND_WRITABLE)\n mv = memoryview(nd)\n self.assertEqual(mv, nd)\n for i in range(-5, 4):\n items[i] = items[i+1]\n mv[i] = mv[i+1]\n self.assertEqual(mv.tolist(), items)\n\n def test_ndarray_index_getitem_multidim(self):\n shape_t = (2, 3, 5)\n nitems = prod(shape_t)\n for shape in permutations(shape_t):\n\n fmt, items, _ = randitems(nitems)\n\n for flags in (0, ND_PIL):\n # C array\n nd = ndarray(items, shape=shape, format=fmt, flags=flags)\n lst = carray(items, shape)\n\n for i in range(-shape[0], shape[0]):\n self.assertEqual(lst[i], nd[i].tolist())\n for j in range(-shape[1], shape[1]):\n self.assertEqual(lst[i][j], nd[i][j].tolist())\n for k in range(-shape[2], shape[2]):\n self.assertEqual(lst[i][j][k], nd[i][j][k])\n\n # Fortran array\n nd = ndarray(items, shape=shape, format=fmt,\n flags=flags|ND_FORTRAN)\n lst = farray(items, shape)\n\n for i in range(-shape[0], shape[0]):\n self.assertEqual(lst[i], nd[i].tolist())\n for j in range(-shape[1], shape[1]):\n self.assertEqual(lst[i][j], nd[i][j].tolist())\n for k in range(shape[2], shape[2]):\n self.assertEqual(lst[i][j][k], nd[i][j][k])\n\n def test_ndarray_sequence(self):\n nd = ndarray(1, shape=())\n self.assertRaises(TypeError, eval, \"1 in nd\", locals())\n mv = memoryview(nd)\n self.assertEqual(mv, nd)\n self.assertRaises(TypeError, eval, \"1 in mv\", locals())\n\n for fmt, items, _ in iter_format(5):\n nd = ndarray(items, shape=[5], format=fmt)\n for i, v in enumerate(nd):\n self.assertEqual(v, items[i])\n self.assertTrue(v in nd)\n\n if is_memoryview_format(fmt):\n mv = memoryview(nd)\n for i, v in enumerate(mv):\n self.assertEqual(v, items[i])\n self.assertTrue(v in mv)\n\n def test_ndarray_slice_invalid(self):\n items = [1,2,3,4,5,6,7,8]\n\n # rvalue is not an exporter\n xl = ndarray(items, shape=[8], flags=ND_WRITABLE)\n ml = memoryview(xl)\n self.assertRaises(TypeError, xl.__setitem__, slice(0,8,1), items)\n self.assertRaises(TypeError, ml.__setitem__, slice(0,8,1), items)\n\n # rvalue is not a full exporter\n xl = ndarray(items, shape=[8], flags=ND_WRITABLE)\n ex = ndarray(items, shape=[8], flags=ND_WRITABLE)\n xr = ndarray(ex, getbuf=PyBUF_ND)\n self.assertRaises(BufferError, xl.__setitem__, slice(0,8,1), xr)\n\n # zero step\n nd = ndarray(items, shape=[8], format=\"L\", flags=ND_WRITABLE)\n mv = memoryview(nd)\n self.assertRaises(ValueError, nd.__getitem__, slice(0,1,0))\n self.assertRaises(ValueError, mv.__getitem__, slice(0,1,0))\n\n nd = ndarray(items, shape=[2,4], format=\"L\", flags=ND_WRITABLE)\n mv = memoryview(nd)\n\n self.assertRaises(ValueError, nd.__getitem__,\n (slice(0,1,1), slice(0,1,0)))\n self.assertRaises(ValueError, nd.__getitem__,\n (slice(0,1,0), slice(0,1,1)))\n self.assertRaises(TypeError, nd.__getitem__, \"@%$\")\n self.assertRaises(TypeError, nd.__getitem__, (\"@%$\", slice(0,1,1)))\n self.assertRaises(TypeError, nd.__getitem__, (slice(0,1,1), {}))\n\n # memoryview: not implemented\n self.assertRaises(NotImplementedError, mv.__getitem__,\n (slice(0,1,1), slice(0,1,0)))\n self.assertRaises(TypeError, mv.__getitem__, \"@%$\")\n\n # differing format\n xl = ndarray(items, shape=[8], format=\"B\", flags=ND_WRITABLE)\n xr = ndarray(items, shape=[8], format=\"b\")\n ml = memoryview(xl)\n mr = memoryview(xr)\n self.assertRaises(ValueError, xl.__setitem__, slice(0,1,1), xr[7:8])\n self.assertEqual(xl.tolist(), items)\n self.assertRaises(ValueError, ml.__setitem__, slice(0,1,1), mr[7:8])\n self.assertEqual(ml.tolist(), items)\n\n # differing itemsize\n xl = ndarray(items, shape=[8], format=\"B\", flags=ND_WRITABLE)\n yr = ndarray(items, shape=[8], format=\"L\")\n ml = memoryview(xl)\n mr = memoryview(xr)\n self.assertRaises(ValueError, xl.__setitem__, slice(0,1,1), xr[7:8])\n self.assertEqual(xl.tolist(), items)\n self.assertRaises(ValueError, ml.__setitem__, slice(0,1,1), mr[7:8])\n self.assertEqual(ml.tolist(), items)\n\n # differing ndim\n xl = ndarray(items, shape=[2, 4], format=\"b\", flags=ND_WRITABLE)\n xr = ndarray(items, shape=[8], format=\"b\")\n ml = memoryview(xl)\n mr = memoryview(xr)\n self.assertRaises(ValueError, xl.__setitem__, slice(0,1,1), xr[7:8])\n self.assertEqual(xl.tolist(), [[1,2,3,4], [5,6,7,8]])\n self.assertRaises(NotImplementedError, ml.__setitem__, slice(0,1,1),\n mr[7:8])\n\n # differing shape\n xl = ndarray(items, shape=[8], format=\"b\", flags=ND_WRITABLE)\n xr = ndarray(items, shape=[8], format=\"b\")\n ml = memoryview(xl)\n mr = memoryview(xr)\n self.assertRaises(ValueError, xl.__setitem__, slice(0,2,1), xr[7:8])\n self.assertEqual(xl.tolist(), items)\n self.assertRaises(ValueError, ml.__setitem__, slice(0,2,1), mr[7:8])\n self.assertEqual(ml.tolist(), items)\n\n # _testbuffer.c module functions\n self.assertRaises(TypeError, slice_indices, slice(0,1,2), {})\n self.assertRaises(TypeError, slice_indices, \"###########\", 1)\n self.assertRaises(ValueError, slice_indices, slice(0,1,0), 4)\n\n x = ndarray(items, shape=[8], format=\"b\", flags=ND_PIL)\n self.assertRaises(TypeError, x.add_suboffsets)\n\n ex = ndarray(items, shape=[8], format=\"B\")\n x = ndarray(ex, getbuf=PyBUF_SIMPLE)\n self.assertRaises(TypeError, x.add_suboffsets)\n\n def test_ndarray_slice_zero_shape(self):\n items = [1,2,3,4,5,6,7,8,9,10,11,12]\n\n x = ndarray(items, shape=[12], format=\"L\", flags=ND_WRITABLE)\n y = ndarray(items, shape=[12], format=\"L\")\n x[4:4] = y[9:9]\n self.assertEqual(x.tolist(), items)\n\n ml = memoryview(x)\n mr = memoryview(y)\n self.assertEqual(ml, x)\n self.assertEqual(ml, y)\n ml[4:4] = mr[9:9]\n self.assertEqual(ml.tolist(), items)\n\n x = ndarray(items, shape=[3, 4], format=\"L\", flags=ND_WRITABLE)\n y = ndarray(items, shape=[4, 3], format=\"L\")\n x[1:2, 2:2] = y[1:2, 3:3]\n self.assertEqual(x.tolist(), carray(items, [3, 4]))\n\n def test_ndarray_slice_multidim(self):\n shape_t = (2, 3, 5)\n ndim = len(shape_t)\n nitems = prod(shape_t)\n for shape in permutations(shape_t):\n\n fmt, items, _ = randitems(nitems)\n itemsize = struct.calcsize(fmt)\n\n for flags in (0, ND_PIL):\n nd = ndarray(items, shape=shape, format=fmt, flags=flags)\n lst = carray(items, shape)\n\n for slices in rslices_ndim(ndim, shape):\n\n listerr = None\n try:\n sliced = multislice(lst, slices)\n except Exception as e:\n listerr = e.__class__\n\n nderr = None\n try:\n ndsliced = nd[slices]\n except Exception as e:\n nderr = e.__class__\n\n if nderr or listerr:\n self.assertIs(nderr, listerr)\n else:\n self.assertEqual(ndsliced.tolist(), sliced)\n\n def test_ndarray_slice_redundant_suboffsets(self):\n shape_t = (2, 3, 5, 2)\n ndim = len(shape_t)\n nitems = prod(shape_t)\n for shape in permutations(shape_t):\n\n fmt, items, _ = randitems(nitems)\n itemsize = struct.calcsize(fmt)\n\n nd = ndarray(items, shape=shape, format=fmt)\n nd.add_suboffsets()\n ex = ndarray(items, shape=shape, format=fmt)\n ex.add_suboffsets()\n mv = memoryview(ex)\n lst = carray(items, shape)\n\n for slices in rslices_ndim(ndim, shape):\n\n listerr = None\n try:\n sliced = multislice(lst, slices)\n except Exception as e:\n listerr = e.__class__\n\n nderr = None\n try:\n ndsliced = nd[slices]\n except Exception as e:\n nderr = e.__class__\n\n if nderr or listerr:\n self.assertIs(nderr, listerr)\n else:\n self.assertEqual(ndsliced.tolist(), sliced)\n\n def test_ndarray_slice_assign_single(self):\n for fmt, items, _ in iter_format(5):\n for lslice in genslices(5):\n for rslice in genslices(5):\n for flags in (0, ND_PIL):\n\n f = flags|ND_WRITABLE\n nd = ndarray(items, shape=[5], format=fmt, flags=f)\n ex = ndarray(items, shape=[5], format=fmt, flags=f)\n mv = memoryview(ex)\n\n lsterr = None\n diff_structure = None\n lst = items[:]\n try:\n lval = lst[lslice]\n rval = lst[rslice]\n lst[lslice] = lst[rslice]\n diff_structure = len(lval) != len(rval)\n except Exception as e:\n lsterr = e.__class__\n\n nderr = None\n try:\n nd[lslice] = nd[rslice]\n except Exception as e:\n nderr = e.__class__\n\n if diff_structure: # ndarray cannot change shape\n self.assertIs(nderr, ValueError)\n else:\n self.assertEqual(nd.tolist(), lst)\n self.assertIs(nderr, lsterr)\n\n if not is_memoryview_format(fmt):\n continue\n\n mverr = None\n try:\n mv[lslice] = mv[rslice]\n except Exception as e:\n mverr = e.__class__\n\n if diff_structure: # memoryview cannot change shape\n self.assertIs(mverr, ValueError)\n else:\n self.assertEqual(mv.tolist(), lst)\n self.assertEqual(mv, nd)\n self.assertIs(mverr, lsterr)\n self.verify(mv, obj=ex,\n itemsize=nd.itemsize, fmt=fmt, readonly=0,\n ndim=nd.ndim, shape=nd.shape, strides=nd.strides,\n lst=nd.tolist())\n\n def test_ndarray_slice_assign_multidim(self):\n shape_t = (2, 3, 5)\n ndim = len(shape_t)\n nitems = prod(shape_t)\n for shape in permutations(shape_t):\n\n fmt, items, _ = randitems(nitems)\n\n for flags in (0, ND_PIL):\n for _ in range(ITERATIONS):\n lslices, rslices = randslice_from_shape(ndim, shape)\n\n nd = ndarray(items, shape=shape, format=fmt,\n flags=flags|ND_WRITABLE)\n lst = carray(items, shape)\n\n listerr = None\n try:\n result = multislice_assign(lst, lst, lslices, rslices)\n except Exception as e:\n listerr = e.__class__\n\n nderr = None\n try:\n nd[lslices] = nd[rslices]\n except Exception as e:\n nderr = e.__class__\n\n if nderr or listerr:\n self.assertIs(nderr, listerr)\n else:\n self.assertEqual(nd.tolist(), result)\n\n def test_ndarray_random(self):\n # construction of valid arrays\n for _ in range(ITERATIONS):\n for fmt in fmtdict['@']:\n itemsize = struct.calcsize(fmt)\n\n t = rand_structure(itemsize, True, maxdim=MAXDIM,\n maxshape=MAXSHAPE)\n self.assertTrue(verify_structure(*t))\n items = randitems_from_structure(fmt, t)\n\n x = ndarray_from_structure(items, fmt, t)\n xlist = x.tolist()\n\n mv = memoryview(x)\n if is_memoryview_format(fmt):\n mvlist = mv.tolist()\n self.assertEqual(mvlist, xlist)\n\n if t[2] > 0:\n # ndim > 0: test against suboffsets representation.\n y = ndarray_from_structure(items, fmt, t, flags=ND_PIL)\n ylist = y.tolist()\n self.assertEqual(xlist, ylist)\n\n mv = memoryview(y)\n if is_memoryview_format(fmt):\n self.assertEqual(mv, y)\n mvlist = mv.tolist()\n self.assertEqual(mvlist, ylist)\n\n if numpy_array:\n shape = t[3]\n if 0 in shape:\n continue # http://projects.scipy.org/numpy/ticket/1910\n z = numpy_array_from_structure(items, fmt, t)\n self.verify(x, obj=None,\n itemsize=z.itemsize, fmt=fmt, readonly=0,\n ndim=z.ndim, shape=z.shape, strides=z.strides,\n lst=z.tolist())\n\n def test_ndarray_random_invalid(self):\n # exceptions during construction of invalid arrays\n for _ in range(ITERATIONS):\n for fmt in fmtdict['@']:\n itemsize = struct.calcsize(fmt)\n\n t = rand_structure(itemsize, False, maxdim=MAXDIM,\n maxshape=MAXSHAPE)\n self.assertFalse(verify_structure(*t))\n items = randitems_from_structure(fmt, t)\n\n nderr = False\n try:\n x = ndarray_from_structure(items, fmt, t)\n except Exception as e:\n nderr = e.__class__\n self.assertTrue(nderr)\n\n if numpy_array:\n numpy_err = False\n try:\n y = numpy_array_from_structure(items, fmt, t)\n except Exception as e:\n numpy_err = e.__class__\n\n if 0: # http://projects.scipy.org/numpy/ticket/1910\n self.assertTrue(numpy_err)\n\n def test_ndarray_random_slice_assign(self):\n # valid slice assignments\n for _ in range(ITERATIONS):\n for fmt in fmtdict['@']:\n itemsize = struct.calcsize(fmt)\n\n lshape, rshape, lslices, rslices = \\\n rand_aligned_slices(maxdim=MAXDIM, maxshape=MAXSHAPE)\n tl = rand_structure(itemsize, True, shape=lshape)\n tr = rand_structure(itemsize, True, shape=rshape)\n self.assertTrue(verify_structure(*tl))\n self.assertTrue(verify_structure(*tr))\n litems = randitems_from_structure(fmt, tl)\n ritems = randitems_from_structure(fmt, tr)\n\n xl = ndarray_from_structure(litems, fmt, tl)\n xr = ndarray_from_structure(ritems, fmt, tr)\n xl[lslices] = xr[rslices]\n xllist = xl.tolist()\n xrlist = xr.tolist()\n\n ml = memoryview(xl)\n mr = memoryview(xr)\n self.assertEqual(ml.tolist(), xllist)\n self.assertEqual(mr.tolist(), xrlist)\n\n if tl[2] > 0 and tr[2] > 0:\n # ndim > 0: test against suboffsets representation.\n yl = ndarray_from_structure(litems, fmt, tl, flags=ND_PIL)\n yr = ndarray_from_structure(ritems, fmt, tr, flags=ND_PIL)\n yl[lslices] = yr[rslices]\n yllist = yl.tolist()\n yrlist = yr.tolist()\n self.assertEqual(xllist, yllist)\n self.assertEqual(xrlist, yrlist)\n\n ml = memoryview(yl)\n mr = memoryview(yr)\n self.assertEqual(ml.tolist(), yllist)\n self.assertEqual(mr.tolist(), yrlist)\n\n if numpy_array:\n if 0 in lshape or 0 in rshape:\n continue # http://projects.scipy.org/numpy/ticket/1910\n\n zl = numpy_array_from_structure(litems, fmt, tl)\n zr = numpy_array_from_structure(ritems, fmt, tr)\n zl[lslices] = zr[rslices]\n\n if not is_overlapping(tl) and not is_overlapping(tr):\n # Slice assignment of overlapping structures\n # is undefined in NumPy.\n self.verify(xl, obj=None,\n itemsize=zl.itemsize, fmt=fmt, readonly=0,\n ndim=zl.ndim, shape=zl.shape,\n strides=zl.strides, lst=zl.tolist())\n\n self.verify(xr, obj=None,\n itemsize=zr.itemsize, fmt=fmt, readonly=0,\n ndim=zr.ndim, shape=zr.shape,\n strides=zr.strides, lst=zr.tolist())\n\n def test_ndarray_re_export(self):\n items = [1,2,3,4,5,6,7,8,9,10,11,12]\n\n nd = ndarray(items, shape=[3,4], flags=ND_PIL)\n ex = ndarray(nd)\n\n self.assertTrue(ex.flags & ND_PIL)\n self.assertIs(ex.obj, nd)\n self.assertEqual(ex.suboffsets, (0, -1))\n self.assertFalse(ex.c_contiguous)\n self.assertFalse(ex.f_contiguous)\n self.assertFalse(ex.contiguous)\n\n def test_ndarray_zero_shape(self):\n # zeros in shape\n for flags in (0, ND_PIL):\n nd = ndarray([1,2,3], shape=[0], flags=flags)\n mv = memoryview(nd)\n self.assertEqual(mv, nd)\n self.assertEqual(nd.tolist(), [])\n self.assertEqual(mv.tolist(), [])\n\n nd = ndarray([1,2,3], shape=[0,3,3], flags=flags)\n self.assertEqual(nd.tolist(), [])\n\n nd = ndarray([1,2,3], shape=[3,0,3], flags=flags)\n self.assertEqual(nd.tolist(), [[], [], []])\n\n nd = ndarray([1,2,3], shape=[3,3,0], flags=flags)\n self.assertEqual(nd.tolist(),\n [[[], [], []], [[], [], []], [[], [], []]])\n\n def test_ndarray_zero_strides(self):\n # zero strides\n for flags in (0, ND_PIL):\n nd = ndarray([1], shape=[5], strides=[0], flags=flags)\n mv = memoryview(nd)\n self.assertEqual(mv, nd)\n self.assertEqual(nd.tolist(), [1, 1, 1, 1, 1])\n self.assertEqual(mv.tolist(), [1, 1, 1, 1, 1])\n\n def test_ndarray_offset(self):\n nd = ndarray(list(range(20)), shape=[3], offset=7)\n self.assertEqual(nd.offset, 7)\n self.assertEqual(nd.tolist(), [7,8,9])\n\n def test_ndarray_memoryview_from_buffer(self):\n for flags in (0, ND_PIL):\n nd = ndarray(list(range(3)), shape=[3], flags=flags)\n m = nd.memoryview_from_buffer()\n self.assertEqual(m, nd)\n\n def test_ndarray_get_pointer(self):\n for flags in (0, ND_PIL):\n nd = ndarray(list(range(3)), shape=[3], flags=flags)\n for i in range(3):\n self.assertEqual(nd[i], get_pointer(nd, [i]))\n\n def test_ndarray_tolist_null_strides(self):\n ex = ndarray(list(range(20)), shape=[2,2,5])\n\n nd = ndarray(ex, getbuf=PyBUF_ND|PyBUF_FORMAT)\n self.assertEqual(nd.tolist(), ex.tolist())\n\n m = memoryview(ex)\n self.assertEqual(m.tolist(), ex.tolist())\n\n def test_ndarray_cmp_contig(self):\n\n self.assertFalse(cmp_contig(b\"123\", b\"456\"))\n\n x = ndarray(list(range(12)), shape=[3,4])\n y = ndarray(list(range(12)), shape=[4,3])\n self.assertFalse(cmp_contig(x, y))\n\n x = ndarray([1], shape=[1], format=\"B\")\n self.assertTrue(cmp_contig(x, b'\\x01'))\n self.assertTrue(cmp_contig(b'\\x01', x))\n\n def test_ndarray_hash(self):\n\n a = array.array('L', [1,2,3])\n nd = ndarray(a)\n self.assertRaises(ValueError, hash, nd)\n\n # one-dimensional\n b = bytes(list(range(12)))\n\n nd = ndarray(list(range(12)), shape=[12])\n self.assertEqual(hash(nd), hash(b))\n\n # C-contiguous\n nd = ndarray(list(range(12)), shape=[3,4])\n self.assertEqual(hash(nd), hash(b))\n\n nd = ndarray(list(range(12)), shape=[3,2,2])\n self.assertEqual(hash(nd), hash(b))\n\n # Fortran contiguous\n b = bytes(transpose(list(range(12)), shape=[4,3]))\n nd = ndarray(list(range(12)), shape=[3,4], flags=ND_FORTRAN)\n self.assertEqual(hash(nd), hash(b))\n\n b = bytes(transpose(list(range(12)), shape=[2,3,2]))\n nd = ndarray(list(range(12)), shape=[2,3,2], flags=ND_FORTRAN)\n self.assertEqual(hash(nd), hash(b))\n\n # suboffsets\n b = bytes(list(range(12)))\n nd = ndarray(list(range(12)), shape=[2,2,3], flags=ND_PIL)\n self.assertEqual(hash(nd), hash(b))\n\n # non-byte formats\n nd = ndarray(list(range(12)), shape=[2,2,3], format='L')\n self.assertEqual(hash(nd), hash(nd.tobytes()))\n\n def test_py_buffer_to_contiguous(self):\n\n # The requests are used in _testbuffer.c:py_buffer_to_contiguous\n # to generate buffers without full information for testing.\n requests = (\n # distinct flags\n PyBUF_INDIRECT, PyBUF_STRIDES, PyBUF_ND, PyBUF_SIMPLE,\n # compound requests\n PyBUF_FULL, PyBUF_FULL_RO,\n PyBUF_RECORDS, PyBUF_RECORDS_RO,\n PyBUF_STRIDED, PyBUF_STRIDED_RO,\n PyBUF_CONTIG, PyBUF_CONTIG_RO,\n )\n\n # no buffer interface\n self.assertRaises(TypeError, py_buffer_to_contiguous, {}, 'F',\n PyBUF_FULL_RO)\n\n # scalar, read-only request\n nd = ndarray(9, shape=(), format=\"L\", flags=ND_WRITABLE)\n for order in ['C', 'F', 'A']:\n for request in requests:\n b = py_buffer_to_contiguous(nd, order, request)\n self.assertEqual(b, nd.tobytes())\n\n # zeros in shape\n nd = ndarray([1], shape=[0], format=\"L\", flags=ND_WRITABLE)\n for order in ['C', 'F', 'A']:\n for request in requests:\n b = py_buffer_to_contiguous(nd, order, request)\n self.assertEqual(b, b'')\n\n nd = ndarray(list(range(8)), shape=[2, 0, 7], format=\"L\",\n flags=ND_WRITABLE)\n for order in ['C', 'F', 'A']:\n for request in requests:\n b = py_buffer_to_contiguous(nd, order, request)\n self.assertEqual(b, b'')\n\n ### One-dimensional arrays are trivial, since Fortran and C order\n ### are the same.\n\n # one-dimensional\n for f in [0, ND_FORTRAN]:\n nd = ndarray([1], shape=[1], format=\"h\", flags=f|ND_WRITABLE)\n ndbytes = nd.tobytes()\n for order in ['C', 'F', 'A']:\n for request in requests:\n b = py_buffer_to_contiguous(nd, order, request)\n self.assertEqual(b, ndbytes)\n\n nd = ndarray([1, 2, 3], shape=[3], format=\"b\", flags=f|ND_WRITABLE)\n ndbytes = nd.tobytes()\n for order in ['C', 'F', 'A']:\n for request in requests:\n b = py_buffer_to_contiguous(nd, order, request)\n self.assertEqual(b, ndbytes)\n\n # one-dimensional, non-contiguous input\n nd = ndarray([1, 2, 3], shape=[2], strides=[2], flags=ND_WRITABLE)\n ndbytes = nd.tobytes()\n for order in ['C', 'F', 'A']:\n for request in [PyBUF_STRIDES, PyBUF_FULL]:\n b = py_buffer_to_contiguous(nd, order, request)\n self.assertEqual(b, ndbytes)\n\n nd = nd[::-1]\n ndbytes = nd.tobytes()\n for order in ['C', 'F', 'A']:\n for request in requests:\n try:\n b = py_buffer_to_contiguous(nd, order, request)\n except BufferError:\n continue\n self.assertEqual(b, ndbytes)\n\n ###\n ### Multi-dimensional arrays:\n ###\n ### The goal here is to preserve the logical representation of the\n ### input array but change the physical representation if necessary.\n ###\n ### _testbuffer example:\n ### ====================\n ###\n ### C input array:\n ### --------------\n ### >>> nd = ndarray(list(range(12)), shape=[3, 4])\n ### >>> nd.tolist()\n ### [[0, 1, 2, 3],\n ### [4, 5, 6, 7],\n ### [8, 9, 10, 11]]\n ###\n ### Fortran output:\n ### ---------------\n ### >>> py_buffer_to_contiguous(nd, 'F', PyBUF_FULL_RO)\n ### >>> b'\\x00\\x04\\x08\\x01\\x05\\t\\x02\\x06\\n\\x03\\x07\\x0b'\n ###\n ### The return value corresponds to this input list for\n ### _testbuffer's ndarray:\n ### >>> nd = ndarray([0,4,8,1,5,9,2,6,10,3,7,11], shape=[3,4],\n ### flags=ND_FORTRAN)\n ### >>> nd.tolist()\n ### [[0, 1, 2, 3],\n ### [4, 5, 6, 7],\n ### [8, 9, 10, 11]]\n ###\n ### The logical array is the same, but the values in memory are now\n ### in Fortran order.\n ###\n ### NumPy example:\n ### ==============\n ### _testbuffer's ndarray takes lists to initialize the memory.\n ### Here's the same sequence in NumPy:\n ###\n ### C input:\n ### --------\n ### >>> nd = ndarray(buffer=bytearray(list(range(12))),\n ### shape=[3, 4], dtype='B')\n ### >>> nd\n ### array([[ 0, 1, 2, 3],\n ### [ 4, 5, 6, 7],\n ### [ 8, 9, 10, 11]], dtype=uint8)\n ###\n ### Fortran output:\n ### ---------------\n ### >>> fortran_buf = nd.tostring(order='F')\n ### >>> fortran_buf\n ### b'\\x00\\x04\\x08\\x01\\x05\\t\\x02\\x06\\n\\x03\\x07\\x0b'\n ###\n ### >>> nd = ndarray(buffer=fortran_buf, shape=[3, 4],\n ### dtype='B', order='F')\n ###\n ### >>> nd\n ### array([[ 0, 1, 2, 3],\n ### [ 4, 5, 6, 7],\n ### [ 8, 9, 10, 11]], dtype=uint8)\n ###\n\n # multi-dimensional, contiguous input\n lst = list(range(12))\n for f in [0, ND_FORTRAN]:\n nd = ndarray(lst, shape=[3, 4], flags=f|ND_WRITABLE)\n if numpy_array:\n na = numpy_array(buffer=bytearray(lst),\n shape=[3, 4], dtype='B',\n order='C' if f == 0 else 'F')\n\n # 'C' request\n if f == ND_FORTRAN: # 'F' to 'C'\n x = ndarray(transpose(lst, [4, 3]), shape=[3, 4],\n flags=ND_WRITABLE)\n expected = x.tobytes()\n else:\n expected = nd.tobytes()\n for request in requests:\n try:\n b = py_buffer_to_contiguous(nd, 'C', request)\n except BufferError:\n continue\n\n self.assertEqual(b, expected)\n\n # Check that output can be used as the basis for constructing\n # a C array that is logically identical to the input array.\n y = ndarray([v for v in b], shape=[3, 4], flags=ND_WRITABLE)\n self.assertEqual(memoryview(y), memoryview(nd))\n\n if numpy_array:\n self.assertEqual(b, na.tostring(order='C'))\n\n # 'F' request\n if f == 0: # 'C' to 'F'\n x = ndarray(transpose(lst, [3, 4]), shape=[4, 3],\n flags=ND_WRITABLE)\n else:\n x = ndarray(lst, shape=[3, 4], flags=ND_WRITABLE)\n expected = x.tobytes()\n for request in [PyBUF_FULL, PyBUF_FULL_RO, PyBUF_INDIRECT,\n PyBUF_STRIDES, PyBUF_ND]:\n try:\n b = py_buffer_to_contiguous(nd, 'F', request)\n except BufferError:\n continue\n self.assertEqual(b, expected)\n\n # Check that output can be used as the basis for constructing\n # a Fortran array that is logically identical to the input array.\n y = ndarray([v for v in b], shape=[3, 4], flags=ND_FORTRAN|ND_WRITABLE)\n self.assertEqual(memoryview(y), memoryview(nd))\n\n if numpy_array:\n self.assertEqual(b, na.tostring(order='F'))\n\n # 'A' request\n if f == ND_FORTRAN:\n x = ndarray(lst, shape=[3, 4], flags=ND_WRITABLE)\n expected = x.tobytes()\n else:\n expected = nd.tobytes()\n for request in [PyBUF_FULL, PyBUF_FULL_RO, PyBUF_INDIRECT,\n PyBUF_STRIDES, PyBUF_ND]:\n try:\n b = py_buffer_to_contiguous(nd, 'A', request)\n except BufferError:\n continue\n\n self.assertEqual(b, expected)\n\n # Check that output can be used as the basis for constructing\n # an array with order=f that is logically identical to the input\n # array.\n y = ndarray([v for v in b], shape=[3, 4], flags=f|ND_WRITABLE)\n self.assertEqual(memoryview(y), memoryview(nd))\n\n if numpy_array:\n self.assertEqual(b, na.tostring(order='A'))\n\n # multi-dimensional, non-contiguous input\n nd = ndarray(list(range(12)), shape=[3, 4], flags=ND_WRITABLE|ND_PIL)\n\n # 'C'\n b = py_buffer_to_contiguous(nd, 'C', PyBUF_FULL_RO)\n self.assertEqual(b, nd.tobytes())\n y = ndarray([v for v in b], shape=[3, 4], flags=ND_WRITABLE)\n self.assertEqual(memoryview(y), memoryview(nd))\n\n # 'F'\n b = py_buffer_to_contiguous(nd, 'F', PyBUF_FULL_RO)\n x = ndarray(transpose(lst, [3, 4]), shape=[4, 3], flags=ND_WRITABLE)\n self.assertEqual(b, x.tobytes())\n y = ndarray([v for v in b], shape=[3, 4], flags=ND_FORTRAN|ND_WRITABLE)\n self.assertEqual(memoryview(y), memoryview(nd))\n\n # 'A'\n b = py_buffer_to_contiguous(nd, 'A', PyBUF_FULL_RO)\n self.assertEqual(b, nd.tobytes())\n y = ndarray([v for v in b], shape=[3, 4], flags=ND_WRITABLE)\n self.assertEqual(memoryview(y), memoryview(nd))\n\n def test_memoryview_construction(self):\n\n items_shape = [(9, []), ([1,2,3], [3]), (list(range(2*3*5)), [2,3,5])]\n\n # NumPy style, C-contiguous:\n for items, shape in items_shape:\n\n # From PEP-3118 compliant exporter:\n ex = ndarray(items, shape=shape)\n m = memoryview(ex)\n self.assertTrue(m.c_contiguous)\n self.assertTrue(m.contiguous)\n\n ndim = len(shape)\n strides = strides_from_shape(ndim, shape, 1, 'C')\n lst = carray(items, shape)\n\n self.verify(m, obj=ex,\n itemsize=1, fmt='B', readonly=1,\n ndim=ndim, shape=shape, strides=strides,\n lst=lst)\n\n # From memoryview:\n m2 = memoryview(m)\n self.verify(m2, obj=ex,\n itemsize=1, fmt='B', readonly=1,\n ndim=ndim, shape=shape, strides=strides,\n lst=lst)\n\n # PyMemoryView_FromBuffer(): no strides\n nd = ndarray(ex, getbuf=PyBUF_CONTIG_RO|PyBUF_FORMAT)\n self.assertEqual(nd.strides, ())\n m = nd.memoryview_from_buffer()\n self.verify(m, obj=None,\n itemsize=1, fmt='B', readonly=1,\n ndim=ndim, shape=shape, strides=strides,\n lst=lst)\n\n # PyMemoryView_FromBuffer(): no format, shape, strides\n nd = ndarray(ex, getbuf=PyBUF_SIMPLE)\n self.assertEqual(nd.format, '')\n self.assertEqual(nd.shape, ())\n self.assertEqual(nd.strides, ())\n m = nd.memoryview_from_buffer()\n\n lst = [items] if ndim == 0 else items\n self.verify(m, obj=None,\n itemsize=1, fmt='B', readonly=1,\n ndim=1, shape=[ex.nbytes], strides=(1,),\n lst=lst)\n\n # NumPy style, Fortran contiguous:\n for items, shape in items_shape:\n\n # From PEP-3118 compliant exporter:\n ex = ndarray(items, shape=shape, flags=ND_FORTRAN)\n m = memoryview(ex)\n self.assertTrue(m.f_contiguous)\n self.assertTrue(m.contiguous)\n\n ndim = len(shape)\n strides = strides_from_shape(ndim, shape, 1, 'F')\n lst = farray(items, shape)\n\n self.verify(m, obj=ex,\n itemsize=1, fmt='B', readonly=1,\n ndim=ndim, shape=shape, strides=strides,\n lst=lst)\n\n # From memoryview:\n m2 = memoryview(m)\n self.verify(m2, obj=ex,\n itemsize=1, fmt='B', readonly=1,\n ndim=ndim, shape=shape, strides=strides,\n lst=lst)\n\n # PIL style:\n for items, shape in items_shape[1:]:\n\n # From PEP-3118 compliant exporter:\n ex = ndarray(items, shape=shape, flags=ND_PIL)\n m = memoryview(ex)\n\n ndim = len(shape)\n lst = carray(items, shape)\n\n self.verify(m, obj=ex,\n itemsize=1, fmt='B', readonly=1,\n ndim=ndim, shape=shape, strides=ex.strides,\n lst=lst)\n\n # From memoryview:\n m2 = memoryview(m)\n self.verify(m2, obj=ex,\n itemsize=1, fmt='B', readonly=1,\n ndim=ndim, shape=shape, strides=ex.strides,\n lst=lst)\n\n # Invalid number of arguments:\n self.assertRaises(TypeError, memoryview, b'9', 'x')\n # Not a buffer provider:\n self.assertRaises(TypeError, memoryview, {})\n # Non-compliant buffer provider:\n ex = ndarray([1,2,3], shape=[3])\n nd = ndarray(ex, getbuf=PyBUF_SIMPLE)\n self.assertRaises(BufferError, memoryview, nd)\n nd = ndarray(ex, getbuf=PyBUF_CONTIG_RO|PyBUF_FORMAT)\n self.assertRaises(BufferError, memoryview, nd)\n\n # ndim > 64\n nd = ndarray([1]*128, shape=[1]*128, format='L')\n self.assertRaises(ValueError, memoryview, nd)\n self.assertRaises(ValueError, nd.memoryview_from_buffer)\n self.assertRaises(ValueError, get_contiguous, nd, PyBUF_READ, 'C')\n self.assertRaises(ValueError, get_contiguous, nd, PyBUF_READ, 'F')\n self.assertRaises(ValueError, get_contiguous, nd[::-1], PyBUF_READ, 'C')\n\n def test_memoryview_cast_zero_shape(self):\n # Casts are undefined if buffer is multidimensional and shape\n # contains zeros. These arrays are regarded as C-contiguous by\n # Numpy and PyBuffer_GetContiguous(), so they are not caught by\n # the test for C-contiguity in memory_cast().\n items = [1,2,3]\n for shape in ([0,3,3], [3,0,3], [0,3,3]):\n ex = ndarray(items, shape=shape)\n self.assertTrue(ex.c_contiguous)\n msrc = memoryview(ex)\n self.assertRaises(TypeError, msrc.cast, 'c')\n # Monodimensional empty view can be cast (issue #19014).\n for fmt, _, _ in iter_format(1, 'memoryview'):\n msrc = memoryview(b'')\n m = msrc.cast(fmt)\n self.assertEqual(m.tobytes(), b'')\n self.assertEqual(m.tolist(), [])\n\n def test_memoryview_struct_module(self):\n\n class INT(object):\n def __init__(self, val):\n self.val = val\n def __int__(self):\n return self.val\n\n class IDX(object):\n def __init__(self, val):\n self.val = val\n def __index__(self):\n return self.val\n\n def f(): return 7\n\n values = [INT(9), IDX(9),\n 2.2+3j, Decimal(\"-21.1\"), 12.2, Fraction(5, 2),\n [1,2,3], {4,5,6}, {7:8}, (), (9,),\n True, False, None, NotImplemented,\n b'a', b'abc', bytearray(b'a'), bytearray(b'abc'),\n 'a', 'abc', r'a', r'abc',\n f, lambda x: x]\n\n for fmt, items, item in iter_format(10, 'memoryview'):\n ex = ndarray(items, shape=[10], format=fmt, flags=ND_WRITABLE)\n nd = ndarray(items, shape=[10], format=fmt, flags=ND_WRITABLE)\n m = memoryview(ex)\n\n struct.pack_into(fmt, nd, 0, item)\n m[0] = item\n self.assertEqual(m[0], nd[0])\n\n itemsize = struct.calcsize(fmt)\n if 'P' in fmt:\n continue\n\n for v in values:\n struct_err = None\n try:\n struct.pack_into(fmt, nd, itemsize, v)\n except struct.error:\n struct_err = struct.error\n\n mv_err = None\n try:\n m[1] = v\n except (TypeError, ValueError) as e:\n mv_err = e.__class__\n\n if struct_err or mv_err:\n self.assertIsNot(struct_err, None)\n self.assertIsNot(mv_err, None)\n else:\n self.assertEqual(m[1], nd[1])\n\n def test_memoryview_cast_zero_strides(self):\n # Casts are undefined if strides contains zeros. These arrays are\n # (sometimes!) regarded as C-contiguous by Numpy, but not by\n # PyBuffer_GetContiguous().\n ex = ndarray([1,2,3], shape=[3], strides=[0])\n self.assertFalse(ex.c_contiguous)\n msrc = memoryview(ex)\n self.assertRaises(TypeError, msrc.cast, 'c')\n\n def test_memoryview_cast_invalid(self):\n # invalid format\n for sfmt in NON_BYTE_FORMAT:\n sformat = '@' + sfmt if randrange(2) else sfmt\n ssize = struct.calcsize(sformat)\n for dfmt in NON_BYTE_FORMAT:\n dformat = '@' + dfmt if randrange(2) else dfmt\n dsize = struct.calcsize(dformat)\n ex = ndarray(list(range(32)), shape=[32//ssize], format=sformat)\n msrc = memoryview(ex)\n self.assertRaises(TypeError, msrc.cast, dfmt, [32//dsize])\n\n for sfmt, sitems, _ in iter_format(1):\n ex = ndarray(sitems, shape=[1], format=sfmt)\n msrc = memoryview(ex)\n for dfmt, _, _ in iter_format(1):\n if (not is_memoryview_format(sfmt) or\n not is_memoryview_format(dfmt)):\n self.assertRaises(ValueError, msrc.cast, dfmt,\n [32//dsize])\n else:\n if not is_byte_format(sfmt) and not is_byte_format(dfmt):\n self.assertRaises(TypeError, msrc.cast, dfmt,\n [32//dsize])\n\n # invalid shape\n size_h = struct.calcsize('h')\n size_d = struct.calcsize('d')\n ex = ndarray(list(range(2*2*size_d)), shape=[2,2,size_d], format='h')\n msrc = memoryview(ex)\n self.assertRaises(TypeError, msrc.cast, shape=[2,2,size_h], format='d')\n\n ex = ndarray(list(range(120)), shape=[1,2,3,4,5])\n m = memoryview(ex)\n\n # incorrect number of args\n self.assertRaises(TypeError, m.cast)\n self.assertRaises(TypeError, m.cast, 1, 2, 3)\n\n # incorrect dest format type\n self.assertRaises(TypeError, m.cast, {})\n\n # incorrect dest format\n self.assertRaises(ValueError, m.cast, \"X\")\n self.assertRaises(ValueError, m.cast, \"@X\")\n self.assertRaises(ValueError, m.cast, \"@XY\")\n\n # dest format not implemented\n self.assertRaises(ValueError, m.cast, \"=B\")\n self.assertRaises(ValueError, m.cast, \"!L\")\n self.assertRaises(ValueError, m.cast, \"<P\")\n self.assertRaises(ValueError, m.cast, \">l\")\n self.assertRaises(ValueError, m.cast, \"BI\")\n self.assertRaises(ValueError, m.cast, \"xBI\")\n\n # src format not implemented\n ex = ndarray([(1,2), (3,4)], shape=[2], format=\"II\")\n m = memoryview(ex)\n self.assertRaises(NotImplementedError, m.__getitem__, 0)\n self.assertRaises(NotImplementedError, m.__setitem__, 0, 8)\n self.assertRaises(NotImplementedError, m.tolist)\n\n # incorrect shape type\n ex = ndarray(list(range(120)), shape=[1,2,3,4,5])\n m = memoryview(ex)\n self.assertRaises(TypeError, m.cast, \"B\", shape={})\n\n # incorrect shape elements\n ex = ndarray(list(range(120)), shape=[2*3*4*5])\n m = memoryview(ex)\n self.assertRaises(OverflowError, m.cast, \"B\", shape=[2**64])\n self.assertRaises(ValueError, m.cast, \"B\", shape=[-1])\n self.assertRaises(ValueError, m.cast, \"B\", shape=[2,3,4,5,6,7,-1])\n self.assertRaises(ValueError, m.cast, \"B\", shape=[2,3,4,5,6,7,0])\n self.assertRaises(TypeError, m.cast, \"B\", shape=[2,3,4,5,6,7,'x'])\n\n # N-D -> N-D cast\n ex = ndarray(list([9 for _ in range(3*5*7*11)]), shape=[3,5,7,11])\n m = memoryview(ex)\n self.assertRaises(TypeError, m.cast, \"I\", shape=[2,3,4,5])\n\n # cast with ndim > 64\n nd = ndarray(list(range(128)), shape=[128], format='I')\n m = memoryview(nd)\n self.assertRaises(ValueError, m.cast, 'I', [1]*128)\n\n # view->len not a multiple of itemsize\n ex = ndarray(list([9 for _ in range(3*5*7*11)]), shape=[3*5*7*11])\n m = memoryview(ex)\n self.assertRaises(TypeError, m.cast, \"I\", shape=[2,3,4,5])\n\n # product(shape) * itemsize != buffer size\n ex = ndarray(list([9 for _ in range(3*5*7*11)]), shape=[3*5*7*11])\n m = memoryview(ex)\n self.assertRaises(TypeError, m.cast, \"B\", shape=[2,3,4,5])\n\n # product(shape) * itemsize overflow\n nd = ndarray(list(range(128)), shape=[128], format='I')\n m1 = memoryview(nd)\n nd = ndarray(list(range(128)), shape=[128], format='B')\n m2 = memoryview(nd)\n if sys.maxsize == 2**63-1:\n self.assertRaises(TypeError, m1.cast, 'B',\n [7, 7, 73, 127, 337, 92737, 649657])\n self.assertRaises(ValueError, m1.cast, 'B',\n [2**20, 2**20, 2**10, 2**10, 2**3])\n self.assertRaises(ValueError, m2.cast, 'I',\n [2**20, 2**20, 2**10, 2**10, 2**1])\n else:\n self.assertRaises(TypeError, m1.cast, 'B',\n [1, 2147483647])\n self.assertRaises(ValueError, m1.cast, 'B',\n [2**10, 2**10, 2**5, 2**5, 2**1])\n self.assertRaises(ValueError, m2.cast, 'I',\n [2**10, 2**10, 2**5, 2**3, 2**1])\n\n def test_memoryview_cast(self):\n bytespec = (\n ('B', lambda ex: list(ex.tobytes())),\n ('b', lambda ex: [x-256 if x > 127 else x for x in list(ex.tobytes())]),\n ('c', lambda ex: [bytes(chr(x), 'latin-1') for x in list(ex.tobytes())]),\n )\n\n def iter_roundtrip(ex, m, items, fmt):\n srcsize = struct.calcsize(fmt)\n for bytefmt, to_bytelist in bytespec:\n\n m2 = m.cast(bytefmt)\n lst = to_bytelist(ex)\n self.verify(m2, obj=ex,\n itemsize=1, fmt=bytefmt, readonly=0,\n ndim=1, shape=[31*srcsize], strides=(1,),\n lst=lst, cast=True)\n\n m3 = m2.cast(fmt)\n self.assertEqual(m3, ex)\n lst = ex.tolist()\n self.verify(m3, obj=ex,\n itemsize=srcsize, fmt=fmt, readonly=0,\n ndim=1, shape=[31], strides=(srcsize,),\n lst=lst, cast=True)\n\n # cast from ndim = 0 to ndim = 1\n srcsize = struct.calcsize('I')\n ex = ndarray(9, shape=[], format='I')\n destitems, destshape = cast_items(ex, 'B', 1)\n m = memoryview(ex)\n m2 = m.cast('B')\n self.verify(m2, obj=ex,\n itemsize=1, fmt='B', readonly=1,\n ndim=1, shape=destshape, strides=(1,),\n lst=destitems, cast=True)\n\n # cast from ndim = 1 to ndim = 0\n destsize = struct.calcsize('I')\n ex = ndarray([9]*destsize, shape=[destsize], format='B')\n destitems, destshape = cast_items(ex, 'I', destsize, shape=[])\n m = memoryview(ex)\n m2 = m.cast('I', shape=[])\n self.verify(m2, obj=ex,\n itemsize=destsize, fmt='I', readonly=1,\n ndim=0, shape=(), strides=(),\n lst=destitems, cast=True)\n\n # array.array: roundtrip to/from bytes\n for fmt, items, _ in iter_format(31, 'array'):\n ex = array.array(fmt, items)\n m = memoryview(ex)\n iter_roundtrip(ex, m, items, fmt)\n\n # ndarray: roundtrip to/from bytes\n for fmt, items, _ in iter_format(31, 'memoryview'):\n ex = ndarray(items, shape=[31], format=fmt, flags=ND_WRITABLE)\n m = memoryview(ex)\n iter_roundtrip(ex, m, items, fmt)\n\n def test_memoryview_cast_1D_ND(self):\n # Cast between C-contiguous buffers. At least one buffer must\n # be 1D, at least one format must be 'c', 'b' or 'B'.\n for _tshape in gencastshapes():\n for char in fmtdict['@']:\n tfmt = ('', '@')[randrange(2)] + char\n tsize = struct.calcsize(tfmt)\n n = prod(_tshape) * tsize\n obj = 'memoryview' if is_byte_format(tfmt) else 'bytefmt'\n for fmt, items, _ in iter_format(n, obj):\n size = struct.calcsize(fmt)\n shape = [n] if n > 0 else []\n tshape = _tshape + [size]\n\n ex = ndarray(items, shape=shape, format=fmt)\n m = memoryview(ex)\n\n titems, tshape = cast_items(ex, tfmt, tsize, shape=tshape)\n\n if titems is None:\n self.assertRaises(TypeError, m.cast, tfmt, tshape)\n continue\n if titems == 'nan':\n continue # NaNs in lists are a recipe for trouble.\n\n # 1D -> ND\n nd = ndarray(titems, shape=tshape, format=tfmt)\n\n m2 = m.cast(tfmt, shape=tshape)\n ndim = len(tshape)\n strides = nd.strides\n lst = nd.tolist()\n self.verify(m2, obj=ex,\n itemsize=tsize, fmt=tfmt, readonly=1,\n ndim=ndim, shape=tshape, strides=strides,\n lst=lst, cast=True)\n\n # ND -> 1D\n m3 = m2.cast(fmt)\n m4 = m2.cast(fmt, shape=shape)\n ndim = len(shape)\n strides = ex.strides\n lst = ex.tolist()\n\n self.verify(m3, obj=ex,\n itemsize=size, fmt=fmt, readonly=1,\n ndim=ndim, shape=shape, strides=strides,\n lst=lst, cast=True)\n\n self.verify(m4, obj=ex,\n itemsize=size, fmt=fmt, readonly=1,\n ndim=ndim, shape=shape, strides=strides,\n lst=lst, cast=True)\n\n def test_memoryview_tolist(self):\n\n # Most tolist() tests are in self.verify() etc.\n\n a = array.array('h', list(range(-6, 6)))\n m = memoryview(a)\n self.assertEqual(m, a)\n self.assertEqual(m.tolist(), a.tolist())\n\n a = a[2::3]\n m = m[2::3]\n self.assertEqual(m, a)\n self.assertEqual(m.tolist(), a.tolist())\n\n ex = ndarray(list(range(2*3*5*7*11)), shape=[11,2,7,3,5], format='L')\n m = memoryview(ex)\n self.assertEqual(m.tolist(), ex.tolist())\n\n ex = ndarray([(2, 5), (7, 11)], shape=[2], format='lh')\n m = memoryview(ex)\n self.assertRaises(NotImplementedError, m.tolist)\n\n ex = ndarray([b'12345'], shape=[1], format=\"s\")\n m = memoryview(ex)\n self.assertRaises(NotImplementedError, m.tolist)\n\n ex = ndarray([b\"a\",b\"b\",b\"c\",b\"d\",b\"e\",b\"f\"], shape=[2,3], format='s')\n m = memoryview(ex)\n self.assertRaises(NotImplementedError, m.tolist)\n\n def test_memoryview_repr(self):\n m = memoryview(bytearray(9))\n r = m.__repr__()\n self.assertTrue(r.startswith(\"<memory\"))\n\n m.release()\n r = m.__repr__()\n self.assertTrue(r.startswith(\"<released\"))\n\n def test_memoryview_sequence(self):\n\n for fmt in ('d', 'f'):\n inf = float(3e400)\n ex = array.array(fmt, [1.0, inf, 3.0])\n m = memoryview(ex)\n self.assertIn(1.0, m)\n self.assertIn(5e700, m)\n self.assertIn(3.0, m)\n\n ex = ndarray(9.0, [], format='f')\n m = memoryview(ex)\n self.assertRaises(TypeError, eval, \"9.0 in m\", locals())\n\n def test_memoryview_index(self):\n\n # ndim = 0\n ex = ndarray(12.5, shape=[], format='d')\n m = memoryview(ex)\n self.assertEqual(m[()], 12.5)\n self.assertEqual(m[...], m)\n self.assertEqual(m[...], ex)\n self.assertRaises(TypeError, m.__getitem__, 0)\n\n ex = ndarray((1,2,3), shape=[], format='iii')\n m = memoryview(ex)\n self.assertRaises(NotImplementedError, m.__getitem__, ())\n\n # range\n ex = ndarray(list(range(7)), shape=[7], flags=ND_WRITABLE)\n m = memoryview(ex)\n\n self.assertRaises(IndexError, m.__getitem__, 2**64)\n self.assertRaises(TypeError, m.__getitem__, 2.0)\n self.assertRaises(TypeError, m.__getitem__, 0.0)\n\n # out of bounds\n self.assertRaises(IndexError, m.__getitem__, -8)\n self.assertRaises(IndexError, m.__getitem__, 8)\n\n # Not implemented: multidimensional sub-views\n ex = ndarray(list(range(12)), shape=[3,4], flags=ND_WRITABLE)\n m = memoryview(ex)\n\n self.assertRaises(NotImplementedError, m.__getitem__, 0)\n self.assertRaises(NotImplementedError, m.__setitem__, 0, 9)\n self.assertRaises(NotImplementedError, m.__getitem__, 0)\n\n def test_memoryview_assign(self):\n\n # ndim = 0\n ex = ndarray(12.5, shape=[], format='f', flags=ND_WRITABLE)\n m = memoryview(ex)\n m[()] = 22.5\n self.assertEqual(m[()], 22.5)\n m[...] = 23.5\n self.assertEqual(m[()], 23.5)\n self.assertRaises(TypeError, m.__setitem__, 0, 24.7)\n\n # read-only\n ex = ndarray(list(range(7)), shape=[7])\n m = memoryview(ex)\n self.assertRaises(TypeError, m.__setitem__, 2, 10)\n\n # range\n ex = ndarray(list(range(7)), shape=[7], flags=ND_WRITABLE)\n m = memoryview(ex)\n\n self.assertRaises(IndexError, m.__setitem__, 2**64, 9)\n self.assertRaises(TypeError, m.__setitem__, 2.0, 10)\n self.assertRaises(TypeError, m.__setitem__, 0.0, 11)\n\n # out of bounds\n self.assertRaises(IndexError, m.__setitem__, -8, 20)\n self.assertRaises(IndexError, m.__setitem__, 8, 25)\n\n # pack_single() success:\n for fmt in fmtdict['@']:\n if fmt == 'c' or fmt == '?':\n continue\n ex = ndarray([1,2,3], shape=[3], format=fmt, flags=ND_WRITABLE)\n m = memoryview(ex)\n i = randrange(-3, 3)\n m[i] = 8\n self.assertEqual(m[i], 8)\n self.assertEqual(m[i], ex[i])\n\n ex = ndarray([b'1', b'2', b'3'], shape=[3], format='c',\n flags=ND_WRITABLE)\n m = memoryview(ex)\n m[2] = b'9'\n self.assertEqual(m[2], b'9')\n\n ex = ndarray([True, False, True], shape=[3], format='?',\n flags=ND_WRITABLE)\n m = memoryview(ex)\n m[1] = True\n self.assertEqual(m[1], True)\n\n # pack_single() exceptions:\n nd = ndarray([b'x'], shape=[1], format='c', flags=ND_WRITABLE)\n m = memoryview(nd)\n self.assertRaises(TypeError, m.__setitem__, 0, 100)\n\n ex = ndarray(list(range(120)), shape=[1,2,3,4,5], flags=ND_WRITABLE)\n m1 = memoryview(ex)\n\n for fmt, _range in fmtdict['@'].items():\n if (fmt == '?'): # PyObject_IsTrue() accepts anything\n continue\n if fmt == 'c': # special case tested above\n continue\n m2 = m1.cast(fmt)\n lo, hi = _range\n if fmt == 'd' or fmt == 'f':\n lo, hi = -2**1024, 2**1024\n if fmt != 'P': # PyLong_AsVoidPtr() accepts negative numbers\n self.assertRaises(ValueError, m2.__setitem__, 0, lo-1)\n self.assertRaises(TypeError, m2.__setitem__, 0, \"xyz\")\n self.assertRaises(ValueError, m2.__setitem__, 0, hi)\n\n # invalid item\n m2 = m1.cast('c')\n self.assertRaises(ValueError, m2.__setitem__, 0, b'\\xff\\xff')\n\n # format not implemented\n ex = ndarray(list(range(1)), shape=[1], format=\"xL\", flags=ND_WRITABLE)\n m = memoryview(ex)\n self.assertRaises(NotImplementedError, m.__setitem__, 0, 1)\n\n ex = ndarray([b'12345'], shape=[1], format=\"s\", flags=ND_WRITABLE)\n m = memoryview(ex)\n self.assertRaises(NotImplementedError, m.__setitem__, 0, 1)\n\n # Not implemented: multidimensional sub-views\n ex = ndarray(list(range(12)), shape=[3,4], flags=ND_WRITABLE)\n m = memoryview(ex)\n\n self.assertRaises(NotImplementedError, m.__setitem__, 0, [2, 3])\n\n def test_memoryview_slice(self):\n\n ex = ndarray(list(range(12)), shape=[12], flags=ND_WRITABLE)\n m = memoryview(ex)\n\n # zero step\n self.assertRaises(ValueError, m.__getitem__, slice(0,2,0))\n self.assertRaises(ValueError, m.__setitem__, slice(0,2,0),\n bytearray([1,2]))\n\n # invalid slice key\n self.assertRaises(TypeError, m.__getitem__, ())\n\n # multidimensional slices\n ex = ndarray(list(range(12)), shape=[12], flags=ND_WRITABLE)\n m = memoryview(ex)\n\n self.assertRaises(NotImplementedError, m.__getitem__,\n (slice(0,2,1), slice(0,2,1)))\n self.assertRaises(NotImplementedError, m.__setitem__,\n (slice(0,2,1), slice(0,2,1)), bytearray([1,2]))\n\n # invalid slice tuple\n self.assertRaises(TypeError, m.__getitem__, (slice(0,2,1), {}))\n self.assertRaises(TypeError, m.__setitem__, (slice(0,2,1), {}),\n bytearray([1,2]))\n\n # rvalue is not an exporter\n self.assertRaises(TypeError, m.__setitem__, slice(0,1,1), [1])\n\n # non-contiguous slice assignment\n for flags in (0, ND_PIL):\n ex1 = ndarray(list(range(12)), shape=[12], strides=[-1], offset=11,\n flags=ND_WRITABLE|flags)\n ex2 = ndarray(list(range(24)), shape=[12], strides=[2], flags=flags)\n m1 = memoryview(ex1)\n m2 = memoryview(ex2)\n\n ex1[2:5] = ex1[2:5]\n m1[2:5] = m2[2:5]\n\n self.assertEqual(m1, ex1)\n self.assertEqual(m2, ex2)\n\n ex1[1:3][::-1] = ex2[0:2][::1]\n m1[1:3][::-1] = m2[0:2][::1]\n\n self.assertEqual(m1, ex1)\n self.assertEqual(m2, ex2)\n\n ex1[4:1:-2][::-1] = ex1[1:4:2][::1]\n m1[4:1:-2][::-1] = m1[1:4:2][::1]\n\n self.assertEqual(m1, ex1)\n self.assertEqual(m2, ex2)\n\n def test_memoryview_array(self):\n\n def cmptest(testcase, a, b, m, singleitem):\n for i, _ in enumerate(a):\n ai = a[i]\n mi = m[i]\n testcase.assertEqual(ai, mi)\n a[i] = singleitem\n if singleitem != ai:\n testcase.assertNotEqual(a, m)\n testcase.assertNotEqual(a, b)\n else:\n testcase.assertEqual(a, m)\n testcase.assertEqual(a, b)\n m[i] = singleitem\n testcase.assertEqual(a, m)\n testcase.assertEqual(b, m)\n a[i] = ai\n m[i] = mi\n\n for n in range(1, 5):\n for fmt, items, singleitem in iter_format(n, 'array'):\n for lslice in genslices(n):\n for rslice in genslices(n):\n\n a = array.array(fmt, items)\n b = array.array(fmt, items)\n m = memoryview(b)\n\n self.assertEqual(m, a)\n self.assertEqual(m.tolist(), a.tolist())\n self.assertEqual(m.tobytes(), a.tobytes())\n self.assertEqual(len(m), len(a))\n\n cmptest(self, a, b, m, singleitem)\n\n array_err = None\n have_resize = None\n try:\n al = a[lslice]\n ar = a[rslice]\n a[lslice] = a[rslice]\n have_resize = len(al) != len(ar)\n except Exception as e:\n array_err = e.__class__\n\n m_err = None\n try:\n m[lslice] = m[rslice]\n except Exception as e:\n m_err = e.__class__\n\n if have_resize: # memoryview cannot change shape\n self.assertIs(m_err, ValueError)\n elif m_err or array_err:\n self.assertIs(m_err, array_err)\n else:\n self.assertEqual(m, a)\n self.assertEqual(m.tolist(), a.tolist())\n self.assertEqual(m.tobytes(), a.tobytes())\n cmptest(self, a, b, m, singleitem)\n\n def test_memoryview_compare_special_cases(self):\n\n a = array.array('L', [1, 2, 3])\n b = array.array('L', [1, 2, 7])\n\n # Ordering comparisons raise:\n v = memoryview(a)\n w = memoryview(b)\n for attr in ('__lt__', '__le__', '__gt__', '__ge__'):\n self.assertIs(getattr(v, attr)(w), NotImplemented)\n self.assertIs(getattr(a, attr)(v), NotImplemented)\n\n # Released views compare equal to themselves:\n v = memoryview(a)\n v.release()\n self.assertEqual(v, v)\n self.assertNotEqual(v, a)\n self.assertNotEqual(a, v)\n\n v = memoryview(a)\n w = memoryview(a)\n w.release()\n self.assertNotEqual(v, w)\n self.assertNotEqual(w, v)\n\n # Operand does not implement the buffer protocol:\n v = memoryview(a)\n self.assertNotEqual(v, [1, 2, 3])\n\n # NaNs\n nd = ndarray([(0, 0)], shape=[1], format='l x d x', flags=ND_WRITABLE)\n nd[0] = (-1, float('nan'))\n self.assertNotEqual(memoryview(nd), nd)\n\n # Depends on issue #15625: the struct module does not understand 'u'.\n a = array.array('u', 'xyz')\n v = memoryview(a)\n self.assertNotEqual(a, v)\n self.assertNotEqual(v, a)\n\n # Some ctypes format strings are unknown to the struct module.\n if ctypes:\n # format: \"T{>l:x:>l:y:}\"\n class BEPoint(ctypes.BigEndianStructure):\n _fields_ = [(\"x\", ctypes.c_long), (\"y\", ctypes.c_long)]\n point = BEPoint(100, 200)\n a = memoryview(point)\n b = memoryview(point)\n self.assertNotEqual(a, b)\n self.assertNotEqual(a, point)\n self.assertNotEqual(point, a)\n self.assertRaises(NotImplementedError, a.tolist)\n\n def test_memoryview_compare_ndim_zero(self):\n\n nd1 = ndarray(1729, shape=[], format='@L')\n nd2 = ndarray(1729, shape=[], format='L', flags=ND_WRITABLE)\n v = memoryview(nd1)\n w = memoryview(nd2)\n self.assertEqual(v, w)\n self.assertEqual(w, v)\n self.assertEqual(v, nd2)\n self.assertEqual(nd2, v)\n self.assertEqual(w, nd1)\n self.assertEqual(nd1, w)\n\n self.assertFalse(v.__ne__(w))\n self.assertFalse(w.__ne__(v))\n\n w[()] = 1728\n self.assertNotEqual(v, w)\n self.assertNotEqual(w, v)\n self.assertNotEqual(v, nd2)\n self.assertNotEqual(nd2, v)\n self.assertNotEqual(w, nd1)\n self.assertNotEqual(nd1, w)\n\n self.assertFalse(v.__eq__(w))\n self.assertFalse(w.__eq__(v))\n\n nd = ndarray(list(range(12)), shape=[12], flags=ND_WRITABLE|ND_PIL)\n ex = ndarray(list(range(12)), shape=[12], flags=ND_WRITABLE|ND_PIL)\n m = memoryview(ex)\n\n self.assertEqual(m, nd)\n m[9] = 100\n self.assertNotEqual(m, nd)\n\n # struct module: equal\n nd1 = ndarray((1729, 1.2, b'12345'), shape=[], format='Lf5s')\n nd2 = ndarray((1729, 1.2, b'12345'), shape=[], format='hf5s',\n flags=ND_WRITABLE)\n v = memoryview(nd1)\n w = memoryview(nd2)\n self.assertEqual(v, w)\n self.assertEqual(w, v)\n self.assertEqual(v, nd2)\n self.assertEqual(nd2, v)\n self.assertEqual(w, nd1)\n self.assertEqual(nd1, w)\n\n # struct module: not equal\n nd1 = ndarray((1729, 1.2, b'12345'), shape=[], format='Lf5s')\n nd2 = ndarray((-1729, 1.2, b'12345'), shape=[], format='hf5s',\n flags=ND_WRITABLE)\n v = memoryview(nd1)\n w = memoryview(nd2)\n self.assertNotEqual(v, w)\n self.assertNotEqual(w, v)\n self.assertNotEqual(v, nd2)\n self.assertNotEqual(nd2, v)\n self.assertNotEqual(w, nd1)\n self.assertNotEqual(nd1, w)\n self.assertEqual(v, nd1)\n self.assertEqual(w, nd2)\n\n def test_memoryview_compare_ndim_one(self):\n\n # contiguous\n nd1 = ndarray([-529, 576, -625, 676, -729], shape=[5], format='@h')\n nd2 = ndarray([-529, 576, -625, 676, 729], shape=[5], format='@h')\n v = memoryview(nd1)\n w = memoryview(nd2)\n\n self.assertEqual(v, nd1)\n self.assertEqual(w, nd2)\n self.assertNotEqual(v, nd2)\n self.assertNotEqual(w, nd1)\n self.assertNotEqual(v, w)\n\n # contiguous, struct module\n nd1 = ndarray([-529, 576, -625, 676, -729], shape=[5], format='<i')\n nd2 = ndarray([-529, 576, -625, 676, 729], shape=[5], format='>h')\n v = memoryview(nd1)\n w = memoryview(nd2)\n\n self.assertEqual(v, nd1)\n self.assertEqual(w, nd2)\n self.assertNotEqual(v, nd2)\n self.assertNotEqual(w, nd1)\n self.assertNotEqual(v, w)\n\n # non-contiguous\n nd1 = ndarray([-529, -625, -729], shape=[3], format='@h')\n nd2 = ndarray([-529, 576, -625, 676, -729], shape=[5], format='@h')\n v = memoryview(nd1)\n w = memoryview(nd2)\n\n self.assertEqual(v, nd2[::2])\n self.assertEqual(w[::2], nd1)\n self.assertEqual(v, w[::2])\n self.assertEqual(v[::-1], w[::-2])\n\n # non-contiguous, struct module\n nd1 = ndarray([-529, -625, -729], shape=[3], format='!h')\n nd2 = ndarray([-529, 576, -625, 676, -729], shape=[5], format='<l')\n v = memoryview(nd1)\n w = memoryview(nd2)\n\n self.assertEqual(v, nd2[::2])\n self.assertEqual(w[::2], nd1)\n self.assertEqual(v, w[::2])\n self.assertEqual(v[::-1], w[::-2])\n\n # non-contiguous, suboffsets\n nd1 = ndarray([-529, -625, -729], shape=[3], format='@h')\n nd2 = ndarray([-529, 576, -625, 676, -729], shape=[5], format='@h',\n flags=ND_PIL)\n v = memoryview(nd1)\n w = memoryview(nd2)\n\n self.assertEqual(v, nd2[::2])\n self.assertEqual(w[::2], nd1)\n self.assertEqual(v, w[::2])\n self.assertEqual(v[::-1], w[::-2])\n\n # non-contiguous, suboffsets, struct module\n nd1 = ndarray([-529, -625, -729], shape=[3], format='h 0c')\n nd2 = ndarray([-529, 576, -625, 676, -729], shape=[5], format='> h',\n flags=ND_PIL)\n v = memoryview(nd1)\n w = memoryview(nd2)\n\n self.assertEqual(v, nd2[::2])\n self.assertEqual(w[::2], nd1)\n self.assertEqual(v, w[::2])\n self.assertEqual(v[::-1], w[::-2])\n\n def test_memoryview_compare_zero_shape(self):\n\n # zeros in shape\n nd1 = ndarray([900, 961], shape=[0], format='@h')\n nd2 = ndarray([-900, -961], shape=[0], format='@h')\n v = memoryview(nd1)\n w = memoryview(nd2)\n\n self.assertEqual(v, nd1)\n self.assertEqual(w, nd2)\n self.assertEqual(v, nd2)\n self.assertEqual(w, nd1)\n self.assertEqual(v, w)\n\n # zeros in shape, struct module\n nd1 = ndarray([900, 961], shape=[0], format='= h0c')\n nd2 = ndarray([-900, -961], shape=[0], format='@ i')\n v = memoryview(nd1)\n w = memoryview(nd2)\n\n self.assertEqual(v, nd1)\n self.assertEqual(w, nd2)\n self.assertEqual(v, nd2)\n self.assertEqual(w, nd1)\n self.assertEqual(v, w)\n\n def test_memoryview_compare_zero_strides(self):\n\n # zero strides\n nd1 = ndarray([900, 900, 900, 900], shape=[4], format='@L')\n nd2 = ndarray([900], shape=[4], strides=[0], format='L')\n v = memoryview(nd1)\n w = memoryview(nd2)\n\n self.assertEqual(v, nd1)\n self.assertEqual(w, nd2)\n self.assertEqual(v, nd2)\n self.assertEqual(w, nd1)\n self.assertEqual(v, w)\n\n # zero strides, struct module\n nd1 = ndarray([(900, 900)]*4, shape=[4], format='@ Li')\n nd2 = ndarray([(900, 900)], shape=[4], strides=[0], format='!L h')\n v = memoryview(nd1)\n w = memoryview(nd2)\n\n self.assertEqual(v, nd1)\n self.assertEqual(w, nd2)\n self.assertEqual(v, nd2)\n self.assertEqual(w, nd1)\n self.assertEqual(v, w)\n\n def test_memoryview_compare_random_formats(self):\n\n # random single character native formats\n n = 10\n for char in fmtdict['@m']:\n fmt, items, singleitem = randitems(n, 'memoryview', '@', char)\n for flags in (0, ND_PIL):\n nd = ndarray(items, shape=[n], format=fmt, flags=flags)\n m = memoryview(nd)\n self.assertEqual(m, nd)\n\n nd = nd[::-3]\n m = memoryview(nd)\n self.assertEqual(m, nd)\n\n # random formats\n n = 10\n for _ in range(100):\n fmt, items, singleitem = randitems(n)\n for flags in (0, ND_PIL):\n nd = ndarray(items, shape=[n], format=fmt, flags=flags)\n m = memoryview(nd)\n self.assertEqual(m, nd)\n\n nd = nd[::-3]\n m = memoryview(nd)\n self.assertEqual(m, nd)\n\n def test_memoryview_compare_multidim_c(self):\n\n # C-contiguous, different values\n nd1 = ndarray(list(range(-15, 15)), shape=[3, 2, 5], format='@h')\n nd2 = ndarray(list(range(0, 30)), shape=[3, 2, 5], format='@h')\n v = memoryview(nd1)\n w = memoryview(nd2)\n\n self.assertEqual(v, nd1)\n self.assertEqual(w, nd2)\n self.assertNotEqual(v, nd2)\n self.assertNotEqual(w, nd1)\n self.assertNotEqual(v, w)\n\n # C-contiguous, different values, struct module\n nd1 = ndarray([(0, 1, 2)]*30, shape=[3, 2, 5], format='=f q xxL')\n nd2 = ndarray([(-1.2, 1, 2)]*30, shape=[3, 2, 5], format='< f 2Q')\n v = memoryview(nd1)\n w = memoryview(nd2)\n\n self.assertEqual(v, nd1)\n self.assertEqual(w, nd2)\n self.assertNotEqual(v, nd2)\n self.assertNotEqual(w, nd1)\n self.assertNotEqual(v, w)\n\n # C-contiguous, different shape\n nd1 = ndarray(list(range(30)), shape=[2, 3, 5], format='L')\n nd2 = ndarray(list(range(30)), shape=[3, 2, 5], format='L')\n v = memoryview(nd1)\n w = memoryview(nd2)\n\n self.assertEqual(v, nd1)\n self.assertEqual(w, nd2)\n self.assertNotEqual(v, nd2)\n self.assertNotEqual(w, nd1)\n self.assertNotEqual(v, w)\n\n # C-contiguous, different shape, struct module\n nd1 = ndarray([(0, 1, 2)]*21, shape=[3, 7], format='! b B xL')\n nd2 = ndarray([(0, 1, 2)]*21, shape=[7, 3], format='= Qx l xxL')\n v = memoryview(nd1)\n w = memoryview(nd2)\n\n self.assertEqual(v, nd1)\n self.assertEqual(w, nd2)\n self.assertNotEqual(v, nd2)\n self.assertNotEqual(w, nd1)\n self.assertNotEqual(v, w)\n\n # C-contiguous, different format, struct module\n nd1 = ndarray(list(range(30)), shape=[2, 3, 5], format='L')\n nd2 = ndarray(list(range(30)), shape=[2, 3, 5], format='l')\n v = memoryview(nd1)\n w = memoryview(nd2)\n\n self.assertEqual(v, nd1)\n self.assertEqual(w, nd2)\n self.assertEqual(v, nd2)\n self.assertEqual(w, nd1)\n self.assertEqual(v, w)\n\n def test_memoryview_compare_multidim_fortran(self):\n\n # Fortran-contiguous, different values\n nd1 = ndarray(list(range(-15, 15)), shape=[5, 2, 3], format='@h',\n flags=ND_FORTRAN)\n nd2 = ndarray(list(range(0, 30)), shape=[5, 2, 3], format='@h',\n flags=ND_FORTRAN)\n v = memoryview(nd1)\n w = memoryview(nd2)\n\n self.assertEqual(v, nd1)\n self.assertEqual(w, nd2)\n self.assertNotEqual(v, nd2)\n self.assertNotEqual(w, nd1)\n self.assertNotEqual(v, w)\n\n # Fortran-contiguous, different values, struct module\n nd1 = ndarray([(2**64-1, -1)]*6, shape=[2, 3], format='=Qq',\n flags=ND_FORTRAN)\n nd2 = ndarray([(-1, 2**64-1)]*6, shape=[2, 3], format='=qQ',\n flags=ND_FORTRAN)\n v = memoryview(nd1)\n w = memoryview(nd2)\n\n self.assertEqual(v, nd1)\n self.assertEqual(w, nd2)\n self.assertNotEqual(v, nd2)\n self.assertNotEqual(w, nd1)\n self.assertNotEqual(v, w)\n\n # Fortran-contiguous, different shape\n nd1 = ndarray(list(range(-15, 15)), shape=[2, 3, 5], format='l',\n flags=ND_FORTRAN)\n nd2 = ndarray(list(range(-15, 15)), shape=[3, 2, 5], format='l',\n flags=ND_FORTRAN)\n v = memoryview(nd1)\n w = memoryview(nd2)\n\n self.assertEqual(v, nd1)\n self.assertEqual(w, nd2)\n self.assertNotEqual(v, nd2)\n self.assertNotEqual(w, nd1)\n self.assertNotEqual(v, w)\n\n # Fortran-contiguous, different shape, struct module\n nd1 = ndarray(list(range(-15, 15)), shape=[2, 3, 5], format='0ll',\n flags=ND_FORTRAN)\n nd2 = ndarray(list(range(-15, 15)), shape=[3, 2, 5], format='l',\n flags=ND_FORTRAN)\n v = memoryview(nd1)\n w = memoryview(nd2)\n\n self.assertEqual(v, nd1)\n self.assertEqual(w, nd2)\n self.assertNotEqual(v, nd2)\n self.assertNotEqual(w, nd1)\n self.assertNotEqual(v, w)\n\n # Fortran-contiguous, different format, struct module\n nd1 = ndarray(list(range(30)), shape=[5, 2, 3], format='@h',\n flags=ND_FORTRAN)\n nd2 = ndarray(list(range(30)), shape=[5, 2, 3], format='@b',\n flags=ND_FORTRAN)\n v = memoryview(nd1)\n w = memoryview(nd2)\n\n self.assertEqual(v, nd1)\n self.assertEqual(w, nd2)\n self.assertEqual(v, nd2)\n self.assertEqual(w, nd1)\n self.assertEqual(v, w)\n\n def test_memoryview_compare_multidim_mixed(self):\n\n # mixed C/Fortran contiguous\n lst1 = list(range(-15, 15))\n lst2 = transpose(lst1, [3, 2, 5])\n nd1 = ndarray(lst1, shape=[3, 2, 5], format='@l')\n nd2 = ndarray(lst2, shape=[3, 2, 5], format='l', flags=ND_FORTRAN)\n v = memoryview(nd1)\n w = memoryview(nd2)\n\n self.assertEqual(v, nd1)\n self.assertEqual(w, nd2)\n self.assertEqual(v, w)\n\n # mixed C/Fortran contiguous, struct module\n lst1 = [(-3.3, -22, b'x')]*30\n lst1[5] = (-2.2, -22, b'x')\n lst2 = transpose(lst1, [3, 2, 5])\n nd1 = ndarray(lst1, shape=[3, 2, 5], format='d b c')\n nd2 = ndarray(lst2, shape=[3, 2, 5], format='d h c', flags=ND_FORTRAN)\n v = memoryview(nd1)\n w = memoryview(nd2)\n\n self.assertEqual(v, nd1)\n self.assertEqual(w, nd2)\n self.assertEqual(v, w)\n\n # different values, non-contiguous\n ex1 = ndarray(list(range(40)), shape=[5, 8], format='@I')\n nd1 = ex1[3:1:-1, ::-2]\n ex2 = ndarray(list(range(40)), shape=[5, 8], format='I')\n nd2 = ex2[1:3:1, ::-2]\n v = memoryview(nd1)\n w = memoryview(nd2)\n\n self.assertEqual(v, nd1)\n self.assertEqual(w, nd2)\n self.assertNotEqual(v, nd2)\n self.assertNotEqual(w, nd1)\n self.assertNotEqual(v, w)\n\n # same values, non-contiguous, struct module\n ex1 = ndarray([(2**31-1, -2**31)]*22, shape=[11, 2], format='=ii')\n nd1 = ex1[3:1:-1, ::-2]\n ex2 = ndarray([(2**31-1, -2**31)]*22, shape=[11, 2], format='>ii')\n nd2 = ex2[1:3:1, ::-2]\n v = memoryview(nd1)\n w = memoryview(nd2)\n\n self.assertEqual(v, nd1)\n self.assertEqual(w, nd2)\n self.assertEqual(v, nd2)\n self.assertEqual(w, nd1)\n self.assertEqual(v, w)\n\n # different shape\n ex1 = ndarray(list(range(30)), shape=[2, 3, 5], format='b')\n nd1 = ex1[1:3:, ::-2]\n nd2 = ndarray(list(range(30)), shape=[3, 2, 5], format='b')\n nd2 = ex2[1:3:, ::-2]\n v = memoryview(nd1)\n w = memoryview(nd2)\n\n self.assertEqual(v, nd1)\n self.assertEqual(w, nd2)\n self.assertNotEqual(v, nd2)\n self.assertNotEqual(w, nd1)\n self.assertNotEqual(v, w)\n\n # different shape, struct module\n ex1 = ndarray(list(range(30)), shape=[2, 3, 5], format='B')\n nd1 = ex1[1:3:, ::-2]\n nd2 = ndarray(list(range(30)), shape=[3, 2, 5], format='b')\n nd2 = ex2[1:3:, ::-2]\n v = memoryview(nd1)\n w = memoryview(nd2)\n\n self.assertEqual(v, nd1)\n self.assertEqual(w, nd2)\n self.assertNotEqual(v, nd2)\n self.assertNotEqual(w, nd1)\n self.assertNotEqual(v, w)\n\n # different format, struct module\n ex1 = ndarray([(2, b'123')]*30, shape=[5, 3, 2], format='b3s')\n nd1 = ex1[1:3:, ::-2]\n nd2 = ndarray([(2, b'123')]*30, shape=[5, 3, 2], format='i3s')\n nd2 = ex2[1:3:, ::-2]\n v = memoryview(nd1)\n w = memoryview(nd2)\n\n self.assertEqual(v, nd1)\n self.assertEqual(w, nd2)\n self.assertNotEqual(v, nd2)\n self.assertNotEqual(w, nd1)\n self.assertNotEqual(v, w)\n\n def test_memoryview_compare_multidim_zero_shape(self):\n\n # zeros in shape\n nd1 = ndarray(list(range(30)), shape=[0, 3, 2], format='i')\n nd2 = ndarray(list(range(30)), shape=[5, 0, 2], format='@i')\n v = memoryview(nd1)\n w = memoryview(nd2)\n\n self.assertEqual(v, nd1)\n self.assertEqual(w, nd2)\n self.assertNotEqual(v, nd2)\n self.assertNotEqual(w, nd1)\n self.assertNotEqual(v, w)\n\n # zeros in shape, struct module\n nd1 = ndarray(list(range(30)), shape=[0, 3, 2], format='i')\n nd2 = ndarray(list(range(30)), shape=[5, 0, 2], format='@i')\n v = memoryview(nd1)\n w = memoryview(nd2)\n\n self.assertEqual(v, nd1)\n self.assertEqual(w, nd2)\n self.assertNotEqual(v, nd2)\n self.assertNotEqual(w, nd1)\n self.assertNotEqual(v, w)\n\n def test_memoryview_compare_multidim_zero_strides(self):\n\n # zero strides\n nd1 = ndarray([900]*80, shape=[4, 5, 4], format='@L')\n nd2 = ndarray([900], shape=[4, 5, 4], strides=[0, 0, 0], format='L')\n v = memoryview(nd1)\n w = memoryview(nd2)\n\n self.assertEqual(v, nd1)\n self.assertEqual(w, nd2)\n self.assertEqual(v, nd2)\n self.assertEqual(w, nd1)\n self.assertEqual(v, w)\n self.assertEqual(v.tolist(), w.tolist())\n\n # zero strides, struct module\n nd1 = ndarray([(1, 2)]*10, shape=[2, 5], format='=lQ')\n nd2 = ndarray([(1, 2)], shape=[2, 5], strides=[0, 0], format='<lQ')\n v = memoryview(nd1)\n w = memoryview(nd2)\n\n self.assertEqual(v, nd1)\n self.assertEqual(w, nd2)\n self.assertEqual(v, nd2)\n self.assertEqual(w, nd1)\n self.assertEqual(v, w)\n\n def test_memoryview_compare_multidim_suboffsets(self):\n\n # suboffsets\n ex1 = ndarray(list(range(40)), shape=[5, 8], format='@I')\n nd1 = ex1[3:1:-1, ::-2]\n ex2 = ndarray(list(range(40)), shape=[5, 8], format='I', flags=ND_PIL)\n nd2 = ex2[1:3:1, ::-2]\n v = memoryview(nd1)\n w = memoryview(nd2)\n\n self.assertEqual(v, nd1)\n self.assertEqual(w, nd2)\n self.assertNotEqual(v, nd2)\n self.assertNotEqual(w, nd1)\n self.assertNotEqual(v, w)\n\n # suboffsets, struct module\n ex1 = ndarray([(2**64-1, -1)]*40, shape=[5, 8], format='=Qq',\n flags=ND_WRITABLE)\n ex1[2][7] = (1, -2)\n nd1 = ex1[3:1:-1, ::-2]\n\n ex2 = ndarray([(2**64-1, -1)]*40, shape=[5, 8], format='>Qq',\n flags=ND_PIL|ND_WRITABLE)\n ex2[2][7] = (1, -2)\n nd2 = ex2[1:3:1, ::-2]\n\n v = memoryview(nd1)\n w = memoryview(nd2)\n\n self.assertEqual(v, nd1)\n self.assertEqual(w, nd2)\n self.assertEqual(v, nd2)\n self.assertEqual(w, nd1)\n self.assertEqual(v, w)\n\n # suboffsets, different shape\n ex1 = ndarray(list(range(30)), shape=[2, 3, 5], format='b',\n flags=ND_PIL)\n nd1 = ex1[1:3:, ::-2]\n nd2 = ndarray(list(range(30)), shape=[3, 2, 5], format='b')\n nd2 = ex2[1:3:, ::-2]\n v = memoryview(nd1)\n w = memoryview(nd2)\n\n self.assertEqual(v, nd1)\n self.assertEqual(w, nd2)\n self.assertNotEqual(v, nd2)\n self.assertNotEqual(w, nd1)\n self.assertNotEqual(v, w)\n\n # suboffsets, different shape, struct module\n ex1 = ndarray([(2**8-1, -1)]*40, shape=[2, 3, 5], format='Bb',\n flags=ND_PIL|ND_WRITABLE)\n nd1 = ex1[1:2:, ::-2]\n\n ex2 = ndarray([(2**8-1, -1)]*40, shape=[3, 2, 5], format='Bb')\n nd2 = ex2[1:2:, ::-2]\n\n v = memoryview(nd1)\n w = memoryview(nd2)\n\n self.assertEqual(v, nd1)\n self.assertEqual(w, nd2)\n self.assertNotEqual(v, nd2)\n self.assertNotEqual(w, nd1)\n self.assertNotEqual(v, w)\n\n # suboffsets, different format\n ex1 = ndarray(list(range(30)), shape=[5, 3, 2], format='i', flags=ND_PIL)\n nd1 = ex1[1:3:, ::-2]\n ex2 = ndarray(list(range(30)), shape=[5, 3, 2], format='@I', flags=ND_PIL)\n nd2 = ex2[1:3:, ::-2]\n v = memoryview(nd1)\n w = memoryview(nd2)\n\n self.assertEqual(v, nd1)\n self.assertEqual(w, nd2)\n self.assertEqual(v, nd2)\n self.assertEqual(w, nd1)\n self.assertEqual(v, w)\n\n # suboffsets, different format, struct module\n ex1 = ndarray([(b'hello', b'', 1)]*27, shape=[3, 3, 3], format='5s0sP',\n flags=ND_PIL|ND_WRITABLE)\n ex1[1][2][2] = (b'sushi', b'', 1)\n nd1 = ex1[1:3:, ::-2]\n\n ex2 = ndarray([(b'hello', b'', 1)]*27, shape=[3, 3, 3], format='5s0sP',\n flags=ND_PIL|ND_WRITABLE)\n ex1[1][2][2] = (b'sushi', b'', 1)\n nd2 = ex2[1:3:, ::-2]\n\n v = memoryview(nd1)\n w = memoryview(nd2)\n\n self.assertEqual(v, nd1)\n self.assertEqual(w, nd2)\n self.assertNotEqual(v, nd2)\n self.assertNotEqual(w, nd1)\n self.assertNotEqual(v, w)\n\n # initialize mixed C/Fortran + suboffsets\n lst1 = list(range(-15, 15))\n lst2 = transpose(lst1, [3, 2, 5])\n nd1 = ndarray(lst1, shape=[3, 2, 5], format='@l', flags=ND_PIL)\n nd2 = ndarray(lst2, shape=[3, 2, 5], format='l', flags=ND_FORTRAN|ND_PIL)\n v = memoryview(nd1)\n w = memoryview(nd2)\n\n self.assertEqual(v, nd1)\n self.assertEqual(w, nd2)\n self.assertEqual(v, w)\n\n # initialize mixed C/Fortran + suboffsets, struct module\n lst1 = [(b'sashimi', b'sliced', 20.05)]*30\n lst1[11] = (b'ramen', b'spicy', 9.45)\n lst2 = transpose(lst1, [3, 2, 5])\n\n nd1 = ndarray(lst1, shape=[3, 2, 5], format='< 10p 9p d', flags=ND_PIL)\n nd2 = ndarray(lst2, shape=[3, 2, 5], format='> 10p 9p d',\n flags=ND_FORTRAN|ND_PIL)\n v = memoryview(nd1)\n w = memoryview(nd2)\n\n self.assertEqual(v, nd1)\n self.assertEqual(w, nd2)\n self.assertEqual(v, w)\n\n def test_memoryview_compare_not_equal(self):\n\n # items not equal\n for byteorder in ['=', '<', '>', '!']:\n x = ndarray([2**63]*120, shape=[3,5,2,2,2], format=byteorder+'Q')\n y = ndarray([2**63]*120, shape=[3,5,2,2,2], format=byteorder+'Q',\n flags=ND_WRITABLE|ND_FORTRAN)\n y[2][3][1][1][1] = 1\n a = memoryview(x)\n b = memoryview(y)\n self.assertEqual(a, x)\n self.assertEqual(b, y)\n self.assertNotEqual(a, b)\n self.assertNotEqual(a, y)\n self.assertNotEqual(b, x)\n\n x = ndarray([(2**63, 2**31, 2**15)]*120, shape=[3,5,2,2,2],\n format=byteorder+'QLH')\n y = ndarray([(2**63, 2**31, 2**15)]*120, shape=[3,5,2,2,2],\n format=byteorder+'QLH', flags=ND_WRITABLE|ND_FORTRAN)\n y[2][3][1][1][1] = (1, 1, 1)\n a = memoryview(x)\n b = memoryview(y)\n self.assertEqual(a, x)\n self.assertEqual(b, y)\n self.assertNotEqual(a, b)\n self.assertNotEqual(a, y)\n self.assertNotEqual(b, x)\n\n def test_memoryview_check_released(self):\n\n a = array.array('d', [1.1, 2.2, 3.3])\n\n m = memoryview(a)\n m.release()\n\n # PyMemoryView_FromObject()\n self.assertRaises(ValueError, memoryview, m)\n # memoryview.cast()\n self.assertRaises(ValueError, m.cast, 'c')\n # getbuffer()\n self.assertRaises(ValueError, ndarray, m)\n # memoryview.tolist()\n self.assertRaises(ValueError, m.tolist)\n # memoryview.tobytes()\n self.assertRaises(ValueError, m.tobytes)\n # sequence\n self.assertRaises(ValueError, eval, \"1.0 in m\", locals())\n # subscript\n self.assertRaises(ValueError, m.__getitem__, 0)\n # assignment\n self.assertRaises(ValueError, m.__setitem__, 0, 1)\n\n for attr in ('obj', 'nbytes', 'readonly', 'itemsize', 'format', 'ndim',\n 'shape', 'strides', 'suboffsets', 'c_contiguous',\n 'f_contiguous', 'contiguous'):\n self.assertRaises(ValueError, m.__getattribute__, attr)\n\n # richcompare\n b = array.array('d', [1.1, 2.2, 3.3])\n m1 = memoryview(a)\n m2 = memoryview(b)\n\n self.assertEqual(m1, m2)\n m1.release()\n self.assertNotEqual(m1, m2)\n self.assertNotEqual(m1, a)\n self.assertEqual(m1, m1)\n\n def test_memoryview_tobytes(self):\n # Many implicit tests are already in self.verify().\n\n t = (-529, 576, -625, 676, -729)\n\n nd = ndarray(t, shape=[5], format='@h')\n m = memoryview(nd)\n self.assertEqual(m, nd)\n self.assertEqual(m.tobytes(), nd.tobytes())\n\n nd = ndarray([t], shape=[1], format='>hQiLl')\n m = memoryview(nd)\n self.assertEqual(m, nd)\n self.assertEqual(m.tobytes(), nd.tobytes())\n\n nd = ndarray([t for _ in range(12)], shape=[2,2,3], format='=hQiLl')\n m = memoryview(nd)\n self.assertEqual(m, nd)\n self.assertEqual(m.tobytes(), nd.tobytes())\n\n nd = ndarray([t for _ in range(120)], shape=[5,2,2,3,2],\n format='<hQiLl')\n m = memoryview(nd)\n self.assertEqual(m, nd)\n self.assertEqual(m.tobytes(), nd.tobytes())\n\n # Unknown formats are handled: tobytes() purely depends on itemsize.\n if ctypes:\n # format: \"T{>l:x:>l:y:}\"\n class BEPoint(ctypes.BigEndianStructure):\n _fields_ = [(\"x\", ctypes.c_long), (\"y\", ctypes.c_long)]\n point = BEPoint(100, 200)\n a = memoryview(point)\n self.assertEqual(a.tobytes(), bytes(point))\n\n def test_memoryview_get_contiguous(self):\n # Many implicit tests are already in self.verify().\n\n # no buffer interface\n self.assertRaises(TypeError, get_contiguous, {}, PyBUF_READ, 'F')\n\n # writable request to read-only object\n self.assertRaises(BufferError, get_contiguous, b'x', PyBUF_WRITE, 'C')\n\n # writable request to non-contiguous object\n nd = ndarray([1, 2, 3], shape=[2], strides=[2])\n self.assertRaises(BufferError, get_contiguous, nd, PyBUF_WRITE, 'A')\n\n # scalar, read-only request from read-only exporter\n nd = ndarray(9, shape=(), format=\"L\")\n for order in ['C', 'F', 'A']:\n m = get_contiguous(nd, PyBUF_READ, order)\n self.assertEqual(m, nd)\n self.assertEqual(m[()], 9)\n\n # scalar, read-only request from writable exporter\n nd = ndarray(9, shape=(), format=\"L\", flags=ND_WRITABLE)\n for order in ['C', 'F', 'A']:\n m = get_contiguous(nd, PyBUF_READ, order)\n self.assertEqual(m, nd)\n self.assertEqual(m[()], 9)\n\n # scalar, writable request\n for order in ['C', 'F', 'A']:\n nd[()] = 9\n m = get_contiguous(nd, PyBUF_WRITE, order)\n self.assertEqual(m, nd)\n self.assertEqual(m[()], 9)\n\n m[()] = 10\n self.assertEqual(m[()], 10)\n self.assertEqual(nd[()], 10)\n\n # zeros in shape\n nd = ndarray([1], shape=[0], format=\"L\", flags=ND_WRITABLE)\n for order in ['C', 'F', 'A']:\n m = get_contiguous(nd, PyBUF_READ, order)\n self.assertRaises(IndexError, m.__getitem__, 0)\n self.assertEqual(m, nd)\n self.assertEqual(m.tolist(), [])\n\n nd = ndarray(list(range(8)), shape=[2, 0, 7], format=\"L\",\n flags=ND_WRITABLE)\n for order in ['C', 'F', 'A']:\n m = get_contiguous(nd, PyBUF_READ, order)\n self.assertEqual(ndarray(m).tolist(), [[], []])\n\n # one-dimensional\n nd = ndarray([1], shape=[1], format=\"h\", flags=ND_WRITABLE)\n for order in ['C', 'F', 'A']:\n m = get_contiguous(nd, PyBUF_WRITE, order)\n self.assertEqual(m, nd)\n self.assertEqual(m.tolist(), nd.tolist())\n\n nd = ndarray([1, 2, 3], shape=[3], format=\"b\", flags=ND_WRITABLE)\n for order in ['C', 'F', 'A']:\n m = get_contiguous(nd, PyBUF_WRITE, order)\n self.assertEqual(m, nd)\n self.assertEqual(m.tolist(), nd.tolist())\n\n # one-dimensional, non-contiguous\n nd = ndarray([1, 2, 3], shape=[2], strides=[2], flags=ND_WRITABLE)\n for order in ['C', 'F', 'A']:\n m = get_contiguous(nd, PyBUF_READ, order)\n self.assertEqual(m, nd)\n self.assertEqual(m.tolist(), nd.tolist())\n self.assertRaises(TypeError, m.__setitem__, 1, 20)\n self.assertEqual(m[1], 3)\n self.assertEqual(nd[1], 3)\n\n nd = nd[::-1]\n for order in ['C', 'F', 'A']:\n m = get_contiguous(nd, PyBUF_READ, order)\n self.assertEqual(m, nd)\n self.assertEqual(m.tolist(), nd.tolist())\n self.assertRaises(TypeError, m.__setitem__, 1, 20)\n self.assertEqual(m[1], 1)\n self.assertEqual(nd[1], 1)\n\n # multi-dimensional, contiguous input\n nd = ndarray(list(range(12)), shape=[3, 4], flags=ND_WRITABLE)\n for order in ['C', 'A']:\n m = get_contiguous(nd, PyBUF_WRITE, order)\n self.assertEqual(ndarray(m).tolist(), nd.tolist())\n\n self.assertRaises(BufferError, get_contiguous, nd, PyBUF_WRITE, 'F')\n m = get_contiguous(nd, PyBUF_READ, order)\n self.assertEqual(ndarray(m).tolist(), nd.tolist())\n\n nd = ndarray(list(range(12)), shape=[3, 4],\n flags=ND_WRITABLE|ND_FORTRAN)\n for order in ['F', 'A']:\n m = get_contiguous(nd, PyBUF_WRITE, order)\n self.assertEqual(ndarray(m).tolist(), nd.tolist())\n\n self.assertRaises(BufferError, get_contiguous, nd, PyBUF_WRITE, 'C')\n m = get_contiguous(nd, PyBUF_READ, order)\n self.assertEqual(ndarray(m).tolist(), nd.tolist())\n\n # multi-dimensional, non-contiguous input\n nd = ndarray(list(range(12)), shape=[3, 4], flags=ND_WRITABLE|ND_PIL)\n for order in ['C', 'F', 'A']:\n self.assertRaises(BufferError, get_contiguous, nd, PyBUF_WRITE,\n order)\n m = get_contiguous(nd, PyBUF_READ, order)\n self.assertEqual(ndarray(m).tolist(), nd.tolist())\n\n # flags\n nd = ndarray([1,2,3,4,5], shape=[3], strides=[2])\n m = get_contiguous(nd, PyBUF_READ, 'C')\n self.assertTrue(m.c_contiguous)\n\n def test_memoryview_serializing(self):\n\n # C-contiguous\n size = struct.calcsize('i')\n a = array.array('i', [1,2,3,4,5])\n m = memoryview(a)\n buf = io.BytesIO(m)\n b = bytearray(5*size)\n buf.readinto(b)\n self.assertEqual(m.tobytes(), b)\n\n # C-contiguous, multi-dimensional\n size = struct.calcsize('L')\n nd = ndarray(list(range(12)), shape=[2,3,2], format=\"L\")\n m = memoryview(nd)\n buf = io.BytesIO(m)\n b = bytearray(2*3*2*size)\n buf.readinto(b)\n self.assertEqual(m.tobytes(), b)\n\n # Fortran contiguous, multi-dimensional\n #size = struct.calcsize('L')\n #nd = ndarray(list(range(12)), shape=[2,3,2], format=\"L\",\n # flags=ND_FORTRAN)\n #m = memoryview(nd)\n #buf = io.BytesIO(m)\n #b = bytearray(2*3*2*size)\n #buf.readinto(b)\n #self.assertEqual(m.tobytes(), b)\n\n def test_memoryview_hash(self):\n\n # bytes exporter\n b = bytes(list(range(12)))\n m = memoryview(b)\n self.assertEqual(hash(b), hash(m))\n\n # C-contiguous\n mc = m.cast('c', shape=[3,4])\n self.assertEqual(hash(mc), hash(b))\n\n # non-contiguous\n mx = m[::-2]\n b = bytes(list(range(12))[::-2])\n self.assertEqual(hash(mx), hash(b))\n\n # Fortran contiguous\n nd = ndarray(list(range(30)), shape=[3,2,5], flags=ND_FORTRAN)\n m = memoryview(nd)\n self.assertEqual(hash(m), hash(nd))\n\n # multi-dimensional slice\n nd = ndarray(list(range(30)), shape=[3,2,5])\n x = nd[::2, ::, ::-1]\n m = memoryview(x)\n self.assertEqual(hash(m), hash(x))\n\n # multi-dimensional slice with suboffsets\n nd = ndarray(list(range(30)), shape=[2,5,3], flags=ND_PIL)\n x = nd[::2, ::, ::-1]\n m = memoryview(x)\n self.assertEqual(hash(m), hash(x))\n\n # equality-hash invariant\n x = ndarray(list(range(12)), shape=[12], format='B')\n a = memoryview(x)\n\n y = ndarray(list(range(12)), shape=[12], format='b')\n b = memoryview(y)\n\n self.assertEqual(a, b)\n self.assertEqual(hash(a), hash(b))\n\n # non-byte formats\n nd = ndarray(list(range(12)), shape=[2,2,3], format='L')\n m = memoryview(nd)\n self.assertRaises(ValueError, m.__hash__)\n\n nd = ndarray(list(range(-6, 6)), shape=[2,2,3], format='h')\n m = memoryview(nd)\n self.assertRaises(ValueError, m.__hash__)\n\n nd = ndarray(list(range(12)), shape=[2,2,3], format='= L')\n m = memoryview(nd)\n self.assertRaises(ValueError, m.__hash__)\n\n nd = ndarray(list(range(-6, 6)), shape=[2,2,3], format='< h')\n m = memoryview(nd)\n self.assertRaises(ValueError, m.__hash__)\n\n def test_memoryview_release(self):\n\n # Create re-exporter from getbuffer(memoryview), then release the view.\n a = bytearray([1,2,3])\n m = memoryview(a)\n nd = ndarray(m) # re-exporter\n self.assertRaises(BufferError, m.release)\n del nd\n m.release()\n\n a = bytearray([1,2,3])\n m = memoryview(a)\n nd1 = ndarray(m, getbuf=PyBUF_FULL_RO, flags=ND_REDIRECT)\n nd2 = ndarray(nd1, getbuf=PyBUF_FULL_RO, flags=ND_REDIRECT)\n self.assertIs(nd2.obj, m)\n self.assertRaises(BufferError, m.release)\n del nd1, nd2\n m.release()\n\n # chained views\n a = bytearray([1,2,3])\n m1 = memoryview(a)\n m2 = memoryview(m1)\n nd = ndarray(m2) # re-exporter\n m1.release()\n self.assertRaises(BufferError, m2.release)\n del nd\n m2.release()\n\n a = bytearray([1,2,3])\n m1 = memoryview(a)\n m2 = memoryview(m1)\n nd1 = ndarray(m2, getbuf=PyBUF_FULL_RO, flags=ND_REDIRECT)\n nd2 = ndarray(nd1, getbuf=PyBUF_FULL_RO, flags=ND_REDIRECT)\n self.assertIs(nd2.obj, m2)\n m1.release()\n self.assertRaises(BufferError, m2.release)\n del nd1, nd2\n m2.release()\n\n # Allow changing layout while buffers are exported.\n nd = ndarray([1,2,3], shape=[3], flags=ND_VAREXPORT)\n m1 = memoryview(nd)\n\n nd.push([4,5,6,7,8], shape=[5]) # mutate nd\n m2 = memoryview(nd)\n\n x = memoryview(m1)\n self.assertEqual(x.tolist(), m1.tolist())\n\n y = memoryview(m2)\n self.assertEqual(y.tolist(), m2.tolist())\n self.assertEqual(y.tolist(), nd.tolist())\n m2.release()\n y.release()\n\n nd.pop() # pop the current view\n self.assertEqual(x.tolist(), nd.tolist())\n\n del nd\n m1.release()\n x.release()\n\n # If multiple memoryviews share the same managed buffer, implicit\n # release() in the context manager's __exit__() method should still\n # work.\n def catch22(b):\n with memoryview(b) as m2:\n pass\n\n x = bytearray(b'123')\n with memoryview(x) as m1:\n catch22(m1)\n self.assertEqual(m1[0], ord(b'1'))\n\n x = ndarray(list(range(12)), shape=[2,2,3], format='l')\n y = ndarray(x, getbuf=PyBUF_FULL_RO, flags=ND_REDIRECT)\n z = ndarray(y, getbuf=PyBUF_FULL_RO, flags=ND_REDIRECT)\n self.assertIs(z.obj, x)\n with memoryview(z) as m:\n catch22(m)\n self.assertEqual(m[0:1].tolist(), [[[0, 1, 2], [3, 4, 5]]])\n\n # Test garbage collection.\n for flags in (0, ND_REDIRECT):\n x = bytearray(b'123')\n with memoryview(x) as m1:\n del x\n y = ndarray(m1, getbuf=PyBUF_FULL_RO, flags=flags)\n with memoryview(y) as m2:\n del y\n z = ndarray(m2, getbuf=PyBUF_FULL_RO, flags=flags)\n with memoryview(z) as m3:\n del z\n catch22(m3)\n catch22(m2)\n catch22(m1)\n self.assertEqual(m1[0], ord(b'1'))\n self.assertEqual(m2[1], ord(b'2'))\n self.assertEqual(m3[2], ord(b'3'))\n del m3\n del m2\n del m1\n\n x = bytearray(b'123')\n with memoryview(x) as m1:\n del x\n y = ndarray(m1, getbuf=PyBUF_FULL_RO, flags=flags)\n with memoryview(y) as m2:\n del y\n z = ndarray(m2, getbuf=PyBUF_FULL_RO, flags=flags)\n with memoryview(z) as m3:\n del z\n catch22(m1)\n catch22(m2)\n catch22(m3)\n self.assertEqual(m1[0], ord(b'1'))\n self.assertEqual(m2[1], ord(b'2'))\n self.assertEqual(m3[2], ord(b'3'))\n del m1, m2, m3\n\n # memoryview.release() fails if the view has exported buffers.\n x = bytearray(b'123')\n with self.assertRaises(BufferError):\n with memoryview(x) as m:\n ex = ndarray(m)\n m[0] == ord(b'1')\n\n def test_memoryview_redirect(self):\n\n nd = ndarray([1.0 * x for x in range(12)], shape=[12], format='d')\n a = array.array('d', [1.0 * x for x in range(12)])\n\n for x in (nd, a):\n y = ndarray(x, getbuf=PyBUF_FULL_RO, flags=ND_REDIRECT)\n z = ndarray(y, getbuf=PyBUF_FULL_RO, flags=ND_REDIRECT)\n m = memoryview(z)\n\n self.assertIs(y.obj, x)\n self.assertIs(z.obj, x)\n self.assertIs(m.obj, x)\n\n self.assertEqual(m, x)\n self.assertEqual(m, y)\n self.assertEqual(m, z)\n\n self.assertEqual(m[1:3], x[1:3])\n self.assertEqual(m[1:3], y[1:3])\n self.assertEqual(m[1:3], z[1:3])\n del y, z\n self.assertEqual(m[1:3], x[1:3])\n\n def test_memoryview_from_static_exporter(self):\n\n fmt = 'B'\n lst = [0,1,2,3,4,5,6,7,8,9,10,11]\n\n # exceptions\n self.assertRaises(TypeError, staticarray, 1, 2, 3)\n\n # view.obj==x\n x = staticarray()\n y = memoryview(x)\n self.verify(y, obj=x,\n itemsize=1, fmt=fmt, readonly=1,\n ndim=1, shape=[12], strides=[1],\n lst=lst)\n for i in range(12):\n self.assertEqual(y[i], i)\n del x\n del y\n\n x = staticarray()\n y = memoryview(x)\n del y\n del x\n\n x = staticarray()\n y = ndarray(x, getbuf=PyBUF_FULL_RO)\n z = ndarray(y, getbuf=PyBUF_FULL_RO)\n m = memoryview(z)\n self.assertIs(y.obj, x)\n self.assertIs(m.obj, z)\n self.verify(m, obj=z,\n itemsize=1, fmt=fmt, readonly=1,\n ndim=1, shape=[12], strides=[1],\n lst=lst)\n del x, y, z, m\n\n x = staticarray()\n y = ndarray(x, getbuf=PyBUF_FULL_RO, flags=ND_REDIRECT)\n z = ndarray(y, getbuf=PyBUF_FULL_RO, flags=ND_REDIRECT)\n m = memoryview(z)\n self.assertIs(y.obj, x)\n self.assertIs(z.obj, x)\n self.assertIs(m.obj, x)\n self.verify(m, obj=x,\n itemsize=1, fmt=fmt, readonly=1,\n ndim=1, shape=[12], strides=[1],\n lst=lst)\n del x, y, z, m\n\n # view.obj==NULL\n x = staticarray(legacy_mode=True)\n y = memoryview(x)\n self.verify(y, obj=None,\n itemsize=1, fmt=fmt, readonly=1,\n ndim=1, shape=[12], strides=[1],\n lst=lst)\n for i in range(12):\n self.assertEqual(y[i], i)\n del x\n del y\n\n x = staticarray(legacy_mode=True)\n y = memoryview(x)\n del y\n del x\n\n x = staticarray(legacy_mode=True)\n y = ndarray(x, getbuf=PyBUF_FULL_RO)\n z = ndarray(y, getbuf=PyBUF_FULL_RO)\n m = memoryview(z)\n self.assertIs(y.obj, None)\n self.assertIs(m.obj, z)\n self.verify(m, obj=z,\n itemsize=1, fmt=fmt, readonly=1,\n ndim=1, shape=[12], strides=[1],\n lst=lst)\n del x, y, z, m\n\n x = staticarray(legacy_mode=True)\n y = ndarray(x, getbuf=PyBUF_FULL_RO, flags=ND_REDIRECT)\n z = ndarray(y, getbuf=PyBUF_FULL_RO, flags=ND_REDIRECT)\n m = memoryview(z)\n # Clearly setting view.obj==NULL is inferior, since it\n # messes up the redirection chain:\n self.assertIs(y.obj, None)\n self.assertIs(z.obj, y)\n self.assertIs(m.obj, y)\n self.verify(m, obj=y,\n itemsize=1, fmt=fmt, readonly=1,\n ndim=1, shape=[12], strides=[1],\n lst=lst)\n del x, y, z, m\n\n def test_memoryview_getbuffer_undefined(self):\n\n # getbufferproc does not adhere to the new documentation\n nd = ndarray([1,2,3], [3], flags=ND_GETBUF_FAIL|ND_GETBUF_UNDEFINED)\n self.assertRaises(BufferError, memoryview, nd)\n\n def test_issue_7385(self):\n x = ndarray([1,2,3], shape=[3], flags=ND_GETBUF_FAIL)\n self.assertRaises(BufferError, memoryview, x)\n\n\nif __name__ == \"__main__\":\n unittest.main()\n"
] | [
[
"numpy.ndarray"
]
] |
jmc529/BentoML | [
"96c1ec9e486d98930e24bbbac5b2991a6d416f97"
] | [
"tests/_internal/bento_services/pytorch_classifier.py"
] | [
"import numpy\nimport torch # pylint: disable=import-error\n\nimport bentoml\nfrom bentoml.adapters import DataframeInput\nfrom bentoml.pytorch import PytorchModelArtifact\n\n\[email protected](infer_pip_packages=True)\[email protected]([PytorchModelArtifact(\"model\")])\nclass PytorchClassifier(bentoml.BentoService):\n @bentoml.api(input=DataframeInput(), batch=True)\n def predict(self, df):\n input_data = df.to_numpy().astype(numpy.float32)\n input_tensor = torch.from_numpy(input_data)\n output = self.artifacts.model(input_tensor)\n\n return output.unsqueeze(dim=0).item()\n"
] | [
[
"torch.from_numpy"
]
] |
lidanh/game-of-thrones-tweets-generator | [
"92921073fd3e0812d785f92dbc2f5e0f3588e15b"
] | [
"create_batch.py"
] | [
"from __future__ import print_function\n\nfrom random import randint\nimport os\n\nimport tensorflow as tf\nfrom six.moves import cPickle\n\nfrom rnnmodel import RNNModel\n\nVOCABULARY_FILE = 'words_vocabulary.pickle'\n\nCONFIGURATION_FILE = 'configuration.pickle'\n\n\ndef main():\n\n\t# typical tweet length\n\tnumber_of_words = randint(8,12)\n\n\tcreate_batch(model_snapshots_dir='model_snapshots', number_of_words=number_of_words)\n\n\ndef create_batch(model_snapshots_dir, number_of_words):\n\n\t# Load original configuration\n\twith open(os.path.join(model_snapshots_dir, CONFIGURATION_FILE), 'rb') as configuration_file:\n\t\tsaved_args = cPickle.load(configuration_file)\n\n\t# For sampling use batch and sequence size of 1\n\tsaved_args.batch_size = 1\n\tsaved_args.seq_length = 1\n\n\t# Init with the original arguments that were given to the model\n\tmodel = RNNModel(saved_args.rnn_size, saved_args.num_layers, saved_args.batch_size,saved_args.seq_length,\n\t\t\t\t\t saved_args.vocabulary_size, saved_args.gradient_clip, sample=True)\n\n\t# Load the words and vocabulary created originally\n\twith open(os.path.join(model_snapshots_dir, VOCABULARY_FILE), 'rb') as vocabulary_file:\n\t\twords, vocabulary = cPickle.load(vocabulary_file)\n\n\n\twith tf.Session() as session:\n\n\t\t# Init tensorflow\n\t\ttf.initialize_all_variables().run()\n\n\t\t# Load saved data and generate the sample\n\t\tsaver = tf.train.Saver(tf.all_variables())\n\n\t\t# Make sure that the model is saved as expected\n\t\tcheckpoint = tf.train.get_checkpoint_state(model_snapshots_dir)\n\n\t\t# load the tensorflow data to a session, and run the model on it\n\t\tif checkpoint and checkpoint.model_checkpoint_path:\n\t\t\tsaver.restore(session, checkpoint.model_checkpoint_path) # restore the LSTM\n\t\t\tsample = model.sample(session, words, vocabulary, number_of_words)\n\t\t\tprint(sample)\n\t\telse:\n\t\t\tprint('Could not load the saved data.\\n'\n\t\t\t\t 'Did you run train_rnn_model.py?')\n\n\nif __name__ == '__main__':\n\tmain()\n"
] | [
[
"tensorflow.train.get_checkpoint_state",
"tensorflow.all_variables",
"tensorflow.initialize_all_variables",
"tensorflow.Session"
]
] |
power4454/studio | [
"d8115a8f483edab8d674f567e277863ea1bb3f79"
] | [
"function/python/brightics/function/statistics/correlation.py"
] | [
"import matplotlib.pyplot as plt\nimport seaborn as sns\nfrom brightics.common.report import ReportBuilder, strip_margin, plt2MD,\\\n pandasDF2MD\nfrom scipy import stats\nfrom brightics.common.groupby import _function_by_group\nfrom brightics.common.utils import check_required_parameters\nimport pandas as pd\n\n\ndef correlation(table, group_by=None, **params):\n check_required_parameters(_correlation, params, ['table'])\n if group_by is not None:\n return _function_by_group(_correlation, table, group_by=group_by, **params)\n else:\n return _correlation(table, **params)\n\n\ndef _correlation(table, vars, method='pearson', height=2.5, corr_prec=2):\n size = len(vars)\n \n s_default = plt.rcParams['lines.markersize'] ** 2.\n scatter_kws = {\"s\": s_default * height / 6.4}\n \n result_arr = []\n \n for i in range(size): \n for j in range(i):\n if method == 'pearson':\n r, p = stats.pearsonr(table[vars[i]], table[vars[j]])\n elif method == 'spearman':\n r, p = stats.spearmanr(table[vars[i]], table[vars[j]])\n elif method == 'kendal':\n r, p = stats.kendalltau(table[vars[i]], table[vars[j]])\n \n result_arr.append([vars[i], vars[j], r, p]) \n \n df_result = pd.DataFrame(result_arr, columns=['x', 'y', 'corr', 'p_value'])\n \n def corr(x, y, **kwargs):\n if kwargs['method'] == 'pearson':\n r, p = stats.pearsonr(x, y)\n elif kwargs['method'] == 'spearman':\n r, p = stats.spearmanr(x, y)\n elif kwargs['method'] == 'kendal':\n r, p = stats.kendalltau(x, y)\n \n p_stars = ''\n if p <= 0.05:\n p_stars = '*'\n if p <= 0.01:\n p_stars = '**'\n if p <= 0.001:\n p_stars = '***'\n \n corr_text = '{:.{prec}f}'.format(r, prec=corr_prec)\n font_size = abs(r) * 15 * 2 / corr_prec + 5\n ax = plt.gca()\n ax.annotate(corr_text, [.5, .5, ], xycoords=\"axes fraction\",\n ha='center', va='center', fontsize=font_size * height)\n ax.annotate(p_stars, xy=(0.65, 0.6), xycoords=ax.transAxes, color='red', fontsize=17 * height)\n \n g = sns.PairGrid(table, vars=vars, height=height)\n g.map_diag(sns.distplot)\n if method == 'pearson':\n g.map_lower(sns.regplot, scatter_kws=scatter_kws)\n else:\n g.map_lower(sns.regplot, lowess=True, scatter_kws=scatter_kws) \n g.map_upper(corr, method=method)\n \n fig_corr = plt2MD(plt)\n plt.clf()\n \n rb = ReportBuilder()\n rb.addMD(strip_margin(\n \"\"\" ## Correlation Results\n | ### Correlation Matrix\n | {fig_corr}\n |\n | ### Correlation Table\n | {table}\n \"\"\".format(fig_corr=fig_corr, table=pandasDF2MD(df_result))))\n \n params = {'vars':vars, 'method':method, 'height':height}\n \n res = dict()\n res['params'] = params\n res['corr_table'] = df_result\n res['report'] = rb.get()\n \n return {'result': res}\n"
] | [
[
"matplotlib.pyplot.gca",
"scipy.stats.pearsonr",
"pandas.DataFrame",
"matplotlib.pyplot.clf",
"scipy.stats.kendalltau",
"scipy.stats.spearmanr"
]
] |
UCIDataLab/PP_dialog_models | [
"fb290bd55578e045eac6f36c6e650fcbb9104a9f"
] | [
"mhddata.py"
] | [
"__author__ = 'Jihyun Park'\n__email__ = '[email protected]'\n\nimport os\nfrom collections import defaultdict\n\nimport numpy as np\nimport pandas as pd\ntry:\n import cPickle as cp\nexcept ImportError:\n import pickle as cp\nimport re\n\nfrom sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizer\n\nimport preprocess as preproc\n\n\nclass MHDData():\n \"\"\"\n Base class for MHD Data\n\n Vocabulary Related Variables\n ----------------------------\n n_vocab : int\n Size of vocabulary\n (including noun phrases and N-grams, depending on the parameters)\n vocabulary : set[str]\n stopwords_all : set[str]\n A set of stopwords, including the user-defined ones and the ones that are\n very rare or common (those are taken out by min_df and max_df parameters)\n stopwords : set[str]\n A set of user-defined stopwords\n nps : set[str]\n A set of noun phrases\n np2cnt : dict[str, int]\n A dictionary that has noun phrases to its counts\n\n\n Label Related Variables\n -----------------------\n n_labels : int\n Number of labels after cleaning/merging\n\n lid2lab_all : list[str]\n A list of labels. Indices are the label IDs.\n '_all' means that these are the list of labels 'before' cleaning.\n Cleaned (merged) version of this label is 'lid2lab'.\n Labels are topic code, which ranges from '1' ~ '39'.\n lab2lid_all : dict[str,int]\n Reverse map of lid2lab_all\n lid2lab : list[str]\n The same type of information as lid2lab_all 'after' cleaning/merging the data.\n Mapping between label ID/index to label can be different from that of lid2lab_all.\n lab2lid : dict[str,int]\n Reverse map of lid2lab\n lab2name : dict[str, str]\n Label to shortnames. 'lab' refers to 'topic code', which ranges from '1'~'39'.\n lid2name : dict[int, str]\n Label ID/IDX (after cleaning labels) to its shortname mapping\n lab2ltr : dict[str, str]\n Label (topic code) to topic letters. Topic letters range from 'A' ~ 'G'\n ltid2lt : list\n A list of Topic letters. Where indices are the IDs of those topic letters\n lt2ltid : dict[str, int]\n Reverse mapping of ltid2lt\n label_mappings: dict[str, str]\n Label mappings\n\n\n Corpus related variables\n ------------------------\n * uid : unique identifier of an utterance starts from 0\n * sid : unique identifier of a session. 5 digits.\n * tt/talkturn : index of each talkturn/utterance within each session.\n This field exists in the original data, and it starts from 0 at\n the beginning of each session.\n * segid : unique identifier of a segment. A segment is a consecutive list of\n utterances that share the same label.\n\n n_utters : int\n Number of utterances that we are using.\n\n uid2sstt : dict[int, dict[int, int]]\n Dictionary that maps utterance ID to its [sessionID, TalkturnID]\n sstt2uid : dict[dict[int, int], int]\n Dictionary that maps [sessionID, talkturnID] to the utterance IDs\n uid2segid : dict[int, int]\n Maps to utterance ID to segment ID\n segid2uids : list[int]\n List that maps segment ID to the list of utterance IDs who belongs to the segment.\n\n corpus_df : pd.DataFrame\n Pandas dataframe that has all the data. (except for the cleaned version of labels)\n corpus_txt : list[str]\n List of utterances (flattened), where each index is the utterance ID\n It is a mapping from uid to cleaned text of that utterance.\n\n segid2lab_all : dict[int, str]\n Mapping between the segment id to the label (topic code), before label cleaning\n segid2lab : dict[int, str]\n Same as above, after label cleaning.\n uid2lab_all : list[str]\n Mapping between the utterance id to the label (topic code), before label cleaning\n uid2lab : list[str]\n same as above, after label cleaning\n uid2lid : list[int]\n Mapping between the utterance ID to the label ID\n\n\n Others\n ------\n spkrid2spkr : list[str]\n A List that maps from speaker ID/index to speaker\n spkr2spkrid : dict[str,int]\n Reverse map of .spkrid2spkr\n valid_sids, valid_segids, valid_uids : list[int]\n List of session, segment, and utterance IDs that are valid (have labels)\n\n \"\"\"\n\n def __init__(self, data_file, nouns_only=False, ignore_case=True,\n remove_numbers=False, sub_numbers=True,\n stopwords_dir=\"./stopwordlists\", proper_nouns_dir=\"./stopwordlists\",\n label_mappings=None, ngram_range=(1,2), max_np_len=3, min_wlen=1,\n min_dfreq=0.0001, max_dfreq=0.9, min_sfreq=5, sep=\"|\",\n token_pattern=r\"(?u)[A-Za-z\\?\\!\\-\\.']+\", verbose=1,\n corpus_pkl='./corpus.pkl', label_pkl='./label.pkl', vocab_pkl='./vocab.pkl'):\n \"\"\"\n\n Parameters\n ----------\n data_file : str\n File path to the data\n nouns_only : bool\n Only include nouns\n ignore_case : bool\n True if ignoring cases (transformed to all lower case, default)\n remove_numbers : bool\n Remove all digits if True, default is False\n sub_numbers : bool\n Rather than removing all digits, substitute them to symbol -num-. default True\n stopwords_dir : str\n Path to the stopwords directory\n proper_nouns_dir : str\n Path to the proper nouns directory\n label_mappings : dict or None\n Label mappings that can be use for label merging/cleaning.\n If None (default), rare labels are mapped to the 'Other' label (topic code: '37')\n ngram_range : tuple\n The lower and upper boundary of the range of n-values for different n-grams\n to be extracted. (Maximum length of noun phrase can be different from this.)\n max_np_len : int\n Maximum length of noun phrases to be considered.\n min_wlen : int\n Minimum word length of an utterance to be considered.\n If an utterance has word length less than 'min_wlen', the utterance is skipped.\n min_dfreq : float\n float in range [0.0, 1.0]\n When building the vocabulary ignore terms that have\n a document frequency strictly lower than the given threshold.\n The parameter represents a proportion of documents, integer absolute counts.\n NOTE: Here, each utterance is treated as a document, therefore very small value would\n still reduce the size of vocabulary. Because the utterances are very short therefore most of the words have very\n small document frequencies.\n max_dfreq : float\n float in range [0.0, 1.0]\n When building the vocabulary ignore terms that have a document frequency strictly higher than\n the given threshold (corpus-specific stop words).\n The parameter represents a proportion of documents, integer absolute counts.\n min_sfreq : int\n If there are labels that appear less than this number of sessions,\n the labels are merged to the 'other' label (topic code: '37')\n token_pattern : str\n Regular expression denoting what constitutes a 'token'.\n verbose : int in range [0,3]\n The level of verbosity. Larger value means more verbosity.\n corpus_pkl : str\n Path to the pickle file that saves corpus related data.\n label_pkl : str\n Path to the pickle file that saves label related data.\n vocab_pkl : str\n Path to the pickle file that saves vocab related data.\n \"\"\"\n self.verbose = verbose\n\n self.data_file = data_file\n self.nouns_only = nouns_only\n\n self.ngram_range = ngram_range\n self.min_dfreq = min_dfreq\n self.max_dfreq = max_dfreq\n\n if self.nouns_only:\n self.max_np_len = 1\n else:\n self.max_np_len = min(2, max_np_len)\n self.max_wlen = max(self.ngram_range[-1], self.max_np_len)\n self.token_pattern = token_pattern\n\n self.stopwords = preproc.get_stopwords(stopwords_dir=stopwords_dir)\n self.stopwords_all = self.stopwords.union() # do union for copying\n\n self.load_corpus(data_file, sep=sep, min_wcnt=min_wlen,\n min_np_len=self.max_np_len, max_np_len=max_np_len,\n token_pattern=token_pattern,\n ignore_case=ignore_case, remove_numbers=remove_numbers,\n sub_numbers=sub_numbers, proper_nouns_dir=proper_nouns_dir,\n corpus_pkl=corpus_pkl, label_pkl=label_pkl, vocab_pkl=vocab_pkl)\n\n self.assign_labnames()\n self.assign_spkr_codes()\n\n def assign_labnames(self):\n \"\"\"\n Assigns short names for each topic code.\n Original topic code ranges from 1~39.\n Topic codes are called as 'lab', and they are treated as strings.\n \"\"\"\n shortnames = ['BiomedHistorySymptom', 'MusSkePain', 'DizzyFallMemoryDentHearVision',\n 'GynGenitoUrinary', 'Prognosis', 'TestDiagnostics', 'TherapeuticIntervention',\n 'Medication', 'PreventiveCare', 'Diet',\n 'Weight', 'Exercise', 'Alcohol', 'Sex', 'Cigarette',\n 'OtherAddictions', 'Sleep', 'Death', 'Bereavement', 'PainSuffering',\n 'Depression', 'GeneralAnxieties', 'HealthCareSystem', 'ActivityDailyLiving',\n 'WorkLeisureActivity', 'Unemployment', 'MoneyBenefits', 'Caregiver', 'HomeEnv', 'Family',\n 'Religion', 'Age', 'LivingWillAdvanceCarePlanning', 'MDLife', 'MDPT-Relationship',\n 'SmallTalk', 'Other', 'VisitFlowManagement', 'PhysicalExam']\n self.lab2name = {str(i + 1): shortnames[i] for i in range(len(shortnames))}\n self.lab2ltr = {'1': 'A', '2': 'A', '3': 'A', '4': 'A', '5': 'A', '6': 'A', '7': 'A',\n '8': 'A', '9': 'A', '10': 'B', '11': 'B', '12': 'B', '13': 'B', '14': 'B',\n '15': 'B', '16': 'B', '17': 'B', '18': 'C', '19': 'C', '20': 'C', '21': 'C',\n '22': 'C', '23': 'D', '24': 'D', '25': 'D', '26': 'D', '27': 'D', '28': 'D',\n '29': 'D', '30': 'D', '31': 'D', '32': 'D', '33': 'D', '34': 'E', '35': 'E',\n '36': 'F', '37': 'F', '38': 'G', '39': 'G'}\n\n def assign_spkr_codes(self):\n \"\"\"\n Assigns speaker codes.\n \"\"\"\n self.spkrid2spkr = [\"MD\", \"PT\", \"OTHER\", \"RA\", \"RN\"]\n self.spkr2spkrid = {sp: i for i, sp in enumerate(self.spkrid2spkr)}\n\n def load_corpus(self, corpus_file, sep, min_wcnt=1, min_np_len=2, max_np_len=3,\n token_pattern=r\"(?u)\\b\\w[A-Za-z']*\\b\",\n ignore_case=True, remove_numbers=False, sub_numbers=True, parser=None, stemmer_type=None,\n proper_nouns_dir=\"./stopwordlists\",\n corpus_pkl='./corpus.pkl', label_pkl='./labels.pkl', vocab_pkl='./vocab.pkl'):\n \"\"\"\n Train and test will have slightly different process.\n \"\"\"\n pass\n\n def _save_lab_pkl(self, lid2lab_all, segid2lt, label_pkl):\n \"\"\"\n Saves label related data to a pickle file. (before cleaning)\n Also creates ltid2lt, lt2ltid, lab2lid_all, lid2lab_all\n\n Parameters\n ----------\n lid2lab_all : list\n Label id to label mapping before cleaning\n segid2lt : list\n Segment id to the topic letters\n label_pkl : str\n File path to the pickle file which the label data will be saved to\n \"\"\"\n lid2lab_all = sorted(list(lid2lab_all))\n lab2lid_all = {ll: i for i, ll in enumerate(lid2lab_all)}\n\n self.ltid2lt = sorted(list(set(segid2lt.values())))\n self.lt2ltid = {ll: i for i, ll in enumerate(self.ltid2lt)}\n\n self.lab2lid_all = lab2lid_all\n self.lid2lab_all = lid2lab_all\n\n lab_data_to_save = (lid2lab_all, lab2lid_all, self.ltid2lt, self.lt2ltid)\n with open(label_pkl, 'wb') as f:\n cp.dump(lab_data_to_save, f, protocol=cp.HIGHEST_PROTOCOL)\n\n def _save_vocab_pkl(self, nps, vocab, stw_all, vocab_pkl):\n \"\"\"\n Saves vocab related data to a pickle file.\n also assigns self.vocabulary and self.stopwords_all\n\n Parameters\n ----------\n nps : set\n Set of noun phrases\n vocab : set\n set of vocabularies\n stw_all : set\n Set of all the stopwords (including user-defined vocabs + vocabs by doc freq cutoffs)\n vocab_pkl : str\n File path to the pickle file which the vocab data will be saved to\n \"\"\"\n if self.nouns_only:\n nps_dict = {}\n for i, nounp in enumerate(nps):\n nps_dict[nounp] = i\n self.vocabulary = nps_dict\n else:\n self.vocabulary = vocab\n self.stopwords_all = stw_all\n\n vocab_data_to_save = (self.vocabulary, stw_all)\n with open(vocab_pkl, 'wb') as f:\n cp.dump(vocab_data_to_save, f, protocol=cp.HIGHEST_PROTOCOL)\n\n def _save_corpus_pkl(self, corpus_df, nps, np2cnt, uid2sstt, sstt2uid,\n uid2segid, segid2uids, sid2labs_all, segid2lab_all,\n segid2lt, uid2lab_all, corpus_pkl):\n \"\"\"\n Saves corpus related data to a pickle file.\n Also assigns bunch of variables as member variables.\n\n For parameter information, please refer to the top of this code,\n description of MHDData class.\n\n Parameters\n ----------\n corpus_df : pd.DataFrame\n nps : set[str]\n np2cnt : dict[str, int]\n uid2sstt : list[int, dict[int, int]]\n sstt2uid : dict[dict[int, int], int]\n uid2segid : list[int]\n segid2uids : dict[int]\n sid2labs_all : dict[int, str]\n segid2lab_all : dict[str] or defaultdict(str)\n segid2lt : dict[str] or defaultdict(str)\n uid2lab_all : list[str]\n corpus_pkl : str\n File path to the pickle file which the corpus related data will be saved to\n\n \"\"\"\n self.nps = nps\n self.np2cnt = np2cnt\n self.uid2sstt = uid2sstt\n self.sstt2uid = sstt2uid\n self.uid2segid = uid2segid\n self.segid2uids = segid2uids\n self.corpus_txt = list(corpus_df.text_cleaned)\n\n self.segid2lab_all = segid2lab_all\n self.segid2lt = segid2lt\n self.sid2labs_all = sid2labs_all\n self.uid2lab_all = uid2lab_all\n\n data_to_save = (corpus_df, nps, np2cnt, uid2sstt, sstt2uid, uid2segid, segid2uids,\n sid2labs_all, segid2lab_all, segid2lt, uid2lab_all)\n if not os.path.isdir(os.path.dirname(corpus_pkl)):\n os.makedirs(os.path.dirname(corpus_pkl))\n with open(corpus_pkl, 'wb') as f:\n cp.dump(data_to_save, f, protocol=cp.HIGHEST_PROTOCOL)\n\n def _load_vocab_pkl(self, vocab_pkl):\n # if the pickle file exists, load the vocab\n if os.path.exists(vocab_pkl):\n if self.verbose > 0:\n print(\"Loading the vocabulary file from \" + vocab_pkl)\n print(\" (Delete the file if you want to re-generate the vocabulary)\")\n vocab_obj = cp.load(open(vocab_pkl))\n if len(vocab_obj) > 2:\n self.vocabulary = vocab_obj\n elif len(vocab_obj) == 2:\n self.vocabulary, self.stopwords_all = vocab_obj\n else:\n return False\n return True\n else:\n return False\n\n def _load_corpus_pkl(self, corpus_pkl):\n # if the pickle file exists, load the corpus\n if os.path.exists(corpus_pkl):\n if self.verbose > 0:\n print(\"Loading the processed file from \" + corpus_pkl)\n print(\" (Delete the file if you want to re-process the corpus)\")\n corpus_data_list = cp.load(open(corpus_pkl, 'rb'))\n if len(corpus_data_list) == 11:\n self.corpus_df, self.nps, self.np2cnt, self.uid2sstt, \\\n self.sstt2uid, self.uid2segid, self.segid2uids, \\\n self.sid2labs_all, self.segid2lab_all, self.segid2lt, self.uid2lab_all = corpus_data_list\n\n self.corpus_txt = list(self.corpus_df.text_cleaned)\n else:\n print(\"ERROR: Cannot load the corpus file.\" + corpus_pkl + \" has different format!\")\n return False\n return True\n else:\n return False\n\n def _load_lab_pkl(self, label_pkl):\n if os.path.exists(label_pkl):\n if self.verbose > 0:\n print(\"Loading labels file from \" + label_pkl)\n print(\" (Delete the file if you want to re-generate the labels)\")\n\n lab_data_list = cp.load(open(label_pkl, 'rb'))\n if len(lab_data_list) == 4:\n self.lid2lab_all, self.lab2lid_all, \\\n self.ltid2lt, self.lt2ltid = lab_data_list\n else:\n print(\"ERROR: Cannot load the label file.\" + label_pkl + \" has different format!\")\n return False\n return True\n else:\n return False\n\n def clean_labels(self, min_sess_freq=20, label_mappings=None):\n pass\n\n def _update_session_labs(self, sid2labs, lab2lid_new, label_mappings, code_other):\n \"\"\"\n Used inside of clean_labels.\n Update the old set of session-level label information\n to the new using 'label_mappings'\n \"\"\"\n sid2labs_new = {}\n sid2lidarr_new = {}\n n_labels = len(lab2lid_new)\n for sessid in sid2labs:\n labarr = np.zeros(n_labels, dtype=np.int8)\n sid2labs_new[sessid] = []\n for lab in sid2labs[sessid]:\n if label_mappings.get(lab, None) is not None:\n lab = label_mappings[lab]\n lid = lab2lid_new.get(lab, lab2lid_new[code_other])\n # To avoid appending the same txtlabels\n if labarr[lid] == 0:\n labarr[lid] = 1\n sid2labs_new[sessid].append(lab)\n # only save the sessions with labels\n if np.sum(labarr) > 0:\n sid2lidarr_new[sessid] = labarr\n return sid2labs_new, sid2lidarr_new\n\n def _update_segment_labs(self, segid2lab, lab2lid_new, segid2lt,\n label_mappings, code_other):\n \"\"\"\n Used inside of clean_labels.\n Update the old set of segment-level label information\n to the new using 'label_mappings'\n \"\"\"\n segid2lab_new = {}\n segid2lid_new = {}\n segid2lidarr = {}\n segid2ltid = {}\n n_labels = len(lab2lid_new)\n for segid in segid2lab:\n labarr = np.zeros(n_labels)\n lab = segid2lab[segid]\n\n # also update tletter\n tletter = segid2lt[segid]\n tltid = self.lt2ltid[tletter]\n\n if label_mappings.get(lab, None) is not None:\n lab = label_mappings[lab]\n lid = lab2lid_new.get(lab, lab2lid_new[code_other])\n\n segid2ltid[segid] = tltid\n segid2lab_new[segid] = lab\n labarr[lid] = 1\n segid2lidarr[segid] = labarr\n segid2lid_new[segid] = lid\n return segid2lab_new, segid2lid_new, segid2lidarr, segid2ltid\n\n def _update_utter_labs(self, uid2lab, lab2lid_new, label_mappings, code_other):\n \"\"\"\n Used inside of clean_labels.\n Update the old set of utterance-level label information\n to the new using 'label_mappings'\n \"\"\"\n uid2lab_new = []\n uid2lid_new = []\n for uid, lab in enumerate(uid2lab):\n if label_mappings.get(lab, None) is not None:\n lab = label_mappings[lab]\n lid = lab2lid_new.get(lab, lab2lid_new[code_other])\n uid2lab_new.append(lab)\n uid2lid_new.append(lid)\n return uid2lab_new, uid2lid_new\n\n def get_valid_data(self):\n pass\n\n def get_spkr_code(self, spkr, include_ra=False, include_nurse=False):\n \"\"\"\n Given a string, returns an ID of the speaker.\n String that describes speaker can be a bit noisy in the raw data,\n this function cleans and assigns the ID.\n\n Parameters\n ----------\n spkr : str\n Description of a speaker, or a speaker type in string.\n (e.g. PT, patient, clinician, RA, etc.)\n include_ra : bool\n True if you want to treat RA as a separate speaker\n Default is False. If False, the RA will have the code for OTHERS.\n include_nurse : bool\n True if you want to treat RN as a separate speaker\n Default is False. If False, the RN will have the code for OTHERS.\n\n Returns\n -------\n int\n ID of a speaker\n\n \"\"\"\n spkr = re.sub(r\"[^A-Za-z]\", \"\", spkr)\n if re.match(r\".*P[Tt].*\", spkr) or re.match(r\"[Pp]atient\", spkr):\n return self.spkr2spkrid[\"PT\"]\n elif re.match(r\"clinician\", spkr) or re.match(r\".*MD.*\", spkr):\n return self.spkr2spkrid[\"MD\"]\n else:\n if include_ra and re.match(r\".*RA.*\", spkr):\n return self.spkr2spkrid[\"RA\"]\n if include_nurse and (re.match(r\".*NURSE.*\", spkr) or re.match(r\".*RN.*\", spkr)):\n return self.spkr2spkrid[\"RN\"]\n return self.spkr2spkrid[\"OTHER\"]\n\n def get_spkr_list(self, uids, get_spkr_category, nested=True):\n \"\"\"\n Given a list of utterance IDs, and\n the function 'get_spkr_code' with appropriate parameters\n to get the list of speaker IDs of those utterances.\n\n Parameters\n ----------\n uids : list[int] or list[list[int]]\n list of utterances.\n It can be nested or flattened.\n get_spkr_category : method\n self.get_spkr_code method with appropriate arguments\n nested : bool\n True if nested.\n\n Returns\n -------\n list[int]\n List of speaker IDs.\n \"\"\"\n if nested: # if uids are nested\n spkrs_list = []\n for ses_uids in uids:\n spkrs = map(get_spkr_category, map(str, self.corpus_df.iloc[ses_uids].speaker))\n spkrs_list.append(spkrs)\n else:\n spkrs_list = map(get_spkr_category, map(str, self.corpus_df.iloc[uids].speaker))\n return spkrs_list\n\n def fit_bow(self, train_doc, tfidf=True, vocabulary=None, stop_words=None,\n token_pattern=r\"(?u)[A-Za-z\\?\\!\\-\\.']+\", max_wlen=0):\n \"\"\"\n Fits bag of words or TF-IDF.\n\n Parameters\n ----------\n train_doc : list[str]\n Training document\n tfidf : bool\n Flag for TF-idf\n vocabulary : set[str] or None\n Set of vocabulary\n If None, uses self.vocabulary\n stop_words : set[str] or None\n Set of stop words\n If None, uses self.stopwords_all\n token_pattern : str\n Regular expression denoting what constitutes a token\n max_wlen : int\n Maximum word length to be considered.\n Upper bound of the n-gram range.\n\n Returns\n -------\n tuple[np.array, Vectorizer]\n Returns a BOW for training data and the vectorizer.\n \"\"\"\n\n if max_wlen == 0:\n max_wlen = self.max_wlen\n\n if vocabulary is None:\n vocabulary = self.vocabulary\n\n if stop_words is None:\n stop_words = self.stopwords_all\n\n if token_pattern != self.token_pattern:\n token_pattern = self.token_pattern\n\n if tfidf is True:\n vectorizer = TfidfVectorizer(ngram_range=(1, max_wlen),\n token_pattern=token_pattern,\n stop_words=stop_words,\n vocabulary=vocabulary)\n else:\n vectorizer = CountVectorizer(ngram_range=(1, max_wlen),\n token_pattern=token_pattern,\n stop_words=stop_words,\n vocabulary=vocabulary)\n\n train_bow = vectorizer.fit_transform(train_doc)\n return train_bow, vectorizer\n\n @staticmethod\n def transform_bow(test_doc, vectorizer):\n \"\"\"\n Transforms test document into a BOW matrix.\n\n Parameters\n ----------\n test_doc : list[str]\n List of test documents (utterances).\n vectorizer : TfidfVectorizer or CountVectorizer\n Vectorizer that was trained using the training data\n\n Returns\n -------\n np.array\n\n \"\"\"\n if test_doc is not None and len(test_doc) > 0:\n return vectorizer.transform(test_doc)\n else:\n return np.array([])\n\n @staticmethod\n def get_nested_bow(nested_docs, vectorizer):\n \"\"\"\n Works for a nested docs. Returns a list of BOW.\n\n Parameters\n ----------\n nested_docs : list[list[str]]\n List of sessions, where each session is a list of utterances in the session\n vectorizer : TfidfVectorizer or CountVectorizer\n Vectorizer that was trained using the training data\n\n Returns\n -------\n list[np.array]\n List of BOW, where each BOW is for each session.\n\n \"\"\"\n\n \"\"\"\n Works for a nested docs.when nested_docs is a list[list[string]].\n \"\"\"\n nested_bows = []\n for doc in nested_docs:\n nested_bows.append(MHDData.transform_bow(doc, vectorizer))\n return nested_bows\n\n def get_utter_level_data_from_sids(self, sesid_list):\n \"\"\"\n Get nested data using a list of session IDs\n\n Parameters\n ----------\n sesid_list :\n\n Returns\n -------\n\n \"\"\"\n ulists = []\n docs = []\n labs = []\n for sesid in sesid_list:\n tmp_uids = self.convert_docids_level([sesid], from_level='session', to_level='utterance',\n insert_st_end=False)\n doc_tmp, lab_tmp, _ = self.get_utter_level_subset(tmp_uids, chunk_size=1, overlap=False)\n ulists.append(tmp_uids)\n docs.append(doc_tmp)\n labs.append(lab_tmp)\n return ulists, docs, labs\n\n def convert_docids_level(self, ids_list, from_level='session', to_level='utterance',\n insert_st_end=False):\n \"\"\"\n Given a list of session or segment IDs, convert them to a list of\n corresponding segment IDs or utterance IDs.\n\n Parameters\n ----------\n ids_list : list[int]\n List of session IDs or segment IDs\n from_level : str\n Either 'session' or 'segment'\n to_level : str\n Either 'segment' or 'utterance'\n insert_st_end : bool\n If True, -1 and -2 will be inserted for start and end of the session or segment\n (depending on the 'from_level').\n (Not used currently. default=False)\n\n Returns\n -------\n list[int]\n \"\"\"\n\n def get_ulist(ids_list, orig_list_type='session', insert_st_end=False):\n \"\"\" from session/segment to utterance\"\"\"\n ulist = []\n if orig_list_type == 'session':\n for sid in ids_list:\n if insert_st_end:\n ulist.append(-1)\n for tt in self.sstt2uid[sid]:\n ulist.append(self.sstt2uid[sid][tt])\n if insert_st_end:\n ulist.append(-2)\n elif orig_list_type == 'segment':\n for segid in ids_list:\n if insert_st_end:\n ulist.append(-1)\n for uid in self.segid2uids[segid]:\n ulist.append(uid)\n if insert_st_end:\n ulist.append(-2)\n else:\n print(\"ERROR: [get_ulist] orig_list_type can be either 'session' or 'segment'!\")\n exit()\n return ulist\n\n def get_seglist(sids_list, insert_st_end=False):\n \"\"\" from session to segment \"\"\"\n seglist = []\n for sid in sids_list:\n if insert_st_end:\n seglist.append(-1)\n for segid in self.sid2segids[sid]:\n seglist.append(segid)\n if insert_st_end:\n seglist.append(-2)\n return seglist\n\n if to_level == 'utterance':\n return get_ulist(ids_list, orig_list_type=from_level, insert_st_end=insert_st_end)\n elif to_level == 'segment':\n return get_seglist(ids_list, insert_st_end=insert_st_end)\n else:\n print(\"ERROR: [convert_docids_level] to_level can be either 'utterance' or 'segment'!\")\n exit()\n\n def get_utter_level_subset(self, uid_list, chunk_size=1, overlap=False):\n \"\"\"\n Given a list of utterance IDs, return the corresponding text and the label data.\n (If the utterance ID has been changed due to chunk sizes and overlaps.)\n\n Parameters\n ----------\n uid_list\n chunk_size : int\n size of the window/chunk. Unit : sentences\n overlap : bool\n Currently not supported\n\n Returns\n -------\n\n \"\"\"\n\n text_list = []\n lab_list = []\n tmp_txt = []\n new_uid_list = []\n tmp_uids = []\n labid = -1\n prev_sid = 0\n i = 0\n\n for uid in uid_list:\n segid = self.uid2segid[uid]\n # Whenever you see a new segment or a new chunk,\n # only when there is some text to save\n if (len(tmp_txt) > 0) and (i % chunk_size == 0 or segid != prev_sid):\n i = 0\n text_list.append('|'.join(tmp_txt))\n lab_list.append(labid)\n if chunk_size > 1:\n new_uid_list.append(tmp_uids)\n tmp_uids = []\n tmp_txt = []\n\n if chunk_size > 1:\n tmp_uids.append(uid)\n tmp_txt.append(self.corpus_txt[uid])\n if len(self.uid2lid) > uid:\n labid = self.uid2lid[uid] #segid2lid[segid] # both could work\n else:\n labid = -1 # If there's no label, assign -1.\n prev_sid = segid\n i += 1\n\n # Take care of the last one\n if len(tmp_txt) > 0:\n lab_list.append(labid)\n text_list.append(' '.join(tmp_txt))\n\n if chunk_size == 1:\n new_uid_list = uid_list\n elif chunk_size > 1 and len(tmp_txt) > 0:\n new_uid_list.append(tmp_uids)\n\n return text_list, lab_list, new_uid_list\n\n\nclass MHDTrainData(MHDData):\n\n def __init__(self, data_file, nouns_only=False, ignore_case=True,\n remove_numbers=False, sub_numbers=True,\n stopwords_dir=\"./stopwordlists\", proper_nouns_dir=\"./stopwordlists\",\n label_mappings=None, ngram_range=(1,1), max_np_len=2, min_wlen=1,\n min_dfreq=0.0, max_dfreq=0.9, min_sfreq=20,\n token_pattern=r\"(?u)[A-Za-z\\?\\!\\-\\.']+\", verbose=1,\n corpus_pkl='./corpus.pkl', label_pkl='./label.pkl', vocab_pkl='./vocab.pkl'):\n \"\"\"\n Parameters\n ----------\n data_file : str\n File path to the data\n nouns_only : bool\n Only include nouns\n ignore_case : bool\n True if ignoring cases (transformed to all lower case, default)\n remove_numbers : bool\n Remove all digits if True, default is False\n sub_numbers : bool\n Rather than removing all digits, substitute them to symbol -num-. default True\n stopwords_dir : str\n Path to the stopwords directory\n proper_nouns_dir : str\n Path to the proper nouns directory\n label_mappings : dict or None\n Label mappings that can be use for label merging/cleaning.\n If None (default), rare labels are mapped to the 'Other' label (topic code: '37')\n ngram_range : tuple\n The lower and upper boundary of the range of n-values for different n-grams\n to be extracted. (Maximum length of noun phrase can be different from this.)\n max_np_len : int\n Maximum length of noun phrases to be considered.\n min_wlen : int\n Minimum word length of an utterance to be considered.\n If an utterance has word length less than 'min_wlen', the utterance is skipped.\n min_dfreq : float\n float in range [0.0, 1.0]\n When building the vocabulary ignore terms that have\n a document frequency strictly lower than the given threshold.\n The parameter represents a proportion of documents, integer absolute counts.\n NOTE: Here, each utterance is treated as a document, therefore very small value would\n still reduce the size of vocabulary. Because the utterances are very short therefore most of the words have very\n small document frequencies.\n max_dfreq : float\n float in range [0.0, 1.0]\n When building the vocabulary ignore terms that have a document frequency strictly higher than\n the given threshold (corpus-specific stop words).\n The parameter represents a proportion of documents, integer absolute counts.\n min_sfreq : int\n If there are labels that appear less than this number of sessions,\n the labels are merged to the 'other' label (topic code: '37')\n token_pattern : str\n Regular expression denoting what constitutes a 'token'.\n verbose : int in range [0,3]\n The level of verbosity. Larger value means more verbosity.\n corpus_pkl : str\n Path to the pickle file that saves corpus related data.\n label_pkl : str\n Path to the pickle file that saves label related data.\n vocab_pkl : str\n Path to the pickle file that saves vocab related data.\n \"\"\"\n\n MHDData.__init__(self, data_file, nouns_only=nouns_only, ignore_case=ignore_case,\n remove_numbers=remove_numbers, sub_numbers=sub_numbers,\n stopwords_dir=stopwords_dir, proper_nouns_dir=proper_nouns_dir,\n label_mappings=label_mappings, ngram_range=ngram_range,\n max_np_len=max_np_len, min_wlen=min_wlen,\n min_dfreq=min_dfreq, max_dfreq=max_dfreq, min_sfreq=min_sfreq,\n token_pattern=token_pattern, verbose=verbose,\n corpus_pkl=corpus_pkl, label_pkl=label_pkl, vocab_pkl=vocab_pkl)\n\n cl_lab_pkl = label_pkl.split(\".pkl\")[0] + \"_cleaned.pkl\"\n\n # Cleans and save cleaned data so that the TestData can load and use\n self.clean_labels(min_sess_freq=min_sfreq, label_mappings=label_mappings)\n self._save_cleaned_lab_pkl(self.lid2lab, self.lab2lid, self.label_mappings, cl_lab_pkl)\n self.get_valid_data()\n\n self.n_utters = len(self.uid2sstt)\n self.n_vocab = len(self.vocabulary)\n self.n_labels = len(self.lid2lab)\n\n self.bow = None\n self.vectorizer = None\n\n def print_stats(self):\n print(\"Number of sessions: %d (ones that have text)\" % len(self.sstt2uid))\n print(\"Number of sessions: %d (ones that have labels)\" % len(self.sid2labs_all))\n print(\"Number of sessions: %d (ones that have both text and labels)\" % len(self.valid_sids))\n print(\"Number of segments: %d (ones that have both text and labels)\" % len(self.valid_segids))\n print(\"Number of utterances: %d (ones that have both text and labels)\" % len(self.valid_uids))\n print(\"Number of labels that originally had: %d (including the ones that appear in the sessions without text)\" % len(self.lid2lab_all))\n print(\"Number of labels: %d (after cleaning the labels)\" % self.n_labels)\n print(\"Vocabulary size: %d\" % self.n_vocab)\n print(\"Number of user-defined stopwords: %d\" % len(self.stopwords))\n print(\"Number of stopwords used in total: %d (including the words with low dfs and high dfs)\" % len(self.stopwords_all))\n\n def get_valid_data(self):\n \"\"\"\n Get valid session, segment, utterance IDs that has labels\n \"\"\"\n # Get session IDs and utterance IDs that both have the text and the labels\n if self.verbose > 0:\n print(\"Getting lists of valid session/utterance IDs that have both text and labels\")\n\n # First get the self.sid2segids\n sid2segids = {}\n segid2sid = {}\n for sid in self.sstt2uid:\n segidset = set()\n for tt in self.sstt2uid[sid]:\n uid = self.sstt2uid[sid][tt]\n segid = self.uid2segid[uid]\n segidset.add(segid)\n if segid2sid.get(segid, None) is None:\n segid2sid[segid] = sid\n sid2segids[sid] = sorted(list(segidset))\n\n self.sid2segids = sid2segids\n self.segid2sid = segid2sid\n\n valid_sids = []\n valid_segids = []\n valid_uids = []\n\n for sid in sid2segids:\n if len(self.sid2labs.get(sid, [])) > 0:\n valid_sids.append(sid)\n for segid in sid2segids[sid]: # segids list\n lid = self.segid2lid.get(segid, self.n_labels) # When there is no label, assign the number n_label\n if lid < self.n_labels and self.lid2lab[lid] != 'nan': # the last label is not always 'nan'. We're currently including 'nan' for now.\n valid_segids.append(segid)\n for uid in self.segid2uids[segid]:\n valid_uids.append(uid)\n self.valid_sids = sorted(valid_sids)\n self.valid_segids = sorted(valid_segids)\n self.valid_uids = sorted(valid_uids)\n\n def load_corpus(self, corpus_file, sep, min_wcnt=1, min_np_len=2, max_np_len=3,\n token_pattern=r\"(?u)\\b\\w[A-Za-z']*\\b\",\n ignore_case=True, remove_numbers=False, sub_numbers=True, parser=None, stemmer_type=None,\n proper_nouns_dir=\"./stopwordlists\",\n corpus_pkl='./corpus.pkl', label_pkl='./labels.pkl', vocab_pkl='./vocab.pkl'):\n \"\"\"\n Read corpus from 'corpus_file',\n cleans the text, (cleaning is mostly done in preprocess.py)\n finds segments and assigns segment IDs,\n saves all the data.\n\n For parameters, see the parameter descriptions of the MHDData and MHDTrainData class.\n\n Parameters\n ----------\n corpus_file\n sep\n min_wcnt\n min_np_len\n max_np_len\n token_pattern\n ignore_case\n remove_numbers\n sub_numbers\n parser\n stemmer_type\n proper_nouns_dir\n corpus_pkl\n label_pkl\n vocab_pkl\n \"\"\"\n\n if self.verbose > 0:\n print('Loading and preprocessing the corpus with labels')\n if not (self._load_corpus_pkl(corpus_pkl) and self._load_vocab_pkl(vocab_pkl) and\n self._load_lab_pkl(label_pkl)):\n uidx = 0\n segidx = -1\n uid2sstt = [] # uid to [session,talkturn]\n sstt2uid = {} # [session][talkturn] to uid\n uid2segid = [] # uid to segment id\n segid2uids = defaultdict(list) # segment id to utter id\n corpus_txt = []\n sesid_arr, segid_arr = [], []\n rows_to_keep = []\n\n prev_lab = None\n prev_sesid = -1\n\n # Does not count on the segments\n sid2labs_all = defaultdict(list)\n lid2lab_all = set()\n\n # Does count on the segments\n segid2lab = {} # segment id to string label\n segid2lt = {}\n\n # Function that checks the valid label\n is_valid_lab = lambda x: True if len(x) > 0 else False # Keep nan as one\n\n # Load the delimited file\n raw_df = pd.read_csv(corpus_file, sep=sep)\n raw_df = raw_df[raw_df.topicnumber > 0]\n raw_df = raw_df[raw_df.visitid > 0]\n\n # Load the list of proper nouns\n names_to_sub = preproc.read_words(os.path.join(proper_nouns_dir, \"names.txt\"), ignore_case)\n locs_to_sub = preproc.read_words(os.path.join(proper_nouns_dir, \"locations.txt\"), ignore_case)\n\n if self.verbose > 1:\n print(\" Cleaning the corpus (removing punctuations..)\")\n\n for i in range(raw_df.shape[0]):\n if self.verbose > 2 and i % 5000 == 0:\n print(\" %10d utterances\" % i)\n row = raw_df.iloc[i]\n sesid = int(row['visitid'])\n tt = int(row['talkturn'])\n text_ = row['text']\n lab = str(int(row['topicnumber']))\n lab_letter = str(row['topicletter']).strip()\n\n # preprocess the sentence/doc\n if type(text_) == str:\n text = preproc.remove_punc(text_, ignore_case, remove_numbers=remove_numbers,\n names_list=names_to_sub, locations_list=locs_to_sub,\n is_mhddata=True)\n\n if len(text.split()) >= min_wcnt: # or maybe do len(text) < min_charcnt?\n sesid_arr.append(sesid)\n rows_to_keep.append(i)\n\n # Finds a segment\n if (prev_sesid != sesid or prev_lab != lab) and is_valid_lab(lab):\n segidx += 1\n segid2lab[segidx] = lab\n segid2lt[segidx] = lab_letter\n sid2labs_all[sesid].append(lab)\n lid2lab_all.add(lab)\n uid2sstt.append([sesid, tt])\n uid2segid.append(segidx)\n segid_arr.append(segidx)\n if sstt2uid.get(sesid, None) is None:\n sstt2uid[sesid] = {}\n sstt2uid[sesid][tt] = uidx\n segid2uids[segidx].append(uidx)\n corpus_txt.append(text)\n uidx += 1\n prev_lab = lab\n prev_sesid = sesid\n\n # Get tokenized & POS tagged corpus with the set of noun phrases\n vocab, stw_all, np2cnt, nps, corpus_pos \\\n = preproc.define_vocabulary(corpus_txt,\n self.stopwords,\n token_pattern,\n self.ngram_range,\n self.min_dfreq,\n self.max_dfreq,\n min_np_len, max_np_len,\n ignore_case,\n parser, stemmer_type, self.verbose)\n\n cleaned_df = raw_df.iloc[rows_to_keep]\n cleaned_df = cleaned_df.assign(visitid=sesid_arr, text_cleaned=corpus_txt,\n text_postag=corpus_pos, segmentid=segid_arr)\n self.corpus_df = cleaned_df.reset_index(drop=True)\n uid2lab = map(str, map(int, list(self.corpus_df.topicnumber)))\n\n self._save_corpus_pkl(self.corpus_df, nps, np2cnt, uid2sstt, sstt2uid,\n uid2segid, segid2uids, sid2labs_all, segid2lab,\n segid2lt, uid2lab, corpus_pkl)\n\n self._save_vocab_pkl(nps, vocab, stw_all, vocab_pkl)\n\n self._save_lab_pkl(lid2lab_all, segid2lt, label_pkl)\n\n # Get the reverse vocab mapping\n voc_len = max(self.vocabulary.values()) + 1\n self.vocabulary_inv = [\"\"] * voc_len\n for voc, i in self.vocabulary.iteritems():\n self.vocabulary_inv[i] = voc\n\n def clean_labels(self, min_sess_freq=20, label_mappings=None):\n \"\"\"\n Clean labels. If there is a 'label_mapping' given, it does the label merging/updates\n using the 'label_mapping'.\n If not, rare labels that appears less than 'miss_sess_freq' sessions\n will be merged to 'Others' label.\n\n Parameters\n ----------\n min_sess_freq : int\n Ignore labels that appear less than min_sess_freq times\n label_mappings : dict or None\n Label mappings can be given manually.\n \"\"\"\n if self.verbose > 0:\n print(\"Cleaning labels ..\")\n self.n_labels = len(self.lid2lab_all)\n\n # Clean labels (ignore labels that appear less than N times)\n cleaned = self._clean_labels_inner(self.lid2lab_all, self.lab2lid_all,\n self.sid2labs_all, self.segid2lab_all, self.segid2lt,\n self.uid2lab_all, min_sess_freq, label_mappings)\n\n self.lid2lab, self.lab2lid = cleaned[0]\n self.sid2labs, self.sid2lidarr = cleaned[1]\n self.segid2lab, self.segid2lid, self.segid2lidarr, self.segid2ltid = cleaned[2]\n self.uid2lab, self.uid2lid = cleaned[3]\n self.label_mappings = cleaned[-1]\n self.lid2name = [self.lab2name[self.lid2lab[i]] for i in range(len(self.lid2lab))]\n\n\n def _clean_labels_inner(self, lid2lab, lab2lid, sid2labs, segid2lab, segid2lt, uid2lab,\n min_sess_freq=10, label_mappings=None):\n \"\"\"\n Parameters\n ----------\n lid2lab : list\n lab2lid : dict\n sid2labs : dict\n segid2lab : dict\n min_sess_freq : int\n Threshold for the minimum number of sessions a label needs to be associated with.\n If not met, label is deleted. Default = 5\n\n Returns\n -------\n lid2lab_new\n lab2lid_new\n sid2txtlabels_new\n sid2labels_new\n\n \"\"\"\n def print_label_mappings(lab_map, labcnts):\n for lab in sorted(lab_map.keys()):\n print(\" %s %s --> %s %s\" % (lab, self.lab2name.get(lab, \"nan\"),\n lab_map[lab], self.lab2name.get(lab_map[lab], \"nan\")))\n # Can include more steps other than deleting less frequent labels\n\n # 1. Label mappings for merging labels (it does not create new labels)\n if label_mappings is None:\n label_mappings = {}\n\n # For deleting rare labels (that appears less than 'min_sess_freq' times)\n # Create a matrix with the subject labels (so that we can get the # sessions per each label)\n labmat = np.zeros((len(sid2labs), self.n_labels)) # n_sessions X n_labels\n for i, sid in enumerate(sid2labs):\n if self.sstt2uid.get(sid, None) is None:\n continue\n labarr = np.zeros(self.n_labels, dtype=np.int8)\n for lab in sid2labs[sid]:\n if lab in lid2lab:\n # merge labels\n if label_mappings.get(lab, None) is not None:\n lab = label_mappings[lab]\n lid = lab2lid[lab]\n labarr[lid] = 1\n labmat[i] = labarr\n\n # Avoid deleting 'other' code\n code_other = '37'\n labmat[:, self.lab2lid_all[code_other]] += min_sess_freq\n\n # Delete rare labels\n labids_to_keep = np.where(np.sum(labmat, axis=0) >= min_sess_freq)[0]\n labids_to_merge = np.where(np.sum(labmat, axis=0) < min_sess_freq)[0]\n if len(labids_to_merge) > 0 and len(label_mappings) == 0:\n # If mapping was not defined, map the rare labels to 'others'\n label_mappings = {self.lid2lab_all[lid]: code_other for lid in labids_to_merge}\n\n if self.verbose > 1:\n print_label_mappings(label_mappings, np.sum(labmat, axis=0))\n\n lid2lab_new = [lid2lab[lid] for lid in labids_to_keep]\n lab2lid_new = {ll: i for i, ll in enumerate(lid2lab_new)}\n self.n_labels = len(lid2lab_new)\n\n # update session-level, segment-level, utterance-level label data\n sid_labs = self._update_session_labs(sid2labs, lab2lid_new,\n label_mappings, code_other)\n segid_labs = self._update_segment_labs(segid2lab, lab2lid_new, segid2lt,\n label_mappings, code_other)\n uid_labs = self._update_utter_labs(uid2lab, lab2lid_new, label_mappings, code_other)\n\n return (lid2lab_new, lab2lid_new), sid_labs, segid_labs, uid_labs, label_mappings\n\n def _save_cleaned_lab_pkl(self, lid2lab, lab2lid, lab_mappings,\n cleaned_label_pkl='./label_cleaned.pkl'):\n \"\"\"\n Save cleaned labels (label variables without '_all' postfix) to a pkl file.\n \"\"\"\n lab_data_to_save = (lid2lab, lab2lid, lab_mappings)\n with open(cleaned_label_pkl, 'wb') as f:\n cp.dump(lab_data_to_save, f, protocol=cp.HIGHEST_PROTOCOL)\n\n\nclass MHDTestData(MHDData):\n \"\"\"\n Additional parameters in this class\n\n has_label : bool\n True if the data has label\n \"\"\"\n def __init__(self, data_file, nouns_only=False, ignore_case=True,\n remove_numbers=False, sub_numbers=True,\n proper_nouns_dir=\"./stopwordlists\", min_wlen=1,\n token_pattern=r\"(?u)[A-Za-z\\?\\!\\-\\.']+\", verbose=1,\n corpus_pkl='./corpus_test.pkl', tr_label_pkl=\"./label.pkl\", tr_vocab_pkl=\"./vocab.pkl\",\n reload_corpus=True):\n \"\"\"\n Parameters\n ----------\n data_file : str\n File path to the data\n nouns_only : bool\n Only include nouns\n ignore_case : bool\n True if ignoring cases (transformed to all lower case, default)\n remove_numbers : bool\n Remove all digits if True, default is False\n sub_numbers : bool\n Rather than removing all digits, substitute them to symbol -num-. default True\n proper_nouns_dir : str\n Path to the proper nouns directory\n min_wlen : int\n Minimum word length of an utterance to be considered.\n If an utterance has word length less than 'min_wlen', the utterance is skipped.\n token_pattern : str\n Regular expression denoting what constitutes a 'token'.\n verbose : int in range [0,3]\n The level of verbosity. Larger value means more verbosity.\n corpus_pkl : str\n Path to the pickle file that saves corpus related data.\n tr_label_pkl : str\n Path to the pickle file where the label related data is saved (from training step).\n vocab_pkl : str\n Path to the pickle file where the vocab related data is saved (from training step).\n \"\"\"\n\n self.verbose = verbose\n cl_lab_pkl = tr_label_pkl.split(\".pkl\")[0] + \"_cleaned.pkl\"\n if self.load_train_lab_pkl(tr_label_pkl, cl_lab_pkl) and self.load_train_vocab_pkl(tr_vocab_pkl):\n\n self.has_label = False\n if reload_corpus:\n if os.path.isfile(corpus_pkl):\n if self.verbose > 1:\n print(\"Removing \" + corpus_pkl + \" to re-load the corpus.\")\n os.remove(corpus_pkl)\n\n MHDData.__init__(self, data_file, nouns_only=nouns_only, ignore_case=ignore_case,\n remove_numbers=remove_numbers, sub_numbers=sub_numbers,\n proper_nouns_dir=proper_nouns_dir,\n min_wlen=min_wlen, token_pattern=token_pattern, verbose=verbose,\n corpus_pkl=corpus_pkl, label_pkl=\"\", vocab_pkl=\"\")\n\n self.clean_labels(label_mappings=self.label_mappings)\n self.n_utters = len(self.uid2sstt)\n self.n_vocab = len(self.vocabulary)\n self.n_labels = len(self.lid2lab)\n\n def print_stats(self):\n print(\"Number of sessions: %d (ones that have text)\" % len(self.sstt2uid))\n print(\"Number of sessions: %d (ones that have labels)\" % len(self.sid2labs_all))\n print(\"Number of labels that originally had: %d (including the ones that appear in the sessions without text)\" % len(self.lid2lab_all))\n print(\"Number of labels: %d (after cleaning the labels)\" % self.n_labels)\n print(\"Vocabulary size: %d\" % self.n_vocab)\n print(\"Number of user-defined stopwords: %d\" % len(self.stopwords))\n print(\"Number of stopwords used in total: %d (including the words with low dfs and high dfs)\" % len(self.stopwords_all))\n\n def load_corpus(self, corpus_file, sep, min_wcnt=1, min_np_len=2, max_np_len=3,\n token_pattern=r\"(?u)\\b\\w[A-Za-z']*\\b\",\n ignore_case=True, remove_numbers=False, sub_numbers=True, parser=None, stemmer_type=None,\n proper_nouns_dir=\"./stopwordlists\",\n corpus_pkl='./corpus_te.pkl', label_pkl='', vocab_pkl=''):\n \"\"\"\n Read corpus from 'corpus_file', which is the test file.\n cleans the text, (cleaning is mostly done in preprocess.py)\n finds segments and assigns segment IDs,\n saves all the data.\n\n Parameters\n ----------\n corpus_file : str\n Path to the test file to be preprocessed.\n sep : str\n Delimiter/separater of delimited file. \"|\" for MHD file.\n min_wcnt : int\n Minimum length of a sentence in words to be considered.\n min_np_len : int\n Redundant variable since the class uses the vocabulary from the training data\n max_np_len : int\n Redundant variable since the class uses the vocabulary from the training data\n token_pattern : str\n Redundant variable since the class uses the vocabulary from the training data\n ignore_case : bool\n remove_numbers : bool\n sub_numbers : bool\n parser : None or str\n stemmer_type : None or str\n proper_nouns_dir : str\n corpus_pkl : str\n Path to the corpus pickle file.\n label_pkl : str\n Redundant variable since the class uses the labels from the training data\n vocab_pkl : str\n Redundant variable since the class uses the vocabulary from the training data\n \"\"\"\n if self.verbose > 0:\n print('Loading and preprocessing the corpus with labels')\n if not self._load_corpus_pkl(corpus_pkl):\n uidx = 0\n segidx = -1\n uid2sstt = [] # uid to [session,talkturn]\n sstt2uid = {} # [session][talkturn] to uid\n uid2segid = [] # uid to segment id\n segid2uids = defaultdict(list) # segment id to utter id\n corpus_txt = []\n sesid_arr, segid_arr = [], []\n rows_to_keep = []\n\n prev_lab = None\n prev_sesid = -1\n\n # Does not count on the segments\n sid2labs_all = defaultdict(list)\n\n # Does count on the segments\n segid2lab = {} # segment id to string label\n segid2lt = {}\n\n # Function that checks the valid label\n is_valid_lab = lambda x: True if len(str(x)) > 0 else False # Keep nan as one\n\n # Load the delimited file\n raw_df = pd.read_csv(corpus_file, sep=sep)\n if 'topicnumber' in raw_df.columns:\n raw_df = raw_df[raw_df.topicnumber > 0]\n raw_df = raw_df[raw_df.visitid > 0]\n\n names_to_sub = preproc.read_words(os.path.join(proper_nouns_dir, \"names.txt\"), ignore_case)\n locs_to_sub = preproc.read_words(os.path.join(proper_nouns_dir, \"locations.txt\"), ignore_case)\n\n if self.verbose > 1:\n print(\" Cleaning the corpus (removing punctuations..)\")\n for i in range(raw_df.shape[0]):\n row = raw_df.iloc[i]\n\n sesid = int(row['visitid'])\n tt = int(row['talkturn'])\n text_ = row['text']\n lab = row.get('topicnumber', '')\n if is_valid_lab(lab):\n lab = str(int(lab))\n lab_letter = row.get('topicletter', '')\n if is_valid_lab(lab_letter):\n lab_letter = str(lab_letter).strip()\n\n # preprocess the sentence/doc\n if type(text_) == str:\n text = preproc.remove_punc(text_, ignore_case, remove_numbers=remove_numbers,\n names_list=names_to_sub, locations_list=locs_to_sub, is_mhddata=True)\n\n if len(text.split()) >= min_wcnt: # or maybe do len(text) < min_charcnt?\n\n sesid_arr.append(sesid)\n rows_to_keep.append(i)\n\n # Finds a segment\n if (prev_sesid != sesid or prev_lab != lab) and is_valid_lab(lab):\n segidx += 1\n segid2lab[segidx] = lab\n segid2lt[segidx] = lab_letter\n sid2labs_all[sesid].append(lab)\n uid2sstt.append([sesid, tt])\n uid2segid.append(segidx)\n segid_arr.append(segidx)\n if sstt2uid.get(sesid, None) is None:\n sstt2uid[sesid] = {}\n sstt2uid[sesid][tt] = uidx\n segid2uids[segidx].append(uidx)\n corpus_txt.append(text)\n uidx += 1\n prev_lab = lab\n prev_sesid = sesid\n\n cleaned_df = raw_df.iloc[rows_to_keep]\n cleaned_df = cleaned_df.assign(visitid=sesid_arr, text_cleaned=corpus_txt,\n segmentid=segid_arr)\n self.corpus_df = cleaned_df.reset_index(drop=True)\n if 'topicnumber' in self.corpus_df.columns:\n uid2lab = map(str, map(int, list(self.corpus_df.topicnumber)))\n else:\n uid2lab = []\n\n self._save_corpus_pkl(self.corpus_df, None, None, uid2sstt, sstt2uid,\n uid2segid, segid2uids, sid2labs_all, segid2lab,\n segid2lt, uid2lab, corpus_pkl)\n\n # Set the extra variable 'has_label' when the data has the column 'topicnumber'\n if 'topicnumber' in self.corpus_df.columns:\n self.has_label = True\n\n def load_train_vocab_pkl(self, tr_vocab_pkl):\n \"\"\"\n Loads vocab data from the pickle file.\n \"\"\"\n if self._load_vocab_pkl(tr_vocab_pkl):\n # Get the reverse vocab mapping\n voc_len = max(self.vocabulary.values()) + 1\n self.vocabulary_inv = [\"\"] * voc_len\n for voc, i in self.vocabulary.iteritems():\n self.vocabulary_inv[i] = voc\n return True\n else:\n return False\n\n def _load_cleaned_lab_pkl(self, cleaned_lab_pkl):\n \"\"\"\n Loads the cleaned (merged) label data from the pickle file.\n (The ones without '_all')\n \"\"\"\n if os.path.exists(cleaned_lab_pkl):\n if self.verbose > 0:\n print(\"Loading cleaned labels file from \" + cleaned_lab_pkl)\n\n lab_data_list = cp.load(open(cleaned_lab_pkl, 'rb'))\n if len(lab_data_list) == 3:\n self.lid2lab, self.lab2lid, self.label_mappings = lab_data_list\n return True\n else:\n print(\"ERROR: Cannot load the label file.\" + cleaned_lab_pkl+ \" has different format!\")\n return False\n else:\n return False\n\n def load_train_lab_pkl(self, tr_label_pkl, cl_tr_label_pkl):\n \"\"\"\n Loads all the label data from the training step.\n (Both the cleaned version and the version before cleaning.)\n \"\"\"\n self.lid2lab = []\n return self._load_lab_pkl(tr_label_pkl) and self._load_cleaned_lab_pkl(cl_tr_label_pkl)\n\n def clean_labels(self, min_sess_freq=20, label_mappings=None):\n \"\"\"\n For test data, all the parameters are redundant since it will use\n the same label cleaning process that training data used.\n \"\"\"\n if self.has_label:\n if label_mappings is None:\n label_mappings = self.label_mappings\n\n if self.verbose > 0:\n print(\"Cleaning labels ..\")\n cleaned = self._clean_labels_inner(self.sid2labs_all, self.segid2lab_all, self.segid2lt,\n self.uid2lab_all, label_mappings)\n\n self.sid2labs, self.sid2lidarr = cleaned[0]\n self.segid2lab, self.segid2lid, self.segid2lidarr, self.segid2ltid = cleaned[1]\n self.uid2lab, self.uid2lid = cleaned[2]\n else:\n self.uid2lid = []\n\n self.lid2name = [self.lab2name[self.lid2lab[i]] for i in range(len(self.lid2lab))]\n\n def _clean_labels_inner(self, sid2labs, segid2lab, segid2lt, uid2lab,\n label_mappings=None):\n \"\"\"\n Skips the step where it defines the label mappings (by removing the rare topics.)\n Instead it uses the label mappings from the train data (that were loaded by pkl file).\n This function is only performed when the test data has labels.\n \"\"\"\n\n def print_label_mappings(lab_map):\n for lab in sorted(lab_map.keys()):\n print(\" %s %s --> %s %s\" % (lab, self.lab2name.get(lab, \"nan\"),\n lab_map[lab], self.lab2name.get(lab_map[lab], \"nan\")))\n\n if self.verbose > 1:\n print_label_mappings(label_mappings)\n\n code_other = '37'\n # update session-level, segment-level, utterance-level label data\n sid_labs = self._update_session_labs(sid2labs, self.lab2lid,\n label_mappings, code_other)\n segid_labs = self._update_segment_labs(segid2lab, self.lab2lid, segid2lt,\n label_mappings, code_other)\n uid_labs = self._update_utter_labs(uid2lab, self.lab2lid, label_mappings, code_other)\n\n return sid_labs, segid_labs, uid_labs"
] | [
[
"pandas.read_csv",
"numpy.sum",
"sklearn.feature_extraction.text.CountVectorizer",
"numpy.array",
"numpy.zeros",
"sklearn.feature_extraction.text.TfidfVectorizer"
]
] |
hiyouga/Toxic_Detection | [
"7545f71ebf8f65043db8e8fb0f5a8072b8b346cf"
] | [
"code/models/bert.py"
] | [
"import torch\nimport torch.nn as nn\n\nfrom .env import multienv\n\n\nclass BERT(nn.Module):\n\n def __init__(self, configs):\n super(BERT, self).__init__()\n self.embeddings = configs[\"embeddings\"]\n self.encoder = configs[\"encoder\"]\n self.num_hidden_layers = configs[\"num_hidden_layers\"]\n self.dropout = nn.Dropout(configs['dropout'])\n self.dense = nn.Linear(768, configs['num_classes'])\n self.output_token_hidden = configs['output_token_hidden'] if 'output_token_hidden' in configs else False\n self.use_env = configs['use_env'] if 'use_env' in configs else False\n self.use_extend_attention = configs['extend_attention'] if 'extend_attention' in configs else False\n if self.use_env:\n accumulator = configs['accumulator']\n self.env_model = multienv(768, accumulator)\n\n def forward(self, text, mask=None, env=None):\n if self.use_env and env is None:\n raise RuntimeWarning(\"build a env-enable model, but get no env input\")\n if not self.use_env and env is not None:\n raise RuntimeError(\"build a env-free model, but get env input\")\n if mask is None:\n mask = torch.where(text > 0, torch.ones_like(text), torch.zeros_like(text))\n # hack huggingface/BertModel to add token_embedding with env_embedding\n embedding_output = self.embeddings(text) * mask.unsqueeze(-1)\n # print(f\"emb.shape: {embedding_output.shape}\")\n # print(f\"mask.shape : {mask.shape}\")\n if self.use_env and env is not None:\n env_embeddings = self.env_model(env)\n env_embeddings = env_embeddings.unsqueeze(dim=1).expand_as(embedding_output)\n embedding_output += env_embeddings\n if self.use_extend_attention:\n extended_attention_mask = get_extended_attention_mask(mask)\n else:\n extended_attention_mask = mask\n head_mask = [None] * self.num_hidden_layers\n encoder_outputs = self.encoder(embedding_output, extended_attention_mask, head_mask)\n sequence_output = encoder_outputs[0]\n if self.output_token_hidden:\n output = self.dense(self.dropout(sequence_output))\n return output\n else:\n cls_out = sequence_output[:, 0]\n output = self.dense(self.dropout(cls_out))\n return output\n\n\ndef bert(configs):\n return BERT(configs)\n\n\ndef get_extended_attention_mask(attention_mask):\n \"\"\"\n Makes broadcastable attention and causal masks so that future and masked tokens are ignored.\n Arguments:\n attention_mask (`torch.Tensor`):\n Mask with ones indicating tokens to attend to, zeros for tokens to ignore.\n Returns:\n `torch.Tensor` The extended attention mask, with a the same dtype as `attention_mask.dtype`.\n \"\"\"\n # We can provide a self-attention mask of dimensions [batch_size, from_seq_length, to_seq_length]\n # ourselves in which case we just need to make it broadcastable to all heads.\n if attention_mask.dim() == 3:\n extended_attention_mask = attention_mask[:, None, :, :]\n elif attention_mask.dim() == 2:\n extended_attention_mask = attention_mask[:, None, None, :]\n else:\n raise ValueError(\n f\"Wrong shape for attention_mask (shape {attention_mask.shape})\"\n )\n # Since attention_mask is 1.0 for positions we want to attend and 0.0 for\n # masked positions, this operation will create a tensor which is 0.0 for\n # positions we want to attend and -10000.0 for masked positions.\n # Since we are adding it to the raw scores before the softmax, this is\n # effectively the same as removing these entirely.\n extended_attention_mask = (1.0 - extended_attention_mask) * -10000.0\n return extended_attention_mask\n"
] | [
[
"torch.nn.Linear",
"torch.nn.Dropout",
"torch.zeros_like",
"torch.ones_like"
]
] |
eulersim/sposm | [
"9e85a7ba65eacc736730ae2799828b570ce51739"
] | [
"code/extract_revenues_sec_fin_stat_data.py"
] | [
"import pandas as pd\n\ndf_names = [\"sub\", \"tag\", \"num\", \"pre\"]\nfor df in df_names:\n globals()[df] = pd.read_csv('data/' + df + '.csv')\n\ndf_merged = sub[(sub.countryba == \"US\") & (sub.fp.str[0] == 'Q')]\n\ndf_merged = df_merged[['adsh', 'cik', 'name', 'sic', 'fp', 'period', 'fye']]\ndf_merged = df_merged[\n df_merged.groupby(['cik'])['period'].transform(max) == df_merged.period]\n\ndf_merged = pd.merge(df_merged, pre, on = ['adsh'], how = 'left')\n\ndf_merged = df_merged[(df_merged.stmt == \"IS\") & \n ((df_merged.tag == \"Revenues\") | \n (df_merged.tag == \"RevenueFromContractWithCustomerExcludingAssessedTax\") |\n (df_merged.tag == \"RevenueFromContractWithCustomerIncludingAssessedTax\"))]\n\ndf_merged = pd.merge(df_merged, num, on = ['adsh', 'tag', 'version'], how = 'left')\n\ndf_merged = df_merged[(df_merged.ddate == df_merged.period) & \n (df_merged.uom == \"USD\") &\n (df_merged.qtrs == 1) & \n df_merged.value.notnull() &\n df_merged.coreg.isna()]\n\ndf_merged = df_merged[\n df_merged.groupby(['adsh', 'cik'])['value'].transform(max) ==\n df_merged.value]\n \ndf_merged = df_merged.rename({'value': 'total_revenue'}, axis = 1)\n\ndf_merged = df_merged[['adsh', 'cik', 'name', 'sic', 'fp', 'fye', \n 'ddate', 'total_revenue']]\n\ndf_merged = df_merged.drop_duplicates(['cik', 'name', 'sic', 'fp', \n 'fye', 'ddate', 'total_revenue'])\n\nprint(len(df_merged.adsh))\n"
] | [
[
"pandas.merge",
"pandas.read_csv"
]
] |
Lucaman99/strawberryfields | [
"627b8e6c1049d1108303bf0d9ba53cf6b120ea1f"
] | [
"strawberryfields/apps/data.py"
] | [
"# Copyright 2019 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\nr\"\"\"\r\nPre-calculated datasets of simulated GBS samples.\r\n\r\n.. seealso::\r\n\r\n :doc:`/introduction/data`\r\n\"\"\"\r\n# pylint: disable=unnecessary-pass\r\nfrom abc import ABC, abstractmethod\r\n\r\nimport pkg_resources\r\nimport numpy as np\r\nimport scipy\r\n\r\nDATA_PATH = pkg_resources.resource_filename(\"strawberryfields\", \"apps/data\") + \"/\"\r\n\r\n\r\nclass Dataset(ABC):\r\n \"\"\"Base class for loading datasets of pre-generated samples.\r\n\r\n Attributes:\r\n n_mean (float): mean number of photons in the GBS device\r\n threshold (bool): flag to indicate whether samples are generated with threshold detection\r\n (i.e., detectors of zero or some photons) or with photon-number-resolving detectors.\r\n n_samples (int): total number of samples in the dataset\r\n modes (int): number of modes in the GBS device or, equivalently, number of nodes in graph\r\n data (sparse): raw data of samples from GBS as a `csr sparse array\r\n <https://docs.scipy.org/doc/scipy/reference/generated/scipy.sparse.csr_matrix.html>`__.\r\n \"\"\"\r\n\r\n _count = 0\r\n\r\n @property\r\n @abstractmethod\r\n def _data_filename(self) -> str:\r\n \"\"\"Base name of files containing the sample data stored in the ``./data/`` directory.\r\n\r\n Samples and corresponding adjacency matrix should both be provided as a\r\n ``scipy.sparse.csr_matrix`` saved in ``.npz`` format.\r\n\r\n For ``_data_filename = \"example\"``, the corresponding samples should be stored as\r\n ``./data/example.npz`` and the adjacency matrix as ``./data/example_A.npz``.\"\"\"\r\n pass\r\n\r\n def __init__(self):\r\n self.data = scipy.sparse.load_npz(DATA_PATH + self._data_filename + \".npz\")\r\n self.n_samples, self.modes = self.data.shape\r\n\r\n def __iter__(self):\r\n return self\r\n\r\n def __next__(self):\r\n if self._count < self.n_samples:\r\n self._count += 1\r\n return self.__getitem__(self._count - 1)\r\n self._count = 0\r\n raise StopIteration\r\n\r\n def _elem(self, i):\r\n \"\"\"Access the i-th element of the sparse array and output as a list.\"\"\"\r\n return list(self.data[i].toarray()[0])\r\n\r\n def __getitem__(self, key):\r\n\r\n if not isinstance(key, (slice, tuple, int)):\r\n raise TypeError(\"Dataset indices must be integers, slices, or tuples\")\r\n\r\n if isinstance(key, int):\r\n return self._elem(key + self.n_samples if key < 0 else key)\r\n\r\n if isinstance(key, tuple):\r\n key = slice(*key)\r\n\r\n range_tuple = key.indices(self.n_samples)\r\n return [self._elem(i) for i in range(*range_tuple)]\r\n\r\n def __len__(self):\r\n return self.n_samples\r\n\r\n def counts(self, axis: int = 1) -> list:\r\n \"\"\"Count number of photons or clicks.\r\n\r\n Counts number of photons/clicks in each sample (``axis==1``) or number of photons/clicks\r\n in each mode compounded over all samples (``axis==0``).\r\n\r\n Args:\r\n axis (int): axis to perform count\r\n\r\n Returns:\r\n list: counts from samples\r\n \"\"\"\r\n return np.array(self.data.sum(axis)).flatten().tolist()\r\n\r\n # pylint: disable=missing-docstring\r\n @property\r\n @abstractmethod\r\n def n_mean(self) -> float:\r\n pass\r\n\r\n # pylint: disable=missing-docstring\r\n @property\r\n @abstractmethod\r\n def threshold(self) -> bool:\r\n pass\r\n\r\n\r\n# pylint: disable=abstract-method\r\nclass GraphDataset(Dataset, ABC):\r\n \"\"\"Class for loading datasets of pre-generated samples from graphs.\r\n\r\n Attributes:\r\n adj (array): adjacency matrix of the graph from which samples were generated\r\n \"\"\"\r\n\r\n def __init__(self):\r\n super().__init__()\r\n self.adj = scipy.sparse.load_npz(DATA_PATH + self._data_filename + \"_A.npz\").toarray()\r\n\r\n\r\nclass Planted(GraphDataset):\r\n \"\"\"A random 30-node graph containing a dense 10-node subgraph planted inside\r\n :cite:`arrazola2018using`.\r\n\r\n The graph is generated by joining two Erdős–Rényi random graphs. The first 20-node graph is\r\n generated with edge probability of 0.5 and the second 10-node planted graph is generated with\r\n edge probability of 0.875. The two graphs are joined by selecting 8 vertices at random from\r\n both and adding an edge between them.\r\n\r\n The 10-node planted clique is contained within the final 10 nodes of the graph.\r\n\r\n **Graph:**\r\n\r\n .. |planted| image:: ../../_static/graphs/planted.png\r\n :align: middle\r\n :width: 250px\r\n :target: javascript:void(0);\r\n\r\n |planted|\r\n\r\n Attributes:\r\n n_mean = 8\r\n threshold = True\r\n n_samples = 50000\r\n modes = 30\r\n \"\"\"\r\n\r\n _data_filename = \"planted\"\r\n n_mean = 8\r\n threshold = True\r\n\r\n\r\nclass TaceAs(GraphDataset):\r\n \"\"\"Binding interaction graph for the TACE-AS complex :cite:`banchi2019molecular`.\r\n\r\n Nodes in this graph correspond to pairs of atoms in a target protein and a pharmaceutical\r\n molecule. Edges in the graph are added if the distance between both pairs of atoms is very\r\n close to equal. Cliques in the graph correspond to possible docking configurations of protein\r\n and molecule, and the largest clique is the most stable configuration. There are multiple\r\n maximum-sized cliques of 8 nodes in this graph.\r\n\r\n **Graph:**\r\n\r\n .. |tace_as| image:: ../../_static/graphs/TACE-AS.png\r\n :align: middle\r\n :width: 250px\r\n :target: javascript:void(0);\r\n\r\n |tace_as|\r\n\r\n Attributes:\r\n n_mean = 8\r\n threshold = True\r\n n_samples = 50000\r\n modes = 24\r\n \"\"\"\r\n\r\n _data_filename = \"TACE-AS\"\r\n n_mean = 8\r\n threshold = True\r\n\r\n\r\nclass PHat(GraphDataset):\r\n \"\"\"Random graph created using the p-hat generator of :cite:`gendreau1993solving`.\r\n\r\n This graph is the ``p_hat300-1`` graph of the `DIMACS\r\n <http://iridia.ulb.ac.be/~fmascia/maximum_clique/DIMACS-benchmark>`__ dataset, which is a\r\n collection of large graphs with cliques that are hard to find. The best known clique of\r\n this 300-node graph is of size 8 and is composed of nodes: ``[53, 123, 180, 218, 246, 267, 270,\r\n 286]``. This graph is not visualized due to its large size.\r\n\r\n Attributes:\r\n n_mean = 10\r\n threshold = True\r\n n_samples = 50000\r\n modes = 300\r\n \"\"\"\r\n\r\n _data_filename = \"p_hat300-1\"\r\n n_mean = 10\r\n threshold = True\r\n\r\n\r\nclass Mutag0(GraphDataset):\r\n \"\"\"First graph of the MUTAG dataset.\r\n\r\n The MUTAG dataset is from :cite:`debnath1991structure,kriege2012subgraph` and is available\r\n `here <https://ls11-www.cs.tu-dortmund.de/staff/morris/graphkerneldatasets>`__.\r\n\r\n **Graph:**\r\n\r\n .. |mutag_0| image:: ../../_static/graphs/MUTAG_0.png\r\n :align: middle\r\n :width: 250px\r\n :target: javascript:void(0);\r\n\r\n |mutag_0|\r\n\r\n Attributes:\r\n n_mean = 6\r\n threshold = False\r\n n_samples = 20000\r\n modes = 17\r\n \"\"\"\r\n\r\n _data_filename = \"MUTAG_0\"\r\n n_mean = 6\r\n threshold = False\r\n\r\n\r\nclass Mutag1(GraphDataset):\r\n \"\"\"Second graph of the MUTAG dataset.\r\n\r\n The MUTAG dataset is from :cite:`debnath1991structure,kriege2012subgraph` and is available\r\n `here <https://ls11-www.cs.tu-dortmund.de/staff/morris/graphkerneldatasets>`__.\r\n\r\n **Graph:**\r\n\r\n .. |mutag_1| image:: ../../_static/graphs/MUTAG_1.png\r\n :align: middle\r\n :width: 250px\r\n :target: javascript:void(0);\r\n\r\n |mutag_1|\r\n\r\n Attributes:\r\n n_mean = 6\r\n threshold = False\r\n n_samples = 20000\r\n modes = 13\r\n \"\"\"\r\n\r\n _data_filename = \"MUTAG_1\"\r\n n_mean = 6\r\n threshold = False\r\n\r\n\r\nclass Mutag2(GraphDataset):\r\n \"\"\"Third graph of the MUTAG dataset.\r\n\r\n The MUTAG dataset is from :cite:`debnath1991structure,kriege2012subgraph` and is available\r\n `here <https://ls11-www.cs.tu-dortmund.de/staff/morris/graphkerneldatasets>`__.\r\n\r\n **Graph:**\r\n\r\n .. |mutag_2| image:: ../../_static/graphs/MUTAG_2.png\r\n :align: middle\r\n :width: 250px\r\n :target: javascript:void(0);\r\n\r\n |mutag_2|\r\n\r\n Attributes:\r\n n_mean = 6\r\n threshold = False\r\n n_samples = 20000\r\n modes = 13\r\n \"\"\"\r\n\r\n _data_filename = \"MUTAG_2\"\r\n n_mean = 6\r\n threshold = False\r\n\r\n\r\nclass Mutag3(GraphDataset):\r\n \"\"\"Fourth graph of the MUTAG dataset.\r\n\r\n The MUTAG dataset is from :cite:`debnath1991structure,kriege2012subgraph` and is available\r\n `here <https://ls11-www.cs.tu-dortmund.de/staff/morris/graphkerneldatasets>`__.\r\n\r\n **Graph:**\r\n\r\n .. |mutag_3| image:: ../../_static/graphs/MUTAG_3.png\r\n :align: middle\r\n :width: 250px\r\n :target: javascript:void(0);\r\n\r\n |mutag_3|\r\n\r\n Attributes:\r\n n_mean = 6\r\n threshold = False\r\n n_samples = 20000\r\n modes = 19\r\n \"\"\"\r\n\r\n _data_filename = \"MUTAG_3\"\r\n n_mean = 6\r\n threshold = False\r\n\r\n\r\n# pylint: disable=abstract-method\r\nclass MoleculeDataset(Dataset, ABC):\r\n r\"\"\"Class for loading datasets of pre-generated samples from molecules.\r\n\r\n Attributes:\r\n w (array): normal mode frequencies of the electronic ground state (:math:`\\mbox{cm}^{-1}`)\r\n wp (array): normal mode frequencies of the electronic excited state (:math:`\\mbox{cm}^{-1}`)\r\n Ud (array): Duschinsky matrix\r\n delta (array): Displacement vector, with entries :math:`\\delta_i=\\sqrt{\\omega'_i/\\hbar}d_i`,\r\n and :math:`d_i` is the Duschinsky displacement\r\n T (float): temperature (Kelvin)\r\n \"\"\"\r\n\r\n def __init__(self):\r\n super().__init__()\r\n self.w = scipy.sparse.load_npz(DATA_PATH + self._data_filename + \"_w.npz\").toarray()[0]\r\n self.wp = scipy.sparse.load_npz(DATA_PATH + self._data_filename + \"_wp.npz\").toarray()[0]\r\n self.Ud = scipy.sparse.load_npz(DATA_PATH + self._data_filename + \"_Ud.npz\").toarray()\r\n self.delta = scipy.sparse.load_npz(\r\n DATA_PATH + self._data_filename + \"_delta.npz\"\r\n ).toarray()[0]\r\n\r\n # pylint: disable=missing-docstring\r\n @property\r\n @abstractmethod\r\n def T(self) -> bool:\r\n pass\r\n\r\n\r\nclass Formic(MoleculeDataset):\r\n \"\"\"Zero temperature formic acid.\r\n\r\n The molecular parameters are obtained from Ref. :cite:`huh2015boson`.\r\n\r\n **Molecule:**\r\n\r\n .. |formic| image:: ../../_static/formic.png\r\n :align: middle\r\n :width: 250px\r\n :target: javascript:void(0);\r\n\r\n |formic|\r\n\r\n Attributes:\r\n n_mean = 1.56\r\n threshold = False\r\n n_samples = 20000\r\n modes = 14\r\n T = 0\r\n \"\"\"\r\n\r\n _data_filename = \"formic\"\r\n n_mean = 1.56\r\n threshold = False\r\n T = 0\r\n"
] | [
[
"scipy.sparse.load_npz"
]
] |
mingye-fsu/Python-code-of-Morris-Sensitivity-Analysis-for-a-single-model | [
"75c69d15522376052cfe9109ff936eda823207bb"
] | [
"morris_Sample.py"
] | [
"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Tue Nov 26 14:56:47 2019\r\n\r\n@author: Jing Yang ([email protected]) and Ming Ye ([email protected]). This program was modified from the python codes\r\navailable at https://salib.readthedocs.io/en/latest/api.html, but has the following features:\r\n(1) it supports generation of random trajectories for parameters following the following distributions: \r\n uniform (unif), normal (norm), lognormal (lognorm), # triangular (triang), and norm distribution truncated above zero (truncnorm).\r\n(2) it can be used for the level number other than 4. The original python code seems to have a bug that it only works with the level number of 4.\r\n\r\nThe MIT License (MIT)\r\n\r\nCopyright (c) 2019 Jing Yang and Ming Ye\r\n\r\nPermission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), \r\nto deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, \r\nand/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:\r\n\r\nThe above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.\r\n\r\nTHE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, \r\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, \r\nWHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\r\n\"\"\"\r\nfrom __future__ import division\r\n\r\nimport numpy as np\r\nfrom util import scale_samples, nonuniform_scale_samples, compute_groups_matrix\r\n\r\ndef sample(parameter_space, N, num_levels=4, seed=None):\r\n \"\"\"Generate N trajectories using the Method of Morris\r\n The details of the random trajectory generation are referred to Section 3.3 of \r\n the book entitled \"Global Sensitivity Analysis: The Primer\" by saltelli et al. (2007)\r\n\r\n Parameters\r\n ----------\r\n parameter_space : dictionary\r\n The parameter_space definition\r\n N : integer\r\n The number of trajectories to generate\r\n num_levels : integer, default=4\r\n The number of grid levels (should be even)\r\n\r\n Returns\r\n -------\r\n sample or scaled_samples: numpy.ndarray\r\n Returns a numpy.ndarray matrix containing the N trajectories required for \r\n Morris sensitivity analysis. Each trajectory (denoted as B* in Section 3.3 of Saltelli's book) \r\n has the dimension of (k+1) x k, where k is the number of model parameters considered in the \r\n sensitivit analysis. All the trajectories are included one after anotehr in the returned matrix. \r\n As a result, the dimension of the returned matrix is ((k+1)xN) x k. When applying the Morris method\r\n to grouped parameters, the matrix dimension changes, and the details are referred to Section 3.5 of\r\n Saltellie's book.\r\n \"\"\"\r\n assert (num_levels%2 == 0), 'num_levels must be even'\r\n \r\n if seed: # generate random seed if users do not provide a seed\r\n np.random.seed(seed)\r\n\r\n# if parameters are grouped, use function sample_groups; otherwise, use function sample_oat (one parameter at a time) \r\n if parameter_space.get('groups'): \r\n samples = _sample_groups(parameter_space, N, num_levels)\r\n else:\r\n samples = _sample_oat(parameter_space, N, num_levels)\r\n\r\n# The function scale_samples is used only when the 'dists\" keyword is not used when defining the parameter space.\r\n if not parameter_space.get('dists'):\r\n # scaling values out of 0-1 range with uniform distributions\r\n scale_samples(samples, parameter_space['bounds'])\r\n return samples\r\n else:\r\n # scaling values to other distributions based on inverse CDFs\r\n scaled_samples = nonuniform_scale_samples(samples, parameter_space['bounds'], parameter_space['dists'])\r\n return scaled_samples\r\n\r\n\r\ndef _sample_oat(parameter_space, N, num_levels=4):\r\n \"\"\"Generate trajectories without groups\r\n\r\n Arguments\r\n ---------\r\n parameter_space : dict\r\n The parameter_space definition\r\n N : int\r\n The number of samples to generate\r\n num_levels : int, default=4\r\n The number of grid levels\r\n \"\"\"\r\n group_membership = np.asmatrix(np.identity(parameter_space['num_vars'],\r\n dtype=int))\r\n\r\n num_params = group_membership.shape[0]\r\n \r\n sample = np.array([generate_trajectory(group_membership,\r\n num_levels)\r\n for n in range(N)])\r\n return sample.reshape((N * (num_params + 1), num_params))\r\n\r\n\r\ndef _sample_groups(parameter_space, N, num_levels=4):\r\n \"\"\"Generate trajectories for groups\r\n\r\n Returns an :math:`N(g+1)`-by-:math:`k` array of `N` trajectories,\r\n where :math:`g` is the number of groups and :math:`k` is the number\r\n of factors\r\n\r\n Arguments\r\n ---------\r\n parameter_space : dict\r\n The parameter_space definition\r\n N : int\r\n The number of trajectories to generate\r\n num_levels : int, default=4\r\n The number of grid levels\r\n\r\n Returns\r\n -------\r\n numpy.ndarray\r\n \"\"\"\r\n if len(parameter_space['groups']) != parameter_space['num_vars']:\r\n raise ValueError(\"Groups do not match to number of variables\")\r\n\r\n group_membership, _ = compute_groups_matrix(parameter_space['groups'])\r\n\r\n if group_membership is None:\r\n raise ValueError(\"Please define the 'group_membership' matrix\")\r\n if not isinstance(group_membership, np.ndarray):\r\n raise TypeError(\"Argument 'group_membership' should be formatted \\\r\n as a numpy ndarray\")\r\n\r\n num_params = group_membership.shape[0]\r\n num_groups = group_membership.shape[1]\r\n sample = np.zeros((N * (num_groups + 1), num_params))\r\n sample = np.array([generate_trajectory(group_membership,\r\n num_levels)\r\n for n in range(N)])\r\n return sample.reshape((N * (num_groups + 1), num_params))\r\n\r\n\r\ndef generate_trajectory(group_membership, num_levels=4):\r\n \"\"\"Return a single trajectory\r\n\r\n Return a single trajectory of size :math:`(g+1)`-by-:math:`k`\r\n where :math:`g` is the number of groups,\r\n and :math:`k` is the number of factors,\r\n both implied by the dimensions of `group_membership`\r\n\r\n Arguments\r\n ---------\r\n group_membership : np.ndarray\r\n a k-by-g matrix which notes factor membership of groups\r\n num_levels : int, default=4\r\n The number of levels in the grid\r\n\r\n Returns\r\n -------\r\n np.ndarray\r\n \"\"\"\r\n\r\n delta = compute_delta(num_levels)\r\n\r\n # Infer number of groups `g` and number of params `k` from\r\n # `group_membership` matrix\r\n num_params = group_membership.shape[0]\r\n num_groups = group_membership.shape[1]\r\n\r\n # Matrix B - size (g + 1) * g - lower triangular matrix\r\n B = np.tril(np.ones([num_groups + 1, num_groups],\r\n dtype=int), -1)\r\n\r\n P_star = generate_p_star(num_groups)\r\n\r\n # Matrix J - a (g+1)-by-num_params matrix of ones\r\n J = np.ones((num_groups + 1, num_params))\r\n\r\n # Matrix D* - num_params-by-num_params matrix which decribes whether\r\n # factors move up or down\r\n D_star = np.diag(np.random.choice([-1, 1], num_params))\r\n\r\n x_star = generate_x_star(num_params, num_levels)\r\n\r\n # Matrix B* - size (num_groups + 1) * num_params\r\n B_star = compute_b_star(J, x_star, delta, B,\r\n group_membership, P_star, D_star)\r\n \r\n return B_star\r\n\r\n\r\ndef compute_b_star(J, x_star, delta, B, G, P_star, D_star):\r\n \"\"\"\r\n \"\"\"\r\n element_a = J[0, :] * x_star\r\n element_b = np.matmul(G, P_star).T\r\n element_c = np.matmul(2.0 * B, element_b)\r\n element_d = np.matmul((element_c - J), D_star)\r\n\r\n b_star = element_a + (delta / 2.0) * (element_d + J)\r\n return b_star\r\n\r\n\r\ndef generate_p_star(num_groups):\r\n \"\"\"Describe the order in which groups move\r\n\r\n Arguments\r\n ---------\r\n num_groups : int\r\n\r\n Returns\r\n -------\r\n np.ndarray\r\n Matrix P* - size (g-by-g)\r\n \"\"\"\r\n p_star = np.eye(num_groups, num_groups)\r\n np.random.shuffle(p_star)\r\n return p_star\r\n\r\n\r\ndef generate_x_star(num_params, num_levels):\r\n \"\"\"Generate an 1-by-num_params array to represent initial position for EE\r\n\r\n This should be a randomly generated array in the p level grid\r\n :math:`\\omega`\r\n\r\n Arguments\r\n ---------\r\n num_params : int\r\n The number of parameters (factors)\r\n num_levels : int\r\n The number of levels\r\n\r\n Returns\r\n -------\r\n numpy.ndarray\r\n The initial starting positions of the trajectory\r\n\r\n \"\"\"\r\n x_star = np.zeros((1, num_params))\r\n delta = compute_delta(num_levels)\r\n bound = 1 - delta\r\n grid = np.linspace(0, bound, int(num_levels / 2))\r\n\r\n x_star[0, :] = np.random.choice(grid, num_params)\r\n\r\n return x_star\r\n\r\ndef compute_delta(num_levels):\r\n \"\"\"Computes the delta value from number of levels\r\n\r\n Arguments\r\n ---------\r\n num_levels : int\r\n The number of levels\r\n\r\n Returns\r\n -------\r\n float\r\n \"\"\"\r\n return num_levels / (2.0 * (num_levels - 1))\r\n"
] | [
[
"numpy.random.seed",
"numpy.random.choice",
"numpy.eye",
"numpy.matmul",
"numpy.random.shuffle",
"numpy.ones",
"numpy.identity",
"numpy.zeros"
]
] |
extsui/AeroMixer | [
"bf5dc6fc75e91178234be72898c5e614476dfda8"
] | [
"bin/FontImage.py"
] | [
"#!/usr/bin/python\n# -*- coding: utf-8 -*-\nimport numpy as np\n\nclass FontImage:\n def __init__(self, fontfile, ch_width, ch_height,\n ch_num_in_line, ch_byte_size):\n self.font = np.fromfile(fontfile, dtype=np.uint8)\n self.ch_width = ch_width\n self.ch_height = ch_height\n self.ch_num_in_line = ch_num_in_line\n self.ch_byte_size = ch_byte_size\n\n def ch_to_index(self, ch_x, ch_y):\n return (ch_y * self.ch_num_in_line + ch_x) * self.ch_byte_size\n\n def get(self, ch_x, ch_y):\n index = self.ch_to_index(ch_x, ch_y)\n ch_data = []\n for i in range(self.ch_byte_size):\n ch_data.append(self.font[index + i])\n return ch_data\n"
] | [
[
"numpy.fromfile"
]
] |
benjaminpillot/gis-tools | [
"4f18d7b39e159375443e74a8c85fc3bb04fa22e6"
] | [
"gistools/network.py"
] | [
"# -*- coding: utf-8 -*-\n\n\"\"\" Module summary description.\n\nMore detailed description.\n\"\"\"\n\n# __all__ = []\n# __version__ = '0.1'\nfrom abc import abstractmethod\n\nimport networkx as nx\nimport numpy as np\nfrom geopandas import GeoDataFrame\nfrom numba import jit, float64\nfrom shapely.geometry import Point, LineString\nfrom shapely.ops import linemerge\n\nfrom gistools.coordinates import r_tree_idx\nfrom gistools.exceptions import EdgeError, NetworkError, RoadError, RoadNodeError\nfrom gistools.geometry import connect_lines_to_point, centroid, intersects\nfrom gistools.layer import return_new_instance, LineLayer, PointLayer\n\n\n# Division by zero\nfrom gistools.utils.check.descriptor import protected_property\nfrom gistools.utils.check.type import type_assert, check_type, check_type_in_collection\nfrom gistools.utils.check.value import check_string\nfrom gistools.utils.toolset import split_list_by_index\n\nnp.seterr(divide='ignore')\n\n# Constants\nSPEED_RATIO = {'m/s': 1, 'km/h': 3.6}\nTIME_FORMAT = {'s': 1, 'm': 1/60, 'h': 1/3600}\n\n\ndef multi_edges(graph):\n \"\"\" Return multiple edges between 2 nodes\n\n :return: list of edge IDs that connect the same nodes\n \"\"\"\n multiple_edges = []\n for node in graph.nodes():\n for neighbor in graph.neighbors(node):\n if graph.number_of_edges(node, neighbor) > 1:\n edge_id = [i for i in graph[node][neighbor]]\n if edge_id not in multiple_edges:\n multiple_edges.append(edge_id)\n\n return multiple_edges\n\n\ndef remote_edges(graph):\n \"\"\" Return remote edges\n\n Remote edges are not connected to anything\n :return: list of edge IDs that are remote\n \"\"\"\n rm_edges = []\n for u, v in graph.edges():\n if len(list(graph.neighbors(u))) == 1 and len(list(graph.neighbors(v))) == 1:\n rm_edges.extend(list(graph[u][v]))\n\n return rm_edges\n\n\ndef remote_nodes(graph):\n \"\"\" Return remote nodes\n\n Remote nodes are isolated nodes that are not connected to anything\n :param graph:\n :return:\n \"\"\"\n return [u for u in graph.nodes() if len(list(graph.neighbors(u))) == 0]\n\n\ndef self_loops(graph):\n \"\"\" Return self-loop edges\n\n :return: list of edge IDs that are self-loops\n \"\"\"\n slf_loops = []\n for self_loop in nx.selfloop_edges(graph, keys=True):\n slf_loops.append(self_loop[2])\n\n return slf_loops\n\n\ndef find_all_disconnected_edges_and_fix(edges, tolerance, method):\n \"\"\" Find all disconnected edges of network and fix it\n\n :param edges: Edge class instance\n :param tolerance: tolerance for considering \"disconnected\" an edge\n :param method: fix method\n :return:\n \"\"\"\n while \"There is still disconnected edges\":\n new_edges = edges.find_disconnected_islands_and_fix(tolerance=tolerance, method=method)\n if len(new_edges) < len(edges):\n edges = new_edges\n else:\n break\n\n return new_edges\n\n\nclass Edge(LineLayer):\n \"\"\" Edge class\n\n Class for implementing edges\n in a geo network\n \"\"\"\n from_to = protected_property('from_to')\n\n DEFAULT_DIRECTION = \"two-ways\"\n\n def __init__(self, edges, *args, **kwargs):\n \"\"\" Edge class constructor\n\n :param edges: geo-like file (e.g. shapefile) or geopandas data frame\n \"\"\"\n super().__init__(edges, *args, **kwargs)\n\n # Set Edge specific attributes\n if \"direction\" not in self.attributes():\n self[\"direction\"] = self.DEFAULT_DIRECTION\n # self._gpd_df[\"direction\"] = [self.DEFAULT_DIRECTION] * len(self) # Set default direction (not directed)\n\n # Simplified edges\n self._from_to = [((geom.coords.xy[0][0], geom.coords.xy[1][0]), (geom.coords.xy[0][-1], geom.coords.xy[1][\n -1])) for geom in self.geometry]\n\n # Corresponding undirected multi-graph\n self._graph = nx.MultiGraph()\n self._graph.add_edges_from([(from_to[0], from_to[1], _id) for _id, from_to in enumerate(self.from_to)])\n\n # Override point layer class attribute (To Edge is associated Node)\n self._point_layer_class = Node\n\n def _check_attr_and_dic(self, attr_name, dic):\n\n if attr_name not in self.attributes():\n raise EdgeError(\"Unknown attribute name '%s'\" % attr_name)\n\n if any([val not in list(set(self[attr_name])) for val in dic.keys()]):\n raise EdgeError(\"Invalid key in '%s'\" % dic)\n\n def find_disconnected_islands_and_fix(self, tolerance=None, method=\"delete\"):\n \"\"\" Find disconnected components in network\n\n Find disconnected components/islands graphs in multi-graph\n and apply method (fix/reconnect, keep, delete) with respect\n to a given tolerance\n :param tolerance:\n :param method:\n :return:\n \"\"\"\n method = check_string(method, {'reconnect_and_delete', 'reconnect_and_keep', 'delete'})\n sub_graphs = list((self._graph.subgraph(c) for c in nx.connected_components(self._graph)))\n main_component = max(sub_graphs, key=len)\n sub_graphs.remove(main_component)\n\n idx_edge = []\n if method == \"delete\":\n for graph in sub_graphs:\n for edge in graph.edges:\n try:\n idx_edge.append(self.from_to.index((edge[0], edge[1])))\n except ValueError:\n idx_edge.append(self.from_to.index((edge[1], edge[0])))\n\n elif method == 'reconnect_and_delete':\n pass\n elif method == 'reconnect_and_keep':\n pass\n\n return self.drop(self.index[idx_edge])\n\n # TODO: implement island reconnection and tolerance (see Edge.reconnect() method)\n\n @return_new_instance\n def get_path(self, path):\n\n edge_path = GeoDataFrame(columns=self.attributes(), crs=self.crs)\n\n for i in range(len(path) - 1):\n try:\n edge_path = edge_path.append(self._gpd_df.loc[self._from_to.index((path[i], path[i + 1]))],\n ignore_index=True)\n except ValueError:\n edge_path = edge_path.append(self._gpd_df.loc[self._from_to.index((path[i + 1], path[i]))],\n ignore_index=True)\n\n return edge_path\n\n def get_end_nodes(self):\n \"\"\" Get end nodes of edges\n\n Get end nodes, that is edge's end that does not connect\n to another edge\n :return: Node layer and list of edge IDs\n \"\"\"\n end = [(node, list(self._graph.edges(node, keys=True))[0]) for node in self._graph.nodes() if len(\n self._graph.edges(node)) == 1]\n return self._point_layer_class.from_gpd(geometry=[Point(n[0]) for n in end], crs=self.crs),\\\n [n[1][2] for n in end]\n\n def get_nodes(self):\n \"\"\" Get nodes from edges\n\n :return:\n \"\"\"\n return self._point_layer_class.from_gpd(geometry=[Point(node) for node\n in self._graph.nodes()], crs=self.crs)\n\n def get_multi_edges(self):\n \"\"\" Get multiple edges between 2 nodes\n\n :return: list of edge IDs that connect the same nodes\n \"\"\"\n return multi_edges(self._graph)\n\n def get_remote_edges(self):\n \"\"\" Get remote edges\n\n Remote edges are not connected to anything\n :return: list of edge IDs that are remote\n \"\"\"\n return remote_edges(self._graph)\n\n def get_self_loops(self):\n \"\"\" Get self-loop edges\n\n :return: list of edge IDs that are self-loops\n \"\"\"\n return self_loops(self._graph)\n\n @return_new_instance\n def get_simplified(self):\n \"\"\" Return simplified edge\n\n Return simplified Edge instance, that is only with starting\n and ending coordinates of each road segment\n :return:\n \"\"\"\n return GeoDataFrame(self._gpd_df.copy(),\n geometry=[LineString(from_to) for from_to in self._from_to],\n crs=self.crs)\n\n def get_single_edges(self):\n \"\"\" Get single edges\n\n Retrieve single edges, that is from intersection to intersection.\n Typically, when a node has only 2 neighbors, the corresponding\n edges can be merged into a new one.\n :return: list of list of edge IDs representing unique elements\n \"\"\"\n to_merge = []\n all_connected_edges = []\n\n for u, v, edge_id in self._graph.edges(keys=True):\n if edge_id not in all_connected_edges:\n connected_nodes = [u, v]\n connected_edges = [edge_id]\n for node in [u, v]:\n previous_node = node\n while \"There are neighbors to connect\":\n next_node = [n for n in self._graph.neighbors(previous_node) if n not in connected_nodes]\n if not next_node or len(next_node) > 1:\n break\n else:\n connected_edges.extend(list(self._graph[previous_node][next_node[0]]))\n connected_nodes.extend(next_node)\n previous_node = next_node[0] # previous node is now the next node in the chain\n\n all_connected_edges.extend(connected_edges)\n to_merge.append(connected_edges)\n\n return to_merge\n\n @return_new_instance\n def merge2(self):\n \"\"\" Merge edges from intersection to intersection\n\n Merge with respect to single entities, that is from\n intersecting node to intersecting node (node with\n more than 2 neighbors).\n :return:\n \"\"\"\n single_edges = self.get_single_edges()\n geometry, rows = [], []\n\n for line in single_edges:\n geometry.append(linemerge(self.geometry[line].values))\n rows.append(self._gpd_df.iloc[line[-1]])\n\n return GeoDataFrame(rows, geometry=geometry, crs=self.crs)\n\n @return_new_instance\n def reconnect(self, tolerance):\n \"\"\" Reconnect disconnected edges with respect to tolerance\n\n :param tolerance: min distance (in m) for reconnection\n :return:\n \"\"\"\n # TODO: link with Edge.find_disconnected_islands_and_fix() method\n outdf = self._gpd_df.copy()\n nodes, edge_idx = self.get_end_nodes()\n nearest_nodes, node_idx = nodes.nearest_neighbors(nodes, tolerance)\n connected_nodes = []\n\n for n, n_nodes in enumerate(nearest_nodes):\n n_idx = [node for node in node_idx[n] if node not in connected_nodes]\n if len(n_idx) > 1:\n e_idx = [edge_idx[i] for i in n_idx]\n connected_nodes.extend([i for i in n_idx if i not in connected_nodes])\n # Use outdf.geometry to ensure that changes are saved\n new_geometry = connect_lines_to_point(outdf.geometry[e_idx], centroid(n_nodes.geometry))\n for edge, geom in zip(e_idx, new_geometry):\n outdf.loc[edge, \"geometry\"] = geom\n\n return outdf\n\n @type_assert(attribute_name=str, direction_dic=dict)\n def set_direction(self, attribute_name, direction_dic):\n \"\"\" Set edge direction\n\n :param attribute_name: layer attribute from which direction must be derived\n :param direction_dic: (valid direction values: \"two-ways\", \"one-way\", \"reverse\", None)\n :return:\n \"\"\"\n self._check_attr_and_dic(attribute_name, direction_dic)\n\n for key in direction_dic.keys():\n if direction_dic[key] not in ['two-ways', 'one-way', 'reverse', None]:\n raise EdgeError(\"'%s' is not a valid direction value\" % direction_dic[key])\n self._gpd_df.loc[self[attribute_name] == key, \"direction\"] = direction_dic[key]\n\n def split_at_ending_edges(self):\n \"\"\" Split edge on which ends another edge\n\n :return:\n \"\"\"\n nodes, edge_idx = self.get_end_nodes()\n splitting_nodes = nodes[[True if intersects(geom, self.geometry, self.r_tree_idx).count(True) > 1 else False for\n geom in nodes.geometry]]\n\n return self.split_at_points(splitting_nodes)\n\n def split_at_underlying_points(self, location, *args):\n \"\"\" Override parent class method\n\n Split corresponding attributes in addition\n to layer, i.e.\n :param location:\n :return:\n \"\"\"\n output = super().split_at_underlying_points(location)\n if len(args) == 0:\n return output\n\n outputs = [output]\n for attr in args:\n split_attr = []\n for n, a in enumerate(attr):\n break_idx = [loc[1] for loc in location if loc[0] == n]\n if len(break_idx) == 0:\n split_attr.append(a)\n else:\n split_attr.extend(split_list_by_index(a, break_idx, include=False))\n outputs.append(split_attr)\n\n return tuple(outputs)\n\n @property\n def direction(self):\n return self[\"direction\"]\n\n @property\n def from_node(self):\n return [coords[0] for coords in self._from_to]\n\n @property\n def to_node(self):\n return [coords[1] for coords in self._from_to]\n\n\nclass Node(PointLayer):\n \"\"\" Node class\n\n Class for implementing a set of nodes\n in a geo network\n \"\"\"\n\n def __init__(self, nodes, *args, **kwargs):\n \"\"\" Node class constructor\n\n :param nodes:\n \"\"\"\n super().__init__(nodes, *args, **kwargs)\n\n @type_assert(edges=Edge)\n def which_edge(self, edges):\n \"\"\" Find to which edge belongs nodes\n\n :param edges:\n :return:\n \"\"\"\n return [i for node in self.geometry for i, from_to\n in enumerate(edges.from_to) if (node.x, node.y) in from_to]\n\n\nclass Road(Edge):\n \"\"\" Road class\n\n Class for implementing a set of roads in a geo network\n \"\"\"\n\n DEFAULT_MAX_SPEED = 25\n DEFAULT_ROLLING_COEFFICIENT = 0.01\n DEFAULT_ROLLOVER_CRITERION = 0.15\n\n def __init__(self, roads, *args, **kwargs):\n \"\"\" Road class constructor\n\n :param roads:\n :param args:\n :param kwargs:\n \"\"\"\n super().__init__(roads, *args, **kwargs)\n\n # Max speed on road segment\n if \"max_speed\" not in self.attributes():\n self._gpd_df[\"max_speed\"] = [self.DEFAULT_MAX_SPEED] * len(self)\n\n # Rolling coefficient on road segment\n if \"rolling_coefficient\" not in self.attributes():\n self._gpd_df[\"rolling_coefficient\"] = [self.DEFAULT_ROLLING_COEFFICIENT] * len(self)\n\n # Rollover criterion on road segment\n if \"rollover_criterion\" not in self.attributes():\n self._gpd_df[\"rollover_criterion\"] = [self.DEFAULT_ROLLOVER_CRITERION] * len(self)\n\n # Override point layer class\n self._point_layer_class = RoadNode\n\n @type_assert(attr_name=str, speed_dic=dict)\n def set_max_speed(self, attr_name, speed_dic, speed_format='km/h'):\n \"\"\" Set road max allowed speed\n\n :param attr_name:\n :param speed_dic:\n :param speed_format:\n :return:\n \"\"\"\n check_string(speed_format, ('m/s', 'km/h'))\n self._check_attr_and_dic(attr_name, speed_dic)\n\n for key in speed_dic.keys():\n if not isinstance(speed_dic[key], (float, int)):\n raise RoadError(\"Speed value must be numeric but is '%s'\" % type(speed_dic[key]))\n self._gpd_df.loc[self[attr_name] == key, \"max_speed\"] = speed_dic[key] / SPEED_RATIO[speed_format]\n\n @type_assert(attr_name=str, rolling_coeff_dic=dict)\n def set_rolling_coefficient(self, attr_name, rolling_coeff_dic):\n \"\"\" Set road rolling coefficient\n\n :param attr_name:\n :param rolling_coeff_dic:\n :return:\n \"\"\"\n self._check_attr_and_dic(attr_name, rolling_coeff_dic)\n\n for key in rolling_coeff_dic.keys():\n if not isinstance(rolling_coeff_dic[key], float):\n raise RoadError(\"Rolling coefficient must be a float but is '%s'\" % type(rolling_coeff_dic[key]))\n self._gpd_df.loc[self[attr_name] == key, \"rolling_coefficient\"] = rolling_coeff_dic[key]\n\n @type_assert(attr_name=str, rollover_criterion_dic=dict)\n def set_rollover_criterion(self, attr_name, rollover_criterion_dic):\n \"\"\" Set road rollover criterion\n\n :param attr_name:\n :param rollover_criterion_dic:\n :return:\n \"\"\"\n self._check_attr_and_dic(attr_name, rollover_criterion_dic)\n\n for key in rollover_criterion_dic.keys():\n if not isinstance(rollover_criterion_dic[key], float):\n raise RoadError(\"Rollover criterion must be a float but is '%s'\" % type(rollover_criterion_dic[key]))\n self._gpd_df.loc[self[attr_name] == key, \"rollover_criterion\"] = rollover_criterion_dic[key]\n\n @property\n def max_speed(self):\n return self[\"max_speed\"]\n\n @property\n def rolling_coefficient(self):\n return self[\"rolling_coefficient\"]\n\n @property\n def rollover_criterion(self):\n return self[\"rollover_criterion\"]\n\n\nclass RoadNode(Node):\n \"\"\" RoadIntersection class\n\n Class for implementing road intersections (inherits from Node)\n \"\"\"\n\n _check_attr_and_dic = Edge._check_attr_and_dic\n\n DEFAULT_MAX_SPEED = 0\n\n def __init__(self, nodes, *args, **kwargs):\n super().__init__(nodes, *args, **kwargs)\n\n if \"max_speed\" not in self.attributes():\n self._gpd_df[\"max_speed\"] = [self.DEFAULT_MAX_SPEED] * len(self)\n\n def set_max_speed(self, attr_name, speed_dic, speed_format='km/h'):\n \"\"\" Set max allowed speed at intersection\n\n :param attr_name:\n :param speed_dic:\n :param speed_format:\n :return:\n \"\"\"\n check_string(speed_format, ('m/s', 'km/h'))\n self._check_attr_and_dic(attr_name, speed_dic)\n\n for key in speed_dic.keys():\n if not isinstance(speed_dic[key], (float, int)):\n raise RoadNodeError(\"Speed value must be numeric but is '%s'\" % type(speed_dic[key]))\n self._gpd_df.loc[self[attr_name] == key, \"max_speed\"] = speed_dic[key] / SPEED_RATIO[speed_format]\n\n @property\n def max_speed(self):\n return self[\"max_speed\"]\n\n\nclass Network:\n \"\"\" Network base class\n\n Use this class to implement sub-class network\n geometry (e.g. from shapefile) and apply\n corresponding tools\n \"\"\"\n edges = protected_property(\"edges\")\n nodes = protected_property(\"nodes\")\n _graph = None\n\n def __init__(self, edges, nodes, match_edge_nodes=True, tolerance=1):\n \"\"\" Network class constructor\n\n :param edges: Edge instance\n :param nodes: Node instance\n :param match_edge_nodes: Boolean --> match edge nodes with respect to tolerance\n :param tolerance: distance tolerance for considering nodes and edge nodes the same (in m)\n \"\"\"\n check_type(edges, Edge, nodes, Node)\n self._edges = edges\n self._nodes = nodes\n\n # Retrieve edge nodes corresponding to nodes\n if match_edge_nodes:\n edge_nodes = self._edges.get_nodes()\n distance, nn = nodes.distance_and_nearest_neighbor(edge_nodes)\n self._nodes[\"geometry\"] = [edge_nodes.geometry[n] for n in nn]\n self._nodes = self._nodes[distance <= tolerance]\n\n def _get_nearest_edge_node(self):\n \"\"\" Get nearest node from edge\n\n :return:\n \"\"\"\n nodes = self._edges.get_nodes()\n idx = r_tree_idx(nodes.geometry)\n edge_nodes = []\n for geom in self.nodes.geometry:\n nn = list(idx.nearest(geom.bounds, 1))\n edge_nodes.append(nodes.geometry[nn[0]])\n\n return Node.from_gpd(geometry=edge_nodes, crs=self._edges.crs)\n\n @abstractmethod\n def build_graph(self, *args, **kwargs):\n pass\n\n def get_self_loops(self):\n \"\"\" Get self-loop edges in network\n\n :return: list of edge IDs\n \"\"\"\n return self_loops(self.graph)\n\n def get_remote_edges(self):\n \"\"\" Get remote edges in network\n\n :return: list of edge IDs\n \"\"\"\n return remote_edges(self.graph)\n\n def get_multi_edges(self):\n \"\"\" Get multi-edges in network\n\n :return: list of list of edge IDs\n \"\"\"\n return multi_edges(self.graph)\n\n def get_minimum_distance_to_network(self, layer):\n \"\"\" get minimum distance from given layer to network\n\n :param layer:\n :return:\n \"\"\"\n distance_to_edge = layer.distance(self.edges)\n distance_to_node = layer.distance(self.nodes)\n\n return np.minimum(distance_to_edge, distance_to_node)\n\n @type_assert(node_start=Point, node_end=Point)\n def get_shortest_path(self, node_start, node_end):\n \"\"\" Get shortest path between 2 nodes using Dijkstra algorithm\n\n :param node_start: shapely Point\n :param node_end: shapely Point\n :return: Edge instance of the path\n \"\"\"\n if node_start not in self.nodes.geometry or node_end not in self.nodes.geometry:\n raise EdgeError(\"Either source or destination node is invalid\")\n\n node_start = (node_start.x, node_start.y)\n node_end = (node_end.x, node_end.y)\n\n if node_start == node_end:\n return [] # Empty path\n\n try:\n path = nx.dijkstra_path(self.graph, node_start, node_end)\n except nx.NetworkXNoPath:\n print(\"No available path between node {} and node {}\".format(node_start, node_end))\n return None\n else:\n return self._edges.get_path(path)\n\n @type_assert(node_start=Point, node_end=Point)\n def get_shortest_path_length(self, node_start, node_end, method: str = \"networkx\"):\n \"\"\" Get dijkstra shortest path length\n\n :param node_start: shapely Point\n :param node_end: shapely Point\n :param method: {'internal', 'networkx'}\n :return: length of path in m\n \"\"\"\n check_string(method, (\"internal\", \"networkx\"))\n if method == \"internal\":\n edge_path = self.get_shortest_path(node_start, node_end)\n length = 0\n if edge_path is not None and edge_path != []:\n for edge in edge_path.geometry:\n length += edge.length\n elif edge_path is None:\n return None\n else:\n node_start = (node_start.x, node_start.y)\n node_end = (node_end.x, node_end.y)\n length = nx.dijkstra_path_length(self.graph, node_start, node_end)\n\n return length\n\n def get_all_shortest_paths(self):\n \"\"\" Get shortest paths between all graph nodes\n\n :return:\n \"\"\"\n return nx.all_pairs_dijkstra_path(self.graph)\n\n def get_all_shortest_path_lengths(self):\n \"\"\" Get shortest path lengths between all graph nodes\n\n :return:\n \"\"\"\n return nx.all_pairs_dijkstra_path_length(self.graph)\n\n @type_assert(source_node=Point)\n def get_all_shortest_paths_from_source(self, source_node):\n \"\"\" Get all paths from one source node using Dijkstra\n\n :param source_node:\n :return:\n \"\"\"\n if source_node not in self.nodes.geometry:\n raise NetworkError(\"Source node is invalid\")\n\n source_node = (source_node.x, source_node.y)\n\n return nx.single_source_dijkstra_path(self.graph, source_node)\n\n @type_assert(source_node=Point)\n def get_all_shortest_path_lengths_from_source(self, source_node):\n \"\"\"\n\n :param source_node:\n :return:\n \"\"\"\n if source_node not in self.nodes.geometry:\n raise NetworkError(\"Source node is invalid\")\n\n source_node = (source_node.x, source_node.y)\n\n return nx.single_source_dijkstra_path_length(self.graph, source_node)\n\n @type_assert(source_node=Point)\n def get_shortest_paths_from_source(self, source_node, target_nodes):\n \"\"\" Get multiple shortest paths from single source using Dijkstra\n\n :param source_node:\n :param target_nodes:\n :return:\n \"\"\"\n try:\n check_type_in_collection(target_nodes, Point)\n except TypeError:\n raise NetworkError(\"'%s' must be a collection of Point instances\" % target_nodes)\n\n paths = []\n all_paths = self.get_all_shortest_paths_from_source(source_node)\n for target in target_nodes:\n target = (target.x, target.y)\n if target in all_paths.keys():\n paths.append(self._edges.get_path(all_paths[target]))\n\n return paths\n\n @type_assert(source_node=Point)\n def get_shortest_path_lengths_from_source(self, source_node, target_nodes):\n \"\"\"\n\n :param source_node:\n :param target_nodes:\n :return:\n \"\"\"\n try:\n check_type_in_collection(target_nodes, Point)\n except TypeError:\n raise NetworkError(\"'%s' must be a collection of Point instances\" % target_nodes)\n\n path_lengths = []\n all_path_lengths = self.get_all_shortest_path_lengths_from_source(source_node)\n for target in target_nodes:\n target = (target.x, target.y)\n if target in all_path_lengths.keys():\n path_lengths.append(all_path_lengths[target])\n\n return path_lengths\n\n def get_shortest_path_matrix(self):\n \"\"\" Get shortest path matrix\n\n Compute shortest path length between all\n starting and ending nodes\n :return:\n \"\"\"\n shortest_path = np.full((len(self.nodes), len(self.nodes)), np.nan)\n edge_nodes = self._get_nearest_edge_node()\n for i, geom_from in enumerate(edge_nodes.geometry):\n for n, geom_to in enumerate(edge_nodes.geometry):\n shortest_path[i, n] = self._edges.get_dijkstra_path_length(geom_from, geom_to)\n\n return shortest_path\n\n def plot(self, edge_color=\"blue\", node_color=\"red\"):\n \"\"\"\n\n :param edge_color:\n :param node_color:\n :return:\n \"\"\"\n self.edges.plot(layer_color=edge_color)\n self.nodes.plot(layer_color=node_color)\n\n @property\n def graph(self):\n if self._graph is None:\n raise NetworkError(\"Corresponding graph has not been built\")\n else:\n return self._graph\n\n\nclass RoadNetwork(Network):\n \"\"\" Road network class\n\n Road network is basically a multi-directed graph with methods\n for computing fuel consumption and travel time of corresponding\n vehicles.\n \"\"\"\n\n roads = protected_property(\"edges\")\n\n def __init__(self, roads, nodes, *args, **kwargs):\n \"\"\"\n\n :param roads: Road instance\n :param nodes: road nodes\n \"\"\"\n check_type(roads, Road, nodes, RoadNode)\n\n super().__init__(roads, nodes, *args, **kwargs)\n\n def build_graph(self, weight_one_way=None, weight_return=None):\n \"\"\" Build corresponding multi-directed graph\n\n :param weight_one_way: array of weight values for edge in one_way direction\n :param weight_return: array of weight values for edge in reverse direction\n :return:\n \"\"\"\n if weight_one_way is None:\n weight_one_way = self._edges.length\n if weight_return is None:\n weight_return = self._edges.length\n\n if len(weight_one_way) != len(self._edges) or len(weight_return) != len(self._edges):\n raise NetworkError(\"Input argument(s) must have the same length as network edges\")\n\n weight, from_node, to_node = [], [], []\n for idx, coords in enumerate(self._edges.from_to):\n if self._edges.direction[idx] != \"reverse\":\n weight.append(weight_one_way[idx])\n from_node.append(coords[0])\n to_node.append(coords[1])\n if self._edges.direction[idx] != \"one-way\":\n weight.append(weight_return[idx])\n from_node.append(coords[1])\n to_node.append(coords[0])\n\n # Create multi-directed graph\n self._graph = nx.MultiDiGraph()\n self._graph.add_weighted_edges_from([(from_n, to_n, w) for from_n, to_n, w in zip(from_node, to_node, weight)])\n\n return self\n\n def fuel_consumption(self, gross_hp, vehicle_weight, vehicle_frontal_area=7.92, engine_efficiency=0.4,\n fuel_energy_density=35, uphill_hp=0.8, downhill_hp=0.6, drag_resistance=0.35,\n mass_correction_factor=1.05, acceleration_rate=1.5 * 0.3048,\n deceleration_rate=-9.5 * 0.3048, rho_air=1.225):\n \"\"\" Compute fuel consumption on road segments\n\n :param vehicle_weight:\n :param gross_hp:\n :param vehicle_frontal_area:\n :param engine_efficiency:\n :param fuel_energy_density: fuel efficiency as L/MJ\n :param uphill_hp:\n :param downhill_hp:\n :param drag_resistance:\n :param mass_correction_factor:\n :param acceleration_rate:\n :param deceleration_rate:\n :param rho_air: air density\n :return:\n \"\"\"\n\n slope = [self.roads.slope_of_geometry(i, slope_format=\"degree\") for i in range(len(self.roads))]\n r_curvature = [self.roads.radius_of_curvature_of_geometry(i) for i in range(len(self.roads))]\n road_length = [self.roads.length_xyz_of_geometry(i) for i in range(len(self.roads))]\n\n # Maximum limited speed\n v_max = self._get_max_limited_speed(slope, r_curvature, vehicle_weight, gross_hp, uphill_hp, downhill_hp)\n\n # Maximum speed at intersection\n v_in_max, v_out_max = self._get_velocity_at_intersection()\n\n # Fuel demand\n fuel_demand = {'one-way': [], 'reverse': []}\n\n for n in range(len(self.roads)):\n\n # Travel time and distance of acceleration\n t_time_one_way, d_a_one_way, _ = get_travel_time_and_distance_of_acceleration(\n v_max[\"one-way\"][n], road_length[n], v_in_max[n], v_out_max[n], acceleration_rate, deceleration_rate)\n t_time_reverse, d_a_reverse, _ = get_travel_time_and_distance_of_acceleration(\n v_max[\"reverse\"][n], road_length[n], v_out_max[n], v_in_max[n], acceleration_rate, deceleration_rate)\n\n # Travel time (for mean velocity over road segment)\n v_mean_one_way = road_length[n] / t_time_one_way\n v_mean_reverse = road_length[n] / t_time_reverse\n\n # Energy demand\n u_r = self.roads.rolling_coefficient[n] * vehicle_weight * 9.81 * np.cos(slope[n] * np.pi / 180) * \\\n road_length[n]\n u_a_one_way = 0.5 * rho_air * vehicle_frontal_area * drag_resistance * v_mean_one_way ** 2 * road_length[n]\n u_a_reverse = 0.5 * rho_air * vehicle_frontal_area * drag_resistance * v_mean_reverse ** 2 * road_length[n]\n u_i_one_way = mass_correction_factor * vehicle_weight * acceleration_rate * d_a_one_way\n u_i_reverse = mass_correction_factor * vehicle_weight * acceleration_rate * d_a_reverse\n u_g_one_way = vehicle_weight * 9.81 * np.sin(slope[n] * np.pi / 180) * road_length[n]\n u_g_reverse = vehicle_weight * 9.81 * np.sin(-slope[n] * np.pi / 180) * road_length[n]\n\n fuel_demand[\"one-way\"].append(np.maximum(0, (u_r + u_a_one_way + u_i_one_way + u_g_one_way) * 1e-6 / (\n fuel_energy_density * engine_efficiency)))\n fuel_demand[\"reverse\"].append(np.maximum(0, (u_r + u_a_reverse + u_i_reverse + u_g_reverse) * 1e-6 / (\n fuel_energy_density * engine_efficiency)))\n\n return fuel_demand\n\n def travel_time(self, gross_hp, vehicle_weight, acceleration_rate=1.5 * 0.3048, deceleration_rate=-9.5 * 0.3048,\n uphill_hp=0.8, downhill_hp=0.6, time_format='h'):\n \"\"\" Compute travel time for each road segment\n\n Compute travel time for each road element according\n to given parameters\n :param gross_hp: gross horse power of the vehicle\n :param vehicle_weight: weight of the vehicle\n :param acceleration_rate: positive acceleration value\n :param deceleration_rate: negative acceleration value (deceleration)\n :param uphill_hp: available horsepower on uphill road (%)\n :param downhill_hp: available horsepower on downhill road (%)\n :param time_format: format of output time (seconds, minutes, hours)\n :return:\n \"\"\"\n travel_time = {'one-way': [], 'reverse': []}\n slope = [self.roads.slope_of_geometry(i, slope_format=\"degree\") for i in range(len(self.roads))]\n r_curvature = [self.roads.radius_of_curvature_of_geometry(i) for i in range(len(self.roads))]\n road_length = [self.roads.length_xyz_of_geometry(i) for i in range(len(self.roads))]\n\n # Maximum limited speed\n v_max = self._get_max_limited_speed(slope, r_curvature, vehicle_weight, gross_hp, uphill_hp, downhill_hp)\n\n # Maximum speed at intersection\n v_in_max, v_out_max = self._get_velocity_at_intersection()\n\n for v, d, v_in, v_out in zip(v_max[\"one-way\"], road_length, v_in_max, v_out_max):\n time, _, _ = get_travel_time_and_distance_of_acceleration(v, d, v_in, v_out, acceleration_rate,\n deceleration_rate)\n travel_time[\"one-way\"].append(TIME_FORMAT[time_format] * time)\n\n for v, d, v_in, v_out in zip(v_max[\"reverse\"], road_length, v_in_max, v_out_max):\n time, _, _ = get_travel_time_and_distance_of_acceleration(v[::-1], d[::-1], v_out, v_in, acceleration_rate,\n deceleration_rate)\n travel_time[\"reverse\"].append(TIME_FORMAT[time_format] * time)\n\n return travel_time\n\n def velocity(self, gross_hp, vehicle_weight, acceleration_rate=1.5 * 0.3048, deceleration_rate=-9.5 * 0.3048,\n uphill_hp=0.8, downhill_hp=0.6):\n \"\"\" Compute velocity for each road segment\n\n :param gross_hp:\n :param vehicle_weight:\n :param acceleration_rate:\n :param deceleration_rate:\n :param uphill_hp:\n :param downhill_hp:\n :return:\n \"\"\"\n velocity = {'one-way': [], 'reverse': []}\n slope = [self.roads.slope_of_geometry(i, slope_format=\"degree\") for i in range(len(self.roads))]\n r_curvature = [self.roads.radius_of_curvature_of_geometry(i) for i in range(len(self.roads))]\n road_length = [self.roads.length_xyz_of_geometry(i) for i in range(len(self.roads))]\n\n # Maximum limited speed\n v_max = self._get_max_limited_speed(slope, r_curvature, vehicle_weight, gross_hp, uphill_hp, downhill_hp)\n\n # Maximum speed at intersection\n v_in_max, v_out_max = self._get_velocity_at_intersection()\n\n for v, d, v_in, v_out in zip(v_max[\"one-way\"], road_length, v_in_max, v_out_max):\n _, _, speed = get_travel_time_and_distance_of_acceleration(v, d, v_in, v_out, acceleration_rate,\n deceleration_rate)\n velocity[\"one-way\"].append(speed)\n\n for v, d, v_in, v_out in zip(v_max[\"reverse\"], road_length, v_in_max, v_out_max):\n _, _, speed = get_travel_time_and_distance_of_acceleration(v[::-1], d[::-1], v_out, v_in,\n acceleration_rate, deceleration_rate)\n velocity[\"reverse\"].append(speed)\n\n velocity[\"v_max_one_way\"] = v_max[\"one-way\"]\n velocity[\"v_max_reverse\"] = v_max[\"reverse\"]\n velocity[\"v_slope_one_way\"] = v_max[\"slope_one_way\"]\n velocity[\"v_slope_reverse\"] = v_max[\"slope_reverse\"]\n velocity[\"v_curvature\"] = v_max[\"curvature\"]\n\n return velocity\n\n def _get_velocity_at_intersection(self):\n \"\"\" Velocity in crossing intersections\n\n Define maximum allowed entering and exiting velocities for each road segment\n :return:\n \"\"\"\n node_coords = [(x, y) for x, y in zip(self.nodes.geometry.x, self.nodes.geometry.y)]\n v_in = np.full(len(self.roads), 0)\n v_out = np.full(len(self.roads), 0)\n\n for from_to in self.roads.from_to:\n v_in[node_coords.index(from_to[0])] = self.nodes.max_speed[node_coords.index(from_to[0])]\n v_out[node_coords.index(from_to[1])] = self.nodes.max_speed[node_coords.index(from_to[1])]\n\n return v_in, v_out\n\n #################\n # Private methods\n\n def _get_max_limited_speed(self, slope, r_curvature, vehicle_weight, gross_hp, uphill_hp, downhill_hp):\n \"\"\" Get maximum limited speed on road segments\n\n :param slope:\n :param r_curvature:\n :param vehicle_weight:\n :param gross_hp:\n :param uphill_hp:\n :param downhill_hp:\n :return:\n \"\"\"\n v_max = dict(slope_one_way=[], slope_reverse=[], curvature=[])\n\n # Maximum speed due to slope (1 mechanical hp = 745.699872 W)\n ehp_uphill = gross_hp * uphill_hp * 745.699872\n ehp_downhill = gross_hp * downhill_hp * 745.699872\n for n in range(len(self.roads)):\n v_one_way = np.zeros(len(slope[n]))\n v_reverse = np.zeros(len(slope[n]))\n grade_resistance = 9.81 * vehicle_weight * np.sin(np.fabs(slope[n]) * np.pi / 180)\n rolling_resistance = 9.81 * self.roads.rolling_coefficient[n] * vehicle_weight * np.cos(slope[n] * np.pi /\n 180)\n v_one_way[slope[n] < 0] = ehp_downhill / np.maximum((grade_resistance[slope[n] < 0] - rolling_resistance[\n slope[n] < 0]), 0)\n v_one_way[slope[n] >= 0] = ehp_uphill / (grade_resistance[slope[n] >= 0] + rolling_resistance[slope[n] >=\n 0])\n v_reverse[slope[n] > 0] = ehp_downhill / np.maximum((grade_resistance[slope[n] > 0] - rolling_resistance[\n slope[n] > 0]), 0)\n v_reverse[slope[n] <= 0] = ehp_uphill / (grade_resistance[slope[n] <= 0] + rolling_resistance[slope[n] <=\n 0])\n v_max[\"slope_one_way\"].append(v_one_way)\n v_max[\"slope_reverse\"].append(v_reverse)\n v_max[\"curvature\"].append((self.roads.rollover_criterion[n] * r_curvature[n] * 9.81) ** 0.5)\n\n # Get maximum limiting speed, i.e. minimum among all previous values\n v_max[\"one-way\"] = [np.minimum(np.minimum(v_r, v_s), v_limit) for v_r, v_s, v_limit in\n zip(v_max[\"curvature\"], v_max[\"slope_one_way\"], self.roads.max_speed)]\n v_max[\"reverse\"] = [np.minimum(np.minimum(v_r, v_s), v_limit) for v_r, v_s, v_limit in\n zip(v_max[\"curvature\"], v_max[\"slope_reverse\"], self.roads.max_speed)]\n\n return v_max\n\n\n@jit((float64[:], float64[:], float64, float64, float64, float64), cache=True, nopython=True)\ndef get_travel_time_and_distance_of_acceleration(v_max, road_segment_length, v_in_max, v_out_max, a_1, a_2):\n \"\"\" Get travel time on road segment\n\n :param v_max: maximum limited speed on road segment\n :param road_segment_length: length of road segment\n :param v_in_max:\n :param v_out_max:\n :param a_1: acceleration rate\n :param a_2: deceleration rate\n :return:\n \"\"\"\n\n v = np.concatenate((np.array([v_in_max]), v_max[1:], np.array([v_out_max])))\n t_time = np.zeros(len(v_max))\n d_a = np.zeros(len(v_max)) # Distance of acceleration\n\n tol = 0.01 # Tolerance for comparing d <= s --> d must be <= s + tolerance (In order to avoid too much\n # backward in the while loop, as well as floating errors where d is not exactly equal to s at 1e-10)\n n = 0\n while n <= len(v_max) - 1:\n v_in = v[n]\n v_fn = v[n + 1]\n s = road_segment_length[n]\n v_m = v_max[n]\n\n d_1 = (v_m ** 2 - v_in ** 2) / (2 * a_1)\n d_2 = (v_fn ** 2 - v_m ** 2) / (2 * a_2)\n if v_m > v_in and v_m > v_fn:\n if v_fn >= v_in:\n d = (v_fn ** 2 - v_in ** 2) / (2 * a_1)\n else:\n d = (v_fn ** 2 - v_in ** 2) / (2 * a_2)\n if d_1 + d_2 <= s:\n t_time[n] = (v_m - v_in) / a_1 + (v_fn - v_m) / a_2 + (s - (d_1 + d_2)) / v_m\n d_a[n] = d_1\n v[n + 1] = v_fn\n n += 1\n else:\n if d <= s + tol:\n v_min = ((2 * s * a_1 * a_2 + a_2 * v_in ** 2 - a_1 * v_fn ** 2) / (a_2 - a_1)) ** 0.5\n t_time[n] = (v_min - v_in) / a_1 + (v_fn - v_min) / a_2\n d_a[n] = (v_min ** 2 - v_in ** 2) / (2 * a_1)\n v[n + 1] = v_fn\n n += 1\n else:\n if v_fn >= v_in:\n v_front = (v_in ** 2 + 2 * a_1 * s) ** 0.5\n t_time[n] = (v_front - v_in) / a_1\n d_a[n] = s\n v[n + 1] = v_front\n n += 1\n else:\n v[n] = (v_fn ** 2 - 2 * a_2 * s) ** 0.5\n n -= 1 if n > 0 else 0\n elif v_fn < v_m <= v_in:\n if d_2 <= s + tol:\n t_time[n] = (v_fn - v_m) / a_2 + (s - d_2) / v_m\n v[n + 1] = v_fn\n n += 1\n else:\n v[n] = (v_fn ** 2 - 2 * a_2 * s) ** 0.5\n n -= 1 if n > 0 else 0\n elif v_in < v_m <= v_fn:\n if d_1 <= s:\n t_time[n] = (v_m - v_in) / a_1 + (s - d_1) / v_m\n d_a[n] = d_1\n v[n + 1] = v_m\n else:\n v_front = (v_in ** 2 + 2 * a_1 * s) ** 0.5\n t_time[n] = (v_front - v_in) / a_1\n d_a[n] = s\n v[n + 1] = v_front\n n += 1\n elif v_m <= v_in and v_m <= v_fn:\n t_time[n] = s / v_m\n v[n + 1] = v_m\n n += 1\n\n return t_time, d_a, v\n"
] | [
[
"numpy.maximum",
"numpy.minimum",
"numpy.cos",
"numpy.sin",
"numpy.seterr",
"numpy.array",
"numpy.fabs"
]
] |
nerettilab/SIMBA3D | [
"4df8f13c3b73a3df4cfa65ad091631bee136ba64"
] | [
"simba3d/gradient_manager.py"
] | [
"# -*- coding: utf-8 -*-\n\"\"\"\n\n\n\n@author: Michael Rosenthal\n\"\"\"\n\n# import the gradients\n'''\nSome gradients have cython code associated with them to speed up the\ncomputation. Try and import the cython and import a python if that fails.\n'''\n\nimport numpy as np\n#import time\n#import scipy.spatial.distance as ssd\n#from scipy.spatial.distance import pdist\n#from scipy.sparse import csr_matrix\n#from scipy.optimize import minimize,check_grad\n#from scipy.misc import comb\nimport scipy.sparse as sp\n\nfrom simba3d.pairwise_computations import run_pairwise_computations,run_adjacent_computations\nfrom simba3d.gradient_poisson import gradient_poisson\nfrom simba3d.h1_penalty import gradient_h1\nfrom simba3d.h2a_penalty import gradient_h2a\nfrom simba3d.h2b_penalty import run_h2b_computations,gradient_h2b\nfrom simba3d.h2c_penalty import run_h2c_computations,gradient_h2c\n\nclass gradient_manager():\n\t'''\n\tManages the gradients\n\n\tAs simba3d has developed, we have gone through many penalty functions. To\n\tease the burden of maintaining these functions, a class object\n\thas been made to efficiciently manage gradient computations.\n\n\tThe reason this is needed is because the gradient computations need to be\n\tvery efficient. They are called thousands of times within an optimization.\n\tThis requires efficient coding and resource utlization. Several functions\n\tuse the same types of computations. Rather than computing these values\n\tmultiple times, it is better to store them within the object class and then\n\tutilize them as required for a particular setting.\n\n\tThere is also the use of c and cython code. As a policy, we first create\n\ta python version of the gradient, and then create a niave cython implementation.\n\tAfterwards, the cython code is further refined to boost performance. This requires\n\tcopilation of source code. If the cython code fails to import, there is a python\n\timplementation which can be loaded natively with a minimal number of depencies.\n\n\t'''\n\tdef __init__(self,term_parameters=None,threads=None):\n\t\t# initialize the stored inputs, calculations, and parameters\n\t\t# set default values for parameters here (set to None to error out when misspecified)\n\t\tself.contact_row_index=None\n\t\tself.contact_col_index=None\n\t\tself.contact_value=None\n\t\tself.contact_sum=None\n\t\tself.lenght=None\n\t\tself.number_of_pairs=None\n\t\tself.pairwise_difference_x=list()\n\t\tself.pairwise_difference_y=list()\n\t\tself.pairwise_difference_z=list()\n\t\tself.pairwise_distance=list()\n\t\tself.sum_pairwise_distance=None\n\t\tself.average_pairwise_distance=None\n\t\tself.sum_adjacent_distance=None\n\t\tself.sum_of_squared_adjacent_distance=None\n\t\tself.average_adjacent_distance=None\n\t\tself.poisson_a_parameter=-3.0\n\t\tself.poisson_b_parameter=1.0\n\t\tself.poisson_loglikelihood=None\n\t\tself.h1_uniform_spacing_value=None\n\t\tself.h2a_value=None\n\t\tself.h2b_alpha=10\n\t\tself.h2b_radius=1\n\t\tself.h2b_unwieghted_value=None\n\t\tself.h2b_F=None\n\t\tself.h2b_H=None\n\t\tself.h2b_G=None\n\t\tself.h2c_radius=1.0\n\t\tself.h2c_unwieghted_value=None\n\t\tself.x_gradient=None\n\t\tself.y_gradient=None\n\t\tself.z_gradient=None\n\t\tself.e=None\n\t\t# a list of functions is created upon initialization to eliminate\n\t\t# the need for if statements or switches during the optimization\n\t\tself.functions =[]\n\t\t# For each iteration, there are calculations that are used in multiple gradients.\n\t\t# This list tells the gradient manager which computations it needs to update prior\n\t\t# to computing the gradients.\n\t\tself.shared_computations=[]\n\t\tpairwise_computations_needed=False\n\t\tadjacent_computations_needed=False\n\t\th2b_computations_needed=False\n\t\th2c_computations_needed=False\n\t\tif term_parameters is None:\n\t\t\tterm_parameters={}\n\t\tif \"poisson_weight\" in term_parameters:\n\t\t\tif term_parameters[\"poisson_weight\"]>0:\n\t\t\t\tself.functions.append([\"poisson\",term_parameters[\"poisson_weight\"],self.gradient_data])\n\t\t\t\tpairwise_computations_needed=True\n\t\t\tif \"poisson_parameter_a\" in term_parameters:\n\t\t\t\t self.poisson_a_parameter=term_parameters[\"poisson_parameter_a\"]\n\t\t\tif \"poisson_parameter_b\" in term_parameters:\n\t\t\t\t self.poisson_b_parameter=term_parameters[\"poisson_parameter_b\"]\n\t\tif \"h1_weight\" in term_parameters:\n\t\t\tif term_parameters[\"h1_weight\"]>0:\n\t\t\t\tself.functions.append([\"h1\",term_parameters[\"h1_weight\"],self.gradient_h1])\n\t\t\t\tpairwise_computations_needed=True\n\t\t\t\tadjacent_computations_needed=True\n\t\tif \"h2a_weight\" in term_parameters:\n\t\t\tif term_parameters[\"h2a_weight\"]>0:\n\t\t\t\tself.functions.append([\"h2a\",term_parameters[\"h2a_weight\"],self.gradient_h2a])\n\t\t\t\tpairwise_computations_needed=True\n\t\t\t\tadjacent_computations_needed=True\n\t\t\tif \"h2a_parameter_radius\" in term_parameters:\n\t\t\t\tself.h2c_radius=term_parameters[\"h2a_parameter_radius\"]\n\t\tif \"h2b_weight\" in term_parameters:\n\t\t\tif term_parameters[\"h2b_weight\"]>0:\n\t\t\t\tself.functions.append([\"h2b\",term_parameters[\"h2b_weight\"],self.gradient_h2b])\n\t\t\t\tpairwise_computations_needed=True\n\t\t\t\tadjacent_computations_needed=True\n\t\t\t\th2b_computations_needed=True\n\t\tif \"h2c_weight\" in term_parameters:\n\t\t\tif term_parameters[\"h2c_weight\"]>0:\n\t\t\t\tself.functions.append([\"h2c\",term_parameters[\"h2c_weight\"],self.gradient_h2c])\n\t\t\t\tpairwise_computations_needed=True\n\t\t\t\tadjacent_computations_needed=True\n\t\t\t\th2c_computations_needed=True\n\t\t# append the shared computation tasks to the list of shared computations\n\t\tif pairwise_computations_needed:\n\t\t\tself.shared_computations.append(self.run_pairwise_computations)\n\t\tif adjacent_computations_needed:\n\t\t\tself.shared_computations.append(self.run_adjacent_computations)\n\t\tif h2b_computations_needed:\n\t\t\tself.shared_computations.append(self.run_h2b_computations)\n\t\tif h2c_computations_needed:\n\t\t\tself.shared_computations.append(self.run_h2c_computations)\n\n\tdef set_contact_data(self,contact_row_index,contact_col_index,contact_value):\n\t\t'''\n\t\t'''\n\t\tself.contact_row_index=contact_row_index\n\t\tself.contact_col_index=contact_col_index\n\t\tself.contact_value=contact_value\n\t\tself.contact_sum=sum(contact_value)\n\tdef add_population_contact_data(self,weight,contact_row_index,contact_col_index,contact_value):\n\t\t'''\n\t\t'''\n\t\tC=sp.coo_matrix((self.ontact_value,(self.contact_row_index,self.contact_col_index)),shape=(self.length,self.length))\n\t\tCpop=sp.coo_matrix((contact_value,(contact_row_index,contact_col_index)),shape=(self.length,self.length))\n\t\tC=C+weight*Cpop\n\t\tself.contact_row_index=C.row.tolist()\n\t\tself.contact_col_index=C.col.tolist()\n\t\tself.contact_value=C.data.tolist()\n\t\tself.contact_sum=sum(self.contact_value)\n\tdef run_pairwise_computations(self):\n\t\t'''\n\t\tStores shared computations derived from each possible combination of pairs\n\t\t'''\n\t\t# pass in mutable objects\n\t\tself.pairwise_difference_x=[0]*self.number_of_pairs\n\t\tself.pairwise_difference_y=[0]*self.number_of_pairs\n\t\tself.pairwise_difference_z=[0]*self.number_of_pairs\n\t\tself.pairwise_distance=[0]*self.number_of_pairs\n\t\tseries=[0]*2\n\t\t# There are several scalar values computed. Rather than outputing them in the return\n\t\t# I opted to pass in mutable objects so that the memory is already allocated\n\t\t# for them and I can assume the memory is allocated when I make the c code.\n\t\trun_pairwise_computations(\n\t\t\t\t\t\t\t\tself.number_of_pairs,\n\t\t\t\t\t\t\t\tself.x,\n\t\t\t\t\t\t\t\tself.y,\n\t\t\t\t\t\t\t\tself.z,\n\t\t\t\t\t\t\t\tself.pairwise_difference_x,\n\t\t\t\t\t\t\t\tself.pairwise_difference_y,\n\t\t\t\t\t\t\t\tself.pairwise_difference_z,\n\t\t\t\t\t\t\t\tself.pairwise_distance,\n\t\t\t\t\t\t\t\tseries\n\t\t\t\t\t\t\t\t)\n\t\tself.sum_pairwise_distance = series[0]\n\t\tself.average_pairwise_distance= series[1]\n\n\tdef run_adjacent_computations(self):\n\t\t'''\n\t\tStores shared computations derived from each adjacent pair of points\n\n\t\tDepends on computations made during run_pairwise_computations\n\t\t'''\n\t\tseries=[0]*4\n\t\trun_adjacent_computations(self.length,self.pairwise_distance,series)\n\t\tself.sum_adjacent_distance = series[0]\n\t\tself.sum_of_squared_adjacent_distance= series[1]\n\t\tself.average_adjacent_distance= series[2]\n\tdef run_h2b_computations(self):\n\t\t'''\n\n\t\tDepends on computations made during run_adjacent_computations and run_pairwise_computations\n\t\t'''\n\t\tseries=[0]*1\n\t\tself.h2b_F=[0]*\tself.number_of_pairs\n\t\tself.h2b_G=[0]*\tself.number_of_pairs\n\t\tself.h2b_H=[0]*\tself.number_of_pairs\n\t\trun_h2b_computations(\n\t\t\t\t\t\t\tself.length,\n\t\t\t\t\t\t\tself.number_of_pairs,\n\t\t\t\t\t\t\tself.h2b_alpha,\n\t\t\t\t\t\t\tself.average_adjacent_distance,\n\t\t\t\t\t\t\tself.pairwise_distance,\n\t\t\t\t\t\t\tself.h2b_F,\n\t\t\t\t\t\t\tself.h2b_G,\n\t\t\t\t\t\t\tself.h2b_H,\n\t\t\t\t\t\t\tseries\n\t\t\t\t\t\t\t)\n\t\tself.h2b_unwieghted_value=series[0]\n\tdef run_h2c_computations(self):\n\t\t'''\n\n\t\tDepends on computations made during run_adjacent_computations and run_pairwise_computations\n\t\t'''\n\t\tseries=[0]*1\n\t\tself.h2b_F=[0]*\tself.number_of_pairs\n\t\trun_h2c_computations(\n\t\t\t\t\t\t\tself.length,\n\t\t\t\t\t\t\tself.number_of_pairs,\n\t\t\t\t\t\t\tself.h2c_radius,\n\t\t\t\t\t\t\tself.average_adjacent_distance,\n\t\t\t\t\t\t\tself.pairwise_distance,\n\t\t\t\t\t\t\tself.h2b_F,\n\t\t\t\t\t\t\tseries\n\t\t\t\t\t\t\t)\n\t\tself.h2c_unwieghted_value=series[0]\n\tdef gradient_data(self,penalty_weight,x_gradient,y_gradient,z_gradient):\n\t\t'''\n\t\t'''\n\t\tseries=[0]*1\n\t\tgradient_poisson(\n\t\t\t\t\t\tpenalty_weight,\n\t\t\t\t\t\tself.contact_row_index,\n\t\t\t\t\t\tself.contact_col_index,\n\t\t\t\t\t\tself.contact_value,\n\t\t\t\t\t\tself.poisson_a_parameter,\n\t\t\t\t\t\tself.poisson_b_parameter,\n\t\t\t\t\t\tself.contact_sum,\n\t\t\t\t\t\tself.pairwise_difference_x,\n\t\t\t\t\t\tself.pairwise_difference_y,\n\t\t\t\t\t\tself.pairwise_difference_z,\n\t\t\t\t\t\tself.pairwise_distance,\n\t\t\t\t\t\tx_gradient,\n\t\t\t\t\t\ty_gradient,\n\t\t\t\t\t\tz_gradient,\n\t\t\t\t\t\tseries\n\t\t\t\t\t\t)\n\t\tself.poisson_loglikelihood =penalty_weight*series[0]\n\t\treturn self.poisson_loglikelihood\n\n\tdef gradient_h1(self,penalty_weight,x_gradient,y_gradient,z_gradient):\n\t\t'''\n\t\tA uniform spacing penalty which will force the nodes to be spaces uniformly.\n\n\t\tDepends on computations made during run_adjacent_computations and run_pairwise_computations\n\t\t'''\n\t\tgradient_h1(\n\t\t\t\tpenalty_weight,\n\t\t\t\tself.length,\n\t\t\t\tself.sum_adjacent_distance,\n\t\t\t\tself.sum_of_squared_adjacent_distance,\n\t\t\t\tself.pairwise_difference_x,\n\t\t\t\tself.pairwise_difference_y,\n\t\t\t\tself.pairwise_difference_z,\n\t\t\t\tself.pairwise_distance,\n\t\t\t\tx_gradient,\n\t\t\t\ty_gradient,\n\t\t\t\tz_gradient\n\t\t\t\t\t)\n\t\tself.h1_uniform_spacing_value = penalty_weight*((self.length-1)*self.sum_of_squared_adjacent_distance/(self.sum_adjacent_distance*self.sum_adjacent_distance) -1)\n\t\treturn self.h1_uniform_spacing_value\n\tdef gradient_h2a(self,penalty_weight,x_gradient,y_gradient,z_gradient):\n\t\t'''\n\t\t'''\n\t\tseries=[0]*1\n\t\tgradient_h2a(\n\t\t\t\tpenalty_weight,\n\t\t\t\tself.length,\n\t\t\t\tself.pairwise_difference_x,\n\t\t\t\tself.pairwise_difference_y,\n\t\t\t\tself.pairwise_difference_z,\n\t\t\t\tself.pairwise_distance,\n\t\t\t\tx_gradient,\n\t\t\t\ty_gradient,\n\t\t\t\tz_gradient,\n\t\t\t\tseries\n\t\t\t\t)\n\t\tself.h2a_value=penalty_weight*series[0];\n\t\treturn self.h2a_value\n\tdef gradient_h2b(self,penalty_weight,x_gradient,y_gradient,z_gradient):\n\t\t'''\n\t\t'''\n\t\tgradient_h2b(\n\t\t\t\tpenalty_weight,\n\t\t\t\tself.length,\n\t\t\t\tself.number_of_pairs,\n\t\t\t\tself.h2b_alpha,\n\t\t\t\tself.h2b_F,\n\t\t\t\tself.h2b_G,\n\t\t\t\tself.h2b_H,\n\t\t\t\tself.average_adjacent_distance,\n\t\t\t\tself.pairwise_difference_x,\n\t\t\t\tself.pairwise_difference_y,\n\t\t\t\tself.pairwise_difference_z,\n\t\t\t\tself.pairwise_distance,\n\t\t\t\tx_gradient,\n\t\t\t\ty_gradient,\n\t\t\t\tz_gradient\n\t\t\t\t)\n\t\treturn penalty_weight*self.h2b_unwieghted_value\n\tdef gradient_h2c(self,penalty_weight,x_gradient,y_gradient,z_gradient):\n\t\t'''\n\t\t'''\n\t\tgradient_h2c(\n\t\t\t\tpenalty_weight,\n\t\t\t\tself.length,\n\t\t\t\tself.number_of_pairs,\n\t\t\t\tself.h2b_alpha,\n\t\t\t\tself.h2b_F,\n\t\t\t\tself.h2c_radius,\n\t\t\t\tself.average_adjacent_distance,\n\t\t\t\tself.pairwise_difference_x,\n\t\t\t\tself.pairwise_difference_y,\n\t\t\t\tself.pairwise_difference_z,\n\t\t\t\tself.pairwise_distance,\n\t\t\t\tx_gradient,\n\t\t\t\ty_gradient,\n\t\t\t\tz_gradient\n\t\t\t\t)\n\t\treturn penalty_weight*self.h2c_unwieghted_value\n\tdef compute_gradient(self,x,y,z,x_gradient,y_gradient,z_gradient):\n\t\t'''\n\t\tCompute the energy and gradient of the functions for a given input curve\n\t\t'''\n\t\tself.length=len(x)\n\t\tself.number_of_pairs=int(self.length*(self.length-1)/2);\n\t\tself.x=list(x)\n\t\tself.y=list(y)\n\t\tself.z=list(z)\n\t\t# Loop through the list of shared calculations\n\t\tfor shared_computation in self.shared_computations:\n\t\t\tshared_computation()\n\n\t\t# initialize the gradient\n\t\tself.x_gradient=[0]*self.length\n\t\tself.y_gradient=[0]*self.length\n\t\tself.z_gradient=[0]*self.length\n\t\t# initialize total energy\n\t\tself.e=0.0\n\t\t# loop through the non-trivial terms\n\t\tfor functional in self.functions:\n\t\t\tself.e+=functional[2](functional[1],x_gradient,y_gradient,z_gradient)\n"
] | [
[
"scipy.sparse.coo_matrix"
]
] |
rickybalin/ALCF | [
"3696756d2af90f1ba179caa46d2001d07db5e01d"
] | [
"SmartSim/Theta/onlineInference/Python/src/inference.py"
] | [
"import argparse\nfrom time import sleep\nimport numpy as np\nfrom smartredis import Client\n\ndef init_client(nnDB):\n if (nnDB==1):\n client = Client(cluster=False)\n else:\n client = Client(cluster=True)\n return client\n\ndef main():\n # Import and initialize MPI\n import mpi4py\n mpi4py.rc.initialize = False\n mpi4py.rc.threads = True\n mpi4py.rc.thread_level = 'multiple'\n from mpi4py import MPI\n if not MPI.Is_initialized():\n MPI.Init_thread()\n comm = MPI.COMM_WORLD\n size = comm.Get_size()\n rank = comm.Get_rank()\n\n # Parse arguments\n parser = argparse.ArgumentParser(description='')\n parser.add_argument('--dbnodes',default=1,type=int,help='Number of database nodes')\n args = parser.parse_args()\n\n # Initialize SmartRedis clients\n client = init_client(args.dbnodes)\n comm.Barrier()\n if (rank==0):\n print('All SmartRedis clients initialized')\n\n # Load model onto Orchestrator\n if (rank==0):\n client.set_model_from_file('model', './model_jit.pt', 'TORCH', device='CPU')\n print('Uploaded model to Orchestrator')\n comm.Barrier()\n\n # Set parameters for array of random numbers to be set as inference data\n # In this example we create inference data for a simple function\n # y=f(x), which has 1 input (x) and 1 output (y)\n # The domain for the function is from 0 to 10\n # The inference data is obtained from a uniform distribution over the domain\n nSamples = 64\n xmin = 0.0 \n xmax = 10.0\n\n # Generate the key for the inference data\n # The key will be tagged with the rank ID\n inf_key = 'x.'+str(rank)\n pred_key = 'p.'+str(rank)\n\n # Open file to write predictions\n if (rank==0):\n fid = open('./predictions.dat', 'w')\n\n # Emulate integration of PDEs with a do loop\n numts = 2\n for its in range(numts):\n sleep(10)\n\n # Generate the input data for the polynomial y=f(x)=x**2 + 3*x + 1\n inputs = np.random.uniform(low=xmin, high=xmax, size=(nSamples,1))\n\n # Perform inferece\n client.put_tensor(inf_key, inputs)\n client.run_model('model', inputs=[inf_key], outputs=[pred_key])\n predictions = client.get_tensor(pred_key)\n comm.Barrier()\n if (rank==0):\n print(f'Performed inference on all ranks for step {its+1}')\n\n # Write predictions to file\n if (rank==0):\n truth = inputs**2 + 3*inputs + 1\n for i in range(nSamples):\n fid.write(f'{inputs[i,0]:.6e} {predictions[i,0]:.6e} {truth[i,0]:.6e}\\n')\n\n if (rank==0):\n fid.close()\n\n\nif __name__ == '__main__':\n main()\n"
] | [
[
"numpy.random.uniform"
]
] |
LightSecAgg/MLSys2022_anonymous | [
"ffda061ce8edaad2e7a3b8d6c38421c06f5bf7f7"
] | [
"fedml_api/data_preprocessing/cifar100/data_loader.py"
] | [
"import logging\n\nimport numpy as np\nimport torch\nimport torch.utils.data as data\nimport torchvision.transforms as transforms\n\nfrom .datasets import CIFAR100_truncated\n\n\n# generate the non-IID distribution for all methods\ndef read_data_distribution(filename='./data_preprocessing/non-iid-distribution/CIFAR10/distribution.txt'):\n distribution = {}\n with open(filename, 'r') as data:\n for x in data.readlines():\n if '{' != x[0] and '}' != x[0]:\n tmp = x.split(':')\n if '{' == tmp[1].strip():\n first_level_key = int(tmp[0])\n distribution[first_level_key] = {}\n else:\n second_level_key = int(tmp[0])\n distribution[first_level_key][second_level_key] = int(tmp[1].strip().replace(',', ''))\n return distribution\n\n\ndef read_net_dataidx_map(filename='./data_preprocessing/non-iid-distribution/CIFAR10/net_dataidx_map.txt'):\n net_dataidx_map = {}\n with open(filename, 'r') as data:\n for x in data.readlines():\n if '{' != x[0] and '}' != x[0] and ']' != x[0]:\n tmp = x.split(':')\n if '[' == tmp[-1].strip():\n key = int(tmp[0])\n net_dataidx_map[key] = []\n else:\n tmp_array = x.split(',')\n net_dataidx_map[key] = [int(i.strip()) for i in tmp_array]\n return net_dataidx_map\n\n\ndef record_net_data_stats(y_train, net_dataidx_map):\n net_cls_counts = {}\n\n for net_i, dataidx in net_dataidx_map.items():\n unq, unq_cnt = np.unique(y_train[dataidx], return_counts=True)\n tmp = {unq[i]: unq_cnt[i] for i in range(len(unq))}\n net_cls_counts[net_i] = tmp\n logging.debug('Data statistics: %s' % str(net_cls_counts))\n return net_cls_counts\n\n\nclass Cutout(object):\n def __init__(self, length):\n self.length = length\n\n def __call__(self, img):\n h, w = img.size(1), img.size(2)\n mask = np.ones((h, w), np.float32)\n y = np.random.randint(h)\n x = np.random.randint(w)\n\n y1 = np.clip(y - self.length // 2, 0, h)\n y2 = np.clip(y + self.length // 2, 0, h)\n x1 = np.clip(x - self.length // 2, 0, w)\n x2 = np.clip(x + self.length // 2, 0, w)\n\n mask[y1: y2, x1: x2] = 0.\n mask = torch.from_numpy(mask)\n mask = mask.expand_as(img)\n img *= mask\n return img\n\n\ndef _data_transforms_cifar100():\n CIFAR_MEAN = [0.5071, 0.4865, 0.4409]\n CIFAR_STD = [0.2673, 0.2564, 0.2762]\n\n train_transform = transforms.Compose([\n transforms.ToPILImage(),\n transforms.RandomCrop(32, padding=4),\n transforms.RandomHorizontalFlip(),\n transforms.ToTensor(),\n transforms.Normalize(CIFAR_MEAN, CIFAR_STD),\n ])\n\n train_transform.transforms.append(Cutout(16))\n\n valid_transform = transforms.Compose([\n transforms.ToTensor(),\n transforms.Normalize(CIFAR_MEAN, CIFAR_STD),\n ])\n\n return train_transform, valid_transform\n\ndef load_cifar100_data(datadir):\n train_transform, test_transform = _data_transforms_cifar100()\n\n cifar10_train_ds = CIFAR100_truncated(datadir, train=True, download=True, transform=train_transform)\n cifar10_test_ds = CIFAR100_truncated(datadir, train=False, download=True, transform=test_transform)\n\n X_train, y_train = cifar10_train_ds.data, cifar10_train_ds.target\n X_test, y_test = cifar10_test_ds.data, cifar10_test_ds.target\n\n return (X_train, y_train, X_test, y_test)\n\n\ndef partition_data(dataset, datadir, partition, n_nets, alpha):\n logging.info(\"*********partition data***************\")\n X_train, y_train, X_test, y_test = load_cifar100_data(datadir)\n n_train = X_train.shape[0]\n # n_test = X_test.shape[0]\n\n if partition == \"homo\":\n total_num = n_train\n idxs = np.random.permutation(total_num)\n batch_idxs = np.array_split(idxs, n_nets)\n net_dataidx_map = {i: batch_idxs[i] for i in range(n_nets)}\n\n elif partition == \"hetero\":\n min_size = 0\n K = 100\n N = y_train.shape[0]\n logging.info(\"N = \" + str(N))\n net_dataidx_map = {}\n\n while min_size < 10:\n idx_batch = [[] for _ in range(n_nets)]\n # for each class in the dataset\n for k in range(K):\n idx_k = np.where(y_train == k)[0]\n np.random.shuffle(idx_k)\n proportions = np.random.dirichlet(np.repeat(alpha, n_nets))\n ## Balance\n proportions = np.array([p * (len(idx_j) < N / n_nets) for p, idx_j in zip(proportions, idx_batch)])\n proportions = proportions / proportions.sum()\n proportions = (np.cumsum(proportions) * len(idx_k)).astype(int)[:-1]\n idx_batch = [idx_j + idx.tolist() for idx_j, idx in zip(idx_batch, np.split(idx_k, proportions))]\n min_size = min([len(idx_j) for idx_j in idx_batch])\n\n for j in range(n_nets):\n np.random.shuffle(idx_batch[j])\n net_dataidx_map[j] = idx_batch[j]\n\n elif partition == \"hetero-fix\":\n dataidx_map_file_path = './data_preprocessing/non-iid-distribution/CIFAR100/net_dataidx_map.txt'\n net_dataidx_map = read_net_dataidx_map(dataidx_map_file_path)\n\n if partition == \"hetero-fix\":\n distribution_file_path = './data_preprocessing/non-iid-distribution/CIFAR100/distribution.txt'\n traindata_cls_counts = read_data_distribution(distribution_file_path)\n else:\n traindata_cls_counts = record_net_data_stats(y_train, net_dataidx_map)\n\n return X_train, y_train, X_test, y_test, net_dataidx_map, traindata_cls_counts\n\n\n# for centralized training\ndef get_dataloader(dataset, datadir, train_bs, test_bs, dataidxs=None):\n return get_dataloader_CIFAR100(datadir, train_bs, test_bs, dataidxs)\n\n\n# for local devices\ndef get_dataloader_test(dataset, datadir, train_bs, test_bs, dataidxs_train, dataidxs_test):\n return get_dataloader_test_CIFAR100(datadir, train_bs, test_bs, dataidxs_train, dataidxs_test)\n\n\ndef get_dataloader_CIFAR100(datadir, train_bs, test_bs, dataidxs=None):\n dl_obj = CIFAR100_truncated\n\n transform_train, transform_test = _data_transforms_cifar100()\n\n train_ds = dl_obj(datadir, dataidxs=dataidxs, train=True, transform=transform_train, download=True)\n test_ds = dl_obj(datadir, train=False, transform=transform_test, download=True)\n\n train_dl = data.DataLoader(dataset=train_ds, batch_size=train_bs, shuffle=True, drop_last=True)\n test_dl = data.DataLoader(dataset=test_ds, batch_size=test_bs, shuffle=False, drop_last=True)\n\n return train_dl, test_dl\n\n\ndef get_dataloader_test_CIFAR100(datadir, train_bs, test_bs, dataidxs_train=None, dataidxs_test=None):\n dl_obj = CIFAR100_truncated\n\n transform_train, transform_test = _data_transforms_cifar100()\n\n train_ds = dl_obj(datadir, dataidxs=dataidxs_train, train=True, transform=transform_train, download=True)\n test_ds = dl_obj(datadir, dataidxs=dataidxs_test, train=False, transform=transform_test, download=True)\n\n train_dl = data.DataLoader(dataset=train_ds, batch_size=train_bs, shuffle=True, drop_last=True)\n test_dl = data.DataLoader(dataset=test_ds, batch_size=test_bs, shuffle=False, drop_last=True)\n\n return train_dl, test_dl\n\n\ndef load_partition_data_distributed_cifar100(process_id, dataset, data_dir, partition_method, partition_alpha,\n client_number, batch_size):\n X_train, y_train, X_test, y_test, net_dataidx_map, traindata_cls_counts = partition_data(dataset,\n data_dir,\n partition_method,\n client_number,\n partition_alpha)\n class_num = len(np.unique(y_train))\n logging.info(\"traindata_cls_counts = \" + str(traindata_cls_counts))\n train_data_num = sum([len(net_dataidx_map[r]) for r in range(client_number)])\n\n # get global test data\n if process_id == 0:\n train_data_global, test_data_global = get_dataloader(dataset, data_dir, batch_size, batch_size)\n logging.info(\"train_dl_global number = \" + str(len(train_data_global)))\n logging.info(\"test_dl_global number = \" + str(len(train_data_global)))\n train_data_local = None\n test_data_local = None\n local_data_num = 0\n else:\n # get local dataset\n dataidxs = net_dataidx_map[process_id - 1]\n local_data_num = len(dataidxs)\n logging.info(\"rank = %d, local_sample_number = %d\" % (process_id, local_data_num))\n # training batch size = 64; algorithms batch size = 32\n train_data_local, test_data_local = get_dataloader(dataset, data_dir, batch_size, batch_size,\n dataidxs)\n logging.info(\"process_id = %d, batch_num_train_local = %d, batch_num_test_local = %d\" % (\n process_id, len(train_data_local), len(test_data_local)))\n train_data_global = None\n test_data_global = None\n\n return train_data_num, train_data_global, test_data_global, local_data_num, train_data_local, test_data_local, class_num\n\n\ndef load_partition_data_cifar100(dataset, data_dir, partition_method, partition_alpha, client_number, batch_size):\n X_train, y_train, X_test, y_test, net_dataidx_map, traindata_cls_counts = partition_data(dataset,\n data_dir,\n partition_method,\n client_number,\n partition_alpha)\n class_num = len(np.unique(y_train))\n logging.info(\"traindata_cls_counts = \" + str(traindata_cls_counts))\n train_data_num = sum([len(net_dataidx_map[r]) for r in range(client_number)])\n\n train_data_global, test_data_global = get_dataloader(dataset, data_dir, batch_size, batch_size)\n logging.info(\"train_dl_global number = \" + str(len(train_data_global)))\n logging.info(\"test_dl_global number = \" + str(len(train_data_global)))\n test_data_num = len(test_data_global)\n\n # get local dataset\n data_local_num_dict = dict()\n train_data_local_dict = dict()\n test_data_local_dict = dict()\n\n for client_idx in range(client_number):\n dataidxs = net_dataidx_map[client_idx]\n local_data_num = len(dataidxs)\n data_local_num_dict[client_idx] = local_data_num\n logging.info(\"client_idx = %d, local_sample_number = %d\" % (client_idx, local_data_num))\n\n # training batch size = 64; algorithms batch size = 32\n train_data_local, test_data_local = get_dataloader(dataset, data_dir, batch_size, batch_size,\n dataidxs)\n logging.info(\"client_idx = %d, batch_num_train_local = %d, batch_num_test_local = %d\" % (\n client_idx, len(train_data_local), len(test_data_local)))\n train_data_local_dict[client_idx] = train_data_local\n test_data_local_dict[client_idx] = test_data_local\n return train_data_num, test_data_num, train_data_global, test_data_global, \\\n data_local_num_dict, train_data_local_dict, test_data_local_dict, class_num\n"
] | [
[
"numpy.split",
"numpy.unique",
"numpy.clip",
"torch.utils.data.DataLoader",
"torch.from_numpy",
"numpy.random.shuffle",
"numpy.ones",
"numpy.cumsum",
"torch.utils.data.readlines",
"numpy.random.permutation",
"numpy.repeat",
"numpy.array_split",
"numpy.where",
"numpy.random.randint"
]
] |
dukeNashor/ChessMaster | [
"0b1f7b75a76e5c9129e73e0722af9e5b3b76f033"
] | [
"Python-Easy-Chess-GUI/python_easy_chess_gui.py"
] | [
"#!/usr/bin/env python3\n\"\"\" \npython_easy_chess_gui.py\n\nRequirements:\n Python 3.7.3 and up\n\nPySimpleGUI Square Mapping\nboard = [\n 56, 57, ... 63\n ...\n 8, 9, ...\n 0, 1, 2, ...\n]\n\nrow = [\n 0, 0, ...\n 1, 1, ...\n ...\n 7, 7 ...\n]\n\ncol = [\n 0, 1, 2, ... 7\n 0, 1, 2, ...\n ...\n 0, 1, 2, ... 7\n]\n\n\nPython-Chess Square Mapping\nboard is the same as in PySimpleGUI\nrow is reversed\ncol is the same as in PySimpleGUI\n\n\"\"\"\n\nimport PySimpleGUI as sg\nimport os\nimport sys\nimport subprocess\nimport threading\nfrom pathlib import Path, PurePath # Python 3.4 and up\nimport queue\nimport copy\nimport time\nfrom datetime import datetime\nimport json\nimport pyperclip\nimport chess\nimport chess.pgn\nimport chess.engine\nimport chess.polyglot\nimport logging\n\n\nlog_format = '%(asctime)s :: %(funcName)s :: line: %(lineno)d :: %(' \\\n 'levelname)s :: %(message)s'\nlogging.basicConfig(filename='pecg_log.txt', filemode='w', level=logging.DEBUG,\n format=log_format)\n\n\nAPP_NAME = 'Python Easy Chess GUI'\nAPP_VERSION = 'v1.11'\nBOX_TITLE = '{} {}'.format(APP_NAME, APP_VERSION)\n\n\nplatform = sys.platform\n \n\nico_path = {'win32': {'pecg': 'Icon/pecg.ico', 'enemy': 'Icon/enemy.ico',\n 'adviser': 'Icon/adviser.ico'}, \n 'linux': {'pecg': 'Icon/pecg.png', 'enemy': 'Icon/enemy.png',\n 'adviser': 'Icon/adviser.png'},\n 'darwin': {'pecg': 'Icon/pecg.png', 'enemy': 'Icon/enemy.png',\n 'adviser': 'Icon/adviser.png'}}\n\n\nMIN_DEPTH = 1\nMAX_DEPTH = 1000\nMANAGED_UCI_OPTIONS = ['ponder', 'uci_chess960', 'multipv', 'uci_analysemode',\n 'ownbook']\nGUI_THEME = ['Green', 'GreenTan', 'LightGreen', 'BluePurple', 'Purple',\n 'BlueMono', 'GreenMono', 'BrownBlue', 'BrightColors',\n 'NeutralBlue', 'Kayak', 'SandyBeach', 'TealMono', 'Topanga',\n 'Dark', 'Black', 'DarkAmber']\n\n# import our classifiers\nsys.path.insert(0,'../')\n\ntry:\n import Classifiers\n import BoardHelper\n from PIL import ImageGrab, ImageOps\n import numpy as np\n\n # this is to fix high-resolution monitor problem so that the \n # screen capture function could work.\n # ref:https://github.com/PySimpleGUI/PySimpleGUI/issues/2962\n import ctypes\n ctypes.windll.user32.SetProcessDPIAware()\n\nexcept:\n print(\"import failed. Check your path.\")\n\nsaved_model_path = \"../saved_model/\"\nabc_model_file = saved_model_path + \"abc_dump.pkl\"\nsvc_model_file = saved_model_path + \"svc_dump.pkl\"\n\n# construct the CNN classifier, and read weights.n\ncnn = Classifiers.CNNClassifier()\ncnn.LoadMostRecentModelFromDirectory(\"../CNN_training_checkpoint/\")\n\nsvc = Classifiers.SVCClassifier()\nsvc.LoadModel(svc_model_file)\n\nabc = Classifiers.ABClassifier()\nabc.LoadModel(abc_model_file)\n\ndef get_grid(window, elem):\n widget = elem.Widget\n box = (widget.winfo_rootx(), widget.winfo_rooty(), widget.winfo_rootx() + widget.winfo_width(), widget.winfo_rooty() + widget.winfo_height())\n grab = np.asarray(ImageGrab.grab(bbox=box))\n return grab\n\n\ndef get_whole_board(window, gray = False):\n elem = window.FindElement(key=(0, 0))\n widget = elem.Widget\n box = (widget.winfo_rootx(), widget.winfo_rooty(), widget.winfo_rootx() + widget.winfo_width() * 8, widget.winfo_rooty() + widget.winfo_height() * 8)\n pil_img = ImageGrab.grab(bbox=box)\n if gray:\n pil_img = ImageOps.grayscale(pil_img)\n \n board_image = np.asarray(pil_img)\n # ImageGrab.grab(bbox=box).save(\"board.png\")\n return board_image\n\n\ndef save_grid_as_file(window, elem, file_name):\n os.makedirs(os.path.dirname(file_name), exist_ok = True)\n grid = get_grid(window, elem)\n PIL.Image.fromarray(grid).save(file_name)\n\ndef ClassifyBoard(window, classifier, window_element_label):\n \n # use classifier to process the image\n if isinstance(classifier, Classifiers.SVCClassifier) or isinstance(classifier, Classifiers.ABClassifier):\n board_image = get_whole_board(window, True)\n else:\n board_image = get_whole_board(window, False)\n\n predicted = classifier.Predict(board_image)\n labels = np.array(predicted).reshape(8, 8)\n\n # update user interface\n #print(labels)\n textbox = window.FindElement(window_element_label)\n textbox.Update(type(classifier).__name__ + \"\\n\" + np.array2string(labels))\n\nPIECE_THEME = [ str(i + 1) for i in range(32) ] + [ \"default\" ]\n\nIMAGE_PATH = 'Images/60_scaled' # path to the chess pieces\nPIECE_IMAGE_PATH = \"../chess-generator/ChessGenerator/pieces/\"\n\nBLANK = 0 # piece names\nPAWNB = 1\nKNIGHTB = 2\nBISHOPB = 3\nROOKB = 4\nKINGB = 5\nQUEENB = 6\nPAWNW = 7\nKNIGHTW = 8\nBISHOPW = 9\nROOKW = 10\nKINGW = 11\nQUEENW = 12\n\n\n# Absolute rank based on real chess board, white at bottom, black at the top.\n# This is also the rank mapping used by python-chess modules.\nRANK_8 = 7\nRANK_7 = 6\nRANK_6 = 5\nRANK_5 = 4\nRANK_4 = 3\nRANK_3 = 2\nRANK_2 = 1\nRANK_1 = 0\n\n\ninitial_board = [[ROOKB, KNIGHTB, BISHOPB, QUEENB, KINGB, BISHOPB, KNIGHTB, ROOKB],\n [PAWNB, ] * 8,\n [BLANK, ] * 8,\n [BLANK, ] * 8,\n [BLANK, ] * 8,\n [BLANK, ] * 8,\n [PAWNW, ] * 8,\n [ROOKW, KNIGHTW, BISHOPW, QUEENW, KINGW, BISHOPW, KNIGHTW, ROOKW]]\n\n\nwhite_init_promote_board = [[QUEENW, ROOKW, BISHOPW, KNIGHTW]]\n\nblack_init_promote_board = [[QUEENB, ROOKB, BISHOPB, KNIGHTB]]\n\n\nHELP_MSG = \"\"\"(A) To play a game\nYou should be in Play mode.\n1. Mode->Play\n2. Make move on the board\n\n(B) To play as black\nYou should be in Neutral mode\n1. Board->Flip\n2. Mode->Play\n3. Engine->Go\nIf you are already in Play mode, go back to \nNeutral mode via Mode->Neutral\n\n(C) To flip board\nYou should be in Neutral mode\n1. Board->Flip\n \n(D) To paste FEN\nYou should be in Play mode\n1. Mode->Play\n2. FEN->Paste\n\n(E) To show engine search info after the move \n1. Right-click on the Opponent Search Info and press Show\n\n(F) To Show book 1 and 2\n1. Right-click on Book 1 or 2 press Show\n\"\"\"\n\n\n# Images/60\nblank = os.path.join(IMAGE_PATH, 'blank.png')\nbishopB = os.path.join(IMAGE_PATH, 'bB.png')\nbishopW = os.path.join(IMAGE_PATH, 'wB.png')\npawnB = os.path.join(IMAGE_PATH, 'bP.png')\npawnW = os.path.join(IMAGE_PATH, 'wP.png')\nknightB = os.path.join(IMAGE_PATH, 'bN.png')\nknightW = os.path.join(IMAGE_PATH, 'wN.png')\nrookB = os.path.join(IMAGE_PATH, 'bR.png')\nrookW = os.path.join(IMAGE_PATH, 'wR.png')\nqueenB = os.path.join(IMAGE_PATH, 'bQ.png')\nqueenW = os.path.join(IMAGE_PATH, 'wQ.png')\nkingB = os.path.join(IMAGE_PATH, 'bK.png')\nkingW = os.path.join(IMAGE_PATH, 'wK.png')\n\n\n#images = {BISHOPB: bishopB, BISHOPW: bishopW, PAWNB: pawnB, PAWNW: pawnW,\n# KNIGHTB: knightB, KNIGHTW: knightW,\n# ROOKB: rookB, ROOKW: rookW, KINGB: kingB, KINGW: kingW,\n# QUEENB: queenB, QUEENW: queenW, BLANK: blank}\n\n# default theme of EasyChessGui\ntheme_default = {BISHOPB: bishopB, BISHOPW: bishopW, PAWNB: pawnB, PAWNW: pawnW,\n KNIGHTB: knightB, KNIGHTW: knightW,\n ROOKB: rookB, ROOKW: rookW, KINGB: kingB, KINGW: kingW,\n QUEENB: queenB, QUEENW: queenW, BLANK: blank}\n\n# themes of our dataset\ndataset_themes = {}\n\nfor i in range(32):\n display_name = str(i+1)\n dataset_themes.setdefault(display_name, {})\n \n theme_dir = PIECE_IMAGE_PATH + \"/\" + str(i+1) + \"/\"\n\n dataset_themes[display_name] = { \\\n BLANK : os.path.join(blank), # use the blank from default\n BISHOPB : os.path.join(theme_dir, 'b_b.png'),\n BISHOPW : os.path.join(theme_dir, 'b_w.png'),\n PAWNB : os.path.join(theme_dir, 'p_b.png'),\n PAWNW : os.path.join(theme_dir, 'p_w.png'),\n KNIGHTB : os.path.join(theme_dir, 'n_b.png'),\n KNIGHTW : os.path.join(theme_dir, 'n_w.png'),\n ROOKB : os.path.join(theme_dir, 'r_b.png'),\n ROOKW : os.path.join(theme_dir, 'r_w.png'),\n QUEENB : os.path.join(theme_dir, 'q_b.png'),\n QUEENW : os.path.join(theme_dir, 'q_w.png'),\n KINGB : os.path.join(theme_dir, 'k_b.png'),\n KINGW : os.path.join(theme_dir, 'k_w.png')\n }\n\ndataset_themes[\"default\"] = theme_default\n\n# images = dataset_themes[\"default\"]\n\n\n# Promote piece from psg (pysimplegui) to pyc (python-chess)\npromote_psg_to_pyc = {KNIGHTB: chess.KNIGHT, BISHOPB: chess.BISHOP,\n ROOKB: chess.ROOK, QUEENB: chess.QUEEN,\n KNIGHTW: chess.KNIGHT, BISHOPW: chess.BISHOP,\n ROOKW: chess.ROOK, QUEENW: chess.QUEEN,}\n\n\nINIT_PGN_TAG = {\n 'Event': 'Human vs computer',\n 'White': 'Human',\n 'Black': 'Computer',\n}\n\n\n# (1) Mode: Neutral\nmenu_def_neutral = [\n ['&Mode', ['Play']],\n ['Boar&d',\n [\n 'Flip',\n 'Color', ['Brown::board_color_k',\n 'Blue::board_color_k',\n 'Green::board_color_k',\n 'Gray::board_color_k'],\n 'Theme', GUI_THEME,\n ]\n ],\n [\"Settings for &Assignment COMP5318\",\n [\n 'Piece Theme', PIECE_THEME\n ]\n ],\n ['&Engine', ['Set Engine Adviser', 'Set Engine Opponent', 'Set Depth',\n 'Manage', ['Install', 'Edit', 'Delete']]],\n ['&Time', ['User::tc_k', 'Engine::tc_k']],\n ['&Book', ['Set Book::book_set_k']],\n ['&User', ['Set Name::user_name_k']],\n ['Tools', ['PGN', ['Delete Player::delete_player_k']]],\n ['&Settings', ['Game::settings_game_k']],\n ['&Help', ['About']],\n]\n\n# (2) Mode: Play, info: hide\nmenu_def_play = [\n ['&Mode', ['Neutral']],\n [\"Settings for &Assignment COMP5318\",\n [\n 'Piece Theme', PIECE_THEME\n ]\n ],\n ['&Game', ['&New::new_game_k',\n 'Save to My Games::save_game_k',\n 'Save to White Repertoire',\n 'Save to Black Repertoire',\n 'Resign::resign_game_k',\n 'User Wins::user_wins_k',\n 'User Draws::user_draws_k']],\n ['FEN', ['Paste']],\n ['&Engine', ['Go', 'Move Now']],\n ['&Help', ['About']],\n]\n\n\nclass Timer:\n def __init__(self, tc_type='fischer', base=300000, inc=10000,\n period_moves=40):\n \"\"\"\n :param tc_type: time control type ['fischer, delay, classical']\n :param base: base time in ms\n :param inc: increment time in ms can be negative and 0\n :param period_moves: number of moves in a period\n \"\"\"\n self.tc_type = tc_type # ['fischer', 'delay', 'timepermove']\n self.base = base\n self.inc = inc\n self.period_moves = period_moves\n self.elapse = 0\n self.init_base_time = self.base\n\n def update_base(self):\n \"\"\"\n Update base time after every move\n\n :return:\n \"\"\"\n if self.tc_type == 'delay':\n self.base += min(0, self.inc - self.elapse)\n elif self.tc_type == 'fischer':\n self.base += self.inc - self.elapse\n elif self.tc_type == 'timepermove':\n self.base = self.init_base_time\n else:\n self.base -= self.elapse\n\n self.base = max(0, self.base)\n self.elapse = 0\n\n\nclass GuiBook:\n def __init__(self, book_file, board, is_random=True):\n \"\"\"\n Handle gui polyglot book for engine opponent.\n\n :param book_file: polgylot book filename\n :param board: given board position\n :param is_random: randomly select move from book\n \"\"\"\n self.book_file = book_file\n self.board = board\n self.is_random = is_random\n self.__book_move = None\n\n def get_book_move(self):\n \"\"\" Returns book move either random or best move \"\"\"\n reader = chess.polyglot.open_reader(self.book_file)\n try:\n if self.is_random:\n entry = reader.weighted_choice(self.board)\n else:\n entry = reader.find(self.board)\n self.__book_move = entry.move\n except IndexError:\n logging.warning('No more book move.')\n except Exception:\n logging.exception('Failed to get book move.')\n finally:\n reader.close()\n\n return self.__book_move\n\n def get_all_moves(self):\n \"\"\"\n Read polyglot book and get all legal moves from a given positions.\n\n :return: move string\n \"\"\"\n is_found = False\n total_score = 0\n book_data = {}\n cnt = 0\n\n if os.path.isfile(self.book_file):\n moves = '{:4s} {:<5s} {}\\n'.format('move', 'score', 'weight')\n with chess.polyglot.open_reader(self.book_file) as reader:\n for entry in reader.find_all(self.board):\n is_found = True\n san_move = self.board.san(entry.move)\n score = entry.weight\n total_score += score\n bd = {cnt: {'move': san_move, 'score': score}}\n book_data.update(bd)\n cnt += 1\n else:\n moves = '{:4s} {:<}\\n'.format('move', 'score')\n\n # Get weight for each move\n if is_found:\n for _, v in book_data.items():\n move = v['move']\n score = v['score']\n weight = score/total_score\n moves += '{:4s} {:<5d} {:<2.1f}%\\n'.format(move, score,\n 100*weight)\n\n return moves, is_found\n\n\nclass RunEngine(threading.Thread):\n pv_length = 9\n move_delay_sec = 3.0\n\n def __init__(self, eng_queue, engine_config_file, engine_path_and_file,\n engine_id_name, max_depth=MAX_DEPTH,\n base_ms=300000, inc_ms=1000, tc_type='fischer',\n period_moves=0, is_stream_search_info=True):\n \"\"\"\n Run engine as opponent or as adviser.\n\n :param eng_queue:\n :param engine_config_file: pecg_engines.json\n :param engine_path_and_file:\n :param engine_id_name:\n :param max_depth:\n \"\"\"\n threading.Thread.__init__(self)\n self._kill = threading.Event()\n self.engine_config_file = engine_config_file\n self.engine_path_and_file = engine_path_and_file\n self.engine_id_name = engine_id_name\n self.own_book = False\n self.bm = None\n self.pv = None\n self.score = None\n self.depth = None\n self.time = None\n self.nps = 0\n self.max_depth = max_depth\n self.eng_queue = eng_queue\n self.engine = None\n self.board = None\n self.analysis = is_stream_search_info\n self.is_nomove_number_in_variation = True\n self.base_ms = base_ms\n self.inc_ms = inc_ms\n self.tc_type = tc_type\n self.period_moves = period_moves\n self.is_ownbook = False\n self.is_move_delay = True\n\n def stop(self):\n \"\"\" Interrupt engine search \"\"\"\n self._kill.set()\n\n def get_board(self, board):\n \"\"\" Get the current board position \"\"\"\n self.board = board\n\n def configure_engine(self):\n \"\"\" Read the engine config file pecg_engines.json and set the engine to\n use the user_value of the value key. Our option name has 2 values,\n default_value and user_value.\n \n Example for hash option\n 'name': Hash\n 'default': default_value\n 'value': user_value\n \n If default_value and user_value are not the same, we will set the\n engine to use the user_value by the command,\n setoption name Hash value user_value\n \n However if default_value and user_value are the same, we will not send\n commands to set the option value because the value is default already.\n \"\"\"\n with open(self.engine_config_file, 'r') as json_file:\n data = json.load(json_file)\n for p in data:\n if p['name'] == self.engine_id_name:\n for n in p['options']:\n\n if n['name'].lower() == 'ownbook':\n self.is_ownbook = True\n\n # Ignore button type for a moment.\n if n['type'] == 'button':\n continue\n\n if n['type'] == 'spin':\n user_value = int(n['value'])\n default_value = int(n['default'])\n else:\n user_value = n['value']\n default_value = n['default']\n\n if user_value != default_value:\n try:\n self.engine.configure({n['name']: user_value})\n logging.info('Set {} to {}'.format(\n n['name'], user_value))\n except Exception:\n logging.exception('{Failed to configure '\n 'engine}')\n\n def run(self):\n \"\"\"\n Run engine to get search info and bestmove. If there is error we\n still send bestmove None.\n\n :return: bestmove thru que\n \"\"\"\n folder = Path(self.engine_path_and_file)\n folder = folder.parents[0]\n\n try:\n if platform == 'win32':\n self.engine = chess.engine.SimpleEngine.popen_uci(\n self.engine_path_and_file)\n else:\n self.engine = chess.engine.SimpleEngine.popen_uci(\n self.engine_path_and_file, cwd=folder)\n except chess.engine.EngineTerminatedError:\n logging.warning('Failed to start {}.'.format(self.engine_path_and_file))\n self.eng_queue.put('bestmove {}'.format(self.bm))\n return\n except Exception:\n logging.exception('Failed to start {}.'.format(\n self.engine_path_and_file))\n self.eng_queue.put('bestmove {}'.format(self.bm))\n return\n\n # Set engine option values\n try:\n self.configure_engine()\n except Exception:\n logging.exception('Failed to configure engine.')\n\n # Set search limits\n if self.tc_type == 'delay':\n limit = chess.engine.Limit(\n depth=self.max_depth if self.max_depth != MAX_DEPTH else None,\n white_clock=self.base_ms/1000,\n black_clock=self.base_ms/1000,\n white_inc=self.inc_ms/1000,\n black_inc=self.inc_ms/1000)\n elif self.tc_type == 'timepermove':\n limit = chess.engine.Limit(time=self.base_ms/1000,\n depth=self.max_depth if\n self.max_depth != MAX_DEPTH else None)\n else:\n limit = chess.engine.Limit(\n depth=self.max_depth if self.max_depth != MAX_DEPTH else None,\n white_clock=self.base_ms/1000,\n black_clock=self.base_ms/1000,\n white_inc=self.inc_ms/1000,\n black_inc=self.inc_ms/1000)\n start_time = time.perf_counter()\n if self.analysis:\n is_time_check = False\n\n with self.engine.analysis(self.board, limit) as analysis:\n for info in analysis:\n\n if self._kill.wait(0.1):\n break\n\n try:\n if 'depth' in info:\n self.depth = int(info['depth'])\n\n if 'score' in info:\n self.score = int(info['score'].relative.score(\n mate_score=32000))/100\n\n self.time = info['time'] if 'time' in info \\\n else time.perf_counter() - start_time\n\n if 'pv' in info and not ('upperbound' in info or\n 'lowerbound' in info):\n self.pv = info['pv'][0:self.pv_length]\n\n if self.is_nomove_number_in_variation:\n spv = self.short_variation_san()\n self.pv = spv\n else:\n self.pv = self.board.variation_san(self.pv)\n\n self.eng_queue.put('{} pv'.format(self.pv))\n self.bm = info['pv'][0]\n\n # score, depth, time, pv\n if self.score is not None and \\\n self.pv is not None and self.depth is not None:\n info_to_send = '{:+5.2f} | {} | {:0.1f}s | {} info_all'.format(\n self.score, self.depth, self.time, self.pv)\n self.eng_queue.put('{}'.format(info_to_send))\n\n # Send stop if movetime is exceeded\n if not is_time_check and self.tc_type != 'fischer' \\\n and self.tc_type != 'delay' and \\\n time.perf_counter() - start_time >= \\\n self.base_ms/1000:\n logging.info('Max time limit is reached.')\n is_time_check = True\n break\n\n # Send stop if max depth is exceeded\n if 'depth' in info:\n if int(info['depth']) >= self.max_depth \\\n and self.max_depth != MAX_DEPTH:\n logging.info('Max depth limit is reached.')\n break\n except Exception:\n logging.exception('Failed to parse search info.')\n else:\n result = self.engine.play(self.board, limit,info=chess.engine.INFO_ALL)\n logging.info('result: {}'.format(result))\n try:\n self.depth = result.info['depth']\n except KeyError:\n self.depth = 1\n logging.exception('depth is missing.')\n try:\n self.score = int(result.info['score'].relative.score(\n mate_score=32000)) / 100\n except KeyError:\n self.score = 0\n logging.exception('score is missing.')\n try:\n self.time = result.info['time'] if 'time' in result.info \\\n else time.perf_counter() - start_time\n except KeyError:\n self.time = 0\n logging.exception('time is missing.')\n try:\n if 'pv' in result.info:\n self.pv = result.info['pv'][0:self.pv_length]\n\n if self.is_nomove_number_in_variation:\n spv = self.short_variation_san()\n self.pv = spv\n else:\n self.pv = self.board.variation_san(self.pv)\n except Exception:\n self.pv = None\n logging.exception('pv is missing.')\n\n if self.pv is not None:\n info_to_send = '{:+5.2f} | {} | {:0.1f}s | {} info_all'.format(\n self.score, self.depth, self.time, self.pv)\n self.eng_queue.put('{}'.format(info_to_send))\n self.bm = result.move\n\n # Apply engine move delay if movetime is small\n if self.is_move_delay:\n while True:\n if time.perf_counter() - start_time >= self.move_delay_sec:\n break\n logging.info('Delay sending of best move {}'.format(self.bm))\n time.sleep(1.0)\n\n # If bm is None, we will use engine.play()\n if self.bm is None:\n logging.info('bm is none, we will try engine,play().')\n try:\n result = self.engine.play(self.board, limit)\n self.bm = result.move\n except Exception:\n logging.exception('Failed to get engine bestmove.')\n self.eng_queue.put('bestmove {}' .format(self.bm))\n logging.info('bestmove {}'.format(self.bm))\n\n def quit_engine(self):\n \"\"\" Quit engine \"\"\"\n logging.info('quit engine')\n try:\n self.engine.quit()\n except AttributeError:\n logging.info('AttributeError, self.engine is already None')\n except Exception:\n logging.exception('Failed to quit engine.')\n\n def short_variation_san(self):\n \"\"\" Returns variation in san but without move numbers \"\"\"\n if self.pv is None:\n return None\n\n short_san_pv = []\n tmp_board = self.board.copy()\n for pc_move in self.pv:\n san_move = tmp_board.san(pc_move)\n short_san_pv.append(san_move)\n tmp_board.push(pc_move)\n\n return ' '.join(short_san_pv)\n\n\nclass EasyChessGui:\n queue = queue.Queue()\n is_user_white = True # White is at the bottom in board layout\n\n def __init__(self, theme, engine_config_file, user_config_file,\n gui_book_file, computer_book_file, human_book_file,\n is_use_gui_book, is_random_book, max_book_ply,\n max_depth=MAX_DEPTH):\n self.theme = theme\n self.user_config_file = user_config_file\n self.engine_config_file = engine_config_file\n self.gui_book_file = gui_book_file\n self.computer_book_file = computer_book_file\n self.human_book_file = human_book_file\n self.max_depth = max_depth\n self.is_use_gui_book = is_use_gui_book\n self.is_random_book = is_random_book\n self.max_book_ply = max_book_ply\n self.opp_path_and_file = None\n self.opp_file = None\n self.opp_id_name = None\n self.adviser_file = None\n self.adviser_path_and_file = None\n self.adviser_id_name = None\n self.adviser_hash = 128\n self.adviser_threads = 1\n self.adviser_movetime_sec = 10\n self.pecg_auto_save_game = 'pecg_auto_save_games.pgn'\n self.my_games = 'pecg_my_games.pgn'\n self.repertoire_file = {'white': 'pecg_white_repertoire.pgn', 'black': 'pecg_black_repertoire.pgn'}\n self.init_game()\n self.fen = None\n self.psg_board = None\n self.menu_elem = None\n self.engine_id_name_list = []\n self.engine_file_list = []\n self.username = 'Human'\n\n self.human_base_time_ms = 5 * 60 * 1000 # 5 minutes\n self.human_inc_time_ms = 10 * 1000 # 10 seconds\n self.human_period_moves = 0\n self.human_tc_type = 'fischer'\n\n self.engine_base_time_ms = 3 * 60 * 1000 # 5 minutes\n self.engine_inc_time_ms = 2 * 1000 # 10 seconds\n self.engine_period_moves = 0\n self.engine_tc_type = 'fischer'\n\n # Default board color is brown\n self.sq_light_color = '#F0D9B5'\n self.sq_dark_color = '#B58863'\n\n # Move highlight, for brown board\n self.move_sq_light_color = '#E8E18E'\n self.move_sq_dark_color = '#B8AF4E'\n\n self.gui_theme = 'Reddit'\n\n self.images = dataset_themes[\"default\"]\n\n self.is_save_time_left = False\n self.is_save_user_comment = True\n\n def update_game(self, mc, user_move, time_left, user_comment):\n \"\"\"\n Used for saving moves in the game.\n\n :param mc: move count\n :param user_move:\n :param time_left:\n :param user_comment: Can be a 'book' from the engine\n :return:\n \"\"\"\n # Save user comment\n if self.is_save_user_comment:\n # If comment is empty\n if not (user_comment and user_comment.strip()):\n if mc == 1:\n self.node = self.game.add_variation(user_move)\n else:\n self.node = self.node.add_variation(user_move)\n\n # Save clock (time left after a move) as move comment\n if self.is_save_time_left:\n rem_time = self.get_time_h_mm_ss(time_left, False)\n self.node.comment = '[%clk {}]'.format(rem_time)\n else:\n if mc == 1:\n self.node = self.game.add_variation(user_move)\n else:\n self.node = self.node.add_variation(user_move)\n\n # Save clock, add clock as comment after a move\n if self.is_save_time_left:\n rem_time = self.get_time_h_mm_ss(time_left, False)\n self.node.comment = '[%clk {}] {}'.format(rem_time,\n user_comment)\n else:\n self.node.comment = user_comment\n # Do not save user comment\n else:\n if mc == 1:\n self.node = self.game.add_variation(user_move)\n else:\n self.node = self.node.add_variation(user_move)\n\n # Save clock, add clock as comment after a move\n if self.is_save_time_left:\n rem_time = self.get_time_h_mm_ss(time_left, False)\n self.node.comment = '[%clk {}]'.format(rem_time)\n\n def create_new_window(self, window, flip=False):\n \"\"\" Close the window param just before turning the new window \"\"\"\n\n loc = window.CurrentLocation()\n window.Disable()\n if flip:\n self.is_user_white = not self.is_user_white\n\n layout = self.build_main_layout(self.is_user_white)\n\n w = sg.Window('{} {}'.format(APP_NAME, APP_VERSION),\n layout,\n default_button_element_size=(12, 1),\n auto_size_buttons=False,\n location=(loc[0], loc[1]),\n icon=ico_path[platform]['pecg'])\n\n # Initialize White and black boxes\n while True:\n button, value = w.Read(timeout=50)\n self.update_labels_and_game_tags(w, human=self.username)\n break\n\n window.Close()\n return w\n\n def delete_player(self, name, pgn, que):\n \"\"\"\n Delete games of player name in pgn.\n\n :param name:\n :param pgn:\n :param que:\n :return:\n \"\"\"\n logging.info(f'Enters delete_player()')\n\n pgn_path = Path(pgn)\n folder_path = pgn_path.parents[0]\n\n file = PurePath(pgn)\n pgn_file = file.name\n\n # Create backup of orig\n backup = pgn_file + '.backup'\n backup_path = Path(folder_path, backup)\n backup_path.touch()\n origfile_text = Path(pgn).read_text()\n backup_path.write_text(origfile_text)\n logging.info(f'backup copy {backup_path} is successfully created.')\n\n # Define output file\n output = 'out_' + pgn_file\n output_path = Path(folder_path, output)\n logging.info(f'output {output_path} is successfully created.')\n\n logging.info(f'Deleting player {name}.')\n gcnt = 0\n\n # read pgn and save each game if player name to be deleted is not in\n # the game, either white or black.\n with open(output_path, 'a') as f:\n with open(pgn_path) as h:\n game = chess.pgn.read_game(h)\n while game:\n gcnt += 1\n que.put('Delete, {}, processing game {}'.format(\n name, gcnt))\n wp = game.headers['White']\n bp = game.headers['Black']\n\n # If this game has no player with name to be deleted\n if wp != name and bp != name:\n f.write('{}\\n\\n'.format(game))\n game = chess.pgn.read_game(h)\n\n if output_path.exists():\n logging.info('Deleting player {} is successful.'.format(name))\n\n # Delete the orig file and rename the current output to orig file\n pgn_path.unlink()\n logging.info('Delete orig pgn file')\n output_path.rename(pgn_path)\n logging.info('Rename output to orig pgn file')\n\n que.put('Done')\n\n def get_players(self, pgn, q):\n logging.info(f'Enters get_players()')\n players = []\n games = 0\n with open(pgn) as h:\n while True:\n headers = chess.pgn.read_headers(h)\n if headers is None:\n break\n\n wp = headers['White']\n bp = headers['Black']\n\n players.append(wp)\n players.append(bp)\n games += 1\n\n p = list(set(players))\n ret = [p, games]\n\n q.put(ret)\n\n def get_engine_id_name(self, path_and_file, q):\n \"\"\" Returns id name of uci engine \"\"\"\n id_name = None\n folder = Path(path_and_file)\n folder = folder.parents[0]\n\n try:\n if platform == 'win32':\n engine = chess.engine.SimpleEngine.popen_uci(\n path_and_file, cwd=folder,\n creationflags=subprocess.CREATE_NO_WINDOW)\n else:\n engine = chess.engine.SimpleEngine.popen_uci(\n path_and_file, cwd=folder)\n id_name = engine.id['name']\n engine.quit()\n except Exception:\n logging.exception('Failed to get id name.')\n\n q.put(['Done', id_name])\n\n def get_engine_hash(self, eng_id_name):\n \"\"\" Returns hash value from engine config file \"\"\"\n eng_hash = None\n with open(self.engine_config_file, 'r') as json_file:\n data = json.load(json_file)\n for p in data:\n if p['name'] == eng_id_name:\n # There engines without options\n try:\n for n in p['options']:\n if n['name'].lower() == 'hash':\n return n['value']\n except KeyError:\n logging.info('This engine {} has no options.'.format(\n eng_id_name))\n break\n except Exception:\n logging.exception('Failed to get engine hash.')\n\n return eng_hash\n\n def get_engine_threads(self, eng_id_name):\n \"\"\"\n Returns number of threads of eng_id_name from pecg_engines.json.\n\n :param eng_id_name: the engine id name\n :return: number of threads\n \"\"\"\n eng_threads = None\n with open(self.engine_config_file, 'r') as json_file:\n data = json.load(json_file)\n for p in data:\n if p['name'] == eng_id_name:\n try:\n for n in p['options']:\n if n['name'].lower() == 'threads':\n return n['value']\n except KeyError:\n logging.info('This engine {} has no options.'.format(\n eng_id_name))\n break\n except Exception:\n logging.exception('Failed to get engine threads.')\n\n return eng_threads\n\n def get_engine_file(self, eng_id_name):\n \"\"\"\n Returns eng_id_name's filename and path from pecg_engines.json file.\n\n :param eng_id_name: engine id name\n :return: engine file and its path\n \"\"\"\n eng_file, eng_path_and_file = None, None\n with open(self.engine_config_file, 'r') as json_file:\n data = json.load(json_file)\n for p in data:\n if p['name'] == eng_id_name:\n eng_file = p['command']\n eng_path_and_file = Path(p['workingDirectory'],\n eng_file).as_posix()\n break\n\n return eng_file, eng_path_and_file\n\n def get_engine_id_name_list(self):\n \"\"\"\n Read engine config file.\n\n :return: list of engine id names\n \"\"\"\n eng_id_name_list = []\n with open(self.engine_config_file, 'r') as json_file:\n data = json.load(json_file)\n for p in data:\n if p['protocol'] == 'uci':\n eng_id_name_list.append(p['name'])\n\n eng_id_name_list = sorted(eng_id_name_list)\n\n return eng_id_name_list\n\n def update_user_config_file(self, username):\n \"\"\"\n Update user config file. If username does not exist, save it.\n :param username:\n :return:\n \"\"\"\n with open(self.user_config_file, 'r') as json_file:\n data = json.load(json_file)\n\n # Add the new entry if it does not exist\n is_name = False\n for i in range(len(data)):\n if data[i]['username'] == username:\n is_name = True\n break\n\n if not is_name:\n data.append({'username': username})\n\n # Save\n with open(self.user_config_file, 'w') as h:\n json.dump(data, h, indent=4)\n\n def check_user_config_file(self):\n \"\"\"\n Check presence of pecg_user.json file, if nothing we will create\n one with ['username': 'Human']\n\n :return:\n \"\"\"\n user_config_file_path = Path(self.user_config_file)\n if user_config_file_path.exists():\n with open(self.user_config_file, 'r') as json_file:\n data = json.load(json_file)\n for p in data:\n username = p['username']\n self.username = username\n else:\n # Write a new user config file\n data = []\n data.append({'username': 'Human'})\n\n # Save data to pecg_user.json\n with open(self.user_config_file, 'w') as h:\n json.dump(data, h, indent=4)\n\n def update_engine_to_config_file(self, eng_path_file, new_name, old_name, user_opt):\n \"\"\"\n Update engine config file based on params.\n\n :param eng_path_file: full path of engine\n :param new_name: new engine id name\n :param new_name: old engine id name\n :param user_opt: a list of dict, i.e d = ['a':a, 'b':b, ...]\n :return:\n \"\"\"\n folder = Path(eng_path_file)\n folder = folder.parents[0]\n folder = Path(folder)\n folder = folder.as_posix()\n\n file = PurePath(eng_path_file)\n file = file.name\n\n with open(self.engine_config_file, 'r') as json_file:\n data = json.load(json_file)\n\n for p in data:\n command = p['command']\n work_dir = p['workingDirectory']\n\n if file == command and folder == work_dir and old_name == p['name']:\n p['name'] = new_name\n for k, v in p.items():\n if k == 'options':\n for d in v:\n # d = {'name': 'Ponder', 'default': False,\n # 'value': False, 'type': 'check'}\n \n default_type = type(d['default']) \n opt_name = d['name']\n opt_value = d['value']\n for u in user_opt:\n # u = {'name': 'CDrill 1400'}\n for k1, v1 in u.items():\n if k1 == opt_name:\n v1 = int(v1) if default_type == int else v1\n if v1 != opt_value:\n d['value'] = v1\n break\n\n # Save data to pecg_engines.json\n with open(self.engine_config_file, 'w') as h:\n json.dump(data, h, indent=4)\n\n def is_name_exists(self, name):\n \"\"\"\n\n :param name: The name to check in pecg.engines.json file.\n :return:\n \"\"\"\n with open(self.engine_config_file, 'r') as json_file:\n data = json.load(json_file)\n\n for p in data:\n jname = p['name']\n if jname == name:\n return True\n\n return False\n\n def add_engine_to_config_file(self, engine_path_and_file, pname, que):\n \"\"\"\n Add pname config in pecg_engines.json file.\n\n :param engine_path_and_file:\n :param pname: id name of uci engine\n :return:\n \"\"\"\n folder = Path(engine_path_and_file).parents[0]\n file = PurePath(engine_path_and_file)\n file = file.name\n\n option = []\n\n with open(self.engine_config_file, 'r') as json_file:\n data = json.load(json_file)\n\n try:\n if platform == 'win32':\n engine = chess.engine.SimpleEngine.popen_uci(\n engine_path_and_file, cwd=folder,\n creationflags=subprocess.CREATE_NO_WINDOW)\n else:\n engine = chess.engine.SimpleEngine.popen_uci(\n engine_path_and_file, cwd=folder)\n except Exception:\n logging.exception('Failed to add {} in config file.'.format(pname))\n que.put('Failure')\n return\n\n try:\n opt_dict = engine.options.items()\n except Exception:\n logging.exception('Failed to get engine options.')\n que.put('Failure')\n return\n\n engine.quit()\n\n for opt in opt_dict:\n o = opt[1]\n\n if o.type == 'spin':\n # Adjust hash and threads values\n if o.name.lower() == 'threads':\n value = 1\n logging.info('config {} is set to {}'.format(o.name,\n value))\n elif o.name.lower() == 'hash':\n value = 32\n logging.info('config {} is set to {}'.format(o.name,\n value))\n else:\n value = o.default\n\n option.append({'name': o.name,\n 'default': o.default,\n 'value': value,\n 'type': o.type,\n 'min': o.min,\n 'max': o.max})\n elif o.type == 'combo':\n option.append({'name': o.name,\n 'default': o.default,\n 'value': o.default,\n 'type': o.type,\n 'choices':o.var})\n else:\n option.append({'name': o.name,\n 'default': o.default,\n 'value': o.default,\n 'type': o.type})\n\n # Save engine filename, working dir, name and options\n wdir = Path(folder).as_posix()\n protocol = 'uci' # Only uci engine is supported so far\n self.engine_id_name_list.append(pname)\n data.append({'command': file, 'workingDirectory': wdir,\n 'name': pname, 'protocol': protocol,\n 'options': option})\n\n # Save data to pecg_engines.json\n with open(self.engine_config_file, 'w') as h:\n json.dump(data, h, indent=4)\n\n que.put('Success')\n\n def check_engine_config_file(self):\n \"\"\"\n Check presence of engine config file pecg_engines.json. If not\n found we will create it, with entries from engines in Engines folder.\n\n :return:\n \"\"\"\n ec = Path(self.engine_config_file)\n if ec.exists():\n return\n\n data = []\n cwd = Path.cwd()\n\n self.engine_file_list = self.get_engines()\n\n for fn in self.engine_file_list:\n # Run engine and get id name and options\n option = []\n\n # cwd=current working dir, engines=folder, fn=exe file\n epath = Path(cwd, 'Engines', fn)\n engine_path_and_file = str(epath)\n folder = epath.parents[0]\n\n try:\n if platform == 'win32':\n engine = chess.engine.SimpleEngine.popen_uci(\n engine_path_and_file, cwd=folder,\n creationflags=subprocess.CREATE_NO_WINDOW)\n else:\n engine = chess.engine.SimpleEngine.popen_uci(\n engine_path_and_file, cwd=folder)\n except Exception:\n logging.exception(f'Failed to start engine {fn}!')\n continue\n\n engine_id_name = engine.id['name']\n opt_dict = engine.options.items()\n engine.quit()\n\n for opt in opt_dict:\n o = opt[1]\n\n if o.type == 'spin':\n # Adjust hash and threads values\n if o.name.lower() == 'threads':\n value = 1\n elif o.name.lower() == 'hash':\n value = 32\n else:\n value = o.default\n\n option.append({'name': o.name,\n 'default': o.default,\n 'value': value,\n 'type': o.type,\n 'min': o.min,\n 'max': o.max})\n elif o.type == 'combo':\n option.append({'name': o.name,\n 'default': o.default,\n 'value': o.default,\n 'type': o.type,\n 'choices':o.var})\n else:\n option.append({'name': o.name,\n 'default': o.default,\n 'value': o.default,\n 'type': o.type})\n\n # Save engine filename, working dir, name and options\n wdir = Path(cwd, 'Engines').as_posix()\n name = engine_id_name\n protocol = 'uci'\n self.engine_id_name_list.append(name)\n data.append({'command': fn, 'workingDirectory': wdir,\n 'name': name, 'protocol': protocol,\n 'options': option})\n\n # Save data to pecg_engines.json\n with open(self.engine_config_file, 'w') as h:\n json.dump(data, h, indent=4)\n\n def get_time_mm_ss_ms(self, time_ms):\n \"\"\" Returns time in min:sec:millisec given time in millisec \"\"\"\n s, ms = divmod(int(time_ms), 1000)\n m, s = divmod(s, 60)\n\n # return '{:02d}m:{:02d}s:{:03d}ms'.format(m, s, ms)\n return '{:02d}m:{:02d}s'.format(m, s)\n\n def get_time_h_mm_ss(self, time_ms, symbol=True):\n \"\"\"\n Returns time in h:mm:ss format.\n\n :param time_ms:\n :param symbol:\n :return:\n \"\"\"\n s, ms = divmod(int(time_ms), 1000)\n m, s = divmod(s, 60)\n h, m = divmod(m, 60)\n\n if not symbol:\n return '{:01d}:{:02d}:{:02d}'.format(h, m, s)\n return '{:01d}h:{:02d}m:{:02d}s'.format(h, m, s)\n\n def update_text_box(self, window, msg, is_hide):\n \"\"\" Update text elements \"\"\"\n best_move = None\n msg_str = str(msg)\n\n if not 'bestmove ' in msg_str:\n if 'info_all' in msg_str:\n info_all = ' '.join(msg_str.split()[0:-1]).strip()\n msg_line = '{}\\n'.format(info_all)\n window.FindElement('search_info_all_k').Update(\n '' if is_hide else msg_line)\n else:\n # Best move can be None because engine dies\n try:\n best_move = chess.Move.from_uci(msg.split()[1])\n except Exception:\n logging.exception('Engine sent {}.'.format(best_move))\n sg.Popup('Engine error, it sent a {} bestmove.\\n'.format(\n best_move) + 'Back to Neutral mode, it is better to '\n 'change engine {}.'.format(\n self.opp_id_name), icon=ico_path[platform]['pecg'],\n title=BOX_TITLE)\n\n return best_move\n\n def get_tag_date(self):\n \"\"\" Return date in pgn tag date format \"\"\"\n return datetime.today().strftime('%Y.%m.%d')\n\n def init_game(self):\n \"\"\" Initialize game with initial pgn tag values \"\"\"\n self.game = chess.pgn.Game()\n self.node = None\n self.game.headers['Event'] = INIT_PGN_TAG['Event']\n self.game.headers['Date'] = self.get_tag_date()\n self.game.headers['White'] = INIT_PGN_TAG['White']\n self.game.headers['Black'] = INIT_PGN_TAG['Black']\n\n def set_new_game(self):\n \"\"\" Initialize new game but save old pgn tag values\"\"\"\n old_event = self.game.headers['Event']\n old_white = self.game.headers['White']\n old_black = self.game.headers['Black']\n\n # Define a game object for saving game in pgn format\n self.game = chess.pgn.Game()\n\n self.game.headers['Event'] = old_event\n self.game.headers['Date'] = self.get_tag_date()\n self.game.headers['White'] = old_white\n self.game.headers['Black'] = old_black\n\n def clear_elements(self, window):\n \"\"\" Clear movelist, score, pv, time, depth and nps boxes \"\"\"\n window.FindElement('search_info_all_k').Update('')\n window.FindElement('_movelist_').Update(disabled=False)\n window.FindElement('_movelist_').Update('', disabled=True)\n window.FindElement('polyglot_book1_k').Update('')\n window.FindElement('polyglot_book2_k').Update('')\n window.FindElement('advise_info_k').Update('')\n #window.FindElement('comment_k').Update('')\n window.FindElement('cnn_prediction').Update('')\n window.FindElement('abc_prediction').Update('')\n window.FindElement('svc_prediction').Update('')\n window.Element('w_base_time_k').Update('')\n window.Element('b_base_time_k').Update('')\n window.Element('w_elapse_k').Update('')\n window.Element('b_elapse_k').Update('')\n\n def update_labels_and_game_tags(self, window, human='Human'):\n \"\"\" Update player names \"\"\"\n engine_id = self.opp_id_name\n if self.is_user_white:\n window.FindElement('_White_').Update(human)\n window.FindElement('_Black_').Update(engine_id)\n self.game.headers['White'] = human\n self.game.headers['Black'] = engine_id\n else:\n window.FindElement('_White_').Update(engine_id)\n window.FindElement('_Black_').Update(human)\n self.game.headers['White'] = engine_id\n self.game.headers['Black'] = human\n\n def get_fen(self):\n \"\"\" Get fen from clipboard \"\"\"\n self.fen = pyperclip.paste()\n\n # Remove empty char at the end of FEN\n if self.fen.endswith(' '):\n self.fen = self.fen[:-1]\n\n def fen_to_psg_board(self, window):\n \"\"\" Update psg_board based on FEN \"\"\"\n psgboard = []\n\n # Get piece locations only to build psg board\n pc_locations = self.fen.split()[0]\n\n board = chess.BaseBoard(pc_locations)\n old_r = None\n\n for s in chess.SQUARES:\n r = chess.square_rank(s)\n\n if old_r is None:\n piece_r = []\n elif old_r != r:\n psgboard.append(piece_r)\n piece_r = []\n elif s == 63:\n psgboard.append(piece_r)\n\n try:\n pc = board.piece_at(s^56)\n except Exception:\n pc = None\n logging.exception('Failed to get piece.')\n\n if pc is not None:\n pt = pc.piece_type\n c = pc.color\n if c:\n if pt == chess.PAWN:\n piece_r.append(PAWNW)\n elif pt == chess.KNIGHT:\n piece_r.append(KNIGHTW)\n elif pt == chess.BISHOP:\n piece_r.append(BISHOPW)\n elif pt == chess.ROOK:\n piece_r.append(ROOKW)\n elif pt == chess.QUEEN:\n piece_r.append(QUEENW)\n elif pt == chess.KING:\n piece_r.append(KINGW)\n else:\n if pt == chess.PAWN:\n piece_r.append(PAWNB)\n elif pt == chess.KNIGHT:\n piece_r.append(KNIGHTB)\n elif pt == chess.BISHOP:\n piece_r.append(BISHOPB)\n elif pt == chess.ROOK:\n piece_r.append(ROOKB)\n elif pt == chess.QUEEN:\n piece_r.append(QUEENB)\n elif pt == chess.KING:\n piece_r.append(KINGB)\n\n # Else if pc is None or square is empty\n else:\n piece_r.append(BLANK)\n\n old_r = r\n\n self.psg_board = psgboard\n self.redraw_board(window)\n\n def change_square_color(self, window, row, col):\n \"\"\" \n Change the color of a square based on square row and col.\n \"\"\"\n btn_sq = window.FindElement(key=(row, col))\n is_dark_square = True if (row + col) % 2 else False\n bd_sq_color = self.move_sq_dark_color if is_dark_square else \\\n self.move_sq_light_color\n btn_sq.Update(button_color=('white', bd_sq_color))\n\n def relative_row(self, s, stm):\n \"\"\"\n The board can be viewed, as white at the bottom and black at the\n top. If stm is white the row 0 is at the bottom. If stm is black\n row 0 is at the top.\n :param s: square\n :param stm: side to move\n :return: relative row\n \"\"\"\n return 7 - self.get_row(s) if stm else self.get_row(s)\n\n def get_row(self, s):\n \"\"\"\n This row is based on PySimpleGUI square mapping that is 0 at the\n top and 7 at the bottom.\n In contrast Python-chess square mapping is 0 at the bottom and 7\n at the top. chess.square_rank() is a method from Python-chess that\n returns row given square s.\n\n :param s: square\n :return: row\n \"\"\"\n return 7 - chess.square_rank(s)\n\n def get_col(self, s):\n \"\"\" Returns col given square s \"\"\"\n return chess.square_file(s)\n\n def redraw_board(self, window):\n \"\"\"\n Redraw board at start and afte a move.\n\n :param window:\n :return:\n \"\"\"\n for i in range(8):\n for j in range(8):\n color = self.sq_dark_color if (i + j) % 2 else \\\n self.sq_light_color\n piece_image = self.images[self.psg_board[i][j]]\n elem = window.FindElement(key=(i, j))\n elem.Update(button_color=('white', color),\n image_filename=piece_image, )\n #save_grid_as_file(window, elem, \"./grids/\" + str(i) + \"-\" + str(j) + \".png\")\n\n\n def render_square(self, image, key, location):\n \"\"\" Returns an RButton (Read Button) with image image \"\"\"\n if (location[0] + location[1]) % 2:\n color = self.sq_dark_color # Dark square\n else:\n color = self.sq_light_color\n return sg.RButton('', image_filename=image, size=(1, 1),\n border_width=0, button_color=('white', color),\n pad=(0, 0), key=key)\n\n def select_promotion_piece(self, stm):\n \"\"\"\n Allow user to select a piece type to promote to.\n\n :param stm: side to move\n :return: promoted piece, i.e QUEENW, QUEENB ...\n \"\"\"\n piece = None\n board_layout, row = [], []\n\n psg_promote_board = copy.deepcopy(white_init_promote_board) if stm \\\n else copy.deepcopy(black_init_promote_board)\n\n # Loop through board and create buttons with images \n for i in range(1):\n for j in range(4):\n piece_image = self.images[psg_promote_board[i][j]]\n row.append(self.render_square(piece_image, key=(i, j),\n location=(i, j)))\n\n board_layout.append(row)\n\n promo_window = sg.Window('{} {}'.format(APP_NAME, APP_VERSION),\n board_layout,\n default_button_element_size=(12, 1),\n auto_size_buttons=False,\n icon=ico_path[platform]['pecg'])\n\n while True:\n button, value = promo_window.Read(timeout=0)\n if button is None:\n break\n if type(button) is tuple:\n move_from = button\n fr_row, fr_col = move_from\n piece = psg_promote_board[fr_row][fr_col]\n logging.info('promote piece: {}'.format(piece))\n break\n\n promo_window.Close()\n\n return piece\n\n def update_rook(self, window, move):\n \"\"\"\n Update rook location for castle move.\n\n :param window:\n :param move: uci move format\n :return:\n \"\"\"\n if move == 'e1g1':\n fr = chess.H1\n to = chess.F1\n pc = ROOKW\n elif move == 'e1c1':\n fr = chess.A1\n to = chess.D1\n pc = ROOKW\n elif move == 'e8g8':\n fr = chess.H8\n to = chess.F8\n pc = ROOKB\n elif move == 'e8c8':\n fr = chess.A8\n to = chess.D8\n pc = ROOKB\n\n self.psg_board[self.get_row(fr)][self.get_col(fr)] = BLANK\n self.psg_board[self.get_row(to)][self.get_col(to)] = pc\n self.redraw_board(window)\n\n def update_ep(self, window, move, stm):\n \"\"\"\n Update board for e.p move.\n\n :param window:\n :param move: python-chess format\n :param stm: side to move\n :return:\n \"\"\"\n to = move.to_square\n if stm:\n capture_sq = to - 8\n else:\n capture_sq = to + 8\n\n self.psg_board[self.get_row(capture_sq)][self.get_col(capture_sq)] = BLANK\n self.redraw_board(window)\n\n def get_promo_piece(self, move, stm, human):\n \"\"\"\n Returns promotion piece.\n\n :param move: python-chess format\n :param stm: side to move\n :param human: if side to move is human this is True\n :return: promoted piece in python-chess and pythonsimplegui formats\n \"\"\"\n # If this move is from a user, we will show a window with piece images\n if human:\n psg_promo = self.select_promotion_piece(stm)\n\n # If user pressed x we set the promo to queen\n if psg_promo is None:\n logging.info('User did not select a promotion piece, '\n 'set this to queen.')\n psg_promo = QUEENW if stm else QUEENB\n\n pyc_promo = promote_psg_to_pyc[psg_promo]\n # Else if move is from computer\n else:\n pyc_promo = move.promotion # This is from python-chess\n if stm:\n if pyc_promo == chess.QUEEN:\n psg_promo = QUEENW\n elif pyc_promo == chess.ROOK:\n psg_promo = ROOKW\n elif pyc_promo == chess.BISHOP:\n psg_promo = BISHOPW\n elif pyc_promo == chess.KNIGHT:\n psg_promo = KNIGHTW\n else:\n if pyc_promo == chess.QUEEN:\n psg_promo = QUEENB\n elif pyc_promo == chess.ROOK:\n psg_promo = ROOKB\n elif pyc_promo == chess.BISHOP:\n psg_promo = BISHOPB\n elif pyc_promo == chess.KNIGHT:\n psg_promo = KNIGHTB\n\n return pyc_promo, psg_promo\n\n def set_depth_limit(self):\n \"\"\" Returns max depth based from user setting \"\"\"\n user_depth = sg.PopupGetText(\n 'Current depth is {}\\n\\nInput depth [{} to {}]'.format(\n self.max_depth, MIN_DEPTH, MAX_DEPTH), title=BOX_TITLE,\n icon=ico_path[platform]['pecg'])\n\n try:\n user_depth = int(user_depth)\n except Exception:\n user_depth = self.max_depth\n logging.exception('Failed to get user depth.')\n\n self.max_depth = min(MAX_DEPTH, max(MIN_DEPTH, user_depth))\n \n def define_timer(self, window, name='human'):\n \"\"\"\n Returns Timer object for either human or engine.\n \"\"\"\n if name == 'human':\n timer = Timer(self.human_tc_type, self.human_base_time_ms,\n self.human_inc_time_ms, self.human_period_moves) \n else:\n timer = Timer(self.engine_tc_type, self.engine_base_time_ms,\n self.engine_inc_time_ms, self.engine_period_moves)\n\n elapse_str = self.get_time_h_mm_ss(timer.base)\n is_white_base = self.is_user_white and name == 'human' or \\\n not self.is_user_white and name != 'human'\n window.Element('w_base_time_k' if is_white_base else 'b_base_time_k').Update(\n elapse_str)\n \n return timer \n\n def play_game(self, window, engine_id_name, board):\n \"\"\"\n User can play a game against and engine.\n\n :param window:\n :param engine_id_name:\n :param board: current board position\n :return:\n \"\"\"\n window.FindElement('_movelist_').Update(disabled=False)\n window.FindElement('_movelist_').Update('', disabled=True)\n\n is_human_stm = True if self.is_user_white else False\n\n move_state = 0\n move_from, move_to = None, None\n is_new_game, is_exit_game, is_exit_app = False, False, False\n\n # Do not play immediately when stm is computer\n is_engine_ready = True if is_human_stm else False\n\n # For saving game\n move_cnt = 0\n\n is_user_resigns = False\n is_user_wins = False\n is_user_draws = False\n is_search_stop_for_exit = False\n is_search_stop_for_new_game = False\n is_search_stop_for_neutral = False\n is_search_stop_for_resign = False\n is_search_stop_for_user_wins = False\n is_search_stop_for_user_draws = False\n is_hide_book1 = True\n is_hide_book2 = True\n is_hide_search_info = True\n\n # Init timer\n human_timer = self.define_timer(window)\n engine_timer = self.define_timer(window, 'engine')\n\n # Game loop\n while not board.is_game_over(claim_draw=True):\n moved_piece = None\n \n # Mode: Play, Hide book 1\n if is_hide_book1:\n window.Element('polyglot_book1_k').Update('')\n else:\n # Load 2 polyglot book files \n ref_book1 = GuiBook(self.computer_book_file, board,\n self.is_random_book)\n all_moves, is_found = ref_book1.get_all_moves()\n if is_found:\n window.Element('polyglot_book1_k').Update(all_moves)\n else:\n window.Element('polyglot_book1_k').Update('no book moves')\n\n # Mode: Play, Hide book 2\n if is_hide_book2:\n window.Element('polyglot_book2_k').Update('')\n else:\n ref_book2 = GuiBook(self.human_book_file, board,\n self.is_random_book)\n all_moves, is_found = ref_book2.get_all_moves()\n if is_found:\n window.Element('polyglot_book2_k').Update(all_moves)\n else:\n window.Element('polyglot_book2_k').Update('no book moves')\n\n # Mode: Play, Stm: computer (first move), Allow user to change settings.\n # User can start the engine by Engine->Go.\n if not is_engine_ready:\n window.FindElement('_gamestatus_').Update(\n 'Mode Play, press Engine->Go')\n while True:\n button, value = window.Read(timeout=100)\n\n # Mode: Play, Stm: computer (first move)\n if button == 'New::new_game_k':\n is_new_game = True\n break\n\n # Mode: Play, Stm: Computer first move\n if button == 'Neutral':\n is_exit_game = True\n break\n\n if button == 'About':\n sg.PopupScrolled(HELP_MSG, title=BOX_TITLE)\n continue\n\n if button == 'Paste':\n try:\n self.get_fen()\n self.set_new_game()\n board = chess.Board(self.fen)\n except Exception:\n logging.exception('Error in parsing FEN from clipboard.')\n continue\n\n self.fen_to_psg_board(window)\n\n # If user is black and side to move is black\n if not self.is_user_white and not board.turn:\n is_human_stm = True\n window.FindElement('_gamestatus_').Update(\n 'Mode Play')\n\n # Elif user is black and side to move is white\n elif not self.is_user_white and board.turn:\n is_human_stm = False\n window.FindElement('_gamestatus_').Update(\n 'Mode Play, press Engine->Go')\n\n # When computer is to move in the first move, don't\n # allow the engine to search immediately, wait for the\n # user to press Engine->Go menu.\n is_engine_ready = True if is_human_stm else False\n\n self.game.headers['FEN'] = self.fen\n break\n\n if button == 'Go':\n is_engine_ready = True\n break\n\n if button is None:\n logging.info('Quit app X is pressed.')\n is_exit_app = True\n break\n\n if is_exit_app or is_exit_game or is_new_game:\n break\n\n # If side to move is human\n if is_human_stm:\n move_state = 0\n\n while True:\n button, value = window.Read(timeout=100)\n\n # Update elapse box in m:s format\n elapse_str = self.get_time_mm_ss_ms(human_timer.elapse)\n k = 'w_elapse_k'\n if not self.is_user_white:\n k = 'b_elapse_k'\n window.Element(k).Update(elapse_str)\n human_timer.elapse += 100\n\n if not is_human_stm:\n break\n\n # Mode: Play, Stm: User, Run adviser engine\n if button == 'Start::right_adviser_k':\n self.adviser_threads = self.get_engine_threads(\n self.adviser_id_name)\n self.adviser_hash = self.get_engine_hash(\n self.adviser_id_name)\n adviser_base_ms = self.adviser_movetime_sec * 1000\n adviser_inc_ms = 0\n\n search = RunEngine(self.queue, self.engine_config_file,\n self.adviser_path_and_file, self.adviser_id_name,\n self.max_depth, adviser_base_ms, adviser_inc_ms,\n tc_type='timepermove',\n period_moves=0,\n is_stream_search_info=True)\n search.get_board(board)\n search.daemon = True\n search.start()\n\n while True:\n button, value = window.Read(timeout=10)\n\n if button == 'Stop::right_adviser_k':\n search.stop()\n\n # Exit app while adviser is thinking \n if button is None:\n search.stop() \n is_search_stop_for_exit = True\n try:\n msg = self.queue.get_nowait()\n if 'pv' in msg:\n # Reformat msg, remove the word pv at the end\n msg_line = ' '.join(msg.split()[0:-1])\n window.Element('advise_info_k').Update(msg_line)\n except Exception:\n continue\n\n if 'bestmove' in msg:\n # bestmove can be None so we do try/except\n try:\n # Shorten msg line to 3 ply moves\n msg_line = ' '.join(msg_line.split()[0:3])\n msg_line += ' - ' + self.adviser_id_name\n window.Element('advise_info_k').Update(msg_line)\n except Exception:\n logging.exception('Adviser engine error')\n sg.Popup('Adviser engine {} error.\\n'.format(\n self.adviser_id_name) + \\\n 'It is better to change this engine.\\n' +\n 'Change to Neutral mode first.',\n icon=ico_path[platform]['pecg'],\n title=BOX_TITLE)\n break\n\n search.join()\n search.quit_engine()\n break\n\n # Mode: Play, Stm: user\n if button == 'Show::right_search_info_k':\n is_hide_search_info = False\n break\n\n # Mode: Play, Stm: user\n if button == 'Hide::right_search_info_k':\n is_hide_search_info = True\n window.Element('search_info_all_k').Update('')\n break\n\n # Mode: Play, Stm: user\n if button == 'Show::right_book1_k':\n is_hide_book1 = False\n break\n\n # Mode: Play, Stm: user\n if button == 'Hide::right_book1_k':\n is_hide_book1 = True\n break\n\n # Mode: Play, Stm: user\n if button == 'Show::right_book2_k':\n is_hide_book2 = False\n break\n\n # Mode: Play, Stm: user\n if button == 'Hide::right_book2_k':\n is_hide_book2 = True\n break\n\n if button is None:\n logging.info('Quit app X is pressed.')\n is_exit_app = True\n break\n\n # redraw when changed theme\n if button in PIECE_THEME:\n print(\"selected piece theme \" + button)\n self.images = dataset_themes[button]\n self.redraw_board(window)\n continue\n\n if is_search_stop_for_exit:\n is_exit_app = True\n break\n\n # Mode: Play, Stm: User\n if button == 'New::new_game_k' or is_search_stop_for_new_game:\n is_new_game = True\n self.clear_elements(window)\n break\n\n if button == 'Save to My Games::save_game_k':\n logging.info('Saving game manually')\n with open(self.my_games, mode = 'a+') as f:\n self.game.headers['Event'] = 'My Games'\n f.write('{}\\n\\n'.format(self.game))\n break\n\n # Mode: Play, Stm: user\n if button == 'Save to White Repertoire':\n with open(self.repertoire_file['white'], mode = 'a+') as f:\n self.game.headers['Event'] = 'White Repertoire'\n f.write('{}\\n\\n'.format(self.game))\n break\n\n # Mode: Play, Stm: user\n if button == 'Save to Black Repertoire':\n with open(self.repertoire_file['black'], mode = 'a+') as f:\n self.game.headers['Event'] = 'Black Repertoire'\n f.write('{}\\n\\n'.format(self.game))\n break\n\n # Mode: Play, stm: User\n if button == 'Resign::resign_game_k' or is_search_stop_for_resign:\n logging.info('User resigns')\n\n # Verify resign\n reply = sg.Popup('Do you really want to resign?',\n button_type=sg.POPUP_BUTTONS_YES_NO,\n title=BOX_TITLE,\n icon=ico_path[platform]['pecg'])\n if reply == 'Yes':\n is_user_resigns = True\n break\n else:\n if is_search_stop_for_resign:\n is_search_stop_for_resign = False\n continue\n\n # Mode: Play, stm: User\n if button == 'User Wins::user_wins_k' or is_search_stop_for_user_wins:\n logging.info('User wins by adjudication')\n is_user_wins = True\n break\n\n # Mode: Play, stm: User\n if button == 'User Draws::user_draws_k' or is_search_stop_for_user_draws:\n logging.info('User draws by adjudication')\n is_user_draws = True\n break\n\n # Mode: Play, Stm: User\n if button == 'Neutral' or is_search_stop_for_neutral:\n is_exit_game = True\n self.clear_elements(window)\n break\n\n # Mode: Play, stm: User\n if button == 'About':\n sg.PopupScrolled(HELP_MSG, title=BOX_TITLE,)\n break\n\n # Mode: Play, stm: User\n if button == 'Go':\n if is_human_stm:\n is_human_stm = False\n else:\n is_human_stm = True\n is_engine_ready = True\n window.FindElement('_gamestatus_').Update(\n 'Mode Play, Engine is thinking ...')\n break\n\n # Mode: Play, stm: User\n if button == 'Paste':\n # Pasting fen is only allowed before the game starts.\n if len(self.game.variations):\n sg.Popup('Press Game->New then paste your fen.',\n title='Mode Play')\n continue\n try:\n self.get_fen()\n self.set_new_game()\n board = chess.Board(self.fen)\n except Exception:\n logging.exception('Error in parsing FEN from clipboard.')\n continue\n\n self.fen_to_psg_board(window)\n\n is_human_stm = True if board.turn else False\n is_engine_ready = True if is_human_stm else False\n\n window.FindElement('_gamestatus_').Update(\n 'Mode Play, side: {}'.format(\n 'white' if board.turn else 'black'))\n\n self.game.headers['FEN'] = self.fen\n break\n\n # Mode: Play, stm: User, user starts moving\n if type(button) is tuple:\n # If fr_sq button is pressed\n if move_state == 0:\n move_from = button\n fr_row, fr_col = move_from\n piece = self.psg_board[fr_row][fr_col] # get the move-from piece\n\n # Change the color of the \"fr\" board square\n self.change_square_color(window, fr_row, fr_col)\n\n move_state = 1\n moved_piece = board.piece_type_at(chess.square(fr_col, 7-fr_row)) # Pawn=1\n\n # Else if to_sq button is pressed\n elif move_state == 1:\n is_promote = False\n move_to = button\n to_row, to_col = move_to\n button_square = window.FindElement(key=(fr_row, fr_col))\n\n # If move is cancelled, pressing same button twice\n if move_to == move_from:\n # Restore the color of the pressed board square\n color = self.sq_dark_color if (to_row + to_col) % 2 else self.sq_light_color\n\n # Restore the color of the fr square\n button_square.Update(button_color=('white', color))\n move_state = 0\n continue\n\n # Create a move in python-chess format based from user input\n user_move = None\n\n # Get the fr_sq and to_sq of the move from user, based from this info\n # we will create a move based from python-chess format.\n # Note chess.square() and chess.Move() are from python-chess module\n fr_row, fr_col = move_from\n fr_sq = chess.square(fr_col, 7-fr_row)\n to_sq = chess.square(to_col, 7-to_row)\n\n # If user move is a promote\n if self.relative_row(to_sq, board.turn) == RANK_8 and \\\n moved_piece == chess.PAWN:\n is_promote = True\n pyc_promo, psg_promo = self.get_promo_piece(\n user_move, board.turn, True)\n user_move = chess.Move(fr_sq, to_sq, promotion=pyc_promo)\n else:\n user_move = chess.Move(fr_sq, to_sq)\n\n # Check if user move is legal\n if user_move in board.legal_moves:\n # Update rook location if this is a castle move\n if board.is_castling(user_move):\n self.update_rook(window, str(user_move))\n\n # Update board if e.p capture\n elif board.is_en_passant(user_move):\n self.update_ep(user_move, board.turn)\n\n # Empty the board from_square, applied to any types of move\n self.psg_board[move_from[0]][move_from[1]] = BLANK\n\n # Update board to_square if move is a promotion\n if is_promote:\n self.psg_board[to_row][to_col] = psg_promo\n # Update the to_square if not a promote move\n else:\n # Place piece in the move to_square\n self.psg_board[to_row][to_col] = piece\n\n self.redraw_board(window)\n\n board.push(user_move)\n move_cnt += 1\n\n # Update clock, reset elapse to zero\n human_timer.update_base()\n\n # Update game, move from human\n time_left = human_timer.base\n # we ignored the comments to better format the move list, and our prediction.\n # user_comment = value['comment_k']\n user_comment = \"\\n\"\n\n self.update_game(move_cnt, user_move, time_left, user_comment)\n\n window.FindElement('_movelist_').Update(disabled=False)\n window.FindElement('_movelist_').Update('')\n window.FindElement('_movelist_').Update(\n self.game.variations[0], append=True, disabled=True)\n\n # Clear comment and engine search box\n #window.FindElement('comment_k').Update('')\n window.Element('search_info_all_k').Update('')\n\n # Change the color of the \"fr\" and \"to\" board squares\n self.change_square_color(window, fr_row, fr_col)\n self.change_square_color(window, to_row, to_col)\n\n # call our classifiers\n window.refresh()\n ClassifyBoard(window, cnn, \"cnn_prediction\")\n ClassifyBoard(window, abc, \"abc_prediction\")\n ClassifyBoard(window, svc, \"svc_prediction\")\n\n is_human_stm = not is_human_stm\n # Human has done its move\n\n k1 = 'w_elapse_k'\n k2 = 'w_base_time_k'\n if not self.is_user_white:\n k1 = 'b_elapse_k'\n k2 = 'b_base_time_k'\n\n # Update elapse box\n elapse_str = self.get_time_mm_ss_ms(\n human_timer.elapse)\n window.Element(k1).Update(elapse_str)\n\n # Update remaining time box\n elapse_str = self.get_time_h_mm_ss(\n human_timer.base)\n window.Element(k2).Update(elapse_str)\n\n window.Element('advise_info_k').Update('')\n\n # Else if move is illegal\n else:\n move_state = 0\n color = self.sq_dark_color \\\n if (move_from[0] + move_from[1]) % 2 else self.sq_light_color\n\n # Restore the color of the fr square\n button_square.Update(button_color=('white', color))\n continue\n\n if is_new_game or is_exit_game or is_exit_app or \\\n is_user_resigns or is_user_wins or is_user_draws:\n break\n\n # Else if side to move is not human\n elif not is_human_stm and is_engine_ready:\n is_promote = False\n best_move = None\n is_book_from_gui = True\n\n # Mode: Play, stm: Computer, If using gui book\n if self.is_use_gui_book and move_cnt <= self.max_book_ply:\n # Verify presence of a book file\n if os.path.isfile(self.gui_book_file):\n gui_book = GuiBook(self.gui_book_file, board, self.is_random_book)\n best_move = gui_book.get_book_move()\n logging.info('Book move is {}.'.format(best_move))\n else:\n logging.warning('GUI book is missing.')\n\n # Mode: Play, stm: Computer, If there is no book move,\n # let the engine search the best move\n if best_move is None:\n search = RunEngine(self.queue, self.engine_config_file,\n self.opp_path_and_file, self.opp_id_name,\n self.max_depth, engine_timer.base,\n engine_timer.inc,\n tc_type=engine_timer.tc_type,\n period_moves=board.fullmove_number)\n search.get_board(board)\n search.daemon = True\n search.start()\n window.FindElement('_gamestatus_').Update(\n 'Mode Play, Engine is thinking ...')\n\n while True:\n button, value = window.Read(timeout=100)\n\n # Update elapse box in m:s format\n elapse_str = self.get_time_mm_ss_ms(engine_timer.elapse)\n k = 'b_elapse_k'\n if not self.is_user_white:\n k = 'w_elapse_k'\n window.Element(k).Update(elapse_str)\n engine_timer.elapse += 100\n\n # Hide/Unhide engine searching info while engine is thinking\n if button == 'Show::right_search_info_k':\n is_hide_search_info = False\n\n if button == 'Hide::right_search_info_k':\n is_hide_search_info = True\n window.Element('search_info_all_k').Update('')\n\n # Show book 1 while engine is searching\n if button == 'Show::right_book1_k':\n is_hide_book1 = False\n ref_book1 = GuiBook(self.computer_book_file,\n board, self.is_random_book)\n all_moves, is_found = ref_book1.get_all_moves()\n if is_found:\n window.Element('polyglot_book1_k').Update(all_moves)\n else:\n window.Element('polyglot_book1_k').Update('no book moves')\n\n # Hide book 1 while engine is searching\n if button == 'Hide::right_book1_k':\n is_hide_book1 = True\n window.Element('polyglot_book1_k').Update('')\n\n # Show book 2 while engine is searching\n if button == 'Show::right_book2_k':\n is_hide_book2 = False\n ref_book2 = GuiBook(self.human_book_file, board,\n self.is_random_book)\n all_moves, is_found = ref_book2.get_all_moves()\n if is_found:\n window.Element('polyglot_book2_k').Update(all_moves)\n else:\n window.Element('polyglot_book2_k').Update('no book moves')\n\n # Hide book 2 while engine is searching\n if button == 'Hide::right_book2_k':\n is_hide_book2 = True\n window.Element('polyglot_book2_k').Update('')\n\n # Exit app while engine is thinking \n if button is None:\n search.stop()\n is_search_stop_for_exit = True\n\n # Forced engine to move now and create a new game\n if button == 'New::new_game_k':\n search.stop()\n is_search_stop_for_new_game = True\n\n # Forced engine to move now\n if button == 'Move Now':\n search.stop()\n\n # Mode: Play, Computer is thinking\n if button == 'Neutral':\n search.stop()\n is_search_stop_for_neutral = True\n\n if button == 'Resign::resign_game_k':\n search.stop()\n is_search_stop_for_resign = True\n\n if button == 'User Wins::user_wins_k':\n search.stop()\n is_search_stop_for_user_wins = True\n\n if button == 'User Draws::user_draws_k':\n search.stop()\n is_search_stop_for_user_draws = True\n\n # Get the engine search info and display it in GUI text boxes\n try:\n msg = self.queue.get_nowait()\n except Exception:\n continue\n\n msg_str = str(msg)\n best_move = self.update_text_box(window, msg, is_hide_search_info)\n if 'bestmove' in msg_str:\n logging.info('engine msg: {}'.format(msg_str))\n break\n\n search.join()\n search.quit_engine()\n is_book_from_gui = False\n\n # If engine failed to send a legal move\n if best_move is None:\n break\n\n # Update board with computer move\n move_str = str(best_move)\n fr_col = ord(move_str[0]) - ord('a')\n fr_row = 8 - int(move_str[1])\n to_col = ord(move_str[2]) - ord('a')\n to_row = 8 - int(move_str[3])\n\n piece = self.psg_board[fr_row][fr_col]\n self.psg_board[fr_row][fr_col] = BLANK\n\n # Update rook location if this is a castle move\n if board.is_castling(best_move):\n self.update_rook(window, move_str)\n\n # Update board if e.p capture\n elif board.is_en_passant(best_move):\n self.update_ep(best_move, board.turn)\n\n # Update board if move is a promotion\n elif best_move.promotion is not None:\n is_promote = True\n _, psg_promo = self.get_promo_piece(best_move, board.turn, False)\n\n # Update board to_square if move is a promotion\n if is_promote:\n self.psg_board[to_row][to_col] = psg_promo\n # Update the to_square if not a promote move\n else:\n # Place piece in the move to_square\n self.psg_board[to_row][to_col] = piece\n\n self.redraw_board(window)\n\n board.push(best_move)\n move_cnt += 1\n\n # Update timer\n engine_timer.update_base()\n\n # Update game, move from engine\n time_left = engine_timer.base\n if is_book_from_gui:\n engine_comment = 'book'\n else:\n engine_comment = ''\n self.update_game(move_cnt, best_move, time_left, engine_comment)\n\n window.FindElement('_movelist_').Update(disabled=False)\n window.FindElement('_movelist_').Update('')\n window.FindElement('_movelist_').Update(\n self.game.variations[0], append=True, disabled=True)\n\n # Change the color of the \"fr\" and \"to\" board squares\n self.change_square_color(window, fr_row, fr_col)\n self.change_square_color(window, to_row, to_col)\n \n # call our classifiers\n window.refresh()\n ClassifyBoard(window, cnn, \"cnn_prediction\")\n ClassifyBoard(window, abc, \"abc_prediction\")\n ClassifyBoard(window, svc, \"svc_prediction\")\n\n is_human_stm = not is_human_stm\n # Engine has done its move\n\n k1 = 'b_elapse_k'\n k2 = 'b_base_time_k'\n if not self.is_user_white:\n k1 = 'w_elapse_k'\n k2 = 'w_base_time_k'\n\n # Update elapse box\n elapse_str = self.get_time_mm_ss_ms(engine_timer.elapse)\n window.Element(k1).Update(elapse_str)\n\n # Update remaining time box\n elapse_str = self.get_time_h_mm_ss(engine_timer.base)\n window.Element(k2).Update(elapse_str)\n\n window.FindElement('_gamestatus_').Update('Mode Play')\n\n # Auto-save game\n logging.info('Saving game automatically')\n if is_user_resigns:\n self.game.headers['Result'] = '0-1' if self.is_user_white else '1-0'\n self.game.headers['Termination'] = '{} resigns'.format(\n 'white' if self.is_user_white else 'black')\n elif is_user_wins:\n self.game.headers['Result'] = '1-0' if self.is_user_white else '0-1'\n self.game.headers['Termination'] = 'Adjudication'\n elif is_user_draws:\n self.game.headers['Result'] = '1/2-1/2'\n self.game.headers['Termination'] = 'Adjudication'\n else:\n self.game.headers['Result'] = board.result(claim_draw = True)\n\n base_h = int(self.human_base_time_ms / 1000)\n inc_h = int(self.human_inc_time_ms / 1000)\n base_e = int(self.engine_base_time_ms / 1000)\n inc_e = int(self.engine_inc_time_ms / 1000)\n\n if self.is_user_white:\n if self.human_tc_type == 'fischer':\n self.game.headers['WhiteTimeControl'] = str(base_h) + '+' + \\\n str(inc_h)\n elif self.human_tc_type == 'delay':\n self.game.headers['WhiteTimeControl'] = str(base_h) + '-' + \\\n str(inc_h)\n if self.engine_tc_type == 'fischer':\n self.game.headers['BlackTimeControl'] = str(base_e) + '+' + \\\n str(inc_e)\n elif self.engine_tc_type == 'timepermove':\n self.game.headers['BlackTimeControl'] = str(1) + '/' + str(base_e)\n else:\n if self.human_tc_type == 'fischer':\n self.game.headers['BlackTimeControl'] = str(base_h) + '+' + \\\n str(inc_h)\n elif self.human_tc_type == 'delay':\n self.game.headers['BlackTimeControl'] = str(base_h) + '-' + \\\n str(inc_h)\n if self.engine_tc_type == 'fischer':\n self.game.headers['WhiteTimeControl'] = str(base_e) + '+' + \\\n str(inc_e)\n elif self.engine_tc_type == 'timepermove':\n self.game.headers['WhiteTimeControl'] = str(1) + '/' + str(base_e)\n self.save_game()\n\n if board.is_game_over(claim_draw=True):\n sg.Popup('Game is over.', title=BOX_TITLE,\n icon=ico_path[platform]['pecg'])\n\n if is_exit_app:\n window.Close()\n sys.exit(0)\n\n self.clear_elements(window)\n\n return False if is_exit_game else is_new_game\n\n def save_game(self):\n \"\"\" Save game in append mode \"\"\"\n with open(self.pecg_auto_save_game, mode = 'a+') as f:\n f.write('{}\\n\\n'.format(self.game))\n\n def get_engines(self):\n \"\"\"\n Get engine filenames [a.exe, b.exe, ...]\n\n :return: list of engine filenames\n \"\"\"\n engine_list = []\n engine_path = Path('Engines')\n files = os.listdir(engine_path)\n for file in files:\n if not file.endswith('.gz') and not file.endswith('.dll') \\\n and not file.endswith('.bin') \\\n and not file.endswith('.dat'):\n engine_list.append(file)\n\n return engine_list\n\n def create_board(self, is_user_white=True):\n \"\"\"\n Returns board layout based on color of user. If user is white,\n the white pieces will be at the bottom, otherwise at the top.\n\n :param is_user_white: user has handling the white pieces\n :return: board layout\n \"\"\"\n file_char_name = 'abcdefgh'\n self.psg_board = copy.deepcopy(initial_board)\n\n board_layout = []\n\n if is_user_white:\n # Save the board with black at the top \n start = 0\n end = 8\n step = 1\n else:\n start = 7\n end = -1\n step = -1\n file_char_name = file_char_name[::-1]\n\n # Loop through the board and create buttons with images\n for i in range(start, end, step):\n # Row numbers at left of board is blank\n row = []\n for j in range(start, end, step):\n piece_image = self.images[self.psg_board[i][j]]\n row.append(self.render_square(piece_image, key=(i, j), location=(i, j)))\n board_layout.append(row)\n\n return board_layout\n\n def build_main_layout(self, is_user_white=True):\n \"\"\"\n Creates all elements for the GUI, icluding the board layout.\n\n :param is_user_white: if user is white, the white pieces are\n oriented such that the white pieces are at the bottom.\n :return: GUI layout\n \"\"\"\n sg.ChangeLookAndFeel(self.gui_theme)\n sg.SetOptions(margins=(0, 3), border_width=1)\n\n # Define board\n board_layout = self.create_board(is_user_white)\n\n board_controls = [\n [sg.Text('Mode Neutral', size=(36, 1), font=('Consolas', 10), key='_gamestatus_')],\n [sg.Text('White', size=(7, 1), font=('Consolas', 10)),\n sg.Text('Human', font=('Consolas', 10), key='_White_',\n size=(24, 1), relief='sunken'),\n sg.Text('', font=('Consolas', 10), key='w_base_time_k',\n size=(11, 1), relief='sunken'),\n sg.Text('', font=('Consolas', 10), key='w_elapse_k', size=(7, 1),\n relief='sunken')\n ],\n [sg.Text('Black', size=(7, 1), font=('Consolas', 10)),\n sg.Text('Computer', font=('Consolas', 10), key='_Black_',\n size=(24, 1), relief='sunken'),\n sg.Text('', font=('Consolas', 10), key='b_base_time_k',\n size=(11, 1), relief='sunken'),\n sg.Text('', font=('Consolas', 10), key='b_elapse_k', size=(7, 1),\n relief='sunken')\n ],\n [sg.Text('Adviser', size=(7, 1), font=('Consolas', 10), key='adviser_k',\n right_click_menu=['Right',\n ['Start::right_adviser_k', 'Stop::right_adviser_k']]),\n sg.Text('', font=('Consolas', 10), key='advise_info_k', relief='sunken',\n size=(46,1))],\n\n [sg.Text('Move list', size=(16, 1), font=('Consolas', 10))],\n [sg.Multiline('', do_not_clear=True, autoscroll=True, size=(52, 8),\n font=('Consolas', 10), key='_movelist_', disabled=True)],\n\n [sg.Text('Comment', size=(7, 1), font=('Consolas', 10))],\n #[sg.Multiline('', do_not_clear=True, autoscroll=True, size=(52, 8),\n # font=('Consolas', 10), key='comment_k')],\n [sg.Multiline('', do_not_clear=True, autoscroll=True, size=(52, 9),\n font=('Consolas', 10), key='cnn_prediction')],\n [sg.Multiline('', do_not_clear=True, autoscroll=True, size=(52, 9),\n font=('Consolas', 10), key='abc_prediction')],\n [sg.Multiline('', do_not_clear=True, autoscroll=True, size=(52, 9),\n font=('Consolas', 10), key='svc_prediction')],\n\n [sg.Text('BOOK 1, Comp games', size=(26, 1),\n font=('Consolas', 10),\n right_click_menu=['Right',\n ['Show::right_book1_k', 'Hide::right_book1_k']]),\n sg.Text('BOOK 2, Human games',\n font=('Consolas', 10),\n right_click_menu=['Right',\n ['Show::right_book2_k', 'Hide::right_book2_k']])],\n [sg.Multiline('', do_not_clear=True, autoscroll=False, size=(23, 4),\n font=('Consolas', 10), key='polyglot_book1_k', disabled=True),\n sg.Multiline('', do_not_clear=True, autoscroll=False, size=(25, 4),\n font=('Consolas', 10), key='polyglot_book2_k', disabled=True)],\n\n [sg.Text('Opponent Search Info', font=('Consolas', 10), size=(30, 1),\n right_click_menu=['Right',\n ['Show::right_search_info_k', 'Hide::right_search_info_k']])],\n [sg.Text('', key='search_info_all_k', size=(55, 1),\n font=('Consolas', 10), relief='sunken')],\n ]\n\n board_tab = [[sg.Column(board_layout)]]\n\n self.menu_elem = sg.Menu(menu_def_neutral, tearoff=False)\n\n # White board layout, mode: Neutral\n layout = [\n [self.menu_elem],\n [sg.Column(board_tab), sg.Column(board_controls)]\n ]\n\n return layout\n \n def set_default_adviser_engine(self): \n try:\n self.adviser_id_name = self.engine_id_name_list[1] \\\n if len(self.engine_id_name_list) >= 2 \\\n else self.engine_id_name_list[0]\n self.adviser_file, self.adviser_path_and_file = \\\n self.get_engine_file(self.adviser_id_name)\n except IndexError as e:\n logging.warning(e)\n except Exception:\n logging.exception('Error in getting adviser engine!')\n \n def get_default_engine_opponent(self):\n engine_id_name = None\n try:\n engine_id_name = self.opp_id_name = self.engine_id_name_list[0]\n self.opp_file, self.opp_path_and_file = self.get_engine_file(\n engine_id_name)\n except IndexError as e:\n logging.warning(e)\n except Exception:\n logging.exception('Error in getting opponent engine!')\n \n return engine_id_name\n\n def main_loop(self):\n \"\"\"\n Build GUI, read user and engine config files and take user inputs.\n\n :return:\n \"\"\"\n engine_id_name = None\n layout = self.build_main_layout(True)\n\n # Use white layout as default window\n window = sg.Window('{} {}'.format(APP_NAME, APP_VERSION),\n layout, default_button_element_size=(12, 1),\n auto_size_buttons=False,\n icon=ico_path[platform]['pecg'])\n\n # Read user config file, if missing create and new one\n self.check_user_config_file()\n\n # If engine config file (pecg_engines.json) is missing, then create it \n self.check_engine_config_file()\n self.engine_id_name_list = self.get_engine_id_name_list()\n\n # Define default opponent engine, user can change this later.\n engine_id_name = self.get_default_engine_opponent()\n\n # Define default adviser engine, user can change this later.\n self.set_default_adviser_engine()\n\n self.init_game()\n\n # Initialize White and black boxes\n while True:\n button, value = window.Read(timeout=50)\n self.update_labels_and_game_tags(window, human=self.username)\n break\n\n # Mode: Neutral, main loop starts here\n while True:\n button, value = window.Read(timeout=50)\n\n # Mode: Neutral\n if button is None:\n logging.info('Quit app from main loop, X is pressed.')\n break\n\n # Mode: Neutral, Delete player\n if button == 'Delete Player::delete_player_k':\n win_title = 'Tools/Delete Player'\n player_list = []\n sum_games = 0\n layout = [\n [sg.Text('PGN', size=(4, 1)),\n sg.Input(size=(40,1), key='pgn_k'), sg.FileBrowse()],\n [sg.Button('Display Players', size=(48,1))],\n [sg.Text('Status:', size=(48, 1), key='status_k',\n relief='sunken')],\n [sg.T('Current players in the pgn', size=(43, 1))],\n [sg.Listbox([], size=(53, 10),\n key='player_k')],\n [sg.Button('Delete Player'), sg.Cancel()]\n ]\n\n window.Disable()\n w = sg.Window(win_title, layout,\n icon=ico_path[platform]['pecg'])\n while True:\n e, v = w.Read(timeout=10)\n if e is None or e == 'Cancel':\n break\n if e == 'Display Players':\n pgn = v['pgn_k']\n if pgn == '':\n logging.info('Missing pgn file.')\n sg.Popup('Please locate your pgn file by pressing '\n 'the Browse button followed by Display '\n 'Players.',\n title=win_title,\n icon=ico_path[platform]['pecg'])\n break\n\n t1 = time.perf_counter()\n que = queue.Queue()\n t = threading.Thread(target=self.get_players,\n args=(pgn, que,),daemon=True)\n t.start()\n msg = None\n while True:\n e1, v1 = w.Read(timeout=100)\n w.Element('status_k').Update(\n 'Display Players: processing ...')\n try:\n msg = que.get_nowait()\n elapse = int(time.perf_counter() - t1)\n w.Element('status_k').Update(\n 'Players are displayed. Done! in ' +\n str(elapse) + 's')\n break\n except Exception:\n continue\n t.join()\n player_list = msg[0]\n sum_games = msg[1]\n w.Element('player_k').Update(sorted(player_list))\n\n if e == 'Delete Player':\n try:\n player_name = v['player_k'][0]\n except IndexError as e:\n logging.info(e)\n sg.Popup('Please locate your pgn file by '\n 'pressing the Browse button followed by Display Players.',\n title=win_title,\n icon=ico_path[platform]['pecg'])\n break\n except Exception:\n logging.exception('Failed to get player.')\n break\n\n t1 = time.perf_counter()\n que = queue.Queue()\n t = threading.Thread(target=self.delete_player,\n args=(player_name, v['pgn_k'], que,),\n daemon=True)\n t.start()\n msg = None\n while True:\n e1, v1 = w.Read(timeout=100)\n w.Element('status_k').Update(\n 'Status: Delete: processing ...')\n try:\n msg = que.get_nowait()\n if msg == 'Done':\n elapse = int(time.perf_counter() - t1)\n w.Element('status_k').Update(\n player_name + ' was deleted. Done! '\n 'in ' + str(elapse) + 's')\n break\n else:\n w.Element('status_k').Update(\n msg + '/' + str(sum_games))\n except Exception:\n continue\n t.join()\n\n # Update player list in listbox\n player_list.remove(player_name)\n w.Element('player_k').Update(sorted(player_list))\n\n w.Close()\n window.Enable()\n continue\n\n # Mode: Neutral, Set User time control\n if button == 'User::tc_k':\n win_title = 'Time/User'\n layout = [\n [sg.T('Base time (minute)', size=(16, 1)),\n sg.Input(self.human_base_time_ms/60/1000,\n key='base_time_k', size=(8, 1))],\n [sg.T('Increment (second)', size=(16, 1)),\n sg.Input(self.human_inc_time_ms/1000, key='inc_time_k',\n size=(8, 1))],\n [sg.T('Period moves', size=(16, 1), visible=False),\n sg.Input(self.human_period_moves, key='period_moves_k',\n size=(8, 1), visible=False)],\n [sg.Radio('Fischer', 'tc_radio', key='fischer_type_k',\n default=True if\n self.human_tc_type=='fischer' else False),\n sg.Radio('Delay', 'tc_radio', key='delay_type_k',\n default=True if self.human_tc_type == 'delay'\n else False)],\n [sg.OK(), sg.Cancel()]\n ]\n\n window.Disable()\n w = sg.Window(win_title, layout,\n icon=ico_path[platform]['pecg'])\n while True:\n e, v = w.Read(timeout=10)\n if e is None:\n break\n if e == 'Cancel':\n break\n if e == 'OK':\n base_time_ms = int(1000 * 60 * float(v['base_time_k']))\n inc_time_ms = int(1000 * float(v['inc_time_k']))\n period_moves = int(v['period_moves_k'])\n\n tc_type = 'fischer'\n if v['fischer_type_k']:\n tc_type = 'fischer'\n elif v['delay_type_k']:\n tc_type = 'delay'\n\n self.human_base_time_ms = base_time_ms\n self.human_inc_time_ms = inc_time_ms\n self.human_period_moves = period_moves\n self.human_tc_type = tc_type\n break\n w.Close()\n window.Enable()\n continue\n\n # Mode: Neutral, Set engine time control\n if button == 'Engine::tc_k':\n win_title = 'Time/Engine'\n layout = [\n [sg.T('Base time (minute)', size=(16, 1)),\n sg.Input(self.engine_base_time_ms / 60 / 1000,\n key='base_time_k', size=(8, 1))],\n [sg.T('Increment (second)', size=(16, 1)),\n sg.Input(self.engine_inc_time_ms / 1000,\n key='inc_time_k',\n size=(8, 1))],\n [sg.T('Period moves', size=(16, 1), visible=False),\n sg.Input(self.engine_period_moves,\n key='period_moves_k', size=(8, 1),\n visible=False)],\n [sg.Radio('Fischer', 'tc_radio', key='fischer_type_k',\n default=True if\n self.engine_tc_type == 'fischer' else False),\n sg.Radio('Time Per Move', 'tc_radio', key='timepermove_k',\n default=True if\n self.engine_tc_type == 'timepermove' else\n False, tooltip='Only base time will be used.')\n ],\n [sg.OK(), sg.Cancel()]\n ]\n\n window.Disable()\n w = sg.Window(win_title, layout,\n icon=ico_path[platform]['pecg'])\n while True:\n e, v = w.Read(timeout=10)\n if e is None:\n break\n if e == 'Cancel':\n break\n if e == 'OK':\n base_time_ms = int(\n 1000 * 60 * float(v['base_time_k']))\n inc_time_ms = int(1000 * float(v['inc_time_k']))\n period_moves = int(v['period_moves_k'])\n\n tc_type = 'fischer'\n if v['fischer_type_k']:\n tc_type = 'fischer'\n elif v['timepermove_k']:\n tc_type = 'timepermove'\n\n self.engine_base_time_ms = base_time_ms\n self.engine_inc_time_ms = inc_time_ms\n self.engine_period_moves = period_moves\n self.engine_tc_type = tc_type\n break\n w.Close()\n window.Enable()\n continue\n\n # Mode: Neutral, set username\n if button == 'Set Name::user_name_k':\n win_title = 'User/username'\n layout = [\n [sg.Text('Current username: {}'.format(\n self.username))],\n [sg.T('Name', size=(4,1)), sg.Input(\n self.username, key='username_k', size=(32,1))],\n [sg.OK(), sg.Cancel()]\n ]\n window.Disable()\n w = sg.Window(win_title, layout,\n icon=ico_path[platform]['pecg'])\n while True:\n e, v = w.Read(timeout=10)\n if e is None:\n break\n if e == 'Cancel':\n break\n if e == 'OK':\n backup = self.username\n username = self.username = v['username_k']\n if username == '':\n username = backup\n self.update_user_config_file(username)\n break\n w.Close()\n window.Enable()\n self.update_labels_and_game_tags(window, human=self.username)\n continue\n\n # Mode: Neutral\n if button == 'Install':\n button_title = 'Engine/Manage/' + button\n new_engine_path_file, new_engine_id_name = None, None\n\n install_layout = [\n [sg.Text('Current configured engine names')],\n [sg.Listbox(values=self.engine_id_name_list,\n size=(48,10), disabled=True)],\n [sg.Button('Add'), sg.Button('Cancel')]\n ]\n\n window.Disable()\n install_win = sg.Window(title=button_title,\n layout=install_layout,\n icon=ico_path[platform]['pecg'])\n\n while True:\n e, v = install_win.Read(timeout=100)\n if e is None or e == 'Cancel':\n break\n if e == 'Add':\n button_title += '/' + e\n\n add_layout = [[sg.Text('Engine', size=(6, 1)),\n sg.Input(key='engine_path_file_k'),\n sg.FileBrowse()],\n [sg.Text('Name', size=(6, 1)),\n sg.Input(key='engine_id_name_k',\n tooltip='Input name'),\n sg.Button('Get Id Name')],\n [sg.OK(), sg.Cancel()]]\n\n install_win.Disable()\n add_win = sg.Window(button_title, add_layout)\n is_cancel_add_win = False\n while True:\n e1, v1 = add_win.Read(timeout=100)\n if e1 is None:\n is_cancel_add_win = True\n break\n if e1 == 'Cancel':\n is_cancel_add_win = True\n break\n if e1 == 'Get Id Name':\n new_engine_path_file = v1['engine_path_file_k']\n\n que = queue.Queue()\n t = threading.Thread(target=self.get_engine_id_name,\n args=(new_engine_path_file, que,),\n daemon=True)\n t.start()\n is_update_list = False\n while True:\n try:\n msg = que.get_nowait()\n break\n except Exception:\n pass\n t.join()\n\n if msg[0] == 'Done' and msg[1] is not None:\n is_update_list = True\n new_engine_id_name = msg[1]\n else:\n is_cancel_add_win = True\n sg.Popup(\n 'This engine cannot be '\n 'installed. Please select '\n 'another engine. It should be uci '\n 'engine.',\n title=button_title + '/Get Id name')\n\n if is_update_list:\n add_win.Element('engine_id_name_k').Update(\n new_engine_id_name)\n\n # If we fail to install the engine, we exit\n # the install window\n if is_cancel_add_win:\n break\n\n if e1 == 'OK':\n try:\n new_engine_path_file = v1[\n 'engine_path_file_k']\n new_engine_id_name = v1['engine_id_name_k']\n if new_engine_id_name != '':\n # Check if new_engine_id_name is already existing\n if self.is_name_exists(\n new_engine_id_name):\n sg.Popup(\n '{} is existing. Please '\n 'modify the name! You can '\n 'modify the config later thru '\n 'Engine->Manage->Edit'.format(\n new_engine_id_name),\n title=button_title,\n icon=ico_path[platform]['pecg'])\n continue\n break\n else:\n sg.Popup('Please input engine id '\n 'name, or press Get Id Name '\n 'button.',\n title=button_title,\n icon=ico_path[platform]['pecg'])\n except Exception:\n logging.exception('Failed to get engine '\n 'path and file')\n\n # Outside add window while loop\n add_win.Close()\n install_win.Enable()\n\n # Save the new configured engine to pecg_engines.json.\n if not is_cancel_add_win:\n que = queue.Queue()\n t = threading.Thread(\n target=self.add_engine_to_config_file,\n args=(new_engine_path_file,\n new_engine_id_name, que,), daemon=True)\n t.start()\n while True:\n try:\n msg = que.get_nowait()\n break\n except Exception:\n continue\n t.join()\n\n if msg == 'Failure':\n sg.Popup('Failed to add {} in config '\n 'file!'.format(new_engine_id_name),\n title=button_title,\n icon=ico_path[platform]['pecg'])\n\n self.engine_id_name_list = \\\n self.get_engine_id_name_list()\n break\n\n install_win.Close()\n window.Enable()\n \n # Define default engine opponent and adviser\n if engine_id_name is None:\n engine_id_name = self.get_default_engine_opponent()\n if self.adviser_id_name is None:\n self.set_default_adviser_engine()\n \n self.update_labels_and_game_tags(window, human=self.username)\n \n continue\n\n # Mode: Neutral\n if button == 'Edit':\n button_title = 'Engine/Manage/' + button\n opt_name = []\n ret_opt_name = []\n engine_path_file, engine_id_name = None, None\n\n edit_layout = [\n [sg.Text('Current configured engine names')],\n [sg.Listbox(values=self.engine_id_name_list,\n size=(48,10),\n key='engine_id_name_k')],\n [sg.Button('Modify'), sg.Button('Cancel')]\n ]\n\n window.Disable()\n edit_win = sg.Window(button_title, layout=edit_layout,\n icon=ico_path[platform]['pecg'])\n is_cancel_edit_win = False\n while True:\n e, v = edit_win.Read(timeout=100)\n if e is None or e == 'Cancel':\n is_cancel_edit_win = True\n break\n if e == 'Modify':\n option_layout, option_layout2 = [], []\n button_title += '/' + e\n\n try:\n orig_idname = engine_id_name = v['engine_id_name_k'][0]\n except Exception:\n sg.Popup('Please select an engine to modify.',\n title='/Edit/Modify',\n icon=ico_path[platform]['pecg'])\n continue\n\n # Read engine config file\n with open(self.engine_config_file, 'r') as json_file:\n data = json.load(json_file)\n\n # First option that can be set is the config name\n option_layout.append(\n [sg.Text('name', size=(4, 1)),\n sg.Input(engine_id_name, size=(38, 1),\n key='string_name_k')])\n opt_name.append(['name', 'string_name_k'])\n\n for p in data:\n name = p['name']\n path = p['workingDirectory']\n file = p['command']\n engine_path_file = Path(path, file)\n option = p['options']\n\n if name == engine_id_name:\n num_opt = len(option)\n opt_cnt = 0\n for o in option:\n opt_cnt += 1\n name = o['name']\n value = o['value']\n type_ = o['type']\n\n if type_ == 'spin':\n min_ = o['min']\n max_ = o['max']\n\n key_name = type_ + '_' + name.lower() + '_k'\n opt_name.append([name, key_name])\n\n ttip = 'min {} max {}'.format(min_, max_)\n spin_layout = \\\n [sg.Text(name, size=(16, 1)),\n sg.Input(value, size=(8, 1),\n key=key_name,\n tooltip=ttip)]\n if num_opt > 10 and opt_cnt > num_opt//2:\n option_layout2.append(spin_layout)\n else:\n option_layout.append(spin_layout)\n\n elif type_ == 'check':\n key_name = type_ + '_' + name.lower() + '_k'\n opt_name.append([name, key_name])\n\n check_layout = \\\n [sg.Text(name, size=(16, 1)),\n sg.Checkbox('', key=key_name,\n default=value)]\n if num_opt > 10 and opt_cnt > num_opt//2:\n option_layout2.append(check_layout)\n else:\n option_layout.append(check_layout)\n\n elif type_ == 'string':\n key_name = type_ + '_' + name + '_k'\n opt_name.append([name, key_name])\n\n # Use FolderBrowse()\n if 'syzygypath' in name.lower():\n sy_layout = \\\n [sg.Text(name, size=(16, 1)),\n sg.Input(value,\n size=(12, 1),\n key=key_name),\n sg.FolderBrowse()]\n\n if num_opt > 10 and opt_cnt > num_opt//2:\n option_layout2.append(sy_layout)\n else:\n option_layout.append(sy_layout)\n\n # Use FileBrowse()\n elif 'weightsfile' in name.lower():\n weight_layout = \\\n [sg.Text(name, size=(16, 1)),\n sg.Input(value,\n size=(12, 1),\n key=key_name),\n sg.FileBrowse()]\n\n if num_opt > 10 and opt_cnt > num_opt//2:\n option_layout2.append(\n weight_layout)\n else:\n option_layout.append(\n weight_layout)\n else:\n str_layout = \\\n [sg.Text(name, size=(16, 1)),\n sg.Input(value, size=(16, 1),\n key=key_name)]\n\n if num_opt > 10 and opt_cnt > num_opt//2:\n option_layout2.append(\n str_layout)\n else:\n option_layout.append(\n str_layout)\n\n elif type_ == 'combo':\n key_name = type_ + '_' + name + '_k'\n opt_name.append([name, key_name])\n var = o['choices']\n combo_layout = [\n sg.Text(name, size=(16, 1)),\n sg.Combo(var, default_value=value,\n size=(12, 1),\n key=key_name)]\n if num_opt > 10 and opt_cnt > num_opt//2:\n option_layout2.append(combo_layout)\n else:\n option_layout.append(combo_layout)\n break\n\n option_layout.append([sg.OK(), sg.Cancel()])\n\n if len(option_layout2) > 1:\n tab1 = [[sg.Column(option_layout)]]\n tab2 = [[sg.Column(option_layout2)]]\n modify_layout = [[sg.Column(tab1), sg.Column(tab2)]]\n else:\n modify_layout = option_layout\n\n edit_win.Disable()\n modify_win = sg.Window(button_title,\n layout=modify_layout,\n icon=ico_path[platform]['pecg'])\n is_cancel_modify_win = False\n while True:\n e1, v1 = modify_win.Read(timeout=100)\n if e1 is None or e1 == 'Cancel':\n is_cancel_modify_win = True\n break\n if e1 == 'OK':\n engine_id_name = v1['string_name_k']\n for o in opt_name:\n d = {o[0]: v1[o[1]]}\n ret_opt_name.append(d)\n break\n\n edit_win.Enable()\n modify_win.Close()\n break # Get out of edit_win loop\n\n # Outside edit_win while loop\n\n # Save the new configured engine to pecg_engines.json file\n if not is_cancel_edit_win and not is_cancel_modify_win:\n self.update_engine_to_config_file(\n engine_path_file, engine_id_name,\n orig_idname, ret_opt_name)\n self.engine_id_name_list = self.get_engine_id_name_list()\n\n edit_win.Close()\n window.Enable()\n continue\n\n # Mode: Neutral\n if button == 'Delete':\n button_title = 'Engine/Manage/' + button\n delete_layout = [\n [sg.Text('Current configured engine names')],\n [sg.Listbox(values=self.engine_id_name_list, size=(48, 10),\n key='engine_id_name_k')],\n [sg.Button('Delete'), sg.Cancel()]\n ]\n window.Disable()\n delete_win = sg.Window(button_title, layout=delete_layout,\n icon=ico_path[platform]['pecg'])\n is_cancel = False\n while True:\n e, v = delete_win.Read(timeout=100)\n if e is None or e == 'Cancel':\n is_cancel = True\n break\n if e == 'Delete':\n try:\n engine_id_name = v['engine_id_name_k'][0]\n except Exception:\n sg.Popup('Please select an engine to delete.',\n title=button_title,\n icon=ico_path[platform]['pecg'])\n continue\n with open(self.engine_config_file, 'r') as json_file:\n data = json.load(json_file)\n\n for i in range(len(data)):\n if data[i]['name'] == engine_id_name:\n logging.info('{} is found for deletion.'.format(\n engine_id_name))\n data.pop(i)\n break\n\n # Save data to pecg_engines.json\n with open(self.engine_config_file, 'w') as h:\n json.dump(data, h, indent=4)\n\n break\n\n # Save the new configured engine to pecg_engines.json file\n if not is_cancel:\n self.engine_id_name_list = self.get_engine_id_name_list()\n\n delete_win.Close()\n window.Enable()\n\n continue\n\n # Mode: Neutral, Allow user to change opponent engine settings\n if button == 'Set Engine Opponent':\n current_engine_file = self.opp_file\n current_engine_id_name = self.opp_id_name\n\n logging.info('Backup current engine list and file.')\n logging.info('Current engine file: {}'.format(\n current_engine_file))\n\n layout = [\n [sg.T('Current Opponent: {}'.format(self.opp_id_name),\n size=(40,1))],\n [sg.Listbox(values=self.engine_id_name_list, size=(48,10),\n key='engine_id_k')],\n [sg.OK(), sg.Cancel()]\n ]\n\n # Create new window and disable the main window\n w = sg.Window(BOX_TITLE + '/Select opponent', layout,\n icon=ico_path[platform]['enemy'])\n window.Disable()\n\n while True:\n e, v = w.Read(timeout=10)\n\n if e is None or e == 'Cancel':\n # Restore current engine list and file\n logging.info('User cancels engine selection. ' +\n 'We restore the current engine data.')\n self.opp_file = current_engine_file\n logging.info('Current engine data were restored.')\n logging.info('current engine file: {}'.format(\n self.opp_file))\n break\n\n if e == 'OK':\n # We use try/except because user can press OK without\n # selecting an engine\n try:\n engine_id_name = self.opp_id_name = v['engine_id_k'][0]\n self.opp_file, self.opp_path_and_file = self.get_engine_file(\n engine_id_name)\n\n except IndexError:\n logging.info('User presses OK but did not select '\n 'an engine.')\n except Exception:\n logging.exception('Failed to set engine.')\n finally:\n if current_engine_id_name != self.opp_id_name:\n logging.info('User selected a new opponent {'\n '}.'.format(self.opp_id_name))\n break\n\n window.Enable()\n w.Close()\n\n # Update the player box in main window\n self.update_labels_and_game_tags(window, human=self.username)\n continue\n\n # Mode: Neutral, Set Adviser engine\n if button == 'Set Engine Adviser':\n current_adviser_engine_file = self.adviser_file\n current_adviser_path_and_file = self.adviser_path_and_file\n\n layout = [\n [sg.T('Current Adviser: {}'.format(self.adviser_id_name),\n size=(40,1))],\n [sg.Listbox(values=self.engine_id_name_list, size=(48,10),\n key='adviser_id_name_k')],\n [sg.T('Movetime (sec)', size=(12, 1)),\n sg.Spin([t for t in range(1, 3600, 1)],\n initial_value=self.adviser_movetime_sec,\n size=(8, 1), key='adviser_movetime_k')],\n [sg.OK(), sg.Cancel()]\n ]\n\n # Create new window and disable the main window\n w = sg.Window(BOX_TITLE + '/Select Adviser', layout,\n icon=ico_path[platform]['adviser'])\n window.Disable()\n\n while True:\n e, v = w.Read(timeout=10)\n\n if e is None or e == 'Cancel':\n self.adviser_file = current_adviser_engine_file\n self.adviser_path_and_file = current_adviser_path_and_file\n break\n\n if e == 'OK':\n movetime_sec = int(v['adviser_movetime_k'])\n self.adviser_movetime_sec = min(3600, max(1, movetime_sec))\n\n # We use try/except because user can press OK without selecting an engine\n try:\n adviser_eng_id_name = self.adviser_id_name = v['adviser_id_name_k'][0]\n self.adviser_file, self.adviser_path_and_file = self.get_engine_file(\n adviser_eng_id_name)\n except IndexError:\n logging.info('User presses OK but did not select an engine')\n except Exception:\n logging.exception('Failed to set engine.')\n break\n\n window.Enable()\n w.Close()\n continue\n\n # Mode: Neutral\n if button == 'Set Depth':\n self.set_depth_limit()\n continue\n\n # Mode: Neutral, Allow user to change book settings\n if button == 'Set Book::book_set_k':\n # Backup current values, we will restore these value in case\n # the user presses cancel or X button\n current_is_use_gui_book = self.is_use_gui_book\n current_is_random_book = self.is_random_book\n current_max_book_ply = self.max_book_ply\n\n layout = [\n [sg.Text('This is the book used by your '\n 'engine opponent.')],\n [sg.T('Book File', size=(8, 1)),\n sg.T(self.gui_book_file, size=(36, 1), relief='sunken')],\n [sg.T('Max Ply', size=(8, 1)),\n sg.Spin([t for t in range(1, 33, 1)],\n initial_value=self.max_book_ply,\n size=(6, 1), key='book_ply_k')],\n [sg.CBox('Use book', key = 'use_gui_book_k',\n default=self.is_use_gui_book)],\n [sg.Radio('Best move', 'Book Radio',\n default = False if self.is_random_book else True),\n sg.Radio('Random move', 'Book Radio',\n key='random_move_k',\n default = True if self.is_random_book else False)],\n [sg.OK(), sg.Cancel()],\n ]\n\n w = sg.Window(BOX_TITLE + '/Set Book', layout,\n icon=ico_path[platform]['pecg'])\n window.Disable()\n\n while True:\n e, v = w.Read(timeout=10)\n\n # If user presses X button\n if e is None:\n self.is_use_gui_book = current_is_use_gui_book\n self.is_random_book = current_is_random_book\n self.max_book_ply = current_max_book_ply\n logging.info('Book setting is exited.')\n break\n\n if e == 'Cancel':\n self.is_use_gui_book = current_is_use_gui_book\n self.is_random_book = current_is_random_book\n self.max_book_ply = current_max_book_ply\n logging.info('Book setting is cancelled.')\n break\n\n if e == 'OK':\n self.max_book_ply = int(v['book_ply_k'])\n self.is_use_gui_book = v['use_gui_book_k']\n self.is_random_book = v['random_move_k']\n logging.info('Book setting is OK')\n break\n\n window.Enable()\n w.Close()\n continue\n\n # Mode: Neutral, Settings menu\n if button == 'Game::settings_game_k':\n win_title = 'Settings/Game'\n layout = [\n [sg.CBox('Save time left in game notation',\n key='save_time_left_k',\n default=self.is_save_time_left,\n tooltip='[%clk h:mm:ss] will appear as\\n' +\n 'move comment and is shown in move\\n' +\n 'list and saved in pgn file.')],\n [sg.OK(), sg.Cancel()],\n ]\n\n w = sg.Window(win_title, layout,\n icon=ico_path[platform]['pecg'])\n window.Disable()\n\n while True:\n e, v = w.Read(timeout=10)\n if e is None or e == 'Cancel':\n break\n if e == 'OK':\n self.is_save_time_left = v['save_time_left_k']\n break\n\n window.Enable()\n w.Close()\n continue\n\n # Mode: Neutral, Change theme\n if button in GUI_THEME:\n self.gui_theme = button\n window = self.create_new_window(window)\n continue\n\n if button in PIECE_THEME:\n print(\"selected piece theme \" + button)\n self.images = dataset_themes[button]\n self.redraw_board(window)\n continue\n\n # Mode: Neutral, Change board to gray\n if button == 'Gray::board_color_k':\n self.sq_light_color = '#D8D8D8'\n self.sq_dark_color = '#808080'\n self.move_sq_light_color = '#e0e0ad'\n self.move_sq_dark_color = '#999966'\n self.redraw_board(window)\n window = self.create_new_window(window)\n continue\n\n # Mode: Neutral, Change board to green\n if button == 'Green::board_color_k':\n self.sq_light_color = '#daf1e3'\n self.sq_dark_color = '#3a7859'\n self.move_sq_light_color = '#bae58f'\n self.move_sq_dark_color = '#6fbc55'\n self.redraw_board(window)\n window = self.create_new_window(window)\n continue\n\n # Mode: Neutral, Change board to blue\n if button == 'Blue::board_color_k':\n self.sq_light_color = '#b9d6e8'\n self.sq_dark_color = '#4790c0'\n self.move_sq_light_color = '#d2e4ba'\n self.move_sq_dark_color = '#91bc9c'\n self.redraw_board(window)\n window = self.create_new_window(window)\n continue\n\n # Mode: Neutral, Change board to brown, default\n if button == 'Brown::board_color_k':\n self.sq_light_color = '#F0D9B5'\n self.sq_dark_color = '#B58863'\n self.move_sq_light_color = '#E8E18E'\n self.move_sq_dark_color = '#B8AF4E'\n self.redraw_board(window)\n window = self.create_new_window(window)\n continue\n\n # Mode: Neutral\n if button == 'Flip':\n window.FindElement('_gamestatus_').Update('Mode Neutral')\n self.clear_elements(window)\n window = self.create_new_window(window, True)\n continue\n\n # Mode: Neutral\n if button == 'About':\n sg.PopupScrolled(HELP_MSG, title='Help/About')\n continue\n\n # Mode: Neutral\n if button == 'Play':\n if engine_id_name is None:\n logging.warning('Install engine first!')\n sg.Popup('Install engine first! in Engine/Manage/Install',\n icon=ico_path[platform]['pecg'], title='Mode')\n continue\n \n # Change menu from Neutral to Play\n self.menu_elem.Update(menu_def_play)\n self.psg_board = copy.deepcopy(initial_board)\n board = chess.Board()\n\n while True:\n button, value = window.Read(timeout=100)\n\n window.FindElement('_gamestatus_').Update('Mode Play')\n window.FindElement('_movelist_').Update(disabled=False)\n window.FindElement('_movelist_').Update('', disabled=True)\n\n start_new_game = self.play_game(window, engine_id_name, board)\n window.FindElement('_gamestatus_').Update('Mode Neutral')\n\n self.psg_board = copy.deepcopy(initial_board)\n self.redraw_board(window)\n board = chess.Board()\n self.set_new_game()\n\n if not start_new_game:\n break\n\n # Restore Neutral menu\n self.menu_elem.Update(menu_def_neutral)\n self.psg_board = copy.deepcopy(initial_board)\n board = chess.Board()\n self.set_new_game()\n continue\n\n window.Close()\n\n\ndef main():\n engine_config_file = 'pecg_engines.json'\n user_config_file = 'pecg_user.json'\n\n pecg_book = 'Book/pecg_book.bin'\n book_from_computer_games = 'Book/computer.bin'\n book_from_human_games = 'Book/human.bin'\n\n is_use_gui_book = True\n is_random_book = True # If false then use best book move\n max_book_ply = 8\n theme = 'Reddit'\n\n pecg = EasyChessGui(theme, engine_config_file, user_config_file,\n pecg_book, book_from_computer_games,\n book_from_human_games, is_use_gui_book, is_random_book,\n max_book_ply)\n\n pecg.main_loop()\n\n\nif __name__ == \"__main__\":\n main()\n"
] | [
[
"numpy.asarray",
"numpy.array2string",
"numpy.array"
]
] |
ug-kim/nerf-pytorch-DDP | [
"8dbda485fc4f243e96eac2112440a5e10efe5ddc"
] | [
"main.py"
] | [
"\nimport os, sys\nimport numpy as np\nimport imageio\nimport json\nimport random\nimport time\nimport wandb\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom tqdm import tqdm, trange\n\nimport matplotlib.pyplot as plt\n\nimport torch.distributed as dist\nimport torch.multiprocessing as mp\nfrom torch.nn.parallel import DistributedDataParallel as DDP\n\nfrom run_nerf_helpers import *\n\nfrom load_llff import load_llff_data\nfrom load_deepvoxels import load_dv_data\nfrom load_blender import load_blender_data\nfrom load_LINEMOD import load_LINEMOD_data\n\nfrom run_nerf import *\n\n# DDP\ndef main(args):\n world_size = args.world_size\n os.environ[\"MASTER_ADDR\"] = \"localhost\"\n os.environ[\"MASTER_PORT\"] = str(args.port)\n\n mp.spawn(train, args=(world_size, args, ), nprocs=world_size, join=True)\n\ndef setup(rank: int, world_size: int):\n # utils.seed_everything()\n torch.cuda.set_device(rank)\n pg = dist.init_process_group(backend=\"nccl\", init_method='env://', rank=rank, world_size=world_size)\n return pg\n\ndef cleanup():\n dist.destroy_process_group()\n\ndef train(rank: int, world_size: int, args):\n # For training DDP -> we have to set_default_tesnor to cuda at each training process\n torch.set_default_tensor_type('torch.cuda.FloatTensor')\n pg = setup(rank, world_size)\n\n if rank == 0:\n wandb.login()\n wandb.init(project=args.wandb_project, entity=args.wandb_entity, name=args.wandb_name, save_code=True, config=args)\n\n # Load data\n K = None\n if args.dataset_type == 'llff':\n images, poses, bds, render_poses, i_test = load_llff_data(args.datadir, args.factor,\n recenter=True, bd_factor=.75,\n spherify=args.spherify)\n hwf = poses[0,:3,-1]\n poses = poses[:,:3,:4]\n print('Loaded llff', images.shape, render_poses.shape, hwf, args.datadir)\n if not isinstance(i_test, list):\n i_test = [i_test]\n\n if args.llffhold > 0:\n print('Auto LLFF holdout,', args.llffhold)\n i_test = np.arange(images.shape[0])[::args.llffhold]\n\n # i_val = i_test\n # i_train = np.array([i for i in np.arange(int(images.shape[0])) if\n # (i not in i_test and i not in i_val)])\n\n i_train = np.array([i for i in np.arange(int(images.shape[0]))])\n i_test = i_train\n i_val = i_test\n\n print('DEFINING BOUNDS')\n if args.no_ndc:\n near = np.ndarray.min(bds) * .9\n far = np.ndarray.max(bds) * 1.\n \n else:\n near = 0.\n far = 1.\n print('NEAR FAR', near, far)\n\n elif args.dataset_type == 'blender':\n images, poses, render_poses, hwf, i_split = load_blender_data(args.datadir, args.half_res, args.testskip)\n print('Loaded blender', images.shape, render_poses.shape, hwf, args.datadir)\n i_train, i_val, i_test = i_split\n\n near = 2.\n far = 6.\n\n if args.white_bkgd:\n images = images[...,:3]*images[...,-1:] + (1.-images[...,-1:])\n else:\n images = images[...,:3]\n\n elif args.dataset_type == 'LINEMOD':\n images, poses, render_poses, hwf, K, i_split, near, far = load_LINEMOD_data(args.datadir, args.half_res, args.testskip)\n print(f'Loaded LINEMOD, images shape: {images.shape}, hwf: {hwf}, K: {K}')\n print(f'[CHECK HERE] near: {near}, far: {far}.')\n i_train, i_val, i_test = i_split\n\n if args.white_bkgd:\n images = images[...,:3]*images[...,-1:] + (1.-images[...,-1:])\n else:\n images = images[...,:3]\n\n elif args.dataset_type == 'deepvoxels':\n\n images, poses, render_poses, hwf, i_split = load_dv_data(scene=args.shape,\n basedir=args.datadir,\n testskip=args.testskip)\n\n print('Loaded deepvoxels', images.shape, render_poses.shape, hwf, args.datadir)\n i_train, i_val, i_test = i_split\n\n hemi_R = np.mean(np.linalg.norm(poses[:,:3,-1], axis=-1))\n near = hemi_R-1.\n far = hemi_R+1.\n\n else:\n print('Unknown dataset type', args.dataset_type, 'exiting')\n return\n\n # Cast intrinsics to right types\n H, W, focal = hwf\n H, W = int(H), int(W)\n hwf = [H, W, focal]\n\n if K is None:\n K = np.array([\n [focal, 0, 0.5*W],\n [0, focal, 0.5*H],\n [0, 0, 1]\n ])\n\n # if args.render_test:\n # render_poses = np.array(poses[i_test])\n\n # Create log dir and copy the config file\n basedir = args.basedir\n expname = args.expname\n os.makedirs(os.path.join(basedir, expname), exist_ok=True)\n f = os.path.join(basedir, expname, 'args.txt')\n with open(f, 'w') as file:\n for arg in sorted(vars(args)):\n attr = getattr(args, arg)\n file.write('{} = {}\\n'.format(arg, attr))\n if args.config is not None:\n f = os.path.join(basedir, expname, 'config.txt')\n with open(f, 'w') as file:\n file.write(open(args.config, 'r').read())\n\n # Create nerf model\n render_kwargs_train, render_kwargs_test, start, grad_vars, optimizer = create_nerf(rank, args)\n \n # make sure different processes sample different rays\n np.random.seed((rank + 1) * 777)\n # make sure different processes have different perturbations in depth samples\n torch.manual_seed((rank + 1) * 777)\n \n \n global_step = start\n\n bds_dict = {\n 'near' : near,\n 'far' : far,\n }\n render_kwargs_train.update(bds_dict)\n render_kwargs_test.update(bds_dict)\n\n # Move testing data to GPU\n render_poses = torch.Tensor(render_poses).cuda()\n\n # Short circuit if only rendering out from trained model\n if args.render_only:\n print('RENDER ONLY')\n with torch.no_grad():\n #TODO: when render only, fix render_test options\n if args.render_test:\n # render_test switches to test poses\n images = images[i_test]\n else:\n # Default is smoother render_poses path\n images = None\n\n testsavedir = os.path.join(basedir, expname, 'renderonly_{}_{:06d}'.format('test' if args.render_test else 'path', start))\n os.makedirs(testsavedir, exist_ok=True)\n print('test poses shape', render_poses.shape)\n\n rgbs, _ = render_path(render_poses, hwf, K, args.chunk, render_kwargs_test, gt_imgs=images, savedir=testsavedir, render_factor=args.render_factor)\n print('Done rendering', testsavedir)\n imageio.mimwrite(os.path.join(testsavedir, 'video.mp4'), to8b(rgbs), fps=30, quality=8)\n\n return\n\n # Prepare raybatch tensor if batching random rays\n N_rand = args.N_rand\n use_batching = not args.no_batching\n if use_batching:\n # For random ray batching\n print('get rays')\n rays = np.stack([get_rays_np(H, W, K, p) for p in poses[:,:3,:4]], 0) # [N, ro+rd, H, W, 3]\n print('done, concats')\n rays_rgb = np.concatenate([rays, images[:,None]], 1) # [N, ro+rd+rgb, H, W, 3]\n rays_rgb = np.transpose(rays_rgb, [0,2,3,1,4]) # [N, H, W, ro+rd+rgb, 3]\n rays_rgb = np.stack([rays_rgb[i] for i in i_train], 0) # train images only\n rays_rgb = np.reshape(rays_rgb, [-1,3,3]) # [(N-1)*H*W, ro+rd+rgb, 3]\n rays_rgb = rays_rgb.astype(np.float32)\n print('shuffle rays')\n np.random.shuffle(rays_rgb)\n\n print('done')\n i_batch = 0\n\n # Move training data to GPU\n if use_batching:\n images = torch.Tensor(images).cuda()\n poses = torch.Tensor(poses).cuda()\n if use_batching:\n rays_rgb = torch.Tensor(rays_rgb).cuda()\n\n\n N_iters = args.N_iters + 1\n print('Begin')\n print('TRAIN views are', i_train)\n print('TEST views are', i_test)\n print('VAL views are', i_val)\n\n # Summary writers\n # writer = SummaryWriter(os.path.join(basedir, 'summaries', expname))\n \n start = start + 1\n for i in trange(start, N_iters):\n time0 = time.time()\n\n # Sample random ray batch\n if use_batching:\n # Random over all images\n batch = rays_rgb[i_batch:i_batch+N_rand] # [B, 2+1, 3*?]\n batch = torch.transpose(batch, 0, 1)\n batch_rays, target_s = batch[:2], batch[2]\n\n i_batch += N_rand\n if i_batch >= rays_rgb.shape[0]:\n print(\"Shuffle data after an epoch!\")\n rand_idx = torch.randperm(rays_rgb.shape[0])\n rays_rgb = rays_rgb[rand_idx]\n i_batch = 0\n\n else:\n # Random from one image\n img_i = np.random.choice(i_train)\n target = images[img_i]\n target = torch.Tensor(target).cuda()\n pose = poses[img_i, :3,:4]\n\n if N_rand is not None:\n rays_o, rays_d = get_rays(H, W, K, torch.Tensor(pose)) # (H, W, 3), (H, W, 3)\n\n if i < args.precrop_iters:\n dH = int(H//2 * args.precrop_frac)\n dW = int(W//2 * args.precrop_frac)\n coords = torch.stack(\n torch.meshgrid(\n torch.linspace(H//2 - dH, H//2 + dH - 1, 2*dH), \n torch.linspace(W//2 - dW, W//2 + dW - 1, 2*dW)\n ), -1)\n if i == start:\n print(f\"[Config] Center cropping of size {2*dH} x {2*dW} is enabled until iter {args.precrop_iters}\") \n else:\n coords = torch.stack(torch.meshgrid(torch.linspace(0, H-1, H), torch.linspace(0, W-1, W)), -1) # (H, W, 2)\n\n coords = torch.reshape(coords, [-1,2]) # (H * W, 2)\n select_inds = np.random.choice(coords.shape[0], size=[N_rand], replace=False) # (N_rand,)\n select_coords = coords[select_inds].long() # (N_rand, 2)\n rays_o = rays_o[select_coords[:, 0], select_coords[:, 1]] # (N_rand, 3)\n rays_d = rays_d[select_coords[:, 0], select_coords[:, 1]] # (N_rand, 3)\n batch_rays = torch.stack([rays_o, rays_d], 0)\n target_s = target[select_coords[:, 0], select_coords[:, 1]] # (N_rand, 3)\n\n ##### Core optimization loop #####\n rgb, disp, acc, extras = render(H, W, K, chunk=args.chunk, rays=batch_rays,\n verbose=i < 10, retraw=True,\n **render_kwargs_train)\n\n optimizer.zero_grad()\n img_loss = img2mse(rgb, target_s)\n trans = extras['raw'][...,-1]\n loss = img_loss\n psnr = mse2psnr(img_loss)\n\n if 'rgb0' in extras:\n img_loss0 = img2mse(extras['rgb0'], target_s)\n loss = loss + img_loss0\n psnr0 = mse2psnr(img_loss0)\n\n loss.backward()\n optimizer.step()\n\n # NOTE: IMPORTANT!\n ### update learning rate ###\n decay_rate = 0.1\n decay_steps = args.lrate_decay * 1000\n new_lrate = args.lrate * (decay_rate ** (global_step / decay_steps))\n for param_group in optimizer.param_groups:\n param_group['lr'] = new_lrate\n ################################\n\n dt = time.time()-time0\n # print(f\"Step: {global_step}, Loss: {loss}, Time: {dt}\")\n ##### end #####\n\n # only for main process\n # Rest is logging\n if (rank == 0) and (i % args.i_weights == 0):\n path = os.path.join(basedir, expname, '{:06d}.tar'.format(i))\n torch.save({\n 'global_step': global_step,\n 'network_fn_state_dict': render_kwargs_train['network_fn'].state_dict(),\n 'network_fine_state_dict': render_kwargs_train['network_fine'].state_dict(),\n 'optimizer_state_dict': optimizer.state_dict(),\n }, path)\n print('Saved checkpoints at', path)\n\n if (rank == 0) and (i % args.i_testset == 0) and (i > 0):\n testsavedir = os.path.join(basedir, expname, 'testset_{:06d}'.format(i))\n\n os.makedirs(testsavedir + \"_rgb\", exist_ok=True)\n os.makedirs(testsavedir + \"_disp\", exist_ok=True)\n\n print('test poses shape', poses[i_test].shape)\n with torch.no_grad():\n render_path(torch.Tensor(poses[i_test]).cuda(), hwf, K, args.chunk, render_kwargs_test, gt_imgs=images[i_test], savedir=testsavedir)\n print('Saved test set')\n\n # only for main process\n if rank == 0 and i%args.i_video==0 and i > 0:\n print(\"Save as video...\")\n videosavedir = os.path.join(basedir, expname, 'videoset_{:06d}'.format(i))\n os.makedirs(videosavedir + \"_rgb\", exist_ok=True)\n os.makedirs(videosavedir + \"_disp\", exist_ok=True)\n with torch.no_grad():\n rgbs, disps = render_path(render_poses, hwf, K, args.chunk, render_kwargs_test, savedir=videosavedir)\n print('Done, saving', rgbs.shape, disps.shape)\n moviebase = os.path.join(basedir, expname, '{}_spiral_{:06d}_'.format(expname, i))\n imageio.mimwrite(moviebase + 'rgb.mp4', to8b(rgbs), fps=30, quality=8)\n imageio.mimwrite(moviebase + 'disp.mp4', to8b(disps / np.max(disps)), fps=30, quality=8)\n \n # if args.use_viewdirs:\n # render_kwargs_test['c2w_staticcam'] = render_poses[0][:3,:4]\n # with torch.no_grad():\n # rgbs_still, _ = render_path(render_poses, hwf, args.chunk, render_kwargs_test)\n # render_kwargs_test['c2w_staticcam'] = None\n # imageio.mimwrite(moviebase + 'rgb_still.mp4', to8b(rgbs_still), fps=30, quality=8)\n\n\n if rank == 0 and i % args.i_img == 0 and i > 0:\n print(\"\\nSave images at wandb...\")\n with torch.no_grad():\n rgbs, disps = render_wandb(torch.Tensor(poses[i_test]).cuda(), hwf, K, args.chunk, render_kwargs_test, gt_imgs=images[i_test])\n _rgbs = [rgbs[i] for i in range(len(rgbs))]\n _disps = [disps[i] for i in range(len(disps))]\n wandb.log({\"rgb\": [wandb.Image(img) for img in _rgbs]})\n wandb.log({\"disp\": [wandb.Image(disp) for disp in _disps]})\n\n #FIXME: check there is deadlock\n # If there is (rank == 0), the process 0 will not dead\n if i % args.i_print == 0:\n tqdm.write(f\"[TRAIN] Iter: {i} Loss: {loss.item()} PSNR: {psnr.item()}\")\n\n global_step += 1\n\n if rank == 0:\n wandb.log({'Loss': loss.item(), 'PSNR': psnr.item()})\n\n wandb.finish()\n cleanup()\n\n\nif __name__=='__main__':\n # torch.set_default_tensor_type('torch.cuda.FloatTensor')\n parser = config_parser()\n args = parser.parse_args()\n\n # train()\n main(args)"
] | [
[
"torch.set_default_tensor_type",
"torch.transpose",
"torch.multiprocessing.spawn",
"torch.randperm",
"numpy.concatenate",
"numpy.max",
"torch.no_grad",
"torch.distributed.init_process_group",
"numpy.reshape",
"numpy.arange",
"torch.reshape",
"numpy.ndarray.min",
"numpy.stack",
"torch.linspace",
"numpy.random.choice",
"numpy.transpose",
"torch.distributed.destroy_process_group",
"torch.stack",
"numpy.array",
"torch.cuda.set_device",
"numpy.random.seed",
"torch.Tensor",
"torch.manual_seed",
"numpy.linalg.norm",
"numpy.random.shuffle",
"numpy.ndarray.max"
]
] |
aiLibrary/lanenet-lane-detection | [
"6abedbe1ba6da2e6f6e3935c6d26bd79c55a0d45"
] | [
"lanenet_model/lanenet_instance_segmentation.py"
] | [
"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n# @Time : 18-5-11 上午11:35\n# @Author : Luo Yao\n# @Site : http://icode.baidu.com/repos/baidu/personal-code/Luoyao\n# @File : lanenet_instance_segmentation.py\n# @IDE: PyCharm Community Edition\n\"\"\"\n实现LaneNet中的实例图像分割模型\n\"\"\"\nimport tensorflow as tf\n\nfrom encoder_decoder_model import vgg_encoder\nfrom encoder_decoder_model import fcn_decoder\nfrom encoder_decoder_model import dense_encoder\nfrom encoder_decoder_model import cnn_basenet\nfrom lanenet_model import lanenet_discriminative_loss\n\n\nclass LaneNetInstanceSeg(cnn_basenet.CNNBaseModel):\n \"\"\"\n 实现语义分割模型\n \"\"\"\n def __init__(self, phase, net_flag='vgg'):\n \"\"\"\n\n \"\"\"\n super(LaneNetInstanceSeg, self).__init__()\n self._net_flag = net_flag\n self._phase = phase\n if self._net_flag == 'vgg':\n self._encoder = vgg_encoder.VGG16Encoder(phase=phase)\n elif self._net_flag == 'dense':\n self._encoder = dense_encoder.DenseEncoder(l=20, growthrate=8,\n with_bc=True,\n phase=self._phase,\n n=5)\n self._decoder = fcn_decoder.FCNDecoder()\n return\n\n def __str__(self):\n \"\"\"\n\n :return:\n \"\"\"\n info = 'Semantic Segmentation use {:s} as basenet to encode'.format(self._net_flag)\n return info\n\n def build_model(self, input_tensor, name):\n \"\"\"\n 前向传播过程\n :param input_tensor:\n :param name:\n :return:\n \"\"\"\n with tf.variable_scope(name):\n # first encode\n encode_ret = self._encoder.encode(input_tensor=input_tensor,\n name='encode')\n\n # second decode\n if self._net_flag.lower() == 'vgg':\n decode_ret = self._decoder.decode(input_tensor_dict=encode_ret,\n name='decode',\n decode_layer_list=['pool5',\n 'pool4',\n 'pool3'])\n return decode_ret\n elif self._net_flag.lower() == 'dense':\n decode_ret = self._decoder.decode(input_tensor_dict=encode_ret,\n name='decode',\n decode_layer_list=['Dense_Block_5',\n 'Dense_Block_4',\n 'Dense_Block_3'])\n return decode_ret\n\n def compute_loss(self, input_tensor, label, name):\n \"\"\"\n 计算损失函数\n :param input_tensor:\n :param label: 1D label image with different n lane with pix value from [1] to [n],\n background pix value is [0]\n :param name:\n :return:\n \"\"\"\n with tf.variable_scope(name):\n # 前向传播获取logits\n inference_ret = self.build_model(input_tensor=input_tensor, name='inference')\n # 计算损失\n decode_deconv = inference_ret['deconv']\n # 像素嵌入\n pix_embedding = self.conv2d(inputdata=decode_deconv, out_channel=3, kernel_size=1,\n use_bias=False, name='pix_embedding_conv')\n pix_embedding = self.relu(inputdata=pix_embedding, name='pix_embedding_relu')\n # 计算discriminative loss\n image_shape = (pix_embedding.get_shape().as_list()[1], pix_embedding.get_shape().as_list()[2])\n disc_loss, l_var, l_dist, l_reg = \\\n lanenet_discriminative_loss.discriminative_loss(\n pix_embedding, label, 3, image_shape, 0.5, 1.5, 1.0, 1.0, 0.001)\n\n ret = {\n 'total_loss': disc_loss,\n 'loss_var': l_var,\n 'loss_dist': l_dist,\n 'loss_reg': l_reg,\n 'binary_seg_logits': decode_deconv,\n 'embedding': pix_embedding\n }\n\n return ret\n\n\nif __name__ == '__main__':\n model = LaneNetInstanceSeg(tf.constant('train', dtype=tf.string))\n input_tensor = tf.placeholder(dtype=tf.float32, shape=[1, 256, 512, 3], name='input')\n label = tf.placeholder(dtype=tf.float32, shape=[1, 256, 512, 1], name='label')\n loss = model.compute_loss(input_tensor=input_tensor, label=label, name='loss')\n print(loss['total_loss'].get_shape().as_list())\n"
] | [
[
"tensorflow.variable_scope",
"tensorflow.constant",
"tensorflow.placeholder"
]
] |
xxchenxx/esm | [
"51e08c09a1687941515d7928181613d594c10981"
] | [
"finetune_temp.py"
] | [
"#!/usr/bin/env python3 -u\n# Copyright (c) Facebook, Inc. and its affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nimport argparse\nimport pathlib\n\nimport torch\n\nfrom esm import Alphabet, FastaBatchedDataset, ProteinBertModel, pretrained, CSVBatchedDataset, creating_ten_folds\n\n\ndef create_parser():\n parser = argparse.ArgumentParser(\n description=\"Extract per-token representations and model outputs for sequences in a FASTA file\" # noqa\n )\n\n parser.add_argument(\n \"model_location\",\n type=str,\n help=\"PyTorch model file OR name of pretrained model to download (see README for models)\",\n )\n parser.add_argument(\n \"fasta_file\",\n type=pathlib.Path,\n help=\"FASTA file on which to extract representations\",\n )\n parser.add_argument(\n \"output_dir\",\n type=pathlib.Path,\n help=\"output directory for extracted representations\",\n )\n\n parser.add_argument(\"--toks_per_batch\", type=int, default=4096, help=\"maximum batch size\")\n parser.add_argument(\n \"--repr_layers\",\n type=int,\n default=[-1],\n nargs=\"+\",\n help=\"layers indices from which to extract representations (0 to num_layers, inclusive)\",\n )\n parser.add_argument(\n \"--include\",\n type=str,\n nargs=\"+\",\n choices=[\"mean\", \"per_tok\", \"bos\", \"contacts\"],\n help=\"specify which representations to return\",\n required=True,\n )\n parser.add_argument(\n \"--truncate\",\n action=\"store_true\",\n help=\"Truncate sequences longer than 1024 to match the training setup\",\n )\n\n parser.add_argument(\"--nogpu\", action=\"store_true\", help=\"Do not use GPU even if available\")\n return parser\n\n\ndef main(args):\n model, alphabet = pretrained.load_model_and_alphabet(args.model_location)\n model.eval()\n if torch.cuda.is_available() and not args.nogpu:\n model = model.cuda()\n print(\"Transferred model to GPU\")\n\n dataset = CSVBatchedDataset.from_file(\"combined_features.csv\")\n train_sets, test_sets = creating_ten_folds(dataset)\n train_batches = train_sets[9].get_batch_indices(args.toks_per_batch, extra_toks_per_seq=1)\n train_data_loader = torch.utils.data.DataLoader(\n train_sets[9], collate_fn=alphabet.get_batch_converter(), batch_sampler=train_batches\n )\n #print(f\"Read {args.fasta_file} with {len(train_sets[0])} sequences\")\n\n test_batches = test_sets[0].get_batch_indices(args.toks_per_batch, extra_toks_per_seq=1)\n\n test_data_loader = torch.utils.data.DataLoader(\n test_sets[0], collate_fn=alphabet.get_batch_converter(), batch_sampler=test_batches\n )\n\n args.output_dir.mkdir(parents=True, exist_ok=True)\n return_contacts = \"contacts\" in args.include\n\n assert all(-(model.num_layers + 1) <= i <= model.num_layers for i in args.repr_layers)\n repr_layers = [(i + model.num_layers + 1) % (model.num_layers + 1) for i in args.repr_layers]\n\n optimizer = torch.optim.AdamW(model.parameters(), lr=1e-5)\n for epoch in range(1):\n model.train()\n for batch_idx, (labels, strs, targets, toks) in enumerate(train_data_loader):\n print(\n f\"Processing {batch_idx + 1} of {len(train_batches)} batches ({toks.size(0)} sequences)\"\n )\n if torch.cuda.is_available() and not args.nogpu:\n toks = toks.to(device=\"cuda\", non_blocking=True)\n #print(toks)\n # The model is trained on truncated sequences and passing longer ones in at\n # infernce will cause an error. See https://github.com/facebookresearch/esm/issues/21\n if args.truncate:\n toks = toks[:, :1022]\n\n out = model(toks, repr_layers=repr_layers, return_contacts=return_contacts, return_temp=True)\n\n temp = out['temp'] * 10\n targets = torch.tensor(targets).cuda().float()\n loss = (torch.nn.functional.mse_loss(temp[:,0].view(-1), targets.view(-1)))\n loss.backward()\n optimizer.step()\n optimizer.zero_grad()\n print(loss.item())\n model.eval()\n with torch.no_grad():\n outputs = []\n tars = []\n for batch_idx, (labels, strs, targets, toks) in enumerate(test_data_loader):\n print(\n f\"Processing {batch_idx + 1} of {len(test_batches)} batches ({toks.size(0)} sequences)\"\n )\n if torch.cuda.is_available() and not args.nogpu:\n toks = toks.to(device=\"cuda\", non_blocking=True)\n # The model is trained on truncated sequences and passing longer ones in at\n # infernce will cause an error. See https://github.com/facebookresearch/esm/issues/21\n if args.truncate:\n toks = toks[:, :1022]\n out = model(toks, repr_layers=repr_layers, return_contacts=return_contacts, return_temp=True)\n temp = out['temp'] * 10\n targets = torch.tensor(targets).cuda().float()\n outputs.append(temp[:,0].view(-1).cpu().numpy())\n tars.append(targets.view(-1).cpu().numpy())\n print(outputs)\n print(tars)\n import numpy as np\n outputs = np.concatenate(outputs, 0)\n tars = np.concatenate(tars, 0)\n print(np.corrcoef(outputs, tars))\n torch.save(model.state_dict(), \"supervised-finetuned.pt\")\n\n\nif __name__ == \"__main__\":\n parser = create_parser()\n args = parser.parse_args()\n main(args)\n"
] | [
[
"torch.tensor",
"numpy.concatenate",
"torch.no_grad",
"torch.cuda.is_available",
"numpy.corrcoef"
]
] |
amey-joshi/physics | [
"66ae9bf4a363bd32b09df22a049e281953adb39b"
] | [
"open-systems/simulation-2.py"
] | [
"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nNumerical simulation of the variance matrix without using the simplification\nintroduced by Simon, Mukunda and others. The transformation matrices are\nderived from canonical commutation relations.\n\nCreated on Sun Dec 20 18:01:54 2020\n\n@author: ajoshi\n\"\"\"\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nomega_1 = 1\nomega_2 = 1\ntau = .3\nT_1 = 9\nT_2 = 1\nomega = 1\nlambda_ = 0.1 # lambda is a Python keyword!!\n\ndef get_S(phi, alpha, beta):\n S1 = np.matrix([[np.cos(phi), np.sin(phi), 0, 0],\n [-np.sin(phi), np.cos(phi), 0, 0],\n [0, 0, np.cos(phi), np.sin(phi)],\n [0, 0, -np.sin(phi), np.cos(phi)]])\n\n S2 = np.matrix([[np.cos(alpha), 0, 0, np.sin(alpha)],\n [0, np.cos(alpha), -np.sin(alpha), 0],\n [0, np.sin(alpha), np.cos(alpha), 0],\n [-np.sin(alpha), 0, 0, np.cos(alpha)]])\n\n S3 = np.matrix([[np.cos(beta), -np.sin(beta), 0, 0],\n [-np.sin(beta), np.cos(beta), 0, 0],\n [0, 0, np.cos(beta), -np.sin(beta)],\n [0, 0, -np.sin(beta), np.cos(beta)]])\n\n S = S1 @ S2 @ S3\n\n return S\n\ndef get_beta(omega, T):\n # return sc.hbar * omega/(2 * sc.Boltzmann * T)\n return omega/(2 * T)\n\ndef get_v(beta):\n return 1/(2 * np.tanh(beta))\n\ndef build_V(v1, v2):\n V = np.matrix([[v1, 0, 0, 0],\n [0, v1, 0, 0],\n [0, 0, v2, 0],\n [0, 0, 0, v2]])\n return V\n\ndef get_temperature(u, omega):\n x1 = np.arctanh(np.reciprocal(2 * u))\n # T = sc.hbar * omega/(2 * sc.Boltzmann) * np.reciprocal(x1)\n T = omega/2 * np.reciprocal(x1)\n\n return T\n\ndef run_simulation(max_iter, tau, phi, alpha, beta):\n beta_1 = get_beta(omega_1, T_1)\n beta_2 = get_beta(omega_2, T_2)\n v1 = get_v(beta_1)\n v2 = get_v(beta_2)\n u00 = np.zeros(max_iter)\n u22 = np.zeros(max_iter)\n\n V = build_V(v1, v2)\n u00[0] = V[0, 0]\n u22[0] = V[2, 2]\n\n for n in range(1, max_iter):\n S = get_S(phi, alpha, beta)\n U = S @ V @ np.transpose(S)\n u00[n] = U[0, 0]\n u22[n] = U[2, 2]\n # If both systems are considered to evolve. They do in Chimonidou-Sudarshan\n # scheme. They don't in the original Jayseetha Rau's scheme.\n V = build_V(u00[n], u22[n])\n\n return (u00, u22)\n\ndef plot_results(omega_1, omega_2, lambda_, T_1, T_2, u00, u22, max_iter, tau, rname):\n params = r'$\\omega_1=$ {:0.1f}, $\\omega_2=$ {:0.1f}, $\\lambda=$ {:0.1f}, $\\tau=$ {:0.1f}'. \\\n format(omega_1, omega_2, lambda_, tau)\n T1 = get_temperature(u00, omega_1)\n T2 = get_temperature(u22, omega_2)\n t = np.zeros(max_iter)\n for n in range(1, max_iter):\n t[n] = tau * n\n\n plt.plot(t, T1, color = 'black', label = rf'$T_1={T_1}$')\n plt.plot(t, T2, color = 'red', label = rf'$T_2={T_2}$')\n plt.xlim(0, max(t))\n plt.legend()\n plt.ylabel(r'$kT/\\hslash\\omega$')\n plt.xlabel(r'$t$')\n plt.title(params)\n plt.show()\n\n # fname = f'fig_{rname}.png'\n # plt.savefig(fname)\n # plt.close()\n\ndef main():\n max_iter = 250\n alpha = lambda_ * omega\n beta = (omega_1 - omega_2)/2\n phi = tau * (omega_1 + omega_2)/2\n\n u00, u22 = run_simulation(max_iter, tau, phi, alpha, beta)\n rname = 'x1'\n plot_results(omega_1, omega_2, lambda_, T_1, T_2, u00, u22, max_iter, tau, rname)\n\nif __name__ == '__main__':\n main()\n"
] | [
[
"numpy.matrix",
"matplotlib.pyplot.legend",
"matplotlib.pyplot.title",
"numpy.cos",
"numpy.sin",
"matplotlib.pyplot.plot",
"numpy.tanh",
"numpy.transpose",
"matplotlib.pyplot.xlabel",
"numpy.reciprocal",
"matplotlib.pyplot.show",
"numpy.zeros",
"matplotlib.pyplot.ylabel"
]
] |
tmsdy/amazon_captcha_break | [
"d9477aaf44ee5a6605b39cb98c1d55f67149ba34"
] | [
"cnn_captcha_break.py"
] | [
"# Builds the cnn network for running the network forward to make predictions.\n# Author : CheihChiu\n# Date : 2017-06-06\n\nimport math\n\nimport tensorflow as tf\n\nimport numpy as np\n\n# The capcha dataset has 18 classes, representing the charaters in ['a', 'b', 'c', 'e', 'f', 'g', 'h', 'j', 'k','l', 'm', 'n', 'p', 'r', 't', 'u', 'x', 'y']\nNUM_CLASSES = 18\n\nW_ALPHA = 0.01\nB_ALPHA = 0.1\nKEEP_PROB = 1.0\n\nCONV_STRIDES = [1, 1, 1, 1]\nPOOLING_STRIDES = [1, 2, 2, 1]\nPOOLING_K_SIZE = [1, 2, 2, 1]\nPADDING = 'SAME'\nOUT_CHANNELS = [128, 256, 256, 512, 512]\nFULL_CONNECT_CHANNELS = 1024\nFILTER_WIDTH = 3\n\n\ndef logits(images, width, height):\n x = tf.reshape(images, shape=[-1, height, width, 1])\n\n # conv layer\n in_channel = 1\n input = x\n for out_channel in OUT_CHANNELS:\n w = tf.Variable(W_ALPHA * tf.random_normal([FILTER_WIDTH, FILTER_WIDTH, in_channel, out_channel]))\n b = tf.Variable(B_ALPHA * tf.random_normal([out_channel]))\n conv = tf.nn.relu(tf.nn.bias_add(tf.nn.conv2d(input, w, strides=CONV_STRIDES, padding=PADDING), b))\n conv = tf.nn.max_pool(conv, ksize=POOLING_K_SIZE, strides=POOLING_STRIDES, padding='SAME')\n conv = tf.nn.dropout(conv, KEEP_PROB)\n input = conv\n # conv = tf.nn.relu(tf.nn.bias_add(tf.nn.conv2d(input, w, strides=CONV_STRIDES, padding=PADDING), b))\n # pool = tf.nn.max_pool(conv, ksize=POOLING_K_SIZE, strides=POOLING_STRIDES, padding='SAME')\n # dropout = tf.nn.dropout(pool, KEEP_PROB)\n # input = dropout\n in_channel = out_channel\n\n # Fully connected layer\n w_f = tf.Variable(W_ALPHA * tf.random_normal([FILTER_WIDTH * (FILTER_WIDTH - 1) * OUT_CHANNELS[len(OUT_CHANNELS) - 1]\n ,FULL_CONNECT_CHANNELS]))\n b_f = tf.Variable(B_ALPHA * tf.random_normal([FULL_CONNECT_CHANNELS]))\n dense = tf.reshape(input, [-1, w_f.get_shape().as_list()[0]])\n dense = tf.nn.relu(tf.add(tf.matmul(dense, w_f), b_f))\n dense = tf.nn.dropout(dense, KEEP_PROB)\n\n w_out = tf.Variable(W_ALPHA * tf.random_normal([FULL_CONNECT_CHANNELS, NUM_CLASSES]))\n b_out = tf.Variable(B_ALPHA * tf.random_normal([NUM_CLASSES]))\n logits = tf.add(tf.matmul(dense, w_out), b_out)\n return logits"
] | [
[
"tensorflow.matmul",
"tensorflow.nn.max_pool",
"tensorflow.reshape",
"tensorflow.nn.dropout",
"tensorflow.nn.conv2d",
"tensorflow.random_normal"
]
] |
mmendiet/next-prediction | [
"bf5ee6cbc640933460a11a45a5df327f3d6f98a7"
] | [
"code/models.py"
] | [
"# Copyright 2019 Google Inc. 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 __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\n\"\"\"Model graph definitions and other functions for training and testing.\"\"\"\n\nimport math\nimport operator\nimport os\nimport random\nimport re\nimport numpy as np\n#import tensorflow as tf\n\nimport tensorflow.compat.v1 as tf\ntf.disable_v2_behavior()\n\n\ndef get_model(config, gpuid):\n \"\"\"Make model instance and pin to one gpu.\n\n Args:\n config: arguments.\n gpuid: gpu id to use\n Returns:\n Model instance.\n \"\"\"\n with tf.name_scope(config.modelname), tf.device('/gpu:%d' % gpuid):\n model = Model(config, '%s' % config.modelname)\n return model\n\n\nclass Model(object):\n \"\"\"Model graph definitions.\n \"\"\"\n\n def __init__(self, config, scope):\n self.scope = scope\n self.config = config\n\n self.global_step = tf.get_variable('global_step', shape=[],\n dtype='int32',\n initializer=tf.constant_initializer(0),\n trainable=False)\n\n # get all the dimension here\n # Tensor dimensions, so pylint: disable=g-bad-name\n N = self.N = config.batch_size\n\n KP = self.KP = config.kp_size\n\n SH = self.SH = config.scene_h\n SW = self.SW = config.scene_w\n SC = self.SC = config.scene_class\n\n K = self.K = config.max_other\n\n self.P = P = 2 # traj coordinate dimension\n\n # all the inputs\n\n # the trajactory sequence,\n # in training, it is the obs+pred combined,\n # in testing, only obs is fed and the rest is zeros\n # [N,T1,2] # T1 is the obs_len\n # mask is used for variable length input extension\n self.traj_obs_gt = tf.placeholder(\n 'float', [N, None, P], name='traj_obs_gt')\n self.traj_obs_gt_mask = tf.placeholder(\n 'bool', [N, None], name='traj_obs_gt_mask')\n\n # [N,T2,2]\n self.traj_pred_gt = tf.placeholder(\n 'float', [N, None, P], name='traj_pred_gt')\n self.traj_pred_gt_mask = tf.placeholder(\n 'bool', [N, None], name='traj_pred_gt_mask')\n\n self.obs_kp = tf.placeholder('float', [N, None, KP, 2], name='obs_kp')\n\n # used for drop out switch\n self.is_train = tf.placeholder('bool', [], name='is_train')\n\n # scene semantic segmentation features\n # the index to the feature\n self.obs_scene = tf.placeholder('int32', [N, None], name='obs_scene')\n self.obs_scene_mask = tf.placeholder(\n 'bool', [N, None], name='obs_scene_mask')\n # the actual feature\n self.scene_feat = tf.placeholder(\n 'float32', [None, SH, SW, SC], name='scene_feat')\n\n # [N, obs_len, 5, 9, 2048]\n self.obs_person_features = tf.placeholder('float32', [\n N, None, config.person_h, config.person_w,\n config.person_feat_dim], name='obs_boxes_features')\n\n # other box\n # the box input is the relative coordinates\n # [N,obs_len, K, 4]\n self.obs_other_boxes = tf.placeholder(\n 'float32', [N, None, K, 4], name='other_boxes')\n # [N,obs_len, K, num_class]\n self.obs_other_boxes_class = tf.placeholder(\n 'float32', [N, None, K, config.num_box_class], name='other_boxes_class')\n # [N,obs_len, K]\n self.obs_other_boxes_mask = tf.placeholder(\n 'bool', [N, None, K], name='other_boxes_mask')\n\n # grid loss\n self.grid_pred_labels = []\n self.grid_pred_targets = []\n self.grid_obs_labels = []\n self.grid_obs_targets = []\n for _ in config.scene_grids:\n # [N, seq_len]\n # currently only the destination\n self.grid_pred_labels.append(\n tf.placeholder('int32', [N])) # grid class\n self.grid_pred_targets.append(tf.placeholder('float32', [N, 2]))\n\n self.grid_obs_labels.append(\n tf.placeholder('int32', [N, None])) # grid class\n self.grid_obs_targets.append(\n tf.placeholder('float32', [N, None, 2]))\n\n # traj class loss\n self.traj_class_gt = tf.placeholder('int64', [N], name='traj_class')\n\n self.future_act_label = tf.placeholder(\n 'uint8', [N, config.num_act], name='future_act')\n\n self.loss = None\n self.build_forward()\n self.build_loss()\n\n def build_forward(self):\n \"\"\"Build the forward model graph.\"\"\"\n config = self.config\n # Tensor dimensions, so pylint: disable=g-bad-name\n N = self.N\n KP = self.KP\n\n # add dropout\n keep_prob = tf.cond(self.is_train,\n lambda: tf.constant(config.keep_prob),\n lambda: tf.constant(1.0))\n\n # ------------------------- encoder ------------------------\n enc_cell_traj = tf.nn.rnn_cell.LSTMCell(\n config.enc_hidden_size, state_is_tuple=True, name='enc_traj')\n enc_cell_traj = tf.nn.rnn_cell.DropoutWrapper(enc_cell_traj, keep_prob)\n\n # scene encoder\n enc_cell_personscene = tf.nn.rnn_cell.LSTMCell(\n config.enc_hidden_size, state_is_tuple=True, name='enc_scene')\n enc_cell_personscene = tf.nn.rnn_cell.DropoutWrapper(\n enc_cell_personscene, keep_prob)\n\n # person pose encoder\n if config.add_kp:\n enc_cell_kp = tf.nn.rnn_cell.LSTMCell(\n config.enc_hidden_size, state_is_tuple=True, name='enc_kp')\n enc_cell_kp = tf.nn.rnn_cell.DropoutWrapper(enc_cell_kp, keep_prob)\n\n # person appearance encoder\n enc_cell_person = tf.nn.rnn_cell.LSTMCell(\n config.enc_hidden_size, state_is_tuple=True, name='enc_person')\n # enc_cell_person = tf.contrib.rnn.ConvLSTMCell(conv_ndims=2,\n # input_shape=[person_h, person_w, person_feat_dim],\n # output_channels=config.enc_hidden_size, kernel_shape=[3,3])\n enc_cell_person = tf.nn.rnn_cell.DropoutWrapper(\n enc_cell_person, keep_prob)\n\n # other box encoder\n enc_cell_other = tf.nn.rnn_cell.LSTMCell(\n config.enc_hidden_size, state_is_tuple=True, name='enc_other')\n enc_cell_other = tf.nn.rnn_cell.DropoutWrapper(\n enc_cell_other, keep_prob)\n\n # activity location/grid loss\n enc_cell_gridclass = []\n for i, _ in enumerate(config.scene_grids):\n enc_cell_gridclass_this = tf.nn.rnn_cell.LSTMCell(\n config.enc_hidden_size, state_is_tuple=True,\n name='enc_gridclass_%s' % i)\n enc_cell_gridclass_this = tf.nn.rnn_cell.DropoutWrapper(\n enc_cell_gridclass_this, keep_prob)\n enc_cell_gridclass.append(enc_cell_gridclass_this)\n\n # ------------------------ decoder\n\n if config.multi_decoder:\n dec_cell_traj = [tf.nn.rnn_cell.LSTMCell(\n config.dec_hidden_size, state_is_tuple=True, name='dec_traj_%s' % i)\n for i in xrange(len(config.traj_cats))]\n dec_cell_traj = [tf.nn.rnn_cell.DropoutWrapper(\n one, keep_prob) for one in dec_cell_traj]\n else:\n dec_cell_traj = tf.nn.rnn_cell.LSTMCell(\n config.dec_hidden_size, state_is_tuple=True, name='dec_traj')\n dec_cell_traj = tf.nn.rnn_cell.DropoutWrapper(\n dec_cell_traj, keep_prob)\n\n # ----------------------------------------------------------\n # the obs part is the same for training and testing\n # obs_out is only used in training\n\n # encoder, decoder\n # top_scope is used for variable inside\n # encode and decode if want to share variable across\n with tf.variable_scope('person_pred') as top_scope:\n\n # [N,T1,h_dim]\n # xy encoder\n obs_length = tf.reduce_sum(\n tf.cast(self.traj_obs_gt_mask, 'int32'), 1)\n\n traj_xy_emb_enc = linear(self.traj_obs_gt,\n output_size=config.emb_size,\n activation=config.activation_func,\n add_bias=True,\n scope='enc_xy_emb')\n traj_obs_enc_h, traj_obs_enc_last_state = tf.nn.dynamic_rnn(\n enc_cell_traj, traj_xy_emb_enc, sequence_length=obs_length,\n dtype='float', scope='encoder_traj')\n\n enc_h_list = [traj_obs_enc_h]\n\n enc_last_state_list = [traj_obs_enc_last_state]\n\n # grid class and grid regression encoder\n # multi-scale\n grid_obs_enc_h = []\n grid_obs_enc_last_state = []\n\n for i, (h, w) in enumerate(config.scene_grids):\n # [N, T] -> [N, T, h*w]\n obs_gridclass_onehot = tf.one_hot(self.grid_obs_labels[i], h*w)\n obs_gridclass_encode_h, obs_gridclass_encode_last_state = \\\n tf.nn.dynamic_rnn(enc_cell_gridclass[i], obs_gridclass_onehot,\n sequence_length=obs_length, dtype='float',\n scope='encoder_gridclass_%s' % i)\n grid_obs_enc_h.append(obs_gridclass_encode_h)\n grid_obs_enc_last_state.append(obs_gridclass_encode_last_state)\n\n enc_h_list.extend(grid_obs_enc_h)\n\n enc_last_state_list.extend(grid_obs_enc_last_state)\n\n # gather all visual observation encoder\n # ------------------------------------------------------------\n with tf.variable_scope('scene'):\n # [N,obs_len, SH, SW, SC]\n obs_scene = tf.nn.embedding_lookup(\n self.scene_feat, self.obs_scene)\n obs_scene = tf.reduce_mean(obs_scene, axis=1) # [N,SH,SW,SC]\n\n with tf.variable_scope('scene_conv'):\n # [N, SH, SW, dim]\n # resnet structure?\n conv_dim = config.scene_conv_dim\n\n scene_conv1 = obs_scene\n\n # [N, SH/2, SW/2, dim]\n scene_conv2 = conv2d(scene_conv1, out_channel=conv_dim,\n kernel=config.scene_conv_kernel,\n stride=2, activation=config.activation_func,\n add_bias=True, scope='conv2')\n # [N, SH/4, SW/4, dim]\n scene_conv3 = conv2d(scene_conv2, out_channel=conv_dim,\n kernel=config.scene_conv_kernel,\n stride=2, activation=config.activation_func,\n add_bias=True, scope='conv3')\n self.scene_convs = [scene_conv2, scene_conv3]\n\n # pool the scene features for each trajectory, for different scale\n # currently only used single scale conv\n pool_scale_idx = config.pool_scale_idx\n\n scene_h, scene_w = config.scene_grids[pool_scale_idx]\n\n # [N, num_grid_class, conv_dim]\n scene_conv_full = tf.reshape(\n self.scene_convs[pool_scale_idx], (N, scene_h*scene_w, conv_dim))\n\n # [N, seq_len]\n obs_grid = self.grid_obs_labels[pool_scale_idx]\n\n obs_grid = tf.reshape(obs_grid, [-1]) # [N*seq_len]\n # [N*seq_len, 2]\n indices = tf.stack(\n [tf.range(tf.shape(obs_grid)[0]), tf.to_int32(obs_grid)], axis=-1)\n\n # [N, seq_len, num_grid_class, conv_dim]\n scene_conv_full_tile = tf.tile(tf.expand_dims(\n scene_conv_full, 1), [1, config.obs_len, 1, 1])\n # [N*seq_len, num_grid_class, conv_dim]\n scene_conv_full_tile = tf.reshape(\n scene_conv_full_tile, (-1, scene_h*scene_w, conv_dim))\n\n # [N*seq_len, h*w, feat_dim] + [N*seq_len,2] -> # [N*seq_len, feat_dim]\n obs_personscene = tf.gather_nd(scene_conv_full_tile, indices)\n obs_personscene = tf.reshape(\n obs_personscene, (N, config.obs_len, conv_dim))\n\n # obs_personscene [N, seq_len, conv_dim]\n personscene_obs_enc_h, personscene_obs_enc_last_state = \\\n tf.nn.dynamic_rnn(enc_cell_personscene, obs_personscene,\n sequence_length=obs_length, dtype='float',\n scope='encoder_personscene')\n\n enc_h_list.append(personscene_obs_enc_h)\n enc_last_state_list.append(personscene_obs_enc_last_state)\n\n # person pose\n if config.add_kp:\n obs_kp = tf.reshape(self.obs_kp, [N, -1, KP*2])\n obs_kp = linear(obs_kp, output_size=config.emb_size, add_bias=True,\n activation=config.activation_func, scope='kp_emb')\n\n kp_obs_enc_h, kp_obs_enc_last_state = tf.nn.dynamic_rnn(\n enc_cell_kp, obs_kp, sequence_length=obs_length, dtype='float',\n scope='encoder_kp')\n\n enc_h_list.append(kp_obs_enc_h)\n enc_last_state_list.append(kp_obs_enc_last_state)\n\n # person appearance\n # average and then normal lstm\n obs_person_features = tf.reduce_mean(\n self.obs_person_features, axis=[2, 3])\n # [N,T,hdim]\n person_obs_enc_h, person_obs_enc_last_state = tf.nn.dynamic_rnn(\n enc_cell_person, obs_person_features, sequence_length=obs_length,\n dtype='float', scope='encoder_person')\n enc_h_list.append(person_obs_enc_h)\n enc_last_state_list.append(person_obs_enc_last_state)\n\n # extract features from other boxes\n # obs_other_boxes [N, obs_len, K, 4]\n # obs_other_boxes_class [N, obs_len, K, num_class]\n # obs_other_boxes_mask [N, obs_len, K]\n\n with tf.variable_scope('other_box'):\n # [N, obs_len, K, box_emb_size]\n obs_other_boxes_geo_features = linear(\n self.obs_other_boxes, add_bias=True,\n activation=config.activation_func, output_size=config.box_emb_size,\n scope='other_box_geo_emb')\n obs_other_boxes_class_features = linear(\n self.obs_other_boxes_class, add_bias=True,\n activation=config.activation_func, output_size=config.box_emb_size,\n scope='other_box_class_emb')\n\n obs_other_boxes_features = tf.concat(\n [obs_other_boxes_geo_features, obs_other_boxes_class_features],\n axis=3)\n\n # cosine simi\n obs_other_boxes_geo_features = tf.nn.l2_normalize(\n obs_other_boxes_geo_features, -1)\n obs_other_boxes_class_features = tf.nn.l2_normalize(\n obs_other_boxes_class_features, -1)\n # [N, T,K]\n other_attention = tf.reduce_sum(tf.multiply(\n obs_other_boxes_geo_features, obs_other_boxes_class_features), 3)\n\n other_attention = exp_mask(\n other_attention, self.obs_other_boxes_mask)\n\n other_attention = tf.nn.softmax(other_attention)\n\n # [N, obs_len, K, 1] * [N, obs_len, K, feat_dim]\n # -> [N, obs_len, feat_dim]\n other_box_features_attended = tf.reduce_sum(tf.expand_dims(\n other_attention, -1)*obs_other_boxes_features, axis=2)\n\n other_obs_enc_h, other_obs_enc_last_state = tf.nn.dynamic_rnn(\n enc_cell_other, other_box_features_attended,\n sequence_length=obs_length, dtype='float', scope='encoder_other')\n\n enc_h_list.append(other_obs_enc_h)\n enc_last_state_list.append(other_obs_enc_last_state)\n\n # pack all observed hidden states\n obs_enc_h = tf.stack(enc_h_list, axis=1)\n # .h is [N,h_dim*k]\n obs_enc_last_state = concat_states(enc_last_state_list, axis=1)\n\n # -------------------------------------------------- xy decoder\n traj_obs_last = self.traj_obs_gt[:, -1]\n\n pred_length = tf.reduce_sum(\n tf.cast(self.traj_pred_gt_mask, 'int32'), 1) # N\n\n if config.multi_decoder:\n\n # [N, num_traj_cat] # each is num_traj_cat classification\n self.traj_class_logits = self.traj_class_head(\n obs_enc_h, obs_enc_last_state, scope='traj_class_predict')\n\n # [N]\n traj_class = tf.argmax(self.traj_class_logits, axis=1)\n\n traj_class_gated = tf.cond(\n self.is_train,\n lambda: self.traj_class_gt,\n lambda: traj_class,\n )\n\n traj_pred_outs = [\n self.decoder(\n traj_obs_last,\n traj_obs_enc_last_state,\n obs_enc_h,\n pred_length,\n dec_cell_traj[traj_cat],\n top_scope=top_scope,\n scope='decoder_%s' % traj_cat)\n for _, traj_cat in config.traj_cats\n ]\n\n # [N, num_decoder, T, 2]\n self.traj_pred_outs = tf.stack(traj_pred_outs, axis=1)\n\n # [N, 2]\n indices = tf.stack(\n [tf.range(N), tf.to_int32(traj_class_gated)], axis=1)\n\n # [N, T, 2]\n traj_pred_out = tf.gather_nd(self.traj_pred_outs, indices)\n\n else:\n traj_pred_out = self.decoder(traj_obs_last, traj_obs_enc_last_state,\n obs_enc_h, pred_length, dec_cell_traj,\n top_scope=top_scope, scope='decoder')\n\n if config.add_activity:\n # activity decoder\n self.future_act_logits = self.activity_head(\n obs_enc_h, obs_enc_last_state, scope='activity_predict')\n\n # predict the activity destination\n with tf.variable_scope('grid_head', reuse=tf.AUTO_REUSE):\n conv_dim = config.scene_conv_dim\n\n assert len(config.scene_grids) == 2\n # grid class and grid target output\n self.grid_class_logits = []\n self.grid_target_logits = []\n for i, (h, w) in enumerate(config.scene_grids):\n # [h,w,c]\n this_scene_conv = self.scene_convs[i]\n this_scene_conv = tf.reshape(\n this_scene_conv, [N, h*w, conv_dim])\n\n # tile\n # [N, h*w, h_dim*k]\n h_tile = tf.tile(tf.expand_dims(\n obs_enc_last_state.h, axis=1), [1, h*w, 1])\n\n # [N, h*w, conv_dim + h_dim + emb]\n\n scene_feature = tf.concat(\n [h_tile, this_scene_conv], axis=-1)\n\n # add the occupation map, grid obs input is already in the h_tile\n # [N, T, h*w]\n obs_gridclass_onehot = tf.one_hot(\n self.grid_obs_labels[i], h*w)\n obs_gridclass_occupy = tf.reduce_sum(\n obs_gridclass_onehot, axis=1)\n obs_gridclass = tf.cast(\n obs_gridclass_occupy, 'float32') # [N,h*w]\n obs_gridclass = tf.reshape(obs_gridclass, [N, h*w, 1])\n\n # [N, h*w, 1] -> [N, h*w, emb]\n obs_grid_class_emb = linear(obs_gridclass,\n output_size=config.emb_size,\n activation=config.activation_func,\n add_bias=True,\n scope='obs_grid_class_emb_%d' % i)\n scene_feature = tf.concat(\n [scene_feature, obs_grid_class_emb], axis=-1)\n\n grid_class_logit = conv2d(tf.reshape(scene_feature, [N, h, w, -1]),\n out_channel=1, kernel=1, stride=1,\n activation=config.activation_func,\n add_bias=True, scope='grid_class_%d' % i)\n grid_target_logit_all = conv2d(tf.reshape(scene_feature,\n [N, h, w, -1]),\n out_channel=2, kernel=1, stride=1,\n activation=config.activation_func,\n add_bias=True,\n scope='grid_target_%d' % i)\n grid_class_logit = tf.reshape(\n grid_class_logit, [N, h*w, 1])\n grid_target_logit_all = tf.reshape(\n grid_target_logit_all, [N, h*w, 2])\n\n grid_class_logit = tf.squeeze(grid_class_logit, axis=-1)\n\n # [N]\n target_class = tf.argmax(grid_class_logit, axis=-1)\n\n # [N,2]\n indices = tf.stack(\n [tf.range(N), tf.to_int32(target_class)], axis=-1)\n # [N,h*w,2] + [N,2] -> # [N,2]\n grid_target_logit = tf.gather_nd(\n grid_target_logit_all, indices)\n\n self.grid_class_logits.append(grid_class_logit)\n self.grid_target_logits.append(grid_target_logit)\n\n # for loss and forward\n self.traj_pred_out = traj_pred_out\n\n # output [N, num_decoder]\n # enc_h for future extension, so pylint: disable=unused-argument\n def traj_class_head(self, enc_h, enc_last_state, scope='predict_traj_cat'):\n \"\"\"Trajectory classification branch.\"\"\"\n config = self.config\n with tf.variable_scope(scope, reuse=tf.AUTO_REUSE):\n\n # [N, hdim*num_enc]\n feature = enc_last_state.h\n\n # [N, num_traj_class]\n logits = linear(feature, output_size=len(config.traj_cats),\n add_bias=False, activation=tf.identity,\n scope='traj_cat_logits')\n\n return logits\n\n def activity_head(self, enc_h, enc_last_state, scope='activity_predict'):\n \"\"\"Activity prediction branch.\"\"\"\n config = self.config\n\n with tf.variable_scope(scope, reuse=tf.AUTO_REUSE):\n\n feature = enc_last_state.h\n\n future_act = linear(feature, output_size=config.num_act, add_bias=False,\n activation=tf.identity, scope='future_act')\n\n return future_act\n\n def decoder(self, first_input, enc_last_state, enc_h, pred_length, rnn_cell,\n top_scope, scope):\n \"\"\"Decoder definition.\"\"\"\n config = self.config\n # Tensor dimensions, so pylint: disable=g-bad-name\n N = self.N\n P = self.P\n\n with tf.variable_scope(scope):\n # this is only used for training\n with tf.name_scope('prepare_pred_gt_training'):\n # these input only used during training\n time_1st_traj_pred = tf.transpose(\n self.traj_pred_gt, perm=[1, 0, 2]) # [N,T2,W] -> [T2,N,W]\n T2 = tf.shape(time_1st_traj_pred)[0] # T2\n traj_pred_gt = tf.TensorArray(size=T2, dtype='float')\n traj_pred_gt = traj_pred_gt.unstack(\n time_1st_traj_pred) # [T2] , [N,W]\n\n # all None for first call\n with tf.name_scope('decoder_rnn'):\n def decoder_loop_fn(time, cell_output, cell_state, loop_state):\n \"\"\"RNN loop function for the decoder.\"\"\"\n emit_output = cell_output # == None for time==0\n\n elements_finished = time >= pred_length\n finished = tf.reduce_all(elements_finished)\n\n # h_{t-1}\n with tf.name_scope('prepare_next_cell_state'):\n\n if cell_output is None:\n next_cell_state = enc_last_state\n else:\n next_cell_state = cell_state\n\n # x_t\n with tf.name_scope('prepare_next_input'):\n if cell_output is None: # first time\n next_input_xy = first_input # the last observed x,y as input\n else:\n # for testing, construct from this output to be next input\n next_input_xy = tf.cond(\n # first check the sequence finished or not\n finished,\n lambda: tf.zeros([N, P], dtype='float'),\n # pylint: disable=g-long-lambda\n lambda: tf.cond(\n self.is_train,\n # this will make training faster than testing\n lambda: traj_pred_gt.read(time),\n # hidden vector from last step to coordinates\n lambda: self.hidden2xy(cell_output, scope=top_scope,\n additional_scope='hidden2xy'))\n )\n\n # spatial embedding\n # [N,emb]\n xy_emb = linear(next_input_xy, output_size=config.emb_size,\n activation=config.activation_func, add_bias=True,\n scope='xy_emb_dec')\n\n next_input = xy_emb\n\n with tf.name_scope('attend_enc'):\n # [N,h_dim]\n\n attended_encode_states = focal_attention(\n next_cell_state.h, enc_h, use_sigmoid=False,\n scope='decoder_attend_encoders')\n\n next_input = tf.concat(\n [xy_emb, attended_encode_states], axis=1)\n\n return elements_finished, next_input, next_cell_state, \\\n emit_output, None # next_loop_state\n\n decoder_out_ta, _, _ = tf.nn.raw_rnn(\n rnn_cell, decoder_loop_fn, scope='decoder_rnn')\n\n with tf.name_scope('reconstruct_output'):\n decoder_out_h = decoder_out_ta.stack() # [T2,N,h_dim]\n # [N,T2,h_dim]\n decoder_out_h = tf.transpose(decoder_out_h, perm=[1, 0, 2])\n\n # recompute the output;\n # if use loop_state to save the output, will 10x slower\n\n # use the same hidden2xy for different decoder\n decoder_out = self.hidden2xy(\n decoder_out_h, scope=top_scope, additional_scope='hidden2xy')\n\n return decoder_out\n\n def hidden2xy(self, lstm_h, return_scope=False, scope='hidden2xy',\n additional_scope=None):\n \"\"\"Hiddent states to xy coordinates.\"\"\"\n # Tensor dimensions, so pylint: disable=g-bad-name\n P = self.P\n with tf.variable_scope(scope, reuse=tf.AUTO_REUSE) as this_scope:\n if additional_scope is not None:\n return self.hidden2xy(lstm_h, return_scope=return_scope,\n scope=additional_scope, additional_scope=None)\n\n out_xy = linear(lstm_h, output_size=P, activation=tf.identity,\n add_bias=False, scope='out_xy_mlp2')\n\n if return_scope:\n return out_xy, this_scope\n return out_xy\n\n def build_loss(self):\n \"\"\"Model loss.\"\"\"\n config = self.config\n losses = []\n # N,T,W\n # L2 loss\n # [N,T2,W]\n traj_pred_out = self.traj_pred_out\n\n traj_pred_gt = self.traj_pred_gt\n\n diff = traj_pred_out - traj_pred_gt\n\n xyloss = tf.pow(diff, 2) # [N,T2,2]\n xyloss = tf.reduce_mean(xyloss)\n\n self.xyloss = xyloss\n\n losses.append(xyloss)\n\n # trajectory classification loss\n if config.multi_decoder:\n traj_class_loss = tf.nn.sparse_softmax_cross_entropy_with_logits(\n labels=self.traj_class_gt, logits=self.traj_class_logits)\n traj_class_loss = tf.reduce_mean(\n traj_class_loss)*tf.constant(config.traj_class_loss_weight,\n dtype='float')\n\n self.traj_class_loss = traj_class_loss\n losses.append(traj_class_loss)\n\n # ------------------------ activity destination loss\n self.grid_loss = []\n grid_loss_weight = config.grid_loss_weight\n for i, _ in enumerate(config.scene_grids):\n grid_pred_label = self.grid_pred_labels[i] # [N]\n grid_pred_target = self.grid_pred_targets[i] # [N,2]\n\n grid_class_logit = self.grid_class_logits[i] # [N,h*w]\n grid_target_logit = self.grid_target_logits[i] # [N,2]\n\n # classification loss\n class_loss = tf.nn.sparse_softmax_cross_entropy_with_logits(\n labels=grid_pred_label, logits=grid_class_logit)\n class_loss = tf.reduce_mean(class_loss)\n\n # regression loss\n regression_loss = tf.losses.huber_loss(\n labels=grid_pred_target, predictions=grid_target_logit,\n reduction=tf.losses.Reduction.MEAN)\n\n class_loss = class_loss * \\\n tf.constant(grid_loss_weight, dtype='float')\n regression_loss = regression_loss * \\\n tf.constant(grid_loss_weight, dtype='float')\n\n self.grid_loss.extend([class_loss, regression_loss])\n\n losses.extend([class_loss, regression_loss])\n\n # --------- activity class loss\n if config.add_activity:\n act_loss_weight = config.act_loss_weight\n future_act_logits = self.future_act_logits # [N,num_act]\n future_act_label = self.future_act_label # [N,num_act]\n\n activity_loss = tf.nn.sigmoid_cross_entropy_with_logits(\n labels=tf.cast(future_act_label, 'float32'), logits=future_act_logits)\n activity_loss = tf.reduce_mean(activity_loss)\n\n activity_loss = activity_loss * \\\n tf.constant(act_loss_weight, dtype='float')\n\n self.activity_loss = activity_loss\n losses.extend([activity_loss])\n\n if config.wd is not None:\n wd = wd_cost('.*/W', config.wd, scope='wd_cost')\n if wd:\n wd = tf.add_n(wd)\n losses.append(wd)\n\n # there might be l2 weight loss in some layer\n self.loss = tf.add_n(losses, name='total_losses')\n\n def get_feed_dict(self, batch, is_train=False):\n \"\"\"Givng a batch of data, construct the feed dict.\"\"\"\n # get the cap for each kind of step first\n config = self.config\n # Tensor dimensions, so pylint: disable=g-bad-name\n N = self.N\n P = self.P\n KP = self.KP\n\n T_in = config.obs_len\n T_pred = config.pred_len\n\n feed_dict = {}\n\n # initial all the placeholder\n\n traj_obs_gt = np.zeros([N, T_in, P], dtype='float')\n traj_obs_gt_mask = np.zeros([N, T_in], dtype='bool')\n\n # link the feed_dict\n feed_dict[self.traj_obs_gt] = traj_obs_gt\n feed_dict[self.traj_obs_gt_mask] = traj_obs_gt_mask\n\n # for getting pred length during test time\n traj_pred_gt_mask = np.zeros([N, T_pred], dtype='bool')\n feed_dict[self.traj_pred_gt_mask] = traj_pred_gt_mask\n\n # this is needed since it is in tf.conf?\n traj_pred_gt = np.zeros([N, T_pred, P], dtype='float')\n feed_dict[self.traj_pred_gt] = traj_pred_gt # all zero when testing,\n\n feed_dict[self.is_train] = is_train\n\n data = batch.data\n # encoder features\n # ------------------------------------- xy input\n\n assert len(data['obs_traj_rel']) == N\n\n for i, (obs_data, pred_data) in enumerate(zip(data['obs_traj_rel'],\n data['pred_traj_rel'])):\n for j, xy in enumerate(obs_data):\n traj_obs_gt[i, j, :] = xy\n traj_obs_gt_mask[i, j] = True\n for j in xrange(config.pred_len):\n # used in testing to get the prediction length\n traj_pred_gt_mask[i, j] = True\n # ---------------------------------------\n\n # scene input\n obs_scene = np.zeros((N, T_in), dtype='int32')\n obs_scene_mask = np.zeros((N, T_in), dtype='bool')\n\n feed_dict[self.obs_scene] = obs_scene\n feed_dict[self.obs_scene_mask] = obs_scene_mask\n feed_dict[self.scene_feat] = data['batch_scene_feat']\n\n # each bacth\n for i in xrange(len(data['batch_obs_scene'])):\n for j in xrange(len(data['batch_obs_scene'][i])):\n # it was (1) shaped\n obs_scene[i, j] = data['batch_obs_scene'][i][j][0]\n obs_scene_mask[i, j] = True\n\n # [N,num_scale, T] # each is int to num_grid_class\n for j, _ in enumerate(config.scene_grids):\n this_grid_label = np.zeros([N, T_in], dtype='int32')\n for i in xrange(len(data['obs_grid_class'])):\n this_grid_label[i, :] = data['obs_grid_class'][i][j, :]\n\n feed_dict[self.grid_obs_labels[j]] = this_grid_label\n\n # person pose input\n if config.add_kp:\n obs_kp = np.zeros((N, T_in, KP, 2), dtype='float')\n\n feed_dict[self.obs_kp] = obs_kp\n\n # each bacth\n for i, obs_kp_rel in enumerate(data['obs_kp_rel']):\n for j, obs_kp_step in enumerate(obs_kp_rel):\n obs_kp[i, j, :, :] = obs_kp_step\n\n split = 'train'\n if not is_train:\n split = 'val'\n if config.is_test:\n split = 'test'\n\n # this is the h/w the bounding box is based on\n person_h = config.person_h\n person_w = config.person_w\n person_feat_dim = config.person_feat_dim\n\n obs_person_features = np.zeros(\n (N, T_in, person_h, person_w, person_feat_dim), dtype='float32')\n\n for i in xrange(len(data['obs_boxid'])):\n for j in xrange(len(data['obs_boxid'][i])):\n boxid = data['obs_boxid'][i][j]\n featfile = os.path.join(\n config.person_feat_path, split, '%s.npy' % boxid)\n obs_person_features[i, j] = np.squeeze(\n np.load(featfile), axis=0)\n\n feed_dict[self.obs_person_features] = obs_person_features\n\n # add other boxes,\n K = self.K # max_other boxes\n other_boxes_class = np.zeros(\n (N, T_in, K, config.num_box_class), dtype='float32')\n other_boxes = np.zeros((N, T_in, K, 4), dtype='float32')\n other_boxes_mask = np.zeros((N, T_in, K), dtype='bool')\n for i in xrange(len(data['obs_other_box'])):\n for j in xrange(len(data['obs_other_box'][i])): # -> seq_len\n this_other_boxes = data['obs_other_box'][i][j]\n this_other_boxes_class = data['obs_other_box_class'][i][j]\n\n other_box_idxs = range(len(this_other_boxes))\n\n if config.random_other:\n random.shuffle(other_box_idxs)\n\n other_box_idxs = other_box_idxs[:K]\n\n # get the current person box\n this_person_x1y1x2y2 = data['obs_box'][i][j] # (4)\n\n for k, idx in enumerate(other_box_idxs):\n other_boxes_mask[i, j, k] = True\n\n other_box_x1y1x2y2 = this_other_boxes[idx]\n\n other_boxes[i, j, k, :] = self.encode_other_boxes(\n this_person_x1y1x2y2, other_box_x1y1x2y2)\n # one-hot representation\n box_class = this_other_boxes_class[idx]\n other_boxes_class[i, j, k, box_class] = 1\n\n feed_dict[self.obs_other_boxes] = other_boxes\n feed_dict[self.obs_other_boxes_class] = other_boxes_class\n feed_dict[self.obs_other_boxes_mask] = other_boxes_mask\n\n # -----------------------------------------------------------\n\n # ----------------------------training\n if is_train:\n for i, (obs_data, pred_data) in enumerate(zip(data['obs_traj_rel'],\n data['pred_traj_rel'])):\n for j, xy in enumerate(pred_data):\n traj_pred_gt[i, j, :] = xy\n traj_pred_gt_mask[i, j] = True\n\n for j, _ in enumerate(config.scene_grids):\n\n this_grid_label = np.zeros([N], dtype='int32')\n this_grid_target = np.zeros([N, 2], dtype='float32')\n for i in xrange(len(data['pred_grid_class'])):\n # last pred timestep\n this_grid_label[i] = data['pred_grid_class'][i][j, -1]\n # last pred timestep\n this_grid_target[i] = data['pred_grid_target'][i][j, -1]\n\n # add new label as kxk for more target loss?\n\n feed_dict[self.grid_pred_labels[j]] = this_grid_label\n feed_dict[self.grid_pred_targets[j]] = this_grid_target\n\n if config.add_activity:\n future_act = np.zeros((N, config.num_act), dtype='uint8')\n # for experiment, training activity detection model\n\n for i in xrange(len(data['future_activity_onehot'])):\n future_act[i, :] = data['future_activity_onehot'][i]\n\n feed_dict[self.future_act_label] = future_act\n\n # needed since it is in tf.conf, but all zero in testing\n feed_dict[self.traj_class_gt] = np.zeros((N), dtype='int32')\n if config.multi_decoder and is_train:\n traj_class = np.zeros((N), dtype='int32')\n for i in xrange(len(data['traj_cat'])):\n traj_class[i] = data['traj_cat'][i]\n feed_dict[self.traj_class_gt] = traj_class\n\n return feed_dict\n\n def encode_other_boxes(self, person_box, other_box):\n \"\"\"Encoder other boxes.\"\"\"\n # get relative geometric feature\n x1, y1, x2, y2 = person_box\n xx1, yy1, xx2, yy2 = other_box\n\n x_m = x1\n y_m = y1\n w_m = x2 - x1\n h_m = y2 - y1\n\n x_n = xx1\n y_n = yy1\n w_n = xx2 - xx1\n h_n = yy2 - yy1\n\n return [\n math.log(max((x_m - x_n), 1e-3)/w_m),\n math.log(max((y_m - y_n), 1e-3)/h_m),\n math.log(w_n/w_m),\n math.log(h_n/h_m),\n ]\n\n\ndef wd_cost(regex, wd, scope):\n \"\"\"Given regex to get the parameter to do regularization.\n\n Args:\n regex: regular expression\n wd: weight decay factor\n scope: variable scope\n Returns:\n Tensor\n \"\"\"\n params = tf.trainable_variables()\n with tf.name_scope(scope):\n costs = []\n for p in params:\n para_name = p.op.name\n if re.search(regex, para_name):\n regloss = tf.multiply(tf.nn.l2_loss(p), wd, name='%s/wd' % p.op.name)\n assert regloss.dtype.is_floating, regloss\n if regloss.dtype != tf.float32:\n regloss = tf.cast(regloss, tf.float32)\n costs.append(regloss)\n\n return costs\n\n\ndef reconstruct(tensor, ref, keep):\n \"\"\"Reverse the flatten function.\n\n Args:\n tensor: the tensor to operate on\n ref: reference tensor to get original shape\n keep: index of dim to keep\n\n Returns:\n Reconstructed tensor\n \"\"\"\n ref_shape = ref.get_shape().as_list()\n tensor_shape = tensor.get_shape().as_list()\n ref_stop = len(ref_shape) - keep\n tensor_start = len(tensor_shape) - keep\n pre_shape = [ref_shape[i] or tf.shape(ref)[i] for i in range(ref_stop)]\n keep_shape = [tensor_shape[i] or tf.shape(tensor)[i]\n for i in range(tensor_start, len(tensor_shape))]\n # keep_shape = tensor.get_shape().as_list()[-keep:]\n target_shape = pre_shape + keep_shape\n out = tf.reshape(tensor, target_shape)\n return out\n\n\ndef flatten(tensor, keep):\n \"\"\"Flatten a tensor.\n\n keep how many dimension in the end, so final rank is keep + 1\n [N,M,JI,JXP,dim] -> [N*M*JI,JXP,dim]\n\n Args:\n tensor: the tensor to operate on\n keep: index of dim to keep\n\n Returns:\n Flattened tensor\n \"\"\"\n # get the shape\n fixed_shape = tensor.get_shape().as_list() # [N, JQ, di] # [N, M, JX, di]\n # len([N, JQ, di]) - 2 = 1 # len([N, M, JX, di] ) - 2 = 2\n start = len(fixed_shape) - keep\n # each num in the [] will a*b*c*d...\n # so [0] -> just N here for left\n # for [N, M, JX, di] , left is N*M\n left = reduce(operator.mul, [fixed_shape[i] or tf.shape(tensor)[i]\n for i in range(start)])\n # [N, JQ,di]\n # [N*M, JX, di]\n out_shape = [left] + [fixed_shape[i] or tf.shape(tensor)[i]\n for i in range(start, len(fixed_shape))]\n # reshape\n flat = tf.reshape(tensor, out_shape)\n return flat\n\n\ndef conv2d(x, out_channel, kernel, padding='SAME', stride=1,\n activation=tf.identity, add_bias=True, data_format='NHWC',\n w_init=None, scope='conv'):\n \"\"\"Convolutional layer.\"\"\"\n with tf.variable_scope(scope):\n in_shape = x.get_shape().as_list()\n\n channel_axis = 3 if data_format == 'NHWC' else 1\n in_channel = in_shape[channel_axis]\n\n assert in_channel is not None\n\n kernel_shape = [kernel, kernel]\n\n filter_shape = kernel_shape + [in_channel, out_channel]\n\n if data_format == 'NHWC':\n stride = [1, stride, stride, 1]\n else:\n stride = [1, 1, stride, stride]\n\n if w_init is None:\n w_init = tf.variance_scaling_initializer(scale=2.0)\n # common weight tensor, so pylint: disable=g-bad-name\n W = tf.get_variable('W', filter_shape, initializer=w_init)\n\n conv = tf.nn.conv2d(x, W, stride, padding, data_format=data_format)\n\n if add_bias:\n b_init = tf.constant_initializer()\n b = tf.get_variable('b', [out_channel], initializer=b_init)\n conv = tf.nn.bias_add(conv, b, data_format=data_format)\n\n ret = activation(conv, name='output')\n\n return ret\n\n\ndef softmax(logits, scope=None):\n \"\"\"a flatten and reconstruct version of softmax.\"\"\"\n with tf.name_scope(scope or 'softmax'):\n flat_logits = flatten(logits, 1)\n flat_out = tf.nn.softmax(flat_logits)\n out = reconstruct(flat_out, logits, 1)\n return out\n\n\ndef softsel(target, logits, use_sigmoid=False, scope=None):\n \"\"\"Apply attention weights.\"\"\"\n\n with tf.variable_scope(scope or 'softsel'): # no new variable tho\n if use_sigmoid:\n a = tf.nn.sigmoid(logits)\n else:\n a = softmax(logits) # shape is the same\n target_rank = len(target.get_shape().as_list())\n # [N,M,JX,JQ,2d] elem* [N,M,JX,JQ,1]\n # second last dim\n return tf.reduce_sum(tf.expand_dims(a, -1)*target, target_rank-2)\n\n\ndef exp_mask(val, mask):\n \"\"\"Apply exponetial mask operation.\"\"\"\n return tf.add(val, (1 - tf.cast(mask, 'float')) * -1e30, name='exp_mask')\n\n\ndef linear(x, output_size, scope, add_bias=False, wd=None, return_scope=False,\n reuse=None, activation=tf.identity, keep=1, additional_scope=None):\n \"\"\"Fully-connected layer.\"\"\"\n with tf.variable_scope(scope or 'xy_emb', reuse=tf.AUTO_REUSE) as this_scope:\n if additional_scope is not None:\n return linear(x, output_size, scope=additional_scope, add_bias=add_bias,\n wd=wd, return_scope=return_scope, reuse=reuse,\n activation=activation, keep=keep, additional_scope=None)\n # since the input here is not two rank,\n # we flat the input while keeping the last dims\n # keeping the last one dim # [N,M,JX,JQ,2d] => [N*M*JX*JQ,2d]\n flat_x = flatten(x, keep)\n # print flat_x.get_shape() # (?, 200) # wd+cwd\n bias_start = 0.0\n # need to be get_shape()[k].value\n if not isinstance(output_size, int):\n output_size = output_size.value\n\n def init(shape, dtype, partition_info):\n dtype = dtype\n partition_info = partition_info\n return tf.truncated_normal(shape, stddev=0.1)\n # Common weight tensor name, so pylint: disable=g-bad-name\n W = tf.get_variable('W', dtype='float', initializer=init,\n shape=[flat_x.get_shape()[-1].value, output_size])\n flat_out = tf.matmul(flat_x, W)\n if add_bias:\n # disable=unused-argument\n def init_b(shape, dtype, partition_info):\n dtype = dtype\n partition_info = partition_info\n return tf.constant(bias_start, shape=shape)\n\n bias = tf.get_variable(\n 'b', dtype='float', initializer=init_b, shape=[output_size])\n flat_out += bias\n\n flat_out = activation(flat_out)\n\n out = reconstruct(flat_out, x, keep)\n if return_scope:\n return out, this_scope\n else:\n return out\n\n\ndef focal_attention(query, context, use_sigmoid=False, scope=None):\n \"\"\"Focal attention layer.\n\n Args:\n query : [N, dim1]\n context: [N, num_channel, T, dim2]\n use_sigmoid: use sigmoid instead of softmax\n scope: variable scope\n\n Returns:\n Tensor\n \"\"\"\n with tf.variable_scope(scope or 'attention', reuse=tf.AUTO_REUSE):\n # Tensor dimensions, so pylint: disable=g-bad-name\n _, d = query.get_shape().as_list()\n _, K, _, d2 = context.get_shape().as_list()\n assert d == d2\n\n T = tf.shape(context)[2]\n\n # [N,d] -> [N,K,T,d]\n query_aug = tf.tile(tf.expand_dims(\n tf.expand_dims(query, 1), 1), [1, K, T, 1])\n\n # cosine simi\n query_aug_norm = tf.nn.l2_normalize(query_aug, -1)\n context_norm = tf.nn.l2_normalize(context, -1)\n # [N, K, T]\n a_logits = tf.reduce_sum(tf.multiply(query_aug_norm, context_norm), 3)\n\n a_logits_maxed = tf.reduce_max(a_logits, 2) # [N,K]\n\n attended_context = softsel(softsel(context, a_logits,\n use_sigmoid=use_sigmoid), a_logits_maxed,\n use_sigmoid=use_sigmoid)\n\n return attended_context\n\n\ndef concat_states(state_tuples, axis):\n \"\"\"Concat LSTM states.\"\"\"\n return tf.nn.rnn_cell.LSTMStateTuple(c=tf.concat([s.c for s in state_tuples],\n axis=axis),\n h=tf.concat([s.h for s in state_tuples],\n axis=axis))\n\n\nclass Trainer(object):\n \"\"\"Trainer class for model.\"\"\"\n\n def __init__(self, model, config):\n self.config = config\n self.model = model # this is an model instance\n\n self.global_step = model.global_step\n\n learning_rate = config.init_lr\n\n if config.learning_rate_decay is not None:\n decay_steps = int(config.train_num_examples /\n config.batch_size * config.num_epoch_per_decay)\n\n learning_rate = tf.train.exponential_decay(\n config.init_lr,\n self.global_step,\n decay_steps, # decay every k samples used in training\n config.learning_rate_decay,\n staircase=True)\n\n if config.optimizer == 'momentum':\n opt_emb = tf.train.MomentumOptimizer(\n learning_rate*config.emb_lr, momentum=0.9)\n opt_rest = tf.train.MomentumOptimizer(learning_rate, momentum=0.9)\n elif config.optimizer == 'adadelta':\n opt_emb = tf.train.AdadeltaOptimizer(learning_rate*config.emb_lr)\n opt_rest = tf.train.AdadeltaOptimizer(learning_rate)\n elif config.optimizer == 'adam':\n opt_emb = tf.train.AdamOptimizer(learning_rate*config.emb_lr)\n opt_rest = tf.train.AdamOptimizer(learning_rate)\n else:\n raise Exception('Optimizer not implemented')\n\n # losses\n self.xyloss = model.xyloss\n self.loss = model.loss # get the loss funcion\n\n # valist for embding layer\n var_emb = [var for var in tf.trainable_variables()\n if 'emb' in var.name]\n var_rest = [var for var in tf.trainable_variables()\n if 'emb' not in var.name]\n\n # for training, we get the gradients first, then apply them\n self.grads = tf.gradients(self.loss, var_emb+var_rest)\n\n if config.clip_gradient_norm is not None:\n # pylint: disable=g-long-ternary\n self.grads = [grad if grad is None else\n tf.clip_by_value(grad, -1*config.clip_gradient_norm,\n config.clip_gradient_norm)\n for grad in self.grads]\n\n grads_emb = self.grads[:len(var_emb)]\n grads_rest = self.grads[len(var_emb):]\n\n train_emb = opt_emb.apply_gradients(zip(grads_emb, var_emb))\n train_rest = opt_rest.apply_gradients(\n zip(grads_rest, var_rest), global_step=self.global_step)\n self.train_op = tf.group(train_emb, train_rest)\n\n def step(self, sess, batch):\n \"\"\"One training step.\"\"\"\n config = self.config\n # idxs is a tuple (23,123,33..) index for sample\n _, batch_data = batch\n feed_dict = self.model.get_feed_dict(batch_data, is_train=True)\n act_loss = -1\n grid_loss = -1\n traj_class_loss = -1\n inputs = [self.loss, self.train_op, self.xyloss]\n num_out = 3\n if config.add_activity:\n inputs += [self.model.activity_loss]\n num_out += 1\n if config.multi_decoder:\n inputs += [self.model.traj_class_loss]\n num_out += 1\n inputs += self.model.grid_loss\n\n outputs = sess.run(inputs, feed_dict=feed_dict)\n\n loss, train_op, xyloss = outputs[:3]\n\n if config.add_activity:\n act_loss = outputs[3]\n\n if config.multi_decoder:\n if config.add_activity:\n traj_class_loss = outputs[4]\n else:\n traj_class_loss = outputs[3]\n\n grid_loss = outputs[num_out:]\n\n return loss, train_op, xyloss, act_loss, traj_class_loss, grid_loss\n\n\nclass Tester(object):\n \"\"\"Tester for model.\"\"\"\n\n def __init__(self, model, config, sess=None):\n self.config = config\n self.model = model\n self.traj_pred_out = self.model.traj_pred_out\n self.grid_pred_class = self.model.grid_class_logits\n self.sess = sess\n if config.add_activity:\n self.future_act_logits = self.model.future_act_logits\n\n if config.multi_decoder:\n self.traj_class_logits = self.model.traj_class_logits\n self.traj_outs = self.model.traj_pred_outs\n\n def step(self, sess, batch):\n \"\"\"One inferencing step.\"\"\"\n config = self.config\n # give one batch of Dataset, use model to get the result,\n _, batch_data = batch\n feed_dict = self.model.get_feed_dict(batch_data, is_train=False)\n\n future_act, grid_pred_1, grid_pred_2, traj_class_logits, traj_outs = \\\n None, None, None, None, None\n\n inputs = [self.traj_pred_out]\n\n num_out = 1\n if config.add_activity:\n inputs += [self.future_act_logits]\n num_out += 1\n\n if config.multi_decoder:\n inputs += [self.traj_class_logits, self.traj_outs]\n num_out += 2\n\n inputs += self.grid_pred_class\n\n outputs = sess.run(inputs, feed_dict=feed_dict)\n\n pred_out = outputs[0]\n\n if config.add_activity:\n future_act = outputs[1]\n if config.multi_decoder:\n if not config.add_activity:\n traj_class_logits = outputs[1]\n traj_outs = outputs[2]\n else:\n traj_class_logits = outputs[2]\n traj_outs = outputs[3]\n\n grid_pred_1, grid_pred_2 = outputs[num_out:]\n\n return pred_out, future_act, grid_pred_1, grid_pred_2, traj_class_logits, \\\n traj_outs\n"
] | [
[
"tensorflow.compat.v1.reduce_all",
"tensorflow.compat.v1.concat",
"tensorflow.compat.v1.gradients",
"tensorflow.compat.v1.group",
"tensorflow.compat.v1.shape",
"tensorflow.compat.v1.nn.rnn_cell.LSTMCell",
"tensorflow.compat.v1.truncated_normal",
"tensorflow.compat.v1.nn.sparse_softmax_cross_entropy_with_logits",
"tensorflow.compat.v1.constant",
"tensorflow.compat.v1.pow",
"tensorflow.compat.v1.to_int32",
"tensorflow.compat.v1.nn.sigmoid",
"tensorflow.compat.v1.train.AdamOptimizer",
"tensorflow.compat.v1.add_n",
"tensorflow.compat.v1.reshape",
"tensorflow.compat.v1.trainable_variables",
"tensorflow.compat.v1.multiply",
"tensorflow.compat.v1.one_hot",
"tensorflow.compat.v1.reduce_sum",
"tensorflow.compat.v1.constant_initializer",
"tensorflow.compat.v1.nn.raw_rnn",
"tensorflow.compat.v1.train.AdadeltaOptimizer",
"numpy.load",
"tensorflow.compat.v1.variable_scope",
"numpy.zeros",
"tensorflow.compat.v1.nn.dynamic_rnn",
"tensorflow.compat.v1.name_scope",
"tensorflow.compat.v1.gather_nd",
"tensorflow.compat.v1.transpose",
"tensorflow.compat.v1.nn.softmax",
"tensorflow.compat.v1.reduce_mean",
"tensorflow.compat.v1.get_variable",
"tensorflow.compat.v1.zeros",
"tensorflow.compat.v1.nn.conv2d",
"tensorflow.compat.v1.train.exponential_decay",
"tensorflow.compat.v1.clip_by_value",
"tensorflow.compat.v1.losses.huber_loss",
"tensorflow.compat.v1.nn.l2_normalize",
"tensorflow.compat.v1.cond",
"tensorflow.compat.v1.reduce_max",
"tensorflow.compat.v1.nn.rnn_cell.DropoutWrapper",
"tensorflow.compat.v1.cast",
"tensorflow.compat.v1.stack",
"tensorflow.compat.v1.device",
"tensorflow.compat.v1.expand_dims",
"tensorflow.compat.v1.disable_v2_behavior",
"tensorflow.compat.v1.variance_scaling_initializer",
"tensorflow.compat.v1.argmax",
"tensorflow.compat.v1.TensorArray",
"tensorflow.compat.v1.matmul",
"tensorflow.compat.v1.placeholder",
"tensorflow.compat.v1.train.MomentumOptimizer",
"tensorflow.compat.v1.nn.embedding_lookup",
"tensorflow.compat.v1.range",
"tensorflow.compat.v1.nn.l2_loss",
"tensorflow.compat.v1.nn.bias_add",
"tensorflow.compat.v1.squeeze"
]
] |
AaltoPML/informative_prior | [
"64661650d2d03050689e841f084b97b0a1e3b1da"
] | [
"models/training.py"
] | [
"import torch\r\nimport torch.nn as nn\r\nimport torch.optim as optim\r\nimport numpy as np\r\n\r\ndef training_lr(model, x, y, learning_rate=0.001, batch_size=50, num_epoch=1000):\r\n \"\"\"\r\n Train a Bayesian linear regression model with stochastic variational inference on data (x, y)\r\n \"\"\"\r\n parameters = set(model.parameters())\r\n optimizer = optim.Adam(parameters, lr=learning_rate, eps=1e-3)\r\n criterion = nn.MSELoss()\r\n\r\n train_errors = []\r\n\r\n num_data, _ = x.shape\r\n _, num_output = y.shape\r\n data = torch.cat((x, y), 1)\r\n\r\n for epoch in range(num_epoch):\r\n # permuate the data\r\n data_perm = data[torch.randperm(len(data))]\r\n x = data_perm[:, :-num_output]\r\n y = data_perm[:, -num_output:]\r\n for index in range(int(num_data / batch_size)):\r\n # data comes in\r\n inputs = x[index * batch_size: (index + 1) * batch_size]\r\n labels = y[index * batch_size: (index + 1) * batch_size]\r\n # initialize the gradient of optimizer\r\n optimizer.zero_grad()\r\n model.train()\r\n output, kl = model(inputs)\r\n # calculate the training loss\r\n loss = criterion(labels, output) / 2 + kl / num_data\r\n # backpropogate the gradient\r\n loss.backward()\r\n # optimize with SGD\r\n optimizer.step()\r\n # validation loss\r\n model.eval()\r\n\r\n # splite the training data\r\n output_x_train, kl = model(x)\r\n\r\n train_errors.append(criterion(output_x_train, y).detach())\r\n if ((epoch + 1) % 4000) == 0:\r\n print('EPOACH %d: TRAIN LOSS: %.4f; KL REG: %.4f.' % (epoch + 1, train_errors[epoch], kl))\r\n\r\n\r\ndef training_hs_lr(model, x, y, learning_rate=0.001, batch_size=50, num_epoch=1000):\r\n \"\"\"\r\n Train a Bayesian linear regression model with the horseshoe prior with stochastic variational inference on data (x, y)\r\n \"\"\"\r\n parameters = set(model.parameters())\r\n optimizer = optim.Adam(parameters, lr=learning_rate, eps=1e-3)\r\n criterion = nn.MSELoss()\r\n\r\n train_errors = []\r\n\r\n num_data, _ = x.shape\r\n _, num_output = y.shape\r\n data = torch.cat((x, y), 1)\r\n\r\n for epoch in range(num_epoch):\r\n # permuate the data\r\n data_perm = data[torch.randperm(len(data))]\r\n x = data_perm[:, :-num_output]\r\n y = data_perm[:, -num_output:]\r\n for index in range(int(num_data / batch_size)):\r\n # data comes in\r\n inputs = x[index * batch_size: (index + 1) * batch_size]\r\n labels = y[index * batch_size: (index + 1) * batch_size]\r\n # initialize the gradient of optimizer\r\n optimizer.zero_grad()\r\n model.train()\r\n output, kl = model(inputs)\r\n # calculate the training loss\r\n loss = criterion(labels, output) / 2 + kl / num_data\r\n # backpropogate the gradient\r\n loss.backward()\r\n # optimize with SGD\r\n optimizer.step()\r\n # analytical update\r\n model._updates()\r\n # validation loss\r\n model.eval()\r\n\r\n # splite the training data\r\n output_x_train, kl = model(x)\r\n\r\n train_errors.append(criterion(output_x_train, y).detach())\r\n if ((epoch + 1) % 4000) == 0:\r\n print('EPOACH %d: TRAIN LOSS: %.4f; KL REG: %.4f.' % (epoch + 1, train_errors[epoch], kl))\r\n\r\n\r\ndef training_nn(model, x, y, x_test, y_test, learning_rate=0.001, batch_size=50, num_epoch=1000):\r\n parameters = set(model.parameters())\r\n optimizer = optim.Adam(parameters, lr=learning_rate, eps=1e-3)\r\n criterion = nn.MSELoss()\r\n\r\n train_errors = []\r\n test_errors = []\r\n\r\n num_data, _ = x.shape\r\n _, num_output = y.shape\r\n data = torch.cat((x, y), 1)\r\n\r\n for epoch in range(num_epoch):\r\n # permuate the data\r\n data_perm = data[torch.randperm(len(data))]\r\n x = data_perm[:, :-num_output]\r\n y = data_perm[:, -num_output:]\r\n for index in range(int(num_data / batch_size)):\r\n # data comes in\r\n inputs = x[index * batch_size: (index + 1) * batch_size]\r\n labels = y[index * batch_size: (index + 1) * batch_size]\r\n # initialize the gradient of optimizer\r\n optimizer.zero_grad()\r\n model.train()\r\n output, kl, sigma_n = model(inputs)\r\n # calculate the training loss\r\n loss = criterion(labels, output) / (2 * sigma_n ** 2) + torch.log(\r\n sigma_n * np.sqrt(2. * np.pi)) + kl / num_data\r\n # backpropogate the gradient\r\n loss.backward()\r\n # optimize with SGD\r\n optimizer.step()\r\n # validation loss\r\n model.eval()\r\n\r\n # splite the training data\r\n output_x_train, kl, _ = model(x)\r\n output_x_test, kl, _ = model(x_test)\r\n\r\n train_errors.append(criterion(output_x_train, y).detach())\r\n test_errors.append(criterion(output_x_test, y_test).detach())\r\n if (epoch % 500) == 0:\r\n print('EPOACH %d: TRAIN LOSS: %.4f; KL REG: %.4f; TEST LOSS IS: %.5f.' % (\r\n epoch + 1, train_errors[epoch], kl, test_errors[epoch]))\r\n\r\n return train_errors, test_errors"
] | [
[
"torch.optim.Adam",
"numpy.sqrt",
"torch.nn.MSELoss",
"torch.cat"
]
] |
NIKH0610/Final-Project | [
"da9f3c3280b979c401e46271638fb92d4fd8d7a7"
] | [
"Weather_Docker.py"
] | [
"import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport sklearn\nimport os\n\ndf = pd.read_csv('/opt/weatherHistory.csv')\n\ndf.columns = ['Date', 'Summary', 'Prec Type', 'Temp', 'App Temp', 'Humidity', 'Wind Speed', 'Wind Angle', 'Visibility', 'Loud Cover', 'Pressure', 'Sum']\n\n#print(df.head())\n#print(df.columns)\n\n#x = df.drop('Temp', axis=1)\n#y = df['Temp']\n\n#print(f'Dataset X Shape: {x.shape}')\n#print(f'Dataset y shape: {y.shape}')\n\ndf = df[['Temp','App Temp', 'Humidity', 'Wind Speed', 'Wind Angle', 'Visibility', 'Pressure']]\n\n#Using Pearson correlation\nplt.figure(figsize=(10,8))\ncor = df.corr()\nsns.heatmap(cor, annot=True, cmap=\"YlGnBu\")\nplt.show()\n\n#Correlation with output variable\ncor_target = abs(cor['App Temp'])\n#Selecting highly correlated features\nrelevant_features = cor_target[cor_target>0.5]\n#print(relevant_features)\n\nx = df['Humidity']\ny = df['App Temp']\nplt.scatter(x,y,marker=\".\", c=\"g\")\nplt.xlabel(\"Humidity\")\nplt.ylabel(\"Apparent Temparature (in C)\")\nplt.title(\"Humidity vs Apparent Temperature\")\nplt.show()\n\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.linear_model import LinearRegression\n\nx = df[['Temp', 'Humidity', 'Wind Speed', 'Wind Angle', 'Visibility', 'Pressure']]\ny = df['App Temp']\n\n\nX_train, X_test, y_train, y_test = train_test_split(x,y, test_size = 0.25, random_state = 0)\nmodel = LinearRegression()\n\nmodel.fit(X_train, y_train)\n\nprint(f\"Coeficients: {model.coef_}\\n\")\nprint(f\"Score with features: {model.score(X_test, y_test)}\")\n\nX = df[['Humidity']]\nY = df[['App Temp']]\n\n#Splitting to test and train\n\nX_train, X_test, Y_train, Y_test = train_test_split(X,Y, test_size=0.25, random_state=42)\n\n#Creating linear regression object\n\nregr = LinearRegression()\nregr.fit(X_train, Y_train)\nscore = regr.score(X_test,Y_test)\ny_pred = regr.predict(X_test)\n\n#Coefficients\nprint(f\"Coefficients : {regr.coef_}\\n\")\n#print(f\"Intercept : {regr.intercept_}\\n\")\nprint(f\"Score using Humidity: {score}\\n\")\nplt.scatter(X, Y, color ='black')\nplt.xlabel(\"Humidity\")\nplt.ylabel(\"Apparent Temparature (in C)\")\nplt.title(\"Humidity vs Apparent Temperature\")\nplt.plot(X_test, y_pred, color='red', linewidth=2)\nplt.xticks(())\nplt.yticks(())\nplt.show()\n\n\n#Recursive fitting for best feature\n#Available features are 7\n#no. of features\n\nfrom sklearn.feature_selection import RFE\n\n#Variable to store optimum features\nprint (\"For RFE\")\nX = df[['Temp', 'Humidity', 'Wind Speed', 'Wind Angle', 'Visibility', 'Pressure']] #features\n\ny = df['App Temp']\nnof_list=np.arange(1,7)\nhigh_score=0\nnof=0\nscore_list=[]\n\nfor n in range(len(nof_list)):\n model = LinearRegression()\n X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=0)\n rfe = RFE(model, nof_list[n])\n X_train_rfe = rfe.fit_transform(X_train, y_train)\n X_test_rfe = rfe.transform(X_test)\n model.fit(X_train_rfe, y_train)\n score = model.score(X_test_rfe, y_test)\n score_list.append(score)\n if (score>high_score):\n high_score = score\n nof = nof_list[n]\n coeff = model.coef_\n intercept = model.intercept_\nprint(f\"Optimum number of feature: {nof}\\n\" )\nprint(f\"Score with features: {nof, high_score}\")\nprint(f\"Coefficients of features: {coeff}\\n\")\nprint(f\"intercept: {intercept}\\n\")\n"
] | [
[
"matplotlib.pyplot.yticks",
"pandas.read_csv",
"matplotlib.pyplot.scatter",
"matplotlib.pyplot.title",
"numpy.arange",
"sklearn.model_selection.train_test_split",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.ylabel",
"sklearn.linear_model.LinearRegression",
"sklearn.feature_selection.RFE",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.xticks",
"matplotlib.pyplot.show",
"matplotlib.pyplot.figure"
]
] |
ksemmendinger/Hydro_Parameter_Sensitivity_Visuals | [
"6d63b90e84172452a4e258d30efa049d6720cea1"
] | [
"HBV/SensIndices_RCPlots.py"
] | [
"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Jul 10 12:56:56 2019\n\n@author: kylasemmendinger\n\"\"\"\n# import python libraries\nimport pandas as pd\nimport os\n\n# back out a directory to load python functions from \"Scripts\" folder\norg_dir_name = os.path.dirname(os.path.realpath('SensIndices_RCPlots.py'))\nparent_dir_name = os.path.dirname(os.path.dirname(os.path.realpath('SensIndices_RCPlots.py')))\nos.chdir(parent_dir_name + \"/Scripts\")\n\n# load python functions from ‘Scripts’ folder\nimport delta\nimport sobol\nimport ols\nimport radial_conv_plots\nimport magnitude_percentile_plots\n\n# move back into case study 0 folder\nos.chdir(org_dir_name)\n\n# Define the model inputs\nproblem = {\n 'num_vars': 11,\n 'names': ['w', 'n_imperv', 'n_perv', 's_imperv', 's_perv', 'k_sat', 'per_routed', 'cmelt', 'Tb', 'A1', 'B1'],\n 'bounds': [[500, 1500], # meters\n [0.01, 0.2],\n [0.01, 0.2],\n [0, 10],\n [0, 10],\n [0.01, 10],\n [0, 100],\n [0, 4],\n [-3, 3],\n [0.0001, 0.01],\n [1, 3]]\n}\n\n# load in model parameter sets (Saltelli sampled) and objective function values\npars = pd.read_csv(\"input/params.csv\", header = 0)\nOF = pd.read_csv(\"input/OF_values.csv\")\n\n# save the parameter names\nparam_names = problem['names']\n\n# calculate Sobol first-, second-, and total order indices --> MUST BE BASED ON SALTELLI SAMPLING SCHEME\nresults_SI = []\nresults_SI = sobol.objective_function_sobol(problem, OF)\n\n# create radial convergence plots based on results_SI\nradial_conv_plots.radial_conv_plots(problem, results_SI, OF)\n\n# calculate delta indices and sobol first-order indices\nresults_delta = []\nresults_delta = delta.objective_function_delta(problem, pars, OF)\n\n# calculate R^2 from OLS regression\nresults_R2 = []\nresults_R2 = ols.objective_function_OLS(OF, pars, param_names)"
] | [
[
"pandas.read_csv"
]
] |
hoangph3/tslearn | [
"c589de380398379f2587f8cc812571d2a6d75938"
] | [
"tslearn/utils/cast.py"
] | [
"import warnings\n\nimport numpy\nfrom sklearn.utils import check_array\n\ntry:\n from scipy.io import arff\n HAS_ARFF = True\nexcept:\n HAS_ARFF = False\n\nfrom .utils import check_dataset, ts_size, to_time_series_dataset\n\n\ndef to_sklearn_dataset(dataset, dtype=float, return_dim=False):\n \"\"\"Transforms a time series dataset so that it fits the format used in\n ``sklearn`` estimators.\n\n Parameters\n ----------\n dataset : array-like\n The dataset of time series to be transformed.\n dtype : data type (default: float64)\n Data type for the returned dataset.\n return_dim : boolean (optional, default: False)\n Whether the dimensionality (third dimension should be returned together\n with the transformed dataset).\n\n Returns\n -------\n numpy.ndarray of shape (n_ts, sz * d)\n The transformed dataset of time series.\n int (optional, if return_dim=True)\n The dimensionality of the original tslearn dataset (third dimension)\n\n Examples\n --------\n >>> to_sklearn_dataset([[1, 2]], return_dim=True)\n (array([[1., 2.]]), 1)\n >>> to_sklearn_dataset([[1, 2], [1, 4, 3]])\n array([[ 1., 2., nan],\n [ 1., 4., 3.]])\n\n See Also\n --------\n to_time_series_dataset : Transforms a time series dataset to ``tslearn``\n format.\n \"\"\"\n tslearn_dataset = to_time_series_dataset(dataset, dtype=dtype)\n n_ts = tslearn_dataset.shape[0]\n d = tslearn_dataset.shape[2]\n if return_dim:\n return tslearn_dataset.reshape((n_ts, -1)), d\n else:\n return tslearn_dataset.reshape((n_ts, -1))\n\n\ndef to_pyts_dataset(X):\n \"\"\"Transform a tslearn-compatible dataset into a pyts dataset.\n\n Parameters\n ----------\n X: array, shape = (n_ts, sz, d)\n tslearn-formatted dataset to be cast to pyts format\n\n Returns\n -------\n array, shape=(n_ts, sz) if d=1, (n_ts, d, sz) otherwise\n pyts-formatted dataset\n\n Examples\n --------\n >>> tslearn_arr = numpy.random.randn(10, 16, 1)\n >>> pyts_arr = to_pyts_dataset(tslearn_arr)\n >>> pyts_arr.shape\n (10, 16)\n >>> tslearn_arr = numpy.random.randn(10, 16, 2)\n >>> pyts_arr = to_pyts_dataset(tslearn_arr)\n >>> pyts_arr.shape\n (10, 2, 16)\n >>> tslearn_arr = [numpy.random.randn(16, 1), numpy.random.randn(10, 1)]\n >>> to_pyts_dataset(tslearn_arr) # doctest: +IGNORE_EXCEPTION_DETAIL\n Traceback (most recent call last):\n ...\n ValueError: All the time series in the array should be of equal lengths\n \"\"\"\n X_ = check_dataset(X, force_equal_length=True)\n if X_.shape[2] == 1:\n return X_.reshape((X_.shape[0], -1))\n else:\n return X_.transpose((0, 2, 1))\n\n\ndef from_pyts_dataset(X):\n \"\"\"Transform a pyts-compatible dataset into a tslearn dataset.\n\n Parameters\n ----------\n X: array, shape = (n_ts, sz) or (n_ts, d, sz)\n pyts-formatted dataset\n\n Returns\n -------\n array, shape=(n_ts, sz, d)\n tslearn-formatted dataset\n\n Examples\n --------\n >>> pyts_arr = numpy.random.randn(10, 16)\n >>> tslearn_arr = from_pyts_dataset(pyts_arr)\n >>> tslearn_arr.shape\n (10, 16, 1)\n >>> pyts_arr = numpy.random.randn(10, 2, 16)\n >>> tslearn_arr = from_pyts_dataset(pyts_arr)\n >>> tslearn_arr.shape\n (10, 16, 2)\n >>> pyts_arr = numpy.random.randn(10)\n >>> from_pyts_dataset(pyts_arr) # doctest: +IGNORE_EXCEPTION_DETAIL\n Traceback (most recent call last):\n ...\n ValueError: X is not a valid input pyts array.\n \"\"\"\n X_ = check_array(X, ensure_2d=False, allow_nd=True)\n if X_.ndim == 2:\n shape = list(X_.shape) + [1]\n return X_.reshape(shape)\n elif X_.ndim == 3:\n return X_.transpose((0, 2, 1))\n else:\n raise ValueError(\"X is not a valid input pyts array. \"\n \"Its dimensions, once cast to numpy.ndarray \"\n \"are {}\".format(X_.shape))\n\n\ndef to_seglearn_dataset(X):\n \"\"\"Transform a tslearn-compatible dataset into a seglearn dataset.\n\n Parameters\n ----------\n X: array, shape = (n_ts, sz, d)\n tslearn-formatted dataset to be cast to seglearn format\n\n Returns\n -------\n array of arrays, shape=(n_ts, )\n seglearn-formatted dataset. i-th sub-array in the list has shape\n (sz_i, d)\n\n Examples\n --------\n >>> tslearn_arr = numpy.random.randn(10, 16, 1)\n >>> seglearn_arr = to_seglearn_dataset(tslearn_arr)\n >>> seglearn_arr.shape\n (10, 16, 1)\n >>> tslearn_arr = numpy.random.randn(10, 16, 2)\n >>> seglearn_arr = to_seglearn_dataset(tslearn_arr)\n >>> seglearn_arr.shape\n (10, 16, 2)\n >>> tslearn_arr = [numpy.random.randn(16, 2), numpy.random.randn(10, 2)]\n >>> seglearn_arr = to_seglearn_dataset(tslearn_arr)\n >>> seglearn_arr.shape\n (2,)\n >>> seglearn_arr[0].shape\n (16, 2)\n >>> seglearn_arr[1].shape\n (10, 2)\n \"\"\"\n X_ = check_dataset(X)\n return numpy.array([Xi[:ts_size(Xi)] for Xi in X_])\n\n\ndef from_seglearn_dataset(X):\n \"\"\"Transform a seglearn-compatible dataset into a tslearn dataset.\n\n Parameters\n ----------\n X: list of arrays, or array of arrays, shape = (n_ts, )\n seglearn-formatted dataset. i-th sub-array in the list has shape\n (sz_i, d)\n\n Returns\n -------\n array, shape=(n_ts, sz, d), where sz is the maximum of all array lengths\n tslearn-formatted dataset\n\n Examples\n --------\n >>> seglearn_arr = [numpy.random.randn(10, 1), numpy.random.randn(10, 1)]\n >>> tslearn_arr = from_seglearn_dataset(seglearn_arr)\n >>> tslearn_arr.shape\n (2, 10, 1)\n >>> seglearn_arr = [numpy.random.randn(10, 1), numpy.random.randn(5, 1)]\n >>> tslearn_arr = from_seglearn_dataset(seglearn_arr)\n >>> tslearn_arr.shape\n (2, 10, 1)\n >>> seglearn_arr = numpy.random.randn(2, 10, 1)\n >>> tslearn_arr = from_seglearn_dataset(seglearn_arr)\n >>> tslearn_arr.shape\n (2, 10, 1)\n \"\"\"\n return to_time_series_dataset(X)\n\n\ndef to_stumpy_dataset(X):\n \"\"\"Transform a tslearn-compatible dataset into a stumpy dataset.\n\n Parameters\n ----------\n X: array, shape = (n_ts, sz, d)\n tslearn-formatted dataset to be cast to stumpy format\n\n Returns\n -------\n list of arrays of shape=(d, sz_i) if d > 1 or (sz_i, ) otherwise\n stumpy-formatted dataset.\n\n Examples\n --------\n >>> tslearn_arr = numpy.random.randn(10, 16, 1)\n >>> stumpy_arr = to_stumpy_dataset(tslearn_arr)\n >>> len(stumpy_arr)\n 10\n >>> stumpy_arr[0].shape\n (16,)\n >>> tslearn_arr = numpy.random.randn(10, 16, 2)\n >>> stumpy_arr = to_stumpy_dataset(tslearn_arr)\n >>> len(stumpy_arr)\n 10\n >>> stumpy_arr[0].shape\n (2, 16)\n \"\"\"\n X_ = check_dataset(X)\n\n def transpose_or_flatten(ts):\n if ts.shape[1] == 1:\n return ts.reshape((-1, ))\n else:\n return ts.transpose()\n\n return [transpose_or_flatten(Xi[:ts_size(Xi)]) for Xi in X_]\n\n\ndef from_stumpy_dataset(X):\n \"\"\"Transform a stumpy-compatible dataset into a tslearn dataset.\n\n Parameters\n ----------\n X: list of arrays of shapes (d, sz_i) if d > 1 or (sz_i, ) otherwise\n stumpy-formatted dataset.\n\n Returns\n -------\n array, shape=(n_ts, sz, d), where sz is the maximum of all array lengths\n tslearn-formatted dataset\n\n Examples\n --------\n >>> stumpy_arr = [numpy.random.randn(10), numpy.random.randn(10)]\n >>> tslearn_arr = from_stumpy_dataset(stumpy_arr)\n >>> tslearn_arr.shape\n (2, 10, 1)\n >>> stumpy_arr = [numpy.random.randn(3, 10), numpy.random.randn(3, 5)]\n >>> tslearn_arr = from_stumpy_dataset(stumpy_arr)\n >>> tslearn_arr.shape\n (2, 10, 3)\n \"\"\"\n def transpose_or_expand(ts):\n if ts.ndim == 1:\n return ts.reshape((-1, 1))\n else:\n return ts.transpose()\n return to_time_series_dataset([transpose_or_expand(Xi) for Xi in X])\n\n\ndef to_sktime_dataset(X):\n \"\"\"Transform a tslearn-compatible dataset into a sktime dataset.\n\n Parameters\n ----------\n X: array, shape = (n_ts, sz, d)\n tslearn-formatted dataset to be cast to sktime format\n\n Returns\n -------\n Pandas data-frame\n sktime-formatted dataset (cf.\n `link <https://alan-turing-institute.github.io/sktime/examples/loading_data.html>`_)\n\n Examples\n --------\n >>> tslearn_arr = numpy.random.randn(10, 16, 1)\n >>> sktime_arr = to_sktime_dataset(tslearn_arr)\n >>> sktime_arr.shape\n (10, 1)\n >>> sktime_arr[\"dim_0\"][0].shape\n (16,)\n >>> tslearn_arr = numpy.random.randn(10, 16, 2)\n >>> sktime_arr = to_sktime_dataset(tslearn_arr)\n >>> sktime_arr.shape\n (10, 2)\n >>> sktime_arr[\"dim_1\"][0].shape\n (16,)\n\n Notes\n -----\n Conversion from/to sktime format requires pandas to be installed.\n \"\"\" # noqa: E501\n try:\n import pandas as pd\n except ImportError:\n raise ImportError(\"Conversion from/to sktime cannot be performed \"\n \"if pandas is not installed.\")\n X_ = check_dataset(X)\n X_pd = pd.DataFrame(dtype=float)\n for dim in range(X_.shape[2]):\n X_pd['dim_' + str(dim)] = [pd.Series(data=Xi[:ts_size(Xi), dim])\n for Xi in X_]\n return X_pd\n\n\ndef from_sktime_dataset(X):\n \"\"\"Transform a sktime-compatible dataset into a tslearn dataset.\n\n Parameters\n ----------\n X: pandas data-frame\n sktime-formatted dataset (cf.\n `link <https://alan-turing-institute.github.io/sktime/examples/loading_data.html>`_)\n\n Returns\n -------\n array, shape=(n_ts, sz, d)\n tslearn-formatted dataset\n\n Examples\n --------\n >>> import pandas as pd\n >>> sktime_df = pd.DataFrame()\n >>> sktime_df[\"dim_0\"] = [pd.Series([1, 2, 3]), pd.Series([4, 5, 6])]\n >>> tslearn_arr = from_sktime_dataset(sktime_df)\n >>> tslearn_arr.shape\n (2, 3, 1)\n >>> sktime_df = pd.DataFrame()\n >>> sktime_df[\"dim_0\"] = [pd.Series([1, 2, 3]),\n ... pd.Series([4, 5, 6, 7])]\n >>> sktime_df[\"dim_1\"] = [pd.Series([8, 9, 10]),\n ... pd.Series([11, 12, 13, 14])]\n >>> tslearn_arr = from_sktime_dataset(sktime_df)\n >>> tslearn_arr.shape\n (2, 4, 2)\n >>> sktime_arr = numpy.random.randn(10, 1, 16)\n >>> from_sktime_dataset(\n ... sktime_arr\n ... ) # doctest: +IGNORE_EXCEPTION_DETAIL\n Traceback (most recent call last):\n ...\n ValueError: X is not a valid input sktime array.\n\n Notes\n -----\n Conversion from/to sktime format requires pandas to be installed.\n \"\"\" # noqa: E501\n try:\n import pandas as pd\n except ImportError:\n raise ImportError(\"Conversion from/to sktime cannot be performed \"\n \"if pandas is not installed.\")\n if not isinstance(X, pd.DataFrame):\n raise ValueError(\"X is not a valid input sktime array. \"\n \"A pandas DataFrame is expected.\")\n data_dimensions = [col_name\n for col_name in X.columns\n if col_name.startswith(\"dim_\")]\n d = len(data_dimensions)\n ordered_data_dimensions = [\"dim_%d\" % di for di in range(d)]\n if sorted(ordered_data_dimensions) != sorted(data_dimensions):\n raise ValueError(\"X is not a valid input sktime array. \"\n \"Provided dimensions are not conitiguous.\"\n \"{}\".format(data_dimensions))\n n = X[\"dim_0\"].shape[0]\n max_sz = -1\n for dim_name in ordered_data_dimensions:\n for i in range(n):\n if X[dim_name][i].size > max_sz:\n max_sz = X[dim_name][i].size\n\n tslearn_arr = numpy.empty((n, max_sz, d))\n tslearn_arr[:] = numpy.nan\n for di in range(d):\n for i in range(n):\n sz = X[\"dim_%d\" % di][i].size\n tslearn_arr[i, :sz, di] = X[\"dim_%d\" % di][i].values.copy()\n return tslearn_arr\n\n\ndef to_pyflux_dataset(X):\n \"\"\"Transform a tslearn-compatible dataset into a pyflux dataset.\n\n Parameters\n ----------\n X: array, shape = (n_ts, sz, d), where n_ts=1\n tslearn-formatted dataset to be cast to pyflux format\n\n Returns\n -------\n Pandas data-frame\n pyflux-formatted dataset (cf.\n `link <https://pyflux.readthedocs.io/en/latest/getting_started.html>`_)\n\n Examples\n --------\n >>> tslearn_arr = numpy.random.randn(1, 16, 1)\n >>> pyflux_df = to_pyflux_dataset(tslearn_arr)\n >>> pyflux_df.shape\n (16, 1)\n >>> pyflux_df.columns[0]\n 'dim_0'\n >>> tslearn_arr = numpy.random.randn(1, 16, 2)\n >>> pyflux_df = to_pyflux_dataset(tslearn_arr)\n >>> pyflux_df.shape\n (16, 2)\n >>> pyflux_df.columns[1]\n 'dim_1'\n >>> tslearn_arr = numpy.random.randn(10, 16, 1)\n >>> to_pyflux_dataset(tslearn_arr) # doctest: +IGNORE_EXCEPTION_DETAIL\n Traceback (most recent call last):\n ...\n ValueError: Array should be made of a single time series (10 here)\n\n Notes\n -----\n Conversion from/to pyflux format requires pandas to be installed.\n \"\"\" # noqa: E501\n try:\n import pandas as pd\n except ImportError:\n raise ImportError(\"Conversion from/to pyflux cannot be performed \"\n \"if pandas is not installed.\")\n X_ = check_dataset(X,\n force_equal_length=True,\n force_single_time_series=True)\n X_pd = pd.DataFrame(X[0], dtype=float)\n X_pd.columns = [\"dim_%d\" % di for di in range(X_.shape[2])]\n return X_pd\n\n\ndef from_pyflux_dataset(X):\n \"\"\"Transform a pyflux-compatible dataset into a tslearn dataset.\n\n Parameters\n ----------\n X: pandas data-frame\n pyflux-formatted dataset\n\n Returns\n -------\n array, shape=(n_ts, sz, d), where n_ts=1\n tslearn-formatted dataset.\n Column order is kept the same as in the original data frame.\n\n Examples\n --------\n >>> import pandas as pd\n >>> pyflux_df = pd.DataFrame()\n >>> pyflux_df[\"dim_0\"] = numpy.random.rand(10)\n >>> tslearn_arr = from_pyflux_dataset(pyflux_df)\n >>> tslearn_arr.shape\n (1, 10, 1)\n >>> pyflux_df = pd.DataFrame()\n >>> pyflux_df[\"dim_0\"] = numpy.random.rand(10)\n >>> pyflux_df[\"dim_1\"] = numpy.random.rand(10)\n >>> pyflux_df[\"dim_2\"] = numpy.random.rand(10)\n >>> tslearn_arr = from_pyflux_dataset(pyflux_df)\n >>> tslearn_arr.shape\n (1, 10, 3)\n >>> pyflux_arr = numpy.random.randn(10, 1, 16)\n >>> from_pyflux_dataset(\n ... pyflux_arr\n ... ) # doctest: +IGNORE_EXCEPTION_DETAIL\n Traceback (most recent call last):\n ...\n ValueError: X is not a valid input pyflux array.\n\n Notes\n -----\n Conversion from/to pyflux format requires pandas to be installed.\n \"\"\"\n try:\n import pandas as pd\n except ImportError:\n raise ImportError(\"Conversion from/to pyflux cannot be performed \"\n \"if pandas is not installed.\")\n if not isinstance(X, pd.DataFrame):\n raise ValueError(\"X is not a valid input pyflux array. \"\n \"A pandas DataFrame is expected.\")\n data_dimensions = [col_name for col_name in X.columns]\n d = len(data_dimensions)\n n = 1\n\n max_sz = -1\n for dim_name in data_dimensions:\n if X[dim_name].size > max_sz:\n max_sz = X[dim_name].size\n\n tslearn_arr = numpy.empty((n, max_sz, d))\n tslearn_arr[:] = numpy.nan\n for di, dim_name in enumerate(data_dimensions):\n data = X[dim_name].values.copy()\n sz = len(data)\n tslearn_arr[0, :sz, di] = data\n return tslearn_arr\n\n\ndef to_tsfresh_dataset(X):\n \"\"\"Transform a tslearn-compatible dataset into a tsfresh dataset.\n\n Parameters\n ----------\n X: array, shape = (n_ts, sz, d)\n tslearn-formatted dataset to be cast to tsfresh format\n\n Returns\n -------\n Pandas data-frame\n tsfresh-formatted dataset (\"flat\" data frame, as described\n `there <https://tsfresh.readthedocs.io/en/latest/text/data_formats.html#input-option-1-flat-dataframe>`_)\n\n Examples\n --------\n >>> tslearn_arr = numpy.random.randn(1, 16, 1)\n >>> tsfresh_df = to_tsfresh_dataset(tslearn_arr)\n >>> tsfresh_df.shape\n (16, 3)\n >>> tslearn_arr = numpy.random.randn(1, 16, 2)\n >>> tsfresh_df = to_tsfresh_dataset(tslearn_arr)\n >>> tsfresh_df.shape\n (16, 4)\n\n Notes\n -----\n Conversion from/to tsfresh format requires pandas to be installed.\n \"\"\" # noqa: E501\n try:\n import pandas as pd\n except ImportError:\n raise ImportError(\"Conversion from/to tsfresh cannot be performed \"\n \"if pandas is not installed.\")\n X_ = check_dataset(X)\n n, sz, d = X_.shape\n dataframes = []\n for i, Xi in enumerate(X_):\n df = pd.DataFrame(columns=[\"id\", \"time\"] +\n [\"dim_%d\" % di for di in range(d)])\n Xi_ = Xi[:ts_size(Xi)]\n sz = Xi_.shape[0]\n df[\"time\"] = numpy.arange(sz)\n df[\"id\"] = numpy.zeros((sz,), dtype=int) + i\n for di in range(d):\n df[\"dim_%d\" % di] = Xi_[:, di]\n dataframes.append(df)\n return pd.concat(dataframes)\n\n\ndef from_tsfresh_dataset(X):\n \"\"\"Transform a tsfresh-compatible dataset into a tslearn dataset.\n\n Parameters\n ----------\n X: pandas data-frame\n tsfresh-formatted dataset (\"flat\" data frame, as described\n `there <https://tsfresh.readthedocs.io/en/latest/text/data_formats.html#input-option-1-flat-dataframe>`_)\n\n Returns\n -------\n array, shape=(n_ts, sz, d)\n tslearn-formatted dataset.\n Column order is kept the same as in the original data frame.\n\n Examples\n --------\n >>> import pandas as pd\n >>> tsfresh_df = pd.DataFrame(columns=[\"id\", \"time\", \"a\", \"b\"])\n >>> tsfresh_df[\"id\"] = [0, 0, 0]\n >>> tsfresh_df[\"time\"] = [0, 1, 2]\n >>> tsfresh_df[\"a\"] = [-1, 4, 7]\n >>> tsfresh_df[\"b\"] = [8, -3, 2]\n >>> tslearn_arr = from_tsfresh_dataset(tsfresh_df)\n >>> tslearn_arr.shape\n (1, 3, 2)\n >>> tsfresh_df = pd.DataFrame(columns=[\"id\", \"time\", \"a\"])\n >>> tsfresh_df[\"id\"] = [0, 0, 0, 1, 1]\n >>> tsfresh_df[\"time\"] = [0, 1, 2, 0, 1]\n >>> tsfresh_df[\"a\"] = [-1, 4, 7, 9, 1]\n >>> tslearn_arr = from_tsfresh_dataset(tsfresh_df)\n >>> tslearn_arr.shape\n (2, 3, 1)\n >>> tsfresh_df = numpy.random.randn(10, 1, 16)\n >>> from_tsfresh_dataset(\n ... tsfresh_df\n ... ) # doctest: +IGNORE_EXCEPTION_DETAIL\n Traceback (most recent call last):\n ...\n ValueError: X is not a valid input tsfresh array.\n\n Notes\n -----\n Conversion from/to tsfresh format requires pandas to be installed.\n \"\"\" # noqa: E501\n try:\n import pandas as pd\n except ImportError:\n raise ImportError(\"Conversion from/to tsfresh cannot be performed \"\n \"if pandas is not installed.\")\n if not isinstance(X, pd.DataFrame):\n raise ValueError(\"X is not a valid input tsfresh array. \"\n \"A pandas DataFrame is expected.\")\n data_dimensions = [col_name\n for col_name in X.columns\n if col_name not in [\"id\", \"time\"]]\n d = len(data_dimensions)\n all_ids = set(X[\"id\"])\n n = len(all_ids)\n\n max_sz = -1\n for ind_id in all_ids:\n sz = X[X[\"id\"] == ind_id].shape[0]\n if sz > max_sz:\n max_sz = sz\n\n tslearn_arr = numpy.empty((n, max_sz, d))\n tslearn_arr[:] = numpy.nan\n for di, dim_name in enumerate(data_dimensions):\n for i, ind_id in enumerate(all_ids):\n data_ind = X[X[\"id\"] == ind_id]\n data = data_ind[dim_name]\n sz = data_ind.shape[0]\n tslearn_arr[i, :sz, di] = data\n return tslearn_arr\n\n\ndef to_cesium_dataset(X):\n \"\"\"Transform a tslearn-compatible dataset into a cesium dataset.\n\n Parameters\n ----------\n X: array, shape = (n_ts, sz, d), where n_ts=1\n tslearn-formatted dataset to be cast to cesium format\n\n Returns\n -------\n list of cesium TimeSeries\n cesium-formatted dataset (cf.\n `link <http://cesium-ml.org/docs/api/cesium.time_series.html#cesium.time_series.TimeSeries>`_)\n\n Examples\n --------\n >>> tslearn_arr = numpy.random.randn(3, 16, 1)\n >>> cesium_ds = to_cesium_dataset(tslearn_arr)\n >>> len(cesium_ds)\n 3\n >>> cesium_ds[0].measurement.shape\n (16,)\n >>> tslearn_arr = numpy.random.randn(3, 16, 2)\n >>> cesium_ds = to_cesium_dataset(tslearn_arr)\n >>> len(cesium_ds)\n 3\n >>> cesium_ds[0].measurement.shape\n (2, 16)\n >>> tslearn_arr = [[1, 2, 3], [1, 2, 3, 4]]\n >>> cesium_ds = to_cesium_dataset(tslearn_arr)\n >>> len(cesium_ds)\n 2\n >>> cesium_ds[0].measurement.shape\n (3,)\n\n Notes\n -----\n Conversion from/to cesium format requires cesium to be installed.\n \"\"\" # noqa: E501\n try:\n from cesium.time_series import TimeSeries\n except ImportError:\n raise ImportError(\"Conversion from/to cesium cannot be performed \"\n \"if cesium is not installed.\")\n\n def transpose_or_flatten(ts):\n ts_ = ts[:ts_size(ts)]\n if ts.shape[1] == 1:\n return ts_.reshape((-1, ))\n else:\n return ts_.transpose()\n\n X_ = check_dataset(X)\n return [TimeSeries(m=transpose_or_flatten(Xi)) for Xi in X_]\n\n\ndef from_cesium_dataset(X):\n \"\"\"Transform a cesium-compatible dataset into a tslearn dataset.\n\n Parameters\n ----------\n X: list of cesium TimeSeries\n cesium-formatted dataset (cf.\n `link <http://cesium-ml.org/docs/api/cesium.time_series.html#cesium.time_series.TimeSeries>`_)\n\n Returns\n -------\n array, shape=(n_ts, sz, d)\n tslearn-formatted dataset.\n\n Examples\n --------\n >>> from cesium.time_series import TimeSeries\n >>> cesium_ds = [TimeSeries(m=numpy.array([1, 2, 3, 4]))]\n >>> tslearn_arr = from_cesium_dataset(cesium_ds)\n >>> tslearn_arr.shape\n (1, 4, 1)\n >>> cesium_ds = [\n ... TimeSeries(m=numpy.array([[1, 2, 3, 4],\n ... [5, 6, 7, 8]]))\n ... ]\n >>> tslearn_arr = from_cesium_dataset(cesium_ds)\n >>> tslearn_arr.shape\n (1, 4, 2)\n\n Notes\n -----\n Conversion from/to cesium format requires cesium to be installed.\n \"\"\" # noqa: E501\n try:\n from cesium.time_series import TimeSeries\n except ImportError:\n raise ImportError(\"Conversion from/to cesium cannot be performed \"\n \"if cesium is not installed.\")\n\n def format_to_tslearn(ts):\n try:\n ts.sort()\n except ValueError:\n warnings.warn(\"Cesium dataset could not be sorted, assuming \"\n \"it is already sorted before casting to \"\n \"tslearn format.\")\n if ts.measurement.ndim == 1:\n data = ts.measurement.reshape((1, -1))\n else:\n data = ts.measurement\n d = len(data)\n max_sz = max([len(ts_di) for ts_di in data])\n tslearn_ts = numpy.empty((max_sz, d))\n tslearn_ts[:] = numpy.nan\n for di in range(d):\n sz = data[di].shape[0]\n tslearn_ts[:sz, di] = data[di]\n return tslearn_ts\n\n if not isinstance(X, list) or \\\n [type(ts) for ts in X] != [TimeSeries] * len(X):\n raise ValueError(\"X is not a valid input cesium array. \"\n \"A list of cesium TimeSeries is expected.\")\n dataset = [format_to_tslearn(ts) for ts in X]\n return to_time_series_dataset(dataset=dataset)\n"
] | [
[
"pandas.concat",
"sklearn.utils.check_array",
"numpy.arange",
"pandas.DataFrame",
"numpy.zeros",
"numpy.empty"
]
] |
CNES/pangeo-pyinterp | [
"5f75f62a6c681db89c5aa8c74e43fc04a77418c3"
] | [
"docs/source/examples/ex_3d.py"
] | [
"\"\"\"\n****************\n3D interpolation\n****************\n\nInterpolation of a three-dimensional regular grid.\n\nTrivariate\n==========\n\nThe :py:func:`trivariate <pyinterp.trivariate>` interpolation allows obtaining\nvalues at arbitrary points in a 3D space of a function defined on a grid.\n\nThe distribution contains a 3D field ``tcw.nc`` that will be used in this help.\nThis file is located in the ``src/pyinterp/tests/dataset`` directory at the root\nof the project.\n\nThis method performs a bilinear interpolation in 2D space by considering the\naxes of longitude and latitude of the grid, then performs a linear\ninterpolation in the third dimension. Its interface is similar to the\n:py:func:`bivariate <pyinterp.bivariate>` class except for a third axis, which\nis handled by this object.\n\n.. note::\n\n When using a time axis, care must be taken to use the same unit of dates,\n between the axis defined and the dates supplied during interpolation. The\n function :py:meth:`pyinterp.TemporalAxis.safe_cast` automates this task and\n will warn you if there is an inconsistency during the date conversion.\n\"\"\"\nimport cartopy.crs\nimport matplotlib\nimport matplotlib.pyplot\nimport numpy\nimport pyinterp\nimport pyinterp.backends.xarray\nimport pyinterp.tests\nimport xarray\n\n#%%\n# The first step is to load the data into memory and create the interpolator\n# object:\nds = xarray.open_dataset(pyinterp.tests.grid3d_path())\ninterpolator = pyinterp.backends.xarray.Grid3D(ds.tcw)\n\n#%%\n# We will build a new grid that will be used to build a new interpolated grid.\n#\n# .. note ::\n#\n# The coordinates used for interpolation are shifted to avoid using the\n# points of the trivariate function.\n#\n# .. warning ::\n#\n# When using a time axis, care must be taken to use the same unit of dates,\n# between the axis defined and the dates supplied during interpolation. The\n# function :py:meth:`pyinterp.TemporalAxis.safe_cast` automates this task and\n# will warn you if there is an inconsistency during the date conversion.\nmx, my, mz = numpy.meshgrid(numpy.arange(-180, 180, 0.25) + 1 / 3.0,\n numpy.arange(-80, 80, 0.25) + 1 / 3.0,\n numpy.array([\"2002-07-02T15:00:00\"],\n dtype=\"datetime64\"),\n indexing='ij')\n\n#%%\n# We interpolate our grid using a :py:meth:`classical\n# <pyinterp.backends.xarray.Grid3D.trivariate>`:\ntrivariate = interpolator.trivariate(\n dict(longitude=mx.flatten(), latitude=my.flatten(), time=mz.flatten()))\n\n#%%\n# Bicubic on 3D grid\n# ==================\n#\n# The grid used organizes the latitudes in descending order. We ask our\n# constructor to flip this axis in order to correctly evaluate the bicubic\n# interpolation from this 3D cube (only necessary to perform a bicubic\n# interpolation).\ninterpolator = pyinterp.backends.xarray.Grid3D(ds.data_vars[\"tcw\"],\n increasing_axes=True)\n\n#%%\n# We interpolate our grid using a :py:meth:`bicubic\n# <pyinterp.backends.xarray.Grid3D.bicubic>` interpolation in space followed by\n# a linear interpolation in the temporal axis:\nbicubic = interpolator.bicubic(\n dict(longitude=mx.flatten(), latitude=my.flatten(), time=mz.flatten()))\n\n#%%\n# We transform our result cubes into a matrix.\ntrivariate = trivariate.reshape(mx.shape).squeeze(axis=2)\nbicubic = bicubic.reshape(mx.shape).squeeze(axis=2)\nlons = mx[:, 0].squeeze()\nlats = my[0, :].squeeze()\n\n#%%\n# Let's visualize our results.\nfig = matplotlib.pyplot.figure(figsize=(5, 8))\nax1 = fig.add_subplot(\n 211, projection=cartopy.crs.PlateCarree(central_longitude=180))\npcm = ax1.pcolormesh(lons,\n lats,\n trivariate.T,\n cmap='jet',\n transform=cartopy.crs.PlateCarree(),\n vmin=0,\n vmax=80)\nax1.coastlines()\nax1.set_extent([80, 170, -45, 30], crs=cartopy.crs.PlateCarree())\nax1.set_title(\"Trilinear\")\n\nax2 = fig.add_subplot(\n 212, projection=cartopy.crs.PlateCarree(central_longitude=180))\npcm = ax2.pcolormesh(lons,\n lats,\n bicubic.T,\n cmap='jet',\n transform=cartopy.crs.PlateCarree(),\n vmin=0,\n vmax=80)\nax2.coastlines()\nax2.set_extent([80, 170, -45, 30], crs=cartopy.crs.PlateCarree())\nax2.set_title(\"Spline & Linear in time\")\nfig.colorbar(pcm, ax=[ax1, ax2], shrink=0.8)\nfig.show()"
] | [
[
"numpy.arange",
"numpy.array",
"matplotlib.pyplot.figure"
]
] |
sphuber/aiida-fleur | [
"df33e9a7b993a52c15a747a4ff23be3e19832b8d",
"df33e9a7b993a52c15a747a4ff23be3e19832b8d"
] | [
"aiida_fleur/workflows/relax.py",
"aiida_fleur/tools/StructureData_util.py"
] | [
"# -*- coding: utf-8 -*-\n###############################################################################\n# Copyright (c), Forschungszentrum Jülich GmbH, IAS-1/PGI-1, Germany. #\n# All rights reserved. #\n# This file is part of the AiiDA-FLEUR package. #\n# #\n# The code is hosted on GitHub at https://github.com/JuDFTteam/aiida-fleur #\n# For further information on the license, see the LICENSE.txt file #\n# For further information please visit http://www.flapw.de or #\n# http://aiida-fleur.readthedocs.io/en/develop/ #\n###############################################################################\n\"\"\"\n In this module you find the workflow 'FleurRelaxWorkChain' for geometry optimization.\n\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import print_function\nimport copy\nimport numpy as np\nimport six\n\nfrom aiida.engine import WorkChain, ToContext, while_, if_\nfrom aiida.engine import calcfunction as cf\nfrom aiida.orm import load_node\nfrom aiida.orm import StructureData, Dict\nfrom aiida.common import AttributeDict\nfrom aiida.common.exceptions import NotExistent\n\nfrom aiida_fleur.workflows.scf import FleurScfWorkChain\nfrom aiida_fleur.calculation.fleur import FleurCalculation as FleurCalc\nfrom aiida_fleur.common.constants import BOHR_A\nfrom aiida_fleur.tools.StructureData_util import break_symmetry_wf\n\n\nclass FleurRelaxWorkChain(WorkChain):\n \"\"\"\n This workflow performs structure optimization.\n \"\"\"\n\n _workflowversion = '0.3.0'\n\n _default_wf_para = {\n 'relax_iter': 5, # Stop if not converged after so many relaxation steps\n 'film_distance_relaxation': False, # Do not relax the z coordinates\n 'force_criterion': 0.001, # Converge the force until lower this value in atomic units\n 'run_final_scf': False, # Run a final scf on the final relaxed structure\n 'break_symmetry': False, # Break the symmetry for the relaxation each atom own type\n 'change_mixing_criterion': 0.025, # After the force is smaller switch mixing scheme\n 'atoms_off': [], # Species to be switched off, '49' is reserved\n 'relaxation_type': 'atoms' # others include None and maybe in the future volume\n # None would run an scf only\n }\n\n _default_options = FleurScfWorkChain._default_options\n\n @classmethod\n def define(cls, spec):\n super().define(spec)\n spec.expose_inputs(FleurScfWorkChain, namespace='scf')\n spec.expose_inputs(FleurScfWorkChain,\n namespace='final_scf',\n exclude=('structure', 'fleur', 'fleurinp', 'remote_data'),\n namespace_options={\n 'required': False,\n })\n spec.input('wf_parameters', valid_type=Dict, required=False)\n\n spec.outline(\n cls.start,\n if_(cls.should_relax)(cls.converge_scf, cls.check_failure, while_(cls.condition)(\n cls.generate_new_fleurinp,\n cls.converge_scf,\n cls.check_failure,\n )),\n cls.get_results_relax,\n if_(cls.should_run_final_scf)(cls.run_final_scf, cls.get_results_final_scf),\n cls.return_results,\n )\n\n spec.output('output_relax_wc_para', valid_type=Dict)\n spec.output('optimized_structure', valid_type=StructureData)\n\n # exit codes\n spec.exit_code(230, 'ERROR_INVALID_INPUT_PARAM', message='Invalid workchain parameters.')\n spec.exit_code(231, 'ERROR_INPGEN_MISSING', message='If you want to run a final scf inpgen has to be there.')\n spec.exit_code(350, 'ERROR_DID_NOT_RELAX', message='Optimization cycle did not lead to convergence of forces.')\n spec.exit_code(351, 'ERROR_SCF_FAILED', message='SCF Workchains failed for some reason.')\n spec.exit_code(352, 'ERROR_NO_RELAX_OUTPUT', message='Found no relaxed structure info in the output of SCF')\n spec.exit_code(353, 'ERROR_NO_SCF_OUTPUT', message='Found no SCF output')\n spec.exit_code(354, 'ERROR_SWITCH_BFGS', message='Force is small, switch to BFGS')\n spec.exit_code(311,\n 'ERROR_VACUUM_SPILL_RELAX',\n message='FLEUR calculation failed because an atom spilled to the'\n 'vacuum during relaxation')\n spec.exit_code(313, 'ERROR_MT_RADII_RELAX', message='Overlapping MT-spheres during relaxation.')\n\n def start(self):\n \"\"\"\n Retrieve and initialize paramters of the WorkChain, validate inputs\n \"\"\"\n self.report('INFO: Started structure relaxation workflow version {}\\n'.format(self._workflowversion))\n\n self.ctx.info = [] # Collects Hints\n self.ctx.warnings = [] # Collects Warnings\n self.ctx.errors = [] # Collects Errors\n\n # Pre-initialization of some variables\n self.ctx.loop_count = 0 # Counts relax restarts\n self.ctx.forces = [] # Collects forces\n self.ctx.final_cell = None # The relaxed Bravais matrix\n self.ctx.final_atom_positions = None # Relaxed atom positions\n self.ctx.pbc = None # Boundary conditions\n self.ctx.reached_relax = False # Bool if is relaxed\n self.ctx.switch_bfgs = False # Bool if BFGS should be switched on\n self.ctx.scf_res = None # Last scf results\n self.ctx.final_structure = None # The optimized structure\n self.ctx.total_magnetic_moment = None\n\n # initialize the dictionary using defaults if no wf paramters are given\n wf_default = copy.deepcopy(self._default_wf_para)\n if 'wf_parameters' in self.inputs:\n wf_dict = self.inputs.wf_parameters.get_dict()\n else:\n wf_dict = wf_default\n\n extra_keys = []\n for key in wf_dict.keys():\n if key not in wf_default.keys():\n extra_keys.append(key)\n if extra_keys:\n error = 'ERROR: input wf_parameters for Relax contains extra keys: {}'.format(extra_keys)\n self.report(error)\n return self.exit_codes.ERROR_INVALID_INPUT_PARAM\n\n # extend wf parameters given by user using defaults\n for key, val in six.iteritems(wf_default):\n wf_dict[key] = wf_dict.get(key, val)\n self.ctx.wf_dict = wf_dict\n\n if '49' in wf_dict['atoms_off']:\n error = '\"49\" label for atoms_off is reserved for internal use'\n self.report(error)\n return self.exit_codes.ERROR_INVALID_INPUT_PARAM\n\n # Check if final scf can be run\n run_final = wf_dict.get('run_final_scf', False)\n if run_final:\n # We need inpgen to be there\n input_scf = AttributeDict(self.exposed_inputs(FleurScfWorkChain, namespace='scf'))\n\n # policy, reuse as much as possible from scf namespace\n input_final_scf = input_scf\n if 'remote_data' in input_final_scf:\n del input_final_scf.remote_data\n if 'structure' in input_final_scf:\n del input_final_scf.structure\n if 'fleurinp' in input_final_scf:\n del input_final_scf.fleurinp\n if 'wf_parameters' in input_final_scf:\n del input_final_scf.wf_parameters\n\n if 'final_scf' in self.inputs:\n # Will defaults of namespace override other given options?\n input_final_scf_given = AttributeDict(self.exposed_inputs(FleurScfWorkChain, namespace='final_scf'))\n for key, val in input_final_scf_given.items():\n input_final_scf[key] = val\n\n self.ctx.input_final_scf = input_final_scf\n if 'inpgen' not in input_scf and 'inpgen' not in input_final_scf:\n self.report('Error: Wrong input: inpgen missing for final scf.')\n return self.exit_codes.ERROR_INPGEN_MISSING\n\n def should_relax(self):\n \"\"\"\n Should we run a relaxation or only a final scf\n This allows to call the workchain to run an scf only and makes\n logic of other higher workflows a lot easier\n \"\"\"\n relaxtype = self.ctx.wf_dict.get('relaxation_type', 'atoms')\n if relaxtype is None:\n self.ctx.reached_relax = True\n return False\n else:\n return True\n\n def converge_scf(self):\n \"\"\"\n Submits :class:`aiida_fleur.workflows.scf.FleurScfWorkChain`.\n \"\"\"\n inputs = {}\n if self.ctx.loop_count:\n inputs = self.get_inputs_scf()\n else:\n inputs = self.get_inputs_first_scf()\n res = self.submit(FleurScfWorkChain, **inputs)\n return ToContext(scf_res=res)\n\n def get_inputs_first_scf(self):\n \"\"\"\n Initialize inputs for the first iteration.\n \"\"\"\n input_scf = AttributeDict(self.exposed_inputs(FleurScfWorkChain, namespace='scf'))\n input_scf.metadata.label = 'SCF_forces'\n input_scf.metadata.description = 'The SCF workchain converging forces, part of the Relax'\n\n if self.ctx.wf_dict['break_symmetry']:\n calc_para = None\n if 'calc_parameters' in input_scf:\n calc_para = input_scf.calc_parameters\n # currently we always break the full symmetry\n break_dict = Dict(dict={'atoms': ['all']}) # for provenance\n broken_sys = break_symmetry_wf(input_scf.structure, wf_para=break_dict, parameterdata=calc_para)\n input_scf.structure = broken_sys['new_structure']\n input_scf.calc_parameters = broken_sys['new_parameters']\n\n if 'wf_parameters' not in input_scf:\n scf_wf_dict = {}\n else:\n scf_wf_dict = input_scf.wf_parameters.get_dict()\n\n if 'inpxml_changes' not in scf_wf_dict:\n scf_wf_dict['inpxml_changes'] = []\n\n scf_wf_dict['mode'] = 'force'\n\n if self.ctx.wf_dict['film_distance_relaxation']:\n scf_wf_dict['inpxml_changes'].append(('set_atomgr_att', {\n 'attributedict': {\n 'force': [('relaxXYZ', 'FFT')]\n },\n 'species': 'all'\n }))\n\n for specie_off in self.ctx.wf_dict['atoms_off']:\n scf_wf_dict['inpxml_changes'].append(('set_atomgr_att_label', {\n 'attributedict': {\n 'force': [('relaxXYZ', 'FFF')]\n },\n 'atom_label': specie_off\n }))\n\n scf_wf_dict['inpxml_changes'].append(('set_atomgr_att_label', {\n 'attributedict': {\n 'force': [('relaxXYZ', 'FFF')]\n },\n 'atom_label': '49'\n }))\n\n input_scf.wf_parameters = Dict(dict=scf_wf_dict)\n\n return input_scf\n\n def get_inputs_scf(self):\n \"\"\"\n Initializes inputs for further iterations.\n \"\"\"\n input_scf = AttributeDict(self.exposed_inputs(FleurScfWorkChain, namespace='scf'))\n if 'structure' in input_scf:\n del input_scf.structure\n del input_scf.inpgen\n del input_scf.calc_parameters\n\n if 'wf_parameters' not in input_scf:\n scf_wf_dict = {}\n else:\n scf_wf_dict = input_scf.wf_parameters.get_dict()\n if 'inpxml_changes' in scf_wf_dict:\n old_changes = scf_wf_dict['inpxml_changes']\n new_changes = []\n for change in old_changes:\n if 'shift_value' not in change[0]:\n new_changes.append(change)\n scf_wf_dict['inpxml_changes'] = new_changes\n\n scf_wf_dict['mode'] = 'force'\n input_scf.wf_parameters = Dict(dict=scf_wf_dict)\n\n scf_wc = self.ctx.scf_res\n last_calc = load_node(scf_wc.outputs.output_scf_wc_para.get_dict()['last_calc_uuid'])\n\n input_scf.remote_data = last_calc.outputs.remote_folder\n if self.ctx.new_fleurinp:\n input_scf.fleurinp = self.ctx.new_fleurinp\n\n return input_scf\n\n def check_failure(self):\n \"\"\"\n Throws an exit code if scf failed\n \"\"\"\n try:\n scf_wc = self.ctx.scf_res\n except AttributeError:\n message = 'ERROR: Something went wrong I do not have new atom positions calculation'\n self.control_end_wc(message)\n return self.exit_codes.ERROR_NO_SCF_OUTPUT\n\n if not scf_wc.is_finished_ok:\n exit_statuses = FleurScfWorkChain.get_exit_statuses(['ERROR_FLEUR_CALCULATION_FAILED'])\n if scf_wc.exit_status == exit_statuses[0]:\n fleur_calc = load_node(scf_wc.outputs.output_scf_wc_para.get_dict()['last_calc_uuid'])\n if fleur_calc.exit_status == FleurCalc.get_exit_statuses(['ERROR_VACUUM_SPILL_RELAX'])[0]:\n self.control_end_wc('ERROR: Failed due to atom and vacuum overlap')\n return self.exit_codes.ERROR_VACUUM_SPILL_RELAX\n elif fleur_calc.exit_status == FleurCalc.get_exit_statuses(['ERROR_MT_RADII_RELAX'])[0]:\n self.control_end_wc('ERROR: Failed due to MT overlap')\n return self.exit_codes.ERROR_MT_RADII_RELAX\n return self.exit_codes.ERROR_SCF_FAILED\n\n def condition(self):\n \"\"\"\n Checks if relaxation criteria is achieved.\n\n :return: True if structure is optimized and False otherwise\n \"\"\"\n scf_wc = self.ctx.scf_res\n\n try:\n last_calc = load_node(scf_wc.outputs.output_scf_wc_para.dict.last_calc_uuid)\n except (NotExistent, AttributeError):\n # TODO: throw exit code\n # message = 'ERROR: Did not manage to read the largest force'\n # self.control_end_wc(message)\n # return self.exit_codes.ERROR_RELAX_FAILED\n return False\n else:\n forces_data = last_calc.outputs.relax_parameters.get_dict()['posforces'][-1]\n all_forces = []\n for force in forces_data:\n all_forces.extend(force[-3:])\n all_forces = [abs(x) for x in all_forces]\n self.ctx.forces.append(max(all_forces))\n\n largest_now = self.ctx.forces[-1]\n\n if largest_now < self.ctx.wf_dict['force_criterion']:\n self.report('INFO: Structure is converged to the largest force ' '{}'.format(self.ctx.forces[-1]))\n self.ctx.reached_relax = True\n return False\n elif largest_now < self.ctx.wf_dict['change_mixing_criterion'] and self.inputs.scf.wf_parameters['force_dict'][\n 'forcemix'] == 'straight':\n self.report('INFO: Seems it is safe to switch to BFGS. Current largest force: '\n '{}'.format(self.ctx.forces[-1]))\n self.ctx.switch_bfgs = True\n return False\n\n self.ctx.loop_count = self.ctx.loop_count + 1\n if self.ctx.loop_count == self.ctx.wf_dict['relax_iter']:\n self.report('INFO: Reached optimization iteration number {}. Largest force is {}, '\n 'force criterion is {}'.format(self.ctx.loop_count + 1, largest_now,\n self.ctx.wf_dict['force_criterion']))\n return False\n\n self.report('INFO: submit optimization iteration number {}. Largest force is {}, '\n 'force criterion is {}'.format(self.ctx.loop_count + 1, largest_now,\n self.ctx.wf_dict['force_criterion']))\n\n return True\n\n def generate_new_fleurinp(self):\n \"\"\"\n This function fetches relax.xml from the previous iteration and calls\n :meth:`~aiida_fleur.workflows.relax.FleurRelaxWorkChain.analyse_relax()`.\n New FleurinpData is stored in the context.\n \"\"\"\n # TODO do we loose provenance here, which we like to keep?\n scf_wc = self.ctx.scf_res\n last_calc = load_node(scf_wc.outputs.output_scf_wc_para.get_dict()['last_calc_uuid'])\n try:\n relax_parsed = last_calc.outputs.relax_parameters\n except NotExistent:\n return self.exit_codes.ERROR_NO_SCF_OUTPUT\n\n new_fleurinp = self.analyse_relax(relax_parsed)\n\n self.ctx.new_fleurinp = new_fleurinp\n\n @staticmethod\n def analyse_relax(relax_dict):\n \"\"\"\n This function generates a new fleurinp analysing parsed relax.xml from the previous\n calculation.\n\n **NOT IMPLEMENTED YET**\n\n :param relax_dict: parsed relax.xml from the previous calculation\n :return new_fleurinp: new FleurinpData object that will be used for next relax iteration\n \"\"\"\n # TODO: implement this function, now always use relax.xml generated in FLEUR\n should_relax = False\n if should_relax:\n return 1\n\n return None\n\n def should_run_final_scf(self):\n \"\"\"\n Check if a final scf should be run on the optimized structure\n \"\"\"\n # Since we run the final scf on the relaxed structure\n return all([self.ctx.wf_dict.get('run_final_scf', False), self.ctx.reached_relax])\n\n def get_inputs_final_scf(self):\n \"\"\"\n Initializes inputs for final scf on relaxed structure.\n \"\"\"\n input_scf = AttributeDict(self.exposed_inputs(FleurScfWorkChain, namespace='scf'))\n input_final_scf = self.ctx.input_final_scf\n\n if 'wf_parameters' not in input_final_scf:\n # use parameters wf para of relax or defaults\n if 'wf_parameters' not in input_scf:\n scf_wf_dict = {}\n else:\n scf_wf_dict = input_scf.wf_parameters.get_dict()\n if 'inpxml_changes' in scf_wf_dict:\n old_changes = scf_wf_dict['inpxml_changes']\n new_changes = []\n for change in old_changes:\n if 'shift_value' not in change[0]:\n new_changes.append(change)\n scf_wf_dict['inpxml_changes'] = new_changes\n\n scf_wf_dict['mode'] = 'density'\n input_final_scf.wf_parameters = Dict(dict=scf_wf_dict)\n structure = self.ctx.final_structure\n formula = structure.get_formula()\n input_final_scf.structure = structure\n input_final_scf.fleur = input_scf.fleur\n input_final_scf.metadata.label = 'SCF_final_{}'.format(formula)\n input_final_scf.metadata.description = ('Final SCF workchain running on optimized structure {}, '\n 'part of relax workchain'.format(formula))\n\n return input_final_scf\n\n def run_final_scf(self):\n \"\"\"\n Run a final scf for charge convergence on the optimized structure\n \"\"\"\n self.report('INFO: Running final SCF after relaxation.')\n inputs = {}\n inputs = self.get_inputs_final_scf()\n res = self.submit(FleurScfWorkChain, **inputs)\n\n return ToContext(scf_final_res=res)\n\n def get_results_relax(self):\n \"\"\"\n Generates results of the workchain.\n Creates a new structure data node which is an\n optimized structure.\n \"\"\"\n\n if self.ctx.wf_dict.get('relaxation_type', 'atoms') is None:\n input_scf = AttributeDict(self.exposed_inputs(FleurScfWorkChain, namespace='scf'))\n if 'structure' in input_scf:\n structure = input_scf.structure\n elif 'fleurinp' in input_scf:\n structure = input_scf.fleurinp.get_structuredata_ncf()\n else:\n pass\n self.ctx.final_structure = structure\n self.ctx.total_energy_last = None #total_energy\n self.ctx.total_energy_units = None #total_energy_units\n self.ctx.final_cell = structure.cell\n self.ctx.final_atom_positions = None #atom_positions\n self.ctx.atomtype_info = None\n\n return\n\n try:\n relax_out = self.ctx.scf_res.outputs.last_fleur_calc_output\n except NotExistent:\n return self.exit_codes.ERROR_NO_SCF_OUTPUT\n\n relax_out = relax_out.get_dict()\n\n try:\n cell = relax_out['relax_brav_vectors']\n atom_positions = relax_out['relax_atom_positions']\n film = relax_out['film']\n total_energy = relax_out['energy']\n total_energy_units = relax_out['energy_units']\n atomtype_info = relax_out['relax_atomtype_info']\n except KeyError:\n return self.exit_codes.ERROR_NO_RELAX_OUTPUT\n\n self.ctx.total_energy_last = total_energy\n self.ctx.total_energy_units = total_energy_units\n self.ctx.final_cell = cell\n self.ctx.final_atom_positions = atom_positions\n self.ctx.atomtype_info = atomtype_info\n\n if film == 'True':\n self.ctx.pbc = (True, True, False)\n else:\n self.ctx.pbc = (True, True, True)\n\n # we build the structure here, that way we can run an scf afterwards\n # construct it in a way which preserves the species information from the initial input structure\n if self.ctx.final_cell:\n np_cell = np.array(self.ctx.final_cell) * BOHR_A\n structure = StructureData(cell=np_cell.tolist())\n #self.report('############ {}'.format(atomtype_info))\n for i, atom in enumerate(self.ctx.final_atom_positions):\n species_name = atomtype_info[i][0]\n element = atomtype_info[i][1]\n np_pos = np.array(atom)\n pos_abs = np_pos @ np_cell\n if self.ctx.pbc == (True, True, True):\n structure.append_atom(position=(pos_abs[0], pos_abs[1], pos_abs[2]),\n symbols=element,\n name=species_name)\n else: # assume z-direction is orthogonal to xy\n structure.append_atom(position=(pos_abs[0], pos_abs[1], atom[3] * BOHR_A),\n symbols=element,\n name=species_name)\n\n structure.pbc = self.ctx.pbc\n self.ctx.final_structure = structure\n\n def get_results_final_scf(self):\n \"\"\"\n Parser some results of final scf\n \"\"\"\n\n try:\n scf_out = self.ctx.scf_final_res.outputs.last_fleur_calc_output\n except NotExistent:\n return self.exit_codes.ERROR_NO_SCF_OUTPUT\n\n scf_out_d = scf_out.get_dict()\n try:\n total_energy = scf_out_d['energy']\n total_energy_units = scf_out_d['energy_units']\n except KeyError:\n self.report('ERROR: Could not parse total energy of final scf run')\n #return self.exit_codes.ERROR_NO_RELAX_OUTPUT\n\n self.ctx.total_energy_last = total_energy\n self.ctx.total_energy_units = total_energy_units\n\n if self.ctx.wf_dict.get('relaxation_type', 'atoms') is None:\n # we need this for run through\n self.ctx.scf_res = self.ctx.scf_final_res\n\n #if jspin ==2\n try:\n total_mag = scf_out_d['total_magnetic_moment_cell']\n self.ctx.total_magnetic_moment = total_mag\n except KeyError:\n self.report('ERROR: Could not parse total magnetic moment cell of final scf run')\n\n def return_results(self):\n \"\"\"\n This function stores results of the workchain into the output nodes.\n \"\"\"\n #TODO maybe we want to have a more detailed array output node with the force and\n # position history of all atoms?\n out = {\n 'workflow_name': self.__class__.__name__,\n 'workflow_version': self._workflowversion,\n 'energy': self.ctx.total_energy_last,\n 'energy_units': self.ctx.total_energy_units,\n 'info': self.ctx.info,\n 'warnings': self.ctx.warnings,\n 'errors': self.ctx.errors,\n 'force': self.ctx.forces,\n 'force_iter_done': self.ctx.loop_count,\n # uuids in the output are bad for caching should be avoided,\n # instead better return the node.\n 'last_scf_wc_uuid': self.ctx.scf_res.uuid,\n 'total_magnetic_moment_cell': self.ctx.total_magnetic_moment,\n 'total_magnetic_moment_cell_units': 'muBohr'\n }\n outnode = Dict(dict=out)\n\n con_nodes = {}\n try:\n relax_out = self.ctx.scf_res.outputs.last_fleur_calc_output\n except NotExistent:\n relax_out = None\n if relax_out is not None:\n con_nodes['last_fleur_calc_output'] = relax_out\n\n if all([self.ctx.wf_dict.get('run_final_scf', False), self.ctx.reached_relax]):\n try:\n scf_out = self.ctx.scf_final_res.outputs.last_fleur_calc_output\n except NotExistent:\n scf_out = None\n if relax_out is not None:\n con_nodes['last_scf__output'] = scf_out\n\n # TODO: for a trajectory output node all corresponding nodes have to go into\n # con_nodes\n\n if self.ctx.final_structure is not None:\n outdict = create_relax_result_node(output_relax_wc_para=outnode,\n optimized_structure=self.ctx.final_structure,\n **con_nodes)\n else:\n outdict = create_relax_result_node(output_relax_wc_para=outnode, **con_nodes)\n\n # return output nodes\n for link_name, node in six.iteritems(outdict):\n self.out(link_name, node)\n\n if self.ctx.switch_bfgs:\n return self.exit_codes.ERROR_SWITCH_BFGS\n if not self.ctx.reached_relax:\n return self.exit_codes.ERROR_DID_NOT_RELAX\n\n def control_end_wc(self, errormsg):\n \"\"\"\n Controlled way to shutdown the workchain. It will initialize the output nodes\n The shutdown of the workchain will has to be done afterwards.\n \"\"\"\n self.report(errormsg)\n self.ctx.errors.append(errormsg)\n self.return_results()\n\n\n@cf\ndef create_relax_result_node(**kwargs):\n \"\"\"\n This calcfunction assures the right provenance (additional links)\n for ALL result nodes it takes any nodes as input\n and return a special set of nodes.\n All other inputs will be connected in the DB to these ourput nodes\n \"\"\"\n outdict = {}\n for key, val in six.iteritems(kwargs):\n if key == 'output_relax_wc_para': # should always be present\n outnode = val.clone() # dublicate node instead of circle (keep DAG)\n outnode.label = 'output_relax_wc_para'\n outnode.description = ('Contains results and information of an FleurRelaxWorkChain run.')\n outdict['output_relax_wc_para'] = outnode\n\n if key == 'optimized_structure':\n structure = val.clone() # dublicate node instead of circle (keep DAG)\n structure.label = 'optimized_structure'\n structure.description = ('Relaxed structure result of an FleurRelaxWorkChain run.')\n outdict['optimized_structure'] = structure\n\n return outdict\n",
"# -*- coding: utf-8 -*-\n###############################################################################\n# Copyright (c), Forschungszentrum Jülich GmbH, IAS-1/PGI-1, Germany. #\n# All rights reserved. #\n# This file is part of the AiiDA-FLEUR package. #\n# #\n# The code is hosted on GitHub at https://github.com/JuDFTteam/aiida-fleur #\n# For further information on the license, see the LICENSE.txt file #\n# For further information please visit http://www.flapw.de or #\n# http://aiida-fleur.readthedocs.io/en/develop/ #\n###############################################################################\n\"\"\"\nCollection of utility routines dealing with StructureData objects\n\"\"\"\n# TODO move imports to workfuncitons namespace?\n\n# from ase import *\n# from ase.lattice.surface import *\n# from ase.io import *\n\nfrom pymatgen.core.surface import generate_all_slabs #, get_symmetrically_distinct_miller_indices\nfrom pymatgen.core.surface import SlabGenerator\n\nimport numpy as np\n\nfrom aiida.plugins import DataFactory\nfrom aiida.orm import load_node\nfrom aiida.orm.nodes.data.structure import Site, Kind\nfrom aiida.engine.processes.functions import calcfunction as cf\n\n\ndef is_structure(structure):\n \"\"\"\n Test if the given input is a StructureData node, by object, id, or pk\n :param structure: AiiDA StructureData\n :return: if yes returns a StructureData node in all cases, if no returns None\n \"\"\"\n from aiida.common import NotExistent\n\n StructureData = DataFactory('structure')\n\n # Test if StructureData\n if isinstance(structure, StructureData):\n return structure\n\n try:\n structure = load_node(structure)\n if isinstance(structure, StructureData):\n return structure\n else:\n return None\n except NotExistent:\n return None\n\n\ndef is_primitive(structure):\n \"\"\"\n Checks if a structure is primitive or not,\n :param structure: AiiDA StructureData\n :return: True if the structure can not be anymore refined.\n prints False if the structure can be futher refined.\n \"\"\"\n refined_cell = find_primitive_cell(structure)\n\n prim = False\n if all(x in structure.cell for x in refined_cell.cell):\n prim = True\n return prim\n\n\n@cf\ndef rescale(inp_structure, scale):\n \"\"\"\n Rescales a crystal structures Volume, atoms stay at their same relative postions,\n therefore the absolute postions change.\n Keeps the provenance in the database.\n\n :param inp_structure: a StructureData node (pk, or uuid)\n :param scale: float scaling factor for the cell\n\n :return: New StructureData node with rescalled structure, which is linked to input Structure\n and None if inp_structure was not a StructureData\n \"\"\"\n\n return rescale_nowf(inp_structure, scale)\n\n\ndef rescale_nowf(inp_structure, scale):\n \"\"\"\n Rescales a crystal structures Volume, atoms stay at their same relative postions,\n therefore the absolute postions change.\n DOES NOT keep the provenance in the database.\n\n :param inp_structure: a StructureData node (pk, or uuid)\n :param scale: float scaling factor for the cell\n\n :return: New StructureData node with rescalled structure, which is linked to input Structure\n and None if inp_structure was not a StructureData\n \"\"\"\n\n # test if structure:\n structure = is_structure(inp_structure)\n if not structure:\n # TODO: log something\n return None\n\n the_ase = structure.get_ase()\n new_ase = the_ase.copy()\n new_ase.set_cell(the_ase.get_cell() * np.power(float(scale), 1.0 / 3), scale_atoms=True)\n rescaled_structure = DataFactory('structure')(ase=new_ase)\n rescaled_structure.label = '{} rescaled'.format(scale) #, structure.uuid)\n #uuids in node labels are bad for caching\n rescaled_structure.pbc = structure.pbc\n\n return rescaled_structure\n\n\n@cf\ndef supercell(inp_structure, n_a1, n_a2, n_a3):\n \"\"\"\n Creates a super cell from a StructureData node.\n Keeps the provenance in the database.\n\n :param StructureData: a StructureData node (pk, or uuid)\n :param scale: tuple of 3 AiiDA integers, number of cells in a1, a2, a3,\n or if cart =True in x,y,z\n\n :return: StructureData Node with supercell\n \"\"\"\n superc = supercell_ncf(inp_structure, n_a1, n_a2, n_a3)\n\n formula = inp_structure.get_formula()\n return superc\n\n\ndef supercell_ncf(inp_structure, n_a1, n_a2, n_a3):\n \"\"\"\n Creates a super cell from a StructureData node.\n Does NOT keeps the provenance in the database.\n\n :param StructureData: a StructureData node (pk, or uuid)\n :param scale: tuple of 3 AiiDA integers, number of cells in a1, a2, a3, or if cart=True in x,y,z\n\n :return: StructureData Node with supercell\n \"\"\"\n # print('in create supercell')\n # test if structure:\n structure = is_structure(inp_structure)\n if not structure:\n # TODO: log something\n return None\n old_cell = structure.cell\n old_a1 = old_cell[0]\n old_a2 = old_cell[1]\n old_a3 = old_cell[2]\n old_sites = structure.sites\n old_pbc = structure.pbc\n\n na1 = int(n_a1)\n na2 = int(n_a2)\n na3 = int(n_a3)\n\n # new cell\n new_a1 = [i * na1 for i in old_a1]\n new_a2 = [i * na2 for i in old_a2]\n new_a3 = [i * na3 for i in old_a3]\n new_cell = [new_a1, new_a2, new_a3]\n new_structure = DataFactory('structure')(cell=new_cell, pbc=old_pbc)\n\n # insert atoms\n # first create all kinds\n old_kinds = structure.kinds\n for kind in old_kinds:\n new_structure.append_kind(kind)\n\n # scale n_a1\n for site in old_sites:\n # get atom position\n kn = site.kind_name\n pos_o = site.position\n for j in range(na1):\n pos = [pos_o[i] + j * old_a1[i] for i in range(0, len(old_a1))]\n new_structure.append_site(Site(kind_name=kn, position=pos))\n\n # scale n_a2\n o_sites = new_structure.sites\n for site in o_sites:\n # get atom position\n kn = site.kind_name\n pos_o = site.position\n for j in range(1, na2): # j=0 these sites/atoms are already added\n pos = [pos_o[i] + j * old_a2[i] for i in range(0, len(old_a2))]\n new_structure.append_site(Site(kind_name=kn, position=pos))\n\n # scale n_a3\n o_sites = new_structure.sites\n for site in o_sites:\n # get atom position\n kn = site.kind_name\n pos_o = site.position\n for j in range(1, na3): # these sites/atoms are already added\n pos = [pos_o[i] + j * old_a3[i] for i in range(0, len(old_a3))]\n new_structure.append_site(Site(kind_name=kn, position=pos))\n\n formula = inp_structure.get_formula()\n new_structure.label = 'supercell of {}'.format(formula)\n new_structure.description = '{}x{}x{} supercell of {}'.format(n_a1, n_a2, n_a3, formula)\n return new_structure\n\n\n# Structure util\n# after ths is in plugin code import these in fleurinp.\ndef abs_to_rel(vector, cell):\n \"\"\"\n Converts a position vector in absolute coordinates to relative coordinates.\n\n :param vector: list or np.array of length 3, vector to be converted\n :param cell: Bravais matrix of a crystal 3x3 Array, List of list or np.array\n :return: list of legth 3 of scaled vector, or False if vector was not length 3\n \"\"\"\n\n if len(vector) == 3:\n cell_np = np.array(cell)\n inv_cell_np = np.linalg.inv(cell_np)\n postionR = np.array(vector)\n # np.matmul(inv_cell_np, postionR)#\n new_rel_post = np.matmul(postionR, inv_cell_np)\n new_rel_pos = list(new_rel_post)\n return new_rel_pos\n else:\n return False\n\n\ndef abs_to_rel_f(vector, cell, pbc):\n \"\"\"\n Converts a position vector in absolute coordinates to relative coordinates\n for a film system.\n\n :param vector: list or np.array of length 3, vector to be converted\n :param cell: Bravais matrix of a crystal 3x3 Array, List of list or np.array\n :param pbc: Boundary conditions, List or Tuple of 3 Boolean\n :return: list of legth 3 of scaled vector, or False if vector was not length 3\n \"\"\"\n # TODO this currently only works if the z-coordinate is the one with no pbc\n # Therefore if a structure with x non pbc is given this should also work.\n # maybe write a 'tranform film to fleur_film routine'?\n if len(vector) == 3:\n if not pbc[2]:\n # leave z coordinate absolute\n # convert only x and y.\n postionR = np.array(vector)\n postionR_f = np.array(postionR[:2])\n cell_np = np.array(cell)\n cell_np = np.array(cell_np[0:2, 0:2])\n inv_cell_np = np.linalg.inv(cell_np)\n # np.matmul(inv_cell_np, postionR_f)]\n new_xy = np.matmul(postionR_f, inv_cell_np)\n new_rel_pos_f = [new_xy[0], new_xy[1], postionR[2]]\n return new_rel_pos_f\n else:\n print('FLEUR can not handle this type of film coordinate')\n else:\n return False\n\n\ndef rel_to_abs(vector, cell):\n \"\"\"\n Converts a position vector in internal coordinates to absolute coordinates\n in Angstrom.\n\n :param vector: list or np.array of length 3, vector to be converted\n :param cell: Bravais matrix of a crystal 3x3 Array, List of list or np.array\n :return: list of legth 3 of scaled vector, or False if vector was not lenth 3\n \"\"\"\n if len(vector) == 3:\n cell_np = np.array(cell)\n postionR = np.array(vector)\n new_abs_post = np.matmul(postionR, cell_np)\n new_abs_pos = list(new_abs_post)\n return new_abs_pos\n else:\n return False\n\n\ndef rel_to_abs_f(vector, cell):\n \"\"\"\n Converts a position vector in internal coordinates to absolute coordinates\n in Angstrom for a film structure (2D).\n \"\"\"\n # TODO this currently only works if the z-coordinate is the one with no pbc\n # Therefore if a structure with x non pbc is given this should also work.\n # maybe write a 'tranform film to fleur_film routine'?\n if len(vector) == 3:\n postionR = np.array(vector)\n postionR_f = np.array(postionR[:2])\n cell_np = np.array(cell)\n cell_np = np.array(cell_np[0:2, 0:2])\n new_xy = np.matmul(postionR_f, cell_np)\n new_abs_pos_f = [new_xy[0], new_xy[1], postionR[2]]\n return new_abs_pos_f\n else:\n return False\n\n\n@cf\ndef break_symmetry_wf(structure, wf_para, parameterdata=None):\n \"\"\"\n This is the calcfunction of the routine break_symmetry, which\n introduces different 'kind objects' in a structure\n and names them that inpgen will make different species/atomgroups out of them.\n If nothing specified breaks ALL symmetry (i.e. every atom gets their own kind)\n\n :param structure: StructureData\n :param wf_para: ParameterData which contains the keys atoms, sites, pos (see below)\n\n 'atoms':\n python list of symbols, exp: ['W', 'Be']. This would make for\n all Be and W atoms their own kinds.\n\n 'site':\n python list of integers, exp: [1, 4, 8]. This would create for\n atom 1, 4 and 8 their own kinds.\n\n 'pos':\n python list of tuples of 3, exp [(0.0, 0.0, -1.837927), ...].\n This will create a new kind for the atom at that position.\n Be carefull the number given has to match EXACTLY the position\n in the structure.\n\n :param parameterdata: AiiDa ParameterData\n :return: StructureData, a AiiDA crystal structure with new kind specification.\n \"\"\"\n Dict = DataFactory('dict')\n if parameterdata is None:\n parameterdata = Dict(dict={})\n wf_dict = wf_para.get_dict()\n atoms = wf_dict.get('atoms', ['all'])\n sites = wf_dict.get('site', [])\n pos = wf_dict.get('pos', [])\n new_kinds_names = wf_dict.get('new_kinds_names', {})\n new_structure, para_new = break_symmetry(structure,\n atoms=atoms,\n site=sites,\n pos=pos,\n new_kinds_names=new_kinds_names,\n parameterdata=parameterdata)\n\n return {'new_structure': new_structure, 'new_parameters': para_new}\n\n\ndef break_symmetry(structure,\n atoms=None,\n site=None,\n pos=None,\n new_kinds_names=None,\n add_atom_base_lists=True,\n parameterdata=None):\n \"\"\"\n This routine introduces different 'kind objects' in a structure\n and names them that inpgen will make different species/atomgroups out of them.\n If nothing specified breaks ALL symmetry (i.e. every atom gets their own kind)\n\n :param structure: StructureData\n :param atoms: python list of symbols, exp: ['W', 'Be']. This would make for\n all Be and W atoms their own kinds.\n :param site: python list of integers, exp: [1, 4, 8]. This would create for\n atom 1, 4 and 8 their own kinds.\n :param pos: python list of tuples of 3, exp [(0.0, 0.0, -1.837927), ...].\n This will create a new kind for the atom at that position.\n Be carefull the number given has to match EXACTLY the position\n in the structure.\n :param parameterdata: Dict node, containing calculation_parameters, however,\n this only works well if you prepare already a node for containing\n the atom lists from the symmetry breaking, or lists without ids.\n :param add_atom_base_lists: Bool (default True), if the atom base lists should be added or not\n :return: StructureData, a AiiDA crystal structure with new kind specification.\n :return: DictData, a AiiDA dict with new parameters for inpgen.\n \"\"\"\n if atoms is None:\n atoms = ['all']\n\n if site is None:\n site = []\n\n if pos is None:\n pos = []\n\n if new_kinds_names is None:\n new_kinds_names = {}\n write_new_kind_names = False\n else:\n write_new_kind_names = True\n from aiida.common.constants import elements as PeriodicTableElements\n from aiida.orm import Dict\n\n _atomic_numbers = {data['symbol']: num for num, data in PeriodicTableElements.items()}\n\n # get all atoms, get the symbol of the atom\n # if wanted make individual kind for that atom\n # kind names will be atomsymbol+number\n # create new structure with new kinds and atoms\n symbol_count = {} # Counts the atom symbol occurrence to set id's and kind names right\n replace = [] # all atoms symbols ('W') to be replaced\n replace_siteN = [] # all site integers to be replaced\n replace_pos = [] # all the atom positions to be replaced\n para_new = None\n kind_name_id_mapping = {}\n\n struc = is_structure(structure)\n if not struc:\n print('Error, no structure given')\n # throw error?\n return None, None\n\n cell = struc.cell\n pbc = struc.pbc\n sites = struc.sites\n new_structure = DataFactory('structure')(cell=cell, pbc=pbc)\n\n for sym in atoms:\n replace.append(sym)\n for position in pos:\n replace_pos.append(position)\n for atom in site:\n replace_siteN.append(atom)\n\n for i, site_c in enumerate(sites):\n # get site info\n kind_name = site_c.kind_name\n pos = site_c.position\n kind = struc.get_kind(kind_name)\n symbol = kind.symbol\n replace_kind = False\n\n # check if kind to replace is in inputs\n if symbol in replace or 'all' in replace:\n replace_kind = True\n if pos in replace_pos:\n replace_kind = True\n if i in replace_siteN:\n replace_kind = True\n\n if replace_kind:\n symbol_count[symbol] = symbol_count.get(symbol, 0) + 1\n symbol_new_kinds_names = new_kinds_names.get(symbol, [])\n if symbol_new_kinds_names and ((len(symbol_new_kinds_names)) == symbol_count[symbol]):\n newkindname = symbol_new_kinds_names[symbol_count[symbol] - 1]\n kind_name_id_mapping[newkindname] = symbol_count[symbol] - 1\n else:\n newkindname = '{}{}'.format(symbol, symbol_count[symbol])\n kind_name_id_mapping[newkindname] = symbol_count[symbol]\n new_kind = Kind(name=newkindname, symbols=symbol)\n new_structure.append_kind(new_kind)\n\n else:\n newkindname = kind_name\n if not kind_name in new_structure.get_kind_names():\n new_structure.append_kind(kind)\n new_structure.append_site(Site(kind_name=newkindname, position=pos))\n\n # update parameter data\n if parameterdata is not None:\n # TODO This may not enough, since for magnetic systems one need a kind mapping\n # i.e if the parameters are for a partly 'pre symmetry broken system'\n # and we want to keep track from which 'old' kind which new kind spawn\n para_new = adjust_calc_para_to_structure(parameterdata,\n new_structure,\n add_atom_base_lists=add_atom_base_lists,\n write_new_kind_names=write_new_kind_names)\n\n new_structure.label = structure.label\n new_structure.description = structure.description + 'more kinds, less sym'\n\n return new_structure, para_new\n\n\ndef adjust_calc_para_to_structure(parameter, structure, add_atom_base_lists=True, write_new_kind_names=False):\n \"\"\"\n Adjust calculation parameters for inpgen to a given structure with several kinds\n\n Rules:\n 1. Only atom lists are changed in the parameter node\n 2. If at least one atomlist of a certain element is in parameter\n all kinds with this elements will have atomlists in the end\n 3. For a certain kind which has no atom list yet and at least one list with such an element\n exists it gets the parameters from the atom list with the lowest number (while atom<atom0<atom1)\n 4. Atom lists with ids are preserved\n\n :param parameter: aiida.orm.Dict node containing calc parameters\n :param structure: aiida.orm.StructureData node containing a crystal structure\n :param add_atom_base_lists: Bool (default True), if the atom base lists should be added or not\n :return: new aiida.orm.Dict with new calc_parameters\n \"\"\"\n from aiida.common.constants import elements as PeriodicTableElements\n from aiida import orm\n atomic_numbers = {data['symbol']: num for num, data in PeriodicTableElements.items()}\n\n param_new_dict = {}\n para_dict = parameter.get_dict()\n atom_lists = []\n j = 1\n for key in sorted(para_dict):\n val = para_dict[key]\n if 'atom' in key:\n atom_lists.append(val)\n if add_atom_base_lists:\n if not 'id' in val:\n atomlistname = 'atom{}'.format(j)\n param_new_dict[atomlistname] = val\n j = j + 1\n else:\n param_new_dict[key] = val\n\n for i, kind in enumerate(structure.kinds):\n symbol = kind.symbol\n atomic_number = atomic_numbers.get(symbol)\n kind_name = kind.name\n try:\n # Kind names can be more then numbers now, this might need to be reworked\n # Every string without a number excepts and will be ignored/assumed covered by base lists\n head = kind_name.rstrip('0123456789')\n kind_namet = int(kind_name[len(head):])\n except ValueError:\n # base lists are already added\n kind_namet = None\n should_id = None\n continue\n\n should_id = '{}.{}'.format(atomic_number, kind_namet)\n # check if atom list with id was given if yes use that one\n found_kind = False\n for atomlst in atom_lists:\n if atomlst.get('id', None) == should_id:\n #if atomlst.get('element', None) != symbol or atomlst.get('z', None) != atomic_number:\n # continue # None id, but wrong element\n atomlistname = 'atom{}'.format(j)\n param_new_dict[atomlistname] = atomlst\n j = j + 1\n found_kind = True\n\n if found_kind:\n continue\n\n # we have to create a new list with right id\n # get first list which has element or charge in given list\n for atomlst in atom_lists:\n if atomlst.get('element', None) == symbol or atomlst.get('z', None) == atomic_number:\n new_alst = atomlst.copy()\n new_alst['id'] = should_id\n if write_new_kind_names:\n new_alst[u'name'] = kind_name\n atomlistname = 'atom{}'.format(j)\n param_new_dict[atomlistname] = new_alst\n j = j + 1\n\n return orm.Dict(dict=param_new_dict)\n\n\ndef check_structure_para_consistent(parameter, structure, verbose=True):\n \"\"\"\n Check if the given calculation parameters for inpgen match to a given structure\n\n If parameter contains atom lists which do not fit to any kind in the structure,\n false is returned\n This knows how the FleurinputgenCalculation prepares structures.\n\n :param parameter: aiida.orm.Dict node containing calc parameters\n :param structure: aiida.orm.StructureData node containing a crystal structure\n\n :return: Boolean, True if parameter is consistent to structure\n \"\"\"\n from aiida.common.constants import elements as PeriodicTableElements\n atomic_numbers = {data['symbol']: num for num, data in PeriodicTableElements.items()}\n\n consistent = True\n para_dict = parameter.get_dict()\n kinds = structure.kinds\n kind_symbols = [kind.symbol for kind in kinds]\n kind_charges = [atomic_numbers[kind.symbol] for kind in kinds]\n kind_names = [kind.name for kind in kinds]\n possible_ids = []\n for i, kind_name in enumerate(kind_names):\n try:\n # Kind names can be more then numbers now, this might need to be reworked\n head = kind_name.rstrip('0123456789')\n kind_namet = int(kind_name[len(head):])\n except ValueError:\n pass\n #print('Warning: Kind name {} will be ignored by a FleurinputgenCalculation and not set a charge number. id'.\n # format(kind_name))\n else:\n atomic_number_name = '{}.{}'.format(kind_charges[i], kind_namet)\n possible_ids.append(atomic_number_name)\n # Id can also be integer number only?\n\n # Now perform the consitency check\n for key, val in para_dict.items():\n if 'atom' in key:\n if 'z' in val:\n if val['z'] not in kind_charges:\n consistent = False\n if not verbose:\n print('Charge z in atomlist {} is not consistent with structure.'.format(key))\n if 'element' in val:\n if val['element'] not in kind_symbols:\n consistent = False\n if not verbose:\n print('Element in atomlist {} is not consistent with structure.'.format(key))\n if 'id' in val:\n if str(val['id']) not in possible_ids:\n consistent = False\n if not verbose:\n print('Id in atomlist {} is not consistent with kinds in structure.'.format(key))\n\n return consistent\n\n\n'''\n# TODO: Bug: parameter data production not right...to many atoms list if break sym of everything\ndef break_symmetry(structure, atoms=None, site=None, pos=None, new_kinds_names=None, add_atom_base_lists=False, parameterdata=None):\n \"\"\"\n This routine introduces different 'kind objects' in a structure\n and names them that inpgen will make different species/atomgroups out of them.\n If nothing specified breaks ALL symmetry (i.e. every atom gets their own kind)\n\n :param structure: StructureData\n :param atoms: python list of symbols, exp: ['W', 'Be']. This would make for\n all Be and W atoms their own kinds.\n :param site: python list of integers, exp: [1, 4, 8]. This would create for\n atom 1, 4 and 8 their own kinds.\n :param pos: python list of tuples of 3, exp [(0.0, 0.0, -1.837927), ...].\n This will create a new kind for the atom at that position.\n Be carefull the number given has to match EXACTLY the position\n in the structure.\n :param parameterdata: Dict node, containing calculation_parameters, however, this only works well\n if you prepare already a node for containing the atom lists from the symmetry breaking,\n or lists without ids.\n :return: StructureData, a AiiDA crystal structure with new kind specification.\n :return: DictData, a AiiDA dict with new parameters for inpgen.\n \"\"\"\n if atoms is None:\n atoms = ['all']\n\n if site is None:\n site = []\n\n if pos is None:\n pos = []\n\n if new_kinds_names is None:\n new_kinds_names = {}\n\n from aiida.common.constants import elements as PeriodicTableElements\n from aiida.orm import Dict\n\n _atomic_numbers = {data['symbol']: num for num, data in PeriodicTableElements.items()}\n\n # get all atoms, get the symbol of the atom\n # if wanted make individual kind for that atom\n # kind names will be atomsymbol+number\n # create new structure with new kinds and atoms\n # Param = DataFactory('dict')\n symbol_count = {} # Counts the atom symbol occurrence to set id's and kind names right\n replace = [] # all atoms symbols ('W') to be replaced\n replace_siteN = [] # all site integers to be replaced\n replace_pos = [] # all the atom positions to be replaced\n new_parameterd = None\n kind_name_id_mapping = {}\n\n struc = is_structure(structure)\n if not struc:\n print('Error, no structure given')\n # throw error?\n\n cell = struc.cell\n pbc = struc.pbc\n sites = struc.sites\n # natoms = len(sites)\n new_structure = DataFactory('structure')(cell=cell, pbc=pbc)\n\n for sym in atoms:\n replace.append(sym)\n for position in pos:\n replace_pos.append(position)\n for atom in site:\n replace_siteN.append(atom)\n\n for i, site_c in enumerate(sites):\n # get site info\n kind_name = site_c.kind_name\n pos = site_c.position\n kind = struc.get_kind(kind_name)\n symbol = kind.symbol\n replace_kind = False\n\n # check if kind to replace is in inputs\n if symbol in replace or 'all' in replace:\n replace_kind = True\n if pos in replace_pos:\n replace_kind = True\n if i in replace_siteN:\n replace_kind = True\n\n if replace_kind:\n symbol_count[symbol] = symbol_count.get(symbol, 0) + 1\n symbol_new_kinds_names = new_kinds_names.get(symbol, [])\n if symbol_new_kinds_names and ((len(symbol_new_kinds_names)) == symbol_count[symbol]):\n newkindname = symbol_new_kinds_names[symbol_count[symbol] - 1]\n kind_name_id_mapping[newkindname] = symbol_count[symbol]-1\n else:\n newkindname = '{}{}'.format(symbol, symbol_count[symbol])\n kind_name_id_mapping[newkindname] = symbol_count[symbol]\n new_kind = Kind(name=newkindname, symbols=symbol)\n new_structure.append_kind(new_kind)\n\n else:\n newkindname = kind_name\n if not kind_name in new_structure.get_kind_names():\n new_structure.append_kind(kind)\n new_structure.append_site(Site(kind_name=newkindname, position=pos))\n\n # now we have to add an atom list to parameterdata with the corresponding id.\n # generate possible IDs\n #symbol_count_added = {symbol: 0 for symbol in symbol_count.keys()}\n symbol_possible_ids = {}\n for key, val in symbol_count.items():\n symbol_possible_ids[key] = [i+1 for i in range(val)]\n new_parameterd = {}\n if parameterdata:\n para = parameterdata.get_dict()\n'''\n'''\n for i, kind in enumerate(new_structure.kinds):\n # for each kind in structure add an individual atom list to parameterdata with id\n # as long as there was some predefined atom list for such an element\n # use the first one you find as base for all new\n # if there is an atom list with such an id use that one\n atomlistname = 'atom{}'.format(i)\n symbol = kind.symbol\n kind_found = False\n for key in sorted(para):\n val = para[key]\n if 'atom' in key:\n # ignore atom lists elements not to break sym for.\n # we also only use the first one we find.\n # therefore best to give only one atom list per element\n if val.get('element', None) != symbol:\n if val.get('z', None) != _atomic_numbers.get(symbol):\n continue\n # we have a list of a kind we did something for\n el_id = str(val.get('id', '0.0'))\n # 0.0 because if case where id is no specified\n # cast str since sometimes people might give as float\n # id has the form Int.Int\n el_id = int(el_id.split('.')[1])\n ids = symbol_possible_ids.get(symbol)\n if el_id in ids: #id_a == el_id and el_id > 0:\n new_parameterd[atomlistname] = val\n ids.remove(el_id)\n symbol_possible_ids[symbol] = ids\n kind_found = True\n break # we assume the user is smart and provides a para node,\n # which incorporates the symmetry breaking already\n # but we need to see all atom lists to know if it is there...\n if kind_found:\n continue\n for key in sorted(para):\n val = para[key]\n if 'atom' in key:\n if val.get('element', None) != symbol:\n if val.get('z', None) != _atomic_numbers.get(symbol):\n continue\n el_id = str(val.get('id', '0.0'))\n el_id = int(el_id.split('.')[1])\n ids = symbol_possible_ids.get(symbol)\n # copy parameter of symbol and add id\n # this would be the lowest predefined atom list of an element\n val_new = {}\n val_new.update(val)\n charge = _atomic_numbers.get((val.get('element', None)))\n if charge is None:\n charge = val.get('z', None)\n idp = '{}.{}'.format(charge, ids[0])\n ids.remove(el_id)\n idp = float('{0:.2f}'.format(float(idp)))\n # dot cannot be stored in AiiDA dict...\n val_new.update({u'id': idp})\n atomlistname = 'atom{}'.format(i)#id_a)\n # Since there are other atoms list also find the next\n # free atom key.\n #j = 0\n #while new_parameterd.get(atomlistname, {}):\n # j = j + 1\n # atomlistname = 'atom{}'.format(id_a + i)\n #symbol_new_kinds_names = new_kinds_names.get(symbol, [])\n # print(symbol_new_kinds_names)\n #if symbol_new_kinds_names and ((len(symbol_new_kinds_names)) == symbol_count[symbol]):\n # species_name = symbol_new_kinds_names[symbol_count[symbol] - 1]\n # val_new.update({u'name': species_name})\n new_parameterd[atomlistname] = val_new\n break # max one new atom list per kind\n'''\n'''\n # add other non atom keys from original parameterdata\n for key, val in para.items():\n if 'atom' not in key:\n new_parameterd[key] = val\n elif add_atom_base_lists:\n if not 'id' in val:\n new_parameterd[key] = val\n para_new = Dict(dict=new_parameterd)\n else:\n para_new = None\n\n print(new_parameterd)\n new_structure.label = structure.label\n new_structure.description = structure.description + 'more kinds, less sym'\n\n return new_structure, para_new\n'''\n\n\ndef find_equi_atoms(structure): # , sitenumber=0, position=None):\n \"\"\"\n This routine uses spglib and ASE to provide informations of all equivivalent\n atoms in the cell.\n\n :param structure: AiiDA StructureData\n\n :return: equi_info_symbol, list of lists ['element': site_indexlist, ...]\n len(equi_info_symbol) = number of symmetryatomtypes\n and n_equi_info_symbol, dict {'element': numberequiatomstypes}\n \"\"\"\n import spglib\n\n equi_info = []\n equi_info_symbol = []\n n_equi_info_symbol = {}\n k_symbols = {}\n\n s_ase = structure.get_ase()\n sym = spglib.get_symmetry(s_ase, symprec=1e-5)\n equi = sym['equivalent_atoms']\n unique = np.unique(equi)\n\n for uni in unique:\n equi_info.append(np.where(equi == uni)[0])\n\n sites = structure.sites\n kinds = structure.kinds\n\n for kind in kinds:\n k_symbols[kind.name] = kind.symbol\n\n for equi in equi_info:\n kind = sites[equi[0]].kind_name\n element = k_symbols[kind]\n n_equi_info_symbol[element] = n_equi_info_symbol.get(element, 0) + 1\n equi_info_symbol.append([element, equi])\n\n return equi_info_symbol, n_equi_info_symbol\n\n\ndef get_spacegroup(structure):\n \"\"\"\n :param structure: AiiDA StructureData\n :return: the spacegroup (spglib class) of a given AiiDA structure\n \"\"\"\n import spglib\n s_ase = structure.get_ase()\n spacegroup = spglib.get_spacegroup(s_ase, symprec=1e-5)\n return spacegroup\n\n\n@cf\n# , _label='move_atoms_in_unitcell_wf', _description='WF, that moves all atoms in a unit cell by a given vector'):#Float1, Float2, Float3, test=None):\ndef move_atoms_incell_wf(structure, wf_para):\n \"\"\"\n moves all atoms in a unit cell by a given vector\n\n :param structure: AiiDA structure\n :param wf_para: AiiDA Dict node with vector: tuple of 3, or array\n (currently 3 AiiDA Floats to make it a wf,\n In the future maybe a list or vector if AiiDa basetype exists)\n :return: AiiDA stucture\n \"\"\"\n wf_para_dict = wf_para.get_dict()\n vector = wf_para_dict.get('vector', [0.0, 0.0, 0.0])\n # [Float1, Float2, Float3])\n new_structure = move_atoms_incell(structure, vector)\n\n return {'moved_struc': new_structure}\n\n\ndef move_atoms_incell(structure, vector):\n \"\"\"\n moves all atoms in a unit cell by a given vector\n\n :param structure: AiiDA structure\n :param vector: tuple of 3, or array\n :return: AiiDA structure\n \"\"\"\n\n StructureData = DataFactory('structure')\n new_structure = StructureData(cell=structure.cell)\n new_structure.pbc = structure.pbc\n sites = structure.sites\n for kind in structure.kinds:\n new_structure.append_kind(kind)\n\n for site in sites:\n pos = site.position\n new_pos = np.around(np.array(pos) + np.array(vector), decimals=10)\n new_site = Site(kind_name=site.kind_name, position=new_pos)\n new_structure.append_site(new_site)\n new_structure.label = structure.label\n\n new_structure.label = structure.label\n new_structure.description = structure.description + 'moved'\n return new_structure\n\n\ndef find_primitive_cell(structure):\n \"\"\"\n uses spglib find_primitive to find the primitive cell\n\n :param sructure: AiiDA structure data\n :return: list of new AiiDA structure data\n \"\"\"\n # TODO: if refinced structure is the same as given structure\n # return the given structure (Is this good practise for prov?)\n from spglib import find_primitive\n from ase.atoms import Atoms\n StructureData = DataFactory('structure')\n\n symprec = 1e-7\n # print('old {}'.format(len(structure.sites)))\n ase_structure = structure.get_ase()\n lattice, scaled_positions, numbers = find_primitive(ase_structure, symprec=symprec)\n new_structure_ase = Atoms(numbers, scaled_positions=scaled_positions, cell=lattice, pbc=True)\n new_structure = StructureData(ase=new_structure_ase)\n # print('new {}'.format(len(new_structure.sites)))\n\n new_structure.label = structure.label + ' primitive'\n new_structure.description = structure.description + ' primitive cell'\n return new_structure\n\n\n@cf\ndef find_primitive_cell_wf(structure):\n \"\"\"\n uses spglib find_primitive to find the primitive cell\n :param structure: AiiDa structure data\n\n :return: list of new AiiDa structure data\n \"\"\"\n\n return {'primitive_cell': find_primitive_cell(structure)}\n\n\ndef find_primitive_cells(uuid_list):\n \"\"\"\n uses spglib find_primitive to find the primitive cell\n :param uuid_list: list of structureData uuids, or pks\n\n :return: list of new AiiDa structure datas\n \"\"\"\n\n new_structures = []\n for uuid in uuid_list:\n structure = load_node(uuid)\n new_structure = find_primitive_cell(structure)\n new_structures.append(new_structure)\n return new_structures\n\n\ndef get_all_miller_indices(structure, highestindex):\n \"\"\"\n wraps the pymatgen function get_symmetrically_distinct_miller_indices for an AiiDa structure\n \"\"\"\n from pymatgen.core.surface import get_symmetrically_distinct_miller_indices\n return get_symmetrically_distinct_miller_indices(structure.get_pymatgen_structure(), highestindex)\n\n\n'''\ndef create_all_slabs_buggy(initial_structure,\n miller_index,\n min_slab_size_ang,\n min_vacuum_size=0,\n bonds=None,\n tol=1e-3,\n max_broken_bonds=0,\n lll_reduce=False,\n center_slab=False,\n primitive=False,\n max_normal_search=None,\n symmetrize=False): # , reorient_lattice=True):\n \"\"\"\n wraps the pymatgen function generate_all_slabs with some useful extras\n :return: a dictionary of structures\n \"\"\"\n StructureData = DataFactory('structure')\n aiida_strucs = {}\n pymat_struc = initial_structure.get_pymatgen_structure()\n # currently the pymatgen method is buggy... no coordinates in x,y....\n all_slabs = generate_all_slabs(pymat_struc,\n miller_index,\n min_slab_size_ang,\n min_vacuum_size,\n bonds=bonds,\n tol=tol,\n max_broken_bonds=max_broken_bonds,\n lll_reduce=lll_reduce,\n center_slab=center_slab,\n primitive=primitive,\n max_normal_search=max_normal_search,\n symmetrize=symmetrize) # , reorient_lattice=reorient_lattice)\n for slab in all_slabs:\n # print(slab)\n # slab2 = #slab.get_orthogonal_c_slab()\n film_struc = StructureData(pymatgen_structure=slab)\n film_struc.pbc = (True, True, False)\n aiida_strucs[slab.miller_index] = film_struc\n return aiida_strucs\n'''\n\n\ndef create_all_slabs(initial_structure,\n miller_index,\n min_slab_size_ang,\n min_vacuum_size=0,\n bonds=None,\n tol=1e-3,\n max_broken_bonds=0,\n lll_reduce=False,\n center_slab=False,\n primitive=False,\n max_normal_search=1,\n symmetrize=False): # , reorient_lattice=True):\n \"\"\"\n :return: a dictionary of structures\n \"\"\"\n StructureData = DataFactory('structure')\n aiida_strucs = {}\n # pymat_struc = initial_structure.get_pymatgen_structure()\n indices = get_all_miller_indices(initial_structure, miller_index)\n for index in indices:\n slab = create_slap(initial_structure, index, min_slab_size_ang, min_vacuum_size, min_slab_size_ang)\n #film_struc = StructureData(pymatgen_structure=slab)\n #film_struc.pbc = (True, True, False)\n aiida_strucs[index] = slab\n\n return aiida_strucs\n\n\ndef create_slap(initial_structure,\n miller_index,\n min_slab_size,\n min_vacuum_size=0,\n lll_reduce=False,\n center_slab=False,\n primitive=False,\n max_normal_search=1,\n reorient_lattice=True):\n \"\"\"\n wraps the pymatgen slab generator\n \"\"\"\n # minimum slab size is in Angstrom!!!\n StructureData = DataFactory('structure')\n pymat_struc = initial_structure.get_pymatgen_structure()\n slabg = SlabGenerator(pymat_struc,\n miller_index,\n min_slab_size,\n min_vacuum_size,\n lll_reduce=lll_reduce,\n center_slab=center_slab,\n primitive=primitive,\n max_normal_search=max_normal_search)\n slab = slabg.get_slab()\n # slab2 = slab.get_orthogonal_c_slab()\n film_struc = StructureData(pymatgen_structure=slab)\n film_struc.pbc = (True, True, False)\n\n # TODO: sort atoms after z-coordinate value,\n # TODO: Move all atoms that the middle atom is at [x,y,0]\n # film_struc2 = move_atoms_incell(film_struc, [0,0, z_of_middle atom])\n\n return film_struc\n\n\n@cf\ndef center_film_wf(structure):\n \"\"\"\n Centers a film at z=0, keeps the provenance in the database\n\n :param structure: AiiDA structure\n\n :return: AiiDA structure\n \"\"\"\n return center_film(structure)\n\n\ndef center_film(structure):\n \"\"\"\n Centers a film at z=0\n\n :param structure: AiiDA structure\n\n :return: AiiDA structure\n \"\"\"\n if structure.pbc != (True, True, False):\n raise TypeError('Only film structures having surface normal to z are supported')\n sorted_struc = sort_atoms_z_value(structure)\n sites = sorted_struc.sites\n shift = [0, 0, -(sites[0].position[2] + sites[-1].position[2]) / 2.0]\n\n return move_atoms_incell(sorted_struc, shift)\n\n\ndef sort_atoms_z_value(structure):\n \"\"\"\n Resorts the atoms in a structure by there Z-value\n\n :param structure: AiiDA structure\n :return: AiiDA structure\n \"\"\"\n StructureData = DataFactory('structure')\n new_structure = StructureData(cell=structure.cell)\n new_structure.pbc = structure.pbc\n for kind in structure.kinds:\n new_structure.append_kind(kind)\n\n sites = structure.sites\n new_site_list = []\n for site in sites:\n new_site_list.append([site, site.position[2]])\n sorted_sites = sorted(new_site_list, key=lambda position: position[1])\n for site in sorted_sites:\n new_structure.append_site(site[0])\n\n return new_structure\n\n\ndef create_manual_slab_ase(lattice='fcc',\n miller=None,\n host_symbol='Fe',\n latticeconstant=4.0,\n size=(1, 1, 5),\n replacements=None,\n decimals=10,\n pop_last_layers=0,\n inverse=False):\n \"\"\"\n Wraps ase.lattice lattices generators to create a slab having given lattice vectors directions.\n\n :param lattice: 'fcc' and 'bcc' are supported. Set the host lattice of a slab.\n :param miller: a list of directions of lattice vectors\n :param symbol: a string specifying the atom type\n :param latticeconstant: the lattice constant of a structure\n :param size: a 3-element tuple that sets supercell size. For instance, use (1,1,5) to set\n 5 layers of a slab.\n :param decimals: sets the rounding of atom positions. See numpy.around.\n :param pop_last_layers: specifies how many bottom layers to remove. Sometimes one does not want\n to use the integer number of unit cells along z, extra layers can be\n removed.\n :return structure: an ase-lattice representing a slab with replaced atoms\n\n \"\"\"\n if miller is None:\n miller = [[1, 0, 0], [0, 1, 0], [0, 0, 1]]\n\n if lattice == 'fcc':\n from ase.lattice.cubic import FaceCenteredCubic\n structure_factory = FaceCenteredCubic\n elif lattice == 'bcc':\n from ase.lattice.cubic import BodyCenteredCubic\n structure_factory = BodyCenteredCubic\n else:\n raise ValueError('The given lattice {} is not supported'.format(lattice))\n\n structure = structure_factory(miller=miller,\n symbol=host_symbol,\n pbc=(1, 1, 0),\n latticeconstant=latticeconstant,\n size=size)\n\n *_, layer_occupancies = get_layers(structure)\n\n if replacements is not None:\n keys = list(replacements.keys())\n if max((abs(int(x)) for x in keys)) >= len(layer_occupancies):\n raise ValueError('\"replacements\" has to contain numbers less than number of layers:'\n ' {}'.format(len(layer_occupancies)))\n else:\n replacements = {}\n\n layer_occupancies.append(0) # technical append\n atoms_to_pop = np.cumsum(np.array(layer_occupancies[-1::-1]))\n for i in range(atoms_to_pop[pop_last_layers]):\n structure.pop()\n\n current_symbols = structure.get_chemical_symbols()\n positions = structure.positions\n\n zipped = zip(positions, current_symbols)\n zipped = sorted(zipped, key=lambda x: x[0][2])\n\n positions = [x for x, _ in zipped]\n current_symbols = [x for _, x in zipped]\n structure.set_chemical_symbols(current_symbols)\n structure.set_positions(positions)\n\n *_, layer_occupancies = get_layers(structure)\n layer_occupancies.insert(0, 0)\n for i, at_type in replacements.items():\n if isinstance(i, str):\n i = int(i)\n if i < 0:\n i = i - 1\n atoms_to_skip = np.cumsum(np.array(layer_occupancies))[i]\n for k in range(layer_occupancies[i + 1]):\n current_symbols[k + atoms_to_skip] = at_type\n structure.set_chemical_symbols(current_symbols)\n\n if inverse:\n structure.positions[:, 2] = -structure.positions[:, 2]\n structure.positions = np.around(structure.positions, decimals=decimals)\n else:\n structure.positions = np.around(structure.positions, decimals=decimals)\n\n return structure\n\n\ndef magnetic_slab_from_relaxed(relaxed_structure,\n orig_structure,\n total_number_layers,\n num_relaxed_layers,\n tolerance_decimals=10):\n \"\"\"\n Transforms a structure that was used for interlayer distance relaxation to\n a structure that can be further used for magnetic calculations.\n\n Usually one uses a slab having z-reflection symmetry e.g. A-B1-B2-B3-B2-B1-A where A is\n a magnetic element (Fe, Ni, Co, Cr) and B is a substrate. However, further magnetic\n calculations are done using assymetric slab A-B1-B2-B3-B4-B5-B6-B7-B8. The function uses\n A-B1, B1-B2 etc. iterlayer distances for constraction of assymetric relaxed film.\n\n The function works as follows: it constructs a new StructureData object taking x and y positions\n from the orig_structure and z positions from relax_structure for first num_relaxed_interlayers.\n Then it appends orig_structure slab to the bottom it a way the total number of layers is\n total_number_layers.\n\n :param relaxed_structure: Structure which is the output of Relax WorkChain. In thin function\n it is assumed to have inversion or at least z-reflection symmetry.\n :param orig_structure: The host structure slab having the lattice perioud corresponding to\n the bulk structure of the substrate.\n :param total_number_layers: the total number of layers to produce\n :param num_relaxed_layers: the number of top layers to adjust according to **relaxed_struct**\n :param tolerance_decimals: sets the rounding of atom positions. See numpy.around.\n :return magn_structure: Resulting assymetric structure with adjusted interlayer distances for\n several top layers.\n\n \"\"\"\n from aiida.orm import StructureData\n\n if relaxed_structure.pbc != (True, True, False):\n raise ValueError('Input structure has to be a film')\n\n sorted_struc = sort_atoms_z_value(relaxed_structure)\n sites = sorted_struc.sites\n\n layers = {np.around(atom.position[2], decimals=tolerance_decimals) for atom in sites}\n num_layers = len(layers)\n max_layers_to_extract = num_layers // 2 + num_layers % 2\n\n if isinstance(orig_structure, StructureData):\n positions = orig_structure.get_ase().positions\n else:\n positions = orig_structure.positions\n\n num_layers_org = len({np.around(x[2], decimals=tolerance_decimals) for x in positions})\n\n if num_layers_org > num_layers:\n raise ValueError('Your original structure contains more layers than given in relaxed '\n 'structure.\\nCould you reduce the number of layers in the'\n 'original structure?\\nIf not, I will not be able to guess '\n 'x-y displacements of some atoms')\n\n if num_relaxed_layers > max_layers_to_extract:\n print('You want to extract more layers than available, I am setting num_relaxed_layers to'\n ' {}'.format(max_layers_to_extract))\n num_relaxed_layers = max_layers_to_extract\n\n # take relaxed interlayers\n magn_structure = StructureData(cell=sorted_struc.cell)\n magn_structure.pbc = (True, True, False)\n for kind in relaxed_structure.kinds:\n magn_structure.append_kind(kind)\n\n done_layers = 0\n while True:\n if done_layers < num_relaxed_layers:\n layer, *_ = get_layers(sorted_struc)\n for atom in layer[done_layers]:\n a = Site(kind_name=atom[1], position=atom[0])\n magn_structure.append_site(a)\n done_layers = done_layers + 1\n elif done_layers < total_number_layers:\n k = done_layers % num_layers_org\n layer, pos_z, _ = get_layers(orig_structure)\n add_distance = abs(pos_z[k] - pos_z[k - 1])\n prev_layer_z = magn_structure.sites[-1].position[2]\n for atom in layer[k]:\n atom[0][2] = prev_layer_z + add_distance\n a = Site(kind_name=atom[1], position=atom[0])\n magn_structure.append_site(a)\n done_layers = done_layers + 1\n else:\n break\n\n magn_structure = center_film(magn_structure)\n return magn_structure\n\n\ndef get_layers(structure, decimals=10):\n \"\"\"\n Extracts atom positions and their types belonging to the same layer\n\n :param structure: ase lattice or StructureData which represents a slab\n :param number: the layer number. Note, that layers will be sorted according to z-position\n :param decimals: sets the tolerance of atom positions determination. See more in numpy.around.\n :return layer, layer_z_positions: layer is a list of tuples, the first element of which is\n atom positions and the second one is atom type.\n layer_z_position is a sorted list of all layer positions\n\n \"\"\"\n from aiida.orm import StructureData\n from ase.lattice.bravais import Lattice\n from itertools import groupby\n import copy\n\n structure = copy.deepcopy(structure)\n\n if isinstance(structure, StructureData):\n reformat = [(list(x.position), x.kind_name) for x in sorted(structure.sites, key=lambda x: x.position[2])]\n elif isinstance(structure, Lattice):\n reformat = list(zip(structure.positions, structure.get_chemical_symbols()))\n else:\n raise ValueError('Structure has to be ase lattice or StructureData')\n\n layer_z_positions = []\n layer_occupancies = []\n layers = []\n for val, e in groupby(reformat, key=lambda x: np.around(x[0][2], decimals=decimals)):\n layer_z_positions.append(val)\n layer_content = list(e)\n layers.append(layer_content)\n layer_occupancies.append(len(layer_content))\n\n return layers, layer_z_positions, layer_occupancies\n\n\ndef adjust_film_relaxation(structure, suggestion, scale_as=None, bond_length=None, hold_layers=3):\n \"\"\"\n Tries to optimize interlayer distances. Can be used before RelaxWC to improve its behaviour.\n This function only works if USER_API_KEY was set.\n\n For now only binary structures are analysed to ensure the closest contact between two\n elements of the interest. In case of trinary systems (like ABC) I can not not guarantee that\n A and C will be the nearest neighbours.\n\n The same is true for interlayer distances of the same element. To ensure the nearest-neighbour\n condition I use unary compounds.\n\n .. warning:\n\n This should work ony for metallic bonding since bond length can drastically\n depend on the atom hybridisation.\n\n :param structure: ase film structure which will be adjusted\n :param suggestion: dictionary containing average bond length between different elements,\n is is basically the result of\n :py:func:`~aiida_fleur.tools.StructureData_util.request_average_bond_length()`\n :param scale_as: an element name, for which the El-El bond length will be enforced. It is\n can be helpful to enforce the same interlayer distance in the substrate,\n i.e. adjust deposited film interlayer distances only.\n :param bond_length: a float that sets the bond length for scale_as element\n :param hold_layers: this parameters sets the number of layers that will be marked via the\n certain label. The label is reserved for future use in the relaxation WC:\n all the atoms marked with the label will not be relaxed.\n \"\"\"\n from aiida.orm import StructureData\n from copy import deepcopy\n from itertools import product\n\n if scale_as and not bond_length:\n raise ValueError('bond_length is required when scale_as was provided')\n\n structure = sort_atoms_z_value(structure)\n layers, z_positions, occupancies = get_layers(structure)\n\n suggestion = deepcopy(suggestion)\n if scale_as:\n norm = suggestion[scale_as][scale_as]\n for sym1, sym2 in product(suggestion.keys(), suggestion.keys()):\n try:\n suggestion[sym1][sym2] = suggestion[sym1][sym2] / norm\n except KeyError:\n pass # do nothing, happens for magnetic-magnetic or substrate-substrate combinations\n\n def suggest_distance_to_previous(num_layer):\n z_distances = []\n for atom_prev in layers[num_layer - 1]:\n pos_prev = np.array(atom_prev[0])[0:2]\n for atom_this in layers[num_layer]:\n pos_this = np.array(atom_this[0])[0:2]\n xy_dist_sq = np.linalg.norm(pos_prev - pos_this)**2\n if scale_as:\n bond_length_sq = suggestion[atom_prev[1]][atom_this[1]]**2 * bond_length**2\n else:\n bond_length_sq = suggestion[atom_prev[1]][atom_this[1]]**2\n if xy_dist_sq > bond_length_sq:\n pass\n else:\n z_distances.append((bond_length_sq - xy_dist_sq)**(0.5))\n\n # find suggestion for distance to 2nd layer back\n z_distances2 = []\n if num_layer != 1:\n for atom_prev in layers[num_layer - 2]:\n pos_prev = np.array(atom_prev[0])[0:2]\n for atom_this in layers[num_layer]:\n pos_this = np.array(atom_this[0])[0:2]\n xy_dist_sq = np.linalg.norm(pos_prev - pos_this)**2\n if scale_as:\n bond_length_sq = suggestion[atom_prev[1]][atom_this[1]]**2 * bond_length**2\n else:\n bond_length_sq = suggestion[atom_prev[1]][atom_this[1]]**2\n if xy_dist_sq > bond_length_sq:\n pass\n else:\n z_distances2.append((bond_length_sq - xy_dist_sq)**(0.5))\n\n if not z_distances:\n z_distances = [0]\n\n if not z_distances2:\n z_distances2 = [0]\n\n return max(z_distances), max(z_distances2)\n\n # take relaxed interlayers\n rebuilt_structure = StructureData(cell=structure.cell)\n rebuilt_structure.pbc = (True, True, False)\n # for kind in structure.kinds:\n # rebuilt_structure.append_kind(kind)\n\n for atom in layers[0]:\n # a = Site(kind_name=atom[1], position=atom[0])\n # minus because I build from bottom (inversed structure)\n if hold_layers < 1:\n rebuilt_structure.append_atom(symbols=atom[1], position=(atom[0][0], atom[0][1], -atom[0][2]), name=atom[1])\n else:\n rebuilt_structure.append_atom(symbols=atom[1],\n position=(atom[0][0], atom[0][1], -atom[0][2]),\n name=atom[1] + '49')\n\n prev_distance = 0\n for i, layer in enumerate(layers[1:]):\n add_distance1, add_distance2 = suggest_distance_to_previous(i + 1)\n add_distance2 = add_distance2 - prev_distance\n if add_distance1 <= 0 and add_distance2 <= 0:\n raise ValueError('error not implemented')\n prev_distance = max(add_distance1, add_distance2)\n if i == len(layers) - 2:\n prev_distance = prev_distance * 0.85 # last layer should be closer\n\n layer_copy = deepcopy(layer)\n prev_layer_z = rebuilt_structure.sites[-1].position[2]\n for atom in layer_copy:\n atom[0][2] = prev_layer_z - prev_distance # minus because I build from bottom (inverse)\n # a = Site(kind_name=atom[1], position=atom[0])\n # rebuilt_structure.append_site(a)\n if i < hold_layers - 1:\n rebuilt_structure.append_atom(position=atom[0], symbols=atom[1], name=atom[1] + '49')\n else:\n rebuilt_structure.append_atom(position=atom[0], symbols=atom[1], name=atom[1])\n\n rebuilt_structure = center_film(rebuilt_structure)\n return rebuilt_structure\n\n\ndef request_average_bond_length_store(main_elements, sub_elements, user_api_key):\n \"\"\"\n Requests MaterialsProject to estimate thermal average bond length between given elements.\n Also requests information about lattice constants of fcc and bcc structures.\n Stores the result in the Database. Notice that this is not a calcfunction!\n Therefore, the inputs are not stored and the result node is unconnected.\n\n :param main_elements: element list to calculate the average bond length\n only combinations of AB, AA and BB are calculated, where\n A belongs to main_elements, B belongs to sub_elements.\n :param sub_elements: element list, see main_elements\n :return: bond_data, a dict containing obtained lattice constants.\n \"\"\"\n result = request_average_bond_length(main_elements, sub_elements, user_api_key)\n result.store()\n return result\n\n\ndef request_average_bond_length(main_elements, sub_elements, user_api_key):\n \"\"\"\n Requests MaterialsProject to estimate thermal average bond length between given elements.\n Also requests information about lattice constants of fcc and bcc structures.\n\n :param main_elements: element list to calculate the average bond length\n only combinations of AB, AA and BB are calculated, where\n A belongs to main_elements, B belongs to sub_elements.\n :param sub_elements: element list, see main_elements\n :return: bond_data, a dict containing obtained lattice constants.\n \"\"\"\n from itertools import product, combinations\n from math import exp\n from aiida.orm import Dict\n from pymatgen.ext.matproj import MPRester\n from collections import defaultdict\n from copy import deepcopy\n\n bond_data = defaultdict(lambda: defaultdict(lambda: 0.0))\n symbols = main_elements + sub_elements\n\n for sym in symbols:\n distance = 0\n partition_function = 0\n with MPRester(user_api_key) as mat_project:\n mp_entries = mat_project.get_entries_in_chemsys([sym])\n fcc_structure = None\n bcc_structure = None\n for entry in mp_entries:\n if sym != entry.name:\n continue\n with MPRester(user_api_key) as mat_project:\n structure_analyse = mat_project.get_structure_by_material_id(entry.entry_id)\n en_per_atom = mat_project.query(entry.entry_id, ['energy_per_atom'])[0]['energy_per_atom']\n structure_analyse.make_supercell([2, 2, 2])\n factor = exp(-(en_per_atom / 0.0259))\n partition_function = partition_function + factor\n indices1 = structure_analyse.indices_from_symbol(sym)\n distances = (structure_analyse.get_distance(x, y) for x, y in combinations(indices1, 2))\n min_distance = min(distances)\n distance = distance + min_distance * factor\n # save distance for particular cases of fcc and bcc\n if structure_analyse.get_space_group_info()[1] == 225: # fcc\n bond_data['fcc'][sym] = min_distance\n elif structure_analyse.get_space_group_info()[1] == 229: # bcc\n bond_data['bcc'][sym] = min_distance\n\n distance = distance / partition_function\n bond_data[sym][sym] = distance\n print('Request completed for {symst} {symst} pair'.format(symst=sym))\n\n for sym1, sym2 in product(main_elements, sub_elements):\n distance = 0\n partition_function = 0\n with MPRester(user_api_key) as mat_project:\n mp_entries = mat_project.get_entries_in_chemsys([sym1, sym2])\n for entry in mp_entries:\n name = ''.join([i for i in entry.name if not i.isdigit()])\n if name not in (sym1 + sym2, sym2 + sym1):\n continue\n with MPRester(user_api_key) as mat_project:\n structure_analyse = mat_project.get_structure_by_material_id(entry.entry_id)\n en_per_atom = mat_project.query(entry.entry_id, ['energy_per_atom'])[0]['energy_per_atom']\n structure_analyse.make_supercell([2, 2, 2])\n factor = exp(-(en_per_atom / 0.0259))\n partition_function = partition_function + factor\n indices1 = structure_analyse.indices_from_symbol(sym1)\n indices2 = structure_analyse.indices_from_symbol(sym2)\n distances = (structure_analyse.get_distance(x, y) for x, y in product(indices1, indices2))\n distance = distance + min(distances) * factor\n if partition_function == 0:\n distance = (bond_data[sym1][sym1] + bond_data[sym2][sym2]) / 2\n else:\n distance = distance / partition_function\n bond_data[sym1][sym2] = distance\n bond_data[sym2][sym1] = distance\n print('Request completed for {} {} pair'.format(sym1, sym2))\n\n return Dict(dict=bond_data)\n\n\n'''\ndef estimate_mt_radii(structure, stepsize=0.05):\n \"\"\"\n # TODO implement\n This method returns for every atom type (group/kind) in the structure a range of\n possible muffin tin radii (min, max).\n Or maybe just the maximal muffin tin radii (or sets of maximal muffin tin radii)\n\n example return for some Be-W compound\n [[{Be: 1.6, W:2.4}, {Be:1.8, W:2.2}]\n\n \"\"\"\n\n # get symmetry equivalent atoms,\n # for each atom estimate muffin tin\n # check what algo fleur uses here\n # Max radius easy increase all spheres until they touch.\n # How to get the minimal muffin tin radii?\n return None\n\n\ndef common_mt(max_muffin_tins):\n \"\"\"\n # TODO implement\n From a list of dictionary given return smallest common set.\n Could be read from the econfig file within AiiDA fleur.\n\n [[{Be: 1.7, W:2.4}, {Be:1.8, W:2.3}], [{Be : 1.75}], [{W:2.5}]\n should return [{Be:1.7, W:2.4}]\n \"\"\"\n return None\n\n\ndef find_common_mt(structures):\n \"\"\"\n # TODO implement (in some phd notebook of Broeder this is implement)\n From a given list of structures, estimate the muffin tin radii and return\n the smallest common set. (therefore a choice for rmt that would work for every structure given)\n\n \"\"\"\n return None\n'''\n"
] | [
[
"numpy.array"
],
[
"numpy.unique",
"numpy.linalg.inv",
"numpy.around",
"numpy.matmul",
"numpy.linalg.norm",
"numpy.array",
"numpy.where"
]
] |
alirezasalemi7/ARMAN | [
"e935f38cb8ee58af09c4e0174e83e91fab90a478"
] | [
"models/pegasus/persian_datasets/summarization/PN_summary.py"
] | [
"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport os\n\nimport tensorflow.compat.v2 as tf\nimport tensorflow_datasets.public_api as tfds\nimport re\n\n_DOCUMENT = \"_DOCUMENT\"\n_SUMMARY = \"_SUMMARY\"\n\n\n\nDIR = '/*path to data*/'\n\nclass PN_Summary(tfds.core.GeneratorBasedBuilder):\n\n VERSION = tfds.core.Version('0.1.0')\n MANUAL_DOWNLOAD_INSTRUCTIONS = 'Here to be description of the dataset'\n SKIP_REGISTERING = True\n def _info(self):\n return tfds.core.DatasetInfo(\n builder=self,\n # This is the description that will appear on the datasets page.\n description=(\"persian dataset.\"),\n # tfds.features.FeatureConnectors\n features=tfds.features.FeaturesDict({\n _DOCUMENT: tfds.features.Text(),\n _SUMMARY: tfds.features.Text(),\n }),\n # If there's a common (input, target) tuple from the features,\n # specify them here. They'll be used if as_supervised=True in\n # builder.as_dataset.\n supervised_keys=(_DOCUMENT, _SUMMARY),\n )\n\n def _split_generators(self, dl_manager):\n # Download source data\n \n extracted_path = DIR\n # Specify the splits\n return [\n tfds.core.SplitGenerator(\n name=tfds.Split.TRAIN,\n gen_kwargs={\n \"raw_texts\": os.path.join(extracted_path, \"train/inputs.txt\"),\n \"target_texts\": os.path.join(extracted_path, \"train/targets.txt\")\n },\n ),\n tfds.core.SplitGenerator(\n name=tfds.Split.TEST,\n gen_kwargs={\n \"raw_texts\": os.path.join(extracted_path, \"test/inputs.txt\"),\n \"target_texts\": os.path.join(extracted_path, \"test/targets.txt\")\n },\n ),\n tfds.core.SplitGenerator(\n name=tfds.Split.VALIDATION,\n gen_kwargs={\n \"raw_texts\": os.path.join(extracted_path, \"validation/inputs.txt\"),\n \"target_texts\": os.path.join(extracted_path, \"validation/targets.txt\")\n },\n )\n ]\n \n def _generate_examples(self, raw_texts,target_texts):\n with tf.io.gfile.GFile(raw_texts,\"rb\") as input_file,tf.io.gfile.GFile(target_texts,\"rb\") as target_file:\n for i, (text, target) in enumerate(zip(input_file, target_file)):\n yield i, {_DOCUMENT: b\"<SUMMARIZATION> \" + text, _SUMMARY: target}\n \n"
] | [
[
"tensorflow.compat.v2.io.gfile.GFile"
]
] |
OKRATechnologies/DiCE | [
"8cbed19e8981d484b1479601ec2669f59b8c9285"
] | [
"dice_ml/explainer_interfaces/explainer_base.py"
] | [
"\"\"\"Module containing a template class to generate counterfactual explanations.\n Subclasses implement interfaces for different ML frameworks such as TensorFlow or PyTorch.\n All methods are in dice_ml.explainer_interfaces\"\"\"\n\nfrom abc import ABC, abstractmethod\nimport numpy as np\nimport pandas as pd\nfrom tqdm import tqdm\n\nfrom collections.abc import Iterable\nfrom sklearn.neighbors import KDTree\nfrom dice_ml.counterfactual_explanations import CounterfactualExplanations\nfrom dice_ml.utils.exception import UserConfigValidationException\nfrom dice_ml.constants import ModelTypes\n\n\nclass ExplainerBase(ABC):\n\n def __init__(self, data_interface, model_interface=None):\n \"\"\"Init method\n\n :param data_interface: an interface class to access data related params.\n :param model_interface: an interface class to access trained ML model.\n \"\"\"\n # initiating data and model related parameters\n self.data_interface = data_interface\n if model_interface is not None:\n # self.data_interface.create_ohe_params()\n self.model = model_interface\n self.model.load_model() # loading pickled trained model if applicable\n self.model.transformer.feed_data_params(data_interface)\n self.model.transformer.initialize_transform_func()\n\n # moved the following snippet to a method in public_data_interface\n # self.minx, self.maxx, self.encoded_categorical_feature_indexes = self.data_interface.get_data_params()\n #\n # # min and max for continuous features in original scale\n # flattened_indexes = [item for sublist in self.encoded_categorical_feature_indexes for item in sublist]\n # self.encoded_continuous_feature_indexes = [ix for ix in range(len(self.minx[0])) if ix not in flattened_indexes]\n # org_minx, org_maxx = self.data_interface.get_minx_maxx(normalized=False)\n # self.cont_minx = list(org_minx[0][self.encoded_continuous_feature_indexes])\n # self.cont_maxx = list(org_maxx[0][self.encoded_continuous_feature_indexes])\n #\n # # decimal precisions for continuous features\n # self.cont_precisions = \\\n # [self.data_interface.get_decimal_precisions()[ix] for ix in self.encoded_continuous_feature_indexes]\n\n def generate_counterfactuals(self, query_instances, total_CFs,\n desired_class=\"opposite\", desired_range=None,\n permitted_range=None, features_to_vary=\"all\",\n stopping_threshold=0.5, posthoc_sparsity_param=0.1,\n posthoc_sparsity_algorithm=\"linear\", verbose=False, **kwargs):\n \"\"\"General method for generating counterfactuals.\n\n :param query_instances: Input point(s) for which counterfactuals are to be generated.\n This can be a dataframe with one or more rows.\n :param total_CFs: Total number of counterfactuals required.\n :param desired_class: Desired counterfactual class - can take 0 or 1. Default value\n is \"opposite\" to the outcome class of query_instance for binary classification.\n :param desired_range: For regression problems. Contains the outcome range to\n generate counterfactuals in.\n :param permitted_range: Dictionary with feature names as keys and permitted range in list as values.\n Defaults to the range inferred from training data.\n If None, uses the parameters initialized in data_interface.\n :param features_to_vary: Either a string \"all\" or a list of feature names to vary.\n :param stopping_threshold: Minimum threshold for counterfactuals target class probability.\n :param posthoc_sparsity_param: Parameter for the post-hoc operation on continuous features to enhance sparsity.\n :param posthoc_sparsity_algorithm: Perform either linear or binary search. Takes \"linear\" or \"binary\".\n Prefer binary search when a feature range is large (for instance,\n income varying from 10k to 1000k) and only if the features share a\n monotonic relationship with predicted outcome in the model.\n :param verbose: Whether to output detailed messages.\n :param sample_size: Sampling size\n :param random_seed: Random seed for reproducibility\n :param kwargs: Other parameters accepted by specific explanation method\n\n :returns: A CounterfactualExplanations object that contains the list of\n counterfactual examples per query_instance as one of its attributes.\n \"\"\"\n if total_CFs <= 0:\n raise UserConfigValidationException(\n \"The number of counterfactuals generated per query instance (total_CFs) should be a positive integer.\")\n cf_examples_arr = []\n query_instances_list = []\n if isinstance(query_instances, pd.DataFrame):\n for ix in range(query_instances.shape[0]):\n query_instances_list.append(query_instances[ix:(ix+1)])\n elif isinstance(query_instances, Iterable):\n query_instances_list = query_instances\n for query_instance in tqdm(query_instances_list):\n res = self._generate_counterfactuals(\n query_instance, total_CFs,\n desired_class=desired_class,\n desired_range=desired_range,\n permitted_range=permitted_range,\n features_to_vary=features_to_vary,\n stopping_threshold=stopping_threshold,\n posthoc_sparsity_param=posthoc_sparsity_param,\n posthoc_sparsity_algorithm=posthoc_sparsity_algorithm,\n verbose=verbose,\n **kwargs)\n cf_examples_arr.append(res)\n return CounterfactualExplanations(cf_examples_list=cf_examples_arr)\n\n @abstractmethod\n def _generate_counterfactuals(self, query_instance, total_CFs,\n desired_class=\"opposite\", desired_range=None,\n permitted_range=None, features_to_vary=\"all\",\n stopping_threshold=0.5, posthoc_sparsity_param=0.1,\n posthoc_sparsity_algorithm=\"linear\", verbose=False, **kwargs):\n \"\"\"Internal method for generating counterfactuals for a given query instance. Any explainerclass\n inherting from this class would need to implement this abstract method.\n\n :param query_instance: Input point for which counterfactuals are to be generated.\n This can be a dataframe with one row.\n :param total_CFs: Total number of counterfactuals required.\n :param desired_class: Desired counterfactual class - can take 0 or 1. Default value\n is \"opposite\" to the outcome class of query_instance for binary classification.\n :param desired_range: For regression problems. Contains the outcome range to\n generate counterfactuals in.\n :param permitted_range: Dictionary with feature names as keys and permitted range in list as values.\n Defaults to the range inferred from training data.\n If None, uses the parameters initialized in data_interface.\n :param features_to_vary: Either a string \"all\" or a list of feature names to vary.\n :param stopping_threshold: Minimum threshold for counterfactuals target class probability.\n :param posthoc_sparsity_param: Parameter for the post-hoc operation on continuous features to enhance sparsity.\n :param posthoc_sparsity_algorithm: Perform either linear or binary search. Takes \"linear\" or \"binary\".\n Prefer binary search when a feature range is large (for instance,\n income varying from 10k to 1000k) and only if the features share a\n monotonic relationship with predicted outcome in the model.\n :param verbose: Whether to output detailed messages.\n :param sample_size: Sampling size\n :param random_seed: Random seed for reproducibility\n :param kwargs: Other parameters accepted by specific explanation method\n\n :returns: A CounterfactualExplanations object that contains the list of\n counterfactual examples per query_instance as one of its attributes.\n \"\"\"\n pass\n\n def setup(self, features_to_vary, permitted_range, query_instance, feature_weights):\n if features_to_vary == 'all':\n features_to_vary = self.data_interface.feature_names\n\n if permitted_range is None: # use the precomputed default\n self.feature_range = self.data_interface.permitted_range\n feature_ranges_orig = self.feature_range\n else: # compute the new ranges based on user input\n self.feature_range, feature_ranges_orig = self.data_interface.get_features_range(permitted_range)\n self.check_query_instance_validity(features_to_vary, permitted_range, query_instance, feature_ranges_orig)\n\n # check feature MAD validity and throw warnings\n self.check_mad_validity(feature_weights)\n\n return features_to_vary\n\n def check_query_instance_validity(self, features_to_vary, permitted_range, query_instance, feature_ranges_orig):\n for feature in query_instance:\n if feature == self.data_interface.outcome_name:\n raise ValueError(\"Target\", self.data_interface.outcome_name, \"present in query instance\")\n\n if feature not in self.data_interface.feature_names:\n raise ValueError(\"Feature\", feature, \"not present in training data!\")\n\n for feature in self.data_interface.categorical_feature_names:\n if query_instance[feature].values[0] not in feature_ranges_orig[feature]:\n raise ValueError(\"Feature\", feature, \"has a value outside the dataset.\")\n\n if feature not in features_to_vary and permitted_range is not None:\n if feature in permitted_range and feature in self.data_interface.continuous_feature_names:\n if not permitted_range[feature][0] <= query_instance[feature].values[0] <= permitted_range[feature][1]:\n raise ValueError(\"Feature:\", feature, \"is outside the permitted range and isn't allowed to vary.\")\n elif feature in permitted_range and feature in self.data_interface.categorical_feature_names:\n if query_instance[feature].values[0] not in self.feature_range[feature]:\n raise ValueError(\"Feature:\", feature, \"is outside the permitted range and isn't allowed to vary.\")\n\n def local_feature_importance(self, query_instances, cf_examples_list=None,\n total_CFs=10,\n desired_class=\"opposite\", desired_range=None, permitted_range=None,\n features_to_vary=\"all\", stopping_threshold=0.5,\n posthoc_sparsity_param=0.1, posthoc_sparsity_algorithm=\"linear\",\n atol = 1e-8,\n **kwargs):\n \"\"\" Estimate local feature importance scores for the given inputs.\n\n :param query_instances: A list of inputs for which to compute the\n feature importances. These can be provided as a dataframe.\n :param cf_examples_list: If precomputed, a list of counterfactual\n examples for every input point. If cf_examples_list is provided, then\n all the following parameters are ignored.\n :param total_CFs: The number of counterfactuals to generate per input\n (default is 10)\n :param other_parameters: These are the same as the\n generate_counterfactuals method.\n\n :returns: An object of class CounterfactualExplanations that includes\n the list of counterfactuals per input, local feature importances per\n input, and the global feature importance summarized over all inputs.\n \"\"\"\n if cf_examples_list is not None:\n if any([len(cf_examples.final_cfs_df) < 10 for cf_examples in cf_examples_list]):\n raise UserConfigValidationException(\n \"The number of counterfactuals generated per query instance should be \"\n \"greater than or equal to 10\")\n elif total_CFs < 10:\n raise UserConfigValidationException(\"The number of counterfactuals generated per \"\n \"query instance should be greater than or equal to 10\")\n importances = self.feature_importance(\n query_instances,\n cf_examples_list=cf_examples_list,\n total_CFs=total_CFs,\n local_importance=True,\n global_importance=False,\n desired_class=desired_class,\n desired_range=desired_range,\n permitted_range=permitted_range,\n features_to_vary=features_to_vary,\n stopping_threshold=stopping_threshold,\n posthoc_sparsity_param=posthoc_sparsity_param,\n posthoc_sparsity_algorithm=posthoc_sparsity_algorithm,\n atol = atol,\n **kwargs)\n return importances\n\n def global_feature_importance(self, query_instances, cf_examples_list=None,\n total_CFs=10, local_importance=True,\n desired_class=\"opposite\", desired_range=None, permitted_range=None,\n features_to_vary=\"all\", stopping_threshold=0.5,\n posthoc_sparsity_param=0.1, posthoc_sparsity_algorithm=\"linear\",\n atol = 1e-8,\n **kwargs):\n \"\"\" Estimate global feature importance scores for the given inputs.\n\n :param query_instances: A list of inputs for which to compute the\n feature importances. These can be provided as a dataframe.\n :param cf_examples_list: If precomputed, a list of counterfactual\n examples for every input point. If cf_examples_list is provided, then\n all the following parameters are ignored.\n :param total_CFs: The number of counterfactuals to generate per input\n (default is 10)\n :param local_importance: Binary flag indicating whether local feature\n importance values should also be returned for each query instance.\n :param other_parameters: These are the same as the generate_counterfactuals method.\n\n :returns: An object of class CounterfactualExplanations that includes\n the list of counterfactuals per input, local feature importances per\n input, and the global feature importance summarized over all inputs.\n \"\"\"\n if query_instances is not None and len(query_instances) < 10:\n raise UserConfigValidationException(\"The number of query instances should be greater than or equal to 10\")\n if cf_examples_list is not None:\n if any([len(cf_examples.final_cfs_df) < 10 for cf_examples in cf_examples_list]):\n raise UserConfigValidationException(\n \"The number of counterfactuals generated per query instance should be \"\n \"greater than or equal to 10\")\n elif total_CFs < 10:\n raise UserConfigValidationException(\n \"The number of counterfactuals generated per query instance should be greater \"\n \"than or equal to 10\")\n importances = self.feature_importance(\n query_instances,\n cf_examples_list=cf_examples_list,\n total_CFs=total_CFs,\n local_importance=local_importance,\n global_importance=True,\n desired_class=desired_class,\n desired_range=desired_range,\n permitted_range=permitted_range,\n features_to_vary=features_to_vary,\n stopping_threshold=stopping_threshold,\n posthoc_sparsity_param=posthoc_sparsity_param,\n posthoc_sparsity_algorithm=posthoc_sparsity_algorithm,\n atol = atol,\n **kwargs)\n return importances\n\n def feature_importance(self, query_instances, cf_examples_list=None,\n total_CFs=10, local_importance=True, global_importance=True,\n desired_class=\"opposite\", desired_range=None,\n permitted_range=None, features_to_vary=\"all\", stopping_threshold=0.5,\n posthoc_sparsity_param=0.1, posthoc_sparsity_algorithm=\"linear\", \n atol = 1e-8, **kwargs):\n \"\"\" Estimate feature importance scores for the given inputs.\n\n :param query_instances: A list of inputs for which to compute the\n feature importances. These can be provided as a dataframe.\n :param cf_examples_list: If precomputed, a list of counterfactual\n examples for every input point. If cf_examples_list is provided, then\n all the following parameters are ignored.\n :param total_CFs: The number of counterfactuals to generate per input\n (default is 10)\n :param other_parameters: These are the same as the generate_counterfactuals method.\n\n :returns: An object of class CounterfactualExplanations that includes\n the list of counterfactuals per input, local feature importances per\n input, and the global feature importance summarized over all inputs.\n \"\"\"\n if cf_examples_list is None:\n cf_examples_list = self.generate_counterfactuals(\n query_instances, total_CFs,\n desired_class=desired_class,\n desired_range=desired_range,\n permitted_range=permitted_range,\n features_to_vary=features_to_vary,\n stopping_threshold=stopping_threshold,\n posthoc_sparsity_param=posthoc_sparsity_param,\n posthoc_sparsity_algorithm=posthoc_sparsity_algorithm,\n **kwargs).cf_examples_list\n allcols = self.data_interface.categorical_feature_names + self.data_interface.continuous_feature_names\n summary_importance = None\n local_importances = None\n if global_importance:\n summary_importance = {}\n # Initializing importance vector\n for col in allcols:\n summary_importance[col] = 0\n\n if local_importance:\n local_importances = [{} for _ in range(len(cf_examples_list))]\n # Initializing local importance for the ith query instance\n for i in range(len(cf_examples_list)):\n for col in allcols:\n local_importances[i][col] = 0\n\n overall_num_cfs = 0\n # Summarizing the found counterfactuals\n for i in range(len(cf_examples_list)):\n cf_examples = cf_examples_list[i]\n org_instance = cf_examples.test_instance_df\n\n if cf_examples.final_cfs_df_sparse is not None:\n df = cf_examples.final_cfs_df_sparse\n else:\n df = cf_examples.final_cfs_df\n\n if df is None:\n continue\n\n per_query_point_cfs = 0\n for index, row in df.iterrows():\n per_query_point_cfs += 1\n for col in self.data_interface.continuous_feature_names:\n if not np.isclose(org_instance[col].iat[0], row[col], atol = atol):\n if summary_importance is not None:\n summary_importance[col] += 1\n if local_importances is not None:\n local_importances[i][col] += 1\n for col in self.data_interface.categorical_feature_names:\n if org_instance[col].iat[0] != row[col]:\n if summary_importance is not None:\n summary_importance[col] += 1\n if local_importances is not None:\n local_importances[i][col] += 1\n\n if local_importances is not None:\n for col in allcols:\n if per_query_point_cfs > 0:\n local_importances[i][col] /= per_query_point_cfs\n\n overall_num_cfs += per_query_point_cfs\n\n if summary_importance is not None:\n for col in allcols:\n if overall_num_cfs > 0:\n summary_importance[col] /= overall_num_cfs\n\n return CounterfactualExplanations(\n cf_examples_list,\n local_importance=local_importances,\n summary_importance=summary_importance)\n\n def predict_fn(self, input_instance):\n \"\"\"prediction function\"\"\"\n return self.model.get_output(input_instance)\n\n def predict_fn_for_sparsity(self, input_instance):\n \"\"\"prediction function for sparsity correction\"\"\"\n return self.model.get_output(input_instance)\n\n def do_posthoc_sparsity_enhancement(self, final_cfs_sparse, query_instance, posthoc_sparsity_param,\n posthoc_sparsity_algorithm):\n \"\"\"Post-hoc method to encourage sparsity in a generated counterfactuals.\n\n :param final_cfs_sparse: Final CFs in original user-fed format, in a pandas dataframe.\n :param query_instance: Query instance in original user-fed format, in a pandas dataframe.\n :param posthoc_sparsity_param: Parameter for the post-hoc operation on continuous features to enhance sparsity.\n :param posthoc_sparsity_algorithm: Perform either linear or binary search.\n Prefer binary search when a feature range is\n large (for instance, income varying from 10k to 1000k)\n and only if the features share a monotonic relationship\n with predicted outcome in the model.\n \"\"\"\n if final_cfs_sparse is None:\n return final_cfs_sparse\n\n # quantiles of the deviation from median for every continuous feature\n quantiles = self.data_interface.get_quantiles_from_training_data(quantile=posthoc_sparsity_param)\n mads = self.data_interface.get_valid_mads()\n # Setting the quantile of a feature to be the minimum of mad and quantile\n # Thus, the maximum deviation can be mad.\n for feature in quantiles:\n quantiles[feature] = min(quantiles[feature], mads[feature])\n\n # Sorting features such that the feature with the highest quantile deviation\n # is first\n features_sorted = sorted(quantiles.items(), key=lambda kv: kv[1], reverse=True)\n for ix in range(len(features_sorted)):\n features_sorted[ix] = features_sorted[ix][0]\n precs = self.data_interface.get_decimal_precisions()\n decimal_prec = dict(zip(self.data_interface.continuous_feature_names, precs))\n\n cfs_preds_sparse = []\n\n for cf_ix in list(final_cfs_sparse.index):\n current_pred = self.predict_fn_for_sparsity(final_cfs_sparse.loc[[cf_ix]][self.data_interface.feature_names])\n for feature in features_sorted:\n # current_pred = self.predict_fn_for_sparsity(final_cfs_sparse.iat[[cf_ix]][self.data_interface.feature_names])\n # feat_ix = self.data_interface.continuous_feature_names.index(feature)\n diff = query_instance[feature].iat[0] - int(final_cfs_sparse.at[cf_ix, feature])\n if(abs(diff) <= quantiles[feature]):\n if posthoc_sparsity_algorithm == \"linear\":\n final_cfs_sparse = self.do_linear_search(diff, decimal_prec, query_instance, cf_ix,\n feature, final_cfs_sparse, current_pred)\n\n elif posthoc_sparsity_algorithm == \"binary\":\n final_cfs_sparse = self.do_binary_search(\n diff, decimal_prec, query_instance, cf_ix, feature, final_cfs_sparse, current_pred)\n\n temp_preds = self.predict_fn_for_sparsity(final_cfs_sparse.loc[[cf_ix]][self.data_interface.feature_names])\n cfs_preds_sparse.append(temp_preds)\n\n final_cfs_sparse[self.data_interface.outcome_name] = self.get_model_output_from_scores(cfs_preds_sparse)\n # final_cfs_sparse[self.data_interface.outcome_name] = np.round(final_cfs_sparse[self.data_interface.outcome_name], 3)\n return final_cfs_sparse\n\n def do_linear_search(self, diff, decimal_prec, query_instance, cf_ix, feature, final_cfs_sparse, current_pred_orig):\n \"\"\"Performs a greedy linear search - moves the continuous features in CFs towards original values in\n query_instance greedily until the prediction class changes.\"\"\"\n\n old_diff = diff\n change = (10**-decimal_prec[feature]) # the minimal possible change for a feature\n current_pred = current_pred_orig\n if self.model.model_type == ModelTypes.Classifier:\n while((abs(diff) > 10e-4) and (np.sign(diff*old_diff) > 0) and self.is_cf_valid(current_pred)):\n old_val = int(final_cfs_sparse.at[cf_ix, feature])\n final_cfs_sparse.at[cf_ix, feature] += np.sign(diff)*change\n current_pred = self.predict_fn_for_sparsity(final_cfs_sparse.loc[[cf_ix]][self.data_interface.feature_names])\n old_diff = diff\n\n if not self.is_cf_valid(current_pred):\n final_cfs_sparse.at[cf_ix, feature] = old_val\n diff = query_instance[feature].iat[0] - int(final_cfs_sparse.at[cf_ix, feature])\n return final_cfs_sparse\n\n diff = query_instance[feature].iat[0] - int(final_cfs_sparse.at[cf_ix, feature])\n\n return final_cfs_sparse\n\n def do_binary_search(self, diff, decimal_prec, query_instance, cf_ix, feature, final_cfs_sparse, current_pred):\n \"\"\"Performs a binary search between continuous features of a CF and corresponding values\n in query_instance until the prediction class changes.\"\"\"\n\n old_val = int(final_cfs_sparse.at[cf_ix, feature])\n final_cfs_sparse.at[cf_ix, feature] = query_instance[feature].iat[0]\n # Prediction of the query instance\n current_pred = self.predict_fn_for_sparsity(final_cfs_sparse.loc[[cf_ix]][self.data_interface.feature_names])\n\n # first check if assigning query_instance values to a CF is required.\n if self.is_cf_valid(current_pred):\n return final_cfs_sparse\n else:\n final_cfs_sparse.at[cf_ix, feature] = old_val\n\n # move the CF values towards the query_instance\n if diff > 0:\n left = int(final_cfs_sparse.at[cf_ix, feature])\n right = query_instance[feature].iat[0]\n\n while left <= right:\n current_val = left + ((right - left)/2)\n current_val = round(current_val, decimal_prec[feature])\n\n final_cfs_sparse.at[cf_ix, feature] = current_val\n current_pred = self.predict_fn_for_sparsity(final_cfs_sparse.loc[[cf_ix]][self.data_interface.feature_names])\n\n if current_val == right or current_val == left:\n break\n\n if self.is_cf_valid(current_pred):\n left = current_val + (10 ** -decimal_prec[feature])\n else:\n right = current_val - (10 ** -decimal_prec[feature])\n\n else:\n left = query_instance[feature].iat[0]\n right = int(final_cfs_sparse.at[cf_ix, feature])\n\n while right >= left:\n current_val = right - ((right - left)/2)\n current_val = round(current_val, decimal_prec[feature])\n\n final_cfs_sparse.at[cf_ix, feature] = current_val\n current_pred = self.predict_fn_for_sparsity(final_cfs_sparse.loc[[cf_ix]][self.data_interface.feature_names])\n\n if current_val == right or current_val == left:\n break\n\n if self.is_cf_valid(current_pred):\n right = current_val - (10**-decimal_prec[feature])\n else:\n left = current_val + (10**-decimal_prec[feature])\n\n return final_cfs_sparse\n\n def misc_init(self, stopping_threshold, desired_class, desired_range, test_pred):\n self.stopping_threshold = stopping_threshold\n if self.model.model_type == ModelTypes.Classifier:\n self.target_cf_class = np.array(\n [[self.infer_target_cfs_class(desired_class, test_pred, self.num_output_nodes)]],\n dtype=np.float32)\n desired_class = self.target_cf_class[0][0]\n if self.target_cf_class == 0 and self.stopping_threshold > 0.5:\n self.stopping_threshold = 0.25\n elif self.target_cf_class == 1 and self.stopping_threshold < 0.5:\n self.stopping_threshold = 0.75\n\n elif self.model.model_type == ModelTypes.Regressor:\n self.target_cf_range = self.infer_target_cfs_range(desired_range)\n return desired_class\n\n def infer_target_cfs_class(self, desired_class_input, original_pred, num_output_nodes):\n \"\"\" Infer the target class for generating CFs. Only called when\n model_type==\"classifier\".\n TODO: Add support for opposite desired class in multiclass. Downstream methods should decide\n whether it is allowed or not.\n \"\"\"\n if desired_class_input == \"opposite\":\n if num_output_nodes == 2:\n original_pred_1 = np.argmax(original_pred)\n target_class = int(1 - original_pred_1)\n return target_class\n elif num_output_nodes > 2:\n raise UserConfigValidationException(\n \"Desired class cannot be opposite if the number of classes is more than 2.\")\n elif isinstance(desired_class_input, int):\n if desired_class_input >= 0 and desired_class_input < num_output_nodes:\n target_class = desired_class_input\n return target_class\n else:\n raise UserConfigValidationException(\"Desired class not present in training data!\")\n else:\n raise UserConfigValidationException(\"The target class for {0} could not be identified\".format(\n desired_class_input))\n\n def infer_target_cfs_range(self, desired_range_input):\n target_range = None\n if desired_range_input is None:\n raise ValueError(\"Need to provide a desired_range for the target counterfactuals for a regression model.\")\n else:\n if desired_range_input[0] > desired_range_input[1]:\n raise ValueError(\"Invalid Range!\")\n else:\n target_range = desired_range_input\n return target_range\n\n def decide_cf_validity(self, model_outputs):\n validity = np.zeros(len(model_outputs), dtype=np.int32)\n for i in range(len(model_outputs)):\n pred = model_outputs[i]\n if self.model.model_type == ModelTypes.Classifier:\n if self.num_output_nodes == 2: # binary\n pred_1 = pred[self.num_output_nodes-1]\n validity[i] = 1 if \\\n ((self.target_cf_class == 0 and pred_1 <= self.stopping_threshold) or\n (self.target_cf_class == 1 and pred_1 >= self.stopping_threshold)) else 0\n else: # multiclass\n if np.argmax(pred) == self.target_cf_class:\n validity[i] = 1\n elif self.model.model_type == ModelTypes.Regressor:\n if self.target_cf_range[0] <= pred <= self.target_cf_range[1]:\n validity[i] = 1\n return validity\n\n def is_cf_valid(self, model_score):\n \"\"\"Check if a cf belongs to the target class or target range.\n \"\"\"\n # Converting to single prediction if the prediction is provided as a\n # singleton array\n correct_dim = 1 if self.model.model_type == ModelTypes.Classifier else 0\n if hasattr(model_score, \"shape\") and len(model_score.shape) > correct_dim:\n model_score = model_score[0]\n # Converting target_cf_class to a scalar (tf/torch have it as (1,1) shape)\n if self.model.model_type == ModelTypes.Classifier:\n target_cf_class = self.target_cf_class\n if hasattr(self.target_cf_class, \"shape\"):\n if len(self.target_cf_class.shape) == 1:\n target_cf_class = self.target_cf_class[0]\n elif len(self.target_cf_class.shape) == 2:\n target_cf_class = self.target_cf_class[0][0]\n target_cf_class = int(target_cf_class)\n\n if self.num_output_nodes == 1: # for tensorflow/pytorch models\n pred_1 = model_score[0]\n validity = True if \\\n ((target_cf_class == 0 and pred_1 <= self.stopping_threshold) or\n (target_cf_class == 1 and pred_1 >= self.stopping_threshold)) else False\n return validity\n if self.num_output_nodes == 2: # binary\n pred_1 = model_score[self.num_output_nodes-1]\n validity = True if \\\n ((target_cf_class == 0 and pred_1 <= self.stopping_threshold) or\n (target_cf_class == 1 and pred_1 >= self.stopping_threshold)) else False\n return validity\n else: # multiclass\n return np.argmax(model_score) == target_cf_class\n else:\n return self.target_cf_range[0] <= model_score and model_score <= self.target_cf_range[1]\n\n def get_model_output_from_scores(self, model_scores):\n if self.model.model_type == ModelTypes.Classifier:\n output_type = np.int32\n else:\n output_type = np.float32\n model_output = np.zeros(len(model_scores), dtype=output_type)\n for i in range(len(model_scores)):\n if self.model.model_type == ModelTypes.Classifier:\n model_output[i] = np.argmax(model_scores[i])\n elif self.model.model_type == ModelTypes.Regressor:\n model_output[i] = model_scores[i]\n return model_output\n\n def check_permitted_range(self, permitted_range):\n \"\"\"checks permitted range for continuous features\n TODO: add comments as to where this is used if this function is necessary, else remove.\n \"\"\"\n if permitted_range is not None:\n # if not self.data_interface.check_features_range(permitted_range):\n # raise ValueError(\n # \"permitted range of features should be within their original range\")\n # else:\n self.data_interface.permitted_range = permitted_range\n self.minx, self.maxx = self.data_interface.get_minx_maxx(normalized=True)\n self.cont_minx = []\n self.cont_maxx = []\n for feature in self.data_interface.continuous_feature_names:\n self.cont_minx.append(self.data_interface.permitted_range[feature][0])\n self.cont_maxx.append(self.data_interface.permitted_range[feature][1])\n\n def check_mad_validity(self, feature_weights):\n \"\"\"checks feature MAD validity and throw warnings.\n TODO: add comments as to where this is used if this function is necessary, else remove.\n \"\"\"\n if feature_weights == \"inverse_mad\":\n self.data_interface.get_valid_mads(display_warnings=True, return_mads=False)\n\n def sigmoid(self, z):\n \"\"\"This is used in VAE-based CF explainers.\"\"\"\n return 1 / (1 + np.exp(-z))\n\n def build_KD_tree(self, data_df_copy, desired_range, desired_class, predicted_outcome_name):\n # Stores the predictions on the training data\n dataset_instance = self.data_interface.prepare_query_instance(\n query_instance=data_df_copy[self.data_interface.feature_names])\n\n predictions = self.model.model.predict(dataset_instance)\n # TODO: Is it okay to insert a column in the original dataframe with the predicted outcome? This is memory-efficient\n data_df_copy[predicted_outcome_name] = predictions\n\n # segmenting the dataset according to outcome\n dataset_with_predictions = None\n if self.model.model_type == ModelTypes.Classifier:\n dataset_with_predictions = data_df_copy.loc[[i == desired_class for i in predictions]].copy()\n\n elif self.model.model_type == ModelTypes.Regressor:\n dataset_with_predictions = data_df_copy.loc[\n [desired_range[0] <= pred <= desired_range[1] for pred in predictions]].copy()\n\n KD_tree = None\n # Prepares the KD trees for DiCE\n if len(dataset_with_predictions) > 0:\n dummies = pd.get_dummies(dataset_with_predictions[self.data_interface.feature_names])\n KD_tree = KDTree(dummies)\n\n return dataset_with_predictions, KD_tree, predictions\n\n def round_to_precision(self):\n # to display the values with the same precision as the original data\n precisions = self.data_interface.get_decimal_precisions()\n for ix, feature in enumerate(self.data_interface.continuous_feature_names):\n self.final_cfs_df[feature] = self.final_cfs_df[feature].astype(float).round(precisions[ix])\n if self.final_cfs_df_sparse is not None:\n self.final_cfs_df_sparse[feature] = self.final_cfs_df_sparse[feature].astype(float).round(precisions[ix])"
] | [
[
"numpy.isclose",
"sklearn.neighbors.KDTree",
"numpy.sign",
"numpy.argmax",
"numpy.exp",
"pandas.get_dummies"
]
] |
collector-m/pole-localization | [
"719d14e2c325a6528e71114691fe15733a6f31eb"
] | [
"src/poles_extractor.py"
] | [
"import numpy as np\nfrom numba import jit\n\ndef detect_poles(xyz, neighbourthr = 0.5, min_point_num = 3, dis_thr = 0.08, width_thr = 10, fov_up=30.67, fov_down=-10.67, proj_H = 32, proj_W = 250, lowest=0.1, highest=6, lowthr = 1.5, highthr = 0.7, totalthr = 0.6):\n range_data, proj_vertex, _ = range_projection(xyz,\n fov_up=fov_up,\n fov_down=fov_down,\n proj_H=proj_H,\n proj_W=proj_W,\n max_range=50, \n cut_z = True, \n low=lowest, \n high=highest)\n \n height = range_data.shape[0]\n width = range_data.shape[1]\n\n open_set = gen_open_set(range_data, height, width)\n open_set = np.array(open_set)\n\n clusters = gen_clusters(open_set, range_data, height, width, min_point_num = min_point_num, dis_thr = dis_thr)\n\n clusters_list = []\n for cluster in clusters:\n clusters_list.append(cluster.tolist())\n\n clusters_copy = list(clusters_list)\n for cluster in clusters_copy:\n cluster.sort()\n min_height = cluster[0][0]\n max_height = cluster[len(cluster)-1][0]\n cluster.sort(key=takeSecond)\n min_width = cluster[0][1]\n max_width = cluster[len(cluster)-1][1]\n ratio = (max_height - min_height + 1) / (max_width - min_width + 1)\n delate = 0\n dela = False\n for index in cluster:\n index[0] = int(index[0])\n index[1] = int(index[1])\n if (range_data[index[0],index[1]+1] != -1) and (not [index[0],index[1]+1] in cluster) and range_data[index[0]][index[1]] > range_data[index[0],index[1]+1]:\n dela = True\n if (range_data[index[0],index[1]-1] != -1) and (not [index[0],index[1]-1] in cluster) and range_data[index[0]][index[1]] > range_data[index[0],index[1]-1]:\n dela = True\n if dela:\n delate += 1\n dela = False\n if ratio < 1.0 or delate > 0.3 * len(cluster) or (max_width - min_width + 1) > width_thr:\n clusters_list.remove(cluster)\n\n poleparams = np.empty([0, 3])\n for cluster in clusters_list:\n x = []\n y = []\n z = []\n for index in cluster:\n index[0] = int(index[0])\n index[1] = int(index[1])\n x.append(proj_vertex[index[0]][index[1]][0])\n y.append(proj_vertex[index[0]][index[1]][1])\n z.append(proj_vertex[index[0]][index[1]][2])\n\n high = max(z)\n low = min(z) \n if high > highthr and low < lowthr and (high-low) > totalthr:\n if fit_circle(x,y) != None:\n average_x,average_y,R_1 = fit_circle(x,y)\n fine_thr = R_1 + 0.1\n scan_x = xyz[:, 0]\n scan_y = xyz[:, 1]\n scan_z = xyz[:, 2]\n\n high = min(high,3.0)\n \n current_vertex_fine = xyz[(scan_x > (average_x - fine_thr)) & (scan_x < (average_x + fine_thr)) & (scan_y < (average_y + fine_thr)) & (scan_y > (average_y - fine_thr)) & (scan_z < high) & (scan_z > low)]\n x = []\n y = []\n for i in range(current_vertex_fine.shape[0]):\n x.append(current_vertex_fine[i, 0])\n y.append(current_vertex_fine[i, 1])\n if len(x) >= 6:\n if fit_circle(x,y) != None:\n xc_1, yc_1, R_1 = fit_circle(x,y)\n if R_1 > 0.02 and R_1 < 0.4:\n neighbour = xyz[(((scan_x > (average_x - fine_thr - neighbourthr)) & (scan_x < (average_x - fine_thr))) | ((scan_x > (average_x + fine_thr)) & (scan_x < (average_x + fine_thr + neighbourthr)))) & (((scan_y > (average_y + fine_thr - neighbourthr)) & (scan_y < (average_y - fine_thr))) | ((scan_y > (average_y + fine_thr)) & (scan_y < (average_y + fine_thr + neighbourthr)))) & (scan_z < high) & (scan_z > low)]\n if neighbour.shape[0] < 0.15 * current_vertex_fine.shape[0]:\n poleparams = np.vstack([poleparams, [xc_1,yc_1,R_1]])\n\n return poleparams\n\n@jit(nopython=True)\ndef gen_open_set(range_data, height, width):\n open_set = []\n for i in range(1,height-1):\n for j in range(1,width-1):\n if range_data[i][j] != -1:\n open_set.append([i, j])\n return open_set\n\n@jit(nopython=True)\ndef in_array(set, index):\n for i in range(set.shape[0]):\n if set[i][0] == index[0] and set[i][1] == index[1]:\n return True\n return False\n\n@jit(nopython=True)\ndef gen_clusters(open_set, range_data, height, width, min_point_num = 3, dis_thr = 0.08):\n clusters = []\n while open_set.shape[0] > 0:\n cluster = np.zeros((0, 2))\n current_index = open_set[0]\n open_set = np.delete(open_set, [0,1]).reshape((-1, 2))\n cluster = np.append(cluster, current_index).reshape((-1, 2))\n near_set = np.zeros((0, 2), dtype=np.int64)\n\n if (current_index[0]+1 < height) and (in_array(open_set, np.array([current_index[0]+1,current_index[1]]))) and abs(range_data[current_index[0]][current_index[1]] - range_data[current_index[0]+1][current_index[1]]) < dis_thr:\n near_set = np.append(near_set, [current_index[0]+1, current_index[1]]).reshape((-1, 2))\n if (current_index[1]+1 < width) and (in_array(open_set, np.array([current_index[0],current_index[1]+1]))) and abs(range_data[current_index[0]][current_index[1]] - range_data[current_index[0]][current_index[1]+1]) < dis_thr:\n near_set = np.append(near_set, [current_index[0], current_index[1]+1]).reshape((-1, 2))\n while len(near_set) > 0:\n near_index = near_set[0]\n near_set = np.delete(near_set, [0,1]).reshape((-1, 2))\n for i in range(open_set.shape[0]):\n if open_set[i][0] == near_index[0] and open_set[i][1] == near_index[1]:\n open_set = np.delete(open_set, [2*i,2*i+1]).reshape((-1, 2))\n break \n cluster = np.append(cluster, near_index).reshape((-1, 2))\n if (near_index[0]+1 < height) and (in_array(open_set, np.array([near_index[0]+1, near_index[1]]))) and (not in_array(cluster, np.array([near_index[0]+1, near_index[1]]))) and (not in_array(near_set, np.array([near_index[0]+1, near_index[1]]))) and (abs(range_data[near_index[0]][near_index[1]] - range_data[near_index[0]+1][near_index[1]]) < dis_thr):\n near_set = np.append(near_set, [near_index[0]+1, near_index[1]]).reshape((-1, 2))\n if (near_index[1]+1 < width) and (in_array(open_set, np.array([near_index[0], near_index[1]+1]))) and (not in_array(cluster, np.array([near_index[0], near_index[1]+1]))) and (not in_array(near_set, np.array([near_index[0], near_index[1]+1]))) and (abs(range_data[near_index[0]][near_index[1]] - range_data[near_index[0]][near_index[1]+1]) < dis_thr):\n near_set = np.append(near_set, [near_index[0], near_index[1]+1]).reshape((-1, 2))\n if (near_index[1]-1 >= 0) and (in_array(open_set, np.array([near_index[0], near_index[1]-1]))) and (not in_array(cluster, np.array([near_index[0], near_index[1]-1]))) and (not in_array(near_set, np.array([near_index[0], near_index[1]-1]))) and (abs(range_data[near_index[0]][near_index[1]] - range_data[near_index[0]][near_index[1]-1]) < dis_thr):\n near_set = np.append(near_set, [near_index[0], near_index[1]-1]).reshape((-1, 2))\n\n if cluster.shape[0] > min_point_num:\n clusters.append(cluster)\n return clusters\n\ndef takeSecond(elem):\n return elem[1]\n\ndef range_projection(current_vertex, fov_up=10.67, fov_down=-30.67, proj_H=32, proj_W=900, max_range=50, cut_z = True, low=0.1, high=6):\n \"\"\" Project a pointcloud into a spherical projection, range image.\n Args:\n current_vertex: raw point clouds\n Returns: \n proj_range: projected range image with depth, each pixel contains the corresponding depth\n proj_vertex: each pixel contains the corresponding point (x, y, z, 1)\n proj_idx: each pixel contains the corresponding index of the point in the raw point cloud\n \"\"\"\n # laser parameters\n fov_up = fov_up / 180.0 * np.pi # field of view up in radians\n fov_down = fov_down / 180.0 * np.pi # field of view down in radians\n fov = abs(fov_down) + abs(fov_up) # get field of view total in radians\n\n # get depth of all points\n depth = np.linalg.norm(current_vertex[:, :3], 2, axis=1)\n\n if cut_z:\n z = current_vertex[:, 2]\n current_vertex = current_vertex[(depth > 0) & (depth < max_range) & (z < high) & (z > low)] # get rid of [0, 0, 0] points\n depth = depth[(depth > 0) & (depth < max_range) & (z < high) & (z > low)]\n else:\n current_vertex = current_vertex[(depth > 0) & (depth < max_range)] # get rid of [0, 0, 0] points\n depth = depth[(depth > 0) & (depth < max_range)]\n\n # get scan components\n scan_x = current_vertex[:, 0]\n scan_y = current_vertex[:, 1]\n scan_z = current_vertex[:, 2]\n\n # get angles of all points\n yaw = -np.arctan2(scan_y, scan_x)\n pitch = np.arcsin(scan_z / depth)\n\n # get projections in image coords\n proj_x = 0.5 * (yaw / np.pi + 1.0) # in [0.0, 1.0]\n proj_y = 1.0 - (pitch + abs(fov_down)) / fov # in [0.0, 1.0]\n\n # scale to image size using angular resolution\n proj_x *= proj_W # in [0.0, W]\n proj_y *= proj_H # in [0.0, H]\n\n # round and clamp for use as index\n proj_x = np.floor(proj_x)\n proj_x = np.minimum(proj_W - 1, proj_x)\n proj_x = np.maximum(0, proj_x).astype(np.int32) # in [0,W-1]\n\n proj_y = np.floor(proj_y)\n proj_y = np.minimum(proj_H - 1, proj_y)\n proj_y = np.maximum(0, proj_y).astype(np.int32) # in [0,H-1]\n\n # order in decreasing depth\n order = np.argsort(depth)[::-1]\n depth = depth[order]\n proj_y = proj_y[order]\n proj_x = proj_x[order]\n\n scan_x = scan_x[order]\n scan_y = scan_y[order]\n scan_z = scan_z[order]\n\n indices = np.arange(depth.shape[0])\n indices = indices[order]\n\n proj_range = np.full((proj_H, proj_W), -1,\n dtype=np.float32) # [H,W] range (-1 is no data)\n proj_vertex = np.full((proj_H, proj_W, 4), -1,\n dtype=np.float32) # [H,W] index (-1 is no data)\n proj_idx = np.full((proj_H, proj_W), -1,\n dtype=np.int32) # [H,W] index (-1 is no data)\n\n proj_range[proj_y, proj_x] = depth\n proj_vertex[proj_y, proj_x] = np.array([scan_x, scan_y, scan_z, np.ones(len(scan_x))]).T\n proj_idx[proj_y, proj_x] = indices\n\n return proj_range, proj_vertex, proj_idx\n\ndef fit_circle(x, y):\n x_m = sum(x)/len(x)\n y_m = sum(y)/len(y)\n u = x - x_m\n v = y - y_m\n # linear system defining the center in reduced coordinates (uc, vc):\n # Suu * uc + Suv * vc = (Suuu + Suvv)/2\n # Suv * uc + Svv * vc = (Suuv + Svvv)/2\n Suv = sum(u*v)\n Suu = sum(u**2)\n Svv = sum(v**2)\n Suuv = sum(u**2 * v)\n Suvv = sum(u * v**2)\n Suuu = sum(u**3)\n Svvv = sum(v**3)\n\n # Solving the linear system\n A = np.array([ [ Suu, Suv ], [Suv, Svv]])\n B = np.array([ Suuu + Suvv, Svvv + Suuv ])/2.0\n\n if np.linalg.det(A) != 0:\n uc, vc = np.linalg.solve(A, B)\n xc_1 = x_m + uc\n yc_1 = y_m + vc\n # Calculation of all distances from the center (xc_1, yc_1)\n Ri_1 = np.sqrt((x-xc_1)**2 + (y-yc_1)**2)\n R_1 = np.mean(Ri_1)\n return xc_1,yc_1,R_1\n\n return None"
] | [
[
"numpy.minimum",
"numpy.sqrt",
"numpy.arctan2",
"numpy.mean",
"numpy.arcsin",
"numpy.arange",
"numpy.full",
"numpy.linalg.det",
"numpy.zeros",
"numpy.delete",
"numpy.append",
"numpy.floor",
"numpy.argsort",
"numpy.array",
"numpy.linalg.solve",
"numpy.maximum",
"numpy.linalg.norm",
"numpy.empty",
"numpy.vstack"
]
] |
Kuigesi/PipelineExecution-Reproducible | [
"f9c78989a872cddbf38e39a007b2e72f8c7f27e7"
] | [
"benchmark_plot.py"
] | [
"import pandas as pd\nimport matplotlib.pyplot as plt\nimport matplotlib.ticker as mtick\n\n\nif __name__==\"__main__\":\n\n # Load data\n df = pd.read_csv('./data/benchmark.csv', index_col=0)\n\n # rename index\n df.rename(index={'Data Parallism (2 GPU)': 'Data Parallism\\n(2 GPU)',\\\n 'Data Parallism (4 GPU)': 'Data Parallism\\n(4 GPU)', 'Mixed Parallism (no pipeline)':\\\n 'Mixed Parallism\\n(no pipeline)', 'Mixed Parallism (4 pipelines)': 'Mixed Parallism\\n(4 pipelines)',\\\n 'Mixed Parallism (8 pipelines)': 'Mixed Parallism\\n(8 pipelines)'}, inplace=True)\n df['Runtime'] = df['Runtime'].round(3)\n\n # plot runtime\n ax = df.plot.bar(grid=False, figsize=(8,4))\n plt.xticks(rotation=0)\n (low, high) = plt.ylim()\n plt.ylim(low, high*1.1)\n plt.xlabel(\"\")\n plt.ylabel(\"\")\n plt.title(\"Runtime of 40 iterations (sec)\")\n for col in df.columns:\n for id, val in enumerate(df[col]):\n ax.text(id, val+1.4, str(val), va=\"top\", ha=\"center\")\n plt.legend().remove()\n plt.savefig(\"./pictures/pipelineparallelruntime.pdf\", format=\"pdf\", bbox_inches=\"tight\")\n\n # plot speed up\n dfspeedup = df.rename(columns={'Runtime':'Speed Up'})\n baseline = dfspeedup.loc['Data Parallism\\n(2 GPU)']['Speed Up']\n dfspeedup['Speed Up'] = baseline / dfspeedup['Speed Up']\n dfspeedup['Speed Up'] = dfspeedup['Speed Up'].round(2)\n axspeed = dfspeedup.plot.bar(grid=False, figsize=(8,4))\n axspeed.yaxis.set_major_formatter(mtick.PercentFormatter(xmax=1, decimals=None, symbol='%', is_latex=False))\n plt.xticks(rotation=0)\n (low, high) = plt.ylim()\n plt.ylim(low, high*1.1)\n plt.xlabel(\"\")\n plt.ylabel(\"\")\n plt.title(\"Speed Up\")\n for col in dfspeedup.columns:\n for id, val in enumerate(dfspeedup[col]):\n axspeed.text(id, val+0.14, str(round(val*100))+'%', va=\"top\", ha=\"center\")\n plt.legend().remove()\n plt.savefig(\"./pictures/pipelineparallelspeedup.pdf\", format=\"pdf\", bbox_inches=\"tight\")\n"
] | [
[
"matplotlib.pyplot.legend",
"pandas.read_csv",
"matplotlib.ticker.PercentFormatter",
"matplotlib.pyplot.title",
"matplotlib.pyplot.ylim",
"matplotlib.pyplot.savefig",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.xticks",
"matplotlib.pyplot.ylabel"
]
] |
lunlun1992/vmaf | [
"efb80822c6a7d8431928404be68a32a1f1574311"
] | [
"python/tools/plot.py"
] | [
"from matplotlib import pyplot as plt\nimport numpy as np\n\n__copyright__ = \"Copyright 2016, Netflix, Inc.\"\n__license__ = \"Apache, Version 2.0\"\n\n\ndef get_cdf(x, num_bins=100):\n x = np.array(x)\n counts, bin_edges = np.histogram(x, bins=num_bins)\n cdf = np.cumsum(counts)\n cdf = cdf / float(cdf[-1]) # normalize\n bin_edges = bin_edges[1:] # make size\n return cdf, bin_edges\n\n\ndef get_pdf(data, num_bins=20):\n pdf, bin_edges = np.histogram(data, density=True, bins=num_bins)\n bin_centres = (bin_edges[:-1] + bin_edges[1:])/2\n return pdf, bin_centres\n\n\ndef plot_distribution(plot_type, df, key, slice_name, slices, colors=None):\n if colors is None:\n colors = [None for _ in slices]\n handles = []\n for slice, color in zip(slices, colors):\n if isinstance(slice, (list, tuple)):\n data = df.loc[df[slice_name].isin(slice)][key].tolist()\n else:\n data = df.loc[df[slice_name] == slice][key].tolist()\n if plot_type == 'cdf':\n ys, xs = get_cdf(data)\n plt.ylabel('CDF')\n elif plot_type == 'pdf':\n ys, xs = get_pdf(data)\n plt.ylabel('PDF')\n else:\n assert False, \"Unknown plot type: {}\".format(plot_type)\n if color:\n handle = plt.plot(xs, ys, label=\"{}\".format(str(slice)), color=color)\n else:\n handle = plt.plot(xs, ys, label=\"{}\".format(str(slice)))\n plt.grid(which='major')\n handles.append(handle)\n return handles\n"
] | [
[
"numpy.cumsum",
"matplotlib.pyplot.grid",
"numpy.array",
"numpy.histogram",
"matplotlib.pyplot.ylabel"
]
] |
idiap/DepthInSpace | [
"fe759807f82df4c48c16b97f061718175ea0e6e9"
] | [
"co/metric.py"
] | [
"# DepthInSpace is a PyTorch-based program which estimates 3D depth maps\n# from active structured-light sensor's multiple video frames.\n#\n# MIT License\n#\n# Copyright (c) 2019 autonomousvision\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\nimport numpy as np\nfrom . import geometry\n\ndef _process_inputs(estimate, target, mask):\n if estimate.shape != target.shape:\n raise Exception('estimate and target have to be same shape')\n if mask is None:\n mask = np.ones(estimate.shape, dtype=np.bool)\n else:\n mask = mask != 0\n if estimate.shape != mask.shape:\n raise Exception('estimate and mask have to be same shape')\n return estimate, target, mask\n\ndef mse(estimate, target, mask=None):\n estimate, target, mask = _process_inputs(estimate, target, mask)\n m = np.sum((estimate[mask] - target[mask])**2) / mask.sum()\n return m\n\ndef rmse(estimate, target, mask=None):\n return np.sqrt(mse(estimate, target, mask))\n\ndef mae(estimate, target, mask=None):\n estimate, target, mask = _process_inputs(estimate, target, mask)\n m = np.abs(estimate[mask] - target[mask]).sum() / mask.sum()\n return m\n\ndef outlier_fraction(estimate, target, mask=None, threshold=0):\n estimate, target, mask = _process_inputs(estimate, target, mask)\n diff = np.abs(estimate[mask] - target[mask])\n m = (diff > threshold).sum() / mask.sum()\n return m\n\n\nclass Metric(object):\n def __init__(self, str_prefix=''):\n self.str_prefix = str_prefix\n self.reset()\n\n def reset(self):\n pass\n\n def add(self, es, ta, ma=None):\n pass\n\n def get(self):\n return {}\n\n def items(self):\n return self.get().items()\n\n def __str__(self):\n return ', '.join([f'{self.str_prefix}{key}={value:.5f}' for key, value in self.get().items()])\n\nclass MultipleMetric(Metric):\n def __init__(self, *metrics, **kwargs):\n self.metrics = [*metrics]\n super().__init__(**kwargs)\n\n def reset(self):\n for m in self.metrics:\n m.reset()\n\n def add(self, es, ta, ma=None):\n for m in self.metrics:\n m.add(es, ta, ma)\n\n def get(self):\n ret = {}\n for m in self.metrics:\n vals = m.get()\n for k in vals:\n ret[k] = vals[k]\n return ret\n\n def __str__(self):\n return '\\n'.join([str(m) for m in self.metrics])\n\nclass BaseDistanceMetric(Metric):\n def __init__(self, name='', **kwargs):\n super().__init__(**kwargs)\n self.name = name\n\n def reset(self):\n self.dists = []\n\n def add(self, es, ta, ma=None):\n pass\n\n def get(self):\n dists = np.hstack(self.dists)\n return {\n f'dist{self.name}_mean': float(np.mean(dists)),\n f'dist{self.name}_std': float(np.std(dists)),\n f'dist{self.name}_median': float(np.median(dists)),\n f'dist{self.name}_q10': float(np.percentile(dists, 10)),\n f'dist{self.name}_q90': float(np.percentile(dists, 90)),\n f'dist{self.name}_min': float(np.min(dists)),\n f'dist{self.name}_max': float(np.max(dists)),\n }\n\nclass DistanceMetric(BaseDistanceMetric):\n def __init__(self, vec_length, p=2, **kwargs):\n super().__init__(name=f'{p}', **kwargs)\n self.vec_length = vec_length\n self.p = p\n\n def add(self, es, ta, ma=None):\n if es.shape != ta.shape or es.shape[1] != self.vec_length or es.ndim != 2:\n print(es.shape, ta.shape)\n raise Exception('es and ta have to be of shape Nxdim')\n if ma is not None:\n es = es[ma != 0]\n ta = ta[ma != 0]\n dist = np.linalg.norm(es - ta, ord=self.p, axis=1)\n self.dists.append( dist )\n\nclass OutlierFractionMetric(DistanceMetric):\n def __init__(self, thresholds, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.thresholds = thresholds\n\n def get(self):\n dists = np.hstack(self.dists)\n ret = {}\n for t in self.thresholds:\n ma = dists > t\n ret[f'of{t}'] = float(ma.sum() / ma.size)\n return ret\n\nclass RelativeDistanceMetric(BaseDistanceMetric):\n def __init__(self, vec_length, p=2, **kwargs):\n super().__init__(name=f'rel{p}', **kwargs)\n self.vec_length = vec_length\n self.p = p\n\n def add(self, es, ta, ma=None):\n if es.shape != ta.shape or es.shape[1] != self.vec_length or es.ndim != 2:\n raise Exception('es and ta have to be of shape Nxdim')\n dist = np.linalg.norm(es - ta, ord=self.p, axis=1)\n denom = np.linalg.norm(ta, ord=self.p, axis=1)\n dist /= denom\n if ma is not None:\n dist = dist[ma != 0]\n self.dists.append( dist )\n\nclass RotmDistanceMetric(BaseDistanceMetric):\n def __init__(self, type='identity', **kwargs):\n super().__init__(name=type, **kwargs)\n self.type = type\n\n def add(self, es, ta, ma=None):\n if es.shape != ta.shape or es.shape[1] != 3 or es.shape[2] != 3 or es.ndim != 3:\n print(es.shape, ta.shape)\n raise Exception('es and ta have to be of shape Nx3x3')\n if ma is not None:\n raise Exception('mask is not implemented')\n if self.type == 'identity':\n self.dists.append( geometry.rotm_distance_identity(es, ta) )\n elif self.type == 'geodesic':\n self.dists.append( geometry.rotm_distance_geodesic_unit_sphere(es, ta) )\n else:\n raise Exception('invalid distance type')\n\nclass QuaternionDistanceMetric(BaseDistanceMetric):\n def __init__(self, type='angle', **kwargs):\n super().__init__(name=type, **kwargs)\n self.type = type\n\n def add(self, es, ta, ma=None):\n if es.shape != ta.shape or es.shape[1] != 4 or es.ndim != 2:\n print(es.shape, ta.shape)\n raise Exception('es and ta have to be of shape Nx4')\n if ma is not None:\n raise Exception('mask is not implemented')\n if self.type == 'angle':\n self.dists.append( geometry.quat_distance_angle(es, ta) )\n elif self.type == 'mineucl':\n self.dists.append( geometry.quat_distance_mineucl(es, ta) )\n elif self.type == 'normdiff':\n self.dists.append( geometry.quat_distance_normdiff(es, ta) )\n else:\n raise Exception('invalid distance type')\n\n\nclass BinaryAccuracyMetric(Metric):\n def __init__(self, thresholds=np.linspace(0.0, 1.0, num=101, dtype=np.float64)[:-1], **kwargs):\n self.thresholds = thresholds\n super().__init__(**kwargs)\n\n def reset(self):\n self.tps = [0 for wp in self.thresholds]\n self.fps = [0 for wp in self.thresholds]\n self.fns = [0 for wp in self.thresholds]\n self.tns = [0 for wp in self.thresholds]\n self.n_pos = 0\n self.n_neg = 0\n\n def add(self, es, ta, ma=None):\n if ma is not None:\n raise Exception('mask is not implemented')\n es = es.ravel()\n ta = ta.ravel()\n if es.shape[0] != ta.shape[0]:\n raise Exception('invalid shape of es, or ta')\n if es.min() < 0 or es.max() > 1:\n raise Exception('estimate has wrong value range')\n ta_p = (ta == 1)\n ta_n = (ta == 0)\n es_p = es[ta_p]\n es_n = es[ta_n]\n for idx, wp in enumerate(self.thresholds):\n wp = np.asscalar(wp)\n self.tps[idx] += (es_p > wp).sum()\n self.fps[idx] += (es_n > wp).sum()\n self.fns[idx] += (es_p <= wp).sum()\n self.tns[idx] += (es_n <= wp).sum()\n self.n_pos += ta_p.sum()\n self.n_neg += ta_n.sum()\n\n def get(self):\n tps = np.array(self.tps).astype(np.float32)\n fps = np.array(self.fps).astype(np.float32)\n fns = np.array(self.fns).astype(np.float32)\n tns = np.array(self.tns).astype(np.float32)\n wp = self.thresholds\n\n ret = {}\n\n precisions = np.divide(tps, tps + fps, out=np.zeros_like(tps), where=tps + fps != 0)\n recalls = np.divide(tps, tps + fns, out=np.zeros_like(tps), where=tps + fns != 0) # tprs\n fprs = np.divide(fps, fps + tns, out=np.zeros_like(tps), where=fps + tns != 0)\n\n precisions = np.r_[0, precisions, 1]\n recalls = np.r_[1, recalls, 0]\n fprs = np.r_[1, fprs, 0]\n\n ret['auc'] = float(-np.trapz(recalls, fprs))\n ret['prauc'] = float(-np.trapz(precisions, recalls))\n ret['ap'] = float(-(np.diff(recalls) * precisions[:-1]).sum())\n\n accuracies = np.divide(tps + tns, tps + tns + fps + fns)\n aacc = np.mean(accuracies)\n for t in np.linspace(0,1,num=11)[1:-1]:\n idx = np.argmin(np.abs(t - wp))\n ret[f'acc{wp[idx]:.2f}'] = float(accuracies[idx])\n\n return ret\n"
] | [
[
"numpy.hstack",
"numpy.asscalar",
"numpy.abs",
"numpy.linspace",
"numpy.min",
"numpy.median",
"numpy.linalg.norm",
"numpy.percentile",
"numpy.ones",
"numpy.max",
"numpy.std",
"numpy.mean",
"numpy.zeros_like",
"numpy.diff",
"numpy.trapz",
"numpy.array",
"numpy.sum",
"numpy.divide"
]
] |
zhong110020/tensorflow | [
"b79ce0029dce3264266ced739590bc238b17096c"
] | [
"tensorflow/python/framework/graph_util_test.py"
] | [
"# Copyright 2015 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"Tests for tensorflow.python.client.graph_util.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nfrom tensorflow.core.framework import attr_value_pb2\nfrom tensorflow.core.framework import graph_pb2\nfrom tensorflow.core.framework import node_def_pb2\nfrom tensorflow.python.client import session\nfrom tensorflow.python.framework import constant_op\nfrom tensorflow.python.framework import dtypes\nfrom tensorflow.python.framework import function\nfrom tensorflow.python.framework import graph_util\nfrom tensorflow.python.framework import importer\nfrom tensorflow.python.framework import ops\nfrom tensorflow.python.framework import tensor_util\nfrom tensorflow.python.ops import gen_state_ops\nfrom tensorflow.python.ops import math_ops # pylint: disable=unused-import\nfrom tensorflow.python.ops import math_ops as math_ops_lib\nfrom tensorflow.python.ops import variables\nfrom tensorflow.python.platform import test\n\n\n# Utility device function to use for testing\ndef test_device_func_pin_variable_to_cpu(op):\n if op.device:\n return op.device\n return \"/cpu:0\" if op.node_def.op in [\"Variable\", \"VariableV2\"] else op.device\n\n\nclass DeviceFunctionsTest(test.TestCase):\n\n def testTwoDeviceFunctions(self):\n with ops.Graph().as_default() as g:\n var_0 = gen_state_ops.variable(\n shape=[1],\n dtype=dtypes.float32,\n name=\"var_0\",\n container=\"\",\n shared_name=\"\")\n with g.device(test_device_func_pin_variable_to_cpu):\n var_1 = gen_state_ops.variable(\n shape=[1],\n dtype=dtypes.float32,\n name=\"var_1\",\n container=\"\",\n shared_name=\"\")\n var_2 = gen_state_ops.variable(\n shape=[1],\n dtype=dtypes.float32,\n name=\"var_2\",\n container=\"\",\n shared_name=\"\")\n var_3 = gen_state_ops.variable(\n shape=[1],\n dtype=dtypes.float32,\n name=\"var_3\",\n container=\"\",\n shared_name=\"\")\n with g.device(test_device_func_pin_variable_to_cpu):\n var_4 = gen_state_ops.variable(\n shape=[1],\n dtype=dtypes.float32,\n name=\"var_4\",\n container=\"\",\n shared_name=\"\")\n with g.device(\"/device:GPU:0\"):\n var_5 = gen_state_ops.variable(\n shape=[1],\n dtype=dtypes.float32,\n name=\"var_5\",\n container=\"\",\n shared_name=\"\")\n var_6 = gen_state_ops.variable(\n shape=[1],\n dtype=dtypes.float32,\n name=\"var_6\",\n container=\"\",\n shared_name=\"\")\n\n self.assertDeviceEqual(var_0.device, None)\n self.assertDeviceEqual(var_1.device, \"/device:CPU:0\")\n self.assertDeviceEqual(var_2.device, None)\n self.assertDeviceEqual(var_3.device, None)\n self.assertDeviceEqual(var_4.device, \"/device:CPU:0\")\n self.assertDeviceEqual(var_5.device, \"/device:GPU:0\")\n self.assertDeviceEqual(var_6.device, \"/device:CPU:0\")\n\n def testNestedDeviceFunctions(self):\n with ops.Graph().as_default():\n var_0 = variables.Variable(0)\n with ops.device(test_device_func_pin_variable_to_cpu):\n var_1 = variables.Variable(1)\n with ops.device(lambda op: \"/device:GPU:0\"):\n var_2 = variables.Variable(2)\n with ops.device(\"/device:GPU:0\"): # Implicit merging device function.\n var_3 = variables.Variable(3)\n\n self.assertDeviceEqual(var_0.device, None)\n self.assertDeviceEqual(var_1.device, \"/device:CPU:0\")\n self.assertDeviceEqual(var_2.device, \"/device:GPU:0\")\n self.assertDeviceEqual(var_3.device, \"/device:GPU:0\")\n\n def testExplicitDevice(self):\n with ops.Graph().as_default() as g:\n const_0 = constant_op.constant(5.0)\n with g.device(\"/device:GPU:0\"):\n const_1 = constant_op.constant(5.0)\n with g.device(\"/device:GPU:1\"):\n const_2 = constant_op.constant(5.0)\n with g.device(\"/device:CPU:0\"):\n const_3 = constant_op.constant(5.0)\n with g.device(\"/device:CPU:1\"):\n const_4 = constant_op.constant(5.0)\n with g.device(\"/job:ps\"):\n const_5 = constant_op.constant(5.0)\n\n self.assertDeviceEqual(const_0.device, None)\n self.assertDeviceEqual(const_1.device, \"/device:GPU:0\")\n self.assertDeviceEqual(const_2.device, \"/device:GPU:1\")\n self.assertDeviceEqual(const_3.device, \"/device:CPU:0\")\n self.assertDeviceEqual(const_4.device, \"/device:CPU:1\")\n self.assertDeviceEqual(const_5.device, \"/job:ps\")\n\n def testDefaultDevice(self):\n with ops.Graph().as_default() as g, g.device(\n test_device_func_pin_variable_to_cpu):\n with g.device(\"/job:ps\"):\n const_0 = constant_op.constant(5.0)\n with g.device(\"/device:GPU:0\"):\n const_1 = constant_op.constant(5.0)\n with g.device(\"/device:GPU:1\"):\n const_2 = constant_op.constant(5.0)\n with g.device(\"/device:CPU:0\"):\n const_3 = constant_op.constant(5.0)\n with g.device(\"/device:CPU:1\"):\n const_4 = constant_op.constant(5.0)\n with g.device(\"/replica:0\"):\n const_5 = constant_op.constant(5.0)\n\n self.assertDeviceEqual(const_0.device, \"/job:ps\")\n self.assertDeviceEqual(const_1.device, \"/device:GPU:0\")\n self.assertDeviceEqual(const_2.device, \"/device:GPU:1\")\n self.assertDeviceEqual(const_3.device, \"/device:CPU:0\")\n self.assertDeviceEqual(const_4.device, \"/device:CPU:1\")\n self.assertDeviceEqual(const_5.device, \"/replica:0\")\n\n def testExtractSubGraph(self):\n graph_def = graph_pb2.GraphDef()\n n1 = graph_def.node.add()\n n1.name = \"n1\"\n n1.input.extend([\"n5\"])\n n2 = graph_def.node.add()\n n2.name = \"n2\"\n # Take the first output of the n1 node as the input.\n n2.input.extend([\"n1:0\"])\n n3 = graph_def.node.add()\n n3.name = \"n3\"\n # Add a control input (which isn't really needed by the kernel, but\n # rather to enforce execution order between nodes).\n n3.input.extend([\"^n2\"])\n n4 = graph_def.node.add()\n n4.name = \"n4\"\n\n # It is fine to have a loops in the graph as well.\n n5 = graph_def.node.add()\n n5.name = \"n5\"\n n5.input.extend([\"n1\"])\n\n sub_graph = graph_util.extract_sub_graph(graph_def, [\"n3\"])\n self.assertEqual(\"n1\", sub_graph.node[0].name)\n self.assertEqual(\"n2\", sub_graph.node[1].name)\n self.assertEqual(\"n3\", sub_graph.node[2].name)\n self.assertEqual(\"n5\", sub_graph.node[3].name)\n\n def testExtractSubGraphWithInvalidDestNodes(self):\n graph_def = graph_pb2.GraphDef()\n n1 = graph_def.node.add()\n n1.name = \"n1\"\n with self.assertRaisesRegexp(TypeError, \"must be a list\"):\n graph_util.extract_sub_graph(graph_def, \"n1\")\n\n def testConvertVariablesToConstsWithFunctions(self):\n @function.Defun(dtypes.float32)\n def plus_one(x):\n return x + 1.0\n\n with ops.Graph().as_default():\n variable_node = variables.Variable(1.0, name=\"variable_node\")\n _ = variables.Variable(1.0, name=\"unused_variable_node\")\n defun_node = plus_one(variable_node)\n output_node = math_ops_lib.multiply(\n defun_node, 2.0, name=\"output_node\")\n\n with session.Session() as sess:\n init = variables.initialize_variables([variable_node])\n sess.run(init)\n output = sess.run(output_node)\n self.assertNear(4.0, output, 0.00001)\n variable_graph_def = sess.graph.as_graph_def()\n\n # First get the constant_graph_def when variable_names_whitelist is set,\n # note that if variable_names_whitelist is not set an error will be\n # thrown because unused_variable_node is not initialized.\n constant_graph_def = graph_util.convert_variables_to_constants(\n sess,\n variable_graph_def, [\"output_node\"],\n variable_names_whitelist=set([\"variable_node\"]))\n\n self.assertEqual(variable_graph_def.library,\n constant_graph_def.library)\n\n def testConvertVariablesToConsts(self):\n with ops.Graph().as_default():\n variable_node = variables.Variable(1.0, name=\"variable_node\")\n _ = variables.Variable(1.0, name=\"unused_variable_node\")\n output_node = math_ops_lib.multiply(\n variable_node, 2.0, name=\"output_node\")\n with session.Session() as sess:\n init = variables.initialize_variables([variable_node])\n sess.run(init)\n output = sess.run(output_node)\n self.assertNear(2.0, output, 0.00001)\n variable_graph_def = sess.graph.as_graph_def()\n # First get the constant_graph_def when variable_names_whitelist is set,\n # note that if variable_names_whitelist is not set an error will be\n # thrown because unused_variable_node is not initialized.\n constant_graph_def = graph_util.convert_variables_to_constants(\n sess,\n variable_graph_def, [\"output_node\"],\n variable_names_whitelist=set([\"variable_node\"]))\n\n # Then initialize the unused variable, and get another\n # constant_graph_def when variable_names_whitelist is not set.\n sess.run(variables.global_variables_initializer())\n constant_graph_def_without_variable_whitelist = (\n graph_util.convert_variables_to_constants(sess, variable_graph_def,\n [\"output_node\"]))\n\n # The unused variable should be cleared so the two graphs should be\n # equivalent.\n self.assertEqual(\n str(constant_graph_def),\n str(constant_graph_def_without_variable_whitelist))\n\n # Test variable name black list. This should result in the variable not\n # being a const.\n sess.run(variables.global_variables_initializer())\n constant_graph_def_with_blacklist = (\n graph_util.convert_variables_to_constants(\n sess,\n variable_graph_def, [\"output_node\"],\n variable_names_blacklist=set([\"variable_node\"])))\n variable_node = None\n for node in constant_graph_def_with_blacklist.node:\n if node.name == \"variable_node\":\n variable_node = node\n self.assertIsNotNone(variable_node)\n self.assertEqual(variable_node.op, \"VariableV2\")\n\n # Now we make sure the variable is now a constant, and that the graph still\n # produces the expected result.\n with ops.Graph().as_default():\n _ = importer.import_graph_def(constant_graph_def, name=\"\")\n self.assertEqual(4, len(constant_graph_def.node))\n for node in constant_graph_def.node:\n self.assertNotEqual(\"Variable\", node.op)\n self.assertNotEqual(\"VariableV2\", node.op)\n with session.Session() as sess:\n output_node = sess.graph.get_tensor_by_name(\"output_node:0\")\n output = sess.run(output_node)\n self.assertNear(2.0, output, 0.00001)\n\n def create_node_def(self, op, name, inputs):\n new_node = node_def_pb2.NodeDef()\n new_node.op = op\n new_node.name = name\n for input_name in inputs:\n new_node.input.extend([input_name])\n return new_node\n\n def create_constant_node_def(self, name, value, dtype, shape=None):\n node = self.create_node_def(\"Const\", name, [])\n self.set_attr_dtype(node, \"dtype\", dtype)\n self.set_attr_tensor(node, \"value\", value, dtype, shape)\n return node\n\n def set_attr_dtype(self, node, key, value):\n node.attr[key].CopyFrom(\n attr_value_pb2.AttrValue(type=value.as_datatype_enum))\n\n def set_attr_tensor(self, node, key, value, dtype, shape=None):\n node.attr[key].CopyFrom(\n attr_value_pb2.AttrValue(tensor=tensor_util.make_tensor_proto(\n value, dtype=dtype, shape=shape)))\n\n def testRemoveTrainingNodes(self):\n a_constant_name = \"a_constant\"\n b_constant_name = \"b_constant\"\n a_check_name = \"a_check\"\n b_check_name = \"b_check\"\n a_identity_name = \"a_identity\"\n b_identity_name = \"b_identity\"\n add_name = \"add\"\n graph_def = graph_pb2.GraphDef()\n a_constant = self.create_constant_node_def(\n a_constant_name, value=1, dtype=dtypes.float32, shape=[])\n graph_def.node.extend([a_constant])\n a_check_node = self.create_node_def(\"CheckNumerics\", a_check_name,\n [a_constant_name])\n graph_def.node.extend([a_check_node])\n a_identity_node = self.create_node_def(\n \"Identity\", a_identity_name, [a_constant_name, \"^\" + a_check_name])\n graph_def.node.extend([a_identity_node])\n b_constant = self.create_constant_node_def(\n b_constant_name, value=1, dtype=dtypes.float32, shape=[])\n graph_def.node.extend([b_constant])\n b_check_node = self.create_node_def(\"CheckNumerics\", b_check_name,\n [b_constant_name])\n graph_def.node.extend([b_check_node])\n b_identity_node = self.create_node_def(\n \"Identity\", b_identity_name, [b_constant_name, \"^\" + b_check_name])\n graph_def.node.extend([b_identity_node])\n add_node = self.create_node_def(\"Add\", add_name,\n [a_identity_name, b_identity_name])\n self.set_attr_dtype(add_node, \"T\", dtypes.float32)\n graph_def.node.extend([add_node])\n\n expected_output = graph_pb2.GraphDef()\n a_constant = self.create_constant_node_def(\n a_constant_name, value=1, dtype=dtypes.float32, shape=[])\n expected_output.node.extend([a_constant])\n b_constant = self.create_constant_node_def(\n b_constant_name, value=1, dtype=dtypes.float32, shape=[])\n expected_output.node.extend([b_constant])\n add_node = self.create_node_def(\"Add\", add_name,\n [a_constant_name, b_constant_name])\n self.set_attr_dtype(add_node, \"T\", dtypes.float32)\n expected_output.node.extend([add_node])\n\n output = graph_util.remove_training_nodes(graph_def)\n self.assertProtoEquals(expected_output, output)\n\n def testRemoveIdentityChains(self):\n \"\"\"Check that chains of Identity nodes are correctly pruned.\n\n Create a chain of four nodes, A, B, C, and D where A inputs B, B inputs C,\n and C inputs D. Nodes B and C are \"Identity\" and should be pruned, resulting\n in the nodes A and D, where A inputs D.\n \"\"\"\n graph_def = graph_pb2.GraphDef()\n graph_def.node.extend([\n self.create_node_def(\"Aop\", \"A\", [\"B\"]), self.create_node_def(\n \"Identity\", \"B\", [\"C\"]), self.create_node_def(\n \"Identity\", \"C\", [\"D\"]), self.create_node_def(\"Dop\", \"D\", [])\n ])\n\n expected_graph_def = graph_pb2.GraphDef()\n expected_graph_def.node.extend([\n self.create_node_def(\"Aop\", \"A\", [\"D\"]), self.create_node_def(\n \"Dop\", \"D\", [])\n ])\n\n self.assertProtoEquals(expected_graph_def,\n graph_util.remove_training_nodes(graph_def))\n\n\nif __name__ == \"__main__\":\n test.main()\n"
] | [
[
"tensorflow.python.framework.graph_util.remove_training_nodes",
"tensorflow.python.ops.variables.Variable",
"tensorflow.python.framework.ops.device",
"tensorflow.python.ops.gen_state_ops.variable",
"tensorflow.python.framework.function.Defun",
"tensorflow.python.platform.test.main",
"tensorflow.python.ops.variables.initialize_variables",
"tensorflow.python.framework.importer.import_graph_def",
"tensorflow.python.framework.graph_util.extract_sub_graph",
"tensorflow.python.client.session.Session",
"tensorflow.python.framework.tensor_util.make_tensor_proto",
"tensorflow.core.framework.attr_value_pb2.AttrValue",
"tensorflow.python.framework.ops.Graph",
"tensorflow.core.framework.node_def_pb2.NodeDef",
"tensorflow.python.framework.graph_util.convert_variables_to_constants",
"tensorflow.python.ops.math_ops.multiply",
"tensorflow.python.ops.variables.global_variables_initializer",
"tensorflow.core.framework.graph_pb2.GraphDef",
"tensorflow.python.framework.constant_op.constant"
]
] |
przemekblasiak/StrayVisualizer | [
"df5f39c750e8eec62b130dc9c8a91bdbcff1d952"
] | [
"stray_visualize.py"
] | [
"import os\nimport open3d as o3d\nimport numpy as np\nfrom scipy.spatial.transform import Rotation\nfrom argparse import ArgumentParser\nfrom PIL import Image\nimport skvideo.io\n\ndescription = \"\"\"\nThis script visualizes datasets collected using the Stray Scanner app.\n\"\"\"\n\nusage = \"\"\"\nBasic usage: python stray_visualize.py <path-to-dataset-folder>\n\"\"\"\n\nDEPTH_WIDTH = 256\nDEPTH_HEIGHT = 192\n\ndef read_args():\n parser = ArgumentParser(description=description, usage=usage)\n parser.add_argument('path', type=str, help=\"Path to StrayScanner dataset to process.\")\n parser.add_argument('--trajectory', '-t', action='store_true', help=\"Visualize the trajectory of the camera as a line.\")\n parser.add_argument('--frames', '-f', action='store_true', help=\"Visualize camera coordinate frames from the odometry file.\")\n parser.add_argument('--point-clouds', '-p', action='store_true', help=\"Show concatenated point clouds.\")\n parser.add_argument('--integrate', '-i', action='store_true', help=\"Integrate point clouds using the Open3D RGB-D integration pipeline, and visualize it.\")\n parser.add_argument('--mesh-filename', type=str, help='Mesh generated from point cloud integration will be stored in this file. open3d.io.write_triangle_mesh will be used.', default=None)\n parser.add_argument('--every', type=int, default=60, help=\"Show only every nth point cloud and coordinate frames. Only used for point cloud and odometry visualization.\")\n parser.add_argument('--voxel-size', type=float, default=0.015, help=\"Voxel size in meters to use in RGB-D integration.\")\n parser.add_argument('--confidence', '-c', type=int, default=1,\n help=\"Keep only depth estimates with confidence equal or higher to the given value. There are three different levels: 0, 1 and 2. Higher is more confident.\")\n return parser.parse_args()\n\ndef _resize_camera_matrix(camera_matrix, scale_x, scale_y):\n fx = camera_matrix[0, 0]\n fy = camera_matrix[1, 1]\n cx = camera_matrix[0, 2]\n cy = camera_matrix[1, 2]\n return np.array([[fx * scale_x, 0.0, cx * scale_x],\n [0., fy * scale_y, cy * scale_y],\n [0., 0., 1.0]])\n\ndef read_data(flags):\n intrinsics = np.loadtxt(os.path.join(flags.path, 'camera_matrix.csv'), delimiter=',')\n odometry = np.loadtxt(os.path.join(flags.path, 'odometry.csv'), delimiter=',', skiprows=1)\n poses = []\n\n for line in odometry:\n # x, y, z, qx, qy, qz, qw\n position = line[2:5]\n quaternion = line[5:]\n T_WC = np.eye(4)\n T_WC[:3, :3] = Rotation.from_quat(quaternion).as_matrix()\n T_WC[:3, 3] = position\n poses.append(T_WC)\n return { 'poses': poses, 'intrinsics': intrinsics }\n\ndef load_depth(path, confidence=None, filter_level=0):\n depth_mm = np.load(path)\n depth_m = depth_mm.astype(np.float32) / 1000.0\n if confidence is not None:\n depth_m[confidence < filter_level] = 0.0\n return o3d.geometry.Image(depth_m)\n\ndef load_confidence(path):\n return np.array(Image.open(path))\n\ndef get_intrinsics(intrinsics):\n \"\"\"\n Scales the intrinsics matrix to be of the appropriate scale for the depth maps.\n \"\"\"\n intrinsics_scaled = _resize_camera_matrix(intrinsics, DEPTH_WIDTH / 1920, DEPTH_HEIGHT / 1440)\n return o3d.camera.PinholeCameraIntrinsic(width=DEPTH_WIDTH, height=DEPTH_HEIGHT, fx=intrinsics_scaled[0, 0],\n fy=intrinsics_scaled[1, 1], cx=intrinsics_scaled[0, 2], cy=intrinsics_scaled[1, 2])\n\ndef trajectory(flags, data):\n \"\"\"\n Returns a set of lines connecting each camera poses world frame position.\n returns: [open3d.geometry.LineSet]\n \"\"\"\n line_sets = []\n previous_pose = None\n for i, T_WC in enumerate(data['poses']):\n if previous_pose is not None:\n points = o3d.utility.Vector3dVector([previous_pose[:3, 3], T_WC[:3, 3]])\n lines = o3d.utility.Vector2iVector([[0, 1]])\n line = o3d.geometry.LineSet(points=points, lines=lines)\n line_sets.append(line)\n previous_pose = T_WC\n return line_sets\n\ndef show_frames(flags, data):\n \"\"\"\n Returns a list of meshes of coordinate axes that have been transformed to represent the camera matrix\n at each --every:th frame.\n\n flags: Command line arguments\n data: dict with keys ['poses', 'intrinsics']\n returns: [open3d.geometry.TriangleMesh]\n \"\"\"\n frames = [o3d.geometry.TriangleMesh.create_coordinate_frame().scale(0.25, np.zeros(3))]\n for i, T_WC in enumerate(data['poses']):\n if not i % flags.every == 0:\n continue\n print(f\"Frame {i}\", end=\"\\r\")\n mesh = o3d.geometry.TriangleMesh.create_coordinate_frame().scale(0.1, np.zeros(3))\n frames.append(mesh.transform(T_WC))\n return frames\n\ndef point_clouds(flags, data):\n \"\"\"\n Converts depth maps to point clouds and merges them all into one global point cloud.\n flags: command line arguments\n data: dict with keys ['intrinsics', 'poses']\n returns: [open3d.geometry.PointCloud]\n \"\"\"\n pcs = []\n intrinsics = get_intrinsics(data['intrinsics'])\n pc = o3d.geometry.PointCloud()\n meshes = []\n for i, T_WC in enumerate(data['poses']):\n if i % flags.every != 0:\n continue\n print(f\"Point cloud {i}\", end=\"\\r\")\n T_CW = np.linalg.inv(T_WC)\n confidence = load_confidence(os.path.join(flags.path, 'confidence', f'{i:06}.png'))\n depth = load_depth(os.path.join(flags.path, 'depth', f'{i:06}.npy'), confidence, filter_level=flags.confidence)\n pc += o3d.geometry.PointCloud.create_from_depth_image(depth, intrinsics, extrinsic=T_CW, depth_scale=1.0)\n return [pc]\n\ndef integrate(flags, data):\n \"\"\"\n Integrates collected RGB-D maps using the Open3D integration pipeline.\n\n flags: command line arguments\n data: dict with keys ['intrinsics', 'poses']\n Returns: open3d.geometry.TriangleMesh\n \"\"\"\n volume = o3d.pipelines.integration.ScalableTSDFVolume(\n voxel_length=flags.voxel_size,\n sdf_trunc=0.05,\n color_type=o3d.pipelines.integration.TSDFVolumeColorType.RGB8)\n\n intrinsics = get_intrinsics(data['intrinsics'])\n\n rgb_path = os.path.join(flags.path, 'rgb.mp4')\n video = skvideo.io.vreader(rgb_path)\n for i, (T_WC, rgb) in enumerate(zip(data['poses'], video)):\n print(f\"Integrating frame {i:06}\", end='\\r')\n depth_path = os.path.join(flags.path, 'depth', f'{i:06}.npy')\n depth = load_depth(depth_path)\n rgb = Image.fromarray(rgb)\n rgb = rgb.resize((DEPTH_WIDTH, DEPTH_HEIGHT))\n rgb = np.array(rgb)\n rgbd = o3d.geometry.RGBDImage.create_from_color_and_depth(\n o3d.geometry.Image(rgb), depth,\n depth_scale=1.0, depth_trunc=4.0, convert_rgb_to_intensity=False)\n\n volume.integrate(rgbd, intrinsics, np.linalg.inv(T_WC))\n mesh = volume.extract_triangle_mesh()\n mesh.compute_vertex_normals()\n return mesh\n\n\ndef validate(flags):\n if not os.path.exists(os.path.join(flags.path, 'rgb.mp4')):\n absolute_path = os.path.abspath(flags.path)\n print(f\"The directory {absolute_path} does not appear to be a directory created by the Stray Scanner app.\")\n return False\n return True\n\ndef main():\n flags = read_args()\n\n if not validate(flags):\n return\n\n if not flags.frames and not flags.point_clouds and not flags.integrate:\n flags.frames = True\n flags.point_clouds = True\n flags.trajectory = True\n\n data = read_data(flags)\n geometries = []\n if flags.trajectory:\n geometries += trajectory(flags, data)\n if flags.frames:\n geometries += show_frames(flags, data)\n if flags.point_clouds:\n geometries += point_clouds(flags, data)\n if flags.integrate:\n mesh = integrate(flags, data)\n if flags.mesh_filename is not None:\n o3d.io.write_triangle_mesh(flags.mesh_filename, mesh)\n geometries += [mesh]\n o3d.visualization.draw_geometries(geometries)\n\nif __name__ == \"__main__\":\n main()\n\n"
] | [
[
"scipy.spatial.transform.Rotation.from_quat",
"numpy.linalg.inv",
"numpy.eye",
"numpy.load",
"numpy.array",
"numpy.zeros"
]
] |
Louis-lew/ROS-Turtlebot3-Burger | [
"2d34ab84a2b5f2c2455d446326756fe9c8f94920"
] | [
"ros_autonomous_slam/nodes/autonomous_move.py"
] | [
"#!/usr/bin/python3\n\nfrom rrt import find_path_RRT\nimport numpy as np\nfrom scipy.misc import imread\nimport math\nimport rospy\nimport geometry_msgs.msg\nfrom geometry_msgs.msg import Point,Pose\nfrom nav_msgs.msg import Odometry, OccupancyGrid, MapMetaData, GridCells\nfrom sensor_msgs.msg import LaserScan\nfrom tf.transformations import euler_from_quaternion\nimport actionlib\nfrom visualization_msgs.msg import Marker\nfrom move_base_msgs.msg import MoveBaseAction, MoveBaseGoal\nimport cv2\nfrom math import cos,sin\nimport actionlib\nfrom move_base_msgs.msg import MoveBaseAction, MoveBaseGoal\n\nglobal final_goal_location, goal_reached, robot_location,robot_rotation, current_map\nfinal_goal_location = [326.0, 279.0]\ngoal_reached = False\nrobot_rotation = [0,0,0]\nrobot_location = [-2,0.5,0]\ncurrent_map = np.zeros((384,384))\n\n\ndef movebase_client(x,y):\n client = actionlib.SimpleActionClient('move_base',MoveBaseAction)\n client.wait_for_server()\n\n goal = MoveBaseGoal()\n goal.target_pose.header.frame_id = \"map\"\n goal.target_pose.header.stamp = rospy.Time.now()\n goal.target_pose.pose.position.x = x\n goal.target_pose.pose.position.y = y\n goal.target_pose.pose.orientation.w = 1\n\n client.send_goal(goal)\n wait = client.wait_for_result()\n if not wait:\n rospy.logerr(\"Action server not available!\")\n rospy.signal_shutdown(\"Action server not available!\")\n else:\n return client.get_result()\n\n# if __name__ == '__main__':\n# try:\n# rospy.init_node('movebase_client_py')\n# result = movebase_client(-2,3)\n# if result:\n# rospy.loginfo(\"Goal execution done!\")\n# except rospy.ROSInterruptException:\n# rospy.loginfo(\"Navigation test finished.\")\n\ndef convert_path(path,trans,t):\n '''\n Translates and Rotates the given set of coordinates\n '''\n npath = []\n for x in path:\n mat = [x[0],x[1]]\n mat = rot2d(mat,t)\n npath.append((mat[0]+trans[0],mat[1]+trans[1]))\n return npath\n\ndef convert_point(x,trans,t):\n '''\n Translates and Rotates the given set of coordinate\n '''\n mat = [x[0],x[1]]\n mat = rot2d(mat,t)\n return (mat[0]+trans[0],mat[1]+trans[1])\n\ndef Distance_compute(pos1,pos2,Type = 'd'):\n '''\n Distance Compute between two positions\n '''\n x1 = pos1[0]\n y1 = pos1[1]\n x2 = pos2[0]\n y2 = pos2[1]\n d = ((x1-x2)**2) + ((y1-y2)**2)\n if Type == 'd':\n return math.sqrt(d)\n if Type == 'eu':\n return d\n if Type == 'manhattan':\n return abs(x1-x2)+abs(y1-y2)\n\ndef rot2d(v,t):\n '''\n 2D Rotation points\n '''\n x,y = v[0],v[1]\n xr = x*cos(t)-y*sin(t)\n yr = x*sin(t)+y*cos(t)\n return [xr,yr]\n\ndef go_to_goal(goal):\n '''\n Function to command robot in ROS stage to go to given goal wrt /odom frame\n '''\n global robot_location,robot_rotation\n d = Distance_compute(robot_location,goal)\n theta = robot_rotation[2]\n kl = 1\n ka = 4\n vx = 0\n va = 0\n heading = math.atan2(goal[1]-robot_location[1],goal[0]-robot_location[0])\n err_theta = heading - theta\n if(d>0.01):\n vx = kl*abs(d)\n vx = 1\n if(abs(err_theta)>0.01):\n va = ka*(err_theta)\n\n vel_1 = rospy.Publisher('/cmd_vel', geometry_msgs.msg.Twist,queue_size=10) # Publish Command to robot_1\n cmd = geometry_msgs.msg.Twist()\n cmd.linear.x = vx\n cmd.angular.z = va\n vel_1.publish(cmd)\n\ndef Follow_path(path):\n '''\n Follows a given set of path\n - Reaches all the points in a list in consecutive order\n '''\n global final_goal_location, goal_reached\n cpath = path\n goal_point = cpath[-1]\n print('Following Path -->',cpath)\n for loc in cpath:\n while(Distance_compute(robot_location,loc)>0.1):\n # goal_location_marker(final_goal_location)\n # points_publisher(cpath)\n \n go_to_goal([loc[0]/10,loc[1]/10])\n if(loc==goal_point):\n goal_reached = True\n\ndef callback_odom(msg):\n '''\n Obtains Odometer readings and assigns to global Variables\n '''\n global robot_location, robot_rotation, robot_orientation\n location = [msg.pose.pose.position.x, msg.pose.pose.position.y]\n robot_location = location\n orientation = [msg.pose.pose.orientation.x, msg.pose.pose.orientation.y, msg.pose.pose.orientation.z, msg.pose.pose.orientation.w]\n (roll, pitch, yaw) = euler_from_quaternion(orientation)\n rot = [roll, pitch, yaw]\n robot_rotation = rot\n robot_orientation = orientation\n\ndef callback_map(msg):\n global current_map\n data = np.array(msg.data)\n map_width = msg.info.width\n map_height = msg.info.height\n current_map = np.reshape(data,(map_height,map_width))\n\ndef map_img(arr):\n disp_map = np.ones((384,384))*255\n for i in range(arr.shape[0]):\n for j in range(arr.shape[1]):\n if arr[i][j]==-1:\n disp_map[i][j] = 100\n if arr[i][j] == 100:\n disp_map[i][j] = 0\n im = np.array(disp_map, dtype = np.uint8)\n return im[::-1]\n\ndef points_publisher(points_list):\n marker_pub = rospy.Publisher('path_points', Marker,queue_size=1) # Publish Robot Position to RVIZ\n marker_data = Marker()\n marker_data.type = marker_data.POINTS\n marker_data.action = marker_data.ADD\n marker_data.header.frame_id = '/map'\n\n marker_data.scale.x = 0.1 # width\n marker_data.scale.y = 0.1 # Height\n\n marker_data.color.a = 1\n marker_data.color.r = 1\n marker_data.color.g = 0\n marker_data.color.b = 0\n\n for p in points_list:\n marker_data.points.append(Point(p[0],p[1],0))\n marker_pub.publish(marker_data)\n\nif __name__ == '__main__':\n rospy.init_node('RRT_Explorer')\n rate = rospy.Rate(10.0)\n # Subscribe to /odom\n sub_odom = rospy.Subscriber('/odom', Odometry, callback_odom) # Receive Odom readings\n sub_map = rospy.Subscriber('/map',OccupancyGrid, callback_map) # Receive Map\n img = imread('/home/fazildgr8/catkin_ws/src/ros_autonomous_slam/media/my_map.png')\n \n flag = True\n while not rospy.is_shutdown():\n start, goal = (convert_point(robot_location,[192,192],0), convert_point([2,0.5],[192,192],0))\n print(start,goal)\n if flag:\n path,graph = find_path_RRT(convert_point(robot_location,[192,192],0),convert_point([-1,0.5],[192,192],0),cv2.cvtColor(map_img(current_map), cv2.COLOR_GRAY2BGR)[::-1])\n print(path)\n print(graph)\n flag = False\n print('Map Shape',current_map.shape)\n # points_publisher(convert_path(path,[-192,-192],0))\n # if flag:\n # result = movebase_client(-2,0.5)\n # if result:\n # flag = False\n # print('reached')\n cv2.imshow('Constructed Map',map_img(current_map))\n # np.savetxt('my_map',map_img(current_map))\n if cv2.waitKey(1) & 0xFF == ord('q'):\n break\n cv2.destroyAllWindows()\n\n\n"
] | [
[
"numpy.reshape",
"numpy.ones",
"scipy.misc.imread",
"numpy.array",
"numpy.zeros"
]
] |
tomershraga/Udacity_Advanced_Lane_Lines | [
"826436fb695402e3ff1edda5568c3a5be5c91c73"
] | [
"perspective_transform.py"
] | [
"import cv2\nimport numpy as np\nimport matplotlib.pyplot as plt\n\ndef create_interest_mask(combined_binary_image):\n mask = np.zeros_like(combined_binary_image)\n region_of_interest = np.array([[0, combined_binary_image.shape[0] - 1], [combined_binary_image.shape[1] / 2, int(0.5 * combined_binary_image.shape[0])],\n [combined_binary_image.shape[1] - 1, combined_binary_image.shape[0] - 1]], dtype=np.int32)\n cv2.fillPoly(mask, [region_of_interest], 1)\n ret_image = cv2.bitwise_and(combined_binary_image, mask)\n return ret_image\n\ndef transform_perspective(threshold_image):\n # Define source points\n src = np.array([[200, 720], [1150, 720], [750, 480], [550, 480]], np.float32)\n # Define destination points\n dst = np.array([[300, 720], [900, 720], [900, 0], [300, 0]], np.float32)\n # Get the transformation matrix by performing perspective transform\n M = cv2.getPerspectiveTransform(src, dst)\n # Get the inverse transformation matrix\n Minv = cv2.getPerspectiveTransform(dst, src)\n # Get the image size\n image_size = (threshold_image.shape[1], threshold_image.shape[0])\n # Warp the image\n warped_image = cv2.warpPerspective(threshold_image, M, image_size)\n return warped_image, M, Minv\n\ndef show_warped_image(combined_binary_image, warped_image):\n # Plot the warped image\n f, (ax1, ax2) = plt.subplots(1, 2, figsize=(24, 9))\n ax1.imshow(combined_binary_image, cmap='gray')\n ax1.set_title('Combined binary image', fontsize=30)\n ax2.imshow(warped_image, cmap='gray')\n ax2.set_title('Warped Image', fontsize=30)\n plt.show()\n #cv2.imwrite('output_images/warped_image.png', warped_image)\n\ndef histogram(img):\n bottom_half = img[img.shape[0] // 2:, :]\n histogram = np.sum(bottom_half, axis=0)\n plt.plot(histogram)\n plt.show()\n"
] | [
[
"matplotlib.pyplot.subplots",
"matplotlib.pyplot.plot",
"numpy.zeros_like",
"numpy.array",
"numpy.sum",
"matplotlib.pyplot.show"
]
] |
manal44/profit | [
"a05a2eb0a5a14c36edc46cadfccce3f43fcc1a4e"
] | [
"profit/run/run.py"
] | [
"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Dec 21 09:27:19 2018\n\n@author: calbert\n\"\"\"\n\nimport os\nimport sys\nimport subprocess\nimport multiprocessing as mp\n\ntry:\n from profit import config, read_input\nexcept:\n pass\n\ntry:\n from tqdm import tqdm\n use_tqdm=True\nexcept:\n use_tqdm=False\n\nclass PythonFunction:\n def __init__(self, function):\n self.function = function\n\n def start(self):\n from numpy import array, savetxt\n nrun = config.eval_points.shape[1]\n\n # if present, use progress bar\n if use_tqdm:\n kruns = tqdm(range(nrun))\n else:\n kruns = range(nrun)\n\n cwd = os.getcwd()\n\n try:\n os.chdir(config.base_dir)\n output = [] # TODO: make this more efficient with preallocation based on shape\n for krun in kruns:\n res = self.function(config.eval_points[:, krun])\n output.append([krun, res])\n savetxt('output.txt', array(output))\n finally:\n os.chdir(cwd)\n\n\ndef spawn(args):\n cmd = args[0]\n fulldir = args[1]\n print(fulldir)\n print(cmd)\n return cmd, subprocess.call(cmd, cwd=fulldir,\n stdout=open(os.path.join(fulldir,'stdout.txt'),'w'),\n stderr=open(os.path.join(fulldir,'stderr.txt'),'w'))\n\nclass LocalCommand:\n def __init__(self, command, ntask=1, run_dir='run', base_dir='.'):\n # self.command = os.path.abspath(os.path.join(base_dir, command))\n # TODO: support relative paths consistently\n self.command = command\n self.ntask = ntask\n self.run_dir = run_dir\n\n def start(self):\n p = mp.Pool(self.ntask)\n subdirs = sorted(os.listdir(self.run_dir))\n\n args = []\n for subdir in subdirs:\n fulldir = os.path.join(self.run_dir, subdir)\n if os.path.isdir(fulldir):\n cmd = self.command.split()\n if cmd[0].endswith('.py'):\n cmd.insert(0, sys.executable)\n args.append((cmd, fulldir))\n p.map(spawn, args)\n\nclass Slurm:\n def __init__(self, config):\n self.eval_points = read_input(config['run_dir'])\n if config['runner_backend'] == 'slurm':\n from backend.run.slurm import slurm_backend\n self.backend = slurm_backend()\n if 'slurm' in config:\n self.backend.write_slurm_scripts(num_experiments=self.eval_points.shape[1], slurm_config=config['slurm'],jobcommand=config['run'])\n else:\n print('''cannot write slurm scripts, please provide slurm details:\n runner_backend: slurm\n slurm:\n tasks_per_node: 36\n partition: compute\n time: 00:10:00\n account: xy123''')\n else:\n self.backend = None\n def start(self):\n if self.backend is not None:\n self.backend.call_run()\n\nclass Runner:\n def __init__(self, config):\n if config['run']:\n print(config['run'])\n return(LocalCommand(config['run']))\n"
] | [
[
"numpy.array"
]
] |
ryanbahneman/kaggle | [
"8a3d329f58aa1f241e655098c5fdfe78c4460770"
] | [
"digits/code/learn_digits.py"
] | [
"#!/usr/bin/env python\n\nimport pandas as pd\nimport numpy as np\nimport IPython as ipy\nfrom PIL import Image\n\nnp.set_printoptions(threshold='nan')\n\ntraining_data_path = \"../data/train.csv\"\n\ntrain_df = pd.read_csv(training_data_path, header=0)\n\nimages_data = train_df.drop([\"label\"], axis=1).values\n\n\n# Plot an image\nfor i in xrange(10):\n a = images_data[i].reshape((28,28)).astype(np.uint8)\n img = Image.fromarray(a, mode=\"L\")\n img.show()\n\nipy.embed()\n\n\n"
] | [
[
"numpy.set_printoptions",
"pandas.read_csv"
]
] |
JiangengDong/CoMPNetX | [
"7ad851db4c2275b099bdab0c151a23f9b753c839"
] | [
"python/test.py"
] | [
"#!/usr/bin/env python2\n\n\"\"\"\nCopyright (c) 2020, University of California, San Diego\nAll rights reserved.\n\nAuthor: Jiangeng Dong <[email protected]>\n Ahmed Qureshi <[email protected]>\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are\nmet:\n\n Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n\n Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in the\n documentation and/or other materials provided with the distribution.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\nLIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\nA PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\nHOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\nSPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\nLIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\nDATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\nTHEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\"\"\"\n\n# This file is used to test our algorithm on the following environments.\n# 1. Bartender\n# 1. Kitchen\n\nfrom __future__ import absolute_import, division, print_function\n\nimport csv\nimport os\nimport pickle\nimport sys\nimport time\nfrom argparse import ArgumentParser\nfrom multiprocessing import Process\n\nimport h5py\nimport numpy as np\nimport openravepy as orpy\nimport rospkg\nimport yaml\nfrom tqdm import tqdm\n\nfrom OMPLInterface import (OMPLInterface, PlannerParameter, RPY2Transform, TSRChain)\n\n\ndef loadTestData(env):\n assert env in [\"bartender\", \"kitchen\"]\n\n with open(\"data/dataset/description.yaml\", \"r\") as f:\n description = yaml.load(f, Loader=yaml.CLoader)\n groups = description[env][\"test\"]\n f_setup = h5py.File(\"data/dataset/{}_setup.hdf5\".format(env), \"r\")\n\n result = {}\n for group in tqdm(groups, desc=\"Load dataset from disk\"):\n result[group] = {}\n result[group][\"obj_order\"] = np.array(f_setup[group][\"obj_order\"])\n for obj_name in result[group][\"obj_order\"]:\n obj_data = f_setup[group][obj_name]\n if obj_name == \"door\":\n result[group][obj_name] = {\n key: np.array(obj_data[key]) for key in (\"initial_config\",\n \"start_config\", \"goal_config\",\n \"start_trans\", \"goal_trans\",\n \"tsr_base\", \"tsr_bound0\", \"tsr_offset0\", \"tsr_bound1\", \"tsr_offset1\")\n }\n else:\n result[group][obj_name] = {\n key: np.array(obj_data[key]) for key in (\"initial_config\",\n \"start_config\", \"goal_config\",\n \"start_trans\", \"goal_trans\",\n \"tsr_bound\", \"tsr_offset\")\n }\n for obj_name in (\"tray\", \"recyclingbin\"):\n result[group][obj_name] = {\"start_trans\": np.array(f_setup[group][obj_name][\"start_trans\"])}\n return result\n\n\ndef setOpenRAVE(visible=False, coll_checker=\"ode\"):\n orEnv = orpy.Environment()\n if visible:\n orEnv.SetViewer('qtcoin')\n viewer = orEnv.GetViewer()\n viewer.SetCamera(np.array([[0.83316667, 0.27865777, -0.4776852, 2.19543743],\n [0.55220156, -0.46622736, 0.69116242, -2.45863342],\n [-0.03011214, -0.839632, -0.54232035, 2.58929443],\n [0., 0., 0., 1.]]))\n orEnv.Reset()\n orEnv.SetDebugLevel(orpy.DebugLevel.Info)\n colchecker = orpy.RaveCreateCollisionChecker(orEnv, coll_checker)\n orEnv.SetCollisionChecker(colchecker)\n return orEnv\n\n\ndef loadTable(orEnv):\n table1 = orpy.RaveCreateKinBody(orEnv, '')\n table1.SetName('table1')\n table1.InitFromBoxes(np.array([[1.0, 0.4509, 0.5256, 0.2794, 0.9017, 0.5256]]), True)\n orEnv.Add(table1, True)\n\n table2 = orpy.RaveCreateKinBody(orEnv, '')\n table2.SetName('table2')\n table2.InitFromBoxes(np.array([[0.3777, -0.7303, 0.5256, 0.9017, 0.2794, 0.5256]]), True)\n orEnv.Add(table2, True)\n\n\ndef loadCabinet(orEnv):\n cabinet = orEnv.ReadRobotURI(os.path.abspath(\"./data/openrave_model/cabinets.robot.xml\"))\n orEnv.Add(cabinet, True)\n cab_rot = [[0, 1, 0], [-1, 0, 0], [0, 0, 1]]\n T0_cab = RPY2Transform(0, 0, -np.pi / 2, 0.85, 1.28, 0)\n cabinet.SetTransform(np.array(T0_cab[0:3][:, 0:4]))\n cabinet.SetActiveDOFs([3])\n return cabinet\n\n\ndef setCabinet(cabinet, joint_value):\n cabinet.SetActiveDOFs([3])\n cabinet.SetActiveDOFValues([joint_value])\n\n\ndef loadObjects(orEnv):\n model_folder = os.path.abspath(\"./data/openrave_model\")\n\n def loadFromFolder(name):\n return orEnv.ReadKinBodyXMLFile(os.path.join(model_folder, name))\n\n obj_dict = {\n \"tray\": loadFromFolder(\"tray.kinbody.xml\"),\n \"recyclingbin\": loadFromFolder('recyclingbin.kinbody.xml'),\n \"juice\": loadFromFolder('juice_bottle.kinbody.xml'),\n \"fuze_bottle\": loadFromFolder('fuze_bottle.kinbody.xml'),\n \"coke_can\": loadFromFolder('coke_can.kinbody.xml'),\n \"mugblack\": loadFromFolder('mugblack.kinbody.xml'),\n \"plasticmug\": loadFromFolder('plasticmug.kinbody.xml'),\n \"pitcher\": loadFromFolder('pitcher.kinbody.xml'),\n \"teakettle\": loadFromFolder('teakettle.kinbody.xml'),\n \"mugred\": loadFromFolder('mugred.kinbody.xml')\n }\n\n return obj_dict\n\n\ndef loadBaxter(orEnv):\n baxter_path = rospkg.RosPack().get_path(\"baxter_description\")\n urdf_path = os.path.join(baxter_path, \"urdf\", \"baxter_sym.urdf\")\n srdf_path = os.path.join(baxter_path, \"urdf\", \"baxter_new.srdf\")\n module = orpy.RaveCreateModule(orEnv, 'urdf')\n name = module.SendCommand('LoadURI {} {}'.format(urdf_path, srdf_path))\n robot = orEnv.GetRobot(name)\n\n T0_baxter = RPY2Transform(0, 0, 0, 0.20, 0.15, 0.9242)\n robot.SetTransform(np.array(T0_baxter[0:3][:, 0:4]))\n\n # set initial configuration\n arm0dofs = [2, 3, 4, 5, 6, 7, 8]\n arm1dofs = [10, 11, 12, 13, 14, 15, 16]\n arm0initvals = [-0.386, 1.321, -0.06, 0.916, -0.349, -0.734, -1.84]\n arm1initvals = [0.216, 1.325, 0.173, 0.581, 0.490, -0.3883, 1.950]\n\n robot.SetActiveDOFs(arm0dofs + arm1dofs)\n robot.SetActiveDOFValues(arm0initvals + arm1initvals)\n robot.SetActiveManipulator(1)\n\n # open hands\n handdof = np.ones([2])\n robot.SetActiveDOFs([1, 9])\n robot.SetActiveDOFValues(handdof)\n return robot\n\n\ndef resetBaxter(robot):\n arm1dofs = [10, 11, 12, 13, 14, 15, 16]\n arm1initvals = [0.216, 1.325, 0.173, 0.581, 0.490, -0.3883, 1.950]\n robot.SetActiveDOFs(arm1dofs)\n robot.SetActiveDOFValues(arm1initvals)\n robot.WaitForController(0)\n\n\ndef initScene(orEnv, robot, cabinet, obj_dict, setup_dict):\n resetBaxter(robot)\n if \"door\" in setup_dict.keys():\n setCabinet(cabinet, setup_dict[\"door\"][\"start_trans\"])\n for obj_name in (\"recyclingbin\", \"tray\",\n \"juice\", \"fuze_bottle\", \"coke_can\",\n \"plasticmug\", \"teakettle\",\n \"mugred\", \"mugblack\", \"pitcher\"):\n if obj_name not in setup_dict.keys():\n continue\n obj = obj_dict[obj_name]\n obj_transform = setup_dict[obj_name][\"start_trans\"]\n orEnv.Add(obj)\n obj.SetTransform(np.array(obj_transform[0:3][:, 0:4]))\n time.sleep(0.1)\n\n\ndef cleanupObject(orEnv, obj_name, obj, setup_dict):\n if obj_name == \"door\":\n setCabinet(obj, setup_dict[\"goal_trans\"])\n elif obj_name in (\"juice\", \"fuze_bottle\", \"coke_can\"):\n orEnv.Remove(obj)\n elif obj_name in (\"mugblack\", \"mugred\", \"plasticmug\", \"pitcher\", \"teakettle\"):\n goal_transform = setup_dict[\"goal_trans\"]\n obj.SetTransform(np.array(goal_transform[0:3][:, 0:4]))\n else:\n raise NotImplementedError\n time.sleep(0.1)\n\n\ndef test_per_scene(scene_name, scene_setup, param, args):\n # preparation\n orEnv = setOpenRAVE(args.visible, \"ode\")\n loadTable(orEnv)\n cabinet = None if args.env == \"bartender\" else loadCabinet(orEnv)\n obj_dict = loadObjects(orEnv)\n robot = loadBaxter(orEnv)\n planner = OMPLInterface(orEnv, robot, loglevel=args.log_level)\n\n result_dict = {}\n # initialize scene. Put all the objects to their start position.\n print(\"\\n========== scene name: %s ==========\" % scene_name)\n initScene(orEnv, robot, cabinet, obj_dict, scene_setup)\n result_dict[scene_name] = {}\n\n obj_names = scene_setup[\"obj_order\"]\n print(\"Object order: %s\" % str(obj_names))\n for obj_name in obj_names:\n print(\"Planning for %s ...\" % obj_name)\n obj_setup = scene_setup[obj_name]\n obj = obj_dict[obj_name] if obj_name != \"door\" else cabinet\n\n # unpack values\n start_config = obj_setup[\"start_config\"]\n goal_config = obj_setup[\"goal_config\"]\n start_trans = obj_setup[\"start_trans\"]\n goal_trans = obj_setup[\"goal_trans\"]\n # go to start position\n robot.SetActiveDOFValues(start_config)\n if obj_name != \"door\":\n robot.Grab(obj)\n robot.WaitForController(0)\n # show the start and goal\n if args.visible:\n robot.SetActiveDOFValues(start_config)\n robot.WaitForController(0)\n if obj_name == \"door\":\n setCabinet(cabinet, start_trans)\n time.sleep(2)\n robot.SetActiveDOFValues(goal_config)\n robot.WaitForController(0)\n if obj_name == \"door\":\n setCabinet(cabinet, goal_trans)\n time.sleep(2)\n robot.SetActiveDOFValues(start_config)\n robot.WaitForController(0)\n if obj_name == \"door\":\n setCabinet(cabinet, start_trans)\n time.sleep(0.1)\n # TSR parameters\n param.clearTSRChains()\n if obj_name != \"door\":\n T0_w = obj_setup[\"goal_trans\"]\n Tw_e = obj_setup[\"tsr_offset\"]\n Bw = obj_setup[\"tsr_bound\"]\n param.addTSRChain(TSRChain().addTSR(T0_w, Tw_e, Bw))\n else:\n T0_w = obj_setup[\"tsr_base\"]\n Tw_e_0 = obj_setup[\"tsr_offset0\"]\n Bw_0 = obj_setup[\"tsr_bound0\"]\n Tw_e_1 = obj_setup[\"tsr_offset1\"]\n Bw_1 = obj_setup[\"tsr_bound1\"]\n param.addTSRChain(TSRChain(mimic_body_name=\"cabinets\", mimic_body_index=[3]).addTSR(T0_w, Tw_e_0, Bw_0).addTSR(T0_w, Tw_e_1, Bw_1))\n # voxel and task representation embeddings\n param.mpnet_parameter.voxel_dataset = \"/%s/%s\" % (scene_name, obj_name)\n param.mpnet_parameter.ohot_dataset = \"/%s/%s\" % (scene_name, obj_name)\n # plan\n resp, t_time, traj = planner.solve(start_config, goal_config, param)\n time.sleep(1) # I don't know why, but removing this line may cause segment fault, so be careful\n robot.WaitForController(0)\n # show the result\n if args.visible and resp is True:\n robot.GetController().SetPath(traj)\n cabinet.GetController().SetPath(traj)\n robot.WaitForController(0)\n cabinet.WaitForController(0)\n # go to goal position\n robot.ReleaseAllGrabbed()\n robot.WaitForController(0)\n robot.SetActiveDOFValues(goal_config)\n cleanupObject(orEnv, obj_name, obj, obj_setup)\n # save result and clean up\n result_dict[scene_name][obj_name] = t_time\n\n if not os.path.exists(os.path.join(args.result_dir, \"temp\")):\n os.makedirs(os.path.join(args.result_dir, \"temp\"))\n result_filename = os.path.join(args.result_dir, \"temp\", \"result_{}.p\".format(scene_name))\n with open(result_filename, \"wb\") as f:\n pickle.dump(result_dict, f)\n\n\ndef mergeResults(work_dir, scene_names):\n all_dict = {}\n for scene_name in scene_names:\n result_filename = os.path.join(work_dir, \"temp\", \"result_{}.p\".format(scene_name))\n if not os.path.exists(result_filename):\n print(result_filename)\n continue\n\n with open(result_filename, \"rb\") as f:\n result_dict = pickle.load(f)\n all_dict[scene_name] = result_dict[scene_name]\n\n return all_dict\n\n\ndef saveResultCSV(filename, cols, result_dict):\n fieldnames = [\"scene_name\"] + list(cols)\n with open(filename, \"wb\") as f:\n csv_writer = csv.DictWriter(f, fieldnames=fieldnames)\n csv_writer.writeheader()\n for (scene_name, scene_result) in result_dict.items():\n row = {\"scene_name\": scene_name}\n row.update(scene_result)\n csv_writer.writerow(row)\n\n\ndef printStatistics(filename, cols):\n data = np.loadtxt(filename, delimiter=\",\", skiprows=1, usecols=cols)\n inf_mask = np.isinf(data)\n nan_mask = np.isnan(data)\n success_mask = np.logical_and(np.logical_not(inf_mask), np.logical_not(nan_mask))\n\n success_count = success_mask.sum()\n valid_count = success_mask.sum() + inf_mask.sum()\n accuracy = float(success_count) / float(valid_count)\n print(\"accuracy: \", accuracy, \" (\", success_count, \"/\", valid_count, \")\")\n\n success_row_mask = np.logical_and.reduce(success_mask, 1)\n success_rows = data[success_row_mask]\n average_time = success_rows.sum(axis=1).mean(axis=0)\n print(\"mean time: \", average_time)\n\n\ndef test(args):\n all_setup_dict = loadTestData(args.env)\n\n param = PlannerParameter()\n param.solver_parameter.type = args.algorithm\n param.solver_parameter.time = 25 if args.env == \"bartender\" else 60\n param.solver_parameter.range = 0.05\n param.constraint_parameter.type = args.space\n param.constraint_parameter.tolerance = 1e-3\n param.constraint_parameter.delta = 0.05\n if args.space == \"proj\":\n pass\n elif args.space == \"atlas\":\n param.atlas_parameter.rho = 1.5\n param.atlas_parameter.exploration = 0.9\n param.atlas_parameter.epsilon = 0.01\n elif args.space in (\"tangent-bundle\", \"tangent_bundle\", \"tb\"):\n param.atlas_parameter.rho = 2.0\n param.atlas_parameter.exploration = 0.9\n param.atlas_parameter.epsilon = 0.01\n # MPNet parameters\n param.mpnet_parameter.pnet_path = os.path.join(args.work_dir, \"torchscript\", \"pnet.pt\")\n param.mpnet_parameter.dnet_path = os.path.join(args.work_dir, \"torchscript\", \"dnet.pt\") if args.use_dnet else \"\"\n param.mpnet_parameter.voxel_path = os.path.join(args.work_dir, \"embedding\", \"voxel.hdf5\")\n param.mpnet_parameter.ohot_path = os.path.join(args.work_dir, \"embedding\", \"task_embedding.hdf5\")\n param.mpnet_parameter.predict_tsr = args.use_tsr\n\n # write settings to a file\n with open(os.path.join(args.result_dir, \"args.xml\"), \"w\") as f:\n f.write(\"<parameter>\\n\")\n f.write(str(param))\n f.write(\"</parameter>\\n\")\n with open(os.path.join(args.result_dir, \"args.yaml\"), \"w\") as f:\n yaml.dump(args.__dict__, f)\n\n # run each test in a separate process\n for (scene_name, scene_setup) in all_setup_dict.items():\n p = Process(target=lambda: test_per_scene(scene_name, scene_setup, param, args))\n p.start()\n p.join()\n\n # collect results, merge into a CSV, and print statistics\n result_dict = mergeResults(args.result_dir, all_setup_dict.keys())\n result_csv_path = os.path.join(args.result_dir, \"result_{}_{}_{}.csv\".format(args.algorithm, args.space, (\"dnet\" if args.use_dnet else \"no-dnet\")))\n if args.env == \"bartender\":\n cols = [\"fuze_bottle\", \"juice\", \"coke_can\", \"plasticmug\", \"teakettle\"]\n col_indices = [1, 2, 3, 4, 5]\n elif args.env == \"kitchen\":\n cols = [\"fuze_bottle\", \"juice\", \"coke_can\", \"mugred\", \"mugblack\", \"pitcher\", \"door\"]\n col_indices = [1, 2, 3, 4, 5, 6, 7]\n else:\n cols = []\n col_indices = []\n saveResultCSV(result_csv_path, cols, result_dict)\n printStatistics(result_csv_path, col_indices)\n\n\ndef get_args():\n parser = ArgumentParser(description=\"A all-in-one script to test RRTConnect, CoMPNet and CoMPNetX algorithm.\")\n parser.add_argument(\"-l\", \"--log_level\", type=int, choices=(0, 1, 2, 3, 4), default=2, help=\"Set log level. Lower level generates more logs.\")\n parser.add_argument(\"-v\", \"--visible\", action=\"store_true\", help=\"Show a 3D visualization of the planning.\")\n parser.add_argument(\"-d\", \"--work_dir\", required=True,\n help=\"Output directory during training. Setting, data and models will be read from this directory automatically.\")\n parser.add_argument(\"-s\", \"--space\", choices=(\"proj\", \"atlas\", \"tb\"), default=\"atlas\", help=\"Constraint-adherence method to use.\")\n parser.add_argument(\"-a\", \"--algorithm\", choices=(\"compnetx\", \"rrtconnect\"), default=\"compnetx\",\n help=\"Select an algorithm. Choose `compnetx` for both CoMPNet and CoMPNetX, and the exact algorithm will be selected according to the settings in the work directory.\")\n parser.add_argument(\"-p\", \"--use_dnet\", action=\"store_true\", help=\"Use neural projector.\")\n return parser.parse_args()\n\n\ndef process_args(args):\n if sys.version_info[0] != 2:\n print(\"This script only works under python2, because of the limitation of OpenRAVE. Exit.\")\n exit()\n if not os.path.exists(args.work_dir):\n print(\"%s does not exist. Exit. \" % args.work_dir)\n exit()\n\n with open(os.path.join(args.work_dir, \"args.yaml\"), \"r\") as f:\n training_args = yaml.load(f, Loader=yaml.CLoader)\n args.env = training_args[\"env\"]\n args.use_text = training_args[\"use_text\"]\n args.use_tsr = training_args[\"use_tsr\"]\n args.torchscript_dir = training_args[\"torchscript_dir\"]\n args.embedding_dir = training_args[\"embedding_dir\"]\n\n args.result_dir = os.path.join(args.work_dir, \"result\")\n if not os.path.exists(args.result_dir):\n os.makedirs(args.result_dir)\n\n if args.use_dnet and not os.path.exists(os.path.join(args.torchscript_dir, \"dnet.pt\")):\n print(\"Cannot find neural projector. use_dnet is set to false.\")\n args.use_dnet = False\n\n return args\n\n\ndef print_args(args):\n print(\"Test will run with the following arguments: \")\n keys = list(args.__dict__.keys())\n keys.sort()\n for key in keys:\n value = args.__dict__[key]\n print(\"\\t%s: %s\" % (key, value))\n\n\nif __name__ == \"__main__\":\n args = process_args(get_args())\n print_args(args)\n test(args)\n"
] | [
[
"numpy.logical_not",
"numpy.isnan",
"numpy.logical_and.reduce",
"numpy.ones",
"numpy.array",
"numpy.isinf",
"numpy.loadtxt"
]
] |
jinxing64/flink-ai-extended | [
"f8eff31d69929f02c0953d60b983104cb60a7aa9"
] | [
"flink-ai-flow/python_ai_flow/test/python_codes/evaluate_component/test_python_evaluate_component.py"
] | [
"#\n# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements. See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership. The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License. You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied. See the License for the\n# specific language governing permissions and limitations\n# under the License.\n#\nimport json\nimport threading\nimport time\nimport unittest\nfrom typing import List\n\nfrom streamz import Stream\n\nfrom ai_flow.util.path_util import get_file_dir\nfrom ai_flow.executor.executor import PythonObjectExecutor\nfrom ai_flow.meta.model_meta import ModelType, ModelMeta\nfrom ai_flow.application_master.master import AIFlowMaster\nimport ai_flow as af\nfrom ai_flow.udf.function_context import FunctionContext\nfrom ai_flow.meta.example_meta import ExampleSupportType, ExampleMeta\nfrom python_ai_flow import ExampleExecutor, Executor\nfrom python_ai_flow.test import test_util\nimport tensorflow as tf\nimport os\n\n\nclass ReadBatchExample(ExampleExecutor):\n def execute(self, function_context: FunctionContext, input_list: List) -> List:\n (x_train, y_train), (x_test, y_test) = tf.keras.datasets.mnist.load_data(path='mnist.npz')\n return [[x_train, y_train, x_test, y_test]]\n\n\ndef get_compiled_model():\n model = tf.keras.models.Sequential([\n tf.keras.layers.Flatten(input_shape=(28, 28)),\n tf.keras.layers.Dense(128, activation='relu'),\n tf.keras.layers.Dropout(0.2),\n tf.keras.layers.Dense(10, activation='softmax')\n ])\n return model\n\n\nclass TrainBatchMnistModel(Executor):\n def execute(self, function_context: FunctionContext, input_list: List) -> List:\n model = get_compiled_model()\n model.compile(optimizer='adam',\n loss='sparse_categorical_crossentropy',\n metrics=['accuracy', 'mse'])\n x_train, y_train = input_list[0][0] / 255.0, input_list[0][1]\n model.fit(x_train, y_train, epochs=1)\n model_meta: ModelMeta = function_context.node_spec.output_model\n save_path = 'saved_models/{}'.format(round(time.time() * 1000))\n model.save(save_path, save_format='tf')\n af.register_model_version(model=model_meta,\n model_path=save_path)\n return []\n\n\nclass EvaluateBatchMnistModel(Executor):\n def __init__(self):\n super().__init__()\n self.path = None\n\n def setup(self, function_context: FunctionContext):\n model_name = function_context.node_spec.model.name\n notifications = af.list_events(key=model_name)\n self.path = json.loads(notifications[0].value).get('_model_path')\n\n def execute(self, function_context: FunctionContext, input_list: List) -> List:\n save_path = self.path\n x_evaluate, y_evaluate = input_list[0][2], input_list[0][3]\n model = tf.keras.models.load_model(save_path)\n result = model.evaluate(x_evaluate, y_evaluate, verbose=2)\n return [result]\n\n\nclass SourceThread(threading.Thread):\n def __init__(self):\n super().__init__()\n self.stream = Stream()\n\n def run(self) -> None:\n (x_train, y_train), (x_test, y_test) = tf.keras.datasets.mnist.load_data(path='mnist.npz')\n for _ in range(0, 4):\n print('The example has been read {} times'.format(_ + 1))\n self.stream.emit((x_test, y_test))\n time.sleep(2)\n\n\nclass ReadStreamExample(ExampleExecutor):\n def setup(self, function_context: FunctionContext):\n self.thread = SourceThread()\n\n def execute(self, function_context: FunctionContext, input_list: List) -> List:\n self.thread.start()\n return [self.thread.stream]\n\n\nclass EvaluateStreamMnistModel(Executor):\n def __init__(self):\n super().__init__()\n self.path = None\n\n def setup(self, function_context: FunctionContext):\n model_name = function_context.node_spec.model.name\n notifications = af.list_events(key=model_name)\n self.path = json.loads(notifications[0].value).get('_model_path')\n\n def execute(self, function_context: FunctionContext, input_list: List) -> List:\n def evaluate(df, model, sess, graph):\n x_evaluate, y_evaluate = df[0] / 255.0, df[1]\n with graph.as_default():\n tf.compat.v1.keras.backend.set_session(sess)\n result = model.evaluate(x_evaluate, y_evaluate, verbose=2)\n return result\n\n save_path = self.path\n sess = tf.Session()\n graph = tf.get_default_graph()\n tf.compat.v1.keras.backend.set_session(sess)\n model = tf.keras.models.load_model(save_path)\n\n data: Stream = input_list[0]\n return [data.map(evaluate, model, sess, graph)]\n\n\nclass WriteStreamExample(ExampleExecutor):\n\n def execute(self, function_context: FunctionContext, input_list: List) -> List:\n example_meta: ExampleMeta = function_context.node_spec.example_meta\n\n def sink(df):\n pass\n\n def write_example(df):\n path = example_meta.stream_uri\n with open(path, 'a') as f:\n f.write(str(df))\n f.write('\\n')\n return df\n\n data: Stream = input_list[0]\n data.map(write_example).sink(sink)\n return []\n\n\nclass TestEvaluateComponent(unittest.TestCase):\n @classmethod\n def setUpClass(cls) -> None:\n config_file = test_util.get_master_config_file()\n cls.master = AIFlowMaster(config_file=config_file)\n cls.master.start()\n test_util.set_project_config(__file__)\n\n @classmethod\n def tearDownClass(cls) -> None:\n cls.master.stop()\n af.unset_project_config()\n\n def tearDown(self):\n TestEvaluateComponent.master._clear_db()\n\n def test_batch_evaluate_component(self):\n input_example_meta = af.register_example(name='batch_train_example',\n support_type=ExampleSupportType.EXAMPLE_BATCH)\n model_meta = af.register_model(model_name='mnist_model',\n model_type=ModelType.SAVED_MODEL)\n batch_output_file = get_file_dir(__file__) + '/batch_evaluate'\n evaluate_output = af.register_artifact(name='batch_evaluate',\n batch_uri=batch_output_file)\n output_example_meta = af.register_example(name='batch_evaluate_example',\n support_type=ExampleSupportType.EXAMPLE_BATCH,\n data_type='numpy',\n data_format='txt',\n batch_uri=batch_output_file)\n if os.path.exists(batch_output_file):\n os.remove(batch_output_file)\n with af.config(af.BaseJobConfig(platform='local', engine='python', job_name='batch_evaluate')):\n input_example = af.read_example(example_info=input_example_meta,\n executor=PythonObjectExecutor(python_object=ReadBatchExample()))\n\n batch_train = af.train(input_data_list=[input_example],\n executor=PythonObjectExecutor(python_object=TrainBatchMnistModel()),\n model_info=model_meta)\n batch_evaluate = af.evaluate(input_data_list=[input_example], model_info=model_meta,\n executor=PythonObjectExecutor(python_object=EvaluateBatchMnistModel()),\n output_num=1)\n af.write_example(input_data=batch_evaluate, example_info=output_example_meta)\n af.stop_before_control_dependency(batch_evaluate, batch_train)\n workflow_id = af.run(test_util.get_project_path())\n res = af.wait_workflow_execution_finished(workflow_id)\n self.assertEqual(0, res)\n\n def test_stream_evaluate_component(self):\n input_example_meta = af.register_example(name='batch_train_example',\n support_type=ExampleSupportType.EXAMPLE_BATCH)\n model_meta = af.register_model(model_name='mnist_model',\n model_type=ModelType.SAVED_MODEL)\n stream_evaluate_example_meta = af.register_example(name='stream_evaluate_example',\n support_type=ExampleSupportType.EXAMPLE_STREAM)\n stream_output_file = get_file_dir(__file__) + '/stream_evaluate'\n evaluate_output = af.register_artifact(name='stream_evaluate',\n stream_uri=stream_output_file)\n stream_evaluate_result_example_meta = af.register_example(name='stream_evaluate_result_example',\n support_type=ExampleSupportType.EXAMPLE_STREAM,\n stream_uri=stream_output_file)\n if os.path.exists(stream_output_file):\n os.remove(stream_output_file)\n with af.config(af.BaseJobConfig(platform='local', engine='python', job_name='stream_evaluate')):\n input_example = af.read_example(example_info=input_example_meta,\n executor=PythonObjectExecutor(python_object=ReadBatchExample()))\n\n batch_train = af.train(input_data_list=[input_example],\n executor=PythonObjectExecutor(python_object=TrainBatchMnistModel()),\n model_info=model_meta)\n stream_evaluate_example = af.read_example(example_info=stream_evaluate_example_meta,\n executor=PythonObjectExecutor(\n python_object=ReadStreamExample()))\n stream_evaluate = af.evaluate(input_data_list=[stream_evaluate_example], model_info=model_meta,\n executor=PythonObjectExecutor(python_object=EvaluateStreamMnistModel()),\n output_num=1)\n af.write_example(input_data=stream_evaluate, example_info=stream_evaluate_result_example_meta,\n executor=PythonObjectExecutor(python_object=WriteStreamExample()))\n af.stop_before_control_dependency(stream_evaluate, batch_train)\n workflow_id = af.run(test_util.get_project_path())\n res = af.wait_workflow_execution_finished(workflow_id)\n self.assertEqual(0, res)\n"
] | [
[
"tensorflow.keras.models.load_model",
"tensorflow.keras.layers.Dropout",
"tensorflow.keras.layers.Dense",
"tensorflow.compat.v1.keras.backend.set_session",
"tensorflow.keras.datasets.mnist.load_data",
"tensorflow.Session",
"tensorflow.get_default_graph",
"tensorflow.keras.layers.Flatten"
]
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.