repo_name
stringlengths 6
130
| hexsha
sequence | file_path
sequence | code
sequence | apis
sequence | possible_versions
list |
---|---|---|---|---|---|
node21challenge/rank1_node21_detection | [
"5c20bb650ed30c4a5f86cfa738018c456af7bfe9",
"5c20bb650ed30c4a5f86cfa738018c456af7bfe9"
] | [
"src/models/modules/DETR/segmentation.py",
"src/models/modules/RetinaNet.py"
] | [
"# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved\n\"\"\"\nThis file provides the definition of the convolutional heads used to predict masks, as well as the losses\n\"\"\"\nimport io\nfrom collections import defaultdict\nfrom typing import List, Optional\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch import Tensor\nfrom PIL import Image\n\nimport src.models.modules.DETR.util.box_ops as box_ops\nfrom src.models.modules.DETR.util.misc import NestedTensor, interpolate, nested_tensor_from_tensor_list\n\ntry:\n from panopticapi.utils import id2rgb, rgb2id\nexcept ImportError:\n pass\n\n\nclass DETRsegm(nn.Module):\n def __init__(self, detr, freeze_detr=False):\n super().__init__()\n self.detr = detr\n\n if freeze_detr:\n for p in self.parameters():\n p.requires_grad_(False)\n\n hidden_dim, nheads = detr.transformer.d_model, detr.transformer.nhead\n self.bbox_attention = MHAttentionMap(hidden_dim, hidden_dim, nheads, dropout=0.0)\n self.mask_head = MaskHeadSmallConv(hidden_dim + nheads, [1024, 512, 256], hidden_dim)\n\n def forward(self, samples: NestedTensor):\n if isinstance(samples, (list, torch.Tensor)):\n samples = nested_tensor_from_tensor_list(samples)\n features, pos = self.detr.backbone(samples)\n\n bs = features[-1].tensors.shape[0]\n\n src, mask = features[-1].decompose()\n assert mask is not None\n src_proj = self.detr.input_proj(src)\n hs, memory = self.detr.transformer(src_proj, mask, self.detr.query_embed.weight, pos[-1])\n\n outputs_class = self.detr.class_embed(hs)\n outputs_coord = self.detr.bbox_embed(hs).sigmoid()\n out = {\"pred_logits\": outputs_class[-1], \"pred_boxes\": outputs_coord[-1]}\n if self.detr.aux_loss:\n out['aux_outputs'] = self.detr._set_aux_loss(outputs_class, outputs_coord)\n\n # FIXME h_boxes takes the last one computed, keep this in mind\n bbox_mask = self.bbox_attention(hs[-1], memory, mask=mask)\n\n seg_masks = self.mask_head(src_proj, bbox_mask, [features[2].tensors, features[1].tensors, features[0].tensors])\n outputs_seg_masks = seg_masks.view(bs, self.detr.num_queries, seg_masks.shape[-2], seg_masks.shape[-1])\n\n out[\"pred_masks\"] = outputs_seg_masks\n return out\n\n\ndef _expand(tensor, length: int):\n return tensor.unsqueeze(1).repeat(1, int(length), 1, 1, 1).flatten(0, 1)\n\n\nclass MaskHeadSmallConv(nn.Module):\n \"\"\"\n Simple convolutional head, using group norm.\n Upsampling is done using a FPN approach\n \"\"\"\n\n def __init__(self, dim, fpn_dims, context_dim):\n super().__init__()\n\n inter_dims = [dim, context_dim // 2, context_dim // 4, context_dim // 8, context_dim // 16, context_dim // 64]\n self.lay1 = torch.nn.Conv2d(dim, dim, 3, padding=1)\n self.gn1 = torch.nn.GroupNorm(8, dim)\n self.lay2 = torch.nn.Conv2d(dim, inter_dims[1], 3, padding=1)\n self.gn2 = torch.nn.GroupNorm(8, inter_dims[1])\n self.lay3 = torch.nn.Conv2d(inter_dims[1], inter_dims[2], 3, padding=1)\n self.gn3 = torch.nn.GroupNorm(8, inter_dims[2])\n self.lay4 = torch.nn.Conv2d(inter_dims[2], inter_dims[3], 3, padding=1)\n self.gn4 = torch.nn.GroupNorm(8, inter_dims[3])\n self.lay5 = torch.nn.Conv2d(inter_dims[3], inter_dims[4], 3, padding=1)\n self.gn5 = torch.nn.GroupNorm(8, inter_dims[4])\n self.out_lay = torch.nn.Conv2d(inter_dims[4], 1, 3, padding=1)\n\n self.dim = dim\n\n self.adapter1 = torch.nn.Conv2d(fpn_dims[0], inter_dims[1], 1)\n self.adapter2 = torch.nn.Conv2d(fpn_dims[1], inter_dims[2], 1)\n self.adapter3 = torch.nn.Conv2d(fpn_dims[2], inter_dims[3], 1)\n\n for m in self.modules():\n if isinstance(m, nn.Conv2d):\n nn.init.kaiming_uniform_(m.weight, a=1)\n nn.init.constant_(m.bias, 0)\n\n def forward(self, x: Tensor, bbox_mask: Tensor, fpns: List[Tensor]):\n x = torch.cat([_expand(x, bbox_mask.shape[1]), bbox_mask.flatten(0, 1)], 1)\n\n x = self.lay1(x)\n x = self.gn1(x)\n x = F.relu(x)\n x = self.lay2(x)\n x = self.gn2(x)\n x = F.relu(x)\n\n cur_fpn = self.adapter1(fpns[0])\n if cur_fpn.size(0) != x.size(0):\n cur_fpn = _expand(cur_fpn, x.size(0) // cur_fpn.size(0))\n x = cur_fpn + F.interpolate(x, size=cur_fpn.shape[-2:], mode=\"nearest\")\n x = self.lay3(x)\n x = self.gn3(x)\n x = F.relu(x)\n\n cur_fpn = self.adapter2(fpns[1])\n if cur_fpn.size(0) != x.size(0):\n cur_fpn = _expand(cur_fpn, x.size(0) // cur_fpn.size(0))\n x = cur_fpn + F.interpolate(x, size=cur_fpn.shape[-2:], mode=\"nearest\")\n x = self.lay4(x)\n x = self.gn4(x)\n x = F.relu(x)\n\n cur_fpn = self.adapter3(fpns[2])\n if cur_fpn.size(0) != x.size(0):\n cur_fpn = _expand(cur_fpn, x.size(0) // cur_fpn.size(0))\n x = cur_fpn + F.interpolate(x, size=cur_fpn.shape[-2:], mode=\"nearest\")\n x = self.lay5(x)\n x = self.gn5(x)\n x = F.relu(x)\n\n x = self.out_lay(x)\n return x\n\n\nclass MHAttentionMap(nn.Module):\n \"\"\"This is a 2D attention module, which only returns the attention softmax (no multiplication by value)\"\"\"\n\n def __init__(self, query_dim, hidden_dim, num_heads, dropout=0.0, bias=True):\n super().__init__()\n self.num_heads = num_heads\n self.hidden_dim = hidden_dim\n self.dropout = nn.Dropout(dropout)\n\n self.q_linear = nn.Linear(query_dim, hidden_dim, bias=bias)\n self.k_linear = nn.Linear(query_dim, hidden_dim, bias=bias)\n\n nn.init.zeros_(self.k_linear.bias)\n nn.init.zeros_(self.q_linear.bias)\n nn.init.xavier_uniform_(self.k_linear.weight)\n nn.init.xavier_uniform_(self.q_linear.weight)\n self.normalize_fact = float(hidden_dim / self.num_heads) ** -0.5\n\n def forward(self, q, k, mask: Optional[Tensor] = None):\n q = self.q_linear(q)\n k = F.conv2d(k, self.k_linear.weight.unsqueeze(-1).unsqueeze(-1), self.k_linear.bias)\n qh = q.view(q.shape[0], q.shape[1], self.num_heads, self.hidden_dim // self.num_heads)\n kh = k.view(k.shape[0], self.num_heads, self.hidden_dim // self.num_heads, k.shape[-2], k.shape[-1])\n weights = torch.einsum(\"bqnc,bnchw->bqnhw\", qh * self.normalize_fact, kh)\n\n if mask is not None:\n weights.masked_fill_(mask.unsqueeze(1).unsqueeze(1), float(\"-inf\"))\n weights = F.softmax(weights.flatten(2), dim=-1).view(weights.size())\n weights = self.dropout(weights)\n return weights\n\n\ndef dice_loss(inputs, targets, num_boxes):\n \"\"\"\n Compute the DICE loss, similar to generalized IOU for masks\n Args:\n inputs: A float tensor of arbitrary shape.\n The predictions for each example.\n targets: A float tensor with the same shape as inputs. Stores the binary\n classification label for each element in inputs\n (0 for the negative class and 1 for the positive class).\n \"\"\"\n inputs = inputs.sigmoid()\n inputs = inputs.flatten(1)\n numerator = 2 * (inputs * targets).sum(1)\n denominator = inputs.sum(-1) + targets.sum(-1)\n loss = 1 - (numerator + 1) / (denominator + 1)\n return loss.sum() / num_boxes\n\n\ndef sigmoid_focal_loss(inputs, targets, num_boxes, alpha: float = 0.25, gamma: float = 2):\n \"\"\"\n Loss used in RetinaNet for dense detection: https://arxiv.org/abs/1708.02002.\n Args:\n inputs: A float tensor of arbitrary shape.\n The predictions for each example.\n targets: A float tensor with the same shape as inputs. Stores the binary\n classification label for each element in inputs\n (0 for the negative class and 1 for the positive class).\n alpha: (optional) Weighting factor in range (0,1) to balance\n positive vs negative examples. Default = -1 (no weighting).\n gamma: Exponent of the modulating factor (1 - p_t) to\n balance easy vs hard examples.\n Returns:\n Loss tensor\n \"\"\"\n prob = inputs.sigmoid()\n ce_loss = F.binary_cross_entropy_with_logits(inputs, targets, reduction=\"none\")\n p_t = prob * targets + (1 - prob) * (1 - targets)\n loss = ce_loss * ((1 - p_t) ** gamma)\n\n if alpha >= 0:\n alpha_t = alpha * targets + (1 - alpha) * (1 - targets)\n loss = alpha_t * loss\n\n return loss.mean(1).sum() / num_boxes\n\n\nclass PostProcessSegm(nn.Module):\n def __init__(self, threshold=0.5):\n super().__init__()\n self.threshold = threshold\n\n @torch.no_grad()\n def forward(self, results, outputs, orig_target_sizes, max_target_sizes):\n assert len(orig_target_sizes) == len(max_target_sizes)\n max_h, max_w = max_target_sizes.max(0)[0].tolist()\n outputs_masks = outputs[\"pred_masks\"].squeeze(2)\n outputs_masks = F.interpolate(outputs_masks, size=(max_h, max_w), mode=\"bilinear\", align_corners=False)\n outputs_masks = (outputs_masks.sigmoid() > self.threshold).cpu()\n\n for i, (cur_mask, t, tt) in enumerate(zip(outputs_masks, max_target_sizes, orig_target_sizes)):\n img_h, img_w = t[0], t[1]\n results[i][\"masks\"] = cur_mask[:, :img_h, :img_w].unsqueeze(1)\n results[i][\"masks\"] = F.interpolate(\n results[i][\"masks\"].float(), size=tuple(tt.tolist()), mode=\"nearest\"\n ).byte()\n\n return results\n\n\nclass PostProcessPanoptic(nn.Module):\n \"\"\"This class converts the output of the model to the final panoptic result, in the format expected by the\n coco panoptic API \"\"\"\n\n def __init__(self, is_thing_map, threshold=0.85):\n \"\"\"\n Parameters:\n is_thing_map: This is a whose keys are the class ids, and the values a boolean indicating whether\n the class is a thing (True) or a stuff (False) class\n threshold: confidence threshold: segments with confidence lower than this will be deleted\n \"\"\"\n super().__init__()\n self.threshold = threshold\n self.is_thing_map = is_thing_map\n\n def forward(self, outputs, processed_sizes, target_sizes=None):\n \"\"\" This function computes the panoptic prediction from the model's predictions.\n Parameters:\n outputs: This is a dict coming directly from the model. See the model doc for the content.\n processed_sizes: This is a list of tuples (or torch tensors) of sizes of the images that were passed to the\n model, ie the size after data augmentation but before batching.\n target_sizes: This is a list of tuples (or torch tensors) corresponding to the requested final size\n of each prediction. If left to None, it will default to the processed_sizes\n \"\"\"\n if target_sizes is None:\n target_sizes = processed_sizes\n assert len(processed_sizes) == len(target_sizes)\n out_logits, raw_masks, raw_boxes = outputs[\"pred_logits\"], outputs[\"pred_masks\"], outputs[\"pred_boxes\"]\n assert len(out_logits) == len(raw_masks) == len(target_sizes)\n preds = []\n\n def to_tuple(tup):\n if isinstance(tup, tuple):\n return tup\n return tuple(tup.cpu().tolist())\n\n for cur_logits, cur_masks, cur_boxes, size, target_size in zip(\n out_logits, raw_masks, raw_boxes, processed_sizes, target_sizes\n ):\n # we filter empty queries and detection below threshold\n scores, labels = cur_logits.softmax(-1).max(-1)\n keep = labels.ne(outputs[\"pred_logits\"].shape[-1] - 1) & (scores > self.threshold)\n cur_scores, cur_classes = cur_logits.softmax(-1).max(-1)\n cur_scores = cur_scores[keep]\n cur_classes = cur_classes[keep]\n cur_masks = cur_masks[keep]\n cur_masks = interpolate(cur_masks[:, None], to_tuple(size), mode=\"bilinear\").squeeze(1)\n cur_boxes = box_ops.box_cxcywh_to_xyxy(cur_boxes[keep])\n\n h, w = cur_masks.shape[-2:]\n assert len(cur_boxes) == len(cur_classes)\n\n # It may be that we have several predicted masks for the same stuff class.\n # In the following, we track the list of masks ids for each stuff class (they are merged later on)\n cur_masks = cur_masks.flatten(1)\n stuff_equiv_classes = defaultdict(lambda: [])\n for k, label in enumerate(cur_classes):\n if not self.is_thing_map[label.item()]:\n stuff_equiv_classes[label.item()].append(k)\n\n def get_ids_area(masks, scores, dedup=False):\n # This helper function creates the final panoptic segmentation image\n # It also returns the area of the masks that appears on the image\n\n m_id = masks.transpose(0, 1).softmax(-1)\n\n if m_id.shape[-1] == 0:\n # We didn't detect any mask :(\n m_id = torch.zeros((h, w), dtype=torch.long, device=m_id.device)\n else:\n m_id = m_id.argmax(-1).view(h, w)\n\n if dedup:\n # Merge the masks corresponding to the same stuff class\n for equiv in stuff_equiv_classes.values():\n if len(equiv) > 1:\n for eq_id in equiv:\n m_id.masked_fill_(m_id.eq(eq_id), equiv[0])\n\n final_h, final_w = to_tuple(target_size)\n\n seg_img = Image.fromarray(id2rgb(m_id.view(h, w).cpu().numpy()))\n seg_img = seg_img.resize(size=(final_w, final_h), resample=Image.NEAREST)\n\n np_seg_img = (\n torch.ByteTensor(torch.ByteStorage.from_buffer(seg_img.tobytes())).view(final_h, final_w, 3).numpy()\n )\n m_id = torch.from_numpy(rgb2id(np_seg_img))\n\n area = []\n for i in range(len(scores)):\n area.append(m_id.eq(i).sum().item())\n return area, seg_img\n\n area, seg_img = get_ids_area(cur_masks, cur_scores, dedup=True)\n if cur_classes.numel() > 0:\n # We know filter empty masks as long as we find some\n while True:\n filtered_small = torch.as_tensor(\n [area[i] <= 4 for i, c in enumerate(cur_classes)], dtype=torch.bool, device=keep.device\n )\n if filtered_small.any().item():\n cur_scores = cur_scores[~filtered_small]\n cur_classes = cur_classes[~filtered_small]\n cur_masks = cur_masks[~filtered_small]\n area, seg_img = get_ids_area(cur_masks, cur_scores)\n else:\n break\n\n else:\n cur_classes = torch.ones(1, dtype=torch.long, device=cur_classes.device)\n\n segments_info = []\n for i, a in enumerate(area):\n cat = cur_classes[i].item()\n segments_info.append({\"id\": i, \"isthing\": self.is_thing_map[cat], \"category_id\": cat, \"area\": a})\n del cur_classes\n\n with io.BytesIO() as out:\n seg_img.save(out, format=\"PNG\")\n predictions = {\"png_string\": out.getvalue(), \"segments_info\": segments_info}\n preds.append(predictions)\n return preds\n",
"import torchvision.models as models\nfrom torchvision.models.detection import faster_rcnn, fasterrcnn_resnet50_fpn, retinanet_resnet50_fpn\nfrom torch import nn\nimport torch\nimport math \nimport torchvision\nimport torch.nn.functional as F \nfrom typing import OrderedDict\nclass RetinaNet(nn.Module): \n def __init__(self,cfg):\n super(RetinaNet, self).__init__()\n if cfg.get('customBackbone',None):\n backbone = torchvision.models.detection.backbone_utils.resnet_fpn_backbone(cfg.customBackbone, pretrained = cfg.pretrained_backbone, returned_layers=[2, 3, 4],\n extra_blocks=torchvision.ops.feature_pyramid_network.LastLevelP6P7(256, 256), trainable_layers=cfg.get('trainable_layers',5))\n self.model = torchvision.models.detection.RetinaNet(backbone=backbone, num_classes=2)\n elif cfg.get('custom_anchors',False):\n anchor_sizes = ((16,), (32,), (64,), (128,), (256,))\n aspect_ratios = ((0.8, 1.0, 1.2),) * len(anchor_sizes)\n anchor_generator = torchvision.models.detection.retinanet.AnchorGenerator(anchor_sizes,\n aspect_ratios)\n self.model = retinanet_resnet50_fpn(\n pretrained = cfg.pretrained,\n pretrained_backbone = cfg.pretrained_backbone,\n trainable_backbone_layers = cfg.get('trainable_layers',5),\n anchor_generator = anchor_generator\n )\n \n else: \n self.model = retinanet_resnet50_fpn(\n pretrained = cfg.pretrained,\n pretrained_backbone = cfg.pretrained_backbone,\n trainable_backbone_layers = cfg.get('trainable_layers',5)\n )\n\n\n\n # replace classification layer \n in_features = self.model.head.classification_head.conv[0].in_channels\n num_anchors = self.model.head.classification_head.num_anchors\n self.model.head.classification_head.num_classes = cfg.num_classes\n\n cls_logits = torch.nn.Conv2d(in_features, num_anchors * cfg.num_classes, kernel_size = 3, stride=1, padding=1)\n torch.nn.init.normal_(cls_logits.weight, std=0.01) # as per pytorch code\n torch.nn.init.constant_(cls_logits.bias, -math.log((1 - 0.01) / 0.01)) # as per pytorcch code \n # assign cls head to model\n self.model.head.classification_head.cls_logits = cls_logits\n\n def get_model(self):\n return self.model\n"
] | [
[
"torch.nn.Dropout",
"torch.ones",
"torch.zeros",
"torch.nn.init.constant_",
"torch.einsum",
"torch.nn.functional.binary_cross_entropy_with_logits",
"torch.nn.Conv2d",
"torch.nn.init.kaiming_uniform_",
"torch.nn.Linear",
"torch.nn.functional.relu",
"torch.no_grad",
"torch.nn.init.xavier_uniform_",
"torch.nn.functional.interpolate",
"torch.nn.init.zeros_",
"torch.nn.GroupNorm"
],
[
"torch.nn.Conv2d",
"torch.nn.init.normal_"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
GAN-Challenger/pytorch-CycleGAN-and-pix2pix | [
"fc5597e7cdef2f5566d6fd2131386fff647080cb"
] | [
"models/base_model.py"
] | [
"import os\nimport torch\n\n\nclass BaseModel():\n def name(self):\n return 'BaseModel'\n\n def initialize(self, opt):\n self.opt = opt\n self.gpu_ids = opt.gpu_ids\n self.isTrain = opt.isTrain\n self.Tensor = torch.cuda.FloatTensor if self.gpu_ids else torch.Tensor\n self.save_dir = os.path.join(opt.checkpoints_dir, opt.name)\n if opt.resize_or_crop != 'scale_width':\n torch.backends.cudnn.benchmark = True\n\n def set_input(self, input):\n self.input = input\n\n def forward(self):\n pass\n\n # used in test time, no backprop\n def test(self):\n pass\n\n def get_image_paths(self):\n pass\n\n def optimize_parameters(self):\n pass\n\n def get_current_visuals(self):\n return self.input\n\n def get_current_errors(self):\n return {}\n\n def save(self, label):\n pass\n\n # helper saving function that can be used by subclasses\n def save_network(self, network, network_label, epoch_label, gpu_ids):\n save_filename = '%s_net_%s.pth' % (epoch_label, network_label)\n save_path = os.path.join(self.save_dir, save_filename)\n torch.save(network.cpu().state_dict(), save_path)\n if len(gpu_ids) and torch.cuda.is_available():\n network.cuda(gpu_ids[0])\n\n # helper loading function that can be used by subclasses\n def load_network(self, network, network_label, epoch_label):\n save_filename = '%s_net_%s.pth' % (epoch_label, network_label)\n save_path = os.path.join(self.save_dir, save_filename)\n network.load_state_dict(torch.load(save_path))\n\n # update learning rate (called once every epoch)\n def update_learning_rate(self):\n for scheduler in self.schedulers:\n scheduler.step()\n lr = self.optimizers[0].param_groups[0]['lr']\n print('learning rate = %.7f' % lr)\n"
] | [
[
"torch.cuda.is_available",
"torch.load"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
AstroHiro/CS155 | [
"c0fbb0fdecb48c4764a56e4fe841468c154eec6e"
] | [
"project1/trial3.py"
] | [
"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Feb 11 22:37:48 2020\n\n@author: hiroyasu\n\"\"\"\n\nimport pandas as pd\nimport torch\nfrom torch import nn\nfrom torch.autograd import Variable\nimport torch.nn.functional as F\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits import mplot3d\nimport random\nfrom sklearn.decomposition import PCA\n\n\nfrom keras.datasets import imdb\nfrom keras.models import Sequential\nfrom keras.layers import Dense\nfrom keras.layers import LSTM\nfrom keras.layers.embeddings import Embedding\nfrom keras.preprocessing import sequence\nfrom keras.layers.convolutional import Conv1D\nfrom keras.layers.convolutional import MaxPooling1D\n\ndf_train = pd.read_csv('data/train.csv', index_col=0)\ndf_test = pd.read_csv('data/test.csv', index_col=0)\n'''\nx_cols = {\n 'series_id': np.uint32,\n 'last_price': np.float32,\n 'mid': np.float32,\n 'opened_position_qty': np.float32,\n 'closed_position_qty': np.float32,\n 'transacted_qty': np.float32,\n 'bid1': np.float32,\n 'bid2': np.float32,\n 'bid3': np.float32,\n 'bid4': np.float32,\n 'bid5': np.float32,\n 'ask1': np.float32,\n 'ask2': np.float32,\n 'ask3': np.float32,\n 'ask4': np.float32,\n 'ask5': np.float32,\n 'bid1vol': np.float32,\n 'bid2vol': np.float32,\n 'bid3vol': np.float32,\n 'bid4vol': np.float32,\n 'bid5vol': np.float32,\n 'ask1vol': np.float32,\n 'ask2vol': np.float32,\n 'ask3vol': np.float32,\n 'ask4vol': np.float32,\n 'ask5vol': np.float32\n}\n'''\ndf_train = df_train.fillna(method='ffill')\ndf_train = df_train.fillna(method='bfill')\ndf_test = df_test.fillna(method='ffill')\ndf_test = df_test.fillna(method='bfill')\nn = (df_train.values).shape[1]-1\nnt = (df_test.values).shape[1]-1\nXall = df_train.values[:,0:n]\nYall = df_train.values[:,n]\nXtest = df_test.values\nn_input = n # rnn input size\nn_hidden = 128 # number of rnn hidden units\nn_output = 1 # rnn input size\nn_layers = 2 # rnn number of layers\n\n# truncate and pad input sequences\n\nclass RNN(nn.Module):\n def __init__(self,n_input,n_hidden,n_output,n_layers):\n super(RNN, self).__init__()\n self.rnn = nn.LSTM(\n input_size=n_input,\n hidden_size=n_hidden, # rnn hidden unit\n num_layers=n_layers, # number of rnn layer\n batch_first=True, # input & output will has batch size as 1s dimension. e.g. (batch, time_step, input_size)\n )\n self.out1 = nn.Linear(n_hidden,n_output)\n #self.out2 = nn.Sigmoid()\n self.n_layers = n_layers\n self.n_hidden = n_hidden\n \n def forward(self,x):\n # x (batch, time_step, input_size)\n # h_state (n_layers, batch, hidden_size)\n # r_out (batch, time_step, hidden_size)\n r_out,_ = self.rnn(x)\n out = self.out1(r_out)\n #out = self.out2(out)\n return out\n \ndef Np2Var(X):\n X = X.astype(np.float32)\n X = torch.from_numpy(X)\n return X\n\ndef RandomizeTrainData(Xtrain,Ytrain,time_step):\n # Note that training data = original data - test data\n N = Ytrain.size\n Ntime = N/time_step\n Ntime = int(Ntime)\n XtrainR = np.zeros((Ntime,time_step,6))\n YtrainR = np.zeros((Ntime,time_step,1))\n for j in range(Ntime):\n XtrainR[j,:,:] = Xtrain[(time_step)*j:(time_step)*(j+1),:]\n YtrainR[j,:,:] = np.array([Ytrain[(time_step)*j:(time_step)*(j+1)]]).T\n idx = np.random.permutation(Ntime)\n XtrainR = XtrainR[idx,:,:]\n YtrainR = YtrainR[idx,:,:]\n return XtrainR,YtrainR\n\ndef preprocessX(X):\n n = X.shape[1]\n XC = np.amax(X,axis=0)\n for i in range(n):\n X[:,i] = X[:,i]/XC[i]\n return X,XC\n\ndef get_model(dropout_prob):\n model = nn.Sequential(\n nn.Conv1d(1, 16, 3), # output dim = (26-2) \\times 16\n nn.BatchNorm1d(16),\n nn.ReLU(),\n nn.MaxPool1d(2),# output dim = 12 \\times 12\n \n nn.Flatten(),\n nn.Linear(2*16, 16),\n nn.ReLU(),\n nn.Linear(16, 1)\n )\n return model\n\ndef train_model(model,Xtrain,Ytrain,Xval,Yval,n_epochs,BatchSize,ValSize):\n # For a multi-class classification problem\n criterion = nn.BCEWithLogitsLoss()\n optimizer = torch.optim.RMSprop(model.parameters())\n # Train the model for 1 epoch, iterating on the data in batches\n N = Ytrain.size/BatchSize\n N = int(N)\n Xval = Np2Var(Xval)\n Xval = Xval.view(ValSize+1,1,-1)\n Yval = Np2Var(np.array([Yval])).T\n for epoch in range(n_epochs):\n print(f'Epoch {epoch+1}/10:', end='')\n # train\n model.train()\n for epoch in range(n_epochs):\n for i in range(N):\n X = Xtrain[BatchSize*i:BatchSize*(i+1),:]\n Y = Ytrain[BatchSize*i:BatchSize*(i+1)]\n Y = np.array([Y]).T\n X = Np2Var(X) \n Y = Np2Var(Y)\n X = X.view(BatchSize,1,-1)\n #Y = Y.view(BatchSize,1,-1)\n optimizer.zero_grad()\n # forward pass\n output = model(X)\n # calculate categorical cross entropy loss\n loss = criterion(output,Y)\n loss.backward() # backpropagation, compute gradients\n optimizer.step() # apply gradients\n Ypred = model(Xval)\n loss_test = criterion(Ypred,Yval)\n print(loss_test)\n return loss_test\n\n\n\n\n\nif __name__ == \"__main__\":\n Xall,XC = preprocessX(Xall)\n Xtest,XCt = preprocessX(Xtest)\n pca = PCA(n_components=6)\n pca.fit(Xall)\n comp = pca.components_\n Xall = pca.transform(Xall)\n lam = pca.explained_variance_ratio_\n print(lam)\n Xall,XC = preprocessX(Xall)\n time_step = 1 # rnn time step\n model = get_model(0.1)\n LR = 0.2 # learning rate\n N = np.size(Xall,0)\n BatchSize = np.floor(N/100)\n BatchSize = BatchSize.astype(np.int32)\n ValSize = 1000-1\n Xval = Xall[0:ValSize+1,:]\n Yval = Yall[0:ValSize+1]\n Xval = Np2Var(Xval)\n Yval = Np2Var(Yval)\n Xval = Xval.view(ValSize+1,1,-1)\n Yval = Yval.view(ValSize+1,1,-1)\n Xtrain0 = Xall[ValSize+1:,:]\n Ytrain0 = Yall[ValSize+1:]\n #optimizer = torch.optim.Adam(model.parameters(),lr=LR) # optimize all cnn parameters\n optimizer = torch.optim.SGD(model.parameters(),lr=LR) # optimize all cnn parameters\n optimizer = torch.optim.RMSprop(model.parameters())\n loss_func = nn.BCEWithLogitsLoss()\n #loss_func = nn.MSELoss()\n h_state = None # for initial hidden state\n model = get_model(0.1)\n #loss = train_model(model,Xtrain0,Ytrain0,Xval,Yval,10,BatchSize)\n\n Nitrs = 1000000\n e_list = []\n t_loss_list = []\n loss_list = []\n Nepochs = 10000\n \n for epoch in range(Nepochs):\n Xtrain,Ytrain = RandomizeTrainData(Xtrain0,Ytrain0,time_step)\n Ntrain = Xtrain.shape[0]/BatchSize\n Ntrain = Ntrain.astype(np.int32)\n for i in range(Ntrain):\n Xi = Xtrain[(BatchSize)*i:(BatchSize)*(i+1),:,:]\n Yi = Ytrain[(BatchSize)*i:(BatchSize)*(i+1),:,:]\n Xi = Np2Var(Xi)\n Yi = Yi[:,0,:]\n Yi = Np2Var(Yi)\n prediction = model(Xi) # rnn output\n loss = loss_func(prediction,Yi)\n optimizer.zero_grad() # clear gradients for this training step\n loss.backward() # backpropagation, compute gradients\n optimizer.step() # apply gradients\n # !! next step is important !!\n \"\"\"\n h_state = rnn.init_hidden(BatchSize)\n h_state[0].detach_()\n h_state[1].detach_()\n \"\"\"\n print(loss)\n e_list.append(epoch)\n Ypred = model(Xval)\n loss_test = loss_func(Ypred,Yval)\n t_loss_list.append(loss.data.numpy())\n loss_list.append(loss_test.data.numpy())\n print('current loss at epoch = ',epoch,': ',loss_test.data.numpy())\n if (np.absolute(loss.data.numpy()) <= 0.0005) or (epoch == 1000):\n break"
] | [
[
"torch.nn.BatchNorm1d",
"numpy.amax",
"pandas.read_csv",
"torch.nn.LSTM",
"torch.nn.Flatten",
"torch.from_numpy",
"torch.nn.Linear",
"torch.nn.BCEWithLogitsLoss",
"numpy.random.permutation",
"numpy.size",
"torch.nn.MaxPool1d",
"numpy.floor",
"torch.nn.Conv1d",
"torch.nn.ReLU",
"numpy.array",
"numpy.zeros",
"sklearn.decomposition.PCA"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [
"2.0",
"1.4",
"1.1",
"1.5",
"1.2",
"1.3"
],
"scipy": [],
"tensorflow": []
}
] |
losedavidpb/kata_ialib | [
"8c7677be0fb6394d4a77402d65fb3485900f336f"
] | [
"nnetwork/backpropagation/layer.py"
] | [
"from abc import ABC, abstractmethod\nimport numpy as np\n\nclass Layer(ABC):\n\n def __init__(self, activation, derivative_activation, num_neurons=1, num_inputs_each_neuron=1):\n self.num_neurons, self.num_inputs_each_neuron = num_neurons, num_inputs_each_neuron\n self.activation_f = {'activation': activation, 'derivative_activation': derivative_activation}\n self.last_net_input, self.last_output = 0, 0\n self.weights = None\n\n def net_input(self, p_x):\n return np.matmul(p_x, self.weights[1:, :]) + self.weights[0, :]\n\n def activation(self, net_input):\n return self.activation_f['activation'](net_input)\n\n def derivative_activation(self):\n return self.activation_f['derivative_activation'](self.last_net_input)\n\n @staticmethod\n def quantization(p_activation):\n return np.where(p_activation >= 0.5, 1, 0)\n\n @abstractmethod\n def init_weights(self):\n \"\"\" Initialize random weights for current layer \"\"\"\n pass\n\n @abstractmethod\n def predict(self, p_x):\n \"\"\" Execute prediction process for passed input values\n\n :param p_x: array of input values\n \"\"\"\n pass\n"
] | [
[
"numpy.where",
"numpy.matmul"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
angnuoli/data-preprocess | [
"7b09f17c031daeccd8feddfac3625149f60fc629"
] | [
"src/clusters/DBSCAN.py"
] | [
"from random import choice\n\nimport numpy as np\n\nfrom src.data_structure.data_structure import StaticData\n\n\nclass DBSCAN:\n \"\"\"This is DBSCAN cluster\"\"\"\n\n def __init__(self, epsilon=5, min_pts=5):\n self.epsilon = epsilon\n self.min_pts = min_pts\n self.edges = {}\n self.core_points = set()\n self.border_points = set()\n self.noise_points = set()\n\n @staticmethod\n def find_epsilon(X):\n k_distance = []\n m = X.shape[0]\n\n for i in range(m):\n for j in range(i + 1, m):\n k_distance.append(np.linalg.norm(X[i] - X[j]))\n\n k_distance = sorted(k_distance)\n StaticData.dbscan_k_distance = k_distance\n\n def preprocess(self, X):\n \"\"\"\n This method is to initialize the distance matrix between each point.\n The matrix is formatted as dict(dict()).\n\n :param X:\n :return:\n \"\"\"\n\n m = X.shape[0]\n\n print(\"Compute the distance matrix between each point...\")\n if len(StaticData.edges) == 0:\n edges = {}\n for i in range(m):\n edges[i] = {}\n\n gap = m / 10\n count = gap\n k = 0\n for i in range(m):\n count -= 1\n if count <= 0 and k < 10:\n k += 1\n count = gap\n print(\"{}% is finished\".format(k * 10))\n for j in range(i + 1, m):\n edges[j][i] = edges[i][j] = np.linalg.norm(X[i] - X[j])\n\n StaticData.edges = edges\n\n edges = {}\n\n for i in range(m):\n edges[i] = {}\n\n print(\"Get the core points set...\")\n for i in range(m):\n for j in range(i + 1, m):\n if StaticData.edges[i][j] <= self.epsilon:\n edges[j][i] = edges[i][j] = StaticData.edges[i][j]\n\n if len(edges[i].keys()) >= self.min_pts:\n self.core_points.add(i)\n\n self.edges = edges\n return edges\n\n @staticmethod\n def purity_in_class(index, labels):\n freq = {}\n\n for i in index:\n for label in labels[i]:\n if label not in freq:\n freq[label] = 0\n freq[label] += 1\n\n p = 0.0\n label_ = ''\n for label in freq.keys():\n if p < freq[label]:\n p = freq[label]\n label_ = label\n\n StaticData.dbscan_labels.append(label_)\n return p / len(index)\n\n def calculate_purity(self, clusters, y):\n purity = 0.0\n total = 0.0\n\n for i, classes in clusters.items():\n m = float(len(classes))\n total += m\n\n purity += m * self.purity_in_class(clusters[i], y)\n\n return purity / total\n\n def fit(self, X):\n matrix = self.preprocess(X)\n core_points = set(self.core_points)\n k = 0\n m = X.shape[0]\n unvisited = set()\n for i in range(m):\n unvisited.add(i)\n clusters = {}\n\n print(\"Generate clusters...\")\n while len(core_points) != 0:\n k_core_point = choice(list(core_points))\n cluster_k = set()\n cur_core_points_queue = set()\n\n cur_core_points_queue.add(k_core_point)\n core_points.remove(k_core_point)\n cluster_k.add(k_core_point)\n unvisited.remove(k_core_point)\n\n while len(cur_core_points_queue) != 0:\n core_point = choice(list(cur_core_points_queue))\n cur_core_points_queue.remove(core_point)\n neighbors = unvisited & matrix[core_point].keys()\n cluster_k = cluster_k | neighbors\n unvisited = unvisited - neighbors\n cur_core_points_queue = cur_core_points_queue | (neighbors & core_points)\n\n clusters[k] = cluster_k\n k += 1\n core_points = core_points - cluster_k\n\n return clusters\n"
] | [
[
"numpy.linalg.norm"
]
] | [
{
"matplotlib": [],
"numpy": [
"1.10",
"1.12",
"1.11",
"1.19",
"1.24",
"1.13",
"1.16",
"1.9",
"1.18",
"1.23",
"1.21",
"1.22",
"1.20",
"1.7",
"1.15",
"1.14",
"1.17",
"1.8"
],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
CheRuisiBesares/vocal-remover | [
"cf00718b0073083bd0ebd8ec6e2b1541f286ee14"
] | [
"train.py"
] | [
"import argparse\nfrom datetime import datetime\nimport json\nimport logging\nimport os\nimport random\n\nimport numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.utils.data\n\nfrom lib import dataset\nfrom lib import nets\nfrom lib import spec_utils\n\n\ndef setup_logger(name, logfile='LOGFILENAME.log'):\n logger = logging.getLogger(name)\n logger.setLevel(logging.DEBUG)\n logger.propagate = False\n\n fh = logging.FileHandler(logfile, encoding='utf8')\n fh.setLevel(logging.DEBUG)\n fh_formatter = logging.Formatter(\n '%(asctime)s - %(levelname)s - %(message)s')\n fh.setFormatter(fh_formatter)\n\n sh = logging.StreamHandler()\n sh.setLevel(logging.INFO)\n\n logger.addHandler(fh)\n logger.addHandler(sh)\n\n return logger\n\n\ndef train_epoch(dataloader, model, device, optimizer, accumulation_steps):\n model.train()\n sum_loss = 0\n crit = nn.L1Loss()\n\n for itr, (X_batch, y_batch) in enumerate(dataloader):\n X_batch = X_batch.to(device)\n y_batch = y_batch.to(device)\n\n pred, aux = model(X_batch)\n\n loss_main = crit(pred * X_batch, y_batch)\n loss_aux = crit(aux * X_batch, y_batch)\n\n loss = loss_main * 0.8 + loss_aux * 0.2\n accum_loss = loss / accumulation_steps\n accum_loss.backward()\n\n if (itr + 1) % accumulation_steps == 0:\n optimizer.step()\n model.zero_grad()\n\n sum_loss += loss.item() * len(X_batch)\n\n # the rest batch\n if (itr + 1) % accumulation_steps != 0:\n optimizer.step()\n model.zero_grad()\n\n return sum_loss / len(dataloader.dataset)\n\n\ndef validate_epoch(dataloader, model, device):\n model.eval()\n sum_loss = 0\n crit = nn.L1Loss()\n\n with torch.no_grad():\n for X_batch, y_batch in dataloader:\n X_batch = X_batch.to(device)\n y_batch = y_batch.to(device)\n\n pred = model.predict(X_batch)\n\n y_batch = spec_utils.crop_center(y_batch, pred)\n loss = crit(pred, y_batch)\n\n sum_loss += loss.item() * len(X_batch)\n\n return sum_loss / len(dataloader.dataset)\n\n\ndef main():\n p = argparse.ArgumentParser()\n p.add_argument('--gpu', '-g', type=int, default=-1)\n p.add_argument('--seed', '-s', type=int, default=2019)\n p.add_argument('--sr', '-r', type=int, default=44100)\n p.add_argument('--hop_length', '-H', type=int, default=1024)\n p.add_argument('--n_fft', '-f', type=int, default=2048)\n p.add_argument('--dataset', '-d', required=True)\n p.add_argument('--split_mode', '-S', type=str, choices=['random', 'subdirs'], default='random')\n p.add_argument('--learning_rate', '-l', type=float, default=0.001)\n p.add_argument('--lr_min', type=float, default=0.0001)\n p.add_argument('--lr_decay_factor', type=float, default=0.9)\n p.add_argument('--lr_decay_patience', type=int, default=6)\n p.add_argument('--batchsize', '-B', type=int, default=4)\n p.add_argument('--accumulation_steps', '-A', type=int, default=1)\n p.add_argument('--cropsize', '-C', type=int, default=256)\n p.add_argument('--patches', '-p', type=int, default=16)\n p.add_argument('--val_rate', '-v', type=float, default=0.2)\n p.add_argument('--val_filelist', '-V', type=str, default=None)\n p.add_argument('--val_batchsize', '-b', type=int, default=6)\n p.add_argument('--val_cropsize', '-c', type=int, default=256)\n p.add_argument('--num_workers', '-w', type=int, default=6)\n p.add_argument('--epoch', '-E', type=int, default=200)\n p.add_argument('--reduction_rate', '-R', type=float, default=0.0)\n p.add_argument('--reduction_level', '-L', type=float, default=0.2)\n p.add_argument('--mixup_rate', '-M', type=float, default=0.0)\n p.add_argument('--mixup_alpha', '-a', type=float, default=1.0)\n p.add_argument('--pretrained_model', '-P', type=str, default=None)\n p.add_argument('--debug', action='store_true')\n args = p.parse_args()\n\n logger.debug(vars(args))\n\n random.seed(args.seed)\n np.random.seed(args.seed)\n torch.manual_seed(args.seed)\n\n val_filelist = []\n if args.val_filelist is not None:\n with open(args.val_filelist, 'r', encoding='utf8') as f:\n val_filelist = json.load(f)\n\n train_filelist, val_filelist = dataset.train_val_split(\n dataset_dir=args.dataset,\n split_mode=args.split_mode,\n val_rate=args.val_rate,\n val_filelist=val_filelist\n )\n\n if args.debug:\n logger.info('### DEBUG MODE')\n train_filelist = train_filelist[:1]\n val_filelist = val_filelist[:1]\n elif args.val_filelist is None and args.split_mode == 'random':\n with open('val_{}.json'.format(timestamp), 'w', encoding='utf8') as f:\n json.dump(val_filelist, f, ensure_ascii=False)\n\n for i, (X_fname, y_fname) in enumerate(val_filelist):\n logger.info('{} {} {}'.format(i + 1, os.path.basename(X_fname), os.path.basename(y_fname)))\n\n device = torch.device('cpu')\n model = nets.CascadedNet(args.n_fft)\n if args.pretrained_model is not None:\n model.load_state_dict(torch.load(args.pretrained_model, map_location=device))\n if torch.cuda.is_available() and args.gpu >= 0:\n device = torch.device('cuda:{}'.format(args.gpu))\n model.to(device)\n\n optimizer = torch.optim.Adam(\n filter(lambda p: p.requires_grad, model.parameters()),\n lr=args.learning_rate\n )\n\n scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(\n optimizer,\n factor=args.lr_decay_factor,\n patience=args.lr_decay_patience,\n threshold=1e-6,\n min_lr=args.lr_min,\n verbose=True\n )\n\n bins = args.n_fft // 2 + 1\n freq_to_bin = 2 * bins / args.sr\n unstable_bins = int(200 * freq_to_bin)\n stable_bins = int(22050 * freq_to_bin)\n reduction_weight = np.concatenate([\n np.linspace(0, 1, unstable_bins, dtype=np.float32)[:, None],\n np.linspace(1, 0, stable_bins - unstable_bins, dtype=np.float32)[:, None],\n np.zeros((bins - stable_bins, 1), dtype=np.float32),\n ], axis=0) * args.reduction_level\n\n training_set = dataset.make_training_set(\n filelist=train_filelist,\n sr=args.sr,\n hop_length=args.hop_length,\n n_fft=args.n_fft\n )\n\n train_dataset = dataset.VocalRemoverTrainingSet(\n training_set * args.patches,\n cropsize=args.cropsize,\n reduction_rate=args.reduction_rate,\n reduction_weight=reduction_weight,\n mixup_rate=args.mixup_rate,\n mixup_alpha=args.mixup_alpha\n )\n\n train_dataloader = torch.utils.data.DataLoader(\n dataset=train_dataset,\n batch_size=args.batchsize,\n shuffle=True,\n num_workers=args.num_workers\n )\n\n patch_list = dataset.make_validation_set(\n filelist=val_filelist,\n cropsize=args.val_cropsize,\n sr=args.sr,\n hop_length=args.hop_length,\n n_fft=args.n_fft,\n offset=model.offset\n )\n\n val_dataset = dataset.VocalRemoverValidationSet(\n patch_list=patch_list\n )\n\n val_dataloader = torch.utils.data.DataLoader(\n dataset=val_dataset,\n batch_size=args.val_batchsize,\n shuffle=False,\n num_workers=args.num_workers\n )\n\n log = []\n best_loss = np.inf\n for epoch in range(args.epoch):\n logger.info('# epoch {}'.format(epoch))\n train_loss = train_epoch(train_dataloader, model, device, optimizer, args.accumulation_steps)\n val_loss = validate_epoch(val_dataloader, model, device)\n\n logger.info(\n ' * training loss = {:.6f}, validation loss = {:.6f}'\n .format(train_loss, val_loss)\n )\n\n scheduler.step(val_loss)\n\n if val_loss < best_loss:\n best_loss = val_loss\n logger.info(' * best validation loss')\n model_path = 'models/model_iter{}.pth'.format(epoch)\n torch.save(model.state_dict(), model_path)\n\n log.append([train_loss, val_loss])\n with open('loss_{}.json'.format(timestamp), 'w', encoding='utf8') as f:\n json.dump(log, f, ensure_ascii=False)\n\n\nif __name__ == '__main__':\n timestamp = datetime.now().strftime('%Y%m%d%H%M%S')\n logger = setup_logger(__name__, 'train_{}.log'.format(timestamp))\n\n try:\n main()\n except Exception as e:\n logger.exception(e)\n"
] | [
[
"torch.optim.lr_scheduler.ReduceLROnPlateau",
"numpy.random.seed",
"torch.load",
"numpy.linspace",
"torch.manual_seed",
"torch.utils.data.DataLoader",
"torch.no_grad",
"torch.cuda.is_available",
"torch.device",
"numpy.zeros",
"torch.nn.L1Loss"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
reinforcementdriving/fiftyone | [
"3db489a1440990858247afd52a8c005415d42d82"
] | [
"fiftyone/core/eta_utils.py"
] | [
"\"\"\"\nUtilities for interfacing with the\n`ETA library <https://github.com/voxel51/eta>`_.\n\n| Copyright 2017-2021, Voxel51, Inc.\n| `voxel51.com <https://voxel51.com/>`_\n|\n\"\"\"\nfrom collections import defaultdict\nimport itertools\nimport warnings\n\nimport numpy as np\n\nimport eta.core.data as etad\nimport eta.core.frames as etaf\nimport eta.core.image as etai\nimport eta.core.keypoints as etak\nimport eta.core.learning as etal\nimport eta.core.objects as etao\nimport eta.core.polylines as etap\nimport eta.core.utils as etau\nimport eta.core.video as etav\n\nimport fiftyone.core.labels as fol\nimport fiftyone.core.models as fom\n\n\nclass ETAModelConfig(fom.ModelConfig):\n \"\"\"Meta-config class that encapsulates the configuration of an\n `eta.core.learning.Model` that is to be run via the :class:`ETAModel`\n wrapper.\n\n Example::\n\n import fiftyone.core.models as fom\n\n model = fom.load_model({\n \"type\": \"fiftyone.core.eta_utils.ETAModel\",\n \"config\": {\n \"type\": \"eta.detectors.YOLODetector\",\n \"config\": {\n \"model_name\": \"yolo-v2-coco\"\n }\n }\n })\n\n Args:\n type: the fully-qualified class name of the\n :class:`fiftyone.core.models.Model` subclass, which must be\n :class:`ETAModel` or a subclass of it\n config: a dict containing the ``eta.core.learning.ModelConfig`` for the\n ETA model\n \"\"\"\n\n @property\n def confidence_thresh(self):\n \"\"\"The confidence threshold of the underlying ``eta.core.model.Model``.\n\n Note that this may not be defined for some models.\n \"\"\"\n return self.config.confidence_thresh\n\n @confidence_thresh.setter\n def confidence_thresh(self, confidence_thresh):\n self.config.confidence_thresh = confidence_thresh\n\n\nclass ETAModel(fom.Model, fom.EmbeddingsMixin, fom.LogitsMixin):\n \"\"\"Wrapper for running an ``eta.core.learning.Model`` model.\n\n Args:\n config: an :class:`ETAModelConfig`\n \"\"\"\n\n def __init__(self, config, _model=None):\n if _model is None:\n _model = config.build() # build the ETA model\n\n self.config = config\n self._model = _model\n fom.LogitsMixin.__init__(self)\n\n def __enter__(self):\n self._model.__enter__()\n return self\n\n def __exit__(self, *args):\n self._model.__exit__(*args)\n\n @property\n def ragged_batches(self):\n try:\n return self._model.ragged_batches\n except AttributeError:\n return True\n\n @property\n def transforms(self):\n try:\n return self._model.transforms\n except AttributeError:\n return None\n\n @property\n def has_logits(self):\n return (\n isinstance(self._model, etal.ExposesProbabilities)\n and isinstance(self._model, etal.Classifier)\n and self._model.exposes_probabilities\n )\n\n @property\n def has_embeddings(self):\n return (\n isinstance(self._model, etal.ExposesFeatures)\n and isinstance(self._model, etal.Classifier)\n and self._model.exposes_features\n )\n\n def _ensure_embeddings(self):\n if not self.has_embeddings:\n raise ValueError(\"This model instance does not expose embeddings\")\n\n def get_embeddings(self):\n self._ensure_embeddings()\n embeddings = self._model.get_features()\n embeddings = _squeeze_extra_unit_dims(embeddings)\n return embeddings.astype(float, copy=False)\n\n def embed(self, arg):\n self._ensure_embeddings()\n self.predict(arg)\n return self.get_embeddings()\n\n def embed_all(self, args):\n self._ensure_embeddings()\n\n if isinstance(self._model, etal.ImageClassifier):\n self._model.predict_all(args)\n return self.get_embeddings()\n\n if isinstance(self._model, etal.ObjectDetector):\n self._model.detect_all(args)\n return self.get_embeddings()\n\n if isinstance(self._model, etal.ImageSemanticSegmenter):\n self._model.segment_all(args)\n return self.get_embeddings()\n\n return np.concatenate(tuple(self.embed(arg) for arg in args))\n\n def predict(self, arg):\n if isinstance(self._model, etal.ImageClassifier):\n eta_labels = self._model.predict(arg)\n elif isinstance(self._model, etal.VideoFramesClassifier):\n eta_labels = self._model.predict(arg)\n elif isinstance(self._model, etal.VideoClassifier):\n eta_labels = self._model.predict(arg)\n elif isinstance(self._model, etal.Classifier):\n eta_labels = self._model.predict(arg)\n elif isinstance(self._model, etal.ObjectDetector):\n eta_labels = self._model.detect(arg)\n elif isinstance(self._model, etal.VideoFramesObjectDetector):\n eta_labels = self._model.detect(arg)\n elif isinstance(self._model, etal.VideoObjectDetector):\n eta_labels = self._model.detect(arg)\n elif isinstance(self._model, etal.Detector):\n eta_labels = self._model.detect(arg)\n elif isinstance(self._model, etal.ImageSemanticSegmenter):\n eta_labels = self._model.segment(arg)\n elif isinstance(self._model, etal.VideoSemanticSegmenter):\n eta_labels = self._model.segment(arg)\n elif isinstance(self._model, etal.SemanticSegmenter):\n eta_labels = self._model.segment(arg)\n elif isinstance(self._model, etal.ImageModel):\n eta_labels = self._model.process(arg)\n elif isinstance(self._model, etal.VideoModel):\n eta_labels = self._model.process(arg)\n else:\n raise ValueError(\n \"Unsupported model type '%s'\" % self._model.__class__\n )\n\n eta_labels = self._parse_predictions(eta_labels)\n\n label = parse_eta_labels(eta_labels)\n\n if self.has_logits and self.store_logits:\n # num_preds x num_classes\n logits = np.log(self._model.get_probabilities()[0])\n _add_logits(label, logits)\n\n return label\n\n def predict_all(self, args):\n if isinstance(self._model, etal.ImageClassifier):\n eta_labels_batch = self._model.predict_all(args)\n elif isinstance(self._model, etal.ObjectDetector):\n eta_labels_batch = self._model.detect_all(args)\n elif isinstance(self._model, etal.ImageSemanticSegmenter):\n eta_labels_batch = self._model.segment_all(args)\n else:\n return [self.predict(arg) for arg in args]\n\n eta_labels_batch = self._parse_predictions(eta_labels_batch)\n\n labels = [parse_eta_labels(el) for el in eta_labels_batch]\n\n if self.has_logits and self.store_logits:\n # num_images x num_preds x num_classes\n logits = np.log(self._model.get_probabilities())\n\n for label, _logits in zip(labels, logits):\n _add_logits(label, _logits)\n\n return labels\n\n def _parse_predictions(self, eta_labels_or_batch):\n if (\n not isinstance(self._model, etal.Classifier)\n or self._model.is_multilabel\n ):\n return eta_labels_or_batch\n\n if isinstance(eta_labels_or_batch, list):\n return [\n attrs[0] if attrs else None for attrs in eta_labels_or_batch\n ]\n\n if not eta_labels_or_batch:\n return None\n\n return eta_labels_or_batch[0]\n\n @classmethod\n def from_eta_model(cls, model):\n \"\"\"Builds an :class:`ETAModel` for running the provided\n ``eta.core.learning.Model`` instance.\n\n Args:\n model: an ``eta.core.learning.Model`` instance\n\n Returns:\n an :class:`ETAModel`\n \"\"\"\n return cls(model.config, _model=model)\n\n\ndef parse_eta_labels(eta_labels):\n \"\"\"Parses the ``eta.core.labels.Labels`` instance and returns the\n corresponding :class:`fiftyone.core.labels.Label` instance(s).\n\n The table below summarizes the conversions that are performed:\n\n .. table::\n\n +-----------------------------------------------+-----------------------------------------------+\n | Input type | Output type |\n +===============================================+===============================================+\n | ``eta.core.data.Attribute`` | :class:`fiftyone.core.labels.Classification` |\n +-----------------------------------------------+-----------------------------------------------+\n | ``eta.core.data.AttributeContainer`` | :class:`fiftyone.core.labels.Classifications` |\n +-----------------------------------------------+-----------------------------------------------+\n | ``eta.core.objects.DetectedObject`` | :class:`fiftyone.core.labels.Detection` |\n +-----------------------------------------------+-----------------------------------------------+\n | ``eta.core.objects.DetectedObjectContainer`` | :class:`fiftyone.core.labels.Detections` |\n +-----------------------------------------------+-----------------------------------------------+\n | ``eta.core.polylines.Polyline`` | :class:`fiftyone.core.labels.Polyline` |\n +-----------------------------------------------+-----------------------------------------------+\n | ``eta.core.polylines.PolylineContainer`` | :class:`fiftyone.core.labels.Polylines` |\n +-----------------------------------------------+-----------------------------------------------+\n | ``eta.core.keypoints.Keypoints`` | :class:`fiftyone.core.labels.Keypoint` |\n +-----------------------------------------------+-----------------------------------------------+\n | ``eta.core.keypoints.KeypointsContainer`` | :class:`fiftyone.core.labels.Keypoints` |\n +-----------------------------------------------+-----------------------------------------------+\n | ``np.ndarray`` | :class:`fiftyone.core.labels.Segmentation` |\n +-----------------------------------------------+-----------------------------------------------+\n | ``eta.core.image.ImageLabels`` | a dictionary mapping field names to |\n | | :class:`fiftyone.core.labels.Label` instances |\n +-----------------------------------------------+-----------------------------------------------+\n | ``eta.core.video.VideoLabels`` | a ``frames`` dict mapping frame numbers |\n | | to dictionaries of frame labels |\n +-----------------------------------------------+-----------------------------------------------+\n\n Args:\n eta_labels: an ````eta.core.labels.Labels`` instance\n\n Returns:\n the FiftyOne labels according to the table above\n \"\"\"\n if isinstance(eta_labels, etad.AttributeContainer):\n label = fol.Classifications.from_attributes(eta_labels)\n elif isinstance(eta_labels, etad.Attribute):\n label = fol.Classification.from_attribute(eta_labels)\n elif isinstance(eta_labels, etao.DetectedObjectContainer):\n label = fol.Detections.from_detected_objects(eta_labels)\n elif isinstance(eta_labels, etao.DetectedObject):\n label = fol.Detection.from_detected_object(eta_labels)\n elif isinstance(eta_labels, etap.PolylineContainer):\n label = fol.Polylines.from_eta_polylines(eta_labels)\n elif isinstance(eta_labels, etap.Polyline):\n label = fol.Polyline.from_eta_polyline(eta_labels)\n elif isinstance(eta_labels, etak.KeypointsContainer):\n label = fol.Keypoints.from_eta_keypoints(eta_labels)\n elif isinstance(eta_labels, etak.Keypoints):\n label = fol.Keypoint.from_eta_keypoints(eta_labels)\n elif isinstance(eta_labels, etav.VideoLabels):\n label = load_video_labels(eta_labels)\n elif isinstance(eta_labels, etaf.FrameLabels):\n label = load_image_labels(eta_labels)\n elif isinstance(eta_labels, np.ndarray):\n label = fol.Segmentation.from_mask(eta_labels)\n elif eta_labels is None:\n label = None\n else:\n raise ValueError(\n \"Unsupported ETA label type '%s'\" % eta_labels.__class__\n )\n\n return label\n\n\ndef load_image_labels(\n image_labels_or_path,\n prefix=None,\n labels_dict=None,\n multilabel=False,\n skip_non_categorical=False,\n):\n \"\"\"Loads the ``eta.core.image.ImageLabels`` or\n ``eta.core.frames.FrameLabels`` into a dictionary of labels.\n\n Provide ``labels_dict`` if you want to customize which components of\n the labels are expanded. Otherwise, all labels are expanded as\n explained below.\n\n If ``multilabel`` is False, frame attributes will be stored in separate\n :class:`Classification` fields with names ``prefix + attr.name``.\n\n If ``multilabel`` if True, all frame attributes will be stored in a\n :class:`Classifications` field called ``prefix + \"attributes\"``.\n\n Objects are expanded into fields with names ``prefix + obj.name``, or\n ``prefix + \"detections\"`` for objects that do not have their ``name``\n field populated.\n\n Polylines are expanded into fields with names\n ``prefix + polyline.name``, or ``prefix + \"polylines\"`` for polylines\n that do not have their ``name`` field populated.\n\n Keypoints are expanded into fields with names\n ``prefix + keypoints.name``, or ``prefix + \"keypoints\"`` for keypoints\n that do not have their ``name`` field populated.\n\n Segmentation masks are expanded into a field with name ``prefix + \"mask\"``.\n\n Args:\n image_labels_or_path: can be a ``eta.core.image.ImageLabels`` instance,\n a ``eta.core.frames.FrameLabels`` instance, a serialized dict\n representation of either, or the path to either on disk\n prefix (None): a string prefix to prepend to each field name in the\n output dict\n labels_dict (None): a dictionary mapping names of labels to keys to\n assign them in the output dictionary\n multilabel (False): whether to store frame attributes in a single\n :class:`Classifications` instance\n skip_non_categorical (False): whether to skip non-categorical\n frame attributes (True) or cast them to strings (False)\n\n Returns:\n a dict mapping label names to :class:`fiftyone.core.labels.ImageLabel`\n instances\n \"\"\"\n if etau.is_str(image_labels_or_path):\n frame_labels = etaf.FrameLabels.from_json(image_labels_or_path)\n elif isinstance(image_labels_or_path, dict):\n frame_labels = etaf.FrameLabels.from_dict(image_labels_or_path)\n else:\n frame_labels = image_labels_or_path\n\n if frame_labels is None:\n return None\n\n if labels_dict is not None:\n return _expand_with_labels_dict(\n frame_labels, labels_dict, multilabel, skip_non_categorical\n )\n\n return _expand_with_prefix(\n frame_labels, prefix, multilabel, skip_non_categorical\n )\n\n\ndef to_image_labels(labels):\n \"\"\"Converts the image label(s) to ``eta.core.image.ImageLabels`` format.\n\n Args:\n labels: can be a :class:`fiftyone.core.labels.ImageLabel` instance or\n a dictionary mapping names to\n :class:`fiftyone.core.labels.ImageLabel` instances\n\n Returns:\n an ``eta.core.image.ImageLabels`` instance\n \"\"\"\n image_labels = etai.ImageLabels()\n\n if labels is None:\n return image_labels\n\n if not isinstance(labels, dict):\n labels = {labels: labels}\n\n for name, label in labels.items():\n if isinstance(label, fol.ImageLabel):\n image_labels.merge_labels(label.to_image_labels(name=name))\n elif label is not None:\n msg = \"Ignoring unsupported label type '%s'\" % label.__class__\n warnings.warn(msg)\n\n return image_labels\n\n\ndef load_video_labels(\n video_labels_or_path,\n prefix=None,\n labels_dict=None,\n multilabel=False,\n skip_non_categorical=False,\n):\n \"\"\"Loads the ``eta.core.video.VideoLabels`` into a frame labels dictionary.\n\n Args:\n video_labels_or_path: can be a ``eta.core.video.VideoLabels`` instance,\n a serialized dict representation of one, or the path to one on disk\n prefix (None): a string prefix to prepend to each label name in the\n expanded frame label dictionaries\n labels_dict (None): a dictionary mapping names of attributes/objects\n in the frame labels to field names into which to expand them\n multilabel (False): whether to store frame attributes in a single\n :class:`fiftyone.core.labels.Classifications` instance\n skip_non_categorical (False): whether to skip non-categorical frame\n attributes (True) or cast them to strings (False)\n\n Returns:\n a dictionary mapping frame numbers to dictionaries that map label\n fields to :class:`fiftyone.core.labels.Label` instances for each video\n frame\n \"\"\"\n if etau.is_str(video_labels_or_path):\n video_labels = etav.VideoLabels.from_json(video_labels_or_path)\n elif isinstance(video_labels_or_path, dict):\n video_labels = etav.VideoLabels.from_dict(video_labels_or_path)\n else:\n video_labels = video_labels_or_path\n\n if video_labels is None:\n return None\n\n frames = {}\n for frame_number in video_labels:\n frames[frame_number] = load_image_labels(\n video_labels[frame_number],\n prefix=prefix,\n labels_dict=labels_dict,\n multilabel=multilabel,\n skip_non_categorical=skip_non_categorical,\n )\n\n return frames\n\n\ndef to_video_labels(frames):\n \"\"\"Converts the frame labels dictionary to ``eta.core.video.VideoLabels``\n format.\n\n Args:\n frames: a dictionary mapping frame numbers to\n :class:`fiftyone.core.frame.Frame` instances or dictionaries\n mapping field names to :class:`fiftyone.core.labels.ImageLabel`\n instances\n\n Returns:\n a ``eta.core.video.VideoLabels`` instance\n \"\"\"\n video_labels = etav.VideoLabels()\n\n if frames is None:\n return video_labels\n\n for frame_number, frame in frames.items():\n video_labels[frame_number] = _to_frame_labels(frame, frame_number)\n\n return video_labels\n\n\ndef _to_frame_labels(frame, frame_number):\n frame_labels = etav.VideoFrameLabels(frame_number)\n\n for name, label in frame.items():\n if isinstance(label, fol.ImageLabel):\n frame_labels.merge_labels(label.to_image_labels(name=name))\n elif label is not None:\n msg = \"Ignoring unsupported label type '%s'\" % label.__class__\n warnings.warn(msg)\n\n return frame_labels\n\n\ndef _expand_with_prefix(\n frame_labels, prefix, multilabel, skip_non_categorical\n):\n if prefix is None:\n prefix = \"\"\n\n labels = {}\n\n #\n # Classifications\n #\n\n if multilabel:\n # Store frame attributes as multilabels\n # pylint: disable=no-member\n labels[prefix + \"attributes\"] = fol.Classifications.from_attributes(\n frame_labels.attrs, skip_non_categorical=skip_non_categorical,\n )\n else:\n # Store each frame attribute separately\n for attr in frame_labels.attrs: # pylint: disable=no-member\n if skip_non_categorical and not etau.is_str(attr.value):\n continue\n\n labels[prefix + attr.name] = fol.Classification.from_attribute(\n attr\n )\n\n #\n # Detections\n #\n\n objects_map = defaultdict(etao.DetectedObjectContainer)\n\n for dobj in frame_labels.objects:\n objects_map[prefix + (dobj.name or \"detections\")].add(dobj)\n\n for name, objects in objects_map.items():\n # pylint: disable=no-member\n labels[name] = fol.Detections.from_detected_objects(objects)\n\n #\n # Polylines\n #\n\n polylines_map = defaultdict(etap.PolylineContainer)\n\n for polyline in frame_labels.polylines:\n polylines_map[prefix + (polyline.name or \"polylines\")].add(polyline)\n\n for name, polylines in polylines_map.items():\n # pylint: disable=no-member\n labels[name] = fol.Polylines.from_eta_polylines(polylines)\n\n #\n # Keypoints\n #\n\n keypoints_map = defaultdict(etak.KeypointsContainer)\n\n for keypoints in frame_labels.keypoints:\n keypoints_map[prefix + (keypoints.name or \"keypoints\")].add(keypoints)\n\n for name, keypoints in keypoints_map.items():\n # pylint: disable=no-member\n labels[name] = fol.Keypoints.from_eta_keypoints(keypoints)\n\n #\n # Segmentations\n #\n\n if frame_labels.has_mask:\n labels[prefix + \"mask\"] = fol.Segmentation.from_mask(frame_labels.mask)\n\n return labels\n\n\ndef _expand_with_labels_dict(\n frame_labels, labels_dict, multilabel, skip_non_categorical\n):\n labels = {}\n\n #\n # Classifications\n #\n\n if multilabel:\n # Store frame attributes as multilabels\n attrs_map = defaultdict(etad.AttributeContainer)\n for attr in frame_labels.attrs:\n if attr.name not in labels_dict:\n continue\n\n attrs_map[labels_dict[attr.name]].add(attr)\n\n for name, attrs in attrs_map.items():\n labels[name] = fol.Classifications.from_attributes(\n attrs, skip_non_categorical=skip_non_categorical\n )\n else:\n # Store each frame attribute separately\n for attr in frame_labels.attrs: # pylint: disable=no-member\n if skip_non_categorical and not etau.is_str(attr.value):\n continue\n\n if attr.name not in labels_dict:\n continue\n\n labels[labels_dict[attr.name]] = fol.Classification.from_attribute(\n attr\n )\n\n #\n # Detections\n #\n\n objects_map = defaultdict(etao.DetectedObjectContainer)\n\n for dobj in frame_labels.objects:\n if dobj.name not in labels_dict:\n continue\n\n objects_map[labels_dict[dobj.name]].add(dobj)\n\n for name, objects in objects_map.items():\n # pylint: disable=no-member\n labels[name] = fol.Detections.from_detected_objects(objects)\n\n #\n # Polylines\n #\n\n polylines_map = defaultdict(etap.PolylineContainer)\n\n for polyline in frame_labels.polylines:\n if polyline.name not in labels_dict:\n continue\n\n polylines_map[labels_dict[polyline.name]].add(polyline)\n\n for name, polylines in polylines_map.items():\n # pylint: disable=no-member\n labels[name] = fol.Polylines.from_eta_polylines(polylines)\n\n #\n # Keypoints\n #\n\n keypoints_map = defaultdict(etak.KeypointsContainer)\n\n for keypoints in frame_labels.keypoints:\n if keypoints.name not in labels_dict:\n continue\n\n keypoints_map[labels_dict[keypoints.name]].add(keypoints)\n\n for name, keypoints in keypoints_map.items():\n # pylint: disable=no-member\n labels[name] = fol.Keypoints.from_eta_keypoints(keypoints)\n\n #\n # Segmentations\n #\n\n if frame_labels.has_mask and \"mask\" in labels_dict:\n labels[\"mask\"] = fol.Segmentation.from_mask(frame_labels.mask)\n\n return labels\n\n\ndef _squeeze_extra_unit_dims(embeddings):\n dims = embeddings.shape[1:]\n extra_axes = tuple(ax for ax, dim in enumerate(dims, 1) if dim == 1)\n\n if len(extra_axes) == len(dims):\n extra_axes = extra_axes[1:]\n\n if extra_axes:\n return np.squeeze(embeddings, axis=extra_axes)\n\n return embeddings\n\n\ndef _add_logits(label, logits):\n if isinstance(label, fol.Classification):\n label.logits = logits[0]\n elif isinstance(label, fol.Classifications):\n for c, l in zip(label.classifications, logits):\n c.logits = l\n elif label is not None:\n msg = \"Cannot store logits on label type '%s'\" % label.__class__\n warnings.warn(msg)\n"
] | [
[
"numpy.squeeze"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
jnsebgosselin/help | [
"f0194a96ba7e1474fe1864d79447ee20cee949ec"
] | [
"pyhelp/scripts/produce_meteo_maps.py"
] | [
"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Feb 27 10:54:25 2018\n@author: jsgosselin\n\"\"\"\n\n# ---- Standard Library Imports\n\nfrom itertools import product\nimport os.path as osp\nimport os\n\n# ---- Third Party Imports\n\nimport netCDF4\nfrom geopandas import GeoDataFrame\nimport pandas as pd\nfrom shapely.geometry import Point, Polygon\nimport numpy as np\n\ndirpath_netcdf = \"D:/MeteoGrilleDaily\"\n\n# %% Get lat/lon from the netCDF\n\nfilename = osp.join(dirpath_netcdf, 'GCQ_v2_2000.nc')\nnetcdf_dset = netCDF4.Dataset(filename, 'r+')\n\nlat = np.array(netcdf_dset['lat'])\nlon = np.array(netcdf_dset['lon'])\n\nnetcdf_dset.close()\n\n# %% Read the weather data from the InfoClimat grid\n\nstack_precip = []\nstack_tasmax = []\nstack_tasmin = []\nnyear = 0\nfor year in range(2000, 2015):\n print(\"\\rProcessing year %d\" % year, end=' ')\n filename = osp.join(dirpath_netcdf, 'GCQ_v2_%d.nc' % year)\n netcdf_dset = netCDF4.Dataset(filename, 'r+')\n\n stack_precip.append(np.array(netcdf_dset['pr']))\n stack_tasmax.append(np.array(netcdf_dset['tasmax']))\n stack_tasmin.append(np.array(netcdf_dset['tasmin']))\n\n netcdf_dset.close()\n nyear += 1\nprint('')\n\ndaily_precip = np.vstack(stack_precip)\ndaily_tasmax = np.vstack(stack_tasmax)\ndaily_tasmin = np.vstack(stack_tasmin)\ndaily_tasavg = (daily_tasmax + daily_tasmin) / 2\n\nyearly_avg_precip = np.sum(daily_precip, axis=0) / nyear\nyearly_avg_tasavg = np.average(daily_tasavg, axis=0)\nyearly_avg_tasmax = np.average(daily_tasmax, axis=0)\nyearly_avg_tasmin = np.average(daily_tasmin, axis=0)\n\n# %% Create a grid\n\nNp = len(lat) * len(lon)\n\ngeometry = []\narr_yearly_avg_precip = np.zeros(Np)\narr_avg_yearly_tasavg = np.zeros(Np)\narr_avg_yearly_tasmax = np.zeros(Np)\narr_avg_yearly_tasmin = np.zeros(Np)\ni = 0\ndx = dy = 0.1/2\nfor j, k in product(range(len(lat)), range(len(lon))):\n print(\"\\rProcessing cell %d of %d\" % (i, Np), end=' ')\n point = Point((lon[k], lat[j]))\n # polygon = Polygon([(lon[k]-dx, lat[j]-dy),\n # (lon[k]-dx, lat[j]+dy),\n # (lon[k]+dx, lat[j]+dy),\n # (lon[k]+dx, lat[j]-dy)])\n geometry.append(point)\n\n arr_yearly_avg_precip[i] = yearly_avg_precip[j, k]\n arr_avg_yearly_tasavg[i] = yearly_avg_tasavg[j, k]\n arr_avg_yearly_tasmax[i] = yearly_avg_tasmax[j, k]\n arr_avg_yearly_tasmin[i] = yearly_avg_tasmin[j, k]\n i += 1\nprint(\"\\rProcessing cell %d of %d\" % (i, Np))\n\n# %%\n\nprint('\\rFormating the data in a shapefile...', end=' ')\ndf = pd.DataFrame(data={'precip': arr_yearly_avg_precip,\n 'tasavg': arr_avg_yearly_tasavg,\n 'tasmax': arr_avg_yearly_tasmax,\n 'tasmin': arr_avg_yearly_tasmin})\ncrs = \"+proj=longlat +ellps=GRS80 +datum=NAD83 +towgs84=0,0,0,0,0,0,0 +no_defs\"\ngdf = GeoDataFrame(df, crs=crs, geometry=geometry)\nprint('\\rFormating the data in a shapefile... done')\n\nprint('\\rSaving to Shapefile...', end=' ')\npath_shp_out = (\"D:/MeteoGrilleDaily/grid_yearly_meteo/grid_yearly_meteo.shp\")\nif not osp.exists(path_shp_out):\n os.makedirs(path_shp_out)\n\ngdf.to_file(path_shp_out)\nprint('\\rSaving to Shapefile... done', end=' ')\n"
] | [
[
"pandas.DataFrame",
"numpy.average",
"numpy.array",
"numpy.zeros",
"numpy.sum",
"numpy.vstack"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [
"0.23",
"0.21",
"2.0",
"1.4",
"0.19",
"1.1",
"1.5",
"1.2",
"0.24",
"0.20",
"1.0",
"0.25",
"1.3"
],
"scipy": [],
"tensorflow": []
}
] |
Vishal-Bhatia/ga-learner-dsmp-repo | [
"95cc328174db230d050ef5a3bbd786f6d0ec1461"
] | [
"SVM-Practice/code.py"
] | [
"# --------------\nimport pandas as pd\nfrom collections import Counter\n\n# Load dataset\n##Loading the CSV data onto a Pandas dataframe\ndata = pd.read_csv(path)\n\n##Checking for null values\nprint(data.isnull().sum())\n\n##Providing a statistical description of the above data\nprint(data.describe())\n\n\n# --------------\nimport seaborn as sns\nfrom matplotlib import pyplot as plt\nsns.set_style(style = \"darkgrid\")\n\n# Store the label values \n##Storing the target column as a variabl;e, and plotting the same\nlabel = data[\"Activity\"]\nsns.countplot(x = label)\nplt.xticks(rotation = 90)\nplt.show()\n\n# plot the countplot\n\n\n\n# --------------\n# make the copy of dataset\n# Create an empty column \n##Creating a copy of the dataset, and then creating an empty column in the copy dataset\nimport numpy as np\ndata_copy = data.copy()\ndata_copy[\"duration\"] = \"\"\n\n# Calculate the duration\n##Creating the groupby dataframe, & transforming the \"duration\" column\nduration_df = (data_copy.groupby([label[label.isin([\"WALKING_UPSTAIRS\", \"WALKING_DOWNSTAIRS\"])], \"subject\"])[\"duration\"].count() * 1.28)\nduration_df = pd.DataFrame(duration_df)\n\n# Sort the values of duration\n##Creating the dataframe for plotting with the \"duration\" values sorted\nplot_data = duration_df.reset_index().sort_values(\"duration\", ascending = False)\nplot_data[\"Activity\"] = plot_data[\"Activity\"].map({\"WALKING_UPSTAIRS\": \"Upstairs\", \"WALKING_DOWNSTAIRS\": \"Downstairs\"})\n\n# Plot the durations for staircase use\n##Plotting the barplot of \"subject\" vs \"duration\" for \"Activity\"\nsns.barplot(data = plot_data, x = \"subject\", y = \"duration\", hue = \"Activity\")\nplt.title(\"Participants Compared By Their Staircase Walking Duration\")\nplt.xlabel(\"Participants\")\nplt.ylabel(\"Total Duration [s]\")\nplt.show()\n\n\n\n# --------------\n#exclude the Activity column and the subject column\n##Creating a sub-dataframe of only the continous variables\nfeature_cols = data.columns[: -2]\n\n#Calculate the correlation values\n#stack the data and convert to a dataframe\n##Outputting the correlation matrix as an unstacked dataframe with column names as instructed\ncorrelated_values = data[feature_cols].corr()\ncorrelated_values = correlated_values.stack().to_frame().reset_index().rename(columns = {\"level_0\": \"Feature_1\", \"level_1\": \"Feature_2\", 0: \"Correlation_score\"})\n\n#create an abs_correlation column\n##Creating a column to capture the absolute correlation\ncorrelated_values[\"abs_correlation\"] = correlated_values[\"Correlation_score\"].apply(lambda x: abs(x))\n\n#Picking most correlated features without having self correlated pairs\n##Creating a column to capture absolute correlation, and seggregating the highly-correlated pairs\ntop_corr_fields = correlated_values.sort_values(\"Correlation_score\", ascending = False).query(\"abs_correlation > 0.8\")\ntop_corr_fields = top_corr_fields[top_corr_fields[\"Feature_1\"] != top_corr_fields[\"Feature_2\"]].reset_index(drop=True)\n\n\n\n\n# --------------\n# importing neccessary libraries\nfrom sklearn.preprocessing import LabelEncoder\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.svm import SVC\nfrom sklearn.metrics import precision_recall_fscore_support as error_metric\nfrom sklearn.metrics import confusion_matrix, accuracy_score\n\n# Encoding the target variable\n##Intantiating and implementing a Label Encoder\nle = LabelEncoder()\ndata[\"Activity\"] = le.fit_transform(data[\"Activity\"])\n\n# split the dataset into train and test\n##Creating the X and y dataframes, and performing the train-test split\nX = data.drop(\"Activity\", axis = 1)\ny = data[\"Activity\"]\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.3, random_state = 40)\n\n# Baseline model \n##Intantiating a baseline SVC model\nclassifier = SVC(random_state = 40)\n\n##Fitting the model\nclf = classifier.fit(X_train, y_train)\ny_pred = clf.predict(X_test)\n\n##Outputting the precision, accuracy, and F1-score of the model, and storing the accuracy in a variable as suggested\nprecision, accuracy, f_score = error_metric(y_test, y_pred, average = \"weighted\")[0:3]\nmodel1_score = accuracy_score(y_test, y_pred)\n\n\n\n# --------------\n# importing libraries\n##Importing the necessary libraries\nfrom sklearn.svm import LinearSVC\nfrom sklearn.feature_selection import SelectFromModel\n\n##Intantiating a LinearSVC model, and fitting the same\nlinsvc = LinearSVC(C = 0.01, penalty = \"l1\", dual = False, random_state = 42)\nlsvc = linsvc.fit(X_train, y_train)\n\n# Feature selection using Linear SVC\n##Intantiating a \"SelectFromModel\" on our Linear SVC model, and creating new train and test features\nmodel_2 = SelectFromModel(lsvc, prefit = True)\nnew_train_features = model_2.transform(X_train)\nnew_test_features = model_2.transform(X_test)\n\n# model building on reduced set of features\n##Intantiating another SVC model, fitting the same on the new features, and computing the error metrics\nclassifier_2 = SVC(random_state = 40)\nclf_2 = classifier_2.fit(new_train_features, y_train)\ny_pred_new = clf_2.predict(new_test_features)\nprecision, accuracy, f_score = error_metric(y_test, y_pred_new, average = \"weighted\")[0:3]\nmodel2_score = accuracy_score(y_test, y_pred_new)\n\n\n\n\n# --------------\n# Importing Libraries\nfrom sklearn.model_selection import GridSearchCV\n\n# Set the hyperparmeters\n# Usage of grid search to select the best hyperparmeters\n##Intantiating a GridSearchCV object with the SVC as the primary model, and fitting the same on new features\nparameters = {\"kernel\": [\"linear\", \"rbf\"], \"C\": [100, 20, 1, 0.1]}\nselector = GridSearchCV(estimator = SVC(), param_grid = parameters, scoring = \"accuracy\")\nselector.fit(new_train_features, y_train)\n\n##Outputting the best hyperparameters, and the detailed scores\nprint(selector.best_params_)\nresults = selector.cv_results_\nmeans = results[\"mean_test_score\"]\nstds = results[\"std_test_score\"]\nparams = results[\"params\"]\nfor mean, std, params in zip(means, stds, params):\n print(\"%0.3f (+/-%0.03f) for %r\" % (mean, std * 2, params))\n print()\n\n# Model building after Hyperparameter tuning\n##Intantiating a new SVC model with the best hyperparameter values, fitting the same, and outputting its error metrics\nclassifier_3 = SVC(C = 20, kernel = \"rbf\", random_state = 40)\nclf_3 = classifier_3.fit(new_train_features, y_train)\ny_pred_final = clf_3.predict(new_test_features)\nprecision, accuracy, f_score = error_metric(y_test, y_pred_final, average = \"weighted\")[0:3]\nmodel3_score = accuracy_score(y_test, y_pred_final)\n\n\n\n\n"
] | [
[
"pandas.read_csv",
"matplotlib.pyplot.title",
"sklearn.metrics.accuracy_score",
"sklearn.model_selection.train_test_split",
"pandas.DataFrame",
"sklearn.preprocessing.LabelEncoder",
"sklearn.metrics.precision_recall_fscore_support",
"sklearn.svm.SVC",
"sklearn.svm.LinearSVC",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.xticks",
"matplotlib.pyplot.show",
"sklearn.feature_selection.SelectFromModel",
"matplotlib.pyplot.ylabel"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [
"2.0",
"1.4",
"1.3",
"1.1",
"1.5",
"1.2"
],
"scipy": [],
"tensorflow": []
}
] |
StefanKDS/Birds | [
"bb0c8e8fd9b1a8658b4f7073b1d18fb7a2c5bdb2"
] | [
"Models.py"
] | [
"import numpy as np\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Dropout, Activation\nfrom keras.layers import Conv1D, MaxPooling1D, GlobalAveragePooling1D\n\n\ndef create_and_fit_dense_model(batch_size, epochs, callbacks, X_train, X_test, y_train, y_test):\n # BUILD THE MODEL\n model = Sequential()\n model.add(Dense(100, input_shape=(40,)))\n model.add(Activation('relu'))\n model.add(Dropout(0.5))\n model.add(Dense(200))\n model.add(Activation('relu'))\n model.add(Dropout(0.5))\n model.add(Dense(100))\n model.add(Activation('relu'))\n model.add(Dropout(0.5))\n model.add(Dense(3, activation='softmax'))\n model.compile(loss='categorical_crossentropy', optimizer='Adam', metrics=['accuracy'])\n\n # TRAIN THE MODEL\n history = model.fit(X_train, y_train, batch_size=batch_size, callbacks=callbacks, epochs=epochs,\n validation_data=(X_test, y_test))\n\n # SAVE MODEL AND HISTORY_DATA\n np.save('Auswertung/history.npy', history.history)\n model.save('Auswertung/model')\n\n return history\n\n\ndef create_and_fit_cnn_model(batch_size, epochs, callbacks, X_train, X_test, y_train, y_test):\n # BUILD THE MODEL\n model = Sequential()\n model.add(Conv1D(64, 3, activation='relu', input_shape=(40, 1)))\n model.add(Conv1D(64, 3, activation='relu'))\n model.add(MaxPooling1D(3))\n model.add(Conv1D(128, 3, activation='relu'))\n model.add(Conv1D(128, 3, activation='relu'))\n model.add(GlobalAveragePooling1D())\n model.add(Dropout(0.5))\n model.add(Dense(3, activation='sigmoid'))\n model.compile(loss='categorical_crossentropy', optimizer='Adam', metrics=['accuracy'])\n\n # TRAIN THE MODEL\n history_CNN = model.fit(X_train, y_train, batch_size=batch_size, callbacks=callbacks, epochs=epochs,\n validation_data=(X_test, y_test))\n\n # SAVE MODEL AND HISTORY_DATA\n np.save('Auswertung/history_CNN.npy', history_CNN.history)\n model.save('Auswertung/model_CNN')\n\n return history_CNN"
] | [
[
"numpy.save"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
simonoso/EasyRL | [
"3d8eb2bf138dd2a0b95f8b3743d15f34cfff0740"
] | [
"easy_rl/models/evolution_strategy.py"
] | [
"# Copyright (c) 2019 Alibaba 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# ==============================================================================\n\nimport tensorflow as tf\nfrom easy_rl.models.model_base import Model\nimport copy\nfrom easy_rl.utils import *\n\n\nclass EvolutionStrategy(Model):\n def __init__(self, obs_space, action_space, scope=\"es_model\", **kwargs):\n\n _default_config = {\n\n # network config\n # specify the parameters of network for each input state.\n # a default config will be used if empty\n # * it is recommended to overrider the `encode_obs` function and then implement a custom network structure.\n \"network_spec\": {},\n\n # size of noise table\n \"noise_table_size\": 25000000,\n\n # seed to initialize the noise table\n # Note that the seed must be same in different worker to ensure\n \"global_seed\": 0,\n\n # training config\n # parameter for grad clipping\n \"global_norm_clip\": 40,\n\n # initialization of learning rate\n \"init_lr\": 0.001,\n\n # strategy of learning rate\n \"lr_strategy_spec\": {}\n }\n\n self.config = copy.deepcopy(_default_config)\n self.config.update(kwargs.get('model_config', {}))\n\n super(EvolutionStrategy, self).__init__(\n obs_space=obs_space,\n action_space=action_space,\n scope=scope,\n **kwargs)\n\n @property\n def perturbed_actions(self):\n return self.perturbed_actions_op\n\n @property\n def learn_feed(self):\n \"\"\"return the dict of placeholder for training.\n the input value will be used to optimize model.\n \"\"\"\n\n return {\n \"perturbation_seeds\": self.perturbation_seeds_ph,\n \"returns\": self.R_ph,\n \"perturbation_scales\": self.perturbation_scales_ph\n }\n\n @property\n def extra_learn_fetches(self):\n \"\"\"return the extra fetches when training.\n \"\"\"\n\n return {}\n\n @property\n def perturbation_feed(self):\n \"\"\"return the placeholder of perturbation seed\n \"\"\"\n\n return {\n \"perturbation_seeds\": self.perturbation_seeds_ph,\n \"perturbation_scales\": self.perturbation_scales_ph,\n \"positive_perturbation\": self.positive_perturbation_ph\n }\n\n @property\n def all_variables(self):\n \"\"\"return all variables of model object\"\"\"\n return self._scope_vars\n\n @property\n def actor_sync_variables(self):\n\n return self.model_vars\n\n def reset_perturbed_parameters(self):\n \"\"\"generate a candidate perturbation and reset the perturbed model with latest \"\"\"\n\n params_size = sum(\n [utils.prod(v.shape.as_list()) for v in self.model_vars])\n\n perturbations = self._generate_perturbations(\n params_size=params_size, seed=self.perturbation_seeds_ph)\n perturbations = tf.squeeze(perturbations)\n\n var_shapes = [v.shape.as_list() for v in self.model_vars]\n perturbations_list = utils.unflatten_tensor(perturbations, var_shapes)\n\n ops = []\n for var, perturbed_var, noise in zip(self.model_vars,\n self.perturbed_model_vars,\n perturbations_list):\n ops.append(\n tf.assign(\n perturbed_var, var +\n (2 * tf.cast(self.positive_perturbation_ph, tf.float32) -\n 1.0) * self.perturbation_scales_ph * noise))\n\n return tf.group(*ops)\n\n def _build_train(self, seed, R, optimizer, vars, global_step=None):\n\n # compute the gradient\n # here we want to maximize the reward\n centered_R = self._get_centered_ranks_tensor(-1.0 * R)\n positive_R, negative_R = tf.split(centered_R, 2, axis=1)\n weights = tf.reshape((positive_R - negative_R), [1, -1])\n\n params_size = sum([utils.prod(v.shape.as_list()) for v in vars])\n noise_size = tf.shape(seed)[0]\n perturbations = self._generate_perturbations(\n params_size=params_size, seed=self.perturbation_seeds_ph)\n perturbations = perturbations * tf.expand_dims(\n self.perturbation_scales_ph, axis=-1)\n delta = tf.matmul(weights, perturbations)\n\n # add summary\n self.summary_ops[\"train\"].append(\n tf.summary.scalar(\"perturbation_scales\",\n tf.reduce_mean(self.perturbation_scales_ph)))\n self.summary_ops[\"train\"].append(\n tf.summary.histogram(\"perturbations\", perturbations))\n self.summary_ops[\"train\"].append(\n tf.summary.scalar(\"mean_noise_episode_returns\", tf.reduce_mean(R)))\n self.summary_ops[\"train\"].append(\n tf.summary.scalar(\"max_noise_episode_returns\", tf.reduce_max(R)))\n self.summary_ops[\"train\"].append(\n tf.summary.scalar(\"min_noise_episode_returns\", tf.reduce_min(R)))\n\n delta = tf.reshape(delta,\n (-1, )) / tf.cast(noise_size, tf.float32) / 2.0\n\n var_shapes = [v.shape.as_list() for v in vars]\n gradients = utils.unflatten_tensor(delta, var_shapes)\n\n # apply grad clipping\n with tf.control_dependencies(gradients):\n clipped_grads, _ = tf.clip_by_global_norm(\n gradients, clip_norm=self.config.get('global_norm_clip', 40))\n grads_and_vars = list(zip(clipped_grads, vars))\n\n train_op = optimizer.apply_gradients(\n grads_and_vars, global_step=global_step)\n\n return train_op\n\n def _build_graph(self, scope, **kwargs):\n\n # get or create global_step\n self.global_step = tf.train.get_or_create_global_step()\n with tf.variable_scope(name_or_scope=scope, reuse=tf.AUTO_REUSE):\n\n # create noise table to generate random perturbation\n noise_table_size = self.config.get('noise_table_size', 25000000)\n global_seed = self.config.get('global_seed', 0)\n self.noise_table = tf.get_variable(\n name='noise_table',\n shape=(noise_table_size, ),\n dtype=tf.float32,\n initializer=tf.random_normal_initializer(\n mean=0.0, stddev=1.0, seed=global_seed, dtype=tf.float32),\n trainable=False)\n\n self.preprocessed_obs_ph, self.preprocessed_next_obs_ph = self.preprocess_obs(\n self.obs_ph, self.next_obs_ph)\n # encode the input obs\n self.obs_embedding = self._encode_obs(\n input_obs=self.preprocessed_obs_ph, scope=\"encode_obs\")\n self.model_vars = tf.get_collection(\n tf.GraphKeys.GLOBAL_VARIABLES,\n scope=tf.get_variable_scope().name + \"/encode_obs\")\n\n # encode the input obs\n self.perturbed_obs_embedding = self._encode_obs(\n input_obs=self.preprocessed_obs_ph,\n scope=\"perturbed_encode_obs\")\n self.perturbed_model_vars = tf.get_collection(\n tf.GraphKeys.GLOBAL_VARIABLES,\n scope=tf.get_variable_scope().name + \"/perturbed_encode_obs\")\n\n # build output action_op\n self.action_op = self._actions_distribution(self.obs_embedding)\n\n self.perturbed_actions_op = self._actions_distribution(\n self.perturbed_obs_embedding)\n\n # no need to create loss function with random search algorithm\n self.loss_op = tf.no_op()\n\n # reset perturbation\n self.reset_perturbation_op = self.reset_perturbed_parameters()\n\n if kwargs.get(\"is_replica\", False):\n self._scope_vars = tf.get_collection(\n tf.GraphKeys.GLOBAL_VARIABLES, scope=scope)\n return\n\n # build train_op\n init_lr = self.config.get('init_lr', 1e-3)\n lr_strategy_spec = self.config.get('lr_strategy_spec', {})\n\n # apply different decay strategy of learning rate\n lr = learning_rate_utils.LearningRateStrategy(\n init_lr=init_lr,\n strategy_spec=lr_strategy_spec)(self.global_step)\n self.summary_ops[\"train\"].append(\n tf.summary.scalar(\"learning_rate\", lr))\n self.opt = tf.train.AdamOptimizer(learning_rate=lr)\n\n self.train_op = self._build_train(\n self.perturbation_seeds_ph,\n self.R_ph,\n optimizer=self.opt,\n vars=self.model_vars,\n global_step=self.global_step)\n\n self._scope_vars = tf.get_collection(\n tf.GraphKeys.GLOBAL_VARIABLES, scope=scope)\n\n def _encode_obs(self, input_obs, scope=\"encode_obs\"):\n \"\"\"build network to encode input feature.the desired output\n consists of two parts: action_logits and value_estimator\n\n Arguments:\n input_obs: the (list, dict)[of] input tensor of observation.\n scope: the name of variable scope\n \"\"\"\n with tf.variable_scope(name_or_scope=scope):\n # override the function `build_graph` to implement the specific network manually\n\n if len(self.config.get('network_spec')) == 0:\n # must set action_dim to use default network\n action_dim = self.action_dim\n\n if isinstance(input_obs, dict):\n is_multi_input = len(input_obs) > 1\n is_image_input = any(\n [(len(ob.shape) > 2) for _, ob in input_obs.items()])\n elif isinstance(input_obs, list):\n is_multi_input = len(input_obs) > 1\n is_image_input = any(\n [(len(ob.shape) > 2) for ob in input_obs])\n else:\n is_multi_input = False\n is_image_input = len(input_obs.shape) > 2\n\n if is_image_input and is_multi_input:\n raise ValueError(\n \"the default convolution network accepts only one input but {} given\"\n .format(len(input_obs)))\n if is_image_input and not is_multi_input:\n obs_embedding = layer_utils.DefaultConvNetwork(\n action_dim=action_dim)(input_obs)\n else:\n obs_embedding = layer_utils.DefaultFCNetwork(\n action_dim=action_dim)(input_obs)\n else:\n # build computation graph from configuration\n assert not isinstance(input_obs, list), \"list type is forbidden, key for each channel of input_\" \\\n \"obs should be supplied to build graph from configuration\" \\\n \"with multi-channel data\"\n obs_embedding = layer_utils.build_model(\n inputs=input_obs,\n network_spec=self.config['network_spec'],\n is_training_ph=self.is_training_ph)\n\n return obs_embedding\n\n def _build_ph_op(self, obs_space, action_space):\n\n super(EvolutionStrategy, self)._build_ph_op(\n obs_space=obs_space, action_space=action_space)\n\n # add extra placeholder of advantage, return and logits for training\n self.perturbation_seeds_ph = tf.placeholder(\n dtype=tf.int32, shape=[None])\n self.positive_perturbation_ph = tf.placeholder(dtype=tf.bool, shape=())\n self.perturbation_scales_ph = tf.placeholder(\n dtype=tf.float32, shape=(None, ))\n self.R_ph = tf.placeholder(dtype=tf.float32, shape=[None, 2])\n\n def _get_centered_ranks_tensor(self, R):\n flatten_R = tf.reshape(R, (-1, ))\n _, sorted_index = tf.nn.top_k(\n -1.0 * flatten_R, k=tf.shape(flatten_R)[0], sorted=False)\n perm_index = tf.cast(tf.invert_permutation(sorted_index), tf.float32)\n perm_index = tf.reshape(perm_index, tf.shape(R))\n centered_rank_R = perm_index / (\n tf.cast(tf.shape(flatten_R)[0], tf.float32) - 1.0) - 0.5\n\n return centered_rank_R\n\n def _generate_perturbations(self, params_size, seed):\n \"\"\"generate the perturbation from fixed noise table\n Note that `seed` is used as a random index\"\"\"\n\n seed = tf.mod(seed, tf.shape(self.noise_table)[0] - params_size)\n noise = tf.map_fn(\n lambda t: self.noise_table[t:t + params_size],\n seed,\n dtype=tf.float32)\n noise = tf.reshape(noise, [-1, params_size])\n return noise\n"
] | [
[
"tensorflow.invert_permutation",
"tensorflow.control_dependencies",
"tensorflow.cast",
"tensorflow.map_fn",
"tensorflow.train.AdamOptimizer",
"tensorflow.group",
"tensorflow.summary.scalar",
"tensorflow.get_collection",
"tensorflow.squeeze",
"tensorflow.train.get_or_create_global_step",
"tensorflow.random_normal_initializer",
"tensorflow.matmul",
"tensorflow.shape",
"tensorflow.placeholder",
"tensorflow.no_op",
"tensorflow.split",
"tensorflow.summary.histogram",
"tensorflow.reduce_max",
"tensorflow.reduce_mean",
"tensorflow.reshape",
"tensorflow.expand_dims",
"tensorflow.reduce_min",
"tensorflow.variable_scope",
"tensorflow.get_variable_scope"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.10"
]
}
] |
vinayya/training-data-analyst | [
"cc26e004863dbaa5490912c361774a880427686e"
] | [
"courses/machine_learning/deepdive2/building_production_ml_systems/solutions/taxifare/trainer/model.py"
] | [
"import datetime\nimport hypertune\nimport logging\nimport os\nimport shutil\n\nimport numpy as np\nimport tensorflow as tf\n\nfrom tensorflow.keras import activations\nfrom tensorflow.keras import callbacks\nfrom tensorflow.keras import layers\nfrom tensorflow.keras import models\n\nfrom tensorflow import feature_column as fc\n\nlogging.info(tf.version.VERSION)\n\n\nCSV_COLUMNS = [\n 'fare_amount',\n 'pickup_datetime',\n 'pickup_longitude',\n 'pickup_latitude',\n 'dropoff_longitude',\n 'dropoff_latitude',\n 'passenger_count',\n 'key',\n]\nLABEL_COLUMN = 'fare_amount'\nDEFAULTS = [[0.0], ['na'], [0.0], [0.0], [0.0], [0.0], [0.0], ['na']]\nDAYS = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']\n\n\ndef features_and_labels(row_data):\n for unwanted_col in ['key']:\n row_data.pop(unwanted_col)\n label = row_data.pop(LABEL_COLUMN)\n return row_data, label\n\n\ndef load_dataset(pattern, batch_size, num_repeat):\n dataset = tf.data.experimental.make_csv_dataset(\n file_pattern=pattern,\n batch_size=batch_size,\n column_names=CSV_COLUMNS,\n column_defaults=DEFAULTS,\n num_epochs=num_repeat,\n )\n return dataset.map(features_and_labels)\n\n\ndef create_train_dataset(pattern, batch_size):\n dataset = load_dataset(pattern, batch_size, num_repeat=None)\n return dataset.prefetch(1)\n\n\ndef create_eval_dataset(pattern, batch_size):\n dataset = load_dataset(pattern, batch_size, num_repeat=1)\n return dataset.prefetch(1)\n\n\ndef parse_datetime(s):\n if type(s) is not str:\n s = s.numpy().decode('utf-8')\n return datetime.datetime.strptime(s, \"%Y-%m-%d %H:%M:%S %Z\")\n\n\ndef euclidean(params):\n lon1, lat1, lon2, lat2 = params\n londiff = lon2 - lon1\n latdiff = lat2 - lat1\n return tf.sqrt(londiff*londiff + latdiff*latdiff)\n\n\ndef get_dayofweek(s):\n ts = parse_datetime(s)\n return DAYS[ts.weekday()]\n\n\[email protected]\ndef dayofweek(ts_in):\n return tf.map_fn(\n lambda s: tf.py_function(get_dayofweek, inp=[s], Tout=tf.string),\n ts_in\n )\n\n\[email protected]\ndef fare_thresh(x):\n return 60 * activations.relu(x)\n\n\ndef transform(inputs, NUMERIC_COLS, STRING_COLS, nbuckets):\n # Pass-through columns\n transformed = inputs.copy()\n del transformed['pickup_datetime']\n\n feature_columns = {\n colname: fc.numeric_column(colname)\n for colname in NUMERIC_COLS\n }\n\n # Scaling longitude from range [-70, -78] to [0, 1]\n for lon_col in ['pickup_longitude', 'dropoff_longitude']:\n transformed[lon_col] = layers.Lambda(\n lambda x: (x + 78)/8.0,\n name='scale_{}'.format(lon_col)\n )(inputs[lon_col])\n\n # Scaling latitude from range [37, 45] to [0, 1]\n for lat_col in ['pickup_latitude', 'dropoff_latitude']:\n transformed[lat_col] = layers.Lambda(\n lambda x: (x - 37)/8.0,\n name='scale_{}'.format(lat_col)\n )(inputs[lat_col])\n\n # Adding Euclidean dist (no need to be accurate: NN will calibrate it)\n transformed['euclidean'] = layers.Lambda(euclidean, name='euclidean')([\n inputs['pickup_longitude'],\n inputs['pickup_latitude'],\n inputs['dropoff_longitude'],\n inputs['dropoff_latitude']\n ])\n feature_columns['euclidean'] = fc.numeric_column('euclidean')\n\n # hour of day from timestamp of form '2010-02-08 09:17:00+00:00'\n transformed['hourofday'] = layers.Lambda(\n lambda x: tf.strings.to_number(\n tf.strings.substr(x, 11, 2), out_type=tf.dtypes.int32),\n name='hourofday'\n )(inputs['pickup_datetime'])\n feature_columns['hourofday'] = fc.indicator_column(\n fc.categorical_column_with_identity(\n 'hourofday', num_buckets=24))\n\n latbuckets = np.linspace(0, 1, nbuckets).tolist()\n lonbuckets = np.linspace(0, 1, nbuckets).tolist()\n b_plat = fc.bucketized_column(\n feature_columns['pickup_latitude'], latbuckets)\n b_dlat = fc.bucketized_column(\n feature_columns['dropoff_latitude'], latbuckets)\n b_plon = fc.bucketized_column(\n feature_columns['pickup_longitude'], lonbuckets)\n b_dlon = fc.bucketized_column(\n feature_columns['dropoff_longitude'], lonbuckets)\n ploc = fc.crossed_column(\n [b_plat, b_plon], nbuckets * nbuckets)\n dloc = fc.crossed_column(\n [b_dlat, b_dlon], nbuckets * nbuckets)\n pd_pair = fc.crossed_column([ploc, dloc], nbuckets ** 4)\n feature_columns['pickup_and_dropoff'] = fc.embedding_column(\n pd_pair, 100)\n\n return transformed, feature_columns\n\n\ndef rmse(y_true, y_pred):\n return tf.sqrt(tf.reduce_mean(tf.square(y_pred - y_true)))\n\n\ndef build_dnn_model(nbuckets, nnsize, lr):\n # input layer is all float except for pickup_datetime which is a string\n STRING_COLS = ['pickup_datetime']\n NUMERIC_COLS = (\n set(CSV_COLUMNS) - set([LABEL_COLUMN, 'key']) - set(STRING_COLS)\n )\n inputs = {\n colname: layers.Input(name=colname, shape=(), dtype='float32')\n for colname in NUMERIC_COLS\n }\n inputs.update({\n colname: layers.Input(name=colname, shape=(), dtype='string')\n for colname in STRING_COLS\n })\n\n # transforms\n transformed, feature_columns = transform(\n inputs, NUMERIC_COLS, STRING_COLS, nbuckets=nbuckets)\n dnn_inputs = layers.DenseFeatures(feature_columns.values())(transformed)\n\n x = dnn_inputs\n for layer, nodes in enumerate(nnsize):\n x = layers.Dense(nodes, activation='relu', name='h{}'.format(layer))(x)\n output = layers.Dense(1, name='fare')(x)\n \n model = models.Model(inputs, output)\n lr_optimizer = tf.keras.optimizers.Adam(learning_rate=lr)\n model.compile(optimizer=lr_optimizer, loss='mse', metrics=[rmse, 'mse'])\n \n return model\n\n\ndef train_and_evaluate(hparams):\n batch_size = hparams['batch_size']\n eval_data_path = hparams['eval_data_path']\n nnsize = hparams['nnsize']\n nbuckets = hparams['nbuckets']\n lr = hparams['lr']\n num_evals = hparams['num_evals']\n num_examples_to_train_on = hparams['num_examples_to_train_on']\n output_dir = hparams['output_dir']\n train_data_path = hparams['train_data_path']\n\n if tf.io.gfile.exists(output_dir):\n tf.io.gfile.rmtree(output_dir)\n\n timestamp = datetime.datetime.now().strftime('%Y%m%d%H%M%S')\n savedmodel_dir = os.path.join(output_dir, 'savedmodel')\n model_export_path = os.path.join(savedmodel_dir, timestamp)\n checkpoint_path = os.path.join(output_dir, 'checkpoints')\n tensorboard_path = os.path.join(output_dir, 'tensorboard')\n\n dnn_model = build_dnn_model(nbuckets, nnsize, lr)\n logging.info(dnn_model.summary())\n\n trainds = create_train_dataset(train_data_path, batch_size)\n evalds = create_eval_dataset(eval_data_path, batch_size)\n\n steps_per_epoch = num_examples_to_train_on // (batch_size * num_evals)\n\n checkpoint_cb = callbacks.ModelCheckpoint(checkpoint_path,\n save_weights_only=True,\n verbose=1)\n\n tensorboard_cb = callbacks.TensorBoard(tensorboard_path,\n histogram_freq=1)\n\n history = dnn_model.fit(\n trainds,\n validation_data=evalds,\n epochs=num_evals,\n steps_per_epoch=max(1, steps_per_epoch),\n verbose=2, # 0=silent, 1=progress bar, 2=one line per epoch\n callbacks=[checkpoint_cb, tensorboard_cb]\n )\n\n # Exporting the model with default serving function.\n tf.saved_model.save(dnn_model, model_export_path)\n\n # TODO 1\n hp_metric = history.history['val_rmse'][num_evals-1]\n\n # TODO 1\n hpt = hypertune.HyperTune()\n hpt.report_hyperparameter_tuning_metric(\n hyperparameter_metric_tag='rmse',\n metric_value=hp_metric,\n global_step=num_evals\n )\n\n return history\n"
] | [
[
"tensorflow.feature_column.bucketized_column",
"numpy.linspace",
"tensorflow.feature_column.categorical_column_with_identity",
"tensorflow.keras.callbacks.TensorBoard",
"tensorflow.feature_column.embedding_column",
"tensorflow.keras.layers.Lambda",
"tensorflow.strings.substr",
"tensorflow.saved_model.save",
"tensorflow.keras.activations.relu",
"tensorflow.square",
"tensorflow.keras.callbacks.ModelCheckpoint",
"tensorflow.keras.models.Model",
"tensorflow.io.gfile.exists",
"tensorflow.keras.layers.Dense",
"tensorflow.feature_column.crossed_column",
"tensorflow.data.experimental.make_csv_dataset",
"tensorflow.feature_column.numeric_column",
"tensorflow.io.gfile.rmtree",
"tensorflow.py_function",
"tensorflow.keras.optimizers.Adam",
"tensorflow.sqrt",
"tensorflow.keras.layers.Input"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.10",
"2.7",
"2.6",
"2.4",
"2.3",
"2.5",
"2.2"
]
}
] |
QingyuanWang/tianshou | [
"c5efc41c448ac1b111f93e467828583e6f5d6f10"
] | [
"examples/halfcheetahBullet_v0_sac.py"
] | [
"import os\nimport gym\nimport torch\nimport pprint\nimport argparse\nimport numpy as np\nfrom torch.utils.tensorboard import SummaryWriter\n\nfrom tianshou.env import SubprocVectorEnv\nfrom tianshou.policy import SACPolicy\nfrom tianshou.trainer import offpolicy_trainer\nfrom tianshou.data import Collector, ReplayBuffer\n\ntry:\n import pybullet_envs\nexcept ImportError:\n pass\n\nfrom continuous_net import ActorProb, Critic\n\n\ndef get_args():\n parser = argparse.ArgumentParser()\n parser.add_argument('--task', type=str, default='HalfCheetahBulletEnv-v0')\n parser.add_argument('--run-id', type=str, default='test')\n parser.add_argument('--seed', type=int, default=1626)\n parser.add_argument('--buffer-size', type=int, default=20000)\n parser.add_argument('--actor-lr', type=float, default=3e-4)\n parser.add_argument('--critic-lr', type=float, default=1e-3)\n parser.add_argument('--gamma', type=float, default=0.99)\n parser.add_argument('--tau', type=float, default=0.005)\n parser.add_argument('--alpha', type=float, default=0.2)\n parser.add_argument('--epoch', type=int, default=200)\n parser.add_argument('--step-per-epoch', type=int, default=1000)\n parser.add_argument('--collect-per-step', type=int, default=10)\n parser.add_argument('--batch-size', type=int, default=128)\n parser.add_argument('--layer-num', type=int, default=1)\n parser.add_argument('--training-num', type=int, default=8)\n parser.add_argument('--test-num', type=int, default=4)\n parser.add_argument('--logdir', type=str, default='log')\n parser.add_argument('--log-interval', type=int, default=100)\n parser.add_argument('--render', type=float, default=0.)\n parser.add_argument(\n '--device', type=str,\n default='cuda' if torch.cuda.is_available() else 'cpu')\n args = parser.parse_known_args()[0]\n return args\n\n\ndef test_sac(args=get_args()):\n torch.set_num_threads(1)\n env = gym.make(args.task)\n args.state_shape = env.observation_space.shape or env.observation_space.n\n args.action_shape = env.action_space.shape or env.action_space.n\n args.max_action = env.action_space.high[0]\n # you can also use tianshou.env.SubprocVectorEnv\n # train_envs = gym.make(args.task)\n train_envs = SubprocVectorEnv(\n [lambda: gym.make(args.task) for _ in range(args.training_num)])\n # test_envs = gym.make(args.task)\n test_envs = SubprocVectorEnv(\n [lambda: gym.make(args.task) for _ in range(args.test_num)])\n # seed\n np.random.seed(args.seed)\n torch.manual_seed(args.seed)\n train_envs.seed(args.seed)\n test_envs.seed(args.seed)\n # model\n actor = ActorProb(\n args.layer_num, args.state_shape, args.action_shape,\n args.max_action, args.device\n ).to(args.device)\n actor_optim = torch.optim.Adam(actor.parameters(), lr=args.actor_lr)\n critic1 = Critic(\n args.layer_num, args.state_shape, args.action_shape, args.device\n ).to(args.device)\n critic1_optim = torch.optim.Adam(critic1.parameters(), lr=args.critic_lr)\n critic2 = Critic(\n args.layer_num, args.state_shape, args.action_shape, args.device\n ).to(args.device)\n critic2_optim = torch.optim.Adam(critic2.parameters(), lr=args.critic_lr)\n policy = SACPolicy(\n actor, actor_optim, critic1, critic1_optim, critic2, critic2_optim,\n args.tau, args.gamma, args.alpha,\n [env.action_space.low[0], env.action_space.high[0]],\n reward_normalization=True, ignore_done=True)\n # collector\n train_collector = Collector(\n policy, train_envs, ReplayBuffer(args.buffer_size))\n test_collector = Collector(policy, test_envs)\n # train_collector.collect(n_step=args.buffer_size)\n # log\n log_path = os.path.join(args.logdir, args.task, 'sac', args.run_id)\n writer = SummaryWriter(log_path)\n\n def stop_fn(x):\n return x >= env.spec.reward_threshold\n\n # trainer\n result = offpolicy_trainer(\n policy, train_collector, test_collector, args.epoch,\n args.step_per_epoch, args.collect_per_step, args.test_num,\n args.batch_size, stop_fn=stop_fn,\n writer=writer, log_interval=args.log_interval)\n assert stop_fn(result['best_reward'])\n train_collector.close()\n test_collector.close()\n if __name__ == '__main__':\n pprint.pprint(result)\n # Let's watch its performance!\n env = gym.make(args.task)\n collector = Collector(policy, env)\n result = collector.collect(n_episode=1, render=args.render)\n print(f'Final reward: {result[\"rew\"]}, length: {result[\"len\"]}')\n collector.close()\n\n\nif __name__ == '__main__':\n __all__ = ('pybullet_envs',) # Avoid F401 error :)\n test_sac()\n"
] | [
[
"numpy.random.seed",
"torch.manual_seed",
"torch.set_num_threads",
"torch.utils.tensorboard.SummaryWriter",
"torch.cuda.is_available"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
HudsonHuang/g2pM | [
"2c63945291d2740288f94088c5203933e3f1adbb"
] | [
"g2pM/g2pM.py"
] | [
"import pickle\nimport torch\nfrom torch import nn\n\nimport numpy as np\nimport os\n\nUNK_TOKEN = \"<UNK>\"\nPAD_TOKEN = \"<PAD>\"\nBOS_TOKEN = \"시\"\nEOS_TOKEN = \"끝\"\nSPLIT_TOKEN = \"▁\"\n\nclass G2pMT(nn.Module):\n def __init__(self):\n super().__init__()\n\n self.cedict = pickle.load(open(os.path.dirname(os.path.abspath(__file__)) + '/digest_cedict.pkl', 'rb'))\n self.char2idx = pickle.load(open(os.path.dirname(os.path.abspath(__file__)) + '/char2idx.pkl', 'rb'))\n class2idx = pickle.load(open(os.path.dirname(os.path.abspath(__file__)) + '/class2idx.pkl', 'rb'))\n state_dict = pickle.load(open(os.path.dirname(os.path.abspath(__file__)) + '/np_ckpt.pkl', 'rb'))\n self.idx2class = {idx: pron for pron, idx in class2idx.items()}\n\n self.embedding = nn.Embedding(5398, 64)\n self.lstm = nn.LSTM(64, 32, 1, bidirectional=True)\n self.logit_layer = nn.Sequential(nn.Linear(64, 32), nn.ReLU(), nn.Linear(32, 876))\n for k, v in state_dict.items():\n state_dict[k] = torch.tensor(v)\n self.load_state_dict(state_dict)\n\n def forward(self, x, target_idx):\n batch_size = x.shape[1]\n lengths = torch.sum(torch.sign(x), axis=1)\n x = self.embedding(x)\n x, _ = self.lstm(x) # seq_len, batch, num_directions * hidden_size\n # x = x.squeeze(1)\n\n if batch_size == 1:\n x = np.squeeze(x, axis=0) # [t,d]\n x = x[target_idx]\n else:\n x = x[np.arange(len(lengths)), target_idx]\n\n x = self.logit_layer(x)\n print(\"logit_layer\", x.shape)\n return torch.argmax(x, 1)\n \n\n def predict(self, inputs, target_idx):\n return self.forward(torch.tensor(inputs).long(), target_idx).numpy()\n\n def __call__(self, sent, char_split=False, tone=True):\n input_ids = []\n poly_indices = []\n pros_lst = []\n for idx, char in enumerate(sent):\n if char in self.char2idx:\n char_id = self.char2idx[char]\n else:\n char_id = self.char2idx[UNK_TOKEN]\n input_ids.append(char_id)\n\n if char in self.cedict:\n prons = self.cedict[char]\n\n # polyphonic character\n if len(prons) > 1:\n poly_indices.append(idx)\n pros_lst.append(SPLIT_TOKEN)\n else:\n pron = prons[0]\n # remove the digit which denotes a tone\n if not tone:\n pron = pron[:-1]\n pros_lst.append(pron)\n else:\n pros_lst.append(char)\n\n if len(poly_indices) > 0:\n # insert and append BOS, EOS ID\n BOS_ID = self.char2idx[BOS_TOKEN]\n EOS_ID = self.char2idx[EOS_TOKEN]\n input_ids.insert(0, BOS_ID)\n input_ids.append(EOS_ID)\n # BOS_ID is inserted at the first position, so +1 for poly idx\n _poly_indices = [idx + 1 for idx in poly_indices]\n\n input_ids = np.array(input_ids, dtype=np.int32)\n input_ids = np.expand_dims(input_ids, axis=0)\n # input_ids = np.tile(input_ids, (len(poly_indices), 1))\n # polyphone disambiguation\n preds = self.predict(input_ids, _poly_indices)\n\n for idx, pred in zip(poly_indices, preds):\n pron = self.idx2class[pred]\n if not tone:\n pron = pron[:-1]\n pros_lst[idx] = pron\n\n if char_split:\n return pros_lst\n else:\n pron_str = \"\"\n delimiter = \"|\"\n for pro in pros_lst:\n if len(pro) == 1:\n pron_str += pro\n else:\n if len(pron_str) > 0 and pron_str[-1] != delimiter:\n pro = delimiter + pro\n pron_str += pro + delimiter\n if pron_str[-1] == delimiter:\n pron_str = pron_str[:-1]\n ret = pron_str.split(delimiter)\n \n return ret\n\nclass G2pM(object):\n # one-layer bi-LSTM with two layered FC\n def __init__(self):\n self.cedict = pickle.load(open(os.path.dirname(os.path.abspath(__file__)) + '/digest_cedict.pkl', 'rb'))\n self.char2idx = pickle.load(open(os.path.dirname(os.path.abspath(__file__)) + '/char2idx.pkl', 'rb'))\n class2idx = pickle.load(open(os.path.dirname(os.path.abspath(__file__)) + '/class2idx.pkl', 'rb'))\n state_dict = pickle.load(open(os.path.dirname(os.path.abspath(__file__)) + '/np_ckpt.pkl', 'rb'))\n \n self.load_variable(state_dict)\n self.idx2class = {idx: pron for pron, idx in class2idx.items()}\n\n def load_variable(self, state_dict):\n self.embeddings = state_dict[\"embedding.weight\"]\n self.weight_ih = state_dict[\"lstm.weight_ih_l0\"]\n self.weight_hh = state_dict[\"lstm.weight_hh_l0\"]\n self.bias_ih = state_dict[\"lstm.bias_ih_l0\"]\n self.bias_hh = state_dict[\"lstm.bias_hh_l0\"]\n\n self.weight_ih_reverse = state_dict[\"lstm.weight_ih_l0_reverse\"]\n self.weight_hh_reverse = state_dict[\"lstm.weight_hh_l0_reverse\"]\n self.bias_ih_reverse = state_dict[\"lstm.bias_ih_l0_reverse\"]\n self.bias_hh_reverse = state_dict[\"lstm.bias_hh_l0_reverse\"]\n\n self.hidden_weight_l0 = state_dict[\"logit_layer.0.weight\"]\n self.hidden_bias_l0 = state_dict[\"logit_layer.0.bias\"]\n self.hidden_weight_l1 = state_dict[\"logit_layer.2.weight\"]\n self.hidden_bias_l1 = state_dict[\"logit_layer.2.bias\"]\n\n def reverse_sequence(self, inputs, lengths):\n # inputs : numpy 2d array\n # lengths: list\n rev_seqs = []\n max_length = max(lengths)\n is_1d = len(inputs.shape) == 2\n for seq, length in zip(inputs, lengths):\n end = length-1\n\n if is_1d:\n zeros = np.array([0] * (max_length-length), dtype=np.int32)\n else:\n d = inputs.shape[-1]\n zeros = np.zeros((max_length-length, d), dtype=np.float64)\n rev_seq = np.concatenate([seq[end::-1], zeros], axis=0)\n rev_seqs.append(rev_seq)\n rev_seqs = np.stack(rev_seqs, axis=0)\n\n return rev_seqs\n\n def sigmoid(self, x):\n return 1 / (1 + np.exp(-x))\n\n def relu(self, x):\n return x * (x > 0)\n\n def get_embedding(self, inputs):\n return np.take(self.embeddings, inputs, axis=0)\n\n def fw_lstm_cell(self, inputs, init_states=None):\n # inputs : [b,d]\n if init_states is None:\n init_h = np.zeros((inputs.shape[0], self.weight_hh.shape[1]))\n init_c = np.zeros_like(init_h)\n init_states = (init_h, init_c)\n states = init_states\n (prev_h, prev_c) = states\n ifgo_ih = np.matmul(\n inputs, self.weight_ih.T) + self.bias_ih\n ifgo_hh = np.matmul(\n prev_h, self.weight_hh.T) + self.bias_hh\n\n if_ih = ifgo_ih[:, :ifgo_ih.shape[-1] * 2 // 4]\n go_ih = ifgo_ih[:, ifgo_ih.shape[-1] * 2 // 4:]\n\n if_hh = ifgo_hh[:, :ifgo_hh.shape[-1] * 2 // 4]\n go_hh = ifgo_hh[:, ifgo_hh.shape[-1] * 2 // 4:]\n\n if_gate = self.sigmoid(if_ih + if_hh)\n\n i, f = if_gate[:, :if_gate.shape[-1] //\n 2], if_gate[:, if_gate.shape[-1] // 2:]\n\n g_ih, o_ih = go_ih[:, :go_ih.shape[-1] //\n 2], go_ih[:, go_ih.shape[-1] // 2:]\n g_hh, o_hh = go_hh[:, :go_hh.shape[-1] //\n 2], go_hh[:, go_hh.shape[-1] // 2:]\n\n g = np.tanh(g_ih + g_hh)\n o = self.sigmoid(o_ih + o_hh)\n c = f * prev_c + i * g\n h = o * np.tanh(c)\n\n return (h, c)\n\n def bw_lstm_cell(self, inputs, init_states=None):\n # inputs : [b,d]\n if init_states is None:\n init_h = np.zeros((inputs.shape[0], self.weight_hh.shape[1]))\n init_c = np.zeros_like(init_h)\n init_states = (init_h, init_c)\n states = init_states\n (prev_h, prev_c) = states\n ifgo_ih = np.matmul(\n inputs, self.weight_ih_reverse.T) + self.bias_ih_reverse\n ifgo_hh = np.matmul(\n prev_h, self.weight_hh_reverse.T) + self.bias_hh_reverse\n\n if_ih = ifgo_ih[:, :ifgo_ih.shape[-1] * 2 // 4]\n go_ih = ifgo_ih[:, ifgo_ih.shape[-1] * 2 // 4:]\n\n if_hh = ifgo_hh[:, :ifgo_hh.shape[-1] * 2 // 4]\n go_hh = ifgo_hh[:, ifgo_hh.shape[-1] * 2 // 4:]\n\n if_gate = self.sigmoid(if_ih + if_hh)\n i, f = if_gate[:, :if_gate.shape[-1] //\n 2:], if_gate[:, if_gate.shape[-1] // 2:]\n\n g_ih, o_ih = go_ih[:, :go_ih.shape[-1] //\n 2], go_ih[:, go_ih.shape[-1] // 2:]\n g_hh, o_hh = go_hh[:, :go_hh.shape[-1] //\n 2], go_hh[:, go_hh.shape[-1] // 2:]\n\n g = np.tanh(g_ih + g_hh)\n o = self.sigmoid(o_ih + o_hh)\n c = f * prev_c + i * g\n h = o * np.tanh(c)\n\n return (h, c)\n\n def fc_layer(self, inputs):\n # inputs : [b,t,d]\n hidden_l0 = np.matmul(\n inputs, self.hidden_weight_l0.T) + self.hidden_bias_l0\n hidden_l0 = self.relu(hidden_l0)\n\n logits = np.matmul(\n hidden_l0, self.hidden_weight_l1.T) + self.hidden_bias_l1\n\n return logits\n\n def predict(self, inputs, target_idx):\n lengths = np.sum(np.sign(inputs), axis=1)\n max_length = max(lengths)\n\n rev_seq = self.reverse_sequence(inputs, lengths)\n fw_emb = self.get_embedding(inputs) # [b,t,d]\n bw_emb = self.get_embedding(rev_seq)\n\n fw_states, bw_states = None, None\n fw_hs = []\n bw_hs = []\n for i in range(max_length):\n fw_input = fw_emb[:, i, :]\n bw_input = bw_emb[:, i, :]\n fw_states = self.fw_lstm_cell(fw_input, fw_states)\n bw_states = self.bw_lstm_cell(bw_input, bw_states)\n\n fw_hs.append(fw_states[0])\n bw_hs.append(bw_states[0])\n fw_hiddens = np.stack(fw_hs, axis=1)\n bw_hiddens = np.stack(bw_hs, axis=1)\n bw_hiddens = self.reverse_sequence(bw_hiddens, lengths)\n\n outputs = np.concatenate([fw_hiddens, bw_hiddens], axis=2) # [b,t,d]\n batch_size = outputs.shape[0]\n if batch_size == 1:\n outputs = np.squeeze(outputs, axis=0) # [t,d]\n target_hidden = outputs[target_idx]\n else:\n target_hidden = outputs[np.arange(len(lengths)), target_idx]\n\n logits = self.fc_layer(target_hidden)\n preds = np.argmax(logits, axis=1)\n\n return preds\n\n def __call__(self, sent, char_split=False, tone=True):\n input_ids = []\n poly_indices = []\n pros_lst = []\n for idx, char in enumerate(sent):\n if char in self.char2idx:\n char_id = self.char2idx[char]\n else:\n char_id = self.char2idx[UNK_TOKEN]\n input_ids.append(char_id)\n\n if char in self.cedict:\n prons = self.cedict[char]\n\n # polyphonic character\n if len(prons) > 1:\n poly_indices.append(idx)\n pros_lst.append(SPLIT_TOKEN)\n else:\n pron = prons[0]\n # remove the digit which denotes a tone\n if not tone:\n pron = pron[:-1]\n pros_lst.append(pron)\n else:\n pros_lst.append(char)\n\n if len(poly_indices) > 0:\n # insert and append BOS, EOS ID\n BOS_ID = self.char2idx[BOS_TOKEN]\n EOS_ID = self.char2idx[EOS_TOKEN]\n input_ids.insert(0, BOS_ID)\n input_ids.append(EOS_ID)\n # BOS_ID is inserted at the first position, so +1 for poly idx\n _poly_indices = [idx + 1 for idx in poly_indices]\n\n input_ids = np.array(input_ids, dtype=np.int32)\n input_ids = np.expand_dims(input_ids, axis=0)\n # input_ids = np.tile(input_ids, (len(poly_indices), 1))\n # polyphone disambiguation\n preds = self.predict(input_ids, _poly_indices)\n\n for idx, pred in zip(poly_indices, preds):\n pron = self.idx2class[pred]\n if not tone:\n pron = pron[:-1]\n pros_lst[idx] = pron\n\n if char_split:\n return pros_lst\n else:\n pron_str = \"\"\n delimiter = \"|\"\n for pro in pros_lst:\n if len(pro) == 1:\n pron_str += pro\n else:\n if len(pron_str) > 0 and pron_str[-1] != delimiter:\n pro = delimiter + pro\n pron_str += pro + delimiter\n if pron_str[-1] == delimiter:\n pron_str = pron_str[:-1]\n ret = pron_str.split(delimiter)\n \n return ret\n\nif __name__ == \"__main__\": \n g2 = G2pM()\n print(g2(\"你好你怎么又,让我我屏幕期货佛批号佛号鬼欧冠IP古·1\"))\n\n \n g2 = G2pMT()\n print(g2(\"你好你怎么又,让我我屏幕期货佛批号佛号鬼欧冠IP古·1\"))\n"
] | [
[
"numpy.expand_dims",
"numpy.take",
"torch.sign",
"numpy.squeeze",
"torch.nn.Embedding",
"numpy.concatenate",
"numpy.zeros_like",
"numpy.exp",
"numpy.matmul",
"numpy.stack",
"torch.tensor",
"numpy.argmax",
"numpy.zeros",
"torch.nn.Linear",
"numpy.array",
"numpy.tanh",
"torch.nn.LSTM",
"numpy.sign",
"torch.nn.ReLU",
"torch.argmax"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
monofo/adversarial-robustness-toolbox-1 | [
"841ce32169c383bc4b35ee33976f56c08ad7df2e"
] | [
"utils/resources/create_inverse_gan_models.py"
] | [
"# MIT License\n#\n# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2020\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\nimport logging\nimport time\nimport os\n\nimport numpy as np\nimport tensorflow as tf\n\nfrom art.utils import load_mnist\n\nconfig = tf.ConfigProto(\n gpu_options=tf.GPUOptions(\n #visible_device_list=\"1\", # specify GPU number\n allow_growth=True\n )\n)\ntf.Session(config = config)\n\n\nlogging.root.setLevel(logging.NOTSET)\nlogging.basicConfig(level=logging.NOTSET)\nlogger = logging.getLogger(__name__)\n\nlogger.setLevel(logging.INFO)\n\n\ndef create_generator_layers(x):\n with tf.variable_scope(\"generator\", reuse=tf.AUTO_REUSE):\n x_reshaped = tf.reshape(x, [-1, 1, 1, x.get_shape()[1]])\n # 1rst HIDDEN LAYER\n conv1 = tf.layers.conv2d_transpose(x_reshaped, 1024, [4, 4], strides=(1, 1), padding=\"valid\")\n normalized1 = tf.layers.batch_normalization(conv1)\n lrelu1 = tf.nn.leaky_relu(normalized1)\n\n # 2nd HIDDEN LAYER\n conv2 = tf.layers.conv2d_transpose(lrelu1, 512, [4, 4], strides=(2, 2), padding=\"same\")\n normalized2 = tf.layers.batch_normalization(conv2)\n lrelu2 = tf.nn.leaky_relu(normalized2)\n\n # 3rd HIDDEN LAYER\n conv3 = tf.layers.conv2d_transpose(lrelu2, 256, [4, 4], strides=(2, 2), padding=\"same\")\n normalized3 = tf.layers.batch_normalization(conv3)\n lrelu3 = tf.nn.leaky_relu(normalized3)\n\n # 4th HIDDEN LAYER\n conv4 = tf.layers.conv2d_transpose(lrelu3, 128, [4, 4], strides=(2, 2), padding=\"same\")\n normalized4 = tf.layers.batch_normalization(conv4)\n lrelu4 = tf.nn.leaky_relu(normalized4)\n\n # OUTPUT LAYER\n conv5 = tf.layers.conv2d_transpose(lrelu4, 1, [4, 4], strides=(2, 2), padding=\"same\")\n output = tf.nn.tanh(conv5, name=\"output_non_normalized\")\n\n # denormalizing images\n output_resized = tf.image.resize_images(output, [28, 28])\n #return tf.multiply(tf.add(output_resized, 0.5), 0.5, name=\"output\")\n return tf.add(tf.multiply(output_resized, 0.5), 0.5, name=\"output\")\n\n\ndef create_discriminator_layers(x):\n with tf.variable_scope(\"discriminator\", reuse=tf.AUTO_REUSE):\n # normalizing images\n x_resized = tf.image.resize_images(x, [64, 64])\n x_resized_normalised = (x_resized - 0.5) / 0.5 # normalization; range: -1 ~ 1\n\n # 1rst HIDDEN LAYER\n conv1 = tf.layers.conv2d(x_resized_normalised, 128, [4, 4], strides=(2, 2), padding=\"same\")\n lrelu1 = tf.nn.leaky_relu(conv1)\n\n # 2nd HIDDEN LAYER\n conv2 = tf.layers.conv2d(lrelu1, 256, [4, 4], strides=(2, 2), padding=\"same\")\n normalized2 = tf.layers.batch_normalization(conv2)\n lrelu2 = tf.nn.leaky_relu(normalized2)\n\n # 3rd HIDDEN LAYER\n conv3 = tf.layers.conv2d(lrelu2, 512, [4, 4], strides=(2, 2), padding=\"same\")\n normalized3 = tf.layers.batch_normalization(conv3)\n lrelu3 = tf.nn.leaky_relu(normalized3)\n\n # 4th HIDDEN LAYER\n conv4 = tf.layers.conv2d(lrelu3, 1024, [4, 4], strides=(2, 2), padding=\"same\")\n normalized4 = tf.layers.batch_normalization(conv4)\n lrelu4 = tf.nn.leaky_relu(normalized4)\n\n # OUTPUT LAYER\n logits = tf.layers.conv2d(lrelu4, 1, [4, 4], strides=(1, 1), padding=\"valid\")\n output = tf.nn.sigmoid(logits)\n\n return output, logits\n\n\ndef create_encoder_layers2(x, net_dim=64, latent_dim=128, reuse=False):\n with tf.variable_scope(\"encoder\", reuse=tf.AUTO_REUSE):\n conv1 = tf.layers.conv2d(x, filters=net_dim, kernel_size=5, strides=(2, 2), padding=\"same\", name=\"conv1\")\n normalized1 = tf.layers.batch_normalization(conv1, name=\"normalization1\")\n\n lrelu1 = tf.nn.leaky_relu(normalized1)\n\n conv2 = tf.layers.conv2d(\n lrelu1, filters=2 * net_dim, kernel_size=5, strides=(2, 2), padding=\"same\", name=\"conv2\"\n )\n\n normalized2 = tf.layers.batch_normalization(conv2, name=\"normalization2\")\n lrelu2 = tf.nn.leaky_relu(normalized2)\n\n conv3 = tf.layers.conv2d(\n lrelu2, filters=4 * net_dim, kernel_size=5, strides=(2, 2), padding=\"same\", name=\"conv3\"\n )\n\n normalized3 = tf.layers.batch_normalization(conv3, name=\"normalization3\")\n lrelu3 = tf.nn.leaky_relu(normalized3)\n\n reshaped = tf.reshape(lrelu3, [-1, 4 * 4 * 4 * net_dim])\n\n z = tf.contrib.layers.fully_connected(reshaped, latent_dim)\n\n return z\n\n\ndef load_model(sess, model_name, model_path):\n saver = tf.train.import_meta_graph(os.path.join(model_path, model_name + \".meta\"))\n saver.restore(sess, os.path.join(model_path, model_name))\n\n graph = tf.get_default_graph()\n generator_tf = graph.get_tensor_by_name(\"generator/output:0\")\n image_to_encode_ph = graph.get_tensor_by_name(\"image_to_encode_input:0\")\n encoder_tf = graph.get_tensor_by_name(\"encoder_1/fully_connected/Relu:0\")\n z_ph = graph.get_tensor_by_name(\"z_input:0\")\n\n return generator_tf, encoder_tf, z_ph, image_to_encode_ph\n\n\ndef predict(sess, batch_size, generator_tf, z):\n z_ = np.random.normal(0, 1, (batch_size, 100))\n return sess.run([generator_tf], {z: z_})[0]\n\n\ndef train_models(\n sess, x_train, gen_loss, gen_opt_tf, disc_loss_tf, disc_opt_tf, x_ph, z_ph, latent_encoder_loss, encoder_optimizer\n):\n train_epoch = 10\n latent_encoding_length = z_ph.get_shape()[1]\n batch_size = 256\n # training-loop\n np.random.seed(int(time.time()))\n logging.info(\"Starting training\")\n\n for epoch in range(train_epoch):\n gen_losses = []\n disc_losses = []\n epoch_start_time = time.time()\n for minibatch_count in range(x_train.shape[0] // batch_size):\n # update discriminator\n x_ = x_train[minibatch_count * batch_size : (minibatch_count + 1) * batch_size]\n z_ = np.random.normal(0, 1, (batch_size, latent_encoding_length))\n\n loss_d_, _ = sess.run([disc_loss_tf, disc_opt_tf], {x_ph: x_, z_ph: z_})\n disc_losses.append(loss_d_)\n\n # update generator\n z_ = np.random.normal(0, 1, (batch_size, latent_encoding_length))\n loss_g_, _ = sess.run([gen_loss, gen_opt_tf], {z_ph: z_, x_ph: x_})\n gen_losses.append(loss_g_)\n\n epoch_end_time = time.time()\n per_epoch_ptime = epoch_end_time - epoch_start_time\n logging.info(\n \"[{0}/{1}] - epoch_time: {2} loss_discriminator: {3}, loss_generator: {4}\".format(\n (epoch + 1),\n train_epoch,\n round(per_epoch_ptime, 2),\n round(np.mean(disc_losses), 2),\n round(np.mean(gen_losses), 2),\n )\n )\n\n # Training inverse gan encoder\n for epoch in range(train_epoch):\n encoder_losses = []\n epoch_start_time = time.time()\n for minibatch_count in range(x_train.shape[0] // batch_size):\n z_ = np.random.normal(0, 1, (batch_size, latent_encoding_length))\n loss_encoder_value, _ = sess.run([latent_encoder_loss, encoder_optimizer], {z_ph: z_})\n encoder_losses.append(loss_encoder_value)\n\n epoch_end_time = time.time()\n per_epoch_ptime = epoch_end_time - epoch_start_time\n logging.info(\n \"[{0}/{1}] - epoch_time: {2} loss_encoder: {3}\".format(\n (epoch + 1), train_epoch, per_epoch_ptime, round(np.mean(encoder_losses), 3)\n )\n )\n\n logging.info(\"Training finish!... save training results\")\n\n\ndef build_gan_graph(learning_rate, latent_encoding_length, batch_size=None):\n if batch_size is None:\n batch_size = 200\n # INPUT VARIABLES\n x_ph = tf.placeholder(tf.float32, shape=(None, 28, 28, 1))\n z_ph = tf.placeholder(tf.float32, shape=(None, latent_encoding_length), name=\"z_input\")\n\n # Building Generator and Discriminator\n generator_tf = create_generator_layers(z_ph)\n disc_real_tf, disc_real_logits_tf = create_discriminator_layers(x_ph)\n disc_fake_tf, disc_fake_logits_tf = create_discriminator_layers(generator_tf)\n\n # CREATE LOSSES\n disc_loss_real_tf = tf.losses.sigmoid_cross_entropy(\n multi_class_labels=tf.ones([batch_size, 1, 1, 1]), logits=disc_real_logits_tf\n )\n\n disc_loss_fake_tf = tf.losses.sigmoid_cross_entropy(\n multi_class_labels=tf.zeros([batch_size, 1, 1, 1]), logits=disc_fake_logits_tf\n )\n disc_loss_tf = disc_loss_real_tf + disc_loss_fake_tf\n\n gen_loss = tf.losses.sigmoid_cross_entropy(\n multi_class_labels=tf.ones([batch_size, 1, 1, 1]), logits=disc_fake_logits_tf\n )\n\n # CREATE OPTIMIZERS\n # We only want generator variables to be trained when running the generator and not discriminator variables etc.\n trainable_variables = tf.trainable_variables()\n disc_trainable_vars = [var for var in trainable_variables if var.name.startswith(\"discriminator\")]\n gen_trainable_vars = [var for var in trainable_variables if var.name.startswith(\"generator\")]\n\n # CREATE OPTIMIZERS\n disc_opt_tf = tf.train.AdamOptimizer(learning_rate, beta1=0.5).minimize(disc_loss_tf, var_list=disc_trainable_vars)\n gen_opt_tf = tf.train.AdamOptimizer(learning_rate, beta1=0.5).minimize(gen_loss, var_list=gen_trainable_vars)\n\n return generator_tf, z_ph, gen_loss, gen_opt_tf, disc_loss_tf, disc_opt_tf, x_ph\n\n\ndef build_inverse_gan_graph(learning_rate, generator_tf, z_ph, latent_encoding_length):\n z_ts = create_encoder_layers2(generator_tf, net_dim=64, latent_dim=latent_encoding_length)\n\n # Reusing exisint nodes with a different input in order to call at inference time\n image_to_encode_ph = tf.placeholder(tf.float32, shape=(None, 28, 28, 1), name=\"image_to_encode_input\")\n encoder_tf = create_encoder_layers2(image_to_encode_ph, net_dim=64, latent_dim=latent_encoding_length)\n\n # CREATE LOSSES\n latent_encoder_loss = tf.reduce_mean(tf.square(z_ts - z_ph), axis=[1])\n\n # CREATE OPTIMIZERS\n trainable_variables = tf.trainable_variables()\n encoder_trainable_vars = [var for var in trainable_variables if var.name.startswith(\"encoder\")]\n\n encoder_optimizer = tf.train.AdamOptimizer(learning_rate, beta1=0.5).minimize(\n latent_encoder_loss, var_list=encoder_trainable_vars\n )\n\n return encoder_tf, image_to_encode_ph, latent_encoder_loss, encoder_optimizer\n\n\ndef main():\n model_name = \"model-dcgan\"\n\n root = \"models/inverseGAN/\"\n\n if not os.path.isdir(root):\n os.mkdir(root)\n\n model_path = root\n\n # STEP 0\n logging.info(\"Loading a Dataset\")\n (x_train_original, y_train_original), (_, _), _, _ = load_mnist()\n\n batch_size = 256\n\n (x_train, y_train) = (x_train_original[:batch_size], y_train_original[:batch_size])\n\n lr = 0.0002\n latent_enc_len = 128\n\n gen_tf, z_ph, gen_loss, gen_opt_tf, disc_loss_tf, disc_opt_tf, x_ph = build_gan_graph(\n lr, latent_enc_len, batch_size\n )\n enc_tf, image_to_enc_ph, latent_enc_loss, enc_opt = build_inverse_gan_graph(lr, gen_tf, z_ph, latent_enc_len)\n\n sess = tf.Session()\n sess.run(tf.global_variables_initializer())\n\n train_models(sess, x_train_original, gen_loss, gen_opt_tf, disc_loss_tf, disc_opt_tf, x_ph, z_ph, latent_enc_loss, enc_opt)\n\n saver = tf.train.Saver()\n saver.save(sess, os.path.join(model_path, model_name))\n\n sess.close()\n\n\nif __name__ == \"__main__\":\n main()\n"
] | [
[
"tensorflow.zeros",
"tensorflow.GPUOptions",
"tensorflow.layers.conv2d_transpose",
"tensorflow.train.AdamOptimizer",
"numpy.mean",
"tensorflow.get_default_graph",
"tensorflow.layers.batch_normalization",
"tensorflow.Session",
"tensorflow.square",
"tensorflow.trainable_variables",
"tensorflow.train.Saver",
"tensorflow.layers.conv2d",
"tensorflow.nn.sigmoid",
"tensorflow.image.resize_images",
"tensorflow.placeholder",
"tensorflow.nn.tanh",
"tensorflow.global_variables_initializer",
"tensorflow.nn.leaky_relu",
"tensorflow.multiply",
"tensorflow.reshape",
"tensorflow.ones",
"tensorflow.contrib.layers.fully_connected",
"numpy.random.normal",
"tensorflow.variable_scope"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.10"
]
}
] |
FPSG-UIUC/synthCT | [
"9debc66a5097280f57b4c6b7d88a4cd95eb9494c"
] | [
"synthesis/synthcomp.py"
] | [
"# Implements strategies for choosing components for synthesis based on the\n# specification to synthesize\n\nfrom collections import defaultdict\nimport random\n\nimport networkx as nx\n\nfrom loguru import logger\nfrom sklearn.neighbors import NearestNeighbors\n\nfrom learning.embedding import Embedding\nfrom semantics.typing import Typing\n\n\nclass CompSelector:\n def __init__(self, isa):\n pass\n\n def components_for(self, inst, count=32):\n raise NotImplementedError\n\n\nclass SimpleSelector(CompSelector):\n def __init__(self, isa):\n self.sems = isa\n\n def components_for(self, inst, count=32):\n components = []\n for comp in self.sems:\n # Ensure spec/inst is not in components\n if comp.name == inst.name:\n continue\n components.append(comp)\n return components\n\n\nclass KNNSelector(CompSelector):\n def __init__(self, isa):\n self.sems = isa\n\n self.gs = []\n self.keys = []\n\n for instsem in self.sems:\n reg_graph = nx.DiGraph()\n for reg, sem in instsem.iter_output_regs():\n reg_graph = nx.union(reg_graph, sem.sem, rename=(None, f\"{reg}-\"))\n\n if reg_graph:\n self.gs.append(reg_graph)\n self.keys.append([sem.name, \"REG\"])\n\n flag_graph = nx.DiGraph()\n for flag, sem in instsem.iter_output_flags():\n flag_graph = nx.union(flag_graph, sem.sem, rename=(None, f\"{flag}-\"))\n\n if flag_graph:\n self.gs.append(flag_graph)\n self.keys.append([sem.name, \"FLAG\"])\n\n self.eb = Embedding.embed(self.keys, self.gs)\n self.nn = NearestNeighbors()\n self.nn.fit([y for _, y in self.eb.get_all()])\n\n def components_for(self, inst, count=32, mode=\"REG\"):\n # Check if there are enough components\n if count > len(self.keys):\n logger.warning(\n f\"Requested for more subcomponents than available: \"\n f\"Choosing {len(self.keys)} instead of {count}\"\n )\n count = len(self.keys)\n\n # Here, we get some number > count to account for the same\n # instruction being chosen multiple times due to multiple output\n # registers\n knn = None\n\n #max_nodes = None\n #for reg, sem in inst.iter_output_regs():\n #if not max_nodes:\n #max_nodes = reg\n #else:\n #cur = len(list(sem.sem.nodes()))\n #maxn = len(list(inst.sems[max_nodes].sem.nodes()))\n #if cur > maxn:\n #max_nodes = reg\n\n #if max_nodes is None:\n #logger.warning(f\"No output registers for {inst.name}?\")\n #for reg, sem in inst.iter_output_flags():\n #if not max_nodes:\n #max_nodes = reg\n #else:\n #cur = len(list(sem.sem.nodes()))\n #maxn = len(list(inst.sems[max_nodes].sem.nodes()))\n #if cur > maxn:\n #max_nodes = reg\n #if max_nodes is None:\n #logger.warning(f\"No output flags for {inst.name}?\")\n #return []\n\n key = [inst.name, mode]\n knn = self.nn.kneighbors([self.eb.get_embedding(key)], (count + 1) * 6)\n\n assert knn is not None, \"No output registers?\"\n\n cnames = []\n for j, idx in enumerate(knn[1][0]):\n name, reg = self.eb.keys[idx]\n if name in cnames:\n continue\n # Do not select the synthesis spec instruction in the components\n if name == inst.name:\n continue\n\n cnames.append(name)\n # Check if we reached threshold number of keys\n if len(cnames) >= count:\n break\n\n assert len(cnames) == count, \"Incorrect number of components chosen?\"\n\n components = [None] * count\n for sem in self.sems:\n if sem.name in cnames:\n components[cnames.index(sem.name)] = sem\n\n return components\n\n\nclass JaccardSelector(CompSelector):\n def __init__(self, isa):\n self.sems = isa\n self.set_map = dict()\n self.sets = []\n\n self._compute_sets(isa)\n\n def _compute_sets(self, isa):\n for idx, inst in enumerate(isa):\n # Calculate the set for register outputs\n current = defaultdict(lambda: 0)\n for reg, sem in inst.iter_output_regs():\n for node in sem.sem.nodes():\n nd = sem.node_data(node, \"data\")\n nt = sem.node_data(node, Typing.KEY)\n label = f\"({nd}:{nt})\"\n current[label] += 1\n self.sets.append(current)\n self.set_map[(sem.name, \"REG\")] = 2 * idx\n\n # Calculate set for flag outputs\n current = defaultdict(lambda: 0)\n for flag, sem in inst.iter_output_flags():\n for node in sem.sem.nodes():\n nd = sem.node_data(node, \"data\")\n nt = sem.node_data(node, Typing.KEY)\n label = f\"({nd}:{nt})\"\n current[label] += 1\n self.sets.append(current)\n self.set_map[(sem.name, \"FLAG\")] = 2 * idx + 1\n\n def _compute_generalized_jaccard(self, idx1, idx2):\n set_1 = self.sets[idx1]\n set_2 = self.sets[idx2]\n\n all_keys = set(set_1.keys()).union(set(set_2.keys()))\n\n num = 0.0\n denom = 0.0\n\n for key in all_keys:\n v1 = set_1[key]\n v2 = set_2[key]\n num += min(v1, v2)\n denom += max(v1, v2)\n\n return float(num) / float(denom)\n\n def components_for(self, inst, count=32, mode=\"REG\"):\n scores = dict()\n current = self.set_map[(inst.name, mode)]\n for k, v in self.set_map.items():\n if k[0] == inst.name:\n continue\n scores[k] = self._compute_generalized_jaccard(current, v)\n\n components = []\n selected = []\n for k, _ in sorted(scores.items(), key=lambda item: item[1], reverse=True):\n idx = self.set_map[k] // 2\n sem = self.sems[idx]\n # Avoid duplicates\n if sem.name not in selected:\n components.append(self.sems[idx])\n selected.append(sem.name)\n\n if len(components) < count:\n logger.warning(\"Selected less than requested number of components!\")\n return components\n\n return components[:count]\n\n\nclass RKNNSelector(KNNSelector):\n def __init__(self, isa):\n super().__init__(isa)\n\n def components_for(self, inst, count=18):\n components = super().components_for(inst, 30)\n # Randomly select count from returned components\n idxs = random.sample(range(0, len(components)), count)\n rcomps = []\n for idx in idxs:\n rcomps.append(components[idx])\n\n return rcomps\n\n\nclass StaticSelector(CompSelector):\n def __init__(self, isa):\n self.isa = isa\n\n self.static = {\n \"ROLQ-R64-ONE\": [\n \"CMPXCHGQ-R64-R64\",\n \"XORW-R16-R16\",\n \"INCQ-R64\",\n \"DECQ-R64\",\n \"XCHGB-R8-R8\",\n \"XCHGQ-R64-R64\",\n \"ROLQ-R64-CL\",\n \"MOVSBL-R32-R8\",\n \"ANDQ-R64-R64\",\n \"ORL-R32-R32\",\n \"BLSRQ-R64-R64\",\n \"NEGQ-R64\",\n \"XORL-R32-R32\",\n \"MOVSLQ-R64-R32\",\n \"MOVSBL-R32-RH\",\n ],\n \"SALQ-R64-CL\": [\n \"SHLQ-R64-CL\",\n \"SETPO-R8\",\n \"CMOVPOL-R32-R32\",\n \"SETNS-R8\",\n \"SBBQ-R64-R64\",\n \"CMPXCHGB-RH-RH\",\n \"SETNO-R8\",\n \"SARW-R16-CL\",\n \"IMULW-R16-R16\",\n \"SHRW-R16-CL\",\n \"SUBQ-R64-R64\",\n \"CMOVBL-R32-R32\",\n \"SHRQ-R64-CL\",\n \"SARQ-R64-ONE\",\n \"CMOVNPL-R32-R32\",\n \"SHLW-R16-CL\",\n \"RCRQ-R64-ONE\",\n \"SETNP-R8\",\n ],\n \"ROLQ-R64-CL\": [\n \"MOVQ-R64-R64\",\n \"ANDQ-R64-R64\",\n \"SUBQ-R64-R64\",\n \"SHRQ-R64-R64\",\n \"SHLQ-R64-R64\",\n \"ORQ-R64-R64\",\n ],\n }\n\n def components_for(self, inst, count=None):\n comps = []\n for sem in self.isa:\n if sem.name in self.static[inst.name]:\n comps.append(sem)\n\n return comps\n\n\nselector = {\n \"simple\": SimpleSelector,\n \"knn\": KNNSelector,\n \"rknn\": RKNNSelector,\n \"jaccard\": JaccardSelector,\n \"static\": StaticSelector,\n}\n"
] | [
[
"sklearn.neighbors.NearestNeighbors"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
pbielak/graph-barlow-twins | [
"f8e20134afed4f17ffcecf8f48764df362ffdcad"
] | [
"gssl/transductive_model_arxiv.py"
] | [
"from pl_bolts.optimizers.lr_scheduler import LinearWarmupCosineAnnealingLR\nimport torch\nfrom torch import nn\nfrom torch_geometric import nn as tgnn\n\nfrom gssl.loss import get_loss\nfrom gssl.transductive_model import Model\n\n\nclass ArxivModel(Model):\n\n def __init__(\n self,\n feature_dim: int,\n emb_dim: int,\n loss_name: str,\n p_x: float,\n p_e: float,\n lr_base: float,\n total_epochs: int,\n warmup_epochs: int,\n ):\n self._device = torch.device(\n \"cuda\" if torch.cuda.is_available() else \"cpu\"\n )\n\n self._encoder = ThreeLayerGCNEncoder(\n in_dim=feature_dim, out_dim=emb_dim\n ).to(self._device)\n\n self._loss_fn = get_loss(loss_name=loss_name)\n\n self._optimizer = torch.optim.AdamW(\n params=self._encoder.parameters(),\n lr=lr_base,\n weight_decay=1e-5,\n )\n self._scheduler = LinearWarmupCosineAnnealingLR(\n optimizer=self._optimizer,\n warmup_epochs=warmup_epochs,\n max_epochs=total_epochs,\n )\n\n self._p_x = p_x\n self._p_e = p_e\n\n self._total_epochs = total_epochs\n\n self._use_pytorch_eval_model = True\n\n\nclass ThreeLayerGCNEncoder(nn.Module):\n\n def __init__(self, in_dim: int, out_dim: int):\n super().__init__()\n\n self._conv1 = tgnn.GCNConv(in_dim, out_dim)\n self._conv2 = tgnn.GCNConv(out_dim, out_dim)\n self._conv3 = tgnn.GCNConv(out_dim, out_dim)\n\n self._bn1 = nn.BatchNorm1d(out_dim, momentum=0.01)\n self._bn2 = nn.BatchNorm1d(out_dim, momentum=0.01)\n\n self._act1 = nn.PReLU()\n self._act2 = nn.PReLU()\n\n def forward(self, x, edge_index):\n x = self._conv1(x, edge_index)\n x = self._bn1(x)\n x = self._act1(x)\n\n x = self._conv2(x, edge_index)\n x = self._bn2(x)\n x = self._act2(x)\n\n x = self._conv3(x, edge_index)\n\n return x\n"
] | [
[
"torch.nn.BatchNorm1d",
"torch.nn.PReLU",
"torch.cuda.is_available"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
prajjwal1/fluence2 | [
"f7353f4947ac4712ecd1df34e97df27d83060f13"
] | [
"tests/test_optim.py"
] | [
"import unittest\n\nimport torch\nfrom torch import nn\n\nfrom fluence.optim import Lamb, Lookahead\n\nclass Test_Optim(unittest.TestCase):\n def test_lookahead(self):\n model = nn.Linear(8, 8)\n base_optim = torch.optim.Adam(model.parameters())\n optim = Lookahead(base_optim, k=5, alpha=0.8)\n output = model(torch.rand(128, 3, 8, 8))\n optim.step()\n\n def test_lamb(self):\n model = nn.Linear(8, 8)\n optim = Lamb(model.parameters())\n output = model(torch.rand(128, 3, 8, 8))\n optim.step()\n\n\nif __name__ == \"__main__\":\n unittest.main()\n"
] | [
[
"torch.nn.Linear",
"torch.rand"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
damiankarol7/python101 | [
"1978a9402a8fb0f20c4ca7bd542cb8d7d4501b9b"
] | [
"docs/pylab/rbrowna01.py"
] | [
"#! /usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nimport numpy as np\nimport random\n\nn = int(input(\"Ile ruchów? \"))\nx = y = 0\n\nfor i in range(0, n):\n # wylosuj kąt i zamień go na radiany\n rad = float(random.randint(0, 360)) * np.pi / 180\n x = x + np.cos(rad) # wylicz współrzędną x\n y = y + np.sin(rad) # wylicz współrzędną y\n print(x, y)\n\n# oblicz wektor końcowego przesunięcia\ns = np.sqrt(x**2 + y**2)\nprint(\"Wektor przesunięcia:\", s)\n"
] | [
[
"numpy.cos",
"numpy.sqrt",
"numpy.sin"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
souvikg10/rasa-nlu-examples | [
"553a6461949f57232601e778fccdff74a488e0cd"
] | [
"rasa_nlu_examples/scikit/classifier.py"
] | [
"import pathlib\nimport numpy as np\n\nfrom sklearn.base import BaseEstimator, ClassifierMixin\nfrom rasa.cli.utils import get_validated_path\nfrom rasa.model import get_model, get_model_subdirectories\nfrom rasa.core.interpreter import RasaNLUInterpreter\n\n\ndef load_interpreter(model_dir, model):\n path_str = str(pathlib.Path(model_dir) / model)\n model = get_validated_path(path_str, \"model\")\n model_path = get_model(model)\n _, nlu_model = get_model_subdirectories(model_path)\n return RasaNLUInterpreter(nlu_model)\n\n\nclass RasaClassifier(BaseEstimator, ClassifierMixin):\n \"\"\"\n The RasaClassifier takes a pretrained Rasa model and turns it into a scikit-learn compatible estimator.\n It expects text as input and it will predict an intent class.\n\n Usage:\n\n ```python\n from rasa_nlu_examples.scikit import RasaClassifier\n\n mod = RasaClassifier(model_path=\"path/to/model.tar.gz\")\n mod.predict([\"hello there\", \"are you a bot?\"])\n mod.predict_proba([\"hello there\", \"are you a bot?\"])\n ```\n \"\"\"\n\n def __init__(self, model_path):\n self.model_path = model_path\n folder = str(pathlib.Path(self.model_path).parents[0])\n file = str(pathlib.Path(self.model_path).parts[-1])\n self.interpreter = load_interpreter(folder, file)\n self.class_names_ = [\n i[\"name\"] for i in self.fetch_info_from_message(\"hello\")[\"intent_ranking\"]\n ]\n\n def fit(self, X, y):\n return self\n\n def fetch_info_from_message(self, text_input):\n \"\"\"\n Fetch all the info from a single text input. Can be used to also retreive entities.\n\n Usage:\n\n ```python\n from rasa_nlu_examples.scikit import RasaClassifier\n\n mod = RasaClassifier(model_path=\"path/to/model.tar.gz\")\n mod.fetch_info_from_message(\"hello there\")\n ```\n \"\"\"\n return self.interpreter.interpreter.parse(text_input)\n\n def predict(self, X):\n \"\"\"\n Makes a class prediction, scikit-style.\n\n Usage:\n\n ```python\n from rasa_nlu_examples.scikit import RasaClassifier\n\n mod = RasaClassifier(model_path=\"path/to/model.tar.gz\")\n mod.predict([\"hello there\", \"are you a bot?\"])\n ```\n \"\"\"\n return np.array([self.fetch_info_from_message(x)[\"intent\"][\"name\"] for x in X])\n\n def predict_proba(self, X):\n \"\"\"\n Makes a class proba prediction, scikit-style.\n\n Usage:\n\n ```python\n from rasa_nlu_examples.scikit import RasaClassifier\n\n mod = RasaClassifier(model_path=\"path/to/model.tar.gz\")\n mod.predict_proba([\"hello there\", \"are you a bot?\"])\n ```\n \"\"\"\n result = []\n for x in X:\n ranking = self.fetch_info_from_message(x)[\"intent_ranking\"]\n ranking_dict = {i[\"name\"]: i[\"confidence\"] for i in ranking}\n result.append([ranking_dict[n] for n in self.class_names_])\n return np.array(result)\n"
] | [
[
"numpy.array"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
rdadolf/fathom | [
"1dc013d055e59fb09c886ae3a667084119deac5c"
] | [
"fathom/speech/speech.py"
] | [
"#!/usr/bin/env python\n\nimport numpy as np\nimport tensorflow as tf\n\n#from tensorflow.models.rnn import rnn, rnn_cell\nfrom tensorflow.python.ops import functional_ops\nfrom tensorflow.python.ops import variable_scope as vs\nfrom tensorflow.contrib.rnn.python.ops.rnn_cell import _linear\n\nfrom fathom.nn import NeuralNetworkModel, default_runstep\n\nfrom .preproc import load_timit, timit_hdf5_filepath\nfrom .phoneme import index2phoneme_dict\n\n\ndef clipped_relu(inputs, clip=20):\n \"\"\"Similar to tf.nn.relu6, but can clip at 20 as in Deep Speech.\"\"\"\n return tf.minimum(tf.nn.relu(inputs), clip)\n\n\nclass ClippedReluRNNCell(tf.contrib.rnn.RNNCell):\n \"\"\"Basic RNN cell with clipped ReLU rather than tanh activation.\"\"\"\n\n def __init__(self, num_units, input_size=None):\n self._num_units = num_units\n\n @property\n def state_size(self):\n return self._num_units\n\n @property\n def output_size(self):\n return self._num_units\n\n def __call__(self, inputs, state, scope=None):\n \"\"\"Basic RNN: output = new_state = clipped_relu(W * input + U * state + B).\"\"\"\n with vs.variable_scope(scope or type(self).__name__):\n output = clipped_relu(_linear([inputs, state], self._num_units, True))\n return output, output\n\n\n# TODO: show label error rate\n# TODO: avoid labels and blank off-by-one error due to padding zeros\nclass Speech(NeuralNetworkModel):\n \"\"\"RNN for speech recognition.\"\"\"\n def __init__(self, device=None, init_options=None):\n super(Speech,self).__init__(device=device, init_options=init_options)\n\n #def inference(self, inputs, n_hidden=2048):\n def build_inference(self, inputs, n_hidden=1024):\n with self.G.as_default():\n self.n_hidden = n_hidden\n\n # Architecture of Deep Speech [Hannun et al. 2014]\n outputs_1 = self.mlp_layer(inputs, self.n_coeffs, self.n_hidden)\n outputs_2 = self.mlp_layer(outputs_1, self.n_hidden, self.n_hidden)\n outputs_3 = self.mlp_layer(outputs_2, self.n_hidden, self.n_hidden)\n outputs_4 = self.bidirectional_layer(outputs_3, n_input=self.n_hidden, n_hidden=self.n_hidden, n_output=self.n_hidden)\n outputs_5 = self.mlp_layer(outputs_3, self.n_hidden, self.n_labels)\n\n self._outputs = outputs_5\n\n # transpose in preparation for CTC loss\n self.logits_t = tf.transpose(self._outputs, perm=[1,0,2])\n\n return outputs_5\n\n @property\n def outputs(self):\n return self._outputs\n\n @property\n def loss(self):\n return self.loss_op\n\n def build_loss(self, logits, labels):\n with self.G.as_default():\n # NOTE: CTC does the softmax for us, according to the code\n\n # CTC loss requires sparse labels\n self.sparse_labels = self.ctc_label_dense_to_sparse(self.labels, self.seq_lens)\n\n # CTC\n self.loss_op = tf.nn.ctc_loss(\n inputs=self.logits_t,\n labels=self.sparse_labels,\n sequence_length=self.seq_lens\n )\n\n return self.loss_op\n\n def build_train(self, loss):\n # TODO: buckets\n with self.G.as_default():\n self.train_op = tf.train.GradientDescentOptimizer(learning_rate=0.01).minimize(loss)\n return self.train_op\n\n @property\n def train(self):\n return self.train_op\n\n def mlp_layer(self, inputs, n_input, n_output):\n with self.G.as_default():\n # layer sees inputs as (batch_size, max_time, n_input)\n W = tf.Variable(tf.zeros([n_input, n_output]))\n b = tf.Variable(tf.zeros([n_output]))\n\n W_batch_multiples = tf.constant([self.batch_size, 1, 1], dtype=tf.int32)\n W_batch = tf.tile(tf.expand_dims(W, 0), W_batch_multiples)\n\n # TODO: is tiling a bias vector over batch and frames correct?\n b_batch_multiples = tf.constant([self.batch_size, self.max_frames, 1], dtype=tf.int32)\n b_batch = tf.tile(tf.expand_dims(tf.expand_dims(b, 0), 0), b_batch_multiples)\n\n # TODO: change batch_matmul to an averaging reshape so that batching happens and dimensions are easier\n outputs = tf.add(tf.matmul(inputs, W_batch), b_batch)\n\n return clipped_relu(outputs)\n\n def bidirectional_layer(self, inputs, n_input, n_hidden, n_output):\n \"\"\"Bidirectional RNN layer.\"\"\"\n with self.G.as_default():\n fw_cell = ClippedReluRNNCell(n_hidden)\n bw_cell = ClippedReluRNNCell(n_hidden)\n\n # input shape: (batch_size, max_time, n_input)\n inputs = tf.transpose(inputs, perm=[1, 0, 2]) # permute max_time and batch_size\n inputs = tf.reshape(inputs, [-1, n_input]) # (max_time*batch_size, n_input)\n\n inputs = tf.split(axis=0, num_or_size_splits=self.max_frames, value=inputs) # max_time * (batch_size, n_hidden)\n\n # optional initial states\n istate_fw = tf.placeholder(\"float\", [None, n_hidden])\n istate_bw = tf.placeholder(\"float\", [None, n_hidden])\n\n # TODO: support both tanh (default) and clipped_relu\n outputs, _, _ = tf.contrib.rnn.static_bidirectional_rnn(fw_cell, bw_cell, inputs, initial_state_fw=istate_fw, initial_state_bw=istate_bw)\n\n # TODO: is this the right output?\n return outputs[-1]\n\n def ctc_label_dense_to_sparse( self, labels, label_lengths ):\n \"\"\"Mike Henry's implementation, with some minor modifications.\"\"\"\n with self.G.as_default():\n label_shape = tf.shape( labels )\n num_batches_tns = tf.stack( [label_shape[0]] )\n max_num_labels_tns = tf.stack( [label_shape[1]] )\n\n def range_less_than(previous_state, current_input):\n return tf.expand_dims( tf.range( label_shape[1] ), 0 ) < current_input\n\n init = tf.cast( tf.fill( max_num_labels_tns, 0 ), tf.bool )\n init = tf.expand_dims( init, 0 )\n dense_mask = functional_ops.scan(range_less_than, label_lengths , initializer=init, parallel_iterations=1)\n dense_mask = dense_mask[ :, 0, : ]\n\n label_array = tf.reshape( tf.tile( tf.range( 0, label_shape[1] ), num_batches_tns ), label_shape )\n label_ind = tf.boolean_mask( label_array, dense_mask )\n\n batch_array = tf.transpose( tf.reshape( tf.tile( tf.range( 0, label_shape[0] ), max_num_labels_tns ), tf.reverse( label_shape,[0]) ) )\n batch_ind = tf.boolean_mask( batch_array, dense_mask )\n\n indices = tf.transpose( tf.reshape( tf.concat( axis=0, values=[batch_ind, label_ind] ), [2,-1] ) )\n vals_sparse = tf.gather_nd( labels, indices )\n return tf.SparseTensor( tf.to_int64(indices), vals_sparse, tf.to_int64( label_shape ) )\n\n def build_hyperparameters(self):\n self.n_labels = 61 + 1 # add blank\n self.max_frames = 1566 # TODO: compute dynamically\n self.max_labels = 75\n self.n_coeffs = 26\n self.batch_size = 32\n if self.init_options:\n self.batch_size = self.init_options.get('batch_size', self.batch_size)\n\n def build_inputs(self):\n with self.G.as_default():\n # NOTE: ctc_loss requires a transpose\n # tf.transpose(inputs,perm=[1,0,2])\n self._inputs = tf.placeholder(tf.float32, [None, self.max_frames, self.n_coeffs], name=\"inputs\")\n\n @property\n def inputs(self):\n return self._inputs\n\n def build_labels(self):\n with self.G.as_default():\n self._labels = tf.placeholder(tf.int32, [None, self.max_labels], name=\"labels\")\n self.seq_lens = tf.placeholder(tf.int32, [None], name=\"seq_lens\")\n\n @property\n def labels(self):\n return self._labels\n\n def build(self):\n super(Speech, self).build()\n\n with self.G.as_default():\n self.decode_op = self.decoding()\n\n def load_data(self):\n self.train_spectrograms, self.train_labels, self.train_seq_lens = load_timit(timit_hdf5_filepath, train=True)\n # TODO: load test\n\n def get_random_batch(self):\n \"\"\"Get random batch from np.arrays (not tf.train.shuffle_batch).\"\"\"\n n_examples = self.train_spectrograms.shape[0]\n random_sample = np.random.randint(n_examples, size=self.batch_size)\n return self.train_spectrograms[random_sample, :, :], self.train_labels[random_sample, :], self.train_seq_lens[random_sample]\n\n def decoding(self):\n \"\"\"Predict labels from learned sequence model.\"\"\"\n # TODO: label error rate on validation set\n decoded, _ = tf.nn.ctc_greedy_decoder(self.logits_t, self.seq_lens)\n sparse_decode_op = decoded[0] # single-element list\n self.decode_op = tf.sparse_to_dense(sparse_decode_op.indices, sparse_decode_op.dense_shape, sparse_decode_op.values)\n return self.decode_op\n\n def run(self, runstep=None, n_steps=1, *args, **kwargs):\n print(\"Loading spectrogram features...\")\n self.load_data()\n\n with self.G.as_default():\n print('Starting run...')\n for _ in range(n_steps):\n spectrogram_batch, label_batch, seq_len_batch = self.get_random_batch()\n\n if not self.forward_only:\n _, _ = runstep(self.session,\n [self.train_op, self.loss_op],\n feed_dict={self.inputs: spectrogram_batch, self.labels: label_batch, self.seq_lens: seq_len_batch})\n else:\n # run forward-only on train batch\n _ = runstep(self.session,\n self.outputs,\n feed_dict={self.inputs: spectrogram_batch, self.labels: label_batch, self.seq_lens: seq_len_batch})\n\n # decode the same batch, for debugging\n decoded = self.session.run(self.decode_op,\n feed_dict={self.inputs: spectrogram_batch, self.labels: label_batch, self.seq_lens: seq_len_batch})\n\n # print some decoded examples\n if False:\n print(' '.join(self.labels2phonemes(decoded[0])))\n # TODO: fix dtypes in dataset (labels are accidentally floats right now)\n print(' '.join(self.labels2phonemes(np.array(label_batch[0,:], dtype=np.int32))))\n\n def labels2phonemes(self, decoded_labels):\n \"\"\"Convert a list of label indices to a list of corresponding phonemes.\"\"\"\n return [index2phoneme_dict[label] for label in decoded_labels]\n\nclass SpeechFwd(Speech):\n forward_only = True\n\nif __name__=='__main__':\n m = Speech()\n m.setup()\n m.run(runstep=default_runstep, n_steps=10)\n m.teardown()\n"
] | [
[
"tensorflow.concat",
"tensorflow.zeros",
"tensorflow.stack",
"numpy.random.randint",
"tensorflow.boolean_mask",
"tensorflow.to_int64",
"tensorflow.sparse_to_dense",
"tensorflow.nn.ctc_greedy_decoder",
"tensorflow.reverse",
"tensorflow.matmul",
"tensorflow.fill",
"tensorflow.gather_nd",
"tensorflow.shape",
"tensorflow.placeholder",
"tensorflow.contrib.rnn.static_bidirectional_rnn",
"tensorflow.train.GradientDescentOptimizer",
"tensorflow.split",
"numpy.array",
"tensorflow.nn.ctc_loss",
"tensorflow.contrib.rnn.python.ops.rnn_cell._linear",
"tensorflow.nn.relu",
"tensorflow.transpose",
"tensorflow.constant",
"tensorflow.range",
"tensorflow.python.ops.functional_ops.scan",
"tensorflow.reshape",
"tensorflow.expand_dims"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.10"
]
}
] |
voschezang/pattern-recognition | [
"1d6a801deba729fc99a6960e2180d0ee204d0c35"
] | [
"src/test_midi2.py"
] | [
"import os, numpy as np\nif __name__ == \"__main__\":\n np.random.seed(333)\n print(os.getcwd())\n\nimport mido # , rtmidi, rtmidi_\nimport matplotlib.pyplot as plt\n\nimport config\nimport setup\nimport midi\nimport midi.decode\nfrom midi import generators as g\nfrom utils import utils, io, plot\n\nif __name__ == \"__main__\":\n context = setup.init()\n n = 10\n multiTrack = True\n reduce_dims = midi.ReduceDimsOptions.GLOBAL\n reduce_dims = midi.ReduceDimsOptions.MIDIFILE\n dim4 = True\n dirname = 'drum_midi'\n x_train, labels = setup.import_data(\n context, n, multiTrack, reduce_dims, dim4, dirname, r=True)\n config.info('x_train', x_train.shape)\n # context, x_train, labels = data.import_data(data.init(), n, multiTrack=True)\n # config.info('arrays2', x_train.shape)\n\n # dn = config.dataset_dir\n # io.export_midifile(mid, dn + 'cycle.mid')\n print(labels[0])\n plot.single(x_train[0, :80, :, 0])\n\n print('\\n\\n\\n-MIDI-\\n')\n f = 5\n # result = g.example(context)\n # result = g.gen_data(context, 2, min_f=f, max_f=f)\n result, params = g.gen_data_complex(\n context,\n 1,\n min_f=f,\n max_f=f + 1,\n n_polyrythms=1,\n n_channels=3,\n d_phase=False,\n multiTrack=True)\n config.info('result', result.shape)\n # print(' 000 ', result.shape, result[:10, :])\n print(type(result))\n print('result', result.shape)\n # print(result[0, :5])\n\n a = midi.MultiTrack.from_array(result[0])\n print(type(a))\n\n # midi.decode.track(context, result[0])\n # plot.single(result[0, :30])\n\n# fn = dn + '4-floor-120bpm.mid'\n# mid = io.import_midifile(fn)\n\n# mid = io.import_midifile(dn + 'song_export.mid')\n# mid = io.import_midifile(dn + 'examples/01 8th Cym.mid')\n\n# encoded = midi.encode(context, mid)\n# # encoded = x_train[0]\n# decoded = midi.decode_track(context, encoded)\n\n# m = decoded\n# print(type(m), m, encoded.shape)\n# print('1000 tick2second',\n# mido.tick2second(context.n_instances, context.ticks_per_beat,\n# context.tempo))\n# print('second2tick',\n# mido.second2tick(context.max_t, context.ticks_per_beat, context.tempo))\n# print(mid.length, m.length, context.max_t)\n\n# # for x in mid: print(x)\n# print(mid.filename)\n# io.export_midifile(m, dn + 'song_export_copy.mid')\n\n# print(m, m.tracks[0])\n# print(encoded.shape)\n"
] | [
[
"numpy.random.seed"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
SKKSaikia/bokeh | [
"f9a4013a3640da3c73fc49ed906f6d202a30a489"
] | [
"bokeh/core/properties.py"
] | [
"''' Properties are objects that can be assigned as class attributes on Bokeh\nmodels, to provide automatic serialization, validation, and documentation.\n\nThis documentation is broken down into the following sections:\n\n.. contents::\n :local:\n\nOverview\n--------\n\nThere are many property types defined in the module, for example ``Int`` to\nrepresent integral values, ``Seq`` to represent sequences (e.g. lists or\ntuples, etc.). Properties can also be combined: ``Seq(Float)`` represents\na sequence of floating point values.\n\nFor example, the following defines a model that has integer, string, and\nlist[float] properties:\n\n.. code-block:: python\n\n class SomeModel(Model):\n foo = Int\n bar = String(default=\"something\")\n baz = List(Float, help=\"docs for baz prop\")\n\nAs seen, properties can be declared as just the property type, e.g.\n``foo = Int``, in which case the properties are automatically instantiated\non new Model objects. Or the property can be instantiated on the class,\nand configured with default values and help strings.\n\nThe properties of this class can be initialized by specifying keyword\narguments to the initializer:\n\n.. code-block:: python\n\n m = SomeModel(foo=10, bar=\"a str\", baz=[1,2,3,4])\n\nBut also by setting the attributes on an instance:\n\n.. code-block:: python\n\n m.foo = 20\n\nAttempts to set a property to a value of the wrong type will\nresult in a ``ValueError`` exception:\n\n.. code-block:: python\n\n >>> m.foo = 2.3\n Traceback (most recent call last):\n\n << traceback omitted >>\n\n ValueError: expected a value of type Integral, got 2.3 of type float\n\nModels with properties know how to serialize themselves, to be understood\nby BokehJS. Additionally, any help strings provided on properties can be\neasily and automatically extracted with the Sphinx extensions in the\n:ref:`bokeh.sphinxext` module.\n\n\nBasic Properties\n----------------\n\n{basic_properties}\n\nContainer Properties\n--------------------\n\n{container_properties}\n\nDataSpec Properties\n-------------------\n\n{dataspec_properties}\n\nHelpers\n~~~~~~~\n\n.. autofunction:: field\n.. autofunction:: value\n\nSpecial Properties\n------------------\n\n.. autoclass:: Include\n.. autoclass:: Override\n\nValidation Control\n------------------\n\nBy default, Bokeh properties perform type validation on values. This helps to\nensure the consistency of any data exchanged between Python and JavaScript, as\nwell as provide detailed and immediate feedback to users if they attempt to\nset values of the wrong type. However, these type checks incur some overhead.\nIn some cases it may be desirable to turn off validation in specific places,\nor even entirely, in order to boost performance. The following API is available\nto control when type validation occurs.\n\n.. autoclass:: validate\n.. autofunction:: without_property_validation\n\n'''\nfrom __future__ import absolute_import, print_function\n\nimport logging\nlogger = logging.getLogger(__name__)\n\nimport base64\nimport collections\nfrom copy import copy\nimport datetime\nimport dateutil.parser\nfrom functools import wraps\nfrom importlib import import_module\nfrom io import BytesIO\nimport numbers\nimport re\n\nimport PIL.Image\nfrom six import string_types, iteritems\n\nfrom .. import colors\nfrom ..util.dependencies import import_optional\nfrom ..util.serialization import convert_datetime_type, convert_timedelta_type, decode_base64_dict, transform_column_source_data\nfrom ..util.string import nice_join, format_docstring\n\nfrom .property.bases import ContainerProperty, DeserializationError, ParameterizedProperty, Property, PrimitiveProperty\nfrom .property.containers import PropertyValueColumnData, PropertyValueDict, PropertyValueList\nfrom .property.descriptor_factory import PropertyDescriptorFactory\nfrom .property.descriptors import (BasicPropertyDescriptor, ColumnDataPropertyDescriptor, DataSpecPropertyDescriptor,\n UnitsSpecPropertyDescriptor)\nfrom . import enums\n\npd = import_optional('pandas')\n\nbokeh_bool_types = (bool,)\ntry:\n import numpy as np\n bokeh_bool_types += (np.bool8,)\nexcept ImportError:\n pass\n\nbokeh_integer_types = (numbers.Integral,)\n\nclass Bool(PrimitiveProperty):\n ''' Accept boolean values.\n\n Args:\n default (obj or None, optional) :\n A default value for attributes created from this property to\n have (default: None)\n\n help (str or None, optional) :\n A documentation string for this property. It will be automatically\n used by the :ref:`bokeh.sphinxext.bokeh_prop` extension when\n generating Spinx documentation. (default: None)\n\n serialized (bool, optional) :\n Whether attributes created from this property should be included\n in serialization (default: True)\n\n readonly (bool, optional) :\n Whether attributes created from this property are read-only.\n (default: False)\n\n Example:\n\n .. code-block:: python\n\n >>> class BoolModel(HasProps):\n ... prop = Bool(default=False)\n ...\n\n >>> m = BoolModel()\n\n >>> m.prop = True\n\n >>> m.prop = False\n\n >>> m.prop = 10 # ValueError !!\n\n '''\n _underlying_type = bokeh_bool_types\n\nclass Int(PrimitiveProperty):\n ''' Accept signed integer values.\n\n Args:\n default (int or None, optional) :\n A default value for attributes created from this property to\n have (default: None)\n\n help (str or None, optional) :\n A documentation string for this property. It will be automatically\n used by the :ref:`bokeh.sphinxext.bokeh_prop` extension when\n generating Spinx documentation. (default: None)\n\n serialized (bool, optional) :\n Whether attributes created from this property should be included\n in serialization (default: True)\n\n readonly (bool, optional) :\n Whether attributes created from this property are read-only.\n (default: False)\n\n Example:\n\n .. code-block:: python\n\n >>> class IntModel(HasProps):\n ... prop = Int()\n ...\n\n >>> m = IntModel()\n\n >>> m.prop = 10\n\n >>> m.prop = -200\n\n >>> m.prop = 10.3 # ValueError !!\n\n '''\n _underlying_type = bokeh_integer_types\n\nclass Float(PrimitiveProperty):\n ''' Accept floating point values.\n\n Args:\n default (float or None, optional) :\n A default value for attributes created from this property to\n have (default: None)\n\n help (str or None, optional) :\n A documentation string for this property. It will be automatically\n used by the :ref:`bokeh.sphinxext.bokeh_prop` extension when\n generating Spinx documentation. (default: None)\n\n serialized (bool, optional) :\n Whether attributes created from this property should be included\n in serialization (default: True)\n\n readonly (bool, optional) :\n Whether attributes created from this property are read-only.\n (default: False)\n\n Example:\n\n .. code-block:: python\n\n >>> class FloatModel(HasProps):\n ... prop = Float()\n ...\n\n >>> m = FloatModel()\n\n >>> m.prop = 10\n\n >>> m.prop = 10.3\n\n >>> m.prop = \"foo\" # ValueError !!\n\n\n '''\n _underlying_type = (numbers.Real,)\n\nclass Complex(PrimitiveProperty):\n ''' Accept complex floating point values.\n\n Args:\n default (complex or None, optional) :\n A default value for attributes created from this property to\n have (default: None)\n\n help (str or None, optional) :\n A documentation string for this property. It will be automatically\n used by the :ref:`bokeh.sphinxext.bokeh_prop` extension when\n generating Spinx documentation. (default: None)\n\n serialized (bool, optional) :\n Whether attributes created from this property should be included\n in serialization (default: True)\n\n readonly (bool, optional) :\n Whether attributes created from this property are read-only.\n (default: False)\n\n '''\n _underlying_type = (numbers.Complex,)\n\nclass String(PrimitiveProperty):\n ''' Accept string values.\n\n Args:\n default (string or None, optional) :\n A default value for attributes created from this property to\n have (default: None)\n\n help (str or None, optional) :\n A documentation string for this property. It will be automatically\n used by the :ref:`bokeh.sphinxext.bokeh_prop` extension when\n generating Spinx documentation. (default: None)\n\n serialized (bool, optional) :\n Whether attributes created from this property should be included\n in serialization (default: True)\n\n readonly (bool, optional) :\n Whether attributes created from this property are read-only.\n (default: False)\n\n Example:\n\n .. code-block:: python\n\n >>> class StringModel(HasProps):\n ... prop = String()\n ...\n\n >>> m = StringModel()\n\n >>> m.prop = \"foo\"\n\n >>> m.prop = 10.3 # ValueError !!\n\n >>> m.prop = [1, 2, 3] # ValueError !!\n\n '''\n _underlying_type = string_types\n\nclass FontSize(String):\n\n _font_size_re = re.compile(r\"^[0-9]+(.[0-9]+)?(%|em|ex|ch|ic|rem|vw|vh|vi|vb|vmin|vmax|cm|mm|q|in|pc|pt|px)$\", re.I)\n\n def validate(self, value, detail=True):\n super(FontSize, self).validate(value, detail)\n\n if isinstance(value, string_types):\n if len(value) == 0:\n msg = \"\" if not detail else \"empty string is not a valid font size value\"\n raise ValueError(msg)\n elif self._font_size_re.match(value) is None:\n msg = \"\" if not detail else \"%r is not a valid font size value\" % value\n raise ValueError(msg)\n\nclass Regex(String):\n ''' Accept strings that match a given regular expression.\n\n Args:\n default (string or None, optional) :\n A default value for attributes created from this property to\n have (default: None)\n\n help (str or None, optional) :\n A documentation string for this property. It will be automatically\n used by the :ref:`bokeh.sphinxext.bokeh_prop` extension when\n generating Spinx documentation. (default: None)\n\n serialized (bool, optional) :\n Whether attributes created from this property should be included\n in serialization (default: True)\n\n readonly (bool, optional) :\n Whether attributes created from this property are read-only.\n (default: False)\n\n Example:\n\n .. code-block:: python\n\n >>> class RegexModel(HasProps):\n ... prop = Regex(\"foo[0-9]+bar\")\n ...\n\n >>> m = RegexModel()\n\n >>> m.prop = \"foo123bar\"\n\n >>> m.prop = \"foo\" # ValueError !!\n\n >>> m.prop = [1, 2, 3] # ValueError !!\n\n '''\n def __init__(self, regex, default=None, help=None):\n self.regex = re.compile(regex)\n super(Regex, self).__init__(default=default, help=help)\n\n def __str__(self):\n return \"%s(%r)\" % (self.__class__.__name__, self.regex.pattern)\n\n def validate(self, value, detail=True):\n super(Regex, self).validate(value, detail)\n\n if not (value is None or self.regex.match(value) is not None):\n msg = \"\" if not detail else \"expected a string matching %r pattern, got %r\" % (self.regex.pattern, value)\n raise ValueError(msg)\n\nclass JSON(String):\n ''' Accept JSON string values.\n\n The value is transmitted and received by BokehJS as a *string*\n containing JSON content. i.e., you must use ``JSON.parse`` to unpack\n the value into a JavaScript hash.\n\n Args:\n default (string or None, optional) :\n A default value for attributes created from this property to\n have (default: None)\n\n help (str or None, optional) :\n A documentation string for this property. It will be automatically\n used by the :ref:`bokeh.sphinxext.bokeh_prop` extension when\n generating Spinx documentation. (default: None)\n\n serialized (bool, optional) :\n Whether attributes created from this property should be included\n in serialization (default: True)\n\n readonly (bool, optional) :\n Whether attributes created from this property are read-only.\n (default: False)\n\n '''\n def validate(self, value, detail=True):\n super(JSON, self).validate(value, detail)\n\n if value is None: return\n\n try:\n import json\n json.loads(value)\n except ValueError:\n msg = \"\" if not detail else \"expected JSON text, got %r\" % value\n raise ValueError(msg)\n\nclass Instance(Property):\n ''' Accept values that are instances of |HasProps|.\n\n\n\n '''\n def __init__(self, instance_type, default=None, help=None):\n if not isinstance(instance_type, (type,) + string_types):\n raise ValueError(\"expected a type or string, got %s\" % instance_type)\n\n from .has_props import HasProps\n if isinstance(instance_type, type) and not issubclass(instance_type, HasProps):\n raise ValueError(\"expected a subclass of HasProps, got %s\" % instance_type)\n\n self._instance_type = instance_type\n\n super(Instance, self).__init__(default=default, help=help)\n\n def __str__(self):\n return \"%s(%s)\" % (self.__class__.__name__, self.instance_type.__name__)\n\n @property\n def has_ref(self):\n return True\n\n @property\n def instance_type(self):\n if isinstance(self._instance_type, string_types):\n module, name = self._instance_type.rsplit(\".\", 1)\n self._instance_type = getattr(import_module(module, \"bokeh\"), name)\n\n return self._instance_type\n\n def from_json(self, json, models=None):\n if json is None:\n return None\n elif isinstance(json, dict):\n from ..model import Model\n if issubclass(self.instance_type, Model):\n if models is None:\n raise DeserializationError(\"%s can't deserialize without models\" % self)\n else:\n model = models.get(json[\"id\"])\n\n if model is not None:\n return model\n else:\n raise DeserializationError(\"%s failed to deserialize reference to %s\" % (self, json))\n else:\n attrs = {}\n\n for name, value in iteritems(json):\n prop_descriptor = self.instance_type.lookup(name).property\n attrs[name] = prop_descriptor.from_json(value, models)\n\n # XXX: this doesn't work when Instance(Superclass) := Subclass()\n # Serialization dict must carry type information to resolve this.\n return self.instance_type(**attrs)\n else:\n raise DeserializationError(\"%s expected a dict or None, got %s\" % (self, json))\n\n def validate(self, value, detail=True):\n super(Instance, self).validate(value, detail)\n\n if value is not None:\n if not isinstance(value, self.instance_type):\n msg = \"\" if not detail else \"expected an instance of type %s, got %s of type %s\" % (self.instance_type.__name__, value, type(value).__name__)\n raise ValueError(msg)\n\n def _may_have_unstable_default(self):\n # because the instance value is mutable\n return True\n\n def _sphinx_type(self):\n fullname = \"%s.%s\" % (self.instance_type.__module__, self.instance_type.__name__)\n return self._sphinx_prop_link() + \"( %s )\" % self._sphinx_model_link(fullname)\n\nclass Any(Property):\n ''' Accept all values.\n\n The ``Any`` property does not do any validation or transformation.\n\n Args:\n default (obj or None, optional) :\n A default value for attributes created from this property to\n have (default: None)\n\n help (str or None, optional) :\n A documentation string for this property. It will be automatically\n used by the :ref:`bokeh.sphinxext.bokeh_prop` extension when\n generating Spinx documentation. (default: None)\n\n serialized (bool, optional) :\n Whether attributes created from this property should be included\n in serialization (default: True)\n\n readonly (bool, optional) :\n Whether attributes created from this property are read-only.\n (default: False)\n\n Example:\n\n .. code-block:: python\n\n >>> class AnyModel(HasProps):\n ... prop = Any()\n ...\n\n >>> m = AnyModel()\n\n >>> m.prop = True\n\n >>> m.prop = 10\n\n >>> m.prop = 3.14\n\n >>> m.prop = \"foo\"\n\n >>> m.prop = [1, 2, 3]\n\n '''\n\nclass AnyRef(Property):\n ''' Accept all values and force reference discovery. '''\n\n @property\n def has_ref(self):\n return True\n\nclass Interval(ParameterizedProperty):\n ''' Accept numeric values that are contained within a given interval.\n\n Args:\n interval_type (numeric property):\n numeric types for the range, e.g. ``Int``, ``Float``\n\n start (number) :\n A minimum allowable value for the range. Values less than\n ``start`` will result in validation errors.\n\n end (number) :\n A maximum allowable value for the range. Values greater than\n ``end`` will result in validation errors.\n\n Example:\n\n .. code-block:: python\n\n >>> class RangeModel(HasProps):\n ... prop = Range(Float, 10, 20)\n ...\n\n >>> m = RangeModel()\n\n >>> m.prop = 10\n\n >>> m.prop = 20\n\n >>> m.prop = 15\n\n >>> m.prop = 2 # ValueError !!\n\n >>> m.prop = 22 # ValueError !!\n\n >>> m.prop = \"foo\" # ValueError !!\n\n '''\n def __init__(self, interval_type, start, end, default=None, help=None):\n self.interval_type = self._validate_type_param(interval_type)\n # Make up a property name for validation purposes\n self.interval_type.validate(start)\n self.interval_type.validate(end)\n self.start = start\n self.end = end\n super(Interval, self).__init__(default=default, help=help)\n\n def __str__(self):\n return \"%s(%s, %r, %r)\" % (self.__class__.__name__, self.interval_type, self.start, self.end)\n\n @property\n def type_params(self):\n return [self.interval_type]\n\n def validate(self, value, detail=True):\n super(Interval, self).validate(value, detail)\n\n if not (value is None or self.interval_type.is_valid(value) and value >= self.start and value <= self.end):\n msg = \"\" if not detail else \"expected a value of type %s in range [%s, %s], got %r\" % (self.interval_type, self.start, self.end, value)\n raise ValueError(msg)\n\nclass Byte(Interval):\n ''' Accept integral byte values (0-255).\n\n Example:\n\n .. code-block:: python\n\n >>> class ByteModel(HasProps):\n ... prop = Byte(default=0)\n ...\n\n >>> m = ByteModel()\n\n >>> m.prop = 255\n\n >>> m.prop = 256 # ValueError !!\n\n >>> m.prop = 10.3 # ValueError !!\n\n '''\n def __init__(self, default=0, help=None):\n super(Byte, self).__init__(Int, 0, 255, default=default, help=help)\n\nclass Either(ParameterizedProperty):\n ''' Accept values according to a sequence of other property types.\n\n Example:\n\n .. code-block:: python\n\n >>> class EitherModel(HasProps):\n ... prop = Either(Bool, Int, Auto)\n ...\n\n >>> m = EitherModel()\n\n >>> m.prop = True\n\n >>> m.prop = 10\n\n >>> m.prop = \"auto\"\n\n >>> m.prop = 10.3 # ValueError !!\n\n >>> m.prop = \"foo\" # ValueError !!\n\n '''\n\n def __init__(self, tp1, tp2, *type_params, **kwargs):\n self._type_params = list(map(self._validate_type_param, (tp1, tp2) + type_params))\n help = kwargs.get(\"help\")\n def choose_default():\n return self._type_params[0]._raw_default()\n default = kwargs.get(\"default\", choose_default)\n super(Either, self).__init__(default=default, help=help)\n self.alternatives = []\n for tp in self._type_params:\n self.alternatives.extend(tp.alternatives)\n\n # TODO (bev) get rid of this?\n def __or__(self, other):\n return self.__class__(*(self.type_params + [other]), default=self._default, help=self.help)\n\n def __str__(self):\n return \"%s(%s)\" % (self.__class__.__name__, \", \".join(map(str, self.type_params)))\n\n @property\n def type_params(self):\n return self._type_params\n\n def from_json(self, json, models=None):\n for tp in self.type_params:\n try:\n return tp.from_json(json, models)\n except DeserializationError:\n pass\n else:\n raise DeserializationError(\"%s couldn't deserialize %s\" % (self, json))\n\n def transform(self, value):\n for param in self.type_params:\n try:\n return param.transform(value)\n except ValueError:\n pass\n\n raise ValueError(\"Could not transform %r\" % value)\n\n def validate(self, value, detail=True):\n super(Either, self).validate(value, detail)\n\n if not (value is None or any(param.is_valid(value) for param in self.type_params)):\n msg = \"\" if not detail else \"expected an element of either %s, got %r\" % (nice_join(self.type_params), value)\n raise ValueError(msg)\n\n # TODO (bev) implement this\n # def _may_have_unstable_default(self):\n # return any(tp._may_have_unstable_default() for tp in self.type_params)\n\n def _sphinx_type(self):\n return self._sphinx_prop_link() + \"( %s )\" % \", \".join(x._sphinx_type() for x in self.type_params)\n\nclass Enum(String):\n ''' Accept values from enumerations.\n\n The first value in enumeration is used as the default value, unless the\n ``default`` keyword argument is used.\n\n See :ref:`bokeh.core.enums` for more information.\n\n '''\n def __init__(self, enum, *values, **kwargs):\n if not (not values and isinstance(enum, enums.Enumeration)):\n enum = enums.enumeration(enum, *values)\n\n self._enum = enum\n\n default = kwargs.get(\"default\", enum._default)\n help = kwargs.get(\"help\")\n\n super(Enum, self).__init__(default=default, help=help)\n\n def __str__(self):\n return \"%s(%s)\" % (self.__class__.__name__, \", \".join(map(repr, self.allowed_values)))\n\n @property\n def allowed_values(self):\n return self._enum._values\n\n def validate(self, value, detail=True):\n super(Enum, self).validate(value, detail)\n\n if not (value is None or value in self._enum):\n msg = \"\" if not detail else \"invalid value: %r; allowed values are %s\" % (value, nice_join(self.allowed_values))\n raise ValueError(msg)\n\n def _sphinx_type(self):\n # try to return a link to a proper enum in bokeh.core.enums if possible\n if self._enum in enums.__dict__.values():\n for name, obj in enums.__dict__.items():\n if self._enum is obj:\n val = self._sphinx_model_link(\"%s.%s\" % (self._enum.__module__, name))\n else:\n val = str(self._enum)\n return self._sphinx_prop_link() + \"( %s )\" % val\n\nclass Auto(Enum):\n ''' Accepts only the string \"auto\".\n\n Useful for properties that can be configured to behave \"automatically\".\n\n Example:\n\n This property is often most useful in conjunction with the\n :class:`~bokeh.core.properties.Either` property.\n\n .. code-block:: python\n\n >>> class AutoModel(HasProps):\n ... prop = Either(Float, Auto)\n ...\n\n >>> m = AutoModel()\n\n >>> m.prop = 10.2\n\n >>> m.prop = \"auto\"\n\n >>> m.prop = \"foo\" # ValueError !!\n\n >>> m.prop = [1, 2, 3] # ValueError !!\n\n '''\n def __init__(self):\n super(Auto, self).__init__(\"auto\")\n\n def __str__(self):\n return self.__class__.__name__\n\n def _sphinx_type(self):\n return self._sphinx_prop_link()\n\nclass MarkerType(Enum):\n '''\n\n '''\n def __init__(self, **kw):\n super(MarkerType, self).__init__(enums.MarkerType, **kw)\n\nclass Image(Property):\n ''' Accept image file types, e.g PNG, JPEG, TIFF, etc.\n\n This property can be configured with:\n\n * A string filename to be loaded with ``PIL.Image.open``\n * An RGB(A) NumPy array, will be converted to PNG\n * A ``PIL.Image.Image`` object\n\n In all cases, the image data is serialized as a Base64 encoded string.\n\n '''\n\n def validate(self, value, detail=True):\n import numpy as np\n\n valid = False\n\n if value is None or isinstance(value, (string_types, PIL.Image.Image)):\n valid = True\n\n if isinstance(value, np.ndarray):\n valid = value.dtype == \"uint8\" and len(value.shape) == 3 and value.shape[2] in (3, 4)\n\n if not valid:\n msg = \"\" if not detail else \"invalid value: %r; allowed values are string filenames, PIL.Image.Image instances, or RGB(A) NumPy arrays\" % value\n raise ValueError(msg)\n\n def transform(self, value):\n if value is None:\n return None\n\n import numpy as np\n if isinstance(value, np.ndarray):\n value = PIL.Image.fromarray(value)\n\n if isinstance(value, string_types):\n value = PIL.Image.open(value)\n\n if isinstance(value, PIL.Image.Image):\n out = BytesIO()\n fmt = value.format or \"PNG\"\n value.save(out, fmt)\n return \"data:image/%s;base64,\" % fmt.lower() + base64.b64encode(out.getvalue()).decode('ascii')\n\n raise ValueError(\"Could not transform %r\" % value)\n\nclass RGB(Property):\n ''' Accept colors.RGB values.\n\n '''\n\n def validate(self, value, detail=True):\n super(RGB, self).validate(value, detail)\n\n if not (value is None or isinstance(value, colors.RGB)):\n msg = \"\" if not detail else \"expected RGB value, got %r\" % (value,)\n raise ValueError(msg)\n\n# Properties useful for defining visual attributes\nclass Color(Either):\n ''' Accept color values in a variety of ways.\n\n For colors, because we support named colors and hex values prefaced\n with a \"#\", when we are handed a string value, there is a little\n interpretation: if the value is one of the 147 SVG named colors or\n it starts with a \"#\", then it is interpreted as a value.\n\n If a 3-tuple is provided, then it is treated as an RGB (0..255).\n If a 4-tuple is provided, then it is treated as an RGBa (0..255), with\n alpha as a float between 0 and 1. (This follows the HTML5 Canvas API.)\n\n Example:\n\n .. code-block:: python\n\n >>> class ColorModel(HasProps):\n ... prop = Color()\n ...\n\n >>> m = ColorModel()\n\n >>> m.prop = \"firebrick\"\n\n >>> m.prop = \"#a240a2\"\n\n >>> m.prop = (100, 100, 255)\n\n >>> m.prop = (100, 100, 255, 0.5)\n\n >>> m.prop = \"junk\" # ValueError !!\n\n >>> m.prop = (100.2, 57.3, 10.2) # ValueError !!\n\n '''\n\n def __init__(self, default=None, help=None):\n types = (Enum(enums.NamedColor),\n Regex(\"^#[0-9a-fA-F]{6}$\"),\n Tuple(Byte, Byte, Byte),\n Tuple(Byte, Byte, Byte, Percent),\n RGB)\n super(Color, self).__init__(*types, default=default, help=help)\n\n def __str__(self):\n return self.__class__.__name__\n\n def transform(self, value):\n if isinstance(value, tuple):\n value = colors.RGB(*value).to_css()\n return value\n\n def _sphinx_type(self):\n return self._sphinx_prop_link()\n\nclass MinMaxBounds(Either):\n ''' Accept (min, max) bounds tuples for use with Ranges.\n\n Bounds are provided as a tuple of ``(min, max)`` so regardless of whether your range is\n increasing or decreasing, the first item should be the minimum value of the range and the\n second item should be the maximum. Setting min > max will result in a ``ValueError``.\n\n Setting bounds to None will allow your plot to pan/zoom as far as you want. If you only\n want to constrain one end of the plot, you can set min or max to\n ``None`` e.g. ``DataRange1d(bounds=(None, 12))`` '''\n\n def __init__(self, accept_datetime=False, default='auto', help=None):\n if accept_datetime:\n types = (\n Auto,\n Tuple(Float, Float),\n Tuple(TimeDelta, TimeDelta),\n Tuple(Datetime, Datetime),\n )\n else:\n types = (\n Auto,\n Tuple(Float, Float),\n Tuple(TimeDelta, TimeDelta),\n )\n super(MinMaxBounds, self).__init__(*types, default=default, help=help)\n\n def validate(self, value, detail=True):\n super(MinMaxBounds, self).validate(value, detail)\n\n if value is None:\n pass\n\n elif value[0] is None or value[1] is None:\n pass\n\n elif value[0] >= value[1]:\n msg = \"\" if not detail else \"Invalid bounds: maximum smaller than minimum. Correct usage: bounds=(min, max)\"\n raise ValueError(msg)\n\n return True\n\n def _sphinx_type(self):\n return self._sphinx_prop_link()\n\n\nclass DashPattern(Either):\n ''' Accept line dash specifications.\n\n Express patterns that describe line dashes. ``DashPattern`` values\n can be specified in a variety of ways:\n\n * An enum: \"solid\", \"dashed\", \"dotted\", \"dotdash\", \"dashdot\"\n * a tuple or list of integers in the `HTML5 Canvas dash specification style`_.\n Note that if the list of integers has an odd number of elements, then\n it is duplicated, and that duplicated list becomes the new dash list.\n\n To indicate that dashing is turned off (solid lines), specify the empty\n list [].\n\n .. _HTML5 Canvas dash specification style: http://www.w3.org/html/wg/drafts/2dcontext/html5_canvas/#dash-list\n\n '''\n\n _dash_patterns = {\n \"solid\": [],\n \"dashed\": [6],\n \"dotted\": [2,4],\n \"dotdash\": [2,4,6,4],\n \"dashdot\": [6,4,2,4],\n }\n\n def __init__(self, default=[], help=None):\n types = Enum(enums.DashPattern), Regex(r\"^(\\d+(\\s+\\d+)*)?$\"), Seq(Int)\n super(DashPattern, self).__init__(*types, default=default, help=help)\n\n def __str__(self):\n return self.__class__.__name__\n\n def transform(self, value):\n value = super(DashPattern, self).transform(value)\n\n if isinstance(value, string_types):\n try:\n return self._dash_patterns[value]\n except KeyError:\n return [int(x) for x in value.split()]\n else:\n return value\n\n def _sphinx_type(self):\n return self._sphinx_prop_link()\n\nclass Size(Float):\n ''' Accept non-negative numeric values.\n\n Args:\n default (float or None, optional) :\n A default value for attributes created from this property to\n have (default: None)\n\n help (str or None, optional) :\n A documentation string for this property. It will be automatically\n used by the :ref:`bokeh.sphinxext.bokeh_prop` extension when\n generating Spinx documentation. (default: None)\n\n serialized (bool, optional) :\n Whether attributes created from this property should be included\n in serialization (default: True)\n\n readonly (bool, optional) :\n Whether attributes created from this property are read-only.\n (default: False)\n\n Example:\n\n .. code-block:: python\n\n >>> class SizeModel(HasProps):\n ... prop = Size()\n ...\n\n >>> m = SizeModel()\n\n >>> m.prop = 0\n\n >>> m.prop = 10e6\n\n >>> m.prop = -10 # ValueError !!\n\n >>> m.prop = \"foo\" # ValueError !!\n\n '''\n def validate(self, value, detail=True):\n super(Size, self).validate(value, detail)\n\n if not (value is None or 0.0 <= value):\n msg = \"\" if not detail else \"expected a non-negative number, got %r\" % value\n raise ValueError(msg)\n\nclass Percent(Float):\n ''' Accept floating point percentage values.\n\n ``Percent`` can be useful and semantically meaningful for specifying\n things like alpha values and extents.\n\n Args:\n default (float or None, optional) :\n A default value for attributes created from this property to\n have (default: None)\n\n help (str or None, optional) :\n A documentation string for this property. It will be automatically\n used by the :ref:`bokeh.sphinxext.bokeh_prop` extension when\n generating Spinx documentation. (default: None)\n\n serialized (bool, optional) :\n Whether attributes created from this property should be included\n in serialization (default: True)\n\n readonly (bool, optional) :\n Whether attributes created from this property are read-only.\n (default: False)\n\n Example:\n\n .. code-block:: python\n\n >>> class PercentModel(HasProps):\n ... prop = Percent()\n ...\n\n >>> m = PercentModel()\n\n >>> m.prop = 0.0\n\n >>> m.prop = 0.2\n\n >>> m.prop = 1.0\n\n >>> m.prop = -2 # ValueError !!\n\n >>> m.prop = 5 # ValueError !!\n\n '''\n def validate(self, value, detail=True):\n super(Percent, self).validate(value, detail)\n\n if not (value is None or 0.0 <= value <= 1.0):\n msg = \"\" if not detail else \"expected a value in range [0, 1], got %r\" % value\n raise ValueError(msg)\n\nclass Angle(Float):\n ''' Accept floating point angle values.\n\n ``Angle`` is equivalent to :class:`~bokeh.core.properties.Float` but is\n provided for cases when it is more semantically meaningful.\n\n Args:\n default (float or None, optional) :\n A default value for attributes created from this property to\n have (default: None)\n\n help (str or None, optional) :\n A documentation string for this property. It will be automatically\n used by the :ref:`bokeh.sphinxext.bokeh_prop` extension when\n generating Spinx documentation. (default: None)\n\n serialized (bool, optional) :\n Whether attributes created from this property should be included\n in serialization (default: True)\n\n readonly (bool, optional) :\n Whether attributes created from this property are read-only.\n (default: False)\n\n '''\n pass\n\nclass Date(Property):\n ''' Accept Date (but not DateTime) values.\n\n '''\n def __init__(self, default=None, help=None):\n super(Date, self).__init__(default=default, help=help)\n\n def transform(self, value):\n value = super(Date, self).transform(value)\n\n if isinstance(value, (float,) + bokeh_integer_types):\n try:\n value = datetime.date.fromtimestamp(value)\n except (ValueError, OSError):\n value = datetime.date.fromtimestamp(value/1000)\n elif isinstance(value, string_types):\n value = dateutil.parser.parse(value).date()\n\n return value\n\n def validate(self, value, detail=True):\n super(Date, self).validate(value, detail)\n\n if not (value is None or isinstance(value, (datetime.date,) + string_types + (float,) + bokeh_integer_types)):\n msg = \"\" if not detail else \"expected a date, string or timestamp, got %r\" % value\n raise ValueError(msg)\n\nclass Datetime(Property):\n ''' Accept Datetime values.\n\n '''\n\n def __init__(self, default=datetime.date.today(), help=None):\n super(Datetime, self).__init__(default=default, help=help)\n\n def transform(self, value):\n value = super(Datetime, self).transform(value)\n return value\n # Handled by serialization in protocol.py for now\n\n def validate(self, value, detail=True):\n super(Datetime, self).validate(value, detail)\n\n datetime_types = (datetime.datetime, datetime.date)\n try:\n import numpy as np\n datetime_types += (np.datetime64,)\n except (ImportError, AttributeError) as e:\n if e.args == (\"'module' object has no attribute 'datetime64'\",):\n import sys\n if 'PyPy' in sys.version:\n pass\n else:\n raise e\n else:\n pass\n\n if (isinstance(value, datetime_types)):\n return\n\n if pd and isinstance(value, (pd.Timestamp)):\n return\n\n msg = \"\" if not detail else \"Expected a datetime instance, got %r\" % value\n raise ValueError(msg)\n\nclass TimeDelta(Property):\n ''' Accept TimeDelta values.\n\n '''\n\n def __init__(self, default=datetime.timedelta(), help=None):\n super(TimeDelta, self).__init__(default=default, help=help)\n\n def transform(self, value):\n value = super(TimeDelta, self).transform(value)\n return value\n # Handled by serialization in protocol.py for now\n\n def validate(self, value, detail=True):\n super(TimeDelta, self).validate(value, detail)\n\n timedelta_types = (datetime.timedelta,)\n try:\n import numpy as np\n timedelta_types += (np.timedelta64,)\n except (ImportError, AttributeError) as e:\n if e.args == (\"'module' object has no attribute 'timedelta64'\",):\n import sys\n if 'PyPy' in sys.version:\n pass\n else:\n raise e\n else:\n pass\n\n if (isinstance(value, timedelta_types)):\n return\n\n if pd and isinstance(value, (pd.Timedelta)):\n return\n\n msg = \"\" if not detail else \"Expected a timedelta instance, got %r\" % value\n raise ValueError(msg)\n\n#------------------------------------------------------------------------------\n# Container properties\n#------------------------------------------------------------------------------\n\nclass Seq(ContainerProperty):\n ''' Accept non-string ordered sequences of values, e.g. list, tuple, array.\n\n '''\n\n def __init__(self, item_type, default=None, help=None):\n self.item_type = self._validate_type_param(item_type)\n super(Seq, self).__init__(default=default, help=help)\n\n def __str__(self):\n return \"%s(%s)\" % (self.__class__.__name__, self.item_type)\n\n @property\n def type_params(self):\n return [self.item_type]\n\n def from_json(self, json, models=None):\n if json is None:\n return None\n elif isinstance(json, list):\n return self._new_instance([ self.item_type.from_json(item, models) for item in json ])\n else:\n raise DeserializationError(\"%s expected a list or None, got %s\" % (self, json))\n\n def validate(self, value, detail=True):\n super(Seq, self).validate(value, True)\n\n if value is not None:\n if not (self._is_seq(value) and all(self.item_type.is_valid(item) for item in value)):\n if self._is_seq(value):\n invalid = []\n for item in value:\n if not self.item_type.is_valid(item):\n invalid.append(item)\n msg = \"\" if not detail else \"expected an element of %s, got seq with invalid items %r\" % (self, invalid)\n raise ValueError(msg)\n else:\n msg = \"\" if not detail else \"expected an element of %s, got %r\" % (self, value)\n raise ValueError(msg)\n\n @classmethod\n def _is_seq(cls, value):\n return ((isinstance(value, collections.Sequence) or cls._is_seq_like(value)) and\n not isinstance(value, string_types))\n\n @classmethod\n def _is_seq_like(cls, value):\n return (isinstance(value, (collections.Container, collections.Sized, collections.Iterable))\n and hasattr(value, \"__getitem__\") # NOTE: this is what makes it disallow set type\n and not isinstance(value, collections.Mapping))\n\n def _new_instance(self, value):\n return value\n\n def _sphinx_type(self):\n return self._sphinx_prop_link() + \"( %s )\" % self.item_type._sphinx_type()\n\nclass List(Seq):\n ''' Accept Python list values.\n\n '''\n\n def __init__(self, item_type, default=[], help=None):\n # todo: refactor to not use mutable objects as default values.\n # Left in place for now because we want to allow None to express\n # optional values. Also in Dict.\n super(List, self).__init__(item_type, default=default, help=help)\n\n @classmethod\n def wrap(cls, value):\n ''' Some property types need to wrap their values in special containers, etc.\n\n '''\n if isinstance(value, list):\n if isinstance(value, PropertyValueList):\n return value\n else:\n return PropertyValueList(value)\n else:\n return value\n\n @classmethod\n def _is_seq(cls, value):\n return isinstance(value, list)\n\nclass Array(Seq):\n ''' Accept NumPy array values.\n\n '''\n\n @classmethod\n def _is_seq(cls, value):\n import numpy as np\n return isinstance(value, np.ndarray)\n\n def _new_instance(self, value):\n import numpy as np\n return np.array(value)\n\n\nclass Dict(ContainerProperty):\n ''' Accept Python dict values.\n\n If a default value is passed in, then a shallow copy of it will be\n used for each new use of this property.\n\n '''\n\n def __init__(self, keys_type, values_type, default={}, help=None):\n self.keys_type = self._validate_type_param(keys_type)\n self.values_type = self._validate_type_param(values_type)\n super(Dict, self).__init__(default=default, help=help)\n\n def __str__(self):\n return \"%s(%s, %s)\" % (self.__class__.__name__, self.keys_type, self.values_type)\n\n @property\n def type_params(self):\n return [self.keys_type, self.values_type]\n\n def from_json(self, json, models=None):\n if json is None:\n return None\n elif isinstance(json, dict):\n return { self.keys_type.from_json(key, models): self.values_type.from_json(value, models) for key, value in iteritems(json) }\n else:\n raise DeserializationError(\"%s expected a dict or None, got %s\" % (self, json))\n\n def validate(self, value, detail=True):\n super(Dict, self).validate(value, detail)\n\n if value is not None:\n if not (isinstance(value, dict) and \\\n all(self.keys_type.is_valid(key) and self.values_type.is_valid(val) for key, val in iteritems(value))):\n msg = \"\" if not detail else \"expected an element of %s, got %r\" % (self, value)\n raise ValueError(msg)\n\n @classmethod\n def wrap(cls, value):\n ''' Some property types need to wrap their values in special containers, etc.\n\n '''\n if isinstance(value, dict):\n if isinstance(value, PropertyValueDict):\n return value\n else:\n return PropertyValueDict(value)\n else:\n return value\n\n def _sphinx_type(self):\n return self._sphinx_prop_link() + \"( %s, %s )\" % (self.keys_type._sphinx_type(), self.values_type._sphinx_type())\n\nclass ColumnData(Dict):\n ''' Accept a Python dictionary suitable as the ``data`` attribute of a\n :class:`~bokeh.models.sources.ColumnDataSource`.\n\n This class is a specialization of ``Dict`` that handles efficiently\n encoding columns that are NumPy arrays.\n\n '''\n\n def make_descriptors(self, base_name):\n ''' Return a list of ``ColumnDataPropertyDescriptor`` instances to\n install on a class, in order to delegate attribute access to this\n property.\n\n Args:\n base_name (str) : the name of the property these descriptors are for\n\n Returns:\n list[ColumnDataPropertyDescriptor]\n\n The descriptors returned are collected by the ``MetaHasProps``\n metaclass and added to ``HasProps`` subclasses during class creation.\n '''\n return [ ColumnDataPropertyDescriptor(base_name, self) ]\n\n\n def from_json(self, json, models=None):\n ''' Decodes column source data encoded as lists or base64 strings.\n '''\n if json is None:\n return None\n elif not isinstance(json, dict):\n raise DeserializationError(\"%s expected a dict or None, got %s\" % (self, json))\n new_data = {}\n for key, value in json.items():\n key = self.keys_type.from_json(key, models)\n if isinstance(value, dict) and '__ndarray__' in value:\n new_data[key] = decode_base64_dict(value)\n elif isinstance(value, list) and any(isinstance(el, dict) and '__ndarray__' in el for el in value):\n new_list = []\n for el in value:\n if isinstance(el, dict) and '__ndarray__' in el:\n el = decode_base64_dict(el)\n elif isinstance(el, list):\n el = self.values_type.from_json(el)\n new_list.append(el)\n new_data[key] = new_list\n else:\n new_data[key] = self.values_type.from_json(value, models)\n return new_data\n\n def serialize_value(self, value):\n return transform_column_source_data(value)\n\n @classmethod\n def wrap(cls, value):\n ''' Some property types need to wrap their values in special containers, etc.\n\n '''\n if isinstance(value, dict):\n if isinstance(value, PropertyValueColumnData):\n return value\n else:\n return PropertyValueColumnData(value)\n else:\n return value\n\nclass Tuple(ContainerProperty):\n ''' Accept Python tuple values.\n\n '''\n def __init__(self, tp1, tp2, *type_params, **kwargs):\n self._type_params = list(map(self._validate_type_param, (tp1, tp2) + type_params))\n super(Tuple, self).__init__(default=kwargs.get(\"default\"), help=kwargs.get(\"help\"))\n\n def __str__(self):\n return \"%s(%s)\" % (self.__class__.__name__, \", \".join(map(str, self.type_params)))\n\n @property\n def type_params(self):\n return self._type_params\n\n def from_json(self, json, models=None):\n if json is None:\n return None\n elif isinstance(json, list):\n return tuple(type_param.from_json(item, models) for type_param, item in zip(self.type_params, json))\n else:\n raise DeserializationError(\"%s expected a list or None, got %s\" % (self, json))\n\n def validate(self, value, detail=True):\n super(Tuple, self).validate(value, detail)\n\n if value is not None:\n if not (isinstance(value, (tuple, list)) and len(self.type_params) == len(value) and \\\n all(type_param.is_valid(item) for type_param, item in zip(self.type_params, value))):\n msg = \"\" if not detail else \"expected an element of %s, got %r\" % (self, value)\n raise ValueError(msg)\n\n def _sphinx_type(self):\n return self._sphinx_prop_link() + \"( %s )\" % \", \".join(x._sphinx_type() for x in self.type_params)\n\nclass RelativeDelta(Dict):\n ''' Accept RelativeDelta dicts for time delta values.\n\n '''\n\n def __init__(self, default={}, help=None):\n keys = Enum(\"years\", \"months\", \"days\", \"hours\", \"minutes\", \"seconds\", \"microseconds\")\n values = Int\n super(RelativeDelta, self).__init__(keys, values, default=default, help=help)\n\n def __str__(self):\n return self.__class__.__name__\n\n#------------------------------------------------------------------------------\n# DataSpec properties\n#------------------------------------------------------------------------------\n\nclass DataSpec(Either):\n ''' Base class for properties that accept either a fixed value, or a\n string name that references a column in a\n :class:`~bokeh.models.sources.ColumnDataSource`.\n\n Many Bokeh models have properties that a user might want to set either\n to a single fixed value, or to have the property take values from some\n column in a data source. As a concrete example consider a glyph with\n an ``x`` property for location. We might want to set all the glyphs\n that get drawn to have the same location, say ``x=10``. It would be\n convenient to just be able to write:\n\n .. code-block:: python\n\n glyph.x = 10\n\n Alternatively, maybe the each glyph that gets drawn should have a\n different location, according to the \"pressure\" column of a data\n source. In this case we would like to be able to write:\n\n .. code-block:: python\n\n glyph.x = \"pressure\"\n\n Bokeh ``DataSpec`` properties (and subclasses) afford this ease of\n and consistency of expression. Ultimately, all ``DataSpec`` properties\n resolve to dictionary values, with either a ``\"value\"`` key, or a\n ``\"field\"`` key, depending on how it is set.\n\n For instance:\n\n .. code-block:: python\n\n glyph.x = 10 # => { 'value': 10 }\n\n glyph.x = \"pressure\" # => { 'field': 'pressure' }\n\n When these underlying dictionary dictionary values are received in\n the browser, BokehJS knows how to interpret them and take the correct,\n expected action (i.e., draw the glyph at ``x=10``, or draw the glyph\n with ``x`` coordinates from the \"pressure\" column). In this way, both\n use-cases may be expressed easily in python, without having to handle\n anything differently, from the user perspective.\n\n It is worth noting that ``DataSpec`` properties can also be set directly\n with properly formed dictionary values:\n\n .. code-block:: python\n\n glyph.x = { 'value': 10 } # same as glyph.x = 10\n\n glyph.x = { 'field': 'pressure' } # same as glyph.x = \"pressure\"\n\n Setting the property directly as a dict can be useful in certain\n situations. For instance some ``DataSpec`` subclasses also add a\n ``\"units\"`` key to the dictionary. This key is often set automatically,\n but the dictionary format provides a direct mechanism to override as\n necessary. Additionally, ``DataSpec`` can have a ``\"transform\"`` key,\n that specifies a client-side transform that should be applied to any\n fixed or field values before they are uses. As an example, you might want\n to apply a ``Jitter`` transform to the ``x`` values:\n\n .. code-block:: python\n\n glyph.x = { 'value': 10, 'transform': Jitter(width=0.4) }\n\n Note that ``DataSpec`` is not normally useful on its own. Typically,\n a model will define properties using one of the sublclasses such\n as :class:`~bokeh.core.properties.NumberSpec` or\n :class:`~bokeh.core.properties.ColorSpec`. For example, a Bokeh\n model with ``x``, ``y`` and ``color`` properties that can handle\n fixed values or columns automatically might look like:\n\n .. code-block:: python\n\n class SomeModel(Model):\n\n x = NumberSpec(default=0, help=\"docs for x\")\n\n y = NumberSpec(default=0, help=\"docs for y\")\n\n color = ColorSpec(help=\"docs for color\") # defaults to None\n\n '''\n def __init__(self, key_type, value_type, default, help=None):\n super(DataSpec, self).__init__(\n String,\n Dict(\n key_type,\n Either(\n String,\n Instance('bokeh.models.transforms.Transform'),\n Instance('bokeh.models.expressions.Expression'),\n value_type)),\n value_type,\n default=default,\n help=help\n )\n self._type = self._validate_type_param(value_type)\n\n # TODO (bev) add stricter validation on keys\n\n def make_descriptors(self, base_name):\n ''' Return a list of ``DataSpecPropertyDescriptor`` instances to\n install on a class, in order to delegate attribute access to this\n property.\n\n Args:\n base_name (str) : the name of the property these descriptors are for\n\n Returns:\n list[DataSpecPropertyDescriptor]\n\n The descriptors returned are collected by the ``MetaHasProps``\n metaclass and added to ``HasProps`` subclasses during class creation.\n '''\n return [ DataSpecPropertyDescriptor(base_name, self) ]\n\n def to_serializable(self, obj, name, val):\n # Check for None value; this means \"the whole thing is\n # unset,\" not \"the value is None.\"\n if val is None:\n return None\n\n # Check for spec type value\n try:\n self._type.validate(val, False)\n return dict(value=val)\n except ValueError:\n pass\n\n # Check for data source field name\n if isinstance(val, string_types):\n return dict(field=val)\n\n # Must be dict, return a new dict\n return dict(val)\n\n def _sphinx_type(self):\n return self._sphinx_prop_link()\n\n_ExprFieldValueTransform = Enum(\"expr\", \"field\", \"value\", \"transform\")\n\nclass NumberSpec(DataSpec):\n ''' A |DataSpec| property that accepts numeric and datetime fixed values.\n\n By default, date and datetime values are immediately converted to\n milliseconds since epoch. It is possible to disable processing of datetime\n values by passing ``accept_datetime=False``.\n\n By default, timedelta values are immediately converted to absolute\n milliseconds. It is possible to disable processing of timedelta\n values by passing ``accept_timedelta=False``\n\n Timedelta values are interpreted as absolute milliseconds.\n\n .. code-block:: python\n\n m.location = 10.3 # value\n\n m.location = \"foo\" # field\n\n '''\n def __init__(self, default=None, help=None, key_type=_ExprFieldValueTransform, accept_datetime=True, accept_timedelta=True):\n super(NumberSpec, self).__init__(key_type, Float, default=default, help=help)\n if accept_timedelta:\n self.accepts(TimeDelta, convert_timedelta_type)\n if accept_datetime:\n self.accepts(Datetime, convert_datetime_type)\n\n\nclass StringSpec(DataSpec):\n ''' A |DataSpec| property that accepts string fixed values.\n\n Because acceptable fixed values and field names are both strings, it can\n be necessary explicitly to disambiguate these possibilities. By default,\n string values are interpreted as fields, but the |value| function can be\n used to specify that a string should interpreted as a value:\n\n .. code-block:: python\n\n m.title = value(\"foo\") # value\n\n m.title = \"foo\" # field\n\n '''\n def __init__(self, default, help=None, key_type=_ExprFieldValueTransform):\n super(StringSpec, self).__init__(key_type, List(String), default=default, help=help)\n\n def prepare_value(self, cls, name, value):\n if isinstance(value, list):\n if len(value) != 1:\n raise TypeError(\"StringSpec convenience list values must have length 1\")\n value = dict(value=value[0])\n return super(StringSpec, self).prepare_value(cls, name, value)\n\nclass FontSizeSpec(DataSpec):\n ''' A |DataSpec| property that accepts font-size fixed values.\n\n The ``FontSizeSpec`` property attempts to first interpret string values as\n font sizes (i.e. valid CSS length values). Otherwise string values are\n interpreted as field names. For example:\n\n .. code-block:: python\n\n m.font_size = \"10pt\" # value\n\n m.font_size = \"1.5em\" # value\n\n m.font_size = \"foo\" # field\n\n A full list of all valid CSS length units can be found here:\n\n https://drafts.csswg.org/css-values/#lengths\n\n '''\n\n def __init__(self, default, help=None, key_type=_ExprFieldValueTransform):\n super(FontSizeSpec, self).__init__(key_type, FontSize, default=default, help=help)\n\n def validate(self, value, detail=True):\n # We want to preserve existing semantics and be a little more restrictive. This\n # validations makes m.font_size = \"\" or m.font_size = \"6\" an error\n super(FontSizeSpec, self).validate(value, detail)\n if isinstance(value, string_types):\n if len(value) == 0 or value[0].isdigit() and FontSize._font_size_re.match(value) is None:\n msg = \"\" if not detail else \"%r is not a valid font size value\" % value\n raise ValueError(msg)\n\nclass MarkerSpec(DataSpec):\n ''' A |DataSpec| property that accepts marker types as fixed values.\n\n The ``MarkerSpec`` property attempts to first interpret string values as\n marker types. Otherwise string values are interpreted as field names.\n For example:\n\n .. code-block:: python\n\n m.font_size = \"circle\" # value\n\n m.font_size = \"square\" # value\n\n m.font_size = \"foo\" # field\n\n '''\n\n def __init__(self, default, help=None, key_type=_ExprFieldValueTransform):\n super(MarkerSpec, self).__init__(key_type, MarkerType, default=default, help=help)\n\n\n_ExprFieldValueTransformUnits = Enum(\"expr\", \"field\", \"value\", \"transform\", \"units\")\n\nclass UnitsSpec(NumberSpec):\n ''' A |DataSpec| property that accepts numeric fixed values, and also\n provides an associated units property to store units information.\n\n '''\n def __init__(self, default, units_type, units_default, help=None):\n super(UnitsSpec, self).__init__(default=default, help=help, key_type=_ExprFieldValueTransformUnits)\n self._units_type = self._validate_type_param(units_type)\n # this is a hack because we already constructed units_type\n self._units_type.validate(units_default)\n self._units_type._default = units_default\n # this is sort of a hack because we don't have a\n # serialized= kwarg on every Property subtype\n self._units_type._serialized = False\n\n def __str__(self):\n return \"%s(units_default=%r)\" % (self.__class__.__name__, self._units_type._default)\n\n def make_descriptors(self, base_name):\n ''' Return a list of ``PropertyDescriptor`` instances to install on a\n class, in order to delegate attribute access to this property.\n\n Unlike simpler property types, ``UnitsSpec`` returns multiple\n descriptors to install. In particular, descriptors for the base\n property as well as the associated units property are returned.\n\n Args:\n name (str) : the name of the property these descriptors are for\n\n Returns:\n list[PropertyDescriptor]\n\n The descriptors returned are collected by the ``MetaHasProps``\n metaclass and added to ``HasProps`` subclasses during class creation.\n '''\n units_name = base_name + \"_units\"\n units_props = self._units_type.make_descriptors(units_name)\n return units_props + [ UnitsSpecPropertyDescriptor(base_name, self, units_props[0]) ]\n\n def to_serializable(self, obj, name, val):\n d = super(UnitsSpec, self).to_serializable(obj, name, val)\n if d is not None and 'units' not in d:\n # d is a PropertyValueDict at this point, we need to convert it to\n # a plain dict if we are going to modify its value, otherwise a\n # notify_change that should not happen will be triggered\n d = dict(d)\n d[\"units\"] = getattr(obj, name+\"_units\")\n return d\n\nclass AngleSpec(UnitsSpec):\n ''' A |DataSpec| property that accepts numeric fixed values, and also\n provides an associated units property to store angle units.\n\n Acceptable values for units are ``\"rad\"`` and ``\"deg\"``.\n\n '''\n def __init__(self, default=None, units_default=\"rad\", help=None):\n super(AngleSpec, self).__init__(default=default, units_type=Enum(enums.AngleUnits), units_default=units_default, help=help)\n\nclass DistanceSpec(UnitsSpec):\n ''' A |DataSpec| property that accepts numeric fixed values or strings\n that refer to columns in a :class:`~bokeh.models.sources.ColumnDataSource`,\n and also provides an associated units property to store units information.\n Acceptable values for units are ``\"screen\"`` and ``\"data\"``.\n\n '''\n def __init__(self, default=None, units_default=\"data\", help=None):\n super(DistanceSpec, self).__init__(default=default, units_type=Enum(enums.SpatialUnits), units_default=units_default, help=help)\n\n def prepare_value(self, cls, name, value):\n try:\n if value is not None and value < 0:\n raise ValueError(\"Distances must be positive or None!\")\n except TypeError:\n pass\n return super(DistanceSpec, self).prepare_value(cls, name, value)\n\nclass ScreenDistanceSpec(UnitsSpec):\n ''' A |DataSpec| property that accepts numeric fixed values for screen\n distances, and also provides an associated units property that reports\n ``\"screen\"`` as the units.\n\n .. note::\n Units are always ``\"screen\"``.\n\n '''\n\n def __init__(self, default=None, help=None):\n super(ScreenDistanceSpec, self).__init__(default=default, units_type=Enum(enums.enumeration(\"screen\")), units_default=\"screen\", help=help)\n\n def prepare_value(self, cls, name, value):\n try:\n if value is not None and value < 0:\n raise ValueError(\"Distances must be positive or None!\")\n except TypeError:\n pass\n return super(ScreenDistanceSpec, self).prepare_value(cls, name, value)\n\n def make_descriptors(self, base_name):\n ''' Return a list of ``PropertyDescriptor`` instances to install on a\n class, in order to delegate attribute access to this property.\n\n Unlike simpler property types, ``UnitsSpec`` returns multiple\n descriptors to install. In particular, descriptors for the base\n property as well as the associated units property are returned.\n\n Args:\n name (str) : the name of the property these descriptors are for\n\n Returns:\n list[PropertyDescriptor]\n\n The descriptors returned are collected by the ``MetaHasProps``\n metaclass and added to ``HasProps`` subclasses during class creation.\n '''\n units_props = self._units_type.make_descriptors(\"unused\")\n return [ UnitsSpecPropertyDescriptor(base_name, self, units_props[0]) ]\n\n def to_serializable(self, obj, name, val):\n d = super(UnitsSpec, self).to_serializable(obj, name, val)\n if d is not None and 'units' not in d:\n # d is a PropertyValueDict at this point, we need to convert it to\n # a plain dict if we are going to modify its value, otherwise a\n # notify_change that should not happen will be triggered\n d = dict(d)\n d[\"units\"] = \"screen\"\n return d\n\n\nclass DataDistanceSpec(UnitsSpec):\n ''' A |DataSpec| property that accepts numeric fixed values for data-space\n distances, and also provides an associated units property that reports\n ``\"data\"`` as the units.\n\n .. note::\n Units are always ``\"data\"``.\n\n '''\n def __init__(self, default=None, help=None):\n super(DataDistanceSpec, self).__init__(default=default, units_type=Enum(enums.enumeration(\"data\")), units_default=\"data\", help=help)\n\n def prepare_value(self, cls, name, value):\n try:\n if value is not None and value < 0:\n raise ValueError(\"Distances must be positive or None!\")\n except TypeError:\n pass\n return super(DataDistanceSpec, self).prepare_value(cls, name, value)\n\n def make_descriptors(self, base_name):\n ''' Return a list of ``PropertyDescriptor`` instances to install on a\n class, in order to delegate attribute access to this property.\n\n Unlike simpler property types, ``UnitsSpec`` returns multiple\n descriptors to install. In particular, descriptors for the base\n property as well as the associated units property are returned.\n\n Args:\n name (str) : the name of the property these descriptors are for\n\n Returns:\n list[PropertyDescriptor]\n\n The descriptors returned are collected by the ``MetaHasProps``\n metaclass and added to ``HasProps`` subclasses during class creation.\n '''\n units_props = self._units_type.make_descriptors(\"unused\")\n return [ UnitsSpecPropertyDescriptor(base_name, self, units_props[0]) ]\n\n def to_serializable(self, obj, name, val):\n d = super(UnitsSpec, self).to_serializable(obj, name, val)\n if d is not None and 'units' not in d:\n # d is a PropertyValueDict at this point, we need to convert it to\n # a plain dict if we are going to modify its value, otherwise a\n # notify_change that should not happen will be triggered\n d = dict(d)\n d[\"units\"] = \"data\"\n return d\n\nclass ColorSpec(DataSpec):\n ''' A |DataSpec| property that accepts |Color| fixed values.\n\n The ``ColorSpec`` property attempts to first interpret string values as\n colors. Otherwise, string values are interpreted as field names. For\n example:\n\n .. code-block:: python\n\n m.color = \"#a4225f\" # value (hex color string)\n\n m.color = \"firebrick\" # value (named CSS color string)\n\n m.color = \"foo\" # field (named \"foo\")\n\n This automatic interpretation can be override using the dict format\n directly, or by using the |field| function:\n\n .. code-block:: python\n\n m.color = { \"field\": \"firebrick\" } # field (named \"firebrick\")\n\n m.color = field(\"firebrick\") # field (named \"firebrick\")\n\n '''\n def __init__(self, default, help=None, key_type=_ExprFieldValueTransform):\n super(ColorSpec, self).__init__(key_type, Color, default=default, help=help)\n\n @classmethod\n def isconst(cls, val):\n ''' Whether the value is a string color literal.\n\n Checks for a well-formed hexadecimal color value or a named color.\n\n Args:\n val (str) : the value to check\n\n Returns:\n True, if the value is a string color literal\n\n '''\n return isinstance(val, string_types) and \\\n ((len(val) == 7 and val[0] == \"#\") or val in enums.NamedColor)\n\n def to_serializable(self, obj, name, val):\n if val is None:\n return dict(value=None)\n\n # Check for hexadecimal or named color\n if self.isconst(val):\n return dict(value=val)\n\n # Check for RGB or RGBa tuple\n if isinstance(val, tuple):\n return dict(value=colors.RGB(*val).to_css())\n\n # Check for data source field name\n if isinstance(val, colors.RGB):\n return val.to_css()\n\n # Check for data source field name or rgb(a) string\n if isinstance(val, string_types):\n if val.startswith((\"rgb(\", \"rgba(\")):\n return val\n\n return dict(field=val)\n\n # Must be dict, return new dict\n return dict(val)\n\n def prepare_value(self, cls, name, value):\n # Some explanation is in order. We want to accept tuples like\n # (12.0, 100.0, 52.0) i.e. that have \"float\" byte values. The\n # ColorSpec has a transform to adapt values like this to tuples\n # of integers, but Property validation happens before the\n # transform step, so values like that will fail Color validation\n # at this point, since Color is very strict about only accepting\n # tuples of (integer) bytes. This conditions tuple values to only\n # have integer RGB components\n if isinstance(value, tuple):\n # TODO (bev) verify that all original floats are integer values?\n value = tuple(int(v) if i < 3 else v for i, v in enumerate(value))\n return super(ColorSpec, self).prepare_value(cls, name, value)\n\n#------------------------------------------------------------------------------\n# DataSpec helpers\n#------------------------------------------------------------------------------\n\ndef expr(expression, transform=None):\n ''' Convenience function to explicitly return an \"expr\" specification for\n a Bokeh :class:`~bokeh.core.properties.DataSpec` property.\n\n Args:\n expression (Expression) : a computed expression for a\n ``DataSpec`` property.\n\n transform (Transform, optional) : a transform to apply (default: None)\n\n Returns:\n dict : ``{ \"expr\": expression }``\n\n .. note::\n This function is included for completeness. String values for\n property specifications are by default interpreted as field names.\n\n '''\n if transform:\n return dict(expr=expression, transform=transform)\n return dict(expr=expression)\n\n\ndef field(name, transform=None):\n ''' Convenience function to explicitly return a \"field\" specification for\n a Bokeh :class:`~bokeh.core.properties.DataSpec` property.\n\n Args:\n name (str) : name of a data source field to reference for a\n ``DataSpec`` property.\n\n transform (Transform, optional) : a transform to apply (default: None)\n\n Returns:\n dict : ``{ \"field\": name }``\n\n .. note::\n This function is included for completeness. String values for\n property specifications are by default interpreted as field names.\n\n '''\n if transform:\n return dict(field=name, transform=transform)\n return dict(field=name)\n\ndef value(val, transform=None):\n ''' Convenience function to explicitly return a \"value\" specification for\n a Bokeh :class:`~bokeh.core.properties.DataSpec` property.\n\n Args:\n val (any) : a fixed value to specify for a ``DataSpec`` property.\n\n transform (Transform, optional) : a transform to apply (default: None)\n\n Returns:\n dict : ``{ \"value\": name }``\n\n .. note::\n String values for property specifications are by default interpreted\n as field names. This function is especially useful when you want to\n specify a fixed value with text properties.\n\n Example:\n\n .. code-block:: python\n\n # The following will take text values to render from a data source\n # column \"text_column\", but use a fixed value \"12pt\" for font size\n p.text(\"x\", \"y\", text=\"text_column\",\n text_font_size=value(\"12pt\"), source=source)\n\n '''\n if transform:\n return dict(value=val, transform=transform)\n return dict(value=val)\n\n#------------------------------------------------------------------------------\n# Special Properties\n#------------------------------------------------------------------------------\n\n# intentional transitive import to put Override in this module, DO NOT REMOVE\nfrom .property.override import Override ; Override\n\nclass Include(PropertyDescriptorFactory):\n ''' Include \"mix-in\" property collection in a Bokeh model.\n\n See :ref:`bokeh.core.property_mixins` for more details.\n\n '''\n\n def __init__(self, delegate, help=\"\", use_prefix=True):\n from .has_props import HasProps\n if not (isinstance(delegate, type) and issubclass(delegate, HasProps)):\n raise ValueError(\"expected a subclass of HasProps, got %r\" % delegate)\n\n self.delegate = delegate\n self.help = help\n self.use_prefix = use_prefix\n\n def make_descriptors(self, base_name):\n descriptors = []\n delegate = self.delegate\n if self.use_prefix:\n prefix = re.sub(\"_props$\", \"\", base_name) + \"_\"\n else:\n prefix = \"\"\n\n # it would be better if we kept the original generators from\n # the delegate and built our Include props from those, perhaps.\n for subpropname in delegate.properties(with_bases=False):\n fullpropname = prefix + subpropname\n subprop_descriptor = delegate.lookup(subpropname)\n if isinstance(subprop_descriptor, BasicPropertyDescriptor):\n prop = copy(subprop_descriptor.property)\n if \"%s\" in self.help:\n doc = self.help % subpropname.replace('_', ' ')\n else:\n doc = self.help\n prop.__doc__ = doc\n descriptors += prop.make_descriptors(fullpropname)\n\n return descriptors\n\n#------------------------------------------------------------------------------\n# Validation Control\n#------------------------------------------------------------------------------\n\nclass validate(object):\n ''' Control validation of bokeh properties\n\n This can be used as a context manager, or as a normal callable\n\n Args:\n value (bool) : Whether validation should occur or not\n\n Example:\n .. code-block:: python\n\n with validate(False): # do no validate while within this block\n pass\n\n validate(False) # don't validate ever\n\n See Also:\n :func:`~bokeh.core.property.bases.validation_on`: check the state of validation\n\n :func:`~bokeh.core.properties.without_property_validation`: function decorator\n\n '''\n def __init__(self, value):\n self.old = Property._should_validate\n Property._should_validate = value\n\n def __enter__(self):\n pass\n\n def __exit__(self, typ, value, traceback):\n Property._should_validate = self.old\n\n\ndef without_property_validation(input_function):\n ''' Turn off property validation during update callbacks\n\n Example:\n .. code-block:: python\n\n @without_property_validation\n def update(attr, old, new):\n # do things without validation\n\n See Also:\n :class:`~bokeh.core.properties.validate`: context mangager for more fine-grained control\n\n '''\n @wraps(input_function)\n def func(*args, **kwargs):\n with validate(False):\n return input_function(*args, **kwargs)\n return func\n\n# Everything below is just to update the module docstring\n_all_props = set(x for x in globals().values() if isinstance(x, type) and issubclass(x, Property))\n_all_props.remove(Property)\n_all_props.remove(PrimitiveProperty)\n_all_props.remove(ParameterizedProperty)\n_all_props.remove(ContainerProperty)\ndef _find_and_remove(typ):\n global _all_props\n sub = set(x for x in _all_props if issubclass(x, typ))\n _all_props -= sub\n return sub\n_data_specs = \"\\n\".join(sorted(\".. autoclass:: %s\" % x.__name__ for x in _find_and_remove(DataSpec)))\n_containers = \"\\n\".join(sorted(\".. autoclass:: %s\" % x.__name__ for x in _find_and_remove(ContainerProperty)))\n_basic = \"\\n\".join(sorted(\".. autoclass:: %s\" % x.__name__ for x in _all_props))\n\n__doc__ = format_docstring(__doc__, basic_properties=_basic, container_properties=_containers, dataspec_properties=_data_specs)\n\ndel _all_props, _data_specs, _containers, _basic, _find_and_remove\n"
] | [
[
"numpy.array"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
Jerry2990/sklearn_keras_wrap | [
"5d4a5f8df114bcb6e2cd23e00ed655d16ab6bc9a"
] | [
"tests/test_wrappers.py"
] | [
"\"\"\"Tests for Scikit-learn API wrapper.\"\"\"\n\n\nimport pickle\n\nimport numpy as np\nimport pytest\nfrom sklearn.calibration import CalibratedClassifierCV\nfrom sklearn.datasets import load_boston, load_digits, load_iris\nfrom sklearn.ensemble import (\n AdaBoostClassifier,\n AdaBoostRegressor,\n BaggingClassifier,\n BaggingRegressor,\n RandomForestClassifier,\n RandomForestRegressor,\n)\nfrom sklearn.metrics import r2_score as sklearn_r2_score\nfrom sklearn.model_selection import GridSearchCV, RandomizedSearchCV\nfrom sklearn.neural_network import MLPClassifier\nfrom sklearn.pipeline import Pipeline\nfrom sklearn.preprocessing import MultiLabelBinarizer, StandardScaler\nfrom sklearn.utils.estimator_checks import check_estimator\nfrom tensorflow.python import keras\nfrom tensorflow.python.framework.ops import convert_to_tensor\nfrom tensorflow.python.keras import backend as K\nfrom tensorflow.python.keras import testing_utils\nfrom tensorflow.python.keras.layers import (\n Concatenate,\n Conv2D,\n Dense,\n Flatten,\n Input,\n)\nfrom tensorflow.python.keras.models import Model, Sequential, clone_model\nfrom tensorflow.python.keras.utils.np_utils import to_categorical\n\nfrom sklearn_keras_wrap import wrappers\nfrom sklearn_keras_wrap.wrappers import KerasClassifier, KerasRegressor\n\nINPUT_DIM = 5\nHIDDEN_DIM = 5\nTRAIN_SAMPLES = 10\nTEST_SAMPLES = 5\nNUM_CLASSES = 2\nBATCH_SIZE = 5\nEPOCHS = 1\n\n\ndef build_fn_clf(hidden_dim):\n \"\"\"Builds a Sequential based classifier.\"\"\"\n model = keras.models.Sequential()\n model.add(keras.layers.Dense(INPUT_DIM, input_shape=(INPUT_DIM,)))\n model.add(keras.layers.Activation(\"relu\"))\n model.add(keras.layers.Dense(hidden_dim))\n model.add(keras.layers.Activation(\"relu\"))\n model.add(keras.layers.Dense(NUM_CLASSES))\n model.add(keras.layers.Activation(\"softmax\"))\n model.compile(\n optimizer=\"sgd\", loss=\"categorical_crossentropy\", metrics=[\"accuracy\"]\n )\n return model\n\n\ndef assert_classification_works(clf):\n \"\"\"Checks a classification task for errors.\"\"\"\n np.random.seed(42)\n (x_train, y_train), (x_test, _) = testing_utils.get_test_data(\n train_samples=TRAIN_SAMPLES,\n test_samples=TEST_SAMPLES,\n input_shape=(INPUT_DIM,),\n num_classes=NUM_CLASSES,\n )\n\n clf.fit(x_train, y_train, batch_size=BATCH_SIZE, epochs=EPOCHS)\n\n score = clf.score(x_train, y_train, batch_size=BATCH_SIZE)\n assert np.isscalar(score) and np.isfinite(score)\n\n preds = clf.predict(x_test, batch_size=BATCH_SIZE)\n assert preds.shape == (TEST_SAMPLES,)\n for prediction in np.unique(preds):\n assert prediction in range(NUM_CLASSES)\n\n proba = clf.predict_proba(x_test, batch_size=BATCH_SIZE)\n assert proba.shape == (TEST_SAMPLES, NUM_CLASSES)\n assert np.allclose(np.sum(proba, axis=1), np.ones(TEST_SAMPLES))\n\n\ndef build_fn_reg(hidden_dim):\n \"\"\"Builds a Sequential based regressor.\"\"\"\n model = keras.models.Sequential()\n model.add(keras.layers.Dense(INPUT_DIM, input_shape=(INPUT_DIM,)))\n model.add(keras.layers.Activation(\"relu\"))\n model.add(keras.layers.Dense(hidden_dim))\n model.add(keras.layers.Activation(\"relu\"))\n model.add(keras.layers.Dense(1))\n model.add(keras.layers.Activation(\"linear\"))\n model.compile(\n optimizer=\"sgd\", loss=\"mean_absolute_error\", metrics=[\"accuracy\"]\n )\n return model\n\n\ndef assert_regression_works(reg):\n \"\"\"Checks a regression task for errors.\"\"\"\n np.random.seed(42)\n (x_train, y_train), (x_test, _) = testing_utils.get_test_data(\n train_samples=TRAIN_SAMPLES,\n test_samples=TEST_SAMPLES,\n input_shape=(INPUT_DIM,),\n num_classes=NUM_CLASSES,\n )\n\n reg.fit(x_train, y_train, batch_size=BATCH_SIZE, epochs=EPOCHS)\n\n score = reg.score(x_train, y_train, batch_size=BATCH_SIZE)\n assert np.isscalar(score) and np.isfinite(score)\n\n preds = reg.predict(x_test, batch_size=BATCH_SIZE)\n assert preds.shape == (TEST_SAMPLES,)\n\n\nclass TestBasicAPI:\n \"\"\"Tests basic functionality.\"\"\"\n\n def test_classify_build_fn(self):\n \"\"\"Tests a classification task for errors.\"\"\"\n clf = wrappers.KerasClassifier(\n build_fn=build_fn_clf,\n hidden_dim=HIDDEN_DIM,\n batch_size=BATCH_SIZE,\n epochs=EPOCHS,\n )\n\n assert_classification_works(clf)\n\n def test_classify_class_build_fn(self):\n \"\"\"Tests for errors using a class implementing __call__.\"\"\"\n\n class ClassBuildFnClf:\n def __call__(self, hidden_dim):\n return build_fn_clf(hidden_dim)\n\n clf = wrappers.KerasClassifier(\n build_fn=ClassBuildFnClf(),\n hidden_dim=HIDDEN_DIM,\n batch_size=BATCH_SIZE,\n epochs=EPOCHS,\n )\n\n assert_classification_works(clf)\n\n def test_classify_inherit_class_build_fn(self):\n \"\"\"Tests for errors using an inherited class.\"\"\"\n\n class InheritClassBuildFnClf(wrappers.KerasClassifier):\n def __call__(self, hidden_dim):\n return build_fn_clf(hidden_dim)\n\n clf = InheritClassBuildFnClf(\n build_fn=None,\n hidden_dim=HIDDEN_DIM,\n batch_size=BATCH_SIZE,\n epochs=EPOCHS,\n )\n\n assert_classification_works(clf)\n\n def test_regression_build_fn(self):\n \"\"\"Tests for errors using KerasRegressor.\"\"\"\n reg = wrappers.KerasRegressor(\n build_fn=build_fn_reg,\n hidden_dim=HIDDEN_DIM,\n batch_size=BATCH_SIZE,\n epochs=EPOCHS,\n )\n\n assert_regression_works(reg)\n\n def test_regression_class_build_fn(self):\n \"\"\"Tests for errors using KerasRegressor implementing __call__.\"\"\"\n\n class ClassBuildFnReg:\n def __call__(self, hidden_dim):\n return build_fn_reg(hidden_dim)\n\n reg = wrappers.KerasRegressor(\n build_fn=ClassBuildFnReg(),\n hidden_dim=HIDDEN_DIM,\n batch_size=BATCH_SIZE,\n epochs=EPOCHS,\n )\n\n assert_regression_works(reg)\n\n def test_regression_inherit_class_build_fn(self):\n \"\"\"Tests for errors using KerasRegressor inherited.\"\"\"\n\n class InheritClassBuildFnReg(wrappers.KerasRegressor):\n def __call__(self, hidden_dim):\n return build_fn_reg(hidden_dim)\n\n reg = InheritClassBuildFnReg(\n build_fn=None,\n hidden_dim=HIDDEN_DIM,\n batch_size=BATCH_SIZE,\n epochs=EPOCHS,\n )\n\n assert_regression_works(reg)\n\n\ndef load_digits8x8():\n \"\"\"Load image 8x8 dataset.\"\"\"\n data = load_digits()\n data.data = data.data.reshape([data.data.shape[0], 1, 8, 8]) / 16.0\n # Convert NCHW to NHWC\n # Convert back to numpy or sklearn funcs (GridSearchCV, etc.) WILL fail\n data.data = np.transpose(data.data, [0, 2, 3, 1])\n K.set_image_data_format(\"channels_last\")\n return data\n\n\ndef check(estimator, loader):\n \"\"\"Run basic checks (fit, score, pickle) on estimator.\"\"\"\n data = loader()\n # limit to 100 data points to speed up testing\n X, y = data.data[:100], data.target[:100]\n estimator.fit(X, y)\n estimator.predict(X)\n score = estimator.score(X, y)\n serialized_estimator = pickle.dumps(estimator)\n deserialized_estimator = pickle.loads(serialized_estimator)\n deserialized_estimator.predict(X)\n score_new = deserialized_estimator.score(X, y)\n np.testing.assert_almost_equal(score, score_new)\n assert True\n\n\ndef build_fn_regs(X, n_outputs_, hidden_layer_sizes=None, n_classes_=None):\n \"\"\"Dynamically build regressor.\"\"\"\n if hidden_layer_sizes is None:\n hidden_layer_sizes = []\n model = Sequential()\n model.add(Dense(X.shape[1], activation=\"relu\", input_shape=X.shape[1:]))\n for size in hidden_layer_sizes:\n model.add(Dense(size, activation=\"relu\"))\n model.add(Dense(n_outputs_))\n model.compile(\"adam\", loss=\"mean_squared_error\")\n return model\n\n\ndef build_fn_clss(X, n_outputs_, hidden_layer_sizes=None, n_classes_=None):\n \"\"\"Dynamically build classifier.\"\"\"\n if hidden_layer_sizes is None:\n hidden_layer_sizes = []\n model = Sequential()\n model.add(Dense(X.shape[1], activation=\"relu\", input_shape=X.shape[1:]))\n for size in hidden_layer_sizes:\n model.add(Dense(size, activation=\"relu\"))\n model.add(Dense(1, activation=\"softmax\"))\n model.compile(\"adam\", loss=\"binary_crossentropy\", metrics=[\"accuracy\"])\n return model\n\n\ndef build_fn_clscs(X, n_outputs_, hidden_layer_sizes=None, n_classes_=None):\n \"\"\"Dynamically build functional API regressor.\"\"\"\n if hidden_layer_sizes is None:\n hidden_layer_sizes = []\n model = Sequential()\n model.add(Conv2D(3, (3, 3), input_shape=X.shape[1:]))\n model.add(Flatten())\n for size in hidden_layer_sizes:\n model.add(Dense(size, activation=\"relu\"))\n model.add(Dense(n_classes_, activation=\"softmax\"))\n model.compile(\n \"adam\", loss=\"categorical_crossentropy\", metrics=[\"accuracy\"]\n )\n return model\n\n\ndef build_fn_clscf(X, n_outputs_, hidden_layer_sizes=None, n_classes_=None):\n \"\"\"Dynamically build functional API classifier.\"\"\"\n if hidden_layer_sizes is None:\n hidden_layer_sizes = []\n x = Input(shape=X.shape[1:])\n z = Conv2D(3, (3, 3))(x)\n z = Flatten()(z)\n for size in hidden_layer_sizes:\n z = Dense(size, activation=\"relu\")(z)\n y = Dense(n_classes_, activation=\"softmax\")(z)\n model = Model(inputs=x, outputs=y)\n model.compile(\n \"adam\", loss=\"categorical_crossentropy\", metrics=[\"accuracy\"]\n )\n return model\n\n\nCONFIG = {\n \"MLPRegressor\": (\n load_boston,\n KerasRegressor,\n build_fn_regs,\n (BaggingRegressor, AdaBoostRegressor),\n ),\n \"MLPClassifier\": (\n load_iris,\n KerasClassifier,\n build_fn_clss,\n (BaggingClassifier, AdaBoostClassifier),\n ),\n \"CNNClassifier\": (\n load_digits8x8,\n KerasClassifier,\n build_fn_clscs,\n (BaggingClassifier, AdaBoostClassifier),\n ),\n \"CNNClassifierF\": (\n load_digits8x8,\n KerasClassifier,\n build_fn_clscf,\n (BaggingClassifier, AdaBoostClassifier),\n ),\n}\n\n\nclass TestAdvancedAPIFuncs:\n \"\"\"Tests advanced features such as pipelines and hyperparameter tuning.\"\"\"\n\n def test_standalone(self):\n \"\"\"Tests standalone estimator.\"\"\"\n for config in [\n \"MLPRegressor\",\n \"MLPClassifier\",\n \"CNNClassifier\",\n \"CNNClassifierF\",\n ]:\n loader, model, build_fn, _ = CONFIG[config]\n estimator = model(build_fn, epochs=1)\n check(estimator, loader)\n\n def test_pipeline(self):\n \"\"\"Tests compatibility with Scikit-learn's pipeline.\"\"\"\n for config in [\"MLPRegressor\", \"MLPClassifier\"]:\n loader, model, build_fn, _ = CONFIG[config]\n estimator = model(build_fn, epochs=1)\n estimator = Pipeline([(\"s\", StandardScaler()), (\"e\", estimator)])\n check(estimator, loader)\n\n def test_searchcv(self):\n \"\"\"Tests compatibility with Scikit-learn's hyperparameter search CV.\"\"\"\n for config in [\n \"MLPRegressor\",\n \"MLPClassifier\",\n \"CNNClassifier\",\n \"CNNClassifierF\",\n ]:\n loader, model, build_fn, _ = CONFIG[config]\n estimator = model(\n build_fn, epochs=1, validation_split=0.1, hidden_layer_sizes=[]\n )\n check(\n GridSearchCV(estimator, {\"hidden_layer_sizes\": [[], [5]]}),\n loader,\n )\n check(\n RandomizedSearchCV(\n estimator,\n {\"epochs\": np.random.randint(1, 5, 2)},\n n_iter=2,\n ),\n loader,\n )\n\n def test_ensemble(self):\n \"\"\"Tests compatibility with Scikit-learn's ensembles.\"\"\"\n for config in [\"MLPRegressor\", \"MLPClassifier\"]:\n loader, model, build_fn, ensembles = CONFIG[config]\n base_estimator = model(build_fn, epochs=1)\n for ensemble in ensembles:\n estimator = ensemble(\n base_estimator=base_estimator, n_estimators=2\n )\n check(estimator, loader)\n\n def test_calibratedclassifiercv(self):\n \"\"\"Tests compatibility with Scikit-learn's calibrated classifier CV.\"\"\"\n for config in [\"MLPClassifier\"]:\n loader, _, build_fn, _ = CONFIG[config]\n base_estimator = KerasClassifier(build_fn, epochs=1)\n estimator = CalibratedClassifierCV(\n base_estimator=base_estimator, cv=5\n )\n check(estimator, loader)\n\n\nclass SentinalCallback(keras.callbacks.Callback):\n \"\"\"\n Callback class that sets an internal value once it's been acessed.\n \"\"\"\n\n called = 0\n\n def on_train_begin(self, logs=None):\n \"\"\"Increments counter.\"\"\"\n self.called += 1\n\n\nclass ClassWithCallback(wrappers.KerasClassifier):\n \"\"\"Must be defined at top level to be picklable.\n \"\"\"\n\n def __init__(self, **sk_params):\n self.callbacks = [SentinalCallback()]\n super().__init__(**sk_params)\n\n def __call__(self, hidden_dim):\n return build_fn_clf(hidden_dim)\n\n\nclass TestCallbacks:\n \"\"\"Tests use of Callbacks.\"\"\"\n\n def test_callbacks_passed_as_arg(self):\n \"\"\"Tests estimators created passing a callback to __init__.\"\"\"\n for config in [\n \"MLPRegressor\",\n \"MLPClassifier\",\n \"CNNClassifier\",\n \"CNNClassifierF\",\n ]:\n loader, model, build_fn, _ = CONFIG[config]\n callback = SentinalCallback()\n estimator = model(build_fn, epochs=1, callbacks=[callback])\n # check that callback did not break estimator\n check(estimator, loader)\n # check that callback is preserved after pickling\n data = loader()\n X, y = data.data[:100], data.target[:100]\n estimator.fit(X, y)\n assert estimator.callbacks[0].called != SentinalCallback.called\n old_callback = estimator.callbacks[0]\n deserialized_estimator = pickle.loads(pickle.dumps(estimator))\n assert (\n deserialized_estimator.callbacks[0].called\n == old_callback.called\n )\n\n def test_callbacks_inherit(self):\n \"\"\"Test estimators that inherit from KerasClassifier and implement\n their own callbacks in their __init___.\n \"\"\"\n clf = ClassWithCallback(\n hidden_dim=HIDDEN_DIM, batch_size=BATCH_SIZE, epochs=EPOCHS\n )\n\n assert_classification_works(clf)\n assert clf.callbacks[0].called != SentinalCallback.called\n serialized_estimator = pickle.dumps(clf)\n deserialized_estimator = pickle.loads(serialized_estimator)\n assert (\n deserialized_estimator.callbacks[0].called\n == clf.callbacks[0].called\n )\n assert_classification_works(deserialized_estimator)\n\n\nclass TestSampleWeights:\n \"\"\"Tests involving the sample_weight parameter.\n TODO: fix warning regarding sample_weight shape coercing.\n \"\"\"\n\n @staticmethod\n def check_sample_weights_work(estimator):\n \"\"\"Checks that using the parameter sample_weight does not cause\n issues (it does not check if the parameter actually works as intended).\n \"\"\"\n (x_train, y_train), (x_test, _) = testing_utils.get_test_data(\n train_samples=TRAIN_SAMPLES,\n test_samples=TEST_SAMPLES,\n input_shape=(INPUT_DIM,),\n num_classes=NUM_CLASSES,\n )\n s_w_train = np.random.randn(x_train.shape[0])\n\n # check that we can train with sample weights\n # TODO: how do we reliably check the effect of training with\n # sample_weights?\n estimator.fit(x_train, y_train, sample_weight=s_w_train)\n estimator.predict(x_test)\n\n # now train with no sample weights, test scoring\n estimator.fit(x_train, y_train, sample_weight=None)\n # re-use training data to try to get score > 0\n score_n_w = estimator.score(x_train, y_train)\n score_w = estimator.score(x_train, y_train, sample_weight=s_w_train)\n # check that sample weights did *something*\n try:\n np.testing.assert_array_almost_equal(score_n_w, score_w)\n except AssertionError:\n return\n\n raise AssertionError(\"`sample_weight` seemed to have no effect.\")\n\n def test_classify_build_fn(self):\n clf = wrappers.KerasClassifier(\n build_fn=build_fn_clf,\n hidden_dim=HIDDEN_DIM,\n batch_size=BATCH_SIZE,\n epochs=EPOCHS,\n )\n self.check_sample_weights_work(clf)\n\n def test_reg_build_fn(self):\n clf = wrappers.KerasRegressor(\n build_fn=build_fn_reg,\n hidden_dim=HIDDEN_DIM,\n batch_size=BATCH_SIZE,\n epochs=EPOCHS,\n )\n self.check_sample_weights_work(clf)\n\n\ndef dynamic_classifier(X, cls_type_, n_classes_, n_outputs_keras_):\n \"\"\"Creates a basic MLP classifier dynamically choosing binary/multiclass\n classification loss and ouput activations.\n \"\"\"\n n_features = X.shape[1]\n\n inp = Input(shape=(n_features,))\n\n x1 = Dense(100)(inp)\n\n if cls_type_ == \"binary\":\n loss = \"binary_crossentropy\"\n out = [Dense(1, activation=\"sigmoid\")(x1)]\n elif cls_type_ == \"multilabel-indicator\":\n loss = \"binary_crossentropy\"\n out = [\n Dense(1, activation=\"sigmoid\")(x1) for _ in range(n_outputs_keras_)\n ]\n elif cls_type_ == \"multiclass-multioutput\":\n loss = \"binary_crossentropy\"\n out = [Dense(n, activation=\"softmax\")(x1) for n in n_classes_]\n else:\n # multiclass\n loss = \"categorical_crossentropy\"\n out = [Dense(n_classes_, activation=\"softmax\")(x1)]\n\n model = Model([inp], out)\n\n model.compile(optimizer=\"adam\", loss=loss)\n\n return model\n\n\ndef dynamic_regressor(X, n_outputs_keras_):\n \"\"\"Creates a basic MLP regressor dynamically.\n \"\"\"\n n_features = X.shape[1]\n\n inp = Input(shape=(n_features,))\n\n x1 = Dense(100)(inp)\n\n out = [Dense(n_outputs_keras_)(x1)]\n\n model = Model([inp], out)\n\n model.compile(\n optimizer=\"adam\", loss=wrappers.KerasRegressor.root_mean_squared_error,\n )\n return model\n\n\nclass FullyCompliantClassifier(wrappers.KerasClassifier):\n \"\"\"A classifier that sets all parameters in __init__ and nothing more.\"\"\"\n\n def __init__(\n self, hidden_dim=HIDDEN_DIM, batch_size=BATCH_SIZE, epochs=EPOCHS\n ):\n self.hidden_dim = hidden_dim\n self.batch_size = batch_size\n self.epochs = epochs\n return super().__init__()\n\n def __call__(self, X, cls_type_, n_classes_, n_outputs_keras_):\n return dynamic_classifier(X, cls_type_, n_classes_, n_outputs_keras_)\n\n\nclass FullyCompliantRegressor(wrappers.KerasRegressor):\n \"\"\"A classifier that sets all parameters in __init__ and nothing more.\"\"\"\n\n def __init__(\n self, hidden_dim=HIDDEN_DIM, batch_size=BATCH_SIZE, epochs=EPOCHS\n ):\n self.hidden_dim = hidden_dim\n self.batch_size = batch_size\n self.epochs = epochs\n return super().__init__()\n\n def __call__(self, X, n_outputs_keras_):\n return dynamic_regressor(X, n_outputs_keras_)\n\n\[email protected](reason=\"Issues not yet fixed\")\nclass TestFullyCompliantWrappers:\n \"\"\"Tests wrappers that fully comply with the Scikit-Learn\n API by not using kwargs. Testing done with Scikit-Learn's\n internal model validation tool\n \"\"\"\n\n @pytest.mark.parametrize(\n \"check\", check_estimator(FullyCompliantClassifier, generate_only=True)\n )\n def test_fully_compliant_classifier_instance(self, check):\n check[1](check[0])\n\n @pytest.mark.parametrize(\n \"check\", check_estimator(FullyCompliantRegressor, generate_only=True)\n )\n def test_fully_compliant_regressor_instance(self, check):\n check[1](check[0])\n\n\nclass TestOutputShapes:\n \"\"\"Tests that compare output shapes to `MLPClassifier` from sklearn to\n check that ouput shapes respect sklearn API.\n \"\"\"\n\n @classmethod\n def setup_class(cls):\n cls.keras_clf = KerasClassifier(build_fn=dynamic_classifier)\n cls.sklearn_clf = MLPClassifier()\n\n def test_1d_multiclass(self):\n \"\"\"Compares KerasClassifier prediction output shape against\n sklearn.neural_net.MPLClassifier for 1D multi-class (n_samples,).\n \"\"\"\n # crate 1D multiclass labels\n (x_train, y_train), (x_test, _) = testing_utils.get_test_data(\n train_samples=TRAIN_SAMPLES,\n test_samples=TEST_SAMPLES,\n input_shape=(INPUT_DIM,),\n num_classes=4,\n )\n self.keras_clf.fit(X=x_train, y=y_train)\n self.sklearn_clf.fit(X=x_train, y=y_train)\n y_pred_keras = self.keras_clf.predict(X=x_test)\n y_pred_sklearn = self.sklearn_clf.predict(X=x_test)\n assert y_pred_keras.shape == y_pred_sklearn.shape\n y_pred_prob_keras = self.keras_clf.predict_proba(X=x_test)\n y_pred_prob_sklearn = self.sklearn_clf.predict_proba(X=x_test)\n assert y_pred_prob_keras.shape == y_pred_prob_sklearn.shape\n\n def test_2d_multiclass(self):\n \"\"\"Compares KerasClassifier prediction output shape against\n sklearn.neural_net.MPLClassifier for 2D multi-class (n_samples,1).\n \"\"\"\n # crate 2D multiclass labels\n (x_train, y_train), (x_test, _) = testing_utils.get_test_data(\n train_samples=TRAIN_SAMPLES,\n test_samples=TEST_SAMPLES,\n input_shape=(INPUT_DIM,),\n num_classes=4,\n )\n y_train = y_train.reshape(-1, 1)\n self.keras_clf.fit(X=x_train, y=y_train)\n self.sklearn_clf.fit(X=x_train, y=y_train)\n y_pred_keras = self.keras_clf.predict(X=x_test)\n y_pred_sklearn = self.sklearn_clf.predict(X=x_test)\n assert y_pred_keras.shape == y_pred_sklearn.shape\n y_pred_prob_keras = self.keras_clf.predict_proba(X=x_test)\n y_pred_prob_sklearn = self.sklearn_clf.predict_proba(X=x_test)\n assert y_pred_prob_keras.shape == y_pred_prob_sklearn.shape\n\n def test_1d_binary(self):\n \"\"\"Compares KerasClassifier prediction output shape against\n sklearn.neural_net.MPLClassifier for binary (n_samples,).\n \"\"\"\n # create 1D binary labels\n (x_train, y_train), (x_test, _) = testing_utils.get_test_data(\n train_samples=TRAIN_SAMPLES,\n test_samples=TEST_SAMPLES,\n input_shape=(INPUT_DIM,),\n num_classes=2,\n )\n self.keras_clf.fit(X=x_train, y=y_train)\n self.sklearn_clf.fit(X=x_train, y=y_train)\n y_pred_keras = self.keras_clf.predict(X=x_test)\n y_pred_sklearn = self.sklearn_clf.predict(X=x_test)\n assert y_pred_keras.shape == y_pred_sklearn.shape\n y_pred_prob_keras = self.keras_clf.predict_proba(X=x_test)\n y_pred_prob_sklearn = self.sklearn_clf.predict_proba(X=x_test)\n assert y_pred_prob_keras.shape == y_pred_prob_sklearn.shape\n\n def test_2d_binary(self):\n \"\"\"Compares KerasClassifier prediction output shape against\n sklearn.neural_net.MPLClassifier for 2D binary (n_samples,1).\n \"\"\"\n # create 2D binary labels\n (x_train, y_train), (x_test, _) = testing_utils.get_test_data(\n train_samples=TRAIN_SAMPLES,\n test_samples=TEST_SAMPLES,\n input_shape=(INPUT_DIM,),\n num_classes=2,\n )\n y_train = y_train.reshape(-1, 1)\n self.keras_clf.fit(X=x_train, y=y_train)\n self.sklearn_clf.fit(X=x_train, y=y_train)\n y_pred_keras = self.keras_clf.predict(X=x_test)\n y_pred_sklearn = self.sklearn_clf.predict(X=x_test)\n assert y_pred_keras.shape == y_pred_sklearn.shape\n y_pred_prob_keras = self.keras_clf.predict_proba(X=x_test)\n y_pred_prob_sklearn = self.sklearn_clf.predict_proba(X=x_test)\n assert y_pred_prob_keras.shape == y_pred_prob_sklearn.shape\n\n\nclass TestPrebuiltModel:\n \"\"\"Tests using a prebuilt model instance.\"\"\"\n\n def test_prebuilt_model(self):\n \"\"\"Tests using a prebuilt model.\"\"\"\n for config in [\n \"MLPRegressor\",\n \"MLPClassifier\",\n \"CNNClassifier\",\n \"CNNClassifierF\",\n ]:\n loader, model, build_fn, _ = CONFIG[config]\n data = loader()\n x_train, y_train = data.data[:100], data.target[:100]\n\n n_classes_ = np.unique(y_train).size\n # make y the same shape as will be used by .fit\n if config != \"MLPRegressor\":\n y_train = to_categorical(y_train)\n keras_model = build_fn(\n X=x_train, n_classes_=n_classes_, n_outputs_=1\n )\n else:\n keras_model = build_fn(X=x_train, n_outputs_=1)\n\n estimator = model(build_fn=keras_model)\n check(estimator, loader)\n\n def test_uncompiled_prebuilt_model_raises_error(self):\n \"\"\"Tests that an uncompiled model cannot be used as build_fn param.\"\"\"\n\n for config in [\n \"MLPRegressor\",\n \"MLPClassifier\",\n \"CNNClassifier\",\n \"CNNClassifierF\",\n ]:\n loader, model, build_fn, _ = CONFIG[config]\n data = loader()\n x_train, y_train = data.data[:100], data.target[:100]\n\n n_classes_ = np.unique(y_train).size\n # make y the same shape as will be used by .fit\n if config != \"MLPRegressor\":\n y_train = to_categorical(y_train)\n keras_model = build_fn(\n X=x_train, n_classes_=n_classes_, n_outputs_=1\n )\n else:\n keras_model = build_fn(X=x_train, n_outputs_=1)\n\n # clone to simulate uncompiled model\n keras_model = clone_model(keras_model)\n estimator = model(build_fn=keras_model)\n with pytest.raises(ValueError):\n check(estimator, loader)\n\n\nclass FunctionalAPIMultiInputClassifier(KerasClassifier):\n \"\"\"Tests Functional API Classifier with 2 inputs.\n \"\"\"\n\n def __call__(self, X, n_classes_):\n inp1 = Input((1,))\n inp2 = Input((3,))\n\n x1 = Dense(100)(inp1)\n x2 = Dense(100)(inp2)\n\n x3 = Concatenate(axis=-1)([x1, x2])\n\n cat_out = Dense(n_classes_, activation=\"softmax\")(x3)\n\n model = Model([inp1, inp2], [cat_out])\n losses = [\"categorical_crossentropy\"]\n model.compile(optimizer=\"adam\", loss=losses, metrics=[\"accuracy\"])\n\n return model\n\n @staticmethod\n def _pre_process_X(X):\n \"\"\"To support multiple inputs, a custom method must be defined.\n \"\"\"\n return [X[:, 0], X[:, 1:4]], dict()\n\n\nclass FunctionalAPIMultiOutputClassifier(KerasClassifier):\n \"\"\"Tests Functional API Classifier with 2 outputs of different type.\n \"\"\"\n\n def __call__(self, X, n_classes_):\n inp = Input((4,))\n\n x1 = Dense(100)(inp)\n\n binary_out = Dense(1, activation=\"sigmoid\")(x1)\n cat_out = Dense(n_classes_[1], activation=\"softmax\")(x1)\n\n model = Model([inp], [binary_out, cat_out])\n losses = [\"binary_crossentropy\", \"categorical_crossentropy\"]\n model.compile(optimizer=\"adam\", loss=losses, metrics=[\"accuracy\"])\n\n return model\n\n def _post_process_y(self, y):\n \"\"\"To support targets of different type, we need to post-precess each one\n manually, there is no way to determine the types accurately.\n\n Takes KerasClassifier._post_process_y as a starting point and\n hardcodes the post-processing.\n \"\"\"\n classes_ = self.classes_\n\n class_predictions = [\n classes_[0][np.where(y[0] > 0.5, 1, 0)],\n classes_[1][np.argmax(y[1], axis=1)],\n ]\n\n class_probabilities = np.squeeze(np.column_stack(y))\n\n y = np.squeeze(np.column_stack(class_predictions))\n\n extra_args = {\"class_probabilities\": class_probabilities}\n\n return y, extra_args\n\n def score(self, X, y):\n \"\"\"Taken from sklearn.multiouput.MultiOutputClassifier\n \"\"\"\n y_pred = self.predict(X)\n return np.mean(np.all(y == y_pred, axis=1))\n\n\nclass FunctionAPIMultiLabelClassifier(KerasClassifier):\n \"\"\"Tests Functional API Classifier with multiple binary outputs.\n \"\"\"\n\n def __call__(self, X, n_outputs_):\n inp = Input((4,))\n\n x1 = Dense(100)(inp)\n\n outputs = []\n for _ in range(n_outputs_):\n # simulate multiple binary classification outputs\n # in reality, these would come from different nodes\n outputs.append(Dense(1, activation=\"sigmoid\")(x1))\n\n model = Model(inp, outputs)\n losses = \"binary_crossentropy\"\n model.compile(optimizer=\"adam\", loss=losses, metrics=[\"accuracy\"])\n\n return model\n\n\nclass FunctionAPIMultiOutputRegressor(KerasRegressor):\n \"\"\"Tests Functional API Regressor with multiple outputs.\n \"\"\"\n\n def __call__(self, X, n_outputs_):\n inp = Input((INPUT_DIM,))\n\n x1 = Dense(100)(inp)\n\n outputs = [Dense(n_outputs_)(x1)]\n\n model = Model([inp], outputs)\n losses = \"mean_squared_error\"\n model.compile(optimizer=\"adam\", loss=losses, metrics=[\"mse\"])\n\n return model\n\n\[email protected]_utils.register_keras_serializable()\nclass CustomLoss(keras.losses.MeanSquaredError):\n \"\"\"Dummy custom loss.\"\"\"\n\n\[email protected]_utils.register_keras_serializable()\nclass CustomModelRegistered(Model):\n \"\"\"Dummy custom Model subclass that is registered to be serializable.\"\"\"\n\n\nclass CustomModelUnregistered(Model):\n \"\"\"Dummy custom Model subclass that is not registered to be\n serializable.\"\"\"\n\n\ndef build_fn_regs_custom_loss(X, n_outputs_, hidden_layer_sizes=None):\n \"\"\"Build regressor with subclassed loss function.\"\"\"\n if hidden_layer_sizes is None:\n hidden_layer_sizes = []\n model = Sequential()\n model.add(Dense(X.shape[1], activation=\"relu\", input_shape=X.shape[1:]))\n for size in hidden_layer_sizes:\n model.add(Dense(size, activation=\"relu\"))\n model.add(Dense(n_outputs_))\n model.compile(\"adam\", loss=CustomLoss())\n return model\n\n\ndef build_fn_regs_custom_model_reg(X, n_outputs_, hidden_layer_sizes=None):\n \"\"\"Build regressor with subclassed Model registered as serializable.\"\"\"\n if hidden_layer_sizes is None:\n hidden_layer_sizes = []\n x = Input(shape=X.shape[1])\n z = Dense(X.shape[1], activation=\"relu\")(x)\n for size in hidden_layer_sizes:\n z = Dense(size, activation=\"relu\")(z)\n y = Dense(n_outputs_, activation=\"linear\")(z)\n model = CustomModelRegistered(inputs=x, outputs=y)\n model.compile(\"adam\", loss=\"mean_squared_error\")\n return model\n\n\ndef build_fn_regs_custom_model_unreg(X, n_outputs_, hidden_layer_sizes=None):\n \"\"\"Build regressor with subclassed Model not registered as serializable.\"\"\"\n if hidden_layer_sizes is None:\n hidden_layer_sizes = []\n x = Input(shape=X.shape[1])\n z = Dense(X.shape[1], activation=\"relu\")(x)\n for size in hidden_layer_sizes:\n z = Dense(size, activation=\"relu\")(z)\n y = Dense(n_outputs_, activation=\"linear\")(z)\n model = CustomModelUnregistered(inputs=x, outputs=y)\n model.compile(\"adam\", loss=\"mean_squared_error\")\n return model\n\n\nclass TestSerializeCustomLayers:\n \"\"\"Tests serializing custom layers.\"\"\"\n\n def test_custom_loss_function(self):\n \"\"\"Test that a registered subclassed Model can be serialized.\"\"\"\n estimator = KerasRegressor(build_fn=build_fn_regs_custom_loss)\n check(estimator, load_boston)\n\n def test_custom_model_registered(self):\n \"\"\"Test that a registered subclassed loss function can be\n serialized.\"\"\"\n estimator = KerasRegressor(build_fn=build_fn_regs_custom_model_reg)\n check(estimator, load_boston)\n\n def test_custom_model_unregistered(self):\n \"\"\"Test that an unregistered subclassed Model raises an error.\"\"\"\n estimator = KerasRegressor(build_fn=build_fn_regs_custom_model_unreg)\n with pytest.raises(ValueError):\n check(estimator, load_boston)\n\n\nclass TestScoring:\n \"\"\"Tests scoring methods.\n \"\"\"\n\n def test_scoring_r2(self):\n \"\"\"Test custom R^2 implementation against scikit-learn's.\"\"\"\n n_samples = 50\n\n datasets = []\n y_true = np.arange(n_samples, dtype=float)\n y_pred = y_true + 1\n datasets.append((y_true.reshape(-1, 1), y_pred.reshape(-1, 1)))\n y_true = np.random.random_sample(size=y_true.shape)\n y_pred = np.random.random_sample(size=y_true.shape)\n datasets.append((y_true.reshape(-1, 1), y_pred.reshape(-1, 1)))\n\n def keras_backend_r2(y_true, y_pred):\n \"\"\"Wrap Keras operations to numpy.\"\"\"\n y_true = convert_to_tensor(y_true)\n y_pred = convert_to_tensor(y_pred)\n return KerasRegressor.root_mean_squared_error(\n y_true, y_pred\n ).numpy()\n\n score_functions = (keras_backend_r2,)\n correct_scorer = sklearn_r2_score\n\n for (y_true, y_pred) in datasets:\n for f in score_functions:\n np.testing.assert_almost_equal(\n f(y_true, y_pred),\n correct_scorer(y_true, y_pred),\n decimal=5,\n )\n\n\nclass TestMultiInputOutput:\n \"\"\"Tests involving multiple inputs / outputs.\n \"\"\"\n\n def test_multi_input(self):\n \"\"\"Compares to the scikit-learn RandomForestRegressor classifier.\n \"\"\"\n clf = FunctionalAPIMultiInputClassifier()\n (x_train, y_train), (x_test, y_test) = testing_utils.get_test_data(\n train_samples=TRAIN_SAMPLES,\n test_samples=TEST_SAMPLES,\n input_shape=(4,),\n num_classes=3,\n )\n\n clf.fit(x_train, y_train)\n clf.predict(x_test)\n clf.score(x_train, y_train)\n\n def test_multi_output(self):\n \"\"\"Compares to the scikit-learn RandomForestRegressor classifier.\n \"\"\"\n clf = FunctionalAPIMultiOutputClassifier()\n (x_train, y_train), (x_test, y_test) = testing_utils.get_test_data(\n train_samples=TRAIN_SAMPLES,\n test_samples=TEST_SAMPLES,\n input_shape=(4,),\n num_classes=3,\n )\n\n # simulate 2 outputs\n y_train = np.stack([y_train == 1, y_train], axis=1)\n y_test = np.stack([y_test == 1, y_test], axis=1)\n\n clf.fit(x_train, y_train)\n clf.predict(x_test)\n clf.score(x_train, y_train)\n\n def test_multi_label_clasification(self):\n \"\"\"Compares to the scikit-learn RandomForestRegressor classifier.\n \"\"\"\n clf_keras = FunctionAPIMultiLabelClassifier()\n clf_sklearn = RandomForestClassifier()\n # taken from https://scikit-learn.org/stable/modules/multiclass.html\n y = np.array([[2, 3, 4], [2], [0, 1, 3], [0, 1, 2, 3, 4], [0, 1, 2]])\n y = MultiLabelBinarizer().fit_transform(y)\n\n (x_train, _), (_, _) = testing_utils.get_test_data(\n train_samples=y.shape[0],\n test_samples=0,\n input_shape=(4,),\n num_classes=3,\n )\n\n clf_keras.fit(x_train, y)\n y_pred_keras = clf_keras.predict(x_train)\n clf_keras.score(x_train, y)\n\n clf_sklearn.fit(x_train, y)\n y_pred_sklearn = clf_sklearn.predict(x_train)\n clf_sklearn.score(x_train, y)\n\n assert y_pred_keras.shape == y_pred_sklearn.shape\n\n def test_multi_output_regression(self):\n \"\"\"Compares to the scikit-learn RandomForestRegressor classifier.\n \"\"\"\n reg_keras = FunctionAPIMultiOutputRegressor()\n reg_sklearn = RandomForestRegressor()\n # taken from https://scikit-learn.org/stable/modules/multiclass.html\n (X, _), (_, _) = testing_utils.get_test_data(\n train_samples=TRAIN_SAMPLES,\n test_samples=TEST_SAMPLES,\n input_shape=(INPUT_DIM,),\n num_classes=NUM_CLASSES,\n )\n y = np.random.random_sample(size=(TRAIN_SAMPLES, NUM_CLASSES))\n\n reg_keras.fit(X, y)\n y_pred_keras = reg_keras.predict(X)\n reg_keras.score(X, y)\n\n reg_sklearn.fit(X, y)\n y_pred_sklearn = reg_sklearn.predict(X)\n reg_sklearn.score(X, y)\n\n assert y_pred_keras.shape == y_pred_sklearn.shape\n"
] | [
[
"sklearn.neural_network.MLPClassifier",
"sklearn.ensemble.RandomForestRegressor",
"tensorflow.python.keras.layers.Flatten",
"tensorflow.python.keras.layers.Dense",
"numpy.random.random_sample",
"numpy.all",
"numpy.random.randn",
"tensorflow.python.keras.layers.Conv2D",
"sklearn.utils.estimator_checks.check_estimator",
"tensorflow.python.keras.utils.np_utils.to_categorical",
"numpy.where",
"numpy.random.randint",
"tensorflow.python.keras.layers.Activation",
"tensorflow.python.keras.models.clone_model",
"sklearn.ensemble.RandomForestClassifier",
"numpy.unique",
"numpy.arange",
"sklearn.preprocessing.MultiLabelBinarizer",
"numpy.stack",
"numpy.testing.assert_almost_equal",
"numpy.argmax",
"numpy.column_stack",
"numpy.testing.assert_array_almost_equal",
"tensorflow.python.keras.models.Sequential",
"tensorflow.python.framework.ops.convert_to_tensor",
"numpy.transpose",
"tensorflow.python.keras.layers.Input",
"numpy.array",
"numpy.sum",
"tensorflow.python.keras.testing_utils.get_test_data",
"sklearn.model_selection.GridSearchCV",
"numpy.random.seed",
"numpy.isfinite",
"tensorflow.python.keras.utils.generic_utils.register_keras_serializable",
"tensorflow.python.keras.backend.set_image_data_format",
"numpy.ones",
"tensorflow.python.keras.layers.Concatenate",
"tensorflow.python.keras.models.Model",
"sklearn.datasets.load_digits",
"numpy.isscalar",
"sklearn.calibration.CalibratedClassifierCV",
"sklearn.preprocessing.StandardScaler"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.5",
"1.4"
]
}
] |
atmyers/WarpX | [
"d9d9721d80ff2f6ceda3c1a6e32e9ab31b7f81c6"
] | [
"Examples/Modules/space_charge_initialization/analysis.py"
] | [
"#!/usr/bin/env python\n\n# Copyright 2019-2020 Axel Huebl, Remi Lehe\n#\n# This file is part of WarpX.\n#\n# License: BSD-3-Clause-LBNL\n\n\"\"\"\nThis script checks the space-charge initialization routine, by\nverifying that the space-charge field of a Gaussian beam corresponds to\nthe expected theoretical field.\n\"\"\"\nimport sys\nimport matplotlib\nmatplotlib.use('Agg')\nimport matplotlib.pyplot as plt\nimport yt\nimport numpy as np\nimport scipy.constants as scc\nfrom scipy.special import gammainc\nyt.funcs.mylog.setLevel(0)\n\n# Parameters from the Simulation\nQtot = -1.e-20\nr0 = 2.e-6\n\n# Open data file\nfilename = sys.argv[1]\nds = yt.load( filename )\n# Extract data\nad0 = ds.covering_grid(level=0, left_edge=ds.domain_left_edge, dims=ds.domain_dimensions)\nEx_array = ad0['Ex'].to_ndarray().squeeze()\nif ds.dimensionality == 2:\n # Rename the z dimension as y, so as to make this script work for 2d and 3d\n Ey_array = ad0['Ez'].to_ndarray().squeeze()\nelif ds.dimensionality == 3:\n Ey_array = ad0['Ey'].to_ndarray()\n Ez_array = ad0['Ez'].to_ndarray()\n\n# Extract grid coordinates\nNx, Ny, Nz = ds.domain_dimensions\nxmin, ymin, zmin = ds.domain_left_edge.v\nLx, Ly, Lz = ds.domain_width.v\nx = xmin + Lx/Nx*(0.5+np.arange(Nx))\ny = ymin + Ly/Ny*(0.5+np.arange(Ny))\nz = zmin + Lz/Nz*(0.5+np.arange(Nz))\n\n# Compute theoretical field\nif ds.dimensionality == 2:\n x_2d, y_2d = np.meshgrid(x, y, indexing='ij')\n r2 = x_2d**2 + y_2d**2\n factor = (Qtot/r0)/(2*np.pi*scc.epsilon_0*r2) * (1-np.exp(-r2/(2*r0**2)))\n Ex_th = x_2d * factor\n Ey_th = y_2d * factor\nelif ds.dimensionality == 3:\n x_2d, y_2d, z_2d = np.meshgrid(x, y, z, indexing='ij')\n r2 = x_2d**2 + y_2d**2 + z_2d**2\n factor = Qtot/(4*np.pi*scc.epsilon_0*r2**1.5) * gammainc(3./2, r2/(2.*r0**2))\n Ex_th = factor*x_2d\n Ey_th = factor*y_2d\n Ez_th = factor*z_2d\n\n# Plot theory and data\ndef make_2d(arr):\n if arr.ndim == 3:\n return arr[:,:,Nz//2]\n else:\n return arr\nplt.figure(figsize=(10,10))\nplt.subplot(221)\nplt.title('Ex: Theory')\nplt.imshow(make_2d(Ex_th))\nplt.colorbar()\nplt.subplot(222)\nplt.title('Ex: Simulation')\nplt.imshow(make_2d(Ex_array))\nplt.colorbar()\nplt.subplot(223)\nplt.title('Ey: Theory')\nplt.imshow(make_2d(Ey_th))\nplt.colorbar()\nplt.subplot(224)\nplt.title('Ey: Simulation')\nplt.imshow(make_2d(Ey_array))\nplt.colorbar()\nplt.savefig('Comparison.png')\n\n# Automatically check the results\ndef check(E, E_th, label):\n print( 'Relative error in %s: %.3f'%(\n label, abs(E-E_th).max()/E_th.max()))\n tolerance_rel = 0.1\n print(\"tolerance_rel: \" + str(tolerance_rel))\n assert np.allclose( E, E_th, atol=tolerance_rel*E_th.max() )\n\ncheck( Ex_array, Ex_th, 'Ex' )\ncheck( Ey_array, Ey_th, 'Ey' )\nif ds.dimensionality == 3:\n check( Ez_array, Ez_th, 'Ez' )\n"
] | [
[
"matplotlib.pyplot.title",
"scipy.special.gammainc",
"matplotlib.use",
"numpy.arange",
"matplotlib.pyplot.savefig",
"matplotlib.pyplot.colorbar",
"matplotlib.pyplot.subplot",
"numpy.exp",
"numpy.meshgrid",
"matplotlib.pyplot.figure"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
spencerimp/mri_segmentation | [
"4b1195c4520b09f0759c11c890ebc6331e3ecb06"
] | [
"cnn_segmentation/utils/voxel_sampling.py"
] | [
"from __future__ import print_function\nimport numpy as np\nfrom skimage.morphology import cube, dilation\n\n\ndef create_boundary(lab, regions, width):\n \"\"\"Create boundary of each region.\n\n For each non-zeros regions, create a\n boundary of dilation. Take the union\n of these boundary areas to have a\n so-called boundary zone, and assign it\n a new label as max(regions) + 1\n\n Omit the new boundary voxel if it overlaps\n with any non-zero region.\n\n For example, the input labeling has non-background regions\n [1, 2, 3], then the corresponding boundary regions\n are [4, 5, 6].\n\n Arguments:\n lab: numpy array\n The 3d labeling matrix\n regions: list or array of int\n The non-background region list\n width: int\n The boundary width\n \"\"\"\n kernel = cube(2 * width + 1)\n lab_dilated = lab.copy()\n n_regions = len(regions)\n idx_protected = np.in1d(lab.ravel(),\n regions).reshape(lab.shape)\n for region in regions:\n lab_binary = np.zeros(lab.shape, dtype=lab.dtype)\n lab_binary[np.where(lab == region)] = 1\n lab_boundary = dilation(lab_binary, kernel) - lab_binary\n\n # assign a label to this boundary\n idx_boundary = (lab_boundary == 1)\n lab_dilated[idx_boundary & ~idx_protected] = region + n_regions\n return lab_dilated\n\n\nclass PickVoxel():\n \"\"\"\n Template of picking voxels.\n \"\"\"\n def __init__(self, labels, voxels, ignored_labels=None):\n assert np.prod(labels.shape) == voxels.shape[0]\n self.labels = labels\n self.regions = np.unique(labels)\n self.voxels = voxels\n if ignored_labels:\n self.regions = list(set(self.regions) - set(ignored_labels))\n idx = np.in1d(self.labels.ravel(),\n self.regions).reshape(self.labels.shape)\n reg_x, reg_y, reg_z = np.where(idx)\n self.voxels = np.array(list(zip(reg_x, reg_y, reg_z)))\n\n def pick_voxels(self, n_voxels):\n raise NotImplementedError\n\n def pick_all(self):\n raise NotImplementedError\n\n\nclass PickVoxelRandom(PickVoxel):\n def __init__(self, labels, voxels, ignored_labels=None):\n super(PickVoxelRandom, self).__init__(labels,\n voxels,\n ignored_labels)\n\n def pick_voxels(self, n_voxels):\n \"\"\"Randomly pick up voxels regardless of label.\"\"\"\n rp = np.random.permutation(range(self.voxels.shape[0]))\n idx_voxels = rp[:n_voxels]\n return self.voxels[idx_voxels]\n\n def pick_all(self):\n return self.voxels\n\n\nclass PickVoxelBalanced(PickVoxel):\n def __init__(self, labels, voxels, ignored_labels=None):\n super(PickVoxelBalanced, self).__init__(labels,\n voxels,\n ignored_labels)\n\n def pick_voxels(self, n_voxels, expand_boundary=False):\n \"\"\"Pick up voxels evently from each region.\n\n In principle, each region will have n_voxels/n_region voxels.\n If any of the region does not have sufficient voxels,\n the small regions will have duplicated voxels\n to fullfil the number of voxels needed for its region.\n\n if expand_boundary is set to True,\n Sample background voxels first on the boundary of\n non-background voxels, and random sampling to get\n the rest of required background voxels.\n\n Note that if the number of voxels is less\n than the number of regions, a random sampling\n regardless of the regions is used.\n \"\"\"\n n_regions = len(self.regions)\n if n_voxels < n_regions:\n # TODO: get voxels in self.regions\n rp = np.random.permutation(range(self.voxels.shape[0]))\n idx_voxels = rp[:n_voxels]\n return self.voxels[idx_voxels]\n\n # Distribute the needed voxels to all regions\n n_exp_vx, n_remain = divmod(n_voxels, n_regions)\n # Number of voxels to be extracted\n n_needed_voxels = np.zeros((n_regions,), dtype=int)\n\n # Sample voxels as expected, leading duplicated voxels\n n_needed_voxels = n_exp_vx * np.ones((n_regions,), dtype=int)\n\n # randomly choose some non-background regions for remain voxels\n rp = np.random.permutation(len(self.regions))\n rp = rp[rp != 0]\n for reg_id in rp[:n_remain]:\n n_needed_voxels[reg_id] += 1\n\n boundary_regions = []\n # create boundary of each region\n if expand_boundary:\n nonzero_regions = self.regions.nonzero()[0]\n # TODO: make boundary_width an argument\n boundary_width = 10\n self.labels = create_boundary(self.labels,\n nonzero_regions,\n boundary_width)\n boundary_regions = list(set(np.unique(self.labels)) -\n set(self.regions))\n\n # Pick up the voxels\n region_voxels = []\n for i, reg_id in enumerate(self.regions):\n n_needed = n_needed_voxels[i]\n reg_indices = np.where(self.labels == reg_id)\n vxs = np.asarray(reg_indices).T\n n_vxs = vxs.shape[0]\n # print(\"region {} has {}, needs {}\".format(i, n_vxs, n_needed))\n # randomly pick as many as it should/could\n rp = np.random.permutation(range(n_vxs))\n sampled_vxs = vxs[rp[:n_needed]]\n region_voxels.extend(sampled_vxs)\n\n # sample duplicate voxels if region is too small\n if n_needed > n_vxs:\n print(\"Extract duplicated voxels in region {}\".format(i))\n idx_dup_vxs = np.random.randint(n_vxs, size=n_needed - n_vxs)\n dup_vxs = vxs[idx_dup_vxs]\n region_voxels.extend(dup_vxs)\n\n # extract boundary voxels seperately\n boundary_voxels = []\n for reg_id in boundary_regions:\n reg_indices = np.where(self.labels == reg_id)\n vxs = np.asarray(reg_indices).T\n rp = np.random.permutation(len(vxs))\n sampled_vxs = vxs[rp]\n boundary_voxels.extend(sampled_vxs)\n\n boundary_voxels = np.asarray(boundary_voxels)\n\n # replace background voxels with unique boundary voxels\n bg_voxels = region_voxels[:n_needed_voxels[0]]\n rp = np.random.permutation(len(boundary_voxels))\n boundary_voxels = boundary_voxels[rp]\n\n # from all boundary voxels pick some of them\n if len(boundary_voxels) > len(bg_voxels):\n boundary_voxels = boundary_voxels[:len(bg_voxels)]\n\n region_voxels[:len(boundary_voxels)] = boundary_voxels\n region_voxels = np.asarray(region_voxels)\n return region_voxels\n\n def pick_all(self, ratio='auto'):\n \"\"\"Pick up all voxels.\n\n Picks up all non-background voxels,\n and the some amount background (if sufficient).\n\n Arguments:\n ratio: int\n The ratio between non-background and background\n (default = 'auto' = 1/n_regions)\n \"\"\"\n if ratio == 'auto':\n ratio = 1 / float(len(self.regions))\n nb = self.labels.nonzero()\n nb_voxels = np.array(list(zip(nb[0], nb[1], nb[2])))\n n_nb_voxels = nb_voxels.shape[0]\n\n bg = np.where(self.labels == 0)\n bg_voxels = np.array(list(zip(bg[0], bg[1], bg[2])))\n rp = np.random.permutation(int(n_nb_voxels * ratio))\n bg_voxels = bg_voxels[rp]\n all_voxels = np.vstack((nb_voxels, bg_voxels))\n return all_voxels\n\n def pick_voxels_region(self, n_voxels, is_strict=False):\n \"\"\"Pick voxels per region.\n\n Arguments:\n n_voxels: int\n The number of voxels from each region.\n is_strict: boolean\n Whether to force the number of sampled voxels\n from each region to be the same.\n\n By default\n If a region does not contain the required amout of voxels,\n use all the voxels.\n\n If the argument is_strict is set to True,\n then all the regions will be forced to have the same amount of voxles.\n \"\"\"\n # Collect the voxels region by region\n reg_all_voxels = []\n num_voxels = np.zeros((len(self.regions),))\n for i, reg_id in enumerate(self.regions):\n reg_indices = np.where(self.labels == reg_id)\n reg_voxels = np.asarray(reg_indices).T\n reg_all_voxels.append(reg_voxels)\n num_voxels[i] = reg_voxels.shape[0]\n\n # Set up the number of voxels needed for each region\n n_needed_voxels = np.zeros((len(self.regions),)) * n_voxels\n min_num_voxels = num_voxels.min()\n if is_strict and (n_voxels > min_num_voxels):\n n_needed_voxels = np.ones((len(self.regions,))) * min_num_voxels\n\n # Check how many we can actually extract\n for i in range(len(self.regions)):\n if n_needed_voxels[i] > num_voxels[i]:\n n_needed_voxels[i] = num_voxels[i]\n\n # Pick up the voxels\n region_voxels = []\n for i in range(len(self.regions)):\n vxs = reg_all_voxels[i]\n rp = np.random.permutation(range(vxs.shape[0]))\n region_voxels.extend(vxs[rp[:n_needed_voxels[i]]])\n region_voxels = np.asarray(region_voxels)\n print(\"Total voxels sampled = {}\".format(region_voxels.shape[0]))\n return region_voxels\n\n\nclass PickVoxelBalancedNonBackground(PickVoxelBalanced):\n \"\"\"Pick up voxels evenly from each non-background region.\"\"\"\n def __init__(self, labels, voxels):\n super(PickVoxelBalancedNonBackground, self).__init__(labels,\n voxels,\n ignored_labels=[0])\n\n def pick_all(self):\n \"\"\"Pick up all non-backgrond voxels.\"\"\"\n nb = self.labels.nonzero()\n nb_voxels = np.array(list(zip(nb[0], nb[1], nb[2])))\n return nb_voxels\n"
] | [
[
"numpy.unique",
"numpy.asarray",
"numpy.ones",
"numpy.prod",
"numpy.zeros",
"numpy.where",
"numpy.vstack",
"numpy.random.randint"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
AnTuo1998/seq2seq-dialogue | [
"61af5099332b749f4026a20d4ea3380f42deb006"
] | [
"seq2seq/trainer/supervised_trainer.py"
] | [
"from __future__ import division\nimport logging\nimport os\nimport random\nimport time\n\nimport torch\nimport torchtext\nfrom torch import optim\n\nimport seq2seq\nfrom seq2seq.evaluator import Evaluator\nfrom seq2seq.loss import NLLLoss\nfrom seq2seq.optim import Optimizer\nfrom seq2seq.util.checkpoint import Checkpoint\n\nclass SupervisedTrainer(object):\n \"\"\" The SupervisedTrainer class helps in setting up a training framework in a\n supervised setting.\n\n Args:\n expt_dir (optional, str): experiment Directory to store details of the experiment,\n by default it makes a folder in the current directory to store the details (default: `experiment`).\n loss (seq2seq.loss.loss.Loss, optional): loss for training, (default: seq2seq.loss.NLLLoss)\n batch_size (int, optional): batch size for experiment, (default: 64)\n checkpoint_every (int, optional): number of batches to checkpoint after, (default: 100)\n \"\"\"\n def __init__(self, expt_dir='experiment', loss=NLLLoss(), batch_size=64,\n random_seed=None,\n checkpoint_every=100, print_every=100):\n self._trainer = \"Simple Trainer\"\n self.random_seed = random_seed\n if random_seed is not None:\n random.seed(random_seed)\n torch.manual_seed(random_seed)\n self.loss = loss\n self.evaluator = Evaluator(loss=self.loss, batch_size=batch_size)\n self.optimizer = None\n self.checkpoint_every = checkpoint_every\n self.print_every = print_every\n\n if not os.path.isabs(expt_dir):\n expt_dir = os.path.join(os.getcwd(), expt_dir)\n self.expt_dir = expt_dir\n if not os.path.exists(self.expt_dir):\n os.makedirs(self.expt_dir)\n self.batch_size = batch_size\n\n self.logger = logging.getLogger(__name__)\n\n def _train_batch(self, input_variable, input_lengths, target_variable, model, teacher_forcing_ratio):\n loss = self.loss\n # Forward propagation\n decoder_outputs, decoder_hidden, other = model(input_variable, input_lengths, target_variable,\n teacher_forcing_ratio=teacher_forcing_ratio)\n # Get loss\n loss.reset()\n for step, step_output in enumerate(decoder_outputs):\n batch_size = target_variable.size(0)\n loss.eval_batch(step_output.contiguous().view(batch_size, -1), target_variable[:, step + 1])\n # Backward propagation\n model.zero_grad()\n loss.backward()\n self.optimizer.step()\n\n return loss.get_loss()\n\n def _train_epoches(self, data, model, n_epochs, start_epoch, start_step,\n dev_data=None, teacher_forcing_ratio=0):\n log = self.logger\n\n print_loss_total = 0 # Reset every print_every\n epoch_loss_total = 0 # Reset every epoch\n\n # device = None if torch.cuda.is_available() else -1\n batch_iterator = torchtext.data.BucketIterator(\n dataset=data, batch_size=self.batch_size,\n sort=False, sort_within_batch=True,\n sort_key=lambda x: len(x.src),\n repeat=False)\n\n steps_per_epoch = len(batch_iterator)\n total_steps = steps_per_epoch * n_epochs\n\n step = start_step\n step_elapsed = 0\n for epoch in range(start_epoch, n_epochs + 1):\n log.debug(\"Epoch: %d, Step: %d\" % (epoch, step))\n\n batch_generator = batch_iterator.__iter__()\n # consuming seen batches from previous training\n for _ in range((epoch - 1) * steps_per_epoch, step):\n next(batch_generator)\n\n model.train(True)\n for batch in batch_generator:\n step += 1\n step_elapsed += 1\n\n input_variables, input_lengths = getattr(batch, seq2seq.src_field_name)\n target_variables = getattr(batch, seq2seq.tgt_field_name)\n\n loss = self._train_batch(input_variables, input_lengths.tolist(), target_variables, model, teacher_forcing_ratio)\n\n # Record average loss\n print_loss_total += loss\n epoch_loss_total += loss\n\n if step % self.print_every == 0 and step_elapsed > self.print_every:\n print_loss_avg = print_loss_total / self.print_every\n print_loss_total = 0\n log_msg = 'Progress: %d%%, Train %s: %.4f' % (\n step / total_steps * 100,\n self.loss.name,\n print_loss_avg)\n log.info(log_msg)\n\n # Checkpoint\n if step % self.checkpoint_every == 0 or step == total_steps:\n Checkpoint(model=model,\n optimizer=self.optimizer,\n epoch=epoch, step=step,\n input_vocab=data.fields[seq2seq.src_field_name].vocab,\n output_vocab=data.fields[seq2seq.tgt_field_name].vocab).save(self.expt_dir)\n\n if step_elapsed == 0: continue\n\n epoch_loss_avg = epoch_loss_total / min(steps_per_epoch, step - start_step)\n epoch_loss_total = 0\n log_msg = \"Finished epoch %d: Train %s: %.4f\" % (epoch, self.loss.name, epoch_loss_avg)\n if dev_data is not None:\n dev_loss, accuracy = self.evaluator.evaluate(model, dev_data)\n self.optimizer.update(dev_loss, epoch)\n log_msg += \", Dev %s: %.4f, Accuracy: %.4f\" % (self.loss.name, dev_loss, accuracy)\n model.train(mode=True)\n else:\n self.optimizer.update(epoch_loss_avg, epoch)\n\n log.info(log_msg)\n\n def train(self, model, data, num_epochs=5,\n resume=False, dev_data=None,\n optimizer=None, teacher_forcing_ratio=0):\n \"\"\" Run training for a given model.\n\n Args:\n model (seq2seq.models): model to run training on, if `resume=True`, it would be\n overwritten by the model loaded from the latest checkpoint.\n data (seq2seq.dataset.dataset.Dataset): dataset object to train on\n num_epochs (int, optional): number of epochs to run (default 5)\n resume(bool, optional): resume training with the latest checkpoint, (default False)\n dev_data (seq2seq.dataset.dataset.Dataset, optional): dev Dataset (default None)\n optimizer (seq2seq.optim.Optimizer, optional): optimizer for training\n (default: Optimizer(pytorch.optim.Adam, max_grad_norm=5))\n teacher_forcing_ratio (float, optional): teaching forcing ratio (default 0)\n Returns:\n model (seq2seq.models): trained model.\n \"\"\"\n # If training is set to resume\n if resume:\n latest_checkpoint_path = Checkpoint.get_latest_checkpoint(self.expt_dir)\n resume_checkpoint = Checkpoint.load(latest_checkpoint_path)\n model = resume_checkpoint.model\n self.optimizer = resume_checkpoint.optimizer\n\n # A walk around to set optimizing parameters properly\n resume_optim = self.optimizer.optimizer\n defaults = resume_optim.param_groups[0]\n defaults.pop('params', None)\n defaults.pop('initial_lr', None)\n self.optimizer.optimizer = resume_optim.__class__(model.parameters(), **defaults)\n\n start_epoch = resume_checkpoint.epoch\n step = resume_checkpoint.step\n else:\n start_epoch = 1\n step = 0\n if optimizer is None:\n optimizer = Optimizer(optim.Adam(model.parameters()), max_grad_norm=5)\n self.optimizer = optimizer\n\n self.logger.info(\"Optimizer: %s, Scheduler: %s\" % (self.optimizer.optimizer, self.optimizer.scheduler))\n\n self._train_epoches(data, model, num_epochs,\n start_epoch, step, dev_data=dev_data,\n teacher_forcing_ratio=teacher_forcing_ratio)\n return model\n"
] | [
[
"torch.manual_seed"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
gramaziokohler/compas_fab | [
"85ec40887004c33ac9764ba73c1b66c6de154457"
] | [
"src/compas_fab/robots/wrench.py"
] | [
"from __future__ import print_function\n\nimport math\n\nimport compas\nfrom compas.geometry import Vector\nfrom compas.geometry import cross_vectors\n\nif not compas.IPY:\n from scipy import stats\nelse:\n stats = None\n\n# TODO: move to some constants file? g is also defined in scipy.constants\n# standard acceleration of gravity [m/s**2]\ng = 9.80665\ngravity_vector = Vector(0, 0, -g)\n\n\n__all__ = ['Wrench']\n\n\nclass Wrench():\n \"\"\"A wrench represents force in free space, separated into its linear (force) and angular (torque) parts.\n\n Attributes\n ----------\n force : :class:`Vector`\n [Fx, Fy, Fz] force vector in Newtons\n torque : :class:`Vector`\n [Tx, Ty, Tz] moments vector in Newton-meters\n\n Examples\n --------\n >>> from compas.geometry import Vector\n >>> w = Wrench([1, 2, 3], [0.1, 0.2, 0.3])\n >>> w = Wrench(Vector(1, 2, 3), Vector(0.1, 0.2, 0.3))\n\n \"\"\"\n\n def __init__(self, force, torque):\n self.force = force\n self.torque = torque\n\n # ==========================================================================\n # factory\n # ==========================================================================\n\n @classmethod\n def from_list(cls, values):\n \"\"\"Construct a wrench from a list of 6 :obj:`float` values.\n\n Parameters\n ----------\n values : :obj:`list` of :obj:`float`\n The list of 6 values representing a wrench.\n\n Returns\n -------\n :class:`Wrench`\n The constructed wrench.\n\n Examples\n --------\n >>> w = Wrench.from_list([1, 2, 3, 0.1, 0.2, 0.3])\n \"\"\"\n force = values[0:3]\n torque = values[3:6]\n return cls(force, torque)\n\n @classmethod\n def from_data(cls, data):\n \"\"\"Construct a wrench from its data representation.\n\n Parameters\n ----------\n data : :obj:`dict`\n The data dictionary.\n\n Returns\n -------\n :class:`Wrench`\n The constructed wrench.\n\n Examples\n --------\n >>> data = {\"force\": [1, 2, 3], \"torque\": [0.1, 0.2, 0.3]}\n >>> w = Wrench.from_data(data)\n \"\"\"\n force = data[\"force\"]\n torque = data[\"torque\"]\n return cls(force, torque)\n\n @classmethod\n def by_samples(cls, wrenches, proportion_to_cut=0.1):\n \"\"\"\n Construct the wrench by sampled data, allowing to filter.\n\n Parameters\n ----------\n wrenches : list of :class:`Wrench`\n List of wrenches.\n proportion_to_cut : :obj:`float`\n Fraction to cut off of both tails of the distribution\n\n Returns\n -------\n Wrench\n The mean wrench after trimming distribution from both tails.\n\n Examples\n --------\n >>> w1 = Wrench([1, 1, 1], [.1,.1,.1])\n >>> w2 = Wrench([2, 2, 2], [.2,.2,.2])\n >>> w3 = Wrench([3, 3, 3], [.3,.3,.3])\n >>> w = Wrench.by_samples([w1, w2, w3])\n >>> print(w)\n Wrench(Vector(2.000, 2.000, 2.000), Vector(0.200, 0.200, 0.200))\n \"\"\"\n if not stats:\n raise NotImplementedError(\"Not supported on this platform\")\n\n forces = [w.force for w in wrenches]\n torques = [w.torque for w in wrenches]\n force = stats.trim_mean(forces, proportion_to_cut, axis=0).tolist()\n torque = stats.trim_mean(torques, proportion_to_cut, axis=0).tolist()\n return cls(force, torque)\n\n # ==========================================================================\n # descriptors\n # ==========================================================================\n\n @property\n def force(self):\n return self._force\n\n @force.setter\n def force(self, vector):\n force = Vector(*list(vector))\n self._force = force\n\n @property\n def torque(self):\n return self._torque\n\n @torque.setter\n def torque(self, vector):\n torque = Vector(*list(vector))\n self._torque = torque\n\n @property\n def data(self):\n \"\"\"Returns the data dictionary that represents the wrench.\n\n Returns\n -------\n dict\n The wrench data.\n \"\"\"\n return {'force': list(self.force),\n 'torque': list(self.torque)}\n\n def to_data(self):\n \"\"\"Returns the data dictionary that represents the wrench.\n\n Returns\n -------\n dict\n The wrench data.\n \"\"\"\n return self.data\n\n # ==========================================================================\n # access\n # ==========================================================================\n\n def __iter__(self):\n return iter(list(self.force) + list(self.torque))\n\n def __getitem__(self, item):\n w = list(self)\n return w[item]\n\n # ==========================================================================\n # representation\n # ==========================================================================\n\n def __repr__(self):\n return \"Wrench({!r}, {!r})\".format(self.force, self.torque)\n\n # ==========================================================================\n # helpers\n # ==========================================================================\n\n def copy(self):\n \"\"\"Make a copy of this ``Wrench``.\n\n Returns\n -------\n Wrench\n The copy.\n \"\"\"\n cls = type(self)\n return cls(self.force.copy(), self.torque.copy())\n\n # ==========================================================================\n # operators\n # ==========================================================================\n\n def __mul__(self, n):\n \"\"\"Create a ``Wrench`` multiplied by the given factor.\n\n Parameters\n ----------\n n : float\n The multiplication factor.\n\n Returns\n -------\n Wrench\n The resulting new ``Wrench``.\n\n \"\"\"\n return Wrench(self.force * n, self.torque * n)\n\n def __add__(self, other):\n \"\"\"Return a ``Wrench`` that is the the sum of this ``Wrench`` and another wrench.\n\n Parameters\n ----------\n other : wrench\n The wrench to add.\n\n Returns\n -------\n Wrench\n The resulting new ``Wrench``.\n\n \"\"\"\n return Wrench(\n self.force + other.force,\n self.torque + other.torque)\n\n def __sub__(self, other):\n \"\"\"Return a ``Wrench`` that is the the difference between this ``Wrench`` and another wrench.\n\n Parameters\n ----------\n other : wrench\n The wrench to subtract.\n\n Returns\n -------\n Wrench\n The resulting new ``Wrench``.\n \"\"\"\n return Wrench(\n self.force - other.force,\n self.torque - other.torque)\n\n def __neg__(self):\n \"\"\"Return the negated ``Wrench``.\n\n Returns\n -------\n Wrench\n The negated ``Wrench``.\n \"\"\"\n return Wrench(\n self.force * -1.0,\n self.torque * -1.0)\n\n def __len__(self):\n return 6\n\n # ==========================================================================\n # comparison\n # ==========================================================================\n\n def __eq__(self, other, tol=1e-05):\n for a, b in zip(list(self), list(other)):\n if math.fabs(a - b) > tol:\n return False\n return True\n\n def __ne__(self, other, tol=1e-05):\n return not self.__eq__(other, tol)\n\n # ==========================================================================\n # transformations\n # ==========================================================================\n\n def transform(self, transformation):\n \"\"\"Transforms a `Wrench` with the transformation.\n\n Parameters\n ----------\n transformation : :class:`Transformation`\n The transformation to transform the `Wrench`.\n\n Returns\n -------\n None\n\n Examples\n --------\n >>> R = Rotation.from_axis_and_angle([1, 0, 0], math.pi)\n >>> w = Wrench([1, 2, 3], [0.1, 0.2, 0.3])\n >>> w.transform(R)\n \"\"\"\n self.force.transform(transformation)\n self.torque.transform(transformation)\n\n def transformed(self, transformation):\n \"\"\"Returns a transformed copy of the `Wrench`.\n\n Parameters\n ----------\n transformation : :class:`Transformation`\n The transformation to transform the `Wrench`.\n\n Returns\n -------\n Wrench\n The transformed wrench.\n\n Examples\n --------\n >>> R = Rotation.from_axis_and_angle([1, 0, 0], math.pi)\n >>> w1 = Wrench([1, 2, 3], [0.1, 0.2, 0.3])\n >>> w2 = w1.transformed(R)\n \"\"\"\n wrench = self.copy()\n wrench.transform(transformation)\n return wrench\n\n def gravity_compensated(self, ft_sensor_frame, mass, center_of_mass):\n \"\"\"Removes the force and torque in effect of gravity from the wrench.\n\n Parameters\n ----------\n ft_sensor_frame : :class:`compas.geometry.Frame`\n The coordinate frame of the force torque sensor.\n mass: float\n The mass of the object in kg.\n center_of_mass : :class:`Point`\n The center of mass of the object in meters.\n\n Returns\n -------\n Wrench\n The gravity compensated wrench.\n\n Examples\n --------\n >>> mass, com = 10, [0, 0, 1]\n >>> f = Frame([0, 0, 0], [1, 0, 0], [0, 1, 0])\n >>> w = Wrench([0, 0, -98], [0, 0, 0])\n >>> w.gravity_compensated(f, mass, com)\n Wrench(Vector(0.000, 0.000, 0.066), Vector(0.000, 0.000, 0.000))\n\n >>> mass, com = 10, [1, 1, 1]\n >>> f = Frame([0, 0, 0], [1, 0, 0], [0, 1, 0])\n >>> w = Wrench([0, 0, -98], [-98, 98, 0])\n >>> w.gravity_compensated(f, mass, com)\n Wrench(Vector(0.000, 0.000, 0.066), Vector(-88.193, 88.193, 0.000))\n\n Notes\n -----\n For more info, see [1]_.\n\n References\n ----------\n .. [1] Vougioukas S., *Bias Estimation and Gravity Compensation For\n Force-Torque Sensors*,\n Available at: http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.552.109\n\n \"\"\"\n # transform gravity vector to FT Sensor coordinate system (FTSCS)\n gravity_vector_FTSCS = ft_sensor_frame.to_local_coordinates(gravity_vector)\n\n # F gravity compensation, F = gravity * mass\n force_gravity = gravity_vector_FTSCS * mass\n\n # torque gravity compensation, T = (lever_arm * mass) X gravity_vector_FTSCS\n torque_gravity = Vector(*cross_vectors((center_of_mass * mass), gravity_vector_FTSCS))\n\n return Wrench(self.force - force_gravity, self.torque - torque_gravity)\n"
] | [
[
"scipy.stats.trim_mean"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [
"0.13",
"1.6",
"0.14",
"1.10",
"0.15",
"1.4",
"0.16",
"1.9",
"0.19",
"1.5",
"0.18",
"1.2",
"1.7",
"0.12",
"1.0",
"0.17",
"1.3",
"1.8"
],
"tensorflow": []
}
] |
78-t0b1/ga-learner-dsmp-repo | [
"78a3d5eb86d2b9e95b1e249bca434162a1157d83"
] | [
"Housing-Problem/code.py"
] | [
"# --------------\nimport numpy as np\r\nimport pandas as pd\r\nfrom sklearn.model_selection import train_test_split\r\n\r\n# path- variable storing file path\r\ndf = pd.read_csv(path)\r\ndf.head()\r\n\r\nX = df.drop(columns=['Price'])\r\ny = df['Price']\r\n\r\nX_train,X_test,y_train,y_test = train_test_split(X,y,test_size = 0.3,random_state = 6)\r\ncorr = X_train.corr()\r\nprint(corr)\r\n#Code starts here\n\n\n# --------------\nfrom sklearn.linear_model import LinearRegression\r\nfrom sklearn.metrics import r2_score\r\n\r\n# Code starts here\r\nregressor = LinearRegression()\r\n\r\nregressor.fit(X_train,y_train)\r\n\r\ny_pred = regressor.predict(X_test)\r\n\r\nr2 = r2_score(y_test,y_pred)\n\n\n# --------------\nfrom sklearn.linear_model import Lasso\r\n\r\n# Code starts here\r\nlasso = Lasso()\r\n\r\nlasso.fit(X_train,y_train)\r\n\r\nlasso_pred = lasso.predict(X_test)\r\n\r\nr2_lasso = r2_score(y_test,lasso_pred)\r\n\n\n\n# --------------\nfrom sklearn.linear_model import Ridge\r\n\r\n# Code starts here\r\nridge = Ridge()\r\n\r\nridge.fit(X_train,y_train)\r\n\r\nridge_pred = ridge.predict(X_test)\r\n\r\nr2_ridge = r2_score(y_test,ridge_pred)\r\n\r\nprint(r2_ridge)\r\n\r\n\r\n\r\n# Code ends here\n\n\n# --------------\nfrom sklearn.model_selection import cross_val_score\r\n\r\n#Code starts here\r\nregressor = LinearRegression()\r\n\r\nscore = cross_val_score(regressor,X_train,y_train ,cv=10)\r\n\r\nmean_score = sum(score)/len(score)\r\n\r\nprint(mean_score)\n\n\n# --------------\nfrom sklearn.preprocessing import PolynomialFeatures\r\nfrom sklearn.pipeline import make_pipeline\r\n\r\n#Code starts here\r\n\r\nmodel = make_pipeline(PolynomialFeatures(2),LinearRegression())\r\n\r\nmodel.fit(X_train,y_train)\r\n\r\ny_pred = model.predict(X_test)\r\n\r\nr2_poly = r2_score(y_test,y_pred)\r\n\r\nprint(r2_poly)\n\n\n"
] | [
[
"pandas.read_csv",
"sklearn.metrics.r2_score",
"sklearn.model_selection.cross_val_score",
"sklearn.model_selection.train_test_split",
"sklearn.preprocessing.PolynomialFeatures",
"sklearn.linear_model.Lasso",
"sklearn.linear_model.Ridge",
"sklearn.linear_model.LinearRegression"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [
"2.0",
"1.4",
"1.1",
"1.5",
"1.2",
"1.3"
],
"scipy": [],
"tensorflow": []
}
] |
chris-tng/transformers | [
"dc9f24544291b25b44c9e87239a0ef4355396a4c"
] | [
"tests/test_modeling_tf_lxmert.py"
] | [
"# coding=utf-8\n# Copyright 2020 The HuggingFace Team. All rights reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport tempfile\nimport unittest\n\nfrom transformers import LxmertConfig, is_tf_available\nfrom transformers.testing_utils import require_tf, slow\n\nfrom .test_configuration_common import ConfigTester\nfrom .test_modeling_tf_common import TFModelTesterMixin, ids_tensor\n\n\nif is_tf_available():\n import tensorflow as tf\n\n from transformers.models.lxmert.modeling_tf_lxmert import TFLxmertForPreTraining, TFLxmertModel\n\n\nclass TFLxmertModelTester(object):\n def __init__(\n self,\n parent,\n vocab_size=300,\n hidden_size=28,\n num_attention_heads=2,\n num_labels=2,\n intermediate_size=64,\n hidden_act=\"gelu\",\n hidden_dropout_prob=0.1,\n attention_probs_dropout_prob=0.1,\n max_position_embeddings=512,\n type_vocab_size=2,\n initializer_range=0.02,\n layer_norm_eps=1e-12,\n pad_token_id=0,\n num_qa_labels=30,\n num_object_labels=16,\n num_attr_labels=4,\n num_visual_features=10,\n l_layers=2,\n x_layers=1,\n r_layers=1,\n visual_feat_dim=128,\n visual_pos_dim=4,\n visual_loss_normalizer=6.67,\n seq_length=20,\n batch_size=8,\n is_training=True,\n task_matched=True,\n task_mask_lm=True,\n task_obj_predict=True,\n task_qa=True,\n visual_obj_loss=True,\n visual_attr_loss=True,\n visual_feat_loss=True,\n use_token_type_ids=True,\n use_lang_mask=True,\n output_attentions=False,\n output_hidden_states=False,\n scope=None,\n ):\n self.parent = parent\n self.vocab_size = vocab_size\n self.hidden_size = hidden_size\n self.num_attention_heads = num_attention_heads\n self.num_labels = num_labels\n self.intermediate_size = intermediate_size\n self.hidden_act = hidden_act\n self.hidden_dropout_prob = hidden_dropout_prob\n self.attention_probs_dropout_prob = attention_probs_dropout_prob\n self.max_position_embeddings = max_position_embeddings\n self.type_vocab_size = type_vocab_size\n self.initializer_range = initializer_range\n self.layer_norm_eps = layer_norm_eps\n self.pad_token_id = pad_token_id\n self.num_qa_labels = num_qa_labels\n self.num_object_labels = num_object_labels\n self.num_attr_labels = num_attr_labels\n self.l_layers = l_layers\n self.x_layers = x_layers\n self.r_layers = r_layers\n self.visual_feat_dim = visual_feat_dim\n self.visual_pos_dim = visual_pos_dim\n self.visual_loss_normalizer = visual_loss_normalizer\n self.seq_length = seq_length\n self.batch_size = batch_size\n self.is_training = is_training\n self.use_lang_mask = use_lang_mask\n self.task_matched = task_matched\n self.task_mask_lm = task_mask_lm\n self.task_obj_predict = task_obj_predict\n self.task_qa = task_qa\n self.visual_obj_loss = visual_obj_loss\n self.visual_attr_loss = visual_attr_loss\n self.visual_feat_loss = visual_feat_loss\n self.num_visual_features = num_visual_features\n self.use_token_type_ids = use_token_type_ids\n self.output_attentions = output_attentions\n self.output_hidden_states = output_hidden_states\n self.scope = scope\n self.num_hidden_layers = {\"vision\": r_layers, \"cross_encoder\": x_layers, \"language\": l_layers}\n\n def prepare_config_and_inputs(self):\n output_attentions = self.output_attentions\n input_ids = ids_tensor([self.batch_size, self.seq_length], vocab_size=self.vocab_size)\n visual_feats = tf.random.uniform((self.batch_size, self.num_visual_features, self.visual_feat_dim))\n bounding_boxes = tf.random.uniform((self.batch_size, self.num_visual_features, 4))\n\n input_mask = None\n if self.use_lang_mask:\n input_mask = ids_tensor([self.batch_size, self.seq_length], vocab_size=2)\n token_type_ids = None\n if self.use_token_type_ids:\n token_type_ids = ids_tensor([self.batch_size, self.seq_length], self.type_vocab_size)\n obj_labels = None\n if self.task_obj_predict:\n obj_labels = {}\n if self.visual_attr_loss and self.task_obj_predict:\n obj_labels[\"attr\"] = (\n ids_tensor([self.batch_size, self.num_visual_features], self.num_attr_labels),\n ids_tensor([self.batch_size, self.num_visual_features], self.num_attr_labels),\n )\n if self.visual_feat_loss and self.task_obj_predict:\n obj_labels[\"feat\"] = (\n ids_tensor(\n [self.batch_size, self.num_visual_features, self.visual_feat_dim], self.num_visual_features\n ),\n ids_tensor([self.batch_size, self.num_visual_features], self.num_visual_features),\n )\n if self.visual_obj_loss and self.task_obj_predict:\n obj_labels[\"obj\"] = (\n ids_tensor([self.batch_size, self.num_visual_features], self.num_object_labels),\n ids_tensor([self.batch_size, self.num_visual_features], self.num_object_labels),\n )\n ans = None\n if self.task_qa:\n ans = ids_tensor([self.batch_size], self.num_qa_labels)\n masked_lm_labels = None\n if self.task_mask_lm:\n masked_lm_labels = ids_tensor([self.batch_size, self.seq_length], self.vocab_size)\n matched_label = None\n if self.task_matched:\n matched_label = ids_tensor([self.batch_size], self.num_labels)\n\n config = LxmertConfig(\n vocab_size=self.vocab_size,\n hidden_size=self.hidden_size,\n num_attention_heads=self.num_attention_heads,\n num_labels=self.num_labels,\n intermediate_size=self.intermediate_size,\n hidden_act=self.hidden_act,\n hidden_dropout_prob=self.hidden_dropout_prob,\n attention_probs_dropout_prob=self.attention_probs_dropout_prob,\n max_position_embeddings=self.max_position_embeddings,\n type_vocab_size=self.type_vocab_size,\n initializer_range=self.initializer_range,\n layer_norm_eps=self.layer_norm_eps,\n pad_token_id=self.pad_token_id,\n num_qa_labels=self.num_qa_labels,\n num_object_labels=self.num_object_labels,\n num_attr_labels=self.num_attr_labels,\n l_layers=self.l_layers,\n x_layers=self.x_layers,\n r_layers=self.r_layers,\n visual_feat_dim=self.visual_feat_dim,\n visual_pos_dim=self.visual_pos_dim,\n visual_loss_normalizer=self.visual_loss_normalizer,\n task_matched=self.task_matched,\n task_mask_lm=self.task_mask_lm,\n task_obj_predict=self.task_obj_predict,\n task_qa=self.task_qa,\n visual_obj_loss=self.visual_obj_loss,\n visual_attr_loss=self.visual_attr_loss,\n visual_feat_loss=self.visual_feat_loss,\n output_attentions=self.output_attentions,\n output_hidden_states=self.output_hidden_states,\n )\n\n return (\n config,\n input_ids,\n visual_feats,\n bounding_boxes,\n token_type_ids,\n input_mask,\n obj_labels,\n masked_lm_labels,\n matched_label,\n ans,\n output_attentions,\n )\n\n def create_and_check_lxmert_model(\n self,\n config,\n input_ids,\n visual_feats,\n bounding_boxes,\n token_type_ids,\n input_mask,\n obj_labels,\n masked_lm_labels,\n matched_label,\n ans,\n output_attentions,\n ):\n model = TFLxmertModel(config=config)\n result = model(\n input_ids,\n visual_feats,\n bounding_boxes,\n token_type_ids=token_type_ids,\n attention_mask=input_mask,\n output_attentions=output_attentions,\n )\n result = model(\n input_ids,\n visual_feats,\n bounding_boxes,\n token_type_ids=token_type_ids,\n attention_mask=input_mask,\n output_attentions=not output_attentions,\n )\n result = model(input_ids, visual_feats, bounding_boxes, return_dict=False)\n result = model(input_ids, visual_feats, bounding_boxes, return_dict=True)\n\n self.parent.assertEqual(result.language_output.shape, (self.batch_size, self.seq_length, self.hidden_size))\n self.parent.assertEqual(\n result.vision_output.shape, (self.batch_size, self.num_visual_features, self.hidden_size)\n )\n self.parent.assertEqual(result.pooled_output.shape, (self.batch_size, self.hidden_size))\n\n def prepare_config_and_inputs_for_common(self, return_obj_labels=False):\n config_and_inputs = self.prepare_config_and_inputs()\n (\n config,\n input_ids,\n visual_feats,\n bounding_boxes,\n token_type_ids,\n input_mask,\n obj_labels,\n masked_lm_labels,\n matched_label,\n ans,\n output_attentions,\n ) = config_and_inputs\n\n inputs_dict = {\n \"input_ids\": input_ids,\n \"visual_feats\": visual_feats,\n \"visual_pos\": bounding_boxes,\n \"token_type_ids\": token_type_ids,\n \"attention_mask\": input_mask,\n }\n\n if return_obj_labels:\n inputs_dict[\"obj_labels\"] = obj_labels\n\n return config, inputs_dict\n\n def create_and_check_lxmert_for_pretraining(\n self,\n config,\n input_ids,\n visual_feats,\n bounding_boxes,\n token_type_ids,\n input_mask,\n obj_labels,\n masked_lm_labels,\n matched_label,\n ans,\n output_attentions,\n ):\n model = TFLxmertForPreTraining(config=config)\n result = model(\n input_ids,\n visual_feats,\n bounding_boxes,\n token_type_ids=token_type_ids,\n attention_mask=input_mask,\n masked_lm_labels=masked_lm_labels,\n obj_labels=obj_labels,\n matched_label=matched_label,\n ans=ans,\n output_attentions=output_attentions,\n )\n result = model(\n input_ids,\n visual_feats,\n bounding_boxes,\n token_type_ids=token_type_ids,\n attention_mask=input_mask,\n masked_lm_labels=masked_lm_labels,\n output_attentions=not output_attentions,\n return_dict=False,\n )\n result = model(\n input_ids,\n visual_feats,\n bounding_boxes,\n token_type_ids=token_type_ids,\n attention_mask=input_mask,\n masked_lm_labels=masked_lm_labels,\n )\n result = model(\n input_ids,\n visual_feats,\n bounding_boxes,\n token_type_ids=token_type_ids,\n attention_mask=input_mask,\n obj_labels=obj_labels,\n )\n result = model(\n input_ids,\n visual_feats,\n bounding_boxes,\n token_type_ids=token_type_ids,\n attention_mask=input_mask,\n matched_label=matched_label,\n )\n result = model(\n input_ids,\n visual_feats,\n bounding_boxes,\n token_type_ids=token_type_ids,\n attention_mask=input_mask,\n ans=ans,\n )\n result = model(\n input_ids,\n visual_feats,\n bounding_boxes,\n token_type_ids=token_type_ids,\n attention_mask=input_mask,\n masked_lm_labels=masked_lm_labels,\n obj_labels=obj_labels,\n matched_label=matched_label,\n ans=ans,\n output_attentions=not output_attentions,\n )\n\n self.parent.assertEqual(result.prediction_logits.shape, (self.batch_size, self.seq_length, self.vocab_size))\n\n\n@require_tf\nclass TFLxmertModelTest(TFModelTesterMixin, unittest.TestCase):\n\n all_model_classes = (TFLxmertModel, TFLxmertForPreTraining) if is_tf_available() else ()\n\n def setUp(self):\n self.model_tester = TFLxmertModelTester(self)\n self.config_tester = ConfigTester(self, config_class=LxmertConfig, hidden_size=37)\n\n def test_config(self):\n self.config_tester.run_common_tests()\n\n def test_lxmert_model(self):\n config_and_inputs = self.model_tester.prepare_config_and_inputs()\n self.model_tester.create_and_check_lxmert_model(*config_and_inputs)\n\n def test_lxmert_for_pretraining(self):\n config_and_inputs = self.model_tester.prepare_config_and_inputs()\n self.model_tester.create_and_check_lxmert_for_pretraining(*config_and_inputs)\n\n @slow\n def test_model_from_pretrained(self):\n for model_name in [\"unc-nlp/lxmert-base-uncased\"]:\n model = TFLxmertModel.from_pretrained(model_name)\n self.assertIsNotNone(model)\n\n def test_attention_outputs(self):\n config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()\n\n encoder_seq_length = (\n self.model_tester.encoder_seq_length\n if hasattr(self.model_tester, \"encoder_seq_length\")\n else self.model_tester.seq_length\n )\n encoder_key_length = (\n self.model_tester.key_length if hasattr(self.model_tester, \"key_length\") else encoder_seq_length\n )\n\n for model_class in self.all_model_classes:\n inputs_dict[\"output_attentions\"] = True\n inputs_dict[\"output_hidden_states\"] = False\n model = model_class(config)\n outputs = model(self._prepare_for_class(inputs_dict, model_class))\n language_attentions, vision_attentions, cross_encoder_attentions = (outputs[-3], outputs[-2], outputs[-1])\n\n self.assertEqual(model.config.output_hidden_states, False)\n\n self.assertEqual(len(language_attentions), self.model_tester.num_hidden_layers[\"language\"])\n self.assertEqual(len(vision_attentions), self.model_tester.num_hidden_layers[\"vision\"])\n self.assertEqual(len(cross_encoder_attentions), self.model_tester.num_hidden_layers[\"cross_encoder\"])\n\n attentions = [language_attentions, vision_attentions, cross_encoder_attentions]\n attention_shapes = [\n [self.model_tester.num_attention_heads, encoder_seq_length, encoder_key_length],\n [\n self.model_tester.num_attention_heads,\n self.model_tester.num_visual_features,\n self.model_tester.num_visual_features,\n ],\n [self.model_tester.num_attention_heads, encoder_key_length, self.model_tester.num_visual_features],\n ]\n\n for attention, attention_shape in zip(attentions, attention_shapes):\n self.assertListEqual(list(attention[0].shape[-3:]), attention_shape)\n out_len = len(outputs)\n\n # Check attention is always last and order is fine\n inputs_dict[\"output_attentions\"] = True\n inputs_dict[\"output_hidden_states\"] = True\n model = model_class(config)\n outputs = model(self._prepare_for_class(inputs_dict, model_class))\n\n # 2 hidden states were added\n self.assertEqual(out_len + 2, len(outputs))\n language_attentions, vision_attentions, cross_encoder_attentions = (outputs[-3], outputs[-2], outputs[-1])\n self.assertEqual(len(language_attentions), self.model_tester.num_hidden_layers[\"language\"])\n self.assertEqual(len(vision_attentions), self.model_tester.num_hidden_layers[\"vision\"])\n self.assertEqual(len(cross_encoder_attentions), self.model_tester.num_hidden_layers[\"cross_encoder\"])\n\n attentions = [language_attentions, vision_attentions, cross_encoder_attentions]\n attention_shapes = [\n [self.model_tester.num_attention_heads, encoder_seq_length, encoder_key_length],\n [\n self.model_tester.num_attention_heads,\n self.model_tester.num_visual_features,\n self.model_tester.num_visual_features,\n ],\n [self.model_tester.num_attention_heads, encoder_key_length, self.model_tester.num_visual_features],\n ]\n\n for attention, attention_shape in zip(attentions, attention_shapes):\n self.assertListEqual(list(attention[0].shape[-3:]), attention_shape)\n\n def test_hidden_states_output(self):\n config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()\n\n def check_hidden_states_output(config, inputs_dict, model_class):\n model = model_class(config)\n outputs = model(self._prepare_for_class(inputs_dict, model_class))\n language_hidden_states, vision_hidden_states = outputs[-2], outputs[-1]\n\n self.assertEqual(len(language_hidden_states), self.model_tester.num_hidden_layers[\"language\"] + 1)\n self.assertEqual(len(vision_hidden_states), self.model_tester.num_hidden_layers[\"vision\"] + 1)\n\n seq_length = self.model_tester.seq_length\n num_visual_features = self.model_tester.num_visual_features\n\n self.assertListEqual(\n list(language_hidden_states[0].shape[-2:]),\n [seq_length, self.model_tester.hidden_size],\n )\n self.assertListEqual(\n list(vision_hidden_states[0].shape[-2:]),\n [num_visual_features, self.model_tester.hidden_size],\n )\n\n for model_class in self.all_model_classes:\n inputs_dict[\"output_hidden_states\"] = True\n check_hidden_states_output(config, inputs_dict, model_class)\n\n del inputs_dict[\"output_hidden_states\"]\n config.output_hidden_states = True\n check_hidden_states_output(config, inputs_dict, model_class)\n\n def test_pt_tf_model_equivalence(self):\n from transformers import is_torch_available\n\n if not is_torch_available():\n return\n\n import torch\n\n import transformers\n\n for model_class in self.all_model_classes:\n config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common(\n return_obj_labels=\"PreTraining\" in model_class.__name__\n )\n\n pt_model_class_name = model_class.__name__[2:] # Skip the \"TF\" at the beginning\n pt_model_class = getattr(transformers, pt_model_class_name)\n\n config.output_hidden_states = True\n config.task_obj_predict = False\n\n tf_model = model_class(config)\n pt_model = pt_model_class(config)\n\n # Check we can load pt model in tf and vice-versa with model => model functions\n\n tf_model = transformers.load_pytorch_model_in_tf2_model(\n tf_model, pt_model, tf_inputs=self._prepare_for_class(inputs_dict, model_class)\n )\n pt_model = transformers.load_tf2_model_in_pytorch_model(pt_model, tf_model)\n\n # Check predictions on first output (logits/hidden-states) are close enought given low-level computational differences\n pt_model.eval()\n\n # Delete obj labels as we want to compute the hidden states and not the loss\n\n if \"obj_labels\" in inputs_dict:\n del inputs_dict[\"obj_labels\"]\n\n def torch_type(key):\n if key in (\"visual_feats\", \"visual_pos\"):\n return torch.float32\n else:\n return torch.long\n\n def recursive_numpy_convert(iterable):\n return_dict = {}\n for key, value in iterable.items():\n if isinstance(value, dict):\n return_dict[key] = recursive_numpy_convert(value)\n else:\n if isinstance(value, (list, tuple)):\n return_dict[key] = (\n torch.from_numpy(iter_value.numpy()).to(torch_type(key)) for iter_value in value\n )\n else:\n return_dict[key] = torch.from_numpy(value.numpy()).to(torch_type(key))\n return return_dict\n\n pt_inputs_dict = recursive_numpy_convert(self._prepare_for_class(inputs_dict, model_class))\n\n # need to rename encoder-decoder \"inputs\" for PyTorch\n if \"inputs\" in pt_inputs_dict and self.is_encoder_decoder:\n pt_inputs_dict[\"input_ids\"] = pt_inputs_dict.pop(\"inputs\")\n\n with torch.no_grad():\n pto = pt_model(**pt_inputs_dict)\n tfo = tf_model(self._prepare_for_class(inputs_dict, model_class), training=False)\n tf_hidden_states = tfo[0].numpy()\n pt_hidden_states = pto[0].numpy()\n\n import numpy as np\n\n tf_nans = np.copy(np.isnan(tf_hidden_states))\n pt_nans = np.copy(np.isnan(pt_hidden_states))\n\n pt_hidden_states[tf_nans] = 0\n tf_hidden_states[tf_nans] = 0\n pt_hidden_states[pt_nans] = 0\n tf_hidden_states[pt_nans] = 0\n\n max_diff = np.amax(np.abs(tf_hidden_states - pt_hidden_states))\n # Debug info (remove when fixed)\n if max_diff >= 2e-2:\n print(\"===\")\n print(model_class)\n print(config)\n print(inputs_dict)\n print(pt_inputs_dict)\n self.assertLessEqual(max_diff, 6e-2)\n\n # Check we can load pt model in tf and vice-versa with checkpoint => model functions\n with tempfile.TemporaryDirectory() as tmpdirname:\n import os\n\n pt_checkpoint_path = os.path.join(tmpdirname, \"pt_model.bin\")\n torch.save(pt_model.state_dict(), pt_checkpoint_path)\n tf_model = transformers.load_pytorch_checkpoint_in_tf2_model(tf_model, pt_checkpoint_path)\n\n tf_checkpoint_path = os.path.join(tmpdirname, \"tf_model.h5\")\n tf_model.save_weights(tf_checkpoint_path)\n pt_model = transformers.load_tf2_checkpoint_in_pytorch_model(pt_model, tf_checkpoint_path)\n\n # Check predictions on first output (logits/hidden-states) are close enought given low-level computational differences\n pt_model.eval()\n pt_inputs_dict = dict(\n (name, torch.from_numpy(key.numpy()).to(torch.long))\n for name, key in self._prepare_for_class(inputs_dict, model_class).items()\n )\n\n for key, value in pt_inputs_dict.items():\n if key in (\"visual_feats\", \"visual_pos\"):\n pt_inputs_dict[key] = value.to(torch.float32)\n else:\n pt_inputs_dict[key] = value.to(torch.long)\n\n with torch.no_grad():\n pto = pt_model(**pt_inputs_dict)\n tfo = tf_model(self._prepare_for_class(inputs_dict, model_class))\n tfo = tfo[0].numpy()\n pto = pto[0].numpy()\n tf_nans = np.copy(np.isnan(tfo))\n pt_nans = np.copy(np.isnan(pto))\n\n pto[tf_nans] = 0\n tfo[tf_nans] = 0\n pto[pt_nans] = 0\n tfo[pt_nans] = 0\n\n max_diff = np.amax(np.abs(tfo - pto))\n self.assertLessEqual(max_diff, 6e-2)\n\n def test_save_load(self):\n for model_class in self.all_model_classes:\n config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common(\n return_obj_labels=\"PreTraining\" in model_class.__name__\n )\n\n model = model_class(config)\n outputs = model(self._prepare_for_class(inputs_dict, model_class))\n\n with tempfile.TemporaryDirectory() as tmpdirname:\n model.save_pretrained(tmpdirname)\n model = model_class.from_pretrained(tmpdirname)\n after_outputs = model(self._prepare_for_class(inputs_dict, model_class))\n\n self.assert_outputs_same(after_outputs, outputs)\n\n def test_compile_tf_model(self):\n optimizer = tf.keras.optimizers.Adam(learning_rate=3e-5, epsilon=1e-08, clipnorm=1.0)\n loss = tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True)\n metric = tf.keras.metrics.SparseCategoricalAccuracy(\"accuracy\")\n\n for model_class in self.all_model_classes:\n config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common(\n return_obj_labels=\"PreTraining\" in model_class.__name__\n )\n\n input_ids = tf.keras.Input(\n batch_shape=(self.model_tester.batch_size, self.model_tester.seq_length),\n name=\"input_ids\",\n dtype=\"int32\",\n )\n visual_feats = tf.keras.Input(\n batch_shape=(\n self.model_tester.batch_size,\n self.model_tester.num_visual_features,\n self.model_tester.visual_feat_dim,\n ),\n name=\"visual_feats\",\n dtype=\"int32\",\n )\n visual_pos = tf.keras.Input(\n batch_shape=(self.model_tester.batch_size, self.model_tester.num_visual_features, 4),\n name=\"visual_pos\",\n dtype=\"int32\",\n )\n\n # Prepare our model\n model = model_class(config)\n\n # Let's load it from the disk to be sure we can use pretrained weights\n with tempfile.TemporaryDirectory() as tmpdirname:\n outputs = model(self._prepare_for_class(inputs_dict, model_class)) # build the model\n model.save_pretrained(tmpdirname)\n model = model_class.from_pretrained(tmpdirname)\n\n outputs_dict = model(input_ids, visual_feats, visual_pos)\n hidden_states = outputs_dict[0]\n\n # Add a dense layer on top to test integration with other keras modules\n outputs = tf.keras.layers.Dense(2, activation=\"softmax\", name=\"outputs\")(hidden_states)\n\n # Compile extended model\n extended_model = tf.keras.Model(inputs=[input_ids, visual_feats, visual_pos], outputs=[outputs])\n extended_model.compile(optimizer=optimizer, loss=loss, metrics=[metric])\n\n def test_model_common_attributes(self):\n config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()\n list_lm_models = [TFLxmertForPreTraining]\n\n for model_class in self.all_model_classes:\n model = model_class(config)\n assert isinstance(model.get_input_embeddings(), tf.keras.layers.Layer)\n\n if model_class in list_lm_models:\n x = model.get_output_layer_with_bias()\n assert isinstance(x, tf.keras.layers.Layer)\n name = model.get_prefix_bias_name()\n assert isinstance(name, str)\n else:\n x = model.get_output_layer_with_bias()\n assert x is None\n name = model.get_prefix_bias_name()\n assert x is None\n\n @slow\n def test_saved_model_with_hidden_states_output(self):\n config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()\n config.output_hidden_states = True\n\n for model_class in self.all_model_classes:\n class_inputs_dict = self._prepare_for_class(inputs_dict, model_class)\n model = model_class(config)\n model._saved_model_inputs_spec = None\n model._set_save_spec(class_inputs_dict)\n\n with tempfile.TemporaryDirectory() as tmpdirname:\n tf.saved_model.save(model, tmpdirname)\n model = tf.keras.models.load_model(tmpdirname)\n outputs = model(class_inputs_dict)\n\n language_hidden_states = outputs[\"language_hidden_states\"]\n vision_hidden_states = outputs[\"vision_hidden_states\"]\n\n self.assertEqual(len(language_hidden_states), self.model_tester.num_hidden_layers[\"language\"] + 1)\n self.assertEqual(len(vision_hidden_states), self.model_tester.num_hidden_layers[\"vision\"] + 1)\n\n seq_length = self.model_tester.seq_length\n num_visual_features = self.model_tester.num_visual_features\n\n self.assertListEqual(\n list(language_hidden_states[0].shape[-2:]),\n [seq_length, self.model_tester.hidden_size],\n )\n self.assertListEqual(\n list(vision_hidden_states[0].shape[-2:]),\n [num_visual_features, self.model_tester.hidden_size],\n )\n\n @slow\n def test_saved_model_with_attentions_output(self):\n config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()\n config.output_attentions = True\n\n encoder_seq_length = getattr(self.model_tester, \"encoder_seq_length\", self.model_tester.seq_length)\n encoder_key_length = getattr(self.model_tester, \"key_length\", encoder_seq_length)\n\n for model_class in self.all_model_classes:\n class_inputs_dict = self._prepare_for_class(inputs_dict, model_class)\n model = model_class(config)\n model._saved_model_inputs_spec = None\n model._set_save_spec(class_inputs_dict)\n\n with tempfile.TemporaryDirectory() as tmpdirname:\n tf.saved_model.save(model, tmpdirname)\n model = tf.keras.models.load_model(tmpdirname)\n outputs = model(class_inputs_dict)\n\n language_attentions = outputs[\"language_attentions\"]\n vision_attentions = outputs[\"vision_attentions\"]\n cross_encoder_attentions = outputs[\"cross_encoder_attentions\"]\n\n self.assertEqual(len(language_attentions), self.model_tester.num_hidden_layers[\"language\"])\n self.assertEqual(len(vision_attentions), self.model_tester.num_hidden_layers[\"vision\"])\n self.assertEqual(len(cross_encoder_attentions), self.model_tester.num_hidden_layers[\"cross_encoder\"])\n\n attentions = [language_attentions, vision_attentions, cross_encoder_attentions]\n attention_shapes = [\n [self.model_tester.num_attention_heads, encoder_seq_length, encoder_key_length],\n [\n self.model_tester.num_attention_heads,\n self.model_tester.num_visual_features,\n self.model_tester.num_visual_features,\n ],\n [self.model_tester.num_attention_heads, encoder_key_length, self.model_tester.num_visual_features],\n ]\n\n for attention, attention_shape in zip(attentions, attention_shapes):\n self.assertListEqual(list(attention[0].shape[-3:]), attention_shape)\n"
] | [
[
"tensorflow.keras.models.load_model",
"tensorflow.keras.Input",
"numpy.abs",
"tensorflow.keras.losses.SparseCategoricalCrossentropy",
"numpy.isnan",
"tensorflow.keras.layers.Dense",
"tensorflow.random.uniform",
"tensorflow.keras.Model",
"tensorflow.saved_model.save",
"tensorflow.keras.optimizers.Adam",
"torch.no_grad",
"tensorflow.keras.metrics.SparseCategoricalAccuracy"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"2.7",
"2.6",
"2.4",
"2.3",
"2.5",
"2.2"
]
}
] |
Limmen/gym-yagw | [
"da7e5eba5bd1c4ad316fb60cc5096ca8bc7c29ae"
] | [
"gym_yagw/algorithms/q_learning.py"
] | [
"from gym_yagw.envs.yagw_env import YagwEnv\nimport numpy as np\nimport random\nimport time\nimport tqdm\nfrom gym import wrappers\n\nclass QAgent:\n \"\"\"\n A simple implementation of the Q(0)-learning algorithm (Sutton & Barto).\n Q-learning is a one-step off-policy algorithm\n \"\"\"\n def __init__(self, env:YagwEnv, gamma=0.8, alpha=0.1, epsilon=0.9, render = False, eval_sleep = 0.35,\n epsilon_decay = 0.999, min_epsilon = 0.1, eval_epochs = 1, log_frequency = 100,\n video = False, video_fps=5, video_dir = None):\n \"\"\"\n Initalize environment and hyperparameters\n\n :param pi: the policy\n :param env: the environment\n :param gamma: the discount factor\n :param alpha: the learning rate\n :param epsilon: the exploration rate\n :param render: whether to render the environment *during training* (it will always render at evaluation)\n :param eval_sleep: amount of sleep between time-steps during evaluation and rendering\n :param epsilon_decay: rate of decay of epsilon\n :param min_epsilon: minimum epsilon rate\n :param eval_epochs: number of evaluation epochs\n :param log_frequency: number of episodes between logs\n :param video: boolean flag whether to record video of the evaluation.\n :param video_dir: path where to save videos (will overwrite)\n \"\"\"\n self.gamma = gamma\n self.env = env\n self.alpha = alpha\n self.epsilon=epsilon\n self.Q = np.random.rand(self.env.num_states, self.env.num_actions)\n self.render = render\n self.eval_sleep = eval_sleep\n self.epsilon_decay = epsilon_decay\n self.min_epsilon = min_epsilon\n self.eval_epochs = eval_epochs\n self.log_frequency = log_frequency\n self.video = video\n self.video_fps = video_fps\n self.video_dir = video_dir\n\n\n def get_action(self, s, eval=False):\n \"\"\"\n Sample an action using an epsilon-greedy policy with respect to the current Q-values\n\n :param s: the state to sample an action for\n :return: a sampled action\n \"\"\"\n if np.random.rand() < self.epsilon and not eval:\n return random.randrange(self.env.num_actions)\n return np.argmax(self.Q[s]).item()\n\n\n def run(self, num_episodes):\n \"\"\"\n Runs the Q(0)-learning algorithm for estimating the state values under a given policy for a specific MDP\n\n :param num_episodes: the number of iterations to run until stopping\n :return: None\n \"\"\"\n done = False\n s = self.env.reset()\n\n # Tracking metrics\n episode_rewards = []\n episode_steps = []\n epsilon_values = []\n\n # Logging\n outer = tqdm.tqdm(total=num_episodes, desc='Epoch', position=0)\n outer.set_description_str(\"epsilon:{:.2f},avg_R:{:.2f},avg_t:{:.2f}\".format(self.epsilon, 0.0, 0.0))\n\n # Training\n for episode in range(num_episodes):\n episode_reward = 0\n episode_step = 0\n epsilon_values.append(self.epsilon)\n while not done:\n if self.render:\n self.env.render(mode=\"human\")\n s_index = self.env.get_state_index(s)\n action = self.get_action(s_index)\n s_prime, reward, done, _ = self.env.step(action)\n episode_reward += reward\n episode_step += 1\n s_prime_index = self.env.get_state_index(s_prime)\n # Q-learning update\n self.Q[s_index, action] = self.Q[s_index, action] + self.alpha*(reward + self.gamma*np.max(self.Q[s_prime_index]) - self.Q[s_index,action])\n s = s_prime\n\n episode_rewards.append(episode_reward)\n episode_steps.append(episode_step)\n if episode % self.log_frequency == 0 and episode > 0:\n outer.set_description_str(\"epsilon:{:.2f},avg_R:{:.2f},avg_t:{:.2f}\".format(\n self.epsilon, sum(episode_rewards)/episode, sum(episode_steps)/episode))\n self.anneal_epsilon()\n done=False\n s = self.env.reset()\n outer.update(1)\n\n print(\"Training Complete\")\n return episode_rewards, episode_steps, epsilon_values\n\n def print_state_values(self, width=5, height=5):\n \"\"\"\n Utility function for pretty printing the state-values of the gridworld_v1 env\n\n :param width: the width of the grid\n :param height: the height of the grid\n :return:\n \"\"\"\n print(\"State values:\")\n state_values = list(map(lambda i: self.Q[i].sum(), range(0, self.env.num_states)))\n for j in range(height):\n str = ''\n for i in range(width):\n idx = i*width + j\n str = '{} {:+02.2f}'.format(str, state_values[idx])\n print(str)\n\n def eval(self):\n \"\"\"\n Performs evaluation with the greedy policy with respect to the learned Q-values\n\n :return: None\n \"\"\"\n if(self.eval_epochs < 1):\n return\n done = False\n if self.video:\n if self.video_dir is None:\n raise AssertionError(\"Video is set to True but no video_dir is provided, please specify \"\n \"the video_dir argument\")\n self.env = wrappers.Monitor(self.env, self.video_dir, force=True)\n self.env.metadata[\"video.frames_per_second\"] = self.video_fps\n s = self.env.reset()\n for epoch in range(self.eval_epochs):\n i = 0\n while not done:\n self.env.render()\n time.sleep(self.eval_sleep)\n i = i+1\n s_index = self.env.get_state_index(s)\n action = self.get_action(s_index, eval=True)\n s, reward, done, _ = self.env.step(action)\n print(\"Eval epoch: {}, Reached the goal after {} steps\".format(epoch, i))\n done = False\n s = self.env.reset()\n\n def anneal_epsilon(self):\n \"\"\"\n Anneals the exploration rate slightly until it reaches the minimum value\n\n :return: None\n \"\"\"\n if self.epsilon > self.min_epsilon:\n self.epsilon = self.epsilon*self.epsilon_decay\n\n# Program entrypoint, runs the Q(0)-learning algorithm\nif __name__ == '__main__':\n env = YagwEnv(height=8, width=8)\n q_agent = QAgent(env, gamma=0.99, alpha=0.2, epsilon=1, render=False, eval_sleep=0.3,\n min_epsilon=0.1, eval_epochs=2, log_frequency=100, epsilon_decay=0.999, video=True,\n video_fps = 5, video_dir=\"./videos\")\n episode_rewards, episode_steps, epsilon_values = q_agent.run(5000)\n q_agent.print_state_values(height=env.height, width=env.width)\n q_agent.eval()"
] | [
[
"numpy.max",
"numpy.argmax",
"numpy.random.rand"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
ChloeSarah13/wavespectra | [
"ae3413ba68fd19703c6a3e1b831b9b5131f84a08"
] | [
"setup.py"
] | [
"# from setuptools import setup\r\nimport os\r\nfrom codecs import open\r\n\r\nimport setuptools\r\nfrom numpy.distutils.core import setup\r\nfrom numpy.distutils.misc_util import Configuration\r\n\r\nimport wavespectra\r\n\r\nNAME = \"wavespectra\"\r\n\r\nCLASSIFIERS = [\r\n \"Development Status :: 4 - Beta\",\r\n \"Intended Audience :: Science/Research\",\r\n \"License :: OSI Approved :: MIT License\",\r\n \"Programming Language :: Python :: 3\",\r\n \"Programming Language :: Python :: 3.7\",\r\n \"Topic :: Scientific/Engineering\",\r\n \"Topic :: Scientific/Engineering :: Physics\",\r\n \"Topic :: Scientific/Engineering :: Visualization\",\r\n]\r\n\r\nPROJECT_URLS = {\r\n \"Funding\": \"http://www.metocean.co.nz\",\r\n \"Say Thanks!\": \"http://www.metocean.co.nz\",\r\n \"Source\": \"https://github.com/metocean/wavespectra\",\r\n \"Bug Reports\": \"https://github.com/metocean/wavespectra/issues\",\r\n}\r\n\r\n\r\ndef _strip_comments(l):\r\n return l.split(\"#\", 1)[0].strip()\r\n\r\n\r\ndef _pip_requirement(req):\r\n if req.startswith(\"-r \"):\r\n _, path = req.split()\r\n return reqs(*path.split(\"/\"))\r\n return [req]\r\n\r\n\r\ndef _reqs(*f):\r\n return [\r\n _pip_requirement(r)\r\n for r in (\r\n _strip_comments(l)\r\n for l in open(os.path.join(os.getcwd(), \"requirements\", *f)).readlines()\r\n )\r\n if r\r\n ]\r\n\r\n\r\ndef reqs(*f):\r\n \"\"\"Parse requirement file.\r\n\r\n Returns:\r\n List[str]: list of requirements specified in the file.\r\n\r\n Example:\r\n reqs('default.txt') # requirements/default.txt\r\n reqs('extras', 'redis.txt') # requirements/extras/redis.txt\r\n\r\n \"\"\"\r\n return [req for subreq in _reqs(*f) for req in subreq]\r\n\r\n\r\ndef install_requires():\r\n \"\"\"Get list of requirements required for installation.\"\"\"\r\n return reqs(\"default.txt\")\r\n\r\n\r\ndef extras_require():\r\n \"\"\"Get map of all extra requirements.\"\"\"\r\n return {\"extra\": reqs(\"extra.txt\")}\r\n\r\n\r\ndef read(fname):\r\n return open(os.path.join(os.path.dirname(__file__), fname)).read()\r\n\r\n\r\ndef ext_configuration(parent_package=\"\", top_path=None):\r\n config = Configuration(\"\", \"\", \"\")\r\n config.add_extension(\r\n \"wavespectra.specpart\",\r\n sources=[\r\n \"wavespectra/specpart/specpart.pyf\",\r\n \"wavespectra/specpart/specpart.f90\",\r\n ],\r\n )\r\n config.add_data_files(\"LICENSE.txt\", \"wavespectra/core/attributes.yml\")\r\n return config\r\n\r\n\r\nkwargs = ext_configuration(top_path=\"\").todict()\r\n\r\nsetup(\r\n name=NAME,\r\n version=wavespectra.__version__,\r\n description=wavespectra.__description__,\r\n long_description=read(\"README.rst\"),\r\n keywords=wavespectra.__keywords__,\r\n author=wavespectra.__author__,\r\n author_email=wavespectra.__contact__,\r\n url=wavespectra.__url__,\r\n license=\"MIT\",\r\n packages=setuptools.find_packages(exclude=[\"test*\"]),\r\n include_package_data=True,\r\n package_data={\"attributes\": [\"wavespectra/core/attributes.yml\"]},\r\n platforms=[\"any\"],\r\n install_requires=install_requires(),\r\n extras_require=extras_require(),\r\n setup_requires=[\"pytest-runner\"],\r\n tests_require=reqs(\"test.txt\"),\r\n python_requires=\">=2.7\",\r\n classifiers=CLASSIFIERS,\r\n project_urls=PROJECT_URLS,\r\n **kwargs\r\n)\r\n"
] | [
[
"numpy.distutils.misc_util.Configuration"
]
] | [
{
"matplotlib": [],
"numpy": [
"1.11",
"1.19",
"1.24",
"1.16",
"1.23",
"1.20",
"1.7",
"1.12",
"1.21",
"1.22",
"1.14",
"1.6",
"1.13",
"1.9",
"1.17",
"1.10",
"1.18",
"1.15",
"1.8"
],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
antonmeskildsen/FeatureNet | [
"f194949762d0627801e7096fb396d8b607699066"
] | [
"featurenet/visdom_fun.py"
] | [
"# Copyright 2017-present, Facebook, Inc.\n# All rights reserved.\n#\n# This source code is licensed under the license found in the\n# LICENSE file in the root directory of this source tree.\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\nfrom __future__ import unicode_literals\n\nfrom visdom import Visdom\nimport argparse\nimport numpy as np\nimport math\nimport os.path\nimport getpass\nimport time\nfrom sys import platform as _platform\nfrom six.moves import urllib\n\n\nDEFAULT_PORT = 6006\nDEFAULT_HOSTNAME = \"http://localhost\"\nparser = argparse.ArgumentParser(description='Demo arguments')\nparser.add_argument('-port', metavar='port', type=int, default=DEFAULT_PORT,\n help='port the visdom server is running on.')\nparser.add_argument('-server', metavar='server', type=str,\n default=DEFAULT_HOSTNAME,\n help='Server address of the target to run the demo on.')\nFLAGS = parser.parse_args()\n\ntry:\n viz = Visdom(port=FLAGS.port, server=FLAGS.server)\n\n assert viz.check_connection(), \\\n 'No connection could be formed quickly'\n\n textwindow = viz.text('Hello World!')\n\n updatetextwindow = viz.text('Hello World! More text should be here')\n assert updatetextwindow is not None, 'Window was none'\n viz.text('And here it is', win=updatetextwindow, append=True)\n\n # text window with Callbacks\n txt = 'This is a write demo notepad. Type below. Delete clears text:<br>'\n callback_text_window = viz.text(txt)\n\n def type_callback(event):\n if event['event_type'] == 'KeyPress':\n curr_txt = event['pane_data']['content']\n if event['key'] == 'Enter':\n curr_txt += '<br>'\n elif event['key'] == 'Backspace':\n curr_txt = curr_txt[:-1]\n elif event['key'] == 'Delete':\n curr_txt = txt\n elif len(event['key']) == 1:\n curr_txt += event['key']\n viz.text(curr_txt, win=callback_text_window)\n\n viz.register_event_handler(type_callback, callback_text_window)\n\n # matplotlib demo:\n try:\n import matplotlib.pyplot as plt\n plt.plot([1, 23, 2, 4])\n plt.ylabel('some numbers')\n viz.matplot(plt)\n except BaseException as err:\n print('Skipped matplotlib example')\n print('Error message: ', err)\n\n # video demo:\n try:\n video = np.empty([256, 250, 250, 3], dtype=np.uint8)\n for n in range(256):\n video[n, :, :, :].fill(n)\n viz.video(tensor=video)\n\n # video demo:\n # download video from http://media.w3.org/2010/05/sintel/trailer.ogv\n video_url = 'http://media.w3.org/2010/05/sintel/trailer.ogv'\n # linux\n if _platform == \"linux\" or _platform == \"linux2\":\n videofile = '/home/%s/trailer.ogv' % getpass.getuser()\n # MAC OS X\n elif _platform == \"darwin\":\n videofile = '/Users/%s/trailer.ogv' % getpass.getuser()\n # download video\n urllib.request.urlretrieve(video_url, videofile)\n\n if os.path.isfile(videofile):\n viz.video(videofile=videofile)\n except BaseException:\n print('Skipped video example')\n\n # image demo\n viz.image(\n np.random.rand(3, 512, 256),\n opts=dict(title='Random!', caption='How random.'),\n )\n\n # grid of images\n viz.images(\n np.random.randn(20, 3, 64, 64),\n opts=dict(title='Random images', caption='How random.')\n )\n\n # scatter plots\n Y = np.random.rand(100)\n old_scatter = viz.scatter(\n X=np.random.rand(100, 2),\n Y=(Y[Y > 0] + 1.5).astype(int),\n opts=dict(\n legend=['Didnt', 'Update'],\n xtickmin=-50,\n xtickmax=50,\n xtickstep=0.5,\n ytickmin=-50,\n ytickmax=50,\n ytickstep=0.5,\n markersymbol='cross-thin-open',\n ),\n )\n\n viz.update_window_opts(\n win=old_scatter,\n opts=dict(\n legend=['Apples', 'Pears'],\n xtickmin=0,\n xtickmax=1,\n xtickstep=0.5,\n ytickmin=0,\n ytickmax=1,\n ytickstep=0.5,\n markersymbol='cross-thin-open',\n ),\n )\n\n # 3d scatterplot with custom labels and ranges\n viz.scatter(\n X=np.random.rand(100, 3),\n Y=(Y + 1.5).astype(int),\n opts=dict(\n legend=['Men', 'Women'],\n markersize=5,\n xtickmin=0,\n xtickmax=2,\n xlabel='Arbitrary',\n xtickvals=[0, 0.75, 1.6, 2],\n ytickmin=0,\n ytickmax=2,\n ytickstep=0.5,\n ztickmin=0,\n ztickmax=1,\n ztickstep=0.5,\n )\n )\n\n # 2D scatterplot with custom intensities (red channel)\n viz.scatter(\n X=np.random.rand(255, 2),\n Y=(np.random.rand(255) + 1.5).astype(int),\n opts=dict(\n markersize=10,\n markercolor=np.random.randint(0, 255, (2, 3,)),\n ),\n )\n\n # 2D scatter plot with custom colors per label:\n viz.scatter(\n X=np.random.rand(255, 2),\n Y=(np.random.randn(255) > 0) + 1,\n opts=dict(\n markersize=10,\n markercolor=np.floor(np.random.random((2, 3)) * 255),\n ),\n )\n\n win = viz.scatter(\n X=np.random.rand(255, 2),\n opts=dict(\n markersize=10,\n markercolor=np.random.randint(0, 255, (255, 3,)),\n ),\n )\n\n # assert that the window exists\n assert viz.win_exists(win), 'Created window marked as not existing'\n\n # add new trace to scatter plot\n viz.scatter(\n X=np.random.rand(255),\n Y=np.random.rand(255),\n win=win,\n name='new_trace',\n update='new'\n )\n\n # 2D scatter plot with text labels:\n viz.scatter(\n X=np.random.rand(10, 2),\n opts=dict(\n textlabels=['Label %d' % (i + 1) for i in range(10)]\n )\n )\n viz.scatter(\n X=np.random.rand(10, 2),\n Y=[1] * 5 + [2] * 3 + [3] * 2,\n opts=dict(\n legend=['A', 'B', 'C'],\n textlabels=['Label %d' % (i + 1) for i in range(10)]\n )\n )\n\n # bar plots\n viz.bar(X=np.random.rand(20))\n viz.bar(\n X=np.abs(np.random.rand(5, 3)),\n opts=dict(\n stacked=True,\n legend=['Facebook', 'Google', 'Twitter'],\n rownames=['2012', '2013', '2014', '2015', '2016']\n )\n )\n viz.bar(\n X=np.random.rand(20, 3),\n opts=dict(\n stacked=False,\n legend=['The Netherlands', 'France', 'United States']\n )\n )\n\n # histogram\n viz.histogram(X=np.random.rand(10000), opts=dict(numbins=20))\n\n # heatmap\n viz.heatmap(\n X=np.outer(np.arange(1, 6), np.arange(1, 11)),\n opts=dict(\n columnnames=['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'],\n rownames=['y1', 'y2', 'y3', 'y4', 'y5'],\n colormap='Electric',\n )\n )\n\n # contour\n x = np.tile(np.arange(1, 101), (100, 1))\n y = x.transpose()\n X = np.exp((((x - 50) ** 2) + ((y - 50) ** 2)) / -(20.0 ** 2))\n viz.contour(X=X, opts=dict(colormap='Viridis'))\n\n # surface\n viz.surf(X=X, opts=dict(colormap='Hot'))\n\n # line plots\n viz.line(Y=np.random.rand(10), opts=dict(showlegend=True))\n\n Y = np.linspace(-5, 5, 100)\n viz.line(\n Y=np.column_stack((Y * Y, np.sqrt(Y + 5))),\n X=np.column_stack((Y, Y)),\n opts=dict(markers=False),\n )\n\n # line using WebGL\n webgl_num_points = 200000\n webgl_x = np.linspace(-1, 0, webgl_num_points)\n webgl_y = webgl_x**3\n viz.line(X=webgl_x, Y=webgl_y,\n opts=dict(title='{} points using WebGL'.format(webgl_num_points), webgl=True),\n win=\"WebGL demo\")\n\n\n # line updates\n win = viz.line(\n X=np.column_stack((np.arange(0, 10), np.arange(0, 10))),\n Y=np.column_stack((np.linspace(5, 10, 10),\n np.linspace(5, 10, 10) + 5)),\n )\n viz.line(\n X=np.column_stack((np.arange(10, 20), np.arange(10, 20))),\n Y=np.column_stack((np.linspace(5, 10, 10),\n np.linspace(5, 10, 10) + 5)),\n win=win,\n update='append'\n )\n viz.line(\n X=np.arange(21, 30),\n Y=np.arange(1, 10),\n win=win,\n name='2',\n update='append'\n )\n viz.line(\n X=np.arange(1, 10),\n Y=np.arange(11, 20),\n win=win,\n name='delete this',\n update='append'\n )\n viz.line(\n X=np.arange(1, 10),\n Y=np.arange(11, 20),\n win=win,\n name='4',\n update='insert'\n )\n viz.line(X=None, Y=None, win=win, name='delete this', update='remove')\n\n viz.line(\n X=webgl_x+1.,\n Y=(webgl_x+1.)**3,\n win=\"WebGL demo\",\n update='append',\n opts=dict(title='{} points using WebGL'.format(webgl_num_points*2), webgl=True)\n )\n\n Y = np.linspace(0, 4, 200)\n win = viz.line(\n Y=np.column_stack((np.sqrt(Y), np.sqrt(Y) + 2)),\n X=np.column_stack((Y, Y)),\n opts=dict(\n fillarea=True,\n showlegend=False,\n width=800,\n height=800,\n xlabel='Time',\n ylabel='Volume',\n ytype='log',\n title='Stacked area plot',\n marginleft=30,\n marginright=30,\n marginbottom=80,\n margintop=30,\n ),\n )\n\n # Assure that the stacked area plot isn't giant\n viz.update_window_opts(\n win=win,\n opts=dict(\n width=300,\n height=300,\n ),\n )\n\n # boxplot\n X = np.random.rand(100, 2)\n X[:, 1] += 2\n viz.boxplot(\n X=X,\n opts=dict(legend=['Men', 'Women'])\n )\n\n # stemplot\n Y = np.linspace(0, 2 * math.pi, 70)\n X = np.column_stack((np.sin(Y), np.cos(Y)))\n viz.stem(\n X=X,\n Y=Y,\n opts=dict(legend=['Sine', 'Cosine'])\n )\n\n # quiver plot\n X = np.arange(0, 2.1, .2)\n Y = np.arange(0, 2.1, .2)\n X = np.broadcast_to(np.expand_dims(X, axis=1), (len(X), len(X)))\n Y = np.broadcast_to(np.expand_dims(Y, axis=0), (len(Y), len(Y)))\n U = np.multiply(np.cos(X), Y)\n V = np.multiply(np.sin(X), Y)\n viz.quiver(\n X=U,\n Y=V,\n opts=dict(normalize=0.9),\n )\n\n # pie chart\n X = np.asarray([19, 26, 55])\n viz.pie(\n X=X,\n opts=dict(legend=['Residential', 'Non-Residential', 'Utility'])\n )\n\n # scatter plot example with various type of updates\n colors = np.random.randint(0, 255, (2, 3,))\n win = viz.scatter(\n X=np.random.rand(255, 2),\n Y=(np.random.rand(255) + 1.5).astype(int),\n opts=dict(\n markersize=10,\n markercolor=colors,\n legend=['1', '2']\n ),\n )\n\n viz.scatter(\n X=np.random.rand(255),\n Y=np.random.rand(255),\n opts=dict(\n markersize=10,\n markercolor=colors[0].reshape(-1, 3),\n\n ),\n name='1',\n update='append',\n win=win)\n\n viz.scatter(\n X=np.random.rand(255, 2),\n Y=(np.random.rand(255) + 1.5).astype(int),\n opts=dict(\n markersize=10,\n markercolor=colors,\n ),\n update='append',\n win=win)\n\n # mesh plot\n x = [0, 0, 1, 1, 0, 0, 1, 1]\n y = [0, 1, 1, 0, 0, 1, 1, 0]\n z = [0, 0, 0, 0, 1, 1, 1, 1]\n X = np.c_[x, y, z]\n i = [7, 0, 0, 0, 4, 4, 6, 6, 4, 0, 3, 2]\n j = [3, 4, 1, 2, 5, 6, 5, 2, 0, 1, 6, 3]\n k = [0, 7, 2, 3, 6, 7, 1, 1, 5, 5, 7, 6]\n Y = np.c_[i, j, k]\n viz.mesh(X=X, Y=Y, opts=dict(opacity=0.5))\n\n # SVG plotting\n svgstr = \"\"\"\n <svg height=\"300\" width=\"300\">\n <ellipse cx=\"80\" cy=\"80\" rx=\"50\" ry=\"30\"\n style=\"fill:red;stroke:purple;stroke-width:2\" />\n Sorry, your browser does not support inline SVG.\n </svg>\n \"\"\"\n viz.svg(\n svgstr=svgstr,\n opts=dict(title='Example of SVG Rendering')\n )\n\n # close text window:\n viz.close(win=textwindow)\n\n # assert that the closed window doesn't exist\n assert not viz.win_exists(textwindow), 'Closed window still exists'\n\n # Arbitrary visdom content\n trace = dict(x=[1, 2, 3], y=[4, 5, 6], mode=\"markers+lines\", type='custom',\n marker={'color': 'red', 'symbol': 104, 'size': \"10\"},\n text=[\"one\", \"two\", \"three\"], name='1st Trace')\n layout = dict(title=\"First Plot\", xaxis={'title': 'x1'},\n yaxis={'title': 'x2'})\n\n viz._send({'data': [trace], 'layout': layout, 'win': 'mywin'})\n\n # PyTorch tensor\n try:\n import torch\n viz.line(Y=torch.Tensor([[0., 0.], [1., 1.]]))\n except ImportError:\n print('Skipped PyTorch example')\n\n # audio demo:\n tensor = np.random.uniform(-1, 1, 441000)\n viz.audio(tensor=tensor, opts={'sample_frequency': 441000})\n\n # audio demo:\n # download from http://www.externalharddrive.com/waves/animal/dolphin.wav\n try:\n audio_url = 'http://www.externalharddrive.com/waves/animal/dolphin.wav'\n # linux\n if _platform == \"linux\" or _platform == \"linux2\":\n audiofile = '/home/%s/dolphin.wav' % getpass.getuser()\n # MAC OS X\n elif _platform == \"darwin\":\n audiofile = '/Users/%s/dolphin.wav' % getpass.getuser()\n # download audio\n urllib.request.urlretrieve(audio_url, audiofile)\n\n if os.path.isfile(audiofile):\n viz.audio(audiofile=audiofile)\n except BaseException:\n print('Skipped audio example')\n\n try:\n input = raw_input # for Python 2 compatibility\n except NameError:\n pass\n input('Waiting for callbacks, press enter to quit.')\nexcept BaseException as e:\n print(\n \"The visdom experienced an exception while running: {}\\n\"\n \"The demo displays up-to-date functionality with the GitHub version, \"\n \"which may not yet be pushed to pip. Please upgrade using \"\n \"`pip install -e .` or `easy_install .`\\n\"\n \"If this does not resolve the problem, please open an issue on \"\n \"our GitHub.\".format(repr(e))\n )"
] | [
[
"numpy.expand_dims",
"numpy.random.random",
"numpy.sqrt",
"numpy.linspace",
"torch.Tensor",
"numpy.asarray",
"numpy.arange",
"numpy.cos",
"numpy.sin",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.ylabel",
"numpy.random.randn",
"numpy.random.rand",
"numpy.column_stack",
"numpy.random.uniform",
"numpy.exp",
"numpy.empty",
"numpy.random.randint"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
sagarjounkani/NCRFpp | [
"7bbca8eb6c99aa27a5ba641283cf53e6905cc114"
] | [
"utils/alphabet.py"
] | [
"# -*- coding: utf-8 -*-\n# @Author: Max\n# @Date: 2018-01-19 11:33:37\n# @Last Modified by: Jie Yang, Contact: [email protected]\n# @Last Modified time: 2018-04-26 13:56:03\n\n\n\"\"\"\nAlphabet maps objects to integer ids. It provides two way mapping from the index to the objects.\n\"\"\"\nfrom __future__ import print_function\nimport json\nimport os\nimport sys\nimport torch\nfrom typing import Dict, List\n\n\[email protected]\nclass Alphabet:\n def __init__(self, name: str, label: bool=False, keep_growing: bool=True):\n self.name = name\n self.UNKNOWN = \"</unk>\"\n self.label = label\n self.instance2index = torch.jit.annotate(Dict[str, int], {})\n self.instances = torch.jit.annotate(List[str], [])\n self.keep_growing = keep_growing\n\n # Index 0 is occupied by default, all else following.\n self.default_index: int = 0\n self.next_index: int = 1\n if not self.label:\n self.add(self.UNKNOWN)\n\n @torch.jit.unused\n def clear(self, keep_growing=True):\n self.instance2index = {}\n self.instances = []\n self.keep_growing = keep_growing\n\n # Index 0 is occupied by default, all else following.\n self.default_index = 0\n self.next_index = 1\n\n def add(self, instance: str):\n if instance not in self.instance2index:\n self.instances.append(instance)\n self.instance2index[instance] = self.next_index\n self.next_index += 1\n\n def get_index(self, instance: str) -> int:\n\n # added for scripting\n if instance in self.instance2index:\n return self.instance2index[instance]\n else:\n if self.keep_growing:\n index = self.next_index\n self.add(instance)\n return index\n else:\n return self.instance2index[self.UNKNOWN]\n\n # commented for scripting\n # try:\n # return self.instance2index[instance]\n # except KeyError:\n # if self.keep_growing:\n # index = self.next_index\n # self.add(instance)\n # return index\n # else:\n # return self.instance2index[self.UNKNOWN]\n\n def get_instance(self, index):\n if index == 0:\n if self.label:\n return self.instances[0]\n # First index is occupied by the wildcard element.\n return None\n\n # added for scripting\n if len(self.instances) >= index > 0:\n return self.instances[index - 1]\n else:\n print('WARNING:Alphabet get_instance ,unknown instance, return the first label.')\n return self.instances[0]\n\n # commented for scripting\n # try:\n # return self.instances[index - 1]\n # except IndexError:\n # print('WARNING:Alphabet get_instance ,unknown instance, return the first label.')\n # return self.instances[0]\n\n def size(self):\n # if self.label:\n # return len(self.instances)\n # else:\n return len(self.instances) + 1\n\n @torch.jit.unused\n def iteritems(self):\n if sys.version_info[0] < 3: # If using python3, dict item access uses different syntax\n return self.instance2index.iteritems()\n else:\n return self.instance2index.items()\n\n @torch.jit.unused\n def enumerate_items(self, start=1):\n if start < 1 or start >= self.size():\n raise IndexError(\"Enumerate is allowed between [1 : size of the alphabet)\")\n return zip(range(start, len(self.instances) + 1), self.instances[start - 1:])\n\n @torch.jit.unused\n def close(self):\n self.keep_growing = False\n\n @torch.jit.unused\n def open(self):\n self.keep_growing = True\n\n @torch.jit.unused\n def get_content(self):\n return {'instance2index': self.instance2index, 'instances': self.instances}\n\n @torch.jit.unused\n def from_json(self, data):\n self.instances = data[\"instances\"]\n self.instance2index = data[\"instance2index\"]\n\n @torch.jit.unused\n def save(self, output_directory, name=None):\n \"\"\"\n Save both alhpabet records to the given directory.\n :param output_directory: Directory to save model and weights.\n :param name: The alphabet saving name, optional.\n :return:\n \"\"\"\n saving_name = name if name else self.__name\n try:\n json.dump(self.get_content(), open(os.path.join(output_directory, saving_name + \".json\"), 'w'))\n except Exception as e:\n print(\"Exception: Alphabet is not saved: \" % repr(e))\n\n @torch.jit.unused\n def load(self, input_directory, name=None):\n \"\"\"\n Load model architecture and weights from the give directory. This allow we use old models even the structure\n changes.\n :param input_directory: Directory to save model and weights\n :return:\n \"\"\"\n loading_name = name if name else self.__name\n self.from_json(json.load(open(os.path.join(input_directory, loading_name + \".json\"))))\n"
] | [
[
"torch.jit.annotate"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
Neklaustares-tPtwP/torchflare | [
"7af6b01ef7c26f0277a041619081f6df4eb1e42c"
] | [
"torchflare/datasets/tabular_dataloader.py"
] | [
"\"\"\"Wrapper for dataloaders.\"\"\"\nfrom __future__ import annotations\n\nfrom typing import List, Union\n\nimport pandas as pd\nfrom torch.utils.data import DataLoader\n\nfrom torchflare.datasets.tabular import TabularDataset\n\n\nclass TabularDataloader:\n \"\"\"Class to create easy to use dataloaders.\"\"\"\n\n def __init__(self, ds):\n \"\"\"Constructor method.\n\n Args:\n ds : A pytorch style dataset having __len__ and __getitem__ methods.\n \"\"\"\n self.ds = ds\n\n @classmethod\n def from_df(\n cls,\n df: pd.DataFrame,\n feature_cols: Union[str, List[str]],\n label_cols: Union[str, List[str]] = None,\n ):\n \"\"\"Classmethod to create dataset for tabular data from dataframe.\n\n Args:\n df: The dataframe containing features and labels.\n feature_cols: name(str) or list containing names feature columns.\n label_cols: name(str) or list containing names label columns.\n\n Returns:\n Tabular pytorch dataset.\n\n Examples:\n .. code-block:: python\n\n from torchflare.datasets import TabularDataloader\n\n dl = TabularDataloader.from_df(df=df,\n feature_cols= [\"col1\" , \"col2\"],\n label_cols=\"labels\"\n ).get_loader(batch_size=64, # Required Args.\n shuffle=True, # Required Args.\n num_workers = 0, # keyword Args.\n collate_fn = collate_fn # keyword Args.)\n\n \"\"\"\n return cls(TabularDataset.from_df(df=df, feature_cols=feature_cols, label_cols=label_cols))\n\n @classmethod\n def from_csv(\n cls,\n csv_path: str,\n feature_cols: Union[str, List[str]],\n label_cols: Union[str, List[str]] = None,\n ):\n \"\"\"Classmethod to create a dataset for tabular data from csv.\n\n Args:\n csv_path: The full path to csv.\n feature_cols: name(str) or list containing names feature columns.\n label_cols: name(str) or list containing names label columns.\n\n Returns:\n Tabular pytorch dataset.\n\n Examples:\n\n .. code-block:: python\n\n from torchflare.datasets import TabularDataloader\n dl = TabularDataloader.from_csv(csv_path=\"/train/train_data.csv\",\n feature_cols=[\"col1\" , \"col2\"],\n label_cols=\"labels\"\n ).get_loader(batch_size=64, # Required Args.\n shuffle=True, # Required Args.\n num_workers = 0, # keyword Args.\n collate_fn = collate_fn # keyword Args.)\n\n \"\"\"\n return cls(TabularDataset.from_csv(csv_path=csv_path, feature_cols=feature_cols, label_cols=label_cols))\n\n def get_loader(self, batch_size: int = 32, shuffle: bool = True, **dl_params) -> DataLoader:\n \"\"\"Method to get dataloader.\n\n Args:\n batch_size: The batch size to use\n shuffle: Whether to shuffle the inputs.\n **dl_params : Keyword arguments related to dataloader\n\n Returns:\n A PyTorch dataloader with given arguments.\n \"\"\"\n dl = DataLoader(self.ds, batch_size=batch_size, shuffle=shuffle, **dl_params)\n return dl\n\n\n__all__ = [\"TabularDataloader\"]\n"
] | [
[
"torch.utils.data.DataLoader"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
RParini/abelfunctions | [
"9263cd865e33cbd3ff4ffc1d59c14d77ff27f155"
] | [
"abelfunctions/riemann_surface_path.py"
] | [
"r\"\"\"Riemann Surface Paths :mod:`abelfunctions.riemann_surface_path`\n\nModule for defining paths on Riemann surfaces. A basic Riemann surface path\nconsists of the Riemann surface on which it's defined, a\n:class:`ComplexPathPrimitive` defining the x-projection of the path, and a\nstarting y-fibre. The first element of the y-fibre defines the starting point /\nplace of the surface. However, an entire ordered fibre of y-roots is requested\nsince many anlgorithms for analytic continuation require all roots.\n\nRiemann surface paths are distinguished by how one analytically continues along\nthe path. Typically, if the complex path stays away from any discriminant\npoints of the Riemann surface then :class:`RiemannSurfaceSmale`, which is based\nin Newton's method for root finding, can be used.\n\nClasses\n-------\n.. autosummary::\n\n RiemannSurfacePathPrimitive\n RiemannSurfacePath\n RiemannSurfacePathPuiseux\n RiemannSurfacePathSmale\n\nFunctions\n---------\n.. autosummary::\n\n ordered_puiseux_series\n newton\n smale_alpha\n smale_beta\n smale_gamma\n\nContents\n--------\n\"\"\"\n\nimport warnings\n\nimport numpy\nimport scipy\nfrom abelfunctions.divisor import DiscriminantPlace\nfrom abelfunctions.puiseux import puiseux\nfrom abelfunctions.utilities import matching_permutation\nfrom numpy import double, complex\n\nfrom sage.all import (\n QQ, QQbar, CC, infinity, fast_callable, factorial, cached_method, cached_function)\nfrom sage.functions.other import real_part, imag_part, floor\nfrom sage.plot.line import line\n\n\nclass RiemannSurfacePathPrimitive(object):\n r\"\"\"Primitive Riemann surface path object.\n\n Defines basic, primitive functionality for Riemann surface paths. Each path\n primitive is parameterized from :math:`t=0` to :math:`t=1`.\n\n Attributes\n ----------\n RS : RiemannSurface\n The Riemann surface on which this path primitive is defined.\n x0 : complex\n Starting x-value of the path.\n y0 : complex[]\n Starting y-fibre of the path.\n segments : list of RiemannSurfacePathPrimitive\n A list of the constituent components of the Riemann surface path.\n\n Methods\n -------\n .. autosummary::\n\n get_x\n get_dxds\n get_y\n plot_x\n plot_y\n plot3d_x\n plot3d_y\n\n \"\"\"\n @property\n def segments(self):\n return [self]\n\n def __init__(self, riemann_surface, complex_path, y0, ncheckpoints=16):\n r\"\"\"Initialize a Riemann surface path.\n\n This is a base class for the other classes in this module and should\n not be instantiated directly.\n\n Parameters\n ----------\n riemann_surface : RiemannSurface\n The Riemann surface on which the path is defined.\n complex_path : ComplexPathPrimitive\n The x-projection of the path.\n y0 : list of complex\n The starting fibre lying above the starting point of\n `complex_path`. The first component of the list indicates the\n starting sheet.\n ncheckpoints : int\n The number of points to cache analytic continuation results along\n the path so that one doesn't have to analytically continue from the\n start of the path every time.\n\n \"\"\"\n self.riemann_surface = riemann_surface\n self.complex_path = complex_path\n self.x0 = complex_path(0)\n self.y0 = numpy.array(y0, dtype=complex)\n\n # cached s, x, and y checkpoints\n self._ncheckpoints = ncheckpoints\n self._scheckpoints = numpy.zeros(ncheckpoints, dtype=double)\n self._xcheckpoints = numpy.zeros(ncheckpoints, dtype=complex)\n self._ycheckpoints = numpy.zeros(\n (ncheckpoints, riemann_surface.deg), dtype=complex)\n\n # initialize the checkpoints on the path. see\n # RiemannSurfacePath.__init__ for additional information on how the\n # following is interpreted in the composite setting.\n if ncheckpoints > 0:\n self._initialize_checkpoints()\n self._repr = None\n\n def __repr__(self):\n if not self._repr:\n self._set_repr()\n return self._repr\n\n def _set_repr(self):\n r\"\"\"Set the string representation of the Riemann surface path.\n\n This can only be done after object instantiation when we know the type\n of path created. String representation depends on whether self is a\n cycle on the surface or not.\n \"\"\"\n is_cycle = False\n startx = self.x0\n endx = self.get_x(1.0)\n\n # cheap check: if the x-endpoints match\n if numpy.abs(startx - endx) < 1e-12:\n starty = self.y0\n endy = self.get_y(1.0)\n\n # expensive check: if the y-endpoints match\n if numpy.linalg.norm(starty - endy) < 1e-12:\n is_cycle = True\n\n if is_cycle:\n self._repr = 'Cycle on the %s'%(self.riemann_surface)\n else:\n self._repr = 'Path on the %s with x-projection %s'%(\n self.riemann_surface, self.complex_path)\n\n\n def __add__(self, other):\n r\"\"\"Add two Riemann surface paths together.\n\n Checks if the ending place of `self` is equal to the ending place of\n `other`. If so, returns a `RiemannSurfacePath` object whose segments\n are a concatenation of the path segments of each summand.\n\n Parameters\n ----------\n other : RiemannSurfacePathPrimitive\n\n Returns\n -------\n RiemannSurfacePath\n \"\"\"\n # try getting the segments of the other object. Doing so asserts that\n # the other object is of type RiemannSurfacePathPrimitve\n try:\n segments = self.segments + other.segments\n except AttributeError:\n raise TypeError('Summands must both be of '\n 'RiemannSurfacePathPrimitive type.')\n\n # assert that the endpoint of the segments of this path matches with\n # those of the other path\n eps = 1e-8\n deg = self.riemann_surface.degree\n\n # get the ending place of the left RSPath (self) and the starting place\n # of the right RSPath (other).\n end_segment = self.segments[-1]\n x_end = end_segment.get_x(1.0)\n y_end = end_segment.get_y(1.0)\n x_start = other.x0\n y_start = other.y0\n\n # if the x- or y-values don't match, raise an error\n x_error = abs(x_start - x_end)\n y_error = numpy.linalg.norm(y_start - y_end)\n if (x_error > eps) or (y_error > eps):\n raise ValueError('Cannot form sum of paths: starting place and '\n 'fibre of right Riemann surface path does not '\n 'match ending place of left path.')\n\n complex_path = self.complex_path + other.complex_path\n gamma = RiemannSurfacePath(self.riemann_surface, complex_path,\n self.y0, segments)\n return gamma\n\n def _nearest_checkpoint_index(self, s):\n r\"\"\"Returns the index of the checkpoint closest to and preceding `s`.\n\n Parameters\n ----------\n s : double\n Path parameter in the interval [0,1].\n\n Returns\n -------\n index : int\n The index `k` such that `self._scheckpoints[k] <= t` but\n `self._scheckpoints[k+1] > t`.\n \"\"\"\n n = self._ncheckpoints\n if s == 1.0:\n return n-1\n for k in range(1,n):\n si = self._scheckpoints[k]\n if si >= s:\n index = k-1\n return index\n\n # use first checkpoint if something goes wrong\n index = 0\n return index\n\n def _initialize_checkpoints(self):\n r\"\"\"Analytically continue along the entire path recording y-values at\n evenly spaced points.\n\n We cache the y-values at various evenly-spaced points :math:`t\n \\in [0,1]` so one doesn't have to analytically continue from\n :math:`t=0` every time.\n\n Parameters\n ----------\n None\n\n Returns\n -------\n None\n\n \"\"\"\n # initialize containers\n n = self._ncheckpoints\n s = numpy.linspace(0, 1, n, dtype=double)\n x = numpy.array([self.get_x(si) for si in s], dtype=complex)\n y = numpy.zeros((n, self.riemann_surface.degree), dtype=complex)\n\n # for each t-checkpoint compute the corresponding x- and y-checkpoint\n # by analytically continuing. note that the analytic continuation is\n # defined by the subclass and is not implemented in the base class\n sim1 = 0.0\n xim1 = self.x0\n yim1 = self.y0\n y[0,:] = yim1\n for i in range(1,n):\n si = s[i]\n xi = self.complex_path(si)\n yi = self.analytically_continue(xim1, yim1, xi)\n y[i,:] = yi\n xim1 = xi\n yim1 = yi\n\n # store the checkpoint information\n self._scheckpoints = s\n self._xcheckpoints = x\n self._ycheckpoints = y\n\n def get_x(self, s):\n r\"\"\"Return the x-part of the path at :math:`s \\in [0,1]`.\n\n Parameters\n ----------\n s : double\n Path parameter in the interval [0,1].\n\n Returns\n -------\n value : complex\n The x-projection of self at s.\n\n \"\"\"\n value = self.complex_path.eval(s)\n return value\n\n def get_dxds(self, s):\n r\"\"\"Return the derivative of the x-part of the path at :math:`s \\in [0,1]`.\n\n Parameters\n ----------\n s : double\n Path parameter in the interval [0,1].\n\n Returns\n -------\n value : complex\n The derivative of the x-projection of self at s.\n\n \"\"\"\n value = self.complex_path.derivative(s)\n return value\n\n def get_y(self, s):\n r\"\"\"Return the y-fibre of the path at :math:`s \\in [0,1]`.\n\n Delegates to :meth:`analytically_continue`.\n\n Parameters\n ----------\n s : double\n Path parameter in the interval [0,1].\n\n Returns\n -------\n value : complex[:]\n The y-fibre above the path at s.\n \"\"\"\n # get the closest checkpoint to the desired t-value\n i = self._nearest_checkpoint_index(s)\n xim1 = self._xcheckpoints[i]\n yim1 = self._ycheckpoints[i]\n\n # analytically continue to target\n xi = self.complex_path.eval(s)\n yi = self.analytically_continue(xim1, yim1, xi)\n return yi\n\n def analytically_continue(xi, yi, xip1):\n raise NotImplementedError('Implement in subclass.')\n\n def integrate(self, omega):\n r\"\"\"Integrate `omega` along this path.\n\n Parameters\n ----------\n omega : Differential\n A differential (one-form) on the Riemann surface.\n\n Returns\n -------\n integral : complex\n The integral of omega along self.\n \"\"\"\n omega_gamma = self.parameterize(omega)\n integral = scipy.integrate.romberg(omega_gamma, 0.0, 1.0)\n return integral\n\n def evaluate(self, omega, s):\n r\"\"\"Evaluates `omega` along the path at :math:`s \\in [0,1]`.\n\n Parameters\n ----------\n omega : Differential\n A differential (one-form) on the Riemann surface.\n s : double or double[:]\n Path parameter(s) in the interval [0,1].\n\n Returns\n -------\n values : complex or complex[:]\n The differential omega evaluated along the path at each of the\n points in `s`.\n \"\"\"\n omega_gamma = self.parameterize(omega)\n values = omega_gamma(s)\n return values\n\n def parameterize(self, omega):\n raise NotImplementedError('Implement in subclass.')\n\n def plot_x(self, *args, **kwds):\n r\"\"\"Plot the x-part of the path in the complex x-plane.\n\n Calls :func:`ComplexPath.plot` on this path's x-projection.\n\n Parameters\n ----------\n *args : list\n Arguments passed to :func:`ComplexPath.plot`.\n **kwds : dict\n Keywords passed to :func:`ComplexPath.plot`.\n Returns\n -------\n matplotlib lines array.\n\n \"\"\"\n return self.complex_path.plot(*args, **kwds)\n\n def plot_y(self, plot_points=128, **kwds):\n r\"\"\"Plot the y-part of the path in the complex y-plane.\n\n Additional arguments and keywords are passed to\n ``matplotlib.pyplot.plot``.\n\n Parameters\n ----------\n N : int\n The number of interpolating points used to plot.\n t0 : double\n Starting t-value in [0,1].\n t1 : double\n Ending t-value in [0,1].\n\n Returns\n -------\n plt : Sage plot.\n A plot of the complex y-projection of the path.\n\n \"\"\"\n s = numpy.linspace(0, 1, plot_points, dtype=double)\n vals = numpy.array([self.get_y(si)[0] for si in s], dtype=complex)\n pts = [(real_part(y), imag_part(y)) for y in vals]\n plt = line(pts, **kwds)\n return plt\n\n\n\nclass RiemannSurfacePath(RiemannSurfacePathPrimitive):\n r\"\"\"A composite of Riemann surface path primitives.\n\n These are usually created via summation of other paths, such as\n :class:`RiemannSurfacePathPuiseux` and :class:`RiemannSurfacePathSmale`,\n and represent a composite of :class:`RiemannSurfacePathPrimitives`.\n\n Attributes\n ----------\n segments : list of RiemannSurfacePathPrimitives\n A list of the constituent paths that make up this composite path.\n\n Methods\n -------\n .. autosummary::\n\n segment_index_at_parameter\n\n \"\"\"\n\n @property\n def segments(self):\n return self._segments\n\n def __init__(self, riemann_surface, complex_path, y0, segments):\n r\"\"\"Directly instantiate a RiemannSurfacePath from a Riemann surface and a list\n of Riemann surface path primitives.\n\n Parameters\n ----------\n riemann_surface : RiemannSurface\n The Riemann surface on which the path is defined.\n complex_path : ComplexPathPrimitive\n The x-projection of the path.\n y0 : list of complex\n The starting fibre lying above the starting point of\n `complex_path`. The first component of the list indicates the\n starting sheet.\n *args : list\n A list of :class:`RiemannSurfacePathPrimitive`s which make up the\n segments / constituents of this path.\n \"\"\"\n # RiemannSurfacePath delegates all analytic continuation to each of its\n # components.\n #\n # Additionally, setting ncheckpoints to \"0\" prevents\n # self._initialize_checkpoints() from executing, which only makes sense\n # on a single path segment / path primitive.\n RiemannSurfacePathPrimitive.__init__(\n self, riemann_surface, complex_path, y0, ncheckpoints=0)\n\n self._segments = segments\n self._nsegments = len(segments)\n\n def __getitem__(self, index):\n return self._segments[index]\n\n def segment_index_at_parameter(self, s):\n r\"\"\"Returns the index of the complex path segment located at the given\n parameter :math:`s \\in [0,1]`.\n\n Parameters\n ----------\n s : float\n Path parameter in the interval [0,1].\n\n Returns\n -------\n index : int\n The index `k` of the path segment :math:`\\gamma_k`.\n \"\"\"\n # the following is a fast way to divide the interval [0,1] into n\n # partitions and determine which partition s lies in. since this is\n # done often it needs to be fast\n k = floor(s*self._nsegments)\n diff = (self._nsegments - 1) - k\n dsgn = diff >> 31\n return k + (diff & dsgn)\n\n def get_x(self, s):\n r\"\"\"Return the x-part of the path at :math:`s \\in [0,1]`.\n\n Parameters\n ----------\n s : double\n Path parameter in the interval [0,1].\n\n Returns\n -------\n value : complex\n The x-projection of self at s.\n\n \"\"\"\n k = self.segment_index_at_parameter(s)\n s_segment = s*self._nsegments - k\n segment = self._segments[k]\n value = segment.get_x(s_segment)\n return value\n\n def get_dxds(self, s):\n r\"\"\"Return the derivative of the x-part of the path at :math:`s \\in [0,1]`.\n\n Parameters\n ----------\n s : double\n Path parameter in the interval [0,1].\n\n Returns\n -------\n value : complex\n The derivative of the x-projection of self at s.\n\n \"\"\"\n k = self.segment_index_at_parameter(s)\n s_segment = s*self._nsegments - k\n segment = self._segments[k]\n value = segment.get_dxds(s_segment)\n return value\n\n def get_y(self, s):\n r\"\"\"Return the y-fibre of the path at :math:`s \\in [0,1]`.\n\n Delegates to :meth:`analytically_continue`.\n\n Parameters\n ----------\n s : double\n Path parameter in the interval [0,1].\n\n Returns\n -------\n value : complex[:]\n The y-fibre above the path at s.\n \"\"\"\n k = self.segment_index_at_parameter(s)\n s_segment = s*self._nsegments - k\n segment = self._segments[k]\n value = segment.get_y(s_segment)\n return value\n\n def parameterize(self, omega):\n r\"\"\"Returns the differential omega parameterized on the path.\n\n Given a differential math:`\\omega = \\omega(x,y)dx`, `parameterize`\n returns the differential\n\n .. math::\n\n \\omega_\\gamma(s) = \\omega(\\gamma_x(s),\\gamma_y(s)) \\gamma_x'(s)\n\n where :math:`s \\in [0,1]` and :math:`\\gamma_x,\\gamma_y` and the x- and\n y-components of the path `\\gamma` using this analytic continuator.\n\n .. note::\n\n This may be pretty slow in the composite path case. Usually, we\n want to integrate using parameterizations which, in the composite\n case, we just perform one segment at a time instead of determining\n a global parameterization here.\n\n Parameters\n ----------\n omega : Differential\n A differential (one-form) on the Riemann surface.\n\n Returns\n -------\n omega_gamma : function\n The differential parameterized on the curve for s in the interval\n [0,1].\n \"\"\"\n def omega_gamma(s):\n k = self.segment_index_at_parameter(s)\n s_segment = s*self._nsegments - k\n segment = self._segments[k]\n omega_gamma_segment = segment.parameterize(omega)\n return omega_gamma_segment(s_segment)\n return omega_gamma\n\n def evaluate(self, omega, s):\n r\"\"\"Evaluates `omega` along the path at :math:`s \\in [0,1]`.\n\n Parameters\n ----------\n omega : Differential\n A differential (one-form) on the Riemann surface.\n s : double[:]\n Path parameter(s) in the interval [0,1].\n\n Returns\n -------\n values : complex or complex[:]\n The differential omega evaluated along the path at each of the\n points in `s`.\n \"\"\"\n # determine the number of points per segment on which to evaluate\n N = len(s)\n nsegs = len(self._segments)\n ppseg = int(N/nsegs)\n values = numpy.zeros(nsegs*ppseg, dtype=complex)\n values_seg = numpy.zeros(ppseg, dtype=complex)\n tseg = numpy.linspace(0, 1, ppseg)\n\n # evaluate along each segment\n for k in range(nsegs):\n segment = self._segments[k]\n values_seg = segment.evaluate(omega, tseg)\n for j in range(ppseg):\n values[k*ppseg+j] = values_seg[j]\n return values\n\n def integrate(self, omega):\n r\"\"\"Integrate `omega` along this path.\n\n Parameters\n ----------\n omega : Differential\n A differential (one-form) on the Riemann surface.\n\n Returns\n -------\n integral : complex\n The integral of omega along self.\n \"\"\"\n integral = complex(0.0)\n for gamma in self._segments:\n integral += gamma.integrate(omega)\n return integral\n\n\n##############################################\n# Puiseux Series-based Riemann Surface Paths #\n##############################################\ndef ordered_puiseux_series(riemann_surface, complex_path, y0, target_point):\n r\"\"\"Returns an ordered list of Puiseux series such that each Puiseux series\n matches with the corresponding y-fibre element above the starting point of\n `complex_path`.\n\n In order to analytically continue from the regular places at the beginning\n of the path :math:`x=a` to the discriminant places at the end of the path\n :math:`x=b`we need to compute all of the `PuiseuxXSeries` at :math:`x=b`.\n There are two steps to this calculation:\n\n * compute enough terms of the Puiseux series centered at :math:`x=b` in\n order to accurately capture the y-roots at :math:`x=a`.\n\n * permute the series accordingly to match up with the y-roots at\n :math:`x=a`.\n\n Parameters\n ----------\n riemann_surface : RiemannSurface\n The riemann surface on which all of this lives.\n complex_path : ComplexPath\n The path or path segment starting at a regular point and ending at a\n discriminant point.\n y0 : list of complex\n The starting fibre lying above the starting point of `complex_path`.\n The first component of the list indicates the starting sheet.\n target_point : complex\n The point to analytically continue to. Usually a discriminant point.\n\n Methods\n -------\n .. autosummary::\n\n analytically_continue\n\n Returns\n -------\n list, Place : a list of Puiseux series and a Place\n A list of ordered Puiseux series corresponding to each branch above\n :math:`x=a` as well as the place that the first y-fibre element\n analytically continues to.\n \"\"\"\n # obtain all puiseux series above the target place\n f = riemann_surface.f\n x0 = CC(complex_path(0)) # XXX - need to coerce input to CC\n y0 = numpy.array(y0, dtype=complex)\n P = puiseux(f, target_point)\n\n # extend the Puiseux series to enough terms to accurately captue the\n # y-fibre above x=a (the starting point of the complex path)\n for Pi in P:\n Pi.extend_to_x(x0)\n\n # compute the corresponding x-series representations of the Puiseux series\n alpha = 0 if target_point == infinity else target_point\n px = [Pi.xseries() for Pi in P]\n p = [pxi for sublist in px for pxi in sublist]\n ramification_indices = [Pi.ramification_index for Pi in P]\n\n # reorder them according to the ordering of the y-fibre above x=x0\n p_evals_above_x0 = [pj(x0-alpha) for pj in p]\n p_evals_above_x0 = numpy.array(p_evals_above_x0, dtype=complex)\n sigma = matching_permutation(p_evals_above_x0, y0)\n p = sigma.action(p)\n\n # also return the place that the first y-fibre element ends up analytically\n # continuing to\n px_idx = sigma[0] # index of target x-series in unsorted list\n place_idx = -1 # index of place corresponding to this x-series\n while px_idx >= 0:\n place_idx += 1\n px_idx -= abs(ramification_indices[place_idx])\n target_place = DiscriminantPlace(riemann_surface,P[place_idx])\n return p, target_place\n\n\nclass RiemannSurfacePathPuiseux(RiemannSurfacePathPrimitive):\n r\"\"\"A Riemann surface path that uses Puiseux series to analytically continue\n along a complex path.\n\n Newton's method / Smale's alpha theory (see\n :class:`RiemannSurfacePathSmale`) breaks down when close to a discriminant\n point of the curve since the y-sheets coalesce at that point. In order to\n accurately track the y-fibre above points near the discrimimant point we\n need to compute an ordered set of puiseux series\n\n Attributes\n ----------\n puiseux_series : list of PuiseuxSeries\n An ordered list of Puiseux series centered at the endpoint of the complex path.\n center : complex\n The center of the above Puiseux series. (The endpoint of the complex path.)\n target_point : complex\n The point in the complex x-plane that we're analytically coninuing to.\n target_place : Place\n The place that the first sheet of the input y-fibre ends up\n analytically continuing to.\n\n Methods\n -------\n .. autosummary::\n\n analytically_continue\n parameterize\n\n See Also\n --------\n * :func:`ordered_puiseux_series`\n * :class:`RiemannSurfacePathSmale`\n\n \"\"\"\n def __init__(self, riemann_surface, complex_path, y0, ncheckpoints=16):\n # if the complex path leads to a discriminant point then get the exact\n # representation of said discrimimant point\n target_point = complex_path(1)\n if target_point in [numpy.Infinity, infinity]:\n target_point = infinity\n elif abs(CC(target_point)) > 1e12:\n target_point = infinity\n else:\n discriminant_point = riemann_surface.path_factory.closest_discriminant_point(target_point)\n if abs(CC(target_point - discriminant_point)) < 1e-12:\n target_point = discriminant_point\n else:\n # if it's not discriminant then try to coerce to QQ or QQbar\n try:\n target_point = QQ(target_point)\n except TypeError:\n try:\n target_point = QQbar(target_point)\n except TypeError:\n pass\n\n # compute and store the ordered puiseux series needed to analytically\n # continue as well as the target place for parameterization purposes\n puiseux_series, target_place = ordered_puiseux_series(\n riemann_surface, complex_path, y0, target_point)\n self.puiseux_series = puiseux_series\n self.target_point = target_point\n self.target_place = target_place\n\n # now that the machinery is set up we can instantiate the base object\n RiemannSurfacePathPrimitive.__init__(\n self, riemann_surface, complex_path, y0, ncheckpoints=ncheckpoints)\n\n def analytically_continue(self, xi, yi, xip1):\n r\"\"\"Analytically continue the y-fibre `yi` lying above `xi` to the y-fibre lying\n above `xip1`.\n\n We analytically continue by simply evaluating the ordered puiseux\n series computed during initialization of the Riemann surface path.\n\n Parameters\n ----------\n xi : complex\n The starting complex x-value.\n yi: complex[:]\n The starting complex y-fibre lying above `xi`.\n xip1: complex\n The target complex x-value.\n\n Returns\n -------\n yi : complex[:]\n The corresponding y-fibre lying above `xi`.\n \"\"\"\n # XXX HACK - need to coerce input to CC for puiseux series to evaluate\n xi = CC(xi)\n xip1 = CC(xip1)\n\n # return the current fibre if the step size is too small\n if numpy.abs(xip1-xi) < 1e-15:\n return yi\n\n # simply evaluate the ordered puiseux series at xip1\n alpha = CC(0) if self.target_point == infinity else CC(self.target_point)\n yip1 = [pj(xip1-alpha) for pj in self.puiseux_series]\n yip1 = numpy.array(yip1, dtype=complex)\n return yip1\n\n @cached_method\n def parameterize(self, omega):\n r\"\"\"Returns the differential omega parameterized on the path.\n\n Given a differential math:`\\omega = \\omega(x,y)dx`, `parameterize`\n returns the differential\n\n .. math::\n\n \\omega_\\gamma(s) = \\omega(\\gamma_x(s),\\gamma_y(s)) \\gamma_x'(s)\n\n where :math:`s \\in [0,1]` and :math:`\\gamma_x,\\gamma_y` and the x- and\n y-components of the path `\\gamma` using this analytic continuator.\n\n Parameters\n ----------\n omega : Differential\n A differential (one-form) on the Riemann surface.\n\n Returns\n -------\n omega_gamma : function\n The differential parameterized on the curve for s in the interval\n [0,1].\n \"\"\"\n # localize the differential at the discriminant place\n P = self.target_place\n omega_local = omega.localize(P)\n omega_local = omega_local.laurent_polynomial().change_ring(CC)\n\n # extract relevant information about the Puiseux series\n p = P.puiseux_series\n x0 = complex(self.gamma.x0)\n y0 = complex(self.gamma.y0[0])\n alpha = 0 if self.target_point == infinity else self.target_point\n xcoefficient = complex(p.xcoefficient)\n e = numpy.int(p.ramification_index)\n\n # the parameter of the path s \\in [0,1] does not necessarily match with\n # the local coordinate t of the place. perform the appropriate scaling\n # on the integral.\n tprim = complex((x0-alpha)/xcoefficient)**(1./e)\n unity = [numpy.exp(2.j*numpy.pi*k/abs(e)) for k in range(abs(e))]\n tall = [unity[k]*tprim for k in range(abs(e))]\n ytprim = numpy.array([p.eval_y(tk) for tk in tall], dtype=numpy.complex)\n k = numpy.argmin(numpy.abs(ytprim - y0))\n tcoefficient = tall[k]\n\n # XXX HACK - CC coercion\n tcoefficient = CC(tcoefficient)\n def omega_gamma(s):\n s = CC(s)\n dtds = -tcoefficient\n val = omega_local(tcoefficient*(1-s)) * dtds\n return complex(val)\n return numpy.vectorize(omega_gamma, otypes=[complex])\n\n\n####################################################\n# Smale's Alpha Theory-based Riemann Surface Paths #\n####################################################\nABELFUNCTIONS_SMALE_ALPHA0 = 1.1884471871911697 # = (13-2*sqrt(17))/4\n\ndef newton(df, xip1, yij):\n \"\"\"Newton iterate a y-root yij of a polynomial :math:`f = f(x,y)`, lying above\n some x-point xi, to the x-point xip1.\n\n Given :math:`f(x_i,y_{i,j}) = 0` and some complex number :math:`x_{i+1}`,\n this function returns a complex number :math:`y_{i+1,j}` such that\n :math:`f(x_{i+1},y_{i+1,j}) = 0`.\n\n Parameters\n ----------\n df : list of polynomials\n A list of all of the y-derivatives of f, including f itself.\n xip1 : complex\n The x-point to analytically continue to.\n yij: complex\n A y-root at xi. The root that we'll analytically continue.\n\n Returns\n -------\n yij : complex\n A y-root of f lying above `xip1`.\n\n \"\"\"\n df0 = df[0]\n df1 = df[1]\n step = numpy.complex(1.0)\n maxIter = 1000\n numIter = 0\n while numpy.abs(step) > 1e-14:\n # if df is not invertible then we are at a critical point.\n df1y = df1(xip1,yij)\n if numpy.abs(df1y) < 1e-14:\n break\n step = df0(xip1,yij) / df1y\n yij = yij - step\n\n numIter += 1\n if numIter >= maxIter:\n warnings.warn('Newton failed to converge after %d iterations. Final step size: %g' % (maxIter, numpy.abs(step)))\n break\n return yij\n\n\ndef smale_beta(df, xip1, yij):\n \"\"\"Smale beta function.\n\n The Smale beta function is simply the size of a Newton iteration\n\n Parameters\n ---------\n df : list of polynomials\n A list of all of the y-derivatives of f, including f itself.\n xip1 : complex\n The x-point to analytically continue to.\n yij: complex\n A y-root at xi. The root that we'll analytically continue.\n\n Returns\n -------\n val : double\n :math:`\\beta(f,x_{i+1},y_{i,j})`.\n \"\"\"\n df0 = df[0]\n df1 = df[1]\n val = numpy.abs(df0(xip1,yij) / df1(xip1,yij))\n return val\n\n\ndef smale_gamma(df, xip1, yij):\n \"\"\"Smale gamma function.\n\n Parameters\n ----------\n df : MultivariatePolynomial\n A list of all of the y-derivatives of f, including f itself.\n xip1 : complex\n The x-point to analytically continue to.\n yij : complex\n A y-root at xi. The root that we'll analytically continue.\n\n Returns\n -------\n double\n The Smale gamma function.\n \"\"\"\n df0 = df[0]\n df1 = df[1]\n deg = len(df) - 1\n df1y = df1(xip1,yij)\n gamma = numpy.double(0)\n\n for n in range(2,deg+1):\n dfn = df[n]\n gamman = numpy.abs(dfn(xip1,yij) / (factorial(n)*df1y))\n gamman = gamman**(1.0/(n-1.0))\n if gamman > gamma:\n gamma = gamman\n return gamma\n\n\ndef smale_alpha(df, xip1, yij):\n \"\"\"Smale alpha function.\n\n Parameters\n ----------\n df : MultivariatePolynomial\n a list of all of the y-derivatives of f (up to the y-degree)\n xip1 : complex\n the x-point to analytically continue to\n yij : complex\n a y-root at xi. The root that we'll analytically continue.\n\n Returns\n -------\n double\n The Smale alpha function.\n \"\"\"\n return smale_beta(df,xip1,yij) * smale_gamma(df,xip1,yij)\n\n\n\nclass RiemannSurfacePathSmale(RiemannSurfacePathPrimitive):\n r\"\"\"A Riemann surface Path that uses Smale's alpha theory with Newton iteration\n to analytically continue along a complex path.\n\n For complex paths that stay sufficiently away from a discrimimant point of\n the curve defining the Riemann surface we can use Newton's method to\n analytically continue. This method is fast compared to calculation and\n evaluation of Puiseux series.\n\n Smale's alpha theory is used to ensure that appropriate steps sizes are\n taken in the complex x-plane. (i.e. along the complex path.)\n\n Attributes\n ----------\n degree : int\n The y-degree of the underlying curve of the Riemann surface.\n df : list of functions\n A list of all of the y-derivatives of f *up to the y-degree).\n\n Methods\n -------\n .. autosummary::\n\n analytically_continue\n parameterize\n\n \"\"\"\n def __init__(self, riemann_surface, complex_path, y0, ncheckpoints=16):\n # store a list of all y-derivatives of f (including the zeroth deriv)\n degree = riemann_surface.degree\n f = riemann_surface.f.change_ring(CC)\n x,y = f.parent().gens()\n df = [\n fast_callable(f.derivative(y,k), vars=(x,y), domain=complex)\n for k in range(degree+1)\n ]\n\n self.degree = degree\n self.df = df\n RiemannSurfacePathPrimitive.__init__(\n self, riemann_surface, complex_path, y0, ncheckpoints=ncheckpoints)\n\n def analytically_continue(self, xi, yi, xip1):\n # return the current fibre if the step size is too small\n if numpy.abs(xip1-xi) < 1e-14:\n return yi\n\n # first determine if the y-fibre guesses are 'approximate solutions'.\n # if any of them are not then refine the step by analytically\n # continuing to an intermediate \"time\"\n for j in range(self.degree):\n yij = yi[j]\n if smale_alpha(self.df, xip1, yij) > ABELFUNCTIONS_SMALE_ALPHA0:\n xiphalf = (xi + xip1)/2.0\n yiphalf = self.analytically_continue(xi, yi, xiphalf)\n yip1 = self.analytically_continue(xiphalf, yiphalf, xip1)\n return yip1\n\n # next, determine if the approximate solutions will converge to\n # different associated solutions\n for j in range(self.degree):\n yij = yi[j]\n betaij = smale_beta(self.df, xip1, yij)\n for k in range(j+1, self.degree):\n yik = yi[k]\n betaik = smale_beta(self.df, xip1, yik)\n distancejk = numpy.abs(yij-yik)\n if distancejk < 2*(betaij + betaik):\n # approximate solutions don't lead to distinct roots.\n # refine the step by analytically continuing to an\n # intermedite time\n xiphalf = (xi + xip1)/2.0\n yiphalf = self.analytically_continue(xi, yi, xiphalf)\n yip1 = self.analytically_continue(xiphalf, yiphalf, xip1)\n return yip1\n\n # finally, since we know that we have approximate solutions that will\n # converge to difference associated solutions we will Netwon iterate\n yip1 = numpy.zeros(self.degree, dtype=complex)\n for j in range(self.degree):\n yip1[j] = newton(self.df, xip1, yi[j])\n return yip1\n\n @cached_method\n def parameterize(self, omega):\n r\"\"\"Returns the differential omega parameterized on the path.\n\n Given a differential math:`\\omega = \\omega(x,y)dx`, `parameterize`\n returns the differential\n\n .. math::\n\n \\omega_\\gamma(s) = \\omega(\\gamma_x(s),\\gamma_y(s)) \\gamma_x'(s)\n\n where :math:`s \\in [0,1]` and :math:`\\gamma_x,\\gamma_y` and the x- and\n y-components of the path `\\gamma` using this analytic continuator.\n\n Parameters\n ----------\n omega : Differential\n A differential (one-form) on the Riemann surface.\n\n Returns\n -------\n omega_gamma : function\n The differential parameterized on the curve for s in the interval\n [0,1].\n \"\"\"\n def omega_gamma(s):\n xs = self.get_x(s)\n ys = self.get_y(s)[0]\n dxds = self.get_dxds(s)\n return omega(xs,ys) * dxds\n return numpy.vectorize(omega_gamma, otypes=[complex])\n"
] | [
[
"scipy.integrate.romberg",
"numpy.abs",
"numpy.linspace",
"numpy.linalg.norm",
"numpy.int",
"numpy.complex",
"numpy.vectorize",
"numpy.array",
"numpy.zeros",
"numpy.double"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [
"0.13",
"1.6",
"0.14",
"1.10",
"0.15",
"1.4",
"0.16",
"1.9",
"0.19",
"1.5",
"0.18",
"1.2",
"1.7",
"0.12",
"1.0",
"0.17",
"1.3",
"1.8"
],
"tensorflow": []
}
] |
bjj9/EVE_SCPT | [
"c91b13f8bbfe8ea29a0e9f1df0dc016a258c904f"
] | [
"src/models/common.py"
] | [
"\"\"\"Copyright 2021 Hangzhou Dianzi University, Jun Bao\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n\"\"\"\nimport os\nimport numpy as np\nimport torch\nimport torch.nn as nn\nfrom torch.nn import functional as F\nfrom ipdb import set_trace as st\n\nfrom core import DefaultConfig\n\nconfig = DefaultConfig()\n# device = torch.device('cuda:0' if torch.cuda.is_available() else \"cpu\")\ncurr_device_index = torch.cuda.current_device()\n#device = torch.device('cuda:'+str(curr_device_index) if torch.cuda.is_available() else \"cpu\")\ndevice = torch.device((\"cuda:0\" if config.use_one_gpu is None else 'cuda:'+str(config.use_one_gpu) ) if torch.cuda.is_available() else \"cpu\")\ndevice = torch.device('cuda:0')\nprint(device, '---nfjjiefjj common.py')\n\n\ndef pitchyaw_to_vector(a):\n if a.shape[1] == 2:\n sin = torch.sin(a)\n cos = torch.cos(a)\n return torch.stack([cos[:, 0] * sin[:, 1], sin[:, 0], cos[:, 0] * cos[:, 1]], dim=1)\n elif a.shape[1] == 3:\n return F.normalize(a)\n else:\n raise ValueError('Do not know how to convert tensor of size %s' % a.shape)\n\n\ndef vector_to_pitchyaw(a):\n if a.shape[1] == 2:\n return a\n elif a.shape[1] == 3:\n a = a.view(-1, 3)\n norm_a = torch.div(a, torch.norm(a, dim=1).view(-1, 1) + 1e-7)\n return torch.stack([\n torch.asin(norm_a[:, 1]),\n torch.atan2(norm_a[:, 0], norm_a[:, 2]),\n ], dim=1)\n else:\n raise ValueError('Do not know how to convert tensor of size %s' % a.shape)\n\n\ndef pitchyaw_to_rotation(a):\n if a.shape[1] == 3:\n a = vector_to_pitchyaw(a)\n\n cos = torch.cos(a)\n sin = torch.sin(a)\n ones = torch.ones_like(cos[:, 0])\n zeros = torch.zeros_like(cos[:, 0])\n matrices_1 = torch.stack([ones, zeros, zeros,\n zeros, cos[:, 0], sin[:, 0],\n zeros, -sin[:, 0], cos[:, 0]\n ], dim=1)\n matrices_2 = torch.stack([cos[:, 1], zeros, sin[:, 1],\n zeros, ones, zeros,\n -sin[:, 1], zeros, cos[:, 1]\n ], dim=1)\n matrices_1 = matrices_1.view(-1, 3, 3)\n matrices_2 = matrices_2.view(-1, 3, 3)\n matrices = torch.matmul(matrices_2, matrices_1)\n return matrices\n\n\ndef rotation_to_vector(a):\n assert(a.ndim == 3)\n assert(a.shape[1] == a.shape[2] == 3)\n frontal_vector = torch.cat([\n torch.zeros_like(a[:, :2, 0]).reshape(-1, 2, 1),\n torch.ones_like(a[:, 2, 0]).reshape(-1, 1, 1),\n ], axis=1)\n return torch.matmul(a, frontal_vector)\n\n\ndef apply_transformation(T, vec):\n if vec.shape[1] == 2:\n vec = pitchyaw_to_vector(vec)\n vec = vec.reshape(-1, 3, 1)\n h_vec = F.pad(vec, pad=(0, 0, 0, 1), value=1.0)\n return torch.matmul(T, h_vec)[:, :3, 0]\n\n\ndef apply_rotation(T, vec):\n if vec.shape[1] == 2:\n vec = pitchyaw_to_vector(vec)\n vec = vec.reshape(-1, 3, 1)\n R = T[:, :3, :3]\n return torch.matmul(R, vec).reshape(-1, 3)\n\n\nnn_plane_normal = None\nnn_plane_other = None\n\n\ndef get_intersect_with_zero(o, g, nn_plane_normal, nn_plane_other):\n \"\"\"Intersects a given gaze ray (origin o and direction g) with z = 0.\"\"\"\n # global nn_plane_normal, nn_plane_other #TODO: muting this is crucial for parallel running gpu\n # if nn_plane_normal is None:\n # # nn_plane_normal = torch.tensor([0, 0, 1], dtype=torch.float32, device=device).view(1, 3, 1)\n # # nn_plane_other = torch.tensor([1, 0, 0], dtype=torch.float32, device=device).view(1, 3, 1)\n # # nn_plane_normal = torch.tensor([0, 0, 1], dtype=torch.float32, device=o.device).view(1, 3, 1)\n # # nn_plane_other = torch.tensor([1, 0, 0], dtype=torch.float32, device=o.device).view(1, 3, 1)\n\n # Define plane to intersect with\n n = nn_plane_normal\n a = nn_plane_other\n g = g.view(-1, 3, 1)\n o = o.view(-1, 3, 1)\n cc = [x.device.index for x in (a, o, n)]\n # print('divice', torch.cuda.current_device(), cc, '---ewfjiijdf common.py')\n # if not all([xx == cc[0] for xx in cc]):\n # print('divice', torch.cuda.current_device(), cc, '---qjijwdij common.py')\n numer = torch.sum(torch.mul(a - o, n), dim=1)\n\n # Intersect with plane using provided 3D origin\n denom = torch.sum(torch.mul(g, n), dim=1) + 1e-7\n t = torch.div(numer, denom).view(-1, 1, 1)\n return (o + torch.mul(t, g))[:, :2, 0]\n\n\ndef calculate_combined_gaze_direction(avg_origin, avg_PoG, head_rotation, camera_transformation):\n # NOTE: PoG is assumed to be in mm and in the screen-plane\n avg_PoG_3D = F.pad(avg_PoG, (0, 1))\n\n # Bring to camera-specific coordinate system, where the origin is\n avg_PoG_3D = apply_transformation(camera_transformation, avg_PoG_3D)\n direction = avg_PoG_3D - avg_origin\n\n # Rotate gaze vector back\n direction = direction.reshape(-1, 3, 1)\n direction = torch.matmul(head_rotation, direction)\n\n # Negate gaze vector back (to user perspective)\n direction = -direction\n\n direction = vector_to_pitchyaw(direction)\n return direction\n\n\ndef to_screen_coordinates(origin, direction, rotation, reference_dict):\n direction = pitchyaw_to_vector(direction)\n\n # Negate gaze vector back (to camera perspective)\n direction = -direction\n\n # De-rotate gaze vector\n inv_rotation = torch.transpose(rotation, 1, 2)\n direction = direction.reshape(-1, 3, 1)\n direction = torch.matmul(inv_rotation, direction)\n\n # Transform values\n #st()\n inv_camera_transformation = reference_dict['inv_camera_transformation']\n direction = apply_rotation(inv_camera_transformation, direction)\n origin = apply_transformation(inv_camera_transformation, origin)\n\n # Intersect with z = 0\n #print('origin', origin, '\\ndirection', direction, '\\nrotation', rotation, '\\nreference_dict', reference_dict, '---nvjfjei common.py')\n if not config.multi_gpu:\n nn_plane_normal = torch.tensor([0, 0, 1], dtype=torch.float32).to(device).view(1, 3, 1)\n nn_plane_other = torch.tensor([1, 0, 0], dtype=torch.float32).to(device).view(1, 3, 1)\n else:\n nn_plane_normal = torch.tensor([0, 0, 1], dtype=torch.float32).cuda().view(1, 3, 1)\n nn_plane_other = torch.tensor([1, 0, 0], dtype=torch.float32).cuda().view(1, 3, 1)\n cc = [x.device.index for x in (origin, direction, nn_plane_normal, nn_plane_other)]\n # print('divice', torch.cuda.current_device(), cc, '---ejvfdij common.py')\n # if not all([xx == cc[0] for xx in cc]):\n # print('divice', torch.cuda.current_device(), cc, '---efddfsddf common.py')\n recovered_target_2D = get_intersect_with_zero(origin, direction, nn_plane_normal, nn_plane_other)\n PoG_mm = recovered_target_2D\n\n # Convert back from mm to pixels\n ppm_w = reference_dict['pixels_per_millimeter'][:, 0]\n ppm_h = reference_dict['pixels_per_millimeter'][:, 1]\n PoG_px = torch.stack([\n torch.clamp(recovered_target_2D[:, 0] * ppm_w,\n 0.0, float(config.actual_screen_size[0])),\n torch.clamp(recovered_target_2D[:, 1] * ppm_h,\n 0.0, float(config.actual_screen_size[1]))\n ], axis=-1)\n\n return PoG_mm, PoG_px\n\n\ndef apply_offset_augmentation(gaze_direction, head_rotation, kappa, inverse_kappa=False):\n #print('gaze_direction', gaze_direction, '\\nhead_rotation', head_rotation, '\\nkappa', kappa, '---jjjieijij common.py')\n gaze_direction = pitchyaw_to_vector(gaze_direction)\n # Negate gaze vector back (to camera perspective)\n gaze_direction = -gaze_direction\n\n # De-rotate gaze vector\n inv_head_rotation = torch.transpose(head_rotation, 1, 2)\n gaze_direction = gaze_direction.reshape(-1, 3, 1)\n gaze_direction = torch.matmul(inv_head_rotation, gaze_direction)\n\n # Negate gaze vector back (to user perspective)\n gaze_direction = -gaze_direction\n\n # Apply kappa to frontal vector [0 0 1]\n kappa_vector = pitchyaw_to_vector(kappa).reshape(-1, 3, 1)\n if inverse_kappa:\n kappa_vector = torch.cat([\n -kappa_vector[:, :2, :], kappa_vector[:, 2, :].reshape(-1, 1, 1),\n ], axis=1)\n\n # Apply head-relative gaze to rotated frontal vector\n head_relative_gaze_rotation = pitchyaw_to_rotation(vector_to_pitchyaw(gaze_direction))\n # print('head_relative_gaze_rotation', head_relative_gaze_rotation, '\\nkappa_vector', kappa_vector, '---ejfijjjdj common.py')\n gaze_direction = torch.matmul(head_relative_gaze_rotation, kappa_vector)\n\n # Negate gaze vector back (to camera perspective)\n gaze_direction = -gaze_direction\n\n # Rotate gaze vector back\n gaze_direction = gaze_direction.reshape(-1, 3, 1)\n gaze_direction = torch.matmul(head_rotation, gaze_direction)\n\n # Negate gaze vector back (to user perspective)\n gaze_direction = -gaze_direction\n\n gaze_direction = vector_to_pitchyaw(gaze_direction)\n return gaze_direction\n\n\nheatmap_xs = None\nheatmap_ys = None\nheatmap_alpha = None\n\n\ndef make_heatmap(centre, sigma):\n global heatmap_xs, heatmap_ys, heatmap_alpha\n w, h = config.gaze_heatmap_size\n if heatmap_xs is None:\n xs = np.arange(0, w, step=1, dtype=np.float32)\n ys = np.expand_dims(np.arange(0, h, step=1, dtype=np.float32), -1)\n if not config.multi_gpu:\n heatmap_xs = torch.tensor(xs).to(device)\n heatmap_ys = torch.tensor(ys).to(device)\n else:\n heatmap_xs = torch.tensor(xs).cuda()\n heatmap_ys = torch.tensor(ys).cuda()\n heatmap_alpha = -0.5 / (sigma ** 2)\n cx = (w / config.actual_screen_size[0]) * centre[0]\n cy = (h / config.actual_screen_size[1]) * centre[1]\n heatmap = torch.exp(heatmap_alpha * ((heatmap_xs - cx)**2 + (heatmap_ys - cy)**2))\n heatmap = 1e-8 + heatmap # Make the zeros non-zero (remove collapsing issue)\n return heatmap.unsqueeze(0) # make it (1 x H x W) in shape\n\n\ndef batch_make_heatmaps(centres, sigma):\n return torch.stack([make_heatmap(centre, sigma) for centre in centres], axis=0)\n\n\ngaze_history_map_decay_per_ms = None\n\n\ndef make_gaze_history_map(history_timestamps, heatmaps, validities):\n # NOTE: heatmaps has dimensions T x H x W\n global gaze_history_map_decay_per_ms\n target_timestamp = history_timestamps[torch.nonzero(history_timestamps)][-1]\n output_heatmap = torch.zeros_like(heatmaps[0])\n if gaze_history_map_decay_per_ms is None:\n if not config.multi_gpu:\n gaze_history_map_decay_per_ms = torch.tensor(config.gaze_history_map_decay_per_ms).to(device)\n else:\n gaze_history_map_decay_per_ms = torch.tensor(config.gaze_history_map_decay_per_ms).cuda()\n\n for timestamp, heatmap, validity in zip(history_timestamps, heatmaps, validities):\n\n if timestamp == 0:\n continue\n\n # Calculate difference in time in milliseconds\n diff_timestamp = (target_timestamp - timestamp) * 1e-6\n assert(diff_timestamp >= 0)\n\n # Weights for later weighted average\n time_based_weight = torch.pow(gaze_history_map_decay_per_ms, diff_timestamp).view(1, 1)\n\n # Keep if within time window\n output_heatmap = output_heatmap + validity.float() * time_based_weight.detach() * heatmap\n\n return output_heatmap\n\n\ndef batch_make_gaze_history_maps(history_timestamps, heatmaps, validity):\n # NOTE: timestamps is a tensor, heatmaps is a list of tensors\n batch_size = history_timestamps.shape[0]\n history_len = len(heatmaps)\n return torch.stack([\n make_gaze_history_map(\n history_timestamps[b, :history_len],\n [h[b, :] for h in heatmaps],\n validity[b, :history_len],\n )\n for b in range(batch_size)\n ], axis=0)\n\n\nsoftargmax_xs = None\nsoftargmax_ys = None\n\n\ndef soft_argmax(heatmaps):\n global softargmax_xs, softargmax_ys\n if softargmax_xs is None:\n # Assume normalized coordinate [0, 1] for numeric stability\n w, h = config.gaze_heatmap_size\n ref_xs, ref_ys = np.meshgrid(np.linspace(0, 1.0, num=w, endpoint=True),\n np.linspace(0, 1.0, num=h, endpoint=True),\n indexing='xy')\n ref_xs = np.reshape(ref_xs, [1, h*w])\n ref_ys = np.reshape(ref_ys, [1, h*w])\n if not config.multi_gpu:\n softargmax_xs = torch.tensor(ref_xs.astype(np.float32)).to(device)\n softargmax_ys = torch.tensor(ref_ys.astype(np.float32)).to(device)\n else:\n softargmax_xs = torch.tensor(ref_xs.astype(np.float32)).cuda()\n softargmax_ys = torch.tensor(ref_ys.astype(np.float32)).cuda()\n ref_xs, ref_ys = softargmax_xs, softargmax_ys\n\n # Yield softmax+integrated coordinates in [0, 1]\n n, _, h, w = heatmaps.shape\n assert(w == config.gaze_heatmap_size[0])\n assert(h == config.gaze_heatmap_size[1])\n beta = 1e2\n x = heatmaps.view(-1, h*w)\n x = F.softmax(beta * x, dim=-1)\n lmrk_xs = torch.sum(ref_xs * x, axis=-1)\n lmrk_ys = torch.sum(ref_ys * x, axis=-1)\n\n # Return to actual coordinates ranges\n pixel_xs = torch.clamp(config.actual_screen_size[0] * lmrk_xs,\n 0.0, config.actual_screen_size[0])\n pixel_ys = torch.clamp(config.actual_screen_size[1] * lmrk_ys,\n 0.0, config.actual_screen_size[1])\n return torch.stack([pixel_xs, pixel_ys], axis=-1)\n\n\nclass Flatten(nn.Module):\n def forward(self, x):\n return x.view(x.size()[0], -1)\n\n\nclass CRNNCell(nn.Module):\n def __init__(self, input_size, hidden_size):\n super(CRNNCell, self).__init__()\n\n self.input_size = input_size\n self.hidden_size = hidden_size\n\n self.cell = nn.Conv2d(self.input_size + self.hidden_size, self.hidden_size,\n kernel_size=3, padding=1)\n\n def forward(self, x, previous_states=None):\n batch_size = x.shape[0]\n if previous_states is None:\n state_shape = [batch_size, self.hidden_size] + list(x.shape[2:])\n if not config.multi_gpu:\n hidden_state = torch.autograd.Variable(torch.zeros(state_shape)).to(device)\n else:\n hidden_state = torch.autograd.Variable(torch.zeros(state_shape)).cuda()\n else:\n hidden_state = previous_states\n\n # Apply RNN\n hidden = self.cell(torch.cat([x, hidden_state], axis=1))\n hidden = torch.tanh(hidden)\n return hidden\n\n\nclass CLSTMCell(nn.Module):\n def __init__(self, input_size, hidden_size):\n super(CLSTMCell, self).__init__()\n\n self.input_size = input_size\n self.hidden_size = hidden_size\n\n self.gates = nn.Conv2d(self.input_size + self.hidden_size, 4 * self.hidden_size,\n kernel_size=3, padding=1)\n\n def forward(self, x, previous_states=None):\n batch_size = x.shape[0]\n if previous_states is None:\n state_shape = [batch_size, self.hidden_size] + list(x.shape[2:])\n if not config.multi_gpu:\n hidden_state = torch.autograd.Variable(torch.zeros(state_shape)).to(device)\n cell_state = torch.autograd.Variable(torch.zeros(state_shape)).to(device)\n else:\n hidden_state = torch.autograd.Variable(torch.zeros(state_shape)).cuda()\n cell_state = torch.autograd.Variable(torch.zeros(state_shape)).cuda()\n else:\n hidden_state, cell_state = previous_states\n\n # Apply LSTM\n gates = self.gates(torch.cat([x, hidden_state], axis=1))\n in_gate, forget_gate, out_gate, cell_gate = gates.chunk(4, 1)\n in_gate = torch.sigmoid(in_gate)\n forget_gate = torch.sigmoid(forget_gate)\n out_gate = torch.sigmoid(out_gate)\n cell_gate = torch.tanh(cell_gate)\n forget = (forget_gate * cell_state)\n update = (in_gate * cell_gate)\n cell = forget + update\n hidden = out_gate * torch.tanh(cell)\n return hidden, cell\n\n\nclass CGRUCell(nn.Module):\n def __init__(self, input_size, hidden_size):\n super(CGRUCell, self).__init__()\n\n self.input_size = input_size\n self.hidden_size = hidden_size\n\n self.gates_1 = nn.Conv2d(self.input_size + self.hidden_size, 2 * self.hidden_size,\n kernel_size=3, padding=1)\n self.gate_2 = nn.Conv2d(self.input_size + self.hidden_size, self.hidden_size,\n kernel_size=3, padding=1)\n\n def forward(self, x, previous_states=None):\n batch_size = x.shape[0]\n if previous_states is None:\n state_shape = [batch_size, self.hidden_size] + list(x.shape[2:])\n if not config.multi_gpu:\n hidden_state = torch.autograd.Variable(torch.zeros(state_shape)).to(device)\n else:\n hidden_state = torch.autograd.Variable(torch.zeros(state_shape)).cuda()\n else:\n hidden_state = previous_states\n\n # Apply GRU\n gates_1 = self.gates_1(torch.cat([x, hidden_state], axis=1))\n reset_gate, update_gate = torch.sigmoid(gates_1).chunk(2, 1)\n reset_gate = (reset_gate * hidden_state)\n output_gate = self.gate_2(torch.cat([reset_gate, x], axis=1))\n output_gate = torch.tanh(output_gate)\n hidden = (1. - update_gate) * output_gate + update_gate * hidden_state\n return hidden\n"
] | [
[
"torch.nn.functional.softmax",
"torch.transpose",
"numpy.linspace",
"torch.sin",
"torch.cat",
"torch.zeros",
"torch.sum",
"torch.tanh",
"torch.cuda.is_available",
"torch.device",
"torch.pow",
"torch.norm",
"numpy.reshape",
"numpy.arange",
"torch.tensor",
"torch.asin",
"torch.mul",
"torch.nonzero",
"torch.ones_like",
"torch.nn.functional.pad",
"torch.cos",
"torch.div",
"torch.sigmoid",
"torch.cuda.current_device",
"torch.nn.Conv2d",
"torch.zeros_like",
"torch.exp",
"torch.stack",
"torch.atan2",
"torch.nn.functional.normalize",
"torch.matmul",
"torch.clamp"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
patchett2002/pyDNMFk | [
"ba73d72eb4f46d8a79a83350db89e568f9ec9351"
] | [
"pyDNMFk/pyDNMFk.py"
] | [
"#@author: Manish Bhattarai\nfrom scipy.stats import wilcoxon\nfrom . import config\nfrom .dist_clustering import *\nfrom .pyDNMF import *\nfrom .plot_results import *\n\nclass sample():\n \"\"\"\n Generates perturbed version of data based on sampling distribution.\n\n Parameters\n ----------\n data : ndarray\n Array of which to find a perturbation.\n noise_var : float\n The perturbation amount.\n method : str\n Method for sampling (uniform/poisson)\n seed : float(optional)\n Set seed for random data generation\n \"\"\"\n\n\n @comm_timing()\n def __init__(self, data, noise_var, method, seed=None):\n\n self.X = data\n self.noise_var = noise_var\n self.seed = seed\n if self.seed != None:\n np.random.seed(self.seed)\n self.method = method\n self.X_per = 0\n\n @comm_timing()\n def randM(self):\n \"\"\"\n Multiplies each element of X by a uniform random number in (1-epsilon, 1+epsilon).\n \"\"\"\n\n M = 2 * self.noise_var * np.random.random_sample(self.X.shape).astype(self.X.dtype) + self.noise_var\n M = M + 1\n self.X_per = np.multiply(self.X, M)\n\n @comm_timing()\n def poisson(self):\n \"\"\"Resamples each element of a matrix from a Poisson distribution with the mean set by that element. Y_{i,j} = Poisson(X_{i,j}\"\"\"\n\n self.X_per = np.random.poisson(self.X).astype(self.X.dtype)\n\n @comm_timing()\n def fit(self):\n r\"\"\"\n Calls the sub routines to perform resampling on data\n\n Returns\n -------\n X_per : ndarry\n Perturbed version of data\n \"\"\"\n\n if self.method == 'uniform':\n self.randM()\n elif self.method == 'poisson':\n self.poisson()\n return self.X_per\n\n\nclass PyNMFk():\n r\"\"\"\n Performs the distributed NMF decomposition with custom clustering for estimating hidden factors k\n\n Parameters\n ----------\n A_ij : ndarray\n Distributed Data\n factors : tuple (optional)\n Distributed factors W and H\n params : class\n Class which comprises following attributes\n params.init : str\n NMF initialization(rand/nnsvd)\n params.comm1 : object\n Global Communicator\n params.comm : object\n Modified communicator object\n params.k : int\n Rank for decomposition\n params.m : int\n Global dimensions m\n params.n : int\n Global dimensions n\n params.p_r : int\n Cartesian grid row count\n params.p_c : int\n Cartesian grid column count\n params.row_comm : object\n Sub communicator along row\n params.col_comm : object\n Sub communicator along columns\n params.W_update : bool\n flag to set W update True/False\n params.norm : str\n NMF norm to be minimized\n params.method : str\n NMF optimization method\n params.eps : float\n Epsilon value\n params.verbose : bool\n Flag to enable/disable display results\n params.save_factors : bool\n Flag to enable/disable saving computed factors\n params.perturbations : int\n Number of Perturbations for clustering\n params.noise_var : float\n Set noise variance for perturbing the data\n params.sill_thr : float\n Set the sillhouette threshold for estimating K with p-test\n params.start_k : int\n Starting range for Feature search K\n params.end_k : int\n Ending range for Feature search K\"\"\"\n\n @comm_timing()\n def __init__(self, A_ij, factors=None, params=None):\n self.A_ij = A_ij\n self.local_m, self.local_n = self.A_ij.shape\n self.params = params\n self.comm1 = self.params.comm1\n self.rank = self.comm1.rank\n self.p_r, self.p_c = self.params.p_r, self.params.p_c\n self.fpath = self.params.fpath\n self.fname = self.params.fname\n self.p = self.p_r * self.p_c\n if self.p_r != 1 and self.p_c != 1:\n self.topo = '2d'\n else:\n self.topo = '1d'\n self.sampling = var_init(self.params,'sampling',default='uniform')\n self.perturbations = var_init(self.params,'perturbations',default=20)\n self.noise_var = var_init(self.params,'noise_var',default=.03)\n self.Hall = 0\n self.Wall = 0\n self.recon_err = 0\n self.AvgH = 0\n self.AvgG = 0\n self.col_err = 0\n self.clusterSilhouetteCoefficients, self.avgSilhouetteCoefficients = 0, 0\n self.L_errDist = 0\n self.avgErr = 0\n self.start_k = self.params.start_k # ['start_k']\n self.end_k = self.params.end_k # ['end_k']\n self.sill_thr = var_init(params,'sill_thr',default=0.9)\n self.verbose = var_init(params,'verbose',default=False)\n\n\n @comm_timing()\n def fit(self):\n r\"\"\"\n Calls the sub routines to perform distributed NMF decomposition and then custom clustering to estimate k\n\n Returns\n -------\n nopt : int\n Estimated value of latent features\n \"\"\"\n SILL_MIN = []\n errRegres = []\n errRegresTol = []\n RECON = []\n RECON1 = []\n self.params.results_path = self.params.results_path + self.params.fname + '/'\n if self.rank == 0:\n try: os.makedirs(self.params.results_paths)\n except: pass\n for self.k in range(self.start_k, self.end_k + 1):\n self.params.k = self.k\n self.pynmfk_per_k()\n SILL_MIN.append(round(np.min(self.clusterSilhouetteCoefficients), 2))\n errRegres.append([self.col_err])\n errRegresTol.append([self.recon_err])\n RECON.append(self.L_errDist)\n RECON1.append(self.avgErr)\n if self.rank == 0:\n nopt1, pvalue1 = self.pvalueAnalysis(errRegres, SILL_MIN)\n print('Rank estimated by NMFk = ', nopt1)\n plot_results(self.start_k, self.end_k, RECON, RECON1, SILL_MIN, self.params.results_path, self.fname)\n else:\n nopt1 = None\n nopt1 = self.comm1.bcast(nopt1, root=0)\n self.comm1.barrier()\n return nopt1\n\n @comm_timing()\n def pynmfk_per_k(self):\n \"\"\"Performs NMF decomposition and clustering for each k to estimate silhouette statistics\"\"\"\n self.params.results_paths = self.params.results_path+ str(self.k) + '/'\n if self.rank == 0:\n try: os.makedirs(self.params.results_paths)\n except: pass\n results = []\n if self.rank == 0: print('*************Computing for k=', self.k, '************')\n for i in range(self.perturbations):\n if self.rank == 0: print('Current perturbation =', i)\n data = sample(data=self.A_ij, noise_var=self.noise_var, method=self.sampling, seed=i * 1000).fit()\n self.params.W_update = True\n results.append(PyNMF(data, factors=None, params=self.params).fit())\n self.Wall = np.hstack(([results[i][0] for i in range(self.perturbations)]))\n self.Wall = self.Wall.reshape(self.Wall.shape[0], self.k, self.perturbations, order='F')\n self.Hall = np.vstack(([results[i][1] for i in range(self.perturbations)]))\n self.Hall = self.Hall.reshape(self.k, self.Hall.shape[1], self.perturbations)\n self.recon_err = [results[i][2] for i in range(self.perturbations)]\n [processAvg, processSTD, self.Hall, self.clusterSilhouetteCoefficients, self.avgSilhouetteCoefficients,\n idx] = custom_clustering(self.Wall, self.Hall, self.params).fit()\n self.AvgH = np.median(self.Hall, axis=-1)\n self.AvgW = processAvg\n self.params.W_update = False\n regressH = PyNMF(self.A_ij, factors=[self.AvgW, self.AvgH], params=self.params)\n self.AvgW, self.AvgH, self.L_errDist = regressH.fit()\n self.col_err = regressH.column_err()\n self.avgErr = np.mean(self.recon_err)\n cluster_stats = {'clusterSilhouetteCoefficients': self.clusterSilhouetteCoefficients,\n 'avgSilhouetteCoefficients': self.avgSilhouetteCoefficients, 'L_errDist': self.L_errDist, \\\n 'L_err': self.col_err, 'avgErr': self.avgErr, 'recon_err': self.recon_err}\n data_writer = data_write(self.params)\n data_writer.save_factors([self.AvgW, self.AvgH], reg=True)\n data_writer.save_cluster_results(cluster_stats)\n\n @comm_timing()\n def pvalueAnalysis(self, errRegres, SILL_MIN):\n \"\"\"\n Calculates nopt by analysing the errors distributions\n\n Parameters\n ----------\n errRegres : array\n array for storing the distributions of errors\n SILL_MIN : float\n Minimum of silhouette score\n \"\"\"\n pvalue = np.ones(self.end_k - self.start_k + 1)\n oneDistrErr = errRegres[0][0];\n i = 1\n i_old = 0\n nopt = 1\n\n while i < (self.end_k - self.start_k + 1):\n i_next = i\n if SILL_MIN[i - 1] > self.sill_thr: # 0.75:\n pvalue[i] = wilcoxon(oneDistrErr, errRegres[i][0])[1]\n if pvalue[i] < 0.05:\n i_old = i\n nopt = i\n oneDistrErr = np.copy(errRegres[i][0])\n i = i + 1\n else:\n i = i + 1\n else:\n i = i + 1\n # print('nopt=', nopt)\n return nopt + self.start_k - 1, pvalue\n"
] | [
[
"scipy.stats.wilcoxon"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [
"0.13",
"1.6",
"0.14",
"1.10",
"0.15",
"1.4",
"0.16",
"1.9",
"0.19",
"1.5",
"0.18",
"1.2",
"1.7",
"0.12",
"1.0",
"0.17",
"1.3",
"1.8"
],
"tensorflow": []
}
] |
bueler/mg-glaciers | [
"649c323f18f31a332c0845bf3955d201cd4c3cf8"
] | [
"paper/genfigs/sia/convergence.py"
] | [
"#!/usr/bin/env python3\n\n# see py/1D/study/siaconv.sh to generate input data siaconv.txt\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom writeout import writeout\n\nINFILE = 'convergence.txt'\nMARKER = ['o','s','D']\nMARKERSIZE = [10.0,9.0,8.0]\nMARKERFACE = ['w','w','k']\nNAME = ['$|s-s_{exact}|_1$','$|s-s_{exact}|_2$','$|H^r-H_{exact}^r|_p$']\n\nprint('reading %s ...' % INFILE)\nv = np.array(np.loadtxt(INFILE))\n#print(v)\n\nN = 13 # number of different resolutions\nassert len(v[:,0]) == N\n\n# columns: J m err2 errrp\nL = 1800.0e3 # m\nm = v[:,1]\nh = L / (m+1)\nh /= 1000.0 # show in km\nerr1 = v[:,2]\nerr2 = v[:,3]\nerrrp = v[:,4]\n\n# numerical error versus h\nplt.figure(figsize=(7,6))\nq1 = np.polyfit(np.log(h),np.log(err1),1)\nq2 = np.polyfit(np.log(h),np.log(err2),1)\nqrp = np.polyfit(np.log(h),np.log(errrp),1)\nprint('|s-sexact|_1 = O(h^%.2f), |s-sexact|_2 = O(h^%.2f), |H^r - Hexact^r|_p = O(h^%.2f)' \\\n % (q1[0],q2[0],qrp[0]))\nplt.loglog(h,err1,\n 'k'+MARKER[0],ms=MARKERSIZE[0],mfc=MARKERFACE[0],\n label=NAME[0] + '$=O(h^{%.2f})$' % q1[0])\nplt.loglog(h,np.exp(q1[0]*np.log(h)+q1[1]),'k--')\nplt.loglog(h,err2,\n 'k'+MARKER[1],ms=MARKERSIZE[1],mfc=MARKERFACE[1],\n label=NAME[1] + '$=O(h^{%.2f})$' % q2[0])\nplt.loglog(h,np.exp(q2[0]*np.log(h)+q2[1]),'k--')\nplt.loglog(h,errrp,\n 'k'+MARKER[2],ms=MARKERSIZE[2],mfc=MARKERFACE[2],\n label=NAME[2] + '$=O(h^{%.2f})$' % qrp[0])\nplt.loglog(h,np.exp(qrp[0]*np.log(h)+qrp[1]),'k--')\nplt.grid(True)\nplt.axis([1.0e-2,1.0e3,1.0e2,1.0e12])\nplt.xlabel('$h$ (km)',fontsize=18.0)\nplt.ylabel('numerical error',fontsize=18.0)\nplt.xticks(fontsize=14.0)\nplt.yticks(fontsize=14.0)\nplt.minorticks_off()\nplt.legend(loc='upper left',fontsize=14.0)\nwriteout('convergence.pdf')\n"
] | [
[
"matplotlib.pyplot.legend",
"matplotlib.pyplot.yticks",
"numpy.log",
"matplotlib.pyplot.minorticks_off",
"matplotlib.pyplot.loglog",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.grid",
"matplotlib.pyplot.axis",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.xticks",
"numpy.loadtxt",
"matplotlib.pyplot.figure"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
ziimiin14/rpg_dvs_ros_modifed | [
"da63b163e5d7ee7ccb8335050d3a3303193d9d3a"
] | [
"dvxplorer_ros_driver/scripts/image_reconstructor_trt.py"
] | [
"import torch\nimport cv2\nimport numpy as np\nfrom model.model import *\nfrom utils.inference_utils import CropParameters, EventPreprocessor, IntensityRescaler, ImageFilter, ImageDisplay, ImageWriter, UnsharpMaskFilter\nfrom utils.inference_utils import upsample_color_image, merge_channels_into_color_image # for color reconstruction\nfrom utils.util import robust_min, robust_max\nfrom utils.timers import CudaTimer, cuda_timers\nfrom os.path import join\nfrom collections import deque\nimport torch.nn.functional as F\nfrom torch2trt import torch2trt\n\n\n\nclass ImageReconstructor:\n def __init__(self, model,height, width, num_bins, options):\n\n self.model = model\n self.use_gpu = options.use_gpu\n self.device = torch.device('cuda:0') if self.use_gpu else torch.device('cpu')\n self.height = height # 240 \n self.width = width # 320\n self.num_bins = num_bins # 5\n\n self.initialize(self.height, self.width, options)\n\n def initialize(self, height, width, options):\n print('== Image reconstruction == ')\n print('Image size: {}x{}'.format(self.height, self.width))\n\n self.no_recurrent = options.no_recurrent\n if self.no_recurrent:\n print('!!Recurrent connection disabled!!')\n\n self.perform_color_reconstruction = options.color # whether to perform color reconstruction (only use this with the DAVIS346color)\n if self.perform_color_reconstruction:\n if options.auto_hdr:\n print('!!Warning: disabling auto HDR for color reconstruction!!')\n options.auto_hdr = False # disable auto_hdr for color reconstruction (otherwise, each channel will be normalized independently)\n\n self.crop = CropParameters(self.width, self.height, 4) # num_encoders = 4\n\n init_1 = torch.zeros((1,16,240,320),device='cuda:0')\n init_2 = torch.zeros((1,16,240,320),device='cuda:0')\n init_state = [init_1,init_2]\n self.last_states_for_each_channel = {'grayscale': init_state}\n\n if self.perform_color_reconstruction:\n self.crop_halfres = CropParameters(int(width / 2), int(height / 2),\n 4)\n for channel in ['R', 'G', 'B', 'W']:\n self.last_states_for_each_channel[channel] = None\n\n self.event_preprocessor = EventPreprocessor(options)\n self.intensity_rescaler = IntensityRescaler(options)\n self.image_filter = ImageFilter(options)\n self.unsharp_mask_filter = UnsharpMaskFilter(options, device=self.device)\n self.image_writer = ImageWriter(options)\n self.image_display = ImageDisplay(options)\n\n def update_reconstruction(self, event_tensor, event_tensor_id, stamp=None):\n with torch.no_grad():\n\n with CudaTimer('Reconstruction'):\n\n with CudaTimer('NumPy (CPU) -> Tensor (GPU)'):\n events = event_tensor.unsqueeze(dim=0) # from (5,240,320) to (1,5,240,320)\n events = events.to(self.device)\n\n events = self.event_preprocessor(events)\n #events = events.type(torch.float16)\n\n # Resize tensor to [1 x C x crop_size x crop_size] by applying zero padding\n events_for_each_channel = {'grayscale': self.crop.pad(events)}\n \n reconstructions_for_each_channel = {}\n if self.perform_color_reconstruction:\n events_for_each_channel['R'] = self.crop_halfres.pad(events[:, :, 0::2, 0::2])\n events_for_each_channel['G'] = self.crop_halfres.pad(events[:, :, 0::2, 1::2])\n events_for_each_channel['W'] = self.crop_halfres.pad(events[:, :, 1::2, 0::2])\n events_for_each_channel['B'] = self.crop_halfres.pad(events[:, :, 1::2, 1::2])\n\n # Reconstruct new intensity image for each channel (grayscale + RGBW if color reconstruction is enabled)\n for channel in events_for_each_channel.keys():\n with CudaTimer('Inference'):\n new_predicted_frame,state1,state2 = self.model(events_for_each_channel[channel],self.last_states_for_each_channel[channel][0],self.last_states_for_each_channel[channel][1])\n\n new_predicted_frame = new_predicted_frame.squeeze(dim=0)\n state1 = state1.squeeze(dim=0)\n state2 = state2.squeeze(dim=0)\n if self.no_recurrent:\n self.last_states_for_each_channel[channel] = None\n else:\n self.last_states_for_each_channel[channel] = [state1,state2]\n \n # Output reconstructed image\n crop = self.crop if channel == 'grayscale' else self.crop_halfres\n # print(crop.ix0,crop.ix1,crop.iy0,crop.iy1) ## 0, 320, 0, 240\n # print(new_predicted_frame.shape) ## ([1,1,240,320])\n\n # Unsharp mask (on GPU)\n # new_predicted_frame = new_predicted_frame.type(torch.float32)\n new_predicted_frame = self.unsharp_mask_filter(new_predicted_frame)\n\n # Intensity rescaler (on GPU)\n new_predicted_frame = self.intensity_rescaler(new_predicted_frame)\n\n with CudaTimer('Tensor (GPU) -> NumPy (CPU)'):\n reconstructions_for_each_channel[channel] = new_predicted_frame[0, 0, crop.iy0:crop.iy1,\n crop.ix0:crop.ix1].cpu().numpy()\n\n if self.perform_color_reconstruction:\n out = merge_channels_into_color_image(reconstructions_for_each_channel)\n else:\n self.out = reconstructions_for_each_channel['grayscale']\n\n # Post-processing, e.g bilateral filter (on CPU)\n #self.out = self.image_filter(out)\n\n #self.image_writer(out, event_tensor_id, stamp, events=events)\n #self.image_display(out, events)\n"
] | [
[
"torch.device",
"torch.no_grad",
"torch.zeros"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
mrogez-yseop/cpp-taskflow | [
"e40c633784cb1712b04c88719dd53fc62f57e806"
] | [
"image/plot/Fig/micro_benchmark/plot.py"
] | [
"import matplotlib.pyplot as plt\nimport numpy as np\nimport matplotlib.mlab as mlab\nimport matplotlib.gridspec as gridspec\n\nplt.subplots_adjust(hspace=0.23)\n\n# dev cost for wavefront\ncosts = [1507, 872, 680, 306]\n\nplt.subplot(221)\nx = np.arange(4)\n#plt.plot(costs, label='v1 (OpenMP)', color='black')\nplt.bar(x, costs)\nplt.title('Dev Cost (matrix wavefront)', fontsize=22)\n#plt.xlabel('task model', fontsize=18)\nplt.ylabel('$USD', fontsize=16)\nplt.xticks(x, ('OpenMP', 'TBB', 'Cpp-Taskflow', 'seq'), fontsize=14)\nplt.legend()\n\n\n# Dev cost for graph traversal\ncosts = [5326, 1384, 920, 306]\n\nplt.subplot(222)\nx = np.arange(4)\n#plt.plot(costs, label='v1 (OpenMP)', color='black')\nplt.bar(x, costs)\nplt.title('Dev Cost (graph traversal)', fontsize=22)\n#plt.xlabel('task model', fontsize=18)\nplt.ylabel('$USD', fontsize=18)\nplt.xticks(x, ('OpenMP', 'TBB', 'Cpp-Taskflow', 'seq'), fontsize=14)\nplt.legend()\n\n\n# Fixing random state for reproducibility\nraw = [line.strip() for line in open(\"graph_algorithm.txt\")]\n\ngraph_sizes = []\nomp_runtimes = []\ntbb_runtimes = []\nctf_runtimes = []\n\n# extract the output data\ni = 0\nfor line in raw:\n token = line.split();\n assert(len(token) == 4)\n graph_sizes.append(int(token[0]))\n omp_runtimes.append(float(token[1]))\n tbb_runtimes.append(float(token[2]))\n ctf_runtimes.append(float(token[3]))\n i = i+1\n\nplt.subplot(224)\nplt.plot(graph_sizes, omp_runtimes, marker='.', label='OpenMP')\nplt.plot(graph_sizes, tbb_runtimes, marker='^', label='TBB')\nplt.plot(graph_sizes, ctf_runtimes, marker='x', label='Cpp-Taskflow')\nplt.title('Runtime (graph traversal)', fontsize=22)\nplt.xlabel('graph size (|V|+|E| ~ # tasks)', fontsize=18)\nplt.ylabel('cpu runtime (ms)', fontsize=16)\n#plt.xticks(np.arange(len(graph_sizes)), graph_sizes)\nplt.legend(fontsize=16)\n\n\n\n# Fixing random state for reproducibility\nraw = [line.strip() for line in open(\"matrix_operation.txt\")]\n\ngraph_sizes = []\nomp_runtimes = []\ntbb_runtimes = []\nctf_runtimes = []\n\n# extract the output data\ni = 0\nfor line in raw:\n token = line.split();\n assert(len(token) == 4)\n graph_sizes.append(int(token[0]))\n omp_runtimes.append(float(token[1]))\n tbb_runtimes.append(float(token[2]))\n ctf_runtimes.append(float(token[3]))\n i = i+1\n\nplt.subplot(223)\nplt.plot(graph_sizes, omp_runtimes, marker='.', label='OpenMP')\nplt.plot(graph_sizes, tbb_runtimes, marker='^', label='TBB')\nplt.plot(graph_sizes, ctf_runtimes, marker='x', label='Cpp-Taskflow')\nplt.title('Runtime (matrix wavefront)', fontsize=22)\nplt.xlabel('partition count (# tasks)', fontsize=18)\nplt.ylabel('cpu runtime (ms)', fontsize=16)\n#plt.xticks(np.arange(len(graph_sizes)), graph_sizes)\nplt.legend(fontsize=16)\n\n\nplt.show()\n\n\n\n"
] | [
[
"matplotlib.pyplot.legend",
"matplotlib.pyplot.title",
"numpy.arange",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.subplot",
"matplotlib.pyplot.bar",
"matplotlib.pyplot.subplots_adjust",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.xticks",
"matplotlib.pyplot.show",
"matplotlib.pyplot.ylabel"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
mwittgen/ndarray | [
"3ae5a4dcac545100296399fbe0019894f8356a89"
] | [
"tests/pybind11_test.py"
] | [
"# -*- python -*-\n#\n# Copyright (c) 2010-2012, Jim Bosch\n# All rights reserved.\n#\n# ndarray is distributed under a simple BSD-like license;\n# see the LICENSE file that should be present in the root\n# of the source distribution, or alternately available at:\n# https://github.com/ndarray/ndarray\n#\nimport numpy\nimport unittest\n\nimport pybind11_test_mod\n\n\nclass TestNumpyPybind11(unittest.TestCase):\n\n def testArray1(self):\n a1 = pybind11_test_mod.returnArray1()\n a2 = numpy.arange(6, dtype=float)\n self.assertTrue((a1 == a2).all())\n self.assertTrue(pybind11_test_mod.acceptArray1(a2))\n a3 = pybind11_test_mod.returnConstArray1()\n self.assertTrue((a1 == a3).all())\n self.assertFalse(a3.flags[\"WRITEABLE\"])\n\n def testArray3(self):\n a1 = pybind11_test_mod.returnArray3()\n a2 = numpy.arange(4*3*2, dtype=float).reshape(4, 3, 2)\n self.assertTrue((a1 == a2).all())\n self.assertTrue(pybind11_test_mod.acceptArray3(a2))\n a3 = pybind11_test_mod.returnConstArray3()\n self.assertTrue((a1 == a3).all())\n self.assertFalse(a3.flags[\"WRITEABLE\"])\n\n def testStrideHandling(self):\n # in NumPy 1.8+ 1- and 0-sized arrays can have arbitrary strides; we should\n # be able to handle those\n array = numpy.zeros(1, dtype=float)\n # just test that these don't throw\n pybind11_test_mod.acceptArray10(array)\n pybind11_test_mod.acceptArray10(array)\n array = numpy.zeros(0, dtype=float)\n pybind11_test_mod.acceptArray10(array)\n pybind11_test_mod.acceptArray10(array)\n # test that we gracefully fail when the strides are no multiples of the itemsize\n dtype = numpy.dtype([(\"f1\", numpy.float64), (\"f2\", numpy.int16)])\n table = numpy.zeros(3, dtype=dtype)\n self.assertRaises(TypeError, pybind11_test_mod.acceptArray10, table['f1'])\n\n def testNone(self):\n array = numpy.zeros(10, dtype=float)\n self.assertEqual(pybind11_test_mod.acceptNoneArray(array), 0)\n self.assertEqual(pybind11_test_mod.acceptNoneArray(None), 1)\n self.assertEqual(pybind11_test_mod.acceptNoneArray(), 1)\n\n def testNonNativeByteOrder(self):\n d1 = numpy.dtype(\"<f8\")\n d2 = numpy.dtype(\">f8\")\n nonnative = d2 if d1 == numpy.dtype(float) else d1\n a = numpy.zeros(5, dtype=nonnative)\n self.assertRaises(TypeError, pybind11_test_mod.acceptArray10, a)\n\n\nif __name__ == \"__main__\":\n unittest.main()\n"
] | [
[
"numpy.arange",
"numpy.zeros",
"numpy.dtype"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
Ceachi/Project-Self-Driving-Car-Advanced-Lane-Lines | [
"ab9b101b211fde7f2eb714d0ae6b47961d63f056"
] | [
"computer_vision_concepts/Curs Gradients and Color Spaces/direction_of_the_gradient.py"
] | [
"import numpy as np\nimport cv2\nimport matplotlib.pyplot as plt\nimport matplotlib.image as mpimg\nimport pickle\n\n\n# Read in an image\nimage = mpimg.imread('signs_vehicles_xygrad.png')\n\n# Define a function that applies Sobel x and y, \n# then computes the direction of the gradient\n# and applies a threshold.\ndef dir_threshold(img, sobel_kernel=3, thresh=(0, np.pi/2)):\n \n # Apply the following steps to img\n # 1) Convert to grayscale\n gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)\n # 2) Take the gradient in x and y separately and \n #Take the absolute value of the x and y gradients\n sobelx = np.absolute(cv2.Sobel(gray, cv2.CV_64F, 1, 0, ksize=sobel_kernel))\n sobely = np.absolute(cv2.Sobel(gray, cv2.CV_64F, 0, 1, ksize=sobel_kernel))\n # 4) Use np.arctan2(abs_sobely, abs_sobelx) to calculate the direction of the gradient \n #vezi ca la functia asta ai (y,x) not (x,y)\n gradientDirection = np.arctan2(sobely, sobelx)\n # 5) Create a binary mask where direction thresholds are met\n thresh_min = thresh[0]\n thresh_max = thresh[1]\n binary_output = np.zeros_like(gradientDirection)\n binary_output[(gradientDirection >= thresh_min) & (gradientDirection <= thresh_max)] = 1\n # 6) Return this mask as your binary_output image\n # binary_output = np.copy(img) # Remove this line\n return binary_output\n \n# Run the function\ndir_binary = dir_threshold(image, sobel_kernel=15, thresh=(0.7, 1.3))\n# Plot the result\nf, (ax1, ax2) = plt.subplots(1, 2, figsize=(24, 9))\nf.tight_layout()\nax1.imshow(image)\nax1.set_title('Original Image', fontsize=50)\nax2.imshow(dir_binary, cmap='gray')\nax2.set_title('Thresholded Grad. Dir.', fontsize=50)\nplt.subplots_adjust(left=0., right=1, top=0.9, bottom=0.)"
] | [
[
"matplotlib.pyplot.subplots",
"numpy.arctan2",
"matplotlib.image.imread",
"numpy.zeros_like",
"matplotlib.pyplot.subplots_adjust"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
ytfksw/blueoil | [
"a85516b7a64b8f49f25388d8f13349f8af72ea6d"
] | [
"blueoil/networks/classification/quantize_example.py"
] | [
"from functools import partial\n\nimport tensorflow as tf\n\nfrom blueoil.networks.classification.base import Base\nfrom blueoil.layers import batch_norm, conv2d\n\n\nclass SampleNetwork(Base):\n \"\"\"Sample network with simple layer.\"\"\"\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n\n self.activation = lambda x: tf.nn.leaky_relu(x, alpha=0.1, name=\"leaky_relu\")\n\n def base(self, images, is_training):\n assert self.data_format == \"NHWC\"\n channel_data_format = \"channels_last\"\n\n self.inputs = self.images = images\n\n with tf.compat.v1.variable_scope(\"block_1\"):\n conv = conv2d(\"conv\", self.inputs, filters=32, kernel_size=3,\n activation=None, use_bias=False, data_format=channel_data_format,\n kernel_initializer=tf.contrib.layers.variance_scaling_initializer())\n batch_normed = batch_norm(\"bn\", conv, is_training=is_training, decay=0.99, scale=True, center=True,\n data_format=self.data_format)\n self.block_1 = self.activation(batch_normed)\n\n self.block_last = conv2d(\"block_last\", self.block_1, filters=self.num_classes, kernel_size=1,\n activation=None, use_bias=True, is_debug=self.is_debug,\n kernel_initializer=tf.random_normal_initializer(mean=0.0, stddev=0.01),\n data_format=channel_data_format)\n\n h = self.block_last.get_shape()[1].value\n w = self.block_last.get_shape()[2].value\n self.pool = tf.layers.average_pooling2d(name='global_average_pool', inputs=self.block_last,\n pool_size=[h, w], padding='VALID', strides=1,\n data_format=channel_data_format)\n self.base_output = tf.reshape(self.pool, [-1, self.num_classes], name=\"pool_reshape\")\n\n return self.base_output\n\n\nclass SampleNetworkQuantize(SampleNetwork):\n \"\"\"Quantize Sample Network.\"\"\"\n\n def __init__(\n self,\n quantize_first_convolution=True,\n quantize_last_convolution=True,\n activation_quantizer=None,\n activation_quantizer_kwargs={},\n weight_quantizer=None,\n weight_quantizer_kwargs={},\n *args,\n **kwargs\n ):\n \"\"\"\n Args:\n quantize_first_convolution(bool): use quantization in first conv.\n quantize_last_convolution(bool): use quantization in last conv.\n weight_quantizer (callable): weight quantizer.\n weight_quantizer_kwargs(dict): Initialize kwargs for weight quantizer.\n activation_quantizer (callable): activation quantizer\n activation_quantizer_kwargs(dict): Initialize kwargs for activation quantizer.\n \"\"\"\n\n super().__init__(*args, **kwargs)\n\n self.quantize_first_convolution = quantize_first_convolution\n self.quantize_last_convolution = quantize_last_convolution\n\n assert callable(weight_quantizer)\n assert callable(activation_quantizer)\n\n self.weight_quantization = weight_quantizer(**weight_quantizer_kwargs)\n self.activation = activation_quantizer(**activation_quantizer_kwargs)\n\n @staticmethod\n def _quantized_variable_getter(\n weight_quantization,\n quantize_first_convolution,\n quantize_last_convolution,\n getter,\n name,\n *args,\n **kwargs):\n \"\"\"Get the quantized variables.\n\n Use if to choose or skip the target should be quantized.\n\n Args:\n weight_quantization: Callable object which quantize variable.\n quantize_first_convolution(bool): Use quantization in first conv.\n quantize_last_convolution(bool): Use quantization in last conv.\n getter: Default from tensorflow.\n name: Default from tensorflow.\n args: Args.\n kwargs: Kwargs.\n \"\"\"\n assert callable(weight_quantization)\n var = getter(name, *args, **kwargs)\n with tf.compat.v1.variable_scope(name):\n if \"kernel\" == var.op.name.split(\"/\")[-1]:\n\n if not quantize_first_convolution:\n if var.op.name.startswith(\"block_1/\"):\n return var\n\n if not quantize_last_convolution:\n if var.op.name.startswith(\"block_last/\"):\n return var\n\n # Apply weight quantize to variable whose last word of name is \"kernel\".\n quantized_kernel = weight_quantization(var)\n tf.compat.v1.summary.histogram(\"quantized_kernel\", quantized_kernel)\n return quantized_kernel\n\n return var\n\n def base(self, images, is_training):\n custom_getter = partial(\n self._quantized_variable_getter,\n self.weight_quantization,\n self.quantize_first_convolution,\n self.quantize_last_convolution,\n )\n with tf.compat.v1.variable_scope(\"\", custom_getter=custom_getter):\n return super().base(images, is_training)\n"
] | [
[
"tensorflow.contrib.layers.variance_scaling_initializer",
"tensorflow.reshape",
"tensorflow.layers.average_pooling2d",
"tensorflow.compat.v1.summary.histogram",
"tensorflow.random_normal_initializer",
"tensorflow.compat.v1.variable_scope",
"tensorflow.nn.leaky_relu"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.10"
]
}
] |
nttcs-ds/fastseq | [
"f1338f1125612df318c9d1f030a8457397ed05a6"
] | [
"examples/EL-attention/summarize.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 os\n\nimport torch\nimport argparse\n\n\nXSUM_KWARGS = dict(beam=6, lenpen=1.0, max_len_b=60, min_len=10, no_repeat_ngram_size=3)\nCNN_KWARGS = dict(beam=4, lenpen=2.0, max_len_b=140, min_len=55, no_repeat_ngram_size=3)\n\n\[email protected]_grad()\ndef generate(bart, infile, outfile=\"bart_hypo.txt\", bsz=32, n_obs=None, **eval_kwargs):\n count = 1\n\n with open(infile) as source, open(outfile, \"w\") as fout:\n sline = source.readline().strip()\n slines = [sline]\n for sline in source:\n if n_obs is not None and count > n_obs:\n break\n if count % bsz == 0:\n hypotheses_batch = bart.sample(slines, **eval_kwargs)\n for hypothesis in hypotheses_batch:\n fout.write(hypothesis + \"\\n\")\n fout.flush()\n slines = []\n\n slines.append(sline.strip())\n count += 1\n\n if slines != []:\n hypotheses_batch = bart.sample(slines, **eval_kwargs)\n for hypothesis in hypotheses_batch:\n fout.write(hypothesis + \"\\n\")\n fout.flush()\n\n\ndef main():\n \"\"\"\n Usage::\n python examples/bart/summarize.py \\\n --model-dir $HOME/bart.large.cnn \\\n --model-file model.pt \\\n --src $HOME/data-bin/cnn_dm/test.source\n \"\"\"\n parser = argparse.ArgumentParser()\n parser.add_argument(\n \"--model-dir\",\n required=True,\n type=str,\n default=\"bart.large.cnn/\",\n help=\"path containing model file and src_dict.txt\",\n )\n parser.add_argument(\n \"--model-file\",\n default=\"checkpoint_best.pt\",\n help=\"where in model_dir are weights saved\",\n )\n parser.add_argument(\n \"--src\", default=\"test.source\", help=\"text to summarize\", type=str\n )\n parser.add_argument(\n \"--out\", default=\"test.hypo\", help=\"where to save summaries\", type=str\n )\n parser.add_argument(\"--bsz\", default=32, help=\"where to save summaries\", type=int)\n parser.add_argument(\n \"--n\", default=None, help=\"how many examples to summarize\", type=int\n )\n parser.add_argument(\n \"--xsum-kwargs\",\n action=\"store_true\",\n default=False,\n help=\"if true use XSUM_KWARGS else CNN_KWARGS\",\n )\n # Fastseq related setting\n parser.add_argument('--use-fastseq', action='store_true',\n help='Use fastseq optimization ? ')\n parser.add_argument('--use-el-attn', action='store_true',\n help='Use Efficient Lossless Attention optimization ? ')\n args = parser.parse_args()\n \n # Check Fastseq related setting\n os.environ['USE_EL_ATTN'] = '1' if args.use_el_attn else '0'\n if args.use_el_attn or args.use_fastseq:\n import fastseq\n\n from fairseq.models.bart import BARTModel\n\n eval_kwargs = XSUM_KWARGS if args.xsum_kwargs else CNN_KWARGS\n if args.model_dir == \"pytorch/fairseq\":\n bart = torch.hub.load(\"pytorch/fairseq\", args.model_file)\n else:\n bart = BARTModel.from_pretrained(\n args.model_dir,\n checkpoint_file=args.model_file,\n data_name_or_path=args.model_dir,\n )\n bart = bart.eval()\n if torch.cuda.is_available():\n bart = bart.cuda().half()\n\n # TODO make this step automatic\n if args.use_el_attn:\n bart.model.transpose_enc_dec_kv_proj()\n bart.model.make_generation_fast_(beamable_mm_beam_size=eval_kwargs['beam'])\n\n generate(\n bart, args.src, bsz=args.bsz, n_obs=args.n, outfile=args.out, **eval_kwargs\n )\n\n\nif __name__ == \"__main__\":\n main()\n\n"
] | [
[
"torch.hub.load",
"torch.no_grad",
"torch.cuda.is_available"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
mi-erasmusmc/Sard | [
"d8228a7c49e2e6f98fbd16d4531cb3fc4b505590"
] | [
"catboost_analysis.py"
] | [
"\"\"\"\nTrain a catboost model with grid search\n\"\"\"\nimport json\nimport pathlib\n\nimport catboost\nimport numpy as np\nfrom sklearn.compose import ColumnTransformer\nfrom sklearn.metrics import roc_auc_score, precision_recall_curve, auc\nfrom sklearn.model_selection import RandomizedSearchCV\nfrom sklearn.pipeline import Pipeline\nfrom sklearn.preprocessing import MaxAbsScaler\n\nfrom utils.data_utils import add_age_gender\nfrom utils.data_utils import window_data_sorted\nfrom utils.utils import load_data, NpEncoder\n\nif __name__ == '__main__':\n \"\"\"\n This script fits a Catboost model. First it uses randomised search to select hyperparameters. Then it takes the best\n estimator and tests it on the test data\n \n \"\"\"\n task = 'mortality'\n data_folder = pathlib.Path(f'/data/home/efridgeirsson/projects/dementia/data/sequence_{task}/')\n\n plp_data = load_data(data_folder=data_folder, name='python_data')\n\n results_directory = pathlib.Path.cwd().joinpath('SavedModels', f'{task}', 'catboost', 'best_params')\n if not results_directory.exists():\n results_directory.mkdir(parents=True)\n population = plp_data[\"population\"]\n indices = dict()\n indices['test'] = np.argwhere(population['index'].values == -1.0).squeeze()\n indices['train'] = np.argwhere(population['index'].values > 0).squeeze()\n\n window_lengths = (30, 180, 365)\n feature_matrix_counts, windowed_feature_names = window_data_sorted(\n window_lengths=list(window_lengths),\n feature_matrix=plp_data['data'],\n all_feature_names=plp_data['feature_names'])\n\n feature_matrix_counts = feature_matrix_counts.T\n\n feature_matrix_counts.data = np.clip(feature_matrix_counts.data, 0, 1) # counts to binary\n\n feature_matrix_counts, windowed_feature_names = add_age_gender(feature_matrix_counts,\n plp_data['nonTemporalData'], windowed_feature_names,\n age_normalized=False)\n outcomes = plp_data['outcomes']\n X = feature_matrix_counts\n y = outcomes\n X_train = X[indices['train']]\n X_test = X[indices['test']]\n y_train = y[indices['train']]\n y_test = y[indices['test']]\n\n # custom cv generator to get exactly the same cv split as in PLP\n cv_iterator = []\n indexes = population[population['index'] > 0]['index'].unique()\n for i in indexes:\n val_idx = i\n val_indices = population[population['index'] == val_idx]['rowIdPython'].values - 1\n train_idx = indexes[indexes != i]\n train_indices = population[population['index'].isin(train_idx)]['rowIdPython'].values - 1\n cv_iterator.append((train_indices, val_indices))\n\n train_indices = population[population['index'].isin([1, 2])]['rowIdPython'].values - 1\n val_indices = population[population['index'] == 3]['rowIdPython'].values - 1\n X_train, y_train = feature_matrix_counts[train_indices], outcomes[train_indices]\n X_val, y_val = feature_matrix_counts[val_indices], outcomes[val_indices]\n\n # train the regression model over several choices of regularization parameter\n scaler = MaxAbsScaler()\n params = {'catboost__depth': list(np.arange(1, 11)),\n 'catboost__loss_function': ['Logloss'],\n 'catboost__iterations': [100, 250, 500, 1000, 2000, 3000, 5000, 10000],\n 'catboost__learning_rate': [0.001, 0.01, 0.03, 0.1, 0.2, 0.3],\n 'catboost__l2_leaf_reg': [1, 3, 5, 10, 100],\n 'catboost__border_count': [5, 10, 20, 32, 50, 100, 200]}\n\n model = catboost.CatBoostClassifier(task_type='GPU', devices='0', auto_class_weights='Balanced',\n logging_level='Silent', early_stopping_rounds=30)\n\n # only normalize continuous features\n ct = ColumnTransformer([('scaler', MaxAbsScaler(), slice(-4, -1))], remainder='passthrough')\n pipeline = Pipeline([('scaler', ct), ('catboost', model)])\n\n grid_search = RandomizedSearchCV(estimator=pipeline, param_distributions=params, scoring='roc_auc', refit=True,\n cv=cv_iterator, n_jobs=1, verbose=10, random_state=42, n_iter=100)\n grid_search.fit(X, y)\n\n best_estimator = grid_search.best_estimator_\n\n best_params = grid_search.best_params_\n\n with open(results_directory.joinpath('catboost_best_params.json'), 'w+') as f:\n json.dump(best_params, f, cls=NpEncoder)\n best_parameters = {key.split('__')[1]: value for (key, value) in best_params.items()}\n best_model = catboost.CatBoostClassifier(task_type='GPU', auto_class_weights='Balanced',\n **best_parameters)\n\n X_train = ct.fit_transform(X_train)\n X_val = ct.transform(X_val)\n\n train_data = catboost.Pool(data=X_train.astype(np.float32), label=y_train)\n eval_data = catboost.Pool(data=X_val.astype(np.float32), label=y_val.values)\n best_model.fit(train_data, eval_set=eval_data, early_stopping_rounds=30)\n\n X_test = ct.transform(X_test)\n predictions_test = best_model.predict_proba(X_test)[:, 1]\n\n roc_auc = roc_auc_score(y_test, predictions_test)\n precision, recall, threshold = precision_recall_curve(y_test, predictions_test)\n auprc = auc(recall, precision)\n\n np.save(f'./results/{task}/catboost_predictions.npy', predictions_test)\n\n all_predictions = best_model.predict_proba(ct.transform(X))[:, 1]\n\n np.save(f'./data/{task}/catboost_predictions.npy', all_predictions)\n"
] | [
[
"sklearn.metrics.roc_auc_score",
"sklearn.model_selection.RandomizedSearchCV",
"numpy.clip",
"numpy.arange",
"sklearn.preprocessing.MaxAbsScaler",
"sklearn.pipeline.Pipeline",
"sklearn.metrics.precision_recall_curve",
"numpy.save",
"numpy.argwhere",
"sklearn.metrics.auc"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
alessiamarcolini/digital-pathology-classification | [
"ea1f3f06994b8ae6b1aeae4552d3784e97cb6913"
] | [
"preprocessing/labels.py"
] | [
"import pandas as pd\n\n\ndef reverse_dict(dictionary):\n \"\"\"Reverse a dictionary.\n\n Keys become values and vice versa.\n\n Parameters\n ----------\n dictionary : dict\n Dictionary to reverse\n\n Returns\n -------\n dict\n Reversed dictionary\n\n Raises\n ------\n TypeError\n If there is a value which is unhashable, therefore cannot be a dictionary key.\n \"\"\"\n return {i: value for value, i in dictionary.items()}\n\n\ndef encode_label(dataframe, column, column_encoded, encoding_dictionary=None):\n \"\"\"Encode ``column`` label in ``dataframe`` with ``encoding_dictionary`` provided.\n\n Parameters\n ----------\n dataframe : pandas.DataFrame\n The DataFrame to read and to write to.\n column : str\n Name of the column to encode\n column_encoded : str\n Name of the encoded column, which will be added to ``dataframe``.\n encoding_dictionary : dict, optional\n Dictionary used to encode values, where the keys are the original values and the\n values are the encoded values. If None (which is the default) each categorical\n value will be mapped to an integer (0 to n_values - 1).\n\n Returns\n -------\n pandas.DataFrame\n A copy of ``dataframe`` with the new column ``column_encoded``.\n\n dict\n Encoding dict reversed\n\n Raises\n ------\n ValueError\n If the column ``column`` does not exist in ``dataframe``.\n ValueError\n If the ``encoding_dict`` is missing some values to encode (keys).\n \"\"\"\n\n if column not in dataframe.columns:\n raise ValueError(f\"Column {column} does not exist in dataframe\")\n\n if encoding_dictionary:\n values_to_encode = set(dataframe[column].unique())\n\n if values_to_encode > set(encoding_dictionary.keys()):\n missing_values = values_to_encode - set(encoding_dictionary.keys())\n raise ValueError(\n \"Encoding dictionary is missing some keys: \", \", \".join(missing_values)\n )\n\n dataframe_encoded = pd.DataFrame(dataframe) # make a copy\n if not encoding_dictionary:\n encoding_dictionary = {\n value: i for i, value in enumerate(dataframe[column].unique())\n }\n dataframe_encoded[column_encoded] = dataframe_encoded[column].apply(\n lambda x: encoding_dictionary[x]\n )\n\n reversed_encoding_dict = reverse_dict(encoding_dictionary)\n\n return dataframe_encoded, reversed_encoding_dict\n"
] | [
[
"pandas.DataFrame"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [
"0.23",
"0.21",
"2.0",
"1.4",
"0.19",
"1.1",
"1.5",
"1.2",
"0.24",
"0.20",
"1.0",
"0.25",
"1.3"
],
"scipy": [],
"tensorflow": []
}
] |
zutn/Simple-Catchments-Hesse | [
"da9a8ba5b535369843e33b24e9cad7afb65449a9"
] | [
"preprocessing/cleaned_data/create_cleaned_data_table.py"
] | [
"import pandas as pd\nimport os\nhome = os.path.dirname(__file__) \n\ndef get_table_dict(calc_water_year=True, et_corrected=True):\n \"\"\"\n Loads the csv data and return a dict with catchment id as key and a dataframe as value\n \"\"\"\n \n matQ = pd.read_csv(home + os.sep + 'dis_mm_1991_2018.csv', delimiter=';', parse_dates=[0], index_col=0, dayfirst=True)\n if et_corrected:\n matE = pd.read_csv(home + os.sep + 'et_mm_1991_2018_corrected.csv', delimiter=';', parse_dates=[0], index_col=0, dayfirst=True)\n else:\n matE = pd.read_csv(home + os.sep + 'et_mm_1991_2018_uncorrected.csv', delimiter=';', parse_dates=[0], index_col=0, dayfirst=True)\n matP = pd.read_csv(home + os.sep + 'prec_mm_1991_2018.csv', delimiter=';', parse_dates=[0], index_col=0, dayfirst=True)\n matdS = pd.read_csv(home + os.sep + 'dS_mm_1991_2018.csv', delimiter=';', parse_dates=[0], index_col=0, dayfirst=True)\n\n dataframes = {}\n\n for catch in matE.columns:\n df = pd.DataFrame()\n df['Q'] = matQ[catch]\n df['E'] = matE[catch]\n df['P'] = matP[catch]\n df[\"dS\"] = matdS[catch]\n if calc_water_year:\n water_year(df)\n dataframes[int(catch)] = df\n\n return dataframes\n\n\ndef water_year(df:pd.DataFrame):\n \"\"\"\n Adds a column to a dataframe (with datetime index) with the hydrological year \n , hydrological day and hydrological month\n \"\"\"\n df[\"water_year\"] = (df.index + pd.DateOffset(months=2)).year\n days_water_year = []\n for i, (year, year_df) in enumerate(df.groupby(\"water_year\")):\n if i == 0:\n days_of_last_year = 30 + 31 # November plus December\n days_water_year += list(range(1 + days_of_last_year, year_df.shape[0]+1 + days_of_last_year))\n else:\n days_water_year += list(range(1, year_df.shape[0]+1))\n df[\"day_of_water_year\"] = days_water_year\n def shift_month(month):\n if month == 11:\n return 1\n elif month == 12:\n return 2\n else:\n return month + 2\n df[\"month_of_water_year\"] = list(map(shift_month, list(df.index.month)))\n\n\ndef translate_catchment_attributes(attributes):\n \"\"\"\n Translates the catchment attributes from their German names to English.\n \"\"\"\n attributes.rename(columns={\"dominating_soil_type_bk500\":\"Soil Type [/]\", \n \"leitercharackter_huek250\":\"Aquifer Conductivity [/]\",\n \"gesteinsart_huek250\":\"Geology Type [/]\",\n \"soil_texture_boart_1000\": \"Soil Texture [/]\",\n \"durchlässigkeit_huek250\":\"Permeability [/]\",\n \"land_use_corine\":\"Land Use [/]\",\n \"area_m2_watershed\":\"Area [km²]\",\n \"grundwasserneubildung_gwn_1000\": \"Ground Water Recharge [mm]\",\n \"greundigkeit_physgru_1000\":\"Soil Depth [m]\",\n \"slope_mean_dem_40\":\"Slope [/]\",\n \"elongation_ratio\":\"Elongation Ratio [/]\",\n \"et_mean\":\"Act. Evapotranspiration [mm]\",\n \"dis_mean\":\"Discharge [mm]\",\n \"prec_mean\":\"Precipitation [mm]\",\n \"runoff_ratio\":\"Runoff-Ratio [/]\"},\n inplace=True)\n attributes[\"Soil Type [/]\"].replace({'Dystric_Cambisols':\"DC\",\n 'Haplic_Luvisols_/_Eutric_Podzoluvisols_/_Stagnic_Gleysols_':\"HL/EP/SG\",\n 'Eutric_Cambisols' :\"EC\",\n 'Spodic_Cambisols' :\"SC\",\n 'Eutric_Cambisols_/_Stagnic_Gleysols':\"EC/SG\", \n 'Dystric_Cambisols_':\"DC\",\n 'Spodic_Cambisol_':\"SC\", \n 'Eutric_Cambisols_/_Stagnic_Gleysols_':\"EC/SG\"}, inplace=True)\n attributes[\"Aquifer Conductivity [/]\"].replace({\n 'Grundwasser-Geringleiter': \"low\", \n 'Grundwasser-Leiter': \"normal\",\n 'Grundwasser-Leiter/Geringleiter':\"normal/low\"}, inplace=True)\n attributes[\"Geology Type [/]\"].replace({\n 'Sediment' : \"sedimentary\", \n 'Magmatit': \"igneous\" },inplace=True)\n attributes[\"Soil Texture [/]\"].replace({\n 'Lehmsande (ls)': \"loamy sand\", \n 'Tonschluffe (tu)':\"clay silt\", \n 'Sandlehme (sl)': \"sandy loam\", \n 'Schlufftone (ut)': \"silty clay\", \n 'Lehmschluffe (lu)': \"loamy silt\"},inplace=True)\n attributes[\"Permeability [/]\"].replace({\n 'gering (>1E-7 - 1E-5)': \"low\", \n 'mittel bis maessig (>1E-5 - 1E-3)':\"mid/moderate\",\n 'maessig (>1E-5 - 1E-4)':\"moderate\", \n 'gering bis aeußerst gering (<1E-5)':\"low/very low\",\n 'maessig bis gering (>1E-6 - 1E-4)':\"moderate/low\", \n 'sehr gering (>1E-9 - 1E-7)':\"very low\",\n 'stark variabel':\"variable\", \n 'mittel (>1E-4 - 1E-3)':\"mid\"}, inplace=True)\n return attributes\n\n\ndef translate_year_attributes(years):\n years.rename(columns={\n 'et_mm_1991_2018_corrected': \"Act. Evapotranspiration [mm]\", \n 'prec_mm_1991_2018': \"Precipitation [mm]\", \n 'most_rain_one_day': \"Max Prec. Day [mm]\", \n 'most_rain_one_month': \"Max Prec. Month [mm]\", \n 'rainfall_seasonality' : \"Rainfall Seasonality [/]\", \n 'snow_fraction': \"Snow Fraction [%]\",\n 'aridity':\"Aridity [/]\"},inplace=True)\n return years\n \n\n\ndef get_attributes_catchments():\n attributes = pd.read_csv(home + os.sep + 'cleaned_catchment_attributes_num.csv', delimiter=';', index_col=0)\n attributes.drop([\"gauge\"], inplace=True,axis=1)\n\n attributes[\"dominating_soil_type_bk500\"] = attributes[\"dominating_soil_type_bk500\"].str.replace(\" \", \"_\")\n attributes[\"area_m2_watershed\"] = attributes[\"area_m2_watershed\"] / 1000000\n attributes = translate_catchment_attributes(attributes)\n return attributes\n\ndef get_attributes_years():\n years = pd.read_csv(home + os.sep + 'cleaned_year_attributes.csv', delimiter=';', index_col=0)\n years = translate_year_attributes(years)\n return years\n\nif __name__ == \"__main__\":\n #dataframes = get_table_dict(calc_water_year=True)\n # attributes = get_attributes_catchments()\n years = get_attributes_years()"
] | [
[
"pandas.read_csv",
"pandas.DateOffset",
"pandas.DataFrame"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [
"0.23",
"0.21",
"2.0",
"1.4",
"0.19",
"1.1",
"1.5",
"1.2",
"0.24",
"0.20",
"1.0",
"0.25",
"1.3"
],
"scipy": [],
"tensorflow": []
}
] |
ZwwWayne/mmclassification | [
"2ccc55ce4f783ca34892fe7d91f247d18906a994"
] | [
"mmcls/core/utils/dist_utils.py"
] | [
"from collections import OrderedDict\n\nimport torch.distributed as dist\nfrom mmcv.runner import OptimizerHook\nfrom torch._utils import (_flatten_dense_tensors, _take_tensors,\n _unflatten_dense_tensors)\n\n\ndef _allreduce_coalesced(tensors, world_size, bucket_size_mb=-1):\n if bucket_size_mb > 0:\n bucket_size_bytes = bucket_size_mb * 1024 * 1024\n buckets = _take_tensors(tensors, bucket_size_bytes)\n else:\n buckets = OrderedDict()\n for tensor in tensors:\n tp = tensor.type()\n if tp not in buckets:\n buckets[tp] = []\n buckets[tp].append(tensor)\n buckets = buckets.values()\n\n for bucket in buckets:\n flat_tensors = _flatten_dense_tensors(bucket)\n dist.all_reduce(flat_tensors)\n flat_tensors.div_(world_size)\n for tensor, synced in zip(\n bucket, _unflatten_dense_tensors(flat_tensors, bucket)):\n tensor.copy_(synced)\n\n\ndef allreduce_grads(params, coalesce=True, bucket_size_mb=-1):\n grads = [\n param.grad.data for param in params\n if param.requires_grad and param.grad is not None\n ]\n world_size = dist.get_world_size()\n if coalesce:\n _allreduce_coalesced(grads, world_size, bucket_size_mb)\n else:\n for tensor in grads:\n dist.all_reduce(tensor.div_(world_size))\n\n\nclass DistOptimizerHook(OptimizerHook):\n\n def __init__(self, grad_clip=None, coalesce=True, bucket_size_mb=-1):\n self.grad_clip = grad_clip\n self.coalesce = coalesce\n self.bucket_size_mb = bucket_size_mb\n\n def after_train_iter(self, runner):\n runner.optimizer.zero_grad()\n runner.outputs['loss'].backward()\n if self.grad_clip is not None:\n self.clip_grads(runner.model.parameters())\n runner.optimizer.step()\n"
] | [
[
"torch._utils._flatten_dense_tensors",
"torch._utils._unflatten_dense_tensors",
"torch.distributed.get_world_size",
"torch.distributed.all_reduce",
"torch._utils._take_tensors"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
adamoses/slab_fitter | [
"b60f69ddb0abffa489ebf13c16dd6b4b00beed97"
] | [
"helpers.py"
] | [
"import numpy as np\nfrom astroquery.hitran import Hitran\nfrom astropy import units as un\nfrom astropy.constants import c, k_B, h, u\nfrom molmass import Formula\nimport pdb as pdb\nimport pickle as pickle\n\ndef line_ids_from_flux_calculator(flux_calculator_output, line_id_dict):\n line_id_list=[]\n for i,myrow in enumerate(flux_calculator_output):\n line_id_key=(str(myrow['molec_id'])+str(myrow['local_iso_id']) + str(myrow['Vp_HITRAN'])+str(myrow['Vpp_HITRAN'])+ str(myrow['Qp_HITRAN'])+str(myrow['Qpp_HITRAN'])).replace(\" \",\"\")\n line_id_list.append(line_id_dict[line_id_key])\n \n line_id_arr=np.array(line_id_list)\n\n return line_id_arr\n\ndef line_ids_from_hitran(hitran_output):\n line_id_dict=pickle.load(open('line_id_dict.p','rb'))\n\n line_id_list=[]\n for i,myrow in enumerate(hitran_output):\n line_id_key=(str(myrow['molec_id'])+str(myrow['local_iso_id']) + str(myrow['Vp'])+str(myrow['Vpp'])+ str(myrow['Qp'])+str(myrow['Qpp'])).replace(\" \",\"\")\n line_id_list.append(line_id_dict[line_id_key])\n\n line_id_arr=np.array(line_id_list)\n\n return line_id_arr\n\n\ndef compute_thermal_velocity(molecule_name, temp):\n '''\n Compute the thermal velocity given a molecule name and temperature\n\n Parameters\n ---------\n molecule_name: string\n Molecule name (e.g., 'CO', 'H2O')\n temp : float\n Temperature at which to compute thermal velocity\n\n Returns\n -------\n v_thermal : float\n Thermal velocity (m/s)\n '''\n\n f=Formula(molecule_name)\n mu=f.isotope.mass*u.value #kg\n\n return np.sqrt(k_B.value*temp/mu) #m/s\n\ndef markgauss(x,mean=0, sigma=1., area=1):\n '''\n Compute a Gaussian function\n\n Parameters\n ----------\n x : float\n x values at which to calculate the Gaussian\n mean : float, optional\n mean of Gaussian\n sigma : float, optional\n standard deviation of Gaussian\n area : float, optional\n area of Gaussian curve\n\n Returns\n ---------\n Gaussian function evaluated at input x values\n\n '''\n\n norm=area\n u = ( (x-mean)/np.abs(sigma) )**2\n norm = norm / (np.sqrt(2. * np.pi)*sigma)\n f=norm*np.exp(-0.5*u)\n\n return f\n\ndef sigma_to_fwhm(sigma):\n '''\n Convert sigma to fwhm\n\n Parameters\n ----------\n sigma : float\n sigma of Gaussian distribution\n\n Returns\n ----------\n fwhm : float\n Full Width at Half Maximum of Gaussian distribution\n ''' \n return sigma*(2.*np.sqrt(2.*np.log(2.)))\n\ndef fwhm_to_sigma(fwhm):\n '''\n Convert fwhm to sigma\n\n Parameters\n ----------\n fwhm : float\n Full Width at Half Maximum of Gaussian distribution\n\n Returns\n ----------\n sigma : float\n sigma of Gaussian distribution\n ''' \n\n return fwhm/(2.*np.sqrt(2.*np.log(2.)))\n\ndef wn_to_k(wn):\n ''' \n Convert wavenumber to Kelvin\n\n Parameters\n ----------\n wn : AstroPy quantity\n Wavenumber including units\n\n Returns\n ---------\n energy : AstroPy quantity\n Energy of photon with given wavenumber\n\n ''' \n return wn.si*h*c/k_B\n\ndef extract_hitran_data(molecule_name, wavemin, wavemax, isotopologue_number=1, eupmax=None, aupmin=None,swmin=None):\n ''' \n Extract data from HITRAN \n Primarily makes use of astroquery.hitran, with some added functionality specific to common IR spectral applications\n Parameters \n ---------- \n molecule_name : string\n String identifier for molecule, for example, 'CO', or 'H2O'\n wavemin: float\n Minimum wavelength of extracted lines (in microns)\n wavemax: float\n Maximum wavelength of extracted lines (in microns) \n isotopologue_number : float, optional\n Number representing isotopologue (1=most common, 2=next most common, etc.)\n eupmax : float, optional\n Maximum extracted upper level energy (in Kelvin)\n aupmin : float, optional\n Minimum extracted Einstein A coefficient\n swmin : float, optional\n Minimum extracted line strength\n Returns\n ------- \n hitran_data : astropy table\n Extracted data\n '''\n\n #Convert molecule name to number\n M = get_molecule_identifier(molecule_name)\n\n #Convert inputs to astroquery formats\n min_wavenumber = 1.e4/wavemax\n max_wavenumber = 1.e4/wavemin\n\n #Extract hitran data using astroquery\n tbl = Hitran.query_lines(molecule_number=M,isotopologue_number=isotopologue_number,min_frequency=min_wavenumber / un.cm,max_frequency=max_wavenumber / un.cm)\n\n #Do some desired bookkeeping, and add some helpful columns\n tbl.rename_column('nu','wn')\n tbl['nu']=tbl['wn']*c.cgs.value #Now actually frequency of transition\n tbl['eup_k']=(wn_to_k((tbl['wn']+tbl['elower'])/un.cm)).value\n tbl['wave']=1.e4/tbl['wn'] #Wavelength of transition, in microns\n tbl.rename_column('global_upper_quanta','Vp')\n tbl.rename_column('global_lower_quanta','Vpp')\n tbl.rename_column('local_upper_quanta','Qp')\n tbl.rename_column('local_lower_quanta','Qpp')\n\n #Extract desired portion of dataset\n ebool = np.full(np.size(tbl), True, dtype=bool) #default to True\n abool = np.full(np.size(tbl), True, dtype=bool) #default to True\n swbool = np.full(np.size(tbl), True, dtype=bool) #default to True\n #Upper level energy\n if(eupmax is not None):\n ebool = tbl['eup_k'] < eupmax\n #Upper level A coeff\n if(aupmin is not None):\n abool = tbl['a'] > aupmin\n #Line strength\n if(swmin is not None):\n swbool = tbl['sw'] > swmin\n #Combine\n extractbool = (abool & ebool & swbool)\n hitran_data=tbl[extractbool]\n\n #Return astropy table\n return hitran_data\n\ndef get_global_identifier(molecule_name,isotopologue_number=1):\n ''' \n For a given input molecular formula, return the corresponding HITRAN *global* identifier number.\n For more info, see https://hitran.org/docs/iso-meta/ \n \n Parameters \n ---------- \n molecular_formula : str \n The string describing the molecule. \n isotopologue_number : int, optional\n The isotopologue number, from most to least common. \n \n Returns \n ------- \n G : int \n The HITRAN global identifier number. \n '''\n\n mol_isot_code=molecule_name+'_'+str(isotopologue_number)\n\n trans = { 'H2O_1':1, 'H2O_2':2, 'H2O_3':3, 'H2O_4':4, 'H2O_5':5, 'H2O_6':6, 'H2O_7':129,\n 'CO2_1':7,'CO2_2':8,'CO2_3':9,'CO2_4':10,'CO2_5':11,'CO2_6':12,'CO2_7':13,'CO2_8':14,\n 'CO2_9':121,'CO2_10':15,'CO2_11':120,'CO2_12':122,\n 'O3_1':16,'O3_2':17,'O3_3':18,'O3_4':19,'O3_5':20,\n 'N2O_1':21,'N2O_2':22,'N2O_3':23,'N2O_4':24,'N2O_5':25,\n 'CO_1':26,'CO_2':27,'CO_3':28,'CO_4':29,'CO_5':30,'CO_6':31,\n 'CH4_1':32,'CH4_2':33,'CH4_3':34,'CH4_4':35,\n 'O2_1':36,'O2_2':37,'O2_3':38,\n 'NO_1':39,'NO_2':40,'NO_3':41,\n 'SO2_1':42,'SO2_2':43,\n 'NO2_1':44,\n 'NH3_1':45,'NH3_2':46,\n 'HNO3_1':47,'HNO3_2':117,\n 'OH_1':48,'OH_2':49,'OH_3':50,\n 'HF_1':51,'HF_2':110,\n 'HCl_1':52,'HCl_2':53,'HCl_3':107,'HCl_4':108,\n 'HBr_1':54,'HBr_2':55,'HBr_3':111,'HBr_4':112,\n 'HI_1':56,'HI_2':113,\n 'ClO_1':57,'ClO_2':58,\n 'OCS_1':59,'OCS_2':60,'OCS_3':61,'OCS_4':62,'OCS_5':63,\n 'H2CO_1':64,'H2CO_2':65,'H2CO_3':66,\n 'HOCl_1':67,'HOCl_2':68,\n 'N2_1':69,'N2_2':118,\n 'HCN_1':70,'HCN_2':71,'HCN_3':72,\n 'CH3Cl_1':73,'CH3CL_2':74,\n 'H2O2_1':75,\n 'C2H2_1':76,'C2H2_2':77,'C2H2_3':105,\n 'C2H6_1':78,'C2H6_2':106,\n 'PH3_1':79,\n 'COF2_1':80,'COF2_2':119,\n 'SF6_1':126,\n 'H2S_1':81,'H2S_2':82,'H2S_3':83,\n 'HCOOH_1':84,\n 'HO2_1':85,\n 'O_1':86,\n 'ClONO2_1':127,'ClONO2_2':128,\n 'NO+_1':87,\n 'HOBr_1':88,'HOBr_2':89,\n 'C2H4_1':90,'C2H4_2':91,\n 'CH3OH_1':92,\n 'CH3Br_1':93,'CH3Br_2':94,\n 'CH3CN_1':95,\n 'CF4_1':96,\n 'C4H2_1':116,\n 'HC3N_1':109,\n 'H2_1':103,'H2_2':115,\n 'CS_1':97,'CS_2':98,'CS_3':99,'CS_4':100,\n 'SO3_1':114,\n 'C2N2_1':123,\n 'COCl2_1':124,'COCl2_2':125}\n \n return trans[mol_isot_code]\n\n#Code from Nathan Hagen\n#https://github.com/nzhagen/hitran\ndef translate_molecule_identifier(M):\n ''' \n For a given input molecule identifier number, return the corresponding molecular formula. \n \n Parameters \n ---------- \n M : int \n The HITRAN molecule identifier number. \n \n Returns \n ------- \n molecular_formula : str \n The string describing the molecule. \n '''\n\n trans = { '1':'H2O', '2':'CO2', '3':'O3', '4':'N2O', '5':'CO', '6':'CH4', '7':'O2', '8':'NO',\n '9':'SO2', '10':'NO2', '11':'NH3', '12':'HNO3', '13':'OH', '14':'HF', '15':'HCl', '16':'HBr',\n '17':'HI', '18':'ClO', '19':'OCS', '20':'H2CO', '21':'HOCl', '22':'N2', '23':'HCN', '24':'CH3Cl',\n '25':'H2O2', '26':'C2H2', '27':'C2H6', '28':'PH3', '29':'COF2', '30':'SF6', '31':'H2S', '32':'HCOOH',\n '33':'HO2', '34':'O', '35':'ClONO2', '36':'NO+', '37':'HOBr', '38':'C2H4', '39':'CH3OH', '40':'CH3Br',\n '41':'CH3CN', '42':'CF4', '43':'C4H2', '44':'HC3N', '45':'H2', '46':'CS', '47':'SO3'}\n return(trans[str(M)])\n\n#Code from Nathan Hagen\n#https://github.com/nzhagen/hitran\ndef get_molecule_identifier(molecule_name):\n ''' \n For a given input molecular formula, return the corresponding HITRAN molecule identifier number. \n \n Parameters \n ---------- \n molecular_formula : str \n The string describing the molecule. \n \n Returns \n ------- \n M : int \n The HITRAN molecular identifier number. \n '''\n\n trans = { '1':'H2O', '2':'CO2', '3':'O3', '4':'N2O', '5':'CO', '6':'CH4', '7':'O2', '8':'NO',\n '9':'SO2', '10':'NO2', '11':'NH3', '12':'HNO3', '13':'OH', '14':'HF', '15':'HCl', '16':'HBr',\n '17':'HI', '18':'ClO', '19':'OCS', '20':'H2CO', '21':'HOCl', '22':'N2', '23':'HCN', '24':'CH3Cl',\n '25':'H2O2', '26':'C2H2', '27':'C2H6', '28':'PH3', '29':'COF2', '30':'SF6', '31':'H2S', '32':'HCOOH',\n '33':'HO2', '34':'O', '35':'ClONO2', '36':'NO+', '37':'HOBr', '38':'C2H4', '39':'CH3OH', '40':'CH3Br',\n '41':'CH3CN', '42':'CF4', '43':'C4H2', '44':'HC3N', '45':'H2', '46':'CS', '47':'SO3'}\n ## Invert the dictionary. \n trans = {v:k for k,v in trans.items()}\n return(int(trans[molecule_name]))\n"
] | [
[
"numpy.log",
"numpy.abs",
"numpy.sqrt",
"numpy.size",
"numpy.array",
"numpy.exp"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
shuo0108/attention-guided-sparsity | [
"be715ff6cbf1d8248a1fc86e5fd10b93db5e3b59"
] | [
"python/train.py"
] | [
"import functools\nimport argparse\nimport os\nimport sys\nimport tensorflow as tf\nfrom tensorflow.examples.tutorials.mnist import input_data\nimport losses\nimport sparsity_ops\nFLAGS = None\n\ndef train(FLAGS):\n\n # Import MNIST data\n mnist = input_data.read_data_sets(FLAGS.data_dir,\n fake_data=FLAGS.fake_data)\n\n sess = tf.InteractiveSession()\n # Create a multilayer model.\n\n # Input placeholders\n with tf.name_scope('input'):\n x = tf.placeholder(tf.float32, [None, 784], name='x-input')\n y_ = tf.placeholder(tf.int64, [None], name='y-input')\n\n with tf.name_scope('input_reshape'):\n image_shaped_input = tf.reshape(x, [-1, 28, 28, 1])\n tf.summary.image('input', image_shaped_input, 10)\n\n with tf.name_scope('dropout'):\n keep_prob = tf.placeholder(tf.float32)\n tf.summary.scalar('dropout_keep_probability', keep_prob)\n\n with tf.name_scope('training_status'):\n training_status = tf.placeholder(tf.bool)\n\n # We can't initialize these variables to 0 - the network will get stuck.\n def weight_variable(shape):\n \"\"\"Create a weight variable with appropriate initialization.\"\"\"\n initial = tf.truncated_normal(shape, stddev=0.1)\n return tf.Variable(initial)\n\n def bias_variable(shape):\n \"\"\"Create a bias variable with appropriate initialization.\"\"\"\n initial = tf.constant(0.1, shape=shape)\n return tf.Variable(initial)\n\n def variable_summaries(var):\n \"\"\"Attach a lot of summaries to a Tensor (for TensorBoard visualization).\"\"\"\n with tf.name_scope('summaries'):\n mean = tf.reduce_mean(var)\n tf.summary.scalar('mean', mean)\n with tf.name_scope('stddev'):\n stddev = tf.sqrt(tf.reduce_mean(tf.square(var - mean)))\n tf.summary.scalar('stddev', stddev)\n tf.summary.scalar('max', tf.reduce_max(var))\n tf.summary.scalar('min', tf.reduce_min(var))\n\n def conv2d(x, W, padding='SAME'):\n \"\"\"conv2d returns a 2d convolution layer with full stride.\"\"\"\n return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding=padding)\n\n def max_pool_2x2(x):\n \"\"\"max_pool_2x2 downsamples a feature map by 2X.\"\"\"\n return tf.nn.max_pool(x, ksize=[1, 2, 2, 1],\n strides=[1, 2, 2, 1], padding='SAME')\n\n\n def nn_layer(input_tensor, input_dim, output_dim, layer_name, training_status=True,\\\n act=tf.nn.relu):\n \"\"\"Reusable code for making a simple neural net layer.\n\n It does a matrix multiply, bias add, and then uses ReLU to nonlinearize.\n It also sets up name scoping so that the resultant graph is easy to read,\n and adds a number of summary ops.\n \"\"\"\n # Adding a name scope ensures logical grouping of the layers in the graph.\n with tf.name_scope(layer_name):\n # This Variable will hold the state of the weights for the layer\n with tf.name_scope('weights'):\n weights = weight_variable([input_dim, output_dim])\n\n # Get the general summaries\n variable_summaries(weights)\n with tf.name_scope('biases'):\n biases = bias_variable([output_dim])\n variable_summaries(biases)\n with tf.name_scope('Wx_plus_b'):\n\n # At evaluation time, some weights are forced to be zero with the sparsity criterion.\n weights = tf.cond(training_status,\n true_fn = lambda: sparsity_ops._sparse_fn(weights,threshold=0.0),\n false_fn = lambda: sparsity_ops._sparse_fn(weights,threshold=FLAGS.sparsity_threshold))\n\n preactivate = tf.matmul(input_tensor, weights) + biases\n # tf.summary.histogram('pre_activations', preactivate)\n\n # Activation summary\n activations = act(preactivate, name='activation')\n tf.summary.scalar('sparsity', tf.nn.zero_fraction(activations))\n tf.summary.histogram('activations', activations)\n\n\n # Overall neurons\n neurons = tf.reduce_sum(tf.abs(weights), axis=1)\n tf.summary.histogram('neurons', neurons)\n\n\n return activations\n\n def nn_conv_layer(input_tensor, w_shape, b_shape, layer_name, padding='SAME', \\\n training_status=True, act=tf.nn.relu):\n \"\"\"Reusable code for making a simple neural net layer.\n\n It does a matrix multiply, bias add, and then uses ReLU to nonlinearize.\n It also sets up name scoping so that the resultant graph is easy to read,\n and adds a number of summary ops.\n \"\"\"\n # Adding a name scope ensures logical grouping of the layers in the graph.\n with tf.name_scope(layer_name):\n # This Variable will hold the state of the weights for the layer\n with tf.name_scope('weights'):\n weights = weight_variable(w_shape)\n variable_summaries(weights)\n with tf.name_scope('biases'):\n biases = bias_variable(b_shape)\n variable_summaries(biases)\n with tf.name_scope('Wx_plus_b'):\n\n # At evaluation time, some weights are forced to be zero with the sparsity criterion.\n weights = tf.cond(training_status,\n true_fn = lambda: sparsity_ops._sparse_fn(weights,threshold=0.0),\n false_fn = lambda: sparsity_ops._sparse_fn(weights,threshold=FLAGS.sparsity_threshold))\n\n preactivate = conv2d(input_tensor, weights,padding) + biases\n # tf.summary.histogram('pre_activations', preactivate)\n\n activations = act(preactivate, name='activation')\n # tf.summary.histogram('activations', activations)\n return activations\n\n def net(x,training_status):\n\n with tf.name_scope('reshape'):\n x_image = tf.reshape(x, [-1, 28, 28, 1])\n\n h_conv1 = nn_conv_layer(x_image, [5, 5, 1, 64], [64], 'conv1', \\\n training_status=training_status, act=tf.nn.relu)\n\n with tf.name_scope('pool1'):\n h_pool1 = max_pool_2x2(h_conv1)\n\n h_conv2 = nn_conv_layer(h_pool1, [5, 5, 64, 128], [128], 'conv2',\\\n training_status=training_status, act=tf.nn.relu)\n\n # Second pooling layer.\n with tf.name_scope('pool2'):\n h_pool2 = max_pool_2x2(h_conv2)\n\n h_pool2_flat = tf.reshape(h_pool2, [-1, 7 * 7 * 128])\n\n h_fc1 = nn_layer(h_pool2_flat, 7 * 7 * 128, 512, 'fc1', \\\n training_status=training_status, act=tf.nn.relu)\n dropped_h_fc1 = tf.nn.dropout(h_fc1, keep_prob)\n\n h_fc2 = nn_layer(dropped_h_fc1, 512, 256, 'fc2', \\\n training_status=training_status, act=tf.nn.relu)\n dropped_h_fc2 = tf.nn.dropout(h_fc2, keep_prob)\n\n # Do not apply softmax activation yet, see below.\n output = nn_layer(dropped_h_fc2, 256, 10, 'softmax', \\\n training_status=training_status, act=tf.identity)\n\n return output, keep_prob\n\n # Network\n output, keep_prob = net(x,training_status)\n\n with tf.name_scope('cross_entropy'):\n with tf.name_scope('total'):\n cross_entropy = tf.losses.sparse_softmax_cross_entropy(\n labels=y_, logits=output)\n tf.summary.scalar('cross_entropy', cross_entropy)\n\n #############################\n ########## LOSS #############\n #############################\n\n # Get all trainable variables except biases\n trainable_variables = tf.trainable_variables()\n\n # Compute the regularization term\n with tf.name_scope('group_lasso'):\n lasso_loss = 0.001 * losses._group_lasso(trainable_variables)\n\n with tf.name_scope('group_variance'):\n variance_loss = 0.01 * losses._group_variance(trainable_variables)\n\n tf.losses.add_loss(\n lasso_loss,\n loss_collection=tf.GraphKeys.LOSSES\n )\n\n tf.losses.add_loss(\n variance_loss,\n loss_collection=tf.GraphKeys.LOSSES\n )\n\n # Compute the regularization term\n with tf.name_scope('Sparsity'):\n sparsity, num_params = sparsity_ops._sparsity_calculatior(trainable_variables,FLAGS.sparsity_threshold)\n\n tf.summary.scalar('sparsity', sparsity)\n\n ###############################################\n ############### Total Loss ###################\n ###############################################\n\n total_loss = tf.losses.get_total_loss(add_regularization_losses=True, name='total_loss')\n list_losses = tf.losses.get_losses(loss_collection=tf.GraphKeys.LOSSES)\n reg_losses = tf.losses.get_losses(loss_collection=tf.GraphKeys.REGULARIZATION_LOSSES)\n\n\n with tf.name_scope('train'):\n train_step = tf.train.AdamOptimizer(FLAGS.learning_rate).minimize(\n total_loss)\n\n with tf.name_scope('accuracy'):\n with tf.name_scope('correct_prediction'):\n correct_prediction = tf.equal(tf.argmax(output, 1), y_)\n with tf.name_scope('accuracy'):\n accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))\n tf.summary.scalar('accuracy', accuracy)\n\n # Merge all the summaries and write them out to\n # /tmp/tensorflow/mnist/logs/mnist_with_summaries (by default)\n merged = tf.summary.merge_all()\n train_writer = tf.summary.FileWriter(FLAGS.log_dir + '/train', sess.graph)\n test_writer = tf.summary.FileWriter(FLAGS.log_dir + '/test')\n tf.global_variables_initializer().run()\n\n # Train the model, and also write summaries.\n def feed_dict(train):\n \"\"\"Make a TensorFlow feed_dict: maps data onto Tensor placeholders.\"\"\"\n if train or FLAGS.fake_data:\n is_train = True\n xs, ys = mnist.train.next_batch(100, fake_data=FLAGS.fake_data)\n k = FLAGS.dropout\n else:\n is_train = False\n xs, ys = mnist.test.next_batch(1000)\n k = 1.0\n return {x: xs, y_: ys, keep_prob: k, training_status:is_train}\n\n for i in range(1, FLAGS.max_steps):\n\n if i % 100 == 0: # Record summaries and test-set accuracy\n summary, acc,sparsity_value, num_parameters = sess.run([merged, \\\n accuracy,sparsity, num_params], feed_dict=feed_dict(False))\n test_writer.add_summary(summary, i)\n print('Accuracy and Sparsity at step %s: %s , %s\\n number of parameters= %s' % (i, \\\n acc, sparsity_value,num_parameters))\n\n\n else: # Record a summary\n summary, _ = sess.run([merged, train_step], feed_dict=feed_dict(True))\n train_writer.add_summary(summary, i)\n\n train_writer.close()\n test_writer.close()\n"
] | [
[
"tensorflow.nn.max_pool",
"tensorflow.cast",
"tensorflow.train.AdamOptimizer",
"tensorflow.summary.scalar",
"tensorflow.nn.conv2d",
"tensorflow.losses.get_total_loss",
"tensorflow.Variable",
"tensorflow.summary.image",
"tensorflow.losses.get_losses",
"tensorflow.name_scope",
"tensorflow.square",
"tensorflow.trainable_variables",
"tensorflow.argmax",
"tensorflow.examples.tutorials.mnist.input_data.read_data_sets",
"tensorflow.nn.dropout",
"tensorflow.matmul",
"tensorflow.truncated_normal",
"tensorflow.InteractiveSession",
"tensorflow.losses.sparse_softmax_cross_entropy",
"tensorflow.placeholder",
"tensorflow.global_variables_initializer",
"tensorflow.summary.merge_all",
"tensorflow.losses.add_loss",
"tensorflow.summary.histogram",
"tensorflow.reduce_max",
"tensorflow.summary.FileWriter",
"tensorflow.constant",
"tensorflow.reduce_mean",
"tensorflow.reshape",
"tensorflow.nn.zero_fraction",
"tensorflow.reduce_min",
"tensorflow.abs"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.10"
]
}
] |
andersonfreitas/mahotas | [
"8ba2a0f14beac059cd5b53d40e39d56247e3d8d7"
] | [
"mahotas/tests/test_stretch.py"
] | [
"from mahotas.stretch import stretch\nimport mahotas\nimport mahotas as mh\nfrom nose.tools import raises\nimport numpy as np\n\ndef test_stretch():\n np.random.seed(2323)\n A = np.random.random_integers(12, 120, size=(100,100))\n A = stretch(A, 255)\n assert A.max() > 250\n assert A.min() == 0\n A = stretch(A,20)\n assert A.max() <= 20\n A = stretch(A, 10, 20)\n assert A.min() >= 10\n A = stretch(A * 0, 10, 20)\n assert A.min() >= 10\n\ndef test_neg_numbers():\n A = np.arange(-10,10)\n scaled = stretch(A, 255)\n assert scaled.shape == A.shape\n assert scaled.min() <= 1\n assert scaled.max() >= 254\n\n\n\ndef test_as_rgb():\n np.random.seed(2323)\n r = np.random.random_integers(12, 120, size=(8,8))\n g = np.random.random_integers(12, 120, size=(8,8))\n b = np.random.random_integers(12, 120, size=(8,8))\n assert mahotas.as_rgb(r,g,b).max() >= 254\n assert mahotas.as_rgb(r,None,b).shape == (8,8,3)\n assert mahotas.as_rgb(r,None,b)[:,:,1].sum() == 0\n\n\n@raises(ValueError)\ndef test_as_rgb_Nones():\n mahotas.as_rgb(None,None,None)\n\n@raises(ValueError)\ndef test_as_rgb_shape_mismatch():\n np.random.seed(2323)\n r = np.random.random_integers(12, 120, size=(8,8))\n g = np.random.random_integers(12, 120, size=(8,8))\n b = np.random.random_integers(12, 120, size=(8,6))\n mahotas.as_rgb(r,g,b)\n\n\n\ndef test_as_rgb_integer():\n int_rgb = mh.as_rgb(1,2,np.zeros((8,6)))\n assert int_rgb.dtype == np.uint8\n assert int_rgb.shape == (8,6,3)\n assert np.all( int_rgb[0,0] == (1,2,0) )\n assert np.all( int_rgb[-1,3] == (1,2,0) )\n assert np.all( int_rgb[-2,4] == (1,2,0) )\n\ndef test_stretch_rgb():\n r = np.arange(256).reshape((32,-1))\n g = 255-r\n b = r/2\n s = mh.stretch(np.dstack([r,g,b]))\n s_rgb = mh.stretch_rgb(np.dstack([r,g,b]))\n assert not np.all(s == s_rgb)\n assert np.all(s[:,:,0] == s_rgb[:,:,0])\n assert np.all(mh.stretch(b) == mh.stretch_rgb(b))\n\n@raises(ValueError)\ndef test_stretch_rgb4():\n mh.stretch_rgb(np.zeros((8,8,3,2)))\n\n\ndef test_overlay():\n im = mh.demos.load('luispedro', as_grey=1)\n im = mh.stretch(im)\n assert np.all(mh.overlay(im).max(2) == im)\n edges = mh.sobel(im)\n\n im3 = mh.overlay(im, green=edges)\n assert np.all(im3[:,:,0] == im)\n assert np.all(im3[:,:,2] == im)\n assert np.all(im3[:,:,1] >= im )\n"
] | [
[
"numpy.random.seed",
"numpy.arange",
"numpy.dstack",
"numpy.all",
"numpy.random.random_integers",
"numpy.zeros"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
stnamjef/object_detection | [
"55b8330f5b4197b9405208db2e6b8154a00469ba"
] | [
"train.py"
] | [
"import os\r\nimport shutil\r\nimport argparse\r\nimport torch as t\r\nfrom tqdm import tqdm\r\nfrom torch.utils.data import DataLoader\r\nfrom torchnet.meter import AverageValueMeter\r\nfrom data.coco_dataset import COCODataset\r\nfrom data.voc_dataset import VOCDataset\r\nfrom models.faster_rcnn_base import LossTuple\r\nfrom models.faster_rcnn import FasterRCNN\r\nfrom models.feature_pyramid_network import FPN\r\nfrom utils.config import opt\r\nfrom utils.eval_tool import evaluate_voc, evaluate_coco\r\nimport utils.array_tool as at\r\n\r\n\r\ndef get_optimizer(model):\r\n lr = opt.lr\r\n params = []\r\n for k, v in dict(model.named_parameters()).items():\r\n if v.requires_grad:\r\n if 'bias' in k:\r\n params += [{'params': [v], 'lr': lr * 2, 'weight_decay': 0}]\r\n else:\r\n params += [{'params': [v], 'lr': lr, 'weight_decay': opt.weight_decay}]\r\n\r\n return t.optim.SGD(params, momentum=0.9)\r\n\r\n\r\ndef reset_meters(meters):\r\n for key, meter in meters.items():\r\n meter.reset()\r\n\r\n\r\ndef update_meters(meters, losses):\r\n loss_d = {k: at.scalar(v) for k, v, in losses._asdict().items()}\r\n for key, meter in meters.items():\r\n meter.add(loss_d[key])\r\n\r\n\r\ndef get_meter_data(meters):\r\n return {k: v.value()[0] for k, v in meters.items()}\r\n\r\n\r\ndef save_model(model, model_name, epoch):\r\n save_path = f'./checkpoints/{model_name}/{epoch}.pth'\r\n save_dir = os.path.dirname(save_path)\r\n if not os.path.exists(save_dir):\r\n os.makedirs(save_dir)\r\n t.save(model.state_dict(), save_path)\r\n\r\n return save_path\r\n\r\n\r\nif __name__ == '__main__':\r\n parser = argparse.ArgumentParser(description='CLI options for training a model.')\r\n parser.add_argument('--model', type=str, default='fpn',\r\n help='Model name: frcnn, fpn (default=fpn).')\r\n parser.add_argument('--backbone', type=str, default='vgg16',\r\n help='Backbone network: vgg16, resnet101 (default=vgg16).')\r\n parser.add_argument('--n_features', type=int, default=1,\r\n help='The number of features to use for RoI-pooling (default=1).')\r\n parser.add_argument('--dataset', type=str, default='voc07',\r\n help='Training dataset: voc07, voc0712, coco (default=voc07).')\r\n parser.add_argument('--data_dir', type=str, default='../dataset',\r\n help='Training dataset directory (default=../dataset).')\r\n parser.add_argument('--save_dir', type=str, default='./model_zoo',\r\n help='Saving directory (default=./model_zoo).')\r\n parser.add_argument('--min_size', type=int, default=600,\r\n help='Minimum input image size (default=600).')\r\n parser.add_argument('--max_size', type=int, default=1000,\r\n help='Maximum input image size (default=1000).')\r\n parser.add_argument('--n_workers_train', type=int, default=8,\r\n help='The number of workers for a train loader (default=8).')\r\n parser.add_argument('--n_workers_test', type=int, default=8,\r\n help='The number of workers for a test loader (default=8).')\r\n parser.add_argument('--lr', type=float, default=1e-3,\r\n help='Learning rate (default=1e-3).')\r\n parser.add_argument('--lr_decay', type=float, default=0.1,\r\n help='Learning rate decay (default=0.1; 1e-3 -> 1e-4).')\r\n parser.add_argument('--weight_decay', type=float, default=5e-4,\r\n help='Weight decay (default=5e-4).')\r\n parser.add_argument('--epoch', type=int, default=15,\r\n help='Total epochs (default=15).')\r\n parser.add_argument('--epoch_decay', type=int, default=10,\r\n help='The epoch to decay learning rate (default=10).')\r\n parser.add_argument('--nms_thresh', type=int, default=0.3,\r\n help='IoU threshold for NMS (default=0.3).')\r\n parser.add_argument('--score_thresh', type=int, default=0.05,\r\n help='BBoxes with scores less than this are excluded (default=0.05).')\r\n\r\n args = parser.parse_args()\r\n opt._parse(vars(args))\r\n\r\n t.multiprocessing.set_sharing_strategy('file_system')\r\n\r\n if opt.dataset == 'voc07':\r\n n_fg_class = 20\r\n train_data = [VOCDataset(opt.data_dir + '/VOCdevkit/VOC2007', 'trainval', 'train')]\r\n test_data = VOCDataset(opt.data_dir + '/VOCdevkit/VOC2007', 'test', 'test', True)\r\n elif opt.dataset == 'voc0712':\r\n n_fg_class = 20\r\n train_data = [VOCDataset(opt.data_dir + '/VOCdevkit/VOC2007', 'trainval', 'train'),\r\n VOCDataset(opt.data_dir + '/VOCdevkit/VOC2012', 'trainval', 'train')]\r\n test_data = VOCDataset(opt.data_dir + '/VOCdevkit/VOC2007', 'test', 'test', True)\r\n elif opt.dataset == 'coco':\r\n n_fg_class = 80\r\n train_data = [COCODataset(opt.data_dir + '/COCO', 'train', 'train')]\r\n test_data = COCODataset(opt.data_dir + '/COCO', 'val', 'test')\r\n else:\r\n raise ValueError('Invalid dataset.')\r\n\r\n train_loaders = [DataLoader(dta, 1, True, num_workers=opt.n_workers_train) for dta in train_data]\r\n test_loader = DataLoader(test_data, 1, False, num_workers=opt.n_workers_test)\r\n\r\n print('Dataset loaded.')\r\n\r\n if opt.model == 'frcnn':\r\n model = FasterRCNN(n_fg_class).cuda()\r\n save_path = f'{opt.save_dir}/{opt.model}_{opt.backbone}.pth'\r\n elif opt.model == 'fpn':\r\n model = FPN(n_fg_class).cuda()\r\n save_path = f'{opt.save_dir}/{opt.model}_{opt.backbone}_{opt.n_features}.pth'\r\n else:\r\n raise ValueError('Invalid model. It muse be either frcnn or fpn.')\r\n\r\n print('Model construction completed.')\r\n\r\n optim = get_optimizer(model)\r\n print('Optimizer loaded.')\r\n\r\n meters = {k: AverageValueMeter() for k in LossTuple._fields}\r\n\r\n lr = opt.lr\r\n best_map = 0\r\n for e in range(1, opt.epoch + 1):\r\n model.train()\r\n reset_meters(meters)\r\n for train_loader in train_loaders:\r\n for img, bbox, label, scale in tqdm(train_loader):\r\n scale = at.scalar(scale)\r\n img, bbox, label = img.cuda().float(), bbox.cuda(), label.cuda()\r\n optim.zero_grad()\r\n losses = model.forward(img, scale, bbox, label)\r\n losses.total_loss.backward()\r\n optim.step()\r\n update_meters(meters, losses)\r\n\r\n md = get_meter_data(meters)\r\n log = f'Epoch: {e:2}, lr: {str(lr)}, ' + \\\r\n f'rpn_loc_loss: {md[\"rpn_loc_loss\"]:.4f}, rpn_cls_loss: {md[\"rpn_cls_loss\"]:.4f}, ' + \\\r\n f'roi_loc_loss: {md[\"roi_loc_loss\"]:.4f}, roi_cls_loss: {md[\"roi_cls_loss\"]:.4f}, ' + \\\r\n f'total_loss: {md[\"total_loss\"]:.4f}'\r\n\r\n print(log)\r\n\r\n model.eval()\r\n if opt.dataset != 'coco':\r\n map = evaluate_voc(test_loader, model)\r\n else:\r\n map = evaluate_coco(test_data, test_loader, model)\r\n\r\n # update best mAP\r\n if map > best_map:\r\n best_map = map\r\n best_path = save_model(model, opt.model, e)\r\n\r\n if e == opt.epoch_decay:\r\n state_dict = t.load(best_path)\r\n model.load_state_dict(state_dict)\r\n # decay learning rate\r\n for param_group in optim.param_groups:\r\n param_group['lr'] *= opt.lr_decay\r\n lr = lr * opt.lr_decay\r\n\r\n # save best model to opt.save_dir\r\n shutil.copyfile(best_path, save_path)\r\n"
] | [
[
"torch.load",
"torch.utils.data.DataLoader",
"torch.multiprocessing.set_sharing_strategy",
"torch.optim.SGD"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
albaltas/learning_to_rank | [
"d9e0a2410a9183dfbdb7e077d9ba17a668d44e55"
] | [
"src/models/adaboost/adaboostdt_final.py"
] | [
"# ====================================================\n# import\n# ====================================================\nimport util\nimport random\nimport numpy as np\nimport pandas as pd\nfrom sklearn.cross_validation import train_test_split\nfrom sklearn.metrics import f1_score\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.ensemble import AdaBoostClassifier\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.metrics import accuracy_score\nimport subprocess\nimport pandas as pd\n# ====================================================\n\n\n\n# ====================================================\n# Loading & File prep\n# ====================================================\n\n#>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> TRAIN\n# Only using small xbb here\n# df_all = pd.read_csv('../data/Fold1/prediction_data/train_set_small_cleaned.csv') # small\ndf_all = pd.read_csv('../data/Fold1/prediction_data/train_set_large_cleaned.csv') # large\ndf_sample = df_all.ix[:,1:]\n\n# Splitting dataset\nX, Y = util.sep_feat_labels(df_sample)\nX.ix[:,1:] = StandardScaler().fit_transform(X.ix[:,1:]) # rescaling features\n\nx_train_qid = X['qid'].copy()\nx_train = X.ix[:,1:].copy()\nx_train = x_train.as_matrix()\ny_train = Y.as_matrix()\n\n#>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> TEST\n# df_test = pd.read_csv('../data/Fold1/prediction_data/test_set_small_cleaned.csv') # small\ndf_test = pd.read_csv('../data/Fold1/prediction_data/test_set_large_cleaned.csv') # large\ndf_sample_test = df_test.ix[:,1:]\n\n# Splitting dataset\nXtest, Ytest = util.sep_feat_labels(df_sample_test)\nXtest.ix[:,1:] = StandardScaler().fit_transform(Xtest.ix[:,1:]) # rescaling features\n\nx_test_qid = Xtest['qid'].copy()\nx_test = Xtest.ix[:,1:].copy()\nx_test = x_test.as_matrix()\ny_test = Ytest.as_matrix()\n\n# ====================================================\n\n\n\n# ====================================================\n# BEST PARAMETER\n# ====================================================\np_max_depth = 26\np_n_estimators = 500\np_learning_rate = 1.0\np_criterion = \"gini\"\np_algorithm = \"SAMME.R\"\n# ====================================================\n\n\nprint(\"Start Model\")\n# ====================================================\n# MODEL\n# ====================================================\n\nparam_depth = p_max_depth\nparam_nest = p_n_estimators\nparam_lr = p_learning_rate\nparam_crit = p_criterion\nparam_algo = p_algorithm\n\nboostedDS = AdaBoostClassifier(\n DecisionTreeClassifier(max_depth=param_depth,criterion=param_crit),\n n_estimators=param_nest,\n learning_rate=param_lr,\n algorithm=param_algo\n ).fit(x_train, y_train)\n\n\nprediction = boostedDS.predict(x_test)\n\n\nndcg10 = util.get_ndcg(x_dev_qid=x_test_qid, preds=prediction, y_dev=y_test, k=10)\nndcg5 = util.get_ndcg(x_dev_qid=x_test_qid, preds=prediction, y_dev=y_test, k=5)\nmapk = util.get_mapk(x_test_qid, prediction, y_test)\nprecision,recall,f1 = util.precision_recall_f1(np.array(y_test), np.array(prediction))\n# err10 =\n# err5 =\nacc_score = accuracy_score(y_test, prediction)\n\n\n\n\n\nprint(\"NDCG@10: \" + str(ndcg10))\nprint(\"NDCG@5 : \" + str(ndcg5))\nprint(\"MAP : \" + str(mapk))\nprint(\"Precision : \" + str(precision))\nprint(\"Recall : \" + str(recall))\nprint(\"F1 : \" + str(f1))\n# print(\"ERR@10: \" + str(err10))\n# print(\"ERR@5 : \" + str(err5))\n# ====================================================\n\n"
] | [
[
"pandas.read_csv",
"sklearn.tree.DecisionTreeClassifier",
"sklearn.preprocessing.StandardScaler",
"numpy.array",
"sklearn.metrics.accuracy_score"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [
"2.0",
"1.4",
"1.1",
"1.5",
"1.2",
"1.3"
],
"scipy": [],
"tensorflow": []
}
] |
Abhishek-Aditya-bs/Anime-Face-Generation-Pytorch | [
"1766259212141b9b04c2fcdc2aef501efb802e3e"
] | [
"MNIST-Image-Generation-Reference/main.py"
] | [
"import torch\nimport torchvision\nimport torch.nn as nn\nfrom IPython.display import Image\nfrom torchvision.utils import save_image\nimport matplotlib.pyplot as plt\nimport os\nfrom dataLoader import data_loader, denorm\nfrom parameters import *\nfrom training import save_fake_images, train_generator, train_discriminator\nfrom discriminator import D\nfrom generator import G\nimport cv2\nfrom IPython.display import FileLink\n\nif not os.path.exists(sample_dir):\n os.makedirs(sample_dir)\n\n# Save some real images\nfor images, _ in data_loader:\n images = images.reshape(images.size(0), 1, 28, 28)\n save_image(denorm(images), os.path.join(sample_dir, 'real_images.png'), nrow=10)\n break\n\nprint(\"Example of a real Image is stored in {}\".format(os.path.join(sample_dir, 'real_images.png')))\nImage(os.path.join(sample_dir, 'real_images.png'))\n\n\nprint(\"Example of a fake Image is stored in {}\".format(os.path.join(sample_dir, 'fake_images-0000.png')))\nsave_fake_images(0)\nImage(os.path.join(sample_dir, 'fake_images-0000.png'))\n\nnum_epochs = 300\ntotal_step = len(data_loader)\nd_losses, g_losses, real_scores, fake_scores = [], [], [], []\n\nfor epoch in range(num_epochs):\n for i, (images, _) in enumerate(data_loader):\n # Load a batch & transform to vectors\n images = images.reshape(batch_size, -1).to(device)\n \n # Train the discriminator and generator\n d_loss, real_score, fake_score = train_discriminator(images)\n g_loss, fake_images = train_generator()\n \n # Inspect the losses\n if (i+1) % 200 == 0:\n d_losses.append(d_loss.item())\n g_losses.append(g_loss.item())\n real_scores.append(real_score.mean().item())\n fake_scores.append(fake_score.mean().item())\n print('Epoch [{}/{}], Step [{}/{}], d_loss: {:.4f}, g_loss: {:.4f}, D(x): {:.2f}, D(G(z)): {:.2f}' \n .format(epoch, num_epochs, i+1, total_step, d_loss.item(), g_loss.item(), \n real_score.mean().item(), fake_score.mean().item()))\n \n # Sample and save images\n save_fake_images(epoch+1)\n\n# Save the model checkpoints \ntorch.save(G.state_dict(), 'G.ckpt')\ntorch.save(D.state_dict(), 'D.ckpt')\n\n# visualize the generated images\nvid_fname = 'gans_training.avi'\n\nfiles = [os.path.join(sample_dir, f) for f in os.listdir(sample_dir) if 'fake_images' in f]\nfiles.sort()\n\nout = cv2.VideoWriter(vid_fname,cv2.VideoWriter_fourcc(*'MP4V'), 8, (302,302))\n[out.write(cv2.imread(fname)) for fname in files]\nout.release()\nFileLink('gans_training.avi')\n\n\nplt.plot(d_losses, '-')\nplt.plot(g_losses, '-')\nplt.xlabel('epoch')\nplt.ylabel('loss')\nplt.legend(['Discriminator', 'Generator'])\nplt.title('Losses');\nplt.savefig('losses-graph.png')\n\nplt.plot(real_scores, '-')\nplt.plot(fake_scores, '-')\nplt.xlabel('epoch')\nplt.ylabel('score')\nplt.legend(['Real Score', 'Fake score'])\nplt.title('Scores');\nplt.savefig('scores-graph.png')"
] | [
[
"matplotlib.pyplot.legend",
"matplotlib.pyplot.title",
"matplotlib.pyplot.savefig",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.ylabel"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
ekrell/wardisland | [
"a9e503c9f73e34674613f59e3fdeadc64157a204"
] | [
"draw-wardisland.py"
] | [
"\n# References used\n# Python & OpenGL for Scientific Visualization, Nicolas P. Rougier\n# - https://www.labri.fr/perso/nrougier/python-opengl/\n\nfrom random import randint\nimport numpy as np\nfrom glumpy import app, gloo, gl, glm, transforms\nfrom glumpy.ext import png\nfrom scipy import interpolate\n\ndef drawStrip(xstart, ystart, xstop, dx, dy):\n n = int ((xstop - xstart) / dx)\n numvertices = n * 6\n vertices = [[0.0, 0.0] for v in range(numvertices)]\n a = xstart\n ytop = ystart\n ybot = ystart - dy\n\n count = count = 0\n for i in range(n):\n b = a + dx\n vertices[count + 0][0] = a\n vertices[count + 0][1] = ytop\n vertices[count + 1][0] = a\n vertices[count + 1][1] = ybot\n vertices[count + 2][0] = b\n vertices[count + 2][1] = ytop\n vertices[count + 3][0] = b\n vertices[count + 3][1] = ytop\n vertices[count + 4][0] = a\n vertices[count + 4][1] = ybot\n vertices[count + 5][0] = b\n vertices[count + 5][1] = ybot\n count = count + 6\n a = b\n return vertices\n\ndef upd(y, deltay, xl, xr, lnudge, rnudge):\n return y - deltay, (xl + lnudge, xr - rnudge)\n\ndef drawVarBlock(ystart, xstart, xstop, deltax, deltay, nudges):\n vertices = []\n outer_a = []\n outer_b = []\n xran = (xstart, xstop)\n for nudgepair in nudges:\n verticesNew = drawStrip(xran[0], ystart, xran[1], deltax, deltay)\n if len(verticesNew) > 0:\n outer_a.append(verticesNew[0])\n outer_b.append(verticesNew[-1])\n vertices = vertices + verticesNew\n ystart, xran = upd(ystart, deltay, xran[0], xran[1], nudgepair[0], nudgepair[1])\n return vertices, outer_a, outer_b\n\ndef eucdist(x0, y0, x1, y1):\n return pow(pow(x0 - x1, 2) + pow(y0 - y1, 2), 0.5)\n\ndef gradiantOpacity(vertices, source):\n dists = np.array([eucdist(source[0], source[1], v[0], v[1]) for v in vertices])\n dists = pow(dists, 10)\n dists = (dists - np.min(dists))/np.ptp(dists)\n return dists\n\n\nvertex = \"\"\"\n attribute vec2 position;\n attribute vec4 color;\n varying vec4 v_color;\n void main(){\n gl_Position = vec4(position, 0.0, 1.0);\n v_color = color;\n } \"\"\"\n\nvertex_m = \"\"\"\n uniform mat4 model; // Model matrix\n uniform mat4 view; // View matrix\n uniform mat4 projection; // Projection matrix\n attribute vec2 position; // Vertex position\n void main()\n {\n gl_Position = model * vec4(position, 0.0, 1.0);\n }\n \"\"\"\n\nfragment_uni = \"\"\"\n uniform vec4 color;\n void main() { gl_FragColor = color; } \"\"\"\n\nfragment_var = \"\"\"\n varying vec4 v_color;\n void main() { gl_FragColor = v_color; } \"\"\"\n\n# Colors\ndebug = np.array((255, 0, 0)) / 255\nsand = np.array((245, 240, 188)) / 255\nlight_green = np.array((171, 191, 157)) /255\n\nbldgs = [ np.array((221, 232, 240)) / 255,\n ]\n\ngreens = [ np.array((138, 168, 146)) / 255,\n np.array((171, 191, 157)) / 255,\n np.array((122, 145, 128)) / 255,\n np.array((171, 194, 177)) / 255,\n np.array(( 90, 105, 94)) / 255,\n np.array((175, 199, 181)) / 255,\n np.array((141, 179, 151)) / 255,\n ]\n\nsands = [ np.array((212, 209, 178)) / 255,\n np.array((214, 208, 186)) / 255,\n np.array((237, 235, 225)) / 255,\n np.array((232, 227, 204)) / 255,\n np.array((222, 214, 204)) / 255,\n np.array((201, 196, 181)) / 255,\n np.array((201, 192, 167)) / 255,\n ]\nwaters = [ np.array((163, 201, 196)) / 255,\n np.array((99, 120, 117)) / 255,\n np.array((176, 191, 207)) / 255,\n np.array((142, 153, 163)) / 255,\n np.array((161, 183, 204)) / 255,\n np.array((100, 130, 128)) / 255,\n np.array((173, 192, 204)) / 255,\n ]\n\n# Shapes, curves\nshapes = []\ncurves = []\ncurves_loop = []\n\n#########\n# Water #\n#########\ndeltay = 0.01\ndeltax = 0.01\nystart = 1.0\nxstart = -1.0\nxstop = 1.0\nnudges = [(0,0) for n in range(250)]\nwater_vertices, _, _ = drawVarBlock(ystart, xstart, xstop, deltax, deltay, nudges)\nwater_colors = [(*waters[randint(0, len(waters) - 1)], 0.6) for v in range(len(water_vertices))]\nwater = gloo.Program(vertex, fragment_var, count = len(water_vertices))\nwater[\"position\"] = water_vertices\nwater[\"color\"] = water_colors\nshapes.append(water)\n\n\n###############\n# Ward Island #\n###############\n\nvertices = []\ndeltay = 0.01\ndeltax = 0.01\nystart = 0.84\nxstart = -1\nxstop = 1\n\nnudges = [ [0.0, 0.0],\n [0.00, 0.000],\n [0.001, 0.00],\n [0.005, 0.000],\n [0.005, 0.000 ],\n [0.007, 0.0000 ],\n [0.005 ,0.0000 ],\n [0.007 , 0.000],\n [0.005,0.00],\n [0.012,0.000],\n [0.014,0.000],\n [0.004,0.000],\n [0.008,0.0001],\n [0.0072,0.0001],\n [0.0075,0.0002],\n [0.008 ,0.0003],\n [0.006 ,00.001],\n [0.011 ,0.001],\n [0.0021 ,0.001],\n [0.0051 ,0.001],\n [0.0054 ,0.001],\n [0.012 ,0.001],\n [0.0101 ,0.001],\n [0.0011 ,0.001],\n [0.027 ,0.001],\n [0.007 ,0.004],\n [0.0201 ,0.014],\n [0.0102 ,0.014],\n [0.0072 ,0.014],\n [0.016 ,0.014],\n [0.0172 ,0.014],\n [0.0015 ,0.014],\n [0.0063 ,-0.00004],\n [0.0065,-0.00004],\n [0.06,-0.014], ########\n [0.0063,-0.00004],\n [-0.0047,-0.00004],\n [0.0046,0.0015],\n [-0.0001,0.015],\n [0.0025,0.016],\n [-0.011,0.0145],\n [-0.0034,0.013],\n [0.002,-0.003],\n [0.0013,0.0145],\n [-0.0116,0.016],\n [0.0025,0.0167],\n [0.0144,0.014],\n [0.0053,0.012],\n [0.0035,0.008],\n [0.0028,0.008],\n [0.0027,0.0086],\n [0.0035,0.0085],\n [0.0035,0.008],\n [0.0047,0.008],\n [0.0037,0.008],\n [0.0035,0.008],\n [0.0035,0.008],\n [0.0035,0.008],\n [0.0035,0.008],\n [0.0033,0.008],\n [0.0033,0.004],\n [0.0033,0.00145],\n [0.0035,0.0019],\n [0.0041,0.0013],\n [-0.0001,0.00135],\n [-0.0005,0.0043],\n [0.0031,0.0013],\n [0.0035,0.0045],\n [0.0021,0.003],\n [0.0022,0.0037],\n [0.0021,-0.000001],\n [-0.0005,0.0002],\n [0.0022,-0.0001],\n [0.0035,-0.0003],\n [0.0025,-0.001],\n [0.0025,0.001],\n [0.0025,0.01],\n [0.0025,0.0014],\n [0.0025,0.004],\n [0.0025,0.004],\n [0.0025,0.008],\n [0.0025,0.007],\n [0.0025,0.007], #####\n [0.0065,0.007],\n [0.0175,0.007],\n [0.0185,0.0075],\n [0.0085,0.007],\n [0.0195,0.007],\n [0.0035,0.0075],\n [0.0125,0.0047],\n [0.0075,0.007],\n [0.0195,0.0075],\n [0.0205,0.006],\n [0.0125,0.0067],\n [0.0055,0.005],\n [0.0095,0.005],\n [0.0700,0.005],\n [0.065,0.005],\n [0.07,0.006],\n [0.013,0.0075],\n [0.011,-0.002],\n [-0.004,0.054],\n [0.01,0.004],\n [0.01,0.004],\n [0.04,0.008],\n [0.04,-0.003],\n [0.04,-0.001],\n [0.04,-0.003],\n [0.01,0.002],\n [0.01,0.0045],\n [0.01,0.004],\n [0.01,0.004],\n [0.01,0.0045],\n [0.001,0.047],\n [0.001,0.007],\n [0.001,0.004],\n [0.01,0.004],\n [0.011,0.0047],\n [0.02,0.004],\n [0.01,0.004],\n [0.02,0.005],\n [0.01,0.004],\n [0.03,0.006],\n [0.005,0.0095],\n [-0.015, 0.015],\n [-0.025,0.022],\n [-0.045,0.013],\n [0.025,0.0194],\n [0.0315,0.0234],\n [0.03015,0.024],\n [0.020127,0.018],\n [0.0004,0.003],\n [0.004,0.001],\n [0.0004,0.003],\n [0.001,0.006],\n [0.011,0.017],\n [0.0101,0.017],\n [0.011,0.0175],\n ]\n\nvertices, va, vb = drawVarBlock(ystart, xstart, xstop, deltax, deltay, nudges)\nislanda_colors = [(*greens[randint(0, len(greens) - 1)], 1) for v in range(len(vertices))]\nislanda = gloo.Program(vertex, fragment_var, count = len(vertices))\nislanda[\"position\"] = vertices\nislanda[\"color\"] = islanda_colors\nshapes.append(islanda)\n\nislandb_opacities = gradiantOpacity(vertices, (0,1)) + gradiantOpacity(vertices, (1,1)) * 0.2 + gradiantOpacity(vertices, (-1,-.5))\nislandb_colors = [(*sands[randint(0, len(greens) - 1)], islandb_opacities[v]) for v in range(len(vertices))]\nislandb = gloo.Program(vertex, fragment_var, count = len(vertices))\nislandb[\"position\"] = vertices\nislandb[\"color\"] = islandb_colors\nshapes.append(islandb)\n\n#############\n# Stitching #\n#############\nborder_points = np.array(va + vb[::-1])\nborder_line = gloo.Program(vertex_m, fragment_uni, count = border_points.shape[0])\nborder_line[\"position\"] = border_points\nborder_line[\"color\"] = (0.05, 0.05, 0.05, 0.9)\nborder_line_model = np.eye(4, dtype=np.float32)\n##glm.rotate(bldg_en_model, 0.5, 1, 1, 1)\n#glm.scale(bldg_en_model, 0.02, .04, 1)\n#glm.translate(bldg_en_model, -.25, .16, 0.0)\nborder_line[\"model\"] = border_line_model\ncurves_loop.append(border_line)\n\n#############\n# Buildings #\n#############\n\n# Corpus Christi Hall (CCH)\nbldg_cch_vertices = np.array([ (-0.7, 0.2), (0.1, 0.2), (0.1, 1),\n (0.1, -1), (-0.4, 0.2), (0.1, 0.2),\n (-0.4, -1), (0.1, -1), (0.1, 0.2)\n ])\nbldg_cch = gloo.Program(vertex_m, fragment_uni, count = len(bldg_cch_vertices))\nbldg_cch[\"position\"] = bldg_cch_vertices\nbldg_cch[\"color\"] = (*bldgs[0], 0.9)\nbldg_cch_model = np.eye(4, dtype=np.float32)\nglm.rotate(bldg_cch_model, 0.3, 0, 0, 1)\nglm.scale(bldg_cch_model, 0.1, 0.1, 1)\nglm.translate(bldg_cch_model, -0.08, .65, 0.0)\nbldg_cch[\"model\"] = bldg_cch_model\nshapes.append(bldg_cch)\n\n# Center for the Arts (CA)\nbldg_ca_vertices = np.array([ (0, 0), (.7, 0), (0, 0.5),\n (.7, .5), (.7, 0), (0, 0.5),\n (.7, 0), (.7, .5), (1, 0.0),\n (1, 0.0), (1, 0.5), (.7, 0.5),\n (0.5, 0), (1, 0.0), (0.7, 0.7),\n (1, 0.0), (1, 0.7), (.7, 0.7),\n (1, 0), (1.5, 0.0), (1, 0.6),\n (1.5, 0.0), (1.5, 0.6), (1, 0.6),\n (.2, 0), (.2, -0.15), (1.6, 0),\n (.2, -0.15), (1.6, 0), (1.6, -0.15),\n\n ])\nbldg_ca = gloo.Program(vertex_m, fragment_uni, count = len(bldg_ca_vertices))\nbldg_ca[\"position\"] = bldg_ca_vertices\nbldg_ca[\"color\"] = (*bldgs[0], 0.9)\nbldg_ca_model = np.eye(4, dtype=np.float32)\nglm.rotate(bldg_ca_model, 0.3, 0, 0, 1)\nglm.scale(bldg_ca_model, 0.13, 0.1, 1)\nglm.translate(bldg_ca_model, -0.04, .55, 0.0)\nbldg_ca[\"model\"] = bldg_ca_model\nshapes.append(bldg_ca)\n\n# O'Conner\nbldg_ocon_vertices = np.array([ (0.0, 0.0), (1, 0.0), (0.0, 1),\n (1, 0.0), (0.0, 1), (1, 1),\n (0.0, 0.6), (-0.2, 0.6), (0.0, 0.4),\n (-0.2, 0.6), (0.0, 0.4), (-0.2, 0.4),\n (.6, 1), (.9, 1), (.6, 1.2),\n (.9, 1), (.6, 1.2), (.9, 1.2),\n ])\nbldg_ocon = gloo.Program(vertex_m, fragment_uni, count = len(bldg_ocon_vertices))\nbldg_ocon[\"position\"] = bldg_ocon_vertices\nbldg_ocon[\"color\"] = (*bldgs[0], 0.9)\nbldg_ocon_model = np.eye(4, dtype=np.float32)\nglm.rotate(bldg_ocon_model, 0.2, 0, 0, 1)\nglm.scale(bldg_ocon_model, 0.14, 0.12, 1)\nglm.translate(bldg_ocon_model, -0.2, .35, 0.0)\nbldg_ocon[\"model\"] = bldg_ocon_model\nshapes.append(bldg_ocon)\n\n# Mary & Jeff Bell Library\nbldg_lib_vertices = np.array([ (0.0, 0.0), (1, 0.0), (0.0, 1),\n (1, 0.0), (0.0, 1), (1, 1),\n ])\nbldg_lib = gloo.Program(vertex_m, fragment_uni, count = len(bldg_lib_vertices))\nbldg_lib[\"position\"] = bldg_lib_vertices\nbldg_lib[\"color\"] = (*bldgs[0], 0.9)\nbldg_lib_model = np.eye(4, dtype=np.float32)\n#glm.rotate(bldg_lib_model, 0.5, 1, 1, 1)\nglm.scale(bldg_lib_model, 0.05, .15, 1)\nglm.translate(bldg_lib_model, -0.11, .164, 0.0)\nbldg_lib[\"model\"] = bldg_lib_model\nshapes.append(bldg_lib)\n\n# Bay Hall (BH)\nbldg_bay_vertices = np.array([ (0.0, 0.0), (1, 0.0), (0.0, 1),\n (1, 0.0), (0.0, 1), (1, 1),\n ])\nbldg_bay = gloo.Program(vertex_m, fragment_uni, count = len(bldg_bay_vertices))\nbldg_bay[\"position\"] = bldg_bay_vertices\nbldg_bay[\"color\"] = (*bldgs[0], 0.9)\nbldg_bay_model = np.eye(4, dtype=np.float32)\n#glm.rotate(bldg_bay_model, 0.5, 1, 1, 1)\nglm.scale(bldg_bay_model, 0.06, .13, 1)\nglm.translate(bldg_bay_model, 0.05, .38, 0.0)\nbldg_bay[\"model\"] = bldg_bay_model\nshapes.append(bldg_bay)\n\n# Faculty Center (FC)\nbldg_fc_vertices = np.array([ (0.0, 0.0), (1, 0.0), (0.0, 1),\n (1, 0.0), (0.0, 1), (1, 1),\n (0.2, 0.0), (0.2, -0.25), (.9, 0.0),\n (.9, 0.0), (0.2, -0.25), (.9, -0.25),\n\n\n ])\nbldg_fc = gloo.Program(vertex_m, fragment_uni, count = len(bldg_fc_vertices))\nbldg_fc[\"position\"] = bldg_fc_vertices\nbldg_fc[\"color\"] = (*bldgs[0], 0.9)\nbldg_fc_model = np.eye(4, dtype=np.float32)\n#glm.rotate(bldg_fc_model, 0.5, 1, 1, 1)\nglm.scale(bldg_fc_model, 0.15, .04, 1)\nglm.translate(bldg_fc_model, -.045, .32, 0.0)\nbldg_fc[\"model\"] = bldg_fc_model\nshapes.append(bldg_fc)\n\n# Center for Instruction (CI)\nbldg_ci_vertices = np.array([ (0, 0), (2, 0), (2, 7),\n (0, 0), (2, 7), (0, 7),\n (-3, 0), (3, 0), (0, -4),\n (-3, 0), (0, 0), (0, 8.5),\n (-3, 8.5), (0, 8.5), (-3, 0),\n (-3, 0), (-11, 0), (-11, 3),\n (-3, 3), (-3, 0),(-11, 3),\n (-11, 3), (-11, 4.5), (-4, 3),\n (-4, 4.5), (-11, 3), (-4, 3),\n ])\nbldg_ci = gloo.Program(vertex_m, fragment_uni, count = len(bldg_ci_vertices))\nbldg_ci[\"position\"] = bldg_ci_vertices\nbldg_ci[\"color\"] = (*bldgs[0], 0.9)\nbldg_ci_model = np.eye(4, dtype=np.float32)\n#glm.rotate(bldg_ci_model, 0.5, 1, 1, 1)\nglm.scale(bldg_ci_model, 0.011, .011, 1)\nglm.translate(bldg_ci_model, .1, .175, 0.0)\nbldg_ci[\"model\"] = bldg_ci_model\nshapes.append(bldg_ci)\n\n# University Services Center (USC)\nbldg_usc_vertices = np.array([ (0, 0), (7, 0), (0, 4),\n (7, 0), (0, 4), (7, 4),\n (-4, 4), (0, 0), (0, 4),\n (3.5, 0), (7, 0), (9, -5),\n (7, 0), (7, 4), (12, -1),\n (12, -1), (9, -5), (7, 0),\n ])\nbldg_usc_vertices = bldg_usc_vertices\nbldg_usc = gloo.Program(vertex_m, fragment_uni, count = len(bldg_usc_vertices))\nbldg_usc[\"position\"] = bldg_usc_vertices\nbldg_usc[\"color\"] = (*bldgs[0], 0.9)\nbldg_usc_model = np.eye(4, dtype=np.float32)\n#glm.rotate(bldg_usc_model, 0.5, 1, 1, 1)\nglm.scale(bldg_usc_model, 0.0075, .0075, 1)\nglm.translate(bldg_usc_model, -.045, .7, 0.0)\nbldg_usc[\"model\"] = bldg_usc_model\nshapes.append(bldg_usc)\n\n# Dugan Wellness Center (DWC)\nbldg_dwc_vertices = np.array([ (0, 0), (0, 1), (1, 0),\n (0, 1), (1, 0), (1, 1),\n (0, 0), (1, 0), (-.02, -0.25),\n (0, 1), (-0.255, 0.94), (-.02, -0.25),\n\n ])\nbldg_dwc = gloo.Program(vertex_m, fragment_uni, count = len(bldg_dwc_vertices))\nbldg_dwc[\"position\"] = bldg_dwc_vertices\nbldg_dwc[\"color\"] = (*bldgs[0], 0.9)\nbldg_dwc_model = np.eye(4, dtype=np.float32)\n#glm.rotate(bldg_dwc_model, 0.5, 1, 1, 1)\nglm.scale(bldg_dwc_model, 0.075, .075, 1)\nglm.translate(bldg_dwc_model, .062, .02, 0.0)\nbldg_dwc[\"model\"] = bldg_dwc_model\nshapes.append(bldg_dwc)\n\n# Glasscock Student Success Center (GSSC)\nbldg_gssc_vertices = np.array([ (0, 0), (7, 0), (0, -1.5),\n (7, -1.5), (7, 0), (0, -1.5),\n (4, 0), (4, 2),(0, 2),\n (0, 0), (0, 2), (4, 0),\n (0, 2), (0, 3.5), (7, 3.5),\n (7, 2), (7, 3.5),(0, 2),\n ])\nbldg_gssc = gloo.Program(vertex_m, fragment_uni, count = len(bldg_gssc_vertices))\nbldg_gssc[\"position\"] = bldg_gssc_vertices\nbldg_gssc[\"color\"] = (*bldgs[0], 0.9)\nbldg_gssc_model = np.eye(4, dtype=np.float32)\n#glm.rotate(bldg_gssc_model, 0.5, 1, 1, 1)\nglm.scale(bldg_gssc_model, 0.012, .014, 1)\nglm.translate(bldg_gssc_model, -.225, .25, 0.0)\nbldg_gssc[\"model\"] = bldg_gssc_model\nshapes.append(bldg_gssc)\n\n# Engineering (EN)\nbldg_en_vertices = np.array([ (0, 0), (0, 1), (6, 1),\n (6, 0), (6, 1), (0, 0),\n (1.5, 0), (1.5, -.7), (0, 0),\n (0, -.7), (1.5, -.7), (0, 0),\n (-1, 1), (0, 1), (0, -.7),\n (0, 1.5), (5.5, 1.5), (0, 1),\n (5.5, 1.5), (5.5, 1), (0, 1),\n ])\nbldg_en = gloo.Program(vertex_m, fragment_uni, count = len(bldg_en_vertices))\nbldg_en[\"position\"] = bldg_en_vertices\nbldg_en[\"color\"] = (*bldgs[0], 0.9)\nbldg_en_model = np.eye(4, dtype=np.float32)\n#glm.rotate(bldg_en_model, 0.5, 1, 1, 1)\nglm.scale(bldg_en_model, 0.02, .04, 1)\nglm.translate(bldg_en_model, -.25, .16, 0.0)\nbldg_en[\"model\"] = bldg_en_model\nshapes.append(bldg_en)\n\n# Round Building (RND)\nbldg_rnd_vertices = np.array([ (0, 0), (0, 1), (0.75, 0.75),\n (0, 0), (1, 0), (0.75, 0.75),\n (0, 0), (0, -1), (0.75, -0.75),\n (0, 0), (1, 0), (0.75, -0.75),\n (0, 0), (0, 1), (-0.75, 0.75),\n (0, 0), (-1, 0), (-0.75, 0.75),\n (0, 0), (0, -1), (-0.75, -0.75),\n (0, 0), (-1, 0), (-0.75, -0.75),\n ])\nbldg_rnd = gloo.Program(vertex_m, fragment_uni, count = len(bldg_rnd_vertices))\nbldg_rnd[\"position\"] = bldg_rnd_vertices\nbldg_rnd[\"color\"] = (*bldgs[0], 0.9)\nbldg_rnd_model = np.eye(4, dtype=np.float32)\n#glm.rotate(bldg_rnd_model, 0.5, 1, 1, 1)\nglm.scale(bldg_rnd_model, 0.04, .04, 1)\nglm.translate(bldg_rnd_model, 0, .46, 0.0)\nbldg_rnd[\"model\"] = bldg_rnd_model\nshapes.append(bldg_rnd)\n\n# University Center (UC)\nbldg_uc_vertices = np.array([ (0, 0), (0.0, 0.25), (0.3, 0.25),\n (0, 0), (0.3, 0.25),(0.3, 0),\n\n\n (0.3, 0.15), (0.3, 0.3), (0.75, 0.3),\n (0.75, 0.3), (0.75, 0.15),(0.3, 0.15),\n\n (0.34, 0.15), (0.75, 0.15), (0.34, 0.1),\n (0.75, 0.15), (0.34, 0.1), (0.75, 0.1),\n\n (0.7, 0.1), (0.45, 0.1), (0.45, 0.06),\n (0.45, 0.06), (0.7, 0.06), (0.7, 0.1),\n\n (0.75, 0.08), (0.75, 0.27), (0.8, 0.27),\n (0.75, 0.08), (0.8, 0.27), (0.8, 0.08),\n\n (0.8, 0.3), (0.9, 0.1), (0.8, 0.1),\n ])\nbldg_uc = gloo.Program(vertex_m, fragment_uni, count = len(bldg_uc_vertices))\nbldg_uc[\"position\"] = bldg_uc_vertices\nbldg_uc[\"color\"] = (*bldgs[0], 0.9)\nbldg_uc_model = np.eye(4, dtype=np.float32)\n#glm.rotate(bldg_uc_model, 0.5, 1, 1, 1)\nglm.scale(bldg_uc_model, 0.35, .35, 1)\nglm.translate(bldg_uc_model, -.3, .0, 0.0)\nbldg_uc[\"model\"] = bldg_uc_model\nshapes.append(bldg_uc)\n\n########\n# Wind #\n########\nXres = 100\nYres = 100\nwind_mag = np.array([ [1.0, 1.0, 1.0, 1.0, 1.0],\n [1.0, 1.0, 1.0, 1.0, 1.0],\n [.5, .5, 1.5, 1.5, 1.5],\n [.4, 1.5, 2.5, 1.5, 2],\n [.4, .4, .0, 2.0, 2.0],\n ])\nwind_dir = np.array([ [-1.6, -1.6, -1.6, -1.3, 1.3],\n [-0.35, -1.6, 1.6, 0.8, 1.3],\n [-0.35, -0.8, -0.3, 0.8, 1.5],\n [0, -0.2, 0.5, 0.7, 2.7],\n [0.2, 0.5, 0.6, 1.7, 2.7],\n ])\n\n# Convert original, not upsampled since cos/sin expensive\nwind_v = wind_mag * np.cos(wind_dir)\nwind_u = wind_mag * np.sin(wind_dir)\n\n# Interpolate (upsample) u, v to Xres, Yres\nx = np.array(range(wind_v.shape[1]))\ny = np.array(range(wind_v.shape[0]))\nxx, yy = np.meshgrid(x, y)\nf_v = interpolate.interp2d(x, y, wind_v, kind = 'linear')\nf_u = interpolate.interp2d(x, y, wind_u, kind = 'linear')\nxnew = np.linspace(0, 5, Xres)\nynew = np.linspace(0, 5, Yres)\ninter_v = f_v(xnew, ynew)\ninter_u = f_u(xnew, ynew)\n\n# Setup environment\nenv = { \"v\" : inter_v,\n \"u\" : inter_u,\n \"wi\" : abs(1 - (-1)),\n \"hi\" : abs(1 - (-1)),\n \"wj\" : Xres,\n \"hj\" : Yres,\n }\n\nnumAgents = 5500\ndirs = np.linspace(-np.pi/2, np.pi/2, numAgents)\nmags = np.cos(np.linspace(0, 100, numAgents))\nypos = np.linspace(-1, 1, numAgents)\nxpos = -1 * np.ones((numAgents))\nvvec = mags * np.sin(dirs)\nuvec = mags * np.cos(dirs)\n\nagents = np.column_stack((ypos, xpos, vvec, uvec))\n\ndef moveAgent(agent, time = 0.05, env = None):\n # Agent : (y, x, v, u)\n e_v = 0.0\n e_u = 0.0\n if env is not None:\n # Convert world coords to env coords\n ylen = agent[0] + 1\n xlen = agent[1] + 1\n erow = int(np.floor(env[\"hj\"] * (ylen / env[\"hi\"])))\n ecol = int(np.floor(env[\"wj\"] * (xlen / env[\"wi\"])))\n if erow < 0 and ecol < env[\"u\"].shape[1]:\n e_v = 4.7\n e_u = 1.7\n elif erow < 0 and ecol >= env[\"u\"].shape[1]:\n e_v = 4.3\n e_u = -2.5\n try:\n e_v = env[\"v\"][erow][ecol]\n e_u = env[\"u\"][erow][ecol]\n except:\n pass\n\n # Move agent with velocity for duration\n # (pos_new = pos_old + velocity * tme)\n agent[0] = agent[0] + (agent[2] + e_v) * time\n agent[1] = agent[1] + (agent[3] + e_u) * time\n\ndef recordAgent(agent, time = 0.05, duration = 10, env = None):\n iters = int(np.ceil(duration / time))\n trajectory = np.zeros((iters, 2))\n for i in range(iters):\n trajectory[i] = (agent[1], (-1) * agent[0])\n moveAgent(agent, time, env)\n trajectory[i] = (agent[1], (-1) * agent[0])\n return trajectory\n\nfor agent in agents:\n traj = recordAgent(agent, time = 0.005, env = env)\n # Trajectory to line object\n traj_line = gloo.Program(vertex_m, fragment_uni, count = traj.shape[0])\n traj_line[\"position\"] = traj\n traj_line[\"color\"] = (*bldgs[0], 0.4)\n traj_line_model = np.eye(4, dtype=np.float32)\n ##glm.rotate(bldg_en_model, 0.5, 1, 1, 1)\n #glm.scale(bldg_en_model, 0.02, .04, 1)\n #glm.translate(bldg_en_model, -.25, .16, 0.0)\n traj_line[\"model\"] = traj_line_model\n curves.append(traj_line)\n\n\n################\n# Setup OpenGL #\n################\n\n# Create a window with a valid GL context\nwindow = app.Window()\nframebuffer = np.zeros((window.height, window.width * 3), dtype=np.uint8)\n\n# Tell glumpy what needs to be done at each redraw\[email protected]\ndef on_draw(dt):\n window.clear()\n for shape in shapes:\n shape.draw(gl.GL_TRIANGLE_STRIP)\n\n for curve_loop in curves_loop:\n curve_loop.draw(gl.GL_LINE_LOOP)\n\n for curve in curves:\n curve.draw(gl.GL_LINES)\n\n gl.glReadPixels(0, 0, window.width, window.height,\n gl.GL_RGB, gl.GL_UNSIGNED_BYTE, framebuffer)\n png.from_array(np.flipud(framebuffer), 'RGB').save('wardisland.png')\n\n# Run the app\napp.run()\n"
] | [
[
"numpy.meshgrid",
"numpy.linspace",
"numpy.min",
"numpy.eye",
"numpy.flipud",
"numpy.cos",
"numpy.ptp",
"numpy.sin",
"numpy.ones",
"numpy.ceil",
"numpy.floor",
"numpy.column_stack",
"scipy.interpolate.interp2d",
"numpy.array",
"numpy.zeros"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [
"0.13",
"1.6",
"0.14",
"1.10",
"0.15",
"1.4",
"0.16",
"1.9",
"0.19",
"1.5",
"0.18",
"1.2",
"1.7",
"0.12",
"1.0",
"0.17",
"1.3",
"1.8"
],
"tensorflow": []
}
] |
xiejx5/GeoSpace | [
"935ebb0593e367c008cc3cc42b2e20ed921b95b1"
] | [
"geospace/gdal_calc.py"
] | [
"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# ******************************************************************************\n#\n# Project: GDAL\n# Purpose: Command line raster calculator with numpy syntax\n# Author: Chris Yesson, [email protected]\n#\n# ******************************************************************************\n# Copyright (c) 2010, Chris Yesson <[email protected]>\n# Copyright (c) 2010-2011, Even Rouault <even dot rouault at mines-paris dot org>\n# Copyright (c) 2016, Piers Titus van der Torren <[email protected]>\n#\n# Permission is hereby granted, free of charge, to any person obtaining a\n# copy of this software and associated documentation files (the \"Software\"),\n# to deal in the Software without restriction, including without limitation\n# the rights to use, copy, modify, merge, publish, distribute, sublicense,\n# and/or sell copies of the Software, and to permit persons to whom the\n# Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included\n# in all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n# DEALINGS IN THE SOFTWARE.\n# ******************************************************************************\n\n################################################################\n# Command line raster calculator with numpy syntax. Use any basic arithmetic supported by numpy arrays such as +-*\\ along with logical operators such as >. Note that all files must have the same dimensions, but no projection checking is performed. Use gdal_calc.py --help for list of options.\n\n# example 1 - add two files together\n# gdal_calc.py -A input1.tif -B input2.tif --outfile=result.tif --calc=\"A+B\"\n\n# example 2 - average of two layers\n# gdal_calc.py -A input.tif -B input2.tif --outfile=result.tif --calc=\"(A+B)/2\"\n\n# example 3 - set values of zero and below to null\n# gdal_calc.py -A input.tif --outfile=result.tif --calc=\"A*(A>0)\" --NoDataValue=0\n################################################################\n\nfrom optparse import OptionParser, Values\nimport os\nimport os.path\nimport sys\n\nimport numpy\n\nfrom osgeo import gdal\nfrom osgeo import gdalnumeric\n\n__all__ = ['Calc']\n\n\n# create alphabetic list for storing input layers\nAlphaList = [\"A\", \"B\", \"C\", \"D\", \"E\", \"F\", \"G\", \"H\", \"I\", \"J\", \"K\", \"L\", \"M\",\n \"N\", \"O\", \"P\", \"Q\", \"R\", \"S\", \"T\", \"U\", \"V\", \"W\", \"X\", \"Y\", \"Z\"]\n\n# set up some default nodatavalues for each datatype\nDefaultNDVLookup = {'Byte': 255, 'UInt16': 65535, 'Int16': -32767, 'UInt32': 4294967293,\n 'Int32': -2147483647, 'Float32': 3.402823466E+38, 'Float64': 1.7976931348623158E+308}\n\n\ndef DoesDriverHandleExtension(drv, ext):\n exts = drv.GetMetadataItem(gdal.DMD_EXTENSIONS)\n return exts is not None and exts.lower().find(ext.lower()) >= 0\n\n\ndef GetExtension(filename):\n ext = os.path.splitext(filename)[1]\n if ext.startswith('.'):\n ext = ext[1:]\n return ext\n\n\ndef GetOutputDriversFor(filename):\n drv_list = []\n ext = GetExtension(filename)\n for i in range(gdal.GetDriverCount()):\n drv = gdal.GetDriver(i)\n if (drv.GetMetadataItem(gdal.DCAP_CREATE) is not None or\n drv.GetMetadataItem(gdal.DCAP_CREATECOPY) is not None) and \\\n drv.GetMetadataItem(gdal.DCAP_RASTER) is not None:\n if len(ext) > 0 and DoesDriverHandleExtension(drv, ext):\n drv_list.append(drv.ShortName)\n else:\n prefix = drv.GetMetadataItem(gdal.DMD_CONNECTION_PREFIX)\n if prefix is not None and filename.lower().startswith(prefix.lower()):\n drv_list.append(drv.ShortName)\n\n # GMT is registered before netCDF for opening reasons, but we want\n # netCDF to be used by default for output.\n if ext.lower() == 'nc' and len(drv_list) == 0 and \\\n drv_list[0].upper() == 'GMT' and drv_list[1].upper() == 'NETCDF':\n drv_list = ['NETCDF', 'GMT']\n\n return drv_list\n\n\ndef GetOutputDriverFor(filename):\n drv_list = GetOutputDriversFor(filename)\n if len(drv_list) == 0:\n ext = GetExtension(filename)\n if len(ext) == 0:\n return 'GTiff'\n else:\n raise Exception(\"Cannot guess driver for %s\" % filename)\n elif len(drv_list) > 1:\n print(\"Several drivers matching %s extension. Using %s\" %\n (ext, drv_list[0]))\n return drv_list[0]\n\n################################################################\n\n\ndef doit(opts, args):\n\n if opts.debug:\n print(\"gdal_calc.py starting calculation %s\" % (opts.calc))\n\n # set up global namespace for eval with all functions of gdalnumeric\n global_namespace = dict([(key, getattr(gdalnumeric, key))\n for key in dir(gdalnumeric) if not key.startswith('__')])\n\n if not opts.calc:\n raise Exception(\"No calculation provided.\")\n elif not opts.outF:\n raise Exception(\"No output file provided.\")\n\n if opts.format is None:\n opts.format = GetOutputDriverFor(opts.outF)\n\n ################################################################\n # fetch details of input layers\n ################################################################\n\n # set up some lists to store data for each band\n myFiles = []\n myBands = []\n myAlphaList = []\n myDataType = []\n myDataTypeNum = []\n myNDV = []\n DimensionsCheck = None\n\n # loop through input files - checking dimensions\n for myI, myF in opts.input_files.items():\n if not myI.endswith(\"_band\"):\n # check if we have asked for a specific band...\n if \"%s_band\" % myI in opts.input_files:\n myBand = opts.input_files[\"%s_band\" % myI]\n else:\n myBand = 1\n\n myFile = gdal.Open(myF, gdal.GA_ReadOnly)\n if not myFile:\n raise IOError(\"No such file or directory: '%s'\" % myF)\n\n myFiles.append(myFile)\n myBands.append(myBand)\n myAlphaList.append(myI)\n myDataType.append(gdal.GetDataTypeName(\n myFile.GetRasterBand(myBand).DataType))\n myDataTypeNum.append(myFile.GetRasterBand(myBand).DataType)\n myNDV.append(myFile.GetRasterBand(myBand).GetNoDataValue())\n # check that the dimensions of each layer are the same\n if DimensionsCheck:\n if DimensionsCheck != [myFile.RasterXSize, myFile.RasterYSize]:\n raise Exception(\"Error! Dimensions of file %s (%i, %i) are different from other files (%i, %i). Cannot proceed\" %\n (myF, myFile.RasterXSize, myFile.RasterYSize, DimensionsCheck[0], DimensionsCheck[1]))\n else:\n DimensionsCheck = [myFile.RasterXSize, myFile.RasterYSize]\n\n if opts.debug:\n print(\"file %s: %s, dimensions: %s, %s, type: %s\" % (\n myI, myF, DimensionsCheck[0], DimensionsCheck[1], myDataType[-1]))\n\n # process allBands option\n allBandsIndex = None\n allBandsCount = 1\n if opts.allBands:\n try:\n allBandsIndex = myAlphaList.index(opts.allBands)\n except ValueError:\n raise Exception(\n \"Error! allBands option was given but Band %s not found. Cannot proceed\" % (opts.allBands))\n allBandsCount = myFiles[allBandsIndex].RasterCount\n if allBandsCount <= 1:\n allBandsIndex = None\n\n ################################################################\n # set up output file\n ################################################################\n\n # open output file exists\n if os.path.isfile(opts.outF) and not opts.overwrite:\n if allBandsIndex is not None:\n raise Exception(\n \"Error! allBands option was given but Output file exists, must use --overwrite option!\")\n if opts.debug:\n print(\"Output file %s exists - filling in results into file\" %\n (opts.outF))\n myOut = gdal.Open(opts.outF, gdal.GA_Update)\n if [myOut.RasterXSize, myOut.RasterYSize] != DimensionsCheck:\n raise Exception(\n \"Error! Output exists, but is the wrong size. Use the --overwrite option to automatically overwrite the existing file\")\n myOutB = myOut.GetRasterBand(1)\n myOutNDV = myOutB.GetNoDataValue()\n myOutType = gdal.GetDataTypeName(myOutB.DataType)\n\n else:\n # remove existing file and regenerate\n if os.path.isfile(opts.outF):\n os.remove(opts.outF)\n # create a new file\n if opts.debug:\n print(\"Generating output file %s\" % (opts.outF))\n\n # find data type to use\n if not opts.type:\n # use the largest type of the input files\n myOutType = gdal.GetDataTypeName(max(myDataTypeNum))\n else:\n myOutType = opts.type\n\n # create file\n myOutDrv = gdal.GetDriverByName(opts.format)\n myOut = myOutDrv.Create(\n opts.outF, DimensionsCheck[0], DimensionsCheck[1], allBandsCount,\n gdal.GetDataTypeByName(myOutType), opts.creation_options)\n\n # set output geo info based on first input layer\n myOut.SetGeoTransform(myFiles[0].GetGeoTransform())\n myOut.SetProjection(myFiles[0].GetProjection())\n\n if opts.NoDataValue is not None:\n myOutNDV = opts.NoDataValue\n else:\n myOutNDV = DefaultNDVLookup[myOutType]\n\n for i in range(1, allBandsCount + 1):\n myOutB = myOut.GetRasterBand(i)\n myOutB.SetNoDataValue(myOutNDV)\n # write to band\n myOutB = None\n\n if opts.debug:\n print(\"output file: %s, dimensions: %s, %s, type: %s\" %\n (opts.outF, myOut.RasterXSize, myOut.RasterYSize, myOutType))\n\n ################################################################\n # find block size to chop grids into bite-sized chunks\n ################################################################\n\n # use the block size of the first layer to read efficiently\n myBlockSize = myFiles[0].GetRasterBand(myBands[0]).GetBlockSize()\n # store these numbers in variables that may change later\n nXValid = myBlockSize[0]\n nYValid = myBlockSize[1]\n # find total x and y blocks to be read\n nXBlocks = (int)(\n (DimensionsCheck[0] + myBlockSize[0] - 1) / myBlockSize[0])\n nYBlocks = (int)(\n (DimensionsCheck[1] + myBlockSize[1] - 1) / myBlockSize[1])\n myBufSize = myBlockSize[0] * myBlockSize[1]\n\n if opts.debug:\n print(\"using blocksize %s x %s\" % (myBlockSize[0], myBlockSize[1]))\n\n # variables for displaying progress\n ProgressCt = -1\n ProgressMk = -1\n ProgressEnd = nXBlocks * nYBlocks * allBandsCount\n\n ################################################################\n # start looping through each band in allBandsCount\n ################################################################\n\n for bandNo in range(1, allBandsCount + 1):\n\n ################################################################\n # start looping through blocks of data\n ################################################################\n\n # loop through X-lines\n for X in range(0, nXBlocks):\n\n # in the rare (impossible?) case that the blocks don't fit perfectly\n # change the block size of the final piece\n if X == nXBlocks - 1:\n nXValid = DimensionsCheck[0] - X * myBlockSize[0]\n myBufSize = nXValid * nYValid\n\n # find X offset\n myX = X * myBlockSize[0]\n\n # reset buffer size for start of Y loop\n nYValid = myBlockSize[1]\n myBufSize = nXValid * nYValid\n\n # loop through Y lines\n for Y in range(0, nYBlocks):\n ProgressCt += 1\n if 10 * ProgressCt / ProgressEnd % 10 != ProgressMk and not opts.quiet:\n ProgressMk = 10 * ProgressCt / ProgressEnd % 10\n from sys import version_info\n if version_info >= (3, 0, 0):\n exec('print(\"%d..\" % (10*ProgressMk), end=\" \")')\n else:\n exec('print 10*ProgressMk, \"..\",')\n\n # change the block size of the final piece\n if Y == nYBlocks - 1:\n nYValid = DimensionsCheck[1] - Y * myBlockSize[1]\n myBufSize = nXValid * nYValid\n\n # find Y offset\n myY = Y * myBlockSize[1]\n\n # create empty buffer to mark where nodata occurs\n myNDVs = None\n\n # make local namespace for calculation\n local_namespace = {}\n\n # fetch data for each input layer\n for i, Alpha in enumerate(myAlphaList):\n\n # populate lettered arrays with values\n if allBandsIndex is not None and allBandsIndex == i:\n myBandNo = bandNo\n else:\n myBandNo = myBands[i]\n myval = gdalnumeric.BandReadAsArray(myFiles[i].GetRasterBand(myBandNo),\n xoff=myX, yoff=myY,\n win_xsize=nXValid, win_ysize=nYValid)\n\n # fill in nodata values\n if myNDV[i] is not None:\n if myNDVs is None:\n myNDVs = numpy.zeros(myBufSize)\n myNDVs.shape = (nYValid, nXValid)\n myNDVs = 1 * \\\n numpy.logical_or(myNDVs == 1, myval == myNDV[i])\n\n # add an array of values for this block to the eval namespace\n local_namespace[Alpha] = myval\n myval = None\n\n # try the calculation on the array blocks\n try:\n myResult = eval(\n opts.calc, global_namespace, local_namespace)\n except:\n print(\"evaluation of calculation %s failed\" % (opts.calc))\n raise\n\n # Propagate nodata values (set nodata cells to zero\n # then add nodata value to these cells).\n if myNDVs is not None:\n myResult = ((1 * (myNDVs == 0)) * myResult) + \\\n (myOutNDV * myNDVs)\n elif not isinstance(myResult, numpy.ndarray):\n myResult = numpy.ones((nYValid, nXValid)) * myResult\n\n # write data block to the output file\n myOutB = myOut.GetRasterBand(bandNo)\n gdalnumeric.BandWriteArray(\n myOutB, myResult, xoff=myX, yoff=myY)\n\n if not opts.quiet:\n print(\"100 - Done\")\n # print(\"Finished - Results written to %s\" %opts.outF)\n\n return\n\n################################################################\n\n\ndef Calc(calc, outfile, NoDataValue=None, type=None, format=None, creation_options=[], allBands='', overwrite=False, debug=False, quiet=False, **input_files):\n \"\"\" Perform raster calculations with numpy syntax.\n Use any basic arithmetic supported by numpy arrays such as +-*\\ along with logical\n operators such as >. Note that all files must have the same dimensions, but no projection checking is performed.\n\n Keyword arguments:\n [A-Z]: input files\n [A_band - Z_band]: band to use for respective input file\n\n Examples:\n add two files together:\n Calc(\"A+B\", A=\"input1.tif\", B=\"input2.tif\", outfile=\"result.tif\")\n\n average of two layers:\n Calc(calc=\"(A+B)/2\", A=\"input1.tif\", B=\"input2.tif\", outfile=\"result.tif\")\n\n set values of zero and below to null:\n Calc(calc=\"A*(A>0)\", A=\"input.tif\", A_Band=2, outfile=\"result.tif\", NoDataValue=0)\n \"\"\"\n opts = Values()\n opts.input_files = input_files\n opts.calc = calc\n opts.outF = outfile\n opts.NoDataValue = NoDataValue\n opts.type = type\n opts.format = format\n opts.creation_options = creation_options\n opts.allBands = allBands\n opts.overwrite = overwrite\n opts.debug = debug\n opts.quiet = quiet\n\n doit(opts, None)\n\n\ndef store_input_file(option, opt_str, value, parser):\n if not hasattr(parser.values, 'input_files'):\n parser.values.input_files = {}\n parser.values.input_files[opt_str.lstrip('-')] = value\n\n\ndef main():\n usage = \"\"\"usage: %prog --calc=expression --outfile=out_filename [-A filename]\n [--A_band=n] [-B...-Z filename] [other_options]\"\"\"\n parser = OptionParser(usage)\n\n # define options\n parser.add_option(\"--calc\", dest=\"calc\",\n help=\"calculation in gdalnumeric syntax using +-/* or any numpy array functions (i.e. log10())\", metavar=\"expression\")\n # limit the input file options to the ones in the argument list\n given_args = set([a[1] for a in sys.argv if a[1:2] in AlphaList] + ['A'])\n for myAlpha in given_args:\n parser.add_option(\"-%s\" % myAlpha, action=\"callback\", callback=store_input_file, type=str,\n help=\"input gdal raster file, you can use any letter (A-Z)\", metavar='filename')\n parser.add_option(\"--%s_band\" % myAlpha, action=\"callback\", callback=store_input_file,\n type=int, help=\"number of raster band for file %s (default 1)\" % myAlpha, metavar='n')\n\n parser.add_option(\"--outfile\", dest=\"outF\",\n help=\"output file to generate or fill\", metavar=\"filename\")\n parser.add_option(\"--NoDataValue\", dest=\"NoDataValue\", type=float,\n help=\"output nodata value (default datatype specific value)\", metavar=\"value\")\n parser.add_option(\"--type\", dest=\"type\", help=\"output datatype, must be one of %s\" %\n list(DefaultNDVLookup.keys()), metavar=\"datatype\")\n parser.add_option(\"--format\", dest=\"format\",\n help=\"GDAL format for output file\", metavar=\"gdal_format\")\n parser.add_option(\n \"--creation-option\", \"--co\", dest=\"creation_options\", default=[], action=\"append\",\n help=\"Passes a creation option to the output format driver. Multiple \"\n \"options may be listed. See format specific documentation for legal \"\n \"creation options for each format.\", metavar=\"option\")\n parser.add_option(\"--allBands\", dest=\"allBands\", default=\"\",\n help=\"process all bands of given raster (A-Z)\", metavar=\"[A-Z]\")\n parser.add_option(\"--overwrite\", dest=\"overwrite\", action=\"store_true\",\n help=\"overwrite output file if it already exists\")\n parser.add_option(\"--debug\", dest=\"debug\",\n action=\"store_true\", help=\"print debugging information\")\n parser.add_option(\"--quiet\", dest=\"quiet\",\n action=\"store_true\", help=\"suppress progress messages\")\n\n (opts, args) = parser.parse_args()\n if not hasattr(opts, \"input_files\"):\n opts.input_files = {}\n\n if len(sys.argv) == 1:\n parser.print_help()\n sys.exit(1)\n elif not opts.calc:\n print(\"No calculation provided. Nothing to do!\")\n parser.print_help()\n sys.exit(1)\n elif not opts.outF:\n print(\"No output file provided. Cannot proceed.\")\n parser.print_help()\n sys.exit(1)\n else:\n try:\n doit(opts, args)\n except IOError as e:\n print(e)\n sys.exit(1)\n\n\nif __name__ == \"__main__\":\n main()\n"
] | [
[
"numpy.logical_or",
"numpy.zeros",
"numpy.ones"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
nishathussain/ssd.pytorch | [
"6547e7522b4f0fdc9b6d12a58045023a95195cb0"
] | [
"ssd.py"
] | [
"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch.autograd import Variable\nfrom functions import Detect, PriorBox\nfrom modules import L2Norm\nfrom data import v2, v1\nimport torchvision.transforms as transforms\nimport torchvision.models as models\nimport torch.backends.cudnn as cudnn\nimport os\n\n\nclass SSD(nn.Module):\n \"\"\"Single Shot Multibox Architecture\n The network is composed of a base VGG network followed by the\n added multibox conv layers. Each multibox layer branches into\n 1) conv2d for class conf scores\n 2) conv2d for localization predictions\n 3) associated priorbox layer to produce default bounding\n boxes specific to the layer's feature map size.\n See: https://arxiv.org/pdf/1512.02325.pdf for more details.\n\n Args:\n phase: (string) Can be \"test\" or \"train\"\n base: VGG16 layers for input, size of either 300 or 500\n extras: extra layers that feed to multibox loc and conf layers\n head: \"multibox head\" consists of loc and conf conv layers\n \"\"\"\n\n def __init__(self, phase, base, extras, head, num_classes):\n super(SSD, self).__init__()\n self.phase = phase\n self.num_classes = num_classes\n # TODO: implement __call__ in PriorBox\n self.priorbox = PriorBox(v2)\n self.priors = Variable(self.priorbox.forward(), volatile=True)\n self.size = 300\n\n # SSD network\n self.vgg = nn.ModuleList(base)\n # Layer learns to scale the l2 normalized features from conv4_3\n self.L2Norm = L2Norm(512, 20)\n self.extras = nn.ModuleList(extras)\n\n self.loc = nn.ModuleList(head[0])\n self.conf = nn.ModuleList(head[1])\n\n if phase == 'test':\n self.softmax = nn.Softmax()\n self.detect = Detect(21, 0, 200, 0.01, 0.25, 400)\n\n\n def forward(self, x):\n \"\"\"Applies network layers and ops on input image(s) x.\n\n Args:\n x: input image or batch of images. Shape: [batch,3*batch,300,300].\n\n Return:\n Depending on phase:\n test:\n Variable(tensor) of output class label predictions,\n confidence score, and corresponding location predictions for\n each object detected. Shape: [batch,topk,7]\n\n train:\n list of concat outputs from:\n 1: confidence layers, Shape: [batch*num_priors,num_classes]\n 2: localization layers, Shape: [batch,num_priors*4]\n 3: priorbox layers, Shape: [2,num_priors*4]\n \"\"\"\n sources = list()\n loc = list()\n conf = list()\n\n # apply vgg up to conv4_3 relu\n for k in range(23):\n x = self.vgg[k](x)\n\n s = self.L2Norm(x)\n sources.append(s)\n\n # apply vgg up to fc7\n for k in range(23, len(self.vgg)):\n x = self.vgg[k](x)\n sources.append(x)\n\n # apply extra layers and cache source layer outputs\n for k, v in enumerate(self.extras):\n x = F.relu(v(x), inplace=True)\n if k % 2 == 1:\n sources.append(x)\n\n # apply multibox head to source layers\n for (x, l, c) in zip(sources, self.loc, self.conf):\n loc.append(l(x).permute(0, 2, 3, 1).contiguous())\n conf.append(c(x).permute(0, 2, 3, 1).contiguous())\n\n loc = torch.cat([o.view(o.size(0), -1) for o in loc], 1)\n conf = torch.cat([o.view(o.size(0), -1) for o in conf], 1)\n\n if self.phase == \"test\":\n output = self.detect(\n loc.view(loc.size(0), -1, 4), # loc preds\n self.softmax(conf.view(-1, self.num_classes)), # conf preds\n self.priors # default boxes\n )\n else:\n output = (\n loc.view(loc.size(0), -1, 4),\n conf.view(conf.size(0), -1, self.num_classes),\n self.priors\n )\n return output\n\n def load_weights(self, base_file):\n other, ext = os.path.splitext(base_file)\n if ext == '.pkl' or '.pth':\n print('Loading weights into state dict...')\n self.load_state_dict(torch.load(base_file))\n print('Finished!')\n else:\n print('Sorry only .pth and .pkl files supported.')\n\n\n# This function is derived from torchvision VGG make_layers()\n# https://github.com/pytorch/vision/blob/master/torchvision/models/vgg.py\ndef vgg(cfg, i, batch_norm=False):\n layers = []\n in_channels = i\n for v in cfg:\n if v == 'M':\n layers += [nn.MaxPool2d(kernel_size=2, stride=2)]\n elif v == 'C':\n layers += [nn.MaxPool2d(kernel_size=2, stride=2, ceil_mode=True)]\n else:\n conv2d = nn.Conv2d(in_channels, v, kernel_size=3, padding=1)\n if batch_norm:\n layers += [conv2d, nn.BatchNorm2d(v), nn.ReLU(inplace=True)]\n else:\n layers += [conv2d, nn.ReLU(inplace=True)]\n in_channels = v\n pool5 = nn.MaxPool2d(kernel_size=3, stride=1, padding=1)\n conv6 = nn.Conv2d(512, 1024, kernel_size=3, padding=6, dilation=6)\n conv7 = nn.Conv2d(1024, 1024, kernel_size=1)\n layers += [pool5, conv6,\n nn.ReLU(inplace=True), conv7, nn.ReLU(inplace=True)]\n return layers\n\n\ndef add_extras(cfg, i, batch_norm=False):\n # Extra layers added to VGG for feature scaling\n layers = []\n in_channels = i\n flag = False\n for k, v in enumerate(cfg):\n if in_channels != 'S':\n if v == 'S':\n layers += [nn.Conv2d(in_channels, cfg[k + 1],\n kernel_size=(1, 3)[flag], stride=2, padding=1)]\n else:\n layers += [nn.Conv2d(in_channels, v, kernel_size=(1, 3)[flag])]\n flag = not flag\n in_channels = v\n return layers\n\n\ndef multibox(vgg, extra_layers, cfg, num_classes):\n loc_layers = []\n conf_layers = []\n vgg_source = [24, -2]\n for k, v in enumerate(vgg_source):\n loc_layers += [nn.Conv2d(vgg[v].out_channels,\n cfg[k] * 4, kernel_size=3, padding=1)]\n conf_layers += [nn.Conv2d(vgg[v].out_channels,\n cfg[k] * num_classes, kernel_size=3, padding=1)]\n for k, v in enumerate(extra_layers[1::2], 2):\n loc_layers += [nn.Conv2d(v.out_channels, cfg[k]\n * 4, kernel_size=3, padding=1)]\n conf_layers += [nn.Conv2d(v.out_channels, cfg[k]\n * num_classes, kernel_size=3, padding=1)]\n return vgg, extra_layers, (loc_layers, conf_layers)\n\n\nbase = {\n '300': [64, 64, 'M', 128, 128, 'M', 256, 256, 256, 'C', 512, 512, 512, 'M', 512, 512, 512],\n '512': [],\n}\nextras = {\n '300': [256, 'S', 512, 128, 'S', 256, 128, 256, 128, 256],\n '512': [],\n}\nmbox = {\n '300': [4, 6, 6, 6, 4, 4], # number of boxes per feature map location\n '512': [],\n}\n\n\ndef build_ssd(phase, size=300, num_classes=21):\n if phase != \"test\" and phase != \"train\":\n print(\"Error: Phase not recognized\")\n return\n if size != 300:\n print(\"Error: Sorry only SSD300 is supported currently!\")\n return\n\n return SSD(phase, *multibox(vgg(base[str(size)], 3),\n add_extras(extras[str(size)], 1024),\n mbox[str(size)], num_classes), num_classes)\n"
] | [
[
"torch.nn.Softmax",
"torch.load",
"torch.nn.ModuleList",
"torch.nn.Conv2d",
"torch.nn.MaxPool2d",
"torch.nn.BatchNorm2d",
"torch.nn.ReLU"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
ntruongv/squad | [
"47d25ae3631ce09894b6ddaa47a2c758d9e285c9"
] | [
"train_tar_sru.py"
] | [
"\"\"\"Train a model on SQuAD.\n\nAuthor:\n Chris Chute ([email protected])\n\"\"\"\n\nimport numpy as np\nimport random\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\nimport torch.optim.lr_scheduler as sched\nimport torch.utils.data as data\nimport util\n\nfrom args import get_train_args\nfrom collections import OrderedDict\nfrom json import dumps\nfrom models_tar_sru import BiDAF\nfrom tensorboardX import SummaryWriter\nfrom tqdm import tqdm\nfrom ujson import load as json_load\nfrom util import collate_fn, SQuAD\n\n\ndef main(args):\n # Set up logging and devices\n args.save_dir = util.get_save_dir(args.save_dir, args.name, training=True)\n log = util.get_logger(args.save_dir, args.name)\n tbx = SummaryWriter(args.save_dir)\n device, args.gpu_ids = util.get_available_devices()\n log.info(f'Args: {dumps(vars(args), indent=4, sort_keys=True)}')\n args.batch_size *= max(1, len(args.gpu_ids))\n\n # Set random seed\n log.info(f'Using random seed {args.seed}...')\n random.seed(args.seed)\n np.random.seed(args.seed)\n torch.manual_seed(args.seed)\n torch.cuda.manual_seed_all(args.seed)\n\n # Get embeddings\n log.info('Loading embeddings...')\n word_vectors = util.torch_from_json(args.word_emb_file)\n char_vectors = util.torch_from_json(args.char_emb_file)\n # Get model\n log.info('Building model...')\n model = BiDAF(word_vectors=word_vectors,\n char_vectors=char_vectors,\n hidden_size=args.hidden_size,\n drop_prob=args.drop_prob)\n model = nn.DataParallel(model, args.gpu_ids)\n if args.load_path:\n log.info(f'Loading checkpoint from {args.load_path}...')\n model, step = util.load_model(model, args.load_path, args.gpu_ids)\n else:\n step = 0\n model = model.to(device)\n model.train()\n ema = util.EMA(model, args.ema_decay)\n\n # Get saver\n saver = util.CheckpointSaver(args.save_dir,\n max_checkpoints=args.max_checkpoints,\n metric_name=args.metric_name,\n maximize_metric=args.maximize_metric,\n log=log)\n\n # Get optimizer and scheduler\n optimizer = optim.Adadelta(model.parameters(), args.lr,\n weight_decay=args.l2_wd)\n scheduler = sched.LambdaLR(optimizer, lambda s: 1.) # Constant LR\n\n # Get data loader\n log.info('Building dataset...')\n train_dataset = SQuAD(args.train_record_file, args.use_squad_v2)\n train_loader = data.DataLoader(train_dataset,\n batch_size=args.batch_size,\n shuffle=True,\n num_workers=args.num_workers,\n collate_fn=collate_fn)\n dev_dataset = SQuAD(args.dev_record_file, args.use_squad_v2)\n dev_loader = data.DataLoader(dev_dataset,\n batch_size=args.batch_size,\n shuffle=False,\n num_workers=args.num_workers,\n collate_fn=collate_fn)\n\n # Train\n log.info('Training...')\n steps_till_eval = args.eval_steps\n epoch = step // len(train_dataset)\n while epoch != args.num_epochs:\n epoch += 1\n log.info(f'Starting epoch {epoch}...')\n with torch.enable_grad(), \\\n tqdm(total=len(train_loader.dataset)) as progress_bar:\n for cw_idxs, cc_idxs, qw_idxs, qc_idxs, y1, y2, ids in train_loader:\n # Setup for forward\n cc_idxs = cc_idxs.to(device)\n qc_idxs = qc_idxs.to(device)\n cw_idxs = cw_idxs.to(device)\n qw_idxs = qw_idxs.to(device)\n batch_size = cw_idxs.size(0)\n optimizer.zero_grad()\n\n # Forward\n log_p1, log_p2, h_vec, hidden_c_state, hidden_q_state = model(cw_idxs, qw_idxs, cc_idxs, qc_idxs)\n ##model now returns the modeling layer outputs also.\n y1, y2 = y1.to(device), y2.to(device)\n #h_vec = torch.stack(h_vec).to(device)\n hidden_c_state = hidden_c_state.to(device) #torch.stack(hidden_c_state).to(device)\n hidden_q_state = hidden_q_state.to(device) #torch.stack(hidden_q_state).to(device)\n #ar = F.dropout(h_vec, p = 0.5) #dropout for the hidden states\n #tar = h_vec[:,1:,:]-h_vec[:,:-1,:] #compute the temporal difference of the hidden states\n alpha = 0.1#args.ar_param\n beta = 0.05#args.tar_param\n p_ar = args.ar_drop\n # if epoch<args.num_epochs/4:\n # alpha = 0\n # beta = 0\n # elif epoch<args.num_epochs*0.75:\n # alpha = alpha / 2\n # beta = beta / 2\n\n \n \n\n\n \n #Find ar and tar for hidden states in the encoding rnn.\n ar_c = F.dropout(hidden_c_state, p = p_ar)\n tar_c = hidden_c_state[:,1:,:]-hidden_c_state[:,:-1,:]\n ar_q = F.dropout(hidden_q_state, p_ar)\n tar_q = hidden_q_state[:,1:,:]-hidden_q_state[:,:-1,:]\n word_len = tar_q.shape[0]\n batch_s = tar_q.shape[1]\n \n \n loss = F.nll_loss(log_p1, y1) + F.nll_loss(log_p2, y2) #+ alpha *torch.norm(ar*ar)+beta *torch.norm(tar*tar)\n loss2 = loss + alpha * torch.norm(ar_c) + alpha*torch.norm(ar_q)/(word_len*batch_s)+beta*torch.norm(tar_c)+beta*torch.norm(tar_q)/(word_len*batch_s)\n loss_val = loss.item()\n \n\n # Backward\n loss2.backward()\n nn.utils.clip_grad_norm_(model.parameters(), args.max_grad_norm)\n optimizer.step()\n scheduler.step(step // batch_size)\n ema(model, step // batch_size)\n\n # Log info\n step += batch_size\n progress_bar.update(batch_size)\n progress_bar.set_postfix(epoch=epoch,\n NLL=loss_val)\n tbx.add_scalar('train/NLL', loss_val, step)\n tbx.add_scalar('train/LR',\n optimizer.param_groups[0]['lr'],\n step)\n\n steps_till_eval -= batch_size\n if steps_till_eval <= 0:\n steps_till_eval = args.eval_steps\n\n # Evaluate and save checkpoint\n log.info(f'Evaluating at step {step}...')\n ema.assign(model)\n results, pred_dict = evaluate(model, dev_loader, device,\n args.dev_eval_file,\n args.max_ans_len,\n args.use_squad_v2)\n saver.save(step, model, results[args.metric_name], device)\n ema.resume(model)\n\n # Log to console\n results_str = ', '.join(f'{k}: {v:05.2f}' for k, v in results.items())\n log.info(f'Dev {results_str}')\n\n # Log to TensorBoard\n log.info('Visualizing in TensorBoard...')\n for k, v in results.items():\n tbx.add_scalar(f'dev/{k}', v, step)\n util.visualize(tbx,\n pred_dict=pred_dict,\n eval_path=args.dev_eval_file,\n step=step,\n split='dev',\n num_visuals=args.num_visuals)\n\n\ndef evaluate(model, data_loader, device, eval_file, max_len, use_squad_v2):\n nll_meter = util.AverageMeter()\n\n model.eval()\n pred_dict = {}\n with open(eval_file, 'r') as fh:\n gold_dict = json_load(fh)\n with torch.no_grad(), \\\n tqdm(total=len(data_loader.dataset)) as progress_bar:\n for cw_idxs, cc_idxs, qw_idxs, qc_idxs, y1, y2, ids in data_loader:\n # Setup for forward\n cw_idxs = cw_idxs.to(device)\n qw_idxs = qw_idxs.to(device)\n batch_size = cw_idxs.size(0)\n\n # Forward\n log_p1, log_p2 = model(cw_idxs, qw_idxs, cc_idxs, qc_idxs)[:2]\n y1, y2 = y1.to(device), y2.to(device)\n loss = F.nll_loss(log_p1, y1) + F.nll_loss(log_p2, y2)\n nll_meter.update(loss.item(), batch_size)\n\n # Get F1 and EM scores\n p1, p2 = log_p1.exp(), log_p2.exp()\n starts, ends = util.discretize(p1, p2, max_len, use_squad_v2)\n\n # Log info\n progress_bar.update(batch_size)\n progress_bar.set_postfix(NLL=nll_meter.avg)\n\n preds, _ = util.convert_tokens(gold_dict,\n ids.tolist(),\n starts.tolist(),\n ends.tolist(),\n use_squad_v2)\n pred_dict.update(preds)\n\n model.train()\n\n results = util.eval_dicts(gold_dict, pred_dict, use_squad_v2)\n results_list = [('NLL', nll_meter.avg),\n ('F1', results['F1']),\n ('EM', results['EM'])]\n if use_squad_v2:\n results_list.append(('AvNA', results['AvNA']))\n results = OrderedDict(results_list)\n\n return results, pred_dict\n\n\nif __name__ == '__main__':\n main(get_train_args())\n"
] | [
[
"torch.optim.lr_scheduler.LambdaLR",
"torch.norm",
"torch.enable_grad",
"numpy.random.seed",
"torch.nn.functional.dropout",
"torch.nn.functional.nll_loss",
"torch.manual_seed",
"torch.utils.data.DataLoader",
"torch.no_grad",
"torch.cuda.manual_seed_all",
"torch.nn.DataParallel"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
eric-tomasi/fuzzyexact | [
"2b419b74c6aec9613a7c040e46e6580607e9412f"
] | [
"tests/test_remove_punctuation.py"
] | [
"import fuzzyexact\nimport pandas as pd\nimport string\nimport unittest\n\n\nclass TestRemovePunctuation(unittest.TestCase):\n\t'''test the remove_punctuation function'''\n\n\tdef setUp(self):\n\t\t'''set up test data frames'''\n\t\tself.my_dict1 = {'fname': ['eric', 'bob', 'john', 'phil', 'sarah', 'jen', 'jill', 'julie', 'jack', 'greg', 'jane'], \n\n 'lname': ['tomasi', 'johnson', 'smith', 'underhill', 'tango', 'whiskey', 'foxtrot', 'delta', 'benson', 'han', 'smol'],\n\n 'address': ['150 right street? RM 205', \n '125 main road + STE 5', \n '325 left avenue_', \n '255 test/close', \n '122 a BOULEVARDE', \n '556 meadow drive BLdG 1', \n '225 lark \"lane', \n '322 park place', \n '998 castle square', \n '020889 country _circuit', \n '123 high street ' + r'!\"#$%&\\'()*+,-./:;<=>?@[\\\\]^_`{|}~']}\n\n\t\tself.df = pd.DataFrame(self.my_dict1)\n\t\tself.df_test = self.df.copy()\n\n\t\tself.no_punc = fuzzyexact.remove_punctuation(self.df_test, 'address')\n\n\tdef tearDown(self):\n\t\tself.my_dict1 = None\n\t\tself.df = None\n\t\tself.df_test = None\n\t\tself.no_punc = None\n\n\tdef test_punctuation(self):\n\t\t'''ensure no punctuation exists in column supplied'''\n\t\tself.assertFalse(self.no_punc['address'].str.contains(string.punctuation, regex=False).any())\n\n\tdef test_dtype(self):\n\t\t'''ensure that the object returned is a pandas dataframe'''\n\t\tself.assertTrue(isinstance(self.no_punc, pd.DataFrame))"
] | [
[
"pandas.DataFrame"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [
"0.23",
"0.21",
"2.0",
"1.4",
"0.19",
"1.1",
"1.5",
"1.2",
"0.24",
"0.20",
"1.0",
"0.25",
"1.3"
],
"scipy": [],
"tensorflow": []
}
] |
shirgur/UnsupervisedDepthFromFocus | [
"33c474c636bdce45cd004873a1391cf25dae4ad1"
] | [
"Utils/Losses.py"
] | [
"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom math import exp\n\n\ndef gaussian(window_size, sigma):\n gauss = torch.Tensor([exp(-(x - window_size // 2) ** 2 / float(2 * sigma ** 2)) for x in range(window_size)])\n return gauss / gauss.sum()\n\n\ndef create_window(window_size, channel, mu=1.5):\n _1D_window = gaussian(window_size, mu).unsqueeze(1)\n _2D_window = _1D_window.mm(_1D_window.t()).float().unsqueeze(0).unsqueeze(0)\n window = _2D_window.expand(channel, 1, window_size, window_size).contiguous()\n window.requires_grad = False\n return window\n\n\ndef create_window_avg(window_size, channel):\n _2D_window = torch.ones(window_size, window_size).float().unsqueeze(0).unsqueeze(0) / (window_size ** 2)\n window = _2D_window.expand(channel, 1, window_size, window_size).contiguous()\n window.requires_grad = False\n return window\n\n\ndef _ssim(img1, img2, window, window_size, channel):\n mu1 = F.conv2d(img1, window, padding=window_size // 2, groups=channel)\n mu2 = F.conv2d(img2, window, padding=window_size // 2, groups=channel)\n\n mu1_sq = mu1.pow(2)\n mu2_sq = mu2.pow(2)\n mu1_mu2 = mu1 * mu2\n\n sigma1_sq = F.conv2d(img1 * img1, window, padding=window_size // 2, groups=channel) - mu1_sq\n sigma2_sq = F.conv2d(img2 * img2, window, padding=window_size // 2, groups=channel) - mu2_sq\n sigma12 = F.conv2d(img1 * img2, window, padding=window_size // 2, groups=channel) - mu1_mu2\n\n C1 = 0.01 ** 2\n C2 = 0.03 ** 2\n\n ssim_map = ((2 * mu1_mu2 + C1) * (2 * sigma12 + C2)) / ((mu1_sq + mu2_sq + C1) * (sigma1_sq + sigma2_sq + C2))\n\n return ssim_map\n\n\nclass SSIM(torch.nn.Module):\n def __init__(self, window_size=11):\n super(SSIM, self).__init__()\n self.window_size = window_size\n self.channel = 1\n self.window = create_window(window_size, self.channel)\n\n def forward(self, img1, img2):\n (_, channel, _, _) = img1.size()\n\n if channel == self.channel and self.window.data.type() == img1.data.type():\n window = self.window\n else:\n window = create_window(self.window_size, channel)\n\n if img1.is_cuda:\n window = window.cuda(img1.get_device())\n window = window.type_as(img1)\n\n self.window = window\n self.channel = channel\n\n return _ssim(img1, img2, window, self.window_size, channel)\n\n\nclass AVERAGE(torch.nn.Module):\n def __init__(self, window_size=7, size_average=False):\n super(AVERAGE, self).__init__()\n self.window_size = window_size\n self.size_average = size_average\n self.channel = 1\n self.window = create_window_avg(window_size, self.channel)\n\n def forward(self, image):\n mu = F.avg_pool2d(image, 7, 1, self.window_size // 2, count_include_pad=False)\n return mu\n\n\nclass Rec_Loss(nn.Module):\n def __init__(self):\n super(Rec_Loss, self).__init__()\n self.AVG = AVERAGE()\n self.SSIM = SSIM()\n\n def forward(self, aif_images, focused_images, rec_images, pred_depth):\n\n alpha = 0.85\n\n rec_loss = F.l1_loss(rec_images, focused_images)\n ssim_loss = (1 - self.SSIM(rec_images, focused_images)).mean()\n rec_loss = alpha * ssim_loss/2 + (1 - alpha)*rec_loss\n\n rec_srp = self.sharpness(rec_images).squeeze(1)\n inp_srp = self.sharpness(focused_images).squeeze(1)\n sharpness_loss = F.l1_loss(rec_srp, inp_srp)\n\n aif_grad = self.gradient(aif_images)\n aif_grad_x_exp = torch.exp(-aif_grad[0].abs())\n aif_grad_y_exp = torch.exp(-aif_grad[1].abs())\n\n dx, dy = self.gradient(pred_depth.unsqueeze(1))\n dD_x = dx.abs() * aif_grad_x_exp\n dD_y = dy.abs() * aif_grad_y_exp\n sm_loss = (dD_x + dD_y).mean()\n\n return rec_loss.unsqueeze(0), ssim_loss.unsqueeze(0), sm_loss.unsqueeze(0), sharpness_loss.unsqueeze(0)\n\n def gradient(self, inp):\n D_dy = inp[:, :, :, :] - F.pad(inp[:, :, :-1, :], (0, 0, 1, 0))\n D_dx = inp[:, :, :, :] - F.pad(inp[:, :, :, :-1], (1, 0, 0, 0))\n return D_dx, D_dy\n\n def sharpness(self, image):\n grad = self.gradient(image)\n mu = self.AVG(image) + 1e-8\n output = - (grad[0]**2 + grad[1]**2) - torch.abs((image - mu) / mu) - torch.pow(image - mu, 2)\n\n return output\n"
] | [
[
"torch.abs",
"torch.ones",
"torch.nn.functional.l1_loss",
"torch.nn.functional.conv2d",
"torch.nn.functional.avg_pool2d",
"torch.pow",
"torch.nn.functional.pad"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
yifan-you-37/ScaffoldLearning | [
"555b1896a2f00731d2880cadec434c63d0a9af4c"
] | [
"simulation/robot_Wrench.py"
] | [
"import time\nimport math\nfrom datetime import datetime\nfrom time import sleep\nimport numpy as np\nimport random\nimport pybullet_data\nimport cv2\nimport os\nimport argparse\nimport torch\n\nimport sys\nsys.path.append('./Eval')\nsys.path.append('./')\n\nclass Robot:\n def __init__(self,pybullet_api,start_pos=[0.4,0.3,0.4],urdf_path=None):\n self.p = pybullet_api\n\n self.gripperMaxForce = 1000.0\n self.armMaxForce = 200.0\n self.endEffectorIndex = 7\n self.start_pos = start_pos\n\n #lower limits for null space\n self.ll=[-2.9671, -1.8326 ,-2.9671, -3.1416, -2.9671, -0.0873, -6.3, -0.0001, -0.0001, -0.0001, 0.0, 0.0, -3.14, -3.14, 0.0, 0.0, 0.0, 0.0, -0.0001, -0.0001]\n #upper limits for null space\n self.ul=[2.9671, 1.8326 ,-2.9671, 0.0, 2.9671, 3.8223, 6.3, 0.0001, 0.0001, 0.0001, 0.81, 0.81, 3.14, 3.14, 0.8757, 0.8757, -0.8, -0.8, 0.0001, 0.0001]\n #joint ranges for null space\n self.jr=[(u-l) for (u,l) in zip(self.ul,self.ll)]\n\n # restposes for null space\n self.rp = [0, 0, 0, 0.5 * math.pi, 0, -math.pi * 0.5 * 0.66, 0]\n # joint damping coefficents\n self.jd = [0.00001, 0.00001, 0.00001, 0.00001, 0.00001, 0.00001, 0.00001,\n 0.00001, 0.00001, 0.00001, 0.00001, 0.00001, 0.00001, 0.00001]\n\n self.num_controlled_joints = 7\n self.controlled_joints = [0, 1, 2, 3, 4, 5, 6]\n\n self.activeGripperJointIndexList = [10, 12, 14, 16, 18, 19]\n\n self.gripper_left_tip_index = 13\n self.gripper_right_tip_index = 17\n\n self.wrench_left_tip_index = 19\n self.wrench_right_tip_index = 20\n\n\n model_path = os.path.join(urdf_path,\"panda_robotiq_wrench.urdf\")\n print(\"model_path in urdf\",model_path)\n\n self.robotId = self.p.loadURDF(model_path, [0, 0, 0],useFixedBase=True) \n self.p.resetBasePositionAndOrientation(self.robotId, [0, 0, 0], [0, 0, 0, 1])\n\n self.targetVelocities = [0] * self.num_controlled_joints\n self.positionGains = [0.03] * self.num_controlled_joints\n self.velocityGains = [1] * self.num_controlled_joints\n\n self.numJoint = self.p.getNumJoints(self.robotId)\n\n self.gripperLowerLimitList = []\n self.gripperUpperLimitList = []\n for jointIndex in range(self.numJoint):\n jointInfo = self.p.getJointInfo(self.robotId,jointIndex)\n print(self.p.getJointInfo(self.robotId,jointIndex))\n if jointIndex in self.activeGripperJointIndexList:\n self.gripperLowerLimitList.append(jointInfo[8])\n self.gripperUpperLimitList.append(jointInfo[9])\n \n def reset(self): \n ####### Set Dynamic Parameters for the gripper pad######\n friction_ceof = 1000.0\n self.p.changeDynamics(self.robotId, self.gripper_left_tip_index, lateralFriction=friction_ceof)\n self.p.changeDynamics(self.robotId, self.gripper_left_tip_index, rollingFriction=friction_ceof)\n self.p.changeDynamics(self.robotId, self.gripper_left_tip_index, spinningFriction=friction_ceof)\n\n self.p.changeDynamics(self.robotId, self.gripper_right_tip_index, lateralFriction=friction_ceof)\n self.p.changeDynamics(self.robotId, self.gripper_right_tip_index, rollingFriction=friction_ceof)\n self.p.changeDynamics(self.robotId, self.gripper_left_tip_index, spinningFriction=friction_ceof)\n\n self.p.changeDynamics(self.robotId, 16, contactStiffness=300.0, contactDamping=0.9)\n self.p.changeDynamics(self.robotId, 17, contactStiffness=300.0, contactDamping=0.9)\n self.p.changeDynamics(self.robotId, 18, linearDamping=0.1)\n self.p.changeDynamics(self.robotId, 18, angularDamping=0.1)\n self.p.changeDynamics(self.robotId, 18, contactStiffness=300.0, contactDamping=0.9)\n self.p.changeDynamics(self.robotId, 19, linearDamping=0.1)\n self.p.changeDynamics(self.robotId, 19, angularDamping=0.1)\n self.p.changeDynamics(self.robotId, 19, contactStiffness=300.0, contactDamping=0.9)\n self.p.changeDynamics(self.robotId, 20, linearDamping=0.1)\n self.p.changeDynamics(self.robotId, 20, angularDamping=0.1)\n self.p.changeDynamics(self.robotId, 20, contactStiffness=300.0, contactDamping=0.9)\n\n\n def jointPositionControl(self,q_list,gripper=None,maxVelocity=None):\n q_list = q_list.tolist()\n if gripper is None:\n self.p.setJointMotorControlArray(bodyUniqueId=self.robotId,jointIndices=self.controlled_joints,controlMode=self.p.POSITION_CONTROL,targetPositions=q_list)\n else:\n self.gripperOpen = 1 - gripper/255.0\n self.gripperPos = np.array(self.gripperUpperLimitList) * (1 - self.gripperOpen) + np.array(self.gripperLowerLimitList) * self.gripperOpen\n self.gripperPos = self.gripperPos.tolist()\n armForce = [self.armMaxForce] * len(self.controlled_joints)\n gripperForce = [self.gripperMaxForce] * len(self.activeGripperJointIndexList)\n \n self.p.setJointMotorControlArray(bodyUniqueId=self.robotId,jointIndices=self.controlled_joints,controlMode=self.p.POSITION_CONTROL,targetPositions=q_list,forces=armForce)\n self.p.setJointMotorControlArray(bodyUniqueId=self.robotId,jointIndices=self.activeGripperJointIndexList,controlMode=self.p.POSITION_CONTROL,targetPositions=self.gripperPos,forces=gripperForce)\n self.p.stepSimulation()\n\n def setJointValue(self,q,gripper):\n for j in range(len(self.controlled_joints)):\n self.p.resetJointState(self.robotId,j,q[j],0.0)\n self.gripperOpen = 1 - gripper/255.0\n self.gripperPos = np.array(self.gripperUpperLimitList) * (1 - self.gripperOpen) + np.array(self.gripperLowerLimitList) * self.gripperOpen\n for j in range(6):\n index_ = self.activeGripperJointIndexList[j]\n self.p.resetJointState(self.robotId,index_,self.gripperPos[j],0.0)\n\n def getJointValue(self):\n qlist = []\n for j in range(len(self.controlled_joints)):\n qlist.append(self.p.getJointState(self.robotId,j)[0])\n #print(qlist)\n return qlist\n\n def getEndEffectorPos(self):\n return self.p.getLinkState(self.robotId, self.endEffectorIndex)[0]\n\n def getEndEffectorVel(self):\n return self.p.getLinkState(self.robotId, self.endEffectorIndex)[6]\n\n def getEndEffectorOrn(self):\n return self.p.getLinkState(self.robotId, self.endEffectorIndex)[1]\n\n def getWrenchTipPos(self):\n left_tip_pos = self.p.getLinkState(self.robotId, self.wrench_left_tip_index)[0]\n right_tip_pos = self.p.getLinkState(self.robotId, self.wrench_right_tip_index)[0]\n gripper_tip_pos = 0.5 * np.array(left_tip_pos) + 0.5 * np.array(right_tip_pos)\n \n return gripper_tip_pos\n \n def getWrenchLeftTipPos(self):\n left_tip_pos = self.p.getLinkState(self.robotId, self.wrench_left_tip_index)[0]\n left_tip_pos = np.array(left_tip_pos)\n return np.array(left_tip_pos)\n\n def getWrenchRightTipPos(self):\n right_tip_pos = self.p.getLinkState(self.robotId, self.wrench_right_tip_index)[0]\n return np.array(right_tip_pos)\n \n def getWrenchLeftTipOrn(self):\n left_tip_orn = self.p.getLinkState(self.robotId, self.wrench_left_tip_index)[1]\n return left_tip_orn\n\n def IK_wrench(self,pos,orn,null_pose=None):\n if null_pose is not None:\n jointPoses = self.p.calculateInverseKinematics(self.robotId, self.wrench_left_tip_index, pos, orn,\n lowerLimits=self.ll,\n upperLimits=self.ul,\n jointRanges=self.jr,\n restPoses=null_pose)[:self.num_controlled_joints]\n else:\n jointPoses = self.p.calculateInverseKinematics(self.robotId, self.wrench_left_tip_index, pos, orn,\n lowerLimits=self.ll,\n upperLimits=self.ul,\n jointRanges=self.jr)[:self.num_controlled_joints]\n\n return jointPoses\n\n def wrench_Control(self,pos,orn,null_pose=None,gripperPos=None):\n jointPoses = self.IK_wrench(pos,orn,null_pose)\n\n if gripperPos is None:\n self.p.setJointMotorControlArray(bodyIndex=self.robotId,\n jointIndices=self.controlled_joints,\n controlMode=self.p.POSITION_CONTROL,\n targetPositions=jointPoses,\n targetVelocities=self.targetVelocities,\n forces=[self.armMaxForce] * self.num_controlled_joints)\n else:\n self.gripperOpen = 1.0 - gripperPos/255.0\n self.gripperPos = np.array(self.gripperUpperLimitList) * (1 - self.gripperOpen) + np.array(self.gripperLowerLimitList) * self.gripperOpen\n self.gripperPos = self.gripperPos.tolist()\n gripperForce = [self.gripperMaxForce] * len(self.activeGripperJointIndexList)\n jointPoses = np.array(jointPoses).tolist()\n self.p.setJointMotorControlArray(bodyIndex=self.robotId,\n jointIndices=self.controlled_joints + self.activeGripperJointIndexList,\n controlMode=self.p.POSITION_CONTROL,\n targetPositions=jointPoses + self.gripperPos,\n targetVelocities=self.targetVelocities + [0.0] * len(self.activeGripperJointIndexList),\n forces=[self.armMaxForce] * self.num_controlled_joints + gripperForce)\n\n self.p.stepSimulation()\n\n\n def operationSpacePositionControl(self,pos,orn=None,null_pose=None,gripperPos=None):\n if null_pose is None and orn is None:\n jointPoses = self.p.calculateInverseKinematics(self.robotId, self.endEffectorIndex, pos,\n lowerLimits=self.ll,\n upperLimits=self.ul,\n jointRanges=self.jr)[:self.num_controlled_joints]\n\n elif null_pose is None and orn is not None:\n jointPoses = self.p.calculateInverseKinematics(self.robotId, self.endEffectorIndex, pos, orn,\n lowerLimits=self.ll,\n upperLimits=self.ul,\n jointRanges=self.jr)[:self.num_controlled_joints]\n\n elif null_pose is not None and orn is None:\n jointPoses = self.p.calculateInverseKinematics(self.robotId, self.endEffectorIndex, pos,\n lowerLimits=self.ll,\n upperLimits=self.ul,\n jointRanges=self.jr,\n restPoses=null_pose)[:self.num_controlled_joints]\n\n else:\n jointPoses = self.p.calculateInverseKinematics(self.robotId, self.endEffectorIndex, pos, orn,\n lowerLimits=self.ll,\n upperLimits=self.ul,\n jointRanges=self.jr,\n restPoses=null_pose)[:self.num_controlled_joints]\n\n #print(\"jointPoses\",jointPoses)\n if gripperPos is None:\n self.p.setJointMotorControlArray(bodyIndex=self.robotId,\n jointIndices=self.controlled_joints,\n controlMode=self.p.POSITION_CONTROL,\n targetPositions=jointPoses,\n targetVelocities=self.targetVelocities,\n forces=[self.armMaxForce] * self.num_controlled_joints)\n else:\n self.gripperOpen = 1.0 - gripperPos/255.0\n self.gripperPos = np.array(self.gripperUpperLimitList) * (1 - self.gripperOpen) + np.array(self.gripperLowerLimitList) * self.gripperOpen\n self.gripperPos = self.gripperPos.tolist()\n gripperForce = [self.gripperMaxForce] * len(self.activeGripperJointIndexList)\n jointPoses = np.array(jointPoses).tolist()\n self.p.setJointMotorControlArray(bodyIndex=self.robotId,\n jointIndices=self.controlled_joints + self.activeGripperJointIndexList,\n controlMode=self.p.POSITION_CONTROL,\n targetPositions=jointPoses + self.gripperPos,\n targetVelocities=self.targetVelocities + [0.0] * len(self.activeGripperJointIndexList),\n forces=[self.armMaxForce] * self.num_controlled_joints + gripperForce)\n\n self.p.stepSimulation()\n\n \n def gripperControl(self,gripperPos):\n self.gripperOpen = 1.0 - gripperPos/255.0 \n self.gripperPos = np.array(self.gripperUpperLimitList) * (1 - self.gripperOpen) + np.array(self.gripperLowerLimitList) * self.gripperOpen\n self.gripperPos = self.gripperPos.tolist()\n gripperForce = [self.gripperMaxForce] * len(self.activeGripperJointIndexList)\n self.p.setJointMotorControlArray(bodyUniqueId=self.robotId,jointIndices=self.activeGripperJointIndexList,controlMode=self.p.POSITION_CONTROL,targetPositions=self.gripperPos,forces=gripperForce)\n self.p.stepSimulation()\n"
] | [
[
"numpy.array"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
dnddnjs/pytorch-vision | [
"d432b467774f838bef37372d6cff3576c6559803"
] | [
"shake_shake/train.py"
] | [
"import os\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nimport torch.backends.cudnn as cudnn\n\nimport torchvision\nimport torchvision.transforms as transforms\n\nfrom model import shake_shake\nfrom cosine_optim import cosine_annealing_scheduler\nimport argparse\nfrom tensorboardX import SummaryWriter\n\n\nparser = argparse.ArgumentParser(description='cifar10 classification models')\nparser.add_argument('--lr', default=0.2, help='')\nparser.add_argument('--resume', default=None, help='')\nparser.add_argument('--batch_size', default=128, help='')\nparser.add_argument('--num_worker', default=4, help='')\nparser.add_argument('--epochs', default=1800, help='')\nparser.add_argument('--logdir', type=str, default='logs', help='')\nargs = parser.parse_args()\n\ndevice = 'cuda' if torch.cuda.is_available() else 'cpu'\n\nprint('==> Preparing data..')\ntransforms_train = transforms.Compose([\n\ttransforms.RandomCrop(32, padding=4),\n\ttransforms.RandomHorizontalFlip(),\n\ttransforms.ToTensor(),\n\ttransforms.Normalize((0.4914, 0.4822, 0.4465), (0.2023, 0.1994, 0.2010)),\n])\ntransforms_test = transforms.Compose([\n\ttransforms.ToTensor(),\n\ttransforms.Normalize((0.4914, 0.4822, 0.4465), (0.2023, 0.1994, 0.2010)),\n])\n\ndataset_train = torchvision.datasets.CIFAR10(root='../data', train=True, download=True, transform=transforms_train)\ndataset_test = torchvision.datasets.CIFAR10(root='../data', train=False, download=True, transform=transforms_test)\ntrain_loader = torch.utils.data.DataLoader(dataset_train, batch_size=args.batch_size, \n\t shuffle=True, num_workers=args.num_worker)\ntest_loader = torch.utils.data.DataLoader(dataset_test, batch_size=100, \n\t shuffle=False, num_workers=args.num_worker)\n\n# there are 10 classes so the dataset name is cifar-10\nclasses = ('plane', 'car', 'bird', 'cat', 'deer', \n\t 'dog', 'frog', 'horse', 'ship', 'truck')\n\nprint('==> Making model..')\n\nnet = shake_shake()\nnet = net.to(device)\n\nif args.resume is not None:\n\tcheckpoint = torch.load('./save_model/' + args.resume)\n\tnet.load_state_dict(checkpoint['net'])\n\ncriterion = nn.CrossEntropyLoss()\noptimizer = optim.SGD(net.parameters(), lr=args.lr, \n\t momentum=0.9, weight_decay=1e-4)\n\n\ncosine_lr_scheduler = cosine_annealing_scheduler(optimizer, args.epochs, args.lr)\nwriter = SummaryWriter(args.logdir)\n\n\ndef train(epoch):\n\tnet.train()\n\ttrain_loss = 0\n\tcorrect = 0\n\ttotal = 0\n\n\tfor batch_idx, (inputs, targets) in enumerate(train_loader):\n\t\tinputs = inputs.to(device)\n\t\ttargets = targets.to(device)\n\t\toutputs = net(inputs)\n\t\tloss = criterion(outputs, targets)\n\n\t\toptimizer.zero_grad()\n\t\tloss.backward()\n\t\toptimizer.step()\n\n\t\ttrain_loss += loss.item()\n\t\t_, predicted = outputs.max(1)\n\t\ttotal += targets.size(0)\n\t\tcorrect += predicted.eq(targets).sum().item()\n \n\tacc = 100 * correct / total\n\tprint('epoch : {} [{}/{}]| loss: {:.3f} | acc: {:.3f}'.format(\n\t\t epoch, batch_idx, len(train_loader), train_loss/(batch_idx+1), acc))\n\n\twriter.add_scalar('log/train error', 100 - acc, epoch)\n\n\n\ndef test(epoch, best_acc):\n\tnet.eval()\n\n\ttest_loss = 0\n\tcorrect = 0\n\ttotal = 0\n\n\twith torch.no_grad():\n\t\tfor batch_idx, (inputs, targets) in enumerate(test_loader):\n\t\t\tinputs = inputs.to(device)\n\t\t\ttargets = targets.to(device)\n\t\t\toutputs = net(inputs)\n\t\t\tloss = criterion(outputs, targets)\n\n\t\t\ttest_loss += loss.item()\n\t\t\t_, predicted = outputs.max(1)\n\t\t\ttotal += targets.size(0)\n\t\t\tcorrect += predicted.eq(targets).sum().item()\n\n\tacc = 100 * correct / total\n\tprint('test epoch : {} [{}/{}]| loss: {:.3f} | acc: {:.3f}'.format(\n\t\t epoch, batch_idx, len(test_loader), test_loss/(batch_idx+1), acc))\n\n\twriter.add_scalar('log/test error', 100 - acc, epoch)\n\n\tif acc > best_acc:\n\t\tprint('==> Saving model..')\n\t\tstate = {\n\t\t 'net': net.state_dict(),\n\t\t 'acc': acc,\n\t\t 'epoch': epoch,\n\t\t}\n\t\tif not os.path.isdir('save_model'):\n\t\t os.mkdir('save_model')\n\t\ttorch.save(state, './save_model/ckpt.pth')\n\t\tbest_acc = acc\n\n\treturn best_acc\n\n\nif __name__=='__main__':\n\tbest_acc = 0\n\tif args.resume is None:\n\t\tfor epoch in range(args.epochs):\n\t\t\tcosine_lr_scheduler.step()\n\t\t\ttrain(epoch)\n\t\t\tbest_acc = test(epoch, best_acc)\n\t\t\tprint('best test accuracy is ', best_acc)\n\telse:\n\t\ttest(epoch=0, best_acc=0)\n"
] | [
[
"torch.nn.CrossEntropyLoss",
"torch.load",
"torch.utils.data.DataLoader",
"torch.no_grad",
"torch.cuda.is_available",
"torch.save"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
djhoese/lmatools | [
"67930612e71c74fdd0eed655b5f8cfdd01933b07"
] | [
"lmatools/lasso/cell_lasso_timeseries.py"
] | [
"from __future__ import absolute_import\nimport numpy as np\nfrom datetime import datetime\n\nfrom lmatools.io.LMA_h5_file import LMAh5Collection\nfrom lmatools.grid.make_grids import time_edges, seconds_since_start_of_day\nfrom lmatools.grid.density_to_files import ArrayChopper, stack_chopped_arrays\n\nclass TimeSeriesGenericFlashSubset(object):\n \"\"\" This class is not meant to be used alone. A subclass which provides\n self.lma corresponding to the LMAh5Collection API is necessary.\n \"\"\"\n def __init__(self, t_start, t_end, dt, base_date=None):\n self.lma = None\n \n if base_date is None:\n self.base_date = datetime(t_start.year, t_start.month, t_start.day)\n else: \n self.base_date = base_date\n \n t_edges, duration = time_edges(t_start, t_end, dt.total_seconds())\n self.t_edges = t_edges\n self.basedate, t_edges_seconds = seconds_since_start_of_day(t_start, t_edges)\n self.t_edges_seconds = np.asarray(t_edges_seconds)\n self.n_frames = len(t_edges)-1\n \n self.t_chopper = ArrayChopper(t_edges_seconds)\n \n def t_edges_to_isoformat(self, as_start_end=False):\n \"\"\" Return a list of ISO formatted time strings.\n \n If as_start_end=True, return (iso_start, iso_end)\n corresponding to the left and right edges of each window\n \"\"\"\n iso = [t.isoformat() for t in self.t_edges]\n if as_start_end == True:\n return iso[:-1], iso[1:]\n else:\n return iso\n \n def gen_chopped_events_flashes(self):\n \"\"\" For each file in h5_filenames, generate a sequence of (events, flashes)\n which have been chopped apart into the individual time series windows.\n \n Because data files might cross time windows (for instance, a time\n series with two minute spacing on odd minutes, which would cross \n a day boundary), the consumer of these events and flashes must wait\n to consume all data from the generator before being certain that \n all events and flashes for a certain time window are available. \n An example of consuming and stacking up all data is \n in self.get_event_flash_time_series.\n \n \"\"\"\n\n for events, flashes in self.lma:\n # Get a list of subarrays corresponding to the time windows given\n # by self.t_edges\n chopped_events = self.t_chopper.chop(events, edge_key='time')\n chopped_flashes = self.t_chopper.chop(flashes, edge_key='start')\n ev_lens = [e.shape for e in chopped_events]\n fl_lens = [f.shape for f in chopped_flashes]\n yield chopped_events, chopped_flashes\n \n def get_event_flash_time_series(self):\n \"\"\" Return two lists: events, flashes\n Each list has N arrays corresponding to N+1 self.t_edges\n \"\"\"\n events = []\n flashes = []\n # This loops over chunks of data generated by the h5 file reader, not\n # the time series windows.\n for ev_chop, fl_chop in self.gen_chopped_events_flashes():\n events.append(ev_chop)\n flashes.append(fl_chop)\n return stack_chopped_arrays(events), stack_chopped_arrays(flashes)\n\nclass TimeSeriesFlashSubset(TimeSeriesGenericFlashSubset):\n def __init__(self, h5_filenames, t_start, t_end, dt, base_date=None, min_points=10):\n \"\"\" \n t_start, t_end: datetime objects giving start and end of the time series\n dt: datetime.timedelta object giving the time series interval\n \n h5_filenames are in the lmatools format.\n \n Attributes\n t_edges: edges of the time series windows as datetime objects\n n_frames: number of time series windows\n \"\"\"\n super(TimeSeriesFlashSubset, self).__init__(t_start, t_end, dt, base_date=None)\n self.lma = LMAh5Collection(h5_filenames, min_points=min_points, base_date=self.base_date)\n \n\n \nclass TimeSeriesPolygonFlashSubset(TimeSeriesFlashSubset):\n def __init__(self, *args, **kwargs):\n # could also accept coord_names and time_key kwargs here, but those\n # should be standardized in the lmatools h5 format, so we hard code\n # them below\n \n # This is here because the PolygonLassoFilter imports matplotlib\n # and we don't want other imports from this module that don't\n # need matplotlib to trigger a matplotlib import\n from lmatools.lasso.energy_stats import TimeSeriesPolygonLassoFilter \n \n self.polys = kwargs.pop('polys', [])\n self.t_edges_polys = kwargs.pop('t_edges_polys', [])\n\n super(TimeSeriesPolygonFlashSubset, self).__init__(*args, **kwargs)\n \n # strictly speaking, we don't even need the time series part; that's been done\n # and we're just lassoin' the points. \n # But, this code is known to work, so we just reuse it here.\n self.fl_lassos = TimeSeriesPolygonLassoFilter(coord_names=('init_lon', 'init_lat'), time_key='start',\n time_edges=self.t_edges_polys, polys=self.polys, basedate=self.base_date )\n self.ev_lassos = TimeSeriesPolygonLassoFilter(coord_names=('lon', 'lat'), time_key='time',\n time_edges=self.t_edges_polys, polys=self.polys, basedate=self.base_date)\n self.grid_lassos = TimeSeriesPolygonLassoFilter(coord_names=('lon', 'lat'), time_key='t',\n time_edges=self.t_edges_polys, polys=self.polys, basedate=self.base_date)\n \n def gen_chopped_events_flashes(self, *args, **kwargs):\n parent = super(TimeSeriesPolygonFlashSubset, self)\n for ch_ev_series, ch_fl_series in parent.gen_chopped_events_flashes(*args, **kwargs):\n # This gives a time series for each HDF5 LMA file. Next loop\n # over each chopped time series window.\n # Apply polygon filter to time series created by superclass, yield chopped events and flashes\n lassoed_ev = [ch_ev[self.ev_lassos.filter_mask(ch_ev)] for ch_ev in ch_ev_series]\n lassoed_fl = [ch_fl[self.fl_lassos.filter_mask(ch_fl)] for ch_fl in ch_fl_series]\n yield lassoed_ev, lassoed_fl\n "
] | [
[
"numpy.asarray"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
txg11/t5-pegasus-chinese | [
"ef8de37ff2e2911ae308f5de937547a71945cdeb"
] | [
"bert4torch/atest.py"
] | [
"from transformers.modeling_bert import BertForPreTraining\nfrom xtools import *\nfrom bert4torch.loss import CrossEntropyLoss\nimport random\nfrom transformers import AdamW, get_linear_schedule_with_warmup\nfrom torch.cuda import amp\nfrom pytorch_lightning import seed_everything\nimport pkbar\n\n# seed_everything(128)\nbatch_size = 32\nmodel_path = 'hfl/chinese-roberta-wwm-ext'\n# model_path = 'hfl/rbt3'\nadam_epsilon = 1e-8\nlr = 5e-5\ndevice = 'cuda'\nsteps = 1000000\ngrad_accumulation_steps = 4\nsave_every = 100000\n\ndebug = 0\n\n\ndef get_data(path):\n ret = []\n _, name = os.path.split(path)\n\n name = name.split('_')[0]\n for idx, line in enumerate(tqdm.tqdm(open(path))):\n line = json.loads(line)\n line['task'] = name\n ret.append(line)\n if debug and idx > 10:\n break\n return ret\n\n\nseq2seq_data = '/home/vocust001/xly/ccc/seq2seq_data.json'\nlm_data = '/home/vocust001/xly/ccc/lm_data.json'\nmlm_data = '/home/vocust001/xly/ccc/mlm_data.json'\n\nprint('start reading data')\nseq2seq_data = get_data(seq2seq_data)\nlm_data = get_data(lm_data)\nmlm_data = get_data(mlm_data)\n\nseq2seq_data = DataLoader(KeyDataset(seq2seq_data), batch_size=batch_size, collate_fn=default_collate, shuffle=True)\nlm_data = DataLoader(KeyDataset(lm_data), batch_size=batch_size, collate_fn=default_collate, shuffle=True)\nmlm_data = DataLoader(KeyDataset(mlm_data), batch_size=batch_size, collate_fn=default_collate, shuffle=True)\n\nprint('finish loading data')\n\n\ndef create_lm_mask(attention_mask, direction='l2r'):\n seq_len = attention_mask.size(-1)\n if attention_mask.ndim == 2:\n attention_mask = attention_mask.view(-1, 1, seq_len)\n\n idxs = torch.arange(0, seq_len).to(attention_mask)\n if direction == 'l2r':\n triu = (idxs.unsqueeze(-1) >= idxs).float()\n elif direction == 'r2l':\n triu = (idxs.unsqueeze(-1) <= idxs).float()\n\n attention_mask = (attention_mask + triu > 1).float()\n return attention_mask\n\n\ndef create_unilm_mask(s):\n idxs = torch.cumsum(s, axis=1)\n mask = idxs[:, None, :] <= idxs[:, :, None]\n mask = mask.float()\n return mask\n\n\nclass UnilmForPreTraining(BertForPreTraining):\n def __init__(self, config):\n super().__init__(config)\n self.loss_fn = CrossEntropyLoss()\n\n def forward(self, input_ids, attention_mask, token_type_ids, *arg, **kwargs):\n prediction_scores, seq_relationship_score = super().forward(input_ids, attention_mask, token_type_ids)\n return prediction_scores, seq_relationship_score\n\n @classmethod\n def prepare_data_for_pretraining(self, batch, task, use_mlm=False):\n new_batch = batch\n if task == 'mlm':\n new_batch['input_ids'] = new_batch.pop('masked_input_ids')\n\n elif task == 'lm':\n new_batch['label_mask'] = new_batch.pop('attention_mask')\n if random.random() < 0.5:\n direction = 'l2r'\n else:\n direction = 'r2l'\n new_batch['attention_mask'] = create_lm_mask(new_batch['label_mask'], direction)\n new_batch['direction'] = direction\n\n elif task == 'seq2seq':\n new_batch['attention_mask'] = create_unilm_mask(new_batch.pop('attention_mask'))\n return new_batch\n\n @classmethod\n def compute_loss(self, logits, batch, task, direction=None):\n if task == 'mlm':\n mlm_logits, seq_logits = logits\n mlm_label = batch['mlm_labels']\n mask = mlm_label != 0\n mlm_loss = loss_fn(mlm_logits, mlm_label, mask)\n\n seq_label = batch['seq_label']\n seq_loss = loss_fn(seq_logits, seq_label, None)\n\n return mlm_loss + seq_loss\n\n elif task == 'seq2seq':\n logits, _ = logits\n label = batch['input_ids']\n logits = logits[:, :-1]\n label = label[:, 1:]\n loss = loss_fn(logits, label, batch['token_type_ids'][:, 1:])\n return loss\n\n elif task == 'lm':\n logits, _ = logits\n label = batch['input_ids']\n if direction == 'r2l':\n logits = logits[:, 1:]\n label = label[:, :-1]\n mask = batch['label_mask'][:, :-1]\n elif direction == 'l2r':\n logits = logits[:, :-1]\n label = label[:, 1:]\n mask = batch['label_mask'][:, 1:]\n loss = loss_fn(logits, label, mask)\n return loss\n\n\n## 训练\nmodel = UnilmForPreTraining.from_pretrained(model_path)\nmodel.to(device)\n\n\nparam_optimizer = list(model.named_parameters())\nno_decay = ['bias', 'LayerNorm.bias', 'LayerNorm.weight']\noptimizer_grouped_parameters = [\n {'params': [p for n, p in param_optimizer if not any(\n nd in n for nd in no_decay)], 'weight_decay': 0.01},\n {'params': [p for n, p in param_optimizer if any(\n nd in n for nd in no_decay)], 'weight_decay': 0.0}\n]\n\noptimizer = AdamW(optimizer_grouped_parameters, lr=lr, eps=adam_epsilon)\nscheduler = get_linear_schedule_with_warmup(optimizer, num_warmup_steps=1000, num_training_steps=steps)\n\nloss_fn = CrossEntropyLoss()\nscaler = amp.GradScaler()\n\n\nclass BatchData:\n def __init__(self):\n self.mlm = mlm_data\n self.lm = lm_data\n self.seq2seq = seq2seq_data\n\n self.data = {'mlm': self.mlm._get_iterator(),\n 'lm': self.lm._get_iterator(),\n 'seq2seq': self.seq2seq._get_iterator()}\n\n def get_next_batch(self):\n if random.random() <= 0.5:\n batch_name = 'mlm'\n elif random.random() <= 0.5:\n batch_name = 'lm'\n else:\n batch_name = 'seq2seq'\n try:\n return next(self.data[batch_name])\n except Exception as e:\n self.data[batch_name] = self.init_new_iter(batch_name)\n return next(self.data[batch_name])\n\n def init_new_iter(self, name):\n return getattr(self, name)._get_iterator()\n\n\ndata = BatchData()\nprogress = pkbar.Kbar(target=steps, width=25)\nprint_loss = 0\nfor step in range(steps * grad_accumulation_steps):\n raw_batch = data.get_next_batch()\n batch = raw_batch.copy()\n task = batch.pop('task')[0]\n batch = UnilmForPreTraining.prepare_data_for_pretraining(batch, task)\n direction = batch.pop('direction') if 'direction' in batch else None\n batch = {k: v.to(device) for k, v in batch.items()}\n logtis = model(**batch)\n loss = UnilmForPreTraining.compute_loss(logtis, batch, task, direction)\n loss = loss / grad_accumulation_steps\n print_loss += loss.item()\n loss.backward()\n\n if (step + 1) % grad_accumulation_steps == 0:\n optimizer.step()\n optimizer.zero_grad()\n scheduler.step()\n progress.update(step, values=[('loss: ', round(print_loss, 4))])\n print_loss = 0\n\n if (step+1) % (grad_accumulation_steps * save_every) == 0:\n save_name = 'model_step_{}_loss_{}'.format(step, round(print_loss, 4))\n torch.save(model.state_dict(), save_name)\n"
] | [
[
"torch.cuda.amp.GradScaler"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
katzkawai/stylecloud | [
"fd97e728e0bb2d9b0a791fb8d386ef34898da43e"
] | [
"stylecloud/stylecloud.py"
] | [
"from icon_font_to_png.icon_font import IconFont\nfrom wordcloud import WordCloud, STOPWORDS, ImageColorGenerator\nimport csv\nimport os\nfrom PIL import Image\nfrom matplotlib.colors import to_rgb\nimport numpy as np\nimport fire\nfrom shutil import rmtree\nfrom pkg_resources import resource_filename\nfrom typing import List, Union\n\nSTATIC_PATH = resource_filename(__name__, \"static\")\n\n\ndef file_to_text(file_path: str):\n \"\"\"\n Reads a text file, or if the file is a .csv,\n read as a dict of word/weights.\n \"\"\"\n\n if not file_path.endswith(\".csv\"):\n with open(file_path, \"r\", encoding=\"utf-8\") as f:\n text = f.read()\n return text\n else: # parse as a CSV\n\n with open(file_path, \"r\", encoding=\"utf-8\") as f:\n r = csv.reader(f)\n header = next(r)\n assert len(header) <= 2, \"The input CSV has too many columns.\"\n\n # If a single-column CSV, read as a bulk text\n if len(header) == 1:\n texts = \"\"\n for row in r:\n texts += row[0] + \"\\n\"\n # If a two-column CSV, read as words/weights\n elif len(header) == 2:\n texts = {}\n for row in r:\n texts[row[0]] = float(row[1])\n return texts\n\n\ndef gen_fa_mask(\n icon_name: str = \"fas fa-grin\",\n size: int = 512,\n icon_dir: str = \".temp\",\n pro_icon_path: str = None,\n pro_css_path: str = None,\n):\n \"\"\"\n Generates a Font Awesome icon mask from the given FA prefix + name.\n \"\"\"\n\n # FA prefixes which map to a font file.\n font_files = {\n \"fas\": \"fa-solid-900.ttf\",\n \"far\": \"fa-regular-400.ttf\",\n \"fab\": \"fa-brands-400.ttf\",\n }\n\n icon_prefix = icon_name.split(\" \")[0]\n icon_name_raw = icon_name.split(\" \")[1]\n\n css_path = pro_css_path or os.path.join(STATIC_PATH, \"fontawesome.min.css\")\n ttf_path = pro_icon_path or os.path.join(STATIC_PATH, font_files[icon_prefix])\n\n icon = IconFont(css_file=css_path, ttf_file=ttf_path)\n\n # If a length and width are provided, make icon the smaller of the two\n if isinstance(size, tuple):\n size = min(size)\n\n icon.export_icon(\n icon=icon_name_raw[len(icon.common_prefix) :],\n size=size,\n filename=\"icon.png\",\n export_dir=icon_dir,\n )\n\n\ndef gen_palette(palette: str):\n \"\"\"Generates the corresponding palette function from `palettable`.\"\"\"\n palette_split = palette.split(\".\")\n palette_name = palette_split[-1]\n\n # https://stackoverflow.com/a/6677505\n palette_func = getattr(\n __import__(\n \"palettable.{}\".format(\".\".join(palette_split[:-1])),\n fromlist=[palette_name],\n ),\n palette_name,\n )\n return palette_func\n\n\ndef gen_mask_array(icon_dir: str, invert_mask: bool, size: int):\n \"\"\"Generates a numpy array of an icon mask.\"\"\"\n icon = Image.open(os.path.join(icon_dir, \"icon.png\"))\n\n if isinstance(size, int):\n size = (size, size)\n\n # https://stackoverflow.com/a/2563883\n icon_w, icon_h = icon.size\n icon_mask = Image.new(\"RGBA\", icon.size, (255, 255, 255, 255))\n icon_mask.paste(icon, icon)\n mask = Image.new(\"RGBA\", size, (255, 255, 255, 255))\n mask_w, mask_h = mask.size\n offset = ((mask_w - icon_w) // 2, (mask_h - icon_h) // 2)\n mask.paste(icon_mask, offset)\n mask_array = np.array(mask, dtype=\"uint8\")\n\n if invert_mask:\n mask_array = np.invert(mask_array)\n\n return mask_array\n\n\ndef gen_gradient_mask(\n size: int,\n palette: str,\n icon_dir: str = \".temp\",\n gradient_dir: str = \"horizontal\",\n invert_mask: bool = False,\n):\n \"\"\"Generates a gradient color mask from a specified palette.\"\"\"\n mask_array = gen_mask_array(icon_dir, invert_mask, size)\n mask_array = np.float32(mask_array)\n\n palette_func = gen_palette(palette)\n gradient = palette_func.mpl_colormap(np.linspace(0.0, 1.0, size))\n\n # matplotlib color maps are from range of (0, 1). Convert to RGB.\n gradient *= 255.0\n\n # Add new axis and repeat gradient across it.\n gradient = np.tile(gradient, (size, 1, 1))\n\n # if vertical, transpose the gradient.\n if gradient_dir == \"vertical\":\n gradient = np.transpose(gradient, (1, 0, 2))\n\n # Turn any nonwhite pixels on the icon into the gradient colors.\n white = (255.0, 255.0, 255.0, 255.0)\n mask_array[mask_array != white] = gradient[mask_array != white]\n\n image_colors = ImageColorGenerator(mask_array)\n return image_colors, np.uint8(mask_array)\n\n\ndef color_to_rgb(color):\n \"\"\"Converts a color to a RGB tuple from (0-255).\"\"\"\n if isinstance(color, tuple):\n # if a RGB tuple already\n return color\n else:\n # to_rgb() returns colors from (0-1)\n color = tuple(int(x * 255) for x in to_rgb(color))\n return color\n\n\ndef gen_stylecloud(\n text: str = None,\n file_path: str = None,\n size: int = 512,\n icon_name: str = \"fas fa-flag\",\n palette: str = \"cartocolors.qualitative.Bold_5\",\n colors: Union[str, List[str]] = None,\n background_color: str = \"white\",\n max_font_size: int = 200,\n max_words: int = 2000,\n stopwords: bool = True,\n custom_stopwords: Union[List[str], set] = STOPWORDS,\n add_stopwords: bool = False,\n icon_dir: str = \".temp\",\n output_name: str = \"stylecloud.png\",\n gradient: str = None,\n font_path: str = os.path.join(STATIC_PATH, \"Staatliches-Regular.ttf\"),\n random_state: int = None,\n collocations: bool = True,\n invert_mask: bool = False,\n pro_icon_path: str = None,\n pro_css_path: str = None,\n):\n \"\"\"Generates a stylecloud!\n :param text: Input text. Best used if calling the function directly.\n :param file_path: File path of the input text/CSV. Best used on the CLI.\n :param size: Size (length and width in pixels) of the stylecloud.\n :param icon_name: Icon Name for the stylecloud shape. (e.g. 'fas fa-grin')\n :param palette: Color palette (via palettable)\n :param colors: Custom color(s) for text (name or hex). Overrides palette.\n :param background_color: Background color (name or hex).\n :param max_font_size: Maximum font size in the stylecloud.\n :param max_words: Maximum number of words to include in the stylecloud.\n :param stopwords: Boolean to filter out common stopwords.\n :param custom_stopwords: list of custom stopwords.\n :param add_stopwords: Whether to use custom_stopwords to add to default\n :param icon_dir: Temp directory to store the icon mask image.\n :param output_name: Output file name of the stylecloud.\n :param gradient: Direction of gradient. (if not None, will use gradient)\n :param font_path: Path to .ttf file for font to use in stylecloud.\n :param random_state: Controls random state of words and colors.\n :param collocations: Whether to include collocations (bigrams) of two words.\n :param invert_mask: Whether to invert the icon mask.\n :param pro_icon_path: Path to Font Awesome Pro .ttf file if using FA Pro.\n :param pro_css_path: Path to Font Awesome Pro .css file if using FA Pro.\n \"\"\"\n\n assert any([text, file_path]), \"Either text or file_path must be specified.\"\n\n if file_path:\n text = file_to_text(file_path)\n\n gen_fa_mask(icon_name, size, icon_dir, pro_icon_path, pro_css_path)\n\n if gradient and colors is None:\n pal_colors, mask_array = gen_gradient_mask(\n size, palette, icon_dir, gradient, invert_mask\n )\n else: # Color each word randomly from the palette\n mask_array = gen_mask_array(icon_dir, invert_mask, size)\n if colors:\n # if specifying a single color string\n if isinstance(colors, str):\n colors = [colors]\n\n # iterate through each color to ensure correct RGB format.\n # see matplotlib docs on how colors are decoded:\n # https://matplotlib.org/3.1.1/api/colors_api.html\n colors = [color_to_rgb(color) for color in colors]\n\n else:\n palette_func = gen_palette(palette)\n colors = palette_func.colors\n\n def pal_colors(word, font_size, position, orientation, random_state, **kwargs):\n rand_color = np.random.randint(0, len(colors))\n return tuple(colors[rand_color])\n\n if add_stopwords:\n custom_stopwords.extend(STOPWORDS)\n\n # cleanup icon folder\n rmtree(icon_dir)\n\n wc = WordCloud(\n background_color=background_color,\n font_path=font_path,\n max_words=max_words,\n mask=mask_array,\n stopwords=custom_stopwords if stopwords else None,\n max_font_size=max_font_size,\n random_state=random_state,\n collocations=collocations,\n )\n\n # generate word cloud\n if isinstance(text, str):\n wc.generate_from_text(text)\n else: # i.e. a dict of word:value from a CSV\n if stopwords: # manually remove stopwords since otherwise ignored\n text = {k: v for k, v in text.items() if k not in custom_stopwords}\n wc.generate_from_frequencies(text)\n wc.recolor(color_func=pal_colors, random_state=random_state)\n wc.to_file(output_name)\n\n\ndef stylecloud_cli(**kwargs):\n \"\"\"Entrypoint for the stylecloud CLI.\"\"\"\n fire.Fire(gen_stylecloud)\n"
] | [
[
"matplotlib.colors.to_rgb",
"numpy.invert",
"numpy.linspace",
"numpy.uint8",
"numpy.tile",
"numpy.float32",
"numpy.transpose",
"numpy.array"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
pacargile/MINESweeper_V2.0 | [
"db01e92e797e7f07f32931bec42396a1d470bfa8"
] | [
"minesweeper/MISTmod.py"
] | [
"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\"\"\"\nContains class to generate all predicted model parameters from sample of \nstellar parameters.\n\"\"\"\n\nimport os\nimport numpy as np\nimport warnings\nwith warnings.catch_warnings():\n warnings.simplefilter('ignore')\n import h5py\nfrom scipy.spatial import KDTree as KDTree\nfrom scipy.interpolate import LinearNDInterpolator\n\nfrom numpy.lib import recfunctions\nimport minesweeper\n\n# # define aliases for the MIST EEP tracks\n# currentpath = __file__\n# if currentpath[-1] == 'c':\n# removeind = -27\n# else:\n# removeind = -26\n# MISTFILE_DEFAULT = os.path.dirname(__file__[:removeind]+'data/MIST/')\n\n# the array of parameters stored in object. Not full eep track\n# due to memory concerns\n\n# inpararr = ([\n# 'EEP','initial_mass','initial_[Fe/H]','initial_[a/Fe]',\n# 'log_age','star_mass','log_R','log_L',\n# 'log_Teff','[Fe/H]','log_g',\n# ])\n# renameparr = ([\n# 'EEP','initial_mass','initial_[Fe/H]','initial_[a/Fe]',\n# 'log(Age)','Mass','log(Rad)','log(L)',\n# 'log(Teff)','[Fe/H]','log(g)',\n# ])\n\n# dictionary to translate par names to MIST names\nMISTrename = {\n 'log(Age)':'log_age',\n 'Mass':'star_mass',\n 'log(R)':'log_R',\n 'log(L)':'log_L',\n 'log(Teff)':'log_Teff',\n 'log(g)':'log_g',\n}\n\nclass GenMIST(object):\n \"\"\"\n The basic class to geneate predicted parameters from the MIST models \n from a set of EEP/initial_mass/initial_[Fe/H]/initial_[a/Fe] \n when using isochrones, (or in the future \n Teff/log(g)/[Fe/H]/[a/Fe] parameters from the Payne).\n\n\n \"\"\"\n def __init__(self,**kwargs):\n super(GenMIST, self).__init__()\n\n # check for a user defined model\n self.mistfile = kwargs.get('model',None)\n\n mistfile = kwargs.get('MISTpath',None)\n if mistfile is None:\n self.mistfile = minesweeper.__abspath__+'data/MIST/MIST_2.0_EEPtrk.h5'\n # self.mistfile = \n else:\n self.mistfile = mistfile\n # else:\n # # define aliases for the MIST isochrones and C3K/CKC files\n # currentpath = __file__\n # if currentpath[-1] == 'c':\n # removeind = -27\n # else:\n # removeind = -26\n # self.MISTpath = os.path.dirname(__file__[:removeind]+'data/MIST/')\n\n # self.mistfile = self.MISTpath+'/MIST_1.2_EEPtrk.h5'\n\n self.verbose = kwargs.get('verbose',True)\n\n # turn on age weighting\n self.ageweight = kwargs.get('ageweight',True)\n\n # list of values you want to interpolate over\n self.labels = kwargs.get('labels',['EEP','initial_mass','initial_[Fe/H]','initial_[a/Fe]'])\n\n # list of output parametrs you want from MIST \n # in addition to EEP, init_mass, init_FeH\n self.predictions = kwargs.get('predictions',\n ['log(Age)','Mass','log(R)','log(L)',\n 'log(Teff)','[Fe/H]','[a/Fe]','log(g)'])\n if type(self.predictions) == type(None):\n self.predictions = (['log(Age)','Mass','log(R)',\n 'log(L)','log(Teff)','[Fe/H]','[a/Fe]','log(g)'])\n\n if self.verbose:\n print('Using Model: {0}'.format(self.mistfile))\n\n # read in HDF5 model\n misth5 = h5py.File(self.mistfile,'r')\n\n # build MIST object to eventually stick into interpolator\n self.modpararr = self.labels+self.predictions\n trans_modpararr = [MISTrename[x] if x in MISTrename.keys() else x for x in self.modpararr]\n for kk in misth5['index']:\n # read in MIST array\n mist_i = np.array(misth5[kk])\n mist_i = mist_i[trans_modpararr]\n\n if kk == misth5['index'][0]:\n self.mist = mist_i.copy()\n else:\n self.mist = np.concatenate([self.mist,mist_i])\n\n if self.ageweight:\n # print('... Fitting w/ equal Age weighting')\n self.predictions.append('Agewgt')\n self.modpararr.append('Agewgt')\n\n # build KD-Tree\n if self.verbose:\n print('Growing the KD-Tree...')\n # determine unique values in grid\n self.eep_uval = np.unique(self.mist['EEP'])\n self.mass_uval = np.unique(self.mist['initial_mass'])\n self.feh_uval = np.unique(self.mist['initial_[Fe/H]'])\n self.afe_uval = np.unique(self.mist['initial_[a/Fe]'])\n\n # calculate min and max values for each of the sampled arrays\n self.minmax = {}\n self.minmax['EEP'] = [self.eep_uval.min(), self.eep_uval.max()]\n self.minmax['MASS'] = [self.mass_uval.min(),self.mass_uval.max()]\n self.minmax['FEH'] = [self.feh_uval.min(),self.feh_uval.max()]\n self.minmax['AFE'] = [self.afe_uval.min(),self.afe_uval.max()]\n\n # determine difference between unique values\n self.eep_diff = np.diff(self.eep_uval)\n self.mass_diff = np.diff(self.mass_uval)\n self.feh_diff = np.diff(self.feh_uval)\n self.afe_diff = np.diff(self.afe_uval)\n\n # determine which unique grid point each EEP point belongs to\n self.eep_dig = np.digitize(self.mist['EEP'],bins=self.eep_uval,right=True)\n self.mass_dig = np.digitize(self.mist['initial_mass'],bins=self.mass_uval,right=True)\n self.feh_dig = np.digitize(self.mist['initial_[Fe/H]'],bins=self.feh_uval,right=True)\n self.afe_dig = np.digitize(self.mist['initial_[a/Fe]'],bins=self.afe_uval,right=True)\n\n # combine digitized arrays\n self.pts_n = np.array([self.eep_dig,self.mass_dig,self.feh_dig,self.afe_dig]).T\n\n # build tree and set distance metric (2-pts)\n self.tree = KDTree(self.pts_n)\n searchrad = 2.0\n self.dist = np.sqrt( \n (searchrad**2.0) + \n (searchrad**2.0) + \n (searchrad**2.0) + \n (searchrad**2.0))\n\n # create stacked array for interpolation\n cols = [MISTrename[x] if x in MISTrename.keys() else x for x in self.predictions]\n self.valuestack = np.stack(\n [self.mist[kk] for kk in cols],\n axis=1)\n\n\n def getMIST(self,eep=300,mass=1.0,feh=0.0,afe=0.0,**kwargs):\n if 'verbose' in kwargs:\n verbose = kwargs['verbose']\n else:\n verbose = True\n\n # unbind the input pars\n # eep = pars[0]\n # mass = pars[1]\n # feh = pars[2]\n\n # check to make sure pars are within bounds of EEP tracks\n if ((eep > self.minmax['EEP'][1]) or \n (eep < self.minmax['EEP'][0]) or \n (mass > self.minmax['MASS'][1]) or \n (mass < self.minmax['MASS'][0]) or \n (feh > self.minmax['FEH'][1]) or\n (feh < self.minmax['FEH'][0]) or\n (afe > self.minmax['AFE'][1]) or\n (afe < self.minmax['AFE'][0])\n ):\n if verbose:\n print('HIT MODEL BOUNDS')\n return None\n\n # build output dictionary to handle everything\n outpred = []\n\n # stick in input pars\n outpred.append(eep)\n outpred.append(mass)\n outpred.append(feh)\n outpred.append(afe)\n\n # # check to see if user is passing Dist and Av, if so stick it into moddict as well\n # if len(pars) > 3:\n # moddict['Dist'] = pars[3]\n # moddict['Av'] = pars[4]\n\n ind_eep = np.digitize(eep,bins=self.eep_uval,right=False)-1\n ind_mass = np.digitize(mass,bins=self.mass_uval,right=False)-1\n ind_feh = np.digitize(feh,bins=self.feh_uval,right=False)-1\n ind_afe = np.digitize(afe,bins=self.afe_uval,right=False)-1\n\n find_eep = ((eep-self.eep_uval[ind_eep])/self.eep_diff[ind_eep]) + ind_eep\n find_mass = ((mass-self.mass_uval[ind_mass])/self.mass_diff[ind_mass]) + ind_mass\n find_feh = ((feh-self.feh_uval[ind_feh])/self.feh_diff[ind_feh]) + ind_feh\n find_afe = ((afe-self.afe_uval[ind_afe])/self.afe_diff[ind_afe]) + ind_afe\n\n KDTind = self.tree.query_ball_point(\n [find_eep,find_mass,find_feh,find_afe],\n self.dist,\n p=1,eps=3)\n\n # pull from the value stack\n valuestack_i = self.valuestack[KDTind]\n\n # pull from the MIST isochrones\n KDTpars = self.mist[KDTind]\n\n # check to make sure there are at least two points in each dimension\n for testkk in ['EEP','initial_mass','initial_[Fe/H]','initial_[a/Fe]']:\n if len(np.unique(KDTpars[testkk])) < 2:\n if verbose:\n print('Not enough points in KD-Tree sample')\n return None\n\n # do the linear N-D interpolation\n try:\n dataint = LinearNDInterpolator(\n (KDTpars['EEP'],KDTpars['initial_mass'],KDTpars['initial_[Fe/H]'],KDTpars['initial_[a/Fe]']),\n valuestack_i,\n fill_value=np.nan_to_num(-np.inf),\n rescale=True\n )(eep,mass,feh,afe)\n except:\n if verbose:\n print('Problem with linear inter of KD-Tree sample')\n print(min(KDTpars['EEP']),max(KDTpars['EEP']),\n min(KDTpars['initial_mass']),max(KDTpars['initial_mass']),\n min(KDTpars['initial_[Fe/H]']),max(KDTpars['initial_[Fe/H]']),\n min(KDTpars['initial_[a/Fe]']),max(KDTpars['initial_[a/Fe]'])\n )\n print (eep,lage,feh,afe)\n return None\n\n # stick interpolated pars into outpred list\n for dd in dataint:\n if dd != np.nan_to_num(-np.inf):\n outpred.append(dd)\n else:\n if verbose:\n print('Tried to extrapolate')\n return None\n\n # # stick interpolated pars into moddict\n # for ii,pp in enumerate(KDTpars.dtype.names):\n # if dataint[ii] != np.nan_to_num(-np.inf):\n # if pp not in ['EEP','initial_mass','initial_[Fe/H]']:\n # moddict[pp] = dataint[ii]\n # else:\n # if verbose:\n # print('Tried to extrapolate')\n # return 'ValueError'\n\n return outpred"
] | [
[
"numpy.sqrt",
"numpy.unique",
"numpy.nan_to_num",
"numpy.stack",
"numpy.concatenate",
"scipy.spatial.KDTree",
"numpy.diff",
"numpy.digitize",
"numpy.array"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [
"1.7",
"1.0",
"0.10",
"1.2",
"0.14",
"0.19",
"1.5",
"0.12",
"0.17",
"0.13",
"1.6",
"1.4",
"1.9",
"1.3",
"1.10",
"0.15",
"0.18",
"0.16",
"1.8"
],
"tensorflow": []
}
] |
alistairjwilson/nrmpInterviews_SimData | [
"8c99ff0d9a4e9db70dec5f7ef92b98054bf42a83"
] | [
"500SIGS/Code to Run SIGS only/Sim500_5_25_25.py"
] | [
"# -*- coding: utf-8 -*-\n\"\"\"faster_simulations_sigs_revised.ipynb\n\nAutomatically generated by Colaboratory.\n\nOriginal file is located at\n https://colab.research.google.com/drive/1_-oQDQXJCYRE3JnPBMlYaLIdoBOpX25f\n\"\"\"\n\nimport numpy as np\nimport pandas as pd\n\nclass Worker(object):\n name = \"\"\n p = [] #original preferences, list of strings of names of hospitals ranked, unchanged\n p_dict = {} # same as p but as a mapping of hospital name to ranking in p\n ranking = [] #list of strings of names of hospitals ranked\n matchings = [] #list of hospitals that worker is matched to, t-algorithm\n wishes = [] #list of names of hospitals used in Gale-Shapley algorithm as rankings submitted\n wishes_dict = {} # same as above but a dictionary mapping name to ranking in p'\n current = None #hospital that worker is currently matched to in Gale-Shapley algorithm\n interviews = [] #simulated interviews, list of hospitals\n choices = [] #list of hospitals that worker wants to interview with, ranked\n pref = [] # this is the total utilities that hospitals provide this worker\n \n def __init__(self, cu, name, we,n):\n ''' \n cu is common utility\n name is in format WN where N is a number\n we is the weight for common utility\n n is the number of hospitals\n '''\n self.name=name\n self.generateP(cu, we, n)\n self.start()\n \n def start(self):\n ''' sets starting conditions '''\n self.match([])\n self.matchings = []\n self.wishes = []\n self.setWishes()\n self.interviews = []\n self.current = None\n \n def generateP(self,cu,we,n): \n ''' generates the preferences p using cu and iu'''\n self.pref = [np.random.normal(0,1) * (1 - we) + cu[x] * we for x in range(n)] #creates array with weighted utility for firms with common utility weighed 60% and idiosyncratic utility weighed 40%\n self.ranking=[\"H\" + str(x + 1) for x in range(n)]\n \n # ranks hospitals based on their weighted utility, highest utility ranked first\n self.pref, self.ranking = self.fastersort(self.pref, self.ranking)\n\n self.p = []\n self.p_dict = {}\n index = 1\n for x in self.ranking:\n self.p.append(x)\n self.p_dict[x] = index\n index += 1\n\n def setChoices(self, hospitals): \n ''' sets choices with ranked list of hospitals '''\n self.choices = []\n for h in self.p:\n self.choices.append(self.getEq(h, hospitals))\n \n def generateP2(self,cu,n):\n ''' generates the preferences using cu only'''\n self.ranking= [\"H\" + str(x + 1) for x in range(n)]\n pref = []\n for c in cu:\n pref.append(c)\n \n pref, self.ranking = self.fastersort(pref, self.ranking)\n\n self.p_dict = {}\n index = 1\n for x in self.ranking:\n self.p_dict[x] = index\n index += 1\n\n def fastersort(self, pref, ranking):\n return zip(*sorted(zip(pref, ranking), reverse=True))\n\n def bubblesort(self, pref, ranking):\n ''' sorts/ranks the hospitals based on the preferences'''\n for i in range(len(pref)):\n for k in range(len(pref) - 1, i, -1):\n if(pref[k] > pref[k - 1]):\n self.swap(pref, ranking, k, k - 1)\n \n def swap(self, pref, ranking, x, y):\n ''' helper function for the bubble sort that swaps two hospitals in ranking '''\n temp1 = pref[x]\n temp2 = ranking[x]\n pref[x] = pref[y]\n ranking[x] = ranking[y]\n pref[y] = temp1\n ranking[y] = temp2\n \n def checkAvailability(self, goal, agent):\n '''\n agent is a hospital\n goal is number of desired matchings in T-algorithm (max number of interviews for hospitals)\n returns True if hospital is available, False otherwise\n '''\n if(not agent.getMatchings() or len(agent.getMatchings())<goal):\n return True\n \n if(len(agent.getMatchings())>goal):\n x = (agent.getMatchings()[:goal])[-1]\n else:\n x = agent.getMatchings()[-1]\n \n ranking = agent.getP_dict()\n \n return ranking[self.getName()] <= ranking[x.getName()]\n \n def getOldRank(self, agent, other=None):\n index = 1\n for a in agent.getRanking():\n if other is not None and a == other.getName():\n return index\n elif other is None and a == self.getName():\n return index\n index += 1\n \n def proposed(self): \n ''' simulates a worker proposing'''\n if(len(self.wishes) > 0):\n self.wishes = self.wishes[1:]\n \n def getEq(self, n, hospitals): \n ''' returns hospital with certain name (Hn)'''\n for h in hospitals:\n if(h.getName() == n):\n return h\n return None\n \n def getOrig(self):\n ''' return the original (untruncated) preference p '''\n return self.p\n \n def getHospitalUtilities(self):\n '''Returns the utilities that hospitals provide this worker, sorted in the \n Same order as p (so in decreasing total utility)'''\n return self.pref\n \n def getTotalUtilityByHospital(self, hospital_name):\n for i in range(len(self.p)):\n if (self.p[i] == hospital_name):\n return self.pref[i]\n \n def setOrig(self, op):\n ''' set the original preference p'''\n self.ranking = []\n self.p = []\n self.p_dict = {}\n index = 1\n for o in op:\n self.ranking.append(o)\n self.p.append(o)\n self.p_dict[o] = index\n index +=1 \n \n def getPref(self, hospitals):\n ''' returns the top unproposed hospital for this worker '''\n h = self.getEq(self.wishes[0], hospitals)\n self.proposed()\n return h\n\n def getP_dict(self):\n return self.p_dict\n\n def match(self, avail): \n '''\n avail is list of hospitals that are available for this worker\n function matches worker to these hospitals\n '''\n self.matchings = []\n for m in avail:\n self.matchings.append(m)\n \n def judge(self, h): \n '''\n Used in Gale-Shapley algorithm when hospitals propose\n Returns rejected hospital if any (so if None returned, then matched for now)\n '''\n if(len(self.wishes) == 1 and self.wishes[0] != h.getName()):\n return h\n x = None\n for i in range(len(self.wishes)):\n if(self.wishes[i] == h.getName()):\n self.wishes = self.wishes[:i + 1]\n if(self.current is not None):\n self.current.setMatch(None)\n x = self.current\n self.current = h\n h.setMatch(self)\n return x\n \n return h\n \n def interview(self, h):\n self.interviews.append(h)\n \n def getTopChoice(self): \n ''' Returns top choice hospital unproposed to \n And removes it from unproposed choices list '''\n h = self.choices[0]\n self.choices = self.choices[1:]\n return h\n \n def setMatch(self, h):\n ''' this is used in Gale-Shapley to set deferred acceptance match for this worker, h is hospital '''\n self.current = h\n \n def setWishes(self): \n ''' sets rankings (wishes) for Gale-shapley algorithm based on matchings produced by T-algorithm'''\n self.wishes = []\n self.wishes_dict = {}\n index = 1\n for r in self.matchings:\n self.wishes.append(r.getName())\n self.wishes_dict[r.getName()] = index\n index += 1\n \n def setWishes2(self): \n ''' sets rankings(wishes) for Gale-Shapley algorithm based on original preferences '''\n self.wishes = []\n self.wishes_dict = {}\n index = 1\n for r in self.ranking:\n self.wishes.append(r)\n self.wishes_dict[r] = index\n index += 1\n \n def setWishes3(self, max_interviews=5): \n ''' sets rankings(wishes) for Gale-Shapley algorithm based on truncated original preferences (top 5)'''\n self.wishes = []\n self.wishes_dict = {}\n index = 1\n for r in self.ranking:\n self.wishes.append(r)\n self.wishes_dict[r] = index\n index += 1\n # Note: change the 5 below to change the length of truncated preferences\n self.wishes=self.wishes[:max_interviews]\n \n def setWishes4(self):\n ''' sets rankings (wishes) for gale shapley algorithm based on matchings from simulated interviews'''\n self.wishes = []\n self.matchings = []\n self.wishes_dict = {}\n index = 1\n for r in self.interviews:\n self.wishes.append(r.getName())\n self.matchings.append(r)\n self.wishes_dict[r.getName()] = index\n index += 1\n \n def checkBlocking(self, h2): \n ''' returns number of blocking pairs contain this worker '''\n count = 0\n for h in self.p:\n if(self.current is not None and h == self.current.getName()):\n return count\n if(self.getEq(h, h2).block(self)):\n count += 1\n return count\n \n def checkBlocking2(self,h2):\n ''' returns number of blocking pairs that contain this worker, but only blocking pairs where both agents are matched'''\n count = 0\n if(self.current is None):\n return 0\n for h in self.p:\n if(h == self.current.getName()):\n return count\n if(self.getEq(h, h2).block2(self)):\n count += 1\n return count\n \n def block(self, h): \n ''' returns True if this worker with h is a blocking pair '''\n if(self.current is None): #since every hospital is ranked in p, then if worker is unmatched it prefers h to being unmatched\n return True\n \n for h2 in self.p:\n if(h2 == self.current.getName()):\n return False\n if(h2 == h.getName()):\n return True\n return False\n\n def getInterviews(self):\n return self.interviews\n \n def getChoices(self):\n return self.choices\n \n def getName(self): \n ''' returns string with name in form Wn where n is number '''\n return self.name\n \n def getMatchings(self): \n ''' returns list of hospitals '''\n return self.matchings\n \n def getRanking(self): \n ''' returns list of strings of names of hospitals ranked '''\n return self.ranking\n \n def getWishes(self): \n ''' returns list of strings of names of hospitals that will be ranked '''\n return self.wishes\n \n def getCurrent(self): \n ''' returns current match (hospital) during Gale Shapley algorithm '''\n return self.current\n \n# note that the hospital class is identical since roles during T-algorithm and Gale-Shapley can be switched depending on who's proposing\n\n\n\nclass Hospital(object):\n name = \"\"\n p = [] #original preferences, list of strings of names of workers ranked, unchanged\n p_dict = {} # same as above but as a dictionary\n ranking = [] #list of strings of names of workers ranked\n matchings = [] #list of workers that hospital is matched to, t-algorithm\n wishes = [] #list of names of workers used in Gale-Shapley algorithm as rankings submitted\n wishes_dict = {} # same as above but as dictionary\n current = None #worker that hospital is currently matched to in Gale-Shapley algorithm assuming One-to-One matching\n interviews = [] #simulated interviews, list of doctors\n iu = [] #idiosyncratic utility that workers provide for this hospital\n iu_sorted = [] # idiosyncratic utility that workers provide for this hospital, in same order as p\n utilities_sorted = [] # combination of idiosyncratic and common utility, in same order as p\n cu_sorted = [] # common utility, in same order as p\n cu_unsorted = [] # cuw in original order, used to sort other lists in same order\n \n def __init__(self, cu, name,we,n):\n '''\n Cu is common utility\n Name is in format HN where N is number\n we is weight for common utility\n n is number of doctors\n '''\n self.name = name\n self.iu = []\n self.iu_sorted = []\n self.utilities_sorted = []\n self.cu_sorted = []\n self.cu_unsorted = []\n self.generateP(cu, we, n)\n self.start()\n self.interviews = []\n \n def start(self): \n ''' sets starting conditions '''\n self.match([])\n self.matchings = []\n self.wishes = []\n self.setWishes()\n self.current = None\n \n def generateP(self,cu,we,n): \n ''' this generates p using cu and iu (common and idiosyncratic utility weights)'''\n # First, let's store this order of common utility\n self.cu_unsorted = [c for c in cu] \n\n self.iu = [np.random.normal(0, 1) for x in range(n)]\n self.iu_sorted = [x for x in self.iu]\n self.utilities_sorted = []\n self.cu_sorted = [x for x in cu]\n pref = [self.iu[x] * (1 - we) + cu[x] * we for x in range(n)] #creates array with weighted utility for workers with common utility weighed 70% and idiosyncratic utility weighed 30%\n for x in pref:\n self.utilities_sorted.append(x)\n self.ranking = [\"W\" + str(x + 1) for x in range(n)]\n # ranks hospitals based on their weighted utility, highest utility ranked first\n pref, self.ranking = self.fastersort(pref, self.ranking)\n\n self.p = []\n self.p_dict = {}\n index = 1\n for x in self.ranking:\n self.p.append(x)\n self.p_dict[x] = index\n index += 1\n # now we also sort iu, cu, and total utility that doctors provide in order of decreasing cu (so doctor with highest cu is first)\n # the commented out lines below can be used to check that outcome is consistent with previous sorting method\n #cu_sorted_copy = [item for item in self.cu_sorted]\n #iu_sorted_copy = [item for item in self.iu_sorted]\n #utilities_sorted_copy = [item for item in self.utilities_sorted]\n #self.bubblesort2(cu_sorted_copy, iu_sorted_copy, utilities_sorted_copy)\n\n self.cu_sorted, self.iu_sorted, self.utilities_sorted = self.fastersort2(self.cu_sorted, self.iu_sorted, self.utilities_sorted)\n \n #for a, b in zip(cu_sorted_copy, self.cu_sorted):\n # assert a == b, f\"Old {a}, New: {b}\" \n\n #for a, b in zip(iu_sorted_copy, self.iu_sorted):\n # assert a == b, f\"Old {a}, New: {b}\"\n \n #for a, b in zip(utilities_sorted_copy, self.utilities_sorted):\n # assert a == b, f\"Old {a}, New: {b}\"\n \n def generateP2(self,cu,n): \n ''' this generates p using cu only '''\n self.ranking = [\"W\" + str(x + 1) for x in range(n)]\n pref = []\n for c in cu:\n pref.append(c)\n\n self.cu_unsorted = [c for c in cu]\n\n pref, self.ranking = self.fastersort(pref, self.ranking)\n\n self.p = []\n self.p_dict = {}\n index = 1\n for x in self.ranking:\n self.p.append(x)\n self.p_dict[x] = index\n index += 1\n \n def fastersort(self, pref, ranking):\n return zip(*sorted(zip(pref, ranking), reverse=True))\n \n def bubblesort(self, pref, ranking):\n ''' used to get the rankings from the preferences '''\n for i in range(len(pref)):\n for k in range(len(pref) - 1, i, -1):\n if(pref[k] > pref[k - 1]):\n self.swap(pref, ranking, k, k - 1)\n \n def bubblesort2(self, cu, iu, u):\n ''' used to get the rankings from the preferences '''\n for i in range(len(cu)):\n for k in range(len(cu) - 1, i, -1):\n if(cu[k] > cu[k - 1]):\n self.swap2(cu, iu, u, k, k - 1)\n\n def fastersort2(self, pref, ranking1, ranking2):\n return zip(*sorted(zip(pref, ranking1, ranking2), reverse=True))\n\n def swap(self, pref, ranking, x, y):\n ''' helper function for bubble sort'''\n temp1 = pref[x]\n temp2 = ranking[x]\n pref[x] = pref[y]\n ranking[x] = ranking[y]\n pref[y] = temp1\n ranking[y] = temp2\n \n def swap2(self, cu, iu, u, x, y):\n ''' helper function for bubble sort'''\n temp1 = cu[x]\n temp2 = iu[x]\n temp3 = u[x]\n\n cu[x] = cu[y]\n iu[x] = iu[y]\n u[x] = u[y]\n\n cu[y] = temp1\n iu[y] = temp2\n u[y] = temp3\n\n def checkAvailability(self, goal, agent):\n '''\n agent is a worker\n goal is number of desired matchings in T-algorithm (max number of interviews for hospitals)\n returns True if hospital is available, False otherwise\n '''\n if(not agent.getMatchings() or len(agent.getMatchings()) < goal):\n return True\n if(len(agent.getMatchings()) > goal):\n x = (agent.getMatchings()[:goal])[-1]\n else:\n x = agent.getMatchings()[-1]\n\n ranking = agent.getP_dict()\n return ranking[self.getName()] <= ranking[x.getName()]\n \n def getOldRank(self, agent, other=None):\n index = 1\n for a in agent.getRanking():\n if other is not None and a == other.getName():\n return index\n elif other is None and a == self.getName():\n return index\n index += 1\n \n def proposed(self):\n ''' simulates a hospital proposing '''\n if(len(self.wishes) > 0):\n self.wishes = self.wishes[1:]\n \n def interview(self, w):\n self.interviews.append(w)\n \n def getEq(self, n, workers): \n ''' returns worker with certain name '''\n for w in workers:\n if(w.getName() == n):\n return w\n return None\n \n def getPref(self,workers):\n ''' returns the top unproposed worker for this hospital '''\n w = self.getEq(self.wishes[0], workers)\n self.proposed()\n return w\n \n def getP_dict(self):\n return self.p_dict\n\n def match(self, avail): \n ''' avail is list of workers that are available for this hospital\n this function matches hospital to those workers'''\n self.matchings = []\n for m in avail:\n self.matchings.append(m)\n \n def judge(self,w): \n ''' used in Gale-Shapley algorithm when workers propose\n returns rejected worker if any '''\n if(len(self.wishes) == 1 and self.wishes[0]!= w.getName()):\n return w\n x = None\n \n for i in range(len(self.wishes)):\n if(self.wishes[i] == w.getName()):\n self.wishes = self.wishes[:i + 1]\n if(self.current is not None):\n self.current.setMatch(None)\n x = self.current\n self.current = w\n w.setMatch(self)\n return x\n return w\n \n def setMatch(self, w):\n ''' this is used in Gale-Shapley to set deferred acceptance match for this hospital\n w is worker'''\n self.current = w\n \n def setWishes(self): \n ''' sets rankings (wishes) for Gale-shapley algorithm based on matchings produced by T-algorithm'''\n self.wishes = []\n self.wishes_dict = {}\n index = 1\n for r in self.matchings:\n self.wishes.append(r.getName())\n self.wishes_dict[r.getName()] = index\n index += 1\n \n def setWishes2(self): \n ''' sets rankings(wishes) for Gale-Shapley algorithm based on original preferences'''\n self.wishes = []\n self.wishes_dict = {}\n index = 1\n for r in self.ranking:\n self.wishes.append(r)\n self.wishes_dict[r] = index\n index += 1\n \n def setWishes3(self, max_interviews=5): \n ''' sets rankings(wishes) for Gale-Shapley algorithm based on truncated original preferences'''\n self.wishes = []\n self.wishes_dict = {}\n index = 1\n for r in self.ranking:\n self.wishes.append(r)\n self.wishes_dict[r] = index\n index += 1\n # Note: to change length of truncated preference, change 5 below\n self.wishes = self.wishes[:max_interviews]\n \n def setWishes4(self, cuh,we): \n '''\n cuh is common utility workers provide\n this adds idiosyncratic shock to matches from simulated interviews,\n we is weight for common utility\n '''\n utilities = []\n pref = []\n for w in self.interviews:\n utilities.append(cuh[int(w.getName()[1:]) - 1] * we + self.iu[int(w.getName()[1:]) - 1] * (1 - we))\n pref.append(w)\n self.bubblesort(utilities, pref)\n self.wishes = []\n self.wishes_dict = {}\n index = 1\n for p in pref:\n self.wishes.append(p.getName())\n self.wishes_dict[p.getName()] = index\n index += 1\n \n \n def block(self, w): \n ''' returns True if this hospital with w is a blocking pair '''\n if(self.current is None): #since every worker is ranked in p, then if hospital is unmatched it prefers w to being unmatched\n return True\n \n for h in self.p:\n if(h == self.current.getName()):\n return False\n if(h == w.getName()):\n return True\n \n def block2(self,w): \n ''' returns True if this hospital with w is a blocking pair, but only if this hospital is matched'''\n if(self.current is None):\n return False\n \n for h in self.p:\n if (h == self.current.getName()):\n return False\n if (h == w.getName()):\n return True\n \n def getIU(self): \n ''' returns list of idiosyncratic utility values'''\n return self.iu\n \n \n def getIU_sorted(self):\n '''returns list of idiosyncratic utility values that doctors, ranked in order of p, provide'''\n return self.iu_sorted\n\n def getCU_sorted(self):\n '''returns list of common utility values that doctors, ranked in order of p, provide'''\n return self.cu_sorted\n \n def getUtilities_sorted(self):\n '''returns list of utility values that doctors, ranked in order of p, provide'''\n return self.utilities_sorted\n \n def setIU(self, i): \n ''' sets idiosyncratic utility values '''\n self.iu = []\n for val in i:\n self.iu.append(val)\n \n def getInterviews(self):\n return self.interviews\n \n def getName(self):\n ''' returns name (string) in format Hn where n is number'''\n return self.name\n \n def getMatchings(self): \n ''' returns list of workers that hospital is matched to '''\n return self.matchings\n \n def getRanking(self): \n ''' returns list of strings of names of workers ranked '''\n return self.ranking\n\n def setRanking(self, another_ranking):\n self.ranking = []\n self.p = []\n self.p_dict = {}\n index = 1\n for r in another_ranking:\n self.ranking.append(r)\n self.p.append(r)\n self.p_dict[r] = index\n index += 1\n\n def getWishes(self): \n ''' returns list of strings of names of workers that will be ranked '''\n return self.wishes\n \n def getCurrent(self): \n ''' returns current match (worker) during Gale Shapley algorithm ''' \n return self.current\n\ndef a(goal, w, hospitals): \n ''' this is the part of the T-algorithm where each worker \"proposes\"\n returns top n (or less) hospitals\n where n is desired number of matchings'''\n available = []\n \n for h in hospitals:\n if(w.checkAvailability(goal, h)):\n available.append(h)\n \n # available contains all hospitals available to this worker\n \n if len(available) > 0:\n temp, available = fastersort(getEquiv(available, w), available)\n\n if(len(available) <= goal):\n return available\n else:\n top = available[:goal]\n return top\n \ndef b(goal, h, workers): \n ''' same as above but this time hospital \"proposes\" '''\n available = []\n \n for w in workers:\n if(h.checkAvailability(goal, w)):\n available.append(w)\n\n if len(available) > 0:\n temp, available = fastersort(getEquiv(available, h), available)\n \n if(len(available) <= goal):\n return available\n else:\n top = available[:goal]\n return top\n\ndef fastersort(pref, ranking):\n # note this sorts in ascending order\n # previous sorts sort in descending order since the first argument, \"pref\"\n # represents utilities\n # here, \"pref\" represents a ranking, so we want \"1\" to be first\n return zip(*sorted(zip(pref, ranking)))\n\ndef bubblesort(pref, ranking):\n # note this sorts in ascending order\n for i in range(len(pref)):\n for k in range(len(pref) - 1, i, -1):\n if(pref[k] < pref[k - 1]):\n swap(pref,ranking, k, k - 1)\n \ndef swap(pref, ranking, x, y):\n temp1 = pref[x]\n temp2 = ranking[x]\n pref[x] = pref[y]\n ranking[x] = ranking[y]\n pref[y] = temp1\n ranking[y] = temp2\n \ndef getEquiv(avail, judge):\n equiv = []\n for a in avail:\n equiv.append(getRank(a, judge))\n return equiv\n\ndef getRank(desired, judge):\n ranking = judge.getP_dict()\n return ranking[desired.getName()]\n\ndef iteration(goal, workers, hospitals):\n ''' this is one iteration of t-algorithm\n this is done until no changes are made'''\n todo = []\n total = []\n for w in workers:\n todo.append(a(goal, w, hospitals))\n \n for h in hospitals:\n todo.append(b(goal, h, workers))\n \n for w in workers:\n w.match(todo.pop(0))\n total.append(w.getMatchings())\n \n for h in hospitals:\n h.match(todo.pop(0))\n total.append(h.getMatchings())\n return total\n\ndef equate(past, current):\n ''' checks if matchings remain same in t-algorithm in two consecutive iterations of \"proposals\" '''\n if(len(past) != len(current)):\n return False\n \n for i in range(len(past)):\n if(len(past[i]) != len(current[i])):\n return False\n for j in range(len(past[i])):\n if(past[i][j] != current[i][j]):\n return False\n return True\n\ndef getPreM(agent): \n ''' gets prematchings for t-algorithm ''' \n updated = []\n for w in agent.getRanking():\n for j in agent.getMatchings():\n if(w == j.getName()):\n updated.append(j)\n continue\n return updated\n\ndef proposals(workers,hospitals): \n ''' gale shapley algorithm where workers propose\n If order of parameters is switched then hospitals propose '''\n\n while(len(workers)>0):\n y = None\n for i in range(len(workers)):\n w = workers[0]\n y = None\n \n if(len(w.getWishes()) > 0 and w.getCurrent() is None):\n y = w.getPref(hospitals).judge(w)\n workers = workers[1:]\n \n if(y is not None):\n workers.append(y)\n\ndef getWorker(name,workers):\n for w in workers:\n if(w.getName()==name):\n return w\n\ndef getNameToWorkerDict(workers):\n nameToWorker = {}\n for w in workers: \n nameToWorker[w.getName()] = w\n return nameToWorker\n\ndef getR(w): \n ''' gets rank of hospital w is matched to based on p' (t-algorithm results) \n Note that p' is reported preferences '''\n h = w.getCurrent()\n if(h is None):\n return 0 # unmatched\n \n for i in range(len(w.getMatchings())):\n if(w.getMatchings()[i].getName() == h.getName()):\n return i + 1\n \ndef getR2(w):\n ''' gets the rank of hospital w is matched to based on p (original preferences)\n (this is based on matchings after both t-algorithm and Gale Shapley are run) '''\n h = w.getCurrent()\n if(h is None):\n return 0 # unmatched\n \n for i in range(len(w.getRanking())):\n if(w.getRanking()[i] == h.getName()):\n return i + 1\n\ndef getR3(w, pprime): \n ''' gets rank of doctor h is matched to based on p' (IU and CU)\n Note that p' is reported preferences '''\n h = w.getCurrent()\n if(h is None):\n return 0 # unmatched\n \n for i in range(len(pprime)):\n if(pprime[i] == h.getName()):\n return i + 1\n return -1\n\ndef fillInUtilities(hospital, hospital_names, worker_index, cu_sorted, iu_sorted, utilities_sorted):\n '''\n Hospital_names, cu_sorted, iu_sorted, utilities_sorted are all in the same order (each entry is a preference list for a hospital)\n Within the cu_sorted, iu_sorted, utilities_sorted lists, they preferences lists are in the order of doctors with highest CU first\n worker_index is 0 for the doctor with highest CU, 1 for second highest, etc\n hospital is the hospital that the worker matched to (so we can match its name to hospital_name to get its preference)\n '''\n hospital_index = 0\n for h in hospital_names:\n if (hospital.getName() == h):\n break\n hospital_index += 1\n return cu_sorted[hospital_index][worker_index], iu_sorted[hospital_index][worker_index], utilities_sorted[hospital_index][worker_index]\n\ndef getDoctorsAndHospitals(num_doctors, num_hospitals, we_doctors, we_hospitals):\n ''' \n we_doctors is weight for common utility for doctors\n we_hospitals is weight for common utility for hospitals '''\n # First, note that we can change the distribution and its parameters for common utility\n cuw = [np.random.normal(0, 1) for x in range(num_hospitals)] # common utility hospitals provide\n cuh = [np.random.normal(0, 1) for x in range(num_doctors)] # common utility workers provide\n \n # This generates the workers and hospitals for this run (same ones used for all algorithms)\n workers = [Worker(cuw, \"W\" + str(x), we_doctors, num_hospitals) for x in range(1, num_doctors + 1)] #creates array of workers with their own randomized preferences\n hospitals = [Hospital(cuh, \"H\" + str(x), we_hospitals, num_doctors) for x in range(1, num_hospitals + 1)] # creates array of hospitals with their own randomized preferences\n workers2 = [Worker(cuw, \"W\" + str(x), we_doctors, num_hospitals) for x in range(1, num_doctors + 1)] # creates array of workers with their own randomized preferences\n hospitals2 = [Hospital(cuh, \"H\" + str(x), we_hospitals, num_doctors) for x in range(1, num_hospitals + 1)] # creates array of hospitals with their own randomized preferences\n workers3 = [Worker(cuw, \"W\" + str(x), we_doctors, num_hospitals) for x in range(1, num_doctors + 1)] # creates array of workers with their own randomized preferences\n\n return workers, hospitals, workers2, workers3, hospitals2, cuw, cuh\n\ndef getDoctorsAndHospitalsExtended(num_doctors, num_hospitals, we_doctors, we_hospitals):\n ''' \n we_doctors is weight for common utility for doctors\n we_hospitals is weight for common utility for hospitals '''\n # First, note that we can change the distribution and its parameters for common utility\n cuw = [np.random.normal(0, 1) for x in range(num_hospitals)] # common utility hospitals provide\n cuh = [np.random.normal(0, 1) for x in range(num_doctors)] # common utility workers provide\n \n # This generates the workers and hospitals for this run (same ones used for all algorithms)\n workers = [Worker(cuw, \"W\" + str(x), we_doctors, num_hospitals) for x in range(1, num_doctors + 1)] #creates array of workers with their own randomized preferences\n hospitals = [Hospital(cuh, \"H\" + str(x), we_hospitals, num_doctors) for x in range(1, num_hospitals + 1)] # creates array of hospitals with their own randomized preferences\n workers2 = [Worker(cuw, \"W\" + str(x), we_doctors, num_hospitals) for x in range(1, num_doctors + 1)] # creates array of workers with their own randomized preferences\n hospitals2 = [Hospital(cuh, \"H\" + str(x), we_hospitals, num_doctors) for x in range(1, num_hospitals + 1)] # creates array of hospitals with their own randomized preferences\n workers3 = [Worker(cuw, \"W\" + str(x), we_doctors, num_hospitals) for x in range(1, num_doctors + 1)] # creates array of workers with their own randomized preferences\n workers4 = [Worker(cuw, \"W\" + str(x), we_doctors, num_hospitals) for x in range(1, num_doctors + 1)] # creates array of workers with their own randomized preferences\n hospitals4 = [Hospital(cuh, \"H\" + str(x), we_hospitals, num_doctors) for x in range(1, num_hospitals + 1)] # creates array of hospitals with their own randomized preferences\n\n return workers, hospitals, workers2, workers3, hospitals2, cuw, cuh, workers4, hospitals4\n\ndef addDoctorsAndWorkersToLists(num_doctors, num_hospitals, docs, works, types, runs, run_num, cu_ranks):\n '''\n This just updates these lists (this is done the same way every run)\n '''\n for i in range(1, num_doctors + 1):\n docs.append(i)\n types.append(\"Doctor\")\n runs.append(run_num)\n cu_ranks.append(i)\n\n for i in range(1, num_hospitals + 1):\n works.append(i)\n types.append(\"Hospital\")\n runs.append(run_num)\n cu_ranks.append(i)\n\ndef recordBlockingPairs(x, y, workers_list, hospitals_list, array_to_record, num_doctors, min_index):\n # make a dictionary mapping worker names to workers \n name_to_worker = getNameToWorkerDict(workers_list)\n \n # same with hospitals\n name_to_hospital = getNameToWorkerDict(hospitals_list)\n\n # now we check for blocking pairs for each individual doctor/hospital\n for i in range(len(x)):\n d = x[i]\n\n # get the actual worker\n w = name_to_worker[d]\n\n for j in range(len(y)):\n e = y[j]\n \n # get the actual hospital\n h = name_to_hospital[e] \n\n if(h.block(w) and w.block(h)):\n array_to_record[i + min_index] += 1\n array_to_record[j + num_doctors + min_index] += 1\n\ndef doTruncatedGS(workers, hospitals, x, y, max_interviews, doDocsPropose, doctors_p, doctors_pprime, hospitals_p, hospital_pprime, match_gs_truncated_pp_docs, match_gs_truncated_p_docs, array_to_record, num_doctors, min_index, match_name):\n w5 = []\n h5 = []\n for w in workers:\n w.setWishes3(max_interviews) # sets wishes according to original preferences, but truncated\n w.setMatch(None)\n w5.append(w)\n for h in hospitals:\n h.setWishes2() # sets wishes according to original preferences\n h.setMatch(None)\n h5.append(h)\n print(\"Starting GS with truncated preferences. Time: \" + str(np.datetime64('now')))\n\n if (doDocsPropose):\n proposals(w5, h5)\n else: \n proposals(h5, w5)\n \n w5_nameToWorkerDict = getNameToWorkerDict(w5)\n h5_nameToWorkerDict = getNameToWorkerDict(h5)\n\n # Now we iterate through the doctors in the order of highest CU and record their matchings\n for i in range(len(x)):\n d = x[i]\n\n # get the actual worker\n w = w5_nameToWorkerDict[d]\n\n match_gs_truncated_pp_docs.append(getR3(w, doctors_pprime[i]))\n match_gs_truncated_p_docs.append(getR3(w, doctors_p[i]))\n if (w.getCurrent() is None):\n match_name.append(\"Unmatched\")\n else:\n match_name.append(w.getCurrent().getName())\n\n # Now we do the same thing, but recording the matchings for hospitals\n for i in range(len(y)):\n d = y[i]\n\n # get the actual hospital\n h = h5_nameToWorkerDict[d]\n\n match_gs_truncated_pp_docs.append(getR3(h, hospital_pprime[i]))\n match_gs_truncated_p_docs.append(getR3(h, hospitals_p[i])) # For p, the rankings are based on CU only\n if (h.getCurrent() is None):\n match_name.append(\"Unmatched\")\n else:\n match_name.append(h.getCurrent().getName())\n\n # now we record blocking pairs\n recordBlockingPairs(x, y, w5, h5, array_to_record, num_doctors, min_index)\n\ndef doGS(workers, hospitals, x, y, doDocsPropose, doctors_p, doctors_pprime, hospitals_p, hospital_pprime, match_gs_p_docs, match_gs_pp_docs, array_to_record, num_doctors, min_index, match_name):\n # Here, we run Gale Shapley with no interview stage\n # Thus, we see what happens if there were no interviews and \n # doctors reported their true, untruncated preferences\n w3gs = []\n h3gs = []\n for w in workers:\n w.setWishes2() #sets wishes according to original preferences\n w.setMatch(None)\n w3gs.append(w)\n\n for h in hospitals:\n h.setWishes2() #sets wishes according to original preferences\n h.setMatch(None)\n h3gs.append(h)\n\n print(\"Starting GS with no interview stage and untruncated preferences. Time: \" + str(np.datetime64('now')))\n\n if (doDocsPropose):\n proposals(w3gs, h3gs) # Actual gale shapley algorithm \n else: \n proposals(h3gs, w3gs)\n\n # Record results\n w3gs_nameToWorkerDict = getNameToWorkerDict(w3gs)\n h3gs_nameToWorkerDict = getNameToWorkerDict(h3gs)\n\n for i in range(len(x)):\n d = x[i]\n\n # get the actual worker\n w = w3gs_nameToWorkerDict[d]\n\n match_gs_pp_docs.append(getR3(w, doctors_pprime[i]))\n match_gs_p_docs.append(getR3(w, doctors_p[i]))\n if (w.getCurrent() is None):\n match_name.append(\"Unmatched\")\n else:\n match_name.append(w.getCurrent().getName())\n\n # Now we do the same thing, but recording the matchings for hospitals\n for i in range(len(y)):\n d = y[i]\n\n # get the actual hospital\n h = h3gs_nameToWorkerDict[d]\n\n match_gs_pp_docs.append(getR3(h, hospital_pprime[i]))\n match_gs_p_docs.append(getR3(h, hospitals_p[i])) # For p, the rankings are based on CU only\n if (h.getCurrent() is None):\n match_name.append(\"Unmatched\")\n else:\n match_name.append(h.getCurrent().getName())\n\n # Check stability for final matchings (we compare with original rankings, p)\n recordBlockingPairs(x, y, w3gs, h3gs, array_to_record, num_doctors, min_index)\n\n # Gale shapley has been run with original preferences and results recorded for how hospitals were ranked in p\n\ndef runSIGSOnly(num_doctors, num_hospitals, we_doctors, we_hospitals, max_interviews, ids, docs, works, types, runs, run_num, match_in_pp_docs, match_in_p_docs, cu_ranks):\n workers, hospitals, workers2, workers3, hospitals2, cuw, cuh = getDoctorsAndHospitals(num_doctors, num_hospitals, we_doctors, we_hospitals)\n\n # First, we simply update the docs, works, and runs lists\n addDoctorsAndWorkersToLists(num_doctors, num_hospitals, docs, works, types, runs, run_num, cu_ranks)\n\n # This generates the preferences for the hospitals based only on common utiltiy (for SIGS)\n for h in hospitals2:\n h.generateP2(cuh, num_doctors) #hospital's original preferences,p, only based on cu\n x = hospitals2[0].getRanking() #these are the names of workers ranked by cu\n\n # Now we do the same thing, simply to get the list of hospitals ranked by CU\n for w in workers3: \n w.generateP2(cuw, num_hospitals)\n y = workers3[0].getRanking() # these are the names of the hospitals ranked by cu\n\n # We add the names to the ids list\n for x_1 in x:\n ids.append(x_1)\n for y_1 in y:\n ids.append(y_1)\n \n workers2_nameToWorkerDict = getNameToWorkerDict(workers2)\n hospitals2_nameToWorkerDict = getNameToWorkerDict(hospitals2)\n\n # Now we get the actual doctors and hospitals corresponding to these names\n # so we can check their final matches at the end\n ranked_workers = []\n for n in x:\n #ranked_workers.append(getWorker(n, workers2))\n ranked_workers.append(workers2_nameToWorkerDict[n])\n\n ranked_hospitals = []\n for n in y:\n #ranked_hospitals.append(getWorker(n, hospitals2))\n ranked_hospitals.append(hospitals2_nameToWorkerDict[n])\n \n # Now we set \"workers2\" to have the same ranking as \"workers\" so they are identical\n for i in range(len(workers)):\n workers2[i].setOrig(workers[i].getOrig())\n \n # Similarly, we want \"hospitals2\" to have the same idiosyncratic utilities \n # as \"hospitals\"even if the rankings aren't changed (still only based off of CU)\n # we use these idiosyncratic utilities to update the preferences after the interviews\n for i in range(len(hospitals)):\n hospitals2[i].setIU(hospitals[i].getIU())\n\n for w in workers2:\n w.setChoices(hospitals2)\n \n # Simulated Interviews\n for w in ranked_workers:\n while(len(w.getInterviews()) < max_interviews and len(w.getChoices()) > 0): # while interviewed at less than the max and has at least one more hospital to apply to\n h = w.getTopChoice()\n if(len(h.getInterviews()) < max_interviews): # if hospital has interviewed less than the max allowed\n h.interview(w)\n w.interview(h)\n # end of simulated interviews\n \n w3=[]\n h3=[]\n m4=[] # m4 are matchings from simulated interviews and Gale shapley with p with doctors proposing\n \n # Report preferences for Gale-Shapley/Deferred Acceptance Algorithm\n # For SIGS\n for w in workers2:\n w.setWishes4() # sets wishes according to matches of simulated interviews\n w3.append(w)\n \n # For SIGS, hospitals initially only had common utility\n # After interviewing candidates, they now have an idiosyncratic utility to their preferences\n # We add this to to create a new ranking of doctors by each hospital\n for h in hospitals2:\n h.setWishes4(cuh, we_hospitals) # add idiosyncratic utility and sets wishes according to matches of simulated interviews\n h3.append(h)\n\n w3_nameToWorkerDict = getNameToWorkerDict(w3)\n h3_nameToWorkerDict = getNameToWorkerDict(h3)\n # Since we just added idiosyncratic utility, we can save the p prime rankings\n hospital_pprime = []\n for d in y:\n\n #h = getWorker(d, h3)\n h = h3_nameToWorkerDict[d]\n\n hospital_pprime.append(h.getWishes())\n \n doctors_pprime = []\n for d in x:\n\n w = getWorker(d, w3)\n w = w3_nameToWorkerDict[d]\n\n doctors_pprime.append(w.getWishes())\n \n # Gale Shapley Algorithm\n proposals(w3,h3) # gale shapley after simulated interviews with doctors proposing \n\n w3_nameToWorkerDict = getNameToWorkerDict(w3)\n h3_nameToWorkerDict = getNameToWorkerDict(h3)\n # Now we iterate through the doctors in the order of highest CU and record their matchings\n for i in range(len(x)):\n d = x[i]\n\n #w = getWorker(d, w3) # get the actual worker\n w = w3_nameToWorkerDict[d]\n\n match_in_pp_docs.append(getR3(w, doctors_pprime[i]))\n match_in_p_docs.append(getR2(w))\n\n # Now we do the same thing, but recording the matchings for hospitals\n for i in range(len(y)):\n d = y[i]\n\n #h = getWorker(d, h3) # get the actual hospital\n h = h3_nameToWorkerDict[d]\n\n match_in_pp_docs.append(getR3(h, hospital_pprime[i]))\n match_in_p_docs.append(getR2(h)) # For p, the rankings are based on CU only\n\ndef runTAGS_and_GS(num_doctors, num_hospitals, we_doctors, we_hospitals, max_interviews, ids, docs, works, types, runs, run_num, cu_ranks, match_gs_p_docs, match_gs_pp_docs, match_gs_p_hosp, match_gs_pp_hosp, match_gs_truncated_p_docs, match_gs_truncated_pp_docs, match_gs_truncated_p_hosp,\n match_gs_truncated_pp_hosp, match_tags_p_docs, match_tags_pp_docs, cu_provided_gs, u_provided_gs, iu_provided_gs, cu_provided_gs_truncated, u_provided_gs_truncated, iu_provided_gs_truncated, cu_provided_tags, u_provided_tags, iu_provided_tags, blocking_pair_counts, \n bp_TAGS, min_index, match_tags_b_p_docs, match_tags_b_pp_docs, cu_provided_tags_b, u_provided_tags_b, iu_provided_tags_b, bp_TAGS_b, bp_GS_Trunc_h, bp_GS_Trunc_d, bp_GS_d, bp_GS_h, preference_profile, match_name_tags_d, match_name_tags_h, match_name_gs_d, match_name_gs_h, match_name_gs_trunc_d, match_name_gs_trunc_h):\n workers, hospitals, workers2, workers3, hospitals2, cuw, cuh, workers4, hospitals4 = getDoctorsAndHospitalsExtended(num_doctors, num_hospitals, we_doctors, we_hospitals)\n # note that workers and hospitals have the preferences that we use for all the other workers/hospitals lists\n # so we can get these preferences\n iu_sorted = []\n cu_sorted = []\n utilities_sorted = []\n hospital_names = [] # this is so we can match hospitals to indices in these lists by name\n for h in hospitals:\n iu_sorted.append(h.getIU_sorted())\n cu_sorted.append(h.getCU_sorted())\n utilities_sorted.append(h.getUtilities_sorted())\n hospital_names.append(h.getName())\n\n # First, we simply update the docs, works, and runs lists\n addDoctorsAndWorkersToLists(num_doctors, num_hospitals, docs, works, types, runs, run_num, cu_ranks)\n\n # This generates the preferences for the hospitals based only on common utiltiy (for SIGS)\n for h in hospitals2:\n h.generateP2(cuh, num_doctors) #hospital's original preferences,p, only based on cu (note that hospitals2 and hospitals have different IU, but same CU)\n x = hospitals2[0].getRanking() #these are the names of workers ranked by cu\n\n # Now we do the same thing, simply to get the list of hospitals ranked by CU\n for w in workers3: \n w.generateP2(cuw, num_hospitals) # this isn't used for any matching\n y = workers3[0].getRanking() # these are the names of the hospitals ranked by cu\n\n # We add the names to the ids list\n for x_1 in x:\n ids.append(x_1)\n for y_1 in y:\n ids.append(y_1)\n \n # Now we get the actual doctors and hospitals corresponding to these names\n # so we can check their final matches at the end\n workers2_nameToWorkerDict = getNameToWorkerDict(workers2)\n hospitals2_nameToWorkerDict = getNameToWorkerDict(hospitals2)\n\n ranked_workers = []\n for n in x:\n ranked_workers.append(workers2_nameToWorkerDict[n])\n\n ranked_hospitals = []\n for n in y:\n ranked_hospitals.append(hospitals2_nameToWorkerDict[n])\n \n # Now we set \"workers2\" to have the same ranking as \"workers\" so they are identical\n for i in range(len(workers)):\n workers2[i].setOrig(workers[i].getOrig())\n workers4[i].setOrig(workers[i].getOrig()) # This sets the preferences of the workers for TAGS to be the exact same as those for SIGS and GS\n \n # Similarly, we want \"hospitals2\" to have the same idiosyncratic utilities \n # as \"hospitals\"even if the rankings aren't changed (still only based off of CU)\n # we use these idiosyncratic utilities to update the preferences after the interviews\n for i in range(len(hospitals)):\n hospitals2[i].setIU(hospitals[i].getIU())\n hospitals4[i].setIU(hospitals[i].getIU())\n hospitals4[i].setRanking(hospitals[i].getRanking()) # This sets the preferences of the hospitals for TAGS to be the exact same as those for SIGS (after interviews)\n\n for w in workers2:\n w.setChoices(hospitals2)\n\n print(\"Starting T-Algorithm. Time: \" + str(np.datetime64('now')))\n past = []\n current = []\n \n for w in workers4: # prematches all hospitals to each worker for t-algorithm\n w.match(hospitals4)\n w.match(getPreM(w))\n past.append(w.getMatchings())\n \n # T-Algorithm\n goal = max_interviews #sets max amount of interviews (matches in T-algorithm for each agent)\n current = iteration(goal,workers,hospitals)\n \n while(not equate(past,current)): # while they don't converge\n past = []\n for p in current:\n past.append(p)\n current = iteration(goal, workers4, hospitals4)\n \n # end of t-algorithm\n\n # Report preferences for Gale-Shapley/Deferred Acceptance Algorithm\n # For TAGS\n workers4b = []\n hospitals4b = [] # in these lists we store hospitals/workers for when doctors propose in GS phase after T-algorithm\n for w in workers4:\n w.setWishes() # sets wishes (reported preferences) according to matches of t-algorithm \n workers4b.append(w)\n \n for h in hospitals4:\n h.setWishes() #sets wishes according to matches of t-algorithm\n hospitals4b.append(h)\n \n hospital_pprime2 = []\n hospitals_p2 = []\n\n workers4_nameToWorkerDict = getNameToWorkerDict(workers4)\n hospitals4_nameToWorkerDict = getNameToWorkerDict(hospitals4)\n\n for d in y:\n h = hospitals4_nameToWorkerDict[d]\n\n hospital_pprime2.append(h.getWishes())\n hospitals_p2.append(h.getRanking())\n \n doctors_pprime2 = []\n doctors_p2 = []\n for d in x:\n w = workers4_nameToWorkerDict[d]\n\n doctors_pprime2.append(w.getWishes())\n doctors_p2.append(w.getOrig())\n \n print(\"Starting DA after T-Algorithm. Time: \" + str(np.datetime64('now')))\n # Gale Shapley Algorithm\n proposals(workers4, hospitals4) # gale-shapley algorithm with doctors proposing after t-algorithm\n\n workers4_nameToWorkerDict = getNameToWorkerDict(workers4)\n hospitals4_nameToWorkerDict = getNameToWorkerDict(hospitals4)\n\n # Now we iterate through the doctors in the order of highest CU and record their matchings\n for i in range(len(x)):\n d = x[i]\n\n # get the actual worker\n w = workers4_nameToWorkerDict[d]\n\n match_tags_pp_docs.append(getR3(w, doctors_pprime2[i]))\n match_tags_p_docs.append(getR3(w, doctors_p2[i]))\n if (w.getCurrent() is None):\n match_name_tags_d.append(\"Unmatched\")\n else:\n match_name_tags_d.append(w.getCurrent().getName())\n\n if (getR3(w, doctors_pprime2[i]) == 0): # unmatched, so no hospital\n cu_provided_tags.append(-2)\n iu_provided_tags.append(-2)\n u_provided_tags.append(-2)\n else:\n\n # Get the worker's match\n h = workers4_nameToWorkerDict[d].getCurrent()\n\n cu_doc, iu_doc, u_doc = fillInUtilities(h, hospital_names, i, cu_sorted, iu_sorted, utilities_sorted)\n cu_provided_tags.append(cu_doc)\n iu_provided_tags.append(iu_doc)\n u_provided_tags.append(u_doc)\n\n # Now we do the same thing, but recording the matchings for hospitals\n for i in range(len(y)):\n d = y[i]\n\n # get the actual hospital\n h = hospitals4_nameToWorkerDict[d]\n\n match_tags_pp_docs.append(getR3(h, hospital_pprime2[i]))\n match_tags_p_docs.append(getR3(h, hospitals_p2[i])) # For p, the rankings are based on CU only\n\n if (h.getCurrent() is None):\n match_name_tags_d.append(\"Unmatched\")\n else:\n match_name_tags_d.append(h.getCurrent().getName())\n\n cu_provided_tags.append(-1)\n iu_provided_tags.append(-1)\n u_provided_tags.append(-1)\n \n # Check stability for final matchings (we compare with original rankings, p)\n bp1 = 0\n bp2 = 0\n for w in workers4:\n bp1 += w.checkBlocking(hospitals4)\n bp2 += w.checkBlocking2(hospitals4) # this excludes unmatched doctors/hospitals\n blocking_pair_counts[4].append(bp1)\n blocking_pair_counts[5].append(bp2)\n\n # now we check for blocking pairs for each individual doctor/hospital\n for i in range(len(x)):\n d = x[i]\n\n # get the actual worker\n w = workers4_nameToWorkerDict[d]\n\n for j in range(len(y)):\n e = y[j]\n\n # get the actual hospital\n h = hospitals4_nameToWorkerDict[e]\n\n if(h.block(w) and w.block(h)):\n bp_TAGS[i + min_index] += 1\n bp_TAGS[j + num_doctors + min_index] += 1\n\n print(\"starting DA for TAGS with hospitals proposing\")\n # Now we run TA GS by re-using the T-algorithm results, but have hospitals propose in GS\n for w in workers4b:\n w.setWishes()\n w.setMatch(None)\n \n for h in hospitals4b:\n h.setWishes()\n h.setMatch(None)\n\n\n workers4b_nameToWorkerDict = getNameToWorkerDict(workers4b)\n hospitals4b_nameToWorkerDict = getNameToWorkerDict(hospitals4b)\n\n # Now that we finished the T-Algorithm, we can fill out the relevant rows for the\n # preference profile\n for i in range(len(x)):\n d = x[i]\n\n # get the actual worker\n w = workers4b_nameToWorkerDict[d]\n\n for j in range(len(y)):\n dh = y[j]\n\n # get the actual hospital\n h = hospitals4b_nameToWorkerDict[dh]\n\n # Row: \n row = []\n # Run ID\n row.append(run_num) \n # Doctor ID (Common Ranking is (i + 1))\n row.append(w.getName())\n # Hospital ID (Common Ranking is (j + 1))\n row.append(h.getName())\n # Doctor (i + 1) total utility from Hospital (j + 1)\n row.append(w.getTotalUtilityByHospital(h.getName()))\n # Hospital (j + 1) total utility from Doctor (i + 1)\n _, _, u_doc = fillInUtilities(h, hospital_names, i, cu_sorted, iu_sorted, utilities_sorted)\n row.append(u_doc)\n # Did Doctor (i + 1) interview at Hospital (j + 1) in TAGS\n if (h.getName() in w.getWishes()):\n row.append(1)\n else:\n row.append(0)\n \n # Now we add the row\n preference_profile.append(row)\n\n \n proposals(hospitals4b, workers4b) # gale-shapley algorithm with hospitals proposing\n\n workers4b_nameToWorkerDict = getNameToWorkerDict(workers4b)\n hospitals4b_nameToWorkerDict = getNameToWorkerDict(hospitals4b)\n\n # Now we iterate through the doctors in the order of highest CU and record their matchings\n for i in range(len(x)):\n d = x[i]\n\n # get the actual worker\n w = workers4b_nameToWorkerDict[d]\n\n match_tags_b_pp_docs.append(getR3(w, doctors_pprime2[i]))\n match_tags_b_p_docs.append(getR3(w, doctors_p2[i]))\n\n if (w.getCurrent() is None):\n match_name_tags_h.append(\"Unmatched\")\n else:\n match_name_tags_h.append(w.getCurrent().getName())\n\n if (getR3(w, doctors_pprime2[i]) == 0): # unmatched, so no hospital\n cu_provided_tags_b.append(-2)\n iu_provided_tags_b.append(-2)\n u_provided_tags_b.append(-2)\n else:\n\n # Get the worker's match\n h = workers4b_nameToWorkerDict[d].getCurrent()\n\n cu_doc, iu_doc, u_doc = fillInUtilities(h, hospital_names, i, cu_sorted, iu_sorted, utilities_sorted)\n cu_provided_tags_b.append(cu_doc)\n iu_provided_tags_b.append(iu_doc)\n u_provided_tags_b.append(u_doc)\n\n # Now we do the same thing, but recording the matchings for hospitals\n for i in range(len(y)):\n d = y[i]\n\n # get the actual hospital\n h = hospitals4b_nameToWorkerDict[d]\n\n match_tags_b_pp_docs.append(getR3(h, hospital_pprime2[i]))\n match_tags_b_p_docs.append(getR3(h, hospitals_p2[i])) # For p, the rankings are based on CU only\n\n if (h.getCurrent() is None):\n match_name_tags_h.append(\"Unmatched\")\n else:\n match_name_tags_h.append(h.getCurrent().getName())\n\n cu_provided_tags_b.append(-1)\n iu_provided_tags_b.append(-1)\n u_provided_tags_b.append(-1)\n \n # Check stability for final matchings (we compare with original rankings, p)\n bp1 = 0\n bp2 = 0\n for w in workers4b:\n bp1 += w.checkBlocking(hospitals4b)\n bp2 += w.checkBlocking2(hospitals4b) # this excludes unmatched doctors/hospitals\n blocking_pair_counts[0].append(bp1)\n blocking_pair_counts[1].append(bp2)\n\n # now we check for blocking pairs for each individual doctor/hospital\n for i in range(len(x)):\n d = x[i]\n\n # get the actual worker\n w = workers4b_nameToWorkerDict[d]\n\n for j in range(len(y)):\n e = y[j]\n\n # get the actual hospital\n h = hospitals4b_nameToWorkerDict[e]\n\n if(h.block(w) and w.block(h)):\n bp_TAGS_b[i + min_index] += 1\n bp_TAGS_b[j + num_doctors + min_index] += 1\n \n # Now we do GS with untrucated preferences with both doctors proposing\n doGS(workers, hospitals, x, y, True, doctors_p2, doctors_pprime2, hospitals_p2, hospital_pprime2, match_gs_p_docs, match_gs_pp_docs, bp_GS_d, num_doctors, min_index, match_name_gs_d)\n\n # And doctors not proposing\n doGS(workers, hospitals, x, y, False, doctors_p2, doctors_pprime2, hospitals_p2, hospital_pprime2, match_gs_p_hosp, match_gs_pp_hosp, bp_GS_h, num_doctors, min_index, match_name_gs_h)\n\n # Here we do the same as above, but we only truncate the preferences for the doctors and assume the hospitals rank every doctor\n doTruncatedGS(workers, hospitals, x, y, max_interviews, True, doctors_p2, doctors_pprime2, hospitals_p2, hospital_pprime2, match_gs_truncated_pp_docs, match_gs_truncated_p_docs, bp_GS_Trunc_d, num_doctors, min_index, match_name_gs_trunc_d)\n\n # Now we have hospitals propose\n doTruncatedGS(workers, hospitals, x, y, max_interviews, False, doctors_p2, doctors_pprime2, hospitals_p2, hospital_pprime2, match_gs_truncated_pp_hosp, match_gs_truncated_p_hosp, bp_GS_Trunc_h, num_doctors, min_index, match_name_gs_trunc_h)\n\n for i in range(len(x) + len(y)):\n cu_provided_gs_truncated.append(-1)\n iu_provided_gs_truncated.append(-1)\n u_provided_gs_truncated.append(-1)\n cu_provided_gs.append(-1)\n iu_provided_gs.append(-1)\n u_provided_gs.append(-1)\n\ndef simulate(n, num_docs, num_hospitals, cud, cuh, max_interviews, filename='empty'):\n ids = []\n docs = []\n works = []\n runs = []\n cu_ranks = []\n types = []\n match_in_pp_docs = []\n match_in_p_docs = []\n match_gs_p_docs = []\n match_gs_pp_docs = []\n match_gs_p_hosp = []\n match_gs_pp_hosp = []\n match_in_pp_hosp = []\n match_in_p_hosp = []\n match_gs_truncated_p_docs = []\n match_gs_truncated_pp_docs = []\n match_gs_truncated_p_hosp = []\n match_gs_truncated_pp_hosp = []\n match_tags_p_docs = []\n match_tags_pp_docs = []\n cu_provided_sigs = []\n iu_provided_sigs = []\n u_provided_sigs = []\n cu_provided_gs = []\n iu_provided_gs = []\n u_provided_gs = []\n cu_provided_gs_truncated = []\n iu_provided_gs_truncated = []\n u_provided_gs_truncated = []\n cu_provided_tags = []\n iu_provided_tags = []\n u_provided_tags = []\n blocking_pair_counts = []\n for i in range(6):\n blocking_pair_counts.append([])\n bp_SIGS = []\n bp_TAGS = []\n match_tags_b_p_docs = []\n match_tags_b_pp_docs = []\n cu_provided_tags_b = []\n u_provided_tags_b = []\n iu_provided_tags_b = []\n bp_TAGS_b = []\n bp_GS_Trunc_h = []\n bp_GS_Trunc_d = []\n bp_GS_d = []\n bp_GS_h = []\n preference_profile = []\n match_name_tags_d = []\n match_name_tags_h = []\n match_name_gs_d = []\n match_name_gs_h = []\n match_name_gs_trunc_d = []\n match_name_gs_trunc_h = []\n\n run_nums = []\n m_i = []\n n_d = []\n n_h = []\n cu_d = []\n cu_h = []\n min_index = 0 # this is for indexing blocking pairs\n max_index = 0\n for run_num in range(1, n + 1):\n min_index = max_index\n print(\"Simulation #\" + str(run_num) + \" Time: \" + str(np.datetime64('now')))\n run_nums.append(run_num)\n m_i.append(max_interviews)\n n_d.append(num_docs)\n n_h.append(num_hospitals)\n cu_d.append(cud)\n cu_h.append(cuh)\n for j in range(num_docs):\n bp_TAGS.append(0)\n bp_SIGS.append(0)\n bp_TAGS_b.append(0)\n bp_GS_Trunc_h.append(0)\n bp_GS_Trunc_d.append(0)\n bp_GS_d.append(0)\n bp_GS_h.append(0)\n max_index += 1\n for j in range(num_hospitals):\n bp_TAGS.append(0)\n bp_SIGS.append(0)\n bp_TAGS_b.append(0)\n bp_GS_Trunc_h.append(0)\n bp_GS_Trunc_d.append(0)\n bp_GS_d.append(0)\n bp_GS_h.append(0) \n max_index += 1\n\n #runTAGS_and_GS(num_docs, num_hospitals, cud, cuh, max_interviews, ids, docs, works, types, runs, run_num, cu_ranks, match_gs_p_docs, match_gs_pp_docs, match_gs_p_hosp, match_gs_pp_hosp, match_gs_truncated_p_docs, match_gs_truncated_pp_docs, match_gs_truncated_p_hosp,\n # match_gs_truncated_pp_hosp, match_tags_p_docs, match_tags_pp_docs, cu_provided_gs, u_provided_gs, iu_provided_gs, cu_provided_gs_truncated, u_provided_gs_truncated, iu_provided_gs_truncated, cu_provided_tags, u_provided_tags, iu_provided_tags, blocking_pair_counts, \n # bp_TAGS, min_index, match_tags_b_p_docs, match_tags_b_pp_docs, cu_provided_tags_b, u_provided_tags_b, iu_provided_tags_b, bp_TAGS_b, bp_GS_Trunc_h, bp_GS_Trunc_d, bp_GS_d, bp_GS_h, preference_profile, match_name_tags_d, match_name_tags_h, match_name_gs_d, match_name_gs_h, match_name_gs_trunc_d, match_name_gs_trunc_h)\n runSIGSOnly(num_docs, num_hospitals, cud, cuh, max_interviews, ids, docs, works, types, runs, run_num, match_in_pp_docs, match_in_p_docs, cu_ranks)\n\n #columns = ['id', 'Run','Type', 'Common ranking', 'Match GS D','GS Match, P (D Prop)', 'GS Match, P Prime (D Prop)', 'Match GS H', 'GS Match, P (H Prop)', 'GS Match, P Prime (H Prop)', 'Match GS Trunc D','GS Truncated Match, P (D Prop)', 'GS Truncated Match, P Prime (D Prop)', 'Match GS Trunc H','GS Truncated Match, P (H Prop)', 'GS Truncated Match, P Prime (H Prop)', 'Match TAGS P D','TAGS, P (D Prop)', 'TAGS, P Prime(D Prop)', 'Match TAGS P H',\n # 'TAGS, P (H Prop)', 'TAGS, P Prime(H Prop)', 'blocking pairs TAGS (D Prop)', 'blocking pairs TAGS (H Prop)', 'blocking pairs Trunc. GS (H Prop)', 'blocking pairs Trunc. GS (D Prop)', 'blocking pairs GS (D Prop)', 'blocking pairs GS (H Prop)']\n #results = pd.DataFrame(list(zip(ids, runs, types, cu_ranks, match_name_gs_d, match_gs_p_docs, match_gs_pp_docs, match_name_gs_h, match_gs_p_hosp, match_gs_pp_hosp, match_name_gs_trunc_d, match_gs_truncated_p_docs, match_gs_truncated_pp_docs, match_name_gs_trunc_h, match_gs_truncated_p_hosp, match_gs_truncated_pp_hosp, match_name_tags_d, match_tags_p_docs, match_tags_pp_docs, match_name_tags_h, match_tags_b_p_docs, match_tags_b_pp_docs, bp_TAGS, bp_TAGS_b, bp_GS_Trunc_h, bp_GS_Trunc_d, bp_GS_d, bp_GS_h)), columns = columns)\n columns = ['id', 'Run','Type', 'Common ranking', 'SIGS Match, P (D Proposing)', 'SIGS Match, P Prime (D Proposing)']\n results = pd.DataFrame(list(zip(ids, runs, types, cu_ranks, match_in_p_docs, match_in_pp_docs)), columns = columns)\n\n col2 = ['Run', 'Max Interviews', 'Num Doctors', 'Num Hospitals', 'Common utility weight Doctors', 'Common utility weight Hospitals']\n results2 = pd.DataFrame(list(zip(run_nums, m_i, n_d, n_h, cu_d, cu_h)), columns = col2) \n\n\n if (filename != 'empty'):\n fn = filename + \".csv\"\n fn2 = filename + \"_key.csv\"\n fn3 = filename + \"_preference_profile.csv\"\n results.to_csv(fn, index = False)\n results2.to_csv(fn2, index = False)\n return results, results2\n\nimport cProfile\nimport pstats\n\ndef profile(filename, func, args=None):\n\n pr = cProfile.Profile()\n pr.enable()\n\n if args is not None:\n func(**args)\n else:\n func()\n\n pr.disable()\n\n f = open(filename, 'w')\n\n ps = pstats.Stats(pr, stream=f)\n ps.sort_stats('cumulative', 'tottime')\n ps.print_stats()\n\n f.close()\n\nsimulate(34,500,500,0.25,0.25,5,'OutSim_SIGS_500_25_25_5X')"
] | [
[
"numpy.random.normal",
"numpy.datetime64"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
abisee/transfer-learning-conv-ai | [
"7cef27a684f1a6a4020c573e39caa1f04d40fbca"
] | [
"csv_response.py"
] | [
"\"\"\"\nLoads utterances from csv file, generates responses under different settings, and writes to another csv file\n\"\"\"\nimport logging\nimport random\nimport csv\nimport torch\nimport json\n\nfrom interact import sample_sequence, load_model, batch_decode, DecodeConfig\n\n\nINFILE = '/workspace/abi/transfer-learning-conv-ai/data/common_howwasyourday_responses.csv'\nOUTFILE = '/workspace/abi/transfer-learning-conv-ai/data/common_howwasyourday_responses_answered.csv'\n\n\ndef load_utterances(filepath):\n with open(filepath, 'r') as f:\n csvreader = csv.reader(f, delimiter=',')\n idx = 0\n rows = []\n for row in csvreader:\n if idx == 0:\n columns = row\n else:\n rows.append(row)\n idx += 1\n return rows, columns\n\n\ndef main(model, model_checkpoint, configs, device=\"cuda\" if torch.cuda.is_available() else \"cpu\", seed=42):\n\n logging.basicConfig(level=logging.INFO)\n logger = logging.getLogger(__file__)\n logger.info('Starting get_response')\n logger.info(f\"device: {device}\")\n\n random.seed(seed)\n torch.random.manual_seed(seed)\n torch.cuda.manual_seed(seed)\n\n model, tokenizer = load_model(model, model_checkpoint, device)\n\n rows, columns = load_utterances(INFILE)\n\n # Init outfile and write column names\n columns = ['freq', 'user_utterance']\n for config in configs:\n columns += ['RESPONSE ' + config.__str__]\n with open(OUTFILE, 'w') as f:\n csvwriter = csv.writer(f, delimiter=',')\n csvwriter.writerow(columns)\n\n for row in rows:\n print()\n freq, utterance = row[0], row[1]\n history = ['how\\'s your day going so far?', utterance]\n\n # Init row to write to file\n row_to_write = [freq, utterance]\n\n # Get responses for each config\n for config in configs:\n finished_responses = batch_decode(model, tokenizer, history, config)\n row_to_write += [json.dumps(finished_responses)]\n\n # Append to outfile\n with open(OUTFILE, 'a') as f:\n csvwriter = csv.writer(f, delimiter=',')\n csvwriter.writerow(row_to_write)\n\n\n\nif __name__ == \"__main__\":\n configs = [\n DecodeConfig(), # natural sampling\n DecodeConfig(temperature=0.7, top_p=0.9), # recommended settings\n DecodeConfig(temperature=0.7), # should be less generic than recommended settings\n DecodeConfig(temperature=1.0, top_p=0.9), # should be less generic than recommended settings\n ]\n main(model='gpt2-medium', model_checkpoint='runs/Jan04_22-40-10_ip-172-31-71-210_gpt2-medium', configs=configs)"
] | [
[
"torch.random.manual_seed",
"torch.cuda.manual_seed",
"torch.cuda.is_available"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
samiri98/TimeGAN | [
"fd29f30bc6cbcf056f84cb158eaa586eb91ddd7f"
] | [
"metrics/predictive_metrics.py"
] | [
"\"\"\"Time-series Generative Adversarial Networks (TimeGAN) Codebase.\n\nReference: Jinsung Yoon, Daniel Jarrett, Mihaela van der Schaar, \n\"Time-series Generative Adversarial Networks,\" \nNeural Information Processing Systems (NeurIPS), 2019.\n\nPaper link: https://papers.nips.cc/paper/8789-time-series-generative-adversarial-networks\n\nLast updated Date: April 24th 2020\nCode author: Jinsung Yoon ([email protected])\n\n-----------------------------\n\npredictive_metrics.py\n\nNote: Use Post-hoc RNN to predict one-step ahead (last feature)\n\"\"\"\n\n# Necessary Packages\n# import tensorflow as tf\n# import tf_slim as tf\nimport tensorflow.compat.v1 as tf\ntf.disable_v2_behavior()\nimport numpy as np\nfrom sklearn.metrics import mean_absolute_error\nfrom utilsTimeGan import extract_time\n\n \ndef predictive_score_metrics (ori_data, generated_data):\n \"\"\"Report the performance of Post-hoc RNN one-step ahead prediction.\n \n Args:\n - ori_data: original data\n - generated_data: generated synthetic data\n \n Returns:\n - predictive_score: MAE of the predictions on the original data\n \"\"\"\n # Initialization on the Graph\n tf.reset_default_graph()\n\n # Basic Parameters\n no, seq_len, dim = np.asarray(ori_data).shape\n \n # Set maximum sequence length and each sequence length\n ori_time, ori_max_seq_len = extract_time(ori_data)\n generated_time, generated_max_seq_len = extract_time(ori_data)\n max_seq_len = max([ori_max_seq_len, generated_max_seq_len]) \n \n ## Builde a post-hoc RNN predictive network \n # Network parameters\n hidden_dim = int(dim/2)\n iterations = 5000\n batch_size = 128\n \n # Input place holders\n X = tf.placeholder(tf.float32, [None, max_seq_len-1, dim-1], name = \"myinput_x\")\n T = tf.placeholder(tf.int32, [None], name = \"myinput_t\") \n Y = tf.placeholder(tf.float32, [None, max_seq_len-1, 1], name = \"myinput_y\")\n \n # Predictor function\n def predictor (x, t):\n \"\"\"Simple predictor function.\n \n Args:\n - x: time-series data\n - t: time information\n \n Returns:\n - y_hat: prediction\n - p_vars: predictor variables\n \"\"\"\n with tf.variable_scope(\"predictor\", reuse = tf.AUTO_REUSE) as vs:\n p_cell = tf.nn.rnn_cell.GRUCell(num_units=hidden_dim, activation=tf.nn.tanh, name = 'p_cell')\n p_outputs, p_last_states = tf.nn.dynamic_rnn(p_cell, x, dtype=tf.float32, sequence_length = t)\n y_hat_logit = tf.layers.dense(p_outputs, 1, activation=None) \n y_hat = tf.nn.sigmoid(y_hat_logit)\n p_vars = [v for v in tf.all_variables() if v.name.startswith(vs.name)]\n \n return y_hat, p_vars\n \n y_pred, p_vars = predictor(X, T)\n # Loss for the predictor\n p_loss = tf.losses.absolute_difference(Y, y_pred)\n # optimizer\n p_solver = tf.train.AdamOptimizer().minimize(p_loss, var_list = p_vars)\n \n ## Training \n # Session start\n sess = tf.Session()\n sess.run(tf.global_variables_initializer())\n \n # Training using Synthetic dataset\n for itt in range(iterations):\n \n # Set mini-batch\n idx = np.random.permutation(len(generated_data))\n train_idx = idx[:batch_size] \n \n X_mb = list(generated_data[i][:-1,:(dim-1)] for i in train_idx)\n T_mb = list(generated_time[i]-1 for i in train_idx)\n Y_mb = list(np.reshape(generated_data[i][1:,(dim-1)],[len(generated_data[i][1:,(dim-1)]),1]) for i in train_idx) \n \n # Train predictor\n _, step_p_loss = sess.run([p_solver, p_loss], feed_dict={X: X_mb, T: T_mb, Y: Y_mb}) \n \n ## Test the trained model on the original data\n idx = np.random.permutation(len(ori_data))\n train_idx = idx[:no]\n \n X_mb = list(ori_data[i][:-1,:(dim-1)] for i in train_idx)\n T_mb = list(ori_time[i]-1 for i in train_idx)\n Y_mb = list(np.reshape(ori_data[i][1:,(dim-1)], [len(ori_data[i][1:,(dim-1)]),1]) for i in train_idx)\n \n # Prediction\n pred_Y_curr = sess.run(y_pred, feed_dict={X: X_mb, T: T_mb})\n \n # Compute the performance in terms of MAE\n MAE_temp = 0\n for i in range(no):\n MAE_temp = MAE_temp + mean_absolute_error(Y_mb[i], pred_Y_curr[i,:,:])\n \n predictive_score = MAE_temp / no\n \n return predictive_score\n "
] | [
[
"tensorflow.compat.v1.nn.sigmoid",
"tensorflow.compat.v1.train.AdamOptimizer",
"tensorflow.compat.v1.disable_v2_behavior",
"numpy.asarray",
"sklearn.metrics.mean_absolute_error",
"tensorflow.compat.v1.all_variables",
"tensorflow.compat.v1.global_variables_initializer",
"tensorflow.compat.v1.Session",
"tensorflow.compat.v1.losses.absolute_difference",
"tensorflow.compat.v1.placeholder",
"tensorflow.compat.v1.layers.dense",
"tensorflow.compat.v1.reset_default_graph",
"tensorflow.compat.v1.variable_scope",
"tensorflow.compat.v1.nn.rnn_cell.GRUCell",
"tensorflow.compat.v1.nn.dynamic_rnn"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
FOXOBioScience/methylprep | [
"53865b309ca1e2345c46b02baa8617839ccb5560"
] | [
"tests/processing/test_pipeline.py"
] | [
"import os\nimport sys\nimport numpy as np\nimport pandas as pd\nfrom pathlib import Path\n# App\nfrom methylprep.processing import pipeline\n#patching\nimport unittest\ntry:\n # python 3.4+ should use builtin unittest.mock not mock package\n from unittest.mock import patch\nexcept ImportError:\n from mock import patch\n\n\nclass TestPipeline():\n\n @staticmethod\n def test_pipeline_cli_minfi():\n test_data_dir = 'docs/example_data/GSE69852'\n test_outputs = [\n Path(test_data_dir, 'control_probes.pkl'),\n Path(test_data_dir, 'beta_values.pkl'),\n Path(test_data_dir, 'm_values.pkl'),\n Path(test_data_dir, 'meth_values.pkl'),\n Path(test_data_dir, 'unmeth_values.pkl'),\n Path(test_data_dir, 'noob_meth_values.pkl'),\n Path(test_data_dir, 'noob_unmeth_values.pkl'),\n Path(test_data_dir, 'sample_sheet_meta_data.pkl'),\n Path(test_data_dir, '9247377085', '9247377085_R04C02_processed.csv'),\n Path(test_data_dir, '9247377093', '9247377093_R02C01_processed.csv'),\n ]\n for outfile in test_outputs:\n if outfile.exists():\n outfile.unlink()\n\n exit_status = os.system(f'python -m methylprep process -d {test_data_dir} --all --minfi')\n if exit_status != 0:\n for outfile in test_outputs:\n if outfile.exists():\n outfile.unlink()\n raise AssertionError(\"methylprep process CLI failed with error(s)\")\n\n testfile_1 = Path(test_data_dir, '9247377085', '9247377085_R04C02_processed.csv')\n test1 = pd.read_csv(testfile_1).set_index('IlmnID')\n if test1['beta_value'].isna().sum() > 0:\n print(test1.head())\n raise AssertionError('missing beta values in processed csv')\n\n testfile_2 = Path(test_data_dir, '9247377093', '9247377093_R02C01_processed.csv')\n test2 = pd.read_csv(testfile_2)\n if test2['beta_value'].isna().sum() > 0:\n print(test2.head())\n raise AssertionError('missing beta values in processed csv')\n\n\n test1_ref_v151 = [ # bug with --all was applying nonlinear dye correction with --minfi here. fixed in v1.5.2.\n ['cg00000029', 3325.0, 2242.0, 1062.0, 823.0, 0.001, 0.0, 0.731, 1.446],\n ['cg00000108', 10266.0, 7892.0, 1035.0, 788.0, 0, 0.0, 0.909, 3.324],\n ['cg00000109', 5055.0, 3527.0, 839.0, 534.0, 0, 0.0, 0.869, 2.724],\n ['cg00000165', 879.0, 350.0, 2556.0, 3021.0, 0.006, 0.0, 0.104, -3.110],\n ['cg00000236', 5161.0, 3612.0, 604.0, 279.0, 0, 0.0, 0.928, 3.694],\n ['rs9363764', 4267.0, 2942.0, 1978.0, 2138.0, 0.001, 0.0, 0.579, 0.461],\n ['rs939290', 5724.0, 4040.0, 2908.0, 3555.0, 0, 0.0, 0.532, 0.185],\n ]\n\n # note that poobah values get a little worse when you apply minfi, linear dye bias correction instead of sesame.\n test1_ref = [\n ['cg00000029', 3325.0, 2798.0, 1062.0, 1340.0, 0.002, 0.0, 0.660, 1.062],\n ['cg00000108', 10266.0, 9739.0, 1035.0, 1288.0, 0, 0.0, 0.875, 2.919],\n ['cg00000109', 5055.0, 4528.0, 839.0, 914.0, 0.001, 0.0, 0.817, 2.309],\n ['cg00000165', 879.0, 373.0, 2556.0, 4196.0, 0.006, 0.0, 0.080, -3.492],\n ['cg00000236', 5161.0, 4634.0, 604.0, 505.0, 0.001, 0.0, 0.885, 3.198],\n ['rs9363764', 4267.0, 3740.0, 1978.0, 3091.0, 0.001, 0.0, 0.540, 0.275],\n ['rs939290', 5724.0, 5197.0, 2908.0, 4869.0, 0.001, 0.0, 0.511, 0.094],\n ]\n test1_ref = pd.DataFrame(data=test1_ref, columns=['IlmnID', 'meth', 'noob_meth', 'unmeth', 'noob_unmeth', 'poobah_pval', 'quality_mask', 'beta_value', 'm_value']).set_index('IlmnID')\n test1_sub = test1.loc[ test1.index.isin(test1_ref.index) ]\n\n if not np.isclose(test1_sub, test1_ref, atol=0.01).all():\n raise AssertionError(f\"test_data_containers[1]._SampleDataContainer__data_frame doesn't match ref values\")\n total_nas = test1['beta_value'].isna().sum()\n if total_nas > 0:\n print(f'found {total_nas} missing beta_values (N/A or inf) in sample')\n raise AssertionError()\n\n for outfile in test_outputs:\n if not outfile.exists():\n raise FileNotFoundError(f\"Expected {outfile.name} to be generated by run_pipeline() but it was missing.\")\n else:\n print('+', outfile)\n outfile.unlink()\n\n\n @staticmethod\n def test_run_pipeline_all():\n \"\"\" check that we get back useful data.\n check that output files exist, then remove them.\n\n - combined with test_run_pipeline_export_data_450k()\n - checks that we get back useful data with --export option\n \"\"\"\n test_data_dir = 'docs/example_data/GSE69852'\n test_outputs = [\n Path(test_data_dir, 'control_probes.pkl'),\n # Path(test_data_dir, 'beta_values.pkl'), -- cannot create this file AND return SDCs\n # Path(test_data_dir, 'm_values.pkl'),\n Path(test_data_dir, 'meth_values.pkl'),\n Path(test_data_dir, 'unmeth_values.pkl'),\n Path(test_data_dir, 'noob_meth_values.pkl'),\n Path(test_data_dir, 'noob_unmeth_values.pkl'),\n Path(test_data_dir, 'sample_sheet_meta_data.pkl'),\n Path(test_data_dir, '9247377085', '9247377085_R04C02_processed.csv'),\n Path(test_data_dir, '9247377093', '9247377093_R02C01_processed.csv'),\n ]\n for outfile in test_outputs:\n if outfile.exists():\n outfile.unlink()\n # betas=True, m_value=True returns betas instead\n test_data_containers = pipeline.run_pipeline(test_data_dir, export=True, save_uncorrected=True, save_control=True, batch_size=None, sesame=False)\n\n testfile_1 = Path(test_data_dir, '9247377085', '9247377085_R04C02_processed.csv')\n test1 = pd.read_csv(testfile_1).set_index('IlmnID')\n if test1['beta_value'].isna().sum() > 0:\n print(test1.head())\n raise AssertionError('missing beta values in processed csv')\n testfile_2 = Path(test_data_dir, '9247377093', '9247377093_R02C01_processed.csv')\n test2 = pd.read_csv(testfile_2)\n if test2['beta_value'].isna().sum() > 0:\n print(test2.head())\n raise AssertionError('missing beta values in processed csv')\n test1_ref = [\n ['cg00000029', 3325.0, 2785.0, 1062.0, 1323.0, 0.662, 1.074],\n ['cg00000108', 10266.0, 9726.0, 1035.0, 1271.0, 0.876, 2.936],\n ['cg00000109', 5055.0, 4515.0, 839.0, 898.0, 0.819, 2.330],\n ['cg00000165', 879.0, 366.0, 2556.0, 4182.0, 0.079, -3.510],\n ['cg00000236', 5161.0, 4621.0, 604.0, 498.0, 0.885, 3.214],\n ['rs9363764', 4267.0, 3727.0, 1978.0, 3076.0, 0.540, 0.277],\n ['rs939290', 5724.0, 5184.0, 2908.0, 4856.0, 0.511, 0.094],\n ]\n test1_ref = pd.DataFrame(data=test1_ref, columns=['IlmnID', 'meth', 'noob_meth', 'unmeth', 'noob_unmeth', 'beta_value', 'm_value']).set_index('IlmnID')\n test1_sub = test1.loc[ test1.index.isin(test1_ref.index) ]\n\n # spot checking the output.\n if not np.isclose(test1_sub, test1_ref, atol=0.01).all():\n raise AssertionError(f\"test_data_containers[1]._SampleDataContainer__data_frame doesn't match ref values\")\n # spot checking the output.\n total_nas = test_data_containers[0]._SampleDataContainer__data_frame['beta_value'].isna().sum()\n if total_nas > 0:\n print(f'found {total_nas} missing beta_values (N/A or inf) in sample')\n raise AssertionError()\n\n for outfile in test_outputs:\n if not outfile.exists():\n raise FileNotFoundError(f\"Expected {outfile.name} to be generated by run_pipeline() but it was missing.\")\n else:\n print('+', outfile)\n outfile.unlink()\n\n def test_minfi(self):\n test_data_dir = 'docs/example_data/GSE69852'\n test_outputs = [\n Path(test_data_dir, 'control_probes.pkl'),\n #Path(test_data_dir, 'beta_values.pkl'),\n #Path(test_data_dir, 'm_values.pkl'),\n #Path(test_data_dir, 'meth_values.pkl'),\n #Path(test_data_dir, 'unmeth_values.pkl'),\n Path(test_data_dir, 'noob_meth_values.pkl'),\n Path(test_data_dir, 'noob_unmeth_values.pkl'),\n Path(test_data_dir, 'sample_sheet_meta_data.pkl'),\n Path(test_data_dir, '9247377085', '9247377085_R04C02_processed.csv'),\n Path(test_data_dir, '9247377093', '9247377093_R02C01_processed.csv'),\n ]\n for outfile in test_outputs:\n if outfile.exists():\n outfile.unlink()\n #testargs = [\"__program__\", '-v', 'process', '-d', test_data_dir, '--no_export', '--sample_name', 'AdultLiver1', 'FetalLiver1', '--minfi', '--debug']\n #with patch.object(sys, 'argv', testargs): # these inputs feed the function, not CLI app\n #testargs = [\"__program__\", '-d', test_data_dir, '--no_export', '--sample_name', 'AdultLiver1', 'FetalLiver1', '--betas', '--all']\n #with patch.object(sys, 'argv', testargs):\n test_data_containers = pipeline.run_pipeline(test_data_dir, sesame=False, export=True, save_control=True)\n test2_ref = [ #minfi, without poobah and quality_mask\n # DEBUG: sesame False switch False noob True poobah False mask False, dye False == minfi mode\n ['cg00000029', 1288.0, 1969.0, 0.383676, -0.612330],\n ['cg00000108', 4631.0, 5237.0, 0.464587, -0.177417],\n ['cg00000109', 4615.0, 309.0, 0.918591, 3.900652],\n ['cg00000165', 597.0, 3518.0, 0.141637, -2.558953],\n ['cg00000236', 4267.0, 651.0, 0.850339, 2.712493],\n ['rs9363764', 3642.0, 2797.0, 0.556966, 0.380851],\n ['rs939290', 380.0, 7564.0, 0.047240, -4.315078],\n ['rs951295', 6391.0, 5675.0, 0.525316, 0.171421],\n ['rs966367', 126.0, 5467.0, 0.022132, -5.439254],\n ['rs9839873', 5485.0, 189.0, 0.949948, 4.859034],\n ]\n test2_ref = pd.DataFrame(data=test2_ref, columns=['IlmnID', 'noob_meth', 'noob_unmeth', 'beta_value', 'm_value']).set_index('IlmnID').astype('float32')\n test2 = test_data_containers[0]._SampleDataContainer__data_frame\n test2_sub = test2.loc[ test2.index.isin(test2_ref.index) ].astype('float32')\n if not np.isclose(test2_sub, test2_ref, atol=0.01).all():\n raise AssertionError()\n\n for outfile in test_outputs:\n if not outfile.exists():\n raise FileNotFoundError(f\"Expected {outfile.name} to be generated by run_pipeline() but it was missing.\")\n else:\n print('+', outfile)\n outfile.unlink()\n\n def test_run_pipeline_with_create_sample_sheet_plus(self):\n test_data_dir = 'docs/example_data/epic_plus'\n test_data_containers = pipeline.run_pipeline(test_data_dir, export=False, sample_name=['Sample_1'],\n meta_data_frame=False, make_sample_sheet=True, sesame=False)\n test1 = test_data_containers[0]._SampleDataContainer__data_frame\n #test2 = test_data_containers[1]._SampleDataContainer__data_frame\n test1_ref = [\n ['cg00000029_II_F_C_rep1_EPIC', 1180.0, 274.0, 0.759331, 2.106539],\n ['cg00000103_II_F_C_rep1_EPIC', 1363.0, 681.0, 0.635728, 1.001059],\n ['cg00000109_II_F_C_rep1_EPIC', 2427.0, 284.0, 0.863394, 3.095211],\n ['cg00000155_II_F_C_rep1_EPIC', 4392.0, 212.0, 0.933673, 4.372742],\n ['cg00000158_II_F_C_rep1_EPIC', 5742.0, 211.0, 0.948620, 4.766238],\n ['rs951295_I_N_C_rep1_EPIC', 210.0, 7981.0, 0.025329, -5.248108],\n ['rs966367_II_F_C_rep1_GWG1', 1587.0, 1569.0, 0.487408, 0.016457],\n ['rs966367_II_N_C_rep1_EPIC', 2419.0, 2774.0, 0.457019, -0.197557],\n ['rs9839873_II_F_C_rep1_GWG1', 3430.0, 173.0, 0.926276, 4.309365],\n ['rs9839873_II_N_C_rep1_EPIC', 3558.0, 170.0, 0.929467, 4.387460],\n ]\n test1_ref = pd.DataFrame(data=test1_ref, columns=['IlmnID', 'noob_meth', 'noob_unmeth', 'beta_value', 'm_value']).set_index('IlmnID').astype('float32')\n # spot checking the output.\n test1_sub = test1.loc[ test1.index.isin(test1_ref.index) ].astype('float32')\n if not np.isclose(test1_sub, test1_ref, atol=0.01).all():\n # test1_ref.equals( test1_sub ) will fail, and pd.testing.assert_frame_equal(test1_sub, test1_ref) fails because of rounding at 7th decimal place.\n raise AssertionError(\"data container values don't match\")\n\n @staticmethod\n def test_run_pipeline_sesame_defaults():\n \"\"\" check that we get back useful data.\n checks SDC, CSV outputs, and pickles after sesame=True processing\n check that output files exist, then remove them.\n \"\"\"\n test_data_dir = 'docs/example_data/GSE69852'\n test_outputs = [\n Path(test_data_dir, 'control_probes.pkl'),\n Path(test_data_dir, 'beta_values.pkl'),\n Path(test_data_dir, 'm_values.pkl'),\n Path(test_data_dir, 'meth_values.pkl'),\n Path(test_data_dir, 'unmeth_values.pkl'),\n Path(test_data_dir, 'noob_meth_values.pkl'),\n Path(test_data_dir, 'noob_unmeth_values.pkl'),\n Path(test_data_dir, 'sample_sheet_meta_data.pkl'),\n Path(test_data_dir, '9247377085', '9247377085_R04C02_processed.csv'),\n Path(test_data_dir, '9247377093', '9247377093_R02C01_processed.csv'),\n ]\n for outfile in test_outputs:\n if outfile.exists():\n outfile.unlink()\n\n test_data_containers = pipeline.run_pipeline(test_data_dir, sesame=True, export=True)\n test_probes = ['cg00063477', 'cg00121626', 'cg00223952', 'cg27614706', 'cg27619353', 'cg27620176', 'cg27647370', 'cg27652464']\n # for version 1.4.0\n minfi_reference_data = [\n ['cg00035864', 2040.0, 4480.0, 0.308157, -1.134930],\n ['cg00061679', 5946.0, 5276.0, 0.525172, 0.172475],\n ['cg00063477', 5759.0, 315.0, 0.932783, 4.192395],\n ['cg00121626', 3811.0, 7636.0, 0.330042, -1.002648],\n ['cg00223952', 277.0, 12107.0, 0.022188, -5.449811],\n ['cg27614706', 5831.0, 265.0, 0.941091, 4.459679],\n ['cg27619353', 7466.0, 14894.0, 0.332413, -0.996324],\n ['cg27620176', 11753.0, 222.0, 0.973333, 5.726326],\n ['cg27647370', 15752.0, 2212.0, 0.872011, 2.832112],\n ['cg27652464', 656.0, 15224.0, 0.041051, -4.536508],\n ]\n minfi_ref = pd.DataFrame(minfi_reference_data, columns=['IlmnID','noob_meth','noob_unmeth','beta_value','m_value']).set_index('IlmnID')\n NaN = np.nan # this matches '9247377093_R02C01'\n reference_data_old_noob = [\n ['cg00063477', 4107.0, 172.0, 1.0, 0.960, 4.578],\n ['cg00121626', 3542.0, 3397.0, 1.0, 0.510, 0.060],\n ['cg00223952', NaN, NaN, NaN, NaN, NaN],\n ['cg27614706', NaN, NaN, NaN, NaN, NaN],\n ['cg27619353', 2226.0, 9714.0, 1.0, 0.186, -2.126],\n ['cg27620176', 6057.0, 94.0, 1.0, 0.985, 6.010],\n ['cg27647370', 8897.0, 167.0, 1.0, 0.982, 5.735],\n ['cg27652464', 398.0, 8832.0, 1.0, 0.043, -4.472],\n ]\n reference_data = [ #CSV file\n ['cg00063477', 4115.0, 172.0, 1.0, 0.960, 4.580],\n ['cg00121626', 3552.0, 3381.0, 1.0, 0.512, 0.071],\n ['cg00223952', 420.0, 7058.0, 0.0, 0.056, -4.071],\n ['cg27614706', 3612.0, 90.0, 0.0, 0.976, 5.327],\n ['cg27619353', 2204.0, 9713.0, 1.0, 0.185, -2.140],\n ['cg27620176', 6052.0, 94.0, 1.0, 0.985, 6.010],\n ['cg27647370', 8895.0, 167.0, 1.0, 0.982, 5.735],\n ['cg27652464', 396.0, 8829.0, 1.0, 0.043, -4.479],\n ]\n reference_container_data = [\n ['cg00063477', 4115.0, 172.0, 1.0, 0.960, 4.580],\n ['cg00121626', 3552.0, 3381.0, 1.0, 0.512, 0.071],\n ['cg00223952', NaN, NaN, NaN, 0.056, -4.071],\n ['cg27614706', NaN, NaN, NaN, 0.976, 5.327],\n ['cg27619353', 2204.0, 9713.0, 1.0, 0.185, -2.140],\n ['cg27620176', 6052.0, 94.0, 1.0, 0.985, 6.010],\n ['cg27647370', 8895.0, 167.0, 1.0, 0.982, 5.735],\n ['cg27652464', 396.0, 8829.0, 1.0, 0.043, -4.479],\n ]\n ref_noobfix_data = [ #CSV file; pre v1.5.0 NOOB wasn't excluding poobah/qualityMask failed probes from oobG/oobR\n ['cg00063477', 4125.0, 171.0, 1.0, 0.960, 4.592],\n ['cg00121626', 3562.0, 3391.0, 1.0, 0.512, 0.071],\n ['cg00223952', 428.0, 7068.0, 0.0, 0.057, -4.046],\n ['cg27614706', 3622.0, 87.0, 0.0, 0.977, 5.363],\n ['cg27619353', 2214.0, 9722.0, 1.0, 0.185, -2.135],\n ['cg27620176', 6062.0, 90.0, 1.0, 0.985, 6.074],\n ['cg27647370', 8905.0, 166.0, 1.0, 0.982, 5.745],\n ['cg27652464', 404.0, 8840.0, 1.0, 0.043, -4.452],\n ]\n ref_noobfix_container_data = [ #CSV file; pre v1.5.0 NOOB wasn't excluding poobah/qualityMask failed probes from oobG/oobR\n ['cg00063477', 4125.0, 171.0, 1.0, 0.960, 4.592],\n ['cg00121626', 3562.0, 3391.0, 1.0, 0.512, 0.071],\n ['cg00223952', NaN, NaN, NaN, 0.057, -4.046],\n ['cg27614706', NaN, NaN, NaN, 0.977, 5.363],\n ['cg27619353', 2214.0, 9722.0, 1.0, 0.185, -2.135],\n ['cg27620176', 6062.0, 90.0, 1.0, 0.985, 6.074],\n ['cg27647370', 8905.0, 166.0, 1.0, 0.982, 5.745],\n ['cg27652464', 404.0, 8840.0, 1.0, 0.043, -4.452],\n ]\n #refref = pd.DataFrame(ref_noobfix_data, columns=['IlmnID','noob_meth','noob_unmeth','quality_mask','beta_value','m_value']).set_index('IlmnID')\n container_ref = pd.DataFrame(ref_noobfix_container_data, columns=['IlmnID','noob_meth','noob_unmeth','quality_mask','beta_value','m_value']).set_index('IlmnID')\n # checking outputs.\n idata = test_data_containers[0]._SampleDataContainer__data_frame.index\n iref = container_ref.index\n subdata = test_data_containers[0]._SampleDataContainer__data_frame[idata.isin(iref)]\n meth = all(np.isclose(subdata[['noob_meth']], container_ref[['noob_meth']], atol=1.0, equal_nan=True))\n unmeth = all(np.isclose(subdata[['noob_unmeth']], container_ref[['noob_unmeth']], atol=1.0, equal_nan=True))\n beta = all(np.isclose(subdata[['beta_value']], container_ref[['beta_value']], atol=0.01, equal_nan=True))\n m = all(np.isclose(subdata[['m_value']], container_ref[['m_value']], atol=0.01, equal_nan=True))\n\n if meth is False:\n raise AssertionError(f\"container meth values don't match in data container:\\n{subdata[['noob_meth']]}\\n{container_ref[['noob_meth']]}\")\n if unmeth is False:\n raise AssertionError(f\"container unmeth values don't match in data container:\\n{subdata[['noob_unmeth']]}\\n{container_ref[['noob_unmeth']]}\")\n if beta is False:\n raise AssertionError(f\"container beta values don't match in data container\")\n if m is False:\n raise AssertionError(f\"container m values don't match in data container\")\n\n csv_ref = pd.DataFrame(ref_noobfix_data, columns=['IlmnID','noob_meth','noob_unmeth','quality_mask','beta_value','m_value']).set_index('IlmnID')\n csv_ref = csv_ref[ csv_ref.index.isin(test_probes)]\n csv_data = pd.read_csv(Path(test_data_dir, '9247377093', '9247377093_R02C01_processed.csv')).set_index('IlmnID')\n csv_data = csv_data[ csv_data.index.isin(test_probes)]\n csv_meth = all(np.isclose(csv_data[['noob_meth']], csv_ref[['noob_meth']], atol=1.0, equal_nan=True))\n csv_unmeth = all(np.isclose(csv_data[['noob_unmeth']], csv_ref[['noob_unmeth']], atol=1.0, equal_nan=True))\n csv_beta = all(np.isclose(csv_data[['beta_value']], csv_ref[['beta_value']], atol=0.01, equal_nan=True))\n csv_m = all(np.isclose(csv_data[['m_value']], csv_ref[['m_value']], atol=0.01, equal_nan=True))\n\n if csv_meth is False:\n raise AssertionError(f\"csv meth values don't match in data container:\\n{csv_data[['noob_meth']]}\\n{csv_ref[['noob_meth']]}\")\n if csv_unmeth is False:\n raise AssertionError(f\"csv unmeth values don't match in data container:\\n{csv_data[['noob_unmeth']]}\\n{csv_ref[['noob_unmeth']]}\")\n if csv_beta is False:\n raise AssertionError(f\"csv beta values don't match in data container\")\n if csv_m is False:\n raise AssertionError(f\"csv m values don't match in data container\")\n\n #beta = pd.read_pickle(Path(test_data_dir, 'beta_values.pkl'))\n noob_meth = pd.read_pickle(Path(test_data_dir, 'noob_meth_values.pkl'))\n noob_unmeth = pd.read_pickle(Path(test_data_dir, 'noob_unmeth_values.pkl'))\n ref_meth = [ # pre v1.5.0\n ['cg00000029', 2231],\n ['cg00000108', 7880],\n ['cg00000109', 3516],\n ['cg00000165', 344],\n ['cg00000236', 3601],\n ]\n ref_meth = [ # v1.5.0+ with noob-poobah-quality_mask fix\n ['cg00000029', 2242],\n ['cg00000108', 7892],\n ['cg00000109', 3527],\n ['cg00000165', 350],\n ['cg00000236', 3612],\n ]\n\n ref_meth = pd.DataFrame(ref_meth, columns = ['IlmnID', '9247377085_R04C02']).set_index('IlmnID')\n test_noob_meth = noob_meth['9247377085_R04C02'][noob_meth.index.isin(ref_meth.index)]\n meth = all(np.isclose(test_noob_meth, ref_meth['9247377085_R04C02'], atol=1.0, equal_nan=True))\n if meth is False:\n raise AssertionError(f\"meth values don't match in pickle (ref: {ref_meth} vs {test_noob_meth})\")\n\n test_data_dir = 'docs/example_data/GSE69852'\n test_outputs = [\n Path(test_data_dir, 'control_probes.pkl'),\n Path(test_data_dir, 'beta_values.pkl'),\n Path(test_data_dir, 'm_values.pkl'),\n Path(test_data_dir, 'meth_values.pkl'),\n Path(test_data_dir, 'unmeth_values.pkl'),\n Path(test_data_dir, 'noob_meth_values.pkl'),\n Path(test_data_dir, 'noob_unmeth_values.pkl'),\n Path(test_data_dir, 'sample_sheet_meta_data.pkl'),\n Path(test_data_dir, '9247377085', '9247377085_R04C02_processed.csv'),\n Path(test_data_dir, '9247377093', '9247377093_R02C01_processed.csv'),\n ]\n for outfile in test_outputs:\n if outfile.exists():\n outfile.unlink()\n\n @staticmethod\n def test_process_mouse():\n \"\"\" catches anything serious broken about mouse array processing\n in v1.4.4 / v0.7.4 I expect this to use the linear dye fallback within the sesame method, because of dupe probe names.\"\"\"\n PATH = 'docs/example_data/mouse'\n ID = '204879580038_R06C02'\n print('* loading mouse manifest')\n import methylprep\n manifest = methylprep.files.Manifest(methylprep.models.ArrayType('mouse'))\n print('* loading one idat pair of files')\n green_filepath = Path(PATH, f'{ID}_Grn.idat') #'204879580038_R06C02_Grn.idat')\n red_filepath = Path(PATH, f'{ID}_Red.idat') #'204879580038_R06C02_Red.idat')\n print(f\"* GREEN --> {green_filepath.name}\")\n print(f\"* RED --> {red_filepath.name}\")\n if not (green_filepath.exists() and green_filepath.is_file()):\n raise FileNotFoundError(\"mouse test data missing\")\n if not (red_filepath.exists() and red_filepath.is_file()):\n raise FileNotFoundError(\"mouse test data missing\")\n files_to_remove = ['samplesheet.csv', 'control_probes.pkl', 'mouse_probes.pkl',\n 'sample_sheet_meta_data.pkl', 'noob_meth_values.pkl', 'noob_unmeth_values.pkl']\n for _file in files_to_remove:\n if Path(PATH, _file).is_file():\n Path(PATH, _file).unlink()\n data = methylprep.run_pipeline(PATH, make_sample_sheet=True)\n df = data[0]._SampleDataContainer__data_frame\n #print( np.isclose(list(df['beta_value'][:3]), [0.905712, 0.841185, 0.129731]) )\n #assert np.isclose(list(df['beta_value'][:3]), [0.905712, 0.841185, 0.129731]).all() == True\n for _file in files_to_remove:\n if Path(PATH, _file).is_file():\n Path(PATH, _file).unlink()\n\n # compare with 10000 randomly selected probes processed in sesame\n # SEE docs/debug_notebooks/sesame_mouse.R\n # sesame data came from openSesame() without any other kwargs\n # test = ses.loc[ sesame_mask].loc[ ~ses['beta_value'].isna() ].sample(10000)\n # 10000 is a sample of all probes that are found in methylprep betas output | excludes mouse probes and rs probes.\n sesame = pd.read_csv(Path(PATH,'open_sesame_mouse_betas_subdata.csv')).set_index('IlmnID')\n # pd.read_csv(Path(PATH,f'sesame_{ID}_beta_subset.csv')).set_index('IlmnID')\n # because sesame's output is ALL probes, I need to filter to just the overlapping ones\n sesame_mask = set(sesame.index) & set(df.index)\n df_test = df[ df.index.isin(sesame_mask) ]\n diff = (df_test[['beta_value']] - sesame)\n # diff.hist(bins=300, range=[-0.1, 0.1])\n # import matplotlib.pyplot as plt;plt.show()\n if diff.mean()[0] > 0.01: # actual is 0.0350574\n raise AssertionError(f\"sesame betas are too different from methylprep's for mouse data. Mean beta diff: {df_test.mean()}\")\n\n\nclass UnitTestCase(unittest.TestCase):\n def test_pipeline_wrong_sample_name_fails(self):\n LOCAL = Path('docs/example_data/GSE69852/')\n with self.assertRaises(SystemExit):\n pipeline.run_pipeline(LOCAL, betas=True, sample_name=['blahblah_wrong_sample_name'])\n"
] | [
[
"pandas.read_csv",
"pandas.DataFrame",
"numpy.isclose"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [
"2.0",
"1.4",
"1.3",
"1.1",
"1.5",
"1.2"
],
"scipy": [],
"tensorflow": []
}
] |
linyc74/lstm_dna | [
"b6db773100a4e408b5acf2c03470926d9934e625"
] | [
"experiments/experiment_001/experiment_001.py"
] | [
"import os\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nfrom torch.utils.tensorboard import SummaryWriter\nfrom typing import Tuple\nfrom ngslite import get_files\nfrom lstm_dna.model import LSTMModel\nfrom lstm_dna.loader import load_genbank, divide_sequence\nfrom lstm_dna.trainer import Trainer\n\n\nEXPERIMENT_NAME = f'{os.path.basename(__file__)[:-3]}'\nTRAINING_FRACTION = 0.7\nMAX_EPOCHS = 1000\nOVERTRAIN_EPOCHS = 5\nCUDA = True\n\n\ndef shuffle(\n X: torch.Tensor,\n Y: torch.Tensor) \\\n -> Tuple[torch.Tensor, torch.Tensor]:\n\n n_samples, _, _ = X.size()\n rand_order = torch.randperm(n_samples)\n\n X = X[rand_order, :, :]\n Y = Y[rand_order, :, :]\n\n return X, Y\n\n\ndef split(\n t: torch.Tensor,\n training_fraction: float) \\\n -> Tuple[torch.Tensor, torch.Tensor]:\n\n n_samples, _, _ = t.size()\n\n train_size = int(n_samples * training_fraction)\n test_size = n_samples - train_size\n\n x_train, x_test = torch.split(t, [train_size, test_size], dim=0)\n\n return x_train, x_test\n\n\ndef train_model(\n stage: int,\n X: torch.Tensor,\n Y: torch.Tensor,\n seq_len: int,\n mini_batch_size: int,\n learning_rate: float,\n model: LSTMModel) -> LSTMModel:\n\n X, Y = divide_sequence(X=X, Y=Y, seq_len=seq_len)\n X, Y = shuffle(X=X, Y=Y)\n X_train, X_test = split(X, training_fraction=TRAINING_FRACTION)\n Y_train, Y_test = split(Y, training_fraction=TRAINING_FRACTION)\n\n criterion = nn.BCEWithLogitsLoss()\n optimizer = optim.Adam(model.parameters(), lr=learning_rate)\n\n writer = SummaryWriter(\n log_dir=f'tensorboard/{EXPERIMENT_NAME}/stage_{stage}_seq_len_{seq_len}_lr_{learning_rate}')\n\n trainer = Trainer(\n model=model,\n X_train=X_train,\n Y_train=Y_train,\n X_test=X_test,\n Y_test=Y_test,\n criterion=criterion,\n optimizer=optimizer,\n mini_batch_size=mini_batch_size,\n writer=writer)\n\n model = trainer.train(\n max_epochs=MAX_EPOCHS,\n overtrain_epochs=OVERTRAIN_EPOCHS)\n\n writer.close()\n\n return model\n\n\ndef main():\n gbkdir = '../data'\n\n gbks = get_files(source=gbkdir, isfullpath=True)\n X, Y = load_genbank(gbks=gbks, cuda=False)\n\n model = LSTMModel(\n sizes=[4, 128, 1],\n batch_first=True,\n bidirectional=True,\n cuda=CUDA)\n\n for stage, seq_len, mini_batch_size, learning_rate in [\n (1, 128, 256, 1e-3),\n (2, 1024, 64, 1e-4),\n (3, 8192, 16, 1e-5),\n ]:\n\n model = train_model(\n stage=stage,\n X=X,\n Y=Y,\n seq_len=seq_len,\n mini_batch_size=mini_batch_size,\n learning_rate=learning_rate,\n model=model)\n\n torch.save(model, f'./models/{EXPERIMENT_NAME}_stage_{stage}.model')\n\n torch.save(model, f'./models/{EXPERIMENT_NAME}.model')\n\n\nif __name__ == '__main__':\n main()\n"
] | [
[
"torch.randperm",
"torch.nn.BCEWithLogitsLoss",
"torch.utils.tensorboard.SummaryWriter",
"torch.split",
"torch.save"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
picbeats/QuOCS | [
"dea114c2d0e7d5f1f09447bdcaffb2ded24b8e78"
] | [
"src/quocslib/pulses/BasePulse.py"
] | [
"# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n# Copyright 2021- QuOCS Team\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n\nfrom abc import abstractmethod\nfrom typing import Callable\n\nimport numpy as np\n\n\nclass BasePulse:\n \"\"\"\n This is the main class for Pulse. Every pulse has to inherit this class.\n \"\"\"\n control_parameters_number: int\n optimized_control_parameters: np.ndarray\n final_time: float\n\n def __init__(self, map_index=-1, pulse_name=\"pulse\", bins_number=101, time_name=\"time\", lower_limit=0.0,\n upper_limit=1.0, amplitude_variation=0.1, initial_guess=None, scaling_function=None,\n is_shrinked:bool = False, shaping_options: list = None, overwrite_base_pulse: bool = False, **kwargs):\n \"\"\"\n Here we defined all the basic features a pulse should have.\n\n :param int map_index: index number for pulse control parameters association\n :param str pulse_name: Pulse name\n :param int bins_number: Number of bins\n :param str time_name: Name of the time associated to this pulse\n :param float lower_limit: Lower amplitude limit of the pulse\n :param float upper_limit: Upper amplitude limit of the pulse\n :param float amplitude_variation: amplitude variation of the pulse\n :param dict initial_guess: dictionary with initial guess information\n :param dict scaling_function: dictionary with scaling function information\n :param kwargs: Other arguments\n \"\"\"\n # The arguments did not use here, use for the other class\n # super().__init__(**kwargs)\n # Pulse name\n self.pulse_name = pulse_name\n # Bins number\n self.bins_number = bins_number\n # Base Pulse\n self.base_pulse = np.zeros(self.bins_number)\n # Time grid initialization\n self.time_grid = np.zeros(self.bins_number)\n # Time\n self.time_name = time_name\n # Amplitude Limits\n # TODO Implement check amplitude lower < amplitude upper\n (self.amplitude_lower, self.amplitude_upper) = (lower_limit, upper_limit)\n # Amplitude variation\n self.amplitude_variation = amplitude_variation\n # Create the parameter indexes list. It is used\n self.control_parameters_list = [map_index + i + 1 for i in range(self.control_parameters_number)]\n # Update the map_index number for the next pulse\n self.last_index = self.control_parameters_list[-1]\n # Shaping options\n print(\"Testing shaping option list mode\")\n shaping_option_dict = {\"add_base_pulse\": self.add_base_pulse, \"add_initial_guess\": self.add_initial_guess,\n \"limit_pulse\": self.limit_pulse, \"scale_pulse\": self.scale_pulse}\n if shaping_options is None:\n self.shaping_options = [self.add_base_pulse, self.add_initial_guess, self.scale_pulse, self.limit_pulse]\n else:\n self.shaping_options = []\n for op_str in shaping_options:\n if op_str in shaping_option_dict:\n self.shaping_options.append(shaping_option_dict[op_str])\n else:\n print(\"Warning: {0} pulse option is not implemented\".format(op_str))\n # Initial guess function\n function_type = initial_guess[\"function_type\"]\n if function_type == \"lambda_function\":\n initial_guess_pulse = eval(initial_guess[\"lambda_function\"])\n elif function_type == \"list_function\":\n initial_guess_pulse = np.asarray(initial_guess[\"list_function\"])\n else:\n initial_guess_pulse = lambda t: 0.0 * t\n self.initial_guess_pulse = initial_guess_pulse\n # Scaling function\n function_type = scaling_function[\"function_type\"]\n if function_type == \"lambda_function\":\n scaling_function = eval(scaling_function[\"lambda_function\"])\n elif function_type == \"list_function\":\n scaling_function = np.asarray(scaling_function[\"list_function\"])\n else:\n scaling_function = lambda t: 1.0 * t\n self.scaling_function = scaling_function\n # Shrink option\n self.is_shrinked = is_shrinked\n # Overwrite the base pulse at the end of the superiteration\n self.overwrite_base_pulse = overwrite_base_pulse\n\n def _set_time_grid(self, final_time: float) -> None:\n \"\"\"Set the time grid\"\"\"\n self.final_time = final_time\n self.time_grid = np.linspace(0, final_time, self.bins_number)\n\n def _get_build_pulse(self) -> np.ndarray:\n \"\"\" Build the pulse with all the constraints\"\"\"\n optimal_pulse = self._get_shaped_pulse()\n for op in self.shaping_options:\n optimal_pulse = op(optimal_pulse)\n # Pulse operations\n # Make a loop with all the operation that the users wants to apply to the pulse shaping\n # optimal_pulse_total = self._get_initial_guess() + self._constrained_pulse(optimal_pulse)\n return optimal_pulse\n\n def _constrained_pulse(self, optimal_pulse: np.ndarray) -> np.ndarray:\n \"\"\" Apply further constraints to the final pulse \"\"\"\n # Shrink the optimal pulse\n optimal_limited_pulse = self._get_limited_pulse(optimal_pulse)\n optimal_scaled_pulse = optimal_limited_pulse * self._get_scaling_function()\n return optimal_scaled_pulse\n\n def _shrink_pulse(self, optimal_pulse: np.ndarray) -> np.ndarray:\n \"\"\" Shrink the optimal pulse to respect the amplitude limits\"\"\"\n # Upper - lower bounds\n u_bound = self.amplitude_upper\n l_bound = self.amplitude_lower\n # Upper - lower values of the optimal pulse\n u_value = np.max(optimal_pulse)\n l_value = np.min(optimal_pulse)\n # Distances to the bounds\n u_distance = u_value - u_bound\n l_distance = l_bound - l_value\n # Check if the bounds are not respect by the optimal pulse\n if u_distance > 0.0 or l_distance > 0.0:\n # Move the pulse to the center of the axis\n distance_u_l_value = (u_value + l_value) / 2.0\n v_optimal_pulse = optimal_pulse - distance_u_l_value\n # Move the bounds to the center of the axis respect the optimal pulses\n distance_u_l_bound = (u_bound + l_bound) / 2.0\n v_u_bound, v_l_bound = [u_bound - distance_u_l_value, l_bound - distance_u_l_value]\n # Check which is the greatest virtual distance\n v_u_value = np.max(v_optimal_pulse)\n v_l_value = np.min(v_optimal_pulse)\n # The distance is preserved under this transformation\n v_l_distance = l_distance\n v_u_distance = u_distance\n # Calculate the max distance and assign the max bound in the virtual frame\n if v_u_distance >= v_l_distance:\n max_value = v_u_value\n max_bound = v_u_bound\n else:\n max_value = v_l_value\n max_bound = v_l_bound\n # Calculate the shrink factor (< 1.0)\n shrink_factor = max_bound / max_value\n # rescale the virtual pulse\n shrinked_v_optimal_pulse = shrink_factor * v_optimal_pulse\n # Go back to the non virtual pulse, i.e. a transformation + distance_u_l_value\n shrinked_pulse = shrinked_v_optimal_pulse + distance_u_l_value\n # Re-assign the optimal pulse\n optimal_pulse = shrinked_pulse\n\n return optimal_pulse\n\n def get_pulse(self, optimized_parameters_vector: np.ndarray, final_time: float = 1.0) -> np.ndarray:\n \"\"\" Set the optimized control parameters, the time grid, and return the pulse\"\"\"\n self._set_control_parameters(optimized_parameters_vector)\n self._set_time_grid(final_time)\n return self._get_build_pulse()\n\n def set_base_pulse(self, optimized_control_parameters: np.ndarray, final_time: float = 1.0) -> None:\n \"\"\" Set the base optimal pulse pulse \"\"\"\n self._set_control_parameters(optimized_control_parameters)\n self._set_time_grid(final_time)\n if self.overwrite_base_pulse:\n self.base_pulse = self._get_shaped_pulse()\n else:\n self.base_pulse += self._get_shaped_pulse()\n\n def _set_control_parameters(self, optimized_control_parameters: np.ndarray) -> None:\n \"\"\" Set the optimized control parameters vector \"\"\"\n # TODO Check if the optimized control parameters vector has a size equal to the control parameters number\n # of this pulse, otherwise raise an error\n self.optimized_control_parameters = optimized_control_parameters\n\n def _get_scaling_function(self) -> np.ndarray:\n \"\"\" Get the array scaling function \"\"\"\n if isinstance(self.scaling_function, Callable):\n scaling_function_t = self.scaling_function(self.time_grid)\n elif isinstance(self.scaling_function, np.ndarray):\n scaling_function_t = self.scaling_function\n else:\n # TODO Handle here\n print(\"Warning: scaling function not good. Do with 1.0\")\n scaling_function_t = (lambda t: 1.0)(self.time_grid)\n return scaling_function_t\n\n def _get_initial_guess(self) -> np.ndarray:\n \"\"\" Get the initial guess pulse \"\"\"\n if isinstance(self.initial_guess_pulse, Callable):\n initial_guess_t = self.initial_guess_pulse(self.time_grid)\n elif isinstance(self.initial_guess_pulse, np.ndarray):\n initial_guess_t = self.initial_guess_pulse\n else:\n # TODO Handle here\n print(\"Warning: initial guess function not good. Do with 0.0\")\n initial_guess_t = (lambda t: 0.0)(self.time_grid)\n return self._get_limited_pulse(initial_guess_t)\n\n def add_base_pulse(self, pulse: np.ndarray):\n \"\"\" Add the base pulse \"\"\"\n return pulse + self.base_pulse\n\n def add_initial_guess(self, pulse: np.ndarray):\n \"\"\" Add the initial pulse to the optimal pulse\"\"\"\n return self._get_initial_guess() + pulse\n\n def limit_pulse(self, pulse: np.ndarray):\n \"\"\" Apply the constraints to the optimal pulse\"\"\"\n return self._get_limited_pulse(pulse)\n\n def scale_pulse(self, pulse: np.ndarray):\n \"\"\" Scale the optimal pulse accordingly to the scaling function\"\"\"\n return self._get_scaling_function() * pulse\n\n def _get_limited_pulse(self, optimal_pulse: np.ndarray):\n \"\"\" Cut the pulse with the amplitude limits constraints \"\"\"\n if self.is_shrinked:\n return self._shrink_pulse(optimal_pulse)\n else:\n return np.maximum(np.minimum(optimal_pulse, self.amplitude_upper), self.amplitude_lower)\n\n @abstractmethod\n def _get_shaped_pulse(self) -> np.ndarray:\n \"\"\" Just an abstract method to get the optimized shape pulse\"\"\"\n"
] | [
[
"numpy.minimum",
"numpy.linspace",
"numpy.min",
"numpy.asarray",
"numpy.max",
"numpy.zeros"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
Chawin-S/TutorialISVC2019 | [
"dfa09aa55ad1e3c8612beb8b0e1437d588de474e"
] | [
"tutorial_notebooks/supplementary_code.py"
] | [
"import matplotlib.pyplot as plt\nimport numpy as np\n\nfrom ipywidgets import interact\nfrom mpl_toolkits.mplot3d.art3d import Poly3DCollection\nfrom scipy import stats\nfrom skimage import exposure, io\n\n\ndef show_plane(axis, plane, cmap=\"gray\", title=None):\n \"\"\"Shows a specific plane within 3D data.\n \"\"\"\n axis.imshow(plane, cmap=cmap)\n axis.set_xticks([])\n axis.set_yticks([])\n\n if title:\n axis.set_title(title)\n\n return None\n\n\ndef slice_in_3D(axis, shape, plane):\n \"\"\"Draws a cube in a 3D plot.\n\n Notes\n -----\n Originally from:\n https://stackoverflow.com/questions/44881885/python-draw-parallelepiped\n \"\"\"\n Z = np.array([[0, 0, 0],\n [1, 0, 0],\n [1, 1, 0],\n [0, 1, 0],\n [0, 0, 1],\n [1, 0, 1],\n [1, 1, 1],\n [0, 1, 1]])\n\n Z = Z * shape\n\n r = [-1, 1]\n\n X, Y = np.meshgrid(r, r)\n\n # plotting vertices\n axis.scatter3D(Z[:, 0], Z[:, 1], Z[:, 2])\n\n # list of sides' polygons of figure\n verts = [[Z[0], Z[1], Z[2], Z[3]],\n [Z[4], Z[5], Z[6], Z[7]],\n [Z[0], Z[1], Z[5], Z[4]],\n [Z[2], Z[3], Z[7], Z[6]],\n [Z[1], Z[2], Z[6], Z[5]],\n [Z[4], Z[7], Z[3], Z[0]],\n [Z[2], Z[3], Z[7], Z[6]]]\n\n # plotting sides\n axis.add_collection3d(\n Poly3DCollection(verts,\n facecolors=(0, 1, 1, 0.25),\n linewidths=1,\n edgecolors='darkblue')\n )\n\n verts = np.array([[[0, 0, 0],\n [0, 0, 1],\n [0, 1, 1],\n [0, 1, 0]]])\n verts = verts * (60, 256, 256)\n verts += [plane, 0, 0]\n\n axis.add_collection3d(\n Poly3DCollection(verts,\n facecolors='magenta',\n linewidths=1,\n edgecolors='black')\n )\n\n axis.set_xlabel('plane')\n axis.set_ylabel('col')\n axis.set_zlabel('row')\n\n # auto-scale plot axes\n scaling = np.array([getattr(axis, 'get_{}lim'.format(dim))() for dim in 'xyz'])\n axis.auto_scale_xyz(*[[np.min(scaling), np.max(scaling)]] * 3)\n\n return None\n\n\ndef slice_explorer(data, cmap='gray'):\n N = len(data)\n\n @interact(plane=(0, N - 1))\n def display_slice(plane=34):\n fig, axis = plt.subplots(figsize=(20, 5))\n axis_3D = fig.add_subplot(133, projection='3d')\n show_plane(axis, data[plane], title=f'Plane {plane}', cmap=cmap)\n slice_in_3D(axis=axis_3D, shape=data.shape, plane=plane)\n\n plt.show()\n\n return display_slice\n\n\ndef display(data, cmap=\"gray\", step=2):\n _, axes = plt.subplots(nrows=5, ncols=6, figsize=(16, 14))\n\n # getting data min and max to plot limits\n vmin, vmax = data.min(), data.max()\n\n for axis, image in zip(axes.flatten(), data[::step]):\n axis.imshow(image, cmap=cmap, vmin=vmin, vmax=vmax)\n axis.set_xticks([])\n axis.set_yticks([])\n\n return None\n\n\ndef plot_hist(axis, data, title=None):\n \"\"\"Helper function for plotting histograms.\n \"\"\"\n axis.hist(data.ravel(), bins=256)\n axis.ticklabel_format(axis='y', style='scientific', scilimits=(0, 0))\n\n if title:\n axis.set_title(title)\n\n return None\n\n\n\ndef results_from_part_1():\n\n data = io.imread(\"images/cells.tif\")\n\n vmin, vmax = stats.scoreatpercentile(data, (0.5, 99.5))\n rescaled = exposure.rescale_intensity(\n data,\n in_range=(vmin, vmax),\n out_range=np.float32\n )\n\n equalized = exposure.equalize_hist(data)\n\n return data, rescaled, equalized\n"
] | [
[
"numpy.meshgrid",
"numpy.min",
"matplotlib.pyplot.subplots",
"numpy.max",
"scipy.stats.scoreatpercentile",
"numpy.array",
"matplotlib.pyplot.show"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [
"0.13",
"1.6",
"0.14",
"1.10",
"0.15",
"1.4",
"0.16",
"1.9",
"0.19",
"1.5",
"0.18",
"1.2",
"1.7",
"0.12",
"1.0",
"0.17",
"1.3",
"1.8"
],
"tensorflow": []
}
] |
tsm55555/ares | [
"1773f82676d92499b196e9ec70a480f6f9e53db2"
] | [
"test/test_bim.py"
] | [
"import tensorflow as tf\nimport numpy as np\nimport os\nimport time\n\nfrom keras.datasets.cifar10 import load_data\n\nfrom ares import BIM, CrossEntropyLoss\nfrom ares.model.loader import load_model_from_path\nimport matplotlib.pyplot as plt\n\ndef plot_image(image,path): \n plt.figure(figsize=(40, 40))\n\n for i in range(100) :\n plt.subplot(10,10,i+1)\n plt.imshow(image[i])\n plt.axis('off')\n plt.tight_layout()\n\n #plt.show()\n \n plt.savefig(path, bbox_inches='tight') \n\nbatch_size = 100\n\nconfig = tf.ConfigProto()\nconfig.gpu_options.allow_growth = True\nsession = tf.Session(config=config)\n\nmodel_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), '../example/cifar10/resnet56.py')\nrs_model = load_model_from_path(model_path)\nmodel = rs_model.load(session)\n\n_, (xs_test, ys_test) = load_data()\nxs_test = (xs_test / 255.0) * (model.x_max - model.x_min) + model.x_min\nys_test = ys_test.reshape(len(ys_test))\n\nxs_ph = tf.placeholder(model.x_dtype, shape=(batch_size, *model.x_shape))\nlgs, lbs = model.logits_and_labels(xs_ph)\n\n\ndef iteration_callback(xs, xs_adv):\n delta = tf.abs(xs_adv - xs)\n return tf.reduce_max(tf.reshape(delta, (xs.shape[0], -1)), axis=1)\n\n\nloss = CrossEntropyLoss(model)\nattack = BIM(\n model=model,\n batch_size=batch_size,\n loss=loss,\n goal='ut',\n distance_metric='l_inf',\n session=session,\n iteration_callback=iteration_callback,\n)\nattack.config(\n iteration=10,\n magnitude=8.0 / 255.0,\n alpha=1.0 / 255.0,\n)\n\n\ni = 0\n\nstart = time.time()\nfor lo in range(batch_size, 5*batch_size, batch_size):\n xs = xs_test[lo - batch_size:lo]\n ys = ys_test[lo - batch_size:lo]\n\n #path = \"BIM/attack_1/original_\"+str(i)+\".png\"\n #plot_image(xs,\"BIM/attack_1/original_\"+str(i)+\".png\")\n count = 1\n try:\n g = attack.batch_attack(xs, ys=ys)\n while True:\n if count < 11:\n #print(\"iter \", count)\n count += 1\n #print(next(g))\n next(g)\n except StopIteration as e:\n xs_adv = e.value\n\n #plot_image(xs_adv,\"BIM/attack_1/adv\"+str(i)+\".png\")\n #i+=1\n\n lbs_pred = session.run(lbs, feed_dict={xs_ph: xs})\n lbs_adv = session.run(lbs, feed_dict={xs_ph: xs_adv})\n\n print(\n np.equal(ys, lbs_pred).astype(np.float).mean(),\n np.equal(ys, lbs_adv).astype(np.float).mean()\n )\nend = time.time()\nprint(\"time:\", end - start,\"s\")\nprint(\"\\nchanging attack config\\n\")\n\neps = np.concatenate((np.ones(50) * 4.0 / 255.0, np.ones(50) * 8.0 / 255.0))\nattack.config(\n iteration=10,\n magnitude=eps,\n alpha=eps / 8,\n)\nstart = time.time()\n\ni = 0\nfor lo in range(batch_size, 5*batch_size, batch_size):\n xs = xs_test[lo - batch_size:lo]\n ys = ys_test[lo - batch_size:lo]\n \n #plot_image(xs,\"BIM/attack_2/original_\"+str(i)+\".png\")\n count = 1\n try:\n g = attack.batch_attack(xs, ys=ys)\n while True:\n if count < 11:\n #print(\"iter \", count)\n count += 1\n #print(next(g))\n next(g)\n except StopIteration as exp:\n xs_adv = exp.value\n\n #plot_image(xs_adv,\"BIM/attack_2/adv_concat(4)_\"+str(i)+\".png\")\n i+=1\n\n lbs_pred = session.run(lbs, feed_dict={xs_ph: xs})\n lbs_adv = session.run(lbs, feed_dict={xs_ph: xs_adv})\n\n print(\n np.equal(ys, lbs_pred).astype(np.float).mean(),\n np.equal(ys, lbs_adv).astype(np.float).mean()\n )\nend = time.time()\nprint(\"time:\", end - start,\"s\")\n"
] | [
[
"matplotlib.pyplot.imshow",
"matplotlib.pyplot.tight_layout",
"tensorflow.reshape",
"tensorflow.placeholder",
"matplotlib.pyplot.savefig",
"numpy.ones",
"tensorflow.ConfigProto",
"matplotlib.pyplot.subplot",
"numpy.equal",
"tensorflow.Session",
"matplotlib.pyplot.axis",
"tensorflow.abs",
"matplotlib.pyplot.figure"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.10",
"1.12",
"1.4",
"1.13",
"1.5",
"1.7",
"0.12",
"1.0",
"1.2"
]
}
] |
mc-nya/darts_on_train | [
"1b184429a972b0ed5ea6fb421bfb5d56ca943b41"
] | [
"pycls/core/meters.py"
] | [
"#!/usr/bin/env python3\n\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\n\"\"\"Meters.\"\"\"\n\nfrom collections import deque\n\nimport numpy as np\nimport pycls.core.logging as logging\nimport torch\nfrom pycls.core.config import cfg\nfrom pycls.core.timer import Timer\n\n\nlogger = logging.get_logger(__name__)\n\n\ndef time_string(seconds):\n \"\"\"Converts time in seconds to a fixed-width string format.\"\"\"\n days, rem = divmod(int(seconds), 24 * 3600)\n hrs, rem = divmod(rem, 3600)\n mins, secs = divmod(rem, 60)\n return \"{0:02},{1:02}:{2:02}:{3:02}\".format(days, hrs, mins, secs)\n\n\ndef inter_union(preds, labels, num_classes):\n _, preds = torch.max(preds, 1)\n preds = preds.type(torch.uint8) + 1\n labels = labels.type(torch.uint8) + 1\n preds = preds * (labels > 0).type(torch.uint8)\n\n inter = preds * (preds == labels).type(torch.uint8)\n area_inter = torch.histc(inter.type(torch.int64), bins=num_classes, min=1, max=num_classes)\n area_preds = torch.histc(preds.type(torch.int64), bins=num_classes, min=1, max=num_classes)\n area_labels = torch.histc(labels.type(torch.int64), bins=num_classes, min=1, max=num_classes)\n area_union = area_preds + area_labels - area_inter\n\n return [area_inter.type(torch.float64) / labels.size(0), area_union.type(torch.float64) / labels.size(0)]\n\n\ndef topk_errors(preds, labels, ks):\n \"\"\"Computes the top-k error for each k.\"\"\"\n err_str = \"Batch dim of predictions and labels must match\"\n assert preds.size(0) == labels.size(0), err_str\n # Find the top max_k predictions for each sample\n _top_max_k_vals, top_max_k_inds = torch.topk(\n preds, max(ks), dim=1, largest=True, sorted=True\n )\n # (batch_size, max_k) -> (max_k, batch_size)\n top_max_k_inds = top_max_k_inds.t()\n # (batch_size, ) -> (max_k, batch_size)\n rep_max_k_labels = labels.view(1, -1).expand_as(top_max_k_inds)\n # (i, j) = 1 if top i-th prediction for the j-th sample is correct\n top_max_k_correct = top_max_k_inds.eq(rep_max_k_labels)\n # Compute the number of topk correct predictions for each k\n topks_correct = [top_max_k_correct[:k, :].view(-1).float().sum() for k in ks]\n return [(1.0 - x / preds.size(0)) * 100.0 for x in topks_correct]\n\n\ndef gpu_mem_usage():\n \"\"\"Computes the GPU memory usage for the current device (MB).\"\"\"\n mem_usage_bytes = torch.cuda.max_memory_allocated()\n return mem_usage_bytes / 1024 / 1024\n\n\nclass ScalarMeter(object):\n \"\"\"Measures a scalar value (adapted from Detectron).\"\"\"\n\n def __init__(self, window_size):\n self.deque = deque(maxlen=window_size)\n self.total = 0.0\n self.count = 0\n\n def reset(self):\n self.deque.clear()\n self.total = 0.0\n self.count = 0\n\n def add_value(self, value):\n self.deque.append(value)\n self.count += 1\n self.total += value\n\n def get_win_median(self):\n return np.median(self.deque)\n\n def get_win_avg(self):\n return np.mean(self.deque)\n\n def get_global_avg(self):\n return self.total / self.count\n\n\nclass TrainMeter(object):\n \"\"\"Measures training stats.\"\"\"\n\n def __init__(self, epoch_iters):\n self.epoch_iters = epoch_iters\n self.max_iter = cfg.OPTIM.MAX_EPOCH * epoch_iters\n self.iter_timer = Timer()\n self.loss = ScalarMeter(cfg.LOG_PERIOD)\n self.loss_total = 0.0\n self.lr = None\n # Current minibatch errors (smoothed over a window)\n self.mb_top1_err = ScalarMeter(cfg.LOG_PERIOD)\n self.mb_top5_err = ScalarMeter(cfg.LOG_PERIOD)\n # Number of misclassified examples\n self.num_top1_mis = 0\n self.num_top5_mis = 0\n self.num_samples = 0\n\n def reset(self, timer=False):\n if timer:\n self.iter_timer.reset()\n self.loss.reset()\n self.loss_total = 0.0\n self.lr = None\n self.mb_top1_err.reset()\n self.mb_top5_err.reset()\n self.num_top1_mis = 0\n self.num_top5_mis = 0\n self.num_samples = 0\n\n def iter_tic(self):\n self.iter_timer.tic()\n\n def iter_toc(self):\n self.iter_timer.toc()\n\n def update_stats(self, top1_err, top5_err, loss, lr, mb_size):\n # Current minibatch stats\n self.mb_top1_err.add_value(top1_err)\n self.mb_top5_err.add_value(top5_err)\n self.loss.add_value(loss)\n self.lr = lr\n # Aggregate stats\n self.num_top1_mis += top1_err * mb_size\n self.num_top5_mis += top5_err * mb_size\n self.loss_total += loss * mb_size\n self.num_samples += mb_size\n\n def get_iter_stats(self, cur_epoch, cur_iter):\n cur_iter_total = cur_epoch * self.epoch_iters + cur_iter + 1\n eta_sec = self.iter_timer.average_time * (self.max_iter - cur_iter_total)\n mem_usage = gpu_mem_usage()\n stats = {\n \"epoch\": \"{}/{}\".format(cur_epoch + 1, cfg.OPTIM.MAX_EPOCH),\n \"iter\": \"{}/{}\".format(cur_iter + 1, self.epoch_iters),\n \"time_avg\": self.iter_timer.average_time,\n \"time_diff\": self.iter_timer.diff,\n \"eta\": time_string(eta_sec),\n \"top1_err\": self.mb_top1_err.get_win_median(),\n \"top5_err\": self.mb_top5_err.get_win_median(),\n \"loss\": self.loss.get_win_median(),\n \"lr\": self.lr,\n \"mem\": int(np.ceil(mem_usage)),\n }\n return stats\n\n def log_iter_stats(self, cur_epoch, cur_iter):\n if (cur_iter + 1) % cfg.LOG_PERIOD != 0:\n return\n stats = self.get_iter_stats(cur_epoch, cur_iter)\n logger.info(logging.dump_log_data(stats, \"train_iter\"))\n return stats\n\n def get_epoch_stats(self, cur_epoch):\n cur_iter_total = (cur_epoch + 1) * self.epoch_iters\n eta_sec = self.iter_timer.average_time * (self.max_iter - cur_iter_total)\n mem_usage = gpu_mem_usage()\n top1_err = self.num_top1_mis / self.num_samples\n top5_err = self.num_top5_mis / self.num_samples\n avg_loss = self.loss_total / self.num_samples\n stats = {\n \"epoch\": \"{}/{}\".format(cur_epoch + 1, cfg.OPTIM.MAX_EPOCH),\n \"time_avg\": self.iter_timer.average_time,\n \"eta\": time_string(eta_sec),\n \"top1_err\": top1_err,\n \"top5_err\": top5_err,\n \"loss\": avg_loss,\n \"lr\": self.lr,\n \"mem\": int(np.ceil(mem_usage)),\n }\n return stats\n\n def log_epoch_stats(self, cur_epoch):\n stats = self.get_epoch_stats(cur_epoch)\n logger.info(logging.dump_log_data(stats, \"train_epoch\"))\n\n\nclass TestMeter(object):\n \"\"\"Measures testing stats.\"\"\"\n\n def __init__(self, max_iter):\n self.max_iter = max_iter\n self.iter_timer = Timer()\n # Current minibatch errors (smoothed over a window)\n self.mb_top1_err = ScalarMeter(cfg.LOG_PERIOD)\n self.mb_top5_err = ScalarMeter(cfg.LOG_PERIOD)\n # Min errors (over the full test set)\n self.min_top1_err = 100.0\n self.min_top5_err = 100.0\n # Number of misclassified examples\n self.num_top1_mis = 0\n self.num_top5_mis = 0\n self.num_samples = 0\n\n def reset(self, min_errs=False):\n if min_errs:\n self.min_top1_err = 100.0\n self.min_top5_err = 100.0\n self.iter_timer.reset()\n self.mb_top1_err.reset()\n self.mb_top5_err.reset()\n self.num_top1_mis = 0\n self.num_top5_mis = 0\n self.num_samples = 0\n\n def iter_tic(self):\n self.iter_timer.tic()\n\n def iter_toc(self):\n self.iter_timer.toc()\n\n def update_stats(self, top1_err, top5_err, mb_size):\n self.mb_top1_err.add_value(top1_err)\n self.mb_top5_err.add_value(top5_err)\n self.num_top1_mis += top1_err * mb_size\n self.num_top5_mis += top5_err * mb_size\n self.num_samples += mb_size\n\n def get_iter_stats(self, cur_epoch, cur_iter):\n mem_usage = gpu_mem_usage()\n iter_stats = {\n \"epoch\": \"{}/{}\".format(cur_epoch + 1, cfg.OPTIM.MAX_EPOCH),\n \"iter\": \"{}/{}\".format(cur_iter + 1, self.max_iter),\n \"time_avg\": self.iter_timer.average_time,\n \"time_diff\": self.iter_timer.diff,\n \"top1_err\": self.mb_top1_err.get_win_median(),\n \"top5_err\": self.mb_top5_err.get_win_median(),\n \"mem\": int(np.ceil(mem_usage)),\n }\n return iter_stats\n\n def log_iter_stats(self, cur_epoch, cur_iter):\n if (cur_iter + 1) % cfg.LOG_PERIOD != 0:\n return\n stats = self.get_iter_stats(cur_epoch, cur_iter)\n logger.info(logging.dump_log_data(stats, \"test_iter\"))\n return stats\n\n def get_epoch_stats(self, cur_epoch):\n top1_err = self.num_top1_mis / self.num_samples\n top5_err = self.num_top5_mis / self.num_samples\n self.min_top1_err = min(self.min_top1_err, top1_err)\n self.min_top5_err = min(self.min_top5_err, top5_err)\n mem_usage = gpu_mem_usage()\n stats = {\n \"epoch\": \"{}/{}\".format(cur_epoch + 1, cfg.OPTIM.MAX_EPOCH),\n \"time_avg\": self.iter_timer.average_time,\n \"top1_err\": top1_err,\n \"top5_err\": top5_err,\n \"min_top1_err\": self.min_top1_err,\n \"min_top5_err\": self.min_top5_err,\n \"mem\": int(np.ceil(mem_usage)),\n }\n return stats\n\n def log_epoch_stats(self, cur_epoch):\n stats = self.get_epoch_stats(cur_epoch)\n #print(stats)\n logger.info(logging.dump_log_data(stats, \"test_epoch\"))\n #print(stats)\n return stats\n\n\nclass TrainMeterIoU(object):\n \"\"\"Measures training stats.\"\"\"\n\n def __init__(self, epoch_iters):\n self.epoch_iters = epoch_iters\n self.max_iter = cfg.OPTIM.MAX_EPOCH * epoch_iters\n self.iter_timer = Timer()\n self.loss = ScalarMeter(cfg.LOG_PERIOD)\n self.loss_total = 0.0\n self.lr = None\n\n self.mb_miou = ScalarMeter(cfg.LOG_PERIOD)\n\n self.num_inter = np.zeros(cfg.MODEL.NUM_CLASSES)\n self.num_union = np.zeros(cfg.MODEL.NUM_CLASSES)\n self.num_samples = 0\n\n def reset(self, timer=False):\n if timer:\n self.iter_timer.reset()\n self.loss.reset()\n self.loss_total = 0.0\n self.lr = None\n self.mb_miou.reset()\n self.num_inter = np.zeros(cfg.MODEL.NUM_CLASSES)\n self.num_union = np.zeros(cfg.MODEL.NUM_CLASSES)\n self.num_samples = 0\n\n def iter_tic(self):\n self.iter_timer.tic()\n\n def iter_toc(self):\n self.iter_timer.toc()\n\n def update_stats(self, inter, union, loss, lr, mb_size):\n # Current minibatch stats\n self.mb_miou.add_value((inter / (union + 1e-10)).mean())\n self.loss.add_value(loss)\n self.lr = lr\n # Aggregate stats\n self.num_inter += inter * mb_size\n self.num_union += union * mb_size\n self.loss_total += loss * mb_size\n self.num_samples += mb_size\n\n def get_iter_stats(self, cur_epoch, cur_iter):\n cur_iter_total = cur_epoch * self.epoch_iters + cur_iter + 1\n eta_sec = self.iter_timer.average_time * (self.max_iter - cur_iter_total)\n mem_usage = gpu_mem_usage()\n stats = {\n \"epoch\": \"{}/{}\".format(cur_epoch + 1, cfg.OPTIM.MAX_EPOCH),\n \"iter\": \"{}/{}\".format(cur_iter + 1, self.epoch_iters),\n \"time_avg\": self.iter_timer.average_time,\n \"time_diff\": self.iter_timer.diff,\n \"eta\": time_string(eta_sec),\n \"miou\": self.mb_miou.get_win_median(),\n \"loss\": self.loss.get_win_median(),\n \"lr\": self.lr,\n \"mem\": int(np.ceil(mem_usage)),\n }\n return stats\n\n def log_iter_stats(self, cur_epoch, cur_iter):\n if (cur_iter + 1) % cfg.LOG_PERIOD != 0:\n return\n stats = self.get_iter_stats(cur_epoch, cur_iter)\n logger.info(logging.dump_log_data(stats, \"train_iter\"))\n\n def get_epoch_stats(self, cur_epoch):\n cur_iter_total = (cur_epoch + 1) * self.epoch_iters\n eta_sec = self.iter_timer.average_time * (self.max_iter - cur_iter_total)\n mem_usage = gpu_mem_usage()\n miou = (self.num_inter / (self.num_union + 1e-10)).mean()\n avg_loss = self.loss_total / self.num_samples\n stats = {\n \"epoch\": \"{}/{}\".format(cur_epoch + 1, cfg.OPTIM.MAX_EPOCH),\n \"time_avg\": self.iter_timer.average_time,\n \"eta\": time_string(eta_sec),\n \"miou\": miou,\n \"loss\": avg_loss,\n \"lr\": self.lr,\n \"mem\": int(np.ceil(mem_usage)),\n }\n return stats\n\n def log_epoch_stats(self, cur_epoch):\n stats = self.get_epoch_stats(cur_epoch)\n logger.info(logging.dump_log_data(stats, \"train_epoch\"))\n\n\nclass TestMeterIoU(object):\n \"\"\"Measures testing stats.\"\"\"\n\n def __init__(self, max_iter):\n self.max_iter = max_iter\n self.iter_timer = Timer()\n\n self.mb_miou = ScalarMeter(cfg.LOG_PERIOD)\n\n self.max_miou = 0.0\n\n self.num_inter = np.zeros(cfg.MODEL.NUM_CLASSES)\n self.num_union = np.zeros(cfg.MODEL.NUM_CLASSES)\n self.num_samples = 0\n\n def reset(self, min_errs=False):\n if min_errs:\n self.max_miou = 0.0\n self.iter_timer.reset()\n self.mb_miou.reset()\n self.num_inter = np.zeros(cfg.MODEL.NUM_CLASSES)\n self.num_union = np.zeros(cfg.MODEL.NUM_CLASSES)\n self.num_samples = 0\n\n def iter_tic(self):\n self.iter_timer.tic()\n\n def iter_toc(self):\n self.iter_timer.toc()\n\n def update_stats(self, inter, union, mb_size):\n self.mb_miou.add_value((inter / (union + 1e-10)).mean())\n self.num_inter += inter * mb_size\n self.num_union += union * mb_size\n self.num_samples += mb_size\n\n def get_iter_stats(self, cur_epoch, cur_iter):\n mem_usage = gpu_mem_usage()\n iter_stats = {\n \"epoch\": \"{}/{}\".format(cur_epoch + 1, cfg.OPTIM.MAX_EPOCH),\n \"iter\": \"{}/{}\".format(cur_iter + 1, self.max_iter),\n \"time_avg\": self.iter_timer.average_time,\n \"time_diff\": self.iter_timer.diff,\n \"miou\": self.mb_miou.get_win_median(),\n \"mem\": int(np.ceil(mem_usage)),\n }\n return iter_stats\n\n def log_iter_stats(self, cur_epoch, cur_iter):\n if (cur_iter + 1) % cfg.LOG_PERIOD != 0:\n return\n stats = self.get_iter_stats(cur_epoch, cur_iter)\n logger.info(logging.dump_log_data(stats, \"test_iter\"))\n\n def get_epoch_stats(self, cur_epoch):\n miou = (self.num_inter / (self.num_union + 1e-10)).mean()\n self.max_miou = max(self.max_miou, miou)\n mem_usage = gpu_mem_usage()\n stats = {\n \"epoch\": \"{}/{}\".format(cur_epoch + 1, cfg.OPTIM.MAX_EPOCH),\n \"time_avg\": self.iter_timer.average_time,\n \"miou\": miou,\n \"max_miou\": self.max_miou,\n \"mem\": int(np.ceil(mem_usage)),\n }\n return stats\n\n def log_epoch_stats(self, cur_epoch):\n stats = self.get_epoch_stats(cur_epoch)\n logger.info(logging.dump_log_data(stats, \"test_epoch\"))\n"
] | [
[
"torch.max",
"numpy.median",
"torch.cuda.max_memory_allocated",
"numpy.ceil",
"numpy.mean",
"numpy.zeros"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
RedHawk989/EyeTrackVR | [
"789879f3df60dc1e000124fdeb09b105c058656e"
] | [
"InceptionNet/inferno.py"
] | [
"import os\n\n\nimport cv2\nimport numpy as np\nfrom sympy import N\nimport tensorflow.compat.v1 as tf\n\nfrom config import config\nfrom models import Inception\nfrom utils import change_channel, gray_normalizer\n\nimport time\nfrom pythonosc import udp_client\nfrom scipy import ndimage\nimport sys\n\n\nimport pyttsx3\n\nengine = pyttsx3.init()\n\n\ntf.disable_v2_behavior()\n\n\ndef load_model(session, m_type, m_name):\n # load the weights based on best loss\n best_dir = \"best_loss\"\n\n # check model dir\n model_path = \"models/\" + m_name\n path = os.path.join(model_path, best_dir)\n if not os.path.exists(path):\n raise FileNotFoundError\n model = Inception(m_name, config)\n\n # load the best saved weights\n ckpt = tf.train.get_checkpoint_state(path)\n if ckpt and tf.train.checkpoint_exists(ckpt.model_checkpoint_path):\n model.restore(session, ckpt.model_checkpoint_path)\n\n else:\n raise ValueError(\"There is no best model with given model\")\n\n return model\n\n\ndef rescale(image):\n \"\"\"\n If the input video is other than network size, it will resize the input video\n :param image: a frame form input video\n :return: scaled down frame\n \"\"\"\n scale_side = max(image.shape)\n # image width and height are equal to 192\n scale_value = config[\"input_width\"] / scale_side\n\n # scale down or up the input image\n scaled_image = cv2.resize(image, dsize=None, fx=scale_value, fy=scale_value)\n\n # convert to numpy array\n scaled_image = np.asarray(scaled_image, dtype=np.uint8)\n\n # one of pad should be zero\n w_pad = int((config[\"input_width\"] - scaled_image.shape[1]) / 2)\n h_pad = int((config[\"input_width\"] - scaled_image.shape[0]) / 2)\n\n # create a new image with size of: (config[\"image_width\"], config[\"image_height\"])\n new_image = (\n np.ones((config[\"input_width\"], config[\"input_height\"]), dtype=np.uint8) * 250\n )\n\n # put the scaled image in the middle of new image\n new_image[\n h_pad : h_pad + scaled_image.shape[0], w_pad : w_pad + scaled_image.shape[1]\n ] = scaled_image\n\n return new_image\n\n\ndef writet(addressipn):\n addressips = addressipn.strip().lower()\n camadd = open(\"cam.txt\",\"w+\")\n camadd.write(str(addressips))\n print(addressips)\n camadd.close\n\n\n\n\n\n#def eyelid(frame1):\n # results = model1(frame1) # inference\n # for box in results.xyxy[0]: # box is a list of 4 numbers\n # if box[5]==0: # if the confidence is 0, then skip \n # xB = int(box[2]) # xB is the x coordinate of the bottom right corner\n # xA = int(box[0]) # xA is the x coordinate of the top left corner\n # yB = int(box[3]) # yB is the y coordinate of the bottom right corner\n # yA = int(box[1]) # yA is the y coordinate of the top left corner\n # vc.eyelidv = yA - yB\n # cv2.rectangle(frame1, (xA, yA), (xB, yB), (0, 255, 0), 2) # draw a rectangle around the detected object\n\n # if vc.eyelidv > vc.lidmax:\n # if vc.lidmax != 0:\n # vc.lidmax = vc.eyelidv\n # \n # if vc.eyelidv < vc.lidmin:\n # if vc.xmin != 0:\n # vc.xmin = vc.eyelidv\n #cv2.circle(img, (int((xA+xB)/2), int((yA+yB)/2)), 2, (0, 0, 255), -1)\n #cv2.imshow('EYEMODEL',frame1)\n\n\n\n\ndef main(\n m_type,\n m_name,\n):\n with tf.Session() as sess: # start a session\n\n # load best model\n model = load_model(sess, m_type, m_name) # load the best model\n cap = cv2.VideoCapture(vc.src) # load the camera\n #cap = rotated = ndimage.rotate(capu, 45)\n while cap.isOpened():\n\n\n with open(\"config.txt\") as calibratefl:\n lines = calibratefl.readlines()\n vx = float(lines[0].strip())\n vy = float(lines[1].strip())\n vxl = float(lines[2].strip())\n vyl = float(lines[3].strip())\n rv = float(lines[4].strip())\n calibratefl.close()\n\n\n ret, frame = cap.read()\n frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n try:\n frame1 = ndimage.rotate(frame, int(rv), reshape=True)\n frame1 = frame1[int(vxl): int(float(vy)), int(vyl): int(float(vx))]\n \n if frame1.shape[0] != 192:\n frame1 = rescale(frame1)\n \n image = gray_normalizer(frame1)\n image = change_channel(image, config[\"input_channel\"])\n \n # vc.el - 1\n # if vc.el == 1:\n # eyelid(frame1)\n # vc.el = 3\n\n \n [p] = model.predict(sess, [image])\n cv2.circle(frame1, (int(p[0]), int(p[1])), int(p[2]), (0, 0, 255), 2)\n cv2.circle(frame1, (int(p[0]), int(p[1])), 1, (0, 0, 255), -1)\n #print(int(p[0]), int(p[1]), int(p[2])) #int(p[2]) pupil pixel size (circ diamiter)\n\n\n\n xt = int(p[0]) \n yt = int(p[1])\n\n if vc.cfc == 1:\n try:\n \n with open(\"eyeconfig.cfg\") as eyecalib:\n lines = eyecalib.readlines()\n calibcenterx = float(lines[0].strip())\n calibcentery = float(lines[1].strip())\n calibrightx = float(lines[2].strip())\n calibleftx = float(lines[3].strip())\n calibupy = float(lines[4].strip())\n calibdowny = float(lines[5].strip())\n eyecalib.close()\n vc.cfc = 2\n \n except:\n print('eror')\n engine.say(\"A saved calibration file was not found. Please run the clibration program first.\")\n \n #will start the calibration program exe on release and close this one\n engine.runAndWait()\n sys.exit()\n\n #percentage = (((input - min) * 100) / (max - min)) / 100 only for reference because im dum and forget stuff\n \n \n\n\n xr = float((((xt - calibcenterx) * 100) / (calibrightx - calibcenterx)) / 100) \n\n xl = float((((xt - calibcenterx) * 100) / (calibleftx - calibcenterx)) / 100) \n\n\n\n yu = float((((yt - calibcentery) * 100) / (calibupy - calibcentery)) / 100)\n\n yd = float((((yt - calibcentery) * 100) / (calibdowny - calibcentery)) / 100)\n\n \n\n\n if xr > 0:\n if xr > 1:\n xr = 1.0\n client.send_message(\"/avatar/parameters/RightEyeX\", xr)\n client.send_message(\"/avatar/parameters/LeftEyeX\", xr)\n\n #print('XR', xr)\n if xl > 0:\n if xl > 1:\n xl = 1.0\n client.send_message(\"/avatar/parameters/RightEyeX\", -abs(xl))\n client.send_message(\"/avatar/parameters/LeftEyeX\", -abs(xl))\n\n\n if yd > 0:\n if yd > 1:\n yd = 1.0\n client.send_message(\"/avatar/parameters/EyesY\", -abs(yd))\n\n if yu > 0:\n if yu > 1:\n yu = 1.0\n \n client.send_message(\"/avatar/parameters/EyesY\", yu)\n\n\n\n\n cv2.imshow(\"frame\", frame1)\n cv2.imshow(\"img\", image)\n except:\n print('[ERROR] Main Loop Error')\n\n\n if cv2.waitKey(1) & 0xFF == ord(\"q\"):\n break\n cap.release()\n cv2.destroyAllWindows()\n\n\nif __name__ == \"__main__\":\n model_name = \"3A4Bh-Ref25\"\n model_type = \"INC\"\n video_path = 0\n\n\n # with open(\"config.txt\") as calibratefl:\n # lines = calibratefl.readlines()\n # rv = float(lines[4].strip())\n # calibratefl.close()\n\n \n def vc():\n\n vc.lidmax = 1 \n vc.lidmin = 6969 #( ͡° ͜ʖ ͡°) yes i know im stupid\n\n\n\n vc.cfc = 1\n vc.cc = 1\n vc.cu = 0\n vc.cd = 0\n vc.cl = 0\n vc.cr = 0\n vc.fc = 0\n\n vc.el = 2\n vc.eyelidv = 1\n vc.src = '1'\n vc()\n\n\n try:\n OSCip=\"127.0.0.1\" \n OSCport=9000 #VR Chat OSC port\n client = udp_client.SimpleUDPClient(OSCip, OSCport)\n except:\n print('[ERROR] Connection to VR Chat via OSC Failed')\n \n try:\n camadd= open(\"cam.txt\",\"r+\")\n vc.src = camadd.read().strip()\n camadd.close \n except:\n addressipn = input('Enter IP Stream Address of Camera :>: ')\n writet(addressipn)\n vc.src = addressipn.strip().lower()\n \n\n # initial a logger\n\n main(model_type, model_name)\n\n\n# 【=◈︿◈=】"
] | [
[
"tensorflow.compat.v1.train.get_checkpoint_state",
"numpy.asarray",
"tensorflow.compat.v1.disable_v2_behavior",
"numpy.ones",
"tensorflow.compat.v1.Session",
"tensorflow.compat.v1.train.checkpoint_exists"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
transformerzhou/NLP | [
"d3a50c7df735e97aeba70d40d1988ec4adb8f0af",
"7432595342b2f2139a788187d3b46fd2097bb10a"
] | [
"tests/CLS/BERT/bert_classification_train.py",
"fennlp/models/albert.py"
] | [
"import tensorflow as tf\n\nfrom fennlp.datas.checkpoint import LoadCheckpoint\nfrom fennlp.datas.dataloader import TFWriter, TFLoader\nfrom fennlp.metrics import Metric\nfrom fennlp.models import bert\nfrom fennlp.optimizers import optim\nfrom fennlp.tools import bert_init_weights_from_checkpoint\n\n# 载入参数\n# LoadCheckpoint(language='zh', model=\"bert\", parameters=\"base\", cased=True, url=None)\n# language: the language you used in your input data\n# model: the model you choose,could be bert albert and gpt2\n# parameters: can be base large xlarge xxlarge for albert, base medium large for gpt2, base large for BERT.\n# cased: True or false, only for bert model.\n# url: you can give a link of other checkpoint.\nload_check = LoadCheckpoint()\nparam, vocab_file, model_path = load_check.load_bert_param()\n\n# 定制参数\nparam.batch_size = 6\nparam.maxlen = 10\nparam.label_size = 15\n\n\n# 构建模型\nclass BERT_NER(tf.keras.Model):\n def __init__(self, param, **kwargs):\n super(BERT_NER, self).__init__(**kwargs)\n self.batch_size = param.batch_size\n self.maxlen = param.maxlen\n self.label_size = param.label_size\n self.bert = bert.BERT(param)\n self.dense = tf.keras.layers.Dense(self.label_size, activation=\"relu\")\n\n def call(self, inputs, is_training=True):\n bert = self.bert(inputs, is_training)\n sequence_output = bert.get_pooled_output() # batch,768\n pre = self.dense(sequence_output)\n output = tf.math.softmax(pre, axis=-1)\n return output\n\n def predict(self, inputs, is_training=False):\n output = self(inputs, is_training=is_training)\n return output\n\n\nmodel = BERT_NER(param)\n\nmodel.build(input_shape=(3, param.batch_size, param.maxlen))\n\nmodel.summary()\n\n# 构建优化器\noptimizer_bert = optim.AdamWarmup(learning_rate=2e-5, # 重要参数\n decay_steps=10000, # 重要参数\n warmup_steps=1000, )\n#\n# # 构建损失函数\n# mask_sparse_categotical_loss = Losess.MaskSparseCategoricalCrossentropy(from_logits=False,use_mask=True)\nmask_sparse_categotical_loss = tf.keras.losses.SparseCategoricalCrossentropy(from_logits=False)\n# # 初始化参数\nbert_init_weights_from_checkpoint(model,\n model_path,\n param.num_hidden_layers,\n pooler=True)\n\n# 写入数据 通过check_exist=True参数控制仅在第一次调用时写入\nwriter = TFWriter(param.maxlen, vocab_file,\n modes=[\"train\"], task='cls',\n check_exist=False)\n\nload = TFLoader(param.maxlen, param.batch_size, task='cls', epoch=5)\n\n# 训练模型\n# 使用tensorboard\nsummary_writer = tf.summary.create_file_writer(\"./tensorboard\")\n\n# Metrics\nf1score = Metric.SparseF1Score(average=\"macro\")\nprecsionscore = Metric.SparsePrecisionScore(average=\"macro\")\nrecallscore = Metric.SparseRecallScore(average=\"macro\")\naccuarcyscore = Metric.SparseAccuracy()\n\n# 保存模型\ncheckpoint = tf.train.Checkpoint(model=model)\nmanager = tf.train.CheckpointManager(checkpoint, directory=\"./save\",\n checkpoint_name=\"model.ckpt\",\n max_to_keep=3)\n# For train model\nBatch = 0\nfor X, token_type_id, input_mask, Y in load.load_train():\n\n with tf.GradientTape() as tape:\n predict = model([X, token_type_id, input_mask])\n loss = mask_sparse_categotical_loss(Y, predict)\n f1 = f1score(Y, predict)\n precision = precsionscore(Y, predict)\n recall = recallscore(Y, predict)\n accuracy = accuarcyscore(Y, predict)\n if Batch % 101 == 0:\n print(\"Batch:{}\\tloss:{:.4f}\".format(Batch, loss.numpy()))\n print(\"Batch:{}\\tacc:{:.4f}\".format(Batch, accuracy))\n print(\"Batch:{}\\tprecision{:.4f}\".format(Batch, precision))\n print(\"Batch:{}\\trecall:{:.4f}\".format(Batch, recall))\n print(\"Batch:{}\\tf1score:{:.4f}\".format(Batch, f1))\n manager.save(checkpoint_number=Batch)\n\n with summary_writer.as_default():\n tf.summary.scalar(\"loss\", loss, step=Batch)\n tf.summary.scalar(\"acc\", accuracy, step=Batch)\n tf.summary.scalar(\"f1\", f1, step=Batch)\n tf.summary.scalar(\"precision\", precision, step=Batch)\n tf.summary.scalar(\"recall\", recall, step=Batch)\n\n grads_bert = tape.gradient(loss, model.variables)\n optimizer_bert.apply_gradients(grads_and_vars=zip(grads_bert, model.variables))\n Batch += 1\n",
"#! usr/bin/env python3\n# -*- coding:utf-8 -*-\n\"\"\"\n@Author:zhoukaiyin\n\"\"\"\nimport tensorflow as tf\nfrom fennlp.tools import get_activation, get_shape_list, create_initializer\nfrom fennlp.layers import dense\nfrom fennlp.layers.embedding import WDEmbedding, SegPosEmbedding\nfrom fennlp.layers.albert_transformer import AlbertTransformer\n\n\nclass ALBERT(tf.keras.layers.Layer):\n def __init__(self,\n param=None,\n batch_size=2,\n maxlen=128,\n vocab_size=30000,\n hidden_size=4096,\n hidden_act=\"gelu\",\n num_hidden_groups=1,\n embedding_size=128,\n inner_group_num=1,\n num_attention_heads=64,\n initializer_range=0.02,\n hidden_dropout_prob=0.,\n type_vocab_size=2,\n intermediate_size=3072,\n max_position_embeddings=512,\n num_hidden_layers=12,\n attention_probs_dropout_prob=0.,\n use_one_hot_embedding=False,\n use_einsum=True,\n name=None,\n **kwargs):\n super(ALBERT, self).__init__(name=name, **kwargs)\n self.maxlen = param.get(\"maxlen\", maxlen)\n self.intermediate_size = param.get(\"intermediate_size\", intermediate_size)\n self.vocab_size = param.get(\"vocab_size\", vocab_size)\n self.batch_size = param.get(\"batch_size\", batch_size)\n self.hidden_size = param.get(\"hidden_size\", hidden_size)\n self.hidden_act = param.get(\"hidden_act\", hidden_act)\n self.initializer_range = param.get(\"initializer_range\", initializer_range)\n self.hidden_dropout_prob = param.get(\"hidden_dropout_prob\", hidden_dropout_prob)\n self.type_vocab_size = param.get(\"type_vocab_size\", type_vocab_size)\n self.num_attention_heads = param.get(\"num_attention_heads\", num_attention_heads)\n self.max_position_embeddings = param.get(\"max_position_embeddings\", max_position_embeddings)\n self.attention_probs_dropout_prob = param.get(\"attention_probs_dropout_prob\", attention_probs_dropout_prob)\n self.num_hidden_layers = param.get(\"num_hidden_layers\", num_hidden_layers)\n self.num_hidden_groups = param.get(\"num_hidden_groups\", num_hidden_groups)\n self.inner_group_num = param.get(\"inner_group_num\", inner_group_num)\n self.embedding_size = param.get(\"embedding_size\", embedding_size)\n self.use_einsum = use_einsum\n self.use_one_hot_embedding = use_one_hot_embedding\n self.attention_head_size = hidden_size // num_attention_heads\n\n def build(self, input_shape):\n self.token_embedding = WDEmbedding(vocab_size=self.vocab_size,\n embedding_size=self.embedding_size,\n initializer_range=self.initializer_range,\n word_embedding_name=\"word_embeddings\",\n use_one_hot_embedding=self.use_one_hot_embedding,\n name=\"embeddings\")\n # segment and position embedding\n self.segposembedding = SegPosEmbedding(use_token_type=True,\n hidden_dropout_prob=self.hidden_dropout_prob,\n token_type_vocab_size=self.type_vocab_size,\n token_type_embedding_name=\"token_type_embeddings\",\n use_position_embeddings=True,\n position_embedding_name=\"position_embeddings\",\n initializer_range=self.initializer_range,\n max_position_embeddings=self.max_position_embeddings,\n use_one_hot_embedding=self.use_one_hot_embedding,\n name=\"embeddings\"\n )\n self.shape_change = dense.DenseLayer2d(\n self.hidden_size,\n create_initializer(self.initializer_range),\n None,\n use_einsum=self.use_einsum,\n name=\"embedding_hidden_mapping_in\",\n )\n\n self.encoder_layer = AlbertTransformer(\n hidden_size=self.hidden_size,\n num_attention_heads=self.num_attention_heads,\n attention_head_size=self.attention_head_size,\n attention_probs_dropout_prob=self.attention_probs_dropout_prob,\n intermediate_size=self.intermediate_size,\n intermediate_act_fn=get_activation(self.hidden_act),\n initializer_range=self.initializer_range,\n hidden_dropout_prob=self.hidden_dropout_prob,\n use_einsum=True,\n name=\"inner_group_{}\".format(0)\n )\n\n self.pool_out = tf.keras.layers.Dense(\n self.hidden_size,\n activation=tf.tanh,\n # kernel_constraint=create_initializer(self.initializer_range),\n name=\"dense\")\n self.built = True\n\n def call(self, inputs, is_training=True):\n input_ids, token_type_ids, input_mask = tf.split(inputs, 3, 0)\n input_ids = tf.cast(tf.squeeze(input_ids, axis=0), tf.int32)\n token_type_ids = tf.cast(tf.squeeze(token_type_ids, axis=0), tf.int32)\n input_mask = tf.cast(tf.squeeze(input_mask, axis=0), tf.int32)\n input_shape = get_shape_list(input_ids)\n batch_size = input_shape[0]\n seq_length = input_shape[1]\n if input_mask is None:\n input_mask = tf.ones(shape=[batch_size, seq_length], dtype=tf.int32)\n if token_type_ids is None:\n token_type_ids = tf.zeros(shape=[batch_size, seq_length], dtype=tf.int32)\n with tf.keras.backend.name_scope(\"bert\"):\n self.embedding_output = self.token_embedding(input_ids)\n self.embedding_output = self.segposembedding(self.embedding_output, token_type_ids, is_training)\n with tf.keras.backend.name_scope(\"encoder\"):\n input_shape = get_shape_list(self.embedding_output, expected_rank=3)\n input_width = input_shape[2]\n self.all_layer_outputs = []\n if input_width != self.hidden_size:\n prev_output = self.shape_change(self.embedding_output)\n else:\n prev_output = self.embedding_output\n with tf.keras.backend.name_scope(\"transformer\"):\n for i in range(self.num_hidden_layers):\n group_idx = int(i / self.num_hidden_layers * self.num_hidden_groups)\n\n with tf.keras.backend.name_scope(\"group_%d\" % group_idx):\n layer_output = prev_output\n\n for inner_group_idx in range(self.inner_group_num):\n # with tf.keras.backend.name_scope(\"layer_%d\" % i):\n # for encoder_layer in encoder_layers:\n layer_output = self.encoder_layer(layer_output, input_mask, is_training)\n prev_output = layer_output\n self.all_layer_outputs.append(layer_output)\n self.sequence_output = layer_output\n\n return self\n\n def get_pooled_output(self):\n with tf.keras.backend.name_scope(\"pooler\"):\n first_token_tensor = tf.squeeze(self.sequence_output[:, 0:1, :], axis=1)\n self.pooled_output = self.pool_out(first_token_tensor)\n return self.pooled_output\n\n def get_sequence_output(self):\n return self.sequence_output\n\n def get_all_encoder_layers(self):\n return self.all_layer_outputs\n\n def get_embedding_output(self):\n return self.embedding_output\n"
] | [
[
"tensorflow.train.CheckpointManager",
"tensorflow.keras.losses.SparseCategoricalCrossentropy",
"tensorflow.train.Checkpoint",
"tensorflow.keras.layers.Dense",
"tensorflow.GradientTape",
"tensorflow.math.softmax",
"tensorflow.summary.scalar",
"tensorflow.summary.create_file_writer"
],
[
"tensorflow.zeros",
"tensorflow.keras.layers.Dense",
"tensorflow.ones",
"tensorflow.squeeze",
"tensorflow.keras.backend.name_scope",
"tensorflow.split"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.10"
]
}
] |
elcharles1/Datathon | [
"4871b351428c5ae177c43f570540c63a1872aac6"
] | [
"cleaning.py"
] | [
"# -*- coding: utf-8 -*-\n\"\"\"Final\n\nAutomatically generated by Colaboratory.\n\nOriginal file is located at\n https://colab.research.google.com/drive/1mE5FnyUrUhJIQx-DieJJqfy_sazRreay\n\"\"\"\n\nfrom google.colab import files\nimport pandas as pd\nimport numpy as np\nfrom sklearn import datasets, linear_model\nimport matplotlib.pyplot as plt\nfrom sklearn.model_selection import train_test_split\nfrom scipy.stats import kstest, norm\nfrom pandas import ExcelWriter\nimport xlrd \nfrom sklearn.preprocessing import Imputer\nimport math\n\nuploaded = files.upload()\n\ndf = []\nfor fn in uploaded.keys():\n df.append(pd.read_excel(fn, na_values='?'))\n\nsg = []\nfor key, item in df[0]['sg'].items():\n if item > 1.02:\n sg.append(item / 1000)\n else:\n sg.append(item + 0.005)\ndf[0]['sg'] = sg\n\n# mean\nmean_value=df[0]['age'].mean()\ndf[0]['age'] = df[0]['age'].fillna(math.ceil(mean_value))\nmean_value=df[0]['bp'].mean()\ndf[0]['bp'] = df[0]['bp'].fillna(math.ceil(mean_value))\nmean_value=df[0]['sg'].mean()\ndf[0]['sg'] = df[0]['sg'].fillna(math.ceil(mean_value))\nmean_value = df[0]['al'].mean()\ndf[0]['al'] = df[0]['al'].fillna(math.ceil(mean_value))\nmean_value = df[0]['su'].mean()\ndf[0]['su'] = df[0]['su'].fillna(math.ceil(mean_value))\nmean_value = df[0]['sc'].mean()\ndf[0]['sc'] = df[0]['sc'].fillna(mean_value)\nmean_value = df[0]['sod'].mean()\ndf[0]['sod'] = df[0]['sod'].fillna(math.ceil(mean_value))\nmean_value = df[0]['pot'].mean()\ndf[0]['pot'] = df[0]['pot'].fillna(mean_value)\nmean_value = df[0]['hemo'].mean()\ndf[0]['hemo'] = df[0]['hemo'].fillna(mean_value)\nmean_value = df[0]['pcv'].mean()\ndf[0]['pcv'] = df[0]['pcv'].fillna(math.ceil(mean_value))\nmean_value = df[0]['wc'].mean()\ndf[0]['wc'] = df[0]['wc'].fillna(math.ceil(mean_value))\nmean_value = df[0]['rc'].mean()\ndf[0]['rc'] = df[0]['rc'].fillna(mean_value)\n# median\nmedian = df[0]['bgr'].median()\ndf[0]['bgr'] = df[0]['bgr'].fillna(median)\nmedian = df[0]['bu'].median()\ndf[0]['bu'] = df[0]['bu'].fillna(median)\n\n# mode\ndf[0]['rbc'] = df[0]['rbc'].fillna(df[0]['rbc'].mode()[0])\ndf[0]['pc'] = df[0]['pc'].fillna(df[0]['pc'].mode()[0])\ndf[0]['pcc'] = df[0]['pcc'].fillna(df[0]['pcc'].mode()[0])\ndf[0]['ba'] = df[0]['ba'].fillna(df[0]['ba'].mode()[0])\ndf[0]['htn'] = df[0]['htn'].fillna(df[0]['htn'].mode()[0])\ndf[0]['htn'] = df[0]['htn'].fillna(df[0]['htn'].mode()[0])\ndf[0]['cad'] = df[0]['cad'].fillna(df[0]['cad'].mode()[0])\ndf[0]['appet'] = df[0]['appet'].fillna(df[0]['appet'].mode()[0])\ndf[0]['pe'] = df[0]['pe'].fillna(df[0]['pe'].mode()[0])\ndf[0]['ane'] = df[0]['ane'].fillna(df[0]['ane'].mode()[0])\ndf[0]['class'] = df[0]['class'].fillna(df[0]['class'].mode()[0])\n\nwriter = ExcelWriter('Result.xlsx')\ndf[0].to_excel(writer,'Hoja1')\n\nwriter.save()\nfiles.download(\"Result.xlsx\")"
] | [
[
"pandas.read_excel",
"pandas.ExcelWriter"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [
"0.23",
"0.21",
"2.0",
"1.4",
"1.3",
"0.19",
"1.1",
"1.5",
"0.24",
"0.20",
"1.0",
"0.25",
"1.2"
],
"scipy": [],
"tensorflow": []
}
] |
MartinPdeS/SuPyMode | [
"8a0a77ccbdae781d878f3d92a2b476774d666fa5"
] | [
"SuPyMode/BaseClass.py"
] | [
"import os\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.gridspec as gridspec\nfrom numpy import min, max\nfrom itertools import combinations\nfrom cycler import cycler\nplt.rc('lines', linewidth=2)\nplt.rc('axes', prop_cycle=(\n cycler('linestyle', ['-', '--', ':', '-.']) *\n cycler('color', ['r', 'g', 'b', 'y', 'k'])\n ))\n\nfrom SuPyMode.Config import *\nfrom SuPyMode.Directories import *\nfrom SuPyMode.utils import Multipage, prePlot, ToList, Enumerate\n\n\nclass SetPlots(object):\n\n @prePlot\n def PlotIndex(self, fig):\n I = self.Index\n for i in range(self.sMode):\n plt.plot(self.Geometry.ITRList, I[:,i], label=f'{i}')\n\n return self.PlotKwarg['Index'], [min(I), max(I)]\n\n @prePlot\n def PlotBeta(self, fig):\n B = self.Beta\n for i in range(self.sMode):\n plt.plot(self.Geometry.ITRList, B[:,i], label=f'{i}')\n\n return self.PlotKwarg['Beta'], [min(B), max(B)]\n\n\n @prePlot\n def PlotCoupling(self, fig):\n C = self.Coupling\n\n for n, (i,j) in enumerate( self.Combination ):\n plt.plot(self.Geometry.ITRList[0:], C[:,i,j], label=f'{i} - {j}')\n\n return self.PlotKwarg['Coupling'], [min(C), max(C)]\n\n\n @prePlot\n def PlotAdiabatic(self, fig):\n A = self.Adiabatic\n print(A)\n print('='*100)\n print(self.Coupling)\n for n, (i,j) in enumerate( self.Combination ):\n plt.plot(self.Geometry.ITRList[0:], A[:,i,j], label=f'{i} - {j}')\n\n return self.PlotKwarg['Adiabatic'], [min(A), max(A)]\n\n\n def PlotFields(self, iter):\n\n fig = plt.figure(figsize=((self.sMode+1)*3,3))\n spec2 = gridspec.GridSpec(ncols=(self.sMode+1), nrows=3, figure=fig)\n\n for mode in range(self.sMode):\n axes = fig.add_subplot(spec2[0:2,mode])\n str = r\"$n_{eff}$\"\n title = f\"Mode {mode} [{str}: {self[mode][iter].Index:.6f}]\"\n\n self[mode][iter].__plot__(axes, title)\n fig.suptitle(f'ITR:{self.Geometry.ITRList[iter]}')\n\n axes = fig.add_subplot(spec2[0:2,-1])\n\n self.Geometry.__plot__(axes)\n\n plt.tight_layout()\n\n return fig\n\n\n def GenFigures(self, Input, iter, PlotKwarg):\n iter = ToList(iter)\n\n Input = set(Input)\n\n self.UpdatePlotKwarg(PlotKwarg)\n\n figures = []\n\n if Input & set( ['All', 'Index'] ): figures.append( self.PlotIndex() )\n\n if Input & set( ['All', 'Beta'] ): figures.append( self.PlotBeta() )\n\n if Input & set( ['All', 'Coupling'] ): figures.append( self.PlotCoupling() )\n\n if Input & set( ['All', 'Adiabatic'] ): figures.append( self.PlotAdiabatic() )\n\n for i in iter:\n if Input & set( ['All', 'Fields'] ): figures.append( self.PlotFields(i) )\n\n return figures\n\n\n def Plot(self, Input, iter=0, PlotKwarg=None, Combination=None):\n\n if Combination is None:\n self.Combination = tuple(combinations( np.arange(self.sMode), 2 ) )\n else:\n self.Combination = Combination\n\n figures = self.GenFigures(Input, iter, PlotKwarg)\n\n plt.show()\n\n\n def UpdatePlotKwarg(self, kwargs):\n if isinstance(kwargs, dict):\n for key, val in kwargs.items():\n BasePlotKwarg[key].update(kwargs[key])\n\n self.PlotKwarg = BasePlotKwarg\n\n\n def SaveFig(self, Input, Directory, iter=0, dpi=100, PlotKwarg=None, Combination=None):\n\n if Combination is None:\n self.Combination = tuple(combinations( np.arange(self.sMode), 2 ) )\n else:\n self.Combination = Combination\n\n figures = self.GenFigures(Input, iter, PlotKwarg)\n\n dir = os.path.join(ZeroPath, Directory) + '.pdf'\n\n Multipage(dir, figs=figures, dpi=dpi)\n\n\n\nclass SetProperties(object):\n\n @property\n def ITR(self):\n return self.Geometry.ITRList\n\n\n @property\n def Coupling(self):\n if self._Coupling is None:\n self._Coupling = self.CppSolver.ComputingCoupling()\n return self._Coupling\n\n else:\n return self._Coupling\n\n\n @property\n def Adiabatic(self):\n if self._Adiabatic is None:\n self._Coupling = self.CppSolver.ComputingCoupling()\n self._Adiabatic = self.CppSolver.ComputingAdiabatic()\n return self._Adiabatic\n\n else:\n return self._Adiabatic\n\n\n @property\n def Beta(self):\n if self._Beta is None:\n self._Beta = self.CppSolver.GetBetas()\n return self._Beta\n\n else:\n return self._Beta\n\n\n @property\n def Index(self):\n if self._Index is None:\n self._Index = self.CppSolver.GetIndices()\n return self._Index\n\n else:\n return self._Index\n\n\n\n\n\n\n\n\n\n\n\n\n\n# -\n"
] | [
[
"matplotlib.pyplot.tight_layout",
"numpy.min",
"numpy.arange",
"matplotlib.pyplot.rc",
"matplotlib.pyplot.plot",
"numpy.max",
"matplotlib.gridspec.GridSpec",
"matplotlib.pyplot.show",
"matplotlib.pyplot.figure"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
abrupt-climate/hypercc | [
"f5c47e4a9056286d318b5f1002f1aa5e10716238"
] | [
"hypercc/data/file.py"
] | [
"\"\"\"\nFunctionality for reading and interpreting single NetCDF files.\n\"\"\"\n\nfrom datetime import date\n\nimport netCDF4\nfrom pyparsing import Word, Suppress, Group, tokenMap, alphas, nums\nimport numpy as np\n\n\ndef parse_time_units(units):\n \"\"\"Parse time unit string from a NetCDF file. Such a string may look like::\n\n \"<unit> since <date>\"\n\n where ``<date>`` looks like::\n\n \"<year>-<month>-<day>\"\n\n Returns: 2-tuple (unit string, datetime object)\n \"\"\"\n p_int = Word(nums).setParseAction(tokenMap(int))\n p_date = Group(p_int('year') + Suppress('-') +\n p_int('month') + Suppress('-') +\n p_int('day'))('date').setParseAction(\n tokenMap(lambda args: date(*args)))\n p_time_unit = Word(alphas)('units') + Suppress(\"since\") + p_date\n result = p_time_unit.parseString(units)\n return result['units'], result['date'][0]\n\n\nclass File(object):\n \"\"\"Interface to single NetCDF4 file with bounds set on the time.\n\n Rationale: When we load a set of datafiles from a time series,\n sometimes the times may overlap. In this case we may set the\n ``bounds`` property in this object to limit data to the needed time slots.\n Combining the limited datasets will result in a a nice contiguous dataset.\n \"\"\"\n def __init__(self, f):\n self.path = f\n # pylint: disable=E1101\n self.data = netCDF4.Dataset(f, 'r', format='NETCDF4')\n self.bounds = slice(None)\n\n @property\n def time(self):\n \"\"\"Returns the time variable restricted to the given bounds.\"\"\"\n return self.data.variables['time'][self.bounds]\n\n @property\n def lat(self):\n \"\"\"Returns the latitudes of the grid.\"\"\"\n return self.data.variables['lat'][:]\n\n @property\n def lon(self):\n \"\"\"Returns the longitudes of the grid.\"\"\"\n return self.data.variables['lon'][:]\n\n @property\n def lat_bnds(self):\n \"\"\"Returns the latitude intervals of the grid.\"\"\"\n return self.data.variables['lat_bnds'][:]\n\n @property\n def lon_bnds(self):\n \"\"\"Returns the longitude intervals of the grid.\"\"\"\n return self.data.variables['lon_bnds'][:]\n\n def get(self, var):\n \"\"\"Get the values of a given variable limited to the time bounds set.\n \"\"\"\n return self.data.variables[var][self.bounds]\n\n def get_masked(self, var):\n \"\"\"The NetCDF file may specify a floating point value for missing\n values, for instance in the case of variables that only have valid\n entries on sea or land cells. In this case we'd like to obtain a\n masked array in stead of a normal ndarray object.\n\n This function returns a masked array for the given variable. When no\n mask is needed, a normal numpy array is returned.\n \"\"\"\n data = self.data.variables[var][self.bounds]\n missing_value = self.data.variables[var].missing_value\n masked_data = np.ma.masked_equal(data, missing_value)\n if masked_data.mask is np.ma.nomask:\n return masked_data.data\n else:\n return masked_data\n\n @property\n def time_units(self):\n \"\"\"Obtain time units from the NetCDF\"\"\"\n dt, t0 = parse_time_units(self.data.variables['time'].units)\n return dt, t0\n"
] | [
[
"numpy.ma.masked_equal"
]
] | [
{
"matplotlib": [],
"numpy": [
"1.10",
"1.12",
"1.11",
"1.19",
"1.13",
"1.16",
"1.9",
"1.18",
"1.20",
"1.7",
"1.15",
"1.14",
"1.17",
"1.8"
],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
alan-toledo/Machine-Learning-Algorithms | [
"5cbf389b28142deab7eb892b981524699571e848"
] | [
"Gaussian Discriminant Analysis/util.py"
] | [
"import matplotlib.pyplot as plt\nimport numpy as np\n\n\ndef load_dataset(csv_path, label_col='y'):\n \"\"\"Load dataset from a CSV file.\n\n Args:\n csv_path: Path to CSV file containing dataset.\n label_col: Name of column to use as labels (should be 'y' or 't').\n add_intercept: Add an intercept entry to x-values.\n\n Returns:\n xs: Numpy array of x-values (inputs).\n ys: Numpy array of y-values (labels).\n \"\"\"\n\n # Validate label_col argument\n allowed_label_cols = ('y', 't')\n if label_col not in allowed_label_cols:\n raise ValueError('Invalid label_col: {} (expected {})'\n .format(label_col, allowed_label_cols))\n\n # Load headers\n with open(csv_path, 'r') as csv_fh:\n headers = csv_fh.readline().strip().split(',')\n\n # Load features and labels\n x_cols = [i for i in range(len(headers)) if headers[i].startswith('x')]\n l_cols = [i for i in range(len(headers)) if headers[i] == label_col]\n inputs = np.loadtxt(csv_path, delimiter=',', skiprows=1, usecols=x_cols)\n labels = np.loadtxt(csv_path, delimiter=',', skiprows=1, usecols=l_cols)\n\n if inputs.ndim == 1:\n inputs = np.expand_dims(inputs, -1)\n\n return inputs, labels\n\n\ndef plot(x, y, theta0, theta, save_path):\n \"\"\"Plot dataset and fitted logistic regression parameters.\n\n Args:\n x: Matrix of training examples, one per row.\n y: Vector of labels in {0, 1}.\n theta: Vector of parameters for logistic regression model.\n save_path: Path to save the plot.\n correction: Correction factor to apply, if any.\n \"\"\"\n # Plot dataset\n plt.figure()\n plt.plot(x[y == 1, -2], x[y == 1, -1], 'bx', linewidth=2)\n plt.plot(x[y == 0, -2], x[y == 0, -1], 'go', linewidth=2)\n\n # Plot decision boundary (found by solving for theta^T x = 0)\n x1 = np.arange(min(x[:, -2]), max(x[:, -2]), 0.01)\n x2 = -(theta0 / theta[1] + theta[0] / theta[1] * x1)\n plt.plot(x1, x2, c='red', linewidth=2)\n plt.xlim(x[:, -2].min()-.1, x[:, -2].max()+.1)\n plt.ylim(x[:, -1].min()-.1, x[:, -1].max()+.1)\n\n # Add labels and save to disk\n plt.xlabel('x1')\n plt.ylabel('x2')\n plt.savefig(save_path)\n"
] | [
[
"numpy.expand_dims",
"matplotlib.pyplot.figure",
"matplotlib.pyplot.savefig",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.xlabel",
"numpy.loadtxt",
"matplotlib.pyplot.ylabel"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
ch6845/attributionpriors | [
"815a7892a8d4c42fb429856746212a44f67d2547"
] | [
"attributionpriors/pytorch_ops_cpu.py"
] | [
"#!/usr/bin/env python\nimport functools\nimport operator\nimport torch\nfrom torch.autograd import grad\nfrom torch.utils.data import DataLoader\n\ndef gather_nd(params, indices):\n \"\"\"\n Args:\n params: Tensor to index\n indices: k-dimension tensor of integers. \n Returns:\n output: 1-dimensional tensor of elements of ``params``, where\n output[i] = params[i][indices[i]]\n\n params indices output\n\n 1 2 1 1 4\n 3 4 2 0 ----> 5\n 5 6 0 0 1\n \"\"\"\n max_value = functools.reduce(operator.mul, list(params.size())) - 1\n indices = indices.t().long()\n ndim = indices.size(0)\n idx = torch.zeros_like(indices[0]).long()\n m = 1\n\n for i in range(ndim)[::-1]:\n idx += indices[i]*m\n m *= params.size(i)\n\n idx[idx < 0] = 0\n idx[idx > max_value] = 0\n return torch.take(params, idx)\n \n\nclass AttributionPriorExplainer(object):\n def __init__(self, background_dataset, batch_size, random_alpha=True,k=1):\n self.random_alpha = random_alpha\n self.k = k\n self.batch_size = batch_size\n self.ref_sampler = DataLoader(\n dataset=background_dataset, \n batch_size=batch_size*k, \n shuffle=True, \n drop_last=True)\n return\n \n def _get_samples_input(self, input_tensor, reference_tensor):\n '''\n calculate interpolation points\n Args:\n input_tensor: Tensor of shape (batch, ...), where ... indicates\n the input dimensions. \n reference_tensor: A tensor of shape (batch, k, ...) where ... \n indicates dimensions, and k represents the number of background \n reference samples to draw per input in the batch.\n Returns: \n samples_input: A tensor of shape (batch, k, ...) with the \n interpolated points between input and ref.\n '''\n input_dims = list(input_tensor.size())[1:]\n num_input_dims = len(input_dims)\n \n batch_size = reference_tensor.size()[0]\n k_ = reference_tensor.size()[1]\n\n # Grab a [batch_size, k]-sized interpolation sample\n if self.random_alpha:\n t_tensor = torch.FloatTensor(batch_size, k_).uniform_(0,1)\n\n shape = [batch_size, k_] + [1] * num_input_dims\n interp_coef = t_tensor.view(*shape)\n\n # Evaluate the end points\n end_point_ref = (1.0 - interp_coef) * reference_tensor\n\n input_expand_mult = input_tensor.unsqueeze(1)\n end_point_input = interp_coef * input_expand_mult\n \n # A fine Affine Combine\n samples_input = end_point_input + end_point_ref\n return samples_input\n \n def _get_samples_delta(self, input_tensor, reference_tensor):\n input_expand_mult = input_tensor.unsqueeze(1)\n sd = input_expand_mult - reference_tensor\n return sd\n \n def _get_grads(self, samples_input, model, sparse_labels=None):\n samples_input.requires_grad = True\n\n grad_tensor = torch.zeros(samples_input.shape).float()\n\n \n for i in range(self.k):\n particular_slice = samples_input[:,i]\n batch_output = model(particular_slice)\n # should check that users pass in sparse labels\n # Only look at the user-specified label\n if batch_output.size(1) > 1:\n sample_indices = torch.arange(0,batch_output.size(0))\n indices_tensor = torch.cat([\n sample_indices.unsqueeze(1), \n sparse_labels.unsqueeze(1)], dim=1)\n batch_output = gather_nd(batch_output, indices_tensor)\n\n model_grads = grad(\n outputs=batch_output,\n inputs=particular_slice,\n grad_outputs=torch.ones_like(batch_output),\n create_graph=True)\n grad_tensor[:,i,:] = model_grads[0]\n return grad_tensor\n \n def shap_values(self, model, input_tensor, sparse_labels=None):\n \"\"\"\n Calculate expected gradients approximation of Shapley values for the \n sample ``input_tensor``.\n\n Args:\n model (torch.nn.Module): Pytorch neural network model for which the\n output should be explained.\n input_tensor (torch.Tensor): Pytorch tensor representing the input\n to be explained.\n sparse_labels (optional, default=None): \n \"\"\"\n reference_tensor = next(iter(self.ref_sampler))[0].float()\n shape = reference_tensor.shape\n reference_tensor = reference_tensor.view(\n self.batch_size, \n self.k, \n *(shape[1:]))\n samples_input = self._get_samples_input(input_tensor, reference_tensor)\n samples_delta = self._get_samples_delta(input_tensor, reference_tensor)\n grad_tensor = self._get_grads(samples_input, model, sparse_labels)\n mult_grads = samples_delta * grad_tensor\n expected_grads = mult_grads.mean(1)\n return expected_grads\n"
] | [
[
"torch.take",
"torch.zeros",
"torch.zeros_like",
"torch.utils.data.DataLoader",
"torch.FloatTensor",
"torch.ones_like"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
amanchhaparia/cupy | [
"a47ad3105f0fe817a4957de87d98ddccb8c7491f"
] | [
"cupyx/jit/_compile.py"
] | [
"import ast\nimport collections\nimport inspect\nimport math\nimport numbers\nimport re\nimport sys\nimport warnings\n\nimport numpy\n\nfrom cupy._core._codeblock import CodeBlock\nfrom cupy._core import _kernel\nfrom cupyx import jit\nfrom cupyx.jit import _cuda_types\nfrom cupyx.jit import _cuda_typerules\nfrom cupyx.jit import _internal_types\nfrom cupyx.jit._internal_types import Data\nfrom cupyx.jit._internal_types import Constant\nfrom cupyx.jit import _builtin_funcs\n\n\n_is_debug_mode = False\n\n_typeclasses = (bool, numpy.bool_, numbers.Number)\n\nResult = collections.namedtuple('Result', ['func_name', 'code', 'return_type'])\n\n\nclass _JitCompileError(Exception):\n\n def __init__(self, e, node):\n self.error_type = type(e)\n self.mes = str(e)\n self.node = node\n\n def reraise(self, pycode):\n start = self.node.lineno\n end = getattr(self.node, 'end_lineno', start)\n pycode = '\\n'.join([\n (f'> {line}' if start <= i + 1 <= end else f' {line}').rstrip()\n for i, line in enumerate(pycode.split('\\n'))])\n raise self.error_type(self.mes + '\\n\\n' + pycode)\n\n\ndef transpile_function_wrapper(func):\n def new_func(node, *args, **kwargs):\n try:\n return func(node, *args, **kwargs)\n except _JitCompileError:\n raise\n except Exception as e:\n raise _JitCompileError(e, node)\n\n return new_func\n\n\ndef _parse_function_object(func):\n # Parses function object into ast.FunctionDef object.\n if not callable(func):\n raise ValueError('`func` must be a callable object.')\n\n if func.__name__ != '<lambda>':\n if jit._getsource_func is None:\n lines = inspect.getsource(func).split('\\n')\n num_indent = len(lines[0]) - len(lines[0].lstrip())\n source = '\\n'.join([\n line.replace(' ' * num_indent, '', 1) for line in lines])\n else:\n source = jit._getsource_func(func)\n tree = ast.parse(source)\n assert isinstance(tree, ast.Module)\n assert len(tree.body) == 1\n return tree.body[0], source\n\n if jit._getsource_func is not None:\n full_source = jit._getsource_func(func)\n start_line, end_line = 0, math.inf\n source = full_source\n else:\n try:\n filename = inspect.getsourcefile(func)\n except TypeError:\n filename = None\n if filename is None:\n raise ValueError(f'JIT needs access to Python source for {func}'\n 'but could not be located')\n with open(filename) as f:\n full_source = f.read()\n source, start_line = inspect.getsourcelines(func)\n end_line = start_line + len(source)\n source = ''.join(source)\n\n tree = ast.parse(full_source)\n\n nodes = [node for node in ast.walk(tree)\n if isinstance(node, ast.Lambda)\n and start_line <= node.lineno < end_line]\n if len(nodes) > 1:\n raise ValueError('Multiple callables are found near the'\n f' definition of {func}, and JIT could not'\n ' identify the source code for it.')\n node = nodes[0]\n return ast.FunctionDef(\n name='_lambda_kernel', args=node.args,\n body=[ast.Return(node.body)],\n decorator_list=[], returns=None, type_comment=None,\n ), source\n\n\ndef transpile(func, attributes, mode, in_types, ret_type):\n \"\"\"Transpile the target function\n Args:\n func (function): Target function.\n attributes (list of str): Attributes of the generated CUDA function.\n mode ('numpy' or 'cuda'): The rule for typecast.\n in_types (list of _cuda_types.TypeBase): Types of the arguments.\n ret_type (_cuda_types.TypeBase or None): Type of the return value.\n \"\"\"\n cvars = inspect.getclosurevars(func)\n consts = dict(**cvars.globals, **cvars.nonlocals, **cvars.builtins)\n attributes = ' '.join(attributes)\n tree, source = _parse_function_object(func)\n cuda_code, env = _transpile_function(\n tree, attributes, mode, consts, in_types, ret_type, source=source)\n cuda_code = ''.join([code + '\\n' for code in env.preambles]) + cuda_code\n return Result(\n func_name=tree.name,\n code=cuda_code,\n return_type=env.ret_type,\n )\n\n\ndef _indent(lines, spaces=' '):\n return [spaces + line for line in lines]\n\n\ndef is_constants(*values):\n assert all(isinstance(x, _internal_types.Expr) for x in values)\n return all(isinstance(x, Constant) for x in values)\n\n\nclass Environment:\n \"\"\"Environment of the scope\n\n Attributes:\n mode ('numpy' or 'cuda'): The rule for typecast.\n consts (dict): The dictionary with keys as the variable names and\n the values as the data that is determined at compile-time.\n params (dict): The dictionary of function arguments with keys as\n the variable names and the values as the Data.\n locals (dict): The dictionary with keys as the variable names and the\n values as the Data stored at the local scope of the function.\n ret_type (_cuda_types.TypeBase):\n The type of return value of the function.\n If it is initialized to be ``None``, the return type must be\n inferred until the end of transpilation of the function.\n \"\"\"\n\n def __init__(self, mode, consts, params, ret_type):\n self.mode = mode\n self.consts = consts\n self.params = params\n self.locals = {}\n self.ret_type = ret_type\n self.preambles = set()\n self.count = 0\n\n def __getitem__(self, key):\n if key in self.locals:\n return self.locals[key]\n if key in self.params:\n return self.params[key]\n if key in self.consts:\n return self.consts[key]\n return None\n\n def __setitem__(self, key, value):\n self.locals[key] = value\n\n def get_fresh_variable_name(self, prefix='', suffix=''):\n self.count += 1\n return f'{prefix}{self.count}{suffix}'\n\n\ndef _transpile_function(\n func, attributes, mode, consts, in_types, ret_type, *, source):\n \"\"\"Transpile the function\n Args:\n func (ast.FunctionDef): Target function.\n attributes (str): The attributes of target function.\n mode ('numpy' or 'cuda'): The rule for typecast.\n consts (dict): The dictionary with keys as variable names and\n values as concrete data object.\n in_types (list of _cuda_types.TypeBase): The types of arguments.\n ret_type (_cuda_types.TypeBase): The type of return value.\n\n Returns:\n code (str): The generated CUDA code.\n env (Environment): More details of analysis result of the function,\n which includes preambles, estimated return type and more.\n \"\"\"\n try:\n return _transpile_function_internal(\n func, attributes, mode, consts, in_types, ret_type)\n except _JitCompileError as e:\n exc = e\n if _is_debug_mode:\n exc.reraise(source)\n\n # Raises the error out of `except` block to clean stack trace.\n exc.reraise(source)\n assert False\n\n\ndef _transpile_function_internal(\n func, attributes, mode, consts, in_types, ret_type):\n consts = dict([(k, Constant(v)) for k, v, in consts.items()])\n\n if not isinstance(func, ast.FunctionDef):\n # TODO(asi1024): Support for `ast.ClassDef`.\n raise NotImplementedError('Not supported: {}'.format(type(func)))\n if len(func.decorator_list) > 0:\n if sys.version_info >= (3, 9):\n # Code path for Python versions that support `ast.unparse`.\n for deco in func.decorator_list:\n deco_code = ast.unparse(deco)\n if not any(word in deco_code\n for word in ['rawkernel', 'vectorize']):\n warnings.warn(\n f'Decorator {deco_code} may not supported in JIT.',\n RuntimeWarning)\n arguments = func.args\n if arguments.vararg is not None:\n raise NotImplementedError('`*args` is not supported currently.')\n if len(arguments.kwonlyargs) > 0: # same length with `kw_defaults`.\n raise NotImplementedError(\n 'keyword only arguments are not supported currently .')\n if arguments.kwarg is not None:\n raise NotImplementedError('`**kwargs` is not supported currently.')\n if len(arguments.defaults) > 0:\n raise NotImplementedError(\n 'Default values are not supported currently.')\n\n args = [arg.arg for arg in arguments.args]\n if len(args) != len(in_types):\n raise TypeError(\n f'{func.name}() takes {len(args)} positional arguments '\n f'but {len(in_types)} were given.')\n params = dict([(x, Data(x, t)) for x, t in zip(args, in_types)])\n env = Environment(mode, consts, params, ret_type)\n body = _transpile_stmts(func.body, True, env)\n params = ', '.join([env[a].ctype.declvar(a) for a in args])\n local_vars = [v.ctype.declvar(n) + ';' for n, v in env.locals.items()]\n\n if env.ret_type is None:\n env.ret_type = _cuda_types.void\n\n head = f'{attributes} {env.ret_type} {func.name}({params})'\n code = CodeBlock(head, local_vars + body)\n return str(code), env\n\n\ndef _eval_operand(op, args, env):\n if is_constants(*args):\n pyfunc = _cuda_typerules.get_pyfunc(type(op))\n return Constant(pyfunc(*[x.obj for x in args]))\n\n ufunc = _cuda_typerules.get_ufunc(env.mode, type(op))\n return _call_ufunc(ufunc, args, None, env)\n\n\ndef _call_ufunc(ufunc, args, dtype, env):\n if len(args) != ufunc.nin:\n raise ValueError('invalid number of arguments')\n\n in_types = []\n for x in args:\n if is_constants(x):\n t = _cuda_typerules.get_ctype_from_scalar(env.mode, x.obj).dtype\n else:\n t = x.ctype.dtype\n in_types.append(t)\n\n op = _cuda_typerules.guess_routine(ufunc, in_types, dtype, env.mode)\n\n if op is None:\n raise TypeError(\n f'\"{ufunc.name}\" does not support for the input types: {in_types}')\n\n if op.error_func is not None:\n op.error_func()\n\n if ufunc.nout == 1 and op.routine.startswith('out0 = '):\n out_type = _cuda_types.Scalar(op.out_types[0])\n expr = op.routine.replace('out0 = ', '')\n\n in_params = []\n for x, t in zip(args, op.in_types):\n x = _astype_scalar(x, _cuda_types.Scalar(t), 'same_kind', env)\n x = Data.init(x, env)\n in_params.append(x)\n\n can_use_inline_expansion = True\n for i in range(ufunc.nin):\n if len(list(re.finditer(r'in{}'.format(i), op.routine))) > 1:\n can_use_inline_expansion = False\n\n if can_use_inline_expansion:\n # Code pass for readable generated code\n for i, x in enumerate(in_params):\n expr = expr.replace(f'in{i}', x.code)\n expr = '(' + expr.replace('out0_type', str(out_type)) + ')'\n env.preambles.add(ufunc._preamble)\n else:\n template_typenames = ', '.join([\n f'typename T{i}' for i in range(ufunc.nin)])\n ufunc_name = f'{ufunc.name}_{str(numpy.dtype(op.out_types[0]))}'\n params = ', '.join([f'T{i} in{i}' for i in range(ufunc.nin)])\n ufunc_code = f\"\"\"template <{template_typenames}>\n__device__ {out_type} {ufunc_name}({params}) {{\n return {expr};\n}}\n\"\"\"\n env.preambles.add(ufunc_code)\n in_params = ', '.join([a.code for a in in_params])\n expr = f'{ufunc_name}({in_params})'\n return Data(expr, out_type)\n\n raise NotImplementedError(f'ufunc `{ufunc.name}` is not supported.')\n\n\ndef _transpile_stmts(stmts, is_toplevel, env):\n codeblocks = []\n for stmt in stmts:\n codeblocks.extend(_transpile_stmt(stmt, is_toplevel, env))\n return codeblocks\n\n\n@transpile_function_wrapper\ndef _transpile_stmt(stmt, is_toplevel, env):\n \"\"\"Transpile the statement.\n\n Returns (list of [CodeBlock or str]): The generated CUDA code.\n \"\"\"\n\n if isinstance(stmt, ast.ClassDef):\n raise NotImplementedError('class is not supported currently.')\n if isinstance(stmt, (ast.FunctionDef, ast.AsyncFunctionDef)):\n raise NotImplementedError(\n 'Nested functions are not supported currently.')\n if isinstance(stmt, ast.Return):\n value = _transpile_expr(stmt.value, env)\n value = Data.init(value, env)\n t = value.ctype\n if env.ret_type is None:\n env.ret_type = t\n elif env.ret_type != t:\n raise ValueError(\n f'Failed to infer the return type: {env.ret_type} or {t}')\n return [f'return {value.code};']\n if isinstance(stmt, ast.Delete):\n raise NotImplementedError('`del` is not supported currently.')\n\n if isinstance(stmt, ast.Assign):\n if len(stmt.targets) != 1:\n raise NotImplementedError('Not implemented.')\n\n value = _transpile_expr(stmt.value, env)\n target = stmt.targets[0]\n\n if is_constants(value) and isinstance(target, ast.Name):\n name = target.id\n if not isinstance(value.obj, _typeclasses):\n if is_toplevel:\n if env[name] is not None and not is_constants(env[name]):\n raise TypeError(f'Type mismatch of variable: `{name}`')\n env.consts[name] = value\n return []\n else:\n raise TypeError(\n 'Cannot assign constant value not at top-level.')\n\n value = Data.init(value, env)\n return _transpile_assign_stmt(target, env, value)\n\n if isinstance(stmt, ast.AugAssign):\n value = _transpile_expr(stmt.value, env)\n target = _transpile_expr(stmt.target, env)\n assert isinstance(target, Data)\n value = Data.init(value, env)\n result = _eval_operand(stmt.op, (target, value), env)\n if not numpy.can_cast(\n result.ctype.dtype, target.ctype.dtype, 'same_kind'):\n raise TypeError('dtype mismatch')\n return [f'{target.code} = {result.code};']\n\n if isinstance(stmt, ast.For):\n if len(stmt.orelse) > 0:\n raise NotImplementedError('while-else is not supported.')\n name = stmt.target.id\n iters = _transpile_expr(stmt.iter, env)\n\n if env[name] is None:\n env[name] = Data(stmt.target.id, iters.ctype)\n elif env[name].ctype.dtype != iters.ctype.dtype:\n raise TypeError(\n f'Data type mismatch of variable: `{name}`: '\n f'{env[name].ctype.dtype} != {iters.ctype.dtype}')\n\n body = _transpile_stmts(stmt.body, False, env)\n\n if not isinstance(iters, _internal_types.Range):\n raise NotImplementedError(\n 'for-loop is supported only for range iterator.')\n\n init_code = (f'{iters.ctype} '\n f'__it = {iters.start.code}, '\n f'__stop = {iters.stop.code}, '\n f'__step = {iters.step.code}')\n cond = '__step >= 0 ? __it < __stop : __it > __stop'\n if iters.step_is_positive is True:\n cond = '__it < __stop'\n elif iters.step_is_positive is False:\n cond = '__it > __stop'\n\n head = f'for ({init_code}; {cond}; __it += __step)'\n return [CodeBlock(head, [f'{name} = __it;'] + body)]\n\n if isinstance(stmt, ast.AsyncFor):\n raise ValueError('`async for` is not allowed.')\n if isinstance(stmt, ast.While):\n if len(stmt.orelse) > 0:\n raise NotImplementedError('while-else is not supported.')\n condition = _transpile_expr(stmt.test, env)\n condition = _astype_scalar(condition, _cuda_types.bool_, 'unsafe', env)\n condition = Data.init(condition, env)\n body = _transpile_stmts(stmt.body, False, env)\n head = f'while ({condition.code})'\n return [CodeBlock(head, body)]\n if isinstance(stmt, ast.If):\n condition = _transpile_expr(stmt.test, env)\n if is_constants(condition):\n stmts = stmt.body if condition.obj else stmt.orelse\n return _transpile_stmts(stmts, is_toplevel, env)\n head = f'if ({condition.code})'\n then_body = _transpile_stmts(stmt.body, False, env)\n else_body = _transpile_stmts(stmt.orelse, False, env)\n return [CodeBlock(head, then_body), CodeBlock('else', else_body)]\n if isinstance(stmt, (ast.With, ast.AsyncWith)):\n raise ValueError('Switching contexts are not allowed.')\n if isinstance(stmt, (ast.Raise, ast.Try)):\n raise ValueError('throw/catch are not allowed.')\n if isinstance(stmt, ast.Assert):\n value = _transpile_expr(stmt.test, env)\n if is_constants(value):\n assert value.obj\n return [';']\n else:\n return ['assert(' + value + ');']\n if isinstance(stmt, (ast.Import, ast.ImportFrom)):\n raise ValueError('Cannot import modules from the target functions.')\n if isinstance(stmt, (ast.Global, ast.Nonlocal)):\n raise ValueError('Cannot use global/nonlocal in the target functions.')\n if isinstance(stmt, ast.Expr):\n value = _transpile_expr(stmt.value, env)\n return [';'] if is_constants(value) else [value.code + ';']\n if isinstance(stmt, ast.Pass):\n return [';']\n if isinstance(stmt, ast.Break):\n raise NotImplementedError('Not implemented.')\n if isinstance(stmt, ast.Continue):\n raise NotImplementedError('Not implemented.')\n assert False\n\n\n@transpile_function_wrapper\ndef _transpile_expr(expr, env):\n \"\"\"Transpile the statement.\n\n Returns (Data): The CUDA code and its type of the expression.\n \"\"\"\n res = _transpile_expr_internal(expr, env)\n\n if isinstance(res, Constant) and isinstance(res.obj, _internal_types.Expr):\n return res.obj\n else:\n return res\n\n\ndef _transpile_expr_internal(expr, env):\n if isinstance(expr, ast.BoolOp):\n values = [_transpile_expr(e, env) for e in expr.values]\n value = values[0]\n for rhs in values[1:]:\n value = _eval_operand(expr.op, (value, rhs), env)\n return value\n if isinstance(expr, ast.BinOp):\n left = _transpile_expr(expr.left, env)\n right = _transpile_expr(expr.right, env)\n return _eval_operand(expr.op, (left, right), env)\n if isinstance(expr, ast.UnaryOp):\n value = _transpile_expr(expr.operand, env)\n return _eval_operand(expr.op, (value,), env)\n if isinstance(expr, ast.Lambda):\n raise NotImplementedError('Not implemented.')\n if isinstance(expr, ast.Compare):\n values = [expr.left] + expr.comparators\n if len(values) != 2:\n raise NotImplementedError(\n 'Comparison of 3 or more values is not implemented.')\n values = [_transpile_expr(e, env) for e in values]\n return _eval_operand(expr.ops[0], values, env)\n if isinstance(expr, ast.IfExp):\n cond = _transpile_expr(expr.test, env)\n x = _transpile_expr(expr.body, env)\n y = _transpile_expr(expr.orelse, env)\n\n if isinstance(expr, Constant):\n return x if expr.obj else y\n if cond.ctype.dtype.kind == 'c':\n raise NotImplementedError('')\n x = Data.init(x, env)\n y = Data.init(y, env)\n if x.ctype.dtype != y.ctype.dtype:\n raise TypeError(\n 'Type mismatch in conditional expression.: '\n f'{x.ctype.dtype} != {y.ctype.dtype}')\n cond = _astype_scalar(cond, _cuda_types.bool_, 'unsafe', env)\n return Data(f'({cond.code} ? {x.code} : {y.code})', x.ctype)\n\n if isinstance(expr, ast.Call):\n func = _transpile_expr(expr.func, env)\n args = [_transpile_expr(x, env) for x in expr.args]\n kwargs = dict([(kw.arg, _transpile_expr(kw.value, env))\n for kw in expr.keywords])\n\n builtin_funcs = _builtin_funcs.builtin_functions_dict\n if is_constants(func) and (func.obj in builtin_funcs):\n func = builtin_funcs[func.obj]\n\n if isinstance(func, _internal_types.BuiltinFunc):\n return func.call(env, *args, **kwargs)\n\n if not is_constants(func):\n raise NotImplementedError(\n 'device function call is not implemented.')\n\n func = func.obj\n\n if is_constants(*args, *kwargs.values()):\n # compile-time function call\n args = [x.obj for x in args]\n kwargs = dict([(k, v.obj) for k, v in kwargs.items()])\n return Constant(func(*args, **kwargs))\n\n if isinstance(func, _kernel.ufunc):\n # ufunc call\n dtype = kwargs.pop('dtype', Constant(None)).obj\n if len(kwargs) > 0:\n name = next(iter(kwargs))\n raise TypeError(\n f\"'{name}' is an invalid keyword to ufunc {func.name}\")\n return _call_ufunc(func, args, dtype, env)\n\n if inspect.isclass(func) and issubclass(func, _typeclasses):\n # explicit typecast\n if len(args) != 1:\n raise TypeError(\n f'function takes {func} invalid number of argument')\n ctype = _cuda_types.Scalar(func)\n return _astype_scalar(args[0], ctype, 'unsafe', env)\n\n raise NotImplementedError(\n f'function call of `{func.__name__}` is not implemented')\n\n if isinstance(expr, ast.Constant):\n return Constant(expr.value)\n if isinstance(expr, ast.Num):\n # Deprecated since py3.8\n return Constant(expr.n)\n if isinstance(expr, ast.Str):\n # Deprecated since py3.8\n return Constant(expr.s)\n if isinstance(expr, ast.NameConstant):\n # Deprecated since py3.8\n return Constant(expr.value)\n if isinstance(expr, ast.Subscript):\n array = _transpile_expr(expr.value, env)\n index = _transpile_expr(expr.slice, env)\n return _indexing(array, index, env)\n if isinstance(expr, ast.Name):\n value = env[expr.id]\n if value is None:\n raise NameError(f'Unbound name: {expr.id}')\n return env[expr.id]\n if isinstance(expr, ast.Attribute):\n value = _transpile_expr(expr.value, env)\n if is_constants(value):\n return Constant(getattr(value.obj, expr.attr))\n if isinstance(value.ctype, _cuda_types.ArrayBase):\n if 'ndim' == expr.attr:\n return Constant(value.ctype.ndim)\n if isinstance(value.ctype, _cuda_types.CArray):\n if 'size' == expr.attr:\n return Data(f'static_cast<long long>({value.code}.size())',\n _cuda_types.Scalar('q'))\n raise NotImplementedError('Not implemented: __getattr__')\n\n if isinstance(expr, ast.Tuple):\n elts = [_transpile_expr(x, env) for x in expr.elts]\n # TODO: Support compile time constants.\n elts = [Data.init(x, env) for x in elts]\n elts_code = ', '.join([x.code for x in elts])\n ctype = _cuda_types.Tuple([x.ctype for x in elts])\n return Data(f'thrust::make_tuple({elts_code})', ctype)\n\n if isinstance(expr, ast.Index):\n return _transpile_expr(expr.value, env)\n\n raise ValueError('Not supported: type {}'.format(type(expr)))\n\n\ndef _emit_assign_stmt(lvalue, rvalue, env):\n if is_constants(lvalue):\n raise TypeError('lvalue of assignment must not be constant value')\n\n if (isinstance(lvalue.ctype, _cuda_types.Scalar)\n and isinstance(rvalue.ctype, _cuda_types.Scalar)):\n rvalue = _astype_scalar(rvalue, lvalue.ctype, 'same_kind', env)\n elif lvalue.ctype != rvalue.ctype:\n raise TypeError(\n f'Data type mismatch of variable: `{lvalue.code}`: '\n f'{lvalue.ctype} != {rvalue.ctype}')\n\n return [f'{lvalue.code} = {rvalue.code};']\n\n\ndef _transpile_assign_stmt(target, env, value, depth=0):\n if isinstance(target, ast.Name):\n name = target.id\n if env[name] is None:\n env[name] = Data(name, value.ctype)\n return _emit_assign_stmt(env[name], value, env)\n\n if isinstance(target, ast.Subscript):\n target = _transpile_expr(target, env)\n return _emit_assign_stmt(target, value, env)\n\n if isinstance(target, ast.Tuple):\n if not isinstance(value.ctype, _cuda_types.Tuple):\n raise ValueError(f'{value.ctype} cannot be unpack')\n size = len(target.elts)\n if len(value.ctype.types) > size:\n raise ValueError(f'too many values to unpack (expected {size})')\n if len(value.ctype.types) < size:\n raise ValueError(f'not enough values to unpack (expected {size})')\n codes = [f'{value.ctype} _temp{depth} = {value.code};']\n for i in range(size):\n code = f'thrust::get<{i}>(_temp{depth})'\n ctype = value.ctype.types[i]\n stmt = _transpile_assign_stmt(\n target.elts[i], env, Data(code, ctype), depth + 1)\n codes.extend(stmt)\n return [CodeBlock('', codes)]\n\n\ndef _indexing(array, index, env):\n if is_constants(array):\n if is_constants(index):\n return Constant(array.obj[index.obj])\n raise TypeError(\n f'{type(array.obj)} is not subscriptable with non-constants.')\n\n array = Data.init(array, env)\n\n if isinstance(array.ctype, _cuda_types.Tuple):\n if is_constants(index):\n i = index.obj\n return Data(f'thrust::get<{i}>({array.code})', array.types[i])\n raise TypeError('Tuple is not subscriptable with non-constants.')\n\n if isinstance(array.ctype, _cuda_types.ArrayBase):\n index = Data.init(index, env)\n ndim = array.ctype.ndim\n if isinstance(index.ctype, _cuda_types.Scalar):\n index_dtype = index.ctype.dtype\n if ndim != 1:\n raise TypeError(\n 'Scalar indexing is supported only for 1-dim array.')\n if index_dtype.kind not in 'ui':\n raise TypeError('Array indices must be integers.')\n return Data(\n f'{array.code}[{index.code}]', array.ctype.child_type)\n if isinstance(index.ctype, _cuda_types.Tuple):\n if ndim != len(index.ctype.types):\n raise IndexError(f'The size of index must be {ndim}')\n for t in index.ctype.types:\n if not isinstance(t, _cuda_types.Scalar):\n raise TypeError('Array indices must be scalar.')\n if t.dtype.kind not in 'iu':\n raise TypeError('Array indices must be integer.')\n if ndim == 0:\n return Data(\n f'{array.code}[0]', array.ctype.child_type)\n if ndim == 1:\n return Data(\n f'{array.code}[thrust::get<0>({index.code})]',\n array.ctype.child_type)\n return Data(\n f'{array.code}._indexing({index.code})',\n array.ctype.child_type)\n if isinstance(index.ctype, _cuda_types.CArray):\n raise TypeError('Advanced indexing is not supported.')\n assert False # Never reach.\n\n raise TypeError(f'{array.code} is not subscriptable.')\n\n\ndef _astype_scalar(x, ctype, casting, env):\n if is_constants(x):\n return Constant(ctype.dtype.type(x.obj))\n\n from_t = x.ctype.dtype\n to_t = ctype.dtype\n if from_t == to_t:\n return x\n # Uses casting rules for scalar values.\n if not numpy.can_cast(from_t.type(0), to_t.type(0), casting):\n raise TypeError(\n f\"Cannot cast from '{from_t}' to {to_t} \"\n f\"with casting rule {casting}.\")\n if from_t.kind == 'c' and to_t.kind != 'c':\n if to_t.kind != 'b':\n warnings.warn(\n 'Casting complex values to real discards the imaginary part',\n numpy.ComplexWarning)\n return Data(f'({ctype})({x.code}.real())', ctype)\n return Data(f'({ctype})({x.code})', ctype)\n"
] | [
[
"numpy.can_cast",
"numpy.dtype"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
dlordtemplar/keras-base-rest | [
"f225d6496ed2e876570eb29d0ba155a0d7b548ac"
] | [
"neuron.py"
] | [
"import random\nimport json\nimport pickle\n\nimport notebook_util\n\nnotebook_util.setup_one_gpu()\n\nimport tensorflow as tf\nfrom flask import (\n Blueprint, request, jsonify\n)\nfrom keras import backend as K\nfrom keras.models import model_from_json\nfrom keras.preprocessing.sequence import pad_sequences\nfrom sklearn.manifold import TSNE\n\nfrom loading_preprocessing_TC import *\n\nbp = Blueprint('neuron', __name__)\nMODEL_DIR = 'out/data/semeval/models'\nDATASET_PATH = 'resources/datasets/semeval/train/'\nDATA_PATH = 'out/data/semeval/'\nMODEL_PATH = 'out/data/semeval/models/'\n\n# model\nmodel = None\ntokenizer = None\nembeddings = None\nvocabulary_encoded = None\nvocabulary_inv = None\nqa_pairs = None\nanswer_texts = None\ngraph = None\n\n# deep learning settings\nMAX_LENGTH = 200\n\n# defaults values for the visualization pages\nDEFAULT_NUM_TEXTS = 5\n\n# Pair\nDEFAULT_PERPLEXITY = 5\n\n\[email protected]_app_first_request\ndef setup():\n global model\n if not model:\n model = load_environment()\n\n\n# global model, tokenizer, embeddings, vocabulary_encoded, vocabulary_inv, qa_pairs, answer_texts, graph\n\n\ndef load_environment():\n \"\"\"Load documents index for search engine, pre-trained embeddings, vocabulary, parameters and the model.\"\"\"\n global model, tokenizer, embeddings, vocabulary_encoded, vocabulary_inv, qa_pairs, answer_texts, graph\n with open(DATA_PATH + 'tokenizer.p', 'rb') as handle:\n tokenizer = pickle.load(handle)\n with open(DATA_PATH + 'embedding_matrix.p', 'rb') as handle:\n embeddings = pickle.load(handle)\n vocabulary_encoded = tokenizer.word_index\n vocabulary_inv = {v: k for k, v in vocabulary_encoded.items()}\n model = load_model('model_visualization_siamesedeeplstm')\n qa_pairs, answer_texts = load_data()\n\n return model\n\n\ndef load_model(new_model_filename):\n \"\"\"Load a pretrained model from PyTorch / Keras checkpoint.\n Args:\n new_model_filename (string): the name of the model used when saving its weights and architecture to\n either a binary (PyTorch) or a .h5 and a .json (Keras)\n\n Returns:\n error (string): The error message displayed to a user. If empty, counts as no error.\n \"\"\"\n global model, model_filename\n print(\"Loading model:\", new_model_filename)\n try:\n json_file = open(MODEL_PATH + new_model_filename + '.json',\n 'r')\n loaded_model_json = json_file.read()\n json_file.close()\n model = model_from_json(loaded_model_json)\n global graph\n graph = tf.get_default_graph()\n # load weights into new model\n model.load_weights(MODEL_PATH + new_model_filename + \".h5\")\n model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])\n model_filename = new_model_filename\n return model\n except Exception as e:\n print(e)\n error = \"<div class=\\\"alert alert-warning\\\"> Sorry, there is something wrong with the model: <br> \" + str(\n e) + \"</div>\"\n return error\n\n\ndef load_data():\n \"\"\"Load SemEval 2017 files from .xml and convert them into pandas dataframes.\n Args:\n\n Returns:\n train (pandas dataframe): QA-pairs in a format question - correct answers (ids) - pool (ids; incorrect answers).\n If there are multiple correct answers to a single question, they are split into multiple QA - pairs.\n answer_texts_train (pandas dataframe): answer texts and their ids.\n \"\"\"\n files = [DATASET_PATH + 'SemEval2016-Task3-CQA-QL-train-part1-subtaskA.xml',\n DATASET_PATH + 'SemEval2016-Task3-CQA-QL-train-part2-subtaskA.xml']\n train_xml = read_xml(files)\n train, answer_texts_train = xml2dataframe_Labels(train_xml, 'train')\n answer_texts_train.set_index('answer_id', drop=False, inplace=True)\n return train, answer_texts_train\n\n\ndef prepare_data(texts):\n \"\"\"Tokenize texts and pad resulting sequences of words using Keras functions.\"\"\"\n global tokenizer, embeddings\n tokens = tokenizer.texts_to_sequences(texts)\n padded_tokens = pad_sequences(tokens, maxlen=MAX_LENGTH, value=embeddings.shape[0] - 1)\n return tokens, padded_tokens\n\n\ndef visualize_model_deep(model, question_lstm=True):\n \"\"\"Retrieve weights of the second shared LSTM to visualize neuron activations.\"\"\"\n recurrent_layer = model.get_layer('SharedLSTM2')\n output_layer = model.layers[-1]\n\n inputs = []\n inputs.extend(model.inputs)\n\n outputs = []\n outputs.extend(model.outputs)\n if question_lstm:\n outputs.append(recurrent_layer.get_output_at(1))\n else:\n outputs.append(recurrent_layer.get_output_at(0))\n\n global graph\n with graph.as_default():\n all_function = K.function(inputs, outputs)\n output_function = K.function([output_layer.input], model.outputs)\n return all_function, output_function\n\n\ndef highlight_neuron(rnn_values, texts, tokens, scale, neuron):\n \"\"\"Generate HTML code where each word is highlighted according to a given neuron activity on it.\"\"\"\n tag_string = \"<span data-toggle=\\\"tooltip\\\" title=\\\"SCORE\\\"><span style = \\\"background-color: rgba(COLOR, OPACITY);\\\">WORD</span></span>\"\n old_texts = texts\n texts = []\n for idx in range(0, len(old_texts)):\n current_neuron_values = rnn_values[idx, :, neuron]\n current_neuron_values = current_neuron_values[-len(tokens[idx]):]\n words = [vocabulary_inv[x] for x in tokens[idx]]\n current_strings = []\n if scale:\n scaled = [\n ((x - min(current_neuron_values)) * (2) / (\n max(current_neuron_values) - min(current_neuron_values))) + (\n -1)\n for x in current_neuron_values]\n else:\n scaled = current_neuron_values\n for score, word, scaled_score in zip(current_neuron_values, words, scaled):\n if score > 0:\n color = '195, 85, 58'\n else:\n color = '63, 127, 147'\n current_string = tag_string.replace('SCORE', str(score)).replace('WORD', word).replace('OPACITY', str(\n abs(scaled_score))).replace('COLOR', color)\n current_strings.append(current_string)\n texts.append(' '.join(current_strings))\n return texts\n\n\[email protected]('/neuron', strict_slashes=False, methods=['GET', 'POST'])\ndef display_neuron():\n global answer_texts, qa_pairs, vocabulary_inv, model\n\n print(request.data)\n data = json.loads(request.data)\n indices = data['indices']\n neuron = data['neuron']\n\n # Start actual visualization\n all_highlighted_wrong_answers = []\n all_wrong_answers = []\n\n min_ca = 1\n min_wa = 1\n max_ca = -1\n max_wa = -1\n\n activated_words = []\n activated_words_values = []\n antiactivated_words = []\n antiactivated_words_values = []\n\n activation_per_word_data = {}\n asked_questions = {}\n\n # plotly\n pl_ca_heatmaps_indexed = {}\n pl_wa_heatmaps_indexed = {}\n indexed_correct_answers = {}\n indexed_highlighted_correct_answers = {}\n indexed_wrong_answers = {}\n indexed_highlighted_wrong_answers = {}\n\n for i in indices:\n print('Generating activations for QA pair', i)\n row = qa_pairs.iloc[i]\n correct_answers = answer_texts.loc[row['answer_ids']]['answer'].values\n wrong_answers = answer_texts.loc[row['pool']]['answer'].values\n question = row['question']\n asked_questions[i] = question\n q_tokens, q_padded_tokens = prepare_data([question])\n ca_tokens, ca_padded_tokens = prepare_data(correct_answers)\n wa_tokens, wa_padded_tokens = prepare_data(wrong_answers)\n all_function_deep, output_function_deep = visualize_model_deep(model, False)\n if len(correct_answers) > 0:\n scores_ca, rnn_values_ca = all_function_deep([q_padded_tokens * len(correct_answers), ca_padded_tokens])\n neuron_num = rnn_values_ca.shape[-1]\n all_values_ca = rnn_values_ca[:, :, neuron:neuron + 1]\n if np.min(all_values_ca) < min_ca:\n min_ca = np.min(all_values_ca)\n if np.max(all_values_ca) > max_ca:\n max_ca = np.max(all_values_ca)\n highlighted_correct_answers = highlight_neuron(rnn_values_ca, correct_answers, ca_tokens,\n False, # Scale placeholder\n neuron)\n\n if i not in indexed_highlighted_correct_answers:\n indexed_highlighted_correct_answers[i] = [highlighted_correct_answers]\n else:\n indexed_highlighted_correct_answers[i].append(highlighted_correct_answers)\n\n current_ca = [[vocabulary_inv[x] for x in ca_tokens[idx]] for idx in range(len(ca_tokens))]\n if i not in indexed_correct_answers:\n indexed_correct_answers[i] = current_ca\n else:\n indexed_correct_answers[i].append(current_ca)\n\n activation_per_word_data['ca_firings' + str(i)] = rnn_values_ca[:, :, neuron].flatten()\n activation_per_word_data['ca_text' + str(i)] = [\n vocabulary_inv[token] if token in vocabulary_inv.keys() else '<pad>' for x in ca_padded_tokens for\n token\n in x]\n else:\n if i not in indexed_highlighted_correct_answers:\n indexed_highlighted_correct_answers[i] = []\n else:\n indexed_highlighted_correct_answers[i].append([])\n\n if i not in indexed_correct_answers:\n indexed_correct_answers[i] = []\n else:\n indexed_correct_answers[i].append([])\n\n activation_per_word_data['ca_text' + str(i)] = []\n activation_per_word_data['ca_firings' + str(i)] = []\n\n if len(wrong_answers) > 0:\n scores_wa, rnn_values_wa = all_function_deep([q_padded_tokens * len(wrong_answers), wa_padded_tokens])\n neuron_num = rnn_values_wa.shape[-1]\n all_values_wa = rnn_values_wa[:, :, neuron:neuron + 1]\n if np.min(all_values_wa) < min_wa:\n min_wa = np.min(all_values_wa)\n if np.max(all_values_wa) > max_wa:\n max_wa = np.max(all_values_wa)\n highlighted_wrong_answers = highlight_neuron(rnn_values_wa, wrong_answers, wa_tokens, False,\n # Scale placeholder\n neuron)\n all_highlighted_wrong_answers.append(highlighted_wrong_answers)\n\n if i not in indexed_highlighted_wrong_answers:\n indexed_highlighted_wrong_answers[i] = [highlighted_wrong_answers]\n else:\n indexed_highlighted_wrong_answers[i].append(highlighted_wrong_answers)\n\n current_wa = [[vocabulary_inv[x] for x in wa_tokens[idx]] for idx in range(len(wa_tokens))]\n if i not in indexed_wrong_answers:\n indexed_wrong_answers[i] = current_wa\n else:\n indexed_wrong_answers[i].append(current_wa)\n\n activation_per_word_data['wa_firings' + str(i)] = rnn_values_wa[:, :, neuron].flatten()\n activation_per_word_data['wa_text' + str(i)] = [\n vocabulary_inv[token] if token in vocabulary_inv.keys() else '<pad>' for x in wa_padded_tokens for\n token\n in x]\n else:\n all_highlighted_wrong_answers.append([])\n\n if i not in indexed_highlighted_wrong_answers:\n indexed_highlighted_wrong_answers[i] = []\n else:\n indexed_highlighted_wrong_answers[i].append([])\n\n all_wrong_answers.append([])\n\n if i not in indexed_wrong_answers:\n indexed_wrong_answers[i] = []\n else:\n indexed_wrong_answers[i].append([])\n\n activation_per_word_data['wa_text' + str(i)] = []\n activation_per_word_data['wa_firings' + str(i)] = []\n\n # Point generation for correct answers\n if len(correct_answers) > 0:\n for idx in range(0, len(ca_tokens)):\n words = [vocabulary_inv[x] for x in ca_tokens[idx]]\n heatmap_points = {'z': rnn_values_ca[idx, -len(ca_tokens[idx]):, neuron:neuron + 1].tolist(),\n 'y': words,\n 'type': 'heatmap'}\n if i in pl_ca_heatmaps_indexed:\n pl_ca_heatmaps_indexed[i].append(heatmap_points)\n else:\n pl_ca_heatmaps_indexed[i] = [heatmap_points]\n\n # Same as above, but for wrong answers\n if len(wrong_answers) > 0:\n for idx in range(0, len(wa_tokens)):\n words = [vocabulary_inv[x] for x in wa_tokens[idx]]\n heatmap_points = {'z': rnn_values_wa[idx, -len(wa_tokens[idx]):, neuron:neuron + 1].tolist(),\n 'y': words,\n 'type': 'heatmap'}\n if i in pl_wa_heatmaps_indexed:\n pl_wa_heatmaps_indexed[i].append(heatmap_points)\n else:\n pl_wa_heatmaps_indexed[i] = [heatmap_points]\n\n all_firings = [x for i in indices for x in activation_per_word_data['wa_firings' + str(i)]] + [x for\n i in indices\n for x\n in\n activation_per_word_data[\n 'ca_firings' + str(\n i)]]\n all_tokens = [x for i in indices for x in activation_per_word_data['wa_text' + str(i)]] + [x for i in\n indices\n for x in\n activation_per_word_data[\n 'ca_text' + str(\n i)]]\n all_firings = np.array(all_firings)\n all_tokens = np.array(all_tokens)\n p_high = np.percentile([x for i, x in enumerate(all_firings) if all_tokens[i] != '<pad>'], 90)\n p_low = np.percentile([x for i, x in enumerate(all_firings) if all_tokens[i] != '<pad>'], 10)\n\n for ind, x in enumerate(all_firings):\n if x >= p_high:\n activated_words.append(all_tokens[ind])\n activated_words_values.append(x)\n elif x <= p_low:\n antiactivated_words.append(all_tokens[ind])\n antiactivated_words_values.append(x)\n\n seen = set()\n activated_words = [x for x in activated_words if not (x in seen or seen.add(x))]\n seen = set()\n antiactivated_words = [x for x in antiactivated_words if not (x in seen or seen.add(x))]\n\n return jsonify({'max_qa_pairs': len(qa_pairs),\n 'activated_words': activated_words,\n 'antiactivated_words': antiactivated_words,\n 'asked_questions': json.dumps(asked_questions),\n # plotly\n 'pl_ca_heatmap_points': pl_ca_heatmaps_indexed,\n 'pl_wa_heatmap_points': pl_wa_heatmaps_indexed,\n 'indexed_correct_answers': indexed_correct_answers,\n 'indexed_highlighted_correct_answers': indexed_highlighted_correct_answers,\n 'indexed_wrong_answers': indexed_wrong_answers,\n 'indexed_highlighted_wrong_answers': indexed_highlighted_wrong_answers\n })\n\n\ndef tsne_plot(model, labels, correct_answers, wrong_answers, question, perplexity=40):\n \"\"\"Creates a TSNE model and plots it\"\"\"\n\n tokens = []\n for word in model.keys():\n tokens.append(model[word])\n\n tsne_model = TSNE(perplexity=perplexity, n_components=2, init='pca', n_iter=2500, random_state=23,\n metric=\"cosine\")\n # list of x y values in format (x, y)\n new_values = tsne_model.fit_transform(tokens)\n\n trace_question_x = []\n trace_ca_x = []\n trace_wa_x = []\n trace_question_y = []\n trace_ca_y = []\n trace_wa_y = []\n trace_question_text = []\n trace_ca_text = []\n trace_wa_text = []\n trace_question_hovertext = []\n trace_ca_hovertext = []\n trace_wa_hovertext = []\n\n ca_index = 0\n wa_index = 0\n for label_index in range(len(labels)):\n if labels[label_index] == 'q':\n trace_question_x.append(new_values[label_index][0])\n trace_question_y.append(new_values[label_index][1])\n trace_question_text.append('Q')\n trace_question_hovertext.append(question if len(question) < 61 else question[:60] + '...')\n elif labels[label_index] == 'ca':\n trace_ca_x.append(new_values[label_index][0])\n trace_ca_y.append(new_values[label_index][1])\n trace_ca_text.append('CA' + str(len(trace_ca_x)))\n trace_ca_hovertext.append(\n correct_answers[ca_index] if len(correct_answers[ca_index]) < 61 else correct_answers[ca_index][\n :60] + '...')\n ca_index += 1\n elif labels[label_index] == 'wa':\n trace_wa_x.append(new_values[label_index][0])\n trace_wa_y.append(new_values[label_index][1])\n trace_wa_text.append('WA' + str(len(trace_wa_x)))\n trace_wa_hovertext.append(\n wrong_answers[wa_index] if len(wrong_answers[wa_index]) < 61 else wrong_answers[wa_index][:60] + '...')\n wa_index += 1\n\n marker_blue = {\n 'size': 20,\n 'color': 'rgb(0, 0, 255)',\n # star\n 'symbol': 17\n }\n marker_green = {\n 'size': 20,\n 'color': 'rgb(0, 204, 0)',\n # circle\n 'symbol': 0\n }\n marker_red = {\n 'size': 20,\n 'color': 'rgb(255, 0, 0)',\n # x\n 'symbol': 4\n }\n trace_question = {\n 'name': 'Question',\n 'x': trace_question_x,\n 'y': trace_question_y,\n 'type': 'scatter',\n 'mode': 'markers+text',\n 'hoverinfo': 'text',\n 'hovertext': trace_question_hovertext,\n 'text': trace_question_text,\n 'textposition': 'top right',\n 'marker': marker_blue\n }\n trace_ca = {\n 'name': 'Correct answer',\n 'x': trace_ca_x,\n 'y': trace_ca_y,\n 'type': 'scatter',\n 'mode': 'markers+text',\n 'hoverinfo': 'text',\n 'hovertext': trace_ca_hovertext,\n 'text': trace_ca_text,\n 'textposition': 'top right',\n 'marker': marker_green\n }\n trace_wa = {\n 'name': 'Wrong answer',\n 'x': trace_wa_x,\n 'y': trace_wa_y,\n 'type': 'scatter',\n 'mode': 'markers+text',\n 'hoverinfo': 'text',\n 'hovertext': trace_wa_hovertext,\n 'text': trace_wa_text,\n 'textposition': 'top right',\n 'marker': marker_red\n }\n plotly_tsne = [trace_question, trace_ca, trace_wa]\n\n plotly_tsne_as_json = pd.Series(plotly_tsne).to_json(orient='values')\n\n return plotly_tsne_as_json\n\n\[email protected]('/pair', strict_slashes=False, methods=['GET', 'POST'])\ndef pair():\n global answer_texts, qa_pairs, vocabulary_inv, model\n\n data = json.loads(request.data)\n print(data)\n\n pair_num = data['pair_num']\n perplexity = data['perplexity']\n scale = data['scale']\n neuron_display_ca = data['ca_neuron']\n if neuron_display_ca > -1:\n neuron_display_ca = int(neuron_display_ca)\n neuron_display_wa = data['wa_neuron']\n if neuron_display_wa > -1:\n neuron_display_wa = int(neuron_display_wa)\n\n if pair_num >= len(qa_pairs):\n return 'Index out of bounds.'\n\n row = qa_pairs.iloc[pair_num]\n correct_answers = answer_texts.loc[row['answer_ids']]['answer'].values\n wrong_answers = answer_texts.loc[row['pool']]['answer'].values\n question = row['question']\n q_tokens, q_padded_tokens = prepare_data([question])\n ca_tokens, ca_padded_tokens = prepare_data(correct_answers)\n wa_tokens, wa_padded_tokens = prepare_data(wrong_answers)\n all_function_deep, output_function_deep = visualize_model_deep(model, False)\n if len(correct_answers) > 0:\n scores_ca, rnn_values_ca = all_function_deep([q_padded_tokens * len(correct_answers), ca_padded_tokens])\n neuron_num = rnn_values_ca.shape[-1]\n else:\n scores_ca = []\n rnn_values_ca = []\n if len(wrong_answers) > 0:\n scores_wa, rnn_values_wa = all_function_deep([q_padded_tokens * len(wrong_answers), wa_padded_tokens])\n neuron_num = rnn_values_wa.shape[-1]\n else:\n scores_wa = []\n rnn_values_wa = []\n\n # generate TSNE\n labels = ['q'] + ['ca'] * len(correct_answers) + ['wa'] * len(wrong_answers)\n model_dict_wa = {}\n model_dict_ca = {}\n if len(correct_answers) > 0:\n model_dict_ca = {i + 1: np.max(rnn_values_ca[i, :, :], axis=1) for i in range(len(correct_answers))}\n if len(wrong_answers) > 0:\n model_dict_wa = {i + 1: np.max(rnn_values_wa[i - len(correct_answers), :, :], axis=1) for i in\n range(len(correct_answers), len(wrong_answers) + len(correct_answers))}\n model_dict = {**model_dict_ca, **model_dict_wa}\n all_function_deep_q, output_function_deep_q = visualize_model_deep(model, True)\n _, rnn_values = all_function_deep_q([q_padded_tokens, [ca_padded_tokens[0]]])\n question_vector = rnn_values[0]\n model_dict[0] = np.max(question_vector, axis=1)\n plotly_tsne = tsne_plot(model_dict, labels, correct_answers, wrong_answers, question, perplexity)\n\n # plotly\n pl_ca_heatmaps = []\n pl_wa_heatmaps = []\n # generate heatmaps\n # plotly\n if len(correct_answers) > 0:\n for idx in range(0, len(ca_tokens)):\n words = [vocabulary_inv[x] for x in ca_tokens[idx]]\n heatmap_points = {'z': rnn_values_ca[idx, -len(ca_tokens[idx]):, :].tolist(),\n 'y': words,\n 'type': 'heatmap'}\n pl_ca_heatmaps.append(heatmap_points)\n # Same as above, but for wrong answers\n if len(wrong_answers) > 0:\n for idx in range(0, len(wa_tokens)):\n words = [vocabulary_inv[x] for x in wa_tokens[idx]]\n heatmap_points = {'z': rnn_values_wa[idx, -len(wa_tokens[idx]):, :].tolist(),\n 'y': words,\n 'type': 'heatmap'}\n pl_wa_heatmaps.append(heatmap_points)\n\n # generate text highlighting based on neuron activity\n highlighted_correct_answers = correct_answers.tolist()\n highlighted_wrong_answers = wrong_answers.tolist()\n\n if neuron_display_ca > -1:\n highlighted_correct_answers = highlight_neuron(rnn_values_ca, correct_answers, ca_tokens, scale,\n neuron_display_ca)\n if neuron_display_wa > -1:\n highlighted_wrong_answers = highlight_neuron(rnn_values_wa, wrong_answers, wa_tokens, scale, neuron_display_wa)\n\n # Convert ndarrays to lists\n if len(scores_ca) > 0:\n scores_ca = scores_ca.tolist()\n if len(scores_wa) > 0:\n scores_wa = scores_wa.tolist()\n\n return jsonify({'question': question,\n 'highlighted_wrong_answers': highlighted_wrong_answers,\n 'highlighted_correct_answers': highlighted_correct_answers,\n 'wrong_answers': wrong_answers.tolist(),\n 'correct_answers': correct_answers.tolist(),\n 'pair_num': pair_num,\n 'neuron_num': neuron_num,\n 'neuron_display_ca': neuron_display_ca,\n 'neuron_display_wa': neuron_display_wa,\n 'scale': scale,\n 'texts_len': len(qa_pairs),\n 'scores_ca': scores_ca,\n 'scores_wa': scores_wa,\n # plotly\n 'plotly_tsne': plotly_tsne,\n 'pl_ca_heatmaps': pl_ca_heatmaps,\n 'pl_wa_heatmaps': pl_wa_heatmaps\n })\n\n\[email protected]('/live/load', strict_slashes=False, methods=['GET', 'POST'])\ndef live_load():\n global qa_pairs\n\n data = json.loads(request.data)\n\n pair_num = data['pair_num']\n\n row = qa_pairs.iloc[pair_num]\n correct_answers = answer_texts.loc[row['answer_ids']]['answer'].values\n wrong_answers = answer_texts.loc[row['pool']]['answer'].values\n question = row['question']\n\n return jsonify({'question': question,\n 'wrong_answers': wrong_answers.tolist(),\n 'correct_answers': correct_answers.tolist(),\n 'pair_num': pair_num,\n })\n\n\[email protected]('/live/random', strict_slashes=False, methods=['GET', 'POST'])\ndef live_random():\n global qa_pairs\n\n data = json.loads(request.data)\n\n pair_num = random.randint(0, len(qa_pairs) - 1)\n\n row = qa_pairs.iloc[pair_num]\n correct_answers = answer_texts.loc[row['answer_ids']]['answer'].values\n wrong_answers = answer_texts.loc[row['pool']]['answer'].values\n question = row['question']\n\n return jsonify({'question': question,\n 'wrong_answers': wrong_answers.tolist(),\n 'correct_answers': correct_answers.tolist(),\n 'pair_num': pair_num,\n })\n\n\[email protected]('/live', strict_slashes=False, methods=['GET', 'POST'])\ndef live():\n global answer_texts, qa_pairs, vocabulary_inv, model\n\n data = json.loads(request.data)\n\n perplexity = data['perplexity']\n scale = data['scale']\n neuron_display = data['neuron']\n if neuron_display > -1:\n neuron_display = int(neuron_display)\n\n correct_answers = []\n for ca in data['correct_answers'].split('\\n'):\n if ca.strip() != '':\n correct_answers.append(ca)\n wrong_answers = []\n for wa in data['wrong_answers'].split('\\n'):\n if wa.strip() != '':\n wrong_answers.append(wa)\n question = data['question']\n q_tokens, q_padded_tokens = prepare_data([question])\n ca_tokens, ca_padded_tokens = prepare_data(correct_answers)\n wa_tokens, wa_padded_tokens = prepare_data(wrong_answers)\n all_function_deep, output_function_deep = visualize_model_deep(model, False)\n if len(correct_answers) > 0:\n scores_ca, rnn_values_ca = all_function_deep([q_padded_tokens * len(correct_answers), ca_padded_tokens])\n neuron_num = rnn_values_ca.shape[-1]\n else:\n scores_ca = []\n rnn_values_ca = []\n if len(wrong_answers) > 0:\n scores_wa, rnn_values_wa = all_function_deep([q_padded_tokens * len(wrong_answers), wa_padded_tokens])\n neuron_num = rnn_values_wa.shape[-1]\n else:\n scores_wa = []\n rnn_values_wa = []\n\n # generate TSNE\n labels = ['q'] + ['ca'] * len(correct_answers) + ['wa'] * len(wrong_answers)\n model_dict_wa = {}\n model_dict_ca = {}\n if len(correct_answers) > 0:\n model_dict_ca = {i + 1: np.max(rnn_values_ca[i, :, :], axis=1) for i in range(len(correct_answers))}\n if len(wrong_answers) > 0:\n model_dict_wa = {i + 1: np.max(rnn_values_wa[i - len(correct_answers), :, :], axis=1) for i in\n range(len(correct_answers), len(wrong_answers) + len(correct_answers))}\n model_dict = {**model_dict_ca, **model_dict_wa}\n all_function_deep_q, output_function_deep_q = visualize_model_deep(model, True)\n _, rnn_values = all_function_deep_q([q_padded_tokens, [ca_padded_tokens[0]]])\n question_vector = rnn_values[0]\n model_dict[0] = np.max(question_vector, axis=1)\n plotly_tsne = tsne_plot(model_dict, labels, correct_answers, wrong_answers, question, perplexity)\n\n # plotly\n pl_ca_heatmaps = []\n pl_wa_heatmaps = []\n # generate heatmaps\n # plotly\n if len(correct_answers) > 0:\n for idx in range(0, len(ca_tokens)):\n words = [vocabulary_inv[x] for x in ca_tokens[idx]]\n heatmap_points = {'z': rnn_values_ca[idx, -len(ca_tokens[idx]):, :].tolist(),\n 'y': words,\n 'type': 'heatmap'}\n pl_ca_heatmaps.append(heatmap_points)\n # Same as above, but for wrong answers\n if len(wrong_answers) > 0:\n for idx in range(0, len(wa_tokens)):\n words = [vocabulary_inv[x] for x in wa_tokens[idx]]\n heatmap_points = {'z': rnn_values_wa[idx, -len(wa_tokens[idx]):, :].tolist(),\n 'y': words,\n 'type': 'heatmap'}\n pl_wa_heatmaps.append(heatmap_points)\n\n # generate text highlighting based on neuron activity\n highlighted_correct_answers = correct_answers\n highlighted_wrong_answers = wrong_answers\n\n if neuron_display > -1:\n highlighted_correct_answers = highlight_neuron(rnn_values_ca, correct_answers, ca_tokens, scale,\n neuron_display)\n highlighted_wrong_answers = highlight_neuron(rnn_values_wa, wrong_answers, wa_tokens, scale, neuron_display)\n\n # Convert ndarrays to lists\n if len(scores_ca) > 0:\n scores_ca = scores_ca.tolist()\n if len(scores_wa) > 0:\n scores_wa = scores_wa.tolist()\n\n return jsonify({'question': question,\n 'highlighted_wrong_answers': highlighted_wrong_answers,\n 'highlighted_correct_answers': highlighted_correct_answers,\n 'wrong_answers': wrong_answers,\n 'correct_answers': correct_answers,\n 'perplexity': perplexity,\n 'neuron_display': neuron_display,\n 'scale': scale,\n 'texts_len': len(qa_pairs),\n 'scores_ca': scores_ca,\n 'scores_wa': scores_wa,\n # plotly\n 'plotly_tsne': plotly_tsne,\n 'pl_ca_heatmaps': pl_ca_heatmaps,\n 'pl_wa_heatmaps': pl_wa_heatmaps\n })\n\n\[email protected]('/questions', strict_slashes=False, methods=['GET', 'POST'])\ndef questions():\n with open('out/data/plotly_all_questions_json_string_p20.json', 'r') as file:\n plotly_all_questions = json.load(file)\n\n return plotly_all_questions\n\n\[email protected]('/pos/ptb', strict_slashes=False, methods=['GET', 'POST'])\ndef pos_ptb():\n with open('out/data/semeval/pos_per_neuron_ptb.json', 'r') as file:\n plotly_pos = json.load(file)\n return plotly_pos\n\n\[email protected]('/pos/upos', strict_slashes=False, methods=['GET', 'POST'])\ndef pos_upos():\n with open('out/data/semeval/pos_per_neuron_upos.json', 'r') as file:\n plotly_pos = json.load(file)\n return plotly_pos\n\n\[email protected]('/pos/xpos', strict_slashes=False, methods=['GET', 'POST'])\ndef pos_xpos():\n with open('out/data/semeval/pos_per_neuron_xpos.json', 'r') as file:\n plotly_pos = json.load(file)\n return plotly_pos\n\n\[email protected]('/tsne_neurons/<perplexity>', strict_slashes=False, methods=['GET', 'POST'])\ndef tsne_neurons(perplexity):\n with open('out/data/semeval/tsne_neurons_points_p' + str(perplexity) + '.json', 'r') as file:\n plotly_tsne_neurons = json.load(file)\n return plotly_tsne_neurons\n"
] | [
[
"sklearn.manifold.TSNE",
"tensorflow.get_default_graph"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.10",
"1.12",
"1.4",
"1.13",
"1.5",
"1.7",
"0.12",
"1.0",
"1.2"
]
}
] |
g147/streamlit | [
"d54fab097caa3e6dc101eb930cddc0832e05dea9"
] | [
"lib/tests/streamlit/delta_generator_test.py"
] | [
"# Copyright 2018-2021 Streamlit Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"DeltaGenerator Unittest.\"\"\"\n\nimport functools\nfrom unittest.mock import patch, MagicMock\nimport json\n\ntry:\n from inspect import signature\nexcept ImportError:\n from funcsigs import signature\n\nfrom parameterized import parameterized\n\nimport pandas as pd\n\nimport streamlit as st\nfrom streamlit.delta_generator import DeltaGenerator\nfrom streamlit.cursor import LockedCursor, make_delta_path\nfrom streamlit.errors import DuplicateWidgetID\nfrom streamlit.errors import StreamlitAPIException\nfrom streamlit.proto.Delta_pb2 import Delta\nfrom streamlit.proto.Element_pb2 import Element\nfrom streamlit.proto.TextArea_pb2 import TextArea\nfrom streamlit.proto.TextInput_pb2 import TextInput\nfrom streamlit.proto.Empty_pb2 import Empty as EmptyProto\nfrom streamlit.proto.RootContainer_pb2 import RootContainer\nfrom streamlit.proto.Text_pb2 import Text as TextProto\nfrom streamlit.state.widgets import _build_duplicate_widget_message\nimport streamlit.state.widgets as w\nfrom tests import testutil\n\n\ndef identity(x):\n return x\n\n\nregister_widget = functools.partial(\n w.register_widget, deserializer=lambda x, s: x, serializer=identity\n)\n\n\nclass FakeDeltaGenerator(object):\n \"\"\"Fake DeltaGenerator class.\n\n The methods in this class are specifically here as to not use the\n one in the actual delta generator. This purely exists just to test the\n DeltaGenerator Decorators without relying on the actual\n DeltaGenerator methods.\n \"\"\"\n\n def __init__(self):\n \"\"\"Constructor.\"\"\"\n pass\n\n def __getattr__(self, name):\n streamlit_methods = [\n method_name for method_name in dir(st) if callable(getattr(st, method_name))\n ]\n\n def wrapper(*args, **kwargs):\n if name in streamlit_methods:\n if self._container == \"sidebar\":\n message = (\n \"Method `%(name)s()` does not exist for \"\n \"`st.sidebar`. Did you mean `st.%(name)s()`?\" % {\"name\": name}\n )\n else:\n message = (\n \"Method `%(name)s()` does not exist for \"\n \"`DeltaGenerator` objects. Did you mean \"\n \"`st.%(name)s()`?\" % {\"name\": name}\n )\n else:\n message = \"`%(name)s()` is not a valid Streamlit command.\" % {\n \"name\": name\n }\n\n raise AttributeError(message)\n\n return wrapper\n\n def fake_text(self, element, body):\n \"\"\"Fake text delta generator.\"\"\"\n element.text.body = str(body)\n\n def fake_dataframe(self, arg0, data=None):\n \"\"\"Fake dataframe.\"\"\"\n return (arg0, data)\n\n def fake_text_raise_exception(self, element, body):\n \"\"\"Fake text that raises exception.\"\"\"\n raise Exception(\"Exception in fake_text_raise_exception\")\n\n def exception(self, e):\n \"\"\"Create fake exception handler.\n\n The real DeltaGenerator exception is more complicated. We use\n this so _with_element can find the exception method. The real\n exception method wil be tested later on.\n \"\"\"\n self._exception_msg = str(e)\n\n def _enqueue(self, delta_type, element_proto):\n delta = Delta()\n el_proto = getattr(delta.new_element, delta_type)\n el_proto.CopyFrom(element_proto)\n return delta\n\n\nclass MockQueue(object):\n def __init__(self):\n self._deltas = []\n\n def __call__(self, data):\n self._deltas.append(data)\n\n\nclass DeltaGeneratorTest(testutil.DeltaGeneratorTestCase):\n \"\"\"Test streamlit.delta_generator methods.\"\"\"\n\n def test_nonexistent_method(self):\n with self.assertRaises(Exception) as ctx:\n st.sidebar.non_existing()\n\n self.assertEqual(\n str(ctx.exception), \"`non_existing()` is not a valid Streamlit command.\"\n )\n\n def test_sidebar_nonexistent_method(self):\n with self.assertRaises(Exception) as ctx:\n st.sidebar.echo()\n\n self.assertEqual(\n str(ctx.exception),\n \"Method `echo()` does not exist for `st.sidebar`. \"\n \"Did you mean `st.echo()`?\",\n )\n\n def set_widget_requires_args(self):\n st.text_input()\n c = self.get_delta_from_queue().new_element.exception\n self.assertEqual(c.type, \"TypeError\")\n\n def test_duplicate_widget_id_error(self):\n \"\"\"Multiple widgets with the same key should report an error.\"\"\"\n widgets = {\n \"button\": lambda key=None: st.button(\"\", key=key),\n \"checkbox\": lambda key=None: st.checkbox(\"\", key=key),\n \"multiselect\": lambda key=None: st.multiselect(\"\", options=[1, 2], key=key),\n \"radio\": lambda key=None: st.radio(\"\", options=[1, 2], key=key),\n \"selectbox\": lambda key=None: st.selectbox(\"\", options=[1, 2], key=key),\n \"slider\": lambda key=None: st.slider(\"\", key=key),\n \"text_area\": lambda key=None: st.text_area(\"\", key=key),\n \"text_input\": lambda key=None: st.text_input(\"\", key=key),\n \"time_input\": lambda key=None: st.time_input(\"\", key=key),\n \"date_input\": lambda key=None: st.date_input(\"\", key=key),\n \"number_input\": lambda key=None: st.number_input(\"\", key=key),\n }\n\n # Create a widget with a user-defined key to test that attempting to\n # create a duplicate raises an exception below.\n st.button(\"\", key=\"key\")\n\n # Iterate each widget type\n for widget_type, create_widget in widgets.items():\n create_widget()\n with self.assertRaises(DuplicateWidgetID) as ctx:\n # Test creating a widget with a duplicate auto-generated key\n # raises an exception.\n create_widget()\n self.assertEqual(\n _build_duplicate_widget_message(\n widget_func_name=widget_type, user_key=None\n ),\n str(ctx.exception),\n )\n\n with self.assertRaises(DuplicateWidgetID) as ctx:\n # Test creating a widget with a duplicate user-defined key\n # raises an exception.\n create_widget(\"key\")\n self.assertEqual(\n _build_duplicate_widget_message(\n widget_func_name=widget_type, user_key=\"key\"\n ),\n str(ctx.exception),\n )\n\n\nclass DeltaGeneratorClassTest(testutil.DeltaGeneratorTestCase):\n \"\"\"Test DeltaGenerator Class.\"\"\"\n\n def test_constructor(self):\n \"\"\"Test default DeltaGenerator().\"\"\"\n dg = DeltaGenerator()\n self.assertFalse(dg._cursor.is_locked)\n self.assertEqual(dg._cursor.index, 0)\n\n def test_constructor_with_id(self):\n \"\"\"Test DeltaGenerator() with an id.\"\"\"\n cursor = LockedCursor(root_container=RootContainer.MAIN, index=1234)\n dg = DeltaGenerator(root_container=RootContainer.MAIN, cursor=cursor)\n self.assertTrue(dg._cursor.is_locked)\n self.assertEqual(dg._cursor.index, 1234)\n\n def test_enqueue_null(self):\n # Test \"Null\" Delta generators\n dg = DeltaGenerator(root_container=None)\n new_dg = dg._enqueue(\"empty\", EmptyProto())\n self.assertEqual(dg, new_dg)\n\n @parameterized.expand([(RootContainer.MAIN,), (RootContainer.SIDEBAR,)])\n def test_enqueue(self, container):\n dg = DeltaGenerator(root_container=container)\n self.assertEqual(0, dg._cursor.index)\n self.assertEqual(container, dg._root_container)\n\n test_data = \"some test data\"\n text_proto = TextProto()\n text_proto.body = test_data\n new_dg = dg._enqueue(\"text\", text_proto)\n\n self.assertNotEqual(dg, new_dg)\n self.assertEqual(1, dg._cursor.index)\n self.assertEqual(container, new_dg._root_container)\n\n element = self.get_delta_from_queue().new_element\n self.assertEqual(element.text.body, test_data)\n\n def test_enqueue_same_id(self):\n cursor = LockedCursor(root_container=RootContainer.MAIN, index=123)\n dg = DeltaGenerator(root_container=RootContainer.MAIN, cursor=cursor)\n self.assertEqual(123, dg._cursor.index)\n\n test_data = \"some test data\"\n text_proto = TextProto()\n text_proto.body = test_data\n new_dg = dg._enqueue(\"text\", text_proto)\n\n self.assertEqual(dg._cursor, new_dg._cursor)\n\n msg = self.get_message_from_queue()\n # The last element in delta_path is the delta's index in its container.\n self.assertEqual(\n make_delta_path(RootContainer.MAIN, (), 123), msg.metadata.delta_path\n )\n self.assertEqual(msg.delta.new_element.text.body, test_data)\n\n\nclass DeltaGeneratorContainerTest(testutil.DeltaGeneratorTestCase):\n \"\"\"Test DeltaGenerator Container.\"\"\"\n\n def test_container(self):\n container = st.beta_container()\n\n self.assertIsInstance(container, DeltaGenerator)\n self.assertFalse(container._cursor.is_locked)\n\n def test_container_paths(self):\n level3 = st.beta_container().beta_container().beta_container()\n level3.markdown(\"hi\")\n level3.markdown(\"bye\")\n\n msg = self.get_message_from_queue()\n self.assertEqual(\n make_delta_path(RootContainer.MAIN, (0, 0, 0), 1), msg.metadata.delta_path\n )\n\n\nclass DeltaGeneratorColumnsTest(testutil.DeltaGeneratorTestCase):\n \"\"\"Test DeltaGenerator Columns.\"\"\"\n\n def test_equal_columns(self):\n for column in st.beta_columns(4):\n self.assertIsInstance(column, DeltaGenerator)\n self.assertFalse(column._cursor.is_locked)\n\n def test_variable_columns(self):\n weights = [3, 1, 4, 1, 5, 9]\n st.beta_columns(weights)\n\n for i, w in enumerate(weights):\n # Pull the delta from the back of the queue, using negative index\n delta = self.get_delta_from_queue(i - len(weights))\n self.assertEqual(delta.add_block.column.weight, w)\n\n def test_bad_columns_negative_int(self):\n with self.assertRaises(StreamlitAPIException):\n st.beta_columns(-1337)\n\n def test_bad_columns_single_float(self):\n with self.assertRaises(TypeError):\n st.beta_columns(6.28)\n\n def test_bad_columns_list_negative_value(self):\n with self.assertRaises(StreamlitAPIException):\n st.beta_columns([5, 6, -1.2])\n\n def test_bad_columns_list_int_zero_value(self):\n with self.assertRaises(StreamlitAPIException):\n st.beta_columns([5, 0, 1])\n\n def test_bad_columns_list_float_zero_value(self):\n with self.assertRaises(StreamlitAPIException):\n st.beta_columns([5.0, 0.0, 1.0])\n\n def test_nested_columns(self):\n level1, _ = st.beta_columns(2)\n with self.assertRaises(StreamlitAPIException):\n level2, _ = level1.beta_columns(2)\n\n\nclass DeltaGeneratorExpanderTest(testutil.DeltaGeneratorTestCase):\n def test_nested_expanders(self):\n level1 = st.beta_expander(\"level 1\")\n with self.assertRaises(StreamlitAPIException):\n level2 = level1.beta_expander(\"level 2\")\n\n\nclass DeltaGeneratorWithTest(testutil.DeltaGeneratorTestCase):\n \"\"\"Test the `with DG` feature\"\"\"\n\n def test_with(self):\n # Same as test_container_paths, but using `with` syntax\n level3 = st.beta_container().beta_container().beta_container()\n with level3:\n st.markdown(\"hi\")\n st.markdown(\"bye\")\n\n msg = self.get_message_from_queue()\n self.assertEqual(\n make_delta_path(RootContainer.MAIN, (0, 0, 0), 1), msg.metadata.delta_path\n )\n\n # Now we're out of the `with` block, commands should use the main dg\n st.markdown(\"outside\")\n\n msg = self.get_message_from_queue()\n self.assertEqual(\n make_delta_path(RootContainer.MAIN, (), 1), msg.metadata.delta_path\n )\n\n def test_nested_with(self):\n with st.beta_container():\n with st.beta_container():\n st.markdown(\"Level 2 with\")\n msg = self.get_message_from_queue()\n self.assertEqual(\n make_delta_path(RootContainer.MAIN, (0, 0), 0),\n msg.metadata.delta_path,\n )\n\n st.markdown(\"Level 1 with\")\n msg = self.get_message_from_queue()\n self.assertEqual(\n make_delta_path(RootContainer.MAIN, (0,), 1),\n msg.metadata.delta_path,\n )\n\n\nclass DeltaGeneratorWriteTest(testutil.DeltaGeneratorTestCase):\n \"\"\"Test DeltaGenerator Text, Alert, Json, and Markdown Classes.\"\"\"\n\n def test_json_object(self):\n \"\"\"Test Text.JSON object.\"\"\"\n json_data = {\"key\": \"value\"}\n\n # Testing python object\n st.json(json_data)\n\n json_string = json.dumps(json_data)\n\n element = self.get_delta_from_queue().new_element\n self.assertEqual(json_string, element.json.body)\n\n def test_json_string(self):\n \"\"\"Test Text.JSON string.\"\"\"\n json_string = '{\"key\": \"value\"}'\n\n # Testing JSON string\n st.json(json_string)\n\n element = self.get_delta_from_queue().new_element\n self.assertEqual(json_string, element.json.body)\n\n def test_json_unserializable(self):\n \"\"\"Test Text.JSON with unserializable object.\"\"\"\n obj = json # Modules aren't serializable.\n\n # Testing unserializable object.\n st.json(obj)\n\n element = self.get_delta_from_queue().new_element\n self.assertEqual(\"\\\"<class 'module'>\\\"\", element.json.body)\n\n def test_markdown(self):\n \"\"\"Test Markdown element.\"\"\"\n test_string = \" data \"\n\n st.markdown(test_string)\n\n element = self.get_delta_from_queue().new_element\n self.assertEqual(\"data\", element.markdown.body)\n\n test_string = \" <a#data>data</a> \"\n st.markdown(test_string)\n element = self.get_delta_from_queue().new_element\n\n assert element.markdown.body.startswith(\"<a#data>\")\n\n def test_code(self):\n \"\"\"Test st.code()\"\"\"\n code = \"print('Hello, %s!' % 'Streamlit')\"\n expected_body = \"```python\\n%s\\n```\" % code\n\n st.code(code, language=\"python\")\n element = self.get_delta_from_queue().new_element\n\n # st.code() creates a MARKDOWN text object that wraps\n # the body inside a codeblock declaration\n self.assertEqual(element.markdown.body, expected_body)\n\n def test_empty(self):\n \"\"\"Test Empty.\"\"\"\n st.empty()\n\n element = self.get_delta_from_queue().new_element\n self.assertEqual(element.empty, EmptyProto())\n\n\nclass DeltaGeneratorProgressTest(testutil.DeltaGeneratorTestCase):\n \"\"\"Test DeltaGenerator Progress.\"\"\"\n\n def test_progress_int(self):\n \"\"\"Test Progress with int values.\"\"\"\n values = [0, 42, 100]\n for value in values:\n st.progress(value)\n\n element = self.get_delta_from_queue().new_element\n self.assertEqual(value, element.progress.value)\n\n def test_progress_float(self):\n \"\"\"Test Progress with float values.\"\"\"\n values = [0.0, 0.42, 1.0]\n for value in values:\n st.progress(value)\n\n element = self.get_delta_from_queue().new_element\n self.assertEqual(int(value * 100), element.progress.value)\n\n def test_progress_bad_values(self):\n \"\"\"Test Progress with bad values.\"\"\"\n values = [-1, 101, -0.01, 1.01]\n for value in values:\n with self.assertRaises(StreamlitAPIException):\n st.progress(value)\n\n with self.assertRaises(StreamlitAPIException):\n st.progress(\"some string\")\n\n\nclass DeltaGeneratorChartTest(testutil.DeltaGeneratorTestCase):\n \"\"\"Test DeltaGenerator Charts.\"\"\"\n\n def test_line_chart(self):\n \"\"\"Test dg.line_chart.\"\"\"\n data = pd.DataFrame([[20, 30, 50]], columns=[\"a\", \"b\", \"c\"])\n\n st.line_chart(data)\n\n element = self.get_delta_from_queue().new_element.vega_lite_chart\n chart_spec = json.loads(element.spec)\n self.assertEqual(chart_spec[\"mark\"], \"line\")\n self.assertEqual(element.datasets[0].data.data.cols[2].int64s.data[0], 20)\n\n def test_line_chart_with_generic_index(self):\n \"\"\"Test dg.line_chart with a generic index.\"\"\"\n data = pd.DataFrame([[20, 30, 50]], columns=[\"a\", \"b\", \"c\"])\n data.set_index(\"a\", inplace=True)\n\n st.line_chart(data)\n\n element = self.get_delta_from_queue().new_element.vega_lite_chart\n chart_spec = json.loads(element.spec)\n self.assertEqual(chart_spec[\"mark\"], \"line\")\n self.assertEqual(element.datasets[0].data.data.cols[2].int64s.data[0], 30)\n\n def test_line_chart_add_rows_with_generic_index(self):\n \"\"\"Test empty dg.line_chart with add_rows funciton and a generic index.\"\"\"\n data = pd.DataFrame([[20, 30, 50]], columns=[\"a\", \"b\", \"c\"])\n data.set_index(\"a\", inplace=True)\n\n chart = st.line_chart()\n chart.add_rows(data)\n\n element = self.get_delta_from_queue().new_element.vega_lite_chart\n chart_spec = json.loads(element.spec)\n self.assertEqual(chart_spec[\"mark\"], \"line\")\n self.assertEqual(element.datasets[0].data.data.cols[2].int64s.data[0], 30)\n\n def test_area_chart(self):\n \"\"\"Test dg.area_chart.\"\"\"\n data = pd.DataFrame([[20, 30, 50]], columns=[\"a\", \"b\", \"c\"])\n\n st.area_chart(data)\n\n element = self.get_delta_from_queue().new_element.vega_lite_chart\n chart_spec = json.loads(element.spec)\n self.assertEqual(chart_spec[\"mark\"], \"area\")\n self.assertEqual(element.datasets[0].data.data.cols[2].int64s.data[0], 20)\n\n def test_bar_chart(self):\n \"\"\"Test dg.bar_chart.\"\"\"\n data = pd.DataFrame([[20, 30, 50]], columns=[\"a\", \"b\", \"c\"])\n\n st.bar_chart(data)\n\n element = self.get_delta_from_queue().new_element.vega_lite_chart\n chart_spec = json.loads(element.spec)\n\n self.assertEqual(chart_spec[\"mark\"], \"bar\")\n self.assertEqual(element.datasets[0].data.data.cols[2].int64s.data[0], 20)\n\n\nclass AutogeneratedWidgetIdTests(testutil.DeltaGeneratorTestCase):\n def test_ids_are_equal_when_proto_is_equal(self):\n text_input1 = TextInput()\n text_input1.label = \"Label #1\"\n text_input1.default = \"Value #1\"\n\n text_input2 = TextInput()\n text_input2.label = \"Label #1\"\n text_input2.default = \"Value #1\"\n\n element1 = Element()\n element1.text_input.CopyFrom(text_input1)\n\n element2 = Element()\n element2.text_input.CopyFrom(text_input2)\n\n register_widget(\"text_input\", element1.text_input)\n\n with self.assertRaises(DuplicateWidgetID):\n register_widget(\"text_input\", element2.text_input)\n\n def test_ids_are_diff_when_labels_are_diff(self):\n text_input1 = TextInput()\n text_input1.label = \"Label #1\"\n text_input1.default = \"Value #1\"\n\n text_input2 = TextInput()\n text_input2.label = \"Label #2\"\n text_input2.default = \"Value #1\"\n\n element1 = Element()\n element1.text_input.CopyFrom(text_input1)\n\n element2 = Element()\n element2.text_input.CopyFrom(text_input2)\n\n register_widget(\"text_input\", element1.text_input)\n register_widget(\"text_input\", element2.text_input)\n\n self.assertNotEqual(element1.text_input.id, element2.text_input.id)\n\n def test_ids_are_diff_when_types_are_diff(self):\n text_input1 = TextInput()\n text_input1.label = \"Label #1\"\n text_input1.default = \"Value #1\"\n\n text_area2 = TextArea()\n text_area2.label = \"Label #1\"\n text_area2.default = \"Value #1\"\n\n element1 = Element()\n element1.text_input.CopyFrom(text_input1)\n\n element2 = Element()\n element2.text_area.CopyFrom(text_area2)\n\n register_widget(\"text_input\", element1.text_input)\n register_widget(\"text_input\", element2.text_input)\n\n self.assertNotEqual(element1.text_input.id, element2.text_area.id)\n\n\nclass KeyWidgetIdTests(testutil.DeltaGeneratorTestCase):\n def test_ids_are_equal_when_keys_are_equal(self):\n text_input1 = TextInput()\n text_input1.label = \"Label #1\"\n text_input1.default = \"Value #1\"\n\n text_input2 = TextInput()\n text_input2.label = \"Label #2\"\n text_input2.default = \"Value #2\"\n\n element1 = Element()\n element1.text_input.CopyFrom(text_input1)\n\n element2 = Element()\n element2.text_input.CopyFrom(text_input2)\n\n register_widget(\"text_input\", element1.text_input, user_key=\"some_key\")\n\n with self.assertRaises(DuplicateWidgetID):\n register_widget(\"text_input\", element2.text_input, user_key=\"some_key\")\n\n def test_ids_are_diff_when_keys_are_diff(self):\n text_input1 = TextInput()\n text_input1.label = \"Label #1\"\n text_input1.default = \"Value #1\"\n\n text_input2 = TextInput()\n text_input2.label = \"Label #1\"\n text_input2.default = \"Value #1\"\n\n element1 = Element()\n element1.text_input.CopyFrom(text_input1)\n\n element2 = Element()\n element2.text_input.CopyFrom(text_input2)\n\n register_widget(\"text_input\", element1.text_input, user_key=\"some_key1\")\n register_widget(\"text_input\", element2.text_input, user_key=\"some_key2\")\n\n self.assertNotEqual(element1.text_input.id, element2.text_input.id)\n\n\nclass DeltaGeneratorImageTest(testutil.DeltaGeneratorTestCase):\n \"\"\"Test DeltaGenerator Images\"\"\"\n\n def test_image_from_url(self):\n \"\"\"Tests dg.image with single and multiple image URLs\"\"\"\n\n url = \"https://streamlit.io/an_image.png\"\n caption = \"ahoy!\"\n\n # single URL\n st.image(url, caption=caption, width=200)\n element = self.get_delta_from_queue().new_element\n self.assertEqual(element.imgs.width, 200)\n self.assertEqual(len(element.imgs.imgs), 1)\n self.assertEqual(element.imgs.imgs[0].url, url)\n self.assertEqual(element.imgs.imgs[0].caption, caption)\n\n # multiple URLs\n st.image([url] * 5, caption=[caption] * 5, width=200)\n element = self.get_delta_from_queue().new_element\n self.assertEqual(len(element.imgs.imgs), 5)\n self.assertEqual(element.imgs.imgs[4].url, url)\n self.assertEqual(element.imgs.imgs[4].caption, caption)\n\n def test_unequal_images_and_captions_error(self):\n \"\"\"Tests that the number of images and captions must match, or\n an exception is generated\"\"\"\n\n url = \"https://streamlit.io/an_image.png\"\n caption = \"ahoy!\"\n\n with self.assertRaises(Exception) as ctx:\n st.image([url] * 5, caption=[caption] * 2)\n self.assertTrue(\"Cannot pair 2 captions with 5 images.\" in str(ctx.exception))\n"
] | [
[
"pandas.DataFrame"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [
"0.23",
"0.21",
"2.0",
"1.4",
"0.19",
"1.1",
"1.5",
"1.2",
"0.24",
"0.20",
"1.0",
"0.25",
"1.3"
],
"scipy": [],
"tensorflow": []
}
] |
SHZ66/westpa | [
"c91711bf8f1f75359c0d4d28765a6d587dfd6adc"
] | [
"src/westpa/westext/weed/UncertMath.py"
] | [
"import numpy as np\nimport numpy.ma as ma\nimport itertools\n\n\nTOL = 1.0e-6\n\n\nclass UncertContainer:\n \"\"\" Container to hold uncertainty measurements. Data is convert to np masked arrays\n to avoid possible numerical problems\n \"\"\"\n\n def __init__(self, vals, vals_dmin, vals_dmax, mask=ma.nomask):\n super().__init__()\n\n # If input data already masked arrays extract unmasked data\n if ma.isMaskedArray(vals):\n vals = vals.data\n if ma.isMaskedArray(vals_dmin):\n vals_dmin = vals_dmin.data\n if ma.isMaskedArray(vals_dmax):\n vals_dmax = vals_dmax.data\n\n # Adjust negative values\n ineg = np.where(vals_dmin <= 0.0)\n vals_dmin[ineg] = TOL * vals[ineg]\n\n # Calculate weight based on fractional uncertainty\n diff = vals_dmax - vals_dmin\n diff_m = ma.masked_where(vals_dmax == vals_dmin, diff)\n\n self.vals = ma.masked_where(vals == 0.0, vals)\n\n self.wt = (self.vals / diff_m) ** 2\n self.uncert = diff_m / self.vals\n\n self.wt.fill_value = np.inf\n self.uncert.fill_vaule = np.inf\n\n assert np.all(self.wt.mask == self.uncert.mask)\n\n # Mask data if uncertainty is not finite or if any of the inputs were\n # already masked\n\n mm = ma.mask_or(self.wt.mask, mask)\n\n self.vals.mask = mm\n self.wt.mask = mm\n self.uncert.mask = mm\n self.dmin = ma.array(vals_dmin, mask=mm, fill_value=np.inf)\n self.dmax = ma.array(vals_dmax, mask=mm, fill_value=np.inf)\n\n self.mask = ma.getmaskarray(self.vals)\n\n def __getitem__(self, indx):\n vals = self.vals[indx]\n dmin = self.dmin[indx]\n dmax = self.dmax[indx]\n\n if isinstance(vals, ma.core.MaskedConstant):\n dum = np.zeros((1,))\n return UncertContainer(dum.copy(), dum.copy(), dum.copy())\n elif isinstance(vals, (float, int, np.float, np.int)):\n return UncertContainer(np.array([vals]), np.array([dmin]), np.array([dmax]))\n elif isinstance(vals, np.ndarray):\n return UncertContainer(vals, dmin, dmax, mask=vals.mask)\n else:\n raise TypeError\n\n def __setitem__(self, indx, value):\n if isinstance(value, UncertContainer):\n self.vals[indx] = value.vals\n self.dmin[indx] = value.dmin\n self.dmax[indx] = value.dmax\n self.wt[indx] = value.wt\n self.uncert[indx] = value.uncert\n else:\n raise TypeError('Can only set values with an UncertContainer object')\n\n def __repr__(self):\n return 'shape={} vals={} dmin={} dmax={} vals.mask={}'.format(\n self.vals.shape, self.vals, self.dmin, self.dmax, self.vals.mask\n )\n\n def __add__(self, value):\n if isinstance(value, UncertContainer):\n vals = self.vals + value.vals\n dmin = self.dmin + value.dmin\n dmax = self.dmax + value.dmax\n\n return UncertContainer(vals, dmin, dmax, mask=vals.mask)\n elif isinstance(value, (float, int, np.float, np.int)):\n vals = self.vals + value\n dmin = self.dmin + value\n dmax = self.dmax + value\n\n return UncertContainer(vals, dmin, dmax, mask=vals.mask)\n else:\n raise TypeError('Attempt to add value of unsupported type')\n\n def __sub__(self, value):\n if isinstance(value, UncertContainer):\n vals = self.vals - value.vals\n dmin = self.dmin - value.dmin\n dmax = self.dmax - value.dmax\n\n return UncertContainer(vals, dmin, dmax, mask=vals.mask)\n else:\n raise TypeError('Attempted to subtract by value of unsupported type')\n\n def __mul__(self, value):\n if isinstance(value, UncertContainer):\n vals = self.vals * value.vals\n dmin = self.dmin * value.dmin\n dmax = self.dmax * value.dmax\n\n return UncertContainer(vals, dmin, dmax, mask=vals.mask)\n\n elif isinstance(value, (float, int, np.float, np.int)):\n vals = self.vals * value\n dmin = self.dmin * value\n dmax = self.dmax * value\n\n return UncertContainer(vals, dmin, dmax, mask=vals.mask)\n else:\n raise TypeError('Attempted to multiply by value of unsupported type')\n\n def __truediv__(self, value):\n if isinstance(value, UncertContainer):\n vals = self.vals / value.vals\n dmin = self.dmin / value.dmax\n dmax = self.dmax / value.dmin\n\n return UncertContainer(vals, dmin, dmax, mask=vals.mask)\n else:\n raise TypeError('Attempted to divide by unsupported type')\n\n def transpose(self):\n vals = self.vals.T\n dmin = self.dmin.T\n dmax = self.dmax.T\n\n return UncertContainer(vals, dmin, dmax, mask=vals.mask)\n\n def recip(self):\n vals = 1.0 / self.vals\n dmin = 1.0 / self.dmax\n dmax = 1.0 / self.dmin\n\n return UncertContainer(vals, dmin, dmax, mask=vals.mask)\n\n def update_mask(self):\n self.vals.mask = self.mask\n self.dmin.mask = self.mask\n self.dmax.mask = self.mask\n self.wt.mask = self.mask\n self.uncert.mask = self.mask\n\n def concatenate(self, value, axis=0):\n \"\"\" Concatentate UncertContainer value to self.\n Assumes that if dimensions of self and value do not match, to\n add a np.newaxis along axis of value\n \"\"\"\n\n if isinstance(value, UncertContainer):\n if value.vals.ndim == self.vals.ndim:\n vals = value.vals\n dmin = value.dmin\n dmax = value.dmax\n wt = value.wt\n uncert = value.uncert\n mask = value.mask\n elif (value.vals.ndim + 1) == self.vals.ndim:\n vals = ma.expand_dims(value.vals, axis)\n dmin = ma.expand_dims(value.dmin, axis)\n dmax = ma.expand_dims(value.dmax, axis)\n wt = ma.expand_dims(value.wt, axis)\n uncert = ma.expand_dims(value.uncert, axis)\n mask = np.expand_dims(value.mask, axis)\n else:\n raise ValueError('Could not propery match dimensionality')\n\n self.vals = ma.concatenate((self.vals, vals), axis=axis)\n self.dmin = ma.concatenate((self.dmin, dmin), axis=axis)\n self.dmax = ma.concatenate((self.dmax, dmax), axis=axis)\n self.wt = ma.concatenate((self.wt, wt), axis=axis)\n self.uncert = ma.concatenate((self.uncert, uncert), axis=axis)\n\n self.mask = np.concatenate((self.mask, mask), axis=axis)\n else:\n raise ValueError('Can only concatenate with an UncertContainer object')\n\n def weighted_average(self, axis=0, expaxis=None):\n \"\"\" Calculate weighted average of data along axis\n after optionally inserting a new dimension into the\n shape array at position expaxis\n \"\"\"\n\n if expaxis is not None:\n vals = ma.expand_dims(self.vals, expaxis)\n dmin = ma.expand_dims(self.dmin, expaxis)\n dmax = ma.expand_dims(self.dmax, expaxis)\n wt = ma.expand_dims(self.wt, expaxis)\n else:\n vals = self.vals\n wt = self.wt\n dmin = self.dmin\n dmax = self.dmax\n\n # Get average value\n avg, norm = ma.average(vals, axis=axis, weights=wt, returned=True)\n avg_ex = ma.expand_dims(avg, 0)\n\n # Calculate weighted uncertainty\n wtmax = ma.max(wt, axis=axis)\n neff = norm / wtmax # Effective number of samples based on uncertainties\n\n # Seeking max deviation from the average; if above avg use max, if below use min\n term = np.empty_like(vals)\n\n indices = np.where(vals > avg_ex)\n i0 = indices[0]\n irest = indices[1:]\n ii = tuple(x for x in itertools.chain([i0], irest))\n jj = tuple(x for x in itertools.chain([np.zeros_like(i0)], irest))\n term[ii] = (dmax[ii] - avg_ex[jj]) ** 2\n\n indices = np.where(vals <= avg_ex)\n i0 = indices[0]\n irest = indices[1:]\n ii = tuple(x for x in itertools.chain([i0], irest))\n jj = tuple(x for x in itertools.chain([np.zeros_like(i0)], irest))\n term[ii] = (avg_ex[jj] - dmin[ii]) ** 2\n\n dsum = ma.sum(term * wt, axis=0) # Sum for weighted average of deviations\n\n dev = 0.5 * np.sqrt(dsum / (norm * neff))\n\n if isinstance(avg, (float, np.float)):\n avg = avg_ex\n\n tmp_min = avg - dev\n ii = np.where(tmp_min < 0)\n tmp_min[ii] = TOL * avg[ii]\n\n return UncertContainer(avg, tmp_min, avg + dev)\n"
] | [
[
"numpy.expand_dims",
"numpy.sqrt",
"numpy.all",
"numpy.concatenate",
"numpy.zeros_like",
"numpy.ma.array",
"numpy.ma.max",
"numpy.ma.masked_where",
"numpy.where",
"numpy.ma.sum",
"numpy.ma.expand_dims",
"numpy.ma.getmaskarray",
"numpy.empty_like",
"numpy.ma.mask_or",
"numpy.zeros",
"numpy.ma.isMaskedArray",
"numpy.ma.concatenate",
"numpy.array",
"numpy.ma.average"
]
] | [
{
"matplotlib": [],
"numpy": [
"1.10",
"1.12",
"1.11",
"1.19",
"1.13",
"1.16",
"1.9",
"1.18",
"1.20",
"1.7",
"1.15",
"1.14",
"1.17",
"1.8"
],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
digitalsimboja/pymc3 | [
"e6749ef7f74359e4ef5f9fb21c3b81cdfab77590"
] | [
"pymc3/step_methods/elliptical_slice.py"
] | [
"# Copyright 2020 The PyMC Developers\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport aesara.tensor as at\nimport numpy as np\nimport numpy.random as nr\n\nfrom pymc3.aesaraf import inputvars\nfrom pymc3.distributions import draw_values\nfrom pymc3.model import modelcontext\nfrom pymc3.step_methods.arraystep import ArrayStep, Competence\n\n__all__ = [\"EllipticalSlice\"]\n\n\ndef get_chol(cov, chol):\n \"\"\"Get Cholesky decomposition of the prior covariance.\n\n Ensure that exactly one of the prior covariance or Cholesky\n decomposition is passed. If the prior covariance was passed, then\n return its Cholesky decomposition.\n\n Parameters\n ----------\n cov: array, optional\n Covariance matrix of the multivariate Gaussian prior.\n chol: array, optional\n Cholesky decomposition of the covariance matrix of the\n multivariate Gaussian prior.\n \"\"\"\n\n if len([i for i in [cov, chol] if i is not None]) != 1:\n raise ValueError(\"Must pass exactly one of cov or chol\")\n\n if cov is not None:\n chol = at.slinalg.cholesky(cov)\n return chol\n\n\nclass EllipticalSlice(ArrayStep):\n \"\"\"Multivariate elliptical slice sampler step.\n\n Elliptical slice sampling (ESS) [1]_ is a variant of slice sampling\n that allows sampling from distributions with multivariate Gaussian\n prior and arbitrary likelihood. It is generally about as fast as\n regular slice sampling, mixes well even when the prior covariance\n might otherwise induce a strong dependence between samples, and\n does not depend on any tuning parameters.\n\n The Gaussian prior is assumed to have zero mean.\n\n Parameters\n ----------\n vars: list\n List of variables for sampler.\n prior_cov: array, optional\n Covariance matrix of the multivariate Gaussian prior.\n prior_chol: array, optional\n Cholesky decomposition of the covariance matrix of the\n multivariate Gaussian prior.\n model: PyMC Model\n Optional model for sampling step. Defaults to None (taken from\n context).\n\n References\n ----------\n .. [1] I. Murray, R. P. Adams, and D. J. C. MacKay. \"Elliptical Slice\n Sampling\", The Proceedings of the 13th International Conference on\n Artificial Intelligence and Statistics (AISTATS), JMLR W&CP\n 9:541-548, 2010.\n \"\"\"\n\n default_blocked = True\n\n def __init__(self, vars=None, prior_cov=None, prior_chol=None, model=None, **kwargs):\n self.model = modelcontext(model)\n chol = get_chol(prior_cov, prior_chol)\n self.prior_chol = at.as_tensor_variable(chol)\n\n if vars is None:\n vars = self.model.cont_vars\n vars = inputvars(vars)\n\n super().__init__(vars, [self.model.fastlogp], **kwargs)\n\n def astep(self, q0, logp):\n \"\"\"q0: current state\n logp: log probability function\n \"\"\"\n\n # Draw from the normal prior by multiplying the Cholesky decomposition\n # of the covariance with draws from a standard normal\n chol = draw_values([self.prior_chol])[0]\n nu = np.dot(chol, nr.randn(chol.shape[0]))\n y = logp(q0) - nr.standard_exponential()\n\n # Draw initial proposal and propose a candidate point\n theta = nr.uniform(0, 2 * np.pi)\n theta_max = theta\n theta_min = theta - 2 * np.pi\n q_new = q0 * np.cos(theta) + nu * np.sin(theta)\n\n while logp(q_new) <= y:\n # Shrink the bracket and propose a new point\n if theta < 0:\n theta_min = theta\n else:\n theta_max = theta\n theta = nr.uniform(theta_min, theta_max)\n q_new = q0 * np.cos(theta) + nu * np.sin(theta)\n\n return q_new\n\n @staticmethod\n def competence(var, has_grad):\n # Because it requires a specific type of prior, this step method\n # should only be assigned explicitly.\n return Competence.INCOMPATIBLE\n"
] | [
[
"numpy.cos",
"numpy.sin",
"numpy.random.standard_exponential",
"numpy.random.randn",
"numpy.random.uniform"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
Kate-Willett/HadISDH_Build | [
"2af5bcda562b97ae2133f7c977a3b312da517320"
] | [
"F12_CreateHomogNCDFStUnc.py"
] | [
"# PYTHON 3\n# \n# Author: Kate Willett\n# Created: 1 February 2013, IDL, Converted to Python 3 December 2020\n# Last update: 20 August 2021\n# Location:/home/h04/hadkw/HadISDH_Code/HADISDH_BUILD/\t\n# GitHub: https://github.com/Kate-Willett/HadISDH_Build\t\t\t\t\t\n# -----------------------\n# CODE PURPOSE AND OUTPUT\n# -----------------------\n# For one variable at a time, IN A SET ORDER!!! [T, RH, DPD, q, e, Td, Tw]\n# Read in list of stations passing through PHA/IDPHA\n# MUST HAVE INPUT ADJUSTMENT UNCERTAINTY FOR EACH VARIABLE - find #***MISSEDADJUNC***\n# Loop through each station\n# read in homogenised station (ASCII VERSION OF ABS)\n# Find cases of subzeros (RH, q and e) or supersaturation (RH, DPD, Td and Tw indirectly q, e) and output to list (continue to process)\n# WORKING WITH HOMOGENISED ACTUALS:\n# create station anomalies and climatologies using desired climatology period\n# WORKING WITH HOMOGENISED ANOMALIES:\n# create station actuals from homogenised anomalies and non-homog climatologies (create these from ascii absolutes, could adjust by climatology of adjustments?)\n# List stations with < 15 years present for each month of climatology as BADS - output to list and do not continue to process.\n# Work out measurement uncertainty\n# Work out adjustment uncertainties an dmissed adjustment uncertainty\n# Output to netCDF (with 2 sigma uncertainties!!!)\n# Make stationstats plot of all uncertainties\n\n# This code now also works through all of the wet bulb extremes: Twmax, Twmax95p, Twmean95p, Tw25, Tw27, Tw29, Tw31, Tw33, Tw35\n# - it works with the already processed good list of Tw (PosthomogIDPHAtw_good... so sats and bads are removed.\n# - temporally matches to homogenised Tw as there are periods within a station that will have been removed because no suitable adjustment could be found.\n# - pulls through measurement uncertainty from Tw netCDFs\n# - pulls through adjustments and adjustment uncertainty from Tw netCDFs\n# - pulls through climatology uncertainty from Tw netCDFs\n# - pulls through total uncertainty from Tw netCDFs\n \n# <references to related published material, e.g. that describes data set>\n# \n# -----------------------\n# LIST OF MODULES\n# -----------------------\n# import numpy as np # used\n# import numpy.ma as npm # used\n# from datetime import datetime # used\n# import matplotlib.pyplot as plt\n# import sys, os, getopt # used\n# import struct\n# import glob # used\n# import pdb # used\n# import netCDF4 as nc4\n# from subprocess import call, check_output, run, PIPE # used\n\n# Kate's Functions\n# import CalcHums\n# from RandomsRanges import LetterRange\n# \n# -----------------------\n# DATA\n# -----------------------\n# Input station lists, adjustment log lists\n# /scratch/hadkw/UPDATE<YYYY>/LISTS_DOCS/'\n# goodforHadISDH.'+versiondots+'_'+typee+var+'.txt'\n# HadISDH.land'+ParamDict[var][0]+'.'+versiondots+'_'+homogtype+'.log'\n# PosthomogIDPHArh_anoms'+CLMlab+'_satsHadISDH.'+versiondots+'.txt' CREATED AFTER RH RUN)\n# PosthomogPHAdpd_anoms'+CLMlab+'_satsHadISDH.'+versiondots+'.txt' CREATED AFTER DPD RUN)\n# Input homogenised ascii data\n# /scratch/hadkw/UPDATE<YYYY>/MONTHLIES/HOMOG/<typee>ASCII/<VAR>DIR/' # this will then be PHAASCII or IDPHAASCII\n# <station>_'_'+typee+'adj.txt'\n# Input SLPclims from 20CR in raw station files\n# /scratch/hadkw/UPDATE<YYYY>/MONTHLIES/NETCDF/'\n# StationListID[st][0:6]+'-'+StationListID[st][6:11]+'_hummonthQC.nc'\n# \n# -----------------------\n# HOW TO RUN THE CODE\n# -----------------------\n# Ensure that you have updated the end year, version, clim period etc or switched HardWire = 0 and F1_HadISDHBuildConfig.txt is up to date\n#\n# The variables should be run in a specific order:\n# T IDPHA first because homogenised t_abs are used to:\n# -> estimate uncertainties in RH, q, e, Td and dpd\n# RH IDPHA second because homogenised rh_abs is used to:\n# -> find supersats in q, e\n# -> estimate uncertainties in q, e, Td, and DPD\n# DPD PHA third because PosthomogPHAdpd_anoms8110_sats are used for:\n# -> find supersats in Tw and Td\n# homog Td is made up from homog T - homog DPD anyway\n# q IDPHA fourth because all dependencies are now complete\n# e IDPHA fifth because all dependencies are now complete\n# td PHADPD sixth because all dependencies are now complete\n# tw IDPHA zeventh because all dependencies are now complete\n#\n# > module load scitools/default-current\n# > python F12_CreateHomogNCDFStUnc --var <var> --typee <type> --runtype <runtype>\n#\n## Which variable?\n# var = 'dpd'\t#'dpd','td','t','tw','e','q','rh'\n#\n## Which homog type?\n# typee = 'PHA'\t#'PHA' (for DPD only),'IDPHA' (for t, e, q, rh and tw),'PHADPD' (for Td) \n#\n## What sort of run?\n# runtype = 'all' # runs all stations within the station list\n# runtype = '00000099999' # restarts from the given station ID then continues through all stations within the station list\n#\n#\n# Or ./F12_submit_spice.sh\n# \n# -----------------------\n# OUTPUT\n# -----------------------\n# Output lists of good, bad, supersaturated and subzero stations\n# /scratch/hadkw/UPDATE<YYYY>/LISTS_DOCS/\n# Posthomog<typee><var>_anoms'+CLMlab+'_<goods,bads,sats,subs>HadISDH.'+versiondots+'.txt' \n# Output homogenised netCDF data\n# /scratch/hadkw/UPDATE<YYYY>/MONTHLIES/HOMOG/<typee>NETCDF/<VAR>DIR/' # this will then be PHANETCDF or IDPHANETCDF\n# <station>'_anoms<climLAB>_homog.nc'\n# Output uncertainty plots\n# /scratch/hadkw/UPDATE<YYYY>/MONTHLIES/HOMOG/STAT_PLOTS/UNCPLOTS/<VAR>DIR/' \n# <station>'_anoms<climLAB>_stationstats.png'\n# Output log info\n# /scratch/hadkw/OutputLogFile'+versiondots+'.txt'\n# \n# -----------------------\n# VERSION/RELEASE NOTES\n# -----------------------\n#\n# Version 6 (20 August 2021)\n# ---------\n# \n# Enhancements\n# Now also outputs all of the Tw extremes: Twmax, Twmax95p, Twmean95p, Tw25, Tw27, Tw29, Tw31, Tw33, Tw35\n# \n# Changes\n# \n# Bug fixes\n# \n#\n# Version 5 (12 January 2021)\n# ---------\n# \n# Enhancements\n# Now only outputs stations that are 'good' or do not have subzeros or supersaturated values. These stations are\n# listed in seperate files with all being in the 'BAD' station list then repeated in the SATS and SUBS files\n# THis doesn't change the final grids but means that we no longer need to faff around pulling out the sats and subs stations\n# \n# Changes\n# This is now python 3 rather than IDL\n# Climatology now calculated where >= 15 years represented for each month, not > 15 - so a few more stations get through.\n# Tw supersats set to when DPD has a supersat (station removed from further processing) so far fewer Tw supersats now found (was Tw > T)\n# Now pulls through monthly standard deviations too\n# Calculates the pseudo e, q, Td with correction to use ice bulb when Twet <= 0 .Twet calculated from T which is set to 5. in case of missing\n# so will result in wet bulb (too high e) in some cases where it should be ice\n# T values only differ due to missed adjustment error\n# RH values only differ due to missed adjustment error\n# DPD values differ due to missed adjustment error AND measurement error which is now lower when pseudoTwet is <= 0 and so the ice bulb calc for e is used\n# q values only differ due to the missed adjustment error\n# e as for q\n# Tw very similar - values only differ due to missed adjustment error. Supersats are now those found from DPD not Tw>T - so far fewer supersats.\n# Td now has own list of sats and bads assessed rather than copied from DPD and T and differs in adj error\n#\n# \n# Bug fixes\n#\n#\n# Version 4 (8 February 2018)\n# ---------\n# \n# Enhancements\n# Now reads in station counts and missed adjustment uncertainty automatically so no updating required.\n# Now runs variable/homogtype from the command line so no updating beyond year required\n### Which variable? T first, RH, DPD, q, e, td, tw\n#param = 'tw'\n## Which homog type?\n#homogtype = 'ID'\t\t#'ID','DPD' for Td, 'PHA' - req for DPD or PHA versions of all variables\n# \n# Changes\n# \n# Bug fixes\n#\n# Version 3 (31 January 2017)\n# ---------\n# \n# Enhancements\n# General tidy up of code and input variable format\n# \n# Changes\n# \n# Bug fixes\n# \n# Version 2 (12 August 2015)\n# ---------\n# \n# Enhancements\n# Improved header\n# Added capacity to output using different climatology period 1981-2010\n# Rearranged file input structure to account for choices of climatolgoy period\n# Tidied up code generally and tried to fix some oddities (changes)\n# \n# Changes\n# NOT SURE WHY BUT FOR UNCERTAINTY IN Td and DPD it tries to read in raw T and station_Pclim but\n# as it was would fail and set statP_arr to standard pressure of 1013. I have changed so that it reads in 20CRstation_Pclim \n# and no raw T (homog T already read in)\n# ALSO - not really sure why DPD has to come first so that it then needs to read in unhomogenised Td - need to go through code again really\n# \n# Bug fixes\n# RH subzeros not listed properly - were added to supersats and labelled as supersats\n# This has resulted in 1 fewer sat and 1 new sub for RH (anoms8110)\n# missed adjustment for e was 0.12 but should have been 0.2!!!\n#\n#\n# Version 1 (15 January 2015)\n# ---------\n# \n# Enhancements\n# \n# Changes\n# \n# Bug fixes\n# \n# -----------------------\n# OTHER INFORMATION\n# -----------------------\n##measurement uncertainty for obs_error:\n# For RH sensors this is approximatly 2% at 10% RH and 2.5% at 98% RH\n# For psychormeters we can assume 0.3 deg C wetbulb depession\n# This scales out as:\n# -50 deg C = 30% 0 deg C = 5.8% RH, 50 deg = 1.2% RH\t- \n# -50 = 30%\n# -40 = 30%\n# -30 = 30%\n# -20 = 20%\n# -10 = 10%\n# 0 = 6%\n# 10 = 4%\n# 20 = 2.5%\n# 30 = 1.8%\n# 40 = 1.4%\n# 50+ = 1.2% \n\n# give all 40-50 1.4%\n# give all 0-10 6% (apply upwards bin)\n# USED Michael de Podesta's spread sheet with eq. (ice and wet) from Buck 1981 (my thesis ch 2)\n# so - read in temperature netcdfs for climatology - scale errors with climatology or raw values?\n# scale with raw - may lead to change over time as temperatures change?\n# - may also lead to biases where adjustments have been made as T is not homog.\n# scale with clim - continuous over time but a little coarse? Although pos and neg should balance out?\n# penalise cold months - but that IS where we're least certain\n# AT GRIDBOX level this could scale with time too - introduce some change to RH sensor uncertainty beginning in 1990s to\n# be almost complete by 2011? Tricky and a bit arbitray - at least doing all using wetbulb uncertainty is a 'worst case'\n\n\n#******************************************************\n# Global variables and imports\n# Inbuilt: (may not all be required actually)\nimport numpy as np # used\nimport numpy.ma as npm # used\nfrom datetime import datetime # used\nimport matplotlib.pyplot as plt\nimport sys, os, getopt # used\nimport struct\nimport glob # used\nimport pdb # used\nimport netCDF4 as nc4\n#from netCDF4 import Dataset # used\nfrom subprocess import call, check_output, run, PIPE # used\n\n# Kate's Functions\nimport CalcHums\nfrom RandomsRanges import LetterRange\n\n# Restarter station ID\nRestartValue = '-----------' # '00000099999'\n\n# Start and end years if HardWire = 1\nstyear = 1973\nedyear = 2019\n\n# Dataset version if HardWire = 1\nversiondots = '4.2.0.2019f'\nversion = 'v420_2019f'\nhadisdversiondots = '3.1.0.2019f'\nhadisdversion = 'v310_2019f'\n\n# HARDWIRED SET UP!!!\n# If HardWire = 1 then program reads from the above run choices\n# If HardWire = 0 then program reads in from F1_HadISDHBuildConfig.txt\nHardWire = 0\n\nif (HardWire == 0):\n \n #' Read in the config file to get all of the info\n with open('F1_HadISDHBuildConfig.txt') as f:\n \n ConfigDict = dict(x.rstrip().split('=', 1) for x in f)\n \n versiondots = ConfigDict['VersionDots']\n hadisdversiondots = ConfigDict['HadISDVersionDots']\n styear = ConfigDict['StartYear']\n edyear = ConfigDict['EndYear']\n\n# AttribDict held in memory to probide global attribute text later\n#' Read in the attribute file to get all of the info\nwith open('F1_HadISDHBuildAttributes.txt') as f:\n \n AttribDict = dict(x.rstrip().split('=', 1) for x in f)\n\n# NOT CODED THIS FUNCTIONALITY YET\n## Are we working with homogenised actuals (True) or anomalies (False)?\n#Actuals = True\n\n# Set up directories locations\nupdateyy = str(edyear)[2:4]\nupdateyyyy = str(edyear)\nworkingdir = '/scratch/hadkw/UPDATE'+updateyyyy\n#workingdir = '/data/users/hadkw/WORKING_HADISDH/UPDATE'+updateyyyy\n\n# Set up filenames\nINDIRLIST = workingdir+'/LISTS_DOCS/'\nINDIRHOM = workingdir+'/MONTHLIES/HOMOG/' # this will then be PHAASCII or IDPHAASCII\nINDIRP = workingdir+'/MONTHLIES/NETCDF/'\n\n#workingdir = '/scratch/hadkw/UPDATE'+updateyyyy\nOUTDIRLIST = workingdir+'/LISTS_DOCS/'\nOUTDIRHOM = workingdir+'/MONTHLIES/HOMOG/' # this will then be PHANETCDF or IDPHANETCDF\nOUTDIRPLOTS = workingdir+'/MONTHLIES/HOMOG/STAT_PLOTS/UNCPLOTS/' \n# File for output stats but also for reading in missed adjustment uncertainties\nOUTPUTLOG = workingdir+'/LISTS_DOCS/OutputLogFile'+versiondots+'.txt'\n\n# Set up variables\nMDI = -1e+30\n#*** at some point add all the header info from the new HadISD files***\n\n# Dictionaries for param, units, homogdirprefix, STATION FILE PREFIX, standard name, long name, raw data suffix(only for test run)\nParamDict = dict([('q',['q','g/kg','IDPHA','Q','specific_humidity','monthly mean 2m specific humidity','qhum']),\n\t ('rh',['RH','%rh','IDPHA','RH','relative_humidity','monthly mean 2m relative humidity','rhum']),\n\t ('t',['T','deg C','IDPHA','T','drybulb_temperature','monthly mean 2m dry bulb temperature','temp']), # Note this needs to be changed to IDPHAMG later\n\t ('td',['Td','deg C','IDPHA','TD','dewpoint_temperature','monthly mean 2m dew point temperature','dewp']),\n\t ('tw',['Tw','deg C','IDPHA','TW','wetbulb_temperature','monthly mean 2m wetbulb temperature','twet']),\n\t ('e',['e','hPa','IDPHA','E','vapour_pressure','monthly mean 2m vapour pressure','evap']),\n\t ('dpd',['DPD','deg C','PHA','DPD','dewpoint depression','monthly mean 2m dew point depression','ddep']),\n\t ('tw_max',['TwX','deg C','IDPHA','TWMAX','wetbulb_temperature_maximum','monthly maximum 2m wetbulb temperature','twmx']),\n\t ('tw_max_95p',['TwX95p','1','IDPHA','TWMAX95','wetbulb_temperature_max95p','days per month maximum >= 95 percentile maximum 2m wetbulb temperature','twx95']),\n\t ('tw_mean_95p',['TwM95p','1','IDPHA','TWMEAN95','wetbulb_temperature_mean95p','days per month mean >= 95 percentile mean 2m wetbulb temperature','twm95']),\n\t ('tw_max_ex25',['Tw25','1','IDPHA','TW25','wetbulb_temperature_ex25','days per month >= 25 deg 2m wetbulb temperature','tw25']),\n\t ('tw_max_ex27',['Tw27','1','IDPHA','TW27','wetbulb_temperature_ex27','days per month >= 27 deg 2m wetbulb temperature','tw27']),\n\t ('tw_max_ex29',['Tw29','1','IDPHA','TW29','wetbulb_temperature_ex29','days per month >= 29 deg 2m wetbulb temperature','tw29']),\n\t ('tw_max_ex31',['Tw31','1','IDPHA','TW31','wetbulb_temperature_ex31','days per month >= 31 deg 2m wetbulb temperature','tw31']),\n\t ('tw_max_ex33',['Tw33','1','IDPHA','TW33','wetbulb_temperature_ex33','days per month >= 33 deg 2m wetbulb temperature','tw33']),\n\t ('tw_max_ex35',['Tw35','1','IDPHA','TW35','wetbulb_temperature_ex35','days per month >= 35 deg 2m wetbulb temperature','tw35'])])\n\n#******************************************************\n# SUBROUTINES #\n#******************************************************\n# READDATA\ndef ReadData(FileName,typee,delimee):\n ''' Use numpy genfromtxt reading to read in all rows from a complex array '''\n ''' Need to specify format as it is complex '''\n ''' outputs an array of tuples that in turn need to be subscripted by their names defaults f0...f8 '''\n return np.genfromtxt(FileName, dtype=typee, delimiter=delimee, encoding='latin-1') # ReadData\n# return np.genfromtxt(FileName, dtype=typee, delimiter=delimee) # ReadData\n\n#****************************************************\n# MakeDaysSince\ndef MakeDaysSince(TheStYr,TheStMon,TheEdYr,TheEdMon):\n ''' Take counts of months since styr, stmn (assume 15th day of month) '''\n ''' Work out counts of days since styr,stmn, January - incl leap days '''\n ''' Also work out time boundaries 1st and last day of month '''\n ''' This can cope with incomplete years or individual months '''\n \n # set up arrays for month month bounds\n BoundsArray = np.empty((((TheEdYr-TheStYr)+1)*((TheEdMon-TheStMon)+1),2))\n \n # make a date object for each time point and subtract start date\n StartDate = datetime(TheStYr,TheStMon,1,0,0,0)\t# January\n \n DaysArray = list(np.array([[(datetime(j,i,1,0,0,0)-StartDate).days + 15 for i in np.arange(1,13)] for j in np.arange(TheStYr,TheEdYr+1)]).flat)\n BoundsArray[:,0] = list(np.array([[(datetime(j,i,1,0,0,0)-StartDate).days for i in np.arange(1,13)] for j in np.arange(TheStYr,TheEdYr+1)]).flat)\n BoundsArray[:,1] = np.append(BoundsArray[1:,0]-1,(datetime(TheEdYr,TheEdMon,31,23,59,59)-StartDate).days)\n \n return DaysArray,BoundsArray\n\n#**************************************************************************************\n# WriteNetCDF\ndef WriteNetCDF(FileName,TheStYr,TheEdYr,TheClims,TheDataList,DimObject,AttrObject,GlobAttrObject,TheMDI):\n ''' WRites NetCDF4 '''\n ''' Sort out the date/times to write out and time bounds '''\n ''' Write to file, set up given dimensions, looping through all potential variables and their attributes, and then the provided dictionary of global attributes '''\n\n# # Attributes and things common to all vars\n# add_offset = -100.0 # storedval=int((var-offset)/scale)\n# scale_factor = 0.01\n \n # Sort out date/times to write out\n TimPoints,TimBounds = MakeDaysSince(int(TheStYr),1,int(TheEdYr),12)\n nTims = len(TimPoints)\n MonthName = ['January ',\n 'February ',\n\t 'March ',\n\t 'April ',\n\t 'May ',\n\t 'June ',\n\t 'July ',\n\t 'August ',\n\t 'September ',\n\t 'October ',\n\t 'November ',\n\t 'December ']\n\t\n # Create a new netCDF file - have tried zlib=True,least_significant_digit=3 (and 1) - no difference\n ncfw = nc4.Dataset(FileName,'w',format='NETCDF4_CLASSIC') # need to try NETCDF4 and also play with compression but test this first\n \n # Write out the global attributes\n if ('description' in GlobAttrObject):\n ncfw.description = GlobAttrObject['description']\n\t#print(GlobAttrObject['description'])\n\t\n if ('File_created' in GlobAttrObject):\n ncfw.File_created = GlobAttrObject['File_created']\n\n if ('Title' in GlobAttrObject):\n ncfw.Title = GlobAttrObject['Title']\n\n if ('Institution' in GlobAttrObject):\n ncfw.Institution = GlobAttrObject['Institution']\n\n if ('History' in GlobAttrObject):\n ncfw.History = GlobAttrObject['History']\n\n if ('Licence' in GlobAttrObject):\n ncfw.Licence = GlobAttrObject['Licence']\n\n if ('Project' in GlobAttrObject):\n ncfw.Project = GlobAttrObject['Project']\n\n if ('Processing_level' in GlobAttrObject):\n ncfw.Processing_level = GlobAttrObject['Processing_level']\n\n if ('Acknowledgement' in GlobAttrObject):\n ncfw.Acknowledgement = GlobAttrObject['Acknowledgement']\n\n if ('Source' in GlobAttrObject):\n ncfw.Source = GlobAttrObject['Source']\n\n if ('Comment' in GlobAttrObject):\n ncfw.Comment = GlobAttrObject['Comment']\n\n if ('References' in GlobAttrObject):\n ncfw.References = GlobAttrObject['References']\n\n if ('Creator_name' in GlobAttrObject):\n ncfw.Creator_name = GlobAttrObject['Creator_name']\n\n if ('Creator_email' in GlobAttrObject):\n ncfw.Creator_email = GlobAttrObject['Creator_email']\n\n if ('Version' in GlobAttrObject):\n ncfw.Version = GlobAttrObject['Version']\n\n if ('doi' in GlobAttrObject):\n ncfw.doi = GlobAttrObject['doi']\n\n if ('Conventions' in GlobAttrObject):\n ncfw.Conventions = GlobAttrObject['Conventions']\n\n if ('netcdf_type' in GlobAttrObject):\n ncfw.netcdf_type = GlobAttrObject['netcdf_type']\n\t\n # Loop through and set up the dimension names and quantities\n for vv in range(len(DimObject[0])):\n ncfw.createDimension(DimObject[0][vv],DimObject[1][vv])\n\t\n # Go through each dimension and set up the variable and attributes for that dimension if needed\n for vv in range(len(DimObject)-2): # ignore first two elements of the list but count all other dictionaries\n# print(DimObject[vv+2]['var_name'])\n\t\n\t# NOt 100% sure this works in a loop with overwriting\n\t# initiate variable with name, type and dimensions\n MyVar = ncfw.createVariable(DimObject[vv+2]['var_name'],DimObject[vv+2]['var_type'],DimObject[vv+2]['var_dims'])\n \n\t# Apply any other attributes\n if ('standard_name' in DimObject[vv+2]):\n MyVar.standard_name = DimObject[vv+2]['standard_name']\n\t \n if ('long_name' in DimObject[vv+2]):\n MyVar.long_name = DimObject[vv+2]['long_name']\n\t \n if ('units' in DimObject[vv+2]):\n MyVar.units = DimObject[vv+2]['units']\n\t\t \t \n if ('axis' in DimObject[vv+2]):\n MyVar.axis = DimObject[vv+2]['axis']\n\n if ('calendar' in DimObject[vv+2]):\n MyVar.calendar = DimObject[vv+2]['calendar']\n\n if ('start_year' in DimObject[vv+2]):\n MyVar.start_year = DimObject[vv+2]['start_year']\n\n if ('end_year' in DimObject[vv+2]):\n MyVar.end_year = DimObject[vv+2]['end_year']\n\n if ('start_month' in DimObject[vv+2]):\n MyVar.start_month = DimObject[vv+2]['start_month']\n\n if ('end_month' in DimObject[vv+2]):\n MyVar.end_month = DimObject[vv+2]['end_month']\n\n if ('bounds' in DimObject[vv+2]):\n MyVar.bounds = DimObject[vv+2]['bounds']\n\t\n\t# Provide the data to the variable\n if (DimObject[vv+2]['var_name'] == 'time'):\n MyVar[:] = TimPoints\n\n if (DimObject[vv+2]['var_name'] == 'bounds_time'):\n MyVar[:,:] = TimBounds\n\n if (DimObject[vv+2]['var_name'] == 'month'):\n# pdb.set_trace()\n# MyVar[mm,:] = [nc4.stringtochar(np.array(MonthName[mm],dtype='S10')) for mm in np.arange(1,13)] \n MyVar[:,:] = [[MonthName[mm][cc] for cc in range(10)] for mm in range(12)] \n\n # Go through each variable and set up the variable attributes\n for vv in range(len(AttrObject)): # ignore first two elements of the list but count all other dictionaries\n\n# print(AttrObject[vv]['var_name'])\n\n # initiate variable with name, type and dimensions\n MyVar = ncfw.createVariable(AttrObject[vv]['var_name'],AttrObject[vv]['var_type'],AttrObject[vv]['var_dims'],fill_value = TheMDI)\n \n\t# Apply any other attributes\n if ('long_name' in AttrObject[vv]):\n MyVar.long_name = AttrObject[vv]['long_name']\n\t \n if ('units' in AttrObject[vv]):\n MyVar.units = AttrObject[vv]['units']\n\n# MyVar.add_offset = add_offset\n# MyVar.scale_factor = scale_factor\n\n MyVar.reference_period = str(TheClims[0])+', '+str(TheClims[1])\n\n\t# Provide the data to the variable - depending on howmany dimensions there are\n\t## First change masked array to normal array filled with MDI\n #TheDataList[vv][TheDataList[vv].mask] = TheMDI\n MyVar[:] = TheDataList[vv].filled()\n\t \n ncfw.close()\n \n return # WriteNCCF\n\n#*******************************************************\n# MAIN #\n#*******************************************************\ndef main(argv):\n\n # INPUT PARAMETERS AS STRINGS!!!!\n var = 'q'\t # 'q','rh','e','td','tw','t','dpd'\n typee = 'IDPHA' # 'PHA','IDPHA','PHADPD'\n runtype = 'all' # 'all','00000099999'\n\n try:\n opts, args = getopt.getopt(argv, \"hi:\",\n\t [\"var=\",\"typee=\",\"runtype=\"])\n except getopt.GetoptError:\n print('Usage (as strings) F12_CreateHomogNCDFStUnc.py --var <q> --typee <IDPHA> --runtype <all>')\n sys.exit(2)\n\n for opt, arg in opts:\n if opt == \"--var\":\n try:\n var = arg\n except:\n sys.exit(\"Failed: var not a string\")\n elif opt == \"--typee\":\n try:\n typee = arg\n except:\n sys.exit(\"Failed: typee not a string\")\n elif opt == \"--runtype\":\n try:\n runtype = arg\n except:\n sys.exit(\"Failed: typee not a string\")\n \n# assert var != '' and typee != '', \"Input values not specified.\"\n\n print(var,typee,runtype)\n \n # Check to see if we're starting from the beginning?\n if (RestartValue == '-----------') & (runtype != 'all'):\n \n # Restarter set from run command line variables\n RestartID = runtype \n\n else:\n \n RestartID = RestartValue\n\t\n # Which climatology?\n MYclst = 1981\t# 1976, 1981\n MYcled = 2010\t# 2005, 2010\n CLMlab = str(MYclst)[2:4]+str(MYcled)[2:4]\n\n#*******************************************************\n # variable specific filepaths and directories\n # homogenised data file suffix\n DatSuffix = '_anoms'+CLMlab+'_homog.nc'\n\n # Needs to be IDPHAMG for T for the log of adjustments and MissedAdjErr\n homogtype = typee\n if (var == 't'):\n homogtype = 'IDPHAMG'\n\n # Set up files for read in and write out\n \n InList = INDIRLIST+'goodforHadISDH.'+versiondots+'_'+typee+var+'.txt'\n \n InHom = INDIRHOM+ParamDict[var][2]+'ASCII/'+ParamDict[var][3]+'DIR/'\t #***\n # Diretories to read in homog T and RH for finding measurement uncertainty\n InHomT = INDIRHOM+'IDPHAASCII/TDIR/'\t #***\n InHomRH = INDIRHOM+'IDPHAASCII/RHDIR/'\t #***\n # Note that homogtype is set to IDPHAMG for T (see above)\n# InLog = INDIRLIST+'HadISDH.land'+ParamDict[var][0]+'.'+versiondots+'_'+homogtype+'_JAN2020.log' #***\n InLog = INDIRLIST+'HadISDH.land'+ParamDict[var][0]+'.'+versiondots+'_'+homogtype+'.log' #***\n \n OutList = OUTDIRLIST+'Posthomog'+typee+var+'_anoms'+CLMlab+'_goodsHadISDH.'+versiondots+'.txt'\n OutFunniesT = OUTDIRLIST+'Posthomog'+typee+var+'_anoms'+CLMlab+'_satsHadISDH.'+versiondots+'.txt'\n OutFunniesZ = OUTDIRLIST+'Posthomog'+typee+var+'_anoms'+CLMlab+'_subzerosHadISDH.'+versiondots+'.txt'\n INRHSATS = OUTDIRLIST+'PosthomogIDPHArh_anoms'+CLMlab+'_satsHadISDH.'+versiondots+'.txt'\n INDPDSATS = OUTDIRLIST+'PosthomogPHAdpd_anoms'+CLMlab+'_satsHadISDH.'+versiondots+'.txt'\n OutBads = OUTDIRLIST+'Posthomog'+typee+var+'_anoms'+CLMlab+'_badsHadISDH.'+versiondots+'.txt'\n\n #OutDat = OUTDIRHOM+typee+'NETCDF/'+ParamDict[var][3]+'DIR/'\n # I think this works for Td and DPD so not need to Td special case loop below (Td read and write from to IDPHAASCII IDPHANETCDF...\n OutDat = OUTDIRHOM+ParamDict[var][2]+'NETCDF/'+ParamDict[var][3]+'DIR/'\n OutPlots = OUTDIRPLOTS+ParamDict[var][3]+'DIR/'\n\n homsuffix = '_'+typee+'adj.txt'\n # Special case for Td \n if (typee == 'PHADPD'):\n\n homsuffix = '_PHAadj.txt'\n# OutDat = OUTDIRHOM+'IDPHANETCDF/'+ParamDict[var][3]+'DIR/'\n# # I'm not copying over from DPD anymote\n\n # A tweak if its a Tw extreme:\n if (var in ['tw_max', 'tw_max_95p', 'tw_mean_95p', 'tw_max_ex25', 'tw_max_ex27', 'tw_max_ex29', 'tw_max_ex31', 'tw_max_ex33', 'tw_max_ex35']):\n\n InList = INDIRLIST+'PosthomogIDPHAtw_anoms'+CLMlab+'_goodsHadISDH.'+versiondots+'.txt'\n InCheckExList = INDIRLIST+'goodforHadISDHTwEx.'+versiondots+'.txt'\n InHom = INDIRHOM+'IDPHANETCDF/TWDIR/'\t #***\n InRaw = INDIRP\t #***\n rawsuffix = '_hummonthQC.nc' \n OutFunniesT = OUTDIRLIST+'Posthomog'+typee+'tw_anoms'+CLMlab+'_satsHadISDH.'+versiondots+'.txt'\n OutFunniesZ = OUTDIRLIST+'Posthomog'+typee+'tw_anoms'+CLMlab+'_subzerosHadISDH.'+versiondots+'.txt'\n OutBads = OUTDIRLIST+'Posthomog'+typee+'tw_anoms'+CLMlab+'_badsHadISDH.'+versiondots+'.txt'\n\n#--------------------------------------------------------\n # other variables and arrays \n clst = MYclst - int(styear)\n cled = MYcled - int(styear)\n nyrs = (int(edyear) + 1) - int(styear)\n nmons = nyrs * 12\n # Save netCDF file as days since 01-01-1973 DD-MM-YYYY\n\n # UNCERTAINTIES IN MEASUREMENT\n RHBins = [-100,-40,-30,-20,-10,0,10,20,30,40,50,100]\t# degrees C\n\n # 1 sigma (THIS IS LATER *2 TO PROVIDE 2 SIGMA UNCS)\n RHUnc = [15,15,15,10,5,2.75,1.8,1.35,1.1,0.95,0.8] \n t_unc = 0.2\n tw_unc = 0.15\n\n # A tweak if its a Tw extreme:\n if (var not in ['tw_max', 'tw_max_95p', 'tw_mean_95p', 'tw_max_ex25', 'tw_max_ex27', 'tw_max_ex29', 'tw_max_ex31', 'tw_max_ex33', 'tw_max_ex35']):\n\n # Find the missed adjustment uncertainty from the Adjs_Stats file for variable and homogtype\n moo = check_output(['grep','-a','^'+var+'_'+homogtype+'_STD_GAUSSDIFFS=',OUTPUTLOG])\n # Now sort out this string which is a byte array, remove newline and split\n moo = moo.decode(\"utf-8\").strip('\\n').split('=')\t\n # print('Check read in of missed adjustment')\n # pdb.set_trace()\n \n MissedAdjErr = float(moo[1]) # THIS IS 1 SIGMA AND LATER * 2 TO PROVIDE 2 SIGMA UNCS\n \n#*************************************************************\n# Work through station by station\n#*************************************************************\n \n # Open and read in station list \n # A tweak if its a Tw extreme:\n if (var not in ['tw_max', 'tw_max_95p', 'tw_mean_95p', 'tw_max_ex25', 'tw_max_ex27', 'tw_max_ex29', 'tw_max_ex31', 'tw_max_ex33', 'tw_max_ex35']):\n MyTypes = (\"|U11\",\"float\",\"float\",\"float\",\"|U1\",\"|U2\",\"|U1\",\"|U29\",\"|U13\")\n MyDelimiters = [11,8,10,7,1,2,1,29,13]\n RawData = ReadData(InList,MyTypes,MyDelimiters)\n StationListID = np.array(RawData['f0'])\n StationListLat = np.array(RawData['f1'])\n StationListLon = np.array(RawData['f2'])\n StationListElev = np.array(RawData['f3'])\n StationListCID = np.array(RawData['f5'])\n StationListName = np.array(RawData['f7'])\n\n else:\n MyTypes = (\"|U11\",\"float\",\"float\",\"float\",\"|U1\",\"|U2\",\"|U1\",\"|U29\")\n MyDelimiters = [11,9,10,7,1,2,1,29]\n RawData = ReadData(InList,MyTypes,MyDelimiters)\n MyTypes = (\"|U11\",\"float\",\"float\",\"float\",\"|U1\",\"|U2\",\"|U1\",\"|U29\",\"|U13\")\n MyDelimiters = [11,8,10,7,1,2,1,29,13]\n CheckData = ReadData(InCheckExList,MyTypes,MyDelimiters)\n # Asuuming both station lists are unique and sorted (ok for numerical station IDs but check alphanumerics?) locate the stations that are common to both lists\n CommonStations, MapToRaw, MapToCheck = np.intersect1d(np.array(RawData['f0']),np.array(CheckData['f0']),assume_unique=True,return_indices=True)\n\n StationListID = np.array(RawData['f0'])[MapToRaw]\n StationListLat = np.array(RawData['f1'])[MapToRaw]\n StationListLon = np.array(RawData['f2'])[MapToRaw]\n StationListElev = np.array(RawData['f3'])[MapToRaw]\n StationListCID = np.array(RawData['f5'])[MapToRaw]\n StationListName = np.array(RawData['f7'])[MapToRaw]\n \n nstations = len(StationListID)\n #print('Test to see if station read in has worked correctly and whether there is a more efficient method')\n # Yes this works as expected\n #pdb.set_trace()\n\n # loop through station by station\n for st in range(nstations):\n\n # check if restart necessary\n if RestartID != '-----------' and RestartID != StationListID[st]:\n continue\n\n RestartID = '-----------'\n \n # find homog file for selected variable and read in to array \n # A tweak if its a Tw extreme:\n if (var not in ['tw_max', 'tw_max_95p', 'tw_mean_95p', 'tw_max_ex25', 'tw_max_ex27', 'tw_max_ex29', 'tw_max_ex31', 'tw_max_ex33', 'tw_max_ex35']):\n InFile = InHom+StationListID[st]+homsuffix\n MyTypes = np.append(\"|U12\",[\"int\"]*13)\n MyDelimiters = np.append([12,4,6],[7]*11)\n RawData = ReadData(InFile,MyTypes,MyDelimiters)\n \n stat_abs = npm.array(()) # initiate empty masked array to append to\n for yy in range(nyrs):\n \n moo = list(RawData[yy])\n stat_abs = npm.append(stat_abs,np.copy(npm.array(moo[2:14])/100.)) \n\n # If its tw extremes then we're reading in from netCDF and MDI is already -1e30\n else:\n ncf = nc4.Dataset(InRaw+StationListID[st][0:6]+'-'+StationListID[st][6:11]+rawsuffix,'r')\n stat_abs = npm.array(ncf.variables[var][:]) # do we need to release the pointer?\n # Convert to float - important for days exceedance variables\n stat_abs = stat_abs.astype(float)\n ncf.close()\n\n #print('Check file read in: ',StationListID[st])\n #pdb.set_trace() \n \n # Initiate other masked arrays\n stat_anoms = npm.repeat(MDI,nmons)\n stat_sds = npm.repeat(MDI,nmons) # to be filled at end\n stat_clims = npm.repeat(MDI,12)\n stat_clim_sds = npm.repeat(MDI,12)\n stat_adjs = npm.repeat(0.,nmons)\n stat_adjs_err = npm.repeat(0.,nmons)\n stat_clims_err = npm.repeat(MDI,nmons)\n stat_obs_err = npm.repeat(MDI,nmons)\n station_err = npm.repeat(MDI,nmons)\n\n # Use masked arrays so set the old MDI which is now -99.99 to the new MDI which is -1e30 then convert to masked - a double check on floating point imprecision for netCDF files (tw extremes)\n stat_abs[stat_abs <= -99.99] = MDI\n stat_abs = npm.masked_equal(stat_abs, MDI) # should not fall over if there are no missing values\n #print('Check masking of stat_abs array and Tw extremes exceedance MDI float/ints')\n #pdb.set_trace()\n\t \n#*******************************************************************************\n# Find subzeros and supersats (if relevant to variable), output to releavnt lists and then move on to next station\n#*******************************************************************************\n \n\t# DO NOT PROCESS THE STATION ANY FURTHER AS ITS NOW CONSIDERED A BAD!!!\n # No relevance for T\n # subsats - RH, q, e should not be less than zero \n # supersats - RH should not be greater than 100\n # DPD should not be less than zero (derived Td then fine)\n # Td should not be greater than T - using same listing as for DPD\n # Tw should not be greater than T\n\t# COULD TRANSFER PROBLEMS IN RH or DPD TO ALL VARIABLES\n # FIND HOMOGENISED FILE IF IT EXISTS\n \n # No need to look for subs and sats if its T or its a tw extreme [already removed those as we're using PosthomogIDPHAtw_goodslist]\n if (var not in ['t', 'tw_max', 'tw_max_95p', 'tw_mean_95p', 'tw_max_ex25', 'tw_max_ex27', 'tw_max_ex29', 'tw_max_ex31', 'tw_max_ex33', 'tw_max_ex35']): \n\t \n GotSats = False\n GotSubs = False\n\t \n # for rh sats where RH > 100. and subs where RH < 0.\n if (var == 'rh'):\n\t \n if (len(np.where(stat_abs.compressed() > 100.)[0]) > 0):\n\t\t#if (len(stat_abs[(stat_abs > MDI) & (stat_abs > 100.)]) > 0):\n\n print('Found supersats!')\n #GotSats = len(stat_abs[(stat_abs > MDI) & (stat_abs > 100.)])\n GotSats = len(np.where(stat_abs.compressed() > 100.)[0])\n\t\t \t\t\n if (len(np.where(stat_abs.compressed() < 0.)[0]) > 0):\n #if (len(stat_abs[(stat_abs > MDI) & (stat_abs < 0.)]) > 0):\n\n print('Found subzeros!')\n GotSubs = len(np.where(stat_abs.compressed() < 0.)[0])\n #GotSubs = len(stat_abs[(stat_abs > MDI) & (stat_abs < 0.)])\n\t \t\n\t # For dpd sats where dpd < 0\n elif (var == 'dpd'):\t\n \n if (len(np.where(stat_abs.compressed() < 0.)[0]) > 0):\n #if (len(stat_abs[(stat_abs > MDI) & (stat_abs < 0.)]) > 0):\n\n print('Found supersats!')\n GotSats = len(np.where(stat_abs.compressed() < 0.)[0])\n #GotSats = len(stat_abs[(stat_abs > MDI) & (stat_abs < 0.)])\n\t \t\t\n\t # for q or e subs if q or e < 0 and if RH station listed as sat\n elif (var == 'q') or (var == 'e'):\n\n if (len(np.where(stat_abs.compressed() < 0.)[0]) > 0):\n #if (len(stat_abs[(stat_abs > MDI) & (stat_abs < 0.)]) > 0):\n\n print('Found subzeros!')\n GotSubs = len(np.where(stat_abs.compressed() < 0.)[0]) \t\n #GotSubs = len(stat_abs[(stat_abs > MDI) & (stat_abs < 0.)]) \t\n\n # Look for the station string in the RH list? - NOTE CHECK_OUTPUT WILL FAIL IF IT CAN@T FIND ANYTHING\n moo = run(['grep','-a','^'+StationListID[st],INRHSATS],stdout=PIPE)\n if (moo.returncode == 0): # then we've found the station\n \n print('Found supersats!')\n GotSats = 'RH supersats found '+moo.stdout.decode('utf-8').split()[1]\n# pdb.set_trace()\n\t \t\n # for td sats if DPD station listed as sat\n elif (var == 'td'):\n\n # Look for the station string in the RH list? - NOTE CHECK_OUTPUT WILL FAIL IF IT CAN@T FIND ANYTHING\n moo = run(['grep','-a','^'+StationListID[st],INDPDSATS],stdout=PIPE)\n if (moo.returncode == 0): # then we've found the station\n \n print('Found supersats!')\n GotSats = 'DPD supersats found '+moo.stdout.decode('utf-8').split()[1]\n# pdb.set_trace()\n\t \n\t # for tw sats if tw > t so need to read in t or just use dpd? Tw is very sensitive to this so it kicks out A LOT of stations\n elif (var == 'tw'):\t\n\t\n # Look for the station string in the RH list? - NOTE CHECK_OUTPUT WILL FAIL IF IT CAN@T FIND ANYTHING\n moo = run(['grep','-a','^'+StationListID[st],INDPDSATS],stdout=PIPE)\n if (moo.returncode == 0): # then we've found the station\n \n print('Found supersats!')\n GotSats = 'DPD supersats found '+moo.stdout.decode('utf-8').split()[1]\n# pdb.set_trace()\t \n\n # If we've got a supersat - write out station to list of supersats\n if (GotSats):\n filee = open(OutFunniesT,'a+')\n filee.write('%s %s\\n' % (StationListID[st],GotSats))\n filee.close()\n\t # Do we need to list as bads too?\n filee = open(OutBads,'a+')\n filee.write('%s %s\\n' % (StationListID[st], 'Supersaturation found'))\n filee.close()\n\n # If we've got a subzero - write out station to list of subzeros\n if (GotSubs):\n filee = open(OutFunniesZ,'a+')\n filee.write('%s %s\\n' % (StationListID[st],GotSubs))\n filee.close()\n\t # Do we need to list as bads too?\n filee = open(OutBads,'a+')\n filee.write('%s %s\\n' % (StationListID[st], 'Subzero found'))\n filee.close()\n\n # Now stop processing this station if we've found a sat or sub\n if (GotSats) or (GotSubs):\n print('Stopping processing station: ',StationListID[st])\n continue\t \n\t \n#******************************************************************\n# create station anomalies and climatologies from homogenised abs\n#******************************************************************\n\n # NOTE: we can do this for the Tw extremes but its not entirely logical or useful I think\n # ALSO: we don't want exceedance days failing because there aren't enough days to calculate a climatology\n # As we're working with masked arrays nothing should in theory break I think - does it fill with MDI if a value cannot be calculated? CHECK!!!\n \n\t# reshape the array to be a row for each year\n stat_abs = np.reshape(stat_abs,(nyrs,12)) \n # subset the values to just the climatology period\n subclm = stat_abs[clst:cled+1,:] \n \n\t# Are there enough years (>= 15) for each month? There must be a climatology value for each month to continue processing station\n if (var not in ['tw_max', 'tw_max_95p', 'tw_mean_95p', 'tw_max_ex25', 'tw_max_ex27', 'tw_max_ex29', 'tw_max_ex31', 'tw_max_ex33', 'tw_max_ex35']) & (npm.sum(npm.count(subclm,0) >= 15) < 12): # counts for each valid month over the 30 year period, sums these counts and enters loop if at least 1 count is less than 15\n\n # No there are not for at least one month so write out to bad station file and cease processeing\n print('At least one month has too few values to calculate a climatology')\n filee = open(OutBads,'a+')\n filee.write('%s %s %i\\n' % (StationListID[st], 'Too few months for a climatology', np.sum(npm.count(subclm,0) >= 15)))\n filee.close()\n #pdb.set_trace()\n continue\n\t \t\n\t# Calculate climatology, climatological standard deviation and anomalies\n stat_clims = npm.mean(subclm,0) # compute the mean over each 30 year slice for each month, ignoring missing data \n # Note that np.std assumes we're calculating st dev from whole population where as IDL assumes sample of population so deg_of_freedom = n-1\n\t# To match with previous IDL code, and because very often we have missing data, set ddof = 1 to use n-1\n stat_clim_sds = npm.std(subclm,0,ddof=1) # compute the stdeviation over each 30 year slice for each month, ignoring missing data \n stat_anoms = stat_abs - stat_clims # this substracts the right month clim from the right month actual, ignoring missing data\n\n #print('Check whether the masked arrays are working on sparse extremes data')\n #pdb.set_trace()\n\n#**# CALCULATE CLIMATOLOGY UNCERTAINTY - ***2-SIGMA*** \n # For Tw extremes - import climatology uncertainty from Tw \n # At this point, also mask in the missing datat from the homogenised anomalies - removing periods of known \n # inhomogeneity that couldn't be adjusted for - and have no adjustment information with which to QC the data\n if (var not in ['tw_max', 'tw_max_95p', 'tw_mean_95p', 'tw_max_ex25', 'tw_max_ex27', 'tw_max_ex29', 'tw_max_ex31', 'tw_max_ex33', 'tw_max_ex35']): \n stat_clims_err = np.tile((stat_clim_sds / np.sqrt(npm.count(subclm,0))) * 2, [nyrs,1])\n # Mask the uncertainty array with the same missing values\n stat_clims_err[stat_abs.mask] = MDI\n stat_clims_err = npm.masked_equal(stat_clims_err, MDI) # should not fall over if there are no missing values\n stat_clims_err = np.reshape(stat_clims_err, 12 * nyrs)\n # Reshape the arrays ready to write to file\n stat_abs = np.reshape(stat_abs, 12 * nyrs)\n stat_anoms = np.reshape(stat_anoms, 12 * nyrs)\n\n else:\n ncf = nc4.Dataset(InHom+StationListID[st]+DatSuffix,'r')\n stat_clims_err = npm.array(ncf.variables['tw_climerr'][:]) # do we need to release the pointer?\n tw_mask = npm.array(ncf.variables['tw_anoms'][:]) \n ncf.close()\n stat_clims_err[stat_clims_err <= -99.99] = MDI\n stat_clims_err = npm.masked_equal(stat_clims_err, MDI) # should not fall over if there are no missing values\n # Reshape the arrays ready to write to file\n stat_abs = np.reshape(stat_abs, 12 * nyrs)\n stat_anoms = np.reshape(stat_anoms, 12 * nyrs)\n stat_abs[tw_mask <= -99.99] = MDI\n stat_anoms[tw_mask <= -99.99] = MDI\n #stat_sds set later to tw_sds which is then masked\n\n #print('Completed anomalies and climatology error - check')\n #pdb.set_trace()\n\t\n#********************************************************************\t\n# Work out the relative measurement uncertainty - ***2 SIGMA***\n#********************************************************************\n \n\t# Find right variable to process\n if (var == 't'):\n\t\n # Easy for T - +/- 0.2 deg - this is 1 sigma so multiply by 2\n stat_obs_err[:] = (t_unc / np.sqrt(60.)) * 2 \t# minimum number of obs per month is 15 days * 4 obs per day = 60 for single station within gridbox \n\n elif (var == 'tw'):\n\t\n # Easy for Tw - +/- 0.15 deg - this is 1 sigma so multiply by 2 - WET BULB ERROR pre 1980 (mostly)\n # 15%rh at -50 deg C T, 0.8 %rh at 50 deg C T\n # scale all error based on %rh at T\n stat_obs_err[:] = (tw_unc / np.sqrt(60.)) * 2 \t# minimum number of obs per month is 15 days * 4 obs per day = 60 for single station within gridbox \n\n elif (var == 'rh'):\n\t\n # FOR RH - easy - bin from -50 to 50 deg C and apply table of %rh errors based on 0.15 deg C error in Tw - multiply by 2 to give 2 sigma unc\n\t # If T file exists then read in T_abs homogenise\n if (len(glob.glob(InHomT+StationListID[st]+'_IDPHAadj.txt')) == 1):\n \n InFile = InHomT+StationListID[st]+'_IDPHAadj.txt'\n RawData = ReadData(InFile,MyTypes,MyDelimiters)\n stat_absT = npm.array(()) # initiate empty masked array to append to\n for yy in range(nyrs):\n \n moo = list(RawData[yy])\n stat_absT = npm.append(stat_absT,np.copy(npm.array(moo[2:14])/100.)) \n\n # Set all missing values to 5. degrees which will map to a 2.75% RH uncertainty (>= 0. and < 10. deg) - may be months where T was removed by PHA so still present in RH\n stat_absT[stat_absT == -99.99] = 5. \n\n # Loop through RH bins start to penultimate bin\n for b,binn in enumerate(RHBins[:-1]):\n\t\t\n # Set T to the RH Uncertainty for the associated level of T in RHBins and compute uncertainty\n stat_obs_err[(stat_absT >= binn) & (stat_absT < RHBins[b+1])] = (RHUnc[b] / np.sqrt(60.)) * 2. # minimum number of obs per month is 15 days * 4 obs per day = 60 for single station within gridbox \t\t\n\n# print('Check the RH unc aligns with T bins')\n# pdb.set_trace()\n\t\t \n\t # No T file exists - # NO TEMPERATURE DATA SO ASSUME MODERATE UNCERTAINTY OF 3%\n else:\n\t \n stat_obs_err[:] = (2.75 / np.sqrt(60.)) * 2 \t# minimum number of obs per month is 15 days * 4 obs per day = 60 for single station within gridbox \n\n elif (var in ['q', 'e', 'td', 'dpd']): # var is q, e, td or dpd\n\t\n # FOR q or e or Td: (ASSUME RH=80% IF NO RH FILE/OB EXISTS, and 2.75%rh uncertainty IF NO TEMPERATURE FILE/OB EXIST - set T = 5. to get that [>=0.<10 deg]) - *2 to get 2sigma\n\t # If T file exists then read in T_abs homogenise\n if (len(glob.glob(InHomT+StationListID[st]+'_IDPHAadj.txt')) == 1):\n \n InFile = InHomT+StationListID[st]+'_IDPHAadj.txt'\n RawData = ReadData(InFile,MyTypes,MyDelimiters)\n stat_absT = npm.array(()) # initiate empty masked array to append to\n for yy in range(nyrs):\n \n moo = list(RawData[yy])\n stat_absT = npm.append(stat_absT,np.copy(np.array(moo[2:14])/100.)) \n\n # Set all missing values to 0 degrees which will map to a 3% RH uncertainty - may be months where T was removed by PHA so still present in RH\n stat_absT[stat_absT == -99.99] = 5. \n\t\t \n # If no T file then set T values to 0. degrees\n else:\n\n stat_absT = npm.repeat(5.,nmons)\n\t\t \n\t # If RH file exists then read in RH_abs homogenise\n if (len(glob.glob(InHomRH+StationListID[st]+'_IDPHAadj.txt')) == 1):\n \n InFile = InHomRH+StationListID[st]+'_IDPHAadj.txt'\n RawData = ReadData(InFile,MyTypes,MyDelimiters)\n stat_absRH = npm.array(()) # initiate empty masked array to append to\n for yy in range(nyrs):\n \n moo = list(RawData[yy])\n stat_absRH = npm.append(stat_absRH,np.copy(npm.array(moo[2:14])/100.)) \n\n # Set all missing values to 80. %rh - may be months where RH was removed by PHA so still present in q\n stat_absRH[stat_absRH == -99.99] = 80. \n\t\t \n # If no RH file then set RH values to 80. %rh\n else:\n\n stat_absRH = npm.repeat(80.,nmons)\n\t\t \n # Get uncertainty for q or e\n # qsat=(q/RH)*100\n # q+err=((RH+err)/100)*qsat\n # qerr=(q+err)-q\n if ((var == 'q') or (var == 'e')):\n \t \n\t\t# Set up a pseudo qsat or esat masked array\n sat_array = (stat_abs / stat_absRH) * 100.\n\t # Loop through RH bins start to penultimate bin\n for b,binn in enumerate(RHBins[:-1]):\n\t\t\n # Set T to the RH Uncertainty for the associated level of T in RHBins and compute uncertainty\n\t\t # straight RHUnc not /sqrt(60.) because we're pretending this is an individual ob\n stat_obs_err[(stat_absT >= binn) & (stat_absT < RHBins[b+1])] = (((((stat_absRH[(stat_absT >= binn) & (stat_absT < RHBins[b+1])] + RHUnc[b]) / 100.) \\\n\t\t * sat_array[(stat_absT >= binn) & (stat_absT < RHBins[b+1])]) \\\n\t\t\t\t\t\t\t\t\t\t - stat_abs[(stat_absT >= binn) & (stat_absT < RHBins[b+1])]) / npm.sqrt(60.)) * 2.\n\t\t # minimum number of obs per month is 15 days * 4 obs per day = 60 for single station within gridbox \t\t\n\n# print('Check the q / e unc aligns with RH and T bins - masking of stat_abs???')\n# pdb.set_trace()\n\t\t\n\t # If its Td or DPD then\n # FOR Td: use error in e. (ASSUME RH=80% IF NO RH FILE/OB EXISTS, and 2.75%rh uncertainty IF NO TEMPERATURE FILE/OB EXIST)\n # e=e(Td)\n # esat=(e/RH)*100\n # e+err=((RH+err)/100)*esat\n # Td+err=Td+err(e+err)\n # Tderr=(Td+err)-Td\n else:\n\n # Need to read in station P from 20CR - that's a pain! - its in the raw station netCDF files\n if (len(glob.glob(INDIRP+StationListID[st][0:6]+'-'+StationListID[st][6:11]+'_hummonthQC.nc')) == 1):\n \n ncf = nc4.Dataset(INDIRP+StationListID[st][0:6]+'-'+StationListID[st][6:11]+'_hummonthQC.nc','r')\n # Climatological station level P from 20CR - repeated for each year giving an nmons array\n P_arr = npm.array(ncf.variables['20CRstation_Pclim'][:]) # do we need to release the pointer?\n ncf.close()\n# print('Read in Station P - check')\n# pdb.set_trace()\n\n # If the station file doesn't exist then assume standard P of 1013\n else:\n\n P_arr = npm.repeat(1013.,nmons)\t\t\n\n # Now compute the uncertainty in Td\n\t\t# Set up a pseudo esat masked array - \n if (var == 'td'):\n\n\t\t # We're working with Td so calculating e fairly easy\t\t\n\t\t # we can use T so that the ice bulb equation can be used - if T is set to 5. when it should be < 0. then its going to be wrong\n\t\t # Using wet bulb instead of ice bulb will give slightly higher values of e \n # Calculate esat\n sat_array = (CalcHums.vap(stat_abs, stat_absT, P_arr,roundit=False) / stat_absRH) * 100.\n\n else: \n\t\n\t\t # we're working with DPD so must get Td from T-DPD\n\t\t # Problem when we have set T to 5. and DPD exists because Td could be very wrong - VERY LOW or possibly too high for cold stations/months - can't do much about this\n # For consistency (its all wrong anyway) we use T here too to choose ice or wet bulb calc\n # Calculate esat\n sat_array = (CalcHums.vap((stat_absT-stat_abs), stat_absT, P_arr,roundit=False) / stat_absRH) * 100.\n\t\t\n\t\t# Loop through RH bins start to penultimate bin\n for b,binn in enumerate(RHBins[:-1]):\n\t\t\n # Set T to the RH Uncertainty for the associated level of T in RHBins and compute e+err\n\t\t # straight RHUnc not /sqrt(60.) because we're pretending this is an individual ob\n # Calculate e+err=((RH+err)/100)*esat\n stat_obs_err[(stat_absT >= binn) & (stat_absT < RHBins[b+1])] = (((stat_absRH[(stat_absT >= binn) & (stat_absT < RHBins[b+1])] + RHUnc[b]) / 100.) \\\n\t\t * sat_array[(stat_absT >= binn) & (stat_absT < RHBins[b+1])])\n\t\t # minimum number of obs per month is 15 days * 4 obs per day = 60 for single station within gridbox \t\t\n\n# print('Check the e+err aligns with RH and T bins')\n# pdb.set_trace()\n\t\n\t\t# Compute Td+err from Td+err(e+err) and then substract Td to get Tderr adn then divide by 60 and * 2 to get 2sigma\n if (var == 'td'):\n \n\t\t # Working with Td so straightforward \n\t\t # Again using T to get pseudowetbulb to detect ice bulb - will be a little too high in erroneous wet bulb cases\t\n # Td+err=Td+err(e+err)\n # Tderr=(Td+err)-Td\n stat_obs_err = (((CalcHums.td_from_vap(stat_obs_err,P_arr,stat_absT,roundit=False)) - stat_abs) / npm.sqrt(60.) ) * 2.\t\n\t\t # minimum number of obs per month is 15 days * 4 obs per day = 60 for single station within gridbox \t\t\n \n else:\n\t\t\n\t\t # Working with DPD so need to get pseudo Td\n # Td+err=Td+err(e+err)\n # Tderr=(Td+err)-Td\n stat_obs_err = ((CalcHums.td_from_vap(stat_obs_err,P_arr,stat_absT,roundit=False)) - (stat_absT - stat_abs)) # Again using Td instead of T to get pseudowetbulb to detect ice bulb - will be a little too low in erroneous ice cases\t\t\n\t\t # DPD = add 0.2 deg C unc from T on to DPD then *2 to get 2sigma\n stat_obs_err = ((stat_obs_err + 0.2) / npm.sqrt(60.)) * 2.\n\t\t # minimum number of obs per month is 15 days * 4 obs per day = 60 for single station within gridbox \t\t\n\t\t \n# print('Check the Tderr or DPDerr aligns with RH and T bins')\n# pdb.set_trace()\n\t\t# This give DPD obs error slightly smaller than the IDL version when T is < or very close to 0. because the ice bulb calculation is used here to convert to vapour pressure\n\n else: # Its a Tw extreme so use Tw measurement error\n ncf = nc4.Dataset(InHom+StationListID[st]+DatSuffix,'r')\n stat_obs_err = npm.array(ncf.variables['tw_obserr'][:]) # do we need to release the pointer?\n ncf.close()\n stat_obs_err[stat_obs_err <= -99.99] = MDI\n stat_obs_err = npm.masked_equal(stat_obs_err, MDI) # should not fall over if there are no missing values\n\n #print('Check the obs error for Tw extreme')\n #pdb.set_trace()\n\n # Now mask in the missing data\n stat_obs_err[stat_abs.mask] = MDI\n stat_obs_err = npm.masked_equal(stat_obs_err, MDI) # should not fall over if there are no missing values\n#\tstat_obs_err.mask = stat_abs.mask\t \n\n#*******************************************************************\n# RH SENSOR ERROR (post 1980 - progressively) - NOT ADDED YET\n#*******************************************************************\n\n#*******************************************************************\n# Work on adjustment uncertainties\n#*******************************************************************\n # If its Tw extreme then read in adj and adjerr from Tw\n if (var not in ['tw_max', 'tw_max_95p', 'tw_mean_95p', 'tw_max_ex25', 'tw_max_ex27', 'tw_max_ex29', 'tw_max_ex31', 'tw_max_ex33', 'tw_max_ex35']):\n \n # read in log and find adjustment uncertainties - apply\n # # Gunzip PHA output file\n # call(['gunzip',InLog+'.gz'])\n\n # find homog adj for this station and append to array \n if (homogtype == 'PHA'):\n #PHA - 0=ID, 3=stmon,6=edmon, 8=ibreak, 9=cbreak, 10=adj, 11=eadj \n\t\n stmonget = 3\n edmonget = 6\n adjget = 10\n eadj = 11\n\t \n moo = check_output(['grep','-a','^Adj write:'+StationListID[st],InLog])\n # Now sort out this string which is a byte array\n # This creates a list of strings for each adjustment with a blank string at the beginning\n moo = moo.decode(\"utf-8\").split('Adj write:')\t\n\n elif (homogtype == 'IDPHAMG') or (homogtype == 'PHADPD'):\n #IDPHAMG - 0=ID, 2=stmon, 3=edmon, 6=adj, 7=eadj, 8=adj source indicator \n\n stmonget = 2\n edmonget = 3\n adjget = 6\n eadj = 7\n\t \n moo = check_output(['grep','-a','^'+StationListID[st],InLog])\n # Now sort out this string which is a byte array\n # This creates a list of strings for each adjustment with a blank string at the beginning\n moo = moo.decode(\"utf-8\").split('\\n') # no space\t\n\n else:\n #IDPHA - 0=ID, 2=stmon, 3=edmon, 6=adj, 7=eadj \n\n stmonget = 2\n edmonget = 3\n adjget = 6\n eadj = 7\n\t \n moo = check_output(['grep','-a','^'+StationListID[st],InLog])\n # Now sort out this string which is a byte array\n # This creates a list of strings for each adjustment with a blank string at the beginning\n moo = moo.decode(\"utf-8\").split(' \\n')\t\n\n # Remove the blank string\n moo.remove('')\n # Strip the \\n newline characters, random letters and split the strings to make a list of lists\n # b, i, p in IDPHAMG \n moo = [i.strip(' ABCDEFGHIJKLMNOPQRSTUVWXYZbip\\n').split() for i in moo] \n\n # Now loop through the adjustments to append to array\n # Ignore first line as this is most recent period so adjustment is 0\n for rec,adjstr in enumerate(moo[1:]):\n\n Adj = -(np.copy(np.float(adjstr[adjget])))\n #print(Adj)\n # these go from 1+, not 0+, first in loop is most recent period - no adjustment here \n stat_adjs[int(adjstr[stmonget])-1:int(adjstr[edmonget])] = Adj\n # THIS IS A 5th-95th so 1.65 sigma\n # divide by 1.65 then multiply by 2 to get 2sigma error - consistent with everything else then.\n stat_adjs_err[int(adjstr[stmonget])-1:int(adjstr[edmonget])] = np.float(adjstr[eadj]) / 1.65\n\n # print('Check read in and processing of adjustment and error')\n # pdb.set_trace()\n\n # # gzip PHA output file for tidiness\n # call(['gzip',InLog])\n\n # add in the flat adjustment error for missed adjustments derived from teh missing middle\n # combine in quadtrature and multiply by 2 to give a 2 sigma error\n stat_adjs_err = (npm.sqrt((stat_adjs_err**2) + (MissedAdjErr**2))) * 2.\n \n else:\n ncf = nc4.Dataset(InHom+StationListID[st]+DatSuffix,'r')\n stat_adjs = npm.array(ncf.variables['tw_adjustments'][:]) \n stat_adjs_err = npm.array(ncf.variables['tw_adjerr'][:]) \n ncf.close()\n stat_adjs_err[stat_adjs_err <= -99.99] = MDI\n stat_adjs_err = npm.masked_equal(stat_adjs_err, MDI) # should not fall over if there are no missing values\n stat_adjs[stat_adjs <= -99.99] = MDI\n stat_adjs = npm.masked_equal(stat_adjs, MDI) # should not fall over if there are no missing values\n\n # Now mask in the missing data\n #stat_adjs_err.mask = stat_abs.mask\n #stat_adjs.mask = stat_abs.mask\t \n stat_adjs_err[stat_abs.mask] = MDI\n stat_adjs_err = npm.masked_equal(stat_adjs_err, MDI) # should not fall over if there are no missing values\n stat_adjs[stat_abs.mask] = MDI\n stat_adjs = npm.masked_equal(stat_adjs, MDI) # should not fall over if there are no missing values\n\n #print('Completed adjustment + MissedAdjErr - check')\n #pdb.set_trace()\n\n#***********************************************************************\n# Calc combined station error - ***2 SIGMA***\n#*********************************************************************** \n \n\t# Combine errors in quadrature - should have same mask as obs\n # Also ok for Tw extremes because we have read in 2 sigma uncertainties\n station_err = npm.sqrt(stat_obs_err**2 + stat_clims_err**2 + stat_adjs_err**2) # NOT * 2 as these are already * 2 !!!!! WORKS OUT SAME AS DOIGN 1 SIGMA COMBINED * 2\n\t\n#*******************************************************************************\n# Read in monthly standard deviations from unhomogenised NetCDF files and mask to homogenised\n#*********************************************************************************\n # File has to be present or we wouldn't be working on it\n ncf = nc4.Dataset(INDIRP+StationListID[st][0:6]+'-'+StationListID[st][6:11]+'_hummonthQC.nc','r')\n # Monthly standard deviation of all hourly values going into the monthly actual value\n\n # If its a Tw extreme then use the standard deviation of the actual Tw across the month from the raw file \n if (var not in ['tw_max', 'tw_max_95p', 'tw_mean_95p', 'tw_max_ex25', 'tw_max_ex27', 'tw_max_ex29', 'tw_max_ex31', 'tw_max_ex33', 'tw_max_ex35']):\n # stat_sds = npm.array(ncf.variables[ParamDict[var][6]+'_std'][:]) # do we need to release the pointer?\n stat_sds = npm.array(ncf.variables[var+'_std'][:]) # do we need to release the pointer?\n else:\n# stat_sds = npm.array(ncf.variables['tw_std'][:]) # do we need to release the pointer?\n stat_sds = npm.array(ncf.variables['tw_max_std'][:]) # do we need to release the pointer?\n ncf.close()\n\n # Use masked arrays with new MDI\n stat_sds[stat_abs.mask] = MDI\n stat_sds = npm.masked_equal(stat_sds, MDI) # should not fall over if there are no missing values\n # Actually because these are the raw (not homogenised!) standard deviations across all hourly data going into the monthly mean\n\t# the missing data may be less than the homogenised version where periods of ambiguous adjustment are removed\n\t# So need to mask using stat_abs too - having first ensured that stat_sds is a masked array which I think it was anyway from the netCDF file.\n\t\n\t# Check whether masked values that were previously -999 are in fact set to -1e30?\n\t# Yes - this is done in WriteNetCDF\n \n# print('Check read in of monthly Std values and masking')\n# pdb.set_trace()\n\n#**********************************************************************************\n# Write out to good list\n#**********************************************************************************\n\n filee = open(OutList,'a+')\n filee.write('%11s% 9.4f% 10.4f% 7.1f %2s %-29s\\n' % (StationListID[st],StationListLat[st], StationListLon[st], StationListElev[st],StationListCID[st],StationListName[st]))\n filee.close()\n \t\n#*********************************************************************************\n# Write out to netCDF file\n#************************************************************************************\n \n\t# NOTE THAT ITS JUST ONE VARIABLE!!!\n # List data together to pass to NetCDF writer\n DataList = [stat_anoms, stat_abs, stat_sds, stat_clims, stat_clim_sds, stat_adjs, stat_adjs_err, stat_clims_err, stat_obs_err, station_err]\n\n DimList = [['time','month','characters','bound_pairs'],\n\t [nmons,12,10,2],\n \t dict([('var_type','f4'),\n \t\t ('var_name','time'),\n \t\t ('var_dims',('time',)),\n \t\t ('standard_name','time'),\n \t\t ('long_name','time'),\n \t\t ('units','days since 1973-1-1 00:00:00'),\n \t\t ('axis','T'),\n \t\t ('calendar','gregorian'),\n \t\t ('start_year',int(styear)),\n \t\t ('end_year',int(edyear)),\n \t\t ('start_month',1),\n \t\t ('end_month',12),\n \t\t ('bounds','bounds_time')]),\n \t dict([('var_type','i4'),\n \t\t ('var_name','bounds_time'),\n \t\t ('var_dims',('time','bound_pairs',)), \n \t\t ('standard_name','time'),\n \t\t ('long_name','time period boundaries')]),\n \t dict([('var_type','S1'),\n \t\t ('var_name','month'),\n \t\t ('var_dims',('month','characters',)), \n \t\t ('long_name','month of year')])]\n\n # Attribute list for variables\n AttrList = [dict([('var_type','f4'),\n\t ('var_name',var+'_anoms'),\n\t\t ('var_dims',('time',)), \n\t ('long_name',ParamDict[var][5]+' anomaly'),\n\t ('units',ParamDict[var][1])]),\n dict([('var_type','f4'),\n\t ('var_name',var+'_abs'),\n\t\t ('var_dims',('time',)), \n\t ('long_name',ParamDict[var][5]),\n\t ('units',ParamDict[var][1])]),\n dict([('var_type','f4'),\n\t ('var_name',var+'_stds'),\n\t\t ('var_dims',('time',)), \n\t ('long_name',ParamDict[var][5]+' standard deviations'),\n\t ('units',ParamDict[var][1])]),\n dict([('var_type','f4'),\n\t ('var_name',var+'_clims'),\n\t\t ('var_dims',('month',)), \n\t ('long_name',ParamDict[var][5]+' climatology '+str(MYclst)+'-'+str(MYcled)),\n\t ('units',ParamDict[var][1])]),\n dict([('var_type','f4'),\n\t ('var_name',var+'_clim_stds'),\n\t\t ('var_dims',('month',)), \n\t ('long_name',ParamDict[var][5]+' climatological standard deviation '+str(MYclst)+'-'+str(MYcled)),\n\t ('units',ParamDict[var][1])]),\n dict([('var_type','f4'),\n\t ('var_name',var+'_adjustments'),\n\t\t ('var_dims',('time',)), \n\t ('long_name',ParamDict[var][5]+' homogenisation adjustments from NCEIs PHA algorithm'),\n\t ('units',ParamDict[var][1])]),\n dict([('var_type','f4'),\n\t ('var_name',var+'_adjerr'),\n\t\t ('var_dims',('time',)), \n\t ('long_name',ParamDict[var][5]+' adjustment uncertainty estimate including missed adjustment (2 sigma)'),\n\t ('units',ParamDict[var][1])]),\n dict([('var_type','f4'),\n\t ('var_name',var+'_climerr'),\n\t\t ('var_dims',('time',)), \n\t ('long_name',ParamDict[var][5]+' climatology uncertainty estimate (2 sigma)'),\n\t ('units',ParamDict[var][1])]),\n dict([('var_type','f4'),\n\t ('var_name',var+'_obserr'),\n\t\t ('var_dims',('time',)), \n\t ('long_name',ParamDict[var][5]+' measurement uncertainty estimate (2 sigma)'),\n\t ('units',ParamDict[var][1])]),\n dict([('var_type','f4'),\n\t ('var_name',var+'_uncertainty'),\n\t\t ('var_dims',('time',)), \n\t ('long_name',ParamDict[var][5]+' combined station uncertainty estimate (2 sigma)'),\n\t ('units',ParamDict[var][1])])] \n\n GlobAttrObjectList = dict([['File_created',datetime.strftime(datetime.now(), '%Y-%m-%d %H:%M:%S')], # Is there a call for time stamping?\n\t\t\t ['Description','HadISDH monthly land surface homogenised data'],\n\t\t\t ['Title','HadISDH monthly land surface climate monitoring product'], \n\t\t\t ['Institution', AttribDict['Institution']],\n\t\t\t ['History', AttribDict['History']], \n\t\t\t ['Licence', AttribDict['NCLicence']],\n\t\t\t ['Project', AttribDict['Project']],\n\t\t\t ['Processing_level', AttribDict['Processing_level']],\n\t\t\t ['Acknowledgement', AttribDict['Acknowledgement']],\n\t\t\t ['Source', 'HadISD '+hadisdversiondots+' '+AttribDict['Source']],\n\t\t\t ['Comment',''],\n\t\t\t ['References', AttribDict['References']],\n\t\t\t ['Creator_name', AttribDict['Creator_name']],\n\t\t\t ['Creator_email', AttribDict['Creator_email']],\n\t\t\t ['Version', versiondots],\n\t\t\t ['doi',''], # This needs to be filled in\n\t\t\t ['Conventions', AttribDict['Conventions']],\n\t\t\t ['netCDF_type', AttribDict['netCDF_type']]]) \n\n # Write out monthly data to netCDH\n WriteNetCDF(OutDat+StationListID[st]+DatSuffix,styear,edyear,[MYclst,MYcled],DataList,DimList,AttrList,GlobAttrObjectList,MDI)\n\n#**********************************************************************************\n# Plot homogenisation plots\n#**********************************************************************************\n# Plot the time series of the anomalies, adjustments and individual and combined uncertainty components\n#**********************************************************************************\n # If its a Tw extreme then do not plot\n if (var not in ['tw_max', 'tw_max_95p', 'tw_mean_95p', 'tw_max_ex25', 'tw_max_ex27', 'tw_max_ex29', 'tw_max_ex31', 'tw_max_ex33', 'tw_max_ex35']):\n \n\t # Set up lists for looping through plot panels\n PlotTitles = [StationListID[st]+' Anomalies (Homogenised)', \n\t 'PHA Adjustments', \n\t\t 'Adjustment Uncertainty (2sigma)', \n\t\t 'Measurement Uncertainty (2sigma)', \n\t\t 'Climatology Uncertainty (2sigma)', \n\t\t 'Total Station Uncertainty (2sigma)']\n\t\t \n PlotVars = [stat_anoms, stat_adjs, stat_adjs_err, stat_obs_err, stat_clims_err, station_err]\n\t\n NPlots = len(PlotVars)\n\n\t # letters for plotting\n Letteree = LetterRange(0,NPlots)\n\n\t # Positioning\n xpos = []\n ypos = []\n xfat = []\n ytall = []\n totalyspace = 0.90\t# start 0.08 end 0.98\n totalxspace = 0.85\t# start 0.12 end 0.98\n \n for n in range(NPlots):\n xpos.append(0.12)\n ypos.append(0.98-((n+1)*(totalyspace/NPlots)))\n xfat.append(totalxspace)\n ytall.append(totalyspace/NPlots)\n \n # Xarray of months\n DateArr = np.array(list(np.array([[datetime(j,i,1,0,0,0) for i in np.arange(1,13)] for j in np.arange(int(styear),int(edyear)+1)]).flat))\n xtitlee = 'Years'\n \n\t # Make the plot \n plt.clf()\n f,axarr = plt.subplots(NPlots, figsize=(7,10), sharex=False)\t#6,18\n \n for pp in range(NPlots):\n \n axarr[pp].set_position([xpos[pp],ypos[pp],xfat[pp],ytall[pp]])\n axarr[pp].set_xlim([DateArr[0],DateArr[-1]])\n \n # If its not the last plot then suppress year tick labels on x axis\n if pp < NPlots-1:\n \n axarr[pp].set_xticklabels([]) \n\n # If its not the first or second plot then ensure y axis goes down to zero.\t\t\n if (pp > 1):\n \n if (np.max(PlotVars[pp]) > 0.):\n\n axarr[pp].set_ylim(0.,np.max(PlotVars[pp])*1.05)\t \t\t\n\n else:\n \n axarr[pp].set_ylim(0.,1.)\t\t \n \n #pdb.set_trace()\n# axarr[pp].plot(DateArr[PlotVars[pp] > MDI],PlotVars[pp][PlotVars[pp] > MDI],c='black',linewidth=0.5)\n axarr[pp].plot(DateArr,PlotVars[pp],c='black',linewidth=0.5)\n\n axarr[pp].annotate(Letteree[pp]+') '+PlotTitles[pp],xy=(0.03,0.03), xycoords='axes fraction',size=12)\n\n axarr[pp].set_ylabel(ParamDict[var][1],fontsize=12)\n #axarr[pp].hlines(0,DataArr[0],DataArr[-1],color='black',linewidth=0.5)\n \n axarr[NPlots-1].set_xlabel(xtitlee,fontsize=12)\n \n #plt.show()\n plt.savefig(OutPlots+StationListID[st]+'_anoms'+CLMlab+'_stationstats'+'.eps')\n plt.savefig(OutPlots+StationListID[st]+'_anoms'+CLMlab+'_stationstats'+'.png')\n plt.close()\n\n#***************************************************************************************\n# If this is the last station in the list then output counts to OUTPUTLOGFILE - shouldn't matter if we've had a restart as long as we haven't double written to the list files???\n#**************************************************************************************\n\n # Write out number of good, bad and (if they exist) supersat and subzero stations\n filee = open(OUTPUTLOG,'a+')\n moo = check_output(['wc','-l',OutList])\n filee.write('%s%s%i\\n' % (var, '_GOOD_STATIONS_AFTER_HOMOG_CONVERSION=', int(moo.decode('utf-8').split()[0])))\n moo = check_output(['wc','-l',OutBads])\n filee.write('%s%s%i\\n' % (var, '_BAD_STATIONS_AFTER_HOMOG_CONVERSION=', int(moo.decode('utf-8').split()[0])))\n if (len(glob.glob(OutFunniesT)) > 0):\n\n moo = check_output(['wc','-l',OutFunniesT])\n filee.write('%s%s%i\\n' % (var, '_SUPERSAT_STATIONS_AFTER_HOMOG_CONVERSION=',int(moo.decode('utf-8').split()[0])))\n\n if (len(glob.glob(OutFunniesZ)) > 0):\n\n moo = check_output(['wc','-l',OutFunniesZ])\n filee.write('%s%s%i\\n' % (var, '_SUBZERO_STATIONS_AFTER_HOMOG_CONVERSION=',int(moo.decode('utf-8').split()[0])))\n\n filee.close()\n \n print('All done!')\n \nif __name__ == '__main__':\n \n main(sys.argv[1:])\n\n#************************************************************************\n \n"
] | [
[
"numpy.sqrt",
"numpy.ma.std",
"numpy.ma.count",
"numpy.max",
"numpy.ma.array",
"numpy.reshape",
"numpy.arange",
"matplotlib.pyplot.close",
"numpy.float",
"numpy.ma.repeat",
"numpy.ma.sqrt",
"matplotlib.pyplot.savefig",
"numpy.genfromtxt",
"numpy.ma.masked_equal",
"numpy.append",
"numpy.ma.mean",
"numpy.array",
"matplotlib.pyplot.subplots",
"matplotlib.pyplot.clf",
"numpy.empty"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
Zacchaeus14/PyTorch-Encoding | [
"1a3a94851e05c56df7a23532e41e9ad587b9d35e"
] | [
"encoding/datasets/vizwiz.py"
] | [
"###########################################################################\n# Created by: Yuchen Wang\n# Email: [email protected]\n# Copyright (c) 2022\n###########################################################################\n\nimport json\nimport os\nfrom glob import glob\n\nimport torch\nfrom PIL import Image\n\nfrom .base import BaseDataset\n\n\nclass VIZWIZSegmentation(BaseDataset):\n BASE_DIR = 'VizWizGrounding2022'\n NUM_CLASS = 2\n def __init__(self, root=os.path.expanduser('~/.encoding/data'), split='train',\n mode=None, transform=None, target_transform=None, **kwargs):\n super(VIZWIZSegmentation, self).__init__(\n root, split, mode, transform, target_transform, **kwargs)\n # assert exists and prepare dataset automatically\n root = os.path.join(root, self.BASE_DIR)\n assert os.path.exists(root), \"Dataset folder not found!\"\n self.images, self.masks = _get_wizviz_pairs(root, split)\n self.questions = []\n with open(os.path.join(root, f'{split}_grounding.json'), 'r') as f:\n grounding = json.load(f)\n for i, img_path in enumerate(self.images):\n self.questions.append(grounding[_get_name_from_path(img_path)]['question'])\n if split != 'test':\n assert len(set([len(self.images), len(self.masks), len(self.questions)])) == 1\n if len(self.images) == 0:\n raise(RuntimeError(\"Found 0 images in subfolders of: \\\n \" + root + \"\\n\"))\n\n def __getitem__(self, index):\n img = Image.open(self.images[index]).convert('RGB')\n if self.mode == 'test':\n if self.transform is not None:\n img = self.transform(img)\n return img, os.path.basename(self.images[index])\n mask = Image.open(self.masks[index])\n # synchrosized transform\n if self.mode == 'train':\n img, mask = self._sync_transform(img, mask)\n elif self.mode == 'val':\n img, mask = self._val_sync_transform(img, mask)\n else:\n assert self.mode == 'testval'\n mask = self._mask_transform(mask)\n # general resize, normalize and toTensor\n if self.transform is not None:\n img = self.transform(img)\n if self.target_transform is not None:\n mask = self.target_transform(mask)\n mask[mask==255] = 1 # 0, 255 to 0, 1\n return img, mask, self.questions[index]\n\n def __len__(self):\n return len(self.images)\n\n @property\n def pred_offset(self):\n return 1\n\n\ndef _get_wizviz_pairs(folder, split='train'):\n def get_path_pairs(img_folder, mask_folder):\n if not mask_folder:\n return glob(os.path.join(img_folder, '*.jpg')), None\n mask_paths = glob(os.path.join(mask_folder, '*.png'))\n names = [_get_name_from_path(path) for path in mask_paths]\n names = [x.split('.')[0] for x in names]\n img_paths = [os.path.join(img_folder, f'{name}.jpg') for name in names]\n assert all(os.path.isfile(img_path) for img_path in img_paths)\n return img_paths, mask_paths\n\n if split == 'train':\n img_folder = os.path.join(folder, 'train')\n mask_folder = os.path.join(folder, 'binary_masks_png/train')\n img_paths, mask_paths = get_path_pairs(img_folder, mask_folder)\n print('len(img_paths):', len(img_paths))\n assert len(img_paths) == 6494, len(img_paths)\n elif split == 'val':\n img_folder = os.path.join(folder, 'val')\n mask_folder = os.path.join(folder, 'binary_masks_png/val')\n img_paths, mask_paths = get_path_pairs(img_folder, mask_folder)\n assert len(img_paths) == 1131, len(img_paths)\n elif split == 'trainval':\n train_img_folder = os.path.join(folder, 'train')\n train_mask_folder = os.path.join(folder, 'binary_masks_png/train')\n val_img_folder = os.path.join(folder, 'val')\n val_mask_folder = os.path.join(folder, 'binary_masks_png/val')\n train_img_paths, train_mask_paths = get_path_pairs(train_img_folder, train_mask_folder)\n val_img_paths, val_mask_paths = get_path_pairs(val_img_folder, val_mask_folder)\n img_paths = train_img_paths + val_img_paths\n mask_paths = train_mask_paths + val_mask_paths\n assert len(img_paths) == 6494 + 1131, len(img_paths)\n else:\n assert split == 'test', 'split unknown'\n img_folder = os.path.join(folder, 'test')\n img_paths, mask_paths = get_path_pairs(img_folder, None)\n assert len(img_paths) == 8000, len(img_paths)\n return img_paths, mask_paths\n\ndef _get_name_from_path(path):\n return os.path.basename(os.path.normpath(path))\n\nif __name__ == '__main__':\n import torchvision.transforms as transforms\n import matplotlib.pyplot as plt\n SPLIT = 'train'\n norm_mean= [0.5, 0.5, 0.5]\n norm_std = [0.5, 0.5, 0.5]\n train_transform = [\n transforms.ToTensor(),\n # transforms.Normalize(norm_mean, norm_std),\n ]\n train_transform = transforms.Compose(train_transform)\n kwargs = {'root': '../../../datasets/', \n 'split': SPLIT, \n 'mode': 'train', \n 'transform': train_transform, \n 'base_size': 520,\n 'crop_size': 480}\n trainset = VIZWIZSegmentation(**kwargs)\n img0, msk0, q0 = trainset[0]\n plt.imshow(img0.permute(1, 2, 0))\n print('mask contains', torch.unique(msk0))\n print('question', q0)\n plt.show()\n plt.imshow(msk0)\n plt.show()"
] | [
[
"torch.unique",
"matplotlib.pyplot.imshow",
"matplotlib.pyplot.show"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
Electronicshelf/Few-shot-regularization | [
"3fd0fef52684af77a5e574b5d61cfd8dd557b14b"
] | [
"models/resnet.py"
] | [
"import torch.nn as nn\nimport torch\nimport torch.nn.functional as F\nfrom torch.distributions import Bernoulli\n\n\ndef conv3x3(in_planes, out_planes, stride=1):\n \"\"\"3x3 convolution with padding\"\"\"\n return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,\n padding=1, bias=False)\n\n\nclass SELayer(nn.Module):\n def __init__(self, channel, reduction=16):\n super(SELayer, self).__init__()\n self.avg_pool = nn.AdaptiveAvgPool2d(1)\n self.fc = nn.Sequential(\n nn.Linear(channel, channel // reduction),\n nn.ReLU(inplace=True),\n nn.Linear(channel // reduction, channel),\n nn.Sigmoid()\n )\n\n def forward(self, x):\n b, c, _, _ = x.size()\n y = self.avg_pool(x).view(b, c)\n y = self.fc(y).view(b, c, 1, 1)\n return x * y\n\n\nclass DropBlock(nn.Module):\n def __init__(self, block_size):\n super(DropBlock, self).__init__()\n\n self.block_size = block_size\n #self.gamma = gamma\n #self.bernouli = Bernoulli(gamma)\n\n def forward(self, x, gamma):\n # shape: (bsize, channels, height, width)\n\n if self.training:\n batch_size, channels, height, width = x.shape\n \n bernoulli = Bernoulli(gamma)\n mask = bernoulli.sample((batch_size, channels, height - (self.block_size - 1), width - (self.block_size - 1))).cuda()\n block_mask = self._compute_block_mask(mask)\n countM = block_mask.size()[0] * block_mask.size()[1] * block_mask.size()[2] * block_mask.size()[3]\n count_ones = block_mask.sum()\n\n return block_mask * x * (countM / count_ones)\n else:\n return x\n\n def _compute_block_mask(self, mask):\n left_padding = int((self.block_size-1) / 2)\n right_padding = int(self.block_size / 2)\n \n batch_size, channels, height, width = mask.shape\n #print (\"mask\", mask[0][0])\n non_zero_idxs = mask.nonzero()\n nr_blocks = non_zero_idxs.shape[0]\n\n offsets = torch.stack(\n [\n torch.arange(self.block_size).view(-1, 1).expand(self.block_size, self.block_size).reshape(-1), # - left_padding,\n torch.arange(self.block_size).repeat(self.block_size), #- left_padding\n ]\n ).t().cuda()\n offsets = torch.cat((torch.zeros(self.block_size**2, 2).cuda().long(), offsets.long()), 1)\n \n if nr_blocks > 0:\n non_zero_idxs = non_zero_idxs.repeat(self.block_size ** 2, 1)\n offsets = offsets.repeat(nr_blocks, 1).view(-1, 4)\n offsets = offsets.long()\n\n block_idxs = non_zero_idxs + offsets\n #block_idxs += left_padding\n padded_mask = F.pad(mask, (left_padding, right_padding, left_padding, right_padding))\n padded_mask[block_idxs[:, 0], block_idxs[:, 1], block_idxs[:, 2], block_idxs[:, 3]] = 1.\n else:\n padded_mask = F.pad(mask, (left_padding, right_padding, left_padding, right_padding))\n \n block_mask = 1 - padded_mask#[:height, :width]\n return block_mask\n \n\nclass BasicBlock(nn.Module):\n expansion = 1\n\n def __init__(self, inplanes, planes, stride=1, downsample=None, drop_rate=0.0, drop_block=False,\n block_size=1, use_se=False):\n super(BasicBlock, self).__init__()\n self.conv1 = conv3x3(inplanes, planes)\n self.sattn = SATTN()\n self.bn1 = nn.BatchNorm2d(planes)\n self.relu = nn.LeakyReLU(0.1)\n self.conv2 = conv3x3(planes, planes)\n self.bn2 = nn.BatchNorm2d(planes)\n self.conv3 = conv3x3(planes, planes)\n self.bn3 = nn.BatchNorm2d(planes)\n self.maxpool = nn.MaxPool2d(stride)\n self.avgpool = nn.AdaptiveAvgPool2d(stride)\n self.downsample = downsample\n self.stride = stride\n self.drop_rate = drop_rate\n self.num_batches_tracked = 0\n self.drop_block = drop_block\n self.block_size = block_size\n self.DropBlock = DropBlock(block_size=self.block_size)\n self.use_se = use_se\n if self.use_se:\n self.se = SELayer(planes, 4)\n\n def forward(self, x):\n self.num_batches_tracked += 1\n\n residual = x\n\n out = self.conv1(x)\n out = self.relu(out)\n out = self.conv2(out)\n out = self.bn2(out)\n out = self.relu(out)\n\n out = self.conv3(out)\n out = self.bn3(out)\n out = self.sattn(out)\n if self.use_se:\n out = self.se(out)\n\n if self.downsample is not None:\n residual = self.downsample(x)\n out += residual\n out = self.relu(out)\n out = self.maxpool(out)\n\n if self.drop_rate > 0:\n if self.drop_block == True:\n feat_size = out.size()[2]\n keep_rate = max(1.0 - self.drop_rate / (20*2000) * (self.num_batches_tracked), 1.0 - self.drop_rate)\n gamma = (1 - keep_rate) / self.block_size**2 * feat_size**2 / (feat_size - self.block_size + 1)**2\n out = self.DropBlock(out, gamma=gamma)\n else:\n out = F.dropout(out, p=self.drop_rate, training=self.training, inplace=True)\n\n return out\n\n\nclass BasicConv(nn.Module):\n def __init__(self, in_planes, out_planes, kernel_size, stride=1, padding=0, dilation=1, groups=1, relu=True, bn=True, bias=False):\n super(BasicConv, self).__init__()\n self.out_channels = out_planes\n self.conv = nn.Conv2d(in_planes, out_planes, kernel_size=kernel_size, stride=stride, padding=padding, dilation=dilation, groups=groups, bias=bias)\n self.bn = nn.BatchNorm2d(out_planes,eps=1e-5, momentum=0.01, affine=True) if bn else None\n self.relu = nn.ReLU() if relu else None\n\n def forward(self, x):\n x = self.conv(x)\n if self.bn is not None:\n x = self.bn(x)\n if self.relu is not None:\n x = self.relu(x)\n return x\n\n\nclass ChannelPool(nn.Module):\n def forward(self, x):\n return torch.cat( (torch.max(x,1)[0].unsqueeze(1), torch.mean(x,1).unsqueeze(1)), dim=1 )\n\n\nclass SpatialGate(nn.Module):\n def __init__(self):\n super(SpatialGate, self).__init__()\n kernel_size = 7\n self.compress = ChannelPool()\n self.spatial = BasicConv(2, 1, kernel_size, stride=1, padding=(kernel_size-1) // 2, relu=False)\n def forward(self, x):\n x_compress = self.compress(x)\n x_out = self.spatial(x_compress)\n scale = F.sigmoid(x_out) # broadcasting\n return x * scale\n\nclass SATTN(nn.Module):\n def __init__(self):\n super(SATTN, self).__init__()\n self.SpatialGate = SpatialGate()\n def forward(self, x):\n x_out = self.SpatialGate(x)\n return x_out\n\nclass ResNet(nn.Module):\n\n def __init__(self, block, n_blocks, keep_prob=1.0, avg_pool=False, drop_rate=0.0,\n dropblock_size=5, num_classes=-1, use_se=False):\n super(ResNet, self).__init__()\n\n self.inplanes = 3\n self.use_se = use_se\n self.layer1 = self._make_layer(block, n_blocks[0], 64,\n stride=2, drop_rate=drop_rate)\n self.layer2 = self._make_layer(block, n_blocks[1], 160,\n stride=2, drop_rate=drop_rate)\n self.layer3 = self._make_layer(block, n_blocks[2], 320,\n stride=2, drop_rate=drop_rate, drop_block=True, block_size=dropblock_size)\n self.layer4 = self._make_layer(block, n_blocks[3], 640,\n stride=2, drop_rate=drop_rate, drop_block=True, block_size=dropblock_size)\n if avg_pool:\n # self.avgpool = nn.AvgPool2d(5, stride=1)\n self.avgpool = nn.AdaptiveAvgPool2d(1)\n self.keep_prob = keep_prob\n self.keep_avg_pool = avg_pool\n self.dropout = nn.Dropout(p=1 - self.keep_prob, inplace=False)\n self.drop_rate = drop_rate\n \n for m in self.modules():\n if isinstance(m, nn.Conv2d):\n nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='leaky_relu')\n elif isinstance(m, nn.BatchNorm2d):\n nn.init.constant_(m.weight, 1)\n nn.init.constant_(m.bias, 0)\n\n self.num_classes = num_classes\n if self.num_classes > 0:\n self.classifier = nn.Linear(640, self.num_classes)\n\n def _make_layer(self, block, n_block, planes, stride=1, drop_rate=0.0, drop_block=False, block_size=1):\n downsample = None\n if stride != 1 or self.inplanes != planes * block.expansion:\n downsample = nn.Sequential(\n nn.Conv2d(self.inplanes, planes * block.expansion,\n kernel_size=1, stride=1, bias=False),\n nn.BatchNorm2d(planes * block.expansion),\n )\n\n layers = []\n if n_block == 1:\n layer = block(self.inplanes, planes, stride, downsample, drop_rate, drop_block, block_size, self.use_se)\n else:\n layer = block(self.inplanes, planes, stride, downsample, drop_rate, self.use_se)\n layers.append(layer)\n self.inplanes = planes * block.expansion\n\n for i in range(1, n_block):\n if i == n_block - 1:\n layer = block(self.inplanes, planes, drop_rate=drop_rate, drop_block=drop_block,\n block_size=block_size, use_se=self.use_se)\n else:\n layer = block(self.inplanes, planes, drop_rate=drop_rate, use_se=self.use_se)\n layers.append(layer)\n\n return nn.Sequential(*layers)\n\n def forward(self, x, is_feat=False):\n\n x = self.layer1(x)\n f0 = x\n x = self.layer2(x)\n f1 = x\n x = self.layer3(x)\n f2 = x\n x = self.layer4(x)\n f3 = x\n\n if self.keep_avg_pool:\n x = self.avgpool(x)\n x = x.view(x.size(0), -1)\n feat = x\n\n if self.num_classes > 0:\n x = self.classifier(x)\n\n if is_feat:\n return [f0, f1, f2, f3, feat], x\n else:\n return x\n\n\ndef resnet12(keep_prob=1.0, avg_pool=False, **kwargs):\n \"\"\"Constructs a ResNet-12 model.\n \"\"\"\n model = ResNet(BasicBlock, [1, 1, 1, 1], keep_prob=keep_prob, avg_pool=avg_pool, **kwargs)\n return model\n\n\ndef resnet18(keep_prob=1.0, avg_pool=False, **kwargs):\n \"\"\"Constructs a ResNet-18 model.\n \"\"\"\n model = ResNet(BasicBlock, [1, 1, 2, 2], keep_prob=keep_prob, avg_pool=avg_pool, **kwargs)\n return model\n\n\ndef resnet24(keep_prob=1.0, avg_pool=False, **kwargs):\n \"\"\"Constructs a ResNet-24 model.\n \"\"\"\n model = ResNet(BasicBlock, [2, 2, 2, 2], keep_prob=keep_prob, avg_pool=avg_pool, **kwargs)\n return model\n\n\ndef resnet50(keep_prob=1.0, avg_pool=False, **kwargs):\n \"\"\"Constructs a ResNet-50 model.\n indeed, only (3 + 4 + 6 + 3) * 3 + 1 = 49 layers\n \"\"\"\n model = ResNet(BasicBlock, [3, 4, 6, 3], keep_prob=keep_prob, avg_pool=avg_pool, **kwargs)\n return model\n\n\ndef resnet101(keep_prob=1.0, avg_pool=False, **kwargs):\n \"\"\"Constructs a ResNet-101 model.\n indeed, only (3 + 4 + 23 + 3) * 3 + 1 = 100 layers\n \"\"\"\n model = ResNet(BasicBlock, [3, 4, 23, 3], keep_prob=keep_prob, avg_pool=avg_pool, **kwargs)\n return model\n\n\ndef seresnet12(keep_prob=1.0, avg_pool=False, **kwargs):\n \"\"\"Constructs a ResNet-12 model.\n \"\"\"\n model = ResNet(BasicBlock, [1, 1, 1, 1], keep_prob=keep_prob, avg_pool=avg_pool, use_se=True, **kwargs)\n return model\n\n\ndef seresnet18(keep_prob=1.0, avg_pool=False, **kwargs):\n \"\"\"Constructs a ResNet-18 model.\n \"\"\"\n model = ResNet(BasicBlock, [1, 1, 2, 2], keep_prob=keep_prob, avg_pool=avg_pool, use_se=True, **kwargs)\n return model\n\n\ndef seresnet24(keep_prob=1.0, avg_pool=False, **kwargs):\n \"\"\"Constructs a ResNet-24 model.\n \"\"\"\n model = ResNet(BasicBlock, [2, 2, 2, 2], keep_prob=keep_prob, avg_pool=avg_pool, use_se=True, **kwargs)\n return model\n\n\ndef seresnet50(keep_prob=1.0, avg_pool=False, **kwargs):\n \"\"\"Constructs a ResNet-50 model.\n indeed, only (3 + 4 + 6 + 3) * 3 + 1 = 49 layers\n \"\"\"\n model = ResNet(BasicBlock, [3, 4, 6, 3], keep_prob=keep_prob, avg_pool=avg_pool, use_se=True, **kwargs)\n return model\n\n\ndef seresnet101(keep_prob=1.0, avg_pool=False, **kwargs):\n \"\"\"Constructs a ResNet-101 model.\n indeed, only (3 + 4 + 23 + 3) * 3 + 1 = 100 layers\n \"\"\"\n model = ResNet(BasicBlock, [3, 4, 23, 3], keep_prob=keep_prob, avg_pool=avg_pool, use_se=True, **kwargs)\n return model\n\n\nif __name__ == '__main__':\n\n import argparse\n\n parser = argparse.ArgumentParser('argument for training')\n parser.add_argument('--model', type=str, choices=['resnet12', 'resnet18', 'resnet24', 'resnet50', 'resnet101',\n 'seresnet12', 'seresnet18', 'seresnet24', 'seresnet50',\n 'seresnet101'])\n args = parser.parse_args()\n\n model_dict = {\n 'resnet12': resnet12,\n 'resnet18': resnet18,\n 'resnet24': resnet24,\n 'resnet50': resnet50,\n 'resnet101': resnet101,\n 'seresnet12': seresnet12,\n 'seresnet18': seresnet18,\n 'seresnet24': seresnet24,\n 'seresnet50': seresnet50,\n 'seresnet101': seresnet101,\n }\n\n model = model_dict[args.model](avg_pool=True, drop_rate=0.1, dropblock_size=5, num_classes=64)\n data = torch.randn(2, 3, 84, 84)\n model = model.cuda()\n data = data.cuda()\n feat, logit = model(data, is_feat=True)\n print(feat[-1].shape)\n print(logit.shape)\n"
] | [
[
"torch.mean",
"torch.max",
"torch.nn.functional.dropout",
"torch.zeros",
"torch.nn.Dropout",
"torch.randn",
"torch.distributions.Bernoulli",
"torch.nn.Sigmoid",
"torch.nn.functional.sigmoid",
"torch.arange",
"torch.nn.functional.pad",
"torch.nn.Sequential",
"torch.nn.init.constant_",
"torch.nn.Conv2d",
"torch.nn.Linear",
"torch.nn.LeakyReLU",
"torch.nn.BatchNorm2d",
"torch.nn.MaxPool2d",
"torch.nn.AdaptiveAvgPool2d",
"torch.nn.ReLU",
"torch.nn.init.kaiming_normal_"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
isabella232/ml-capsules-inverted-attention-routing | [
"53899ae5b75b576a693a1bd79a2173ac3f1cdf1d"
] | [
"main_capsule.py"
] | [
"#\n# For licensing see accompanying LICENSE file.\n# Copyright (C) 2020 Apple Inc. All rights reserved.\n#\n'''Train CIFAR10 with PyTorch.'''\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nimport torch.nn.functional as F\nimport torch.backends.cudnn as cudnn\n\nimport torchvision\nimport torchvision.transforms as transforms\n\nimport os\nimport argparse\n\nfrom src import capsule_model\nfrom utils import progress_bar\nimport pickle\nimport json\n\nfrom datetime import datetime\n\n# +\nparser = argparse.ArgumentParser(description='Training Capsules using Inverted Dot-Product Attention Routing')\n\nparser.add_argument('--resume_dir', '-r', default='', type=str, help='dir where we resume from checkpoint')\nparser.add_argument('--num_routing', default=1, type=int, help='number of routing. Recommended: 0,1,2,3.')\nparser.add_argument('--dataset', default='CIFAR10', type=str, help='dataset. CIFAR10 or CIFAR100.')\nparser.add_argument('--backbone', default='resnet', type=str, help='type of backbone. simple or resnet')\nparser.add_argument('--num_workers', default=2, type=int, help='number of workers. 0 or 2')\nparser.add_argument('--config_path', default='./configs/full_rank_2C1F_matrix_for_iterations.json', type=str, help='path of the config')\nparser.add_argument('--debug', action='store_true',\n help='use debug mode (without saving to a directory)')\nparser.add_argument('--sequential_routing', action='store_true', help='not using concurrent_routing')\n\n\nparser.add_argument('--lr', default=0.1, type=float, help='learning rate. 0.1 for SGD')\nparser.add_argument('--dp', default=0.0, type=float, help='dropout rate')\nparser.add_argument('--weight_decay', default=5e-4, type=float, help='weight decay')\n# -\n\nargs = parser.parse_args()\nassert args.num_routing > 0\n\ndevice = 'cuda' if torch.cuda.is_available() else 'cpu'\nbest_acc = 0 # best test accuracy\nstart_epoch = 0 # start from epoch 0 or last checkpoint epoch\n\n# Data\nprint('==> Preparing data..')\nassert args.dataset == 'CIFAR10' or args.dataset == 'CIFAR100'\ntransform_train = transforms.Compose([\n transforms.RandomCrop(32, padding=4),\n transforms.RandomHorizontalFlip(),\n transforms.ToTensor(),\n transforms.Normalize((0.4914, 0.4822, 0.4465), (0.2023, 0.1994, 0.2010)),\n ])\ntransform_test = transforms.Compose([\n transforms.ToTensor(),\n transforms.Normalize((0.4914, 0.4822, 0.4465), (0.2023, 0.1994, 0.2010)),\n ])\n\ntrainset = getattr(torchvision.datasets, args.dataset)(root='../data', train=True, download=True, transform=transform_train)\ntestset = getattr(torchvision.datasets, args.dataset)(root='../data', train=False, download=True, transform=transform_test)\nnum_class = int(args.dataset.split('CIFAR')[1])\n\ntrainloader = torch.utils.data.DataLoader(trainset, batch_size=128, shuffle=True, num_workers=args.num_workers)\ntestloader = torch.utils.data.DataLoader(testset, batch_size=100, shuffle=False, num_workers=args.num_workers)\n\nprint('==> Building model..')\n# Model parameters\n\nimage_dim_size = 32\n\nwith open(args.config_path, 'rb') as file:\n params = json.load(file)\n\nnet = capsule_model.CapsModel(image_dim_size,\n params,\n args.backbone,\n args.dp,\n args.num_routing,\n sequential_routing=args.sequential_routing)\n\n# +\noptimizer = optim.SGD(net.parameters(), lr=args.lr, momentum=0.9, weight_decay=args.weight_decay)\n\nlr_decay = torch.optim.lr_scheduler.MultiStepLR(optimizer, milestones=[150, 250], gamma=0.1)\n\n\n# -\n\ndef count_parameters(model):\n for name, param in model.named_parameters():\n if param.requires_grad:\n print(name, param.numel())\n return sum(p.numel() for p in model.parameters() if p.requires_grad)\n\nprint(net)\ntotal_params = count_parameters(net)\nprint(total_params)\n\nif not os.path.isdir('results') and not args.debug:\n os.mkdir('results')\nif not args.debug:\n store_dir = os.path.join('results', datetime.today().strftime('%Y-%m-%d-%H-%M-%S'))\n os.mkdir(store_dir)\n\nnet = net.to(device)\nif device == 'cuda':\n net = torch.nn.DataParallel(net)\n cudnn.benchmark = True\n\nloss_func = nn.CrossEntropyLoss()\n\nif args.resume_dir and not args.debug:\n # Load checkpoint.\n print('==> Resuming from checkpoint..')\n checkpoint = torch.load(os.path.join(args.resume_dir, 'ckpt.pth'))\n net.load_state_dict(checkpoint['net'])\n best_acc = checkpoint['acc']\n start_epoch = checkpoint['epoch']\n\n# Training\ndef train(epoch):\n print('\\nEpoch: %d' % epoch)\n net.train()\n train_loss = 0\n correct = 0\n total = 0\n for batch_idx, (inputs, targets) in enumerate(trainloader):\n inputs = inputs.to(device)\n\n targets = targets.to(device)\n \n optimizer.zero_grad()\n \n v = net(inputs)\n \n loss = loss_func(v, targets)\n \n loss.backward()\n optimizer.step()\n\n train_loss += loss.item()\n _, predicted = v.max(dim=1)\n \n total += targets.size(0)\n \n correct += predicted.eq(targets).sum().item()\n\n progress_bar(batch_idx, len(trainloader), 'Loss: %.3f | Acc: %.3f%% (%d/%d)'\n % (train_loss/(batch_idx+1), 100.*correct/total, correct, total))\n return 100.*correct/total\n\ndef test(epoch):\n global best_acc\n net.eval()\n test_loss = 0\n correct = 0\n total = 0\n with torch.no_grad():\n for batch_idx, (inputs, targets) in enumerate(testloader):\n inputs = inputs.to(device)\n\n targets = targets.to(device)\n \n v = net(inputs)\n \n loss = loss_func(v, targets)\n \n test_loss += loss.item()\n \n _, predicted = v.max(dim=1)\n \n total += targets.size(0)\n \n correct += predicted.eq(targets).sum().item()\n\n progress_bar(batch_idx, len(testloader), 'Loss: %.3f | Acc: %.3f%% (%d/%d)'\n % (test_loss/(batch_idx+1), 100.*correct/total, correct, total))\n\n # Save checkpoint.\n acc = 100.*correct/total\n if acc > best_acc and not args.debug:\n print('Saving..')\n state = {\n 'net': net.state_dict(),\n 'acc': acc,\n 'epoch': epoch,\n }\n torch.save(state, os.path.join(store_dir, 'ckpt.pth'))\n best_acc = acc\n return 100.*correct/total\n\n# +\nresults = {\n 'total_params': total_params,\n 'args': args,\n 'params': params,\n 'train_acc': [],\n 'test_acc': [],\n}\n\ntotal_epochs = 350\n\nfor epoch in range(start_epoch, start_epoch+total_epochs):\n results['train_acc'].append(train(epoch))\n\n lr_decay.step()\n results['test_acc'].append(test(epoch))\n# -\n\nif not args.debug: \n store_file = os.path.join(store_dir, 'dataset_' + str(args.dataset) + '_num_routing_' + str(args.num_routing) + \\\n '_backbone_' + args.backbone + '.dct')\n\n pickle.dump(results, open(store_file, 'wb'))\n"
] | [
[
"torch.optim.lr_scheduler.MultiStepLR",
"torch.nn.CrossEntropyLoss",
"torch.utils.data.DataLoader",
"torch.no_grad",
"torch.cuda.is_available",
"torch.nn.DataParallel"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
mayura1996/CO3302---Automatic-Traffic-Sign-Recognition-System | [
"04463e3113c25ada68b500947bb891527e7234da"
] | [
"Source Codes/YOLOv3-OpenCV dNN.py"
] | [
"\"\"\"\nName: Mayura Manawadu - 17/ENG/072\nDetector with OpenCV dnn\n\"\"\"\n\n# Importing necessary libraries\nimport numpy as np\nimport cv2\nimport time\n\n\"\"\"\nInput video -> please rename the video file according to the input\n\"\"\"\n\nvideo = cv2.VideoCapture('videos/traffic-cars.mp4')\n\nwriter = None\nh, w = None, None\n\n\"\"\"\nLoading YOLOV3 network - Here before training the traffic signs I used this model to check the speed of detections\nTherefore I have used the COCO dataset's weights\n\"\"\"\n\nwith open('yolo-coco-data/coco.names') as f:\n labels = [line.strip() for line in f]\n\n\n\"\"\"\nLoading coco weights to the YOLOv3 Objects Detector\n\"\"\"\n\nnetwork = cv2.dnn.readNetFromDarknet('yolo-coco-data/yolov3.cfg',\n 'yolo-coco-data/yolov3.weights')\n\nall_layers = network.getLayerNames()\n\n\"\"\"\n# taking the output layers of the yolo network 82,94,106\n\"\"\"\n\n\nlayers_names_output = \\\n [all_layers[i[0] - 1] for i in network.getUnconnectedOutLayers()]\n\nprobability_minimum = 0.5\n\nthresh = 0.3\n\ncolours = np.random.randint(0, 255, size=(len(labels), 3), dtype='uint8')\n\n\"\"\"\nReading frames\n\"\"\"\nf = 0\nt = 0\n\nwhile True:\n ret, frame = video.read()\n if not ret:\n break\n # Reading dimensions of the frames\n if w is None or h is None:\n h, w = frame.shape[:2]\n blob = cv2.dnn.blobFromImage(frame, 1 / 255.0, (416, 416),\n swapRB=True, crop=False)\n\n\n # passing the blob through input layers\n network.setInput(blob)\n start = time.time()\n output_from_network = network.forward(layers_names_output)\n end = time.time()\n\n f += 1\n t += end - start\n\n boundingBoxes = []\n confidences = []\n classIndex = []\n\n # Going through output layers\n for result in output_from_network:\n # Going through all detections in the output layer\n for detected_objects in result:\n # Getting 80 classes of COCO datatset\n scores = detected_objects[5:]\n currentClass = np.argmax(scores)\n confidence_current = scores[currentClass]\n\n if confidence_current > probability_minimum:\n box_current = detected_objects[0:4] * np.array([w, h, w, h])\n x_center, y_center, box_width, box_height = box_current\n x_min = int(x_center - (box_width / 2))\n y_min = int(y_center - (box_height / 2))\n boundingBoxes.append([x_min, y_min,\n int(box_width), int(box_height)])\n confidences.append(float(confidence_current))\n classIndex.append(currentClass)\n\n results = cv2.dnn.NMSBoxes(boundingBoxes, confidences,\n probability_minimum, thresh)\n\n if len(results) > 0:\n for i in results.flatten():\n x_min, y_min = boundingBoxes[i][0], boundingBoxes[i][1]\n box_width, box_height = boundingBoxes[i][2], boundingBoxes[i][3]\n currentBBox = colours[classIndex[i]].tolist()\n cv2.rectangle(frame, (x_min, y_min),\n (x_min + box_width, y_min + box_height),\n currentBBox, 2)\n text_box_current = '{}: {:.4f}'.format(labels[int(classIndex[i])],\n confidences[i])\n cv2.putText(frame, text_box_current, (x_min, y_min - 5),\n cv2.FONT_HERSHEY_SIMPLEX, 0.5, currentBBox, 2)\n if writer is None:\n fourcc = cv2.VideoWriter_fourcc(*'mp4v')\n writer = cv2.VideoWriter('videos/result-traffic-cars.mp4', fourcc, 30,\n (frame.shape[1], frame.shape[0]), True)\n writer.write(frame)\n\n\nprint('\\nTotal number of frames', f)\nprint('Total amount of time taken {:.5f} seconds'.format(t))\nprint('FPS:', round((f / t), 1))\n\n\nvideo.release()\nwriter.release()"
] | [
[
"numpy.array",
"numpy.argmax"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
davewhipps/speechbrain | [
"3ea4d4878be74465bfbfc8c5e560bbc6417e8812"
] | [
"speechbrain/nnet/containers.py"
] | [
"\"\"\"Library for implementing cascade (sequences) of different neural modules.\n\nAuthors\n * Peter Plantinga 2020\n\"\"\"\n\nimport torch\nimport inspect\nimport logging\nimport operator\nimport functools\nfrom speechbrain.nnet.linear import Linear\nfrom speechbrain.utils.callchains import lengths_arg_exists\n\nlogger = logging.getLogger(__name__)\n\n\nclass Sequential(torch.nn.ModuleDict):\n \"\"\"A sequence of modules with potentially inferring shape on construction.\n\n If layers are passed with names, these can be referenced with dot notation.\n\n Arguments\n ---------\n input_shape : iterable\n A list or tuple of ints or None, representing the expected shape of an\n input tensor. None represents a variable-length dimension. If no\n ``input_shape`` is passed, no shape inference will be performed.\n *layers, **named_layers\n The inputs are treated as a list of layers to be\n applied in sequence. The output shape of each layer is used to\n infer the shape of the following layer. If a tuple is returned,\n only the shape of the first element is used to determine input\n shape of the next layer (e.g. RNN returns output, hidden).\n\n Example\n -------\n >>> inputs = torch.rand(10, 40, 50)\n >>> model = Sequential(input_shape=inputs.shape)\n >>> model.append(Linear, n_neurons=100, layer_name=\"layer1\")\n >>> model.append(Linear, n_neurons=200, layer_name=\"layer2\")\n >>> outputs = model(inputs)\n >>> outputs.shape\n torch.Size([10, 40, 200])\n >>> outputs = model.layer1(inputs)\n >>> outputs.shape\n torch.Size([10, 40, 100])\n \"\"\"\n\n def __init__(self, *layers, input_shape=None, **named_layers):\n super().__init__()\n\n # Make sure either layers or input_shape is passed\n if not layers and input_shape is None and not named_layers:\n raise ValueError(\"Must pass either layers or input shape\")\n\n # Keep track of what layers need \"lengths\" passed\n self.length_layers = []\n\n # Replace None dimensions with arbitrary value\n self.input_shape = input_shape\n if input_shape and None in input_shape:\n self.input_shape = list(input_shape)\n for i, dim in enumerate(self.input_shape):\n\n # To reduce size of dummy tensors, use 1 for batch dim\n if i == 0 and dim is None:\n dim = 1\n\n # Use 64 as nice round arbitrary value, big enough that\n # halving this dimension a few times doesn't reach 1\n self.input_shape[i] = dim or 64\n\n # Append non-named layers\n for layer in layers:\n self.append(layer)\n\n # Append named layers\n for name, layer in named_layers.items():\n self.append(layer, layer_name=name)\n\n def append(self, layer, *args, layer_name=None, **kwargs):\n \"\"\"Add a layer to the list of layers, inferring shape if necessary.\n\n Arguments\n ---------\n layer : A torch.nn.Module class or object\n If the layer is a class, it should accept an argument called\n ``input_shape`` which will be inferred and passed. If the layer\n is a module object, it is added as-is.\n layer_name : str\n The name of the layer, for reference. If the name is in use,\n ``_{count}`` will be appended.\n *args, **kwargs\n These are passed to the layer if it is constructed.\n \"\"\"\n\n # Compute layer_name\n if layer_name is None:\n layer_name = str(len(self))\n elif layer_name in self:\n index = 0\n while f\"{layer_name}_{index}\" in self:\n index += 1\n layer_name = f\"{layer_name}_{index}\"\n\n # Check if it needs to be constructed with input shape\n if self.input_shape:\n argspec = inspect.getfullargspec(layer)\n if \"input_shape\" in argspec.args + argspec.kwonlyargs:\n input_shape = self.get_output_shape()\n layer = layer(*args, input_shape=input_shape, **kwargs)\n\n # Finally, append the layer.\n try:\n self.add_module(layer_name, layer)\n except TypeError:\n raise ValueError(\n \"Must pass `input_shape` at initialization and use \"\n \"modules that take `input_shape` to infer shape when \"\n \"using `append()`.\"\n )\n\n def get_output_shape(self):\n \"\"\"Returns expected shape of the output.\n\n Computed by passing dummy input constructed with the\n ``self.input_shape`` attribute.\n \"\"\"\n with torch.no_grad():\n dummy_input = torch.zeros(self.input_shape)\n dummy_output = self(dummy_input)\n return dummy_output.shape\n\n def forward(self, x):\n \"\"\"Applies layers in sequence, passing only the first element of tuples.\n\n Arguments\n ---------\n x : torch.Tensor\n The input tensor to run through the network.\n \"\"\"\n for layer in self.values():\n x = layer(x)\n if isinstance(x, tuple):\n x = x[0]\n\n return x\n\n\nclass LengthsCapableSequential(Sequential):\n \"\"\"Sequential model that can take ``lengths`` in the forward method.\n\n This is useful for Sequential models that include RNNs where it is\n important to avoid padding, or for some feature normalization layers.\n\n Unfortunately, this module is not jit-able because the compiler doesn't\n know ahead of time if the length will be passed, and some layers don't\n accept the length parameter.\n \"\"\"\n\n def __init__(self, *args, **kwargs):\n # Add takes_lengths list here.\n self.takes_lengths = []\n super().__init__(*args, **kwargs)\n\n def append(self, *args, **kwargs):\n # Add lengths arg inference here.\n super().append(*args, **kwargs)\n latest_forward_method = list(self.values())[-1].forward\n self.takes_lengths.append(lengths_arg_exists(latest_forward_method))\n\n def forward(self, x, lengths=None):\n \"\"\"Applies layers in sequence, passing only the first element of tuples.\n\n In addition, forward the ``lengths`` argument to all layers that accept\n a ``lengths`` argument in their ``forward()`` method (e.g. RNNs).\n\n Arguments\n ---------\n x : torch.Tensor\n The input tensor to run through the network.\n lengths : torch.Tensor\n The relative lengths of each signal in the tensor.\n \"\"\"\n for layer, give_lengths in zip(self.values(), self.takes_lengths):\n if give_lengths:\n x = layer(x, lengths=lengths)\n else:\n x = layer(x)\n if isinstance(x, tuple):\n x = x[0]\n return x\n\n\nclass ModuleList(torch.nn.Module):\n \"\"\"This class implements a wrapper to torch.nn.ModuleList with a forward()\n method to forward all the layers sequentially.\n For some pretained model with the SpeechBrain older implementation of\n Sequential class, user can use this class to load those pretrained models\n\n Arguments\n ---------\n *layers : torch class\n Torch objects to be put in a ModuleList.\n \"\"\"\n\n def __init__(self, *layers):\n super().__init__()\n self.layers = torch.nn.ModuleList(layers)\n\n def forward(self, x):\n for layer in self.layers:\n x = layer(x)\n if isinstance(x, tuple):\n x = x[0]\n return x\n\n def append(self, module):\n self.layers.append(module)\n\n def extend(self, modules):\n self.layers.extend(modules)\n\n def insert(self, index, module):\n self.layers.insert(module)\n\n\nclass ConnectBlocks(torch.nn.Module):\n \"\"\"Connect a sequence of blocks with shortcut connections.\n\n Note: all shortcuts start from the output of the first block,\n since the first block may change the shape significantly.\n\n Arguments\n ---------\n input_shape : tuple\n The shape of the\n shortcut_type : str\n One of:\n * \"residual\" - first block output passed to final output,\n * \"dense\" - input of each block is from all previous blocks,\n * \"skip\" - output of each block is passed to final output.\n shortcut_projection : bool\n Only has an effect if `shortcut_type` is passed. Whether to add a\n linear projection layer to the shortcut connection before combining\n with the output, to handle different sizes.\n shortcut_combine_fn : str or function\n Either a pre-defined function (one of \"add\", \"sub\", \"mul\", \"div\",\n \"avg\", \"cat\") or a user-defined function that takes the shortcut\n and next input, and combines them, as well as `init_params`\n in case parameters need to be initialized inside of the function.\n\n Example\n -------\n >>> inputs = torch.rand(10, 100, 20)\n >>> model = ConnectBlocks(\n ... input_shape=inputs.shape, shortcut_projection=True\n ... )\n >>> model.append(Linear, n_neurons=10)\n >>> model.append(Linear, n_neurons=10, end_of_block=True)\n >>> model.append(Linear, n_neurons=10)\n >>> model.append(Linear, n_neurons=10, end_of_block=True)\n >>> outputs = model(inputs)\n >>> outputs.shape\n torch.Size([10, 100, 10])\n \"\"\"\n\n def __init__(\n self,\n input_shape,\n shortcut_type=\"residual\",\n shortcut_projection=False,\n shortcut_combine_fn=torch.add,\n ):\n super().__init__()\n\n self.first_input_shape = input_shape\n self.block_input_shape = input_shape\n self.new_block = True\n self.blocks = torch.nn.ModuleList()\n if shortcut_type not in [\"residual\", \"dense\", \"skip\"]:\n raise ValueError(\n \"'shortcuts' must be one of 'residual', 'dense', or 'skip'\"\n )\n self.shortcut_type = shortcut_type\n self.shortcut_projection = shortcut_projection\n if shortcut_projection:\n self.projections = torch.nn.ModuleList()\n self.shortcut_combine_fn = shortcut_combine_fn\n\n def append(self, layer, *args, **kwargs):\n \"\"\"Appends the specified module to the shortcut model.\n\n Arguments\n ---------\n layer : torch.nn.Module class\n This layer will get initialized with *args and **kwargs. Also,\n the argument ``input_shape`` will be passed if the layer takes it.\n *args, **kwargs\n Passed unchanged to the layer **EXCEPT** the kwarg ``end_of_block``\n which is used to indicate that the shortcut should be added in.\n \"\"\"\n if self.new_block:\n self.blocks.append(Sequential(input_shape=self.block_input_shape))\n self.new_block = False\n\n end_of_block = False\n if \"end_of_block\" in kwargs:\n end_of_block = kwargs[\"end_of_block\"]\n del kwargs[\"end_of_block\"]\n\n self.blocks[-1].append(layer, *args, **kwargs)\n\n # When we reach the end of the block, prepare to add shortcut\n if end_of_block:\n\n # Use dummy input to find shape of next block\n dummy_input = torch.zeros(self.block_input_shape)\n dummy_output = self.blocks[-1](dummy_input)\n\n # Initialize projection if necessary\n if self.shortcut_projection:\n projection_size = functools.reduce(\n operator.mul, dummy_output.shape[2:], 1\n )\n\n if self.shortcut_type == \"residual\":\n shape = self.first_input_shape\n dummy_input = torch.zeros(self.first_input_shape)\n else:\n shape = self.block_input_shape\n\n self.projections.append(\n Linear(\n n_neurons=projection_size,\n input_shape=shape,\n bias=False,\n combine_dims=True,\n )\n )\n\n # Prepare for next block\n self.new_block = True\n dummy_output = self._combine(dummy_input, dummy_output, -1)\n self.block_input_shape = dummy_output.shape\n\n def forward(self, x):\n \"\"\"\n Arguments\n ---------\n x : torch.Tensor\n The inputs to the replicated modules.\n \"\"\"\n shortcut = x\n\n for i, block in enumerate(self.blocks):\n x = block(x)\n\n if self.shortcut_type == \"skip\":\n shortcut = self._combine(shortcut, x, i)\n if self.shortcut_type == \"dense\":\n x = shortcut = self._combine(shortcut, x, i)\n if self.shortcut_type == \"residual\":\n x = self._combine(shortcut, x, i)\n\n if self.shortcut_type == \"skip\":\n return shortcut\n else:\n return x\n\n def _combine(self, shortcut, x, block_index=0):\n \"\"\"Handle combining shortcut with outputs.\"\"\"\n\n # Apply projection\n if self.shortcut_projection:\n shortcut = self.projections[block_index](shortcut)\n shortcut = shortcut.reshape(x.shape)\n\n return self.shortcut_combine_fn(shortcut, x)\n"
] | [
[
"torch.nn.ModuleList",
"torch.no_grad",
"torch.zeros"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
rainwoodman/h5py | [
"f9e536b4a9d96322d7e971073602c8969dbd9369"
] | [
"h5py/tests/old/test_attrs_data.py"
] | [
"# This file is part of h5py, a Python interface to the HDF5 library.\n#\n# http://www.h5py.org\n#\n# Copyright 2008-2013 Andrew Collette and contributors\n#\n# License: Standard 3-clause BSD; see \"license.txt\" for full license terms\n# and contributor agreement.\n\n\"\"\"\n Attribute data transfer testing module\n\n Covers all data read/write and type-conversion operations for attributes.\n\"\"\"\n\nfrom __future__ import absolute_import\n\nimport six\n\nimport numpy as np\n\nfrom .common import TestCase, ut\n\nimport h5py\nfrom h5py import h5a, h5s, h5t\nfrom h5py.highlevel import File\n\nclass BaseAttrs(TestCase):\n\n def setUp(self):\n self.f = File(self.mktemp(), 'w')\n \n def tearDown(self):\n if self.f:\n self.f.close()\n\nclass TestScalar(BaseAttrs):\n\n \"\"\"\n Feature: Scalar types map correctly to array scalars\n \"\"\"\n\n def test_int(self):\n \"\"\" Integers are read as correct NumPy type \"\"\"\n self.f.attrs['x'] = np.array(1, dtype=np.int8)\n out = self.f.attrs['x']\n self.assertIsInstance(out, np.int8)\n\n def test_compound(self):\n \"\"\" Compound scalars are read as numpy.void \"\"\"\n dt = np.dtype([('a','i'),('b','f')])\n data = np.array((1,4.2), dtype=dt)\n self.f.attrs['x'] = data\n out = self.f.attrs['x']\n self.assertIsInstance(out, np.void)\n self.assertEqual(out, data)\n self.assertEqual(out['b'], data['b'])\n\nclass TestArray(BaseAttrs):\n\n \"\"\"\n Feature: Non-scalar types are correctly retrieved as ndarrays\n \"\"\"\n\n def test_single(self):\n \"\"\" Single-element arrays are correctly recovered \"\"\"\n data = np.ndarray((1,), dtype='f')\n self.f.attrs['x'] = data\n out = self.f.attrs['x']\n self.assertIsInstance(out, np.ndarray)\n self.assertEqual(out.shape, (1,))\n\n def test_multi(self):\n \"\"\" Rank-1 arrays are correctly recovered \"\"\"\n data = np.ndarray((42,), dtype='f')\n data[:] = 42.0\n data[10:35] = -47.0\n self.f.attrs['x'] = data\n out = self.f.attrs['x']\n self.assertIsInstance(out, np.ndarray)\n self.assertEqual(out.shape, (42,))\n self.assertArrayEqual(out, data)\n\nclass TestTypes(BaseAttrs):\n\n \"\"\"\n Feature: All supported types can be stored in attributes\n \"\"\"\n\n def test_int(self):\n \"\"\" Storage of integer types \"\"\"\n dtypes = (np.int8, np.int16, np.int32, np.int64,\n np.uint8, np.uint16, np.uint32, np.uint64)\n for dt in dtypes:\n data = np.ndarray((1,), dtype=dt)\n data[...] = 42\n self.f.attrs['x'] = data\n out = self.f.attrs['x']\n self.assertEqual(out.dtype, dt)\n self.assertArrayEqual(out, data)\n\n def test_float(self):\n \"\"\" Storage of floating point types \"\"\"\n dtypes = tuple(np.dtype(x) for x in ('<f4','>f4','<f8','>f8'))\n \n for dt in dtypes:\n data = np.ndarray((1,), dtype=dt)\n data[...] = 42.3\n self.f.attrs['x'] = data\n out = self.f.attrs['x'] \n self.assertEqual(out.dtype, dt)\n self.assertArrayEqual(out, data)\n\n def test_complex(self):\n \"\"\" Storage of complex types \"\"\"\n dtypes = tuple(np.dtype(x) for x in ('<c8','>c8','<c16','>c16'))\n \n for dt in dtypes:\n data = np.ndarray((1,), dtype=dt)\n data[...] = -4.2j+35.9\n self.f.attrs['x'] = data\n out = self.f.attrs['x'] \n self.assertEqual(out.dtype, dt)\n self.assertArrayEqual(out, data)\n\n def test_string(self):\n \"\"\" Storage of fixed-length strings \"\"\"\n dtypes = tuple(np.dtype(x) for x in ('|S1', '|S10'))\n \n for dt in dtypes:\n data = np.ndarray((1,), dtype=dt)\n data[...] = 'h'\n self.f.attrs['x'] = data\n out = self.f.attrs['x'] \n self.assertEqual(out.dtype, dt)\n self.assertEqual(out[0], data[0])\n\n def test_bool(self):\n \"\"\" Storage of NumPy booleans \"\"\"\n \n data = np.ndarray((2,), dtype=np.bool_)\n data[...] = True, False\n self.f.attrs['x'] = data\n out = self.f.attrs['x']\n self.assertEqual(out.dtype, data.dtype)\n self.assertEqual(out[0], data[0])\n self.assertEqual(out[1], data[1])\n\n def test_vlen_string_array(self):\n \"\"\" Storage of vlen byte string arrays\"\"\"\n dt = h5py.special_dtype(vlen=bytes)\n \n data = np.ndarray((2,), dtype=dt)\n data[...] = b\"Hello\", b\"Hi there! This is HDF5!\"\n\n self.f.attrs['x'] = data\n out = self.f.attrs['x']\n self.assertEqual(out.dtype, dt)\n self.assertEqual(out[0], data[0])\n self.assertEqual(out[1], data[1])\n\n def test_string_scalar(self):\n \"\"\" Storage of variable-length byte string scalars (auto-creation) \"\"\"\n\n self.f.attrs['x'] = b'Hello'\n out = self.f.attrs['x']\n\n self.assertEqual(out,b'Hello')\n self.assertEqual(type(out), bytes)\n\n aid = h5py.h5a.open(self.f.id, b\"x\")\n tid = aid.get_type()\n self.assertEqual(type(tid), h5py.h5t.TypeStringID)\n self.assertEqual(tid.get_cset(), h5py.h5t.CSET_ASCII)\n self.assertTrue(tid.is_variable_str())\n\n def test_unicode_scalar(self):\n \"\"\" Storage of variable-length unicode strings (auto-creation) \"\"\"\n\n self.f.attrs['x'] = six.u(\"Hello\") + six.unichr(0x2340) + six.u(\"!!\")\n out = self.f.attrs['x']\n self.assertEqual(out, six.u(\"Hello\") + six.unichr(0x2340) + six.u(\"!!\"))\n self.assertEqual(type(out), six.text_type)\n\n aid = h5py.h5a.open(self.f.id, b\"x\")\n tid = aid.get_type()\n self.assertEqual(type(tid), h5py.h5t.TypeStringID)\n self.assertEqual(tid.get_cset(), h5py.h5t.CSET_UTF8)\n self.assertTrue(tid.is_variable_str())\n\n\nclass TestEmpty(BaseAttrs):\n\n def setUp(self):\n BaseAttrs.setUp(self)\n sid = h5s.create(h5s.NULL)\n tid = h5t.C_S1.copy()\n tid.set_size(10)\n aid = h5a.create(self.f.id, b'x', tid, sid)\n\n def test_read(self):\n with self.assertRaises(IOError):\n self.f.attrs['x']\n\n def test_modify(self):\n with self.assertRaises(IOError):\n self.f.attrs.modify('x', 1)\n\n def test_values(self):\n with self.assertRaises(IOError):\n # list() is for Py3 where these are iterators\n list(self.f.attrs.values())\n\n def test_items(self):\n with self.assertRaises(IOError):\n list(self.f.attrs.items())\n\n def test_itervalues(self):\n with self.assertRaises(IOError):\n list(six.itervalues(self.f.attrs))\n\n def test_iteritems(self):\n with self.assertRaises(IOError):\n list(six.iteritems(self.f.attrs))\n\n\nclass TestWriteException(BaseAttrs):\n\n \"\"\"\n Ensure failed attribute writes don't leave garbage behind.\n \"\"\"\n\n def test_write(self):\n \"\"\" ValueError on string write wipes out attribute \"\"\"\n\n s = b\"Hello\\x00\\Hello\"\n\n try:\n self.f.attrs['x'] = s\n except ValueError:\n pass\n\n with self.assertRaises(KeyError):\n self.f.attrs['x']\n\n\n\n\n\n\n\n\n\n\n\n\n"
] | [
[
"numpy.array",
"numpy.ndarray",
"numpy.dtype"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
rdadolf/torch-mlir | [
"86eb493a443ffceada475e33dcd648628b16a808"
] | [
"examples/torchscript_resnet18_all_output_types.py"
] | [
"# Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.\n# See https://llvm.org/LICENSE.txt for license information.\n# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception\n# Also available under a BSD-style license. See LICENSE.\n\nimport torch\nimport torchvision\n\nimport torch_mlir\n\nresnet18 = torchvision.models.resnet18(pretrained=True)\nresnet18.eval()\n\nmodule = torch_mlir.compile(resnet18, torch.ones(1, 3, 224, 224), output_type=torch_mlir.OutputType.TORCH)\nprint(\"TORCH OutputType\\n\", module.operation.get_asm(large_elements_limit=10))\nmodule = torch_mlir.compile(resnet18, torch.ones(1, 3, 224, 224), output_type=torch_mlir.OutputType.LINALG_ON_TENSORS)\nprint(\"LINALG_ON_TENSORS OutputType\\n\", module.operation.get_asm(large_elements_limit=10))\n# TODO: Debug why this is so slow.\nmodule = torch_mlir.compile(resnet18, torch.ones(1, 3, 224, 224), output_type=torch_mlir.OutputType.TOSA)\nprint(\"TOSA OutputType\\n\", module.operation.get_asm(large_elements_limit=10))\n"
] | [
[
"torch.ones"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
PhotonSpheres/manim | [
"7399c24b33095e29633fd75460d13eae5703cba9"
] | [
"manim/animation/transform.py"
] | [
"\"\"\"Animations transforming one mobject into another.\"\"\"\n\n__all__ = [\n \"Transform\",\n \"ReplacementTransform\",\n \"TransformFromCopy\",\n \"ClockwiseTransform\",\n \"CounterclockwiseTransform\",\n \"MoveToTarget\",\n \"ApplyMethod\",\n \"ApplyPointwiseFunction\",\n \"ApplyPointwiseFunctionToCenter\",\n \"FadeToColor\",\n \"FadeTransform\",\n \"FadeTransformPieces\",\n \"ScaleInPlace\",\n \"ShrinkToCenter\",\n \"Restore\",\n \"ApplyFunction\",\n \"ApplyMatrix\",\n \"ApplyComplexFunction\",\n \"CyclicReplace\",\n \"Swap\",\n \"TransformAnimations\",\n]\n\nimport inspect\nimport types\nfrom typing import TYPE_CHECKING, Any, Callable, Iterable, Optional, Sequence\n\nimport numpy as np\n\nfrom .. import config\nfrom ..animation.animation import Animation\nfrom ..constants import DEFAULT_POINTWISE_FUNCTION_RUN_TIME, DEGREES, ORIGIN, OUT\nfrom ..mobject.mobject import Group, Mobject\nfrom ..mobject.opengl_mobject import OpenGLGroup, OpenGLMobject\nfrom ..utils.paths import path_along_arc, path_along_circles\nfrom ..utils.rate_functions import smooth, squish_rate_func\n\nif TYPE_CHECKING:\n from ..scene.scene import Scene\n\n\nclass Transform(Animation):\n def __init__(\n self,\n mobject: Optional[Mobject],\n target_mobject: Optional[Mobject] = None,\n path_func: Optional[Callable] = None,\n path_arc: float = 0,\n path_arc_axis: np.ndarray = OUT,\n path_arc_centers: np.ndarray = None,\n replace_mobject_with_target_in_scene: bool = False,\n **kwargs,\n ) -> None:\n self.path_arc_axis: np.ndarray = path_arc_axis\n self.path_arc_centers: np.ndarray = path_arc_centers\n self.path_arc: float = path_arc\n\n if self.path_arc_centers is not None:\n self.path_func = path_along_circles(\n path_arc,\n self.path_arc_centers,\n self.path_arc_axis,\n )\n\n self.path_func: Optional[Callable] = path_func\n self.replace_mobject_with_target_in_scene: bool = (\n replace_mobject_with_target_in_scene\n )\n self.target_mobject: Mobject = (\n target_mobject if target_mobject is not None else Mobject()\n )\n super().__init__(mobject, **kwargs)\n\n @property\n def path_arc(self) -> float:\n return self._path_arc\n\n @path_arc.setter\n def path_arc(self, path_arc: float) -> None:\n self._path_arc = path_arc\n self._path_func = path_along_arc(\n arc_angle=self._path_arc,\n axis=self.path_arc_axis,\n )\n\n @property\n def path_func(\n self,\n ) -> Callable[\n [Iterable[np.ndarray], Iterable[np.ndarray], float],\n Iterable[np.ndarray],\n ]:\n return self._path_func\n\n @path_func.setter\n def path_func(\n self,\n path_func: Callable[\n [Iterable[np.ndarray], Iterable[np.ndarray], float],\n Iterable[np.ndarray],\n ],\n ) -> None:\n if path_func is not None:\n self._path_func = path_func\n\n def begin(self) -> None:\n # Use a copy of target_mobject for the align_data\n # call so that the actual target_mobject stays\n # preserved.\n self.target_mobject = self.create_target()\n self.target_copy = self.target_mobject.copy()\n # Note, this potentially changes the structure\n # of both mobject and target_mobject\n if config[\"renderer\"] == \"opengl\":\n self.mobject.align_data_and_family(self.target_copy)\n else:\n self.mobject.align_data(self.target_copy)\n super().begin()\n\n def create_target(self) -> Mobject:\n # Has no meaningful effect here, but may be useful\n # in subclasses\n return self.target_mobject\n\n def clean_up_from_scene(self, scene: \"Scene\") -> None:\n super().clean_up_from_scene(scene)\n if self.replace_mobject_with_target_in_scene:\n scene.remove(self.mobject)\n scene.add(self.target_mobject)\n\n def get_all_mobjects(self) -> Sequence[Mobject]:\n return [\n self.mobject,\n self.starting_mobject,\n self.target_mobject,\n self.target_copy,\n ]\n\n def get_all_families_zipped(self) -> Iterable[tuple]: # more precise typing?\n mobs = [\n self.mobject,\n self.starting_mobject,\n self.target_copy,\n ]\n if config[\"renderer\"] == \"opengl\":\n return zip(*(mob.get_family() for mob in mobs))\n return zip(*(mob.family_members_with_points() for mob in mobs))\n\n def interpolate_submobject(\n self,\n submobject: Mobject,\n starting_submobject: Mobject,\n target_copy: Mobject,\n alpha: float,\n ) -> \"Transform\":\n submobject.interpolate(starting_submobject, target_copy, alpha, self.path_func)\n return self\n\n\nclass ReplacementTransform(Transform):\n \"\"\"Replaces and morphs a mobject into a target mobject.\n\n Parameters\n ----------\n mobject\n The starting :class:`~.Mobject`.\n target_mobject\n The target :class:`~.Mobject`.\n kwargs\n Further keyword arguments that are passed to :class:`Transform`.\n\n Examples\n --------\n\n .. manim:: ReplacementTransformOrTransform\n :quality: low\n\n class ReplacementTransformOrTransform(Scene):\n def construct(self):\n # set up the numbers\n r_transform = VGroup(*[Integer(i) for i in range(1,4)])\n text_1 = Text(\"ReplacementTransform\", color=RED)\n r_transform.add(text_1)\n\n transform = VGroup(*[Integer(i) for i in range(4,7)])\n text_2 = Text(\"Transform\", color=BLUE)\n transform.add(text_2)\n\n ints = VGroup(r_transform, transform)\n texts = VGroup(text_1, text_2).scale(0.75)\n r_transform.arrange(direction=UP, buff=1)\n transform.arrange(direction=UP, buff=1)\n\n ints.arrange(buff=2)\n self.add(ints, texts)\n\n # The mobs replace each other and none are left behind\n self.play(ReplacementTransform(r_transform[0], r_transform[1]))\n self.play(ReplacementTransform(r_transform[1], r_transform[2]))\n\n # The mobs linger after the Transform()\n self.play(Transform(transform[0], transform[1]))\n self.play(Transform(transform[1], transform[2]))\n self.wait()\n\n \"\"\"\n\n def __init__(self, mobject: Mobject, target_mobject: Mobject, **kwargs) -> None:\n super().__init__(\n mobject, target_mobject, replace_mobject_with_target_in_scene=True, **kwargs\n )\n\n\nclass TransformFromCopy(Transform):\n \"\"\"\n Performs a reversed Transform\n \"\"\"\n\n def __init__(self, mobject: Mobject, target_mobject: Mobject, **kwargs) -> None:\n super().__init__(target_mobject, mobject, **kwargs)\n\n def interpolate(self, alpha: float) -> None:\n super().interpolate(1 - alpha)\n\n\nclass ClockwiseTransform(Transform):\n def __init__(\n self,\n mobject: Mobject,\n target_mobject: Mobject,\n path_arc: float = -np.pi,\n **kwargs,\n ) -> None:\n super().__init__(mobject, target_mobject, path_arc=path_arc, **kwargs)\n\n\nclass CounterclockwiseTransform(Transform):\n def __init__(\n self,\n mobject: Mobject,\n target_mobject: Mobject,\n path_arc: float = np.pi,\n **kwargs,\n ) -> None:\n super().__init__(mobject, target_mobject, path_arc=path_arc, **kwargs)\n\n\nclass MoveToTarget(Transform):\n def __init__(self, mobject: Mobject, **kwargs) -> None:\n self.check_validity_of_input(mobject)\n super().__init__(mobject, mobject.target, **kwargs)\n\n def check_validity_of_input(self, mobject: Mobject) -> None:\n if not hasattr(mobject, \"target\"):\n raise ValueError(\n \"MoveToTarget called on mobject\" \"without attribute 'target'\",\n )\n\n\nclass _MethodAnimation(MoveToTarget):\n def __init__(self, mobject, methods):\n self.methods = methods\n super().__init__(mobject)\n\n\nclass ApplyMethod(Transform):\n \"\"\"Animates a mobject by applying a method.\n\n Note that only the method needs to be passed to this animation,\n it is not required to pass the corresponding mobject. Furthermore,\n this animation class only works if the method returns the modified\n mobject.\n\n Parameters\n ----------\n method\n The method that will be applied in the animation.\n args\n Any positional arguments to be passed when applying the method.\n kwargs\n Any keyword arguments passed to :class:`~.Transform`.\n\n \"\"\"\n\n def __init__(\n self, method: Callable, *args, **kwargs\n ) -> None: # method typing (we want to specify Mobject method)? for args?\n self.check_validity_of_input(method)\n self.method = method\n self.method_args = args\n super().__init__(method.__self__, **kwargs)\n\n def check_validity_of_input(self, method: Callable) -> None:\n if not inspect.ismethod(method):\n raise ValueError(\n \"Whoops, looks like you accidentally invoked \"\n \"the method you want to animate\",\n )\n assert isinstance(method.__self__, (Mobject, OpenGLMobject))\n\n def create_target(self) -> Mobject:\n method = self.method\n # Make sure it's a list so that args.pop() works\n args = list(self.method_args)\n\n if len(args) > 0 and isinstance(args[-1], dict):\n method_kwargs = args.pop()\n else:\n method_kwargs = {}\n target = method.__self__.copy()\n method.__func__(target, *args, **method_kwargs)\n return target\n\n\nclass ApplyPointwiseFunction(ApplyMethod):\n \"\"\"Animation that applies a pointwise function to a mobject.\n\n Examples\n --------\n\n .. manim:: WarpSquare\n :quality: low\n\n class WarpSquare(Scene):\n def construct(self):\n square = Square()\n self.play(\n ApplyPointwiseFunction(\n lambda point: complex_to_R3(np.exp(R3_to_complex(point))), square\n )\n )\n self.wait()\n\n \"\"\"\n\n def __init__(\n self,\n function: types.MethodType,\n mobject: Mobject,\n run_time: float = DEFAULT_POINTWISE_FUNCTION_RUN_TIME,\n **kwargs,\n ) -> None:\n super().__init__(mobject.apply_function, function, run_time=run_time, **kwargs)\n\n\nclass ApplyPointwiseFunctionToCenter(ApplyPointwiseFunction):\n def __init__(self, function: types.MethodType, mobject: Mobject, **kwargs) -> None:\n self.function = function\n super().__init__(mobject.move_to, **kwargs)\n\n def begin(self) -> None:\n self.method_args = [self.function(self.mobject.get_center())]\n super().begin()\n\n\nclass FadeToColor(ApplyMethod):\n def __init__(self, mobject: Mobject, color: str, **kwargs) -> None:\n super().__init__(mobject.set_color, color, **kwargs)\n\n\nclass ScaleInPlace(ApplyMethod):\n def __init__(self, mobject: Mobject, scale_factor: float, **kwargs) -> None:\n super().__init__(mobject.scale, scale_factor, **kwargs)\n\n\nclass ShrinkToCenter(ScaleInPlace):\n def __init__(self, mobject: Mobject, **kwargs) -> None:\n super().__init__(mobject, 0, **kwargs)\n\n\nclass Restore(ApplyMethod):\n def __init__(self, mobject: Mobject, **kwargs) -> None:\n super().__init__(mobject.restore, **kwargs)\n\n\nclass ApplyFunction(Transform):\n def __init__(self, function: types.MethodType, mobject: Mobject, **kwargs) -> None:\n self.function = function\n super().__init__(mobject, **kwargs)\n\n def create_target(self) -> Any:\n target = self.function(self.mobject.copy())\n if not isinstance(target, (Mobject, OpenGLMobject)):\n raise TypeError(\n \"Functions passed to ApplyFunction must return object of type Mobject\",\n )\n return target\n\n\nclass ApplyMatrix(ApplyPointwiseFunction):\n \"\"\"Applies a matrix transform to an mobject.\n\n Parameters\n ----------\n matrix\n The transformation matrix.\n mobject\n The :class:`~.Mobject`.\n about_point\n The origin point for the transform. Defaults to ``ORIGIN``.\n kwargs\n Further keyword arguments that are passed to :class:`ApplyPointwiseFunction`.\n \"\"\"\n\n def __init__(\n self,\n matrix: np.ndarray,\n mobject: Mobject,\n about_point: np.ndarray = ORIGIN,\n **kwargs,\n ) -> None:\n matrix = self.initialize_matrix(matrix)\n\n def func(p):\n return np.dot(p - about_point, matrix.T) + about_point\n\n super().__init__(func, mobject, **kwargs)\n\n def initialize_matrix(self, matrix: np.ndarray) -> np.ndarray:\n matrix = np.array(matrix)\n if matrix.shape == (2, 2):\n new_matrix = np.identity(3)\n new_matrix[:2, :2] = matrix\n matrix = new_matrix\n elif matrix.shape != (3, 3):\n raise ValueError(\"Matrix has bad dimensions\")\n return matrix\n\n\nclass ApplyComplexFunction(ApplyMethod):\n def __init__(self, function: types.MethodType, mobject: Mobject, **kwargs) -> None:\n self.function = function\n method = mobject.apply_complex_function\n super().__init__(method, function, **kwargs)\n\n def _init_path_func(self) -> None:\n func1 = self.function(complex(1))\n self.path_arc = np.log(func1).imag\n super()._init_path_func()\n\n\n###\n\n\nclass CyclicReplace(Transform):\n def __init__(\n self, *mobjects: Mobject, path_arc: float = 90 * DEGREES, **kwargs\n ) -> None:\n self.group = Group(*mobjects)\n super().__init__(self.group, path_arc=path_arc, **kwargs)\n\n def create_target(self) -> Group:\n target = self.group.copy()\n cycled_targets = [target[-1], *target[:-1]]\n for m1, m2 in zip(cycled_targets, self.group):\n m1.move_to(m2)\n return target\n\n\nclass Swap(CyclicReplace):\n pass # Renaming, more understandable for two entries\n\n\n# TODO, this may be deprecated...worth reimplementing?\nclass TransformAnimations(Transform):\n def __init__(\n self,\n start_anim: Animation,\n end_anim: Animation,\n rate_func: Callable = squish_rate_func(smooth),\n **kwargs,\n ) -> None:\n self.start_anim = start_anim\n self.end_anim = end_anim\n if \"run_time\" in kwargs:\n self.run_time = kwargs.pop(\"run_time\")\n else:\n self.run_time = max(start_anim.run_time, end_anim.run_time)\n for anim in start_anim, end_anim:\n anim.set_run_time(self.run_time)\n if (\n start_anim.starting_mobject is not None\n and end_anim.starting_mobject is not None\n and start_anim.starting_mobject.get_num_points()\n != end_anim.starting_mobject.get_num_points()\n ):\n start_anim.starting_mobject.align_data(end_anim.starting_mobject)\n for anim in start_anim, end_anim:\n if isinstance(anim, Transform) and anim.starting_mobject is not None:\n anim.starting_mobject.align_data(anim.target_mobject)\n\n super().__init__(\n start_anim.mobject, end_anim.mobject, rate_func=rate_func, **kwargs\n )\n # Rewire starting and ending mobjects\n start_anim.mobject = self.starting_mobject\n end_anim.mobject = self.target_mobject\n\n def interpolate(self, alpha: float) -> None:\n self.start_anim.interpolate(alpha)\n self.end_anim.interpolate(alpha)\n super().interpolate(alpha)\n\n\nclass FadeTransform(Transform):\n \"\"\"Fades one mobject into another.\n\n Parameters\n ----------\n mobject\n The starting :class:`~.Mobject`.\n target_mobject\n The target :class:`~.Mobject`.\n stretch\n Controls whether the target :class:`~.Mobject` is stretched during\n the animation. Default: ``True``.\n dim_to_match\n If the target mobject is not stretched automatically, this allows\n to adjust the initial scale of the target :class:`~.Mobject` while\n it is shifted in. Setting this to 0, 1, and 2, respectively,\n matches the length of the target with the length of the starting\n :class:`~.Mobject` in x, y, and z direction, respectively.\n kwargs\n Further keyword arguments are passed to the parent class.\n\n Examples\n --------\n\n .. manim:: DifferentFadeTransforms\n\n class DifferentFadeTransforms(Scene):\n def construct(self):\n starts = [Rectangle(width=4, height=1) for _ in range(3)]\n VGroup(*starts).arrange(DOWN, buff=1).shift(3*LEFT)\n targets = [Circle(fill_opacity=1).scale(0.25) for _ in range(3)]\n VGroup(*targets).arrange(DOWN, buff=1).shift(3*RIGHT)\n\n self.play(*[FadeIn(s) for s in starts])\n self.play(\n FadeTransform(starts[0], targets[0], stretch=True),\n FadeTransform(starts[1], targets[1], stretch=False, dim_to_match=0),\n FadeTransform(starts[2], targets[2], stretch=False, dim_to_match=1)\n )\n\n self.play(*[FadeOut(mobj) for mobj in self.mobjects])\n\n \"\"\"\n\n def __init__(self, mobject, target_mobject, stretch=True, dim_to_match=1, **kwargs):\n self.to_add_on_completion = target_mobject\n self.stretch = stretch\n self.dim_to_match = dim_to_match\n mobject.save_state()\n if config[\"renderer\"] == \"opengl\":\n group = OpenGLGroup(mobject, target_mobject.copy())\n else:\n group = Group(mobject, target_mobject.copy())\n super().__init__(group, **kwargs)\n\n def begin(self):\n \"\"\"Initial setup for the animation.\n\n The mobject to which this animation is bound is a group consisting of\n both the starting and the ending mobject. At the start, the ending\n mobject replaces the starting mobject (and is completely faded). In the\n end, it is set to be the other way around.\n \"\"\"\n self.ending_mobject = self.mobject.copy()\n Animation.begin(self)\n # Both 'start' and 'end' consists of the source and target mobjects.\n # At the start, the target should be faded replacing the source,\n # and at the end it should be the other way around.\n start, end = self.starting_mobject, self.ending_mobject\n for m0, m1 in ((start[1], start[0]), (end[0], end[1])):\n self.ghost_to(m0, m1)\n\n def ghost_to(self, source, target):\n \"\"\"Replaces the source by the target and sets the opacity to 0.\"\"\"\n source.replace(target, stretch=self.stretch, dim_to_match=self.dim_to_match)\n source.set_opacity(0)\n\n def get_all_mobjects(self) -> Sequence[Mobject]:\n return [\n self.mobject,\n self.starting_mobject,\n self.ending_mobject,\n ]\n\n def get_all_families_zipped(self):\n return Animation.get_all_families_zipped(self)\n\n def clean_up_from_scene(self, scene):\n Animation.clean_up_from_scene(self, scene)\n scene.remove(self.mobject)\n self.mobject[0].restore()\n scene.add(self.to_add_on_completion)\n\n\nclass FadeTransformPieces(FadeTransform):\n \"\"\"Fades submobjects of one mobject into submobjects of another one.\n\n See also\n --------\n :class:`~.FadeTransform`\n\n Examples\n --------\n .. manim:: FadeTransformSubmobjects\n\n class FadeTransformSubmobjects(Scene):\n def construct(self):\n src = VGroup(Square(), Circle().shift(LEFT + UP))\n src.shift(3*LEFT + 2*UP)\n src_copy = src.copy().shift(4*DOWN)\n\n target = VGroup(Circle(), Triangle().shift(RIGHT + DOWN))\n target.shift(3*RIGHT + 2*UP)\n target_copy = target.copy().shift(4*DOWN)\n\n self.play(FadeIn(src), FadeIn(src_copy))\n self.play(\n FadeTransform(src, target),\n FadeTransformPieces(src_copy, target_copy)\n )\n self.play(*[FadeOut(mobj) for mobj in self.mobjects])\n\n \"\"\"\n\n def begin(self):\n self.mobject[0].align_submobjects(self.mobject[1])\n super().begin()\n\n def ghost_to(self, source, target):\n \"\"\"Replaces the source submobjects by the target submobjects and sets\n the opacity to 0.\n \"\"\"\n for sm0, sm1 in zip(source.get_family(), target.get_family()):\n super().ghost_to(sm0, sm1)\n"
] | [
[
"numpy.dot",
"numpy.log",
"numpy.array",
"numpy.identity"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
CityOfLosAngeles/planning-entitlements | [
"cf83b57063b4e55722cc640172b529611b263b3a"
] | [
"src/A4_toc_work.py"
] | [
"\"\"\"\r\nUpload TOC Tiers and TOC-eligible parcels\r\nIncluded: TOC Tiers\r\n TOC-eligible parcels for 2017 and 2019\r\n\"\"\"\r\nimport boto3\r\nimport geopandas as gpd\r\nimport intake\r\nimport numpy as np\r\nimport pandas as pd\r\nimport utils\r\n\r\nfrom datetime import datetime\r\n\r\ns3 = boto3.client('s3')\r\ncatalog = intake.open_catalog(\"./catalogs/*.yml\")\r\nbucket_name = 'city-planning-entitlements'\r\n\r\n#------------------------------------------------------------------------#\r\n## TOC Tiers shapefile\r\n#------------------------------------------------------------------------#\r\ngdf = catalog.toc_tiers.read()\r\n\r\ngdf = gdf.drop(columns = ['Shape_Leng', 'Shape_Area'])\r\ngdf.rename(columns = {'FINALTIER': 'TOC_Tier'}, inplace = True)\r\n\r\ngdf.to_file(driver = 'GeoJSON', filename = './gis/raw/TOC_Tiers.geojson')\r\ns3.upload_file('./gis/raw/TOC_Tiers.geojson', bucket_name, 'gis/raw/TOC_Tiers.geojson')\r\n\r\ntime1 = datetime.now()\r\nprint(f'Upload TOC Tiers shapefile to S3: {time1 - time0}')\r\n\r\n\r\n#------------------------------------------------------------------------#\r\n## Upload TOC-eligible parcels\r\n#------------------------------------------------------------------------#\r\n# Upload City Planning's version of TOC parcels\r\nparcels = catalog.parcels2014.read().to_crs(\"EPSG:2229\")\r\n\r\ntiers = gpd.read_file(f's3://{bucket_name}/gis/raw/TOC_Tiers.geojson')\r\n\r\ntoc_parcels = catalog.toc_parcels_raw.read()\r\n\r\ntoc_parcels = (toc_parcels[toc_parcels.BPP != \"\"][['BPP']]\r\n .rename(columns = {'BPP':'AIN'})\r\n .drop_duplicates(subset = 'AIN')\r\n )\r\n\r\n# Attach geometry\r\ntoc_parcels = pd.merge(parcels, toc_parcels, how = 'inner', validate = '1:1')\r\n\r\n# Doing a spatial join between parcels and TOC tiers is consuming, \r\n# because TOC tiers are multipolygons.\r\n# Let's use the centroid of the parcel instead and do a spatial join on that.\r\ntoc_parcels = (toc_parcels.assign(\r\n centroid = toc_parcels.geometry.centroid\r\n ).set_geometry('centroid')\r\n)\r\n\r\n# Spatial join with tiers\r\ntoc_parcels2 = gpd.sjoin(toc_parcels, tiers, how = 'left', op = 'intersects')\r\n\r\nkeep = ['AIN', 'TOC_Tier', 'geometry']\r\ntoc_parcels2 = (toc_parcels2.set_geometry('geometry')\r\n .assign(\r\n TOC_Tier = toc_parcels2.TOC_Tier.fillna(0).astype(int)\r\n )[keep]\r\n)\r\n\r\n# Zip the shapefile and upload to S3\r\nfile_name = \"TOC_Parcels\"\r\n\r\nutils.make_zipped_shapefile(toc_parcels2, f'./gis/intermediate/{file_name}')\r\ns3.upload_file(f'./gis/intermediate/{file_name}.zip', \r\n bucket_name, f'gis/intermediate/{file_name}.zip')\r\n\r\ntime2 = datetime.now()\r\nprint(f'Upload TOC eligible parcels to S3: {time2 - time1}')\r\n"
] | [
[
"pandas.merge"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [
"0.23",
"0.21",
"2.0",
"1.4",
"0.19",
"1.1",
"1.5",
"1.2",
"0.24",
"0.20",
"1.0",
"0.25",
"1.3"
],
"scipy": [],
"tensorflow": []
}
] |
nkolot/smplx | [
"c0c796feec25b7febbb826bf7819227783cf21fc"
] | [
"smplx/lbs.py"
] | [
"# -*- coding: utf-8 -*-\n\n# Max-Planck-Gesellschaft zur Förderung der Wissenschaften e.V. (MPG) is\n# holder of all proprietary rights on this computer program.\n# You can only use this computer program if you have closed\n# a license agreement with MPG or you get the right to use the computer\n# program from someone who is authorized to grant you that right.\n# Any use of the computer program without a valid license is prohibited and\n# liable to prosecution.\n#\n# Copyright©2019 Max-Planck-Gesellschaft zur Förderung\n# der Wissenschaften e.V. (MPG). acting on behalf of its Max Planck Institute\n# for Intelligent Systems. All rights reserved.\n#\n# Contact: [email protected]\n\nfrom __future__ import absolute_import\nfrom __future__ import print_function\nfrom __future__ import division\n\nimport numpy as np\n\nimport torch\nimport torch.nn.functional as F\n\nfrom .utils import rot_mat_to_euler\n\n\ndef find_dynamic_lmk_idx_and_bcoords(vertices, pose, dynamic_lmk_faces_idx,\n dynamic_lmk_b_coords,\n neck_kin_chain, dtype=torch.float32):\n ''' Compute the faces, barycentric coordinates for the dynamic landmarks\n\n\n To do so, we first compute the rotation of the neck around the y-axis\n and then use a pre-computed look-up table to find the faces and the\n barycentric coordinates that will be used.\n\n Special thanks to Soubhik Sanyal ([email protected])\n for providing the original TensorFlow implementation and for the LUT.\n\n Parameters\n ----------\n vertices: torch.tensor BxVx3, dtype = torch.float32\n The tensor of input vertices\n pose: torch.tensor Bx(Jx3), dtype = torch.float32\n The current pose of the body model\n dynamic_lmk_faces_idx: torch.tensor L, dtype = torch.long\n The look-up table from neck rotation to faces\n dynamic_lmk_b_coords: torch.tensor Lx3, dtype = torch.float32\n The look-up table from neck rotation to barycentric coordinates\n neck_kin_chain: list\n A python list that contains the indices of the joints that form the\n kinematic chain of the neck.\n dtype: torch.dtype, optional\n\n Returns\n -------\n dyn_lmk_faces_idx: torch.tensor, dtype = torch.long\n A tensor of size BxL that contains the indices of the faces that\n will be used to compute the current dynamic landmarks.\n dyn_lmk_b_coords: torch.tensor, dtype = torch.float32\n A tensor of size BxL that contains the indices of the faces that\n will be used to compute the current dynamic landmarks.\n '''\n\n batch_size = vertices.shape[0]\n\n aa_pose = torch.index_select(pose.view(batch_size, -1, 3), 1,\n neck_kin_chain)\n rot_mats = batch_rodrigues(\n aa_pose.view(-1, 3), dtype=dtype).view(batch_size, -1, 3, 3)\n\n rel_rot_mat = torch.eye(3, device=vertices.device,\n dtype=dtype).unsqueeze_(dim=0)\n for idx in range(len(neck_kin_chain)):\n rel_rot_mat = torch.bmm(rot_mats[:, idx], rel_rot_mat)\n\n y_rot_angle = torch.round(\n torch.clamp(-rot_mat_to_euler(rel_rot_mat) * 180.0 / np.pi,\n max=39)).to(dtype=torch.long)\n neg_mask = y_rot_angle.lt(0).to(dtype=torch.long)\n mask = y_rot_angle.lt(-39).to(dtype=torch.long)\n neg_vals = mask * 78 + (1 - mask) * (39 - y_rot_angle)\n y_rot_angle = (neg_mask * neg_vals +\n (1 - neg_mask) * y_rot_angle)\n\n dyn_lmk_faces_idx = torch.index_select(dynamic_lmk_faces_idx,\n 0, y_rot_angle)\n dyn_lmk_b_coords = torch.index_select(dynamic_lmk_b_coords,\n 0, y_rot_angle)\n\n return dyn_lmk_faces_idx, dyn_lmk_b_coords\n\n\ndef vertices2landmarks(vertices, faces, lmk_faces_idx, lmk_bary_coords):\n ''' Calculates landmarks by barycentric interpolation\n\n Parameters\n ----------\n vertices: torch.tensor BxVx3, dtype = torch.float32\n The tensor of input vertices\n faces: torch.tensor Fx3, dtype = torch.long\n The faces of the mesh\n lmk_faces_idx: torch.tensor L, dtype = torch.long\n The tensor with the indices of the faces used to calculate the\n landmarks.\n lmk_bary_coords: torch.tensor Lx3, dtype = torch.float32\n The tensor of barycentric coordinates that are used to interpolate\n the landmarks\n\n Returns\n -------\n landmarks: torch.tensor BxLx3, dtype = torch.float32\n The coordinates of the landmarks for each mesh in the batch\n '''\n # Extract the indices of the vertices for each face\n # BxLx3\n batch_size, num_verts = vertices.shape[:2]\n device = vertices.device\n\n lmk_faces = torch.index_select(faces, 0, lmk_faces_idx.view(-1)).view(\n batch_size, -1, 3)\n\n lmk_faces += torch.arange(\n batch_size, dtype=torch.long, device=device).view(-1, 1, 1) * num_verts\n\n lmk_vertices = vertices.view(-1, 3)[lmk_faces].view(\n batch_size, -1, 3, 3)\n\n landmarks = torch.einsum('blfi,blf->bli', [lmk_vertices, lmk_bary_coords])\n return landmarks\n\n\ndef lbs(betas, pose, v_template, shapedirs, posedirs, J_regressor, parents,\n lbs_weights, pose2rot=True, dtype=torch.float32):\n ''' Performs Linear Blend Skinning with the given shape and pose parameters\n\n Parameters\n ----------\n betas : torch.tensor BxNB\n The tensor of shape parameters\n pose : torch.tensor Bx(J + 1) * 3\n The pose parameters in axis-angle format\n v_template torch.tensor BxVx3\n The template mesh that will be deformed\n shapedirs : torch.tensor 1xNB\n The tensor of PCA shape displacements\n posedirs : torch.tensor Px(V * 3)\n The pose PCA coefficients\n J_regressor : torch.tensor JxV\n The regressor array that is used to calculate the joints from\n the position of the vertices\n parents: torch.tensor J\n The array that describes the kinematic tree for the model\n lbs_weights: torch.tensor N x V x (J + 1)\n The linear blend skinning weights that represent how much the\n rotation matrix of each part affects each vertex\n pose2rot: bool, optional\n Flag on whether to convert the input pose tensor to rotation\n matrices. The default value is True. If False, then the pose tensor\n should already contain rotation matrices and have a size of\n Bx(J + 1)x9\n dtype: torch.dtype, optional\n\n Returns\n -------\n verts: torch.tensor BxVx3\n The vertices of the mesh after applying the shape and pose\n displacements.\n joints: torch.tensor BxJx3\n The joints of the model\n '''\n\n batch_size = max(betas.shape[0], pose.shape[0])\n device = betas.device\n\n # Add shape contribution\n v_shaped = v_template + blend_shapes(betas, shapedirs)\n\n # Get the joints\n # NxJx3 array\n J = vertices2joints(J_regressor, v_shaped)\n\n # 3. Add pose blend shapes\n # N x J x 3 x 3\n ident = torch.eye(3, dtype=dtype, device=device)\n if pose2rot:\n rot_mats = batch_rodrigues(\n pose.view(-1, 3), dtype=dtype).view([batch_size, -1, 3, 3])\n\n pose_feature = (rot_mats[:, 1:, :, :] - ident).view([batch_size, -1])\n # (N x P) x (P, V * 3) -> N x V x 3\n pose_offsets = torch.matmul(pose_feature, posedirs) \\\n .view(batch_size, -1, 3)\n else:\n pose_feature = pose[:, 1:].view(batch_size, -1, 3, 3) - ident\n rot_mats = pose.view(batch_size, -1, 3, 3)\n\n pose_offsets = torch.matmul(pose_feature.view(batch_size, -1),\n posedirs).view(batch_size, -1, 3)\n\n v_posed = pose_offsets + v_shaped\n # 4. Get the global joint location\n J_transformed, A = batch_rigid_transform(rot_mats, J, parents, dtype=dtype)\n\n # 5. Do skinning:\n # W is N x V x (J + 1)\n W = lbs_weights.unsqueeze(dim=0).expand([batch_size, -1, -1])\n # (N x V x (J + 1)) x (N x (J + 1) x 16)\n num_joints = J_regressor.shape[0]\n T = torch.matmul(W, A.view(batch_size, num_joints, 16)) \\\n .view(batch_size, -1, 4, 4)\n\n homogen_coord = torch.ones([batch_size, v_posed.shape[1], 1],\n dtype=dtype, device=device)\n v_posed_homo = torch.cat([v_posed, homogen_coord], dim=2)\n v_homo = torch.matmul(T, torch.unsqueeze(v_posed_homo, dim=-1))\n\n verts = v_homo[:, :, :3, 0]\n\n return verts, J_transformed\n\n\ndef vertices2joints(J_regressor, vertices):\n ''' Calculates the 3D joint locations from the vertices\n\n Parameters\n ----------\n J_regressor : torch.tensor JxV\n The regressor array that is used to calculate the joints from the\n position of the vertices\n vertices : torch.tensor BxVx3\n The tensor of mesh vertices\n\n Returns\n -------\n torch.tensor BxJx3\n The location of the joints\n '''\n\n return torch.einsum('bik,ji->bjk', [vertices, J_regressor])\n\n\ndef blend_shapes(betas, shape_disps):\n ''' Calculates the per vertex displacement due to the blend shapes\n\n\n Parameters\n ----------\n betas : torch.tensor Bx(num_betas)\n Blend shape coefficients\n shape_disps: torch.tensor Vx3x(num_betas)\n Blend shapes\n\n Returns\n -------\n torch.tensor BxVx3\n The per-vertex displacement due to shape deformation\n '''\n\n # Displacement[b, m, k] = sum_{l} betas[b, l] * shape_disps[m, k, l]\n # i.e. Multiply each shape displacement by its corresponding beta and\n # then sum them.\n blend_shape = torch.einsum('bl,mkl->bmk', [betas, shape_disps])\n return blend_shape\n\n\ndef batch_rodrigues(rot_vecs, epsilon=1e-8, dtype=torch.float32):\n ''' Calculates the rotation matrices for a batch of rotation vectors\n Parameters\n ----------\n rot_vecs: torch.tensor Nx3\n array of N axis-angle vectors\n Returns\n -------\n R: torch.tensor Nx3x3\n The rotation matrices for the given axis-angle parameters\n '''\n\n batch_size = rot_vecs.shape[0]\n device = rot_vecs.device\n\n angle = torch.norm(rot_vecs + 1e-8, dim=1, keepdim=True)\n rot_dir = rot_vecs / angle\n\n cos = torch.unsqueeze(torch.cos(angle), dim=1)\n sin = torch.unsqueeze(torch.sin(angle), dim=1)\n\n # Bx1 arrays\n rx, ry, rz = torch.split(rot_dir, 1, dim=1)\n K = torch.zeros((batch_size, 3, 3), dtype=dtype, device=device)\n\n zeros = torch.zeros((batch_size, 1), dtype=dtype, device=device)\n K = torch.cat([zeros, -rz, ry, rz, zeros, -rx, -ry, rx, zeros], dim=1) \\\n .view((batch_size, 3, 3))\n\n ident = torch.eye(3, dtype=dtype, device=device).unsqueeze(dim=0)\n rot_mat = ident + sin * K + (1 - cos) * torch.bmm(K, K)\n return rot_mat\n\n\ndef transform_mat(R, t):\n ''' Creates a batch of transformation matrices\n Args:\n - R: Bx3x3 array of a batch of rotation matrices\n - t: Bx3x1 array of a batch of translation vectors\n Returns:\n - T: Bx4x4 Transformation matrix\n '''\n # No padding left or right, only add an extra row\n return torch.cat([F.pad(R, [0, 0, 0, 1]),\n F.pad(t, [0, 0, 0, 1], value=1)], dim=2)\n\n\ndef batch_rigid_transform(rot_mats, joints, parents, dtype=torch.float32):\n \"\"\"\n Applies a batch of rigid transformations to the joints\n\n Parameters\n ----------\n rot_mats : torch.tensor BxNx3x3\n Tensor of rotation matrices\n joints : torch.tensor BxNx3\n Locations of joints\n parents : torch.tensor BxN\n The kinematic tree of each object\n dtype : torch.dtype, optional:\n The data type of the created tensors, the default is torch.float32\n\n Returns\n -------\n posed_joints : torch.tensor BxNx3\n The locations of the joints after applying the pose rotations\n rel_transforms : torch.tensor BxNx4x4\n The relative (with respect to the root joint) rigid transformations\n for all the joints\n \"\"\"\n\n joints = torch.unsqueeze(joints, dim=-1)\n\n rel_joints = joints.clone()\n rel_joints[:, 1:] -= joints[:, parents[1:]]\n\n transforms_mat = transform_mat(\n rot_mats.view(-1, 3, 3),\n rel_joints.view(-1, 3, 1)).view(-1, joints.shape[1], 4, 4)\n\n transform_chain = [transforms_mat[:, 0]]\n for i in range(1, parents.shape[0]):\n # Subtract the joint location at the rest pose\n # No need for rotation, since it's identity when at rest\n curr_res = torch.matmul(transform_chain[parents[i]],\n transforms_mat[:, i])\n transform_chain.append(curr_res)\n\n transforms = torch.stack(transform_chain, dim=1)\n\n # The last column of the transformations contains the posed joints\n posed_joints = transforms[:, :, :3, 3]\n\n # The last column of the transformations contains the posed joints\n posed_joints = transforms[:, :, :3, 3]\n\n joints_homogen = F.pad(joints, [0, 0, 0, 1])\n\n rel_transforms = transforms - F.pad(\n torch.matmul(transforms, joints_homogen), [3, 0, 0, 0, 0, 0, 0, 0])\n\n return posed_joints, rel_transforms\n"
] | [
[
"torch.cos",
"torch.norm",
"torch.ones",
"torch.cat",
"torch.zeros",
"torch.einsum",
"torch.sin",
"torch.eye",
"torch.arange",
"torch.unsqueeze",
"torch.matmul",
"torch.bmm",
"torch.split",
"torch.stack",
"torch.index_select",
"torch.nn.functional.pad"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
ezequieljsosa/goatools | [
"3aaf4ccaa44ed254674540d73817efb0466a5cf6"
] | [
"goatools/multiple_testing.py"
] | [
"#!/usr/bin/env python\n# -*- coding: UTF-8 -*-\n\n\"\"\"\nA list of commonly used multiple correction routines\n\"\"\"\nfrom __future__ import print_function\nfrom __future__ import absolute_import\nimport sys\nimport random\nimport numpy as np\nimport collections as cx\n\n__copyright__ = \"Copyright (C) 2010-2016, H Tang et al., All rights reserved.\"\n__author__ = \"various\"\n\nclass Methods(object):\n \"\"\"Class to manage multipletest methods from both local and remote sources.\"\"\"\n\n # https://github.com/statsmodels/statsmodels/blob/master/statsmodels/stats/multitest.py\n all_methods = [\n (\"local\", (\"bonferroni\", \"sidak\", \"holm\", \"fdr\")),\n (\"statsmodels\", (\n 'bonferroni', # 0) Bonferroni one-step correction\n 'sidak', # 1) Sidak one-step correction\n 'holm-sidak', # 2) Holm-Sidak step-down method using Sidak adjustments\n 'holm', # 3) Holm step-down method using Bonferroni adjustments\n 'simes-hochberg', # 4) Simes-Hochberg step-up method (independent)\n 'hommel', # 5) Hommel closed method based on Simes tests (non-negative)\n 'fdr_bh', # 6) FDR Benjamini/Hochberg (non-negative)\n 'fdr_by', # 7) FDR Benjamini/Yekutieli (negative)\n 'fdr_tsbh', # 8) FDR 2-stage Benjamini-Hochberg (non-negative)\n 'fdr_tsbky', # 9) FDR 2-stage Benjamini-Krieger-Yekutieli (non-negative)\n 'fdr_gbs', # 10) FDR adaptive Gavrilov-Benjamini-Sarkar\n )),\n\n ]\n prefixes = {'statsmodels':'sm_'}\n NtMethodInfo = cx.namedtuple(\"NtMethodInfo\", \"source method fieldname\")\n\n def __init__(self, usr_methods=None):\n self._srcmethod2fieldname = self._init_srcmethod2fieldname()\n self.statsmodels_multicomp = None\n if usr_methods is None:\n usr_methods = ['bonferroni']\n self._init_methods(usr_methods)\n\n def _init_methods(self, usr_methods):\n \"\"\"From the methods list, set list of methods to be used during GOEA.\"\"\"\n self.methods = []\n for usr_method in usr_methods:\n self._add_method(usr_method)\n\n def _add_method(self, method, method_source=None):\n \"\"\"Determine method source if needed. Add method to list.\"\"\"\n try:\n if method_source is not None:\n self._add_method_src(method_source, method)\n else:\n self._add_method_nosrc(method)\n except Exception as inst:\n raise Exception(\"{ERRMSG}\".format(ERRMSG=inst))\n\n def _add_method_nosrc(self, usr_method):\n \"\"\"Add method source, method, and fieldname to list of methods.\"\"\"\n for method_source, available_methods in self.all_methods:\n if usr_method in available_methods:\n fieldname = self.get_fldnm_method(usr_method)\n nmtup = self.NtMethodInfo(method_source, usr_method, fieldname)\n self.methods.append(nmtup)\n return\n for src, prefix in self.prefixes.items():\n if usr_method.startswith(prefix):\n method_source = src\n method = usr_method[len(prefix):]\n nmtup = self.NtMethodInfo(method_source, method, usr_method)\n self.methods.append(nmtup)\n return\n raise self.rpt_invalid_method(usr_method)\n\n def getmsg_valid_methods(self):\n \"\"\"Return a string containing valid method names.\"\"\"\n msg = []\n msg.append(\" Available methods:\")\n for method_source, methods in self.all_methods:\n msg.append(\" {SRC}(\".format(SRC=method_source))\n for method in methods:\n attrname = self._srcmethod2fieldname[(method_source, method)]\n msg.append(\" {ATTR}\".format(ATTR=attrname))\n msg.append(\" )\")\n return \"\\n\".join(msg)\n\n def _init_srcmethod2fieldname(self):\n \"\"\"Return an OrderedDict with key, (method_src, method), and value, attrname.\"\"\"\n srcmethod_fieldname = []\n ctr = self._get_method_cnts()\n for method_source, methods in self.all_methods:\n for method in methods:\n prefix = self.prefixes.get(method_source, \"\")\n prefix = prefix if ctr[method] != 1 else \"\"\n fieldname = \"{P}{M}\".format(P=prefix, M=method.replace('-', '_'))\n srcmethod_fieldname.append(((method_source, method), fieldname))\n return cx.OrderedDict(srcmethod_fieldname)\n\n def rpt_invalid_method(self, usr_method):\n \"\"\"Report which methods are available.\"\"\"\n msgerr = \"FATAL: UNRECOGNIZED METHOD({M})\".format(M=usr_method)\n msg = [msgerr, self.getmsg_valid_methods(), msgerr]\n raise Exception(\"\\n\".join(msg))\n\n def _get_method_cnts(self):\n \"\"\"Count the number of times a method is seen.\"\"\"\n ctr = cx.Counter()\n for source_methods in self.all_methods:\n for method in source_methods[1]:\n ctr[method] += 1\n return ctr\n\n def _add_method_src(self, method_source, usr_method, fieldname=None):\n \"\"\"Add method source and method to list of methods.\"\"\"\n fieldname = self._srcmethod2fieldname.get((method_source, usr_method), None)\n if fieldname is not None:\n nmtup = self.NtMethodInfo(method_source, usr_method, fieldname)\n self.methods.append(nmtup)\n else: raise Exception(\"ERROR: FIELD({FN}) METHOD_SOURCE({MS}) AND METHOD({M})\".format(\n FN=fieldname, MS=method_source, M=usr_method))\n\n @staticmethod\n def get_fldnm_method(method):\n \"\"\"Given method and source, return fieldname for method.\"\"\"\n fieldname = method.replace('-', '_')\n return fieldname\n\n def get_statsmodels_multipletests(self):\n \"\"\"Only load statsmodels package if it is used.\"\"\"\n if self.statsmodels_multicomp is not None:\n return self.statsmodels_multicomp\n from statsmodels.sandbox.stats.multicomp import multipletests\n self.statsmodels_multicomp = multipletests\n return self.statsmodels_multicomp\n\n def __iter__(self):\n return iter(self.methods)\n\n\nclass _AbstractCorrection(object):\n \"\"\"Base class for local multiple test correction calculations.\"\"\"\n\n def __init__(self, pvals, a=.05):\n self.pvals = self.corrected_pvals = np.array(pvals)\n self.n = len(self.pvals) # number of multiple tests\n self.a = a # type-1 error cutoff for each test\n\n self.set_correction()\n # Reset all pvals > 1 to 1\n self.corrected_pvals[self.corrected_pvals > 1] = 1\n\n def set_correction(self):\n # the purpose of multiple correction is to lower the alpha\n # instead of the canonical value (like .05)\n pass\n\n\nclass Bonferroni(_AbstractCorrection):\n \"\"\"\n >>> Bonferroni([0.01, 0.01, 0.03, 0.05, 0.005], a=0.05).corrected_pvals\n array([ 0.05 , 0.05 , 0.15 , 0.25 , 0.025])\n \"\"\"\n def set_correction(self):\n \"\"\"Do Bonferroni multiple test correction on original p-values.\"\"\"\n self.corrected_pvals *= self.n\n\n\nclass Sidak(_AbstractCorrection):\n \"\"\"http://en.wikipedia.org/wiki/Bonferroni_correction\n >>> Sidak([0.01, 0.01, 0.03, 0.05, 0.005], a=0.05).corrected_pvals\n array([ 0.04898974, 0.04898974, 0.14696923, 0.24494871, 0.02449487])\n \"\"\"\n\n def set_correction(self):\n \"\"\"Do Sidak multiple test correction on original p-values.\"\"\"\n if self.n != 0:\n correction = self.a * 1. / (1 - (1 - self.a) ** (1. / self.n))\n else:\n correction = 1\n self.corrected_pvals *= correction\n\n\nclass HolmBonferroni(_AbstractCorrection):\n\n \"\"\"http://en.wikipedia.org/wiki/Holm-Bonferroni_method\n given a list of pvals, perform the Holm-Bonferroni correction\n and return the indexes from original list that are significant.\n (cant use p-value as that may be repeated.)\n >>> HolmBonferroni([0.01, 0.01, 0.03, 0.05, 0.005], a=0.05).corrected_pvals\n array([ 0.04 , 0.04 , 0.06 , 0.05 , 0.025])\n \"\"\"\n def set_correction(self):\n \"\"\"Do Holm-Bonferroni multiple test correction on original p-values.\"\"\"\n if len(self.pvals):\n idxs, correction = list(zip(*self._generate_significant()))\n idxs = list(idxs)\n self.corrected_pvals[idxs] *= correction\n\n def _generate_significant(self):\n\n pvals = self.pvals\n pvals_idxs = list(zip(pvals, list(range(len(pvals)))))\n pvals_idxs.sort()\n\n num_pvals = len(self.pvals)\n\n from itertools import groupby\n for pval, idxs in groupby(pvals_idxs, lambda x: x[0]):\n idxs = list(idxs)\n for p, i in idxs:\n if p * 1. / num_pvals < self.a:\n yield (i, num_pvals)\n num_pvals -= len(idxs)\n\n\nclass FDR(object):\n \"\"\"\n Generate a p-value distribution based on re-sampling, as described in:\n http://www.biomedcentral.com/1471-2105/6/168\n \"\"\"\n def __init__(self, p_val_distribution, results, a=.05):\n self.corrected_pvals = fdr = []\n for rec in results:\n q = (sum(1 for x in p_val_distribution if x < rec.p_uncorrected)\n * 1.0 / len(p_val_distribution))\n fdr.append(q)\n\ndef mcorrection_factory(pvals, alpha, method):\n \"\"\"Return 'multiple correction' object of requested AbstractCorrection base class.\"\"\"\n correctioncls = globals().get(method, None)\n if correctioncls is not None:\n return correctioncls(pvals, alpha)\n\n\n\n\n\ndef calc_qval(study_n, pop_n,\n pop, assoc, term_pop, obo_dag, T=500):\n \"\"\"Generate p-value distribution for FDR based on resampling.\"\"\"\n from goatools.pvalcalc import FisherFactory\n from goatools.ratio import count_terms\n print((\"Generate p-value distribution for FDR \"\n \"based on resampling (this might take a while)\"), file=sys.stderr)\n distribution = []\n calc_pvalue = FisherFactory().pval_obj.calc_pvalue\n for i in range(T):\n new_study = random.sample(pop, study_n)\n new_term_study = count_terms(new_study, assoc, obo_dag)\n\n smallest_p = 1\n for term, study_count in list(new_term_study.items()):\n pop_count = term_pop[term]\n p_uncorrected = calc_pvalue(study_count,\n study_n,\n pop_count,\n pop_n)\n if p_uncorrected < smallest_p:\n smallest_p = p_uncorrected\n\n distribution.append(smallest_p)\n if i % 10 == 0:\n print(\"Sample {0} / {1}: p-value {2}\".\\\n format(i, T, smallest_p), file=sys.stderr)\n return distribution\n\n\nif __name__ == '__main__':\n import doctest\n doctest.testmod()\n\n# Copyright (C) 2010-2016, H Tang et al., All rights reserved.\n"
] | [
[
"numpy.array"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.