repo_name
stringlengths
6
130
hexsha
list
file_path
list
code
list
apis
list
marchcarax/Portfolio-stats
[ "0c52ac18d376e1adbb226fe8c41caf9573c6c517" ]
[ "PredictiveModels/Arima_Model.py" ]
[ "import src.price_calcs\nimport src.arima_calcs\nimport pandas as pd\nimport statsmodels.api as sm\nimport matplotlib.pyplot as plt\n\ndef main():\n\n #Reads csv file and takes the data we need, in this case Adjusted Close prices\n #and divide in train and test db\n series = pd.read_csv('PredictiveModels\\\\Data\\\\MSFT.csv', header=0, index_col=0)\n #test period:\n n = 20\n arima_model(series, n)\n\ndef arima_model(series: pd.DataFrame, n: int):\n split_point = len(series) - n\n dataset, validation = series[0:split_point], series[split_point:]\n print('Dataset %d, Validation %d' % (len(dataset), len(validation)))\n dataset.to_csv('PredictiveModels\\\\Data\\\\dataset.csv', index=True)\n validation.to_csv('PredictiveModels\\\\Data\\\\validation.csv', index=True)\n \n #We will do the ARIMA tests and model with logreturns\n series_train = pd.read_csv('PredictiveModels\\\\Data\\\\dataset.csv', header=0, index_col=0)\n logreturns = src.price_calcs.price_to_logreturns(series_train)\n \n #Check stationarity test\n src.arima_calcs.check_stationarity(logreturns.values)\n #Checks best ARIMA model. Write down the results for the ARIMA Model\n bestarima = src.arima_calcs.autoarima(logreturns.values)\n\n #Arima model\n mod = sm.tsa.statespace.SARIMAX(logreturns.values,order=(int(bestarima[0]),int(bestarima[1]),int(bestarima[2])))\n results = mod.fit()\n print(results.summary())\n\n #Print Residual Stats \n residuals = pd.DataFrame(results.resid)\n src.arima_calcs.arima_graphs(residuals)\n\n #multi-step out-of-sample prediction for next n steps (days in our case)\n future_days = n * 2\n start_index = len(logreturns.values)-n\n end_index = start_index + future_days - 1\n predict = results.predict(start=start_index, end=end_index)\n\n #Validation data\n validation = pd.read_csv('PredictiveModels\\\\Data\\\\validation.csv', header=0, index_col=0)\n\n #Returns logreturns to price data\n predict_test = predict[:-n]\n initial_price = validation['Adj Close'][:-len(validation)+1]\n test_data = src.price_calcs.logreturns_to_price(initial_price, predict_test, validation)\n print(test_data)\n\n #Predict vs validation data\n src.arima_calcs.prediction_traintest_graph(test_data)\n #Forecast for next n days\n src.arima_calcs.prediction_graph(predict, validation[-n:])\n\n\nif __name__ == '__main__':\n main()" ]
[ [ "pandas.DataFrame", "pandas.read_csv" ] ]
AakashKumarNain/addons
[ "eab8deae0e6d4d33e87a748b6fa3233fd21c97cc" ]
[ "tensorflow_addons/image/transform_ops.py" ]
[ "# Copyright 2019 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"Image transform ops.\"\"\"\n\nimport tensorflow as tf\nfrom tensorflow_addons.image import utils as img_utils\nfrom tensorflow_addons.utils.types import TensorLike\nfrom tensorflow_addons.image.utils import wrap, unwrap\n\nfrom typing import Optional\n\n\n_IMAGE_DTYPES = {\n tf.dtypes.uint8,\n tf.dtypes.int32,\n tf.dtypes.int64,\n tf.dtypes.float16,\n tf.dtypes.float32,\n tf.dtypes.float64,\n}\n\n\ndef transform(\n images: TensorLike,\n transforms: TensorLike,\n interpolation: str = \"NEAREST\",\n output_shape: Optional[list] = None,\n name: Optional[str] = None,\n) -> tf.Tensor:\n \"\"\"Applies the given transform(s) to the image(s).\n\n Args:\n images: A tensor of shape (num_images, num_rows, num_columns,\n num_channels) (NHWC), (num_rows, num_columns, num_channels) (HWC), or\n (num_rows, num_columns) (HW).\n transforms: Projective transform matrix/matrices. A vector of length 8 or\n tensor of size N x 8. If one row of transforms is\n [a0, a1, a2, b0, b1, b2, c0, c1], then it maps the *output* point\n `(x, y)` to a transformed *input* point\n `(x', y') = ((a0 x + a1 y + a2) / k, (b0 x + b1 y + b2) / k)`,\n where `k = c0 x + c1 y + 1`. The transforms are *inverted* compared to\n the transform mapping input points to output points. Note that\n gradients are not backpropagated into transformation parameters.\n interpolation: Interpolation mode.\n Supported values: \"NEAREST\", \"BILINEAR\".\n output_shape: Output dimesion after the transform, [height, width].\n If None, output is the same size as input image.\n\n name: The name of the op.\n\n Returns:\n Image(s) with the same type and shape as `images`, with the given\n transform(s) applied. Transformed coordinates outside of the input image\n will be filled with zeros.\n\n Raises:\n TypeError: If `image` is an invalid type.\n ValueError: If output shape is not 1-D int32 Tensor.\n \"\"\"\n with tf.name_scope(name or \"transform\"):\n image_or_images = tf.convert_to_tensor(images, name=\"images\")\n transform_or_transforms = tf.convert_to_tensor(\n transforms, name=\"transforms\", dtype=tf.dtypes.float32\n )\n if image_or_images.dtype.base_dtype not in _IMAGE_DTYPES:\n raise TypeError(\"Invalid dtype %s.\" % image_or_images.dtype)\n images = img_utils.to_4D_image(image_or_images)\n original_ndims = img_utils.get_ndims(image_or_images)\n\n if output_shape is None:\n output_shape = tf.shape(images)[1:3]\n\n output_shape = tf.convert_to_tensor(\n output_shape, tf.dtypes.int32, name=\"output_shape\"\n )\n\n if not output_shape.get_shape().is_compatible_with([2]):\n raise ValueError(\n \"output_shape must be a 1-D Tensor of 2 elements: \"\n \"new_height, new_width\"\n )\n\n if len(transform_or_transforms.get_shape()) == 1:\n transforms = transform_or_transforms[None]\n elif transform_or_transforms.get_shape().ndims is None:\n raise ValueError(\"transforms rank must be statically known\")\n elif len(transform_or_transforms.get_shape()) == 2:\n transforms = transform_or_transforms\n else:\n transforms = transform_or_transforms\n raise ValueError(\n \"transforms should have rank 1 or 2, but got rank %d\"\n % len(transforms.get_shape())\n )\n\n output = tf.raw_ops.ImageProjectiveTransformV2(\n images=images,\n transforms=transforms,\n output_shape=output_shape,\n interpolation=interpolation.upper(),\n )\n return img_utils.from_4D_image(output, original_ndims)\n\n\ndef compose_transforms(transforms: TensorLike, name: Optional[str] = None) -> tf.Tensor:\n \"\"\"Composes the transforms tensors.\n\n Args:\n transforms: List of image projective transforms to be composed. Each\n transform is length 8 (single transform) or shape (N, 8) (batched\n transforms). The shapes of all inputs must be equal, and at least one\n input must be given.\n name: The name for the op.\n\n Returns:\n A composed transform tensor. When passed to `transform` op,\n equivalent to applying each of the given transforms to the image in\n order.\n \"\"\"\n assert transforms, \"transforms cannot be empty\"\n with tf.name_scope(name or \"compose_transforms\"):\n composed = flat_transforms_to_matrices(transforms[0])\n for tr in transforms[1:]:\n # Multiply batches of matrices.\n composed = tf.matmul(composed, flat_transforms_to_matrices(tr))\n return matrices_to_flat_transforms(composed)\n\n\ndef flat_transforms_to_matrices(\n transforms: TensorLike, name: Optional[str] = None\n) -> tf.Tensor:\n \"\"\"Converts projective transforms to affine matrices.\n\n Note that the output matrices map output coordinates to input coordinates.\n For the forward transformation matrix, call `tf.linalg.inv` on the result.\n\n Args:\n transforms: Vector of length 8, or batches of transforms with shape\n `(N, 8)`.\n name: The name for the op.\n\n Returns:\n 3D tensor of matrices with shape `(N, 3, 3)`. The output matrices map the\n *output coordinates* (in homogeneous coordinates) of each transform to\n the corresponding *input coordinates*.\n\n Raises:\n ValueError: If `transforms` have an invalid shape.\n \"\"\"\n with tf.name_scope(name or \"flat_transforms_to_matrices\"):\n transforms = tf.convert_to_tensor(transforms, name=\"transforms\")\n if transforms.shape.ndims not in (1, 2):\n raise ValueError(\"Transforms should be 1D or 2D, got: %s\" % transforms)\n # Make the transform(s) 2D in case the input is a single transform.\n transforms = tf.reshape(transforms, tf.constant([-1, 8]))\n num_transforms = tf.shape(transforms)[0]\n # Add a column of ones for the implicit last entry in the matrix.\n return tf.reshape(\n tf.concat([transforms, tf.ones([num_transforms, 1])], axis=1),\n tf.constant([-1, 3, 3]),\n )\n\n\ndef matrices_to_flat_transforms(\n transform_matrices: TensorLike, name: Optional[str] = None\n) -> tf.Tensor:\n \"\"\"Converts affine matrices to projective transforms.\n\n Note that we expect matrices that map output coordinates to input\n coordinates. To convert forward transformation matrices,\n call `tf.linalg.inv` on the matrices and use the result here.\n\n Args:\n transform_matrices: One or more affine transformation matrices, for the\n reverse transformation in homogeneous coordinates. Shape `(3, 3)` or\n `(N, 3, 3)`.\n name: The name for the op.\n\n Returns:\n 2D tensor of flat transforms with shape `(N, 8)`, which may be passed\n into `transform` op.\n\n Raises:\n ValueError: If `transform_matrices` have an invalid shape.\n \"\"\"\n with tf.name_scope(name or \"matrices_to_flat_transforms\"):\n transform_matrices = tf.convert_to_tensor(\n transform_matrices, name=\"transform_matrices\"\n )\n if transform_matrices.shape.ndims not in (2, 3):\n raise ValueError(\n \"Matrices should be 2D or 3D, got: %s\" % transform_matrices\n )\n # Flatten each matrix.\n transforms = tf.reshape(transform_matrices, tf.constant([-1, 9]))\n # Divide each matrix by the last entry (normally 1).\n transforms /= transforms[:, 8:9]\n return transforms[:, :8]\n\n\ndef angles_to_projective_transforms(\n angles: TensorLike,\n image_height: TensorLike,\n image_width: TensorLike,\n name: Optional[str] = None,\n) -> tf.Tensor:\n \"\"\"Returns projective transform(s) for the given angle(s).\n\n Args:\n angles: A scalar angle to rotate all images by, or (for batches of\n images) a vector with an angle to rotate each image in the batch. The\n rank must be statically known (the shape is not `TensorShape(None)`.\n image_height: Height of the image(s) to be transformed.\n image_width: Width of the image(s) to be transformed.\n\n Returns:\n A tensor of shape (num_images, 8). Projective transforms which can be\n given to `transform` op.\n \"\"\"\n with tf.name_scope(name or \"angles_to_projective_transforms\"):\n angle_or_angles = tf.convert_to_tensor(\n angles, name=\"angles\", dtype=tf.dtypes.float32\n )\n if len(angle_or_angles.get_shape()) == 0:\n angles = angle_or_angles[None]\n elif len(angle_or_angles.get_shape()) == 1:\n angles = angle_or_angles\n else:\n raise ValueError(\"angles should have rank 0 or 1.\")\n cos_angles = tf.math.cos(angles)\n sin_angles = tf.math.sin(angles)\n x_offset = (\n (image_width - 1)\n - (cos_angles * (image_width - 1) - sin_angles * (image_height - 1))\n ) / 2.0\n y_offset = (\n (image_height - 1)\n - (sin_angles * (image_width - 1) + cos_angles * (image_height - 1))\n ) / 2.0\n num_angles = tf.shape(angles)[0]\n return tf.concat(\n values=[\n cos_angles[:, None],\n -sin_angles[:, None],\n x_offset[:, None],\n sin_angles[:, None],\n cos_angles[:, None],\n y_offset[:, None],\n tf.zeros((num_angles, 2), tf.dtypes.float32),\n ],\n axis=1,\n )\n\n\ndef rotate(\n images: TensorLike,\n angles: TensorLike,\n interpolation: str = \"NEAREST\",\n name: Optional[str] = None,\n) -> tf.Tensor:\n \"\"\"Rotate image(s) counterclockwise by the passed angle(s) in radians.\n\n Args:\n images: A tensor of shape\n `(num_images, num_rows, num_columns, num_channels)`\n (NHWC), `(num_rows, num_columns, num_channels)` (HWC), or\n `(num_rows, num_columns)` (HW).\n angles: A scalar angle to rotate all images by, or (if `images` has rank 4)\n a vector of length num_images, with an angle for each image in the\n batch.\n interpolation: Interpolation mode. Supported values: \"NEAREST\",\n \"BILINEAR\".\n name: The name of the op.\n\n Returns:\n Image(s) with the same type and shape as `images`, rotated by the given\n angle(s). Empty space due to the rotation will be filled with zeros.\n\n Raises:\n TypeError: If `images` is an invalid type.\n \"\"\"\n with tf.name_scope(name or \"rotate\"):\n image_or_images = tf.convert_to_tensor(images)\n if image_or_images.dtype.base_dtype not in _IMAGE_DTYPES:\n raise TypeError(\"Invalid dtype %s.\" % image_or_images.dtype)\n images = img_utils.to_4D_image(image_or_images)\n original_ndims = img_utils.get_ndims(image_or_images)\n\n image_height = tf.cast(tf.shape(images)[1], tf.dtypes.float32)[None]\n image_width = tf.cast(tf.shape(images)[2], tf.dtypes.float32)[None]\n output = transform(\n images,\n angles_to_projective_transforms(angles, image_height, image_width),\n interpolation=interpolation,\n )\n return img_utils.from_4D_image(output, original_ndims)\n\n\ndef shear_x(image: TensorLike, level: float, replace: int) -> TensorLike:\n \"\"\"Perform shear operation on an image (x-axis).\n\n Args:\n image: A 3D image Tensor.\n level: A float denoting shear element along y-axis\n replace: A one or three value 1D tensor to fill empty pixels.\n Returns:\n Transformed image along X or Y axis, with space outside image\n filled with replace.\n \"\"\"\n # Shear parallel to x axis is a projective transform\n # with a matrix form of:\n # [1 level\n # 0 1].\n image = transform(wrap(image), [1.0, level, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0])\n return unwrap(image, replace)\n\n\ndef shear_y(image: TensorLike, level: float, replace: int) -> TensorLike:\n \"\"\"Perform shear operation on an image (y-axis).\n\n Args:\n image: A 3D image `Tensor`.\n level: A float denoting shear element along x-axis\n replace: A one or three value 1D tensor to fill empty pixels.\n Returns:\n Transformed image along X or Y axis, with space outside image\n filled with replace.\n \"\"\"\n # Shear parallel to y axis is a projective transform\n # with a matrix form of:\n # [1 0\n # level 1].\n image = transform(wrap(image), [1.0, 0.0, 0.0, level, 1.0, 0.0, 0.0, 0.0])\n return unwrap(image, replace)\n" ]
[ [ "tensorflow.convert_to_tensor", "tensorflow.shape", "tensorflow.zeros", "tensorflow.ones", "tensorflow.constant", "tensorflow.math.sin", "tensorflow.name_scope", "tensorflow.math.cos" ] ]
yizt/crnn.pytorch
[ "2f626841f35c8f69a23518ee2496554cac080cff" ]
[ "crnn.py" ]
[ "# -*- coding: utf-8 -*-\n\"\"\"\n @File : crnn.py\n @Time : 2019/12/2 下午8:21\n @Author : yizuotian\n @Description :\n\"\"\"\n\nfrom collections import OrderedDict\n\nimport torch\nfrom torch import nn\n\n\nclass CRNN(nn.Module):\n def __init__(self, num_classes, **kwargs):\n super(CRNN, self).__init__(**kwargs)\n self.cnn = nn.Sequential(OrderedDict([\n ('conv_block_1', _ConvBlock(1, 64)), # [B,64,W,32]\n ('max_pool_1', nn.MaxPool2d(2, 2)), # [B,64,W/2,16]\n\n ('conv_block_2', _ConvBlock(64, 128)), # [B,128,W/2,16]\n ('max_pool_2', nn.MaxPool2d(2, 2)), # [B,128,W/4,8]\n\n ('conv_block_3_1', _ConvBlock(128, 256)), # [B,256,W/4,8]\n ('conv_block_3_2', _ConvBlock(256, 256)), # [B,256,W/4,8]\n ('max_pool_3', nn.MaxPool2d((2, 2), (1, 2))), # [B,256,W/4,4]\n\n ('conv_block_4_1', _ConvBlock(256, 512, bn=True)), # [B,512,W/4,4]\n ('conv_block_4_2', _ConvBlock(512, 512, bn=True)), # [B,512,W/4,4]\n ('max_pool_4', nn.MaxPool2d((2, 2), (1, 2))), # [B,512,W/4,2]\n\n ('conv_block_5', _ConvBlock(512, 512, kernel_size=2, padding=0)) # [B,512,W/4,1]\n ]))\n\n self.rnn1 = nn.GRU(512, 256, batch_first=True, bidirectional=True)\n self.rnn2 = nn.GRU(512, 256, batch_first=True, bidirectional=True)\n self.transcript = nn.Linear(512, num_classes)\n\n def forward(self, x):\n \"\"\"\n\n :param x: [B, 1, W, 32]\n :return: [B, W,num_classes]\n \"\"\"\n x = self.cnn(x) # [B,512,W/16,1]\n x = torch.squeeze(x, 3) # [B,512,W]\n x = x.permute([0, 2, 1]) # [B,W,512]\n x, h1 = self.rnn1(x)\n x, h2 = self.rnn2(x, h1)\n x = self.transcript(x)\n return x\n\n\nclass CRNNV(nn.Module):\n \"\"\"\n 垂直版CRNN,不同于水平版下采样4倍,下采样16倍\n \"\"\"\n\n def __init__(self, num_classes, **kwargs):\n super(CRNNV, self).__init__(**kwargs)\n self.cnn = nn.Sequential(OrderedDict([\n ('conv_block_1', _ConvBlock(1, 64)), # [B,64,W,32]\n ('max_pool_1', nn.MaxPool2d(2, 2)), # [B,64,W/2,16]\n\n ('conv_block_2', _ConvBlock(64, 128)), # [B,128,W/2,16]\n ('max_pool_2', nn.MaxPool2d(2, 2)), # [B,128,W/4,8]\n\n ('conv_block_3_1', _ConvBlock(128, 256)), # [B,256,W/4,8]\n ('conv_block_3_2', _ConvBlock(256, 256)), # [B,256,W/4,8]\n ('max_pool_3', nn.MaxPool2d((1, 2), 2)), # [B,256,W/8,4]\n\n ('conv_block_4_1', _ConvBlock(256, 512, bn=True)), # [B,512,W/8,4]\n ('conv_block_4_2', _ConvBlock(512, 512, bn=True)), # [B,512,W/8,4]\n ('max_pool_4', nn.MaxPool2d((1, 2), 2)), # [B,512,W/16,2]\n\n ('conv_block_5', _ConvBlock(512, 512, kernel_size=2, padding=0)) # [B,512,W/4,1]\n ]))\n\n self.rnn1 = nn.GRU(512, 256, batch_first=True, bidirectional=True)\n self.rnn2 = nn.GRU(512, 256, batch_first=True, bidirectional=True)\n self.transcript = nn.Linear(512, num_classes)\n\n def forward(self, x):\n \"\"\"\n\n :param x: [B, 1, W, 32]\n :return: [B, W,num_classes]\n \"\"\"\n x = self.cnn(x) # [B,512,W/16,1]\n x = torch.squeeze(x, 3) # [B,512,W]\n x = x.permute([0, 2, 1]) # [B,W,512]\n x, h1 = self.rnn1(x)\n x, h2 = self.rnn2(x, h1)\n x = self.transcript(x)\n return x\n\n\nclass _ConvBlock(nn.Sequential):\n def __init__(self, in_channels, out_channels, kernel_size=3, stride=1, padding=1, bn=False):\n super(_ConvBlock, self).__init__()\n self.add_module('conv', nn.Conv2d(in_channels, out_channels, kernel_size, stride, padding))\n if bn:\n self.add_module('norm', nn.BatchNorm2d(out_channels))\n self.add_module('relu', nn.ReLU(inplace=True))\n\n\nif __name__ == '__main__':\n import torchsummary\n\n net = CRNN(num_classes=1000)\n torchsummary.summary(net, input_size=(1, 512, 32), batch_size=1)\n" ]
[ [ "torch.nn.Linear", "torch.nn.GRU", "torch.nn.MaxPool2d", "torch.nn.BatchNorm2d", "torch.nn.ReLU", "torch.nn.Conv2d", "torch.squeeze" ] ]
espoirMur/medical-image-captionning
[ "05d23a811d800fa73ef5196e649323d060ac27a1" ]
[ "src/models/train_model.py" ]
[ "import time\nimport json\nimport math\nimport mlflow\nfrom numpy import dtype, hypot\nimport pandas as pd\nfrom pathlib import Path\nimport torch.backends.cudnn as cudnn\nimport torch.optim\nimport torch.utils.data\nimport numpy as np\nimport torchvision.transforms as transforms\nfrom torch import embedding, nn\nfrom torch.nn.utils.rnn import pack_padded_sequence, pad_packed_sequence\nfrom src.data.dataloader import ImageCaptionDataset\nfrom src.utils import (save_checkpoint,\n adjust_learning_rate,\n AverageMeter,\n clip_gradient,\n get_text_for_batch,\n log_scalar,\n BaseLogger)\nfrom nltk.translate.bleu_score import corpus_bleu\nfrom src.models.models import EncoderCNN, DecoderRNN\nfrom torch.utils.data import DataLoader\nfrom torchtext.data.utils import get_tokenizer\nfrom torchtext.vocab import build_vocab_from_iterator\nfrom torchtext.transforms import Sequential, AddToken, Truncate, ToTensor, VocabTransform\nfrom nltk.translate.bleu_score import corpus_bleu\n\n\n# Data parameters\ndata_path = Path(__file__).resolve().parents[2].joinpath(\"data\", \"raw\")\ncaption_prediction_path = data_path.joinpath(\"caption-prediction\")\n\n# Model parameters\nembedding_size = 512 # dimension of word embeddings\nhidden_size = 512\nattention_dim = 512 # dimension of attention linear layers\ndecoder_dim = 512 # dimension of decoder RNN\ndropout = 0.5\ndecoder_layers = 8\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\") # sets device for model and PyTorch tensors\ncudnn.benchmark = True # set to true only if inputs to model are fixed size; otherwise lot of computational overhead\n\n# Training parameters\nstart_epoch = 0\nepochs = 30 # number of epochs to train for (if early stopping is not triggered)\nepochs_since_improvement = 0 # keeps track of number of epochs since there's been an improvement in validation BLEU\nbatch_size = 64\nencoder_lr = 1e-4 # learning rate for encoder if fine-tuning\ndecoder_lr = 4e-3 # learning rate for decoder\ngrad_clip = 5. # clip gradients at an absolute value of\nalpha_c = 1. # regularization parameter for 'doubly stochastic attention', as in the paper\nbest_bleu4 = 0. # BLEU-4 score right now\nprint_freq = 100 # print training/validation stats every __ batches\nfine_tune_encoder = False # fine-tune encoder?\ncheckpoint = None # path to checkpoint, None if none\ntokenizer = get_tokenizer('basic_english')\n\ncorpus = pd.read_csv(caption_prediction_path.joinpath(\"corpus.csv\"), sep=\"\\t\").loc[:, \"caption\"].values\n\n\ndef yield_tokens(data_iter):\n for text in data_iter:\n yield tokenizer(text)\n\n\nUNKNOWN_TOKEN = \"<unk>\"\nSTART_TOKEN = \"<sos>\"\nEND_TOKEN = \"<eos>\"\nPAD_TOKEN = \"<pad>\"\nMAX_SEQ_LEN = 128\n\nvocabulary = build_vocab_from_iterator(yield_tokens(corpus), specials=[UNKNOWN_TOKEN, START_TOKEN, END_TOKEN, PAD_TOKEN])\nvocabulary.set_default_index(vocabulary[UNKNOWN_TOKEN])\nvocab_size = vocabulary.__len__()\n\n\ndef collate_function(batch):\n \"\"\"\n create a mini batch an make sure the image are of the same size\n \"\"\"\n batch.sort(key=lambda data: len(data[1]), reverse=True) # sort by the longest caption\n images, captions = zip(*batch) # unzip the batch\n images = torch.stack(images) # stack the images\n captions_lengths = [len(caption) for caption in captions]\n captions_array = np.full((len(captions), max(captions_lengths)), vocabulary.lookup_indices([PAD_TOKEN])[0])\n captions_tensor = torch.from_numpy(captions_array)\n for index, caption in enumerate(captions):\n end = captions_lengths[index]\n captions_tensor[index, :end] = caption[:end]\n \n return images.to(device), captions_tensor.to(device), captions_lengths\n\n\ndef main():\n \"\"\"\n Training and validation.\n \"\"\"\n\n global best_bleu4, epochs_since_improvement, checkpoint, start_epoch, fine_tune_encoder, data_name, word_map\n\n text_tranform = Sequential(VocabTransform(vocabulary),\n Truncate(max_seq_len=MAX_SEQ_LEN - 2),\n ToTensor())\n\n # Initialize / load checkpoint\n if checkpoint is None:\n encoder = EncoderCNN(embedding_size=embedding_size)\n decoder = DecoderRNN(embed_size=embedding_size,\n hidden_size=hidden_size,\n vocab_size=vocab_size,\n num_layers=decoder_layers)\n encoder_optimizer = torch.optim.Adam(params=filter(lambda p: p.requires_grad, encoder.parameters()),\n lr=encoder_lr) if fine_tune_encoder else None\n decoder_optimizer = torch.optim.Adam(params=filter(lambda p: p.requires_grad, decoder.parameters()),\n lr=decoder_lr)\n else:\n checkpoint = torch.load(checkpoint)\n start_epoch = checkpoint['epoch'] + 1\n epochs_since_improvement = checkpoint['epochs_since_improvement']\n best_bleu4 = checkpoint['bleu-4']\n decoder = checkpoint['decoder']\n decoder_optimizer = checkpoint['decoder_optimizer']\n encoder = checkpoint['encoder']\n encoder_optimizer = checkpoint['encoder_optimizer']\n if fine_tune_encoder is True and encoder_optimizer is None:\n encoder.fine_tune(fine_tune_encoder)\n encoder_optimizer = torch.optim.Adam(params=filter(lambda p: p.requires_grad, encoder.parameters()),\n lr=encoder_lr)\n\n # Move to GPU, if available\n decoder = decoder.to(device)\n encoder = encoder.to(device)\n\n # Loss function\n criterion = nn.CrossEntropyLoss().cuda() if torch.cuda.is_available() else nn.CrossEntropyLoss()\n\n # Custom dataloaders\n training_dataset = ImageCaptionDataset(caption_path=caption_prediction_path.joinpath(\"training-captions.csv\"),\n images_dir=data_path.joinpath(\"training-images\", \"train\"),\n sequence_length=200,\n text_tokenizer=tokenizer,\n text_transform=text_tranform)\n validation_dataset = ImageCaptionDataset(caption_path=caption_prediction_path.joinpath(\"validation-captions.csv\"),\n images_dir=data_path.joinpath(\"validation-images\", \"valid\"),\n sequence_length=200,\n text_tokenizer=tokenizer,\n text_transform=text_tranform)\n \"\"\"\n uncomment when tesing locally to see how the model works \n indices = list(range(0, 10)) # select your indices here as a list \n train_subset = torch.utils.data.Subset(training_dataset, indices)\n validation_subset = torch.utils.data.Subset(validation_dataset, list(range(11, 30)))\"\"\"\n train_dataloader = DataLoader(training_dataset, batch_size=batch_size, shuffle=False, collate_fn=collate_function)\n validation_dataloader = DataLoader(validation_dataset, batch_size=batch_size, shuffle=False, collate_fn=collate_function)\n # Epochs\n for epoch in range(start_epoch, epochs):\n\n # Decay learning rate if there is no improvement for 8 consecutive epochs, and terminate training after 20\n if epochs_since_improvement == 20:\n break\n if epochs_since_improvement > 0 and epochs_since_improvement % 4 == 0:\n adjust_learning_rate(decoder_optimizer, 0.8)\n if fine_tune_encoder:\n adjust_learning_rate(encoder_optimizer, 0.8)\n\n # One epoch's training\n train(train_loader=train_dataloader,\n encoder=encoder,\n decoder=decoder,\n criterion=criterion,\n encoder_optimizer=encoder_optimizer,\n decoder_optimizer=decoder_optimizer,\n epoch=epoch)\n\n # One epoch's validation\n recent_bleu4 = validate(val_loader=validation_dataloader,\n encoder=encoder,\n decoder=decoder,\n criterion=criterion,\n epoch=epoch)\n\n # Check if there was an improvement\n is_best = recent_bleu4 > best_bleu4\n best_bleu4 = max(recent_bleu4, best_bleu4)\n if not is_best:\n epochs_since_improvement += 1\n print(\"\\nEpochs since last improvement: %d\\n\" % (epochs_since_improvement,))\n else:\n epochs_since_improvement = 0\n\n # Save checkpoint\n save_checkpoint(\"images-captioning\", epoch, epochs_since_improvement, encoder, decoder, encoder_optimizer,\n decoder_optimizer, recent_bleu4, is_best)\n\n\ndef train(train_loader, encoder, decoder, criterion, encoder_optimizer, decoder_optimizer, epoch):\n \"\"\"\n Performs one epoch's training.\n\n :param train_loader: DataLoader for training data\n :param encoder: encoder model\n :param decoder: decoder model\n :param criterion: loss layer\n :param encoder_optimizer: optimizer to update encoder's weights (if fine-tuning)\n :param decoder_optimizer: optimizer to update decoder's weights\n :param epoch: epoch number\n \"\"\"\n with mlflow.start_run():\n\n decoder.train() # train mode (dropout and batchnorm is used)\n encoder.train()\n\n batch_time = AverageMeter() # forward prop. + back prop. time\n data_time = AverageMeter() # data loading time\n losses = AverageMeter() # loss (per word decoded)\n top5accs = AverageMeter() # top5 accuracy\n\n start = time.time()\n # Batches\n for i, (images, captions, lengths) in enumerate(iter(train_loader)):\n\n data_time.update(time.time() - start)\n\n # this part can be a function because it is repeated\n\n # Move to GPU, if available\n images = images.to(device)\n captions = captions.to(device)\n features = encoder(images) # batch size x hidden size or (512)\n \n features = features.expand(decoder_layers, features.shape[0], features.shape[1]) # (number of layer X batch size X hidden size)\n # Set the initial hidden state of the decoder to be the output of the encoder\n decoder_hidden = (features.contiguous(), features.contiguous())\n outputs = decoder(captions, decoder_hidden)\n # Calculate loss\n loss = criterion(outputs, captions)\n\n # Add doubly stochastic attention regularization\n # loss += alpha_c * ((1. - alphas.sum(dim=1)) ** 2).mean() # should comment to improve the model in the future\n\n # Back prop.\n decoder_optimizer.zero_grad()\n if encoder_optimizer is not None:\n encoder_optimizer.zero_grad()\n loss.backward()\n\n # Clip gradients\n if grad_clip is not None:\n clip_gradient(decoder_optimizer, grad_clip)\n if encoder_optimizer is not None:\n clip_gradient(encoder_optimizer, grad_clip)\n\n # Update weights\n decoder_optimizer.step()\n if encoder_optimizer is not None:\n encoder_optimizer.step()\n # Keep track of metrics\n # top5 = accuracy(scores, targets, 5)\n losses.update(loss.item(), 1)\n # top5accs.update(top5, sum(decode_lengths))\n batch_time.update(time.time() - start)\n\n start = time.time()\n\n # Print status\n if i % print_freq == 0:\n print('Epoch: [{0}][{1}/{2}]\\t'\n 'Batch Time {batch_time.val:.3f} ({batch_time.avg:.3f})\\t'\n 'Data Load Time {data_time.val:.3f} ({data_time.avg:.3f})\\t'\n 'Loss {loss.val:.4f} ({loss.avg:.4f})\\t'.format(epoch, i, len(train_loader),\n batch_time=batch_time,\n data_time=data_time, loss=losses))\n step = epoch * len(train_loader) + i\n log_scalar('train_loss', losses.avg, step)\n\n\ndef validate(val_loader, encoder, decoder, criterion, epoch):\n \"\"\"\n Performs one epoch's validation.\n\n :param val_loader: DataLoader for validation data.\n :param encoder: encoder model\n :param decoder: decoder model\n :param criterion: loss layer\n :return: BLEU-4 score\n \"\"\"\n with mlflow.start_run():\n decoder.eval() # eval mode (no dropout or batchnorm)\n if encoder is not None:\n encoder.eval()\n\n batch_time = AverageMeter()\n losses = AverageMeter()\n\n start = time.time()\n\n original_texts = list() \n predicted_texts = list()\n \n\n # explicitly disable gradient calculation to avoid CUDA memory error\n # solves the issue #57\n\n\n # Batches\n\n with torch.no_grad():\n # Batches\n for i, (images, captions, lengths) in enumerate(iter(val_loader)):\n\n # Move to device, if available\n\n images = images.to(device)\n captions = captions.to(device)\n features = encoder(images) # batch size x hidden size or (512)\n\n features = features.expand(decoder_layers, features.shape[0], features.shape[1]) # (number of layer X batch size X hidden size)\n # Set the initial hidden state of the decoder to be the output of the encoder\n decoder_hidden = (features.contiguous(), features.contiguous())\n outputs = decoder(captions, decoder_hidden)\n # Calculate loss\n loss = criterion(outputs, captions)\n predicted_indices = outputs.argmax(dim=1)\n\n assert predicted_indices.shape == captions.shape\n\n caption_text = get_text_for_batch(captions, vocabulary, lengths)\n original_texts.extend(caption_text)\n predicted_text = get_text_for_batch(predicted_indices, vocabulary, lengths)\n predicted_text = [\" \".join(text) for text in predicted_text]\n predicted_texts.extend(predicted_text)\n # Keep track of metrics\n losses.update(loss.item(), sum(lengths))\n batch_time.update(time.time() - start)\n\n start = time.time()\n\n if i % print_freq == 0:\n print('Validation: [{0}/{1}]\\t'\n 'Batch Time {batch_time.val:.3f} ({batch_time.avg:.3f})\\t'\n 'Loss {loss.val:.4f} ({loss.avg:.4f})\\t'.format(i, len(val_loader),\n batch_time=batch_time,\n loss=losses))\n for original, predicted in zip(original_texts[:5], predicted_texts[:5]):\n print(\"original caption: {}\".format(original))\n print(20 * \"=|=\")\n print(\"predicted caption: {}\".format(predicted))\n print(20 * \"-----\")\n\n assert len(original_texts) == len(predicted_texts)\n bleu4 = corpus_bleu(original_texts, predicted_texts,)\n print('\\n * LOSS - {loss.avg:.3f},, BLEU-4 - {bleu}\\n'.format(loss=losses, bleu=bleu4))\n step = (epoch + 1) * len(val_loader)\n log_scalar('test_loss', losses.avg, step)\n return bleu4\n\n\nif __name__ == '__main__':\n main()\n" ]
[ [ "torch.nn.CrossEntropyLoss", "torch.utils.data.DataLoader" ] ]
renyi533/ULTRA
[ "f22b178115e25b8cfcd4c02097f5e9eab4cbc021" ]
[ "ultra/learning_algorithm/base_algorithm.py" ]
[ "\"\"\"The basic class that contains all the API needed for the implementation of an unbiased learning to rank algorithm.\n\n\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport math\nimport os\nimport random\nimport sys\nimport tensorflow as tf\nfrom abc import ABC, abstractmethod\n\nimport ultra\nimport ultra.utils as utils\n\n\nclass BaseAlgorithm(ABC):\n \"\"\"The basic class that contains all the API needed for the\n implementation of an unbiased learning to rank algorithm.\n\n \"\"\"\n PADDING_SCORE = -100000\n\n @abstractmethod\n def __init__(self, data_set, exp_settings, forward_only=False):\n \"\"\"Create the model.\n\n Args:\n data_set: (Raw_data) The dataset used to build the input layer.\n exp_settings: (dictionary) The dictionary containing the model settings.\n forward_only: Set true to conduct prediction only, false to conduct training.\n \"\"\"\n self.is_training = None\n self.docid_inputs = None # a list of top documents\n self.letor_features = None # the letor features for the documents\n self.labels = None # the labels for the documents (e.g., clicks)\n self.output = None # the ranking scores of the inputs\n # the number of documents considered in each rank list.\n self.rank_list_size = None\n # the maximum number of candidates for each query.\n self.max_candidate_num = None\n self.optimizer_func = tf.train.AdagradOptimizer\n pass\n\n @abstractmethod\n def step(self, session, input_feed, forward_only):\n \"\"\"Run a step of the model feeding the given inputs.\n\n Args:\n session: (tf.Session) tensorflow session to use.\n input_feed: (dictionary) A dictionary containing all the input feed data.\n forward_only: whether to do the backward step (False) or only forward (True).\n\n Returns:\n A triple consisting of the loss, outputs (None if we do backward),\n and a tf.summary containing related information about the step.\n\n \"\"\"\n pass\n\n def remove_padding_for_metric_eval(self, input_id_list, model_output):\n output_scores = tf.unstack(model_output, axis=1)\n if len(output_scores) > len(input_id_list):\n raise AssertionError(\n 'Input id list is shorter than output score list when remove padding.')\n # Build mask\n valid_flags = tf.cast(\n tf.concat(\n values=[tf.ones([tf.shape(self.letor_features)[0]]), tf.zeros([1])], axis=0),\n tf.bool\n )\n input_flag_list = []\n for i in range(len(output_scores)):\n input_flag_list.append(\n tf.nn.embedding_lookup(\n valid_flags, input_id_list[i]))\n # Mask padding documents\n for i in range(len(output_scores)):\n output_scores[i] = tf.where(\n input_flag_list[i],\n output_scores[i],\n tf.ones_like(output_scores[i]) * self.PADDING_SCORE\n )\n return tf.stack(output_scores, axis=1)\n\n def ranking_model(self, list_size, scope=None):\n \"\"\"Construct ranking model with the given list size.\n\n Args:\n list_size: (int) The top number of documents to consider in the input docids.\n scope: (string) The name of the variable scope.\n\n Returns:\n A tensor with the same shape of input_docids.\n\n \"\"\"\n output_scores = self.get_ranking_scores(\n self.docid_inputs[:list_size], self.is_training, scope)\n return tf.concat(output_scores, 1)\n\n def get_ranking_scores(self, input_id_list,\n is_training=False, scope=None, **kwargs):\n \"\"\"Compute ranking scores with the given inputs.\n\n Args:\n input_id_list: (list<tf.Tensor>) A list of tensors containing document ids.\n Each tensor must have a shape of [None].\n is_training: (bool) A flag indicating whether the model is running in training mode.\n scope: (string) The name of the variable scope.\n\n Returns:\n A tensor with the same shape of input_docids.\n\n \"\"\"\n with tf.variable_scope(scope or \"ranking_model\"):\n # Build feature padding\n PAD_embed = tf.zeros([1, self.feature_size], dtype=tf.float32)\n letor_features = tf.concat(\n axis=0, values=[\n self.letor_features, PAD_embed])\n input_feature_list = []\n if not hasattr(self, \"model\") or self.model is None:\n self.model = utils.find_class(\n self.exp_settings['ranking_model'])(\n self.exp_settings['ranking_model_hparams'])\n for i in range(len(input_id_list)):\n input_feature_list.append(\n tf.nn.embedding_lookup(\n letor_features, input_id_list[i]))\n return self.model.build(\n input_feature_list, is_training=is_training, **kwargs)\n\n def pairwise_cross_entropy_loss(\n self, pos_scores, neg_scores, propensity_weights=None, name=None):\n \"\"\"Computes pairwise softmax loss without propensity weighting.\n\n Args:\n pos_scores: (tf.Tensor) A tensor with shape [batch_size, 1]. Each value is\n the ranking score of a positive example.\n neg_scores: (tf.Tensor) A tensor with shape [batch_size, 1]. Each value is\n the ranking score of a negative example.\n propensity_weights: (tf.Tensor) A tensor of the same shape as `output` containing the weight of each element.\n name: A string used as the name for this variable scope.\n\n Returns:\n (tf.Tensor) A single value tensor containing the loss.\n \"\"\"\n if propensity_weights is None:\n propensity_weights = tf.ones_like(pos_scores)\n\n loss = None\n with tf.name_scope(name, \"pairwise_cross_entropy_loss\", [pos_scores, neg_scores]):\n label_dis = tf.concat(\n [tf.ones_like(pos_scores), tf.zeros_like(neg_scores)], axis=1)\n loss = tf.nn.softmax_cross_entropy_with_logits(\n logits=tf.concat([pos_scores, neg_scores], axis=1), labels=label_dis\n ) * propensity_weights\n return loss\n\n def sigmoid_loss_on_list(self, output, labels,\n propensity_weights=None, name=None):\n \"\"\"Computes pointwise sigmoid loss without propensity weighting.\n\n Args:\n output: (tf.Tensor) A tensor with shape [batch_size, list_size]. Each value is\n the ranking score of the corresponding example.\n labels: (tf.Tensor) A tensor of the same shape as `output`. A value >= 1 means a\n relevant example.\n propensity_weights: (tf.Tensor) A tensor of the same shape as `output` containing the weight of each element.\n name: A string used as the name for this variable scope.\n\n Returns:\n (tf.Tensor) A single value tensor containing the loss.\n \"\"\"\n if propensity_weights is None:\n propensity_weights = tf.ones_like(labels)\n\n loss = None\n with tf.name_scope(name, \"sigmoid_loss\", [output]):\n label_dis = tf.math.minimum(labels, 1)\n loss = tf.nn.sigmoid_cross_entropy_with_logits(\n labels=label_dis, logits=output) * propensity_weights\n return tf.reduce_mean(tf.reduce_sum(loss, axis=1))\n\n def pairwise_loss_on_list(self, output, labels,\n propensity_weights=None, name=None):\n \"\"\"Computes pairwise entropy loss.\n\n Args:\n output: (tf.Tensor) A tensor with shape [batch_size, list_size]. Each value is\n the ranking score of the corresponding example.\n labels: (tf.Tensor) A tensor of the same shape as `output`. A value >= 1 means a\n relevant example.\n propensity_weights: (tf.Tensor) A tensor of the same shape as `output` containing the weight of each element.\n name: A string used as the name for this variable scope.\n\n Returns:\n (tf.Tensor) A single value tensor containing the loss.\n \"\"\"\n if propensity_weights is None:\n propensity_weights = tf.ones_like(labels)\n\n loss = None\n with tf.name_scope(name, \"pairwise_loss\", [output]):\n sliced_output = tf.unstack(output, axis=1)\n sliced_label = tf.unstack(labels, axis=1)\n sliced_propensity = tf.unstack(propensity_weights, axis=1)\n for i in range(len(sliced_output)):\n for j in range(i + 1, len(sliced_output)):\n cur_label_weight = tf.math.sign(\n sliced_label[i] - sliced_label[j])\n cur_propensity = sliced_propensity[i] * \\\n sliced_label[i] + \\\n sliced_propensity[j] * sliced_label[j]\n cur_pair_loss = - \\\n tf.exp(\n sliced_output[i]) / (tf.exp(sliced_output[i]) + tf.exp(sliced_output[j]))\n if loss is None:\n loss = cur_label_weight * cur_pair_loss\n loss += cur_label_weight * cur_pair_loss * cur_propensity\n batch_size = tf.shape(labels[0])[0]\n # / (tf.reduce_sum(propensity_weights)+1)\n return tf.reduce_sum(loss) / tf.cast(batch_size, dtypes.float32)\n\n def softmax_loss(self, output, labels, propensity_weights=None, name=None):\n \"\"\"Computes listwise softmax loss without propensity weighting.\n\n Args:\n output: (tf.Tensor) A tensor with shape [batch_size, list_size]. Each value is\n the ranking score of the corresponding example.\n labels: (tf.Tensor) A tensor of the same shape as `output`. A value >= 1 means a\n relevant example.\n propensity_weights: (tf.Tensor) A tensor of the same shape as `output` containing the weight of each element.\n name: A string used as the name for this variable scope.\n\n Returns:\n (tf.Tensor) A single value tensor containing the loss.\n \"\"\"\n if propensity_weights is None:\n propensity_weights = tf.ones_like(labels)\n loss = None\n with tf.name_scope(name, \"softmax_loss\", [output]):\n weighted_labels = (labels + 0.0000001) * propensity_weights\n label_dis = weighted_labels / \\\n tf.reduce_sum(weighted_labels, 1, keep_dims=True)\n loss = tf.nn.softmax_cross_entropy_with_logits(\n logits=output, labels=label_dis) * tf.reduce_sum(weighted_labels, 1)\n return tf.reduce_sum(loss) / tf.reduce_sum(weighted_labels)\n" ]
[ [ "tensorflow.exp", "tensorflow.zeros", "tensorflow.shape", "tensorflow.concat", "tensorflow.nn.softmax_cross_entropy_with_logits", "tensorflow.ones_like", "tensorflow.math.minimum", "tensorflow.nn.sigmoid_cross_entropy_with_logits", "tensorflow.math.sign", "tensorflow.variable_scope", "tensorflow.zeros_like", "tensorflow.name_scope", "tensorflow.stack", "tensorflow.reduce_sum", "tensorflow.nn.embedding_lookup", "tensorflow.unstack", "tensorflow.cast" ] ]
melodieboillet/flashtorch
[ "d36768a96bde87241f5f158c8e3ca2d706c72bc4" ]
[ "tests/test_utils.py" ]
[ "import pytest\n\nfrom os import path\nfrom PIL import Image\n\nimport numpy as np\nimport torch\n\nfrom flashtorch.utils import (load_image,\n apply_transforms,\n denormalize,\n standardize_and_clip,\n format_for_plotting)\n\n\n#################\n# Test fixtures #\n#################\n\n\[email protected]\ndef image():\n image_path = path.join(path.dirname(__file__),\n 'resources',\n 'test_image.jpg')\n\n return load_image(image_path)\n\n\n##############\n# Test cases #\n##############\n\n\ndef test_convert_image_to_rgb_when_loading_image(image):\n assert isinstance(image, Image.Image)\n assert image.mode == 'RGB'\n\n\ndef test_handle_non_pil_as_input():\n non_pil_input = np.uint8(np.random.uniform(150, 180, (3, 224, 224)))\n\n transformed = apply_transforms(non_pil_input)\n\n assert isinstance(transformed, torch.Tensor)\n assert transformed.requires_grad\n\n\ndef test_handle_non_pil_input_with_channel_last():\n non_pil_input = np.uint8(np.random.uniform(150, 180, (224, 224, 3)))\n\n transformed = apply_transforms(non_pil_input)\n\n assert isinstance(transformed, torch.Tensor)\n assert transformed.shape == (1, 3, 224, 224)\n\n\ndef test_transform_image_to_tensor(image):\n transformed = apply_transforms(image)\n\n assert isinstance(transformed, torch.Tensor)\n\n\ndef test_crop_to_224_by_default(image):\n transformed = apply_transforms(image)\n\n assert transformed.shape == (1, 3, 224, 224)\n\n\ndef test_crop_to_custom_size(image):\n transformed = apply_transforms(image, 299)\n\n assert transformed.shape == (1, 3, 299, 299)\n\n\ndef test_denormalize_tensor(image):\n transformed = apply_transforms(image)\n denormalized = denormalize(transformed)\n\n assert denormalized.shape == transformed.shape\n assert denormalized.min() >= 0.0 and denormalized.max() <= 1.0\n\n\ndef test_format_multi_channel_tensor_with_batch_dimension():\n input_ = torch.zeros((1, 3, 224, 224))\n\n formatted = format_for_plotting(input_)\n\n assert formatted.shape == (224, 224, 3)\n\n\ndef test_format_mono_channel_tensor_with_batch_dimension():\n input_ = torch.zeros((1, 1, 224, 224))\n formatted = format_for_plotting(input_)\n\n assert formatted.shape == (224, 224)\n\n\ndef test_format_multi_channel_tensor_without_batch_dimension():\n input_ = torch.zeros((3, 224, 224))\n formatted = format_for_plotting(input_)\n\n assert formatted.shape == (224, 224, 3)\n\n\ndef test_format_mono_channel_tensor_without_batch_dimension():\n input_ = torch.zeros((1, 224, 224))\n formatted = format_for_plotting(input_)\n\n assert formatted.shape == (224, 224)\n\n\ndef test_detach_tensor_from_computational_graph():\n input_ = torch.zeros((1, 224, 224))\n input_.requires_grad = True\n\n formatted = format_for_plotting(input_)\n\n assert not formatted.requires_grad\n\n\ndef test_standardize_and_clip_tensor():\n default_min = 0.0\n default_max = 1.0\n\n input_ = torch.randint(low=-1000, high=1000, size=(224, 224)).float()\n normalized = standardize_and_clip(input_)\n\n assert normalized.shape == input_.shape\n assert normalized.min().item() >= default_min\n assert normalized.max().item() <= default_max\n\n\ndef test_standardize_and_clip_detach_input_from_graph():\n default_min = 0.0\n default_max = 1.0\n\n input_ = torch.randint(low=-1000, high=1000, size=(224, 224)).float()\n input_.requires_grad = True\n normalized = standardize_and_clip(input_)\n\n assert normalized.requires_grad == False\n\n\ndef test_standardize_and_clip_with_custom_min_max():\n custom_min = 2.0\n custom_max = 3.0\n\n input_ = torch.randint(low=-1000, high=1000, size=(224, 224)).float()\n normalized = standardize_and_clip(input_, min_value=custom_min, max_value=custom_max)\n\n assert normalized.shape == input_.shape\n assert normalized.min() >= custom_min\n assert normalized.max() <= custom_max\n\n\ndef test_standardize_and_clip_mono_channel_tensor():\n default_min = 0.0\n default_max = 1.0\n\n input_ = torch.randint(low=-1000, high=1000, size=(1, 224, 224)).float()\n normalized = standardize_and_clip(input_)\n\n assert normalized.shape == input_.shape\n assert normalized.min().item() >= default_min\n assert normalized.max().item() <= default_max\n\n\ndef test_standardize_and_clip_multi_channel_tensor():\n default_min = 0.0\n default_max = 1.0\n\n input_ = torch.randint(low=-1000, high=1000, size=(3, 224, 224)).float()\n normalized = standardize_and_clip(input_)\n\n assert normalized.shape == input_.shape\n\n for channel in normalized:\n assert channel.min().item() >= default_min\n assert channel.max().item() <= default_max\n\n\ndef test_standardize_and_clip_add_eplison_when_std_is_zero():\n default_min = 0.0\n default_max = 1.0\n\n input_ = torch.zeros(1, 244, 244)\n normalized = standardize_and_clip(input_)\n\n assert normalized.shape == input_.shape\n\n for channel in normalized:\n assert channel.min().item() >= default_min\n assert channel.max().item() <= default_max\n\n\nif __name__ == '__main__':\n pytest.main([__file__])\n" ]
[ [ "torch.zeros", "torch.randint", "numpy.random.uniform" ] ]
khuang110/GamestonkTerminal
[ "98ac22eef1b61de73b4056debc128b66f520ffb9" ]
[ "gamestonk_terminal/cryptocurrency/crypto_controller.py" ]
[ "__docformat__ = \"numpy\"\n\nimport argparse\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom prompt_toolkit.completion import NestedCompleter\nfrom gamestonk_terminal import feature_flags as gtff\nfrom gamestonk_terminal.helper_funcs import get_flair\nfrom gamestonk_terminal.menu import session\nfrom gamestonk_terminal.cryptocurrency import pycoingecko_view\nfrom gamestonk_terminal.cryptocurrency import coinmarketcap_view as cmc_view\n\n\nclass CryptoController:\n\n CHOICES = [\"help\", \"q\", \"quit\", \"load\", \"view\", \"top\"]\n\n def __init__(self):\n \"\"\"CONSTRUCTOR\"\"\"\n\n self.crypto_parser = argparse.ArgumentParser(add_help=False, prog=\"crypto\")\n self.crypto_parser.add_argument(\"cmd\", choices=self.CHOICES)\n self.current_coin = None\n self.current_df = pd.DataFrame()\n\n @staticmethod\n def print_help(current_coin):\n \"\"\"Print help\"\"\"\n print(\"\\nCryptocurrency:\")\n print(\" help show this menu again\")\n print(\" q quit this menu, and shows back to main menu\")\n print(\" quit quit to abandon program\")\n print(f\"\\nCurrent Coin: {current_coin}\")\n print(\"\")\n print(\" load load cryptocurrency data\")\n print(\" view load and view cryptocurrency data\")\n print(\"\")\n print(\" top view top coins from coinmarketcap\")\n print(\"\")\n\n def switch(self, an_input: str):\n \"\"\"Process and dispatch input\n\n Returns\n -------\n True, False or None\n False - quit the menu\n True - quit the program\n None - continue in the menu\n \"\"\"\n (known_args, other_args) = self.crypto_parser.parse_known_args(an_input.split())\n\n return getattr(\n self, \"call_\" + known_args.cmd, lambda: \"Command not recognized!\"\n )(other_args)\n\n def call_help(self, _):\n \"\"\"Process Help command\"\"\"\n self.print_help(self.current_coin)\n\n def call_q(self, _):\n \"\"\"Process Q command - quit the menu\"\"\"\n return False\n\n def call_quit(self, _):\n \"\"\"Process Quit command - quit the program\"\"\"\n return True\n\n def call_load(self, other_args):\n self.current_coin, self.current_df = pycoingecko_view.load(other_args)\n\n def call_view(self, other_args):\n if self.current_coin:\n pycoingecko_view.view(self.current_coin, self.current_df, other_args)\n\n else:\n print(\"No coin selected. Use 'load' to load the coin you want to look at.\")\n print(\"\")\n\n def call_top(self, other_args):\n cmc_view.get_cmc_top_n(other_args)\n\n\ndef menu():\n crypto_controller = CryptoController()\n crypto_controller.print_help(crypto_controller.current_coin)\n plt.close(\"all\")\n while True:\n # Get input command from user\n if session and gtff.USE_PROMPT_TOOLKIT:\n completer = NestedCompleter.from_nested_dict(\n {c: None for c in crypto_controller.CHOICES}\n )\n an_input = session.prompt(\n f\"{get_flair()} (crypto)> \",\n completer=completer,\n )\n else:\n an_input = input(f\"{get_flair()} (crypto)> \")\n\n try:\n process_input = crypto_controller.switch(an_input)\n\n if process_input is not None:\n return process_input\n\n except SystemExit:\n print(\"The command selected doesn't exist\\n\")\n continue\n" ]
[ [ "pandas.DataFrame", "matplotlib.pyplot.close" ] ]
wesen/FastMaskRCNN
[ "bdae07702acccd85803e658f5e49690981efcdb2" ]
[ "unit_test/preprocessing_test.py" ]
[ "#!/usr/bin/env python\n# coding=utf-8\n\nimport numpy as np\nimport sys\nimport os\nimport tensorflow as tf \nsys.path.append(os.path.join(os.path.dirname(__file__), '..'))\n\nimport libs.preprocessings.coco_v1 as coco_preprocess\nimport libs.configs.config_v1 as cfg\n\nih, iw, ic = 400,500, 3\nN = 3\nimage = np.random.randint(0, 255, (ih, iw, ic)).astype(np.uint8)\ngt_masks = np.zeros((N, ih, iw)).astype(np.int32)\nxy = np.random.randint(0, min(iw, ih)-100, (N, 2)).astype(np.float32)\nwh = np.random.randint(20, 40, (N, 2)).astype(np.float32)\ncls = np.random.randint(1, 6, (N, 1)).astype(np.float32)\ngt_boxes = np.hstack((xy, xy + wh, cls)).astype(np.float32)\ngt_boxes_np = gt_boxes \nimage_np = image \ngt_masks_np = gt_masks \n\nfor i in range(N):\n box = gt_boxes[i, 0:4]\n gt_masks[i, int(box[1]):int(box[3]),\n int(box[0]):int(box[2])] = 1\nimage = tf.constant(image)\ngt_boxes = tf.constant(gt_boxes)\ngt_masks = tf.constant(gt_masks)\n\nimage, gt_boxes, gt_masks = \\\n coco_preprocess.preprocess_image(image, gt_boxes, gt_masks, is_training=True)\n\nwith tf.Session() as sess:\n # print(image.eval())\n image_tf, gt_boxes_tf, gt_masks_tf = \\\n sess.run([image, gt_boxes, gt_masks])\n print ('#######################')\n print ('DATA PREPROCESSING TEST')\n print ('#######################')\n print ('gt_boxes shape:', gt_boxes_tf.shape)\n print('mask shape:', gt_masks_tf.shape)\n print(gt_boxes_tf)\n for i in range(N):\n box = np.round(gt_boxes_tf[i, 0:4])\n box = box.astype(np.int32)\n m = gt_masks_tf[i, box[1]:box[3], box[0]:box[2]]\n print ('after:', box)\n print (np.sum(m)/ (0.0 + m.size))\n print (m)\n box = np.round(gt_boxes_np[i, 0:4])\n box = box.astype(np.int32)\n m = gt_masks_np[i, box[1]:box[3], box[0]:box[2]]\n print ('ori box:', box)\n print (np.sum(m)/ (0.0 + m.size))\n" ]
[ [ "numpy.zeros", "numpy.round", "numpy.sum", "tensorflow.Session", "tensorflow.constant", "numpy.random.randint", "numpy.hstack" ] ]
mayank-mst/Xtraction
[ "cab10ccce93ad844952e534c4fe2456a06556633" ]
[ "textractdemomain.py" ]
[ "import os\nimport cv2\nimport PyPDF2 \nimport textract\nimport fpdf\nimport numpy as np\nimport pytesseract\nfrom PIL import Image\n#from nltk.tokenize import word_tokenize\n#from nltk.corpus import stopwords\nimport pandas as pd\nimport re\n\n#file Path\nsrc_path = \"D:\\\\Documents\\\\MiniProject\\\\New folder\\\\Final\\\\nonsearchable.pdf\"\n\ndef get_string_from_image(img_path):\n # Read image with opencv\n img = cv2.imread(img_path)\n img = cv2.resize(img, None, fx=2, fy=2, interpolation=cv2.INTER_CUBIC)\n img = cv2.medianBlur(img, 3)\n img = cv2.bilateralFilter(img,9,75,75)\n # Convert to gray\n img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n # Apply dilation and erosion to remove some noise\n kernel = np.ones((1, 1), np.uint8)\n img = cv2.dilate(img, kernel, iterations=1)\n img = cv2.erode(img, kernel, iterations=1) \n # Apply threshold to get image with only black and white\n img = cv2.adaptiveThreshold(img, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 31, 2) \n # Recognize text with tesseract for python\n result = pytesseract.image_to_string(Image.open(img_path))\n return result\n\ndef get_string_from_pdf(pdf_path):\n #open allows you to read the file\n pdfFileObj = open(pdf_path,'rb')\n #The pdfReader variable is a readable object that will be parsed\n pdfReader = PyPDF2.PdfFileReader(pdfFileObj)\n #discerning the number of pages will allow us to parse through all #the pages\n num_pages = pdfReader.numPages\n count = 0\n pdftext = \"\"\n #The while loop will read each page\n while count < num_pages:\n pageObj = pdfReader.getPage(count)\n count +=1\n pdftext += pageObj.extractText()\n\n if pdftext != \"\":\n pdftext = pdftext\n \n else:#This if statement exists to check if the above library returned #words. It's done because PyPDF2 cannot read scanned files.\n pdftext = textract.process(pdf_path, method='tesseract', language='eng').decode('utf-8')\n # Now we have a text variable which contains all the text derived #from our PDF file. Type print(text) to see what it contains. It #likely contains a lot of spaces, possibly junk such as '\\n' etc.\n # Now, we will clean our text variable, and return it as a list of keywords.\n #The word_tokenize() function will break our text phrases into #individual words \n #tokens = word_tokenize(pdftext)\n #we'll create a new list which contains punctuation we wish to clean\n #punctuations = ['(',')',';',':','[',']',',']\n #We initialize the stopwords variable which is a list of words like #\"The\", \"I\", \"and\", etc. that don't hold much value as keywords\n ##stop_words = stopwords.words('english')\n #We create a list comprehension which only returns a list of words #that are NOT IN stop_words and NOT IN punctuations.\n #keywords = [word for word in tokens if not word in punctuations]\n #result= (\" \".join(keywords))\n return pdftext\n\n#Get extension of file & Call functions accordingly\nfilename_w_ext = os.path.basename(src_path)\nfilename, file_extension = os.path.splitext(filename_w_ext)\nlistofextensions = ['.jpeg', '.png', '.gif', '.bmp', '.tiff','.jpg']\n\nif file_extension in listofextensions:\n print ('\\n--- Started recognizing text from image ---\\n')\n mst=get_string_from_image(src_path)\nelse:\n print ('\\n--- Started recognizing text from pdf --\\n')\n mst=get_string_from_pdf(src_path)\n\n#-----------------------------------------------------------\n\ntext = mst.encode('ascii','ignore').lower()\nkeywords = re.findall(r'[a-zA-Z]\\w+',text)\ndf = pd.DataFrame(list(set(keywords)),columns=['keywords'])\n\n\n\ndef weightage(word1,text,number_of_documents=1):\n word_list = re.findall(word1,text)\n number_of_times_word_appeared =len(word_list)\n tf = number_of_times_word_appeared/float(len(text))\n idf = np.log((number_of_documents)/float(number_of_times_word_appeared))\n tf_idf = tf*idf\n return number_of_times_word_appeared,tf,idf ,tf_idf \n\n\n \ndf['number_of_times_word_appeared'] = df['keywords'].apply(lambda x: weightage(x,text)[0])\ndf['tf'] = df['keywords'].apply(lambda x: weightage(x,text)[1])\ndf['idf'] = df['keywords'].apply(lambda x: weightage(x,text)[2])\ndf['tf_idf'] = df['keywords'].apply(lambda x: weightage(x,text)[3])\n\ndf = df.sort_values('tf_idf',ascending=True)\ndf.to_csv('Keywords.csv')\ndf.head(25) \n\n#converting String to Searchable pdf\npdf = fpdf.FPDF(format='letter', unit='in')\npdf.alias_nb_pages()\npdf.add_page()\neffective_page_width = pdf.w - 2*pdf.l_margin\npdf.set_font('Times','',13.5)\npdf.multi_cell(effective_page_width, 0.25, mst)\npdf.ln(2)\npdf.output(\"testings.pdf\", 'F')\nprint(\"\\n--- Succesfully Converted._.\")\n\n\"\"\"filename1 = \"D:\\\\Documents\\\\MiniProject\\\\New folder\\\\Final\\\\UQP.pdf\"\n\npdfFileObj1 = open(filename1, 'rb')\n\npdfReader1 = PyPDF2.PdfFileReader(pdfFileObj1)\nsearch_word = input(\"Enter word: \") \n#search_word = \"looks\"\nsearch_word_count = 0\npageno=[]\nfor pageNum in range(0, pdfReader1.numPages):\n pageObj = pdfReader1.getPage(pageNum)\n text = pageObj.extractText()\n search_text = text.lower().split()\n for word in search_text:\n if search_word in word:\n search_word_count += 1\n pageno.append(pageNum+1)\n \nprint(\"The word {} was found {} times \\n\".format(search_word, search_word_count,))\nprint(\"In Page Numbers:\")\nprint(pageno)\"\"\"\n\n" ]
[ [ "numpy.ones" ] ]
bbrighttaer/irelease
[ "632e204436027fe30c2a3a22a1040fc0cd996a94" ]
[ "proj/internal_diversity.py" ]
[ "# Author: bbrighttaer\n# Project: irelease\n# Date: 7/15/2020\n# Time: 11:59 AM\n# File: internal_diversity.py\n\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nimport numpy as np\nimport rdkit.Chem as Chem\nfrom rdkit import DataStructs\nfrom rdkit.Chem import AllChem\n\n\ndef verify_sequence(smile):\n mol = Chem.MolFromSmiles(smile)\n return smile != '' and mol is not None and mol.GetNumAtoms() > 1\n\n\ndef batch_internal_diversity(smiles):\n \"\"\"\n Calculates internal diversity of the given compounds.\n See http://arxiv.org/abs/1708.08227\n\n :param smiles:\n :param set_smiles:\n :return:\n \"\"\"\n rand_mols = [Chem.MolFromSmiles(s) for s in smiles]\n fps = [AllChem.GetMorganFingerprintAsBitVect(m, 4, nBits=2048) for m in rand_mols]\n vals = [bulk_tanimoto_distance(s, fps) if verify_sequence(s) else 0.0 for s in smiles]\n return np.mean(vals)\n\n\ndef bulk_tanimoto_distance(smile, fps):\n ref_mol = Chem.MolFromSmiles(smile)\n ref_fps = AllChem.GetMorganFingerprintAsBitVect(ref_mol, 4, nBits=2048)\n dist = DataStructs.BulkTanimotoSimilarity(ref_fps, fps, returnDistance=True)\n return dist\n\n\nif __name__ == '__main__':\n comps = ['COc1cc(Cc2ccccc2Cl)ncc1NC(=N)Nc1ccc(C(=O)N=C2NCCN2C)cc1',\n 'Oc1ccc2ccccc2c1-c1nc2ccccc2[nH]1',\n 'CN(C)CCn1c(Nc2ccccc2)nc2ccc(NC3CCCC3)cc21',\n 'CCCCCCCCCCCCCC(=O)N(C(=O)CCCCCCCC(C)C)C(C)C',\n 'COc1ccc(-c2ncnc(N3CCCC3C(=O)NC3CCOC3)n2)cc1']\n print(batch_internal_diversity(comps))\n" ]
[ [ "numpy.mean" ] ]
choyingw/GAIS-Net
[ "ee4192976ff37b30e8c442dc17cadbcbdade0ba0" ]
[ "maskrcnn_benchmark/modeling/roi_heads/mask_head/inference.py" ]
[ "import numpy as np\nimport torch\nfrom torch import nn\nfrom maskrcnn_benchmark.layers.misc import interpolate\n\nfrom maskrcnn_benchmark.structures.bounding_box import BoxList\n\nclass MaskPostProcessor(nn.Module):\n \"\"\"\n From the results of the CNN, post process the masks\n by taking the mask corresponding to the class with max\n probability (which are of fixed size and directly output\n by the CNN) and return the masks in the mask field of the BoxList.\n\n If a masker object is passed, it will additionally\n project the masks in the image according to the locations in boxes,\n \"\"\"\n\n def __init__(self, masker=None):\n super(MaskPostProcessor, self).__init__()\n self.masker = masker\n\n def forward(self, x, boxes, x2=None, x3=None):\n \"\"\"\n Arguments:\n x (Tensor): the mask logits\n boxes (list[BoxList]): bounding boxes that are used as\n reference, one for ech image\n\n Returns:\n results (list[BoxList]): one BoxList for each image, containing\n the extra field of \"mask shape\". Mask scores are predicted during the maskiou_head stage.\n \"\"\"\n mask_prob = x.sigmoid()\n\n if x2 is not None:\n mask_prob2 = x2.sigmoid()\n else:\n mask_prob2 = None\n\n if x3 is not None:\n mask_prob3 = x3.sigmoid()\n else:\n mask_prob3 = None\n\n # select masks coresponding to the predicted classes\n num_masks = x.shape[0]\n labels = [bbox.get_field(\"labels\") for bbox in boxes]\n labels = torch.cat(labels)\n index = torch.arange(num_masks, device=labels.device)\n mask_prob = mask_prob[index, labels][:, None]\n\n if x2 is not None:\n mask_prob2 = mask_prob2[index, labels][:, None]\n if x3 is not None:\n mask_prob3 = mask_prob3[index, labels][:, None]\n\n boxes_per_image = [len(box) for box in boxes]\n mask_prob = mask_prob.split(boxes_per_image, dim=0)\n\n if mask_prob2 is not None:\n mask_prob2 = mask_prob2.split(boxes_per_image, dim=0)\n if mask_prob3 is not None:\n mask_prob3 = mask_prob3.split(boxes_per_image, dim=0)\n\n if self.masker:\n mask_prob = self.masker(mask_prob, boxes)\n if mask_prob2 is not None:\n mask_prob2 = self.masker(mask_prob2, boxes)\n if mask_prob3 is not None:\n mask_prob3 = self.masker(mask_prob3, boxes)\n\n results = []\n if mask_prob2 is None:\n for prob, box in zip(mask_prob, boxes):\n bbox = BoxList(box.bbox, box.size, mode=\"xyxy\")\n for field in box.fields():\n bbox.add_field(field, box.get_field(field))\n bbox.add_field(\"mask\", prob)\n results.append(bbox)\n else:\n for prob, prob2, prob3, box in zip(mask_prob, mask_prob2, mask_prob3, boxes):\n bbox = BoxList(box.bbox, box.size, mode=\"xyxy\")\n for field in box.fields():\n bbox.add_field(field, box.get_field(field))\n bbox.add_field(\"mask1\", prob)\n bbox.add_field(\"mask2\", prob2)\n bbox.add_field(\"mask3\", prob3)\n results.append(bbox)\n \n return results\n\n\nclass MaskPostProcessorCOCOFormat(MaskPostProcessor):\n \"\"\"\n From the results of the CNN, post process the results\n so that the masks are pasted in the image, and\n additionally convert the results to COCO format.\n \"\"\"\n\n def forward(self, x, boxes):\n import pycocotools.mask as mask_util\n import numpy as np\n\n results = super(MaskPostProcessorCOCOFormat, self).forward(x, boxes)\n for result in results:\n masks = result.get_field(\"mask\").cpu()\n rles = [\n mask_util.encode(np.array(mask[0, :, :, np.newaxis], order=\"F\"))[0]\n for mask in masks\n ]\n for rle in rles:\n rle[\"counts\"] = rle[\"counts\"].decode(\"utf-8\")\n result.add_field(\"mask\", rles)\n return results\n\n\n# the next two functions should be merged inside Masker\n# but are kept here for the moment while we need them\n# temporarily gor paste_mask_in_image\ndef expand_boxes(boxes, scale):\n w_half = (boxes[:, 2] - boxes[:, 0]) * .5\n h_half = (boxes[:, 3] - boxes[:, 1]) * .5\n x_c = (boxes[:, 2] + boxes[:, 0]) * .5\n y_c = (boxes[:, 3] + boxes[:, 1]) * .5\n\n w_half *= scale\n h_half *= scale\n\n boxes_exp = torch.zeros_like(boxes)\n boxes_exp[:, 0] = x_c - w_half\n boxes_exp[:, 2] = x_c + w_half\n boxes_exp[:, 1] = y_c - h_half\n boxes_exp[:, 3] = y_c + h_half\n return boxes_exp\n\n\ndef expand_masks(mask, padding):\n N = mask.shape[0]\n M = mask.shape[-1]\n pad2 = 2 * padding\n scale = float(M + pad2) / M\n padded_mask = mask.new_zeros((N, 1, M + pad2, M + pad2))\n\n padded_mask[:, :, padding:-padding, padding:-padding] = mask\n return padded_mask, scale\n\n\ndef paste_mask_in_image(mask, box, im_h, im_w, thresh=0.5, padding=1):\n # Need to work on the CPU, where fp16 isn't supported - cast to float to avoid this\n mask = mask.float()\n box = box.float()\n\n padded_mask, scale = expand_masks(mask[None], padding=padding)\n mask = padded_mask[0, 0]\n box = expand_boxes(box[None], scale)[0]\n box = box.to(dtype=torch.int32)\n\n TO_REMOVE = 1\n w = int(box[2] - box[0] + TO_REMOVE)\n h = int(box[3] - box[1] + TO_REMOVE)\n w = max(w, 1)\n h = max(h, 1)\n\n # Set shape to [batchxCxHxW]\n mask = mask.expand((1, 1, -1, -1))\n\n # Resize mask\n mask = mask.to(torch.float32)\n mask = interpolate(mask, size=(h, w), mode='bilinear', align_corners=False)\n mask = mask[0][0]\n\n if thresh >= 0:\n mask = mask > thresh\n else:\n # for visualization and debugging, we also\n # allow it to return an unmodified mask\n mask = (mask * 255).to(torch.uint8)\n\n im_mask = torch.zeros((im_h, im_w), dtype=torch.uint8)\n x_0 = max(box[0], 0)\n x_1 = min(box[2] + 1, im_w)\n y_0 = max(box[1], 0)\n y_1 = min(box[3] + 1, im_h)\n\n im_mask[y_0:y_1, x_0:x_1] = mask[\n (y_0 - box[1]) : (y_1 - box[1]), (x_0 - box[0]) : (x_1 - box[0])\n ]\n return im_mask\n\n\nclass Masker(object):\n \"\"\"\n Projects a set of masks in an image on the locations\n specified by the bounding boxes\n \"\"\"\n\n def __init__(self, threshold=0.5, padding=1):\n self.threshold = threshold\n self.padding = padding\n\n def forward_single_image(self, masks, boxes):\n boxes = boxes.convert(\"xyxy\")\n im_w, im_h = boxes.size\n res = [\n paste_mask_in_image(mask[0], box, im_h, im_w, self.threshold, self.padding)\n for mask, box in zip(masks, boxes.bbox)\n ]\n if len(res) > 0:\n res = torch.stack(res, dim=0)[:, None]\n else:\n res = masks.new_empty((0, 1, masks.shape[-2], masks.shape[-1]))\n return res\n\n def __call__(self, masks, boxes):\n if isinstance(boxes, BoxList):\n boxes = [boxes]\n\n # Make some sanity check\n assert len(boxes) == len(masks), \"Masks and boxes should have the same length.\"\n\n # TODO: Is this JIT compatible?\n # If not we should make it compatible.\n results = []\n for mask, box in zip(masks, boxes):\n assert mask.shape[0] == len(box), \"Number of objects should be the same.\"\n result = self.forward_single_image(mask, box)\n results.append(result)\n return results\n\n\ndef make_roi_mask_post_processor(cfg):\n if cfg.MODEL.ROI_MASK_HEAD.POSTPROCESS_MASKS:\n mask_threshold = cfg.MODEL.ROI_MASK_HEAD.POSTPROCESS_MASKS_THRESHOLD\n masker = Masker(threshold=mask_threshold, padding=1)\n else:\n masker = None\n mask_post_processor = MaskPostProcessor(masker)\n return mask_post_processor\n" ]
[ [ "torch.zeros", "torch.cat", "numpy.array", "torch.stack", "torch.arange", "torch.zeros_like" ] ]
mitjanikolaus/EGG
[ "bbc0ae49ea3e214d969e2c7af1d1e03b7fd56e43" ]
[ "egg/zoo/language_bottleneck/guess_number/features.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 numpy as np\nimport torch\nimport torch.nn.parallel\nimport torch.utils.data as data\n\n\ndef sender_receiver_examples(examples, n_bits, bits_s, bits_r):\n sender_examples = np.copy(examples)\n sender_examples[:, bits_s:] = 0\n sender_examples = torch.from_numpy(sender_examples)\n\n receiver_examples = np.copy(examples)\n receiver_examples[:, :n_bits - bits_r] = 0\n receiver_examples = torch.from_numpy(receiver_examples)\n\n examples = torch.from_numpy(examples)\n\n return sender_examples, examples, receiver_examples\n\n\nclass _OneHotIterator:\n \"\"\"\n >>> it = _OneHotIterator(n_bits=8, bits_s=4, bits_r=4, n_batches_per_epoch=1, batch_size=128)\n >>> batch = list(it)[0]\n >>> s, l, r = batch\n >>> ((s + r) == l).all().item()\n 1\n >>> it = _OneHotIterator(n_bits=8, bits_s=5, bits_r=5, n_batches_per_epoch=1, batch_size=128)\n >>> batch = list(it)[0]\n >>> ((s + r).clamp(0, 1) == l).all().item()\n 1\n >>> it = _OneHotIterator(n_bits=8, bits_s=8, bits_r=8, n_batches_per_epoch=1, batch_size=128)\n >>> batch = list(it)[0]\n >>> s, l, r = batch\n >>> (s == r).all().item()\n 1\n >>> it = _OneHotIterator(n_bits=8, bits_s=8, bits_r=1, n_batches_per_epoch=1, batch_size=128)\n >>> batch = list(it)[0]\n >>> s, l, r = batch\n >>> (r[:, -1] > 0).any().item()\n 1\n >>> (r[:, :-1] == 0).all().item()\n 1\n \"\"\"\n def __init__(self, n_bits, bits_s, bits_r, n_batches_per_epoch, batch_size, seed=None):\n self.n_batches_per_epoch = n_batches_per_epoch\n self.n_bits = n_bits\n self.bits_s = bits_s\n self.bits_r = bits_r\n self.batch_size = batch_size\n\n self.batches_generated = 0\n self.random_state = np.random.RandomState(seed)\n\n def __iter__(self):\n return self\n\n def __next__(self):\n if self.batches_generated >= self.n_batches_per_epoch:\n raise StopIteration()\n\n examples = self.random_state.randint(low=0, high=2, size=(self.batch_size, self.n_bits))\n\n sender_examples, examples, receiver_examples = \\\n sender_receiver_examples(examples, self.n_bits, self.bits_s, self.bits_r)\n\n self.batches_generated += 1\n return sender_examples, examples, receiver_examples\n\n\nclass OneHotLoader(torch.utils.data.DataLoader):\n def __init__(self, n_bits, bits_s, bits_r, batches_per_epoch, batch_size, seed=None):\n self.seed = seed\n self.batches_per_epoch = batches_per_epoch\n self.n_bits = n_bits\n self.bits_r = bits_r\n self.bits_s = bits_s\n self.batch_size = batch_size\n\n def __iter__(self):\n if self.seed is None:\n seed = np.random.randint(0, 2 ** 32)\n else:\n seed = self.seed\n\n return _OneHotIterator(n_bits=self.n_bits, bits_s=self.bits_s, bits_r=self.bits_r,\n n_batches_per_epoch=self.batches_per_epoch,\n batch_size=self.batch_size, seed=seed)\n\n\nclass UniformLoader(torch.utils.data.DataLoader):\n def __init__(self, n_bits, bits_s, bits_r):\n\n batch_size = 2**(n_bits)\n numbers = np.array(range(batch_size))\n\n examples = np.zeros((batch_size, n_bits), dtype=np.int)\n\n for i in range(n_bits):\n examples[:, i] = np.bitwise_and(numbers, 2 ** i) > 0\n\n sender_examples, examples, receiver_examples = \\\n sender_receiver_examples(examples, n_bits, bits_s, bits_r)\n\n self.batch = sender_examples, examples, receiver_examples\n\n def __iter__(self):\n return iter([self.batch])\n\n" ]
[ [ "numpy.zeros", "numpy.random.RandomState", "numpy.copy", "torch.from_numpy", "numpy.bitwise_and", "numpy.random.randint" ] ]
ChrisHad/algorithm-reference-library
[ "bded1b62ea801ea4f4f5bd0794c18cd81d4b2810" ]
[ "tests/workflows/test_calibrate_serial.py" ]
[ "\"\"\"Unit tests for pipelines expressed via dask.delayed\n\n\n\"\"\"\n\nimport logging\nimport sys\nimport unittest\n\nimport numpy\nfrom astropy import units as u\nfrom astropy.coordinates import SkyCoord\n\nfrom data_models.polarisation import PolarisationFrame\nfrom workflows.serial.calibration.calibration_serial import calibrate_list_serial_workflow\nfrom wrappers.serial.calibration.operations import qa_gaintable\nfrom wrappers.serial.calibration.calibration_control import create_calibration_controls\nfrom wrappers.serial.imaging.base import predict_skycomponent_visibility\nfrom wrappers.serial.simulation.testing_support import create_named_configuration, ingest_unittest_visibility, \\\n create_unittest_components, insert_unittest_errors, create_unittest_model\nfrom wrappers.serial.visibility.base import copy_visibility\nfrom wrappers.serial.visibility.coalesce import convert_blockvisibility_to_visibility\n\nlog = logging.getLogger(__name__)\n\nlog.setLevel(logging.DEBUG)\nlog.addHandler(logging.StreamHandler(sys.stdout))\nlog.addHandler(logging.StreamHandler(sys.stderr))\n\n\nclass TestCalibrateGraphs(unittest.TestCase):\n \n def setUp(self):\n from data_models.parameters import arl_path\n self.dir = arl_path('test_results')\n \n def tearDown(self):\n pass\n \n def actualSetUp(self, nfreqwin=3, dospectral=True, dopol=False,\n amp_errors=None, phase_errors=None, zerow=True):\n \n if amp_errors is None:\n amp_errors = {'T': 0.0, 'G': 0.1}\n if phase_errors is None:\n phase_errors = {'T': 1.0, 'G': 0.0}\n \n self.npixel = 512\n self.low = create_named_configuration('LOWBD2', rmax=750.0)\n self.freqwin = nfreqwin\n self.vis_list = list()\n self.ntimes = 1\n self.times = numpy.linspace(-3.0, +3.0, self.ntimes) * numpy.pi / 12.0\n self.frequency = numpy.linspace(0.8e8, 1.2e8, self.freqwin)\n \n if self.freqwin > 1:\n self.channelwidth = numpy.array(self.freqwin * [self.frequency[1] - self.frequency[0]])\n else:\n self.channelwidth = numpy.array([1e6])\n \n if dopol:\n self.vis_pol = PolarisationFrame('linear')\n self.image_pol = PolarisationFrame('stokesIQUV')\n f = numpy.array([100.0, 20.0, -10.0, 1.0])\n else:\n self.vis_pol = PolarisationFrame('stokesI')\n self.image_pol = PolarisationFrame('stokesI')\n f = numpy.array([100.0])\n \n if dospectral:\n flux = numpy.array([f * numpy.power(freq / 1e8, -0.7) for freq in self.frequency])\n else:\n flux = numpy.array([f])\n \n self.phasecentre = SkyCoord(ra=+180.0 * u.deg, dec=-60.0 * u.deg, frame='icrs', equinox='J2000')\n self.blockvis_list = [ingest_unittest_visibility(self.low,\n [self.frequency[i]],\n [self.channelwidth[i]],\n self.times,\n self.vis_pol,\n self.phasecentre, block=True,\n zerow=zerow)\n for i in range(nfreqwin)]\n \n for v in self.blockvis_list:\n v.data['vis'][...] = 1.0+0.0j\n \n self.error_blockvis_list = [copy_visibility(v) for v in self.blockvis_list]\n self.error_blockvis_list = [insert_unittest_errors\n (self.error_blockvis_list[i], amp_errors=amp_errors, phase_errors=phase_errors,\n calibration_context=\"TG\")\n for i in range(self.freqwin)]\n \n assert numpy.max(numpy.abs(self.error_blockvis_list[0].vis - self.blockvis_list[0].vis)) > 1.0\n \n def test_time_setup(self):\n self.actualSetUp()\n \n def test_calibrate_serial(self):\n amp_errors = {'T': 0.0, 'G': 0.0}\n phase_errors = {'T': 1.0, 'G': 0.0}\n self.actualSetUp(amp_errors=amp_errors, phase_errors=phase_errors)\n \n controls = create_calibration_controls()\n controls['T']['first_selfcal'] = 0\n controls['T']['timescale'] = 'auto'\n \n calibrate_list = \\\n calibrate_list_serial_workflow(self.error_blockvis_list, self.blockvis_list,\n calibration_context='T', controls=controls, do_selfcal=True,\n global_solution=False)\n assert numpy.max(calibrate_list[1][0]['T'].residual) < 7e-6, numpy.max(calibrate_list[1][0]['T'].residual)\n assert numpy.max(numpy.abs(calibrate_list[0][0].vis - self.blockvis_list[0].vis)) < 2e-6\n\n def test_calibrate_serial_global(self):\n amp_errors = {'T': 0.0, 'G': 0.0}\n phase_errors = {'T': 1.0, 'G': 0.0}\n self.actualSetUp(amp_errors=amp_errors, phase_errors=phase_errors)\n \n controls = create_calibration_controls()\n controls['T']['first_selfcal'] = 0\n controls['T']['timescale'] = 'auto'\n \n calibrate_list = \\\n calibrate_list_serial_workflow(self.error_blockvis_list, self.blockvis_list,\n calibration_context='T', controls=controls, do_selfcal=True,\n global_solution=True)\n \n assert numpy.max(calibrate_list[1][0]['T'].residual) < 7e-6, numpy.max(calibrate_list[1][0]['T'].residual)\n assert numpy.max(numpy.abs(calibrate_list[0][0].vis - self.blockvis_list[0].vis)) < 2e-6\n\nif __name__ == '__main__':\n unittest.main()\n" ]
[ [ "numpy.max", "numpy.array", "numpy.power", "numpy.abs", "numpy.linspace" ] ]
shingtgen/OG-USA
[ "b0db1ee158944d023ea2b9fc139873f1a24001c4" ]
[ "ogusa/deterministic_profiles.py" ]
[ "import numpy as np\nimport pandas as pd\nimport os\nimport matplotlib.pyplot as plt\nfrom linearmodels import PanelOLS\nimport ogcore # import just for MPL style file\n\n# Create directory if output directory does not already exist\ncur_path = os.path.split(os.path.abspath(__file__))[0]\noutput_fldr = \"csv_output_files\"\noutput_dir = os.path.join(cur_path, output_fldr)\nif not os.access(output_dir, os.F_OK):\n os.makedirs(output_dir)\n\n\ndef estimate_profiles(graphs=False):\n \"\"\"\n Function to estimate deterministic lifecycle profiles of hourly\n earnings. Follows methodology of Fullerton and Rogers (1993).\n\n Args:\n graphs (bool): whether to create graphs of profiles\n\n Returns:\n reg_results (Pandas DataFrame): regression model coefficients\n for lifetime earnings profiles\n\n \"\"\"\n # Read in dataframe of PSID data\n df = ogcore.utils.safe_read_pickle(\n os.path.join(cur_path, \"data\", \"PSID\", \"psid_lifetime_income.pkl\")\n )\n\n model_results = {\n \"Names\": [\n \"Constant\",\n \"\",\n \"Head Age\",\n \"\",\n \"Head Age^2\",\n \"\",\n \"Head Age^3\",\n \"\",\n \"R-Squared\",\n \"Observations\",\n ]\n }\n cats_pct = [\"0-25\", \"26-50\", \"51-70\", \"71-80\", \"81-90\", \"91-99\", \"100\"]\n long_model_results = {\n \"Lifetime Income Group\": [],\n \"Constant\": [],\n \"Age\": [],\n \"Age^2\": [],\n \"Age^3\": [],\n \"Observations\": [],\n }\n for i, group in enumerate(cats_pct):\n data = df[df[group] == 1].copy()\n data[\"ones\"] = np.ones(len(data.index))\n mod = PanelOLS(\n data.ln_earn_rate, data[[\"ones\", \"age\", \"age2\", \"age3\"]]\n )\n res = mod.fit(cov_type=\"clustered\", cluster_entity=True)\n # print('Summary for lifetime income group ', group)\n # print(res.summary)\n # Save model results to dictionary\n model_results[group] = [\n res.params[\"ones\"],\n res.std_errors[\"ones\"],\n res.params[\"age\"],\n res.std_errors[\"age\"],\n res.params[\"age2\"],\n res.std_errors[\"age2\"],\n res.params[\"age3\"],\n res.std_errors[\"age3\"],\n res.rsquared,\n res.nobs,\n ]\n long_model_results[\"Lifetime Income Group\"].extend([cats_pct[i], \"\"])\n long_model_results[\"Constant\"].extend(\n [res.params[\"ones\"], res.std_errors[\"ones\"]]\n )\n long_model_results[\"Age\"].extend(\n [res.params[\"age\"], res.std_errors[\"age\"]]\n )\n long_model_results[\"Age^2\"].extend(\n [res.params[\"age2\"], res.std_errors[\"age2\"]]\n )\n long_model_results[\"Age^3\"].extend(\n [res.params[\"age3\"], res.std_errors[\"age3\"]]\n )\n long_model_results[\"Observations\"].extend([res.nobs, \"\"])\n\n reg_results = pd.DataFrame.from_dict(model_results)\n reg_results.to_csv(\n os.path.join(output_dir, \"DeterministicProfileRegResults.csv\")\n )\n long_reg_results = pd.DataFrame.from_dict(model_results)\n long_reg_results.to_csv(\n os.path.join(output_dir, \"DeterministicProfileRegResults_long.csv\")\n )\n\n if graphs:\n # Plot lifecycles of hourly earnings from processes estimated above\n age_vec = np.arange(20, 81, step=1)\n for i, group in enumerate(cats_pct):\n earn_profile = (\n model_results[group][0]\n + model_results[group][2] * age_vec\n + model_results[group][4] * age_vec ** 2\n + model_results[group][6] * age_vec ** 3\n )\n plt.plot(age_vec, earn_profile, label=group)\n plt.title(\n \"Estimated Lifecycle Earnings Profiles by Lifetime Income Group\"\n )\n plt.legend()\n\n plt.savefig(\n os.path.join(output_dir, \"lifecycle_earnings_profiles.png\")\n )\n\n # Plot of lifecycles of hourly earnings from processes from data\n pd.pivot_table(\n df,\n values=\"ln_earn_rate\",\n index=\"age\",\n columns=\"li_group\",\n aggfunc=\"mean\",\n ).plot(legend=True)\n plt.title(\n \"Empirical Lifecycle Earnings Profiles by Lifetime Income Group\"\n )\n\n plt.savefig(\n os.path.join(output_dir, \"lifecycle_earnings_profiles_data.png\")\n )\n\n # Plot of lifecycle profiles of hours by lifetime income group\n # create variable from fraction of time endowment work\n df[\"labor_supply\"] = df[\"earnhours_hh\"] / (\n 24 * 5 * (df[\"married\"] + 1) * 50\n )\n pd.pivot_table(\n df,\n values=\"labor_supply\",\n index=\"age\",\n columns=\"li_group\",\n aggfunc=\"mean\",\n ).plot(legend=True)\n plt.title(\"Lifecycle Profiles of Hours by Lifetime Income Group\")\n\n plt.savefig(os.path.join(output_dir, \"lifecycle_laborsupply.png\"))\n\n return reg_results\n" ]
[ [ "pandas.DataFrame.from_dict", "matplotlib.pyplot.title", "matplotlib.pyplot.legend", "matplotlib.pyplot.plot", "numpy.arange", "pandas.pivot_table" ] ]
ckmganesh/Visual-Question-Answering-Flask-Application
[ "3fed82c142a5b4d926dbd78324c72d1b63c2c94a" ]
[ "VQA_main.py" ]
[ "import numpy as np\nimport pandas as pd\nimport re\nimport glob\nfrom flask import Flask, request, render_template, url_for\nfrom flask_cors import CORS\nfrom werkzeug.utils import secure_filename\nimport os\nimport logging\nlogging.basicConfig(level=logging.INFO)\n\nimport tensorflow as tf\nimport silence_tensorflow.auto \nphysical_devices = tf.config.experimental.list_physical_devices('GPU')\ntf.config.experimental.set_memory_growth(physical_devices[0], True)\nfrom tensorflow.keras.applications import VGG19\nfrom tensorflow.keras.layers import Input\nfrom tensorflow.keras.preprocessing import sequence\n\nfrom models.arch import build_model\nfrom models.layers import ContextVector, PhraseLevelFeatures, AttentionMaps\nfrom utils.load_pickles import tok, labelencoder\nfrom utils.helper_functions import image_feature_extractor, process_sentence, predict_answers\n\nmax_answers = 1000\nmax_seq_len = 22\nvocab_size = len(tok.word_index) + 1\ndim_d = 512\ndim_k = 256\nl_rate = 1e-4\nd_rate = 0.5\nreg_value = 0.01\nMODEL_PATH = 'pickles/complete_model.h5'\nIMAGE_PATH = 'static'\n\ncustom_objects = {\n 'PhraseLevelFeatures': PhraseLevelFeatures,\n 'AttentionMaps': AttentionMaps,\n 'ContextVector': ContextVector\n }\n\n# load the model\nmodel = tf.keras.models.load_model(MODEL_PATH, custom_objects=custom_objects)\nvgg_model = VGG19(weights=\"imagenet\", include_top=False, input_tensor=Input(shape=(3, 224, 224)))\n \n# Create Flask application\napp = Flask(__name__, static_url_path='/static')\nCORS(app)\n\[email protected]('/')\ndef home():\n return render_template('index.html')\n\[email protected]('/', methods=['POST'])\ndef predict():\n try:\n \n # delete images uploaded in previous session\n files = glob.glob(IMAGE_PATH+'/*')\n for f in files:\n os.remove(f)\n \n #0 --- Get the image file and question\n f = request.files['image_file']\n fname = secure_filename(f.filename)\n f.save(IMAGE_PATH +'/'+ fname)\n f.close()\n question = request.form[\"question\"]\n \n #1 --- Extract image features\n img_feat = image_feature_extractor(IMAGE_PATH +'/'+ fname, vgg_model)\n #2 --- Clean the question\n questions_processed = pd.Series(question).apply(process_sentence)\n \n \n #3 --- Tokenize the question data using a pre-trained tokenizer and pad them\n question_data = tok.texts_to_sequences(questions_processed)\n question_data = sequence.pad_sequences(question_data, \\\n maxlen=max_seq_len,\\\n padding='post')\n \n \n #4 --- Predict the answers\n y_predict = predict_answers(img_feat, question_data, model, labelencoder)\n return render_template('index.html', fname=fname, question=question, answer=y_predict[0])\n \n except Exception as e:\n \n return render_template(\"error.html\" , error = e)\n \n# RUN FLASK APPLICATION\nif __name__ == \"__main__\":\n\n # RUNNNING FLASK APP \n app.run(debug=False, host = '0.0.0.0', port=8080)\n\n\n\n\n" ]
[ [ "tensorflow.keras.preprocessing.sequence.pad_sequences", "tensorflow.keras.layers.Input", "tensorflow.config.experimental.set_memory_growth", "tensorflow.keras.models.load_model", "pandas.Series", "tensorflow.config.experimental.list_physical_devices" ] ]
x-hacker/pkuseg-python
[ "15801afe97cb4f450a196335b38d83e1b29a3e59" ]
[ "pkuseg/viterbi.py" ]
[ "import numpy as np\nimport math\n\nclass decisionNode:\n def __init__(self):\n self._preY = -1\n self._maxPreScore = -1\n self._maxNowScore = -1\n self._initCheck = False\n\nclass Viterbi:\n def __init__(self ,w, h):\n self._w = w\n self._h = h\n self._nodeScore = []\n self._edgeScore = []\n self._decisionLattice = []\n for i in range(w):\n tmp = []\n for j in range(h):\n tmp.append(decisionNode())\n self._decisionLattice.append(tmp)\n for i in range(w):\n self._nodeScore.append(np.zeros(h))\n self._edgeScore.append(np.zeros((h, h)))\n self._edgeScore[0] = None\n\n def setScores(self, i, Y, YY):\n self._nodeScore[i] = Y.copy()\n if i>0:\n self._edgeScore[i] = YY.copy()\n\n def runViterbi(self, states, exp):\n for y in range(self._h):\n curNode = self._decisionLattice[-1][y]\n curNode._initCheck = True\n curNode._maxPreScore = 0\n curNode._maxNowScore = self._nodeScore[-1][y]\n curNode._preY = -1\n for i in range(self._w-2, -1, -1):\n for y in range(self._h):\n for yPre in range(self._h):\n iPre = i+1\n preNode = self._decisionLattice[iPre][yPre]\n curNode = self._decisionLattice[i][y]\n score1 = self._nodeScore[iPre][yPre]\n score2 = self._edgeScore[iPre][y, yPre]\n score3 = preNode._maxPreScore\n score4 = self._nodeScore[i][y]\n preScore = score1+score2+score3\n if not curNode._initCheck:\n curNode._initCheck = True\n curNode._maxPreScore = preScore\n curNode._maxNowScore = preScore + score4\n curNode._preY = yPre\n elif preScore >= curNode._maxPreScore:\n curNode._maxPreScore = preScore\n curNode._maxNowScore = preScore + score4\n curNode._preY = yPre\n states.clear()\n ma = self._decisionLattice[0][0]._maxNowScore\n tag = 0\n for y in range(1, self._h):\n sc = self._decisionLattice[0][y]._maxNowScore\n if ma<sc:\n ma = sc\n tag = y\n states.append(tag)\n for i in range(1, self._w):\n iPre = i-1\n tag = self._decisionLattice[iPre][tag]._preY\n states.append(tag)\n # overflow\n if ma>300:\n ma = 300\n return math.exp(ma)\n" ]
[ [ "numpy.zeros" ] ]
zmlabe/AMIP_Simu
[ "6370626fe81baf5c2280dab95fdab08a873f3a84" ]
[ "Scripts/calc_SNA_Data_Eurasia.py" ]
[ "\"\"\"\nScript calculates Eurasian snow area index for October-November following the \nmethods of Peings et al. 2017\n\nNotes\n-----\n Author : Zachary Labe\n Date : 23 July 2019\n\"\"\"\n\n### Import modules\nimport datetime\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport read_MonthlyData as MOM\nimport scipy.stats as sts\nimport scipy.signal as SS\nimport read_Reanalysis as MOR\n\n### Define directories\ndirectoryfigure = '/home/zlabe/Desktop/'\ndirectoryoutput = '/home/zlabe/Documents/Research/AMIP/Data/'\n\n### Define time \nnow = datetime.datetime.now()\ncurrentmn = str(now.month)\ncurrentdy = str(now.day)\ncurrentyr = str(now.year)\ncurrenttime = currentmn + '_' + currentdy + '_' + currentyr\ntitletime = currentmn + '/' + currentdy + '/' + currentyr\nprint('\\n' '----Calculating Snow Cover Area Index - %s----' % titletime)\n\n#### Alott time series\nyear1 = 1979\nyear2 = 2015\nyears = np.arange(year1,year2+1,1)\n\n### Add parameters\nensembles = 10\nvarnames = 'SNC'\nrunnames = [r'ERA-I',r'CSST',r'Csnow',r'AMIP',r'AMQ',r'AMS',r'AMQS']\nrunnamesm = [r'CSST',r'CSIC',r'AMIP',r'AMQ',r'AMS',r'AMQS']\n\ndef readVar(varnames,runnamesm):\n### Call function to read in ERA-Interim\n lat,lon,time,lev,era = MOR.readDataR('T2M','surface',False,True)\n \n ### Call functions to read in WACCM data\n models = np.empty((len(runnamesm),ensembles,era.shape[0],era.shape[1],\n era.shape[2],era.shape[3]))\n for i in range(len(runnamesm)):\n lat,lon,time,lev,models[i] = MOM.readDataM(varnames,runnamesm[i],\n 'surface',False,True)\n \n ### Select October-November for index\n modq = np.nanmean(models[:,:,:,9:11,:,:],axis=3)\n \n ### Calculate ensemble mean\n modmean = np.nanmean(modq[:,:,:,:,:],axis=1)\n \n return modmean,lat,lon,lev\n\n###############################################################################\n### Read in data functions\nmod,lat,lon,lev = readVar(varnames,runnamesm)\n\n### Slice over region of interest for Eurasia (40-80N,35-180E)\nlatq = np.where((lat >= 40) & (lat <= 80))[0]\nlonq = np.where((lon >= 35) & (lon <=180))[0]\nlatn = lat[latq]\nlonn = lon[lonq]\nlon2,lat2 = np.meshgrid(lonn,latn)\n\nmodlat = mod[:,:,latq,:]\nmodlon = modlat[:,:,:,lonq]\nmodslice = modlon.copy()\n\n### Calculate sea ice extent\ndef calcExtent(snowq,lat2):\n \"\"\"\n Calculate snow cover extent from snow concentration grids following\n the methods of Robinson et al. 1993 [BAMS]\n \"\"\"\n ### Extent is a binary 0 or 1 for 50% snow threshold\n thresh=50.\n snow = snowq.copy()\n snow[np.where(snow<thresh)]=np.nan\n snow[np.where(snow>thresh)]=1\n \n ext = np.zeros((snow.shape[0]))\n valyr = np.zeros((snow.shape))\n for ti in range(snow.shape[0]):\n for i in range(snow.shape[1]):\n for j in range(snow.shape[2]):\n if snow[ti,i,j] == 1.0:\n ### Area 1.9x2.5 grid cell [58466.1 = (278.30) * (210.083)]\n valyr[ti,i,j] = 58466.1 * np.cos(np.radians(lat2[i,j]))\n ext[ti] = np.nansum(valyr[ti,:,:])/1e6\n \n return ext\n\n### Consider years 1979-2015\nmodsliceq = modslice[:,:-1,:,:]\n\n### Calculate snow cover area\nsnowarea = np.empty((modsliceq.shape[0],modsliceq.shape[1]))\nfor i in range(snowarea.shape[0]):\n snowarea[i,:] = calcExtent(modsliceq[i,:,:,:],lat2)\n\n### Calculate detrended snow index\nsnowareaindexdt = SS.detrend(snowarea,type='linear',axis=1)\n\n### Save both indices\nnp.savetxt(directoryoutput + 'SNA_Eurasia_ON.txt',\n np.vstack([years,snowarea]).transpose(),delimiter=',',fmt='%3.1f',\n footer='\\n Snow cover index calculated for each' \\\n '\\n experiment [CSST,CSIC,AMIP,AMQ,AMS,AMQS]\\n' \\\n ' in Oct-Nov (AREA)',newline='\\n\\n')\nnp.savetxt(directoryoutput + 'SNA_Eurasia_ON_DETRENDED.txt',\n np.vstack([years,snowareaindexdt]).transpose(),delimiter=',',fmt='%3.1f',\n footer='\\n Snow cover index calculated for each' \\\n '\\n experiment [CSST,CSIC,AMIP,AMQ,AMS,AMQS]\\n' \\\n ' in Oct-Nov ---> detrended data (AREA)',newline='\\n\\n')" ]
[ [ "numpy.empty", "numpy.zeros", "numpy.nansum", "scipy.signal.detrend", "numpy.where", "numpy.nanmean", "numpy.radians", "numpy.arange", "numpy.meshgrid", "numpy.vstack" ] ]
MohammadChalaki/morph-net
[ "83addae677195b4beba34a321ccf9c0cd55d5b62" ]
[ "morph_net/tools/configurable_ops.py" ]
[ "\"\"\"A module that facilitates creation of configurable networks.\n\nThe goal of this module is to allow centralized parameterization of a (possibly)\ncomplex deep network.\n\nAn important detail in this implementation is about the behaviour of function\ngiven a trivial parameterization. By trivial we mean the case where\nNUM_OUTPUTS is 0. We define the output of a trivial parameterization to be the\nspecial value VANISHED, which is recognized by supported ops. We use 0.0 for its\nvalue, so that it's treated as a regular 0.0 by supported Tensorflow ops.\nThis choice implies that:\n * For a vanished input, functions such as 'conv2d', or 'fully_connected' will\n also produce vanished output.\n * The 'concat' function will ignore VANISHED inputs. If all inputs are\n VANISHED, then the output is also VANISHED.\n\nThis edge-case behaviour achieves two goals:\n * It minimizes creation of ops in the graph which are not used.\n * It allows seamless use of the class in networks where some elements\n might be \"turned off\" by the parameterization.\n\nFor instance the following code will work for any parameterization of\nthe first and second convolutions, including 0.\n```\n# input.shape[-1] == 128\nops = ConfigurableOps(parameterization)\nnet_1 = ops.conv2d(input, num_outputs=256, kernel_size=1, scope='conv1')\nnet_2 = ops.conv2d(net_1, num_outputs=64, kernel_size=3, scope='conv2')\nnet_3 = ops.conv2d(net_2, num_outputs=128, kernel_size=1, scope='conv3')\n\noutput = net_3 + input\n```\nFor `parameterization = '{'conv1': 0}'`\nthe values of `net_1`, `net_2`, and `net_3` will be all vanished sentinels, and\nthe bypass of this block will essentially vanish.\n\nNote that the VANISHED functionality will save downsteam ops from being created\nbut not upstream ops. For example, with `parameterization = '{'conv2': 0}'`,\nthen `net_1` will still be created.\n\n\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport collections\nimport copy\nimport enum\nimport functools\nimport json\n\nfrom morph_net.tools import structure_exporter as se\nimport tensorflow.compat.v1 as tf\nfrom tensorflow.compat.v1 import layers as tf_layers\nfrom tensorflow.compat.v1.keras import layers as keras_layers\nfrom tensorflow.contrib import framework\nfrom tensorflow.contrib import layers as contrib_layers\nfrom tensorflow.contrib import slim as slim_layers\n# gfile = tf.gfile # Aliase needed for mock.\n\nVANISHED = 0.0\n_DEFAULT_NUM_OUTPUTS_KWARG = 'num_outputs'\n\nDEFAULT_FUNCTION_DICT = {\n 'fully_connected': contrib_layers.fully_connected,\n 'conv2d': contrib_layers.conv2d,\n 'separable_conv2d': contrib_layers.separable_conv2d,\n 'concat': tf.concat,\n 'add_n': tf.add_n,\n 'avg_pool2d': contrib_layers.avg_pool2d,\n 'max_pool2d': contrib_layers.max_pool2d,\n 'batch_norm': contrib_layers.batch_norm,\n}\n\n_OP_SCOPE_DEFAULTS = {\n tf_layers.conv2d: 'conv2d',\n slim_layers.conv2d: 'Conv',\n contrib_layers.conv2d: 'Conv',\n\n tf_layers.separable_conv2d: 'separable_conv2d',\n slim_layers.separable_conv2d: 'SeparableConv2d',\n contrib_layers.separable_conv2d: 'SeparableConv2d',\n\n tf_layers.dense: 'dense',\n slim_layers.fully_connected: 'fully_connected',\n contrib_layers.fully_connected: 'fully_connected',\n}\n\n# Maps function names to the suffix of the name of the regularized ops.\n_SUFFIX_DICT = {\n 'fully_connected': 'MatMul',\n 'conv2d': 'Conv2D',\n 'separable_conv2d': 'separable_conv2d',\n}\n\n\ndef get_function_dict(overrides=None):\n \"\"\"Get mapping from function name to function for ConfigurableOps.\n\n Args:\n overrides: Dict: str -> function. Optionally replace entries in\n `DEFAULT_FUNCTION_DICT`.\n\n Returns:\n Dict: function name (str) to function.\n \"\"\"\n overrides = overrides or {}\n function_dict = copy.deepcopy(DEFAULT_FUNCTION_DICT)\n function_dict.update(overrides)\n return function_dict\n\n\ndef is_vanished(maybe_tensor):\n \"\"\"Checks if the argument represents a real tensor or None/vanished sentinel.\n\n For example:\n `is_vanished(ConfigurableOps({'conv1': 0}).conv2d(...,scope='conv1'))`\n returns True, since 0 channels in a conv2d produces vanished output.\n\n Args:\n maybe_tensor: A tensor or None or the vanished sentinel.\n\n Returns:\n A boolean, whether maybe_tensor is a tensor.\n \"\"\"\n return (isinstance(maybe_tensor, float) and\n maybe_tensor == VANISHED) or maybe_tensor is None\n\n\nclass FallbackRule(enum.Enum):\n \"\"\"Fallback rules for the ConfigurableOps class.\"\"\"\n pass_through = 'pass_through'\n strict = 'strict'\n zero = 'zero'\n\n\ndef _get_op_name(configurable_keras_layer_instance):\n \"\"\"Get full op name including scopes.\"\"\"\n parameterization = configurable_keras_layer_instance.parameterization\n layer_name = configurable_keras_layer_instance.name\n op_suffixes = configurable_keras_layer_instance.op_suffixes\n is_strict = configurable_keras_layer_instance.is_strict\n\n full_scope = framework.get_name_scope()\n sep = '' if layer_name.endswith('/') else '/'\n possible_op_names = [full_scope + sep + suffix for suffix in op_suffixes]\n matches_in_parameterization = [\n name for name in possible_op_names if name in parameterization]\n\n if (is_strict and not matches_in_parameterization):\n raise KeyError(\n 'None of the following op names were found in the '\n 'parameterization: {}'.format(possible_op_names))\n\n if len(matches_in_parameterization) > 1:\n raise KeyError(\n 'Found multiple matching op names in the parameterization: {}'.format(\n matches_in_parameterization))\n\n if matches_in_parameterization:\n return matches_in_parameterization[0]\n\n # If no op names were found in the parameterization, then return the default\n # op name generated by Keras\n default_op_suffix = configurable_keras_layer_instance.default_op_suffix\n return full_scope + '/' + default_op_suffix\n\n\ndef _insert_to_constructed_ops(\n configurable_keras_layer_instance, op_name, num_outputs):\n \"\"\"Logs the NUM_OUTPUTS into constructed_ops dict.\"\"\"\n constructed_ops = configurable_keras_layer_instance.constructed_ops\n if op_name in constructed_ops:\n tf.logging.warning('Function called more than once with scope %s.', op_name)\n constructed_ops[op_name] = num_outputs\n\n\ndef _configurable_keras_layer_build(configurable_keras_layer_instance):\n \"\"\"Encapsulates the `build` logic of all Configurable Keras layers.\"\"\"\n parameterization = configurable_keras_layer_instance.parameterization\n num_outputs_attr = configurable_keras_layer_instance.num_outputs_attr\n\n op_name = _get_op_name(configurable_keras_layer_instance)\n original_num_outputs = getattr(\n configurable_keras_layer_instance, num_outputs_attr)\n num_outputs = parameterization.get(op_name, original_num_outputs)\n _insert_to_constructed_ops(\n configurable_keras_layer_instance, op_name, num_outputs)\n configurable_keras_layer_instance.is_null_op = num_outputs == 0\n setattr(configurable_keras_layer_instance, num_outputs_attr, num_outputs)\n\n\nclass ConfigurableConv2D(keras_layers.Conv2D):\n \"\"\"Keras Conv2D Layer that sets NUM_OUTPUTS according to parameterization.\"\"\"\n\n def __init__(self,\n sentinel=None,\n parameterization=None,\n constructed_ops=None,\n is_strict=False,\n **kwargs):\n \"\"\"Initialize configurable Keras layer.\n\n Args:\n sentinel: Sentinel argument to prevent positional arguments.\n parameterization: Dict: MorphNet-generated parameterization dict mapping\n op names to number of filters/neurons.\n constructed_ops: A dict to keep track of parameterized ops. NOTE: This\n dict will be modified during `build`.\n is_strict: If True, all constructed ops must exist in the\n parameterization.\n **kwargs: Kwargs for Keras layer.\n \"\"\"\n if sentinel is not None:\n raise ValueError(\n 'Found positional argument. __init__ only accepts kwargs.')\n self.parameterization = parameterization or {}\n self.constructed_ops = (constructed_ops if constructed_ops is not None else\n collections.OrderedDict())\n self.is_strict = is_strict\n\n # may be modified by `_configurable_keras_layer_build` (during `build`)\n self.is_null_op = False\n\n super(ConfigurableConv2D, self).__init__(**kwargs)\n\n @property\n def op_suffixes(self):\n return ['Conv2D', 'ConfigurableConv2D']\n\n @property\n def default_op_suffix(self):\n return 'ConfigurableConv2D'\n\n @property\n def num_outputs_attr(self):\n return 'filters'\n\n def __call__(self, inputs, *args, **kwargs):\n if is_vanished(inputs):\n return VANISHED\n\n outputs = super(ConfigurableConv2D, self).__call__(inputs, *args, **kwargs)\n\n # Note: If num_outputs=0, we want to return VANISHED. However, we can't\n # return VANISHED in `call` since Keras requires the outputs of `call` be\n # Tensors. Instead, we let Keras build a no-op convolution (with output\n # channels = 0) and ignore its output.\n return VANISHED if self.is_null_op else outputs\n\n def build(self, input_shape):\n _configurable_keras_layer_build(self)\n return super(ConfigurableConv2D, self).build(input_shape)\n\n\nclass ConfigurableSeparableConv2D(keras_layers.SeparableConv2D):\n \"\"\"Keras SeparableConv2D that sets NUM_OUTPUTS from parameterization.\"\"\"\n\n def __init__(self,\n sentinel=None,\n parameterization=None,\n constructed_ops=None,\n is_strict=False,\n **kwargs):\n \"\"\"Initialize configurable Keras layer.\n\n Args:\n sentinel: Sentinel argument to prevent positional arguments.\n parameterization: Dict: MorphNet-generated parameterization dict mapping\n op names to number of filters/neurons.\n constructed_ops: A dict to keep track of parameterized ops. NOTE: This\n dict will be modified during `build`.\n is_strict: If True, all constructed ops must exist in the\n parameterization.\n **kwargs: Kwargs for Keras layer.\n \"\"\"\n if sentinel is not None:\n raise ValueError(\n 'Found positional argument. __init__ only accepts kwargs.')\n self.parameterization = parameterization or {}\n self.constructed_ops = (constructed_ops if constructed_ops is not None else\n collections.OrderedDict())\n self.is_strict = is_strict\n\n # may be modified by `_configurable_keras_layer_build` (during `build`)\n self.is_null_op = False\n\n super(ConfigurableSeparableConv2D, self).__init__(**kwargs)\n\n @property\n def op_suffixes(self):\n return ['separable_conv2d']\n\n @property\n def default_op_suffix(self):\n return 'separable_conv2d'\n\n @property\n def num_outputs_attr(self):\n return 'filters'\n\n def __call__(self, inputs, *args, **kwargs):\n if is_vanished(inputs):\n return VANISHED\n outputs = super(ConfigurableSeparableConv2D, self).__call__(\n inputs, *args, **kwargs)\n\n # Note: If num_outputs=0, we want to return VANISHED. However, we can't\n # return VANISHED in `call` since Keras requires the outputs of `call` be\n # Tensors. Instead, we let Keras build a no-op convolution (with output\n # channels = 0) and ignore its output.\n return VANISHED if self.is_null_op else outputs\n\n def build(self, input_shape):\n _configurable_keras_layer_build(self)\n return super(ConfigurableSeparableConv2D, self).build(input_shape)\n\n\nclass ConfigurableDense(keras_layers.Dense):\n \"\"\"Keras Dense Layer that sets NUM_OUTPUTS according to parameterization.\"\"\"\n\n def __init__(self,\n sentinel=None,\n parameterization=None,\n constructed_ops=None,\n is_strict=False,\n **kwargs):\n \"\"\"Initialize configurable Keras layer.\n\n Args:\n sentinel: Sentinel argument to prevent positional arguments.\n parameterization: Dict: MorphNet-generated parameterization dict mapping\n op names to number of filters/neurons.\n constructed_ops: A dict to keep track of parameterized ops. NOTE: This\n dict will be modified during `build`.\n is_strict: If True, all constructed ops must exist in the\n parameterization.\n **kwargs: Kwargs for Keras layer.\n \"\"\"\n if sentinel is not None:\n raise ValueError(\n 'Found positional argument. __init__ only accepts kwargs.')\n self.parameterization = parameterization or {}\n self.constructed_ops = (constructed_ops if constructed_ops is not None else\n collections.OrderedDict())\n self.is_strict = is_strict\n\n # may be modified by `_configurable_keras_layer_build` (during `build`)\n self.is_null_op = False\n\n super(ConfigurableDense, self).__init__(**kwargs)\n\n @property\n def op_suffixes(self):\n return ['Tensordot/MatMul']\n\n @property\n def default_op_suffix(self):\n return 'Tensordot/MatMul'\n\n @property\n def num_outputs_attr(self):\n return 'units'\n\n def __call__(self, inputs, *args, **kwargs):\n if is_vanished(inputs):\n return VANISHED\n outputs = super(ConfigurableDense, self).__call__(inputs, *args, **kwargs)\n\n # Note: If num_outputs=0, we want to return VANISHED. However, we can't\n # return VANISHED in `call` since Keras requires the outputs of `call` be\n # Tensors. Instead, we let Keras build a no-op convolution (with output\n # channels = 0) and ignore its output.\n return VANISHED if self.is_null_op else outputs\n\n def build(self, input_shape):\n _configurable_keras_layer_build(self)\n return super(ConfigurableDense, self).build(input_shape)\n\n\nclass PassThroughKerasLayerWrapper(object):\n \"\"\"Wraps Keras Layer to handle VANISHED inputs.\n\n Wraps `keras_layer_class` (Keras Layer) to return VANISHED output on VANISHED\n input. This is useful when MorphNet removes convolutions from the network (by\n setting num_filters=0) in which case downstream ops should not be constructed.\n \"\"\"\n\n def __init__(self,\n keras_layer_class,\n *args_for_keras_layer,\n **kwargs_for_keras_layer):\n \"\"\"Initialize configurable Keras Layer wrapper.\n\n Args:\n keras_layer_class: Keras Layer class to wrap.\n *args_for_keras_layer: Args to initialize keras_layer_class (see\n `__call__`).\n **kwargs_for_keras_layer: Kwargs to initialize keras_layer_class (see\n `__call__`).\n \"\"\"\n self.keras_layer_class = keras_layer_class\n self.args_for_keras_layer = args_for_keras_layer\n self.kwargs_for_keras_layer = kwargs_for_keras_layer\n\n def __call__(self, inputs, *args, **kwargs):\n # Handle list of tensors (Merge layers).\n if isinstance(inputs, (list, tuple)):\n inputs = [t for t in inputs if not is_vanished(t)]\n\n # If `inputs` is a list, we assume it is correct behavior to return\n # `inputs[0]` if len(inputs) == 1 (as is true with Add, Multiply,\n # Concatenate). We preempt __call__ since Merge layers require\n # len(inputs) > 1.\n if not inputs:\n return VANISHED\n elif len(inputs) == 1:\n return inputs[0]\n\n # Handle single tensor inputs.\n elif is_vanished(inputs):\n return VANISHED\n\n self.keras_layer_instance = self.keras_layer_class(\n *self.args_for_keras_layer,\n **self.kwargs_for_keras_layer)\n return self.keras_layer_instance(inputs, *args, **kwargs)\n\n\ndef hijack_keras_module(\n parameterization_or_file,\n module,\n fallback_rule=FallbackRule.pass_through,\n remove_common_prefix=False,\n keep_first_channel_alive=True):\n \"\"\"Replaces Keras module with a fake \"module\" containing configurable Layers.\n\n If a module imports Keras layers:\n ```\n from tensorflow.compat.v1.keras.layers import Conv2D\n from tensorflow.compat.v1.keras.layers import SeparableConv2D\n # ...\n ```\n\n or defines global aliases:\n ```\n import tensorflow.compat.v1.keras.layers as keras_layers\n Conv2D = keras_layers.Conv2D\n ```\n\n then this function can be used to easily replace these classes with a\n configurable variant where the number of filters/neurons in each layer are\n set by a parameterization dict (or file) produced by MorphNet.\n\n After calling `hijack_keras_module(parameterization, module)`, any call to\n `module.Conv2D` or `module.Dense` will be replaced with a call to a unique\n Keras Layer which wraps the original base_class (see\n `_configurable_keras_layer_factory` for more details).\n\n Args:\n parameterization_or_file: Either:\n * A dict mapping op names to integer NUM_OUTPUTs\n * A path to a JSON file containing the above dict.\n module: A module name to override its Keras.\n fallback_rule: A `FallbackRule` enum which controls fallback behavior\n (see ConfigurableOps.__init__ for more details.)\n remove_common_prefix: If True, ignores outer level scope in all op names\n in the parameterization.\n keep_first_channel_alive: If True, keeps at least 1 neuron in each layer.\n\n Returns:\n (1) An OrderedDict of constructed ops.\n (2) A dict of function pointers before the hijacking.\n\n Raises:\n ValueError if trying to hijack the Keras layers module\n (`tensorflow.compat.v1.keras`) itself.\n \"\"\"\n parameterization_or_file = parameterization_or_file or {}\n if not isinstance(parameterization_or_file, (str, dict)):\n raise ValueError(\n 'Expected dict or string (filename) for `parameterization_or_file`. '\n 'Instead got: {}'.format(type(parameterization_or_file)))\n if isinstance(parameterization_or_file, str):\n with tf.gfile.Open(parameterization_or_file, 'r') as f:\n parameterization = json.loads(f.read())\n else:\n parameterization = parameterization_or_file\n\n if remove_common_prefix:\n rename_op = se.get_remove_common_prefix_fn(parameterization)\n parameterization = {rename_op(k): v for k, v in parameterization.items()}\n\n if keep_first_channel_alive:\n parameterization = {k: max(v, 1) for k, v in parameterization.items()}\n\n fallback_rule = _get_fallback_rule_as_enum(fallback_rule)\n is_strict = fallback_rule == FallbackRule.strict\n original_layer_classes = {}\n constructed_ops = collections.OrderedDict()\n\n def _maybe_replace_layer_class(class_name, configurable_layer_class):\n if hasattr(module, class_name):\n original_layer_classes[class_name] = getattr(module, class_name)\n setattr(module, class_name, configurable_layer_class)\n\n for configurable_layer_class, class_name in [\n (ConfigurableConv2D, 'Conv2D'),\n (ConfigurableSeparableConv2D, 'SeparableConv2D'),\n (ConfigurableDense, 'Dense')]:\n configurable_layer_class = functools.partial(\n configurable_layer_class,\n parameterization=parameterization,\n constructed_ops=constructed_ops,\n is_strict=is_strict)\n _maybe_replace_layer_class(class_name, configurable_layer_class)\n\n for keras_layer_class, class_name in [\n (keras_layers.BatchNormalization, 'BatchNormalization'),\n (keras_layers.Activation, 'Activation'),\n (keras_layers.UpSampling2D, 'UpSampling2D'),\n (keras_layers.Add, 'Add'),\n (keras_layers.Concatenate, 'Concatenate'),\n (keras_layers.Multiply, 'Multiply')]:\n pass_through_layer_class = functools.partial(\n PassThroughKerasLayerWrapper,\n keras_layer_class)\n _maybe_replace_layer_class(class_name, pass_through_layer_class)\n\n return constructed_ops, original_layer_classes\n\n\ndef _get_fallback_rule_as_enum(fallback_rule):\n if not (isinstance(fallback_rule, FallbackRule) or\n isinstance(fallback_rule, str)):\n raise ValueError('fallback_rule must be a string or FallbackRule Enum')\n if isinstance(fallback_rule, str):\n return FallbackRule[fallback_rule] # Converts from string.\n return fallback_rule\n\n\nclass ConfigurableOps(object):\n \"\"\"A class that facilitates structure modification of a Tensorflow graph.\n\n The ConfigurableOps allows modifications of the NUM_OUTPUTS argument ops.\n The functionality is determined by a 'parameterization' and by modifiers.\n The 'parameterization' is a map between scope names and new NUM_OUTPUTS\n values. If the scope of an op matches a key from the parameterization, the\n decorator will override the NUM_OUTPUTS argument.\n\n Another feature of the ConfigurableOps is support for vanishing input sizes\n that arise when an the NUM_OUTPUTS argument of a downstream op is set to\n zero. Specifically, the functions decorated by the class adhere to the\n following input/output logic:\n * If NUM_OUTPUTS is set to zero, then the output of the op will be the\n vanished sentinel, and will return False when checked with is_vanished().\n * If the input is vanished, the output will be the same.\n * The concatenation (configurable_ops.concat) of an vanished element with\n other tensors ignores the vanished elements. The result of concatenating\n only vanished elements is also vanished.\n\n In addition the object collects and report the actual NUM_OUTPUTS argument\n that was used in every context.\n \"\"\"\n\n def __init__(self,\n parameterization=None,\n function_dict=None,\n fallback_rule=FallbackRule.pass_through):\n \"\"\"Constructs a ConfigurableOps.\n\n Args:\n parameterization: A dictionary between scope name to be overridden and a\n integer which is the target NUM_OUTPUTS.\n function_dict: A dict between names of ops (strings) and functions\n which accept num_outputs as the second argument. If None defaults to\n DEFAULT_FUNCTION_DICT.\n fallback_rule: A `FallbackRule` enum which controls fallback behavior:\n * 'pass_through' provided NUM_OUTPUTS is passed to decorated\n function (default).\n * 'strict' requires the scope name appear in parameterization or else\n throws an error.\n * 'zero' uses `num_outputs` equal to zero if scope name is not in the\n parameterization.\n Raises:\n ValueError: If fallback_rule is not a string or a FallbackRule enum.\n \"\"\"\n\n fallback_rule = _get_fallback_rule_as_enum(fallback_rule)\n self._parameterization = parameterization or {}\n self._function_dict = function_dict or DEFAULT_FUNCTION_DICT\n self._suffix_dict = _SUFFIX_DICT\n self._constructed_ops = collections.OrderedDict()\n self._default_to_zero = fallback_rule == FallbackRule.zero\n self._strict = fallback_rule == FallbackRule.strict\n self.default_scope_to_counts_map = {}\n\n # To keep track of the number of identical scopes encountered\n self._scope_counts = {}\n\n @property\n def parameterization(self):\n \"\"\"Returns the parameterization dict mapping op names to num_outputs.\"\"\"\n return self._parameterization\n\n @framework.add_arg_scope\n def conv2d(self, *args, **kwargs):\n \"\"\"Masks num_outputs from the function pointed to by 'conv2d'.\n\n The object's parameterization has precedence over the given NUM_OUTPUTS\n argument. The resolution of the op names uses\n tf.contrib.framework.get_name_scope() and kwargs['scope'].\n\n Args:\n *args: Arguments for the operation.\n **kwargs: Key arguments for the operation.\n\n Returns:\n The result of the application of the function_dict['conv2d'] to the given\n 'inputs', '*args' and '**kwargs' while possibly overriding NUM_OUTPUTS\n according the parameterization.\n\n Raises:\n ValueError: If kwargs does not contain a key named 'scope'.\n \"\"\"\n fn, suffix = self._get_function_and_suffix('conv2d')\n return self._mask(fn, suffix, *args, **kwargs)\n\n @framework.add_arg_scope\n def fully_connected(self, *args, **kwargs):\n \"\"\"Masks NUM_OUTPUTS from the function pointed to by 'fully_connected'.\n\n The object's parameterization has precedence over the given NUM_OUTPUTS\n argument. The resolution of the op names uses\n tf.contrib.framework.get_name_scope() and kwargs['scope'].\n\n Args:\n *args: Arguments for the operation.\n **kwargs: Key arguments for the operation.\n\n Returns:\n The result of the application of the function_map['fully_connected'] to\n the given 'inputs', '*args' and '**kwargs' while possibly overriding\n NUM_OUTPUTS according the parameterization.\n\n Raises:\n ValueError: If kwargs does not contain a key named 'scope'.\n \"\"\"\n inputs = _get_from_args_or_kwargs('inputs', 0, args, kwargs)\n if inputs.shape.ndims != 2:\n raise ValueError(\n 'ConfigurableOps does not suport fully_connected with rank != 2')\n fn, suffix = self._get_function_and_suffix('fully_connected')\n return self._mask(fn, suffix, *args, **kwargs)\n\n @framework.add_arg_scope\n def separable_conv2d(self, *args, **kwargs):\n \"\"\"Masks NUM_OUTPUTS from the function pointed to by 'separable_conv2d'.\n\n The object's parameterization has precedence over the given NUM_OUTPUTS\n argument. The resolution of the op names uses\n tf.contrib.framework.get_name_scope() and kwargs['scope'].\n\n Args:\n *args: Arguments for the operation.\n **kwargs: Key arguments for the operation.\n\n Returns:\n The result of the application of the function_map['separable_conv2d'] to\n the given 'inputs', '*args', and '**kwargs' while possibly overriding\n NUM_OUTPUTS according the parameterization.\n\n Raises:\n ValueError: If kwargs does not contain a key named 'scope'.\n \"\"\"\n # This function actually only decorates the num_outputs of the Conv2D after\n # the depthwise convolution, as the former does not have any free params.\n fn, suffix = self._get_function_and_suffix('separable_conv2d')\n num_outputs_kwarg_name = self._get_num_outputs_kwarg_name(fn)\n num_outputs = _get_from_args_or_kwargs(\n num_outputs_kwarg_name, 1, args, kwargs, False)\n if num_outputs is None:\n tf.logging.warning(\n 'Trying to decorate separable_conv2d with num_outputs = None')\n kwargs[num_outputs_kwarg_name] = None\n\n return self._mask(fn, suffix, *args, **kwargs)\n\n def _mask(self, function, suffix, *args, **kwargs):\n \"\"\"Masks num_outputs from the given function.\n\n The object's parameterization has precedence over the given NUM_OUTPUTS\n argument. The resolution of the op names uses\n `tf.contrib.framework.get_name_scope()` and `kwargs['scope']`.\n\n The NUM_OUTPUTS argument is assumed to be either in **kwargs or held in\n *args[1].\n\n In case the `inputs` argument is VANISHED or that `num_outputs` is 0,\n returns VANISHED without adding ops to the graph.\n\n Args:\n function: A callable function to mask the NUM_OUTPUTS parameter from.\n Examples for functions are in DEFAULT_FUNCTION_DICT.\n The callable function must accept a NUM_OUTPUTS parameter as the\n second argument.\n suffix: A string with the suffix of the op name.\n *args: Arguments for the operation.\n **kwargs: Key arguments for the operation.\n\n Returns:\n The result of the application of the function to the given 'inputs',\n '*args', and '**kwargs' while possibly overriding NUM_OUTPUTS according\n to the parameterization.\n\n Raises:\n ValueError: If kwargs does not contain a key named 'scope'.\n \"\"\"\n inputs = args[0] if args else kwargs.pop('inputs')\n if is_vanished(inputs):\n return VANISHED\n\n # Support for tf.contrib.layers and tf.layers API.\n op_scope = kwargs.get('scope')\n current_scope = framework.get_name_scope() or ''\n if current_scope and not current_scope.endswith('/'):\n current_scope += '/'\n\n op_scope = kwargs.get('scope') or kwargs.get('name')\n if op_scope:\n if op_scope.endswith('/'):\n raise ValueError(\n 'Scope `{}` ends with `/` which leads to unexpected '\n 'behavior.'.format(op_scope))\n full_scope = current_scope + op_scope\n else:\n # Use default scope, optionally appending a unique ID if scope exists\n if function not in _OP_SCOPE_DEFAULTS:\n raise ValueError(\n 'No `scope` or `name` found in kwargs, and no default scope '\n 'defined for {}'.format(_get_function_name(function)))\n op_scope = _OP_SCOPE_DEFAULTS[function]\n full_scope = current_scope + op_scope\n if full_scope in self._scope_counts:\n new_scope = full_scope + '_' + str(self._scope_counts[full_scope])\n self._scope_counts[full_scope] += 1\n full_scope = new_scope\n else:\n self._scope_counts[full_scope] = 1\n\n op_name = full_scope + '/' + suffix\n\n # Assumes `inputs` is the first argument and `num_outputs` is the second\n # argument.\n num_outputs = self._parse_num_outputs(\n op_name, self._get_num_outputs_kwarg_name(function), args, kwargs)\n args = args[2:] # Possibly and empty list of < 3 positional args are used.\n\n self._insert_to_constructed_ops(op_name, num_outputs)\n if num_outputs == 0:\n return VANISHED\n\n return function(inputs, num_outputs, *args, **kwargs)\n\n @property\n def constructed_ops(self):\n \"\"\"Returns a dictionary between op names built to their NUM_OUTPUTS.\n\n The dictionary will contain an op.name: NUM_OUTPUTS pair for each op\n constructed by the decorator. The dictionary is ordered according to the\n order items were added.\n The parameterization is accumulated during all the calls to the object's\n members, such as `conv2d`, `fully_connected` and `separable_conv2d`.\n The values used are either the values from the parameterization set for\n the object, or the values that where passed to the members.\n \"\"\"\n return self._constructed_ops\n\n def concat(self, *args, **kwargs):\n return self._pass_through_mask_list('concat', 'values', *args, **kwargs)\n\n def add_n(self, *args, **kwargs):\n return self._pass_through_mask_list('add_n', 'inputs', *args, **kwargs)\n\n @framework.add_arg_scope\n def avg_pool2d(self, *args, **kwargs):\n return self._pass_through_mask(\n self._function_dict['avg_pool2d'], *args, **kwargs)\n\n @framework.add_arg_scope\n def max_pool2d(self, *args, **kwargs):\n return self._pass_through_mask(\n self._function_dict['max_pool2d'], *args, **kwargs)\n\n @framework.add_arg_scope\n def batch_norm(self, *args, **kwargs):\n return self._pass_through_mask(\n self._function_dict['batch_norm'], *args, **kwargs)\n\n def _get_num_outputs_kwarg_name(self, function):\n \"\"\"Gets the `num_outputs`-equivalent kwarg for a supported function.\"\"\"\n alt_num_outputs_kwarg = {\n tf_layers.conv2d: 'filters',\n tf_layers.separable_conv2d: 'filters',\n tf_layers.dense: 'units',\n }\n return alt_num_outputs_kwarg.get(function, _DEFAULT_NUM_OUTPUTS_KWARG)\n\n def _parse_num_outputs(self, op_name, num_outputs_kwarg_name, args, kwargs):\n \"\"\"Computes the target NUM_OUTPUTS and adjusts kwargs in place.\n\n Will try to extract the number of outputs from the op_name's\n parameterization. If that's not possible, it will default to 0 when\n _default_to_zero is set, otherwise defaulting to the NUM_OUTPUTS argument\n that is either in kwargs or args[1].\n\n Args:\n op_name: A string, the name of the op to get NUM_OUTPUTS for.\n num_outputs_kwarg_name: A string, the name of the `num_outputs`-equivalent\n kwarg.\n args: Position arguments for the callable. Assumes that NUM_OUTPUTS\n position is 1.\n kwargs: key word arguments for the callable.\n\n Returns:\n The target value.\n\n Raises:\n KeyError: If strict and op_name not found in parameterization.\n \"\"\"\n if self._strict and op_name not in self._parameterization:\n # If strict and op_name not found in parameterization, throw an error.\n raise KeyError('op_name \\\"%s\\\" not found in parameterization' % op_name)\n\n # Assumes that the position of num_outputs is 1.\n base_num_outputs = _get_from_args_or_kwargs(\n num_outputs_kwarg_name, 1, args, kwargs)\n kwargs.pop(num_outputs_kwarg_name, None) # Removes num_outputs from kwargs.\n\n default_num_outputs = 0 if self._default_to_zero else base_num_outputs\n return self._parameterization.get(op_name, default_num_outputs)\n\n def _get_function_and_suffix(self, key):\n \"\"\"Returns the function and suffix associated with key.\"\"\"\n if key not in self._function_dict:\n raise KeyError('Function \"%s\" not supported by function_dict' % key)\n return self._function_dict[key], self._suffix_dict[key]\n\n def _insert_to_constructed_ops(self, name, num_outputs):\n \"\"\"Logs the NUM_OUTPUTS for scope 'name' into _constructed_ops.\"\"\"\n if name in self._constructed_ops:\n tf.logging.warning('Function called more than once with scope %s.', name)\n self._constructed_ops[name] = num_outputs\n\n def _pass_through_mask_list(self, fn_name, inputs_name, *args, **kwargs):\n \"\"\"Drops any tensors that are None or vanished and applies `fn` to result.\n\n Assumes the first argument to `fn` is the list of tensors.\n\n Args:\n fn_name: Function name to apply on filtered inputs, must be a key of\n 'function_dict'.\n inputs_name: Name of the input argument (in case it's passed as a kwarg).\n *args: Args for the function defined by `fn_name`.\n **kwargs: Kwargs for he function defined by `fn_name`.\n\n Returns:\n Output of function on filtered inputs, or vanished if all inputs are\n vanished.\n \"\"\"\n if fn_name not in self._function_dict:\n raise ValueError('Unrecognized function name %s' % fn_name)\n fn = self._function_dict[fn_name]\n if args:\n inputs = args[0]\n args = args[1:]\n else:\n if inputs_name not in kwargs:\n raise ValueError('Missing `{}` argument.'.format(inputs_name))\n inputs = kwargs.pop(inputs_name)\n\n inputs = [t for t in inputs if not is_vanished(t)]\n return fn(inputs, *args, **kwargs) if inputs else VANISHED\n\n def _pass_through_mask(self, layer_fn, *args, **kwargs):\n inputs = args[0] if args else kwargs['inputs']\n return VANISHED if is_vanished(inputs) else layer_fn(*args, **kwargs)\n\n\ndef _get_from_args_or_kwargs(name, index, args, kwargs, is_required=True):\n try:\n return kwargs[name] if name in kwargs else args[index]\n except IndexError:\n if is_required:\n raise ValueError('Argument `{}` is required.'.format(name))\n return None\n\n\ndef _get_function_name(function):\n \"\"\"Get a descriptive identifier for `function`.\"\"\"\n return '{}.{}'.format(function.__module__, function.__name__)\n\n\ndef hijack_module_functions(configurable_ops, module):\n \"\"\"Hijacks the functions from module using configurable_ops.\n\n Overrides globally declared function reference in module with configurable_ops\n member functions.\n\n If a module defines global aliases in the form:\n\n example_module.py\n ```\n conv2d = tr.contrib.layers.conv2d\n fully_connected = tr.contrib.layers.fully_connected\n\n def build_layer(inputs):\n return conv2d(inputs, 64, 3, scope='demo')\n ```\n\n Then this function provides the possibility to replace these aliases with\n the members of the given `configurable_ops` object.\n\n So after a call to `hijack_module_functions(configurable_ops, example_module)`\n the call `example_module.build_layer(net)` will under the hood use\n `configurable_ops.conv2d` rather than `tf.contrib.layers.conv2d`.\n\n Note: This function could be unsafe as it depends on aliases defined in a\n possibly external module. In addition, a function in that module that calls\n directly, will not be affected by the hijacking, for instance:\n\n ```\n def build_layer_not_affected(inputs):\n return tf.contrib.layers.conv2d(inputs, 64, 3, scope='bad')\n ```\n\n Args:\n configurable_ops: An ConfigurableOps object, to use functions as defined in\n 'DEFAULT_FUNCTION_DICT'.\n module: A module name to override its functions.\n\n Returns:\n A dict of the function pointers before the hijacking.\n \"\"\"\n originals = {}\n\n def maybe_setattr(attr):\n \"\"\"Sets module.attr = configurable_ops.attr if module has attr.\n\n Overrides module.'attr' with configurable_ops.'attr', if module already has\n an attribute name 'attr'.\n\n Args:\n\n attr: Name of the attribute to override.\n \"\"\"\n if hasattr(module, attr):\n originals[attr] = getattr(module, attr)\n setattr(module, attr, getattr(configurable_ops, attr))\n\n for fn in DEFAULT_FUNCTION_DICT:\n maybe_setattr(fn)\n return originals\n\n\ndef recover_module_functions(originals, module):\n \"\"\"Recovers the functions hijacked to from module.\n\n Args:\n originals: Dict of functions to recover. Assumes keys are a contained in\n 'DEFAULT_FUNCTION_DICT'.\n module: A module name to recover its functions.\n\n \"\"\"\n for attr, original in originals.items():\n setattr(module, attr, original)\n\n\ndef decorator_from_parameterization_file(\n filename, fallback_rule=FallbackRule.pass_through, **kwargs):\n \"\"\"Create a ConfigurableOps from a parameterization file.\n\n Loads a json parameterization file from disk\n (as saved by tools.structure_exporter) and creates an ConfigurableOps from\n it.\n\n Args:\n filename: Path to a parameterization file in json format.\n fallback_rule: A `FallbackRule` enum which controls fallback behavior\n (see __init__ for more detail.)\n **kwargs: Miscellaneous args for ConfigurableOps.\n\n Returns:\n An ConfigurableOps instance with the parameterization from `filename`.\n \"\"\"\n with tf.gfile.Open(filename, 'r') as f:\n parameterization = json.loads(f.read())\n return ConfigurableOps(\n parameterization=parameterization, fallback_rule=fallback_rule,\n **kwargs)\n" ]
[ [ "tensorflow.compat.v1.gfile.Open", "tensorflow.compat.v1.logging.warning", "tensorflow.contrib.framework.get_name_scope" ] ]
kkanellis/MLOS
[ "f828cf2b46ed63d7c9b3bd6cef73b2027a7ad12a" ]
[ "source/Mlos.Python/mlos/OptimizerEvaluationTools/SyntheticFunctions/MultiObjectiveEnvelopedWaves.py" ]
[ "#\r\n# Copyright (c) Microsoft Corporation.\r\n# Licensed under the MIT License.\r\n#\r\nimport math\r\nimport pandas as pd\r\n\r\nfrom mlos.OptimizerEvaluationTools.ObjectiveFunctionBase import ObjectiveFunctionBase\r\nfrom mlos.OptimizerEvaluationTools.SyntheticFunctions.EnvelopedWaves import EnvelopedWaves, enveloped_waves_config_store\r\nfrom mlos.Spaces import CategoricalDimension, ContinuousDimension, DiscreteDimension, Point, SimpleHypergrid, Hypergrid\r\nfrom mlos.Spaces.Configs import ComponentConfigStore\r\nfrom mlos.Utils.KeyOrderedDict import KeyOrderedDict\r\n\r\n\r\nmulti_objective_enveloped_waves_config_space = SimpleHypergrid(\r\n name=\"multi_objective_enveloped_waves_config\",\r\n dimensions=[\r\n DiscreteDimension(name=\"num_objectives\", min=1, max=10),\r\n ContinuousDimension(name=\"phase_difference\", min=0, max=2 * math.pi),\r\n ContinuousDimension(name=\"period_change\", min=1, max=1.2),\r\n CategoricalDimension(name=\"single_objective_function\", values=[EnvelopedWaves.__name__])\r\n ]\r\n).join(\r\n on_external_dimension=CategoricalDimension(name=\"single_objective_function\", values=[EnvelopedWaves.__name__]),\r\n subgrid=enveloped_waves_config_store.parameter_space\r\n)\r\n\r\nmulti_objective_enveloped_waves_config_store = ComponentConfigStore(\r\n parameter_space=multi_objective_enveloped_waves_config_space,\r\n default=Point(\r\n num_objectives=2,\r\n phase_difference=0.5 * math.pi,\r\n period_change=1.0,\r\n single_objective_function=EnvelopedWaves.__name__,\r\n enveloped_waves_config=enveloped_waves_config_store.default\r\n ),\r\n description=\"TODO\"\r\n)\r\n\r\nmulti_objective_enveloped_waves_config_store.add_config_by_name(\r\n config_name=\"no_phase_difference\",\r\n config_point=Point(\r\n num_objectives=2,\r\n phase_difference=0,\r\n period_change=1.0,\r\n single_objective_function=EnvelopedWaves.__name__,\r\n enveloped_waves_config=enveloped_waves_config_store.default\r\n ),\r\n description=\"This function should produce a pareto frontier consisting of a single point at all parameter values equal to (math.pi / 2).\"\r\n)\r\n\r\nmulti_objective_enveloped_waves_config_store.add_config_by_name(\r\n config_name=\"half_pi_phase_difference\",\r\n config_point=Point(\r\n num_objectives=2,\r\n phase_difference=math.pi / 2,\r\n period_change=1.0,\r\n single_objective_function=EnvelopedWaves.__name__,\r\n enveloped_waves_config=enveloped_waves_config_store.default\r\n ),\r\n description=\"This function should produce a pareto frontier consisting of points in a quarter cricle in a first quadrat with the radius equal to 3.\"\r\n)\r\n\r\nmulti_objective_enveloped_waves_config_store.add_config_by_name(\r\n config_name=\"pi_phase_difference\",\r\n config_point=Point(\r\n num_objectives=2,\r\n phase_difference=math.pi,\r\n period_change=1.0,\r\n single_objective_function=EnvelopedWaves.__name__,\r\n enveloped_waves_config=enveloped_waves_config_store.default\r\n ),\r\n description=\"This function should produce a pareto frontier consisting of points on a diagonal of a square centered on the origin\"\r\n \" with side length equal to 18.\"\r\n)\r\n\r\nclass MultiObjectiveEnvelopedWaves(ObjectiveFunctionBase):\r\n \"\"\"Multi-objective function with many useful properties.\r\n The way it works is that we pass the same parameters through 1 or more single-objective enveloped waves functions.\r\n One useful property is that we not only know where the optima for individual functions are (maxima of sine are easy to find),\r\n but we can also know and control the shape of the pareto frontier, by controlling the phase difference between the individual\r\n objectives. For example: a phase difference of 0, means that that the objective functions are overlaid on top of each other\r\n and their optima are exactly on top of each other, so the pareto frontier is a single, optimal point\r\n Alternatively, the phase difference of quarter-period, introduces a trade-off between the objectives where\r\n y0 = sin(x)\r\n and\r\n y1 = sin(x - math.pi / 2) = -cos(x)\r\n which yields a pareto frontier in a shape of a quarter-cirle of radius 1 (or amplitude more generally).\r\n Yet another option is to use a phase difference of math.pi. This yields a trade-off between the objectives where:\r\n y0 = sin(x)\r\n and\r\n y1 = sin(x - math.pi) = -sin(x) = -y0\r\n which yields a pareto frontier where a gain in one objective results in an equal loss in the other objective, so the shape\r\n of that frontier is a diagonal of a square with side length equal to amplitude.\r\n \"\"\"\r\n\r\n def __init__(self, objective_function_config: Point = None):\r\n assert objective_function_config in multi_objective_enveloped_waves_config_space\r\n ObjectiveFunctionBase.__init__(self, objective_function_config)\r\n single_objective_enveloped_waves_config = objective_function_config.enveloped_waves_config\r\n self._individual_objectives = KeyOrderedDict(\r\n ordered_keys=[f\"y{objective_id}\" for objective_id in range(objective_function_config.num_objectives)],\r\n value_type=EnvelopedWaves\r\n )\r\n\r\n for objective_id in range(objective_function_config.num_objectives):\r\n config = single_objective_enveloped_waves_config.copy()\r\n config.phase_shift += objective_function_config.phase_difference * objective_id\r\n config.period *= objective_function_config.period_change ** objective_id\r\n\r\n while config.period > enveloped_waves_config_store.parameter_space[\"period\"].max:\r\n config.period -= enveloped_waves_config_store.parameter_space[\"period\"].max\r\n\r\n while config.phase_shift > enveloped_waves_config_store.parameter_space[\"phase_shift\"].max:\r\n config.phase_shift -= enveloped_waves_config_store.parameter_space[\"phase_shift\"].max\r\n\r\n self._individual_objectives[objective_id] = EnvelopedWaves(objective_function_config=config)\r\n\r\n self._parameter_space = self._individual_objectives[0].parameter_space\r\n self._output_space = SimpleHypergrid(\r\n name=\"range\",\r\n dimensions=[\r\n ContinuousDimension(name=f\"y{objective_id}\", min=-math.inf, max=math.inf)\r\n for objective_id in range(objective_function_config.num_objectives)\r\n ]\r\n )\r\n\r\n @property\r\n def parameter_space(self) -> Hypergrid:\r\n return self._parameter_space\r\n\r\n @property\r\n def output_space(self) -> Hypergrid:\r\n return self._output_space\r\n\r\n def evaluate_dataframe(self, dataframe: pd.DataFrame) -> pd.DataFrame:\r\n results_df = pd.DataFrame()\r\n for objective_dim_name, individual_objective_function in self._individual_objectives:\r\n single_objective_df = individual_objective_function.evaluate_dataframe(dataframe)\r\n results_df[objective_dim_name] = single_objective_df['y']\r\n return results_df\r\n\r\n def get_context(self) -> Point:\r\n return self.objective_function_config\r\n" ]
[ [ "pandas.DataFrame" ] ]
victor45664/espnet
[ "0ccacc32d25feddec5270cb3f8e08c24183755d8" ]
[ "espnet2/VC_SRC/preprocessing/cal_target_mel_kaldi_format.py" ]
[ "\nimport sys\nsys.path.append('')\nimport numpy as np\nimport os\nimport pandas as pd\nimport kaldi_io\n\nfrom espnet2.VC_SRC import melspectrogram,load_wav\nimport librosa\n\ndef load_wav(path):\n return librosa.core.load(path, sr=24000)[0]\n\n\ndef cal_mel_target(data_dir):\n wav_scp_path=os.path.join(data_dir,\"wav.scp\")\n ark_path=os.path.join(data_dir,\"feats.ark\")\n\n wav_scp = pd.read_csv(wav_scp_path, header=None, delim_whitespace=True, names=['key', 'wav_path'])\n with open(ark_path, 'wb') as f:\n for i in range(len(wav_scp)):\n utt_id = wav_scp['key'][i]\n wav_path = wav_scp['wav_path'][i]\n\n\n\n wav = load_wav(wav_path)\n mel_spectrogram = melspectrogram(wav).astype(np.float32) # 这里提取MFCC特征\n kaldi_io.write_mat(f, mel_spectrogram.T, key=utt_id)\n\n# def cal_mel_target(data_dir):\n# wav_scp_path=os.path.join(data_dir,\"wav.scp\")\n# ark_path=os.path.join(data_dir,\"feats.ark\")\n#\n# wav_scp = pd.read_csv(wav_scp_path, names=['code'])\n# wav_scp[['key', 'wav_path']] = wav_scp[\"code\"].str.split(\" \", 1, expand=True)\n# temp_wav_path=os.path.join(data_dir, \"temp.wav\")\n# with open(ark_path, 'wb') as f:\n# for i in range(len(wav_scp)):\n# utt_id=wav_scp['key'][i]\n# wav_path=wav_scp['wav_path'][i]\n#\n# cmd=wav_path[:-3]+temp_wav_path\n#\n# os.system(cmd)\n#\n# wav = load_wav(temp_wav_path)\n# mel_spectrogram = melspectrogram(wav).astype(np.float32) # 这里提取MFCC特征\n# kaldi_io.write_mat(f, mel_spectrogram.T, key=utt_id)\n\n\n\nif __name__ == '__main__':\n import sys\n\n\n data_dir=sys.argv[1]\n\n cal_mel_target(data_dir)\n\n # from subprocess import PIPE, run\n # import subprocess\n #\n #\n # cmd='sox --vol 0.221527020709 -t wav $root_path/Data/056020296.WAV -t wav -'\n # output = subprocess.Popen(cmd)\n # wav = np.fromstring(output, dtype=np.float32)\n #\n # print(wav.shape)\n\n # cmd='King-ASR-166_056020292 sox --vol 0.221527020709 -t wav $root_path/Data/056020296.WAV -t wav - |'\n # f=os.popen(cmd)\n # wav=load_wav(f)\n\n\n\n\n\n\n\n\n\n\n" ]
[ [ "pandas.read_csv" ] ]
wesm/duckdb
[ "f2fa094abc59d70a8c981d6e9f9c9c3911f08362" ]
[ "tools/pythonpkg/tests/pandas/test_timestamp.py" ]
[ "import duckdb\nimport os\nimport sys\nimport datetime\nimport pytest\nimport pandas as pd\n\nclass TestPandasTimestamps(object):\n def test_timestamp_types_roundtrip(self, duckdb_cursor):\n d = {'a': [pd.Timestamp(datetime.datetime.now(), unit='s')], 'b': [pd.Timestamp(datetime.datetime.now(), unit='ms')], 'c': [pd.Timestamp(datetime.datetime.now(), unit='us')], 'd': [pd.Timestamp(datetime.datetime.now(), unit='ns')]}\n df = pd.DataFrame(data=d)\n df_from_duck = duckdb.from_df(df).df()\n assert(df_from_duck.equals(df))\n\n def test_timestamp_nulls(self, duckdb_cursor):\n d = {'a': [pd.Timestamp(None, unit='s')], 'b': [pd.Timestamp(None, unit='ms')], 'c': [pd.Timestamp(None, unit='us')], 'd': [pd.Timestamp(None, unit='ns')]}\n df = pd.DataFrame(data=d)\n df_from_duck = duckdb.from_df(df).df()\n assert (df_from_duck.equals(df))\n\n def test_timestamp_timedelta(self, duckdb_cursor):\n df = pd.DataFrame({'a': [pd.Timedelta(1, unit='s')], 'b': [pd.Timedelta(None, unit='s')], 'c': [pd.Timedelta(1, unit='us')] , 'd': [pd.Timedelta(1, unit='ms')]})\n df_from_duck = duckdb.from_df(df).df()\n assert (df_from_duck.equals(df))" ]
[ [ "pandas.DataFrame", "pandas.Timestamp", "pandas.Timedelta" ] ]
TiagoFilipeSousaGoncalves/web-scrapping-project
[ "06a308a453c81a7fd7b39bda6b783683bdf2c3a0" ]
[ "code/chexpert_generate_results_plots.py" ]
[ "# Imports\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport os\n\n\n# Results directory\ndirectory = os.path.join(\"results\", \"chexpert\", \"history\")\nfigs_directory = os.path.join(\"results\", \"chexpert\", \"figures\")\n\n\n# Models\nMODELS = [\"densenet121\", \"resnet50\", \"vgg16\"]\n\n# Training Formats\nTRAINING_MODE = [\"baseline\", \"baselinedaug\", \"mldam\", \"mldamdaug\"]\n\n\n\n# Go through models\nfor model in MODELS:\n\n # Go through mode of training\n for train_mode in TRAINING_MODE:\n\n # Get filenames\n # Train\n train_losses = np.load(os.path.join(directory, f\"{model}_{train_mode}_tr_losses.npy\"), allow_pickle=True)\n train_metrics = np.load(os.path.join(directory, f\"{model}_{train_mode}_tr_metrics.npy\"), allow_pickle=True)\n \n # Validation\n val_losses = np.load(os.path.join(directory, f\"{model}_{train_mode}_val_losses.npy\"), allow_pickle=True)\n val_metrics = np.load(os.path.join(directory, f\"{model}_{train_mode}_val_metrics.npy\"), allow_pickle=True)\n\n\n\n # Plot losses\n plt.title(f\"{model.upper()} | {train_mode.upper()}\")\n plt.plot(range(len(train_losses)), train_losses, label=\"Train\")\n plt.plot(range(len(val_losses)), val_losses, label=\"Validation\")\n plt.ylabel(\"Loss\")\n plt.xlabel(\"Epoch\")\n plt.legend()\n plt.savefig(os.path.join(figs_directory, f\"{model.lower()}_{train_mode.lower()}_loss.png\"))\n # plt.show()\n plt.clf()\n\n\n # Plot metrics\n metrics_dict = {0:\"Accuracy\", 1:\"Recall\", 2:\"Precision\", 3:\"F1-Score\"}\n for metric in range(4):\n metric_name = metrics_dict[metric]\n\n plt.title(f\"{model.upper()} | {train_mode.upper()}\")\n plt.plot(range(train_metrics.shape[0]), train_metrics[:, metric], label=\"Train\")\n plt.plot(range(val_metrics.shape[0]), val_metrics[:, metric], label=\"Validation\")\n plt.ylabel(f\"{metric_name}\")\n plt.xlabel(\"Epoch\")\n plt.legend()\n plt.savefig(os.path.join(figs_directory, f\"{model.lower()}_{train_mode.lower()}_{metric_name.lower()}.png\"))\n # plt.show()\n plt.clf()" ]
[ [ "matplotlib.pyplot.clf", "matplotlib.pyplot.xlabel", "matplotlib.pyplot.legend", "matplotlib.pyplot.ylabel" ] ]
exowanderer/exoplanet
[ "dfd4859525ca574f1936de7b683951c35c292586" ]
[ "exoplanet/theano_ops/starry/limbdark_test.py" ]
[ "# -*- coding: utf-8 -*-\n\nfrom __future__ import division, print_function\n\nimport numpy as np\n\nimport theano\nimport theano.tensor as tt\nfrom theano.tests import unittest_tools as utt\n\nfrom .limbdark import LimbDarkOp\n\n\nclass TestLimbDark(utt.InferShapeTester):\n\n def setUp(self):\n super(TestLimbDark, self).setUp()\n self.op_class = LimbDarkOp\n self.op = LimbDarkOp()\n\n def get_args(self):\n c = tt.vector()\n b = tt.vector()\n r = tt.vector()\n los = tt.vector()\n f = theano.function([c, b, r, los], self.op(c, b, r, los)[0])\n\n c_val = np.array([-0.85, 2.5, -0.425, 0.1])\n b_val = np.linspace(-1.5, 1.5, 100)\n r_val = 0.1 + np.zeros_like(b_val)\n los_val = np.ones_like(b_val)\n\n return f, [c, b, r, los], [c_val, b_val, r_val, los_val]\n\n def test_basic(self):\n f, _, in_args = self.get_args()\n out = f(*in_args)\n utt.assert_allclose(0.0, out[0])\n utt.assert_allclose(0.0, out[-1])\n\n def test_los(self):\n f, _, in_args = self.get_args()\n in_args[-1] = -np.ones_like(in_args[-1])\n out = f(*in_args)\n utt.assert_allclose(0.0, out)\n\n def test_infer_shape(self):\n f, args, arg_vals = self.get_args()\n self._compile_and_check(args,\n self.op(*args),\n arg_vals,\n self.op_class)\n\n def test_grad(self):\n _, _, in_args = self.get_args()\n func = lambda *args: self.op(*args)[0] # NOQA\n utt.verify_grad(func, in_args)\n" ]
[ [ "numpy.zeros_like", "numpy.array", "numpy.ones_like", "numpy.linspace" ] ]
charudattapokale/Image
[ "881aaa078a400ef36906847eb23f2700ed640124" ]
[ "dataloader/datareader.py" ]
[ "# -*- coding: utf-8 -*-\nimport numpy as np\nimport sys\nsys.path.append('../')\nimport os\nimport random\nimport cv2\nimport matplotlib.pyplot as plt\nfrom tensorflow.python.keras.preprocessing.image import ImageDataGenerator\n\n\n\ndef read_image(path):\n \n img_path_labels_list=[os.path.join(path, img) for img in os.listdir(path) if img.endswith(\"_L.png\")]\n img_path_features_list=[feature for feature in [os.path.join(path, img) for img in os.listdir(path)] if feature not in img_path_labels_list and feature.endswith(\".png\")] \n \n img_path_labels_list = sorted(img_path_labels_list)\n img_path_features_list = sorted(img_path_features_list)\n \n feature = np.array([cv2.resize(img,(256,128) , interpolation = cv2.INTER_AREA) for img in\n [cv2.imread(i) for i in img_path_features_list]])\n label = np.array([cv2.resize(img,(256,128) , interpolation = cv2.INTER_AREA) for img in\n [cv2.imread(l) for l in img_path_labels_list]])\n return feature,label\n\n\n\ndef pre_processing(img):\n ''' Random exposure and saturation (0.9 ~ 1.1 scale)'''\n \n rand_s = random.uniform(0.9, 1.1)\n rand_v = random.uniform(0.9, 1.1)\n\n img = cv2.cvtColor(img, cv2.COLOR_RGB2HSV)\n\n tmp = np.ones_like(img[:, :, 1]) * 255\n img[:, :, 1] = np.where(img[:, :, 1] * rand_s > 255, tmp, img[:, :, 1] * rand_s)\n img[:, :, 2] = np.where(img[:, :, 2] * rand_v > 255, tmp, img[:, :, 2] * rand_v)\n\n img = cv2.cvtColor(img, cv2.COLOR_HSV2RGB)\n\n # normalization of image \n return img / 127.5 - 1\n\n\n\ndef get_data_gen_args(mode):\n ''' Get ImageDataGenerator arguments(options) depends on mode - (train, val, test)'''\n \n if mode == 'train' or mode == 'val':\n x_data_gen_args = dict(preprocessing_function=pre_processing,\n shear_range=0.1,\n zoom_range=0.1,\n rotation_range=10,\n width_shift_range=0.1,\n height_shift_range=0.1,\n fill_mode='constant',\n horizontal_flip=True)\n\n y_data_gen_args = dict(shear_range=0.1,\n zoom_range=0.1,\n rotation_range=10,\n width_shift_range=0.1,\n height_shift_range=0.1,\n fill_mode='constant',\n horizontal_flip=True)\n\n elif mode == 'test':\n x_data_gen_args = dict(preprocessing_function=pre_processing)\n y_data_gen_args = dict()\n\n else:\n print(\"Invalid mode only 'train' or 'val' or 'test' allowed\")\n return -1\n\n return x_data_gen_args, y_data_gen_args\n\n\n\ndef get_result_map(batch_size, label_img):\n '''One hot encoding for label_img.'''\n \n #label_img = np.squeeze(label_img, axis=-1)\n result_map = np.zeros((batch_size, 128, 256, 4),dtype = np.uint8)\n \n # For np.where calculation.\n building = (label_img == [0 ,0, 128]).all(axis = -1) #bgr\n car = (label_img == [128,0,64]).all(axis = -1) #BGR\n road = (label_img == [128,64,128]).all(axis = -1)\n background = np.logical_not(building + car + road)\n\n result_map[:, :, :, 0] = np.where(building, 1, 0)\n result_map[:, :, :, 1] = np.where(car, 1, 0)\n result_map[:, :, :, 2] = np.where(road, 1, 0)\n result_map[:, :, :, 3] = np.where(background, 1, 0)\n\n return result_map\n\n\n\ndef data_generator(dir_path, batch_size, mode):\n '''Data generator for fit_generator'''\n \n \n x_imgs,y_imgs = read_image(dir_path)\n a = y_imgs.shape\n print(f\"**********************{a}***************\")\n \n # Make ImageDataGenerator.\n x_data_gen_args, y_data_gen_args = get_data_gen_args(mode)\n x_data_gen = ImageDataGenerator(**x_data_gen_args)\n y_data_gen = ImageDataGenerator(**y_data_gen_args)\n\n # random index for random data access.\n d_size = x_imgs.shape[0]\n shuffled_idx = list(range(d_size))\n\n x = []\n y = []\n while True:\n random.shuffle(shuffled_idx)\n for i in range(d_size):\n idx = shuffled_idx[i]\n\n x.append(x_imgs[idx].reshape((128, 256, 3)))\n y.append(y_imgs[idx].reshape((128, 256, 3)))\n\n if len(x) == batch_size:\n # Adapt ImageDataGenerator flow method for data augmentation.\n _ = np.zeros(batch_size)\n seed = random.randrange(1, 1000)\n\n x_tmp_gen = x_data_gen.flow(np.array(x), _,\n batch_size=batch_size,\n seed=seed)\n y_tmp_gen = y_data_gen.flow(np.array(y), _,\n batch_size=batch_size,\n seed=seed)\n\n # Finally, yield x, y data.\n x_result, _ = next(x_tmp_gen)\n y_result, _ = next(y_tmp_gen)\n\n yield x_result, get_result_map(batch_size, y_result)\n\n x.clear()\n y.clear()\n\n\n \n\nif __name__ == \"__main__\":\n feature,label = read_image(DATASET_PATH)" ]
[ [ "numpy.logical_not", "numpy.array", "numpy.ones_like", "numpy.zeros", "numpy.where", "tensorflow.python.keras.preprocessing.image.ImageDataGenerator" ] ]
space-technologies-at-california/simple-space-simulator
[ "52c0d791fed7f5804059c7680345c6865e88d247" ]
[ "simple_space_simulator/physics.py" ]
[ "import numpy as np\nimport pyIGRF\n\nimport simple_space_simulator.utils as utils\nimport simple_space_simulator.cubesat as cube\nfrom simple_space_simulator import constants\n\n\nclass Simulator:\n \"\"\"\n This class handles the step by step calculations required to simulate an orbiting body and\n the interactions with multiple forcers, torquers, and accelerators\n \"\"\"\n\n def __init__(self, cubesat, planet, state, dt=0.1):\n \"\"\"\n Parameters\n ----------\n cubesat : Cubesat\n The orbiting cubesat object\n planet : Planet\n The planet that the cubesat object will be orbiting\n state : State\n Initial state of the simulation\n dt : float, optional\n The time between steps of the simulation\n\n Returns\n -------\n Simulator\n A simulator object that can be stepped through and used with a renderer object\n \"\"\"\n assert isinstance(cubesat, cube.Cubesat), \"cubesat must be a Cubesat object\"\n assert isinstance(planet, Planet), \"planet must be a Planet object\"\n assert isinstance(state, cube.State), \"state must be a State object\"\n assert isinstance(dt, (int, float)) and dt > 0, \"dt must be a positive value\"\n self.dt = dt\n self.cubesat = cubesat\n self.planet = planet\n self.elapsed_time = 0\n self.state = state\n # functions that take in a state and returns a force vector <Fx,Fy,Fz> acting on the COM of the cubesat\n self.forces = []\n # functions that take in a state and returns an acceleration vector <ax,ay,az> acting on the COM of the cubesat\n self.accelerations = []\n # function that takes in a state and returns a torque vector <tx, ty, tz> acting around the COM of the\n # cubesat with inertia I\n self.torques = []\n # function that takes in a state and returns an angular acceleration vector <alphax, alphay, alphaz> acting\n # around the COM\n self.angular_accelerations = []\n\n # The new state is provided by the following equation\n # xk = Axk-1 + Buk-1 + wk-1\n # u is the vector sum of all the accelerations\n\n # 3D state matrix - A\n self.A = np.array([[1, 0, 0, self.dt, 0, 0],\n [0, 1, 0, 0, self.dt, 0],\n [0, 0, 1, 0, 0, self.dt],\n [0, 0, 0, 1, 0, 0],\n [0, 0, 0, 0, 1, 0],\n [0, 0, 0, 0, 0, 1]])\n\n # 3D control matrix - B\n self.B = np.array([[1 / 2 * self.dt ** 2, 0, 0],\n [0, 1 / 2 * self.dt ** 2, 0],\n [0, 0, 1 / 2 * self.dt ** 2],\n [self.dt, 0, 0],\n [0, self.dt, 0],\n [0, 0, self.dt]])\n\n def step(self):\n \"\"\"\n Computes the accelerations for the current time step given state S.\n Returns\n -------\n tuple\n A tuple that contains the elapsed time and the new state\n \"\"\"\n net_force = np.zeros(3)\n for forcer in self.forces:\n net_force += forcer(self.state, self.cubesat, self.planet)\n\n net_acc = np.zeros(3)\n for accelerator in self.accelerations:\n net_acc += accelerator(self.state, self.cubesat, self.planet)\n\n net_acc += net_force / self.cubesat.mass\n\n net_torque = np.zeros(3)\n for torquer in self.torques:\n net_torque += torquer(self.state, self.cubesat, self.planet)\n\n net_angular_acc = np.zeros(3)\n for angular_accelerator in self.angular_accelerations:\n net_angular_acc += angular_accelerator(self.state, self.cubesat, self.planet)\n\n net_angular_acc += np.dot(self.cubesat.inertia_inv, net_torque)\n\n angular_velocity = self.state.get_angular_velocity_vector() + net_angular_acc * self.dt\n\n # https://math.stackexchange.com/questions/39553/how-do-i-apply-an-angular-velocity-vector3-to-a-unit-quaternion-orientation\n w = angular_velocity * self.dt\n\n w_norm = np.linalg.norm(w)\n w_f = w * np.sin(w_norm / 2) / w_norm if w_norm != 0 else [0, 0, 0]\n q = utils.quaternion_multiply(\n np.array([np.cos(w_norm / 2), w_f[0], w_f[1], w_f[2]]),\n self.state.get_orientation_quaternion())\n\n a = 1/2 * net_angular_acc * self.dt ** 2\n a_norm = np.linalg.norm(a)\n a_f = a * np.sin(a_norm / 2) / a_norm if a_norm != 0 else [0, 0, 0]\n q = utils.quaternion_multiply(np.array([np.cos(a_norm / 2), a_f[0], a_f[1], a_f[2]]), q)\n\n q /= np.linalg.norm(q)\n\n # A*state + B*acceleration\n self.state = cube.state_from_vectors(\n np.dot(self.A, self.state.get_cartesian_state_vector()) + np.dot(self.B, net_acc), q, angular_velocity)\n self.elapsed_time += self.dt\n return self.elapsed_time, self.state\n\n def add_forcer(self, forcer):\n assert callable(forcer), \"forcer must be a function\"\n self.forces.append(forcer)\n\n def add_accelerator(self, accelerator):\n assert callable(accelerator), \"accelerator must be a function\"\n self.accelerations.append(accelerator)\n\n def add_torquer(self, torquer):\n assert callable(torquer), \"torquer must be a function\"\n self.torques.append(torquer)\n\n def add_angular_accelerator(self, angular_accelerator):\n assert callable(angular_accelerator), \"angular_accelerator must be a function\"\n self.angular_accelerations.append(angular_accelerator)\n\n\nclass Planet:\n def __init__(self, mass, radius, magnetic_field_model=pyIGRF):\n assert isinstance(mass, (int, float)) and mass > 0, \"mass must be a positive value\"\n assert isinstance(radius, (int, float)) and radius > 0, \"radius must be a positive value\"\n self.radius = radius # m\n self.mass = mass # kg\n self.magnetic_field_model = magnetic_field_model\n\n def get_gravitational_acceleration(self, state):\n assert isinstance(state, cube.State), \"state must be a State object\"\n r_hat = state.state_vector[:3] / np.linalg.norm(state.state_vector[:3])\n a = -constants.G * self.mass / np.linalg.norm(state.state_vector[:3]) ** 2 * r_hat\n return a\n\n def get_magnetic_field(self, state, ecef=True):\n assert isinstance(state, cube.State), \"state must be a State object\"\n assert isinstance(ecef, bool), \"ecef must be a boolean\"\n # D: declination (+ve east)\n # I: inclination (+ve down)\n # H: horizontal intensity\n # X: north component\n # Y: east component\n # Z: vertical component (+ve down)\n # F: total intensity\n # unit: degree or nT\n s = self.magnetic_field_model.igrf_value(\n state.get_lat(), state.get_lon(), state.get_r() - constants.R_EARTH, 1999)\n magnetic_field_vector = np.array([s[3], s[4], s[5]]) / 1e9 # converted to T\n if ecef:\n return state.ned_to_ecef(magnetic_field_vector)\n return state\n" ]
[ [ "numpy.array", "numpy.dot", "numpy.sin", "numpy.linalg.norm", "numpy.zeros", "numpy.cos" ] ]
mehrdad-shokri/spartan
[ "854b26e3af75910ef57b874db7853abd4249543e" ]
[ "modules/spartan/utils/utils.py" ]
[ "__author__ = 'manuelli'\nimport numpy as np\nimport collections\nimport yaml\nfrom yaml import CLoader\nimport os\nimport datetime\nimport time\n\n# director\nfrom director import transformUtils\n\nimport spartan.utils.transformations as transformations\n\n\ndef getSpartanSourceDir():\n return os.getenv(\"SPARTAN_SOURCE_DIR\")\n\n\ndef get_sandbox_dir():\n return os.getenv(\"SPARTAN_SANDBOX_DIR\")\n\ndef get_data_dir():\n return os.getenv(\"DATA_DIR\")\n\ndef getDictFromYamlFilename(filename):\n \"\"\"\n Read data from a YAML files\n \"\"\"\n return yaml.load(file(filename), Loader=CLoader)\n\ndef saveToYaml(data, filename):\n with open(filename, 'w') as outfile:\n yaml.dump(data, outfile, default_flow_style=False)\n\ndef poseFromTransform(transform):\n pos, quat = transformUtils.poseFromTransform(transform)\n pos = pos.tolist()\n quat = quat.tolist()\n d = dict()\n d['translation'] = dict()\n d['translation']['x'] = pos[0]\n d['translation']['y'] = pos[1]\n d['translation']['z'] = pos[2]\n\n d['quaternion'] = dict()\n d['quaternion']['w'] = quat[0]\n d['quaternion']['x'] = quat[1]\n d['quaternion']['y'] = quat[2]\n d['quaternion']['z'] = quat[3]\n\n return d\n\ndef dictFromPosQuat(pos, quat):\n d = dict()\n d['translation'] = dict()\n d['translation']['x'] = pos[0]\n d['translation']['y'] = pos[1]\n d['translation']['z'] = pos[2]\n\n d['quaternion'] = dict()\n d['quaternion']['w'] = quat[0]\n d['quaternion']['x'] = quat[1]\n d['quaternion']['y'] = quat[2]\n d['quaternion']['z'] = quat[3]\n\n return d\n\ndef transformFromPose(d):\n pos = [0]*3\n pos[0] = d['translation']['x']\n pos[1] = d['translation']['y']\n pos[2] = d['translation']['z']\n\n quatDict = getQuaternionFromDict(d)\n quat = [0]*4\n quat[0] = quatDict['w']\n quat[1] = quatDict['x']\n quat[2] = quatDict['y']\n quat[3] = quatDict['z']\n\n return transformUtils.transformFromPose(pos, quat)\n\ndef homogenous_transform_from_dict(d):\n \"\"\"\n Returns a transform from a standard encoding in dict format\n :param d:\n :return:\n \"\"\"\n pos = [0]*3\n pos[0] = d['translation']['x']\n pos[1] = d['translation']['y']\n pos[2] = d['translation']['z']\n\n quatDict = getQuaternionFromDict(d)\n quat = [0]*4\n quat[0] = quatDict['w']\n quat[1] = quatDict['x']\n quat[2] = quatDict['y']\n quat[3] = quatDict['z']\n\n transform_matrix = transformations.quaternion_matrix(quat)\n transform_matrix[0:3,3] = np.array(pos)\n\n return transform_matrix\n\n\"\"\"\nmsg: geometry_msgs/Pose\n\"\"\"\ndef transformFromROSPoseMsg(msg):\n pos = [msg.position.x, msg.position.y, msg.position.z]\n quat = [msg.orientation.w, msg.orientation.x, msg.orientation.y, msg.orientation.z]\n\n return transformUtils.transformFromPose(pos,quat)\n\ndef transformFromROSTransformMsg(msg):\n pos = [msg.translation.x, msg.translation.y, msg.translation.z]\n quat = [msg.rotation.w, msg.rotation.x, msg.rotation.y, msg.rotation.z]\n\n return transformUtils.transformFromPose(pos,quat)\n\ndef getQuaternionFromDict(d):\n quat = None\n quatNames = ['orientation', 'rotation', 'quaternion']\n for name in quatNames:\n if name in d:\n quat = d[name]\n\n\n if quat is None:\n raise ValueError(\"Error when trying to extract quaternion from dict, your dict doesn't contain a key in ['orientation', 'rotation', 'quaternion']\")\n\n return quat\n\ndef get_current_time_unique_name():\n \"\"\"\n Converts current date to a unique name\n\n Note: this function will return variable-length strings.\n\n :return:\n :rtype: str\n \"\"\"\n\n unique_name = time.strftime(\"%Y%m%d-%H%M%S\")\n return unique_name\n\ndef homogenous_transform_from_dict(d):\n \"\"\"\n Returns a transform from a standard encoding in dict format\n :param d:\n :return:\n \"\"\"\n pos = [0]*3\n pos[0] = d['translation']['x']\n pos[1] = d['translation']['y']\n pos[2] = d['translation']['z']\n\n quatDict = getQuaternionFromDict(d)\n quat = [0]*4\n quat[0] = quatDict['w']\n quat[1] = quatDict['x']\n quat[2] = quatDict['y']\n quat[3] = quatDict['z']\n\n transform_matrix = transformations.quaternion_matrix(quat)\n transform_matrix[0:3,3] = np.array(pos)\n\n return transform_matrix\n\ndef dict_from_homogenous_transform(tf):\n \"\"\"\n Returns standard encoding in dict format from 4x4 transform matrix\n :param tf:\n :return:\n \"\"\"\n return dictFromPosQuat(tf[:3, 3], transformations.quaternion_from_matrix(tf))\n\ndef apply_homogenous_transform_to_points(tf, pts):\n ''' Given a homogenous tf matrix and a 3xN NP array\n of points, apply the tf to the points to produce\n a new 3xN array of points.\n :param tf: 4x4 numpy array of matching dtype to pts\n :param pts: 3xN numpy array of matching dtype to tf\n :return: 3xN numpy array of matching dtype to tf and pts'''\n return ((tf[:3, :3].dot(pts).T) + tf[:3, 3]).T\n\ndef get_current_YYYY_MM_DD_hh_mm_ss():\n \"\"\"\n Returns a string identifying the current:\n - year, month, day, hour, minute, second\n\n Using this format:\n\n YYYY-MM-DD-hh-mm-ss\n\n For example:\n\n 2018-04-07-19-02-50\n\n Note: this function will always return strings of the same length.\n\n :return: current time formatted as a string\n :rtype: string\n\n \"\"\"\n\n now = datetime.datetime.now()\n string = \"%0.4d-%0.2d-%0.2d-%0.2d-%0.2d-%0.2d\" % (now.year, now.month, now.day, now.hour, now.minute, now.second)\n return string\n\ndef compute_angle_between_quaternions(q, r):\n \"\"\"\n Computes the angle between two quaternions.\n\n theta = arccos(2 * <q1, q2>^2 - 1)\n\n See https://math.stackexchange.com/questions/90081/quaternion-distance\n :param q: numpy array in form [w,x,y,z]. As long as both q,r are consistent it doesn't matter\n :type q:\n :param r:\n :type r:\n :return: angle between the quaternions, in radians\n :rtype:\n \"\"\"\n\n theta = 2*np.arccos(2 * np.dot(q,r)**2 - 1)\n return theta\n\ndef compute_translation_distance_between_poses(pose_a, pose_b):\n \"\"\"\n Computes the linear difference between pose_a and pose_b\n :param pose_a: 4 x 4 homogeneous transform\n :type pose_a:\n :param pose_b:\n :type pose_b:\n :return: Distance between translation component of the poses\n :rtype:\n \"\"\"\n\n pos_a = pose_a[0:3,3]\n pos_b = pose_b[0:3,3]\n\n return np.linalg.norm(pos_a - pos_b)\n\ndef compute_angle_between_poses(pose_a, pose_b):\n \"\"\"\n Computes the angle distance in radians between two homogenous transforms\n :param pose_a: 4 x 4 homogeneous transform\n :type pose_a:\n :param pose_b:\n :type pose_b:\n :return: Angle between poses in radians\n :rtype:\n \"\"\"\n\n quat_a = transformations.quaternion_from_matrix(pose_a)\n quat_b = transformations.quaternion_from_matrix(pose_b)\n\n return compute_angle_between_quaternions(quat_a, quat_b)\n\ndef get_kuka_joint_names():\n return [\n 'iiwa_joint_1', 'iiwa_joint_2', 'iiwa_joint_3',\n 'iiwa_joint_4', 'iiwa_joint_5', 'iiwa_joint_6',\n 'iiwa_joint_7']\n" ]
[ [ "numpy.array", "numpy.linalg.norm", "numpy.dot" ] ]
cdesira/astroML
[ "503dc95945afdf7dcbe04d0e12cb4bf813bb98a5" ]
[ "astroML/filters.py" ]
[ "import numpy as np\nfrom scipy import optimize, fftpack, signal\n\n\n# Note: there is a scipy PR to include an improved SG filter within the\n# scipy.signal submodule. It should replace this when it's finished.\n# see http://github.com/scipy/scipy/pull/304\ndef savitzky_golay(y, window_size, order, deriv=0,\n use_fft=True):\n r\"\"\"Smooth (and optionally differentiate) data with a Savitzky-Golay filter\n\n This implementation is based on [1]_.\n\n The Savitzky-Golay filter removes high frequency noise from data.\n It has the advantage of preserving the original shape and\n features of the signal better than other types of filtering\n approaches, such as moving averages techhniques.\n\n Parameters\n ----------\n y : array_like, shape (N,)\n the values of the time history of the signal.\n window_size : int\n the length of the window. Must be an odd integer number.\n order : int\n the order of the polynomial used in the filtering.\n Must be less then `window_size` - 1.\n deriv: int\n the order of the derivative to compute\n (default = 0 means only smoothing)\n use_fft : bool\n if True (default) then convolue using FFT for speed\n\n Returns\n -------\n y_smooth : ndarray, shape (N)\n the smoothed signal (or it's n-th derivative).\n\n Notes\n -----\n The Savitzky-Golay is a type of low-pass filter, particularly\n suited for smoothing noisy data. The main idea behind this\n approach is to make for each point a least-square fit with a\n polynomial of high order over a odd-sized window centered at\n the point.\n\n Examples\n --------\n >>> t = np.linspace(-4, 4, 500)\n >>> y = np.exp(-t ** 2)\n >>> np.random.seed(0)\n >>> y_noisy = y + np.random.normal(0, 0.05, t.shape)\n >>> y_smooth = savitzky_golay(y, window_size=31, order=4)\n >>> print(np.rms(y_noisy - y))\n >>> print(np.rms(y_smooth - y))\n\n References\n ----------\n .. [1] http://www.scipy.org/Cookbook/SavitzkyGolay\n .. [2] A. Savitzky, M. J. E. Golay, Smoothing and Differentiation of\n Data by Simplified Least Squares Procedures. Analytical\n Chemistry, 1964, 36 (8), pp 1627-1639.\n .. [3] Numerical Recipes 3rd Edition: The Art of Scientific Computing\n W.H. Press, S.A. Teukolsky, W.T. Vetterling, B.P. Flannery\n Cambridge University Press ISBN-13: 9780521880688\n \"\"\"\n try:\n window_size = np.abs(np.int(window_size))\n order = np.abs(np.int(order))\n except ValueError:\n raise ValueError(\"window_size and order have to be of type int\")\n\n if window_size % 2 != 1 or window_size < 1:\n raise TypeError(\"window_size size must be a positive odd number\")\n\n if window_size < order + 2:\n raise TypeError(\"window_size is too small for the polynomials order\")\n\n order_range = range(order + 1)\n\n half_window = (window_size - 1) // 2\n\n # precompute coefficients\n b = np.mat([[k ** i for i in order_range]\n for k in range(-half_window, half_window + 1)])\n m = np.linalg.pinv(b).A[deriv]\n\n # pad the signal at the extremes with\n # values taken from the signal itself\n firstvals = y[0] - np.abs(y[1:half_window + 1][::-1] - y[0])\n lastvals = y[-1] + np.abs(y[-half_window - 1:-1][::-1] - y[-1])\n\n y = np.concatenate((firstvals, y, lastvals))\n\n if use_fft:\n return signal.fftconvolve(y, m, mode='valid')\n else:\n return np.convolve(y, m, mode='valid')\n\n\ndef wiener_filter(t, h, signal='gaussian', noise='flat', return_PSDs=False,\n signal_params=None, noise_params=None):\n \"\"\"Compute a Wiener-filtered time-series\n\n Parameters\n ----------\n t : array_like\n evenly-sampled time series, length N\n h : array_like\n observations at each t\n signal : str (optional)\n currently only 'gaussian' is supported\n noise : str (optional)\n currently only 'flat' is supported\n return_PSDs : bool (optional)\n if True, then return (PSD, P_S, P_N)\n signal_guess : tuple (optional)\n A starting guess at the parameters for the signal. If not specified,\n a suitable guess will be estimated from the data itself. (see Notes\n below)\n noise_guess : tuple (optional)\n A starting guess at the parameters for the noise. If not specified,\n a suitable guess will be estimated from the data itself. (see Notes\n below)\n\n Returns\n -------\n h_smooth : ndarray\n a smoothed version of h, length N\n\n Notes\n -----\n The Wiener filter operates by fitting a functional form to the PSD::\n\n PSD = P_S + P_N\n\n The resulting frequency-space filter is given by::\n\n Phi = P_S / (P_S + P_N)\n\n This entire operation is equivalent to a kernel smoothing by a\n kernel whose Fourier transform is Phi.\n\n Choosing Signal/Noise Parameters\n ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n the arguments ``signal_guess`` and ``noise_guess`` specify the initial\n guess for the characteristics of signal and noise used in the minimization.\n They are generally expected to be tuples, and the meaning varies depending\n on the form of signal and noise used. For ``gaussian``, the params are\n (amplitude, width). For ``flat``, the params are (amplitude,).\n\n See Also\n --------\n scipy.signal.wiener : a static (non-adaptive) wiener filter\n \"\"\"\n # Validate signal\n if signal != 'gaussian':\n raise ValueError(\"only signal='gaussian' is supported\")\n if signal_params is not None and len(signal_params) != 2:\n raise ValueError(\"signal_params should be length 2\")\n\n # Validate noise\n if noise != 'flat':\n raise ValueError(\"only noise='flat' is supported\")\n if noise_params is not None and len(noise_params) != 1:\n raise ValueError(\"noise_params should be length 1\")\n\n # Validate t and hd\n t = np.asarray(t)\n h = np.asarray(h)\n\n if (t.ndim != 1) or (t.shape != h.shape):\n raise ValueError('t and h must be equal-length 1-dimensional arrays')\n\n # compute the PSD of the input\n N = len(t)\n Df = 1. / N / (t[1] - t[0])\n f = fftpack.ifftshift(Df * (np.arange(N) - N / 2))\n\n H = fftpack.fft(h)\n PSD = abs(H) ** 2\n\n # fit signal/noise params if necessary\n if signal_params is None:\n amp_guess = np.max(PSD[1:])\n width_guess = np.min(np.abs(f[PSD < np.mean(PSD)]))\n signal_params = (amp_guess, width_guess)\n if noise_params is None:\n noise_params = (np.mean(PSD[1:]),)\n\n # Set up the Wiener filter:\n # fit a model to the PSD: sum of signal form and noise form\n\n def signal(x, A, width):\n width = abs(width) + 1E-99 # prevent divide-by-zero errors\n return A * np.exp(-0.5 * (x / width) ** 2)\n\n def noise(x, n):\n return n * np.ones(x.shape)\n\n # use [1:] here to remove the zero-frequency term: we don't want to\n # fit to this for data with an offset.\n min_func = lambda v: np.sum((PSD[1:] - signal(f[1:], v[0], v[1])\n - noise(f[1:], v[2])) ** 2)\n v0 = tuple(signal_params) + tuple(noise_params)\n v = optimize.fmin(min_func, v0)\n\n P_S = signal(f, v[0], v[1])\n P_N = noise(f, v[2])\n Phi = P_S / (P_S + P_N)\n Phi[0] = 1 # correct for DC offset\n\n # Use Phi to filter and smooth the values\n h_smooth = fftpack.ifft(Phi * H)\n\n if not np.iscomplexobj(h):\n h_smooth = h_smooth.real\n\n if return_PSDs:\n return h_smooth, PSD, P_S, P_N, Phi\n else:\n return h_smooth\n\n\ndef min_component_filter(x, y, feature_mask, p=1, fcut=None, Q=None):\n \"\"\"Minimum component filtering\n\n Minimum component filtering is useful for determining the background\n component of a signal in the presence of spikes\n\n Parameters\n ----------\n x : array_like\n 1D array of evenly spaced x values\n y : array_like\n 1D array of y values corresponding to x\n feature_mask : array_like\n 1D mask array giving the locations of features in the data which\n should be ignored for smoothing\n p : integer (optional)\n polynomial degree to be used for the fit (default = 1)\n fcut : float (optional)\n the cutoff frequency for the low-pass filter. Default value is\n f_nyq / sqrt(N)\n Q : float (optional)\n the strength of the low-pass filter. Larger Q means a steeper cutoff\n default value is 0.1 * fcut\n\n Returns\n -------\n y_filtered : ndarray\n The filtered version of y.\n\n Notes\n -----\n This code follows the procedure explained in the book\n \"Practical Statistics for Astronomers\" by Wall & Jenkins book, as\n well as in Wall, J, A&A 122:371, 1997\n \"\"\"\n x = np.asarray(x, dtype=float)\n y = np.asarray(y, dtype=float)\n feature_mask = np.asarray(feature_mask, dtype=bool)\n\n if ((x.ndim != 1) or (x.shape != y.shape) or (y.shape !=\n feature_mask.shape)):\n raise ValueError('x, y, and feature_mask must be 1 dimensional '\n 'with matching lengths')\n\n if fcut is None:\n f_nyquist = 1. / (x[1] - x[0])\n fcut = f_nyquist / np.sqrt(len(x))\n\n if Q is None:\n Q = 0.1 * fcut\n\n # compute polynomial features\n XX = x[:, None] ** np.arange(p + 1)\n\n # compute least-squares fit to non-masked data\n beta = np.linalg.lstsq(XX[~feature_mask], y[~feature_mask])[0]\n\n # subtract polynomial fit and mask the data\n y_mask = y - np.dot(XX, beta)\n y_mask[feature_mask] = 0\n\n # get Fourier transforms of arrays\n yFT_mask = fftpack.fft(y_mask)\n\n # compute (shifted) frequency array for filter\n N = len(x)\n f = fftpack.ifftshift((np.arange(N) - N / 2.) * 1. / N / (x[1] - x[0]))\n\n # construct low-pass filter\n filt = np.exp(- (Q * (abs(f) - fcut) / fcut) ** 2)\n filt[abs(f) < fcut] = 1\n\n # reconstruct filtered signal\n y_filtered = fftpack.ifft(yFT_mask * filt).real + np.dot(XX, beta)\n\n return y_filtered\n" ]
[ [ "numpy.dot", "scipy.signal", "numpy.exp", "numpy.mean", "numpy.iscomplexobj", "numpy.linalg.lstsq", "numpy.concatenate", "numpy.max", "scipy.signal.fftconvolve", "scipy.optimize.fmin", "scipy.fftpack.fft", "numpy.arange", "numpy.convolve", "numpy.int", "numpy.linalg.pinv", "scipy.fftpack.ifft", "numpy.asarray", "numpy.ones", "numpy.abs" ] ]
apostolidoum/modeling-behaviour-of-SoC-players
[ "0a97597dace9a5b279ce6644a9879894596bc59c" ]
[ "NNarchitecture/GamestatesOHE.py" ]
[ "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nTransform the gamestate data to onehot vectors\n\"\"\"\n\nfrom sklearn.preprocessing import OneHotEncoder,LabelEncoder\nimport pandas as pd \nimport numpy as np\nimport re\nimport os\nfrom pathlib import Path\n\n\n# settlements and cities are built on node coordinates\n# roads are built on edge coordinates\n# nodes are named after an adjacent rode\n# hence the set of node coords is a subset of the edge coords\n# Additionally, no nodes close to the sea are needed...\n# these are inaccessible for building\n\n# edge_coordinates contains the edge coordinates on which a player\n# could actually built\n# len(edge_coordinates) = 72 \nedge_coordinates = ['0x27','0x38','0x49','0x5a','0x6b','0x7c',\n '0x26','0x48','0x6a','0x8c',\n '0x25','0x36','0x47','0x58','0x69','0x7a','0x8b','0x9c',\n '0x24','0x46','0x68','0x8a','0xac',\n '0x23','0x34','0x45','0x56','0x67','0x78','0x89','0x9a','0xab','0xbc',\n '0x22','0x44','0x66','0x88','0xaa','0xcc',\n '0x32','0x43','0x54','0x65','0x76','0x87','0x98','0xa9','0xba','0xcb',\n '0x42','0x64','0x86','0xa8','0xca',\n '0x52','0x63','0x74','0x85','0x96','0xa7','0xb8', '0xc9',\n '0x62','0x84','0xa6','0xc8',\n '0x72','0x83','0x94','0xa5','0xb6','0xc7']\n\n# additional node coordinates\n# (that are not in the accessible edge_coordinates list)\n# the ones on the right side of the land that are named after\n# sea edge nodes\nnode_coordinates = ['0x8d', '0xad','0xcd','0xdc','0xda','0xd8']\n\n# all the coordinates of the table that a player can build on\n# plus the none value for when the player has not built \n# len(build_coords) = 79\nbuild_coords = edge_coordinates + node_coordinates + ['None']\n\n################################\n# encoding the build coordinates\n################################\n\n\nnp_build_coords = np.array(build_coords)\nlabel_encoder = LabelEncoder()\ninteger_encoded_build_coords = label_encoder.fit_transform(np_build_coords)\n#print(label_encoder.transform(np.array(['0x69'])))\n######################\n# for debugging use:\n######################\n#print('building coordinates label encoding')\n#for x in build_coords:\n# print('coordinate ' + str(x) + ' : '+str(label_encoder.transform(np.ravel(x))))\n#print('-----------------------------------')\n#building coordinates label encoding\n#coordinate 0x27 : [5]\n#coordinate 0x38 : [9]\n#coordinate 0x49 : [17]\n#coordinate 0x5a : [22]\n#coordinate 0x6b : [32]\n#coordinate 0x7c : [38]\n#coordinate 0x26 : [4]\n#coordinate 0x48 : [16]\n#coordinate 0x6a : [31]\n#coordinate 0x8c : [48]\n#coordinate 0x25 : [3]\n#coordinate 0x36 : [8]\n#coordinate 0x47 : [15]\n#coordinate 0x58 : [21]\n#coordinate 0x69 : [30]\n#coordinate 0x7a : [37]\n#coordinate 0x8b : [47]\n#coordinate 0x9c : [54]\n#coordinate 0x24 : [2]\n#coordinate 0x46 : [14]\n#coordinate 0x68 : [29]\n#coordinate 0x8a : [46]\n#coordinate 0xac : [62]\n#coordinate 0x23 : [1]\n#coordinate 0x34 : [7]\n#coordinate 0x45 : [13]\n#coordinate 0x56 : [20]\n#coordinate 0x67 : [28]\n#coordinate 0x78 : [36]\n#coordinate 0x89 : [45]\n#coordinate 0x9a : [53]\n#coordinate 0xab : [61]\n#coordinate 0xbc : [67]\n#coordinate 0x22 : [0]\n#coordinate 0x44 : [12]\n#coordinate 0x66 : [27]\n#coordinate 0x88 : [44]\n#coordinate 0xaa : [60]\n#coordinate 0xcc : [73]\n#coordinate 0x32 : [6]\n#coordinate 0x43 : [11]\n#coordinate 0x54 : [19]\n#coordinate 0x65 : [26]\n#coordinate 0x76 : [35]\n#coordinate 0x87 : [43]\n#coordinate 0x98 : [52]\n#coordinate 0xa9 : [59]\n#coordinate 0xba : [66]\n#coordinate 0xcb : [72]\n#coordinate 0x42 : [10]\n#coordinate 0x64 : [25]\n#coordinate 0x86 : [42]\n#coordinate 0xa8 : [58]\n#coordinate 0xca : [71]\n#coordinate 0x52 : [18]\n#coordinate 0x63 : [24]\n#coordinate 0x74 : [34]\n#coordinate 0x85 : [41]\n#coordinate 0x96 : [51]\n#coordinate 0xa7 : [57]\n#coordinate 0xb8 : [65]\n#coordinate 0xc9 : [70]\n#coordinate 0x62 : [23]\n#coordinate 0x84 : [40]\n#coordinate 0xa6 : [56]\n#coordinate 0xc8 : [69]\n#coordinate 0x72 : [33]\n#coordinate 0x83 : [39]\n#coordinate 0x94 : [50]\n#coordinate 0xa5 : [55]\n#coordinate 0xb6 : [64]\n#coordinate 0xc7 : [68]\n#coordinate 0x8d : [49]\n#coordinate 0xad : [63]\n#coordinate 0xcd : [74]\n#coordinate 0xdc : [77]\n#coordinate 0xda : [76]\n#coordinate 0xd8 : [75]\n#coordinate None : [78]\n\n# binary encode\nonehot_encoder = OneHotEncoder(sparse=False)\ninteger_encoded_build_coords = integer_encoded_build_coords.reshape(len(integer_encoded_build_coords), 1)\nonehot_encoded_build_coords = onehot_encoder.fit_transform(integer_encoded_build_coords)\n#print(onehot_encoded_build_coords)\n\n##############################################\n# Testing\n##############################################\n# test label transform ['0x69' '0x89' 'None']\n#print('Testing the build coordinates')\n#y = gamestates.iloc[2,6:9]\n#values = np.array(y)\n#print(values)\n#integer_encoded = label_encoder.transform(np.ravel(values))\n#print(integer_encoded)\n#integer_encoded = integer_encoded.reshape(len(integer_encoded), 1)\n#onehot_encoded = onehot_encoder.transform(integer_encoded)\n#print(onehot_encoded)\n#print('eotesting build coordinates')\n\n# robber can be placed on land hexes (19)\nland_coords = ['0x37','0x59','0x7b',\n '0x35','0x57','0x79','0x9b',\n '0x33','0x55','0x77','0x99','0xbb',\n '0x53','0x75','0x97','0xb9',\n '0x73','0x95','0xb7'\n ]\n################################\n# encoding the land coordinates\n# aka robber coordinates\n################################\nnp_rob_coords = np.array(land_coords)\nrob_label_encoder = LabelEncoder()\ninteger_encoded_rob_coords = rob_label_encoder.fit_transform(np_rob_coords)\n# print(integer_encoded_rob_coords)\n# [ 2 6 11 1 5 10 15 0 4 9 14 18 3 8 13 17 7 12 16]\n# binary encode\nrob_onehot_encoder = OneHotEncoder(sparse=False)\ninteger_encoded_rob_coords = integer_encoded_rob_coords.reshape(len(integer_encoded_rob_coords), 1)\nonehot_encoded_rob_coords = rob_onehot_encoder.fit_transform(integer_encoded_rob_coords)\n#print(onehot_encoded_rob_coords)\n\n##############################################\n# Testing\n##############################################\n## test robber coordinates of pilot01\n#print('Testing the robber ')\n#y = gamestates.iloc[:,3]\n#values = np.array(y)\n#print(values)\n#integer_encoded = rob_label_encoder.transform(np.ravel(values))\n#print(integer_encoded)\n#integer_encoded = integer_encoded.reshape(len(integer_encoded), 1)\n#onehot_encoded = rob_onehot_encoder.transform(integer_encoded)\n#print(onehot_encoded)\n#print('eotesting robber')\n\n\n################################\n# encoding the hex typed\n################################\n# this needs to have custom categories because of the ports\n# in the game version of the data\n# 6: water\n# 0: desert\n# 1: clay\n# 2: ore\n# 3: sheep\n# 4: wheat\n# 5: wood\n# 7 - 12 : miscelaneous ports(3:1) facing on the different directions\n# 16+ : non miscelaneous ports(2:1)\n#\n# 9 categories \n\ndef hexLabelEncoder(hextypes):\n '''\n converts the hextypes to labeled (9 labels for the 9 categories)\n Parameters: hex board layout array\n Returns: array that contains the labels \n '''\n y = []\n # pilot1 hexlayout is \n #[9, 6, 67, 6, 6, 2, 5, 1, 66, 8, 2, 3, 1, 2, 6, 6, 5, 3, 4, 1, 4, 11, 36, 5, 4, 0, 5, 6, 6, 4, 3, 3, 97, 21, 6, 12, 6]\n for x in hextypes:\n if x < 7 : \n y.append(x)\n elif 7<= x <= 12:\n y.append(7)\n else :\n y.append(8)\n \n return y\n\n###### checking the general fit\n###### generalized ohe encoder for list of all possible land types\nhex_type_OHencoder = OneHotEncoder(sparse=False)\nhex_type_labels = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8])\n#integer_encoded_types = integer_encoded_types.reshape(len(integer_encoded_types),1)\nOHE_land_types = hex_type_OHencoder.fit_transform(hex_type_labels.reshape(len(hex_type_labels),1))\n#print(OHE_land_types)\n\n################################################\n# Testing\n##############################################\n## test land types of pilot01\n#hextypes = gamestates.iloc[0,1]\n#integer_encoded_types = np.array(hexLabelEncoder(hextypes))\n#print(integer_encoded_types)\n# outputs:\n# pilot1 hexlayout is \n#[9, 6, 67, 6, 6, 2, 5, 1, 66, 8, 2, 3, 1, 2, 6, 6, 5, 3, 4, 1, 4, 11, 36, 5, 4, 0, 5, 6, 6, 4, 3, 3, 97, 21, 6, 12, 6]\n# converted to:\n# [7 6 8 6 6 2 5 1 8 7 2 3 1 2 6 6 5 3 4 1 4 7 8 5 4 0 5 6 6 4 3 3 8 8 6 7 6]\n\n\n#ohe_hex_layout = hex_type_OHencoder.transform(integer_encoded_types.reshape(len(integer_encoded_types),1))\n\n\n\n\n\n######################################################\n# create the numpy array that contains the ohe vectors\n######################################################\n#\n# store the data to an np array so that the can be used\n# in keras \n#\n# a massive np array will be created with all the games at the end, when we \n# will be ready to train\n\n# to convert to ohe you first transform to label encoded\n# and then to one-hot encode\n\n# np array size :\n# rows : 4150 \n# i.e. for all 57 games we have 4150 gameturns\n# columns : \n# hex layout : 37 hexes x 9 categories \n# -> 333\n# robber positions : 19 possible positions (land hexes)\n# -> 19\n# player state : \n# builds : 24 building blocks x 79 categories(coords)\n# -> 1896\n# dev cards : 25 dev cards (true-false)\n# -> 25\n##\n# total : 333 + 19 + 4x(1896+25) = 8017 + 19 = 8036 \n\n\n######### IMPORTAND ##########\n## Instead of a big, chaotic table, save to various small np arrays \n##\n#ohedata = np.zeros((4150,8036)) \n## saving pilot1 to np data array\n## land hex types \n#temp = np.array(hexLabelEncoder(gamestates.iloc[0,1]))\n#print('-------')\n#print(temp)\n#print(hex_type_OHencoder.transform(temp.reshape(len(temp),1)))\n#\n##oned_temp = np.ravel(hex_type_OHencoder.transform(temp.reshape(len(temp),1)))\n## this goes from 0 to 332\n#ohedata[0,0:333] = np.ravel(hex_type_OHencoder.transform(temp.reshape(len(temp),1)))\n#ohedata[0,0:3]=1 # -> writes 1 to columns 0,1,2\n######## IMPORTAND ##########\n\n# OHE conversion steps: \n# 1. convert hex layout\n# 2. convert robber position and append it\n# 3. convert player1 build and append them\n# 4. convert player1 devcard and append them\n# 5. convert player2 3 4 \n# 6. check size of all this\n\ndef convert_hex_layout(hexlayout):\n ''' converts the gamestates hexlayout to one hot encoding\n \n PARAMETERS\n ----------\n hexlayout : the gamestates hexlayout\n \n Returns\n -------\n an np array of size (1,333)\n '''\n \n # convert the layout to label encoding\n labeled = np.array(hexLabelEncoder(hexlayout))\n # convert the layout to one hot encoding\n ohe = hex_type_OHencoder.transform(labeled.reshape(len(labeled),1))\n return np.ravel(ohe)\n \n####Testing OK\n#print('Testing hex layout conversion')\n#methodlayout = convert_hex_layout(gamestates.iloc[0,1])\n#scriptlayout = np.ravel(hex_type_OHencoder.transform(temp.reshape(len(temp),1)))\n \ndef convert_robber_position(robber):\n ''' converts the robber position coordinates to one hot encoding\n \n Parameters\n ----------\n robber: the robber coordinates from the gamestates dataframe\n \n Returns\n -------\n encoded np array of size 19\n '''\n \n # convert the robber position to labeled encoding\n robber = np.array(robber)\n labeled = rob_label_encoder.transform(np.ravel(robber))\n # convert the robber position to one hot encoding\n labeled = labeled.reshape(len(labeled),1)\n ohe = rob_onehot_encoder.transform(labeled)\n # return with ravel to avoid the double list [[]]\n return np.ravel(ohe)\n\n####Testing OK\n#print('Testing the robber ')\n#y = gamestates.iloc[1,3]\n#values = np.array(y)\n#print(values)\n#integer_encoded = rob_label_encoder.transform(np.ravel(values))\n#print(integer_encoded)\n#integer_encoded = integer_encoded.reshape(len(integer_encoded), 1)\n#onehot_encoded = rob_onehot_encoder.transform(integer_encoded)\n#print(onehot_encoded)\n#print('eotesting robber')\n#print('Testing the robber method')\n#methodrobber = convert_robber_position(gamestates.iloc[1,3])\n#print(methodrobber)\n\ndef convert_player_buildings(playerbuildings):\n '''\n Converts the player buildings coordinates to one hot encoding\n \n Parameters\n ----------\n from the gamestate the players columns of settlements, cities and roads\n a list of 24 coordinates\n \n Returns\n -------\n np array of one hot encoding for all 24 building blocks of the player\n size should be (24,79) (in one line vector 24*79 = 1896)\n \n '''\n \n # list of the buildings \n buildings = []\n for coord in playerbuildings:\n ohe_coord = convert_building_coord(coord)\n buildings.append(ohe_coord)\n \n #print(buildings)\n npbuildings = np.array(buildings)\n return np.ravel(npbuildings)\n \n \n \n\ndef convert_building_coord(hexcoord):\n '''\n Convert a hex building coordinate to one hot encoding\n \n Parameters\n ----------\n a hex coordinate\n \n Returns\n -------\n one hot encoding of the coordinate, an np array or size 79\n '''\n \n value = np.array(hexcoord)\n # convert the coordinate to labeled encoding\n labeled = label_encoder.transform(np.ravel(value))\n # convert the coordinate to one hot encoding\n labeled = labeled.reshape(len(labeled), 1)\n ohe = onehot_encoder.transform(labeled)\n return ohe\n\n\n#######\n## Testing the coordinate convertion OK\n#print('Testing the coordinate convertion to ohe')\n## testing only one coordinate\n#coord = gamestates.iloc[2,6]\n#print(coord)\n#methodcoord = convert_building_coord(coord)\n## testing group of coordinates OK\n#coords = gamestates.iloc[2,6:9]\n#print(coords)\n#methodcoords = convert_player_buildings(coords)\n#print(methodcoords)\n#print(methodcoords.reshape(3,79))\n\n\ndef convert_player_devcards(dev_cards):\n '''\n Coverts the gamestate fields of the players dev cards\n from true/false to binary 1/0 \n \n Parameters\n ----------\n dev_cards : the 25 dev cards potentialy available to the player\n \n Returns\n -------\n np array of size 25 where true is 1 and false is 0\n '''\n \n \n binary_dev_cards =[]\n for card in dev_cards:\n # type is np.bool, don't use quotes \n if card == True :\n binary_dev_cards.append(1)\n else:\n binary_dev_cards.append(0)\n return np.array(binary_dev_cards)\n \n#### Testing player dev cards OK\n#dev_cards = gamestates.loc[58, 'pl0knight1' : 'pl0vp5']\n#dclist = convert_player_devcards(dev_cards)\n#print(dclist)\n \n\n\n##############################################################################\n# OHE conversion\n##############################################################################\n \n# convert each dataframe to np arrays \n# each game has 10 np arrays of the board, robber and player states in ohe data\n \ndatafiles = [\"../soclogsData_NoResources/DataTables/pilot/pilot03_gamestates.pkl\",\n \"../soclogsData_NoResources/DataTables/pilot/pilot15_gamestates.pkl\",\n \"../soclogsData_NoResources/DataTables/pilot/pilot17_gamestates.pkl\",\n \"../soclogsData_NoResources/DataTables/pilot/pilot04_gamestates.pkl\",\n \"../soclogsData_NoResources/DataTables/pilot/pilot21_gamestates.pkl\",\n \"../soclogsData_NoResources/DataTables/pilot/pilot02_gamestates.pkl\",\n \"../soclogsData_NoResources/DataTables/pilot/pilot08_gamestates.pkl\",\n \"../soclogsData_NoResources/DataTables/pilot/pilot09_gamestates.pkl\",\n \"../soclogsData_NoResources/DataTables/pilot/pilot14_gamestates.pkl\",\n \"../soclogsData_NoResources/DataTables/pilot/pilot11_gamestates.pkl\",\n \"../soclogsData_NoResources/DataTables/pilot/pilot05_gamestates.pkl\",\n \"../soclogsData_NoResources/DataTables/pilot/pilot16_gamestates.pkl\",\n \"../soclogsData_NoResources/DataTables/pilot/pilot01_gamestates.pkl\",\n \"../soclogsData_NoResources/DataTables/pilot/pilot20_gamestates.pkl\",\n \"../soclogsData_NoResources/DataTables/pilot/pilot13_gamestates.pkl\",\n \"../soclogsData_NoResources/DataTables/pilot/pilot10_gamestates.pkl\",\n \"../soclogsData_NoResources/DataTables/pilot/pilot12_gamestates.pkl\",\n \"../soclogsData_NoResources/DataTables/pilot/pilot07_gamestates.pkl\",\n \"../soclogsData_NoResources/DataTables/pilot/pilot06_gamestates.pkl\",\n \"../soclogsData_NoResources/DataTables/season2/league4_attempt2-2012-11-14-19-46-22-+0000_gamestates.pkl\",\n \"../soclogsData_NoResources/DataTables/season2/practice-2012-10-30-18-41-07-+0000_gamestates.pkl\",\n \"../soclogsData_NoResources/DataTables/season2/League4-2012-11-24-09-17-47-+0000_gamestates.pkl\",\n \"../soclogsData_NoResources/DataTables/season2/Test-2012-10-16-14-53-15-+0100_gamestates.pkl\",\n \"../soclogsData_NoResources/DataTables/season2/L5 Real game-2012-11-11-19-58-55-+0000_gamestates.pkl\",\n \"../soclogsData_NoResources/DataTables/season2/Master League final-2012-12-05-16-59-57-+0000_gamestates.pkl\",\n \"../soclogsData_NoResources/DataTables/season2/League 8 Game 2-2012-11-26-18-55-31-+0000_gamestates.pkl\",\n \"../soclogsData_NoResources/DataTables/season2/SOCL League 5 Game 2-2012-11-25-17-25-09-+0000_gamestates.pkl\",\n \"../soclogsData_NoResources/DataTables/season2/league 5 last game-2012-12-09-21-08-39-+0000_gamestates.pkl\",\n \"../soclogsData_NoResources/DataTables/season2/SOCL League 5 Game 4-2012-12-03-02-11-10-+0000_gamestates.pkl\",\n \"../soclogsData_NoResources/DataTables/season2/League8-2012-11-24-12-04-51-+0000_gamestates.pkl\",\n \"../soclogsData_NoResources/DataTables/season2/League3Game5-2012-11-30-19-59-18-+0000_gamestates.pkl\",\n \"../soclogsData_NoResources/DataTables/season2/master league 4-2012-12-04-17-37-56-+0000_gamestates.pkl\",\n \"../soclogsData_NoResources/DataTables/season2/Master league game 2-2012-11-13-18-07-14-+0000_gamestates.pkl\",\n \"../soclogsData_NoResources/DataTables/season2/Game 3-2012-11-25-20-09-16-+0000_gamestates.pkl\",\n \"../soclogsData_NoResources/DataTables/season2/League 5 game 3-2012-11-26-00-51-20-+0000_gamestates.pkl\",\n \"../soclogsData_NoResources/DataTables/season2/League4-2012-11-09-19-08-53-+0000_gamestates.pkl\",\n \"../soclogsData_NoResources/DataTables/season2/3version2-2012-11-21-20-23-31-+0000_gamestates.pkl\",\n \"../soclogsData_NoResources/DataTables/season2/League3Game1-2012-11-18-20-34-38-+0000_gamestates.pkl\",\n \"../soclogsData_NoResources/DataTables/season2/League3Game4-2012-11-28-20-01-30-+0000_gamestates.pkl\",\n \"../soclogsData_NoResources/DataTables/season2/L5 practicegame-2012-11-11-19-26-36-+0000_gamestates.pkl\",\n \"../soclogsData_NoResources/DataTables/season2/Master League Game 3-2012-11-17-17-01-18-+0000_gamestates.pkl\",\n \"../soclogsData_NoResources/DataTables/season2/Settles league 1-2012-11-08-18-05-34-+0000_gamestates.pkl\",\n \"../soclogsData_NoResources/DataTables/season1/league3practice-2012-05-31-19-23-46-+0100_gamestates.pkl\",\n \"../soclogsData_NoResources/DataTables/season1/League2.4-2012-06-26-22-47-04-+0100_gamestates.pkl\",\n \"../soclogsData_NoResources/DataTables/season1/league3-2012-05-27-19-53-48-+0100_gamestates.pkl\",\n \"../soclogsData_NoResources/DataTables/season1/league2.2-2012-06-18-20-50-12-+0100_gamestates.pkl\",\n \"../soclogsData_NoResources/DataTables/season1/league3 michael-2012-06-17-20-54-03-+0100_gamestates.pkl\",\n \"../soclogsData_NoResources/DataTables/season1/3-2012-06-06-19-58-56-+0100_gamestates.pkl\",\n \"../soclogsData_NoResources/DataTables/season1/League 1-2012-06-17-19-53-24-+0100_gamestates.pkl\",\n \"../soclogsData_NoResources/DataTables/season1/League 1.2-2012-06-21-20-27-05-+0100_gamestates.pkl\",\n \"../soclogsData_NoResources/DataTables/season1/league 3 (-k)-2012-06-25-18-22-53-+0100_gamestates.pkl\",\n \"../soclogsData_NoResources/DataTables/season1/league3minus1-2012-05-25-22-22-21-+0100_gamestates.pkl\",\n \"../soclogsData_NoResources/DataTables/season1/League 2-2012-06-26-20-23-20-+0100_gamestates.pkl\",\n \"../soclogsData_NoResources/DataTables/season1/League 1 game-2012-06-19-18-49-00-+0100_gamestates.pkl\",\n \"../soclogsData_NoResources/DataTables/season1/League 1.1-2012-06-21-18-58-22-+0100_gamestates.pkl\",\n \"../soclogsData_NoResources/DataTables/season1/league1 31may-2012-05-31-19-59-37-+0100_gamestates.pkl\",\n \"../soclogsData_NoResources/DataTables/season1/League 3 Finale-2012-06-25-21-57-53-+0100_gamestates.pkl\",\n \"../soclogsData_NoResources/DataTables/season1/League2-2012-06-17-19-58-07-+0100_gamestates.pkl\"\n ]\n\n# make directories to save the results\nohedata_dir = Path.cwd() / \"OHEdata/season2\" \nohedata_dir.mkdir(parents=True, exist_ok=True)\n\nohedata_dir = Path.cwd() / \"OHEdata/season1\" \nohedata_dir.mkdir(parents=True, exist_ok=True)\n\nohedata_dir = Path.cwd() / \"OHEdata/pilot\" \nohedata_dir.mkdir(parents=True, exist_ok=True) \n\nprint('Converting gamestates data to ohe-hot encoded vectors')\nprint('This might take a while. Please be patient...')\nfor file in datafiles:\n # create a dir with the game name\n # to save the 11 np arrays of the game\n # with the data in ohe\n \n filename_parts = re.split(r'[/]', file)\n season = filename_parts[3]\n dest = \"./OHEdata/\"+season\n gamename = filename_parts[4][:-15] #exclude the _gamestates.pkl part :-) \n path = dest+\"/\"+gamename\n try:\n os.mkdir(path)\n except OSError :\n print(\"Creation of the directory %s failed\" %path)\n \n \n gamestates = pd.read_pickle(file)\n # replace None values with 'None' to work with np\n gamestates.replace(to_replace=[None], value='None', inplace=True)\n # initialize nptables\n nplayout = np.zeros((1,333))\n nprobber = np.zeros((len(gamestates.index),19))\n np_pl0_builds = np.zeros((len(gamestates.index),1896))\n np_pl0_devcards = np.zeros((len(gamestates.index),25))\n np_pl1_builds = np.zeros((len(gamestates.index),1896))\n np_pl1_devcards = np.zeros((len(gamestates.index),25))\n np_pl2_builds = np.zeros((len(gamestates.index),1896))\n np_pl2_devcards = np.zeros((len(gamestates.index),25))\n np_pl3_builds = np.zeros((len(gamestates.index),1896))\n np_pl3_devcards = np.zeros((len(gamestates.index),25))\n \n # convert the hex layout, column 1 is hexlayout\n # hex layout does not change during a game, hence it is saved only once\n # to view it nplayout.reshape(37,9) tested OK\n nplayout[:] = convert_hex_layout(gamestates.iloc[0,1]) \n \n # for every row of the df, i.e. every game turn\n for turn in range(len(gamestates.index)):\n # convert the robber position, column 3 is robber\n # tested OK\n ohe_robber = convert_robber_position(gamestates.iloc[turn,3]) \n nprobber[turn,:] = ohe_robber\n \n # convert player 0 building coordinates\n # (note the None is also a category in the ohe endoding)\n #print(gamestates.loc[turn,'pl0setm1':'pl0road15'])\n # ohe_pl0_builds is a np.array of size (1896,)\n ohe_pl0_builds = convert_player_buildings(gamestates.loc[turn,'pl0setm1':'pl0road15'])\n #print(ohe_pl0_builds)\n np_pl0_builds[turn,:] = ohe_pl0_builds\n #print(np_pl0_builds[turn,:])\n \n # convert player 0 dev cards\n np_pl0_devcards[turn,:] = convert_player_devcards(gamestates.loc[turn,'pl0knight1' : 'pl0vp5'])\n \n # convert player 1 building coordinates\n ohe_pl1_builds = convert_player_buildings(gamestates.loc[turn,'pl1setm1':'pl1road15'])\n np_pl1_builds[turn,:] = ohe_pl1_builds\n # convert player 1 dev cards\n np_pl1_devcards[turn,:] = convert_player_devcards(gamestates.loc[turn,'pl1knight1' : 'pl1vp5'])\n \n # convert player 2 building coordinates\n ohe_pl2_builds = convert_player_buildings(gamestates.loc[turn,'pl2setm1':'pl2road15'])\n np_pl2_builds[turn,:] = ohe_pl2_builds\n # convert player 1 dev cards\n np_pl2_devcards[turn,:] = convert_player_devcards(gamestates.loc[turn,'pl2knight1' : 'pl2vp5'])\n\n # convert player 3 building coordinates\n ohe_pl3_builds = convert_player_buildings(gamestates.loc[turn,'pl3setm1':'pl3road15'])\n np_pl3_builds[turn,:] = ohe_pl3_builds\n # convert player 3 dev cards\n np_pl3_devcards[turn,:] = convert_player_devcards(gamestates.loc[turn,'pl3knight1' : 'pl3vp5'])\n\n \n\n # save the np arrays of the game\n np.save(path+\"/\"+'layout.npy',nplayout)\n np.save(path+\"/\"+'robber.npy',nprobber)\n np.save(path+\"/\"+'pl0builds.npy',np_pl0_builds)\n np.save(path+\"/\"+'pl0devcards.npy',np_pl0_devcards)\n np.save(path+\"/\"+'pl1builds.npy',np_pl1_builds)\n np.save(path+\"/\"+'pl1devcards.npy',np_pl1_devcards)\n np.save(path+\"/\"+'pl2builds.npy',np_pl2_builds)\n np.save(path+\"/\"+'pl2devcards.npy',np_pl2_devcards)\n np.save(path+\"/\"+'pl3builds.npy',np_pl2_builds)\n np.save(path+\"/\"+'pl3devcards.npy',np_pl2_devcards)\n\n" ]
[ [ "pandas.read_pickle", "sklearn.preprocessing.LabelEncoder", "numpy.array", "numpy.zeros", "numpy.save", "numpy.ravel", "sklearn.preprocessing.OneHotEncoder" ] ]
Xiaoqiong-Liu/pointcloud
[ "3d77ef2896297acd103301dfa01beeee49e65057" ]
[ "models/main.py" ]
[ "import pytorch_lightning as pl\nimport argparse\nfrom dataset.KITTI import KITTI\nfrom dataset.KITTISampler import KITTISampler\nfrom torch.utils.data import DataLoader\nfrom bat import bat\nimport yaml\nfrom easydict import EasyDict\n\nkitti_path = '/mnt/Data/KITTI'\n\ndef load_yaml(file_name):\n with open(file_name, 'r') as f:\n try:\n config = yaml.load(f, Loader=yaml.FullLoader)\n except:\n config = yaml.load(f)\n return config\n\ndef parse_config():\n parser = argparse.ArgumentParser()\n parser.add_argument('--checkpoint', type=str, default='/home/UNT/xl0217/pointcloud/pretrained_models/bat_kitti_car.ckpt', help='checkpoint location')\n parser.add_argument('--epoch', type=int, default=60, help='number of epochs')\n parser.add_argument('--gpu', type=int, nargs='+', default=(0, 1), help='specify gpu devices')\n parser.add_argument('--cfg', type=str, default='/home/UNT/xl0217/pointcloud/config/BAT.yaml', help='the config_file')\n parser.add_argument('--use_fps', default=True, help='specify use farthest point sampling or not')\n parser.add_argument('--test', action='store_true', default=True, help='test mode')\n parser.add_argument('--check_val_every_n_epoch', type=int, default=1, help='check_val_every_n_epoch')\n args = parser.parse_args()\n config = load_yaml(args.cfg)\n config.update(vars(args)) # override the configuration using the value in args\n return EasyDict(config)\n\ncfg = parse_config()\n\n\n\"\"\"\"\"\"\"1.implement bat\"\"\"\"\"\"\"\n# prepare data\nkitti = KITTI(kitti_path, split='test', config=cfg)\ntest_data = KITTISampler(kitti) \ntrain_loader = DataLoader(test_data, batch_size=1, num_workers=40, collate_fn=lambda x: x, pin_memory=True)\n# get model\nnet = bat(cfg).load_from_checkpoint(cfg.checkpoint, config=cfg)\ntrainer = pl.Trainer(gpus=cfg.gpu, accelerator=\"ddp\")\ntrainer.validate(net, train_loader)" ]
[ [ "torch.utils.data.DataLoader" ] ]
btilmon/illumiGrad
[ "14d17d18ed1cde1bd8d948003f6d188ce71cf7ef" ]
[ "camera.py" ]
[ "import torch\nimport numpy as np\nimport sys\n\nclass BackprojectDepth(torch.nn.Module):\n \"\"\"\n Backproject absolute depth from depth camera to point cloud\n (adapted from https://github.com/nianticlabs/monodepth2)\n \"\"\"\n def __init__(self, opt):\n super(BackprojectDepth, self).__init__()\n\n self.batchSize = opt.numPairs\n self.height = opt.height\n self.width = opt.width\n\n meshgrid = np.meshgrid(range(self.width), range(self.height), indexing='xy')\n self.idCoords = np.stack(meshgrid, axis=0).astype(np.float32)\n self.idCoords = torch.tensor(self.idCoords, requires_grad=False)\n\n self.ones = torch.ones(self.batchSize, 1, self.height * self.width, requires_grad=False)\n self.pixCoords = torch.unsqueeze(torch.stack(\n [self.idCoords[0].view(-1), self.idCoords[1].view(-1)], 0), 0)\n self.pixCoords = self.pixCoords.repeat(self.batchSize, 1, 1)\n self.pixCoords = torch.cat([self.pixCoords, self.ones], 1)\n\n def forward(self, depth, K):\n invK = torch.linalg.pinv(K)\n camPoints = torch.matmul(invK[:, :3, :3], self.pixCoords)\n camPoints = depth.view(self.batchSize, 1, -1) * camPoints\n camPoints = torch.cat([camPoints, self.ones], 1)\n return camPoints.float()\n\nclass ProjectDepth(torch.nn.Module):\n \"\"\"\n Project point cloud into color camera\n (adapted from https://github.com/nianticlabs/monodepth2)\n \"\"\"\n def __init__(self, opt, eps=1e-7):\n super(ProjectDepth, self).__init__()\n self.batchSize = opt.numPairs\n self.height = opt.height\n self.width = opt.width\n self.eps = eps\n\n def forward(self, points, K, T):\n P = torch.matmul(K, T)[:, :3, :]\n cam_points = torch.matmul(P, points)\n pix_coords = cam_points[:, :2, :] / (cam_points[:, 2, :].unsqueeze(1) + self.eps)\n pix_coords = pix_coords.view(self.batchSize, 2, self.height, self.width)\n pix_coords = pix_coords.permute(0, 2, 3, 1)\n pix_coords[..., 0] /= self.width - 1\n pix_coords[..., 1] /= self.height - 1\n pix_coords = (pix_coords - 0.5) * 2\n return pix_coords\n\nclass Camera(torch.nn.Module):\n \"\"\"\n projective geometry model\n fx = lens * sensor size\"\"\"\n def __init__(self, opt):\n super(Camera, self).__init__()\n self.opt = opt\n \n # projection layers\n self.backprojectDepth = BackprojectDepth(opt)\n self.projectDepth = ProjectDepth(opt)\n\n # initialize color camera intrinsics K and extrinsics E\n self.initColorCamera()\n # initialize depth camera intrinsics K\n self.initDepthCamera()\n\n\n def initDepthCamera(self):\n # NYU Depth V2 has calibrated camera parameters\n # self.opt.refine is if you have already have decently good cailibration but \n # still want to tune it\n if self.opt.refine:\n self.depthK = torch.tensor(\n [[582.624, 0, 0.0313, 0], \n [0, 582.691, 0.024, 0], \n [0, 0, 1, 0], \n [0, 0, 0, 1]], requires_grad=True)[None]\n else:\n # randomly generate focal lengths in a range\n # randomly generate remaining intrinsic parameters between 0 and 1\n f = (400 - 600) * torch.rand(1, 1, requires_grad=True) + 600\n offsets = torch.tensor([[0.5]], requires_grad=True)\n col1 = torch.cat((f, torch.zeros(3, 1, requires_grad=False)))\n col2 = torch.cat( (torch.cat((offsets, f), dim=0), torch.zeros(2,1, requires_grad=False)) )\n col3 = torch.cat((offsets, offsets), dim=0)\n col3 = torch.cat((col3, torch.tensor([[1], [0]], requires_grad=False)), dim=0)\n col4 = torch.tensor([[0], [0], [0], [1]], requires_grad=False)\n self.depthK = torch.nn.Parameter(\n torch.cat((col1, col2, col3, col4), dim=1)[None], \n requires_grad=True) \n\n def initColorCamera(self):\n # NYU Depth V2 has calibrated camera parameters\n if self.opt.refine:\n self.colorK = torch.tensor(\n [[518.858, 0, 0.033, 0], \n [0, 519.470, 0.024, 0], \n [0, 0, 1, 0], \n [0, 0, 0, 1]], requires_grad=True)[None]\n self.colorE = torch.tensor(\n [[0.999, 0.0051, 0.0043, 0.025], \n [-0.0050, 0.999, -0.0037, -0.000293], \n [-0.00432, 0.0037, 0.999, 0.000662], \n [0, 0, 0, 1]])[None]\n self.colorE = self.colorE.transpose(1,2)\n self.colorE = torch.linalg.inv(self.colorE)\n print(self.colorE); sys.exit()\n self.colorE = torch.nn.Parameter(self.colorE, requires_grad=True)\n else:\n # randomly generate focal lengths in a range\n # randomly generate remaining intrinsic parameters between 0 and 1\n f = (400 - 600) * torch.rand(1, 1, requires_grad=True) + 600\n offsets = torch.tensor([[0.5]], requires_grad=True)\n col1 = torch.cat((f, torch.zeros(3, 1, requires_grad=False)))\n col2 = torch.cat( (torch.cat((offsets, f), dim=0), torch.zeros(2,1, requires_grad=False)) )\n col3 = torch.cat((offsets, offsets), dim=0)\n col3 = torch.cat((col3, torch.tensor([[1], [0]], requires_grad=False)), dim=0)\n col4 = torch.tensor([[0], [0], [0], [1]], requires_grad=False)\n self.colorK = torch.nn.Parameter(\n torch.cat((col1, col2, col3, col4), dim=1)[None], \n requires_grad=True)\n\n # randomly generate translation vector and assume identity rotation matrix\n # rotation matrix and translation vector are optimized\n a = torch.eye(3) # rotation matrix\n a = torch.cat((a, torch.zeros(1, 3)), dim=0)\n t = torch.tensor([[.1], [0.], [0.]], requires_grad=True) # translation vec\n t = torch.cat((t, torch.tensor([[1.]])))\n self.colorE = torch.cat((a, t), dim=1)[None]\n self.colorE = self.colorE.transpose(1, 2)\n self.colorE = torch.linalg.inv(self.colorE)\n self.colorE = torch.nn.Parameter(self.colorE, requires_grad=True)\n\n def forward(self, depth, color):\n pointCloud = self.backprojectDepth(depth, self.depthK)\n predCoords = self.projectDepth(pointCloud, self.colorK, self.colorE)\n predColor = torch.nn.functional.grid_sample(color, \n predCoords, \n padding_mode=\"border\", \n align_corners=False)\n return predColor\n" ]
[ [ "torch.zeros", "torch.rand", "torch.cat", "torch.ones", "torch.nn.Parameter", "torch.linalg.pinv", "torch.tensor", "torch.nn.functional.grid_sample", "torch.eye", "torch.linalg.inv", "numpy.stack", "torch.matmul" ] ]
RICE-EIC/GCoD
[ "6633859513e56b8843c4d6486e214364a0a4c74c" ]
[ "models/global_gat_conv.py" ]
[ "from typing import Union, Tuple, Optional\nfrom torch_geometric.typing import (OptPairTensor, Adj, Size, NoneType,\n OptTensor)\n\nimport torch\nfrom torch import Tensor\nimport torch.nn.functional as F\nfrom torch.nn import Parameter, Linear\nfrom torch_sparse import SparseTensor, set_diag\nfrom torch_geometric.nn.conv import MessagePassing\nfrom torch_geometric.utils import remove_self_loops, add_self_loops, softmax\n\nfrom torch_geometric.nn.inits import glorot, zeros\n\nfrom .quantize import *\n\n\nclass GATConv(MessagePassing):\n r\"\"\"The graph attentional operator from the `\"Graph Attention Networks\"\n <https://arxiv.org/abs/1710.10903>`_ paper\n\n .. math::\n \\mathbf{x}^{\\prime}_i = \\alpha_{i,i}\\mathbf{\\Theta}\\mathbf{x}_{i} +\n \\sum_{j \\in \\mathcal{N}(i)} \\alpha_{i,j}\\mathbf{\\Theta}\\mathbf{x}_{j},\n\n where the attention coefficients :math:`\\alpha_{i,j}` are computed as\n\n .. math::\n \\alpha_{i,j} =\n \\frac{\n \\exp\\left(\\mathrm{LeakyReLU}\\left(\\mathbf{a}^{\\top}\n [\\mathbf{\\Theta}\\mathbf{x}_i \\, \\Vert \\, \\mathbf{\\Theta}\\mathbf{x}_j]\n \\right)\\right)}\n {\\sum_{k \\in \\mathcal{N}(i) \\cup \\{ i \\}}\n \\exp\\left(\\mathrm{LeakyReLU}\\left(\\mathbf{a}^{\\top}\n [\\mathbf{\\Theta}\\mathbf{x}_i \\, \\Vert \\, \\mathbf{\\Theta}\\mathbf{x}_k]\n \\right)\\right)}.\n\n Args:\n in_channels (int or tuple): Size of each input sample. A tuple\n corresponds to the sizes of source and target dimensionalities.\n out_channels (int): Size of each output sample.\n heads (int, optional): Number of multi-head-attentions.\n (default: :obj:`1`)\n concat (bool, optional): If set to :obj:`False`, the multi-head\n attentions are averaged instead of concatenated.\n (default: :obj:`True`)\n negative_slope (float, optional): LeakyReLU angle of the negative\n slope. (default: :obj:`0.2`)\n dropout (float, optional): Dropout probability of the normalized\n attention coefficients which exposes each node to a stochastically\n sampled neighborhood during training. (default: :obj:`0`)\n add_self_loops (bool, optional): If set to :obj:`False`, will not add\n self-loops to the input graph. (default: :obj:`True`)\n bias (bool, optional): If set to :obj:`False`, the layer will not learn\n an additive bias. (default: :obj:`True`)\n **kwargs (optional): Additional arguments of\n :class:`torch_geometric.nn.conv.MessagePassing`.\n \"\"\"\n _alpha: OptTensor\n\n def __init__(self, in_channels: Union[int, Tuple[int, int]],\n out_channels: int, heads: int = 1, concat: bool = True,\n negative_slope: float = 0.2, dropout: float = 0.,\n add_self_loops: bool = True, bias: bool = True, **kwargs):\n super(GATConv, self).__init__(aggr='add', node_dim=0, **kwargs)\n\n self.in_channels = in_channels\n self.out_channels = out_channels\n self.heads = heads\n self.concat = concat\n self.negative_slope = negative_slope\n self.dropout = dropout\n self.add_self_loops = add_self_loops\n\n if isinstance(in_channels, int):\n self.lin_l = Linear(in_channels, heads * out_channels, bias=False)\n self.lin_r = self.lin_l\n else:\n self.lin_l = Linear(in_channels[0], heads * out_channels, False)\n self.lin_r = Linear(in_channels[1], heads * out_channels, False)\n\n self.att_l = Parameter(torch.Tensor(1, heads, out_channels))\n self.att_r = Parameter(torch.Tensor(1, heads, out_channels))\n\n if bias and concat:\n self.bias = Parameter(torch.Tensor(heads * out_channels))\n elif bias and not concat:\n self.bias = Parameter(torch.Tensor(out_channels))\n else:\n self.register_parameter('bias', None)\n\n self._alpha = None\n\n self.quantize_input = QuantMeasure(shape_measure=(1, 1), flatten_dims=(1, -1), momentum=0.1)\n\n self.quant = None\n self.num_bits = None\n\n self.reset_parameters()\n\n def reset_parameters(self):\n glorot(self.lin_l.weight)\n glorot(self.lin_r.weight)\n glorot(self.att_l)\n glorot(self.att_r)\n zeros(self.bias)\n\n def forward(self, x: Union[Tensor, OptPairTensor], edge_index: Adj, quant=True, num_bits=None,\n size: Size = None, return_attention_weights=None):\n # type: (Union[Tensor, OptPairTensor], Tensor, Size, NoneType) -> Tensor # noqa\n # type: (Union[Tensor, OptPairTensor], SparseTensor, Size, NoneType) -> Tensor # noqa\n # type: (Union[Tensor, OptPairTensor], Tensor, Size, bool) -> Tuple[Tensor, Tuple[Tensor, Tensor]] # noqa\n # type: (Union[Tensor, OptPairTensor], SparseTensor, Size, bool) -> Tuple[Tensor, SparseTensor] # noqa\n r\"\"\"\n\n Args:\n return_attention_weights (bool, optional): If set to :obj:`True`,\n will additionally return the tuple\n :obj:`(edge_index, attention_weights)`, holding the computed\n attention weights for each edge. (default: :obj:`None`)\n \"\"\"\n\n self.quant = quant\n self.num_bits = num_bits\n\n H, C = self.heads, self.out_channels\n\n x_l: OptTensor = None\n x_r: OptTensor = None\n alpha_l: OptTensor = None\n alpha_r: OptTensor = None\n\n if self.quant:\n # quantize input\n x = self.quantize_input(x, num_bits)\n # quantize weight\n att_l_qparams = calculate_qparams(\n self.att_l, num_bits=num_bits, flatten_dims=(1, -1), reduce_dim=None)\n qatt_l = quantize(self.att_l, qparams=att_l_qparams)\n att_r_qparams = calculate_qparams(\n self.att_r, num_bits=num_bits, flatten_dims=(1, -1), reduce_dim=None)\n qatt_r = quantize(self.att_r, qparams=att_r_qparams)\n\n if isinstance(x, Tensor):\n assert x.dim() == 2, 'Static graphs not supported in `GATConv`.'\n x_l = x_r = self.lin_l(x).view(-1, H, C)\n alpha_l = alpha_r = (x_l * qatt_l).sum(dim=-1)\n else:\n x_l, x_r = x[0], x[1]\n assert x[0].dim() == 2, 'Static graphs not supported in `GATConv`.'\n x_l = self.lin_l(x_l).view(-1, H, C)\n alpha_l = (x_l * qatt_l).sum(dim=-1)\n if x_r is not None:\n x_r = self.lin_r(x_r).view(-1, H, C)\n alpha_r = (x_r * qatt_r).sum(dim=-1)\n else:\n if isinstance(x, Tensor):\n assert x.dim() == 2, 'Static graphs not supported in `GATConv`.'\n x_l = x_r = self.lin_l(x).view(-1, H, C)\n alpha_l = (x_l * self.att_l).sum(dim=-1)\n alpha_r = (x_r * self.att_r).sum(dim=-1)\n else:\n x_l, x_r = x[0], x[1]\n assert x[0].dim() == 2, 'Static graphs not supported in `GATConv`.'\n x_l = self.lin_l(x_l).view(-1, H, C)\n alpha_l = (x_l * self.att_l).sum(dim=-1)\n if x_r is not None:\n x_r = self.lin_r(x_r).view(-1, H, C)\n alpha_r = (x_r * self.att_r).sum(dim=-1)\n\n # add by haoran\n print('x_l: ', x_l.shape)\n print('x_r: ', x_r.shape)\n print('alpha_l: ', alpha_l.shape)\n print('alpha_r: ', alpha_r.shape)\n\n assert x_l is not None\n assert alpha_l is not None\n\n if self.add_self_loops:\n if isinstance(edge_index, Tensor):\n num_nodes = x_l.size(0)\n num_nodes = size[1] if size is not None else num_nodes\n num_nodes = x_r.size(0) if x_r is not None else num_nodes\n edge_index, _ = remove_self_loops(edge_index)\n edge_index, _ = add_self_loops(edge_index, num_nodes=num_nodes)\n elif isinstance(edge_index, SparseTensor):\n edge_index = set_diag(edge_index)\n\n # propagate_type: (x: OptPairTensor, alpha: OptPairTensor)\n out = self.propagate(edge_index, x=(x_l, x_r),\n alpha=(alpha_l, alpha_r), size=size)\n\n print('out: ', out.shape)\n\n alpha = self._alpha\n self._alpha = None\n\n if self.concat:\n out = out.view(-1, self.heads * self.out_channels)\n else:\n out = out.mean(dim=1)\n\n if self.bias is not None:\n if self.quant:\n # quantize bias\n qbias = quantize(\n self.bias, num_bits=num_bits,\n flatten_dims=(0, -1))\n out += qbias\n else:\n out += self.bias\n\n if self.quant:\n # quantize output\n out = quantize(out, num_bits=num_bits)\n\n if isinstance(return_attention_weights, bool):\n assert alpha is not None\n if isinstance(edge_index, Tensor):\n return out, (edge_index, alpha)\n elif isinstance(edge_index, SparseTensor):\n return out, edge_index.set_value(alpha, layout='coo')\n else:\n return out\n\n def message(self, x_j: Tensor, alpha_j: Tensor, alpha_i: OptTensor,\n index: Tensor, ptr: OptTensor,\n size_i: Optional[int]) -> Tensor:\n # x_j has shape [E, out_channels]\n\n print('x_j: ', x_j.shape)\n print('alpha_i', alpha_i.shape)\n print('alpha_j', alpha_j.shape)\n\n alpha = alpha_j if alpha_i is None else alpha_j + alpha_i\n alpha = F.leaky_relu(alpha, self.negative_slope)\n\n print('alpha before softmax: ', alpha.shape)\n alpha = softmax(alpha, index, ptr, size_i)\n self._alpha = alpha\n\n print('alpha: ', alpha.shape)\n print('alpha: ', alpha.unsqueeze(-1).shape)\n # exit()\n alpha = F.dropout(alpha, p=self.dropout, training=self.training)\n if self.quant:\n # quantize attention matrix\n alpha = quantize(alpha, num_bits=self.num_bits)\n return x_j * alpha.unsqueeze(-1) # 每条边乘以权重后的embedding 每一行=每条边的target端\n\n def __repr__(self):\n return '{}({}, {}, heads={})'.format(self.__class__.__name__,\n self.in_channels,\n self.out_channels, self.heads)\n" ]
[ [ "torch.nn.Linear", "torch.nn.functional.dropout", "torch.Tensor", "torch.nn.functional.leaky_relu" ] ]
bds-ailab/logflow
[ "dfd9e40864494bcfe15f4c1d5a1c72b8a7b67410" ]
[ "logflow/logsparser/Embedding.py" ]
[ "# Copyright 2020 BULL SAS All rights reserved #\nimport word2vec # type: ignore\nimport os\nimport h5py # type: ignore\nfrom loguru import logger\nimport tempfile\nfrom multiprocessing import Pool\nfrom collections import Counter\nimport pickle\nfrom tqdm import tqdm # type: ignore\nimport time\nimport numpy as np # type: ignore\nfrom itertools import repeat\nfrom typing import List, Tuple\n\nclass Embedding:\n \"\"\"Compute the embedding of each pattern based on the word2vec method. Here, each line is represented by the ID (integer) of its pattern.\n\n Note that the word2vec is based on the C++ google implementation. Then, we need to use a file and we cannot use directly the list_classes for the learning step. For best performance, we use\n temporary file to write the list_classes as a file and then remove it.\n\n Args:\n list_classes (list, optional): list of patterns. Defaults to [].\n loading (bool, optional): load the list of patterns from a file. Note that you must provide list_classes is loading is False. Defaults to False.\n name_dataset (str, optional): name of the dataset. Use for loading it. Defaults to \"\".\n path_data (str, optional): path to the dataset. Defaults to \"\".\n path_model (str, optional): path to the model. Defaults to \"\".\n dir_tmp (str, optional): path used for the temporary file. This path can be on SSD or RAM to better performance. Defaults to \"/tmp/\".\n \"\"\"\n def __init__(self, list_classes=[], loading=False, name_dataset=\"\", path_data=\"\", path_model=\"\", dir_tmp=\"\"):\n self.loading = loading\n self.name_dataset = name_dataset\n self.path_data = path_data\n self.path_model = path_model\n self.dir_tmp = dir_tmp\n assert self.path_model != \"\"\n self.giant_str = \"\"\n self.list_classes = list_classes\n self.path_h5py = self.path_data + self.name_dataset + \".lf\"\n\n def load(self):\n \"\"\"Loads the files\n \"\"\"\n logger.info(\"Loading file for embeddings: \" + self.path_h5py)\n\n with h5py.File(self.path_h5py, 'r') as file_h5py:\n self.list_classes = file_h5py['list_patterns'][()]\n logger.info(\"Number of exemples for embeddings: \" + str(len(self.list_classes)))\n\n def start(self):\n \"\"\"Starts the process\n \"\"\"\n self.create_temporary_file()\n if self.loading:\n self.load()\n else:\n assert self.list_classes != []\n self.train()\n self.new_list_classes = []\n self.generate_list_embeddings()\n\n def create_temporary_file(self):\n \"\"\"Create the temporary files for the learning step\n \"\"\"\n # For writting the list_classes as a file.\n if self.dir_tmp != \"\":\n self.fp = tempfile.NamedTemporaryFile(mode=\"w\", dir=self.dir_tmp)\n self.fp_model = tempfile.NamedTemporaryFile(mode=\"w\", dir=self.dir_tmp)\n else:\n self.fp = tempfile.NamedTemporaryFile(mode=\"w\")\n self.fp_model = tempfile.NamedTemporaryFile(mode=\"w\")\n logger.info(\"Temporary files are created: \" + str(self.fp_model.name) + \" , \" + str(self.fp.name))\n\n def train(self):\n \"\"\"Trains the word2vec model based on the list of patterns.\n \"\"\"\n # Merge the list_classes (list of int) into a string for the writting.\n nb_files_per_chunck = int(len(self.list_classes) / (os.cpu_count() * 8))\n if nb_files_per_chunck < 1:\n nb_files_per_chunck = 2\n self.list_chunck = [self.list_classes[i:i + nb_files_per_chunck] for i in range(0, len(self.list_classes), nb_files_per_chunck)]\n list_str_tmp = []\n with Pool(os.cpu_count()) as mp:\n for res in tqdm(mp.imap(Embedding.list_to_str, self.list_chunck), total=len(self.list_chunck)):\n list_str_tmp.append(res)\n self.giant_str = ' '.join(e for e in list_str_tmp)\n with open(self.fp.name, 'w') as f:\n f.write(self.giant_str)\n # Start the learning\n logger.info(\"Starting training w2v: \" + str(os.cpu_count()) + \" threads\")\n word2vec.word2vec(self.fp.name, self.fp_model.name, size=20, verbose=True, threads=os.cpu_count(), binary=True)\n with open(self.path_model + self.name_dataset + \"_model.lf\", \"rb\") as input_file:\n dict_local = pickle.load(input_file)\n # Save the model\n dict_local[\"word2vec\"] = word2vec.load(self.fp_model.name, kind=\"bin\")\n with open(self.path_model + self.name_dataset + \"_model.lf\", \"wb\") as output_file:\n pickle.dump(dict_local, output_file)\n self.fp.close()\n self.fp_model.close()\n\n def generate_list_embeddings(self):\n \"\"\"Filter the list of patterns according to the learned embeddings. The word2vec model requires at least a minimum of examples per word to be learned. We remove the words excluded of the word2vec learning.\n \"\"\"\n with open(self.path_model + self.name_dataset + \"_model.lf\", \"rb\") as file_model:\n dict_model = pickle.load(file_model)\n self.w2v = dict_model[\"word2vec\"]\n self.dict_issue = {}\n try:\n self.list_chunck\n except:\n nb_files_per_chunck = int(len(self.list_classes) / (os.cpu_count() * 2))\n if nb_files_per_chunck < 1:\n nb_files_per_chunck = 2\n self.list_chunck = [self.list_classes[i:i + nb_files_per_chunck] for i in range(0, len(self.list_classes), nb_files_per_chunck)]\n self.list_vocab = []\n # Build the list of vocab. If the word is not an integer, then it's not a valid ID. Remove it.\n for word in self.w2v.vocab:\n try:\n int(word)\n self.list_vocab.append(int(word))\n except:\n pass\n new_list_classes = []\n # Keep only the learned words during the word2vec learning step.\n with Pool(os.cpu_count()) as mp:\n for res in tqdm(mp.imap(Embedding.clear_list, zip(self.list_chunck, repeat(self.list_vocab))), total=len(self.list_chunck)):\n new_list_classes += res.tolist()\n logger.info(str(len(self.list_classes) - len(new_list_classes)) + \" elements are removed due to not enought examples\")\n self.list_classes = new_list_classes\n f = h5py.File(self.path_data + self.name_dataset + \"_embedding.lf\", \"w\")\n f.create_dataset('list_classes', data=self.list_classes)\n f.close()\n\n @staticmethod\n def list_to_str(list_str : List[str]) -> str:\n \"\"\"Merge a list of integer into a string.\n\n Args:\n list_str (list): list of integer\n\n Returns:\n str: string representation\n \"\"\"\n return ' '.join(str(e) for e in list_str)\n\n @staticmethod\n def clear_list(args: Tuple[List[int], List[int]]) -> list:\n \"\"\"Keep only the words from the list of vocab in the list of patterns.\n\n Args:\n args ((list, list)): The first argument is the list of patterns. The second is the list of vocab.\n\n Returns:\n list: list of patterns with only the words into the list of vocab. \n \"\"\"\n list_int, list_vocab = args\n return np.delete(list_int, np.where(np.isin(list_int, list_vocab, invert=True))[0])\n\n" ]
[ [ "numpy.isin" ] ]
jamo1011/hat
[ "ffda7c9eb6d45671ca36eb6f2fdfbf856626d8df" ]
[ "gps/gpstest.py" ]
[ "\nimport gps\nimport numpy as np\n\n# Listen on port 2947 (gpsd) of localhost\nsession = gps.gps(\"localhost\", \"2947\")\nsession.stream(gps.WATCH_ENABLE | gps.WATCH_NEWSTYLE)\n\nlats = np.array([])\nlons = np.array([])\n\nfor i in range(20):\n try:\n report = session.next()\n # Wait for a 'TPV' report and display the current time\n # To see all report data, uncomment the line below\n # print(report)\n if report['class'] == 'TPV':\n if hasattr(report, 'time'):\n print(\"Time: \" + str(report.time))\n if hasattr(report, 'lat'):\n #print(\"Latitude: \" + str(report.lat))\n lats = np.append(lats, report.lat)\n if hasattr(report, 'lon'):\n lons = np.append(lons, report.lon)\n #print(\"Longitude:\" + str(report.lon))\n print()\n except KeyError:\n pass\n except KeyboardInterrupt:\n quit()\n except StopIteration:\n session = None\n print(\"GPSD has terminated\")\n\nf = open(\"data.txt\", \"w\")\n\nprint(\"Average Lattitude: {}\" .format(np.mean(lats)))\nf.write(str(np.means(lats)))\n\nprint(\"Average Longitude: {}\" .format(np.mean(lons)))\nf.write(str(np.means(lons)))\n\nf.close()\n" ]
[ [ "numpy.array", "numpy.means", "numpy.mean", "numpy.append" ] ]
Panxjia/SPA_CVPR2021
[ "32bf2d5d9a49176a32b64b88eef9ea4a6a24d925" ]
[ "utils/list_factory.py" ]
[ "import os\nimport numpy as np\nimport xml.etree.ElementTree as ET\n\n\ndef cub():\n IMAGE_LIST_FILE = '../data/CUB_200_2011/images.txt'\n IMAGE_LABEL_FILE = '../data/CUB_200_2011/image_class_labels.txt'\n BOX_FILE = '../data/CUB_200_2011/bounding_boxes.txt'\n SPLIT_FILE = '../data/CUB_200_2011/train_test_split.txt'\n SPLIT_SET_TEMPLATE = '../data/CUB_200_2011/split_{}.txt'\n SPLIT_SET_BOX_TEMPLATE = '../data/CUB_200_2011/split_{}_box.txt'\n\n with open(IMAGE_LIST_FILE, 'r') as f:\n lines = f.readlines()\n image_names = [x.strip().split(' ')[-1] for x in lines]\n image_names = np.asarray(image_names)\n\n with open(IMAGE_LABEL_FILE, 'r') as f:\n lines = f.readlines()\n img_labels = [int(x.strip().split(' ')[-1]) for x in lines]\n img_labels = np.asarray(img_labels)\n\n with open(BOX_FILE, 'r') as f:\n lines = f.readlines()\n all_box = [x for x in lines]\n\n with open(SPLIT_FILE, 'r') as f:\n lines = f.readlines()\n split_idx = [int(x.strip().split(' ')[-1]) for x in lines]\n split_idx = np.array(split_idx)\n\n for i in np.unique(split_idx):\n with open(SPLIT_SET_TEMPLATE.format(i), 'w') as f:\n for img_idx in np.where(split_idx == i)[0]:\n f.write('{} {}\\n'.format(image_names[img_idx], img_labels[img_idx]-1))\n\n with open(SPLIT_SET_BOX_TEMPLATE.format(i), 'w') as f:\n for img_idx in np.where(split_idx == i)[0]:\n f.write(all_box[img_idx])\n\n\ndef generate_voc_listfile(set_file, list_file):\n classes = ['__background__', # always index 0\n 'aeroplane', 'bicycle', 'bird', 'boat',\n 'bottle', 'bus', 'car', 'cat', 'chair',\n 'cow', 'diningtable', 'dog', 'horse',\n 'motorbike', 'person', 'pottedplant',\n 'sheep', 'sofa', 'train', 'tvmonitor']\n\n IMAGE_FILE_NAME = 'JPEGImages/{}.jpg'\n ANNOTATION_FILE_NAME = '../data/voc2012/Annotations/{}.xml'\n\n with open(set_file, 'r') as f:\n lines = f.readlines()\n train_list_filenmae = [IMAGE_FILE_NAME.format(x.strip()) for x in lines]\n\n # get gt_labels\n gt_labels = []\n for x in lines:\n tree = ET.parse(ANNOTATION_FILE_NAME.format(x.strip()))\n\n objs = tree.findall('object')\n\n # filter difficult example\n non_diff_objs = [obj for obj in objs if int(obj.find('difficult').text) == 0]\n objs = non_diff_objs\n num_objs = len(objs)\n\n gt_classes = np.zeros(num_objs, dtype=np.int32)\n class_to_index = dict(zip(classes, range(len(classes))))\n\n # Load object bounding boxes into a data frame.\n for ix, obj in enumerate(objs):\n cls = class_to_index[obj.find('name').text.lower().strip()]\n gt_classes[ix] = cls - 1\n gt_labels.append(np.unique(gt_classes))\n\n with open(list_file, 'w') as f:\n for img_name, labels in zip(train_list_filenmae, gt_labels):\n line_str = img_name\n for lbl in labels:\n line_str += ' {}'.format(lbl)\n line_str += '\\n'\n f.write(line_str)\n\n\ndef voc():\n TRAINSET_FILE = '../data/voc2012/ImageSets/Main/train.txt'\n VALSET_FILE = '../data/voc2012/ImageSets/Main/val.txt'\n\n if not os.path.exists('../data/voc2012/list'):\n os.makedirs('../data/voc2012/list')\n\n TRAIN_LIST_FILE = '../data/voc2012/list/train_list.txt'\n VAL_LIST_FILE = '../data/voc2012/list/val_list.txt'\n\n generate_voc_listfile(TRAINSET_FILE, TRAIN_LIST_FILE)\n generate_voc_listfile(VALSET_FILE, VAL_LIST_FILE)\n\n\nif __name__ == '__main__':\n cub()\n" ]
[ [ "numpy.array", "numpy.asarray", "numpy.zeros", "numpy.where", "numpy.unique" ] ]
xrazis/university
[ "925bce38fa4d3a9cc013cfa6d7f1de26227cc38f" ]
[ "imageProcessing/lab2/part2.py" ]
[ "import cv2 as cv\nimport numpy as np\nfrom matplotlib import pyplot as plt\nfrom skimage.util import random_noise\n\n\ndef compare_images(image_1, image_2):\n diff = image_1 - image_2\n return np.count_nonzero(abs(diff))\n\n\n# Read the image and convert to b&w\nimg = cv.imread('me-ktm.jpg', 0)\n\n# Detect edges with Canny\ncanny_edges_0 = cv.Canny(img, 100, 200)\nplt.imshow(canny_edges_0, cmap='gray')\nplt.show()\n\n# Add Gaussian noise to image\ngaussian_img = random_noise(img, mode='gaussian', seed=None, clip=True)\ncv.imwrite('me-ktm-gaussian.jpg', gaussian_img)\ncv.imshow('Image with Gaussian noise', gaussian_img)\n\n# Clean with median filter\nmedian_img = cv.medianBlur((255 * gaussian_img).astype(np.uint8), 5)\ncv.imwrite('me-ktm-median.jpg', median_img)\ncv.imshow('Gaussian noise image cleared with median filter', median_img)\n\n# Wait for user keypress then destroy windows\ncv.waitKey()\ncv.destroyAllWindows()\n\n# Detect edges with Canny\ncanny_edges_1 = cv.Canny(median_img, 100, 200)\nplt.imshow(canny_edges_1, cmap='gray')\nplt.show()\n\n# Compare the two edge images\nprint('The two images differ by {} pixels'.format(compare_images(canny_edges_0, canny_edges_1)))\n\n# Detect edges with Sobel\nsobel_edges = cv.Sobel(gaussian_img, cv.CV_64F, 1, 1, ksize=7)\nsobel_edges = np.uint8(np.absolute(sobel_edges))\nplt.imshow(sobel_edges, cmap='gray')\nplt.show()\nprint('The two images differ by {} pixels'.format(compare_images(canny_edges_0, sobel_edges)))\n\n# Detect edges with Laplace\nlaplace_edges = cv.Laplacian(gaussian_img, cv.CV_64F, ksize=7)\nlaplace_edges = np.uint8(np.absolute(laplace_edges))\nplt.imshow(laplace_edges, cmap='gray')\nplt.show()\nprint('The two images differ by {} pixels'.format(compare_images(canny_edges_0, laplace_edges)))\n" ]
[ [ "matplotlib.pyplot.show", "numpy.absolute", "matplotlib.pyplot.imshow" ] ]
flourscent/DLFS_code
[ "173d72884cea4609957cb3f38557a2cacbf8df03" ]
[ "lincoln/lincoln/losses.py" ]
[ "import numpy as np\nfrom numpy import ndarray\n\nfrom lincoln.utils.np_utils import (assert_same_shape,\n softmax,\n normalize,\n #exp_ratios,\n unnormalize)\n\n\nclass Loss(object):\n\n def __init__(self):\n pass\n\n def forward(self,\n prediction: ndarray,\n target: ndarray) -> float:\n\n # batch size x num_classes\n assert_same_shape(prediction, target)\n\n self.prediction = prediction\n self.target = target\n\n self.output = self._output()\n\n return self.output\n\n def backward(self) -> ndarray:\n\n self.input_grad = self._input_grad()\n\n assert_same_shape(self.prediction, self.input_grad)\n\n return self.input_grad\n\n def _output(self) -> float:\n raise NotImplementedError()\n\n def _input_grad(self) -> ndarray:\n raise NotImplementedError()\n\n\nclass MeanSquaredError(Loss):\n\n def __init__(self,\n normalize: bool = False) -> None:\n super().__init__()\n self.normalize = normalize\n\n def _output(self) -> float:\n\n if self.normalize:\n self.prediction = self.prediction / self.prediction.sum(axis=1, keepdims=True)\n\n loss = np.sum(np.power(self.prediction - self.target, 2)) / self.prediction.shape[0]\n\n return loss\n\n def _input_grad(self) -> ndarray:\n\n return 2.0 * (self.prediction - self.target) / self.prediction.shape[0]\n\n\nclass SoftmaxCrossEntropy(Loss):\n def __init__(self, eps: float=1e-9) -> None:\n super().__init__()\n self.eps = eps\n self.single_class = False\n\n def _output(self) -> float:\n\n # if the network is just outputting probabilities\n # of just belonging to one class:\n if self.target.shape[1] == 0:\n self.single_class = True\n\n # if \"single_class\", apply the \"normalize\" operation defined above:\n if self.single_class:\n self.prediction, self.target = \\\n normalize(self.prediction), normalize(self.target)\n\n # applying the softmax function to each row (observation)\n softmax_preds = softmax(self.prediction, axis=1)\n\n # clipping the softmax output to prevent numeric instability\n self.softmax_preds = np.clip(softmax_preds, self.eps, 1 - self.eps)\n\n # actual loss computation\n softmax_cross_entropy_loss = (\n -1.0 * self.target * np.log(self.softmax_preds) - \\\n (1.0 - self.target) * np.log(1 - self.softmax_preds)\n )\n\n return np.sum(softmax_cross_entropy_loss) / self.prediction.shape[0]\n\n def _input_grad(self) -> ndarray:\n\n # if \"single_class\", \"un-normalize\" probabilities before returning gradient:\n if self.single_class:\n return unnormalize(self.softmax_preds - self.target)\n else:\n return (self.softmax_preds - self.target) / self.prediction.shape[0]\n\n\nclass SoftmaxCrossEntropyComplex(SoftmaxCrossEntropy):\n def __init__(self, eta: float=1e-9,\n single_output: bool = False) -> None:\n super().__init__()\n self.single_output = single_output\n\n def _input_grad(self) -> ndarray:\n\n prob_grads = []\n batch_size = self.softmax_preds.shape[0]\n num_features = self.softmax_preds.shape[1]\n for n in range(batch_size):\n exp_ratio = exp_ratios(self.prediction[n] - np.max(self.prediction[n]))\n jacobian = np.zeros((num_features, num_features))\n for f1 in range(num_features): # p index\n for f2 in range(num_features): # SCE index\n if f1 == f2:\n jacobian[f1][f2] = (\n self.softmax_preds[n][f1] - self.target[n][f1])\n else:\n jacobian[f1][f2] = (\n -(self.target[n][f2]-1) * exp_ratio[f1][f2] + self.target[n][f2] + self.softmax_preds[n][f1] - 1)\n prob_grads.append(jacobian.sum(axis=1))\n\n if self.single_class:\n return unnormalize(np.stack(prob_grads))\n else:\n return np.stack(prob_grads)\n" ]
[ [ "numpy.max", "numpy.zeros", "numpy.log", "numpy.sum", "numpy.stack", "numpy.power", "numpy.clip" ] ]
phareskrad/seizure-detection
[ "01da41fd0006afddda0bc87e1a7613c73d37a712" ]
[ "seizure/models.py" ]
[ "import numpy as np\nfrom sklearn.ensemble import RandomForestClassifier\nimport xgboost as xgb\nfrom keras.models import Sequential\nfrom common.utils.generator import dict_generator\nfrom common.classifiers import Model\n\n\nclass RandomForest(Model):\n def __init__(self, name, **params):\n super(RandomForest, self).__init__(name)\n self.model = RandomForestClassifier()\n self.model.set_params(**params)\n\n def fit(self, data, use_all_data):\n if use_all_data:\n self.model.fit(data.X, data.y)\n else:\n self.model.fit(data.X_train, data.y_train)\n\n def predict_proba(self, x_test):\n predictions = self.model.predict_proba(x_test)\n return predictions[:, 1]\n\n @staticmethod\n def generate_models(params):\n models = []\n for param in dict_generator(params):\n name = 'RFe%ss%sb%sj%sr%s' % tuple(param.values())\n models.append(RandomForest(name, **param))\n return models\n\n\nclass XGBTree(Model):\n def __init__(self, name, **params):\n super(XGBTree, self).__init__(name)\n self.model = xgb.XGBClassifier()\n self.model.set_params(**params)\n\n def fit(self, data, use_all_data):\n self.model.fit(data.X_train, data.y_train,\n eval_set=[(data.X_train, data.y_train), (data.X_cv, data.y_cv)],\n eval_metric='logloss', early_stopping_rounds=5)\n if use_all_data:\n self.model.set_params(n_estimators=self.model.best_iteration)\n self.model.fit(data.X, data.y)\n\n def predict_proba(self, x_test):\n predictions = self.model.predict_proba(x_test, ntree_limit=self.model.best_ntree_limit)\n return predictions[:, 1]\n\n @staticmethod\n def generate_models(params):\n #params are reg_alpha, learning_rate, nthread, n_estimators, subsample, reg_lambda, max_depth, gamma\n models = []\n for param in dict_generator(params):\n name = 'XGBTreed%sl%se%sg%ss%sa%sl%st%s' % tuple(param.values())\n models.append(XGBTree(name, **param))\n return models\n\n\nclass XGBLinear(Model):\n def __init__(self, name, **params):\n super(XGBLinear, self).__init__(name)\n self.model = xgb.XGBRegressor()\n self.model.set_params(**params)\n\n def fit(self, data, use_all_data):\n self.model.fit(data.X_train, data.y_train,\n eval_set=[(data.X_train, data.y_train), (data.X_cv, data.y_cv)],\n eval_metric='logloss', early_stopping_rounds=5)\n if use_all_data:\n self.model.set_params(n_estimators=self.model.best_iteration)\n self.model.fit(data.X, data.y)\n\n def predict_proba(self, x_test):\n return self.model.predict(x_test, ntree_limit=self.model.best_ntree_limit)\n\n @staticmethod\n def generate_models(params):\n # params are reg_alpha, learning_rate, nthread, n_estimators, subsample, reg_lambda, max_depth, gamma\n models = []\n for param in dict_generator(params):\n name = 'XGBLineard%sl%se%sg%ss%sa%sl%st%s' % tuple(param.values())\n models.append(XGBLinear(name, **param))\n return models\n\n\nclass NNSeq(Model):\n \"\"\"\n layer_set should be as [layer, layer ,layer,]\n compile_params and fit_params should be dictionary\n \"\"\"\n def __init__(self, name, layer_set, compile_params, fit_params):\n super(NNSeq, self).__init__(name)\n self.model = Sequential(layer_set)\n self.model.compile(**compile_params)\n self.fit_params = fit_params\n\n def batch_generator(self, x, y=None):\n batch_size = self.fit_params['batch_size']\n number_of_batches = np.ceil(x.shape[0] / float(batch_size))\n counter = 0\n sample_index = np.arange(x.shape[0])\n is_train = y is not None\n if is_train:\n np.random.shuffle(sample_index)\n while True:\n batch_index = sample_index[batch_size * counter:batch_size * (counter + 1)]\n X_batch = x[batch_index, :]\n counter += 1\n if is_train:\n y_batch = y[batch_index]\n yield X_batch, y_batch\n else:\n yield X_batch\n if (counter == number_of_batches):\n if is_train:\n np.random.shuffle(sample_index)\n counter = 0\n\n def get_sample_size(self, data_shape):\n batch_size = self.fit_params['batch_size']\n return min(data_shape, batch_size * np.ceil(data_shape / float(batch_size)))\n\n def fit(self, data, use_all_data):\n if use_all_data:\n self.model.fit_generator(generator=self.batch_generator(x=data.X, y=data.y),\n nb_epoch=self.fit_params['nb_epoch'],\n samples_per_epoch=self.get_sample_size(data.X.shape[0]),\n verbose=self.fit_params['verbose'])\n else:\n self.model.fit_generator(generator=self.batch_generator(x=data.X_train, y=data.y_train),\n nb_epoch=self.fit_params['nb_epoch'],\n samples_per_epoch=self.get_sample_size(data.X_train.shape[0]),\n verbose=self.fit_params['verbose'])\n\n def predict_proba(self, x_test):\n predictions = self.model.predict_generator(generator=self.batch_generator(x_test),\n val_samples=x_test.shape[0])\n return predictions[:, 0]\n" ]
[ [ "sklearn.ensemble.RandomForestClassifier", "numpy.arange", "numpy.random.shuffle" ] ]
mandy0104/ada-job-shop
[ "e9127eae7d5ce788d27af85ceb2aaefaf2918844" ]
[ "model.py" ]
[ "import os\nimport copy\nimport math\nimport numpy as np\nimport gurobipy as gp\nfrom gurobipy import GRB\n\n\ndef save_checkpoint(model, where):\n try:\n model_check_point = np.array([abs(var.x) for var in model.getVars()])\n np.save(os.path.join(\"sol\", model.ModelName), model_check_point)\n except:\n pass\n\n\nclass Model:\n def __init__(self, model_name, input, output, problem_cnt):\n print(\"Creating model: {}\".format(model_name))\n self.m = gp.Model(name=model_name)\n self.problem = problem_cnt.split(\".\")[0]\n self.data = copy.deepcopy(input)\n self.L_cnt = len(self.data.sets.L)\n self.N_cnt = len(self.data.sets.N)\n self.M_cnt = max(self.data.sets.M)\n self.T_cnt = self.data.parameters.T\n self.output = copy.deepcopy(output)\n\n def __cal_obj_numpy(self, x):\n return (\n np.max(np.max(x + self.data.parameters.D - 1, axis=1))\n + np.sum(\n self.data.parameters.W * np.max(x + self.data.parameters.D - 1, axis=1)\n )\n * self.window\n )\n\n def __get_sol_result_params(self, path):\n try:\n saved_model_params = np.load(path)\n x_saved = np.empty((self.N_cnt, self.M_cnt)).astype(\"int\")\n y_saved = np.zeros((self.N_cnt, self.M_cnt, self.T_cnt)).astype(\"int\")\n tmp_T_cnt = (\n int(\n (len(saved_model_params) - (1 + self.N_cnt))\n / self.N_cnt\n / self.M_cnt\n )\n - 1\n )\n npy_idx = 1 + self.N_cnt\n for n in range(self.N_cnt):\n for m in range(self.M_cnt):\n x_saved[n][m] = saved_model_params[npy_idx]\n npy_idx += 1\n for n in range(self.N_cnt):\n for m in range(self.M_cnt):\n for t in range(tmp_T_cnt):\n y_saved[n][m][t] = saved_model_params[npy_idx]\n npy_idx += 1\n return x_saved, y_saved\n except:\n return None, None\n\n def gen_operations_order(self, problem_prefix):\n x_saved, _ = self.__get_sol_result_params(\n os.path.join(\"sol\", \"{}.sol.npy\".format(problem_prefix))\n )\n results = []\n for n in range(self.N_cnt):\n for m in range(self.M_cnt):\n if self.data.parameters.S[n][m]:\n results.append(\n [\n n,\n m,\n x_saved[n][m],\n self.data.parameters.S[n][m],\n self.data.parameters.D[n][m],\n [],\n ]\n )\n return results\n\n def pre_solve(self, window, sort_num=1):\n\n print(\"Running presolve...\")\n print(\"window = {}\".format(window))\n\n self.window = window\n self.data.parameters.D = (\n np.ceil(np.array(self.data.parameters.D) / window).astype(\"int\").tolist()\n )\n\n \"\"\"\n 選所有 jobs 中 W 最大的\n 選沒被 block 且 S 夠的當中 D 最小的 operation\n \"\"\"\n\n dp = np.zeros((self.T_cnt, self.L_cnt)).astype(\"int\")\n x = np.empty((self.N_cnt, self.M_cnt))\n y = np.zeros((self.N_cnt, self.M_cnt, self.T_cnt)).astype(\"int\")\n finish_time = -1 * np.ones((self.N_cnt, self.M_cnt)).astype(\"int\")\n\n for t in range(self.T_cnt):\n jobs_idx_sorted_by_w = sorted(\n zip(\n np.arange(self.N_cnt).tolist(),\n self.data.parameters.W,\n np.sum(self.data.parameters.D, axis=1).tolist(),\n np.sum(self.data.parameters.S, axis=1).tolist(),\n ),\n key=lambda x: x[1]\n if sort_num == 1\n else x[1] / x[2]\n if sort_num == 2\n else x[1] / x[2] / x[3],\n reverse=True,\n )\n for job_idx, _, __, ___ in jobs_idx_sorted_by_w:\n operations_idx_sorted_by_D = sorted(\n zip(\n np.arange(self.data.sets.M[job_idx]).tolist(),\n self.data.parameters.D[job_idx][: self.data.sets.M[job_idx]],\n ),\n key=lambda x: x[1],\n )\n for operation_idx, d in operations_idx_sorted_by_D:\n if (\n finish_time[job_idx][operation_idx] == -1\n and self.L_cnt - np.sum(dp[t])\n >= self.data.parameters.S[job_idx][operation_idx]\n ):\n needed = self.data.parameters.S[job_idx][operation_idx]\n usage_queue_if_available = []\n for l in range(self.L_cnt):\n if needed and not dp[t][l]:\n dependency_finished = True\n for a in self.data.parameters.A[job_idx][operation_idx]:\n if (\n finish_time[job_idx][a] == -1\n or t <= finish_time[job_idx][a]\n ):\n dependency_finished = False\n if dependency_finished:\n needed -= 1\n usage_queue_if_available.append(l)\n if not needed:\n x[job_idx][operation_idx] = t\n for t_prime in range(d):\n for l in usage_queue_if_available:\n dp[t + t_prime][l] = 1\n y[job_idx][operation_idx][t + t_prime] = 1\n finish_time[job_idx][operation_idx] = t + d - 1\n\n obj_from_greedy = self.__cal_obj_numpy(x)\n\n if os.path.exists(os.path.join(\"sol\", \"{}.npy\".format(self.m.ModelName))):\n\n x_saved, y_saved = self.__get_sol_result_params(\n os.path.join(\"sol\", \"{}.npy\".format(self.m.ModelName))\n )\n\n if x_saved is not None:\n obj_from_saved = self.__cal_obj_numpy(x_saved)\n else:\n obj_from_saved = np.inf\n\n print(\"saved: {}, greedy: {}\".format(obj_from_saved, obj_from_greedy))\n\n if obj_from_saved < obj_from_greedy:\n print(\"Using saved...\")\n x = x_saved\n y = y_saved\n else:\n print(\"Using greedy...\")\n\n else:\n print(\"Using greedy...\")\n print(\"Objective value = {}\".format(obj_from_greedy))\n\n # 操作必須連續執行\n for n in range(self.N_cnt):\n for m in range(self.M_cnt):\n assert np.sum(\n [y[n][m][i] * y[n][m][i + 1] for i in range(self.T_cnt - 1)]\n ) == max(0, self.data.parameters.D[n][m] - 1)\n\n # 操作時長等於所需時長\n for n in range(self.N_cnt):\n for m in range(self.M_cnt):\n assert (\n np.sum([y[n][m][i] for i in range(self.T_cnt)])\n == self.data.parameters.D[n][m]\n )\n\n # Dependency 限制\n for n in range(self.N_cnt):\n for m in range(self.M_cnt):\n for a in self.data.parameters.A[n][m]:\n dependency = (\n np.sum([y[n][a][t] * t for t in range(self.T_cnt)])\n * 2\n // self.data.parameters.D[n][a]\n + 1\n - self.data.parameters.D[n][a]\n ) // 2\n target = (\n np.sum([y[n][m][t] * t for t in range(self.T_cnt)])\n * 2\n // self.data.parameters.D[n][m]\n + self.data.parameters.D[n][m]\n - 1\n ) // 2\n assert target > dependency\n\n self.T_cnt = min(\n self.T_cnt,\n int(np.max(np.where(np.sum(np.sum(y, axis=0), axis=0) != 0))) + 5,\n )\n\n self.output.variables.C_max = self.m.addVar(\n vtype=GRB.INTEGER, lb=0.0, ub=float(self.T_cnt)\n )\n self.output.variables.C = self.m.addVars(\n self.N_cnt, vtype=GRB.INTEGER, lb=0.0, ub=float(self.T_cnt)\n )\n self.output.variables.x = self.m.addVars(\n self.N_cnt, self.M_cnt, vtype=GRB.INTEGER, lb=0.0, ub=float(self.T_cnt)\n )\n self.output.variables.y = self.m.addVars(\n self.N_cnt, self.M_cnt, self.T_cnt, vtype=GRB.BINARY, lb=0.0, ub=1.0\n )\n\n for i, c in enumerate(np.max(x + self.data.parameters.D - 1, axis=1)):\n self.output.variables.C[i].start = c\n self.output.variables.C_max.start = np.max(\n np.max(x + self.data.parameters.D - 1, axis=1)\n )\n for n in range(self.N_cnt):\n for m in range(self.M_cnt):\n self.output.variables.x[n, m].start = x[n][m]\n for t in range(self.T_cnt):\n try:\n self.output.variables.y[n, m, t].start = y[n][m][t]\n except:\n print(n, m, t, self.T_cnt)\n exit()\n\n def formulation(self):\n \"\"\"\n Set Objective\n \"\"\"\n self.m.setObjective(\n (\n self.output.variables.C_max\n + gp.quicksum(\n (self.data.parameters.W[n] * self.output.variables.C[n])\n for n in range(self.N_cnt)\n )\n )\n * self.window,\n GRB.MINIMIZE,\n )\n print(\"Objective\")\n \"\"\"\n Add Constraints\n \"\"\"\n # Makespan 的計算\n for n in range(self.N_cnt):\n for m in range(self.M_cnt):\n if self.data.parameters.S[n][m]:\n for t in range(self.T_cnt):\n self.m.addConstr(\n self.output.variables.C[n]\n >= self.output.variables.x[n, m]\n + self.data.parameters.D[n][m]\n - 1\n )\n for n in range(self.N_cnt):\n self.m.addConstr(self.output.variables.C_max >= self.output.variables.C[n])\n print(\"c1: Makespan 的計算\")\n # 同時間資源使用不能超過總資源數\n for t in range(self.T_cnt):\n self.m.addConstr(\n gp.quicksum(\n self.data.parameters.S[n][m] * self.output.variables.y[n, m, t]\n for n in range(self.N_cnt)\n for m in range(self.M_cnt)\n if self.data.parameters.S[n][m]\n )\n <= self.L_cnt\n )\n print(\"c2: 同時間資源使用不能超過總資源數\")\n # 操作必須連續執行\n for n in range(self.N_cnt):\n for m in range(self.M_cnt):\n if self.data.parameters.S[n][m]:\n self.m.addConstr(\n (\n gp.quicksum(\n self.output.variables.y[n, m, t] * t\n for t in range(self.T_cnt)\n )\n * 2\n / self.data.parameters.D[n][m]\n + 1\n - self.data.parameters.D[n][m]\n )\n / 2\n >= self.output.variables.x[n, m]\n )\n for t in range(self.T_cnt):\n self.m.addConstr(\n self.output.variables.y[n, m, t] * t\n <= self.output.variables.x[n, m]\n + self.data.parameters.D[n][m]\n - 1\n )\n print(\"c3: 操作必須連續執行\")\n # 操作時長等於所需時長\n for n in range(self.N_cnt):\n for m in range(self.M_cnt):\n if self.data.parameters.S[n][m]:\n self.m.addConstr(\n gp.quicksum(\n self.output.variables.y[n, m, t] for t in range(self.T_cnt)\n )\n == self.data.parameters.D[n][m]\n )\n print(\"c4: 操作時長等於所需時長\")\n # Dependency 限制\n for n in range(self.N_cnt):\n for m in range(self.M_cnt):\n for m_prime in self.data.parameters.A[n][m]:\n self.m.addConstr(\n self.output.variables.x[n, m]\n >= self.output.variables.x[n, m_prime]\n + self.data.parameters.D[n][m_prime]\n )\n print(\"c5: Dependency 限制\")\n\n def optimize(self, time_limit=np.inf, target=-np.inf):\n \"\"\"\n Optimization\n \"\"\"\n if self.m.ModelName != \"01.sol\":\n self.m.setParam(\"Timelimit\", time_limit)\n self.m.params.BestObjStop = target\n self.m.optimize(callback=save_checkpoint)" ]
[ [ "numpy.max", "numpy.array", "numpy.empty", "numpy.zeros", "numpy.sum", "numpy.ones", "numpy.load", "numpy.arange" ] ]
amznero/graph-learn
[ "77bd92f960e4d178a3606444684f7f04c7f5b738" ]
[ "graphlearn/python/tests/test_node.py" ]
[ "# Copyright 2020 Alibaba Group Holding Limited. 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\"\"\" Base class for node test cases.\n\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport unittest\nimport numpy as np\n\nimport graphlearn.python.tests.utils as utils\n\n\nclass NodeTestCase(unittest.TestCase):\n @classmethod\n def setUpClass(cls):\n pass\n\n @classmethod\n def tearDownClass(cls):\n pass\n\n def setUp(self):\n utils.prepare_env()\n\n self.node_type_ = 'user'\n self.value_range_ = (0, 100)\n self.ids_ = np.array([2, 5, 8])\n\n def tearDown(self):\n pass\n\n def gen_test_data(self, schema):\n return utils.gen_node_data(id_type=self.node_type_,\n id_range=self.value_range_,\n schema=schema)\n\n def check_weights(self, nodes):\n self.assertEqual(3, nodes.weights.shape[0])\n self.assertAlmostEqual(0.2, nodes.weights[0])\n self.assertAlmostEqual(0.5, nodes.weights[1])\n self.assertAlmostEqual(0.8, nodes.weights[2])\n\n def check_labels(self, nodes):\n self.assertEqual(3, nodes.labels.shape[0])\n self.assertEqual(2, nodes.labels[0])\n self.assertEqual(5, nodes.labels[1])\n self.assertEqual(8, nodes.labels[2])\n\n def check_attrs(self, nodes):\n self.assertListEqual([3, 2], list(nodes.int_attrs.shape)) # [int_num, batch_size]\n self.assertListEqual([3, 1], list(nodes.float_attrs.shape)) # [float_num, batch_size]\n self.assertListEqual([3, 1], list(nodes.string_attrs.shape)) # [string_num, batch_size]\n\n for i, value in zip(range(3), self.ids_):\n # the second int is hash value, here we just check the first one\n self.assertEqual(nodes.int_attrs[i][0], value)\n self.assertEqual(nodes.float_attrs[i][0], float(value))\n self.assertEqual(nodes.string_attrs[i][0], str(value))\n" ]
[ [ "numpy.array" ] ]
safooray/tensor_factorization_mtl
[ "9d8257db6b54b202ad51fcc632573f1dc5e4bcb9" ]
[ "survival_mtl.py" ]
[ "import sys\nsys.path.append('../TranSurvivalNet')\nfrom IPython import embed\nfrom losses.tf_cox_loss import cox_loss\nfrom survival_analysis import calc_at_risk, c_index\nfrom utils.data_utils import load_pca_npy_data\nfrom utils.data_utils import pca \n\nimport numpy as np\nimport os\nimport tensorflow as tf\nslim = tf.contrib.slim\nfrom tensor_toolbox_yyang import TensorProducer\n\ndata_path = '../TranSurvivalNet/data/gene_pca/'\nT = 3 # number of tasks\nH = 50\n\nD = 300 \nX = []\nY = []\nA = []\nACROS = ['BRCA', 'OV', 'HNSC', 'KIRC']\nbrca_x, brca_t, brca_o = load_pca_npy_data(data_path, acronym='BRCA')\nhnsc_x, hnsc_t, hnsc_o = load_pca_npy_data(data_path, acronym='HNSC')\nkirc_x, kirc_t, kirc_o = load_pca_npy_data(data_path, acronym='KIRC')\n\n\nX = [brca_x, hnsc_x, kirc_x]\nC = [1-brca_o, 1-hnsc_o, 1-kirc_o]\nY = [brca_t, hnsc_t, kirc_t]\n#A = [None] * T\n#for i in range(T):\n# X[i], Y[i], E[i], A[i] = calc_at_risk(X[i], Y[i], E[i])\n\n\n#Single Task Learning\nwith tf.device(\"/cpu:0\"):\n with tf.Graph().as_default():\n X_placeholder = [tf.placeholder(tf.float32, shape=[n, D]) for n in [x.shape[0] for x in X]]\n C_placeholder = [tf.placeholder(tf.float32, shape=[n,]) for n in [x.shape[0] for x in X]]\n Y_placeholder = [tf.placeholder(tf.float32, shape=[n,]) for n in [x.shape[0] for x in X]]\n\n W_input_to_hidden = [tf.Variable(tf.truncated_normal(shape=[D, H])) for _ in range(T)]\n b_input_to_hidden = [tf.Variable(tf.zeros(shape=[H])) for _ in range(T)]\n W_hidden_to_output = [tf.Variable(tf.truncated_normal(shape=[H,1])) for _ in range(T)]\n b_hidden_to_output = [tf.Variable(tf.zeros(shape=[1])) for _ in range(T)]\n\n Y_hat = [tf.nn.xw_plus_b(tf.nn.sigmoid(tf.nn.xw_plus_b(x,w0,b0)),w1,b1) \n for x,w0,b0,w1,b1 in zip(X_placeholder, W_input_to_hidden, b_input_to_hidden, W_hidden_to_output, b_hidden_to_output)]\n\n loss = tf.reduce_mean([cox_loss(pred, t, c) for pred, t, c in zip(Y_hat, Y_placeholder, C_placeholder)])\n opt = tf.train.GradientDescentOptimizer(learning_rate=0.01)\n train = opt.minimize(loss)\n with tf.Session() as sess:\n sess.run(tf.global_variables_initializer())\n feed_dict = dict(list(zip(X_placeholder,X))+list(zip(Y_placeholder,Y))+list(zip(C_placeholder,C)))\n for _ in range(100):\n train.run(feed_dict=feed_dict)\n if _ % 10 == 0:\n print(loss.eval(feed_dict=feed_dict))\n \n preds_val = sess.run(Y_hat, feed_dict=feed_dict)\n W_init = sess.run(W_input_to_hidden)\n\nfor i in range(T):\n ci = c_index(preds_val[i], Y[i], C[i])\n print(\"MTL ci {} = {}\".format(ACROS[i], ci))\n\n# Multi-task Learning with Tensor Factorisation\nwith tf.device(\"/cpu:0\"):\n with tf.Graph().as_default():\n X_placeholder = [tf.placeholder(tf.float32, shape=[n, D]) for n in [x.shape[0] for x in X]]\n C_placeholder = [tf.placeholder(tf.float32, shape=[n,]) for n in [x.shape[0] for x in X]]\n Y_placeholder = [tf.placeholder(tf.float32, shape=[n,]) for n in [x.shape[0] for x in X]]\n\n W_init = np.stack(W_init, axis=0)\n W_init = np.transpose(W_init, axes=[1,2,0])\n W_input_to_hidden, W_factors = TensorProducer(W_init, 'LAF', eps_or_k=0.1, return_true_var=True)\n W_input_to_hidden = [W_input_to_hidden[:,:,i] for i in range(T)]\n b_input_to_hidden = [tf.Variable(tf.zeros(shape=[H])) for _ in range(T)]\n W_hidden_to_output = [tf.Variable(tf.truncated_normal(shape=[H,1])) for _ in range(T)]\n b_hidden_to_output = [tf.Variable(tf.zeros(shape=[1])) for _ in range(T)]\n \n Y_hat = [tf.nn.xw_plus_b(tf.nn.sigmoid(tf.nn.xw_plus_b(x,w0,b0)),w1,b1) \n for x,w0,b0,w1,b1 in zip(X_placeholder, W_input_to_hidden, b_input_to_hidden, W_hidden_to_output, b_hidden_to_output)]\n\n loss = tf.reduce_mean([cox_loss(pred, t, c) for pred, t, c in zip(Y_hat, Y_placeholder, C_placeholder)])\n opt = tf.train.GradientDescentOptimizer(learning_rate=0.001)\n train = opt.minimize(loss)\n with tf.Session() as sess:\n sess.run(tf.global_variables_initializer())\n feed_dict = dict(list(zip(X_placeholder,X))+list(zip(Y_placeholder,Y))+list(zip(C_placeholder,C)))\n for _ in range(1000):\n train.run(feed_dict=feed_dict)\n if _ % 10 == 0:\n print(loss.eval(feed_dict=feed_dict))\n \n preds_val = sess.run(Y_hat, feed_dict=feed_dict)\n W_val, W_factors_val = sess.run([W_input_to_hidden, W_factors])\n embed()\n\nfor i in range(T):\n ci = c_index(preds_val[i], Y[i], C[i])\n print(\"MTL ci {} = {}\".format(ACROS[i], ci))\n" ]
[ [ "tensorflow.zeros", "tensorflow.Graph", "tensorflow.Session", "tensorflow.truncated_normal", "numpy.stack", "numpy.transpose", "tensorflow.placeholder", "tensorflow.device", "tensorflow.nn.xw_plus_b", "tensorflow.global_variables_initializer", "tensorflow.train.GradientDescentOptimizer" ] ]
ckmah/scanpy
[ "300435f30f6805e27ba59a7314fe06ef21d03c17" ]
[ "scanpy/tools/louvain.py" ]
[ "\"\"\"Cluster cells using Louvain community detection algorithm.\n\nUses the pip package \"louvain\" by V. Traag.\n\"\"\"\n\nimport numpy as np\nimport pandas as pd\nfrom natsort import natsorted\nfrom .. import utils\nfrom .. import settings\nfrom .. import logging as logg\nfrom ..data_structs.data_graph import add_or_update_graph_in_adata\n\n\ndef louvain(\n adata,\n n_neighbors=None,\n resolution=None,\n n_pcs=50,\n random_state=0,\n restrict_to=None,\n key_added=None,\n flavor='vtraag',\n directed=True,\n recompute_pca=False,\n recompute_distances=False,\n recompute_graph=False,\n n_dcs=None,\n n_jobs=None,\n copy=False):\n \"\"\"Cluster cells into subgroups [Blondel08]_ [Levine15]_ [Traag17]_.\n\n Cluster cells using the Louvain algorithm [Blondel08]_ in the implementation\n of [Traag17]_. The Louvain algorithm has been proposed for single-cell\n analysis by [Levine15]_.\n\n Parameters\n ----------\n adata : :class:`~scanpy.api.AnnData`\n The annotated data matrix.\n n_neighbors : `int`, optional (default: 30)\n Number of neighbors to use for construction of knn graph.\n resolution : `float` or `None`, optional (default: 1)\n For the default flavor ('vtraag'), you can provide a resolution (higher\n resolution means finding more and smaller clusters), which defaults to\n 1.0.\n n_pcs : int, optional (default: 50)\n Number of PCs to use for computation of data point graph.\n random_state : int, optional (default: 0)\n Change the initialization of the optimization.\n key_added : str, optional (default: `None`)\n Key under which to add the cluster labels.\n restrict_to : tuple, optional (default: None)\n Restrict the clustering to the categories within the key for sample\n annotation, tuple needs to contain (obs key, list of categories).\n flavor : {'vtraag', 'igraph'}\n Choose between to packages for computing the clustering. 'vtraag' is\n much more powerful.\n copy : `bool` (default: False)\n Copy adata or modify it inplace.\n\n Returns\n -------\n Depending on `copy`, returns or updates `adata` with the following fields.\n\n louvain_groups : `pd.Series` (``adata.obs``, dtype `category`)\n Array of dim (number of samples) that stores the subgroup id ('0',\n '1', ...) for each cell.\n \"\"\"\n logg.info('running Louvain clustering', r=True)\n adata = adata.copy() if copy else adata\n add_or_update_graph_in_adata(\n adata,\n n_neighbors=n_neighbors,\n n_pcs=n_pcs,\n n_dcs=n_dcs,\n recompute_pca=recompute_pca,\n recompute_distances=recompute_distances,\n recompute_graph=recompute_graph,\n n_jobs=n_jobs)\n adjacency = adata.uns['data_graph_norm_weights']\n if restrict_to is not None:\n restrict_key, restrict_categories = restrict_to\n if not isinstance(restrict_categories[0], str):\n raise ValueError('You need to use strings to label categories, '\n 'e.g. \\'1\\' instead of 1.')\n restrict_indices = adata.obs[restrict_key].isin(restrict_categories).values\n adjacency = adjacency[restrict_indices, :]\n adjacency = adjacency[:, restrict_indices]\n if flavor in {'vtraag', 'igraph'}:\n if flavor == 'igraph' and resolution is not None:\n logg.warn('`resolution` parameter has no effect for flavor \"igraph\"')\n if directed and flavor == 'igraph':\n directed = False\n if not directed: logg.m(' using the undirected graph', v=4)\n g = utils.get_igraph_from_adjacency(adjacency, directed=directed)\n if flavor == 'vtraag':\n import louvain\n if resolution is None: resolution = 1\n try:\n logg.info(' using the \"louvain\" package of Traag (2017)')\n louvain.set_rng_seed(random_state)\n part = louvain.find_partition(g, louvain.RBConfigurationVertexPartition,\n resolution_parameter=resolution)\n # adata.uns['louvain_quality'] = part.quality()\n except AttributeError:\n logg.warn('Did not find package louvain>=0.6, '\n 'the clustering result will therefore not '\n 'be 100% reproducible, '\n 'but still meaningful. '\n 'If you want 100% reproducible results, '\n 'update via \"pip install louvain --upgrade\".')\n part = louvain.find_partition(g, method='RBConfiguration',\n resolution_parameter=resolution)\n elif flavor == 'igraph':\n part = g.community_multilevel()\n groups = np.array(part.membership)\n elif flavor == 'taynaud':\n # this is deprecated\n import networkx as nx\n import community\n g = nx.Graph(adata.uns['data_graph_distance_local'])\n partition = community.best_partition(g)\n groups = np.zeros(len(partition), dtype=int)\n for k, v in partition.items(): groups[k] = v\n else:\n raise ValueError('`flavor` needs to be \"vtraag\" or \"igraph\" or \"taynaud\".')\n unique_groups = np.unique(groups)\n n_clusters = len(unique_groups)\n if restrict_to is None:\n groups = groups.astype('U')\n key_added = 'louvain_groups' if key_added is None else key_added\n adata.obs[key_added] = pd.Categorical(\n values=groups,\n categories=natsorted(unique_groups.astype('U')))\n else:\n key_added = restrict_key + '_R' if key_added is None else key_added\n groups += 1\n adata.obs[key_added] = adata.obs[restrict_key].astype('U')\n adata.obs[key_added] += ','\n adata.obs[key_added].iloc[restrict_indices] += groups.astype('U')\n adata.obs[key_added].iloc[~restrict_indices] += '0'\n adata.obs[key_added] = adata.obs[key_added].astype(\n 'category', categories=natsorted(adata.obs[key_added].unique()))\n adata.uns['louvain_params'] = np.array((resolution, random_state,),\n dtype=[('resolution', float), ('random_state', int)])\n logg.info(' finished', time=True, end=' ' if settings.verbosity > 2 else '\\n')\n logg.hint('found {} clusters and added\\n'\n ' \\'{}\\', the cluster labels (adata.obs, dtype=category)'\n .format(n_clusters, key_added))\n return adata if copy else None\n" ]
[ [ "numpy.array", "numpy.unique" ] ]
ningning-718/DeepCamera
[ "b2788a884996fd7761f48fbf59094b0375e3df96" ]
[ "src/yolo_detector/work.py" ]
[ "# coding=utf-8\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport os\nimport json\nimport time\n\nfrom celery import Celery\nfrom celery.signals import worker_process_init\nfrom celery.concurrency import asynpool\nfrom yolo import Yolo\nfrom face_filter import FaceFilterClass\nfrom scipy import misc\n\n# deeepeye\nasynpool.PROC_ALIVE_TIMEOUT = 60.0 # set this long enough\n\nredis_host = os.getenv(\"REDIS_HOST\", default=\"localhost\")\nredis_port = os.getenv(\"REDIS_PORT\", default=\"6379\")\n\nENABLE_STATIC_OBJECT_FILTER = json.loads(os.getenv(\"ENABLE_STATIC_OBJECT_FILTER\", default=\"false\").lower())\n\ndeepeye = Celery('upload_api-v2',\n broker='redis://guest@'+redis_host+':'+redis_port+'/0',\n backend='redis://guest@'+redis_host+':'+redis_port+'/0')\n\n\n@worker_process_init.connect()\ndef setup(sender=None, **kwargs):\n global yolo\n yolo = Yolo()\n\n global face_filter\n face_filter = FaceFilterClass()\n\n #warm up\n yolo.crop_persons(\"test3.png\")\n\n\[email protected]\ndef detect(image_path, trackerid, ts, cameraId):\n if ENABLE_STATIC_OBJECT_FILTER:\n img = misc.imread(image_path)\n result, resized_img = face_filter.resize_image(img, 480)\n if result is not None:\n print(\"Resize image error!\")\n return\n star_time = time.time()\n result, rects, min_value, max_value = face_filter.motion_detect(cameraId, resized_img)\n end_time = time.time()\n print('Performance: motion_detect is {}S'.format(end_time-star_time))\n face_filter.save_static_image(cameraId, result, image_path, min_value, max_value)\n result = yolo.detect(image_path, trackerid, ts, cameraId, face_filter)\n else:\n result = yolo.detect(image_path, trackerid, ts, cameraId, face_filter=None)\n\n return result\n\n\ndeepeye.conf.task_routes = {\n 'upload_api-v2.detect': {'queue': 'detect'}\n}\n\nif __name__ == '__main__':\n deepeye.start()\n" ]
[ [ "scipy.misc.imread" ] ]
dcs4cop/xcube-cci
[ "81aab9b30bb00306f783ce2f2f79cb8fab54758d" ]
[ "xcube_cci/chunkstore.py" ]
[ "# The MIT License (MIT)\n# Copyright (c) 2021 by the xcube development team and contributors\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of\n# this software and associated documentation files (the \"Software\"), to deal in\n# the Software without restriction, including without limitation the rights to\n# use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies\n# of the Software, and to permit persons to whom the Software is furnished to do\n# so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all\n# copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\nfrom datetime import datetime\nfrom dateutil.relativedelta import relativedelta\nimport bisect\nimport copy\nimport itertools\nimport json\nimport logging\nimport math\nimport time\nimport warnings\nfrom abc import abstractmethod, ABCMeta\nfrom collections.abc import MutableMapping\nfrom numcodecs import Blosc\nfrom typing import Iterator, Any, List, Dict, Tuple, Callable, Iterable, KeysView, Mapping, Union\n\nimport numpy as np\nimport pandas as pd\n\nfrom .cciodp import CciOdp\nfrom .constants import COMMON_COORD_VAR_NAMES\n\n_STATIC_ARRAY_COMPRESSOR_PARAMS = dict(cname='zstd', clevel=1, shuffle=Blosc.SHUFFLE, blocksize=0)\n_STATIC_ARRAY_COMPRESSOR_CONFIG = dict(id='blosc', **_STATIC_ARRAY_COMPRESSOR_PARAMS)\n_STATIC_ARRAY_COMPRESSOR = Blosc(**_STATIC_ARRAY_COMPRESSOR_PARAMS)\n\n_LOG = logging.getLogger()\n_TIMESTAMP_FORMAT = \"%Y-%m-%dT%H:%M:%S\"\n\n\ndef _dict_to_bytes(d: Dict):\n return _str_to_bytes(json.dumps(d, indent=2))\n\n\ndef _str_to_bytes(s: str):\n return bytes(s, encoding='utf-8')\n\n\n# todo move this to xcube\nclass RemoteChunkStore(MutableMapping, metaclass=ABCMeta):\n \"\"\"\n A remote Zarr Store.\n\n :param data_id: The identifier of the data resource\n :param cube_params: A mapping containing additional parameters to define\n the data set.\n :param observer: An optional callback function called when remote requests\n are mode: observer(**kwargs).\n :param trace_store_calls: Whether store calls shall be printed\n (for debugging).\n \"\"\"\n\n def __init__(self,\n data_id: str,\n cube_params: Mapping[str, Any] = None,\n observer: Callable = None,\n trace_store_calls=False):\n if not cube_params:\n cube_params = {}\n self._variable_names = cube_params.get('variable_names',\n self.get_all_variable_names())\n self._attrs = {}\n self._observers = [observer] if observer is not None else []\n self._trace_store_calls = trace_store_calls\n\n self._dataset_name = data_id\n self._time_ranges = self.get_time_ranges(data_id, cube_params)\n logging.debug('Determined time ranges')\n if not self._time_ranges:\n raise ValueError('Could not determine any valid time stamps')\n\n t_array = [s.to_pydatetime()\n + 0.5 * (e.to_pydatetime() - s.to_pydatetime())\n for s, e in self._time_ranges]\n t_array = np.array(t_array).astype('datetime64[s]').astype(np.int64)\n t_bnds_array = \\\n np.array(self._time_ranges).astype('datetime64[s]').astype(np.int64)\n time_coverage_start = self._time_ranges[0][0]\n time_coverage_end = self._time_ranges[-1][1]\n cube_params['time_range'] = (self._extract_time_range_as_strings(\n cube_params.get('time_range',\n self.get_default_time_range(data_id))))\n\n self._vfs = {}\n self._var_name_to_ranges = {}\n self._ranges_to_indexes = {}\n self._ranges_to_var_names = {}\n\n bbox = cube_params.get('bbox', None)\n lon_size = -1\n lat_size = -1\n self._dimension_chunk_offsets = {}\n self._dimensions = self.get_dimensions()\n coords_data = self.get_coords_data(data_id)\n logging.debug('Determined coordinates')\n coords_data['time'] = {}\n coords_data['time']['size'] = len(t_array)\n coords_data['time']['data'] = t_array\n if 'time_bounds' in coords_data:\n coords_data.pop('time_bounds')\n coords_data['time_bnds'] = {}\n coords_data['time']['size'] = len(t_bnds_array)\n coords_data['time']['data'] = t_bnds_array\n sorted_coords_names = list(coords_data.keys())\n sorted_coords_names.sort()\n lat_min_offset = -1\n lat_max_offset = -1\n lon_min_offset = -1\n lon_max_offset = -1\n for coord_name in sorted_coords_names:\n if coord_name == 'time' or coord_name == 'time_bnds':\n continue\n coord_attrs = self.get_attrs(coord_name)\n coord_attrs['_ARRAY_DIMENSIONS'] = coord_attrs['dimensions']\n coord_data = coords_data[coord_name]['data']\n if bbox is not None and \\\n (coord_name == 'lat' or coord_name == 'latitude'):\n if coord_data[0] < coord_data[-1]:\n lat_min_offset = bisect.bisect_left(coord_data, bbox[1])\n lat_max_offset = bisect.bisect_right(coord_data, bbox[3])\n else:\n lat_min_offset = len(coord_data) - \\\n bisect.bisect_left(coord_data[::-1], bbox[3])\n lat_max_offset = len(coord_data) - \\\n bisect.bisect_right(coord_data[::-1], bbox[1])\n coords_data = self._adjust_coord_data(coord_name,\n lat_min_offset,\n lat_max_offset,\n coords_data,\n coord_attrs)\n coord_data = coords_data[coord_name]['data']\n elif bbox is not None and \\\n (coord_name == 'lon' or coord_name == 'longitude'):\n lon_min_offset = bisect.bisect_left(coord_data, bbox[0])\n lon_max_offset = bisect.bisect_right(coord_data, bbox[2])\n coords_data = self._adjust_coord_data(coord_name,\n lon_min_offset,\n lon_max_offset,\n coords_data,\n coord_attrs)\n coord_data = coords_data[coord_name]['data']\n elif bbox is not None and \\\n (coord_name == 'latitude_bounds' or coord_name == 'lat_bounds'\n or coord_name == 'latitude_bnds' or coord_name == 'lat_bnds'):\n coords_data = self._adjust_coord_data(coord_name,\n lat_min_offset,\n lat_max_offset,\n coords_data,\n coord_attrs)\n coord_data = coords_data[coord_name]['data']\n elif bbox is not None and \\\n (coord_name == 'longitude_bounds' or coord_name == 'lon_bounds'\n or coord_name == 'longitude_bnds' or coord_name == 'lon_bnds'):\n coords_data = self._adjust_coord_data(coord_name,\n lon_min_offset,\n lon_max_offset,\n coords_data,\n coord_attrs)\n coord_data = coords_data[coord_name]['data']\n if len(coord_data) > 0:\n coord_array = np.array(coord_data)\n self._add_static_array(coord_name, coord_array, coord_attrs)\n else:\n shape = list(coords_data[coord_name].\n get('shape', coords_data[coord_name].get('size')))\n chunk_size = coords_data[coord_name]['chunkSize']\n if not isinstance(chunk_size, List):\n chunk_size = [chunk_size]\n encoding = self.get_encoding(coord_name)\n self._add_remote_array(coord_name, shape, chunk_size,\n encoding, coord_attrs)\n\n time_attrs = {\n \"_ARRAY_DIMENSIONS\": ['time'],\n \"units\": \"seconds since 1970-01-01T00:00:00Z\",\n \"calendar\": \"proleptic_gregorian\",\n \"standard_name\": \"time\",\n \"bounds\": \"time_bnds\",\n }\n time_bnds_attrs = {\n \"_ARRAY_DIMENSIONS\": ['time', 'bnds'],\n \"units\": \"seconds since 1970-01-01T00:00:00Z\",\n \"calendar\": \"proleptic_gregorian\",\n \"standard_name\": \"time_bnds\",\n }\n\n self._add_static_array('time', t_array, time_attrs)\n self._add_static_array('time_bnds', t_bnds_array, time_bnds_attrs)\n\n coordinate_names = [coord for coord in coords_data.keys()\n if coord not in COMMON_COORD_VAR_NAMES]\n coordinate_names = ' '.join(coordinate_names)\n\n global_attrs = dict(\n Conventions='CF-1.7',\n coordinates=coordinate_names,\n title=data_id,\n date_created=pd.Timestamp.now().isoformat(),\n processing_level=self._dataset_name.split('.')[3],\n time_coverage_start=time_coverage_start.isoformat(),\n time_coverage_end=time_coverage_end.isoformat(),\n time_coverage_duration=\n (time_coverage_end - time_coverage_start).isoformat(),\n )\n\n self._time_indexes = {}\n remove = []\n self._num_data_var_chunks_not_in_vfs = 0\n logging.debug('Adding variables to dataset ...')\n for variable_name in self._variable_names:\n if variable_name in coords_data or variable_name == 'time_bnds':\n remove.append(variable_name)\n continue\n var_encoding = self.get_encoding(variable_name)\n var_attrs = self.get_attrs(variable_name)\n dimensions = var_attrs.get('dimensions', [])\n self._maybe_adjust_attrs(lon_size, lat_size, var_attrs)\n chunk_sizes = var_attrs.get('chunk_sizes', [-1] * len(dimensions))\n if isinstance(chunk_sizes, int):\n chunk_sizes = [chunk_sizes]\n if len(dimensions) > 0 and 'time' not in dimensions:\n dimensions.insert(0, 'time')\n chunk_sizes.insert(0, 1)\n var_attrs.update(_ARRAY_DIMENSIONS=dimensions)\n sizes = []\n self._time_indexes[variable_name] = -1\n time_dimension = -1\n for i, coord_name in enumerate(dimensions):\n if coord_name in coords_data:\n sizes.append(coords_data[coord_name]['size'])\n else:\n sizes.append(self._dimensions.get(coord_name))\n if coord_name == 'time':\n self._time_indexes[variable_name] = i\n time_dimension = i\n if chunk_sizes[i] == -1:\n chunk_sizes[i] = sizes[i]\n var_attrs['shape'] = sizes\n var_attrs['size'] = math.prod(sizes)\n if var_encoding.get('dtype', '') == 'bytes1024':\n if 'grid_mapping_name' in var_attrs:\n var_encoding['dtype'] = 'U'\n elif len(dimensions) == 1 and sizes[0] < 512 * 512:\n _LOG.info(f\"Variable '{variable_name}' is encoded as \"\n f\"string. Will convert it to metadata.\")\n variable = {variable_name: sizes[0]}\n var_data = self.get_variable_data(data_id, variable)\n global_attrs[variable_name] = \\\n [var.decode('utf-8')\n for var in var_data[variable_name]['data']]\n remove.append(variable_name)\n continue\n else:\n warnings.warn(f\"Variable '{variable_name}' is encoded as \"\n f\"string. Will omit it from the dataset.\")\n remove.append(variable_name)\n continue\n chunk_sizes = self._adjust_chunk_sizes(chunk_sizes,\n sizes,\n time_dimension)\n var_attrs['chunk_sizes'] = chunk_sizes\n if len(var_attrs.get('file_dimensions', [])) < len(dimensions):\n var_attrs['file_chunk_sizes'] = chunk_sizes[1:]\n else:\n var_attrs['file_chunk_sizes'] = chunk_sizes\n self._add_remote_array(variable_name,\n sizes,\n chunk_sizes,\n var_encoding,\n var_attrs)\n self._num_data_var_chunks_not_in_vfs += np.prod(chunk_sizes)\n logging.debug(f\"Added a total of {len(self._variable_names)} variables \"\n f\"to the data set\")\n for r in remove:\n self._variable_names.remove(r)\n cube_params['variable_names'] = self._variable_names\n global_attrs['history'] = [dict(\n program=f'{self._class_name}',\n cube_params=cube_params\n )]\n # setup Virtual File System (vfs)\n self._vfs['.zgroup'] = _dict_to_bytes(dict(zarr_format=2))\n self._vfs['.zattrs'] = _dict_to_bytes(global_attrs)\n\n def _adjust_coord_data(self, coord_name: str, min_offset:int,\n max_offset: int, coords_data, dim_attrs: dict):\n self._dimension_chunk_offsets[coord_name] = min_offset\n coord_data = coords_data[coord_name]['data'][min_offset:max_offset]\n shape = coord_data.shape\n self._set_chunk_sizes(dim_attrs, shape, 'chunk_sizes')\n self._set_chunk_sizes(dim_attrs, shape, 'file_chunk_sizes')\n dim_attrs['size'] = coord_data.size\n if 'shape' in dim_attrs:\n dim_attrs['shape'] = list(shape)\n if len(shape) == 1:\n self._dimensions[coord_name] = coord_data.size\n coords_data[coord_name]['size'] = coord_data.size\n coords_data[coord_name]['chunkSize'] = dim_attrs['chunk_sizes']\n coords_data[coord_name]['data'] = coord_data\n return coords_data\n\n def _set_chunk_sizes(self, dim_attrs, shape, name):\n chunk_sizes = dim_attrs.get(name, 1000000)\n if isinstance(chunk_sizes, int):\n dim_attrs[name] = min(chunk_sizes, shape[0])\n else:\n # chunk sizes is list of ints\n for i, chunk_size in enumerate(chunk_sizes):\n chunk_sizes[i] = min(chunk_size, shape[i])\n dim_attrs[name] = chunk_sizes\n\n @classmethod\n def _maybe_adjust_attrs(cls, lon_size, lat_size, var_attrs):\n cls._maybe_adjust_to('lat', 'latitude', lat_size, var_attrs)\n cls._maybe_adjust_to('lon', 'longitude', lon_size, var_attrs)\n\n @classmethod\n def _maybe_adjust_to(cls, first_name, second_name, adjusted_size, var_attrs):\n if adjusted_size == -1:\n return\n try:\n index = var_attrs['dimensions'].index(first_name)\n except ValueError:\n try:\n index = var_attrs['dimensions'].index(second_name)\n except ValueError:\n index = -1\n if index > 0:\n var_attrs['shape'][index] = adjusted_size\n if 'chunk_sizes' in var_attrs:\n var_attrs['chunk_sizes'][index] = \\\n min(var_attrs['chunk_sizes'][index], adjusted_size)\n var_attrs['file_chunk_sizes'][index] = \\\n min(var_attrs['file_chunk_sizes'][index], adjusted_size)\n\n @classmethod\n def _adjust_chunk_sizes(cls, chunks, sizes, time_dimension):\n # check if we can actually read in everything as one big chunk\n sum_sizes = np.prod(sizes, dtype=np.int64)\n if time_dimension >= 0:\n sum_sizes = sum_sizes / sizes[time_dimension] * chunks[time_dimension]\n if sum_sizes < 1000000:\n best_chunks = sizes.copy()\n best_chunks[time_dimension] = chunks[time_dimension]\n return best_chunks\n if sum_sizes < 1000000:\n return sizes\n # determine valid values for a chunk size. A value is valid if the size can be divided by it without remainder\n valid_chunk_sizes = []\n for i, chunk, size in zip(range(len(chunks)), chunks, sizes):\n # do not rechunk time dimension\n if i == time_dimension:\n valid_chunk_sizes.append([chunk])\n continue\n # handle case that the size cannot be divided evenly by the chunk\n if size % chunk > 0:\n if np.prod(chunks, dtype=np.int64) / chunk * size < 1000000:\n # if the size is small enough to be ingested in single chunk, take it\n valid_chunk_sizes.append([size])\n else:\n # otherwise, give in to that we cannot chunk the data evenly\n valid_chunk_sizes.append(list(range(chunk, size + 1, chunk)))\n continue\n valid_dim_chunk_sizes = []\n for r in range(chunk, size + 1, chunk):\n if size % r == 0:\n valid_dim_chunk_sizes.append(r)\n valid_chunk_sizes.append(valid_dim_chunk_sizes)\n # recursively determine the chunking with the biggest size smaller than 1000000\n chunks, chunk_size = cls._get_best_chunks(chunks, valid_chunk_sizes, chunks.copy(), 0, 0, time_dimension)\n return chunks\n\n @classmethod\n def _get_best_chunks(cls, chunks, valid_sizes, best_chunks, best_chunk_size, index, time_dimension):\n for valid_size in valid_sizes[index]:\n test_chunks = chunks.copy()\n test_chunks[index] = valid_size\n if index < len(chunks) - 1:\n test_chunks, test_chunk_size = \\\n cls._get_best_chunks(test_chunks, valid_sizes, best_chunks, best_chunk_size, index + 1,\n time_dimension)\n else:\n test_chunk_size = np.prod(test_chunks, dtype=np.int64)\n if test_chunk_size > 1000000:\n break\n if test_chunk_size > best_chunk_size:\n best_chunk_size = test_chunk_size\n best_chunks = test_chunks.copy()\n elif test_chunk_size == best_chunk_size:\n # in case two chunkings have the same size, choose the one where values are more similar\n where = np.full(len(test_chunks), fill_value=True)\n where[time_dimension] = False\n test_min_chunk = np.max(test_chunks, initial=0, where=where)\n best_min_chunk = np.max(best_chunks, initial=0, where=where)\n if best_min_chunk > test_min_chunk:\n best_chunk_size = test_chunk_size\n best_chunks = test_chunks.copy()\n return best_chunks, best_chunk_size\n\n @classmethod\n def _adjust_size(cls, size: int, tile_size: int) -> int:\n if size > tile_size:\n num_tiles = cls._safe_int_div(size, tile_size)\n size = num_tiles * tile_size\n return size\n\n @classmethod\n def _safe_int_div(cls, x: int, y: int) -> int:\n return (x + y - 1) // y\n\n @classmethod\n def _extract_time_as_string(cls, time: Union[pd.Timestamp, str]) -> str:\n if isinstance(time, str):\n time = pd.to_datetime(time, utc=True)\n return time.tz_localize(None).isoformat()\n\n @classmethod\n def _extract_time_range_as_strings(cls, time_range: Union[Tuple, List]) -> (str, str):\n if isinstance(time_range, tuple):\n time_start, time_end = time_range\n else:\n time_start = time_range[0]\n time_end = time_range[1]\n return cls._extract_time_as_string(time_start), cls._extract_time_as_string(time_end)\n\n @abstractmethod\n def get_time_ranges(self, cube_id: str, cube_params: Mapping[str, Any]) -> List[Tuple]:\n pass\n\n @abstractmethod\n def get_default_time_range(self, ds_id: str) -> Tuple[str, str]:\n return '', ''\n\n @abstractmethod\n def get_all_variable_names(self) -> List[str]:\n pass\n\n # def get_spatial_lat_res(self):\n # return self._cube_config.spatial_res\n\n # def get_spatial_lon_res(self):\n # return self._cube_config.spatial_res\n\n @abstractmethod\n def get_dimensions(self) -> Mapping[str, int]:\n pass\n\n @abstractmethod\n def get_coords_data(self, dataset_id: str) -> dict:\n pass\n\n @abstractmethod\n def get_variable_data(self, dataset_id: str, variable_names: Dict[str, int]):\n pass\n\n def add_observer(self, observer: Callable):\n \"\"\"\n Add a request observer.\n\n :param observer: A callback function called when remote requests are mode: observer(**kwargs).\n \"\"\"\n self._observers.append(observer)\n\n @abstractmethod\n def get_encoding(self, band_name: str) -> Dict[str, Any]:\n \"\"\"\n Get the encoding settings for band (variable) *band_name*.\n Must at least contain \"dtype\" whose value is a numpy array-protocol type string.\n Refer to https://docs.scipy.org/doc/numpy/reference/arrays.interface.html#arrays-interface\n and zarr format 2 spec.\n \"\"\"\n\n @abstractmethod\n def get_attrs(self, band_name: str) -> Dict[str, Any]:\n \"\"\"\n Get any metadata attributes for band (variable) *band_name*.\n \"\"\"\n\n def request_bbox(self, x_tile_index: int, y_tile_index: int) -> Tuple[float, float, float, float]:\n x_index = x_tile_index * self._tile_width\n y_index = y_tile_index * self._tile_height\n\n x01, _, _, y02 = self.cube_config.geometry\n spatial_lat_res = self.get_spatial_lat_res()\n spatial_lon_res = self.get_spatial_lon_res()\n\n x1 = x01 + spatial_lon_res * x_index\n x2 = x01 + spatial_lon_res * (x_index + self._tile_width)\n y1 = y02 - spatial_lat_res * (y_index + self._tile_height)\n y2 = y02 - spatial_lat_res * y_index\n\n return x1, y1, x2, y2\n\n def request_time_range(self, time_index: int) -> Tuple[pd.Timestamp, pd.Timestamp]:\n start_time, end_time = self._time_ranges[time_index]\n return start_time, end_time\n\n def _add_static_array(self, name: str, array: np.ndarray, attrs: Dict):\n shape = list(map(int, array.shape))\n dtype = str(array.dtype.str)\n order = \"C\"\n array_metadata = {\n \"zarr_format\": 2,\n \"chunks\": shape,\n \"shape\": shape,\n \"dtype\": dtype,\n \"fill_value\": None,\n \"compressor\": _STATIC_ARRAY_COMPRESSOR_CONFIG,\n \"filters\": None,\n \"order\": order,\n }\n chunk_key = '.'.join(['0'] * array.ndim)\n self._vfs[name] = _str_to_bytes('')\n self._vfs[name + '/.zarray'] = _dict_to_bytes(array_metadata)\n self._vfs[name + '/.zattrs'] = _dict_to_bytes(attrs)\n self._vfs[name + '/' + chunk_key] = \\\n _STATIC_ARRAY_COMPRESSOR.encode(array.tobytes(order=order))\n\n\n def _add_remote_array(self,\n name: str,\n shape: List[int],\n chunks: List[int],\n encoding: Dict[str, Any],\n attrs: Dict):\n array_metadata = dict(zarr_format=2,\n shape=shape,\n chunks=chunks,\n compressor=None,\n fill_value=None,\n filters=None,\n order='C')\n array_metadata.update(encoding)\n self._vfs[name] = _str_to_bytes('')\n self._vfs[name + '/.zarray'] = _dict_to_bytes(array_metadata)\n self._vfs[name + '/.zattrs'] = _dict_to_bytes(attrs)\n nums = np.array(shape) // np.array(chunks)\n ranges = tuple(map(range, map(int, nums)))\n self._var_name_to_ranges[name] = ranges\n if ranges not in self._ranges_to_indexes:\n self._ranges_to_indexes[ranges] = list(itertools.product(*ranges))\n if ranges not in self._ranges_to_var_names:\n self._ranges_to_var_names[ranges] = []\n self._ranges_to_var_names[ranges].append(name)\n\n def _fetch_chunk(self, key: str, var_name: str, chunk_index: Tuple[int, ...]) -> bytes:\n request_time_range = self.request_time_range(chunk_index[self._time_indexes[var_name]])\n\n t0 = time.perf_counter()\n try:\n exception = None\n chunk_data = self.fetch_chunk(key, var_name, chunk_index, request_time_range)\n except Exception as e:\n exception = e\n chunk_data = None\n duration = time.perf_counter() - t0\n\n for observer in self._observers:\n observer(var_name=var_name,\n chunk_index=chunk_index,\n # bbox=request_bbox,\n time_range=request_time_range,\n duration=duration,\n exception=exception)\n\n if exception:\n raise exception\n\n return chunk_data\n\n @abstractmethod\n def fetch_chunk(self,\n key: str,\n var_name: str,\n chunk_index: Tuple[int, ...],\n time_range: Tuple[pd.Timestamp, pd.Timestamp]\n ) -> bytes:\n \"\"\"\n Fetch chunk data from remote.\n\n :param key: The original chunk key being retrieved.\n :param var_name: Variable name\n :param chunk_index: chunk index\n :param time_range: Requested time range\n :return: chunk data as raw bytes\n \"\"\"\n pass\n\n @property\n def _class_name(self):\n return self.__module__ + '.' + self.__class__.__name__\n\n ###############################################################################\n # Zarr Store (MutableMapping) implementation\n ###############################################################################\n\n def keys(self) -> KeysView[str]:\n if self._trace_store_calls:\n print(f'{self._class_name}.keys()')\n self._build_missing_vfs_entries()\n return self._vfs.keys()\n\n def listdir(self, key: str) -> Iterable[str]:\n if self._trace_store_calls:\n print(f'{self._class_name}.listdir(key={key!r})')\n if key == '':\n return list((k for k in self._vfs.keys() if '/' not in k))\n else:\n prefix = key + '/'\n start = len(prefix)\n return list((k for k in self._vfs.keys() if k.startswith(prefix) and k.find('/', start) == -1))\n\n def getsize(self, key: str) -> int:\n if self._trace_store_calls:\n print(f'{self._class_name}.getsize(key={key!r})')\n return len(self._vfs[key]) + self._num_data_var_chunks_not_in_vfs\n\n def __iter__(self) -> Iterator[str]:\n if self._trace_store_calls:\n print(f'{self._class_name}.__iter__()')\n self._build_missing_vfs_entries()\n return iter(self._vfs.keys())\n\n def __len__(self) -> int:\n if self._trace_store_calls:\n print(f'{self._class_name}.__len__()')\n return len(self._vfs.keys()) + self._num_data_var_chunks_not_in_vfs\n\n def __contains__(self, key) -> bool:\n if self._trace_store_calls:\n print(f'{self._class_name}.__contains__(key={key!r})')\n if key in self._vfs:\n return True\n self._try_building_vfs_entry(key)\n return key in self._vfs\n\n def __getitem__(self, key: str) -> bytes:\n if self._trace_store_calls:\n print(f'{self._class_name}.__getitem__(key={key!r})')\n try:\n value = self._vfs[key]\n except KeyError:\n self._try_building_vfs_entry(key)\n value = self._vfs[key]\n if isinstance(value, tuple):\n return self._fetch_chunk(key, *value)\n return value\n\n def _try_building_vfs_entry(self, key):\n if '/' in key:\n name, chunk_index_part = key.split('/')\n try:\n chunk_indexes = \\\n tuple(int(chunk_index) for chunk_index in chunk_index_part.split('.'))\n except ValueError:\n # latter part of key does not consist of chunk indexes\n return\n # build vfs entry of this chunk index for all variables that have this range\n ranges = self._var_name_to_ranges[name]\n indexes = self._ranges_to_indexes[ranges]\n if chunk_indexes in indexes:\n for var_name in self._ranges_to_var_names[ranges]:\n self._vfs[var_name + '/' + chunk_index_part] = var_name, chunk_indexes\n self._num_data_var_chunks_not_in_vfs -= 1\n indexes.remove(chunk_indexes)\n\n def _build_missing_vfs_entries(self):\n for name, ranges in self._var_name_to_ranges.items():\n indexes = self._ranges_to_indexes[ranges]\n for index in indexes:\n filename = '.'.join(map(str, index))\n self._vfs[name + '/' + filename] = name, index\n\n def __setitem__(self, key: str, value: bytes) -> None:\n if self._trace_store_calls:\n print(f'{self._class_name}.__setitem__(key={key!r}, value={value!r})')\n raise TypeError(f'{self._class_name} is read-only')\n\n def __delitem__(self, key: str) -> None:\n if self._trace_store_calls:\n print(f'{self._class_name}.__delitem__(key={key!r})')\n raise TypeError(f'{self._class_name} is read-only')\n\n\nclass CciChunkStore(RemoteChunkStore):\n \"\"\"\n A remote Zarr Store using the ESA CCI Open Data Portal as backend.\n\n :param cci_odp: CCI ODP instance.\n :param cube_config: Cube configuration.\n :param observer: An optional callback function called when remote requests are mode: observer(**kwargs).\n :param trace_store_calls: Whether store calls shall be printed (for debugging).\n \"\"\"\n\n _SAMPLE_TYPE_TO_DTYPE = {\n # Note: Sentinel Hub currently only supports unsigned\n # integer values therefore requesting INT8 or INT16\n # will return the same as UINT8 or UINT16 respectively.\n 'uint8': '|u1',\n 'uint16': '<u2',\n 'uint32': '<u4',\n 'int8': '|u1',\n 'int16': '<u2',\n 'int32': '<u4',\n 'float32': '<f4',\n 'float64': '<f8',\n }\n\n def __init__(self,\n cci_odp: CciOdp,\n dataset_id: str,\n cube_params: Mapping[str, Any] = None,\n observer: Callable = None,\n trace_store_calls=False):\n self._cci_odp = cci_odp\n if dataset_id not in self._cci_odp.dataset_names:\n raise ValueError(f'Data ID {dataset_id} not provided by ODP.')\n self._metadata = self._cci_odp.get_dataset_metadata(dataset_id)\n super().__init__(dataset_id,\n cube_params,\n observer=observer,\n trace_store_calls=trace_store_calls)\n\n def _extract_time_range_as_datetime(self, time_range: Union[Tuple, List]) -> (datetime, datetime, str, str):\n iso_start_time, iso_end_time = self._extract_time_range_as_strings(time_range)\n start_time = datetime.strptime(iso_start_time, _TIMESTAMP_FORMAT)\n end_time = datetime.strptime(iso_end_time, _TIMESTAMP_FORMAT)\n return start_time, end_time, iso_start_time, iso_end_time\n\n def get_time_ranges(self, dataset_id: str, cube_params: Mapping[str, Any]) -> List[Tuple]:\n start_time, end_time, iso_start_time, iso_end_time = \\\n self._extract_time_range_as_datetime(\n cube_params.get('time_range', self.get_default_time_range(dataset_id)))\n time_period = dataset_id.split('.')[2]\n if time_period == 'day':\n start_time = datetime(year=start_time.year, month=start_time.month, day=start_time.day)\n end_time = datetime(year=end_time.year, month=end_time.month, day=end_time.day,\n hour=23, minute=59, second=59)\n delta = relativedelta(days=1)\n elif time_period == 'month' or time_period == 'mon':\n start_time = datetime(year=start_time.year, month=start_time.month, day=1)\n end_time = datetime(year=end_time.year, month=end_time.month, day=1)\n delta = relativedelta(months=+1)\n end_time += delta\n elif time_period == 'year' or time_period == 'yr':\n start_time = datetime(year=start_time.year, month=1, day=1)\n end_time = datetime(year=end_time.year, month=12, day=31)\n delta = relativedelta(years=1)\n else:\n end_time = end_time.replace(hour=23, minute=59, second=59)\n end_time_str = datetime.strftime(end_time, _TIMESTAMP_FORMAT)\n iso_end_time = self._extract_time_as_string(end_time_str)\n request_time_ranges = self._cci_odp.get_time_ranges_from_data(dataset_id, iso_start_time, iso_end_time)\n return request_time_ranges\n request_time_ranges = []\n this = start_time\n while this < end_time:\n next = this + delta\n pd_this = pd.Timestamp(datetime.strftime(this, _TIMESTAMP_FORMAT))\n pd_next = pd.Timestamp(datetime.strftime(next, _TIMESTAMP_FORMAT))\n request_time_ranges.append((pd_this, pd_next))\n this = next\n return request_time_ranges\n\n def get_default_time_range(self, ds_id: str):\n temporal_start = self._metadata.get('temporal_coverage_start', None)\n temporal_end = self._metadata.get('temporal_coverage_end', None)\n if not temporal_start or not temporal_end:\n time_ranges = self._cci_odp.get_time_ranges_from_data(ds_id, '1000-01-01', '3000-12-31')\n if not temporal_start:\n if len(time_ranges) == 0:\n raise ValueError(\n \"Could not determine temporal start of dataset. Please use 'time_range' parameter.\")\n temporal_start = time_ranges[0][0]\n if not temporal_end:\n if len(time_ranges) == 0:\n raise ValueError(\n \"Could not determine temporal end of dataset. Please use 'time_range' parameter.\")\n temporal_end = time_ranges[-1][1]\n return (temporal_start, temporal_end)\n\n def get_all_variable_names(self) -> List[str]:\n return [variable['name'] for variable in self._metadata['variables']]\n\n def get_dimensions(self) -> Mapping[str, int]:\n return copy.copy(self._metadata['dimensions'])\n\n def get_coords_data(self, dataset_id: str):\n var_names, coord_names = self._cci_odp.var_and_coord_names(dataset_id)\n coords_dict = {}\n for coord_name in coord_names:\n coords_dict[coord_name] = self.get_attrs(coord_name).get('size')\n dimension_data = self.get_variable_data(dataset_id, coords_dict)\n if len(dimension_data) == 0:\n # no valid data found in indicated time range, let's set this broader\n dimension_data = self._cci_odp.get_variable_data(dataset_id, coords_dict)\n return dimension_data\n\n def get_variable_data(self, dataset_id: str, variable_dict: Dict[str, int]):\n return self._cci_odp.get_variable_data(dataset_id,\n variable_dict,\n self._time_ranges[0][0].strftime(_TIMESTAMP_FORMAT),\n self._time_ranges[0][1].strftime(_TIMESTAMP_FORMAT))\n\n def get_encoding(self, var_name: str) -> Dict[str, Any]:\n encoding_dict = {}\n encoding_dict['fill_value'] = self.get_attrs(var_name).get('fill_value')\n encoding_dict['dtype'] = self.get_attrs(var_name).get('data_type')\n return encoding_dict\n\n def get_attrs(self, var_name: str) -> Dict[str, Any]:\n if var_name not in self._attrs:\n self._attrs[var_name] = copy.deepcopy(\n self._metadata.get('variable_infos', {}).get(var_name, {}))\n return self._attrs[var_name]\n\n def fetch_chunk(self,\n key: str,\n var_name: str,\n chunk_index: Tuple[int, ...],\n time_range: Tuple[pd.Timestamp, pd.Timestamp]) -> bytes:\n\n start_time, end_time = time_range\n identifier = self._cci_odp.get_dataset_id(self._dataset_name)\n iso_start_date = start_time.tz_localize(None).isoformat()\n iso_end_date = end_time.tz_localize(None).isoformat()\n dim_indexes = self._get_dimension_indexes_for_chunk(var_name, chunk_index)\n request = dict(parentIdentifier=identifier,\n varNames=[var_name],\n startDate=iso_start_date,\n endDate=iso_end_date,\n drsId=self._dataset_name,\n fileFormat='.nc'\n )\n data = self._cci_odp.get_data_chunk(request, dim_indexes)\n if not data:\n raise KeyError(f'{key}: cannot fetch chunk for variable {var_name!r} '\n f'and time_range {time_range!r}.')\n _LOG.info(f'Fetched chunk for ({chunk_index})\"{var_name}\"')\n return data\n\n def _get_dimension_indexes_for_chunk(self, var_name: str, chunk_index: Tuple[int, ...]) -> tuple:\n dim_indexes = []\n var_dimensions = self.get_attrs(var_name).get('file_dimensions', [])\n chunk_sizes = self.get_attrs(var_name).get('file_chunk_sizes', [])\n offset = 0\n # dealing with the case that time has been added as additional first dimension\n if len(chunk_index) > len(chunk_sizes):\n offset = 1\n for i, var_dimension in enumerate(var_dimensions):\n if var_dimension == 'time':\n dim_indexes.append(slice(None, None, None))\n continue\n dim_size = self._dimensions.get(var_dimension, -1)\n if dim_size < 0:\n raise ValueError(f'Could not determine size of dimension {var_dimension}')\n data_offset = self._dimension_chunk_offsets.get(var_dimension, 0)\n start = data_offset + chunk_index[i + offset] * chunk_sizes[i]\n end = min(start + chunk_sizes[i], data_offset + dim_size)\n dim_indexes.append(slice(start, end))\n return tuple(dim_indexes)\n" ]
[ [ "pandas.to_datetime", "numpy.max", "numpy.array", "pandas.Timestamp.now", "numpy.prod" ] ]
viathor/OpenFermion-Cirq
[ "b4b7f8d82c40f0a6282873b5d2867e9d8778cea6" ]
[ "openfermioncirq/primitives/optimal_givens_decomposition.py" ]
[ "# 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# https://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\"\"\"\nA routine for constructing a circuit to exactly implement a unitary generated by\none-body rotations through the optimal Givens rotation network. Construction\nof this circuit can be found in Optica Vol. 3, Issue 12, pp. 1460-1465 (2016).\nThis Givens network improves upon the parallel Givens network for implementing\nbasis rotations in Phys. Rev. Lett. 120, 110501 (2018).\n\"\"\"\nfrom typing import cast, Iterable, Sequence, Tuple\n\nimport numpy\nimport cirq\n\nfrom openfermion.ops._givens_rotations import (givens_matrix_elements,\n givens_rotate)\nfrom openfermioncirq import Ryxxy\n\n\nclass GivensTranspositionError(Exception):\n pass\n\n\nclass GivensMatrixError(Exception):\n pass\n\n\ndef optimal_givens_decomposition(qubits: Sequence[cirq.Qid],\n unitary: numpy.ndarray\n ) -> Iterable[cirq.Operation]:\n \"\"\"\n Implement a circuit that provides the unitary that is generated by\n single-particle fermion generators\n\n .. math::\n\n U(v) = exp(log(v)_{p,q}(a_{p}^{\\dagger}a_{q} - a_{q}^{\\dagger}a_{p})\n\n This can be used for implementing an exact single-body basis rotation\n\n Args:\n qubits: Sequence of qubits to apply the operations over. The qubits\n should be ordered in linear physical order.\n unitary:\n \"\"\"\n N = unitary.shape[0]\n right_rotations = []\n left_rotations = []\n for i in range(1, N):\n if i % 2 == 1:\n for j in range(0, i):\n # eliminate U[N - j, i - j] by mixing U[N - j, i - j],\n # U[N - j, i - j - 1] by right multiplication\n # of a givens rotation matrix in column [i - j, i - j + 1]\n gmat = givens_matrix_elements(unitary[N - j - 1, i - j - 1],\n unitary[N - j - 1, i - j - 1 + 1],\n which='left')\n right_rotations.append((gmat.T, (i - j - 1, i - j)))\n givens_rotate(unitary, gmat.conj(), i - j - 1, i - j,\n which='col')\n else:\n for j in range(1, i + 1):\n # elimination of U[N + j - i, j] by mixing U[N + j - i, j] and\n # U[N + j - i - 1, j] by left multiplication\n # of a givens rotation that rotates row space\n # [N + j - i - 1, N + j - i\n gmat = givens_matrix_elements(unitary[N + j - i - 1 - 1, j - 1],\n unitary[N + j - i - 1, j - 1],\n which='right')\n left_rotations.append((gmat, (N + j - i - 2, N + j - i - 1)))\n givens_rotate(unitary, gmat, N + j - i - 2, N + j - i - 1,\n which='row')\n\n new_left_rotations = []\n for (left_gmat, (i, j)) in reversed(left_rotations):\n phase_matrix = numpy.diag([unitary[i, i], unitary[j, j]])\n matrix_to_decompose = left_gmat.conj().T.dot(phase_matrix)\n new_givens_matrix = givens_matrix_elements(matrix_to_decompose[1, 0],\n matrix_to_decompose[1, 1],\n which='left')\n new_phase_matrix = matrix_to_decompose.dot(new_givens_matrix.T)\n\n # check if T_{m,n}^{-1}D = D T.\n # coverage: ignore\n if not numpy.allclose(new_phase_matrix.dot(new_givens_matrix.conj()),\n matrix_to_decompose):\n raise GivensTranspositionError(\n \"Failed to shift the phase matrix \"\n \"from right to left\")\n # coverage: ignore\n\n unitary[i, i], unitary[j, j] = new_phase_matrix[0, 0], new_phase_matrix[\n 1, 1]\n new_left_rotations.append((new_givens_matrix.conj(), (i, j)))\n\n phases = numpy.diag(unitary)\n rotations = []\n ordered_rotations = []\n for (gmat, (i, j)) in list(reversed(new_left_rotations)) + list(\n map(lambda x: (x[0].conj().T, x[1]), reversed(right_rotations))):\n ordered_rotations.append((gmat, (i, j)))\n\n # if this throws the impossible has happened\n # coverage: ignore\n if not numpy.isclose(gmat[0, 0].imag, 0.0):\n raise GivensMatrixError(\n \"Givens matrix does not obey our convention that all elements \"\n \"in the first column are real\")\n if not numpy.isclose(gmat[1, 0].imag, 0.0):\n raise GivensMatrixError(\n \"Givens matrix does not obey our convention that all elements \"\n \"in the first column are real\")\n # coverage: ignore\n\n theta = numpy.arcsin(numpy.real(gmat[1, 0]))\n phi = numpy.angle(gmat[1, 1])\n rotations.append((i, j, theta, phi))\n\n for op in reversed(rotations):\n i, j, theta, phi = cast(Tuple[int, int, float, float], op)\n if not numpy.isclose(phi, 0.0):\n yield cirq.Z(qubits[j]) ** (phi / numpy.pi)\n\n yield Ryxxy(-theta).on(qubits[i], qubits[j])\n\n for idx, phase in enumerate(phases):\n yield cirq.Z(qubits[idx]) ** (numpy.angle(phase) / numpy.pi)\n" ]
[ [ "numpy.angle", "numpy.isclose", "numpy.diag", "numpy.real" ] ]
lindlind/ITMO_FS
[ "8662b67a98bceaac800ccc8ea3230cc9f9a250e1" ]
[ "ITMO_FS/ensembles/model_based/best_sum.py" ]
[ "import numpy as np\n\n\nclass BestSum: ## TODO refactor , not stable\n\n def __init__(self, models, cutting_rule):\n self.models = models\n self.cutting_rule = cutting_rule\n self.features = None\n\n def fit(self, x, y, feature_names=None):\n try:\n feature_names = x.columns\n except AttributeError:\n if feature_names is None:\n feature_names = list(range(x.shape[1]))\n self.features = dict(zip(feature_names, np.zeros(len(feature_names))))\n for model in self.models:\n model.fit(x, y)\n for i, k in enumerate(model.selected_features):\n self.features[k] += (model.best_score - self.features[k]) / (i + 1)\n\n def cut(self, cutting_rule=None):\n if cutting_rule is None:\n return self.cutting_rule(self.features)\n return cutting_rule(self.features)\n\n def predict(self, X):\n new = self.cut(self.features)\n n = len(self.models)\n result = np.zeros((X.shape[0], n))\n for i, model in enumerate(self.models):\n result[:, i] = model.predict(X[:, new])\n return np.array([1 if i else 0 for i in result.sum(axis=1) / n > 0.5])\n" ]
[ [ "numpy.zeros" ] ]
TAMUSFC/H5HutAccessor
[ "0d5495b07dcb912a2e8cdc740e93628fd16508aa" ]
[ "H5HutAccessor/__init__.py" ]
[ "\"\"\"\nUtilities for dealing with H5Hut files generated by OPAL\n\"\"\"\nimport os\nimport pathlib\nfrom datetime import datetime\nfrom functools import lru_cache\n\nimport h5py\nimport numpy as np\nfrom scipy.signal import argrelmin\nfrom matplotlib import pyplot as plt\nfrom matplotlib.gridspec import GridSpec\nfrom matplotlib.colorbar import Colorbar\n\nfrom .analysis_helpers import in_sector\n\n\nclass H5HutAccessor():\n r\"\"\"\n Loads an H5Hut file and stores the data in more useful numpy arrays.\n\n Parameters\n ----------\n fn : str\n path to the H5Hut file to process\n stride : int, optional\n stepsize (default: 1) between adjacent steps to load. Useful if the \n user wants to examine a very fine file without using ALL the \n temporal resolution.\n minstep : int, optional\n phase dump (not integrator!) step (default: 0) to begin processing \n from\n maxstep : int, optional \n maximum phase dump (not integrator!) step (default: -1) to process\n steps : sequence of ints, optional\n sequence of step indices to load. If this argument is given, `minstep,\n maxstep, stride` are all ignored!\n maxparts : int, optional\n max number of particles to consider on each step. This is the same\n as only taking the first `maxparts` columns in an un-filtered \n instance, and is meant for quickly loading files with lots of\n particles.\n\n Attributes\n ----------\n t : float\n global time (sec)\n reftheta : float\n reference angle for each step (deg)\n refs : float\n reference axial distance for each step (m)\n refx, refy, refz : float\n reference position for each step (m)\n refpx, refpy, refpz : float\n reference momentum for each step (beta*gamma)\n refT : float\n reference energy for each step (MeV)\n Bref : float ndarray with shape (Nstep, 3)\n Reference magnetic field (T)\n Eref : float ndarray with shape (Nstep, 3)\n Reference electric field (MV/m)\n x, y, z : float ndarray with shape (Nstep, Nparticles)\n spatial coordinates (global frame) of all particles (m)\n px, py, pz : float ndarray with shape (Nstep, Nparticles)\n momentum coordinates (global frame) of all particles (units of beta*gamma)\n unitinfo : dict\n all unit information stored on the head of the H5Hut file\n\n Notes\n -----\n The HDF5 file will be closed after initialization.\n\n The units given above are typical for my use case, but check the `unitinfo`\n property to be sure.\n\n OPAL uses the symbol # to indicate special characters, which seem to correspond \n to the equivalent LaTeX commands, i.e.:\n #varepsilon -> $\\varepsilon$\n #beta -> $\\beta$\n etc...\n \"\"\"\n\n def __init__(self, fn, stride=1, minstep=0, maxstep=None, steps=None, maxparts=None):\n self._fn = str(pathlib.Path(fn).resolve())\n self._h5 = h5file = h5py.File(self._fn, 'r')\n self.modified_time = datetime.fromtimestamp(int(os.stat(fn).st_mtime))\n filesteps = [k for k in h5file.keys() if k.startswith('Step#')]\n filesteps.sort(key=lambda n: int(n.split('#')[-1]))\n\n if steps: # user has provided a list of step indices\n filesteps = [filesteps[idx] for idx in steps]\n elif minstep or maxstep or stride: # user has provided striding information\n filesteps = filesteps[minstep:maxstep:stride]\n\n self.steps = filesteps\n\n Nstep = len(self.steps)\n\n assert h5file[self.steps[0]].attrs['NumBunch'] == 1, \"Only single-bunch files are supported\"\n\n # N.B. this is NOT correct if we inject additional beam after the first saved step!\n pid0 = h5file[self.steps[0]]['id']\n Npart = pid0.size\n if maxparts:\n Npart = min(Npart, maxparts)\n pid0 = pid0[:Npart]\n \n # iterating steps is relatively expensive, so let's establish arrays to store data\n # the default datatype is np.float64 (8 bytes per value), so 8 * (Nstep*(3+6+6*Npart)) bytes total\n # (~ 80 MB for 1000 particles and 1667 steps; attrs data should be kbytes worth at O(Nstep))\n for refarray in ('refs', 'refr', 'reftheta', 'refz', \n 'refpr', 'refpt', 'refpz', 't',\n 'refT'):\n setattr(self, refarray, np.full((Nstep,), np.nan))\n for refarray in ('Bref', 'Eref', 'emit_norm', 'emit_geom'):\n setattr(self, refarray, np.full((Nstep, 3), np.nan))\n\n # initialize all values to NaN \n self._particledata = np.full((Nstep, Npart, 6), np.nan)\n\n # store a bunch of unit information\n self.unitinfo = {k: v for k,v in h5file.attrs.items() if 'unit' in k.lower()}\n for stepnum, step in enumerate(self.steps):\n try:\n s = h5file[step]\n self.refs[stepnum] = s.attrs['SPOS'][()]\n self.t[stepnum] = s.attrs['TIME'][()]\n self.refr[stepnum] = s.attrs['REFR'][()] * 1e-3 # mm -> m\n self.reftheta[stepnum] = s.attrs['REFTHETA'][()]\n self.refz[stepnum] = s.attrs['REFZ'][()] * 1e-3 # mm -> m\n self.refpr[stepnum] = s.attrs['REFPR'][()]\n self.refpt[stepnum] = s.attrs['REFPT'][()]\n self.refpz[stepnum] = s.attrs['REFPZ'][()]\n self.refT[stepnum] = s.attrs['ENERGY'][()]\n # normalized emittance - m rad\n # the statistic eps_norm_m from classic/5.0/src/Algorithms/PartBunch.cpp\n self.emit_norm[stepnum, :] = s.attrs['#varepsilon'][()]\n # geometric emittance - m rad\n # the statistic eps_m from classic/5.0/src/Algorithms/PartBunch.cpp\n self.emit_geom[stepnum, :] = s.attrs['#varepsilon-geom'][()]\n\n # HUH, these are backwards?!\n self.Bref[stepnum, :] = s.attrs['E-ref'][()]\n self.Eref[stepnum, :] = s.attrs['B-ref'][()]\n\n # identify particles that are part of original selection AND in this step\n _, pidsave, pidstep = np.intersect1d(pid0, s['id'][()], assume_unique=True, return_indices=True) \n \n for idx, val in enumerate(('x', 'y', 'z', 'px', 'py', 'pz')):\n self._particledata[stepnum, pidsave, idx] = s[val][()][pidstep]\n\n except (KeyError, IOError):\n print(\"Can't read step %d, truncating arrays\" % (stepnum+1))\n for arr in (self.refs, self.reftheta, self.refz, self.t, \n self.Bref, self.Eref):\n arr.resize(stepnum, refcheck=False)\n# [a[:stepnum] for a in (self.refs, self.reftheta, self.refz, self.t, self.Bref, self.Eref)]\n self._particledata = self._particledata[:stepnum, :, :]\n Nstep = stepnum\n self.steps = self.steps[:Nstep]\n break\n \n (self.x, self.y, self.z, self.px, self.py, self.pz) = [col.reshape(self._particledata.shape[:-1]) for col in np.split(self._particledata, 6, axis=-1)]\n\n # TODO: particle with pid=0 is not particularly special and can be lost, so probably\n # remove these entirely\n self.x0 = self.x[:, [0]]\n self.y0 = self.y[:, [0]]\n self.z0 = self.z[:, [0]]\n self.px0 = self.px[:, [0]]\n self.py0 = self.py[:, [0]]\n self.pz0 = self.pz[:, [0]]\n self.p0 = np.linalg.norm((self.px0, self.py0, self.pz0), axis=0)\n\n self.xbar = np.nanmean(self.x, axis=-1)\n self.ybar = np.nanmean(self.y, axis=-1)\n self.zbar = np.nanmean(self.z, axis=-1)\n self.pxbar = np.nanmean(self.px, axis=-1)\n self.pybar = np.nanmean(self.py, axis=-1)\n self.pzbar = np.nanmean(self.pz, axis=-1)\n\n # the trace-space coordinate x'=dx/ds=(dx/dt)/(ds/dt) should be ~ px/p\n # self.xp = self.px / self.p0\n # self.yp = self.py / self.p0\n # self.zp = self.pz / self.p0\n\n # (x0, y0) might be nan, so use bar instead...\n# self.turnidx = turn_transitions(self.x0.reshape((Nstep,)), self.y0.reshape((Nstep,)))\n self.turnidx = turn_transitions(self.xbar, self.ybar)\n\n # ndarray shape (Nstep,) - number of particles alive at a given timestep \"\"\"\n self.N = (np.isfinite(self._particledata).all(axis=-1) # last axis is 6D phase-space, all must be finite\n .sum(axis=-1)) # last axis is PID axis, sum to get number alive\n\n # There isn't a good reason to keep the file open at the moment\n h5file.close()\n\n def __enter__(self):\n return self\n\n def __exit__(self, *args):\n self.__del__(args)\n\n def __del__(self, *args):\n try:\n self._h5.close()\n except ValueError:\n pass\n\n def __len__(self):\n return len(self.steps)\n\n @property\n def refx(self):\n return self.refr * np.cos(self.reftheta * np.pi/180.)\n\n @property\n def refy(self):\n return self.refr * np.sin(self.reftheta * np.pi/180.)\n\n @property\n def refp(self):\n \"\"\"\n Reference momentum, in units of beta*gamma (dimensionless) and in\n global Cartesian coordinates\n \"\"\"\n # OPAL's output of reference quantities can't be trusted\n# theta = self.reftheta * np.pi/180.\n# transp = (self.refpr[:, np.newaxis] * rhat(theta) + \n# self.refpt[:, np.newaxis] * phihat(theta))\n# return np.concatenate((transp, self.refpz[:, np.newaxis]), axis=1)\n return np.stack((self.pxbar, self.pybar, self.pzbar), axis=-1)\n\n @property\n def bg(self):\n return np.linalg.norm(self.refp, axis=1)\n\n @property\n def beta(self):\n \"\"\" Lorentz beta (v/c) at each step \"\"\"\n # naturally, OPAL's output is sometimes zero for refp, and shouldn't be trusted...\n# bg = self.refp # beta*gamma\n# bg = np.linalg.norm(bg, axis=1)\n# beta = np.sqrt((bg**2) / (1 + bg**2))\n# assert np.all((beta >= 0) &\n# (beta < 1))\n bg = self.bg\n beta = np.sqrt((bg**2) / (1 + bg**2))\n return beta\n\n @property\n def gama(self):\n \"\"\" Lorentz at each step \"\"\"\n return np.sqrt(1 / (1 - self.beta))\n\n @property\n def tns(self):\n \"\"\" Step times in ns \"\"\"\n return self.t*1e9\n\n @property\n def refpx(self):\n# return self.refp[:, 0]\n return self.pbarx\n\n @property\n def refpy(self):\n return self.refp[:, 1]\n \n @property\n def dx(self):\n \"\"\" x-offset from reference position (m) \"\"\"\n return self.x - self.refx[:, np.newaxis]\n\n @property\n def dy(self):\n \"\"\" y-offset from reference position (m) \"\"\"\n return self.y - self.refy[:, np.newaxis]\n\n @property\n def dz(self):\n \"\"\" z-offset from reference position (m) \"\"\"\n return self.z - self.refz[:, np.newaxis]\n\n @property\n def dr(self):\n return np.stack((self.dx, self.dy, self.dz), axis=-1)\n\n @property\n def dpx(self):\n \"\"\" offset from reference x-momentum (m) \"\"\"\n return self.px - self.refpx[:, np.newaxis]\n\n @property\n def dpy(self):\n \"\"\" offset from reference y-momentum (m) \"\"\"\n return self.py - self.refpy[:, np.newaxis]\n\n @property\n def dpz(self):\n \"\"\" offset from reference z-momentum (m) \"\"\"\n return self.pz - self.refpz[:, np.newaxis]\n\n @property\n def r(self):\n \"\"\" The radius of each particle in the global cylindrical coordinate system (m) \"\"\"\n return np.sqrt(self.x**2 + self.y**2)\n\n @property\n def th(self):\n \"\"\" The angle of each particle (rad) \"\"\"\n return np.arctan2(self.y, self.x)\n \n def phase(self, refs=None):\n \"\"\"\n Calculate the betatron phases (rad) at all steps\n \n Parameters\n ----------\n h : H5HutAccessor\n Simulation output file to use\n refs : ndarray (optional)\n reference axial coordinate to use. Must have shape `(Nstep,)`.\n If not given, the bunch average will be calculated for each step, and \n the cumulative sum of the distances between these points will be used.\n\n Returns\n -------\n phase_x, phase_y\n \"\"\"\n \n if refs is None:\n r = np.stack((self.xbar, self.ybar), axis=-1)\n dr = np.diff(r, axis=0)\n ds = np.linalg.norm(dr, axis=-1)\n assert (ds > 0).all() # s should be monotonically-increasing\n else:\n ds = np.ediff1d(refs)\n\n dx, xp, dy, yp, ds, dps = self.frenet_6D()\n beta_x, alfa_x, gama_x, emit_x = twiss(dx, xp)\n beta_y, alfa_y, gama_y, emit_y = twiss(dy, yp)\n\n phase_x = np.cumsum(ds/beta_x[1:])\n phase_y = np.cumsum(ds/beta_y[1:])\n return phase_x, phase_y\n \n def arc_mask(self, secnum, turnnum):\n \"\"\"\n Return the step numbers of this trajectory that correspond to the given arc\n \"\"\"\n assert 1 <= turnnum <= 16\n if turnnum == 1:\n turnstart = 0\n turnend = self.turnidx[0]\n if turnend < 10:\n raise RuntimeError('Something is almost certainly wrong, less than 10 steps in the first turn...')\n else:\n turnstart = self.turnidx[turnnum-2]\n turnend = self.turnidx[turnnum-1]\n turnx = self.x0[turnstart:turnend]\n turny = self.y0[turnstart:turnend]\n \n return turnstart + np.argwhere(in_sector(turnx, turny, secnum))[:, 0]\n \n @lru_cache(1)\n def frenet_6D(self):\n \"\"\"\n Calculate the values in the Frenet-Serret frame of (dx, x', dy, y', ds, dps)\n\n NOTE: +y in this notation means the vertical coordinate (what OPAL/H5HutAccessor call +z), and\n +s means the longitundinal coordinate.\n\n Returns\n -------\n (dx, x', dy, y', ds, dps) - ndarrays of shape (Nstep, Npart) with the 6D coordinates of the particle\n in the Frenet-Serret frame:\n dx - horizontal distance from bunch mean (m) (+x means radially out)\n x' - horizontal transverse angle (rad)\n dy - vertical distance from bunch mean (m) (+y means vertically up)\n y' - vertical transverse angle (rad)\n ds - longitudinal distance from bunch mean (m) (+s means in the direction of rms momentum)\n dps - longitudinal momentum offset from bunch mean (dimensionless, multiples of beta*gama)\n \"\"\"\n # step-by-step transformation into the Frenet frame\n # p0 lies in the +s direction (beam direction)\n # crossing this with the vertical direction gives radially OUT (+x)\n\n # per-step average momentum, ignoring lost particles\n# pxbar = np.nanmean(self.px, axis=1)[:, np.newaxis]\n# pybar = np.nanmean(self.py, axis=1)[:, np.newaxis]\n# pzbar = np.nanmean(self.pz, axis=1)[:, np.newaxis]\n# pbar = np.concatenate((pxbar, pybar, pzbar), axis=-1)\n # stack: (Nstep, Npart) -> (Nstep, Npart, 3)\n # nanmean: (Nstep, Npart, 3) -> (Nstep, 3) (averaging over particles)\n pbar = np.stack((self.pxbar, self.pybar, self.pzbar), axis=-1) # (Nstep, 3)\n pxbar, pybar, pzbar = np.split(pbar, 3, axis=-1) # each array (Nstep, 1)\n normp = np.linalg.norm(pbar, axis=-1)[:, np.newaxis] # (Nstep, 1)\n phat = (pbar/normp) # +s direction, (Nstep, 3)\n\n assert np.isclose(np.linalg.norm(phat, axis=1), 1.0).all(), \"Something is wrong, not all values of phat have norm ~ 1.0\"\n\n # NOTE that this notation is different from the global coordinate system\n # it is conventional to call the vertical direction +y, the\n # radial/transverse +x, and the axial +z/+s\n yhat = np.array([0, 0, 1])\n xhat = np.cross(phat, yhat)\n\n # per-step average position, ignoring lost particles\n\n # shape (Nstep, Npart), NaN for lost particles\n dx = self.x - self.xbar[:, np.newaxis]\n dy = self.y - self.ybar[:, np.newaxis]\n dz = self.z - self.zbar[:, np.newaxis]\n dpx = self.px - self.pxbar[:, np.newaxis]\n dpy = self.py - self.pybar[:, np.newaxis]\n dpz = self.pz - self.pzbar[:, np.newaxis]\n\n # shape (Nstep, 1, 3) for the broadcast below\n xhat = xhat[:, np.newaxis, :]\n phat = phat[:, np.newaxis, :]\n\n # stack into vectors, then project into the Frenet basis (spanned by [phat, xhat, yhat])\n dr = np.stack((dx, dy, dz), axis=-1) # shape (Nstep, Npart, 3)\n # results in shape (Nstep, Npart)\n dx = (dr * xhat).sum(axis=-1)\n dy = (dr * yhat).sum(axis=-1)\n ds = (dr * phat).sum(axis=-1)\n\n dp = np.stack((dpx, dpy, dpz), axis=-1) # shape (Nstep, Npart, 3)\n # shape (Nstep, Npart)\n dpx = (dp * xhat).sum(axis=-1)\n dpy = (dp * yhat).sum(axis=-1)\n dps = (dp * phat).sum(axis=-1)\n\n # convert to angles i' ~ p_i/|p|\n xp = dpx / normp\n yp = dpy / normp\n\n return (dx, xp, dy, yp, ds, dps)\n\n\n def poincareplot(self, steps, extralabel=lambda step: '', lims=None, colorbar=True):\n \"\"\"\n Make a set of Poincare plots for a given step of sequence thereof.\n\n Parameters\n ----------\n steps : sequence of int or a single integer\n The step(s) to plot\n extralabel : callable, optional \n A callable with signature `extralabel(step)` that returns an extra\n string label to add to the title for a given step number\n lims : dict, optional \n A dictionary of limits for the Poincaré plots, with keys `'xy.h',\n 'xy.v', 's.h', 's.v'`, and values corresponding to the magnitude of\n the (symmetric) axis limits on the respective plots. The transverse\n plots share limits to ensure that they are always comparable, and\n because we expect roughly axisymmetric beams.\n colorbar : bool, optional\n Boolean indicating whether or not to draw colorbars\n\n Returns\n -------\n poincarefig : Figure\n \"\"\"\n try:\n iter(steps)\n except TypeError:\n steps = [steps]\n\n dx, xp, dy, yp, ds, dps = self.frenet_6D()\n hvar_x = 1e3*dx[steps, :]\n vvar_x = 1e3*xp[steps, :]\n hvar_y = 1e3*dy[steps, :]\n vvar_y = 1e3*yp[steps, :]\n hvar_s = 1e3*ds[steps, :]\n vvar_s = dps[steps, :]\n# sxy_h = max(np.nanstd(hvar_x, axis=1).max(), np.nanstd(hvar_y, axis=1).max())\n# sxy_v = max(np.nanstd(vvar_x, axis=1).max(), np.nanstd(vvar_y, axis=1).max())\n# ss_h = np.nanstd(hvar_s, axis=1).max()\n# ss_v = np.nanstd(vvar_s, axis=1).max()\n sxy_h = max(np.nanstd(hvar_x, axis=1).mean(), np.nanstd(hvar_y, axis=1).mean())\n sxy_v = max(np.nanstd(vvar_x, axis=1).mean(), np.nanstd(vvar_y, axis=1).mean())\n ss_h = np.nanstd(hvar_s, axis=1).mean()\n ss_v = np.nanstd(vvar_s, axis=1).mean()\n _lims = {\n 'xy.h': 3*sxy_h,\n 'xy.v': 3*sxy_v,\n 's.h': 3*ss_h,\n 's.v': 3*ss_v,\n }\n if lims: \n _lims.update(lims)\n\n N = len(steps)\n if colorbar:\n Ncols = 9\n else:\n Ncols = 3\n\n w_hb = 5\n h_hb = 6\n w_cb = 1\n cb_pad = 1\n w_fig = 3*w_hb + int(Ncols>3)*(w_cb + cb_pad)\n h_fig = N*h_hb\n if colorbar:\n widths = [8, 1, 3, 8, 1, 3, 8, 1, 3]\n else:\n widths = [1, 1, 1]\n poincarefig = plt.figure(figsize=(w_fig, h_fig), facecolor='white')\n gs = GridSpec(nrows=N, ncols=Ncols, hspace=0.2, width_ratios=widths, figure=poincarefig)\n for row, step in enumerate(steps):\n hsl = slice(row*h_hb, (row+1)*h_hb)\n if colorbar:\n ax_x = plt.subplot(gs[row, 0])\n cax_x = plt.subplot(gs[row, 1])\n ax_y = plt.subplot(gs[row, 3])\n cax_y = plt.subplot(gs[row, 4])\n ax_s = plt.subplot(gs[row, 6])\n cax_s = plt.subplot(gs[row, 7])\n else:\n _w = w_fig//3\n ax_x = plt.subplot(gs[row, 0])\n ax_y = plt.subplot(gs[row, 1])\n ax_s = plt.subplot(gs[row, 2])\n ax_x.set_xlabel(r\"$\\Delta x$ (mm)\")\n ax_x.set_ylabel(r\"$x'$ (mrad)\")\n hlim, vlim = _lims['xy.h'], _lims['xy.v']\n hb_x = ax_x.hexbin(hvar_x[row], vvar_x[row], extent=[-hlim, hlim, -vlim, vlim])\n if colorbar:\n Colorbar(mappable=hb_x, ax=cax_x)\n\n ax_y.set_xlabel(r\"$\\Delta y$ (mm)\")\n ax_y.set_ylabel(r\"$y'$ (mrad)\")\n hb_y = ax_y.hexbin(hvar_y[row], vvar_y[row], extent=[-hlim, hlim, -vlim, vlim])\n ax_y.set_title(f't={self.tns[step]:.2f} ns {extralabel(step)}')\n if colorbar:\n Colorbar(mappable=hb_y, ax=cax_y)\n\n ax_s.set_xlabel(r\"$\\Delta s$ (mm)\")\n ax_s.set_ylabel(r\"$\\Delta p_s (\\beta\\gamma)$\")\n hlim, vlim = _lims['s.h'], _lims['s.v']\n hb_s = ax_s.hexbin(hvar_s[row], vvar_s[row], extent=[-hlim, hlim, -vlim, vlim])\n if colorbar:\n Colorbar(mappable=hb_s, ax=cax_s, )\n\n if not colorbar:\n gs.tight_layout(poincarefig)\n \n return poincarefig\n\n \n def plot_trace(self, step, which, kind='marker', ax=None, *args, **kwargs):\n \"\"\"\n Given a step number, plot one of the transverse trace spaces\n\n Params\n ------\n step - step number to plot\n which - \"xx'\", \"yy'\", or \"ss'\" to indicate which trace space to plot\n kind - 'marker' or 'hex'\n controls whether the plot uses unfilled circular markers (default) or hexbin()\n ax (optional) - matplotlib Axes object to use to plot. Defaults to gca()\n\n Notes\n -----\n *args, **kwargs are passed to each plotting function (plot() and hexbin())\n \"\"\"\n if ax is None:\n fig = plt.figure(figsize=(16, 12), facecolor='white')\n ax = plt.gca()\n else:\n fig = ax.figure\n\n dx, xp, dy, yp, ds, dps = self.frenet_6D()\n\n if which == \"xx'\":\n hvar = dx[step, :]\n vvar = xp[step, :]\n xlabel = \"x (m)\"\n ylabel = \"x' (rad)\"\n beta, alfa, gama, emit = [val[step] for val in self.twiss_x()]\n title = f' $\\\\beta_x={beta:.2f}$ m'\n elif which == \"yy'\":\n hvar = dy[step, :]\n vvar = yp[step, :]\n xlabel = \"y (m)\"\n ylabel = \"y' (rad)\"\n beta, alfa, gama, emit = [val[step] for val in self.twiss_y()]\n title = f' $\\\\beta_y={beta:.2f}$ m'\n elif which == \"sdps\":\n hvar = ds[step, :]\n vvar = dps[step, :]\n xlabel = \"s (m)\"\n ylabel = r\"$\\Delta p_s (\\beta*\\gamma)$\"\n else:\n raise ValueError(f\"Plot type '{which}' not supported\")\n\n if kind == 'marker':\n ax.plot(hvar, vvar, 'ko', mfc='none')\n elif kind == 'hex':\n gridsize = kwargs['gridsize'] if 'gridsize' in kwargs else NBINS\n mappable = ax.hexbin(hvar, vvar, gridsize=gridsize)\n plt.colorbar(mappable, ax=ax)\n else:\n raise ValueError(\"'kind' must be either 'marker' or 'hex' \")\n\n ax.set_title(title) \n ax.set_xlabel(xlabel)\n ax.set_ylabel(ylabel)\n\n # plot RMS \"window\"\n if which in (\"xx'\", \"yy'\"):\n XLIM = plt.xlim()\n YLIM = plt.ylim()\n winH = np.sqrt(beta * emit)\n winV = np.sqrt(gama * emit)\n ax.vlines([-winH, winH], -1, 1, 'r', '--')\n ax.hlines([-winV, winV], -1, 1, 'r', '--')\n a, b = l_axes(alfa, beta, gama, emit)\n ang = angle(alfa, beta, gama, emit)\n t = np.linspace(0, 2*np.pi, 100)\n xe = a*np.cos(t)\n ye = b*np.sin(t)\n xe, ye = (xe*np.cos(ang) + ye*np.sin(ang), xe*np.sin(ang) - ye*np.cos(ang))\n ax.plot(xe, ye, 'r-')\n ax.set_xlim(XLIM)\n ax.set_ylim(YLIM)\n\n return fig\n\n def twiss_x(self):\n \"\"\" \n Compute the horizontal Twiss parameters (beta_x, alfa_x, gama_x, emit_x)\n \"\"\"\n dx, xp, dy, yp, ds, dps = self.frenet_6D()\n return twiss(dx, xp)\n\n def twiss_y(self):\n \"\"\"\n Compute the vertical Twiss parameters (beta_y, alfa_y, gama_y, emit_y)\n \"\"\"\n dx, xp, dy, yp, ds, dps = self.frenet_6D() \n return twiss(dy, yp)\n \n\n\ndef rhat(theta):\n r\"\"\" \n Returns the unit vector $\\hat{r} = cos(\\theta) \\hat{x} + sin(\\theta) \\hat{y}$\n \n theta - angle in radians\n \"\"\"\n return np.stack((np.cos(theta), np.sin(theta)), axis=1).squeeze()\n\ndef phihat(theta):\n r\"\"\" \n Returns the unit vector $\\hat{phi} = -sin(\\theta) \\hat{x} + cos(\\theta) \\hat{y}$\n \n theta - angle in radians\n \"\"\"\n return np.stack((-np.sin(theta), np.cos(theta)), axis=1).squeeze()\n\ndef l_axes(alfa, beta, gama, emit):\n u\"\"\"\n Given parameters (α, β, γ, ε) for a trace-space ellipse, calculate the length of each axis\n \n Notes\n -----\n Taken unceremoniously from http://mathworld.wolfram.com/Ellipse.html\n \"\"\"\n g = -emit\n a = gama\n b = alfa\n c = beta\n \n numerator = 2*(g*b**2 - a*c*g)\n \n denom = (b**2 - a*c) * (np.sqrt((a-c)**2 + 4*b**2) - (a+c))\n \n La = np.sqrt(numerator/denom)\n \n denom = (b**2 - a*c) * (-np.sqrt((a-c)**2 + 4*b**2) - (a+c))\n \n Lb = np.sqrt(numerator/denom)\n \n return La, Lb\n\ndef angle(alfa, beta, gama, emit):\n u\"\"\"\n Given parameters (α, β, γ, ε) for a trace-space ellipse, calculate the angle of rotation of the ellipse (from major along +x) \n \n Notes\n -----\n Taken unceremoniously from http://mathworld.wolfram.com/Ellipse.html\n \"\"\"\n a = gama\n b = alfa\n c = beta\n if np.isclose(alfa, 0):\n if a < c:\n return 0\n else:\n return np.pi\n \n assert((a-c)/(2*b) != 0)\n \n # note: numpy does not have arccot(), but if z != 0, arccot(z) = arctan(1/z)\n ang = 1./2 * np.arctan((2*b)/(a-c))\n if a <= c:\n return ang \n else:\n return np.pi/2 + ang\n \ndef rmsemit(x, xp):\n \"\"\" Given a trace space (x, xp), calculate the RMS emittance \"\"\"\n x = np.asarray(x)\n xp = np.asarray(xp)\n xx = (x**2).mean()\n xxp = (x*xp).mean()\n xpxp = (xp**2).mean()\n return np.sqrt(xx*xpxp - xxp**2)\n\ndef twiss(x, xp):\n \"\"\"\n Given a trace space (x, xp) (in the Frenet frame), calculate the \n RMS values of beta_x, alfa_x, gama_x, emit_x, according to:\n\n $$$\n emit = \\sqrt(<x^2> * <x'^2> - <x x'>^2)\n beta = <x^2> / emit\n alfa = -<x x'> / emit\n gama = <x' x'> / emit\n $$$\n\n Notes\n -----\n NaN values in either `x` or `xp` are ignored.\n The units of the returned Twiss parameters will depend on the input, but\n if `x` is given in meters and `xp` is given in radians, then beta will be\n in meters and emit will be in m*rad.\n\n Returns\n -------\n (beta, alfa, gama, emit)\n \"\"\"\n # \"centering\" the distribution so that <x> = <x'> = 0 exactly by construction\n x = x - np.nanmean(x, axis=1, keepdims=True)\n xp = xp - np.nanmean(xp, axis=1, keepdims=True)\n \n # expectation values of <x^2> <x'^2>, <xx'>\n xx = np.nanmean(x**2, axis=1)\n xpxp = np.nanmean(xp**2, axis=1)\n xxp = np.nanmean(x*xp, axis=1)\n\n emit = np.sqrt(xx*xpxp - xxp**2)\n beta = xx / emit\n alfa = -xxp / emit\n gama = xpxp / emit\n \n return (beta, alfa, gama, emit)\n\n\ndef turn_transitions(x, y, angle=0.0):\n r\"\"\"\n return array of indices of the arrays x, y indicating where the given particle (column) crossed\n the line defined by theta=angle (rad) (default = 0) in the last step.\n\n Parameters\n ----------\n x, y - 1d array_like (nturns,)\n of x and y coordinates\n angle - float\n defining angle (rad) for the transition line\n \n Returns\n -------\n indices - tuple (nparticles)\n indices of the crossing step for each particle\n\n Notes\n -----\n any `angle` can be provided, but the calculation will be done modulo 2*pi\n \"\"\"\n assert np.ndim(x) == 1 and np.ndim(y) == 1, \"input must be 1d\"\n theta = np.arctan2(y, x)\n return argrelmin((theta + angle) % (2*np.pi))[0]\n" ]
[ [ "numpy.isclose", "matplotlib.pyplot.xlim", "numpy.nanmean", "scipy.signal.argrelmin", "numpy.cumsum", "numpy.cos", "numpy.full", "numpy.sin", "numpy.linalg.norm", "matplotlib.pyplot.colorbar", "numpy.sqrt", "numpy.ndim", "numpy.isfinite", "matplotlib.pyplot.gca", "numpy.cross", "numpy.nanstd", "matplotlib.pyplot.subplot", "numpy.array", "matplotlib.colorbar.Colorbar", "matplotlib.pyplot.figure", "numpy.diff", "numpy.stack", "numpy.arctan", "numpy.arctan2", "numpy.intersect1d", "matplotlib.gridspec.GridSpec", "numpy.asarray", "matplotlib.pyplot.ylim", "numpy.split", "numpy.ediff1d", "numpy.linspace" ] ]
tangunner/python-trading-robot
[ "358fbfb3ca95cb423b2fb4223481d2ac2c77b9f4" ]
[ "pyrobot/portfolio.py" ]
[ "import numpy as np\nfrom datetime import datetime, timedelta\n\nimport pandas as pd\n\nfrom pandas import DataFrame\nfrom typing import Tuple\nfrom typing import List\nfrom typing import Optional\n\n\nfrom pyrobot.stock_frame import StockFrame\nfrom td.client import TDClient\n\n\nclass Portfolio():\n\n def __init__(self, account_number: Optional[str] = None) -> None:\n \"\"\"Initalizes a new instance of the Portfolio object.\n\n Keyword Arguments:\n ----\n account_number {str} -- An accout number to associate with the Portfolio. (default: {None})\n \"\"\"\n\n self.cash = 0.00\n self.positions = {}\n self.position_lots = {}\n self.positions_count = 0\n\n self.total_return = 0.00\n self.profit_loss = 0.00\n self.market_value = 0.00\n self.total_value = self.cash + self.market_value\n self.invested_capital = 0.00\n self.risk_tolerance = 0.00\n self.account_number = account_number\n\n self._historical_prices = []\n self.performance_tracker = {}\n\n self._td_client: TDClient = None\n self._stock_frame: StockFrame = None\n self._stock_frame_daily: StockFrame = None\n\n def add_positions(self, positions: List[dict]) -> dict:\n \"\"\"Add Multiple positions to the portfolio at once.\n\n This method will take an iterable containing the values\n normally passed through in the `add_position` endpoint and\n then adds each position to the portfolio.\n\n Arguments:\n ----\n positions {list[dict]} -- Multiple positions with the required arguments\n to be added.\n position_lots -- \n\n Returns:\n ----\n {dict} -- The current positions in the portfolio.\n\n Usage:\n ----\n >>> # Define mutliple positions to add.\n >>> multi_position = [\n {\n 'asset_type': 'equity',\n 'quantity': 2,\n 'purchase_price': 4.00,\n 'symbol': 'TSLA',\n 'purchase_date': '2020-01-31'\n },\n {\n 'asset_type': 'equity',\n 'quantity': 2,0\n 'purchase_price': 4.00,\n 'symbol': 'SQ',\n 'purchase_date': '2020-01-31'\n }\n ]\n >>> new_positions = trading_robot.portfolio.add_positions(positions=multi_position)\n {\n 'SQ': {\n 'asset_type': 'equity',\n 'purchase_date': '2020-01-31',\n 'purchase_price': 4.00,\n 'quantity': 2,\n 'symbol': 'SQ'\n },\n 'TSLA': {\n 'asset_type': 'equity',\n 'purchase_date': '2020-01-31',\n 'purchase_price': 4.00,\n 'quantity': 2,\n 'symbol': 'TSLA'\n }\n }\n \"\"\"\n\n if isinstance(positions, list):\n\n # Loop through each position.\n for position in positions:\n\n # Add the position.\n self.add_position(\n symbol=position['symbol'],\n asset_type=position['asset_type'],\n quantity=position.get('quantity', 0),\n purchase_price=position.get('purchase_price', 0.0),\n purchase_date=position.get('purchase_date', None)\n )\n\n return self.positions\n\n else:\n raise TypeError('Positions must be a list of dictionaries.')\n\n def add_position(self, symbol: str, asset_type: str, purchase_date: Optional[str] = None, \n quantity: int = 0, purchase_price: float = 0.0, indicator_used: str = None) -> dict:\n \"\"\"Adds a single new position to the the portfolio.\n\n Arguments:\n ----\n symbol {str} -- The Symbol of the Financial Instrument. Example: 'AAPL' or '/ES'\n\n asset_type {str} -- The type of the financial instrument to be added. For example,\n 'equity', 'forex', 'option', 'futures'\n\n Keyword Arguments:\n ----\n quantity {int} -- The number of shares or contracts you own. (default: {0})\n\n purchase_price {float} -- The price at which the position was purchased. (default: {0.00})\n\n purchase_date {str} -- The date which the asset was purchased. Must be ISO Format \"YYYY-MM-DD\"\n For example, \"2020-04-01\" (default: {None})\n\n Returns:\n ----\n {dict} -- A dictionary object that represents a position in the portfolio.\n\n Usage:\n ----\n >>> portfolio = Portfolio()\n >>> new_position = Portfolio.add_position(symbol='MSFT', \n asset_type='equity', \n quantity=2, \n purchase_price=4.00,\n purchase_date=\"2020-01-31\"\n )\n >>> new_position\n {\n 'asset_type': 'equity', \n 'quantity': 2, \n 'purchase_price': 4.00,\n 'symbol': 'MSFT',\n 'purchase_date': '2020-01-31'\n }\n \"\"\"\n\n # if security already owned, update the existing position\n if self.in_portfolio(symbol) and self.positions[symbol]['ownership_status']:\n\n # add the new lot to the existing position_lots entry\n position_lot = {}\n position_lot['quantity'] = quantity\n position_lot['purchase_price'] = purchase_price\n position_lot['purchase_date'] = purchase_date\n position_lot['cost_basis'] = quantity * purchase_price\n position_lot['asset_type'] = asset_type\n position_lot['indicator_used'] = indicator_used\n self.position_lots[symbol].append(position_lot)\n\n # update the position values (purchase price is the WA price)\n self.positions[symbol]['quantity'] += quantity\n self.positions[symbol]['cost_basis'] += quantity * purchase_price\n self.positions[symbol]['purchase_price'] = (\n self.positions[symbol]['cost_basis'] / self.positions[symbol]['quantity']\n )\n\n else:\n # if security not owned yet, add it to the positions\n self.positions[symbol] = {}\n self.positions[symbol]['symbol'] = symbol\n self.positions[symbol]['quantity'] = quantity\n self.positions[symbol]['purchase_price'] = purchase_price\n self.positions[symbol]['purchase_date'] = purchase_date\n self.positions[symbol]['cost_basis'] = quantity * purchase_price\n self.positions[symbol]['asset_type'] = asset_type\n\n # ownership_status allows adding a unowned security to the port\n if purchase_date:\n self.positions[symbol]['ownership_status'] = True\n else:\n self.positions[symbol]['ownership_status'] = False\n\n # also add the security to the position lots\n self.position_lots[symbol] = []\n position_lot = {}\n position_lot['quantity'] = quantity\n position_lot['purchase_price'] = purchase_price\n position_lot['purchase_date'] = purchase_date\n position_lot['cost_basis'] = quantity * purchase_price\n position_lot['asset_type'] = asset_type\n position_lot['indicator_used'] = indicator_used\n self.position_lots[symbol].append(position_lot)\n\n return self.positions[symbol]\n\n def reduce_position(self, symbol: str, quantity: int = 0, tax_lot_method: str = 'fifo', \n indicator_used: str = None) -> dict:\n \"\"\"Updates a single position for a partial or entire sale.\"\"\"\n\n if not self.in_portfolio(symbol) or not self.positions[symbol]['ownership_status']:\n raise KeyError(f'The symbol {symbol} is not in the portfolio.')\n\n \n if quantity == self.positions[symbol]['quantity']:\n self.remove_position(symbol)\n\n elif quantity > self.positions[symbol]['quantity']:\n raise ValueError(f'The quantity {quantity} exceeds the num of shares held.')\n \n else:\n _quantity = quantity\n \n # create copy so the original list can be edited\n _lots = self.position_lots[symbol].copy()\n\n \"\"\"(1) First, update the lots values\"\"\"\n \n # fifo order sells the lots in the same order they were purchased\n if tax_lot_method == 'fifo':\n for lot in _lots:\n # replace ALL of the lots' indicators; we still want to eval\n # all indicators for signals even though we're holding some\n # residual SPY shares\n lot_idx = self.position_lots[symbol].index(lot)\n self.position_lots[symbol][lot_idx]['indicator_used'] = indicator_used\n \n if quantity > 0:\n adj_quant = min(quantity, lot['quantity'])\n \n # the entire lot is sold\n if lot['quantity'] == adj_quant:\n self.position_lots[symbol].remove(lot)\n \n # only part of the lot is sold\n else:\n self.position_lots[symbol][0]['quantity'] -= adj_quant\n self.position_lots[symbol][0]['cost_basis'] = (\n self.position_lots[symbol][0]['quantity'] * self.position_lots[symbol][0]['purchase_price']\n )\n \n quantity -= adj_quant\n\n # sells the lot(s) according to the lot number(s) passed\n elif tax_lot_method == 'specific_lot':\n \n \"\"\"[specified lot sales WIP - right now sold based on holding\n period / tax logic, but eventually will be updated to specify\n the specific lots to sell by identifier]\"\"\"\n\n # grab any LT lots and sort them by purchase price\n all_LT_lots = [lot['purchase_price'] for lot in _lots if lot['days_held'] > 365]\n if all_LT_lots:\n all_LT_lots.sort(reverse=True)\n \n # sell all of the highest cost LT lots first\n for lot in all_LT_lots:\n lot_idx = self.position_lots[symbol].index(lot)\n self.position_lots[symbol][lot_idx]['indicator_used'] = indicator_used\n \n if quantity > 0:\n adj_quant = min(quantity, lot['quantity'])\n\n if lot['quantity'] == adj_quant:\n self.position_lots[symbol].remove(lot)\n quantity -= adj_quant\n \n else:\n self.position_lots[symbol][0]['quantity'] -= adj_quant\n quantity -= adj_quant\n \n # refresh _lots def to reflect changes in self.position_lots\n _lots = self.position_lots[symbol].copy()\n _lots_prices = [lot['purchase_price'] for lot in _lots].sort(reverse=True)\n \n for price in _lots_prices:\n lot_idx = self.position_lots[symbol].index(lot)\n self.position_lots[symbol][lot_idx]['indicator_used'] = indicator_used\n \n if quantity > 0:\n for lot in _lots:\n if lot['purchase_price'] == price:\n adj_quant = min(quantity, lot['quantity'])\n\n if lot['quantity'] == adj_quant:\n self.position_lots[symbol].remove(lot)\n quantity -= adj_quant\n\n else:\n self.position_lots[symbol][0]['quantity'] -= adj_quant\n quantity -= adj_quant\n break\n else:\n break\n else:\n raise Exception(\"ATM reduce_position only implemented for 'fifo' and 'specific_lot' tax lots.\")\n\n\n \"\"\"(2) Then, total the lots values to get the updated position vals\"\"\"\n\n position_quantity = 0\n position_cost_basis = 0\n \n for lot in self.position_lots[symbol]:\n position_quantity += lot['quantity']\n position_cost_basis += lot['cost_basis']\n \n assert (self.positions[symbol]['quantity'] - _quantity) == position_quantity\n \n self.positions[symbol]['quantity'] = position_quantity\n self.positions[symbol]['cost_basis'] = position_cost_basis\n self.positions[symbol]['purchase_price'] = (\n position_cost_basis / position_quantity\n )\n\n def check_portfolio_indicators(self, indicator: str=None, symbol: str=None):\n \"\"\"Returns the set of all indicators currently in use in all\n position_lots in the portfolio. If indicator given, returns True if it\n has been used to purchase shares in the active portfolio.\n\n If symbol given and no indicator, returns a set of all indicators\n for the position_lots of that security. Returns True if the indicator is\n given and found in security's position_lots.\n \"\"\"\n \n if not self.positions and not self.position_lots:\n return None\n \n if not symbol:\n all_indicators = []\n for ticker, lots in self.position_lots.items():\n ticker_indicators = [all_indicators.append(lot['indicator_used']) for lot in lots]\n indicators = set(all_indicators)\n else:\n indicators = None\n if symbol in self.position_lots.keys():\n indicators = set([lot['indicator_used'] for lot in self.position_lots[symbol]])\n\n return indicator in indicators if indicator else indicators\n \n def remove_position(self, symbol: str) -> Tuple[bool, str]:\n \"\"\"Deletes a single position from the portfolio.\n\n Arguments:\n ----\n symbol {str} -- The symbol of the instrument to be deleted. Example: 'AAPL' or '/ES'\n\n Returns:\n ----\n {Tuple[bool, str]} -- Returns `True` if successfully deleted, `False` otherwise \n along with a message.\n\n Usage:\n ----\n >>> portfolio = Portfolio()\n\n >>> new_position = Portfolio.add_position(\n symbol='MSFT', \n asset_type='equity', \n quantity=2, \n purchase_price=4.00,\n purchase_date=\"2020-01-31\"\n )\n >>> delete_status = Portfolio.delete_position(symbol='MSFT')\n >>> delete_status\n (True, 'MSFT was successfully removed.')\n\n >>> delete_status = Portfolio.delete_position(symbol='AAPL')\n >>> delete_status\n (False, 'AAPL did not exist in the porfolio.')\n \"\"\"\n\n if symbol in self.positions:\n del self.positions[symbol]\n if symbol in self.position_lots:\n del self.position_lots[symbol]\n return (True, \"{symbol} was successfully removed.\".format(symbol=symbol))\n else:\n return (False, \"{symbol} did not exist in the porfolio.\".format(symbol=symbol))\n \n def get_performance_tracker(self, totals_only=False):\n \"\"\"Returns the performance_tracker dict\"\"\"\n \n if not self.performance_tracker:\n raise AttributeError('Must create performance tracker before calling.')\n \n tracker = self.performance_tracker\n \n # if we only want the 'total' portfolio metrics\n if totals_only:\n tracker = {}\n \n # reformat dict for making into a DF\n for dt in self.performance_tracker:\n tracker[dt] = {}\n tracker[dt]['cash'] = self.performance_tracker[dt]['total']['cash']\n tracker[dt]['market_value'] = self.performance_tracker[dt]['total']['market_value']\n tracker[dt]['total_value'] = self.performance_tracker[dt]['total']['total_value']\n tracker[dt]['invested_capital'] = self.performance_tracker[dt]['total']['invested_capital']\n tracker[dt]['total_profit_or_loss'] = self.performance_tracker[dt]['total']['total_profit_or_loss']\n tracker[dt]['total_return'] = self.performance_tracker[dt]['total']['total_return']\n \n return tracker\n \n def update_metrics(self, current_prices, date=None, cash=0):\n \"\"\"Updates the returns for each position and the overall portfolio and\n stores them in the performance tracker\n \n current_prices {Dict} -- dict of historical prices of the form\n current_prices[symbol]['close'] = <value>\n date {datetime} -- the date corresponding to the current_prices\n \"\"\"\n \n if not date:\n date = datetime.today()\n\n if not cash:\n cash = self.cash\n \n # if there are no positions in the portfolio yet\n if current_prices == 0:\n\n # add placeholders for each 'total' portfolio metric for that date\n self.performance_tracker[date] = {}\n self.performance_tracker[date]['total'] = {}\n self.performance_tracker[date]['total']['cash'] = cash\n self.performance_tracker[date]['total']['market_value'] = 0\n self.performance_tracker[date]['total']['total_value'] = cash + self.performance_tracker[date]['total']['market_value']\n self.performance_tracker[date]['total']['invested_capital'] = 0\n self.performance_tracker[date]['total']['total_profit_or_loss'] = 0\n self.performance_tracker[date]['total']['total_return'] = 0\n \n else:\n # calc the portfolio values for the timestep\n portfolio_metrics = self.projected_market_value(\n current_prices=current_prices, \n date=date, \n cash=cash\n )\n \n # add the updated values for the timestep to the performance tracker\n self.performance_tracker[date] = portfolio_metrics\n return portfolio_metrics\n\n\n def total_allocation(self) -> dict:\n \"\"\"Returns a summary of the portfolio by asset allocation.\"\"\"\n\n total_allocation = {\n 'equity': [],\n 'fixed_income': [],\n 'options': [],\n 'futures': [],\n 'forex': []\n }\n\n if len(self.positions.keys()) > 0:\n for symbol in self.positions:\n total_allocation[self.positions[symbol]['asset_type']].append(self.positions[symbol])\n return total_allocation\n\n def portfolio_variance(self, weights: dict, covariance_matrix: DataFrame) -> dict:\n\n sorted_keys = list(weights.keys())\n sorted_keys.sort()\n\n sorted_weights = np.array([weights[symbol] for symbol in sorted_keys])\n portfolio_variance = np.dot(\n sorted_weights.T,\n np.dot(covariance_matrix, sorted_weights)\n )\n\n return portfolio_variance\n\n def update_risk_metrics(self) -> dict:\n \"\"\"Calculates different portfolio risk metrics using daily data.\n\n Overview:\n ----\n To build an effective summary of our portfolio we will need to\n calculate different metrics that help represent the risk of our\n portfolio and it's performance. The following metrics will be calculated\n in this method:\n\n 1. Standard Deviation of Percent Returns.\n 2. Covariance of Percent Returns.\n 2. Variance of Percent Returns.\n 3. Average Percent Return\n 4. Weighted Average Percent Return.\n 5. Portfolio Variance.\n\n Returns:\n ----\n dict -- [description]\n \"\"\"\n\n if not self._stock_frame_daily:\n self._grab_daily_historical_prices()\n\n # Calculate the weights.\n porftolio_weights = self.portfolio_weights()\n\n # Calculate the Daily Returns (%)\n self._stock_frame_daily.frame['daily_returns_pct'] = self._stock_frame_daily.symbol_groups['close'].transform(\n lambda x: x.pct_change()\n )\n\n # Calculate the Daily Returns (Mean)\n self._stock_frame_daily.frame['daily_returns_avg'] = self._stock_frame_daily.symbol_groups['daily_returns_pct'].transform(\n lambda x: x.mean()\n )\n\n # Calculate the Daily Returns (Standard Deviation)\n self._stock_frame_daily.frame['daily_returns_std'] = self._stock_frame_daily.symbol_groups['daily_returns_pct'].transform(\n lambda x: x.std()\n )\n\n # Calculate the Covariance.\n returns_cov = self._stock_frame_daily.frame.unstack(\n level=0)['daily_returns_pct'].cov()\n\n # Take the other columns and get ready to add them to our dictionary.\n returns_avg = self._stock_frame_daily.symbol_groups['daily_returns_avg'].tail(\n n=1\n ).to_dict()\n\n returns_std = self._stock_frame_daily.symbol_groups['daily_returns_std'].tail(\n n=1\n ).to_dict()\n\n metrics_dict = {}\n\n portfolio_variance = self.portfolio_variance(\n weights=porftolio_weights,\n covariance_matrix=returns_cov\n )\n\n for index_tuple in returns_std:\n\n symbol = index_tuple[0]\n metrics_dict[symbol] = {}\n metrics_dict[symbol]['weight'] = porftolio_weights[symbol]\n metrics_dict[symbol]['average_returns'] = returns_avg[index_tuple]\n metrics_dict[symbol]['weighted_returns'] = returns_avg[index_tuple] * \\\n metrics_dict[symbol]['weight']\n metrics_dict[symbol]['standard_deviation_of_returns'] = returns_std[index_tuple]\n metrics_dict[symbol]['variance_of_returns'] = returns_std[index_tuple] ** 2\n metrics_dict[symbol]['covariance_of_returns'] = returns_cov.loc[[\n symbol]].to_dict()\n\n metrics_dict['portfolio'] = {}\n metrics_dict['portfolio']['variance'] = portfolio_variance\n\n return metrics_dict\n\n def portfolio_weights(self) -> dict:\n \"\"\"Calculate the weights for each position in the portfolio\n\n Returns:\n ----\n {dict} -- Each symbol with their designated weights.\n \"\"\"\n\n weights = {}\n symbols = self.positions.keys()\n quotes = self.td_client.get_quotes(instruments=list(symbols))\n\n # Grab the projected market value.\n projected_market_value_dict = self.projected_market_value(\n current_prices=quotes\n )\n\n # Calc the weights\n for symbol in projected_market_value_dict:\n if symbol != 'total':\n weights[symbol] = projected_market_value_dict[symbol]['market_value'] / \\\n projected_market_value_dict['total']['market_value']\n\n return weights\n\n def portfolio_summary(self):\n \"\"\"Generates a summary of our portfolio.\"\"\"\n\n # First grab all the symbols.\n symbols = self.positions.keys()\n\n # Grab the quotes.\n quotes = self.td_client.get_quotes(instruments=list(symbols))\n\n portfolio_summary_dict = {}\n portfolio_summary_dict['projected_market_value'] = self.projected_market_value(\n current_prices=quotes\n )\n \n portfolio_summary_dict['portfolio_weights'] = self.portfolio_weights()\n portfolio_summary_dict['portfolio_risk'] = \"\"\n return portfolio_summary_dict\n\n def in_portfolio(self, symbol: str) -> bool:\n \"\"\"checks if the symbol is in the portfolio.\n\n Arguments:\n ----\n symbol {str} -- The symbol of the instrument to be deleted. Example: 'AAPL' or '/ES'\n\n Returns:\n ----\n bool -- `True` if the position is in the portfolio, `False` otherwise.\n\n Usage:\n ----\n >>> portfolio = Portfolio()\n >>> new_position = Portfolio.add_position(\n symbol='MSFT', \n asset_type='equity'\n )\n >>> in_position_flag = Portfolio.in_portfolio(symbol='MSFT')\n >>> in_position_flag\n True\n \"\"\"\n\n return symbol in self.positions\n\n def get_ownership_status(self, symbol: str) -> bool:\n \"\"\"Gets the ownership status for a position in the portfolio.\n\n Arguments:\n ----\n symbol {str} -- The symbol you want to grab the ownership status for.\n\n Returns:\n ----\n {bool} -- `True` if the we own the position, `False` if we do not own it.\n \"\"\"\n\n if self.in_portfolio(symbol=symbol) and self.positions[symbol]['ownership_status']:\n return self.positions[symbol]['ownership_status']\n else:\n return False\n\n def set_ownership_status(self, symbol: str, ownership: bool=None) -> None:\n \"\"\"Sets the ownership status for a position in the portfolio.\n\n Arguments:\n ----\n symbol {str} -- The symbol you want to change the ownership status for.\n\n ownership {bool} -- The ownership status you want the symbol to have. Can either\n be `True` or `False`.\n\n Raises:\n ----\n KeyError: If the symbol does not exist in the portfolio it will return an error.\n \"\"\"\n\n if ownership:\n self.positions[symbol]['ownership_status'] = ownership\n \n else:\n try:\n self.positions[symbol]['ownership_status'] = self.in_portfolio(symbol) and \\\n self.positions[symbol]['quantity'] != 0\n except KeyError:\n raise KeyError(\n \"Can't set ownership status, you either do not have the symbol in your portfolio or no invested shares.\"\n )\n\n def is_profitable(self, symbol: str, current_price: float) -> bool:\n \"\"\"Specifies whether a position is profitable.\n\n Arguments:\n ----\n symbol {str} -- The symbol of the instrument, to check profitability.\n\n current_price {float} -- The current trading price of the instrument.\n\n Returns:\n ----\n {bool} -- Specifies whether the position is profitable or flat `True` or not\n profitable `False`.\n\n Raises:\n ----\n KeyError: If the Symbol does not exist it will return a key error.\n\n Usage:\n ----\n >>> portfolio = Portfolio()\n >>> new_position = Portfolio.add_position(\n symbol='MSFT', \n asset_type='equity',\n purchase_price=4.00,\n purchase_date=\"2020-01-31\"\n )\n >>> is_profitable_flag = Portfolio.is_profitable(\n symbol='MSFT',\n current_price=7.00\n )\n >>> is_profitable_flag\n True\n \"\"\"\n\n # Grab the purchase price, if it exists.\n if self.in_portfolio(symbol=symbol):\n purchase_price = self.positions[symbol]['purchase_price']\n else:\n raise KeyError(\"The Symbol you tried to request does not exist.\")\n\n return purchase_price <= current_price\n\n def projected_market_value(self, current_prices: dict, date=None, cash=0) -> dict:\n \"\"\"Returns the Projected market value for all the positions in the portfolio.\n\n Arguments:\n ----\n current_prices {dict} -- A dictionary of current quotes for each of the symbols\n in the portfolio.\n date {datetime} -- The then-current date of the prices data\n cash {float} -- The then-current cash balance\n\n Returns:\n ----\n dict -- A summarized version of the portfolio with each position, purchase price, current price,\n and projected values.\n\n Usage:\n ----\n >>> portfolio = Portfolio()\n >>> new_position = portfolio.add_position(\n symbol='MSFT', \n asset_type='equity',\n purchase_price=4.00,\n purchase_date=\"2020-01-31\"\n )\n >>> portfolio_summary = portfolio.projected_market_value(current_prices={'MSFT':{'lastPrice': 8.00, 'openPrice': 7.50}}) \n \"\"\"\n\n projected_value = {}\n market_value = 0.0\n invested_capital = 0.0\n\n if not date:\n date = datetime.today()\n\n for symbol in current_prices:\n if self.in_portfolio(symbol=symbol):\n \n try:\n current_price = current_prices[symbol]['lastPrice']\n except KeyError:\n current_price = current_prices[symbol]['close']\n \n self.positions[symbol]['current_price'] = current_price\n\n position_quantity = 0\n position_cost_basis = 0\n position_market_value = 0\n \n for lot in self.position_lots[symbol]:\n lot['days_held'] = date - lot['purchase_date']\n lot['market_value'] = lot['quantity'] * current_price\n lot['cost_basis'] = lot['quantity'] * lot['purchase_price']\n lot['profit_loss'] = lot['market_value'] - lot['cost_basis']\n lot['total_return'] = round((lot['profit_loss'] / lot['cost_basis']), 4)\n lot['annualized_return'] = round((lot['profit_loss'] / lot['cost_basis']) * (365 / (date - datetime.strptime(str(lot['purchase_date']), \"%Y-%m-%d %H:%M:%S\")).days), 4)\n \n # aggregate for total position values\n position_quantity += lot['quantity']\n position_cost_basis += lot['cost_basis']\n position_market_value += lot['market_value']\n\n self.positions[symbol]['quantity'] = position_quantity\n self.positions[symbol]['cost_basis'] = position_cost_basis\n self.positions[symbol]['market_value'] = position_market_value\n self.positions[symbol]['purchase_price'] = round(position_cost_basis / position_quantity, 4)\n\n self.positions[symbol]['profit_loss'] = round(\n (position_market_value - position_cost_basis), 4)\n self.positions[symbol]['total_return'] = round(\n (position_market_value - position_cost_basis) / position_cost_basis, 4)\n self.positions[symbol]['annualized_return'] = round(\n self.positions[symbol]['total_return'] * (365 / (date - datetime.strptime(\n str(self.positions[symbol]['purchase_date']), \"%Y-%m-%d %H:%M:%S\")).days), 4)\n \n projected_value[symbol] = self.positions[symbol].copy()\n\n # aggregate for total portfolio metrics\n market_value += self.positions[symbol]['market_value']\n invested_capital += projected_value[symbol]['cost_basis']\n\n projected_value['total'] = {}\n projected_value['total']['cash'] = cash\n projected_value['total']['positions_count'] = len(self.positions)\n projected_value['total']['market_value'] = market_value\n projected_value['total']['total_value'] = cash + market_value\n projected_value['total']['invested_capital'] = invested_capital\n \n # grab the initial portfolio balance to calc returns\n initial_bar = self._get_earliest_performance_bar()\n beginning_balance = initial_bar['total']['total_value'] if initial_bar else cash + market_value\n \n projected_value['total']['total_profit_or_loss'] = round((cash + market_value - beginning_balance), 4)\n projected_value['total']['total_return'] = round((projected_value['total']['total_profit_or_loss'] / beginning_balance), 4)\n\n self.cash = cash\n self.market_value = market_value\n self.total_value = cash + market_value\n self.invested_capital = invested_capital\n self.profit_loss = projected_value['total']['total_profit_or_loss']\n self.total_return = projected_value['total']['total_return']\n \n return projected_value\n\n def _get_earliest_performance_bar(self):\n \"\"\"Grabs the beginning values in the performance tracker\"\"\"\n\n if not self.performance_tracker:\n return None\n\n earliest_date = min(self.performance_tracker.keys())\n return self.performance_tracker[earliest_date]\n\n def get_portfolio_max_drawdown(self, window: int=252):\n \"\"\"Calcs the max drawdown for the portfolio. Max DD calc as the max\n percent decrease in the port's total val (mv + cash) from the highest\n preceeding total val\n\n window -- the size of the rolling period to use to calc min/max\n drawdown; note there are 252 trading days in a year, so if you want a\n window of 2, 3, 4,... years the window will be 504, 756, 1008,... days\n\n \"\"\"\n\n if not self.performance_tracker:\n raise AttributeError('Must create performance tracker before calc max drawdown.')\n\n total_performance_tracker = self.get_performance_tracker(totals_only=True)\n df = pd.DataFrame.from_dict(total_performance_tracker, orient='index')\n \n # # calc daily max marketval over window days\n # rolling_max_mv = df['market_value'].rolling(window=window, min_periods=1).max()\n\n # # calc daily drawdown; subtract 1 to make DD negative\n # daily_drawdown = df['market_value'] / rolling_max_mv - 1.0\n\n\n # # calc daily max totalval over window days\n # rolling_max_tv = df['total_value'].rolling(window=window, min_periods=1).max()\n\n # # calc daily drawdown; subtract 1 to make DD negative\n # daily_drawdown = df['total_value'] / rolling_max_tv - 1.0\n\n # # then calc max drawdown as min of daily drawdowns over 'window' days\n # daily_max_drawdown = daily_drawdown.rolling(window, min_periods=1).min()\n \n\n # calc daily max totalval over window days\n df['rolling_max_tv'] = df['total_value'].rolling(window=window, min_periods=1).max()\n\n # calc daily drawdown; subtract 1 to make DD negative\n df['daily_drawdown'] = df['total_value'] / df['rolling_max_tv'] - 1.0\n\n # then calc max drawdown as min of daily drawdowns over 'window' days\n df['daily_max_drawdown'] = df['daily_drawdown'].rolling(window, min_periods=1).min()\n\n\n # pd.set_option('display.max_rows', 300)\n print(df.head(500))\n\n return min(df['daily_max_drawdown'])\n\n def get_max_drawdown(self, tracker: dict=None, keys=None, print_stuff=True):\n \"\"\"My original method fo calculating the max drawdown [DELETE?] -- note\n that this returns the same val as get_portfolio_max_drawdown (although I\n think the other func is faster)\n \n \"\"\"\n\n if not tracker:\n tracker = self.get_performance_tracker(totals_only=False)\n if not keys:\n keys = set([tracker[dt]['total'] for dt in tracker])\n\n display_min_vals = {}\n display_min_val_dates = {}\n display_max_prior_vals = {}\n display_max_prior_vals_dates = {}\n display_min_portfolio_mv = {}\n display_max_prior_portfolio_mv = {}\n display_max_drawdowns = {}\n \n daily_portfolio_mvs = [(dt, tracker[dt]['total']['market_value']) for dt in tracker if isinstance(tracker[dt], dict)]\n \n for key in keys:\n daily_portfolio_vals = [(dt, tracker[dt]['total'][key]) for dt in tracker if isinstance(tracker[dt], dict)]\n min_portfolio_val = min([x[1] for x in daily_portfolio_vals])\n min_portfolio_val_date = [x[0] for x in daily_portfolio_vals if x[1] == min_portfolio_val][0]\n \n prior_daily_portfolio_vals = [tup for tup in daily_portfolio_vals if tup[0] < min_portfolio_val_date]\n max_prior_portfolio_val = max([tup[1] for tup in prior_daily_portfolio_vals])\n max_prior_portfolio_val_date = [tup[0] for tup in prior_daily_portfolio_vals if tup[1] == max_prior_portfolio_val][0]\n \n min_portfolio_mv = [x[1] for x in daily_portfolio_mvs if x[0] == min_portfolio_val_date][0]\n max_prior_portfolio_mv = [x[1] for x in daily_portfolio_mvs if x[0] == max_prior_portfolio_val_date][0]\n \n max_drawdown = round((min_portfolio_mv - max_prior_portfolio_mv) / max_prior_portfolio_mv, 4)\n \n display_min_vals[f'min_val_(key={key})'] = min_portfolio_val\n display_min_val_dates[f'date_min_val_(key={key})'] = min_portfolio_val_date\n display_max_prior_vals[f'max_prior_val_(key={key})'] = max_prior_portfolio_val\n display_max_prior_vals_dates[f'date_max_prior_val_(key={key})'] = max_prior_portfolio_val_date\n display_min_portfolio_mv[f'min_mv_(key={key})'] = min_portfolio_mv\n display_max_prior_portfolio_mv[f'max_prior_mv_(key={key})'] = max_prior_portfolio_mv\n display_max_drawdowns[f'max_drawdown_(key={key})'] = max_drawdown\n\n if print_stuff:\n print('--'*50)\n [print(f'{min_val}: {display_min_vals[min_val]}') for min_val in display_min_vals]\n print()\n [print(f'{min_val_date}: {display_min_val_dates[min_val_date]}') for min_val_date in display_min_val_dates]\n print()\n [print(f'{max_val}: {display_max_prior_vals[max_val]}') for max_val in display_max_prior_vals]\n print()\n [print(f'{max_val_date}: {display_max_prior_vals_dates[max_val_date]}') for max_val_date in display_max_prior_vals_dates]\n print()\n [print(f'{min_mv}: {display_min_portfolio_mv[min_mv]}') for min_mv in display_min_portfolio_mv]\n print()\n [print(f'{max_mv}: {display_max_prior_portfolio_mv[max_mv]}') for max_mv in display_max_prior_portfolio_mv]\n print()\n [print(f'{drawdown}: {display_max_drawdowns[drawdown]}') for drawdown in display_max_drawdowns]\n print('--'*50)\n\n all_drawdowns = [display_max_drawdowns[d] for d in display_max_drawdowns]\n max_drawdown = max(set(all_drawdowns), key = all_drawdowns.count)\n return max_drawdown\n \n @property\n def historical_prices(self) -> List[dict]:\n \"\"\"Gets the historical prices for the Portfolio\n\n Returns:\n ----\n List[dict] -- A list of historical candle prices.\n \"\"\"\n\n return self._historical_prices\n\n @historical_prices.setter\n def historical_prices(self, historical_prices: List[dict]) -> None:\n \"\"\"Sets the historical prices for the Portfolio\n\n Arguments:\n ----\n historical_prices {List[dict]} -- A list of historical candle prices.\n \"\"\"\n\n self._historical_prices = historical_prices\n\n @property\n def stock_frame(self) -> StockFrame:\n \"\"\"Gets the StockFrame object for the Portfolio\n\n Returns:\n ----\n {StockFrame} -- A StockFrame object with symbol groups, and rolling windows.\n \"\"\"\n\n return self._stock_frame\n\n @stock_frame.setter\n def stock_frame(self, stock_frame: StockFrame) -> None:\n \"\"\"Sets the StockFrame object for the Portfolio\n\n Arguments:\n ----\n stock_frame {StockFrame} -- A StockFrame object with symbol groups, and rolling windows.\n \"\"\"\n\n self._stock_frame = stock_frame\n\n @property\n def td_client(self) -> TDClient:\n \"\"\"Gets the TDClient object for the Portfolio\n\n Returns:\n ----\n {TDClient} -- An authenticated session with the TD API.\n \"\"\"\n\n return self._td_client\n\n @td_client.setter\n def td_client(self, td_client: TDClient) -> None:\n \"\"\"Sets the TDClient object for the Portfolio\n\n Arguments:\n ----\n td_client {TDClient} -- An authenticated session with the TD API.\n \"\"\"\n\n self._td_client: TDClient = td_client\n\n def _grab_daily_historical_prices(self) -> StockFrame:\n \"\"\"Grabs the daily historical prices for each position and sets the daily\n stock frame, which is multi indexed by symbol and datetime\n\n Returns:\n ----\n {StockFrame} -- A StockFrame object with data organized, grouped, and\n sorted.\n \"\"\"\n\n new_prices = []\n\n # Loop through each position.\n for symbol in self.positions:\n\n # Grab the historical prices.\n historical_prices_response = self.td_client.get_price_history(\n symbol=symbol,\n period_type='year',\n period=1,\n frequency_type='daily',\n frequency=1,\n extended_hours=True\n )\n\n # Loop through the chandles.\n for candle in historical_prices_response['candles']:\n\n new_price_mini_dict = {}\n new_price_mini_dict['symbol'] = symbol\n new_price_mini_dict['open'] = candle['open']\n new_price_mini_dict['close'] = candle['close']\n new_price_mini_dict['high'] = candle['high']\n new_price_mini_dict['low'] = candle['low']\n new_price_mini_dict['volume'] = candle['volume']\n new_price_mini_dict['datetime'] = candle['datetime']\n new_prices.append(new_price_mini_dict)\n\n # Create and set the StockFrame\n self._stock_frame_daily = StockFrame(data=new_prices)\n self._stock_frame_daily.create_frame()\n\n return self._stock_frame_daily\n\n\n# s = 'happy is friday everyone that is awesome how we doing happy how'\n# test_set = set([i for i in s.split()])\n# print('happy' in test_set)" ]
[ [ "pandas.DataFrame.from_dict", "numpy.array", "numpy.dot" ] ]
liuhuaijjin/epnet_det3d_rcnn_reg_dir_cls_iou3d_loss
[ "0123c341243846aa3b412addcb9e2c07fd305237" ]
[ "lib/utils/roipool3d/roipool3d_utils.py" ]
[ "import torch\nimport roipool3d_cuda\nimport numpy as np\nimport lib.utils.kitti_utils as kitti_utils\n\n\ndef roipool3d_gpu(pts, pts_feature, boxes3d, pool_extra_width, sampled_pt_num = 512):\n \"\"\"\n :param pts: (B, N, 3)\n :param pts_feature: (B, N, C)\n :param boxes3d: (B, M, 7)\n :param pool_extra_width: float\n :param sampled_pt_num: int\n :return:\n pooled_features: (B, M, 512, 3 + C)\n pooled_empty_flag: (B, M)\n \"\"\"\n batch_size, boxes_num, feature_len = pts.shape[0], boxes3d.shape[1], pts_feature.shape[2]\n pooled_boxes3d = kitti_utils.enlarge_box3d(boxes3d.view(-1, 7), pool_extra_width).view(batch_size, -1, 7)\n\n pooled_features = torch.cuda.FloatTensor(torch.Size((batch_size, boxes_num,\n sampled_pt_num, 3 + feature_len))).zero_()\n pooled_empty_flag = torch.cuda.IntTensor(torch.Size((batch_size, boxes_num))).zero_()\n\n roipool3d_cuda.forward(pts.contiguous(), pooled_boxes3d.contiguous(),\n pts_feature.contiguous(), pooled_features, pooled_empty_flag)\n\n return pooled_features, pooled_empty_flag\n\n\ndef pts_in_boxes3d_cpu(pts, boxes3d):\n \"\"\"\n :param pts: (N, 3) in rect-camera coords\n :param boxes3d: (M, 7)\n :return: boxes_pts_mask_list: (M), list with [(N), (N), ..]\n \"\"\"\n if not pts.is_cuda:\n pts = pts.float().contiguous()\n boxes3d = boxes3d.float().contiguous()\n pts_flag = torch.LongTensor(torch.Size((boxes3d.size(0), pts.size(0)))) # (M, N)\n roipool3d_cuda.pts_in_boxes3d_cpu(pts_flag, pts, boxes3d)\n\n boxes_pts_mask_list = []\n for k in range(0, boxes3d.shape[0]):\n cur_mask = pts_flag[k] > 0\n boxes_pts_mask_list.append(cur_mask)\n return boxes_pts_mask_list\n else:\n raise NotImplementedError\n\n\ndef roipool_pc_cpu(pts, pts_feature, boxes3d, sampled_pt_num):\n \"\"\"\n :param pts: (N, 3)\n :param pts_feature: (N, C)\n :param boxes3d: (M, 7)\n :param sampled_pt_num: int\n :return:\n \"\"\"\n pts = pts.cpu().float().contiguous()\n pts_feature = pts_feature.cpu().float().contiguous()\n boxes3d = boxes3d.cpu().float().contiguous()\n assert pts.shape[0] == pts_feature.shape[0] and pts.shape[1] == 3, '%s %s' % (pts.shape, pts_feature.shape)\n assert pts.is_cuda is False\n pooled_pts = torch.FloatTensor(torch.Size((boxes3d.shape[0], sampled_pt_num, 3))).zero_()\n pooled_features = torch.FloatTensor(torch.Size((boxes3d.shape[0], sampled_pt_num, pts_feature.shape[1]))).zero_()\n pooled_empty_flag = torch.LongTensor(boxes3d.shape[0]).zero_()\n roipool3d_cuda.roipool3d_cpu(pts, boxes3d, pts_feature, pooled_pts, pooled_features, pooled_empty_flag)\n return pooled_pts, pooled_features, pooled_empty_flag\n\n\ndef roipool3d_cpu(boxes3d, pts, pts_feature, pts_extra_input, pool_extra_width, sampled_pt_num = 512,\n canonical_transform = True):\n \"\"\"\n :param boxes3d: (N, 7)\n :param pts: (N, 3)\n :param pts_feature: (N, C)\n :param pts_extra_input: (N, C2)\n :param pool_extra_width: constant\n :param sampled_pt_num: constant\n :return:\n \"\"\"\n pooled_boxes3d = kitti_utils.enlarge_box3d(boxes3d, pool_extra_width)\n\n pts_feature_all = np.concatenate((pts_extra_input, pts_feature), axis = 1)\n\n # Note: if pooled_empty_flag[i] > 0, the pooled_pts[i], pooled_features[i] will be zero\n pooled_pts, pooled_features, pooled_empty_flag = \\\n roipool_pc_cpu(torch.from_numpy(pts), torch.from_numpy(pts_feature_all),\n torch.from_numpy(pooled_boxes3d), sampled_pt_num)\n\n extra_input_len = pts_extra_input.shape[1]\n sampled_pts_input = torch.cat((pooled_pts, pooled_features[:, :, 0:extra_input_len]), dim = 2).numpy()\n sampled_pts_feature = pooled_features[:, :, extra_input_len:].numpy()\n\n if canonical_transform:\n # Translate to the roi coordinates\n roi_ry = boxes3d[:, 6] % (2 * np.pi) # 0~2pi\n roi_center = boxes3d[:, 0:3]\n\n # shift to center\n sampled_pts_input[:, :, 0:3] = sampled_pts_input[:, :, 0:3] - roi_center[:, np.newaxis, :]\n for k in range(sampled_pts_input.shape[0]):\n sampled_pts_input[k] = kitti_utils.rotate_pc_along_y(sampled_pts_input[k], roi_ry[k])\n\n return sampled_pts_input, sampled_pts_feature\n\n return sampled_pts_input, sampled_pts_feature, pooled_empty_flag.numpy()\n\n\nif __name__ == '__main__':\n pass\n" ]
[ [ "numpy.concatenate", "torch.Size", "torch.cat", "torch.from_numpy", "torch.LongTensor" ] ]
BYU-PRISM/Grid-Energy-Management
[ "a10c6f9a9bbd9a8a8a44dc0b42fb7bd923d33cd0" ]
[ "gekko_load_follow.py" ]
[ "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Feb 26 09:28:49 2021\n\n@author: nathanielgates\n\"\"\"\n\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport utilities as util\nimport feasibility as fs\nfrom gekko import GEKKO\n\n\ndef model(t, plot=False, disp=False, ramp=1, imode=6, nodes='', solver=3,\n mv_step_hor='', cv_type=1, max_time='',\n # server='https://gekko.apmonitor.com'):\n server='http://byu.apmonitor.com'):\n \n '''\n Test options:\n n = 16\n t = np.linspace(0, 1, n+1)\n plot=False\n disp=True\n ramp=1\n imode=6\n nodes=3\n server='https://gekko.apmonitor.com'\n '''\n \n # t = np.linspace(0, 1, 101)\n m = GEKKO(remote=True)\n m._server = server\n\n m.time = t\n \n # m.options.MAX_ITER = 1000\n if max_time == '':\n pass\n else:\n m.options.MAX_TIME = max_time\n\n load = m.Param(np.cos(2*np.pi*t)+3)\n # load = m.Param(np.cos(2*np.pi*t)/2 + 3.5)\n gen = m.Var(load[0])\n\n err = m.CV(0)\n err.STATUS = 1\n err.SPHI = err.SPLO = 0\n err.WSPHI = 1000\n err.WSPLO = 1\n\n dgen = m.MV(0, lb=-ramp, ub=ramp) # ramp rate\n dgen.STATUS = 1\n\n m.Equations([gen.dt() == dgen, err == load-gen])\n \n m.Obj(err**2 / len(t)) # Added\n \n if nodes == '':\n pass\n else:\n m.options.NODES = nodes # 4\n \n m.options.SOLVER = solver\n m.options.IMODE = imode\n # m.options.CV_TYPE = 2 # 1 = Linear penalty from a dead-band trajectory\n m.options.CV_TYPE = cv_type # 1 = Linear penalty from a dead-band trajectory\n\n if mv_step_hor != '':\n m.options.MV_STEP_HOR = mv_step_hor\n \n try:\n \n # Solve the optimization model (enforces disp=True)\n txt = util.solve_and_get_txt(m)\n \n # Get additional APMonitor values\n out = util.get_apm_values(txt)\n \n if plot:\n import matplotlib.pyplot as plt\n plt.plot(t, load)\n plt.plot(t, gen)\n plt.plot(t, dgen)\n plt.show()\n M = m.options\n message = M.APPINFO\n if message == 0:\n message = \"Optimization terminated successfully\"\n consCheck = [\n gen.value, t,\n dgen.value\n ]\n feasible, error1 = fs.load_feasibility(consCheck, tol=1e-6)\n except:\n M = m.options\n message = M.APPINFO\n if message == 0:\n message = \"Solution not found\"\n feasible = False\n error1 = \"NA\"\n out = {}\n info = {\n 'Model':'Gekko load-following',\n 'time_steps':len(t),\n 'fcalls':M.ITERATIONS,\n 'gcalls':'NA',\n 'f':M.OBJFCNVAL,\n 'feasible':feasible,\n 'ramp err':error1,\n 'total err':error1,\n 'time (s)':M.SOLVETIME,\n 'message':message,\n 'status':M.APPSTATUS,\n 'path':m._path\n }\n data = {\n 'load': load,\n 'gen': gen,\n 'dgen': dgen,\n 't': t\n }\n \n # Add in the APMonitor data\n info = {**info, **out}\n \n return info, data \n\n#%%\n\nif __name__ == \"__main__\":\n \n option = 0 # Run model once and plot data\n # option = 2 # Grid refinement study, sim vs seq\n # option = 3 # Grid refinement, sim vs seq, changing DOF with mv_step_hor\n model_name = '1 - Load Following'\n \n # plt.close('all')\n \n if option == 0:\n t = np.linspace(0, 1, 101)\n # t = np.linspace(0, 1, 73)\n imode = 6\n # imode = 9\n info, data = model(t, plot=False, disp=True, imode=imode)\n print(info['fcalls'])\n \n util.plot_load_follow(data, version=2)\n \n elif option == 1:\n d = {}\n df = {}\n ramps = [0.25, 0.5, 1, 2, 4, 8]\n t = np.linspace(0, 1, 101) # Need to weight ramp by timestep length...\n for ramp in ramps:\n print(ramp)\n sol, res = model(t, plot=False, ramp=ramp)\n df[ramp] = sol\n d[ramp] = res\n df = pd.DataFrame(df).T.reset_index().rename(columns={'index': 'ramp'})\n for ramp in ramps:\n d[ramp] = pd.DataFrame(d[ramp], index=np.arange(len(t)))\n # test = pd.DataFrame(d).T.reset_index().rename(columns={'index': 'ramp'})\n\n #%%\n \n plt.figure(); plt.plot(df.ramp, df['time (s)'])\n # Need to run n times and take the average\n \n fig, axes = plt.subplots(3, 2, sharex=True)\n axes = axes.ravel()\n \n for i, ramp in enumerate(ramps):\n ax = axes[i]\n d[ramp].plot(ax=ax, legend=False)\n ax.set_title(ramp)\n ax.set_ylim(-2*np.pi*1.1, 2*np.pi*1.1)\n plt.tight_layout()\n #%%\n \n elif option == 2:\n \n #%%\n df = {}\n d = {}\n imodes = [6, 9]\n # imodes = [9, 6]\n for imode in imodes:\n print('iMode: {}'.format(imode))\n # steps = [3, 6, 9] # [5, 10, 20]#, 40, 80]#, 160, 320]\n base = 2\n end = 5 # 8 # 5 # 7 # 9\n # base = 1.5 # 2\n # end = 13 # 8 # 5 # 7 # 9\n steps = [int(base**i) for i in range(2, end)]\n df[imode] = {}\n d[imode] = {}\n for n in steps:\n t = np.linspace(0, 1, n+1)\n add = [0.01]#, 0.02]\n t = np.array(list(sorted(list(t) + add)))\n print(n)\n sol, res = model(t, disp=True, imode=imode)\n df[imode][n] = sol\n d[imode][n] = res\n for imode in imodes:\n df[imode] = pd.DataFrame(df[imode]).T.reset_index().rename(columns={'index': 'step'})\n df = (pd.concat(df)\n .reset_index()\n .rename(columns={'level_0': 'imode'})\n .drop(columns='level_1')\n )\n \n df[['imode', 'step']] = df[['imode', 'step']].astype(int)\n df = df.set_index(['imode', 'time_steps'])\n \n df['TIME/ITERATION'] = df['time (s)'] / df.ITERATIONS\n \n for imode in imodes:\n for n in steps:\n d[imode][n] = pd.DataFrame(d[imode][n], \n index=np.arange(n+1+len(add)))\n d[imode] = pd.concat(d[imode])\n d = (pd.concat(d)\n .reset_index()\n .rename(columns={'level_0': 'imode', 'level_1': 'step'})\n .drop(columns='level_2')\n .set_index(['imode', 'step'])\n )\n \n #%% Plot time\n \n if 0:\n var = 'time (s)'\n label = 'Solve Time (s)'\n \n plt.figure()\n logx = logy = True\n df.loc[6][var].plot(marker='o', \n markeredgecolor='C0', \n markerfacecolor='None',\n label='Simultaneous',\n logx=logx,\n logy=logy)\n df.loc[9][var].plot(marker='o', \n markeredgecolor='C1', \n markerfacecolor='None',\n label='Sequential',\n logx=logx,\n logy=logy)\n \n ax = plt.gca()\n ax.set_xlabel('Number of Timesteps')\n ax.set_ylabel(label)\n ax.legend()\n ax.set_title(model_name)\n ax.grid(linestyle=':', alpha=0.6, c='k', linewidth=0.6)\n plt.tight_layout()\n plt.savefig(model_name.replace(' ', '_')+'_time.pdf')\n \n #%% Plot iterations\n \n if 0:\n var = 'ITERATIONS'\n label = 'Number of Iterations'\n \n plt.figure()\n logx = True\n logy = False\n df.loc[6][var].plot(marker='o', \n markeredgecolor='C0', \n markerfacecolor='None',\n label='Simultaneous',\n logx=logx,\n logy=logy)\n df.loc[9][var].plot(marker='o', \n markeredgecolor='C1', \n markerfacecolor='None',\n label='Sequential',\n logx=logx,\n logy=logy)\n \n ax = plt.gca()\n ax.set_xlabel('Number of Timesteps')\n ax.set_ylabel(label)\n ax.legend()\n model_name = '1 - Load Following'\n ax.set_title(model_name)\n ax.grid(linestyle=':', alpha=0.6, c='k', linewidth=0.6)\n plt.tight_layout()\n plt.savefig(model_name.replace(' ', '_')+'_iterations.pdf')\n \n #%% Plot results\n \n fig, axes = plt.subplots(len(steps), 2, sharex=True, sharey=True, \n figsize=(8, 6))\n \n imode_name = {6: 'Simultaneous', 9: 'Sequential'}\n \n step_dict = df.reset_index()[['step', 'time_steps']].drop_duplicates()\n step_dict = dict(zip(step_dict['step'], step_dict.time_steps))\n \n for j, imode in enumerate(imodes):\n # time_steps = list(sorted(list(set(d.loc[imode].index))))\n for i, step in enumerate(steps):\n ax = axes[i, j]\n dp = d.loc[imode].loc[step].set_index('t')\n dp.plot(ax=ax, legend=False, \n marker='.')\n # marker='o',\n # markerfacecolor='None', markersize=5)\n if j == 0:\n ax.set_ylabel('$t_n=${} '.format(step_dict[step]), \n rotation=0, ha='right', va='center')\n if i == 0:\n ax.set_title(imode_name[imode])\n ax.grid(linestyle=':', alpha=0.6, c='k', linewidth=0.6)\n axes[1, 1].legend(bbox_to_anchor=(1.05, 0.5), loc='center left',\n frameon=False)\n util.set_equal_ylim(axes.ravel())\n plt.suptitle(model_name)\n plt.tight_layout(rect=[0, 0, 1, 0.95])\n plt.subplots_adjust(hspace=0.1)\n plt.savefig(model_name.replace(' ', '_')+'_data.pdf')\n \n #%% Plot quadrant of data\n \n util.plot_data(df, model_name)\n \n #%%\n \n elif option == 3:\n #%%\n df = {}\n d = {}\n imodes = [6, 9]\n # imodes = [9, 6]\n for imode in imodes:\n print('iMode: {}'.format(imode))\n # steps = [3, 6, 9] # [5, 10, 20]#, 40, 80]#, 160, 320]\n base = 2\n end = 5 # 8 # 5 # 7 # 9\n # base = 1.5 # 2\n # end = 13 # 8 # 5 # 7 # 9\n steps = [int(base**i) for i in range(2, end)]\n # steps = [5, 10, 20]#, 40]\n # mv_step_hors = [1, 2, 4]#, 8]\n steps = [10, 20, 40]#, 80, 160]\n mv_step_hors = [5, 10, 20]\n # mv_step_hors = [2]*len(steps) #[1, 2, 3]\n df[imode] = {}\n d[imode] = {}\n for i, n in enumerate(steps):\n t = np.linspace(0, 1, n+1)\n add = []# Removed to keep things constant with DOF [0.01]#, 0.02]\n add = list(np.linspace(0+t[1]/n, t[1], (mv_step_hors[i]+2)*2)[:-1])\n t = np.array(list(sorted(list(t) + add)))\n print(n)\n sol, res = model(t, disp=True, imode=imode, \n mv_step_hor=mv_step_hors[i])\n df[imode][n] = sol\n d[imode][n] = res\n for imode in imodes:\n df[imode] = pd.DataFrame(df[imode]).T.reset_index().rename(columns={'index': 'step'})\n df = (pd.concat(df)\n .reset_index()\n .rename(columns={'level_0': 'imode'})\n .drop(columns='level_1')\n )\n \n df[['imode', 'step']] = df[['imode', 'step']].astype(int)\n df = df.set_index(['imode', 'time_steps'])\n \n df['TIME/ITERATION'] = df['time (s)'] / df.ITERATIONS\n \n for imode in imodes:\n for n in steps:\n d[imode][n] = pd.DataFrame(d[imode][n])#, \n # index=np.arange(n+1+len(add)))\n d[imode] = pd.concat(d[imode])\n d = (pd.concat(d)\n .reset_index()\n .rename(columns={'level_0': 'imode', 'level_1': 'step'})\n .drop(columns='level_2')\n .set_index(['imode', 'step'])\n )\n\n #%% Plot results\n \n fig, axes = plt.subplots(len(steps), 2, sharex=True, sharey=True, \n figsize=(8, 6))\n \n imode_name = {6: 'Simultaneous', 9: 'Sequential'}\n \n step_dict = df.reset_index()[['step', 'time_steps']].drop_duplicates()\n step_dict = dict(zip(step_dict['step'], step_dict.time_steps))\n \n for j, imode in enumerate(imodes):\n # time_steps = list(sorted(list(set(d.loc[imode].index))))\n for i, step in enumerate(steps):\n ax = axes[i, j]\n dp = d.loc[imode].loc[step].set_index('t')\n dp.plot(ax=ax, legend=False, \n marker='.')\n # marker='o',\n # markerfacecolor='None', markersize=5)\n if j == 0:\n ax.set_ylabel('$t_n=${} '.format(step_dict[step]), \n rotation=0, ha='right', va='center')\n if i == 0:\n ax.set_title(imode_name[imode])\n ax.grid(linestyle=':', alpha=0.6, c='k', linewidth=0.6)\n axes[1, 1].legend(bbox_to_anchor=(1.05, 0.5), loc='center left',\n frameon=False)\n util.set_equal_ylim(axes.ravel())\n plt.suptitle(model_name)\n plt.tight_layout(rect=[0, 0, 1, 0.95])\n plt.subplots_adjust(hspace=0.1)\n # plt.savefig(model_name.replace(' ', '_')+'_data.pdf')\n \n #%% Plot quadrant of data\n \n util.plot_data(df, model_name, save=False)\n \n\n" ]
[ [ "matplotlib.pyplot.gca", "pandas.DataFrame", "matplotlib.pyplot.plot", "matplotlib.pyplot.suptitle", "matplotlib.pyplot.subplots", "matplotlib.pyplot.figure", "matplotlib.pyplot.tight_layout", "numpy.cos", "pandas.concat", "matplotlib.pyplot.show", "numpy.linspace", "matplotlib.pyplot.subplots_adjust" ] ]
gradientinstitute/ai-impact-control-panel
[ "4a00a8d8f731344b9f5599ec40748ba5b79d7904" ]
[ "deva/pareto.py" ]
[ "\"\"\"\nModule to filter pareto inefficient candidates.\n\nCopyright 2021-2022 Gradient Institute Ltd. <[email protected]>\n\"\"\"\n\nimport numpy as np\n\n\ndef remove_non_pareto(models):\n \"\"\"Reduces the set of models down to the efficient set.\"\"\"\n n = len(models)\n dominated = np.zeros(n, dtype=bool)\n\n names, scores = zip(*models.items())\n # count = 0\n\n for i, m in enumerate(scores):\n for j, n in enumerate(scores):\n\n # optional checks to reduce the number of comparisons\n if dominated[i]:\n break\n\n if dominated[j] | (i == j):\n continue\n\n dominated[i] |= (all(m[a] >= n[a] for a in m)\n & any(m[a] > n[a] for a in m))\n # count += 1\n\n # print(f\"Comparisons: {count/len(names)**2:.0%}\")\n efficient = models.copy()\n for name, dom in zip(names, dominated):\n if dom:\n del efficient[name]\n\n d = sum(dominated)\n s = \"\" if d == 1 else \"s\"\n print(\"Deleted {} pareto inefficient model{}.\".format(d, s))\n\n return efficient\n" ]
[ [ "numpy.zeros" ] ]
Emilurenius/Pool-Table-RGB
[ "209ca77b21e5fe487c65488a8b77afbd7d9982da" ]
[ "imageRecognition/testCode/colorDetection.py" ]
[ "import cv2, numpy as np\n\ndef empty(a):\n pass\n\npath = \"resources/lambo.png\"\n\ncv2.namedWindow(\"TrackBars\")\ncv2.resizeWindow(\"TrackBars\",640,240)\ncv2.createTrackbar(\"Hue Min\",\"TrackBars\",0,179,empty)\ncv2.createTrackbar(\"Hue Max\",\"TrackBars\",19,179,empty)\ncv2.createTrackbar(\"Sat Min\",\"TrackBars\",110,255,empty)\ncv2.createTrackbar(\"Sat Max\",\"TrackBars\",240,255,empty)\ncv2.createTrackbar(\"Val Min\",\"TrackBars\",153,255,empty)\ncv2.createTrackbar(\"Val Max\",\"TrackBars\",255,255,empty)\n\nwhile True:\n img = cv2.imread(path)\n\n imgHSV = cv2.cv2.cvtColor(img,cv2.COLOR_BGR2HSV)\n h_min = cv2.getTrackbarPos(\"Hue Min\",\"TrackBars\")\n h_max = cv2.getTrackbarPos(\"Hue Max\",\"TrackBars\")\n s_min = cv2.getTrackbarPos(\"Sat Min\",\"TrackBars\")\n s_max = cv2.getTrackbarPos(\"Sat Max\",\"TrackBars\")\n v_min = cv2.getTrackbarPos(\"Val Min\",\"TrackBars\")\n v_max = cv2.getTrackbarPos(\"Val Max\",\"TrackBars\")\n print(h_min,h_max,s_min,s_max,v_min,v_max)\n\n lower = np.array([h_min,s_min,v_min])\n upper = np.array([h_max,s_max,v_max])\n mask = cv2.inRange(imgHSV,lower,upper)\n imgResult = cv2.bitwise_and(img,img,mask=mask)\n\n cv2.imshow(\"Original\",img)\n cv2.imshow(\"HSV\",imgHSV)\n cv2.imshow(\"Mask\",mask)\n cv2.imshow(\"Result\",imgResult)\n cv2.waitKey(1)" ]
[ [ "numpy.array" ] ]
aws-samples/aws-sagemaker-byoc-end2end
[ "86052e858c1333757a878e73c9067a0314b9918f" ]
[ "processing/create_dataset.py" ]
[ "import argparse\nimport pathlib\nimport json\nimport pandas as pd\nimport numpy as np\nimport os\n\n# Parse argument variables passed via the CreateDataset processing step\nparser = argparse.ArgumentParser()\nparser.add_argument(\"--athena-data\", type=str)\nargs = parser.parse_args()\n\ndataset = pd.read_parquet(args.athena_data, engine=\"pyarrow\")\ntrain = dataset[dataset[\"data_type\"]==\"train\"]\ntest = dataset.drop(train.index)\n\n# ####################################################################\n# Provide your own logics to generate train data!!!!!!!\n# ####################################################################\n\n\"\"\"\ntrain:\n pos:\n xxx.txt\n neg:\n xxx.txt\nval:\n pos:\n xxx.txt\n net:\n xxx.txt\n\"\"\"\n\ndef gen_train_val(df, save_dir):\n for index, row in df.iterrows():\n file_name = row[\"index\"]\n label = row[\"label\"]\n file_dir = save_dir / label\n if not os.path.exists(file_dir):\n os.makedirs(file_dir)\n \n with open(f\"{file_dir}/{file_name}.txt\", 'w') as f:\n f.write(row[\"text\"])\n\n# Write train, test splits to output path\ntrain_output_path = pathlib.Path(\"/opt/ml/processing/output/train\")\ntest_output_path = pathlib.Path(\"/opt/ml/processing/output/test\")\n#baseline_path = pathlib.Path(\"/opt/ml/processing/output/baseline\")\n\ngen_train_val(train, train_output_path)\ngen_train_val(test, test_output_path)\n\n# Save baseline with headers\n# train.to_csv(baseline_path / \"baseline.csv\", index=False, header=True) " ]
[ [ "pandas.read_parquet" ] ]
Jayanth-kumar5566/pyro
[ "a98bb57e1704997a3e01c76a7820c0b1db909ee3" ]
[ "examples/lkj.py" ]
[ "# Copyright (c) 2017-2019 Uber Technologies, Inc.\n# SPDX-License-Identifier: Apache-2.0\n\nimport argparse\n\nimport torch\n\nimport pyro\nimport pyro.distributions as dist\nfrom pyro.infer.mcmc import NUTS\nfrom pyro.infer.mcmc.api import MCMC\n\n\"\"\"\nThis simple example is intended to demonstrate how to use an LKJ prior with\na multivariate distribution.\n\nIt generates entirely random, uncorrelated data, and then attempts to fit a correlation matrix\nand vector of variances.\n\"\"\"\n\n\ndef model(y):\n d = y.shape[1]\n N = y.shape[0]\n options = dict(dtype=y.dtype, device=y.device)\n # Vector of variances for each of the d variables\n theta = pyro.sample(\"theta\", dist.HalfCauchy(torch.ones(d, **options)))\n # Lower cholesky factor of a correlation matrix\n concentration = torch.ones(\n (), **options\n ) # Implies a uniform distribution over correlation matrices\n L_omega = pyro.sample(\"L_omega\", dist.LKJCholesky(d, concentration))\n # Lower cholesky factor of the covariance matrix\n L_Omega = torch.mm(torch.diag(theta.sqrt()), L_omega)\n # For inference with SVI, one might prefer to use torch.bmm(theta.sqrt().diag_embed(), L_omega)\n\n # Vector of expectations\n mu = torch.zeros(d, **options)\n\n with pyro.plate(\"observations\", N):\n obs = pyro.sample(\"obs\", dist.MultivariateNormal(mu, scale_tril=L_Omega), obs=y)\n return obs\n\n\ndef main(args):\n y = torch.randn(args.n, args.num_variables).to(dtype=torch.double)\n if args.cuda:\n y = y.cuda()\n nuts_kernel = NUTS(model, jit_compile=False, step_size=1e-5)\n MCMC(\n nuts_kernel,\n num_samples=args.num_samples,\n warmup_steps=args.warmup_steps,\n num_chains=args.num_chains,\n ).run(y)\n\n\nif __name__ == \"__main__\":\n assert pyro.__version__.startswith(\"1.8.1\")\n parser = argparse.ArgumentParser(description=\"Demonstrate the use of an LKJ Prior\")\n parser.add_argument(\"--num-samples\", nargs=\"?\", default=200, type=int)\n parser.add_argument(\"--n\", nargs=\"?\", default=500, type=int)\n parser.add_argument(\"--num-chains\", nargs=\"?\", default=4, type=int)\n parser.add_argument(\"--num-variables\", nargs=\"?\", default=5, type=int)\n parser.add_argument(\"--warmup-steps\", nargs=\"?\", default=100, type=int)\n parser.add_argument(\"--rng_seed\", nargs=\"?\", default=0, type=int)\n parser.add_argument(\"--cuda\", action=\"store_true\", default=False)\n args = parser.parse_args()\n\n pyro.set_rng_seed(args.rng_seed)\n # Enable validation checks\n\n # work around with the error \"RuntimeError: received 0 items of ancdata\"\n # see https://discuss.pytorch.org/t/received-0-items-of-ancdata-pytorch-0-4-0/19823\n torch.multiprocessing.set_sharing_strategy(\"file_system\")\n\n main(args)\n" ]
[ [ "torch.zeros", "torch.randn", "torch.multiprocessing.set_sharing_strategy", "torch.ones" ] ]
takehuge/PYQUM
[ "bfc9d9b1c2f4246c7aac3a371baaf587c99f8069" ]
[ "TEST/FACE/pyqum/instrument/machine/TKAWG.py" ]
[ "# Communicating with Benchtop TKAWG (Tektronix AWG)\nfrom colorama import init, Fore, Back\ninit(autoreset=True) #to convert termcolor to wins color\n\nfrom os.path import basename as bs\nmdlname = bs(__file__).split('.')[0] # module's name e.g. PSG\n\nimport pyvisa as visa\nfrom pyqum.instrument.logger import address, set_status, status_code, debug\nfrom pyqum.instrument.logger import translate_scpi as Attribute\nfrom numpy import array, zeros, ceil, where, floor\nimport array as arr\n\nfrom pyqum.instrument.toolbox import normalize_dipeak\nfrom pyqum.instrument.composer import pulser\nfrom time import sleep\ndebugger = debug(mdlname)\n\n# INITIALIZATION\ndef Initiate(which, mode='DATABASE'):\n ad = address(mode)\n rs = ad.lookup(mdlname, which) # Instrument's Address\n rm = visa.ResourceManager()\n try:\n bench = rm.open_resource(rs) #establishing connection using GPIB# with the machine\n stat = bench.write('*ESR?') # serve to check connection availibility\n bench.read_termination = '\\n' #omit termination tag from output \n bench.timeout = 150000 #set timeout in ms\n set_status(mdlname, dict(state='connected'), which)\n print(Fore.GREEN + \"%s-%s's connection Initialized: %s\" % (mdlname,which, str(stat)))\n ad.update_machine(1, \"%s_%s\"%(mdlname,which))\n except: \n set_status(mdlname, dict(state='DISCONNECTED'), which)\n print(Fore.RED + \"%s-%s's connection NOT FOUND\" %(mdlname,which))\n # bench = \"disconnected\"\n return bench\n\n@Attribute\ndef model(bench, action=['Get', '']):\n SCPIcore = '*IDN' #inquiring machine identity: \"who r u?\"\n return mdlname, bench, SCPIcore, action\n@Attribute\ndef ready(bench, action=['Get', '']):\n SCPIcore = '*OPC' #inquiring machine: \"r u ready?\"\n return mdlname, bench, SCPIcore, action\n\n@Attribute\ndef clock(bench, action=['Get'] + 10 * ['']):\n '''\n Source:\n INTernal - Clock signal is generated internally and the reference frequency is derived from the internal oscillator. \n EFIXed – Clock is generated internally and the reference frequency is derived from a fixed 10MHz reference supplied at the Reference-In connector. \n EVARiable – Clock is generated internally and the reference frequency is derived from a variable reference supplied at the Reference-In connector. \n EXTernal – Clock signal supplied by the Clock In connector. The reference frequency is deactivated. \n *RST sets this to INT.\n Rate:\n Range: 298 S/s to 2.5 G/s (option-25), 298 S/s to 5 G/s (option-50)\n *RST sets this to the maximum value.\n '''\n SCPIcore = 'CLOCk:SOURce;SRATe'\n return mdlname, bench, SCPIcore, action\n\n@Attribute\ndef waveformlist(bench, action=['Get']):\n '''\n Most Recent, A List of, Size of Waveform-list (Query ONLY)\n '''\n SCPIcore = 'WLISt:LAST;LIST;SIZE'\n action += 10 * [''] # for multiple parameters\n return mdlname, bench, SCPIcore, action\n@Attribute\ndef waveformpick(bench, action=['Get']):\n '''\n This command returns the waveform name from the waveform list at the position specified by the index value. (Query ONLY)\n '''\n SCPIcore = 'WLISt:NAME'\n action += 10 * [''] # for multiple parameters\n return mdlname, bench, SCPIcore, action\n\n@Attribute\ndef outputpath(bench, channel, action=['Get'] + 10 * ['']):\n '''This command sets or returns the output path of the specified channel.\n Path: DCHB (DC High Bandwidth), DCHV (DC High Voltage), ACD (AC Direct), ACAM (AC Amplified)\n '''\n SCPIcore = 'OUTPUT%s:PATH' %channel\n return mdlname, bench, SCPIcore, action\n@Attribute\ndef output(bench, channel, action=['Get'] + 10 * ['']):\n '''This command sets or returns the output state of the specified channel.\n '''\n SCPIcore = 'OUTPUT%s:STATE' %channel\n return mdlname, bench, SCPIcore, action\n@Attribute\ndef alloff(bench, action=['Get'] + 10 * ['']):\n '''This command sets or returns the state (enabled or disabled) of the 'All Outputs Off' control.\n '''\n SCPIcore = 'OUTPUT:OFF'\n return mdlname, bench, SCPIcore, action\n@Attribute\ndef sourcelevel(bench, channel, action=['Get'] + 10 * ['']):\n '''This command sets or returns the amplitude and offset for the waveform associated with the specified channel. \n '''\n SCPIcore = 'SOURCE%s:VOLTAGE:LEVEL:IMMEDIATE:AMPLITUDE;OFFSET' %channel\n return mdlname, bench, SCPIcore, action\n@Attribute\ndef sourceresolution(bench, channel, action=['Get'] + 10 * ['']):\n '''This command sets or returns the DAC resolution. \n 16(12) indicates 16 bit DAC Resolution + 0(4) Marker bits. \n '''\n SCPIcore = 'SOURCE%s:DAC:RESOLUTION' %channel\n return mdlname, bench, SCPIcore, action\n@Attribute\ndef markerdelay(bench, channel, marker, action=['Get'] + 10 * ['']):\n '''This command sets or returns the delay for the specified marker of the specified channel. \n Marker delay is independent for each channel. Range: –3 ns to 3 ns \n *RST sets all channel marker delays to 0.\n '''\n SCPIcore = 'SOURCE%s:MARKER%s:DELAY' %(channel,marker)\n return mdlname, bench, SCPIcore, action\n@Attribute\ndef runmode(bench, channel, action=['Get'] + 10 * ['']):\n '''This command sets or returns the run-mode of the specified channel:\n [SOURce[n]:]RMODe {CONTinuous|TRIGgered|TCONtinuous|GATed}\n '''\n SCPIcore = 'SOURCE%s:RMODE' %channel\n return mdlname, bench, SCPIcore, action\n@Attribute\ndef runstate(bench, action=['Get'] + 10 * ['']):\n '''This command returns the run-state of the AWG. (Query ONLY)\n 0 indicates that the AWG has stopped. \n 1 indicates that the AWG is waiting for trigger. \n 2 indicates that the AWG is running.\n '''\n SCPIcore = 'AWGCONTROL:RSTATE'\n return mdlname, bench, SCPIcore, action\n\n@Attribute\ndef testscpi(bench, action=['Get', '']):\n '''TEST SCPI CODE'''\n # SCPIcore = 'WLISt:LIST'\n SCPIcore = 'OUTPUT1:STATE'\n return mdlname, bench, SCPIcore, action\n\n# Handling Waveforms:\ndef initwaveform(bench,name,size):\n '''Initialize waveform with its name and length'''\n status = bench.write('WLIST:WAVEFORM:NEW \"%s\",%s,REAL' %(name,size))\n return status\ndef create_waveform(bench,name,data,startindex=0):\n '''This command has a limit of 999,999,999 bytes of data (~49ms of single playtime per waveform given max sampling rate). \n The IEEE 488.2 limits that the largest read or write that may occur in a single command is 999,999,999 bytes. \n Because of the size limitation, it is suggested that the user make use of the starting index (and size for querying) to append data in multiple commands/queries. \n '''\n try: \n # bench.write_binary_values('WLIST:WAVEFORM:DATA \"%s\",%s,%s,'%(name,startindex,size), data, datatype='d', is_big_endian=False) # Old way\n # Prepare the data block from data array:\n wavebytes = arr.array('f', array(data).astype('float32')).tobytes() # use 32-bit or 4-Byte floating numbers\n # Assemble SCPI command:\n bytesize = len(wavebytes)\n command = ('WLISt:WAVeform:DATA \"{}\",{},{},'.format(name,startindex,bytesize//4)).encode('UTF-8')\n header = ('#' + str(len(str(bytesize))) + str(bytesize)).encode('UTF-8')\n # Send to machine:\n status = bench.write_raw(command + header + wavebytes)\n except: \n # raise \n print(\"Check waveform again?\")\n # print(status)\n return status\ndef create_markers(bench,name,channel,marker,data,startindex=0):\n '''This command sets or returns the waveform marker data.\n This command has a limit of 999,999,999 bytes of data. \n The marker arrays must contain only 1's and 0's.\n Each marker data occupies one bit. Four most significant bits of each byte are used for markers. \n Bit 7 for marker 1 and bit 6 for marker 2, bit 5 for marker 3, and bit 4 for marker 4.\n You will have to use bit masks to obtain the actual value. \n When used on a waveform with n data points, you get only n bytes, each byte having values for both markers. \n data: concatenated array of all activated markers.\n '''\n try: \n # Adjust DAC resolution to accomadate more markers:\n sourceresolution(bench, channel, action=['Set',16-int(marker)])\n # Masking marker: (for multiple markers)\n DATA = zeros(int(len(data)/marker)) # masked marker array\n data = array(data).reshape(marker,int(len(data)/marker))\n for mkr in range(marker):\n # print(Fore.GREEN + \"Byte-Shift data of %s into DATA of %s.\" %(str(data[mkr].shape), str(DATA.shape)))\n DATA += array(data[mkr]) * 2**(8-int(mkr+1)) # Bit 7 for marker 1, bit 6 for marker 2, bit 5 for marker 3, bit 4 for marker 4.\n # Prepare the data block from data array:\n markerbytes = arr.array('B', DATA.astype('uint8')).tobytes() # use 8-bit or 1-Byte integer numbers\n # Assemble SCPI command:\n bytesize = len(markerbytes) # must be the same length with waveform\n command = ('WLIST:WAVEFORM:MARKER:DATA \"{}\",{},{},'.format(name,startindex,bytesize)).encode('UTF-8')\n header = ('#' + str(len(str(bytesize))) + str(bytesize)).encode('UTF-8')\n # Send to machine:\n status = bench.write_raw(command + header + markerbytes)\n except: \n # raise \n print(\"Check marker again?\")\n # print(command + header + markerbytes)\n return status\ndef assign_waveform(bench,name,channel):\n status = bench.write('SOURCE%s:CASSET:WAVEFORM \"%s\"' %(channel,name))\n return status\ndef normalize_waveform(bench,name):\n '''This command normalizes a waveform in the waveform list.\n '''\n bench.write('WLIST:WAVEFORM:NORMALIZE \"%s\",ZREFerence' %(name))\n status = bench.query('*OPC?')\n return status\ndef clear_waveform(bench,name):\n if name.lower() == 'all':\n status = bench.write('WLIST:WAVEFORM:DELETE ALL')\n else: status = bench.write('WLIST:WAVEFORM:DELETE \"%s\"' %name)\n return status\n\ndef play(bench):\n try:\n status = bench.write('AWGCONTROL:RUN:IMMEDIATE') # Playing\n set_status(mdlname, dict(play='yes'))\n except: set_status(mdlname, dict(play='error'))\n return status\ndef stop(bench):\n try:\n status = bench.write('AWGCONTROL:STOP:IMMEDIATE') # Stop Playing\n set_status(mdlname, dict(play='no'))\n except: set_status(mdlname, dict(play='error'))\n return status\n\ndef close(bench, which, reset=True, mode='DATABASE'):\n if reset:\n bench.write('*RST') # reset to factory setting (including switch-off)\n set_status(mdlname, dict(config='reset'), which)\n else: set_status(mdlname, dict(config='previous'), which)\n try:\n bench.close() #None means Success?\n status = \"Success\"\n ad = address(mode)\n ad.update_machine(0, \"%s_%s\"%(mdlname,which))\n except: status = \"Error\"\n set_status(mdlname, dict(state='disconnected with %s' %status), which)\n print(Back.WHITE + Fore.BLACK + \"%s's connection Closed with %s\" %(mdlname,status))\n return status\n\n# Composite functions for directives:\ndef prepare_DAC(bench, channel, datasize, maxlevel=1.5, update_settings={}):\n initwaveform(bench, \"Waveform-%s\"%channel, datasize)\n normalize_waveform(bench, \"Waveform-%s\"%channel)\n runmode(bench, channel, action=['Set','CONT'])\n sourcelevel(bench, channel, action=['Set',maxlevel,0])\n outputpath(bench, channel, action=['Set','DCHB'])\n return bench\ndef compose_DAC(bench, channel, pulsedata, envelope=[], marker=0, update_settings={}):\n # MUST Create waveform before markers:\n create_waveform(bench, \"Waveform-%s\"%channel, pulsedata)\n if marker-1 in range(4): # only 1-4 is valid\n mkr_array = zeros(len(pulsedata))\n # automated marker array based solely on pulse-data (considered: global offset):\n if not channel%2: # EVEN-Channel: Making sure marker-width is finite & less than pulse-length since it is for TRIGGER PURPOSES ONLY:\n try: # pulse case\n shrinkage = 3\n first_rising_edge, last_falling_edge = where(ceil(abs(pulsedata-pulsedata[-1]))==1)[0][0], where(ceil(abs(pulsedata-pulsedata[-1]))==1)[0][-1]\n last_falling_edge = first_rising_edge + int(ceil((last_falling_edge - first_rising_edge)/shrinkage))\n except: # CW case\n first_rising_edge, last_falling_edge = 0, 300\n mkr_array[first_rising_edge : last_falling_edge] = 1\n else: # ODD-Channel: for DRIVING PIN-SWITCH:\n if len(envelope): \n mkr_array = abs(normalize_dipeak(envelope))\n create_markers(bench, \"Waveform-%s\"%channel, channel, marker, array(list(mkr_array)*marker))\n else:\n sourceresolution(bench, channel, action=['Set',16])\n assign_waveform(bench, \"Waveform-%s\"%channel, channel)\n ready(bench)\n output(bench, channel, action=['Set','ON'])\n return bench\n\n# Test Zone: (Embedded in UI, thus excluded from TESTALL)\ndef test(bench, detail=True):\n s = bench #Initiate(1)\n if s == \"disconnected\":\n pass\n else:\n if debug(mdlname, detail):\n print(Fore.RED + \"Detailed Test:\")\n model(s)\n clock(s)\n waveformlist(s)\n # waveformpick(s, action=['Get','0'])\n\n # To be put in directives:\n ch = [1,2,3,4]\n # clock(s, action=['Set', 'EFIXed', 2.5e9])\n clear_waveform(s,'all')\n alloff(s, action=['Set',1])\n\n dt = 0.4\n wavelength = 20000 # points\n # Prepare all channels:\n for i in range(4):\n prepare_DAC(s, ch[i], wavelength)\n\n # Compose songs for each channel:\n song1 = pulser(dt, 1, score='ns=%s;GAUSS UP/,250,0.3;GAUSS DN/,250,0.3;'%(wavelength*dt))\n song1.song()\n song2 = pulser(dt, 1, score='ns=%s;Flat,0,0'%(wavelength*dt))\n song2.song()\n song3 = pulser(dt, 1, score='ns=%s;Flat,800,0.5'%(wavelength*dt))\n song3.song()\n song4 = pulser(dt, 1, score='ns=%s;Flat,0,0'%(wavelength*dt))\n song4.song()\n\n # Inject each song into respective channels:\n compose_DAC(s, ch[0], song1.music, 1, 200)\n compose_DAC(s, ch[1], song2.music)\n compose_DAC(s, ch[2], song3.music, 1, 200)\n compose_DAC(s, ch[3], song4.music)\n \n alloff(s, action=['Set',0])\n ready(s)\n print(\"Play: %s\" %str(play(s)))\n\n # Changing waveform on the fly:\n sleep(3)\n song1 = pulser(dt, 1, score='ns=%s;GAUSS UP/,350,0.3;GAUSS DN/,350,0.3;'%(wavelength*dt))\n song1.song()\n compose_DAC(s, ch[0], song1.music, 1, 200)\n sleep(3)\n song1 = pulser(dt, 1, score='ns=%s;GAUSS UP/,200,0.3;Flat,300,0.3;GAUSS DN/,200,0.3;'%(wavelength*dt))\n song1.song()\n compose_DAC(s, ch[0], song1.music, 1, 200)\n\n # ch = 3\n # runmode(s, ch)\n # output(s, ch)\n # sourcelevel(s, ch)\n # sourceresolution(s, ch)\n # runstate(s)\n\n else: print(Fore.RED + \"Basic IO Test\")\n # if not bool(input(\"Press ENTER (OTHER KEY) to (skip) reset: \")):\n # state = True\n # else: state = False\n # close(s, reset=reset)\n return \"Success\"\n\n# test()" ]
[ [ "numpy.array", "numpy.ceil" ] ]
sculmh/pytorch-deeplab-xception
[ "4dd5e16a389cf686aa61b4c640eb68c1ff1f97d0" ]
[ "modeling/backbone/xception_gn.py" ]
[ "# -*- coding: utf-8 -*-\nimport math\nimport torch.nn as nn\nimport torch.nn.functional as F\n\n\ndef fixed_padding(inputs, kernel_size, dilation):\n kernel_size_effective = kernel_size + (kernel_size - 1) * (dilation - 1)\n pad_total = kernel_size_effective - 1\n pad_beg = pad_total // 2\n pad_end = pad_total - pad_beg\n padded_inputs = F.pad(inputs, (pad_beg, pad_end, pad_beg, pad_end))\n return padded_inputs\n\n\nclass SeparableConv2d(nn.Module):\n def __init__(self, inplanes, planes, kernel_size=3, stride=1, dilation=1, bias=False, groups=32):\n super(SeparableConv2d, self).__init__()\n\n self.conv1 = nn.Conv2d(inplanes, inplanes, kernel_size, stride, 0, dilation,\n groups=inplanes, bias=bias)\n self.gn = nn.GroupNorm(groups, inplanes, affine=True)\n self.pointwise = nn.Conv2d(inplanes, planes, 1, 1, 0, 1, 1, bias=bias)\n\n def forward(self, x):\n x = fixed_padding(x, self.conv1.kernel_size[0], dilation=self.conv1.dilation[0])\n x = self.conv1(x)\n x = self.gn(x)\n x = self.pointwise(x)\n return x\n\n\nclass Block(nn.Module):\n def __init__(self, inplanes, planes, reps, stride=1, dilation=1, groups=32,\n start_with_relu=True, grow_first=True, is_last=False):\n super(Block, self).__init__()\n\n if planes != inplanes or stride != 1:\n self.skip = nn.Conv2d(inplanes, planes, 1, stride=stride, bias=False)\n self.skipgn = nn.GroupNorm(groups, planes, affine=True)\n else:\n self.skip = None\n\n self.relu = nn.ReLU(inplace=True)\n rep = []\n\n filters = inplanes\n if grow_first:\n rep.append(self.relu)\n rep.append(SeparableConv2d(inplanes, planes, 3, 1, dilation, groups=groups))\n rep.append(nn.GroupNorm(groups, planes, affine=True))\n filters = planes\n\n for i in range(reps - 1):\n rep.append(self.relu)\n rep.append(SeparableConv2d(filters, filters, 3, 1, dilation, groups=groups))\n rep.append(nn.GroupNorm(groups, filters, affine=True))\n\n if not grow_first:\n rep.append(self.relu)\n rep.append(SeparableConv2d(inplanes, planes, 3, 1, dilation, groups=groups))\n rep.append(nn.GroupNorm(groups, planes, affine=True))\n\n if stride != 1:\n rep.append(self.relu)\n rep.append(SeparableConv2d(planes, planes, 3, 2, groups=groups))\n rep.append(nn.GroupNorm(groups, planes, affine=True))\n\n if stride == 1 and is_last:\n rep.append(self.relu)\n rep.append(SeparableConv2d(planes, planes, 3, 1, groups=groups))\n rep.append(nn.GroupNorm(groups, planes, affine=True))\n\n if not start_with_relu:\n rep = rep[1:]\n\n self.rep = nn.Sequential(*rep)\n\n def forward(self, inp):\n x = self.rep(inp)\n\n if self.skip is not None:\n skip = self.skip(inp)\n skip = self.skipgn(skip)\n else:\n skip = inp\n\n x = x + skip\n\n return x\n\n\nclass AlignedXception_GN(nn.Module):\n \"\"\"\n Modified Alighed Xception\n \"\"\"\n def __init__(self, output_stride, groups):\n super(AlignedXception_GN, self).__init__()\n\n if output_stride == 16:\n entry_block3_stride = 2\n middle_block_dilation = 1\n exit_block_dilations = (1, 2)\n elif output_stride == 8:\n entry_block3_stride = 1\n middle_block_dilation = 2\n exit_block_dilations = (2, 4)\n else:\n raise NotImplementedError\n\n # Entry flow\n self.conv1 = nn.Conv2d(3, 32, 3, stride=2, padding=1, bias=False)\n self.gn1 = nn.GroupNorm(groups, 32, affine=True)\n self.relu = nn.ReLU(inplace=True)\n\n self.conv2 = nn.Conv2d(32, 64, 3, stride=1, padding=1, bias=False)\n self.gn2 = nn.GroupNorm(groups, 64, affine=True)\n\n self.block1 = Block(64, 128, reps=2, stride=2, groups=groups, start_with_relu=False)\n self.block2 = Block(128, 256, reps=2, stride=2, groups=groups, start_with_relu=False,\n grow_first=True)\n self.block3 = Block(256, 736, reps=2, stride=entry_block3_stride, groups=groups,\n start_with_relu=True, grow_first=True, is_last=True)\n\n # Middle flow\n self.block4 = Block(736, 736, reps=3, stride=1, dilation=middle_block_dilation,\n groups=groups, start_with_relu=True, grow_first=True)\n self.block5 = Block(736, 736, reps=3, stride=1, dilation=middle_block_dilation,\n groups=groups, start_with_relu=True, grow_first=True)\n self.block6 = Block(736, 736, reps=3, stride=1, dilation=middle_block_dilation,\n groups=groups, start_with_relu=True, grow_first=True)\n self.block7 = Block(736, 736, reps=3, stride=1, dilation=middle_block_dilation,\n groups=groups, start_with_relu=True, grow_first=True)\n self.block8 = Block(736, 736, reps=3, stride=1, dilation=middle_block_dilation,\n groups=groups, start_with_relu=True, grow_first=True)\n self.block9 = Block(736, 736, reps=3, stride=1, dilation=middle_block_dilation,\n groups=groups, start_with_relu=True, grow_first=True)\n self.block10 = Block(736, 736, reps=3, stride=1, dilation=middle_block_dilation,\n groups=groups, start_with_relu=True, grow_first=True)\n self.block11 = Block(736, 736, reps=3, stride=1, dilation=middle_block_dilation,\n groups=groups, start_with_relu=True, grow_first=True)\n self.block12 = Block(736, 736, reps=3, stride=1, dilation=middle_block_dilation,\n groups=groups, start_with_relu=True, grow_first=True)\n self.block13 = Block(736, 736, reps=3, stride=1, dilation=middle_block_dilation,\n groups=groups, start_with_relu=True, grow_first=True)\n self.block14 = Block(736, 736, reps=3, stride=1, dilation=middle_block_dilation,\n groups=groups, start_with_relu=True, grow_first=True)\n self.block15 = Block(736, 736, reps=3, stride=1, dilation=middle_block_dilation,\n groups=groups, start_with_relu=True, grow_first=True)\n self.block16 = Block(736, 736, reps=3, stride=1, dilation=middle_block_dilation,\n groups=groups, start_with_relu=True, grow_first=True)\n self.block17 = Block(736, 736, reps=3, stride=1, dilation=middle_block_dilation,\n groups=groups, start_with_relu=True, grow_first=True)\n self.block18 = Block(736, 736, reps=3, stride=1, dilation=middle_block_dilation,\n groups=groups, start_with_relu=True, grow_first=True)\n self.block19 = Block(736, 736, reps=3, stride=1, dilation=middle_block_dilation,\n groups=groups, start_with_relu=True, grow_first=True)\n\n # Exit flow\n self.block20 = Block(736, 1024, reps=2, stride=1, dilation=exit_block_dilations[0],\n groups=groups, start_with_relu=True, grow_first=False, is_last=True)\n\n self.conv3 = SeparableConv2d(1024, 1536, 3, stride=1, dilation=exit_block_dilations[1], groups=groups)\n self.gn3 = nn.GroupNorm(groups, 1536, affine=True)\n\n self.conv4 = SeparableConv2d(1536, 1536, 3, stride=1, dilation=exit_block_dilations[1], groups=groups)\n self.gn4 = nn.GroupNorm(groups, 1536, affine=True)\n\n self.conv5 = SeparableConv2d(1536, 2048, 3, stride=1, dilation=exit_block_dilations[1], groups=groups)\n self.gn5 = nn.GroupNorm(groups, 2048, affine=True)\n\n # Init weights\n self._init_weight()\n\n def forward(self, x):\n # Entry flow\n x = self.conv1(x)\n x = self.gn1(x)\n x = self.relu(x)\n\n x = self.conv2(x)\n x = self.gn2(x)\n x = self.relu(x)\n\n x = self.block1(x)\n # add relu here\n x = self.relu(x)\n low_level_feat = x\n x = self.block2(x)\n x = self.block3(x)\n\n # Middle flow\n x = self.block4(x)\n x = self.block5(x)\n x = self.block6(x)\n x = self.block7(x)\n x = self.block8(x)\n x = self.block9(x)\n x = self.block10(x)\n x = self.block11(x)\n x = self.block12(x)\n x = self.block13(x)\n x = self.block14(x)\n x = self.block15(x)\n x = self.block16(x)\n x = self.block17(x)\n x = self.block18(x)\n x = self.block19(x)\n\n # Exit flow\n x = self.block20(x)\n x = self.relu(x)\n x = self.conv3(x)\n x = self.gn3(x)\n x = self.relu(x)\n\n x = self.conv4(x)\n x = self.gn4(x)\n x = self.relu(x)\n\n x = self.conv5(x)\n x = self.gn5(x)\n x = self.relu(x)\n\n return x, low_level_feat\n\n def _init_weight(self):\n for m in self.modules():\n if isinstance(m, nn.Conv2d):\n n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels\n m.weight.data.normal_(0, math.sqrt(2. / n))\n # nn.init.kaiming_normal_(m.weight)\n\n\nif __name__ == \"__main__\":\n import torch\n model = AlignedXception_GN(groups=32, output_stride=16)\n input = torch.rand(1, 3, 512, 512)\n output, low_level_feat = model(input)\n print(output.size())\n print(low_level_feat.size())\n" ]
[ [ "torch.rand", "torch.nn.Sequential", "torch.nn.GroupNorm", "torch.nn.ReLU", "torch.nn.Conv2d", "torch.nn.functional.pad" ] ]
Jeffrey-Ede/adaptive-scans
[ "a4f8f0275d5f894c34f7ae9bbd64222f635fb73e" ]
[ "dnc/dnc.py" ]
[ "# Copyright 2017 Google Inc.\r\n#\r\n# Licensed under the Apache License, Version 2.0 (the \"License\");\r\n# you may not use this file except in compliance with the License.\r\n# You may obtain a copy of the License at\r\n#\r\n# http://www.apache.org/licenses/LICENSE-2.0\r\n#\r\n# Unless required by applicable law or agreed to in writing, software\r\n# distributed under the License is distributed on an \"AS IS\" BASIS,\r\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n# See the License for the specific language governing permissions and\r\n# limitations under the License.\r\n# ==============================================================================\r\n\"\"\"DNC Cores.\r\n\r\nThese modules create a DNC core. They take input, pass parameters to the memory\r\naccess module, and integrate the output of memory to form an output.\r\n\"\"\"\r\n\r\nfrom __future__ import absolute_import\r\nfrom __future__ import division\r\nfrom __future__ import print_function\r\n\r\nimport collections\r\nimport numpy as np\r\nimport sonnet as snt\r\nimport tensorflow as tf\r\n\r\nfrom dnc import access\r\n\r\nfrom utility import auto_name\r\n\r\nFLAGS = tf.flags.FLAGS\r\n\r\n\r\nDNCState = collections.namedtuple('DNCState', ('access_output', 'access_state',\r\n 'controller_state', 'output', \r\n 'position', 'noise'))\r\n\r\nclass Components(snt.AbstractModule):\r\n\r\n def __init__(self,\r\n access_config,\r\n controller_config,\r\n output_size,\r\n name='components'\r\n ):\r\n \"\"\"Initializes the DNC core.\r\n\r\n Args:\r\n access_config: dictionary of access module configurations.\r\n controller_config: dictionary of controller (LSTM) module configurations.\r\n output_size: output dimension size of core.\r\n clip_value: clips controller and core output values to between\r\n `[-clip_value, clip_value]` if specified.\r\n name: module name (default 'dnc').\r\n\r\n Raises:\r\n TypeError: if direct_input_size is not None for any access module other\r\n than KeyValueMemory.\r\n \"\"\"\r\n super(Components, self).__init__(name=name)\r\n\r\n\r\n with self._enter_variable_scope():\r\n self.controller = snt.DeepRNN([snt.LSTM(**controller_config) for _ in range(FLAGS.lstm_depth)], skip_connections=True)\r\n #self.controller = snt.LSTM(**controller_config)\r\n self.access = access.MemoryAccess(**access_config)\r\n\r\n self.output_linear = snt.Linear(output_size=output_size, use_bias=False)\r\n\r\n if FLAGS.is_input_embedder:\r\n self.input_embedder = snt.Sequential([\r\n snt.Linear(output_size=64, use_bias=True),\r\n tf.nn.tanh\r\n ])\r\n\r\n if FLAGS.is_variable_initial_states:\r\n def c_fn(x):\r\n shape = x.get_shape().as_list()\r\n y = tf.Variable(initial_value=tf.zeros(shape=[1]+shape[1:]), dtype=tf.float32, trainable=True)\r\n return y\r\n self.initial_controller_state = tf.contrib.framework.nest.map_structure(\r\n c_fn, self.controller.initial_state(1, tf.float32))\r\n\r\n def _build(self):\r\n return\r\n\r\nclass DNC(snt.RNNCore):\r\n \"\"\"DNC core module.\r\n\r\n Contains controller and memory access module.\r\n \"\"\"\r\n\r\n def __init__(self,\r\n components,\r\n output_size,\r\n clip_value=None,\r\n is_new=False,\r\n noise_decay=None,\r\n is_double_critic=False,\r\n sampled_full_scans=None,\r\n is_noise=False,\r\n is_actor=True,\r\n name='dnc'\r\n ):\r\n \"\"\"Initializes the DNC core.\r\n\r\n Args:\r\n access_config: dictionary of access module configurations.\r\n controller_config: dictionary of controller (LSTM) module configurations.\r\n output_size: output dimension size of core.\r\n clip_value: clips controller and core output values to between\r\n `[-clip_value, clip_value]` if specified.\r\n name: module name (default 'dnc').\r\n\r\n Raises:\r\n TypeError: if direct_input_size is not None for any access module other\r\n than KeyValueMemory.\r\n \"\"\"\r\n super(DNC, self).__init__(name=name)\r\n\r\n with self._enter_variable_scope():\r\n self._controller = components.controller\r\n self._access = components.access\r\n\r\n self._batch_flatten = snt.BatchFlatten()\r\n\r\n self._output_linear = components.output_linear\r\n\r\n if FLAGS.is_input_embedder:\r\n self._input_embedder = components.input_embedder\r\n\r\n if FLAGS.is_variable_initial_states:\r\n self._initial_controller_state = components.initial_controller_state\r\n\r\n self._access_output_size = np.prod(self._access.output_size.as_list())\r\n self._output_size_features = output_size\r\n self._clip_value = clip_value or 0\r\n\r\n self._state_size = DNCState(\r\n access_output=self._access_output_size,\r\n access_state=self._access.state_size,\r\n controller_state=self._controller.state_size,\r\n output=tf.TensorShape([output_size]),\r\n position=tf.TensorShape([output_size]),\r\n noise=tf.TensorShape([1]))\r\n\r\n if is_new:\r\n self._output_size = tf.TensorShape([FLAGS.step_size+FLAGS.num_actions])\r\n self._full_scans = sampled_full_scans\r\n elif is_double_critic:\r\n self._output_size = tf.TensorShape([2*output_size])\r\n else:\r\n self._output_size = tf.TensorShape([output_size])\r\n\r\n self._is_new = is_new\r\n\r\n self._is_noise = is_noise\r\n\r\n self._noise_decay = noise_decay\r\n \r\n self._is_actor = is_actor\r\n\r\n self.first = True\r\n\r\n\r\n def _clip_if_enabled(self, x):\r\n if self._clip_value > 0:\r\n return tf.clip_by_value(x, -self._clip_value, self._clip_value)\r\n else:\r\n return x\r\n\r\n def _build(self, inputs, prev_state):\r\n \"\"\"Connects the DNC core into the graph.\r\n\r\n Args:\r\n inputs: Tensor input.\r\n prev_state: A `DNCState` tuple containing the fields `access_output`,\r\n `access_state` and `controller_state`. `access_state` is a 3-D Tensor\r\n of shape `[batch_size, num_reads, word_size]` containing read words.\r\n `access_state` is a tuple of the access module's state, and\r\n `controller_state` is a tuple of controller module's state.\r\n\r\n Returns:\r\n A tuple `(output, next_state)` where `output` is a tensor and `next_state`\r\n is a `DNCState` tuple containing the fields `access_output`,\r\n `access_state`, and `controller_state`.\r\n \"\"\"\r\n\r\n prev_access_output = prev_state.access_output\r\n prev_access_state = prev_state.access_state\r\n prev_controller_state = prev_state.controller_state\r\n prev_output = prev_state.output\r\n prev_position = prev_state.position\r\n prev_noise = prev_state.noise\r\n\r\n if FLAGS.is_variable_initial_states and self.first:\r\n self.first = False\r\n def c_fn(x):\r\n shape = x.get_shape().as_list()\r\n y = tf.tile(x, prev_output.get_shape().as_list()[0:1] + [1 for _ in shape[1:]])\r\n return y\r\n prev_controller_state = tf.contrib.framework.nest.map_structure(\r\n c_fn, self._initial_controller_state)\r\n\r\n if FLAGS.is_prev_position_input:\r\n prev_position = tf.stop_gradient(prev_position) # Gotta catch 'em all\r\n\r\n if FLAGS.model == \"DNC\":\r\n neural_machine = self._neural_machine\r\n elif FLAGS.model == \"LSTM\":\r\n neural_machine = self._neural_machine2\r\n\r\n extra_tiled_actions = []\r\n if self._is_new:\r\n actions = prev_output\r\n observations = self.obs(actions, prev_position)\r\n else:\r\n actions = inputs[:,FLAGS.step_size:FLAGS.step_size+FLAGS.num_actions]\r\n observations = inputs[:,:FLAGS.step_size]\r\n\r\n new_actions = inputs[:,FLAGS.step_size+FLAGS.num_actions:FLAGS.step_size+2*FLAGS.num_actions]\r\n\r\n if FLAGS.is_prev_position_input:\r\n scaled_prev_position = (FLAGS.img_side/FLAGS.step_size)*prev_position\r\n if not self._is_actor and not FLAGS.is_advantage_actor_critic: #If critic\r\n new_actions = tf.concat([new_actions, scaled_prev_position], axis=-1)\r\n else: #If not critic\r\n new_actions = scaled_prev_position\r\n\r\n if FLAGS.is_immediate_critic_loss and not self._is_actor:\r\n hidden_output, _, _, _ = neural_machine(\r\n observations=observations,\r\n actions=new_actions,\r\n prev_controller_state=tf.contrib.framework.nest.map_structure(tf.stop_gradient, prev_controller_state),\r\n prev_access_output=tf.contrib.framework.nest.map_structure(tf.stop_gradient, prev_access_output),\r\n prev_access_state=tf.contrib.framework.nest.map_structure(tf.stop_gradient, prev_access_state)\r\n )\r\n else:\r\n hidden_output, _, _, _ = neural_machine(\r\n observations=observations,\r\n actions=new_actions,\r\n prev_controller_state=prev_controller_state,\r\n prev_access_output=prev_access_output,\r\n prev_access_state=prev_access_state\r\n )\r\n\r\n if FLAGS.num_actions == 2:\r\n position = prev_position + FLAGS.step_size*actions/FLAGS.img_side\r\n elif FLAGS.num_actions == 1:\r\n cartesian_actions = FLAGS.step_incr*tf.concat([tf.cos(actions), tf.sin(actions)], axis=-1)\r\n position = prev_position + FLAGS.step_size*cartesian_actions/FLAGS.img_side\r\n\r\n if FLAGS.is_prev_position_input:\r\n scaled_prev_position = (FLAGS.img_side/FLAGS.step_size)*prev_position\r\n if not self._is_actor and not FLAGS.is_advantage_actor_critic: #If critic\r\n actions = tf.concat([actions, scaled_prev_position], axis=-1)\r\n else: #If not critic\r\n actions = scaled_prev_position\r\n\r\n output, access_output, access_state, controller_state = neural_machine(\r\n observations=observations, \r\n actions=actions,\r\n prev_controller_state=prev_controller_state,\r\n prev_access_output=prev_access_output,\r\n prev_access_state=prev_access_state\r\n )\r\n\r\n if not self._is_actor: #If critic\r\n hidden_output = tf.concat([output, hidden_output], axis=-1)\r\n else: #If not critic\r\n if FLAGS.num_actions == 2:\r\n output /= tf.sqrt(1.e-8 + tf.reduce_sum(output**2, axis=-1, keepdims=True))\r\n\r\n if FLAGS.step_incr != 1:\r\n output *= FLAGS.step_incr\r\n elif FLAGS.num_actions == 1:\r\n output = np.pi*tf.tanh(output)\r\n\r\n if self._is_new and self._is_noise and self._is_actor and FLAGS.is_ornstein_uhlenbeck:\r\n noise = self.ornstein_uhlenbeck(prev_noise, FLAGS.ou_theta, FLAGS.ou_sigma)\r\n \r\n if not self._noise_decay is None:\r\n if FLAGS.num_actions == 2:\r\n applied_noise = tf.scalar_mul(self._noise_decay, noise)\r\n\r\n #Apply noise to action as a rotation\r\n c = tf.cos(applied_noise)\r\n s = tf.sin(applied_noise)\r\n\r\n x = c*output[:, :1] - s*output[:, 1:]\r\n y = s*output[:, :1] + c*output[:, 1:]\r\n \r\n output = tf.concat([x, y], axis=-1)\r\n elif FLAGS.num_actions == 1:\r\n output += tf.clip_by_value(noise, -np.pi, np.pi)\r\n\r\n output = tf.where(output > np.pi,\r\n output - 2*np.pi,\r\n output)\r\n output = tf.where(output < -np.pi,\r\n output + 2*np.pi,\r\n output)\r\n else:\r\n noise = prev_noise #Unchanged unless exploring\r\n\r\n if self._is_new:\r\n hidden_output = tf.concat([observations, output], axis=-1)\r\n elif self._is_actor:#If not critic\r\n if FLAGS.num_actions == 2:\r\n hidden_output /= tf.sqrt(1.e-8 + tf.reduce_sum(hidden_output**2, axis=-1, keepdims=True))\r\n if FLAGS.step_incr != 1:\r\n hidden_output *= FLAGS.step_incr\r\n elif FLAGS.num_actions == 1:\r\n hidden_output = np.pi*tf.tanh(hidden_output)\r\n\r\n return hidden_output, DNCState(\r\n access_output=access_output,\r\n access_state=access_state,\r\n controller_state=controller_state,\r\n output=output,\r\n position=position,\r\n noise=noise)\r\n\r\n def _neural_machine(\r\n self,\r\n observations, \r\n actions,\r\n prev_controller_state,\r\n prev_access_output,\r\n prev_access_state\r\n ):\r\n \r\n #step_size = observations.get_shape().as_list()[-1]\r\n #actions_size = actions.get_shape().as_list()[-1]\r\n tiled_actions = tf.tile(actions, [1, FLAGS.step_size//FLAGS.num_actions])\r\n\r\n inputs = tf.concat([observations, tiled_actions], axis=-1)\r\n\r\n if self._is_actor: #If not critic\r\n inputs = tf.stop_gradient(inputs)\r\n\r\n if FLAGS.is_input_embedder:\r\n inputs = self._input_embedder(inputs)\r\n\r\n controller_input = tf.concat(\r\n [self._batch_flatten(inputs), self._batch_flatten(prev_access_output)], 1)\r\n controller_output, controller_state = self._controller(\r\n controller_input, prev_controller_state)\r\n\r\n controller_output = self._clip_if_enabled(controller_output)\r\n controller_state = tf.contrib.framework.nest.map_structure(self._clip_if_enabled, controller_state)\r\n\r\n access_output, access_state = self._access(controller_output, prev_access_state)\r\n\r\n output = tf.concat([controller_output, self._batch_flatten(access_output)], 1)\r\n output = self._output_linear(output)\r\n\r\n if not self._is_actor:\r\n output = tf.abs(output)\r\n \r\n return output, access_output, access_state, controller_state\r\n\r\n def _neural_machine2(\r\n self,\r\n observations, \r\n actions,\r\n prev_controller_state,\r\n prev_access_output,\r\n prev_access_state\r\n ):\r\n \"\"\"Simple LSTM\"\"\"\r\n\r\n #step_size = observations.get_shape().as_list()[-1]\r\n #actions_size = actions.get_shape().as_list()[-1]\r\n tiled_actions = tf.tile(actions, [1, FLAGS.step_size//FLAGS.num_actions])\r\n\r\n inputs = tf.concat([observations, tiled_actions], axis=-1)\r\n\r\n if self._is_actor: #If not critic\r\n inputs = tf.stop_gradient(inputs)\r\n\r\n if FLAGS.is_input_embedder:\r\n inputs = self._input_embedder(inputs)\r\n\r\n controller_output, controller_state = self._controller(\r\n self._batch_flatten(inputs), prev_controller_state)\r\n\r\n controller_output = self._clip_if_enabled(controller_output)\r\n controller_state = tf.contrib.framework.nest.map_structure(self._clip_if_enabled, controller_state)\r\n\r\n output = self._output_linear(controller_output)\r\n\r\n if not self._is_actor:\r\n output = tf.abs(output)\r\n\r\n return output, prev_access_output, prev_access_state, controller_state\r\n\r\n\r\n def initial_state(self, batch_size, dtype=tf.float32):\r\n \r\n controller_state = self._controller.initial_state(batch_size, dtype)\r\n\r\n if FLAGS.num_actions == 2:\r\n output = FLAGS.step_incr*tf.ones([batch_size, self._output_size_features])/np.sqrt(2)\r\n else:\r\n output = (np.pi/4) * tf.ones([batch_size, self._output_size_features])\r\n\r\n return DNCState(\r\n controller_state=controller_state,\r\n access_state=self._access.initial_state(batch_size, dtype),\r\n access_output=tf.zeros(\r\n [batch_size] + self._access.output_size.as_list(), dtype),\r\n output=output,\r\n position=tf.ones([batch_size, 2])/2,\r\n noise=tf.zeros([batch_size, 1])\r\n )\r\n\r\n def obs(self, actions, starts):\r\n x = tf.py_func(self.make_observations, [actions, starts, self._full_scans], tf.float32)\r\n if hasattr(tf, 'ensure_shape'):\r\n x = tf.ensure_shape(x, [FLAGS.batch_size // FLAGS.avg_replays, FLAGS.step_size])\r\n else:\r\n x = tf.reshape(x, [FLAGS.batch_size // FLAGS.avg_replays, FLAGS.step_size])\r\n return x\r\n\r\n def ornstein_uhlenbeck(self, input, theta, sigma):\r\n \"\"\"Ornstein-Uhlembeck perturbation. Using Gaussian Wiener process.\"\"\"\r\n noise_perturb = -theta*input + sigma*tf.random_normal(shape=input.get_shape())\r\n return input + noise_perturb\r\n\r\n @staticmethod\r\n def make_observations(actions, starts, full_scans):\r\n\r\n if FLAGS.num_actions == 1:\r\n actions = FLAGS.step_incr*np.concatenate((np.cos(actions), np.sin(actions)), axis=-1)\r\n\r\n starts *= FLAGS.img_side\r\n x = np.minimum(np.maximum(np.stack([starts + i*actions for i in range(FLAGS.step_size)]), 0), FLAGS.img_side-1)\r\n\r\n indices = []\r\n for j in range(FLAGS.batch_size // FLAGS.avg_replays):\r\n for i in range(FLAGS.step_size):\r\n indices.append( [j, int(x[i][j][0]), int(x[i][j][1]), 0] )\r\n indices = tuple([np.array(indices)[:,i] for i in range(4)])\r\n\r\n observations = full_scans[indices].reshape([-1, FLAGS.step_size])\r\n\r\n return observations\r\n\r\n @property\r\n def state_size(self):\r\n return self._state_size\r\n\r\n @property\r\n def output_size(self):\r\n return self._output_size\r\n" ]
[ [ "tensorflow.ones", "tensorflow.reshape", "tensorflow.clip_by_value", "numpy.cos", "tensorflow.tile", "tensorflow.tanh", "numpy.sin", "tensorflow.concat", "tensorflow.TensorShape", "numpy.sqrt", "tensorflow.contrib.framework.nest.map_structure", "tensorflow.abs", "numpy.array", "tensorflow.ensure_shape", "tensorflow.zeros", "tensorflow.where", "tensorflow.py_func", "tensorflow.cos", "tensorflow.reduce_sum", "tensorflow.sin", "tensorflow.scalar_mul", "tensorflow.stop_gradient" ] ]
ruyueshuo/YOLOv4_Deployment
[ "b5c2c9c949b367b57a1e5f5c489b247ddaf44c83" ]
[ "split_datasets.py" ]
[ "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Time : 2020/11/13 16:26\n# @Author : ruyueshuo\n# @File : split_datasets.py\n# @Software: PyCharm\nimport os\nimport random\n\n\ndef split_datasets(image_path, save_path, ratio=0.8, seed=41, name=None):\n \"\"\"\n Split dataset to train and validation sets.\n :param image_path: str or Path. raw image data path.\n :param save_path: str or Path. train and validation text file saving path.\n :param ratios: float. ratio of train set.\n :param seed: int. random seed.\n :return:\n \"\"\"\n # set random seed\n random.seed(seed)\n\n # get raw image list\n image_list = os.listdir(image_path)\n image_list = [image for image in image_list if image.endswith('.jpg')]\n image_list = [os.path.join(image_path, file) for file in image_list]\n\n # # get label list\n # label_list = os.listdir(label_path)\n # label_list = [os.path.join(label_path, file) for file in label_list]\n\n file_num = len(image_list)\n\n # split dataset\n train_list = random.sample(image_list, int(file_num*ratio))\n valid_list = list(set(image_list).difference(set(train_list)))\n print(\"length of train dataset :{}\".format(len(train_list)))\n print(\"length of valid dataset :{}\".format(len(valid_list)))\n\n # save results\n save_txt(train_list, os.path.join(save_path, 'train-{}.txt'.format(name)))\n save_txt(valid_list, os.path.join(save_path, 'valid-{}.txt'.format(name)))\n\n\ndef save_txt(data, file):\n \"\"\"save data to text file.\"\"\"\n with open(file, 'w', encoding='utf-8') as f:\n for line in data:\n f.write(line + '\\n')\n # f.write(str(data))\n f.close()\n\n\ndef joint_video(video1, video2, video_out):\n \"\"\"将视频拼接\"\"\"\n import cv2\n import numpy as np\n cap1 = cv2.VideoCapture(video1)\n cap2 = cv2.VideoCapture(video2)\n suc1 = cap1.isOpened() # 是否成功打开\n suc2 = cap2.isOpened() # 是否成功打开\n frame_count = 0\n\n # 获得码率及尺寸\n video_fps = cap1.get(cv2.CAP_PROP_FPS)\n video_fps2 = cap2.get(cv2.CAP_PROP_FPS)\n\n size1 = (int(cap1.get(cv2.CAP_PROP_FRAME_WIDTH)), int(cap1.get(cv2.CAP_PROP_FRAME_HEIGHT)))\n size2 = (int(cap2.get(cv2.CAP_PROP_FRAME_WIDTH)), int(cap2.get(cv2.CAP_PROP_FRAME_HEIGHT)))\n\n size = (size1[0]+size2[0], size1[1])\n\n fourcc = cv2.VideoWriter_fourcc(*'MJPG')\n vw = cv2.VideoWriter(video_out, fourcc, video_fps, size)\n\n while suc1 and suc2:\n frame_count += 1\n\n suc1, frame1 = cap1.read()\n suc2, frame2 = cap2.read()\n if frame_count > 1000:\n break\n if frame1 is not None and frame2 is not None:\n frame1 = cv2.putText(frame1, \"DeepStream-YOLOv4\", (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2)\n frame2 = cv2.putText(frame2, \"Darknet-YOLOv4\", (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2)\n new_frame = np.concatenate((frame1, frame2),axis=1)\n vw.write(new_frame)\n cap1.release()\n cap2.release()\n vw.release()\n print('Unlock video, total image number: {}.'.format(frame_count))\n\n\nif __name__ == '__main__':\n # video2video('results/deepstream_yolov4.mp4', 'results/test_result.mp4', 'results/test.avi')\n image_path = \"/home/ubuntu/Datasets/reflective/VOC2021/JPEGImages\"\n save_path = \"/home/ubuntu/Projects/DeepStream-YOLOv4/data\"\n split_datasets(image_path, save_path, ratio=0.8, seed=41, name='reflective')\n" ]
[ [ "numpy.concatenate" ] ]
koki0702/chainer
[ "62c800e610ef37bffdcd32334d24a120a0641b8c" ]
[ "tests/chainer_tests/test_variable.py" ]
[ "import copy\nimport inspect\nimport platform\nimport re\nimport sys\nimport unittest\n\nimport mock\nimport numpy as np\nimport six\n\nimport chainer\nfrom chainer import cuda\nimport chainer.functions as F\nfrom chainer import initializers\nfrom chainer import testing\nfrom chainer.testing import attr\nfrom chainer import variable\n\n\nclass Constant(chainer.Function):\n\n def __init__(self, outputs):\n self.__outputs = outputs\n\n def forward_cpu(self, inputs):\n return self.__outputs\n\n def forward_gpu(self, inputs):\n return tuple(map(cuda.to_gpu, self.__outputs))\n\n def backward_cpu(self, inputs, grad_outputs):\n return tuple(map(np.zeros_like, inputs))\n\n def backward_gpu(self, inputs, grad_outputs):\n return tuple(map(cuda.cupy.zeros_like, inputs))\n\n\ndef constant(xs, value):\n return Constant(value)(*xs)\n\n\nclass TestVariableNode(unittest.TestCase):\n\n def test_grad(self):\n with self.assertRaises(ValueError):\n variable.VariableNode(chainer.Variable(), '', grad=None)\n\n\[email protected](\n {'x_shape': (10,), 'c_shape': (2, 5), 'label': '(2, 5), float32'},\n {'x_shape': (), 'c_shape': (1,), 'label': '(1), float32'},\n)\nclass TestVariable(unittest.TestCase):\n\n def setUp(self):\n self.x = np.random.uniform(-1, 1, self.x_shape).astype(np.float32)\n self.a = np.random.uniform(0.1, 10, self.x_shape).astype(np.float32)\n self.size = int(np.prod(self.x_shape))\n self.c = np.arange(self.size).reshape(self.c_shape).astype(np.float32)\n\n def check_attributes(self, gpu):\n a = self.x\n if gpu:\n a = cuda.to_gpu(a)\n x = chainer.Variable(a)\n self.assertIs(x.data, a)\n self.assertIs(x.array, a)\n self.assertEqual(x.shape, self.x.shape)\n self.assertEqual(x.ndim, self.x.ndim)\n self.assertEqual(x.size, self.x.size)\n self.assertEqual(x.dtype, self.x.dtype)\n self.assertTrue(x.requires_grad)\n self.assertTrue(x.node.requires_grad)\n\n def test_attributes_cpu(self):\n self.check_attributes(False)\n\n @attr.gpu\n def test_attributes_gpu(self):\n self.check_attributes(True)\n\n def check_grad(self, x, xp):\n g = xp.array(x)\n v = chainer.Variable(x)\n gv = chainer.Variable(g)\n v.grad_var = gv\n\n self.assertIs(v.grad, g)\n self.assertIs(v.grad_var, gv)\n\n def check_len(self, gpu):\n x = self.x\n if gpu:\n x = cuda.to_gpu(x)\n x = chainer.Variable(x)\n if x.ndim == 0:\n self.assertRaises(TypeError, x.__len__)\n else:\n self.assertEqual(len(x), self.x_shape[0])\n\n def test_len_cpu(self):\n self.check_len(False)\n\n @attr.gpu\n def test_len_gpu(self):\n self.check_len(True)\n\n def check_get_item(self, gpu):\n x_data = self.x\n if gpu:\n x_data = cuda.to_gpu(x_data)\n x = chainer.Variable(x_data)\n if len(self.x_shape) > 0:\n slices = slice(2, 5)\n np.testing.assert_equal(cuda.to_cpu(x[slices].data),\n cuda.to_cpu(x_data[slices]))\n slices = slice(2, 5),\n np.testing.assert_equal(cuda.to_cpu(x[slices].data),\n cuda.to_cpu(x_data[slices]))\n\n def test_get_item_cpu(self):\n self.check_get_item(False)\n\n @attr.gpu\n def test_get_item_gpu(self):\n self.check_get_item(True)\n\n def check_label(self, expected, gpu):\n c = self.c\n if gpu:\n c = cuda.to_gpu(c)\n c = chainer.Variable(c)\n self.assertEqual(c.label, expected)\n\n def test_label_cpu(self):\n self.check_label(self.label, False)\n\n @attr.gpu\n def test_label_gpu(self):\n self.check_label(self.label, True)\n\n def get_xp_and_variable(self, gpu):\n if gpu:\n return cuda.cupy, chainer.Variable(cuda.to_gpu(self.x))\n return np, chainer.Variable(self.x)\n\n def check_backward(self, inputs, intermediates, outputs, retain_grad):\n for o in outputs:\n o.backward(retain_grad)\n\n self.assertTrue(all([x.grad_var is not None for x in inputs]))\n if retain_grad:\n self.assertTrue(\n all([x.grad_var is not None for x in intermediates]))\n else:\n self.assertTrue(all([x.grad_var is None for x in intermediates]))\n self.assertTrue(any([x.grad_var is not None for x in outputs]))\n\n # length is number of edges. So, # of Variables created is length+1\n def create_linear_chain(self, length, gpu):\n _, x = self.get_xp_and_variable(gpu)\n ret = [x]\n for i in six.moves.range(length):\n ret.append(constant((ret[i], ), (self.a, )))\n if gpu:\n ret[-1].grad = cuda.cupy.zeros_like(ret[-1].data)\n else:\n ret[-1].grad = np.zeros_like(ret[-1].data)\n return ret\n\n def test_backward_cpu(self):\n ret = self.create_linear_chain(2, False)\n self.check_backward((ret[0], ), (ret[1], ), (ret[2], ), False)\n\n @attr.gpu\n def test_backward_gpu(self):\n ret = self.create_linear_chain(2, False)\n self.check_backward((ret[0], ), (ret[1], ), (ret[2], ), False)\n\n def check_backward_accumulate(self, gpu):\n xp, x = self.get_xp_and_variable(gpu)\n y = constant((x, x, x), (self.a, ))\n y.grad = xp.zeros_like(y.data)\n y.backward()\n self.assertEqual(x.grad_var.shape, self.x_shape)\n\n def test_backward_accumulate_cpu(self):\n self.check_backward_accumulate(False)\n\n @attr.gpu\n def test_backward_accumulate_gpu(self):\n self.check_backward_accumulate(True)\n\n def test_backward_cpu_retain_grad(self):\n ret = self.create_linear_chain(2, False)\n self.check_backward((ret[0], ), (ret[1], ), (ret[2], ), True)\n\n @attr.gpu\n def test_backward_gpu_retain_grad(self):\n ret = self.create_linear_chain(2, True)\n self.check_backward((ret[0], ), (ret[1], ), (ret[2], ), True)\n\n def check_double_backprop(self, gpu):\n xp, x = self.get_xp_and_variable(gpu)\n x.grad_var = None\n\n y = x * x * x\n y.grad = xp.ones_like(y.data)\n y.backward(enable_double_backprop=True)\n gx = x.grad_var\n x.grad_var = None # clear grad\n gx.grad = xp.ones_like(x.data)\n gx.backward()\n\n expect = 6 * x\n testing.assert_allclose(x.grad_var.data, expect.data)\n\n def test_double_backprop_cpu(self):\n self.check_double_backprop(False)\n\n @attr.gpu\n def test_double_backprop_gpu(self):\n self.check_double_backprop(True)\n\n def test_backward_no_grad_required(self):\n class DummyId(F.Identity):\n\n def backward(self, a, b):\n raise Exception('backward should not be called on inputs that '\n 'do not require grads')\n\n x = chainer.Variable(self.x)\n y1, y2 = DummyId().apply((x, x))\n x.node._requires_grad = False\n y1.backward()\n\n def test_unchain(self):\n ret = self.create_linear_chain(3, False)\n old_rank = ret[1].rank\n ret[1].unchain()\n self.assertIsNone(ret[1].creator)\n self.assertEqual(ret[1].rank, old_rank)\n self.check_backward((ret[1],), (ret[2],), (ret[3],), False)\n\n def check_set_none_to_creator(self, use_creator_node):\n ret = self.create_linear_chain(3, False)\n old_rank = ret[1].rank\n if use_creator_node:\n ret[1].creator_node = None\n else:\n ret[1].creator = None\n self.assertIsNone(ret[1].creator)\n self.assertIsNone(ret[1].creator_node)\n self.assertEqual(ret[1].rank, old_rank)\n self.check_backward((ret[1],), (ret[2],), (ret[3],), False)\n\n def test_set_none_to_creator(self):\n self.check_set_none_to_creator(False)\n\n def test_set_none_to_creator_node(self):\n self.check_set_none_to_creator(True)\n\n def test_set_none_and_original_to_creator(self):\n ret = self.create_linear_chain(2, False)\n old_rank = ret[1].rank\n creator_node = ret[1].creator_node\n ret[1].creator = None\n self.assertIsNone(ret[1].creator)\n self.assertEqual(ret[1].rank, old_rank)\n\n ret[1].node._rank = -1\n ret[1].creator_node = creator_node\n self.assertIs(ret[1].creator_node, creator_node)\n self.assertEqual(ret[1].rank, creator_node.rank + 1)\n self.check_backward((ret[0],), (ret[1],), (ret[2],), False)\n\n def test_set_fresh_creator(self):\n v = chainer.Variable()\n f = chainer.Function()\n v.creator = f\n self.assertIs(v.creator, f)\n self.assertIs(v.creator_node, f.node)\n self.assertEqual(v.rank, 1)\n\n def test_set_fresh_creator_node(self):\n v = chainer.Variable()\n f = chainer.FunctionNode()\n v.creator_node = f\n self.assertIs(v.creator, f)\n self.assertIs(v.creator_node, f)\n self.assertEqual(v.rank, 1)\n\n def test_unchain_backward_cpu(self):\n ret = self.create_linear_chain(3, False)\n ret[1].unchain_backward()\n self.check_backward((ret[1], ), (ret[2], ), (ret[3], ), False)\n\n @attr.gpu\n def test_unchain_backward_gpu(self):\n ret = self.create_linear_chain(3, True)\n ret[1].unchain_backward()\n self.check_backward((ret[1], ), (ret[2], ), (ret[3], ), False)\n\n def test_unchain_backward_cpu_retain_grad(self):\n ret = self.create_linear_chain(3, False)\n ret[1].unchain_backward()\n self.check_backward((ret[1], ), (ret[2], ), (ret[3], ), False)\n\n @attr.gpu\n def test_unchain_backward_gpu_retain_grad(self):\n ret = self.create_linear_chain(3, False)\n ret[1].unchain_backward()\n self.check_backward((ret[1], ), (ret[2], ), (ret[3], ), False)\n\n def test_invalid_value_type(self):\n with six.assertRaisesRegex(self, TypeError, 'int'):\n chainer.Variable(1)\n\n def test_grad_type_check_pass(self):\n a = chainer.Variable(np.empty((3,), dtype=np.float32))\n a.grad = np.ndarray((3,), dtype=np.float32)\n\n def test_grad_type_check_type(self):\n a = chainer.Variable(np.empty((), dtype=np.float32))\n with self.assertRaises(TypeError):\n a.grad = np.float32()\n\n @attr.gpu\n def test_grad_type_check_type_cpu_gpu_mixture(self):\n a = chainer.Variable(np.empty((3,), dtype=np.float32))\n with self.assertRaises(TypeError):\n a.grad = cuda.cupy.empty((3,), dtype=np.float32)\n\n def test_grad_type_check_dtype(self):\n a = chainer.Variable(np.empty((3,), dtype=np.float32))\n with self.assertRaises(TypeError):\n a.grad = np.empty((3,), dtype=np.float64)\n\n def test_grad_type_check_shape(self):\n a = chainer.Variable(np.empty((3,), dtype=np.float32))\n with self.assertRaises(ValueError):\n a.grad = np.empty((2,), dtype=np.float32)\n\n def test_to_cpu_from_cpu(self):\n a = chainer.Variable(np.zeros(3, dtype=np.float32))\n a.grad = np.ones_like(a.data)\n b = a.data\n gb = a.grad\n c = b.copy()\n gc = gb.copy()\n a.to_cpu()\n self.assertIs(a.data, b)\n self.assertIs(a.grad, gb)\n np.testing.assert_array_equal(a.data, c)\n np.testing.assert_array_equal(a.grad, gc)\n\n @attr.gpu\n def test_to_cpu(self):\n a = chainer.Variable(cuda.cupy.zeros(3, dtype=np.float32))\n a.grad = cuda.cupy.ones_like(a.data)\n a.to_cpu()\n np.testing.assert_array_equal(a.data, np.zeros(3, dtype=np.float32))\n np.testing.assert_array_equal(a.grad, np.ones(3, dtype=np.float32))\n\n @attr.gpu\n def test_to_gpu_from_gpu(self):\n cp = cuda.cupy\n a = chainer.Variable(cp.zeros(3, dtype=np.float32))\n a.grad = cuda.cupy.ones_like(a.data)\n b = a.data\n gb = a.grad\n c = b.copy()\n gc = gb.copy()\n a.to_gpu()\n self.assertIs(a.data, b)\n self.assertIs(a.grad, gb)\n cp.testing.assert_array_equal(a.data, c)\n cp.testing.assert_array_equal(a.grad, gc)\n\n @attr.gpu\n def test_to_gpu(self):\n cp = cuda.cupy\n a = chainer.Variable(np.zeros(3, dtype=np.float32))\n a.grad = np.ones(3, dtype=np.float32)\n a.to_gpu()\n cp.testing.assert_array_equal(a.data, cp.zeros(3, dtype=np.float32))\n cp.testing.assert_array_equal(a.grad, cp.ones(3, dtype=np.float32))\n\n @attr.multi_gpu(2)\n def test_to_gpu_from_another_gpu(self):\n cp = cuda.cupy\n a = chainer.Variable(cp.zeros(3, dtype=np.float32))\n a.grad = cuda.cupy.ones_like(a.data)\n b = a.data.copy()\n gb = a.grad.copy()\n a.to_gpu(1)\n\n self.assertEqual(int(cuda.get_device_from_array(a.data)), 1)\n self.assertEqual(int(cuda.get_device_from_array(a.grad)), 1)\n cp.testing.assert_array_equal(a.data, b)\n cp.testing.assert_array_equal(a.grad, gb)\n\n def check_cleargrad(self, a_data, fill=False):\n xp = cuda.get_array_module(a_data)\n a = chainer.Variable(a_data)\n if fill:\n a.grad = xp.full_like(a_data, np.nan)\n\n a.cleargrad()\n self.assertIsNone(a.grad)\n\n def test_cleargrad_cpu(self):\n self.check_cleargrad(np.empty(3, dtype=np.float32))\n\n def test_cleargrad_fill_cpu(self):\n self.check_cleargrad(np.empty(3, dtype=np.float32), fill=True)\n\n @attr.gpu\n def test_cleargrad_gpu(self):\n self.check_cleargrad(cuda.cupy.empty(3, dtype=np.float32))\n\n @attr.gpu\n def test_cleargrad_fill_gpu(self):\n self.check_cleargrad(cuda.cupy.empty(3, dtype=np.float32), fill=True)\n\n def check_zerograd(self, a_data, fill=False):\n xp = cuda.get_array_module(a_data)\n a = chainer.Variable(a_data)\n if fill:\n a.grad_var = chainer.Variable(xp.full_like(a_data, np.nan))\n a.grad_var.creator_node = chainer.FunctionNode()\n\n with testing.assert_warns(DeprecationWarning):\n a.zerograd()\n self.assertIsNot(a.grad, None)\n if fill:\n self.assertIsNone(a.grad_var.creator_node)\n g_expect = xp.zeros_like(a.data)\n xp.testing.assert_array_equal(a.grad, g_expect)\n\n def test_zerograd_cpu(self):\n self.check_zerograd(np.empty(3, dtype=np.float32))\n\n def test_zerograd_fill_cpu(self):\n self.check_zerograd(np.empty(3, dtype=np.float32), fill=True)\n\n @attr.multi_gpu(2)\n def test_zerograds_multi_gpu(self):\n cupy = cuda.cupy\n with cuda.get_device_from_id(1):\n a = chainer.Variable(cupy.empty(3, dtype=np.float32))\n with testing.assert_warns(DeprecationWarning):\n a.zerograd()\n self.assertIsNot(a.grad, None)\n self.assertEqual(int(a.grad.device), 1)\n with cuda.get_device_from_id(1):\n g_expect = cupy.zeros_like(a.data)\n cupy.testing.assert_array_equal(a.grad, g_expect)\n\n @attr.multi_gpu(2)\n def test_zerograds_fill_multi_gpu(self):\n cupy = cuda.cupy\n with cuda.get_device_from_id(1):\n a = chainer.Variable(cupy.empty(3, dtype=np.float32))\n a.grad = cupy.empty_like(a.data)\n with testing.assert_warns(DeprecationWarning):\n a.zerograd()\n self.assertEqual(int(a.grad.device), 1)\n with cuda.get_device_from_id(1):\n g_expect = cupy.zeros_like(a.data)\n cupy.testing.assert_array_equal(a.grad, g_expect)\n\n @attr.gpu\n def test_zerograd_gpu(self):\n self.check_zerograd(cuda.cupy.empty(3, dtype=np.float32))\n\n @attr.gpu\n def test_zerograd_fill_gpu(self):\n self.check_zerograd(cuda.cupy.empty(3, dtype=np.float32), fill=True)\n\n def check_copydata(self, data1, data2, expect):\n xp = cuda.get_array_module(data1)\n v = chainer.Variable(data1)\n w = chainer.Variable(data2)\n v.copydata(w)\n xp.testing.assert_array_equal(v.data, expect)\n\n def test_copydata_cpu_to_cpu(self):\n self.check_copydata(np.zeros(3, dtype=np.float32),\n np.ones(3, dtype=np.float32),\n np.ones(3, dtype=np.float32))\n\n @attr.gpu\n def test_copydata_cpu_to_gpu(self):\n cp = cuda.cupy\n self.check_copydata(cp.zeros(3, dtype=np.float32),\n np.ones(3, dtype=np.float32),\n cp.ones(3, dtype=np.float32))\n\n @attr.gpu\n def test_copydata_gpu_to_gpu(self):\n cp = cuda.cupy\n self.check_copydata(cp.zeros(3, dtype=np.float32),\n cp.ones(3, dtype=np.float32),\n cp.ones(3, dtype=np.float32))\n\n @attr.gpu\n def test_copydata_gpu_to_cpu(self):\n cp = cuda.cupy\n self.check_copydata(np.zeros(3, dtype=np.float32),\n cp.ones(3, dtype=np.float32),\n np.ones(3, dtype=np.float32))\n\n @attr.multi_gpu(2)\n def test_copydata_gpu_to_another_gpu(self):\n cp = cuda.cupy\n with cuda.get_device_from_id(0):\n data1 = cp.zeros(3, dtype=np.float32)\n expect = cp.ones(3, dtype=np.float32)\n with cuda.get_device_from_id(1):\n data2 = cp.ones(3, dtype=np.float32)\n self.check_copydata(data1, data2, expect)\n\n def check_addgrad(self, src, dst, expect,\n clear_src_grad=False, clear_dst_grad=False):\n xp = cuda.get_array_module(dst)\n a = chainer.Variable(src)\n a.grad = src\n b = chainer.Variable(dst)\n b.grad = dst\n if clear_src_grad:\n a.cleargrad()\n if clear_dst_grad:\n b.cleargrad()\n b.addgrad(a)\n xp.testing.assert_array_equal(b.grad, expect)\n self.assertEqual(cuda.get_device_from_array(b.data),\n cuda.get_device_from_array(b.grad))\n\n def test_addgrad_cpu_to_cpu(self):\n self.check_addgrad(np.full(3, 10, dtype=np.float32),\n np.full(3, 20, dtype=np.float32),\n np.full(3, 30, dtype=np.float32))\n\n @attr.gpu\n def test_addgrad_cpu_to_gpu(self):\n cp = cuda.cupy\n self.check_addgrad(np.full(3, 10, dtype=np.float32),\n cp.full(3, 20, dtype=np.float32),\n cp.full(3, 30, dtype=np.float32))\n\n @attr.gpu\n def test_addgrad_gpu_to_gpu(self):\n cp = cuda.cupy\n self.check_addgrad(cp.full(3, 10, dtype=np.float32),\n cp.full(3, 20, dtype=np.float32),\n cp.full(3, 30, dtype=np.float32))\n\n @attr.gpu\n def test_addgrad_gpu_to_cpu(self):\n cp = cuda.cupy\n self.check_addgrad(cp.full(3, 10, dtype=np.float32),\n np.full(3, 20, dtype=np.float32),\n np.full(3, 30, dtype=np.float32))\n\n @attr.multi_gpu(2)\n def test_addgrad_gpu_to_gpu_multi(self):\n cp = cuda.cupy\n with cuda.get_device_from_id(1):\n a = cp.full(3, 10, dtype=np.float32)\n b = cp.full(3, 20, dtype=np.float32)\n c = cp.full(3, 30, dtype=np.float32)\n with cuda.get_device_from_id(0):\n self.check_addgrad(a, b, c)\n\n @attr.multi_gpu(2)\n def test_addgrad_gpu_to_another_gpu(self):\n cp = cuda.cupy\n with cuda.get_device_from_id(1):\n a = cp.full(3, 10, dtype=np.float32)\n with cuda.get_device_from_id(0):\n b = cp.full(3, 20, dtype=np.float32)\n c = cp.full(3, 30, dtype=np.float32)\n self.check_addgrad(a, b, c)\n\n def test_addgrad_cpu_to_cpu_none_src(self):\n self.check_addgrad(np.full(3, 10, dtype=np.float32),\n np.full(3, 20, dtype=np.float32),\n np.full(3, 20, dtype=np.float32),\n clear_src_grad=True)\n\n @attr.gpu\n def test_addgrad_gpu_to_gpu_none_src(self):\n cp = cuda.cupy\n self.check_addgrad(cp.full(3, 10, dtype=np.float32),\n cp.full(3, 20, dtype=np.float32),\n cp.full(3, 20, dtype=np.float32),\n clear_src_grad=True)\n\n @attr.multi_gpu(2)\n def test_addgrad_gpu_to_another_gpu_none_src_dev0(self):\n cp = cuda.cupy\n with cuda.get_device_from_id(1):\n a = cp.full(3, 10, dtype=np.float32)\n with cuda.get_device_from_id(0):\n b = cp.full(3, 20, dtype=np.float32)\n c = cp.full(3, 20, dtype=np.float32)\n with cuda.get_device_from_id(0):\n self.check_addgrad(a, b, c, clear_src_grad=True)\n\n @attr.multi_gpu(2)\n def test_addgrad_gpu_to_another_gpu_none_src_dev1(self):\n cp = cuda.cupy\n with cuda.get_device_from_id(1):\n a = cp.full(3, 10, dtype=np.float32)\n with cuda.get_device_from_id(0):\n b = cp.full(3, 20, dtype=np.float32)\n c = cp.full(3, 20, dtype=np.float32)\n with cuda.get_device_from_id(1):\n self.check_addgrad(a, b, c, clear_src_grad=True)\n\n def test_addgrad_cpu_to_cpu_none_dst(self):\n self.check_addgrad(np.full(3, 20, dtype=np.float32),\n np.full(3, 10, dtype=np.float32),\n np.full(3, 20, dtype=np.float32),\n clear_dst_grad=True)\n\n @attr.gpu\n def test_addgrad_gpu_to_gpu_none_dst(self):\n cp = cuda.cupy\n self.check_addgrad(cp.full(3, 20, dtype=np.float32),\n cp.full(3, 10, dtype=np.float32),\n cp.full(3, 20, dtype=np.float32),\n clear_dst_grad=True)\n\n @attr.multi_gpu(2)\n def test_addgrad_gpu_to_another_gpu_none_dst_dev0(self):\n cp = cuda.cupy\n with cuda.get_device_from_id(1):\n a = cp.full(3, 20, dtype=np.float32)\n with cuda.get_device_from_id(0):\n b = cp.full(3, 10, dtype=np.float32)\n c = cp.full(3, 20, dtype=np.float32)\n with cuda.get_device_from_id(0):\n self.check_addgrad(a, b, c, clear_dst_grad=True)\n\n @attr.multi_gpu(2)\n def test_addgrad_gpu_to_another_gpu_none_dst_dev1(self):\n cp = cuda.cupy\n with cuda.get_device_from_id(1):\n a = cp.full(3, 20, dtype=np.float32)\n with cuda.get_device_from_id(0):\n b = cp.full(3, 10, dtype=np.float32)\n c = cp.full(3, 20, dtype=np.float32)\n with cuda.get_device_from_id(1):\n self.check_addgrad(a, b, c, clear_dst_grad=True)\n\n def test_addgrad_none_src_dst(self):\n x = chainer.Variable(self.x)\n y = chainer.Variable(self.x)\n y.addgrad(x)\n self.assertIsNone(y.grad)\n\n def test_pickle_cpu(self):\n x = chainer.Variable(self.x)\n x.grad = np.ones_like(x.data)\n binary = six.moves.cPickle.dumps(x)\n d = six.moves.cPickle.loads(binary)\n np.testing.assert_array_equal(x.data, d.data)\n np.testing.assert_array_equal(x.grad, d.grad)\n\n @attr.gpu\n def test_pickle_gpu(self):\n cp = cuda.cupy\n x = chainer.Variable(self.x)\n x.grad = np.ones_like(x.data)\n x.to_gpu()\n binary = six.moves.cPickle.dumps(x)\n d = six.moves.cPickle.loads(binary)\n cp.testing.assert_array_equal(x.data, d.data)\n cp.testing.assert_array_equal(x.grad, d.grad)\n\n\nclass TestVariableBasic(unittest.TestCase):\n def test_unhashable(self):\n a = chainer.Variable(np.ones((2,)))\n with six.assertRaisesRegex(self, TypeError, '^unhashable type: '):\n hash(a)\n\n def test_unequatable(self):\n a = chainer.Variable(np.ones((2,)))\n b = chainer.Variable(np.ones((2,)))\n with self.assertRaises(NotImplementedError):\n a == b\n with self.assertRaises(NotImplementedError):\n a == a\n with self.assertRaises(NotImplementedError):\n a != b\n with self.assertRaises(NotImplementedError):\n a != a\n\n def test_uncomparable(self):\n a = chainer.Variable(np.ones((2,)))\n b = chainer.Variable(np.ones((2,)))\n with self.assertRaises(NotImplementedError):\n a < b\n with self.assertRaises(NotImplementedError):\n a <= b\n with self.assertRaises(NotImplementedError):\n a > b\n with self.assertRaises(NotImplementedError):\n a >= b\n\n def test_bool_inconvertible(self):\n a = chainer.Variable(np.ones((2,)))\n with self.assertRaises(NotImplementedError):\n if a:\n pass\n with self.assertRaises(NotImplementedError):\n if not a:\n pass\n\n\nclass TestVariableDataAssign(unittest.TestCase):\n\n def test_variable_data_assign(self):\n x = chainer.Variable(np.ones((3, 2), np.float32))\n chainer.functions.sin(x)\n x.data = np.ones((2, 4), np.float64)\n assert x.data.shape == (2, 4)\n assert x.data.dtype == np.float64\n assert x.shape == (2, 4)\n assert x.dtype == np.float64\n assert x.node.shape == (2, 4)\n assert x.node.dtype == np.float64\n assert x.node.data.shape == (2, 4)\n assert x.node.data.dtype == np.float64\n\n\nclass TestParameter(unittest.TestCase):\n\n def setUp(self):\n self.a = np.random.rand(3, 2).astype(np.float32)\n\n def test_initializer(self):\n x = chainer.Parameter(shape=(1,))\n self.assertIsNone(x.initializer)\n\n def test_initialize_by_scalar(self):\n x = chainer.Parameter(2., (3,))\n np.testing.assert_array_equal(x.data, np.array([2., 2., 2.]))\n\n def test_initialize_by_initializer(self):\n x = chainer.Parameter(initializers.One(), (3,))\n np.testing.assert_array_equal(\n x.data, np.array([1., 1., 1.], dtype='f'))\n\n def test_initialize_by_none(self):\n x = chainer.Parameter(None, (3,))\n np.testing.assert_array_equal(\n x.data, np.full((3,), np.nan, dtype='f'))\n\n def test_initialize_by_array(self):\n data = np.array([1., 2., 3.], dtype='f')\n x = chainer.Parameter(data)\n self.assertIs(x.data, data)\n\n @attr.gpu\n def test_initialize_by_cupy_array(self):\n data = cuda.cupy.array([1., 2., 3.], dtype='f')\n x = chainer.Parameter(data, (3,))\n self.assertIsInstance(x.data, cuda.cupy.ndarray)\n cuda.cupy.testing.assert_array_equal(x.data, data)\n\n def test_update_rule(self):\n update_rule = mock.MagicMock()\n g = self.a.copy()\n x = chainer.Parameter(self.a)\n x.grad = g\n x.update_rule = update_rule\n x.update()\n self.assertEqual(update_rule.update.call_count, 1)\n self.assertEqual(update_rule.update.call_args_list[0], [(x,), {}])\n\n def test_update_rule_without_grad(self):\n update_rule = mock.MagicMock()\n x = chainer.Parameter(self.a)\n x.update_rule = update_rule\n x.update()\n self.assertEqual(update_rule.update.call_count, 1)\n\n\nclass TestUninitializedParameter(unittest.TestCase):\n\n def setUp(self):\n self.a = np.random.rand(3, 2).astype(np.float32)\n self.b = np.random.rand(*self.a.shape).astype(self.a.dtype)\n\n def test_init_without_data(self):\n x = chainer.Parameter()\n self.assertIsNone(x.data)\n self.assertIsNone(x.grad)\n\n def test_initialize(self):\n x = chainer.Parameter()\n x.initialize((3, 2))\n self.assertEqual(x.shape, (3, 2))\n self.assertEqual(x.dtype, np.float32)\n np.testing.assert_array_equal(x.data, np.float32('nan'))\n np.testing.assert_array_equal(x.grad, np.float32('nan'))\n\n def check_constant_initialization(self, x, a, xp):\n x.initialize(a.shape)\n self.assertIsInstance(x.data, xp.ndarray)\n xp.testing.assert_array_equal(x.data, xp.asarray(a))\n xp.testing.assert_array_equal(x.grad, np.float32('nan'))\n\n def test_initialize_with_initializer(self):\n x = chainer.Parameter(initializers.Constant(self.a))\n self.check_constant_initialization(x, self.a, np)\n\n def test_initialize_dtype(self):\n initializer = initializers.Zero(np.float64)\n x = chainer.Parameter(initializer=initializer)\n x.initialize((2, 3))\n self.assertEqual(x.data.dtype, np.float64)\n self.assertEqual(x.grad.dtype, np.float64)\n\n def test_initialize_node(self):\n initializer = initializers.Zero(np.float64)\n x = chainer.Parameter(initializer=initializer)\n x.initialize((2, 3))\n self.assertEqual(x.node.shape, (2, 3))\n self.assertEqual(x.node.dtype, np.float64)\n\n @attr.gpu\n def test_initialize_to_gpu(self):\n x = chainer.Parameter(initializer=initializers.Constant(self.a))\n x.to_gpu()\n self.check_constant_initialization(x, self.a, cuda.cupy)\n\n @attr.gpu\n def test_initialize_to_cpu(self):\n x = chainer.Parameter(initializer=initializers.Constant(self.a))\n x.to_gpu()\n x.to_cpu()\n self.check_constant_initialization(x, self.a, np)\n\n def test_copy_to_initialize(self):\n # This test intends the use case of link.copy() method.\n x = chainer.Parameter()\n y = copy.copy(x)\n x.initialize((3, 2))\n self.assertIs(x.data, y.data)\n\n def test_cleargrad(self):\n x = chainer.Parameter()\n x.cleargrad()\n x.initialize((3, 2))\n self.assertIsNone(x.grad)\n\n def check_zerograd(self, x, xp):\n self.assertIsInstance(x.grad, xp.ndarray)\n self.assertEqual(x.grad.shape, x.data.shape)\n self.assertEqual(x.grad.dtype, x.data.dtype)\n xp.testing.assert_array_equal(x.grad, 0)\n\n def test_zerograd(self):\n x = chainer.Parameter()\n with testing.assert_warns(DeprecationWarning):\n x.zerograd()\n x.initialize((3, 2))\n self.check_zerograd(x, np)\n\n @attr.gpu\n def test_zerograd_to_gpu(self):\n x = chainer.Parameter()\n with testing.assert_warns(DeprecationWarning):\n x.zerograd()\n x.to_gpu()\n x.initialize((3, 2))\n self.check_zerograd(x, cuda.cupy)\n\n @attr.gpu\n def test_to_gpu_zerograd(self):\n x = chainer.Parameter()\n x.to_gpu()\n with testing.assert_warns(DeprecationWarning):\n x.zerograd()\n x.initialize((3, 2))\n self.check_zerograd(x, cuda.cupy)\n\n def test_zerograd_dtype(self):\n x = chainer.Parameter(initializers.Zero(dtype=np.float16))\n with testing.assert_warns(DeprecationWarning):\n x.zerograd()\n x.initialize((3, 2))\n self.assertEqual(x.grad.dtype, x.data.dtype)\n\n def test_copydata_to_uninitialized_parameter(self):\n x = chainer.Parameter()\n y = chainer.Parameter(self.a)\n x.copydata(y)\n np.testing.assert_array_equal(x.data, self.a)\n\n @attr.gpu\n def test_copydata_to_uninitialized_parameter_gpu(self):\n x = chainer.Parameter()\n y = chainer.Parameter(self.a)\n x.to_gpu()\n x.copydata(y)\n cp = cuda.cupy\n self.assertIsInstance(x.data, cp.ndarray)\n cp.testing.assert_array_equal(x.data, self.a)\n\n def test_copydata_from_uninitialized_parameter(self):\n initializer = initializers.Zero()\n x = chainer.Parameter(self.a)\n y = chainer.Parameter(initializer)\n x.copydata(y)\n self.assertIsInstance(x.data, np.ndarray)\n self.assertIsInstance(y.data, np.ndarray)\n np.testing.assert_array_equal(x.data, y.data)\n\n @attr.gpu\n def test_copydata_from_uninitialized_parameter_gpu(self):\n initializer = initializers.Zero()\n x = chainer.Parameter(self.a)\n y = chainer.Parameter(initializer)\n y.to_gpu()\n x.copydata(y)\n cp = cuda.cupy\n self.assertIsInstance(x.data, np.ndarray)\n self.assertIsInstance(y.data, cp.ndarray)\n cp.testing.assert_array_equal(x.data, y.data)\n\n def test_copydata_from_to_uninitialized_parameters(self):\n x = chainer.Parameter()\n y = chainer.Parameter()\n x.copydata(y)\n self.assertIsNone(x.data)\n self.assertIsNone(y.data)\n\n def test_addgrad_to_uninitialized_parameter(self):\n x = chainer.Parameter()\n y = chainer.Parameter(self.a)\n y.grad = self.b\n x.cleargrad()\n x.addgrad(y)\n self.assertIsInstance(x.data, np.ndarray)\n self.assertIsInstance(x.grad, np.ndarray)\n np.testing.assert_array_equal(x.grad, self.b)\n\n @attr.gpu\n def test_addgrad_to_uninitialized_parameter_cpu_to_gpu(self):\n x = chainer.Parameter()\n y = chainer.Parameter(self.a)\n y.grad = self.b\n x.to_gpu()\n x.cleargrad()\n x.addgrad(y)\n cp = cuda.cupy\n self.assertIsInstance(x.data, cp.ndarray)\n self.assertIsInstance(x.grad, cp.ndarray)\n cp.testing.assert_array_equal(x.grad, self.b)\n\n @attr.gpu\n def test_addgrad_to_uninitialized_parameter_gpu_to_cpu(self):\n x = chainer.Parameter()\n y = chainer.Parameter(self.a)\n y.grad = self.b\n y.to_gpu()\n x.cleargrad()\n x.addgrad(y)\n self.assertIsInstance(x.data, np.ndarray)\n self.assertIsInstance(x.grad, np.ndarray)\n np.testing.assert_array_equal(x.grad, self.b)\n\n @attr.gpu\n def test_addgrad_to_uninitialized_parameter_gpu_to_gpu(self):\n x = chainer.Parameter()\n y = chainer.Parameter(self.a)\n y.grad = self.b\n x.to_gpu()\n y.to_gpu()\n x.cleargrad()\n x.addgrad(y)\n cp = cuda.cupy\n self.assertIsInstance(x.data, cp.ndarray)\n self.assertIsInstance(x.grad, cp.ndarray)\n cp.testing.assert_array_equal(x.grad, self.b)\n\n @attr.multi_gpu(2)\n def test_addgrad_to_uninitialized_parameter_gpu_to_another_gpu(self):\n x = chainer.Parameter()\n y = chainer.Parameter(self.a)\n y.grad = self.b\n x.to_gpu(1)\n y.to_gpu(0)\n x.cleargrad()\n x.addgrad(y)\n cp = cuda.cupy\n self.assertIsInstance(x.data, cp.ndarray)\n self.assertIsInstance(x.grad, cp.ndarray)\n self.assertEqual(int(x.data.device), 1)\n self.assertEqual(int(x.grad.device), 1)\n cp.testing.assert_array_equal(x.grad, self.b)\n\n\nclass TestDebugPrint(unittest.TestCase):\n\n def setUp(self):\n self.arr = np.random.randn(5, 3, 5, 5).astype(np.float32)\n\n def check_debug_print(self, v, mean, std):\n result = v.debug_print()\n self.assertIn(v.summary(), result)\n self.assertIn('dtype: float32', result)\n # py2.7 on win64 returns shape as long\n self.assertTrue(re.match(r'- shape: \\(5L?, 3L?, 5L?, 5L?\\)',\n result.splitlines()[3]))\n\n # no grad\n msg = 'statistics: mean={mean:.8f}, std={std:.8f}'\n msg = msg.format(mean=mean, std=std)\n self.assertIn(msg, result)\n self.assertIn('grad: None', result)\n\n # zero grad\n with testing.assert_warns(DeprecationWarning):\n v.zerograd()\n result = v.debug_print()\n self.assertIn('grad: 0', result)\n\n # add grad\n v.grad = v.data\n result = v.debug_print()\n\n msg = 'grad: mean={mean:.8f}, std={std:.8f}'.format(mean=mean, std=std)\n self.assertIn(msg, result)\n\n def check_debug_print_empty(self, v):\n result = v.debug_print()\n self.assertIn('device: None', result)\n self.assertIn('backend: None', result)\n self.assertIn('shape: None', result)\n self.assertIn('dtype: None', result)\n self.assertIn('statistics: None', result)\n self.assertIn('grad: None', result)\n\n def test_debug_print_cpu(self):\n v = chainer.Variable(self.arr)\n result = v.debug_print()\n self.assertIn('device: CPU', result)\n self.assertIn('numpy.ndarray', result)\n\n self.check_debug_print(v, mean=float(np.mean(v.data)),\n std=float(np.std(v.data)))\n\n @attr.gpu\n def test_debug_print_gpu(self):\n v = chainer.Variable(self.arr)\n v.to_gpu(0)\n\n result = v.debug_print()\n self.assertIn('device: <CUDA Device 0>', result)\n self.assertIn('cupy.core.core.ndarray', result)\n\n self.check_debug_print(v, mean=float(cuda.cupy.mean(v.data)),\n std=float(cuda.cupy.std(v.data)))\n\n def test_debug_print_empty(self):\n v = chainer.Variable()\n self.check_debug_print_empty(v)\n\n\nclass TestVariableSetCreator(unittest.TestCase):\n\n class MockFunction(chainer.Function):\n pass\n\n def setUp(self):\n self.x = np.random.uniform(-1, 1, (2, 5)).astype(np.float32)\n self.f = self.MockFunction()\n self.node = self.f.node\n self.node.rank = 10\n\n def check_set_creator(self, x):\n x = chainer.Variable(x)\n x.set_creator(self.f)\n self.assertEqual(x.creator, self.f)\n self.assertEqual(x.rank, 11)\n\n def test_set_creator_cpu(self):\n self.check_set_creator(self.x)\n\n @attr.gpu\n def test_set_creator_gpu(self):\n self.check_set_creator(cuda.to_gpu(self.x))\n\n def check_set_creator_node(self, x):\n x = chainer.Variable(x)\n x.set_creator_node(self.node)\n self.assertEqual(x.creator_node, self.node)\n self.assertEqual(x.rank, 11)\n\n def test_set_creator_node_cpu(self):\n self.check_set_creator_node(self.x)\n\n @attr.gpu\n def test_set_creator_node_gpu(self):\n self.check_set_creator_node(cuda.to_gpu(self.x))\n\n\nclass TestVariableBackwardError(unittest.TestCase):\n\n def setUp(self):\n self.x = np.array([1], np.float32)\n\n def check_type_mismatch(self, x_data):\n xp = cuda.get_array_module(x_data)\n\n class DummyFunction(chainer.Function):\n label = 'dummy_function'\n\n def forward(self, inputs):\n return xp.array(1, np.float32),\n\n def backward(self, inputs, grads):\n return [1]\n\n x = chainer.Variable(x_data)\n y = DummyFunction()(x)\n with six.assertRaisesRegex(self, TypeError, 'dummy_function'):\n y.backward()\n\n def test_type_mismatch_cpu(self):\n self.check_type_mismatch(self.x)\n\n @attr.gpu\n def test_type_mismatch_gpu(self):\n self.check_type_mismatch(cuda.to_gpu(self.x))\n\n def check_dtype_mismatch(self, x_data):\n xp = cuda.get_array_module(x_data)\n\n class DummyFunction(chainer.Function):\n label = 'dummy_function'\n\n def forward(self, inputs):\n return xp.array(1, np.float32),\n\n def backward(self, inputs, grads):\n return xp.array([1], np.int32),\n\n x = chainer.Variable(x_data)\n y = DummyFunction()(x)\n with six.assertRaisesRegex(self, TypeError, 'dummy_function'):\n y.backward()\n\n def test_dtype_mismatch_cpu(self):\n self.check_dtype_mismatch(self.x)\n\n @attr.gpu\n def test_dtype_mismatch_gpu(self):\n self.check_dtype_mismatch(cuda.to_gpu(self.x))\n\n def check_shape_mismatch(self, x_data):\n xp = cuda.get_array_module(x_data)\n\n class DummyFunction(chainer.Function):\n label = 'dummy_function'\n\n def forward(self, inputs):\n return xp.array(1, np.float32),\n\n def backward(self, inputs, grads):\n return xp.array([1, 2], np.float32),\n\n x = chainer.Variable(x_data)\n y = DummyFunction()(x)\n with six.assertRaisesRegex(self, ValueError, 'dummy_function'):\n y.backward()\n\n def test_shape_mismatch_cpu(self):\n self.check_shape_mismatch(self.x)\n\n @attr.gpu\n def test_shape_mismatch_gpu(self):\n self.check_shape_mismatch(cuda.to_gpu(self.x))\n\n\nclass TestVariableBackwardErrorTraceback(unittest.TestCase):\n\n def setUp(self):\n self.x = np.array([1], np.float32)\n chainer.set_debug(True)\n\n def tearDown(self):\n chainer.set_debug(False)\n\n def check_traceback(self, x_data):\n xp = cuda.get_array_module(x_data)\n\n class DummyFunction(chainer.Function):\n label = 'dummy_function'\n\n def forward(self, inputs):\n return xp.array(1, np.float32),\n\n def backward(self, inputs, grads):\n return xp.array([1, 2], np.float32),\n\n x = chainer.Variable(x_data)\n line = inspect.currentframe().f_lineno + 1\n y = DummyFunction()(x) # `line` is THIS line\n try:\n y.backward()\n self.fail()\n except ValueError as e:\n self.assertIn('Stacktrace', str(e))\n self.assertIn('line %d' % line, str(e))\n\n def test_traceback_cpu(self):\n self.check_traceback(self.x)\n\n @attr.gpu\n def test_traceback_gpu(self):\n self.check_traceback(cuda.to_gpu(self.x))\n\n def test_raise(self):\n x = np.array([1], np.float32)\n x = chainer.Variable(x)\n y = F.identity(x)\n y.grad = np.array([np.nan], np.float32)\n with self.assertRaises(RuntimeError):\n y.backward()\n\n def test_int(self):\n x = np.array([1], np.int)\n x = chainer.Variable(x)\n y = F.identity(x)\n y.grad = np.array([0], np.int)\n y.backward()\n\n\[email protected](*testing.product({\n 'in_shape': [(4, 3, 2)],\n 'out_shape': [(2, 2, 6), (2, -1, 6), 24, (-1,), [2, 12]],\n 'dtype': [np.float16, np.float32, np.float64],\n}))\nclass TestReshape(unittest.TestCase):\n\n def setUp(self):\n self.x = np.random.uniform(-1, 1, self.in_shape).astype(self.dtype)\n\n def check_forward(self, x_data):\n shape = self.out_shape\n x = chainer.Variable(x_data)\n y = x.reshape(shape)\n self.assertEqual(y.data.dtype, self.dtype)\n self.assertTrue((self.x.reshape(shape) == cuda.to_cpu(y.data)).all())\n\n def test_forward_cpu(self):\n self.check_forward(self.x)\n\n @attr.gpu\n def test_forward_gpu(self):\n self.check_forward(cuda.to_gpu(self.x))\n\n def check_backward(self, x_data):\n x = chainer.Variable(x_data)\n y = x.reshape(self.out_shape)\n y.grad = y.data\n y.backward()\n testing.assert_allclose(x.data, x.grad, atol=0, rtol=0)\n\n def test_backward_cpu(self):\n self.check_backward(self.x)\n\n @attr.gpu\n def test_backward_gpu(self):\n self.check_backward(cuda.to_gpu(self.x))\n\n\[email protected](*testing.product({\n 'in_shape': [(4, 3, 2)],\n 'axes': [[], [(-1, 0, 1)], [[-1, 0, 1]], [None], [-1, 0, 1]],\n 'dtype': [np.float16, np.float32, np.float32],\n}))\nclass TestTranspose(unittest.TestCase):\n\n def setUp(self):\n self.x = np.random.uniform(-1, 1, self.in_shape).astype(self.dtype)\n\n def check_forward(self, x_data):\n axes = self.axes\n x = chainer.Variable(x_data)\n y = x.transpose(*axes)\n self.assertEqual(y.data.dtype, self.dtype)\n self.assertTrue((self.x.transpose(*axes) == cuda.to_cpu(y.data)).all())\n\n def test_forward_cpu(self):\n self.check_forward(self.x)\n\n @attr.gpu\n def test_forward_gpu(self):\n self.check_forward(cuda.to_gpu(self.x))\n\n def check_backward(self, x_data):\n x = chainer.Variable(x_data)\n y = x.transpose(*self.axes)\n y.grad = y.data\n y.backward()\n testing.assert_allclose(x.data, x.grad, atol=0, rtol=0)\n\n def test_backward_cpu(self):\n self.check_backward(self.x)\n\n @attr.gpu\n def test_backward_gpu(self):\n self.check_backward(cuda.to_gpu(self.x))\n\n\nclass UnnamedVariableToStringTestBase(object):\n\n def setUp(self):\n if self.x_shape is None:\n self.x = chainer.Variable()\n else:\n x = np.empty(self.x_shape)\n x = np.arange(x.size).reshape(self.x_shape)\n x = x.astype(self.dtype)\n self.x = chainer.Variable(x)\n\n def test_repr_cpu(self):\n self.assertEqual(repr(self.x), self.repr)\n\n def test_str_cpu(self):\n self.assertEqual(str(self.x), self.str)\n\n @attr.gpu\n def test_repr_gpu(self):\n self.x.to_gpu()\n self.assertEqual(repr(self.x), self.repr)\n\n @attr.gpu\n def test_str_gpu(self):\n self.x.to_gpu()\n self.assertEqual(str(self.x), self.str)\n\n\[email protected](\n {'x_shape': None, 'dtype': None, 'repr': 'variable(None)',\n 'str': 'variable(None)'},\n {'x_shape': (2, 2,), 'dtype': np.float16,\n 'repr': 'variable([[ 0., 1.],\\n [ 2., 3.]])',\n 'str': 'variable([[ 0. 1.]\\n [ 2. 3.]])'},\n {'x_shape': (2, 2,), 'dtype': np.float32,\n 'repr': 'variable([[ 0., 1.],\\n [ 2., 3.]])',\n 'str': 'variable([[ 0. 1.]\\n [ 2. 3.]])'},\n {'x_shape': (2, 2,), 'dtype': np.float64,\n 'repr': 'variable([[ 0., 1.],\\n [ 2., 3.]])',\n 'str': 'variable([[ 0. 1.]\\n [ 2. 3.]])'},\n {'x_shape': (3,), 'dtype': np.float32,\n 'repr': 'variable([ 0., 1., 2.])', 'str': 'variable([ 0. 1. 2.])'},\n)\[email protected]_requires('numpy<1.14')\nclass TestUnnamedVariableToStringLegacy(\n UnnamedVariableToStringTestBase, unittest.TestCase):\n # Textual representation of arrays in NumPy 1.13 or earlier.\n pass\n\n\[email protected](\n {'x_shape': None, 'dtype': None, 'repr': 'variable(None)',\n 'str': 'variable(None)'},\n {'x_shape': (2, 2,), 'dtype': np.float16,\n 'repr': 'variable([[0., 1.],\\n [2., 3.]])',\n 'str': 'variable([[0. 1.]\\n [2. 3.]])'},\n {'x_shape': (2, 2,), 'dtype': np.float32,\n 'repr': 'variable([[0., 1.],\\n [2., 3.]])',\n 'str': 'variable([[0. 1.]\\n [2. 3.]])'},\n {'x_shape': (2, 2,), 'dtype': np.float64,\n 'repr': 'variable([[0., 1.],\\n [2., 3.]])',\n 'str': 'variable([[0. 1.]\\n [2. 3.]])'},\n {'x_shape': (3,), 'dtype': np.float32,\n 'repr': 'variable([0., 1., 2.])', 'str': 'variable([0. 1. 2.])'},\n)\[email protected]_requires('numpy>=1.14')\nclass TestUnnamedVariableToStringModern(\n UnnamedVariableToStringTestBase, unittest.TestCase):\n # Textual representation of arrays in NumPy 1.14 or later.\n pass\n\n\nclass TestUnnamedVariableDim2Size0ToString(unittest.TestCase):\n\n def setUp(self):\n x = np.empty((0, 0))\n x = x.astype(np.float32)\n self.x = chainer.Variable(x)\n if (sys.version_info < (3,) and sys.maxsize > 2**32 and\n platform.system() == 'Windows'):\n self.repr = 'variable([], shape=(0L, 0L))'\n else:\n self.repr = 'variable([], shape=(0, 0))'\n self.str = 'variable([])'\n\n def test_repr_cpu(self):\n self.assertEqual(repr(self.x), self.repr)\n\n def test_str_cpu(self):\n self.assertEqual(str(self.x), self.str)\n\n @attr.gpu\n def test_repr_gpu(self):\n self.x.to_gpu()\n self.assertEqual(repr(self.x), self.repr)\n\n @attr.gpu\n def test_str_gpu(self):\n self.x.to_gpu()\n self.assertEqual(str(self.x), self.str)\n\n\nclass NamedVariableToStringTestBase(object):\n\n def setUp(self):\n if self.x_shape is None:\n self.x = chainer.Variable(name='x')\n else:\n x = np.empty(self.x_shape)\n x = np.arange(x.size).reshape(self.x_shape)\n x = x.astype(self.dtype)\n self.x = chainer.Variable(x, name='x')\n\n def test_named_repr(self):\n self.assertEqual(repr(self.x), self.repr)\n\n def test_named_str(self):\n self.assertEqual(str(self.x), self.str)\n\n @attr.gpu\n def test_repr_gpu(self):\n self.x.to_gpu()\n self.assertEqual(repr(self.x), self.repr)\n\n @attr.gpu\n def test_str_gpu(self):\n self.x.to_gpu()\n self.assertEqual(str(self.x), self.str)\n\n\[email protected](\n {'x_shape': None, 'dtype': None, 'repr': 'variable x(None)',\n 'str': 'variable x(None)'},\n {'x_shape': (2, 2,), 'dtype': np.float32,\n 'repr': 'variable x([[ 0., 1.],\\n [ 2., 3.]])',\n 'str': 'variable x([[ 0. 1.]\\n [ 2. 3.]])'},\n {'x_shape': (), 'dtype': np.float32,\n 'repr': 'variable x(0.0)', 'str': 'variable x(0.0)'},\n)\[email protected]_requires('numpy<1.14')\nclass TestNamedVariableToStringLegacy(\n NamedVariableToStringTestBase, unittest.TestCase):\n # Textual representation of arrays in NumPy 1.13 or earlier.\n pass\n\n\[email protected](\n {'x_shape': None, 'dtype': None, 'repr': 'variable x(None)',\n 'str': 'variable x(None)'},\n {'x_shape': (2, 2,), 'dtype': np.float32,\n 'repr': 'variable x([[0., 1.],\\n [2., 3.]])',\n 'str': 'variable x([[0. 1.]\\n [2. 3.]])'},\n {'x_shape': (), 'dtype': np.float32,\n 'repr': 'variable x(0.)', 'str': 'variable x(0.)'},\n)\[email protected]_requires('numpy>=1.14')\nclass TestNamedVariableToStringModern(\n NamedVariableToStringTestBase, unittest.TestCase):\n # Textual representation of arrays in NumPy 1.14 or later.\n pass\n\n\nclass TestNamedVariableDim2Size0ToString(unittest.TestCase):\n\n def setUp(self):\n x = np.empty((0, 0))\n x = x.astype(np.float32)\n self.x = chainer.Variable(x, name='x')\n if (sys.version_info < (3,) and sys.maxsize > 2**32 and\n platform.system() == 'Windows'):\n self.repr = 'variable x([], shape=(0L, 0L))'\n else:\n self.repr = 'variable x([], shape=(0, 0))'\n self.str = 'variable x([])'\n\n def test_named_repr(self):\n self.assertEqual(repr(self.x), self.repr)\n\n def test_named_str(self):\n self.assertEqual(str(self.x), self.str)\n\n @attr.gpu\n def test_repr_gpu(self):\n self.x.to_gpu()\n self.assertEqual(repr(self.x), self.repr)\n\n @attr.gpu\n def test_str_gpu(self):\n self.x.to_gpu()\n self.assertEqual(str(self.x), self.str)\n\n\nclass IdentityFunction(chainer.Function):\n\n def forward(self, inputs):\n return inputs\n\n def backward(self, inputs, grad_outputs):\n return grad_outputs\n\n\nclass TestVariableDoubleBackward(unittest.TestCase):\n\n def test_default_backward(self):\n x = chainer.Variable(np.empty(1, np.float32))\n y = F.identity(x)\n y.backward()\n self.assertIsNone(x.grad_var.creator)\n x.grad_var.backward()\n self.assertIsNone(y.grad_var.grad_var)\n\n def test_raise_double_backprop(self):\n x = chainer.Variable(np.empty(1, np.float32))\n y = IdentityFunction()(x)\n y.backward(enable_double_backprop=True)\n with self.assertRaises(RuntimeError):\n x.grad_var.backward()\n\n def test_raise_double_backprop_2(self):\n x = chainer.Variable(np.empty(1, np.float32))\n z = F.identity(x) # new style\n y = IdentityFunction()(z) # old style\n y.backward(enable_double_backprop=True)\n with self.assertRaises(RuntimeError):\n x.grad_var.backward()\n\n\nclass TestAsVariable(unittest.TestCase):\n\n def check_to_variable_from_array(self, x):\n y = chainer.as_variable(x)\n self.assertIsInstance(y, chainer.Variable)\n self.assertIs(y.data, x)\n self.assertFalse(y.requires_grad)\n\n def test_to_variable_from_numpy(self):\n self.check_to_variable_from_array(np.empty(1, np.float32))\n\n @attr.gpu\n def test_to_variable_from_cupy(self):\n self.check_to_variable_from_array(cuda.cupy.empty(1, np.float32))\n\n def test_to_variable_from_variable(self):\n x = chainer.Variable(np.array(1, np.float32))\n y = chainer.as_variable(x)\n self.assertIs(x, y)\n self.assertTrue(y.requires_grad)\n\n\[email protected](*testing.product({\n 'in_shape': [(4, 3, 2)],\n 'dtype': [np.float16, np.float32, np.float64],\n 'loss_scale': [None, 1, 10],\n}))\nclass TestLossScale(unittest.TestCase):\n\n def setUp(self):\n self.x = np.random.uniform(-1, 1, self.in_shape).astype(self.dtype)\n self.y = np.random.uniform(-1, 1, self.in_shape).astype(self.dtype)\n\n def check_loss_scale(self, x_data, y_data):\n x = chainer.Variable(x_data)\n y = chainer.Variable(y_data)\n z = x * y\n loss = F.sum(z)\n loss.backward(loss_scale=self.loss_scale)\n if self.loss_scale is not None:\n x.grad /= self.loss_scale\n y.grad /= self.loss_scale\n rtol, atol = 1e-4, 1e-5\n if self.dtype is np.float16:\n rtol, atol = 1e-1, 1e-2\n testing.assert_allclose(x.data, y.grad, rtol=rtol, atol=atol)\n testing.assert_allclose(y.data, x.grad, rtol=rtol, atol=atol)\n\n def test_loss_scale_cpu(self):\n self.check_loss_scale(self.x, self.y)\n\n @attr.gpu\n def test_loss_scale_gpu(self):\n self.check_loss_scale(cuda.to_gpu(self.x), cuda.to_gpu(self.y))\n\n\ntesting.run_module(__name__, __file__)\n" ]
[ [ "numpy.full", "numpy.array", "numpy.ones_like", "numpy.empty", "numpy.zeros_like", "numpy.zeros", "numpy.random.rand", "numpy.testing.assert_array_equal", "numpy.ones", "numpy.random.randn", "numpy.mean", "numpy.ndarray", "numpy.float32", "numpy.prod", "numpy.random.uniform", "numpy.std", "numpy.arange" ] ]
rgerkin/Scoreboard
[ "e072c8cecc1160509a1d2549a0185d6eba234001" ]
[ "Scoreboard19/datagrab.py" ]
[ "\"\"\"Functions for getting and analyzing data.\"\"\"\n\nimport scipy.interpolate\nimport pandas as pd\nimport numpy as np\nfrom datetime import date, datetime, timedelta\nimport os\nfrom urllib.parse import quote\nfrom . import paths\n\n\ndef read_observed(kind, writetocsv: bool = False, use_cache: bool = False)-> pd.DataFrame:\n \"\"\"Read US cumulative cases or deaths from covid19-forecast-hub\n Args:\n use_cache (bool), if True use previously written csv file\n writetocsv (bool), if True writes pd to US_deaths.csv\n Returns:\n US_deaths (pd dataframe) \n \"\"\" \n assert kind in ['cases', 'deaths']\n file_path = paths.data_dir / ('US_%s.csv' % kind)\n if use_cache:\n weekly = pd.read_csv(file_path, index_col=0, parse_dates=['DateObserved'])\n return weekly\n \n #Read Observed\n address = \"raw.githubusercontent.com/reichlab/covid19-forecast-hub/master/data-truth/truth-Cumulative %s.csv\"\n address = \"http://\" + quote(address % kind.title())\n df = pd.read_csv(address,\n dtype = {'location': str}, parse_dates=['date'],\n na_values = ['NA', 'no info', '.'])\n df = df[(df['location_name'] == 'US')]\n df.drop(columns=['location', 'location_name'], inplace=True)\n df.columns = ['DateObserved', kind.title()]\n df.reset_index(drop=True, inplace=True)\n \n #Convert from daily to weekly measured from Sun-Sat\n weekly = df.iloc[np.arange(df[df[\"DateObserved\"]==\"2020-01-25\"].index[0],\n len(df), 7)].copy()\n weekly[kind.title()] = weekly[kind.title()].diff()\n weekly.reset_index(drop=True, inplace=True)\n \n if writetocsv == True:\n weekly.to_csv(file_path) \n \n return weekly\n\n\ndef getmodeltypes(Scoreboard, quiet=False)-> pd.DataFrame:\n uniques = Scoreboard.model.unique()\n modeltypes = pd.read_csv('../Data/modeltypes.dat')\n modeltypes['model'] = modeltypes['model'].str.strip()\n modeltypes['modeltype'] = modeltypes['modeltype'].str.strip()\n \n if not quiet:\n print('================================')\n print('Unique models in the scoreboard:')\n for i in range(0,len(uniques)):\n print(str(i)+'. '+uniques[i])\n print('========================================================')\n print(\"Models in the latest Scoreboard that are not yet in modeltypes.dat:\")\n print(np.setdiff1d(np.sort(Scoreboard.model.drop_duplicates()), modeltypes.model))\n print(\"Edit modeltypes.dat accordingly\")\n return modeltypes" ]
[ [ "pandas.read_csv" ] ]
asuiconlab/psiz
[ "4f05348cf43d2d53ff9cc6dee633de385df883e3" ]
[ "examples/rank/vi_3ge.py" ]
[ "# -*- coding: utf-8 -*-\n# Copyright 2020 The PsiZ Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ============================================================================\n\"\"\"Example that infers a shared embedding for three groups.\n\nFake data is generated from a ground truth model for three different\ngroups. In this example, these groups represent groups of agents with\nvarying levels of skill: novices, intermediates, and experts. Each group\nhas a different set of attention weights. An embedding model is\ninferred from the simulated data and compared to the ground truth\nmodel.\n\nResults are saved in the directory specified by `fp_example`. By\ndefault, a `psiz_examples` directory is created in your home directory.\n\nExample output:\n\n Restart Summary\n n_valid_restart 1 | total_duration: 2104 s\n best | n_epoch: 999 | val_loss: 3.0700\n mean ±stddev | n_epoch: 999 ±0 | val_loss: 3.0700 ±0.0000 |\n 2088 ±0 s | 2090 ±0 ms/epoch\n\n Model Comparison (R^2)\n ================================\n True | Inferred\n | Novice Interm Expert\n --------+-----------------------\n Novice | 0.94 0.67 0.06\n Interm | 0.55 0.87 0.35\n Expert | 0.09 0.42 0.85\n\n\"\"\"\n\nimport copy\nimport os\nfrom pathlib import Path\nimport shutil\n\nimport imageio\nimport matplotlib\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport tensorflow as tf\nimport tensorflow_probability as tfp\n\nimport psiz\n\n# Uncomment the following line to force eager execution.\n# tf.config.experimental_run_functions_eagerly(True)\n\n# Modify the following to control GPU visibility.\nos.environ[\"CUDA_DEVICE_ORDER\"] = \"PCI_BUS_ID\"\nos.environ[\"CUDA_VISIBLE_DEVICES\"] = \"0\"\n\n\ndef main():\n \"\"\"Run script.\"\"\"\n # Settings.\n fp_example = Path.home() / Path('psiz_examples', 'rank', 'vi_3ge')\n fp_board = fp_example / Path('logs', 'fit')\n n_stimuli = 30\n n_dim = 3\n n_group = 3\n n_trial = 2000\n epochs = 1000\n n_restart = 1\n batch_size = 128\n n_frame = 1\n\n # Directory preparation.\n fp_example.mkdir(parents=True, exist_ok=True)\n # Remove existing TensorBoard logs.\n if fp_board.exists():\n shutil.rmtree(fp_board)\n\n # Plot settings.\n small_size = 6\n medium_size = 8\n large_size = 10\n plt.rc('font', size=small_size) # controls default text sizes\n plt.rc('axes', titlesize=medium_size)\n plt.rc('axes', labelsize=small_size)\n plt.rc('xtick', labelsize=small_size)\n plt.rc('ytick', labelsize=small_size)\n plt.rc('legend', fontsize=small_size)\n plt.rc('figure', titlesize=large_size)\n\n model_true = ground_truth(n_stimuli, n_group)\n proxy_true = psiz.models.Proxy(model=model_true)\n\n # Generate a random docket of trials to show each group.\n generator = psiz.generators.RandomRank(\n n_stimuli, n_reference=8, n_select=2\n )\n docket = generator.generate(n_trial)\n\n # Create virtual agents for each group.\n agent_novice = psiz.agents.RankAgent(proxy_true.model, group_id=0)\n agent_interm = psiz.agents.RankAgent(proxy_true.model, group_id=1)\n agent_expert = psiz.agents.RankAgent(proxy_true.model, group_id=2)\n\n # Simulate similarity judgments for each group.\n obs_novice = agent_novice.simulate(docket)\n obs_interm = agent_interm.simulate(docket)\n obs_expert = agent_expert.simulate(docket)\n obs = psiz.trials.stack((obs_novice, obs_interm, obs_expert))\n\n # Compute ground truth similarity matrices.\n def truth_sim_func0(z_q, z_ref):\n return proxy_true.similarity(z_q, z_ref, group_id=0)\n\n def truth_sim_func1(z_q, z_ref):\n return proxy_true.similarity(z_q, z_ref, group_id=1)\n\n def truth_sim_func2(z_q, z_ref):\n return proxy_true.similarity(z_q, z_ref, group_id=2)\n\n simmat_truth = (\n psiz.utils.pairwise_matrix(truth_sim_func0, proxy_true.z[0]),\n psiz.utils.pairwise_matrix(truth_sim_func1, proxy_true.z[0]),\n psiz.utils.pairwise_matrix(truth_sim_func2, proxy_true.z[0])\n )\n\n # Partition observations into 80% train, 10% validation and 10% test set.\n obs_train, obs_val, obs_test = psiz.utils.standard_split(obs)\n\n compile_kwargs = {\n 'loss': tf.keras.losses.CategoricalCrossentropy(),\n 'optimizer': tf.keras.optimizers.Adam(lr=.001),\n 'weighted_metrics': [\n tf.keras.metrics.CategoricalCrossentropy(name='cce')\n ]\n }\n\n # Infer independent models with increasing amounts of data.\n if n_frame == 1:\n n_obs = np.array([obs_train.n_trial], dtype=int)\n else:\n n_obs = np.round(\n np.linspace(15, obs_train.n_trial, n_frame)\n ).astype(np.int64)\n r2 = np.empty([n_frame, n_group, n_group]) * np.nan\n train_loss = np.empty((n_frame)) * np.nan\n val_loss = np.empty((n_frame)) * np.nan\n test_loss = np.empty((n_frame)) * np.nan\n for i_frame in range(n_frame):\n include_idx = np.arange(0, n_obs[i_frame])\n obs_round_train = obs_train.subset(include_idx)\n print(\n '\\n Frame {0} ({1} obs)'.format(i_frame, obs_round_train.n_trial)\n )\n\n # Define model.\n model = build_model(n_stimuli, n_dim, n_group, obs_round_train.n_trial)\n proxy_inferred = psiz.models.Proxy(model=model)\n\n # Define callbacks.\n fp_board_frame = fp_board / Path('frame_{0}'.format(i_frame))\n cb_board = psiz.keras.callbacks.TensorBoardRe(\n log_dir=fp_board_frame, histogram_freq=0,\n write_graph=False, write_images=False, update_freq='epoch',\n profile_batch=0, embeddings_freq=0, embeddings_metadata=None\n )\n cb_early = psiz.keras.callbacks.EarlyStoppingRe(\n 'loss', patience=100, mode='min', restore_best_weights=False,\n verbose=1\n )\n callbacks = [cb_board, cb_early]\n\n # Infer model.\n restart_record = proxy_inferred.fit(\n obs_round_train, validation_data=obs_val, epochs=epochs,\n batch_size=batch_size, callbacks=callbacks, n_restart=n_restart,\n monitor='val_loss', verbose=1, compile_kwargs=compile_kwargs\n )\n\n train_loss[i_frame] = restart_record.record['loss'][0]\n val_loss[i_frame] = restart_record.record['val_loss'][0]\n\n tf.keras.backend.clear_session()\n proxy_inferred.model.n_sample = 100\n proxy_inferred.compile(**compile_kwargs)\n test_metrics = proxy_inferred.evaluate(\n obs_test, verbose=0, return_dict=True\n )\n test_loss[i_frame] = test_metrics['loss']\n\n z = proxy_inferred.model.stimuli.embeddings.mode().numpy()\n if proxy_inferred.model.stimuli.mask_zero:\n z = z[:, 1:, :]\n\n # Compare the inferred model with ground truth by comparing the\n # similarity matrices implied by each model.\n def infer_sim_func(z_q, z_ref):\n return proxy_inferred.similarity(z_q, z_ref)\n\n simmat_infer = (\n psiz.utils.pairwise_matrix(infer_sim_func, z[0]),\n psiz.utils.pairwise_matrix(infer_sim_func, z[1]),\n psiz.utils.pairwise_matrix(infer_sim_func, z[2])\n )\n for i_truth in range(n_group):\n for j_infer in range(n_group):\n r2[i_frame, i_truth, j_infer] = psiz.utils.matrix_comparison(\n simmat_truth[i_truth], simmat_infer[j_infer],\n score='r2'\n )\n\n # Display comparison results. A good inferred model will have a high\n # R^2 value on the diagonal elements (max is 1) and relatively low R^2\n # values on the off-diagonal elements.\n print('\\n Model Comparison (R^2)')\n print(' ================================')\n print(' True | Inferred')\n print(' | Novice Interm Expert')\n print(' --------+-----------------------')\n print(' Novice | {0: >6.2f} {1: >6.2f} {2: >6.2f}'.format(\n r2[i_frame, 0, 0], r2[i_frame, 0, 1], r2[i_frame, 0, 2]))\n print(' Interm | {0: >6.2f} {1: >6.2f} {2: >6.2f}'.format(\n r2[i_frame, 1, 0], r2[i_frame, 1, 1], r2[i_frame, 1, 2]))\n print(' Expert | {0: >6.2f} {1: >6.2f} {2: >6.2f}'.format(\n r2[i_frame, 2, 0], r2[i_frame, 2, 1], r2[i_frame, 2, 2]))\n print('\\n')\n\n # Create and save visual frame.\n fig0 = plt.figure(figsize=(12, 5), dpi=200)\n plot_frame(\n fig0, n_obs, train_loss, val_loss, test_loss, r2, proxy_true,\n proxy_inferred, i_frame\n )\n fname = fp_example / Path('frame_{0}.tiff'.format(i_frame))\n plt.savefig(\n os.fspath(fname), format='tiff', bbox_inches=\"tight\", dpi=300\n )\n\n # Create animation.\n if n_frame > 1:\n frames = []\n for i_frame in range(n_frame):\n fname = fp_example / Path('frame_{0}.tiff'.format(i_frame))\n frames.append(imageio.imread(fname))\n imageio.mimwrite(fp_example / Path('evolution.gif'), frames, fps=1)\n\n\ndef ground_truth(n_stimuli, n_group):\n \"\"\"Return a ground truth embedding.\"\"\"\n n_dim = 4\n embedding = tf.keras.layers.Embedding(\n n_stimuli+1, n_dim, mask_zero=True,\n embeddings_initializer=tf.keras.initializers.RandomNormal(\n stddev=.17, seed=58\n )\n )\n stimuli = psiz.keras.layers.Stimuli(embedding=embedding)\n kernel = psiz.keras.layers.AttentionKernel(\n group_level=1,\n distance=psiz.keras.layers.WeightedMinkowski(\n rho_initializer=tf.keras.initializers.Constant(2.),\n trainable=False,\n ),\n attention=psiz.keras.layers.GroupAttention(\n n_dim=n_dim, n_group=n_group\n ),\n similarity=psiz.keras.layers.ExponentialSimilarity(\n tau_initializer=tf.keras.initializers.Constant(1.),\n gamma_initializer=tf.keras.initializers.Constant(0.),\n trainable=False,\n )\n )\n kernel.attention.embeddings.assign(\n np.array((\n (1.8, 1.8, .2, .2),\n (1., 1., 1., 1.),\n (.2, .2, 1.8, 1.8)\n ))\n )\n model = psiz.models.Rank(stimuli=stimuli, kernel=kernel)\n return model\n\n\ndef build_model(n_stimuli, n_dim, n_group, n_obs_train):\n \"\"\"Build model.\n\n Arguments:\n n_stimuli: Integer indicating the number of stimuli in the\n embedding.\n n_dim: Integer indicating the dimensionality of the embedding.\n n_group: Integer indicating the number of groups.\n n_obs_train: Integer indicating the number of training\n observations. Used to determine KL weight for variational\n inference.\n\n Returns:\n model: A TensorFlow Keras model.\n\n \"\"\"\n kl_weight = 1. / n_obs_train\n prior_scale = .2\n\n n_source_embeddings = n_group * (n_stimuli + 1)\n embedding_posterior = psiz.keras.layers.EmbeddingNormalDiag(\n n_source_embeddings, n_dim, mask_zero=True,\n scale_initializer=tf.keras.initializers.Constant(\n tfp.math.softplus_inverse(prior_scale).numpy()\n )\n )\n embedding_prior = psiz.keras.layers.EmbeddingShared(\n n_source_embeddings, n_dim, mask_zero=True,\n embedding=psiz.keras.layers.EmbeddingNormalDiag(\n 1, 1,\n loc_initializer=tf.keras.initializers.Constant(0.),\n scale_initializer=tf.keras.initializers.Constant(\n tfp.math.softplus_inverse(prior_scale).numpy()\n ),\n loc_trainable=False\n )\n )\n embedding_variational = psiz.keras.layers.EmbeddingVariational(\n posterior=embedding_posterior, prior=embedding_prior,\n kl_weight=kl_weight, kl_n_sample=30\n )\n stimuli = psiz.keras.layers.Stimuli(\n embedding=embedding_variational, group_level=1, n_group=n_group\n )\n\n kernel = psiz.keras.layers.Kernel(\n distance=psiz.keras.layers.WeightedMinkowski(\n rho_initializer=tf.keras.initializers.Constant(2.),\n trainable=False,\n ),\n similarity=psiz.keras.layers.ExponentialSimilarity(\n beta_initializer=tf.keras.initializers.Constant(10.),\n tau_initializer=tf.keras.initializers.Constant(1.),\n gamma_initializer=tf.keras.initializers.Constant(0.),\n trainable=False\n )\n )\n model = psiz.models.Rank(\n stimuli=stimuli, kernel=kernel, n_sample=1\n )\n return model\n\n\ndef plot_frame(\n fig0, n_obs, train_loss, val_loss, test_loss, r2, proxy_true,\n proxy_inferred, i_frame):\n \"\"\"Plot posteriors.\"\"\"\n # Settings.\n group_labels = ['Novice', 'Intermediate', 'Expert']\n\n n_group = proxy_inferred.model.stimuli.n_group\n n_dim = proxy_inferred.model.n_dim\n\n gs = fig0.add_gridspec(n_group + 1, 4)\n\n f0_ax0 = fig0.add_subplot(gs[0, 0:2])\n plot_loss(f0_ax0, n_obs, train_loss, val_loss, test_loss)\n\n f0_ax1 = fig0.add_subplot(gs[0, 2])\n plot_convergence(fig0, f0_ax1, n_obs, r2[i_frame])\n\n gs.tight_layout(fig0)\n\n\ndef plot_logitnormal(ax, dist, name=None, c=None):\n \"\"\"Plot univariate distribution.\n\n Arguments:\n ax:\n dist:\n name:\n\n \"\"\"\n if name is None:\n name = 'x'\n\n x = np.linspace(.001, .999, 1000)\n y = dist.prob(x)\n\n # Determine mode from samples.\n idx = np.argmax(y)\n x_mode = x[idx]\n\n ax.plot(x, y, c=c)\n ax.text(x_mode, .75 * np.max(y), '{0:.2f}'.format(x_mode))\n ax.set_xlabel(r'${0}$'.format(name))\n ax.set_ylabel(r'$p({0})$'.format(name))\n ax.set_xlim([0, 1])\n ax.set_xticks([0, 1])\n ax.set_xticklabels([0, 1])\n\n\ndef plot_loss(ax, n_obs, train_loss, val_loss, test_loss):\n \"\"\"Plot loss.\"\"\"\n # Settings\n ms = 2\n\n ax.plot(n_obs, train_loss, 'bo-', ms=ms, label='Train Loss')\n ax.plot(n_obs, val_loss, 'go-', ms=ms, label='Val. Loss')\n ax.plot(n_obs, test_loss, 'ro-', ms=ms, label='Test Loss')\n ax.set_title('Optimization Objective')\n\n ax.set_xlabel('Trials')\n limits = [0, np.max(n_obs) + 10]\n ax.set_xlim(limits)\n ticks = [np.min(n_obs), np.max(n_obs)]\n ax.set_xticks(ticks)\n\n ax.set_ylabel('Loss')\n ax.legend()\n\n\ndef plot_convergence(fig, ax, n_obs, r2):\n \"\"\"Plot convergence.\"\"\"\n # Settings.\n cmap = matplotlib.cm.get_cmap('Greys')\n labels = ['Nov', 'Int', 'Exp']\n\n im = ax.imshow(r2, cmap=cmap, vmin=0., vmax=1.)\n fig.colorbar(im, ax=ax)\n ax.set_xticks([0, 1, 2])\n ax.set_xticklabels(labels)\n ax.set_yticks([0, 1, 2])\n ax.set_yticklabels(labels)\n ax.set_ylabel('True')\n ax.set_xlabel('Inferred')\n ax.set_title(r'$R^2$ Convergence')\n\n\nif __name__ == \"__main__\":\n main()\n" ]
[ [ "numpy.max", "numpy.array", "numpy.empty", "matplotlib.cm.get_cmap", "numpy.min", "matplotlib.pyplot.rc", "matplotlib.pyplot.figure", "tensorflow.keras.initializers.RandomNormal", "numpy.argmax", "numpy.arange", "tensorflow.keras.losses.CategoricalCrossentropy", "tensorflow.keras.backend.clear_session", "tensorflow.keras.metrics.CategoricalCrossentropy", "numpy.linspace", "tensorflow.keras.optimizers.Adam", "tensorflow.keras.initializers.Constant" ] ]
TarapongSrisongkram/paccmann_kinase_binding_residues
[ "83ae7be5f9883215da41958a8cbdf0a9d6739083" ]
[ "scripts/knn_cv.py" ]
[ "#!/usr/bin/env python3\n\"\"\"\nEvaluate lazy KNN baseline predictor in a Cross-Validation setting.\nAssumes that ligand_fp and kinase_fp contain all molecules and kinases that\nare used in training and testng dataset.\n\n\"\"\"\nimport argparse\nimport json\nimport logging\nimport os\nimport sys\nfrom typing import List\n\nimport numpy as np\nimport pandas as pd\nfrom pkbr.knn import knn\nfrom pytoda.files import read_smi\nfrom scipy.stats import pearsonr, spearmanr\nfrom sklearn.metrics import mean_squared_error\n\n# setup logging\nlogging.basicConfig(stream=sys.stdout, level=logging.DEBUG)\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\n \"-d\",\n \"--data_path\",\n type=str,\n help=\"Path to the folder where the fold-specific data is stored\",\n)\nparser.add_argument(\n \"-tr\",\n \"--train_name\",\n type=str,\n help=\"Name of train files stored _inside_ the fold-specific folders.\"\n \"Needs to have column names as specified in column_names\",\n)\nparser.add_argument(\n \"-te\",\n \"--test_name\",\n type=str,\n help=\"Name of test files stored _inside_ the fold-specific folders\"\n \"Needs to have column names as specified in column_names\",\n)\nparser.add_argument(\n \"-f\",\n \"--num_folds\",\n type=int,\n help=\"Number of folds. Folders should be named fold_0, fold_1 etc. \",\n)\nparser.add_argument(\n \"-lp\", \"--ligand_fp\", type=str, help=\"Path to the ligand data (.smi)\"\n)\nparser.add_argument(\n \"-kp\", \"--kinase_fp\", type=str, help=\"Path to the kinase data (.smi)\"\n)\nparser.add_argument(\n \"-r\", \"--results_path\", type=str, help=\"Path to folder to store results\"\n)\nparser.add_argument(\n \"-k\",\n \"--k\",\n type=int,\n help=(\n \"K for the KNN classification. Note that classification reports are generated\"\n \" for all odd x: 1<= x <= k\"\n ),\n default=25,\n)\nparser.add_argument(\n \"-c\",\n \"--column_names\",\n type=List[str],\n help=\"Columns in train/test files. Order: Name of ligand, name of protein, label\",\n default=[\"ligand_name\", \"uniprot_accession\", \"pIC50\"],\n)\n\n\ndef main(\n # fmt: off\n data_path, train_name, test_name, num_folds, ligand_fp, kinase_fp, results_path, k, \n column_names\n):\n # fmt: on\n logger = logging.getLogger(\"knn_prediction\")\n logging.getLogger(\"matplotlib.font_manager\").disabled = True\n\n rename_dict = {\n column_names[0]: \"ligand_name\",\n column_names[1]: \"sequence_id\",\n column_names[2]: \"label\",\n }\n\n ligands = read_smi(ligand_fp, names=[\"data\"])\n kinases = read_smi(kinase_fp, names=[\"data\"])\n\n # Create right amount of empty lists\n all_results = np.empty((np.ceil(k / 2).astype(int), 0)).tolist()\n\n for fold in range(num_folds):\n train_data = pd.read_csv(\n os.path.join(data_path, f\"fold_{fold}\", train_name), index_col=0\n )[column_names]\n test_data = pd.read_csv(\n os.path.join(data_path, f\"fold_{fold}\", test_name), index_col=0\n )[column_names]\n train_data.rename(columns=rename_dict, inplace=True)\n test_data.rename(columns=rename_dict, inplace=True)\n\n try:\n test_data[\"SMILES\"] = ligands.loc[test_data[\"ligand_name\"]].values\n test_data[\"sequence\"] = kinases.loc[test_data[\"sequence_id\"]].values\n train_data[\"SMILES\"] = ligands.loc[train_data[\"ligand_name\"]].values\n train_data[\"sequence\"] = kinases.loc[train_data[\"sequence_id\"]].values\n except KeyError:\n raise KeyError(\n \"Either colum names in the dataframes are incorrect or\"\n \"some SMILES or AAs were not found in the .smi files.\"\n )\n\n logger.info(f\"Fold {fold}: Data loaded\")\n\n # Classify data\n predictions, knn_labels = knn(\n train_data,\n test_data,\n k=k,\n return_knn_labels=True,\n verbose=False,\n approx=True,\n seq_nns=15,\n result_path=os.path.join(results_path, f\"knn_all_fold_{fold}.csv\"),\n )\n logger.info(f\"Fold {fold}: Predictions done\")\n\n labels = list(test_data[\"label\"].values)\n\n for idx, _k in enumerate(range(k, 0, -2)):\n\n # Overwrite predictions to match _k instead of k\n predictions = [np.mean(sample_knns[:_k]) for sample_knns in knn_labels]\n\n # Compute metrics\n rmse = np.sqrt(mean_squared_error(labels, predictions))\n pearson = pearsonr(labels, predictions)[0]\n spearman = spearmanr(labels, predictions)[0]\n\n # Create and save json\n results = {\"RMSE\": rmse, \"Pearson\": pearson, \"Spearman\": spearman}\n\n # Write data\n os.makedirs(os.path.join(results_path, f\"k{_k}\"), exist_ok=True)\n with open(\n os.path.join(results_path, f\"k{_k}\", f\"fold_{fold}_report.json\"),\n \"w\",\n ) as f:\n json.dump(results, f)\n all_results[idx].append(results)\n\n # Save predictions\n pd.DataFrame({\"labels\": labels, \"predictions\": predictions}).to_csv(\n os.path.join(results_path, f\"k{_k}\", f\"fold_{fold}_results.csv\")\n )\n logger.info(f\"Fold {fold}: Reports generated and saved.\")\n\n # Generate reports across folds\n for idx, _k in enumerate(range(k, 0, -2)):\n df = pd.DataFrame(all_results[idx])\n df.index = range(num_folds)\n df.loc[\"mean\"] = df.mean()\n df.loc[\"std\"] = df.std()\n df.to_csv(os.path.join(results_path, f\"knn_{_k}_cv_results.csv\"))\n\n logger.info(\"Done, shutting down.\")\n\n\nif __name__ == \"__main__\":\n args = parser.parse_args()\n main(\n args.data_path,\n args.train_name,\n args.test_name,\n args.num_folds,\n args.ligand_fp,\n args.kinase_fp,\n args.results_path,\n args.k,\n args.column_names,\n )\n" ]
[ [ "numpy.ceil", "sklearn.metrics.mean_squared_error", "pandas.DataFrame", "scipy.stats.spearmanr", "numpy.mean", "scipy.stats.pearsonr" ] ]
gianscarpe/udacity_deep_reinforcement_learning
[ "c45a95f27f8ebf38afa7fed6f718691ae86d5d46" ]
[ "p3_collab-compet/model.py" ]
[ "import numpy as np\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nclass Actor(nn.Module):\n def __init__(self, state_size, action_size, fc1=256, fc2=128, leak=0.01, seed=0):\n \"\"\" Initialize parameters and build model.\n\n Params\n ======\n state_size (int): Dimension of each state\n action_size (int): Dimension of each action\n seed (int): Random seed\n hidden_size (int): Number of nodes in hidden layers\n leak: amount of leakiness in leaky relu\n \"\"\"\n super(Actor, self).__init__()\n self.leak = leak\n self.seed = torch.manual_seed(seed)\n\n self.fc1 = nn.Linear(state_size, fc1)\n self.fc2 = nn.Linear(fc1, fc2)\n self.fc3 = nn.Linear(fc2, action_size)\n\n self.bn = nn.BatchNorm1d(state_size)\n self.reset_parameters()\n\n def reset_parameters(self):\n \"\"\" Initilaize the weights using He et al (2015) weights \"\"\"\n torch.nn.init.kaiming_normal_(self.fc1.weight.data, a=self.leak, mode='fan_in')\n torch.nn.init.kaiming_normal_(self.fc2.weight.data, a=self.leak, mode='fan_in')\n torch.nn.init.uniform_(self.fc3.weight.data, -3e-3, 3e-3)\n\n def forward(self, state):\n \"\"\"Build an actor (policy) network that maps states -> actions.\"\"\"\n state = self.bn(state)\n x = F.leaky_relu(self.fc1(state), negative_slope=self.leak)\n x = F.leaky_relu(self.fc2(x), negative_slope=self.leak)\n x = torch.tanh(self.fc3(x))\n return x\n\n\nclass Critic(nn.Module):\n def __init__(self, state_size, action_size, fc1=256, fc2=128, fc3=128,\n leak=0.01, seed=0):\n \"\"\"\n Params\n state_size (int): Dimension of each state\n action_size (int): Dimension of each action\n seed (int): Random seed\n fcs1_units (int): Number of nodes in the first hidden layer\n fc2_units (int): Number of nodes in the second hidden layer\n hidden_size:\n \"\"\"\n super(Critic, self).__init__()\n self.leak = leak\n self.seed = torch.manual_seed(seed)\n self.bn = nn.BatchNorm1d(state_size)\n self.fcs1 = nn.Linear(state_size, fc1)\n self.fc2 = nn.Linear(fc1 + action_size, fc2)\n self.fc3 = nn.Linear(fc2, fc3)\n self.fc4 = nn.Linear(fc3, 1)\n self.reset_parameters()\n\n def reset_parameters(self):\n \n torch.nn.init.kaiming_normal_(self.fcs1.weight.data, a=self.leak, mode='fan_in')\n torch.nn.init.kaiming_normal_(self.fc2.weight.data, a=self.leak, mode='fan_in')\n torch.nn.init.uniform_(self.fc3.weight.data, -3e-3, 3e-3)\n\n def forward(self, state, action):\n \"\"\" Build a critic (value) network that maps (state, action) pairs -> Q-values.\"\"\"\n state = self.bn(state)\n x = F.leaky_relu(self.fcs1(state), negative_slope=self.leak)\n x = torch.cat((x, action), dim=1)\n x = F.leaky_relu(self.fc2(x), negative_slope=self.leak)\n x = F.leaky_relu(self.fc3(x), negative_slope=self.leak)\n x = self.fc4(x)\n return x\n" ]
[ [ "torch.nn.Linear", "torch.cat", "torch.nn.init.kaiming_normal_", "torch.manual_seed", "torch.nn.BatchNorm1d", "torch.nn.init.uniform_" ] ]
Flash-Tang/MARL-Env
[ "ef40d95ba9e9b93d620009ef899c6b2e83680eee" ]
[ "smac/examples/run_mn.py" ]
[ "from smac.env import StarCraft2Env\nimport numpy as np\n\nfrom mininet.topo import Topo, SingleSwitchTopo\nfrom mininet.net import Mininet\nfrom mininet.log import lg, info\nfrom mininet.cli import CLI\n\nfrom threading import Thread\nfrom mlp import Mlp\n\nimport time\n\n\nclass simpleMultiLinkTopo(Topo):\n \"Simple topology with multiple links\"\n\n # pylint: disable=arguments-differ\n def build(self, **_kwargs):\n for i in range(n_agents):\n hosts[i] = self.addHost(f'h{i}')\n\n for i in range(0, n_agents, 3):\n self.addLink(hosts[i], hosts[i + 1])\n self.addLink(hosts[i], hosts[i + 2])\n self.addLink(hosts[i + 1], hosts[i + 2])\n\n\nclass AgentThread(Thread):\n def __init__(self, agent_id, obs, avail_actions):\n super(AgentThread, self).__init__()\n self.agent_id = agent_id\n self.obs = obs\n self.avail_actions = avail_actions\n\n def run(self):\n start_time = time.time()\n\n # print(f'thread {threading.current_thread().name} starts')\n\n # avail_actions = env.get_avail_agent_actions(self.agent_id)\n avail_actions_ind = np.nonzero(self.avail_actions)[0]\n\n # obs = env.get_obs_agent(self.agent_id)\n nn_model = Mlp(avail_actions_ind.size)\n action_index = np.argmax(nn_model(np.expand_dims(np.array(self.obs), axis=0)))\n self.action = avail_actions_ind[action_index]\n\n # self.action = 4\n\n run_time = time.time() - start_time\n # print(f'thread {threading.current_thread().name} runs {time.time() - start_time}')\n # print(f'thread {threading.current_thread().name} terminates')\n\n def get_action(self):\n return self.agent_id, self.action\n\n\ndef main():\n lg.setLogLevel('info')\n topo = simpleMultiLinkTopo()\n net = Mininet(topo=topo)\n net.start()\n\n n_episodes = 1\n\n for e in range(n_episodes):\n env.reset()\n terminated = False\n episode_reward = 0\n\n step = 0\n\n for agent_id in range(0, n_agents, 3):\n h1 = net.get(hosts[agent_id])\n h2 = net.get(hosts[agent_id + 1])\n h3 = net.get(hosts[agent_id + 2])\n\n h1.cmd(f'python3 ~/PycharmProjects/MARL-Env/smac/examples/node_recv.py -i {h3.IP()} &')\n h2.cmd(f'python3 ~/PycharmProjects/MARL-Env/smac/examples/node_recv.py -i {h3.IP()} &')\n\n for _ in range(1):\n obs = env.get_obs()\n avail_actions = env.get_avail_actions()\n\n threads = []\n\n start_time = time.time()\n\n for agent_id in range(0, n_agents, 3):\n h1 = net.get(hosts[agent_id])\n h2 = net.get(hosts[agent_id + 1])\n h3 = net.get(hosts[agent_id + 2])\n\n # CLI(net)\n h3.cmd(f'python3 ~/PycharmProjects/smac/smac/examples/node_send.py -i1 {h1.IP()} -i2 {h2.IP()}')\n\n print('---------step---------')\n threads = []\n\n start_time = time.time()\n\n for agent_id in range(n_agents):\n t = AgentThread(agent_id, obs[agent_id], avail_actions[agent_id])\n t.start()\n threads.append(t)\n # t.join()\n\n for t in threads:\n t.join()\n\n print(f'all threads run {time.time() - start_time}seconds')\n\n actions = [0] * n_agents\n for t in threads:\n agent, action = t.get_action()\n actions[agent] = action\n\n reward, terminated, _ = env.step(actions)\n episode_reward += reward\n\n step += 1\n\n print(\"Total reward in episode {} = {}\".format(e, episode_reward))\n\n env.close()\n net.stop()\n\n\nif __name__ == \"__main__\":\n env = StarCraft2Env(map_name=\"3m\", debug=True)\n\n env_info = env.get_env_info()\n n_actions = env_info[\"n_actions\"]\n n_agents = env_info[\"n_agents\"]\n\n hosts = [''] * n_agents\n\n main()\n" ]
[ [ "numpy.array", "numpy.nonzero" ] ]
tarrade/proj_NLP_text_classification_with_GCP
[ "ac09d6dbf8c07470d03cfb8140a26db7cd5bef9f" ]
[ "src/utils/evaluation.py" ]
[ "\"\"\"\nCreated on Wed Nov 7 2018\n\n@author: Renato Durrer [email protected]\n Fabien Tarrade [email protected]\n\"\"\"\nimport itertools\nfrom sklearn.metrics import (log_loss, f1_score, accuracy_score, average_precision_score, precision_score,\n recall_score, roc_auc_score, mean_squared_error, r2_score)\nfrom sklearn.model_selection import learning_curve\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport scikitplot as skplt\n\n\ndef print_metrics(y_t, y_pred_t, mode=''):\n \"\"\"\n Print metrics of various kind\n\n Parameters\n ----------\n y_t :\n\n y_pred_t :\n\n mode : string\n\n \"\"\"\n print('Model performance on the {} dataset:'.format(mode))\n\n #mse = mean_squared_error(y_t, y_pred_t)\n #logloss = log_loss(y_t, y_pred_t)\n accuracy = accuracy_score(y_t, y_pred_t)\n f1 = f1_score(y_t, y_pred_t)\n precision_micro = precision_score(y_t, y_pred_t, average='micro')\n precision_macro = precision_score(y_t, y_pred_t, average='macro')\n avg_precision = average_precision_score(y_t, y_pred_t)\n precision = precision_score(y_t, y_pred_t)\n recall = recall_score(y_t, y_pred_t, average='binary')\n auc = roc_auc_score(y_t, y_pred_t)\n r2 = r2_score(y_t, y_pred_t)\n\n print(' Metric {}'.format(mode.title()))\n print('accuracy........... {0:8.4f}'.format(accuracy))\n print('recall............. {0:8.4f}'.format(recall))\n print('auc................ {0:8.4f}'.format(auc))\n print('precision (p=0.5).. {0:8.4f}'.format(precision))\n print('precision (avg).... {0:8.4f}'.format(avg_precision))\n print('precision (micro).. {0:8.4f}'.format(precision_micro))\n print('precision (macro).. {0:8.4f}'.format(precision_macro))\n print('f1................. {0:8.4f}'.format(f1))\n print('r2................. {0:8.4f}'.format(r2))\n print('logloss............ {0:8.4f}'.format(logloss))\n print('mse................ {0:8.4f}'.format(mse))\n\n\ndef plot_confusion_matrix(cm, classes,\n normalize=False,\n cmap=plt.cm.Blues):\n \"\"\"\n This function prints and plots the confusion matrix.\n Normalization can be applied by setting `normalize=True`.\n\n Parameters\n ----------\n cm : matrix\n confusion matrix\n\n classes : list\n list of names of the classes\n\n normalize : bool, optional\n normalizes confusion matrix if True\n\n title : string, optional\n title of confusion matrix\n\n cmap : optional\n some plot object\n default: plt.cm.Blues\n \"\"\"\n if normalize:\n cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]\n title = 'Normalized Confusion Matrix'\n else:\n title = 'Confusion Matrix'\n\n plt.title(title)\n tick_marks = np.arange(len(classes))\n plt.xticks(tick_marks, classes, rotation=45)\n plt.yticks(tick_marks, classes)\n plt.imshow(cm, interpolation='nearest', cmap=cmap)\n plt.colorbar()\n\n fmt = '.2f' if normalize else 'd'\n thresh = cm.max() / 2.\n for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):\n plt.text(j, i, format(cm[i, j], fmt),\n horizontalalignment=\"center\",\n color=\"white\" if cm[i, j] > thresh else \"black\")\n\n plt.tight_layout()\n plt.ylabel('True label')\n plt.xlabel('Predicted label')\n\n\ndef print_confusion_matrix(cm, cr, label, mode=''):\n \"\"\"\n Print confusino matrix for binary classification\n\n Parameters\n ----------\n cm : matrix\n confusion matrix\n\n cr : string\n\n label :\n\n mode : optional\n \"\"\"\n print('Confusion matrics of the {} data set:\\n'.format(mode))\n\n print('confusion matrix: \\n {} \\n'.format(cm))\n true_negative = cm[0, 0]\n true_positive = cm[1, 1]\n false_negative = cm[1, 0]\n false_positive = cm[0, 1]\n\n print('True labels:')\n for i, j in zip(np.sum(cm, axis=1), label):\n print('{} {:,}'.format(j, i))\n print('')\n print('Predicted labels:')\n for i, j in zip(np.sum(cm, axis=0), label):\n print('{} {:,}'.format(j, i))\n\n total = true_negative + true_positive + false_negative + false_positive\n accuracy = (true_positive + true_negative) / total\n precision = true_positive / (true_positive + false_positive)\n recall = true_positive / (true_positive + false_negative)\n misclassification_rate = (false_positive + false_negative) / total\n f1 = (2 * true_positive) / (2 * true_positive + false_positive + false_negative)\n print('\\n accuracy................. {0:.4f}'.format(accuracy))\n print(' precision................ {0:.4f}'.format(precision))\n print(' recall................... {0:.4f}'.format(recall))\n print(' misclassification_rate... {0:.4f}'.format(misclassification_rate))\n print(' f1....................... {0:.4f}\\n'.format(f1))\n\n print('classification report: \\n {} \\n '.format(cr))\n\n\ndef plot_learning_curve(estimator, title, x, y, ylim=None, cv=None,\n n_jobs=-1, train_sizes=np.linspace(.1, 1.0, 5)):\n \"\"\"\n Generate a simple plot of the test and training learning curves.\n Does not work with Keras/Tensorflow\n\n Parameters\n ----------\n estimator : object type that implements the \"fit\" and \"predict\" methods\n An object of that type which is cloned for each validation.\n\n title : string\n Title for the chart.\n\n x : array-like, shape (n_samples, n_features)\n Training vector, where n_samples is the number of samples and\n n_features is the number of features.\n\n y : array-like, shape (n_samples) or (n_samples, n_features), optional\n Target relative to X for classification or regression;\n None for unsupervised learning.\n\n ylim : tuple, shape (ymin, ymax), optional\n Defines minimum and maximum yvalues plotted.\n\n cv : integer, cross-validation generator, optional\n If an integer is passed, it is the number of folds (defaults to 3).\n Specific cross-validation objects can be passed, see\n sklearn.cross_validation module for the list of possible objects\n\n n_jobs : integer, optional\n Number of jobs to run in parallel (default 1).\n\n train_sizes: array-like\n e.g. np.linspace(.1, 1.0, 5)\n \"\"\"\n plt.figure()\n plt.title(title)\n if ylim is not None:\n plt.ylim(*ylim)\n plt.xlabel(\"Training examples\")\n plt.ylabel(\"Score\")\n train_sizes, train_scores, test_scores = learning_curve(\n estimator, x, y, cv=cv, n_jobs=n_jobs, train_sizes=train_sizes)\n train_scores_mean = np.mean(train_scores, axis=1)\n train_scores_std = np.std(train_scores, axis=1)\n test_scores_mean = np.mean(test_scores, axis=1)\n test_scores_std = np.std(test_scores, axis=1)\n plt.grid(True)\n\n plt.fill_between(train_sizes, train_scores_mean - train_scores_std,\n train_scores_mean + train_scores_std, alpha=0.1,\n color=\"r\")\n plt.fill_between(train_sizes, test_scores_mean - test_scores_std,\n test_scores_mean + test_scores_std, alpha=0.1, color=\"g\")\n plt.plot(train_sizes, train_scores_mean, 'o-', color=\"r\",\n label=\"Training score\")\n plt.plot(train_sizes, test_scores_mean, 'o-', color=\"g\",\n label=\"Cross-validation score\")\n\n plt.legend(loc=\"best\")\n plt.show()\n\n\ndef auc_plot(model, title, x_test, y_test, x_train=None, y_train=None, prefit=True):\n \"\"\"\n Creates a simple AUC ROC plot.\n\n Parameters\n ----------\n model : scikit-learn model\n model that is evaluated. May be prefitted. Needs to have attribute .predict_proba\n\n title : string\n title of the plot\n\n x_test : array-like, shape (n_samples, n_features)\n Training vector, where n_samples is the number of samples and\n n_features is the number of features.\n\n y_test : array-like, shape (n_samples) or (n_samples, n_features)\n Target relative to x_test for classification\n\n x_train : array-like, shape (n_samples, n_features), optional\n Training vector, where n_samples is the number of samples and\n n_features is the number of features.\n\n y_train : array-like, shape (n_samples) or (n_samples, n_features), optional\n Target relative to x_train for classification\n\n prefit : bool, optional\n default False\n wheter or not to use a prefitted model. If true x_train and y_train do not need to be passed.\n \"\"\"\n if not prefit:\n model.fit(x_train, y_train)\n y_probas = model.predict_proba(x_test)\n skplt.metrics.plot_roc(y_test, y_probas)\n plt.title(title)\n plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)\n plt.tight_layout(rect=[0, 0, 2, 1])\n plt.show()\n\n\ndef wrongly_classified(model, x_test, y_test, x_train=None, y_train=None, prefit=True, return_correct=False):\n \"\"\"\n Returns the features of the wrongly classified points.\n\n Parameters\n ----------\n model : clf\n classifier implementing methods: fit & predict\n\n x_test : array-like, shape (n_samples, n_features)\n Feature vector, where n_samples is the number of samples and\n n_features is the number of features.\n\n y_test : array-like, shape (n_samples) or (n_samples, n_features)\n Target relative to x_test for classification\n\n x_train : array-like, shape (n_samples, n_features), optional\n Training vector, where n_samples is the number of samples and\n n_features is the number of features.\n\n y_train : array-like, shape (n_samples) or (n_samples, n_features), optional\n Target relative to x_train for classification\n\n prefit : bool, optional\n if False model is fitted first. x_train and y_train need to be passed in this case.\n default: True\n\n return_correct : bool, optional\n if True,\n\n Returns\n -------\n DataFrame\n DataFrame containing wrongly (or correct) classified data points\n \"\"\"\n if not prefit:\n model.fit(x_train, y_train)\n df = pd.DataFrame(model.predict(x_test), columns=['predicted_label'], index=x_test.index.values)\n df['true_label'] = y_test\n df2 = pd.DataFrame(x_test)\n df = pd.concat([df, df2], axis='columns')\n if return_correct:\n return df[df['true_label'] == df['predicted_label']]\n else:\n return df[df['true_label'] != df['predicted_label']]\n\n\ndef check_confidence(model, min_conf, x_test, y_test):\n \"\"\"\n Prints accuracy for minimal confidence for classification.\n\n Parameters\n ----------\n model : pretrained scikit-learn model (needs, fit, predict & predict_proba)\n\n min_conf : float,\n minimal confidence for classificaton\n\n x_test : array-like, shape (n_samples, n_features)\n Feature vector, where n_samples is the number of samples and\n n_features is the number of features.\n\n y_test : array-like, shape (n_samples) or (n_samples, n_features)\n Target relative to x_test for classification\n\n Returns\n -------\n None\n \"\"\"\n predictions = model.predict_proba(x_test)\n wrong_class = pd.DataFrame(predictions[model.predict(x_test) != y_test])\n right_class = pd.DataFrame(predictions[model.predict(x_test) == y_test])\n wrong_class_counts = (wrong_class.apply(lambda row: max(row), axis=1) > min_conf).value_counts()\n right_class_counts = (right_class.apply(lambda row: max(row), axis=1) > min_conf).value_counts()\n baseline = accuracy_score(y_test, model.predict(x_test))\n Accuracy = right_class_counts[True] / (right_class_counts[True] + wrong_class_counts[True])\n Classifications = (right_class_counts[True] + wrong_class_counts[True]) / len(y_test)\n print('With a minimal confidence of {} we\\'d have {} accuracy and {} of the datapoints would'\n ' \\nbe classified. '\n 'The baseline is given as {}'.format(min_conf,\n round(Accuracy, 4),\n round(Classifications, 4),\n round(baseline, 4)))\n" ]
[ [ "sklearn.metrics.precision_score", "numpy.mean", "sklearn.metrics.average_precision_score", "pandas.concat", "sklearn.metrics.r2_score", "sklearn.metrics.f1_score", "matplotlib.pyplot.xticks", "sklearn.model_selection.learning_curve", "matplotlib.pyplot.colorbar", "pandas.DataFrame", "sklearn.metrics.accuracy_score", "matplotlib.pyplot.fill_between", "matplotlib.pyplot.tight_layout", "matplotlib.pyplot.title", "matplotlib.pyplot.yticks", "matplotlib.pyplot.figure", "numpy.std", "matplotlib.pyplot.show", "sklearn.metrics.roc_auc_score", "sklearn.metrics.recall_score", "matplotlib.pyplot.xlabel", "matplotlib.pyplot.grid", "matplotlib.pyplot.plot", "matplotlib.pyplot.legend", "numpy.sum", "matplotlib.pyplot.ylim", "matplotlib.pyplot.ylabel", "numpy.linspace", "matplotlib.pyplot.imshow" ] ]
amanhari-projects/Satellite-image-road-extraction
[ "92f29f7245d44b982c295358f344952cdb5389f9" ]
[ "data.py" ]
[ "import numpy as np\r\nimport cv2\r\nimport matplotlib.pyplot as plt\r\nimport glob\r\nimport os\r\n\r\nREQ_W = 224\r\nREQ_H = 224\r\nTRAIN_IMAGES_INPUT_PATH = 'road_segmentation_ideal/training/input/'\r\nTRAIN_IMAGES_OUTPUT_PATH = 'road_segmentation_ideal/training/output/'\r\n\r\n# function to load the dataset\r\ndef load_dataset():\r\n # loads the dataset files into a list\r\n train_images_inp_list = os.listdir(TRAIN_IMAGES_INPUT_PATH)\r\n train_images_out_list = os.listdir(TRAIN_IMAGES_OUTPUT_PATH)\r\n inp_img_path = []\r\n out_img_path = []\r\n for p in train_images_inp_list:\r\n inp_img_path.append(os.path.split(p)[1])\r\n for p in train_images_out_list:\r\n out_img_path.append(os.path.split(p)[1])\r\n train_images_path = list(set(inp_img_path).intersection(out_img_path))\r\n # show first 4 images as trial\r\n # uncomment these to show the images while loading the dataset\r\n # for i in range(2):\r\n # img_inp = input_encoding(TRAIN_IMAGES_INPUT_PATH+train_images_path[i])\r\n # img_out = output_encoding(TRAIN_IMAGES_OUTPUT_PATH+train_images_path[i])\r\n # display(img_inp,img_out,train_images_path[i])\r\n # print(\"Number of training samples:\"+str(len(train_images_path)))\r\n return train_images_path\r\n\r\n# function to read and preprocess the input image of network\r\ndef input_encoding(file_name):\r\n print(file_name)\r\n image = cv2.imread(filename=file_name)\r\n image = cv2.cvtColor(image,cv2.COLOR_BGR2RGB)\r\n h,w,c = image.shape\r\n image = cv2.resize(image,(REQ_W,REQ_H))\r\n image = image/255.0\r\n return image\r\n\r\n# function to read and preprocess the output image of network\r\ndef output_encoding(file_name):\r\n print(file_name)\r\n image = cv2.imread(filename=file_name)\r\n image = cv2.cvtColor(image,cv2.COLOR_BGR2GRAY)\r\n h,w = image.shape\r\n image = cv2.resize(image,(REQ_W,REQ_H))\r\n image = image/255.0\r\n return image\r\n\r\ndef display(img_inp,img_out,img_name):\r\n fig = plt.figure(figsize=(8,8))\r\n plt.subplot(1,2,1)\r\n plt.title(img_name)\r\n plt.imshow(img_inp)\r\n\r\n plt.subplot(1,2,2)\r\n plt.title(img_name)\r\n plt.imshow(img_out,cmap=plt.get_cmap('gray'))\r\n plt.show()" ]
[ [ "matplotlib.pyplot.subplot", "matplotlib.pyplot.get_cmap", "matplotlib.pyplot.title", "matplotlib.pyplot.figure", "matplotlib.pyplot.show", "matplotlib.pyplot.imshow" ] ]
wep21/jetson-containers
[ "0071a4bd3f2f5235c99eb5fb71486d461d9e8774" ]
[ "test/test_numpy.py" ]
[ "\nprint('testing numpy...')\nimport numpy as np\n\nprint('numpy version: ' + str(np.__version__))\nprint(np.show_config())\n\nprint('numpy OK\\n')\n" ]
[ [ "numpy.show_config" ] ]
ademirmarquesjunior/multilooking_linear_solving
[ "98e01beb3c48093680195099f00545fc3dc91e39" ]
[ "multilooking_linear_solving.py" ]
[ "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Feb 17 15:47:16 2021\n\n@author: adeju\n\"\"\"\n\n\nimport numpy as np\n\nnum_images = 9\nsquared_size = int(np.sqrt(num_images))\nimage = np.zeros((num_images, 500, 500), dtype=np.uint8)\nimage_out = np.zeros((num_images, 3*500, 3*500), dtype=np.uint8)\n\n# Create index array helper\nindex_array = np.reshape(list(range(9)), (3, 3))\nindex_array = np.concatenate((index_array, index_array[:, 0:2]), axis=1)\nindex_array = np.concatenate((index_array, index_array[0:2, :]), axis=0)\n\n\ndef pixel_positions(ref_index, index_array, num_images):\n # uses array of indexes with the same size of the image depth (# of bands)\n # return image indexes and pixels positions offset\n\n image_index = np.zeros((num_images), dtype=np.uint8)\n offset_i = np.zeros((num_images), dtype=np.uint8)\n offset_j = np.zeros((num_images), dtype=np.uint8)\n\n # squared_size = int(np.sqrt(num_images))\n\n position = np.where(np.reshape(list(range(num_images)),\n (squared_size, squared_size)) == ref_index)\n x, y = position[0][0], position[1][0]\n\n index = 0\n for i in range(squared_size):\n for j in range(squared_size):\n\n image_index[index] = index_array[x + i, y + j]\n\n if x + i > squared_size:\n offset_i[index] = 1\n else:\n offset_i[index] = 0\n\n if y + i > squared_size:\n offset_j[index] = 1\n else:\n offset_j[index] = 0\n\n index = index + 1\n\n return image_index, offset_i, offset_j\n\n\ndef blit(dest, src, loc):\n # Paste array values into other larger array into determined position\n # https://stackoverflow.com/questions/28676187/numpy-blit-copy-part-of-an-array-to-another-one-with-a-different-size\n pos = [i if i >= 0 else None for i in loc]\n neg = [-i if i < 0 else None for i in loc]\n target = dest[[slice(i, None) for i in pos]]\n src = src[[slice(i, j) for i, j in zip(neg, target.shape)]]\n target[[slice(None, i) for i in src.shape]] = src\n return dest\n\n\ndef lin_sis_solve(im):\n import sympy as sym\n\n # im = image[image_index, 0+offset_i, 0+offset_j]\n\n p = []\n eqn = []\n\n for i in range(25):\n p.append(sym.symbols('p' + str(i)))\n\n # Create index array helper\n im_index_array = np.reshape(list(range(np.size(im))), (3, 3))\n p_index_array = np.reshape(list(range(np.size(p))), (5, 5))\n\n # Create list of unique image combinations\n im_combinations = []\n for i in range(num_images):\n for j in range(num_images):\n if str(np.sort((i, j))) not in im_combinations:\n im_combinations.append(str(np.sort((i, j))))\n\n eqn = []\n for combination in im_combinations:\n\n im_indexes = np.fromstring(combination[1:-1], sep=' ').astype(int)\n\n # Recover im_indexes position in im_index_array\n x, y = np.where(im_index_array == im_indexes[0])\n positive_variable_indexes = []\n for i in range(squared_size):\n for j in range(squared_size):\n positive_variable_indexes.append(p_index_array[x + i, y + j][0])\n\n # Create the \n negative_variable_indexes = []\n\n # if the indexes are the same the second list must be empty\n if im_indexes[0] != im_indexes[1]:\n x, y = np.where(im_index_array == im_indexes[1])\n for i in range(squared_size):\n for j in range(squared_size):\n negative_variable_indexes.append(p_index_array[x + i, y + j][0])\n\n # Create list with unique values between variable lists\n A = [i for i in positive_variable_indexes if i not in negative_variable_indexes]\n B = [i for i in negative_variable_indexes if i not in positive_variable_indexes]\n\n # Create the equation expression\n for i in A:\n if \"expression\" not in locals():\n expression = sym.Add(p[i])\n else:\n expression = sym.Add(expression, p[i])\n\n for i in B:\n if \"expression\" not in locals():\n expression = sym.Add(-p[i])\n else:\n expression = sym.Add(expression, -p[i])\n\n if im_indexes[0] == im_indexes[1]:\n result = (im[im_indexes[0]]*9)\n else:\n result = ((im[im_indexes[0]] - im[im_indexes[1]])*9)\n eqn.append(sym.Eq(expression, result))\n del(expression)\n\n print(eqn)\n\n return sym.solve(eqn, p)\n\n\ndef subpixel_offset(num_images, ref_index, squared_size):\n position = np.where(np.reshape(list(range(num_images)),\n (squared_size, squared_size)) == ref_index)\n x, y = position[0][0], position[1][0]\n\n x = x*(1/np.sqrt(num_images))\n y = y*(1/np.sqrt(num_images))\n\n return x, y\n\n\nfor i in range(0, np.shape(image)[1]):\n for j in range(0, np.shape(image)[2]):\n for t in range(0, num_images):\n\n image_index, offset_i, offset_j = pixel_positions(\n t, index_array, num_images)\n\n X = lin_sis_solve(image[image_index, i+offset_i, j+offset_j])\n\n X = np.reshape(X, (int(np.sqrt(X)), int(np.sqrt(X))))\n\n # offsets\n tile_size_offset = int(np.shape(X)[0]/2)\n tile_size_offset = int(5/2)\n offset = subpixel_offset(num_images, 0, squared_size)\n x = int(round(squared_size*(i + offset[0])-tile_size_offset))\n y = int(round(squared_size*(j + offset[0]))-tile_size_offset)\n\n blit(image_out[t, :, :], index_array, (x, y))\n\n" ]
[ [ "numpy.concatenate", "numpy.zeros", "numpy.shape", "numpy.where", "numpy.sort", "numpy.sqrt", "numpy.size", "numpy.fromstring" ] ]
cfont03/Anomaly-breast-cancer-detection
[ "d0fca05747b30afb546fe55ba3851883d99eb34f" ]
[ "src/preprocess/utils/vertical_flip.py" ]
[ "import cv2\nimport numpy as np\nfrom pathlib import Path\nimport os\n\ndef vertical_flip (info_file, display = False):\n\n ''' \n \n Function to apply a vertical flip to the images\n\n Params:\n 0: reference number\n 1: features\n 2: size\n 3: class\n 4: x_coordinate of the abnormality\n 5: y_coordiante of the abnormality\n 6: radius in pixels\n 7: path of the image\n 8: xmin coordinate bounding box\n 9: ymin coordinate bounding box\n 10: xmax coordinate bounding box\n 11: ymax coordinate bounding box\n \n Outputs: saved imgs into system, list with (x,y) coordinates, list with (xmin, ymax) coordinates, list with (ymin, ymax) coordinates\n\n '''\n\n x_y = []\n x_min_max = []\n y_min_max = []\n\n for name, path, size_x, size_y, xcoord, ycoord, xmin, xmax, ymin, ymax in zip(info_file.iloc[:, 0], info_file.iloc[:, 7], \n info_file.iloc[:, 2], info_file.iloc[:, 2],\n info_file.iloc[:, 4], info_file.iloc[:, 5],\n info_file.iloc[:, 8], info_file.iloc[:, 9],\n info_file.iloc[:, 10], info_file.iloc[:, 11]):\n \n vflip_ = cv2.imread(str(path))\n vflip = cv2.flip(vflip_, 0)\n new_path = Path(\"res/all-mias/{:}_vflip{:}\".format(name, '.jpeg'))\n if os.path.exists(new_path) == True:\n print(new_path, \": File already exists\")\n else:\n status = cv2.imwrite(str(new_path), vflip)\n ### CHECKPOINT OUTPUT\n print(\"Image written to file-system \" , new_path, \" :\", status)\n\n ### adapt bounding boxes points\n ycoord_ = int(1024) - int(float(ycoord))\n ymax_ = int(1024) - int(ymin)\n ymin_ = int(1024) - int(ymax)\n x_y.append(np.array([[xcoord, ycoord_]]))\n x_min_max.append(np.array([[xmin, xmax]]))\n y_min_max.append(np.array([[ymin_, ymax_]]))\n \n return x_y, x_min_max, y_min_max" ]
[ [ "numpy.array" ] ]
facebookresearch/habitat-matterport3d-dataset
[ "9c1852efca7ff3db3d46455b18c154f6b08769e5" ]
[ "scale_comparison/metrics.py" ]
[ "#!/usr/bin/env python3\n\n# Copyright (c) Facebook, Inc. and its affiliates.\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nimport math\nfrom typing import Any, Dict, List\n\nimport habitat_sim\nimport numpy as np\nimport scipy\nimport trimesh\nfrom scipy.spatial import ConvexHull\nfrom sklearn.cluster import DBSCAN\n\nEPS = 1e-10\n\n\ndef get_geodesic_distance(\n hsim: habitat_sim.Simulator, p1: np.ndarray, p2: np.ndarray\n) -> float:\n \"\"\"Computes the geodesic distance between two points.\"\"\"\n path = habitat_sim.ShortestPath()\n path.requested_start = p1\n path.requested_end = p2\n hsim.pathfinder.find_path(path)\n return path.geodesic_distance\n\n\ndef get_euclidean_distance(p1: np.ndarray, p2: np.ndarray) -> float:\n \"\"\"Computes the euclidean distance between two points.\"\"\"\n return np.linalg.norm(p1 - p2).item()\n\n\ndef get_navcomplexity(\n hsim: habitat_sim.Simulator, p1: np.ndarray, p2: np.ndarray\n) -> float:\n \"\"\"Computes the navigation complexity between two points in a scene.\"\"\"\n geod = get_geodesic_distance(hsim, p1, p2)\n eucd = get_euclidean_distance(p1, p2)\n return geod / (eucd + EPS)\n\n\ndef get_triangle_areas(triangles: np.ndarray) -> np.ndarray:\n \"\"\"\n Measure the area of mesh triangles.\n Args:\n triangles: (N, 3, 3) ndarray with dimension 1 representing 3 vertices\n \"\"\"\n vtr10 = triangles[:, 1] - triangles[:, 0] # (N, 3)\n vtr20 = triangles[:, 2] - triangles[:, 0] # (N, 3)\n area = 0.5 * np.linalg.norm(np.abs(np.cross(vtr10, vtr20, axis=1)), axis=1)\n return area\n\n\ndef transform_coordinates_hsim_to_trimesh(xyz: np.ndarray) -> np.ndarray:\n \"\"\"\n Transforms points from hsim coordinates to trimesh.\n\n Habitat conventions: X is rightward, Y is upward, -Z is forward\n Trimesh conventions: X is rightward, Y is forward, Z is upward\n\n Args:\n xyz: (N, 3) array of coordinates\n \"\"\"\n xyz_trimesh = np.stack([xyz[:, 0], -xyz[:, 2], xyz[:, 1]], axis=1)\n return xyz_trimesh\n\n\ndef get_floor_navigable_extents(\n hsim: habitat_sim.Simulator, num_points_to_sample: int = 20000\n) -> List[Dict[str, float]]:\n \"\"\"\n Function to estimate the number of floors in a 3D scene and the Y extents\n of the navigable space on each floor. It samples a random number\n of navigable points and clusters them based on their height coordinate.\n Each cluster corresponds to a floor, and the points within a cluster\n determine the extents of the navigable surfaces in a floor.\n \"\"\"\n # randomly sample navigable points\n random_navigable_points = []\n for _i in range(num_points_to_sample):\n point = hsim.pathfinder.get_random_navigable_point()\n if np.isnan(point).any() or np.isinf(point).any():\n continue\n random_navigable_points.append(point)\n random_navigable_points = np.array(random_navigable_points)\n # cluster the rounded y_coordinates using DBScan\n y_coors = np.around(random_navigable_points[:, 1], decimals=1)\n clustering = DBSCAN(eps=0.2, min_samples=500).fit(y_coors[:, np.newaxis])\n c_labels = clustering.labels_\n n_clusters = len(set(c_labels)) - (1 if -1 in c_labels else 0)\n # estimate floor extents\n floor_extents = []\n core_sample_y = y_coors[clustering.core_sample_indices_]\n core_sample_labels = c_labels[clustering.core_sample_indices_]\n for i in range(n_clusters):\n floor_min = core_sample_y[core_sample_labels == i].min().item()\n floor_max = core_sample_y[core_sample_labels == i].max().item()\n floor_mean = core_sample_y[core_sample_labels == i].mean().item()\n floor_extents.append({\"min\": floor_min, \"max\": floor_max, \"mean\": floor_mean})\n\n return floor_extents\n\n\ndef compute_navigable_area(\n hsim: habitat_sim.Simulator, *args: Any, **kwargs: Any\n) -> float:\n \"\"\"\n Navigable area (m^2) measures the total scene area that is actually\n navigable in the scene. This is computed for a cylindrical robot with radius\n 0.1m and height 1.5m using the AI Habitat navigation mesh implementation.\n This excludes points that are not reachable by the robot. Higher values\n indicate larger quantity and diversity of viewpoints for a robot.\n \"\"\"\n return hsim.pathfinder.navigable_area\n\n\ndef compute_navigation_complexity(\n hsim: habitat_sim.Simulator,\n *args: Any,\n max_pairs_to_sample: int = 20000,\n max_trials_per_pair: int = 10,\n **kwargs: Any,\n) -> float:\n \"\"\"\n Navigation complexity measures the difficulty of navigating in a scene.\n This is computed as the maximum ratio of geodesic path to euclidean\n distances between any two navigable locations in the scene. Higher values\n indicate more complex layouts with navigation paths that deviate\n significantly from straight-line paths.\n\n Args:\n hsim: habitat simulator instance\n max_pairs_to_sample: the maximum number of random point pairs to sample\n max_trials_per_pair: the maximum trials to find a paired point p2 for\n a given point p1\n \"\"\"\n if not hsim.pathfinder.is_loaded:\n return 0.0\n navcomplexity = 0.0\n num_sampled_pairs = 0\n while num_sampled_pairs < max_pairs_to_sample:\n num_sampled_pairs += 1\n p1 = hsim.pathfinder.get_random_navigable_point()\n num_trials = 0\n while num_trials < max_trials_per_pair:\n num_trials += 1\n p2 = hsim.pathfinder.get_random_navigable_point()\n # Different floors\n if abs(p1[1] - p2[1]) > 0.5:\n continue\n cur_navcomplexity = get_navcomplexity(hsim, p1, p2)\n # Ignore disconnected pairs\n if math.isinf(cur_navcomplexity):\n continue\n navcomplexity = max(navcomplexity, cur_navcomplexity)\n\n return navcomplexity\n\n\ndef compute_scene_clutter(\n hsim: habitat_sim.Simulator,\n trimesh_scene: trimesh.parent.Geometry,\n closeness_thresh: float = 0.5,\n) -> float:\n \"\"\"\n Scene clutter measures amount of clutter in the scene. This is computed as\n the ratio between the raw scene mesh area within 0.5m of the navigable\n regions and the navigable space. We restrict to 0.5m to only pick the\n surfaces that are near navigable spaces in the building\n (e.g., furniture, and interior walls), and to ignore other surfaces outside\n the building. This is implemented in the same way as by Xia et al. to\n make the reported statistics comparable. Higher values are better and\n indicate more cluttered scenes that provide more obstacles for navigation.\n\n Args:\n hsim: habitat simulator instance\n trimesh_scene: 3D scene loaded in trimesh\n closeness_thresh: a distance threshold for points on the mesh to be\n considered \"close\" to navigable space.\n\n Reference:\n Xia, Fei, et al.\n \"Gibson env: Real-world perception for embodied agents.\"\n Proceedings of the IEEE Conference on Computer Vision and Pattern Recognition. 2018.\n \"\"\"\n if not hsim.pathfinder.is_loaded:\n return 0.0\n mesh_triangles = np.copy(trimesh_scene.triangles)\n # convert habitat navmesh to a trimesh scene\n navmesh_vertices = np.array(hsim.pathfinder.build_navmesh_vertices())\n navmesh_vertices = transform_coordinates_hsim_to_trimesh(navmesh_vertices)\n ## three consecutive vertices form a triangle face\n navmesh_faces = np.arange(0, navmesh_vertices.shape[0], dtype=np.uint32)\n navmesh_faces = navmesh_faces.reshape(-1, 3)\n navmesh_triangles = navmesh_vertices.reshape(-1, 3, 3)\n navmesh_centroids = navmesh_triangles.mean(axis=1)\n navmesh = trimesh.Trimesh(vertices=navmesh_vertices, faces=navmesh_faces)\n # Find closest distance between a mesh_triangle and the navmesh\n # This is approximated by measuring the distance between each vertex and\n # centroid of a mesh_triangle to the navmesh surface\n ## (1) pre-filtering to remove unrelated mesh_triangles\n tree = scipy.spatial.cKDTree(navmesh_centroids)\n mesh_centroids = mesh_triangles.mean(axis=1)[:, np.newaxis, :]\n mindist, _ = tree.query(mesh_centroids)\n valid_mask = mindist[:, 0] <= 2 * closeness_thresh\n mesh_triangles = mesh_triangles[valid_mask]\n mesh_centroids = mesh_centroids[valid_mask]\n # (2) min distance b/w vertex / centroid of a mesh triangle to navmesh\n mesh_tricents = np.concatenate(\n [mesh_triangles, mesh_centroids], axis=1\n ) # (N, 4, 3)\n mesh_tricents = mesh_tricents.reshape(-1, 3)\n _, d2navmesh, _ = navmesh.nearest.on_surface(mesh_tricents) # (N * 4, )\n d2navmesh = d2navmesh.reshape(-1, 4).min(axis=1) # (N, )\n closest_mesh_triangles = mesh_triangles[(d2navmesh < closeness_thresh)]\n clutter_area = get_triangle_areas(closest_mesh_triangles).sum().item()\n navmesh_area = hsim.pathfinder.navigable_area\n clutter = clutter_area / (navmesh_area + EPS)\n\n return clutter\n\n\ndef compute_floor_area(\n hsim: habitat_sim.Simulator,\n trimesh_scene: trimesh.parent.Geometry,\n floor_limit: float = 0.5,\n) -> float:\n \"\"\"\n Floor area (m^2) measures the overall extents of the floor regions in the\n scene. This is the area of the 2D convex hull of all navigable locations in\n a floor. For scenes with multiple floors, the floor space is summed over all\n floors. This is implemented in the same way as by Xia et al. to make the\n reported statistics comparable. Higher values indicate the presence of more\n navigation space and rooms.\n\n Args:\n hsim: habitat simulator instance\n trimesh_scene: 3D scene loaded in trimesh\n floor_limit: defines the maximum height above the navigable space\n that is considered as a part of the current floor.\n\n Reference:\n Xia, Fei, et al.\n \"Gibson env: Real-world perception for embodied agents.\"\n Proceedings of the IEEE Conference on Computer Vision and Pattern Recognition. 2018.\n \"\"\"\n if not hsim.pathfinder.is_loaded:\n return 0.0\n floor_extents = get_floor_navigable_extents(hsim)\n mesh_vertices = trimesh_scene.triangles.reshape(-1, 3)\n # Z axis in trimesh is vertically upward\n floor_area = 0.0\n for fext in floor_extents:\n mask = (mesh_vertices[:, 2] >= fext[\"min\"]) & (\n mesh_vertices[:, 2] < fext[\"max\"] + floor_limit\n )\n floor_convex_hull = ConvexHull(mesh_vertices[mask, :2])\n # convex_hull.volume computes the area for 2D convex hull\n floor_area += floor_convex_hull.volume\n return floor_area\n" ]
[ [ "numpy.concatenate", "numpy.isinf", "numpy.array", "scipy.spatial.cKDTree", "numpy.linalg.norm", "numpy.isnan", "numpy.copy", "numpy.stack", "numpy.arange", "sklearn.cluster.DBSCAN", "scipy.spatial.ConvexHull", "numpy.around", "numpy.cross" ] ]
loujiabin1994/crazyswarm
[ "893325b63b3b19015fe261bfa989846a1c82dc82" ]
[ "ros_ws/src/crazyswarm/scripts/cmdFullState.py" ]
[ "#!/usr/bin/env python\n\nimport numpy as np\n\nfrom pycrazyswarm import *\nimport uav_trajectory\n\n\ndef executeTrajectory(timeHelper, cf, trajpath, rate=100, offset=np.zeros(3)):\n traj = uav_trajectory.Trajectory()\n traj.loadcsv(trajpath)\n\n start_time = timeHelper.time()\n while not timeHelper.isShutdown():\n t = timeHelper.time() - start_time\n if t > traj.duration:\n break\n\n e = traj.eval(t)\n cf.cmdFullState(\n # (e.pos + np.array(cf.initialPosition) + offset),\n (e.pos + offset)/2,\n e.vel/2,\n e.acc/2,\n e.yaw/2,\n e.omega)\n\n timeHelper.sleepForRate(rate)\n\n\nif __name__ == \"__main__\":\n swarm = Crazyswarm()\n timeHelper = swarm.timeHelper\n cf = swarm.allcfs.crazyflies[0]\n\n rate = 30.0\n Z = 1\n\n cf.takeoff(targetHeight=Z, duration=Z+1.0)\n timeHelper.sleep(Z+2.0)\n cf.goTo([2, 0, Z], 0, 2)\n timeHelper.sleep(2)\n executeTrajectory(timeHelper, cf, \"sequence_trajectories/7/19.csv\", offset=np.array([2, 0, 0.1]))\n\n cf.notifySetpointsStop()\n cf.land(targetHeight=0.03, duration=Z+1.0)\n timeHelper.sleep(Z+2.0)\n" ]
[ [ "numpy.array", "numpy.zeros" ] ]
higex/qpath
[ "02db9dbf1148106a576d7b4dd7965c73607efdae" ]
[ "scripts/wsi_import_he_slide.py" ]
[ "#!/usr/bin/env python2\n\n\"\"\"\nWSI_IMPORT_SLIDE: imports a scanned slide into a structure used for image processing.\nThis structure is saved on the disk as a hierarchy of folders and files:\n\n .../original image name/\n +---- meta.xml <- meta data about the file\n +---- first downsampling level/\n +---- tile_i_j.ppm...\n +---- second downsampling level/\n +---- tile_i_j.ppm\n etc\n\nExample:\nwsi_import_he_slide.py --shrink 1,2,4,8,16,32,64 --split \"(20,20),(20,20),(10,10),(10,10),(10,10),(5,5),(1,1)\"\n --overlap 0 orig/1017-04-f-1-vlp-40x-he.tif\n\"\"\"\n\nfrom __future__ import print_function, division, with_statement\n\n__author__ = 'vlad'\n__version__ = 0.15\n\nfrom vipsCC import VImage\nimport argparse as opt\nimport re\nimport xml.etree.ElementTree as ET\nfrom xml.dom import minidom\nimport os\nimport numpy as np\nimport gc\n\nfrom segm.tissue import tissue_region_from_rgb\nfrom segm.basic import bounding_box\n\nfrom skimage.io import imsave, imread\nfrom skimage.transform import resize\n\n\nimg_file = ''\nres_prefix = ''\nres_format = ''\ns_factors = []\nn_splits = []\novlap = 0\nn_levels = 0\n\n\ndef run():\n global img_file, res_prefix, s_factors, n_splits, ovlap\n\n # print(img_file)\n # print(res_prefix)\n # print(s_factors)\n # print(n_splits)\n # print(ovlap)\n\n r = ET.Element('meta')\n t = ET.SubElement(r, 'file')\n t.text = img_file\n\n t = ET.SubElement(r, 'parameters')\n t1 = ET.SubElement(t, 'prefix')\n t1.text = res_prefix\n\n t1 = ET.SubElement(t, 'shrink')\n for s in s_factors:\n t2 = ET.SubElement(t1, 'factor')\n t2.text = str(s)\n\n t1 = ET.SubElement(t, 'split')\n for s in n_splits:\n t2 = ET.SubElement(t1, 'tile')\n t2.text = str(s)\n\n t1 = ET.SubElement(t, 'overlap')\n t1.text = str(ovlap)\n\n img = VImage.VImage(img_file)\n\n t1 = ET.SubElement(r, 'original')\n t2 = ET.SubElement(t1, 'width')\n t2.text = str(img.Xsize())\n t2 = ET.SubElement(t1, 'height')\n t2.text = str(img.Ysize())\n t2 = ET.SubElement(t1, 'channels')\n t2.text = str(img.Bands())\n t2 = ET.SubElement(t1, 'xres')\n t2.text = str(img.Xres())\n t2 = ET.SubElement(t1, 'yres')\n t2.text = str(img.Yres())\n t2 = ET.SubElement(t1, 'scale')\n t2.text = '1.0'\n t2 = ET.SubElement(t1, 'tile')\n t2.text = '(1, 1)'\n\n path = res_prefix + '/' + os.path.basename(img_file)\n if os.path.exists(path):\n print('Warning: Overwriting old files!')\n else:\n os.mkdir(path)\n\n print(\"ROI detection: \")\n # Find the ROI:\n # img_scaled = img.shrink(100, 100)\n os.spawnv(os.P_WAIT, 'div100', ['./div100', img_file, path+'/small.ppm'])\n # save downscaled image - not the best way for going to Scikit Image,\n # but for large images we go through disk I/O anyway:\n # print(\" -saving small version of the image\")\n # img_scaled.write(path+'/small.ppm')\n\n print(\" -read into scikit-learn\")\n img_scaled = imread(path+'/small.ppm')\n\n # compute a minimal area based on the resolution of the image\n # -the image is 100x smaller than the original -> resolution is\n print(\" -computing mask\")\n xres, yres = img.Xres() / 100, img.Yres() / 100\n min_area = 4 * min(xres, yres) # ~4 mm**2\n mask, _ = tissue_region_from_rgb(img_scaled, min_area)\n\n # save the mask:\n print(\" -saving mask\")\n imsave(path + '/' + 'mask_div100.pbm', mask)\n t2 = ET.SubElement(t1, 'mask')\n t2.text = 'mask_div100.pbm'\n\n # coordinates of the ROI encompassing the objects, at 0.01 of original image\n print(\" -detect ROI\")\n rmin, cmin, rmax, cmax = bounding_box(mask)\n mask = mask[rmin:rmax+1, cmin:cmax+1]\n\n # get back to original coordinates, with an approximation of 100 pixels...\n rmin *= 100\n cmin *= 100\n rmax = min((rmax + 1) * 100, img.Ysize())\n cmax = min((cmax + 1) * 100, img.Xsize())\n\n t2 = ET.SubElement(t1, 'roi',\n {'xmin': str(cmin), 'ymin': str(rmin), 'xmax': str(cmax), 'ymax': str(rmax)})\n\n print(\"...end ROI detection.\")\n\n # Save initial level 0:\n print(\"Crop ROI and save...\")\n img_cropped = img.extract_area(cmin, rmin, cmax-cmin+1, rmax-rmin+1)\n img_cropped.write(path + '/pyramid-level_0.ppm')\n new_width, new_height = img_cropped.Xsize(), img_cropped.Ysize()\n img_cropped = None\n print(\"...OK\")\n\n mask = None\n img = None # done with it\n gc.collect()\n\n # Generate the pyramid\n t1 = ET.SubElement(r, 'pyramid')\n t2 = ET.SubElement(t1, 'level', {'value': '0', 'file': 'pyramid-level_0.ppm'})\n t2 = ET.SubElement(t1, 'level', {'value': '1', 'file': 'pyramid-level_1.ppm'})\n t2 = ET.SubElement(t1, 'level', {'value': '2', 'file': 'pyramid-level_2.ppm'})\n t2 = ET.SubElement(t1, 'level', {'value': '3', 'file': 'pyramid-level_3.ppm'})\n t2 = ET.SubElement(t1, 'level', {'value': '4', 'file': 'pyramid-level_4.ppm'})\n t2 = ET.SubElement(t1, 'level', {'value': '5', 'file': 'pyramid-level_5.ppm'})\n\n # call external tool:\n print(\"Computing pyramid...\")\n os.spawnv(os.P_WAIT, 'pyr', ['./pyr', path+'/pyramid-level_0.ppm', path+'/pyramid', str(n_levels)])\n print(\"...done\")\n\n k = 0\n for l in np.arange(n_levels+1):\n f = s_factors[l]\n pt = path + '/' + str(s_factors[l])\n if not os.path.exists(pt):\n os.mkdir(pt)\n\n t1 = ET.SubElement(r, 'version')\n t2 = ET.SubElement(t1, 'scale')\n t2.text = str(f)\n\n n_horiz, n_vert = n_splits[k]\n t2 = ET.SubElement(t1, 'split')\n t2.text = str((n_horiz, n_vert))\n\n # img_scaled = img_cropped.shrink(f, f)\n # load the corresponding level in the pyramid:\n img_scaled = VImage.VImage(path + '/pyramid-level_' + str(l) + '.ppm')\n width = img_scaled.Xsize()\n height = img_scaled.Ysize()\n\n w = width / n_horiz\n h = height / n_vert\n ov = ovlap/100.0/2.0 # ovlap is in % and we need half of it\n sv = int(n_vert != 1)\n sh = int(n_horiz != 1)\n\n print('Processing scale %d and tile %d,%d' % (f, n_horiz, n_vert))\n\n y0 = 0\n for i in np.arange(n_vert):\n x0 = 0\n\n if i < n_vert - 1:\n y1 = int(y0 + h * (1.0 + sv*ov)) - 1\n else:\n y1 = height - 1\n\n for j in np.arange(n_horiz):\n if j < n_horiz - 1:\n x1 = int(x0 + w * (1.0 + sh*ov)) - 1\n else:\n x1 = width - 1\n\n tile_name = 'tile_' + str(i) + '_' + str(j) + '.' + res_format\n res_file = pt + '/' + tile_name\n print('Save to' + res_file)\n t2 = ET.SubElement(t1, 'tile',\n {'name': tile_name, 'x0':str(x0), 'y0':str(y0), 'x1':str(x1), 'y1':str(y1)})\n\n #print('x0 = %d, y0 = %d, x1 = %d, y1 = %d, sh = %d, ov = %f; image: %d x %d' % (x0, y0, x1, y1, sh, ov, width, height))\n\n # do the actual work...\n img_sub = img_scaled.extract_area(x0, y0, x1-x0+1, y1-y0+1)\n img_sub.write(res_file)\n\n x0 = int(x1 + 1 - 2.0 * w * ov)\n\n y0 = int(y1 + 1 - 2.0 * w * ov)\n\n k += 1\n\n\n raw_txt = ET.tostring(r, 'utf-8')\n reparsed = minidom.parseString(raw_txt)\n pp_txt = reparsed.toprettyxml(indent=' ')\n\n #print(pp_txt)\n meta_file = open(path+'/meta.xml', 'w')\n meta_file.write(pp_txt)\n\n return\n\n\ndef main():\n global img_file, res_prefix, s_factors, n_splits, ovlap, res_format, n_levels\n\n p = opt.ArgumentParser(description=\"Generate a series of re-scaled and cropped versions of the original slide.\")\n p.add_argument('img_file', action='store', help='image file')\n p.add_argument('--prefix', action='store', help='path where to store the results', default='./')\n p.add_argument('--levels', action='store', help='number of levels in pyramid', type=int, default=1)\n p.add_argument('--split', action='store', help='number of splits on horizontal and vertical axes at each level',\n default='(1,1)')\n p.add_argument('--overlap', action='store', help='overlapping percentage between images', type=float, default=0)\n p.add_argument('--format', action='store', help='output image format',\n choices=['ppm', 'tiff', 'jpeg'], default='ppm')\n\n args = p.parse_args()\n img_file = args.img_file\n res_prefix = args.prefix\n res_format = args.format\n n_levels = args.levels\n\n # all non-integer scaling factors are rounded and ensured to be\n # positive\n s_factors = [int(2**_f) for _f in np.arange(args.levels+1)]\n\n # number of splits horizontally and vertically, at each shrinking level:\n rx = re.compile(r'(\\d+,\\d+)')\n n_splits = [(int(abs(float(h))),int(abs(float(v))))\n for h, v in [_p.split(',') for _p in rx.findall(args.split)]]\n\n # window overlapping\n ovlap = args.overlap\n\n if len(s_factors) != len(n_splits):\n raise(ValueError('There must be (1+levels) split specifiers (first specifiers refers to original scale)'))\n\n run()\n\n return\n\nif __name__ == '__main__':\n main()\n" ]
[ [ "numpy.arange" ] ]
Kaushal28/FOTS-PyTorch
[ "30f6180754899c7f5fb35845ab5d6f108eb1b4a8" ]
[ "trainer.py" ]
[ "import os\nfrom time import time\n\nimport torch\n\nimport numpy as np\n\nfrom tqdm import tqdm\n\nfrom utils import TranscriptEncoder, classes\n\nclass Train:\n \"\"\"\n Trainer class which defines model training and evaluation methods.\n \"\"\"\n\n def __init__(self, model, train_iterator, valid_iterator, loss, metric, optimizer, lr_scheduler, config):\n super().__init__()\n\n self.device = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n self.model = model\n self.train_iterator = train_iterator\n self.valid_iterator = valid_iterator\n self.optimizer = optimizer\n self.lr_scheduler = lr_scheduler\n self.transcript_encoder = TranscriptEncoder(classes)\n self.metric = metric\n self.epochs = config[\"epochs\"]\n self.loss = loss\n self.config = config\n\n self.model.to(self.device)\n\n def _eval_metrics(self, y_pred, y_true):\n \"\"\"\n Calculate evaluation metrics given predictions and ground truths.\n \"\"\"\n precious, recall, hmean = self.metric(y_pred, y_true)\n return np.array([precious, recall, hmean])\n\n def train_epoch(self, epoch):\n \"\"\"Train a single epoch.\"\"\"\n self.model.train()\n epoch_loss, total_metrics = 0, np.zeros(3)\n\n for i, batch in tqdm(enumerate(self.train_iterator), total=len(self.train_iterator), position=0, leave=True):\n # image_paths, images, bboxs, transcripts, score_map, geo_map, mapping = batch\n images, score_map, geo_map, training_mask = batch\n\n images = images.to(self.device)\n score_map = score_map.to(self.device)\n geo_map = geo_map.to(self.device)\n training_mask = training_mask.to(self.device)\n\n self.optimizer.zero_grad()\n \n # Forward pass\n # pred_score_map, pred_geo_map, pred_recog, pred_boxes, pred_mapping, indices = self.model(images, bboxs, mapping)\n\n # Forward pass\n pred_score_map, pred_geo_map = self.model(images)\n\n # Calculate loss\n loss = self.loss(score_map, pred_score_map, geo_map, pred_geo_map, training_mask)\n # Backward pass\n loss.backward()\n self.optimizer.step()\n\n epoch_loss += loss.item()\n\n # transcripts = transcripts[indices]\n # pred_boxes = pred_boxes[indices]\n # pred_mapping = mapping[indices]\n # pred_fns = [image_paths[i] for i in pred_mapping]\n\n # labels, label_lengths = self.transcript_encoder.encode(transcripts.tolist())\n # labels, label_lengths = labels.to(self.device), label_lengths.to(self.device)\n # recog = (labels, label_lengths)\n\n # # Calculate loss\n # loss = self.loss(score_map, pred_score_map, geo_map, pred_geo_map, recog, pred_recog)\n # # Backward pass\n # loss.backward()\n # self.optimizer.step()\n\n # epoch_loss += loss.item()\n # print(f'### LOSS: {loss.item()}')\n # pred_transcripts = []\n # if len(pred_mapping) > 0:\n # pred, lengths = pred_recog\n # _, pred = pred.max(2)\n # for idx in range(lengths.numel()):\n # l = lengths[idx]\n # p = pred[:l, idx]\n # txt = self.transcript_encoder.decode(p, l)\n # pred_transcripts.append(txt)\n # pred_transcripts = np.array(pred_transcripts)\n\n # total_metrics += self._eval_metrics(\n # (pred_boxes, pred_transcripts, pred_fns),\n # (bboxs, transcripts, pred_fns)\n # )\n \n return (\n epoch_loss / len(self.train_iterator)\n )\n # return (\n # epoch_loss / len(self.train_iterator),\n # total_metrics[0] / len(self.train_iterator), # precision\n # total_metrics[1] / len(self.train_iterator), # recall\n # total_metrics[2] / len(self.train_iterator) # f1-score\n # )\n\n def eval_epoch(self):\n \"\"\"Validate after training a single epoch.\"\"\"\n self.model.eval()\n # total_metrics = np.zeros(3)\n\n val_loss = 0\n\n with torch.no_grad():\n for i, batch in tqdm(enumerate(self.valid_iterator), total=len(self.valid_iterator), position=0, leave=True):\n # image_paths, images, bboxs, transcripts, score_map, geo_map, mapping = batch\n images, score_map, geo_map, training_mask = batch\n\n images = images.to(self.device)\n score_map = score_map.to(self.device)\n geo_map = geo_map.to(self.device)\n training_mask = training_mask.to(self.device)\n\n\n # Forward pass\n # pred_score_map, pred_geo_map, pred_recog, pred_boxes, pred_mapping, indices = self.model(images, bboxs, mapping)\n\n # Forward pass\n pred_score_map, pred_geo_map = self.model(images)\n\n # Calculate loss\n val_loss += self.loss(score_map, pred_score_map, geo_map, pred_geo_map, training_mask)\n\n # pred_transcripts = []\n # pred_fns = []\n # if len(pred_mapping) > 0:\n # pred_mapping = pred_mapping[indices]\n # pred_boxes = pred_boxes[indices]\n # pred_fns = [image_paths[i] for i in pred_mapping]\n\n # pred, lengths = pred_recog\n # _, pred = pred.max(2)\n # for i in range(lengths.numel()):\n # l = lengths[i]\n # p = pred[:l, i]\n # t = self.transcript_encoder.decode(p, l)\n # pred_transcripts.append(t)\n # pred_transcripts = np.array(pred_transcripts)\n\n # gt_fns = [image_paths[i] for i in mapping]\n # total_metrics += self._eval_metrics((pred_boxes, pred_transcripts, pred_fns),\n # (bboxs, transcripts, gt_fns))\n\n return val_loss / len(self.valid_iterator)\n \n # return (\n # total_metrics[0] / len(self.train_iterator), # precision\n # total_metrics[1] / len(self.train_iterator), # recall\n # total_metrics[2] / len(self.train_iterator) # f1-score\n # )\n \n @staticmethod\n def epoch_time(start_time, end_time):\n \"\"\"Measure single epoch time based on epoch's start and end times.\"\"\"\n elapsed_time = end_time - start_time\n elapsed_mins = int(elapsed_time / 60)\n elapsed_secs = int(elapsed_time - (elapsed_mins * 60))\n return elapsed_mins, elapsed_secs\n \n def _save_model(self, name, model):\n \"\"\"Save the given model at given path.\"\"\"\n if not os.path.isdir(self.config[\"model_save_path\"]):\n os.makedirs(self.config[\"model_save_path\"], exist_ok=True)\n torch.save(\n model.state_dict(),\n os.path.join(self.config[\"model_save_path\"], name)\n )\n\n def train(self):\n \"\"\"Train the model for given numner of epochs.\"\"\"\n\n best_val_loss = float('inf')\n for epoch in range(self.epochs):\n # Epoch start time\n start_time = time()\n\n # Train\n # loss, train_precision, train_recall, train_f1 = self.train_epoch(epoch)\n train_loss = self.train_epoch(epoch)\n # Evaluate\n # val_precision, val_recall, val_f1 = \n val_loss = self.eval_epoch()\n\n self.lr_scheduler.step(val_loss)\n\n # Epoch start time\n end_time = time()\n\n epoch_mins, epoch_secs = self.epoch_time(start_time, end_time)\n\n # Save the model when loss improves and at last epoch\n if val_loss < best_val_loss:\n print(f\"Loss reduced from previous best {best_val_loss} to {val_loss}. Saving the model!\")\n self._save_model(f\"FOTS_epoch{epoch+1}.pt\", self.model)\n best_val_loss = val_loss\n \n if epoch+1 == self.epochs:\n self._save_model(f\"FOTS_epoch{epoch+1}.pt\", self.model)\n\n # Log the training progress per epoch\n # print(f'Epoch: {epoch+1:02} | Time: {epoch_mins}m {epoch_secs}s')\n # print(f'\\t Train Loss: {loss:.3f} | Train Precision: {train_precision:7.3f} | Train Recall: {train_recall:7.3f} | Train F1: {train_f1:7.3f}')\n # print(f'\\t Val. Precision: {val_precision:7.3f} | Val. Recall: {val_recall:7.3f} | Val F1: {val_f1:7.3f}')\n print(f'Epoch: {epoch+1:02} | Time: {epoch_mins}m {epoch_secs}s')\n print(f'\\t Train Loss: {train_loss:.3f}')\n print(f'\\t Val. Loss: {val_loss:.3f}\\n')\n" ]
[ [ "numpy.array", "torch.cuda.is_available", "torch.no_grad", "numpy.zeros" ] ]
Ruomei/model-optimization
[ "b6a97f26e240c39a1d4290f4639f7136168774aa" ]
[ "tensorflow_model_optimization/python/core/quantization/keras/quantize_wrapper_test.py" ]
[ "# Copyright 2019 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"Tests for QuantizeWrapper.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nfrom absl.testing import parameterized\n\nimport numpy as np\nimport tensorflow as tf\n\nfrom tensorflow_model_optimization.python.core.quantization.keras import quantize_aware_activation\nfrom tensorflow_model_optimization.python.core.quantization.keras import quantize_wrapper\nfrom tensorflow_model_optimization.python.core.quantization.keras.default_8bit import default_8bit_quantize_registry\n\nQuantizeAwareActivation = quantize_aware_activation.QuantizeAwareActivation\nQuantizeWrapper = quantize_wrapper.QuantizeWrapper\nQuantizeRegistry = default_8bit_quantize_registry.QuantizeRegistry\n\nkeras = tf.keras\nlayers = tf.keras.layers\n\ncustom_object_scope = tf.keras.utils.custom_object_scope\ndeserialize_layer = tf.keras.layers.deserialize\nserialize_layer = tf.keras.layers.serialize\n\n\nclass QuantizeWrapperTest(tf.test.TestCase, parameterized.TestCase):\n\n def setUp(self):\n super(QuantizeWrapperTest, self).setUp()\n self.quantize_registry = QuantizeRegistry()\n\n def testQuantizesWeightsInLayer(self):\n weights = lambda shape, dtype: np.array([[-1.0, 0.0], [0.0, 1.0]])\n layer = keras.layers.Dense(2, kernel_initializer=weights)\n\n model = keras.Sequential([\n QuantizeWrapper(\n layer=layer,\n quantize_config=self.quantize_registry.get_quantize_config(layer),\n input_shape=(2,))\n ])\n\n # FakeQuant([-1.0, 1.0]) = [-0.9882355, 0.9882355]\n # Obtained from tf.fake_quant_with_min_max_vars\n self.assertAllClose(\n np.array([[-0.9882355, 0.9882355]]),\n # Inputs are all ones, so result comes directly from weights.\n model.predict(np.ones((1, 2))))\n\n # TODO(pulkitb): Extend test to support more layers.\n # The test validates several keras layers, but has limitations currently.\n # 1. Only layers with 'kernel' attribute work. Need to extend to others.\n # 2. Activations are not tested currently.\n # 3. RNN layers need to be added\n\n @parameterized.parameters(\n (layers.Conv1D, (3, 6), {\n 'filters': 4,\n 'kernel_size': 2\n }),\n (layers.Conv2D, (4, 6, 1), {\n 'filters': 4,\n 'kernel_size': (2, 2)\n }),\n (layers.Conv2DTranspose, (7, 6, 3), {\n 'filters': 2,\n 'kernel_size': (3, 3)\n }),\n (layers.Conv3D, (5, 7, 6, 3), {\n 'filters': 2,\n 'kernel_size': (3, 3, 3)\n }),\n (layers.Conv3DTranspose, (5, 7, 6, 3), {\n 'filters': 2,\n 'kernel_size': (3, 3, 3)\n }),\n # TODO(pulkitb): Add missing SeparableConv layers. The initializers are\n # different, so will need a change.\n (layers.Dense, (3,), {\n 'units': 2\n }),\n (layers.LocallyConnected1D, (3, 6), {\n 'filters': 4,\n 'kernel_size': 2\n }),\n (layers.LocallyConnected2D, (4, 6, 1), {\n 'filters': 4,\n 'kernel_size': (2, 2)\n }))\n def testQuantizesWeights_KerasLayers(self, layer_type, input_shape, kwargs):\n self.weights = None\n\n def _get_random_weights(shape, dtype): # pylint: disable=unused-argument\n self.weights = np.random.rand(*shape)\n return self.weights\n\n def _get_quantized_weights(shape, dtype): # pylint: disable=unused-argument\n assert tuple(shape) == self.weights.shape\n\n # Default values used in DefaultRegistry.\n return tf.quantization.fake_quant_with_min_max_vars(\n self.weights, -6.0, 6.0, num_bits=8, narrow_range=True)\n\n layer = layer_type(kernel_initializer=_get_random_weights, **kwargs)\n quantized_model = keras.Sequential([\n QuantizeWrapper(\n layer=layer,\n quantize_config=self.quantize_registry.get_quantize_config(layer),\n input_shape=input_shape)\n ])\n # `model` gets constructed with same parameters as `quantized_model`. The\n # weights used are a quantized version of weights used in `quantized_model`.\n # This ensures the results of both the models should be the same since\n # quantization has been applied externally to `model`.\n model = keras.Sequential([\n layer_type(\n input_shape=input_shape,\n kernel_initializer=_get_quantized_weights,\n **kwargs)\n ])\n\n inputs = np.random.rand(1, *input_shape)\n # `quantized_model` should apply FakeQuant. Explicitly applying to the\n # results of `model` to verify QuantizeWrapper works as expected.\n expected_output = tf.quantization.fake_quant_with_min_max_vars(\n model.predict(inputs), -6.0, 6.0, num_bits=8, narrow_range=False)\n self.assertAllClose(expected_output, quantized_model.predict(inputs))\n\n def testQuantizesOutputsFromLayer(self):\n # TODO(pulkitb): Increase coverage by adding other output quantize layers\n # such as AveragePooling etc.\n\n layer = layers.ReLU()\n quantized_model = keras.Sequential([\n QuantizeWrapper(\n layers.ReLU(),\n quantize_config=self.quantize_registry.get_quantize_config(layer))\n ])\n\n model = keras.Sequential([layers.ReLU()])\n\n inputs = np.random.rand(1, 2, 1)\n expected_output = tf.quantization.fake_quant_with_min_max_vars(\n model.predict(inputs), -6.0, 6.0, num_bits=8, narrow_range=False)\n self.assertAllClose(expected_output, quantized_model.predict(inputs))\n\n def testSerializationQuantizeWrapper(self):\n input_shape = (2,)\n layer = keras.layers.Dense(3)\n wrapper = QuantizeWrapper(\n layer=layer,\n quantize_config=self.quantize_registry.get_quantize_config(layer),\n input_shape=input_shape)\n\n custom_objects = {\n 'QuantizeAwareActivation': QuantizeAwareActivation,\n 'QuantizeWrapper': QuantizeWrapper\n }\n custom_objects.update(default_8bit_quantize_registry._types_dict())\n\n serialized_wrapper = serialize_layer(wrapper)\n with custom_object_scope(custom_objects):\n wrapper_from_config = deserialize_layer(serialized_wrapper)\n\n self.assertEqual(wrapper_from_config.get_config(), wrapper.get_config())\n\n def testQuantizeWrapper_FailsWithModel(self):\n layer = keras.layers.Dense(5, activation='relu', input_shape=(10,))\n model = keras.Sequential([layer])\n\n with self.assertRaises(ValueError):\n QuantizeWrapper(\n model,\n quantize_config=self.quantize_registry.get_quantize_config(layer))\n\n # TODO(pulkitb): Add test to ensure weights are also preserved.\n\n\nif __name__ == '__main__':\n tf.test.main()\n" ]
[ [ "numpy.array", "numpy.random.rand", "numpy.ones", "tensorflow.test.main", "tensorflow.quantization.fake_quant_with_min_max_vars" ] ]
harunpehlivan/LightGBM
[ "8ba65be9c93b79c095ea06e74de2cc5bf35ab169" ]
[ "examples/python-guide/simple_example.py" ]
[ "# coding: utf-8\n# pylint: disable = invalid-name, C0111\nimport json\nimport lightgbm as lgb\nimport pandas as pd\nfrom sklearn.metrics import mean_squared_error\n\n\n# load or create your dataset\nprint('Load data...')\ndf_train = pd.read_csv('../regression/regression.train', header=None, sep='\\t')\ndf_test = pd.read_csv('../regression/regression.test', header=None, sep='\\t')\n\ny_train = df_train[0].values\ny_test = df_test[0].values\nX_train = df_train.drop(0, axis=1).values\nX_test = df_test.drop(0, axis=1).values\n\n# create dataset for lightgbm\nlgb_train = lgb.Dataset(X_train, y_train)\nlgb_eval = lgb.Dataset(X_test, y_test, reference=lgb_train)\n\n# specify your configurations as a dict\nparams = {\n 'task': 'train',\n 'boosting_type': 'gbdt',\n 'objective': 'regression',\n 'metric': {'l2', 'auc'},\n 'num_leaves': 31,\n 'learning_rate': 0.05,\n 'feature_fraction': 0.9,\n 'bagging_fraction': 0.8,\n 'bagging_freq': 5,\n 'verbose': 0\n}\n\nprint('Start training...')\n# train\ngbm = lgb.train(params,\n lgb_train,\n num_boost_round=20,\n valid_sets=lgb_eval,\n early_stopping_rounds=5)\n\nprint('Save model...')\n# save model to file\ngbm.save_model('model.txt')\n\nprint('Start predicting...')\n# predict\ny_pred = gbm.predict(X_test, num_iteration=gbm.best_iteration)\n# eval\nprint('The rmse of prediction is:', mean_squared_error(y_test, y_pred) ** 0.5)\n\nprint('Dump model to JSON...')\n# dump model to json (and save to file)\nmodel_json = gbm.dump_model()\n\nwith open('model.json', 'w+') as f:\n json.dump(model_json, f, indent=4)\n\n\nprint('Feature names:', gbm.feature_name())\n\nprint('Calculate feature importances...')\n# feature importances\nprint('Feature importances:', list(gbm.feature_importance()))\n" ]
[ [ "pandas.read_csv", "sklearn.metrics.mean_squared_error" ] ]
sulaimanvesal/vertebraeSegementation
[ "eafdc946d31918194a83cbd79b66569ce19127de" ]
[ "src/model/dilated_unet.py" ]
[ "\"\"\"\r\n@Author: Sulaiman Vesal\r\nDate: Tuesday, 04, 2020\r\n\r\n\r\n\"\"\"\r\nfrom torch import nn, cat\r\nfrom torch.utils.tensorboard import SummaryWriter\r\nfrom torch import rand\r\n\r\nclass Encoder(nn.Module):\r\n\r\n def __init__(self, filters=64, in_channels=3, n_block=3, kernel_size=(3, 3), batch_norm=True, padding='same'):\r\n super().__init__()\r\n self.filter = filters\r\n for i in range(n_block):\r\n out_ch = filters * 2 ** i\r\n if i == 0:\r\n in_ch = in_channels\r\n else:\r\n in_ch = filters * 2 ** (i - 1)\r\n\r\n if padding == 'same':\r\n pad = kernel_size[0] // 2\r\n else:\r\n pad = 0\r\n model = [nn.Conv2d(in_channels=in_ch, out_channels=out_ch, kernel_size=kernel_size, padding=pad),\r\n nn.ReLU(inplace=True)]\r\n if batch_norm:\r\n model += [nn.BatchNorm2d(num_features=out_ch)]\r\n model += [nn.Conv2d(in_channels=out_ch, out_channels=out_ch, kernel_size=kernel_size, padding=pad),\r\n nn.ReLU(inplace=True)]\r\n if batch_norm:\r\n model += [nn.BatchNorm2d(num_features=out_ch)]\r\n self.add_module('encoder%d' % (i + 1), nn.Sequential(*model))\r\n conv = [nn.Conv2d(in_channels=in_ch * 3, out_channels=out_ch, kernel_size=1), nn.ReLU(inplace=True)]\r\n self.add_module('conv1_%d' % (i + 1), nn.Sequential(*conv))\r\n\r\n def forward(self, x):\r\n skip = []\r\n output = x\r\n res = None\r\n i = 0\r\n for name, layer in self._modules.items():\r\n if i % 2 == 0:\r\n output = layer(output)\r\n skip.append(output)\r\n else:\r\n if i > 1:\r\n output = cat([output, res], 1)\r\n output = layer(output)\r\n output = nn.MaxPool2d(kernel_size=(2,2))(output)\r\n res = output\r\n i += 1\r\n return output, skip\r\n\r\n\r\nclass Bottleneck(nn.Module):\r\n def __init__(self, filters=64, n_block=3, depth=4, kernel_size=(3,3)):\r\n super().__init__()\r\n out_ch = filters * 2 ** n_block\r\n in_ch = filters * 2 ** (n_block - 1)\r\n for i in range(depth):\r\n dilate = 2 ** i\r\n model = [nn.Conv2d(in_channels=in_ch, out_channels=out_ch, kernel_size=kernel_size, padding=dilate,\r\n dilation=dilate),nn.ReLU(inplace=True)]\r\n self.add_module('bottleneck%d' % (i + 1), nn.Sequential(*model))\r\n if i == 0:\r\n in_ch = out_ch\r\n\r\n def forward(self, x):\r\n bottleneck_output = 0\r\n output = x\r\n for _, layer in self._modules.items():\r\n output = layer(output)\r\n bottleneck_output += output\r\n return bottleneck_output\r\n\r\n\r\nclass Decoder(nn.Module):\r\n def __init__(self, filters=64, n_block=3, kernel_size=(3, 3), batch_norm=True, padding='same'):\r\n super().__init__()\r\n self.n_block = n_block\r\n if padding == 'same':\r\n pad = kernel_size[0] // 2\r\n else:\r\n pad = 0\r\n for i in reversed(range(n_block)):\r\n out_ch = filters * 2 ** i\r\n in_ch = 2 * out_ch\r\n model = [nn.UpsamplingNearest2d(scale_factor=(2, 2)),\r\n nn.Conv2d(in_channels=in_ch, out_channels=out_ch, kernel_size=kernel_size,\r\n padding=pad)]\r\n self.add_module('decoder1_%d' % (i + 1), nn.Sequential(*model))\r\n\r\n model = [nn.Conv2d(in_channels=in_ch, out_channels=out_ch, kernel_size=kernel_size, padding=pad),\r\n nn.ReLU(inplace=True)]\r\n if batch_norm:\r\n model += [nn.BatchNorm2d(num_features=out_ch)]\r\n model += [nn.Conv2d(in_channels=out_ch, out_channels=out_ch, kernel_size=kernel_size, padding=pad),\r\n nn.ReLU(inplace=True)]\r\n if batch_norm:\r\n model += [nn.BatchNorm2d(num_features=out_ch)]\r\n self.add_module('decoder2_%d' % (i + 1), nn.Sequential(*model))\r\n\r\n def forward(self, x, skip):\r\n i = 0\r\n output = x\r\n for _, layer in self._modules.items():\r\n output = layer(output)\r\n if i % 2 == 0:\r\n output = cat([skip.pop(), output], 1)\r\n i += 1\r\n return output\r\n\r\n\r\nclass Segmentation_model(nn.Module):\r\n def __init__(self, filters=32, in_channels=3, n_block=4, bottleneck_depth=4, n_class=3):\r\n super().__init__()\r\n self.encoder = Encoder(filters=filters, in_channels=in_channels, n_block=n_block)\r\n self.bottleneck = Bottleneck(filters=filters, n_block=n_block, depth=bottleneck_depth)\r\n self.decoder = Decoder(filters=filters, n_block=n_block)\r\n self.classifier = nn.Conv2d(in_channels=filters, out_channels=n_class, kernel_size=(1, 1))\r\n\r\n def forward(self, x, features_out=True):\r\n output, skip = self.encoder(x)\r\n output_bottleneck = self.bottleneck(output)\r\n output = self.decoder(output_bottleneck, skip)\r\n output = self.classifier(output)\r\n if features_out:\r\n return output, output_bottleneck\r\n else:\r\n return output\r\n\r\nif __name__ == '__main__':\r\n model = Segmentation_model(filters=32, n_block=4)\r\n x = rand(2, 3, 224, 224)\r\n output = model(x)\r\n print(\"finish\")\r\n input()\r\n\r\n" ]
[ [ "torch.rand", "torch.cat", "torch.nn.MaxPool2d", "torch.nn.Sequential", "torch.nn.BatchNorm2d", "torch.nn.ReLU", "torch.nn.Conv2d", "torch.nn.UpsamplingNearest2d" ] ]
flynnbr11/QMD
[ "ac8cfe1603658ee9b916452f29b99460ee5e3d44", "ac8cfe1603658ee9b916452f29b99460ee5e3d44" ]
[ "qmla/remote_bayes_factor.py", "qmla/shared_functionality/probe_set_generation.py" ]
[ "import copy\nimport pickle\nimport random\nimport time as time\nimport numpy as np\nimport os as os\nimport pandas as pd\n\nimport matplotlib.pyplot as plt\nfrom matplotlib.gridspec import GridSpec\n\ntry:\n from lfig import LatexFigure\nexcept:\n from qmla.shared_functionality.latex_figure import LatexFigure\n\nimport qmla.model_building_utilities as model_building_utilities\nimport qmla.model_for_comparison\nimport qmla.logging\nimport qmla.redis_settings as rds\nimport redis\n\npickle.HIGHEST_PROTOCOL = 4\nplt.switch_backend(\"agg\")\n\n\n__all__ = [\"remote_bayes_factor_calculation\", \"plot_dynamics_from_models\"]\n\n\ndef remote_bayes_factor_calculation(\n model_a_id,\n model_b_id,\n branch_id=None,\n # num_times_to_use='all', # TODO remove\n bf_data_folder=None,\n times_record=\"BayesFactorsTimes.txt\",\n check_db=False,\n bayes_threshold=1,\n host_name=\"localhost\",\n port_number=6379,\n qid=0,\n log_file=\"rq_output.log\",\n):\n r\"\"\"\n Standalone function to compute Bayes factors.\n\n Used in conjunction with redis databases so this calculation can be\n performed without any knowledge other than model IDs.\n Data is unpickled from a redis databse, containing\n `learned_model` information, i.e. final parameters etc.\n Given `model_id`s correspond to model names in the database, which are combined\n with the final learned parameters to reconstruct model classes of\n complete learned models.\n Each model had been trained on a given set of experimental parmaeters (times).\n The reconstructed model classes are updated according to the experimental parameters\n of the opponent model, such that both models have underwent the same experiments.\n From these we extract log likelihoods to compute the Bayes factor, BF(A,B).\n Models have a unique pair_id, simply (min(A,B), max(A,B)).\n For BF(A,B) >> 1, A is deemed the winner; BF(A,B)<<1 deems B the winner.\n The result is then stored redis databases:\n - bayes_factors_db: BF(A,B)\n - bayes_factors_winners_db: id of winning model\n - active_branches_bayes: when complete, increase the count of\n complete pairs' BF on the given branch.\n\n :param int model_a_id: unique id for model A\n :param int model_b_id: unique id for model B\n :param int branch_id: unique id of branch the pair (A,B) are on\n :param str or int num_times_to_use: how many times, used during the training of\n models A,B, to use during the BF calculation. Default 'all'; if\n otherwise, Nt, keeps the most recent Nt experiment times of A,B.\n :param str bf_data_folder: folder path to store information such as times\n used during calculation, and plots of posterior marginals.\n :param str times_record: filename to store times used during calculation.\n :param bool check_db: look in redis databases to check if this pair's BF\n has already been computed; return pre-computed BF if so.\n :param float bayes_threshold: value to determine whether either model is superior\n enough to \"win\" the comparison. If 1 < BF < threshold, neither win.\n :param str host_name: name of host server on which redis database exists.\n :param int port_number: this QMLA instance's unique port number,\n on which redis database exists.\n :param int qid: QMLA id, unique to a single instance within a run.\n Used to identify the redis database corresponding to this instance.\n :param str log_file: Path of the log file.\n \"\"\"\n\n def log_print(to_print_list):\n qmla.logging.print_to_log(\n to_print_list=to_print_list,\n log_file=log_file,\n log_identifier=\"BF ({}/{})\".format(int(model_a_id), int(model_b_id)),\n )\n\n log_print([\"BF start on branch\", branch_id])\n num_redis_retries = (\n 5 # TODO this is a hideous hack to get around redis database temporary failures\n )\n time_start = time.time()\n\n # Access databases\n for k in range(num_redis_retries):\n try:\n redis_databases = rds.get_redis_databases_by_qmla_id(\n host_name, port_number, qid\n )\n qmla_core_info_database = redis_databases[\"qmla_core_info_database\"]\n learned_models_info_db = redis_databases[\"learned_models_info_db\"]\n learned_models_ids = redis_databases[\"learned_models_ids\"]\n bayes_factors_db = redis_databases[\"bayes_factors_db\"]\n bayes_factors_winners_db = redis_databases[\"bayes_factors_winners_db\"]\n active_branches_learning_models = redis_databases[\n \"active_branches_learning_models\"\n ]\n active_branches_bayes = redis_databases[\"active_branches_bayes\"]\n active_interbranch_bayes = redis_databases[\"active_interbranch_bayes\"]\n any_job_failed_db = redis_databases[\"any_job_failed\"]\n\n # Retrieve data from databases\n qmla_core_info_dict = pickle.loads(\n redis_databases[\"qmla_core_info_database\"][\"qmla_settings\"]\n )\n break\n except Exception as e:\n if k == num_redis_retries - 1:\n log_print(\n [\n \"BF Failed (branch {}) to retrieve redis databases. Error: {}\".format(\n branch_id, e\n )\n ]\n )\n any_job_failed_db.set(\"Status\", 1)\n raise\n\n # Whether to build plots\n save_plots_of_posteriors = False\n plot_level = qmla_core_info_dict[\"plot_level\"]\n figure_format = qmla_core_info_dict[\"figure_format\"]\n\n # Get model instances\n for k in range(num_redis_retries):\n try:\n model_a = qmla.model_for_comparison.ModelInstanceForComparison(\n model_id=model_a_id,\n qid=qid,\n opponent=model_b_id,\n log_file=log_file,\n host_name=host_name,\n port_number=port_number,\n )\n break\n except Exception as e:\n if k == num_redis_retries - 1:\n log_print(\n [\n \"BF Failed to instantiate model {}. Error: {}\".format(\n model_a_id, e\n )\n ]\n )\n any_job_failed_db.set(\"Status\", 1)\n raise\n\n for k in range(num_redis_retries):\n try:\n model_b = qmla.model_for_comparison.ModelInstanceForComparison(\n model_id=model_b_id,\n qid=qid,\n opponent=model_a_id,\n log_file=log_file,\n host_name=host_name,\n port_number=port_number,\n )\n break\n except Exception as e:\n if k == num_redis_retries - 1:\n log_print(\n [\n \"BF Failed to instantiate model {}. Error: {}\".format(\n model_b_id, e\n )\n ]\n )\n any_job_failed_db.set(\"Status\", 1)\n raise\n\n log_print([\"Both models instantiated on branch {}.\".format(branch_id)])\n\n # Take a copy of each updater before updates (for plotting later)\n for k in range(num_redis_retries):\n try:\n updater_a_copy = copy.deepcopy(model_a.qinfer_updater)\n updater_b_copy = copy.deepcopy(model_b.qinfer_updater)\n break\n except Exception as e:\n if k == num_redis_retries - 1:\n log_print([\"BF Failed to copy updaters. Error: {}\".format(e)])\n any_job_failed_db.set(\"Status\", 1)\n raise\n\n # Update the models with the times trained by the other model.\n for k in range(num_redis_retries):\n try:\n log_l_a = model_a.update_log_likelihood(\n new_times=model_b.times_learned_over,\n new_experimental_params=model_b.track_experiment_parameters,\n )\n break\n except Exception as e:\n if k == num_redis_retries - 1:\n log_print(\n [\n \"BF Failed to compute log likelihood for {}. Error: {}\".format(\n model_a_id, e\n )\n ]\n )\n any_job_failed_db.set(\"Status\", 1)\n raise\n for k in range(num_redis_retries):\n try:\n log_l_b = model_b.update_log_likelihood(\n new_times=model_a.times_learned_over,\n new_experimental_params=model_a.track_experiment_parameters,\n )\n break\n except Exception as e:\n if k == num_redis_retries - 1:\n log_print(\n [\n \"BF Failed to compute log likelihood for {}. Error: {}\".format(\n model_b_id, k\n )\n ]\n )\n any_job_failed_db.set(\"Status\", 1)\n raise\n\n bayes_factor = np.exp(log_l_a - log_l_b)\n\n # Plot the posterior of the true model only\n if save_plots_of_posteriors and (model_a.is_true_model or model_b.is_true_model):\n if model_a.is_true_model:\n true_model = model_a\n updater_copy = updater_a_copy\n elif model_b.is_true_model:\n true_model = model_b\n updater_copy = updater_b_copy\n\n try:\n plot_posterior_marginals(\n model=true_model,\n qmla_id=qid,\n initial_updater_copy=updater_copy,\n save_directory=bf_data_folder,\n )\n log_print([\"Plotting posterior marginal of true model succeeded.\"])\n except BaseException:\n log_print([\"Plotting posterior marginal of true model failed.\"])\n pass\n\n # Plot dynamics on which models were compared\n if plot_level >= 4:\n try:\n log_print([\"Plotting dynamics of models involved.\"])\n plot_dynamics_from_models(\n models=[model_a, model_b],\n exp_msmts=qmla_core_info_dict[\"experimental_measurements\"],\n bayes_factor=bayes_factor,\n bf_times=model_a.bf_times, # same as model_b.bf_times\n save_directory=bf_data_folder,\n figure_format=figure_format,\n )\n except:\n log_print([\"plot failure: plot_dynamics_from_models\"])\n else:\n log_print([\"NOT Plotting dynamics of models involved.\"])\n\n # Present result\n log_print(\n [\n \"BF computed on branch {}: A:{}; B:{}; log10 BF={}\".format(\n branch_id, model_a_id, model_b_id, np.round(np.log10(bayes_factor), 2)\n )\n ]\n )\n if bayes_factor < 1e-160:\n bayes_factor = 1e-160\n elif bayes_factor > 1e160:\n bayes_factor = 1e160\n\n pair_id = model_building_utilities.unique_model_pair_identifier(\n model_a_id, model_b_id\n )\n\n for k in range(num_redis_retries):\n try:\n if float(model_a_id) < float(model_b_id):\n # so that BF in database always refers to (low/high), not (high/low).\n bayes_factors_db.set(pair_id, bayes_factor)\n else:\n bayes_factors_db.set(pair_id, (1.0 / bayes_factor))\n break\n except Exception as e:\n if k == num_redis_retries - 1:\n log_print([\"BF Failed to set bf on redis bf db. Error: \", e])\n any_job_failed_db.set(\"Status\", 1)\n raise\n\n # Record winner if BF > threshold\n for k in range(num_redis_retries):\n try:\n if bayes_factor > bayes_threshold:\n bayes_factors_winners_db.set(pair_id, \"a\")\n elif bayes_factor < (1.0 / bayes_threshold):\n bayes_factors_winners_db.set(pair_id, \"b\")\n else:\n log_print([\"Neither model much better.\"])\n log_print(\n [\n \"Renorm record A: \\n {}\".format(\n model_a.qinfer_updater._normalization_record\n ),\n \"\\nRenorm record B: \\n {}\".format(\n model_b.qinfer_updater._normalization_record\n ),\n ]\n )\n break\n except Exception as e:\n if k == num_redis_retries - 1:\n log_print([\"BF Failed to set bf on redis winner db. Error: \", e])\n any_job_failed_db.set(\"Status\", 1)\n raise\n\n # Record this result to the branch\n for k in range(num_redis_retries):\n try:\n if branch_id is not None:\n active_branches_bayes.incr(int(branch_id), 1)\n else:\n active_interbranch_bayes.set(pair_id, True)\n break\n except Exception as e:\n if k == num_redis_retries - 1:\n log_print([\"BF Failed to compute log likelihoods. Error: \", e])\n any_job_failed_db.set(\"Status\", 1)\n raise\n\n log_print(\n [\n \"BF finished on branch {}. rq time: {}\".format(\n branch_id,\n str(time.time() - time_start),\n )\n ]\n )\n\n del model_a, model_b\n return bayes_factor\n\n\n#########\n# Utilities\n#########\n\n\ndef log_print(to_print_list, log_file, log_identifier):\n r\"\"\"Wrapper for :func:`~qmla.print_to_log`\"\"\"\n qmla.logging.print_to_log(\n to_print_list=to_print_list, log_file=log_file, log_identifier=log_identifier\n )\n\n\n#########\n# Plotting\n#########\n\n\ndef plot_dynamics_from_models(\n models, exp_msmts, bf_times, bayes_factor, save_directory, figure_format=\"png\"\n):\n \"\"\"Plot the dynamics of the pair of models considered in a Bayes factor comparison.\n\n :param models: list of 2 models which were compared during this calculation, [model_a, model_b].\n :type models: :class:`~qmla.ModelInstanceForLearning`\n :param exp_msmts: times and expectation values for the system.\n :type exp_msmts: dict\n :param bf_times: Times used for the BF calculation\n :type bf_times: list\n :param bayes_factor: Bayes factor between the two input models, to be read as BF(model_a, model_b)\n :type bayes_factor: float\n :param save_directory: path where the generated figure is to be saved\n :type save_directory: path\n \"\"\"\n\n times = list(sorted(exp_msmts.keys()))\n lf = LatexFigure(fraction=0.45, auto_label=False)\n ax1 = lf.new_axis()\n lines = []\n\n for model in models:\n l = model.plot_dynamics(ax=ax1, times=times)\n lines.extend(l)\n ax1.set_xlim((min(times), max(times)))\n\n # Plot system measurements\n l = ax1.scatter(\n times, [exp_msmts[t] for t in times], label=r\"$Q$\", color=\"red\", alpha=0.6, s=5\n )\n lines.append(l)\n\n # Overlay times\n try:\n # in background, show how often that time was considered\n ax2 = ax1.twinx()\n num_times = int(len(times)) - 1\n l = ax2.hist(\n bf_times,\n bins=num_times,\n # TODO put on separate plot to see when higher times compared on\n range=(min(times), max(times)),\n histtype=\"stepfilled\",\n fill=False,\n label=r\"$t$\",\n alpha=0.25,\n )\n ax2.set_ylabel(\"Frequency\")\n max_freq = max(l[0])\n ax2.set_ylim(0, 1.6 * max_freq)\n ax2.set_yticks([0, int(max_freq / 2), max_freq])\n\n lines.append(l[-1][0])\n except BaseException:\n raise\n # pass\n\n bf = np.log10(bayes_factor)\n labels = [l.get_label() for l in lines]\n ax1.set_ylim(0, 1.6)\n ax1.set_yticks([0, 0.5, 1])\n ax1.set_ylabel(\"Expectation Value\")\n ax1.set_xlabel(\"Time\")\n\n ax1.legend(lines, labels, ncol=2, loc=\"upper center\")\n\n plot_path = os.path.join(\n save_directory,\n \"BF_{}_{}\".format(str(models[0].model_id), str(models[1].model_id)),\n )\n # plt.savefig(plot_path)\n lf.save(plot_path, file_format=figure_format)\n\n\ndef plot_models_dynamics(\n model_a,\n model_b,\n exp_msmts,\n plot_probes_path,\n bayes_factor,\n bf_times,\n qmla_id,\n log_file,\n save_directory=None,\n):\n times = list(sorted(exp_msmts.keys()))\n experimental_exp_vals = [exp_msmts[t] for t in times]\n fig, ax1 = plt.subplots()\n\n # Plot true measurements\n ax1.scatter(\n times, experimental_exp_vals, label=\"Exp data\", color=\"red\", alpha=0.6, s=5\n )\n ax1.set_ylabel(\"Exp Val\")\n plot_probes = pickle.load(open(plot_probes_path, \"rb\"))\n\n for mod in [model_a, model_b]:\n final_params = mod.qinfer_updater.est_mean()\n final_ham = np.tensordot(final_params, mod.model_terms_matrices, axes=1)\n dim = int(np.log2(np.shape(final_ham)[0]))\n plot_probe = plot_probes[dim]\n\n mod_exp_vals = [\n mod.exploration_class.get_expectation_value(\n ham=final_ham,\n t=t,\n state=plot_probe,\n log_file=log_file,\n log_identifier=\"[remote_bayes_factor: plotting]\",\n )\n for t in times\n ]\n ax1.plot(\n times,\n mod_exp_vals,\n label=str(\"({}) {}\".format(mod.model_id, mod.model_name_latex)),\n )\n try:\n # in background, show how often that time was considered\n ax2 = ax1.twinx()\n num_times = int(len(times)) - 1\n print(\"BF times: \", repr(bf_times))\n ax2.hist(\n bf_times,\n bins=num_times,\n # TODO put on separate plot to see when higher times compared on\n range=(min(times), max(times)),\n histtype=\"stepfilled\",\n fill=False,\n label=str(\"{} times total\".format(len(bf_times))),\n alpha=0.1,\n )\n ax2.set_ylabel(\"Frequency time was during comparison\")\n except BaseException:\n raise\n # pass\n\n bf = np.log10(bayes_factor)\n plt.title(\"[$log_{10}$ Bayes Factor]: \" + str(np.round(bf, 2)))\n plt.figlegend()\n\n plot_path = os.path.join(\n save_directory,\n \"BF_{}_{}.png\".format(str(model_a.model_id), str(model_b.model_id)),\n )\n plt.savefig(plot_path)\n\n\ndef plot_posterior_marginals(\n model,\n initial_updater_copy,\n qmla_id,\n save_directory,\n):\n r\"\"\"\n Shows parameter distribution before/after updates for BF.\n\n # TODO indicate which comparison this corresponds to\n # TODO plot posterior for both models in this comparison\n # TODO also plot learned posterior --\n # ie particle locations and weights that are learned, rather than\n # the normal approximation the BF assumes\n \"\"\"\n\n num_terms = model.qinfer_model.n_modelparams\n\n before_updates = [\n initial_updater_copy.posterior_marginal(idx_param=i) for i in range(num_terms)\n ]\n\n after_updates = [\n model.qinfer_updater.posterior_marginal(idx_param=i) for i in range(num_terms)\n ]\n\n ncols = int(np.ceil(np.sqrt(num_terms)))\n nrows = int(np.ceil(num_terms / ncols))\n fig, axes = plt.subplots(figsize=(10, 7), nrows=nrows, ncols=ncols)\n\n gs = GridSpec(\n nrows=nrows,\n ncols=ncols,\n )\n row = 0\n col = 0\n\n for param in range(num_terms):\n ax = fig.add_subplot(gs[row, col])\n\n ax.plot(\n before_updates[param][0],\n before_updates[param][1],\n color=\"blue\",\n ls=\"-\",\n label=\"Before\",\n )\n ax.plot(\n after_updates[param][0],\n after_updates[param][1],\n color=\"red\",\n ls=\":\",\n label=\"After\",\n )\n if row == 0 and col == ncols - 1:\n ax.legend()\n\n col += 1\n if col == ncols:\n col = 0\n row += 1\n\n save_path = os.path.join(\n save_directory, \"bf_posteriors_qmla_{}_model_{}\".format(qmla_id, model.model_id)\n )\n plt.savefig(save_path)\n", "r\"\"\"\nFunctions to generate sets of probe states to be used for training models.\n\nThese functions are set to exploration strategy attributes, which are then called in wrapper functions. \n- probe_generation_function: \n used for training, assumed to be the probes used on the system\n i.e. probes implemented during experiments. \n- simulator_probes_generation_subroutine: \n used for training, for the simulator. \n Should be the same as used for system, \n but in practice this is not always the case. \n Note exploration_strategy.shared_probes controls whether\n to default to the same probe set. \n- plot_probes_generation_subroutine: \n State to use for plotting purposes only (not training). \n Plots all use the same set of probes for consistency\n\n\"\"\"\n\nimport numpy as np\nimport itertools\nfrom scipy import linalg, stats\nimport random\n\nfrom scipy.linalg import expm\n\nimport qmla.utilities\nimport qmla.model_building_utilities\n\n__all__ = [\n \"separable_probe_dict\",\n \"tomographic_basis\",\n \"manual_set_probes\",\n \"eigenbasis_of_first_qubit\",\n \"NV_centre_ising_probes_plus\",\n \"plus_plus_with_phase_difference\",\n \"plus_probes_dict\",\n \"zero_state_probes\",\n \"separable_fermi_hubbard_half_filled\",\n \"fermi_hubbard_occupation_basis_down_in_first_site\",\n \"fermi_hubbard_occupation_basis_up_in_first_site\",\n \"fermi_hubbard_occupation_basis_down_in_all_sites\",\n \"pauli_eigenvector_based_probes\",\n]\n\n###################################\n# General useful functions\n###################################\n\n\ndef random_probe(num_qubits):\n r\"\"\"\n Random probe of dimension num_qubits.\n \"\"\"\n\n dim = 2 ** num_qubits\n real = []\n imaginary = []\n complex_vectors = []\n for i in range(dim):\n real.append(np.random.uniform(low=-1, high=1))\n imaginary.append(np.random.uniform(low=-1, high=1))\n complex_vectors.append(real[i] + 1j * imaginary[i])\n\n a = np.array(complex_vectors)\n norm_factor = np.linalg.norm(a)\n probe = complex_vectors / norm_factor\n while np.abs(np.linalg.norm(probe)) - 1 > 1e-14:\n print(\"generating new random probe..\")\n probe = random_probe(num_qubits)\n\n return probe\n\n\ndef n_qubit_plus_state(num_qubits):\n r\"\"\"\n Probe of dimension num_qubits, where for each qubit |+> is appended.\n \"\"\"\n\n one_qubit_plus = (1 / np.sqrt(2) + 0j) * np.array([1, 1])\n plus_n = one_qubit_plus\n for i in range(num_qubits - 1):\n plus_n = np.kron(plus_n, one_qubit_plus)\n return plus_n\n\n\ndef n_qubit_repeat_probe(num_qubits, input_state=np.array([1, 0])):\n\n state = input_state\n for i in range(num_qubits - 1):\n state = np.tensordot(state, input_state, axes=0).flatten(\"c\")\n return state\n\n\ndef harr_random_probe(num_qubits=1):\n\n random_unitary = stats.unitary_group.rvs(2 ** num_qubits)\n zero_probe = n_qubit_repeat_probe(num_qubits=num_qubits)\n random_state = np.dot(random_unitary, zero_probe)\n if not np.isclose(np.linalg.norm(random_state), 1, atol=1e-14):\n # call again until a normalised probe is generated\n print(\"Probe generated is not normalised\")\n random_state = harr_random_probe(num_qubits=num_qubits)\n return random_state\n\n\n###################################\n# Default probe set\n###################################\n\n\ndef separable_probe_dict(max_num_qubits, num_probes, **kwargs):\n r\"\"\"\n Random separable probes.\n\n Produces num_probes random states up to max_num_qubits.\n Probes are indexed by dimension and an identifier,\n e.g. (2, 10) is the 2-qubit version of probe 10.\n For each probe, 1-qubit states are generated at random,\n and tensor-producted with the probe id of smaller dimension,\n such that, for N qubits, probe i is:\n (N+1, i) = (N, i) \\otimes r,\n where r is a random 1-qubit probe.\n\n :param int max_num_qubits: Largest number of qubits to generate probes up to.\n :param int num_probes: How many probes to produce.\n :return dict separable_probes: probe library indexed by (num-qubit, probe-id)\n \"\"\"\n separable_probes = {}\n for i in range(num_probes):\n separable_probes[i, 0] = harr_random_probe(1)\n for j in range(1, 1 + max_num_qubits):\n if j == 1:\n separable_probes[i, j] = separable_probes[i, 0]\n else:\n separable_probes[i, j] = np.tensordot(\n separable_probes[i, j - 1], harr_random_probe(1), axes=0\n ).flatten(order=\"c\")\n norm = np.linalg.norm(separable_probes[i, j])\n while np.abs(norm - 1) > 1e-13:\n print(\"non-unit norm: \", norm)\n # keep replacing until a unit-norm\n separable_probes[i, j] = np.tensordot(\n separable_probes[i, j - 1], harr_random_probe(1), axes=0\n ).flatten(order=\"c\")\n norm = np.linalg.norm(separable_probes[i, j])\n # print(\"unit norm:\", np.abs(1-norm) )\n\n return separable_probes\n\n\ndef tomographic_basis(max_num_qubits=2, num_probes=10, noise_level=0.01, **kwargs):\n r\"\"\"\n To manually check something. Currently should be ideal for learning Y.\n \"\"\"\n probes = {}\n probe_list = [\n np.array([1, 0j]),\n np.array([0j, 1]),\n 1 / np.sqrt(2) * np.array([1 + 0j, 1 + 0j]),\n 1 / np.sqrt(2) * np.array([1 + 0j, -1 + 0j]),\n 1 / np.sqrt(2) * np.array([1, 1j]),\n 1 / np.sqrt(2) * np.array([1, -1j]),\n ]\n\n available_probes = itertools.cycle(probe_list)\n for j in range(num_probes):\n probe = next(available_probes)\n # add noise and normalise\n probe += noise_level * random_probe(1)\n probe /= np.linalg.norm(probe)\n\n probes[(j, 1)] = probe\n\n for N in range(2, max_num_qubits + 1):\n\n for j in range(num_probes):\n # add noise and normalise\n new = next(available_probes)\n new += noise_level * random_probe(1)\n new /= np.linalg.norm(new)\n\n probes[(j, N)] = np.kron(probes[(j, N - 1)], new)\n return probes\n\n\n###################################\n# Specific probe sets\n## e.g. matching experiment.\n###################################\n\n\ndef manual_set_probes(max_num_qubits=2, num_probes=10, noise_level=0, **kwargs):\n r\"\"\"\n To manually check something. Currently should be ideal for learning Y.\n \"\"\"\n probes = {}\n probe_list = [\n np.array([1, 0j]),\n np.array([0, 1]),\n # np.array([1j, 0]),\n # np.array([0, 1j]),\n 1 / np.sqrt(2) * np.array([1, 1]),\n 1 / np.sqrt(2) * np.array([1, -1]),\n 1 / np.sqrt(2) * np.array([1, 1j]),\n 1 / np.sqrt(2) * np.array([1, -1j]),\n ]\n available_probes = itertools.cycle(probe_list)\n for j in range(num_probes):\n probes[(j, 1)] = next(available_probes)\n\n for N in range(2, max_num_qubits + 1):\n for j in range(num_probes):\n new = next(available_probes)\n new += noise_level * random_probe(1)\n new /= np.linalg.norm(new)\n\n probes[(j, N)] = np.kron(probes[(j, N - 1)], new)\n return probes\n\n\n# test the probe transformer -\n# probes should match in first quantisation and second quantisation,\n# when generated consistently from these methods\n\n\ndef get_fh_amplitudes():\n r\"\"\"For consistency, use this both for first and second quantisation test probes.\"\"\"\n amplitudes = [\n (1, 0),\n (np.sqrt(1 / 2), np.sqrt(1 / 2)),\n (np.sqrt(1 / 3), np.sqrt(2 / 3)),\n (np.sqrt(1 / 4), np.sqrt(3 / 4)),\n (np.sqrt(1 / 5), np.sqrt(4 / 5)),\n (np.sqrt(1 / 6), np.sqrt(5 / 6)),\n ]\n\n random_generated_probes = [\n # this set worked when learned by FH\n # down up\n (\n 0.2917277328868723 - 0.8933988007482713j,\n 0.10473305565400699 - 0.32521454416986145j,\n ),\n (\n 0.11122644079879992 + 0.1595943558100543j,\n -0.7513991464733198 - 0.6305217229723107j,\n ),\n (\n 0.28064370126754434 - 0.351305094219218j,\n -0.8493632346334402 - 0.27641624295163864j,\n ),\n (\n 0.2697895657085366 - 0.048882904448255944j,\n -0.7554567811194581 + 0.595070671221603j,\n ),\n (\n -0.011033351809655593 - 0.2666075610217924j,\n 0.8261679156032085 + 0.49623104375049476j,\n ),\n (\n -0.41877834698776184 - 0.2531210159787065j,\n -0.5076736765270682 - 0.7090993481350797j,\n ),\n (\n -0.7550629339850182 + 0.4348391445682299j,\n -0.399627248364159 - 0.2847682328455842j,\n ),\n (\n -0.4911366925901858 + 0.06873816771050045j,\n -0.1506997100526583 + 0.8551896929228165j,\n ),\n (\n 0.512704399952025 + 0.2746240218810056j,\n -0.5892032449747409 - 0.5608523700466731j,\n ),\n (\n -0.8708048547409585 - 0.19844529152441565j,\n 0.24732142630473528 + 0.3756999911125355j,\n ),\n ]\n return random_generated_probes # amplitudes\n\n\ndef one_site_probes_first_quantisation():\n amplitudes = get_fh_amplitudes()\n\n one_site_probes = []\n for a in amplitudes:\n phases = [\n np.array([a[0], a[1]]),\n # np.array([a[0], -a[1]]),\n # np.array([a[0], 1j*a[1]]),\n # np.array([1j*a[0], a[1]]),\n ]\n one_site_probes.extend(phases)\n\n one_site_probes = [np.array(a) for a in one_site_probes]\n one_site_probes = itertools.cycle(one_site_probes)\n return one_site_probes\n\n\ndef one_site_probes_second_quantisation():\n r\"\"\"\n This picture uses the occupation basis:\n |down> = |10> = (0,0,1,0);\n |up> = |10> = (0,1,0,0);\n\n \"\"\"\n\n amplitudes = get_fh_amplitudes()\n\n one_site_probes = []\n for a in amplitudes:\n phases = [\n np.array([0, a[1], a[0], 0]),\n # np.array([ 0, -a[1], a[0], 0 ]),\n # np.array([ 0, 1j*a[1], a[0], 0 ]),\n # np.array([ 0 , a[1], 1j*a[0], 0 ]),\n ]\n one_site_probes.extend(phases)\n\n one_site_probes = [np.array(a) for a in one_site_probes]\n one_site_probes = itertools.cycle(one_site_probes)\n return one_site_probes\n\n\ndef test_probes_first_quantisation(num_probes=10, max_num_qubits=4, **kwargs):\n\n designed_probes = one_site_probes_first_quantisation()\n\n probes = {}\n\n for p in range(num_probes):\n probes[(p, 1)] = next(designed_probes)\n\n for nq in range(2, max_num_qubits + 1):\n\n pid = (p, nq)\n new_probe = np.tensordot(\n probes[(p, nq - 1)], probes[(p, 1)], axes=0\n ).flatten(\"c\")\n probes[pid] = new_probe\n\n norm = np.linalg.norm(new_probe)\n if not np.isclose(norm, 1, atol=1e-6):\n print(\"norm=\", norm)\n return probes\n\n\ndef test_probes_second_quantisation(num_probes=10, max_num_qubits=4, **kwargs):\n\n designed_probes = one_site_probes_second_quantisation()\n\n probes = {}\n\n for p in range(num_probes):\n probes[(p, 1)] = next(designed_probes)\n\n for nq in range(2, max_num_qubits + 1):\n\n pid = (p, nq)\n new_probe = np.tensordot(\n probes[(p, nq - 1)], probes[(p, 1)], axes=0\n ).flatten(\"c\")\n probes[pid] = new_probe\n\n norm = np.linalg.norm(new_probe)\n if not np.isclose(norm, 1, atol=1e-6):\n print(\"norm=\", norm)\n\n return probes\n\n\ndef eigenbasis_of_first_qubit(max_num_qubits=2, num_probes=40, **kwargs):\n probes = {}\n bases_to_learn = [\"x\", \"y\", \"z\"]\n for N in range(1, max_num_qubits + 1):\n bases = [\"pauliSet_1_{}_d{}\".format(b, N) for b in bases_to_learn]\n base_matrices = [qmla.model_building_utilities.compute(b) for b in bases]\n eig_vectors_list = qmla.utilities.flatten(\n [np.linalg.eig(b)[1] for b in base_matrices]\n )\n eig_vectors = itertools.cycle(eig_vectors_list)\n\n for j in range(num_probes):\n probes[(j, N)] = next(eig_vectors)\n return probes\n\n\ndef NV_centre_ising_probes_plus(\n max_num_qubits=2,\n num_probes=40,\n noise_level=0.03, # from 1000 counts - Poissonian noise = 1/sqrt(1000)\n **kwargs\n):\n r\"\"\"\n Returns a dict of separable probes where the first qubit always acts on |+>.\n\n Used for QMLA on NV centre, experiment in Bristol 2016.\n Probe library has each probe like |+>|r>..|r>, where |r> is random 1-qubit state.\n\n :param int max_num_qubits: Largest number of qubits to generate probes up to.\n :param int num_probes: How many probes to produce.\n :param float noise_level: factor to multiple generated states by to simulate noise.\n :return dict separable_probes: probe library.\n \"\"\"\n minimum_tolerable_noise = 1e-6\n # minimum_tolerable_noise needed\n # or else run the risk of having\n # exact eigenstate and no learning occurs, and crashes.\n print(\n \"[NV_centre_ising_probes_plus] min tol noise:\",\n minimum_tolerable_noise,\n \"noise level:\",\n noise_level,\n )\n if minimum_tolerable_noise > noise_level:\n noise_level = minimum_tolerable_noise\n # print(\"using minimum_tolerable_noise\")\n plus_state = np.array([1 + 0j, 1]) / np.sqrt(2)\n random_noise = noise_level * random_probe(1)\n noisy_plus = plus_state + random_noise\n norm_factor = np.linalg.norm(noisy_plus)\n noisy_plus = noisy_plus / norm_factor\n print(\"\\n\\t noisy plus:\", noisy_plus)\n # print(\"\\n\\t has type:\", type(noisy_plus))\n\n separable_probes = {}\n for i in range(num_probes):\n # separable_probes[i,0] = plus_state\n separable_probes[i, 0] = noisy_plus\n for j in range(1, 1 + max_num_qubits):\n if j == 1:\n separable_probes[i, j] = separable_probes[i, 0]\n else:\n separable_probes[i, j] = np.tensordot(\n separable_probes[i, j - 1],\n # noisy_plus,\n random_probe(1),\n axes=0,\n ).flatten(order=\"c\")\n while (\n np.isclose(1.0, np.linalg.norm(separable_probes[i, j]), atol=1e-14)\n is False\n ):\n print(\"non-unit norm: \", np.linalg.norm(separable_probes[i, j]))\n # keep replacing until a unit-norm\n separable_probes[i, j] = np.tensordot(\n separable_probes[i, j - 1], random_probe(1), axes=0\n ).flatten(order=\"c\")\n return separable_probes\n\n\ndef random_initialised_qubit_for_hahn_sequence(hahn_rotation=None):\n pauli_y = np.array([[0, -1j], [1j, 0]])\n spin_qubit = np.array([1, 0]) # prepared in |0>\n if hahn_rotation is None:\n hahn_rotation = np.random.uniform(-1, 1)\n hahn_angle = hahn_rotation * (np.pi / 2)\n\n hahn_gate = expm(-1j * hahn_angle * pauli_y)\n\n spin_qubit = np.dot(hahn_gate, spin_qubit)\n return spin_qubit\n\n\ndef hahn_sequence_random_initial(\n max_num_qubits=2, num_probes=40, noise_level=0.03, **kwargs\n):\n\n separable_probes = {}\n for i in range(num_probes):\n rand_init_state = random_initialised_qubit_for_hahn_sequence()\n # rand_init_state = harr_random_probe()\n separable_probes[i, 0] = rand_init_state\n for j in range(1, 1 + max_num_qubits):\n if j == 1:\n separable_probes[i, j] = separable_probes[i, 0]\n else:\n\n separable_probes[i, j] = np.tensordot(\n separable_probes[i, j - 1], rand_init_state, axes=0\n ).flatten(order=\"c\")\n while (\n np.isclose(1.0, np.linalg.norm(separable_probes[i, j]), atol=1e-14)\n is False\n ):\n print(\"non-unit norm: \", np.linalg.norm(separable_probes[i, j]))\n # keep replacing until a unit-norm\n separable_probes[i, j] = np.tensordot(\n separable_probes[i, j - 1], rand_init_state, axes=0\n ).flatten(order=\"c\")\n return separable_probes\n\n\ndef plus_plus_with_phase_difference(\n max_num_qubits=2,\n num_probes=40,\n noise_level=0.03, # from 1000 counts - Poissonian noise = 1/sqrt(1000)\n # noise_level=0.03, # from 1000 counts - Poissonian noise = 1/sqrt(1000)\n # *args,\n **kwargs\n):\n r\"\"\"\n Probes |+> |+'> ... |+'>\n\n To match NV centre experiment in Bristol, 2016.\n First qubit is prepared in |+>;\n second (and subsequent) qubits (representing environment)\n assumed to be in |+'> = |0> + e^{iR}|1> (normalised, R = random phase)\n i.e.\n 1 qubit : |+>\n 2 qubits : |+>|+'>\n N qubits : |+> |+'> ... |+'>\n\n :param int max_num_qubits: Largest number of qubits to generate probes up to.\n :param int num_probes: How many probes to produce.\n :param float noise_level: factor to multiple generated states by to simulate noise.\n :return dict separable_probes: probe library.\n\n \"\"\"\n\n # minimum_tolerable_noise=1e-6\n # minimum_tolerable_noise needed\n # or else run the risk of having\n # exact eigenstate and no learning occurs, and crashes.\n\n # if minimum_tolerable_noise > noise_level:\n # noise_level = minimum_tolerable_noise\n # noise_level = 0.01\n plus_state = np.array([1 + 0j, 1]) / np.sqrt(2)\n random_noise = noise_level * random_probe(1)\n noisy_plus = plus_state + random_noise\n norm_factor = np.linalg.norm(noisy_plus)\n noisy_plus = noisy_plus / norm_factor\n print(\"[|++'> probes] Noise factor:\", noise_level)\n\n separable_probes = {}\n for i in range(num_probes):\n separable_probes[i, 0] = noisy_plus\n for j in range(1, 1 + max_num_qubits):\n if j == 1:\n separable_probes[i, j] = separable_probes[i, 0]\n else:\n separable_probes[i, j] = np.tensordot(\n separable_probes[i, j - 1],\n # noisy_plus,\n random_phase_plus(noise_level=noise_level),\n axes=0,\n ).flatten(order=\"c\")\n while (\n np.isclose(1.0, np.linalg.norm(separable_probes[i, j]), atol=1e-14)\n is False\n ):\n print(\"non-unit norm: \", np.linalg.norm(separable_probes[i, j]))\n # keep replacing until a unit-norm\n separable_probes[i, j] = np.tensordot(\n separable_probes[i, j - 1],\n random_phase_plus(noise_level=noise_level),\n axes=0,\n ).flatten(order=\"c\")\n return separable_probes\n\n\ndef random_phase_plus(noise_level=1e-5):\n r\"\"\"\n To produce |+'> = |0> + e^{iR}|1> (normalised, R = random phase)\n \"\"\"\n\n random_phase = random.uniform(0, np.pi)\n rand_phase_plus = np.array([1.0 + 0.0j, np.exp(1.0j * random_phase)]) / np.sqrt(2)\n\n noisy_state = noise_level * random_probe(1)\n rand_phase_plus += noisy_state\n norm = np.linalg.norm(rand_phase_plus)\n rand_phase_plus = rand_phase_plus / norm\n return rand_phase_plus\n\n\n###################################\n# General purpose probe dictionaries for specific cases\n## e.g. experimental method, generalised to multiple dimensions\n###################################\n\n\ndef plus_probes_dict(\n max_num_qubits,\n noise_level=0.0, # from 1000 counts - Poissonian noise = 1/sqrt(1000)\n minimum_tolerable_noise=0,\n **kwargs\n):\n r\"\"\"\n Produces exactly |+>|+>...|+> with no noise.\n \"\"\"\n\n num_probes = kwargs[\"num_probes\"]\n # if minimum_tolerable_noise > noise_level:\n # noise_level = minimum_tolerable_noise\n probe_dict = {}\n for j in range(num_probes):\n for i in range(1, 1 + max_num_qubits):\n # dict key is tuple of form (0,i) for consistency with other probe\n # dict generation functions.\n new_probe = n_qubit_plus_state(i)\n noisy_state = random_probe(i) * noise_level\n noisy_probe = new_probe + noisy_state\n norm = np.linalg.norm(noisy_probe)\n noisy_probe = noisy_probe / norm\n probe_dict[(j, i)] = noisy_probe\n return probe_dict\n\n\ndef zero_state_probes(max_num_qubits=9, **kwargs):\n r\"\"\"\n Probe library: |0>|0> ... |0>\n \"\"\"\n\n zero = np.array([1 + 0j, 0])\n num_probes = kwargs[\"num_probes\"]\n probes = {}\n\n for q in range(1, 1 + max_num_qubits):\n for j in range(num_probes):\n state = zero\n for i in range(q - 1):\n state = np.tensordot(state, zero, axes=0).flatten(\"c\")\n probes[(j, q)] = state\n\n return probes\n\n\n###################################\n# Exploration Strategy specific probes\n###################################\n\n# Fermi Hubbard model -- requires encoding via Jordan-Wigner transformation.\ndef separable_fermi_hubbard_half_filled(max_num_qubits, num_probes, **kwargs):\n r\"\"\"\n Probes for Fermi-Hubbard Hamiltonians.\n\n Generates separable probes using a half filled system,\n i.e. N spins in N sites.\n First generates completely random probes,\n then projects so that for each dimension\n the probe is projected onto the subspace of n\n fermions on the n dimensional space,\n i.e. the half-filled basis.\n\n :param int max_num_qubits: Largest number of qubits to generate probes up to.\n :param int num_probes: How many probes to produce.\n :return dict separable_probes: probe library.\n \"\"\"\n\n separable_probes = {}\n for i in range(num_probes):\n separable_probes[i, 0] = random_superposition_occupation_basis()\n for j in range(1, 1 + max_num_qubits):\n if j == 1:\n separable_probes[i, j] = separable_probes[i, 0]\n else:\n separable_probes[i, j] = np.tensordot(\n separable_probes[i, j - 1],\n random_superposition_occupation_basis(),\n axes=0,\n ).flatten(order=\"c\")\n norm = np.linalg.norm(separable_probes[i, j])\n while np.abs(norm - 1) > 1e-13:\n print(\"non-unit norm: \", norm)\n # keep replacing until a unit-norm\n separable_probes[i, j] = np.tensordot(\n separable_probes[i, j - 1],\n random_superposition_half_filled_occupation_basis(),\n axes=0,\n ).flatten(order=\"c\")\n norm = np.linalg.norm(separable_probes[i, j])\n # print(\"unit norm:\", np.abs(1-norm) )\n\n # project onto subspace representing half-filled (n fermions on n sites)\n # by removing amplitude of basis vectors of different form\n # eg 2 sites, keep |0101>; remove |0111>, etc\n combined_base_vectors = {\n i: sum(get_half_filled_basis_vectors(i)) for i in range(1, max_num_qubits + 1)\n }\n for j in range(1, 1 + max_num_qubits):\n bv = combined_base_vectors[j]\n for i in range(num_probes):\n p = separable_probes[(i, j)]\n p *= bv\n p /= np.linalg.norm(p)\n separable_probes[(i, j)] = p\n\n return separable_probes\n\n\ndef get_half_filled_basis_vectors(num_sites):\n half_filled_list = [0, 1] * num_sites\n\n # all the ways in which half filled can be spread across lattice\n perms = list(itertools.permutations(half_filled_list))\n perms = [\n \"\".join([str(j) for j in this_el]) for this_el in perms\n ] # restore as strings instead of lists\n perms = list(set(perms)) # unique strings\n\n basis = [state_from_string(s) for s in perms]\n return basis\n\n\ndef random_superposition_occupation_basis():\n r\"\"\"\n Returns a random superposition over the occupation basis of a single site\n which can be singly or doubly occupied.\n #TODO equivalent to 2 qubit Harr-random?\n\n vacant = np.array([1,0])\n occupied = np.array([0,1])\n down = np.kron(occupied, vacant) #|10>\n up = np.kron(vacant, occupied) #|01>\n \"\"\"\n\n down = np.array([0, 0, 1, 0])\n up = np.array([0, 1, 0, 0])\n unoccupied = np.array([1, 0, 0, 0])\n doubly_occupied = np.array([0, 0, 0, 1])\n\n alpha = np.random.randn() + 1j * np.random.randn()\n beta = np.random.randn() + 1j * np.random.randn()\n gamma = np.random.randn() + 1j * np.random.randn()\n delta = np.random.randn() + 1j * np.random.randn()\n\n state = (\n (alpha * down) + (beta * up) + (gamma * unoccupied) + (delta * doubly_occupied)\n )\n state = state / np.linalg.norm(state) # normalise\n return state\n\n\ndef state_from_string(s, basis_states={\"0\": np.array([1, 0]), \"1\": np.array([0, 1])}):\n # input s, form 1001, returns corresponding basis vector\n state = None\n for i in s:\n if state is None:\n state = basis_states[i]\n else:\n state = np.kron(state, basis_states[i])\n state = np.array(state)\n return state\n\n\ndef fermi_hubbard_half_filled_superposition(max_num_qubits, **kwargs):\n num_sites = max_num_qubits\n probe_dict = {}\n for N in range(1, 1 + num_sites):\n\n state = None\n for i in range(1, N + 1):\n for spin_type in [\"up\", \"down\"]:\n\n new_state = vector_from_fermion_state_description(\n {\"num_sites\": N, \"occupations\": {i: [spin_type]}}\n )\n\n if state is None:\n state = new_state\n else:\n state += new_state\n\n state = state / np.linalg.norm(state)\n\n probe_dict[(1, N)] = state\n print(\"[fermi_hubbard_half_filled_superposition] keys:\", probe_dict.keys())\n return probe_dict\n\n\ndef vector_from_fermion_state_description(state):\n\n occupied = np.array([0, 1])\n vacant = np.array([1, 0])\n\n vector = 1 # so we can perform tensor product on it\n for i in range(1, 1 + state[\"num_sites\"]):\n try:\n occupation = state[\"occupations\"][i]\n except BaseException:\n occupation = [\"vacant\"]\n\n # in order: (i, down), (i, up)\n # i.e. 2 qubit encoding per site\n if \"down\" in occupation:\n vector = np.kron(vector, occupied)\n else:\n vector = np.kron(vector, vacant)\n\n if \"up\" in occupation:\n vector = np.kron(vector, occupied)\n else:\n vector = np.kron(vector, vacant)\n\n return vector\n\n\ndef fermi_hubbard_occupation_basis_down_in_first_site(\n max_num_qubits, num_probes=1, **kwargs\n):\n r\"\"\"\n To test hopping out of first site\n \"\"\"\n\n print(\"Fermi hubbard down in first site probes. max num qubits:\", max_num_qubits)\n probe_dict = {}\n for j in range(num_probes):\n for n in range(1, max_num_qubits + 1):\n num_occupation_locations = 2 * n\n down_in_first_site = [\"0\"] * num_occupation_locations\n down_in_first_site[0] = \"1\"\n down_in_first_site = \"\".join(down_in_first_site)\n probe_dict[(j, n)] = state_from_string(down_in_first_site)\n\n return probe_dict\n\n\ndef fermi_hubbard_occupation_basis_up_in_first_site(\n max_num_qubits, num_probes=1, **kwargs\n):\n r\"\"\"\n To test hopping out of first site\n \"\"\"\n\n print(\"Fermi hubbard down in first site probes. max num qubits:\", max_num_qubits)\n probe_dict = {}\n for j in range(num_probes):\n for n in range(1, max_num_qubits + 1):\n num_occupation_locations = 2 * n\n down_in_first_site = [\"0\"] * num_occupation_locations\n down_in_first_site[1] = \"1\"\n down_in_first_site = \"\".join(down_in_first_site)\n probe_dict[(j, n)] = state_from_string(down_in_first_site)\n\n return probe_dict\n\n\ndef fermi_hubbard_occupation_basis_down_in_all_sites(\n max_num_qubits, num_probes=1, **kwargs\n):\n probe_dict = {}\n\n for j in range(num_probes):\n for n in range(1, max_num_qubits + 1):\n down_in_all_sites = \"10\" * n\n probe_dict[(j, n)] = state_from_string(down_in_all_sites)\n\n return probe_dict\n\n\n###################################\n# Testing/development\n###################################\n\n# probes generated according to Pauli matrices' eigenvectors\ncore_operator_dict = {\n # 'a': np.array([[0 + 0.j, 1 + 0.j], [0 + 0.j, 0 + 0.j]]),\n # 's': np.array([[0 + 0.j, 0 + 0.j], [1 + 0.j, 0 + 0.j]])\n \"i\": np.array([[1 + 0.0j, 0 + 0.0j], [0 + 0.0j, 1 + 0.0j]]),\n \"x\": np.array([[0 + 0.0j, 1 + 0.0j], [1 + 0.0j, 0 + 0.0j]]),\n \"y\": np.array([[0 + 0.0j, 0 - 1.0j], [0 + 1.0j, 0 + 0.0j]]),\n \"z\": np.array([[1 + 0.0j, 0 + 0.0j], [0 + 0.0j, -1 + 0.0j]]),\n}\n\n\neigvals = {k: linalg.eig(core_operator_dict[k])[0] for k in core_operator_dict}\neigvecs = {k: linalg.eig(core_operator_dict[k])[1] for k in core_operator_dict}\nall_eigvecs = [eigvecs[k][l] for k in eigvecs for l in range(eigvecs[k].shape[0])]\neigvec_indices = range(len(all_eigvecs))\neigenvectors = {i: all_eigvecs[i] for i in eigvec_indices}\n\n\ndef random_sum_eigenvectors():\n # num_to_sum = random.randrange(2, 5)\n num_to_sum = 1\n indices_to_include = []\n while len(indices_to_include) < num_to_sum:\n a = random.choice(eigvec_indices)\n if a not in indices_to_include:\n indices_to_include.append(a)\n\n state = None\n for i in indices_to_include:\n if state is None:\n state = eigenvectors[i]\n else:\n state += eigenvectors[i]\n print(\"Including eig i={}: {}\".format(i, eigenvectors[i]))\n return state / linalg.norm(state)\n\n\ndef pauli_eigenvector_based_probes(max_num_qubits, num_probes, **kwargs):\n separable_probes = {}\n for i in range(num_probes):\n # separable_probes[i, 0] = random_probe(1)\n separable_probes[i, 0] = random_sum_eigenvectors()\n for j in range(1, 1 + max_num_qubits):\n if j == 1:\n separable_probes[i, j] = separable_probes[i, 0]\n else:\n separable_probes[i, j] = np.tensordot(\n separable_probes[i, j - 1], random_sum_eigenvectors(), axes=0\n ).flatten(order=\"c\")\n norm = np.linalg.norm(separable_probes[i, j])\n while np.abs(norm - 1) > 1e-13:\n print(\"non-unit norm: \", norm)\n # keep replacing until a unit-norm\n separable_probes[i, j] = np.tensordot(\n separable_probes[i, j - 1],\n random_sum_eigenvectors(),\n # random_probe(1),\n axes=0,\n ).flatten(order=\"c\")\n norm = np.linalg.norm(separable_probes[i, j])\n # print(\"unit norm:\", np.abs(1-norm) )\n\n return separable_probes\n\n\n# probes generated according to Pauli matrices' eigenvectors\n# testing eigenvalue of Paulis probes - not in use\ncore_operator_dict = {\n # 'a': np.array([[0 + 0.j, 1 + 0.j], [0 + 0.j, 0 + 0.j]]),\n # 's': np.array([[0 + 0.j, 0 + 0.j], [1 + 0.j, 0 + 0.j]])\n \"i\": np.array([[1 + 0.0j, 0 + 0.0j], [0 + 0.0j, 1 + 0.0j]]),\n \"x\": np.array([[0 + 0.0j, 1 + 0.0j], [1 + 0.0j, 0 + 0.0j]]),\n \"y\": np.array([[0 + 0.0j, 0 - 1.0j], [0 + 1.0j, 0 + 0.0j]]),\n \"z\": np.array([[1 + 0.0j, 0 + 0.0j], [0 + 0.0j, -1 + 0.0j]]),\n}\n\n\neigvals = {k: linalg.eig(core_operator_dict[k])[0] for k in core_operator_dict}\neigvecs = {k: linalg.eig(core_operator_dict[k])[1] for k in core_operator_dict}\nall_eigvecs = [eigvecs[k][l] for k in eigvecs for l in range(eigvecs[k].shape[0])]\neigvec_indices = range(len(all_eigvecs))\neigenvectors = {i: all_eigvecs[i] for i in eigvec_indices}\n\n\ndef random_sum_eigenvectors():\n # num_to_sum = random.randrange(2, 5)\n num_to_sum = 1\n indices_to_include = []\n while len(indices_to_include) < num_to_sum:\n a = random.choice(eigvec_indices)\n if a not in indices_to_include:\n indices_to_include.append(a)\n\n state = None\n for i in indices_to_include:\n if state is None:\n state = eigenvectors[i]\n else:\n state += eigenvectors[i]\n print(\"Including eig i={}: {}\".format(i, eigenvectors[i]))\n return state / linalg.norm(state)\n\n\ndef pauli_eigenvector_based_probes(max_num_qubits, num_probes, **kwargs):\n separable_probes = {}\n for i in range(num_probes):\n # separable_probes[i, 0] = random_probe(1)\n separable_probes[i, 0] = random_sum_eigenvectors()\n for j in range(1, 1 + max_num_qubits):\n if j == 1:\n separable_probes[i, j] = separable_probes[i, 0]\n else:\n separable_probes[i, j] = np.tensordot(\n separable_probes[i, j - 1], random_sum_eigenvectors(), axes=0\n ).flatten(order=\"c\")\n norm = np.linalg.norm(separable_probes[i, j])\n while np.abs(norm - 1) > 1e-13:\n print(\"non-unit norm: \", norm)\n # keep replacing until a unit-norm\n separable_probes[i, j] = np.tensordot(\n separable_probes[i, j - 1],\n random_sum_eigenvectors(),\n # random_probe(1),\n axes=0,\n ).flatten(order=\"c\")\n norm = np.linalg.norm(separable_probes[i, j])\n # print(\"unit norm:\", np.abs(1-norm) )\n\n return separable_probes\n" ]
[ [ "matplotlib.pyplot.switch_backend", "numpy.ceil", "numpy.round", "matplotlib.pyplot.savefig", "numpy.exp", "matplotlib.pyplot.subplots", "numpy.shape", "numpy.tensordot", "numpy.sqrt", "numpy.log10", "matplotlib.pyplot.figlegend", "matplotlib.gridspec.GridSpec" ], [ "scipy.linalg.expm", "numpy.array", "numpy.linalg.norm", "numpy.dot", "numpy.isclose", "numpy.random.randn", "numpy.exp", "numpy.tensordot", "numpy.random.uniform", "scipy.linalg.eig", "scipy.stats.unitary_group.rvs", "numpy.sqrt", "numpy.abs", "numpy.linalg.eig", "scipy.linalg.norm", "numpy.kron" ] ]
hari-sikchi/spinningup
[ "6098384a9cb78e3b30c777bc3d7b9bcd19d63498" ]
[ "spinup/algos/pytorch/ppo/ipo.py" ]
[ "import numpy as np\nimport torch\nfrom torch.optim import Adam\nimport gym\nimport time\nimport spinup.algos.pytorch.ppo.core as core\nfrom spinup.utils.logx import EpochLogger\nfrom spinup.utils.mpi_pytorch import setup_pytorch_for_mpi, sync_params, mpi_avg_grads\nfrom spinup.utils.mpi_tools import mpi_fork, mpi_avg, proc_id, mpi_statistics_scalar, num_procs\nimport driftgym\nimport safety_gym\n\nclass PPOBuffer:\n \"\"\"\n A buffer for storing trajectories experienced by a PPO agent interacting\n with the environment, and using Generalized Advantage Estimation (GAE-Lambda)\n for calculating the advantages of state-action pairs.\n \"\"\"\n\n def __init__(self, obs_dim, act_dim, size, gamma=0.99, lam=0.95):\n self.obs_buf = np.zeros(core.combined_shape(size, obs_dim), dtype=np.float32)\n self.act_buf = np.zeros(core.combined_shape(size, act_dim), dtype=np.float32)\n self.adv_buf = np.zeros(size, dtype=np.float32)\n self.rew_buf = np.zeros(size, dtype=np.float32)\n self.ret_buf = np.zeros(size, dtype=np.float32)\n self.val_buf = np.zeros(size, dtype=np.float32)\n self.logp_buf = np.zeros(size, dtype=np.float32)\n self.gamma, self.lam = gamma, lam\n self.ptr, self.path_start_idx, self.max_size = 0, 0, size\n\n def store(self, obs, act, rew, val, logp):\n \"\"\"\n Append one timestep of agent-environment interaction to the buffer.\n \"\"\"\n if(self.ptr>=self.max_size):\n return\n assert self.ptr < self.max_size # buffer has to have room so you can store\n self.obs_buf[self.ptr] = obs\n self.act_buf[self.ptr] = act\n self.rew_buf[self.ptr] = rew\n self.val_buf[self.ptr] = val\n self.logp_buf[self.ptr] = logp\n self.ptr += 1\n\n def finish_path(self, last_val=0):\n \"\"\"\n Call this at the end of a trajectory, or when one gets cut off\n by an epoch ending. This looks back in the buffer to where the\n trajectory started, and uses rewards and value estimates from\n the whole trajectory to compute advantage estimates with GAE-Lambda,\n as well as compute the rewards-to-go for each state, to use as\n the targets for the value function.\n\n The \"last_val\" argument should be 0 if the trajectory ended\n because the agent reached a terminal state (died), and otherwise\n should be V(s_T), the value function estimated for the last state.\n This allows us to bootstrap the reward-to-go calculation to account\n for timesteps beyond the arbitrary episode horizon (or epoch cutoff).\n \"\"\"\n\n path_slice = slice(self.path_start_idx, self.ptr)\n rews = np.append(self.rew_buf[path_slice], last_val)\n vals = np.append(self.val_buf[path_slice], last_val)\n \n # the next two lines implement GAE-Lambda advantage calculation\n deltas = rews[:-1] + self.gamma * vals[1:] - vals[:-1]\n self.adv_buf[path_slice] = core.discount_cumsum(deltas, self.gamma * self.lam)\n \n # the next line computes rewards-to-go, to be targets for the value function\n self.ret_buf[path_slice] = core.discount_cumsum(rews, self.gamma)[:-1]\n \n self.path_start_idx = self.ptr\n\n def get(self):\n \"\"\"\n Call this at the end of an epoch to get all of the data from\n the buffer, with advantages appropriately normalized (shifted to have\n mean zero and std one). Also, resets some pointers in the buffer.\n \"\"\"\n assert self.ptr == self.max_size # buffer has to be full before you can get\n self.ptr, self.path_start_idx = 0, 0\n # the next two lines implement the advantage normalization trick\n adv_mean, adv_std = mpi_statistics_scalar(self.adv_buf)\n self.adv_buf = (self.adv_buf - adv_mean) / adv_std\n data = dict(obs=self.obs_buf, act=self.act_buf, ret=self.ret_buf,\n adv=self.adv_buf, logp=self.logp_buf,val=self.val_buf)\n return {k: torch.as_tensor(v, dtype=torch.float32) for k,v in data.items()}\n\n\n\n\n\n\ndef ppo(env_fn, actor_critic=core.MLPActorCritic, ac_kwargs=dict(), seed=0, \n steps_per_epoch=4000, epochs=50, gamma=0.99, clip_ratio=0.2, pi_lr=3e-4,\n vf_lr=1e-3, train_pi_iters=80, train_v_iters=80, lam=0.97, max_ep_len=1000,\n target_kl=0.01, logger_kwargs=dict(), save_freq=10):\n \"\"\"\n Proximal Policy Optimization (by clipping), \n\n with early stopping based on approximate KL\n\n Args:\n env_fn : A function which creates a copy of the environment.\n The environment must satisfy the OpenAI Gym API.\n\n actor_critic: The constructor method for a PyTorch Module with a \n ``step`` method, an ``act`` method, a ``pi`` module, and a ``v`` \n module. The ``step`` method should accept a batch of observations \n and return:\n\n =========== ================ ======================================\n Symbol Shape Description\n =========== ================ ======================================\n ``a`` (batch, act_dim) | Numpy array of actions for each \n | observation.\n ``v`` (batch,) | Numpy array of value estimates\n | for the provided observations.\n ``logp_a`` (batch,) | Numpy array of log probs for the\n | actions in ``a``.\n =========== ================ ======================================\n\n The ``act`` method behaves the same as ``step`` but only returns ``a``.\n\n The ``pi`` module's forward call should accept a batch of \n observations and optionally a batch of actions, and return:\n\n =========== ================ ======================================\n Symbol Shape Description\n =========== ================ ======================================\n ``pi`` N/A | Torch Distribution object, containing\n | a batch of distributions describing\n | the policy for the provided observations.\n ``logp_a`` (batch,) | Optional (only returned if batch of\n | actions is given). Tensor containing \n | the log probability, according to \n | the policy, of the provided actions.\n | If actions not given, will contain\n | ``None``.\n =========== ================ ======================================\n\n The ``v`` module's forward call should accept a batch of observations\n and return:\n\n =========== ================ ======================================\n Symbol Shape Description\n =========== ================ ======================================\n ``v`` (batch,) | Tensor containing the value estimates\n | for the provided observations. (Critical: \n | make sure to flatten this!)\n =========== ================ ======================================\n\n\n ac_kwargs (dict): Any kwargs appropriate for the ActorCritic object \n you provided to PPO.\n\n seed (int): Seed for random number generators.\n\n steps_per_epoch (int): Number of steps of interaction (state-action pairs) \n for the agent and the environment in each epoch.\n\n epochs (int): Number of epochs of interaction (equivalent to\n number of policy updates) to perform.\n\n gamma (float): Discount factor. (Always between 0 and 1.)\n\n clip_ratio (float): Hyperparameter for clipping in the policy objective.\n Roughly: how far can the new policy go from the old policy while \n still profiting (improving the objective function)? The new policy \n can still go farther than the clip_ratio says, but it doesn't help\n on the objective anymore. (Usually small, 0.1 to 0.3.) Typically\n denoted by :math:`\\epsilon`. \n\n pi_lr (float): Learning rate for policy optimizer.\n\n vf_lr (float): Learning rate for value function optimizer.\n\n train_pi_iters (int): Maximum number of gradient descent steps to take \n on policy loss per epoch. (Early stopping may cause optimizer\n to take fewer than this.)\n\n train_v_iters (int): Number of gradient descent steps to take on \n value function per epoch.\n\n lam (float): Lambda for GAE-Lambda. (Always between 0 and 1,\n close to 1.)\n\n max_ep_len (int): Maximum length of trajectory / episode / rollout.\n\n target_kl (float): Roughly what KL divergence we think is appropriate\n between new and old policies after an update. This will get used \n for early stopping. (Usually small, 0.01 or 0.05.)\n\n logger_kwargs (dict): Keyword args for EpochLogger.\n\n save_freq (int): How often (in terms of gap between epochs) to save\n the current policy and value function.\n\n \"\"\"\n\n # Special function to avoid certain slowdowns from PyTorch + MPI combo.\n setup_pytorch_for_mpi()\n\n # Set up logger and save configuration\n logger = EpochLogger(**logger_kwargs)\n logger.save_config(locals())\n\n # Random seed\n seed += 10000 * proc_id()\n torch.manual_seed(seed)\n np.random.seed(seed)\n\n # Instantiate environment\n env = env_fn()\n obs_dim = env.observation_space.shape\n act_dim = env.action_space.shape\n\n # Create actor-critic module\n ac = actor_critic(env.observation_space, env.action_space, **ac_kwargs)\n\n cost_ac = actor_critic(env.observation_space, env.action_space, **ac_kwargs)\n cost_ac.pi = ac.pi\n # Sync params across processes\n sync_params(ac)\n sync_params(cost_ac)\n \n # Count variables\n var_counts = tuple(core.count_vars(module) for module in [ac.pi, ac.v])\n logger.log('\\nNumber of parameters: \\t pi: %d, \\t v: %d\\n'%var_counts)\n\n # Set up experience buffer\n local_steps_per_epoch = int(steps_per_epoch / num_procs())\n buf = PPOBuffer(obs_dim, act_dim, local_steps_per_epoch, gamma, lam)\n cost_buf = PPOBuffer(obs_dim, act_dim, local_steps_per_epoch, gamma, lam)\n # replay_buf = PPOBuffer(obs_dim, act_dim, 100000, gamma, lam)\n\n # Set up function for computing PPO policy loss\n def compute_loss_pi(data,cost_data=None):\n obs, act, val,adv, logp_old = data['obs'], data['act'],data['val'], data['adv'], data['logp']\n if(cost_data is not None):\n cost_obs, cost_act,cost_val, cost_adv, cost_logp_old = cost_data['obs'], cost_data['act'], cost_data['val'], cost_data['adv'], cost_data['logp']\n\n # Policy loss\n ## Uses GAE \n pi, logp = ac.pi(obs, act)\n ratio = torch.exp(logp - logp_old)\n clip_adv = torch.clamp(ratio, 1-clip_ratio, 1+clip_ratio) * adv\n loss_pi_vector = -(torch.min(ratio * adv, clip_adv))\n loss_pi = loss_pi_vector.mean()\n # Uses value function directly\n # pi, logp = ac.pi(obs, act)\n # ratio = torch.exp(logp - logp_old)\n # clip_adv = torch.clamp(ratio, 1-clip_ratio, 1+clip_ratio) * val\n # loss_pi_vector = -(torch.min(ratio * val, clip_adv))\n # loss_pi = loss_pi_vector.mean()\n\n\n\n # Penalty parameter\n t = 100\n # Policy loss wrt Cumulative cost function\n # print(cost_data)\n if cost_data is not None:\n cost_pi, cost_logp = ac.pi(cost_obs, cost_act)\n cost_ratio = torch.exp(cost_logp - cost_logp_old)\n cost_clip_adv = torch.clamp(cost_ratio, 1-clip_ratio, 1+clip_ratio) * (cost_val+cost_adv)\n cost_loss_pi_vector = (torch.min(cost_ratio * (cost_val+cost_adv), cost_clip_adv))\n # cost_loss_pi_hat = cost_loss_pi_vector.mean()-25\n\n cost_loss_pi_hat = cost_loss_pi_vector.mean()-env.constraint_limit\n\n cost_loss_pi= -torch.log(torch.clamp(-cost_loss_pi_hat,min=1e-6))/t\n # print(\"V_hat: {} J_hat:{} Constraint limit: {}, Cost loss pi: {}\".format(-loss_pi,cost_loss_pi_vector.mean(),env.constraint_limit,cost_loss_pi))\n loss_pi+=cost_loss_pi\n\n # Useful extra info\n approx_kl = (logp_old - logp).mean().item()\n ent = pi.entropy().mean().item()\n clipped = ratio.gt(1+clip_ratio) | ratio.lt(1-clip_ratio)\n clipfrac = torch.as_tensor(clipped, dtype=torch.float32).mean().item()\n pi_info = dict(kl=approx_kl, ent=ent, cf=clipfrac)\n\n return loss_pi, pi_info\n\n # Set up function for computing value loss\n def compute_loss_v(data):\n obs, ret = data['obs'], data['ret']\n return ((ac.v(obs) - ret)**2).mean()\n\n def compute_loss_j(data):\n obs, ret = data['obs'], data['ret']\n return ((ac.j(obs) - ret)**2).mean()\n\n\n # Set up optimizers for policy and value function\n pi_optimizer = Adam(ac.pi.parameters(), lr=pi_lr)\n vf_optimizer = Adam(ac.v.parameters(), lr=vf_lr)\n jf_optimizer = Adam(ac.j.parameters(), lr=vf_lr)\n # Set up model saving\n logger.setup_pytorch_saver(ac)\n\n def update():\n data = buf.get()\n cost_data = cost_buf.get()\n\n # Compute cost using regular PPO\n pi_l_old, pi_info_old = compute_loss_pi(data)\n pi_l_old = pi_l_old.item()\n v_l_old = compute_loss_v(data).item()\n\n \n\n # Train policy with multiple steps of gradient descent\n for i in range(train_pi_iters):\n pi_optimizer.zero_grad()\n loss_pi, pi_info = compute_loss_pi(data,cost_data=cost_data)\n kl = mpi_avg(pi_info['kl'])\n if kl > 1.5 * target_kl:\n logger.log('Early stopping at step %d due to reaching max kl.'%i)\n break\n loss_pi.backward()\n mpi_avg_grads(ac.pi) # average grads across MPI processes\n pi_optimizer.step()\n\n logger.store(StopIter=i)\n\n # Value function learning\n for i in range(train_v_iters):\n vf_optimizer.zero_grad()\n loss_v = compute_loss_v(data)\n loss_v.backward()\n mpi_avg_grads(ac.v) # average grads across MPI processes\n vf_optimizer.step()\n\n jf_optimizer.zero_grad()\n loss_j = compute_loss_j(cost_data)\n loss_j.backward()\n mpi_avg_grads(ac.j) # average grads across MPI processes\n jf_optimizer.step()\n\n\n # Log changes from update\n kl, ent, cf = pi_info['kl'], pi_info_old['ent'], pi_info['cf']\n logger.store(LossPi=pi_l_old, LossV=v_l_old,\n KL=kl, Entropy=ent, ClipFrac=cf,\n DeltaLossPi=(loss_pi.item() - pi_l_old),\n DeltaLossV=(loss_v.item() - v_l_old))\n\n # Prepare for interaction with environment\n start_time = time.time()\n o, ep_ret, ep_len,ep_cost = env.reset(), 0, 0, 0\n\n # Main loop: collect experience in env and update/log each epoch\n for epoch in range(epochs):\n for t in range(local_steps_per_epoch):\n a, v,j,logp = ac.step(torch.as_tensor(o, dtype=torch.float32))\n\n next_o, r, d, info = env.step(a)\n ep_ret += r\n ep_len += 1\n # print(info)\n ep_cost += info['cost']\n # save and log\n buf.store(o, a, r, v, logp)\n cost_buf.store(o,a,info['cost'],j,logp)\n logger.store(VVals=v)\n \n # Update obs (critical!)\n o = next_o\n\n timeout = ep_len == max_ep_len\n terminal = d or timeout\n epoch_ended = t==local_steps_per_epoch-1\n\n if terminal or epoch_ended:\n if epoch_ended and not(terminal):\n print('Warning: trajectory cut off by epoch at %d steps.'%ep_len, flush=True)\n # if trajectory didn't reach terminal state, bootstrap value target\n if timeout or epoch_ended:\n _, v,j, _ = ac.step(torch.as_tensor(o, dtype=torch.float32))\n else:\n v = 0\n j=0\n buf.finish_path(v)\n cost_buf.finish_path(j)\n if terminal:\n # only save EpRet / EpLen if trajectory finished\n logger.store(EpRet=ep_ret, EpLen=ep_len,EpCost=ep_cost)\n o, ep_ret, ep_len, ep_cost = env.reset(), 0, 0, 0\n\n\n # Save model\n if (epoch % save_freq == 0) or (epoch == epochs-1):\n logger.save_state({'env': env}, None)\n\n # Perform PPO update!\n update()\n\n # Log info about epoch\n logger.log_tabular('Epoch', epoch)\n logger.log_tabular('EpRet', with_min_and_max=True)\n logger.log_tabular('EpCost', with_min_and_max=True)\n logger.log_tabular('EpLen', average_only=True)\n logger.log_tabular('VVals', with_min_and_max=True)\n logger.log_tabular('TotalEnvInteracts', (epoch+1)*steps_per_epoch)\n logger.log_tabular('LossPi', average_only=True)\n logger.log_tabular('LossV', average_only=True)\n logger.log_tabular('DeltaLossPi', average_only=True)\n logger.log_tabular('DeltaLossV', average_only=True)\n logger.log_tabular('Entropy', average_only=True)\n logger.log_tabular('KL', average_only=True)\n logger.log_tabular('ClipFrac', average_only=True)\n logger.log_tabular('StopIter', average_only=True)\n logger.log_tabular('Time', time.time()-start_time)\n logger.dump_tabular()\n\nif __name__ == '__main__':\n import argparse\n parser = argparse.ArgumentParser()\n parser.add_argument('--env', type=str, default='HalfCheetah-v2')\n parser.add_argument('--hid', type=int, default=64)\n parser.add_argument('--l', type=int, default=2)\n parser.add_argument('--gamma', type=float, default=0.99)\n parser.add_argument('--seed', '-s', type=int, default=0)\n parser.add_argument('--cpu', type=int, default=4)\n parser.add_argument('--steps', type=int, default=4000)\n parser.add_argument('--epochs', type=int, default=50)\n parser.add_argument('--exp_name', type=str, default='ppo')\n args = parser.parse_args()\n\n mpi_fork(args.cpu) # run parallel code with mpi\n\n from spinup.utils.run_utils import setup_logger_kwargs\n logger_kwargs = setup_logger_kwargs(args.exp_name, args.seed)\n\n ppo(lambda : gym.make(args.env), actor_critic=core.MLPActorCritic,\n ac_kwargs=dict(hidden_sizes=[args.hid]*args.l), gamma=args.gamma, \n seed=args.seed, steps_per_epoch=args.steps, epochs=args.epochs,\n logger_kwargs=logger_kwargs)\n" ]
[ [ "torch.min", "numpy.zeros", "numpy.random.seed", "torch.clamp", "torch.manual_seed", "numpy.append", "torch.as_tensor", "torch.exp" ] ]
brucespang/plorts
[ "78194a64128a0bba9cdf49279bcc09807df62fcf", "78194a64128a0bba9cdf49279bcc09807df62fcf" ]
[ "plorts/style.py", "examples/histogram.py" ]
[ "# Most of this is lifted from Seaborn (https://stanford.edu/~mwaskom/software/seaborn/)\n#\n# Copyright (c) 2012-2013, Michael L. Waskom\n# All rights reserved.\n\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are met:\n\n# * Redistributions of source code must retain the above copyright notice, this\n# list of conditions and the following disclaimer.\n\n# * Redistributions in binary form must reproduce the above copyright notice,\n# this list of conditions and the following disclaimer in the documentation\n# and/or other materials provided with the distribution.\n\n# * Neither the name of the {organization} nor the names of its\n# contributors may be used to endorse or promote products derived from\n# this software without specific prior written permission.\n\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\nfrom __future__ import division\nimport matplotlib\nimport matplotlib.pyplot as plt\n\n# Does a bunch of styling stuff that needs to be done manually instead of in the\n# rcparams\ndef style_axis(show_xaxis=False, label_fontweight='medium', label_fontstyle='italic'):\n ax = plt.gca()\n\n ax.xaxis.grid(show_xaxis) \n ax.xaxis.label.set_fontweight(label_fontweight)\n ax.xaxis.label.set_fontstyle(label_fontstyle)\n \n # position the y label at the top left, left-aligned with the ticks.\n left_in_axis = [0, 1]\n left_in_display = ax.transAxes.transform(left_in_axis)\n left_label_in_display = [left_in_display[0] - ax.yaxis.get_tick_space() * ax.figure.dpi/72.,\n left_in_display[1] + ax.xaxis.get_tick_space() * ax.figure.dpi/72.]\n left_label_in_axis = ax.transAxes.inverted().transform(left_label_in_display)\n\n ax.yaxis.set_label_coords(*left_label_in_axis)\n ax.yaxis.label.set_fontweight(label_fontweight)\n ax.yaxis.label.set_fontstyle(label_fontstyle)\n ax.yaxis.label.set_ha('left')\n ax.yaxis.label.set_va('bottom')\n ax.yaxis.label.set_rotation(0)\n\n # position the y label at the top left, left-aligned with the ticks.\n title_in_display = [left_in_display[0] - ax.yaxis.get_tick_space() * ax.figure.dpi/72.,\n left_label_in_display[1] + ax.xaxis.get_tick_space() * ax.figure.dpi/72.]\n title_in_axis = ax.transAxes.inverted().transform(title_in_display)\n ax.title.set_position(title_in_axis)\n ax.title.set_fontweight(\"bold\")\n ax.title.set_ha(\"left\")\n ax.title.set_ha(\"left\")\n \n plt.tight_layout()\n", "import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport plorts\nimport seaborn as sns\nplt.style.use(['plorts', 'plorts-web'])\n\nxmax = 2*np.pi\nf = lambda x,offset: (offset+1)*np.sin(x-offset)\nxs = np.arange(0,xmax,0.1)\noffsets = range(0,len(plorts.palettes.solarized))\noffsets = [4,5,6,7]\ndf = pd.DataFrame([[x, f(x, offset), i, np.abs(f(x, offset))] for x in xs for i,offset in enumerate(offsets)], columns=[\"x\", \"y\", \"offset\", \"abs\"])\n\nplt.figure()\nplorts.hist(data=df[np.logical_or(df.offset == 3, df.offset == 0)],\n x=\"y\", hue=\"offset\",\n bins=np.arange(-10,10,1))\nplt.ylabel(\"Y label\")\nplt.xlabel(\"X label\")\nplt.legend(loc='best')\nplt.title(\"Histogram Example\")\nplt.axis(xmin=-8,xmax=8)\nplorts.style_axis()\n" ]
[ [ "matplotlib.pyplot.gca", "matplotlib.pyplot.tight_layout" ], [ "numpy.logical_or", "numpy.sin", "matplotlib.pyplot.xlabel", "matplotlib.pyplot.title", "matplotlib.pyplot.legend", "matplotlib.pyplot.figure", "numpy.arange", "matplotlib.pyplot.ylabel", "matplotlib.pyplot.style.use", "matplotlib.pyplot.axis" ] ]
amn32/ML_implementations
[ "e54e363ac3ed19f16faf3ac47bc1c41469592bc7" ]
[ "regression/util_funcs.py" ]
[ "import numpy as np\nimport random\nimport pandas as pd\nimport os\nimport gc\nfrom sklearn.model_selection import train_test_split\n\ndef load_data(dataset, train_size = 10000, test_size = 0, standardise = False, validation_size = 0, noise = False):\n\n X_val = None\n Y_val = None\n \n if dataset == 'Sarcos':\n\n sarcos = pd.read_csv('sarcos_inv.csv',header=None).values\n\n X_vals = sarcos[:,:21]\n Y_vals = sarcos[:,[21]]\n \n del sarcos\n gc.collect()\n\n else:\n \n random.seed(50)\n\n n = int(train_size + test_size)\n\n X_vals = np.random.uniform(low = 0, high = 1, size = (n, 3))\n\n W = [[10], [2], [20]]\n b = [5]\n\n if dataset == 'L_toy':\n Y_vals = X_vals.dot(W) + b\n elif dataset == 'NL_toy':\n Y_vals = X_vals.dot(W)**2/10\n else:\n print('Incorrect dataset name')\n return\n \n if noise:\n \n Y_vals += np.random.normal(0,5,[len(Y_vals)]).reshape(-1,1)\n\n Y_vals = Y_vals.reshape(-1, 1)\n \n X_train, X_test, Y_train, Y_test = train_test_split(X_vals, Y_vals, train_size = train_size, random_state = 50)\n\n if standardise == True:\n mean = X_train.mean(axis = 0)\n std = X_train.std(axis = 0)\n\n X_train = (X_train - mean)/std\n X_test = (X_test - mean)/std\n \n if validation_size > 0:\n X_val, X_train, Y_val, Y_train = train_test_split(X_train, Y_train, train_size = validation_size)\n\n if test_size>0:\n\n X_test = X_test[:test_size]\n Y_test = Y_test[:test_size]\n \n print(f'{dataset} Data Loaded')\n \n return X_train, X_test, X_val, Y_train, Y_test, Y_val" ]
[ [ "sklearn.model_selection.train_test_split", "pandas.read_csv", "numpy.random.uniform" ] ]
lvclark/pyseer
[ "21ad8f2f00eb8b17e4de55a1a7f4954be7f3ddf6" ]
[ "scripts/phylogeny_distance.py" ]
[ "#!/usr/bin/env python\n# Copyright 2017 Marco Galardini and John Lees\n\n'''Extract a distance matrix from a phylogeny'''\n\n\ndef get_options():\n import argparse\n\n description = 'Extract a distance matrix from a phylogeny'\n parser = argparse.ArgumentParser(description=description)\n\n parser.add_argument('phylogeny',\n help='Tree file')\n\n parser.add_argument('--format',\n default=\"newick\",\n help=\"Format of tree file [Default: newick]\")\n parser.add_argument('--midpoint',\n action='store_true',\n default=False,\n help='Midpoint root the tree before calculating '\n 'distances.')\n method_group = parser.add_mutually_exclusive_group()\n method_group.add_argument('--lmm', '--calc-C',\n action='store_true',\n help='Produce var-covar matrix C (as from PDDIST). '\n 'Always uses branch lengths.')\n method_group.add_argument('--topology',\n action='store_true',\n default=False,\n help='Ignore branch lengths, and only use topological '\n 'distances')\n\n return parser.parse_args()\n\n\nif __name__ == \"__main__\":\n options = get_options()\n\n import sys\n import re\n import pandas as pd\n import dendropy\n\n tree = dendropy.Tree.get(\n path=options.phylogeny,\n schema=options.format,\n preserve_underscores=True)\n\n if options.midpoint:\n # Needs to be run twice\n tree.reroot_at_midpoint(update_bipartitions=True, suppress_unifurcations=False)\n tree.reroot_at_midpoint(update_bipartitions=True, suppress_unifurcations=False)\n\n d = {}\n pdm = tree.phylogenetic_distance_matrix()\n for idx1, taxon1 in enumerate(tree.taxon_namespace):\n d[taxon1.label] = d.get(taxon1.label, {})\n for taxon2 in tree.taxon_namespace:\n if taxon2.label not in d[taxon1.label].keys():\n if options.lmm:\n mrca = pdm.mrca(taxon1, taxon2)\n d[taxon1.label][taxon2.label] = mrca.distance_from_root()\n elif options.topology:\n d[taxon1.label][taxon2.label] = pdm.path_edge_count(taxon1, taxon2)\n else:\n d[taxon1.label][taxon2.label] = pdm.patristic_distance(taxon1, taxon2)\n\n m = pd.DataFrame(d)\n m = m.reindex(m.columns)\n m.to_csv(sys.stdout,\n sep='\\t')\n\n" ]
[ [ "pandas.DataFrame" ] ]
MatteoLacki/msspec
[ "587fb7dc91d5f2d3618aa4ba8a2803969a40ea97" ]
[ "msspec/__init__.py" ]
[ "try:\n import matplotlib.pyplot as plt\nexcept ModuleNotFoundError:\n plt = None\n\n\ntry:\n import plotly\nexcept ModuleNotFoundError:\n plotly = None\n\n\nprint('Setting matplotlib style to dark.')\nplt.style.use('dark_background')" ]
[ [ "matplotlib.pyplot.style.use" ] ]
yanxurui/portfolio
[ "032cf47ccac1c5815fd4827bf0d5f3cf43cec990" ]
[ "portfolio_env.py" ]
[ "import gym\nfrom gym import spaces\nimport numpy as np\nimport pandas as pd\nfrom dataset import Dataset\n\nclass PortfolioEnv(gym.Env):\n def __init__(self, features, stocks, batch_num=1, batch_size=10, window=10):\n self.features = features\n self.stocks = stocks\n self.batch_num = batch_num\n self.batch_size = batch_size\n self.window = window # using historical price in the past M days as feature\n self.assets = len(self.stocks) + 1\n self.observation_shape = (len(self.features), self.assets, self.window)\n self.action_space = spaces.Box(low=0, high=1, shape=(self.assets,), dtype=np.float32)\n self.observation_space = spaces.Box(\n low=np.zeros(self.observation_shape),\n high=np.full(self.observation_shape, np.finfo(np.float32).max),\n dtype=np.float32)\n\n self.data = Dataset('data.csv', features=self.features, stocks=self.stocks,\n train_batch_num=self.batch_num,\n batch_size=self.batch_size,\n window=self.window)\n self._step = self._step_generator()\n\n def _step_generator(self):\n while True: # loop\n for X, y in self.data.train_batch(): # episode\n for i in range(self.batch_size+1): # step\n if self._reset:\n self._reset = False\n if i: # not at the begining, move to next batch\n break\n if i == self.batch_size:\n self.done = True\n self.state = None\n self.y = None\n else:\n self.done = False\n self.state = X[i]\n self.y = y[i]\n yield\n\n def step(self, w):\n self._record = np.array([self.y-1, w]) # # record for rendering\n if self.done:\n raise RuntimeError('Current episode has already been done. Call reset to start another episode.')\n w = np.clip(w, 0, 1)\n reward = np.log(np.sum(w * self.y))\n next(self._step)\n return self.state, reward, self.done, {}\n\n def reset(self):\n '''reset can be called at any step:\n 1. it will be called at the begining of any episode\n 2. it might also be called during an episode\n \n This method results in moving to next batch\n '''\n self._reset = True\n next(self._step)\n return self.state\n\n def render(self, mode='human'):\n '''first line is price relative change rate, second line is portfolio weights'''\n print(self._record)\n\n \nfrom gym.envs.registration import register\ngym.envs.registry.env_specs.pop('Portfolio-v0', None)\nregister(\n id='Portfolio-v0',\n entry_point=PortfolioEnv\n)\n\n\nif __name__ == '__main__':\n from numpy.testing import assert_equal\n w = [1, 0]\n env = gym.make('Portfolio-v0',\n features=['Close'],\n stocks = ['GOOGL'],\n batch_num = 1,\n batch_size = 10,\n window=10)\n obsv = env.reset()\n for i in range(9):\n state, reward, done, _ = env.step(w)\n assert_equal(done, False)\n state, reward, done, _ = env.step(w)\n assert_equal(done, True)\n assert_equal(state, None)\n obsv2 = env.reset()\n assert_equal(obsv, obsv2)\n\n env = gym.make('Portfolio-v0',\n features=['Close'],\n stocks = ['GOOGL'],\n batch_num = 2,\n batch_size = 10,\n window=10)\n obsv = env.reset()\n for i in range(10):\n env.step(w)\n env.reset()\n state, reward, done, _ = env.step(w)\n obsv2 = env.reset()\n assert_equal(obsv, obsv2)\n" ]
[ [ "numpy.array", "numpy.zeros", "numpy.testing.assert_equal", "numpy.sum", "numpy.finfo", "numpy.clip" ] ]
michaelgzt/kaggle-digit-recognizer
[ "0e1b98f2e7f391e78950d1b55484166293aa2a24" ]
[ "dataloader.py" ]
[ "import torch\nimport pandas as pd\nimport numpy as np\nimport math\nimport time\nfrom random import shuffle, randint\nimport matplotlib.pyplot as plt\nfrom torch.utils.data import Dataset, DataLoader, sampler\nfrom torchvision import transforms\n\n\n\"\"\"\nDataset for Digit Data\nand Transformation functions\n\"\"\"\n\n\nclass DigitDataset(Dataset):\n \"\"\" Digit Dataset \"\"\"\n\n def __init__(self, csv_file, root_dir, train=False, argument=False, transform=None):\n \"\"\"\n\n :param csv_file: file name for data\n :param root_dir: directory to the csv file\n :param train: train dataset or test dataset\n :param transform: Optional transform functions\n \"\"\"\n self.digit_data = DigitDataset.gen_dataset(csv_file, root_dir, argument, train)\n self.transform = transform\n\n def __len__(self):\n \"\"\"\n Return length of the dataset\n\n :return: length of dataset\n \"\"\"\n return len(self.digit_data)\n\n def __getitem__(self, item):\n \"\"\"\n Iterator of the dataset\n\n :param item: index of data\n :return: one item\n \"\"\"\n sample = self.digit_data[item].copy()\n if self.transform:\n sample[0] = self.transform(sample[0])\n return sample\n\n @staticmethod\n def gen_dataset(csv_file, root_dir, argument, train):\n \"\"\"\n\n\n :param csv_file: file name for data\n :param root_dir: directory to the csv file\n :param argument: if true use data argument\n :param train: train dataset or test dataset\n :return: all data\n \"\"\"\n data_df = pd.read_csv(root_dir + csv_file)\n all_data = []\n for num in range(len(data_df)):\n if train:\n digit = data_df.iloc[num, 1:].values\n digit = digit.astype('float').reshape((28, 28))\n label = data_df.iloc[num, 0]\n else:\n digit = data_df.iloc[num, :].values\n digit = digit.astype('float').reshape((28, 28))\n label = 0\n sample = [digit, label]\n all_data.append(sample)\n if argument:\n rand_theta = randint(-10, 10)\n rand_x = randint(-3, 3)\n rand_y = randint(-3, 3)\n new_digit = affine_transform_rotation(digit, rand_theta)\n new_digit = affine_transform_translation(new_digit, rand_x, rand_y)\n new_sample = [new_digit, label]\n all_data.append(new_sample)\n return all_data\n\n\nclass Regularize(object):\n \"\"\" Regularize digit pixel value \"\"\"\n\n def __init__(self, max_pixel=255):\n \"\"\"\n\n :param max_pixel: max pixel value\n \"\"\"\n self.max_pixel = max_pixel\n\n def __call__(self, digit):\n \"\"\"\n\n :param digit: digit image\n :return:\n \"\"\"\n assert isinstance(digit, np.ndarray)\n digit = digit / self.max_pixel\n return digit\n\n\nclass ToTensor(object):\n \"\"\" Covert ndarrays to Tensors \"\"\"\n\n def __call__(self, digit):\n \"\"\"\n\n :param digit: digit image\n :return:\n \"\"\"\n assert isinstance(digit, np.ndarray)\n digit = digit.reshape((1, 28, 28))\n digit = torch.from_numpy(digit)\n digit = digit.float()\n return digit\n\n\ndef digits_per_class(dataset, indices):\n \"\"\"\n Compute number of digits per class base on indices\n\n :param dataset: dataset of all digits\n :param indices: list of indices\n :return: number of digits for all classes\n \"\"\"\n assert isinstance(dataset, DigitDataset)\n assert isinstance(indices, list)\n digit_num = [0 for num in range(10)]\n for idx in indices:\n digit_num[dataset[idx][1]] += 1\n return digit_num\n\n\ndef train_validate_split(dataset, test_ratio=0.1):\n \"\"\"\n Divide dataset into training and validation randomly\n and with balanced number of digits in each class\n\n :param dataset: dataset of all digits\n :param test_ratio: ratio of validation data\n :return: lists of indices of train and validate dataset\n \"\"\"\n assert isinstance(dataset, DigitDataset)\n overall_indices = [num for num in range(len(dataset))]\n overall_class_num = digits_per_class(dataset, overall_indices)\n test_class_num = [int(num*test_ratio) for num in overall_class_num]\n tmp_test_class_num = [0 for num in range(10)]\n shuffle(overall_indices)\n train_indices = []\n val_indices = []\n for idx in overall_indices:\n tmp_label = dataset[idx][1]\n if tmp_test_class_num[tmp_label] < test_class_num[tmp_label]:\n val_indices.append(idx)\n tmp_test_class_num[tmp_label] += 1\n else:\n train_indices.append(idx)\n return train_indices, val_indices\n\n\ndef affine_transform_translation(image, x, y):\n \"\"\"\n Perform translation on digit image\n\n :param image: numpy image\n :param x: translation on x\n :param y: translation on y\n :return: new image\n \"\"\"\n digit_location = np.argwhere(image > 0)\n transform_location = np.int_(np.ones((digit_location.shape[0], 3)))\n transform_location[:, :2] = digit_location\n translation_matrix = np.array([[1, 0, x],\n [0, 1, y],\n [0, 0, 1]])\n transform_location = np.int_(np.dot(translation_matrix, transform_location.T)).T\n \"\"\"\n Check if the digit is out of image\n \"\"\"\n max_x = np.amax(transform_location[:, 0])\n min_x = np.amin(transform_location[:, 0])\n max_y = np.amax(transform_location[:, 1])\n min_y = np.amin(transform_location[:, 1])\n if max_x > 27 or min_x < 0 or max_y > 27 or min_y < 0:\n back_x = 0\n back_y = 0\n if max_x > 27:\n back_x = 27 - max_x\n elif min_x < 0:\n back_x = -min_x\n if max_y > 27:\n back_y = 27 - max_y\n elif min_y < 0:\n back_y = -min_y\n back_translation_matrix = np.array([[1, 0, back_x],\n [0, 1, back_y],\n [0, 0, 1]])\n transform_location = np.int_(np.dot(back_translation_matrix, transform_location.T)).T\n \"\"\"\n Generate new image\n \"\"\"\n new_image = np.zeros((28, 28))\n new_image[transform_location[:, 0], transform_location[:, 1]] = image[digit_location[:, 0], digit_location[:, 1]]\n return new_image\n\n\ndef affine_transform_rotation(image, theta):\n \"\"\"\n Preform rotation on digit image\n\n :param image: numpy image\n :param theta: rotation\n :return: new image\n \"\"\"\n digit_location = np.argwhere(image > 0)\n \"\"\"\n move digit to [0, 0]\n \"\"\"\n digit_mass_center = digit_location.mean(axis=0)\n transform_location = np.int_(np.ones((digit_location.shape[0], 3)))\n transform_location[:, :2] = digit_location\n translation_matrix = np.array([[1, 0, -digit_mass_center[0]],\n [0, 1, -digit_mass_center[1]],\n [0, 0, 1]])\n transform_location = np.int_(np.round(np.dot(translation_matrix, transform_location.T))).T\n \"\"\"\n rotate image\n \"\"\"\n theta = (theta / 360) * (2 * math.pi)\n rotation_matrix = np.array([[math.cos(theta), math.sin(theta), 0],\n [-math.sin(theta), math.cos(theta), 0],\n [0, 0, 1]])\n transform_location = np.int_(np.round(np.dot(rotation_matrix, transform_location.T))).T\n \"\"\"\n move back digit\n \"\"\"\n back_translation_matrix = np.array([[1, 0, digit_mass_center[0]],\n [0, 1, digit_mass_center[1]],\n [0, 0, 1]])\n transform_location = np.int_(np.round(np.dot(back_translation_matrix, transform_location.T))).T\n \"\"\"\n Check if the digit is out of image\n \"\"\"\n max_x = np.amax(transform_location[:, 0])\n min_x = np.amin(transform_location[:, 0])\n max_y = np.amax(transform_location[:, 1])\n min_y = np.amin(transform_location[:, 1])\n if max_x > 27 or min_x < 0 or max_y > 27 or min_y < 0:\n back_x = 0\n back_y = 0\n if max_x > 27:\n back_x = 27 - max_x\n elif min_x < 0:\n back_x = -min_x\n if max_y > 27:\n back_y = 27 - max_y\n elif min_y < 0:\n back_y = -min_y\n back_translation_matrix = np.array([[1, 0, back_x],\n [0, 1, back_y],\n [0, 0, 1]])\n transform_location = np.int_(np.dot(back_translation_matrix, transform_location.T)).T\n \"\"\"\n Generate new image\n \"\"\"\n new_image = np.zeros((28, 28))\n new_image[transform_location[:, 0], transform_location[:, 1]] = image[digit_location[:, 0], digit_location[:, 1]]\n \"\"\"\n Fill the empty pixels\n \"\"\"\n max_x = np.amax(transform_location[:, 0])\n min_x = np.amin(transform_location[:, 0])\n max_y = np.amax(transform_location[:, 1])\n min_y = np.amin(transform_location[:, 1])\n for tmp_x in range(min_x, max_x):\n for tmp_y in range(min_y, max_y):\n pixel = new_image[tmp_x, tmp_y]\n if pixel == 0:\n up_pixel = new_image[tmp_x-1, tmp_y]\n down_pixel = new_image[tmp_x+1, tmp_y]\n left_pixel = new_image[tmp_x, tmp_y-1]\n right_pixel = new_image[tmp_x, tmp_y+1]\n if up_pixel > 0 and down_pixel > 0 and right_pixel > 0 and left_pixel > 0:\n new_image[tmp_x, tmp_y] = (up_pixel + down_pixel + right_pixel + left_pixel) / 4\n elif up_pixel > 0 and down_pixel > 0:\n new_image[tmp_x, tmp_y] = (up_pixel + down_pixel) / 2\n elif left_pixel > 0 and right_pixel > 0:\n new_image[tmp_x, tmp_y] = (left_pixel + right_pixel) / 2\n return new_image\n\n\nif __name__ == '__main__':\n composed_transform = transforms.Compose([Regularize(), ToTensor()])\n time1 = time.time()\n data = DigitDataset('train.csv', './data/', train=True, argument=False)\n print(len(data))\n class_num = digits_per_class(data, [num for num in range(len(data))])\n print(class_num)\n train_idx, val_idx = train_validate_split(data)\n print(len(train_idx), len(val_idx), len(train_idx) + len(val_idx))\n train_class_num = digits_per_class(data, train_idx)\n print(train_class_num)\n val_class_num = digits_per_class(data, val_idx)\n print(val_class_num)\n" ]
[ [ "numpy.array", "numpy.dot", "numpy.zeros", "numpy.ones", "torch.from_numpy", "numpy.amax", "numpy.amin", "pandas.read_csv", "numpy.argwhere" ] ]
SgtVincent/Robothor-2020---VIPL-ICT
[ "5eee00c077c07e69120fb8108f574c2339688f34" ]
[ "runners/nonadaptivea3c_val.py" ]
[ "from __future__ import division\n\nimport time\nimport torch\nimport setproctitle\nimport copy\nfrom datasets.glove import Glove\nfrom datasets.prototypes import Prototype\n\nfrom datasets.robothor_data import (\n preload_metadata,\n get_curriculum_meta,\n load_offline_shortest_path_data\n)\n\nfrom models.model_io import ModelOptions\nimport os\n\nfrom .train_util import (\n compute_loss,\n new_episode,\n run_episode,\n end_episode,\n reset_player,\n compute_spl,\n get_bucketed_metrics,\n)\n\n\ndef nonadaptivea3c_val(\n rank,\n args,\n model_to_open,\n model_create_fn,\n initialize_agent,\n res_queue,\n max_count,\n scene_type,\n):\n\n glove = None\n protos = None\n pre_metadata = None\n curriculum_meta = None\n scene_types = [scene_type]\n offline_shortest_data = None\n\n\n if args.glove_file:\n glove = Glove(args.glove_file)\n if args.proto_file:\n protos = Prototype(args.proto_file)\n\n if args.data_source == \"ithor\":\n\n from datasets.ithor_data import get_data, name_to_num\n\n scenes, possible_targets, targets = get_data(scene_types, args.val_scenes)\n num = name_to_num(scene_type)\n scenes = scenes[0]\n targets = targets[0]\n\n elif args.data_source == \"robothor\":\n\n from datasets.robothor_data import get_data\n # TODO: design a flexible scene allocating strategy\n\n pre_metadata = preload_metadata(args, scene_types)\n\n scenes, possible_targets, targets = get_data(scene_types)\n scenes = scenes[0]\n targets = targets[0]\n\n if args.curriculum_learning:\n curriculum_meta = get_curriculum_meta(args, scenes)\n if args.offline_shortest_data:\n offline_shortest_data = load_offline_shortest_path_data(args, scenes)\n\n\n setproctitle.setproctitle(\"Val Agent: {}\".format(rank))\n\n gpu_id = args.gpu_ids[rank % len(args.gpu_ids)]\n torch.manual_seed(args.seed + rank)\n if gpu_id >= 0:\n torch.cuda.manual_seed(args.seed + rank)\n\n shared_model = model_create_fn(args)\n\n if model_to_open != \"\":\n saved_state = torch.load(\n model_to_open, map_location=lambda storage, loc: storage\n )\n shared_model.load_state_dict(saved_state)\n\n player = initialize_agent(model_create_fn, args, rank, gpu_id=gpu_id)\n player.sync_with_shared(shared_model)\n count = 0\n\n model_options = ModelOptions()\n\n while count < max_count:\n\n # Get a new episode.\n total_reward = 0\n player.eps_len = 0\n scene = new_episode(args, player, scenes, possible_targets, targets, glove=glove, protos=protos,\n pre_metadata=pre_metadata, curriculum_meta=curriculum_meta)\n if scene == None: # iteration stopped\n break\n\n player_start_state = copy.deepcopy(player.environment.controller.state)\n player_start_time = time.time()\n\n # Train on the new episode.\n while not player.done:\n\n # Make sure model is up to date.\n # player.sync_with_shared(shared_model)\n # Run episode for num_steps or until player is done.\n total_reward = run_episode(player, args, total_reward, model_options, False)\n # Compute the loss.\n # loss = compute_loss(args, player, gpu_id, model_options)\n if not player.done:\n reset_player(player)\n\n # for k in loss:\n # loss[k] = loss[k].item()\n if offline_shortest_data: # assume data_source == robothor and curriculum_learning is True\n scene = player.environment.scene_name\n episode_id = player.episode.episode_id\n best_path_length = offline_shortest_data[scene][episode_id]\n spl = player.success * (best_path_length / float(player.eps_len))\n else:\n spl, best_path_length = compute_spl(player, player_start_state)\n\n bucketed_spl = get_bucketed_metrics(spl, best_path_length, player.success)\n if args.curriculum_learning:\n end_episode(\n player,\n res_queue,\n total_time=time.time() - player_start_time,\n total_reward=total_reward,\n spl=spl,\n **bucketed_spl,\n scene_type=scene_type,\n difficulty=player.episode.difficulty\n ) \n else:\n end_episode(\n player,\n res_queue,\n total_time=time.time() - player_start_time,\n total_reward=total_reward,\n spl=spl,\n **bucketed_spl,\n scene_type=scene_type,\n )\n\n count += 1\n reset_player(player)\n\n player.exit()\n res_queue.put({\"END\":True, \"scene_type\":scene_type, \"total_episodes\": count})\n" ]
[ [ "torch.manual_seed", "torch.cuda.manual_seed", "torch.load" ] ]
MCG-NJU/MMN
[ "64641d12d4e1197b7378b3f786916b4cfd1a5080" ]
[ "mmn/data/datasets/evaluation.py" ]
[ "from terminaltables import AsciiTable\nfrom tqdm import tqdm\nimport logging\nimport torch\nfrom mmn.data.datasets.utils import iou, score2d_to_moments_scores\nfrom mmn.utils.comm import is_main_process\n\n\ndef nms(moments, scores, thresh):\n scores, ranks = scores.sort(descending=True)\n moments = moments[ranks]\n suppressed = ranks.zero_().bool()\n numel = suppressed.numel()\n for i in range(numel - 1):\n if suppressed[i]:\n continue\n mask = iou(moments[i+1:], moments[i]) > thresh\n suppressed[i+1:][mask] = True\n return moments[~suppressed]\n\n\ndef evaluate(cfg, dataset, predictions, nms_thresh, recall_metrics=(1, 5)):\n \"\"\"evaluate dataset using different methods based on dataset type.\n Args:\n Returns:\n \"\"\"\n if not is_main_process():\n return\n if cfg.DATASETS.NAME == \"tacos\":\n iou_metrics = (0.1, 0.3, 0.5)\n elif cfg.DATASETS.NAME == \"activitynet\":\n iou_metrics = (0.3, 0.5, 0.7)\n elif cfg.DATASETS.NAME == \"charades\":\n iou_metrics = (0.5, 0.7)\n else:\n raise NotImplementedError(\"No support for %s dataset!\" % cfg.DATASETS.NAME)\n dataset_name = dataset.__class__.__name__\n logger = logging.getLogger(\"mmn.inference\")\n logger.info(\"Performing {} evaluation (Size: {}).\".format(dataset_name, len(dataset)))\n num_recall_metrics, num_iou_metrics = len(recall_metrics), len(iou_metrics)\n recall_metrics = torch.tensor(recall_metrics)\n iou_metrics = torch.tensor(iou_metrics)\n num_clips = predictions[0]['iou'].shape[-1]\n table = [['R@{},IoU@{:.01f}'.format(i, torch.round(j*100)/100) for i in recall_metrics for j in iou_metrics]]\n recall_x_iou = torch.zeros(num_recall_metrics, num_iou_metrics)\n num_instance = 0\n for idx, result2d in tqdm(enumerate(predictions)): # each video\n score2d = torch.pow(result2d['contrastive'] * 0.5 + 0.5, cfg.TEST.CONTRASTIVE_SCORE_POW) * result2d['iou']\n duration = dataset.get_duration(idx)\n gt_moments = dataset.get_moment(idx)\n for gt_moment, pred_score2d in zip(gt_moments, score2d): # each sentence\n num_instance += 1\n candidates, scores = score2d_to_moments_scores(pred_score2d, num_clips, duration)\n moments = nms(candidates, scores, nms_thresh)\n for i, r in enumerate(recall_metrics):\n mious = iou(moments[:r], gt_moment)\n bools = mious[:, None].expand(r, num_iou_metrics) >= iou_metrics\n recall_x_iou[i] += bools.any(dim=0)\n recall_x_iou /= num_instance\n table.append(['{:.02f}'.format(recall_x_iou[i][j]*100) for i in range(num_recall_metrics) for j in range(num_iou_metrics)])\n table = AsciiTable(table)\n for i in range(num_recall_metrics*num_iou_metrics):\n table.justify_columns[i] = 'center'\n logger.info('\\n' + table.table)\n result_dict = {}\n for i in range(num_recall_metrics):\n for j in range(num_iou_metrics):\n result_dict['R@{},IoU@{:.01f}'.format(recall_metrics[i], torch.round(iou_metrics[j]*100)/100)] = recall_x_iou[i][j]\n best_r1 = sum(recall_x_iou[0])/num_iou_metrics\n best_r5 = sum(recall_x_iou[1])/num_iou_metrics\n result_dict['Best_R1'] = best_r1\n result_dict['Best_R5'] = best_r5\n return result_dict\n\n" ]
[ [ "torch.zeros", "torch.round", "torch.tensor", "torch.pow" ] ]
hkaneko1985/y_randomization
[ "bccb8eaf99b57ecb63dd6fe413319e0fa91bb0f4" ]
[ "demo_y_randamization.py" ]
[ "# -*- coding: utf-8 -*- \r\n# %reset -f\r\n\"\"\"\r\n@author: Hiromasa Kaneko\r\n\"\"\"\r\n# Demonstration of y-randomization\r\n\r\n\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\nfrom sklearn import datasets\r\nfrom sklearn import model_selection\r\nfrom sklearn.cross_decomposition import PLSRegression\r\nfrom sklearn.model_selection import train_test_split\r\n\r\n# settings\r\nnumber_of_training_samples = 100\r\nnumber_of_test_samples = 10000\r\nnumber_of_x_variables = 1000\r\nnumber_of_y_randomization = 30\r\nmax_number_of_pls_components = 20\r\nfold_number = 5\r\n\r\n# generate sample dataset\r\nx, y = datasets.make_regression(n_samples=number_of_training_samples + number_of_test_samples,\r\n n_features=number_of_x_variables, n_informative=10, noise=30, random_state=0)\r\nx_train, x_test, y_train, y_test = train_test_split(x, y, test_size=number_of_test_samples, random_state=0)\r\n\r\n# autoscaling\r\nautoscaled_x_train = (x_train - x_train.mean(axis=0)) / x_train.std(axis=0, ddof=1)\r\nautoscaled_y_train = (y_train - y_train.mean()) / y_train.std(ddof=1)\r\nautoscaled_x_test = (x_test - x_train.mean(axis=0)) / x_train.std(axis=0, ddof=1)\r\n\r\n# modeling and prediction\r\npls_components = np.arange(1, min(np.linalg.matrix_rank(autoscaled_x_train) + 1, max_number_of_pls_components + 1), 1)\r\nmae_all_cv = list()\r\nfor pls_component in pls_components:\r\n pls_model_in_cv = PLSRegression(n_components=pls_component)\r\n pls_model_in_cv.fit(autoscaled_x_train, autoscaled_y_train)\r\n calculated_y_in_cv = np.ndarray.flatten(pls_model_in_cv.predict(autoscaled_x_train))\r\n estimated_y_in_cv = np.ndarray.flatten(\r\n model_selection.cross_val_predict(pls_model_in_cv, autoscaled_x_train, autoscaled_y_train, cv=fold_number))\r\n calculated_y_in_cv = calculated_y_in_cv * y_train.std(ddof=1) + y_train.mean()\r\n estimated_y_in_cv = estimated_y_in_cv * y_train.std(ddof=1) + y_train.mean()\r\n mae_all_cv.append(float(sum(abs(y_train - estimated_y_in_cv)) / len(y_train)))\r\noptimal_pls_component_number = np.where(mae_all_cv == np.min(mae_all_cv))\r\noptimal_pls_component_number = optimal_pls_component_number[0][0] + 1\r\nregression_model = PLSRegression(n_components=optimal_pls_component_number)\r\nregression_model.fit(autoscaled_x_train, autoscaled_y_train)\r\nestimated_y_train = np.ndarray.flatten(regression_model.predict(autoscaled_x_train))\r\nestimated_y_train = estimated_y_train * y_train.std(ddof=1) + y_train.mean()\r\nestimated_y_train_cv = np.ndarray.flatten(\r\n model_selection.cross_val_predict(regression_model, autoscaled_x_train, autoscaled_y_train, cv=fold_number))\r\nestimated_y_train_cv = estimated_y_train_cv * y_train.std(ddof=1) + y_train.mean()\r\npredicted_y_test = np.ndarray.flatten(regression_model.predict(autoscaled_x_test))\r\npredicted_y_test = predicted_y_test * y_train.std(ddof=1) + y_train.mean()\r\n\r\n# y-randomization\r\nstatistics_yrand = np.empty([number_of_y_randomization, 6])\r\nfor y_rand_num in range(number_of_y_randomization):\r\n print('{0} / {1}'.format(y_rand_num + 1, number_of_y_randomization))\r\n autoscaled_y_train_rand = np.random.permutation(autoscaled_y_train)\r\n y_train_rand = autoscaled_y_train_rand * y_train.std(ddof=1) + y_train.mean()\r\n mae_all_cv = list()\r\n for pls_component in pls_components:\r\n pls_model_in_cv = PLSRegression(n_components=pls_component)\r\n pls_model_in_cv.fit(autoscaled_x_train, autoscaled_y_train_rand)\r\n calculated_y_in_cv = np.ndarray.flatten(pls_model_in_cv.predict(autoscaled_x_train))\r\n estimated_y_in_cv = np.ndarray.flatten(\r\n model_selection.cross_val_predict(pls_model_in_cv, autoscaled_x_train, autoscaled_y_train_rand,\r\n cv=fold_number))\r\n calculated_y_in_cv = calculated_y_in_cv * y_train.std(ddof=1) + y_train.mean()\r\n estimated_y_in_cv = estimated_y_in_cv * y_train.std(ddof=1) + y_train.mean()\r\n mae_all_cv.append(float(sum(abs(y_train_rand - estimated_y_in_cv)) / len(y_train)))\r\n optimal_pls_component_number_rand = np.where(mae_all_cv == np.min(mae_all_cv))\r\n optimal_pls_component_number_rand = optimal_pls_component_number_rand[0][0] + 1\r\n regression_model = PLSRegression(n_components=optimal_pls_component_number_rand)\r\n regression_model.fit(autoscaled_x_train, autoscaled_y_train_rand)\r\n estimated_y_train_rand = np.ndarray.flatten(regression_model.predict(autoscaled_x_train))\r\n estimated_y_train_rand = estimated_y_train_rand * y_train.std(ddof=1) + y_train.mean()\r\n estimated_y_in_cv_rand = np.ndarray.flatten(\r\n model_selection.cross_val_predict(regression_model, autoscaled_x_train, autoscaled_y_train_rand,\r\n cv=fold_number))\r\n estimated_y_in_cv_rand = estimated_y_in_cv_rand * y_train.std(ddof=1) + y_train.mean()\r\n\r\n statistics_yrand[y_rand_num, 0] = float(\r\n 1 - sum((y_train_rand - estimated_y_train_rand) ** 2) / sum((y_train_rand - y_train.mean()) ** 2))\r\n statistics_yrand[y_rand_num, 1] = float((sum((y_train_rand - estimated_y_train_rand) ** 2) / len(y_train)) ** 0.5)\r\n statistics_yrand[y_rand_num, 2] = float(sum(abs(y_train_rand - estimated_y_train_rand)) / len(y_train))\r\n statistics_yrand[y_rand_num, 3] = float(\r\n 1 - sum((y_train_rand - estimated_y_in_cv_rand) ** 2) / sum((y_train_rand - y_train.mean()) ** 2))\r\n statistics_yrand[y_rand_num, 4] = float((sum((y_train_rand - estimated_y_in_cv_rand) ** 2) / len(y_train)) ** 0.5)\r\n statistics_yrand[y_rand_num, 5] = float(sum(abs(y_train_rand - estimated_y_in_cv_rand)) / len(y_train))\r\n\r\n# results\r\nplt.rcParams[\"font.size\"] = 16\r\nplt.plot(np.ones(number_of_y_randomization), statistics_yrand[:, 0], 'b.')\r\nplt.plot(np.ones(number_of_y_randomization) * 2, statistics_yrand[:, 3], 'b.')\r\nplt.xticks([1, 2], ['r2rand', 'r2rand,cv'])\r\nplt.ylabel('r2')\r\nplt.show()\r\nprint('average: {0}, {1}'.format(statistics_yrand[:, 0].mean(), statistics_yrand[:, 3].mean()))\r\n\r\nplt.plot(np.ones(number_of_y_randomization), statistics_yrand[:, 1], 'b.')\r\nplt.plot(np.ones(number_of_y_randomization) * 2, statistics_yrand[:, 2], 'r.')\r\nplt.plot(np.ones(number_of_y_randomization) * 3, statistics_yrand[:, 4], 'b.')\r\nplt.plot(np.ones(number_of_y_randomization) * 4, statistics_yrand[:, 5], 'r.')\r\nplt.xticks([1, 2, 3, 4], ['RMSErand', 'MAErand', 'RMSErand,cv', 'MAErand,cv'])\r\nplt.ylabel('RMSE(blue), MAE(red)')\r\nplt.show()\r\nprint('average: {0}, {1}, {2}, {3}'.format(statistics_yrand[:, 1].mean(), statistics_yrand[:, 2].mean(),\r\n statistics_yrand[:, 4].mean(), statistics_yrand[:, 5].mean()))\r\n\r\nprint('')\r\nprint('RMSEaverage: {0}'.format(float((sum((y_train - y_train.mean()) ** 2) / len(y_train)) ** 0.5)))\r\nprint('MAEaverage: {0}'.format(float(sum(abs(y_train - y_train.mean())) / len(y_train))))\r\nprint('')\r\nprint('r2: {0}'.format(float(1 - sum((y_train - estimated_y_train) ** 2) / sum((y_train - y_train.mean()) ** 2))))\r\nprint('RMSE: {0}'.format(float((sum((y_train - estimated_y_train) ** 2) / len(y_train)) ** 0.5)))\r\nprint('MAE: {0}'.format(float(sum(abs(y_train - estimated_y_train)) / len(y_train))))\r\nprint('')\r\nprint('r2cv: {0}'.format(float(1 - sum((y_train - estimated_y_train_cv) ** 2) / sum((y_train - y_train.mean()) ** 2))))\r\nprint('RMSEcv: {0}'.format(float((sum((y_train - estimated_y_train_cv) ** 2) / len(y_train)) ** 0.5)))\r\nprint('MAEcv: {0}'.format(float(sum(abs(y_train - estimated_y_train_cv)) / len(y_train))))\r\nprint('')\r\nprint('r2p: {0}'.format(float(1 - sum((y_test - predicted_y_test) ** 2) / sum((y_test - y_test.mean()) ** 2))))\r\nprint('RMSEp: {0}'.format(float((sum((y_test - predicted_y_test) ** 2) / len(y_test)) ** 0.5)))\r\nprint('MAEp: {0}'.format(float(sum(abs(y_test - predicted_y_test)) / len(y_test))))\r\n" ]
[ [ "sklearn.cross_decomposition.PLSRegression", "numpy.empty", "numpy.linalg.matrix_rank", "numpy.random.permutation", "numpy.ones", "numpy.min", "sklearn.datasets.make_regression", "matplotlib.pyplot.ylabel", "sklearn.model_selection.train_test_split", "matplotlib.pyplot.show", "sklearn.model_selection.cross_val_predict", "matplotlib.pyplot.xticks" ] ]
dmachalz/molpy
[ "acc026b1c1b577c7dce4ee50f6b7ad946a2a5fdd" ]
[ "molpy/util.py" ]
[ "import numpy as np\n\ndef distance(point1, point2):\n \"\"\"\n Calculate distance between two points.\n Parameters\n ----------\n point1: array_like\n The first point\n point2 : array_like\n The second point\n\n Returns\n ----------\n float\n The distance between point1 and point2.\n \"\"\"\n point1 = np.asarray(point1)\n point2 = np.asarray(point2)\n return np.linalg.norm(point1-point2)\n" ]
[ [ "numpy.linalg.norm", "numpy.asarray" ] ]
fy0cc/factor-inference-net
[ "1ade2a91f5adf8f049f818183910797db56a70b4" ]
[ "factor_gnn/layers.py" ]
[ "import torch\nimport torch.nn as nn\n\nfrom .mlp import MLP\n\nNDIM_HIDDEN = 64\n\n\nclass SigmoidWrapper(nn.Module):\n def __init__(self, model):\n super(SigmoidWrapper, self).__init__()\n self.model = model\n self.m = nn.Sigmoid()\n\n def forward(self, *args, **kwargs):\n return self.m(self.model(*args, **kwargs))\n\n\nclass GGNNReadoutLayer(nn.Module):\n def __init__(self, nhid, nout):\n super(GGNNReadoutLayer, self).__init__()\n self.readout1 = MLP(2*nhid, NDIM_HIDDEN, nout, n_hidden=2)\n self.readout2 = MLP(nhid, NDIM_HIDDEN, nout, n_hidden=2)\n\n def forward(self, h0, ht):\n return torch.sigmoid(self.readout1(torch.cat([ht, h0], dim=-1)))*self.readout2(ht)\n" ]
[ [ "torch.cat", "torch.nn.Sigmoid" ] ]
dice-group/LearnALCLengths
[ "cb019ba234092a323f3785517d1cc6152a5ef7a4" ]
[ "Method/concept_length_predictors/models.py" ]
[ "import torch, torch.nn as nn, numpy as np\nfrom sklearn.metrics import accuracy_score, f1_score\nimport random\n\ntorch.backends.cudnn.deterministic = True\nseed = 1\ntorch.manual_seed(seed)\n\ndef RM(Ytest, max_len, probs): #Random model\n \"\"\"Random length predictor\n \"\"\"\n np.random.seed(1)\n Pred = []\n for y in range(len(Ytest)):\n pred = np.random.choice(range(1, max_len+1), p=probs)\n Pred.append(pred)\n F1 = f1_score(Pred, Ytest, average='macro')\n Acc = accuracy_score(Pred, Ytest)\n print(\"Accuracy: {}, F1 score: {}\".format(Acc, F1))\n\nclass LengthLearner_LSTM(nn.Module):\n \n def __init__(self, kwargs):\n super().__init__()\n self.name = 'LSTM'\n self.as_classification = kwargs['as_classification']\n self.lstm = nn.LSTM(kwargs['input_size'], kwargs['rnn_hidden'], kwargs['rnn_n_layers'], \n dropout=kwargs['dropout_prob'], batch_first=True)\n self.bn = nn.BatchNorm1d(kwargs['linear_hidden'])\n self.dropout = nn.Dropout(kwargs['dropout_prob'])\n self.fc1 = nn.Linear(kwargs['rnn_hidden'], kwargs['linear_hidden']) \n self.fc2 = nn.Linear(kwargs['linear_hidden'], kwargs['out_size']) \n \n def forward(self, x):\n ''' Forward pass through the network. \n These inputs are x, and the hidden/cell state `hidden`. '''\n \n x, _ = self.lstm(x)\n x = x.sum(1).contiguous().view(x.shape[0], -1)\n x = self.fc1(x)\n x = torch.selu(x)\n x = self.bn(x)\n x = self.dropout(x)\n x = self.fc2(x)\n if self.as_classification:\n x = torch.sigmoid(x)\n else:\n x = torch.selu(x)\n return x\n\nclass LengthLearner_GRU(nn.Module):\n \n def __init__(self, kwargs):\n super().__init__()\n self.name = 'GRU'\n self.as_classification = kwargs['as_classification']\n self.gru = nn.GRU(kwargs['input_size'], kwargs['rnn_hidden'], kwargs['rnn_n_layers'], dropout = kwargs['dropout_prob'], batch_first=True)\n self.bn = nn.BatchNorm1d(kwargs['linear_hidden'])\n self.dropout = nn.Dropout(kwargs['dropout_prob'])\n self.fc1 = nn.Linear(kwargs['rnn_hidden'], kwargs['linear_hidden'])\n self.fc2 = nn.Linear(kwargs['linear_hidden'], kwargs['out_size'])\n\n def forward(self, x):\n x, _ = self.gru(x)\n x = x.sum(1).contiguous().view(x.shape[0], -1)\n x = self.fc1(x)\n x = torch.selu(x)\n x = self.bn(x)\n x = self.dropout(x)\n x = self.fc2(x)\n if self.as_classification:\n x = torch.sigmoid(x)\n else:\n x = torch.selu(x)\n return x\n\nclass LengthLearner_MLP(nn.Module):\n def __init__(self, kwargs):\n super().__init__()\n self.name = 'MLP'\n self.as_classification = kwargs['as_classification']\n linears = []\n random.seed(kwargs['seed'])\n layer_dims = [kwargs['input_size']] + [kwargs['num_units']//random.choice(range(1,10)) for _ in range(kwargs['mlp_n_layers']-1)]+[kwargs['out_size']]\n self.layer_dims = layer_dims\n self.__architecture__()\n for i in range(kwargs['mlp_n_layers']):\n if i == 0:\n linears.extend([nn.Linear(layer_dims[i], layer_dims[i+1]), nn.ReLU()])\n elif i < kwargs['mlp_n_layers']-1 and i%2==0:\n linears.extend([nn.Linear(layer_dims[i], layer_dims[i+1]), nn.ReLU()])\n elif i < kwargs['mlp_n_layers']-1 and i%2==1:\n linears.extend([nn.Linear(layer_dims[i], layer_dims[i+1]), nn.SELU(), nn.BatchNorm1d(layer_dims[i+1]), nn.Dropout(p=kwargs['dropout_prob'])])\n else:\n linears.extend([nn.Linear(layer_dims[i], layer_dims[i+1])])\n self.linears = nn.ModuleList(linears)\n \n def forward(self, x):\n for l in self.linears:\n x = x.view(x.shape[0], -1)\n x = l(x)\n if self.as_classification:\n x = torch.sigmoid(x)\n else:\n x = torch.selu(x)\n return x\n def __architecture__(self):\n print(\"MLP architecture:\")\n print(self.layer_dims)\n\nclass LengthLearner_MLP2(nn.Module):\n def __init__(self, kwargs):\n super().__init__()\n self.name = 'MLP2'\n self.as_classification = kwargs['as_classification']\n linears = []\n random.seed(kwargs['seed'])\n layer_dims = [kwargs['input_size']] + [kwargs['num_units']//random.choice(range(1,10)) for _ in range(kwargs['mlp_n_layers']-1)]+[kwargs['out_size']]\n self.layer_dims = layer_dims\n self.__architecture__()\n for i in range(kwargs['mlp_n_layers']):\n if i == 0:\n linears.extend([nn.Linear(layer_dims[i], layer_dims[i+1]), nn.ReLU()])\n elif i < kwargs['mlp_n_layers']-1 and i%2==0:\n linears.extend([nn.Linear(layer_dims[i], layer_dims[i+1]), nn.ReLU()])\n elif i < kwargs['mlp_n_layers']-1 and i%2==1:\n linears.extend([nn.Linear(layer_dims[i], layer_dims[i+1]), nn.SELU(), nn.Dropout(p=kwargs['dropout_prob'])])\n else:\n linears.extend([nn.Linear(layer_dims[i], layer_dims[i+1])])\n self.linears = nn.ModuleList(linears)\n \n def forward(self, x):\n for l in self.linears:\n x = x.view(x.shape[0], x.shape[1], -1)\n x = l(x)\n if self.as_classification:\n x = torch.sigmoid(x.mean(1))\n else:\n x = torch.selu(x.mean(1))\n return x\n \n def __architecture__(self):\n print(\"MLP2 architecture:\")\n print(self.layer_dims)\n \n\nclass LengthLearner_CNN(nn.Module):\n def __init__(self, kwargs):\n super().__init__()\n self.name = 'CNN'\n self.as_classification = kwargs['as_classification']\n self.conv1 = nn.Conv2d(in_channels=1, out_channels=4, kernel_size=(kwargs['kernel_h'],kwargs['kernel_w']), stride=(kwargs['stride_h'],kwargs['stride_w']), padding=(0,0))\n self.conv2 = nn.Conv2d(in_channels=4, out_channels=8, kernel_size=(kwargs['kernel_h']+1,kwargs['kernel_w']), stride=(kwargs['stride_h']+2,kwargs['stride_w']+1), padding=(0,0))\n self.dropout1d = nn.Dropout(kwargs['dropout_prob'])\n self.dropout2d = nn.Dropout2d(kwargs['dropout_prob'])\n self.bn = nn.BatchNorm1d(kwargs['conv_out']//5)\n self.fc1 = nn.Linear(in_features=kwargs['conv_out'], out_features=kwargs['conv_out']//5)\n self.fc2 = nn.Linear(kwargs['conv_out']//5, kwargs['out_size'])\n \n def forward(self, x):\n x = x.unsqueeze(1)\n x = self.conv1(x)\n x = torch.selu(x)\n x = self.dropout2d(x)\n x = self.conv2(x)\n x = x.view(x.shape[0], -1)\n #print(\"shape\", x.shape)\n x = self.fc1(x)\n x = torch.relu(x)\n x = self.bn(x)\n x = self.dropout1d(x)\n x = self.fc2(x)\n if self.as_classification:\n x = torch.sigmoid(x)\n else:\n x = torch.selu(x)\n return x\n \nclass LengthLearner_Reformer(nn.Module):\n def __init__(self, kwargs):\n super().__init__()\n raise NotImplementedError\n \n \n" ]
[ [ "torch.nn.Linear", "torch.sigmoid", "torch.nn.Dropout", "torch.nn.SELU", "torch.nn.LSTM", "torch.nn.GRU", "torch.nn.ModuleList", "torch.relu", "numpy.random.seed", "sklearn.metrics.accuracy_score", "torch.manual_seed", "torch.nn.ReLU", "torch.nn.Conv2d", "torch.nn.BatchNorm1d", "torch.selu", "sklearn.metrics.f1_score", "torch.nn.Dropout2d" ] ]
xugangwu95/stellargraph
[ "512e60a8f572a4bb432b0397a2b452251e167d8f" ]
[ "stellargraph/layer/graph_attention.py" ]
[ "# -*- coding: utf-8 -*-\n#\n# Copyright 2018-2019 Data61, CSIRO\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\"\"\"\nDefinition of Graph Attention Network (GAT) layer, and GAT class that is a stack of GAT layers\n\"\"\"\n__all__ = [\"GraphAttention\", \"GraphAttentionSparse\", \"GAT\"]\n\nimport warnings\nimport tensorflow as tf\nfrom tensorflow.keras import backend as K\nfrom tensorflow.keras import activations, constraints, initializers, regularizers\nfrom tensorflow.keras.layers import Input, Layer, Dropout, LeakyReLU, Lambda, Reshape\n\nfrom ..mapper import FullBatchNodeGenerator\nfrom .misc import SqueezedSparseConversion\n\n\nclass GraphAttention(Layer):\n \"\"\"\n Graph Attention (GAT) layer. The base implementation is taken from\n https://github.com/danielegrattarola/keras-gat,\n with some modifications added for ease of use.\n\n Based on the original paper: Graph Attention Networks. P. Velickovic et al. ICLR 2018 https://arxiv.org/abs/1710.10903\n\n Notes:\n - The inputs are tensors with a batch dimension of 1:\n Keras requires this batch dimension, and for full-batch methods\n we only have a single \"batch\".\n\n - There are three inputs required, the node features, the output\n indices (the nodes that are to be selected in the final layer)\n and the graph adjacency matrix\n\n - This does not add self loops to the adjacency matrix, you should preprocess\n the adjacency matrix to add self-loops\n\n - The output indices are used when ``final_layer=True`` and the returned outputs\n are the final-layer features for the nodes indexed by output indices.\n\n - If ``final_layer=False`` all the node features are output in the same ordering as\n given by the adjacency matrix.\n\n Args:\n F_out (int): dimensionality of output feature vectors\n attn_heads (int or list of int): number of attention heads\n attn_heads_reduction (str): reduction applied to output features of each attention head, 'concat' or 'average'.\n 'Average' should be applied in the final prediction layer of the model (Eq. 6 of the paper).\n in_dropout_rate (float): dropout rate applied to features\n attn_dropout_rate (float): dropout rate applied to attention coefficients\n activation (str): nonlinear activation applied to layer's output to obtain output features (eq. 4 of the GAT paper)\n final_layer (bool): If False the layer returns output for all nodes,\n if True it returns the subset specified by the indices passed to it.\n use_bias (bool): toggles an optional bias\n saliency_map_support (bool): If calculating saliency maps using the tools in\n stellargraph.utils.saliency_maps this should be True. Otherwise this should be False (default).\n kernel_initializer (str or func): The initialiser to use for the head weights;\n defaults to 'glorot_uniform'.\n kernel_regularizer (str or func): The regulariser to use for the head weights;\n defaults to None.\n kernel_constraint (str or func): The constraint to use for the head weights;\n defaults to None.\n bias_initializer (str or func): The initialiser to use for the head bias;\n defaults to 'zeros'.\n bias_regularizer (str or func): The regulariser to use for the head bias;\n defaults to None.\n bias_constraint (str or func): The constraint to use for the head bias;\n defaults to None.\n attn_kernel_initializer (str or func): The initialiser to use for the attention weights;\n defaults to 'glorot_uniform'.\n attn_kernel_regularizer (str or func): The regulariser to use for the attention weights;\n defaults to None.\n attn_kernel_constraint (str or func): The constraint to use for the attention weights;\n defaults to None.\n \"\"\"\n\n def __init__(\n self,\n units,\n attn_heads=1,\n attn_heads_reduction=\"concat\", # {'concat', 'average'}\n in_dropout_rate=0.0,\n attn_dropout_rate=0.0,\n activation=\"relu\",\n use_bias=True,\n final_layer=False,\n saliency_map_support=False,\n **kwargs,\n ):\n\n if attn_heads_reduction not in {\"concat\", \"average\"}:\n raise ValueError(\n \"{}: Possible heads reduction methods: concat, average; received {}\".format(\n type(self).__name__, attn_heads_reduction\n )\n )\n\n self.units = units # Number of output features (F' in the paper)\n self.attn_heads = attn_heads # Number of attention heads (K in the paper)\n self.attn_heads_reduction = attn_heads_reduction # Eq. 5 and 6 in the paper\n self.in_dropout_rate = in_dropout_rate # dropout rate for node features\n self.attn_dropout_rate = attn_dropout_rate # dropout rate for attention coefs\n self.activation = activations.get(activation) # Eq. 4 in the paper\n self.use_bias = use_bias\n self.final_layer = final_layer\n\n self.saliency_map_support = saliency_map_support\n # Populated by build()\n self.kernels = [] # Layer kernels for attention heads\n self.biases = [] # Layer biases for attention heads\n self.attn_kernels = [] # Attention kernels for attention heads\n\n if attn_heads_reduction == \"concat\":\n # Output will have shape (..., K * F')\n self.output_dim = self.units * self.attn_heads\n else:\n # Output will have shape (..., F')\n self.output_dim = self.units\n\n self._get_regularisers_from_keywords(kwargs)\n\n super().__init__(**kwargs)\n\n def _get_regularisers_from_keywords(self, kwargs):\n self.kernel_initializer = initializers.get(\n kwargs.pop(\"kernel_initializer\", \"glorot_uniform\")\n )\n self.kernel_regularizer = regularizers.get(\n kwargs.pop(\"kernel_regularizer\", None)\n )\n self.kernel_constraint = constraints.get(kwargs.pop(\"kernel_constraint\", None))\n\n self.bias_initializer = initializers.get(\n kwargs.pop(\"bias_initializer\", \"zeros\")\n )\n self.bias_regularizer = regularizers.get(kwargs.pop(\"bias_regularizer\", None))\n self.bias_constraint = constraints.get(kwargs.pop(\"bias_constraint\", None))\n\n self.attn_kernel_initializer = initializers.get(\n kwargs.pop(\"attn_kernel_initializer\", \"glorot_uniform\")\n )\n self.attn_kernel_regularizer = regularizers.get(\n kwargs.pop(\"attn_kernel_regularizer\", None)\n )\n self.attn_kernel_constraint = constraints.get(\n kwargs.pop(\"attn_kernel_constraint\", None)\n )\n\n def get_config(self):\n \"\"\"\n Gets class configuration for Keras serialization\n\n \"\"\"\n config = {\n \"units\": self.units,\n \"attn_heads\": self.attn_heads,\n \"attn_heads_reduction\": self.attn_heads_reduction,\n \"in_dropout_rate\": self.in_dropout_rate,\n \"attn_dropout_rate\": self.attn_dropout_rate,\n \"activation\": activations.serialize(self.activation),\n \"use_bias\": self.use_bias,\n \"final_layer\": self.final_layer,\n \"saliency_map_support\": self.saliency_map_support,\n \"kernel_initializer\": initializers.serialize(self.kernel_initializer),\n \"kernel_regularizer\": regularizers.serialize(self.kernel_regularizer),\n \"kernel_constraint\": constraints.serialize(self.kernel_constraint),\n \"bias_initializer\": initializers.serialize(self.bias_initializer),\n \"bias_regularizer\": regularizers.serialize(self.bias_regularizer),\n \"bias_constraint\": constraints.serialize(self.bias_constraint),\n \"attn_kernel_initializer\": initializers.serialize(\n self.attn_kernel_initializer\n ),\n \"attn_kernel_regularizer\": regularizers.serialize(\n self.attn_kernel_regularizer\n ),\n \"attn_kernel_constraint\": constraints.serialize(\n self.attn_kernel_constraint\n ),\n }\n base_config = super().get_config()\n return {**base_config, **config}\n\n def compute_output_shape(self, input_shapes):\n \"\"\"\n Computes the output shape of the layer.\n Assumes the following inputs:\n\n Args:\n input_shapes (tuple of ints)\n Shape tuples can include None for free dimensions, instead of an integer.\n\n Returns:\n An input shape tuple.\n \"\"\"\n feature_shape, out_shape, *As_shapes = input_shapes\n\n batch_dim = feature_shape[0]\n if self.final_layer:\n out_dim = out_shape[1]\n else:\n out_dim = feature_shape[1]\n\n return batch_dim, out_dim, self.output_dim\n\n def build(self, input_shapes):\n \"\"\"\n Builds the layer\n\n Args:\n input_shapes (list of int): shapes of the layer's inputs (node features and adjacency matrix)\n\n \"\"\"\n feat_shape = input_shapes[0]\n input_dim = int(feat_shape[-1])\n\n # Variables to support integrated gradients\n self.delta = self.add_weight(\n name=\"ig_delta\", shape=(), trainable=False, initializer=initializers.ones()\n )\n self.non_exist_edge = self.add_weight(\n name=\"ig_non_exist_edge\",\n shape=(),\n trainable=False,\n initializer=initializers.zeros(),\n )\n\n # Initialize weights for each attention head\n for head in range(self.attn_heads):\n # Layer kernel\n kernel = self.add_weight(\n shape=(input_dim, self.units),\n initializer=self.kernel_initializer,\n regularizer=self.kernel_regularizer,\n constraint=self.kernel_constraint,\n name=\"kernel_{}\".format(head),\n )\n self.kernels.append(kernel)\n\n # # Layer bias\n if self.use_bias:\n bias = self.add_weight(\n shape=(self.units,),\n initializer=self.bias_initializer,\n regularizer=self.bias_regularizer,\n constraint=self.bias_constraint,\n name=\"bias_{}\".format(head),\n )\n self.biases.append(bias)\n\n # Attention kernels\n attn_kernel_self = self.add_weight(\n shape=(self.units, 1),\n initializer=self.attn_kernel_initializer,\n regularizer=self.attn_kernel_regularizer,\n constraint=self.attn_kernel_constraint,\n name=\"attn_kernel_self_{}\".format(head),\n )\n attn_kernel_neighs = self.add_weight(\n shape=(self.units, 1),\n initializer=self.attn_kernel_initializer,\n regularizer=self.attn_kernel_regularizer,\n constraint=self.attn_kernel_constraint,\n name=\"attn_kernel_neigh_{}\".format(head),\n )\n self.attn_kernels.append([attn_kernel_self, attn_kernel_neighs])\n self.built = True\n\n def call(self, inputs):\n \"\"\"\n Creates the layer as a Keras graph.\n\n Note that the inputs are tensors with a batch dimension of 1:\n Keras requires this batch dimension, and for full-batch methods\n we only have a single \"batch\".\n\n There are three inputs required, the node features, the output\n indices (the nodes that are to be selected in the final layer)\n and the graph adjacency matrix\n\n Notes:\n This does not add self loops to the adjacency matrix.\n The output indices are only used when ``final_layer=True``\n\n Args:\n inputs (list): list of inputs with 3 items:\n node features (size 1 x N x F),\n output indices (size 1 x M),\n graph adjacency matrix (size N x N),\n where N is the number of nodes in the graph,\n F is the dimensionality of node features\n M is the number of output nodes\n \"\"\"\n X = inputs[0] # Node features (1 x N x F)\n out_indices = inputs[1] # output indices (1 x K)\n A = inputs[2] # Adjacency matrix (N x N)\n N = K.int_shape(A)[-1]\n\n batch_dim, n_nodes, _ = K.int_shape(X)\n if batch_dim != 1:\n raise ValueError(\n \"Currently full-batch methods only support a batch dimension of one\"\n )\n\n else:\n # Remove singleton batch dimension\n X = K.squeeze(X, 0)\n out_indices = K.squeeze(out_indices, 0)\n\n outputs = []\n for head in range(self.attn_heads):\n kernel = self.kernels[head] # W in the paper (F x F')\n attention_kernel = self.attn_kernels[\n head\n ] # Attention kernel a in the paper (2F' x 1)\n\n # Compute inputs to attention network\n features = K.dot(X, kernel) # (N x F')\n\n # Compute feature combinations\n # Note: [[a_1], [a_2]]^T [[Wh_i], [Wh_2]] = [a_1]^T [Wh_i] + [a_2]^T [Wh_j]\n attn_for_self = K.dot(\n features, attention_kernel[0]\n ) # (N x 1), [a_1]^T [Wh_i]\n attn_for_neighs = K.dot(\n features, attention_kernel[1]\n ) # (N x 1), [a_2]^T [Wh_j]\n\n # Attention head a(Wh_i, Wh_j) = a^T [[Wh_i], [Wh_j]]\n dense = attn_for_self + K.transpose(\n attn_for_neighs\n ) # (N x N) via broadcasting\n\n # Add nonlinearity\n dense = LeakyReLU(alpha=0.2)(dense)\n\n # Mask values before activation (Vaswani et al., 2017)\n # YT: this only works for 'binary' A, not for 'weighted' A!\n # YT: if A does not have self-loops, the node itself will be masked, so A should have self-loops\n # YT: this is ensured by setting the diagonal elements of A tensor to 1 above\n if not self.saliency_map_support:\n mask = -10e9 * (1.0 - A)\n self.A = A\n dense += mask\n dense = K.softmax(dense) # (N x N), Eq. 3 of the paper\n\n else:\n # dense = dense - tf.reduce_max(dense)\n # GAT with support for saliency calculations\n W = (self.delta * A) * K.exp(\n dense - K.max(dense, axis=1, keepdims=True)\n ) * (1 - self.non_exist_edge) + self.non_exist_edge * (\n A\n + self.delta * (K.ones(shape=[N, N], dtype=\"float\") - A)\n + K.eye(N)\n ) * K.exp(\n dense - K.max(dense, axis=1, keepdims=True)\n )\n dense = W / K.sum(W, axis=1, keepdims=True)\n\n # Apply dropout to features and attention coefficients\n dropout_feat = Dropout(self.in_dropout_rate)(features) # (N x F')\n dropout_attn = Dropout(self.attn_dropout_rate)(dense) # (N x N)\n\n # Linear combination with neighbors' features [YT: see Eq. 4]\n node_features = K.dot(dropout_attn, dropout_feat) # (N x F')\n\n if self.use_bias:\n node_features = K.bias_add(node_features, self.biases[head])\n\n # Add output of attention head to final output\n outputs.append(node_features)\n\n # Aggregate the heads' output according to the reduction method\n if self.attn_heads_reduction == \"concat\":\n output = K.concatenate(outputs) # (N x KF')\n else:\n output = K.mean(K.stack(outputs), axis=0) # N x F')\n\n # Nonlinear activation function\n output = self.activation(output)\n\n # On the final layer we gather the nodes referenced by the indices\n if self.final_layer:\n output = K.gather(output, out_indices)\n\n # Add batch dimension back if we removed it\n if batch_dim == 1:\n output = K.expand_dims(output, 0)\n\n return output\n\n\nclass GraphAttentionSparse(GraphAttention):\n \"\"\"\n Graph Attention (GAT) layer, base implementation taken from https://github.com/danielegrattarola/keras-gat,\n some modifications added for ease of use.\n\n Based on the original paper: Graph Attention Networks. P. Velickovic et al. ICLR 2018 https://arxiv.org/abs/1710.10903\n\n Notes:\n - The inputs are tensors with a batch dimension of 1:\n Keras requires this batch dimension, and for full-batch methods\n we only have a single \"batch\".\n\n - There are three inputs required, the node features, the output\n indices (the nodes that are to be selected in the final layer),\n and the graph adjacency matrix\n\n - This does not add self loops to the adjacency matrix, you should preprocess\n the adjacency matrix to add self-loops\n\n - The output indices are used when `final_layer=True` and the returned outputs\n are the final-layer features for the nodes indexed by output indices.\n\n - If `final_layer=False` all the node features are output in the same ordering as\n given by the adjacency matrix.\n\n\n Args:\n F_out (int): dimensionality of output feature vectors\n attn_heads (int or list of int): number of attention heads\n attn_heads_reduction (str): reduction applied to output features of each attention head, 'concat' or 'average'.\n 'Average' should be applied in the final prediction layer of the model (Eq. 6 of the paper).\n in_dropout_rate (float): dropout rate applied to features\n attn_dropout_rate (float): dropout rate applied to attention coefficients\n activation (str): nonlinear activation applied to layer's output to obtain output features (eq. 4 of the GAT paper)\n final_layer (bool): If False the layer returns output for all nodes,\n if True it returns the subset specified by the indices passed to it.\n use_bias (bool): toggles an optional bias\n saliency_map_support (bool): If calculating saliency maps using the tools in\n stellargraph.utils.saliency_maps this should be True. Otherwise this should be False (default).\n kernel_initializer (str or func): The initialiser to use for the head weights;\n defaults to 'glorot_uniform'.\n kernel_regularizer (str or func): The regulariser to use for the head weights;\n defaults to None.\n kernel_constraint (str or func): The constraint to use for the head weights;\n defaults to None.\n bias_initializer (str or func): The initialiser to use for the head bias;\n defaults to 'zeros'.\n bias_regularizer (str or func): The regulariser to use for the head bias;\n defaults to None.\n bias_constraint (str or func): The constraint to use for the head bias;\n defaults to None.\n attn_kernel_initializer (str or func): The initialiser to use for the attention weights;\n defaults to 'glorot_uniform'.\n attn_kernel_regularizer (str or func): The regulariser to use for the attention weights;\n defaults to None.\n attn_kernel_constraint (str or func): The constraint to use for the attention weights;\n defaults to None.\n \"\"\"\n\n def call(self, inputs, **kwargs):\n \"\"\"\n Creates the layer as a Keras graph\n\n Notes:\n This does not add self loops to the adjacency matrix.\n The output indices are only used when `final_layer=True`\n\n Args:\n inputs (list): list of inputs with 4 items:\n node features (size b x N x F),\n output indices (size b x M),\n sparse graph adjacency matrix (size N x N),\n where N is the number of nodes in the graph,\n F is the dimensionality of node features\n M is the number of output nodes\n \"\"\"\n X = inputs[0] # Node features (1 x N x F)\n out_indices = inputs[1] # output indices (1 x K)\n A_sparse = inputs[2] # Adjacency matrix (1 x N x N)\n\n if not isinstance(A_sparse, tf.SparseTensor):\n raise TypeError(\"A is not sparse\")\n\n # Get undirected graph edges (E x 2)\n A_indices = A_sparse.indices\n\n batch_dim, n_nodes, _ = K.int_shape(X)\n if batch_dim != 1:\n raise ValueError(\n \"Currently full-batch methods only support a batch dimension of one\"\n )\n else:\n # Remove singleton batch dimension\n out_indices = K.squeeze(out_indices, 0)\n X = K.squeeze(X, 0)\n\n outputs = []\n for head in range(self.attn_heads):\n kernel = self.kernels[head] # W in the paper (F x F')\n attention_kernel = self.attn_kernels[\n head\n ] # Attention kernel a in the paper (2F' x 1)\n\n # Compute inputs to attention network\n features = K.dot(X, kernel) # (N x F')\n\n # Compute feature combinations\n # Note: [[a_1], [a_2]]^T [[Wh_i], [Wh_j]] = [a_1]^T [Wh_i] + [a_2]^T [Wh_j]\n attn_for_self = K.dot(\n features, attention_kernel[0]\n ) # (N x 1), [a_1]^T [Wh_i]\n attn_for_neighs = K.dot(\n features, attention_kernel[1]\n ) # (N x 1), [a_2]^T [Wh_j]\n\n # Attention head a(Wh_i, Wh_j) = a^T [[Wh_i], [Wh_j]]\n dense = attn_for_self + K.transpose(\n attn_for_neighs\n ) # (N x N) via broadcasting\n\n # Create sparse attention vector (All non-zero values of the matrix)\n sparse_attn_self = tf.gather(\n K.reshape(attn_for_self, [-1]), A_indices[:, 0], axis=0\n )\n sparse_attn_neighs = tf.gather(\n K.reshape(attn_for_neighs, [-1]), A_indices[:, 1], axis=0\n )\n attn_values = sparse_attn_self + sparse_attn_neighs\n\n # Add nonlinearity\n attn_values = LeakyReLU(alpha=0.2)(attn_values)\n\n # Apply dropout to features and attention coefficients\n dropout_feat = Dropout(self.in_dropout_rate)(features) # (N x F')\n dropout_attn = Dropout(self.attn_dropout_rate)(attn_values) # (N x N)\n\n # Convert to sparse matrix\n sparse_attn = tf.sparse.SparseTensor(\n A_indices, values=dropout_attn, dense_shape=[n_nodes, n_nodes]\n )\n\n # Apply softmax to get attention coefficients\n sparse_attn = tf.sparse.softmax(sparse_attn) # (N x N), Eq. 3 of the paper\n\n # Linear combination with neighbors' features [YT: see Eq. 4]\n node_features = tf.sparse.matmul(sparse_attn, dropout_feat) # (N x F')\n\n if self.use_bias:\n node_features = K.bias_add(node_features, self.biases[head])\n\n # Add output of attention head to final output\n outputs.append(node_features)\n\n # Aggregate the heads' output according to the reduction method\n if self.attn_heads_reduction == \"concat\":\n output = K.concatenate(outputs) # (N x KF')\n else:\n output = K.mean(K.stack(outputs), axis=0) # N x F')\n\n output = self.activation(output)\n\n # On the final layer we gather the nodes referenced by the indices\n if self.final_layer:\n output = K.gather(output, out_indices)\n\n # Add batch dimension back if we removed it\n if batch_dim == 1:\n output = K.expand_dims(output, 0)\n return output\n\n\nclass GAT:\n \"\"\"\n A stack of Graph Attention (GAT) layers with aggregation of multiple attention heads,\n Eqs 5-6 of the GAT paper https://arxiv.org/abs/1710.10903\n\n To use this class as a Keras model, the features and pre-processed adjacency matrix\n should be supplied using the :class:`FullBatchNodeGenerator` class.\n\n Examples:\n Creating a GAT node classification model from an existing :class:`StellarGraph` object `G`::\n\n generator = FullBatchNodeGenerator(G, method=\"gat\")\n gat = GAT(\n layer_sizes=[8, 4],\n activations=[\"elu\",\"softmax\"],\n attn_heads=8,\n generator=generator,\n in_dropout=0.5,\n attn_dropout=0.5,\n )\n x_inp, predictions = gat.node_model()\n\n For more details, please see the GAT demo notebook:\n demos/node-classification/gat/gat-cora-node-classification-example.ipynb\n\n Notes:\n - The inputs are tensors with a batch dimension of 1. These are provided by the \\\n :class:`FullBatchNodeGenerator` object.\n\n - This does not add self loops to the adjacency matrix, you should preprocess\n the adjacency matrix to add self-loops, using the ``method='gat'`` argument\n of the :class:`FullBatchNodeGenerator`.\n\n - The nodes provided to the :class:`FullBatchNodeGenerator.flow` method are\n used by the final layer to select the predictions for those nodes in order.\n However, the intermediate layers before the final layer order the nodes\n in the same way as the adjacency matrix.\n\n Args:\n layer_sizes (list of int): list of output sizes of GAT layers in the stack. The length of this list defines\n the number of GraphAttention layers in the stack.\n generator (FullBatchNodeGenerator): an instance of FullBatchNodeGenerator class constructed on the graph of interest\n attn_heads (int or list of int): number of attention heads in GraphAttention layers. The options are:\n\n - a single integer: the passed value of ``attn_heads`` will be applied to all GraphAttention layers in the stack, except the last layer (for which the number of attn_heads will be set to 1).\n - a list of integers: elements of the list define the number of attention heads in the corresponding layers in the stack.\n\n attn_heads_reduction (list of str or None): reductions applied to output features of each attention head,\n for all layers in the stack. Valid entries in the list are {'concat', 'average'}.\n If None is passed, the default reductions are applied: 'concat' reduction to all layers in the stack\n except the final layer, 'average' reduction to the last layer (Eqs. 5-6 of the GAT paper).\n bias (bool): toggles an optional bias in GAT layers\n in_dropout (float): dropout rate applied to input features of each GAT layer\n attn_dropout (float): dropout rate applied to attention maps\n normalize (str or None): normalization applied to the final output features of the GAT layers stack. Default is None.\n activations (list of str): list of activations applied to each layer's output; defaults to ['elu', ..., 'elu'].\n saliency_map_support (bool): If calculating saliency maps using the tools in\n stellargraph.utils.saliency_maps this should be True. Otherwise this should be False (default).\n kernel_regularizer (str or func): The regulariser to use for the head weights;\n defaults to None.\n attn_kernel_regularizer (str or func): The regulariser to use for the attention weights;\n defaults to None.\n \"\"\"\n\n def __init__(\n self,\n layer_sizes,\n generator=None,\n attn_heads=1,\n attn_heads_reduction=None,\n bias=True,\n in_dropout=0.0,\n attn_dropout=0.0,\n normalize=None,\n activations=None,\n saliency_map_support=False,\n **kwargs,\n ):\n self.bias = bias\n self.in_dropout = in_dropout\n self.attn_dropout = attn_dropout\n self.generator = generator\n self.saliency_map_support = saliency_map_support\n # Check layer_sizes (must be list of int):\n # check type:\n if not isinstance(layer_sizes, list):\n raise TypeError(\n \"{}: layer_sizes should be a list of integers; received type {} instead.\".format(\n type(self).__name__, type(layer_sizes).__name__\n )\n )\n # check that values are valid:\n elif not all([isinstance(s, int) and s > 0 for s in layer_sizes]):\n raise ValueError(\n \"{}: all elements in layer_sizes should be positive integers!\".format(\n type(self).__name__\n )\n )\n self.layer_sizes = layer_sizes\n n_layers = len(layer_sizes)\n\n # Check attn_heads (must be int or list of int):\n if isinstance(attn_heads, list):\n # check the length\n if not len(attn_heads) == n_layers:\n raise ValueError(\n \"{}: length of attn_heads list ({}) should match the number of GAT layers ({})\".format(\n type(self).__name__, len(attn_heads), n_layers\n )\n )\n # check that values in the list are valid\n if not all([isinstance(a, int) and a > 0 for a in attn_heads]):\n raise ValueError(\n \"{}: all elements in attn_heads should be positive integers!\".format(\n type(self).__name__\n )\n )\n self.attn_heads = attn_heads # (list of int as passed by the user)\n\n elif isinstance(attn_heads, int):\n self.attn_heads = list()\n for l, _ in enumerate(layer_sizes):\n # number of attention heads for layer l: attn_heads (int) for all but the last layer (for which it's set to 1)\n self.attn_heads.append(attn_heads if l < n_layers - 1 else 1)\n\n else:\n raise TypeError(\n \"{}: attn_heads should be an integer or a list of integers!\".format(\n type(self).__name__\n )\n )\n\n # Check attn_heads_reduction (list of str, or None):\n if attn_heads_reduction is None:\n # set default head reductions, see eqs 5-6 of the GAT paper\n self.attn_heads_reduction = [\"concat\"] * (n_layers - 1) + [\"average\"]\n else:\n # user-specified list of head reductions (valid entries are 'concat' and 'average')\n # check type (must be a list of str):\n if not isinstance(attn_heads_reduction, list):\n raise TypeError(\n \"{}: attn_heads_reduction should be a string; received type {} instead.\".format(\n type(self).__name__, type(attn_heads_reduction).__name__\n )\n )\n\n # check length of attn_heads_reduction list:\n if not len(attn_heads_reduction) == len(layer_sizes):\n raise ValueError(\n \"{}: length of attn_heads_reduction list ({}) should match the number of GAT layers ({})\".format(\n type(self).__name__, len(attn_heads_reduction), n_layers\n )\n )\n\n # check that list elements are valid:\n if all(\n [ahr.lower() in {\"concat\", \"average\"} for ahr in attn_heads_reduction]\n ):\n self.attn_heads_reduction = attn_heads_reduction\n else:\n raise ValueError(\n \"{}: elements of attn_heads_reduction list should be either 'concat' or 'average'!\".format(\n type(self).__name__\n )\n )\n\n # Check activations (list of str):\n # check type:\n if activations is None:\n activations = [\"elu\"] * n_layers\n if not isinstance(activations, list):\n raise TypeError(\n \"{}: activations should be a list of strings; received {} instead\".format(\n type(self).__name__, type(activations)\n )\n )\n # check length:\n if not len(activations) == n_layers:\n raise ValueError(\n \"{}: length of activations list ({}) should match the number of GAT layers ({})\".format(\n type(self).__name__, len(activations), n_layers\n )\n )\n self.activations = activations\n\n # check generator:\n if generator is not None:\n if not isinstance(generator, FullBatchNodeGenerator):\n raise ValueError(\n \"{}: generator must be of type FullBatchNodeGenerator or None; received object of type {} instead\".format(\n type(self).__name__, type(generator).__name__\n )\n )\n\n # Check if the generator is producing a sparse matrix\n self.use_sparse = generator.use_sparse\n\n else:\n self.use_sparse = False\n\n # Set the normalization layer used in the model\n if normalize == \"l2\":\n self._normalization = Lambda(lambda x: K.l2_normalize(x, axis=2))\n\n elif normalize is None or str(normalize).lower() in {\"none\", \"linear\"}:\n self._normalization = Lambda(lambda x: x)\n\n else:\n raise ValueError(\n \"Normalization should be either 'l2' or None (also allowed as 'none'); received '{}'\".format(\n normalize\n )\n )\n\n # Switch between sparse or dense model\n if self.use_sparse:\n self._gat_layer = GraphAttentionSparse\n else:\n self._gat_layer = GraphAttention\n\n # Optional regulariser, etc. for weights and biases\n self._get_regularisers_from_keywords(kwargs)\n\n # Initialize a stack of GAT layers\n self._layers = []\n n_layers = len(self.layer_sizes)\n for ii in range(n_layers):\n # Dropout on input node features before each GAT layer\n self._layers.append(Dropout(self.in_dropout))\n\n # GraphAttention layer\n self._layers.append(\n self._gat_layer(\n units=self.layer_sizes[ii],\n attn_heads=self.attn_heads[ii],\n attn_heads_reduction=self.attn_heads_reduction[ii],\n in_dropout_rate=self.in_dropout,\n attn_dropout_rate=self.attn_dropout,\n activation=self.activations[ii],\n use_bias=self.bias,\n final_layer=ii == (n_layers - 1),\n saliency_map_support=self.saliency_map_support,\n **self._regularisers,\n )\n )\n\n def _get_regularisers_from_keywords(self, kwargs):\n regularisers = {}\n for param_name in [\n \"kernel_initializer\",\n \"kernel_regularizer\",\n \"kernel_constraint\",\n \"bias_initializer\",\n \"bias_regularizer\",\n \"bias_constraint\",\n \"attn_kernel_initializer\",\n \"attn_kernel_regularizer\",\n \"attn_kernel_constraint\",\n ]:\n param_value = kwargs.pop(param_name, None)\n if param_value is not None:\n regularisers[param_name] = param_value\n self._regularisers = regularisers\n\n def __call__(self, inputs):\n \"\"\"\n Apply a stack of GAT layers to the input x_inp\n\n Args:\n x_inp (Tensor): input of the 1st GAT layer in the stack\n\n Returns: Output tensor of the GAT layers stack\n\n \"\"\"\n assert isinstance(inputs, list), \"input must be a list, got {} instead\".format(\n type(inputs)\n )\n x_in, out_indices, *As = inputs\n\n # Currently we require the batch dimension to be one for full-batch methods\n batch_dim, n_nodes, _ = K.int_shape(x_in)\n\n if batch_dim != 1:\n raise ValueError(\n \"Currently full-batch methods only support a batch dimension of one\"\n )\n\n # Convert input indices & values to a sparse matrix\n if self.use_sparse:\n A_indices, A_values = As\n Ainput = [\n SqueezedSparseConversion(shape=(n_nodes, n_nodes))(\n [A_indices, A_values]\n )\n ]\n\n # Otherwise, create dense matrix from input tensor\n else:\n Ainput = [Lambda(lambda A: K.squeeze(A, 0))(A) for A in As]\n\n # TODO: Support multiple matrices?\n if len(Ainput) != 1:\n raise NotImplementedError(\n \"The GAT method currently only accepts a single matrix\"\n )\n\n # Remove singleton batch dimension\n h_layer = x_in\n for layer in self._layers:\n if isinstance(layer, self._gat_layer):\n # For a GAT layer add the matrix and output indices\n # Note that the output indices are only used if `final_layer=True`\n h_layer = layer([h_layer, out_indices] + Ainput)\n\n else:\n # For other (non-graph) layers only supply the input tensor\n h_layer = layer(h_layer)\n\n # print(\"Hlayer:\", h_layer)\n\n return self._normalization(h_layer)\n\n def node_model(self, num_nodes=None, feature_size=None):\n \"\"\"\n Builds a GAT model for node prediction\n\n Returns:\n tuple: `(x_inp, x_out)`, where `x_inp` is a list of two Keras input tensors for the GAT model (containing node features and graph adjacency matrix),\n and `x_out` is a Keras tensor for the GAT model output.\n \"\"\"\n # Create input tensor:\n if self.generator is not None:\n # Placeholder for node features\n N_nodes = self.generator.features.shape[0]\n N_feat = self.generator.features.shape[1]\n\n elif num_nodes is not None and feature_size is not None:\n N_nodes = num_nodes\n N_feat = feature_size\n\n else:\n raise RuntimeError(\n \"node_model: if generator is not provided to object constructor, num_nodes and feature_size must be specified.\"\n )\n\n # Inputs for features & target indices\n x_t = Input(batch_shape=(1, N_nodes, N_feat))\n out_indices_t = Input(batch_shape=(1, None), dtype=\"int32\")\n\n # Create inputs for sparse or dense matrices\n if self.use_sparse:\n # Placeholders for the sparse adjacency matrix\n A_indices_t = Input(batch_shape=(1, None, 2), dtype=\"int64\")\n A_values_t = Input(batch_shape=(1, None))\n A_placeholders = [A_indices_t, A_values_t]\n\n else:\n # Placeholders for the dense adjacency matrix\n A_m = Input(batch_shape=(1, N_nodes, N_nodes))\n A_placeholders = [A_m]\n\n # TODO: Support multiple matrices?\n x_inp = [x_t, out_indices_t] + A_placeholders\n x_out = self(x_inp)\n\n # Flatten output by removing singleton batch dimension\n if x_out.shape[0] == 1:\n self.x_out_flat = Lambda(lambda x: K.squeeze(x, 0))(x_out)\n else:\n self.x_out_flat = x_out\n\n return x_inp, x_out\n\n def link_model(self):\n \"\"\"\n Builds a GAT model for link (node pair) prediction (implementation pending)\n\n \"\"\"\n raise NotImplemented\n\n def default_model(self, flatten_output=True):\n warnings.warn(\n \"The .default_model() method will be deprecated in future versions. \"\n \"Please use .node_model() or .link_model() methods instead.\",\n PendingDeprecationWarning,\n )\n return self.node_model()\n" ]
[ [ "tensorflow.keras.backend.stack", "tensorflow.keras.backend.transpose", "tensorflow.sparse.SparseTensor", "tensorflow.keras.backend.ones", "tensorflow.keras.backend.reshape", "tensorflow.keras.backend.int_shape", "tensorflow.keras.backend.sum", "tensorflow.keras.backend.l2_normalize", "tensorflow.keras.activations.get", "tensorflow.keras.backend.softmax", "tensorflow.keras.regularizers.serialize", "tensorflow.keras.layers.LeakyReLU", "tensorflow.keras.initializers.serialize", "tensorflow.keras.initializers.zeros", "tensorflow.sparse.softmax", "tensorflow.keras.constraints.serialize", "tensorflow.keras.backend.dot", "tensorflow.keras.backend.expand_dims", "tensorflow.keras.backend.eye", "tensorflow.keras.layers.Dropout", "tensorflow.keras.backend.max", "tensorflow.keras.initializers.ones", "tensorflow.keras.backend.squeeze", "tensorflow.keras.layers.Lambda", "tensorflow.keras.layers.Input", "tensorflow.keras.backend.concatenate", "tensorflow.keras.backend.gather", "tensorflow.keras.activations.serialize", "tensorflow.keras.backend.bias_add", "tensorflow.sparse.matmul" ] ]
MDCHAMP/humpday
[ "45e2cea95ae951d991ebc6c1e98314cc8c726f25" ]
[ "humpday/comparison/eloratings.py" ]
[ "import numpy as np\nimport random\nfrom pprint import pprint\nimport traceback\nfrom humpday.objectives.classic import CLASSIC_OBJECTIVES\nfrom humpday.optimizers.alloptimizers import OPTIMIZERS\nfrom humpday.comparison.eloformulas import elo_update\n\nN_DIM_CHOICES = [1, 2, 3, 5, 8]\nN_TRIALS_CHOICES = [130, 210, 340]\n\nOPTIMIZER_F_FACTOR = 1000\nOPTIMIZER_K_FACTOR = 60\nN_PROVISIONAL = 0 # Number of games for which player is considered provisional\nN_ATTEMPTS_WHITE = 3\nN_ATTEMPTS_BLACK = 6\n\n\ndef optimizer_game(white, black, n_dim, n_trials, objective, tol=0.001):\n \"\"\"\n :param white: optimizer\n :param black: optimizer\n :param n_dim:\n :param n_trials:\n :param objective:\n :return: dict\n \"\"\"\n\n game_result = {'n_dim': n_dim, 'n_trials': n_trials, 'objective': objective.__name__, 'white': white,\n 'black': black,\n 'traceback': ['passing', 'passing'], 'best_val': [None, None], 'best_x': [None, None],\n 'feval_count': [None, None],\n 'n_trials_instructed': [None, None], 'passing': [None, None],\n 'completed': False}\n\n # White to play..\n n_white_trials = n_trials\n n_white_attempts = 0\n while True:\n try:\n white_best_val, white_best_x, white_feval_count = white(objective, n_trials=n_white_trials, n_dim=n_dim,\n with_count=True)\n white_passing, white_traceback = white_best_val is not None, 'passing'\n except Exception as e:\n white_traceback = traceback.format_exc()\n white_passing, white_best_x, white_best_val, white_feval_count = False, None, None, None\n if not white_passing or (white_feval_count <= 1.1*n_trials) or (n_white_attempts > N_ATTEMPTS_WHITE):\n break\n else:\n n_white_attempts += 1\n print('Playing white,' + white.__name__ + ' attempt ' + str(\n n_white_attempts + 1) + ' after instruction to use ' + str(n_white_trials) + ' resulted in ' + str(\n white_feval_count) + ' evaluations.')\n n_white_trials = int(0.7 * n_white_trials)\n game_result['best_val'][0] = white_best_val\n game_result['passing'][0] = white_passing\n white_success = white_passing and white_feval_count <= 1.1*n_trials\n if white_passing and n_white_trials > n_trials:\n white_traceback = 'White took ' + str(white_feval_count) + ' function evals when instructed to use ' + str(\n n_white_trials)\n game_result['traceback'][0] = white_traceback\n if white_passing:\n game_result['n_trials_instructed'][0] = n_white_trials\n game_result['feval_count'][0] = white_feval_count\n game_result['best_val'][0] = white_best_val\n game_result['best_x'][0] = white_best_x\n else:\n pass\n\n # Black to play\n if white_success:\n n_black_trials = white_feval_count # <-- Tries to match the number of white actual evaluations\n n_black_attempts = 0\n while True:\n try:\n black_best_val, black_best_x, black_feval_count = black(objective, n_trials=n_black_trials,\n n_dim=n_dim,\n with_count=True)\n black_traceback, black_passing = 'passing', black_best_val is not None\n except Exception as e:\n black_traceback = traceback.format_exc()\n black_passing, black_best_x, black_best_val, black_feval_count = False, None, None, None\n\n if not black_passing or (black_feval_count <= 1.1*white_feval_count) or (\n n_black_attempts > N_ATTEMPTS_BLACK):\n break\n else:\n n_black_attempts += 1\n print('Playing black, ' + black.__name__ + ' attempt ' + str(\n n_black_attempts + 1) + ' after instruction to use ' + str(\n n_black_trials) + ' resulted in ' + str(black_feval_count) + ' evaluations.')\n n_black_trials = int(0.85 * n_black_trials)\n black_success = black_passing and black_feval_count <= 1.1 * white_feval_count\n game_result['n_trials_instructed'][1] = n_black_trials\n game_result['feval_count'][1] = black_feval_count\n game_result['best_val'][1] = black_best_val\n if black_passing and n_black_trials > n_trials:\n black_traceback = 'Black took ' + str(black_feval_count) + ' function evals when instructed to use ' + str(\n n_black_trials)\n game_result['traceback'][1] = black_traceback\n game_result['passing'][1] = black_passing\n if black_passing:\n game_result['best_val'][1] = black_best_val\n game_result['best_x'][1] = black_best_x\n game_result['n_trials_instructed'][1] = n_black_trials\n game_result['feval_count'][1] = black_feval_count\n else:\n print('White failed ')\n pprint(game_result)\n\n # Now that White and Black have both played...\n if white_success and black_success:\n game_result['completed'] = True\n small = tol * (abs(white_best_val) + abs(black_best_val)) # Ties\n points = 1. if white_best_val < black_best_val - small else 0. if black_best_val < white_best_val - small else 0.5\n game_result['points'] = points\n game_result['winner'] = white.__name__.replace('_cube',\n '') if points > 0.75 else black.__name__ if points < 0.25 else 'draw'\n game_result['loser'] = black.__name__.replace('_cube',\n '') if points > 0.75 else white.__name__ if points < 0.25 else 'draw'\n if game_result['winner'] != 'draw':\n print(game_result['winner'] + ' beats ' + game_result['loser'])\n else:\n print(black.__name__ + ' holds ' + white.__name__ + ' to a draw.')\n else:\n game_result['winner'] = 'incomplete'\n game_result['points'] = None\n\n return game_result\n\n\ndef random_optimizer_game(optimizers=None, objectives=None, n_dim_choices: [int] = None,\n n_trials_choices: [int] = None, tol=0.001, announce=False, pattern=None):\n \"\"\"\n pattern: string to match in at least one optimizer name\n \"\"\"\n from pprint import pprint\n if n_dim_choices is None:\n n_dim_choices = N_DIM_CHOICES\n\n if n_trials_choices is None:\n n_trials_choices = N_TRIALS_CHOICES\n\n if objectives is None:\n objectives = CLASSIC_OBJECTIVES\n\n if optimizers is None:\n optimizers = OPTIMIZERS\n\n n_attempts_left = 1000\n found = False\n while n_attempts_left>0 and not found:\n n_attempts_left -= 1\n white, black = np.random.choice(optimizers, size=2, replace=False)\n if pattern is None or (pattern in white.__name__) or (pattern in black.__name__):\n found = True\n\n if not found:\n pprint(optimizers)\n raise ValueError('No optimizer matches '+pattern)\n\n matchup = {'n_dim':random.choice(n_dim_choices),\n 'n_trials':random.choice(n_trials_choices),\n 'white':white,\n 'black':black,\n 'objective': random.choice(objectives),\n 'tol':tol}\n if announce:\n pprint(matchup)\n return optimizer_game(**matchup)\n\n\ndef optimizer_population_elo_update(optimizers, game_result: dict, elo: dict, initial_elo=1600, peg=True):\n \"\"\" Create or update elo ratings for optimizers\n\n optimizers - List of optimizers that were considered\n game_result - Produced by optimizer_game\n elo - Dictionary containing the 'state' of the population (i.e. elo ratings and game counts)\n tol - Objective function ratio that results in a tie being declared\n peg - If True, optuna_random is set to initial rating every time\n\n Chooses random objective function, random dimensions and random number of trials\n Speed is not taken into account\n \"\"\"\n\n if not elo:\n # Initialize game counts and Elo ratings\n elo['name'] = [f.__name__ for f in optimizers]\n elo['count'] = [0 for _ in optimizers]\n elo['rating'] = [initial_elo for _ in optimizers]\n elo['traceback'] = ['not yet run' for _ in optimizers]\n elo['active'] = [True for _ in optimizers]\n\n else:\n # Check for newcomers\n new_names = [f.__name__ for f in optimizers if f.__name__ not in elo['name']]\n for new_name in new_names:\n elo['name'].append(new_name)\n elo['count'].append(0)\n elo['rating'].append(initial_elo)\n elo['traceback'].append('not yet run')\n elo['active'].append(True)\n\n # Who is active?\n optimizer_names = [o.__name__ for o in optimizers]\n elo['active'] = [name_ in optimizer_names for name_ in elo['name']]\n\n # Peg to random sampling?\n if peg:\n elo['rating'] = [initial_elo if 'optuna_random' in name_ else r for r, name_ in zip(elo['rating'], elo['name'])]\n\n # Process results of match\n white_name = game_result['white'].__name__\n black_name = game_result['black'].__name__\n white_ndx = elo['name'].index(white_name)\n black_ndx = elo['name'].index(black_name)\n elo['traceback'][white_ndx] = game_result['traceback'][0]\n elo['traceback'][black_ndx] = game_result['traceback'][1]\n if game_result['completed']:\n elo['count'][white_ndx] += 1\n elo['count'][black_ndx] += 1\n points = game_result['points']\n print('>>>> ' + game_result['winner'])\n white_elo, black_elo = elo['rating'][white_ndx], elo['rating'][black_ndx]\n min_games = min(elo['count'][white_ndx], elo['count'][black_ndx])\n k = OPTIMIZER_K_FACTOR / 2.0 if min_games > 10 else OPTIMIZER_K_FACTOR\n new_white_elo, new_black_elo = elo_update(white_elo=white_elo, black_elo=black_elo, points=points, k=k,\n f=OPTIMIZER_F_FACTOR)\n # Don't allow players with provisional ratings to impact other's.\n if elo['count'][black_ndx] >= N_PROVISIONAL:\n elo['rating'][white_ndx] = new_white_elo\n if elo['count'][white_ndx] > N_PROVISIONAL:\n elo['rating'][black_ndx] = new_black_elo\n else:\n print('>>>> incomplete ')\n\n return elo\n\n\ndef demo_optimizer_elo():\n # Run this to generate Elo ratings that will update for as long as you have the patience.\n elo = {}\n while True:\n game_result = random_optimizer_game(optimizers=OPTIMIZERS, objectives=CLASSIC_OBJECTIVES,\n n_dim_choices=N_DIM_CHOICES, n_trials_choices=N_TRIALS_CHOICES, tol=0.001)\n print(' Game...')\n pprint(game_result)\n\n elo = optimizer_population_elo_update(optimizers=OPTIMIZERS, elo=elo, game_result=game_result)\n if random.choice(list(range(5))) == 1:\n print(' ')\n pprint(sorted(list(zip(elo['rating'], elo['name'])), reverse=True))\n print(' ')\n\n\nif __name__ == '__main__':\n demo_optimizer_elo()\n" ]
[ [ "numpy.random.choice" ] ]
xinbinhuang/featuretools
[ "f93a90bac32aa6ea5d1ca8e808d57473856d8542", "f93a90bac32aa6ea5d1ca8e808d57473856d8542" ]
[ "featuretools/primitives/transform_primitive.py", "featuretools/demo/retail.py" ]
[ "from __future__ import division\n\nimport copy\nimport datetime\nimport functools\nimport os\nfrom builtins import str\n\nimport numpy as np\nimport pandas as pd\n\nfrom .primitive_base import PrimitiveBase\nfrom .utils import inspect_function_args\n\nfrom featuretools.variable_types import (\n Boolean,\n Datetime,\n DatetimeTimeIndex,\n Discrete,\n Id,\n LatLong,\n Numeric,\n Ordinal,\n Text,\n Timedelta,\n Variable\n)\n\ncurrent_path = os.path.dirname(os.path.realpath(__file__))\nFEATURE_DATASETS = os.path.join(os.path.join(current_path, '..'),\n 'feature_datasets')\n\n\nclass TransformPrimitive(PrimitiveBase):\n \"\"\"Feature for entity that is a based off one or more other features\n in that entity.\"\"\"\n rolling_function = False\n\n def __init__(self, *base_features):\n # Any edits made to this method should also be made to the\n # new_class_init method in make_trans_primitive\n self.base_features = [self._check_feature(f) for f in base_features]\n if any(bf.expanding for bf in self.base_features):\n self.expanding = True\n assert len(set([f.entity for f in self.base_features])) == 1, \\\n \"More than one entity for base features\"\n super(TransformPrimitive, self).__init__(self.base_features[0].entity,\n self.base_features)\n\n def generate_name(self):\n name = u\"{}(\".format(self.name.upper())\n name += u\", \".join(f.get_name() for f in self.base_features)\n name += u\")\"\n return name\n\n @property\n def default_value(self):\n return self.base_features[0].default_value\n\n\ndef make_trans_primitive(function, input_types, return_type, name=None,\n description='A custom transform primitive',\n cls_attributes=None, uses_calc_time=False,\n commutative=False):\n '''Returns a new transform primitive class\n\n Args:\n function (function): Function that takes in an array and applies some\n transformation to it, returning an array.\n\n input_types (list[Variable]): Variable types of the inputs.\n\n return_type (Variable): Variable type of return.\n\n name (str): Name of the primitive. If no name is provided, the name\n of `function` will be used.\n\n description (str): Description of primitive.\n\n cls_attributes (dict[str -> anytype]): Custom attributes to be added to\n class. Key is attribute name, value is the attribute value.\n\n uses_calc_time (bool): If True, the cutoff time the feature is being\n calculated at will be passed to the function as the keyword\n argument 'time'.\n\n commutative (bool): If True, will only make one feature per unique set\n of base features.\n\n Example:\n .. ipython :: python\n\n from featuretools.primitives import make_trans_primitive\n from featuretools.variable_types import Variable, Boolean\n\n\n def pd_is_in(array, list_of_outputs=None):\n if list_of_outputs is None:\n list_of_outputs = []\n return pd.Series(array).isin(list_of_outputs)\n\n def isin_generate_name(self):\n return u\"%s.isin(%s)\" % (self.base_features[0].get_name(),\n str(self.kwargs['list_of_outputs']))\n\n IsIn = make_trans_primitive(\n function=pd_is_in,\n input_types=[Variable],\n return_type=Boolean,\n name=\"is_in\",\n description=\"For each value of the base feature, checks \"\n \"whether it is in a list that provided.\",\n cls_attributes={\"generate_name\": isin_generate_name})\n '''\n # dictionary that holds attributes for class\n cls = {\"__doc__\": description}\n if cls_attributes is not None:\n cls.update(cls_attributes)\n\n # creates the new class and set name and types\n name = name or function.__name__\n new_class = type(name, (TransformPrimitive,), cls)\n new_class.name = name\n new_class.input_types = input_types\n new_class.return_type = return_type\n new_class.commutative = commutative\n new_class, default_kwargs = inspect_function_args(new_class,\n function,\n uses_calc_time)\n\n if len(default_kwargs) > 0:\n new_class.default_kwargs = default_kwargs\n\n def new_class_init(self, *args, **kwargs):\n self.kwargs = copy.deepcopy(self.default_kwargs)\n self.base_features = [self._check_feature(f) for f in args]\n if any(bf.expanding for bf in self.base_features):\n self.expanding = True\n assert len(set([f.entity for f in self.base_features])) == 1, \\\n \"More than one entity for base features\"\n self.kwargs.update(kwargs)\n self.partial = functools.partial(function, **self.kwargs)\n super(TransformPrimitive, self).__init__(\n self.base_features[0].entity, self.base_features)\n new_class.__init__ = new_class_init\n new_class.get_function = lambda self: self.partial\n else:\n # creates a lambda function that returns function every time\n new_class.get_function = lambda self, f=function: f\n\n return new_class\n\n\nclass IsNull(TransformPrimitive):\n \"\"\"For each value of base feature, return 'True' if value is null.\"\"\"\n name = \"is_null\"\n input_types = [Variable]\n return_type = Boolean\n\n def get_function(self):\n return lambda array: pd.isnull(pd.Series(array))\n\n\nclass Absolute(TransformPrimitive):\n \"\"\"Absolute value of base feature.\"\"\"\n name = \"absolute\"\n input_types = [Numeric]\n return_type = Numeric\n\n def get_function(self):\n return lambda array: np.absolute(array)\n\n\nclass TimeSincePrevious(TransformPrimitive):\n \"\"\"Compute the time since the previous instance.\"\"\"\n name = \"time_since_previous\"\n input_types = [DatetimeTimeIndex, Id]\n return_type = Numeric\n\n def __init__(self, time_index, group_feature):\n \"\"\"Summary\n\n Args:\n base_feature (PrimitiveBase): Base feature.\n group_feature (None, optional): Variable or feature to group\n rows by before calculating diff.\n\n \"\"\"\n group_feature = self._check_feature(group_feature)\n assert issubclass(group_feature.variable_type, Discrete), \\\n \"group_feature must have a discrete variable_type\"\n self.group_feature = group_feature\n super(TimeSincePrevious, self).__init__(time_index, group_feature)\n\n def generate_name(self):\n return u\"time_since_previous_by_%s\" % self.group_feature.get_name()\n\n def get_function(self):\n def pd_diff(base_array, group_array):\n bf_name = 'base_feature'\n groupby = 'groupby'\n grouped_df = pd.DataFrame.from_dict({bf_name: base_array,\n groupby: group_array})\n grouped_df = grouped_df.groupby(groupby).diff()\n return grouped_df[bf_name].apply(lambda x: x.total_seconds())\n return pd_diff\n\n\nclass DatetimeUnitBasePrimitive(TransformPrimitive):\n \"\"\"Transform Datetime feature into time or calendar units\n (second/day/week/etc)\"\"\"\n name = None\n input_types = [Datetime]\n return_type = Ordinal\n\n def get_function(self):\n return lambda array: pd_time_unit(self.name)(pd.DatetimeIndex(array))\n\n\nclass TimedeltaUnitBasePrimitive(TransformPrimitive):\n \"\"\"Transform Timedelta features into number of time units\n (seconds/days/etc) they encompass.\"\"\"\n name = None\n input_types = [Timedelta]\n return_type = Numeric\n\n def get_function(self):\n return lambda array: pd_time_unit(self.name)(pd.TimedeltaIndex(array))\n\n\nclass Day(DatetimeUnitBasePrimitive):\n \"\"\"Transform a Datetime feature into the day.\"\"\"\n name = \"day\"\n\n\nclass Days(TimedeltaUnitBasePrimitive):\n \"\"\"Transform a Timedelta feature into the number of days.\"\"\"\n name = \"days\"\n\n\nclass Hour(DatetimeUnitBasePrimitive):\n \"\"\"Transform a Datetime feature into the hour.\"\"\"\n name = \"hour\"\n\n\nclass Hours(TimedeltaUnitBasePrimitive):\n \"\"\"Transform a Timedelta feature into the number of hours.\"\"\"\n name = \"hours\"\n\n def get_function(self):\n def pd_hours(array):\n return pd_time_unit(\"seconds\")(pd.TimedeltaIndex(array)) / 3600.\n return pd_hours\n\n\nclass Second(DatetimeUnitBasePrimitive):\n \"\"\"Transform a Datetime feature into the second.\"\"\"\n name = \"second\"\n\n\nclass Seconds(TimedeltaUnitBasePrimitive):\n \"\"\"Transform a Timedelta feature into the number of seconds.\"\"\"\n name = \"seconds\"\n\n\nclass Minute(DatetimeUnitBasePrimitive):\n \"\"\"Transform a Datetime feature into the minute.\"\"\"\n name = \"minute\"\n\n\nclass Minutes(TimedeltaUnitBasePrimitive):\n \"\"\"Transform a Timedelta feature into the number of minutes.\"\"\"\n name = \"minutes\"\n\n def get_function(self):\n def pd_minutes(array):\n return pd_time_unit(\"seconds\")(pd.TimedeltaIndex(array)) / 60\n return pd_minutes\n\n\nclass Week(DatetimeUnitBasePrimitive):\n \"\"\"Transform a Datetime feature into the week.\"\"\"\n name = \"week\"\n\n\nclass Weeks(TimedeltaUnitBasePrimitive):\n \"\"\"Transform a Timedelta feature into the number of weeks.\"\"\"\n name = \"weeks\"\n\n def get_function(self):\n def pd_weeks(array):\n return pd_time_unit(\"days\")(pd.TimedeltaIndex(array)) / 7\n return pd_weeks\n\n\nclass Month(DatetimeUnitBasePrimitive):\n \"\"\"Transform a Datetime feature into the month.\"\"\"\n name = \"month\"\n\n\nclass Months(TimedeltaUnitBasePrimitive):\n \"\"\"Transform a Timedelta feature into the number of months.\"\"\"\n name = \"months\"\n\n def get_function(self):\n def pd_months(array):\n return pd_time_unit(\"days\")(pd.TimedeltaIndex(array)) * (12 / 365)\n return pd_months\n\n\nclass Year(DatetimeUnitBasePrimitive):\n \"\"\"Transform a Datetime feature into the year.\"\"\"\n name = \"year\"\n\n\nclass Years(TimedeltaUnitBasePrimitive):\n \"\"\"Transform a Timedelta feature into the number of years.\"\"\"\n name = \"years\"\n\n def get_function(self):\n def pd_years(array):\n return pd_time_unit(\"days\")(pd.TimedeltaIndex(array)) / 365\n return pd_years\n\n\nclass Weekend(TransformPrimitive):\n \"\"\"Transform Datetime feature into the boolean of Weekend.\"\"\"\n name = \"weekend\"\n input_types = [Datetime]\n return_type = Boolean\n\n def get_function(self):\n return lambda df: pd_time_unit(\"weekday\")(pd.DatetimeIndex(df)) > 4\n\n\nclass Weekday(DatetimeUnitBasePrimitive):\n \"\"\"Transform Datetime feature into the boolean of Weekday.\"\"\"\n name = \"weekday\"\n\n\nclass NumCharacters(TransformPrimitive):\n \"\"\"Return the characters in a given string.\n \"\"\"\n name = 'characters'\n input_types = [Text]\n return_type = Numeric\n\n def get_function(self):\n return lambda array: pd.Series(array).fillna('').str.len()\n\n\nclass NumWords(TransformPrimitive):\n \"\"\"Returns the words in a given string by counting the spaces.\n \"\"\"\n name = 'numwords'\n input_types = [Text]\n return_type = Numeric\n\n def get_function(self):\n def word_counter(array):\n return pd.Series(array).fillna('').str.count(' ') + 1\n return word_counter\n\n\n# class Like(TransformPrimitive):\n# \"\"\"Equivalent to SQL LIKE(%text%)\n# Returns true if text is contained with the string base_feature\n# \"\"\"\n# name = \"like\"\n# input_types = [(Text,), (Categorical,)]\n# return_type = Boolean\n\n# def __init__(self, base_feature, like_statement, case_sensitive=False):\n# self.like_statement = like_statement\n# self.case_sensitive = case_sensitive\n# super(Like, self).__init__(base_feature)\n\n# def get_function(self):\n# def pd_like(df, f):\n# return df[df.columns[0]].str.contains(f.like_statement,\n# case=f.case_sensitive)\n# return pd_like\n\n\n# class TimeSince(TransformPrimitive):\n# \"\"\"\n# For each value of the base feature, compute the timedelta between it and\n# a datetime\n# \"\"\"\n# name = \"time_since\"\n# input_types = [[DatetimeTimeIndex], [Datetime]]\n# return_type = Timedelta\n# uses_calc_time = True\n\n# def get_function(self):\n# def pd_time_since(array, time):\n# if time is None:\n# time = datetime.now()\n# return (time - pd.DatetimeIndex(array)).values\n# return pd_time_since\n\n\ndef pd_time_since(array, time):\n if time is None:\n time = datetime.now()\n return (time - pd.DatetimeIndex(array)).values\n\n\nTimeSince = make_trans_primitive(function=pd_time_since,\n input_types=[[DatetimeTimeIndex], [Datetime]],\n return_type=Timedelta,\n uses_calc_time=True,\n description=\"Calculates time since the cutoff time.\",\n name=\"time_since\")\n\n\nclass DaysSince(TransformPrimitive):\n \"\"\"For each value of the base feature, compute the number of days between it\n and a datetime.\n \"\"\"\n name = \"days_since\"\n input_types = [DatetimeTimeIndex]\n return_type = Numeric\n uses_calc_time = True\n\n def get_function(self):\n def pd_days_since(array, time):\n if time is None:\n time = datetime.now()\n return pd_time_unit('days')(time - pd.DatetimeIndex(array))\n return pd_days_since\n\n\nclass IsIn(TransformPrimitive):\n \"\"\"For each value of the base feature, checks whether it is in a provided list.\n \"\"\"\n name = \"isin\"\n input_types = [Variable]\n return_type = Boolean\n\n def __init__(self, base_feature, list_of_outputs=None):\n self.list_of_outputs = list_of_outputs\n super(IsIn, self).__init__(base_feature)\n\n def get_function(self):\n def pd_is_in(array, list_of_outputs=self.list_of_outputs):\n if list_of_outputs is None:\n list_of_outputs = []\n return pd.Series(array).isin(list_of_outputs)\n return pd_is_in\n\n def generate_name(self):\n return u\"%s.isin(%s)\" % (self.base_features[0].get_name(),\n str(self.list_of_outputs))\n\n\nclass Diff(TransformPrimitive):\n \"\"\"Compute the difference between the value of a base feature and the previous value.\n\n If it is a Datetime feature, compute the difference in seconds.\n \"\"\"\n name = \"diff\"\n input_types = [Numeric, Id]\n return_type = Numeric\n\n def __init__(self, base_feature, group_feature):\n \"\"\"Summary\n\n Args:\n base_feature (PrimitiveBase): Base feature.\n group_feature (PrimitiveBase): Variable or feature to\n group rows by before calculating diff.\n\n \"\"\"\n self.group_feature = self._check_feature(group_feature)\n super(Diff, self).__init__(base_feature, group_feature)\n\n def generate_name(self):\n base_features_str = self.base_features[0].get_name() + u\" by \" + \\\n self.group_feature.get_name()\n return u\"%s(%s)\" % (self.name.upper(), base_features_str)\n\n def get_function(self):\n def pd_diff(base_array, group_array):\n bf_name = 'base_feature'\n groupby = 'groupby'\n grouped_df = pd.DataFrame.from_dict({bf_name: base_array,\n groupby: group_array})\n grouped_df = grouped_df.groupby(groupby).diff()\n try:\n return grouped_df[bf_name]\n except KeyError:\n return pd.Series([np.nan] * len(base_array))\n return pd_diff\n\n\nclass Not(TransformPrimitive):\n \"\"\"For each value of the base feature, negates the boolean value.\n \"\"\"\n name = \"not\"\n input_types = [Boolean]\n return_type = Boolean\n\n def generate_name(self):\n return u\"NOT({})\".format(self.base_features[0].get_name())\n\n def _get_op(self):\n return \"__not__\"\n\n def get_function(self):\n return lambda array: np.logical_not(array)\n\n\nclass Percentile(TransformPrimitive):\n \"\"\"For each value of the base feature, determines the percentile in relation\n to the rest of the feature.\n \"\"\"\n name = 'percentile'\n uses_full_entity = True\n input_types = [Numeric]\n return_type = Numeric\n\n def get_function(self):\n return lambda array: pd.Series(array).rank(pct=True)\n\n\ndef pd_time_unit(time_unit):\n def inner(pd_index):\n return getattr(pd_index, time_unit).values\n return inner\n\n\nclass Latitude(TransformPrimitive):\n \"\"\"Returns the first value of the tuple base feature.\n For use with the LatLong variable type.\n \"\"\"\n name = 'latitude'\n input_types = [LatLong]\n return_type = Numeric\n\n def get_function(self):\n return lambda array: pd.Series([x[0] for x in array])\n\n\nclass Longitude(TransformPrimitive):\n \"\"\"Returns the second value on the tuple base feature.\n For use with the LatLong variable type.\n \"\"\"\n name = 'longitude'\n input_types = [LatLong]\n return_type = Numeric\n\n def get_function(self):\n return lambda array: pd.Series([x[1] for x in array])\n\n\nclass Haversine(TransformPrimitive):\n \"\"\"Calculate the approximate haversine distance in miles between two LatLong variable types.\n \"\"\"\n name = 'haversine'\n input_types = [LatLong, LatLong]\n return_type = Numeric\n commutative = True\n\n def get_function(self):\n def haversine(latlong1, latlong2):\n lat_1s = np.array([x[0] for x in latlong1])\n lon_1s = np.array([x[1] for x in latlong1])\n lat_2s = np.array([x[0] for x in latlong2])\n lon_2s = np.array([x[1] for x in latlong2])\n lon1, lat1, lon2, lat2 = map(\n np.radians, [lon_1s, lat_1s, lon_2s, lat_2s])\n dlon = lon2 - lon1\n dlat = lat2 - lat1\n a = np.sin(dlat / 2.0) ** 2 + np.cos(lat1) * \\\n np.cos(lat2) * np.sin(dlon / 2.0)**2\n mi = 3950 * 2 * np.arcsin(np.sqrt(a))\n return mi\n return haversine\n", "import os\nfrom builtins import str\n\nimport pandas as pd\n\nimport featuretools as ft\nimport featuretools.variable_types as vtypes\nfrom featuretools.config import config as ft_config\n\n\ndef load_retail(id='demo_retail_data', nrows=None, use_cache=True):\n '''\n Returns the retail entityset example.\n\n Args:\n id (str): Id to assign to EntitySet.\n nrows (int): Number of rows to load of item_purchases\n entity. If None, load all.\n\n Examples:\n\n .. ipython::\n :verbatim:\n\n In [1]: import featuretools as ft\n\n In [2]: es = ft.demo.load_retail()\n\n In [3]: es\n Out[3]:\n Entityset: demo_retail_data\n Entities:\n orders (shape = [25900, 3])\n products (shape = [4070, 3])\n customers (shape = [4373, 3])\n order_products (shape = [541909, 6])\n\n Load in subset of data\n\n .. ipython::\n :verbatim:\n\n In [2]: es = ft.demo.load_retail(nrows=1000)\n\n In [3]: es\n Out[3]:\n Entityset: demo_retail_data\n Entities:\n orders (shape = [66, 3])\n products (shape = [590, 3])\n customers (shape = [49, 3])\n order_products (shape = [1000, 6])\n\n '''\n demo_save_path = make_retail_pathname(nrows)\n\n es = ft.EntitySet(id)\n csv_s3 = \"https://s3.amazonaws.com/featurelabs-static/online-retail-logs.csv\"\n\n if not use_cache or not os.path.isfile(demo_save_path):\n\n df = pd.read_csv(csv_s3,\n nrows=nrows,\n parse_dates=[\"order_date\"])\n df.to_csv(demo_save_path, index_label='order_product_id')\n\n df = pd.read_csv(demo_save_path,\n nrows=nrows,\n parse_dates=[\"order_date\"])\n\n es.entity_from_dataframe(\"order_products\",\n dataframe=df,\n index=\"order_product_id\",\n variable_types={'description': vtypes.Text})\n\n es.normalize_entity(new_entity_id=\"products\",\n base_entity_id=\"order_products\",\n index=\"product_id\",\n additional_variables=[\"description\"])\n\n es.normalize_entity(new_entity_id=\"orders\",\n base_entity_id=\"order_products\",\n index=\"order_id\",\n additional_variables=[\n \"customer_id\", \"country\", \"order_date\"],\n make_time_index=\"order_date\")\n\n es.normalize_entity(new_entity_id=\"customers\",\n base_entity_id=\"orders\",\n index=\"customer_id\",\n additional_variables=[\"country\"])\n es.add_last_time_indexes()\n\n return es\n\n\ndef make_retail_pathname(nrows):\n file_name = 'online_retail_logs_' + str(nrows) + '.csv'\n return os.path.join(ft_config['csv_save_location'], file_name)\n" ]
[ [ "numpy.logical_not", "numpy.array", "numpy.sin", "pandas.DatetimeIndex", "numpy.absolute", "pandas.DataFrame.from_dict", "numpy.sqrt", "pandas.Series", "numpy.cos", "pandas.TimedeltaIndex" ], [ "pandas.read_csv" ] ]
wangzehui20/instance-segmentation-farmland
[ "571b1a31cfa4476cdccdfd90aa7fec981eba3695" ]
[ "tools/analysis_tools/get_flops.py" ]
[ "import argparse\n\nimport torch\nfrom mmcv import Config, DictAction\n\nfrom mmdet.models import build_detector\n\ntry:\n from mmcv.cnn import get_model_complexity_info\nexcept ImportError:\n raise ImportError('Please upgrade mmcv to >0.6.2')\n\n\ndef parse_args():\n parser = argparse.ArgumentParser(description='Train a detector')\n parser.add_argument('config', help='train config file path')\n parser.add_argument(\n '--shape',\n type=int,\n nargs='+',\n default=[1024, 1024],\n help='input image size')\n parser.add_argument(\n '--cfg-options',\n nargs='+',\n action=DictAction,\n help='override some settings in the used config, the key-value pair '\n 'in xxx=yyy format will be merged into config file. If the value to '\n 'be overwritten is a list, it should be like key=\"[a,b]\" or key=a,b '\n 'It also allows nested list/tuple values, e.g. key=\"[(a,b),(c,d)]\" '\n 'Note that the quotation marks are necessary and that no white space '\n 'is allowed.')\n args = parser.parse_args()\n return args\n\n\ndef main():\n\n args = parse_args()\n\n if len(args.shape) == 1:\n input_shape = (3, args.shape[0], args.shape[0])\n elif len(args.shape) == 2:\n input_shape = (3, ) + tuple(args.shape)\n else:\n raise ValueError('invalid input shape')\n\n cfg = Config.fromfile(args.config)\n if args.cfg_options is not None:\n cfg.merge_from_dict(args.cfg_options)\n # import modules from string list.\n if cfg.get('custom_imports', None):\n from mmcv.utils import import_modules_from_strings\n import_modules_from_strings(**cfg['custom_imports'])\n\n model = build_detector(\n cfg.model,\n train_cfg=cfg.get('train_cfg'),\n test_cfg=cfg.get('test_cfg'))\n if torch.cuda.is_available():\n model.cuda()\n model.eval()\n\n if hasattr(model, 'forward_dummy'):\n model.forward = model.forward_dummy\n else:\n raise NotImplementedError(\n 'FLOPs counter is currently not currently supported with {}'.\n format(model.__class__.__name__))\n\n flops, params = get_model_complexity_info(model, input_shape)\n split_line = '=' * 30\n print(f'{split_line}\\nInput shape: {input_shape}\\n'\n f'Flops: {flops}\\nParams: {params}\\n{split_line}')\n print('!!!Please be cautious if you use the results in papers. '\n 'You may need to check if all ops are supported and verify that the '\n 'flops computation is correct.')\n\n\nif __name__ == '__main__':\n main()\n" ]
[ [ "torch.cuda.is_available" ] ]
sourav-majumder/qtlab
[ "96b2a127b1df7b45622c90229bd5ef8a4083614e", "96b2a127b1df7b45622c90229bd5ef8a4083614e" ]
[ "scripts/Qubit/Analysis/Fit/temp_Q.py", "scripts/Qubit/Analysis/Two tone/sideband_drive.py" ]
[ "import numpy as np\r\nfrom fitter import *\r\nleft = 130\r\nright = 270\r\n\r\n\r\npath =[r'D:\\data\\20190511\\154729_power_sweep_7.002MoRe_Al_50mk',\r\nr'D:\\data\\20190511\\160529_power_sweep_7.002MoRe_Al_100mk',\r\nr'D:\\data\\20190511\\162138_power_sweep_7.002MoRe_Al_200mk',\r\nr'D:\\data\\20190511\\164423_power_sweep_7.002MoRe_Al_500mk',\r\nr'D:\\data\\20190511\\171153_power_sweep_7.002MoRe_Al_800mk']\r\n\r\nname = '7.002 GHz MoRe-Al'\r\n\r\ntemp = [50,100,200,500,800]\r\n\r\nn = len(path)\r\nki = np.array([9.5284e+05,9.6835e+05,9.7947e+05,1.0056e+06,1.0193e+06])#np.zeros(n)\r\nf0 = np.array([7.0038e+09,7.0038e+09,7.0038e+09,7.0038e+09,7.0038e+09] )#np.zeros(n)\r\nki_err = np.array([2.29e+03,2.59e+03,2.58e+03,2.84e+03,2.72e+03] )#np.zeros(n)\r\nf0_err = np.array([1.17e+03,1.32e+03,1.31e+03,1.41e+03,1.34e+03] )#np.zeros(n)\r\nQ_err = np.zeros(n)\r\n\r\nfor i in range(n):\r\n\t# data_name = path[i]+path[i][16:]+r'.dat'\r\n\t# data = np.loadtxt(data_name, unpack=True)\r\n\t# freq = data[1][left:right]\r\n\t# real = data[2]\r\n\t# imag = data[3]\r\n\t# absol = data[4][left:right]\r\n\t# f = Fitter(custom)\r\n\t# result = f.fit(freq, absol, print_report = True)\r\n\t# f.plot()\r\n\t# ki[i] = result.params['ki'].value\r\n\t# f0[i] = result.params['f0'].value\r\n\t# ki_err[i] = result.params['ki'].stderr\r\n\t# f0_err[i] = result.params['f0'].stderr\r\n\tQ_err[i] = (f0_err[i]/f0[i] + ki_err[i]/ki[i])*(f0[i]/ki[i])\r\n\r\nfig, ax = plt.subplots(nrows=1, ncols=1, sharex=True)\r\n\r\nax.errorbar(temp, (f0/ki)/1e3, fmt='o', yerr = Q_err/1e3 ,capsize=2, elinewidth=1, markeredgewidth=2)\r\nax.set_xlabel(r'$T (mK)$')\r\nax.set_ylabel(r'$Q_{i} (kU)$')\r\nax.set_title(name)\r\nplt.show()\r\n\r\n\r\n# fr.fit(freq, real[-1], print_report = True)\r\n# fr.plot()\r\n# fm.fit(freq, imag[-1], print_report = True)\r\n# fm.plot()\r\n", "import numpy as np\r\nimport matplotlib.pyplot as plt\r\n\r\n\r\ndef volt(dBm):\r\n\treturn np.sqrt(50*1e-3*(10**(dBm/10)))\r\n\r\npath = r'D:\\data\\20190320\\200420_omit_5to6_good'\r\ndata_name = path+path[16:]+r'.dat'\r\n\r\ndata = np.loadtxt(data_name, unpack=True)\r\n\r\n\r\nn = 1\r\n# power= np.array_split(data[0],n)\r\nfreq = data[6]\r\nabsol = data[4]\r\n# print(freq)\r\n\r\n\r\n# print(cavity_freq[0])\r\n# plt.plot(cavity_freq[0])\r\n# plt.show()\r\n# print(len(absol[0]))\r\n# absol=np.delete(absol,[133],1)\r\n# print(len(absol[0]))\r\n\r\nplt.plot((freq-np.ones(len(freq))*4.52142*1e9)/1e6, 20*np.log10(absol))\r\nplt.xlabel('Detuned sideband (MHz)')\r\nplt.ylabel(r'$S_{21}$ dBm')\r\nplt.show()" ]
[ [ "numpy.array", "numpy.zeros" ], [ "matplotlib.pyplot.xlabel", "numpy.loadtxt", "numpy.sqrt", "matplotlib.pyplot.ylabel", "matplotlib.pyplot.show", "numpy.log10" ] ]
CVIR/CoMix
[ "593b5b3ba6e060018e4b55ab288dab71c2ee2e18" ]
[ "dataset.py" ]
[ "import torch\nimport torchvision\nfrom torch.utils.data import Dataset, DataLoader, ConcatDataset\nfrom torchvision import transforms, utils\nfrom pathlib import Path\nimport pandas as pd\nfrom torchvision import datasets\nimport imageio\nimport numpy as np\nfrom PIL import Image\nimport glob\nfrom i3d.pytorch_i3d import InceptionI3d\nimport os\nfrom torch.autograd import Variable\nimport i3d.videotransforms\nimport GPUtil\nimport time\nimport math\nimport pickle\n\n\ndef im2tensor(im, transform=None):\n\tim = Image.fromarray(im) # convert numpy array to PIL image\n\tif transform is not None :\n\t\tim = transform(im)# Create a PyTorch Variable with the transformed image\n\tif not isinstance(im, torch.Tensor) :\n\t\ttran = transforms.ToTensor()\n\t\tim = tran(im)\n\treturn im\n\ndef video_to_tensor(pic):\n \"\"\"Convert a ``numpy.ndarray`` to tensor.\n Converts a numpy.ndarray (T x H x W x C)\n to a torch.FloatTensor of shape (C x T x H x W)\n \n Args:\n pic (numpy.ndarray): Video to be converted to tensor.\n Returns:\n Tensor: Converted video.\n \"\"\"\n return torch.from_numpy(pic.transpose([3,0,1,2]))\n\ndef load_frame(frame_file, resize=False):\n\n data = Image.open(frame_file)\n\n if resize:\n data = data.resize((224, 224), Image.ANTIALIAS)\n\n data = np.array(data)\n data = data.astype(float)\n data = (data * 2 / 255) - 1\n\n assert(data.max()<=1.0)\n assert(data.min()>=-1.0)\n\n return data\n\ndef load_rgb_batch(frames_dir, rgb_files, frame_indices, resize=False):\n if resize:\n batch_data = np.zeros(frame_indices.shape + (224,224,3))\n else:\n batch_data = np.zeros(frame_indices.shape + (256,340,3))\n\n for i in range(frame_indices.shape[0]):\n #print(\"Loading frame : \", os.path.join(frames_dir,rgb_files[frame_indices[i]]))\n batch_data[i,:,:,:] = load_frame(os.path.join(frames_dir, \n rgb_files[frame_indices[i]]), resize)\n return batch_data\n\nclass VideoDataset_EpicKitchens(Dataset):\n\t'''\n Input : \n\t csv_file : Path to file where path to videos is stored - <path>, label\n frequency : Sampling frequency for the i3d.\n num_nodes : Number of graph nodes. Set to 16\n is_test : Test/Train\n\t transform : if specified applies the transform to the frames.\n base_dir : Base directory to the dataset. Please follow the instructions mentioned in the ReadMe\n \n Returns : \n Tensor : [num_nodes, C, 8, H, W] ### num_nodes clips each consisting of 8 consecutive frames: \n label : Label of the video. (Not used for target dataset during training) \n\n\t'''\n\tdef __init__(self, csv_file, frequency = 4, num_nodes = 16, is_test = False, transform = None, base_dir='./data/epic_kitchens'):\n\t\tself.transform = transform\n\t\twith open(csv_file, 'rb') as f:\n\t\t\tdataset_pd = pickle.load(f)\n\t\tself.csv_file = csv_file\n\t\tself.uid = dataset_pd[\"uid\"].to_numpy()\n\t\tself.start_frame = dataset_pd[\"start_frame\"].to_numpy()\n\t\tself.stop_frame = dataset_pd[\"stop_frame\"].to_numpy()\n\t\tself.video_id = dataset_pd[\"video_id\"].to_numpy()\n\t\tself.verb_class = dataset_pd[\"verb_class\"].to_numpy()\n\n\t\tself.min_frames = 72\n\t\tself.frequency = frequency\n\t\tself.chunk_size = 8\n\t\tself.num_nodes = num_nodes\n\t\tself.is_test = is_test\n\t\tif not base_dir.endswith(\"/\"):\n\t\t\tbase_dir += \"/\"\n\t\tself.video_dir = base_dir + \"epic_kitchens_videos/\"\n\t\tif self.csv_file[:-4].endswith(\"train\"):\n\t\t\tself.video_dir += \"train/\"\n\t\telse : \n\t\t\tassert(self.is_test == True)\n\t\t\tself.video_dir += \"test/\"\n\t\t\n\t\tstripped_csv_file = self.csv_file.split(\"/\")[-1]\n\t\tif stripped_csv_file.startswith(\"D1\"):\n\t\t\tself.video_dir += \"D1/\"\n\t\tif stripped_csv_file.startswith(\"D2\"):\n\t\t\tself.video_dir += \"D2/\"\n\t\tif stripped_csv_file.startswith(\"D3\"):\n\t\t\tself.video_dir += \"D3/\"\n\n\tdef __len__(self):\n\t\treturn len(self.uid)\n\n\tdef __getitem__(self, idx) :\n\t\tpath = self.video_dir + self.video_id[idx]\n\t\tlabel = self.verb_class[idx] \n\t\tif not self.is_test:\n\t\t\tbg_path = path.replace(\"epic_kitchens_videos\", \"epic_kitchens_BG\") + \"_\" + str(self.uid[idx])\n\t\t\tbg_rgb_files = [i for i in os.listdir(bg_path)]\n\t\t\tbg_rgb_files.sort()\n\t\t\tbg_frame_indices = np.arange(len(bg_rgb_files))\n\n\t\trgb_files = [i for i in os.listdir(path)]\n\t\trgb_files.sort()\n\t\trgb_files = rgb_files[self.start_frame[idx]:self.stop_frame[idx]]\n\n\t\tframe_indices = np.arange(len(rgb_files))\n\t\tnum_frames = len(rgb_files)\n\t\tif num_frames == 0:\n\t\t\tprint(\"No images found inside the directory : \", path)\n\t\t\traise Exception\n\t\tframes_tensor = load_rgb_batch(path, rgb_files, frame_indices, resize=True)\n\t\tif not self.is_test:\n\t\t\tbg_frames_tensor = load_rgb_batch(bg_path, bg_rgb_files, bg_frame_indices, resize=True)\n\n\t\tif self.transform and not self.is_test : \n\t\t\tframes_tensor = self.transform(frames_tensor)\n\n\t\tframes_tensor = video_to_tensor(frames_tensor) # [C,T,H,W] pytorch tensor\n\t\tif not self.is_test:\n\t\t\tbg_frames_tensor = video_to_tensor(bg_frames_tensor) # [C,T,H,W] pytorch tensor\n\n\t\tif num_frames < self.min_frames :\n\t\t\tframes_tensor = torch.repeat_interleave(frames_tensor, math.ceil(self.min_frames/frames_tensor.shape[1]), dim=1)\n\n\t\tmax_num_feats = frames_tensor.shape[1] // self.frequency - math.ceil(self.chunk_size/self.frequency) # ith feature is [i*frequency, i*frequency + chunk_size]\t\n\t\tallRange = np.arange(max_num_feats)\n\t\tsplitRange = np.array_split(allRange, self.num_nodes)\n\t\ttry: \n\t\t\tif not self.is_test : \n\t\t\t\tfidx = [np.random.choice(a) for a in splitRange]\n\t\t\telse : \n\t\t\t\tfidx = [a[0] for a in splitRange]\n\t\texcept:\n\t\t\tprint(\"Path : \", path)\n\t\t\tprint(\"Split range : \", splitRange)\n\t\t\tprint(\"All range : \", allRange)\n\t\t\traise Exception\n\t\t\t\n\t\tind = [np.arange(start=i*self.frequency, stop=i*self.frequency + self.chunk_size, step=1) for i in fidx]\t\n\t\tframes_tensor_chunks = torch.empty(self.num_nodes, frames_tensor.shape[0], self.chunk_size, frames_tensor.shape[2], frames_tensor.shape[3]) # [16, C, chunk_size, H, W]\t\n\t\tfor chunk_ind, i in zip(ind, range(self.num_nodes)) : \n\t\t\tframes_tensor_chunks[i, :, :, :, :] = frames_tensor[:, chunk_ind, :, :]\n\n\t\tif self.is_test:\n\t\t\tbg_frames_tensor = 'None'\n\n\t\treturn [frames_tensor_chunks, bg_frames_tensor], label # List of tensors, label\n\nclass VideoDataset_Jester(Dataset):\n\t'''\n Input : \n\t csv_file : Path to file where path to videos is stored - <path>, label\n frequency : Sampling frequency for the i3d.\n num_nodes : Number of graph nodes. Set to 16\n is_test : Test/Train\n\t transform : if specified applies the transform to the frames.\n base_dir : Base directory to the dataset. Please follow the instructions mentioned in the ReadMe\n \n Returns : \n Tensor : [num_nodes, C, 8, H, W] ### num_nodes clips each consisting of 8 consecutive frames: \n label : Label of the video. (Not used for target dataset during training) \n\n\t'''\n\tdef __init__(self, csv_file, frequency = 4, num_nodes = 16, is_test = False, transform = None, base_dir='./data/jester'):\n\t\tself.transform = transform\n\t\tself.dataset = pd.read_csv(csv_file, header=None)\n\t\tself.min_frames = 72\n\t\tself.frequency = frequency\n\t\tself.chunk_size = 8\n\t\tself.num_nodes = num_nodes\n\t\tself.is_test = is_test\n\t\tif not base_dir.endswith(\"/\"):\n\t\t\tbase_dir += \"/\"\n\t\tself.bg_dir = base_dir + \"jester_BG/\"\n\t\tself.video_dir = base_dir + \"jester_videos/\"\n\tdef __len__(self):\n\t\treturn len(self.dataset)\n\tdef __getitem__(self, idx) :\n\t\tpath = self.video_dir + str(self.dataset.iloc[idx, 0])\n\t\tlabel = self.dataset.iloc[idx, 1]\n\t\tbg_path = self.bg_dir + '/' + path.split('/')[-1]\n\t\trgb_files = [i for i in os.listdir(path)]\n\t\tbg_rgb_files = [i for i in os.listdir(bg_path)]\n\t\trgb_files.sort()\n\t\tbg_rgb_files.sort()\n\n\t\tframe_indices = np.arange(len(rgb_files))\n\t\tbg_frame_indices = np.arange(len(bg_rgb_files))\n\t\tnum_frames = len(rgb_files)\n\t\tif num_frames == 0:\n\t\t\tprint(\"No images found inside the directory : \", path)\n\t\t\traise Exception\n\t\tframes_tensor = load_rgb_batch(path, rgb_files, frame_indices, resize=True)\n\t\tbg_frames_tensor = load_rgb_batch(bg_path, bg_rgb_files, bg_frame_indices, resize=True)\n\n\t\tif self.transform and not self.is_test : \n\t\t\tframes_tensor = self.transform(frames_tensor)\n\n\t\tframes_tensor = video_to_tensor(frames_tensor) # [C,T,H,W] pytorch tensor\n\t\tbg_frames_tensor = video_to_tensor(bg_frames_tensor) # [C,T,H,W] pytorch tensor\n\n\t\tif num_frames < self.min_frames :\n\t\t\tframes_tensor = torch.repeat_interleave(frames_tensor, math.ceil(self.min_frames/frames_tensor.shape[1]), dim=1)\n\n\t\tmax_num_feats = frames_tensor.shape[1] // self.frequency - math.ceil(self.chunk_size/self.frequency) # ith feature is [i*frequency, i*frequency + chunk_size]\t\n\t\tallRange = np.arange(max_num_feats)\n\t\tsplitRange = np.array_split(allRange, self.num_nodes)\n\t\ttry: \n\t\t\tif not self.is_test : \n\t\t\t\tfidx = [np.random.choice(a) for a in splitRange]\n\t\t\telse : \n\t\t\t\tfidx = [a[0] for a in splitRange]\n\t\texcept:\n\t\t\tprint(\"Path : \", path)\n\t\t\tprint(\"Split range : \", splitRange)\n\t\t\tprint(\"All range : \", allRange)\n\t\t\traise Exception\n\t\t\t\n\t\tind = [np.arange(start=i*self.frequency, stop=i*self.frequency + self.chunk_size, step=1) for i in fidx]\t\n\t\tframes_tensor_chunks = torch.empty(self.num_nodes, frames_tensor.shape[0], self.chunk_size, frames_tensor.shape[2], frames_tensor.shape[3]) # [16, C, chunk_size, H, W]\t\n\t\t#print(\"Final size : \", frames_tensor_chunks.shape)\n\t\tfor chunk_ind, i in zip(ind, range(self.num_nodes)) : \n\t\t\t#print(\"Iteration : \", i, \" Chunk indices : \", chunk_ind, frames_tensor[:,chunk_ind,:,:].shape)\n\t\t\tframes_tensor_chunks[i, :, :, :, :] = frames_tensor[:, chunk_ind, :, :]\n\n\t\treturn [frames_tensor_chunks, bg_frames_tensor], label # List of tensors, label\n\nclass VideoDataset_UCFHMDB(Dataset):\n\t'''\n Input : \n\t csv_file : Path to file where path to videos is stored - <path>, label\n frequency : Sampling frequency for the i3d.\n num_nodes : Number of graph nodes. Set to 16\n is_test : Test/Train\n\t transform : if specified applies the transform to the frames.\n dataset_name : Name of the dataset\n base_dir : Base directory to the dataset. Please follow the instructions mentioned in the ReadMe\n \n Returns : \n Tensor : [num_nodes, C, 8, H, W] ### num_nodes clips each consisting of 8 consecutive frames: \n label : Label of the video. (Not used for target dataset during training) \n\n\t'''\n\tdef __init__(self, csv_file, frequency = 4, num_nodes = 16, is_test = False, transform = None, dataset_name='ucf', base_dir='./data/ucf_hmdb'):\n\t\tself.transform = transform\n\t\tself.dataset = pd.read_csv(csv_file, header=None)\n\t\tself.min_frames = 72\n\t\tself.frequency = frequency\n\t\tself.chunk_size = 8\n\t\tself.num_nodes = num_nodes\n\t\tself.is_test = is_test\n\t\tif not base_dir.endswith(\"/\"):\n\t\t\tbase_dir += \"/\"\n\t\tself.bg_dir = base_dir + str(dataset_name) + \"_BG/\"\n\t\tself.video_dir = base_dir + str(dataset_name) + \"_videos/\" \n\tdef __len__(self):\n\t\treturn len(self.dataset)\n\tdef __getitem__(self, idx) :\n\t\tpath = self.video_dir + self.dataset.iloc[idx, 0]\n\t\tlabel = self.dataset.iloc[idx, 1]\n\t\tbg_path = self.bg_dir + path.split('/')[-1]\n\t\trgb_files = [i for i in os.listdir(path)]\n\t\tbg_rgb_files = [i for i in os.listdir(bg_path)]\n\n\t\trgb_files.sort()\n\t\tbg_rgb_files.sort()\n\n\t\tframe_indices = np.arange(len(rgb_files))\n\t\tbg_frame_indices = np.arange(len(bg_rgb_files))\n\t\tnum_frames = len(rgb_files)\n\t\tif num_frames == 0:\n\t\t\tprint(\"No images found inside the directory : \", path)\n\t\t\traise Exception\n\t\tframes_tensor = load_rgb_batch(path, rgb_files, frame_indices, resize=True)\n\t\tbg_frames_tensor = load_rgb_batch(bg_path, bg_rgb_files, bg_frame_indices, resize=True)\n\n\t\tif self.transform and not self.is_test : \n\t\t\tframes_tensor = self.transform(frames_tensor)\n\n\t\tframes_tensor = video_to_tensor(frames_tensor) # [C,T,H,W] pytorch tensor\n\t\tbg_frames_tensor = video_to_tensor(bg_frames_tensor) # [C,T,H,W] pytorch tensor\n\n\t\tif num_frames < self.min_frames :\n\t\t\tframes_tensor = torch.repeat_interleave(frames_tensor, math.ceil(self.min_frames/frames_tensor.shape[1]), dim=1)\n\n\t\tmax_num_feats = frames_tensor.shape[1] // self.frequency - math.ceil(self.chunk_size/self.frequency) # ith feature is [i*frequency, i*frequency + chunk_size]\t\n\t\tallRange = np.arange(max_num_feats)\n\t\tsplitRange = np.array_split(allRange, self.num_nodes)\n\t\ttry: \n\t\t\tif not self.is_test : \n\t\t\t\tfidx = [np.random.choice(a) for a in splitRange]\n\t\t\telse : \n\t\t\t\tfidx = [a[0] for a in splitRange]\n\t\texcept:\n\t\t\tprint(\"Path : \", path)\n\t\t\tprint(\"Split range : \", splitRange)\n\t\t\tprint(\"All range : \", allRange)\n\t\t\traise Exception\n\t\t\t\n\t\tind = [np.arange(start=i*self.frequency, stop=i*self.frequency + self.chunk_size, step=1) for i in fidx]\t\n\t\tframes_tensor_chunks = torch.empty(self.num_nodes, frames_tensor.shape[0], self.chunk_size, frames_tensor.shape[2], frames_tensor.shape[3]) # [16, C, chunk_size, H, W]\t\n\t\tfor chunk_ind, i in zip(ind, range(self.num_nodes)) : \n\t\t\tframes_tensor_chunks[i, :, :, :, :] = frames_tensor[:, chunk_ind, :, :]\n\n\t\treturn [frames_tensor_chunks, bg_frames_tensor], label # List of tensors, label\n\t\t\n" ]
[ [ "numpy.array", "numpy.random.choice", "numpy.zeros", "numpy.arange", "pandas.read_csv", "torch.empty", "numpy.array_split" ] ]
JUNEeer/Paddle
[ "0ec3a42e9740a5f5066053bb49a923d538eba24a" ]
[ "python/paddle/fluid/tests/unittests/dygraph_to_static/test_ifelse.py" ]
[ "# Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom __future__ import print_function\n\nimport numpy as np\nimport unittest\n\nfrom paddle.fluid.dygraph.jit import declarative\nfrom paddle.fluid.dygraph.dygraph_to_static.program_translator import ProgramTranslator\n\nfrom ifelse_simple_func import *\n\nnp.random.seed(1)\n\nif fluid.is_compiled_with_cuda():\n place = fluid.CUDAPlace(0)\nelse:\n place = fluid.CPUPlace()\n\n\nclass TestDygraphIfElse(unittest.TestCase):\n \"\"\"\n TestCase for the transformation from control flow `if/else`\n dependent on tensor in Dygraph into Static `fluid.layers.cond`.\n \"\"\"\n\n def setUp(self):\n self.x = np.random.random([10, 16]).astype('float32')\n self.dyfunc = dyfunc_with_if_else\n\n def _run_static(self):\n return self._run_dygraph(to_static=True)\n\n def _run_dygraph(self, to_static=False):\n\n with fluid.dygraph.guard(place):\n x_v = fluid.dygraph.to_variable(self.x)\n if to_static:\n ret = declarative(self.dyfunc)(x_v)\n else:\n ret = self.dyfunc(x_v)\n return ret.numpy()\n\n def test_ast_to_func(self):\n self.assertTrue((self._run_dygraph() == self._run_static()).all())\n\n\nclass TestDygraphIfElse2(TestDygraphIfElse):\n def setUp(self):\n self.x = np.random.random([10, 16]).astype('float32')\n self.dyfunc = dyfunc_with_if_else2\n\n\nclass TestDygraphIfElse3(TestDygraphIfElse):\n def setUp(self):\n self.x = np.random.random([10, 16]).astype('float32')\n self.dyfunc = nested_if_else\n\n\nclass TestDygraphIfElse4(TestDygraphIfElse):\n def setUp(self):\n self.x = np.random.random([10, 16]).astype('float32')\n self.dyfunc = nested_if_else_2\n\n\nclass TestDygraphIfElse5(TestDygraphIfElse):\n def setUp(self):\n self.x = np.random.random([10, 16]).astype('float32')\n self.dyfunc = nested_if_else_3\n\n\ndef dyfunc_ifExp_with_while(x):\n y = [x]\n\n def add_fn(x):\n x = x + 1\n return x\n\n def cond(i, ten, y):\n return i < ten\n\n def map_func(func, tensor_list):\n return [func(x) for x in tensor_list]\n\n def body(i, ten, y):\n # It will be converted into `layers.cond` as followed.\n # map_func(lambda x: fluid.layers.cond(i==0, lambda: x, lambda: add_fn(x), y)\n y = map_func(lambda x: x if (i == 0) is not None else add_fn(x), y)\n i += 1\n return [i, ten, y]\n\n i = fluid.layers.fill_constant(shape=[1], dtype='int64', value=0)\n ten = fluid.layers.fill_constant(shape=[1], dtype='int64', value=10)\n i, ten, y = fluid.layers.while_loop(cond, body, [i, ten, y])\n return y[0]\n\n\nclass TestDygraphIfElse6(TestDygraphIfElse):\n def setUp(self):\n self.x = np.random.random([10, 16]).astype('float32')\n self.dyfunc = dyfunc_ifExp_with_while\n\n\ndef dyfunc_ifExp(x):\n y = [x]\n\n def add_fn(x):\n x = x + 1\n return x\n\n def map_func(func, tensor_list):\n return [func(x) for x in tensor_list]\n\n i = fluid.layers.fill_constant(shape=[1], dtype='int64', value=0)\n # It will be converted into `layers.cond` as followed.\n # map_func(lambda x: fluid.layers.cond(i==1, lambda: x, lambda: add_fn(x), y)\n # `if (Tensor) == 1` is supported in dygraph.\n y = map_func(lambda x: x if i == 1 else add_fn(x), y)\n return y[0]\n\n\nclass TestDygraphIfElse7(TestDygraphIfElse):\n def setUp(self):\n self.x = np.random.random([10, 16]).astype('float32')\n self.dyfunc = dyfunc_ifExp\n\n\nclass TestDygraphIfElseWithAndOr(TestDygraphIfElse):\n def setUp(self):\n self.x = np.random.random([10, 16]).astype('float32')\n self.dyfunc = if_with_and_or\n\n\nclass TestDygraphIfElseWithAndOr1(TestDygraphIfElse):\n def setUp(self):\n self.x = np.random.random([10, 16]).astype('float32')\n self.dyfunc = if_with_and_or_1\n\n\nclass TestDygraphIfElseWithAndOr2(TestDygraphIfElse):\n def setUp(self):\n self.x = np.random.random([10, 16]).astype('float32')\n self.dyfunc = if_with_and_or_2\n\n\nclass TestDygraphIfElseWithAndOr3(TestDygraphIfElse):\n def setUp(self):\n self.x = np.random.random([10, 16]).astype('float32')\n self.dyfunc = if_with_and_or_3\n\n\nclass TestDygraphIfElseWithAndOr4(TestDygraphIfElse):\n def setUp(self):\n self.x = np.random.random([10, 16]).astype('float32')\n self.dyfunc = if_with_and_or_4\n\n\nclass TestDygraphIfElseWithClassVar(TestDygraphIfElse):\n def setUp(self):\n self.x = np.random.random([10, 16]).astype('float32')\n self.dyfunc = if_with_class_var\n\n\nclass TestDygraphIfTensor(TestDygraphIfElse):\n def setUp(self):\n self.x = np.random.random([10, 16]).astype('float32')\n self.dyfunc = if_tensor_case\n\n\nclass TestDygraphIfElseNet(unittest.TestCase):\n \"\"\"\n TestCase for the transformation from control flow `if/else`\n dependent on tensor in Dygraph into Static `fluid.layers.cond`.\n \"\"\"\n\n def setUp(self):\n self.x = np.random.random([10, 16]).astype('float32')\n self.Net = NetWithControlFlowIf\n\n def _run_static(self):\n return self._run(to_static=True)\n\n def _run_dygraph(self):\n return self._run(to_static=False)\n\n def _run(self, to_static=False):\n prog_trans = ProgramTranslator()\n prog_trans.enable(to_static)\n\n with fluid.dygraph.guard(place):\n net = self.Net()\n x_v = fluid.dygraph.to_variable(self.x)\n ret = net(x_v)\n return ret.numpy()\n\n def test_ast_to_func(self):\n self.assertTrue((self._run_dygraph() == self._run_static()).all())\n\n\n# Test to call function ahead caller.\ndef relu(x):\n return fluid.layers.relu(x)\n\n\ndef call_external_func(x, label=None):\n if fluid.layers.mean(x) < 0:\n x_v = x - 1\n else:\n x_v = add_fn(x)\n\n x_v = relu(x_v)\n if label is not None:\n loss = loss_fn(x_v, label)\n return loss\n return x_v\n\n\nclass TestAst2FuncWithExternalFunc(TestDygraphIfElse):\n def setUp(self):\n self.x = np.random.random([10, 16]).astype('float32')\n self.dyfunc = call_external_func\n\n\nclass NetWithExternalFunc(fluid.dygraph.Layer):\n @declarative\n def forward(self, x, label=None):\n if fluid.layers.mean(x) < 0:\n x_v = x - 1\n else:\n x_v = add_fn(x)\n\n x_v = softmax(x_v)\n if label is not None:\n loss = loss_fn(x_v, label)\n return loss\n return x_v\n\n\n# Test to call function behind caller.\ndef softmax(x):\n return fluid.layers.softmax(x)\n\n\nclass TestNetWithExternalFunc(TestDygraphIfElseNet):\n def setUp(self):\n self.x = np.random.random([10, 16]).astype('float32')\n self.Net = NetWithExternalFunc\n\n\nif __name__ == '__main__':\n unittest.main()\n" ]
[ [ "numpy.random.seed", "numpy.random.random" ] ]
databyjp/asset_correlation_analysis
[ "c988f4eacf67f1da3991a72e00a59e457623424a" ]
[ "vid1_simple_plots.py" ]
[ "# ========== (c) JP Hwang 3/8/21 ==========\n\nimport logging\nimport pandas as pd\nimport numpy as np\nimport plotly.express as px\n\nlogger = logging.getLogger(__name__)\nroot_logger = logging.getLogger()\nroot_logger.setLevel(logging.INFO)\nsh = logging.StreamHandler()\nformatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')\nsh.setFormatter(formatter)\nroot_logger.addHandler(sh)\n\ndesired_width = 320\npd.set_option('display.max_columns', 20)\npd.set_option('display.width', desired_width)\n\ndf = pd.read_csv(\"data-vid/player_data.csv\")\ndf = df[df[\"height\"].notna()]\ndf[\"ht_inches\"] = df[\"height\"].str.split(\"-\").str[0].apply(lambda x: int(x) * 12) + df[\"height\"].str.split(\"-\").str[1].apply(lambda x: int(x))\n\nfig = px.scatter(df, x=\"weight\", y=\"ht_inches\", template=\"plotly_dark\",\n title=f\"Height vs Weight\",\n height=600, width=700,\n labels={'weight': \"Weight (lbs)\", \"ht_inches\": \"Height (inches)\"})\nfig.show()\n\ncal_rate = 600\nx = list(range(120))\ny = [cal_rate / 60 * i for i in x]\ndf = pd.DataFrame({'Minutes': x, 'Calories': y})\nfig = px.scatter(df, x=\"Minutes\", y=\"Calories\", template=\"plotly_dark\",\n title=f\"Calories burnt vs running time\",\n height=600, width=700)\nfig.show()\n\ndf = pd.read_csv(\"data-vid/auto-mpg.csv\")\nfig = px.scatter(df, x=\"mpg\", y=\"weight\", template=\"plotly_dark\",\n title=f\"Car Fuel Efficiency vs Weight\",\n height=600, width=700,\n labels={'weight': \"Weight (lbs)\", \"mpg\": \"Fuel Efficiency (miles per gallon)\"})\nfig.show()\n\n# Random walk data:\nimport random\nts = list(range(100))\ny1s = list()\ny2s = list()\n\ny1 = 5\ny2 = 5.5\nfor t in ts:\n tmp = random.random() - 0.5 # Correlated variable\n y1 = y1 + tmp\n y1s.append(y1)\n noise = (random.random() - 0.5) * 0.1\n y2 = y2 + (tmp * random.random() + noise)\n y2s.append(y2)\ndf = pd.DataFrame({'Time': ts, 'Variable A': y1s, 'Variable B': y2s})\ndf = df.melt(id_vars=[\"Time\"], value_vars=[\"Variable A\", \"Variable B\"])\nfig = px.line(df, x=\"Time\", y=\"value\", template=\"plotly_dark\", color=\"variable\",\n title=f\"Example - Positive correlation\",\n labels={\"variable\": \"Variable\", \"value\": \"Value\", \"var_a\": \"Variable A\", \"var_b\": \"Variable B\"},\n height=600, width=700)\nfig.show()\n\n\n# Random walk - negative correlation:\nimport random\nts = list(range(100))\ny1s = list()\ny2s = list()\ny1 = 5\ny2 = 5.5\nfor t in ts:\n tmp = random.random() - 0.5 # Correlated variable\n y1 = y1 + tmp\n y1s.append(y1)\n noise = (random.random() - 0.5) * 0.1\n y2 = y2 + (tmp * (random.random() - 1) + noise)\n y2s.append(y2)\ndf = pd.DataFrame({'Time': ts, 'Variable A': y1s, 'Variable B': y2s})\ndf = df.melt(id_vars=[\"Time\"], value_vars=[\"Variable A\", \"Variable B\"])\nfig = px.line(df, x=\"Time\", y=\"value\", template=\"plotly_dark\", color=\"variable\",\n title=f\"Example - Negative correlation\",\n labels={\"variable\": \"Variable\", \"value\": \"Value\", \"var_a\": \"Variable A\", \"var_b\": \"Variable B\"},\n height=600, width=700)\nfig.show()\n\ndf = pd.DataFrame({'Time': ts, 'Variable A': y1s, 'Variable B': y2s})\ndf[\"Average\"] = (df[\"Variable A\"] + df[\"Variable B\"]) / 2\ndf = df.melt(id_vars=[\"Time\"], value_vars=[\"Variable A\", \"Variable B\", \"Average\"])\nfig = px.line(df, x=\"Time\", y=\"value\", template=\"plotly_dark\", color=\"variable\",\n title=f\"Example - Negative correlation\",\n labels={\"variable\": \"Variable\", \"value\": \"Value\", \"var_a\": \"Variable A\", \"var_b\": \"Variable B\"},\n height=600, width=700)\nfig.show()\n\n# ====================\n# Other sample graphs\n# ====================\nts = list(range(100))\ny1s = list()\ny2s = list()\n\ny1 = 5\ny2 = 5.5\nfor t in ts:\n tmp = random.random() - 0.5 # Correlated variable\n y1 = y1 + tmp\n y1s.append(y1)\n noise = (random.random() - 0.5) * 0.1\n y2 = y2 + (tmp * random.random() + noise)\n y2s.append(y2)\ndf = pd.DataFrame({'Time': ts, 'Variable A': y1s, 'Variable B': y2s})\ndf = df.melt(id_vars=[\"Time\"], value_vars=[\"Variable A\", \"Variable B\"])\nfig = px.line(df, x=\"Time\", y=\"value\", template=\"plotly_dark\", color=\"variable\",\n title=f\"Example - Dataset 1\",\n labels={\"variable\": \"Variable\", \"value\": \"Value\", \"var_a\": \"Variable A\", \"var_b\": \"Variable B\"},\n height=400, width=700)\nfig.show()\n\ndf_a = pd.read_json(\"data/AAPL_3m.json\")\ndf_a[\"sym\"] = \"AAPL\"\ndf_m = pd.read_json(\"data/MMM_3m.json\")\ndf_m[\"sym\"] = \"MMM\"\ndf = pd.concat([df_a, df_m])\nfig = px.line(df, x=\"date\", y=\"close\", template=\"plotly_dark\", color=\"sym\",\n title=f\"Example - Dataset 2\",\n labels={\"sym\": \"Symbol\", \"close\": \"Close\"},\n height=400, width=700)\nfig.show()\n" ]
[ [ "pandas.set_option", "pandas.DataFrame", "pandas.read_json", "pandas.concat", "pandas.read_csv" ] ]
STaylorT/Machine-Learning-Linear-Regression
[ "d4afaeea8396c52e0e9661f9488c036c6d67f2b7" ]
[ "multi-linear-regression.py" ]
[ "# Linear Regression Machine Learning Program\n#\n# Sources used:\n# - https://towardsdatascience.com/master-machine-learning-multiple-linear-regression-from-scratch-with-python-ac716a9b78a4\n# Sean Taylor Thomas\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n# from matplotlib import rcParams\n# rcParams['figure.figsize'] = (14,7)\n# rcParams['axes.spines.top'] = False\n# rcParams['axes.spins.right'] = False\n\ndef import_data(filename):\n \"\"\" Take data from txt file\"\"\"\n dataset = list()\n with open(filename) as f:\n lines = f.readlines()\n\n for line in lines:\n dataset.append(line.split())\n\n return dataset\n\n\ndef str_column_to_float(dataset, column):\n \"\"\" Convert string column to float \"\"\"\n for row in dataset:\n row[column] = float(row[column].strip())\n\n\nclass LinearRegression:\n \"\"\" Implementation of linear regression using gradient descent\"\"\"\n def __init__(self, l_rate = 0.7, iterations=1000):\n self.l_rate = l_rate\n self.iterations = iterations\n self.weights = None\n self.bias = None\n self.loss =[]\n\n @staticmethod\n def _mean_squared_error(y, y_hat):\n \"\"\" Evaluating loss at each iteration\n y = array of known values\n y_hat = array of predicted values\n returns float representing error\"\"\"\n error = 0\n for i in range(len(y)):\n error += (y[i] - y_hat[i]) **2\n return error / len(y)\n\n def fit(self, X, y):\n\n self.weights = np.zeros(X.shape[1])\n self.bias = 0\n\n for i in range(self.iterations):\n y_hat = np.dot(X, self.weights) + self.bias\n loss = self._mean_squared_error(y, y_hat)\n self.loss.append(loss)\n\n deriv_w = (1 / X.shape[0]) * (2 * np.dot(X.T, (y_hat - y)))\n deriv_d = (1 / X.shape[0]) * (2 * np.sum(y_hat - y))\n\n self.weights -= self.l_rate * deriv_w\n self.bias -= self.l_rate * deriv_d\n\n def predict(self, X):\n return np.dot(X, self.weights) + self.bias\n\n\nfrom sklearn.datasets import load_diabetes\n\ndata = load_diabetes()\nx = data.data\ny = data.target\n\nfilename = 'housing.data'\nx = import_data(filename)\n\n# put data in x and target (dependent var) data in y\nfor i in range(len(x[0])):\n str_column_to_float(x, i)\ny = list()\nfor row in x:\n y.append(row[-1])\n row.remove(row[-1]) # separate x (independent vars) from y (dependent var)\n\n# put into numpy arrays and normalize data\nx = np.array(x)\ny = np.array(y)\nxnorm = np.linalg.norm(x)\nx = x / xnorm\n\n# split data into training and testing data\nfrom sklearn.model_selection import train_test_split\nx_train, x_test, y_train, t_test = train_test_split(x,y, test_size = .2, random_state = 42)\n\nmodel = LinearRegression()\nmodel.fit(x_train, y_train)\npredictions = model.predict(x_test)\nprint(x_test)\n\nprint(predictions)\nxs = np.arange(len(model.loss))\nys = model.loss\n\n# Plotting our loss over iterations\nplt.plot(xs, ys, lw=3, c='#0033a3')\nplt.title('Loss per iteration(MSE)', size=20)\nplt.xlabel('Iteration', size=14)\nplt.ylabel('Loss', size=14)\nplt.show()\n\n# test over different learning rates\n# losses = {}\n# for lr in [.7,0.5, 0.1, 0.01, 0.001]:\n# model = LinearRegression(l_rate=lr)\n# model.fit(x_train, y_train)\n# losses[f'LR={str(lr)}'] = model.loss\n#\n# xs = np.arange(len(model.loss))\n# plt.plot(xs, losses['LR=0.7'], lw=3, label=f\"LR = 0.7, Final = {losses['LR=0.7'][-1]:.2f}\")\n# plt.plot(xs, losses['LR=0.5'], lw=3, label=f\"LR = 0.5, Final = {losses['LR=0.5'][-1]:.2f}\")\n# plt.plot(xs, losses['LR=0.1'], lw=3, label=f\"LR = 0.1, Final = {losses['LR=0.1'][-1]:.2f}\")\n# plt.plot(xs, losses['LR=0.01'], lw=3, label=f\"LR = 0.01, Final = {losses['LR=0.01'][-1]:.2f}\")\n# plt.plot(xs, losses['LR=0.001'], lw=3, label=f\"LR = 0.001, Final = {losses['LR=0.001'][-1]:.2f}\")\n# plt.title('Loss per iteration (MSE) across l_rates', size=20)\n# plt.xlabel('Iteration', size=14)\n# plt.ylabel('Loss', size=14)\n# plt.legend()\n# plt.show()\n\n# User predictions:\nnum_cols = len(x[0])\nuser_input = input(\"Would you like to provide input for prediction? y/n\")\niter1 = 0\nx1 = list() # user x\nwhile user_input == 'y' and iter1 < num_cols:\n user_x = input(\"Attribute %d : \" % iter1)\n if not(user_x == '' or user_x == \" \" or user_x == \"\\n\"):\n x1.append(float(user_x))\n iter1 += 1\nif (user_input == 'y'):\n x1 = x1 / xnorm\n user_prediction = model.predict(x1)\n print(x1)\n print(\"Prediction : \", user_prediction)\n" ]
[ [ "numpy.array", "numpy.linalg.norm", "numpy.dot", "numpy.zeros", "sklearn.datasets.load_diabetes", "matplotlib.pyplot.xlabel", "numpy.sum", "matplotlib.pyplot.plot", "matplotlib.pyplot.title", "matplotlib.pyplot.ylabel", "sklearn.model_selection.train_test_split", "matplotlib.pyplot.show" ] ]
PedroBernardino/ross
[ "d8b74aa97b0a02108e15c316b8202964b2f7a532" ]
[ "ross/disk_element.py" ]
[ "import os\nfrom pathlib import Path\n\nimport bokeh.palettes as bp\nimport matplotlib.patches as mpatches\nimport numpy as np\nimport toml\nfrom bokeh.models import ColumnDataSource, HoverTool\n\nfrom ross.element import Element\nfrom ross.utils import read_table_file\n\n__all__ = [\"DiskElement\", \"DiskElement6DoF\"]\nbokeh_colors = bp.RdGy[11]\n\n\nclass DiskElement(Element):\n \"\"\"A disk element.\n\n This class will create a disk element from input data of inertia and mass.\n\n Parameters\n ----------\n n: int\n Node in which the disk will be inserted.\n m : float\n Mass of the disk element.\n Id : float\n Diametral moment of inertia.\n Ip : float\n Polar moment of inertia\n tag : str, optional\n A tag to name the element\n Default is None\n color : str, optional\n A color to be used when the element is represented.\n Default is '#b2182b' (Cardinal).\n Examples\n --------\n >>> disk = DiskElement(n=0, m=32, Id=0.2, Ip=0.3)\n >>> disk.Ip\n 0.3\n \"\"\"\n\n def __init__(self, n, m, Id, Ip, tag=None, color=bokeh_colors[9]):\n self.n = int(n)\n self.n_l = n\n self.n_r = n\n\n self.m = m\n self.Id = Id\n self.Ip = Ip\n self.tag = tag\n self.color = color\n self.dof_global_index = None\n\n def __eq__(self, other):\n \"\"\"This function allows disk elements to be compared.\n Parameters\n ----------\n other: object\n The second object to be compared with.\n\n Returns\n -------\n bool\n True if the comparison is true; False otherwise.\n Examples\n --------\n >>> disk1 = disk_example()\n >>> disk2 = disk_example()\n >>> disk1 == disk2\n True\n \"\"\"\n false_number = 0\n for i in self.__dict__:\n try:\n if np.allclose(self.__dict__[i], other.__dict__[i]):\n pass\n else:\n false_number += 1\n\n except TypeError:\n if self.__dict__[i] == other.__dict__[i]:\n pass\n else:\n false_number += 1\n\n if false_number == 0:\n return True\n else:\n return False\n\n def __repr__(self):\n \"\"\"This function returns a string representation of a disk element.\n Parameters\n ----------\n\n Returns\n -------\n A string representation of a disk object.\n Examples\n --------\n >>> disk = disk_example()\n >>> disk # doctest: +ELLIPSIS\n DiskElement(Id=0.17809, Ip=0.32956...\n \"\"\"\n return (\n f\"{self.__class__.__name__}\"\n f\"(Id={self.Id:{0}.{5}}, Ip={self.Ip:{0}.{5}}, \"\n f\"m={self.m:{0}.{5}}, color={self.color!r}, \"\n f\"n={self.n}, tag={self.tag!r})\"\n )\n\n def __hash__(self):\n return hash(self.tag)\n\n def save(self, file_name=os.getcwd()):\n \"\"\"Saves a disk element in a toml format.\n\n It works as an auxiliary function of the save function in the Rotor\n class.\n\n Parameters\n ----------\n file_name: string\n The name of the file the disk element will be saved in.\n\n Returns\n -------\n None\n\n Examples\n --------\n >>> disk = disk_example()\n >>> disk.save()\n \"\"\"\n data = self.get_data(Path(file_name) / \"DiskElement.toml\")\n data[\"DiskElement\"][str(self.n)] = {\n \"n\": self.n,\n \"m\": self.m,\n \"Id\": self.Id,\n \"Ip\": self.Ip,\n \"tag\": self.tag,\n }\n self.dump_data(data, Path(file_name) / \"DiskElement.toml\")\n\n @staticmethod\n def load(file_name=os.getcwd()):\n \"\"\"Loads a list of disk elements saved in a toml format.\n\n Parameters\n ----------\n file_name: str\n The name of the file of the disk element to be loaded.\n\n Returns\n -------\n disk_elements: list\n A list of disk elements.\n\n Examples\n --------\n >>> disk1 = disk_example()\n >>> disk1.save(os.getcwd())\n >>> list_of_disks = DiskElement.load(os.getcwd())\n >>> disk1 == list_of_disks[0]\n True\n \"\"\"\n disk_elements = []\n with open(\"DiskElement.toml\", \"r\") as f:\n disk_elements_dict = toml.load(f)\n for element in disk_elements_dict[\"DiskElement\"]:\n disk_elements.append(\n DiskElement(**disk_elements_dict[\"DiskElement\"][element])\n )\n return disk_elements\n\n def dof_mapping(self):\n \"\"\"Degrees of freedom mapping.\n\n Returns a dictionary with a mapping between degree of freedom and its\n index.\n\n Returns\n -------\n dof_mapping: dict\n A dictionary containing the degrees of freedom and their indexes.\n\n Examples\n --------\n >>> disk = disk_example()\n >>> disk.dof_mapping()\n {'x_0': 0, 'y_0': 1, 'alpha_0': 2, 'beta_0': 3}\n \"\"\"\n return dict(x_0=0, y_0=1, alpha_0=2, beta_0=3)\n\n def M(self):\n \"\"\"Mass matrix.\n\n This method will return the mass matrix for an instance of a disk\n element.\n\n Returns\n -------\n Mass matrix for the disk element.\n\n Examples\n --------\n >>> disk = DiskElement(0, 32.58972765, 0.17808928, 0.32956362)\n >>> disk.M()\n array([[32.58972765, 0. , 0. , 0. ],\n [ 0. , 32.58972765, 0. , 0. ],\n [ 0. , 0. , 0.17808928, 0. ],\n [ 0. , 0. , 0. , 0.17808928]])\n \"\"\"\n m = self.m\n Id = self.Id\n # fmt: off\n M = np.array([[m, 0, 0, 0],\n [0, m, 0, 0],\n [0, 0, Id, 0],\n [0, 0, 0, Id]])\n # fmt: on\n return M\n\n def K(self):\n \"\"\"Stiffness matrix.\n\n This method will return the stiffness matrix for an instance of a disk\n element.\n\n Returns\n -------\n K: np.ndarray\n A matrix of floats containing the values of the stiffness matrix.\n\n Examples\n --------\n >>> disk = disk_example()\n >>> disk.K()\n array([[0., 0., 0., 0.],\n [0., 0., 0., 0.],\n [0., 0., 0., 0.],\n [0., 0., 0., 0.]])\n \"\"\"\n K = np.zeros((4, 4))\n\n return K\n\n def C(self):\n \"\"\"Returns the damping matrix.\n\n Returns\n -------\n C: np.ndarray\n A matrix of floats containing the values of the damping matrix.\n\n Examples\n --------\n >>> disk = disk_example()\n >>> disk.C()\n array([[0., 0., 0., 0.],\n [0., 0., 0., 0.],\n [0., 0., 0., 0.],\n [0., 0., 0., 0.]])\n \"\"\"\n C = np.zeros((4, 4))\n\n return C\n\n def G(self):\n \"\"\"Gyroscopic matrix.\n\n This method will return the gyroscopic matrix for an instance of a disk\n element.\n\n Returns\n -------\n G: np.ndarray\n Gyroscopic matrix for the disk element.\n\n Examples\n --------\n >>> disk = DiskElement(0, 32.58972765, 0.17808928, 0.32956362)\n >>> disk.G()\n array([[ 0. , 0. , 0. , 0. ],\n [ 0. , 0. , 0. , 0. ],\n [ 0. , 0. , 0. , 0.32956362],\n [ 0. , 0. , -0.32956362, 0. ]])\n \"\"\"\n\n Ip = self.Ip\n # fmt: off\n G = np.array([[0, 0, 0, 0],\n [0, 0, 0, 0],\n [0, 0, 0, Ip],\n [0, 0, -Ip, 0]])\n # fmt: on\n return G\n\n def patch(self, position, ax):\n \"\"\"Disk element patch.\n\n Patch that will be used to draw the disk element.\n\n Parameters\n ----------\n ax : matplotlib axes, optional\n Axes in which the plot will be drawn.\n position : float\n Position in which the patch will be drawn.\n\n Returns\n -------\n \"\"\"\n zpos, ypos, step = position\n radius = step / 6\n\n # matplotlib node (x pos), outer diam. (y pos)\n disk_points_u = [\n [zpos, ypos], # upper\n [zpos + step / 6, ypos + 2 * step],\n [zpos - step / 6, ypos + 2 * step],\n [zpos, ypos],\n ]\n disk_points_l = [\n [zpos, -ypos], # lower\n [zpos + step / 6, -ypos - 2 * step],\n [zpos - step / 6, -ypos - 2 * step],\n [zpos, -ypos],\n ]\n\n ax.add_patch(mpatches.Polygon(disk_points_u, facecolor=self.color))\n ax.add_patch(mpatches.Polygon(disk_points_l, facecolor=self.color))\n\n ax.add_patch(\n mpatches.Circle(xy=(zpos, ypos + 2 * step), radius=radius, color=self.color)\n )\n ax.add_patch(\n mpatches.Circle(\n xy=(zpos, -ypos - 2 * step), radius=radius, color=self.color\n )\n )\n\n def bokeh_patch(self, position, bk_ax):\n \"\"\"Disk element patch.\n Patch that will be used to draw the disk element.\n Parameters\n ----------\n bk_ax : bokeh plotting axes, optional\n Axes in which the plot will be drawn.\n position : float\n Position in which the patch will be drawn.\n Returns\n -------\n bk_ax : bokeh plotting axes\n Returns the axes object with the plot.\n \"\"\"\n zpos, ypos, step = position\n\n # bokeh plot - coordinates to plot disks elements\n z_upper = [zpos, zpos + step / 6, zpos - step / 6]\n y_upper = [ypos, ypos + 2 * step, ypos + 2 * step]\n\n z_lower = [zpos, zpos + step / 6, zpos - step / 6]\n y_lower = [-ypos, -ypos - 2 * step, -ypos - 2 * step]\n\n source = ColumnDataSource(\n dict(\n z_l=[z_lower],\n y_l=[y_lower],\n z_u=[z_upper],\n y_u=[y_upper],\n elnum=[self.n],\n IP=[self.Ip],\n ID=[self.Id],\n mass=[self.m],\n tag=[self.tag],\n )\n )\n source_c = ColumnDataSource(\n dict(\n z_circle=[z_upper[0]],\n yu_circle=[y_upper[1]],\n yl_circle=[-y_upper[1]],\n radius=[step / 6],\n elnum=[self.n],\n IP=[self.Ip],\n ID=[self.Id],\n mass=[self.m],\n tag=[self.tag],\n )\n )\n\n bk_ax.patches(\n xs=\"z_u\",\n ys=\"y_u\",\n source=source,\n alpha=1,\n line_width=2,\n color=self.color,\n legend_label=\"Disk\",\n name=\"ub_disk\",\n )\n bk_ax.patches(\n xs=\"z_l\",\n ys=\"y_l\",\n source=source,\n alpha=1,\n line_width=2,\n color=self.color,\n name=\"ub_disk\",\n )\n bk_ax.circle(\n x=\"z_circle\",\n y=\"yu_circle\",\n radius=\"radius\",\n source=source_c,\n fill_alpha=1,\n color=self.color,\n name=\"uc_disk\",\n )\n bk_ax.circle(\n x=\"z_circle\",\n y=\"yl_circle\",\n radius=\"radius\",\n source=source_c,\n fill_alpha=1,\n color=self.color,\n name=\"lc_disk\",\n )\n\n hover = HoverTool(names=[\"uc_disk\", \"lc_disk\", \"ub_disk\", \"lb_disk\"])\n hover.tooltips = [\n (\"Disk Node :\", \"@elnum\"),\n (\"Polar Moment of Inertia :\", \"@IP\"),\n (\"Diametral Moment of Inertia :\", \"@ID\"),\n (\"Disk mass :\", \"@mass\"),\n (\"Tag :\", \"@tag\"),\n ]\n hover.mode = \"mouse\"\n\n return hover\n\n @classmethod\n def from_geometry(cls, n, material, width, i_d, o_d, tag=None):\n \"\"\"A disk element.\n\n This class method will create a disk element from geometry data.\n\n Parameters\n ----------\n n: int\n Node in which the disk will be inserted.\n material: ross.Material\n Shaft material.\n width: float\n The disk width.\n i_d: float\n Inner diameter.\n o_d: float\n Outer diameter.\n\n Attributes\n ----------\n m : float\n Mass of the disk element.\n Id : float\n Diametral moment of inertia.\n Ip : float\n Polar moment of inertia\n tag : str, optional\n A tag to name the element\n Default is None\n\n Examples\n --------\n >>> from ross.materials import steel\n >>> disk = DiskElement.from_geometry(0, steel, 0.07, 0.05, 0.28)\n >>> disk.Ip\n 0.32956362089137037\n \"\"\"\n m = 0.25 * material.rho * np.pi * width * (o_d ** 2 - i_d ** 2)\n # fmt: off\n Id = (\n 0.015625 * material.rho * np.pi * width * (o_d ** 4 - i_d ** 4)\n + m * (width ** 2) / 12\n )\n # fmt: on\n Ip = 0.03125 * material.rho * np.pi * width * (o_d ** 4 - i_d ** 4)\n\n tag = tag\n\n return cls(n, m, Id, Ip, tag)\n\n @classmethod\n def from_table(cls, file, sheet_name=0):\n \"\"\"Instantiate one or more disks using inputs from an Excel table.\n\n A header with the names of the columns is required. These names should\n match the names expected by the routine (usually the names of the\n parameters, but also similar ones). The program will read every row\n bellow the header until they end or it reaches a NaN.\n\n Parameters\n ----------\n file: str\n Path to the file containing the disk parameters.\n sheet_name: int or str, optional\n Position of the sheet in the file (starting from 0) or its name.\n If none is passed, it is assumed to be the first sheet in the file.\n Returns\n -------\n disk : list\n A list of disk objects.\n\n Examples\n --------\n >>> import os\n >>> file_path = os.path.dirname(os.path.realpath(__file__)) + '/tests/data/shaft_si.xls'\n >>> list_of_disks = DiskElement.from_table(file_path, sheet_name=\"More\")\n >>> list_of_disks[0]\n DiskElement(Id=0.0, Ip=0.0, m=15.12, color='#b2182b', n=3, tag=None)\n \"\"\"\n parameters = read_table_file(file, \"disk\", sheet_name=sheet_name)\n list_of_disks = []\n for i in range(0, len(parameters[\"n\"])):\n list_of_disks.append(\n cls(\n n=parameters[\"n\"][i],\n m=parameters[\"m\"][i],\n Id=float(parameters[\"Id\"][i]),\n Ip=float(parameters[\"Ip\"][i]),\n )\n )\n return list_of_disks\n\n\ndef disk_example():\n \"\"\"This function returns an instance of a simple disk.\n The purpose is to make available a simple model\n so that doctest can be written using it.\n\n Parameters\n ----------\n\n Returns\n -------\n An instance of a disk object.\n\n Examples\n --------\n >>> disk = disk_example()\n >>> disk.Ip\n 0.32956362\n \"\"\"\n disk = DiskElement(0, 32.589_727_65, 0.178_089_28, 0.329_563_62)\n return disk\n\n\nclass DiskElement6DoF(DiskElement):\n \"\"\"A disk element for 6 DoFs.\n\n This class will create a disk element with 6 DoF from input data of inertia and mass.\n\n Parameters\n ----------\n n: int\n Node in which the disk will be inserted.\n m : float\n Mass of the disk element.\n Id : float\n Diametral moment of inertia.\n Ip : float\n Polar moment of inertia\n tag : str, optional\n A tag to name the element\n Default is None\n\n Examples\n --------\n >>> disk = DiskElement6DoF(n=0, m=32, Id=0.2, Ip=0.3)\n >>> disk.Ip\n 0.3\n \"\"\"\n\n def dof_mapping(self):\n \"\"\"6DoFs degrees of freedom mapping.\n\n Returns a dictionary with a mapping between degree of freedom and its\n index.\n\n Returns\n -------\n dof_mapping: dict\n A dictionary containing the degrees of freedom and their indexes.\n\n Examples\n --------\n The numbering of the degrees of freedom for each node. \n \n Being the following their ordering for a node:\n\n x_0,u_0 - horizontal translation, \n y_0,v_0 - vertical translation, \n z_0,w_0 - axial translation, \n theta_0 - rotation around horizontal, \n psi_0 - rotation around vertical, \n phi_0 - torsion around axial,\n \"\"\"\n return dict(u_0=0, v_0=1, w_0=2, theta_0=3, psi_0=4, phi_0=5,)\n\n def M(self):\n \"\"\"6DoFs mass matrix.\n\n This method will return the mass matrix for an instance of a disk\n element with 6DoFs.\n\n Returns\n -------\n Mass matrix for the 6DoFs disk element.\n\n Examples\n --------\n >>> disk = DiskElement6DoF(0, 32.58972765, 0.17808928, 0.32956362)\n >>> disk.M().round(2)\n array([[32.59, 0. , 0. , 0. , 0. , 0. ],\n [ 0. , 32.59, 0. , 0. , 0. , 0. ],\n [ 0. , 0. , 32.59, 0. , 0. , 0. ],\n [ 0. , 0. , 0. , 0.18, 0. , 0. ],\n [ 0. , 0. , 0. , 0. , 0.18, 0. ],\n [ 0. , 0. , 0. , 0. , 0. , 0.33]])\n \"\"\"\n m = self.m\n Id = self.Id\n Ip = self.Ip\n # fmt: off\n M = np.array([\n [ m, 0, 0, 0, 0, 0],\n [ 0, m, 0, 0, 0, 0],\n [ 0, 0, m, 0, 0, 0],\n [ 0, 0, 0, Id, 0, 0],\n [ 0, 0, 0, 0, Id, 0],\n [ 0, 0, 0, 0, 0, Ip]])\n # fmt: on\n return M\n\n def K(self):\n \"\"\"6DoFs stiffness matrix.\n\n This method will return the stiffness matrix for an instance of a disk\n element with 6DoFs.\n\n Returns\n -------\n K: np.ndarray\n A matrix of floats containing the values of the stiffness matrix.\n\n Examples\n --------\n >>> disk = disk_example_6dof()\n >>> disk.K().round(2)\n array([[0. , 0. , 0. , 0. , 0. , 0. ],\n [0. , 0. , 0. , 0. , 0. , 0. ],\n [0. , 0. , 0. , 0. , 0. , 0. ],\n [0. , 0. , 0. , 0. , 0. , 0. ],\n [0. , 0. , 0. , 0. , 0. , 0. ],\n [0. , 0. , 0. , 0.33, 0. , 0. ]])\n \"\"\"\n Ip = self.Ip\n # fmt: off\n K = np.array([\n [ 0, 0, 0, 0, 0, 0],\n [ 0, 0, 0, 0, 0, 0],\n [ 0, 0, 0, 0, 0, 0],\n [ 0, 0, 0, 0, 0, 0],\n [ 0, 0, 0, 0, 0, 0],\n [ 0, 0, 0, Ip, 0, 0]])\n # fmt: on\n return K\n\n def C(self):\n \"\"\"6DoFs damping matrix.\n\n Returns\n -------\n C: np.ndarray\n A matrix of floats containing the values of the damping matrix.\n\n Examples\n --------\n >>> disk = disk_example_6dof()\n >>> disk.C()\n array([[0., 0., 0., 0., 0., 0.],\n [0., 0., 0., 0., 0., 0.],\n [0., 0., 0., 0., 0., 0.],\n [0., 0., 0., 0., 0., 0.],\n [0., 0., 0., 0., 0., 0.],\n [0., 0., 0., 0., 0., 0.]])\n \"\"\"\n # fmt: off\n C = np.zeros((6, 6))\n # fmt: on\n return C\n\n def G(self):\n \"\"\"6DoFs gyroscopic matrix.\n\n This method will return the gyroscopic matrix for an instance of a disk\n element.\n\n Returns\n -------\n G: np.ndarray\n Gyroscopic matrix for the disk element.\n\n Examples\n --------\n >>> disk = DiskElement6DoF(0, 32.58972765, 0.17808928, 0.32956362)\n >>> disk.G().round(2)\n array([[ 0. , 0. , 0. , 0. , 0. , 0. ],\n [ 0. , 0. , 0. , 0. , 0. , 0. ],\n [ 0. , 0. , 0. , 0. , 0. , 0. ],\n [ 0. , 0. , 0. , 0. , 0.33, 0. ],\n [ 0. , 0. , 0. , -0.33, 0. , 0. ],\n [ 0. , 0. , 0. , 0. , 0. , 0. ]])\n \"\"\"\n Ip = self.Ip\n # fmt: off\n G = np.array([\n [ 0, 0, 0, 0, 0, 0],\n [ 0, 0, 0, 0, 0, 0],\n [ 0, 0, 0, 0, 0, 0],\n [ 0, 0, 0, 0, Ip, 0],\n [ 0, 0, 0, -Ip, 0, 0],\n [ 0, 0, 0, 0, 0, 0]])\n # fmt: on\n return G\n\n\ndef disk_example():\n \"\"\"This function returns an instance of a simple disk.\n The purpose is to make available a simple model\n so that doctest can be written using it.\n\n Parameters\n ----------\n\n Returns\n -------\n An instance of a disk object.\n\n Examples\n --------\n >>> disk = disk_example()\n >>> disk.Ip\n 0.32956362\n \"\"\"\n disk = DiskElement(0, 32.589_727_65, 0.178_089_28, 0.329_563_62)\n return disk\n\n\ndef disk_example_6dof():\n \"\"\"This function returns an instance of a simple disk.\n The purpose is to make available a simple 6DoFs model\n so that doctest can be written using it.\n\n Parameters\n ----------\n\n Returns\n -------\n An instance of a disk object.\n\n Examples\n --------\n >>> disk = disk_example()\n >>> disk.Ip\n 0.32956362\n \"\"\"\n disk = DiskElement6DoF(0, 32.589_727_65, 0.178_089_28, 0.329_563_62)\n return disk\n" ]
[ [ "numpy.array", "numpy.zeros", "matplotlib.patches.Polygon", "numpy.allclose", "matplotlib.patches.Circle" ] ]
jiangwenj02/SOLO
[ "da6b1c82715c189bf33e944c6edda80590b5a867" ]
[ "mmdet/utils/contextmanagers.py" ]
[ "# coding: utf-8\nimport asyncio\nimport contextlib\nimport logging\nimport os\nimport time\nfrom typing import List\n\nimport torch\n\nlogger = logging.getLogger(__name__)\n\nDEBUG_COMPLETED_TIME = bool(os.environ.get('DEBUG_COMPLETED_TIME', False))\n\n\[email protected]\nasync def completed(trace_name='',\n name='',\n sleep_interval=0.05,\n streams: List[torch.cuda.Stream] = None):\n \"\"\"\n Async context manager that waits for work to complete on\n given CUDA streams.\n\n \"\"\"\n if not torch.cuda.is_available():\n yield\n return\n\n stream_before_context_switch = torch.cuda.current_stream()\n if not streams:\n streams = [stream_before_context_switch]\n else:\n streams = [s if s else stream_before_context_switch for s in streams]\n\n end_events = [\n torch.cuda.Event(enable_timing=DEBUG_COMPLETED_TIME) for _ in streams\n ]\n\n if DEBUG_COMPLETED_TIME:\n start = torch.cuda.Event(enable_timing=True)\n stream_before_context_switch.record_event(start)\n\n cpu_start = time.monotonic()\n logger.debug('%s %s starting, streams: %s', trace_name, name, streams)\n grad_enabled_before = torch.is_grad_enabled()\n try:\n yield\n finally:\n current_stream = torch.cuda.current_stream()\n assert current_stream == stream_before_context_switch\n\n if DEBUG_COMPLETED_TIME:\n cpu_end = time.monotonic()\n for i, stream in enumerate(streams):\n event = end_events[i]\n stream.record_event(event)\n\n grad_enabled_after = torch.is_grad_enabled()\n\n # observed change of torch.is_grad_enabled() during concurrent run of\n # async_test_bboxes code\n assert (grad_enabled_before == grad_enabled_after\n ), 'Unexpected is_grad_enabled() value change'\n\n are_done = [e.query() for e in end_events]\n logger.debug('%s %s completed: %s streams: %s', trace_name, name,\n are_done, streams)\n with torch.cuda.stream(stream_before_context_switch):\n while not all(are_done):\n await asyncio.sleep(sleep_interval)\n are_done = [e.query() for e in end_events]\n logger.debug(\n '%s %s completed: %s streams: %s',\n trace_name,\n name,\n are_done,\n streams,\n )\n\n current_stream = torch.cuda.current_stream()\n assert current_stream == stream_before_context_switch\n\n if DEBUG_COMPLETED_TIME:\n cpu_time = (cpu_end - cpu_start) * 1000\n stream_times_ms = ''\n for i, stream in enumerate(streams):\n elapsed_time = start.elapsed_time(end_events[i])\n stream_times_ms += ' {} {:.2f} ms'.format(stream, elapsed_time)\n logger.info('%s %s %.2f ms %s', trace_name, name, cpu_time,\n stream_times_ms)\n\n\[email protected]\nasync def concurrent(streamqueue: asyncio.Queue,\n trace_name='concurrent',\n name='stream'):\n \"\"\"Run code concurrently in different streams.\n\n :param streamqueue: asyncio.Queue instance.\n\n Queue tasks define the pool of streams used for concurrent execution.\n\n \"\"\"\n if not torch.cuda.is_available():\n yield\n return\n\n initial_stream = torch.cuda.current_stream()\n\n with torch.cuda.stream(initial_stream):\n stream = await streamqueue.get()\n assert isinstance(stream, torch.cuda.Stream)\n\n try:\n with torch.cuda.stream(stream):\n logger.debug('%s %s is starting, stream: %s', trace_name, name,\n stream)\n yield\n current = torch.cuda.current_stream()\n assert current == stream\n logger.debug('%s %s has finished, stream: %s', trace_name,\n name, stream)\n finally:\n streamqueue.task_done()\n streamqueue.put_nowait(stream)\n" ]
[ [ "torch.cuda.Event", "torch.cuda.current_stream", "torch.cuda.is_available", "torch.cuda.stream", "torch.is_grad_enabled" ] ]