repo_name
stringlengths
6
130
hexsha
list
file_path
list
code
list
apis
list
MapleLeafKiller/affinity-loss
[ "9ce933fd2fd94928a2231f39b7f3302fcd9a6388" ]
[ "cnn_cifar_optuna_affinity.py" ]
[ "import tensorflow as tf\nfrom tensorflow.keras import layers\nfrom tensorflow.keras.models import Model\nfrom tensorflow.keras.callbacks import LearningRateScheduler, Callback\nimport tensorflow.keras.backend as K\nfrom tensorflow.contrib.tpu.python.tpu import keras_support\nfrom affinity_loss_tpu import *\nfrom datasets import inbalanced_cifar\n\nfrom keras.datasets import cifar10\nimport numpy as np\nfrom keras.utils import to_categorical\nfrom sklearn.metrics import f1_score\nimport os, optuna\n\ndef conv_bn_relu(input, ch):\n x = layers.Conv2D(ch, 3, padding=\"same\")(input)\n x = layers.BatchNormalization()(x)\n return layers.Activation(\"relu\")(x)\n\ndef create_models(sigma, m):\n input = layers.Input((32,32,3))\n x = input\n for i in range(3):\n x = conv_bn_relu(x, 64)\n x = layers.AveragePooling2D(2)(x)\n for i in range(3):\n x = conv_bn_relu(x, 128)\n x = layers.AveragePooling2D(2)(x)\n for i in range(3):\n x = conv_bn_relu(x, 256)\n x = layers.GlobalAveragePooling2D()(x)\n x = layers.BatchNormalization()(x)\n x = ClusteringAffinity(10, m, sigma)(x)\n\n return Model(input, x)\n\ndef acc(y_true_plusone, y_pred_plusone):\n y_true = K.argmax(y_true_plusone[:, :-1], axis=-1)\n y_pred = K.argmax(y_pred_plusone[:, :-1], axis=-1)\n equals = K.cast(K.equal(y_true, y_pred), \"float\")\n return K.mean(equals)\n\ndef step_decay(epoch):\n x = 5e-3\n if epoch >= 50: x /= 5.0\n if epoch >= 80: x /= 5.0\n return x\n\nclass F1Callback(Callback):\n def __init__(self, model, X_test, y_test, trial):\n self.model = model\n self.X_test = X_test\n self.y_test_label = np.argmax(y_test, axis=-1)\n self.trial = trial\n self.f1_log = []\n\n def on_epoch_end(self, epoch, logs):\n y_pred = self.model.predict(self.X_test)[:, :10]\n y_pred_label = np.argmax(y_pred, axis=-1)\n f1 = f1_score(self.y_test_label, y_pred_label, average=\"macro\")\n self.f1_log.append(f1)\n # optuna prune\n self.trial.report(1.0-f1, step=epoch)\n if self.trial.should_prune(epoch):\n raise optuna.structs.TrialPruned()\n\n\ndef train(lambd, sigma, n_centers, trial):\n K.clear_session()\n (X_train, y_train), (X_test, y_test) = inbalanced_cifar(200)\n\n model = create_models(sigma, n_centers)\n model.compile(\"adam\", affinity_loss(lambd), [acc])\n tf.logging.set_verbosity(tf.logging.FATAL) # ログを埋めないようにする\n\n tpu_grpc_url = \"grpc://\"+os.environ[\"COLAB_TPU_ADDR\"]\n tpu_cluster_resolver = tf.contrib.cluster_resolver.TPUClusterResolver(tpu_grpc_url)\n strategy = keras_support.TPUDistributionStrategy(tpu_cluster_resolver)\n model = tf.contrib.tpu.keras_to_tpu_model(model, strategy=strategy)\n\n scheduler = LearningRateScheduler(step_decay)\n f1 = F1Callback(model, X_test, y_test, trial)\n\n history = model.fit(X_train, y_train, callbacks=[scheduler, f1],\n batch_size=640, epochs=100, verbose=0).history\n\n max_f1 = max(f1.f1_log)\n print(\"lambda:{lambd:.04}, sigma:{sigma:.04} n_centers:{n_centers} / f1 = {max_f1:.04}\")\n return max_f1\n\ndef objective(trial):\n lambd = trial.suggest_uniform(\"lambda\", 0.01, 1.0)\n sigma = trial.suggest_loguniform(\"sigma\", 10.0, 100.0)\n center = trial.suggest_int(\"n_centers\", 1, 30)\n max_f1 = train(lambd, sigma, center, trial)\n return 1.0-max_f1\n\nif __name__ == \"__main__\":\n study = optuna.create_study()\n study.optimize(objective, n_trials=200)\n df = study.trials_dataframe()\n df.to_csv(\"optuna_affinity.csv\")\n" ]
[ [ "tensorflow.contrib.cluster_resolver.TPUClusterResolver", "tensorflow.keras.layers.AveragePooling2D", "tensorflow.keras.layers.Activation", "tensorflow.keras.layers.GlobalAveragePooling2D", "tensorflow.keras.models.Model", "tensorflow.keras.layers.Conv2D", "tensorflow.keras.callbacks.LearningRateScheduler", "tensorflow.keras.backend.mean", "tensorflow.contrib.tpu.python.tpu.keras_support.TPUDistributionStrategy", "tensorflow.keras.layers.BatchNormalization", "tensorflow.keras.backend.clear_session", "tensorflow.logging.set_verbosity", "numpy.argmax", "tensorflow.keras.backend.argmax", "tensorflow.contrib.tpu.keras_to_tpu_model", "sklearn.metrics.f1_score", "tensorflow.keras.backend.equal", "tensorflow.keras.layers.Input" ] ]
AnTao97/LGM
[ "95dc5c2e814f6bf27baae73a7e75578cb6dab659" ]
[ "indoor_scene/models/dynamics_aware_utils.py" ]
[ "\"\"\"\n\nDynamics-aware Adversarial Attack of 3D Sparse Convolution Network\n\n@Author: \n An Tao,\n Pengliang Ji\n\n@Contact: \n ta19@mails.tsinghua.edu.cn, \n jpl1723@buaa.edu.cn\n \n@Time: \n 2022/1/23 9:32 PM\n\n\"\"\"\n\nimport torch\nimport torch.nn.functional as F\nfrom torch_scatter import scatter_mul\nimport MinkowskiEngine as ME\nimport utils\nfrom SparseTensor import _get_coords_key\n\n\ndef conv_nosample(conv, x, occupy, real_num, stride=1, mul_occupy_after=True):\n \"\"\"\n Add occupancy value for sparse convolution that does not change the stride for input data\n \"\"\"\n\n if occupy.ndim < 2:\n occupy = occupy.unsqueeze(1)\n\n if conv.kernel.ndim < 3:\n conv.kernel.data = conv.kernel.data.unsqueeze(0)\n\n conv.kernel.requires_grad_(False)\n if conv.bias is not None:\n conv.bias.requires_grad_(False)\n\n out0_coords_key = _get_coords_key(x, x.C[:real_num])\n out0_feat = conv(x, out0_coords_key).F\n\n if x.C[real_num:].shape[0] > 0:\n out1_coords_key = _get_coords_key(x, x.C[real_num:])\n out1_feat = conv(x, out1_coords_key).F\n out_feat = torch.cat([out0_feat, out1_feat], dim=0)\n else:\n out_feat = out0_feat\n out = ME.SparseTensor(out_feat, coords=x.C, tensor_stride=stride)\n\n if mul_occupy_after:\n out._F = out._F * occupy\n return out\n\n\ndef conv_downsample(conv, x, occupy, real_num, out_stride=1, mul_occupy_after=True):\n \"\"\"\n Add occupancy value for sparse convolution that increases the stride for input data\n \"\"\"\n\n if occupy.ndim < 2:\n occupy = occupy.unsqueeze(1)\n\n if conv.kernel.ndim < 3:\n conv.kernel.data = conv.kernel.data.unsqueeze(0)\n\n conv.kernel.requires_grad_(False)\n if conv.bias is not None:\n conv.bias.requires_grad_(False)\n\n unique_map, inverse_map = utils.quantize(torch.floor(x.C.float() / out_stride).int() * out_stride)\n out_coords = (torch.floor(x.C.float() / out_stride).int() * out_stride)[unique_map]\n occupy_new = 1 - scatter_mul(1-occupy.view(-1), inverse_map.to(occupy.device)).unsqueeze(1)\n\n real_num_new = utils.quantize(torch.floor(x.C.float()[:real_num] / out_stride).int() * out_stride)[0].shape[0]\n \n out0_coords_key = _get_coords_key(x, out_coords[:real_num_new], tensor_stride=out_stride)\n out0_feat = conv(x, out0_coords_key).F\n\n if out_coords[real_num_new:].shape[0] > 0:\n out1_coords_key = _get_coords_key(x, out_coords[real_num_new:], tensor_stride=out_stride)\n out1_feat = conv(x, out1_coords_key).F\n out_feat = torch.cat([out0_feat, out1_feat], dim=0)\n else:\n out_feat = out0_feat\n out = ME.SparseTensor(out_feat, coords=out_coords, tensor_stride=out_stride)\n\n if mul_occupy_after:\n out._F = out._F * occupy_new\n return out, occupy_new, real_num_new\n\n\ndef conv_upample(conv, x, occupy, real_num, out_coords, out_occupy, out_stride=1, mul_occupy_after=True):\n \"\"\"\n Add occupancy value for sparse convolution that decreases the stride for input data\n \"\"\"\n\n if occupy.ndim < 2:\n occupy = occupy.unsqueeze(1)\n\n if conv.kernel.ndim < 3:\n conv.kernel.data = conv.kernel.data.unsqueeze(0)\n\n conv.kernel.requires_grad_(False)\n if conv.bias is not None:\n conv.bias.requires_grad_(False)\n \n x0 = ME.SparseTensor(x.F[:real_num], coords=x.C[:real_num], tensor_stride=x.tensor_stride)\n out0_coords_key = _get_coords_key(x0, out_coords, tensor_stride=out_stride)\n out0_feat = conv(x0, out0_coords_key).F\n\n if x.C[real_num:].shape[0] > 0:\n x1 = ME.SparseTensor(x.F[real_num:], coords=x.C[real_num:], tensor_stride=x.tensor_stride)\n out1_coords_key = _get_coords_key(x1, out_coords, tensor_stride=out_stride)\n out1_feat = conv(x1, out1_coords_key).F\n out_feat = out0_feat + out1_feat\n else:\n out_feat = out0_feat\n out = ME.SparseTensor(out_feat, coords=out_coords, tensor_stride=out_stride)\n\n if mul_occupy_after:\n out._F = out._F * out_occupy\n return out\n\n\ndef fn_forward(fn, x, occupy, mul_occupy_after=True):\n \"\"\"\n Add occupancy value for normal forward function\n \"\"\"\n\n if occupy.ndim < 2:\n occupy = occupy.unsqueeze(1)\n\n fn.bn.requires_grad_(False)\n\n out = fn(x)\n if mul_occupy_after:\n out._F = out._F * occupy\n return out\n\n" ]
[ [ "torch.cat" ] ]
XenonLamb/higan
[ "c08e2081413c3319b712c2f7193ac8013f601382" ]
[ "utils/visualizer.py" ]
[ "# python 3.7\n\"\"\"Utility functions for visualizing results on html page.\"\"\"\n\nimport base64\nimport os.path\nimport cv2\nimport numpy as np\n\n__all__ = [\n 'get_grid_shape', 'get_blank_image', 'load_image', 'save_image',\n 'add_text_to_image', 'fuse_images', 'HtmlPageVisualizer', 'VideoReader',\n 'VideoWriter'\n]\n\n\ndef get_grid_shape(size, row=0, col=0, is_portrait=False):\n \"\"\"Gets the shape of a grid based on the size.\n\n This function makes greatest effort on making the output grid square if\n neither `row` nor `col` is set. If `is_portrait` is set as `False`, the height\n will always be equal to or smaller than the width. For example, if input\n `size = 16`, output shape will be `(4, 4)`; if input `size = 15`, output shape\n will be (3, 5). Otherwise, the height will always be equal to or larger than\n the width.\n\n Args:\n size: Size (height * width) of the target grid.\n is_portrait: Whether to return a portrait size of a landscape size.\n (default: False)\n\n Returns:\n A two-element tuple, representing height and width respectively.\n \"\"\"\n assert isinstance(size, int)\n assert isinstance(row, int)\n assert isinstance(col, int)\n if size == 0:\n return (0, 0)\n\n if row > 0 and col > 0 and row * col != size:\n row = 0\n col = 0\n\n if row > 0 and size % row == 0:\n return (row, size // row)\n if col > 0 and size % col == 0:\n return (size // col, col)\n\n row = int(np.sqrt(size))\n while row > 0:\n if size % row == 0:\n col = size // row\n break\n row = row - 1\n\n return (col, row) if is_portrait else (row, col)\n\n\ndef get_blank_image(height, width, channels=3, is_black=True):\n \"\"\"Gets a blank image, either white of black.\n\n NOTE: This function will always return an image with `RGB` channel order for\n color image and pixel range [0, 255].\n\n Args:\n height: Height of the returned image.\n width: Width of the returned image.\n channels: Number of channels. (default: 3)\n is_black: Whether to return a black image or white image. (default: True)\n \"\"\"\n shape = (height, width, channels)\n if is_black:\n return np.zeros(shape, dtype=np.uint8)\n return np.ones(shape, dtype=np.uint8) * 255\n\n\ndef load_image(path):\n \"\"\"Loads an image from disk.\n\n NOTE: This function will always return an image with `RGB` channel order for\n color image and pixel range [0, 255].\n\n Args:\n path: Path to load the image from.\n\n Returns:\n An image with dtype `np.ndarray` or `None` if input `path` does not exist.\n \"\"\"\n if not os.path.isfile(path):\n return None\n\n image = cv2.imread(path)\n return image[:, :, ::-1]\n\n\ndef save_image(path, image):\n \"\"\"Saves an image to disk.\n\n NOTE: The input image (if colorful) is assumed to be with `RGB` channel order\n and pixel range [0, 255].\n\n Args:\n path: Path to save the image to.\n image: Image to save.\n \"\"\"\n if image is None:\n return\n\n assert len(image.shape) == 3 and image.shape[2] in [1, 3]\n cv2.imwrite(path, image[:, :, ::-1])\n\n\ndef add_text_to_image(image,\n text='',\n position=None,\n font=cv2.FONT_HERSHEY_TRIPLEX,\n font_size=1.0,\n line_type=cv2.LINE_8,\n line_width=1,\n color=(255, 255, 255)):\n \"\"\"Overlays text on given image.\n\n NOTE: The input image is assumed to be with `RGB` channel order.\n\n Args:\n image: The image to overlay text on.\n text: Text content to overlay on the image. (default: '')\n position: Target position (bottom-left corner) to add text. If not set,\n center of the image will be used by default. (default: None)\n font: Font of the text added. (default: cv2.FONT_HERSHEY_TRIPLEX)\n font_size: Font size of the text added. (default: 1.0)\n line_type: Line type used to depict the text. (default: cv2.LINE_8)\n line_width: Line width used to depict the text. (default: 1)\n color: Color of the text added in `RGB` channel order. (default:\n (255, 255, 255))\n\n Returns:\n An image with target text overlayed on.\n \"\"\"\n if image is None or not text:\n return image\n\n cv2.putText(img=image,\n text=text,\n org=position,\n fontFace=font,\n fontScale=font_size,\n color=color,\n thickness=line_width,\n lineType=line_type,\n bottomLeftOrigin=False)\n\n return image\n\n\ndef fuse_images(images,\n image_size=None,\n row=0,\n col=0,\n is_row_major=True,\n is_portrait=False,\n row_spacing=0,\n col_spacing=0,\n border_left=0,\n border_right=0,\n border_top=0,\n border_bottom=0,\n black_background=True):\n \"\"\"Fuses a collection of images into an entire image.\n\n Args:\n images: A collection of images to fuse. Should be with shape [num, height,\n width, channels].\n image_size: Int or two-element tuple. This field is used to resize the image\n before fusing. `None` disables resizing. (default: None)\n row: Number of rows used for image fusion. If not set, this field will be\n automatically assigned based on `col` and total number of images.\n (default: None)\n col: Number of columns used for image fusion. If not set, this field will be\n automatically assigned based on `row` and total number of images.\n (default: None)\n is_row_major: Whether the input images should be arranged row-major or\n column-major. (default: True)\n is_portrait: Only active when both `row` and `col` should be assigned\n automatically. (default: False)\n row_spacing: Space between rows. (default: 0)\n col_spacing: Space between columns. (default: 0)\n border_left: Width of left border. (default: 0)\n border_right: Width of right border. (default: 0)\n border_top: Width of top border. (default: 0)\n border_bottom: Width of bottom border. (default: 0)\n\n Returns:\n The fused image.\n\n Raises:\n ValueError: If the input `images` is not with shape [num, height, width,\n width].\n \"\"\"\n if images is None:\n return images\n\n if not images.ndim == 4:\n raise ValueError(f'Input `images` should be with shape [num, height, '\n f'width, channels], but {images.shape} is received!')\n\n num, image_height, image_width, channels = images.shape\n if image_size is not None:\n if isinstance(image_size, int):\n image_size = (image_size, image_size)\n assert isinstance(image_size, (list, tuple)) and len(image_size) == 2\n width, height = image_size\n else:\n height, width = image_height, image_width\n row, col = get_grid_shape(num, row=row, col=col, is_portrait=is_portrait)\n fused_height = (\n height * row + row_spacing * (row - 1) + border_top + border_bottom)\n fused_width = (\n width * col + col_spacing * (col - 1) + border_left + border_right)\n fused_image = get_blank_image(\n fused_height, fused_width, channels=channels, is_black=black_background)\n images = images.reshape(row, col, image_height, image_width, channels)\n if not is_row_major:\n images = images.transpose(1, 0, 2, 3, 4)\n\n for i in range(row):\n y = border_top + i * (height + row_spacing)\n for j in range(col):\n x = border_left + j * (width + col_spacing)\n if image_size is not None:\n image = cv2.resize(images[i, j], image_size)\n else:\n image = images[i, j]\n fused_image[y:y + height, x:x + width] = image\n\n return fused_image\n\n\ndef get_sortable_html_header(column_name_list, sort_by_ascending=False):\n \"\"\"Gets header for sortable html page.\n\n Basically, the html page contains a sortable table, where user can sort the\n rows by a particular column by clicking the column head.\n\n Example:\n\n column_name_list = [name_1, name_2, name_3]\n header = get_sortable_html_header(column_name_list)\n footer = get_sortable_html_footer()\n sortable_table = ...\n html_page = header + sortable_table + footer\n\n Args:\n column_name_list: List of column header names.\n sort_by_ascending: Default sorting order. If set as `True`, the html page\n will be sorted by ascending order when the header is clicked for the first\n time.\n\n Returns:\n A string, which represents for the header for a sortable html page.\n \"\"\"\n header = '\\n'.join([\n '<script type=\"text/javascript\">',\n 'var column_idx;',\n 'var sort_by_ascending = ' + str(sort_by_ascending).lower() + ';',\n '',\n 'function sorting(tbody, column_idx){',\n ' this.column_idx = column_idx;',\n ' Array.from(tbody.rows)',\n ' .sort(compareCells)',\n ' .forEach(function(row) { tbody.appendChild(row); })',\n ' sort_by_ascending = !sort_by_ascending;',\n '}',\n '',\n 'function compareCells(row_a, row_b) {',\n ' var val_a = row_a.cells[column_idx].innerText;',\n ' var val_b = row_b.cells[column_idx].innerText;',\n ' var flag = sort_by_ascending ? 1 : -1;',\n ' return flag * (val_a > val_b ? 1 : -1);',\n '}',\n '</script>',\n '',\n '<html>',\n '',\n '<head>',\n '<style>',\n ' table {',\n ' border-spacing: 0;',\n ' border: 1px solid black;',\n ' }',\n ' th {',\n ' cursor: pointer;',\n ' }',\n ' th, td {',\n ' text-align: left;',\n ' vertical-align: middle;',\n ' border-collapse: collapse;',\n ' border: 0.5px solid black;',\n ' padding: 8px;',\n ' }',\n ' tr:nth-child(even) {',\n ' background-color: #d2d2d2;',\n ' }',\n '</style>',\n '</head>',\n '',\n '<body>',\n '',\n '<table>',\n '<thead>',\n '<tr>',\n ''])\n for idx, column_name in enumerate(column_name_list):\n header += f' <th onclick=\"sorting(tbody, {idx})\">{column_name}</th>\\n'\n header += '</tr>\\n'\n header += '</thead>\\n'\n header += '<tbody id=\"tbody\">\\n'\n\n return header\n\n\ndef get_sortable_html_footer():\n \"\"\"Gets footer for sortable html page.\n\n Check function `get_sortable_html_header()` for more details.\n \"\"\"\n return '</tbody>\\n</table>\\n\\n</body>\\n</html>\\n'\n\n\ndef encode_image_to_html_str(image, image_size=None):\n \"\"\"Encodes an image to html language.\n\n Args:\n image: The input image to encode. Should be with `RGB` channel order.\n image_size: Int or two-element tuple. This field is used to resize the image\n before encoding. `None` disables resizing. (default: None)\n\n Returns:\n A string which represents the encoded image.\n \"\"\"\n if image is None:\n return ''\n\n assert len(image.shape) == 3 and image.shape[2] in [1, 3]\n\n # Change channel order to `BGR`, which is opencv-friendly.\n image = image[:, :, ::-1]\n\n # Resize the image if needed.\n if image_size is not None:\n if isinstance(image_size, int):\n image_size = (image_size, image_size)\n assert isinstance(image_size, (list, tuple)) and len(image_size) == 2\n image = cv2.resize(image, image_size)\n\n # Encode the image to html-format string.\n encoded_image = cv2.imencode(\".jpg\", image)[1].tostring()\n encoded_image_base64 = base64.b64encode(encoded_image).decode('utf-8')\n html_str = f'<img src=\"data:image/jpeg;base64, {encoded_image_base64}\"/>'\n\n return html_str\n\n\nclass HtmlPageVisualizer(object):\n \"\"\"Defines the html page visualizer.\n\n This class can be used to visualize image results as html page. Basically, it\n is based on an html-format sorted table with helper functions\n `get_sortable_html_header()`, `get_sortable_html_footer()`, and\n `encode_image_to_html_str()`. To simplify the usage, specifying the following\n fields is enough to create a visualization page:\n\n (1) num_rows: Number of rows of the table (header-row exclusive).\n (2) num_cols: Number of columns of the table.\n (3) header contents (optional): Title of each column.\n\n NOTE: `grid_size` can be used to assign `num_rows` and `num_cols`\n automatically.\n\n Example:\n\n html = HtmlPageVisualizer(num_rows, num_cols)\n html.set_headers([...])\n for i in range(num_rows):\n for j in range(num_cols):\n html.set_cell(i, j, text=..., image=...)\n html.save('visualize.html')\n \"\"\"\n\n def __init__(self,\n num_rows=0,\n num_cols=0,\n grid_size=0,\n is_portrait=False,\n viz_size=None):\n if grid_size > 0:\n num_rows, num_cols = get_grid_shape(\n grid_size, row=num_rows, col=num_cols, is_portrait=is_portrait)\n assert num_rows > 0 and num_cols > 0\n\n self.num_rows = num_rows\n self.num_cols = num_cols\n self.viz_size = viz_size\n self.headers = ['' for _ in range(self.num_cols)]\n self.cells = [[{\n 'text': '',\n 'image': '',\n } for _ in range(self.num_cols)] for _ in range(self.num_rows)]\n\n def set_header(self, column_idx, content):\n \"\"\"Sets the content of a particular header by column index.\"\"\"\n self.headers[column_idx] = content\n\n def set_headers(self, contents):\n \"\"\"Sets the contents of all headers.\"\"\"\n if isinstance(contents, str):\n contents = [contents]\n assert isinstance(contents, (list, tuple))\n assert len(contents) == self.num_cols\n for column_idx, content in enumerate(contents):\n self.set_header(column_idx, content)\n\n def set_cell(self, row_idx, column_idx, text='', image=None):\n \"\"\"Sets the content of a particular cell.\n\n Basically, a cell contains some text as well as an image. Both text and\n image can be empty.\n\n Args:\n row_idx: Row index of the cell to edit.\n column_idx: Column index of the cell to edit.\n text: Text to add into the target cell.\n image: Image to show in the target cell. Should be with `RGB` channel\n order.\n \"\"\"\n self.cells[row_idx][column_idx]['text'] = text\n self.cells[row_idx][column_idx]['image'] = encode_image_to_html_str(\n image, self.viz_size)\n\n def save(self, save_path):\n \"\"\"Saves the html page.\"\"\"\n html = ''\n for i in range(self.num_rows):\n html += f'<tr>\\n'\n for j in range(self.num_cols):\n text = self.cells[i][j]['text']\n image = self.cells[i][j]['image']\n if text:\n html += f' <td>{text}<br><br>{image}</td>\\n'\n else:\n html += f' <td>{image}</td>\\n'\n html += f'</tr>\\n'\n\n header = get_sortable_html_header(self.headers)\n footer = get_sortable_html_footer()\n\n with open(save_path, 'w') as f:\n f.write(header + html + footer)\n\n\nclass VideoReader(object):\n \"\"\"Defines the video reader.\n\n This class can be used to read frames from a given video.\n \"\"\"\n\n def __init__(self, path):\n \"\"\"Initializes the video reader by loading the video from disk.\"\"\"\n if not os.path.isfile(path):\n raise ValueError(f'Video `{path}` does not exist!')\n\n self.path = path\n self.video = cv2.VideoCapture(path)\n assert self.video.isOpened()\n self.position = 0\n\n self.length = int(self.video.get(cv2.CAP_PROP_FRAME_COUNT))\n self.frame_height = int(self.video.get(cv2.CAP_PROP_FRAME_HEIGHT))\n self.frame_width = int(self.video.get(cv2.CAP_PROP_FRAME_WIDTH))\n self.fps = self.video.get(cv2.CAP_PROP_FPS)\n\n def __del__(self):\n \"\"\"Releases the opened video.\"\"\"\n self.video.release()\n\n def read(self, position=None):\n \"\"\"Reads a certain frame.\n\n NOTE: The returned frame is assumed to be with `RGB` channel order.\n\n Args:\n position: Optional. If set, the reader will read frames from the exact\n position. Otherwise, the reader will read next frames. (default: None)\n \"\"\"\n if position is not None and position < self.length:\n self.video.set(cv2.CAP_PROP_POS_FRAMES, position)\n self.position = position\n\n success, frame = self.video.read()\n self.position = self.position + 1\n\n return frame[:, :, ::-1] if success else None\n\n\nclass VideoWriter(object):\n \"\"\"Defines the video writer.\n\n This class can be used to create a video.\n\n NOTE: `.avi` and `DIVX` is the most recommended codec format since it does not\n rely on other dependencies.\n \"\"\"\n\n def __init__(self, path, frame_height, frame_width, fps=24, codec='DIVX'):\n \"\"\"Creates the video writer.\"\"\"\n self.path = path\n self.frame_height = frame_height\n self.frame_width = frame_width\n self.fps = fps\n self.codec = codec\n\n self.video = cv2.VideoWriter(filename=path,\n fourcc=cv2.VideoWriter_fourcc(*codec),\n fps=fps,\n frameSize=(frame_width, frame_height))\n\n def __del__(self):\n \"\"\"Releases the opened video.\"\"\"\n self.video.release()\n\n def write(self, frame):\n \"\"\"Writes a target frame.\n\n NOTE: The input frame is assumed to be with `RGB` channel order.\n \"\"\"\n self.video.write(frame[:, :, ::-1])\n" ]
[ [ "numpy.zeros", "numpy.sqrt", "numpy.ones" ] ]
softsys4ai/neural-distiller
[ "12863bd8b69cf73c67ead5e14dbd2122c6db01ec" ]
[ "src/pruning/prune_experiments.py" ]
[ "from pruning.prune_util import load_dataset, load_model, compile_model, train_model, save_model_h5, \\\n evaluate_model_size, format_experiment_name, evaluate_percentage_of_zeros\n\nfrom pruning.pruner import Pruner\n\nimport tensorflow as tf\nimport tensorflow_model_optimization as tfmot\n\nimport numpy as np\n\nimport datetime\n\n\ndef prune_mnist_pruner(test_size=500, **pruning_params):\n \"\"\"\n :param test_size: Number of samples to be used for test set\n :keyword\n pruning_params:\n intial_epochs - Epochs to train model before pruning\n prune_schedule - PruningSchedule object to be used\n continue_epochs - Epochs to continue training after wrapping model\n fine_tune_epochs - Epochs to train after pruning model\n :return:\n \"\"\"\n experiment_name = format_experiment_name(\"low_magnitude\", \"weight\", \"mnist\", **pruning_params)\n initial_epochs = pruning_params.get(\"initial_epochs\", 4)\n\n prune_method = \"low_magnitude\"\n prune_level = \"weight\"\n\n # Load model and dataset, and compile model\n model = load_model(\"mnist\")\n compile_model(model)\n (X_train, Y_train), (X_test, Y_test) = load_dataset(\"mnist\", test_size=test_size)\n\n # Train model with TensorBoard callback\n log_dir = f\"./logs/{experiment_name}/unpruned\"\n tensorboard_callback = tf.keras.callbacks.TensorBoard(\n log_dir=log_dir,\n )\n train_model(model, X_train, Y_train, X_test, Y_test,\n callbacks=[tensorboard_callback],\n epochs=initial_epochs, verbose=0)\n\n # Initialize Pruner\n log_dir = f\"./logs/{experiment_name}/pruned\"\n tensorboard_callback = tf.keras.callbacks.TensorBoard(\n log_dir=log_dir,\n )\n model_pruner = Pruner(model, X_train, Y_train, X_test, Y_test,\n prune_level, prune_method)\n pruning_params[\"callbacks\"] = [tensorboard_callback]\n model_pruner.prune(**pruning_params)\n\n pruned_model = model_pruner.pruned_model\n print(evaluate_percentage_of_zeros(pruned_model))\n\n\nif __name__ == \"__main__\":\n \"\"\"\n :param test_size: Number of samples to be used for test set \n :keyword \n pruning_params:\n intial_epoch - Epochs to train model before pruning\n prune_schedule - PruningSchedule object to be used\n continue_epochs - Epochs to continue training after wrapping model\n fine_tune_epochs - Epochs to train after pruning model \n :return: \n \"\"\"\n # Test 1\n _initial_epochs = 10\n _continue_epochs = 5\n _fine_tune_epochs = 3\n\n begin_step = 0\n end_step = 4\n initial_sparsity = 0.5\n final_sparsity = 0.9\n _pruning_schedule = tfmot.sparsity.keras.PolynomialDecay(begin_step=begin_step,\n end_step=end_step,\n initial_sparsity=initial_sparsity,\n final_sparsity=final_sparsity)\n\n pruning_params = {\n \"initial_epochs\": _initial_epochs,\n \"continue_epochs\": _continue_epochs,\n \"fine_tune_epochs\": _fine_tune_epochs,\n \"pruning_schedule\": _pruning_schedule\n }\n prune_mnist_pruner(**pruning_params)\n" ]
[ [ "tensorflow.keras.callbacks.TensorBoard" ] ]
CalebEverett/trax
[ "77b6e8e3830f0994481ed78e57e3070ed98e41e4" ]
[ "trax/supervised/training_test.py" ]
[ "# coding=utf-8\n# Copyright 2021 The Trax Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# Lint as: python3\n\"\"\"Tests for supervised training: core classes and flows.\"\"\"\n\nimport os\nimport time\n\nfrom absl.testing import absltest\nfrom jax import test_util # pylint: disable=unused-import\nfrom jax.config import config\nimport numpy as np\n\nfrom trax import fastmath\nfrom trax import layers as tl\nfrom trax import optimizers\nfrom trax import shapes\nfrom trax import test_utils\nfrom trax.models import transformer\nfrom trax.supervised import callbacks\nfrom trax.supervised import training\n\n\nclass TrainingTest(absltest.TestCase):\n\n def setUp(self):\n super().setUp()\n test_utils.ensure_flag('test_tmpdir')\n\n def test_loop_no_eval_task(self):\n \"\"\"Runs a training loop with no eval task(s).\"\"\"\n model = tl.Serial(tl.Dense(1))\n task = training.TrainTask(\n _very_simple_data(), tl.L2Loss(), optimizers.SGD(.01))\n training_session = training.Loop(model, [task])\n # Loop should initialize and run successfully, even with no eval task.\n training_session.run(n_steps=5)\n\n def test_loop_no_eval_task_tfnp(self):\n \"\"\"Runs a training loop with no eval task(s), TFNP backend.\"\"\"\n with fastmath.use_backend(fastmath.Backend.TFNP):\n model = tl.Serial(tl.Dense(1))\n task = training.TrainTask(\n _very_simple_data(), tl.L2Loss(), optimizers.Adam(.01))\n training_session = training.Loop(model, [task])\n # Loop should initialize and run successfully, even with no eval task.\n training_session.run(n_steps=5)\n\n def test_train_dense_layer(self):\n \"\"\"Trains a very simple network on a very simple task.\"\"\"\n model = tl.Serial(tl.Dense(1))\n task = training.TrainTask(\n _very_simple_data(), tl.L2Loss(), optimizers.SGD(.01))\n eval_task = training.EvalTask(\n _very_simple_data(), # deliberately re-using training data\n [tl.L2Loss()],\n metric_names=['SGD.L2Loss'])\n training_session = training.Loop(model, [task], eval_tasks=[eval_task],\n eval_at=lambda step_n: step_n % 2 == 0)\n self.assertEqual(0, training_session.step)\n training_session.run(n_steps=15)\n self.assertEqual(15, training_session.step)\n training_session.run(n_steps=5)\n self.assertEqual(20, training_session.step)\n\n def test_loop_with_initialized_model(self):\n \"\"\"Check that loop does not re-initialize an already initialized model.\"\"\"\n model = tl.Serial(tl.Dense(1))\n example_data = next(_very_simple_data())\n model.init(example_data)\n w = model.weights[0][0]\n task = training.TrainTask(\n _very_simple_data(), tl.L2Loss(), optimizers.SGD(.01))\n eval_task = training.EvalTask(\n _very_simple_data(), # deliberately re-using training data\n [tl.L2Loss()],\n metric_names=['SGD.L2Loss'])\n loop = training.Loop(model, [task], eval_tasks=[eval_task],\n eval_at=lambda step_n: step_n % 2 == 0)\n self.assertEqual(0, loop.step)\n self.assertEqual(loop.model.weights[0][0], w)\n\n def test_train_save_restore_dense(self):\n \"\"\"Saves and restores a checkpoint to check for equivalence.\"\"\"\n task = training.TrainTask(\n _very_simple_data(), tl.L2Loss(), optimizers.SGD(.01))\n eval_task = training.EvalTask(\n _very_simple_data(), # deliberately re-using training data\n [tl.L2Loss()],\n metric_names=['SGD.L2Loss'])\n tmp_dir = self.create_tempdir().full_path\n\n def _make_model_and_session():\n m = tl.Serial(tl.Dense(1))\n ts = training.Loop(m, [task], eval_tasks=[eval_task],\n eval_at=lambda step_n: step_n % 2 == 0,\n output_dir=tmp_dir)\n return m, ts\n\n model, training_session = _make_model_and_session()\n self.assertEqual(0, training_session.step)\n training_session.run(n_steps=1)\n training_session.save_checkpoint()\n model2, training_session2 = _make_model_and_session()\n\n x = np.ones((8, 1))\n y1 = model(x, rng=fastmath.random.get_prng(0))\n y2 = model2(x, rng=fastmath.random.get_prng(0))\n self.assertEqual(str(y1), str(y2))\n\n training_session2.run(n_steps=1)\n y1 = model(x, rng=fastmath.random.get_prng(0))\n y2 = model2(x, rng=fastmath.random.get_prng(0))\n self.assertNotEqual(str(y1), str(y2))\n\n def test_train_save_restore_transformer(self):\n \"\"\"Saves and restores a checkpoint to check for equivalence.\"\"\"\n vocab_size = 8\n task = training.TrainTask(\n _very_simple_transformer_data(), tl.L2Loss(), optimizers.SGD(.01))\n eval_task = training.EvalTask(\n _very_simple_transformer_data(), # deliberately re-using training data\n [tl.L2Loss()],\n metric_names=['SGD.L2Loss'])\n tmp_dir = self.create_tempdir().full_path\n\n def _make_model_and_session():\n m = transformer.TransformerLM(\n vocab_size, d_model=4, d_ff=4, n_layers=1, n_heads=2, dropout=0.)\n ts = training.Loop(m, [task], eval_tasks=[eval_task],\n eval_at=lambda step_n: step_n % 2 == 0,\n output_dir=tmp_dir)\n return m, ts\n\n model, training_session = _make_model_and_session()\n self.assertEqual(0, training_session.step)\n training_session.run(n_steps=1)\n training_session.save_checkpoint()\n model2, training_session2 = _make_model_and_session()\n\n x = np.ones((2, 2)).astype(np.int32)\n y1 = model(x, rng=fastmath.random.get_prng(0))\n y2 = model2(x, rng=fastmath.random.get_prng(0))\n self.assertEqual(str(y1), str(y2))\n\n training_session2.run(n_steps=1)\n y1 = model(x, rng=fastmath.random.get_prng(0))\n y2 = model2(x, rng=fastmath.random.get_prng(0))\n self.assertNotEqual(str(y1), str(y2))\n\n def test_train_dense_layer_with_momentum(self):\n \"\"\"Trains with an optimizer that has slots / requires initialization.\"\"\"\n model = tl.Serial(tl.Dense(1))\n task = training.TrainTask(\n _very_simple_data(), tl.L2Loss(), optimizers.Momentum(.01))\n eval_task = training.EvalTask(\n _very_simple_data(), # deliberately re-using training data\n [tl.L2Loss()],\n metric_names=['Momentum.L2Loss'])\n training_session = training.Loop(model, [task], eval_tasks=[eval_task],\n eval_at=lambda step_n: step_n % 2 == 0)\n self.assertEqual(0, training_session.step)\n training_session.run(n_steps=20)\n self.assertEqual(20, training_session.step)\n\n def test_train_dense_layer_evals(self):\n \"\"\"Trains a very simple network on a very simple task, 2 epochs.\"\"\"\n model = tl.Serial(tl.Dense(1))\n task = training.TrainTask(\n _very_simple_data(), tl.L2Loss(), optimizers.SGD(.01))\n eval_task = training.EvalTask(\n _very_simple_data(), # deliberately re-using training data\n [tl.L2Loss()])\n training_session = training.Loop(model, [task], eval_tasks=[eval_task],\n eval_at=lambda step_n: False)\n self.assertEqual(0, training_session.step)\n training_session.run(n_steps=10)\n self.assertEqual(10, training_session.step)\n training_session.run_evals()\n self.assertEqual(10, training_session.step) # Unchanged\n\n def test_summaries_are_written(self):\n \"\"\"Training writes down metrics when writing is turned on.\"\"\"\n model = tl.Serial(tl.Dense(1))\n task = training.TrainTask(\n _very_simple_data(), tl.L2Loss(), optimizers.SGD(.01))\n eval_task = training.EvalTask(\n _very_simple_data(), # deliberately re-using training data\n [tl.L2Loss()],\n metric_names=['SGD.L2Loss'])\n tmp_dir = self.create_tempdir().full_path\n training_session = training.Loop(model, [task], eval_tasks=[eval_task],\n eval_at=lambda step_n: step_n % 2 == 0,\n output_dir=tmp_dir)\n expected_train_metric_dir = os.path.join(tmp_dir, 'train')\n expected_eval_metric_dir = os.path.join(tmp_dir, 'eval')\n for directory in [expected_train_metric_dir, expected_eval_metric_dir]:\n self.assertFalse(\n os.path.isdir(directory), 'Failed for directory %s.' % directory)\n training_session.run(n_steps=15)\n time.sleep(1) # wait for the files to be closed\n for directory in [expected_train_metric_dir, expected_eval_metric_dir]:\n self.assertTrue(\n os.path.isdir(directory), 'Failed for directory %s.' % directory)\n self.assertEqual(\n 1, _count_files(directory), 'Failed for directory %s.' % directory)\n training_session.run(n_steps=5)\n time.sleep(1) # wait for the files to be closed\n for directory in [expected_train_metric_dir, expected_eval_metric_dir]:\n self.assertEqual(\n 2, _count_files(directory), 'Failed for directory %s.' % directory)\n\n def test_restores_step(self):\n \"\"\"Training restores step from directory where it saved it.\"\"\"\n model = tl.Serial(tl.Dense(1))\n task = training.TrainTask(\n _very_simple_data(), tl.L2Loss(), optimizers.SGD(.01))\n tmp_dir = self.create_tempdir().full_path\n loop = training.Loop(model, [task],\n checkpoint_at=lambda step_n: step_n % 2 == 0,\n output_dir=tmp_dir)\n loop.run(4)\n loop2 = training.Loop(model, [task], output_dir=tmp_dir)\n self.assertEqual(4, loop2.step)\n\n def test_restores_step_bfloat16(self):\n \"\"\"Training restores step from directory where it saved it, w/ bfloat16.\"\"\"\n model = tl.Serial(tl.Dense(1, use_bfloat16=True))\n task = training.TrainTask(\n _very_simple_data(), tl.L2Loss(), optimizers.SGD(.01))\n tmp_dir = self.create_tempdir().full_path\n loop = training.Loop(model, [task],\n checkpoint_at=lambda step_n: step_n % 2 == 0,\n output_dir=tmp_dir)\n loop.run(4)\n loop2 = training.Loop(model, [task], output_dir=tmp_dir)\n self.assertEqual(4, loop2.step)\n loop2.run(2) # check that continued training works\n self.assertEqual(6, loop2.step)\n\n def test_restores_step_sharded(self):\n \"\"\"Training restores step from directory where it saved it, sharded.\"\"\"\n model = tl.Serial(tl.Dense(1))\n task = training.TrainTask(\n _very_simple_data(), tl.L2Loss(), optimizers.SGD)\n tmp_dir = self.create_tempdir().full_path\n loop = training.Loop(model, [task],\n checkpoint_at=lambda step_n: step_n % 2 == 0,\n output_dir=tmp_dir, use_memory_efficient_trainer=True)\n loop.run(4)\n loop2 = training.Loop(model, [task],\n output_dir=tmp_dir, use_memory_efficient_trainer=True)\n self.assertEqual(4, loop2.step)\n\n def test_restores_step_sharded_bfloat16(self):\n \"\"\"Training restores step from where it saved it, sharded and bfloat16.\"\"\"\n model = tl.Serial(tl.Dense(1, use_bfloat16=True))\n task = training.TrainTask(\n _very_simple_data(), tl.L2Loss(), optimizers.SGD)\n tmp_dir = self.create_tempdir().full_path\n loop = training.Loop(model, [task],\n checkpoint_at=lambda step_n: step_n % 2 == 0,\n output_dir=tmp_dir, use_memory_efficient_trainer=True)\n loop.run(4)\n loop2 = training.Loop(model, [task],\n output_dir=tmp_dir, use_memory_efficient_trainer=True)\n self.assertEqual(4, loop2.step)\n loop2.run(2) # check that continued training works\n self.assertEqual(6, loop2.step)\n\n def test_restores_history(self):\n \"\"\"Training restores history from directory where it saved it.\"\"\"\n model = tl.Serial(tl.Dense(1))\n task = training.TrainTask(_very_simple_data(), tl.L2Loss(),\n optimizers.SGD(.01))\n eval_task = training.EvalTask(\n _very_simple_data(), # deliberately re-using training data\n [tl.L2Loss()])\n tmp_dir = self.create_tempdir().full_path\n loop = training.Loop(\n model, [task],\n eval_tasks=[eval_task],\n eval_at=lambda step_n: step_n % 2 == 0,\n checkpoint_at=lambda step_n: step_n % 2 == 0,\n output_dir=tmp_dir)\n loop.run(4)\n loop2 = training.Loop(model, [task], output_dir=tmp_dir)\n self.assertLen(loop2.history.modes, 2)\n self.assertLen(loop2.history.metrics_for_mode('train'), 6)\n self.assertLen(loop2.history.metrics_for_mode('eval'), 1)\n for mode, metric in [\n ('train', 'metrics/L2Loss'),\n ('train', 'training/learning_rate'),\n ('train', 'training/steps per second'),\n ('train', 'training/gradients_l2'),\n ('train', 'training/loss'),\n ('train', 'training/weights_l2'),\n ('eval', 'metrics/L2Loss'),\n ]:\n self.assertLen(loop2.history.get(mode, metric), 1)\n self.assertEqual(2, loop2.history.get(mode, metric)[0][0])\n\n def test_trains_on_two_tasks(self):\n \"\"\"Trains a very simple network on two very simple tasks.\"\"\"\n model = tl.Serial(tl.Dense(3), tl.Dense(1))\n task = training.TrainTask(\n _very_simple_data(),\n tl.L2Loss(),\n optimizers.SGD(.01)\n )\n eval_task = training.EvalTask(\n _very_simple_data(), # deliberately re-using training data\n [tl.L2Loss()],\n )\n training_session = training.Loop(\n model,\n tasks=(task, task),\n eval_tasks=(eval_task, eval_task),\n which_task=lambda step_n: step_n % 2,\n )\n self.assertEqual(0, training_session.step)\n training_session.run(n_steps=15)\n self.assertEqual(15, training_session.step)\n training_session.run(n_steps=5)\n self.assertEqual(20, training_session.step)\n\n def test_train_one_task_eval_two_tasks(self):\n \"\"\"Trains a very simple network on one task and evaluates on two tasks.\"\"\"\n model = tl.Serial(tl.Dense(3), tl.Dense(1))\n task = training.TrainTask(\n _very_simple_data(),\n tl.L2Loss(),\n optimizers.SGD(.01)\n )\n eval_task = training.EvalTask(\n _very_simple_data(), # deliberately re-using training data\n [tl.L2Loss()],\n )\n training_session = training.Loop(\n model,\n tasks=(task,),\n eval_tasks=(eval_task, eval_task),\n )\n self.assertEqual(0, training_session.step)\n training_session.run(n_steps=5)\n self.assertEqual(5, training_session.step)\n\n def test_can_predict_with_trained_model(self):\n model = tl.Serial(tl.Dense(3), tl.Branch(tl.Dense(1), tl.Dense(2)))\n train_tasks, eval_tasks = [], []\n for output_dim in [1, 2]:\n # The head we select from the model: 0 for output_dim 1 and 1 for 2.\n head_index = output_dim - 1\n train_tasks.append(training.TrainTask(\n _very_simple_data(output_dim),\n tl.Serial(tl.Select([head_index], n_in=2), tl.L2Loss()),\n optimizers.SGD(.01)\n ))\n eval_tasks.append(training.EvalTask(\n _very_simple_data(output_dim), # deliberately re-use training data\n [tl.Serial(tl.Select([head_index], n_in=2), tl.L2Loss())]\n ))\n tmp_dir = self.create_tempdir().full_path\n training_session = training.Loop(\n model,\n tasks=train_tasks,\n eval_tasks=eval_tasks,\n checkpoint_at=lambda step_n: step_n == 1,\n output_dir=tmp_dir,\n which_task=lambda step_n: step_n % 2,\n )\n training_session.run(n_steps=2)\n\n trained_model = training_session.eval_model\n inp = next(_very_simple_data())[0]\n out = trained_model(inp)\n self.assertEqual(\n shapes.signature(out),\n (shapes.ShapeDtype((8, 1)), shapes.ShapeDtype((8, 2))),\n )\n\n def test_train_memory_efficient(self):\n \"\"\"Trains a large network in a memory-efficient way.\"\"\"\n # This test requires > 16GB RAM, only run on TPUs. It does pass on GPU\n # and CPU when you run it locally, but it's too big for unit-testing.\n ram_limited = True # Set to False to run this test locally.\n if fastmath.device_count() == 1 and ram_limited:\n return\n\n # Create the model.\n n_layers = 16 # 16 layers each 16K x 16K = 256M weights ~= 1GB, 16GB ram\n model = tl.Serial(\n tl.Embedding(9, 16*1024),\n tl.Dup(),\n [[tl.ReversibleHalfResidual(tl.Dense(16*1024)), tl.ReversibleSwap()]\n for _ in range(n_layers)],\n tl.Concatenate(),\n tl.Dense(9),\n )\n\n # Create inputs.\n inputs_batch = np.arange(8).reshape((2, 4))\n targets_batch = inputs_batch\n labeled_batch = (inputs_batch, targets_batch, np.ones_like(targets_batch))\n def _data_gen():\n while True:\n yield labeled_batch\n\n # Run training.\n loss_layer = tl.WeightedCategoryCrossEntropy()\n task = training.TrainTask(_data_gen(), loss_layer, optimizers.Adafactor)\n eval_task = training.EvalTask(_data_gen(),\n [tl.WeightedCategoryCrossEntropy()])\n loop = training.Loop(model, [task], eval_tasks=[eval_task],\n eval_at=lambda step_n: step_n == 2,\n use_memory_efficient_trainer=True)\n self.assertEqual(0, loop.step)\n loop.run(n_steps=2)\n self.assertEqual(2, loop.step)\n\n def test_initializes_step_callbacks_with_loop_instance(self):\n \"\"\"Runs a training loop, asserting that callbacks are initialized.\"\"\"\n\n class ActualLoop:\n # Wrapper object to make the Loop reference mutable.\n loop = None\n\n class TestCallback(callbacks.TrainingStepCallback):\n\n def __init__(self, loop):\n super().__init__(loop)\n ActualLoop.loop = loop\n\n def call_at(self, step):\n return False\n\n def on_step_begin(self, step):\n del step\n\n def on_step_end(self, step):\n del step\n\n model = tl.Serial(tl.Dense(1))\n task = training.TrainTask(\n _very_simple_data(), tl.L2Loss(), optimizers.SGD(.01)\n )\n expected_loop = training.Loop(\n model, [task], callbacks=[TestCallback]\n )\n self.assertIs(ActualLoop.loop, expected_loop)\n\n def test_calls_step_callbacks(self):\n \"\"\"Runs a training loop, asserting that callbacks are called.\"\"\"\n call_at_steps = [1, 3, 4]\n begin_steps = []\n end_steps = []\n test_case = self\n\n class TestCallback(callbacks.TrainingStepCallback):\n\n def call_at(self, step):\n return step in call_at_steps\n\n def on_step_begin(self, step):\n begin_steps.append(step)\n\n def on_step_end(self, step):\n # Assert that on_step_begin() was called before.\n test_case.assertIn(step, begin_steps)\n end_steps.append(step)\n\n model = tl.Serial(tl.Dense(1))\n task = training.TrainTask(\n _very_simple_data(), tl.L2Loss(), optimizers.SGD(.01)\n )\n loop = training.Loop(model, [task], callbacks=[TestCallback])\n loop.run(n_steps=5)\n\n # Assert that the callback has been called at the appropriate steps.\n self.assertEqual(begin_steps, call_at_steps)\n self.assertEqual(end_steps, call_at_steps)\n\n\ndef _very_simple_data(output_dim=1):\n \"\"\"\"Returns stream of labeled data that maps small integers to constant pi.\"\"\"\n inputs_batch = np.arange(8).reshape((8, 1)) # 8 items per batch\n targets_batch = np.pi * np.ones((8, output_dim))\n labeled_batch = (inputs_batch, targets_batch, np.ones_like(targets_batch))\n while True:\n yield labeled_batch\n\n\ndef _very_simple_transformer_data():\n \"\"\"\"Returns stream of labeled data that maps small integers to constant pi.\"\"\"\n inputs_batch = np.ones((2, 2)).astype(np.int32)\n targets_batch = np.ones((2, 2, 8)).astype(np.int32)\n labeled_batch = (inputs_batch, targets_batch, np.ones_like(targets_batch))\n while True:\n yield labeled_batch\n\n\ndef _count_files(path):\n \"\"\"Returns number of files in a given directory.\"\"\"\n return len([filename for filename in os.listdir(path)\n if os.path.isfile(os.path.join(path, filename))])\n\n\nif __name__ == '__main__':\n config.config_with_absl()\n absltest.main()\n" ]
[ [ "numpy.arange", "numpy.ones_like", "numpy.ones" ] ]
juancroldan/datamart
[ "9ec3b99f36192f812edd74ad2262bebccc22bc66" ]
[ "datamart/materializers/parsers/json_parser.py" ]
[ "from pandas.io.json import json_normalize\nimport json\n\nfrom datamart.materializers.parsers.parser_base import *\n\n\nclass JSONParser(ParserBase):\n\n def get_all(self, url: str) -> typing.List[pd.DataFrame]:\n \"\"\"\n Parses json and returns result\n\n Params:\n - url: (str)\n\n Returns:\n - result: (list) \n \"\"\"\n\n data = json.loads(self.load_content(url))\n\n if type(data) is list:\n data = [self._flatten_dict(x) for x in data]\n return [json_normalize(data)]\n else:\n return [json_normalize(self._flatten_dict(data))]\n\n \n @staticmethod\n def _flatten_dict(d: dict) -> typing.Dict:\n \"\"\"\n Flattens a dictionary and returns the flattented dict\n\n Params:\n - d: (dict) Dictionary to be flattened\n\n Returns:\n - out: (dict) Flattened dictionary\n \"\"\"\n out = {}\n def flatten(x, name=''):\n if type(x) is dict:\n for a in x:\n flatten(x[a], name + a + '.')\n elif type(x) is list:\n i = 0\n for a in x:\n flatten(a, name + str(i) + '.')\n i += 1\n else:\n out[name[:-1]] = x \n\n flatten(d)\n return out" ]
[ [ "pandas.io.json.json_normalize" ] ]
harizMunawar/REI
[ "ff0cb47eba9134078636ecc29efb152f29463e31" ]
[ "helpers/excel_handlers.py" ]
[ "import pandas as pd\nimport json\nfrom sekolah.models import Kelas\nfrom helpers import active_semester, active_tp\n\ndef append_df_to_excel(filename, df, sheet_name='Sheet1', startrow=None,\n truncate_sheet=False, \n **to_excel_kwargs):\n # ignore [engine] parameter if it was passed\n if 'engine' in to_excel_kwargs:\n to_excel_kwargs.pop('engine')\n\n with pd.ExcelWriter(filename, engine='openpyxl') as writer:\n df.to_excel(writer, sheet_name=sheet_name, index=False)\n writer.save()\n\ndef extract_and_clean_siswa(file):\n excel = pd.read_excel(file, dtype={'NIS':str, 'NISN':str})\n json_string = json.loads(excel.to_json(orient='records', date_format='iso'))\n\n tp = active_tp()\n cleaned_json = []\n for data in json_string:\n if not data['NISN'].startswith('00'):\n data['NISN'] = '00'+data['NISN']\n data['NISN'] = data['NISN'][0:10]\n data['NIS'] = data['NIS'][0:9]\n \n data['Tanggal Lahir'] = data['Tanggal Lahir'][0:10]\n if data['Gender'].lower() == 'pria' or data['Gender'].lower() == 'laki-laki':\n data['Gender'] = 'P'\n else:\n data['Gender'] = 'W'\n \n try:\n data['Kelas'] = data['Kelas'].replace(' ', '-')\n data['Kelas'] = Kelas.objects.get(nama=data['Kelas'], tahun_pelajaran=tp)\n except Kelas.DoesNotExist:\n data['Kelas'] = None\n except AttributeError:\n data['Kelas'] = None\n \n siswa = {}\n for key, value in data.items():\n key = str(key).lower().replace(' ', '_')\n siswa[key] = value\n cleaned_json.append(siswa)\n\n return cleaned_json" ]
[ [ "pandas.read_excel", "pandas.ExcelWriter" ] ]
matthewmcampbell/connect4RL
[ "c39db321813165c73fdc595b8eeb145672516771" ]
[ "frontend/streamlit_app.py" ]
[ "import numpy as np\nimport streamlit as st\nimport requests\nimport json\n\n# GLOBAL CONFIG\nIMG_FOLDER = \"./frontend/imgs/\"\nNROWS = 6\nNCOLS = 7\n\n\n# Setup API query structures and perform a cold call at app load.\n# This will make the gameplay smoother once the user starts.\nhost_address = st.secrets['host_address']\nai_url = st.secrets['ai_url']\n\nheaders = {\n \"accept\": \"*/*\",\n \"content-type\": \"text/plain\",\n \"host\": host_address,\n }\n\nddqn_url = ai_url\nmyobj = {\"obs\": {\"board\": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1, 0, -1, 1, 1]}}\n\n# Cold call\nx = requests.post(ddqn_url,headers=headers, data=json.dumps(myobj))\n\n# Setup state-space.\nif 'button_disable' not in st.session_state:\n st.session_state.button_disable = False\n\nif 'connect' not in st.session_state:\n st.session_state.connect = np.zeros(shape=(NROWS, NCOLS))\n st.session_state.connect[NROWS - 1, 3] = 1\n\n# Game logic and win-conditions\ndef is_win(seq, mark):\n for i in seq:\n if i != mark:\n return False\n return True\n\ndef break_into_l_list(x, l=4):\n if len(x) <= 4:\n return x\n else:\n return [break_into_l_list(x[i:i+l]) for i in range(len(x) - l + 1)]\n\ndef get_diags(a, l=4):\n diags = [a[::-1,:].diagonal(i) for i in range(-a.shape[0]+1, a.shape[1])]\n diags.extend(a.diagonal(i) for i in range(a.shape[1]-1, -a.shape[0], -1))\n res = [n.tolist() for n in diags if len(n) >= l]\n new_list = []\n for x in res:\n if len(x) == 4:\n new_list.append(x)\n else:\n l = break_into_l_list(x, l=4)\n for i in l:\n new_list.append(i)\n return new_list\n\ndef check_win():\n player1_win = (True, \"AI Wins\")\n player2_win = (True, \"Player Wins\")\n no_win = (False, \"Nobody Yet\")\n\n board = st.session_state.connect\n # Horizontal\n for i in range(NROWS):\n for j in range(NCOLS-4 + 1):\n seq = board[i, j:(j+4)]\n if is_win(seq, 1):\n return player1_win\n if is_win(seq, -1):\n return player2_win\n # Vertical\n for i in range(NROWS-4 + 1):\n for j in range(NCOLS):\n seq = board[i:(i+4), j]\n if is_win(seq, 1):\n return player1_win\n if is_win(seq, -1):\n return player2_win\n\n # Diagonals\n diagonals = get_diags(board)\n for seq in diagonals:\n if is_win(seq, 1):\n return player1_win\n if is_win(seq, -1):\n return player2_win\n\n return no_win\n\n\ndef enemy_play():\n curr_board = list(st.session_state.connect.reshape(NROWS*NCOLS))\n payload = {\n \"obs\":\n {\"board\": curr_board}\n }\n req = requests.post(ddqn_url, headers=headers, data=json.dumps(payload))\n action = json.loads(req.text)['prediction']\n return action\n\ndef win_process():\n st.balloons()\n st.success(\"You win! Congrats!\")\n\ndef loss_process():\n st.warning(\"Failure... the AI beat you!\")\n\ndef end_game(win_status):\n st.session_state.button_disable = True\n\n if win_status[1] == \"AI Wins\":\n loss_process()\n if win_status[1] == \"Player Wins\":\n win_process()\n\ndef update_board(col):\n row = NROWS - 1\n while st.session_state.connect[row, col]:\n row -= 1\n if row < 0:\n break\n st.session_state.connect[row, col] = -1\n\n win_check = check_win()\n if win_check[0]:\n end_game(win_check)\n return\n\n enemy_action = enemy_play()\n row = NROWS - 1\n while st.session_state.connect[row, enemy_action]:\n row -= 1\n if row < 0:\n break\n st.session_state.connect[row, enemy_action] = 1\n\n win_check = check_win()\n if win_check[0]:\n end_game(win_check)\n return\n\ndef select_img(mark):\n if mark == -1:\n return f\"{IMG_FOLDER}circle_blue.png\"\n elif mark == 1:\n return f\"{IMG_FOLDER}circle_red.png\"\n else:\n return f\"{IMG_FOLDER}circle_white.png\"\n\n\ndef reset_game():\n st.session_state.button_disable = False\n st.session_state.connect = np.zeros(shape=(NROWS, NCOLS))\n st.session_state.connect[NROWS - 1, 3] = 1\n\n\n# UI\nst.title('Connect Four!')\nst.subheader(\"Can you beat the AI?\")\n\ncols = st.columns(NCOLS)\nimages = [[cols[i].image(select_img(st.session_state.connect[j, i])) for i in range(NCOLS)] for j in range(NROWS)]\nbuttons = [\n cols[i].button(\"Play\", key=i, disabled=st.session_state.button_disable, on_click=update_board, args=(i,))\n for i in range(NCOLS)\n]\nst.button(\"Reset Game\", on_click=reset_game)\nst.sidebar.title(\"Self-play reinforcement AI\")\nst.sidebar.text(\"This app is built using a:\")\nst.sidebar.image(IMG_FOLDER + \"docker_torch.png\", caption=\"Dockerized PyTorch Model\")\nst.sidebar.text(\"With cloud based,\\nstate-dependent API requests:\")\nst.sidebar.image(IMG_FOLDER + \"test.png\", caption=\"Cloud Architecture\")\nst.sidebar.text(\"With frontend built in:\")\nst.sidebar.image(IMG_FOLDER + \"streamlit.png\")\nst.sidebar.text(\"Enjoy! :)\")\nst.sidebar.markdown(\"[Git Repo](https://github.com/matthewmcampbell/connect4RL)\")\n" ]
[ [ "numpy.zeros" ] ]
vhgnguyen/occlusion_behavior_planning
[ "33dea1fb9c5e3274e4482ca0d9eeb56f9beaa11e" ]
[ "src/stuffs/risk_functions.py" ]
[ "from scipy.stats import mvn\n\nimport numpy as np\nimport math\n\nimport _param as param\nimport gaussian as gaussian\n\n\ndef collisionEventSeverity(ego_vx, obj_vx, method='sigmoid', gom_rate=1,\n min_weight=param._SEVERITY_MIN_WEIGHT_CONST,\n quad_weight=param._SEVERITY_QUAD_WEIGHT,\n sig_vx=param._SEVERITY_SIG_AVG_VX,\n sig_max=param._SEVERITY_SIG_MAX,\n sig_beta=param._SEVERITY_SIG_B,\n gom_vx=param._SEVERITY_GOM_AVG_VX,\n gom_max=param._SEVERITY_GOM_MAX,\n gom_beta=param._SEVERITY_GOM_BETA):\n \"\"\"\n Collision event severity of ego vehicle with another object\n Args:\n ego_vx: longtitude velocity vector of vehicle in UTM\n obj_vx: longtitude velocity vector of object in UTM\n method: one of these ['constant', 'linear',\n 'quadratic', 'sigmoid', 'gompertz']\n Return:\n severity: collision event severity\n \"\"\"\n # assert ego_vx.shape == (2,) and obj_vx.shape == (2,)\n\n dv = ego_vx - obj_vx\n severity = 0.0\n if method == 'constant':\n severity = min_weight\n elif method == 'linear':\n severity = np.linalg.norm(dv)\n elif method == 'quadratic':\n severity = np.linalg.norm(dv)**2\n severity *= quad_weight\n severity += min_weight\n elif method == 'sigmoid':\n sig_dv = np.linalg.norm(dv) - sig_vx\n severity = sig_max\n severity /= (1.0 + np.exp(-sig_beta * sig_dv))\n severity += min_weight\n elif method == 'gompertz':\n gom_dv = np.linalg.norm(dv) - gom_vx\n severity = gom_max\n severity *= np.exp(-gom_beta*np.exp(-gom_rate*gom_dv))\n severity += min_weight\n else:\n severity = min_weight\n\n return severity\n\n\ndef collisionSeverityHypoVeh(ego_vx, obj_vx, method='sigmoid',\n quad_weight=param._SEVERITY_QUAD_WEIGHT,\n min_weight=param._SEVERITY_HYPOVEH_MIN_WEIGHT,\n sig_max=param._SEVERITY_HYPOVEH_SIG_MAX,\n sig_avg_vx=param._SEVERITY_HYPOVEH_AVG_VX,\n sig_beta=param._SEVERITY_HYPOVEH_SIG_B):\n \"\"\"\n Collision event severity of ego vehicle with hypthetical vehicle\n Args:\n ego_vx: longtitude velocity vector of vehicle in UTM\n obj_vx: longtitude velocity vector of object in UTM\n method: one of these ['constant', 'quadratic', 'sigmoid']\n Return:\n severity: collision event severity\n \"\"\"\n dv = ego_vx - obj_vx\n severity = 0.0\n if method == 'quadratic':\n severity = np.linalg.norm(dv)**2\n severity *= quad_weight\n severity += min_weight\n elif method == 'sigmoid':\n severity = sig_max\n sig_dv = np.linalg.norm(dv) - sig_avg_vx\n severity /= (1.0 + np.exp(-sig_beta * sig_dv))\n severity += min_weight\n else:\n severity = min_weight\n\n return severity\n\n\ndef collisionSeverityHypoPedes(ego_vx, obj_vx, method='gompertz',\n min_weight=param._SEVERITY_HYPOPEDES_MIN_WEIGHT,\n avg_vx=param._SEVERITY_HYPOPEDES_AVG_VX,\n sig_max=param._SEVERITY_HYPOPEDES_SIG_MAX,\n sig_beta=param._SEVERITY_HYPOPEDES_SIG_BETA,\n gom_max=param._SEVERITY_HYPOPEDES_GOM_MAX,\n gom_beta=param._SEVERITY_HYPOPEDES_GOM_BETA):\n \"\"\"\n Collision event severity of ego vehicle with hypthetical vehicle\n Args:\n ego_vx: longtitude velocity vector of vehicle in UTM\n obj_vx: longtitude velocity vector of object in UTM\n method: one of these ['constant', 'gompertz', 'sigmoid']\n Return:\n severity: collision event severity\n \"\"\"\n dv = ego_vx - obj_vx\n severity = 0.0\n if method == 'sigmoid':\n sig_dv = np.linalg.norm(dv) - avg_vx\n severity = sig_max\n severity /= (1.0 + np.exp(-sig_beta*sig_dv))\n severity += min_weight\n elif method == 'gompertz':\n gom_dv = np.linalg.norm(dv) - avg_vx\n severity = gom_max\n severity *= np.exp(-gom_beta*np.exp(-gom_dv))\n severity += min_weight\n else:\n severity = min_weight\n\n return severity\n\n\ndef collisionIndicatorComputeSimple(bound, dMean, dCov):\n \"\"\"\n Risk indicator function for collision\n by CDF of distance's PDF between two objects over minkowski polygon\n in orthogonal or parallel case\n Param:\n bound: min/max distance from (0, 0) to polygon's vertices\n dMean: (2,) vector mean distance between two objects\n dCov: (2,2) array covariance matrix of distance\n Return:\n I: (float) value of collision indicator\n \"\"\"\n # assert bound['max'].shape == (2,) and bound['min'].shape == (2,)\n # assert dMean.shape == (2,)\n # assert dCov.shape == (2, 2)\n\n # quick check for long distance\n if (dMean > 10).all():\n return 0\n else:\n prob, _ = mvn.mvnun(bound['min'], bound['max'], dMean, dCov)\n return prob\n\n\ndef collisionIndicatorCompute(poly, bound, dMean, dCov):\n \"\"\"\n Risk indicator function for collision\n by CDF of distance's PDF between two objects over minkowski polygon\n Param:\n poly: (n,2) array of minkowski polygon vertices\n bound: min/max distance from (0, 0) to polygon's vertices\n dMean: (2,) vector mean distance between two objects\n dCov: (2,2) array covariance matrix of distance\n Return:\n I: (float) value of collision indicator\n \"\"\"\n # assert poly.ndim == 2 and poly.shape[1] == 2\n # assert dMean.shape == (2,)\n # assert dCov.shape == (2, 2)\n\n # quick check for long distance\n if (dMean > 10).all():\n return 0\n else:\n return gaussian.polyIntegratePdf(poly, dMean, dCov)\n\n\ndef collisionIndicator(egoPose, egoPoly, objPose, objPoly):\n \"\"\"\n Indicator function for collision between ego vehicle and moving object\n Param:\n egoPose: ego vehicle\n objPose: pose of object\n Return:\n col_indicator: (float) collision indicator between two object\n \"\"\"\n dMean = np.array([egoPose.x_m-objPose.x_m,\n egoPose.y_m-objPose.y_m])\n dCov = egoPose.covUtm + objPose.covUtm\n diff_yaw = abs(egoPose.yaw_rad-objPose.yaw_rad)\n col_indicator = 0\n\n # handle parallel and orthogonal case\n if abs(math.remainder(diff_yaw, np.pi/2)) < param._COLLISION_ORTHO_THRES:\n poly, bound = gaussian.minkowskiSumOrthogonal(egoPoly, objPoly)\n col_indicator = collisionIndicatorComputeSimple(bound, dMean, dCov)\n\n # handle general case\n else:\n poly, bound = gaussian.minkowskiSum(egoPoly, objPoly)\n col_indicator = collisionIndicatorCompute(\n poly=poly,\n bound=bound,\n dMean=dMean,\n dCov=dCov)\n return col_indicator\n\n\ndef collisionEventRate(collisionIndicator,\n eventRate_max, exp_beta=param._COLLISION_RATE_EXP_BETA,\n sig_beta=param._COLLISION_RATE_SIG_BETA,\n method='exponential'):\n \"\"\"\n Function to calculate event rate\n Args:\n eventRate_max: maximal event rate\n eventRate_beta: slope weight\n collisionIndicator: indicator factor between [0,1]\n Return: (float) collision event rate\n \"\"\"\n # assert np.isscalar(eventRate_max) and eventRate_max >= 1.0\n # assert np.isscalar(eventRate_beta) and eventRate_beta > 0.0\n # assert np.isscalar(collisionIndicator) and 0.0 <= collisionIndicator <= 1.0\n if method == 'exponential':\n return eventRate_max \\\n * (1.0 - np.exp(-exp_beta*collisionIndicator)) \\\n / (1.0 - np.exp(-exp_beta))\n if method == 'sigmoid':\n t = max(collisionIndicator, 0.005)\n return eventRate_max / (1 + (t / (1-t))**(-sig_beta))\n\n\ndef collisionRisk(col_severity, col_rate):\n \"\"\"\n Risk function for collision between ego vehicle and moving object\n Param:\n col_rate: (float) collision rate of the event\n col_indicator: (float) collision indicator between two object\n Return:\n col_risk: (float) collision risk cost in a time point\n \"\"\"\n\n return col_rate * col_severity\n\n\ndef interactRate(a, b=param._AWARENESS_DISTANCE, k=1):\n return 1 - 1 / (1 + np.exp(k * (a-b)))\n\n\ndef limitViewRisk(fov_range, ego_vx, aBrake, dBrake, stdLon, tReact,\n rateMax=param._FOV_EVENTRATE_MAX,\n rateBeta=param._FOV_EVENTRATE_BETA,\n severity_min_weight=param._FOV_SEVERITY_MIN,\n severity_weight=param._FOV_SEVERITY_WEIGHT):\n ego_vx2 = ego_vx**2\n dReact = ego_vx*tReact\n dSafe = dBrake + stdLon + dReact\n sBrake_max = abs(0.5 * ego_vx2 / aBrake) + dSafe\n\n # event rate\n eventRate = rateMax\n eventRate *= 1 - 1 / (1 + rateBeta * np.exp(-(fov_range - sBrake_max)))\n # severity\n v_max2 = ego_vx2 + 2*aBrake*(fov_range - dReact)\n severity = severity_weight * max(v_max2, 0)\n severity += severity_min_weight\n # risk\n risk = eventRate * severity\n\n return eventRate, risk\n" ]
[ [ "numpy.exp", "numpy.array", "scipy.stats.mvn.mvnun", "numpy.linalg.norm" ] ]
wangyibin/biowy
[ "a534f35fc6f96fe1b3a6ca78853a5aa076337328" ]
[ "apps/numparse.py" ]
[ "#!/usr/bin/env python\n# -*- coding:utf-8 -*-\n\n\n\"\"\"\nA library of number parse.\n\"\"\"\nimport logging\nimport numpy as np\nimport os\nimport os.path as op\nimport sys\n\n#from scipy import stats\n\n\nclass OrdNum(object):\n \"\"\"\n Return the corresponding ordinal number of a number.\n Such as 21>21st; 11>11th; 3>3rd.\n \"\"\"\n\n def __init__(self, num):\n self.num = str(num)\n\n def __str__(self):\n\n if not self.num.isnumeric():\n print('Please input a number!')\n\n last2bits = int(str(self.num)[-2:])\n if (last2bits < 10) or (last2bits > 20):\n if last2bits % 10 == 1:\n suffix = 'st'\n elif last2bits % 10 == 2:\n suffix = 'nd'\n elif last2bits % 10 == 3:\n suffix = 'rd'\n else:\n suffix = 'th'\n else:\n suffix = 'th'\n\n ordnum = '%s%s' % (self.num, suffix)\n\n return ordnum\n\n __repr__ = __str__\n\ndef get_mode(numlist):\n \"\"\"\n Caculate the mode value of a lists by numpy.\n >>>get_mode(numlist)\n \"\"\"\n count = np.bincount(numlist)\n return np.argmax(count)\n\n\ndef get_median(numlist):\n \"\"\"\n Caculate the median value of a list by numpy.\n >>>get_median(numlist)\n \"\"\"\n return np.median(numlist)\n\n\ndef get_mean(numlist):\n \"\"\"\n Caculate the mean value of a list by numpy.\n >>>l = [1,4,5,6,7]\n >>>get_mean(l)\n 4.6\n \"\"\"\n return np.mean(numlist)\n\n\ndef factorial(n, end=1):\n \"\"\"\n \n \"\"\"\n\n if n < end:\n logging.debug(\"{} is \".format(n))\n elif n == end:\n return end \n else:\n return n*factorial(n-1,end)\n\n\n\n" ]
[ [ "numpy.median", "numpy.argmax", "numpy.mean", "numpy.bincount" ] ]
mwsmith2/recognit
[ "849c66754971a66a12b0b57d205a7873e0fb8eae" ]
[ "examples/quickplot.py" ]
[ "import os\n\nimport matplotlib\nmatplotlib.use('PDF')\nimport matplotlib.cm as cm\nimport matplotlib.pyplot as plt\nfrom sklearn.lda import LDA\nimport numpy as np\nfrom collections import defaultdict\nfrom scipy.spatial.distance import cdist\n\nfrom recognit import load\nfrom recognit import pca\nfrom recognit import predict\nfrom recognit import visual as vis\n\nbase = os.path.dirname(__file__)\npath = os.path.realpath(base + '/../data/faces')\n\n# Load faces from the path.\nfaces = load.Faces(path, 'pgm')\nfaces.set_params(seed=895, train=0.60, valid=0.15)\nfaces.get_labels()\n\nfaces.get_data(id=0, exclude={4: ['2', '4']})\nfaces.create_matrices()\n\n# Start principal component analysis.\nclf = pca.PCA(faces.xtrain)\nclf.find_principal_components()\nclf.transform()\n\nres = 0\ntrait = 0\n\nd = []\nx1 = []\nx2 = []\n\nfor i in range(len(faces.yvalid)):\n\ts = clf.project(faces.xvalid[:, i])\n\td.append(np.min(cdist(clf.xtransform.T, s.T, \"mahalanobis\")))\n\tx1.append(s[0])\n\tx2.append(s[1])\n\nfor trait in range(4):\n\tprefix = 'res_' + str(res) + '_trait_' + str(trait) + '_'\n\tfaces.set_params(seed=895, train=0.60, valid=0.15)\n\tfaces.get_data(id=trait, exclude={4: ['2', '4']})\n\tfaces.create_matrices()\n\tfaceweights = defaultdict(list)\n\t\n\tfor i, y in enumerate(faces.yvalid):\n\t\tfaceweights[y].append([x1[i], x2[i], d[i]])\n\n\tfn = prefix + \"face_scatter_w\" + str(1) + \"_v_w\" + str(2) + \".pdf\"\n\ttitle = r'Principal Components: $\\omega_1$ vs. $\\omega_2$'\n\tvis.scatter_face(title, faceweights, filename=fn)\n\n" ]
[ [ "matplotlib.use", "scipy.spatial.distance.cdist" ] ]
2326wz/sharp-in
[ "520056ed923f1eb0b8bf8e06b0e959ff0ce73997" ]
[ "telegram-bot/core/unet/u_net.py" ]
[ "from tensorflow.keras import Model\nfrom tensorflow.keras.layers import Input, Concatenate, Convolution2D, MaxPooling2D, UpSampling2D\nfrom pathlib import Path\nfrom tensorflow.keras.optimizers import Adam\nimport cv2\nimport os\nimport time\nimport numpy as np\nfrom core.config import get_config\n\ncrop_size = get_config().crop_size\n \ndef define_unet(img_rows, img_cols, optimizer):\n ''' Defines U-net with img_rows*img_cols input.\n Output: Keras Model.'''\n \n inputs = Input(shape=(img_rows, img_cols, 3))\n conv1 = Convolution2D(32, (3, 3), activation='relu', padding='same')(inputs)\n conv1 = Convolution2D(32, (3, 3), activation='relu', padding='same')(conv1)\n pool1 = MaxPooling2D(pool_size=(2, 2))(conv1)\n\n conv2 = Convolution2D(64, (3, 3), activation='relu', padding='same')(pool1)\n conv2 = Convolution2D(64, (3, 3), activation='relu', padding='same')(conv2)\n pool2 = MaxPooling2D(pool_size=(2, 2))(conv2)\n\n conv3 = Convolution2D(128, (3, 3), activation='relu', padding='same')(pool2)\n conv3 = Convolution2D(128, (3, 3), activation='relu', padding='same')(conv3)\n pool3 = MaxPooling2D(pool_size=(2, 2))(conv3)\n\n conv4 = Convolution2D(256, (3, 3), activation='relu', padding='same')(pool3)\n conv4 = Convolution2D(256, (3, 3), activation='relu', padding='same')(conv4)\n pool4 = MaxPooling2D(pool_size=(2, 2))(conv4)\n\n conv5 = Convolution2D(512, (3, 3), activation='relu', padding='same')(pool4)\n conv5 = Convolution2D(512, (3, 3), activation='relu', padding='same')(conv5)\n \n up6 = Concatenate()([Convolution2D(256, (2, 2), activation='relu', padding='same')(UpSampling2D(size=(2, 2))(conv5)), conv4])\n conv6 = Convolution2D(256, (3, 3), activation='relu', padding='same')(up6)\n conv6 = Convolution2D(256, (3, 3), activation='relu', padding='same')(conv6)\n\n up7 = Concatenate()([Convolution2D(128, (2, 2),activation='relu', padding='same')(UpSampling2D(size=(2, 2))(conv6)), conv3])\n conv7 = Convolution2D(128, (3, 3), activation='relu', padding='same')(up7)\n conv7 = Convolution2D(128, (3, 3), activation='relu', padding='same')(conv7)\n\n up8 = Concatenate()([Convolution2D(64, (2, 2),activation='relu', padding='same')(UpSampling2D(size=(2, 2))(conv7)), conv2])\n conv8 = Convolution2D(64, (3, 3), activation='relu', padding='same')(up8)\n conv8 = Convolution2D(64, (3, 3), activation='relu', padding='same')(conv8)\n\n up9 = Concatenate()([Convolution2D(32, (2, 2),activation='relu', padding='same')(UpSampling2D(size=(2, 2))(conv8)), conv1])\n conv9 = Convolution2D(32, (3, 3), activation='relu', padding='same')(up9)\n conv9 = Convolution2D(32, (3, 3), activation='relu', padding='same')(conv9)\n\n conv10 = Convolution2D(3, (1, 1), activation='sigmoid')(conv9)\n\n model = Model(inputs=inputs, outputs=conv10)\n\n model.compile(optimizer=optimizer, loss='mse', metrics=['mse'])\n\n return model\n \n \ndef image_prediction(unet, fpath, fname):\n\n ''' Split and predict input image.\n Input: U-net Model, file path, file name.\n Output: list of filenames:\n [0] - predicted image of the same size.\n [1] - predicted image of the same size with painted splitting lines.\n [2:]- predicted crops of U-net in-out size.'''\n \n # load img\n img = cv2.imread(str(Path(fpath,fname)))\n img_y, img_x, _ = img.shape\n\n # divide for crop_size squares, write to array\n min_size = min(img_x, img_y)\n\n if min_size<crop_size:\n zoom = crop_size/min_size\n new_x = int(img_x*zoom)\n new_y = int(img_y*zoom)\n img = cv2.resize(img,(new_x, new_y))\n img_y, img_x, _ = img.shape\n\n if img_x!=crop_size:\n n_crops_x = int(img_x/crop_size)\n dx = int((img_x - n_crops_x*crop_size)/n_crops_x) # смещение X для каждого кадра\n else:\n n_crops_x=0\n dx=0\n\n if img_y!=crop_size:\n n_crops_y = int(img_y/crop_size)\n dy = int((img_y - n_crops_y*crop_size)/n_crops_y) # смещение Y для каждого кадра\n else:\n n_crops_y=0\n dy=0\n \n res_img = np.zeros_like(img)\n\n xmin=0\n ymax=0\n img_n=0\n shapes = np.zeros(((n_crops_x+1)*(n_crops_y+1), 4),'int')\n\n for x in range(n_crops_x):\n xmax = xmin + crop_size\n ymin=0 \n for y in range(n_crops_y):\n ymax = ymin + crop_size\n shapes[img_n,:] = [xmin, xmax, ymin, ymax]\n img_n+=1\n ymin = ymax - dy\n ymin = img_y - crop_size\n ymax = img_y \n shapes[img_n,:] = [xmin, xmax, ymin, ymax]\n img_n+=1\n xmin = xmax - dx\n xmin = img_x - crop_size\n xmax = img_x\n ymin=0 \n for y in range(n_crops_y):\n ymax = ymin + crop_size\n shapes[img_n,:] = [xmin, xmax, ymin, ymax]\n img_n+=1\n ymin = ymax - dy\n ymin = img_y - crop_size\n ymax = img_y \n shapes[img_n,:] = [xmin, xmax, ymin, ymax]\n img_n+=1\n\n # predict\n result_fnames=[]\n result_fnames.append('pred_res_'+fname) # [0]\n result_fnames.append('pred_net_'+fname) # [1]\n \n # save predicted crops\n for rec in range(shapes.shape[0]):\n xmin, xmax, ymin, ymax = shapes[rec,:]\n X = img[ymin:ymax, xmin:xmax, :]\n X = np.expand_dims(X,0) \n y_pred = unet.predict(X/255.) \n cv2.imwrite(str(Path(fpath,'pred_'+str(rec)+'_'+fname)), (y_pred[0,]*255.).astype('uint8'))\n result_fnames.append('pred_'+str(rec)+'_'+fname) # [2:]\n res_img[ymin:ymax, xmin:xmax, :] = (y_pred[0,]*255.).astype('uint8')\n\n # plot lines\n for rec in range(shapes.shape[0]):\n xmin, xmax, ymin, ymax = shapes[rec,:] \n img = cv2.line(img, (xmin,ymin), (xmin,ymax), (0,255,255), 3)\n img = cv2.line(img, (xmin,ymin), (xmax,ymin), (0,255,255), 3)\n img = cv2.line(img, (xmax,ymin), (xmax,ymax), (0,255,255), 3)\n img = cv2.line(img, (xmin,ymax), (xmax,ymax), (0,255,255), 3)\n cv2.imwrite(str(Path(fpath,'pred_net_'+fname)), img) \n \n # save joined prediction\n cv2.imwrite(str(Path(fpath,'pred_res_'+fname)), res_img) \n \n return result_fnames\n\n \n\ndef image_preprocess(bot, unet, save_path, save_name, chat_id=False):\n ''' Manage input image prediction process and operate TG bot if (chat_id != False).\n Output: None'''\n\n # message: user waits\n if chat_id: bot.send_message(chat_id, 'Картинка получена, ожидайте.')\n \n # predict image, get list of files\n result_fnames = image_prediction(unet, save_path, save_name)\n \n if len(result_fnames)>4:\n \n # several crops predicted \n for file in result_fnames:\n capt='' \n if file == result_fnames[1]: \n capt = 'Это схема деления вашей картинки, дальше идут обработанные фрагменты - всего будет %s шт по 512х512 пикс.' % str(len(result_fnames)-2)\n if file == result_fnames[0]: \n capt = 'Это обработанная картинка.'\n \n photo = open(Path(save_path, file), 'rb')\n if chat_id: bot.send_photo(chat_id, photo, caption = capt)\n del photo\n \n else:\n \n # only one crop predicted\n capt = 'Это обработанная картинка.'\n photo = open(Path(save_path, result_fnames[0]), 'rb')\n if chat_id: bot.send_photo(chat_id, photo, caption = capt)\n del photo\n \n result_fnames.append(save_name)\n\n return result_fnames\n \n" ]
[ [ "tensorflow.keras.layers.Concatenate", "numpy.expand_dims", "tensorflow.keras.layers.UpSampling2D", "tensorflow.keras.Model", "numpy.zeros_like", "tensorflow.keras.layers.Convolution2D", "tensorflow.keras.layers.MaxPooling2D", "numpy.zeros", "tensorflow.keras.layers.Input" ] ]
joleroi/gammapy
[ "c4e0c4bd74c79d30e0837559d18b7a1a269f70d9" ]
[ "gammapy/scripts/iterative_source_detect.py" ]
[ "# Licensed under a 3-clause BSD style license - see LICENSE.rst\nfrom __future__ import (absolute_import, division, print_function,\n unicode_literals)\nfrom ..utils.scripts import get_parser\n\n__all__ = ['iterative_source_detect']\n\n\ndef main(args=None):\n parser = get_parser(iterative_source_detect)\n parser.add_argument('scales', type=float, nargs='*', default=[0.1, 0.2, 0.4],\n help='List of spatial scales (deg) to search for sources')\n parser.add_argument('--counts', type=str, default='counts.fits',\n help='Counts FITS file name')\n parser.add_argument('--background', type=str, default='background.fits',\n help='Background FITS file name')\n parser.add_argument('--exposure', type=str, default='exposure.fits',\n help='Exposure FITS file name')\n parser.add_argument('--output_fits', type=str, default='detections.fits',\n help='Output catalog of detections (FITS table format)')\n parser.add_argument('--output_regions', type=str, default='detections.reg',\n help='Output catalog of detections (ds9 region file format)')\n parser.add_argument('--debug_output_folder', type=str, default='',\n help='Debug output folder name (empty string for no output)')\n parser.add_argument('--overwrite', action='store_true',\n help='Overwrite existing output file?')\n args = parser.parse_args(args)\n iterative_source_detect(**vars(args))\n\n\ndef iterative_source_detect(scales,\n counts,\n background,\n exposure,\n output_fits,\n output_regions,\n debug_output_folder,\n overwrite):\n \"\"\"Run an iterative multi-scale source detection.\n \"\"\"\n from collections import OrderedDict\n import numpy as np\n from astropy.io import fits\n from ..detect import IterativeSourceDetector\n import logging\n logging.basicConfig(level=logging.DEBUG, format='%(levelname)s - %(message)s')\n\n # Load data\n maps = OrderedDict()\n maps['counts'] = counts\n maps['background'] = background\n maps['exposure'] = exposure\n for mapname, filename in maps.items():\n logging.info('Reading {0} map: {1}'.format(mapname, filename))\n maps[mapname] = fits.getdata(filename)\n\n # Compute scales in pixel coordinates\n DEG_PER_PIX = np.abs(fits.getval(counts, 'CDELT1'))\n scales_deg = scales\n scales_pix = np.array(scales_deg) / DEG_PER_PIX\n logging.info('Number of scales: {0}'.format(len(scales_deg)))\n logging.info('DEG_PER_PIX: {0}'.format(DEG_PER_PIX))\n logging.info('Scales in deg: {0}'.format(scales_deg))\n logging.info('Scales in pix: {0}'.format(scales_pix))\n\n # Run the iterative source detection\n detector = IterativeSourceDetector(maps=maps,\n scales=scales_pix,\n debug_output_folder=debug_output_folder,\n overwrite=overwrite)\n detector.run()\n\n # Save the results\n # detector.save_fits(output_fits)\n detector.save_regions(output_regions)\n # detector.save_json('detect.json')\n" ]
[ [ "numpy.array" ] ]
Jeanca64091/CoronavirusML
[ "867f8e72579c60001719ede7211b86743c669fe6", "867f8e72579c60001719ede7211b86743c669fe6" ]
[ "2020-11/20080862.py", "2020-11/201503821.py" ]
[ "from sklearn.linear_model import LinearRegression \nfrom sklearn.preprocessing import PolynomialFeatures \nfrom sklearn.metrics import mean_squared_error, r2_score\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport random\n\n#----------------------------------------------------------------------------------------#\n# Step 1: training data\n\nX = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30]\nY = [0,1,2,3,6,6,8,9,13,17,19,20,21,24,25,32,34,36,39,46,47,50,61,70,74,80,87,126,139,153,156]\n\nX = np.asarray(X)\nY = np.asarray(Y)\n\nX = X[:,np.newaxis]\nY = Y[:,np.newaxis]\n\nplt.scatter(X,Y)\n\n#plt.show()\n\n\n\n#----------------------------------------------------------------------------------------#\n# Step 2: data preparation\n\nnb_degree = 3\n\npolynomial_features = PolynomialFeatures(degree = nb_degree)\n#print(X)\nX_TRANSF = polynomial_features.fit_transform(X)\n\n#----------------------------------------------------------------------------------------#\n# Step 3: define and train a model\n\nmodel = LinearRegression()\n\nmodel.fit(X_TRANSF, Y)\n\n#----------------------------------------------------------------------------------------#\n# Step 4: calculate bias and variance\n\nY_NEW = model.predict(X_TRANSF)\n\nrmse = np.sqrt(mean_squared_error(Y,Y_NEW))\nr2 = r2_score(Y,Y_NEW)\n\nprint('RMSE: ', rmse)\nprint('R2: ', r2)\n\n#----------------------------------------------------------------------------------------#\n# Step 5: prediction\n\nx_new_min = 0.0\nx_new_max = 50.0\n\nX_NEW = np.linspace(x_new_min, x_new_max, 50)\nX_NEW = X_NEW[:,np.newaxis]\n\nX_NEW_TRANSF = polynomial_features.fit_transform(X_NEW)\n\nY_NEW = model.predict(X_NEW_TRANSF)\n\nplt.plot(X_NEW, Y_NEW, color='coral', linewidth=3)\n\nplt.grid()\nplt.xlim(x_new_min,x_new_max)\nplt.ylim(0,1000)\n\ntitle = 'Degree = {}; RMSE = {}; R2 = {}'.format(nb_degree, round(rmse,2), round(r2,2))\n\nplt.title(\"Polynomial Linear Regression using scikit-learn and python 3 \\n \" + title,\n fontsize=10)\nplt.xlabel('x')\nplt.ylabel('y')\n\nplt.savefig(\"polynomial_linear_regression.png\", bbox_inches='tight')\nplt.show()\n", "from sklearn.linear_model import LinearRegression\nfrom sklearn.preprocessing import PolynomialFeatures\nfrom sklearn.metrics import mean_squared_error, r2_score\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport random\n\n# _______________________________________________________________________ \n# Step 1: Entrenar data\n\n#https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_confirmed_global.csv\n# 05/03/20 -> dia 0\n# 11/08/20 -> dia 248\n\nX = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,161,162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213,214,215,216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,240,241,242,243,244,245,246,247,248]\nY = [0,1,1,5,9,9,13,22,23,26,27,35,41,50,69,89,117,134,158,177,201,231,263,295,314,330,347,375,396,416,435,454,467,483,502,539,558,577,595,612,618,626,642,649,655,660,662,669,681,686,687,693,695,697,705,713,719,725,733,739,742,755,761,765,773,780,792,801,804,815,830,843,853,863,866,882,897,903,911,918,930,951,956,984,1000,1022,1047,1056,1084,1105,1157,1194,1228,1263,1318,1342,1375,1461,1538,1612,1662,1715,1744,1796,1871,1939,2058,2127,2213,2277,2368,2515,2684,2836,2979,3130,3269,3459,3753,4023,4311,4621,4996,5241,5486,5836,6485,6845,7231,7596,8036,8482,8986,9546,9969,10551,11114,11534,11811,12361,13129,13669,14600,15229,15841,16344,16800,17290,17820,18187,18975,19402,19837,20417,21070,22081,22802,23286,23872,24508,25057,26129,26931,27737,28465,29084,29643,30409,31075,32134,33084,33820,34463,35305,36307,37292,38485,39699,39699,41287,42184,43305,44458,45680,46920,46920,48780,49897,51224,52549,53969,55454,55454,57361,58137,59516,60818,62374,63712,63712,65602,66689,68059,69459,70816,72049,72049,73714,74604,75760,76828,77829,79182,79182,81129,82142,83497,84828,86053,87439,87439,89223,90238,91780,93152,94348,95514,95514,97075,97922,99425,100616,101826,103088,103088,104460,105322,106553,107570,108866,109971,109971,111257,112120,113261,114367,115417,116363,116363]\n\nX = np.asarray(X)\nY = np.asarray(Y)\n\nX = X[:,np.newaxis]\nY = Y[:,np.newaxis]\n\nplt.scatter(X,Y) \n#plt.show()\n\n# _________________________________________________________________ \n# Step 2: Predecir data\n\nnb_degree = 4\npolynomial_features = PolynomialFeatures(degree = nb_degree) \n#print(X) \nX_TRANSF = polynomial_features.fit_transform(X) \n\n# _________________________________________________________________ \n# Step 3: Definir y entrenar modelo\n\nmodel = LinearRegression() \nmodel.fit(X_TRANSF, Y) \n\n# _________________________________________________________________ \n# Step 4: Calcular varianza\n\nY_NEW = model.predict(X_TRANSF) \nrmse = np.sqrt(mean_squared_error(Y,Y_NEW)) \nr2 = r2_score(Y,Y_NEW) \n\nprint('RMSE: ', rmse) \nprint('R2: ', r2)\n\n# _________________________________________________________________ \n# Step 5: Prediccion\n\nx_new_min = 0.0 \nx_new_max = 300.0\n\nX_NEW = np.linspace(x_new_min, x_new_max, 50) \nX_NEW = X_NEW[:,np.newaxis] \n\nX_NEW_TRANSF = polynomial_features.fit_transform(X_NEW) \nY_NEW = model.predict(X_NEW_TRANSF) \n\nplt.plot(X_NEW, Y_NEW, color='coral', linewidth=3) \n\nplt.grid() \nplt.xlim(x_new_min,x_new_max) \nplt.ylim(0,170000) \n\ntitle = 'Degree = {}; RMSE = {}; R2 = {}'.format(nb_degree, round(rmse,2), round(r2,2))\nplt.title('Costa Rica \\n ' + title, fontsize=10)\nplt.xlabel('Days') \nplt.ylabel('Infecteds') \nplt.savefig(\"201503821.png\", bbox_inches='tight') \nplt.show()\n" ]
[ [ "sklearn.metrics.r2_score", "matplotlib.pyplot.scatter", "numpy.linspace", "numpy.asarray", "matplotlib.pyplot.ylim", "matplotlib.pyplot.title", "sklearn.preprocessing.PolynomialFeatures", "matplotlib.pyplot.savefig", "sklearn.metrics.mean_squared_error", "matplotlib.pyplot.plot", "matplotlib.pyplot.xlim", "sklearn.linear_model.LinearRegression", "matplotlib.pyplot.grid", "matplotlib.pyplot.xlabel", "matplotlib.pyplot.show", "matplotlib.pyplot.ylabel" ], [ "sklearn.metrics.r2_score", "matplotlib.pyplot.scatter", "numpy.linspace", "numpy.asarray", "matplotlib.pyplot.ylim", "matplotlib.pyplot.title", "sklearn.preprocessing.PolynomialFeatures", "matplotlib.pyplot.savefig", "sklearn.metrics.mean_squared_error", "matplotlib.pyplot.plot", "matplotlib.pyplot.xlim", "sklearn.linear_model.LinearRegression", "matplotlib.pyplot.grid", "matplotlib.pyplot.xlabel", "matplotlib.pyplot.show", "matplotlib.pyplot.ylabel" ] ]
ankitshah009/argus-freesound
[ "4faf8f192035b413e8946bda3555474cb9ad8237" ]
[ "src/argus_models.py" ]
[ "import torch\n\nfrom argus import Model\nfrom argus.utils import deep_detach, deep_to\n\nfrom src.models import resnet\nfrom src.models import senet\nfrom src.models.feature_extractor import FeatureExtractor\nfrom src.models.simple_kaggle import SimpleKaggle\nfrom src.models.simple_attention import SimpleAttention\nfrom src.models.skip_attention import SkipAttention\nfrom src.models.aux_skip_attention import AuxSkipAttention\nfrom src.models.rnn_aux_skip_attention import RnnAuxSkipAttention\nfrom src.losses import OnlyNoisyLqLoss, OnlyNoisyLSoftLoss, BCEMaxOutlierLoss\nfrom src import config\n\n\nclass FreesoundModel(Model):\n nn_module = {\n 'resnet18': resnet.resnet18,\n 'resnet34': resnet.resnet34,\n 'FeatureExtractor': FeatureExtractor,\n 'SimpleKaggle': SimpleKaggle,\n 'se_resnext50_32x4d': senet.se_resnext50_32x4d,\n 'SimpleAttention': SimpleAttention,\n 'SkipAttention': SkipAttention,\n 'AuxSkipAttention': AuxSkipAttention,\n 'RnnAuxSkipAttention': RnnAuxSkipAttention\n }\n loss = {\n 'OnlyNoisyLqLoss': OnlyNoisyLqLoss,\n 'OnlyNoisyLSoftLoss': OnlyNoisyLSoftLoss,\n 'BCEMaxOutlierLoss': BCEMaxOutlierLoss\n }\n prediction_transform = torch.nn.Sigmoid\n\n def __init__(self, params):\n super().__init__(params)\n\n if 'aux' in params:\n self.aux_weights = params['aux']['weights']\n else:\n self.aux_weights = None\n\n self.use_amp = not config.kernel and 'amp' in params\n if self.use_amp:\n from apex import amp\n self.amp = amp\n self.nn_module, self.optimizer = self.amp.initialize(\n self.nn_module, self.optimizer,\n opt_level=params['amp']['opt_level'],\n keep_batchnorm_fp32=params['amp']['keep_batchnorm_fp32'],\n loss_scale=params['amp']['loss_scale']\n )\n\n def train_step(self, batch, state) -> dict:\n if not self.nn_module.training:\n self.nn_module.train()\n self.optimizer.zero_grad()\n input, target, noisy = deep_to(batch, self.device, non_blocking=True)\n prediction = self.nn_module(input)\n if self.aux_weights is not None:\n loss = 0\n for pred, weight in zip(prediction, self.aux_weights):\n loss += self.loss(pred, target, noisy) * weight\n else:\n loss = self.loss(prediction, target, noisy)\n if self.use_amp:\n with self.amp.scale_loss(loss, self.optimizer) as scaled_loss:\n scaled_loss.backward()\n else:\n loss.backward()\n self.optimizer.step()\n\n prediction = deep_detach(prediction)\n target = deep_detach(target)\n return {\n 'prediction': self.prediction_transform(prediction[0]),\n 'target': target,\n 'loss': loss.item(),\n 'noisy': noisy\n }\n\n def val_step(self, batch, state) -> dict:\n if self.nn_module.training:\n self.nn_module.eval()\n with torch.no_grad():\n input, target, noisy = deep_to(batch, self.device, non_blocking=True)\n prediction = self.nn_module(input)\n if self.aux_weights is not None:\n loss = 0\n for pred, weight in zip(prediction, self.aux_weights):\n loss += self.loss(pred, target, noisy) * weight\n else:\n loss = self.loss(prediction, target, noisy)\n return {\n 'prediction': self.prediction_transform(prediction[0]),\n 'target': target,\n 'loss': loss.item(),\n 'noisy': noisy\n }\n\n def predict(self, input):\n assert self.predict_ready()\n with torch.no_grad():\n if self.nn_module.training:\n self.nn_module.eval()\n input = deep_to(input, self.device)\n prediction = self.nn_module(input)\n if self.aux_weights is not None:\n prediction = prediction[0]\n prediction = self.prediction_transform(prediction)\n return prediction\n" ]
[ [ "torch.no_grad" ] ]
siouxmathware/ijsbeer-ai
[ "35b47a7735bb29dd0018b09ece683f57d8da0585" ]
[ "models/nlp/mocks/mock_bert.py" ]
[ "from models.nlp.mocks import mock_bert_layer, mock_tokenizer\nimport numpy as np\n\n\nclass MockHistory:\n def __init__(self, categories):\n all_categories = categories + ['loss']\n all_categories = all_categories + [f'val_{cat}' for cat in all_categories]\n self.history = {cat.lower(): [i] for i, cat in enumerate(all_categories)}\n\n\nclass MockBertModel:\n def __init__(self, nr_categories, config, bert_trainable, topping_sizes):\n self.nr_categories = nr_categories\n self.nr_tags = 2*nr_categories + 1 + 1\n self.config = config\n self.bert_trainable = bert_trainable\n self.topping_sizes = topping_sizes\n self.layers = [mock_bert_layer.MockBertLayer()]\n self.output_shape = [self.nr_tags]\n self.loss = None\n self.optimzer = None\n self.metrics = None\n self.tokenizer = mock_tokenizer.MockTokenizer()\n self.max_length = 512\n\n def summary(self, print_fn=None):\n print_fn = print_fn if print_fn is not None else print\n print_fn(f'This is a mocked BERT with {self.nr_categories} categories')\n\n def compile(self, loss, optimizer, metrics, **kwargs):\n self.loss = loss\n self.optimzer = optimizer\n self.metrics = metrics\n\n def fit(self, **kwargs):\n print(\"TRAINING the mocked BERT\")\n history = MockHistory([self.get_name(metric) for metric in self.metrics])\n return history\n\n @staticmethod\n def get_name(metric):\n if isinstance(metric, str):\n return metric\n else:\n return metric.name\n\n def __call__(self, x):\n tokens = x[0]\n result = np.zeros(tokens.shape + (self.nr_tags,))\n for i, row in enumerate(tokens):\n result[i, :, i % self.nr_tags] = 1\n return result\n\n\ndef get_bert_ner_model(nr_categories, config, bert_trainable, topping_sizes):\n model = MockBertModel(nr_categories, config, bert_trainable, topping_sizes)\n return model\n" ]
[ [ "numpy.zeros" ] ]
Sindhuja-R-21/class-110
[ "cf87dd5225ea49a55f4ecbab2778893f936e0eee" ]
[ "main.py" ]
[ "import plotly.figure_factory as ff\nimport plotly.graph_objects as go\nimport statistics\nimport random\nimport pandas as pd\nimport csv\n\ndf=pd.read_csv(\"data.csv\")\ndata=df[\"temp\"].to_list()\npopulation_mean=statistics.mean(data)\nstd_deviation=statistics.stdev(data)\nprint(\"Population Mean = \",population_mean)\nprint(\"Std_deviation=\",std_deviation)\n\n\ndef random_set_of_means():\n\n dataset=[]\n\n for i in range(0,100):\n random_index=random.randint(0,len(data))\n value=data[random_index]\n dataset.append(value)\n\n mean=statistics.mean(dataset)\n return mean\n\n\n\ndef show_fig(mean_list):\n df=mean_list\n fig=ff.create_distplot([df],[\"temp\"],show_hist=False)\n fig.show()\n\n\ndef setup():\n mean_list=[]\n for i in range(0,1000):\n set_of_means=random_set_of_means()\n mean_list.append(set_of_means)\n show_fig(mean_list)\n\n\nsetup()\n\n\n" ]
[ [ "pandas.read_csv" ] ]
hvy/optuna-core
[ "be9df49424aa4022cfcec7d9423768cc39c73ae6" ]
[ "optuna_core/samplers/_random.py" ]
[ "from typing import Any\nfrom typing import Dict\nfrom typing import Optional\n\nimport numpy\n\nimport optuna_core\nfrom optuna_core import distributions\nfrom optuna_core.distributions import BaseDistribution\nfrom optuna_core.samplers._base import BaseSampler\nfrom optuna_core.trial import FrozenTrial\n\n\nclass RandomSampler(BaseSampler):\n \"\"\"Sampler using random sampling.\n\n This sampler is based on *independent sampling*.\n See also :class:`~optuna.samplers.BaseSampler` for more details of 'independent sampling'.\n\n Example:\n\n .. testcode::\n\n import optuna\n from optuna.samplers import RandomSampler\n\n\n def objective(trial):\n x = trial.suggest_uniform(\"x\", -5, 5)\n return x ** 2\n\n\n study = optuna.create_study(sampler=RandomSampler())\n study.optimize(objective, n_trials=10)\n\n Args:\n seed: Seed for random number generator.\n \"\"\"\n\n def __init__(self, seed: Optional[int] = None) -> None:\n\n self._rng = numpy.random.RandomState(seed)\n\n def reseed_rng(self) -> None:\n\n self._rng = numpy.random.RandomState()\n\n def infer_relative_search_space(\n self, study: \"optuna_core.study.Study\", trial: FrozenTrial\n ) -> Dict[str, BaseDistribution]:\n\n return {}\n\n def sample_relative(\n self,\n study: \"optuna_core.study.Study\",\n trial: FrozenTrial,\n search_space: Dict[str, BaseDistribution],\n ) -> Dict[str, Any]:\n\n return {}\n\n def sample_independent(\n self,\n study: \"optuna_core.study.Study\",\n trial: FrozenTrial,\n param_name: str,\n param_distribution: distributions.BaseDistribution,\n ) -> Any:\n\n if isinstance(param_distribution, distributions.UniformDistribution):\n return self._rng.uniform(param_distribution.low, param_distribution.high)\n elif isinstance(param_distribution, distributions.LogUniformDistribution):\n log_low = numpy.log(param_distribution.low)\n log_high = numpy.log(param_distribution.high)\n return float(numpy.exp(self._rng.uniform(log_low, log_high)))\n elif isinstance(param_distribution, distributions.DiscreteUniformDistribution):\n q = param_distribution.q\n r = param_distribution.high - param_distribution.low\n # [low, high] is shifted to [0, r] to align sampled values at regular intervals.\n low = 0 - 0.5 * q\n high = r + 0.5 * q\n s = self._rng.uniform(low, high)\n v = numpy.round(s / q) * q + param_distribution.low\n # v may slightly exceed range due to round-off errors.\n return float(min(max(v, param_distribution.low), param_distribution.high))\n elif isinstance(param_distribution, distributions.IntUniformDistribution):\n # [low, high] is shifted to [0, r] to align sampled values at regular intervals.\n r = (param_distribution.high - param_distribution.low) / param_distribution.step\n # numpy.random.randint includes low but excludes high.\n s = self._rng.randint(0, r + 1)\n v = s * param_distribution.step + param_distribution.low\n return int(v)\n elif isinstance(param_distribution, distributions.IntLogUniformDistribution):\n log_low = numpy.log(param_distribution.low - 0.5)\n log_high = numpy.log(param_distribution.high + 0.5)\n s = numpy.exp(self._rng.uniform(log_low, log_high))\n v = numpy.round(s)\n return int(min(max(v, param_distribution.low), param_distribution.high))\n elif isinstance(param_distribution, distributions.CategoricalDistribution):\n choices = param_distribution.choices\n index = self._rng.randint(0, len(choices))\n return choices[index]\n else:\n raise NotImplementedError\n" ]
[ [ "numpy.round", "numpy.log", "numpy.random.RandomState" ] ]
pysimu/pysimu
[ "646432bc96be199165b112a77b5ff650b97152ba", "646432bc96be199165b112a77b5ff650b97152ba" ]
[ "examples/notebooks/smib_milano_ex8p1_v1/smib_milano_ex8p1_avr_pss.py", "pysimu/ssa.py" ]
[ "import numpy as np\nimport numba\nfrom pysimu.nummath import interp\n\n\nclass smib_milano_ex8p1_avr_pss_class: \n def __init__(self): \n\n self.t_end = 20.000000 \n self.Dt = 0.001000 \n self.decimation = 10.000000 \n self.itol = 0.000000 \n self.solvern = 1 \n self.imax = 100 \n self.N_x = 7 \n self.N_y = 12 \n self.update() \n\n def update(self): \n\n self.N_steps = int(np.ceil(self.t_end/self.Dt)) \n self.N_store = int(np.ceil(self.N_steps/self.decimation))\n dt = [ \n ('t_end', np.float64),\n ('Dt', np.float64),\n ('decimation', np.float64),\n ('itol', np.float64),\n ('solvern', np.int64),\n ('imax', np.int64),\n ('N_steps', np.int64),\n ('N_store', np.int64),\n ('X_d', np.float64),\n ('X1d', np.float64),\n ('T1d0', np.float64),\n ('X_q', np.float64),\n ('X1q', np.float64),\n ('T1q0', np.float64),\n ('R_a', np.float64),\n ('X_l', np.float64),\n ('H', np.float64),\n ('D', np.float64),\n ('Omega_b', np.float64),\n ('v_0', np.float64),\n ('theta_0', np.float64),\n ('T_r', np.float64),\n ('K_a', np.float64),\n ('T_pss_1', np.float64),\n ('T_pss_2', np.float64),\n ('T_w', np.float64),\n ('K_stab', np.float64),\n ('p_m', np.float64),\n ('v_ref', np.float64),\n ('N_x', np.int64),\n ('idx', np.int64),\n ('f', np.float64, (7,1)),\n ('x', np.float64, (7,1)),\n ('x_0', np.float64, (7,1)),\n ('h', np.float64, (1,1)),\n ('Fx', np.float64, (7,7)),\n ('T', np.float64, (self.N_store+1,1)),\n ('X', np.float64, (self.N_store+1,7)),\n ] \n\n values = [\n self.t_end,\n self.Dt,\n self.decimation,\n self.itol,\n self.solvern,\n self.imax,\n self.N_steps,\n self.N_store,\n 1.81, # X_d \n 0.3, # X1d \n 8.0, # T1d0 \n 1.76, # X_q \n 0.65, # X1q \n 1.0, # T1q0 \n 0.003, # R_a \n 0.5, # X_l \n 3.5, # H \n 1.0, # D \n 314.1592653589793, # Omega_b \n 1.0, # v_0 \n 0.0, # theta_0 \n 0.05, # T_r \n 200.0, # K_a \n 0.154, # T_pss_1 \n 0.033, # T_pss_2 \n 5.0, # T_w \n 10, # K_stab \n 0.2, # p_m \n 1.0, # v_ref \n 7,\n 0,\n np.zeros((7,1)),\n np.zeros((7,1)),\n np.zeros((7,1)),\n np.zeros((1,1)),\n np.zeros((7,7)),\n np.zeros((self.N_store+1,1)),\n np.zeros((self.N_store+1,7)),\n ] \n ini_struct(dt,values)\n\n dt += [('t', np.float64)]\n values += [0.0]\n\n dt += [('N_y', np.int64)]\n values += [self.N_y]\n\n dt += [('g', np.float64, (12,1))]\n values += [np.zeros((12,1))]\n dt += [('y', np.float64, (12,1))]\n values += [np.zeros((12,1))]\n dt += [('Fy', np.float64, (7,12))]\n values += [np.zeros((7,12))]\n dt += [('Gx', np.float64, (12,7))]\n values += [np.zeros((12,7))]\n dt += [('Gy', np.float64, (12,12))]\n values += [np.zeros((12,12))]\n\n\n\n\n self.struct = np.rec.array([tuple(values)], dtype=np.dtype(dt))\n\n\n def ini_problem(self,x):\n self.struct[0].x_ini[:,0] = x[0:self.N_x]\n self.struct[0].y_ini[:,0] = x[self.N_x:(self.N_x+self.N_y)]\n initialization(self.struct)\n fg = np.vstack((self.struct[0].f_ini,self.struct[0].g_ini))[:,0]\n return fg\n\n def run_problem(self,x):\n t = self.struct[0].t\n self.struct[0].x[:,0] = x[0:self.N_x]\n self.struct[0].y[:,0] = x[self.N_x:(self.N_x+self.N_y)]\n run(t,self.struct,2)\n run(t,self.struct,3)\n run(t,self.struct,10)\n run(t,self.struct,11)\n fg = np.vstack((self.struct[0].f,self.struct[0].g))[:,0]\n return fg\n@numba.jit(nopython=True, cache=True)\ndef run(t,struct, mode):\n\n sin = np.sin\n cos = np.cos\n sqrt = np.sqrt\n it = 0\n\n # parameters \n X_d = struct[it].X_d\n X1d = struct[it].X1d\n T1d0 = struct[it].T1d0\n X_q = struct[it].X_q\n X1q = struct[it].X1q\n T1q0 = struct[it].T1q0\n R_a = struct[it].R_a\n X_l = struct[it].X_l\n H = struct[it].H\n D = struct[it].D\n Omega_b = struct[it].Omega_b\n v_0 = struct[it].v_0\n theta_0 = struct[it].theta_0\n T_r = struct[it].T_r\n K_a = struct[it].K_a\n T_pss_1 = struct[it].T_pss_1\n T_pss_2 = struct[it].T_pss_2\n T_w = struct[it].T_w\n K_stab = struct[it].K_stab\n\n # inputs \n p_m = struct[it].p_m\n v_ref = struct[it].v_ref\n\n # states \n delta = struct[it].x[0,0] \n omega = struct[it].x[1,0] \n e1q = struct[it].x[2,0] \n e1d = struct[it].x[3,0] \n v_c = struct[it].x[4,0] \n x_pss = struct[it].x[5,0] \n x_w = struct[it].x[6,0] \n\n\n # algebraic states \n v_1 = struct[it].y[0,0] \n theta_1 = struct[it].y[1,0] \n v_d = struct[it].y[2,0] \n v_q = struct[it].y[3,0] \n i_d = struct[it].y[4,0] \n i_q = struct[it].y[5,0] \n p_e = struct[it].y[6,0] \n P_t = struct[it].y[7,0] \n Q_t = struct[it].y[8,0] \n v_f = struct[it].y[9,0] \n v_pss = struct[it].y[10,0] \n omega_w = struct[it].y[11,0] \n\n\n if mode==2: # derivatives \n\n ddelta = Omega_b*(omega - 1) \n domega = 1/(2*H)*(p_m - p_e - D*(omega - 1)) \n de1q = 1/T1d0*(-e1q - (X_d - X1d)*i_d + v_f) \n de1d = 1/T1q0*(-e1d + (X_q - X1q)*i_q) \n dv_c = (v_1 - v_c)/T_r \n dx_pss = (omega_w - x_pss)/T_pss_2 \n dx_w = (omega - x_w)/T_w \n\n struct[it].f[0,0] = ddelta \n struct[it].f[1,0] = domega \n struct[it].f[2,0] = de1q \n struct[it].f[3,0] = de1d \n struct[it].f[4,0] = dv_c \n struct[it].f[5,0] = dx_pss \n struct[it].f[6,0] = dx_w \n\n if mode==3: # algebraic equations \n\n struct[it].g[0,0] = P_t + v_0*v_1*sin(theta_0 - theta_1)/X_l \n struct[it].g[1,0] = Q_t + v_0*v_1*cos(theta_0 - theta_1)/X_l - v_1**2/X_l \n struct[it].g[2,0] = v_1*sin(delta - theta_1) - v_d \n struct[it].g[3,0] = v_1*cos(delta - theta_1) - v_q \n struct[it].g[4,0] = R_a*i_q + X1d*i_d - e1q + v_q \n struct[it].g[5,0] = R_a*i_d - X1q*i_q - e1d + v_d \n struct[it].g[6,0] = i_d*(R_a*i_d + v_d) + i_q*(R_a*i_q + v_q) - p_e \n struct[it].g[7,0] = -P_t + i_d*v_d + i_q*v_q \n struct[it].g[8,0] = -Q_t + i_d*v_q - i_q*v_d \n struct[it].g[9,0] = K_a*(-v_c + v_pss + v_ref) - v_f + 1.0 \n struct[it].g[10,0] = K_stab*(-T_pss_1*omega_w/T_pss_2 + x_pss*(-1 + 1/T_pss_2)) - v_pss \n struct[it].g[11,0] = -omega + omega_w + x_w \n\n if mode==4: # outputs \n\n struct[it].h[0,0] = omega \n \n\n if mode==10: # Fx \n\n struct[it].Fx[0,1] = Omega_b \n struct[it].Fx[1,1] = -D/(2*H) \n struct[it].Fx[2,2] = -1/T1d0 \n struct[it].Fx[3,3] = -1/T1q0 \n struct[it].Fx[4,4] = -1/T_r \n struct[it].Fx[5,5] = -1/T_pss_2 \n struct[it].Fx[6,1] = 1/T_w \n struct[it].Fx[6,6] = -1/T_w \n \n\n if mode==11: # Fy,Gx,Gy \n\n struct[it].Fy[1,6] = -1/(2*H) \n struct[it].Fy[2,4] = (X1d - X_d)/T1d0 \n struct[it].Fy[2,9] = 1/T1d0 \n struct[it].Fy[3,5] = (-X1q + X_q)/T1q0 \n struct[it].Fy[4,0] = 1/T_r \n struct[it].Fy[5,11] = 1/T_pss_2 \n \n\n struct[it].Gx[2,0] = v_1*cos(delta - theta_1) \n struct[it].Gx[3,0] = -v_1*sin(delta - theta_1) \n struct[it].Gx[4,2] = -1 \n struct[it].Gx[5,3] = -1 \n struct[it].Gx[9,4] = -K_a \n struct[it].Gx[10,5] = K_stab*(-1 + 1/T_pss_2) \n struct[it].Gx[11,1] = -1 \n struct[it].Gx[11,6] = 1 \n \n\n struct[it].Gy[0,0] = v_0*sin(theta_0 - theta_1)/X_l \n struct[it].Gy[0,1] = -v_0*v_1*cos(theta_0 - theta_1)/X_l \n struct[it].Gy[0,7] = 1 \n struct[it].Gy[1,0] = v_0*cos(theta_0 - theta_1)/X_l - 2*v_1/X_l \n struct[it].Gy[1,1] = v_0*v_1*sin(theta_0 - theta_1)/X_l \n struct[it].Gy[1,8] = 1 \n struct[it].Gy[2,0] = sin(delta - theta_1) \n struct[it].Gy[2,1] = -v_1*cos(delta - theta_1) \n struct[it].Gy[2,2] = -1 \n struct[it].Gy[3,0] = cos(delta - theta_1) \n struct[it].Gy[3,1] = v_1*sin(delta - theta_1) \n struct[it].Gy[3,3] = -1 \n struct[it].Gy[4,3] = 1 \n struct[it].Gy[4,4] = X1d \n struct[it].Gy[4,5] = R_a \n struct[it].Gy[5,2] = 1 \n struct[it].Gy[5,4] = R_a \n struct[it].Gy[5,5] = -X1q \n struct[it].Gy[6,2] = i_d \n struct[it].Gy[6,3] = i_q \n struct[it].Gy[6,4] = 2*R_a*i_d + v_d \n struct[it].Gy[6,5] = 2*R_a*i_q + v_q \n struct[it].Gy[6,6] = -1 \n struct[it].Gy[7,2] = i_d \n struct[it].Gy[7,3] = i_q \n struct[it].Gy[7,4] = v_d \n struct[it].Gy[7,5] = v_q \n struct[it].Gy[7,7] = -1 \n struct[it].Gy[8,2] = -i_q \n struct[it].Gy[8,3] = i_d \n struct[it].Gy[8,4] = v_q \n struct[it].Gy[8,5] = -v_d \n struct[it].Gy[8,8] = -1 \n struct[it].Gy[9,9] = -1 \n struct[it].Gy[9,10] = K_a \n struct[it].Gy[10,10] = -1 \n struct[it].Gy[10,11] = -K_stab*T_pss_1/T_pss_2 \n struct[it].Gy[11,11] = 1 \n\n\n@numba.njit(cache=True)\ndef initialization(struct):\n\n sin = np.sin\n cos = np.cos\n sqrt = np.sqrt\n X_d = struct[0].X_d \n X1d = struct[0].X1d \n T1d0 = struct[0].T1d0 \n X_q = struct[0].X_q \n X1q = struct[0].X1q \n T1q0 = struct[0].T1q0 \n R_a = struct[0].R_a \n X_l = struct[0].X_l \n H = struct[0].H \n D = struct[0].D \n Omega_b = struct[0].Omega_b \n v_0 = struct[0].v_0 \n theta_0 = struct[0].theta_0 \n T_r = struct[0].T_r \n K_a = struct[0].K_a \n T_pss_1 = struct[0].T_pss_1 \n T_pss_2 = struct[0].T_pss_2 \n T_w = struct[0].T_w \n K_stab = struct[0].K_stab \n p_m = struct[0].p_m \n v_ref = struct[0].v_ref \n delta = struct[0].x_ini[0,0] \n omega = struct[0].x_ini[1,0] \n e1q = struct[0].x_ini[2,0] \n e1d = struct[0].x_ini[3,0] \n v_c = struct[0].x_ini[4,0] \n x_pss = struct[0].x_ini[5,0] \n x_w = struct[0].x_ini[6,0] \n theta_1 = struct[0].y_ini[0,0] \n v_1 = struct[0].y_ini[1,0] \n v_d = struct[0].y_ini[2,0] \n v_q = struct[0].y_ini[3,0] \n i_d = struct[0].y_ini[4,0] \n i_q = struct[0].y_ini[5,0] \n p_e = struct[0].y_ini[6,0] \n P_t = struct[0].y_ini[7,0] \n Q_t = struct[0].y_ini[8,0] \n v_f = struct[0].y_ini[9,0] \n v_pss = struct[0].y_ini[10,0] \n omega_w = struct[0].y_ini[11,0] \n struct[0].f_ini[0,0] = Omega_b*(omega - 1) \n struct[0].f_ini[1,0] = (-D*(omega - 1) - p_e + p_m)/(2*H) \n struct[0].f_ini[2,0] = (-e1q - i_d*(-X1d + X_d) + v_f)/T1d0 \n struct[0].f_ini[3,0] = (-e1d + i_q*(-X1q + X_q))/T1q0 \n struct[0].f_ini[4,0] = (v_1 - v_c)/T_r \n struct[0].f_ini[5,0] = (omega_w - x_pss)/T_pss_2 \n struct[0].f_ini[6,0] = (omega - x_w)/T_w \n struct[0].g_ini[0,0] = P_t + v_0*v_1*sin(theta_0 - theta_1)/X_l \n struct[0].g_ini[1,0] = Q_t + v_0*v_1*cos(theta_0 - theta_1)/X_l - v_1**2/X_l \n struct[0].g_ini[2,0] = v_1*sin(delta - theta_1) - v_d \n struct[0].g_ini[3,0] = v_1*cos(delta - theta_1) - v_q \n struct[0].g_ini[4,0] = R_a*i_q + X1d*i_d - e1q + v_q \n struct[0].g_ini[5,0] = R_a*i_d - X1q*i_q - e1d + v_d \n struct[0].g_ini[6,0] = i_d*(R_a*i_d + v_d) + i_q*(R_a*i_q + v_q) - p_e \n struct[0].g_ini[7,0] = -P_t + i_d*v_d + i_q*v_q \n struct[0].g_ini[8,0] = -Q_t + i_d*v_q - i_q*v_d \n struct[0].g_ini[9,0] = K_a*(-v_c + v_pss + v_ref) - v_f + 1.0 \n struct[0].g_ini[10,0] = K_stab*(-T_pss_1*omega_w/T_pss_2 + x_pss*(-1 + 1/T_pss_2)) - v_pss \n struct[0].g_ini[11,0] = -omega + omega_w + x_w \n struct[0].Fx_ini[0,1] = Omega_b \n struct[0].Fx_ini[1,1] = -D/(2*H) \n struct[0].Fx_ini[2,2] = -1/T1d0 \n struct[0].Fx_ini[3,3] = -1/T1q0 \n struct[0].Fx_ini[4,4] = -1/T_r \n struct[0].Fx_ini[5,5] = -1/T_pss_2 \n struct[0].Fx_ini[6,1] = 1/T_w \n struct[0].Fx_ini[6,6] = -1/T_w \n struct[0].Fy_ini[1,6] = -1/(2*H) \n struct[0].Fy_ini[2,4] = (X1d - X_d)/T1d0 \n struct[0].Fy_ini[2,9] = 1/T1d0 \n struct[0].Fy_ini[3,5] = (-X1q + X_q)/T1q0 \n struct[0].Fy_ini[4,1] = 1/T_r \n struct[0].Fy_ini[5,11] = 1/T_pss_2 \n struct[0].Gx_ini[2,0] = v_1*cos(delta - theta_1) \n struct[0].Gx_ini[3,0] = -v_1*sin(delta - theta_1) \n struct[0].Gx_ini[4,2] = -1 \n struct[0].Gx_ini[5,3] = -1 \n struct[0].Gx_ini[9,4] = -K_a \n struct[0].Gx_ini[10,5] = K_stab*(-1 + 1/T_pss_2) \n struct[0].Gx_ini[11,1] = -1 \n struct[0].Gx_ini[11,6] = 1 \n struct[0].Gy_ini[0,0] = -v_0*v_1*cos(theta_0 - theta_1)/X_l \n struct[0].Gy_ini[0,1] = v_0*sin(theta_0 - theta_1)/X_l \n struct[0].Gy_ini[0,7] = 1 \n struct[0].Gy_ini[1,0] = v_0*v_1*sin(theta_0 - theta_1)/X_l \n struct[0].Gy_ini[1,1] = v_0*cos(theta_0 - theta_1)/X_l - 2*v_1/X_l \n struct[0].Gy_ini[1,8] = 1 \n struct[0].Gy_ini[2,0] = -v_1*cos(delta - theta_1) \n struct[0].Gy_ini[2,1] = sin(delta - theta_1) \n struct[0].Gy_ini[2,2] = -1 \n struct[0].Gy_ini[3,0] = v_1*sin(delta - theta_1) \n struct[0].Gy_ini[3,1] = cos(delta - theta_1) \n struct[0].Gy_ini[3,3] = -1 \n struct[0].Gy_ini[4,3] = 1 \n struct[0].Gy_ini[4,4] = X1d \n struct[0].Gy_ini[4,5] = R_a \n struct[0].Gy_ini[5,2] = 1 \n struct[0].Gy_ini[5,4] = R_a \n struct[0].Gy_ini[5,5] = -X1q \n struct[0].Gy_ini[6,2] = i_d \n struct[0].Gy_ini[6,3] = i_q \n struct[0].Gy_ini[6,4] = 2*R_a*i_d + v_d \n struct[0].Gy_ini[6,5] = 2*R_a*i_q + v_q \n struct[0].Gy_ini[6,6] = -1 \n struct[0].Gy_ini[7,2] = i_d \n struct[0].Gy_ini[7,3] = i_q \n struct[0].Gy_ini[7,4] = v_d \n struct[0].Gy_ini[7,5] = v_q \n struct[0].Gy_ini[7,7] = -1 \n struct[0].Gy_ini[8,2] = -i_q \n struct[0].Gy_ini[8,3] = i_d \n struct[0].Gy_ini[8,4] = v_q \n struct[0].Gy_ini[8,5] = -v_d \n struct[0].Gy_ini[8,8] = -1 \n struct[0].Gy_ini[9,9] = -1 \n struct[0].Gy_ini[9,10] = K_a \n struct[0].Gy_ini[10,10] = -1 \n struct[0].Gy_ini[10,11] = -K_stab*T_pss_1/T_pss_2 \n struct[0].Gy_ini[11,11] = 1 \n\n\ndef ini_struct(dt,values):\n\n dt += [('x_ini', np.float64, (7,1))]\n values += [np.zeros((7,1))]\n dt += [('y_ini', np.float64, (12,1))]\n values += [np.zeros((12,1))]\n dt += [('f_ini', np.float64, (7,1))]\n values += [np.zeros((7,1))]\n dt += [('g_ini', np.float64, (12,1))]\n values += [np.zeros((12,1))]\n dt += [('Fx_ini', np.float64, (7,7))]\n values += [np.zeros((7,7))]\n dt += [('Fy_ini', np.float64, (7,12))]\n values += [np.zeros((7,12))]\n dt += [('Gx_ini', np.float64, (12,7))]\n values += [np.zeros((12,7))]\n dt += [('Gy_ini', np.float64, (12,12))]\n values += [np.zeros((12,12))]\n\n\n@numba.njit(cache=True) \ndef solver(struct): \n sin = np.sin\n cos = np.cos\n sqrt = np.sqrt\n i = 0 \n\n Dt = struct[i].Dt \n N_steps = struct[i].N_steps \n N_store = struct[i].N_store \n N_x = 7 \n N_outs = 1 \n decimation = struct[i].decimation \n # initialization \n t = 0.0 \n run(0.0,struct, 1) \n it_store = 0 \n struct[i]['T'][0] = t \n struct[i].X[0,:] = struct[i].x[:,0] \n for it in range(N_steps-1): \n t += Dt \n \n perturbations(t,struct) \n solver = struct[i].solvern \n if solver == 1: \n # forward euler solver \n run(t,struct, 2) \n struct[i].x[:] += Dt*struct[i].f \n \n if solver == 2: \n # bacward euler solver\n x_0 = np.copy(struct[i].x[:]) \n for j in range(struct[i].imax): \n run(t,struct, 2) \n run(t,struct, 10) \n phi = x_0 + Dt*struct[i].f - struct[i].x \n Dx = np.linalg.solve(-(Dt*struct[i].Fx - np.eye(N_x)), phi) \n struct[i].x[:] += Dx[:] \n if np.max(np.abs(Dx)) < struct[i].itol: break \n \n if solver == 3: \n # trapezoidal solver\n run(t,struct, 2) \n f_0 = np.copy(struct[i].f[:]) \n x_0 = np.copy(struct[i].x[:]) \n for j in range(struct[i].imax): \n run(t,struct, 10) \n phi = x_0 + 0.5*Dt*(f_0 + struct[i].f) - struct[i].x \n Dx = np.linalg.solve(-(0.5*Dt*struct[i].Fx - np.eye(N_x)), phi) \n struct[i].x[:] += Dx[:] \n run(t,struct, 2) \n if np.max(np.abs(Dx)) < struct[i].itol: break \n \n # channels \n if it >= it_store*decimation: \n struct[i]['T'][it_store+1] = t \n struct[i].X[it_store+1,:] = struct[i].x[:,0] \n it_store += 1 \n \n return struct[i]['T'][:], struct[i].X[:] \n\n\n@numba.njit(cache=True) \ndef perturbations(t,struct): \n if t>1.000000: struct[0].p_m = 1.010000\n\n\n\nif __name__ == \"__main__\":\n sys = {'t_end': 20.0, 'Dt': 0.001, 'solver': 'forward-euler', 'decimation': 10, 'name': 'smib_milano_ex8p1_avr_pss', 'models': [{'params': {'X_d': 1.81, 'X1d': 0.3, 'T1d0': 8.0, 'X_q': 1.76, 'X1q': 0.65, 'T1q0': 1.0, 'R_a': 0.003, 'X_l': 0.5, 'H': 3.5, 'D': 1.0, 'Omega_b': 314.1592653589793, 'v_0': 1.0, 'theta_0': 0.0, 'T_r': 0.05, 'K_a': 200.0, 'T_pss_1': 0.154, 'T_pss_2': 0.033, 'T_w': 5.0, 'K_stab': 10}, 'f': ['ddelta = Omega_b*(omega - 1)', 'domega = 1/(2*H)*(p_m - p_e - D*(omega - 1))', 'de1q = 1/T1d0*(-e1q - (X_d - X1d)*i_d + v_f)', 'de1d = 1/T1q0*(-e1d + (X_q - X1q)*i_q)', 'dv_c = (v_1 - v_c)/T_r', 'dx_pss = (omega_w - x_pss)/T_pss_2', 'dx_w = (omega - x_w)/T_w'], 'g': ['v_1@ P_t - (v_1*v_0*sin(theta_1 - theta_0))/X_l ', 'theta_1@ Q_t + (v_1*v_0*cos(theta_1 - theta_0))/X_l - v_1**2/X_l', 'v_d@ v_1*sin(delta - theta_1) - v_d', 'v_q@ v_1*cos(delta - theta_1) - v_q', 'i_d@ v_q + R_a*i_q + X1d*i_d - e1q', 'i_q@ v_d + R_a*i_d - X1q*i_q - e1d', 'p_e@ i_d*(v_d + R_a*i_d) + i_q*(v_q + R_a*i_q) - p_e', 'P_t@ i_d*v_d + i_q*v_q - P_t', 'Q_t@ i_d*v_q - i_q*v_d - Q_t', 'v_f@K_a*(v_ref - v_c + v_pss) - v_f + 1.0', 'v_pss@ -v_pss + K_stab*(x_pss*(1/T_pss_2 - 1) - (T_pss_1*omega_w)/T_pss_2)', 'omega_w@ omega_w - omega + x_w'], 'u': {'p_m': 0.2, 'v_ref': 1.0}, 'u_ini': {}, 'y_ini': ['theta_1', 'v_1', 'v_d', 'v_q', 'i_d', 'i_q', 'p_e', 'P_t', 'Q_t', 'v_f', 'v_pss', 'omega_w'], 'h': ['omega']}], 'perturbations': [{'type': 'step', 'time': 1.0, 'var': 'p_m', 'final': 1.01}], 'itol': 1e-08, 'imax': 100, 'solvern': 1}\n syst = smib_milano_ex8p1_avr_pss_class()\n T,X = solver(syst.struct)\n from scipy.optimize import fsolve\n x0 = np.ones(syst.N_x+syst.N_y)\n s = fsolve(syst.ini_problem,x0 )\n print(s)", "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Sep 5 20:43:46 2018\n\n@author: jmmauricio\n\"\"\"\n\nimport numpy as np\n\ndef eval_A(system):\n \n Fx = system.struct[0].Fx\n Fy = system.struct[0].Fy\n Gx = system.struct[0].Gx\n Gy = system.struct[0].Gy\n \n A = Fx - Fy @ np.linalg.solve(Gy,Gx)\n \n return A" ]
[ [ "scipy.optimize.fsolve", "numpy.abs", "numpy.eye", "numpy.dtype", "numpy.ones", "numpy.ceil", "numpy.copy", "numpy.zeros", "numpy.vstack" ], [ "numpy.linalg.solve" ] ]
NinaCalvi/OKBC
[ "e25ad0296137ed354593c74509b077a22f60425e", "e25ad0296137ed354593c74509b077a22f60425e" ]
[ "preprocessing.py", "get_turk_useful_res.py" ]
[ "import argparse\nimport logging\nimport os\nimport pickle\nimport sys\n\nimport numpy as np\n\nimport kb\nimport template_builder\nimport utils\n\n\ndef get_input(fact, y, template_obj_list,add_ids):\n if (add_ids):\n x = [fact[0],fact[1],fact[2]]\n else:\n x = []\n for template in template_obj_list:\n x.extend(template.get_input(fact))\n x.append(y)\n return x\n\n\ndef preprocess(kb, template_obj_list, negative_count,add_ids,y_labels):\n\n new_facts = []\n ctr = 0\n for facts in kb.facts:\n if(ctr % 500 == 0):\n logging.info(\"Processed {0} facts out of {1}\".format(\n ctr, len(kb.facts)))\n ns = np.random.randint(0, len(kb.entity_map), negative_count)\n no = np.random.randint(0, len(kb.entity_map), negative_count)\n\n new_facts.append(get_input(facts, y_labels[ctr], template_obj_list,add_ids))\n\n for neg_facts in range(negative_count):\n new_fact = (ns[neg_facts], facts[1], facts[2])\n new_facts.append(get_input(new_fact, 0, template_obj_list,add_ids))\n new_fact = (facts[0], facts[1], no[neg_facts])\n new_facts.append(get_input(new_fact, 0, template_obj_list,add_ids))\n\n ctr += 1\n\n return np.array(new_facts)\n\n\ndef write_to_file(facts, fileprefix):\n with open(fileprefix+\".pkl\", \"wb\") as f:\n pickle.dump(facts, f)\n logging.info(\"Written data to {0}\".format(fileprefix+\".txt\"))\n np.savetxt(fileprefix+\".txt\", facts, delimiter=',',fmt='%.6e')\n logging.info(\"Written data to {0}\".format(fileprefix+\".pkl\"))\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument(\n '-d', '--dataset', help=\"Name of the dataset as in data folder\", required=True)\n parser.add_argument(\n '-m', '--model_type', help=\"model name. Can be distmult or complex \", required=True)\n parser.add_argument('-f', '--preprocess_file',\n required=True, help=\"Path of the file which is to be preprocessed\")\n parser.add_argument('-y', '--y_labels',\n required=False, help=\"Path of the y label file, which has same number of lines as preprocess_file. Use it to generate test or valid data, which has y labels instead of 1 and 0 in last column\",default='')\n parser.add_argument('-s', '--sm_data_write',\n required=True, default=\"selection_module.data\")\n parser.add_argument('-w', '--model_weights',\n help=\"Pickle file of model wieghts\", required=True)\n parser.add_argument('-l', '--template_load_dir',\n required=False, default=None)\n parser.add_argument('-v', '--oov_entity', required=False, default=True)\n parser.add_argument('--t_ids', nargs='+', type=int, required=True,\n help='List of templates to run for')\n parser.add_argument('--del_ids', action='store_true', required=False,\n help='Use the flag to delete entity and relation ids to the start of row\\nDefault behaviour is to add ids in front of each record.')\n parser.add_argument('--data_repo_root',\n required=False, default='data')\n parser.add_argument('--negative_count',\n required=False, type=int,default=2)\n parser.add_argument('--log_level',\n default='INFO',\n dest='log_level',\n type=utils._log_level_string_to_int,\n nargs='?',\n help='Set the logging output level. {0}'.format(utils._LOG_LEVEL_STRINGS))\n args = parser.parse_args()\n\n logging.basicConfig(format='%(levelname)s :: %(asctime)s - %(message)s',\n level=args.log_level, datefmt='%d/%m/%Y %I:%M:%S %p')\n\n if(args.y_labels != '' and args.negative_count!=0):\n logging.error('Cannot generate random samples with y labels. If using --y_labels use flag --negative_count 0 also')\n exit(-1)\n\n dataset_root = os.path.join(args.data_repo_root, args.dataset)\n template_objs = template_builder.template_obj_builder(dataset_root, args.model_weights,args.template_load_dir,None, args.model_type, args.t_ids, args.oov_entity)\n\n ktrain = template_objs[0].kb\n\n k_preprocess = kb.KnowledgeBase(args.preprocess_file, ktrain.entity_map, ktrain.relation_map,add_unknowns=not args.oov_entity)\n\n y_labels = [1 for _ in range(k_preprocess.facts.shape[0])]\n\n if(args.y_labels != ''):\n #y_labels = np.loadtxt(args.y_labels)\n y_labels,y_multilabels = utils.read_multilabel(args.y_labels)\n if(y_labels.shape[0] != k_preprocess.facts.shape[0]):\n logging.error('Number of facts and their y labels do not match')\n exit(-1)\n\n new_facts = preprocess(k_preprocess, template_objs, args.negative_count, not args.del_ids, y_labels)\n write_to_file(new_facts, args.sm_data_write)\n", "# This code is used to generate an analysis html for the results of the mturk batch of project -\n# TexKBC useful? (id=1419750).\n# It requires the results.csv downloaded from mturk.\n# Quality control is done, by giving all true facts (data from test.txt, which is known to be true)\n# If turker choses false, then that hit is rejected.\n# It then generates an analysis html file if all the HITs are valid, if Not it generates a CSV with a reason for rejecting the HIT.\n# Upload that CSV to Mturk to reject the HITs, not pay the turkers and republish the hits for other workers to do.\nimport pandas as pd\nimport numpy as np\nimport pprint\nimport argparse\nimport collections\nimport string\nimport os\nimport bs4 as bs\nimport itertools\n\n#ANSWER_OPTIONS = ['true','false','na']\nANSWER_OPTIONS = ['true','false'] \nREASON_OPTIONS = ['know','exp','guess','web']\n\ndef get_key_answer(key,id):\n return string.Template('Answer.${key}_${id}.on').substitute(key=key,id=id)\n\ndef get_key_reason(key,id):\n return string.Template('Answer.reason_${id}.${key}').substitute(id=id,key=key)\n\ndef get_key_input(key,id):\n return string.Template('Input.${key}_${id}').substitute(key=key,id=id)\n\ndef valid_row(row,book):\n total_sum = 0\n for i in range(5):\n for opt in ANSWER_OPTIONS:\n total_sum += row[get_key_answer(opt,i)]\n if(total_sum != 5):\n return 'You did not mark any option in some questions'\n\n if(book is None):\n return ''\n\n invalid_ct = 0\n for i in range(5):\n fact = row[get_key_input('fact',i)]\n fact_text = bs.BeautifulSoup(fact,'lxml').text\n if(str(book[book.fact == fact_text]['true?'].iloc[0]) == 'na'):\n continue\n elif(float(book[book.fact == fact_text]['true?'].iloc[0]) == 1 and row[get_key_answer('false',i)] == 1):\n invalid_ct += 1\n elif(float(book[book.fact == fact_text]['true?'].iloc[0]) == 0 and row[get_key_answer('true',i)] == 1):\n invalid_ct += 1\n # return 'You did not chose that the fact is false, though the fact was false.'\n if(invalid_ct >= 3):\n return 'You did not chose the correct option in more than 3 facts'\n return ''\n\ndef get_invalid_hits(df,outfilename,book):\n df_new = df.copy()\n df = df.fillna(False)\n invalid_hits = collections.defaultdict(list)\n for index,row in df.iterrows():\n message = valid_row(row,book)\n if(message!=''):\n print('Invalid HIT at {} with message ==> {} '.format(index, message))\n df_new['Reject'][index] = message\n invalid_hits[row['WorkerId']].append(row['AssignmentId'])\n if(len(invalid_hits)!=0):\n df_new.to_csv(outfilename,index=False,sep=',')\n return invalid_hits\n\ndef get_winner(answers):\n true_ct = 0\n false_ct = 0\n for el in answers:\n if(el=='true'):\n true_ct += 1\n elif(el=='false'):\n false_ct += 1\n if(true_ct > false_ct):\n return ['true']\n elif (false_ct > true_ct):\n return ['false']\n else:\n return ['na']\n\ndef get_book(book_filename,args):\n # TODO: Change this to have a clean pipeline\n with open(book_filename,'r') as f:\n soup = bs.BeautifulSoup(f, 'lxml')\n table = soup.find('table')\n table_body = table.find('tbody')\n rows = table_body.find_all('tr')\n data = []\n for row in rows:\n cols = row.find_all('td')\n cols = [ele.text for ele in cols]\n data.append([ele for ele in cols if ele])\n #\n df = pd.DataFrame(data,columns=['fact','exp','true?'])\n if args.all_true:\n df['true?'] = True\n elif args.all_false:\n df['true?'] = False\n #\n return df\n\ndef get_results(df,book,reason):\n df = df.fillna(False)\n results = {}\n for index, row in df.iterrows():\n for i in range(5):\n fact = row[get_key_input('fact',i)]\n exp = row[get_key_input('exp',i)]\n fact_text = bs.BeautifulSoup(fact,'lxml').text\n if(fact not in results):\n our_true = 'na' if book is None else book[book.fact == fact_text]['true?'].iloc[0]\n results[fact] = {'exp': exp, 'answers' : [],'time_taken': [] ,'reasons':[] ,'row_idx':[], 'fact_no':[],'our_true?': our_true}\n\n# if(row[get_key_answer('true',i)]):\n results[fact]['time_taken'].append(float(row['WorkTimeInSeconds'])/5.0)\n\n for opt in ANSWER_OPTIONS:\n if(row[get_key_answer(opt,i)]):\n results[fact]['answers'].append(opt)\n results[fact]['row_idx'].append(index)\n results[fact]['fact_no'].append(i)\n\n if reason:\n reason_list = []\n for opt in REASON_OPTIONS:\n if(row[get_key_reason(opt,i)]):\n reason_list.append(opt)\n results[fact]['reasons'].append('_'.join(reason_list))\n\n for k in results:\n winner = get_winner(results[k]['answers'])\n results[k]['winner'] = winner\n results[k]['avg_time'] = np.mean(results[k]['time_taken'])\n\n return results\n\ndef write_results(results,output_file,analysis_str):\n results_df = pd.DataFrame.from_dict(results,orient='index')\n results_df = results_df.reset_index()\n results_df = results_df.drop(['row_idx','fact_no'],axis=1)\n with open('css_style.css','r') as css_file:\n CSS = css_file.read()\n with open(output_file,'w') as f:\n f.write(CSS+'\\n\\n')\n analysis_str = analysis_str.replace('\\n','<br><br>')\n f.write(analysis_str+'\\n\\n')\n pd.set_option('display.max_colwidth', -1)\n results_df.to_html(f, escape=False, justify='center')\n\nif __name__ == \"__main__\":\n\n parser = argparse.ArgumentParser()\n parser.add_argument('-rf', '--result_file', help=\"Name of the result csv downloaded from mturk\", required=True)\n parser.add_argument('-op', '--output_path', help=\"Output path for rejected people and results\", required=True)\n parser.add_argument('-bf', '--book_file', help=\"Original HTML (Book) written by get_turk_useful_data\",required=False,default=None)\n parser.add_argument('--reason', action='store_true', required=False,\n help='Use the flag to know the reason of users',default=False)\n parser.add_argument('--all_true',action='store_true',required=False,default=False)\n parser.add_argument('--all_false',action='store_true',required=False,default=False)\n args = parser.parse_args()\n assert not(args.all_true and args.all_false)\n\n book = None\n if(args.book_file is not None):\n book = get_book(args.book_file,args)\n\n # if(args.reason):\n # ANSWER_OPTIONS = ANSWER_OPTIONS[:-1]\n\n df = pd.read_csv(args.result_file)\n df = df[df['AssignmentStatus'] != 'Rejected']\n\n res_file_last_part = os.path.basename(os.path.normpath(args.result_file)).split('.')[0]\n invalid_hits = get_invalid_hits(df,os.path.join(args.output_path,res_file_last_part+'_rejected.csv'),book)\n if(len(invalid_hits)!=0):\n print('There are {} invalid assignments which have id \\n{}'.format(len(list(itertools.chain(*list(invalid_hits.values())))),pprint.pformat(invalid_hits)))\n # exit(-1)\n results = get_results(df,book,args.reason)\n #print(\"------\")\n #print(results)\n #print(\"------\")\n answers_list = []\n winner_list = []\n avg_time_list = []\n reason_list = []\n accuracy = 0\n for k in results:\n # print(results[k])\n answers_list.extend(results[k]['answers'])\n winner_list.extend(results[k]['winner'])\n avg_time_list.extend(results[k]['time_taken'])\n\n if book is not None:\n if(float(results[k]['our_true?']) == 1 and results[k]['winner'][0] == 'true'):\n accuracy +=1\n elif(float(results[k]['our_true?']) == 0 and results[k]['winner'][0] == 'false'):\n accuracy +=1\n if args.reason:\n reason_list.extend(list(itertools.chain(*[x.split('_') for x in results[k]['reasons']])))\n accuracy = accuracy*100.0/len(results.keys())\n\n ctr_answers = collections.Counter(answers_list)\n analysis_str = ''\n analysis_str += 'Total number of annotations = {}\\n'.format(len(answers_list))\n for el in ctr_answers:\n ctr_answers[el] /= len(answers_list)*0.01\n analysis_str += '{}\\n\\n'.format(ctr_answers)\n\n ctr_winner = collections.Counter(winner_list)\n analysis_str += ('Total number of facts = {}\\n'.format(len(results)))\n analysis_str += ('Total number of truth determined facts = {}\\n'.format(len(winner_list)-winner_list.count('na')))\n for el in ctr_winner:\n ctr_winner[el] /= len(winner_list)*0.01\n analysis_str += '{}\\n\\n'.format(ctr_winner)\n analysis_str += '\\nAverage time taken in seconds: {}\\n\\n'.format(np.mean(avg_time_list))\n\n if book is not None:\n analysis_str += 'Turkers Accuracy: {}%\\n\\n'.format(accuracy)\n\n if args.reason:\n analysis_str += '\\n\\n Workers reason: {}\\n'.format(collections.Counter(reason_list))\n\n print(analysis_str)\n write_results(results,os.path.join(args.output_path,res_file_last_part+'_analysis.html'),analysis_str)\n" ]
[ [ "numpy.savetxt", "numpy.array" ], [ "pandas.read_csv", "pandas.DataFrame", "numpy.mean", "pandas.DataFrame.from_dict", "pandas.set_option" ] ]
lucienwang1009/tensorflow-onnx
[ "cb016ef5b2483b78b0c0ceea23652d4a6a142cf0" ]
[ "tests/test_onnx_shape_inference.py" ]
[ "# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT license.\n\n\"\"\"Unit Tests for shape inference.\"\"\"\n\nfrom __future__ import division\nfrom __future__ import print_function\nfrom __future__ import unicode_literals\n\nimport numpy as np\nfrom onnx import TensorProto\nfrom tf2onnx import utils\nfrom tf2onnx.graph import Graph\nfrom backend_test_base import Tf2OnnxBackendTestBase\nfrom common import * # pylint: disable=wildcard-import,unused-wildcard-import\n\n# pylint: disable=missing-docstring\n\nINPUT1 = \"input1\"\nINPUT2 = \"input2\"\nINPUT3 = \"input3\"\n\n\nclass ONNXShapeInferenceTests(Tf2OnnxBackendTestBase):\n \"\"\"\n Test shape inference, it's just a subset of all cases that can be inferred shape.\n For more information, please refer to onnx shape inference test:\n https://github.com/onnx/onnx/blob/master/onnx/test/shape_inference_test.py\n \"\"\"\n\n def _run_test_case(self, graph, feed_dict):\n \"\"\"Run model with onnxruntime and compare results' shape with internal shape inference.\"\"\"\n outputs = graph.outputs\n results = self.run_backend(graph, outputs, feed_dict)\n\n for actual, inferred in zip(results, outputs):\n actual_shape = actual.shape\n inferred_shape = tuple(graph.get_shape(inferred))\n self.assertTrue(utils.are_shapes_compatible(actual_shape, inferred_shape))\n\n actual_dtype = actual.dtype\n inferred_dtype = utils.ONNX_TO_NUMPY_DTYPE[graph.get_dtype(inferred)]\n self.assertEqual(actual_dtype, inferred_dtype)\n\n def _create_empty_graph(self, inputs, shapes, dtypes):\n graph = Graph([], target=self.config.target, opset=self.config.opset)\n for inp, shape, dtype in zip(inputs, shapes, dtypes):\n graph.add_graph_input(inp, dtype, shape)\n return graph\n\n def _generate_random_inputs(self, inputs, shapes, dtypes):\n \"\"\"Generate random input of shape and ONNX dtypes\"\"\"\n res = {}\n for inp, shape, dtype in zip(inputs, shapes, dtypes):\n new_shape = [1 if s == -1 else s for s in shape]\n res[inp] = np.random.random(new_shape).astype(utils.ONNX_TO_NUMPY_DTYPE[dtype])\n return res\n\n # one input\n def test_identity(self):\n inputs = [INPUT1]\n shapes = [[1, 3, 4, 1]]\n dtypes = [TensorProto.FLOAT]\n graph = self._create_empty_graph(inputs, shapes, dtypes)\n node = graph.make_node(\"Identity\", [INPUT1])\n graph.add_graph_output(node.output[0])\n self._run_test_case(graph, self._generate_random_inputs(inputs, shapes, dtypes))\n\n def test_transpose(self):\n inputs = [INPUT1]\n shapes = [[1, 3, 4, 1]]\n dtypes = [TensorProto.FLOAT]\n graph = self._create_empty_graph(inputs, shapes, dtypes)\n node = graph.make_node(\"Transpose\", [INPUT1], attr={\"perm\": [1, 0, 2, 3]})\n graph.add_graph_output(node.output[0])\n self._run_test_case(graph, self._generate_random_inputs(inputs, shapes, dtypes))\n\n def test_shape(self):\n inputs = [INPUT1]\n shapes = [[1, 3, 4, 1]]\n dtypes = [TensorProto.FLOAT]\n graph = self._create_empty_graph(inputs, shapes, dtypes)\n node = graph.make_node(\"Shape\", [INPUT1])\n graph.add_graph_output(node.output[0])\n self._run_test_case(graph, self._generate_random_inputs(inputs, shapes, dtypes))\n\n @check_opset_min_version(2, \"Split\")\n def test_split(self):\n inputs = [INPUT1]\n shapes = [[5, 6, 7]]\n dtypes = [TensorProto.FLOAT]\n graph = self._create_empty_graph(inputs, shapes, dtypes)\n node = graph.make_node(\"Split\", [INPUT1], output_count=2, attr={\"axis\": 1})\n graph.add_graph_output(node.output[0])\n graph.add_graph_output(node.output[1])\n self._run_test_case(graph, self._generate_random_inputs(inputs, shapes, dtypes))\n\n # two inputs\n @check_opset_min_version(6, \"Add\")\n def test_add(self):\n inputs = [INPUT1, INPUT2]\n shapes = [[1, 3, 4, 1], [2, 1, 4, 10]]\n dtypes = [TensorProto.FLOAT, TensorProto.FLOAT]\n graph = self._create_empty_graph(inputs, shapes, dtypes)\n node = graph.make_node(\"Add\", [INPUT1, INPUT2])\n graph.add_graph_output(node.output[0])\n self._run_test_case(graph, self._generate_random_inputs(inputs, shapes, dtypes))\n\n def test_matmul(self):\n inputs = [INPUT1, INPUT2]\n shapes = [[1, 3, 4, 1], [2, 1, 1, 10]]\n dtypes = [TensorProto.FLOAT, TensorProto.FLOAT]\n graph = self._create_empty_graph(inputs, shapes, dtypes)\n node = graph.make_node(\"MatMul\", [INPUT1, INPUT2])\n graph.add_graph_output(node.output[0])\n self._run_test_case(graph, self._generate_random_inputs(inputs, shapes, dtypes))\n\n def _test_matmul_unknown_shape(self, shapes):\n data_shapes = [\n [1 if s == -1 else s for s in shapes[0]],\n [1 if s == -1 else s for s in shapes[1]]\n ]\n inputs = [INPUT1, INPUT2]\n dtypes = [TensorProto.FLOAT, TensorProto.FLOAT]\n graph = self._create_empty_graph(inputs, shapes, dtypes)\n node = graph.make_node(\"MatMul\", [INPUT1, INPUT2])\n graph.add_graph_output(node.output[0])\n self._run_test_case(graph, self._generate_random_inputs(inputs, data_shapes, dtypes))\n\n def test_matmul_unknown(self):\n self._test_matmul_unknown_shape([[-1], [-1]])\n self._test_matmul_unknown_shape([[3], [-1]])\n self._test_matmul_unknown_shape([[2], [2, -1]])\n self._test_matmul_unknown_shape([[4, 2], [2, -1]])\n self._test_matmul_unknown_shape([[1, 4, 2], [-1, 2, 5]])\n self._test_matmul_unknown_shape([[1, 3, 4, 2], [-1, 2, 5]])\n\n @check_opset_min_version(4, \"Concat\")\n def test_concat(self):\n inputs = [INPUT1, INPUT2]\n shapes = [[10, 20, 9], [12, 20, 9]]\n dtypes = [TensorProto.FLOAT, TensorProto.FLOAT]\n graph = self._create_empty_graph(inputs, shapes, dtypes)\n node = graph.make_node(\"Concat\", [INPUT1, INPUT2], attr={\"axis\": 0})\n graph.add_graph_output(node.output[0])\n self._run_test_case(graph, self._generate_random_inputs(inputs, shapes, dtypes))\n\n def test_conv(self):\n inputs = [INPUT1, INPUT2]\n shapes = [[3, 4, 5, 6, 7], [5, 4, 2, 4, 3]]\n dtypes = [TensorProto.FLOAT, TensorProto.FLOAT]\n graph = self._create_empty_graph(inputs, shapes, dtypes)\n node = graph.make_node(\n \"Conv\", [INPUT1, INPUT2],\n attr={\n \"pads\": [0, 1, 1, 0, 0, 1],\n \"dilations\": [1, 2, 2],\n \"strides\": [1, 1, 2]\n }\n )\n graph.add_graph_output(node.output[0])\n self._run_test_case(graph, self._generate_random_inputs(inputs, shapes, dtypes))\n\n # more than two inputs\n @check_opset_min_version(8, \"Sum\")\n def test_sum(self):\n inputs = [INPUT1, INPUT2, INPUT3]\n shapes = [[30, 1, 5], [-1, 4, 1], [4, -1]]\n dtypes = [TensorProto.FLOAT, TensorProto.FLOAT, TensorProto.FLOAT]\n graph = self._create_empty_graph(inputs, shapes, dtypes)\n node = graph.make_node(\"Sum\", [INPUT1, INPUT2, INPUT3])\n graph.add_graph_output(node.output[0])\n self._run_test_case(graph, self._generate_random_inputs(inputs, shapes, dtypes))\n\n @check_opset_min_version(7, \"RNN\")\n def test_rnn(self):\n seq_len = 64\n batch_size = 32\n input_size = 10\n hidden_size = 4\n inputs = [INPUT1, INPUT2, INPUT3]\n shapes = [[seq_len, batch_size, input_size], [1, hidden_size, input_size], [1, hidden_size, hidden_size]]\n dtypes = [TensorProto.FLOAT, TensorProto.FLOAT, TensorProto.FLOAT]\n graph = self._create_empty_graph(inputs, shapes, dtypes)\n node = graph.make_node(\"RNN\", [INPUT1, INPUT2, INPUT3], output_count=2, attr={\"hidden_size\": hidden_size})\n graph.add_graph_output(node.output[0])\n graph.add_graph_output(node.output[1])\n self._run_test_case(graph, self._generate_random_inputs(inputs, shapes, dtypes))\n\n @check_opset_min_version(7, \"LSTM\")\n def test_lstm(self):\n seq_len = 64\n batch_size = 32\n input_size = 10\n hidden_size = 4\n inputs = [INPUT1, INPUT2, INPUT3]\n shapes = [\n [seq_len, batch_size, input_size],\n [1, 4 * hidden_size, input_size],\n [1, 4 * hidden_size, hidden_size]\n ]\n dtypes = [TensorProto.FLOAT, TensorProto.FLOAT, TensorProto.FLOAT]\n graph = self._create_empty_graph(inputs, shapes, dtypes)\n node = graph.make_node(\"LSTM\", [INPUT1, INPUT2, INPUT3], output_count=3, attr={\"hidden_size\": hidden_size})\n graph.add_graph_output(node.output[0])\n graph.add_graph_output(node.output[1])\n graph.add_graph_output(node.output[2])\n self._run_test_case(graph, self._generate_random_inputs(inputs, shapes, dtypes))\n\n # with const input\n @check_opset_min_version(5, \"Reshape\")\n def test_reshape(self):\n inputs = [INPUT1]\n shapes = [[10, 20]]\n dtypes = [TensorProto.FLOAT]\n graph = self._create_empty_graph(inputs, shapes, dtypes)\n const = graph.make_const(\"shape\", np.array([5, 40], dtype=np.int64))\n node = graph.make_node(\"Reshape\", [INPUT1, const.output[0]])\n graph.add_graph_output(node.output[0])\n self._run_test_case(graph, self._generate_random_inputs(inputs, shapes, dtypes))\n\n def test_gather(self):\n inputs = [INPUT1]\n shapes = [[4, 3]]\n dtypes = [TensorProto.FLOAT]\n graph = self._create_empty_graph(inputs, shapes, dtypes)\n const = graph.make_const(\"index\", np.array([1, 2], dtype=np.int64))\n node = graph.make_node(\"Gather\", [INPUT1, const.output[0]])\n graph.add_graph_output(node.output[0])\n self._run_test_case(graph, self._generate_random_inputs(inputs, shapes, dtypes))\n\n def test_gather_axis1(self):\n inputs = [INPUT1]\n shapes = [[4, 3, 5]]\n dtypes = [TensorProto.FLOAT]\n graph = self._create_empty_graph(inputs, shapes, dtypes)\n const = graph.make_const(\"index\", np.array([[1, 2]], dtype=np.int64))\n node = graph.make_node(\"Gather\", [INPUT1, const.output[0]], attr={\"axis\": 1})\n graph.add_graph_output(node.output[0])\n self._run_test_case(graph, self._generate_random_inputs(inputs, shapes, dtypes))\n\n def test_gather_into_scalar(self):\n inputs = [INPUT1]\n shapes = [[4]]\n dtypes = [TensorProto.FLOAT]\n graph = self._create_empty_graph(inputs, shapes, dtypes)\n const = graph.make_const(\"index\", np.array(2, dtype=np.int64))\n node = graph.make_node(\"Gather\", [INPUT1, const.output[0]])\n graph.add_graph_output(node.output[0])\n self._run_test_case(graph, self._generate_random_inputs(inputs, shapes, dtypes))\n\n @check_opset_min_version(9, \"ConstantOfShape\")\n def test_constant_of_shape(self):\n inputs = [INPUT1]\n shapes = [[3]]\n dtypes = [TensorProto.INT64]\n graph = self._create_empty_graph(inputs, shapes, dtypes)\n node = graph.make_node(\"ConstantOfShape\", [INPUT1])\n graph.add_graph_output(node.output[0])\n self._run_test_case(graph, self._generate_random_inputs(inputs, shapes, dtypes))\n\n graph = self._create_empty_graph([], [], [])\n const = graph.make_const(\"shape\", np.array([3, 5, 6], dtype=np.int64))\n node = graph.make_node(\"ConstantOfShape\", [const.output[0]])\n graph.add_graph_output(node.output[0])\n self._run_test_case(graph, self._generate_random_inputs([], [], []))\n\n # node with subgraph\n @check_opset_min_version(8, \"Scan\")\n @check_opset_max_version(8, \"Scan\")\n def test_scan(self):\n batch_size = 1\n seq_len = 16\n input_size = 2\n loop_state_size = 3\n inputs = [INPUT1, INPUT2]\n shapes = [[batch_size, loop_state_size, loop_state_size],\n [batch_size, seq_len, input_size, input_size]]\n dtypes = [TensorProto.FLOAT, TensorProto.FLOAT]\n\n graph = self._create_empty_graph(inputs, shapes, dtypes)\n\n subgraph = self._create_empty_graph(\n [\"loop_state_in\", \"input\"],\n [[-1, -1], [-1, -1]],\n [TensorProto.FLOAT, TensorProto.FLOAT],\n )\n subgraph.parent_graph = graph\n loop_state_iden = subgraph.make_node(\"Identity\", [\"loop_state_in\"])\n input_iden = subgraph.make_node(\"Identity\", [\"input\"])\n subgraph.add_graph_output(loop_state_iden.output[0])\n subgraph.add_graph_output(input_iden.output[0])\n\n seq_len_node = graph.make_const(\"seq_len\", np.array(seq_len, dtype=np.int64))\n scan = graph.make_node(\n \"Scan\", [seq_len_node.output[0], INPUT1, INPUT2],\n output_count=2, attr={\"num_scan_inputs\": 1}\n )\n scan.set_body_graph_as_attr(\"body\", subgraph)\n\n # explicitly infer shape for scan node\n graph.update_node_shape_dtype(scan)\n\n graph.add_graph_output(scan.output[0])\n graph.add_graph_output(scan.output[1])\n self._run_test_case(graph, self._generate_random_inputs(inputs, shapes, dtypes))\n\n @check_opset_min_version(9, \"Scan\")\n def test_scan_opset9(self):\n seq_len = 16\n input_size = 2\n loop_state_size = 3\n inputs = [INPUT1, INPUT2]\n shapes = [[loop_state_size, loop_state_size],\n [seq_len, input_size, input_size]]\n dtypes = [TensorProto.FLOAT, TensorProto.FLOAT]\n graph = self._create_empty_graph(inputs, shapes, dtypes)\n\n subgraph = self._create_empty_graph(\n [\"loop_state_in\", \"input\"],\n [[-1, -1], [-1, -1]],\n [TensorProto.FLOAT, TensorProto.FLOAT],\n )\n subgraph.parent_graph = graph\n loop_state_iden = subgraph.make_node(\"Identity\", [\"loop_state_in\"])\n input_iden = subgraph.make_node(\"Identity\", [\"input\"])\n subgraph.add_graph_output(loop_state_iden.output[0])\n subgraph.add_graph_output(input_iden.output[0])\n\n scan = graph.make_node(\"Scan\", [INPUT1, INPUT2], output_count=2, attr={\"num_scan_inputs\": 1})\n scan.set_body_graph_as_attr(\"body\", subgraph)\n\n # explicitly infer shape for scan node\n graph.update_node_shape_dtype(scan)\n\n graph.add_graph_output(scan.output[0])\n graph.add_graph_output(scan.output[1])\n self._run_test_case(graph, self._generate_random_inputs(inputs, shapes, dtypes))\n\n def test_if(self):\n inputs = [INPUT1, INPUT2, INPUT3]\n shapes = [[2, 3, 4], [2, 3, 4], [2, 3, 4]]\n dtypes = [TensorProto.FLOAT, TensorProto.FLOAT, TensorProto.FLOAT]\n graph = self._create_empty_graph(inputs, shapes, dtypes)\n\n then_subgraph = self._create_empty_graph([], [], [])\n then_subgraph.parent_graph = graph\n add = then_subgraph.make_node(\"Add\", [INPUT1, INPUT2])\n then_subgraph.add_graph_output(add.output[0])\n\n else_subgraph = self._create_empty_graph([], [], [])\n else_subgraph.parent_graph = graph\n sub = else_subgraph.make_node(\"Sub\", [INPUT1, INPUT3])\n else_subgraph.add_graph_output(sub.output[0])\n\n cond = graph.make_const(\"cond\", np.array(True, dtype=np.bool))\n if_node = graph.make_node(\"If\", [cond.output[0]])\n if_node.set_body_graph_as_attr(\"then_branch\", then_subgraph)\n if_node.set_body_graph_as_attr(\"else_branch\", else_subgraph)\n\n # explicitly infer shape for if node\n graph.update_node_shape_dtype(if_node)\n\n graph.add_graph_output(if_node.output[0])\n self._run_test_case(graph, self._generate_random_inputs(inputs, shapes, dtypes))\n\n def test_loop(self):\n inputs = [INPUT1, INPUT2]\n shapes = [[3, 4], [4, 5]]\n dtypes = [TensorProto.FLOAT, TensorProto.FLOAT]\n graph = self._create_empty_graph(inputs, shapes, dtypes)\n\n subgraph = self._create_empty_graph(\n [\"iter_num\", \"cond\", \"loop_state\"],\n [[-1], [-1], [-1, -1]],\n [TensorProto.INT64, TensorProto.BOOL, TensorProto.FLOAT]\n )\n subgraph.parent_graph = graph\n cond_out = subgraph.make_node(\"Identity\", [\"cond\"])\n loop_state_out = subgraph.make_node(\"Identity\", [\"loop_state\"])\n out = subgraph.make_node(\"MatMul\", [\"loop_state\", INPUT2])\n subgraph.add_graph_output(cond_out.output[0])\n subgraph.add_graph_output(loop_state_out.output[0])\n subgraph.add_graph_output(out.output[0])\n\n max_iter = graph.make_const(\"max_iter\", np.array([10], dtype=np.int64))\n cond_const = graph.make_const(\"cond_const\", np.array([True], dtype=np.bool))\n loop = graph.make_node(\"Loop\", [max_iter.output[0], cond_const.output[0], INPUT1],\n output_count=2)\n loop.set_body_graph_as_attr(\"body\", subgraph)\n\n graph.update_node_shape_dtype(loop)\n\n # state shape may change between iterations\n # graph.add_graph_output(loop.output[0])\n graph.add_graph_output(loop.output[1])\n self._run_test_case(graph, self._generate_random_inputs(inputs, shapes, dtypes))\n\n # overrider shape\n def test_override_shape(self):\n inputs = [INPUT1]\n shapes = [[1, 3, 4, 1]]\n dtypes = [TensorProto.FLOAT]\n graph = self._create_empty_graph(inputs, shapes, dtypes)\n output_name = utils.make_name(\"output\")\n graph._output_shapes[output_name] = [-1, -1, 2, 3] # pylint: disable=protected-access\n node = graph.make_node(\"Transpose\", [INPUT1], attr={\"perm\": [1, 0, 2, 3]}, outputs=[output_name])\n\n graph.update_node_shape_dtype(node, override=True)\n\n graph.add_graph_output(node.output[0])\n self._run_test_case(graph, self._generate_random_inputs(inputs, shapes, dtypes))\n\n\nif __name__ == \"__main__\":\n unittest_main()\n" ]
[ [ "numpy.array", "numpy.random.random" ] ]
abinashpanda/pgmpy
[ "bd4019f0b711eae95217cda82087d3ef90e2457a" ]
[ "pgmpy/factors/discrete/CPD.py" ]
[ "#!/usr/bin/env python3\n\"\"\"Contains the different formats of CPDs used in PGM\"\"\"\nfrom __future__ import division\n\nfrom itertools import product\nfrom warnings import warn\nimport numbers\n\nimport numpy as np\n\nfrom pgmpy.factors.discrete import DiscreteFactor\nfrom pgmpy.extern import tabulate\nfrom pgmpy.extern import six\nfrom pgmpy.extern.six.moves import range, zip\nfrom pgmpy.utils import StateNameInit\nfrom pgmpy.utils import StateNameDecorator\n\n\nclass TabularCPD(DiscreteFactor):\n \"\"\"\n Defines the conditional probability distribution table (cpd table)\n\n Example\n -------\n For a distribution of P(grade|diff, intel)\n\n +-------+--------------------+------------------+\n |diff | easy | hard |\n +-------+-----+------+-------+------+----+------+\n |intel |dumb | avg | smart | dumb |avg |smart |\n +-------+-----+------+-------+------+----+------+\n |gradeA |0.1 | 0.1 | 0.1 | 0.1 |0.1 | 0.1 |\n +-------+-----+------+-------+------+----+------+\n |gradeB |0.1 | 0.1 | 0.1 | 0.1 |0.1 | 0.1 |\n +-------+-----+------+-------+------+----+------+\n |gradeC |0.8 | 0.8 | 0.8 | 0.8 |0.8 | 0.8 |\n +-------+-----+------+-------+------+----+------+\n\n values should be\n [[0.1,0.1,0.1,0.1,0.1,0.1],\n [0.1,0.1,0.1,0.1,0.1,0.1],\n [0.8,0.8,0.8,0.8,0.8,0.8]]\n\n >>> cpd = TabularCPD('grade',3,[[0.1,0.1,0.1,0.1,0.1,0.1],\n [0.1,0.1,0.1,0.1,0.1,0.1],\n [0.8,0.8,0.8,0.8,0.8,0.8]],\n evidence=['diff', 'intel'], evidence_card=[2,3])\n >>> print(cpd)\n +---------+---------+---------+---------+---------+---------+---------+\n | diff | diff_0 | diff_0 | diff_0 | diff_1 | diff_1 | diff_1 |\n +---------+---------+---------+---------+---------+---------+---------+\n | intel | intel_0 | intel_1 | intel_2 | intel_0 | intel_1 | intel_2 |\n +---------+---------+---------+---------+---------+---------+---------+\n | grade_0 | 0.1 | 0.1 | 0.1 | 0.1 | 0.1 | 0.1 |\n +---------+---------+---------+---------+---------+---------+---------+\n | grade_1 | 0.1 | 0.1 | 0.1 | 0.1 | 0.1 | 0.1 |\n +---------+---------+---------+---------+---------+---------+---------+\n | grade_2 | 0.8 | 0.8 | 0.8 | 0.8 | 0.8 | 0.8 |\n +---------+---------+---------+---------+---------+---------+---------+\n >>> cpd.values\n array([[[ 0.1, 0.1, 0.1],\n [ 0.1, 0.1, 0.1]],\n\n [[ 0.1, 0.1, 0.1],\n [ 0.1, 0.1, 0.1]],\n\n [[ 0.8, 0.8, 0.8],\n [ 0.8, 0.8, 0.8]]])\n >>> cpd.variables\n ['grade', 'diff', 'intel']\n >>> cpd.cardinality\n array([3, 2, 3])\n >>> cpd.variable\n 'grade'\n >>> cpd.variable_card\n 3\n\n Parameters\n ----------\n variable: int, string (any hashable python object)\n The variable whose CPD is defined.\n\n variable_card: integer\n cardinality of variable\n\n values: 2d array, 2d list or 2d tuple\n values of the cpd table\n\n evidence: array-like\n evidences(if any) w.r.t. which cpd is defined\n\n evidence_card: integer, array-like\n cardinality of evidences (if any)\n\n Public Methods\n --------------\n get_cpd()\n marginalize([variables_list])\n normalize()\n reduce([values_list])\n \"\"\"\n @StateNameInit()\n def __init__(self, variable, variable_card, values,\n evidence=None, evidence_card=None):\n\n self.variable = variable\n self.variable_card = None\n\n variables = [variable]\n\n if not isinstance(variable_card, numbers.Integral):\n raise TypeError(\"Event cardinality must be an integer\")\n self.variable_card = variable_card\n\n cardinality = [variable_card]\n if evidence_card is not None:\n if isinstance(evidence_card, numbers.Real):\n raise TypeError(\"Evidence card must be a list of numbers\")\n cardinality.extend(evidence_card)\n\n if evidence is not None:\n if isinstance(evidence, six.string_types):\n raise TypeError(\"Evidence must be list, tuple or array of strings.\")\n variables.extend(evidence)\n if not len(evidence_card) == len(evidence):\n raise ValueError(\"Length of evidence_card doesn't match length of evidence\")\n\n values = np.array(values)\n if values.ndim != 2:\n raise TypeError(\"Values must be a 2D list/array\")\n\n super(TabularCPD, self).__init__(variables, cardinality, values.flatten('C'),\n state_names=self.state_names)\n\n def __repr__(self):\n var_str = '<TabularCPD representing P({var}:{card}'.format(\n var=self.variable, card=self.variable_card)\n\n evidence = self.variables[1:]\n evidence_card = self.cardinality[1:]\n if evidence:\n evidence_str = ' | ' + ', '.join(['{var}:{card}'.format(var=var, card=card)\n for var, card in zip(evidence, evidence_card)])\n else:\n evidence_str = ''\n\n return var_str + evidence_str + ') at {address}>'.format(address=hex(id(self)))\n\n def get_cpd(self):\n \"\"\"\n Returns the cpd\n >>> from pgmpy.factors import TabularCPD\n >>> cpd = TabularCPD('grade', 3, [[0.1, 0.1],\n ... [0.1, 0.1],\n ... [0.8, 0.8]],\n ... evidence='evi1', evidence_card=2)\n >>> cpd.get_cpd()\n array([[ 0.1, 0.1],\n [ 0.1, 0.1],\n [ 0.8, 0.8]])\n\n \"\"\"\n if self.variable in self.variables:\n return self.values.reshape(self.cardinality[0], np.prod(self.cardinality[1:]))\n else:\n return self.values.reshape(1, np.prod(self.cardinality))\n\n def __str__(self):\n if six.PY2:\n return self._make_table_str(\"grid\")\n else:\n return self._make_table_str(\"fancy_grid\")\n\n def _str(self, phi_or_p=\"p\", tablefmt=\"fancy_grid\"):\n return super(self, TabularCPD)._str(phi_or_p, tablefmt)\n\n def _make_table_str(self, tablefmt=\"fancy_grid\", print_state_names=True):\n headers_list = []\n # build column headers\n\n evidence = self.variables[1:]\n evidence_card = self.cardinality[1:]\n if evidence:\n col_indexes = np.array(list(product(*[range(i) for i in evidence_card])))\n if self.state_names and print_state_names:\n for i in range(len(evidence_card)):\n column_header = [evidence[i]] + ['{var}({state})'.format\n (var=evidence[i],\n state=self.state_names[evidence[i]][d])\n for d in col_indexes.T[i]]\n headers_list.append(column_header)\n else:\n for i in range(len(evidence_card)):\n column_header = [evidence[i]] + ['{s}_{d}'.format(s=evidence[i], d=d) for d in col_indexes.T[i]]\n headers_list.append(column_header)\n\n # Build row headers\n if self.state_names and print_state_names:\n variable_array = [['{var}({state})'.format\n (var=self.variable, state=self.state_names[self.variable][i])\n for i in range(self.variable_card)]]\n else:\n variable_array = [['{s}_{d}'.format(s=self.variable, d=i) for i in range(self.variable_card)]]\n # Stack with data\n labeled_rows = np.hstack((np.array(variable_array).T, self.get_cpd())).tolist()\n # No support for multi-headers in tabulate\n cdf_str = tabulate(headers_list + labeled_rows, tablefmt=tablefmt)\n return cdf_str\n\n def copy(self):\n \"\"\"\n Returns a copy of the TabularCPD object.\n\n Examples\n --------\n >>> from pgmpy.factors import TabularCPD\n >>> cpd = TabularCPD('grade', 2,\n ... [[0.7, 0.6, 0.6, 0.2],[0.3, 0.4, 0.4, 0.8]],\n ... ['intel', 'diff'], [2, 2])\n >>> copy = cpd.copy()\n >>> copy.variable\n 'grade'\n >>> copy.variable_card\n 2\n >>> copy.evidence\n ['intel', 'diff']\n >>> copy.values\n array([[[ 0.7, 0.6],\n [ 0.6, 0.2]],\n\n [[ 0.3, 0.4],\n [ 0.4, 0.8]]])\n \"\"\"\n evidence = self.variables[1:] if len(self.variables) > 1 else None\n evidence_card = self.cardinality[1:] if len(self.variables) > 1 else None\n return TabularCPD(self.variable, self.variable_card, self.get_cpd(),\n evidence, evidence_card)\n\n def normalize(self, inplace=True):\n \"\"\"\n Normalizes the cpd table.\n\n Parameters\n ----------\n inplace: boolean\n If inplace=True it will modify the CPD itself, else would return\n a new CPD\n\n Examples\n --------\n >>> from pgmpy.factors import TabularCPD\n >>> cpd_table = TabularCPD('grade', 2,\n ... [[0.7, 0.2, 0.6, 0.2],[0.4, 0.4, 0.4, 0.8]],\n ... ['intel', 'diff'], [2, 2])\n >>> cpd_table.normalize()\n >>> cpd_table.get_cpd()\n array([[ 0.63636364, 0.33333333, 0.6 , 0.2 ],\n [ 0.36363636, 0.66666667, 0.4 , 0.8 ]])\n \"\"\"\n tabular_cpd = self if inplace else self.copy()\n cpd = tabular_cpd.get_cpd()\n tabular_cpd.values = (cpd / cpd.sum(axis=0)).reshape(tabular_cpd.cardinality)\n if not inplace:\n return tabular_cpd\n\n def marginalize(self, variables, inplace=True):\n \"\"\"\n Modifies the cpd table with marginalized values.\n\n Parameters\n ---------\n variables: list, array-like\n list of variable to be marginalized\n\n inplace: boolean\n If inplace=True it will modify the CPD itself, else would return\n a new CPD\n\n Examples\n --------\n >>> from pgmpy.factors import TabularCPD\n >>> cpd_table = TabularCPD('grade', 2,\n ... [[0.7, 0.6, 0.6, 0.2],[0.3, 0.4, 0.4, 0.8]],\n ... ['intel', 'diff'], [2, 2])\n >>> cpd_table.marginalize(['diff'])\n >>> cpd_table.get_cpd()\n array([[ 0.65, 0.4 ],\n [ 0.35, 0.6 ]])\n \"\"\"\n if self.variable in variables:\n raise ValueError(\"Marginalization not allowed on the variable on which CPD is defined\")\n\n tabular_cpd = self if inplace else self.copy()\n\n super(TabularCPD, tabular_cpd).marginalize(variables)\n tabular_cpd.normalize()\n\n if not inplace:\n return tabular_cpd\n\n @StateNameDecorator(argument='values', return_val=None)\n def reduce(self, values, inplace=True):\n \"\"\"\n Reduces the cpd table to the context of given variable values.\n\n Parameters\n ----------\n values: list, array-like\n A list of tuples of the form (variable_name, variable_state).\n\n inplace: boolean\n If inplace=True it will modify the factor itself, else would return\n a new factor.\n\n Examples\n --------\n >>> from pgmpy.factors import TabularCPD\n >>> cpd_table = TabularCPD('grade', 2,\n ... [[0.7, 0.6, 0.6, 0.2],[0.3, 0.4, 0.4, 0.8]],\n ... ['intel', 'diff'], [2, 2])\n >>> cpd_table.reduce([('diff', 0)])\n >>> cpd_table.get_cpd()\n array([[ 0.7, 0.6],\n [ 0.3, 0.4]])\n \"\"\"\n if self.variable in (value[0] for value in values):\n raise ValueError(\"Reduce not allowed on the variable on which CPD is defined\")\n\n tabular_cpd = self if inplace else self.copy()\n\n super(TabularCPD, tabular_cpd).reduce(values)\n tabular_cpd.normalize()\n\n if not inplace:\n return tabular_cpd\n\n def to_factor(self):\n \"\"\"\n Returns an equivalent factor with the same variables, cardinality, values as that of the cpd\n\n Examples\n --------\n >>> from pgmpy.factors.discrete.CPD import TabularCPD\n >>> cpd = TabularCPD('grade', 3, [[0.1, 0.1],\n ... [0.1, 0.1],\n ... [0.8, 0.8]],\n ... evidence='evi1', evidence_card=2)\n >>> factor = cpd.to_factor()\n >>> factor\n <DiscreteFactor representing phi(grade:3, evi1:2) at 0x7f847a4f2d68>\n \"\"\"\n return DiscreteFactor(self.variables, self.cardinality, self.values)\n\n def reorder_parents(self, new_order, inplace=True):\n \"\"\"\n Returns a new cpd table according to provided order\n\n Parameters\n ----------\n new_order: list\n list of new ordering of variables\n\n inplace: boolean\n If inplace == True it will modify the CPD itself\n otherwise new value will be returned without affecting old values\n\n Examples\n --------\n Consider a CPD P(grade| diff, intel)\n >>> cpd = TabularCPD('grade',3,[[0.1,0.1,0.1,0.1,0.1,0.1],\n [0.1,0.1,0.1,0.1,0.1,0.1],\n [0.8,0.8,0.8,0.8,0.8,0.8]],\n evidence=['diff', 'intel'], evidence_card=[2,3])\n >>> print(cpd)\n +---------+---------+---------+---------+---------+---------+---------+\n | diff | diff_0 | diff_0 | diff_0 | diff_1 | diff_1 | diff_1 |\n +---------+---------+---------+---------+---------+---------+---------+\n | intel | intel_0 | intel_1 | intel_2 | intel_0 | intel_1 | intel_2 |\n +---------+---------+---------+---------+---------+---------+---------+\n | grade_0 | 0.1 | 0.1 | 0.1 | 0.1 | 0.1 | 0.1 |\n +---------+---------+---------+---------+---------+---------+---------+\n | grade_1 | 0.1 | 0.1 | 0.1 | 0.1 | 0.1 | 0.1 |\n +---------+---------+---------+---------+---------+---------+---------+\n | grade_2 | 0.8 | 0.8 | 0.8 | 0.8 | 0.8 | 0.8 |\n +---------+---------+---------+---------+---------+---------+---------+\n >>> cpd.values\n array([[[ 0.1, 0.1, 0.1],\n [ 0.1, 0.1, 0.1]],\n\n [[ 0.1, 0.1, 0.1],\n [ 0.1, 0.1, 0.1]],\n\n [[ 0.8, 0.8, 0.8],\n [ 0.8, 0.8, 0.8]]])\n >>> cpd.variables\n ['grade', 'diff', 'intel']\n >>> cpd.cardinality\n array([3, 2, 3])\n >>> cpd.variable\n 'grade'\n >>> cpd.variable_card\n 3\n\n >>> cpd.reorder_parents(['intel', 'diff'])\n array([[ 0.1, 0.1, 0.2, 0.2, 0.1, 0.1],\n [ 0.1, 0.1, 0.1, 0.1, 0.1, 0.1],\n [ 0.8, 0.8, 0.7, 0.7, 0.8, 0.8]])\n >>> print(cpd)\n +---------+---------+---------+---------+---------+---------+---------+\n | intel | intel_0 | intel_0 | intel_1 | intel_1 | intel_2 | intel_2 |\n +---------+---------+---------+---------+---------+---------+---------+\n | diff | diff_0 | diff_1 | diff_0 | diff_1 | diff_0 | diff_1 |\n +---------+---------+---------+---------+---------+---------+---------+\n | grade_0 | 0.1 | 0.1 | 0.2 | 0.2 | 0.1 | 0.1 |\n +---------+---------+---------+---------+---------+---------+---------+\n | grade_1 | 0.1 | 0.1 | 0.1 | 0.1 | 0.1 | 0.1 |\n +---------+---------+---------+---------+---------+---------+---------+\n | grade_2 | 0.8 | 0.8 | 0.7 | 0.7 | 0.8 | 0.8 |\n +---------+---------+---------+---------+---------+---------+---------+\n\n >>> cpd.values\n array([[[ 0.1, 0.1],\n [ 0.2, 0.2],\n [ 0.1, 0.1]],\n\n [[ 0.1, 0.1],\n [ 0.1, 0.1],\n [ 0.1, 0.1]],\n\n [[ 0.8, 0.8],\n [ 0.7, 0.7],\n [ 0.8, 0.8]]])\n\n >>> cpd.variables\n ['grade', 'intel', 'diff']\n >>> cpd.cardinality\n array([3, 3, 2])\n >>> cpd.variable\n 'grade'\n >>> cpd.variable_card\n 3\n \"\"\"\n if (len(self.variables) <= 1 or (set(new_order) - set(self.variables)) or\n (set(self.variables[1:]) - set(new_order))):\n raise ValueError(\"New order either has missing or extra arguments\")\n else:\n if new_order != self.variables[1:]:\n evidence = self.variables[1:]\n evidence_card = self.cardinality[1:]\n card_map = dict(zip(evidence, evidence_card))\n old_pos_map = dict(zip(evidence, range(len(evidence))))\n trans_ord = [0] + [(old_pos_map[letter] + 1) for letter in new_order]\n new_values = np.transpose(self.values, trans_ord)\n\n if inplace:\n variables = [self.variables[0]] + new_order\n cardinality = [self.variable_card] + [card_map[var] for var in new_order]\n super(TabularCPD, self).__init__(variables, cardinality, new_values.flatten('C'))\n return self.get_cpd()\n else:\n return new_values.reshape(self.cardinality[0], np.prod([card_map[var] for var in new_order]))\n else:\n warn(\"Same ordering provided as current\")\n return self.get_cpd()\n\n def get_evidence(self):\n return self.variables[:0:-1]\n\n# Commenting out because not used anywhere for now and not implemented in a very good way.\n# class TreeCPD(nx.DiGraph):\n# \"\"\"\n# Base Class for Tree CPD.\n# \"\"\"\n# def __init__(self, data=None):\n# \"\"\"\n# Base Class for Tree CPD.\n#\n# Parameters\n# ----------\n# data: input tree\n# Data to initialize the tree. If data=None (default) an empty\n# tree is created. The data can be an edge list with label for\n# each edge. Label should be the observed value of the variable.\n#\n# Examples\n# --------\n# For P(A|B, C, D), to construct a tree like:\n#\n# B\n# 0 / \\1\n# / \\\n# P(A|b_0) C\n# 0/ \\1\n# / \\\n# P(A|b_1, c_0) D\n# 0/ \\\n# / \\\n# P(A|b_1,c_1,d_0) P(A|b_1,c_1,d_1)\n#\n# >>> from pgmpy.factors import TreeCPD, DiscreteFactor\n# >>> tree = TreeCPD([('B', DiscreteFactor(['A'], [2], [0.8, 0.2]), '0'),\n# ... ('B', 'C', '1'),\n# ... ('C', DiscreteFactor(['A'], [2], [0.1, 0.9]), '0'),\n# ... ('C', 'D', '1'),\n# ... ('D', DiscreteFactor(['A'], [2], [0.9, 0.1]), '0'),\n# ... ('D', DiscreteFactor(['A'], [2], [0.4, 0.6]), '1')])\n# \"\"\"\n# nx.DiGraph.__init__(self)\n# # TODO: Check cycles and self loops.\n# if data:\n# for edge in data:\n# if len(edge) != 3:\n# raise ValueError(\"Each edge tuple must have 3 values (u, v, label).\")\n# self.add_edge(edge[0], edge[1], label=edge[2])\n#\n# def add_edge(self, u, v, label):\n# \"\"\"\n# Add an edge between u and v.\n#\n# The nodes u and v will be automatically added if they are\n# not already in the graph.\n#\n# Parameters\n# ----------\n# u,v: nodes\n# Nodes can be any hashable (and not None) Python object.\n# label: string\n# Label should be value of the variable observed.\n# (underscore separated if multiple variables)\n# attr_dict: dictionary, optional (default= no attributes)\n# Dictionary of edge attributes. Key/Value pairs will\n# update existing data associated with the edge.\n# attr: Keyword arguments, optional\n# Edge data can be assigned using keyword arguments.\n#\n# Examples\n# --------\n# >>> from pgmpy.factors import TreeCPD, DiscreteFactor\n# >>> tree = TreeCPD([('B', DiscreteFactor(['A'], [2], [0.8, 0.2]), 0),\n# ... ('B', 'C', 1)])\n# >>> tree.add_edge('C', DiscreteFactor(['A'], [2], [0.1, 0.9]), label=0)\n# \"\"\"\n# if u != v:\n# if u in self.nodes() and v in self.nodes() and nx.has_path(self, v, u):\n# # check if adding edge (u, v) forms a cycle\n# raise ValueError(\n# 'Loops are not allowed. Adding the edge from (%s->%s) forms a loop.' % (u, v))\n# else:\n# super(TreeCPD, self).add_edge(u, v, label=label)\n# else:\n# raise ValueError('Self loops are not allowed. Edge (%s->%s) forms a self loop.' % (u, v))\n#\n# def add_edges_from(self, ebunch):\n# \"\"\"\n# Add all the edges in ebunch.\n#\n# Parameters\n# ----------\n# ebunch : container of edges\n# Each edge given in the container will be added to the\n# graph. The edges must be given as as 3-tuples (u,v,label).\n# attr_dict : dictionary, optional (default= no attributes)\n# Dictionary of edge attributes. Key/value pairs will\n# update existing data associated with each edge.\n# attr : keyword arguments, optional\n# Edge data (or labels or objects) can be assigned using\n# keyword arguments.\n#\n# Examples\n# --------\n# >>> from pgmpy.factors import TreeCPD, DiscreteFactor\n# >>> tree = TreeCPD()\n# >>> tree.add_edges_from([('B', 'C', 1), ('C', 'D', 1),\n# ... ('D', DiscreteFactor(['A'], [2], [0.6, 0.4]))])\n# \"\"\"\n# for edge in ebunch:\n# if len(edge) == 2:\n# raise ValueError(\"Each edge tuple must have 3 values (u, v, label).\")\n# nx.DiGraph.add_edges_from(self, [(edge[0], edge[1], {'label': edge[2]}) for edge in ebunch])\n#\n# def to_tabular_cpd(self, parents_order=None):\n# edge_attributes = nx.get_edge_attributes(self, 'label')\n# edge_values = {}\n# edge_dict = {}\n# adjlist = {}\n# node_list = []\n# stack = []\n# values = []\n# cardinality = []\n#\n# for edge in edge_attributes:\n# edge_dict.setdefault(edge[0], []).append(edge_attributes[edge])\n# if isinstance(edge[1], DiscreteFactor):\n# variable = edge[1].scope()\n# variable_card = edge[1].cardinality\n# edge_values[(edge[0], edge[0] + edge_attributes.get(edge))] = edge[1].values.tolist()\n# else:\n# edge_values[(edge[0], edge[0] + edge_attributes.get(edge))] = edge[1]\n# #adjlist\n# for source in self.nodes():\n# if not isinstance(source, DiscreteFactor):\n# adjlist[source] = [i[1] for i in edge_attributes if not isinstance(i[1], DiscreteFactor) and i[0] == source]\n# adjlist[source] = sorted(adjlist[source], key=lambda x: (len(nx.descendants(self, x)), x))\n#\n# root = [node for node, in_degree in self.in_degree().items() if in_degree == 0][0]\n# stack.append(root)\n#\n# #dfs\n# while stack:\n# top_node = stack[-1]\n# node_list.append(top_node)\n# stack = stack[:-1]\n# for end_node in adjlist[top_node]:\n# stack.append(end_node)\n#\n# for node in node_list:\n# cardinality.append(len(edge_dict[node]))\n#\n# for i in product(*[range(index) for index in cardinality]):\n# edge_list = [a + str(b) for a, b in zip(node_list, i)]\n# current_node = root\n# for edge in edge_list:\n# if (current_node, edge) in edge_values.keys():\n# if not isinstance(edge_values[(current_node, edge)], list):\n# current_node = edge_values[(current_node, edge)]\n# else:\n# values.append(edge_values[(current_node, edge)])\n# break\n#\n# values = np.array(values).flatten('F').reshape((len(values[0]), len(values)))\n# return TabularCPD(variable[0], int(variable_card[0]), values, node_list[::-1], cardinality)\n#\n# def to_rule_cpd(self):\n# \"\"\"\n# Returns a RuleCPD object which represents the TreeCPD\n#\n# Examples\n# --------\n# >>> from pgmpy.factors import TreeCPD, DiscreteFactor\n# >>> tree = TreeCPD([('B', factors(['A'], [2], [0.8, 0.2]), '0'),\n# ... ('B', 'C', '1'),\n# ... ('C', factors(['A'], [2], [0.1, 0.9]), '0'),\n# ... ('C', 'D', '1'),\n# ... ('D', factors(['A'], [2], [0.9, 0.1]), '0'),\n# ... ('D', factors(['A'], [2], [0.4, 0.6]), '1')])\n# >>> tree.to_rule_cpd()\n#\n# \"\"\"\n# # TODO: This method assumes that factors class has a get_variable method. Check this after merging navin's PR.\n# root = [node for node, in_degree in self.in_degree().items() if in_degree == 0][0]\n# paths_root_to_factors = {target: path for target, path in nx.single_source_shortest_path(self, root).items() if\n# isinstance(target, DiscreteFactor)}\n# for node in self.nodes_iter():\n# if isinstance(node, DiscreteFactor):\n# rule_cpd = RuleCPD(node.scope()[0])\n#\n# for factor, path in paths_root_to_factors.items():\n# rule_key = []\n# for node_index in range(len(path) - 1):\n# rule_key.append(path[node_index] + '_' + self.edge[path[node_index]][path[node_index + 1]]['label'])\n# for value_index in range(len(factor.values)):\n# rule_key.append(factor.get_variables()[0] + '_' + str(value_index))\n# rule_cpd.add_rules({tuple(sorted(rule_key)): factor.values[value_index]})\n# return rule_cpd\n#\n#\n# class RuleCPD:\n# def __init__(self, variable, rules=None):\n# \"\"\"\n# Base class for Rule CPD.\n#\n# Parameters\n# ----------\n# variable: str\n# The variable for which the CPD is to be defined.\n#\n# rules: dict. (optional)\n# dict of rules. Each rule should be in the form of\n# tuple_of_assignment: probability.\n# For example: ('A_0', 'J_0'): 0.8\n#\n# Examples\n# --------\n# For constructing a RuleCPD on variable A with the following rules:\n# p1: <A_0, B_0; 0.8>\n# p2: <A_1, B_0; 0.2>\n# p3: <A_0, B_1, C_0; 0.4>\n# p4: <A_1, B_1, C_0; 0.6>\n# p5: <A_0, B_1, C_1; 0.9>\n# p6: <A_1, B_1, C_1; 0.1>\n#\n# >>> from pgmpy.factors import RuleCPD\n# >>> rule = RuleCPD('A', {('A_0', 'B_0'): 0.8,\n# ... ('A_1', 'B_0'): 0.2,\n# ... ('A_0', 'B_1', 'C_0'): 0.4,\n# ... ('A_1', 'B_1', 'C_0'): 0.6,\n# ... ('A_0', 'B_1', 'C_1'): 0.9,\n# ... ('A_1', 'B_1', 'C_1'): 0.1})\n# \"\"\"\n# self.variable = variable\n# if rules:\n# self.rules = {}\n# for rule, value in rules.items():\n# self.rules[tuple(sorted(rule))] = value\n# else:\n# self.rules = {}\n# verify = self._verify()\n# if not verify[0]:\n# del self\n# raise ValueError(str(verify[1]) + \" and \" + str(verify[2]) + \" point to the same assignment\")\n#\n# def _verify(self):\n# \"\"\"\n# Verifies the RuleCPD for multiple values of the\n# assignment.\n# \"\"\"\n# from itertools import combinations\n# for rule, another_rule in combinations(self.rules, 2):\n# rule, another_rule = (rule, another_rule) if len(rule) < len(another_rule) else (another_rule, rule)\n# if not set(rule) - set(another_rule):\n# return False, rule, another_rule\n# return True,\n#\n# def add_rules(self, rules):\n# \"\"\"\n# Add one or more rules to the Rule CPD.\n#\n# Parameters\n# ----------\n# rules: dict\n# dict of rules. Each rule should be in the form of\n# tuple_of_assignment: probability.\n# For example: ('A_0', 'J_0'): 0.8\n#\n# Examples\n# --------\n# >>> from pgmpy.factors import RuleCPD\n# >>> rule = RuleCPD(variable='A')\n# >>> rule.add_rules({('A_0', 'B_0'): 0.8,\n# ... ('A_1', 'B_0'): 0.2})\n# \"\"\"\n# for rule in rules:\n# self.rules[rule] = rules[rule]\n# verify = self._verify()\n# if not verify[0]:\n# for rule in rules:\n# del(self.rules[rule])\n# raise ValueError(str(verify[1]) + \" and \" + str(verify[2]) + \" point to the same assignment\")\n#\n# def scope(self):\n# \"\"\"\n# Returns a set of variables which is the scope of the Rule CPD.\n#\n# Examples\n# --------\n# >>> from pgmpy.factors import RuleCPD\n# >>> rule = RuleCPD('A', {('A_0', 'B_0'): 0.8,\n# >>> ('A_1', 'B_0'): 0.2,\n# >>> ('A_0', 'B_1', 'C_0'): 0.4,\n# >>> ('A_1', 'B_1', 'C_0'): 0.6,\n# >>> ('A_0', 'B_1', 'C_!'): 0.9,\n# >>> ('A_1', 'B_1', 'C_1'): 0.1}\n# >>> rule.scope()\n# {'A', 'B', 'C'}\n# \"\"\"\n# scope = set()\n# for rule in self.rules:\n# scope.update([assignment.split('_')[0] for assignment in rule])\n# return scope\n#\n# def cardinality(self, variable=None):\n# \"\"\"\n# Returns a dict of variable: cardinality.\n#\n# Parameters\n# ----------\n# variable: string, list\n# variable or list of variables whose cardinality will be returned.\n#\n# Examples\n# --------\n# >>> from pgmpy.factors import RuleCPD\n# >>> rule = RuleCPD('A', {('A_0', 'B_0'): 0.8,\n# >>> ('A_1', 'B_0'): 0.2,\n# >>> ('A_0', 'B_1', 'C_0'): 0.4,\n# >>> ('A_1', 'B_1', 'C_0'): 0.6,\n# >>> ('A_0', 'B_1', 'C_!'): 0.9,\n# >>> ('A_1', 'B_1', 'C_1'): 0.1}\n# >>> rule.cardinality()\n# {'A': 2, 'B': 2, 'C': 2}\n# \"\"\"\n# from itertools import chain\n# from collections import Counter\n# assignments = set(chain.from_iterable(self.rules))\n# cardinality = dict(Counter([element.split('_')[0] for element in assignments]))\n# if variable:\n# return cardinality[variable] if isinstance(variable, str) else {var: cardinality[var] for var in variable}\n# else:\n# return cardinality\n#\n# def to_tabular_cpd(self, parents_order=None):\n# \"\"\"\n# Returns an equivalent TabularCPD.\n#\n# Parameters\n# ----------\n# parents_order: array-like. list, tuple. (optional)\n# The order of the evidence variables.\n#\n# Examples\n# --------\n# >>> from pgmpy.factors import RuleCPD\n# >>> rule = RuleCPD('A', {('A_0', 'B_0'): 0.8,\n# >>> ('A_1', 'B_0'): 0.2,\n# >>> ('A_0', 'B_1', 'C_1'): 0.9,\n# >>> ('A_1', 'B_1', 'C_1'): 0.1,\n# >>> ('A_0', 'B_1', 'C_0', 'D_0'): 0.4,\n# >>> ('A_1', 'B_1', 'C_0', 'D_0'): 0.6,\n# >>> ('A_0', 'B_1', 'C_0', 'D_1'): 0.3,\n# >>> ('A_1', 'B_1', 'C_0', 'D_1'): 0.7})\n# >>> rule.to_tabular_cpd()\n# \"\"\"\n# if not parents_order:\n# parents_order = sorted(self.scope() - {self.variable})\n# cardinality_dict = self.cardinality()\n# cardinality_product = np.product(list(cardinality_dict.values()))\n# tabular_cpd = [[0] * cardinality_product\n# for _ in range(cardinality_dict[self.variable])]\n# for rule, value in self.rules:\n# start, end = 0, cardinality_product\n# for var in sorted(rule):\n# if var.split('_')[0] != self.variable:\n# start, end = (start + (end-start)/cardinality_dict[var] * int(var.split('_')[1]),\n# start + (end-start)/cardinality_dict[var] * (int(var.split('_')[1]) + 1))\n# else:\n# var_assignment = int(var.split('_')[1])\n# for index in range(start, end):\n# tabular_cpd[var_assignment][index] = value\n#\n# return TabularCPD(self.variable, cardinality_dict[self.variable], tabular_cpd,\n# parents_order, [cardinality_dict[var] for var in parents_order])\n#\n# def _merge(self):\n# \"\"\"\n# Removes the variable from the rules and then merges the rules\n# having the same variables.\n# For example:\n# If we are given these rules:\n# ('A_0', 'B_0'): 0.8,\n# ('A_1', 'B_0'): 0.2,\n# ('A_0', 'B_1', 'C_1'): 0.9,\n# ('A_1', 'B_1', 'C_1'): 0.1,\n# ('A_0', 'B_1', 'C_0', 'D_0'): 0.4,\n# ('A_1', 'B_1', 'C_0', 'D_0'): 0.6,\n# ('A_0', 'B_1', 'C_0', 'D_1'): 0.3,\n# ('A_1', 'B_1', 'C_0', 'D_1'): 0.7\n#\n# then after merging _merge will return this dict:\n# {('B_0',): array([ 0.8, 0.2]),\n# ('B_1', 'C_0', 'D_1'): array([ 0.3, 0.7]),\n# ('B_1', 'C_1'): array([ 0.9, 0.1]),\n# ('B_1', 'C_0', 'D_0'): array([ 0.4, 0.6])}\n# \"\"\"\n# var_card = self.cardinality(self.variable)\n# dict_without_var = {}\n# for assignments in self.rules.keys():\n# dict_without_var[tuple(sorted([var for var in assignments if not var.startswith(self.variable)]))] = None\n# for key in dict_without_var:\n# value_list = []\n# for assign in range(var_card):\n# value_list.append(self.rules[tuple(sorted(list(key) + [(self.variable + '_' + str(assign))]))])\n# dict_without_var[key] = np.array(value_list)\n# return dict_without_var\n#\n# def to_tree_cpd(self):\n# \"\"\"\n# Return a TreeCPD object which represents the RuleCPD.\n#\n# Examples\n# --------\n# >>> from pgmpy.factors import RuleCPD\n# >>> rule = RuleCPD('A', {('A_0', 'B_0'): 0.8,\n# ... ('A_1', 'B_0'): 0.2,\n# ... ('A_0', 'B_1', 'C_1'): 0.9,\n# ... ('A_1', 'B_1', 'C_1'): 0.1,\n# ... ('A_0', 'B_1', 'C_0', 'D_0'): 0.4,\n# ... ('A_1', 'B_1', 'C_0', 'D_0'): 0.6,\n# ... ('A_0', 'B_1', 'C_0', 'D_1'): 0.3,\n# ... ('A_1', 'B_1', 'C_0', 'D_1'): 0.7})\n# >>> rule.to_tree_cpd()\n# <CPD.TreeCPD object at 0x7f6b6f952fd0>\n# \"\"\"\n# from collections import OrderedDict\n# tree_cpd = TreeCPD()\n# merged_rules = OrderedDict(sorted(self._merge().items(), key=lambda t: len(t[0])))\n#\n# for assignments, value in merged_rules.items():\n# for assignment_index in range(len(assignments) - 1):\n# tree_cpd.add_edge(assignments[assignment_index].split('_')[0],\n# assignments[assignment_index+1].split('_')[0],\n# assignments[assignment_index].split('_')[1])\n# tree_cpd.add_edge(assignments[-1].split('_')[0],\n# DiscreteFactor([self.variable], [len(value)], value),\n# assignments[-1].split('_')[1])\n# return tree_cpd\n#\n# def __str__(self):\n# from collections import OrderedDict\n# string = \"\"\n# for index, key in enumerate(OrderedDict(sorted(self.rules.items(), key=lambda t: len(t[0])))):\n# key_string = ', '.join(key)\n# string += 'p' + str(index) + ': <' + key_string + '; ' + str(self.rules[key]) + '>' + '\\n'\n# return string\n" ]
[ [ "numpy.array", "numpy.prod", "numpy.transpose" ] ]
hoxbug/Computational_Geometry
[ "9672afa17f9a7c79e2285adb0398a45873e657f2" ]
[ "plotpoints.py" ]
[ "import matplotlib.pyplot as plt\nfrom convexhull import Point, readDataPts, isPtOnSegment, segmentIntn\n\ndef plot_points(listPts, plane, color = 'red', size = 4):\n \"\"\"Plots a given list of (x, y) values on a given figure\"\"\"\n x = []\n y = []\n for points in listPts:\n x.append(points[0])\n y.append(points[1])\n\n plane.scatter(x, y, s = size, c = color, edgecolors = color)\n\ndef draw_line(plot_list, plane, color = 'blue'):\n for ptA, ptB in plot_list:\n plane.plot([ptA[0], ptB[0]], [ptA[1], ptB[1]], c = color)\n\ndef main():\n \"\"\"Main function\"\"\"\n #listPts = readDataPts('Data/A_10.dat')\n fig = plt.figure()\n plane = fig.add_subplot(1, 1, 1)\n\n A = Point(5, 5)\n B = Point(10, 10)\n C = Point(9, 9)\n D = Point(9, 13)\n E = Point(4, 7)\n F = Point(9, 7)\n G = Point(1, 1)\n H = Point(4, 4)\n I = Point(10, 5)\n J = Point(15, 10)\n\n listPts = [A, B, C, D, E, F, G, H, J]\n listLines = [(A, B), (C, D), (E, F), (G, H), (I, J)]\n\n plot_points(listPts, plane)\n draw_line(listLines, plane)\n\n draw_line([], fig)\n plt.show()\n\n\nif __name__ == \"__main__\":\n main()\n" ]
[ [ "matplotlib.pyplot.show", "matplotlib.pyplot.figure" ] ]
brettgohre/still_life_rendering_gqn
[ "66053435f7b9e729bbebbef34c171a8fb72e1630" ]
[ "preprocess/make_dataset.py" ]
[ "import tensorflow as tf\nimport numpy as np\nimport os\nfrom glob import glob\nfrom skimage.io import imread\n\n\n\ndef make_dataset():\n\n # First 130 scenes. 12 facing away from wall.\n final_frames = []\n final_viewpoints = []\n frames = np.ndarray(shape=(12, 6, 64, 64, 3), dtype=float)\n viewpoints = np.ndarray(shape=(12, 6, 7), dtype=float)\n folder_choices = np.random.choice(235, 12, replace=False)\n\n list1 = np.arange(12).tolist()\n views1 = [[-1., -1., 0., 0.707, 0.707, 0., 1.],\n [-0.5, -1., 0., 1., 0., 0., 1.],\n [0.5, -1., 0., 1., 0., 0., 1.],\n [1., -1., 0., 0.707, -0.707, 0., 1.],\n [1., -0.5, 0., 0., -1., 0., 1.],\n [1., 0.5, 0., 0., -1., 0., 1.],\n [1., 1., 0., -0.707, -0.707, 0., 1.],\n [0.5, 1., 0., -1, 0., 0., 1.],\n [-0.5, 1., 0., -1., 0., 0., 1.],\n [-1., 1., 0., -0.707, 0.707, 0., 1.],\n [-1., 0.5, 0., 0., 1., 0., 1.],\n [-1, -0.5, 0., 0., 1., 0., 1.]]\n\n # Scenes 131 and up. 8 center facing.\n list1 = np.arange(8).tolist()\n views2 = [[-1., -1., 0., 0.707, 0.707, 0., 1.],\n [0., -1., 0., 1., 0., 0., 1.],\n [1., -1., 0., 0.707, -0.707, 0., 1.],\n [1., 0., 0., 0., -1., 0., 1.],\n [1., 1., 0., -0.707, -0.707, 0., 1.],\n [0., 1., 0., -1., 0., 0., 1.],\n [-1., 1., 0., -0.707, 0.707, 0., 1.],\n [-1., 0., 0., 0., 1., 0., 1.]]\n\n\n for element in folder_choices:\n\n if element < 129:\n file_choices = []\n view_choices = []\n name = \"/Users/brett/Documents/Photos/Fruit_Stills/fruit_stills_2/fruit_stills/Scene\" + str(element+1) + \"/*\"\n list_of_files = glob(name)\n index = np.random.choice(12, 6, replace=False).tolist()\n for nn in index:\n nn = int(nn)\n view_choices.append(views1[nn])\n file_choices.append(list_of_files[nn])\n frames = np.asarray([imread(file) for file in file_choices])\n final_frames.append(frames)\n viewpoints = np.asarray(view_choices)\n final_viewpoints.append(viewpoints)\n # print(np.shape(frames))\n\n\n else:\n file_choices = []\n view_choices = []\n name = \"/Users/brett/Documents/Photos/Fruit_Stills/fruit_stills_2/fruit_stills/Scene\" + str(element+1) + \"/*\"\n list_of_files = glob(name)\n index = np.random.choice(8, 6, replace=False).tolist()\n for nnn in index:\n nnn = int(nnn)\n view_choices.append(views2[nnn])\n file_choices.append(list_of_files[nnn])\n frames = np.asarray([imread(file) for file in file_choices])\n final_frames.append(frames)\n viewpoints = np.asarray(view_choices)\n final_viewpoints.append(viewpoints)\n\n # print(np.shape(frames))\n\n final_frames = np.asarray(final_frames)\n final_frames = final_frames.astype(np.float32)\n frames = 2 * ((1/255) * final_frames) - 1\n frames = frames.astype(np.float32)\n viewpoints = np.asarray(final_viewpoints)\n viewpoints = viewpoints.astype(np.float32)\n# print(np.shape(frames))\n# print(np.shape(viewpoints))\n return frames, viewpoints\n\n\n# attempt at generator\n\ndef your_iterator():\n # make_dataset() --> (12, 6, 64, 64, 3) , (12, 6, 7)\n frames, viewpoints = make_dataset()\n frames = tf.convert_to_tensor(frames, np.float32)\n viewpoints = tf.convert_to_tensor(viewpoints, np.float32)\n yield frames, viewpoints\n\n# for i in range(len(frames)):\n# frames = frames[i]\n# viewpoints = viewpoints[i]\n# yield frames, viewpoint\n\ng = your_iterator()\nf, v = next(g)\n\nprint(f)\nprint(v)\n\nprint(f[:, :-1])\nprint(f[:, -1])\n\n\n# run with ipython -i preprocess.py\n" ]
[ [ "tensorflow.convert_to_tensor", "numpy.random.choice", "numpy.asarray", "numpy.arange", "numpy.ndarray" ] ]
AndrewReynen/WaveformGUI
[ "22a08dbc4215e50685dfdb68cd8729f7d539d76b" ]
[ "lazylyst/Plugins/Locate.py" ]
[ "from __future__ import print_function\r\nimport warnings\r\n\r\nimport numpy as np\r\nimport scipy.optimize as optimize\r\nwarnings.simplefilter(\"ignore\", optimize.OptimizeWarning)\r\n\r\nfrom StationMeta import unitConversionDict\r\n\r\n# Get the velocity and delay values based on the current source...\r\n# ...used for the simple locator (see simpleLocatorFunc for the equation, units in km and s)\r\n# ...Vp=P-velocity,Vs=S-velocity,Dp=P-delay,Ds=S-delay\r\n# ...tResThresh is the time residual which is residual value beyond which is considered poor\r\ndef getVelDelay(sourceDict):\r\n # Ensure all required values are present\r\n if 'Velocity' not in sourceDict.keys():\r\n return '$pass'\r\n velDict={}\r\n for key in ['Vp','Vs','Dp','Ds','tResThresh']:\r\n if key not in sourceDict['Velocity'].keys():\r\n return '$pass'\r\n velDict[key]=sourceDict['Velocity'][key]\r\n return velDict\r\n\r\n# Function to calculate the arrival times\r\n# ti=function((xi,yi,zi,vi,di),x0,y0,t0)\r\n# ti=t0+(Dist+Vel*Delay)/Vel\r\ndef simpleLocatorFunc(data,x0,y0,z0,t0):\r\n return t0+((((data[:,0]-x0)**2+(data[:,1]-y0)**2+(data[:,2]-z0)**2)**0.5)+data[:,3]*data[:,4])/data[:,3]\r\n\r\n# Gather the information to be sent to the location minimization function\r\ndef getPickData(pickSet,staLoc,vdInfo,mapProj):\r\n # Form array to be able to send to the 0 dimensional travel time function\r\n data,stas=[],[] #[xi,yi,zi,vi,ti],[]\r\n for aPick in pickSet:\r\n # Ensure that this pick has station metadata present\r\n idx=np.where(staLoc[:,0]==aPick[0])[0]\r\n if len(idx)<1:\r\n continue\r\n aStaX,aStaY,aStaZ=staLoc[idx[0],1:4].astype(float)\r\n # Assign appropriate velocity values \r\n if aPick[1]=='P':\r\n aVel=vdInfo['Vp']\r\n aDelay=vdInfo['Dp']\r\n elif aPick[1]=='S':\r\n aVel=vdInfo['Vs']\r\n aDelay=vdInfo['Ds']\r\n else:\r\n continue\r\n aTime=float(aPick[2]) ## Give more sig digs?... rough approximation anyways\r\n data.append([aStaX,aStaY,aStaZ,aVel,aDelay,aTime])\r\n stas.append(aPick[0])\r\n data=np.array(data)\r\n if len(data)>0:\r\n # Get the unit conversion factor between the default km and current\r\n convFactor=unitConversionDict()[mapProj['units']]/1000.0\r\n # Divide by factor to get the wanted velocity\r\n data[:,3]/=convFactor\r\n return np.array(data),np.array(stas,dtype=str)\r\n\r\n# Locate event using a straight ray path, and non-linear least squares curve fitting\r\n# Also assign residual coloring to the stations\r\n# Will not return a location if no velocities supplied, or stations are not projected\r\ndef simpleLocator(pickSet,staLoc,mapProj,staSort,sourceDict):\r\n # Convert from Lon,Lat,Ele to X,Y,Z\r\n staLoc[:,1:4]=mapProj['func'](staLoc[:,1:4])\r\n # Use only P and S picks\r\n if len(pickSet)>=4:\r\n pickSet=pickSet[np.where((pickSet[:,1]=='P')|(pickSet[:,1]=='S'))]\r\n # Set up the pen assignment arrays\r\n if len(staLoc)==0:\r\n traceBgPenAssign={'noStaData':list(staSort)}\r\n else:\r\n traceBgPenAssign={'noStaData':[sta for sta in staSort if sta not in staLoc[:,0]]}\r\n if len(staSort)==0:\r\n mapStaPenAssign={'noTraceData':[row[0] for row in staLoc]}\r\n else:\r\n mapStaPenAssign={'noTraceData':[row[0] for row in staLoc if row[0] not in staSort]}\r\n mapStaPenAssign['goodMap']=list(np.unique(pickSet[:,0]))\r\n # If there is no vpInfo defined or the stations are not projected, do not update the location\r\n vdInfo=getVelDelay(sourceDict)\r\n if vdInfo=='$pass' or mapProj['units']=='deg':\r\n return '$pass',traceBgPenAssign,mapStaPenAssign\r\n data,stas=getPickData(pickSet,staLoc,vdInfo,mapProj)\r\n # If there are too few picks, do not try to locate\r\n if len(data)<4:\r\n return np.empty((0,5)),traceBgPenAssign,mapStaPenAssign\r\n # Compute value to take away from the very large travel times (easier on the curve fitting)\r\n Tref=np.min(pickSet[:,2].astype(float))\r\n data[:,5]-=Tref\r\n # Solve for event origin parameters\r\n try:\r\n params, pcov = optimize.curve_fit(simpleLocatorFunc, data[:,:5], data[:,5],(0,0,0,0))\r\n x0,y0,z0,t0=params\r\n except:\r\n print('simpleLocator failed')\r\n return np.empty((0,5)),traceBgPenAssign,mapStaPenAssign\r\n # Get the residual values...\r\n # ...predicted arrival times\r\n ti=simpleLocatorFunc(data[:,:5],x0,y0,z0,t0)\r\n # Get the difference with the actual arrival times\r\n resids=np.abs(ti-data[:,5])\r\n poorResidStas=np.unique(stas[np.where(resids>=vdInfo['tResThresh'])])\r\n goodResidStas=np.unique(stas[np.where(resids<vdInfo['tResThresh'])])\r\n # Add the good/bad stations to proper pen assignments\r\n mapStaPenAssign['poorMap']=list(poorResidStas)\r\n mapStaPenAssign['goodMap']=list(goodResidStas)\r\n # Add back the time offset\r\n t0=Tref+t0\r\n eveLoc=np.array([[0,x0,y0,z0,t0]])\r\n # Convert back to Lon,Lat from X,Y\r\n eveLoc[:,1:4]=mapProj['funcInv'](eveLoc[:,1:4])\r\n return eveLoc,traceBgPenAssign,mapStaPenAssign" ]
[ [ "numpy.abs", "numpy.unique", "scipy.optimize.curve_fit", "numpy.array", "numpy.where", "numpy.empty" ] ]
qiujunlin/Segmentation
[ "b1514ca33bdf35737426de89850349aaf4ef59d4" ]
[ "dataset/DatasetUtro.py" ]
[ "import torch\nimport glob\nimport os\nimport sys\nimport numpy as np\nfrom torchvision import transforms\nfrom torchvision.transforms import functional as F\n#import cv2\nfrom PIL import Image\nimport random\nfrom imgaug import augmenters as iaa\nimport imgaug as ia\nclass Dataset(torch.utils.data.Dataset):\n\n def __init__(self, dataset_path,scale=(352,352),augmentations = True,hasEdg =False):\n super().__init__()\n self.augmentations = augmentations\n self.img_path=dataset_path+'/images/'\n self.mask_path=dataset_path+'/masks/'\n #self.edge_path = dataset_path +'/edgs/'\n self.scale =scale\n\n self.edge_flage = hasEdg\n self.images = [self.img_path + f for f in os.listdir(self.img_path) if f.endswith('.jpg') or f.endswith('.png')]\n self.gts = [self.mask_path + f for f in os.listdir(self.mask_path) if f.endswith('.png') or f.endswith(\".jpg\")]\n # self.edges = [self.edge_path + f for f in os.listdir(self.edge_path) if f.endswith('.png') or f.endswith(\".jpg\")]\n self.flip = iaa.SomeOf((2, 5), [\n iaa.ElasticTransformation(alpha=(0, 50), sigma=(4.0, 6.0)),\n\n iaa.PiecewiseAffine(scale=(0, 0.1), nb_rows=4, nb_cols=4, cval=0),\n iaa.Fliplr(0.5),\n iaa.Flipud(0.1),\n # iaa.Sharpen(alpha=(0, 1.0), lightness=(0.75, 1.5)),\n iaa.Affine(rotate=(-10, 10),\n scale={\"x\": (0.8, 1.2), \"y\": (0.8, 1.2)}),\n iaa.OneOf([\n iaa.GaussianBlur((0, 1.0)), # blur images with a sigma between 0 and 3.0\n iaa.AverageBlur(k=(3, 5)), # blur image using local means with kernel sizes between 2 and 7\n iaa.MedianBlur(k=(3, 5)), # blur image using local medians with kernel sizes between 2 and 7\n ]),\n iaa.contrast.LinearContrast((0.5, 1.5))],\n random_order=True)\n\n\n self.img_transform = transforms.Compose([\n transforms.Resize(scale,Image.BILINEAR),\n transforms.ToTensor(),\n transforms.Normalize([0.485, 0.456, 0.406],\n [0.229, 0.224, 0.225])])\n\n self.gt_transform = transforms.Compose([\n transforms.Resize(scale,Image.BILINEAR),\n transforms.ToTensor()])\n\n\n def __getitem__(self, index):\n img = self.rgb_loader(self.images[index])\n label = self.binary_loader(self.gts[index])\n img = img.resize(self.scale)\n label =label.resize(self.scale)\n img = np.array(img)\n\n label = np.array(label)\n label = label/255\n seq_det = self.flip.to_deterministic() # 固定变换\n segmap = ia.SegmentationMapsOnImage(label, shape=label.shape)\n img = seq_det.augment_image(img)\n label = seq_det.augment_segmentation_maps([segmap])[0].get_arr().astype(np.uint8)\n\n imgs = img.transpose(2, 0, 1) / 255.0\n img = torch.from_numpy(imgs.copy()).float()\n label = torch.from_numpy(label.copy()).float()\n label = label.unsqueeze(0)\n\n\n return img,label\n\n\n\n def rgb_loader(self, path):\n with open(path, 'rb') as f:\n img = Image.open(f)\n return img.convert('RGB')\n\n def binary_loader(self, path):\n with open(path, 'rb') as f:\n img = Image.open(f)\n # return img.convert('1')\n return img.convert('L')\n\n\n def __len__(self):\n return len(self.images)\n\n\nclass TestDataset(torch.utils.data.Dataset):\n\n def __init__(self, dataset_path,scale=(256,448)):\n super().__init__()\n self.img_path=dataset_path+'/images/'\n self.mask_path=dataset_path+'/masks/'\n self.images = [self.img_path + f for f in os.listdir(self.img_path) if f.endswith('.jpg') or f.endswith('.png')]\n self.gts = [self.mask_path + f for f in os.listdir(self.mask_path) if f.endswith('.png') or f.endswith(\".jpg\")]\n self.img_transform = transforms.Compose([\n transforms.Resize((scale)),\n transforms.ToTensor(),\n transforms.Normalize([0.485, 0.456, 0.406],\n [0.229, 0.224, 0.225])])\n self.gt_transform = transforms.ToTensor()\n\n\n def __getitem__(self, index):\n image = self.rgb_loader(self.images[index])\n gt = self.binary_loader(self.gts[index])\n image = self.img_transform(image)\n gt = self.gt_transform(gt)\n name = self.images[index].split('/')[-1]\n if name.endswith('.png'):\n name = name.split('.png')[0] + '.png'\n # print(gt.shape[1:])\n return image,gt,name\n\n\n def rgb_loader(self, path):\n with open(path, 'rb') as f:\n img = Image.open(f)\n return img.convert('RGB')\n\n def binary_loader(self, path):\n with open(path, 'rb') as f:\n img = Image.open(f)\n # return img.convert('1')\n return img.convert('L')\n\n\n def __len__(self):\n return len(self.images)\n\n\nif __name__ == '__main__':\n data = Dataset(r'E:\\dataset\\Ultro\\TrainDataset')\n print(data.__getitem__(0))\n\n\n\n\n" ]
[ [ "numpy.array" ] ]
renll/ComerNet
[ "d466e9b0c69f74003654c1cb0bcf6e5c591eaa9f" ]
[ "create_data.py" ]
[ "# -*- coding: utf-8 -*-\nimport copy\nimport json\nimport os\nimport re\nimport shutil\nimport urllib\nfrom collections import OrderedDict\nfrom io import BytesIO\nfrom zipfile import ZipFile\nimport difflib\nimport numpy as np\n\nnp.set_printoptions(precision=3)\n\nnp.random.seed(2)\n\n\n'''\nMost of the codes are from https://github.com/budzianowski/multiwoz\n'''\n\n\n# GLOBAL VARIABLES\nDICT_SIZE = 400\nMAX_LENGTH = 50\nIGNORE_KEYS_IN_GOAL = ['eod', 'topic', 'messageLen', 'message']\n\nfin = file('mapping.pair')\nreplacements = []\nfor line in fin.readlines():\n tok_from, tok_to = line.replace('\\n', '').split('\\t')\n replacements.append((' ' + tok_from + ' ', ' ' + tok_to + ' '))\n\n\ndef is_ascii(s):\n return all(ord(c) < 128 for c in s)\n\ndef insertSpace(token, text):\n sidx = 0\n while True:\n sidx = text.find(token, sidx)\n if sidx == -1:\n break\n if sidx + 1 < len(text) and re.match('[0-9]', text[sidx - 1]) and \\\n re.match('[0-9]', text[sidx + 1]):\n sidx += 1\n continue\n if text[sidx - 1] != ' ':\n text = text[:sidx] + ' ' + text[sidx:]\n sidx += 1\n if sidx + len(token) < len(text) and text[sidx + len(token)] != ' ':\n text = text[:sidx + 1] + ' ' + text[sidx + 1:]\n sidx += 1\n return text\n\ndef normalize(text, clean_value=True):\n # lower case every word\n text = text.lower()\n\n # replace white spaces in front and end\n text = re.sub(r'^\\s*|\\s*$', '', text)\n\n # hotel domain pfb30\n text = re.sub(r\"b&b\", \"bed and breakfast\", text)\n text = re.sub(r\"b and b\", \"bed and breakfast\", text)\n\n if clean_value:\n # normalize phone number\n ms = re.findall('\\(?(\\d{3})\\)?[-.\\s]?(\\d{3})[-.\\s]?(\\d{4,5})', text)\n if ms:\n sidx = 0\n for m in ms:\n sidx = text.find(m[0], sidx)\n if text[sidx - 1] == '(':\n sidx -= 1\n eidx = text.find(m[-1], sidx) + len(m[-1])\n text = text.replace(text[sidx:eidx], ''.join(m))\n\n # normalize postcode\n ms = re.findall('([a-z]{1}[\\. ]?[a-z]{1}[\\. ]?\\d{1,2}[, ]+\\d{1}[\\. ]?[a-z]{1}[\\. ]?[a-z]{1}|[a-z]{2}\\d{2}[a-z]{2})',\n text)\n if ms:\n sidx = 0\n for m in ms:\n sidx = text.find(m, sidx)\n eidx = sidx + len(m)\n text = text[:sidx] + re.sub('[,\\. ]', '', m) + text[eidx:]\n\n # weird unicode bug\n text = re.sub(u\"(\\u2018|\\u2019)\", \"'\", text)\n\n if clean_value:\n # replace time and and price\n text = re.sub(timepat, ' [value_time] ', text)\n text = re.sub(pricepat, ' [value_price] ', text)\n #text = re.sub(pricepat2, '[value_price]', text)\n\n # replace st.\n text = text.replace(';', ',')\n text = re.sub('$\\/', '', text)\n text = text.replace('/', ' and ')\n\n # replace other special characters\n text = text.replace('-', ' ')\n text = re.sub('[\\\"\\<>@\\(\\)]', '', text) # remove\n\n # insert white space before and after tokens:\n for token in ['?', '.', ',', '!']:\n text = insertSpace(token, text)\n\n # insert white space for 's\n text = insertSpace('\\'s', text)\n\n # replace it's, does't, you'd ... etc\n text = re.sub('^\\'', '', text)\n text = re.sub('\\'$', '', text)\n text = re.sub('\\'\\s', ' ', text)\n text = re.sub('\\s\\'', ' ', text)\n for fromx, tox in replacements:\n text = ' ' + text + ' '\n text = text.replace(fromx, tox)[1:-1]\n\n # remove multiple spaces\n text = re.sub(' +', ' ', text)\n\n # concatenate numbers\n tmp = text\n tokens = text.split()\n i = 1\n while i < len(tokens):\n if re.match(u'^\\d+$', tokens[i]) and \\\n re.match(u'\\d+$', tokens[i - 1]):\n tokens[i - 1] += tokens[i]\n del tokens[i]\n else:\n i += 1\n text = ' '.join(tokens)\n\n return text\n\ndef fixDelex(filename, data, data2, idx, idx_acts):\n \"\"\"Given system dialogue acts fix automatic delexicalization.\"\"\"\n try:\n turn = data2[filename.strip('.json')][str(idx_acts)]\n except:\n return data\n\n if not isinstance(turn, str) and not isinstance(turn, unicode):\n for k, act in turn.items():\n if 'Attraction' in k:\n if 'restaurant_' in data['log'][idx]['text']:\n data['log'][idx]['text'] = data['log'][idx]['text'].replace(\"restaurant\", \"attraction\")\n if 'hotel_' in data['log'][idx]['text']:\n data['log'][idx]['text'] = data['log'][idx]['text'].replace(\"hotel\", \"attraction\")\n if 'Hotel' in k:\n if 'attraction_' in data['log'][idx]['text']:\n data['log'][idx]['text'] = data['log'][idx]['text'].replace(\"attraction\", \"hotel\")\n if 'restaurant_' in data['log'][idx]['text']:\n data['log'][idx]['text'] = data['log'][idx]['text'].replace(\"restaurant\", \"hotel\")\n if 'Restaurant' in k:\n if 'attraction_' in data['log'][idx]['text']:\n data['log'][idx]['text'] = data['log'][idx]['text'].replace(\"attraction\", \"restaurant\")\n if 'hotel_' in data['log'][idx]['text']:\n data['log'][idx]['text'] = data['log'][idx]['text'].replace(\"hotel\", \"restaurant\")\n\n return data\n\n\ndef getDialogueAct(filename, data, data2, idx, idx_acts):\n \"\"\"Given system dialogue acts fix automatic delexicalization.\"\"\"\n acts = []\n try:\n turn = data2[filename.strip('.json')][str(idx_acts)]\n except:\n return acts\n\n if not isinstance(turn, str) and not isinstance(turn, unicode):\n for k in turn.keys():\n # temp = [k.split('-')[0].lower(), k.split('-')[1].lower()]\n # for a in turn[k]:\n # acts.append(temp + [a[0].lower()])\n\n if k.split('-')[1].lower() == 'request':\n for a in turn[k]:\n acts.append(a[0].lower())\n elif k.split('-')[1].lower() == 'inform':\n for a in turn[k]:\n acts.append([a[0].lower(), normalize(a[1].lower(), False)])\n\n return acts\n\n\ndef get_summary_bstate(bstate, get_domain=False):\n \"\"\"Based on the mturk annotations we form multi-domain belief state\"\"\"\n domains = [u'taxi',u'restaurant', u'hospital', u'hotel',u'attraction', u'train', u'police']\n summary_bstate = []\n summary_bvalue = []\n active_domain = []\n for domain in domains:\n domain_active = False\n\n booking = []\n #print(domain,len(bstate[domain]['book'].keys()))\n for slot in sorted(bstate[domain]['book'].keys()):\n if slot == 'booked':\n if len(bstate[domain]['book']['booked'])!=0:\n booking.append(1)\n # summary_bvalue.append(\"book {} {}:{}\".format(domain, slot, \"Yes\"))\n else:\n booking.append(0)\n else:\n if bstate[domain]['book'][slot] != \"\":\n booking.append(1)\n summary_bvalue.append([\"{}-book {}\".format(domain, slot.strip().lower()), normalize(bstate[domain]['book'][slot].strip().lower(), False)]) #([\"book\", domain, slot, bstate[domain]['book'][slot]])\n else:\n booking.append(0)\n if domain == 'train':\n if 'people' not in bstate[domain]['book'].keys():\n booking.append(0)\n if 'ticket' not in bstate[domain]['book'].keys():\n booking.append(0)\n summary_bstate += booking\n\n for slot in bstate[domain]['semi']:\n slot_enc = [0, 0, 0] # not mentioned, dontcare, filled\n if bstate[domain]['semi'][slot] == 'not mentioned':\n slot_enc[0] = 1\n elif bstate[domain]['semi'][slot] in ['dont care', 'dontcare', \"don't care\", \"do not care\"]:\n slot_enc[1] = 1\n summary_bvalue.append([\"{}-{}\".format(domain, slot.strip().lower()), \"dontcare\"]) #([\"semi\", domain, slot, \"dontcare\"])\n elif bstate[domain]['semi'][slot]:\n summary_bvalue.append([\"{}-{}\".format(domain, slot.strip().lower()), normalize(bstate[domain]['semi'][slot].strip().lower(), False)]) #([\"semi\", domain, slot, bstate[domain]['semi'][slot]])\n if slot_enc != [0, 0, 0]:\n domain_active = True\n summary_bstate += slot_enc\n\n # quasi domain-tracker\n if domain_active:\n summary_bstate += [1]\n active_domain.append(domain)\n else:\n summary_bstate += [0]\n\n #print(len(summary_bstate))\n assert len(summary_bstate) == 94\n if get_domain:\n return active_domain\n else:\n return summary_bstate, summary_bvalue\n\n\ndef analyze_dialogue(dialogue, maxlen):\n \"\"\"Cleaning procedure for all kinds of errors in text and annotation.\"\"\"\n d = dialogue\n # do all the necessary postprocessing\n if len(d['log']) % 2 != 0:\n #print path\n print('odd # of turns')\n return None # odd number of turns, wrong dialogue\n d_pp = {}\n d_pp['goal'] = d['goal'] # for now we just copy the goal\n usr_turns = []\n sys_turns = []\n # last_bvs = []\n for i in range(len(d['log'])):\n if len(d['log'][i]['text'].split()) > maxlen:\n print('too long')\n return None # too long sentence, wrong dialogue\n if i % 2 == 0: # usr turn\n text = d['log'][i]['text']\n if not is_ascii(text):\n print ('not ascii')\n return None\n usr_turns.append(d['log'][i])\n else: # sys turn\n text = d['log'][i]['text']\n if not is_ascii(text):\n print ('not ascii')\n return None\n belief_summary, belief_value_summary = get_summary_bstate(d['log'][i]['metadata'])\n d['log'][i]['belief_summary'] = str(belief_summary)\n d['log'][i]['belief_value_summary'] = belief_value_summary\n sys_turns.append(d['log'][i])\n d_pp['usr_log'] = usr_turns\n d_pp['sys_log'] = sys_turns\n\n return d_pp\n\n\ndef get_dial(dialogue):\n \"\"\"Extract a dialogue from the file\"\"\"\n dial = []\n d_orig = analyze_dialogue(dialogue, MAX_LENGTH) # max turn len is 50 words\n if d_orig is None:\n return None\n usr = [t['text'] for t in d_orig['usr_log']]\n sys = [t['text'] for t in d_orig['sys_log']]\n sys_a = [t['dialogue_acts'] for t in d_orig['sys_log']]\n bvs = [t['belief_value_summary'] for t in d_orig['sys_log']]\n domain = [t['domain'] for t in d_orig['usr_log']]\n for item in zip(usr, sys, sys_a, domain, bvs):\n dial.append({'usr':item[0],'sys':item[1], 'sys_a':item[2], 'domain':item[3], 'bvs':item[4]})\n return dial\n\n\ndef loadData():\n data_url = \"data/multi-woz/data.json\"\n dataset_url = \"https://www.repository.cam.ac.uk/bitstream/handle/1810/280608/MULTIWOZ2.zip?sequence=3&isAllowed=y\"\n if not os.path.exists(\"data\"):\n os.makedirs(\"data\")\n os.makedirs(\"data/multi-woz\")\n\n if not os.path.exists(data_url):\n print(\"Downloading and unzipping the MultiWOZ dataset\")\n resp = urllib.urlopen(dataset_url)\n zip_ref = ZipFile(BytesIO(resp.read()))\n zip_ref.extractall(\"data/multi-woz\")\n zip_ref.close()\n shutil.copy('data/multi-woz/MULTIWOZ2 2/data.json', 'data/multi-woz/')\n shutil.copy('data/multi-woz/MULTIWOZ2 2/valListFile.json', 'data/multi-woz/')\n shutil.copy('data/multi-woz/MULTIWOZ2 2/testListFile.json', 'data/multi-woz/')\n shutil.copy('data/multi-woz/MULTIWOZ2 2/dialogue_acts.json', 'data/multi-woz/')\n\n\ndef getDomain(idx, log, domains, last_domain):\n if idx == 1:\n active_domains = get_summary_bstate(log[idx][\"metadata\"], True) \n crnt_doms = active_domains[0] if len(active_domains)!=0 else domains[0]\n return crnt_doms\n else:\n ds_diff = get_ds_diff(log[idx-2][\"metadata\"], log[idx][\"metadata\"])\n if len(ds_diff.keys()) == 0: # no clues from dialog states\n crnt_doms = last_domain\n else:\n crnt_doms = ds_diff.keys()\n return crnt_doms[0] # How about multiple domains in one sentence senario ?\n\n\ndef get_ds_diff(prev_d, crnt_d):\n diff = {}\n # Sometimes, metadata is an empty dictionary, bug?\n if not prev_d or not crnt_d:\n return diff\n\n for ((k1, v1), (k2, v2)) in zip(prev_d.items(), crnt_d.items()):\n assert k1 == k2\n if v1 != v2: # updated\n diff[k2] = v2\n return diff\n\n\ndef createData():\n # download the data\n loadData()\n \n # create dictionary of delexicalied values that then we will search against, order matters here!\n # dic = delexicalize.prepareSlotValuesIndependent()\n delex_data = {}\n\n fin1 = file('data/multi-woz/data.json')\n data = json.load(fin1)\n\n fin2 = file('data/multi-woz/dialogue_acts.json')\n data2 = json.load(fin2)\n\n for didx, dialogue_name in enumerate(data):\n\n dialogue = data[dialogue_name]\n\n domains = []\n for dom_k, dom_v in dialogue['goal'].items():\n if dom_v and dom_k not in IGNORE_KEYS_IN_GOAL: # check whether contains some goal entities\n domains.append(dom_k)\n\n idx_acts = 1\n last_domain, last_slot_fill = \"\", []\n for idx, turn in enumerate(dialogue['log']):\n # normalization, split and delexicalization of the sentence\n origin_text = normalize(turn['text'], False)\n # origin_text = delexicalize.markEntity(origin_text, dic)\n dialogue['log'][idx]['text'] = origin_text\n\n if idx % 2 == 1: # if it's a system turn\n\n cur_domain = getDomain(idx, dialogue['log'], domains, last_domain)\n last_domain = [cur_domain]\n\n dialogue['log'][idx - 1]['domain'] = cur_domain\n dialogue['log'][idx]['dialogue_acts'] = getDialogueAct(dialogue_name, dialogue, data2, idx, idx_acts)\n idx_acts += 1\n\n # FIXING delexicalization:\n dialogue = fixDelex(dialogue_name, dialogue, data2, idx, idx_acts)\n \n delex_data[dialogue_name] = dialogue\n\n # if didx > 10:\n # break\n\n # with open('data/multi-woz/woz2like_data.json', 'w') as outfile:\n # json.dump(delex_data, outfile)\n\n return delex_data\n\n\ndef buildDelexDict(origin_sent, delex_sent):\n dictionary = {}\n s = difflib.SequenceMatcher(None, delex_sent.split(), origin_sent.split())\n bs = s.get_matching_blocks()\n for i, b in enumerate(bs):\n if i < len(bs)-2:\n a_start = b.a + b.size\n b_start = b.b + b.size\n b_end = bs[i+1].b\n dictionary[a_start] = \" \".join(origin_sent.split()[b_start:b_end])\n return dictionary\n\n\ndef divideData(data):\n \"\"\"Given test and validation sets, divide\n the data for three different sets\"\"\"\n testListFile = []\n fin = file('data/multi-woz/testListFile.json')\n for line in fin:\n testListFile.append(line[:-1])\n fin.close()\n\n valListFile = []\n fin = file('data/multi-woz/valListFile.json')\n for line in fin:\n valListFile.append(line[:-1])\n fin.close()\n\n trainListFile = open('data/trainListFile', 'w')\n\n test_dials = []\n val_dials = []\n train_dials = []\n \n # dictionaries\n word_freqs_usr = OrderedDict()\n word_freqs_sys = OrderedDict()\n\n count_train, count_val, count_test = 0, 0, 0\n \n for dialogue_name in data:\n # print dialogue_name\n dial_item = data[dialogue_name]\n domains = []\n for dom_k, dom_v in dial_item['goal'].items():\n if dom_v and dom_k not in IGNORE_KEYS_IN_GOAL: # check whether contains some goal entities\n domains.append(dom_k)\n\n dial = get_dial(data[dialogue_name])\n if dial:\n dialogue = {}\n dialogue['dialogue_idx'] = dialogue_name\n dialogue['domains'] = list(set(domains)) #list(set([d['domain'] for d in dial]))\n last_bs = []\n dialogue['dialogue'] = []\n\n for turn_i, turn in enumerate(dial):\n # usr, usr_o, sys, sys_o, sys_a, domain\n turn_dialog = {}\n turn_dialog['system_transcript'] = dial[turn_i-1]['sys'] if turn_i > 0 else \"\"\n turn_dialog['turn_idx'] = turn_i\n turn_dialog['belief_state'] = [{\"slots\": [s], \"act\": \"inform\"} for s in turn['bvs']]\n turn_dialog['turn_label'] = [bs[\"slots\"][0] for bs in turn_dialog['belief_state'] if bs not in last_bs] \n turn_dialog['transcript'] = turn['usr']\n turn_dialog['system_acts'] = dial[turn_i-1]['sys_a'] if turn_i > 0 else []\n turn_dialog['domain'] = turn['domain']\n last_bs = turn_dialog['belief_state']\n dialogue['dialogue'].append(turn_dialog)\n \n if dialogue_name in testListFile:\n test_dials.append(dialogue)\n count_test += 1\n elif dialogue_name in valListFile:\n val_dials.append(dialogue)\n count_val += 1\n else:\n trainListFile.write(dialogue_name + '\\n')\n train_dials.append(dialogue)\n count_train += 1\n\n print(\"# of dialogues: Train {}, Val {}, Test {}\".format(count_train, count_val, count_test))\n\n # save all dialogues\n with open('data/dev_dials.json', 'wb') as f:\n json.dump(val_dials, f, indent=4)\n\n with open('data/test_dials.json', 'wb') as f:\n json.dump(test_dials, f, indent=4)\n\n with open('data/train_dials.json', 'wb') as f:\n json.dump(train_dials, f, indent=4)\n\n # return word_freqs_usr, word_freqs_sys\n\n\ndef main():\n print('Create WOZ-like dialogues. Get yourself a coffee, this might take a while.')\n delex_data = createData()\n print('Divide dialogues...')\n divideData(delex_data)\n # print('Building dictionaries')\n # buildDictionaries(word_freqs_usr, word_freqs_sys)\n\n\nif __name__ == \"__main__\":\n main()\n" ]
[ [ "numpy.set_printoptions", "numpy.random.seed" ] ]
navies/neural_multistyle_transfer
[ "e122d57e4dee82a8076fec84b9a143cab8236df5" ]
[ "neural_multistyle/model.py" ]
[ "import torch\nimport torch.nn.functional as F\nimport torch.optim as optim\nimport torchvision.models as models\nfrom tqdm import tqdm\n\ndevice = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n\n\ndef gram_matrix(x):\n \"\"\"Computes the gram matrix of the input\n\n Parameters\n ----------\n input : tensor\n The tensor to compute the gram matrix\n \"\"\"\n a, b, c, d = x.size()\n features = x.view(a * b, c * d)\n # For input matrices with large dimensions, the gram matrix\n # typically has large values, thus we normalize\n return (features @ features.T) / (a * b * c * d)\n\n\nclass Normalization(torch.nn.Module):\n '''Normalization layer\n\n Normalizes the input tensor to match the model\n That is, every value x in the tensor is mapped to the standard score\n\n Attributes\n ----------\n mean : tensor\n The mean of the normalization\n std : tensor\n The standard deviation of the normalization\n Methods\n -------\n forward(x):\n Normalizes the input the this layer\n '''\n def __init__(self, mean, std):\n super(Normalization, self).__init__()\n self.mean = torch.tensor(mean).view(-1, 1, 1).to(device)\n self.std = torch.tensor(std).view(-1, 1, 1).to(device)\n\n def forward(self, x):\n return (x - self.mean) / self.std\n\n\nclass ContentLoss(torch.nn.Module):\n '''A dummy layer to compute the content loss at a given layer\n\n Attributes\n ----------\n target : tensor\n The hidden representation of the content image at this layer\n loss : num\n The content loss between the hidden representations of the content image\n and the input image at this layer\n '''\n def __init__(self):\n super(ContentLoss, self).__init__()\n # self.target = target.detach()\n self.target = None\n self.loss = None\n\n def forward(self, x):\n if self.target is not None:\n self.loss = F.mse_loss(x, self.target)\n return x\n\n\nclass StyleLoss(torch.nn.Module):\n '''A dummy layer to compute the style loss at a given layer\n\n Attributes\n ----------\n target : [tensor]\n The hidden representations of the style images at this layer\n loss : num\n The content loss between the hidden representations of the style images\n and the input image at this layer\n '''\n def __init__(self):\n super(StyleLoss, self).__init__()\n self.targets = None\n self.weights = None\n self.loss = None\n\n def forward(self, x):\n if self.targets is not None:\n self.loss = sum([\n w * F.mse_loss(gram_matrix(x), t)\n for w, t in zip(self.weights, self.targets)\n ])\n return x\n\n def __str__(self):\n return self.weights\n\n\nclass NeuralStyle(torch.nn.Module):\n \"\"\"Runs the multistyle transfer algorithms\n\n Attributes\n ----------\n content_layers : [str]\n A list of layers that contributes to the total content loss\n style_layers : [str]\n A list of layers that contributes to the total style loss\n weights : [int]\n For multistyle transfer, each value corresponds to the weight of that style\n in the total loss function\n style_images : [tensor]\n The style images for which we do multistyle transfer from\n content_image : tensor\n The content image for which we apply the mutlistyle transfer to\n\n Methods\n -------\n build_model(net, content_layers, style_layers)\n Builds a model for neural style transfer from VGG19\n calculate_loss(content_layers, style_layers)\n Calculates the total loss of an input image\n style_transfer_gd()\n Runs style transfer via repeatedly doing feedforward and backpropogation\n via gradient descent. This currently doesn't work\n style_transfer_lbfgs()\n Runs style transfer via repeatedly doing feedforward and backpropogation\n via lbfgs\n \"\"\"\n def __init__(self, content_layers, style_layers):\n super(NeuralStyle, self).__init__()\n self.model, self.content_layers, self.style_layers = self.init_model(\n content_layers, style_layers)\n\n self.style_targets = None\n self.weights = None\n\n def set_style_targets(self, targets, weights):\n with torch.no_grad():\n self.style_targets = targets\n self.weights = weights\n for layer in self.model.children():\n targets = [layer(target) for target in targets]\n if isinstance(layer, StyleLoss):\n layer.weights = weights\n layer.targets = [\n gram_matrix(target).detach() for target in targets\n ]\n\n @property\n def content_target(self):\n return self._content_target\n\n @content_target.setter\n def content_target(self, target):\n with torch.no_grad():\n self._content_target = target\n for layer in self.model.children():\n target = layer(target).detach()\n if isinstance(layer, ContentLoss):\n layer.target = target\n\n def init_model(self, content_layers, style_layers):\n '''Builds the model for multistyle neural style transfer from vgg19\n\n Parameters\n ----------\n content_layers : [str]\n A list of layers that contributes to the total content loss\n style_layers : [str]\n A list of layers that contributes to the total style loss\n '''\n # import vgg19 with the pretrained weights\n net = models.vgg19(pretrained=True).features.to(device).eval()\n # start our sequential model whose first layer in normalization\n model = torch.nn.Sequential()\n model.add_module(\n 'norm_0',\n Normalization(mean=[0.485, 0.456, 0.406],\n std=[0.229, 0.224, 0.225]))\n # keep track of the layers to compute style loss and content loss\n style_losses, content_losses = [], []\n i = 0\n for layer in net.children():\n if isinstance(layer, torch.nn.Conv2d):\n i += 1\n name = f'conv_{i}'\n elif isinstance(layer, torch.nn.ReLU):\n name = f'relu_{i}'\n # the ReLU layer in the vgg19 implementation is done in place\n # which will throw an error for autograd during backpropogation\n layer = torch.nn.ReLU(inplace=False)\n elif isinstance(layer, torch.nn.MaxPool2d):\n name = f'pool_{i}'\n # layer = torch.nn.AvgPool2d(layer.kernel_size)\n elif isinstance(layer, torch.nn.BatchNorm2d):\n name = f'bn_{i}'\n\n model.add_module(name, layer)\n\n # add dummy content loss layer\n if name in content_layers:\n # target = model(self._content_target).detach()\n layer = ContentLoss()\n model.add_module(f'content_loss_{i}', layer)\n content_losses.append(layer)\n\n # add dummy style loss layer\n if name in style_layers:\n # target = model(self._style_target).detach()\n layer = StyleLoss()\n model.add_module(f'style_loss_{i}', layer)\n style_losses.append(layer)\n\n # trim the remaining layers proceeding the last content loss or style loss layer\n for i in range(len(model) - 1, -1, -1):\n if isinstance(model[i], (ContentLoss, StyleLoss)):\n break\n\n return model[:i + 1], content_losses, style_losses\n\n def calculate_losses(self):\n '''Calculates the total loss of an input image\n '''\n content_loss = sum([lyr.loss for lyr in self.content_layers])\n style_loss = sum([lyr.loss for lyr in self.style_layers])\n\n return content_loss, style_loss\n\n def transfer(self,\n input_image,\n epochs=300,\n style_weight=1e6,\n content_weight=1,\n verbose=False):\n \"\"\"Runs style transfer via repeatedly doing feedforward and backpropogation via lbfgs\n\n Parameters\n ----------\n input_image : tensor\n The initial input image to be optimized.\n Example: white noise, content image, style image, or any image.\n epochs : int\n The number of epochs to run the lbfps algorithm for\n style_weight : num\n The weight of the total style loss function in the total loss function\n content_weight : num\n The weight of the total content loss function in the total loss function\n \"\"\"\n input_image.requires_grad_()\n optimizer = optim.LBFGS([input_image])\n\n losses = {'style': [], 'content': [], 'total': []}\n run = [1]\n images = []\n\n progressbar = tqdm(total=epochs)\n while run[0] < epochs:\n\n def closure():\n input_image.data.clamp_(0, 1)\n images.append(input_image.cpu().clone())\n optimizer.zero_grad()\n self.model(input_image)\n content_loss, style_loss = self.calculate_losses()\n total_loss = style_weight * style_loss + content_weight * content_loss\n total_loss.backward()\n\n if verbose:\n losses['style'].append(style_loss.item())\n losses['content'].append(content_loss.item())\n losses['total'].append(total_loss.item())\n if run[0] % 10 == 0:\n print(f'Epoch: {run[0]} | '\n f'Style loss: {style_loss} | '\n f'Content loss: {content_loss} |'\n f'Total Loss : {total_loss} | ')\n run[0] += 1\n progressbar.update(1)\n return total_loss\n\n optimizer.step(closure)\n\n input_image.data.clamp_(0, 1)\n images.append(input_image.cpu().clone())\n return input_image.detach(), images\n" ]
[ [ "torch.nn.Sequential", "torch.tensor", "torch.nn.functional.mse_loss", "torch.optim.LBFGS", "torch.no_grad", "torch.cuda.is_available", "torch.nn.ReLU" ] ]
ngocphucck/SimpleMLP
[ "e05cfce7e8f2e823f491c6564fa6c2c2e0cef420" ]
[ "optimizer.py" ]
[ "import numpy as np\n\n\nclass SGD(object):\n def __init__(self, parameters, grads, lr):\n self.parameters = parameters\n self.grads = grads\n self.lr = lr\n\n def zero_grad(self):\n for key in self.grads.keys():\n self.grads[key] = np.zeros(self.grads[key].shape)\n\n def step(self):\n for key in self.parameters.keys():\n self.parameters[key] = self.parameters[key] - self.lr * self.grads[\"d\" + str(key)]\n" ]
[ [ "numpy.zeros" ] ]
ChristianIngwersen/BombermanRL
[ "6cad61708211d74fbc1e16776a579861b614f360" ]
[ "evolutionarystrategies/evolutionarystrategy.py" ]
[ "import torch\nimport numpy as np\n#import pathos.multiprocessing as mp\nimport multiprocessing as mp\n\nclass EvolutionaryStrategy:\n\n def __init__(self, model, fitness, impact, processes=4, populationsize=10, learning_rate=0.5):\n self.model = model(transfer = True)\n self.processes = processes\n self.fitness = fitness(individuals=populationsize)\n self.learning_rate = learning_rate\n self.populationsize = populationsize\n self.impact = impact\n\n def evolution(self, id, output):\n seed = int(torch.randint(0,100000,(1,)))\n torch.manual_seed(seed)\n epsilon = {}\n for key, shape in self.model.shape().items():\n if self.model.params[key].type() == \"torch.FloatTensor\":\n epsilon[key] = torch.randn(shape).float()\n elif self.model.params[key].type() == \"torch.LongTensor\":\n epsilon[key] = torch.randn(shape).long()\n else:\n epsilon[key] = torch.randn(shape)\n # fitness function\n reward = self.fitness.evaluate(self.model, epsilon,self.learning_rate, self.impact,5 ,id)\n output.put((reward , seed)) # book keeping\n return\n\n\n def play_game(self,num_episode):\n reward = self.fitness.evaluate(self.model, 0, 0, 0, num_episode, 0)\n return reward\n\n def parallel_evolution(self):\n\n pool = mp.Pool(self.processes)\n results = pool.map(self.evolution,range(self.populationsize))\n #pool.close()\n \n # Setup a list of processes that we want to run\n #processes = [mp.Process(target=self.evolution, args=(x, output)) for x in range(permutations)]\n #self.model.update_params(epsilons, self.learning_rate)\n # Run processes\n '''for p in processes:\n p.start()\n\n # Exit the completed processes\n for p in processes:\n p.join()\n\n # Get process results from the output queue\n results = [output.get() for p in processes]\n '''\n #print(results)\n def sequential_evolution(self):\n epsilons = []\n rewards = []\n for _ in range(self.populationsize):\n reward, epsilon = self.evolution(impact,1)\n epsilons.append(epsilon)\n rewards.append(reward)\n self.model.update_params(epsilons, rewards, self.learning_rate)\n" ]
[ [ "torch.manual_seed", "torch.randint", "torch.randn" ] ]
tgaillard1/ucaip-labs
[ "44b2d8ec017793e40ae1a26b6b6a505d18bdf002" ]
[ "src/model_training/model.py" ]
[ "# Copyright 2021 Google LLC\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\"\"\"A DNN Keras classification model.\"\"\"\n\nimport tensorflow as tf\nfrom tensorflow import keras\n\nfrom src.common import features\n\n\ndef create_model_inputs():\n \"\"\"Creates Keras model input dictionary.\"\"\"\n\n inputs = {}\n for feature_name in features.FEATURE_NAMES:\n name = features.transformed_name(feature_name)\n if feature_name in features.NUMERICAL_FEATURE_NAMES:\n inputs[name] = keras.layers.Input(name=name, shape=[], dtype=tf.float32)\n elif feature_name in features.categorical_feature_names():\n inputs[name] = keras.layers.Input(name=name, shape=[], dtype=tf.int64)\n else:\n pass\n return inputs\n\n\ndef _create_binary_classifier(feature_vocab_sizes, hyperparams):\n \"\"\"Return a Keras binary classifier.\"\"\"\n\n input_layers = create_model_inputs()\n\n layers = []\n for key in input_layers:\n feature_name = features.original_name(key)\n if feature_name in features.EMBEDDING_CATEGORICAL_FEATURES:\n vocab_size = feature_vocab_sizes[feature_name]\n embedding_size = features.EMBEDDING_CATEGORICAL_FEATURES[feature_name]\n embedding_output = keras.layers.Embedding(\n input_dim=vocab_size + 1,\n output_dim=embedding_size,\n name=f\"{key}_embedding\",\n )(input_layers[key])\n layers.append(embedding_output)\n elif feature_name in features.ONEHOT_CATEGORICAL_FEATURE_NAMES:\n vocab_size = feature_vocab_sizes[feature_name]\n onehot_layer = keras.layers.experimental.preprocessing.CategoryEncoding(\n max_tokens=vocab_size,\n output_mode=\"binary\",\n name=f\"{key}_onehot\",\n )(input_layers[key])\n layers.append(onehot_layer)\n elif feature_name in features.NUMERICAL_FEATURE_NAMES:\n numeric_layer = tf.expand_dims(input_layers[key], -1)\n layers.append(numeric_layer)\n else:\n pass\n\n joined = keras.layers.Concatenate(name=\"combines_inputs\")(layers)\n feedforward_output = keras.Sequential(\n [\n keras.layers.Dense(units, activation=\"relu\")\n for units in hyperparams[\"hidden_units\"]\n ],\n name=\"feedforward_network\",\n )(joined)\n logits = keras.layers.Dense(units=1, name=\"logits\")(feedforward_output)\n\n model = keras.Model(inputs=input_layers, outputs=[logits])\n return model\n\n\ndef create_binary_classifier(tft_output, hyperparams):\n \"\"\"Returns a Keras binary classifier.\"\"\"\n\n feature_vocab_sizes = dict()\n for feature_name in features.categorical_feature_names():\n feature_vocab_sizes[feature_name] = tft_output.vocabulary_size_by_name(\n feature_name\n )\n\n return _create_binary_classifier(feature_vocab_sizes, hyperparams)\n" ]
[ [ "tensorflow.keras.layers.Concatenate", "tensorflow.keras.layers.Embedding", "tensorflow.keras.layers.Dense", "tensorflow.keras.layers.experimental.preprocessing.CategoryEncoding", "tensorflow.expand_dims", "tensorflow.keras.Model", "tensorflow.keras.layers.Input" ] ]
shonenkov/TPU-Star
[ "184ca912e4c3e6300af0156213ed792997d1fcc4", "184ca912e4c3e6300af0156213ed792997d1fcc4" ]
[ "tpu_star/experiment/torch_tpu.py", "tpu_star/utils.py" ]
[ "# -*- coding: utf-8 -*-\nimport os\nimport random\nimport time\n\nimport torch\nimport numpy as np\n\nfrom .torch_gpu import TorchGPUExperiment\n\n\nclass TorchTPUExperiment(TorchGPUExperiment):\n\n def __init__(\n self,\n model,\n optimizer,\n scheduler,\n criterion,\n device,\n xm,\n pl,\n xser,\n rank,\n seed=42,\n verbose=True,\n verbose_step=1,\n verbose_ndigits=5,\n base_dir='./saved_models',\n jupyters_path=None,\n notebook_name=None,\n experiment_name=None,\n neptune=None,\n neptune_params=None,\n best_saving=True,\n last_saving=True,\n **kwargs,\n ):\n if rank == 0:\n time.sleep(1)\n # #\n self.xm = xm\n self.pl = pl\n self.xser = xser,\n super().__init__(\n model=model,\n optimizer=optimizer,\n scheduler=scheduler,\n criterion=criterion,\n device=device,\n rank=rank,\n seed=seed,\n verbose=verbose,\n verbose_end='\\n',\n verbose_ndigits=verbose_ndigits,\n verbose_step=verbose_step,\n base_dir=base_dir,\n jupyters_path=jupyters_path,\n notebook_name=notebook_name,\n experiment_name=experiment_name,\n neptune=neptune,\n neptune_params=neptune_params,\n best_saving=best_saving,\n last_saving=last_saving,\n **kwargs,\n )\n\n def handle_one_batch(self, batch, *args, **kwargs):\n \"\"\"\n you can use this structure, for example:\n\n [model forward using self.model]\n\n [call criterion using self.criterion]\n\n [calculate metrics]\n\n self.metrics.update(bs=bs, <metric_name_1>=<value_1>, ..., <metric_name_n>=<value_n>)\n\n if self.is_train:\n loss.backward()\n self.optimizer_step()\n self.optimizer.zero_grad()\n self.scheduler.step()\n \"\"\"\n raise NotImplementedError\n\n def _rebuild_loader(self, loader):\n para_loader = self.pl.ParallelLoader(loader, [self.device])\n return para_loader.per_device_loader(self.device)\n\n def _get_current_metrics(self, stage):\n if stage == 'train':\n return self.__mesh_reduce_metrics(stage, **self.metrics.train_metrics[self.epoch].avg)\n elif stage == 'valid':\n return self.__mesh_reduce_metrics(stage, **self.metrics.valid_metrics[self.epoch].avg)\n else:\n raise ValueError(f'Incorrect stage: \"{stage}\".')\n\n def save(self, path):\n self.model.eval()\n self.xm.save(self.model.state_dict(), path)\n if self.rank == 0:\n metrics_path = os.path.join(os.path.dirname(path), 'metrics.pt')\n torch.save({\n 'metrics_state_dict': self.metrics.state_dict(),\n }, metrics_path)\n\n def load(self, path):\n raise ValueError\n\n @classmethod\n def resume(cls, *args, **kwargs):\n raise\n\n def destroy(self):\n if self.rank == 0 and self.neptune:\n self.neptune.stop()\n\n def optimizer_step(self):\n self.xm.optimizer_step(self.optimizer)\n\n def _seed_everything(self, seed):\n random.seed(seed)\n os.environ['PYTHONHASHSEED'] = str(seed)\n np.random.seed(seed)\n torch.manual_seed(seed)\n torch.cuda.manual_seed(seed)\n torch.backends.cudnn.deterministic = True\n torch.backends.cudnn.benchmark = True\n self.xm.set_rng_state(seed)\n\n def _print(self, msg, *args, **kwargs):\n if self.verbose:\n msg = self._prepare_msg(msg, *args, **kwargs)\n self.xm.master_print(msg)\n\n def _log(self, msg, *args, **kwargs):\n msg = self._prepare_msg(msg, *args, **kwargs)\n if self.verbose:\n self._print(msg)\n if self.rank == 0:\n with open(self.log_path, 'a+') as logger:\n self.xm.master_print(f'{msg}', fd=logger)\n\n @staticmethod\n def __reduce_fn(vals):\n return sum(vals) / len(vals)\n\n def __mesh_reduce_metrics(self, stage=None, **kwargs):\n mesh_metrics = {}\n prefix = f'_{stage}' if stage else ''\n for metric, value in kwargs.items():\n mesh_value = self.xm.mesh_reduce(f'{metric}{prefix}_reduce', value, self.__reduce_fn)\n mesh_metrics[metric] = mesh_value\n return mesh_metrics\n", "# -*- coding: utf-8 -*-\nimport torch\nimport torch.utils.data\n\n\ndef TPULoaderWrapper(\n dataset,\n xm,\n batch_size=1,\n shuffle=False,\n collate_fn=None,\n pin_memory=False,\n drop_last=False,\n num_workers=0,\n):\n sampler = torch.utils.data.distributed.DistributedSampler(\n dataset,\n num_replicas=xm.xrt_world_size(),\n rank=xm.get_ordinal(),\n shuffle=shuffle\n )\n loader = torch.utils.data.DataLoader(\n dataset,\n batch_size=batch_size,\n sampler=sampler,\n pin_memory=pin_memory,\n drop_last=drop_last,\n num_workers=num_workers,\n collate_fn=collate_fn,\n )\n return loader\n" ]
[ [ "torch.manual_seed", "torch.cuda.manual_seed", "numpy.random.seed" ], [ "torch.utils.data.DataLoader" ] ]
fgolemo/kubric
[ "a8b6bc8260add2f516e4805929dcb17f223974ba" ]
[ "kubric/datasets/movid.py" ]
[ "# Copyright 2021 The Kubric Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# Copyright 2021 The Kubric Authors\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# 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# pylint: disable=line-too-long, unexpected-keyword-arg\n\"\"\"TODO(klausg): description.\"\"\"\n\nimport dataclasses\nimport logging\nimport os\nimport json\nimport imageio\n\nimport numpy as np\nimport png\nimport tensorflow as tf\nimport tensorflow_datasets.public_api as tfds\nfrom typing import List, Dict\n\n_DESCRIPTION = \"TODO(klausg).\"\n\n_CITATION = \"TODO(klausg).\"\n\n\n@dataclasses.dataclass\nclass MovidConfig(tfds.core.BuilderConfig):\n \"\"\"\"Configuration for Multi-Object Video (MOVid) dataset.\"\"\"\n height: int = 256\n width: int = 256\n validation_ratio: float = 0.1\n train_val_path: str = None\n test_split_paths: Dict[str, str] = dataclasses.field(default_factory=dict)\n shape_info: str = \"None\" # also export shape, material, color, size (for A and B)\n\n\nclass Movid(tfds.core.BeamBasedBuilder):\n \"\"\"DatasetBuilder for Katr dataset.\"\"\"\n VERSION = tfds.core.Version(\"1.1.0\")\n RELEASE_NOTES = {\n \"1.0.0\": \"initial release\",\n \"1.1.0\": \"fixed segmentation, and various other minor issues\"\n }\n\n BUILDER_CONFIGS = [\n MovidConfig(\n name=\"E_256x256\",\n description=\"Static objects, moving camera, full resolution of 256x256\",\n height=256,\n width=256,\n validation_ratio=0.1,\n train_val_path=\"gs://research-brain-kubric-xgcp/jobs/movid_e_v11\",\n test_split_paths={\n \"test_held_out_objects\": \"gs://research-brain-kubric-xgcp/jobs/movid_e_v11_test_obj\",\n \"test_held_out_backgrounds\": \"gs://research-brain-kubric-xgcp/jobs/movid_e_v11_test_bg1\",\n \"test_held_out_objects_and_backgrounds\": \"gs://research-brain-kubric-xgcp/jobs/movid_e_v11_test_objbg\",\n \"test_all_same\": \"gs://research-brain-kubric-xgcp/jobs/movid_e_v11_test_same2\",\n }\n ),\n MovidConfig(\n name=\"E_128x128\",\n description=\"Static objects, moving camera, downscaled to 128x128\",\n height=128,\n width=128,\n validation_ratio=0.1,\n train_val_path=\"gs://research-brain-kubric-xgcp/jobs/movid_e_v11\",\n test_split_paths={\n \"test_held_out_objects\": \"gs://research-brain-kubric-xgcp/jobs/movid_e_v11_test_obj\",\n \"test_held_out_backgrounds\": \"gs://research-brain-kubric-xgcp/jobs/movid_e_v11_test_bg1\",\n \"test_held_out_objects_and_backgrounds\": \"gs://research-brain-kubric-xgcp/jobs/movid_e_v11_test_objbg\",\n \"test_all_same\": \"gs://research-brain-kubric-xgcp/jobs/movid_e_v11_test_same2\",\n }\n ),\n MovidConfig(\n name=\"E_64x64\",\n description=\"Static objects, moving camera, downscaled to 64x64\",\n height=64,\n width=64,\n validation_ratio=0.1,\n train_val_path=\"gs://research-brain-kubric-xgcp/jobs/movid_e_v11\",\n test_split_paths={\n \"test_held_out_objects\": \"gs://research-brain-kubric-xgcp/jobs/movid_e_v11_test_obj\",\n \"test_held_out_backgrounds\": \"gs://research-brain-kubric-xgcp/jobs/movid_e_v11_test_bg1\",\n \"test_held_out_objects_and_backgrounds\": \"gs://research-brain-kubric-xgcp/jobs/movid_e_v11_test_objbg\",\n \"test_all_same\": \"gs://research-brain-kubric-xgcp/jobs/movid_e_v11_test_same2\",\n }\n ),\n MovidConfig(\n name=\"D_256x256\",\n description=\"Static objects, random camera, full resolution of 256x256\",\n height=256,\n width=256,\n validation_ratio=0.1,\n train_val_path=\"gs://research-brain-kubric-xgcp/jobs/movid_d_v11\",\n test_split_paths={\n \"test_held_out_objects\": \"gs://research-brain-kubric-xgcp/jobs/movid_d_v11_testobj\",\n \"test_held_out_backgrounds\": \"gs://research-brain-kubric-xgcp/jobs/movid_d_v11_testbg\",\n \"test_held_out_objects_and_backgrounds\": \"gs://research-brain-kubric-xgcp/jobs/movid_d_v11_testobjbg\",\n \"test_all_same\": \"gs://research-brain-kubric-xgcp/jobs/movid_d_v11_testsame\",\n \"test_many\": \"gs://research-brain-kubric-xgcp/jobs/movid_d_v11_testmany\",\n }\n ),\n MovidConfig(\n name=\"D_128x128\",\n description=\"Static objects, random camera, downscaled to 128x128\",\n height=128,\n width=128,\n validation_ratio=0.1,\n train_val_path=\"gs://research-brain-kubric-xgcp/jobs/movid_d_v11\",\n test_split_paths={\n \"test_held_out_objects\": \"gs://research-brain-kubric-xgcp/jobs/movid_d_v11_testobj\",\n \"test_held_out_backgrounds\": \"gs://research-brain-kubric-xgcp/jobs/movid_d_v11_testbg\",\n \"test_held_out_objects_and_backgrounds\": \"gs://research-brain-kubric-xgcp/jobs/movid_d_v11_testobjbg\",\n \"test_all_same\": \"gs://research-brain-kubric-xgcp/jobs/movid_d_v11_testsame\",\n \"test_many\": \"gs://research-brain-kubric-xgcp/jobs/movid_d_v11_testmany\",\n }\n ),\n MovidConfig(\n name=\"D_64x64\",\n description=\"Static objects, random camera, downscaled to 64x64\",\n height=64,\n width=64,\n validation_ratio=0.1,\n train_val_path=\"gs://research-brain-kubric-xgcp/jobs/movid_d_v11\",\n test_split_paths={\n \"test_held_out_objects\": \"gs://research-brain-kubric-xgcp/jobs/movid_d_v11_testobj\",\n \"test_held_out_backgrounds\": \"gs://research-brain-kubric-xgcp/jobs/movid_d_v11_testbg\",\n \"test_held_out_objects_and_backgrounds\": \"gs://research-brain-kubric-xgcp/jobs/movid_d_v11_testobjbg\",\n \"test_all_same\": \"gs://research-brain-kubric-xgcp/jobs/movid_d_v11_testsame\",\n \"test_many\": \"gs://research-brain-kubric-xgcp/jobs/movid_d_v11_testmany\",\n }\n ),\n MovidConfig(\n name=\"C_256x256\",\n description=\"Dynamic objects, random camera, full resolution of 256x256\",\n height=256,\n width=256,\n validation_ratio=0.1,\n train_val_path=\"gs://research-brain-kubric-xgcp/jobs/movid_c_v11\",\n test_split_paths={\n \"test_held_out_objects\": \"gs://research-brain-kubric-xgcp/jobs/movid_c_v11_testobj\",\n \"test_held_out_backgrounds\": \"gs://research-brain-kubric-xgcp/jobs/movid_c_v11_testbg\",\n \"test_held_out_objects_and_backgrounds\": \"gs://research-brain-kubric-xgcp/jobs/movid_c_v11_testobjbg\",\n \"test_all_same\": \"gs://research-brain-kubric-xgcp/jobs/movid_c_v11_testsame\",\n \"test_many\": \"gs://research-brain-kubric-xgcp/jobs/movid_c_v11_testmany\",\n }\n ),\n MovidConfig(\n name=\"C_128x128\",\n description=\"Dynamic objects, random camera, downscaled to 128x128\",\n height=128,\n width=128,\n validation_ratio=0.1,\n train_val_path=\"gs://research-brain-kubric-xgcp/jobs/movid_c_v11\",\n test_split_paths={\n \"test_held_out_objects\": \"gs://research-brain-kubric-xgcp/jobs/movid_c_v11_testobj\",\n \"test_held_out_backgrounds\": \"gs://research-brain-kubric-xgcp/jobs/movid_c_v11_testbg\",\n \"test_held_out_objects_and_backgrounds\": \"gs://research-brain-kubric-xgcp/jobs/movid_c_v11_testobjbg\",\n \"test_all_same\": \"gs://research-brain-kubric-xgcp/jobs/movid_c_v11_testsame\",\n \"test_many\": \"gs://research-brain-kubric-xgcp/jobs/movid_c_v11_testmany\",\n }\n ),\n MovidConfig(\n name=\"C_64x64\",\n description=\"Static objects, random camera, downscaled to 64x64\",\n height=64,\n width=64,\n validation_ratio=0.1,\n train_val_path=\"gs://research-brain-kubric-xgcp/jobs/movid_c_v11\",\n test_split_paths={\n \"test_held_out_objects\": \"gs://research-brain-kubric-xgcp/jobs/movid_c_v11_testobj\",\n \"test_held_out_backgrounds\": \"gs://research-brain-kubric-xgcp/jobs/movid_c_v11_testbg\",\n \"test_held_out_objects_and_backgrounds\": \"gs://research-brain-kubric-xgcp/jobs/movid_c_v11_testobjbg\",\n \"test_all_same\": \"gs://research-brain-kubric-xgcp/jobs/movid_c_v11_testsame\",\n \"test_many\": \"gs://research-brain-kubric-xgcp/jobs/movid_c_v11_testmany\",\n }\n ),\n MovidConfig(\n name=\"CC_256x256\",\n description=\"Dynamic objects, moving camera, full resolution of 256x256\",\n height=256,\n width=256,\n validation_ratio=0.1,\n train_val_path=\"gs://research-brain-kubric-xgcp/jobs/movid_cc_v11\",\n test_split_paths={\n # \"test_held_out_objects\": \"gs://research-brain-kubric-xgcp/jobs/movid_cc_v11_testobj\",\n # \"test_held_out_backgrounds\": \"gs://research-brain-kubric-xgcp/jobs/movid_c_v11_testbg\",\n # \"test_held_out_objects_and_backgrounds\": \"gs://research-brain-kubric-xgcp/jobs/movid_c_v11_testobjbg\",\n # \"test_all_same\": \"gs://research-brain-kubric-xgcp/jobs/movid_c_v11_testsame\",\n # \"test_many\": \"gs://research-brain-kubric-xgcp/jobs/movid_c_v11_testmany\",\n }\n ),\n MovidConfig(\n name=\"CC_128x128\",\n description=\"Dynamic objects, moving camera, downscaled to 128x128\",\n height=128,\n width=128,\n validation_ratio=0.1,\n train_val_path=\"gs://research-brain-kubric-xgcp/jobs/movid_cc_v11\",\n test_split_paths={\n # \"test_held_out_objects\": \"gs://research-brain-kubric-xgcp/jobs/movid_c_v11_testobj\",\n # \"test_held_out_backgrounds\": \"gs://research-brain-kubric-xgcp/jobs/movid_c_v11_testbg\",\n # \"test_held_out_objects_and_backgrounds\": \"gs://research-brain-kubric-xgcp/jobs/movid_c_v11_testobjbg\",\n # \"test_all_same\": \"gs://research-brain-kubric-xgcp/jobs/movid_c_v11_testsame\",\n # \"test_many\": \"gs://research-brain-kubric-xgcp/jobs/movid_c_v11_testmany\",\n }\n ),\n MovidConfig(\n name=\"CC_64x64\",\n description=\"Static objects, moving camera, downscaled to 64x64\",\n height=64,\n width=64,\n validation_ratio=0.1,\n train_val_path=\"gs://research-brain-kubric-xgcp/jobs/movid_cc_v11\",\n test_split_paths={\n # \"test_held_out_objects\": \"gs://research-brain-kubric-xgcp/jobs/movid_c_v11_testobj\",\n # \"test_held_out_backgrounds\": \"gs://research-brain-kubric-xgcp/jobs/movid_c_v11_testbg\",\n # \"test_held_out_objects_and_backgrounds\": \"gs://research-brain-kubric-xgcp/jobs/movid_c_v11_testobjbg\",\n # \"test_all_same\": \"gs://research-brain-kubric-xgcp/jobs/movid_c_v11_testsame\",\n # \"test_many\": \"gs://research-brain-kubric-xgcp/jobs/movid_c_v11_testmany\",\n }\n ),\n\n MovidConfig(\n name=\"B_256x256\",\n description=\"Random color background, Kubasic objects, random camera, full resolution of 256x256\",\n height=256,\n width=256,\n validation_ratio=0.1,\n train_val_path=\"gs://research-brain-kubric-xgcp/jobs/movid_b_v11\",\n shape_info=\"KuBasic\",\n test_split_paths={\n \"test_held_out_objects\": \"gs://research-brain-kubric-xgcp/jobs/movid_b_v11_testobj\",\n \"test_held_out_backgrounds\": \"gs://research-brain-kubric-xgcp/jobs/movid_b_v11_testbg\",\n \"test_held_out_objects_and_backgrounds\": \"gs://research-brain-kubric-xgcp/jobs/movid_b_v11_testobjbg\",\n \"test_all_same\": \"gs://research-brain-kubric-xgcp/jobs/movid_b_v11_testsame\",\n \"test_many\": \"gs://research-brain-kubric-xgcp/jobs/movid_b_v11_testmany\",\n }\n ),\n MovidConfig(\n name=\"B_128x128\",\n description=\"Random color background, Kubasic objects, random camera, downscaled to 128x128\",\n height=128,\n width=128,\n validation_ratio=0.1,\n train_val_path=\"gs://research-brain-kubric-xgcp/jobs/movid_b_v11\",\n shape_info=\"KuBasic\",\n test_split_paths={\n \"test_held_out_objects\": \"gs://research-brain-kubric-xgcp/jobs/movid_b_v11_testobj\",\n \"test_held_out_backgrounds\": \"gs://research-brain-kubric-xgcp/jobs/movid_b_v11_testbg\",\n \"test_held_out_objects_and_backgrounds\": \"gs://research-brain-kubric-xgcp/jobs/movid_b_v11_testobjbg\",\n \"test_all_same\": \"gs://research-brain-kubric-xgcp/jobs/movid_b_v11_testsame\",\n \"test_many\": \"gs://research-brain-kubric-xgcp/jobs/movid_b_v11_testmany\",\n }\n ),\n MovidConfig(\n name=\"B_64x64\",\n description=\"Random color background, Kubasic objects, random camera, downscaled to 64x64\",\n height=64,\n width=64,\n validation_ratio=0.1,\n train_val_path=\"gs://research-brain-kubric-xgcp/jobs/movid_b_v11\",\n shape_info=\"KuBasic\",\n test_split_paths={\n \"test_held_out_objects\": \"gs://research-brain-kubric-xgcp/jobs/movid_b_v11_testobj\",\n \"test_held_out_backgrounds\": \"gs://research-brain-kubric-xgcp/jobs/movid_b_v11_testbg\",\n \"test_held_out_objects_and_backgrounds\": \"gs://research-brain-kubric-xgcp/jobs/movid_b_v11_testobjbg\",\n \"test_all_same\": \"gs://research-brain-kubric-xgcp/jobs/movid_b_v11_testsame\",\n \"test_many\": \"gs://research-brain-kubric-xgcp/jobs/movid_b_v11_testmany\",\n }\n ),\n MovidConfig(\n name=\"A_256x256\",\n description=\"CLEVR setup, full resolution of 256x256\",\n height=256,\n width=256,\n validation_ratio=0.1,\n train_val_path=\"gs://research-brain-kubric-xgcp/jobs/movid_a_v11\",\n shape_info=\"CLEVR\",\n test_split_paths={\n \"test_held_out_objects\": \"gs://research-brain-kubric-xgcp/jobs/movid_a_v11_test_obj\",\n \"test_held_out_backgrounds\": \"gs://research-brain-kubric-xgcp/jobs/movid_a_v11_test_bg\",\n \"test_held_out_objects_and_backgrounds\": \"gs://research-brain-kubric-xgcp/jobs/movid_a_v11_test_objbg\",\n \"test_all_same\": \"gs://research-brain-kubric-xgcp/jobs/movid_a_v11_test_same\",\n \"test_many\": \"gs://research-brain-kubric-xgcp/jobs/movid_a_v11_test_many\",\n }\n ),\n MovidConfig(\n name=\"A_128x128\",\n description=\"CLEVR setup, downscaled to 128x128\",\n height=128,\n width=128,\n validation_ratio=0.1,\n train_val_path=\"gs://research-brain-kubric-xgcp/jobs/movid_a_v11\",\n shape_info=\"CLEVR\",\n test_split_paths={\n \"test_held_out_objects\": \"gs://research-brain-kubric-xgcp/jobs/movid_a_v11_test_obj\",\n \"test_held_out_backgrounds\": \"gs://research-brain-kubric-xgcp/jobs/movid_a_v11_test_bg\",\n \"test_held_out_objects_and_backgrounds\": \"gs://research-brain-kubric-xgcp/jobs/movid_a_v11_test_objbg\",\n \"test_all_same\": \"gs://research-brain-kubric-xgcp/jobs/movid_a_v11_test_same\",\n \"test_many\": \"gs://research-brain-kubric-xgcp/jobs/movid_a_v11_test_many\",\n }\n ),\n MovidConfig(\n name=\"A_64x64\",\n description=\"CLEVR setup, downscaled to 64x64\",\n height=64,\n width=64,\n validation_ratio=0.1,\n train_val_path=\"gs://research-brain-kubric-xgcp/jobs/movid_a_v11\",\n shape_info=\"CLEVR\",\n test_split_paths={\n \"test_held_out_objects\": \"gs://research-brain-kubric-xgcp/jobs/movid_a_v11_test_obj\",\n \"test_held_out_backgrounds\": \"gs://research-brain-kubric-xgcp/jobs/movid_a_v11_test_bg\",\n \"test_held_out_objects_and_backgrounds\": \"gs://research-brain-kubric-xgcp/jobs/movid_a_v11_test_objbg\",\n \"test_all_same\": \"gs://research-brain-kubric-xgcp/jobs/movid_a_v11_test_same\",\n \"test_many\": \"gs://research-brain-kubric-xgcp/jobs/movid_a_v11_test_many\",\n }\n ),\n\n ]\n\n def _info(self) -> tfds.core.DatasetInfo:\n \"\"\"Returns the dataset metadata.\"\"\"\n\n h = self.builder_config.height\n w = self.builder_config.width\n s = 24\n\n instance_features = {\n \"asset_id\": tfds.features.Text(),\n \"is_dynamic\": tfds.features.Tensor(shape=(), dtype=tf.bool),\n \"mass\": tf.float32,\n \"friction\": tf.float32,\n \"restitution\": tf.float32,\n\n \"positions\": tfds.features.Tensor(shape=(s, 3), dtype=tf.float32),\n \"quaternions\": tfds.features.Tensor(shape=(s, 4), dtype=tf.float32),\n \"velocities\": tfds.features.Tensor(shape=(s, 3), dtype=tf.float32),\n \"angular_velocities\": tfds.features.Tensor(shape=(s, 3), dtype=tf.float32),\n \"bboxes_3d\": tfds.features.Tensor(shape=(s, 8, 3), dtype=tf.float32),\n\n \"image_positions\": tfds.features.Tensor(shape=(s, 2), dtype=tf.float32),\n \"bboxes\": tfds.features.Sequence(\n tfds.features.BBoxFeature()),\n \"bbox_frames\": tfds.features.Sequence(\n tfds.features.Tensor(shape=(), dtype=tf.int32)),\n \"visibility\": tfds.features.Tensor(shape=(s,), dtype=tf.uint16),\n }\n\n if self.builder_config.shape_info == \"CLEVR\":\n instance_features[\"shape_label\"] = tfds.features.ClassLabel(names=[\"Cube\", \"Cylinder\", \"Sphere\"])\n instance_features[\"size_label\"] = tfds.features.ClassLabel(names=[\"small\", \"large\"])\n instance_features[\"size\"] = tfds.features.Tensor(shape=(3,), dtype=tf.float32)\n instance_features[\"material_label\"] = tfds.features.ClassLabel(names=[\"Metal\", \"Rubber\"])\n instance_features[\"color_label\"] = tfds.features.ClassLabel(names=[\n \"blue\", \"brown\", \"cyan\", \"gray\", \"green\", \"purple\", \"red\", \"yellow\"])\n instance_features[\"color\"] = tfds.features.Tensor(shape=(3,), dtype=tf.float32)\n\n elif self.builder_config.shape_info == \"KuBasic\":\n instance_features[\"shape_label\"] = tfds.features.ClassLabel(names=[\n \"Cube\", \"Cylinder\", \"Sphere\", \"Cone\", \"Torus\", \"Gear\", \"TorusKnot\", \"Sponge\", \"Spot\",\n \"Teapot\", \"Suzanne\"])\n instance_features[\"size\"] = tf.float32\n instance_features[\"material_label\"] = tfds.features.ClassLabel(names=[\"Metal\", \"Rubber\"])\n instance_features[\"color\"] = tfds.features.Tensor(shape=(3,), dtype=tf.float32)\n\n return tfds.core.DatasetInfo(\n builder=self,\n description=_DESCRIPTION,\n features=tfds.features.FeaturesDict({\n \"metadata\": {\n \"video_name\": tfds.features.Text(),\n \"width\": tf.int32,\n \"height\": tf.int32,\n \"num_frames\": tf.int32,\n \"num_instances\": tf.uint16,\n\n \"depth_range\": tfds.features.Tensor(shape=(2,), dtype=tf.float32),\n \"forward_flow_range\": tfds.features.Tensor(shape=(2,), dtype=tf.float32),\n \"backward_flow_range\": tfds.features.Tensor(shape=(2,), dtype=tf.float32),\n },\n \"background\": tfds.features.Text(),\n \"instances\": tfds.features.Sequence(feature=instance_features),\n \"camera\": {\n \"focal_length\": tf.float32,\n \"sensor_width\": tf.float32,\n \"field_of_view\": tf.float32,\n \"positions\": tfds.features.Tensor(shape=(s, 3), dtype=tf.float32),\n \"quaternions\": tfds.features.Tensor(shape=(s, 4), dtype=tf.float32),\n },\n \"events\": {\n \"collisions\": tfds.features.Sequence({\n \"instances\": tfds.features.Tensor(shape=(2,), dtype=tf.uint16),\n \"frame\": tf.int32,\n \"force\": tf.float32,\n \"position\": tfds.features.Tensor(shape=(3,), dtype=tf.float32),\n \"image_position\": tfds.features.Tensor(shape=(2,), dtype=tf.float32),\n \"contact_normal\": tfds.features.Tensor(shape=(3,), dtype=tf.float32),\n }),\n },\n \"video\": tfds.features.Video(shape=(s, h, w, 3)),\n \"segmentations\": tfds.features.Sequence(\n tfds.features.Image(shape=(h, w, 1), dtype=tf.uint16), length=s),\n \"forward_flow\": tfds.features.Sequence(\n tfds.features.Tensor(shape=(h, w, 2), dtype=tf.uint16), length=s),\n \"backward_flow\": tfds.features.Sequence(\n tfds.features.Tensor(shape=(h, w, 2), dtype=tf.uint16), length=s),\n \"depth\": tfds.features.Sequence(\n tfds.features.Image(shape=(h, w, 1), dtype=tf.uint16), length=s),\n \"uv\": tfds.features.Sequence(\n tfds.features.Image(shape=(h, w, 3), dtype=tf.uint16), length=s),\n \"normal\": tfds.features.Sequence(\n tfds.features.Image(shape=(h, w, 3), dtype=tf.uint16), length=s),\n }),\n supervised_keys=None,\n homepage=\"https://github.com/google-research/kubric\",\n citation=_CITATION)\n\n def _split_generators(self, unused_dl_manager: tfds.download.DownloadManager):\n \"\"\"Returns SplitGenerators.\"\"\"\n del unused_dl_manager\n path = tfds.core.as_path(self.builder_config.train_val_path)\n all_subdirs = [d for d in path.glob(\"*\") if (d / \"events.json\").exists()]\n all_subdirs = sorted(all_subdirs, key=lambda x: int(x.name))\n all_subdirs = [str(d) for d in all_subdirs]\n logging.info(\"Found %d sub-folders in master path: %s\", len(all_subdirs), path)\n\n validation_ratio = self.builder_config.validation_ratio\n validation_examples = round(len(all_subdirs) * validation_ratio)\n training_examples = len(all_subdirs) - validation_examples\n logging.info(\"Using %s of examples for validation for a total of %d\",\n \"{:.2%}\".format(validation_ratio), validation_examples)\n logging.info(\"Using the other %d examples for training\", training_examples)\n\n splits = {\n tfds.Split.TRAIN: self._generate_examples(all_subdirs[:training_examples]),\n tfds.Split.VALIDATION: self._generate_examples(all_subdirs[training_examples:]),\n }\n\n for key, path in self.builder_config.test_split_paths.items():\n path = tfds.core.as_path(path)\n split_dirs = [d for d in path.glob(\"*\") if (d / \"events.json\").exists()]\n # sort the directories by their integer number\n split_dirs = sorted(split_dirs, key=lambda x: int(x.name))\n logging.info(\"Found %d sub-folders in '%s' path: %s\", len(split_dirs), key, path)\n splits[key] = self._generate_examples([str(d) for d in split_dirs])\n\n return splits\n\n def _generate_examples(self, directories: List[str]):\n \"\"\"Yields examples.\"\"\"\n\n target_size = (self.builder_config.height, self.builder_config.width)\n\n def _process_example(video_dir):\n video_dir = tfds.core.as_path(video_dir)\n key = f\"{video_dir.name}\"\n\n with tf.io.gfile.GFile(str(video_dir / \"data_ranges.json\"), \"r\") as fp:\n data_ranges = json.load(fp)\n\n with tf.io.gfile.GFile(str(video_dir / \"metadata.json\"), \"r\") as fp:\n metadata = json.load(fp)\n\n with tf.io.gfile.GFile(str(video_dir / \"events.json\"), \"r\") as fp:\n events = json.load(fp)\n\n num_frames = metadata[\"metadata\"][\"num_frames\"]\n num_instances = metadata[\"metadata\"][\"num_instances\"]\n\n assert len(metadata[\"instances\"]) == num_instances, f\"{len(metadata['instances'])} != {num_instances}\"\n\n # assert \"depth\" in data_ranges, f\"ERROR {key}\\t{video_dir}\\t{data_ranges}\"\n assert \"forward_flow\" in data_ranges, f\"ERROR {key}\\t{video_dir}\\t{data_ranges}\"\n assert \"backward_flow\" in data_ranges, f\"ERROR {key}\\t{video_dir}\\t{data_ranges}\"\n # depth_min, depth_max = data_ranges[\"depth\"][\"min\"], data_ranges[\"depth\"][\"max\"]\n\n rgba_frame_paths = [video_dir / f\"rgba_{f:05d}.png\" for f in range(num_frames)]\n segmentation_frame_paths = [video_dir / f\"segmentation_{f:05d}.png\" for f in range(num_frames)]\n fwd_flow_frame_paths = [video_dir / f\"forward_flow_{f:05d}.png\" for f in range(num_frames)]\n bwd_flow_frame_paths = [video_dir / f\"backward_flow_{f:05d}.png\" for f in range(num_frames)]\n depth_frame_paths = [video_dir / f\"depth_{f:05d}.tiff\" for f in range(num_frames)]\n uv_frame_paths = [video_dir / f\"uv_{f:05d}.png\" for f in range(num_frames)]\n normal_frame_paths = [video_dir / f\"normal_{f:05d}.png\" for f in range(num_frames)]\n\n scale = 256 / target_size[0]\n\n depth_frames = np.array([subsample_nearest_neighbor(read_tiff(frame_path), target_size)\n for frame_path in depth_frame_paths])\n depth_min, depth_max = np.min(depth_frames), np.max(depth_frames)\n depth_frames_uint16 = convert_float_to_uint16(depth_frames, depth_min, depth_max)\n\n def get_instance_info(obj):\n instance_info = {\n \"asset_id\": obj[\"asset_id\"],\n \"is_dynamic\": bool(obj[\"is_dynamic\"]),\n \"mass\": obj[\"mass\"],\n \"friction\": obj[\"friction\"],\n \"restitution\": obj[\"restitution\"],\n \"positions\": np.array(obj[\"positions\"], np.float32),\n \"quaternions\": np.array(obj[\"quaternions\"], np.float32),\n \"velocities\": np.array(obj[\"velocities\"], np.float32),\n \"angular_velocities\": np.array(obj[\"angular_velocities\"], np.float32),\n \"bboxes_3d\": np.array(obj[\"bboxes_3d\"], np.float32),\n \"image_positions\": np.array(obj[\"image_positions\"], np.float32),\n \"bboxes\": [tfds.features.BBox(*bbox) for bbox in obj[\"bboxes\"]],\n \"bbox_frames\": np.array(obj[\"bbox_frames\"], dtype=np.uint16),\n \"visibility\": np.array(obj[\"visibility\"], dtype=np.uint16),\n }\n if self.builder_config.shape_info == \"CLEVR\":\n instance_info[\"shape_label\"] = obj[\"shape_label\"]\n instance_info[\"size_label\"] = obj[\"size_label\"]\n instance_info[\"size\"] = obj[\"size\"]\n instance_info[\"material_label\"] = obj[\"material\"]\n instance_info[\"color_label\"] = obj[\"color_label\"]\n instance_info[\"color\"] = obj[\"color\"]\n\n elif self.builder_config.shape_info == \"KuBasic\":\n instance_info[\"shape_label\"] = obj[\"shape_label\"]\n instance_info[\"size\"] = obj[\"size\"]\n instance_info[\"material_label\"] = obj[\"material\"]\n instance_info[\"color\"] = obj[\"color\"]\n return instance_info\n\n return key, {\n \"metadata\": {\n \"video_name\": os.fspath(key),\n \"width\": target_size[1],\n \"height\": target_size[0],\n \"num_frames\": num_frames,\n \"num_instances\": num_instances,\n \"depth_range\": [depth_min, depth_max],\n \"forward_flow_range\": [data_ranges[\"forward_flow\"][\"min\"] / scale,\n data_ranges[\"forward_flow\"][\"max\"] / scale],\n \"backward_flow_range\": [data_ranges[\"backward_flow\"][\"min\"] / scale,\n data_ranges[\"backward_flow\"][\"max\"] / scale],\n },\n \"background\": metadata[\"metadata\"][\"background\"],\n \"instances\": [get_instance_info(obj) for obj in metadata[\"instances\"]],\n \"camera\": {\n \"focal_length\": metadata[\"camera\"][\"focal_length\"],\n \"sensor_width\": metadata[\"camera\"][\"sensor_width\"],\n \"field_of_view\": metadata[\"camera\"][\"field_of_view\"],\n \"positions\": np.array(metadata[\"camera\"][\"positions\"], np.float32),\n \"quaternions\": np.array(metadata[\"camera\"][\"quaternions\"], np.float32),\n },\n \"events\": {\n \"collisions\": [{\n \"instances\": np.array(c[\"instances\"], dtype=np.uint16),\n \"frame\": c[\"frame\"],\n \"force\": c[\"force\"],\n \"position\": np.array(c[\"position\"], dtype=np.float32),\n \"image_position\": np.array(c[\"image_position\"], dtype=np.float32),\n \"contact_normal\": np.array(c[\"contact_normal\"], dtype=np.float32),\n } for c in events[\"collisions\"]],\n },\n \"video\": [subsample_avg(read_png(frame_path), target_size)[..., :3]\n for frame_path in rgba_frame_paths],\n \"segmentations\": [subsample_nearest_neighbor(read_png(frame_path).astype(np.uint16),\n target_size)\n for frame_path in segmentation_frame_paths],\n \"forward_flow\": [subsample_nearest_neighbor(read_png(frame_path)[..., :2], target_size)\n for frame_path in fwd_flow_frame_paths],\n \"backward_flow\": [subsample_nearest_neighbor(read_png(frame_path)[..., :2], target_size)\n for frame_path in bwd_flow_frame_paths],\n \"depth\": depth_frames_uint16,\n \"uv\": [subsample_nearest_neighbor(read_png(frame_path), target_size)\n for frame_path in uv_frame_paths],\n \"normal\": [subsample_nearest_neighbor(read_png(frame_path), target_size)\n for frame_path in normal_frame_paths],\n }\n\n beam = tfds.core.lazy_imports.apache_beam\n return beam.Create(directories) | beam.Map(_process_example)\n\n\ndef _get_files_from_subdir(path: str) -> List[str]:\n path = tfds.core.as_path(path)\n files = [str(f) for f in path.glob(\"frame*.pkl\")]\n logging.info(\"Found %d files in path: %s\", len(files), path)\n return files\n\n\ndef subsample_nearest_neighbor(arr, size):\n src_height, src_width, _ = arr.shape\n dst_height, dst_width = size\n height_step = src_height // dst_height\n width_step = src_width // dst_width\n height_offset = int(np.floor((height_step-1)/2))\n width_offset = int(np.floor((width_step-1)/2))\n subsampled = arr[height_offset::height_step, width_offset::width_step, :]\n return subsampled\n\n\ndef subsample_avg(arr, size):\n src_height, src_width, channels = arr.shape\n dst_height, dst_width = size\n height_bin = src_height // dst_height\n width_bin = src_width // dst_width\n return np.round(arr.reshape((dst_height, height_bin,\n dst_width, width_bin,\n channels)).mean(axis=(1, 3))).astype(np.uint8)\n\n\ndef read_png(path: os.PathLike):\n path = tfds.core.as_path(path)\n png_reader = png.Reader(bytes=path.read_bytes())\n width, height, pngdata, info = png_reader.read()\n del png_reader\n bitdepth = info[\"bitdepth\"]\n if bitdepth == 8:\n dtype = np.uint8\n elif bitdepth == 16:\n dtype = np.uint16\n else:\n raise NotImplementedError(f\"Unsupported bitdepth: {bitdepth}\")\n plane_count = info[\"planes\"]\n pngdata = np.vstack(list(map(dtype, pngdata)))\n return pngdata.reshape((height, width, plane_count))\n\n\ndef read_tiff(path: os.PathLike):\n img_bytes = tfds.core.as_path(path).read_bytes()\n return imageio.imread(img_bytes, format=\"tif\")[:, :, None]\n\n\ndef convert_float_to_uint16(array, min_val, max_val):\n return np.round((array - min_val) / (max_val - min_val) * 65535).astype(np.uint16)\n" ]
[ [ "numpy.min", "numpy.round", "numpy.max", "numpy.floor", "numpy.array" ] ]
NoahEmbedded/EmbeddedKWD
[ "2380d56b0b75bae4fedeb60885358332766f7319" ]
[ "Modell/CSV/CSVErstellen.py" ]
[ "import csv\nimport time\nimport tensorflow as tf\nimport tensorflow.keras.models\nfrom tensorflow.keras.preprocessing.image import load_img,img_to_array\nfrom numpy import expand_dims\nfrom os import listdir\n\ndef ladeBild(pfad):\n bild = load_img(path = pfad,color_mode = 'grayscale')\n array = img_to_array(bild)\n array = expand_dims(array,axis = 0)\n return array\n\n#Pfade Spektrogramme\npfadMarvin = \"D:\\Bachelorarbeit\\Spektrogramme_MarvinGo\"\npfadNoise = \"D:\\Bachelorarbeit\\Spektrogramme_Noise\"\npfadStille = \"D:\\Bachelorarbeit\\Spektrogramme_Stille\"\n\n#dateilisten\nlisteDatenMarvin = listdir(pfadMarvin)[-300:]\nlisteDatenNoise = listdir(pfadNoise)[-300:]\nlisteDatenStille = listdir(pfadStille)[-300:]\n\n\n#Tabellenkopfzeilen\nheaderNoise = [\"Input = Sprache\",\"Sprache in %\",\"Marvin Go in %\",\"Stille in %\",\"Inferenzdauer in ms\"]\nheaderMarvinGo = [\"Input = Marvin Go\",\"Sprache in %\",\"Marvin Go in %\",\"Stille in %\",\"Inferenzdauer in ms\"]\nheaderStille = [\"Input = Stille\",\"Sprache in %\",\"Marvin Go in %\",\"Stille in %\",\"Inferenzdauer in ms\"]\n#Optimalwerte\nZielZeileNoise = [\"Zielwert\",100,0,0,\"N/A\"]\nZielZeileMarvin = [\"Zielwert\",0,100,0,\"N/A\"]\nZielZeileStille = [\"Zielwert\",0,0,100,\"N/A\"]\n\ndatenNoise = []#Input = Noise\ndatenMarvin = []#Input = Marvin\ndatenStille = []#Input = Stille\n#############################################################\n# Berechnung Tensorflow #\n#############################################################\nprint(\"Starte Tensorflowinferenz\\n\")\nmodel = tensorflow.keras.models.load_model(\"model.h5\")\n#input = Noise\ni = 0\nfor noise in listeDatenNoise:\n pruefling = ladeBild(pfadNoise+\"/\"+noise)\n start = time.time()\n ergebnis = model.predict(pruefling)\n zeit = time.time()-start\n tempNoise = round(ergebnis[0][0]*100,2)\n tempMarvin = round(ergebnis[0][1]*100,2)\n tempStille = round(ergebnis[0][2]*100,2)\n datenNoise.append([\"Sample{}\".format(i),tempNoise,tempMarvin,tempStille,zeit*1000])\n i+=1\n#input = Marvin\ni = 0\nfor marvin in listeDatenMarvin:\n pruefling = ladeBild(pfadMarvin+\"/\"+marvin)\n start = time.time()\n ergebnis = model.predict(pruefling)\n zeit = time.time()-start\n tempNoise = round(ergebnis[0][0]*100,2)\n tempMarvin = round(ergebnis[0][1]*100,2)\n tempStille = round(ergebnis[0][2]*100,2)\n datenMarvin.append([\"Sample{}\".format(i),tempNoise,tempMarvin,tempStille,zeit*1000])\n i+=1\n#input = Stille\ni = 0\nfor stille in listeDatenStille:\n pruefling = ladeBild(pfadStille+\"/\"+stille)\n start = time.time()\n ergebnis = model.predict(pruefling)\n zeit = time.time()-start\n tempNoise = round(ergebnis[0][0]*100,2)\n tempMarvin = round(ergebnis[0][1]*100,2)\n tempStille = round(ergebnis[0][2]*100,2)\n datenStille.append([\"Sample{}\".format(i),tempNoise,tempMarvin,tempStille,zeit*1000])\n i+=1\nprint(\"Tensorflow Inferenz abgeschlossen\\n\")\n\n#############################################################\n# CSV Tensorflow #\n#############################################################\nwith open('tf.csv', mode='w') as file:\n writer = csv.writer(file, delimiter=';', quotechar='\"', quoting=csv.QUOTE_MINIMAL,lineterminator = \"\\n\")\n #Input = Sprache\n print(\"Sprache\\n\")\n writer.writerow(headerNoise)\n writer.writerow(ZielZeileNoise)\n writer.writerows(datenNoise)\n writer.writerow(\"\")\n #Input = Marvin Go\n print(\"Marvin\\n\")\n writer.writerow(headerMarvinGo)\n writer.writerow(ZielZeileMarvin)\n writer.writerows(datenMarvin)\n writer.writerow(\"\")\n #Input = Stille\n print(\"Stille\\n\")\n writer.writerow(headerStille)\n writer.writerow(ZielZeileStille)\n writer.writerows(datenStille)\n writer.writerow(\"\")\nfile.close()\n\ndatenNoise = []#Input = Noise\ndatenMarvin = []#Input = Marvin\ndatenStille = []#Input = Stille\n\n#############################################################\n# Berechnung Tensorflow Lite #\n#############################################################\nprint(\"Starte Tensorflow Lite Inferenz\\n\")\n# Load TFLite model and allocate tensors.\ninterpreter = tf.lite.Interpreter(model_path=\"model.tflite\")\ninterpreter.allocate_tensors()\n# Get input and output tensors.\ninput_details = interpreter.get_input_details()\noutput_details = interpreter.get_output_details()\n\ni = 0\nfor noise in listeDatenNoise:\n pruefling = ladeBild(pfadNoise+\"/\"+noise)\n start = time.time()\n interpreter.set_tensor(input_details[0]['index'], pruefling)\n interpreter.invoke()\n ergebnis = interpreter.get_tensor(output_details[0]['index'])\n zeit = time.time() - start\n tempNoise = round(ergebnis[0][0]*100,2)\n tempMarvin = round(ergebnis[0][1]*100,2)\n tempStille = round(ergebnis[0][2]*100,2)\n datenNoise.append([\"Sample{}\".format(i),tempNoise,tempMarvin,tempStille,zeit*1000])\n i+=1\ni = 0\nfor marvin in listeDatenMarvin:\n pruefling = ladeBild(pfadMarvin+\"/\"+marvin)\n start = time.time()\n interpreter.set_tensor(input_details[0]['index'], pruefling)\n interpreter.invoke()\n ergebnis = interpreter.get_tensor(output_details[0]['index'])\n zeit = time.time() - start\n tempNoise = round(ergebnis[0][0]*100,2)\n tempMarvin = round(ergebnis[0][1]*100,2)\n tempStille = round(ergebnis[0][2]*100,2)\n datenMarvin.append([\"Sample{}\".format(i),tempNoise,tempMarvin,tempStille,zeit*1000])\n i+=1\ni = 0\nfor stille in listeDatenStille:\n start = time.time()\n interpreter.set_tensor(input_details[0]['index'], pruefling)\n interpreter.invoke()\n ergebnis = interpreter.get_tensor(output_details[0]['index'])\n zeit = time.time() - start\n tempNoise = round(ergebnis[0][0]*100,2)\n tempMarvin = round(ergebnis[0][1]*100,2)\n tempStille = round(ergebnis[0][2]*100,2)\n datenStille.append([\"Sample{}\".format(i),tempNoise,tempMarvin,tempStille,zeit*1000])\n i+=1\nprint(\"Tensorflow Lite Inferenz abgeschlossen\\n\")\n#############################################################\n# CSV Tensorflow Lite #\n#############################################################\nwith open('tfLite.csv', mode='w') as file:\n writer = csv.writer(file, delimiter=';', quotechar='\"', quoting=csv.QUOTE_MINIMAL,lineterminator = \"\\n\")\n #Input = Sprache\n print(\"Sprache\\n\")\n writer.writerow(headerNoise)\n writer.writerow(ZielZeileNoise)\n writer.writerows(datenNoise)\n writer.writerow(\"\")\n #Input = Marvin Go\n print(\"Marvin\\n\")\n writer.writerow(headerMarvinGo)\n writer.writerow(ZielZeileMarvin)\n writer.writerows(datenMarvin)\n writer.writerow(\"\")\n #Input = Stille\n print(\"Stille\\n\")\n writer.writerow(headerStille)\n writer.writerow(ZielZeileStille)\n writer.writerows(datenStille)\n writer.writerow(\"\")\nfile.close()\nprint(\"CSV erstellen Abgeschlossen\\n\")" ]
[ [ "tensorflow.lite.Interpreter", "numpy.expand_dims", "tensorflow.keras.preprocessing.image.img_to_array", "tensorflow.keras.preprocessing.image.load_img" ] ]
leyp1/darts
[ "edeb1810f0a5e63ddef2b6db2a997c6c9428c51d" ]
[ "darts/tests/models/forecasting/test_NBEATS.py" ]
[ "import shutil\nimport tempfile\n\nimport numpy as np\n\nfrom darts.logging import get_logger\nfrom darts.tests.base_test_class import DartsBaseTestClass\nfrom darts.utils import timeseries_generation as tg\n\nlogger = get_logger(__name__)\n\ntry:\n from darts.models.forecasting.nbeats import NBEATSModel\n\n TORCH_AVAILABLE = True\nexcept ImportError:\n logger.warning(\"Torch not available. TCN tests will be skipped.\")\n TORCH_AVAILABLE = False\n\n\nif TORCH_AVAILABLE:\n\n class NBEATSModelTestCase(DartsBaseTestClass):\n def setUp(self):\n self.temp_work_dir = tempfile.mkdtemp(prefix=\"darts\")\n\n def tearDown(self):\n shutil.rmtree(self.temp_work_dir)\n\n def test_creation(self):\n with self.assertRaises(ValueError):\n # if a list is passed to the `layer_widths` argument, it must have a length equal to `num_stacks`\n NBEATSModel(\n input_chunk_length=1,\n output_chunk_length=1,\n num_stacks=3,\n layer_widths=[1, 2],\n )\n\n def test_fit(self):\n large_ts = tg.constant_timeseries(length=100, value=1000)\n small_ts = tg.constant_timeseries(length=100, value=10)\n\n # Test basic fit and predict\n model = NBEATSModel(\n input_chunk_length=1,\n output_chunk_length=1,\n n_epochs=10,\n num_stacks=1,\n num_blocks=1,\n layer_widths=20,\n )\n model.fit(large_ts[:98])\n pred = model.predict(n=2).values()[0]\n\n # Test whether model trained on one series is better than one trained on another\n model2 = NBEATSModel(\n input_chunk_length=1,\n output_chunk_length=1,\n n_epochs=10,\n num_stacks=1,\n num_blocks=1,\n layer_widths=20,\n )\n model2.fit(small_ts[:98])\n pred2 = model2.predict(n=2).values()[0]\n self.assertTrue(abs(pred2 - 10) < abs(pred - 10))\n\n # test short predict\n pred3 = model2.predict(n=1)\n self.assertEqual(len(pred3), 1)\n\n def test_multivariate(self):\n\n # testing a 2-variate linear ts, first one from 0 to 1, second one from 0 to 0.5, length 100\n series_multivariate = tg.linear_timeseries(length=100).stack(\n tg.linear_timeseries(length=100, start_value=0, end_value=0.5)\n )\n model = NBEATSModel(\n input_chunk_length=3, output_chunk_length=1, n_epochs=20\n )\n\n model.fit(series_multivariate)\n res = model.predict(n=2).values()\n\n # the theoretical result should be [[1.01, 1.02], [0.505, 0.51]].\n # We just test if the given result is not too far in average.\n self.assertTrue(\n abs(np.average(res - np.array([[1.01, 1.02], [0.505, 0.51]])) < 0.03)\n )\n\n # Test Covariates\n series_covariates = tg.linear_timeseries(length=100).stack(\n tg.linear_timeseries(length=100, start_value=0, end_value=0.1)\n )\n model = NBEATSModel(input_chunk_length=3, output_chunk_length=4, n_epochs=5)\n model.fit(series_multivariate, past_covariates=series_covariates)\n\n res = model.predict(\n n=3, series=series_multivariate, past_covariates=series_covariates\n ).values()\n\n self.assertEqual(len(res), 3)\n self.assertTrue(abs(np.average(res)) < 5)\n\n def test_logtensorboard(self):\n ts = tg.constant_timeseries(length=50, value=10)\n\n # testing if both the modes (generic and interpretable) runs with tensorboard\n architectures = [True, False]\n for architecture in architectures:\n # Test basic fit and predict\n model = NBEATSModel(\n input_chunk_length=1,\n output_chunk_length=1,\n n_epochs=1,\n log_tensorboard=True,\n work_dir=self.temp_work_dir,\n generic_architecture=architecture,\n )\n model.fit(ts)\n model.predict(n=2)\n" ]
[ [ "numpy.array", "numpy.average" ] ]
MichalOleszak/tsaugur
[ "367d04081395e691bacc725133c2b247453ae464" ]
[ "tsaugur/models/holt_winters.py" ]
[ "import itertools\nimport warnings\nimport numpy as np\nfrom statsmodels.tsa.holtwinters import ExponentialSmoothing\n\nfrom tsaugur.utils import data_utils, model_utils\nfrom tsaugur.models import base_model\nfrom tsaugur.metrics import get_metric\n\n\nclass HoltWinters(base_model.BaseModel):\n \"\"\"\n Holt-Winters Exponential Smoothing.\n \"\"\"\n\n def _tune(self, y, period, x=None, metric=\"smape\", val_size=None, verbose=False):\n \"\"\"\n Tune hyperparameters of the model.\n :param y: pd.Series or 1-D np.array, time series to predict.\n :param period: Int or Str, the number of observations per cycle: 1 or \"annual\" for yearly data, 4 or \"quarterly\"\n for quarterly data, 7 or \"daily\" for daily data, 12 or \"monthly\" for monthly data, 24 or \"hourly\" for hourly\n data, 52 or \"weekly\" for weekly data. First-letter abbreviations of strings work as well (\"a\", \"q\", \"d\", \"m\",\n \"h\" and \"w\", respectively). Additional reference: https://robjhyndman.com/hyndsight/seasonal-periods/.\n :param x: not used for Holt-Winters model\n :param metric: Str, the metric used for model selection. One of: \"mse\", \"mae\", \"mape\", \"smape\", \"rmse\".\n :param val_size: Int, the number of most recent observations to use as validation set for tuning.\n :param verbose: Boolean, True for printing additional info while tuning.\n :return: None\n \"\"\"\n self.period = data_utils.period_to_int(period) if type(period) == str else period\n val_size = int(len(y) * .1) if val_size is None else val_size\n y_train, y_val = model_utils.train_val_split(y, val_size=val_size)\n metric_fun = get_metric(metric)\n\n params_grid = {\n \"trend\": [\"add\", \"mul\"],\n \"seasonal\": [\"add\", \"mul\"],\n \"damped\": [True, False],\n \"use_boxcox\": [True, False, \"log\"],\n \"remove_bias\": [True, False]\n }\n params_keys, params_values = zip(*params_grid.items())\n params_permutations = [dict(zip(params_keys, v)) for v in itertools.product(*params_values)]\n\n scores = []\n for permutation in params_permutations:\n try:\n with warnings.catch_warnings():\n warnings.simplefilter(\"ignore\")\n model = ExponentialSmoothing(y_train, seasonal_periods=self.period, trend=permutation[\"trend\"],\n seasonal=permutation[\"seasonal\"], damped=permutation[\"damped\"])\n model = model.fit(use_boxcox=permutation[\"use_boxcox\"], remove_bias=permutation[\"remove_bias\"])\n y_pred = model.forecast(len(y_val))\n score = metric_fun(y_val, y_pred)\n scores.append(score)\n except:\n scores.append(np.inf)\n\n best_params = params_permutations[np.nanargmin(scores)]\n self.params.update(best_params)\n self.params[\"tuned\"] = True\n\n def fit(self, y, period, x=None, metric=\"smape\", val_size=None, verbose=False):\n \"\"\"\n Build the model with using best-tuned hyperparameter values.\n :param y: pd.Series or 1-D np.array, time series to predict.\n :param period: Int or Str, the number of observations per cycle: 1 or \"annual\" for yearly data, 4 or \"quarterly\"\n for quarterly data, 7 or \"daily\" for daily data, 12 or \"monthly\" for monthly data, 24 or \"hourly\" for hourly\n data, 52 or \"weekly\" for weekly data. First-letter abbreviations of strings work as well (\"a\", \"q\", \"d\", \"m\",\n \"h\" and \"w\", respectively). Additional reference: https://robjhyndman.com/hyndsight/seasonal-periods/.\n :param x: not used for Holt-Winters model\n :param metric: Str, the metric used for model selection. One of: \"mse\", \"mae\", \"mape\", \"smape\", \"rmse\".\n :param val_size: Int, the number of most recent observations to use as validation set for tuning.\n :param verbose: Boolean, True for printing additional info while tuning.\n :return: None\n \"\"\"\n self.y = y\n self.name = \"Holt-Winters Exponential Smoothing\"\n self.key = \"holt_winters\"\n self._tune(y=y, period=period, x=x, metric=metric, val_size=val_size, verbose=verbose)\n model = ExponentialSmoothing(y, seasonal_periods=self.period, trend=self.params[\"trend\"],\n seasonal=self.params[\"seasonal\"], damped=self.params[\"damped\"])\n self.model = model.fit(use_boxcox=self.params[\"use_boxcox\"], remove_bias=self.params[\"remove_bias\"])\n\n def predict(self, horizon, x=None):\n \"\"\"\n Predict future values of the time series using the fitted model.\n :param horizon: Int, the number of observations in the future to predict\n :param x: not used for Holt-Winters model\n :return: 1-D np.array with predictions\n \"\"\"\n return self.model.forecast(horizon).values\n" ]
[ [ "numpy.nanargmin" ] ]
afcarl/Useful-python
[ "5d1947052fb25b2388704926e4692511cc162031" ]
[ "Scikit-learn/sklearn_tutorial_notebooks/fig_code/sgd_separator.py" ]
[ "import numpy as np\nimport matplotlib.pyplot as plt\nfrom sklearn.linear_model import SGDClassifier\nfrom sklearn.datasets.samples_generator import make_blobs\n\ndef plot_sgd_separator():\n # we create 50 separable points\n X, Y = make_blobs(n_samples=50, centers=2,\n random_state=0, cluster_std=0.60)\n\n # fit the model\n clf = SGDClassifier(loss=\"hinge\", alpha=0.01,\n n_iter=200, fit_intercept=True)\n clf.fit(X, Y)\n\n # plot the line, the points, and the nearest vectors to the plane\n xx = np.linspace(-1, 5, 10)\n yy = np.linspace(-1, 5, 10)\n\n X1, X2 = np.meshgrid(xx, yy)\n Z = np.empty(X1.shape)\n for (i, j), val in np.ndenumerate(X1):\n x1 = val\n x2 = X2[i, j]\n\n x1 = np.array(x1)\n x2 = np.array(x2)\n x_tot = np.array([x1, x2])\n x_tot = x_tot.reshape(1, -1)\n p = clf.decision_function(x_tot)\n Z[i, j] = p[0]\n levels = [-1.0, 0.0, 1.0]\n linestyles = ['dashed', 'solid', 'dashed']\n colors = 'k'\n\n ax = plt.axes()\n ax.contour(X1, X2, Z, levels, colors=colors, linestyles=linestyles)\n ax.scatter(X[:, 0], X[:, 1], c=Y, cmap=plt.cm.Paired)\n\n ax.axis('tight')\n\n\nif __name__ == '__main__':\n plot_sgd_separator()\n plt.show()\n" ]
[ [ "numpy.array", "numpy.linspace", "sklearn.linear_model.SGDClassifier", "matplotlib.pyplot.show", "matplotlib.pyplot.axes", "numpy.ndenumerate", "sklearn.datasets.samples_generator.make_blobs", "numpy.meshgrid", "numpy.empty" ] ]
SergioAlvarezB/ml-numpy
[ "bf450b0d48b52c56fd3d124a5b41f2b99594ea3b" ]
[ "models/svm.py" ]
[ "import numpy as np\n\nfrom utils import kernels\n\n\nclass SVM:\n \"\"\"SVM classifier class.\n\n Implements a SVM classification model. The algorithm minimize the dual form\n cost using a projected version of gradient descent.\n\n Parameters\n ----------\n kernel : `str`, optional\n Kernel to use. Defaults to \"linear\".\n\n C : `float`, optional\n Cost parameter, specifies how much we penalize incorrectly classified\n points, the case C=inf is only possible with separable data.\n Defaults to 1.\n\n \"\"\"\n def __init__(self, kernel='linear', C=1, degree=2, gamma=1.0/4):\n self.C = C\n self.kernel = self._get_kernel(kernel, degree, gamma)\n\n def _get_kernel(self, kernel, degree, gamma):\n # return kernel as a Callable\n if kernel == 'linear':\n return kernels.linear\n\n elif kernel == 'quadratic':\n return lambda x, y: kernels.polynomial(x, y, d=2)\n\n elif kernel == 'polynomial':\n return lambda x, y: kernels.polynomial(x, y, d=degree)\n\n elif kernel == 'rbf':\n return lambda x, y: kernels.rbf(x, y, gamma=gamma)\n\n else:\n raise NotImplemented\n\n def _fit_analytic(self, X, y):\n \"\"\"Fits the lagr_multipliers with the analytic solution of the dual\n form. THIS METHOD IS NOT CORRECT, although KKT conditions can be\n enforced a posteriory, the solution is no longer guaranteed to be\n optimal.\n \"\"\"\n # Transform labels from format {0, 1} to {-1, 1}\n y[y == 0] = -1\n\n n_samples, n_dimensions = X.shape\n\n # Compute kernel_matrix labeled\n G = np.zeros([n_samples, n_samples])\n\n for i in range(n_samples-1):\n for j in range(i, n_samples):\n G[i, j] = y[i]*y[j]*self.kernel(X[i, :], X[j, :])\n G[j, i] = G[i, j]\n\n # Compute analytic solution\n lagr_multipliers = np.sum(np.linalg.pinv(G), axis=0)\n lagr_multipliers = np.clip(lagr_multipliers, 0, self.C)\n\n supported = lagr_multipliers > 0\n self.lagr_multipliers = lagr_multipliers[supported]\n self.supported_vectors = X[supported, :]\n self.labels = y[supported]\n\n # Compute intercept\n bias = []\n for i in range(len(self.labels)):\n\n if self.lagr_multipliers[i] < self.C:\n b = self.labels[i]\n for j in range(len(self.labels)):\n if i != j:\n k = self.kernel(self.supported_vectors[j],\n self.supported_vectors[i])\n b -= self.lagr_multipliers[j] * self.labels[j] * k\n bias.append(b)\n self.b = np.mean(np.array(bias))\n\n def fit(self, X, y, iterations=1000, learning_rate=0.01):\n\n # Transform labels from format {0, 1} to {-1, 1}\n y[y == 0] = -1\n\n n_samples, n_dimensions = X.shape\n\n # Initialize lagrange multipliers\n lagr_multipliers = np.random.rand(n_samples)/n_samples\n\n # Compute kernel_matrix labeled\n G = np.zeros([n_samples, n_samples])\n\n for i in range(n_samples-1):\n for j in range(i, n_samples):\n G[i, j] = y[i]*y[j]*self.kernel(X[i, :], X[j, :])\n G[j, i] = G[i, j]\n\n # Projected gradient descent\n loss = []\n for i in range(iterations):\n # Gradient of the dual form with respect to lagrange multipliers.\n dl = np.dot(lagr_multipliers, G) - 1\n\n # Update lagrange multipliers.\n lagr_multipliers -= (1/n_samples)*learning_rate*dl\n\n # Project update to satisfy constrains.\n lagr_multipliers = np.clip(lagr_multipliers, 0, self.C)\n\n # Compute loss.\n loss.append(self.loss(lagr_multipliers, G))\n\n # Only vectors with multipler greater than 0 contibute\n # to the margin.\n supported = lagr_multipliers > 1e-7\n self.lagr_multipliers = lagr_multipliers[supported]\n self.supported_vectors = X[supported, :]\n self.labels = y[supported]\n\n # Compute intercept\n bias = []\n for i in range(len(self.labels)):\n if self.lagr_multipliers[i] < self.C:\n b = self.labels[i]\n for j in range(len(self.labels)):\n if i != j:\n k = self.kernel(self.supported_vectors[j],\n self.supported_vectors[i])\n b -= self.lagr_multipliers[j] * self.labels[j] *k\n\n bias.append(b)\n\n self.b = np.mean(np.array(bias))\n return loss\n\n def loss(self, lagr_multipliers, G):\n # Return dual form cost function\n\n target = np.dot(np.dot(lagr_multipliers, G), lagr_multipliers)\n constraint = np.sum(lagr_multipliers)\n return 0.5 * (target - constraint)\n\n def _predict_single(self, x):\n K = np.array([self.kernel(xi, x) for xi in self.supported_vectors])\n return (np.sum(self.lagr_multipliers * self.labels * K) + self.b) > 0\n\n def predict(self, X):\n X = np.atleast_2d(X)\n y_hat = np.zeros(X.shape[0])\n for i in range(len(y_hat)):\n y_hat[i] = self._predict_single(X[i, :])\n\n return y_hat\n" ]
[ [ "numpy.dot", "numpy.clip", "numpy.atleast_2d", "numpy.linalg.pinv", "numpy.random.rand", "numpy.array", "numpy.zeros", "numpy.sum" ] ]
tp5uiuc/PyElastica
[ "37db35137b198d1c0756e058ec1635a3675fab22" ]
[ "examples/JointCases/hinge_joint.py" ]
[ "__doc__ = \"\"\"Hinge joint example, for detailed explanation refer to Zhang et. al. Nature Comm. methods section.\"\"\"\n\nimport numpy as np\nimport sys\n\n# FIXME without appending sys.path make it more generic\nsys.path.append(\"../../\")\nfrom elastica import *\nfrom examples.JointCases.external_force_class_for_joint_test import (\n EndpointForcesSinusoidal,\n)\nfrom examples.JointCases.joint_cases_postprocessing import (\n plot_position,\n plot_video,\n plot_video_xy,\n plot_video_xz,\n)\n\n\nclass HingeJointSimulator(\n BaseSystemCollection, Constraints, Connections, Forcing, CallBacks\n):\n pass\n\n\nhinge_joint_sim = HingeJointSimulator()\n\n# setting up test params\nn_elem = 10\ndirection = np.array([0.0, 0.0, 1.0])\nnormal = np.array([0.0, 1.0, 0.0])\nroll_direction = np.cross(direction, normal)\nbase_length = 0.2\nbase_radius = 0.007\nbase_area = np.pi * base_radius ** 2\ndensity = 1750\nnu = 0.001\nE = 3e7\npoisson_ratio = 0.5\nshear_modulus = E / (poisson_ratio + 1.0)\n\nstart_rod_1 = np.zeros((3,))\nstart_rod_2 = start_rod_1 + direction * base_length\n\n# Create rod 1\nrod1 = CosseratRod.straight_rod(\n n_elem,\n start_rod_1,\n direction,\n normal,\n base_length,\n base_radius,\n density,\n nu,\n E,\n shear_modulus=shear_modulus,\n)\nhinge_joint_sim.append(rod1)\n# Create rod 2\nrod2 = CosseratRod.straight_rod(\n n_elem,\n start_rod_2,\n direction,\n normal,\n base_length,\n base_radius,\n density,\n nu,\n E,\n shear_modulus=shear_modulus,\n)\nhinge_joint_sim.append(rod2)\n\n# Apply boundary conditions to rod1.\nhinge_joint_sim.constrain(rod1).using(\n OneEndFixedRod, constrained_position_idx=(0,), constrained_director_idx=(0,)\n)\n\n# Connect rod 1 and rod 2\nhinge_joint_sim.connect(\n first_rod=rod1, second_rod=rod2, first_connect_idx=-1, second_connect_idx=0\n).using(\n HingeJoint, k=1e5, nu=0, kt=5e3, normal_direction=roll_direction\n) # 1e-2\n\n# Add forces to rod2\nhinge_joint_sim.add_forcing_to(rod2).using(\n EndpointForcesSinusoidal,\n start_force_mag=0,\n end_force_mag=5e-3,\n ramp_up_time=0.2,\n tangent_direction=direction,\n normal_direction=normal,\n)\n\n\n# Callback functions\n# Add call backs\nclass TestJoints(CallBackBaseClass):\n \"\"\"\n Call back function for testing joints\n \"\"\"\n\n def __init__(self, step_skip: int, callback_params: dict):\n CallBackBaseClass.__init__(self)\n self.every = step_skip\n self.callback_params = callback_params\n\n def make_callback(self, system, time, current_step: int):\n if current_step % self.every == 0:\n self.callback_params[\"time\"].append(time)\n self.callback_params[\"step\"].append(current_step)\n self.callback_params[\"position\"].append(system.position_collection.copy())\n self.callback_params[\"velocity\"].append(system.velocity_collection.copy())\n return\n\n\npp_list_rod1 = defaultdict(list)\npp_list_rod2 = defaultdict(list)\n\n\nhinge_joint_sim.collect_diagnostics(rod1).using(\n TestJoints, step_skip=1000, callback_params=pp_list_rod1\n)\nhinge_joint_sim.collect_diagnostics(rod2).using(\n TestJoints, step_skip=1000, callback_params=pp_list_rod2\n)\n\n\nhinge_joint_sim.finalize()\ntimestepper = PositionVerlet()\n# timestepper = PEFRL()\n\nfinal_time = 10\ndl = base_length / n_elem\ndt = 1e-5\ntotal_steps = int(final_time / dt)\nprint(\"Total steps\", total_steps)\nintegrate(timestepper, hinge_joint_sim, final_time, total_steps)\n\nPLOT_FIGURE = True\nSAVE_FIGURE = False\nPLOT_VIDEO = False\n\n# plotting results\nif PLOT_FIGURE:\n filename = \"hinge_joint_test.png\"\n plot_position(pp_list_rod1, pp_list_rod2, filename, SAVE_FIGURE)\n\nif PLOT_VIDEO:\n filename = \"hinge_joint_test.mp4\"\n plot_video(pp_list_rod1, pp_list_rod2, video_name=filename, margin=0.2, fps=100)\n plot_video_xy(\n pp_list_rod1, pp_list_rod2, video_name=filename + \"_xy.mp4\", margin=0.2, fps=100\n )\n plot_video_xz(\n pp_list_rod1, pp_list_rod2, video_name=filename + \"_xz.mp4\", margin=0.2, fps=100\n )\n" ]
[ [ "numpy.array", "numpy.zeros", "numpy.cross" ] ]
rosechung-unity3d/Robotics-Object-Pose-Estimation
[ "f33075d7e5f9476e10eddee055f6150aeb4efb66" ]
[ "Model/pose_estimation/pose_estimation_estimator.py" ]
[ "import copy\nimport os\nimport logging\nfrom pose_estimation.logger import Logger\nfrom .storage.checkpoint import EstimatorCheckpoint\n\nfrom pose_estimation.model import PoseEstimationNetwork\nfrom pose_estimation.train import train_model\nfrom pose_estimation.evaluate import evaluate_model\nfrom pose_estimation.single_cube_dataset import SingleCubeDataset\nfrom pose_estimation.evaluation_metrics.translation_average_mean_square_error import (\n translation_average_mean_square_error,\n)\nfrom pose_estimation.evaluation_metrics.orientation_average_quaternion_error import (\n orientation_average_quaternion_error,\n)\n\nimport torch\nimport torchvision\n\n\nclass PoseEstimationEstimator:\n \"\"\"\n This model is used on the SingleCube dataset.\n Its aim is to predict the position and the orientation of the cube.\n This class contains the method to train, evaluate, save and load the model.\n\n\n Attributes:\n config (dict): estimator config\n data_root (str): path towards the data\n writer: Tensorboard writer object\n checkpointer: Model checkpointer callback to save models\n device: model training on device (cpu|cuda)\n logger (Logger object form the class in logger.py): Log the performance\n model (lsit): list of the PoseEstimationNetwork where the length is equal\n to the number of classes\n \"\"\"\n\n def __init__(self, *, config, **kwargs):\n\n self.config = config\n self.data_root = config.system.data_root\n self.writer = Logger(\n log_dir=self.config.system.log_dir_system,\n config=config,\n )\n print(\"writer log:\", config.system.log_dir_system)\n\n self.checkpointer = EstimatorCheckpoint(\n estimator_name=self.config.estimator, log_dir=config.system.log_dir_system,\n )\n self.device = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n\n # logging config\n logging.basicConfig(\n level=logging.INFO,\n format=(\n \"%(levelname)s | %(asctime)s | %(name)s | %(threadName)s | \"\n \"%(message)s\"\n ),\n datefmt=\"%Y-%m-%d %H:%M:%S\",\n )\n self.logger = logging.getLogger(__name__)\n\n # We will create as many networks as there are objects to predict the position\n self.model = PoseEstimationNetwork(is_symetric=config.dataset.symmetric)\n\n # load estimators from file if checkpoint_file exists\n checkpoint_file = config.checkpoint.load_dir_checkpoint\n if checkpoint_file != \"None\":\n self.checkpointer.load(self, checkpoint_file)\n\n def train(self):\n \"\"\"\n This method is to train the PoseEstimationEstimator model\n \"\"\"\n self.logger.info(\"Start training\")\n train_model(self)\n\n def evaluate(self):\n \"\"\"\n This method is to evaluate the PoseEstimationEstimator model\n \"\"\"\n self.logger.info(\"Start evaluation\")\n evaluate_model(self)\n\n def save(self, path):\n \"\"\"Save all models into a directory\n\n Args:\n path (str): full path to save serialized estimator\n\n Returns:\n saved full path of the serialized estimator\n \"\"\"\n save_dict = {\n \"model\": self.model.state_dict(),\n \"config\": self.config,\n }\n torch.save(save_dict, path)\n\n def load(self, path):\n \"\"\"Load Estimator from path\n\n Args:\n path (str): full path to the serialized estimator\n label_id (int): corresponds to the label id in the captures_*.json folder minus 1.\n \"\"\"\n self.logger.info(f\"loading checkpoint from file\")\n checkpoint = torch.load(path, map_location=self.device)\n self.model.load_state_dict(checkpoint[\"model\"])\n\n loaded_config = copy.deepcopy(checkpoint[\"config\"])\n stored_config = copy.deepcopy(self.config)\n del stored_config[\"checkpoint\"][\"load_dir_checkpoint\"]\n if stored_config != loaded_config:\n self.logger.warning(\n f\"Found difference in estimator config.\"\n f\"Estimator loaded from {path} was trained using config: \"\n f\"{loaded_config}. However, the current config is: \"\n f\"{self.config}.\"\n )\n" ]
[ [ "torch.load", "torch.cuda.is_available", "torch.save" ] ]
dasturge/eisen-core
[ "09056f1e6aff450ef402b35b10ef96a7d4a3ff87" ]
[ "eisen/datasets/camus.py" ]
[ "import os\nimport torch\nimport copy\n\nfrom torch.utils.data import Dataset\n\n\nclass CAMUS(Dataset):\n \"\"\"\n This object implements the capability of reading CAMUS data. The CAMUS dataset is a dataset of ultrasound\n images of the heart. Further information about this dataset can be found on the official website\n https://www.creatis.insa-lyon.fr/Challenge/camus/index.html\n\n Through this module, users are able to make use of the challenge data by simply specifying the directory where\n the data is locally stored. Therefore it is necessary to first download the data, store or unpack it in a specific\n directory and then instantiate an object of type CAMUS which will make use of the data in the directory\n and make it available to Eisen.\n\n .. note::\n\n This dataset will generate data entries with keys: 'type', 'image_2CH', 'label_2CH', 'sequence_2CH',\n 'image_4CH', 'label_4CH', sequence_4CH depending on the selected input parameter configuration.\n The data generated consists of paths to images and type (string).\n\n .. code-block:: python\n\n from eisen.datasets import CAMUS\n\n dset = CAMUS('/data/root/path')\n\n \"\"\"\n def __init__(\n self,\n data_dir,\n with_ground_truth,\n with_2CH=True,\n with_4CH=True,\n with_entire_sequences=False,\n transform=None\n ):\n \"\"\"\n :param data_dir: the base directory where the data is located\n :type data_dir: str\n :param with_ground_truth: whether ground truth annotation should be included (won't work during testing)\n :type with_ground_truth: bool\n :param with_2CH: whether 2 chambers data should be included (default True)\n :type with_2CH: bool\n :param with_4CH: whether 4 chambers data should be included (default True)\n :type with_4CH: bool\n :param with_entire_sequences: whether the entire sequences for 4CH and 2CH data should be included (default False)\n :type with_entire_sequences: bool\n :param transform: a transform object (can be the result of a composition of transforms)\n :type transform: callable\n\n .. code-block:: python\n\n from eisen.datasets import CAMUS\n\n dset = CAMUS(\n data_dir='/data/root/path',\n with_ground_truth=True,\n with_2CH=True,\n with_4CH=True,\n with_entire_sequences=False\n transform=None\n )\n\n <json>\n [\n {\"name\": \"with_ground_truth\", \"type\": \"bool\", \"value\": \"\"},\n {\"name\": \"with_2CH\", \"type\": \"bool\", \"value\": \"true\"},\n {\"name\": \"with_4CH\", \"type\": \"bool\", \"value\": \"true\"},\n {\"name\": \"with_entire_sequences\", \"type\": \"bool\", \"value\": \"false\"}\n ]\n </json>\n \"\"\"\n self.data_dir = data_dir\n\n self.with_ground_truth = with_ground_truth\n self.with_2CH = with_2CH\n self.with_4CH = with_4CH\n self.with_entire_sequences = with_entire_sequences\n\n self.data = []\n\n all_subdirs = [o for o in os.listdir(self.data_dir) if os.path.isdir(os.path.join(self.data_dir, o))]\n\n for dir_name in all_subdirs:\n\n dir = os.path.join(self.data_dir, dir_name)\n\n if len(os.listdir(dir)) == 0:\n print('WARNING: dataset directory {} appears empty'.format(dir))\n continue\n\n for typ in ['ED', 'ES']:\n item = dict()\n\n item['type'] = typ\n\n if self.with_2CH:\n item['image_2CH'] = os.path.join(dir_name, '{}_2CH_{}.mhd'.format(dir_name, typ))\n\n if self.with_ground_truth:\n item['label_2CH'] = os.path.join(dir_name, '{}_2CH_{}_gt.mhd'.format(dir_name, typ))\n\n if self.with_entire_sequences:\n item['sequence_2CH'] = os.path.join(dir_name, '{}_2CH_sequence.mhd'.format(dir_name))\n\n if self.with_4CH:\n item['image_4CH'] = os.path.join(dir_name, '{}_4CH_{}.mhd'.format(dir_name, typ))\n\n if self.with_ground_truth:\n item['label_4CH'] = os.path.join(dir_name, '{}_4CH_{}_gt.mhd'.format(dir_name, typ))\n\n if self.with_entire_sequences:\n item['sequence_4CH'] = os.path.join(dir_name, '{}_4CH_sequence.mhd'.format(dir_name))\n\n self.data.append(item)\n\n self.transform = transform\n\n def __len__(self):\n return len(self.data)\n\n def __getitem__(self, idx):\n if torch.is_tensor(idx):\n idx = idx.tolist()\n\n item = copy.deepcopy(self.data[idx])\n\n if self.transform:\n item = self.transform(item)\n\n return item\n" ]
[ [ "torch.is_tensor" ] ]
neurallayer/fos
[ "92c3cd485a45c2243900c881b6625c4453f6a359" ]
[ "test/test_metrics.py" ]
[ "# pylint: disable=E1101, C0116, C0114\nimport torch\nfrom fos.metrics import BinaryAccuracy, ConfusionMetric\n\ndef test_accuracy():\n metric = BinaryAccuracy()\n y_pred = torch.randn(100, 10, 10)\n value = metric(y_pred, y_pred > 0.)\n assert value == 1.0\n value = metric(y_pred, y_pred < 0.)\n assert value == 0.0\n\ndef test_tp():\n metric = ConfusionMetric(threshold=0.5, sigmoid=False)\n y_pred = torch.FloatTensor([[0.1, 0.2, 0.8], [0.4, 0.5, 0.6], [0.6, 0.7, 0.8]])\n y_true = (y_pred > 0.5).int()\n result = metric(y_pred, y_true)\n assert len(result) == 4\n" ]
[ [ "torch.randn", "torch.FloatTensor" ] ]
GuillaumeSimo/autoforecast
[ "7205ce5f426b2950f7de2877303fb5999edf63be" ]
[ "autoforecast/metrics/metrics.py" ]
[ "import numpy as np\nfrom sklearn.metrics import mean_absolute_error, mean_absolute_percentage_error, mean_squared_error\n\n\ndef encode(data, col=\"bank\"):\n map_col_to_col_id = {col: col_id for col_id, col in enumerate(data[col].unique())}\n data[f\"{col}_token\"] = data[col].map(map_col_to_col_id)\n return data, map_col_to_col_id\n\n\ndef smape_score(y_test, y_pred):\n \"\"\"\n https://www.statology.org/smape-python/\n \"\"\"\n y_test_ = []\n y_pred_ = []\n for test, pred in zip(y_test, y_pred):\n if abs(test) < 50 and abs(pred) < 50:\n y_test_.append(1)\n y_pred_.append(1)\n elif abs(test - pred) < 100:\n y_test_.append(1)\n y_pred_.append(1)\n else:\n y_test_.append(test)\n y_pred_.append(pred)\n\n y_test = np.array(y_test_)\n y_pred = np.array(y_pred_)\n if len(y_test) == 0:\n return 0.0\n return (\n 1\n / len(y_test)\n * np.sum(2 * np.abs(y_pred - y_test) / (np.abs(y_test) + np.abs(y_pred)) * 100)\n )\n\n\ndef get_metrics(y_pred, y_test, y_naive=None):\n mse = mean_squared_error(y_pred, y_test)\n rmse = np.sqrt(mse)\n rmsle = np.log(rmse)\n mape = mean_absolute_percentage_error(y_test, y_pred)\n mae = mean_absolute_error(y_true=y_test, y_pred=y_pred)\n y_pred = np.array(y_pred)\n y_test = np.array(y_test)\n # https://en.wikipedia.org/wiki/Symmetric_mean_absolute_percentage_error#\n smape = smape_score(y_pred, y_test)\n y_pred = np.array([0.0 if pred_ < 1e-6 else pred_ for pred_ in y_pred])\n mase = None\n if y_naive is not None:\n mae_naive = mean_absolute_error(y_true=y_test, y_pred=y_naive)\n if mae_naive == 0.0:\n if mae != 0.0:\n mae_naive = mae\n else:\n mase = 0.0\n mae_naive = mae if mae_naive == 0.0 else mae_naive\n if mase is None:\n mase = mae / mae_naive\n return {\n \"mse\": mse,\n \"rmse\": rmse,\n \"rmsle\": rmsle,\n \"mape\": mape,\n \"mae\": mae,\n \"smape\": smape,\n \"mase\": mase,\n }\n" ]
[ [ "numpy.log", "numpy.sqrt", "numpy.abs", "sklearn.metrics.mean_absolute_error", "sklearn.metrics.mean_squared_error", "sklearn.metrics.mean_absolute_percentage_error", "numpy.array" ] ]
jan-xu/2d-slam
[ "11b0e5e0157578d342270aea6465d673cd2de470" ]
[ "icp.py" ]
[ "#!/usr/bin/env python\n# coding: utf-8\n\nimport numpy as np\nfrom sklearn.neighbors import NearestNeighbors\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n\ndef wraptopi(phi):\n return np.mod(phi + np.pi, 2*np.pi) - np.pi\n\ndef best_fit_transform(A, B):\n '''\n Calculates the least-squares best-fit transform that maps corresponding points A to B in m spatial dimensions\n Input:\n A: Nxm numpy array of corresponding points\n B: Nxm numpy array of corresponding points\n Returns:\n T: (m+1)x(m+1) homogeneous transformation matrix that maps A on to B\n R: mxm rotation matrix\n t: mx1 translation vector\n '''\n\n # get number of dimensions\n m = A.shape[1]\n\n # translate points to their centroids\n centroid_A = np.mean(A, axis=0)\n centroid_B = np.mean(B, axis=0)\n AA = A - centroid_A\n BB = B - centroid_B\n\n # rotation matrix\n H = np.dot(AA.T, BB)\n U, S, Vt = np.linalg.svd(H)\n R = np.dot(Vt.T, U.T)\n\n # special reflection case\n if np.linalg.det(R) < 0:\n Vt[m-1,:] *= -1\n R = np.dot(Vt.T, U.T)\n\n # translation\n t = centroid_B.T - np.dot(R,centroid_A.T)\n\n # homogeneous transformation\n T = np.identity(m+1)\n T[:m, :m] = R\n T[:m, m] = t\n\n return T, R, t\n\n\ndef nearest_neighbor(src, dst):\n '''\n Find the nearest (Euclidean) neighbor in dst for each point in src\n Input:\n src: Nxm array of points\n dst: Nxm array of points\n Output:\n distances: Euclidean distances of the nearest neighbor\n indices: dst indices of the nearest neighbor\n '''\n\n neigh = NearestNeighbors(n_neighbors=1)\n neigh.fit(dst)\n distances, indices = neigh.kneighbors(src, return_distance=True)\n return distances.ravel(), indices.ravel()\n\n\ndef icp(A, B, init_pose=None, max_iterations=25, tolerance=0.0001):\n '''\n The Iterative Closest Point method: finds best-fit transform that maps points A on to points B\n Input:\n A: Nxm numpy array of source mD points\n B: Nxm numpy array of destination mD point\n init_pose: (m+1)x(m+1) homogeneous transformation\n max_iterations: exit algorithm after max_iterations\n tolerance: convergence criteria\n Output:\n T: final homogeneous transformation that maps A on to B\n distances: Euclidean distances (errors) of the nearest neighbor\n i: number of iterations to converge\n '''\n\n # get number of dimensions\n m = A.shape[1]\n\n # make points homogeneous, copy them to maintain the originals\n src = np.ones((m+1,A.shape[0]))\n dst = np.ones((m+1,B.shape[0]))\n src[:m,:] = np.copy(A.T)\n dst[:m,:] = np.copy(B.T)\n\n # apply the initial pose estimation\n if init_pose is not None:\n src = np.dot(init_pose, src)\n\n prev_error = 0\n\n for i in range(max_iterations):\n # find the nearest neighbors between the current source and destination points\n distances, indices = nearest_neighbor(src[:m,:].T, dst[:m,:].T)\n\n # compute the transformation between the current source and nearest destination points\n T,_,_ = best_fit_transform(src[:m,:].T, dst[:m,indices].T)\n\n # update the current source\n src = np.dot(T, src)\n\n # check error\n mean_error = np.max(distances)\n #if mean_error < tolerance:#np.abs(prev_error - mean_error) < tolerance:\n # break\n prev_error = mean_error\n\n # calculate final transformation\n _,R,t = best_fit_transform(A, src[:m,:].T)\n\n return R, t, distances, i\n\n\nclass ScanICP(object):\n\n phi = np.linspace(-2*np.pi/3, 2*np.pi/3, 682)\n\n def __init__(self, r):\n mask = (r < 1.5) & (r > 0.1)\n self.r = r[mask]\n self.phi = ScanICP.phi[mask]\n self.m = len(self.r)\n self.x = self.r*np.cos(self.phi)\n self.y = self.r*np.sin(self.phi)\n self.P = np.array([self.x, self.y]).T\n\n def icp_match(self, prev_scan):\n\n if prev_scan.m > self.m:\n P_prev = prev_scan.P[np.random.randint(prev_scan.m, size=self.m), :]\n P_new = self.P\n elif prev_scan.m < self.m:\n P_new = self.P[np.random.randint(self.m, size=prev_scan.m), :]\n P_prev = prev_scan.P\n else:\n P_prev = prev_scan.P\n P_new = self.P\n\n Ricp, Ticp, d, i = icp(P_prev, P_new)\n\n while np.any(d >= 0.025):\n P_prev = P_prev[d < 0.025,:]\n P_new = P_new[d < 0.025,:]\n\n Ricp, Ticp, d, i = icp(P_prev, P_new)\n\n return Ricp, Ticp\n\nclass GlobalFrame(object):\n\n def __init__(self, lidar_r):\n self.n = lidar_r.shape[0]\n self.ref_scan = ScanICP(lidar_r[0,:])\n self.x_pc = self.ref_scan.x\n self.y_pc = self.ref_scan.y\n self.pose = np.zeros((2,))\n self.traj = self.pose\n\n # Initialize translation and rotation arrays\n self.R = np.zeros((self.n,2,2))\n self.R[0,:,:] = np.eye(2)\n self.T = np.zeros((self.n,2))\n\n self.scans = [self.ref_scan]\n\n def next_scan(self, r, pose=None, head=None):\n k = len(self.scans)\n\n if pose is None:\n pose = self.pose\n if head is None:\n head = np.arctan2(self.R[k-1,1,0], self.R[k-1,0,0])\n\n new_scan = ScanICP(r)\n Ricp, Ticp = new_scan.icp_match(self.scans[-1])\n\n self.R[k,:,:] = np.dot(self.R[k-1,:,:], Ricp.T)\n self.T[k,:] = np.dot(self.R[k,:,:], Ticp.reshape(2,1)).flatten()\n\n self.pose = pose - self.T[k,:].flatten()\n head = wraptopi(head - np.arctan2(Ricp[1,0], Ricp[0,0]))\n self.traj = np.vstack((self.traj, self.pose))\n\n P_trans = np.dot(self.R[k,:,:], new_scan.P.T) - np.sum(self.T,0).reshape(2,1)\n\n self.x_pc = np.hstack((self.x_pc, P_trans[0,:]))\n self.y_pc = np.hstack((self.y_pc, P_trans[1,:]))\n\n self.scans.append(new_scan)\n\n return self.pose[0], self.pose[1], head\n" ]
[ [ "numpy.dot", "numpy.linspace", "numpy.arctan2", "numpy.max", "numpy.mean", "numpy.any", "numpy.random.randint", "numpy.hstack", "numpy.linalg.svd", "numpy.eye", "numpy.sin", "numpy.linalg.det", "numpy.copy", "sklearn.neighbors.NearestNeighbors", "numpy.zeros", "numpy.identity", "numpy.array", "numpy.sum", "numpy.cos", "numpy.ones", "numpy.mod", "numpy.vstack" ] ]
matteoacrossi/adapt_ic-povm
[ "1c9a0b4b98fafff478aed66686692ec97c0342ae" ]
[ "tomography_script.py" ]
[ "import pandas as pd\nimport numpy as np\nfrom qiskit import execute, Aer\nimport tomography.workinglib as wl\nimport tomography.likelihood_maximisation as lm\nimport networkx as nx\nimport tomography.hilbert_graph_tools as ht\nfrom povm.povm_operator import POVMOperator\nimport qiskit.quantum_info as qi\nimport itertools as it\n\nfrom pandarallel import pandarallel\n\n\ndef generate_all_povm_effects(povms, ids, k=2, order=\"Standard\"):\n\n obs = {}\n for kple in it.combinations(list(range(len(ids))), k):\n obs[kple] = {}\n for ijk in wl.create_labels_list(4, k):\n i = 0\n effect = povms[kple[k - i - 1]][int(ijk[0])]\n for e in ijk[1:]:\n i += 1\n if order == \"Standard\":\n effect = np.kron(povms[kple[k - i - 1]][int(e)], effect)\n else:\n effect = np.kron(effect, povms[kple[k - i - 1]][int(e)])\n obs[kple][ijk] = effect\n return obs\n\n\ndef merge_results(result, Nspins, k=2):\n marginals = {}\n observables = {}\n tot_shots = sum([res[\"shots_per_circuit\"] for res in result])\n for i, res in enumerate(result):\n\n # Compute all marginal distributions and k-qubit effects\n marginals_i = wl.compute_all_simplified_marginals(\n res[\"counts\"], range(Nspins), k=k\n )\n povms_i = POVMOperator(\n [(1, qi.Pauli(label=\"I\" * Nspins))],\n basis=None,\n atol=1e-12,\n name=None,\n povm_params=res[\"povm_params\"],\n ).povms\n # print(res['povm_params'])\n effects_i = generate_all_povm_effects(\n povms_i, range(Nspins), order=\"Qiskit\", k=k\n )\n\n for pair in marginals_i:\n if pair not in marginals:\n marginals[pair] = {}\n observables[pair] = {}\n for outcome in marginals_i[pair]:\n marginals[pair][str(i) + \"_\" + outcome] = marginals_i[pair][outcome]\n observables[pair][str(i) + \"_\" + outcome] = (\n effects_i[pair][outcome] * res[\"shots_per_circuit\"] / tot_shots\n )\n\n return marginals, observables\n\n\ndef concurrence_network_grad(simulation, exact, k=2):\n Nspins = int(np.log2(exact.get_statevector().shape))\n # Compute all marginal distributions and k-qubit effects\n marginals, observables = merge_results(simulation, Nspins, k=k)\n\n # Infer all pairwise states\n inferred_states = {}\n # concurrences = {}\n fidelities = {}\n for kple in marginals:\n inferred_states[kple] = qi.DensityMatrix(\n lm.infer_state(marginals, kple, observables[kple], tol=1e-6, maxiter=100)\n )\n if inferred_states[kple].is_valid():\n # concurrences[kple] = qi.concurrence(inferred_states[kple])\n exact_state = qi.partial_trace(\n exact.get_statevector(), [q for q in range(Nspins) if q not in kple]\n )\n fidelities[kple] = qi.state_fidelity(inferred_states[kple], exact_state)\n else:\n print(\"Warning: invalid state for\", kple)\n\n # print(fidelities)\n return np.mean(list(fidelities.values()))\n\n\ndef kwise_fidelity(x, k=2):\n try:\n data = concurrence_network_grad(\n x.to_dict(orient=\"records\"), x.iloc[0][\"exact_state\"], k=k\n )\n print(\"Done with\", x[\"qubits\"].iloc[0], x[\"method\"].iloc[0], x[\"id\"].iloc[0])\n except Exception as err:\n print(f'Problem with {x[\"id\"].iloc[0]}', err)\n print(x)\n data = None\n return data\n\n\nif __name__ == \"__main__\":\n pandarallel.initialize(nb_workers=20)\n\n hamiltonians_df = pd.DataFrame(pd.read_pickle(\"hamiltonians.pickle\"))\n\n df = pd.read_json(\"data/tomography_counts_data.jsonl\", lines=True)\n\n df = pd.merge(\n df,\n hamiltonians_df[[\"molecule\", \"mapping\", \"name\", \"vqe_circuit\"]],\n left_on=\"name\",\n right_on=\"name\",\n how=\"left\",\n sort=False,\n )\n\n df[\"exact_state\"] = df[\"vqe_circuit\"].apply(\n lambda x: execute(x, Aer.get_backend(\"statevector_simulator\")).result()\n )\n\n sample_df = df\n avg_fidelities_k = {}\n\n for k in range(2, 6):\n print(k)\n avg_fidelities_k[k] = sample_df.groupby(\n [\"qubits\", \"method\", \"id\"]\n ).parallel_apply(lambda x: kwise_fidelity(x, k))\n\n dfs = []\n for k in avg_fidelities_k:\n fid_df = pd.DataFrame(avg_fidelities_k[k], columns=[\"avg_fidelity\"])\n fid_df[\"k\"] = k\n dfs.append(fid_df)\n\n fid_df = pd.concat(dfs)\n\n fid_df[\"infidelity\"] = 1 - fid_df[\"avg_fidelity\"]\n\n filename = \"data/fidelities_tomo.json\"\n fid_df.reset_index().to_json(filename, orient=\"records\")\n print(\"Written to\", filename)\n" ]
[ [ "pandas.merge", "pandas.concat", "pandas.DataFrame", "pandas.read_json", "pandas.read_pickle" ] ]
DavidBert/N7-techno-IA
[ "a43105be602282ac3a564066ef588d46a7e4251f" ]
[ "code/developpement/train_mnist.py" ]
[ "import argparse\nfrom statistics import mean\n\nimport torch\nimport torchvision\nimport torchvision.transforms as transforms\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\nfrom torch.utils.tensorboard import SummaryWriter\nfrom tqdm import tqdm\n\nfrom mnist_net import MNISTNet\n#use it if you have module 'tensorflow._api.v2.io.gfile' has no attribute 'get_filesystem' error\n# import tensorflow as tf\n# import tensorboard as tb\n# tf.io.gfile = tb.compat.tensorflow_stub.io.gfile\n\n # setting device on GPU if available, else CPU\ndevice = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n\ndef train(net, optimizer, loader, epochs=10, writer=None):\n criterion = nn.CrossEntropyLoss()\n for epoch in range(epochs):\n running_loss = []\n t = tqdm(loader)\n for x, y in t:\n x, y = x.to(device), y.to(device)\n outputs = net(x)\n loss = criterion(outputs, y)\n running_loss.append(loss.item())\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n t.set_description(f'training loss: {mean(running_loss)}')\n if writer is not None:\n writer.add_scalar('training loss', mean(running_loss), epoch)\n\ndef test(model, dataloader):\n test_corrects = 0\n total = 0\n with torch.no_grad():\n for x, y in dataloader:\n x = x.to(device)\n y = y.to(device)\n y_hat = model(x).argmax(1)\n test_corrects += y_hat.eq(y).sum().item()\n total += y.size(0)\n return test_corrects / total\n\nif __name__=='__main__':\n#TODO remove exp_name and add batch_size\n parser = argparse.ArgumentParser()\n parser.add_argument('--exp_name', type=str, default = 'MNIST', help='experiment name')\n parser.add_argument('--batch_size', type=int, default = int(64), help='batch_size')\n parser.add_argument('--lr', type=float, default = float(1e-3), help='learning rate')\n parser.add_argument('--epochs', type=int, default = int(10), help='epochs')\n\n args = parser.parse_args()\n exp_name = args.exp_name\n batch_size = args.batch_size\n lr = args.lr\n epochs = args.epochs\n\n \n\n # transforms\n transform = transforms.Compose(\n [transforms.ToTensor(),\n transforms.Normalize((0.5,), (0.5,))])\n\n # datasets\n trainset = torchvision.datasets.MNIST('./data', download=True, train=True, transform=transform)\n testset = torchvision.datasets.MNIST('./data', download=True, train=False, transform=transform)\n\n # dataloaders\n trainloader = torch.utils.data.DataLoader(trainset, batch_size=batch_size, shuffle=True, num_workers=2)\n testloader = torch.utils.data.DataLoader(testset, batch_size=batch_size, shuffle=False, num_workers=2)\n\n net = MNISTNet().to(device)\n # default `log_dir` is \"runs\" - we'll be more specific here\n writer = SummaryWriter(f'runs/{exp_name}')\n \n optimizer = optim.SGD(net.parameters(), lr=lr, momentum=0.9)\n\n train(net, optimizer, trainloader, epochs, writer)\n test_acc = test(net, testloader)\n # for experiment management\n writer.add_hparams({'lr': lr, 'bsize': batch_size}, {'hparam/accuracy': test_acc}, run_name='MNIST')\n\n\n #add embeddings to tensorboard\n perm = torch.randperm(len(trainset.data))\n images, labels = trainset.data[perm][:256], trainset.targets[perm][:256]\n images = images.unsqueeze(1).float().to(device)\n with torch.no_grad():\n embeddings = net.get_features(images)\n writer.add_embedding(embeddings,\n metadata=labels,\n label_img=images, global_step=1)\n \n # save networks computational graph in tensorboard\n writer.add_graph(net, images)\n # save a dataset sample in tensorboard\n img_grid = torchvision.utils.make_grid(images[:64])\n writer.add_image('mnist_images', img_grid)\n torch.save(net.state_dict(), \"mnist_net.pth\")\n" ]
[ [ "torch.nn.CrossEntropyLoss", "torch.utils.data.DataLoader", "torch.no_grad", "torch.utils.tensorboard.SummaryWriter", "torch.cuda.is_available" ] ]
zlWang573/ggnnForSentimentTreebank
[ "351b6a0f34248c10116a7a49d88d651083df6fc7" ]
[ "utils/train.py" ]
[ "import torch\nimport torch.tensor\n\nfrom torch.autograd import Variable\n\ndef train(epoch, dataloader, net, criterion, optimizer, opt):\n net.train()\n \"\"\"\n 以下m_node为当前图节点数量\n lable为节点与子树上最远叶子节点距离,lable == 0为叶子节点\n lable并不参与运算,用于统计信息\n \"\"\"\n for i, (m_node, adj_matrix, annotation, lable, target) in enumerate(dataloader, 0): \n net.zero_grad()\n padding = torch.zeros(len(annotation), m_node, opt.state_dim - opt.annotation_dim).double()\n init_input = torch.cat((annotation, padding), 2)\n \n if opt.cuda:\n init_input = init_input.cuda()\n adj_matrix = adj_matrix.cuda()\n annotation = annotation.cuda()\n target = target.cuda()\n \n init_input = Variable(init_input)\n adj_matrix = Variable(adj_matrix)\n annotation = Variable(annotation)\n target = Variable(target)\n\n output = net(init_input, annotation, adj_matrix ,m_node)\n \n loss = criterion(output, target)\n loss.backward()\n optimizer.step()\n\n if i % int(len(dataloader) / 10 + 1) == 0 :\n print('[%d/%d][%d/%d] Loss: %.4f' % (epoch, opt.niter, i, len(dataloader), loss.data[0]))\n" ]
[ [ "torch.autograd.Variable", "torch.cat" ] ]
ydavidchen/pytorch_dl_challenge
[ "3feab77f6d40709805e3d2b94d5b50f4a1109c78" ]
[ "lessons_and_tutorials/02_intro_to_neuralnet/2.10_perceptron_algorithm.py" ]
[ "# Section 2.10: Perceptron algorithm\n\nimport numpy as np\n\nLEARN_RATE = 0.01;\nNUM_EPOCHS = 25;\nSEED = 42;\n\nnp.random.seed(SEED)\n\ndef stepFunction(t):\n if t >= 0: return 1\n return 0\n\ndef prediction(X, W, b):\n pred = stepFunction((np.matmul(X,W)+b)[0]);\n return pred;\n\ndef perceptronStep(X, y, W, b, learn_rate=LEARN_RATE):\n # TODO: Fill in the code below to implement the perceptron trick.\n # The function should receive as inputs the data X, the labels y,\n # the weights W (as an array), and the bias b,\n # update the weights and bias W, b, according to the perceptron algorithm,\n # and return W and b.\n ### Fill in code ###\n for i in range(len(X)):\n y_hat = prediction(X[i], W, b);\n\n if y[i] - y_hat == 1:\n W[0] += X[i][0] * learn_rate;\n W[1] += X[i][1] * learn_rate;\n b += learn_rate;\n\n elif y[i] - y_hat == -1:\n W[0] -= X[i][0] * learn_rate;\n W[1] -= X[i][1] * learn_rate;\n b -= learn_rate;\n\n return W, b\n\ndef trainPerceptronAlgorithm(X, y, learn_rate=LEARN_RATE, num_epochs=NUM_EPOCHS):\n # This function runs the perceptron algorithm repeatedly on the dataset,\n # and returns a few of the boundary lines obtained in the iterations,\n # for plotting purposes.\n # Feel free to play with the learning rate and the num_epochs,\n # and see your results plotted below.\n x_min, x_max = min(X.T[0]), max(X.T[0])\n y_min, y_max = min(X.T[1]), max(X.T[1])\n W = np.array(np.random.rand(2,1))\n b = np.random.rand(1)[0] + x_max\n # These are the solution lines that get plotted below:\n boundary_lines = []\n for i in range(num_epochs):\n # In each epoch, we apply the perceptron step.\n W, b = perceptronStep(X, y, W, b, learn_rate)\n boundary_lines.append((-W[0]/W[1], -b/W[1]))\n return boundary_lines\n" ]
[ [ "numpy.matmul", "numpy.random.rand", "numpy.random.seed" ] ]
SakshayMahna/Robotics-Mechanics
[ "3fa4b5860c4c9b4e22bd8799c0edc08237707aef" ]
[ "Part-12-RobotJacobian/tests/test_transformations.py" ]
[ "\"\"\"\nUnit Testing Rigid Body Transformations\n\"\"\"\n\nimport unittest\nimport numpy as np\nfrom tools.transformations import *\n\nclass TestTransformations(unittest.TestCase):\n\n def test_transl(self):\n x = 1\n y = 2\n z = 3\n\n transformation = transl(x, y, z)\n actual_transformation = np.array([[1, 0, 0, 1],\n [0, 1, 0, 2],\n [0, 0, 1, 3],\n [0, 0, 0, 1]])\n\n np.testing.assert_almost_equal(actual_transformation, transformation)\n\n def test_rpy2tr(self):\n roll = np.pi / 3\n yaw = np.pi / 3\n pitch = np.pi / 3\n\n transformation = rpy2tr(roll, pitch, yaw)\n actual_transformation = np.array([[0.2500, -0.0580, 0.9665, 0],\n [0.4330, 0.8995, -0.0580, 0],\n [-0.8660, 0.4330, 0.2500, 0],\n [0, 0, 0, 1.0000]])\n\n np.testing.assert_almost_equal(actual_transformation, transformation, \n decimal = 4)\n\n def test_tr2rpy(self):\n transformation = np.array([[0.2500, -0.0580, 0.9665, 0],\n [0.4330, 0.8995, -0.0580, 0],\n [-0.8660, 0.4330, 0.2500, 0],\n [0, 0, 0, 1.0000]])\n \n r, p, y = tr2rpy(transformation)\n angles = np.array([r, p, y])\n actual_angles = np.array([np.pi / 3, np.pi / 3, np.pi / 3])\n\n np.testing.assert_almost_equal(actual_angles, angles, decimal = 4)\n\n def test_rot(self):\n rotation_x = rotx(np.pi/3)\n rotation_y = roty(np.pi/3)\n rotation_z = rotz(np.pi/3)\n\n actual_rotation_x = np.array([[1.0000, 0, 0],\n [0, 0.5000, -0.8660],\n [0, 0.8660, 0.5000]])\n actual_rotation_y = np.array([[0.5000, 0, 0.8660],\n [0, 1.0000, 0],\n [-0.8660, 0, 0.5000]]) \n actual_rotation_z = np.array([[0.5000, -0.8660, 0],\n [0.8660, 0.5000, 0],\n [0, 0, 1.0000]])\n\n np.testing.assert_almost_equal(actual_rotation_z, rotation_z, decimal = 4)\n np.testing.assert_almost_equal(actual_rotation_y, rotation_y, decimal = 4)\n np.testing.assert_almost_equal(actual_rotation_x, rotation_x, decimal = 4) \n" ]
[ [ "numpy.testing.assert_almost_equal", "numpy.array" ] ]
anandkamat05/TDEOC
[ "11749457c3a7550e11ba1acc4784e8545f8087aa" ]
[ "baselines/common/atari_wrappers.py" ]
[ "import numpy as np\nfrom collections import deque\nimport gym\nfrom gym import spaces\nimport cv2\n\nclass NoopResetEnv(gym.Wrapper):\n def __init__(self, env, noop_max=30):\n \"\"\"Sample initial states by taking random number of no-ops on reset.\n No-op is assumed to be action 0.\n \"\"\"\n gym.Wrapper.__init__(self, env)\n self.noop_max = noop_max\n self.override_num_noops = None\n self.noop_action = 0\n assert env.unwrapped.get_action_meanings()[0] == 'NOOP'\n\n def _reset(self, **kwargs):\n \"\"\" Do no-op action for a number of steps in [1, noop_max].\"\"\"\n self.env.reset(**kwargs)\n if self.override_num_noops is not None:\n noops = self.override_num_noops\n else:\n noops = self.unwrapped.np_random.randint(1, self.noop_max + 1) #pylint: disable=E1101\n assert noops > 0\n obs = None\n for _ in range(noops):\n obs, _, done, _ = self.env.step(self.noop_action)\n if done:\n obs = self.env.reset(**kwargs)\n return obs\n\nclass FireResetEnv(gym.Wrapper):\n def __init__(self, env):\n \"\"\"Take action on reset for environments that are fixed until firing.\"\"\"\n gym.Wrapper.__init__(self, env)\n assert env.unwrapped.get_action_meanings()[1] == 'FIRE'\n assert len(env.unwrapped.get_action_meanings()) >= 3\n\n def _reset(self, **kwargs):\n self.env.reset(**kwargs)\n obs, _, done, _ = self.env.step(1)\n if done:\n self.env.reset(**kwargs)\n obs, _, done, _ = self.env.step(2)\n if done:\n self.env.reset(**kwargs)\n return obs\n\nclass EpisodicLifeEnv(gym.Wrapper):\n def __init__(self, env):\n \"\"\"Make end-of-life == end-of-episode, but only reset on true game over.\n Done by DeepMind for the DQN and co. since it helps value estimation.\n \"\"\"\n gym.Wrapper.__init__(self, env)\n self.lives = 0\n self.was_real_done = True\n\n def step(self, action):\n obs, reward, done, info = self.env.step(action)\n self.was_real_done = done\n # check current lives, make loss of life terminal,\n # then update lives to handle bonus lives\n lives = self.env.unwrapped.ale.lives()\n if lives < self.lives and lives > 0:\n # for Qbert sometimes we stay in lives == 0 condtion for a few frames\n # so its important to keep lives > 0, so that we only reset once\n # the environment advertises done.\n done = True\n self.lives = lives\n return obs, reward, done, info\n\n def _reset(self, **kwargs):\n \"\"\"Reset only when lives are exhausted.\n This way all states are still reachable even though lives are episodic,\n and the learner need not know about any of this behind-the-scenes.\n \"\"\"\n if self.was_real_done:\n obs = self.env.reset(**kwargs)\n else:\n # no-op step to advance from terminal/lost life state\n obs, _, _, _ = self.env.step(0)\n self.lives = self.env.unwrapped.ale.lives()\n return obs\n\nclass MaxAndSkipEnv(gym.Wrapper):\n def __init__(self, env, skip=4):\n \"\"\"Return only every `skip`-th frame\"\"\"\n gym.Wrapper.__init__(self, env)\n # most recent raw observations (for max pooling across time steps)\n self._obs_buffer = np.zeros((2,)+env.observation_space.shape, dtype='uint8')\n self._skip = skip\n\n def step(self, action):\n \"\"\"Repeat action, sum reward, and max over last observations.\"\"\"\n total_reward = 0.0\n done = None\n for i in range(self._skip):\n obs, reward, done, info = self.env.step(action)\n if i == self._skip - 2: self._obs_buffer[0] = obs\n if i == self._skip - 1: self._obs_buffer[1] = obs\n total_reward += reward\n if done:\n break\n # Note that the observation on the done=True frame\n # doesn't matter\n max_frame = self._obs_buffer.max(axis=0)\n\n return max_frame, total_reward, done, info\n\nclass ClipRewardEnv(gym.RewardWrapper):\n def _reward(self, reward):\n \"\"\"Bin reward to {+1, 0, -1} by its sign.\"\"\"\n return np.sign(reward)\n\nclass WarpFrame(gym.ObservationWrapper):\n def __init__(self, env):\n \"\"\"Warp frames to 84x84 as done in the Nature paper and later work.\"\"\"\n gym.ObservationWrapper.__init__(self, env)\n self.width = 84\n self.height = 84\n self.observation_space = spaces.Box(low=0, high=255, shape=(self.height, self.width, 1))\n\n def _observation(self, frame):\n frame = cv2.cvtColor(frame, cv2.COLOR_RGB2GRAY)\n frame = cv2.resize(frame, (self.width, self.height), interpolation=cv2.INTER_AREA)\n return frame[:, :, None]\n\nclass FrameStack(gym.Wrapper):\n def __init__(self, env, k):\n \"\"\"Stack k last frames.\n\n Returns lazy array, which is much more memory efficient.\n\n See Also\n --------\n baselines.common.atari_wrappers.LazyFrames\n \"\"\"\n gym.Wrapper.__init__(self, env)\n self.k = k\n self.frames = deque([], maxlen=k)\n shp = env.observation_space.shape\n self.observation_space = spaces.Box(low=0, high=255, shape=(shp[0], shp[1], shp[2] * k))\n\n def _reset(self):\n ob = self.env.reset()\n for _ in range(self.k):\n self.frames.append(ob)\n return self._get_ob()\n\n def step(self, action):\n ob, reward, done, info = self.env.step(action)\n self.frames.append(ob)\n return self._get_ob(), reward, done, info\n\n def _get_ob(self):\n assert len(self.frames) == self.k\n return LazyFrames(list(self.frames))\n\nclass ScaledFloatFrame(gym.ObservationWrapper):\n def _observation(self, observation):\n # careful! This undoes the memory optimization, use\n # with smaller replay buffers only.\n return np.array(observation).astype(np.float32) / 255.0\n\nclass LazyFrames(object):\n def __init__(self, frames):\n \"\"\"This object ensures that common frames between the observations are only stored once.\n It exists purely to optimize memory usage which can be huge for DQN's 1M frames replay\n buffers.\n\n This object should only be converted to numpy array before being passed to the model.\n\n You'd not believe how complex the previous solution was.\"\"\"\n self._frames = frames\n\n def __array__(self, dtype=None):\n out = np.concatenate(self._frames, axis=2)\n if dtype is not None:\n out = out.astype(dtype)\n return out\n\ndef make_atari(env_id):\n env = gym.make(env_id)\n assert 'NoFrameskip' in env.spec.id\n env = NoopResetEnv(env, noop_max=30)\n env = MaxAndSkipEnv(env, skip=4)\n return env\n\ndef wrap_deepmind(env, episode_life=True, clip_rewards=True, frame_stack=False, scale=False):\n \"\"\"Configure environment for DeepMind-style Atari.\n \"\"\"\n if episode_life:\n env = EpisodicLifeEnv(env)\n if 'FIRE' in env.unwrapped.get_action_meanings():\n env = FireResetEnv(env)\n env = WarpFrame(env)\n if scale:\n env = ScaledFloatFrame(env)\n if clip_rewards:\n env = ClipRewardEnv(env)\n if frame_stack:\n env = FrameStack(env, 4)\n return env\n\n" ]
[ [ "numpy.sign", "numpy.array", "numpy.zeros", "numpy.concatenate" ] ]
kotania/impy
[ "85ddd5764a3c1f955fae8d1b9422b619d4d12a4d" ]
[ "impy/kinematics.py" ]
[ "\"\"\" This module handles transformations between Lorentz frames and\ndifferent inputs required by the low-level event generator interfaces.\n\n\n@Hans @Sonia: we need to come up with some sort general handling\nof different inputs. Hans suggested to mimic a similar behavior as for\ncolors in matplotlib. That one can initialize with different arguments, like\n'pp' 7 TeV would be internally translated to 2212, 2212 and to 4-vectors\n[0.,0.,+-3.499999TeV, 3.5TeV]. This assumes that the input interpreted as\ncenter of mass total energy (not momentum) AND that the final state is\ndefined in center-of-mass as well.\n\nThis was already the initial motivation but I have the impression that\nthe implementation is very \"cooked up\". We have to discuss this.\n\n\"\"\"\n\nimport six\nimport numpy as np\nfrom impy import pdata, impy_config\nfrom impy.util import info\n\n\nclass CompositeTarget(object):\n \"\"\"Definition of composite targets made of multiple (atomic) nuclei.\n\n Examples of such composite targets are Air, CO_2, HCl, C_2H_60.\n \"\"\"\n def __init__(self, label=''):\n self.label = label\n self.ncomponents = 0\n self.component_fractions = []\n self._component_orig_fractions = []\n self.component_A = []\n self.component_Z = []\n self.component_name = []\n\n def add_component(self, name, A, Z, fraction):\n \"\"\"Add material for composite target.\n\n Fraction needs relative specification, in percent, number,\n fraction of one, etc. Just make sure it's the same definition\n for all components. Internal list is sorted according to\n relative fractions.\n \"\"\"\n\n self.component_name.append(name)\n self.component_A.append(A)\n self.component_Z.append(Z)\n self._component_orig_fractions.append(float(fraction))\n self.component_fractions = np.array([\n f / np.sum(self._component_orig_fractions)\n for f in self._component_orig_fractions\n ])\n self.ncomponents += 1\n\n self._sort()\n\n assert (len(self.component_name) == len(self.component_A) == len(\n self.component_Z) == len(self.component_fractions) == len(\n self._component_orig_fractions))\n assert np.sum(self.component_fractions) == 1.\n\n def _sort(self):\n \"\"\"Sorts list acording to fraction\"\"\"\n def sort_list(l, idcs):\n return [l[i] for i in idcs]\n\n idcs = np.argsort(self.component_fractions)\n self.component_fractions = self.component_fractions[idcs]\n self._component_orig_fractions = sort_list(\n self._component_orig_fractions, idcs)\n self.component_A = sort_list(self.component_A, idcs)\n self.component_Z = sort_list(self.component_Z, idcs)\n self.component_name = sort_list(self.component_name, idcs)\n\n def get_random_AZ(self):\n \"\"\"Return randomly an (A, Z) tuple according to the component fraction.\"\"\"\n from numpy.random import choice\n\n ic = choice(self.ncomponents, 1, p=self.component_fractions)\n return self.component_A[ic], self.component_Z[ic]\n\n def __repr__(self):\n ostr = \"Composite target '\" + self.label + \"' \\n\"\n\n ostr += \"Average mass: {0:4.1f}\\n\".format(\n np.sum([\n A * f\n for A, f in zip(self.component_A, self.component_fractions)\n ]))\n\n ostr += \" Nr | Name | A | Z | fraction\\n\"\n templ = \" {0:3} | {1:10s} |{2:4} |{3:4} | {4:3.2f}\\n\"\n for i in range(self.ncomponents):\n ostr += templ.format(i, self.component_name[i],\n self.component_A[i], self.component_Z[i],\n self.component_fractions[i])\n\n return ostr\n\n\nclass EventKinematics(object):\n \"\"\"Handles kinematic variables and conversions between reference frames.\n\n There are different ways to specify a particle collision. For instance\n the projectile and target momenta can be specified in the target rest frame,\n the so called 'laboratory' frame, or the nucleon-nucleon center of mass frame\n where the modulus of the nucleon momenta is the same but the direction\n inverted. Each event generator expects its arguments to be given in one\n or the other frame. This class allows the generator to pick itself the correct\n frame, while the user can specify the kinematics in the preferred form.\n\n Args:\n (float) ecm : :math:`\\\\sqrt{s}`, the center-of-mass energy\n (float) plab : projectile momentum in lab frame\n (float) elab : projectile energy in lab frame\n (float) ekin : projectile kinetic energy in lab frame\n (float) p1pdg : PDG ID of the projectile\n (float) p2pdg : PDG ID of the target\n (tuple) beam : Specification as tuple of 4-vectors (np.array)s\n (tuple) nuc1prop : Projectile nucleus mass & charge (A, Z)\n (tuple) nuc2prop : Target nucleus mass & charge (A, Z)\n\n \"\"\"\n def __init__(self,\n ecm=None,\n plab=None,\n elab=None,\n ekin=None,\n p1pdg=None,\n p2pdg=None,\n beam=None,\n nuc1_prop=None,\n nuc2_prop=None):\n\n # Catch input errors\n assert np.sum(np.asarray(\n [ecm, plab, elab, ekin, beam], dtype='bool')) == 1, (\n 'Define exclusively one energy/momentum definition')\n assert p1pdg or nuc1_prop, ('Define either particle id or ' +\n 'nuclear properties for side 1.')\n assert p2pdg or nuc2_prop, ('Define either particle id or ' +\n 'nuclear properties for side 2.')\n assert nuc1_prop is None or (isinstance(nuc1_prop, tuple)\n and len(nuc1_prop) == 2), (\n 'Define nuc1_prop as an (A,Z) tuple.')\n assert nuc2_prop is None or (isinstance(nuc2_prop, tuple)\n and len(nuc2_prop) == 2), (\n 'Define nuc2_prop as an (A,Z) tuple.')\n\n # Store average nucleon mass\n mnuc = 0.5 * (pdata.mass(2212) + pdata.mass(2112))\n\n # Handle projectile type\n if p1pdg:\n pmass1 = pdata.mass(p1pdg)\n self.A1 = 1\n self.Z1 = pdata.charge(p1pdg)\n self.p1pdg = p1pdg\n self.p1_is_nucleus = False\n info(20, 'Particle 1 identified from PDG ID.')\n else:\n pmass1 = mnuc\n self.p1pdg = 2212\n self.A1, self.Z1 = nuc1_prop\n self.p1_is_nucleus = True if self.A1 > 1 else False\n if self.A1 == 1 and self.Z1 == 0:\n self.p1pdg = 2212\n info(20, 'Particle 1 is a nucleus.')\n\n # Handle target type\n if p2pdg:\n pmass2 = pdata.mass(p2pdg)\n self.p2pdg = p2pdg\n self.A2 = 1\n self.Z2 = pdata.charge(p2pdg)\n self.p2_is_nucleus = False\n info(20, 'Particle 2 identified from PDG ID.')\n else:\n pmass2 = mnuc\n self.p2pdg = 2212\n self.A2, self.Z2 = nuc2_prop\n self.p2_is_nucleus = True if self.A2 > 1 else False\n if self.A2 == 1 and self.Z2 == 0:\n self.p2pdg = 2112\n info(20, 'Particle 2 is a nucleus.')\n\n info(10, 'Proj. and targ. identified', (self.p1pdg, self.A1, self.Z1),\n (self.p2pdg, self.A2, self.Z2))\n\n # Input specification in center of mass frame\n if ecm:\n self.ecm = ecm\n self.elab = 0.5 * (ecm**2 - pmass1**2 - pmass2**2) / pmass2\n self.plab = self._e2p(self.elab, pmass1)\n info(20, 'ecm specified.')\n # Input specification in lab frame\n elif elab:\n assert elab > pmass1, 'Lab. energy > particle mass required.'\n self.elab = elab\n self.plab = self._e2p(self.elab, pmass1)\n self.ecm = np.sqrt(2. * self.elab * pmass2 + pmass2**2 + pmass1**2)\n # self.ecm = np.sqrt((self.elab + pmass2)**2 - self.plab**2)\n info(20, 'elab specified.')\n elif ekin:\n self.elab = ekin + pmass1\n self.plab = self._e2p(self.elab, pmass1)\n self.ecm = np.sqrt(2. * self.elab * pmass2 + pmass2**2 + pmass1**2)\n # self.ecm = np.sqrt((self.elab + pmass2)**2 - self.plab**2)\n info(20, 'ekin specified.')\n elif plab:\n self.plab = plab\n self.elab = np.sqrt(plab**2 + pmass1**2)\n self.ecm = np.sqrt(2. * self.elab * pmass2 + pmass2**2 + pmass1**2)\n # self.ecm = np.sqrt((self.elab + pmass2)**2 - self.plab**2)\n info(20, 'plab specified.')\n\n # Input specification as 4-vectors\n elif beam:\n p1, p2 = beam\n s = p1 + p2\n self.ecm = np.sqrt(s[3]**2 - np.sum(s[:3]**2))\n self.elab = 0.5 * (self.ecm**2 - pmass1**2 + pmass2**2) / pmass2\n self.plab = self._e2p(self.elab, pmass1)\n info(20, 'beam spec: beam, ecms, elab, plab', beam, self.ecm,\n self.elab, self.plab)\n else:\n raise Exception(self.__class__.__name__ +\n '::init(): Define at least ecm or plab')\n\n self.pmass1 = pmass1\n self.pmass2 = pmass2\n\n # compute center-of-mass variables\n s = self.ecm**2\n self.s = s\n self.pcm = np.sqrt(s**2 - 2 * (s *\n (pmass1 + pmass2) + pmass1 * pmass2) +\n pmass1**2 + pmass2**2) / (2 * self.ecm)\n self.gamma_cm = (self.elab + pmass2) / self.ecm\n self.betagamma_z_cm = self.plab / self.ecm\n\n self.boost_def = {\n (\"center-of-mass\", \"laboratory\"): self.boost_cms_to_lab,\n (\"laboratory\", \"center-of-mass\"): self.boost_lab_to_cms\n }\n\n # self.e_range = []\n\n @property\n def beam_as_4vec(self):\n \"\"\"Return the projectile target kinematics as 4-vectors. Can be used\n for PHOJET and PYTHIA.\"\"\"\n\n p1, p2 = np.array(np.zeros(4), dtype='d'), np.array(np.zeros(4),\n dtype='d')\n p1[0] = 0.0\n p1[1] = 0.0\n p1[2] = self.pcm\n p1[3] = self.ecm / 2.\n p2[0] = 0.0\n p2[1] = 0.0\n p2[2] = -self.pcm\n p2[3] = self.ecm / 2.\n\n return p1, p2\n\n def _e2p(self, E, m):\n return np.sqrt((E + m) * (E - m))\n\n def __getstate__(self):\n if 'boost_def' in self.__dict__:\n _ = self.__dict__.pop('boost_def')\n return self.__dict__\n\n def __setstate__(self, state):\n self.__dict__ = state\n self.boost_def = {\n (\"center-of-mass\", \"laboratory\"): self.boost_cms_to_lab,\n (\"laboratory\", \"center-of-mass\"): self.boost_lab_to_cms\n }\n\n def __ne__(self, other):\n for key, value in six.iteritems(other.__dict__):\n if key == 'boost_def':\n continue\n if value != self.__dict__[key]:\n return True\n\n return False\n\n def __eq__(self, other):\n return not self.__ne__(other)\n\n def __hash__(self):\n return hash('_'.join([\n '{0}_{1}'.format(key, self.__dict__[key])\n for key in sorted(self.__dict__.keys())\n ]))\n\n def __le__(self, other):\n return self.ecm < other.ecm\n\n def __ge__(self, other):\n return self.ecm > other.ecm\n\n def __repr__(self):\n ostr = 'Event kinematics:\\n'\n ostr += '\\tecm : {0:10.5f}\\n'.format(self.ecm)\n ostr += '\\tpcm : {0:10.5f}\\n'.format(self.pcm)\n ostr += '\\telab : {0:10.5f}\\n'.format(self.elab)\n ostr += '\\tplab : {0:10.5f}\\n'.format(self.plab)\n ostr += '\\tgamma_cm : {0:10.5f}\\n'.format(self.gamma_cm)\n ostr += '\\tbgamm_cm : {0:10.5f}\\n'.format(self.betagamma_z_cm)\n ostr += '\\tpdgid 1 : {0:10}\\n'.format(self.p1pdg)\n ostr += '\\tnucprop 1: {0}/{1}\\n'.format(self.A1, self.Z1)\n ostr += '\\tpdgid 2 : {0:10}\\n'.format(self.p2pdg)\n ostr += '\\tnucprop 2: {0}/{1}\\n'.format(self.A2, self.Z2)\n\n return ostr\n\n def apply_boost(self, event, gen_frame, user_frame):\n if (gen_frame, user_frame) not in self.boost_def:\n info(20, 'FS boost not applicable', gen_frame, '->', user_frame)\n return\n info(20, 'Boosting FS', gen_frame, '->', user_frame)\n self.boost_def[(gen_frame, user_frame)](event)\n\n def boost_cms_to_lab(self, event):\n \"\"\"Boosts from center of mass to lab frame.\n\n Viewed from the target rest frame the center of mass frame\n is moving backwards.\n \"\"\"\n new_en = self.gamma_cm * event.en + self.betagamma_z_cm * event.pz\n event.pz = self.betagamma_z_cm * event.en + self.gamma_cm * event.pz\n event.en = new_en\n\n def boost_lab_to_cms(self, event):\n \"\"\"Boosts from lab to center of mass frame\n\n Viewed from the target rest frame the center of mass frame\n is moving backwards.\n \"\"\"\n new_en = self.gamma_cm * event.en - self.betagamma_z_cm * event.pz\n event.pz = -self.betagamma_z_cm * event.en + self.gamma_cm * event.pz\n event.en = new_en\n" ]
[ [ "numpy.sqrt", "numpy.random.choice", "numpy.asarray", "numpy.argsort", "numpy.zeros", "numpy.sum" ] ]
patel-zeel/lab
[ "cc0df2c03196863041e78fa4179445341e86958c" ]
[ "tests/util.py" ]
[ "import logging\nfrom itertools import product\n\nimport jax.numpy as jnp\nimport numpy as np\nimport plum\nimport pytest\nimport tensorflow as tf\nimport torch\nfrom autograd.core import VJPNode, getval\nfrom autograd.tracer import trace_stack, new_box\nfrom plum import Dispatcher, Union\n\nimport lab as B\nfrom lab.shape import Shape, Dimension, unwrap_dimension\n\n__all__ = [\n \"check_lazy_shapes\",\n \"autograd_box\",\n \"to_np\",\n \"approx\",\n \"check_function\",\n \"Tensor\",\n \"PositiveTensor\",\n \"ComplexTensor\",\n \"BoolTensor\",\n \"NaNTensor\",\n \"Matrix\",\n \"PSD\",\n \"PSDTriangular\",\n \"Tuple\",\n \"List\",\n \"Value\",\n \"Bool\",\n]\n\nlog = logging.getLogger(\"lab.\" + __name__)\n\n_dispatch = Dispatcher()\n\n\n@pytest.fixture(params=[False, True])\ndef check_lazy_shapes(request):\n if request.param:\n with B.lazy_shapes():\n yield\n else:\n yield\n\n\ndef autograd_box(x):\n \"\"\"Box a tensor in AutoGrad.\"\"\"\n t = trace_stack.new_trace().__enter__()\n n = VJPNode.new_root()\n return new_box(x, t, n)\n\n\n@_dispatch(precedence=1)\ndef to_np(x: Union[B.NPNumeric, B.Number]):\n \"\"\"Convert a tensor to NumPy.\"\"\"\n return x\n\n\n@_dispatch\ndef to_np(x: Dimension):\n return unwrap_dimension(x)\n\n\n@_dispatch\ndef to_np(x: B.AGNumeric):\n return getval(x)\n\n\n@_dispatch\ndef to_np(x: Union[B.TorchNumeric, B.TFNumeric]):\n return x.numpy()\n\n\n@_dispatch\ndef to_np(x: B.JAXNumeric):\n return np.array(x)\n\n\n@_dispatch\ndef to_np(tup: Union[tuple, tf.TensorShape, torch.Size, Shape]):\n return tuple(to_np(x) for x in tup)\n\n\n@_dispatch\ndef to_np(lst: list):\n return to_np(tuple(lst))\n\n\n@_dispatch\ndef approx(x, y, assert_dtype: bool = False, **kw_args):\n \"\"\"Assert that two numeric objects are close.\"\"\"\n x, y = to_np(x), to_np(y)\n\n # Assert that data types are equal if required.\n if assert_dtype:\n dtype_x = np.array(x).dtype\n dtype_y = np.array(y).dtype\n if dtype_x != dtype_y:\n raise AssertionError(\n f\"Data types not equal: `{dtype_x}` versus `{dtype_y}`.\"\n )\n\n np.testing.assert_allclose(x, y, **kw_args)\n\n\n@_dispatch\ndef approx(x: tuple, y: tuple, assert_dtype: bool = False, **kw_args):\n assert len(x) == len(y)\n for xi, yi in zip(x, y):\n approx(xi, yi, assert_dtype=assert_dtype, **kw_args)\n\n\ndef check_function(\n f,\n args_spec,\n kw_args_spec=None,\n assert_dtype=True,\n skip=None,\n contains_nans=None,\n):\n \"\"\"Check that a function produces consistent output. Moreover, if the first\n argument is a data type, check that the result is exactly of that type.\"\"\"\n skip = [] if skip is None else skip\n\n if kw_args_spec is None:\n kw_args_spec = {}\n\n # Construct product of keyword arguments.\n kw_args_prod = list(\n product(*[[(k, v) for v in vs.forms()] for k, vs in kw_args_spec.items()])\n )\n kw_args_prod = [{k: v for k, v in kw_args} for kw_args in kw_args_prod]\n\n # Add default call.\n kw_args_prod += [{}]\n\n # Construct product of arguments.\n args_prod = list(product(*[arg.forms() for arg in args_spec]))\n\n # Construct framework types to skip mixes of.\n fw_types = [\n plum.Union(t, plum.List(t), plum.Tuple(t))\n for t in [B.AGNumeric, B.TorchNumeric, B.TFNumeric, B.JAXNumeric]\n ]\n\n # Construct other types to skip entirely.\n skip_types = [plum.Union(t, plum.List(t), plum.Tuple(t)) for t in skip]\n\n # Check consistency of results.\n for kw_args in kw_args_prod:\n # Compare everything against the first result.\n first_result = f(*args_prod[0], **kw_args)\n\n # If first argument is a data type, then check that.\n if isinstance(args_prod[0][0], B.DType):\n assert B.dtype(first_result) is args_prod[0][0]\n\n for args in args_prod:\n # Skip mixes of FW types.\n fw_count = sum([any(isinstance(arg, t) for arg in args) for t in fw_types])\n\n # Skip all skips.\n skip_count = sum(\n [any(isinstance(arg, t) for arg in args) for t in skip_types]\n )\n\n if fw_count >= 2 or skip_count >= 1:\n log.debug(\n f\"Skipping call with arguments {args} and keyword \"\n f\"arguments {kw_args}.\"\n )\n continue\n\n # Check consistency.\n log.debug(f\"Call with arguments {args} and keyword arguments {kw_args}.\")\n result = f(*args, **kw_args)\n approx(first_result, result, assert_dtype=assert_dtype)\n\n # If first argument is a data type, then again check that.\n if isinstance(args[0], B.DType):\n assert B.dtype(result) is args[0]\n\n # Check NaNs.\n if contains_nans is not None:\n assert B.any(B.isnan(result)) == contains_nans\n\n\nclass Tensor:\n \"\"\"Tensor placeholder.\"\"\"\n\n def __init__(self, *dims, **kw_args):\n if \"mat\" not in kw_args or kw_args[\"mat\"] is None:\n self.mat = np.array(np.random.randn(*dims))\n else:\n self.mat = kw_args[\"mat\"]\n\n def forms(self):\n return [self.np(), self.tf(), self.torch(), self.ag(), self.jax()]\n\n def np(self):\n return self.mat\n\n def tf(self):\n return tf.constant(self.mat)\n\n def torch(self):\n return torch.tensor(self.mat)\n\n def ag(self):\n return autograd_box(self.mat)\n\n def jax(self):\n return jnp.array(self.mat)\n\n\nclass PositiveTensor(Tensor):\n \"\"\"Positive tensor placeholder.\"\"\"\n\n def __init__(self, *dims, upper=1, **kw_args):\n if \"mat\" not in kw_args or kw_args[\"mat\"] is None:\n mat = np.array(upper * np.random.rand(*dims))\n else:\n mat = kw_args[\"mat\"]\n Tensor.__init__(self, mat=mat)\n\n\nclass ComplexTensor(Tensor):\n \"\"\"Complex tensor placeholder.\"\"\"\n\n def __init__(self, *dims, **kw_args):\n if \"mat\" not in kw_args or kw_args[\"mat\"] is None:\n mat = np.array(np.random.randn(*dims), dtype=np.complex128)\n else:\n mat = kw_args[\"mat\"]\n Tensor.__init__(self, mat=mat)\n\n\nclass BoolTensor(Tensor):\n \"\"\"Boolean tensor placeholder.\"\"\"\n\n def __init__(self, *dims, **kw_args):\n if \"mat\" not in kw_args or kw_args[\"mat\"] is None:\n mat = np.array(np.random.rand(*dims) > 0.5)\n else:\n mat = kw_args[\"mat\"]\n Tensor.__init__(self, mat=mat)\n\n def torch(self):\n return torch.tensor(self.mat.astype(np.uint8))\n\n\nclass NaNTensor(Tensor):\n \"\"\"Tensor containing NaNs placeholder.\"\"\"\n\n def __init__(self, *dims, **kw_args):\n if \"mat\" not in kw_args or kw_args[\"mat\"] is None:\n mat = np.array(np.random.randn(*dims))\n if len(dims) > 0:\n # Checkboard from https://stackoverflow.com/q/2169478.\n checkerboard = np.indices(dims).sum(axis=0) % 2\n mat[checkerboard == 1] = np.nan\n else:\n mat = kw_args[\"mat\"]\n Tensor.__init__(self, mat=mat)\n\n\nclass Matrix(Tensor):\n \"\"\"Matrix placeholder.\"\"\"\n\n def __init__(self, *shape, **kw_args):\n # Handle shorthands.\n if shape == ():\n shape = (3, 3)\n elif len(shape) == 1:\n shape = shape * 2\n\n Tensor.__init__(self, *shape, **kw_args)\n\n\nclass PSD(Matrix):\n \"\"\"Positive-definite tensor placeholder.\"\"\"\n\n def __init__(self, *shape):\n # Handle shorthands.\n if shape == ():\n shape = (3, 3)\n elif len(shape) == 1:\n shape = shape * 2\n\n if not shape[-2] == shape[-1]:\n raise ValueError(\"PSD matrix must be square.\")\n\n a = np.random.randn(*shape)\n perm = list(range(len(a.shape)))\n perm[-2], perm[-1] = perm[-1], perm[-2]\n a_t = np.transpose(a, perm)\n Matrix.__init__(self, mat=np.matmul(a, a_t))\n\n\nclass PSDTriangular(PSD):\n def __init__(self, *shape, **kw_args):\n PSD.__init__(self, *shape)\n\n # Zero upper triangular part.\n for i in range(self.mat.shape[0]):\n for j in range(i + 1, self.mat.shape[1]):\n self.mat[..., i, j] = 0\n\n # Create upper-triangular matrices, if asked for.\n if kw_args.get(\"upper\", False):\n perm = list(range(len(self.mat.shape)))\n perm[-2], perm[-1] = perm[-1], perm[-2]\n self.mat = np.transpose(self.mat, perm)\n\n\nclass Tuple:\n \"\"\"Tuple placeholder.\"\"\"\n\n def __init__(self, *xs):\n self.xs = xs\n\n def forms(self):\n return map(tuple, zip(*(x.forms() for x in self.xs)))\n\n\nclass List:\n \"\"\"List placeholder for in argument specification.\"\"\"\n\n def __init__(self, *xs):\n self.xs = xs\n\n def forms(self):\n return map(list, zip(*(x.forms() for x in self.xs)))\n\n\nclass Value:\n \"\"\"Value placeholder.\"\"\"\n\n def __init__(self, *values):\n self._values = values\n\n def forms(self):\n return self._values\n\n\nclass Bool(Value):\n \"\"\"Boolean placeholder.\"\"\"\n\n def __init__(self):\n Value.__init__(self, False, True)\n" ]
[ [ "tensorflow.constant", "numpy.matmul", "numpy.indices", "numpy.transpose", "torch.tensor", "numpy.random.randn", "numpy.random.rand", "numpy.testing.assert_allclose", "numpy.array" ] ]
LynXies/lab3
[ "8c35daecfde8a6aae6fdc9ccdfa9f097552e1743" ]
[ "lab2.py" ]
[ "import sqlite3\r\nfrom bottle import route, run, debug, template, request\r\nimport requests\r\nimport json\r\nfrom bs4 import BeautifulSoup\r\nimport pandas as pd\r\nurl = 'https://xakep.ru/'\r\nheaders = {\"accept\": \"text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9\",\r\n \"accept-language\": \"ru-RU,ru;q=0.9,en-US;q=0.8,en;q=0.7\",\r\n \"sec-ch-ua\": \"\\\"Google Chrome\\\";v=\\\"95\\\", \\\"Chromium\\\";v=\\\"95\\\", \\\";Not A Brand\\\";v=\\\"99\\\"\",\r\n \"sec-ch-ua-mobile\": \"?0\",\r\n \"sec-ch-ua-platform\": \"\\\"Windows\\\"\",\r\n \"sec-fetch-dest\": \"document\",\r\n \"sec-fetch-mode\": \"navigate\",\r\n \"sec-fetch-site\": \"same-origin\",\r\n \"sec-fetch-user\": \"?1\",\r\n \"upgrade-insecure-requests\": \"1\",\r\n \"cookie\": \"_ga=GA1.2.737393603.1634229632; __gads=ID=8f33bcf4f46c6739:T=1634229641:S=ALNI_MamWgAseKX7uBYtPWn-A7fpsXAY1Q; _ym_uid=1634229749562852097; _ym_d=1634229749; wordpress_logged_in_95a2ce14874d444647baa643165aaf19=Doctor_wHo_Try%7C1637264911%7CrRX7rfJMO5U2cpBYsboiWgrCgyYJQGqYmCVrWg72aVY%7C080f019e9f45e3d770bef2f97b063c7c145d0e17095481cc29ab15ae2ed27b09; _gid=GA1.2.144395574.1636783796; _gat=1\",\r\n \"Referer\": \"https://xakep.ru/\",\r\n \"Referrer-Policy\": \"strict-origin-when-cross-origin\"\r\n }\r\nconn = sqlite3.connect('lab.db')\r\ncursor = conn.cursor()\r\n\r\n\r\n@route('/select')\r\ndef select():\r\n cursor.execute(\"SELECT * FROM links\")\r\n result = cursor.fetchall()\r\n output = template('interface', result=result)\r\n print(result)\r\n conn.commit()\r\n\r\n return output\r\n\r\n\r\ndef add_data(df):\r\n add = df.to_sql('links', conn, if_exists='replace')\r\n if (add):\r\n print(\"Данные успешно добавлены\")\r\n\r\n return add\r\n\r\n\r\n@route('/crawler', method='GET')\r\ndef crawler():\r\n hs = []\r\n hrefs = []\r\n spans = []\r\n tags = []\r\n n_pages = 0\r\n if request.GET.parse:\r\n first = int(request.GET.first.strip())\r\n last = int(request.GET.last.strip())\r\n for page in range(first, last):\r\n url = 'https://xakep.ru/page/'+str(page)\r\n r = requests.get(url, headers=headers)\r\n soup = BeautifulSoup(r.content, 'html.parser')\r\n h = soup.find_all(\"h3\", {\"class\": \"entry-title\"})\r\n for el in h:\r\n hs.append(el)\r\n for h in hs:\r\n article_hrefs = h.find_all('a')\r\n for tag in article_hrefs:\r\n href = tag['href']\r\n hrefs.append(href)\r\n t = tag.select('a > span')\r\n tags.append(t)\r\n n_pages += 1\r\n\r\n flatten_tags = [item for sublist in tags for item in sublist]\r\n for elem in flatten_tags:\r\n el = elem.text\r\n spans.append((el))\r\n print(len(spans))\r\n print(len(hrefs))\r\n\r\n cols = ['href', 'title']\r\n df = pd.DataFrame({'href': hrefs,\r\n 'title': spans})[cols]\r\n\r\n add_data(df)\r\n print(len(df))\r\n conn.commit()\r\n\r\n return template('crawler.tpl')\r\n\r\n\r\n@route('/insert', method='GET')\r\ndef insert():\r\n if request.GET.save:\r\n id = str(cursor.lastrowid+1)\r\n href = request.GET.href.strip()\r\n title = request.GET.title.strip()\r\n cursor.execute(\"INSERT INTO links VALUES(?,?,?)\", (id, href, title))\r\n new_id = cursor.lastrowid\r\n\r\n conn.commit()\r\n\r\n return '<p>>The new task was inserted into the database, the ID is %s</p>' % new_id\r\n else:\r\n return template('new_task.tpl')\r\n\r\n\r\n@ route('/update/<no:int>', method='GET')\r\ndef update_item(no):\r\n if request.GET.save:\r\n href = request.GET.href.strip()\r\n title = request.GET.title.strip()\r\n cursor.execute(\r\n \"UPDATE links SET href = ?, title = ? WHERE id LIKE ?\", (href, title, no))\r\n conn.commit()\r\n\r\n return '<p>The item number %s was successfully updated</p>' % no\r\n else:\r\n cursor.execute(\"SELECT * FROM links WHERE id LIKE ?\", str((no)))\r\n cur_data = cursor.fetchone()\r\n print(cur_data)\r\n\r\n return template('edit_task', old=cur_data, no=no)\r\n\r\n\r\n@ route('/delete/<no:int>', method=\"GET\")\r\ndef delete_item(no):\r\n cursor.execute(\"SELECT count(*) FROM links\")\r\n cursor.execute(\"DELETE FROM links WHERE id=?\", str(no))\r\n cursor.execute(\"SELECT count(*) FROM links\")\r\n conn.commit()\r\n return '<p>The item number %s was successfully deleted</p>' % no\r\n\r\n\r\nrun(host='localhost', port=8080, debug=True)\r\n" ]
[ [ "pandas.DataFrame" ] ]
naesseth/nestedsmc
[ "b94633c14c2fd335b143d2bd264fd4900ed278cd" ]
[ "src/lgss/runBootstrap.py" ]
[ "import helpfunctions as hlp\nimport numpy as np\nfrom optparse import OptionParser\n\n\ndef runBootstrap(d, tauPhi, N, nrRuns):\n r\"\"\"Run bootstrap particle filtering on high-dimensional LGSS.\n \n Parameters\n ----------\n d : int\n State dimension.\n tauPhi : float\n Measurement precision.\n N : int\n Number of particles\n nrRuns : int\n Number of independent runs of the algorithm..\n \n Returns\n -------\n Saves E[X] and E[X**2] estimates.\n \"\"\"\n a = 0.5\n tauPsi = 1.\n tauRho = 1.\n filename = 'simulatedData/d'+str(d)+'tauPhi'+str(tauPhi)+'y.txt'\n y = np.loadtxt(filename)\n filename = 'simulatedData/d'+str(d)+'tauPhi'+str(tauPhi)+'P.txt'\n P = np.loadtxt(filename)\n P = P[:d,:d]\n\n T = y.shape[1]\n\n for j in range(nrRuns):\n filename = './results/paper/d'+str(d)+'_N'+str(N)+'tauPhi'+str(tauPhi)+'_bootstraprun'+str(j+1)+'.csv'\n f = open(filename, 'w')\n f.close()\n \n xCur = np.zeros((N,d))\n xPrev = np.zeros((N,d))\n ancestors = np.zeros(N)\n weights = np.zeros(N)\n logWeights = np.zeros(N)\n ESS = np.zeros(T)\n\n xCur = np.random.multivariate_normal(np.zeros(d), P, size=N)\n xPrev = xCur\n\n # t = 1\n for i in range(N):\n logWeights[i] = -0.5*tauPhi*np.sum((xCur[i,:]-y[:,0])**2)\n maxLw = np.max(logWeights)\n weights = np.exp(logWeights-maxLw)\n weights /= np.sum(weights)\n ancestors = hlp.resampling(weights)\n xCur = xCur[ancestors,:]\n ESS[0] = 1/np.sum(weights**2)\n\n f = open(filename, 'a')\n tmpVec = np.r_[1, ESS[0], np.mean(xCur,axis=0), np.mean(xCur**2,axis=0)]\n np.savetxt(f, tmpVec.reshape((1,len(tmpVec))),delimiter=',')\n f.close()\n \n # t > 1 \n for t in np.arange(1,T):\n # Resampling\n ancestors = hlp.resampling(weights)\n \n # Generate samples\n rndSamp = np.random.multivariate_normal(np.zeros(d), P, size=N)\n \n # Propagate\n for i in range(N):\n mu = tauRho*a*np.dot(P,xPrev[ancestors[i],:])\n xCur[i,:] = mu + rndSamp[i,:]\n logWeights[i] = -0.5*tauPhi*np.sum((xCur[i,:]-y[:,t])**2)\n maxLw = np.max(logWeights)\n weights = np.exp(logWeights-maxLw)\n weights /= np.sum(weights)\n ESS[t] = 1/np.sum(weights**2)\n xPrev = xCur\n \n f = open(filename, 'a')\n tmpVec = np.r_[t+1, ESS[t], np.mean(xCur,axis=0), np.mean(xCur**2,axis=0)]\n np.savetxt(f, tmpVec.reshape((1,len(tmpVec))),delimiter=',')\n f.close()\n\nif __name__ == \"__main__\":\n parser = OptionParser()\n parser.add_option(\"-d\", type=int, help=\"State dimension\")\n parser.add_option(\"--tauPhi\", type=float, help=\"Measurement precision\")\n parser.add_option(\"-N\", type=int, help=\"Particles\")\n parser.add_option(\"--nrRuns\", type=int, help=\"Number of independent runs\")\n (args, options) = parser.parse_args()\n runBootstrap(args.d, args.tauPhi, args.N, args.nrRuns)\n" ]
[ [ "numpy.dot", "numpy.arange", "numpy.max", "numpy.mean", "numpy.exp", "numpy.zeros", "numpy.sum", "numpy.loadtxt" ] ]
Franck-Dernoncourt/meta_cross_nlu_qa
[ "98f0af07988f24d9c7827030765246c6f67a0f4d" ]
[ "nlu/meta_learner_l2l_no_acc.py" ]
[ "from torch import optim\nfrom torch import nn\nimport torch\n\nfrom sklearn.metrics import f1_score, precision_score, recall_score\nfrom copy import deepcopy\nfrom tqdm import tqdm\nimport learn2learn as l2l\n\n\ndef accuracy(logits, targets):\n intent_corrects = 0\n for j in range(len(logits)):\n true_intent = targets[j].squeeze().item()\n pred_intent = logits[j].squeeze().max(0)[1]\n intent_corrects += int(pred_intent == true_intent)\n return intent_corrects / targets.size(0)\n\n\nclass MetaLearner(nn.Module):\n \"\"\"\n Doesn't accumulates gradients in the outer loop over all tasks but each task at time (equivalent to maml with one task per batch)\n \"\"\"\n def __init__(self, opti_config, base_model, use_slots, intent_types, slot_types, device, dataset, freeze_bert, use_freeze_bert, use_freeze_linear):\n super(MetaLearner, self).__init__()\n self.n_up_train_step = opti_config[\"n_up_train_step\"]\n self.n_up_test_step = opti_config[\"n_up_test_step\"]\n self.alpha_lr = opti_config[\"alpha_lr\"]\n self.beta_lr = opti_config[\"beta_lr\"]\n self.gamma_lr = opti_config[\"gamma_lr\"]\n self.use_slots = use_slots\n self.slot_types = slot_types\n\n self.base_model = base_model\n self.initial_parameters = base_model.parameters()\n self.inner_optim = optim.Adam(self.base_model.parameters(), lr=self.alpha_lr)\n self.tune_optim = optim.Adam(self.base_model.parameters(), lr=self.gamma_lr)\n self.device = device\n self.use_freeze_bert = use_freeze_bert\n self.use_freeze_linear = use_freeze_linear\n self.freeze_bert_params = []\n if 13 in freeze_bert:\n self.freeze_bert_params += [\"trans_model.embeddings.word_embeddings.weight\",\n \"trans_model.embeddings.position_embeddings.weight\",\n \"trans_model.embeddings.token_type_embeddings.weight\",\n \"trans_model.embeddings.LayerNorm.weight\",\n \"trans_model.embeddings.LayerNorm.bias\"]\n if 12 in freeze_bert:\n self.freeze_bert_params += [\"trans_model.pooler.dense.weight\",\n \"trans_model.pooler.dense.bias\"]\n freeze_bert_layers = []\n for i in freeze_bert:\n if i not in [12, 13]:\n freeze_bert_layers.append(i)\n self.freeze_bert_params += [\"trans_model.encoder.layer.\"+str(i)+\".attention.self.\"+j+\".\"+k\n for i in freeze_bert_layers for j in [\"query\", \"key\"] for k in [\"weight\", \"bias\"]]+ \\\n [[\"trans_model.encoder.layer.\"+str(i)+\".attention.output.\"+j+\".\"+k for i in freeze_bert_layers\n for j in [\"dense\", \"LayerNorm\"] for k in [\"weight\", \"bias\"]]] + \\\n [[\"trans_model.encoder.layer.\"+str(i)+\".\"+j+\".dense.\"+k for i in freeze_bert_layers\n for j in [\"intermediate\", \"output\"] for k in [\"weight\", \"bias\"] ]] + \\\n [[\"trans_model.encoder.layer.\"+str(i)+\".output.LayerNorm.\"+j for i in freeze_bert_layers\n for j in [\"weight\", \"bias\"] ]] + ['pooler.dense.weight', 'pooler.dense.bias']\n\n def forward(self, use_adapt, use_back, use_spt_back, use_ada_independent, opt, inp_ids_spt, tok_typ_ids_spt, att_masks_spt, len_spt, int_l_spt, slot_l_spt,\n inp_ids_qry, tok_typ_ids_qry, att_masks_qry, len_qry, int_l_qry, slot_l_qry,\n ##\n inp_ids_spt_tune, tok_typ_ids_spt_tune, att_masks_spt_tune, len_spt_tune,\n int_l_spt_tune, slot_l_spt_tune, inp_ids_qry_tune, tok_typ_ids_qry_tune,\n att_masks_qry_tune, len_qry_tune, int_l_qry_tune, slot_l_qry_tune):\n\n n_tasks = inp_ids_qry.size(0)\n\n maml = l2l.algorithms.MAML(self.base_model, lr=self.alpha_lr, first_order=True)\n\n meta_train_error = 0.0\n meta_train_accuracy = 0.0\n meta_tune_error = 0.0\n meta_tune_accuracy = 0.0\n\n for name, param in self.base_model.named_parameters():\n if self.use_freeze_bert:\n if \"trans_model\" in name:\n param.requires_grad = False\n\n if self.use_freeze_linear:\n if \"trans_model\" not in name:\n param.requires_grad = False\n\n for i in range(n_tasks):\n learner = maml.clone()\n\n for _ in range(0, self.n_up_train_step):\n if self.use_slots:\n logits_intents, logits_slots, intent_loss, slot_loss = learner(input_ids=inp_ids_spt[i],\n intent_labels=int_l_spt[i],\n slot_labels=slot_l_spt[i])\n\n loss = intent_loss + slot_loss\n\n else:\n logits_intents, intent_loss = learner(input_ids=inp_ids_spt[i],\n intent_labels=int_l_spt[i])\n loss = intent_loss\n\n learner.adapt(loss, allow_nograd=True, allow_unused=True)\n\n # On the query data\n if self.use_slots:\n logits_intents, logits_slots, intent_loss, slot_loss = learner(input_ids=inp_ids_qry[i],\n intent_labels=int_l_qry[i],\n slot_labels=slot_l_qry[i])\n\n loss_qry = intent_loss + slot_loss\n\n else:\n logits_intents, intent_loss = learner(input_ids=inp_ids_qry[i],\n intent_labels=int_l_qry[i])\n loss_qry = intent_loss\n\n loss_qry.backward()\n\n meta_train_error += loss_qry.item()\n meta_train_accuracy += accuracy(logits_intents, int_l_qry[i])\n\n ### Meta-validation Optimization\n if use_adapt and not use_ada_independent:\n #learner = maml.clone()\n\n for _ in range(0, self.n_up_test_step):\n if self.use_slots:\n logits_intents, logits_slots, intent_loss, slot_loss = learner(input_ids=inp_ids_spt_tune[i],\n intent_labels=int_l_spt_tune[i],\n slot_labels=slot_l_spt_tune[i])\n\n loss = intent_loss + slot_loss\n\n else:\n logits_intents, intent_loss = learner(input_ids=inp_ids_spt_tune[i],\n intent_labels=int_l_spt_tune[i])\n loss = intent_loss\n\n learner.adapt(loss, allow_nograd=True, allow_unused=True)\n\n if use_spt_back:\n loss.backward(retain_graph=True)\n\n if self.use_slots:\n logits_intents, logits_slots, intent_loss, slot_loss = learner(input_ids=inp_ids_qry_tune[i],\n intent_labels=int_l_qry_tune[i],\n slot_labels=slot_l_qry_tune[i])\n\n loss_qry = intent_loss + slot_loss\n\n else:\n logits_intents, intent_loss = learner(input_ids=inp_ids_qry_tune[i],\n intent_labels=int_l_qry_tune[i])\n loss_qry = intent_loss\n\n meta_tune_error += loss_qry.item()\n meta_tune_accuracy += accuracy(logits_intents, int_l_qry_tune[i])\n\n if use_back:\n loss_qry.backward()\n\n if use_adapt and use_ada_independent:\n for i in range(n_tasks):\n learner = maml.clone()\n\n for _ in range(0, self.n_up_test_step):\n if self.use_slots:\n logits_intents, logits_slots, intent_loss, slot_loss = learner(input_ids=inp_ids_spt_tune[i],\n intent_labels=int_l_spt_tune[i],\n slot_labels=slot_l_spt_tune[i])\n\n loss = intent_loss + slot_loss\n\n else:\n logits_intents, intent_loss = learner(input_ids=inp_ids_spt_tune[i],\n intent_labels=int_l_spt_tune[i])\n loss = intent_loss\n\n learner.adapt(loss, allow_nograd=True, allow_unused=True)\n if use_spt_back:\n loss.backward(retain_graph=True)\n\n # On the query data\n if self.use_slots:\n logits_intents, logits_slots, intent_loss, slot_loss = learner(input_ids=inp_ids_qry_tune[i],\n intent_labels=int_l_qry_tune[i],\n slot_labels=slot_l_qry_tune[i])\n\n loss_qry = intent_loss + slot_loss\n\n else:\n logits_intents, intent_loss = learner(input_ids=inp_ids_qry_tune[i],\n intent_labels=int_l_qry_tune[i])\n loss_qry = intent_loss\n\n if use_back:\n loss_qry.backward()\n\n meta_train_error += loss_qry.item()\n meta_train_accuracy += accuracy(logits_intents, int_l_qry[i])\n\n # Average the accumulated gradients and optimize\n for p in maml.parameters():\n if p.grad is not None:\n p.grad.mul_(1.0 / n_tasks)\n opt.step()\n return maml, meta_train_error, meta_train_accuracy, meta_tune_error, meta_tune_accuracy\n\n def zero_shot_test(self, test_langs, dataset):\n \"\"\"\n Testing the method on test split in the non-meta-learning setup and comparing before and after the meta-training\n :return:\n \"\"\"\n\n metrics = {}\n\n for lang in test_langs:\n metrics_sub = {}\n self.base_model.eval()\n\n intent_corrects = 0\n intents_true, intents_pred, slots_true, slots_pred = [], [], [], []\n\n for _ in range(dataset.test_size[lang]):\n (input_ids, lengths, token_type_ids, attention_mask, intent_labels, slot_labels, input_texts), text \\\n = dataset.next_batch(1, dataset.test[lang], dev_langs=[])\n batch = input_ids, lengths, token_type_ids, attention_mask, intent_labels, slot_labels\n batch = tuple(t.to(self.device) for t in batch)\n input_ids, lengths, token_type_ids, attention_mask, intent_labels, slot_labels = batch\n\n with torch.no_grad():\n if self.use_slots:\n intent_logits, slot_logits, intent_loss, slot_loss \\\n = self.base_model(input_ids=input_ids,\n intent_labels=intent_labels,\n slot_labels=slot_labels)\n\n # Slot Golden Truth/Predictions\n true_slot = slot_labels[0]\n pred_slot = list(slot_logits.cpu().squeeze().max(-1)[1].numpy())\n\n true_slot_l = [dataset.slot_types[s] for s in true_slot]\n pred_slot_l = [dataset.slot_types[s] for s in pred_slot]\n\n true_slot_no_x, pred_slot_no_x = [], []\n\n for i, slot in enumerate(true_slot_l):\n if slot != \"X\":\n true_slot_no_x.append(true_slot_l[i])\n pred_slot_no_x.append(pred_slot_l[i])\n\n slots_true.extend(true_slot_no_x)\n slots_pred.extend(pred_slot_no_x)\n\n else:\n intent_logits, intent_loss = self.base_model(input_ids=input_ids,\n intent_labels=intent_labels)\n\n # Intent Golden Truth/Predictions\n true_intent = intent_labels.squeeze().item()\n pred_intent = intent_logits.squeeze().max(0)[1]\n\n intent_corrects += int(pred_intent == true_intent)\n\n masked_text = ' '.join(dataset.tokenizer.convert_ids_to_tokens(input_ids.squeeze().tolist()))\n intents_true.append(true_intent)\n intents_pred.append(pred_intent.item())\n\n metrics_sub.update({\"intent_accuracy\": float(intent_corrects) / dataset.test_size[lang],\n \"intent_prec\": precision_score(intents_true, intents_pred, average=\"macro\"),\n \"intent_rec\": recall_score(intents_true, intents_pred, average=\"macro\"),\n \"intent_f1\": f1_score(intents_true, intents_pred, average=\"macro\")})\n\n if self.use_slots:\n metrics_sub.update({\"slot_prec\": precision_score(slots_true, slots_pred, average=\"macro\"),\n \"slot_rec\": recall_score(slots_true, slots_pred, average=\"macro\"),\n \"slot_f1\": f1_score(slots_true, slots_pred, average=\"macro\")})\n\n metrics.update({lang: metrics_sub})\n\n return metrics\n\n def val_eval(self, dev_langs, dataset):\n \"\"\"\n Validating the method on dev split\n :return:\n \"\"\"\n\n metrics = {}\n for lang in dev_langs:\n metrics_sub = {}\n self.base_model.eval()\n\n intent_corrects = 0\n intents_true, intents_pred, slots_true, slots_pred = [], [], [], []\n\n for _ in range(dataset.val_size[lang]):\n (input_ids, lengths, token_type_ids, attention_mask, intent_labels, slot_labels, input_texts), text \\\n = dataset.next_batch(1, dataset.val[lang], dev_langs=[])\n batch = input_ids, lengths, token_type_ids, attention_mask, intent_labels, slot_labels\n batch = tuple(t.to(self.device) for t in batch)\n input_ids, lengths, token_type_ids, attention_mask, intent_labels, slot_labels = batch\n\n with torch.no_grad():\n if self.use_slots:\n intent_logits, slot_logits, intent_loss, slot_loss \\\n = self.base_model(input_ids=input_ids,\n intent_labels=intent_labels,\n slot_labels=slot_labels)\n\n # Slot Golden Truth/Predictions\n true_slot = slot_labels[0]\n pred_slot = list(slot_logits.cpu().squeeze().max(-1)[1].numpy())\n\n true_slot_l = [dataset.slot_types[s] for s in true_slot]\n pred_slot_l = [dataset.slot_types[s] for s in pred_slot]\n\n true_slot_no_x, pred_slot_no_x = [], []\n\n for i, slot in enumerate(true_slot_l):\n if slot != \"X\":\n true_slot_no_x.append(true_slot_l[i])\n pred_slot_no_x.append(pred_slot_l[i])\n\n slots_true.extend(true_slot_no_x)\n slots_pred.extend(pred_slot_no_x)\n\n else:\n intent_logits, intent_loss = self.base_model(input_ids=input_ids,\n intent_labels=intent_labels)\n\n # Intent Golden Truth/Predictions\n true_intent = intent_labels.squeeze().item()\n pred_intent = intent_logits.squeeze().max(0)[1]\n\n intent_corrects += int(pred_intent == true_intent)\n\n masked_text = ' '.join(dataset.tokenizer.convert_ids_to_tokens(input_ids.squeeze().tolist()))\n intents_true.append(true_intent)\n intents_pred.append(pred_intent.item())\n\n metrics_sub.update({\"intent_accuracy\": float(intent_corrects) / dataset.test_size[lang],\n \"intent_prec\": precision_score(intents_true, intents_pred, average=\"macro\"),\n \"intent_rec\": recall_score(intents_true, intents_pred, average=\"macro\"),\n \"intent_f1\": f1_score(intents_true, intents_pred, average=\"macro\")})\n\n if self.use_slots:\n metrics_sub.update({\"slot_prec\": precision_score(slots_true, slots_pred, average=\"macro\"),\n \"slot_rec\": recall_score(slots_true, slots_pred, average=\"macro\"),\n \"slot_f1\": f1_score(slots_true, slots_pred, average=\"macro\")})\n\n metrics.update({lang: metrics_sub})\n\n return metrics\n" ]
[ [ "sklearn.metrics.f1_score", "sklearn.metrics.precision_score", "torch.no_grad", "sklearn.metrics.recall_score" ] ]
smit2k14/awkward-array
[ "a2645fdaed1a6997c4677ae47cbb2cd0663e8a21" ]
[ "awkward/persist.py" ]
[ "#!/usr/bin/env python\n\n# BSD 3-Clause License; see https://github.com/scikit-hep/awkward-array/blob/master/LICENSE\n\nimport base64\nimport fnmatch\nimport importlib\nimport json\nimport numbers\nimport os\nimport pickle\nimport types\nimport zipfile\nimport zlib\nfrom itertools import count\ntry:\n from collections.abc import Mapping, MutableMapping\nexcept ImportError:\n from collections import Mapping, MutableMapping\n\nimport numpy\n\nimport awkward.type\nimport awkward.version\n\ncompression = [\n {\"minsize\": 8192, \"types\": [numpy.bool_, numpy.bool, numpy.integer], \"contexts\": \"*\", \"pair\": (zlib.compress, (\"zlib\", \"decompress\"))},\n ]\n\nwhitelist = [\n [\"numpy\", \"frombuffer\"],\n [\"zlib\", \"decompress\"],\n [\"lzma\", \"decompress\"],\n [\"backports.lzma\", \"decompress\"],\n [\"lz4.block\", \"decompress\"],\n [\"awkward\", \"*Array\"],\n [\"awkward\", \"Table\"],\n [\"awkward\", \"numpy\", \"frombuffer\"],\n [\"awkward.util\", \"frombuffer\"],\n [\"awkward.persist\"],\n [\"awkward.arrow\", \"_ParquetFile\", \"fromjson\"],\n [\"uproot_methods.classes.*\"],\n [\"uproot_methods.profiles.*\"],\n [\"uproot.tree\", \"_LazyFiles\"],\n [\"uproot.tree\", \"_LazyTree\"],\n [\"uproot.tree\", \"_LazyBranch\"],\n ]\n\ndef frompython(obj):\n return base64.b64encode(pickle.dumps(obj)).decode(\"ascii\")\n\ndef topython(string):\n return pickle.loads(base64.b64decode(string.encode(\"ascii\")))\n\ndef spec2function(obj, awkwardlib=\"awkward\", whitelist=whitelist):\n for white in whitelist:\n for n, p in zip(obj, white):\n if not fnmatch.fnmatchcase(n, p):\n break\n else:\n if obj[0] == \"awkward\":\n obj = [awkwardlib] + obj[1:]\n gen, genname = importlib.import_module(obj[0]), obj[1:]\n if not isinstance(gen, types.ModuleType):\n raise TypeError(\"first item of a function description must be a module\")\n if genname[:1] == [\"numpy\"]:\n gen, genname = getattr(gen, genname[0]), genname[1:]\n while len(genname) > 0:\n gen, genname = getattr(gen, genname[0]), genname[1:]\n if isinstance(gen, types.ModuleType):\n raise TypeError(\"non-first items of a function description must not be a module\")\n break\n else:\n raise RuntimeError(\"callable not in whitelist; add it by passing a whitelist argument:\\n\\n whitelist = awkward.persist.whitelist + [{0}]\".format(repr(obj)))\n return gen\n\ndef dtype2json(obj):\n if obj.subdtype is not None:\n dt, sh = obj.subdtype\n return (dtype2json(dt), sh)\n elif obj.names is not None:\n return [(n, dtype2json(obj[n])) for n in obj.names]\n else:\n return str(obj)\n\ndef json2dtype(obj):\n def recurse(obj):\n if isinstance(obj, (list, tuple)) and len(obj) > 0 and (isinstance(obj[-1], numbers.Integral) or isinstance(obj[0], str) or (isinstance(obj[-1], (list, tuple)) and all(isinstance(x, numbers.Integral) for x in obj[-1]))):\n return tuple(recurse(x) for x in obj)\n elif isinstance(obj, (list, tuple)):\n return [recurse(x) for x in obj]\n else:\n return obj\n return numpy.dtype(recurse(obj))\n\ndef type2json(obj):\n if isinstance(obj, awkward.type.Type):\n labeled = obj._labeled()\n else:\n labeled = []\n\n seen = set()\n\n def takes(n):\n if n == float(\"inf\"):\n return \"inf\"\n else:\n return int(n)\n\n def recurse(obj):\n if isinstance(obj, awkward.type.Type):\n if id(obj) in seen:\n for i, x in enumerate(labeled):\n if obj is x:\n return {\"ref\": \"T{0}\".format(i)}\n\n else:\n seen.add(id(obj))\n if isinstance(obj, awkward.type.ArrayType):\n out = {\"takes\": takes(obj._takes), \"to\": recurse(obj._to)}\n\n elif isinstance(obj, awkward.type.TableType):\n out = {\"fields\": [[n, recurse(x)] for n, x in obj._fields.items()]}\n\n elif isinstance(obj, awkward.type.UnionType):\n out = {\"possibilities\": [recurse(x) for x in obj._possibilities]}\n\n elif isinstance(obj, awkward.type.OptionType):\n out = {\"type\": recurse(obj._type)}\n\n for i, x in enumerate(labeled):\n if obj is x:\n return {\"set\": \"T{0}\".format(i), \"as\": out}\n else:\n return out\n\n elif isinstance(obj, numpy.dtype):\n return {\"dtype\": dtype2json(obj)}\n\n elif callable(obj):\n if obj.__module__ == \"__main__\":\n raise TypeError(\"cannot persist object type: its generator is defined in __main__, which won't be available in a subsequent session\")\n if hasattr(obj, \"__qualname__\"):\n spec = [obj.__module__] + obj.__qualname__.split(\".\")\n else:\n spec = [obj.__module__, obj.__name__]\n\n gen, genname = importlib.import_module(spec[0]), spec[1:]\n while len(genname) > 0:\n gen, genname = getattr(gen, genname[0]), genname[1:]\n if gen is not obj:\n raise TypeError(\"cannot persist object type: its generator cannot be found via its __name__ (Python 2) or __qualname__ (Python 3)\")\n\n return {\"function\": spec}\n\n else:\n raise TypeError(\"only awkward.type.Type, numpy.dtype, and callables are types\")\n\n return recurse(obj)\n\ndef json2type(obj, whitelist=whitelist):\n labels = {}\n\n def takes(n):\n if n == \"inf\":\n return float(\"inf\")\n else:\n return n\n\n def recurse(obj):\n if not isinstance(obj, dict):\n raise TypeError(\"json2type is expecting a JSON object, found: {0}\".format(repr(obj)))\n\n if \"set\" in obj:\n placeholder = labels[obj[\"set\"]] = awkward.type.Placeholder()\n placeholder.value = recurse(obj[\"as\"])\n return placeholder\n\n elif \"ref\" in obj:\n return labels[obj[\"ref\"]]\n\n elif \"takes\" in obj and \"to\" in obj:\n return awkward.type.ArrayType(takes(obj[\"takes\"]), recurse(obj[\"to\"]))\n\n elif \"fields\" in obj:\n out = awkward.type.TableType()\n for n, x in obj[\"fields\"]:\n out[n] = recurse(x)\n return out\n\n elif \"possibilities\" in obj:\n return awkward.type.UnionType(*[recurse(x) for x in obj[\"possibilities\"]])\n\n elif \"type\" in obj:\n return awkward.type.OptionType(recurse(obj[\"type\"]))\n\n elif \"dtype\" in obj:\n return json2dtype(obj[\"dtype\"])\n\n elif \"function\" in obj:\n return spec2function(obj[\"function\"], whitelist=whitelist)\n\n else:\n raise ValueError(\"unexpected set of keys in JSON: {0}\".format(\", \".join(repr(x) for x in obj)))\n\n return awkward.type._resolve(recurse(obj), {})\n\ndef jsonable(obj):\n if obj is None:\n return obj\n\n elif isinstance(obj, dict) and all(isinstance(n, str) for n in obj):\n return {n: jsonable(x) for n, x in obj.items()}\n\n elif isinstance(obj, list):\n return [jsonable(x) for x in obj]\n\n elif isinstance(obj, str):\n return str(obj)\n\n elif isinstance(obj, (bool, numpy.bool_, numpy.bool)):\n return bool(obj) # policy: eliminate Numpy types\n\n elif isinstance(obj, (numbers.Integral, numpy.integer)):\n return int(obj) # policy: eliminate Numpy types\n\n elif isinstance(obj, (numbers.Real, numpy.floating)) and numpy.isfinite(obj):\n return float(obj) # policy: eliminate Numpy types\n\n else:\n raise TypeError(\"object cannot be losslessly serialized as JSON\")\n\nclass ObjRef(object):\n def __init__(self, idgen=None):\n if idgen:\n self.idgen = iter(idgen)\n self._i2r = {}\n self._r2o = {}\n\n def nextid(self):\n return next(self.idgen)\n\n def __contains__(self, obj):\n return id(obj) in self._i2r\n\n def __setitem__(self, obj, ref):\n self._i2r[id(obj)] = ref\n self._r2o[ref] = obj\n\n def __getitem__(self, obj):\n if obj not in self:\n self[obj] = self.nextid()\n return self._i2r[id(obj)]\n\n def __delitem__(self, obj):\n assert obj in self\n del self._r2o[self._i2r[id(obj)]]\n del self._i2r[id(obj)]\n\n def get(self, obj, default=None):\n return self[obj] if obj in self else default\n\n def obj(self, ref):\n if ref in self._r2o:\n return self._r2o[ref]\n else:\n return awkward.array.virtual.VirtualArray(lambda: self._r2o[ref])\n\nclass Serializer(object):\n def __init__(self, storage, prefix=\"\", suffix=\"\", schemasuffix=\"\"):\n self.storage = storage\n self.suffix = suffix\n self.prefix = prefix\n self.schemasuffix = schemasuffix\n self.seen = ObjRef(idgen=count())\n\n def store(self, name, obj):\n schema = {\"awkward\": awkward.version.__version__, \"schema\": self(obj)}\n if self.prefix != \"\":\n schema[\"prefix\"] = self.prefix\n\n schema = self._finalize_schema(schema) or schema\n\n self.storage[name + self.schemasuffix] = self._encode_schema(schema)\n return schema\n\n def load(self, *args, **kwargs):\n return deserialize(*args, storage=self.storage, seen=self.seen, **kwargs)\n\n def encode_call(self, *args, **kwargs):\n func, args = args[0], args[1:]\n out = {\"call\": self._obj2spec(func) if callable(func) else tuple(func)}\n if args:\n out[\"args\"] = list(args)\n if kwargs:\n out[\"kwargs\"] = kwargs\n return out\n\n def encode_json(self, obj):\n return {\"json\": jsonable(obj)}\n\n def encode_python(self, obj):\n return {\"python\": frompython(obj)}\n\n @classmethod\n def _encode_primitive(cls, obj):\n if isinstance(obj, numpy.dtype):\n return {\"dtype\": dtype2json(obj)}\n\n @classmethod\n def _obj2spec(cls, obj, test=True):\n if hasattr(obj, \"__qualname__\"):\n spec = [obj.__module__] + obj.__qualname__.split(\".\")\n else:\n spec = [obj.__module__, obj.__name__]\n\n if test:\n val = importlib.import_module(spec[0])\n for key in spec[1:]:\n val = getattr(val, key)\n assert val == obj\n\n return spec\n\n def _encode_complex(self, obj, context):\n if callable(getattr(obj, \"__awkward_serialize__\", None)):\n return obj.__awkward_serialize__(self)\n\n if hasattr(obj, \"tojson\") and hasattr(type(obj), \"fromjson\"):\n try:\n return self.encode_call(self._obj2spec(type(obj).fromjson), self.encode_json(obj.tojson()))\n except:\n pass\n\n if isinstance(obj, numpy.ndarray):\n return self._encode_numpy(obj, context)\n\n if hasattr(obj, \"__module__\") and (hasattr(obj, \"__qualname__\") or hasattr(obj, \"__name__\")) and obj.__module__ != \"__main__\":\n try:\n return {\"function\": self._obj2spec(obj)}\n except:\n pass\n\n try:\n return self.encode_json(obj)\n except TypeError:\n pass\n\n try:\n return self.encode_python(obj)\n except:\n pass\n\n def _encode_numpy(self, obj, context):\n key = str(self.seen[obj]) + self.suffix\n self.storage[self.prefix + key] = obj\n return {\"read\": key}\n\n def _encode_schema(self, schema):\n return json.dumps(schema).encode(\"ascii\")\n\n def _finalize_schema(self, schema):\n pass\n\n def __call__(self, obj, context=\"\"):\n out = self._encode_primitive(obj)\n\n if out is not None:\n return out\n\n if obj in self.seen:\n return {\"ref\": self.seen[obj]}\n else:\n ident = self.seen[obj]\n\n out = self._encode_complex(obj, context)\n if out is None:\n raise TypeError(\"failed to encode {0} (type: {1})\".format(repr(obj), type(obj)))\n\n if \"id\" in out:\n if out[\"id\"] is False:\n del self.seen[obj]\n elif out[\"id\"] != self.seen[obj]:\n raise RuntimeError(\"unexpected id change\")\n else:\n out[\"id\"] = ident\n\n return out\n\n def fill(self, obj, context, prefix, suffix, schemasuffix, storage, compression, **kwargs):\n assert self.prefix == prefix\n assert self.suffix == suffix\n assert self.schemasuffix == schemasuffix\n assert self.storage == storage\n assert self.compression == compression\n return self(obj, context=context)\n\nclass BlobSerializer(Serializer):\n class CompressPolicy(object):\n enc2dec = {\n zlib.compress: (\"zlib\", \"decompress\"),\n }\n\n @classmethod\n def parse(cls, x):\n if isinstance(x, cls):\n return x\n elif isinstance(x, dict):\n return cls(**x)\n elif callable(x):\n return cls(enc=x)\n elif len(x) == 2 and callable(x[0]):\n return cls(enc=x[0], dec=x[1])\n else:\n raise TypeError(\"can't parse compression policy {0}\".format(x))\n\n def __init__(self, pair=None, enc=None, dec=None, minsize=0, types=object, contexts=\"*\"):\n if pair is not None:\n enc, dec = pair\n if dec is None:\n dec = self.enc2dec[enc]\n if isinstance(types, list):\n types = tuple(types)\n elif not isinstance(types, tuple):\n types = types,\n if isinstance(contexts, list):\n contexts = tuple(contexts)\n elif not isinstance(contexts, tuple):\n contexts = contexts,\n assert callable(enc)\n assert isinstance(dec, tuple)\n assert 0 <= minsize\n self.enc = enc\n self.dec = dec\n self.minsize = minsize\n self.types = types\n self.contexts = contexts\n\n @property\n def pair(self):\n return (self.enc, self.dec)\n\n def test(self, obj, context):\n return (obj.nbytes >= self.minsize and issubclass(obj.dtype.type, tuple(self.types)) and any(fnmatch.fnmatchcase(context, p) for p in self.contexts))\n\n @classmethod\n def _parse_compression(cls, comp):\n if comp is None or comp is False:\n comp = []\n elif comp is True:\n comp = [{\"minsize\": 0, \"types\": object, \"contexts\": \"*\", \"pair\": (zlib.compress, (\"zlib\", \"decompress\"))}]\n elif not isinstance(comp, (list, tuple)):\n comp = [comp]\n\n return list(map(cls.CompressPolicy.parse, comp))\n\n def __init__(self, *args, **kwargs):\n self.compression = self._parse_compression(kwargs.pop(\"compression\", compression))\n super(BlobSerializer, self).__init__(*args, **kwargs)\n\n def _put_raw(self, data, ref=None):\n if ref is None:\n ref = data\n key = str(self.seen[ref]) + self.suffix\n self.storage[self.prefix + key] = data\n return dict(read=key)\n\n def _encode_numpy(self, obj, context):\n if obj.ndim > 1:\n dtype = numpy.dtype((obj.dtype, obj.shape[1:]))\n else:\n dtype = obj.dtype\n\n buf = None\n for policy in self._parse_compression(self.compression):\n if policy.test(obj, context):\n buf = self.encode_call(policy.dec, self._put_raw(policy.enc(obj.ravel()), ref=obj))\n break\n else:\n buf = self._put_raw(obj.ravel(), ref=obj)\n\n return self.encode_call([\"awkward\", \"numpy\", \"frombuffer\"], buf, self(dtype), self(obj.shape[0]))\n\ndef serialize(obj, storage, name=\"\", delimiter=\"-\", **kwargs):\n if delimiter is None:\n delimiter = \"\"\n if name:\n kwargs.setdefault(\"prefix\", name + delimiter)\n return BlobSerializer(storage, **kwargs).store(name, obj)\n\ndef deserialize(storage, name=\"\", awkwardlib=\"awkward\", whitelist=whitelist, cache=None, seen=None):\n import awkward.array.virtual\n\n schema = storage[name]\n if isinstance(schema, numpy.ndarray):\n schema = schema.tostring()\n if isinstance(schema, bytes):\n schema = schema.decode(\"ascii\")\n schema = json.loads(schema)\n\n if \"awkward\" not in schema:\n raise ValueError(\"JSON object is not an awkward-array schema (missing 'awkward' field)\")\n\n prefix = schema.get(\"prefix\", \"\")\n if seen is None:\n seen = ObjRef()\n\n if isinstance(whitelist, str):\n whitelist = [whitelist]\n elif len(whitelist) > 0 and isinstance(whitelist[0], str):\n whitelist = [whitelist]\n\n def unfill(schema):\n if isinstance(schema, dict):\n if \"call\" in schema and isinstance(schema[\"call\"], list) and len(schema[\"call\"]) > 0:\n gen = spec2function(schema[\"call\"], awkwardlib=awkwardlib, whitelist=whitelist)\n args = [unfill(x) for x in schema.get(\"args\", [])]\n\n kwargs = {}\n if schema.get(\"cacheable\", False):\n kwargs[\"cache\"] = cache\n if schema.get(\"whitelistable\", False):\n kwargs[\"whitelist\"] = whitelist\n if \"kwargs\" in schema:\n kwargs.update({n: unfill(x) for n, x in schema[\"kwargs\"].items()})\n\n out = gen(*args, **kwargs)\n\n elif \"read\" in schema:\n if schema.get(\"absolute\", False):\n out = storage[schema[\"read\"]]\n else:\n out = storage[prefix + schema[\"read\"]]\n\n elif \"list\" in schema:\n out = [unfill(x) for x in schema[\"list\"]]\n\n elif \"tuple\" in schema:\n out = tuple(unfill(x) for x in schema[\"tuple\"])\n\n elif \"dict\" in schema:\n out = {n: unfill(x) for n, x in schema[\"dict\"].items()}\n\n elif \"pairs\" in schema:\n out = [(n, unfill(x)) for n, x in schema[\"pairs\"]]\n\n elif \"dtype\" in schema:\n out = json2dtype(schema[\"dtype\"])\n\n elif \"function\" in schema:\n out = spec2function(schema[\"function\"], awkwardlib=awkwardlib, whitelist=whitelist)\n\n elif \"json\" in schema:\n out = schema[\"json\"]\n\n elif \"python\" in schema:\n out = topython(schema[\"python\"])\n\n elif \"ref\" in schema:\n out = seen.obj(schema[\"ref\"])\n\n else:\n raise ValueError(\"unrecognized JSON object with fields {0}\".format(\", \".join(repr(x) for x in schema)))\n\n if \"id\" in schema:\n seen[out] = schema[\"id\"]\n return out\n\n elif isinstance(schema, list):\n raise ValueError(\"unrecognized JSON list with length {0}\".format(len(schema)))\n\n else:\n raise ValueError(\"unrecognized JSON object: {0}\".format(repr(schema)))\n\n return unfill(schema[\"schema\"])\n\ndef keys(storage, name=\"\", subschemas=True):\n schema = storage[name]\n if isinstance(schema, numpy.ndarray):\n schema = schema.tostring()\n if isinstance(schema, bytes):\n schema = schema.decode(\"ascii\")\n schema = json.loads(schema)\n\n prefix = schema.get(\"prefix\", \"\")\n\n def recurse(schema):\n if isinstance(schema, dict):\n if \"call\" in schema and isinstance(schema[\"call\"], list) and len(schema[\"call\"]) > 0:\n for x in schema.get(\"args\", []):\n for y in recurse(x):\n yield y\n for x in schema.get(\"kwargs\", {}).values():\n for y in recurse(x):\n yield y\n for x in schema.get(\"*\", []):\n for y in recurse(x):\n yield y\n for x in schema.get(\"**\", {}).values():\n for y in recurse(x):\n yield y\n\n elif \"read\" in schema:\n if schema.get(\"absolute\", False):\n yield schema[\"read\"]\n else:\n yield prefix + schema[\"read\"]\n\n elif \"list\" in schema:\n for x in schema[\"list\"]:\n for y in recurse(x):\n yield y\n\n elif \"tuple\" in schema:\n for x in schema[\"tuple\"]:\n for y in recurse(x):\n yield y\n\n elif \"dict\" in schema:\n for x in schema[\"dict\"].values():\n for y in recurse(x):\n yield y\n\n elif \"pairs\" in schema:\n for n, x in schema[\"pairs\"]:\n for y in recurse(x):\n yield y\n\n elif \"dtype\" in schema:\n pass\n\n elif \"function\" in schema:\n pass\n\n elif \"json\" in schema:\n pass\n\n elif \"python\" in schema:\n pass\n\n elif \"ref\" in schema:\n pass\n\n yield name\n for x in recurse(schema[\"schema\"]):\n yield x\n\ndef save(file, array, name=None, mode=\"a\", **options):\n if isinstance(array, dict):\n arrays = array\n else:\n arrays = {\"\": array}\n\n if name is not None:\n arrays = {name + n: x for n, x in arrays.items()}\n\n arraynames = list(arrays)\n for i in range(len(arraynames)):\n for j in range(i + 1, len(arraynames)):\n if arraynames[i].startswith(arraynames[j]) or arraynames[j].startswith(arraynames[i]):\n raise KeyError(\"cannot write both {0} and {1} to zipfile because one is a prefix of the other\", repr(arraynames[i]), repr(arraynames[j]))\n\n if isinstance(file, getattr(os, \"PathLike\", ())):\n file = os.fspath(file)\n elif hasattr(file, \"__fspath__\"):\n file = file.__fspath__()\n elif file.__class__.__module__ == \"pathlib\":\n import pathlib\n if isinstance(file, pathlib.Path):\n file = str(file)\n\n if isinstance(file, str) and not file.endswith(\".awkd\"):\n file = file + \".awkd\"\n\n alloptions = {\"delimiter\": \"-\", \"suffix\": \".raw\", \"schemasuffix\": \".json\", \"compression\": compression}\n alloptions.update(options)\n options = alloptions\n\n class Wrap(object):\n def __init__(self, f):\n self.f = f\n def __setitem__(self, where, what):\n if isinstance(what, numpy.ndarray):\n what = what.tostring()\n self.f.writestr(where, what, compress_type=zipfile.ZIP_STORED)\n\n with zipfile.ZipFile(file, mode=mode, compression=zipfile.ZIP_STORED) as f:\n namelist = f.namelist()\n for name in arraynames:\n if any(n.startswith(name) for n in namelist):\n raise KeyError(\"cannot add {0} to zipfile because the following already exist: {1}\".format(repr(name), \", \".join(repr(n) for n in namelist if n.startswith(name))))\n\n wrapped = Wrap(f)\n for name, array in arrays.items():\n serialize(array, wrapped, name=name, **options)\n\ndef load(file, **options):\n f = Load(file, **options)\n if list(f) == [\"\"]:\n out = f[\"\"]\n f.close()\n return out\n else:\n return f\n\nclass Load(Mapping):\n def __init__(self, file, **options):\n class Wrap(object):\n def __init__(self):\n self.f = zipfile.ZipFile(file, mode=\"r\")\n def __getitem__(self, where):\n return self.f.read(where)\n\n self._file = Wrap()\n\n alloptions = {\"schemasuffix\": \".json\", \"awkwardlib\": \"awkward\", \"whitelist\": whitelist, \"cache\": None}\n alloptions.update(options)\n self.schemasuffix = alloptions.pop(\"schemasuffix\")\n self.options = alloptions\n\n def __getitem__(self, where):\n return deserialize(self._file, name=where + self.schemasuffix, awkwardlib=self.options[\"awkwardlib\"], whitelist=self.options[\"whitelist\"], cache=self.options[\"cache\"])\n\n def __iter__(self):\n for n in self._file.f.namelist():\n if n.endswith(\".json\"):\n yield n[:-5]\n\n def __len__(self):\n count = 0\n for n in self._file.f.namelist():\n if n.endswith(\".json\"):\n count += 1\n return count\n\n def __repr__(self):\n return \"<awkward.load ({0} members)>\".format(len(self))\n\n def close(self):\n self._file.f.close()\n\n def __del__(self):\n self.close()\n\n def __enter__(self, *args, **kwds):\n return self\n\n def __exit__(self, *args, **kwds):\n self.close()\n\nclass hdf5(MutableMapping):\n def __init__(self, group, **options):\n alloptions = {\"compression\": compression, \"awkwardlib\": \"awkward\", \"whitelist\": whitelist, \"cache\": None}\n alloptions.update(options)\n self.options = alloptions\n self.options[\"delimiter\"] = \"/\"\n self.options[\"schemasuffix\"] = \"/schema.json\"\n\n class Wrap(object):\n def __init__(self):\n self.g = group\n def __getitem__(self, where):\n return self.g[where][()]\n def __setitem__(self, where, what):\n self.g[where] = numpy.frombuffer(what, dtype=numpy.uint8)\n\n self._group = Wrap()\n\n def __getitem__(self, where):\n return deserialize(self._group, name=where + self.options[\"schemasuffix\"], awkwardlib=self.options[\"awkwardlib\"], whitelist=self.options[\"whitelist\"], cache=self.options[\"cache\"])\n\n def __setitem__(self, where, what):\n options = dict(self.options)\n if \"awkwardlib\" in options:\n del options[\"awkwardlib\"]\n if \"whitelist\" in options:\n del options[\"whitelist\"]\n if \"cache\" in options:\n del options[\"cache\"]\n self._group.g.create_group(where)\n serialize(what, self._group, name=where, **options)\n\n def __delitem__(self, where):\n for subname in keys(self._group, name=where + self.options[\"schemasuffix\"]):\n del self._group.g[subname]\n del self._group.g[where]\n\n def __iter__(self):\n schemaname = self.options[\"schemasuffix\"].split(\"/\")[-1]\n for subname in self._group.g:\n if schemaname in self._group.g[subname]:\n yield subname\n\n def __len__(self):\n schemaname = self.options[\"schemasuffix\"].split(\"/\")[-1]\n count = 0\n for subname in self._group.g:\n if schemaname in self._group.g[subname]:\n count += 1\n return count\n\n def __repr__(self):\n return \"<awkward.hdf5 {0} ({1} members)>\".format(repr(self._group.g.name), len(self))\n" ]
[ [ "numpy.frombuffer", "numpy.isfinite", "numpy.dtype" ] ]
jmhuer/computer-vision-framework
[ "508c8efe0bf4d983d533f0547210b2732d5e9620" ]
[ "distance.py" ]
[ "# distance.py\nfrom math import sqrt\nfrom scipy.spatial.distance import euclidean\n\ndef get_shoulder_dist_from_pe(candidate, subset):\n ''' From the pose estimation results (cadidate and subset) extract shoulder points and calculate their euclidean distance.\n '''\n distances = []\n # Check if there is any information in the vectors\n if len(candidate)>0 and len(subset)>0:\n people_sh_points = []\n # For each person body keypoints, extract shoulder points\n for sub in subset:\n sh_points = [(int(cand[0]), int(cand[1])) for cand in candidate if cand[3]==int(sub[2]) or cand[3]==int(sub[5])]\n if len(sh_points)==2:\n people_sh_points.append(sh_points)\n #points = [(int(cand[0]), int(cand[1])) for cand in candidate if cand[3]==int(subset[0,2]) or cand[3]==int(subset[0,5])]\n if len(people_sh_points) > 0:\n for person_pts in people_sh_points:\n dist = dist=43*484.04*0.58/(euclidean(person_pts[0], person_pts[1]))\n centerx = int((person_pts[0][0] + person_pts[1][0])/2)\n centery = int((person_pts[0][1] + person_pts[1][1])/2)\n #distances.append([person_pts[0], person_pts[1], round(dist, ndigits=2)])\n distances.append([round(dist, ndigits=2), person_pts[0][0]-10, person_pts[0][1]-40, centerx, centery])\n return distances\n\ndef get_obj_obj_dist(obj1_pos, obj2_pos, img_pos, obj1_dist, obj2_dist, factor):\n # Factor pixels\n f_px = factor #obj1_dist/(484.04 / 0.58)\n # Calculate objs x-dist to image center\n obj1_aal = f_px * abs(obj1_pos[0] - img_pos[0]) # AA' - Projection of obj1 center in x axis\n obj2_bbl = f_px * abs(obj2_pos[0] - img_pos[0]) # BB' - Projection of obj2 center in x axis\n # Calculate in between dist\n dist_albl = abs(obj1_dist - obj2_dist) # Eq. 6 MA = CB' - CA'\n # Calculate\n blo = obj2_bbl * dist_albl / (obj1_aal + obj2_bbl) # Eq. 7 BM/MA = BB'/B'O\n bo = sqrt(blo**2 + obj2_bbl**2) # Eq. 8 BO = SQRT( B'O **2 + BB' ** 2 )\n dist_obj1_obj2 = round(bo * dist_albl / blo, 1) # Eq. 9 AB/MA = BO/B'O\n return [dist_obj1_obj2, obj2_pos[0], obj2_pos[1], obj2_pos[0], obj2_pos[1]]\n\nclass ObjDistanceError(Exception):\n pass\n\nclass ObjDistance():\n ''' Person or Object Distance and Appearance Class to handle dimensions, distances, etc.\n '''\n def __init__(self, obj_type, label, pos, shoulder_lenght=None):\n if not isinstance(obj_type, str):\n raise ObjDistanceError(f\"obj_type must be a string. Received {type(obj_type)}.\")\n if not obj_type in ['object', 'person']:\n raise ObjDistanceError(f\"obj_type must be 'object' or 'person'. Received {obj_type}.\")\n self.type = obj_type\n if obj_type == 'object':\n self.pos = pos # x1, y1, x2, y2\n self.height = abs(self.pos[0] - self.pos[2])\n self.width = abs(self.pos[1] - self.pos[3])\n self.centerx = int((self.pos[0] + self.pos[2])/2)\n self.centery = int((self.pos[1] + self.pos[3])/2)\n self.diagonal = euclidean((self.pos[0], self.pos[1]), (self.pos[2], self.pos[3]))\n self.label = label\n self.diagonal_real = 15.8\n self.factor = self.diagonal_real / self.diagonal\n f = 484.04 #*0.58\n self.dist= round(f*15.8/self.diagonal, 1)\n if obj_type == 'person':\n self.shoulder_lenght = shoulder_lenght\n self.dist_to_cam = None" ]
[ [ "scipy.spatial.distance.euclidean" ] ]
jkznst/detectron2
[ "790f1894134bb85b897b0912367ee54a24caf2b2" ]
[ "projects/SixDPose/sixdpose/pvnet_pose_utils.py" ]
[ "import numpy as np\nimport cv2\n\n\ndef pnp(points_3d, points_2d, camera_matrix, method=cv2.SOLVEPNP_ITERATIVE):\n try:\n dist_coeffs = pnp.dist_coeffs\n except:\n dist_coeffs = np.zeros(shape=[8, 1], dtype='float64')\n\n assert points_3d.shape[0] == points_2d.shape[0], 'points 3D and points 2D must have same number of vertices'\n if method == cv2.SOLVEPNP_EPNP:\n points_3d = np.expand_dims(points_3d, 0)\n points_2d = np.expand_dims(points_2d, 0)\n\n points_2d = np.ascontiguousarray(points_2d.astype(np.float64))\n points_3d = np.ascontiguousarray(points_3d.astype(np.float64))\n camera_matrix = camera_matrix.astype(np.float64)\n _, R_exp, t = cv2.solvePnP(points_3d,\n points_2d,\n camera_matrix,\n dist_coeffs,\n flags=method)\n # , None, None, False, cv2.SOLVEPNP_UPNP)\n\n # R_exp, t, _ = cv2.solvePnPRansac(points_3D,\n # points_2D,\n # cameraMatrix,\n # distCoeffs,\n # reprojectionError=12.0)\n\n R, _ = cv2.Rodrigues(R_exp)\n # trans_3d=np.matmul(points_3d,R.transpose())+t.transpose()\n # if np.max(trans_3d[:,2]<0):\n # R=-R\n # t=-t\n\n return np.concatenate([R, t], axis=-1)\n\ndef project(xyz, K, RT):\n \"\"\"\n xyz: [N, 3]\n K: [3, 3]\n RT: [3, 4]\n \"\"\"\n xyz = np.dot(xyz, RT[:, :3].T) + RT[:, 3:].T\n xyz = np.dot(xyz, K.T)\n xy = xyz[:, :2] / xyz[:, 2:]\n return xy\n\ndef get_3rd_point(a, b):\n direct = a - b\n return b + np.array([-direct[1], direct[0]], dtype=np.float32)\n\ndef get_dir(src_point, rot_rad):\n sn, cs = np.sin(rot_rad), np.cos(rot_rad)\n\n src_result = [0, 0]\n src_result[0] = src_point[0] * cs - src_point[1] * sn\n src_result[1] = src_point[0] * sn + src_point[1] * cs\n\n return src_result\n \ndef get_affine_transform(center,\n scale,\n rot,\n output_size,\n shift=np.array([0, 0], dtype=np.float32),\n inv=0):\n if not isinstance(scale, np.ndarray) and not isinstance(scale, list):\n scale = np.array([scale, scale], dtype=np.float32)\n\n scale_tmp = scale\n src_w = scale_tmp[0]\n dst_w = output_size[0]\n dst_h = output_size[1]\n\n rot_rad = np.pi * rot / 180\n src_dir = get_dir([0, src_w * -0.5], rot_rad)\n dst_dir = np.array([0, dst_w * -0.5], np.float32)\n\n src = np.zeros((3, 2), dtype=np.float32)\n dst = np.zeros((3, 2), dtype=np.float32)\n src[0, :] = center + scale_tmp * shift\n src[1, :] = center + src_dir + scale_tmp * shift\n dst[0, :] = [dst_w * 0.5, dst_h * 0.5]\n dst[1, :] = np.array([dst_w * 0.5, dst_h * 0.5], np.float32) + dst_dir\n\n src[2:, :] = get_3rd_point(src[0, :], src[1, :])\n dst[2:, :] = get_3rd_point(dst[0, :], dst[1, :])\n\n if inv:\n trans = cv2.getAffineTransform(np.float32(dst), np.float32(src))\n else:\n trans = cv2.getAffineTransform(np.float32(src), np.float32(dst))\n\n return trans\n" ]
[ [ "numpy.dot", "numpy.expand_dims", "numpy.cos", "numpy.sin", "numpy.concatenate", "numpy.float32", "numpy.array", "numpy.zeros" ] ]
amaotone/pygtm
[ "94cd5effc10a565cb111235faec96790cc4d2bbe" ]
[ "pygtm/gtm.py" ]
[ "import numpy as np\nfrom scipy.spatial.distance import cdist\nfrom sklearn.base import BaseEstimator, TransformerMixin\nfrom sklearn.decomposition import PCA\n\n\nclass GTM(BaseEstimator, TransformerMixin):\n def __init__(self, n_components=2, n_rbfs=10, sigma=1, alpha=1e-3, n_grids=20, method='mean',\n max_iter=10, tol=1e-3, random_state=None, verbose=False):\n self.n_components = n_components\n self.n_rbfs = n_rbfs\n self.sigma = sigma\n self.alpha = alpha\n self.n_grids = n_grids\n self.max_iter = max_iter\n self.method = method\n self.tol = tol\n self.random_state = random_state\n self.verbose = verbose\n self.prev_likelihood_ = -float('inf')\n \n def get_lattice_points(self, n_grid):\n grid = np.meshgrid(*[np.linspace(-1, 1, n_grid + 1) for _ in range(self.n_components)])\n return np.array([c.ravel() for c in grid]).T\n \n def init(self, X):\n # generate map\n self.z = self.get_lattice_points(self.n_grids)\n self.rbfs = self.get_lattice_points(self.n_rbfs)\n d = cdist(self.z, self.rbfs, 'sqeuclidean')\n self.phi = np.exp(-d / (2 * self.sigma))\n \n # init W and beta from PCA\n pca = PCA(n_components=self.n_components + 1, random_state=self.random_state)\n pca.fit(X)\n self.W = np.linalg.pinv(self.phi).dot(self.z).dot(pca.components_[:self.n_components, :])\n \n betainv1 = pca.explained_variance_[self.n_components]\n inter_dist = cdist(self.phi.dot(self.W), self.phi.dot(self.W))\n np.fill_diagonal(inter_dist, np.inf)\n betainv2 = inter_dist.min(axis=0).mean() / 2\n self.beta = 1 / max(betainv1, betainv2)\n \n def responsibility(self, X):\n p = np.exp((-self.beta / 2) * cdist(self.phi.dot(self.W), X, 'sqeuclidean'))\n return p / p.sum(axis=0)\n \n def likelihood(self, X):\n R = self.responsibility(X)\n D = X.shape[1]\n k1 = (D / 2) * np.log(self.beta / (2 * np.pi))\n k2 = -(self.beta / 2) * cdist(self.phi.dot(self.W), X, 'sqeuclidean')\n return (R * (k1 + k2)).sum()\n \n def fit(self, X, y=None, **fit_params):\n self.init(X)\n \n for i in range(self.max_iter):\n R = self.responsibility(X)\n G = np.diag(R.sum(axis=1))\n self.W = np.linalg.solve(\n self.phi.T.dot(G).dot(self.phi) + (self.alpha / self.beta) * np.identity(self.phi.shape[1]),\n self.phi.T.dot(R).dot(X))\n \n self.beta = X.size / (cdist(self.phi.dot(self.W), X, 'sqeuclidean') * R).sum()\n \n likelihood = self.likelihood(X)\n diff = abs(likelihood - self.prev_likelihood_) / X.shape[0]\n self.prev_likelihood_ = likelihood\n if self.verbose:\n print('cycle #{}: likelihood: {:.3f}, diff: {:.3f}'.format(i + 1, likelihood, diff))\n \n if diff < self.tol:\n if self.verbose:\n print('converged.')\n break\n return self\n \n def transform(self, X, y=None):\n assert self.method in ('mean', 'mode')\n if self.method == 'mean':\n R = self.responsibility(X)\n return self.z.T.dot(R).T\n elif self.method == 'mode':\n return self.z[self.responsibility(X).argmax(axis=0), :]\n \n def inverse_transform(self, Xt):\n d = cdist(Xt, self.rbfs, 'sqeuclidean')\n phi = np.exp(-d / (2 * self.sigma))\n return phi.dot(self.W)\n" ]
[ [ "numpy.log", "numpy.linspace", "scipy.spatial.distance.cdist", "numpy.linalg.pinv", "numpy.identity", "numpy.fill_diagonal", "numpy.exp", "sklearn.decomposition.PCA" ] ]
tacaswell/silx
[ "67f0ac8d3fcb5764c23b2210becfe2052f98061d" ]
[ "silx/gui/plot3d/scene/primitives.py" ]
[ "# coding: utf-8\n# /*##########################################################################\n#\n# Copyright (c) 2015-2019 European Synchrotron Radiation Facility\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in\n# all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n# THE SOFTWARE.\n#\n# ###########################################################################*/\n\nfrom __future__ import absolute_import, division, unicode_literals\n\n__authors__ = [\"T. Vincent\"]\n__license__ = \"MIT\"\n__date__ = \"24/04/2018\"\n\ntry:\n from collections import abc\nexcept ImportError: # Python2 support\n import collections as abc\nimport ctypes\nfrom functools import reduce\nimport logging\nimport string\n\nimport numpy\n\nfrom silx.gui.colors import rgba\n\nfrom ... import _glutils\nfrom ..._glutils import gl\n\nfrom . import event\nfrom . import core\nfrom . import transform\nfrom . import utils\nfrom .function import Colormap, Fog\n\n_logger = logging.getLogger(__name__)\n\n\n# Geometry ####################################################################\n\nclass Geometry(core.Elem):\n \"\"\"Set of vertices with normals and colors.\n\n :param str mode: OpenGL drawing mode:\n lines, line_strip, loop, triangles, triangle_strip, fan\n :param indices: Array of vertex indices or None\n :param bool copy: True (default) to copy the data, False to use as is.\n :param str attrib0: Name of the attribute that MUST be an array.\n :param attributes: Provide list of attributes as extra parameters.\n \"\"\"\n\n _ATTR_INFO = {\n 'position': {'dims': (1, 2), 'lastDim': (2, 3, 4)},\n 'normal': {'dims': (1, 2), 'lastDim': (3,)},\n 'color': {'dims': (1, 2), 'lastDim': (3, 4)},\n }\n\n _MODE_CHECKS = { # Min, Modulo\n 'lines': (2, 2), 'line_strip': (2, 0), 'loop': (2, 0),\n 'points': (1, 0),\n 'triangles': (3, 3), 'triangle_strip': (3, 0), 'fan': (3, 0)\n }\n\n _MODES = {\n 'lines': gl.GL_LINES,\n 'line_strip': gl.GL_LINE_STRIP,\n 'loop': gl.GL_LINE_LOOP,\n\n 'points': gl.GL_POINTS,\n\n 'triangles': gl.GL_TRIANGLES,\n 'triangle_strip': gl.GL_TRIANGLE_STRIP,\n 'fan': gl.GL_TRIANGLE_FAN\n }\n\n _LINE_MODES = 'lines', 'line_strip', 'loop'\n\n _TRIANGLE_MODES = 'triangles', 'triangle_strip', 'fan'\n\n def __init__(self,\n mode,\n indices=None,\n copy=True,\n attrib0='position',\n **attributes):\n super(Geometry, self).__init__()\n\n self._attrib0 = str(attrib0)\n\n self._vbos = {} # Store current vbos\n self._unsyncAttributes = [] # Store attributes to copy to vbos\n self.__bounds = None # Cache object's bounds\n # Attribute names defining the object bounds\n self.__boundsAttributeNames = (self._attrib0,)\n\n assert mode in self._MODES\n self._mode = mode\n\n # Set attributes\n self._attributes = {}\n for name, data in attributes.items():\n self.setAttribute(name, data, copy=copy)\n\n # Set indices\n self._indices = None\n self.setIndices(indices, copy=copy)\n\n # More consistency checks\n mincheck, modulocheck = self._MODE_CHECKS[self._mode]\n if self._indices is not None:\n nbvertices = len(self._indices)\n else:\n nbvertices = self.nbVertices\n\n if nbvertices != 0:\n assert nbvertices >= mincheck\n if modulocheck != 0:\n assert (nbvertices % modulocheck) == 0\n\n @property\n def drawMode(self):\n \"\"\"Kind of primitive to render, in :attr:`_MODES` (str)\"\"\"\n return self._mode\n\n @staticmethod\n def _glReadyArray(array, copy=True):\n \"\"\"Making a contiguous array, checking float types.\n\n :param iterable array: array-like data to prepare for attribute\n :param bool copy: True to make a copy of the array, False to use as is\n \"\"\"\n # Convert single value (int, float, numpy types) to tuple\n if not isinstance(array, abc.Iterable):\n array = (array, )\n\n # Makes sure it is an array\n array = numpy.array(array, copy=False)\n\n dtype = None\n if array.dtype.kind == 'f' and array.dtype.itemsize != 4:\n # Cast to float32\n _logger.info('Cast array to float32')\n dtype = numpy.float32\n elif array.dtype.itemsize > 4:\n # Cast (u)int64 to (u)int32\n if array.dtype.kind == 'i':\n _logger.info('Cast array to int32')\n dtype = numpy.int32\n elif array.dtype.kind == 'u':\n _logger.info('Cast array to uint32')\n dtype = numpy.uint32\n\n return numpy.array(array, dtype=dtype, order='C', copy=copy)\n\n @property\n def nbVertices(self):\n \"\"\"Returns the number of vertices of current attributes.\n\n It returns None if there is no attributes.\n \"\"\"\n for array in self._attributes.values():\n if len(array.shape) == 2:\n return len(array)\n return None\n\n @property\n def attrib0(self):\n \"\"\"Attribute name that MUST be an array (str)\"\"\"\n return self._attrib0\n\n def setAttribute(self, name, array, copy=True):\n \"\"\"Set attribute with provided array.\n\n :param str name: The name of the attribute\n :param array: Array-like attribute data or None to remove attribute\n :param bool copy: True (default) to copy the data, False to use as is\n \"\"\"\n # This triggers associated GL resources to be garbage collected\n self._vbos.pop(name, None)\n\n if array is None:\n self._attributes.pop(name, None)\n\n else:\n array = self._glReadyArray(array, copy=copy)\n\n if name not in self._ATTR_INFO:\n _logger.debug('Not checking attribute %s dimensions', name)\n else:\n checks = self._ATTR_INFO[name]\n\n if (array.ndim == 1 and checks['lastDim'] == (1,) and\n len(array) > 1):\n array = array.reshape((len(array), 1))\n\n # Checks\n assert array.ndim in checks['dims'], \"Attr %s\" % name\n assert array.shape[-1] in checks['lastDim'], \"Attr %s\" % name\n\n # Makes sure attrib0 is considered as an array of values\n if name == self.attrib0 and array.ndim == 1:\n array.shape = 1, -1\n\n # Check length against another attribute array\n # Causes problems when updating\n # nbVertices = self.nbVertices\n # if array.ndim == 2 and nbVertices is not None:\n # assert len(array) == nbVertices\n\n self._attributes[name] = array\n if array.ndim == 2: # Store this in a VBO\n self._unsyncAttributes.append(name)\n\n if name in self.boundsAttributeNames: # Reset bounds\n self.__bounds = None\n\n self.notify()\n\n def getAttribute(self, name, copy=True):\n \"\"\"Returns the numpy.ndarray corresponding to the name attribute.\n\n :param str name: The name of the attribute to get.\n :param bool copy: True to get a copy (default),\n False to get internal array (DO NOT MODIFY)\n :return: The corresponding array or None if no corresponding attribute.\n :rtype: numpy.ndarray\n \"\"\"\n attr = self._attributes.get(name, None)\n return None if attr is None else numpy.array(attr, copy=copy)\n\n def useAttribute(self, program, name=None):\n \"\"\"Enable and bind attribute(s) for a specific program.\n\n This MUST be called with OpenGL context active and after prepareGL2\n has been called.\n\n :param GLProgram program: The program for which to set the attributes\n :param str name: The attribute name to set or None to set then all\n \"\"\"\n if name is None:\n for name in program.attributes:\n self.useAttribute(program, name)\n\n else:\n attribute = program.attributes.get(name)\n if attribute is None:\n return\n\n vboattrib = self._vbos.get(name)\n if vboattrib is not None:\n gl.glEnableVertexAttribArray(attribute)\n vboattrib.setVertexAttrib(attribute)\n\n elif name not in self._attributes:\n gl.glDisableVertexAttribArray(attribute)\n\n else:\n array = self._attributes[name]\n assert array is not None\n\n if array.ndim == 1:\n assert len(array) in (1, 2, 3, 4)\n gl.glDisableVertexAttribArray(attribute)\n _glVertexAttribFunc = getattr(\n _glutils.gl, 'glVertexAttrib{}f'.format(len(array)))\n _glVertexAttribFunc(attribute, *array)\n else:\n # TODO As is this is a never event, remove?\n gl.glEnableVertexAttribArray(attribute)\n gl.glVertexAttribPointer(\n attribute,\n array.shape[-1],\n _glutils.numpyToGLType(array.dtype),\n gl.GL_FALSE,\n 0,\n array)\n\n def setIndices(self, indices, copy=True):\n \"\"\"Set the primitive indices to use.\n\n :param indices: Array-like of uint primitive indices or None to unset\n :param bool copy: True (default) to copy the data, False to use as is\n \"\"\"\n # Trigger garbage collection of previous indices VBO if any\n self._vbos.pop('__indices__', None)\n\n if indices is None:\n self._indices = None\n else:\n indices = self._glReadyArray(indices, copy=copy).ravel()\n assert indices.dtype.name in ('uint8', 'uint16', 'uint32')\n if _logger.getEffectiveLevel() <= logging.DEBUG:\n # This might be a costy check\n assert indices.max() < self.nbVertices\n self._indices = indices\n self.notify()\n\n def getIndices(self, copy=True):\n \"\"\"Returns the numpy.ndarray corresponding to the indices.\n\n :param bool copy: True to get a copy (default),\n False to get internal array (DO NOT MODIFY)\n :return: The primitive indices array or None if not set.\n :rtype: numpy.ndarray or None\n \"\"\"\n if self._indices is None:\n return None\n else:\n return numpy.array(self._indices, copy=copy)\n\n @property\n def boundsAttributeNames(self):\n \"\"\"Tuple of attribute names defining the bounds of the object.\n\n Attributes name are taken in the given order to compute the\n (x, y, z) the bounding box, e.g.::\n\n geometry.boundsAttributeNames = 'position'\n geometry.boundsAttributeNames = 'x', 'y', 'z'\n \"\"\"\n return self.__boundsAttributeNames\n\n @boundsAttributeNames.setter\n def boundsAttributeNames(self, names):\n self.__boundsAttributeNames = tuple(str(name) for name in names)\n self.__bounds = None\n self.notify()\n\n def _bounds(self, dataBounds=False):\n if self.__bounds is None:\n if len(self.boundsAttributeNames) == 0:\n return None # No bounds\n\n self.__bounds = numpy.zeros((2, 3), dtype=numpy.float32)\n\n # Coordinates defined in one or more attributes\n index = 0\n for name in self.boundsAttributeNames:\n if index == 3:\n _logger.error(\"Too many attributes defining bounds\")\n break\n\n attribute = self._attributes[name]\n assert attribute.ndim in (1, 2)\n if attribute.ndim == 1: # Single value\n min_ = attribute\n max_ = attribute\n elif len(attribute) > 0: # Array of values, compute min/max\n min_ = numpy.nanmin(attribute, axis=0)\n max_ = numpy.nanmax(attribute, axis=0)\n else:\n min_, max_ = numpy.zeros((2, attribute.shape[1]), dtype=numpy.float32)\n\n toCopy = min(len(min_), 3-index)\n if toCopy != len(min_):\n _logger.error(\"Attribute defining bounds\"\n \" has too many dimensions\")\n\n self.__bounds[0, index:index+toCopy] = min_[:toCopy]\n self.__bounds[1, index:index+toCopy] = max_[:toCopy]\n\n index += toCopy\n\n self.__bounds[numpy.isnan(self.__bounds)] = 0. # Avoid NaNs\n\n return self.__bounds.copy()\n\n def prepareGL2(self, ctx):\n # TODO manage _vbo and multiple GL context + allow to share them !\n # TODO make one or multiple VBO depending on len(vertices),\n # TODO use a general common VBO for small amount of data\n for name in self._unsyncAttributes:\n array = self._attributes[name]\n self._vbos[name] = ctx.glCtx.makeVboAttrib(array)\n self._unsyncAttributes = []\n\n if self._indices is not None and '__indices__' not in self._vbos:\n vbo = ctx.glCtx.makeVbo(self._indices,\n usage=gl.GL_STATIC_DRAW,\n target=gl.GL_ELEMENT_ARRAY_BUFFER)\n self._vbos['__indices__'] = vbo\n\n def _draw(self, program=None, nbVertices=None):\n \"\"\"Perform OpenGL draw calls.\n\n :param GLProgram program:\n If not None, call :meth:`useAttribute` for this program.\n :param int nbVertices:\n The number of vertices to render or None to render all vertices.\n \"\"\"\n if program is not None:\n self.useAttribute(program)\n\n if self._indices is None:\n if nbVertices is None:\n nbVertices = self.nbVertices\n gl.glDrawArrays(self._MODES[self._mode], 0, nbVertices)\n else:\n if nbVertices is None:\n nbVertices = self._indices.size\n with self._vbos['__indices__']:\n gl.glDrawElements(self._MODES[self._mode],\n nbVertices,\n _glutils.numpyToGLType(self._indices.dtype),\n ctypes.c_void_p(0))\n\n\n# Lines #######################################################################\n\nclass Lines(Geometry):\n \"\"\"A set of segments\"\"\"\n _shaders = (\"\"\"\n attribute vec3 position;\n attribute vec3 normal;\n attribute vec4 color;\n\n uniform mat4 matrix;\n uniform mat4 transformMat;\n\n varying vec4 vCameraPosition;\n varying vec3 vPosition;\n varying vec3 vNormal;\n varying vec4 vColor;\n\n void main(void)\n {\n gl_Position = matrix * vec4(position, 1.0);\n vCameraPosition = transformMat * vec4(position, 1.0);\n vPosition = position;\n vNormal = normal;\n vColor = color;\n }\n \"\"\",\n string.Template(\"\"\"\n varying vec4 vCameraPosition;\n varying vec3 vPosition;\n varying vec3 vNormal;\n varying vec4 vColor;\n\n $sceneDecl\n $lightingFunction\n\n void main(void)\n {\n $scenePreCall(vCameraPosition);\n gl_FragColor = $lightingCall(vColor, vPosition, vNormal);\n $scenePostCall(vCameraPosition);\n }\n \"\"\"))\n\n def __init__(self, positions, normals=None, colors=(1., 1., 1., 1.),\n indices=None, mode='lines', width=1.):\n if mode == 'strip':\n mode = 'line_strip'\n assert mode in self._LINE_MODES\n\n self._width = width\n self._smooth = True\n\n super(Lines, self).__init__(mode, indices,\n position=positions,\n normal=normals,\n color=colors)\n\n width = event.notifyProperty('_width', converter=float,\n doc=\"Width of the line in pixels.\")\n\n smooth = event.notifyProperty(\n '_smooth',\n converter=bool,\n doc=\"Smooth line rendering enabled (bool, default: True)\")\n\n def renderGL2(self, ctx):\n # Prepare program\n isnormals = 'normal' in self._attributes\n if isnormals:\n fraglightfunction = ctx.viewport.light.fragmentDef\n else:\n fraglightfunction = ctx.viewport.light.fragmentShaderFunctionNoop\n\n fragment = self._shaders[1].substitute(\n sceneDecl=ctx.fragDecl,\n scenePreCall=ctx.fragCallPre,\n scenePostCall=ctx.fragCallPost,\n lightingFunction=fraglightfunction,\n lightingCall=ctx.viewport.light.fragmentCall)\n prog = ctx.glCtx.prog(self._shaders[0], fragment)\n prog.use()\n\n if isnormals:\n ctx.viewport.light.setupProgram(ctx, prog)\n\n gl.glLineWidth(self.width)\n\n prog.setUniformMatrix('matrix', ctx.objectToNDC.matrix)\n prog.setUniformMatrix('transformMat',\n ctx.objectToCamera.matrix,\n safe=True)\n\n ctx.setupProgram(prog)\n\n with gl.enabled(gl.GL_LINE_SMOOTH, self._smooth):\n self._draw(prog)\n\n\nclass DashedLines(Lines):\n \"\"\"Set of dashed lines\n\n This MUST be defined as a set of lines (no strip or loop).\n \"\"\"\n\n _shaders = (\"\"\"\n attribute vec3 position;\n attribute vec3 origin;\n attribute vec3 normal;\n attribute vec4 color;\n\n uniform mat4 matrix;\n uniform mat4 transformMat;\n uniform vec2 viewportSize; /* Width, height of the viewport */\n\n varying vec4 vCameraPosition;\n varying vec3 vPosition;\n varying vec3 vNormal;\n varying vec4 vColor;\n varying vec2 vOriginFragCoord;\n\n void main(void)\n {\n gl_Position = matrix * vec4(position, 1.0);\n vCameraPosition = transformMat * vec4(position, 1.0);\n vPosition = position;\n vNormal = normal;\n vColor = color;\n\n vec4 clipOrigin = matrix * vec4(origin, 1.0);\n vec4 ndcOrigin = clipOrigin / clipOrigin.w; /* Perspective divide */\n /* Convert to same frame as gl_FragCoord: lower-left, pixel center at 0.5, 0.5 */\n vOriginFragCoord = (ndcOrigin.xy + vec2(1.0, 1.0)) * 0.5 * viewportSize + vec2(0.5, 0.5);\n }\n \"\"\", # noqa\n string.Template(\"\"\"\n varying vec4 vCameraPosition;\n varying vec3 vPosition;\n varying vec3 vNormal;\n varying vec4 vColor;\n varying vec2 vOriginFragCoord;\n\n uniform vec2 dash;\n\n $sceneDecl\n $lightingFunction\n\n void main(void)\n {\n $scenePreCall(vCameraPosition);\n\n /* Discard off dash fragments */\n float lineDist = distance(vOriginFragCoord, gl_FragCoord.xy);\n if (mod(lineDist, dash.x + dash.y) > dash.x) {\n discard;\n }\n gl_FragColor = $lightingCall(vColor, vPosition, vNormal);\n\n $scenePostCall(vCameraPosition);\n }\n \"\"\"))\n\n def __init__(self, positions, colors=(1., 1., 1., 1.),\n indices=None, width=1.):\n self._dash = 1, 0\n super(DashedLines, self).__init__(positions=positions,\n colors=colors,\n indices=indices,\n mode='lines',\n width=width)\n\n @property\n def dash(self):\n \"\"\"Dash of the line as a 2-tuple of lengths in pixels: (on, off)\"\"\"\n return self._dash\n\n @dash.setter\n def dash(self, dash):\n dash = float(dash[0]), float(dash[1])\n if dash != self._dash:\n self._dash = dash\n self.notify()\n\n def getPositions(self, copy=True):\n \"\"\"Get coordinates of lines.\n\n :param bool copy: True to get a copy, False otherwise\n :returns: Coordinates of lines\n :rtype: numpy.ndarray of float32 of shape (N, 2, Ndim)\n \"\"\"\n return self.getAttribute('position', copy=copy)\n\n def setPositions(self, positions, copy=True):\n \"\"\"Set line coordinates.\n\n :param positions: Array of line coordinates\n :param bool copy: True to copy input array, False to use as is\n \"\"\"\n self.setAttribute('position', positions, copy=copy)\n # Update line origins from given positions\n origins = numpy.array(positions, copy=True, order='C')\n origins[1::2] = origins[::2]\n self.setAttribute('origin', origins, copy=False)\n\n def renderGL2(self, context):\n # Prepare program\n isnormals = 'normal' in self._attributes\n if isnormals:\n fraglightfunction = context.viewport.light.fragmentDef\n else:\n fraglightfunction = \\\n context.viewport.light.fragmentShaderFunctionNoop\n\n fragment = self._shaders[1].substitute(\n sceneDecl=context.fragDecl,\n scenePreCall=context.fragCallPre,\n scenePostCall=context.fragCallPost,\n lightingFunction=fraglightfunction,\n lightingCall=context.viewport.light.fragmentCall)\n program = context.glCtx.prog(self._shaders[0], fragment)\n program.use()\n\n if isnormals:\n context.viewport.light.setupProgram(context, program)\n\n gl.glLineWidth(self.width)\n\n program.setUniformMatrix('matrix', context.objectToNDC.matrix)\n program.setUniformMatrix('transformMat',\n context.objectToCamera.matrix,\n safe=True)\n\n gl.glUniform2f(\n program.uniforms['viewportSize'], *context.viewport.size)\n gl.glUniform2f(program.uniforms['dash'], *self.dash)\n\n context.setupProgram(program)\n\n self._draw(program)\n\n\nclass Box(core.PrivateGroup):\n \"\"\"Rectangular box\"\"\"\n\n _lineIndices = numpy.array((\n (0, 1), (1, 2), (2, 3), (3, 0), # Lines with z=0\n (0, 4), (1, 5), (2, 6), (3, 7), # Lines from z=0 to z=1\n (4, 5), (5, 6), (6, 7), (7, 4)), # Lines with z=1\n dtype=numpy.uint8)\n\n _faceIndices = numpy.array(\n (0, 3, 1, 2, 5, 6, 4, 7, 7, 6, 6, 2, 7, 3, 4, 0, 5, 1),\n dtype=numpy.uint8)\n\n _vertices = numpy.array((\n # Corners with z=0\n (0., 0., 0.), (1., 0., 0.), (1., 1., 0.), (0., 1., 0.),\n # Corners with z=1\n (0., 0., 1.), (1., 0., 1.), (1., 1., 1.), (0., 1., 1.)),\n dtype=numpy.float32)\n\n def __init__(self, stroke=(1., 1., 1., 1.), fill=(1., 1., 1., 0.)):\n super(Box, self).__init__()\n\n self._fill = Mesh3D(self._vertices,\n colors=rgba(fill),\n mode='triangle_strip',\n indices=self._faceIndices)\n self._fill.visible = self.fillColor[-1] != 0.\n\n self._stroke = Lines(self._vertices,\n indices=self._lineIndices,\n colors=rgba(stroke),\n mode='lines')\n self._stroke.visible = self.strokeColor[-1] != 0.\n self.strokeWidth = 1.\n\n self._children = [self._stroke, self._fill]\n\n self._size = 1., 1., 1.\n\n @classmethod\n def getLineIndices(cls, copy=True):\n \"\"\"Returns 2D array of Box lines indices\n\n :param copy: True (default) to get a copy,\n False to get internal array (Do not modify!)\n :rtype: numpy.ndarray\n \"\"\"\n return numpy.array(cls._lineIndices, copy=copy)\n\n @classmethod\n def getVertices(cls, copy=True):\n \"\"\"Returns 2D array of Box corner coordinates.\n\n :param copy: True (default) to get a copy,\n False to get internal array (Do not modify!)\n :rtype: numpy.ndarray\n \"\"\"\n return numpy.array(cls._vertices, copy=copy)\n\n @property\n def size(self):\n \"\"\"Size of the box (sx, sy, sz)\"\"\"\n return self._size\n\n @size.setter\n def size(self, size):\n assert len(size) == 3\n size = tuple(size)\n if size != self.size:\n self._size = size\n self._fill.setAttribute(\n 'position',\n self._vertices * numpy.array(size, dtype=numpy.float32))\n self._stroke.setAttribute(\n 'position',\n self._vertices * numpy.array(size, dtype=numpy.float32))\n self.notify()\n\n @property\n def strokeSmooth(self):\n \"\"\"True to draw smooth stroke, False otherwise\"\"\"\n return self._stroke.smooth\n\n @strokeSmooth.setter\n def strokeSmooth(self, smooth):\n smooth = bool(smooth)\n if smooth != self._stroke.smooth:\n self._stroke.smooth = smooth\n self.notify()\n\n @property\n def strokeWidth(self):\n \"\"\"Width of the stroke (float)\"\"\"\n return self._stroke.width\n\n @strokeWidth.setter\n def strokeWidth(self, width):\n width = float(width)\n if width != self.strokeWidth:\n self._stroke.width = width\n self.notify()\n\n @property\n def strokeColor(self):\n \"\"\"RGBA color of the box lines (4-tuple of float in [0, 1])\"\"\"\n return tuple(self._stroke.getAttribute('color', copy=False))\n\n @strokeColor.setter\n def strokeColor(self, color):\n color = rgba(color)\n if color != self.strokeColor:\n self._stroke.setAttribute('color', color)\n # Fully transparent = hidden\n self._stroke.visible = color[-1] != 0.\n self.notify()\n\n @property\n def fillColor(self):\n \"\"\"RGBA color of the box faces (4-tuple of float in [0, 1])\"\"\"\n return tuple(self._fill.getAttribute('color', copy=False))\n\n @fillColor.setter\n def fillColor(self, color):\n color = rgba(color)\n if color != self.fillColor:\n self._fill.setAttribute('color', color)\n # Fully transparent = hidden\n self._fill.visible = color[-1] != 0.\n self.notify()\n\n @property\n def fillCulling(self):\n return self._fill.culling\n\n @fillCulling.setter\n def fillCulling(self, culling):\n self._fill.culling = culling\n\n\nclass Axes(Lines):\n \"\"\"3D RGB orthogonal axes\"\"\"\n _vertices = numpy.array(((0., 0., 0.), (1., 0., 0.),\n (0., 0., 0.), (0., 1., 0.),\n (0., 0., 0.), (0., 0., 1.)),\n dtype=numpy.float32)\n\n _colors = numpy.array(((255, 0, 0, 255), (255, 0, 0, 255),\n (0, 255, 0, 255), (0, 255, 0, 255),\n (0, 0, 255, 255), (0, 0, 255, 255)),\n dtype=numpy.uint8)\n\n def __init__(self):\n super(Axes, self).__init__(self._vertices,\n colors=self._colors,\n width=3.)\n self._size = 1., 1., 1.\n\n @property\n def size(self):\n \"\"\"Size of the axes (sx, sy, sz)\"\"\"\n return self._size\n\n @size.setter\n def size(self, size):\n assert len(size) == 3\n size = tuple(size)\n if size != self.size:\n self._size = size\n self.setAttribute(\n 'position',\n self._vertices * numpy.array(size, dtype=numpy.float32))\n self.notify()\n\n\nclass BoxWithAxes(Lines):\n \"\"\"Rectangular box with RGB OX, OY, OZ axes\n\n :param color: RGBA color of the box\n \"\"\"\n\n _vertices = numpy.array((\n # Axes corners\n (0., 0., 0.), (1., 0., 0.),\n (0., 0., 0.), (0., 1., 0.),\n (0., 0., 0.), (0., 0., 1.),\n # Box corners with z=0\n (1., 0., 0.), (1., 1., 0.), (0., 1., 0.),\n # Box corners with z=1\n (0., 0., 1.), (1., 0., 1.), (1., 1., 1.), (0., 1., 1.)),\n dtype=numpy.float32)\n\n _axesColors = numpy.array(((1., 0., 0., 1.), (1., 0., 0., 1.),\n (0., 1., 0., 1.), (0., 1., 0., 1.),\n (0., 0., 1., 1.), (0., 0., 1., 1.)),\n dtype=numpy.float32)\n\n _lineIndices = numpy.array((\n (0, 1), (2, 3), (4, 5), # Axes lines\n (6, 7), (7, 8), # Box lines with z=0\n (6, 10), (7, 11), (8, 12), # Box lines from z=0 to z=1\n (9, 10), (10, 11), (11, 12), (12, 9)), # Box lines with z=1\n dtype=numpy.uint8)\n\n def __init__(self, color=(1., 1., 1., 1.)):\n self._color = (1., 1., 1., 1.)\n colors = numpy.ones((len(self._vertices), 4), dtype=numpy.float32)\n colors[:len(self._axesColors), :] = self._axesColors\n\n super(BoxWithAxes, self).__init__(self._vertices,\n indices=self._lineIndices,\n colors=colors,\n width=2.)\n self._size = 1., 1., 1.\n self.color = color\n\n @property\n def color(self):\n \"\"\"The RGBA color to use for the box: 4 float in [0, 1]\"\"\"\n return self._color\n\n @color.setter\n def color(self, color):\n color = rgba(color)\n if color != self._color:\n self._color = color\n colors = numpy.empty((len(self._vertices), 4), dtype=numpy.float32)\n colors[:len(self._axesColors), :] = self._axesColors\n colors[len(self._axesColors):, :] = self._color\n self.setAttribute('color', colors) # Do the notification\n\n @property\n def size(self):\n \"\"\"Size of the axes (sx, sy, sz)\"\"\"\n return self._size\n\n @size.setter\n def size(self, size):\n assert len(size) == 3\n size = tuple(size)\n if size != self.size:\n self._size = size\n self.setAttribute(\n 'position',\n self._vertices * numpy.array(size, dtype=numpy.float32))\n self.notify()\n\n\nclass PlaneInGroup(core.PrivateGroup):\n \"\"\"A plane using its parent bounds to display a contour.\n\n If plane is outside the bounds of its parent, it is not visible.\n\n Cannot set the transform attribute of this primitive.\n This primitive never has any bounds.\n \"\"\"\n # TODO inherit from Lines directly?, make sure the plane remains visible?\n\n def __init__(self, point=(0., 0., 0.), normal=(0., 0., 1.)):\n super(PlaneInGroup, self).__init__()\n self._cache = None, None # Store bounds, vertices\n self._outline = None\n\n self._color = None\n self.color = 1., 1., 1., 1. # Set _color\n self._width = 2.\n self._strokeVisible = True\n\n self._plane = utils.Plane(point, normal)\n self._plane.addListener(self._planeChanged)\n\n def moveToCenter(self):\n \"\"\"Place the plane at the center of the data, not changing orientation.\n \"\"\"\n if self.parent is not None:\n bounds = self.parent.bounds(dataBounds=True)\n if bounds is not None:\n center = (bounds[0] + bounds[1]) / 2.\n _logger.debug('Moving plane to center: %s', str(center))\n self.plane.point = center\n\n @property\n def color(self):\n \"\"\"Plane outline color (array of 4 float in [0, 1]).\"\"\"\n return self._color.copy()\n\n @color.setter\n def color(self, color):\n self._color = numpy.array(color, copy=True, dtype=numpy.float32)\n if self._outline is not None:\n self._outline.setAttribute('color', self._color)\n self.notify() # This is OK as Lines are rebuild for each rendering\n\n @property\n def width(self):\n \"\"\"Width of the plane stroke in pixels\"\"\"\n return self._width\n\n @width.setter\n def width(self, width):\n self._width = float(width)\n if self._outline is not None:\n self._outline.width = self._width # Sync width\n\n @property\n def strokeVisible(self):\n \"\"\"Whether surrounding stroke is visible or not (bool).\"\"\"\n return self._strokeVisible\n\n @strokeVisible.setter\n def strokeVisible(self, visible):\n self._strokeVisible = bool(visible)\n if self._outline is not None:\n self._outline.visible = self._strokeVisible\n\n # Plane access\n\n @property\n def plane(self):\n \"\"\"The plane parameters in the frame of the object.\"\"\"\n return self._plane\n\n def _planeChanged(self, source):\n \"\"\"Listener of plane changes: clear cache and notify listeners.\"\"\"\n self._cache = None, None\n self.notify()\n\n # Disable some scene features\n\n @property\n def transforms(self):\n # Ready-only transforms to prevent using it\n return self._transforms\n\n def _bounds(self, dataBounds=False):\n # This is bound less as it uses the bounds of its parent.\n return None\n\n @property\n def contourVertices(self):\n \"\"\"The vertices of the contour of the plane/bounds intersection.\"\"\"\n parent = self.parent\n if parent is None:\n return None # No parent: no vertices\n\n bounds = parent.bounds(dataBounds=True)\n if bounds is None:\n return None # No bounds: no vertices\n\n # Check if cache is valid and return it\n cachebounds, cachevertices = self._cache\n if numpy.all(numpy.equal(bounds, cachebounds)):\n return cachevertices\n\n # Cache is not OK, rebuild it\n boxVertices = Box.getVertices(copy=True)\n boxVertices = bounds[0] + boxVertices * (bounds[1] - bounds[0])\n lineIndices = Box.getLineIndices(copy=False)\n vertices = utils.boxPlaneIntersect(\n boxVertices, lineIndices, self.plane.normal, self.plane.point)\n\n self._cache = bounds, vertices if len(vertices) != 0 else None\n\n return self._cache[1]\n\n @property\n def center(self):\n \"\"\"The center of the plane/bounds intersection points.\"\"\"\n if not self.isValid:\n return None\n else:\n return numpy.mean(self.contourVertices, axis=0)\n\n @property\n def isValid(self):\n \"\"\"True if a contour is defined, False otherwise.\"\"\"\n return self.plane.isPlane and self.contourVertices is not None\n\n def prepareGL2(self, ctx):\n if self.isValid:\n if self._outline is None: # Init outline\n self._outline = Lines(self.contourVertices,\n mode='loop',\n colors=self.color)\n self._outline.width = self._width\n self._outline.visible = self._strokeVisible\n self._children.append(self._outline)\n\n # Update vertices, TODO only when necessary\n self._outline.setAttribute('position', self.contourVertices)\n\n super(PlaneInGroup, self).prepareGL2(ctx)\n\n def renderGL2(self, ctx):\n if self.isValid:\n super(PlaneInGroup, self).renderGL2(ctx)\n\n\nclass BoundedGroup(core.Group):\n \"\"\"Group with data bounds\"\"\"\n\n _shape = None # To provide a default value without overriding __init__\n\n @property\n def shape(self):\n \"\"\"Data shape (depth, height, width) of this group or None\"\"\"\n return self._shape\n\n @shape.setter\n def shape(self, shape):\n if shape is None:\n self._shape = None\n else:\n depth, height, width = shape\n self._shape = float(depth), float(height), float(width)\n\n @property\n def size(self):\n \"\"\"Data size (width, height, depth) of this group or None\"\"\"\n shape = self.shape\n if shape is None:\n return None\n else:\n return shape[2], shape[1], shape[0]\n\n @size.setter\n def size(self, size):\n if size is None:\n self.shape = None\n else:\n self.shape = size[2], size[1], size[0]\n\n def _bounds(self, dataBounds=False):\n if dataBounds and self.size is not None:\n return numpy.array(((0., 0., 0.), self.size),\n dtype=numpy.float32)\n else:\n return super(BoundedGroup, self)._bounds(dataBounds)\n\n\n# Points ######################################################################\n\nclass _Points(Geometry):\n \"\"\"Base class to render a set of points.\"\"\"\n\n DIAMOND = 'd'\n CIRCLE = 'o'\n SQUARE = 's'\n PLUS = '+'\n X_MARKER = 'x'\n ASTERISK = '*'\n H_LINE = '_'\n V_LINE = '|'\n\n SUPPORTED_MARKERS = (DIAMOND, CIRCLE, SQUARE, PLUS,\n X_MARKER, ASTERISK, H_LINE, V_LINE)\n \"\"\"List of supported markers:\n\n - 'd' diamond\n - 'o' circle\n - 's' square\n - '+' cross\n - 'x' x-cross\n - '*' asterisk\n - '_' horizontal line\n - '|' vertical line\n \"\"\"\n\n _MARKER_FUNCTIONS = {\n DIAMOND: \"\"\"\n float alphaSymbol(vec2 coord, float size) {\n vec2 centerCoord = abs(coord - vec2(0.5, 0.5));\n float f = centerCoord.x + centerCoord.y;\n return clamp(size * (0.5 - f), 0.0, 1.0);\n }\n \"\"\",\n CIRCLE: \"\"\"\n float alphaSymbol(vec2 coord, float size) {\n float radius = 0.5;\n float r = distance(coord, vec2(0.5, 0.5));\n return clamp(size * (radius - r), 0.0, 1.0);\n }\n \"\"\",\n SQUARE: \"\"\"\n float alphaSymbol(vec2 coord, float size) {\n return 1.0;\n }\n \"\"\",\n PLUS: \"\"\"\n float alphaSymbol(vec2 coord, float size) {\n vec2 d = abs(size * (coord - vec2(0.5, 0.5)));\n if (min(d.x, d.y) < 0.5) {\n return 1.0;\n } else {\n return 0.0;\n }\n }\n \"\"\",\n X_MARKER: \"\"\"\n float alphaSymbol(vec2 coord, float size) {\n vec2 pos = floor(size * coord) + 0.5;\n vec2 d_x = abs(pos.x + vec2(- pos.y, pos.y - size));\n if (min(d_x.x, d_x.y) <= 0.5) {\n return 1.0;\n } else {\n return 0.0;\n }\n }\n \"\"\",\n ASTERISK: \"\"\"\n float alphaSymbol(vec2 coord, float size) {\n /* Combining +, x and circle */\n vec2 d_plus = abs(size * (coord - vec2(0.5, 0.5)));\n vec2 pos = floor(size * coord) + 0.5;\n vec2 d_x = abs(pos.x + vec2(- pos.y, pos.y - size));\n if (min(d_plus.x, d_plus.y) < 0.5) {\n return 1.0;\n } else if (min(d_x.x, d_x.y) <= 0.5) {\n float r = distance(coord, vec2(0.5, 0.5));\n return clamp(size * (0.5 - r), 0.0, 1.0);\n } else {\n return 0.0;\n }\n }\n \"\"\",\n H_LINE: \"\"\"\n float alphaSymbol(vec2 coord, float size) {\n float dy = abs(size * (coord.y - 0.5));\n if (dy < 0.5) {\n return 1.0;\n } else {\n return 0.0;\n }\n }\n \"\"\",\n V_LINE: \"\"\"\n float alphaSymbol(vec2 coord, float size) {\n float dx = abs(size * (coord.x - 0.5));\n if (dx < 0.5) {\n return 1.0;\n } else {\n return 0.0;\n }\n }\n \"\"\"\n }\n\n _shaders = (string.Template(\"\"\"\n #version 120\n\n attribute float x;\n attribute float y;\n attribute float z;\n attribute $valueType value;\n attribute float size;\n\n uniform mat4 matrix;\n uniform mat4 transformMat;\n\n varying vec4 vCameraPosition;\n varying $valueType vValue;\n varying float vSize;\n\n void main(void)\n {\n vValue = value;\n\n vec4 positionVec4 = vec4(x, y, z, 1.0);\n gl_Position = matrix * positionVec4;\n vCameraPosition = transformMat * positionVec4;\n\n gl_PointSize = size;\n vSize = size;\n }\n \"\"\"),\n string.Template(\"\"\"\n #version 120\n\n varying vec4 vCameraPosition;\n varying float vSize;\n varying $valueType vValue;\n\n $valueToColorDecl\n $sceneDecl\n $alphaSymbolDecl\n\n void main(void)\n {\n $scenePreCall(vCameraPosition);\n\n float alpha = alphaSymbol(gl_PointCoord, vSize);\n\n gl_FragColor = $valueToColorCall(vValue);\n gl_FragColor.a *= alpha;\n if (gl_FragColor.a == 0.0) {\n discard;\n }\n\n $scenePostCall(vCameraPosition);\n }\n \"\"\"))\n\n _ATTR_INFO = {\n 'x': {'dims': (1, 2), 'lastDim': (1,)},\n 'y': {'dims': (1, 2), 'lastDim': (1,)},\n 'z': {'dims': (1, 2), 'lastDim': (1,)},\n 'size': {'dims': (1, 2), 'lastDim': (1,)},\n }\n\n def __init__(self, x, y, z, value, size=1., indices=None):\n super(_Points, self).__init__('points', indices,\n x=x,\n y=y,\n z=z,\n value=value,\n size=size,\n attrib0='x')\n self.boundsAttributeNames = 'x', 'y', 'z'\n self._marker = 'o'\n\n @property\n def marker(self):\n \"\"\"The marker symbol used to display the scatter plot (str)\n\n See :attr:`SUPPORTED_MARKERS` for the list of supported marker string.\n \"\"\"\n return self._marker\n\n @marker.setter\n def marker(self, marker):\n marker = str(marker)\n assert marker in self.SUPPORTED_MARKERS\n if marker != self._marker:\n self._marker = marker\n self.notify()\n\n def _shaderValueDefinition(self):\n \"\"\"Type definition, fragment shader declaration, fragment shader call\n \"\"\"\n raise NotImplementedError(\n \"This method must be implemented in subclass\")\n\n def _renderGL2PreDrawHook(self, ctx, program):\n \"\"\"Override in subclass to run code before calling gl draw\"\"\"\n pass\n\n def renderGL2(self, ctx):\n valueType, valueToColorDecl, valueToColorCall = \\\n self._shaderValueDefinition()\n vertexShader = self._shaders[0].substitute(\n valueType=valueType)\n fragmentShader = self._shaders[1].substitute(\n sceneDecl=ctx.fragDecl,\n scenePreCall=ctx.fragCallPre,\n scenePostCall=ctx.fragCallPost,\n valueType=valueType,\n valueToColorDecl=valueToColorDecl,\n valueToColorCall=valueToColorCall,\n alphaSymbolDecl=self._MARKER_FUNCTIONS[self.marker])\n program = ctx.glCtx.prog(vertexShader, fragmentShader,\n attrib0=self.attrib0)\n program.use()\n\n gl.glEnable(gl.GL_VERTEX_PROGRAM_POINT_SIZE) # OpenGL 2\n gl.glEnable(gl.GL_POINT_SPRITE) # OpenGL 2\n # gl.glEnable(gl.GL_PROGRAM_POINT_SIZE)\n\n program.setUniformMatrix('matrix', ctx.objectToNDC.matrix)\n program.setUniformMatrix('transformMat',\n ctx.objectToCamera.matrix,\n safe=True)\n\n ctx.setupProgram(program)\n\n self._renderGL2PreDrawHook(ctx, program)\n\n self._draw(program)\n\n\nclass Points(_Points):\n \"\"\"A set of data points with an associated value and size.\"\"\"\n\n _ATTR_INFO = _Points._ATTR_INFO.copy()\n _ATTR_INFO.update({'value': {'dims': (1, 2), 'lastDim': (1,)}})\n\n def __init__(self, x, y, z, value=0., size=1.,\n indices=None, colormap=None):\n super(Points, self).__init__(x=x,\n y=y,\n z=z,\n indices=indices,\n size=size,\n value=value)\n\n self._colormap = colormap or Colormap() # Default colormap\n self._colormap.addListener(self._cmapChanged)\n\n @property\n def colormap(self):\n \"\"\"The colormap used to render the image\"\"\"\n return self._colormap\n\n def _cmapChanged(self, source, *args, **kwargs):\n \"\"\"Broadcast colormap changes\"\"\"\n self.notify(*args, **kwargs)\n\n def _shaderValueDefinition(self):\n \"\"\"Type definition, fragment shader declaration, fragment shader call\n \"\"\"\n return 'float', self.colormap.decl, self.colormap.call\n\n def _renderGL2PreDrawHook(self, ctx, program):\n \"\"\"Set-up colormap before calling gl draw\"\"\"\n self.colormap.setupProgram(ctx, program)\n\n\nclass ColorPoints(_Points):\n \"\"\"A set of points with an associated color and size.\"\"\"\n\n _ATTR_INFO = _Points._ATTR_INFO.copy()\n _ATTR_INFO.update({'value': {'dims': (1, 2), 'lastDim': (4,)}})\n\n def __init__(self, x, y, z, color=(1., 1., 1., 1.), size=1.,\n indices=None):\n super(ColorPoints, self).__init__(x=x,\n y=y,\n z=z,\n indices=indices,\n size=size,\n value=color)\n\n def _shaderValueDefinition(self):\n \"\"\"Type definition, fragment shader declaration, fragment shader call\n \"\"\"\n return 'vec4', '', ''\n\n def setColor(self, color, copy=True):\n \"\"\"Set colors\n\n :param color: Single RGBA color or\n 2D array of color of length number of points\n :param bool copy: True to copy colors (default),\n False to use provided array (Do not modify!)\n \"\"\"\n self.setAttribute('value', color, copy=copy)\n\n def getColor(self, copy=True):\n \"\"\"Returns the color or array of colors of the points.\n\n :param copy: True to get a copy (default),\n False to return internal array (Do not modify!)\n :return: Color or array of colors\n :rtype: numpy.ndarray\n \"\"\"\n return self.getAttribute('value', copy=copy)\n\n\nclass GridPoints(Geometry):\n # GLSL 1.30 !\n \"\"\"Data points on a regular grid with an associated value and size.\"\"\"\n _shaders = (\"\"\"\n #version 130\n\n in float value;\n in float size;\n\n uniform ivec3 gridDims;\n uniform mat4 matrix;\n uniform mat4 transformMat;\n uniform vec2 valRange;\n\n out vec4 vCameraPosition;\n out float vNormValue;\n\n //ivec3 coordsFromIndex(int index, ivec3 shape)\n //{\n /*Assumes that data is stored as z-major, then y, contiguous on x\n */\n // int yxPlaneSize = shape.y * shape.x; /* nb of elem in 2d yx plane */\n // int z = index / yxPlaneSize;\n // int yxIndex = index - z * yxPlaneSize; /* index in 2d yx plane */\n // int y = yxIndex / shape.x;\n // int x = yxIndex - y * shape.x;\n // return ivec3(x, y, z);\n // }\n\n ivec3 coordsFromIndex(int index, ivec3 shape)\n {\n /*Assumes that data is stored as x-major, then y, contiguous on z\n */\n int yzPlaneSize = shape.y * shape.z; /* nb of elem in 2d yz plane */\n int x = index / yzPlaneSize;\n int yzIndex = index - x * yzPlaneSize; /* index in 2d yz plane */\n int y = yzIndex / shape.z;\n int z = yzIndex - y * shape.z;\n return ivec3(x, y, z);\n }\n\n void main(void)\n {\n vNormValue = clamp((value - valRange.x) / (valRange.y - valRange.x),\n 0.0, 1.0);\n\n bool isValueInRange = value >= valRange.x && value <= valRange.y;\n if (isValueInRange) {\n /* Retrieve 3D position from gridIndex */\n vec3 coords = vec3(coordsFromIndex(gl_VertexID, gridDims));\n vec3 position = coords / max(vec3(gridDims) - 1.0, 1.0);\n gl_Position = matrix * vec4(position, 1.0);\n vCameraPosition = transformMat * vec4(position, 1.0);\n } else {\n gl_Position = vec4(2.0, 0.0, 0.0, 1.0); /* Get clipped */\n vCameraPosition = vec4(0.0, 0.0, 0.0, 0.0);\n }\n\n gl_PointSize = size;\n }\n \"\"\",\n string.Template(\"\"\"\n #version 130\n\n in vec4 vCameraPosition;\n in float vNormValue;\n out vec4 gl_FragColor;\n\n $sceneDecl\n\n void main(void)\n {\n $scenePreCall(vCameraPosition);\n\n gl_FragColor = vec4(0.5 * vNormValue + 0.5, 0.0, 0.0, 1.0);\n\n $scenePostCall(vCameraPosition);\n }\n \"\"\"))\n\n _ATTR_INFO = {\n 'value': {'dims': (1, 2), 'lastDim': (1,)},\n 'size': {'dims': (1, 2), 'lastDim': (1,)}\n }\n\n # TODO Add colormap, shape?\n # TODO could also use a texture to store values\n\n def __init__(self, values=0., shape=None, sizes=1., indices=None,\n minValue=None, maxValue=None):\n if isinstance(values, abc.Iterable):\n values = numpy.array(values, copy=False)\n\n # Test if gl_VertexID will overflow\n assert values.size < numpy.iinfo(numpy.int32).max\n\n self._shape = values.shape\n values = values.ravel() # 1D to add as a 1D vertex attribute\n\n else:\n assert shape is not None\n self._shape = tuple(shape)\n\n assert len(self._shape) in (1, 2, 3)\n\n super(GridPoints, self).__init__('points', indices,\n value=values,\n size=sizes)\n\n data = self.getAttribute('value', copy=False)\n self._minValue = data.min() if minValue is None else minValue\n self._maxValue = data.max() if maxValue is None else maxValue\n\n minValue = event.notifyProperty('_minValue')\n maxValue = event.notifyProperty('_maxValue')\n\n def _bounds(self, dataBounds=False):\n # Get bounds from values shape\n bounds = numpy.zeros((2, 3), dtype=numpy.float32)\n bounds[1, :] = self._shape\n bounds[1, :] -= 1\n return bounds\n\n def renderGL2(self, ctx):\n fragment = self._shaders[1].substitute(\n sceneDecl=ctx.fragDecl,\n scenePreCall=ctx.fragCallPre,\n scenePostCall=ctx.fragCallPost)\n prog = ctx.glCtx.prog(self._shaders[0], fragment)\n prog.use()\n\n gl.glEnable(gl.GL_VERTEX_PROGRAM_POINT_SIZE) # OpenGL 2\n gl.glEnable(gl.GL_POINT_SPRITE) # OpenGL 2\n # gl.glEnable(gl.GL_PROGRAM_POINT_SIZE)\n\n prog.setUniformMatrix('matrix', ctx.objectToNDC.matrix)\n prog.setUniformMatrix('transformMat',\n ctx.objectToCamera.matrix,\n safe=True)\n\n ctx.setupProgram(prog)\n\n gl.glUniform3i(prog.uniforms['gridDims'],\n self._shape[2] if len(self._shape) == 3 else 1,\n self._shape[1] if len(self._shape) >= 2 else 1,\n self._shape[0])\n\n gl.glUniform2f(prog.uniforms['valRange'], self.minValue, self.maxValue)\n\n self._draw(prog, nbVertices=reduce(lambda a, b: a * b, self._shape))\n\n\n# Spheres #####################################################################\n\nclass Spheres(Geometry):\n \"\"\"A set of spheres.\n\n Spheres are rendered as circles using points.\n This brings some limitations:\n - Do not support non-uniform scaling.\n - Assume the projection keeps ratio.\n - Do not render distorion by perspective projection.\n - If the sphere center is clipped, the whole sphere is not displayed.\n \"\"\"\n # TODO check those links\n # Accounting for perspective projection\n # http://iquilezles.org/www/articles/sphereproj/sphereproj.htm\n\n # Michael Mara and Morgan McGuire.\n # 2D Polyhedral Bounds of a Clipped, Perspective-Projected 3D Sphere\n # Journal of Computer Graphics Techniques, Vol. 2, No. 2, 2013.\n # http://jcgt.org/published/0002/02/05/paper.pdf\n # https://research.nvidia.com/publication/2d-polyhedral-bounds-clipped-perspective-projected-3d-sphere\n\n # TODO some issues with small scaling and regular grid or due to sampling\n\n _shaders = (\"\"\"\n #version 120\n\n attribute vec3 position;\n attribute vec4 color;\n attribute float radius;\n\n uniform mat4 transformMat;\n uniform mat4 projMat;\n uniform vec2 screenSize;\n\n varying vec4 vCameraPosition;\n varying vec3 vPosition;\n varying vec4 vColor;\n varying float vViewDepth;\n varying float vViewRadius;\n\n void main(void)\n {\n vCameraPosition = transformMat * vec4(position, 1.0);\n gl_Position = projMat * vCameraPosition;\n\n vPosition = gl_Position.xyz / gl_Position.w;\n\n /* From object space radius to view space diameter.\n * Do not support non-uniform scaling */\n vec4 viewSizeVector = transformMat * vec4(2.0 * radius, 0.0, 0.0, 0.0);\n float viewSize = length(viewSizeVector.xyz);\n\n /* Convert to pixel size at the xy center of the view space */\n vec4 projSize = projMat * vec4(0.5 * viewSize, 0.0,\n vCameraPosition.z, vCameraPosition.w);\n gl_PointSize = max(1.0, screenSize[0] * projSize.x / projSize.w);\n\n vColor = color;\n vViewRadius = 0.5 * viewSize;\n vViewDepth = vCameraPosition.z;\n }\n \"\"\",\n string.Template(\"\"\"\n # version 120\n\n uniform mat4 projMat;\n\n varying vec4 vCameraPosition;\n varying vec3 vPosition;\n varying vec4 vColor;\n varying float vViewDepth;\n varying float vViewRadius;\n\n $sceneDecl\n $lightingFunction\n\n void main(void)\n {\n $scenePreCall(vCameraPosition);\n\n /* Get normal from point coords */\n vec3 normal;\n normal.xy = 2.0 * gl_PointCoord - vec2(1.0);\n normal.y *= -1.0; /*Invert y to match NDC orientation*/\n float sqLength = dot(normal.xy, normal.xy);\n if (sqLength > 1.0) { /* Length -> out of sphere */\n discard;\n }\n normal.z = sqrt(1.0 - sqLength);\n\n /*Lighting performed in NDC*/\n /*TODO update this when lighting changed*/\n //XXX vec3 position = vPosition + vViewRadius * normal;\n gl_FragColor = $lightingCall(vColor, vPosition, normal);\n\n /*Offset depth*/\n float viewDepth = vViewDepth + vViewRadius * normal.z;\n vec2 clipZW = viewDepth * projMat[2].zw + projMat[3].zw;\n gl_FragDepth = 0.5 * (clipZW.x / clipZW.y) + 0.5;\n\n $scenePostCall(vCameraPosition);\n }\n \"\"\"))\n\n _ATTR_INFO = {\n 'position': {'dims': (2, ), 'lastDim': (2, 3, 4)},\n 'radius': {'dims': (1, 2), 'lastDim': (1, )},\n 'color': {'dims': (1, 2), 'lastDim': (3, 4)},\n }\n\n def __init__(self, positions, radius=1., colors=(1., 1., 1., 1.)):\n self.__bounds = None\n super(Spheres, self).__init__('points', None,\n position=positions,\n radius=radius,\n color=colors)\n\n def renderGL2(self, ctx):\n fragment = self._shaders[1].substitute(\n sceneDecl=ctx.fragDecl,\n scenePreCall=ctx.fragCallPre,\n scenePostCall=ctx.fragCallPost,\n lightingFunction=ctx.viewport.light.fragmentDef,\n lightingCall=ctx.viewport.light.fragmentCall)\n prog = ctx.glCtx.prog(self._shaders[0], fragment)\n prog.use()\n\n ctx.viewport.light.setupProgram(ctx, prog)\n\n gl.glEnable(gl.GL_VERTEX_PROGRAM_POINT_SIZE) # OpenGL 2\n gl.glEnable(gl.GL_POINT_SPRITE) # OpenGL 2\n # gl.glEnable(gl.GL_PROGRAM_POINT_SIZE)\n\n prog.setUniformMatrix('projMat', ctx.projection.matrix)\n prog.setUniformMatrix('transformMat',\n ctx.objectToCamera.matrix,\n safe=True)\n\n ctx.setupProgram(prog)\n\n gl.glUniform2f(prog.uniforms['screenSize'], *ctx.viewport.size)\n\n self._draw(prog)\n\n def _bounds(self, dataBounds=False):\n if self.__bounds is None:\n self.__bounds = numpy.zeros((2, 3), dtype=numpy.float32)\n # Support vertex with to 2 to 4 coordinates\n positions = self._attributes['position']\n radius = self._attributes['radius']\n self.__bounds[0, :positions.shape[1]] = \\\n (positions - radius).min(axis=0)[:3]\n self.__bounds[1, :positions.shape[1]] = \\\n (positions + radius).max(axis=0)[:3]\n return self.__bounds.copy()\n\n\n# Meshes ######################################################################\n\nclass Mesh3D(Geometry):\n \"\"\"A conventional 3D mesh\"\"\"\n\n _shaders = (\"\"\"\n attribute vec3 position;\n attribute vec3 normal;\n attribute vec4 color;\n\n uniform mat4 matrix;\n uniform mat4 transformMat;\n //uniform mat3 matrixInvTranspose;\n\n varying vec4 vCameraPosition;\n varying vec3 vPosition;\n varying vec3 vNormal;\n varying vec4 vColor;\n\n void main(void)\n {\n vCameraPosition = transformMat * vec4(position, 1.0);\n //vNormal = matrixInvTranspose * normalize(normal);\n vPosition = position;\n vNormal = normal;\n vColor = color;\n gl_Position = matrix * vec4(position, 1.0);\n }\n \"\"\",\n string.Template(\"\"\"\n varying vec4 vCameraPosition;\n varying vec3 vPosition;\n varying vec3 vNormal;\n varying vec4 vColor;\n\n $sceneDecl\n $lightingFunction\n\n void main(void)\n {\n $scenePreCall(vCameraPosition);\n\n gl_FragColor = $lightingCall(vColor, vPosition, vNormal);\n\n $scenePostCall(vCameraPosition);\n }\n \"\"\"))\n\n def __init__(self,\n positions,\n colors,\n normals=None,\n mode='triangles',\n indices=None,\n copy=True):\n assert mode in self._TRIANGLE_MODES\n super(Mesh3D, self).__init__(mode, indices,\n position=positions,\n normal=normals,\n color=colors,\n copy=copy)\n\n self._culling = None\n\n @property\n def culling(self):\n \"\"\"Face culling (str)\n\n One of 'back', 'front' or None.\n \"\"\"\n return self._culling\n\n @culling.setter\n def culling(self, culling):\n assert culling in ('back', 'front', None)\n if culling != self._culling:\n self._culling = culling\n self.notify()\n\n def renderGL2(self, ctx):\n isnormals = 'normal' in self._attributes\n if isnormals:\n fragLightFunction = ctx.viewport.light.fragmentDef\n else:\n fragLightFunction = ctx.viewport.light.fragmentShaderFunctionNoop\n\n fragment = self._shaders[1].substitute(\n sceneDecl=ctx.fragDecl,\n scenePreCall=ctx.fragCallPre,\n scenePostCall=ctx.fragCallPost,\n lightingFunction=fragLightFunction,\n lightingCall=ctx.viewport.light.fragmentCall)\n prog = ctx.glCtx.prog(self._shaders[0], fragment)\n prog.use()\n\n if isnormals:\n ctx.viewport.light.setupProgram(ctx, prog)\n\n if self.culling is not None:\n cullFace = gl.GL_FRONT if self.culling == 'front' else gl.GL_BACK\n gl.glCullFace(cullFace)\n gl.glEnable(gl.GL_CULL_FACE)\n\n prog.setUniformMatrix('matrix', ctx.objectToNDC.matrix)\n prog.setUniformMatrix('transformMat',\n ctx.objectToCamera.matrix,\n safe=True)\n\n ctx.setupProgram(prog)\n\n self._draw(prog)\n\n if self.culling is not None:\n gl.glDisable(gl.GL_CULL_FACE)\n\n\nclass ColormapMesh3D(Geometry):\n \"\"\"A 3D mesh with color computed from a colormap\"\"\"\n\n _shaders = (\"\"\"\n attribute vec3 position;\n attribute vec3 normal;\n attribute float value;\n\n uniform mat4 matrix;\n uniform mat4 transformMat;\n //uniform mat3 matrixInvTranspose;\n\n varying vec4 vCameraPosition;\n varying vec3 vPosition;\n varying vec3 vNormal;\n varying float vValue;\n\n void main(void)\n {\n vCameraPosition = transformMat * vec4(position, 1.0);\n //vNormal = matrixInvTranspose * normalize(normal);\n vPosition = position;\n vNormal = normal;\n vValue = value;\n gl_Position = matrix * vec4(position, 1.0);\n }\n \"\"\",\n string.Template(\"\"\"\n varying vec4 vCameraPosition;\n varying vec3 vPosition;\n varying vec3 vNormal;\n varying float vValue;\n\n $colormapDecl\n $sceneDecl\n $lightingFunction\n\n void main(void)\n {\n $scenePreCall(vCameraPosition);\n\n vec4 color = $colormapCall(vValue);\n gl_FragColor = $lightingCall(color, vPosition, vNormal);\n\n $scenePostCall(vCameraPosition);\n }\n \"\"\"))\n\n def __init__(self,\n position,\n value,\n colormap=None,\n normal=None,\n mode='triangles',\n indices=None,\n copy=True):\n super(ColormapMesh3D, self).__init__(mode, indices,\n position=position,\n normal=normal,\n value=value,\n copy=copy)\n\n self._lineWidth = 1.0\n self._lineSmooth = True\n self._culling = None\n self._colormap = colormap or Colormap() # Default colormap\n self._colormap.addListener(self._cmapChanged)\n\n lineWidth = event.notifyProperty('_lineWidth', converter=float,\n doc=\"Width of the line in pixels.\")\n\n lineSmooth = event.notifyProperty(\n '_lineSmooth',\n converter=bool,\n doc=\"Smooth line rendering enabled (bool, default: True)\")\n\n @property\n def culling(self):\n \"\"\"Face culling (str)\n\n One of 'back', 'front' or None.\n \"\"\"\n return self._culling\n\n @culling.setter\n def culling(self, culling):\n assert culling in ('back', 'front', None)\n if culling != self._culling:\n self._culling = culling\n self.notify()\n\n @property\n def colormap(self):\n \"\"\"The colormap used to render the image\"\"\"\n return self._colormap\n\n def _cmapChanged(self, source, *args, **kwargs):\n \"\"\"Broadcast colormap changes\"\"\"\n self.notify(*args, **kwargs)\n\n def renderGL2(self, ctx):\n if 'normal' in self._attributes:\n self._renderGL2(ctx)\n else: # Disable lighting\n with self.viewport.light.turnOff():\n self._renderGL2(ctx)\n\n def _renderGL2(self, ctx):\n fragment = self._shaders[1].substitute(\n sceneDecl=ctx.fragDecl,\n scenePreCall=ctx.fragCallPre,\n scenePostCall=ctx.fragCallPost,\n lightingFunction=ctx.viewport.light.fragmentDef,\n lightingCall=ctx.viewport.light.fragmentCall,\n colormapDecl=self.colormap.decl,\n colormapCall=self.colormap.call)\n program = ctx.glCtx.prog(self._shaders[0], fragment)\n program.use()\n\n ctx.viewport.light.setupProgram(ctx, program)\n ctx.setupProgram(program)\n self.colormap.setupProgram(ctx, program)\n\n if self.culling is not None:\n cullFace = gl.GL_FRONT if self.culling == 'front' else gl.GL_BACK\n gl.glCullFace(cullFace)\n gl.glEnable(gl.GL_CULL_FACE)\n\n program.setUniformMatrix('matrix', ctx.objectToNDC.matrix)\n program.setUniformMatrix('transformMat',\n ctx.objectToCamera.matrix,\n safe=True)\n\n if self.drawMode in self._LINE_MODES:\n gl.glLineWidth(self.lineWidth)\n with gl.enabled(gl.GL_LINE_SMOOTH, self.lineSmooth):\n self._draw(program)\n else:\n self._draw(program)\n\n if self.culling is not None:\n gl.glDisable(gl.GL_CULL_FACE)\n\n\n# ImageData ##################################################################\n\nclass _Image(Geometry):\n \"\"\"Base class for ImageData and ImageRgba\"\"\"\n\n _shaders = (\"\"\"\n attribute vec2 position;\n\n uniform mat4 matrix;\n uniform mat4 transformMat;\n uniform vec2 dataScale;\n\n varying vec4 vCameraPosition;\n varying vec3 vPosition;\n varying vec3 vNormal;\n varying vec2 vTexCoords;\n\n void main(void)\n {\n vec4 positionVec4 = vec4(position, 0.0, 1.0);\n vCameraPosition = transformMat * positionVec4;\n vPosition = positionVec4.xyz;\n vTexCoords = dataScale * position;\n gl_Position = matrix * positionVec4;\n }\n \"\"\",\n string.Template(\"\"\"\n varying vec4 vCameraPosition;\n varying vec3 vPosition;\n varying vec2 vTexCoords;\n uniform sampler2D data;\n uniform float alpha;\n\n $imageDecl\n $sceneDecl\n $lightingFunction\n\n void main(void)\n {\n $scenePreCall(vCameraPosition);\n\n vec4 color = imageColor(data, vTexCoords);\n color.a = alpha;\n\n vec3 normal = vec3(0.0, 0.0, 1.0);\n gl_FragColor = $lightingCall(color, vPosition, normal);\n\n $scenePostCall(vCameraPosition);\n }\n \"\"\"))\n\n _UNIT_SQUARE = numpy.array(((0., 0.), (1., 0.), (0., 1.), (1., 1.)),\n dtype=numpy.float32)\n\n def __init__(self, data, copy=True):\n super(_Image, self).__init__(mode='triangle_strip',\n position=self._UNIT_SQUARE)\n\n self._texture = None\n self._update_texture = True\n self._update_texture_filter = False\n self._data = None\n self.setData(data, copy)\n self._alpha = 1.\n self._interpolation = 'linear'\n\n self.isBackfaceVisible = True\n\n def setData(self, data, copy=True):\n assert isinstance(data, numpy.ndarray)\n\n if copy:\n data = numpy.array(data, copy=True)\n\n self._data = data\n self._update_texture = True\n # By updating the position rather than always using a unit square\n # we benefit from Geometry bounds handling\n self.setAttribute('position', self._UNIT_SQUARE * self._data.shape[:2])\n self.notify()\n\n def getData(self, copy=True):\n return numpy.array(self._data, copy=copy)\n\n @property\n def interpolation(self):\n \"\"\"The texture interpolation mode: 'linear' or 'nearest'\"\"\"\n return self._interpolation\n\n @interpolation.setter\n def interpolation(self, interpolation):\n assert interpolation in ('linear', 'nearest')\n self._interpolation = interpolation\n self._update_texture_filter = True\n self.notify()\n\n @property\n def alpha(self):\n \"\"\"Transparency of the image, float in [0, 1]\"\"\"\n return self._alpha\n\n @alpha.setter\n def alpha(self, alpha):\n self._alpha = float(alpha)\n self.notify()\n\n def _textureFormat(self):\n \"\"\"Implement this method to provide texture internal format and format\n\n :return: 2-tuple of gl flags (internalFormat, format)\n \"\"\"\n raise NotImplementedError(\n \"This method must be implemented in a subclass\")\n\n def prepareGL2(self, ctx):\n if self._texture is None or self._update_texture:\n if self._texture is not None:\n self._texture.discard()\n\n if self.interpolation == 'nearest':\n filter_ = gl.GL_NEAREST\n else:\n filter_ = gl.GL_LINEAR\n self._update_texture = False\n self._update_texture_filter = False\n if self._data.size == 0:\n self._texture = None\n else:\n internalFormat, format_ = self._textureFormat()\n self._texture = _glutils.Texture(\n internalFormat,\n self._data,\n format_,\n minFilter=filter_,\n magFilter=filter_,\n wrap=gl.GL_CLAMP_TO_EDGE)\n\n if self._update_texture_filter and self._texture is not None:\n self._update_texture_filter = False\n if self.interpolation == 'nearest':\n filter_ = gl.GL_NEAREST\n else:\n filter_ = gl.GL_LINEAR\n self._texture.minFilter = filter_\n self._texture.magFilter = filter_\n\n super(_Image, self).prepareGL2(ctx)\n\n def renderGL2(self, ctx):\n if self._texture is None:\n return # Nothing to render\n\n with self.viewport.light.turnOff():\n self._renderGL2(ctx)\n\n def _renderGL2PreDrawHook(self, ctx, program):\n \"\"\"Override in subclass to run code before calling gl draw\"\"\"\n pass\n\n def _shaderImageColorDecl(self):\n \"\"\"Returns fragment shader imageColor function declaration\"\"\"\n raise NotImplementedError(\n \"This method must be implemented in a subclass\")\n\n def _renderGL2(self, ctx):\n fragment = self._shaders[1].substitute(\n sceneDecl=ctx.fragDecl,\n scenePreCall=ctx.fragCallPre,\n scenePostCall=ctx.fragCallPost,\n lightingFunction=ctx.viewport.light.fragmentDef,\n lightingCall=ctx.viewport.light.fragmentCall,\n imageDecl=self._shaderImageColorDecl()\n )\n program = ctx.glCtx.prog(self._shaders[0], fragment)\n program.use()\n\n ctx.viewport.light.setupProgram(ctx, program)\n\n if not self.isBackfaceVisible:\n gl.glCullFace(gl.GL_BACK)\n gl.glEnable(gl.GL_CULL_FACE)\n\n program.setUniformMatrix('matrix', ctx.objectToNDC.matrix)\n program.setUniformMatrix('transformMat',\n ctx.objectToCamera.matrix,\n safe=True)\n gl.glUniform1f(program.uniforms['alpha'], self._alpha)\n\n shape = self._data.shape\n gl.glUniform2f(program.uniforms['dataScale'], 1./shape[0], 1./shape[1])\n\n gl.glUniform1i(program.uniforms['data'], self._texture.texUnit)\n\n ctx.setupProgram(program)\n\n self._texture.bind()\n\n self._renderGL2PreDrawHook(ctx, program)\n\n self._draw(program)\n\n if not self.isBackfaceVisible:\n gl.glDisable(gl.GL_CULL_FACE)\n\n\nclass ImageData(_Image):\n \"\"\"Display a 2x2 data array with a texture.\"\"\"\n\n _imageDecl = string.Template(\"\"\"\n $colormapDecl\n\n vec4 imageColor(sampler2D data, vec2 texCoords) {\n float value = texture2D(data, texCoords).r;\n vec4 color = $colormapCall(value);\n return color;\n }\n \"\"\")\n\n def __init__(self, data, copy=True, colormap=None):\n super(ImageData, self).__init__(data, copy=copy)\n\n self._colormap = colormap or Colormap() # Default colormap\n self._colormap.addListener(self._cmapChanged)\n\n def setData(self, data, copy=True):\n data = numpy.array(data, copy=copy, order='C', dtype=numpy.float32)\n # TODO support (u)int8|16\n assert data.ndim == 2\n\n super(ImageData, self).setData(data, copy=False)\n\n @property\n def colormap(self):\n \"\"\"The colormap used to render the image\"\"\"\n return self._colormap\n\n def _cmapChanged(self, source, *args, **kwargs):\n \"\"\"Broadcast colormap changes\"\"\"\n self.notify(*args, **kwargs)\n\n def _textureFormat(self):\n return gl.GL_R32F, gl.GL_RED\n\n def _renderGL2PreDrawHook(self, ctx, program):\n self.colormap.setupProgram(ctx, program)\n\n def _shaderImageColorDecl(self):\n return self._imageDecl.substitute(\n colormapDecl=self.colormap.decl,\n colormapCall=self.colormap.call)\n\n\n# ImageRgba ##################################################################\n\nclass ImageRgba(_Image):\n \"\"\"Display a 2x2 RGBA image with a texture.\n\n Supports images of float in [0, 1] and uint8.\n \"\"\"\n\n _imageDecl = \"\"\"\n vec4 imageColor(sampler2D data, vec2 texCoords) {\n vec4 color = texture2D(data, texCoords);\n return color;\n }\n \"\"\"\n\n def __init__(self, data, copy=True):\n super(ImageRgba, self).__init__(data, copy=copy)\n\n def setData(self, data, copy=True):\n data = numpy.array(data, copy=copy, order='C')\n assert data.ndim == 3\n assert data.shape[2] in (3, 4)\n if data.dtype.kind == 'f':\n if data.dtype != numpy.dtype(numpy.float32):\n _logger.warning(\"Converting image data to float32\")\n data = numpy.array(data, dtype=numpy.float32, copy=False)\n else:\n assert data.dtype == numpy.dtype(numpy.uint8)\n\n super(ImageRgba, self).setData(data, copy=False)\n\n def _textureFormat(self):\n format_ = gl.GL_RGBA if self._data.shape[2] == 4 else gl.GL_RGB\n return format_, format_\n\n def _shaderImageColorDecl(self):\n return self._imageDecl\n\n\n# Group ######################################################################\n\n# TODO lighting, clipping as groups?\n# group composition?\n\nclass GroupDepthOffset(core.Group):\n \"\"\"A group using 2-pass rendering and glDepthRange to avoid Z-fighting\"\"\"\n\n def __init__(self, children=(), epsilon=None):\n super(GroupDepthOffset, self).__init__(children)\n self._epsilon = epsilon\n self.isDepthRangeOn = True\n\n def prepareGL2(self, ctx):\n if self._epsilon is None:\n depthbits = gl.glGetInteger(gl.GL_DEPTH_BITS)\n self._epsilon = 1. / (1 << (depthbits - 1))\n\n def renderGL2(self, ctx):\n if self.isDepthRangeOn:\n self._renderGL2WithDepthRange(ctx)\n else:\n super(GroupDepthOffset, self).renderGL2(ctx)\n\n def _renderGL2WithDepthRange(self, ctx):\n # gl.glDepthFunc(gl.GL_LESS)\n with gl.enabled(gl.GL_CULL_FACE):\n gl.glCullFace(gl.GL_BACK)\n for child in self.children:\n gl.glColorMask(\n gl.GL_FALSE, gl.GL_FALSE, gl.GL_FALSE, gl.GL_FALSE)\n gl.glDepthMask(gl.GL_TRUE)\n gl.glDepthRange(self._epsilon, 1.)\n\n child.render(ctx)\n\n gl.glColorMask(\n gl.GL_TRUE, gl.GL_TRUE, gl.GL_TRUE, gl.GL_TRUE)\n gl.glDepthMask(gl.GL_FALSE)\n gl.glDepthRange(0., 1. - self._epsilon)\n\n child.render(ctx)\n\n gl.glCullFace(gl.GL_FRONT)\n for child in reversed(self.children):\n gl.glColorMask(\n gl.GL_FALSE, gl.GL_FALSE, gl.GL_FALSE, gl.GL_FALSE)\n gl.glDepthMask(gl.GL_TRUE)\n gl.glDepthRange(self._epsilon, 1.)\n\n child.render(ctx)\n\n gl.glColorMask(\n gl.GL_TRUE, gl.GL_TRUE, gl.GL_TRUE, gl.GL_TRUE)\n gl.glDepthMask(gl.GL_FALSE)\n gl.glDepthRange(0., 1. - self._epsilon)\n\n child.render(ctx)\n\n gl.glDepthMask(gl.GL_TRUE)\n gl.glDepthRange(0., 1.)\n # gl.glDepthFunc(gl.GL_LEQUAL)\n # TODO use epsilon for all rendering?\n # TODO issue with picking in depth buffer!\n\n\nclass GroupNoDepth(core.Group):\n \"\"\"A group rendering its children without writing to the depth buffer\n\n :param bool mask: True (default) to disable writing in the depth buffer\n :param bool notest: True (default) to disable depth test\n \"\"\"\n\n def __init__(self, children=(), mask=True, notest=True):\n super(GroupNoDepth, self).__init__(children)\n self._mask = bool(mask)\n self._notest = bool(notest)\n\n def renderGL2(self, ctx):\n if self._mask:\n gl.glDepthMask(gl.GL_FALSE)\n\n with gl.disabled(gl.GL_DEPTH_TEST, disable=self._notest):\n super(GroupNoDepth, self).renderGL2(ctx)\n\n if self._mask:\n gl.glDepthMask(gl.GL_TRUE)\n\n\nclass GroupBBox(core.PrivateGroup):\n \"\"\"A group displaying a bounding box around the children.\"\"\"\n\n def __init__(self, children=(), color=(1., 1., 1., 1.)):\n super(GroupBBox, self).__init__()\n self._group = core.Group(children)\n\n self._boxTransforms = transform.TransformList((transform.Translate(),))\n\n # Using 1 of 3 primitives to render axes and/or bounding box\n # To avoid z-fighting between axes and bounding box\n self._boxWithAxes = BoxWithAxes(color)\n self._boxWithAxes.smooth = False\n self._boxWithAxes.transforms = self._boxTransforms\n\n self._box = Box(stroke=color, fill=(1., 1., 1., 0.))\n self._box.strokeSmooth = False\n self._box.transforms = self._boxTransforms\n self._box.visible = False\n\n self._axes = Axes()\n self._axes.smooth = False\n self._axes.transforms = self._boxTransforms\n self._axes.visible = False\n\n self.strokeWidth = 2.\n\n self._children = [self._boxWithAxes, self._box, self._axes, self._group]\n\n def _updateBoxAndAxes(self):\n \"\"\"Update bbox and axes position and size according to children.\"\"\"\n bounds = self._group.bounds(dataBounds=True)\n if bounds is not None:\n origin = bounds[0]\n size = bounds[1] - bounds[0]\n else:\n origin, size = (0., 0., 0.), (1., 1., 1.)\n\n self._boxTransforms[0].translation = origin\n\n self._boxWithAxes.size = size\n self._box.size = size\n self._axes.size = size\n\n def _bounds(self, dataBounds=False):\n self._updateBoxAndAxes()\n return super(GroupBBox, self)._bounds(dataBounds)\n\n def prepareGL2(self, ctx):\n self._updateBoxAndAxes()\n super(GroupBBox, self).prepareGL2(ctx)\n\n # Give access to _group children\n\n @property\n def children(self):\n return self._group.children\n\n @children.setter\n def children(self, iterable):\n self._group.children = iterable\n\n # Give access to box color and stroke width\n\n @property\n def color(self):\n \"\"\"The RGBA color to use for the box: 4 float in [0, 1]\"\"\"\n return self._box.strokeColor\n\n @color.setter\n def color(self, color):\n self._box.strokeColor = color\n self._boxWithAxes.color = color\n\n @property\n def strokeWidth(self):\n \"\"\"The width of the stroke lines in pixels (float)\"\"\"\n return self._box.strokeWidth\n\n @strokeWidth.setter\n def strokeWidth(self, width):\n width = float(width)\n self._box.strokeWidth = width\n self._boxWithAxes.width = width\n self._axes.width = width\n\n # Toggle axes visibility\n\n def _updateBoxAndAxesVisibility(self, axesVisible, boxVisible):\n \"\"\"Update visible flags of box and axes primitives accordingly.\n\n :param bool axesVisible: True to display axes\n :param bool boxVisible: True to display bounding box\n \"\"\"\n self._boxWithAxes.visible = boxVisible and axesVisible\n self._box.visible = boxVisible and not axesVisible\n self._axes.visible = not boxVisible and axesVisible\n\n @property\n def axesVisible(self):\n \"\"\"Whether axes are displayed or not (bool)\"\"\"\n return self._boxWithAxes.visible or self._axes.visible\n\n @axesVisible.setter\n def axesVisible(self, visible):\n self._updateBoxAndAxesVisibility(axesVisible=bool(visible),\n boxVisible=self.boxVisible)\n\n @property\n def boxVisible(self):\n \"\"\"Whether bounding box is displayed or not (bool)\"\"\"\n return self._boxWithAxes.visible or self._box.visible\n\n @boxVisible.setter\n def boxVisible(self, visible):\n self._updateBoxAndAxesVisibility(axesVisible=self.axesVisible,\n boxVisible=bool(visible))\n\n\n# Clipping Plane ##############################################################\n\nclass ClipPlane(PlaneInGroup):\n \"\"\"A clipping plane attached to a box\"\"\"\n\n def renderGL2(self, ctx):\n super(ClipPlane, self).renderGL2(ctx)\n\n if self.visible:\n # Set-up clipping plane for following brothers\n\n # No need of perspective divide, no projection\n point = ctx.objectToCamera.transformPoint(self.plane.point,\n perspectiveDivide=False)\n normal = ctx.objectToCamera.transformNormal(self.plane.normal)\n ctx.setClipPlane(point, normal)\n\n def postRender(self, ctx):\n if self.visible:\n # Disable clip planes\n ctx.setClipPlane()\n" ]
[ [ "numpy.nanmax", "numpy.isnan", "numpy.nanmin", "numpy.dtype", "numpy.mean", "numpy.equal", "numpy.iinfo", "numpy.array", "numpy.zeros" ] ]
ludehsar/bangla-frequency-calculator
[ "8c5d2da0bf6f214f89c812a80c4287a6aa88de36" ]
[ "main.py" ]
[ "import matplotlib.font_manager as fm\nimport matplotlib.pyplot as plt\nimport matplotlib.font_manager as fm\nimport numpy as np\n\nfreq = {}\n\n\ndef read_file(filename='input.txt'):\n f = open(filename, \"r\", encoding=\"utf-8\")\n for character in f.read():\n if (character in freq):\n freq[character] += 1\n else:\n freq[character] = 1\n\n\ndef main():\n read_file()\n\n bangla_alphabets = 'অআ াই িঈ ীউ ুঊ ূঋ ৃএ েঐ ৈও োঔ ৌকখগঘঙচছজঝঞটঠডঢণতথদধনপফবভমযরলশষসহড়ঢ়য়ৎংঃ'\n bangla_alphabets = \"\".join(bangla_alphabets.split())\n sorted_counts = []\n\n for character in bangla_alphabets:\n if character in freq:\n sorted_counts.append(freq[character])\n else:\n sorted_counts.append(0)\n\n total_count = 0\n\n for value in sorted_counts:\n total_count += value\n\n sorted_counts = [100 * value / total_count for value in sorted_counts]\n\n fig, ax = plt.subplots(figsize=(40, 20))\n prop = fm.FontProperties(fname='kalpurush.ttf')\n ax.legend(prop=prop)\n\n font_dirs = ['./', ]\n font_files = fm.findSystemFonts(fontpaths=font_dirs)\n font_list = fm.createFontList(font_files)\n fm.fontManager.ttflist.extend(font_list)\n plt.tick_params(labelsize=20)\n\n plt.bar(range(len(bangla_alphabets)), sorted_counts, align='center')\n plt.xticks(np.arange(len(bangla_alphabets)),\n list(bangla_alphabets), fontfamily='Kalpurush')\n\n plt.xlabel('বর্ণ-সমূহ', fontsize=24, fontfamily='Kalpurush')\n plt.ylabel('শতকরা-হার (%)', fontsize=24, fontfamily='Kalpurush')\n\n fig.suptitle(\n 'Relative Frequencies of letters in Bengali text\\nCreated by Md. Rashedul Alam Anik', fontsize=18)\n\n plt.show()\n\n\nif __name__ == \"__main__\":\n main()\n" ]
[ [ "matplotlib.font_manager.fontManager.ttflist.extend", "matplotlib.font_manager.FontProperties", "matplotlib.pyplot.subplots", "matplotlib.pyplot.ylabel", "matplotlib.font_manager.createFontList", "matplotlib.pyplot.xlabel", "matplotlib.pyplot.show", "matplotlib.pyplot.tick_params", "matplotlib.font_manager.findSystemFonts" ] ]
WeatherGod/geopandas
[ "891c5cd73c604862fbefd014cc6536faf571d260" ]
[ "geopandas/base.py" ]
[ "from warnings import warn\n\nimport numpy as np\nimport pandas as pd\nfrom pandas import Series, DataFrame, MultiIndex\nfrom pandas.core.indexing import _NDFrameIndexer\nfrom shapely.geometry import box, MultiPoint, MultiLineString, MultiPolygon\nfrom shapely.ops import cascaded_union, unary_union\nimport shapely.affinity as affinity\n\nimport geopandas as gpd\n\ntry:\n from rtree.core import RTreeError\n HAS_SINDEX = True\nexcept ImportError:\n class RTreeError(Exception):\n pass\n HAS_SINDEX = False\n\n\ndef _geo_op(this, other, op):\n \"\"\"Operation that returns a GeoSeries\"\"\"\n if isinstance(other, GeoPandasBase):\n this = this.geometry\n crs = this.crs\n if crs != other.crs:\n warn('GeoSeries crs mismatch: {0} and {1}'.format(this.crs,\n other.crs))\n this, other = this.align(other.geometry)\n return gpd.GeoSeries([getattr(this_elem, op)(other_elem)\n for this_elem, other_elem in zip(this, other)],\n index=this.index, crs=crs)\n else:\n return gpd.GeoSeries([getattr(s, op)(other)\n for s in this.geometry],\n index=this.index, crs=this.crs)\n\n\n# TODO: think about merging with _geo_op\ndef _series_op(this, other, op, **kwargs):\n \"\"\"Geometric operation that returns a pandas Series\"\"\"\n null_val = False if op != 'distance' else np.nan\n\n if isinstance(other, GeoPandasBase):\n this = this.geometry\n this, other = this.align(other.geometry)\n return Series([getattr(this_elem, op)(other_elem, **kwargs)\n if not this_elem.is_empty | other_elem.is_empty else null_val\n for this_elem, other_elem in zip(this, other)],\n index=this.index)\n else:\n return Series([getattr(s, op)(other, **kwargs) if s else null_val\n for s in this.geometry], index=this.index)\n\n\ndef _geo_unary_op(this, op):\n \"\"\"Unary operation that returns a GeoSeries\"\"\"\n return gpd.GeoSeries([getattr(geom, op) for geom in this.geometry],\n index=this.index, crs=this.crs)\n\n\ndef _series_unary_op(this, op, null_value=False):\n \"\"\"Unary operation that returns a Series\"\"\"\n return Series([getattr(geom, op, null_value) for geom in this.geometry],\n index=this.index)\n\n\nclass GeoPandasBase(object):\n _sindex = None\n _sindex_generated = False\n\n def _generate_sindex(self):\n if not HAS_SINDEX:\n warn(\"Cannot generate spatial index: Missing package `rtree`.\")\n else:\n from geopandas.sindex import SpatialIndex\n stream = ((i, item.bounds, idx) for i, (idx, item) in\n enumerate(self.geometry.iteritems()) if\n pd.notnull(item) and not item.is_empty)\n try:\n self._sindex = SpatialIndex(stream)\n # What we really want here is an empty generator error, or\n # for the bulk loader to log that the generator was empty\n # and move on. See https://github.com/Toblerity/rtree/issues/20.\n except RTreeError:\n pass\n self._sindex_generated = True\n\n def _invalidate_sindex(self):\n \"\"\"\n Indicates that the spatial index should be re-built next\n time it's requested.\n\n \"\"\"\n self._sindex = None\n self._sindex_generated = False\n\n @property\n def area(self):\n \"\"\"Returns a ``Series`` containing the area of each geometry in the\n ``GeoSeries``.\"\"\"\n return _series_unary_op(self, 'area', null_value=np.nan)\n\n @property\n def geom_type(self):\n \"\"\"Returns a ``Series`` of strings specifying the `Geometry Type` of each\n object.\"\"\"\n return _series_unary_op(self, 'geom_type', null_value=None)\n\n @property\n def type(self):\n \"\"\"Return the geometry type of each geometry in the GeoSeries\"\"\"\n return self.geom_type\n\n @property\n def length(self):\n \"\"\"Returns a ``Series`` containing the length of each geometry.\"\"\"\n return _series_unary_op(self, 'length', null_value=np.nan)\n\n @property\n def is_valid(self):\n \"\"\"Returns a ``Series`` of ``dtype('bool')`` with value ``True`` for\n geometries that are valid.\"\"\"\n return _series_unary_op(self, 'is_valid', null_value=False)\n\n @property\n def is_empty(self):\n \"\"\"Returns a ``Series`` of ``dtype('bool')`` with value ``True`` for\n empty geometries.\"\"\"\n return _series_unary_op(self, 'is_empty', null_value=False)\n\n @property\n def is_simple(self):\n \"\"\"Returns a ``Series`` of ``dtype('bool')`` with value ``True`` for\n geometries that do not cross themselves.\n\n This is meaningful only for `LineStrings` and `LinearRings`.\n \"\"\"\n return _series_unary_op(self, 'is_simple', null_value=False)\n\n @property\n def is_ring(self):\n \"\"\"Returns a ``Series`` of ``dtype('bool')`` with value ``True`` for\n features that are closed.\"\"\"\n # operates on the exterior, so can't use _series_unary_op()\n return Series([geom.exterior.is_ring for geom in self.geometry],\n index=self.index)\n\n @property\n def has_z(self):\n \"\"\"Returns a ``Series`` of ``dtype('bool')`` with value ``True`` for\n features that have a z-component.\"\"\"\n # operates on the exterior, so can't use _series_unary_op()\n return _series_unary_op(self, 'has_z', null_value=False)\n\n #\n # Unary operations that return a GeoSeries\n #\n\n @property\n def boundary(self):\n \"\"\"Returns a ``GeoSeries`` of lower dimensional objects representing\n each geometries's set-theoretic `boundary`.\"\"\"\n return _geo_unary_op(self, 'boundary')\n\n @property\n def centroid(self):\n \"\"\"Returns a ``GeoSeries`` of points representing the centroid of each\n geometry.\"\"\"\n return _geo_unary_op(self, 'centroid')\n\n @property\n def convex_hull(self):\n \"\"\"Returns a ``GeoSeries`` of geometries representing the convex hull\n of each geometry.\n\n The convex hull of a geometry is the smallest convex `Polygon`\n containing all the points in each geometry, unless the number of points\n in the geometric object is less than three. For two points, the convex\n hull collapses to a `LineString`; for 1, a `Point`.\"\"\"\n return _geo_unary_op(self, 'convex_hull')\n\n @property\n def envelope(self):\n \"\"\"Returns a ``GeoSeries`` of geometries representing the envelope of\n each geometry.\n\n The envelope of a geometry is the bounding rectangle. That is, the\n point or smallest rectangular polygon (with sides parallel to the\n coordinate axes) that contains the geometry.\"\"\"\n return _geo_unary_op(self, 'envelope')\n\n @property\n def exterior(self):\n \"\"\"Returns a ``GeoSeries`` of LinearRings representing the outer\n boundary of each polygon in the GeoSeries.\n\n Applies to GeoSeries containing only Polygons.\n \"\"\"\n # TODO: return empty geometry for non-polygons\n return _geo_unary_op(self, 'exterior')\n\n @property\n def interiors(self):\n \"\"\"Returns a ``GeoSeries`` of InteriorRingSequences representing the\n inner rings of each polygon in the GeoSeries.\n\n Applies to GeoSeries containing only Polygons.\n \"\"\"\n # TODO: return empty list or None for non-polygons\n return _series_unary_op(self, 'interiors', null_value=False)\n\n def representative_point(self):\n \"\"\"Returns a ``GeoSeries`` of (cheaply computed) points that are\n guaranteed to be within each geometry.\n \"\"\"\n return gpd.GeoSeries([geom.representative_point()\n for geom in self.geometry],\n index=self.index)\n\n #\n # Reduction operations that return a Shapely geometry\n #\n\n @property\n def cascaded_union(self):\n \"\"\"Deprecated: Return the unary_union of all geometries\"\"\"\n return cascaded_union(self.geometry.values)\n\n @property\n def unary_union(self):\n \"\"\"Returns a geometry containing the union of all geometries in the\n ``GeoSeries``.\"\"\"\n return unary_union(self.geometry.values)\n\n #\n # Binary operations that return a pandas Series\n #\n\n def contains(self, other):\n \"\"\"Returns a ``Series`` of ``dtype('bool')`` with value ``True`` for\n each geometry that contains `other`.\n\n An object is said to contain `other` if its `interior` contains the\n `boundary` and `interior` of the other object and their boundaries do\n not touch at all.\n\n This is the inverse of :meth:`within` in the sense that the expression\n ``a.contains(b) == b.within(a)`` always evaluates to ``True``.\n\n Parameters\n ----------\n other : GeoSeries or geometric object\n The GeoSeries (elementwise) or geometric object to test if is\n contained.\n \"\"\"\n return _series_op(self, other, 'contains')\n\n def geom_equals(self, other):\n \"\"\"Returns a ``Series`` of ``dtype('bool')`` with value ``True`` for\n each geometry equal to `other`.\n\n An object is said to be equal to `other` if its set-theoretic\n `boundary`, `interior`, and `exterior` coincides with those of the\n other.\n\n Parameters\n ----------\n other : GeoSeries or geometric object\n The GeoSeries (elementwise) or geometric object to test for\n equality.\n \"\"\"\n return _series_op(self, other, 'equals')\n\n def geom_almost_equals(self, other, decimal=6):\n \"\"\"Returns a ``Series`` of ``dtype('bool')`` with value ``True`` if\n each geometry is approximately equal to `other`.\n\n Approximate equality is tested at all points to the specified `decimal`\n place precision. See also :meth:`equals`.\n\n Parameters\n ----------\n other : GeoSeries or geometric object\n The GeoSeries (elementwise) or geometric object to compare to.\n decimal : int\n Decimal place presion used when testing for approximate equality.\n \"\"\"\n # TODO: pass precision argument\n return _series_op(self, other, 'almost_equals', decimal=decimal)\n\n def geom_equals_exact(self, other, tolerance):\n \"\"\"Return True for all geometries that equal *other* to a given\n tolerance, else False\"\"\"\n # TODO: pass tolerance argument.\n return _series_op(self, other, 'equals_exact', tolerance=tolerance)\n\n def crosses(self, other):\n \"\"\"Returns a ``Series`` of ``dtype('bool')`` with value ``True`` for\n each geometry that cross `other`.\n\n An object is said to cross `other` if its `interior` intersects the\n `interior` of the other but does not contain it, and the dimension of\n the intersection is less than the dimension of the one or the other.\n\n Parameters\n ----------\n other : GeoSeries or geometric object\n The GeoSeries (elementwise) or geometric object to test if is\n crossed.\n \"\"\"\n return _series_op(self, other, 'crosses')\n\n def disjoint(self, other):\n \"\"\"Returns a ``Series`` of ``dtype('bool')`` with value ``True`` for\n each geometry disjoint to `other`.\n\n An object is said to be disjoint to `other` if its `boundary` and\n `interior` does not intersect at all with those of the other.\n\n Parameters\n ----------\n other : GeoSeries or geometric object\n The GeoSeries (elementwise) or geometric object to test if is\n disjoint.\n \"\"\"\n return _series_op(self, other, 'disjoint')\n\n def intersects(self, other):\n \"\"\"Returns a ``Series`` of ``dtype('bool')`` with value ``True`` for\n each geometry that intersects `other`.\n\n An object is said to intersect `other` if its `boundary` and `interior`\n intersects in any way with those of the other.\n\n Parameters\n ----------\n other : GeoSeries or geometric object\n The GeoSeries (elementwise) or geometric object to test if is\n intersected.\n \"\"\"\n return _series_op(self, other, 'intersects')\n\n def overlaps(self, other):\n \"\"\"Return True for all geometries that overlap *other*, else False\"\"\"\n return _series_op(self, other, 'overlaps')\n\n def touches(self, other):\n \"\"\"Returns a ``Series`` of ``dtype('bool')`` with value ``True`` for\n each geometry that touches `other`.\n\n An object is said to touch `other` if it has at least one point in\n common with `other` and its interior does not intersect with any part\n of the other.\n\n Parameters\n ----------\n other : GeoSeries or geometric object\n The GeoSeries (elementwise) or geometric object to test if is\n touched.\n \"\"\"\n return _series_op(self, other, 'touches')\n\n def within(self, other):\n \"\"\"Returns a ``Series`` of ``dtype('bool')`` with value ``True`` for\n each geometry that is within `other`.\n\n An object is said to be within `other` if its `boundary` and `interior`\n intersects only with the `interior` of the other (not its `boundary` or\n `exterior`).\n\n This is the inverse of :meth:`contains` in the sense that the\n expression ``a.within(b) == b.contains(a)`` always evaluates to\n ``True``.\n\n Parameters\n ----------\n other : GeoSeries or geometric object\n The GeoSeries (elementwise) or geometric object to test if each\n geometry is within.\n\n \"\"\"\n return _series_op(self, other, 'within')\n\n def distance(self, other):\n \"\"\"Returns a ``Series`` containing the minimum distance to `other`.\n\n Parameters\n ----------\n other : Geoseries or geometric object\n The Geoseries (elementwise) or geometric object to find the minimum\n distance to.\n \"\"\"\n return _series_op(self, other, 'distance')\n\n #\n # Binary operations that return a GeoSeries\n #\n\n def difference(self, other):\n \"\"\"Returns a ``GeoSeries`` of the points in each geometry that\n are not in `other`.\n\n Parameters\n ----------\n other : Geoseries or geometric object\n The Geoseries (elementwise) or geometric object to find the\n difference to.\n \"\"\"\n return _geo_op(self, other, 'difference')\n\n def symmetric_difference(self, other):\n \"\"\"Returns a ``GeoSeries`` of the symmetric difference of points in\n each geometry with `other`.\n\n For each geometry, the symmetric difference consists of points in the\n geometry not in `other`, and points in `other` not in the geometry.\n\n Parameters\n ----------\n other : Geoseries or geometric object\n The Geoseries (elementwise) or geometric object to find the\n symmetric difference to.\n \"\"\"\n return _geo_op(self, other, 'symmetric_difference')\n\n def union(self, other):\n \"\"\"Returns a ``GeoSeries`` of the union of points in each geometry with\n `other`.\n\n Parameters\n ----------\n other : Geoseries or geometric object\n The Geoseries (elementwise) or geometric object to find the union\n with.\n \"\"\"\n return _geo_op(self, other, 'union')\n\n def intersection(self, other):\n \"\"\"Returns a ``GeoSeries`` of the intersection of points in each\n geometry with `other`.\n\n Parameters\n ----------\n other : Geoseries or geometric object\n The Geoseries (elementwise) or geometric object to find the\n intersection with.\n \"\"\"\n return _geo_op(self, other, 'intersection')\n\n #\n # Other operations\n #\n\n @property\n def bounds(self):\n \"\"\"Returns a ``DataFrame`` with columns ``minx``, ``miny``, ``maxx``,\n ``maxy`` values containing the bounds for each geometry.\n\n See ``GeoSeries.total_bounds`` for the limits of the entire series.\n \"\"\"\n bounds = np.array([geom.bounds for geom in self.geometry])\n return DataFrame(bounds,\n columns=['minx', 'miny', 'maxx', 'maxy'],\n index=self.index)\n\n @property\n def total_bounds(self):\n \"\"\"Returns a tuple containing ``minx``, ``miny``, ``maxx``, ``maxy``\n values for the bounds of the series as a whole.\n\n See ``GeoSeries.bounds`` for the bounds of the geometries contained in\n the series.\n \"\"\"\n b = self.bounds\n return np.array((b['minx'].min(),\n b['miny'].min(),\n b['maxx'].max(),\n b['maxy'].max()))\n\n @property\n def sindex(self):\n if not self._sindex_generated:\n self._generate_sindex()\n return self._sindex\n\n def buffer(self, distance, resolution=16, **kwargs):\n \"\"\"Returns a ``GeoSeries`` of geometries representing all points within\n a given `distance` of each geometric object.\n\n See http://shapely.readthedocs.io/en/latest/manual.html#object.buffer\n for details.\n\n Parameters\n ----------\n distance : float\n The radius of the buffer.\n resolution: float\n Optional, the resolution of the buffer around each vertex.\n \"\"\"\n return gpd.GeoSeries([geom.buffer(distance, resolution, **kwargs)\n for geom in self.geometry],\n index=self.index, crs=self.crs)\n\n def simplify(self, *args, **kwargs):\n \"\"\"Returns a ``GeoSeries`` containing a simplified representation of\n each geometry.\n\n See http://shapely.readthedocs.io/en/latest/manual.html#object.simplify\n for details\n\n Parameters\n ----------\n tolerance : float\n All points in a simplified geometry will be no more than\n `tolerance` distance from the original.\n preserve_topology: bool\n False uses a quicker algorithm, but may produce self-intersecting\n or otherwise invalid geometries.\n \"\"\"\n return gpd.GeoSeries([geom.simplify(*args, **kwargs)\n for geom in self.geometry],\n index=self.index, crs=self.crs)\n\n def relate(self, other):\n raise NotImplementedError\n\n def project(self, other, normalized=False):\n \"\"\"\n Return the distance along each geometry nearest to *other*\n\n Parameters\n ----------\n other : BaseGeometry or GeoSeries\n The *other* geometry to computed projected point from.\n normalized : boolean\n If normalized is True, return the distance normalized to\n the length of the object.\n\n The project method is the inverse of interpolate.\n \"\"\"\n\n return _series_op(self, other, 'project', normalized=normalized)\n\n def interpolate(self, distance, normalized=False):\n \"\"\"\n Return a point at the specified distance along each geometry\n\n Parameters\n ----------\n distance : float or Series of floats\n Distance(s) along the geometries at which a point should be returned\n normalized : boolean\n If normalized is True, distance will be interpreted as a fraction\n of the geometric object's length.\n \"\"\"\n\n return gpd.GeoSeries([s.interpolate(distance, normalized)\n for s in self.geometry],\n index=self.index, crs=self.crs)\n\n def translate(self, xoff=0.0, yoff=0.0, zoff=0.0):\n \"\"\"Returns a ``GeoSeries`` with translated geometries.\n\n See http://shapely.readthedocs.io/en/latest/manual.html#shapely.affinity.translate\n for details.\n\n Parameters\n ----------\n xoff, yoff, zoff : float, float, float\n Amount of offset along each dimension.\n xoff, yoff, and zoff for translation along the x, y, and z\n dimensions respectively.\n \"\"\"\n return gpd.GeoSeries([affinity.translate(s, xoff, yoff, zoff)\n for s in self.geometry],\n index=self.index, crs=self.crs)\n\n def rotate(self, angle, origin='center', use_radians=False):\n \"\"\"Returns a ``GeoSeries`` with rotated geometries.\n\n See http://shapely.readthedocs.io/en/latest/manual.html#shapely.affinity.rotate\n for details.\n\n Parameters\n ----------\n angle : float\n The angle of rotation can be specified in either degrees (default)\n or radians by setting use_radians=True. Positive angles are\n counter-clockwise and negative are clockwise rotations.\n origin : string, Point, or tuple (x, y)\n The point of origin can be a keyword 'center' for the bounding box\n center (default), 'centroid' for the geometry's centroid, a Point\n object or a coordinate tuple (x, y).\n use_radians : boolean\n Whether to interpret the angle of rotation as degrees or radians\n \"\"\"\n return gpd.GeoSeries([affinity.rotate(s, angle, origin=origin,\n use_radians=use_radians) for s in self.geometry],\n index=self.index, crs=self.crs)\n\n def scale(self, xfact=1.0, yfact=1.0, zfact=1.0, origin='center'):\n \"\"\"Returns a ``GeoSeries`` with scaled geometries.\n\n The geometries can be scaled by different factors along each\n dimension. Negative scale factors will mirror or reflect coordinates.\n\n See http://shapely.readthedocs.io/en/latest/manual.html#shapely.affinity.scale\n for details.\n\n Parameters\n ----------\n xfact, yfact, zfact : float, float, float\n Scaling factors for the x, y, and z dimensions respectively.\n origin : string, Point, or tuple\n The point of origin can be a keyword 'center' for the 2D bounding\n box center (default), 'centroid' for the geometry's 2D centroid, a\n Point object or a coordinate tuple (x, y, z).\n \"\"\"\n return gpd.GeoSeries([affinity.scale(s, xfact, yfact, zfact,\n origin=origin) for s in self.geometry], index=self.index,\n crs=self.crs)\n\n def skew(self, xs=0.0, ys=0.0, origin='center', use_radians=False):\n \"\"\"Returns a ``GeoSeries`` with skewed geometries.\n\n The geometries are sheared by angles along the x and y dimensions.\n\n See http://shapely.readthedocs.io/en/latest/manual.html#shapely.affinity.skew\n for details.\n\n Parameters\n ----------\n xs, ys : float, float\n The shear angle(s) for the x and y axes respectively. These can be\n specified in either degrees (default) or radians by setting\n use_radians=True.\n origin : string, Point, or tuple (x, y)\n The point of origin can be a keyword 'center' for the bounding box\n center (default), 'centroid' for the geometry's centroid, a Point\n object or a coordinate tuple (x, y).\n use_radians : boolean\n Whether to interpret the shear angle(s) as degrees or radians\n \"\"\"\n return gpd.GeoSeries([affinity.skew(s, xs, ys, origin=origin,\n use_radians=use_radians) for s in self.geometry],\n index=self.index, crs=self.crs)\n\n def explode(self):\n \"\"\"\n Explode multi-part geometries into multiple single geometries.\n\n Single rows can become multiple rows.\n This is analogous to PostGIS's ST_Dump(). The 'path' index is the\n second level of the returned MultiIndex\n\n Returns\n ------\n A GeoSeries with a MultiIndex. The levels of the MultiIndex are the\n original index and an integer.\n\n Example\n -------\n >>> gdf # gdf is GeoSeries of MultiPoints\n 0 (POINT (0 0), POINT (1 1))\n 1 (POINT (2 2), POINT (3 3), POINT (4 4))\n\n >>> gdf.explode()\n 0 0 POINT (0 0)\n 1 POINT (1 1)\n 1 0 POINT (2 2)\n 1 POINT (3 3)\n 2 POINT (4 4)\n dtype: object\n\n \"\"\"\n index = []\n geometries = []\n for idx, s in self.geometry.iteritems():\n if s.type.startswith('Multi') or s.type == 'GeometryCollection':\n geoms = s.geoms\n idxs = [(idx, i) for i in range(len(geoms))]\n else:\n geoms = [s]\n idxs = [(idx, 0)]\n index.extend(idxs)\n geometries.extend(geoms)\n return gpd.GeoSeries(geometries,\n index=MultiIndex.from_tuples(index)).__finalize__(self)\n\n\nclass _CoordinateIndexer(_NDFrameIndexer):\n \"\"\"\n Coordinate based indexer to select by intersection with bounding box.\n\n Format of input should be ``.cx[xmin:xmax, ymin:ymax]``. Any of ``xmin``,\n ``xmax``, ``ymin``, and ``ymax`` can be provided, but input must\n include a comma separating x and y slices. That is, ``.cx[:, :]`` will\n return the full series/frame, but ``.cx[:]`` is not implemented.\n \"\"\"\n\n def _getitem_tuple(self, tup):\n obj = self.obj\n xs, ys = tup\n # handle numeric values as x and/or y coordinate index\n if type(xs) is not slice:\n xs = slice(xs, xs)\n if type(ys) is not slice:\n ys = slice(ys, ys)\n # don't know how to handle step; should this raise?\n if xs.step is not None or ys.step is not None:\n warn(\"Ignoring step - full interval is used.\")\n xmin, ymin, xmax, ymax = obj.total_bounds\n bbox = box(xs.start if xs.start is not None else xmin,\n ys.start if ys.start is not None else ymin,\n xs.stop if xs.stop is not None else xmax,\n ys.stop if ys.stop is not None else ymax)\n idx = obj.intersects(bbox)\n return obj[idx]\n" ]
[ [ "pandas.notnull", "pandas.Series", "pandas.MultiIndex.from_tuples", "pandas.DataFrame", "numpy.array" ] ]
austinkwillis/flexmatcher
[ "c771cea696014f62bf919ecf678835d8c655d04f" ]
[ "examples/movie_schemas.py" ]
[ "import pandas as pd\n\nimport flexmatcher\n# Let's assume that the mediated schema has three attributes\n# movie_name, movie_year, movie_rating\n\n# creating one sample DataFrame where the schema is (year, Movie, imdb_rating)\nvals1 = [['year', 'Movie', 'imdb_rating'],\n ['2001', 'Lord of the Rings', '8.8'],\n ['2010', 'Inception', '8.7'],\n ['1999', 'The Matrix', '8.7']]\nheader = vals1.pop(0)\ndata1 = pd.DataFrame(vals1, columns=header)\n# specifying mapping between schema of the dataframe and the mediated schema\ndata1_mapping = {'year': 'movie_year', 'imdb_rating': 'movie_rating',\n 'Movie': 'movie_name'}\n\n# creating another sample DataFrame where the schema is\n# (title, produced, popularity)\nvals2 = [['title', 'produced', 'popularity'],\n ['The Godfather', '1972', '9.2'],\n ['Silver Linings Playbook', '2012', '7.8'],\n ['The Big Short', '2015', '7.8']]\nheader = vals2.pop(0)\ndata2 = pd.DataFrame(vals2, columns=header)\n# specifying mapping between schema of the dataframe and the mediated schema\ndata2_mapping = {'popularity': 'movie_rating', 'produced': 'movie_year',\n 'title': 'movie_name'}\n\n# creating a list of dataframes and their mappings\nschema_list = [data1, data2]\nmapping_list = [data1_mapping, data2_mapping]\n\n# creating the third dataset (which is our test dataset)\n# we assume that we don't know the mapping and we want FlexMatcher to find it.\nvals3 = [['rt', 'id', 'yr'],\n ['8.5', 'The Pianist', '2002'],\n ['7.7', 'The Social Network', '2010']]\nheader = vals3.pop(0)\ndata3 = pd.DataFrame(vals3, columns=header)\n\n\n# Using Flexmatcher\nfm = flexmatcher.FlexMatcher(schema_list, mapping_list, sample_size=100)\nfm.train() # train flexmatcher\npredicted_mapping = fm.make_prediction(data3)\n\n# printing the predictions\nprint ('FlexMatcher predicted that \"rt\" should be mapped to ' +\n predicted_mapping['rt'])\nprint ('FlexMatcher predicted that \"yr\" should be mapped to ' +\n predicted_mapping['yr'])\nprint ('FlexMatcher predicted that \"id\" should be mapped to ' +\n predicted_mapping['id'])\n" ]
[ [ "pandas.DataFrame" ] ]
void-main/Paddle
[ "fabdb43c94c20b9fdf5ce87438f710e680f2588f" ]
[ "python/paddle/fluid/tests/unittests/npu/test_reduce_any_op_npu.py" ]
[ "# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom __future__ import print_function\n\nimport unittest\nimport numpy as np\nfrom op_test import OpTest, skip_check_grad_ci\nimport paddle\nimport paddle.fluid.core as core\nimport paddle.fluid as fluid\nfrom paddle.fluid import compiler, Program, program_guard\nfrom paddle.fluid.framework import convert_np_dtype_to_dtype_\n\npaddle.enable_static()\n\n\n@unittest.skipIf(not paddle.is_compiled_with_npu(),\n \"core is not compiled with NPU\")\nclass TestAny8DOp(OpTest):\n def setUp(self):\n self.set_npu()\n self.op_type = \"reduce_any\"\n self.place = paddle.NPUPlace(0)\n self.inputs = {\n 'X': np.random.randint(0, 2,\n (2, 5, 3, 2, 2, 3, 4, 2)).astype(\"bool\")\n }\n self.attrs = {'dim': (3, 5, 4)}\n self.outputs = {'Out': self.inputs['X'].any(axis=self.attrs['dim'])}\n\n def set_npu(self):\n self.__class__.use_npu = True\n\n def test_check_output(self):\n self.check_output_with_place(self.place, check_dygraph=False)\n\n\n@unittest.skipIf(not paddle.is_compiled_with_npu(),\n \"core is not compiled with NPU\")\nclass TestAnyOpWithDim(OpTest):\n def setUp(self):\n self.set_npu()\n self.op_type = \"reduce_any\"\n self.place = paddle.NPUPlace(0)\n self.inputs = {'X': np.random.randint(0, 2, (5, 6, 10)).astype(\"bool\")}\n self.attrs = {'dim': [1]}\n self.outputs = {'Out': self.inputs['X'].any(axis=1)}\n\n def set_npu(self):\n self.__class__.use_npu = True\n\n def test_check_output(self):\n self.check_output_with_place(self.place, check_dygraph=False)\n\n\n@unittest.skipIf(not paddle.is_compiled_with_npu(),\n \"core is not compiled with NPU\")\nclass TestAny8DOpWithDim(OpTest):\n def setUp(self):\n self.set_npu()\n self.op_type = \"reduce_any\"\n self.place = paddle.NPUPlace(0)\n self.inputs = {\n 'X': np.random.randint(0, 2,\n (2, 5, 3, 2, 2, 3, 4, 2)).astype(\"bool\")\n }\n self.attrs = {'dim': (3, 6)}\n self.outputs = {'Out': self.inputs['X'].any(axis=self.attrs['dim'])}\n\n def set_npu(self):\n self.__class__.use_npu = True\n\n def test_check_output(self):\n self.check_output_with_place(self.place, check_dygraph=False)\n\n\n@unittest.skipIf(not paddle.is_compiled_with_npu(),\n \"core is not compiled with NPU\")\nclass TestAnyOpWithKeepDim(OpTest):\n def setUp(self):\n self.set_npu()\n self.op_type = \"reduce_any\"\n self.place = paddle.NPUPlace(0)\n self.inputs = {'X': np.random.randint(0, 2, (5, 6, 10)).astype(\"bool\")}\n self.attrs = {'dim': (1, ), 'keep_dim': True}\n self.outputs = {\n 'Out': np.expand_dims(\n self.inputs['X'].any(axis=self.attrs['dim']), axis=1)\n }\n\n def set_npu(self):\n self.__class__.use_npu = True\n\n def test_check_output(self):\n self.check_output_with_place(self.place, check_dygraph=False)\n\n\nclass TestAny8DOpWithKeepDim(OpTest):\n def setUp(self):\n self.set_npu()\n self.op_type = \"reduce_any\"\n self.place = paddle.NPUPlace(0)\n self.inputs = {\n 'X': np.random.randint(0, 2,\n (2, 5, 3, 2, 2, 3, 4, 2)).astype(\"bool\")\n }\n self.attrs = {'dim': (1, ), 'keep_dim': True}\n self.outputs = {\n 'Out': np.expand_dims(\n self.inputs['X'].any(axis=self.attrs['dim']), axis=1)\n }\n\n def set_npu(self):\n self.__class__.use_npu = True\n\n def test_check_output(self):\n self.check_output_with_place(self.place, check_dygraph=False)\n\n\nif __name__ == '__main__':\n unittest.main()\n" ]
[ [ "numpy.random.randint" ] ]
danielballan/edrixs
[ "57fbd11ba9aaeaa393c3e2f06af41e4e386749e4" ]
[ "edrixs/basis_transform.py" ]
[ "#!/usr/bin/env python\n\nimport numpy as np\n\ndef cb_op(oper_A, t_mat):\n \"\"\"\n Change the basis of an operator :math:`\\hat{O}` from one basis :math:`A`: :math:`\\\\psi^{A}_{i}` to another basis :math:`B`: :math:`\\\\phi^{B}_{j}`. \n\n .. math::\n\n O^{\\\\prime} = T^{\\dagger} O T, \n \n T_{ij} = <\\\\psi^{A}_{i}|\\\\phi^{B}_{j}>.\n \n\n Parameters\n ----------\n oper_A : 2d array\n The matrix form of operator :math:`\\hat{O}` in basis :math:`A`.\n\n t_mat : 2d array\n The unitary transformation matrix from basis :math:`A` to basis :math:`B`, namely, :math:`T_{ij} = <\\\\psi^{A}_{i}|\\\\phi^{B}_{j}>`.\n\n Returns \n -------\n oper_B : 2d array\n The matrix form of operator :math:`\\hat{O}` in basis :math:`B`.\n \"\"\"\n\n oper_B = np.dot(np.dot(np.conj(np.transpose(t_mat)), oper_A), t_mat)\n return oper_B\n\ndef cb_op2(oper_A, TL, TR):\n \"\"\"\n Change the basis of an operator :math:`\\hat{O}`.\n\n .. math::\n\n O^{\\\\prime} = (TL)^{\\dagger} O (TR), \n \n\n Parameters\n ----------\n oper_A : 2d array\n The matrix form of operator :math:`\\hat{O}` in basis :math:`A`.\n\n TL : 2d array\n The unitary transformation matrix applied on the left.\n\n TR : 2d array\n The unitary transformation matrix applied on the right.\n\n Returns \n -------\n oper_B : 2d array\n The matrix form of operator :math:`\\hat{O}` after the transformation.\n \"\"\"\n\n oper_B = np.dot(np.dot(np.conj(np.transpose(TL)), oper_A), TR)\n return oper_B\n\ndef tmat_c2r(case, ispin=False):\n \"\"\"\n Get the unitary transformation matrix from the basis of complex spherical harmonics to real spherical harmonics.\n \n Parameters\n ----------\n case : string \n Label for different systems.\n\n - 'p': for :math:`p`-shell\n - 't2g': for :math:`t_{2g}`-shell \n - 'd': for :math:`d`-shell\n - 'f': for :math:`f`-shell\n\n ispin : logical \n Whether including spin degree of freedom or not (default: False).\n \n Returns\n ------- \n t_c2r : 2d complex array\n The transformation matrix.\n \"\"\"\n\n sqrt2 = np.sqrt(2.0)\n ci = np.complex128(0.0+1.0j)\n cone = np.complex128(1.0+0.0j)\n\n # p orbitals: px, py, pz\n if case.strip() == 'p':\n norbs = 3\n t_c2r = np.zeros((norbs, norbs), dtype=np.complex128)\n # px=1/sqrt(2)( |1,-1> - |1,1> )\n t_c2r[0,0] = cone/sqrt2\n t_c2r[2,0] = -cone/sqrt2\n # py=i/sqrt(2)( |1,-1> + |1,1> )\n t_c2r[0,1] = ci/sqrt2\n t_c2r[2,1] = ci/sqrt2\n # pz=|1,0>\n t_c2r[1,2] = cone\n\n # t2g orbitals in the t2g subspace, here, we use the so-called T-P equivalence,\n # t2g orbitals behave like the effective orbital angular momentum leff=1\n # dzx ~ py, dzy ~ px, dxy ~ pz\n elif case.strip() == 't2g':\n norbs = 3\n t_c2r = np.zeros((norbs, norbs), dtype=np.complex128)\n # dzx --> py=i/sqrt(2)( |1,-1> + |1,1> )\n t_c2r[0,0] = ci/sqrt2\n t_c2r[2,0] = ci/sqrt2\n # dzy --> px=1/sqrt(2)( |1,-1> - |1,1> )\n t_c2r[0,1] = cone/sqrt2\n t_c2r[2,1] = -cone/sqrt2\n # dxy --> pz=|1,0>\n t_c2r[1,2] = cone\n\n # d orbitals: dz2, dzx, dzy, dx2-y2, dxy\n elif case.strip() == 'd':\n norbs = 5\n t_c2r = np.zeros((norbs, norbs), dtype=np.complex128)\n # dz2=|2,0>\n t_c2r[2,0] = cone\n # dzx=1/sqrt(2)( |2,-1> - |2,1> )\n t_c2r[1,1] = cone/sqrt2 \n t_c2r[3,1] = -cone/sqrt2\n # dzy=i/sqrt(2)( |2,-1> + |2,1> )\n t_c2r[1,2] = ci/sqrt2\n t_c2r[3,2] = ci/sqrt2\n # dx2-y2=1/sqrt(2)( |2,-2> + |2,2> )\n t_c2r[0,3] = cone/sqrt2\n t_c2r[4,3] = cone/sqrt2\n # dxy=i/sqrt(2)( |2,-2> - |2,2> )\n t_c2r[0,4] = ci/sqrt2\n t_c2r[4,4] = -ci/sqrt2\n\n # f orbitals, please NOTE that this real form of the f orbitals is not the\n # basis of the representation of the cubic point group, please call the \n # function ``tmat_r2cub\" to get the transformation matrix from this basis\n # to the cubic basis that is the representation of the cubic point group.\n elif case.strip() == 'f':\n norbs = 7\n t_c2r = np.zeros((norbs, norbs), dtype=np.complex128)\n # fz3 = |3,0>\n t_c2r[3, 0] = cone \n # fxz2 = 1/sqrt(2)( |3,-1> - |3,1> )\n t_c2r[2, 1] = cone/sqrt2\n t_c2r[4, 1] = -cone/sqrt2\n # fyz2 = i/sqrt(2)( |3,-1> + |3,1> )\n t_c2r[2, 2] = ci/sqrt2\n t_c2r[4, 2] = ci/sqrt2\n # fz(x2-y2) = 1/sqrt(2)( |3,-2> + |3,2> )\n t_c2r[1, 3] = cone/sqrt2\n t_c2r[5, 3] = cone/sqrt2\n # fxyz = i/sqrt(2)( |3,-2> - |3,2> )\n t_c2r[1, 4] = ci/sqrt2\n t_c2r[5, 4] = -ci/sqrt2\n # fx(x2-3y2) = 1/sqrt(2) ( |3,-3> - |3,3> )\n t_c2r[0, 5] = cone/sqrt2\n t_c2r[6, 5] = -cone/sqrt2\n # fy(3x2-y2) = i/sqrt(2) ( |3,-3> + |3,3> )\n t_c2r[0, 6] = ci/sqrt2\n t_c2r[6, 6] = ci/sqrt2\n else:\n print(\"don't support tmat_c2r for this case: \", case)\n return\n\n # the spin order is: up dn up dn ... up dn\n if ispin:\n ntot_orbs=2*norbs\n t_c2r_spin = np.zeros((ntot_orbs,ntot_orbs), dtype=np.complex128)\n # spin up\n t_c2r_spin[0:ntot_orbs:2, 0:ntot_orbs:2] = t_c2r \n # spin dn\n t_c2r_spin[1:ntot_orbs:2, 1:ntot_orbs:2] = t_c2r \n return t_c2r_spin\n else:\n return t_c2r\n\ndef tmat_r2c(case, ispin=False):\n \"\"\"\n Get the unitary transformation matrix from the basis of complex spherical harmonics to real spherical harmonics.\n \n Parameters\n ----------\n case : string \n Label for different systems. \n\n - 'p': for :math:`p`-shell\n - 't2g': for :math:`t_{2g}`-shell \n - 'd': for :math:`d`-shell\n - 'f': for :math:`f`-shell\n\n ispin : logical \n Whether including spin degree of freedom or not (default: False).\n \n Returns\n ------- \n t_r2c : 2d complex array\n The transformation matrix.\n \"\"\"\n\n t_r2c = np.conj(np.transpose(tmat_c2r(case, ispin)))\n return t_r2c\n\ndef tmat_r2cub_f(ispin=False):\n \n \"\"\"\n Get the transformation matrix from real spherical harmonics to the cubic spherical harmonics\n that is the representation of the cubic point group, only for :math:`f` system.\n\n Parameters\n ----------\n ispin : logical\n Whether including spin degree of freedom or not (default: False).\n\n Returns\n -------\n t_r2cub : 2d complex array\n The transformation matrix.\n \"\"\"\n\n a = np.sqrt(10.0) / 4.0 + 0.0j\n b = np.sqrt(6.0) / 4.0 + 0.0j\n c = 1.0 + 0.0j\n\n norbs = 7\n t_r2cub = np.zeros((norbs,norbs), dtype=np.complex128)\n\n # T1u\n # fx3 = -sqrt(6)/4 fxz2 + sqrt(10)/4 fx(x2-3y2) \n t_r2cub[1, 0] = -b\n t_r2cub[5, 0] = a\n # fy3 = -sqrt(6)/4 fyz2 - sqrt(10)/4 fy(3x2-y2) \n t_r2cub[2, 1] = -b\n t_r2cub[6, 1] = -a\n # fz3 = fz3\n t_r2cub[0, 2] = c\n\n # T2u\n # fx(y2-z2) = -sqrt(10)/4 fxz2 - sqrt(6)/4 fx(x2-3y2)\n t_r2cub[1, 3] = -a\n t_r2cub[5, 3] = -b\n # fy(z2-x2) = sqrt(10)/4 fyz2 - sqrt(6)/4 fy(3x2-y2)\n t_r2cub[2, 4] = a\n t_r2cub[6, 4] = -b\n # fz(x2-y2) = fz(x2-y2)\n t_r2cub[3, 5] = c\n\n # A2u\n # fxyz = fxyz\n t_r2cub[4, 6] = c\n\n if ispin:\n ntot_orbs = 2 * norbs\n t_r2cub_spin = np.zeros((ntot_orbs, ntot_orbs), dtype=np.complex128)\n # spin up\n t_r2cub_spin[0:ntot_orbs:2, 0:ntot_orbs:2] = t_r2cub\n # spin dn\n t_r2cub_spin[1:ntot_orbs:2, 1:ntot_orbs:2] = t_r2cub\n return t_r2cub_spin\n else:\n return t_r2cub\n\ndef tmat_cub2r_f(ispin=False):\n \"\"\"\n Get the transformation matrix from the cubic spherical harmonics to real spherical harmonics, only for :math:`f` system.\n\n Parameters\n ---------- \n ispin : logical\n Whether including spin degree of freedom or not (default: False).\n\n Returns\n ------- \n t_cub2r : 2d complex array\n The transformation matrix.\n \"\"\"\n\n t_cub2r = np.conj( np.transpose( tmat_r2cub(ispin) ) )\n return t_cub2r\n\ndef tmat_c2j(l):\n \"\"\"\n Get the transformation matrix from the complex spherical harmonics to \n the :math:`|j^2,j_z>` basis in which the spin-oribt coupling Hamiltonian is diagonal.\n The orbital order is: \n\n :math:`|j=l-1/2, -j>, |j=l-1/2, -j+1>, ... |j=l-1/2, +j>,`\n\n :math:`|j=l+1/2, -j>, |j=l+1/2, -j+1>, ..., |j=l+1/2, +j>`.\n \n Parameters\n ----------\n l : int\n Quantum number of orbital angular momentum.\n\n Returns\n -------\n t_c2j : 2d complex array\n The transformation matrix. \n \"\"\"\n\n if l == 1:\n t_c2j = np.zeros((6, 6), dtype=np.complex128)\n t_c2j[0,0] = -np.sqrt(2.0/3.0) \n t_c2j[3,0] = np.sqrt(1.0/3.0) \n t_c2j[2,1] = -np.sqrt(1.0/3.0) \n t_c2j[5,1] = np.sqrt(2.0/3.0) \n t_c2j[1,2] = 1.0\n t_c2j[0,3] = np.sqrt(1.0/3.0)\n t_c2j[3,3] = np.sqrt(2.0/3.0)\n t_c2j[2,4] = np.sqrt(2.0/3.0)\n t_c2j[5,4] = np.sqrt(1.0/3.0)\n t_c2j[4,5] = 1.0\n\n return t_c2j\n\n elif l == 2:\n t_c2j = np.zeros((10, 10), dtype=np.complex128)\n t_c2j[0,0] = -np.sqrt(4.0/5.0)\n t_c2j[3,0] = np.sqrt(1.0/5.0)\n t_c2j[2,1] = -np.sqrt(3.0/5.0)\n t_c2j[5,1] = np.sqrt(2.0/5.0)\n t_c2j[4,2] = -np.sqrt(2.0/5.0)\n t_c2j[7,2] = np.sqrt(3.0/5.0)\n t_c2j[6,3] = -np.sqrt(1.0/5.0)\n t_c2j[9,3] = np.sqrt(4.0/5.0)\n t_c2j[1,4] = 1.0\n t_c2j[0,5] = np.sqrt(1.0/5.0)\n t_c2j[3,5] = np.sqrt(4.0/5.0)\n t_c2j[2,6] = np.sqrt(2.0/5.0)\n t_c2j[5,6] = np.sqrt(3.0/5.0)\n t_c2j[4,7] = np.sqrt(3.0/5.0)\n t_c2j[7,7] = np.sqrt(2.0/5.0)\n t_c2j[6,8] = np.sqrt(4.0/5.0)\n t_c2j[9,8] = np.sqrt(1.0/5.0)\n t_c2j[8,9] = 1.0\n\n return t_c2j\n\n elif l == 3:\n t_c2j = np.zeros((14,14), dtype=np.complex128)\n t_c2j[0,0] = -np.sqrt(6.0/7.0)\n t_c2j[3,0] = np.sqrt(1.0/7.0)\n t_c2j[2,1] = -np.sqrt(5.0/7.0)\n t_c2j[5,1] = np.sqrt(2.0/7.0)\n t_c2j[4,2] = -np.sqrt(4.0/7.0)\n t_c2j[7,2] = np.sqrt(3.0/7.0)\n t_c2j[6,3] = -np.sqrt(3.0/7.0)\n t_c2j[9,3] = np.sqrt(4.0/7.0)\n t_c2j[8,4] = -np.sqrt(2.0/7.0)\n t_c2j[11,4] = np.sqrt(5.0/7.0)\n t_c2j[10,5] = -np.sqrt(1.0/7.0)\n t_c2j[13,5] = np.sqrt(6.0/7.0)\n t_c2j[1,6] = 1.0\n t_c2j[0,7] = np.sqrt(1.0/7.0)\n t_c2j[3,7] = np.sqrt(6.0/7.0)\n t_c2j[2,8] = np.sqrt(2.0/7.0)\n t_c2j[5,8] = np.sqrt(5.0/7.0)\n t_c2j[4,9] = np.sqrt(3.0/7.0)\n t_c2j[7,9] = np.sqrt(4.0/7.0)\n t_c2j[6,10] = np.sqrt(4.0/7.0)\n t_c2j[9,10] = np.sqrt(3.0/7.0)\n t_c2j[8,11] = np.sqrt(5.0/7.0)\n t_c2j[11,11] = np.sqrt(2.0/7.0)\n t_c2j[10,12] = np.sqrt(6.0/7.0)\n t_c2j[13,12] = np.sqrt(1.0/7.0)\n t_c2j[12,13] = 1.0\n\n return t_c2j\n\n else:\n print(\"NOT Implemented for this angular momentrum !!!\", l)\n\ndef transform_utensor(umat, tmat):\n \"\"\"\n Transform the rank-4 Coulomb interaction tensor from one basis to another basis.\n\n Parameters\n ----------\n umat : 4d array\n Coulomb interaction tensor (rank-4).\n\n tmat : 2d array\n The transformation matrix.\n\n Returns\n -------\n umat_new : 4d complex array\n The Coulomb interaction tensor in the new basis.\n \"\"\"\n\n n = umat.shape[0]\n umat_new = np.zeros((n,n,n,n), dtype=np.complex128)\n\n a1,a2,a3,a4 = np.nonzero(abs(umat) > 1E-10)\n nonzero = np.stack((a1,a2,a3,a4), axis=-1)\n\n for ii,jj,kk,ll in nonzero:\n for i in range(n):\n if abs(tmat[ii,i]) < 1E-10:\n continue\n else:\n for j in range(n):\n if abs(tmat[jj,j]) < 1E-10:\n continue\n else:\n for k in range(n):\n if abs(tmat[kk,k]) < 1E-10:\n continue\n else:\n for l in range(n):\n umat_new[i,j,k,l] += np.conj(tmat[ii,i]) * np.conj(tmat[jj,j]) * umat[ii,jj,kk,ll] * tmat[kk,k] * tmat[ll,l]\n\n return umat_new\n\ndef fourier_hr2hk(norbs, nkpt, kvec, nrpt, rvec, deg_rpt, hr):\n \"\"\"\n Fourier transform a tight-binding Hamiltonian :math:`H(r)` from real space to :math:`k` space :math:`H(k)`,\n for Wannier90.\n\n Parameters\n ----------\n norbs : int\n Number of orbitals.\n\n nkpt : int \n Number of :math:`k`-points.\n\n kvec : 2d float array \n Fractional coordinate for k-points.\n\n nrpt : int \n Number of r-points.\n\n rvec : 2d float array\n Fractional coordinate for r-points.\n\n deg_rpt : int \n The degenerancy for each r-point.\n\n hr : 3d complex array \n Hamiltonian in r-space.\n\n Returns\n -------\n hk : 3d complex array\n Hamiltonian in k-space.\n \"\"\"\n\n hk = np.zeros((nkpt, norbs, norbs), dtype=np.complex128)\n for i in range(nkpt):\n for j in range(nrpt):\n coef = -2*np.pi*np.dot(kvec[i,:], rvec[j,:])\n ratio = (np.cos(coef) + np.sin(coef) * 1j) / float(deg_rpt[j])\n hk[i,:,:] = hk[i,:,:] + ratio * hr[j,:,:]\n return hk\n" ]
[ [ "numpy.complex128", "numpy.dot", "numpy.sqrt", "numpy.conj", "numpy.cos", "numpy.stack", "numpy.sin", "numpy.transpose", "numpy.zeros" ] ]
compsciencelab/pytorch-cifar
[ "4a526d0bbe53163b738602657cee220265ea6a55" ]
[ "models/densenet.py" ]
[ "'''DenseNet in PyTorch.'''\nimport math\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\n\nclass Bottleneck(nn.Module):\n def __init__(self, in_planes, growth_rate):\n super(Bottleneck, self).__init__()\n self.bn1 = nn.BatchNorm2d(in_planes)\n self.conv1 = nn.Conv2d(in_planes, 4*growth_rate, kernel_size=1, bias=False)\n self.bn2 = nn.BatchNorm2d(4*growth_rate)\n self.conv2 = nn.Conv2d(4*growth_rate, growth_rate, kernel_size=3, padding=1, bias=False)\n\n def forward(self, x):\n out = self.conv1(F.relu(self.bn1(x)))\n out = self.conv2(F.relu(self.bn2(out)))\n out = torch.cat([out,x], 1)\n return out\n\n\nclass Transition(nn.Module):\n def __init__(self, in_planes, out_planes):\n super(Transition, self).__init__()\n self.bn = nn.BatchNorm2d(in_planes)\n self.conv = nn.Conv2d(in_planes, out_planes, kernel_size=1, bias=False)\n\n def forward(self, x):\n out = self.conv(F.relu(self.bn(x)))\n out = F.avg_pool2d(out, 2)\n return out\n\n\nclass DenseNet(nn.Module):\n def __init__(self, block, nblocks, growth_rate=12, reduction=0.5, num_classes=10):\n super(DenseNet, self).__init__()\n self.growth_rate = growth_rate\n\n num_planes = 2*growth_rate\n self.conv1 = nn.Conv2d(3, num_planes, kernel_size=3, padding=1, bias=False)\n\n self.dense1 = self._make_dense_layers(block, num_planes, nblocks[0])\n num_planes += nblocks[0]*growth_rate\n out_planes = int(math.floor(num_planes*reduction))\n self.trans1 = Transition(num_planes, out_planes)\n num_planes = out_planes\n\n self.dense2 = self._make_dense_layers(block, num_planes, nblocks[1])\n num_planes += nblocks[1]*growth_rate\n out_planes = int(math.floor(num_planes*reduction))\n self.trans2 = Transition(num_planes, out_planes)\n num_planes = out_planes\n\n self.dense3 = self._make_dense_layers(block, num_planes, nblocks[2])\n num_planes += nblocks[2]*growth_rate\n out_planes = int(math.floor(num_planes*reduction))\n self.trans3 = Transition(num_planes, out_planes)\n num_planes = out_planes\n\n self.dense4 = self._make_dense_layers(block, num_planes, nblocks[3])\n num_planes += nblocks[3]*growth_rate\n\n self.bn = nn.BatchNorm2d(num_planes)\n self.linear = nn.Linear(num_planes, num_classes)\n\n def _make_dense_layers(self, block, in_planes, nblock):\n layers = []\n for i in range(nblock):\n layers.append(block(in_planes, self.growth_rate))\n in_planes += self.growth_rate\n return nn.Sequential(*layers)\n\n def forward(self, x):\n out = self.conv1(x)\n out = self.trans1(self.dense1(out))\n out = self.trans2(self.dense2(out))\n out = self.trans3(self.dense3(out))\n out = self.dense4(out)\n out = F.avg_pool2d(F.relu(self.bn(out)), 4)\n out = out.view(out.size(0), -1)\n out = self.linear(out)\n return out\n\ndef DenseNet121():\n return DenseNet(Bottleneck, [6,12,24,16], growth_rate=32)\n\ndef DenseNet169():\n return DenseNet(Bottleneck, [6,12,32,32], growth_rate=32)\n\ndef DenseNet201():\n return DenseNet(Bottleneck, [6,12,48,32], growth_rate=32)\n\ndef DenseNet161():\n return DenseNet(Bottleneck, [6,12,36,24], growth_rate=48)\n\ndef densenet_cifar():\n return DenseNet(Bottleneck, [6,12,24,16], growth_rate=12)\n\ndef _test():\n net = densenet_cifar()\n x = torch.randn(1,3,32,32)\n y = net(x)\n print(y)\n\n# test()\n" ]
[ [ "torch.nn.Sequential", "torch.cat", "torch.randn", "torch.nn.functional.avg_pool2d", "torch.nn.Conv2d", "torch.nn.Linear", "torch.nn.BatchNorm2d" ] ]
jlanga/exfi
[ "6cd28423213aba0ab8ac191e002396ddc84c4be3" ]
[ "tests/io/gfa1.py" ]
[ "#!/usr/bin/env python3\n\n\"\"\"tests.io.gfa1.py: Fragments of GFA1 files\"\"\"\n\nimport pandas as pd\n\n\nfrom exfi.io.gfa1 import \\\n HEADER_COLS, SEGMENT_COLS, LINK_COLS, CONTAINMENT_COLS, PATH_COLS, \\\n HEADER_DTYPES, SEGMENT_DTYPES, LINK_DTYPES, CONTAINMENT_DTYPES, PATH_DTYPES\n\nHEADER = pd.DataFrame(\n data=[[\"H\", \"VN:Z:1.0\"]],\n columns=HEADER_COLS\n).astype(HEADER_DTYPES)\n\n\n\nSEGMENTS_EMPTY = pd.DataFrame(\n columns=SEGMENT_COLS\n).astype(SEGMENT_DTYPES)\n\n\nSEGMENTS_COMPLEX_DATA = [[\n \"S\",\n \"ENSDART00000161035.1:0-326\",\n \"TGCACGGGTTTATTGTTCACAAAGAGATCGACAATGTGCGCAACTAAAATAAACATAGTACATTTTGATT\"\n \"ATACACGAACTTAAACTAAAGTCCAATCACACCTCCGCCCCGTTTCCACAGCAGCCTGTCAGGGTGGAGG\"\n \"AAAAGCGCGGCGGTCATGTGAGGCTCGAGCATCTCTCTCTCTCTCTCTCTCTCTCTCTCTACAGAATGAT\"\n \"AGAGGGAGCTCGTGAATCACATCATAGTCGTCCTCCCCTCATTCGTCCTCTCCAGCAGACACCGAAAAAC\"\n \"TGCGTTCATGCCAAAATGGGATGTGGAAATTCCTCCGCCACGAGCA\",\n], [\n \"S\",\n \"ENSDART00000161035.1:397-472\",\n \"AGGAACTACGGTGGAGTGTATGTGGGTCTTCCTGCTGATCTGACTGCAGTCGCTGCCAGTCAGTCCAAAT\"\n \"CAACA\"\n], [\n \"S\",\n \"ENSDART00000161035.1:477-523\",\n \"AGTCAACAGATGTTTATTGCAGACCTTCAGATAAAACAACATAGAA\"\n], [\n \"S\",\n \"ENSDART00000165342.1:5-127\",\n \"TGGAGCTGAAGCCGAGTATCTTGGTATTGGACTGGAACAGAAATCCAGCAAAAACTTTAAGGGAAATCAC\"\n \"TTTCATTTCATGATCGAAAAACTCCCGCAGATCATAAAAGAGTGGAAGGAAG\"\n], [\n \"S\",\n \"ENSDART00000165342.1:125-304\",\n \"AGGACCTGTAGTAGAAACAAAACTAGGATCTCTGAGAGGTGCCTTCTTGACTGTGAAGGGCAAGGACACA\"\n \"ATAGTCAATAGTTATCTAGGTGTGCCGTTCGCCAAGCCGCCTGTAGGACCCCTGAGACTTGCTCGACCAC\"\n \"AGGCTGCAGAGAAATGGCAAGGAGTTAGAGATGCCACCA\"\n], [\n \"S\",\n \"ENSDART00000165342.1:317-460\",\n \"GTGCCTCCAGGAAAGGCAAATGACTGTAACTGAACTGGAGTTTCTATCGATGGATGTGGAGGTTCCTGAG\"\n \"GTCTCGGAGGATTGCCTGTATCTTAACATCTACACCCCAGTTAAACCTGGACAAGGAGACAAGAAGTTAC\"\n \"CAG\"\n], [\n \"S\",\n \"ENSDART00000165342.1:459-592\",\n \"GTCATGGTTTGGATTCATGGTGGAGGACTCTCTCTTGGATCGGCTTCAATGTATGATGGCTCTGTTCTGG\"\n \"CTGCGTATCAGGATGTGGTCGTGGTGCTCATTCAGTACAGATTGGGTCTTCTGGGGTTCTTAA\"\n], [\n \"S\",\n \"ENSDART00000165342.1:591-650\",\n \"AGCACCGGAGACGAGCATGCGCCAGGAAACTATGGTTTTCTGGATCAAGTAGCTGCCCT\"\n], [\n \"S\",\n \"ENSDART00000165342.1:645-746\",\n \"GCCCTTCAGTGGGTTCAGGAGAACATCCACAGCTTCGGTGGAGATCCTGGATCAGTGACCATCTTTGGAG\"\n \"AGTCTGCTGGAGGAATCAGTGTATCCACGCT\"\n], [\n \"S\",\n \"ENSDART00000165342.1:746-851\",\n \"GATTCTTTCCCCGCTGGCGTCTGGACTGTTTCATCGCGCCATTGCAGAAAGTGGAACTGCCTTCTGGGAT\"\n \"GGTTTAGTCATGGCTGATCCTTTTCAGAGAGCCCA\"\n], [\n \"S\",\n \"ENSDART00000165342.1:854-886\",\n \"TGCAGCCAAACAATGCAACTGTGACAGCAGCA\"\n], [\n \"S\",\n \"ENSDART00000165342.1:899-953\",\n \"TGTCGACTGCATTATGCACTGGTCTGAAGAGGAGGCTCTGGAATGTGCTAAAAA\"\n], [\n \"S\",\n \"ENSDART00000165342.1:974-1097\",\n \"CGTTGCTGTAGATTCTTATTTCCTTCCCAAACCCATCGAGGAGATTGTTGAGAAACAAGAGTTTAGTAAA\"\n \"GTTCCTCTCATCAACGGCATTAACAATGATGAGTTTGGCTTCTTGTTGGCTGA\"\n], [\n \"S\",\n \"ENSDART00000165342.1:1098-1175\",\n \"TATTTCTTGGGTCCTGAATGGATGAATGGGTTGAAAAGAGAGCAAATCGCTGAAGCCTTGACGCTCACAT\"\n \"ATCCTGA\"\n], [\n \"S\",\n \"ENSDART00000165342.1:1176-1324\",\n \"CCCAAGGATCGATGGATCATTGATCTGGTGGCGAAGGAATATCTGGGCGACACACACGACCCCATTGAAA\"\n \"TCCGTGAAGTTTATCGGGAGATGATGGGAGACGTGCTGTTTAACATCCCTGCCCTGCAACTGGCAAAACA\"\n \"CCACAGCG\"\n]]\n\nSEGMENTS_SIMPLE = pd.DataFrame(\n data=[SEGMENTS_COMPLEX_DATA[0]],\n columns=SEGMENT_COLS\n).astype(SEGMENT_DTYPES)\n\n\n\nSEGMENTS_COMPLEX = pd.DataFrame(\n data=SEGMENTS_COMPLEX_DATA,\n columns=SEGMENT_COLS\n).astype(SEGMENT_DTYPES)\n\n\nSEGMENTS_COMPLEX_SOFT_DATA = [[\n \"S\",\n \"ENSDART00000161035.1:0-326\",\n \"TGCACGGGTTTATTGTTCACAAAGAGATCGACAATGTGCGCAACTAAAATAAACATAGTACATTTTGATT\"\n \"ATACACGAACTTAAACTAAAGTCCAATCACACCTCCGCCCCGTTTCCACAGCAGCCTGTCAGGGTGGAGG\"\n \"AAAAGCGCGGCGGTCATGTGAGGCTCGAGCATCTCTCTCTCTCTCTCTCTCTCTCTCTCTACAGAATGAT\"\n \"AGAGGGAGCTCGTGAATCACATCATAGTCGTCCTCCCCTCATTCGTCCTCTCCAGCAGACACCGAAAAAC\"\n \"TGCGTTCATGCCAAAATGGGATGTGGAAATTCCTCCGCCACGAGCA\"\n], [\n \"S\",\n \"ENSDART00000161035.1:397-472\",\n \"AGGAACTACGGTGGAGTGTATGTGGGTCTTCCTGCTGATCTGACTGCAGTCGCTGCCAGTCAGTCCAAAT\"\n \"CAACA\"\n], [\n \"S\",\n \"ENSDART00000161035.1:477-523\",\n \"AGTCAACAGATGTTTATTGCAGACCTTCAGATAAAACAACATAGAA\"\n], [\n \"S\",\n \"ENSDART00000165342.1:5-127\",\n \"TGGAGCTGAAGCCGAGTATCTTGGTATTGGACTGGAACAGAAATCCAGCAAAAACTTTAAGGGAAATCAC\"\n \"TTTCATTTCATGATCGAAAAACTCCCGCAGATCATAAAAGAGTGGAAGGAag\"\n], [\n \"S\",\n \"ENSDART00000165342.1:125-304\",\n \"agGACCTGTAGTAGAAACAAAACTAGGATCTCTGAGAGGTGCCTTCTTGACTGTGAAGGGCAAGGACACA\"\n \"ATAGTCAATAGTTATCTAGGTGTGCCGTTCGCCAAGCCGCCTGTAGGACCCCTGAGACTTGCTCGACCAC\"\n \"AGGCTGCAGAGAAATGGCAAGGAGTTAGAGATGCCACCA\"\n], [\n \"S\",\n \"ENSDART00000165342.1:317-460\",\n \"GTGCCTCCAGGAAAGGCAAATGACTGTAACTGAACTGGAGTTTCTATCGATGGATGTGGAGGTTCCTGAG\"\n \"GTCTCGGAGGATTGCCTGTATCTTAACATCTACACCCCAGTTAAACCTGGACAAGGAGACAAGAAGTTAC\"\n \"CAg\"\n], [\n \"S\",\n \"ENSDART00000165342.1:459-592\",\n \"gTCATGGTTTGGATTCATGGTGGAGGACTCTCTCTTGGATCGGCTTCAATGTATGATGGCTCTGTTCTGG\"\n \"CTGCGTATCAGGATGTGGTCGTGGTGCTCATTCAGTACAGATTGGGTCTTCTGGGGTTCTTAa\"\n], [\n \"S\",\n \"ENSDART00000165342.1:591-650\",\n \"aGCACCGGAGACGAGCATGCGCCAGGAAACTATGGTTTTCTGGATCAAGTAGCTgccct\"\n], [\n \"S\",\n \"ENSDART00000165342.1:645-746\",\n \"gccctTCAGTGGGTTCAGGAGAACATCCACAGCTTCGGTGGAGATCCTGGATCAGTGACCATCTTTGGAG\"\n \"AGTCTGCTGGAGGAATCAGTGTATCCACGCT\"\n]] + SEGMENTS_COMPLEX_DATA[9:]\n\nSEGMENTS_COMPLEX_SOFT = pd.DataFrame(\n data=SEGMENTS_COMPLEX_SOFT_DATA,\n columns=SEGMENT_COLS\n).astype(SEGMENT_DTYPES)\n\nSEGMENTS_COMPLEX_HARD = pd.DataFrame(\n data=[[\n \"S\",\n \"ENSDART00000161035.1:0-326\",\n \"TGCACGGGTTTATTGTTCACAAAGAGATCGACAATGTGCGCAACTAAAATAAACATAGTACATTTTGATT\"\n \"ATACACGAACTTAAACTAAAGTCCAATCACACCTCCGCCCCGTTTCCACAGCAGCCTGTCAGGGTGGAGG\"\n \"AAAAGCGCGGCGGTCATGTGAGGCTCGAGCATCTCTCTCTCTCTCTCTCTCTCTCTCTCTACAGAATGAT\"\n \"AGAGGGAGCTCGTGAATCACATCATAGTCGTCCTCCCCTCATTCGTCCTCTCCAGCAGACACCGAAAAAC\"\n \"TGCGTTCATGCCAAAATGGGATGTGGAAATTCCTCCGCCACGAGCA\"\n ], [\n \"S\",\n \"ENSDART00000161035.1:397-472\",\n \"AGGAACTACGGTGGAGTGTATGTGGGTCTTCCTGCTGATCTGACTGCAGTCGCTGCCAGTCAGTCCAAAT\"\n \"CAACA\"\n ], [\n \"S\",\n \"ENSDART00000161035.1:477-523\",\n \"AGTCAACAGATGTTTATTGCAGACCTTCAGATAAAACAACATAGAA\"\n ], [\n \"S\",\n \"ENSDART00000165342.1:5-127\",\n \"TGGAGCTGAAGCCGAGTATCTTGGTATTGGACTGGAACAGAAATCCAGCAAAAACTTTAAGGGAAATCAC\"\n \"TTTCATTTCATGATCGAAAAACTCCCGCAGATCATAAAAGAGTGGAAGGANN\"\n ], [\n \"S\",\n \"ENSDART00000165342.1:125-304\",\n \"NNGACCTGTAGTAGAAACAAAACTAGGATCTCTGAGAGGTGCCTTCTTGACTGTGAAGGGCAAGGACACA\"\n \"ATAGTCAATAGTTATCTAGGTGTGCCGTTCGCCAAGCCGCCTGTAGGACCCCTGAGACTTGCTCGACCAC\"\n \"AGGCTGCAGAGAAATGGCAAGGAGTTAGAGATGCCACCA\"\n ], [\n \"S\",\n \"ENSDART00000165342.1:317-460\",\n \"GTGCCTCCAGGAAAGGCAAATGACTGTAACTGAACTGGAGTTTCTATCGATGGATGTGGAGGTTCCTGAG\"\n \"GTCTCGGAGGATTGCCTGTATCTTAACATCTACACCCCAGTTAAACCTGGACAAGGAGACAAGAAGTTAC\"\n \"CAN\"\n ], [\n \"S\",\n \"ENSDART00000165342.1:459-592\",\n \"NTCATGGTTTGGATTCATGGTGGAGGACTCTCTCTTGGATCGGCTTCAATGTATGATGGCTCTGTTCTGG\"\n \"CTGCGTATCAGGATGTGGTCGTGGTGCTCATTCAGTACAGATTGGGTCTTCTGGGGTTCTTAN\"\n ], [\n \"S\",\n \"ENSDART00000165342.1:591-650\",\n \"NGCACCGGAGACGAGCATGCGCCAGGAAACTATGGTTTTCTGGATCAAGTAGCTNNNNN\"\n ], [\n \"S\",\n \"ENSDART00000165342.1:645-746\",\n \"NNNNNTCAGTGGGTTCAGGAGAACATCCACAGCTTCGGTGGAGATCCTGGATCAGTGACCATCTTTGGAG\"\n \"AGTCTGCTGGAGGAATCAGTGTATCCACGCT\"\n ]] + SEGMENTS_COMPLEX_DATA[9:],\n columns=SEGMENT_COLS\n).astype(SEGMENT_DTYPES)\n\n\n\n\nLINKS_EMPTY = pd.DataFrame(\n columns=LINK_COLS\n).astype(LINK_DTYPES)\n\nLINKS_SIMPLE = pd.DataFrame(\n columns=LINK_COLS\n).astype(LINK_DTYPES)\n\nLINKS_COMPLEX = pd.DataFrame(\n data=[[\n \"L\", \"ENSDART00000161035.1:0-326\", \"+\",\n \"ENSDART00000161035.1:397-472\", \"+\", \"71N\"\n ], [\n \"L\", \"ENSDART00000161035.1:397-472\", \"+\",\n \"ENSDART00000161035.1:477-523\", \"+\", \"5N\"\n ], [\n \"L\", \"ENSDART00000165342.1:5-127\", \"+\",\n \"ENSDART00000165342.1:125-304\", \"+\", \"2M\"\n ], [\n \"L\", \"ENSDART00000165342.1:125-304\", \"+\",\n \"ENSDART00000165342.1:317-460\", \"+\", \"13N\"\n ], [\n \"L\", \"ENSDART00000165342.1:317-460\", \"+\",\n \"ENSDART00000165342.1:459-592\", \"+\", \"1M\"\n ], [\n \"L\", \"ENSDART00000165342.1:459-592\", \"+\",\n \"ENSDART00000165342.1:591-650\", \"+\", \"1M\"\n ], [\n \"L\", \"ENSDART00000165342.1:591-650\", \"+\",\n \"ENSDART00000165342.1:645-746\", \"+\", \"5M\"\n ], [\n \"L\", \"ENSDART00000165342.1:645-746\", \"+\",\n \"ENSDART00000165342.1:746-851\", \"+\", \"0M\"\n ], [\n \"L\", \"ENSDART00000165342.1:746-851\", \"+\",\n \"ENSDART00000165342.1:854-886\", \"+\", \"3N\"\n ], [\n \"L\", \"ENSDART00000165342.1:854-886\", \"+\",\n \"ENSDART00000165342.1:899-953\", \"+\", \"13N\"\n ], [\n \"L\", \"ENSDART00000165342.1:899-953\", \"+\",\n \"ENSDART00000165342.1:974-1097\", \"+\", \"21N\"\n ], [\n \"L\", \"ENSDART00000165342.1:974-1097\", \"+\",\n \"ENSDART00000165342.1:1098-1175\", \"+\", \"1N\"\n ], [\n \"L\", \"ENSDART00000165342.1:1098-1175\", \"+\",\n \"ENSDART00000165342.1:1176-1324\", \"+\", \"1N\"\n ]],\n columns=LINK_COLS\n).astype(LINK_DTYPES)\n\n\n\nCONTAINMENTS_EMPTY = pd.DataFrame(\n columns=CONTAINMENT_COLS\n).astype(CONTAINMENT_DTYPES)\n\nCONTAINMENTS_SIMPLE = pd.DataFrame(\n data=[[\n \"C\", \"ENSDART00000161035.1\", \"+\", \"ENSDART00000161035.1:0-326\", \"+\",\n 0, \"326M\"\n ]],\n columns=CONTAINMENT_COLS\n).astype(CONTAINMENT_DTYPES)\n\nCONTAINMENTS_COMPLEX = pd.DataFrame(\n data=[[\n \"C\", \"ENSDART00000161035.1\", \"+\", \"ENSDART00000161035.1:0-326\", \"+\",\n 0, \"326M\"\n ], [\n \"C\", \"ENSDART00000161035.1\", \"+\", \"ENSDART00000161035.1:397-472\", \"+\",\n 397, \"75M\"\n ], [\n \"C\", \"ENSDART00000161035.1\", \"+\", \"ENSDART00000161035.1:477-523\", \"+\",\n 477, \"46M\"\n ], [\n \"C\", \"ENSDART00000165342.1\", \"+\", \"ENSDART00000165342.1:5-127\", \"+\",\n 5, \"122M\"\n ], [\n \"C\", \"ENSDART00000165342.1\", \"+\", \"ENSDART00000165342.1:125-304\", \"+\",\n 125, \"179M\"\n ], [\n \"C\", \"ENSDART00000165342.1\", \"+\", \"ENSDART00000165342.1:317-460\", \"+\",\n 317, \"143M\"\n ], [\n \"C\", \"ENSDART00000165342.1\", \"+\", \"ENSDART00000165342.1:459-592\", \"+\",\n 459, \"133M\"\n ], [\n \"C\", \"ENSDART00000165342.1\", \"+\", \"ENSDART00000165342.1:591-650\", \"+\",\n 591, \"59M\"\n ], [\n \"C\", \"ENSDART00000165342.1\", \"+\", \"ENSDART00000165342.1:645-746\", \"+\",\n 645, \"101M\"\n ], [\n \"C\", \"ENSDART00000165342.1\", \"+\", \"ENSDART00000165342.1:746-851\", \"+\",\n 746, \"105M\"\n ], [\n \"C\", \"ENSDART00000165342.1\", \"+\", \"ENSDART00000165342.1:854-886\", \"+\",\n 854, \"32M\"\n ], [\n \"C\", \"ENSDART00000165342.1\", \"+\", \"ENSDART00000165342.1:899-953\", \"+\",\n 899, \"54M\"\n ], [\n \"C\", \"ENSDART00000165342.1\", \"+\", \"ENSDART00000165342.1:974-1097\", \"+\",\n 974, \"123M\"\n ], [\n \"C\", \"ENSDART00000165342.1\", \"+\", \"ENSDART00000165342.1:1098-1175\",\n \"+\", 1098, \"77M\"\n ], [\n \"C\", \"ENSDART00000165342.1\", \"+\", \"ENSDART00000165342.1:1176-1324\",\n \"+\", 1176, \"148M\"\n ]],\n columns=CONTAINMENT_COLS\n).astype(CONTAINMENT_DTYPES)\n\n\nPATHS_EMPTY = pd.DataFrame(\n columns=PATH_COLS\n).astype(PATH_DTYPES)\nPATHS_SIMPLE = pd.DataFrame(\n data=[[\"P\", \"ENSDART00000161035.1\", \"ENSDART00000161035.1:0-326+\", \"*\"]],\n columns=PATH_COLS\n).astype(PATH_DTYPES)\nPATHS_COMPLEX = pd.DataFrame(\n data=[[\n \"P\", \"ENSDART00000161035.1\",\n \"ENSDART00000161035.1:0-326+,\"\n \"ENSDART00000161035.1:397-472+,\"\n \"ENSDART00000161035.1:477-523+\",\n \"*\"\n ], [\n \"P\", \"ENSDART00000165342.1\",\n \"ENSDART00000165342.1:5-127+,ENSDART00000165342.1:125-304+,\"\n \"ENSDART00000165342.1:317-460+,ENSDART00000165342.1:459-592+,\"\n \"ENSDART00000165342.1:591-650+,ENSDART00000165342.1:645-746+,\"\n \"ENSDART00000165342.1:746-851+,ENSDART00000165342.1:854-886+,\"\n \"ENSDART00000165342.1:899-953+,ENSDART00000165342.1:974-1097+,\"\n \"ENSDART00000165342.1:1098-1175+,ENSDART00000165342.1:1176-1324+\",\n \"*\"\n ]],\n columns=PATH_COLS\n).astype(PATH_DTYPES)\n\nGFA1_EMPTY_FN = \"tests/io/empty.gfa\"\nGFA1_SIMPLE_FN = \"tests/io/simple.gfa\"\nGFA1_COMPLEX_FN = \"tests/io/complex.gfa\"\nGFA1_COMPLEX_SOFT_FN = \"tests/io/complex_soft.gfa\"\nGFA1_COMPLEX_HARD_FN = \"tests/io/complex_hard.gfa\"\nGFA1_COMPLEX_COLLAPSED_FN = \"tests/io/complex_collapsed.gfa\"\nGFA1_COMPLEX_COLLAPSED_SOFT_FN = \"tests/io/complex_collapsed_soft.gfa\"\nGFA1_COMPLEX_COLLAPSED_HARD_FN = \"tests/io/complex_collapsed_hard.gfa\"\n" ]
[ [ "pandas.DataFrame" ] ]
chidinzerem/chidinzerem.github.io
[ "0a5ac76b944531179e3d7f46abe45a0cce7ad1af" ]
[ "code/WEBSCRAPER PYTHON/core/logger.py" ]
[ "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# ------------------------\n# Penji OpDev Fall 2019\n# Open AI Based Logger\n# Modifications: Cory Paik\n# ------------------------\n\n# General\nimport os\nimport sys\nimport shutil\nimport os.path as osp\nimport json\nimport time\nimport datetime\nimport tempfile\nfrom collections import defaultdict\nfrom contextlib import contextmanager\n# Local\n\nDEBUG = 10\nINFO = 20\nWARN = 30\nERROR = 40\n\nDISABLED = 50\n\nclass KVWriter(object):\n def writekvs(self, kvs):\n raise NotImplementedError\n\nclass SeqWriter(object):\n def writeseq(self, seq):\n raise NotImplementedError\n\nclass HumanOutputFormat(KVWriter, SeqWriter):\n def __init__(self, filename_or_file):\n if isinstance(filename_or_file, str):\n self.file = open(filename_or_file, 'wt')\n self.own_file = True\n else:\n assert hasattr(filename_or_file, 'read'), 'expected file or str, got %s'%filename_or_file\n self.file = filename_or_file\n self.own_file = False\n\n def writekvs(self, kvs):\n # Create strings for printing\n key2str = {}\n for (key, val) in sorted(kvs.items()):\n if hasattr(val, '__float__'):\n valstr = '%-8.3g' % val\n else:\n valstr = str(val)\n key2str[self._truncate(key)] = self._truncate(valstr)\n\n # Find max widths\n if len(key2str) == 0:\n print('WARNING: tried to write empty key-value dict')\n return\n else:\n keywidth = max(map(len, key2str.keys()))\n valwidth = max(map(len, key2str.values()))\n\n # Write out the data\n dashes = '-' * (keywidth + valwidth + 7)\n lines = [dashes]\n for (key, val) in sorted(key2str.items(), key=lambda kv: kv[0].lower()):\n lines.append('| %s%s | %s%s |' % (\n key,\n ' ' * (keywidth - len(key)),\n val,\n ' ' * (valwidth - len(val)),\n ))\n lines.append(dashes)\n self.file.write('\\n'.join(lines) + '\\n')\n\n # Flush the output to the file\n self.file.flush()\n\n def _truncate(self, s):\n maxlen = 30\n return s[:maxlen-3] + '...' if len(s) > maxlen else s\n\n def writeseq(self, seq):\n seq = list(seq)\n for (i, elem) in enumerate(seq):\n self.file.write(elem)\n if i < len(seq) - 1: # add space unless this is the last one\n self.file.write(' ')\n self.file.write('\\n')\n self.file.flush()\n\n def close(self):\n if self.own_file:\n self.file.close()\n\nclass JSONOutputFormat(KVWriter):\n def __init__(self, filename):\n self.file = open(filename, 'wt')\n\n def writekvs(self, kvs):\n for k, v in sorted(kvs.items()):\n if hasattr(v, 'dtype'):\n kvs[k] = float(v)\n self.file.write(json.dumps(kvs) + '\\n')\n self.file.flush()\n\n def close(self):\n self.file.close()\n\nclass CSVOutputFormat(KVWriter):\n def __init__(self, filename):\n self.file = open(filename, 'w+t')\n self.keys = []\n self.sep = ','\n\n def writekvs(self, kvs):\n # Add our current row to the history\n extra_keys = list(kvs.keys() - self.keys)\n extra_keys.sort()\n if extra_keys:\n self.keys.extend(extra_keys)\n self.file.seek(0)\n lines = self.file.readlines()\n self.file.seek(0)\n for (i, k) in enumerate(self.keys):\n if i > 0:\n self.file.write(',')\n self.file.write(k)\n self.file.write('\\n')\n for line in lines[1:]:\n self.file.write(line[:-1])\n self.file.write(self.sep * len(extra_keys))\n self.file.write('\\n')\n for (i, k) in enumerate(self.keys):\n if i > 0:\n self.file.write(',')\n v = kvs.get(k)\n if v is not None:\n self.file.write(str(v))\n self.file.write('\\n')\n self.file.flush()\n\n def close(self):\n self.file.close()\n\n\nclass TensorBoardOutputFormat(KVWriter):\n \"\"\"\n Dumps key/value pairs into TensorBoard's numeric format.\n \"\"\"\n def __init__(self, dir):\n os.makedirs(dir, exist_ok=True)\n self.dir = dir\n self.step = 1\n prefix = 'events'\n path = osp.join(osp.abspath(dir), prefix)\n import tensorflow as tf\n from tensorflow.python import pywrap_tensorflow\n from tensorflow.core.util import event_pb2\n from tensorflow.python.util import compat\n self.tf = tf\n self.event_pb2 = event_pb2\n self.pywrap_tensorflow = pywrap_tensorflow\n self.writer = pywrap_tensorflow.EventsWriter(compat.as_bytes(path))\n\n def writekvs(self, kvs):\n def summary_val(k, v):\n kwargs = {'tag': k, 'simple_value': float(v)}\n return self.tf.Summary.Value(**kwargs)\n summary = self.tf.Summary(value=[summary_val(k, v) for k, v in kvs.items()])\n event = self.event_pb2.Event(wall_time=time.time(), summary=summary)\n event.step = self.step # is there any reason why you'd want to specify the step?\n self.writer.WriteEvent(event)\n self.writer.Flush()\n self.step += 1\n\n def close(self):\n if self.writer:\n self.writer.Close()\n self.writer = None\n\ndef make_output_format(format, ev_dir, log_suffix=''):\n os.makedirs(ev_dir, exist_ok=True)\n if format == 'stdout':\n return HumanOutputFormat(sys.stdout)\n elif format == 'log':\n return HumanOutputFormat(osp.join(ev_dir, 'log%s.txt' % log_suffix))\n elif format == 'json':\n return JSONOutputFormat(osp.join(ev_dir, 'progress%s.json' % log_suffix))\n elif format == 'csv':\n return CSVOutputFormat(osp.join(ev_dir, 'progress%s.csv' % log_suffix))\n elif format == 'tensorboard':\n return TensorBoardOutputFormat(osp.join(ev_dir, 'tb%s' % log_suffix))\n else:\n raise ValueError('Unknown format specified: %s' % (format,))\n\n# ================================================================\n# API\n# ================================================================\n\ndef logkv(key, val):\n \"\"\"\n Log a value of some diagnostic\n Call this once for each diagnostic quantity, each iteration\n If called many times, last value will be used.\n \"\"\"\n get_current().logkv(key, val)\n\ndef logkv_mean(key, val):\n \"\"\"\n The same as logkv(), but if called many times, values averaged.\n \"\"\"\n get_current().logkv_mean(key, val)\n\ndef logkvs(d):\n \"\"\"\n Log a dictionary of key-value pairs\n \"\"\"\n for (k, v) in d.items():\n logkv(k, v)\n\ndef dumpkvs():\n \"\"\"\n Write all of the diagnostics from the current iteration\n \"\"\"\n return get_current().dumpkvs()\n\ndef getkvs():\n return get_current().name2val\n\n\ndef log(*args, level=INFO):\n \"\"\"\n Write the sequence of args, with no separators, to the console and output files (if you've configured an output file).\n \"\"\"\n get_current().log(*args, level=level)\n\ndef debug(*args):\n args = [f'DEBUG: {log}' for log in args]\n log(*args, level=DEBUG)\n\ndef info(*args):\n args = [f'INFO: {log}' for log in args]\n log(*args, level=INFO)\n\ndef warn(*args):\n args = [f'WARN: {log}' for log in args]\n log(*args, level=WARN)\n\ndef error(*args):\n args = [f'ERROR: {log}' for log in args]\n log(*args, level=ERROR)\n\n\ndef set_level(level):\n \"\"\"\n Set logging threshold on current logger.\n \"\"\"\n get_current().set_level(level)\n\ndef set_comm(comm):\n get_current().set_comm(comm)\n\ndef get_dir():\n \"\"\"\n Get directory that log files are being written to.\n will be None if there is no output directory (i.e., if you didn't call start)\n \"\"\"\n return get_current().get_dir()\n\nrecord_tabular = logkv\ndump_tabular = dumpkvs\n\n@contextmanager\ndef profile_kv(scopename):\n logkey = 'wait_' + scopename\n tstart = time.time()\n try:\n yield\n finally:\n get_current().name2val[logkey] += time.time() - tstart\n\ndef profile(n):\n \"\"\"\n Usage:\n @profile(\"my_func\")\n def my_func(): code\n \"\"\"\n def decorator_with_name(func):\n def func_wrapper(*args, **kwargs):\n with profile_kv(n):\n return func(*args, **kwargs)\n return func_wrapper\n return decorator_with_name\n\n\n# ================================================================\n# Backend\n# ================================================================\n\ndef get_current():\n if Logger.CURRENT is None:\n _configure_default_logger()\n\n return Logger.CURRENT\n\n\nclass Logger(object):\n DEFAULT = None # A logger with no output files. (See right below class definition)\n # So that you can still log to the terminal without setting up any output files\n CURRENT = None # Current logger being used by the free functions above\n\n def __init__(self, dir, output_formats, comm=None):\n self.name2val = defaultdict(float) # values this iteration\n self.name2cnt = defaultdict(int)\n self.level = INFO\n self.dir = dir\n self.output_formats = output_formats\n self.comm = comm\n\n # Logging API, forwarded\n # ----------------------------------------\n def logkv(self, key, val):\n self.name2val[key] = val\n\n def logkv_mean(self, key, val):\n oldval, cnt = self.name2val[key], self.name2cnt[key]\n self.name2val[key] = oldval*cnt/(cnt+1) + val/(cnt+1)\n self.name2cnt[key] = cnt + 1\n\n def dumpkvs(self):\n if self.comm is None:\n d = self.name2val\n else:\n from baselines.common import mpi_util\n d = mpi_util.mpi_weighted_mean(self.comm,\n {name : (val, self.name2cnt.get(name, 1))\n for (name, val) in self.name2val.items()})\n if self.comm.rank != 0:\n d['dummy'] = 1 # so we don't get a warning about empty dict\n out = d.copy() # Return the dict for unit testing purposes\n for fmt in self.output_formats:\n if isinstance(fmt, KVWriter):\n fmt.writekvs(d)\n self.name2val.clear()\n self.name2cnt.clear()\n return out\n\n def log(self, *args, level=INFO):\n if self.level <= level:\n self._do_log(args)\n\n # Configuration\n # ----------------------------------------\n def set_level(self, level):\n self.level = level\n\n def set_comm(self, comm):\n self.comm = comm\n\n def get_dir(self):\n return self.dir\n\n def close(self):\n for fmt in self.output_formats:\n fmt.close()\n\n # Misc\n # ----------------------------------------\n def _do_log(self, args):\n for fmt in self.output_formats:\n if isinstance(fmt, SeqWriter):\n fmt.writeseq(map(str, args))\n\ndef get_rank_without_mpi_import():\n # check environment variables here instead of importing mpi4py\n # to avoid calling MPI_Init() when this module is imported\n for varname in ['PMI_RANK', 'OMPI_COMM_WORLD_RANK']:\n if varname in os.environ:\n return int(os.environ[varname])\n return 0\n\n\ndef configure(dir=None, format_strs=None, comm=None, log_suffix=''):\n \"\"\"\n If comm is provided, average all numerical stats across that comm\n \"\"\"\n if dir is None:\n dir = os.getenv('OPENAI_LOGDIR')\n if dir is None:\n dir = osp.join(tempfile.gettempdir(),\n datetime.datetime.now().strftime(\"openai-%Y-%m-%d-%H-%M-%S-%f\"))\n assert isinstance(dir, str)\n dir = os.path.expanduser(dir)\n os.makedirs(os.path.expanduser(dir), exist_ok=True)\n\n rank = get_rank_without_mpi_import()\n if rank > 0:\n log_suffix = log_suffix + \"-rank%03i\" % rank\n\n if format_strs is None:\n if rank == 0:\n format_strs = os.getenv('OPENAI_LOG_FORMAT', 'stdout,log,csv').split(',')\n else:\n format_strs = os.getenv('OPENAI_LOG_FORMAT_MPI', 'log').split(',')\n format_strs = filter(None, format_strs)\n output_formats = [make_output_format(f, dir, log_suffix) for f in format_strs]\n\n Logger.CURRENT = Logger(dir=dir, output_formats=output_formats, comm=comm)\n if output_formats:\n log('Logging to %s'%dir)\n\ndef _configure_default_logger():\n configure()\n Logger.DEFAULT = Logger.CURRENT\n\ndef reset():\n if Logger.CURRENT is not Logger.DEFAULT:\n Logger.CURRENT.close()\n Logger.CURRENT = Logger.DEFAULT\n log('Reset logger')\n\n@contextmanager\ndef scoped_configure(dir=None, format_strs=None, comm=None):\n prevlogger = Logger.CURRENT\n configure(dir=dir, format_strs=format_strs, comm=comm)\n try:\n yield\n finally:\n Logger.CURRENT.close()\n Logger.CURRENT = prevlogger\n\n# ================================================================\n\ndef _demo():\n info(\"hi\")\n debug(\"shouldn't appear\")\n set_level(DEBUG)\n debug(\"should appear\")\n dir = \"/tmp/testlogging\"\n if os.path.exists(dir):\n shutil.rmtree(dir)\n configure(dir=dir)\n logkv(\"a\", 3)\n logkv(\"b\", 2.5)\n dumpkvs()\n logkv(\"b\", -2.5)\n logkv(\"a\", 5.5)\n dumpkvs()\n info(\"^^^ should see a = 5.5\")\n logkv_mean(\"b\", -22.5)\n logkv_mean(\"b\", -44.4)\n logkv(\"a\", 5.5)\n dumpkvs()\n info(\"^^^ should see b = -33.3\")\n\n logkv(\"b\", -2.5)\n dumpkvs()\n\n logkv(\"a\", \"longasslongasslongasslongasslongasslongassvalue\")\n dumpkvs()\n\n\n# ================================================================\n# Readers\n# ================================================================\n\ndef read_json(fname):\n import pandas\n ds = []\n with open(fname, 'rt') as fh:\n for line in fh:\n ds.append(json.loads(line))\n return pandas.DataFrame(ds)\n\ndef read_csv(fname):\n import pandas\n return pandas.read_csv(fname, index_col=None, comment='#')\n\ndef read_tb(path):\n \"\"\"\n path : a tensorboard file OR a directory, where we will find all TB files\n of the form events.*\n \"\"\"\n import pandas\n import numpy as np\n from glob import glob\n import tensorflow as tf\n if osp.isdir(path):\n fnames = glob(osp.join(path, \"events.*\"))\n elif osp.basename(path).startswith(\"events.\"):\n fnames = [path]\n else:\n raise NotImplementedError(\"Expected tensorboard file or directory containing them. Got %s\"%path)\n tag2pairs = defaultdict(list)\n maxstep = 0\n for fname in fnames:\n for summary in tf.train.summary_iterator(fname):\n if summary.step > 0:\n for v in summary.summary.value:\n pair = (summary.step, v.simple_value)\n tag2pairs[v.tag].append(pair)\n maxstep = max(summary.step, maxstep)\n data = np.empty((maxstep, len(tag2pairs)))\n data[:] = np.nan\n tags = sorted(tag2pairs.keys())\n for (colidx,tag) in enumerate(tags):\n pairs = tag2pairs[tag]\n for (step, value) in pairs:\n data[step-1, colidx] = value\n return pandas.DataFrame(data, columns=tags)\n\nif __name__ == \"__main__\":\n _demo()" ]
[ [ "tensorflow.python.util.compat.as_bytes", "pandas.read_csv", "tensorflow.train.summary_iterator", "pandas.DataFrame" ] ]
eqy/autotosis
[ "93fc800ed7c3b0fe0fcf58af90283de8d2036568" ]
[ "inference.py" ]
[ "import argparse\nimport ast\nimport os\nimport sys\nimport time\nfrom clip import Clip\nfrom artosisnet_transforms import crop_callbacks\nimport random\nimport shutil\nimport subprocess\n\nimport ffmpeg\nimport numpy as np\nimport torch\n\nsys.setrecursionlimit(10**6)\n\ndef _join_videos(listpath, outputpath):\n (\n ffmpeg\n .input(listpath, format='concat', safe=0)\n .output(outputpath, c='copy')\n .overwrite_output()\n .run()\n )\n\n\ndef _concat_highlights(paths, output_path):\n tempfile = 'highlightconcatlist'\n with open(tempfile, 'w') as f:\n for path in paths:\n f.write(f'file \\'{path}\\'\\n')\n (\n ffmpeg\n .input(tempfile, format='concat', safe=0)\n .output(output_path, c='copy')\n .overwrite_output()\n .run()\n )\n\n\ndef _crossfade_concat_highlights(paths, output_path):\n command = ['xvfb-run', '-s', '-ac -screen 1 1920x1080x24', 'ffmpeg-concat']\n for path in paths:\n command.append(path)\n command += ['-o', output_path]\n print(command)\n subprocess.call(command)\n\n\ndef single_inference(args):\n text = 'salt'\n if args.chill:\n text = 'chill'\n assert not args.pog\n if args.pog:\n text = 'pog'\n assert not args.chill\n if args.bbox is not None:\n try:\n bbox = ast.literal_eval(args.bbox)\n except ValueError:\n bbox = crop_callbacks[args.bbox]\n clip = Clip(args.single_inference, bbox=bbox, text=text, uncap=args.uncap)\n else:\n clip = Clip(args.single_inference, text=text, uncap=args.uncap)\n clip.inference_frameskip = args.frameskip\n clip.inference(args.model_path, audio_cutoff=args.audio_cutoff, arch=args.arch, batch_size=args.batch_size, use_sound=not args.no_sound, concat_full=args.concat_full, fp16=args.fp16)\n averages = [np.mean(second) for second in clip.inference_results]\n average = np.mean(averages)\n if args.benchmark:\n return\n clip.generate_annotated(args.name)\n print(\"clip average:\", average)\n\n\ndef highlights(args):\n paths = list()\n idx = 0\n while True:\n path = f'{args.prefix}{idx}.mp4'\n if os.path.exists(f'{args.prefix}{idx}.mp4'):\n paths.append(path)\n idx += 1\n else:\n break\n\n paths = sorted(paths)\n\n if not len(paths):\n assert os.path.exists(args.prefix)\n\n text = 'salt'\n if args.chill:\n text = 'chill'\n if args.pog:\n text = 'pog'\n\n if len(paths) >= 1:\n print(\"joining videos...\")\n tempvideolist = 'tempvideolist' + str(random.randint(0,2**32))\n basename = os.path.splitext(args.name)[0]\n tempconcatvideo = f'temp{basename}.mp4'\n with open(tempvideolist, 'w') as f:\n for path in paths:\n f.write(f'file \\'{path}\\'\\n')\n _join_videos(tempvideolist, tempconcatvideo)\n if args.bbox is not None:\n try:\n bbox = ast.literal_eval(args.bbox)\n except ValueError:\n bbox = crop_callbacks[args.bbox]\n clip = Clip(tempconcatvideo, bbox=bbox, text=text, uncap=args.uncap)\n else:\n clip = Clip(tempconcatvideo, text=text, uncap=args.uncap)\n clip.inference_frameskip = args.frameskip\n clip.inference(args.model_path, audio_cutoff=args.audio_cutoff, arch=args.arch, batch_size=args.batch_size, use_sound=not args.no_sound, concat_full=args.concat_full, fp16=args.fp16)\n if args.benchmark:\n return\n clip.bin(args.bin_size)\n print(clip.bins)\n # old method\n # clip.generate_highlights(bin_size=args.bin_size, output_path=args.name, percentile=args.percentile, threshold=args.threshold, delete_temp=args.delete_temp, adjacent=not args.no_adacjent)\n temp_clips = clip.generate_highlights_flex(bin_size=args.bin_size, output_path=args.name, threshold=args.threshold, notext=args.notext)\n os.unlink(tempconcatvideo)\n os.unlink(tempvideolist)\n else:\n path = args.prefix\n if args.bbox is not None:\n try:\n bbox = ast.literal_eval(args.bbox)\n except ValueError:\n bbox = crop_callbacks[args.bbox]\n clip = Clip(path, bbox=bbox, text=text, uncap=args.uncap)\n else:\n clip = Clip(path, text=text, uncap=args.uncap)\n clip.inference_frameskip = args.frameskip\n clip.inference(args.model_path, audio_cutoff=args.audio_cutoff, arch=args.arch, batch_size=args.batch_size, use_sound=not args.no_sound, concat_full=args.concat_full, fp16=args.fp16)\n if args.benchmark:\n return\n clip.bin(args.bin_size)\n print(clip.bins)\n #clip.generate_highlights(bin_size=args.bin_size, output_path=args.name, percentile=args.percentile, threshold=args.threshold, adjacent=not args.no_adjacent)\n temp_clips = clip.generate_highlights_flex(bin_size=args.bin_size, output_path=args.name, threshold=args.threshold, notext=args.notext, url=args.url)\n\n if args.delete_temp:\n for temp_clip_path in temp_clips:\n os.unlink(temp_clip_path)\n\n if len(temp_clips):\n if len(temp_clips) > 1:\n if args.crossfade:\n _crossfade_concat_highlights(temp_clips, args.name)\n else:\n _concat_highlights(temp_clips, args.name)\n else:\n shutil.copy(temp_clips[0], args.name)\n\n\ndef main():\n parser = argparse.ArgumentParser()\n parser.add_argument(\"-s\", \"--single-inference\", help=\"file name for single full inference\")\n parser.add_argument(\"-p\", \"--prefix\", help=\"prefix of file name to parse\")\n parser.add_argument(\"-n\", \"--name\", help=\"name of output\", required=True)\n parser.add_argument(\"-d\", \"--delete-temp\", help=\"delete temporary clips\", action='store_true')\n parser.add_argument(\"-b\", \"--benchmark\", help=\"benchmark mode\", action='store_true')\n parser.add_argument(\"--model-path\", help=\"path to model checkpoint\", default='model_best.pth.tar')\n parser.add_argument(\"-a\", \"--arch\", help=\"model architecture to use\", default='resnet18')\n parser.add_argument(\"--no-sound\", help=\"no sound\", action='store_true')\n parser.add_argument(\"--no-adjacent\", help=\"don't append adjacent segments for highlights\", action='store_true')\n parser.add_argument(\"--concat-full\", help=\"concat full frame\", action='store_true')\n parser.add_argument(\"--audio-cutoff\", help=\"audio frequency cutoff\", default=8000, type=int)\n parser.add_argument(\"--percentile\", default=0.990, type=float)\n parser.add_argument(\"--threshold\", default=0.7, type=float)\n parser.add_argument(\"--bin-size\", default=5, type=int)\n parser.add_argument(\"--batch-size\", default=32, type=int)\n parser.add_argument(\"--bbox\", type=str)\n parser.add_argument(\"--frameskip\", default=10, type=int)\n parser.add_argument(\"--chill\", action='store_true')\n parser.add_argument(\"--pog\", action='store_true')\n parser.add_argument(\"--gypsy\", action='store_true')\n parser.add_argument(\"--artosis\", action='store_true')\n parser.add_argument(\"--notext\", action='store_true')\n parser.add_argument(\"--fp16\", action='store_true')\n parser.add_argument(\"--uncap\", action='store_true', help='meme uncapped softmax')\n parser.add_argument(\"--nowaitgpu\", action='store_true', help='do not wait for at least 1 gpu')\n parser.add_argument(\"--crossfade\", action='store_true', help='use crossfade concat')\n parser.add_argument(\"--url\", type=str, help=\"url for generating clip links\")\n args = parser.parse_args()\n\n if not args.nowaitgpu:\n while not torch.cuda.device_count():\n print(torch.cuda.device_count())\n print(\"waiting for gpu to be available...\")\n time.sleep(1)\n\n # shortcut some defaults for strimmers\n if args.gypsy:\n assert not args.artosis\n assert not args.pog\n assert 'gyp' in args.model_path\n args.bbox = \"[0.77109375, 0.6875, 0.98828125, 1.0]\"\n args.bin_size = 8\n args.threshold = 0.7\n args.chill = True\n if args.artosis:\n assert not args.gypsy\n assert not args.pog\n # args.bbox = \"[0.7833, 0.1296, 0.9682, 0.3694]\"\n # args.bbox = \"[0.7572916666666667, 0.12407407407407407, 0.9854166666666667, 0.4564814814814815]\"\n args.bbox = \"artosis_callback\"\n args.bin_size = 15\n args.threshold = 0.70\n if args.pog:\n assert not args.gypsy\n assert not args.artosis\n args.bbox = \"[0.0, 0.0, 1.0, 1.0]\"\n args.bin_size = 20\n args.threshold = 0.75\n args.frameskip = 6\n\n assert args.single_inference is not None or args.prefix is not None\n if args.single_inference is not None:\n single_inference(args)\n else:\n highlights(args) \n\n\nif __name__ == '__main__':\n main()\n" ]
[ [ "torch.cuda.device_count", "numpy.mean" ] ]
The-Edgar/Marketing-Attribution-Models
[ "299a2e9097bb55da38d7c8d3cbb13e677b65efba" ]
[ "marketing_attribution_models/MAM.py" ]
[ "import numpy as np\nimport pandas as pd\nimport itertools\nimport math\nimport re\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport warnings\nplt.style.use('seaborn-white')\n\n\nclass MAM:\n \"\"\"\n MAM (Marketing Attribution Models) is a class inspired on the R Package ‘GameTheoryAllocation’ from Alejandro Saavedra-Nieves\n and ‘ChannelAttribution’ from Davide Altomare and David Loris that was created to bring these concepts to\n Python and to help us understand how the different marketing channels behave during the customer journey.\n Parameters:\n df = None by default, but should only be None if choosing to use a random dataframe. Otherwise,\n it has to receive a Pandas dataframe;\n time_till_conv_colname = None by default. Column name in the df containing the time in hours untill\n the moment of the conversion. The column must have the same elements as the\n channels_colname has.\n Values could be on a list ou a string with a separator;\n If your session is crashing here, try setting the variable time_till_conv_colname equal to 'skip_column'.\n But skipping this column you will not be able to run all the models in this class\n conversion_value = 1 by default. Integer that represents a monetary value of a 'conversion', can\n also receive a string indicating the column name on the dataframe containing the\n conversion values;\n channels_colname = None by default. Column name in the df containing the different channels during the\n customer journey. The column must have the same elements as the time_till_conv_colname\n has.\n Values could be on a list ou a string with a separator;\n journey_with_conv_colname = None by default.\n group_channels = False by default. Most important parameter on this class. This indicates the input\n format of the dataframe.\n True = Each row represents a user session that will be grouped\n into a user journey;\n False = Each row represents a user journey and the columns\n group_channels_by_id_list = Empty list by default.\n group_timestamp_colname = None by default.\n create_journey_id_based_on_conversion = False by default.\n path_separator = ' > ' by default. If using 'group_channels = True', this should match the separator\n being used on the inputed dataframe in the channels_colname;\n verbose = False by default. Internal parameter for printing while working with MAM;\n random_df = False by default. Will create a random dataframe with testing purpose;\n OBS: If your session is crashing, try setting the variable verbose True and some status and tips will be printed;\n \"\"\"\n\n def __init__(\n self,\n df=None,\n time_till_conv_colname=None,\n conversion_value=1,\n channels_colname=None,\n journey_with_conv_colname=None,\n group_channels=False,\n group_channels_by_id_list=[],\n group_timestamp_colname=None,\n create_journey_id_based_on_conversion = False,\n path_separator=' > ',\n verbose=False,\n random_df=False):\n\n self.verbose = verbose\n self.sep = path_separator\n self.group_by_channels_models = None\n\n ##########################################################\n ################## Instance attributes ###################\n ##########################################################\n\n self.__first_click = None\n self.__last_click = None\n self.__last_click_non = None\n self.__linear = None\n self.__position_based = None\n self.__time_decay = None\n\n ##########################################################\n ##### Section 0: Funcions needed to create the class #####\n ##########################################################\n\n def journey_id_based_on_conversion(df,\n group_id,\n transaction_colname):\n \"\"\"\n Internal function that creates a journey_id column into a DF containing a User ID and Boolean column\n that indicates if there has been a conversion on that instance\n \"\"\"\n df_temp = df.copy()\n\n for i in group_id:\n df_temp[i] = df_temp[i].apply(str)\n\n #Converting bool column to int\n df_temp['journey_id'] = df_temp[transaction_colname].map(lambda x: 0 if x == False else 1)\n\n #Cumsum for each transaction to expand the value for the rows that did not have a transaction\n df_temp['journey_id'] = df_temp.groupby(group_id)['journey_id'].cumsum()\n\n #Subtracting 1 only for the row that had a transaction\n t = df_temp['journey_id'] - 1\n df_temp['journey_id'] = df_temp['journey_id'].where((df_temp[transaction_colname] == False), t).apply(str)\n df_temp['journey_id'] = 'id:' + df_temp[group_id[0]] + '_J:' + df_temp['journey_id']\n\n del t\n return df_temp\n\n def random_mam_data_frame(user_id = 300, k = 50000, conv_rate = 0.4):\n import random\n channels = ['Direct', 'Direct', 'Facebook', 'Facebook', 'Facebook',\n 'Google Search', 'Google Search', 'Google Search', 'Google Search', 'Google Display',\n 'Organic', 'Organic', 'Organic', 'Organic', 'Organic', 'Organic',\n 'Email Marketing', 'Youtube', 'Instagram']\n has_transaction = ([True] * int(conv_rate * 100)) + ([False] * int((1 - conv_rate) * 100))\n user_id = list(range(0, 700))\n day = range(1, 30)\n month = range(1, 12)\n\n res = []\n for i in [channels,has_transaction, user_id, day, month]:\n res.append(random.choices(population=i, k=k))\n\n df = pd.DataFrame(res).transpose()\n df.columns = ['channels', 'has_transaction', 'user_id', 'day', 'month']\n df['visitStartTime'] = '2020-' + df['month'].apply(lambda val: str(val) if val > 9 else '0' + str(val)) +'-'+ df['day'].apply(lambda val: str(val) if val > 9 else '0' + str(val))\n\n return df\n\n #####################################################\n ##### Section 1: Creating object and attributes #####\n #####################################################\n\n ###########################\n #### random_df == True ####\n ###########################\n\n if random_df:\n df = random_mam_data_frame()\n group_channels=True\n channels_colname = 'channels'\n journey_with_conv_colname= 'has_transaction'\n group_channels_by_id_list=['user_id']\n group_timestamp_colname = 'visitStartTime'\n create_journey_id_based_on_conversion = True\n\n self.original_df = df.copy()\n\n ################################\n #### group_channels == True ####\n ################################\n\n if group_channels:\n\n # Copying, sorting and converting variables\n df = df.reset_index().copy()\n df[group_timestamp_colname] = pd.to_datetime( df[group_timestamp_colname])\n df.sort_values( group_channels_by_id_list + [group_timestamp_colname], inplace=True)\n\n if create_journey_id_based_on_conversion:\n\n df = journey_id_based_on_conversion(df = df,\n group_id = group_channels_by_id_list,\n transaction_colname = journey_with_conv_colname)\n group_channels_by_id_list = ['journey_id']\n\n # Grouping channels based on group_channels_by_id_list\n ######################################################\n \n self.print('group_channels == True')\n self.print('Grouping channels...')\n temp_channels = df.groupby(group_channels_by_id_list)[\n channels_colname].apply(list).reset_index()\n self.channels = temp_channels[channels_colname]\n self.print('Status: Done')\n\n # Grouping timestamp based on group_channels_by_id_list\n ####################################################\n self.print('Grouping timestamp...')\n df_temp = df[group_channels_by_id_list + [group_timestamp_colname]]\n df_temp = df_temp.merge(\n df.groupby(group_channels_by_id_list)[group_timestamp_colname].max(),\n on=group_channels_by_id_list)\n\n # calculating the time till conversion\n ######################################\n df_temp['time_till_conv'] = (df_temp[group_timestamp_colname + '_y'] -\n df_temp[group_timestamp_colname + '_x']).astype('timedelta64[h]')\n\n df_temp = df_temp.groupby(group_channels_by_id_list)[\n 'time_till_conv'].apply(list).reset_index()\n self.time_till_conv = df_temp['time_till_conv']\n self.print('Status: Done')\n\n if journey_with_conv_colname is None:\n\n # If journey_with_conv_colname is None, we will assume that\n # all journeys ended in a conversion\n ###########################################################\n self.journey_with_conv = self.channels.apply(lambda x: True)\n self.journey_id = pd.Series(df[group_channels_by_id_list].unique())\n\n else:\n # Grouping unique journeys and whether the journey ended with a\n # conversion\n ##########################################################\n self.print('Grouping journey_id and journey_with_conv...')\n df_temp = df[group_channels_by_id_list +\n [journey_with_conv_colname]]\n temp_journey_id_conv = df_temp.groupby(group_channels_by_id_list)[\n journey_with_conv_colname].max().reset_index()\n self.journey_id = temp_journey_id_conv[group_channels_by_id_list]\n self.print('Status: Done')\n self.journey_with_conv = temp_journey_id_conv[journey_with_conv_colname]\n self.print('Status: Done')\n\n # conversion_value could be a single int value or a panda series\n if isinstance(conversion_value, int):\n self.conversion_value = self.journey_with_conv.apply(lambda valor: conversion_value if valor else 0)\n else:\n self.conversion_value = df.groupby(group_channels_by_id_list)[conversion_value].sum().reset_index()[conversion_value]\n\n #################################\n #### group_channels == False ####\n #################################\n else:\n df = df.reset_index().copy()\n self.journey_id = df[group_channels_by_id_list]\n self.print('Status_journey_id: Done')\n\n #####################\n ### self.channels ###\n #####################\n\n # converts channels str to list of channels\n if isinstance(df[channels_colname][0], str):\n self.print('Status_journey_to_list: Working')\n self.channels = df[channels_colname].apply(lambda x: x.split(self.sep))\n self.print('Status_journey_to_list: Done')\n else:\n self.channels = df[channels_colname]\n self.print('Status_journey_to_list: Skipped')\n\n \n\n ###########################\n ### self.time_till_conv ###\n ###########################\n if time_till_conv_colname is None:\n self.print('If your session is crashing here, try setting the variable time_till_conv_colname equal to skip_column')\n self.time_till_conv = self.channels.apply(lambda x: list(range(len(x)))[::-1])\n self.time_till_conv = self.time_till_conv.apply(lambda x: list(np.asarray(x) * 24 ))\n else:\n if time_till_conv_colname == 'skip_column':\n self.time_till_conv = None\n print('Skipping this column you will not be able to run all the models in this class')\n else:\n if isinstance(df[channels_colname][0], str):\n self.time_till_conv = df[time_till_conv_colname].apply(lambda x: [float(value) for value in x.split(self.sep)])\n else:\n self.time_till_conv = df[time_till_conv_colname]\n self.print('Status_time_till_conv: Done')\n\n ##############################\n ### self.journey_with_conv ###\n ##############################\n if journey_with_conv_colname is None:\n self.journey_with_conv = self.channels.apply(lambda x: True)\n else:\n self.journey_with_conv = df[journey_with_conv_colname]\n self.print('Status_journey_with_conv: Done')\n\n ########################\n ### conversion_value ###\n ########################\n\n # conversion_value could be a single int value or a panda series\n if isinstance(conversion_value, int):\n self.conversion_value = self.journey_with_conv.apply(lambda valor: conversion_value if valor else 0)\n else:\n self.conversion_value = df[conversion_value]\n\n #################\n ### DataFrame ###\n #################\n\n self.DataFrame = None\n self.as_pd_dataframe()\n\n\n ######################################\n ##### Section 2: Output methods #####\n ######################################\n\n def print(self, *args, **kwargs):\n if self.verbose:\n print(*args, **kwargs)\n \n\n def as_pd_dataframe(self):\n \"\"\"\n Return inputed attributes as a Pandas Data Frame on self.DataFrame\n \"\"\"\n if not(isinstance(self.DataFrame, pd.DataFrame)):\n if isinstance(self.journey_id, pd.DataFrame):\n self.DataFrame = self.journey_id\n self.DataFrame['channels_agg'] = self.channels.apply(lambda x: self.sep.join(x))\n self.DataFrame['converted_agg'] = self.journey_with_conv\n self.DataFrame['conversion_value'] = self.conversion_value\n else:\n self.DataFrame = pd.DataFrame({'journey_id': self.journey_id,\n 'channels_agg': self.channels.apply(lambda x: self.sep.join(x)),\n 'converted_agg': self.journey_with_conv,\n 'conversion_value': self.conversion_value})\n if self.time_till_conv is None:\n self.DataFrame['time_till_conv_agg'] = None\n else:\n self.DataFrame['time_till_conv_agg'] = self.time_till_conv.apply(lambda x : self.sep.join([str(value) for value in x]))\n\n\n return self.DataFrame\n\n def attribution_all_models(\n self,\n model_type='all',\n last_click_non_but_not_this_channel='Direct',\n time_decay_decay_over_time=0.5,\n time_decay_frequency=128,\n shapley_size=4,\n shapley_order=False,\n shapley_values_col= 'conv_rate',\n markov_transition_to_same_state=False,\n group_by_channels_models=True):\n \"\"\"\n Runs all heuristic models on this class and returns a data frame.\n Models: attribution_last_click_non, attribution_first_click, attribution_linear, attribution_position_based, attribution_time_decay\n Parameters:\n model_type = ['all',\n 'heuristic'\n 'algorithmic']\n \"\"\"\n\n if model_type == 'all':\n heuristic = True\n algorithmic = True\n elif model_type == 'heuristic':\n heuristic = True\n algorithmic = False\n else:\n heuristic = False\n algorithmic = True\n\n if heuristic:\n # Running attribution_last_click\n self.attribution_last_click(group_by_channels_models=group_by_channels_models)\n\n # Running attribution_last_click_non\n self.attribution_last_click_non(but_not_this_channel = last_click_non_but_not_this_channel)\n\n # Running attribution_first_click\n self.attribution_first_click(group_by_channels_models=group_by_channels_models)\n\n # Running attribution_linear\n self.attribution_linear(\n group_by_channels_models=group_by_channels_models)\n\n # Running attribution_position_based\n self.attribution_position_based(group_by_channels_models=group_by_channels_models)\n\n # Running attribution_time_decay\n self.attribution_time_decay(\n decay_over_time = time_decay_decay_over_time,\n frequency=time_decay_frequency,\n group_by_channels_models=group_by_channels_models)\n\n if algorithmic:\n\n # Running attribution_shapley\n self.attribution_shapley(size=shapley_size,\n order=shapley_order,\n group_by_channels_models=group_by_channels_models,\n values_col=shapley_values_col)\n\n # Running attribution_shapley\n self.attribution_markov(transition_to_same_state=markov_transition_to_same_state)\n\n\n return self.group_by_channels_models\n\n def plot(self,\n model_type='all',\n sort_model=None,\n number_of_channels=10,\n other_df = None,\n *args, **kwargs):\n\n \"\"\"\n Barplot of the results that were generated and stored on the variable self.group_by_channels_models\n Parameters:\n model_type = ['all',\n 'heuristic'\n 'algorithmic']\n sort_model = has to be a string and accept regex by inputing r'example'\n other_df = None. In case the user wants to use a new data frame\n \"\"\"\n\n model_types = {'all':'all',\n 'heuristic': r'heuristic',\n 'algorithmic': r'algorithmic'}\n\n if not isinstance(other_df, pd.DataFrame):\n # Checking if there are any results on self.group_by_channels_models\n if isinstance(self.group_by_channels_models, pd.DataFrame):\n df_plot = self.group_by_channels_models\n else:\n ax = 'self.group_by_channels_models == None'\n else:\n df_plot = other_df\n\n # Sorting self.group_by_channels_models\n if sort_model != None:\n # List comprehension to accept regex\n df_plot = df_plot.sort_values([[x for x in df_plot.columns if (re.search(sort_model, x))]][0],\n ascending=True)\n\n #Selecting columns that matches the pattern\n if model_types[model_type] != 'all':\n df_plot = df_plot[['channels'] + [x for x in df_plot.columns if re.search(model_types[model_type], x)]]\n\n # Subsetting the results based on the number of channels to be shown\n df_plot = df_plot.tail(number_of_channels)\n\n # Melting DF so the results are devided into 'channels', 'variable' and 'value'\n df_plot = pd.melt(df_plot,id_vars='channels')\n\n # Plot Parameters\n ax, fig = plt.subplots(figsize=(20,7))\n ax = sns.barplot(data = df_plot, hue = 'variable', y = 'value', x = 'channels', *args, **kwargs)\n plt.xticks(rotation=15)\n ax.legend(loc = 'upper left', frameon = True, fancybox = True)\n ax.axhline(0, color='black', linestyle='-', alpha=1,lw=2)\n ax.grid(color='gray', linestyle=':', linewidth=1, axis='y')\n ax.set_frame_on(False)\n\n return ax\n\n\n def channels_journey_time_based_overwrite(\n self, selected_channel='Direct', time_window=24, order=1, inplace=False):\n \"\"\"\n Overwrites channels in the conversion jorney that matches the criteria with the previous\n channel in the journey:\n - Is equal to the selected_channel;\n - The diference between the contacts is less than the time_window selected;\n Parameters:\n selected_channel = channel to be overwritten;\n time_window = the time window in hours that the selected channel will be overwritten;\n order = how many times the function will loop throught the same journey;\n ex: journey [Organic > Direct > Direct]\n order 1 output: [Organic > Organic > Direct]\n order 2 output: [Organic > Organic > Organic]\n \"\"\"\n frame = self.channels.to_frame(name='channels')\n frame['time_till_conv_window'] = self.time_till_conv.apply(lambda time_till_conv: [time_window + 1] + [\n time - time_till_conv[i + 1] for i, time in enumerate(time_till_conv) if i < len(time_till_conv) - 1])\n frame['time_till_conv_window'] = frame['time_till_conv_window'].apply(\n lambda time_till_conv: np.absolute(np.asarray(time_till_conv)).tolist())\n loop_count = 0\n while loop_count < order:\n frame['channels'] = frame.apply(lambda x: [x.channels[i - 1] if ((canal == selected_channel) & (\n time < time_window)) else canal for i, (canal, time) in enumerate(zip(x.channels, x.time_till_conv_window))], axis=1)\n loop_count += 1\n\n if inplace:\n self.channels = frame['channels'].copy()\n new_channels = None\n else:\n new_channels = frame['channels'].copy()\n\n return new_channels\n\n def group_by_results_function(self, channels_value, model_name):\n \"\"\"\n Internal function to generate the group_by_channels_models. A pandas DF containing\n the attributed values for each channel\n \"\"\"\n channels_list = []\n self.channels.apply(lambda x: channels_list.extend(x))\n values_list = []\n channels_value.apply(lambda x: values_list.extend(x))\n\n frame = pd.DataFrame(\n {'channels': channels_list, 'value': values_list})\n frame = frame.groupby(['channels'])['value'].sum()\n\n if isinstance(self.group_by_channels_models, pd.DataFrame):\n frame = frame.reset_index()\n frame.columns = ['channels', model_name]\n self.group_by_channels_models = pd.merge(self.group_by_channels_models, frame,\n how='outer', on=['channels']).fillna(0)\n else:\n self.group_by_channels_models = frame.reset_index()\n self.group_by_channels_models.columns = ['channels', model_name]\n\n return frame\n\n\n ##############################################\n #\n #\n # Begin of new methods\n #\n #\n #################################\n\n def first_click_journeys(self):\n \"\"\"\n Returns an object that contains First Click results with journey granularity\n \"\"\"\n if self.__first_click is None:\n warnings.warn('In order to call this method, attribution_first_click method must be called first')\n else:\n return self.__first_click[0]\n\n def first_click_channels(self):\n \"\"\"\n Returns an object that contains First Click results with channel granularity\n \"\"\"\n if self.__first_click is None:\n warnings.warn('In order to call this method, attribution_first_click method must be called first')\n else:\n return self.__first_click[1]\n\n def last_click_journeys(self):\n \"\"\"\n Returns an object that contains Last Click results with journey granularity\n \"\"\"\n if self.__last_click is None:\n warnings.warn('In order to call this method, attribution_last_click method must be called first')\n else:\n return self.__last_click[0]\n\n def last_click_channels(self):\n \"\"\"\n Returns an object that contains Last Click results with channel granularity\n \"\"\"\n if self.__last_click is None:\n warnings.warn('In order to call this method, attribution_last_click method must be called first')\n else:\n return self.__last_click[1]\n\n def last_click_non_journeys(self):\n \"\"\"\n Returns an object that contains Last Click ignoring a specific channel results with journey granularity\n \"\"\"\n if self.__last_click_non is None:\n warnings.warn('In order to call this method, attribution_last_click_non method must be called first')\n else:\n return self.__last_click_non[0]\n\n def last_click_non_channels(self):\n \"\"\"\n Returns an object that contains Last Click ignoring a specific channel results with channel granularity\n \"\"\"\n if self.__last_click_non is None:\n warnings.warn('In order to call this method, attribution_last_click_non method must be called first')\n else:\n return self.__last_click_non[1]\n\n def linear_journeys(self):\n \"\"\"\n Returns an object that contains Linear results with journey granularity\n \"\"\"\n if self.__linear is None:\n warnings.warn('In order to call this method, attribution_linear method must be called first')\n else:\n return self.__linear[0]\n\n def linear_channels(self):\n \"\"\"\n Returns an object that contains Linear results with channel granularity\n \"\"\"\n if self.__linear is None:\n warnings.warn('In order to call this method, attribution_linear method must be called first')\n else:\n return self.__linear[1]\n\n def position_based_journeys(self):\n \"\"\"\n Returns an object that contains Position based results with journey granularity\n \"\"\"\n if self.__position_based is None:\n warnings.warn('In order to call this method, attribution_position_based method must be called first')\n else:\n return self.__position_based[0]\n\n def position_based_channels(self):\n \"\"\"\n Returns an object that contains Position Based results with channel granularity\n \"\"\"\n if self.__position_based is None:\n warnings.warn('In order to call this method, attribution_position_based method must be called first')\n else:\n return self.__position_based[1]\n\n def time_decay_journeys(self):\n \"\"\"\n Returns an object that contains Time Decay results with journey granularity\n \"\"\"\n if self.__time_decay is None:\n warnings.warn('In order to call this method, attribution_time_decay method must be called first')\n else:\n return self.__time_decay[0]\n\n def time_decay_channels(self):\n \"\"\"\n Returns an object that contains Time Decay results with channel granularity\n \"\"\"\n if self.__first_click is None:\n warnings.warn('In order to call this method, attribution_time_decay method must be called first')\n else:\n return self.__time_decay[1]\n\n ###################################################\n ##### Section 3: Channel Attribution methods #####\n ###################################################\n\n def attribution_last_click(self, group_by_channels_models=True):\n \"\"\"\n The last touchpoint receives all the credit\n Parameters:\n group_by_channels_models= True by default. Will aggregate the attributed results by each channel on\n self.group_by_channels_models\n \"\"\"\n model_name = 'attribution_last_click_heuristic'\n\n # Results part 1: Column values\n # Results in the same format as the DF\n channels_value = self.channels.apply(\n lambda channels: np.asarray(([0] * (len(channels) - 1)) + [1]))\n # multiplying the results with the conversion value\n channels_value = channels_value * self.conversion_value\n # multiplying with the boolean column that indicates whether the conversion\n # happened\n channels_value = channels_value * self.journey_with_conv.apply(int)\n channels_value = channels_value.apply(lambda values: values.tolist())\n\n # Adding the results to self.DataFrame\n self.as_pd_dataframe()\n self.DataFrame[model_name] = channels_value.apply(lambda x : self.sep.join([str(value) for value in x]))\n\n\n # Results part 2: Results\n if group_by_channels_models:\n\n\n # Selecting last channel from the series\n channels_series = self.channels.apply(lambda x: x[-1])\n\n # Creating a data_frame where we have the last channel and the\n # conversion values\n frame = channels_series.to_frame(name='channels')\n # multiplying with the boolean column that indicates if the conversion\n # happened\n frame['value'] = self.conversion_value * \\\n self.journey_with_conv.apply(int)\n\n # Grouping by channels and adding the values\n frame = frame.groupby(['channels'])['value'].sum()\n\n # Grouped Results\n if isinstance(self.group_by_channels_models, pd.DataFrame):\n frame = frame.reset_index()\n frame.columns = ['channels', model_name]\n self.group_by_channels_models = pd.merge(self.group_by_channels_models, frame, how='outer', on=['channels']).fillna(0)\n else:\n self.group_by_channels_models = frame.reset_index()\n self.group_by_channels_models.columns = ['channels', model_name]\n else:\n frame = 'group_by_channels_models = False'\n\n self.__last_click = (channels_value, frame)\n\n return self.__last_click\n\n def attribution_last_click_non(self, but_not_this_channel='Direct', group_by_channels_models=True):\n \"\"\"\n All the traffic from a Specific channel is ignored,\n and 100% of the credit for the sale goes to the last channel that the customer clicked through from before converting\n Parameters:\n but_not_this_channel = channel to be overwritten\n group_by_channels_models= True by default. Will aggregate the attributed results by each channel on\n self.group_by_channels_models\n \"\"\"\n model_name = 'attribution_last_click_non_' + but_not_this_channel + '_heuristic'\n\n # Results part 1: Column values\n # Results in the same format as the DF\n channels_value = self.channels.apply(\n lambda canais: np.asarray(\n [\n 1 if i == max(\n [\n i if canal != but_not_this_channel else 0 for i,\n canal in enumerate(canais)]) else 0 for i,\n canal in enumerate(canais)]))\n # multiplying the results with the conversion value\n channels_value = channels_value * self.conversion_value\n # multiplying with the boolean column that indicates if the conversion\n # happened\n channels_value = channels_value * self.journey_with_conv.apply(int)\n channels_value = channels_value.apply(lambda values: values.tolist())\n\n # Adding the results to self.DataFrame\n self.as_pd_dataframe()\n self.DataFrame[model_name] = channels_value.apply(lambda x : self.sep.join([str(value) for value in x]))\n\n # Results part 2: Results\n if group_by_channels_models:\n\n # Selecting the last channel that is not the one chosen\n channels_series = self.channels.apply(\n lambda canais: (\n canais[-1] if len([canal for canal in canais if canal != but_not_this_channel]) == 0\n else canais[max([i for i, canal in enumerate(canais) if canal != but_not_this_channel])]))\n\n # Creating a data_frame where we have the last channel and the\n # conversion values\n frame = channels_series.to_frame(name='channels')\n # multiplying with the boolean column that indicates whether the conversion\n # happened\n frame['value'] = self.conversion_value * \\\n self.journey_with_conv.apply(int)\n\n # Grouping by channels and adding the values\n frame = frame.groupby(['channels'])['value'].sum()\n\n if isinstance(self.group_by_channels_models, pd.DataFrame):\n frame = frame.reset_index()\n frame.columns = ['channels', model_name]\n self.group_by_channels_models = pd.merge(self.group_by_channels_models, frame, how='outer', on=['channels']).fillna(0)\n else:\n self.group_by_channels_models = frame.reset_index()\n self.group_by_channels_models.columns = ['channels', model_name]\n\n self.__last_click_non = (channels_value, frame)\n \n return self.__last_click_non\n\n def attribution_first_click(self, group_by_channels_models=True):\n \"\"\"\n The first touchpoint recieves all the credit\n Parameters:\n group_by_channels_models= True by default. Will aggregate the attributed results by each channel on\n self.group_by_channels_models\n \"\"\"\n model_name = 'attribution_first_click_heuristic'\n\n # Results part 1: Column values\n ###############################\n\n # Results in the same format as the DF\n channels_value = self.channels.apply(\n lambda channels: np.asarray([1] + ([0] * (len(channels) - 1))))\n # multiplying the results with the conversion value\n channels_value = channels_value * self.conversion_value\n # multiplying with the boolean column that indicates if the conversion\n # happened\n channels_value = channels_value * self.journey_with_conv.apply(int)\n channels_value = channels_value.apply(lambda values: values.tolist())\n\n # Adding the results to self.DataFrame\n self.as_pd_dataframe()\n self.DataFrame[model_name] = channels_value.apply(lambda x : self.sep.join([str(value) for value in x]))\n\n # Results part 2: Grouped Results\n #################################\n\n if group_by_channels_models:\n # Selecting first channel from the series\n channels_series = self.channels.apply(lambda x: x[0])\n\n # Creating a data_frame where we have the last channel and the\n # conversion values\n frame = channels_series.to_frame(name='channels')\n # multiplying with the boolean column that indicates if the conversion\n # happened\n frame['value'] = self.conversion_value * \\\n self.journey_with_conv.apply(int)\n\n # Grouping by channels and adding the values\n frame = frame.groupby(['channels'])['value'].sum()\n\n if isinstance(self.group_by_channels_models, pd.DataFrame):\n frame = frame.reset_index()\n frame.columns = ['channels', model_name]\n self.group_by_channels_models = pd.merge(self.group_by_channels_models, frame, how='outer', on=['channels']).fillna(0)\n else:\n self.group_by_channels_models = frame.reset_index()\n self.group_by_channels_models.columns = ['channels', model_name]\n \n self.__first_click = (channels_value, frame)\n\n return self.__first_click\n\n def attribution_linear(self, group_by_channels_models=True):\n \"\"\"\n Each touchpoint in the conversion path has an equal value\n Parameters:\n group_by_channels_models= True by default. Will aggregate the attributed results by each channel on\n self.group_by_channels_models\n \"\"\"\n model_name = 'attribution_linear_heuristic'\n\n channels_count = self.channels.apply(lambda x: len(x))\n channels_value = (self.conversion_value * self.journey_with_conv.apply(int) /\n channels_count).apply(lambda x: [round(x, 2)]) * channels_count\n\n # Adding the results to self.DataFrame\n self.as_pd_dataframe()\n self.DataFrame[model_name] = channels_value.apply(lambda x : self.sep.join([str(value) for value in x]))\n\n # Grouping the attributed values for each channel\n if group_by_channels_models:\n frame = self.group_by_results_function(channels_value, model_name)\n else:\n frame = 'group_by_channels_models = False'\n\n self.__linear = (channels_value, frame)\n \n return self.__linear\n\n def attribution_position_based(\n self, list_positions_first_middle_last=[\n 0.4, 0.2, 0.4], group_by_channels_models=True):\n \"\"\"\n First and last contact have preset values, middle touchpoints are evenly distributed with the chosen weight.\n default:\n - First channel = 0.4\n - Distributed among the middle channels = 0.2\n - Last channel = 0.4\n Parameters:\n list_positions_first_middle_last = list with percentages that will be given to each position\n group_by_channels_models= True by default. Will aggregate the attributed results by each channel on\n self.group_by_channels_models\n \"\"\"\n model_name = 'attribution_position_based_' + '_'.join([str(value) for value in list_positions_first_middle_last]) + '_heuristic'\n\n # Selecting last channel from the series\n channels_value = self.channels.apply(\n lambda canais: np.asarray([1]) if len(canais) == 1\n else np.asarray([list_positions_first_middle_last[0] + list_positions_first_middle_last[1] / 2, list_positions_first_middle_last[2] + list_positions_first_middle_last[1] / 2]) if len(canais) == 2\n else np.asarray([list_positions_first_middle_last[0]] + [list_positions_first_middle_last[1] / (len(canais) - 2)] * (len(canais) - 2) + [list_positions_first_middle_last[0]]))\n # multiplying the results with the conversion value\n channels_value = channels_value * self.conversion_value\n # multiplying with the boolean column that indicates if the conversion\n # happened\n channels_value = channels_value * self.journey_with_conv.apply(int)\n channels_value = channels_value.apply(lambda values: values.tolist())\n\n # Adding the results to self.DataFrame\n self.as_pd_dataframe()\n self.DataFrame[model_name] = channels_value.apply(lambda x : self.sep.join([str(value) for value in x]))\n\n # Grouping the attributed values for each channel\n if group_by_channels_models:\n frame = self.group_by_results_function(channels_value, model_name)\n else:\n frame = 'group_by_channels_models = False'\n\n self.__position_based = (channels_value, frame)\n\n return self.__position_based\n\n def attribution_position_decay(self, group_by_channels_models=True):\n \"\"\"\n OBS: This function is in working progress\n Linear decay for each touchpoint further from conversion.\n Parameters:\n group_by_channels_models= True by default. Will aggregate the attributed results by each channel on\n self.group_by_channels_models\n \"\"\"\n model_name = 'attribution_position_decay_heuristic'\n\n channels_value = self.channels.apply(\n lambda channels: np.asarray(\n [1]) if len(channels) == 1 else (\n np.asarray(\n list(\n range(\n 1,\n len(channels) +\n 1))) /\n np.sum(\n np.asarray(\n list(\n range(\n 1,\n len(channels) +\n 1))))))\n # multiplying the results with the conversion value\n channels_value = channels_value * self.conversion_value\n # multiplying with the boolean column that indicates if the conversion\n # happened\n channels_value = channels_value * self.journey_with_conv.apply(int)\n channels_value = channels_value.apply(lambda values: values.tolist())\n\n # Adding the results to self.DataFrame\n self.as_pd_dataframe()\n self.DataFrame[model_name] = channels_value.apply(lambda x : self.sep.join([str(value) for value in x]))\n\n # Grouping the attributed values for each channel\n if group_by_channels_models:\n frame = self.group_by_results_function(channels_value, model_name)\n else:\n frame = 'group_by_channels_models = False'\n\n return (channels_value, frame)\n\n def attribution_time_decay(\n self,\n decay_over_time=0.5,\n frequency=168,\n group_by_channels_models=True):\n \"\"\"\n Decays for each touchpoint further from conversion\n Parameters:\n decay_over_time = percentage that will be lost by time away from the conversion\n frequency = The frequency in hours that the decay will happen\n group_by_channels_models= True by default. Will aggregate the attributed results by each channel on\n self.group_by_channels_models\n \"\"\"\n model_name = 'attribution_time_decay' + str(decay_over_time) + '_freq' + str(frequency) + '_heuristic'\n\n if self.time_till_conv is None:\n print(\"time_till_conv is None, attribution_time_decay model will not work\")\n\n else: \n # Removing zeros and dividing by the frequency\n time_till_conv_window = self.time_till_conv.apply(lambda time_till_conv:\n np.exp(math.log(decay_over_time) * np.floor(np.asarray(time_till_conv) / frequency)) /\n sum(np.exp(math.log(decay_over_time) * np.floor(np.asarray(time_till_conv) / frequency))) )\n\n\n # multiplying the results with the conversion value\n channels_value = time_till_conv_window * self.conversion_value\n # multiplying with the boolean column that indicates if the conversion\n # happened\n channels_value = channels_value * self.journey_with_conv.apply(int)\n channels_value = channels_value.apply(lambda values: values.tolist())\n\n # Adding the results to self.DataFrame\n self.as_pd_dataframe()\n self.DataFrame[model_name] = channels_value.apply(lambda x : self.sep.join([str(value) for value in x]))\n\n # Grouping the attributed values for each channel\n if group_by_channels_models:\n frame = self.group_by_results_function(channels_value, model_name)\n else:\n frame = 'group_by_channels_models = False'\n\n self.__time_decay = (channels_value, frame)\n \n return self.__time_decay\n\n\n def attribution_markov(self, transition_to_same_state=False, group_by_channels_models=True, conversion_value_as_frequency = True):\n \"\"\"\n \"\"\"\n model_name = 'attribution_markov'\n model_type = '_algorithmic'\n if transition_to_same_state:\n model_name = model_name + '_same_state' + model_type\n else:\n model_name = model_name + model_type\n\n def power_to_infinity(matrix):\n \"\"\"\n Raises a square matrix to an infinite power using eigendecomposition.\n All matrix rows must add to 1.\n M = Q*L*inv(Q), where L = eigenvalue diagonal values, Q = eigenvector matrix\n M^N = Q*(L^N)*inv(Q)\n \"\"\"\n eigen_value, eigen_vectors = np.linalg.eig(matrix)\n\n # At infinity everything converges to 0 or 1, thus we use np.trunc()\n diagonal = np.diag(np.trunc(eigen_value.real + 0.001))\n try:\n result = (eigen_vectors @ diagonal @ np.linalg.inv(eigen_vectors)).real\n except np.linalg.LinAlgError as err:\n if 'Singular matrix' in str(err):\n warnings.warn(\"Warning... Singular matrix error. Check for lines or cols fully filled with zeros\")\n result = (eigen_vectors @ diagonal @ np.linalg.pinv(eigen_vectors)).real\n else:\n raise\n return result\n\n def normalize_rows(matrix):\n size = matrix.shape[0]\n mean = matrix.sum(axis=1).reshape((size, 1))\n mean = np.where(mean == 0, 1, mean)\n return matrix / mean\n\n def calc_total_conversion(matrix):\n normal_matrix = normalize_rows(matrix)\n infinity_matrix = power_to_infinity(normal_matrix)\n return infinity_matrix[0, -1]\n\n def removal_effect(matrix):\n size = matrix.shape[0]\n conversions = np.zeros(size)\n for column in range(1, size - 2):\n temp = matrix.copy()\n temp[:, -2] = temp[:, -2] + temp[:, column]\n temp[:, column] = 0\n conversions[column] = calc_total_conversion(temp)\n conversion_orig = calc_total_conversion(matrix)\n return 1 - (conversions / conversion_orig)\n\n def path_to_matrix(paths):\n channel_max = int(paths[:, 0:2].max()) + 1\n matrix = np.zeros((channel_max, channel_max), dtype=\"float\")\n for x, y, val in paths:\n matrix[int(x), int(y)] = val\n matrix[-1, -1] = 1\n matrix[-2, -2] = 1\n return matrix\n\n temp = self.channels.apply(\n lambda x: [\"(inicio)\"] + x) + self.journey_with_conv.apply(\n lambda x: [\n \"(conversion)\" if x else \"(null)\"])\n\n orig = []\n dest = []\n journey_length = []\n\n def save_orig_dest(arr):\n orig.extend(arr[:-1])\n dest.extend(arr[1:])\n journey_length.append(len(arr))\n\n temp.apply(save_orig_dest)\n\n # copying conversion_quantity to each new row\n if type(self.conversion_value) in (int, float):\n #we do not hava a frequency column yet so we are using self.conversion_value.apply(lambda x: 1)\n # to count each line\n conversion_quantity = self.conversion_value.apply(lambda x: 1)\n \n else:\n if conversion_value_as_frequency:\n freq_values = self.conversion_value\n else: \n freq_values = self.conversion_value.apply(lambda x: 1)\n\n conversion_quantity = []\n\n for a,b in zip(freq_values, journey_length):\n conversion_quantity.extend([a] * (b-1))\n\n temp = pd.DataFrame({\"orig\": orig, \"dest\": dest, \"count\": conversion_quantity})\n temp = temp.groupby([\"orig\", \"dest\"], as_index=False).sum()\n self.print(temp)\n\n if not transition_to_same_state:\n temp = temp[temp.orig != temp.dest]\n\n # Converting channels_names to index and pass a numpy array foward\n channels_names = (\n [\"(inicio)\"]\n + list(\n (set(temp.orig) - set([\"(inicio)\"]))\n | (set(temp.dest) - set([\"(conversion)\", \"(null)\"]))\n )\n + [\"(null)\", \"(conversion)\"]\n )\n temp[\"orig\"] = temp.orig.apply(channels_names.index)\n temp[\"dest\"] = temp.dest.apply(channels_names.index)\n matrix = path_to_matrix(temp[[\"orig\", \"dest\", \"count\"]].values)\n removal_effect_result = removal_effect(matrix)[1:-2]\n results = removal_effect_result / removal_effect_result.sum(axis=0)\n\n # Channels weights\n frame = pd.DataFrame({\"value\": results}, index=channels_names[1:-2])\n removal_effect_result = pd.DataFrame({\"removal_effect\": removal_effect_result}, index=channels_names[1:-2])\n\n # Transition matrix\n matrix = normalize_rows(matrix)\n matrix = pd.DataFrame(matrix, columns=channels_names, index=channels_names)\n\n # Apply weights back to each journey\n chmap = {a: b[0] for a,b in zip(frame.index.values, frame.values)}\n channels_value = self.channels.apply(lambda y: [chmap[x] for x in y])\n channels_value = channels_value.apply(lambda x: list(np.array(x) / sum(x)))\n\n # Adding the results to self.DataFrame\n self.as_pd_dataframe()\n self.DataFrame[model_name] = channels_value.apply(lambda x : self.sep.join([str(value) for value in x]))\n\n\n # Grouping the attributed values for each channel\n total_conv_value = self.journey_with_conv * self.conversion_value\n if group_by_channels_models:\n if isinstance(self.group_by_channels_models, pd.DataFrame):\n frame = frame.reset_index()\n frame.columns = ['channels', model_name]\n frame[model_name] = frame[model_name] * total_conv_value.sum()\n self.group_by_channels_models = pd.merge(self.group_by_channels_models, frame, how='outer', on=['channels']).fillna(0)\n else:\n frame = frame.reset_index()\n frame.columns = ['channels', model_name]\n frame[model_name] = frame[model_name] * total_conv_value.sum()\n self.group_by_channels_models = frame\n else:\n frame = 'group_by_channels_models = False'\n\n return (channels_value, frame, matrix, removal_effect_result)\n\n def journey_conversion_table(self, order = False, size = None):\n \"\"\"\n Transforms journey channels in boolean columns,\n count the number of conversions and journeys and\n compute the conversion rate of the channel combination\n \"\"\"\n #Creating Channels DF\n df_temp = self.journey_id.copy()\n\n if order:\n df_temp['combinations'] = self.channels.apply(lambda channels: sorted(list(set(channels)), key=lambda x: channels.index(x)) ).copy()\n else:\n df_temp['combinations'] = self.channels.apply(lambda channels: sorted(list(set(channels))) ).copy()\n\n if size != None:\n df_temp['combinations'] = df_temp['combinations'].apply(lambda channels: self.sep.join(channels[size * -1:]) )\n else:\n df_temp['combinations'] = df_temp['combinations'].apply(lambda channels: self.sep.join(channels) )\n\n #Adding journey_with_conv column\n df_temp['journey_with_conv'] = self.journey_with_conv.apply(int)\n df_temp['conversion_value'] = self.conversion_value\n\n\n #Grouping journey_with_conv\n conv_val = df_temp.groupby(['combinations'])['conversion_value'].sum().reset_index()['conversion_value']\n df_temp = df_temp.groupby(['combinations'])['journey_with_conv'].agg([('conversions', 'sum'), ('total_sequences', 'count')]).reset_index()\n df_temp['conversion_value'] = conv_val\n #Calculating the conversion rate\n df_temp['conv_rate'] = df_temp['conversions'] / df_temp['total_sequences']\n\n\n return df_temp\n\n def coalitions(self, size = 4, unique_channels = None, order=False):\n \"\"\"\n This function gives all the coalitions of different channels in a matrix. Most of the extra parameters\n are used when calculating Shapley's value with order.\n **size** = limits max size of unique channels in a single journey\n **unique_channels** = By default will check self.channels unique values, or a list of channels can be passed\n as well.\n **order** = Boolean that indicates if the order of channels matters during the process.\n \"\"\"\n if unique_channels is None:\n unique_channels = list(set(sum(self.channels.values, [])))\n else:\n unique_channels = unique_channels\n channels_combination = []\n\n # Creating a list with all the permutations if order is True\n if order is True:\n for L in range(0, size + 1):\n for subset in itertools.combinations(unique_channels, L):\n channels_combination.append(list(subset))\n else:\n for L in range(0, size + 1):\n for subset in itertools.combinations(sorted(unique_channels), L):\n channels_combination.append(list(subset))\n\n\n #Creating a DF with the channels as the boolean columns\n df_temp = pd.Series(channels_combination).to_frame(name='combinations')\n for channel in unique_channels:\n df_temp[channel] = df_temp.combinations.apply( lambda channels: any(channel in s for s in channels))\n\n return df_temp\n\n def attribution_shapley(self, size=4, order=False, values_col='conv_rate', group_by_channels_models = True):\n \"\"\"\n Defined by Wikipedia:\n The Shapley value is a solution concept in Cooperative Game Theory. It was named in honor of Lloyd\n Shapley, who introduced it in 1953.To each cooperative game it assigns a unique\n distribution (among the players) of a total surplus generated by the coalition of all players.\n Here in the context of marketing channels we can use the model to understand the valeu of the cooperation\n of channels to generate a conversion.\n Parameters:\n size = limits max size of unique channels in a single journey. If there is a journey that has more channels\n than the defined limit, the last N channels will be considered.\n It's also important to accentuate that increasing the number of channels, increases the number calculations\n exponentially.\n order = Boolean that indicates if the order of channels matters during the process.\n values_col = The conversion rate is used by default, but the other columns in the journey_conversion_table\n can be used as well like 'conversions', 'conversion_value'.\n group_by_channels_models = True by default. Will aggregate the attributed results by each channel on\n self.group_by_channels_models\n \"\"\"\n\n # Creating conv_table that will contain the aggregated results based on the journeys\n conv_table = self.journey_conversion_table(order=order, size=size)\n # Removing all jouneys that have not converted\n conv_table = conv_table[conv_table.conversions > 0]\n channels_shapley = conv_table.combinations.apply(lambda x: x.split(self.sep)).copy()\n results = []\n\n\n for journey in channels_shapley:\n\n n = len(journey)\n\n coalitions = self.coalitions(n, journey, order=order)\n coalitions.combinations = coalitions.combinations.apply(lambda x: self.sep.join(x))\n coa = coalitions[1:].drop('combinations',axis = 1).astype(int).astype(float).reset_index(drop=True)\n\n\n valores = pd.merge(coalitions, conv_table, on='combinations', how='left')[values_col].fillna(0).values\n\n\n v = valores[1:]\n coaux = coa.copy()\n\n for line in list(range(0,((2**n)-1))):\n\n for channel in coa.columns:\n s = len(coaux.iloc[line,:][coaux.iloc[line,:] != 0])\n if coa[channel][line] == 0:\n a = -(math.factorial(s) * math.factorial(n-s-1)) / math.factorial(n) * v[line]\n coa[channel][line] = a\n else:\n b = (math.factorial(s-1) * math.factorial(n-s)) / math.factorial(n) * v[line]\n coa[channel][line] = b\n\n results.append(list(coa.sum()))\n\n # Model col_name\n model_name = 'attribution_shapley_size' + str(size) + '_' + values_col\n model_type = '_algorithmic'\n if order:\n model_name = model_name+ '_order' + model_type\n else:\n model_name = model_name + model_type\n\n\n if values_col == 'conv_rate':\n conv_table[model_name] = results\n conv_table[model_name] = conv_table[model_name].apply(lambda x: np.asarray(x)) * conv_table['total_sequences']\n conv_table[model_name] = conv_table[model_name].apply(lambda x: x / x.sum() ) * conv_table['conversion_value']\n conv_table[model_name] = conv_table[model_name].apply(lambda x: x.tolist())\n else:\n conv_table[model_name] = results\n\n ##########################\n #group_by_channels_models#\n ##########################\n\n\n # Aggregating the results by unique channel\n if group_by_channels_models:\n channels_list = sum(channels_shapley, [])\n values_list = sum(conv_table[model_name].values, [])\n frame = pd.DataFrame(\n {'channels': channels_list, 'value': values_list})\n frame = frame.groupby(['channels'])['value'].sum()\n\n if isinstance(self.group_by_channels_models, pd.DataFrame):\n frame = frame.reset_index()\n frame.columns = ['channels', model_name]\n self.group_by_channels_models = pd.merge(self.group_by_channels_models, frame, how='outer', on=['channels']).fillna(0)\n else:\n self.group_by_channels_models = frame.reset_index()\n self.group_by_channels_models.columns = ['channels', model_name]\n else:\n frame = 'group_by_channels_models=False'\n\n return (conv_table, frame)\n" ]
[ [ "numpy.trunc", "pandas.to_datetime", "pandas.merge", "pandas.Series", "numpy.asarray", "numpy.linalg.eig", "numpy.linalg.inv", "matplotlib.pyplot.subplots", "pandas.DataFrame", "numpy.linalg.pinv", "pandas.melt", "matplotlib.pyplot.xticks", "numpy.array", "numpy.where", "matplotlib.pyplot.style.use", "numpy.zeros" ] ]
MrMiilk/SuperPoint
[ "a67bac07f6922677f0108b26d434bf4b61ee9de9" ]
[ "superpoint/models/classical_detectors.py" ]
[ "import tensorflow as tf\nimport numpy as np\nimport cv2\n\nfrom .base_model import BaseModel\nfrom .utils import box_nms\n\n\ndef classical_detector(im, **config):\n if config['method'] == 'harris':\n detections = cv2.cornerHarris(im, 4, 3, 0.04)\n\n elif config['method'] == 'shi':\n detections = np.zeros(im.shape[:2], np.float)\n thresh = np.linspace(0.0001, 1, 600, endpoint=False)\n for t in thresh:\n corners = cv2.goodFeaturesToTrack(im, 600, t, 5)\n if corners is not None:\n corners = corners.astype(np.int)\n detections[(corners[:, 0, 1], corners[:, 0, 0])] = t\n\n elif config['method'] == 'fast':\n detector = cv2.FastFeatureDetector_create(10)\n corners = detector.detect(im.astype(np.uint8))\n detections = np.zeros(im.shape[:2], np.float)\n for c in corners:\n detections[tuple(np.flip(np.int0(c.pt), 0))] = c.response\n\n elif config['method'] == 'random':\n detections = np.random.rand(im.shape[0], im.shape[1])\n\n return detections.astype(np.float32)\n\n\nclass ClassicalDetectors(BaseModel):\n input_spec = {\n 'image': {'shape': [None, None, None, 1], 'type': tf.float32}\n }\n default_config = {\n 'method': 'harris', # 'shi', 'fast', 'random'\n 'threshold': 0.5,\n 'nms': 4,\n 'top_k': 300,\n }\n trainable = False\n\n def _model(self, inputs, mode, **config):\n im = inputs['image']\n with tf.device('/cpu:0'):\n prob = tf.map_fn(lambda i: tf.py_func(\n lambda x: classical_detector(x, **config), [i], tf.float32), im)\n prob_nms = prob\n if config['nms']:\n prob_nms = tf.map_fn(lambda p: box_nms(p, config['nms'], min_prob=0.,\n keep_top_k=config['top_k']), prob)\n pred = tf.cast(tf.greater_equal(prob_nms, config['threshold']), tf.int32)\n return {'prob': prob, 'prob_nms': prob_nms, 'pred': pred}\n\n def _loss(self, outputs, inputs, **config):\n raise NotImplementedError\n\n def _metrics(self, outputs, inputs, **config):\n pred = outputs['pred']\n labels = inputs['keypoint_map']\n precision = tf.reduce_sum(pred*labels) / tf.reduce_sum(pred)\n recall = tf.reduce_sum(pred*labels) / tf.reduce_sum(labels)\n return {'precision': precision, 'recall': recall}\n" ]
[ [ "numpy.int0", "tensorflow.device", "numpy.linspace", "tensorflow.reduce_sum", "numpy.random.rand", "tensorflow.greater_equal", "numpy.zeros" ] ]
dashings/CAMVIS
[ "fb7e4e5d885ae227140f7ab40b5f47e730ec249b" ]
[ "models/long_range_perception/eval.py" ]
[ "import tqdm\nimport torch\nimport torch.nn as nn\n\nimport numpy as np\nfrom sklearn.metrics import roc_auc_score, roc_curve\n\nimport seaborn as sns\nimport matplotlib.pyplot as plt\n\nfrom .model import SimpleCNN\nfrom .utils import *\n\nmodel = torch.load('./model.pt', map_location=lambda storage, loc: storage)\ntest_dl, test_ds = get_dl(np.arange(9, 11), H5_PATH, test=True)\n\n# TEST\ntot_loss = torch.zeros(1).to(device)\nbar = tqdm.tqdm(enumerate(test_dl))\ni = 0\n\nmodel.eval()\nrng = np.random.RandomState(13) # 13 lucky number\n\ndistances = list(range(0, 65, 1))\nn_dist = len(distances)\n\nauc_array = []\n\ndef eval():\n model = SimpleCNN().to(device)\n\n criterion = nn.MSELoss()\n\n tot_loss = torch.zeros(1).to(device)\n bar = tqdm.tqdm(enumerate(test_dl))\n\n for n_batch, (x, y) in bar:\n\n x, y = x.to(device), y.to(device)\n\n mask = y != -1\n\n mask = mask.to(device).float()\n\n y_ = model(x)\n loss = criterion(y_ * mask, y * mask)\n\n\n with torch.no_grad():\n tot_loss += loss\n\n bar.set_description('loss={:.4f}'.format((tot_loss / (n_batch + 1)).cpu().item()))\n\n print((tot_loss / (n_batch + 1)).cpu().item())\n\ndef make_auc_map():\n for i in range(1):\n with torch.no_grad():\n x, y = test_ds[500]\n\n x, y = x.unsqueeze(0), y.unsqueeze(0),\n accs = 0\n\n x, y = x.to(device), y.to(device)\n\n mask = y != -1\n\n mask = mask.cpu().numpy()\n # mask[y == -1] = 0\n y_ = model(x)\n\n y_ = y_.cpu().numpy()\n y = y.cpu().numpy()\n\n print(mask.shape)\n # for y_1, y1 in zip(y_, y):\n # y1 = np.expand_dims(y1, axis=0)\n # y_1 = np.expand_dims(y_1, axis=0)\n\n aucs = np.zeros([n_dist, 5])\n y_1 = y\n y1=y_\n for i, d in enumerate(distances):\n for j in range(5):\n print(mask[:,i * 5 + j])\n indices = np.where(mask[i * 5 : i * 5 +j])\n print(indices, 'indices')\n\n yc_1 = y_1[indices, i * 5 + j]\n yc1 = y1[indices, i * 5 + j]\n\n if len(indices[0]) > 0:\n indices = (rng.choice(indices[0], len(indices[0])),)\n try:\n yc1, yc_1 = yc1.tolist()[0], yc_1.tolist()[0]\n auc = roc_auc_score(yc1, yc_1)\n print(auc, 'ddddd')\n except ValueError as e:\n auc = 0.5\n aucs[n_dist - 1 - i, j] = auc\n break\n auc_array.append(aucs)\n\n # AUC MAP\n mean_auc = np.mean(auc_array, axis=0)\n std_auc = np.std(auc_array, axis=0)\n\n dist_labels = ['%.0f' % d for d in np.flipud(distances)]\n dist_labels = [d for i, d in enumerate(dist_labels) if i % 2 == 0]\n colors = ['aqua', 'darkorange', 'deeppink', 'cornflowerblue', 'green']\n\n fig, ax = plt.subplots(nrows=1, ncols=1, figsize=(8, 8))\n sns.heatmap(mean_auc * 100, cmap='gray', annot=True, vmin=50, vmax=100, annot_kws={\"color\": \"white\"})\n ax.set_xticklabels(['left', '', 'center', '', 'right'])\n ax.set_yticklabels(dist_labels, rotation=0)\n plt.xlabel('Sensors')\n plt.ylabel('Distance [cm]')\n plt.title('Area Under the pReceiver Operating Characteristic Curve')\n plt.show()\n\neval()" ]
[ [ "sklearn.metrics.roc_auc_score", "matplotlib.pyplot.title", "torch.zeros", "torch.load", "numpy.arange", "numpy.flipud", "matplotlib.pyplot.subplots", "numpy.std", "numpy.mean", "torch.no_grad", "numpy.where", "matplotlib.pyplot.xlabel", "numpy.random.RandomState", "numpy.zeros", "torch.nn.MSELoss", "matplotlib.pyplot.show", "matplotlib.pyplot.ylabel" ] ]
jacarvalho/mushroom-rl
[ "ba0a62454d771a1d3cacbec1ea9d71535f476b31" ]
[ "mushroom_rl/algorithms/actor_critic/classic_actor_critic/stochastic_ac.py" ]
[ "import numpy as np\n\nfrom mushroom_rl.algorithms.agent import Agent\nfrom mushroom_rl.approximators import Regressor\nfrom mushroom_rl.approximators.parametric import LinearApproximator\n\n\nclass StochasticAC(Agent):\n \"\"\"\n Stochastic Actor critic in the episodic setting as presented in:\n \"Model-Free Reinforcement Learning with Continuous Action in Practice\".\n Degris T. et al.. 2012.\n\n \"\"\"\n def __init__(self, mdp_info, policy, alpha_theta, alpha_v, lambda_par=.9,\n value_function_features=None, policy_features=None):\n \"\"\"\n Constructor.\n\n Args:\n alpha_theta (Parameter): learning rate for policy update;\n alpha_v (Parameter): learning rate for the value function;\n lambda_par (float, .9): trace decay parameter;\n value_function_features (Features, None): features used by the\n value function approximator;\n policy_features (Features, None): features used by the policy.\n\n \"\"\"\n self._psi = value_function_features\n\n self._alpha_theta = alpha_theta\n self._alpha_v = alpha_v\n\n self._lambda = lambda_par\n\n super().__init__(mdp_info, policy, policy_features)\n\n if self._psi is not None:\n input_shape = (self._psi.size,)\n else:\n input_shape = mdp_info.observation_space.shape\n\n self._V = Regressor(LinearApproximator, input_shape=input_shape,\n output_shape=(1,))\n\n self._e_v = np.zeros(self._V.weights_size)\n self._e_theta = np.zeros(self.policy.weights_size)\n\n self._add_save_attr(\n _psi='pickle',\n _alpha_theta='pickle',\n _alpha_v='pickle',\n _lambda='numpy',\n _V='pickle',\n _e_v='numpy',\n _e_theta='numpy'\n )\n\n def episode_start(self):\n self._e_v = np.zeros(self._V.weights_size)\n self._e_theta = np.zeros(self.policy.weights_size)\n\n super().episode_start()\n\n def fit(self, dataset):\n for step in dataset:\n s, a, r, ss, absorbing, _ = step\n\n s_phi = self.phi(s) if self.phi is not None else s\n s_psi = self._psi(s) if self._psi is not None else s\n ss_psi = self._psi(ss) if self._psi is not None else ss\n\n v_next = self._V(ss_psi) if not absorbing else 0\n\n delta = self._compute_td_n_traces(a, r, v_next, s_psi, s_phi)\n\n # Update value function\n delta_v = self._alpha_v(s, a) * delta * self._e_v\n v_new = self._V.get_weights() + delta_v\n self._V.set_weights(v_new)\n\n # Update policy\n delta_theta = self._alpha_theta(s, a) * delta * self._e_theta\n theta_new = self.policy.get_weights() + delta_theta\n self.policy.set_weights(theta_new)\n\n def _compute_td_n_traces(self, a, r, v_next, s_psi, s_phi):\n # Compute TD error\n delta = r + self.mdp_info.gamma * v_next - self._V(s_psi)\n\n # Update traces\n self._e_v = self.mdp_info.gamma * self._lambda * self._e_v + s_psi\n self._e_theta = self.mdp_info.gamma * self._lambda * \\\n self._e_theta + self.policy.diff_log(s_phi, a)\n\n return delta\n\n\nclass StochasticAC_AVG(StochasticAC):\n \"\"\"\n Stochastic Actor critic in the average reward setting as presented in:\n \"Model-Free Reinforcement Learning with Continuous Action in Practice\".\n Degris T. et al.. 2012.\n\n \"\"\"\n def __init__(self, mdp_info, policy, alpha_theta, alpha_v, alpha_r,\n lambda_par=.9, value_function_features=None,\n policy_features=None):\n \"\"\"\n Constructor.\n\n Args:\n alpha_r (Parameter): learning rate for the reward trace.\n\n \"\"\"\n super().__init__(mdp_info, policy, alpha_theta, alpha_v, lambda_par,\n value_function_features, policy_features)\n\n self._alpha_r = alpha_r\n self._r_bar = 0\n\n self._add_save_attr(_alpha_r='pickle', _r_bar='numpy')\n\n def _compute_td_n_traces(self, a, r, v_next, s_psi, s_phi):\n # Compute TD error\n delta = r - self._r_bar + v_next - self._V(s_psi)\n\n # Update traces\n self._r_bar += self._alpha_r() * delta\n self._e_v = self._lambda * self._e_v + s_psi\n self._e_theta = self._lambda * self._e_theta + \\\n self.policy.diff_log(s_phi, a)\n\n return delta\n" ]
[ [ "numpy.zeros" ] ]
zhiqiang-hu/bl_iot_sdk
[ "154ee677a8cc6a73e6a42a5ff12a8edc71e6d15d" ]
[ "toolchain/riscv/Linux/python/lib/python3.7/test/test_buffer.py" ]
[ "#\n# The ndarray object from _testbuffer.c is a complete implementation of\n# a PEP-3118 buffer provider. It is independent from NumPy's ndarray\n# and the tests don't require NumPy.\n#\n# If NumPy is present, some tests check both ndarray implementations\n# against each other.\n#\n# Most ndarray tests also check that memoryview(ndarray) behaves in\n# the same way as the original. Thus, a substantial part of the\n# memoryview tests is now in this module.\n#\n# Written and designed by Stefan Krah for Python 3.3.\n#\n\nimport contextlib\nimport unittest\nfrom test import support\nfrom itertools import permutations, product\nfrom random import randrange, sample, choice\nimport warnings\nimport sys, array, io, os\nfrom decimal import Decimal\nfrom fractions import Fraction\n\ntry:\n from _testbuffer import *\nexcept ImportError:\n ndarray = None\n\ntry:\n import struct\nexcept ImportError:\n struct = None\n\ntry:\n import ctypes\nexcept ImportError:\n ctypes = None\n\ntry:\n with support.EnvironmentVarGuard() as os.environ, \\\n warnings.catch_warnings():\n from numpy import ndarray as numpy_array\nexcept ImportError:\n numpy_array = None\n\n\nSHORT_TEST = True\n\n\n# ======================================================================\n# Random lists by format specifier\n# ======================================================================\n\n# Native format chars and their ranges.\nNATIVE = {\n '?':0, 'c':0, 'b':0, 'B':0,\n 'h':0, 'H':0, 'i':0, 'I':0,\n 'l':0, 'L':0, 'n':0, 'N':0,\n 'f':0, 'd':0, 'P':0\n}\n\n# NumPy does not have 'n' or 'N':\nif numpy_array:\n del NATIVE['n']\n del NATIVE['N']\n\nif struct:\n try:\n # Add \"qQ\" if present in native mode.\n struct.pack('Q', 2**64-1)\n NATIVE['q'] = 0\n NATIVE['Q'] = 0\n except struct.error:\n pass\n\n# Standard format chars and their ranges.\nSTANDARD = {\n '?':(0, 2), 'c':(0, 1<<8),\n 'b':(-(1<<7), 1<<7), 'B':(0, 1<<8),\n 'h':(-(1<<15), 1<<15), 'H':(0, 1<<16),\n 'i':(-(1<<31), 1<<31), 'I':(0, 1<<32),\n 'l':(-(1<<31), 1<<31), 'L':(0, 1<<32),\n 'q':(-(1<<63), 1<<63), 'Q':(0, 1<<64),\n 'f':(-(1<<63), 1<<63), 'd':(-(1<<1023), 1<<1023)\n}\n\ndef native_type_range(fmt):\n \"\"\"Return range of a native type.\"\"\"\n if fmt == 'c':\n lh = (0, 256)\n elif fmt == '?':\n lh = (0, 2)\n elif fmt == 'f':\n lh = (-(1<<63), 1<<63)\n elif fmt == 'd':\n lh = (-(1<<1023), 1<<1023)\n else:\n for exp in (128, 127, 64, 63, 32, 31, 16, 15, 8, 7):\n try:\n struct.pack(fmt, (1<<exp)-1)\n break\n except struct.error:\n pass\n lh = (-(1<<exp), 1<<exp) if exp & 1 else (0, 1<<exp)\n return lh\n\nfmtdict = {\n '':NATIVE,\n '@':NATIVE,\n '<':STANDARD,\n '>':STANDARD,\n '=':STANDARD,\n '!':STANDARD\n}\n\nif struct:\n for fmt in fmtdict['@']:\n fmtdict['@'][fmt] = native_type_range(fmt)\n\nMEMORYVIEW = NATIVE.copy()\nARRAY = NATIVE.copy()\nfor k in NATIVE:\n if not k in \"bBhHiIlLfd\":\n del ARRAY[k]\n\nBYTEFMT = NATIVE.copy()\nfor k in NATIVE:\n if not k in \"Bbc\":\n del BYTEFMT[k]\n\nfmtdict['m'] = MEMORYVIEW\nfmtdict['@m'] = MEMORYVIEW\nfmtdict['a'] = ARRAY\nfmtdict['b'] = BYTEFMT\nfmtdict['@b'] = BYTEFMT\n\n# Capabilities of the test objects:\nMODE = 0\nMULT = 1\ncap = { # format chars # multiplier\n 'ndarray': (['', '@', '<', '>', '=', '!'], ['', '1', '2', '3']),\n 'array': (['a'], ['']),\n 'numpy': ([''], ['']),\n 'memoryview': (['@m', 'm'], ['']),\n 'bytefmt': (['@b', 'b'], ['']),\n}\n\ndef randrange_fmt(mode, char, obj):\n \"\"\"Return random item for a type specified by a mode and a single\n format character.\"\"\"\n x = randrange(*fmtdict[mode][char])\n if char == 'c':\n x = bytes([x])\n if obj == 'numpy' and x == b'\\x00':\n # http://projects.scipy.org/numpy/ticket/1925\n x = b'\\x01'\n if char == '?':\n x = bool(x)\n if char == 'f' or char == 'd':\n x = struct.pack(char, x)\n x = struct.unpack(char, x)[0]\n return x\n\ndef gen_item(fmt, obj):\n \"\"\"Return single random item.\"\"\"\n mode, chars = fmt.split('#')\n x = []\n for c in chars:\n x.append(randrange_fmt(mode, c, obj))\n return x[0] if len(x) == 1 else tuple(x)\n\ndef gen_items(n, fmt, obj):\n \"\"\"Return a list of random items (or a scalar).\"\"\"\n if n == 0:\n return gen_item(fmt, obj)\n lst = [0] * n\n for i in range(n):\n lst[i] = gen_item(fmt, obj)\n return lst\n\ndef struct_items(n, obj):\n mode = choice(cap[obj][MODE])\n xfmt = mode + '#'\n fmt = mode.strip('amb')\n nmemb = randrange(2, 10) # number of struct members\n for _ in range(nmemb):\n char = choice(tuple(fmtdict[mode]))\n multiplier = choice(cap[obj][MULT])\n xfmt += (char * int(multiplier if multiplier else 1))\n fmt += (multiplier + char)\n items = gen_items(n, xfmt, obj)\n item = gen_item(xfmt, obj)\n return fmt, items, item\n\ndef randitems(n, obj='ndarray', mode=None, char=None):\n \"\"\"Return random format, items, item.\"\"\"\n if mode is None:\n mode = choice(cap[obj][MODE])\n if char is None:\n char = choice(tuple(fmtdict[mode]))\n multiplier = choice(cap[obj][MULT])\n fmt = mode + '#' + char * int(multiplier if multiplier else 1)\n items = gen_items(n, fmt, obj)\n item = gen_item(fmt, obj)\n fmt = mode.strip('amb') + multiplier + char\n return fmt, items, item\n\ndef iter_mode(n, obj='ndarray'):\n \"\"\"Iterate through supported mode/char combinations.\"\"\"\n for mode in cap[obj][MODE]:\n for char in fmtdict[mode]:\n yield randitems(n, obj, mode, char)\n\ndef iter_format(nitems, testobj='ndarray'):\n \"\"\"Yield (format, items, item) for all possible modes and format\n characters plus one random compound format string.\"\"\"\n for t in iter_mode(nitems, testobj):\n yield t\n if testobj != 'ndarray':\n return\n yield struct_items(nitems, testobj)\n\n\ndef is_byte_format(fmt):\n return 'c' in fmt or 'b' in fmt or 'B' in fmt\n\ndef is_memoryview_format(fmt):\n \"\"\"format suitable for memoryview\"\"\"\n x = len(fmt)\n return ((x == 1 or (x == 2 and fmt[0] == '@')) and\n fmt[x-1] in MEMORYVIEW)\n\nNON_BYTE_FORMAT = [c for c in fmtdict['@'] if not is_byte_format(c)]\n\n\n# ======================================================================\n# Multi-dimensional tolist(), slicing and slice assignments\n# ======================================================================\n\ndef atomp(lst):\n \"\"\"Tuple items (representing structs) are regarded as atoms.\"\"\"\n return not isinstance(lst, list)\n\ndef listp(lst):\n return isinstance(lst, list)\n\ndef prod(lst):\n \"\"\"Product of list elements.\"\"\"\n if len(lst) == 0:\n return 0\n x = lst[0]\n for v in lst[1:]:\n x *= v\n return x\n\ndef strides_from_shape(ndim, shape, itemsize, layout):\n \"\"\"Calculate strides of a contiguous array. Layout is 'C' or\n 'F' (Fortran).\"\"\"\n if ndim == 0:\n return ()\n if layout == 'C':\n strides = list(shape[1:]) + [itemsize]\n for i in range(ndim-2, -1, -1):\n strides[i] *= strides[i+1]\n else:\n strides = [itemsize] + list(shape[:-1])\n for i in range(1, ndim):\n strides[i] *= strides[i-1]\n return strides\n\ndef _ca(items, s):\n \"\"\"Convert flat item list to the nested list representation of a\n multidimensional C array with shape 's'.\"\"\"\n if atomp(items):\n return items\n if len(s) == 0:\n return items[0]\n lst = [0] * s[0]\n stride = len(items) // s[0] if s[0] else 0\n for i in range(s[0]):\n start = i*stride\n lst[i] = _ca(items[start:start+stride], s[1:])\n return lst\n\ndef _fa(items, s):\n \"\"\"Convert flat item list to the nested list representation of a\n multidimensional Fortran array with shape 's'.\"\"\"\n if atomp(items):\n return items\n if len(s) == 0:\n return items[0]\n lst = [0] * s[0]\n stride = s[0]\n for i in range(s[0]):\n lst[i] = _fa(items[i::stride], s[1:])\n return lst\n\ndef carray(items, shape):\n if listp(items) and not 0 in shape and prod(shape) != len(items):\n raise ValueError(\"prod(shape) != len(items)\")\n return _ca(items, shape)\n\ndef farray(items, shape):\n if listp(items) and not 0 in shape and prod(shape) != len(items):\n raise ValueError(\"prod(shape) != len(items)\")\n return _fa(items, shape)\n\ndef indices(shape):\n \"\"\"Generate all possible tuples of indices.\"\"\"\n iterables = [range(v) for v in shape]\n return product(*iterables)\n\ndef getindex(ndim, ind, strides):\n \"\"\"Convert multi-dimensional index to the position in the flat list.\"\"\"\n ret = 0\n for i in range(ndim):\n ret += strides[i] * ind[i]\n return ret\n\ndef transpose(src, shape):\n \"\"\"Transpose flat item list that is regarded as a multi-dimensional\n matrix defined by shape: dest...[k][j][i] = src[i][j][k]... \"\"\"\n if not shape:\n return src\n ndim = len(shape)\n sstrides = strides_from_shape(ndim, shape, 1, 'C')\n dstrides = strides_from_shape(ndim, shape[::-1], 1, 'C')\n dest = [0] * len(src)\n for ind in indices(shape):\n fr = getindex(ndim, ind, sstrides)\n to = getindex(ndim, ind[::-1], dstrides)\n dest[to] = src[fr]\n return dest\n\ndef _flatten(lst):\n \"\"\"flatten list\"\"\"\n if lst == []:\n return lst\n if atomp(lst):\n return [lst]\n return _flatten(lst[0]) + _flatten(lst[1:])\n\ndef flatten(lst):\n \"\"\"flatten list or return scalar\"\"\"\n if atomp(lst): # scalar\n return lst\n return _flatten(lst)\n\ndef slice_shape(lst, slices):\n \"\"\"Get the shape of lst after slicing: slices is a list of slice\n objects.\"\"\"\n if atomp(lst):\n return []\n return [len(lst[slices[0]])] + slice_shape(lst[0], slices[1:])\n\ndef multislice(lst, slices):\n \"\"\"Multi-dimensional slicing: slices is a list of slice objects.\"\"\"\n if atomp(lst):\n return lst\n return [multislice(sublst, slices[1:]) for sublst in lst[slices[0]]]\n\ndef m_assign(llst, rlst, lslices, rslices):\n \"\"\"Multi-dimensional slice assignment: llst and rlst are the operands,\n lslices and rslices are lists of slice objects. llst and rlst must\n have the same structure.\n\n For a two-dimensional example, this is not implemented in Python:\n\n llst[0:3:2, 0:3:2] = rlst[1:3:1, 1:3:1]\n\n Instead we write:\n\n lslices = [slice(0,3,2), slice(0,3,2)]\n rslices = [slice(1,3,1), slice(1,3,1)]\n multislice_assign(llst, rlst, lslices, rslices)\n \"\"\"\n if atomp(rlst):\n return rlst\n rlst = [m_assign(l, r, lslices[1:], rslices[1:])\n for l, r in zip(llst[lslices[0]], rlst[rslices[0]])]\n llst[lslices[0]] = rlst\n return llst\n\ndef cmp_structure(llst, rlst, lslices, rslices):\n \"\"\"Compare the structure of llst[lslices] and rlst[rslices].\"\"\"\n lshape = slice_shape(llst, lslices)\n rshape = slice_shape(rlst, rslices)\n if (len(lshape) != len(rshape)):\n return -1\n for i in range(len(lshape)):\n if lshape[i] != rshape[i]:\n return -1\n if lshape[i] == 0:\n return 0\n return 0\n\ndef multislice_assign(llst, rlst, lslices, rslices):\n \"\"\"Return llst after assigning: llst[lslices] = rlst[rslices]\"\"\"\n if cmp_structure(llst, rlst, lslices, rslices) < 0:\n raise ValueError(\"lvalue and rvalue have different structures\")\n return m_assign(llst, rlst, lslices, rslices)\n\n\n# ======================================================================\n# Random structures\n# ======================================================================\n\n#\n# PEP-3118 is very permissive with respect to the contents of a\n# Py_buffer. In particular:\n#\n# - shape can be zero\n# - strides can be any integer, including zero\n# - offset can point to any location in the underlying\n# memory block, provided that it is a multiple of\n# itemsize.\n#\n# The functions in this section test and verify random structures\n# in full generality. A structure is valid iff it fits in the\n# underlying memory block.\n#\n# The structure 't' (short for 'tuple') is fully defined by:\n#\n# t = (memlen, itemsize, ndim, shape, strides, offset)\n#\n\ndef verify_structure(memlen, itemsize, ndim, shape, strides, offset):\n \"\"\"Verify that the parameters represent a valid array within\n the bounds of the allocated memory:\n char *mem: start of the physical memory block\n memlen: length of the physical memory block\n offset: (char *)buf - mem\n \"\"\"\n if offset % itemsize:\n return False\n if offset < 0 or offset+itemsize > memlen:\n return False\n if any(v % itemsize for v in strides):\n return False\n\n if ndim <= 0:\n return ndim == 0 and not shape and not strides\n if 0 in shape:\n return True\n\n imin = sum(strides[j]*(shape[j]-1) for j in range(ndim)\n if strides[j] <= 0)\n imax = sum(strides[j]*(shape[j]-1) for j in range(ndim)\n if strides[j] > 0)\n\n return 0 <= offset+imin and offset+imax+itemsize <= memlen\n\ndef get_item(lst, indices):\n for i in indices:\n lst = lst[i]\n return lst\n\ndef memory_index(indices, t):\n \"\"\"Location of an item in the underlying memory.\"\"\"\n memlen, itemsize, ndim, shape, strides, offset = t\n p = offset\n for i in range(ndim):\n p += strides[i]*indices[i]\n return p\n\ndef is_overlapping(t):\n \"\"\"The structure 't' is overlapping if at least one memory location\n is visited twice while iterating through all possible tuples of\n indices.\"\"\"\n memlen, itemsize, ndim, shape, strides, offset = t\n visited = 1<<memlen\n for ind in indices(shape):\n i = memory_index(ind, t)\n bit = 1<<i\n if visited & bit:\n return True\n visited |= bit\n return False\n\ndef rand_structure(itemsize, valid, maxdim=5, maxshape=16, shape=()):\n \"\"\"Return random structure:\n (memlen, itemsize, ndim, shape, strides, offset)\n If 'valid' is true, the returned structure is valid, otherwise invalid.\n If 'shape' is given, use that instead of creating a random shape.\n \"\"\"\n if not shape:\n ndim = randrange(maxdim+1)\n if (ndim == 0):\n if valid:\n return itemsize, itemsize, ndim, (), (), 0\n else:\n nitems = randrange(1, 16+1)\n memlen = nitems * itemsize\n offset = -itemsize if randrange(2) == 0 else memlen\n return memlen, itemsize, ndim, (), (), offset\n\n minshape = 2\n n = randrange(100)\n if n >= 95 and valid:\n minshape = 0\n elif n >= 90:\n minshape = 1\n shape = [0] * ndim\n\n for i in range(ndim):\n shape[i] = randrange(minshape, maxshape+1)\n else:\n ndim = len(shape)\n\n maxstride = 5\n n = randrange(100)\n zero_stride = True if n >= 95 and n & 1 else False\n\n strides = [0] * ndim\n strides[ndim-1] = itemsize * randrange(-maxstride, maxstride+1)\n if not zero_stride and strides[ndim-1] == 0:\n strides[ndim-1] = itemsize\n\n for i in range(ndim-2, -1, -1):\n maxstride *= shape[i+1] if shape[i+1] else 1\n if zero_stride:\n strides[i] = itemsize * randrange(-maxstride, maxstride+1)\n else:\n strides[i] = ((1,-1)[randrange(2)] *\n itemsize * randrange(1, maxstride+1))\n\n imin = imax = 0\n if not 0 in shape:\n imin = sum(strides[j]*(shape[j]-1) for j in range(ndim)\n if strides[j] <= 0)\n imax = sum(strides[j]*(shape[j]-1) for j in range(ndim)\n if strides[j] > 0)\n\n nitems = imax - imin\n if valid:\n offset = -imin * itemsize\n memlen = offset + (imax+1) * itemsize\n else:\n memlen = (-imin + imax) * itemsize\n offset = -imin-itemsize if randrange(2) == 0 else memlen\n return memlen, itemsize, ndim, shape, strides, offset\n\ndef randslice_from_slicelen(slicelen, listlen):\n \"\"\"Create a random slice of len slicelen that fits into listlen.\"\"\"\n maxstart = listlen - slicelen\n start = randrange(maxstart+1)\n maxstep = (listlen - start) // slicelen if slicelen else 1\n step = randrange(1, maxstep+1)\n stop = start + slicelen * step\n s = slice(start, stop, step)\n _, _, _, control = slice_indices(s, listlen)\n if control != slicelen:\n raise RuntimeError\n return s\n\ndef randslice_from_shape(ndim, shape):\n \"\"\"Create two sets of slices for an array x with shape 'shape'\n such that shapeof(x[lslices]) == shapeof(x[rslices]).\"\"\"\n lslices = [0] * ndim\n rslices = [0] * ndim\n for n in range(ndim):\n l = shape[n]\n slicelen = randrange(1, l+1) if l > 0 else 0\n lslices[n] = randslice_from_slicelen(slicelen, l)\n rslices[n] = randslice_from_slicelen(slicelen, l)\n return tuple(lslices), tuple(rslices)\n\ndef rand_aligned_slices(maxdim=5, maxshape=16):\n \"\"\"Create (lshape, rshape, tuple(lslices), tuple(rslices)) such that\n shapeof(x[lslices]) == shapeof(y[rslices]), where x is an array\n with shape 'lshape' and y is an array with shape 'rshape'.\"\"\"\n ndim = randrange(1, maxdim+1)\n minshape = 2\n n = randrange(100)\n if n >= 95:\n minshape = 0\n elif n >= 90:\n minshape = 1\n all_random = True if randrange(100) >= 80 else False\n lshape = [0]*ndim; rshape = [0]*ndim\n lslices = [0]*ndim; rslices = [0]*ndim\n\n for n in range(ndim):\n small = randrange(minshape, maxshape+1)\n big = randrange(minshape, maxshape+1)\n if big < small:\n big, small = small, big\n\n # Create a slice that fits the smaller value.\n if all_random:\n start = randrange(-small, small+1)\n stop = randrange(-small, small+1)\n step = (1,-1)[randrange(2)] * randrange(1, small+2)\n s_small = slice(start, stop, step)\n _, _, _, slicelen = slice_indices(s_small, small)\n else:\n slicelen = randrange(1, small+1) if small > 0 else 0\n s_small = randslice_from_slicelen(slicelen, small)\n\n # Create a slice of the same length for the bigger value.\n s_big = randslice_from_slicelen(slicelen, big)\n if randrange(2) == 0:\n rshape[n], lshape[n] = big, small\n rslices[n], lslices[n] = s_big, s_small\n else:\n rshape[n], lshape[n] = small, big\n rslices[n], lslices[n] = s_small, s_big\n\n return lshape, rshape, tuple(lslices), tuple(rslices)\n\ndef randitems_from_structure(fmt, t):\n \"\"\"Return a list of random items for structure 't' with format\n 'fmtchar'.\"\"\"\n memlen, itemsize, _, _, _, _ = t\n return gen_items(memlen//itemsize, '#'+fmt, 'numpy')\n\ndef ndarray_from_structure(items, fmt, t, flags=0):\n \"\"\"Return ndarray from the tuple returned by rand_structure()\"\"\"\n memlen, itemsize, ndim, shape, strides, offset = t\n return ndarray(items, shape=shape, strides=strides, format=fmt,\n offset=offset, flags=ND_WRITABLE|flags)\n\ndef numpy_array_from_structure(items, fmt, t):\n \"\"\"Return numpy_array from the tuple returned by rand_structure()\"\"\"\n memlen, itemsize, ndim, shape, strides, offset = t\n buf = bytearray(memlen)\n for j, v in enumerate(items):\n struct.pack_into(fmt, buf, j*itemsize, v)\n return numpy_array(buffer=buf, shape=shape, strides=strides,\n dtype=fmt, offset=offset)\n\n\n# ======================================================================\n# memoryview casts\n# ======================================================================\n\ndef cast_items(exporter, fmt, itemsize, shape=None):\n \"\"\"Interpret the raw memory of 'exporter' as a list of items with\n size 'itemsize'. If shape=None, the new structure is assumed to\n be 1-D with n * itemsize = bytelen. If shape is given, the usual\n constraint for contiguous arrays prod(shape) * itemsize = bytelen\n applies. On success, return (items, shape). If the constraints\n cannot be met, return (None, None). If a chunk of bytes is interpreted\n as NaN as a result of float conversion, return ('nan', None).\"\"\"\n bytelen = exporter.nbytes\n if shape:\n if prod(shape) * itemsize != bytelen:\n return None, shape\n elif shape == []:\n if exporter.ndim == 0 or itemsize != bytelen:\n return None, shape\n else:\n n, r = divmod(bytelen, itemsize)\n shape = [n]\n if r != 0:\n return None, shape\n\n mem = exporter.tobytes()\n byteitems = [mem[i:i+itemsize] for i in range(0, len(mem), itemsize)]\n\n items = []\n for v in byteitems:\n item = struct.unpack(fmt, v)[0]\n if item != item:\n return 'nan', shape\n items.append(item)\n\n return (items, shape) if shape != [] else (items[0], shape)\n\ndef gencastshapes():\n \"\"\"Generate shapes to test casting.\"\"\"\n for n in range(32):\n yield [n]\n ndim = randrange(4, 6)\n minshape = 1 if randrange(100) > 80 else 2\n yield [randrange(minshape, 5) for _ in range(ndim)]\n ndim = randrange(2, 4)\n minshape = 1 if randrange(100) > 80 else 2\n yield [randrange(minshape, 5) for _ in range(ndim)]\n\n\n# ======================================================================\n# Actual tests\n# ======================================================================\n\ndef genslices(n):\n \"\"\"Generate all possible slices for a single dimension.\"\"\"\n return product(range(-n, n+1), range(-n, n+1), range(-n, n+1))\n\ndef genslices_ndim(ndim, shape):\n \"\"\"Generate all possible slice tuples for 'shape'.\"\"\"\n iterables = [genslices(shape[n]) for n in range(ndim)]\n return product(*iterables)\n\ndef rslice(n, allow_empty=False):\n \"\"\"Generate random slice for a single dimension of length n.\n If zero=True, the slices may be empty, otherwise they will\n be non-empty.\"\"\"\n minlen = 0 if allow_empty or n == 0 else 1\n slicelen = randrange(minlen, n+1)\n return randslice_from_slicelen(slicelen, n)\n\ndef rslices(n, allow_empty=False):\n \"\"\"Generate random slices for a single dimension.\"\"\"\n for _ in range(5):\n yield rslice(n, allow_empty)\n\ndef rslices_ndim(ndim, shape, iterations=5):\n \"\"\"Generate random slice tuples for 'shape'.\"\"\"\n # non-empty slices\n for _ in range(iterations):\n yield tuple(rslice(shape[n]) for n in range(ndim))\n # possibly empty slices\n for _ in range(iterations):\n yield tuple(rslice(shape[n], allow_empty=True) for n in range(ndim))\n # invalid slices\n yield tuple(slice(0,1,0) for _ in range(ndim))\n\ndef rpermutation(iterable, r=None):\n pool = tuple(iterable)\n r = len(pool) if r is None else r\n yield tuple(sample(pool, r))\n\ndef ndarray_print(nd):\n \"\"\"Print ndarray for debugging.\"\"\"\n try:\n x = nd.tolist()\n except (TypeError, NotImplementedError):\n x = nd.tobytes()\n if isinstance(nd, ndarray):\n offset = nd.offset\n flags = nd.flags\n else:\n offset = 'unknown'\n flags = 'unknown'\n print(\"ndarray(%s, shape=%s, strides=%s, suboffsets=%s, offset=%s, \"\n \"format='%s', itemsize=%s, flags=%s)\" %\n (x, nd.shape, nd.strides, nd.suboffsets, offset,\n nd.format, nd.itemsize, flags))\n sys.stdout.flush()\n\n\nITERATIONS = 100\nMAXDIM = 5\nMAXSHAPE = 10\n\nif SHORT_TEST:\n ITERATIONS = 10\n MAXDIM = 3\n MAXSHAPE = 4\n genslices = rslices\n genslices_ndim = rslices_ndim\n permutations = rpermutation\n\n\n@unittest.skipUnless(struct, 'struct module required for this test.')\n@unittest.skipUnless(ndarray, 'ndarray object required for this test')\nclass TestBufferProtocol(unittest.TestCase):\n\n def setUp(self):\n # The suboffsets tests need sizeof(void *).\n self.sizeof_void_p = get_sizeof_void_p()\n\n def verify(self, result, obj=-1,\n itemsize={1}, fmt=-1, readonly={1},\n ndim={1}, shape=-1, strides=-1,\n lst=-1, sliced=False, cast=False):\n # Verify buffer contents against expected values. Default values\n # are deliberately initialized to invalid types.\n if shape:\n expected_len = prod(shape)*itemsize\n else:\n if not fmt: # array has been implicitly cast to unsigned bytes\n expected_len = len(lst)\n else: # ndim = 0\n expected_len = itemsize\n\n # Reconstruct suboffsets from strides. Support for slicing\n # could be added, but is currently only needed for test_getbuf().\n suboffsets = ()\n if result.suboffsets:\n self.assertGreater(ndim, 0)\n\n suboffset0 = 0\n for n in range(1, ndim):\n if shape[n] == 0:\n break\n if strides[n] <= 0:\n suboffset0 += -strides[n] * (shape[n]-1)\n\n suboffsets = [suboffset0] + [-1 for v in range(ndim-1)]\n\n # Not correct if slicing has occurred in the first dimension.\n stride0 = self.sizeof_void_p\n if strides[0] < 0:\n stride0 = -stride0\n strides = [stride0] + list(strides[1:])\n\n self.assertIs(result.obj, obj)\n self.assertEqual(result.nbytes, expected_len)\n self.assertEqual(result.itemsize, itemsize)\n self.assertEqual(result.format, fmt)\n self.assertEqual(result.readonly, readonly)\n self.assertEqual(result.ndim, ndim)\n self.assertEqual(result.shape, tuple(shape))\n if not (sliced and suboffsets):\n self.assertEqual(result.strides, tuple(strides))\n self.assertEqual(result.suboffsets, tuple(suboffsets))\n\n if isinstance(result, ndarray) or is_memoryview_format(fmt):\n rep = result.tolist() if fmt else result.tobytes()\n self.assertEqual(rep, lst)\n\n if not fmt: # array has been cast to unsigned bytes,\n return # the remaining tests won't work.\n\n # PyBuffer_GetPointer() is the definition how to access an item.\n # If PyBuffer_GetPointer(indices) is correct for all possible\n # combinations of indices, the buffer is correct.\n #\n # Also test tobytes() against the flattened 'lst', with all items\n # packed to bytes.\n if not cast: # casts chop up 'lst' in different ways\n b = bytearray()\n buf_err = None\n for ind in indices(shape):\n try:\n item1 = get_pointer(result, ind)\n item2 = get_item(lst, ind)\n if isinstance(item2, tuple):\n x = struct.pack(fmt, *item2)\n else:\n x = struct.pack(fmt, item2)\n b.extend(x)\n except BufferError:\n buf_err = True # re-exporter does not provide full buffer\n break\n self.assertEqual(item1, item2)\n\n if not buf_err:\n # test tobytes()\n self.assertEqual(result.tobytes(), b)\n\n # test hex()\n m = memoryview(result)\n h = \"\".join(\"%02x\" % c for c in b)\n self.assertEqual(m.hex(), h)\n\n # lst := expected multi-dimensional logical representation\n # flatten(lst) := elements in C-order\n ff = fmt if fmt else 'B'\n flattened = flatten(lst)\n\n # Rules for 'A': if the array is already contiguous, return\n # the array unaltered. Otherwise, return a contiguous 'C'\n # representation.\n for order in ['C', 'F', 'A']:\n expected = result\n if order == 'F':\n if not is_contiguous(result, 'A') or \\\n is_contiguous(result, 'C'):\n # For constructing the ndarray, convert the\n # flattened logical representation to Fortran order.\n trans = transpose(flattened, shape)\n expected = ndarray(trans, shape=shape, format=ff,\n flags=ND_FORTRAN)\n else: # 'C', 'A'\n if not is_contiguous(result, 'A') or \\\n is_contiguous(result, 'F') and order == 'C':\n # The flattened list is already in C-order.\n expected = ndarray(flattened, shape=shape, format=ff)\n\n contig = get_contiguous(result, PyBUF_READ, order)\n self.assertEqual(contig.tobytes(), b)\n self.assertTrue(cmp_contig(contig, expected))\n\n if ndim == 0:\n continue\n\n nmemb = len(flattened)\n ro = 0 if readonly else ND_WRITABLE\n\n ### See comment in test_py_buffer_to_contiguous for an\n ### explanation why these tests are valid.\n\n # To 'C'\n contig = py_buffer_to_contiguous(result, 'C', PyBUF_FULL_RO)\n self.assertEqual(len(contig), nmemb * itemsize)\n initlst = [struct.unpack_from(fmt, contig, n*itemsize)\n for n in range(nmemb)]\n if len(initlst[0]) == 1:\n initlst = [v[0] for v in initlst]\n\n y = ndarray(initlst, shape=shape, flags=ro, format=fmt)\n self.assertEqual(memoryview(y), memoryview(result))\n\n # To 'F'\n contig = py_buffer_to_contiguous(result, 'F', PyBUF_FULL_RO)\n self.assertEqual(len(contig), nmemb * itemsize)\n initlst = [struct.unpack_from(fmt, contig, n*itemsize)\n for n in range(nmemb)]\n if len(initlst[0]) == 1:\n initlst = [v[0] for v in initlst]\n\n y = ndarray(initlst, shape=shape, flags=ro|ND_FORTRAN,\n format=fmt)\n self.assertEqual(memoryview(y), memoryview(result))\n\n # To 'A'\n contig = py_buffer_to_contiguous(result, 'A', PyBUF_FULL_RO)\n self.assertEqual(len(contig), nmemb * itemsize)\n initlst = [struct.unpack_from(fmt, contig, n*itemsize)\n for n in range(nmemb)]\n if len(initlst[0]) == 1:\n initlst = [v[0] for v in initlst]\n\n f = ND_FORTRAN if is_contiguous(result, 'F') else 0\n y = ndarray(initlst, shape=shape, flags=f|ro, format=fmt)\n self.assertEqual(memoryview(y), memoryview(result))\n\n if is_memoryview_format(fmt):\n try:\n m = memoryview(result)\n except BufferError: # re-exporter does not provide full information\n return\n ex = result.obj if isinstance(result, memoryview) else result\n self.assertIs(m.obj, ex)\n self.assertEqual(m.nbytes, expected_len)\n self.assertEqual(m.itemsize, itemsize)\n self.assertEqual(m.format, fmt)\n self.assertEqual(m.readonly, readonly)\n self.assertEqual(m.ndim, ndim)\n self.assertEqual(m.shape, tuple(shape))\n if not (sliced and suboffsets):\n self.assertEqual(m.strides, tuple(strides))\n self.assertEqual(m.suboffsets, tuple(suboffsets))\n\n n = 1 if ndim == 0 else len(lst)\n self.assertEqual(len(m), n)\n\n rep = result.tolist() if fmt else result.tobytes()\n self.assertEqual(rep, lst)\n self.assertEqual(m, result)\n\n def verify_getbuf(self, orig_ex, ex, req, sliced=False):\n def simple_fmt(ex):\n return ex.format == '' or ex.format == 'B'\n def match(req, flag):\n return ((req&flag) == flag)\n\n if (# writable request to read-only exporter\n (ex.readonly and match(req, PyBUF_WRITABLE)) or\n # cannot match explicit contiguity request\n (match(req, PyBUF_C_CONTIGUOUS) and not ex.c_contiguous) or\n (match(req, PyBUF_F_CONTIGUOUS) and not ex.f_contiguous) or\n (match(req, PyBUF_ANY_CONTIGUOUS) and not ex.contiguous) or\n # buffer needs suboffsets\n (not match(req, PyBUF_INDIRECT) and ex.suboffsets) or\n # buffer without strides must be C-contiguous\n (not match(req, PyBUF_STRIDES) and not ex.c_contiguous) or\n # PyBUF_SIMPLE|PyBUF_FORMAT and PyBUF_WRITABLE|PyBUF_FORMAT\n (not match(req, PyBUF_ND) and match(req, PyBUF_FORMAT))):\n\n self.assertRaises(BufferError, ndarray, ex, getbuf=req)\n return\n\n if isinstance(ex, ndarray) or is_memoryview_format(ex.format):\n lst = ex.tolist()\n else:\n nd = ndarray(ex, getbuf=PyBUF_FULL_RO)\n lst = nd.tolist()\n\n # The consumer may have requested default values or a NULL format.\n ro = 0 if match(req, PyBUF_WRITABLE) else ex.readonly\n fmt = ex.format\n itemsize = ex.itemsize\n ndim = ex.ndim\n if not match(req, PyBUF_FORMAT):\n # itemsize refers to the original itemsize before the cast.\n # The equality product(shape) * itemsize = len still holds.\n # The equality calcsize(format) = itemsize does _not_ hold.\n fmt = ''\n lst = orig_ex.tobytes() # Issue 12834\n if not match(req, PyBUF_ND):\n ndim = 1\n shape = orig_ex.shape if match(req, PyBUF_ND) else ()\n strides = orig_ex.strides if match(req, PyBUF_STRIDES) else ()\n\n nd = ndarray(ex, getbuf=req)\n self.verify(nd, obj=ex,\n itemsize=itemsize, fmt=fmt, readonly=ro,\n ndim=ndim, shape=shape, strides=strides,\n lst=lst, sliced=sliced)\n\n def test_ndarray_getbuf(self):\n requests = (\n # distinct flags\n PyBUF_INDIRECT, PyBUF_STRIDES, PyBUF_ND, PyBUF_SIMPLE,\n PyBUF_C_CONTIGUOUS, PyBUF_F_CONTIGUOUS, PyBUF_ANY_CONTIGUOUS,\n # compound requests\n PyBUF_FULL, PyBUF_FULL_RO,\n PyBUF_RECORDS, PyBUF_RECORDS_RO,\n PyBUF_STRIDED, PyBUF_STRIDED_RO,\n PyBUF_CONTIG, PyBUF_CONTIG_RO,\n )\n # items and format\n items_fmt = (\n ([True if x % 2 else False for x in range(12)], '?'),\n ([1,2,3,4,5,6,7,8,9,10,11,12], 'b'),\n ([1,2,3,4,5,6,7,8,9,10,11,12], 'B'),\n ([(2**31-x) if x % 2 else (-2**31+x) for x in range(12)], 'l')\n )\n # shape, strides, offset\n structure = (\n ([], [], 0),\n ([1,3,1], [], 0),\n ([12], [], 0),\n ([12], [-1], 11),\n ([6], [2], 0),\n ([6], [-2], 11),\n ([3, 4], [], 0),\n ([3, 4], [-4, -1], 11),\n ([2, 2], [4, 1], 4),\n ([2, 2], [-4, -1], 8)\n )\n # ndarray creation flags\n ndflags = (\n 0, ND_WRITABLE, ND_FORTRAN, ND_FORTRAN|ND_WRITABLE,\n ND_PIL, ND_PIL|ND_WRITABLE\n )\n # flags that can actually be used as flags\n real_flags = (0, PyBUF_WRITABLE, PyBUF_FORMAT,\n PyBUF_WRITABLE|PyBUF_FORMAT)\n\n for items, fmt in items_fmt:\n itemsize = struct.calcsize(fmt)\n for shape, strides, offset in structure:\n strides = [v * itemsize for v in strides]\n offset *= itemsize\n for flags in ndflags:\n\n if strides and (flags&ND_FORTRAN):\n continue\n if not shape and (flags&ND_PIL):\n continue\n\n _items = items if shape else items[0]\n ex1 = ndarray(_items, format=fmt, flags=flags,\n shape=shape, strides=strides, offset=offset)\n ex2 = ex1[::-2] if shape else None\n\n m1 = memoryview(ex1)\n if ex2:\n m2 = memoryview(ex2)\n if ex1.ndim == 0 or (ex1.ndim == 1 and shape and strides):\n self.assertEqual(m1, ex1)\n if ex2 and ex2.ndim == 1 and shape and strides:\n self.assertEqual(m2, ex2)\n\n for req in requests:\n for bits in real_flags:\n self.verify_getbuf(ex1, ex1, req|bits)\n self.verify_getbuf(ex1, m1, req|bits)\n if ex2:\n self.verify_getbuf(ex2, ex2, req|bits,\n sliced=True)\n self.verify_getbuf(ex2, m2, req|bits,\n sliced=True)\n\n items = [1,2,3,4,5,6,7,8,9,10,11,12]\n\n # ND_GETBUF_FAIL\n ex = ndarray(items, shape=[12], flags=ND_GETBUF_FAIL)\n self.assertRaises(BufferError, ndarray, ex)\n\n # Request complex structure from a simple exporter. In this\n # particular case the test object is not PEP-3118 compliant.\n base = ndarray([9], [1])\n ex = ndarray(base, getbuf=PyBUF_SIMPLE)\n self.assertRaises(BufferError, ndarray, ex, getbuf=PyBUF_WRITABLE)\n self.assertRaises(BufferError, ndarray, ex, getbuf=PyBUF_ND)\n self.assertRaises(BufferError, ndarray, ex, getbuf=PyBUF_STRIDES)\n self.assertRaises(BufferError, ndarray, ex, getbuf=PyBUF_C_CONTIGUOUS)\n self.assertRaises(BufferError, ndarray, ex, getbuf=PyBUF_F_CONTIGUOUS)\n self.assertRaises(BufferError, ndarray, ex, getbuf=PyBUF_ANY_CONTIGUOUS)\n nd = ndarray(ex, getbuf=PyBUF_SIMPLE)\n\n # Issue #22445: New precise contiguity definition.\n for shape in [1,12,1], [7,0,7]:\n for order in 0, ND_FORTRAN:\n ex = ndarray(items, shape=shape, flags=order|ND_WRITABLE)\n self.assertTrue(is_contiguous(ex, 'F'))\n self.assertTrue(is_contiguous(ex, 'C'))\n\n for flags in requests:\n nd = ndarray(ex, getbuf=flags)\n self.assertTrue(is_contiguous(nd, 'F'))\n self.assertTrue(is_contiguous(nd, 'C'))\n\n def test_ndarray_exceptions(self):\n nd = ndarray([9], [1])\n ndm = ndarray([9], [1], flags=ND_VAREXPORT)\n\n # Initialization of a new ndarray or mutation of an existing array.\n for c in (ndarray, nd.push, ndm.push):\n # Invalid types.\n self.assertRaises(TypeError, c, {1,2,3})\n self.assertRaises(TypeError, c, [1,2,'3'])\n self.assertRaises(TypeError, c, [1,2,(3,4)])\n self.assertRaises(TypeError, c, [1,2,3], shape={3})\n self.assertRaises(TypeError, c, [1,2,3], shape=[3], strides={1})\n self.assertRaises(TypeError, c, [1,2,3], shape=[3], offset=[])\n self.assertRaises(TypeError, c, [1], shape=[1], format={})\n self.assertRaises(TypeError, c, [1], shape=[1], flags={})\n self.assertRaises(TypeError, c, [1], shape=[1], getbuf={})\n\n # ND_FORTRAN flag is only valid without strides.\n self.assertRaises(TypeError, c, [1], shape=[1], strides=[1],\n flags=ND_FORTRAN)\n\n # ND_PIL flag is only valid with ndim > 0.\n self.assertRaises(TypeError, c, [1], shape=[], flags=ND_PIL)\n\n # Invalid items.\n self.assertRaises(ValueError, c, [], shape=[1])\n self.assertRaises(ValueError, c, ['XXX'], shape=[1], format=\"L\")\n # Invalid combination of items and format.\n self.assertRaises(struct.error, c, [1000], shape=[1], format=\"B\")\n self.assertRaises(ValueError, c, [1,(2,3)], shape=[2], format=\"B\")\n self.assertRaises(ValueError, c, [1,2,3], shape=[3], format=\"QL\")\n\n # Invalid ndim.\n n = ND_MAX_NDIM+1\n self.assertRaises(ValueError, c, [1]*n, shape=[1]*n)\n\n # Invalid shape.\n self.assertRaises(ValueError, c, [1], shape=[-1])\n self.assertRaises(ValueError, c, [1,2,3], shape=['3'])\n self.assertRaises(OverflowError, c, [1], shape=[2**128])\n # prod(shape) * itemsize != len(items)\n self.assertRaises(ValueError, c, [1,2,3,4,5], shape=[2,2], offset=3)\n\n # Invalid strides.\n self.assertRaises(ValueError, c, [1,2,3], shape=[3], strides=['1'])\n self.assertRaises(OverflowError, c, [1], shape=[1],\n strides=[2**128])\n\n # Invalid combination of strides and shape.\n self.assertRaises(ValueError, c, [1,2], shape=[2,1], strides=[1])\n # Invalid combination of strides and format.\n self.assertRaises(ValueError, c, [1,2,3,4], shape=[2], strides=[3],\n format=\"L\")\n\n # Invalid offset.\n self.assertRaises(ValueError, c, [1,2,3], shape=[3], offset=4)\n self.assertRaises(ValueError, c, [1,2,3], shape=[1], offset=3,\n format=\"L\")\n\n # Invalid format.\n self.assertRaises(ValueError, c, [1,2,3], shape=[3], format=\"\")\n self.assertRaises(struct.error, c, [(1,2,3)], shape=[1],\n format=\"@#$\")\n\n # Striding out of the memory bounds.\n items = [1,2,3,4,5,6,7,8,9,10]\n self.assertRaises(ValueError, c, items, shape=[2,3],\n strides=[-3, -2], offset=5)\n\n # Constructing consumer: format argument invalid.\n self.assertRaises(TypeError, c, bytearray(), format=\"Q\")\n\n # Constructing original base object: getbuf argument invalid.\n self.assertRaises(TypeError, c, [1], shape=[1], getbuf=PyBUF_FULL)\n\n # Shape argument is mandatory for original base objects.\n self.assertRaises(TypeError, c, [1])\n\n\n # PyBUF_WRITABLE request to read-only provider.\n self.assertRaises(BufferError, ndarray, b'123', getbuf=PyBUF_WRITABLE)\n\n # ND_VAREXPORT can only be specified during construction.\n nd = ndarray([9], [1], flags=ND_VAREXPORT)\n self.assertRaises(ValueError, nd.push, [1], [1], flags=ND_VAREXPORT)\n\n # Invalid operation for consumers: push/pop\n nd = ndarray(b'123')\n self.assertRaises(BufferError, nd.push, [1], [1])\n self.assertRaises(BufferError, nd.pop)\n\n # ND_VAREXPORT not set: push/pop fail with exported buffers\n nd = ndarray([9], [1])\n nd.push([1], [1])\n m = memoryview(nd)\n self.assertRaises(BufferError, nd.push, [1], [1])\n self.assertRaises(BufferError, nd.pop)\n m.release()\n nd.pop()\n\n # Single remaining buffer: pop fails\n self.assertRaises(BufferError, nd.pop)\n del nd\n\n # get_pointer()\n self.assertRaises(TypeError, get_pointer, {}, [1,2,3])\n self.assertRaises(TypeError, get_pointer, b'123', {})\n\n nd = ndarray(list(range(100)), shape=[1]*100)\n self.assertRaises(ValueError, get_pointer, nd, [5])\n\n nd = ndarray(list(range(12)), shape=[3,4])\n self.assertRaises(ValueError, get_pointer, nd, [2,3,4])\n self.assertRaises(ValueError, get_pointer, nd, [3,3])\n self.assertRaises(ValueError, get_pointer, nd, [-3,3])\n self.assertRaises(OverflowError, get_pointer, nd, [1<<64,3])\n\n # tolist() needs format\n ex = ndarray([1,2,3], shape=[3], format='L')\n nd = ndarray(ex, getbuf=PyBUF_SIMPLE)\n self.assertRaises(ValueError, nd.tolist)\n\n # memoryview_from_buffer()\n ex1 = ndarray([1,2,3], shape=[3], format='L')\n ex2 = ndarray(ex1)\n nd = ndarray(ex2)\n self.assertRaises(TypeError, nd.memoryview_from_buffer)\n\n nd = ndarray([(1,)*200], shape=[1], format='L'*200)\n self.assertRaises(TypeError, nd.memoryview_from_buffer)\n\n n = ND_MAX_NDIM\n nd = ndarray(list(range(n)), shape=[1]*n)\n self.assertRaises(ValueError, nd.memoryview_from_buffer)\n\n # get_contiguous()\n nd = ndarray([1], shape=[1])\n self.assertRaises(TypeError, get_contiguous, 1, 2, 3, 4, 5)\n self.assertRaises(TypeError, get_contiguous, nd, \"xyz\", 'C')\n self.assertRaises(OverflowError, get_contiguous, nd, 2**64, 'C')\n self.assertRaises(TypeError, get_contiguous, nd, PyBUF_READ, 961)\n self.assertRaises(UnicodeEncodeError, get_contiguous, nd, PyBUF_READ,\n '\\u2007')\n self.assertRaises(ValueError, get_contiguous, nd, PyBUF_READ, 'Z')\n self.assertRaises(ValueError, get_contiguous, nd, 255, 'A')\n\n # cmp_contig()\n nd = ndarray([1], shape=[1])\n self.assertRaises(TypeError, cmp_contig, 1, 2, 3, 4, 5)\n self.assertRaises(TypeError, cmp_contig, {}, nd)\n self.assertRaises(TypeError, cmp_contig, nd, {})\n\n # is_contiguous()\n nd = ndarray([1], shape=[1])\n self.assertRaises(TypeError, is_contiguous, 1, 2, 3, 4, 5)\n self.assertRaises(TypeError, is_contiguous, {}, 'A')\n self.assertRaises(TypeError, is_contiguous, nd, 201)\n\n def test_ndarray_linked_list(self):\n for perm in permutations(range(5)):\n m = [0]*5\n nd = ndarray([1,2,3], shape=[3], flags=ND_VAREXPORT)\n m[0] = memoryview(nd)\n\n for i in range(1, 5):\n nd.push([1,2,3], shape=[3])\n m[i] = memoryview(nd)\n\n for i in range(5):\n m[perm[i]].release()\n\n self.assertRaises(BufferError, nd.pop)\n del nd\n\n def test_ndarray_format_scalar(self):\n # ndim = 0: scalar\n for fmt, scalar, _ in iter_format(0):\n itemsize = struct.calcsize(fmt)\n nd = ndarray(scalar, shape=(), format=fmt)\n self.verify(nd, obj=None,\n itemsize=itemsize, fmt=fmt, readonly=1,\n ndim=0, shape=(), strides=(),\n lst=scalar)\n\n def test_ndarray_format_shape(self):\n # ndim = 1, shape = [n]\n nitems = randrange(1, 10)\n for fmt, items, _ in iter_format(nitems):\n itemsize = struct.calcsize(fmt)\n for flags in (0, ND_PIL):\n nd = ndarray(items, shape=[nitems], format=fmt, flags=flags)\n self.verify(nd, obj=None,\n itemsize=itemsize, fmt=fmt, readonly=1,\n ndim=1, shape=(nitems,), strides=(itemsize,),\n lst=items)\n\n def test_ndarray_format_strides(self):\n # ndim = 1, strides\n nitems = randrange(1, 30)\n for fmt, items, _ in iter_format(nitems):\n itemsize = struct.calcsize(fmt)\n for step in range(-5, 5):\n if step == 0:\n continue\n\n shape = [len(items[::step])]\n strides = [step*itemsize]\n offset = itemsize*(nitems-1) if step < 0 else 0\n\n for flags in (0, ND_PIL):\n nd = ndarray(items, shape=shape, strides=strides,\n format=fmt, offset=offset, flags=flags)\n self.verify(nd, obj=None,\n itemsize=itemsize, fmt=fmt, readonly=1,\n ndim=1, shape=shape, strides=strides,\n lst=items[::step])\n\n def test_ndarray_fortran(self):\n items = [1,2,3,4,5,6,7,8,9,10,11,12]\n ex = ndarray(items, shape=(3, 4), strides=(1, 3))\n nd = ndarray(ex, getbuf=PyBUF_F_CONTIGUOUS|PyBUF_FORMAT)\n self.assertEqual(nd.tolist(), farray(items, (3, 4)))\n\n def test_ndarray_multidim(self):\n for ndim in range(5):\n shape_t = [randrange(2, 10) for _ in range(ndim)]\n nitems = prod(shape_t)\n for shape in permutations(shape_t):\n\n fmt, items, _ = randitems(nitems)\n itemsize = struct.calcsize(fmt)\n\n for flags in (0, ND_PIL):\n if ndim == 0 and flags == ND_PIL:\n continue\n\n # C array\n nd = ndarray(items, shape=shape, format=fmt, flags=flags)\n\n strides = strides_from_shape(ndim, shape, itemsize, 'C')\n lst = carray(items, shape)\n self.verify(nd, obj=None,\n itemsize=itemsize, fmt=fmt, readonly=1,\n ndim=ndim, shape=shape, strides=strides,\n lst=lst)\n\n if is_memoryview_format(fmt):\n # memoryview: reconstruct strides\n ex = ndarray(items, shape=shape, format=fmt)\n nd = ndarray(ex, getbuf=PyBUF_CONTIG_RO|PyBUF_FORMAT)\n self.assertTrue(nd.strides == ())\n mv = nd.memoryview_from_buffer()\n self.verify(mv, obj=None,\n itemsize=itemsize, fmt=fmt, readonly=1,\n ndim=ndim, shape=shape, strides=strides,\n lst=lst)\n\n # Fortran array\n nd = ndarray(items, shape=shape, format=fmt,\n flags=flags|ND_FORTRAN)\n\n strides = strides_from_shape(ndim, shape, itemsize, 'F')\n lst = farray(items, shape)\n self.verify(nd, obj=None,\n itemsize=itemsize, fmt=fmt, readonly=1,\n ndim=ndim, shape=shape, strides=strides,\n lst=lst)\n\n def test_ndarray_index_invalid(self):\n # not writable\n nd = ndarray([1], shape=[1])\n self.assertRaises(TypeError, nd.__setitem__, 1, 8)\n mv = memoryview(nd)\n self.assertEqual(mv, nd)\n self.assertRaises(TypeError, mv.__setitem__, 1, 8)\n\n # cannot be deleted\n nd = ndarray([1], shape=[1], flags=ND_WRITABLE)\n self.assertRaises(TypeError, nd.__delitem__, 1)\n mv = memoryview(nd)\n self.assertEqual(mv, nd)\n self.assertRaises(TypeError, mv.__delitem__, 1)\n\n # overflow\n nd = ndarray([1], shape=[1], flags=ND_WRITABLE)\n self.assertRaises(OverflowError, nd.__getitem__, 1<<64)\n self.assertRaises(OverflowError, nd.__setitem__, 1<<64, 8)\n mv = memoryview(nd)\n self.assertEqual(mv, nd)\n self.assertRaises(IndexError, mv.__getitem__, 1<<64)\n self.assertRaises(IndexError, mv.__setitem__, 1<<64, 8)\n\n # format\n items = [1,2,3,4,5,6,7,8]\n nd = ndarray(items, shape=[len(items)], format=\"B\", flags=ND_WRITABLE)\n self.assertRaises(struct.error, nd.__setitem__, 2, 300)\n self.assertRaises(ValueError, nd.__setitem__, 1, (100, 200))\n mv = memoryview(nd)\n self.assertEqual(mv, nd)\n self.assertRaises(ValueError, mv.__setitem__, 2, 300)\n self.assertRaises(TypeError, mv.__setitem__, 1, (100, 200))\n\n items = [(1,2), (3,4), (5,6)]\n nd = ndarray(items, shape=[len(items)], format=\"LQ\", flags=ND_WRITABLE)\n self.assertRaises(ValueError, nd.__setitem__, 2, 300)\n self.assertRaises(struct.error, nd.__setitem__, 1, (b'\\x001', 200))\n\n def test_ndarray_index_scalar(self):\n # scalar\n nd = ndarray(1, shape=(), flags=ND_WRITABLE)\n mv = memoryview(nd)\n self.assertEqual(mv, nd)\n\n x = nd[()]; self.assertEqual(x, 1)\n x = nd[...]; self.assertEqual(x.tolist(), nd.tolist())\n\n x = mv[()]; self.assertEqual(x, 1)\n x = mv[...]; self.assertEqual(x.tolist(), nd.tolist())\n\n self.assertRaises(TypeError, nd.__getitem__, 0)\n self.assertRaises(TypeError, mv.__getitem__, 0)\n self.assertRaises(TypeError, nd.__setitem__, 0, 8)\n self.assertRaises(TypeError, mv.__setitem__, 0, 8)\n\n self.assertEqual(nd.tolist(), 1)\n self.assertEqual(mv.tolist(), 1)\n\n nd[()] = 9; self.assertEqual(nd.tolist(), 9)\n mv[()] = 9; self.assertEqual(mv.tolist(), 9)\n\n nd[...] = 5; self.assertEqual(nd.tolist(), 5)\n mv[...] = 5; self.assertEqual(mv.tolist(), 5)\n\n def test_ndarray_index_null_strides(self):\n ex = ndarray(list(range(2*4)), shape=[2, 4], flags=ND_WRITABLE)\n nd = ndarray(ex, getbuf=PyBUF_CONTIG)\n\n # Sub-views are only possible for full exporters.\n self.assertRaises(BufferError, nd.__getitem__, 1)\n # Same for slices.\n self.assertRaises(BufferError, nd.__getitem__, slice(3,5,1))\n\n def test_ndarray_index_getitem_single(self):\n # getitem\n for fmt, items, _ in iter_format(5):\n nd = ndarray(items, shape=[5], format=fmt)\n for i in range(-5, 5):\n self.assertEqual(nd[i], items[i])\n\n self.assertRaises(IndexError, nd.__getitem__, -6)\n self.assertRaises(IndexError, nd.__getitem__, 5)\n\n if is_memoryview_format(fmt):\n mv = memoryview(nd)\n self.assertEqual(mv, nd)\n for i in range(-5, 5):\n self.assertEqual(mv[i], items[i])\n\n self.assertRaises(IndexError, mv.__getitem__, -6)\n self.assertRaises(IndexError, mv.__getitem__, 5)\n\n # getitem with null strides\n for fmt, items, _ in iter_format(5):\n ex = ndarray(items, shape=[5], flags=ND_WRITABLE, format=fmt)\n nd = ndarray(ex, getbuf=PyBUF_CONTIG|PyBUF_FORMAT)\n\n for i in range(-5, 5):\n self.assertEqual(nd[i], items[i])\n\n if is_memoryview_format(fmt):\n mv = nd.memoryview_from_buffer()\n self.assertIs(mv.__eq__(nd), NotImplemented)\n for i in range(-5, 5):\n self.assertEqual(mv[i], items[i])\n\n # getitem with null format\n items = [1,2,3,4,5]\n ex = ndarray(items, shape=[5])\n nd = ndarray(ex, getbuf=PyBUF_CONTIG_RO)\n for i in range(-5, 5):\n self.assertEqual(nd[i], items[i])\n\n # getitem with null shape/strides/format\n items = [1,2,3,4,5]\n ex = ndarray(items, shape=[5])\n nd = ndarray(ex, getbuf=PyBUF_SIMPLE)\n\n for i in range(-5, 5):\n self.assertEqual(nd[i], items[i])\n\n def test_ndarray_index_setitem_single(self):\n # assign single value\n for fmt, items, single_item in iter_format(5):\n nd = ndarray(items, shape=[5], format=fmt, flags=ND_WRITABLE)\n for i in range(5):\n items[i] = single_item\n nd[i] = single_item\n self.assertEqual(nd.tolist(), items)\n\n self.assertRaises(IndexError, nd.__setitem__, -6, single_item)\n self.assertRaises(IndexError, nd.__setitem__, 5, single_item)\n\n if not is_memoryview_format(fmt):\n continue\n\n nd = ndarray(items, shape=[5], format=fmt, flags=ND_WRITABLE)\n mv = memoryview(nd)\n self.assertEqual(mv, nd)\n for i in range(5):\n items[i] = single_item\n mv[i] = single_item\n self.assertEqual(mv.tolist(), items)\n\n self.assertRaises(IndexError, mv.__setitem__, -6, single_item)\n self.assertRaises(IndexError, mv.__setitem__, 5, single_item)\n\n\n # assign single value: lobject = robject\n for fmt, items, single_item in iter_format(5):\n nd = ndarray(items, shape=[5], format=fmt, flags=ND_WRITABLE)\n for i in range(-5, 4):\n items[i] = items[i+1]\n nd[i] = nd[i+1]\n self.assertEqual(nd.tolist(), items)\n\n if not is_memoryview_format(fmt):\n continue\n\n nd = ndarray(items, shape=[5], format=fmt, flags=ND_WRITABLE)\n mv = memoryview(nd)\n self.assertEqual(mv, nd)\n for i in range(-5, 4):\n items[i] = items[i+1]\n mv[i] = mv[i+1]\n self.assertEqual(mv.tolist(), items)\n\n def test_ndarray_index_getitem_multidim(self):\n shape_t = (2, 3, 5)\n nitems = prod(shape_t)\n for shape in permutations(shape_t):\n\n fmt, items, _ = randitems(nitems)\n\n for flags in (0, ND_PIL):\n # C array\n nd = ndarray(items, shape=shape, format=fmt, flags=flags)\n lst = carray(items, shape)\n\n for i in range(-shape[0], shape[0]):\n self.assertEqual(lst[i], nd[i].tolist())\n for j in range(-shape[1], shape[1]):\n self.assertEqual(lst[i][j], nd[i][j].tolist())\n for k in range(-shape[2], shape[2]):\n self.assertEqual(lst[i][j][k], nd[i][j][k])\n\n # Fortran array\n nd = ndarray(items, shape=shape, format=fmt,\n flags=flags|ND_FORTRAN)\n lst = farray(items, shape)\n\n for i in range(-shape[0], shape[0]):\n self.assertEqual(lst[i], nd[i].tolist())\n for j in range(-shape[1], shape[1]):\n self.assertEqual(lst[i][j], nd[i][j].tolist())\n for k in range(shape[2], shape[2]):\n self.assertEqual(lst[i][j][k], nd[i][j][k])\n\n def test_ndarray_sequence(self):\n nd = ndarray(1, shape=())\n self.assertRaises(TypeError, eval, \"1 in nd\", locals())\n mv = memoryview(nd)\n self.assertEqual(mv, nd)\n self.assertRaises(TypeError, eval, \"1 in mv\", locals())\n\n for fmt, items, _ in iter_format(5):\n nd = ndarray(items, shape=[5], format=fmt)\n for i, v in enumerate(nd):\n self.assertEqual(v, items[i])\n self.assertTrue(v in nd)\n\n if is_memoryview_format(fmt):\n mv = memoryview(nd)\n for i, v in enumerate(mv):\n self.assertEqual(v, items[i])\n self.assertTrue(v in mv)\n\n def test_ndarray_slice_invalid(self):\n items = [1,2,3,4,5,6,7,8]\n\n # rvalue is not an exporter\n xl = ndarray(items, shape=[8], flags=ND_WRITABLE)\n ml = memoryview(xl)\n self.assertRaises(TypeError, xl.__setitem__, slice(0,8,1), items)\n self.assertRaises(TypeError, ml.__setitem__, slice(0,8,1), items)\n\n # rvalue is not a full exporter\n xl = ndarray(items, shape=[8], flags=ND_WRITABLE)\n ex = ndarray(items, shape=[8], flags=ND_WRITABLE)\n xr = ndarray(ex, getbuf=PyBUF_ND)\n self.assertRaises(BufferError, xl.__setitem__, slice(0,8,1), xr)\n\n # zero step\n nd = ndarray(items, shape=[8], format=\"L\", flags=ND_WRITABLE)\n mv = memoryview(nd)\n self.assertRaises(ValueError, nd.__getitem__, slice(0,1,0))\n self.assertRaises(ValueError, mv.__getitem__, slice(0,1,0))\n\n nd = ndarray(items, shape=[2,4], format=\"L\", flags=ND_WRITABLE)\n mv = memoryview(nd)\n\n self.assertRaises(ValueError, nd.__getitem__,\n (slice(0,1,1), slice(0,1,0)))\n self.assertRaises(ValueError, nd.__getitem__,\n (slice(0,1,0), slice(0,1,1)))\n self.assertRaises(TypeError, nd.__getitem__, \"@%$\")\n self.assertRaises(TypeError, nd.__getitem__, (\"@%$\", slice(0,1,1)))\n self.assertRaises(TypeError, nd.__getitem__, (slice(0,1,1), {}))\n\n # memoryview: not implemented\n self.assertRaises(NotImplementedError, mv.__getitem__,\n (slice(0,1,1), slice(0,1,0)))\n self.assertRaises(TypeError, mv.__getitem__, \"@%$\")\n\n # differing format\n xl = ndarray(items, shape=[8], format=\"B\", flags=ND_WRITABLE)\n xr = ndarray(items, shape=[8], format=\"b\")\n ml = memoryview(xl)\n mr = memoryview(xr)\n self.assertRaises(ValueError, xl.__setitem__, slice(0,1,1), xr[7:8])\n self.assertEqual(xl.tolist(), items)\n self.assertRaises(ValueError, ml.__setitem__, slice(0,1,1), mr[7:8])\n self.assertEqual(ml.tolist(), items)\n\n # differing itemsize\n xl = ndarray(items, shape=[8], format=\"B\", flags=ND_WRITABLE)\n yr = ndarray(items, shape=[8], format=\"L\")\n ml = memoryview(xl)\n mr = memoryview(xr)\n self.assertRaises(ValueError, xl.__setitem__, slice(0,1,1), xr[7:8])\n self.assertEqual(xl.tolist(), items)\n self.assertRaises(ValueError, ml.__setitem__, slice(0,1,1), mr[7:8])\n self.assertEqual(ml.tolist(), items)\n\n # differing ndim\n xl = ndarray(items, shape=[2, 4], format=\"b\", flags=ND_WRITABLE)\n xr = ndarray(items, shape=[8], format=\"b\")\n ml = memoryview(xl)\n mr = memoryview(xr)\n self.assertRaises(ValueError, xl.__setitem__, slice(0,1,1), xr[7:8])\n self.assertEqual(xl.tolist(), [[1,2,3,4], [5,6,7,8]])\n self.assertRaises(NotImplementedError, ml.__setitem__, slice(0,1,1),\n mr[7:8])\n\n # differing shape\n xl = ndarray(items, shape=[8], format=\"b\", flags=ND_WRITABLE)\n xr = ndarray(items, shape=[8], format=\"b\")\n ml = memoryview(xl)\n mr = memoryview(xr)\n self.assertRaises(ValueError, xl.__setitem__, slice(0,2,1), xr[7:8])\n self.assertEqual(xl.tolist(), items)\n self.assertRaises(ValueError, ml.__setitem__, slice(0,2,1), mr[7:8])\n self.assertEqual(ml.tolist(), items)\n\n # _testbuffer.c module functions\n self.assertRaises(TypeError, slice_indices, slice(0,1,2), {})\n self.assertRaises(TypeError, slice_indices, \"###########\", 1)\n self.assertRaises(ValueError, slice_indices, slice(0,1,0), 4)\n\n x = ndarray(items, shape=[8], format=\"b\", flags=ND_PIL)\n self.assertRaises(TypeError, x.add_suboffsets)\n\n ex = ndarray(items, shape=[8], format=\"B\")\n x = ndarray(ex, getbuf=PyBUF_SIMPLE)\n self.assertRaises(TypeError, x.add_suboffsets)\n\n def test_ndarray_slice_zero_shape(self):\n items = [1,2,3,4,5,6,7,8,9,10,11,12]\n\n x = ndarray(items, shape=[12], format=\"L\", flags=ND_WRITABLE)\n y = ndarray(items, shape=[12], format=\"L\")\n x[4:4] = y[9:9]\n self.assertEqual(x.tolist(), items)\n\n ml = memoryview(x)\n mr = memoryview(y)\n self.assertEqual(ml, x)\n self.assertEqual(ml, y)\n ml[4:4] = mr[9:9]\n self.assertEqual(ml.tolist(), items)\n\n x = ndarray(items, shape=[3, 4], format=\"L\", flags=ND_WRITABLE)\n y = ndarray(items, shape=[4, 3], format=\"L\")\n x[1:2, 2:2] = y[1:2, 3:3]\n self.assertEqual(x.tolist(), carray(items, [3, 4]))\n\n def test_ndarray_slice_multidim(self):\n shape_t = (2, 3, 5)\n ndim = len(shape_t)\n nitems = prod(shape_t)\n for shape in permutations(shape_t):\n\n fmt, items, _ = randitems(nitems)\n itemsize = struct.calcsize(fmt)\n\n for flags in (0, ND_PIL):\n nd = ndarray(items, shape=shape, format=fmt, flags=flags)\n lst = carray(items, shape)\n\n for slices in rslices_ndim(ndim, shape):\n\n listerr = None\n try:\n sliced = multislice(lst, slices)\n except Exception as e:\n listerr = e.__class__\n\n nderr = None\n try:\n ndsliced = nd[slices]\n except Exception as e:\n nderr = e.__class__\n\n if nderr or listerr:\n self.assertIs(nderr, listerr)\n else:\n self.assertEqual(ndsliced.tolist(), sliced)\n\n def test_ndarray_slice_redundant_suboffsets(self):\n shape_t = (2, 3, 5, 2)\n ndim = len(shape_t)\n nitems = prod(shape_t)\n for shape in permutations(shape_t):\n\n fmt, items, _ = randitems(nitems)\n itemsize = struct.calcsize(fmt)\n\n nd = ndarray(items, shape=shape, format=fmt)\n nd.add_suboffsets()\n ex = ndarray(items, shape=shape, format=fmt)\n ex.add_suboffsets()\n mv = memoryview(ex)\n lst = carray(items, shape)\n\n for slices in rslices_ndim(ndim, shape):\n\n listerr = None\n try:\n sliced = multislice(lst, slices)\n except Exception as e:\n listerr = e.__class__\n\n nderr = None\n try:\n ndsliced = nd[slices]\n except Exception as e:\n nderr = e.__class__\n\n if nderr or listerr:\n self.assertIs(nderr, listerr)\n else:\n self.assertEqual(ndsliced.tolist(), sliced)\n\n def test_ndarray_slice_assign_single(self):\n for fmt, items, _ in iter_format(5):\n for lslice in genslices(5):\n for rslice in genslices(5):\n for flags in (0, ND_PIL):\n\n f = flags|ND_WRITABLE\n nd = ndarray(items, shape=[5], format=fmt, flags=f)\n ex = ndarray(items, shape=[5], format=fmt, flags=f)\n mv = memoryview(ex)\n\n lsterr = None\n diff_structure = None\n lst = items[:]\n try:\n lval = lst[lslice]\n rval = lst[rslice]\n lst[lslice] = lst[rslice]\n diff_structure = len(lval) != len(rval)\n except Exception as e:\n lsterr = e.__class__\n\n nderr = None\n try:\n nd[lslice] = nd[rslice]\n except Exception as e:\n nderr = e.__class__\n\n if diff_structure: # ndarray cannot change shape\n self.assertIs(nderr, ValueError)\n else:\n self.assertEqual(nd.tolist(), lst)\n self.assertIs(nderr, lsterr)\n\n if not is_memoryview_format(fmt):\n continue\n\n mverr = None\n try:\n mv[lslice] = mv[rslice]\n except Exception as e:\n mverr = e.__class__\n\n if diff_structure: # memoryview cannot change shape\n self.assertIs(mverr, ValueError)\n else:\n self.assertEqual(mv.tolist(), lst)\n self.assertEqual(mv, nd)\n self.assertIs(mverr, lsterr)\n self.verify(mv, obj=ex,\n itemsize=nd.itemsize, fmt=fmt, readonly=0,\n ndim=nd.ndim, shape=nd.shape, strides=nd.strides,\n lst=nd.tolist())\n\n def test_ndarray_slice_assign_multidim(self):\n shape_t = (2, 3, 5)\n ndim = len(shape_t)\n nitems = prod(shape_t)\n for shape in permutations(shape_t):\n\n fmt, items, _ = randitems(nitems)\n\n for flags in (0, ND_PIL):\n for _ in range(ITERATIONS):\n lslices, rslices = randslice_from_shape(ndim, shape)\n\n nd = ndarray(items, shape=shape, format=fmt,\n flags=flags|ND_WRITABLE)\n lst = carray(items, shape)\n\n listerr = None\n try:\n result = multislice_assign(lst, lst, lslices, rslices)\n except Exception as e:\n listerr = e.__class__\n\n nderr = None\n try:\n nd[lslices] = nd[rslices]\n except Exception as e:\n nderr = e.__class__\n\n if nderr or listerr:\n self.assertIs(nderr, listerr)\n else:\n self.assertEqual(nd.tolist(), result)\n\n def test_ndarray_random(self):\n # construction of valid arrays\n for _ in range(ITERATIONS):\n for fmt in fmtdict['@']:\n itemsize = struct.calcsize(fmt)\n\n t = rand_structure(itemsize, True, maxdim=MAXDIM,\n maxshape=MAXSHAPE)\n self.assertTrue(verify_structure(*t))\n items = randitems_from_structure(fmt, t)\n\n x = ndarray_from_structure(items, fmt, t)\n xlist = x.tolist()\n\n mv = memoryview(x)\n if is_memoryview_format(fmt):\n mvlist = mv.tolist()\n self.assertEqual(mvlist, xlist)\n\n if t[2] > 0:\n # ndim > 0: test against suboffsets representation.\n y = ndarray_from_structure(items, fmt, t, flags=ND_PIL)\n ylist = y.tolist()\n self.assertEqual(xlist, ylist)\n\n mv = memoryview(y)\n if is_memoryview_format(fmt):\n self.assertEqual(mv, y)\n mvlist = mv.tolist()\n self.assertEqual(mvlist, ylist)\n\n if numpy_array:\n shape = t[3]\n if 0 in shape:\n continue # http://projects.scipy.org/numpy/ticket/1910\n z = numpy_array_from_structure(items, fmt, t)\n self.verify(x, obj=None,\n itemsize=z.itemsize, fmt=fmt, readonly=0,\n ndim=z.ndim, shape=z.shape, strides=z.strides,\n lst=z.tolist())\n\n def test_ndarray_random_invalid(self):\n # exceptions during construction of invalid arrays\n for _ in range(ITERATIONS):\n for fmt in fmtdict['@']:\n itemsize = struct.calcsize(fmt)\n\n t = rand_structure(itemsize, False, maxdim=MAXDIM,\n maxshape=MAXSHAPE)\n self.assertFalse(verify_structure(*t))\n items = randitems_from_structure(fmt, t)\n\n nderr = False\n try:\n x = ndarray_from_structure(items, fmt, t)\n except Exception as e:\n nderr = e.__class__\n self.assertTrue(nderr)\n\n if numpy_array:\n numpy_err = False\n try:\n y = numpy_array_from_structure(items, fmt, t)\n except Exception as e:\n numpy_err = e.__class__\n\n if 0: # http://projects.scipy.org/numpy/ticket/1910\n self.assertTrue(numpy_err)\n\n def test_ndarray_random_slice_assign(self):\n # valid slice assignments\n for _ in range(ITERATIONS):\n for fmt in fmtdict['@']:\n itemsize = struct.calcsize(fmt)\n\n lshape, rshape, lslices, rslices = \\\n rand_aligned_slices(maxdim=MAXDIM, maxshape=MAXSHAPE)\n tl = rand_structure(itemsize, True, shape=lshape)\n tr = rand_structure(itemsize, True, shape=rshape)\n self.assertTrue(verify_structure(*tl))\n self.assertTrue(verify_structure(*tr))\n litems = randitems_from_structure(fmt, tl)\n ritems = randitems_from_structure(fmt, tr)\n\n xl = ndarray_from_structure(litems, fmt, tl)\n xr = ndarray_from_structure(ritems, fmt, tr)\n xl[lslices] = xr[rslices]\n xllist = xl.tolist()\n xrlist = xr.tolist()\n\n ml = memoryview(xl)\n mr = memoryview(xr)\n self.assertEqual(ml.tolist(), xllist)\n self.assertEqual(mr.tolist(), xrlist)\n\n if tl[2] > 0 and tr[2] > 0:\n # ndim > 0: test against suboffsets representation.\n yl = ndarray_from_structure(litems, fmt, tl, flags=ND_PIL)\n yr = ndarray_from_structure(ritems, fmt, tr, flags=ND_PIL)\n yl[lslices] = yr[rslices]\n yllist = yl.tolist()\n yrlist = yr.tolist()\n self.assertEqual(xllist, yllist)\n self.assertEqual(xrlist, yrlist)\n\n ml = memoryview(yl)\n mr = memoryview(yr)\n self.assertEqual(ml.tolist(), yllist)\n self.assertEqual(mr.tolist(), yrlist)\n\n if numpy_array:\n if 0 in lshape or 0 in rshape:\n continue # http://projects.scipy.org/numpy/ticket/1910\n\n zl = numpy_array_from_structure(litems, fmt, tl)\n zr = numpy_array_from_structure(ritems, fmt, tr)\n zl[lslices] = zr[rslices]\n\n if not is_overlapping(tl) and not is_overlapping(tr):\n # Slice assignment of overlapping structures\n # is undefined in NumPy.\n self.verify(xl, obj=None,\n itemsize=zl.itemsize, fmt=fmt, readonly=0,\n ndim=zl.ndim, shape=zl.shape,\n strides=zl.strides, lst=zl.tolist())\n\n self.verify(xr, obj=None,\n itemsize=zr.itemsize, fmt=fmt, readonly=0,\n ndim=zr.ndim, shape=zr.shape,\n strides=zr.strides, lst=zr.tolist())\n\n def test_ndarray_re_export(self):\n items = [1,2,3,4,5,6,7,8,9,10,11,12]\n\n nd = ndarray(items, shape=[3,4], flags=ND_PIL)\n ex = ndarray(nd)\n\n self.assertTrue(ex.flags & ND_PIL)\n self.assertIs(ex.obj, nd)\n self.assertEqual(ex.suboffsets, (0, -1))\n self.assertFalse(ex.c_contiguous)\n self.assertFalse(ex.f_contiguous)\n self.assertFalse(ex.contiguous)\n\n def test_ndarray_zero_shape(self):\n # zeros in shape\n for flags in (0, ND_PIL):\n nd = ndarray([1,2,3], shape=[0], flags=flags)\n mv = memoryview(nd)\n self.assertEqual(mv, nd)\n self.assertEqual(nd.tolist(), [])\n self.assertEqual(mv.tolist(), [])\n\n nd = ndarray([1,2,3], shape=[0,3,3], flags=flags)\n self.assertEqual(nd.tolist(), [])\n\n nd = ndarray([1,2,3], shape=[3,0,3], flags=flags)\n self.assertEqual(nd.tolist(), [[], [], []])\n\n nd = ndarray([1,2,3], shape=[3,3,0], flags=flags)\n self.assertEqual(nd.tolist(),\n [[[], [], []], [[], [], []], [[], [], []]])\n\n def test_ndarray_zero_strides(self):\n # zero strides\n for flags in (0, ND_PIL):\n nd = ndarray([1], shape=[5], strides=[0], flags=flags)\n mv = memoryview(nd)\n self.assertEqual(mv, nd)\n self.assertEqual(nd.tolist(), [1, 1, 1, 1, 1])\n self.assertEqual(mv.tolist(), [1, 1, 1, 1, 1])\n\n def test_ndarray_offset(self):\n nd = ndarray(list(range(20)), shape=[3], offset=7)\n self.assertEqual(nd.offset, 7)\n self.assertEqual(nd.tolist(), [7,8,9])\n\n def test_ndarray_memoryview_from_buffer(self):\n for flags in (0, ND_PIL):\n nd = ndarray(list(range(3)), shape=[3], flags=flags)\n m = nd.memoryview_from_buffer()\n self.assertEqual(m, nd)\n\n def test_ndarray_get_pointer(self):\n for flags in (0, ND_PIL):\n nd = ndarray(list(range(3)), shape=[3], flags=flags)\n for i in range(3):\n self.assertEqual(nd[i], get_pointer(nd, [i]))\n\n def test_ndarray_tolist_null_strides(self):\n ex = ndarray(list(range(20)), shape=[2,2,5])\n\n nd = ndarray(ex, getbuf=PyBUF_ND|PyBUF_FORMAT)\n self.assertEqual(nd.tolist(), ex.tolist())\n\n m = memoryview(ex)\n self.assertEqual(m.tolist(), ex.tolist())\n\n def test_ndarray_cmp_contig(self):\n\n self.assertFalse(cmp_contig(b\"123\", b\"456\"))\n\n x = ndarray(list(range(12)), shape=[3,4])\n y = ndarray(list(range(12)), shape=[4,3])\n self.assertFalse(cmp_contig(x, y))\n\n x = ndarray([1], shape=[1], format=\"B\")\n self.assertTrue(cmp_contig(x, b'\\x01'))\n self.assertTrue(cmp_contig(b'\\x01', x))\n\n def test_ndarray_hash(self):\n\n a = array.array('L', [1,2,3])\n nd = ndarray(a)\n self.assertRaises(ValueError, hash, nd)\n\n # one-dimensional\n b = bytes(list(range(12)))\n\n nd = ndarray(list(range(12)), shape=[12])\n self.assertEqual(hash(nd), hash(b))\n\n # C-contiguous\n nd = ndarray(list(range(12)), shape=[3,4])\n self.assertEqual(hash(nd), hash(b))\n\n nd = ndarray(list(range(12)), shape=[3,2,2])\n self.assertEqual(hash(nd), hash(b))\n\n # Fortran contiguous\n b = bytes(transpose(list(range(12)), shape=[4,3]))\n nd = ndarray(list(range(12)), shape=[3,4], flags=ND_FORTRAN)\n self.assertEqual(hash(nd), hash(b))\n\n b = bytes(transpose(list(range(12)), shape=[2,3,2]))\n nd = ndarray(list(range(12)), shape=[2,3,2], flags=ND_FORTRAN)\n self.assertEqual(hash(nd), hash(b))\n\n # suboffsets\n b = bytes(list(range(12)))\n nd = ndarray(list(range(12)), shape=[2,2,3], flags=ND_PIL)\n self.assertEqual(hash(nd), hash(b))\n\n # non-byte formats\n nd = ndarray(list(range(12)), shape=[2,2,3], format='L')\n self.assertEqual(hash(nd), hash(nd.tobytes()))\n\n def test_py_buffer_to_contiguous(self):\n\n # The requests are used in _testbuffer.c:py_buffer_to_contiguous\n # to generate buffers without full information for testing.\n requests = (\n # distinct flags\n PyBUF_INDIRECT, PyBUF_STRIDES, PyBUF_ND, PyBUF_SIMPLE,\n # compound requests\n PyBUF_FULL, PyBUF_FULL_RO,\n PyBUF_RECORDS, PyBUF_RECORDS_RO,\n PyBUF_STRIDED, PyBUF_STRIDED_RO,\n PyBUF_CONTIG, PyBUF_CONTIG_RO,\n )\n\n # no buffer interface\n self.assertRaises(TypeError, py_buffer_to_contiguous, {}, 'F',\n PyBUF_FULL_RO)\n\n # scalar, read-only request\n nd = ndarray(9, shape=(), format=\"L\", flags=ND_WRITABLE)\n for order in ['C', 'F', 'A']:\n for request in requests:\n b = py_buffer_to_contiguous(nd, order, request)\n self.assertEqual(b, nd.tobytes())\n\n # zeros in shape\n nd = ndarray([1], shape=[0], format=\"L\", flags=ND_WRITABLE)\n for order in ['C', 'F', 'A']:\n for request in requests:\n b = py_buffer_to_contiguous(nd, order, request)\n self.assertEqual(b, b'')\n\n nd = ndarray(list(range(8)), shape=[2, 0, 7], format=\"L\",\n flags=ND_WRITABLE)\n for order in ['C', 'F', 'A']:\n for request in requests:\n b = py_buffer_to_contiguous(nd, order, request)\n self.assertEqual(b, b'')\n\n ### One-dimensional arrays are trivial, since Fortran and C order\n ### are the same.\n\n # one-dimensional\n for f in [0, ND_FORTRAN]:\n nd = ndarray([1], shape=[1], format=\"h\", flags=f|ND_WRITABLE)\n ndbytes = nd.tobytes()\n for order in ['C', 'F', 'A']:\n for request in requests:\n b = py_buffer_to_contiguous(nd, order, request)\n self.assertEqual(b, ndbytes)\n\n nd = ndarray([1, 2, 3], shape=[3], format=\"b\", flags=f|ND_WRITABLE)\n ndbytes = nd.tobytes()\n for order in ['C', 'F', 'A']:\n for request in requests:\n b = py_buffer_to_contiguous(nd, order, request)\n self.assertEqual(b, ndbytes)\n\n # one-dimensional, non-contiguous input\n nd = ndarray([1, 2, 3], shape=[2], strides=[2], flags=ND_WRITABLE)\n ndbytes = nd.tobytes()\n for order in ['C', 'F', 'A']:\n for request in [PyBUF_STRIDES, PyBUF_FULL]:\n b = py_buffer_to_contiguous(nd, order, request)\n self.assertEqual(b, ndbytes)\n\n nd = nd[::-1]\n ndbytes = nd.tobytes()\n for order in ['C', 'F', 'A']:\n for request in requests:\n try:\n b = py_buffer_to_contiguous(nd, order, request)\n except BufferError:\n continue\n self.assertEqual(b, ndbytes)\n\n ###\n ### Multi-dimensional arrays:\n ###\n ### The goal here is to preserve the logical representation of the\n ### input array but change the physical representation if necessary.\n ###\n ### _testbuffer example:\n ### ====================\n ###\n ### C input array:\n ### --------------\n ### >>> nd = ndarray(list(range(12)), shape=[3, 4])\n ### >>> nd.tolist()\n ### [[0, 1, 2, 3],\n ### [4, 5, 6, 7],\n ### [8, 9, 10, 11]]\n ###\n ### Fortran output:\n ### ---------------\n ### >>> py_buffer_to_contiguous(nd, 'F', PyBUF_FULL_RO)\n ### >>> b'\\x00\\x04\\x08\\x01\\x05\\t\\x02\\x06\\n\\x03\\x07\\x0b'\n ###\n ### The return value corresponds to this input list for\n ### _testbuffer's ndarray:\n ### >>> nd = ndarray([0,4,8,1,5,9,2,6,10,3,7,11], shape=[3,4],\n ### flags=ND_FORTRAN)\n ### >>> nd.tolist()\n ### [[0, 1, 2, 3],\n ### [4, 5, 6, 7],\n ### [8, 9, 10, 11]]\n ###\n ### The logical array is the same, but the values in memory are now\n ### in Fortran order.\n ###\n ### NumPy example:\n ### ==============\n ### _testbuffer's ndarray takes lists to initialize the memory.\n ### Here's the same sequence in NumPy:\n ###\n ### C input:\n ### --------\n ### >>> nd = ndarray(buffer=bytearray(list(range(12))),\n ### shape=[3, 4], dtype='B')\n ### >>> nd\n ### array([[ 0, 1, 2, 3],\n ### [ 4, 5, 6, 7],\n ### [ 8, 9, 10, 11]], dtype=uint8)\n ###\n ### Fortran output:\n ### ---------------\n ### >>> fortran_buf = nd.tostring(order='F')\n ### >>> fortran_buf\n ### b'\\x00\\x04\\x08\\x01\\x05\\t\\x02\\x06\\n\\x03\\x07\\x0b'\n ###\n ### >>> nd = ndarray(buffer=fortran_buf, shape=[3, 4],\n ### dtype='B', order='F')\n ###\n ### >>> nd\n ### array([[ 0, 1, 2, 3],\n ### [ 4, 5, 6, 7],\n ### [ 8, 9, 10, 11]], dtype=uint8)\n ###\n\n # multi-dimensional, contiguous input\n lst = list(range(12))\n for f in [0, ND_FORTRAN]:\n nd = ndarray(lst, shape=[3, 4], flags=f|ND_WRITABLE)\n if numpy_array:\n na = numpy_array(buffer=bytearray(lst),\n shape=[3, 4], dtype='B',\n order='C' if f == 0 else 'F')\n\n # 'C' request\n if f == ND_FORTRAN: # 'F' to 'C'\n x = ndarray(transpose(lst, [4, 3]), shape=[3, 4],\n flags=ND_WRITABLE)\n expected = x.tobytes()\n else:\n expected = nd.tobytes()\n for request in requests:\n try:\n b = py_buffer_to_contiguous(nd, 'C', request)\n except BufferError:\n continue\n\n self.assertEqual(b, expected)\n\n # Check that output can be used as the basis for constructing\n # a C array that is logically identical to the input array.\n y = ndarray([v for v in b], shape=[3, 4], flags=ND_WRITABLE)\n self.assertEqual(memoryview(y), memoryview(nd))\n\n if numpy_array:\n self.assertEqual(b, na.tostring(order='C'))\n\n # 'F' request\n if f == 0: # 'C' to 'F'\n x = ndarray(transpose(lst, [3, 4]), shape=[4, 3],\n flags=ND_WRITABLE)\n else:\n x = ndarray(lst, shape=[3, 4], flags=ND_WRITABLE)\n expected = x.tobytes()\n for request in [PyBUF_FULL, PyBUF_FULL_RO, PyBUF_INDIRECT,\n PyBUF_STRIDES, PyBUF_ND]:\n try:\n b = py_buffer_to_contiguous(nd, 'F', request)\n except BufferError:\n continue\n self.assertEqual(b, expected)\n\n # Check that output can be used as the basis for constructing\n # a Fortran array that is logically identical to the input array.\n y = ndarray([v for v in b], shape=[3, 4], flags=ND_FORTRAN|ND_WRITABLE)\n self.assertEqual(memoryview(y), memoryview(nd))\n\n if numpy_array:\n self.assertEqual(b, na.tostring(order='F'))\n\n # 'A' request\n if f == ND_FORTRAN:\n x = ndarray(lst, shape=[3, 4], flags=ND_WRITABLE)\n expected = x.tobytes()\n else:\n expected = nd.tobytes()\n for request in [PyBUF_FULL, PyBUF_FULL_RO, PyBUF_INDIRECT,\n PyBUF_STRIDES, PyBUF_ND]:\n try:\n b = py_buffer_to_contiguous(nd, 'A', request)\n except BufferError:\n continue\n\n self.assertEqual(b, expected)\n\n # Check that output can be used as the basis for constructing\n # an array with order=f that is logically identical to the input\n # array.\n y = ndarray([v for v in b], shape=[3, 4], flags=f|ND_WRITABLE)\n self.assertEqual(memoryview(y), memoryview(nd))\n\n if numpy_array:\n self.assertEqual(b, na.tostring(order='A'))\n\n # multi-dimensional, non-contiguous input\n nd = ndarray(list(range(12)), shape=[3, 4], flags=ND_WRITABLE|ND_PIL)\n\n # 'C'\n b = py_buffer_to_contiguous(nd, 'C', PyBUF_FULL_RO)\n self.assertEqual(b, nd.tobytes())\n y = ndarray([v for v in b], shape=[3, 4], flags=ND_WRITABLE)\n self.assertEqual(memoryview(y), memoryview(nd))\n\n # 'F'\n b = py_buffer_to_contiguous(nd, 'F', PyBUF_FULL_RO)\n x = ndarray(transpose(lst, [3, 4]), shape=[4, 3], flags=ND_WRITABLE)\n self.assertEqual(b, x.tobytes())\n y = ndarray([v for v in b], shape=[3, 4], flags=ND_FORTRAN|ND_WRITABLE)\n self.assertEqual(memoryview(y), memoryview(nd))\n\n # 'A'\n b = py_buffer_to_contiguous(nd, 'A', PyBUF_FULL_RO)\n self.assertEqual(b, nd.tobytes())\n y = ndarray([v for v in b], shape=[3, 4], flags=ND_WRITABLE)\n self.assertEqual(memoryview(y), memoryview(nd))\n\n def test_memoryview_construction(self):\n\n items_shape = [(9, []), ([1,2,3], [3]), (list(range(2*3*5)), [2,3,5])]\n\n # NumPy style, C-contiguous:\n for items, shape in items_shape:\n\n # From PEP-3118 compliant exporter:\n ex = ndarray(items, shape=shape)\n m = memoryview(ex)\n self.assertTrue(m.c_contiguous)\n self.assertTrue(m.contiguous)\n\n ndim = len(shape)\n strides = strides_from_shape(ndim, shape, 1, 'C')\n lst = carray(items, shape)\n\n self.verify(m, obj=ex,\n itemsize=1, fmt='B', readonly=1,\n ndim=ndim, shape=shape, strides=strides,\n lst=lst)\n\n # From memoryview:\n m2 = memoryview(m)\n self.verify(m2, obj=ex,\n itemsize=1, fmt='B', readonly=1,\n ndim=ndim, shape=shape, strides=strides,\n lst=lst)\n\n # PyMemoryView_FromBuffer(): no strides\n nd = ndarray(ex, getbuf=PyBUF_CONTIG_RO|PyBUF_FORMAT)\n self.assertEqual(nd.strides, ())\n m = nd.memoryview_from_buffer()\n self.verify(m, obj=None,\n itemsize=1, fmt='B', readonly=1,\n ndim=ndim, shape=shape, strides=strides,\n lst=lst)\n\n # PyMemoryView_FromBuffer(): no format, shape, strides\n nd = ndarray(ex, getbuf=PyBUF_SIMPLE)\n self.assertEqual(nd.format, '')\n self.assertEqual(nd.shape, ())\n self.assertEqual(nd.strides, ())\n m = nd.memoryview_from_buffer()\n\n lst = [items] if ndim == 0 else items\n self.verify(m, obj=None,\n itemsize=1, fmt='B', readonly=1,\n ndim=1, shape=[ex.nbytes], strides=(1,),\n lst=lst)\n\n # NumPy style, Fortran contiguous:\n for items, shape in items_shape:\n\n # From PEP-3118 compliant exporter:\n ex = ndarray(items, shape=shape, flags=ND_FORTRAN)\n m = memoryview(ex)\n self.assertTrue(m.f_contiguous)\n self.assertTrue(m.contiguous)\n\n ndim = len(shape)\n strides = strides_from_shape(ndim, shape, 1, 'F')\n lst = farray(items, shape)\n\n self.verify(m, obj=ex,\n itemsize=1, fmt='B', readonly=1,\n ndim=ndim, shape=shape, strides=strides,\n lst=lst)\n\n # From memoryview:\n m2 = memoryview(m)\n self.verify(m2, obj=ex,\n itemsize=1, fmt='B', readonly=1,\n ndim=ndim, shape=shape, strides=strides,\n lst=lst)\n\n # PIL style:\n for items, shape in items_shape[1:]:\n\n # From PEP-3118 compliant exporter:\n ex = ndarray(items, shape=shape, flags=ND_PIL)\n m = memoryview(ex)\n\n ndim = len(shape)\n lst = carray(items, shape)\n\n self.verify(m, obj=ex,\n itemsize=1, fmt='B', readonly=1,\n ndim=ndim, shape=shape, strides=ex.strides,\n lst=lst)\n\n # From memoryview:\n m2 = memoryview(m)\n self.verify(m2, obj=ex,\n itemsize=1, fmt='B', readonly=1,\n ndim=ndim, shape=shape, strides=ex.strides,\n lst=lst)\n\n # Invalid number of arguments:\n self.assertRaises(TypeError, memoryview, b'9', 'x')\n # Not a buffer provider:\n self.assertRaises(TypeError, memoryview, {})\n # Non-compliant buffer provider:\n ex = ndarray([1,2,3], shape=[3])\n nd = ndarray(ex, getbuf=PyBUF_SIMPLE)\n self.assertRaises(BufferError, memoryview, nd)\n nd = ndarray(ex, getbuf=PyBUF_CONTIG_RO|PyBUF_FORMAT)\n self.assertRaises(BufferError, memoryview, nd)\n\n # ndim > 64\n nd = ndarray([1]*128, shape=[1]*128, format='L')\n self.assertRaises(ValueError, memoryview, nd)\n self.assertRaises(ValueError, nd.memoryview_from_buffer)\n self.assertRaises(ValueError, get_contiguous, nd, PyBUF_READ, 'C')\n self.assertRaises(ValueError, get_contiguous, nd, PyBUF_READ, 'F')\n self.assertRaises(ValueError, get_contiguous, nd[::-1], PyBUF_READ, 'C')\n\n def test_memoryview_cast_zero_shape(self):\n # Casts are undefined if buffer is multidimensional and shape\n # contains zeros. These arrays are regarded as C-contiguous by\n # Numpy and PyBuffer_GetContiguous(), so they are not caught by\n # the test for C-contiguity in memory_cast().\n items = [1,2,3]\n for shape in ([0,3,3], [3,0,3], [0,3,3]):\n ex = ndarray(items, shape=shape)\n self.assertTrue(ex.c_contiguous)\n msrc = memoryview(ex)\n self.assertRaises(TypeError, msrc.cast, 'c')\n # Monodimensional empty view can be cast (issue #19014).\n for fmt, _, _ in iter_format(1, 'memoryview'):\n msrc = memoryview(b'')\n m = msrc.cast(fmt)\n self.assertEqual(m.tobytes(), b'')\n self.assertEqual(m.tolist(), [])\n\n check_sizeof = support.check_sizeof\n\n def test_memoryview_sizeof(self):\n check = self.check_sizeof\n vsize = support.calcvobjsize\n base_struct = 'Pnin 2P2n2i5P P'\n per_dim = '3n'\n\n items = list(range(8))\n check(memoryview(b''), vsize(base_struct + 1 * per_dim))\n a = ndarray(items, shape=[2, 4], format=\"b\")\n check(memoryview(a), vsize(base_struct + 2 * per_dim))\n a = ndarray(items, shape=[2, 2, 2], format=\"b\")\n check(memoryview(a), vsize(base_struct + 3 * per_dim))\n\n def test_memoryview_struct_module(self):\n\n class INT(object):\n def __init__(self, val):\n self.val = val\n def __int__(self):\n return self.val\n\n class IDX(object):\n def __init__(self, val):\n self.val = val\n def __index__(self):\n return self.val\n\n def f(): return 7\n\n values = [INT(9), IDX(9),\n 2.2+3j, Decimal(\"-21.1\"), 12.2, Fraction(5, 2),\n [1,2,3], {4,5,6}, {7:8}, (), (9,),\n True, False, None, NotImplemented,\n b'a', b'abc', bytearray(b'a'), bytearray(b'abc'),\n 'a', 'abc', r'a', r'abc',\n f, lambda x: x]\n\n for fmt, items, item in iter_format(10, 'memoryview'):\n ex = ndarray(items, shape=[10], format=fmt, flags=ND_WRITABLE)\n nd = ndarray(items, shape=[10], format=fmt, flags=ND_WRITABLE)\n m = memoryview(ex)\n\n struct.pack_into(fmt, nd, 0, item)\n m[0] = item\n self.assertEqual(m[0], nd[0])\n\n itemsize = struct.calcsize(fmt)\n if 'P' in fmt:\n continue\n\n for v in values:\n struct_err = None\n try:\n struct.pack_into(fmt, nd, itemsize, v)\n except struct.error:\n struct_err = struct.error\n\n mv_err = None\n try:\n m[1] = v\n except (TypeError, ValueError) as e:\n mv_err = e.__class__\n\n if struct_err or mv_err:\n self.assertIsNot(struct_err, None)\n self.assertIsNot(mv_err, None)\n else:\n self.assertEqual(m[1], nd[1])\n\n def test_memoryview_cast_zero_strides(self):\n # Casts are undefined if strides contains zeros. These arrays are\n # (sometimes!) regarded as C-contiguous by Numpy, but not by\n # PyBuffer_GetContiguous().\n ex = ndarray([1,2,3], shape=[3], strides=[0])\n self.assertFalse(ex.c_contiguous)\n msrc = memoryview(ex)\n self.assertRaises(TypeError, msrc.cast, 'c')\n\n def test_memoryview_cast_invalid(self):\n # invalid format\n for sfmt in NON_BYTE_FORMAT:\n sformat = '@' + sfmt if randrange(2) else sfmt\n ssize = struct.calcsize(sformat)\n for dfmt in NON_BYTE_FORMAT:\n dformat = '@' + dfmt if randrange(2) else dfmt\n dsize = struct.calcsize(dformat)\n ex = ndarray(list(range(32)), shape=[32//ssize], format=sformat)\n msrc = memoryview(ex)\n self.assertRaises(TypeError, msrc.cast, dfmt, [32//dsize])\n\n for sfmt, sitems, _ in iter_format(1):\n ex = ndarray(sitems, shape=[1], format=sfmt)\n msrc = memoryview(ex)\n for dfmt, _, _ in iter_format(1):\n if not is_memoryview_format(dfmt):\n self.assertRaises(ValueError, msrc.cast, dfmt,\n [32//dsize])\n else:\n if not is_byte_format(sfmt) and not is_byte_format(dfmt):\n self.assertRaises(TypeError, msrc.cast, dfmt,\n [32//dsize])\n\n # invalid shape\n size_h = struct.calcsize('h')\n size_d = struct.calcsize('d')\n ex = ndarray(list(range(2*2*size_d)), shape=[2,2,size_d], format='h')\n msrc = memoryview(ex)\n self.assertRaises(TypeError, msrc.cast, shape=[2,2,size_h], format='d')\n\n ex = ndarray(list(range(120)), shape=[1,2,3,4,5])\n m = memoryview(ex)\n\n # incorrect number of args\n self.assertRaises(TypeError, m.cast)\n self.assertRaises(TypeError, m.cast, 1, 2, 3)\n\n # incorrect dest format type\n self.assertRaises(TypeError, m.cast, {})\n\n # incorrect dest format\n self.assertRaises(ValueError, m.cast, \"X\")\n self.assertRaises(ValueError, m.cast, \"@X\")\n self.assertRaises(ValueError, m.cast, \"@XY\")\n\n # dest format not implemented\n self.assertRaises(ValueError, m.cast, \"=B\")\n self.assertRaises(ValueError, m.cast, \"!L\")\n self.assertRaises(ValueError, m.cast, \"<P\")\n self.assertRaises(ValueError, m.cast, \">l\")\n self.assertRaises(ValueError, m.cast, \"BI\")\n self.assertRaises(ValueError, m.cast, \"xBI\")\n\n # src format not implemented\n ex = ndarray([(1,2), (3,4)], shape=[2], format=\"II\")\n m = memoryview(ex)\n self.assertRaises(NotImplementedError, m.__getitem__, 0)\n self.assertRaises(NotImplementedError, m.__setitem__, 0, 8)\n self.assertRaises(NotImplementedError, m.tolist)\n\n # incorrect shape type\n ex = ndarray(list(range(120)), shape=[1,2,3,4,5])\n m = memoryview(ex)\n self.assertRaises(TypeError, m.cast, \"B\", shape={})\n\n # incorrect shape elements\n ex = ndarray(list(range(120)), shape=[2*3*4*5])\n m = memoryview(ex)\n self.assertRaises(OverflowError, m.cast, \"B\", shape=[2**64])\n self.assertRaises(ValueError, m.cast, \"B\", shape=[-1])\n self.assertRaises(ValueError, m.cast, \"B\", shape=[2,3,4,5,6,7,-1])\n self.assertRaises(ValueError, m.cast, \"B\", shape=[2,3,4,5,6,7,0])\n self.assertRaises(TypeError, m.cast, \"B\", shape=[2,3,4,5,6,7,'x'])\n\n # N-D -> N-D cast\n ex = ndarray(list([9 for _ in range(3*5*7*11)]), shape=[3,5,7,11])\n m = memoryview(ex)\n self.assertRaises(TypeError, m.cast, \"I\", shape=[2,3,4,5])\n\n # cast with ndim > 64\n nd = ndarray(list(range(128)), shape=[128], format='I')\n m = memoryview(nd)\n self.assertRaises(ValueError, m.cast, 'I', [1]*128)\n\n # view->len not a multiple of itemsize\n ex = ndarray(list([9 for _ in range(3*5*7*11)]), shape=[3*5*7*11])\n m = memoryview(ex)\n self.assertRaises(TypeError, m.cast, \"I\", shape=[2,3,4,5])\n\n # product(shape) * itemsize != buffer size\n ex = ndarray(list([9 for _ in range(3*5*7*11)]), shape=[3*5*7*11])\n m = memoryview(ex)\n self.assertRaises(TypeError, m.cast, \"B\", shape=[2,3,4,5])\n\n # product(shape) * itemsize overflow\n nd = ndarray(list(range(128)), shape=[128], format='I')\n m1 = memoryview(nd)\n nd = ndarray(list(range(128)), shape=[128], format='B')\n m2 = memoryview(nd)\n if sys.maxsize == 2**63-1:\n self.assertRaises(TypeError, m1.cast, 'B',\n [7, 7, 73, 127, 337, 92737, 649657])\n self.assertRaises(ValueError, m1.cast, 'B',\n [2**20, 2**20, 2**10, 2**10, 2**3])\n self.assertRaises(ValueError, m2.cast, 'I',\n [2**20, 2**20, 2**10, 2**10, 2**1])\n else:\n self.assertRaises(TypeError, m1.cast, 'B',\n [1, 2147483647])\n self.assertRaises(ValueError, m1.cast, 'B',\n [2**10, 2**10, 2**5, 2**5, 2**1])\n self.assertRaises(ValueError, m2.cast, 'I',\n [2**10, 2**10, 2**5, 2**3, 2**1])\n\n def test_memoryview_cast(self):\n bytespec = (\n ('B', lambda ex: list(ex.tobytes())),\n ('b', lambda ex: [x-256 if x > 127 else x for x in list(ex.tobytes())]),\n ('c', lambda ex: [bytes(chr(x), 'latin-1') for x in list(ex.tobytes())]),\n )\n\n def iter_roundtrip(ex, m, items, fmt):\n srcsize = struct.calcsize(fmt)\n for bytefmt, to_bytelist in bytespec:\n\n m2 = m.cast(bytefmt)\n lst = to_bytelist(ex)\n self.verify(m2, obj=ex,\n itemsize=1, fmt=bytefmt, readonly=0,\n ndim=1, shape=[31*srcsize], strides=(1,),\n lst=lst, cast=True)\n\n m3 = m2.cast(fmt)\n self.assertEqual(m3, ex)\n lst = ex.tolist()\n self.verify(m3, obj=ex,\n itemsize=srcsize, fmt=fmt, readonly=0,\n ndim=1, shape=[31], strides=(srcsize,),\n lst=lst, cast=True)\n\n # cast from ndim = 0 to ndim = 1\n srcsize = struct.calcsize('I')\n ex = ndarray(9, shape=[], format='I')\n destitems, destshape = cast_items(ex, 'B', 1)\n m = memoryview(ex)\n m2 = m.cast('B')\n self.verify(m2, obj=ex,\n itemsize=1, fmt='B', readonly=1,\n ndim=1, shape=destshape, strides=(1,),\n lst=destitems, cast=True)\n\n # cast from ndim = 1 to ndim = 0\n destsize = struct.calcsize('I')\n ex = ndarray([9]*destsize, shape=[destsize], format='B')\n destitems, destshape = cast_items(ex, 'I', destsize, shape=[])\n m = memoryview(ex)\n m2 = m.cast('I', shape=[])\n self.verify(m2, obj=ex,\n itemsize=destsize, fmt='I', readonly=1,\n ndim=0, shape=(), strides=(),\n lst=destitems, cast=True)\n\n # array.array: roundtrip to/from bytes\n for fmt, items, _ in iter_format(31, 'array'):\n ex = array.array(fmt, items)\n m = memoryview(ex)\n iter_roundtrip(ex, m, items, fmt)\n\n # ndarray: roundtrip to/from bytes\n for fmt, items, _ in iter_format(31, 'memoryview'):\n ex = ndarray(items, shape=[31], format=fmt, flags=ND_WRITABLE)\n m = memoryview(ex)\n iter_roundtrip(ex, m, items, fmt)\n\n def test_memoryview_cast_1D_ND(self):\n # Cast between C-contiguous buffers. At least one buffer must\n # be 1D, at least one format must be 'c', 'b' or 'B'.\n for _tshape in gencastshapes():\n for char in fmtdict['@']:\n tfmt = ('', '@')[randrange(2)] + char\n tsize = struct.calcsize(tfmt)\n n = prod(_tshape) * tsize\n obj = 'memoryview' if is_byte_format(tfmt) else 'bytefmt'\n for fmt, items, _ in iter_format(n, obj):\n size = struct.calcsize(fmt)\n shape = [n] if n > 0 else []\n tshape = _tshape + [size]\n\n ex = ndarray(items, shape=shape, format=fmt)\n m = memoryview(ex)\n\n titems, tshape = cast_items(ex, tfmt, tsize, shape=tshape)\n\n if titems is None:\n self.assertRaises(TypeError, m.cast, tfmt, tshape)\n continue\n if titems == 'nan':\n continue # NaNs in lists are a recipe for trouble.\n\n # 1D -> ND\n nd = ndarray(titems, shape=tshape, format=tfmt)\n\n m2 = m.cast(tfmt, shape=tshape)\n ndim = len(tshape)\n strides = nd.strides\n lst = nd.tolist()\n self.verify(m2, obj=ex,\n itemsize=tsize, fmt=tfmt, readonly=1,\n ndim=ndim, shape=tshape, strides=strides,\n lst=lst, cast=True)\n\n # ND -> 1D\n m3 = m2.cast(fmt)\n m4 = m2.cast(fmt, shape=shape)\n ndim = len(shape)\n strides = ex.strides\n lst = ex.tolist()\n\n self.verify(m3, obj=ex,\n itemsize=size, fmt=fmt, readonly=1,\n ndim=ndim, shape=shape, strides=strides,\n lst=lst, cast=True)\n\n self.verify(m4, obj=ex,\n itemsize=size, fmt=fmt, readonly=1,\n ndim=ndim, shape=shape, strides=strides,\n lst=lst, cast=True)\n\n if ctypes:\n # format: \"T{>l:x:>d:y:}\"\n class BEPoint(ctypes.BigEndianStructure):\n _fields_ = [(\"x\", ctypes.c_long), (\"y\", ctypes.c_double)]\n point = BEPoint(100, 200.1)\n m1 = memoryview(point)\n m2 = m1.cast('B')\n self.assertEqual(m2.obj, point)\n self.assertEqual(m2.itemsize, 1)\n self.assertEqual(m2.readonly, 0)\n self.assertEqual(m2.ndim, 1)\n self.assertEqual(m2.shape, (m2.nbytes,))\n self.assertEqual(m2.strides, (1,))\n self.assertEqual(m2.suboffsets, ())\n\n x = ctypes.c_double(1.2)\n m1 = memoryview(x)\n m2 = m1.cast('c')\n self.assertEqual(m2.obj, x)\n self.assertEqual(m2.itemsize, 1)\n self.assertEqual(m2.readonly, 0)\n self.assertEqual(m2.ndim, 1)\n self.assertEqual(m2.shape, (m2.nbytes,))\n self.assertEqual(m2.strides, (1,))\n self.assertEqual(m2.suboffsets, ())\n\n def test_memoryview_tolist(self):\n\n # Most tolist() tests are in self.verify() etc.\n\n a = array.array('h', list(range(-6, 6)))\n m = memoryview(a)\n self.assertEqual(m, a)\n self.assertEqual(m.tolist(), a.tolist())\n\n a = a[2::3]\n m = m[2::3]\n self.assertEqual(m, a)\n self.assertEqual(m.tolist(), a.tolist())\n\n ex = ndarray(list(range(2*3*5*7*11)), shape=[11,2,7,3,5], format='L')\n m = memoryview(ex)\n self.assertEqual(m.tolist(), ex.tolist())\n\n ex = ndarray([(2, 5), (7, 11)], shape=[2], format='lh')\n m = memoryview(ex)\n self.assertRaises(NotImplementedError, m.tolist)\n\n ex = ndarray([b'12345'], shape=[1], format=\"s\")\n m = memoryview(ex)\n self.assertRaises(NotImplementedError, m.tolist)\n\n ex = ndarray([b\"a\",b\"b\",b\"c\",b\"d\",b\"e\",b\"f\"], shape=[2,3], format='s')\n m = memoryview(ex)\n self.assertRaises(NotImplementedError, m.tolist)\n\n def test_memoryview_repr(self):\n m = memoryview(bytearray(9))\n r = m.__repr__()\n self.assertTrue(r.startswith(\"<memory\"))\n\n m.release()\n r = m.__repr__()\n self.assertTrue(r.startswith(\"<released\"))\n\n def test_memoryview_sequence(self):\n\n for fmt in ('d', 'f'):\n inf = float(3e400)\n ex = array.array(fmt, [1.0, inf, 3.0])\n m = memoryview(ex)\n self.assertIn(1.0, m)\n self.assertIn(5e700, m)\n self.assertIn(3.0, m)\n\n ex = ndarray(9.0, [], format='f')\n m = memoryview(ex)\n self.assertRaises(TypeError, eval, \"9.0 in m\", locals())\n\n @contextlib.contextmanager\n def assert_out_of_bounds_error(self, dim):\n with self.assertRaises(IndexError) as cm:\n yield\n self.assertEqual(str(cm.exception),\n \"index out of bounds on dimension %d\" % (dim,))\n\n def test_memoryview_index(self):\n\n # ndim = 0\n ex = ndarray(12.5, shape=[], format='d')\n m = memoryview(ex)\n self.assertEqual(m[()], 12.5)\n self.assertEqual(m[...], m)\n self.assertEqual(m[...], ex)\n self.assertRaises(TypeError, m.__getitem__, 0)\n\n ex = ndarray((1,2,3), shape=[], format='iii')\n m = memoryview(ex)\n self.assertRaises(NotImplementedError, m.__getitem__, ())\n\n # range\n ex = ndarray(list(range(7)), shape=[7], flags=ND_WRITABLE)\n m = memoryview(ex)\n\n self.assertRaises(IndexError, m.__getitem__, 2**64)\n self.assertRaises(TypeError, m.__getitem__, 2.0)\n self.assertRaises(TypeError, m.__getitem__, 0.0)\n\n # out of bounds\n self.assertRaises(IndexError, m.__getitem__, -8)\n self.assertRaises(IndexError, m.__getitem__, 8)\n\n # multi-dimensional\n ex = ndarray(list(range(12)), shape=[3,4], flags=ND_WRITABLE)\n m = memoryview(ex)\n\n self.assertEqual(m[0, 0], 0)\n self.assertEqual(m[2, 0], 8)\n self.assertEqual(m[2, 3], 11)\n self.assertEqual(m[-1, -1], 11)\n self.assertEqual(m[-3, -4], 0)\n\n # out of bounds\n for index in (3, -4):\n with self.assert_out_of_bounds_error(dim=1):\n m[index, 0]\n for index in (4, -5):\n with self.assert_out_of_bounds_error(dim=2):\n m[0, index]\n self.assertRaises(IndexError, m.__getitem__, (2**64, 0))\n self.assertRaises(IndexError, m.__getitem__, (0, 2**64))\n\n self.assertRaises(TypeError, m.__getitem__, (0, 0, 0))\n self.assertRaises(TypeError, m.__getitem__, (0.0, 0.0))\n\n # Not implemented: multidimensional sub-views\n self.assertRaises(NotImplementedError, m.__getitem__, ())\n self.assertRaises(NotImplementedError, m.__getitem__, 0)\n\n def test_memoryview_assign(self):\n\n # ndim = 0\n ex = ndarray(12.5, shape=[], format='f', flags=ND_WRITABLE)\n m = memoryview(ex)\n m[()] = 22.5\n self.assertEqual(m[()], 22.5)\n m[...] = 23.5\n self.assertEqual(m[()], 23.5)\n self.assertRaises(TypeError, m.__setitem__, 0, 24.7)\n\n # read-only\n ex = ndarray(list(range(7)), shape=[7])\n m = memoryview(ex)\n self.assertRaises(TypeError, m.__setitem__, 2, 10)\n\n # range\n ex = ndarray(list(range(7)), shape=[7], flags=ND_WRITABLE)\n m = memoryview(ex)\n\n self.assertRaises(IndexError, m.__setitem__, 2**64, 9)\n self.assertRaises(TypeError, m.__setitem__, 2.0, 10)\n self.assertRaises(TypeError, m.__setitem__, 0.0, 11)\n\n # out of bounds\n self.assertRaises(IndexError, m.__setitem__, -8, 20)\n self.assertRaises(IndexError, m.__setitem__, 8, 25)\n\n # pack_single() success:\n for fmt in fmtdict['@']:\n if fmt == 'c' or fmt == '?':\n continue\n ex = ndarray([1,2,3], shape=[3], format=fmt, flags=ND_WRITABLE)\n m = memoryview(ex)\n i = randrange(-3, 3)\n m[i] = 8\n self.assertEqual(m[i], 8)\n self.assertEqual(m[i], ex[i])\n\n ex = ndarray([b'1', b'2', b'3'], shape=[3], format='c',\n flags=ND_WRITABLE)\n m = memoryview(ex)\n m[2] = b'9'\n self.assertEqual(m[2], b'9')\n\n ex = ndarray([True, False, True], shape=[3], format='?',\n flags=ND_WRITABLE)\n m = memoryview(ex)\n m[1] = True\n self.assertEqual(m[1], True)\n\n # pack_single() exceptions:\n nd = ndarray([b'x'], shape=[1], format='c', flags=ND_WRITABLE)\n m = memoryview(nd)\n self.assertRaises(TypeError, m.__setitem__, 0, 100)\n\n ex = ndarray(list(range(120)), shape=[1,2,3,4,5], flags=ND_WRITABLE)\n m1 = memoryview(ex)\n\n for fmt, _range in fmtdict['@'].items():\n if (fmt == '?'): # PyObject_IsTrue() accepts anything\n continue\n if fmt == 'c': # special case tested above\n continue\n m2 = m1.cast(fmt)\n lo, hi = _range\n if fmt == 'd' or fmt == 'f':\n lo, hi = -2**1024, 2**1024\n if fmt != 'P': # PyLong_AsVoidPtr() accepts negative numbers\n self.assertRaises(ValueError, m2.__setitem__, 0, lo-1)\n self.assertRaises(TypeError, m2.__setitem__, 0, \"xyz\")\n self.assertRaises(ValueError, m2.__setitem__, 0, hi)\n\n # invalid item\n m2 = m1.cast('c')\n self.assertRaises(ValueError, m2.__setitem__, 0, b'\\xff\\xff')\n\n # format not implemented\n ex = ndarray(list(range(1)), shape=[1], format=\"xL\", flags=ND_WRITABLE)\n m = memoryview(ex)\n self.assertRaises(NotImplementedError, m.__setitem__, 0, 1)\n\n ex = ndarray([b'12345'], shape=[1], format=\"s\", flags=ND_WRITABLE)\n m = memoryview(ex)\n self.assertRaises(NotImplementedError, m.__setitem__, 0, 1)\n\n # multi-dimensional\n ex = ndarray(list(range(12)), shape=[3,4], flags=ND_WRITABLE)\n m = memoryview(ex)\n m[0,1] = 42\n self.assertEqual(ex[0][1], 42)\n m[-1,-1] = 43\n self.assertEqual(ex[2][3], 43)\n # errors\n for index in (3, -4):\n with self.assert_out_of_bounds_error(dim=1):\n m[index, 0] = 0\n for index in (4, -5):\n with self.assert_out_of_bounds_error(dim=2):\n m[0, index] = 0\n self.assertRaises(IndexError, m.__setitem__, (2**64, 0), 0)\n self.assertRaises(IndexError, m.__setitem__, (0, 2**64), 0)\n\n self.assertRaises(TypeError, m.__setitem__, (0, 0, 0), 0)\n self.assertRaises(TypeError, m.__setitem__, (0.0, 0.0), 0)\n\n # Not implemented: multidimensional sub-views\n self.assertRaises(NotImplementedError, m.__setitem__, 0, [2, 3])\n\n def test_memoryview_slice(self):\n\n ex = ndarray(list(range(12)), shape=[12], flags=ND_WRITABLE)\n m = memoryview(ex)\n\n # zero step\n self.assertRaises(ValueError, m.__getitem__, slice(0,2,0))\n self.assertRaises(ValueError, m.__setitem__, slice(0,2,0),\n bytearray([1,2]))\n\n # 0-dim slicing (identity function)\n self.assertRaises(NotImplementedError, m.__getitem__, ())\n\n # multidimensional slices\n ex = ndarray(list(range(12)), shape=[12], flags=ND_WRITABLE)\n m = memoryview(ex)\n\n self.assertRaises(NotImplementedError, m.__getitem__,\n (slice(0,2,1), slice(0,2,1)))\n self.assertRaises(NotImplementedError, m.__setitem__,\n (slice(0,2,1), slice(0,2,1)), bytearray([1,2]))\n\n # invalid slice tuple\n self.assertRaises(TypeError, m.__getitem__, (slice(0,2,1), {}))\n self.assertRaises(TypeError, m.__setitem__, (slice(0,2,1), {}),\n bytearray([1,2]))\n\n # rvalue is not an exporter\n self.assertRaises(TypeError, m.__setitem__, slice(0,1,1), [1])\n\n # non-contiguous slice assignment\n for flags in (0, ND_PIL):\n ex1 = ndarray(list(range(12)), shape=[12], strides=[-1], offset=11,\n flags=ND_WRITABLE|flags)\n ex2 = ndarray(list(range(24)), shape=[12], strides=[2], flags=flags)\n m1 = memoryview(ex1)\n m2 = memoryview(ex2)\n\n ex1[2:5] = ex1[2:5]\n m1[2:5] = m2[2:5]\n\n self.assertEqual(m1, ex1)\n self.assertEqual(m2, ex2)\n\n ex1[1:3][::-1] = ex2[0:2][::1]\n m1[1:3][::-1] = m2[0:2][::1]\n\n self.assertEqual(m1, ex1)\n self.assertEqual(m2, ex2)\n\n ex1[4:1:-2][::-1] = ex1[1:4:2][::1]\n m1[4:1:-2][::-1] = m1[1:4:2][::1]\n\n self.assertEqual(m1, ex1)\n self.assertEqual(m2, ex2)\n\n def test_memoryview_array(self):\n\n def cmptest(testcase, a, b, m, singleitem):\n for i, _ in enumerate(a):\n ai = a[i]\n mi = m[i]\n testcase.assertEqual(ai, mi)\n a[i] = singleitem\n if singleitem != ai:\n testcase.assertNotEqual(a, m)\n testcase.assertNotEqual(a, b)\n else:\n testcase.assertEqual(a, m)\n testcase.assertEqual(a, b)\n m[i] = singleitem\n testcase.assertEqual(a, m)\n testcase.assertEqual(b, m)\n a[i] = ai\n m[i] = mi\n\n for n in range(1, 5):\n for fmt, items, singleitem in iter_format(n, 'array'):\n for lslice in genslices(n):\n for rslice in genslices(n):\n\n a = array.array(fmt, items)\n b = array.array(fmt, items)\n m = memoryview(b)\n\n self.assertEqual(m, a)\n self.assertEqual(m.tolist(), a.tolist())\n self.assertEqual(m.tobytes(), a.tobytes())\n self.assertEqual(len(m), len(a))\n\n cmptest(self, a, b, m, singleitem)\n\n array_err = None\n have_resize = None\n try:\n al = a[lslice]\n ar = a[rslice]\n a[lslice] = a[rslice]\n have_resize = len(al) != len(ar)\n except Exception as e:\n array_err = e.__class__\n\n m_err = None\n try:\n m[lslice] = m[rslice]\n except Exception as e:\n m_err = e.__class__\n\n if have_resize: # memoryview cannot change shape\n self.assertIs(m_err, ValueError)\n elif m_err or array_err:\n self.assertIs(m_err, array_err)\n else:\n self.assertEqual(m, a)\n self.assertEqual(m.tolist(), a.tolist())\n self.assertEqual(m.tobytes(), a.tobytes())\n cmptest(self, a, b, m, singleitem)\n\n def test_memoryview_compare_special_cases(self):\n\n a = array.array('L', [1, 2, 3])\n b = array.array('L', [1, 2, 7])\n\n # Ordering comparisons raise:\n v = memoryview(a)\n w = memoryview(b)\n for attr in ('__lt__', '__le__', '__gt__', '__ge__'):\n self.assertIs(getattr(v, attr)(w), NotImplemented)\n self.assertIs(getattr(a, attr)(v), NotImplemented)\n\n # Released views compare equal to themselves:\n v = memoryview(a)\n v.release()\n self.assertEqual(v, v)\n self.assertNotEqual(v, a)\n self.assertNotEqual(a, v)\n\n v = memoryview(a)\n w = memoryview(a)\n w.release()\n self.assertNotEqual(v, w)\n self.assertNotEqual(w, v)\n\n # Operand does not implement the buffer protocol:\n v = memoryview(a)\n self.assertNotEqual(v, [1, 2, 3])\n\n # NaNs\n nd = ndarray([(0, 0)], shape=[1], format='l x d x', flags=ND_WRITABLE)\n nd[0] = (-1, float('nan'))\n self.assertNotEqual(memoryview(nd), nd)\n\n # Depends on issue #15625: the struct module does not understand 'u'.\n a = array.array('u', 'xyz')\n v = memoryview(a)\n self.assertNotEqual(a, v)\n self.assertNotEqual(v, a)\n\n # Some ctypes format strings are unknown to the struct module.\n if ctypes:\n # format: \"T{>l:x:>l:y:}\"\n class BEPoint(ctypes.BigEndianStructure):\n _fields_ = [(\"x\", ctypes.c_long), (\"y\", ctypes.c_long)]\n point = BEPoint(100, 200)\n a = memoryview(point)\n b = memoryview(point)\n self.assertNotEqual(a, b)\n self.assertNotEqual(a, point)\n self.assertNotEqual(point, a)\n self.assertRaises(NotImplementedError, a.tolist)\n\n def test_memoryview_compare_ndim_zero(self):\n\n nd1 = ndarray(1729, shape=[], format='@L')\n nd2 = ndarray(1729, shape=[], format='L', flags=ND_WRITABLE)\n v = memoryview(nd1)\n w = memoryview(nd2)\n self.assertEqual(v, w)\n self.assertEqual(w, v)\n self.assertEqual(v, nd2)\n self.assertEqual(nd2, v)\n self.assertEqual(w, nd1)\n self.assertEqual(nd1, w)\n\n self.assertFalse(v.__ne__(w))\n self.assertFalse(w.__ne__(v))\n\n w[()] = 1728\n self.assertNotEqual(v, w)\n self.assertNotEqual(w, v)\n self.assertNotEqual(v, nd2)\n self.assertNotEqual(nd2, v)\n self.assertNotEqual(w, nd1)\n self.assertNotEqual(nd1, w)\n\n self.assertFalse(v.__eq__(w))\n self.assertFalse(w.__eq__(v))\n\n nd = ndarray(list(range(12)), shape=[12], flags=ND_WRITABLE|ND_PIL)\n ex = ndarray(list(range(12)), shape=[12], flags=ND_WRITABLE|ND_PIL)\n m = memoryview(ex)\n\n self.assertEqual(m, nd)\n m[9] = 100\n self.assertNotEqual(m, nd)\n\n # struct module: equal\n nd1 = ndarray((1729, 1.2, b'12345'), shape=[], format='Lf5s')\n nd2 = ndarray((1729, 1.2, b'12345'), shape=[], format='hf5s',\n flags=ND_WRITABLE)\n v = memoryview(nd1)\n w = memoryview(nd2)\n self.assertEqual(v, w)\n self.assertEqual(w, v)\n self.assertEqual(v, nd2)\n self.assertEqual(nd2, v)\n self.assertEqual(w, nd1)\n self.assertEqual(nd1, w)\n\n # struct module: not equal\n nd1 = ndarray((1729, 1.2, b'12345'), shape=[], format='Lf5s')\n nd2 = ndarray((-1729, 1.2, b'12345'), shape=[], format='hf5s',\n flags=ND_WRITABLE)\n v = memoryview(nd1)\n w = memoryview(nd2)\n self.assertNotEqual(v, w)\n self.assertNotEqual(w, v)\n self.assertNotEqual(v, nd2)\n self.assertNotEqual(nd2, v)\n self.assertNotEqual(w, nd1)\n self.assertNotEqual(nd1, w)\n self.assertEqual(v, nd1)\n self.assertEqual(w, nd2)\n\n def test_memoryview_compare_ndim_one(self):\n\n # contiguous\n nd1 = ndarray([-529, 576, -625, 676, -729], shape=[5], format='@h')\n nd2 = ndarray([-529, 576, -625, 676, 729], shape=[5], format='@h')\n v = memoryview(nd1)\n w = memoryview(nd2)\n\n self.assertEqual(v, nd1)\n self.assertEqual(w, nd2)\n self.assertNotEqual(v, nd2)\n self.assertNotEqual(w, nd1)\n self.assertNotEqual(v, w)\n\n # contiguous, struct module\n nd1 = ndarray([-529, 576, -625, 676, -729], shape=[5], format='<i')\n nd2 = ndarray([-529, 576, -625, 676, 729], shape=[5], format='>h')\n v = memoryview(nd1)\n w = memoryview(nd2)\n\n self.assertEqual(v, nd1)\n self.assertEqual(w, nd2)\n self.assertNotEqual(v, nd2)\n self.assertNotEqual(w, nd1)\n self.assertNotEqual(v, w)\n\n # non-contiguous\n nd1 = ndarray([-529, -625, -729], shape=[3], format='@h')\n nd2 = ndarray([-529, 576, -625, 676, -729], shape=[5], format='@h')\n v = memoryview(nd1)\n w = memoryview(nd2)\n\n self.assertEqual(v, nd2[::2])\n self.assertEqual(w[::2], nd1)\n self.assertEqual(v, w[::2])\n self.assertEqual(v[::-1], w[::-2])\n\n # non-contiguous, struct module\n nd1 = ndarray([-529, -625, -729], shape=[3], format='!h')\n nd2 = ndarray([-529, 576, -625, 676, -729], shape=[5], format='<l')\n v = memoryview(nd1)\n w = memoryview(nd2)\n\n self.assertEqual(v, nd2[::2])\n self.assertEqual(w[::2], nd1)\n self.assertEqual(v, w[::2])\n self.assertEqual(v[::-1], w[::-2])\n\n # non-contiguous, suboffsets\n nd1 = ndarray([-529, -625, -729], shape=[3], format='@h')\n nd2 = ndarray([-529, 576, -625, 676, -729], shape=[5], format='@h',\n flags=ND_PIL)\n v = memoryview(nd1)\n w = memoryview(nd2)\n\n self.assertEqual(v, nd2[::2])\n self.assertEqual(w[::2], nd1)\n self.assertEqual(v, w[::2])\n self.assertEqual(v[::-1], w[::-2])\n\n # non-contiguous, suboffsets, struct module\n nd1 = ndarray([-529, -625, -729], shape=[3], format='h 0c')\n nd2 = ndarray([-529, 576, -625, 676, -729], shape=[5], format='> h',\n flags=ND_PIL)\n v = memoryview(nd1)\n w = memoryview(nd2)\n\n self.assertEqual(v, nd2[::2])\n self.assertEqual(w[::2], nd1)\n self.assertEqual(v, w[::2])\n self.assertEqual(v[::-1], w[::-2])\n\n def test_memoryview_compare_zero_shape(self):\n\n # zeros in shape\n nd1 = ndarray([900, 961], shape=[0], format='@h')\n nd2 = ndarray([-900, -961], shape=[0], format='@h')\n v = memoryview(nd1)\n w = memoryview(nd2)\n\n self.assertEqual(v, nd1)\n self.assertEqual(w, nd2)\n self.assertEqual(v, nd2)\n self.assertEqual(w, nd1)\n self.assertEqual(v, w)\n\n # zeros in shape, struct module\n nd1 = ndarray([900, 961], shape=[0], format='= h0c')\n nd2 = ndarray([-900, -961], shape=[0], format='@ i')\n v = memoryview(nd1)\n w = memoryview(nd2)\n\n self.assertEqual(v, nd1)\n self.assertEqual(w, nd2)\n self.assertEqual(v, nd2)\n self.assertEqual(w, nd1)\n self.assertEqual(v, w)\n\n def test_memoryview_compare_zero_strides(self):\n\n # zero strides\n nd1 = ndarray([900, 900, 900, 900], shape=[4], format='@L')\n nd2 = ndarray([900], shape=[4], strides=[0], format='L')\n v = memoryview(nd1)\n w = memoryview(nd2)\n\n self.assertEqual(v, nd1)\n self.assertEqual(w, nd2)\n self.assertEqual(v, nd2)\n self.assertEqual(w, nd1)\n self.assertEqual(v, w)\n\n # zero strides, struct module\n nd1 = ndarray([(900, 900)]*4, shape=[4], format='@ Li')\n nd2 = ndarray([(900, 900)], shape=[4], strides=[0], format='!L h')\n v = memoryview(nd1)\n w = memoryview(nd2)\n\n self.assertEqual(v, nd1)\n self.assertEqual(w, nd2)\n self.assertEqual(v, nd2)\n self.assertEqual(w, nd1)\n self.assertEqual(v, w)\n\n def test_memoryview_compare_random_formats(self):\n\n # random single character native formats\n n = 10\n for char in fmtdict['@m']:\n fmt, items, singleitem = randitems(n, 'memoryview', '@', char)\n for flags in (0, ND_PIL):\n nd = ndarray(items, shape=[n], format=fmt, flags=flags)\n m = memoryview(nd)\n self.assertEqual(m, nd)\n\n nd = nd[::-3]\n m = memoryview(nd)\n self.assertEqual(m, nd)\n\n # random formats\n n = 10\n for _ in range(100):\n fmt, items, singleitem = randitems(n)\n for flags in (0, ND_PIL):\n nd = ndarray(items, shape=[n], format=fmt, flags=flags)\n m = memoryview(nd)\n self.assertEqual(m, nd)\n\n nd = nd[::-3]\n m = memoryview(nd)\n self.assertEqual(m, nd)\n\n def test_memoryview_compare_multidim_c(self):\n\n # C-contiguous, different values\n nd1 = ndarray(list(range(-15, 15)), shape=[3, 2, 5], format='@h')\n nd2 = ndarray(list(range(0, 30)), shape=[3, 2, 5], format='@h')\n v = memoryview(nd1)\n w = memoryview(nd2)\n\n self.assertEqual(v, nd1)\n self.assertEqual(w, nd2)\n self.assertNotEqual(v, nd2)\n self.assertNotEqual(w, nd1)\n self.assertNotEqual(v, w)\n\n # C-contiguous, different values, struct module\n nd1 = ndarray([(0, 1, 2)]*30, shape=[3, 2, 5], format='=f q xxL')\n nd2 = ndarray([(-1.2, 1, 2)]*30, shape=[3, 2, 5], format='< f 2Q')\n v = memoryview(nd1)\n w = memoryview(nd2)\n\n self.assertEqual(v, nd1)\n self.assertEqual(w, nd2)\n self.assertNotEqual(v, nd2)\n self.assertNotEqual(w, nd1)\n self.assertNotEqual(v, w)\n\n # C-contiguous, different shape\n nd1 = ndarray(list(range(30)), shape=[2, 3, 5], format='L')\n nd2 = ndarray(list(range(30)), shape=[3, 2, 5], format='L')\n v = memoryview(nd1)\n w = memoryview(nd2)\n\n self.assertEqual(v, nd1)\n self.assertEqual(w, nd2)\n self.assertNotEqual(v, nd2)\n self.assertNotEqual(w, nd1)\n self.assertNotEqual(v, w)\n\n # C-contiguous, different shape, struct module\n nd1 = ndarray([(0, 1, 2)]*21, shape=[3, 7], format='! b B xL')\n nd2 = ndarray([(0, 1, 2)]*21, shape=[7, 3], format='= Qx l xxL')\n v = memoryview(nd1)\n w = memoryview(nd2)\n\n self.assertEqual(v, nd1)\n self.assertEqual(w, nd2)\n self.assertNotEqual(v, nd2)\n self.assertNotEqual(w, nd1)\n self.assertNotEqual(v, w)\n\n # C-contiguous, different format, struct module\n nd1 = ndarray(list(range(30)), shape=[2, 3, 5], format='L')\n nd2 = ndarray(list(range(30)), shape=[2, 3, 5], format='l')\n v = memoryview(nd1)\n w = memoryview(nd2)\n\n self.assertEqual(v, nd1)\n self.assertEqual(w, nd2)\n self.assertEqual(v, nd2)\n self.assertEqual(w, nd1)\n self.assertEqual(v, w)\n\n def test_memoryview_compare_multidim_fortran(self):\n\n # Fortran-contiguous, different values\n nd1 = ndarray(list(range(-15, 15)), shape=[5, 2, 3], format='@h',\n flags=ND_FORTRAN)\n nd2 = ndarray(list(range(0, 30)), shape=[5, 2, 3], format='@h',\n flags=ND_FORTRAN)\n v = memoryview(nd1)\n w = memoryview(nd2)\n\n self.assertEqual(v, nd1)\n self.assertEqual(w, nd2)\n self.assertNotEqual(v, nd2)\n self.assertNotEqual(w, nd1)\n self.assertNotEqual(v, w)\n\n # Fortran-contiguous, different values, struct module\n nd1 = ndarray([(2**64-1, -1)]*6, shape=[2, 3], format='=Qq',\n flags=ND_FORTRAN)\n nd2 = ndarray([(-1, 2**64-1)]*6, shape=[2, 3], format='=qQ',\n flags=ND_FORTRAN)\n v = memoryview(nd1)\n w = memoryview(nd2)\n\n self.assertEqual(v, nd1)\n self.assertEqual(w, nd2)\n self.assertNotEqual(v, nd2)\n self.assertNotEqual(w, nd1)\n self.assertNotEqual(v, w)\n\n # Fortran-contiguous, different shape\n nd1 = ndarray(list(range(-15, 15)), shape=[2, 3, 5], format='l',\n flags=ND_FORTRAN)\n nd2 = ndarray(list(range(-15, 15)), shape=[3, 2, 5], format='l',\n flags=ND_FORTRAN)\n v = memoryview(nd1)\n w = memoryview(nd2)\n\n self.assertEqual(v, nd1)\n self.assertEqual(w, nd2)\n self.assertNotEqual(v, nd2)\n self.assertNotEqual(w, nd1)\n self.assertNotEqual(v, w)\n\n # Fortran-contiguous, different shape, struct module\n nd1 = ndarray(list(range(-15, 15)), shape=[2, 3, 5], format='0ll',\n flags=ND_FORTRAN)\n nd2 = ndarray(list(range(-15, 15)), shape=[3, 2, 5], format='l',\n flags=ND_FORTRAN)\n v = memoryview(nd1)\n w = memoryview(nd2)\n\n self.assertEqual(v, nd1)\n self.assertEqual(w, nd2)\n self.assertNotEqual(v, nd2)\n self.assertNotEqual(w, nd1)\n self.assertNotEqual(v, w)\n\n # Fortran-contiguous, different format, struct module\n nd1 = ndarray(list(range(30)), shape=[5, 2, 3], format='@h',\n flags=ND_FORTRAN)\n nd2 = ndarray(list(range(30)), shape=[5, 2, 3], format='@b',\n flags=ND_FORTRAN)\n v = memoryview(nd1)\n w = memoryview(nd2)\n\n self.assertEqual(v, nd1)\n self.assertEqual(w, nd2)\n self.assertEqual(v, nd2)\n self.assertEqual(w, nd1)\n self.assertEqual(v, w)\n\n def test_memoryview_compare_multidim_mixed(self):\n\n # mixed C/Fortran contiguous\n lst1 = list(range(-15, 15))\n lst2 = transpose(lst1, [3, 2, 5])\n nd1 = ndarray(lst1, shape=[3, 2, 5], format='@l')\n nd2 = ndarray(lst2, shape=[3, 2, 5], format='l', flags=ND_FORTRAN)\n v = memoryview(nd1)\n w = memoryview(nd2)\n\n self.assertEqual(v, nd1)\n self.assertEqual(w, nd2)\n self.assertEqual(v, w)\n\n # mixed C/Fortran contiguous, struct module\n lst1 = [(-3.3, -22, b'x')]*30\n lst1[5] = (-2.2, -22, b'x')\n lst2 = transpose(lst1, [3, 2, 5])\n nd1 = ndarray(lst1, shape=[3, 2, 5], format='d b c')\n nd2 = ndarray(lst2, shape=[3, 2, 5], format='d h c', flags=ND_FORTRAN)\n v = memoryview(nd1)\n w = memoryview(nd2)\n\n self.assertEqual(v, nd1)\n self.assertEqual(w, nd2)\n self.assertEqual(v, w)\n\n # different values, non-contiguous\n ex1 = ndarray(list(range(40)), shape=[5, 8], format='@I')\n nd1 = ex1[3:1:-1, ::-2]\n ex2 = ndarray(list(range(40)), shape=[5, 8], format='I')\n nd2 = ex2[1:3:1, ::-2]\n v = memoryview(nd1)\n w = memoryview(nd2)\n\n self.assertEqual(v, nd1)\n self.assertEqual(w, nd2)\n self.assertNotEqual(v, nd2)\n self.assertNotEqual(w, nd1)\n self.assertNotEqual(v, w)\n\n # same values, non-contiguous, struct module\n ex1 = ndarray([(2**31-1, -2**31)]*22, shape=[11, 2], format='=ii')\n nd1 = ex1[3:1:-1, ::-2]\n ex2 = ndarray([(2**31-1, -2**31)]*22, shape=[11, 2], format='>ii')\n nd2 = ex2[1:3:1, ::-2]\n v = memoryview(nd1)\n w = memoryview(nd2)\n\n self.assertEqual(v, nd1)\n self.assertEqual(w, nd2)\n self.assertEqual(v, nd2)\n self.assertEqual(w, nd1)\n self.assertEqual(v, w)\n\n # different shape\n ex1 = ndarray(list(range(30)), shape=[2, 3, 5], format='b')\n nd1 = ex1[1:3:, ::-2]\n nd2 = ndarray(list(range(30)), shape=[3, 2, 5], format='b')\n nd2 = ex2[1:3:, ::-2]\n v = memoryview(nd1)\n w = memoryview(nd2)\n\n self.assertEqual(v, nd1)\n self.assertEqual(w, nd2)\n self.assertNotEqual(v, nd2)\n self.assertNotEqual(w, nd1)\n self.assertNotEqual(v, w)\n\n # different shape, struct module\n ex1 = ndarray(list(range(30)), shape=[2, 3, 5], format='B')\n nd1 = ex1[1:3:, ::-2]\n nd2 = ndarray(list(range(30)), shape=[3, 2, 5], format='b')\n nd2 = ex2[1:3:, ::-2]\n v = memoryview(nd1)\n w = memoryview(nd2)\n\n self.assertEqual(v, nd1)\n self.assertEqual(w, nd2)\n self.assertNotEqual(v, nd2)\n self.assertNotEqual(w, nd1)\n self.assertNotEqual(v, w)\n\n # different format, struct module\n ex1 = ndarray([(2, b'123')]*30, shape=[5, 3, 2], format='b3s')\n nd1 = ex1[1:3:, ::-2]\n nd2 = ndarray([(2, b'123')]*30, shape=[5, 3, 2], format='i3s')\n nd2 = ex2[1:3:, ::-2]\n v = memoryview(nd1)\n w = memoryview(nd2)\n\n self.assertEqual(v, nd1)\n self.assertEqual(w, nd2)\n self.assertNotEqual(v, nd2)\n self.assertNotEqual(w, nd1)\n self.assertNotEqual(v, w)\n\n def test_memoryview_compare_multidim_zero_shape(self):\n\n # zeros in shape\n nd1 = ndarray(list(range(30)), shape=[0, 3, 2], format='i')\n nd2 = ndarray(list(range(30)), shape=[5, 0, 2], format='@i')\n v = memoryview(nd1)\n w = memoryview(nd2)\n\n self.assertEqual(v, nd1)\n self.assertEqual(w, nd2)\n self.assertNotEqual(v, nd2)\n self.assertNotEqual(w, nd1)\n self.assertNotEqual(v, w)\n\n # zeros in shape, struct module\n nd1 = ndarray(list(range(30)), shape=[0, 3, 2], format='i')\n nd2 = ndarray(list(range(30)), shape=[5, 0, 2], format='@i')\n v = memoryview(nd1)\n w = memoryview(nd2)\n\n self.assertEqual(v, nd1)\n self.assertEqual(w, nd2)\n self.assertNotEqual(v, nd2)\n self.assertNotEqual(w, nd1)\n self.assertNotEqual(v, w)\n\n def test_memoryview_compare_multidim_zero_strides(self):\n\n # zero strides\n nd1 = ndarray([900]*80, shape=[4, 5, 4], format='@L')\n nd2 = ndarray([900], shape=[4, 5, 4], strides=[0, 0, 0], format='L')\n v = memoryview(nd1)\n w = memoryview(nd2)\n\n self.assertEqual(v, nd1)\n self.assertEqual(w, nd2)\n self.assertEqual(v, nd2)\n self.assertEqual(w, nd1)\n self.assertEqual(v, w)\n self.assertEqual(v.tolist(), w.tolist())\n\n # zero strides, struct module\n nd1 = ndarray([(1, 2)]*10, shape=[2, 5], format='=lQ')\n nd2 = ndarray([(1, 2)], shape=[2, 5], strides=[0, 0], format='<lQ')\n v = memoryview(nd1)\n w = memoryview(nd2)\n\n self.assertEqual(v, nd1)\n self.assertEqual(w, nd2)\n self.assertEqual(v, nd2)\n self.assertEqual(w, nd1)\n self.assertEqual(v, w)\n\n def test_memoryview_compare_multidim_suboffsets(self):\n\n # suboffsets\n ex1 = ndarray(list(range(40)), shape=[5, 8], format='@I')\n nd1 = ex1[3:1:-1, ::-2]\n ex2 = ndarray(list(range(40)), shape=[5, 8], format='I', flags=ND_PIL)\n nd2 = ex2[1:3:1, ::-2]\n v = memoryview(nd1)\n w = memoryview(nd2)\n\n self.assertEqual(v, nd1)\n self.assertEqual(w, nd2)\n self.assertNotEqual(v, nd2)\n self.assertNotEqual(w, nd1)\n self.assertNotEqual(v, w)\n\n # suboffsets, struct module\n ex1 = ndarray([(2**64-1, -1)]*40, shape=[5, 8], format='=Qq',\n flags=ND_WRITABLE)\n ex1[2][7] = (1, -2)\n nd1 = ex1[3:1:-1, ::-2]\n\n ex2 = ndarray([(2**64-1, -1)]*40, shape=[5, 8], format='>Qq',\n flags=ND_PIL|ND_WRITABLE)\n ex2[2][7] = (1, -2)\n nd2 = ex2[1:3:1, ::-2]\n\n v = memoryview(nd1)\n w = memoryview(nd2)\n\n self.assertEqual(v, nd1)\n self.assertEqual(w, nd2)\n self.assertEqual(v, nd2)\n self.assertEqual(w, nd1)\n self.assertEqual(v, w)\n\n # suboffsets, different shape\n ex1 = ndarray(list(range(30)), shape=[2, 3, 5], format='b',\n flags=ND_PIL)\n nd1 = ex1[1:3:, ::-2]\n nd2 = ndarray(list(range(30)), shape=[3, 2, 5], format='b')\n nd2 = ex2[1:3:, ::-2]\n v = memoryview(nd1)\n w = memoryview(nd2)\n\n self.assertEqual(v, nd1)\n self.assertEqual(w, nd2)\n self.assertNotEqual(v, nd2)\n self.assertNotEqual(w, nd1)\n self.assertNotEqual(v, w)\n\n # suboffsets, different shape, struct module\n ex1 = ndarray([(2**8-1, -1)]*40, shape=[2, 3, 5], format='Bb',\n flags=ND_PIL|ND_WRITABLE)\n nd1 = ex1[1:2:, ::-2]\n\n ex2 = ndarray([(2**8-1, -1)]*40, shape=[3, 2, 5], format='Bb')\n nd2 = ex2[1:2:, ::-2]\n\n v = memoryview(nd1)\n w = memoryview(nd2)\n\n self.assertEqual(v, nd1)\n self.assertEqual(w, nd2)\n self.assertNotEqual(v, nd2)\n self.assertNotEqual(w, nd1)\n self.assertNotEqual(v, w)\n\n # suboffsets, different format\n ex1 = ndarray(list(range(30)), shape=[5, 3, 2], format='i', flags=ND_PIL)\n nd1 = ex1[1:3:, ::-2]\n ex2 = ndarray(list(range(30)), shape=[5, 3, 2], format='@I', flags=ND_PIL)\n nd2 = ex2[1:3:, ::-2]\n v = memoryview(nd1)\n w = memoryview(nd2)\n\n self.assertEqual(v, nd1)\n self.assertEqual(w, nd2)\n self.assertEqual(v, nd2)\n self.assertEqual(w, nd1)\n self.assertEqual(v, w)\n\n # suboffsets, different format, struct module\n ex1 = ndarray([(b'hello', b'', 1)]*27, shape=[3, 3, 3], format='5s0sP',\n flags=ND_PIL|ND_WRITABLE)\n ex1[1][2][2] = (b'sushi', b'', 1)\n nd1 = ex1[1:3:, ::-2]\n\n ex2 = ndarray([(b'hello', b'', 1)]*27, shape=[3, 3, 3], format='5s0sP',\n flags=ND_PIL|ND_WRITABLE)\n ex1[1][2][2] = (b'sushi', b'', 1)\n nd2 = ex2[1:3:, ::-2]\n\n v = memoryview(nd1)\n w = memoryview(nd2)\n\n self.assertEqual(v, nd1)\n self.assertEqual(w, nd2)\n self.assertNotEqual(v, nd2)\n self.assertNotEqual(w, nd1)\n self.assertNotEqual(v, w)\n\n # initialize mixed C/Fortran + suboffsets\n lst1 = list(range(-15, 15))\n lst2 = transpose(lst1, [3, 2, 5])\n nd1 = ndarray(lst1, shape=[3, 2, 5], format='@l', flags=ND_PIL)\n nd2 = ndarray(lst2, shape=[3, 2, 5], format='l', flags=ND_FORTRAN|ND_PIL)\n v = memoryview(nd1)\n w = memoryview(nd2)\n\n self.assertEqual(v, nd1)\n self.assertEqual(w, nd2)\n self.assertEqual(v, w)\n\n # initialize mixed C/Fortran + suboffsets, struct module\n lst1 = [(b'sashimi', b'sliced', 20.05)]*30\n lst1[11] = (b'ramen', b'spicy', 9.45)\n lst2 = transpose(lst1, [3, 2, 5])\n\n nd1 = ndarray(lst1, shape=[3, 2, 5], format='< 10p 9p d', flags=ND_PIL)\n nd2 = ndarray(lst2, shape=[3, 2, 5], format='> 10p 9p d',\n flags=ND_FORTRAN|ND_PIL)\n v = memoryview(nd1)\n w = memoryview(nd2)\n\n self.assertEqual(v, nd1)\n self.assertEqual(w, nd2)\n self.assertEqual(v, w)\n\n def test_memoryview_compare_not_equal(self):\n\n # items not equal\n for byteorder in ['=', '<', '>', '!']:\n x = ndarray([2**63]*120, shape=[3,5,2,2,2], format=byteorder+'Q')\n y = ndarray([2**63]*120, shape=[3,5,2,2,2], format=byteorder+'Q',\n flags=ND_WRITABLE|ND_FORTRAN)\n y[2][3][1][1][1] = 1\n a = memoryview(x)\n b = memoryview(y)\n self.assertEqual(a, x)\n self.assertEqual(b, y)\n self.assertNotEqual(a, b)\n self.assertNotEqual(a, y)\n self.assertNotEqual(b, x)\n\n x = ndarray([(2**63, 2**31, 2**15)]*120, shape=[3,5,2,2,2],\n format=byteorder+'QLH')\n y = ndarray([(2**63, 2**31, 2**15)]*120, shape=[3,5,2,2,2],\n format=byteorder+'QLH', flags=ND_WRITABLE|ND_FORTRAN)\n y[2][3][1][1][1] = (1, 1, 1)\n a = memoryview(x)\n b = memoryview(y)\n self.assertEqual(a, x)\n self.assertEqual(b, y)\n self.assertNotEqual(a, b)\n self.assertNotEqual(a, y)\n self.assertNotEqual(b, x)\n\n def test_memoryview_check_released(self):\n\n a = array.array('d', [1.1, 2.2, 3.3])\n\n m = memoryview(a)\n m.release()\n\n # PyMemoryView_FromObject()\n self.assertRaises(ValueError, memoryview, m)\n # memoryview.cast()\n self.assertRaises(ValueError, m.cast, 'c')\n # getbuffer()\n self.assertRaises(ValueError, ndarray, m)\n # memoryview.tolist()\n self.assertRaises(ValueError, m.tolist)\n # memoryview.tobytes()\n self.assertRaises(ValueError, m.tobytes)\n # sequence\n self.assertRaises(ValueError, eval, \"1.0 in m\", locals())\n # subscript\n self.assertRaises(ValueError, m.__getitem__, 0)\n # assignment\n self.assertRaises(ValueError, m.__setitem__, 0, 1)\n\n for attr in ('obj', 'nbytes', 'readonly', 'itemsize', 'format', 'ndim',\n 'shape', 'strides', 'suboffsets', 'c_contiguous',\n 'f_contiguous', 'contiguous'):\n self.assertRaises(ValueError, m.__getattribute__, attr)\n\n # richcompare\n b = array.array('d', [1.1, 2.2, 3.3])\n m1 = memoryview(a)\n m2 = memoryview(b)\n\n self.assertEqual(m1, m2)\n m1.release()\n self.assertNotEqual(m1, m2)\n self.assertNotEqual(m1, a)\n self.assertEqual(m1, m1)\n\n def test_memoryview_tobytes(self):\n # Many implicit tests are already in self.verify().\n\n t = (-529, 576, -625, 676, -729)\n\n nd = ndarray(t, shape=[5], format='@h')\n m = memoryview(nd)\n self.assertEqual(m, nd)\n self.assertEqual(m.tobytes(), nd.tobytes())\n\n nd = ndarray([t], shape=[1], format='>hQiLl')\n m = memoryview(nd)\n self.assertEqual(m, nd)\n self.assertEqual(m.tobytes(), nd.tobytes())\n\n nd = ndarray([t for _ in range(12)], shape=[2,2,3], format='=hQiLl')\n m = memoryview(nd)\n self.assertEqual(m, nd)\n self.assertEqual(m.tobytes(), nd.tobytes())\n\n nd = ndarray([t for _ in range(120)], shape=[5,2,2,3,2],\n format='<hQiLl')\n m = memoryview(nd)\n self.assertEqual(m, nd)\n self.assertEqual(m.tobytes(), nd.tobytes())\n\n # Unknown formats are handled: tobytes() purely depends on itemsize.\n if ctypes:\n # format: \"T{>l:x:>l:y:}\"\n class BEPoint(ctypes.BigEndianStructure):\n _fields_ = [(\"x\", ctypes.c_long), (\"y\", ctypes.c_long)]\n point = BEPoint(100, 200)\n a = memoryview(point)\n self.assertEqual(a.tobytes(), bytes(point))\n\n def test_memoryview_get_contiguous(self):\n # Many implicit tests are already in self.verify().\n\n # no buffer interface\n self.assertRaises(TypeError, get_contiguous, {}, PyBUF_READ, 'F')\n\n # writable request to read-only object\n self.assertRaises(BufferError, get_contiguous, b'x', PyBUF_WRITE, 'C')\n\n # writable request to non-contiguous object\n nd = ndarray([1, 2, 3], shape=[2], strides=[2])\n self.assertRaises(BufferError, get_contiguous, nd, PyBUF_WRITE, 'A')\n\n # scalar, read-only request from read-only exporter\n nd = ndarray(9, shape=(), format=\"L\")\n for order in ['C', 'F', 'A']:\n m = get_contiguous(nd, PyBUF_READ, order)\n self.assertEqual(m, nd)\n self.assertEqual(m[()], 9)\n\n # scalar, read-only request from writable exporter\n nd = ndarray(9, shape=(), format=\"L\", flags=ND_WRITABLE)\n for order in ['C', 'F', 'A']:\n m = get_contiguous(nd, PyBUF_READ, order)\n self.assertEqual(m, nd)\n self.assertEqual(m[()], 9)\n\n # scalar, writable request\n for order in ['C', 'F', 'A']:\n nd[()] = 9\n m = get_contiguous(nd, PyBUF_WRITE, order)\n self.assertEqual(m, nd)\n self.assertEqual(m[()], 9)\n\n m[()] = 10\n self.assertEqual(m[()], 10)\n self.assertEqual(nd[()], 10)\n\n # zeros in shape\n nd = ndarray([1], shape=[0], format=\"L\", flags=ND_WRITABLE)\n for order in ['C', 'F', 'A']:\n m = get_contiguous(nd, PyBUF_READ, order)\n self.assertRaises(IndexError, m.__getitem__, 0)\n self.assertEqual(m, nd)\n self.assertEqual(m.tolist(), [])\n\n nd = ndarray(list(range(8)), shape=[2, 0, 7], format=\"L\",\n flags=ND_WRITABLE)\n for order in ['C', 'F', 'A']:\n m = get_contiguous(nd, PyBUF_READ, order)\n self.assertEqual(ndarray(m).tolist(), [[], []])\n\n # one-dimensional\n nd = ndarray([1], shape=[1], format=\"h\", flags=ND_WRITABLE)\n for order in ['C', 'F', 'A']:\n m = get_contiguous(nd, PyBUF_WRITE, order)\n self.assertEqual(m, nd)\n self.assertEqual(m.tolist(), nd.tolist())\n\n nd = ndarray([1, 2, 3], shape=[3], format=\"b\", flags=ND_WRITABLE)\n for order in ['C', 'F', 'A']:\n m = get_contiguous(nd, PyBUF_WRITE, order)\n self.assertEqual(m, nd)\n self.assertEqual(m.tolist(), nd.tolist())\n\n # one-dimensional, non-contiguous\n nd = ndarray([1, 2, 3], shape=[2], strides=[2], flags=ND_WRITABLE)\n for order in ['C', 'F', 'A']:\n m = get_contiguous(nd, PyBUF_READ, order)\n self.assertEqual(m, nd)\n self.assertEqual(m.tolist(), nd.tolist())\n self.assertRaises(TypeError, m.__setitem__, 1, 20)\n self.assertEqual(m[1], 3)\n self.assertEqual(nd[1], 3)\n\n nd = nd[::-1]\n for order in ['C', 'F', 'A']:\n m = get_contiguous(nd, PyBUF_READ, order)\n self.assertEqual(m, nd)\n self.assertEqual(m.tolist(), nd.tolist())\n self.assertRaises(TypeError, m.__setitem__, 1, 20)\n self.assertEqual(m[1], 1)\n self.assertEqual(nd[1], 1)\n\n # multi-dimensional, contiguous input\n nd = ndarray(list(range(12)), shape=[3, 4], flags=ND_WRITABLE)\n for order in ['C', 'A']:\n m = get_contiguous(nd, PyBUF_WRITE, order)\n self.assertEqual(ndarray(m).tolist(), nd.tolist())\n\n self.assertRaises(BufferError, get_contiguous, nd, PyBUF_WRITE, 'F')\n m = get_contiguous(nd, PyBUF_READ, order)\n self.assertEqual(ndarray(m).tolist(), nd.tolist())\n\n nd = ndarray(list(range(12)), shape=[3, 4],\n flags=ND_WRITABLE|ND_FORTRAN)\n for order in ['F', 'A']:\n m = get_contiguous(nd, PyBUF_WRITE, order)\n self.assertEqual(ndarray(m).tolist(), nd.tolist())\n\n self.assertRaises(BufferError, get_contiguous, nd, PyBUF_WRITE, 'C')\n m = get_contiguous(nd, PyBUF_READ, order)\n self.assertEqual(ndarray(m).tolist(), nd.tolist())\n\n # multi-dimensional, non-contiguous input\n nd = ndarray(list(range(12)), shape=[3, 4], flags=ND_WRITABLE|ND_PIL)\n for order in ['C', 'F', 'A']:\n self.assertRaises(BufferError, get_contiguous, nd, PyBUF_WRITE,\n order)\n m = get_contiguous(nd, PyBUF_READ, order)\n self.assertEqual(ndarray(m).tolist(), nd.tolist())\n\n # flags\n nd = ndarray([1,2,3,4,5], shape=[3], strides=[2])\n m = get_contiguous(nd, PyBUF_READ, 'C')\n self.assertTrue(m.c_contiguous)\n\n def test_memoryview_serializing(self):\n\n # C-contiguous\n size = struct.calcsize('i')\n a = array.array('i', [1,2,3,4,5])\n m = memoryview(a)\n buf = io.BytesIO(m)\n b = bytearray(5*size)\n buf.readinto(b)\n self.assertEqual(m.tobytes(), b)\n\n # C-contiguous, multi-dimensional\n size = struct.calcsize('L')\n nd = ndarray(list(range(12)), shape=[2,3,2], format=\"L\")\n m = memoryview(nd)\n buf = io.BytesIO(m)\n b = bytearray(2*3*2*size)\n buf.readinto(b)\n self.assertEqual(m.tobytes(), b)\n\n # Fortran contiguous, multi-dimensional\n #size = struct.calcsize('L')\n #nd = ndarray(list(range(12)), shape=[2,3,2], format=\"L\",\n # flags=ND_FORTRAN)\n #m = memoryview(nd)\n #buf = io.BytesIO(m)\n #b = bytearray(2*3*2*size)\n #buf.readinto(b)\n #self.assertEqual(m.tobytes(), b)\n\n def test_memoryview_hash(self):\n\n # bytes exporter\n b = bytes(list(range(12)))\n m = memoryview(b)\n self.assertEqual(hash(b), hash(m))\n\n # C-contiguous\n mc = m.cast('c', shape=[3,4])\n self.assertEqual(hash(mc), hash(b))\n\n # non-contiguous\n mx = m[::-2]\n b = bytes(list(range(12))[::-2])\n self.assertEqual(hash(mx), hash(b))\n\n # Fortran contiguous\n nd = ndarray(list(range(30)), shape=[3,2,5], flags=ND_FORTRAN)\n m = memoryview(nd)\n self.assertEqual(hash(m), hash(nd))\n\n # multi-dimensional slice\n nd = ndarray(list(range(30)), shape=[3,2,5])\n x = nd[::2, ::, ::-1]\n m = memoryview(x)\n self.assertEqual(hash(m), hash(x))\n\n # multi-dimensional slice with suboffsets\n nd = ndarray(list(range(30)), shape=[2,5,3], flags=ND_PIL)\n x = nd[::2, ::, ::-1]\n m = memoryview(x)\n self.assertEqual(hash(m), hash(x))\n\n # equality-hash invariant\n x = ndarray(list(range(12)), shape=[12], format='B')\n a = memoryview(x)\n\n y = ndarray(list(range(12)), shape=[12], format='b')\n b = memoryview(y)\n\n self.assertEqual(a, b)\n self.assertEqual(hash(a), hash(b))\n\n # non-byte formats\n nd = ndarray(list(range(12)), shape=[2,2,3], format='L')\n m = memoryview(nd)\n self.assertRaises(ValueError, m.__hash__)\n\n nd = ndarray(list(range(-6, 6)), shape=[2,2,3], format='h')\n m = memoryview(nd)\n self.assertRaises(ValueError, m.__hash__)\n\n nd = ndarray(list(range(12)), shape=[2,2,3], format='= L')\n m = memoryview(nd)\n self.assertRaises(ValueError, m.__hash__)\n\n nd = ndarray(list(range(-6, 6)), shape=[2,2,3], format='< h')\n m = memoryview(nd)\n self.assertRaises(ValueError, m.__hash__)\n\n def test_memoryview_release(self):\n\n # Create re-exporter from getbuffer(memoryview), then release the view.\n a = bytearray([1,2,3])\n m = memoryview(a)\n nd = ndarray(m) # re-exporter\n self.assertRaises(BufferError, m.release)\n del nd\n m.release()\n\n a = bytearray([1,2,3])\n m = memoryview(a)\n nd1 = ndarray(m, getbuf=PyBUF_FULL_RO, flags=ND_REDIRECT)\n nd2 = ndarray(nd1, getbuf=PyBUF_FULL_RO, flags=ND_REDIRECT)\n self.assertIs(nd2.obj, m)\n self.assertRaises(BufferError, m.release)\n del nd1, nd2\n m.release()\n\n # chained views\n a = bytearray([1,2,3])\n m1 = memoryview(a)\n m2 = memoryview(m1)\n nd = ndarray(m2) # re-exporter\n m1.release()\n self.assertRaises(BufferError, m2.release)\n del nd\n m2.release()\n\n a = bytearray([1,2,3])\n m1 = memoryview(a)\n m2 = memoryview(m1)\n nd1 = ndarray(m2, getbuf=PyBUF_FULL_RO, flags=ND_REDIRECT)\n nd2 = ndarray(nd1, getbuf=PyBUF_FULL_RO, flags=ND_REDIRECT)\n self.assertIs(nd2.obj, m2)\n m1.release()\n self.assertRaises(BufferError, m2.release)\n del nd1, nd2\n m2.release()\n\n # Allow changing layout while buffers are exported.\n nd = ndarray([1,2,3], shape=[3], flags=ND_VAREXPORT)\n m1 = memoryview(nd)\n\n nd.push([4,5,6,7,8], shape=[5]) # mutate nd\n m2 = memoryview(nd)\n\n x = memoryview(m1)\n self.assertEqual(x.tolist(), m1.tolist())\n\n y = memoryview(m2)\n self.assertEqual(y.tolist(), m2.tolist())\n self.assertEqual(y.tolist(), nd.tolist())\n m2.release()\n y.release()\n\n nd.pop() # pop the current view\n self.assertEqual(x.tolist(), nd.tolist())\n\n del nd\n m1.release()\n x.release()\n\n # If multiple memoryviews share the same managed buffer, implicit\n # release() in the context manager's __exit__() method should still\n # work.\n def catch22(b):\n with memoryview(b) as m2:\n pass\n\n x = bytearray(b'123')\n with memoryview(x) as m1:\n catch22(m1)\n self.assertEqual(m1[0], ord(b'1'))\n\n x = ndarray(list(range(12)), shape=[2,2,3], format='l')\n y = ndarray(x, getbuf=PyBUF_FULL_RO, flags=ND_REDIRECT)\n z = ndarray(y, getbuf=PyBUF_FULL_RO, flags=ND_REDIRECT)\n self.assertIs(z.obj, x)\n with memoryview(z) as m:\n catch22(m)\n self.assertEqual(m[0:1].tolist(), [[[0, 1, 2], [3, 4, 5]]])\n\n # Test garbage collection.\n for flags in (0, ND_REDIRECT):\n x = bytearray(b'123')\n with memoryview(x) as m1:\n del x\n y = ndarray(m1, getbuf=PyBUF_FULL_RO, flags=flags)\n with memoryview(y) as m2:\n del y\n z = ndarray(m2, getbuf=PyBUF_FULL_RO, flags=flags)\n with memoryview(z) as m3:\n del z\n catch22(m3)\n catch22(m2)\n catch22(m1)\n self.assertEqual(m1[0], ord(b'1'))\n self.assertEqual(m2[1], ord(b'2'))\n self.assertEqual(m3[2], ord(b'3'))\n del m3\n del m2\n del m1\n\n x = bytearray(b'123')\n with memoryview(x) as m1:\n del x\n y = ndarray(m1, getbuf=PyBUF_FULL_RO, flags=flags)\n with memoryview(y) as m2:\n del y\n z = ndarray(m2, getbuf=PyBUF_FULL_RO, flags=flags)\n with memoryview(z) as m3:\n del z\n catch22(m1)\n catch22(m2)\n catch22(m3)\n self.assertEqual(m1[0], ord(b'1'))\n self.assertEqual(m2[1], ord(b'2'))\n self.assertEqual(m3[2], ord(b'3'))\n del m1, m2, m3\n\n # memoryview.release() fails if the view has exported buffers.\n x = bytearray(b'123')\n with self.assertRaises(BufferError):\n with memoryview(x) as m:\n ex = ndarray(m)\n m[0] == ord(b'1')\n\n def test_memoryview_redirect(self):\n\n nd = ndarray([1.0 * x for x in range(12)], shape=[12], format='d')\n a = array.array('d', [1.0 * x for x in range(12)])\n\n for x in (nd, a):\n y = ndarray(x, getbuf=PyBUF_FULL_RO, flags=ND_REDIRECT)\n z = ndarray(y, getbuf=PyBUF_FULL_RO, flags=ND_REDIRECT)\n m = memoryview(z)\n\n self.assertIs(y.obj, x)\n self.assertIs(z.obj, x)\n self.assertIs(m.obj, x)\n\n self.assertEqual(m, x)\n self.assertEqual(m, y)\n self.assertEqual(m, z)\n\n self.assertEqual(m[1:3], x[1:3])\n self.assertEqual(m[1:3], y[1:3])\n self.assertEqual(m[1:3], z[1:3])\n del y, z\n self.assertEqual(m[1:3], x[1:3])\n\n def test_memoryview_from_static_exporter(self):\n\n fmt = 'B'\n lst = [0,1,2,3,4,5,6,7,8,9,10,11]\n\n # exceptions\n self.assertRaises(TypeError, staticarray, 1, 2, 3)\n\n # view.obj==x\n x = staticarray()\n y = memoryview(x)\n self.verify(y, obj=x,\n itemsize=1, fmt=fmt, readonly=1,\n ndim=1, shape=[12], strides=[1],\n lst=lst)\n for i in range(12):\n self.assertEqual(y[i], i)\n del x\n del y\n\n x = staticarray()\n y = memoryview(x)\n del y\n del x\n\n x = staticarray()\n y = ndarray(x, getbuf=PyBUF_FULL_RO)\n z = ndarray(y, getbuf=PyBUF_FULL_RO)\n m = memoryview(z)\n self.assertIs(y.obj, x)\n self.assertIs(m.obj, z)\n self.verify(m, obj=z,\n itemsize=1, fmt=fmt, readonly=1,\n ndim=1, shape=[12], strides=[1],\n lst=lst)\n del x, y, z, m\n\n x = staticarray()\n y = ndarray(x, getbuf=PyBUF_FULL_RO, flags=ND_REDIRECT)\n z = ndarray(y, getbuf=PyBUF_FULL_RO, flags=ND_REDIRECT)\n m = memoryview(z)\n self.assertIs(y.obj, x)\n self.assertIs(z.obj, x)\n self.assertIs(m.obj, x)\n self.verify(m, obj=x,\n itemsize=1, fmt=fmt, readonly=1,\n ndim=1, shape=[12], strides=[1],\n lst=lst)\n del x, y, z, m\n\n # view.obj==NULL\n x = staticarray(legacy_mode=True)\n y = memoryview(x)\n self.verify(y, obj=None,\n itemsize=1, fmt=fmt, readonly=1,\n ndim=1, shape=[12], strides=[1],\n lst=lst)\n for i in range(12):\n self.assertEqual(y[i], i)\n del x\n del y\n\n x = staticarray(legacy_mode=True)\n y = memoryview(x)\n del y\n del x\n\n x = staticarray(legacy_mode=True)\n y = ndarray(x, getbuf=PyBUF_FULL_RO)\n z = ndarray(y, getbuf=PyBUF_FULL_RO)\n m = memoryview(z)\n self.assertIs(y.obj, None)\n self.assertIs(m.obj, z)\n self.verify(m, obj=z,\n itemsize=1, fmt=fmt, readonly=1,\n ndim=1, shape=[12], strides=[1],\n lst=lst)\n del x, y, z, m\n\n x = staticarray(legacy_mode=True)\n y = ndarray(x, getbuf=PyBUF_FULL_RO, flags=ND_REDIRECT)\n z = ndarray(y, getbuf=PyBUF_FULL_RO, flags=ND_REDIRECT)\n m = memoryview(z)\n # Clearly setting view.obj==NULL is inferior, since it\n # messes up the redirection chain:\n self.assertIs(y.obj, None)\n self.assertIs(z.obj, y)\n self.assertIs(m.obj, y)\n self.verify(m, obj=y,\n itemsize=1, fmt=fmt, readonly=1,\n ndim=1, shape=[12], strides=[1],\n lst=lst)\n del x, y, z, m\n\n def test_memoryview_getbuffer_undefined(self):\n\n # getbufferproc does not adhere to the new documentation\n nd = ndarray([1,2,3], [3], flags=ND_GETBUF_FAIL|ND_GETBUF_UNDEFINED)\n self.assertRaises(BufferError, memoryview, nd)\n\n def test_issue_7385(self):\n x = ndarray([1,2,3], shape=[3], flags=ND_GETBUF_FAIL)\n self.assertRaises(BufferError, memoryview, x)\n\n\nif __name__ == \"__main__\":\n unittest.main()\n" ]
[ [ "numpy.ndarray" ] ]
leanth/OSUCoursework
[ "ccfbf5f9daa8f6d3818bb5e4cc8df7c5135a5f34" ]
[ "CS534-MachineLearning/hw2/perc-svm-demo/perc.py" ]
[ "import numpy as np\nimport sys\nimport math\n\nprec = 1e-4\nsign = lambda x: -1 if x < -prec else 1 if x > prec else 0\n\ndef perc(data, MIRA=False, aggressive=False, margin=0.5):\n\n weight = np.array([0.,0.,0.]) # must be float!\n avgw = np.array([0.,0.,0.])\n\n supp_vec = set()\n for i in range(10000):\n best_margin = 100000\n error = 0\n tavgw = np.array([0.,0.,0.])\n for j, ((x,y), label) in enumerate(data):\n point = np.array([x,y,1.])\n s = weight.dot(point)\n result = sign(s)\n if result != label or aggressive and math.fabs(s)<margin-prec:\n if MIRA:\n ratio = (label-s) / point.dot(point)\n else:\n ratio = label\n weight += point * ratio\n #print point, weight\n if MIRA:\n assert math.fabs(weight.dot(point)-label)<prec\n error += 1\n supp_vec.add(j) # support vector set\n else:\n m = math.fabs(s) / np.linalg.norm(weight)\n if m < best_margin:\n best_margin = m\n avgw += weight\n if error == 0:\n break\n else:\n #pass\n print(i, error, weight)\n #avgw += weight\n\n return i+1, weight, avgw, len(supp_vec), best_margin\n" ]
[ [ "numpy.array", "numpy.linalg.norm" ] ]
angusll/kaggle_greatbarrierreef
[ "cf1065833a8009be765f8d5d3f81a0c39485f312" ]
[ "csl_yolo/callbacks.py" ]
[ "import tensorflow as tf\r\nimport os\r\nimport math\r\n\r\nclass LearningRateReducer(tf.keras.callbacks.Callback):\r\n def __init__(self,lr_tune_dict={}):\r\n super(LearningRateReducer,self).__init__()\r\n self._lr_tune_dict=lr_tune_dict\r\n def on_epoch_end(self,epoch,logs={}):\r\n lr_tune=self._lr_tune_dict.get(epoch,False)\r\n if(lr_tune!=False):\r\n self.model.optimizer.lr.assign(lr_tune)\r\n return \r\n\r\nclass Stabilizer(tf.keras.callbacks.Callback):\r\n def __init__(self,security_boundary=0.1):\r\n super(Stabilizer,self).__init__()\r\n self._security_boundary=1+security_boundary\r\n self._last_loss=None\r\n def on_train_begin(self,logs={}):\r\n if(os.path.isfile(\"stabilizer.hdf5\")==True):\r\n os.remove(\"stabilizer.hdf5\")\r\n self.model.save_weights(\"stabilizer.hdf5\")\r\n def on_train_end(self,logs={}):\r\n os.remove(\"stabilizer.hdf5\")\r\n def on_epoch_end(self,epoch,logs={}):\r\n loss=logs.get('loss')\r\n if(math.isnan(loss)==True):\r\n for var in self.model.optimizer.variables():\r\n var.assign(tf.zeros_like(var))\r\n self.model.load_weights(\"stabilizer.hdf5\")\r\n elif(self._last_loss==None or loss<self._last_loss*self._security_boundary):\r\n self.model.save_weights(\"stabilizer.hdf5\")\r\n self._last_loss=loss\r\n\r\nclass WeightsSaver(tf.keras.callbacks.Callback):\r\n def __init__(self,save_path):\r\n super(WeightsSaver,self).__init__()\r\n self._save_path=save_path\r\n def on_epoch_begin(self,epoch,logs={}):\r\n self.model.save_weights(self._save_path)\r\n return \r\n \r\nclass BestWeightsSaver(tf.keras.callbacks.Callback):\r\n def __init__(self,save_path,eval_function,eval_parms=None,init_metric=0.0):\r\n super(BestWeightsSaver,self).__init__()\r\n self._save_path=save_path\r\n self._eval_function=eval_function\r\n self._eval_parms=eval_parms\r\n self._cur_metric=init_metric\r\n def on_epoch_begin(self,epoch,logs={}):\r\n if(self._eval_parms==None or self._eval_parms==[]):\r\n metric=self._eval_function(self.model)\r\n else:\r\n metric=self._eval_function(self.model,*self._eval_parms)\r\n if(metric<self._cur_metric):return\r\n if(metric>self._cur_metric):\r\n self._cur_metric=metric\r\n self.model.save_weights(self._save_path)\r\n return " ]
[ [ "tensorflow.zeros_like" ] ]
mikedwhite/microstructural-fingerprinting-tools
[ "969ac9d032f82ca002846ac39017b7de04f50e85" ]
[ "mftools/assess/classify.py" ]
[ "import graphlearning as gl\nimport numpy as np\nfrom sklearn.cluster import KMeans, SpectralClustering\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.neighbors import NearestNeighbors\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.svm import SVC\n\n\ndef train_svm(xtrain, xtest, ytrain, ytest, kernel='linear'):\n r\"\"\"Train support vector machine (SVM) on training data, validate on test data and compute accuracy score for the\n validation.\n\n Parameters\n ----------\n xtrain : ndarray\n Array of fingerprints with shape :math:`(n_{\\text{train}}, d)`, where :math:`n_{\\text{train}}` is the number of\n fingerprints within the training set and :math:`d` is the length of each fingerprint.\n xtest : ndarray\n Array of fingerprints with shape :math:`(n_{\\text{test}}, d)`, where :math:`n_{\\text{test}}` is the number of\n fingerprints within the test set and :math:`d` is the length of each fingerprint.\n ytrain : ndarray\n List of labels corresponding to xtrain, with shape :math:`(n_{\\text{train}}, )`.\n ytest : ndarray\n List of labels corresponding to xtest, with shape :math:`(n_{\\text{test}}, )`.\n kernel : str, optional\n Type of kernel to use for training. Can be 'linear' (default) or some other suitable kernel (see\n sklearn.svm.SVC).\n\n Returns\n -------\n accuracy : float\n Accuracy score when validating SVM on test data. Has range [0, 1].\n \"\"\"\n\n print('Training SVM')\n svm = SVC(kernel=kernel, C=1.0, gamma='auto').fit(xtrain, ytrain)\n ypred = svm.predict(xtest)\n accuracy = accuracy_score(ytest, ypred)\n\n return accuracy\n\n\ndef train_rf(xtrain, xtest, ytrain, ytest):\n r\"\"\"Train random forest on training data, validate on test data and compute accuracy score for the validation.\n\n Parameters\n ----------\n xtrain : ndarray\n Array of fingerprints with shape :math:`(n_{\\text{train}}, d)`, where :math:`n_{\\text{train}}` is the number of\n fingerprints within the training set and :math:`d` is the length of each fingerprint.\n xtest : ndarray\n Array of fingerprints with shape :math:`(n_{\\text{test}}, d)`, where :math:`n_{\\text{test}}` is the number of\n fingerprints within the test set and :math:`d` is the length of each fingerprint.\n ytrain : ndarray\n List of labels corresponding to xtrain, with shape :math:`(n_{\\text{train}}, )`.\n ytest : ndarray\n List of labels corresponding to xtest, with shape :math:`(n_{\\text{test}}, )`.\n\n Returns\n -------\n accuracy : float\n Accuracy score when validating random forest on test data. Has range [0, 1].\n \"\"\"\n\n print('Training Random Forest')\n clf = RandomForestClassifier(n_estimators=10000, max_depth=10).fit(xtrain, ytrain)\n ypred = clf.predict(xtest)\n accuracy = accuracy_score(ytest, ypred)\n\n return accuracy\n\n\ndef train_ul(xtrain, xtest, ytest, nclass, method='kmeans'):\n r\"\"\"Perform unsupervised learning (UL) on training data and compute accuracy score. Supports k-means and spectral\n clustering via the `method` parameter.\n\n Parameters\n ----------\n xtrain : ndarray\n Array of fingerprints with shape :math:`(n_{\\text{train}}, d)`, where :math:`n_{\\text{train}}` is the number of\n fingerprints within the training set and :math:`d` is the length of each fingerprint.\n xtest : ndarray\n Array of fingerprints with shape :math:`(n_{\\text{test}}, d)`, where :math:`n_{\\text{test}}` is the number of\n fingerprints within the test set and :math:`d` is the length of each fingerprint.\n ytest : ndarray\n List of labels corresponding to xtest, with shape :math:`(n_{\\text{test}}, )`.\n nclass : int\n Number of classes to split data into.\n method : str, optional\n 'kmeans' (deafult)\n :math:`k`-means clustering.\n 'spectral'\n Spectral clustering.\n\n Returns\n -------\n accuracy : float\n Accuracy score when validating UL on test data. Has range [0, 1].\n \"\"\"\n\n print('Training unsupervised')\n scaler = StandardScaler()\n ytest = np.array(ytest)\n if method == 'kmeans':\n kmeans = KMeans(n_clusters=nclass)\n kmeans.fit(scaler.fit_transform(xtest))\n ytrain_pred = kmeans.predict(scaler.fit_transform(xtrain))\n ytest_pred = kmeans.predict(scaler.fit_transform(xtest))\n elif method == 'spectral':\n kmeans = SpectralClustering(n_clusters=nclass, random_state=0, affinity='nearest_neighbors')\n ytrain_pred = kmeans.fit_predict(scaler.fit_transform(xtrain))\n ytest_pred = kmeans.fit_predict(scaler.fit_transform(xtest))\n else:\n print('method must be set as either `kmeans` or `spectral`.')\n return 1\n\n lab_truth = np.array(range(nclass))\n lab_map = np.array(([0, 1, 2],\n [0, 2, 1],\n [1, 0, 2],\n [1, 2, 0],\n [2, 0, 1],\n [2, 1, 0]))\n\n accuracy_list = np.zeros(lab_map.shape[0])\n for m in range(lab_map.shape[0]):\n ytrain_pred_mapped = np.zeros(ytrain_pred.shape[0])\n for n in range(lab_truth.shape[0]):\n args = np.argwhere(ytrain_pred == n)\n ytrain_pred_mapped[args] = lab_map[m, n]\n\n ytest_pred_mapped = np.zeros(ytest_pred.shape[0])\n for n in range(lab_truth.shape[0]):\n args = np.argwhere(ytest_pred == n)\n ytest_pred_mapped[args] = lab_map[m, n]\n\n accuracy_list[m] = accuracy_score(ytest, ytest_pred_mapped)\n\n accuracy = np.max(accuracy_list)\n\n return accuracy\n\n\ndef train_ssl(xtrain, xtest, ytrain, ytest, frac_data):\n r\"\"\"Propagate labels via semi-supervised learning (SSL) and compute accuracy score.\n\n Parameters\n ----------\n xtrain : ndarray\n Array of fingerprints with shape :math:`(n_{\\text{train}}, d)`, where :math:`n_{\\text{train}}` is the number of\n fingerprints within the training set and :math:`d` is the length of each fingerprint.\n xtest : ndarray\n Array of fingerprints with shape :math:`(n_{\\text{test}}, d)`, where :math:`n_{\\text{test}}` is the number of\n fingerprints within the test set and :math:`d` is the length of each fingerprint.\n ytrain : ndarray\n List of labels corresponding to xtrain, with shape :math:`(n_{\\text{train}}, )`.\n ytest : ndarray\n List of labels corresponding to xtest, with shape :math:`(n_{\\text{test}}, )`.\n frac_data : float\n Fraction of ytrain used to initialise label propagation. Must have range (0, 1).\n\n Returns\n -------\n acc_laplace : float\n Accuracy score when validating SSL on test data via laplace learning. Has range [0, 1].\n acc_poisson : float\n Accuracy score when validating SSL on test data via poisson learning. Has range [0, 1].\n \"\"\"\n\n print('Training semi-supervised')\n ytrain = np.array(ytrain)\n ytest = np.array(ytest)\n scaler = StandardScaler()\n xtrain = scaler.fit_transform(xtrain)\n xtest = scaler.fit_transform(xtest)\n idx = np.random.permutation(ytrain.size)\n num_ind = np.int64(frac_data * idx.size)\n idx_train = np.asarray(range(num_ind), dtype=int)\n xdata = np.concatenate((xtrain[idx[0: num_ind], :], xtrain[idx[num_ind:], :], xtest), axis=0)\n ydata = np.concatenate((ytrain[idx[0: num_ind]], ytrain[idx[num_ind:]], ytest))\n\n neigh = NearestNeighbors(n_neighbors=10)\n neigh.fit(xdata)\n W = neigh.kneighbors_graph(xdata).toarray()\n\n labels_laplace = gl.graph_ssl(W, idx_train, ydata[0: num_ind], algorithm='laplace')\n labels_poisson = gl.graph_ssl(W, idx_train, ydata[0: num_ind], algorithm='poisson')\n\n acc_laplace = accuracy_score(ydata[num_ind:], labels_laplace[num_ind:])\n acc_poisson = accuracy_score(ydata[num_ind:], labels_poisson[num_ind:])\n\n return acc_laplace, acc_poisson" ]
[ [ "sklearn.cluster.KMeans", "sklearn.ensemble.RandomForestClassifier", "sklearn.cluster.SpectralClustering", "numpy.concatenate", "numpy.max", "numpy.int64", "numpy.random.permutation", "numpy.argwhere", "sklearn.neighbors.NearestNeighbors", "sklearn.svm.SVC", "sklearn.preprocessing.StandardScaler", "numpy.array", "numpy.zeros", "sklearn.metrics.accuracy_score" ] ]
abcp4/coach
[ "ae6593bb33cf0ae3c5a4b3b351560dd6b47cd031" ]
[ "rl_coach/architectures/tensorflow_components/general_network.py" ]
[ "#\n# Copyright (c) 2017 Intel Corporation\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n\nimport copy\nfrom typing import Dict\n\nimport numpy as np\nimport tensorflow as tf\n\nfrom rl_coach.architectures.tensorflow_components.embedders.embedder import InputEmbedderParameters\nfrom rl_coach.architectures.tensorflow_components.architecture import TensorFlowArchitecture\nfrom rl_coach.architectures.tensorflow_components.heads.head import HeadParameters\nfrom rl_coach.architectures.tensorflow_components.middlewares.middleware import MiddlewareParameters\nfrom rl_coach.base_parameters import AgentParameters, EmbeddingMergerType\nfrom rl_coach.core_types import PredictionType\nfrom rl_coach.spaces import SpacesDefinition, PlanarMapsObservationSpace\nfrom rl_coach.utils import get_all_subclasses, dynamic_import_and_instantiate_module_from_params, indent_string\n\n\nclass GeneralTensorFlowNetwork(TensorFlowArchitecture):\n \"\"\"\n A generalized version of all possible networks implemented using tensorflow.\n \"\"\"\n def __init__(self, agent_parameters: AgentParameters, spaces: SpacesDefinition, name: str,\n global_network=None, network_is_local: bool=True, network_is_trainable: bool=False):\n \"\"\"\n :param agent_parameters: the agent parameters\n :param spaces: the spaces definition of the agent\n :param name: the name of the network\n :param global_network: the global network replica that is shared between all the workers\n :param network_is_local: is the network global (shared between workers) or local (dedicated to the worker)\n :param network_is_trainable: is the network trainable (we can apply gradients on it)\n \"\"\"\n self.global_network = global_network\n self.network_is_local = network_is_local\n self.network_wrapper_name = name.split('/')[0]\n self.network_parameters = agent_parameters.network_wrappers[self.network_wrapper_name]\n self.num_heads_per_network = 1 if self.network_parameters.use_separate_networks_per_head else \\\n len(self.network_parameters.heads_parameters)\n self.num_networks = 1 if not self.network_parameters.use_separate_networks_per_head else \\\n len(self.network_parameters.heads_parameters)\n\n self.gradients_from_head_rescalers = []\n self.gradients_from_head_rescalers_placeholders = []\n self.update_head_rescaler_value_ops = []\n\n self.adaptive_learning_rate_scheme = None\n self.current_learning_rate = None\n\n # init network modules containers\n self.input_embedders = []\n self.output_heads = []\n super().__init__(agent_parameters, spaces, name, global_network,\n network_is_local, network_is_trainable)\n\n def fill_return_types():\n ret_dict = {}\n for cls in get_all_subclasses(PredictionType):\n ret_dict[cls] = []\n components = self.input_embedders + [self.middleware] + self.output_heads\n for component in components:\n if not hasattr(component, 'return_type'):\n raise ValueError(\"{} has no return_type attribute. This should not happen.\")\n if component.return_type is not None:\n ret_dict[component.return_type].append(component)\n\n return ret_dict\n\n self.available_return_types = fill_return_types()\n self.is_training = None\n\n def predict_with_prediction_type(self, states: Dict[str, np.ndarray],\n prediction_type: PredictionType) -> Dict[str, np.ndarray]:\n \"\"\"\n Search for a component[s] which has a return_type set to the to the requested PredictionType, and get\n predictions for it.\n\n :param states: The input states to the network.\n :param prediction_type: The requested PredictionType to look for in the network components\n :return: A dictionary with predictions for all components matching the requested prediction type\n \"\"\"\n\n ret_dict = {}\n for component in self.available_return_types[prediction_type]:\n ret_dict[component] = self.predict(inputs=states, outputs=component.output)\n\n return ret_dict\n\n @staticmethod\n def get_activation_function(activation_function_string: str):\n \"\"\"\n Map the activation function from a string to the tensorflow framework equivalent\n :param activation_function_string: the type of the activation function\n :return: the tensorflow activation function\n \"\"\"\n activation_functions = {\n 'relu': tf.nn.relu,\n 'tanh': tf.nn.tanh,\n 'sigmoid': tf.nn.sigmoid,\n 'elu': tf.nn.elu,\n 'selu': tf.nn.selu,\n 'leaky_relu': tf.nn.leaky_relu,\n 'none': None\n }\n assert activation_function_string in activation_functions.keys(), \\\n \"Activation function must be one of the following {}. instead it was: {}\"\\\n .format(activation_functions.keys(), activation_function_string)\n return activation_functions[activation_function_string]\n\n def get_input_embedder(self, input_name: str, embedder_params: InputEmbedderParameters):\n \"\"\"\n Given an input embedder parameters class, creates the input embedder and returns it\n :param input_name: the name of the input to the embedder (used for retrieving the shape). The input should\n be a value within the state or the action.\n :param embedder_params: the parameters of the class of the embedder\n :return: the embedder instance\n \"\"\"\n allowed_inputs = copy.copy(self.spaces.state.sub_spaces)\n allowed_inputs[\"action\"] = copy.copy(self.spaces.action)\n allowed_inputs[\"goal\"] = copy.copy(self.spaces.goal)\n\n if input_name not in allowed_inputs.keys():\n raise ValueError(\"The key for the input embedder ({}) must match one of the following keys: {}\"\n .format(input_name, allowed_inputs.keys()))\n\n type = \"vector\"\n if isinstance(allowed_inputs[input_name], PlanarMapsObservationSpace):\n type = \"image\"\n\n embedder_path = 'rl_coach.architectures.tensorflow_components.embedders.' + embedder_params.path[type]\n embedder_params_copy = copy.copy(embedder_params)\n embedder_params_copy.activation_function = self.get_activation_function(embedder_params.activation_function)\n embedder_params_copy.input_rescaling = embedder_params_copy.input_rescaling[type]\n embedder_params_copy.input_offset = embedder_params_copy.input_offset[type]\n embedder_params_copy.name = input_name\n module = dynamic_import_and_instantiate_module_from_params(embedder_params_copy,\n path=embedder_path,\n positional_args=[allowed_inputs[input_name].shape])\n return module\n\n def get_middleware(self, middleware_params: MiddlewareParameters):\n \"\"\"\n Given a middleware type, creates the middleware and returns it\n :param middleware_params: the paramaeters of the middleware class\n :return: the middleware instance\n \"\"\"\n middleware_params_copy = copy.copy(middleware_params)\n middleware_params_copy.activation_function = self.get_activation_function(middleware_params.activation_function)\n module = dynamic_import_and_instantiate_module_from_params(middleware_params_copy)\n return module\n\n def get_output_head(self, head_params: HeadParameters, head_idx: int):\n \"\"\"\n Given a head type, creates the head and returns it\n :param head_params: the parameters of the head to create\n :param head_type: the path to the class of the head under the embedders directory or a full path to a head class.\n the path should be in the following structure: <module_path>:<class_path>\n :param head_idx: the head index\n :param loss_weight: the weight to assign for the embedders loss\n :return: the head\n \"\"\"\n\n head_params_copy = copy.copy(head_params)\n head_params_copy.activation_function = self.get_activation_function(head_params_copy.activation_function)\n return dynamic_import_and_instantiate_module_from_params(head_params_copy, extra_kwargs={\n 'agent_parameters': self.ap, 'spaces': self.spaces, 'network_name': self.network_wrapper_name,\n 'head_idx': head_idx, 'is_local': self.network_is_local})\n\n def get_model(self):\n # validate the configuration\n if len(self.network_parameters.input_embedders_parameters) == 0:\n raise ValueError(\"At least one input type should be defined\")\n\n if len(self.network_parameters.heads_parameters) == 0:\n raise ValueError(\"At least one output type should be defined\")\n\n if self.network_parameters.middleware_parameters is None:\n raise ValueError(\"Exactly one middleware type should be defined\")\n\n # ops for defining the training / testing phase\n self.is_training = tf.Variable(False, trainable=False, collections=[tf.GraphKeys.LOCAL_VARIABLES])\n self.is_training_placeholder = tf.placeholder(\"bool\")\n self.assign_is_training = tf.assign(self.is_training, self.is_training_placeholder)\n\n for network_idx in range(self.num_networks):\n with tf.variable_scope('network_{}'.format(network_idx)):\n\n ####################\n # Input Embeddings #\n ####################\n\n state_embedding = []\n for input_name in sorted(self.network_parameters.input_embedders_parameters):\n input_type = self.network_parameters.input_embedders_parameters[input_name]\n # get the class of the input embedder\n input_embedder = self.get_input_embedder(input_name, input_type)\n self.input_embedders.append(input_embedder)\n\n # input placeholders are reused between networks. on the first network, store the placeholders\n # generated by the input_embedders in self.inputs. on the rest of the networks, pass\n # the existing input_placeholders into the input_embedders.\n if network_idx == 0:\n input_placeholder, embedding = input_embedder()\n self.inputs[input_name] = input_placeholder\n else:\n input_placeholder, embedding = input_embedder(self.inputs[input_name])\n\n state_embedding.append(embedding)\n\n ##########\n # Merger #\n ##########\n\n if len(state_embedding) == 1:\n state_embedding = state_embedding[0]\n else:\n if self.network_parameters.embedding_merger_type == EmbeddingMergerType.Concat:\n state_embedding = tf.concat(state_embedding, axis=-1, name=\"merger\")\n elif self.network_parameters.embedding_merger_type == EmbeddingMergerType.Sum:\n state_embedding = tf.add_n(state_embedding, name=\"merger\")\n\n ##############\n # Middleware #\n ##############\n\n self.middleware = self.get_middleware(self.network_parameters.middleware_parameters)\n _, self.state_embedding = self.middleware(state_embedding)\n\n ################\n # Output Heads #\n ################\n\n head_count = 0\n for head_idx in range(self.num_heads_per_network):\n\n if self.network_parameters.use_separate_networks_per_head:\n # if we use separate networks per head, then the head type corresponds to the network idx\n head_type_idx = network_idx\n head_count = network_idx\n else:\n # if we use a single network with multiple embedders, then the head type is the current head idx\n head_type_idx = head_idx\n head_params = self.network_parameters.heads_parameters[head_type_idx]\n\n for head_copy_idx in range(head_params.num_output_head_copies):\n # create output head and add it to the output heads list\n self.output_heads.append(\n self.get_output_head(head_params,\n head_idx*head_params.num_output_head_copies + head_copy_idx)\n )\n\n # rescale the gradients from the head\n self.gradients_from_head_rescalers.append(\n tf.get_variable('gradients_from_head_{}-{}_rescalers'.format(head_idx, head_copy_idx),\n initializer=float(head_params.rescale_gradient_from_head_by_factor),\n dtype=tf.float32))\n\n self.gradients_from_head_rescalers_placeholders.append(\n tf.placeholder('float',\n name='gradients_from_head_{}-{}_rescalers'.format(head_type_idx, head_copy_idx)))\n\n self.update_head_rescaler_value_ops.append(self.gradients_from_head_rescalers[head_count].assign(\n self.gradients_from_head_rescalers_placeholders[head_count]))\n\n head_input = (1-self.gradients_from_head_rescalers[head_count]) * tf.stop_gradient(self.state_embedding) + \\\n self.gradients_from_head_rescalers[head_count] * self.state_embedding\n\n # build the head\n if self.network_is_local:\n output, target_placeholder, input_placeholders, importance_weight_ph = \\\n self.output_heads[-1](head_input)\n\n self.targets.extend(target_placeholder)\n self.importance_weights.extend(importance_weight_ph)\n else:\n output, input_placeholders = self.output_heads[-1](head_input)\n\n self.outputs.extend(output)\n # TODO: use head names as well\n for placeholder_index, input_placeholder in enumerate(input_placeholders):\n self.inputs['output_{}_{}'.format(head_type_idx, placeholder_index)] = input_placeholder\n\n head_count += 1\n\n # Losses\n self.losses = tf.losses.get_losses(self.full_name)\n self.losses += tf.losses.get_regularization_losses(self.full_name)\n self.total_loss = tf.losses.compute_weighted_loss(self.losses, scope=self.full_name)\n # tf.summary.scalar('total_loss', self.total_loss)\n\n # Learning rate\n if self.network_parameters.learning_rate_decay_rate != 0:\n self.adaptive_learning_rate_scheme = \\\n tf.train.exponential_decay(\n self.network_parameters.learning_rate,\n self.global_step,\n decay_steps=self.network_parameters.learning_rate_decay_steps,\n decay_rate=self.network_parameters.learning_rate_decay_rate,\n staircase=True)\n\n self.current_learning_rate = self.adaptive_learning_rate_scheme\n else:\n self.current_learning_rate = self.network_parameters.learning_rate\n\n # Optimizer\n if self.distributed_training and self.network_is_local and self.network_parameters.shared_optimizer:\n # distributed training + is a local network + optimizer shared -> take the global optimizer\n self.optimizer = self.global_network.optimizer\n elif (self.distributed_training and self.network_is_local and not self.network_parameters.shared_optimizer) \\\n or self.network_parameters.shared_optimizer or not self.distributed_training:\n # distributed training + is a global network + optimizer shared\n # OR\n # distributed training + is a local network + optimizer not shared\n # OR\n # non-distributed training\n # -> create an optimizer\n\n if self.network_parameters.optimizer_type == 'Adam':\n self.optimizer = tf.train.AdamOptimizer(learning_rate=self.current_learning_rate,\n beta1=self.network_parameters.adam_optimizer_beta1,\n beta2=self.network_parameters.adam_optimizer_beta2,\n epsilon=self.network_parameters.optimizer_epsilon)\n elif self.network_parameters.optimizer_type == 'RMSProp':\n self.optimizer = tf.train.RMSPropOptimizer(self.current_learning_rate,\n decay=self.network_parameters.rms_prop_optimizer_decay,\n epsilon=self.network_parameters.optimizer_epsilon)\n elif self.network_parameters.optimizer_type == 'LBFGS':\n self.optimizer = tf.contrib.opt.ScipyOptimizerInterface(self.total_loss, method='L-BFGS-B',\n options={'maxiter': 25})\n else:\n raise Exception(\"{} is not a valid optimizer type\".format(self.network_parameters.optimizer_type))\n\n def __str__(self):\n result = []\n\n for network in range(self.num_networks):\n network_structure = []\n\n # embedder\n for embedder in self.input_embedders:\n network_structure.append(\"Input Embedder: {}\".format(embedder.name))\n network_structure.append(indent_string(str(embedder)))\n\n if len(self.input_embedders) > 1:\n network_structure.append(\"{} ({})\".format(self.network_parameters.embedding_merger_type.name,\n \", \".join([\"{} embedding\".format(e.name) for e in self.input_embedders])))\n\n # middleware\n network_structure.append(\"Middleware:\")\n network_structure.append(indent_string(str(self.middleware)))\n\n # head\n if self.network_parameters.use_separate_networks_per_head:\n heads = range(network, network+1)\n else:\n heads = range(0, len(self.output_heads))\n\n for head_idx in heads:\n head = self.output_heads[head_idx]\n head_params = self.network_parameters.heads_parameters[head_idx]\n if head_params.num_output_head_copies > 1:\n network_structure.append(\"Output Head: {} (num copies = {})\".format(head.name, head_params.num_output_head_copies))\n else:\n network_structure.append(\"Output Head: {}\".format(head.name))\n network_structure.append(indent_string(str(head)))\n\n # finalize network\n if self.num_networks > 1:\n result.append(\"Sub-network for head: {}\".format(self.output_heads[network].name))\n result.append(indent_string('\\n'.join(network_structure)))\n else:\n result.append('\\n'.join(network_structure))\n\n result = '\\n'.join(result)\n return result\n" ]
[ [ "tensorflow.losses.get_regularization_losses", "tensorflow.concat", "tensorflow.contrib.opt.ScipyOptimizerInterface", "tensorflow.Variable", "tensorflow.train.RMSPropOptimizer", "tensorflow.losses.get_losses", "tensorflow.assign", "tensorflow.placeholder", "tensorflow.losses.compute_weighted_loss", "tensorflow.train.exponential_decay", "tensorflow.stop_gradient", "tensorflow.train.AdamOptimizer", "tensorflow.add_n" ] ]
bchu/pandas
[ "5a150694731d2ecce670cca65760c472338a04fa" ]
[ "pandas/core/sparse/frame.py" ]
[ "\"\"\"\nData structures for sparse float data. Life is made simpler by dealing only\nwith float64 data\n\"\"\"\nimport warnings\n\nimport numpy as np\n\nfrom pandas._libs.sparse import BlockIndex, get_blocks\nimport pandas.compat as compat\nfrom pandas.compat import lmap\nfrom pandas.compat.numpy import function as nv\nfrom pandas.util._decorators import Appender\n\nfrom pandas.core.dtypes.cast import find_common_type, maybe_upcast\nfrom pandas.core.dtypes.common import ensure_platform_int, is_scipy_sparse\nfrom pandas.core.dtypes.missing import isna, notna\n\nimport pandas.core.algorithms as algos\nfrom pandas.core.arrays.sparse import SparseArray, SparseDtype\nimport pandas.core.common as com\nfrom pandas.core.frame import DataFrame\nimport pandas.core.generic as generic\nfrom pandas.core.index import Index, MultiIndex, ensure_index\nimport pandas.core.indexes.base as ibase\nfrom pandas.core.internals import (\n BlockManager, create_block_manager_from_arrays)\nfrom pandas.core.internals.construction import extract_index, prep_ndarray\nimport pandas.core.ops as ops\nfrom pandas.core.series import Series\nfrom pandas.core.sparse.series import SparseSeries\n\n# pylint: disable=E1101,E1103,W0231,E0202\n\n\n_shared_doc_kwargs = dict(klass='SparseDataFrame')\n\n\nclass SparseDataFrame(DataFrame):\n \"\"\"\n DataFrame containing sparse floating point data in the form of SparseSeries\n objects\n\n Parameters\n ----------\n data : same types as can be passed to DataFrame or scipy.sparse.spmatrix\n .. versionchanged :: 0.23.0\n If data is a dict, argument order is maintained for Python 3.6\n and later.\n\n index : array-like, optional\n column : array-like, optional\n default_kind : {'block', 'integer'}, default 'block'\n Default sparse kind for converting Series to SparseSeries. Will not\n override SparseSeries passed into constructor\n default_fill_value : float\n Default fill_value for converting Series to SparseSeries\n (default: nan). Will not override SparseSeries passed in.\n \"\"\"\n _subtyp = 'sparse_frame'\n\n def __init__(self, data=None, index=None, columns=None, default_kind=None,\n default_fill_value=None, dtype=None, copy=False):\n\n # pick up the defaults from the Sparse structures\n if isinstance(data, SparseDataFrame):\n if index is None:\n index = data.index\n if columns is None:\n columns = data.columns\n if default_fill_value is None:\n default_fill_value = data.default_fill_value\n if default_kind is None:\n default_kind = data.default_kind\n elif isinstance(data, (SparseSeries, SparseArray)):\n if index is None:\n index = data.index\n if default_fill_value is None:\n default_fill_value = data.fill_value\n if columns is None and hasattr(data, 'name'):\n columns = [data.name]\n if columns is None:\n raise Exception(\"cannot pass a series w/o a name or columns\")\n data = {columns[0]: data}\n\n if default_fill_value is None:\n default_fill_value = np.nan\n if default_kind is None:\n default_kind = 'block'\n\n self._default_kind = default_kind\n self._default_fill_value = default_fill_value\n\n if is_scipy_sparse(data):\n mgr = self._init_spmatrix(data, index, columns, dtype=dtype,\n fill_value=default_fill_value)\n elif isinstance(data, dict):\n mgr = self._init_dict(data, index, columns, dtype=dtype)\n elif isinstance(data, (np.ndarray, list)):\n mgr = self._init_matrix(data, index, columns, dtype=dtype)\n elif isinstance(data, SparseDataFrame):\n mgr = self._init_mgr(data._data,\n dict(index=index, columns=columns),\n dtype=dtype, copy=copy)\n elif isinstance(data, DataFrame):\n mgr = self._init_dict(data, data.index, data.columns, dtype=dtype)\n elif isinstance(data, Series):\n mgr = self._init_dict(data.to_frame(), data.index,\n columns=None, dtype=dtype)\n elif isinstance(data, BlockManager):\n mgr = self._init_mgr(data, axes=dict(index=index, columns=columns),\n dtype=dtype, copy=copy)\n elif data is None:\n data = DataFrame()\n\n if index is None:\n index = Index([])\n else:\n index = ensure_index(index)\n\n if columns is None:\n columns = Index([])\n else:\n for c in columns:\n data[c] = SparseArray(self._default_fill_value,\n index=index, kind=self._default_kind,\n fill_value=self._default_fill_value)\n mgr = to_manager(data, columns, index)\n if dtype is not None:\n mgr = mgr.astype(dtype)\n else:\n msg = ('SparseDataFrame called with unknown type \"{data_type}\" '\n 'for data argument')\n raise TypeError(msg.format(data_type=type(data).__name__))\n\n generic.NDFrame.__init__(self, mgr)\n\n @property\n def _constructor(self):\n return SparseDataFrame\n\n _constructor_sliced = SparseSeries\n\n def _init_dict(self, data, index, columns, dtype=None):\n # pre-filter out columns if we passed it\n if columns is not None:\n columns = ensure_index(columns)\n data = {k: v for k, v in compat.iteritems(data) if k in columns}\n else:\n keys = com.dict_keys_to_ordered_list(data)\n columns = Index(keys)\n\n if index is None:\n index = extract_index(list(data.values()))\n\n def sp_maker(x):\n return SparseArray(x, kind=self._default_kind,\n fill_value=self._default_fill_value,\n copy=True, dtype=dtype)\n sdict = {}\n for k, v in compat.iteritems(data):\n if isinstance(v, Series):\n # Force alignment, no copy necessary\n if not v.index.equals(index):\n v = v.reindex(index)\n\n if not isinstance(v, SparseSeries):\n v = sp_maker(v.values)\n elif isinstance(v, SparseArray):\n v = v.copy()\n else:\n if isinstance(v, dict):\n v = [v.get(i, np.nan) for i in index]\n\n v = sp_maker(v)\n\n if index is not None and len(v) != len(index):\n msg = \"Length of passed values is {}, index implies {}\"\n raise ValueError(msg.format(len(v), len(index)))\n sdict[k] = v\n\n if len(columns.difference(sdict)):\n # TODO: figure out how to handle this case, all nan's?\n # add in any other columns we want to have (completeness)\n nan_arr = np.empty(len(index), dtype='float64')\n nan_arr.fill(np.nan)\n nan_arr = SparseArray(nan_arr, kind=self._default_kind,\n fill_value=self._default_fill_value,\n copy=False)\n sdict.update((c, nan_arr) for c in columns if c not in sdict)\n\n return to_manager(sdict, columns, index)\n\n def _init_matrix(self, data, index, columns, dtype=None):\n \"\"\"\n Init self from ndarray or list of lists.\n \"\"\"\n data = prep_ndarray(data, copy=False)\n index, columns = self._prep_index(data, index, columns)\n data = {idx: data[:, i] for i, idx in enumerate(columns)}\n return self._init_dict(data, index, columns, dtype)\n\n def _init_spmatrix(self, data, index, columns, dtype=None,\n fill_value=None):\n \"\"\"\n Init self from scipy.sparse matrix.\n \"\"\"\n index, columns = self._prep_index(data, index, columns)\n data = data.tocoo()\n N = len(index)\n\n # Construct a dict of SparseSeries\n sdict = {}\n values = Series(data.data, index=data.row, copy=False)\n for col, rowvals in values.groupby(data.col):\n # get_blocks expects int32 row indices in sorted order\n rowvals = rowvals.sort_index()\n rows = rowvals.index.values.astype(np.int32)\n blocs, blens = get_blocks(rows)\n\n sdict[columns[col]] = SparseSeries(\n rowvals.values, index=index,\n fill_value=fill_value,\n sparse_index=BlockIndex(N, blocs, blens))\n\n # Add any columns that were empty and thus not grouped on above\n sdict.update({column: SparseSeries(index=index,\n fill_value=fill_value,\n sparse_index=BlockIndex(N, [], []))\n for column in columns\n if column not in sdict})\n\n return self._init_dict(sdict, index, columns, dtype)\n\n def _prep_index(self, data, index, columns):\n N, K = data.shape\n if index is None:\n index = ibase.default_index(N)\n if columns is None:\n columns = ibase.default_index(K)\n\n if len(columns) != K:\n raise ValueError('Column length mismatch: {columns} vs. {K}'\n .format(columns=len(columns), K=K))\n if len(index) != N:\n raise ValueError('Index length mismatch: {index} vs. {N}'\n .format(index=len(index), N=N))\n return index, columns\n\n def to_coo(self):\n \"\"\"\n Return the contents of the frame as a sparse SciPy COO matrix.\n\n .. versionadded:: 0.20.0\n\n Returns\n -------\n coo_matrix : scipy.sparse.spmatrix\n If the caller is heterogeneous and contains booleans or objects,\n the result will be of dtype=object. See Notes.\n\n Notes\n -----\n The dtype will be the lowest-common-denominator type (implicit\n upcasting); that is to say if the dtypes (even of numeric types)\n are mixed, the one that accommodates all will be chosen.\n\n e.g. If the dtypes are float16 and float32, dtype will be upcast to\n float32. By numpy.find_common_type convention, mixing int64 and\n and uint64 will result in a float64 dtype.\n \"\"\"\n try:\n from scipy.sparse import coo_matrix\n except ImportError:\n raise ImportError('Scipy is not installed')\n\n dtype = find_common_type(self.dtypes)\n if isinstance(dtype, SparseDtype):\n dtype = dtype.subtype\n\n cols, rows, datas = [], [], []\n for col, name in enumerate(self):\n s = self[name]\n row = s.sp_index.to_int_index().indices\n cols.append(np.repeat(col, len(row)))\n rows.append(row)\n datas.append(s.sp_values.astype(dtype, copy=False))\n\n cols = np.concatenate(cols)\n rows = np.concatenate(rows)\n datas = np.concatenate(datas)\n return coo_matrix((datas, (rows, cols)), shape=self.shape)\n\n def __array_wrap__(self, result):\n return self._constructor(\n result, index=self.index, columns=self.columns,\n default_kind=self._default_kind,\n default_fill_value=self._default_fill_value).__finalize__(self)\n\n def __getstate__(self):\n # pickling\n return dict(_typ=self._typ, _subtyp=self._subtyp, _data=self._data,\n _default_fill_value=self._default_fill_value,\n _default_kind=self._default_kind)\n\n def _unpickle_sparse_frame_compat(self, state):\n \"\"\"\n Original pickle format\n \"\"\"\n series, cols, idx, fv, kind = state\n\n if not isinstance(cols, Index): # pragma: no cover\n from pandas.io.pickle import _unpickle_array\n columns = _unpickle_array(cols)\n else:\n columns = cols\n\n if not isinstance(idx, Index): # pragma: no cover\n from pandas.io.pickle import _unpickle_array\n index = _unpickle_array(idx)\n else:\n index = idx\n\n series_dict = DataFrame()\n for col, (sp_index, sp_values) in compat.iteritems(series):\n series_dict[col] = SparseSeries(sp_values, sparse_index=sp_index,\n fill_value=fv)\n\n self._data = to_manager(series_dict, columns, index)\n self._default_fill_value = fv\n self._default_kind = kind\n\n def to_dense(self):\n \"\"\"\n Convert to dense DataFrame\n\n Returns\n -------\n df : DataFrame\n \"\"\"\n data = {k: v.to_dense() for k, v in compat.iteritems(self)}\n return DataFrame(data, index=self.index, columns=self.columns)\n\n def _apply_columns(self, func):\n \"\"\"\n Get new SparseDataFrame applying func to each columns\n \"\"\"\n\n new_data = {col: func(series)\n for col, series in compat.iteritems(self)}\n\n return self._constructor(\n data=new_data, index=self.index, columns=self.columns,\n default_fill_value=self.default_fill_value).__finalize__(self)\n\n def astype(self, dtype):\n return self._apply_columns(lambda x: x.astype(dtype))\n\n def copy(self, deep=True):\n \"\"\"\n Make a copy of this SparseDataFrame\n \"\"\"\n result = super(SparseDataFrame, self).copy(deep=deep)\n result._default_fill_value = self._default_fill_value\n result._default_kind = self._default_kind\n return result\n\n @property\n def default_fill_value(self):\n return self._default_fill_value\n\n @property\n def default_kind(self):\n return self._default_kind\n\n @property\n def density(self):\n \"\"\"\n Ratio of non-sparse points to total (dense) data points\n represented in the frame\n \"\"\"\n tot_nonsparse = sum(ser.sp_index.npoints\n for _, ser in compat.iteritems(self))\n tot = len(self.index) * len(self.columns)\n return tot_nonsparse / float(tot)\n\n def fillna(self, value=None, method=None, axis=0, inplace=False,\n limit=None, downcast=None):\n new_self = super(SparseDataFrame,\n self).fillna(value=value, method=method, axis=axis,\n inplace=inplace, limit=limit,\n downcast=downcast)\n if not inplace:\n self = new_self\n\n # set the fill value if we are filling as a scalar with nothing special\n # going on\n if (value is not None and value == value and method is None and\n limit is None):\n self._default_fill_value = value\n\n if not inplace:\n return self\n\n # ----------------------------------------------------------------------\n # Support different internal representation of SparseDataFrame\n\n def _sanitize_column(self, key, value, **kwargs):\n \"\"\"\n Creates a new SparseArray from the input value.\n\n Parameters\n ----------\n key : object\n value : scalar, Series, or array-like\n kwargs : dict\n\n Returns\n -------\n sanitized_column : SparseArray\n\n \"\"\"\n def sp_maker(x, index=None):\n return SparseArray(x, index=index,\n fill_value=self._default_fill_value,\n kind=self._default_kind)\n if isinstance(value, SparseSeries):\n clean = value.reindex(self.index).as_sparse_array(\n fill_value=self._default_fill_value, kind=self._default_kind)\n\n elif isinstance(value, SparseArray):\n if len(value) != len(self.index):\n raise ValueError('Length of values does not match '\n 'length of index')\n clean = value\n\n elif hasattr(value, '__iter__'):\n if isinstance(value, Series):\n clean = value.reindex(self.index)\n if not isinstance(value, SparseSeries):\n clean = sp_maker(clean)\n else:\n if len(value) != len(self.index):\n raise ValueError('Length of values does not match '\n 'length of index')\n clean = sp_maker(value)\n\n # Scalar\n else:\n clean = sp_maker(value, self.index)\n\n # always return a SparseArray!\n return clean\n\n def get_value(self, index, col, takeable=False):\n \"\"\"\n Quickly retrieve single value at passed column and index\n\n .. deprecated:: 0.21.0\n\n Please use .at[] or .iat[] accessors.\n\n Parameters\n ----------\n index : row label\n col : column label\n takeable : interpret the index/col as indexers, default False\n\n Returns\n -------\n value : scalar value\n \"\"\"\n warnings.warn(\"get_value is deprecated and will be removed \"\n \"in a future release. Please use \"\n \".at[] or .iat[] accessors instead\", FutureWarning,\n stacklevel=2)\n return self._get_value(index, col, takeable=takeable)\n\n def _get_value(self, index, col, takeable=False):\n if takeable is True:\n series = self._iget_item_cache(col)\n else:\n series = self._get_item_cache(col)\n\n return series._get_value(index, takeable=takeable)\n _get_value.__doc__ = get_value.__doc__\n\n def set_value(self, index, col, value, takeable=False):\n \"\"\"\n Put single value at passed column and index\n\n .. deprecated:: 0.21.0\n\n Please use .at[] or .iat[] accessors.\n\n Parameters\n ----------\n index : row label\n col : column label\n value : scalar value\n takeable : interpret the index/col as indexers, default False\n\n Notes\n -----\n This method *always* returns a new object. It is currently not\n particularly efficient (and potentially very expensive) but is provided\n for API compatibility with DataFrame\n\n Returns\n -------\n frame : DataFrame\n \"\"\"\n warnings.warn(\"set_value is deprecated and will be removed \"\n \"in a future release. Please use \"\n \".at[] or .iat[] accessors instead\", FutureWarning,\n stacklevel=2)\n return self._set_value(index, col, value, takeable=takeable)\n\n def _set_value(self, index, col, value, takeable=False):\n dense = self.to_dense()._set_value(\n index, col, value, takeable=takeable)\n return dense.to_sparse(kind=self._default_kind,\n fill_value=self._default_fill_value)\n _set_value.__doc__ = set_value.__doc__\n\n def _slice(self, slobj, axis=0, kind=None):\n if axis == 0:\n new_index = self.index[slobj]\n new_columns = self.columns\n else:\n new_index = self.index\n new_columns = self.columns[slobj]\n\n return self.reindex(index=new_index, columns=new_columns)\n\n def xs(self, key, axis=0, copy=False):\n \"\"\"\n Returns a row (cross-section) from the SparseDataFrame as a Series\n object.\n\n Parameters\n ----------\n key : some index contained in the index\n\n Returns\n -------\n xs : Series\n \"\"\"\n if axis == 1:\n data = self[key]\n return data\n\n i = self.index.get_loc(key)\n data = self.take([i]).get_values()[0]\n return Series(data, index=self.columns)\n\n # ----------------------------------------------------------------------\n # Arithmetic-related methods\n\n def _combine_frame(self, other, func, fill_value=None, level=None):\n if level is not None:\n raise NotImplementedError(\"'level' argument is not supported\")\n\n this, other = self.align(other, join='outer', level=level, copy=False)\n new_index, new_columns = this.index, this.columns\n\n if self.empty and other.empty:\n return self._constructor(index=new_index).__finalize__(self)\n\n new_data = {}\n if fill_value is not None:\n # TODO: be a bit more intelligent here\n for col in new_columns:\n if col in this and col in other:\n dleft = this[col].to_dense()\n dright = other[col].to_dense()\n result = dleft._binop(dright, func, fill_value=fill_value)\n result = result.to_sparse(fill_value=this[col].fill_value)\n new_data[col] = result\n else:\n\n for col in new_columns:\n if col in this and col in other:\n new_data[col] = func(this[col], other[col])\n\n new_fill_value = self._get_op_result_fill_value(other, func)\n\n return self._constructor(data=new_data, index=new_index,\n columns=new_columns,\n default_fill_value=new_fill_value\n ).__finalize__(self)\n\n def _combine_match_index(self, other, func, level=None):\n new_data = {}\n\n if level is not None:\n raise NotImplementedError(\"'level' argument is not supported\")\n\n this, other = self.align(other, join='outer', axis=0, level=level,\n copy=False)\n\n for col, series in compat.iteritems(this):\n new_data[col] = func(series.values, other.values)\n\n fill_value = self._get_op_result_fill_value(other, func)\n\n return self._constructor(\n new_data, index=this.index, columns=self.columns,\n default_fill_value=fill_value).__finalize__(self)\n\n def _combine_match_columns(self, other, func, level=None):\n # patched version of DataFrame._combine_match_columns to account for\n # NumPy circumventing __rsub__ with float64 types, e.g.: 3.0 - series,\n # where 3.0 is numpy.float64 and series is a SparseSeries. Still\n # possible for this to happen, which is bothersome\n\n if level is not None:\n raise NotImplementedError(\"'level' argument is not supported\")\n\n left, right = self.align(other, join='outer', axis=1, level=level,\n copy=False)\n assert left.columns.equals(right.index)\n\n new_data = {}\n\n for col in left.columns:\n new_data[col] = func(left[col], float(right[col]))\n\n return self._constructor(\n new_data, index=left.index, columns=left.columns,\n default_fill_value=self.default_fill_value).__finalize__(self)\n\n def _combine_const(self, other, func):\n return self._apply_columns(lambda x: func(x, other))\n\n def _get_op_result_fill_value(self, other, func):\n own_default = self.default_fill_value\n\n if isinstance(other, DataFrame):\n # i.e. called from _combine_frame\n\n other_default = getattr(other, 'default_fill_value', np.nan)\n\n # if the fill values are the same use them? or use a valid one\n if own_default == other_default:\n # TOOD: won't this evaluate as False if both are np.nan?\n fill_value = own_default\n elif np.isnan(own_default) and not np.isnan(other_default):\n fill_value = other_default\n elif not np.isnan(own_default) and np.isnan(other_default):\n fill_value = own_default\n else:\n fill_value = None\n\n elif isinstance(other, SparseSeries):\n # i.e. called from _combine_match_index\n\n # fill_value is a function of our operator\n if isna(other.fill_value) or isna(own_default):\n fill_value = np.nan\n else:\n fill_value = func(np.float64(own_default),\n np.float64(other.fill_value))\n\n else:\n raise NotImplementedError(type(other))\n\n return fill_value\n\n def _reindex_index(self, index, method, copy, level, fill_value=np.nan,\n limit=None, takeable=False):\n if level is not None:\n raise TypeError('Reindex by level not supported for sparse')\n\n if self.index.equals(index):\n if copy:\n return self.copy()\n else:\n return self\n\n if len(self.index) == 0:\n return self._constructor(\n index=index, columns=self.columns).__finalize__(self)\n\n indexer = self.index.get_indexer(index, method, limit=limit)\n indexer = ensure_platform_int(indexer)\n mask = indexer == -1\n need_mask = mask.any()\n\n new_series = {}\n for col, series in self.iteritems():\n if mask.all():\n continue\n\n values = series.values\n # .take returns SparseArray\n new = values.take(indexer)\n if need_mask:\n new = new.values\n # convert integer to float if necessary. need to do a lot\n # more than that, handle boolean etc also\n new, fill_value = maybe_upcast(new, fill_value=fill_value)\n np.putmask(new, mask, fill_value)\n\n new_series[col] = new\n\n return self._constructor(\n new_series, index=index, columns=self.columns,\n default_fill_value=self._default_fill_value).__finalize__(self)\n\n def _reindex_columns(self, columns, method, copy, level, fill_value=None,\n limit=None, takeable=False):\n if level is not None:\n raise TypeError('Reindex by level not supported for sparse')\n\n if notna(fill_value):\n raise NotImplementedError(\"'fill_value' argument is not supported\")\n\n if limit:\n raise NotImplementedError(\"'limit' argument is not supported\")\n\n if method is not None:\n raise NotImplementedError(\"'method' argument is not supported\")\n\n # TODO: fill value handling\n sdict = {k: v for k, v in compat.iteritems(self) if k in columns}\n return self._constructor(\n sdict, index=self.index, columns=columns,\n default_fill_value=self._default_fill_value).__finalize__(self)\n\n def _reindex_with_indexers(self, reindexers, method=None, fill_value=None,\n limit=None, copy=False, allow_dups=False):\n\n if method is not None or limit is not None:\n raise NotImplementedError(\"cannot reindex with a method or limit \"\n \"with sparse\")\n\n if fill_value is None:\n fill_value = np.nan\n\n reindexers = {self._get_axis_number(a): val\n for (a, val) in compat.iteritems(reindexers)}\n\n index, row_indexer = reindexers.get(0, (None, None))\n columns, col_indexer = reindexers.get(1, (None, None))\n\n if columns is None:\n columns = self.columns\n\n new_arrays = {}\n for col in columns:\n if col not in self:\n continue\n if row_indexer is not None:\n new_arrays[col] = algos.take_1d(self[col].get_values(),\n row_indexer,\n fill_value=fill_value)\n else:\n new_arrays[col] = self[col]\n\n return self._constructor(new_arrays, index=index,\n columns=columns).__finalize__(self)\n\n def _join_compat(self, other, on=None, how='left', lsuffix='', rsuffix='',\n sort=False):\n if on is not None:\n raise NotImplementedError(\"'on' keyword parameter is not yet \"\n \"implemented\")\n return self._join_index(other, how, lsuffix, rsuffix)\n\n def _join_index(self, other, how, lsuffix, rsuffix):\n if isinstance(other, Series):\n if other.name is None:\n raise ValueError('Other Series must have a name')\n\n other = SparseDataFrame(\n {other.name: other},\n default_fill_value=self._default_fill_value)\n\n join_index = self.index.join(other.index, how=how)\n\n this = self.reindex(join_index)\n other = other.reindex(join_index)\n\n this, other = this._maybe_rename_join(other, lsuffix, rsuffix)\n\n from pandas import concat\n return concat([this, other], axis=1, verify_integrity=True)\n\n def _maybe_rename_join(self, other, lsuffix, rsuffix):\n to_rename = self.columns.intersection(other.columns)\n if len(to_rename) > 0:\n if not lsuffix and not rsuffix:\n raise ValueError('columns overlap but no suffix specified: '\n '{to_rename}'.format(to_rename=to_rename))\n\n def lrenamer(x):\n if x in to_rename:\n return '{x}{lsuffix}'.format(x=x, lsuffix=lsuffix)\n return x\n\n def rrenamer(x):\n if x in to_rename:\n return '{x}{rsuffix}'.format(x=x, rsuffix=rsuffix)\n return x\n\n this = self.rename(columns=lrenamer)\n other = other.rename(columns=rrenamer)\n else:\n this = self\n\n return this, other\n\n def transpose(self, *args, **kwargs):\n \"\"\"\n Returns a DataFrame with the rows/columns switched.\n \"\"\"\n nv.validate_transpose(args, kwargs)\n return self._constructor(\n self.values.T, index=self.columns, columns=self.index,\n default_fill_value=self._default_fill_value,\n default_kind=self._default_kind).__finalize__(self)\n\n T = property(transpose)\n\n @Appender(DataFrame.count.__doc__)\n def count(self, axis=0, **kwds):\n if axis is None:\n axis = self._stat_axis_number\n\n return self.apply(lambda x: x.count(), axis=axis)\n\n def cumsum(self, axis=0, *args, **kwargs):\n \"\"\"\n Return SparseDataFrame of cumulative sums over requested axis.\n\n Parameters\n ----------\n axis : {0, 1}\n 0 for row-wise, 1 for column-wise\n\n Returns\n -------\n y : SparseDataFrame\n \"\"\"\n nv.validate_cumsum(args, kwargs)\n\n if axis is None:\n axis = self._stat_axis_number\n\n return self.apply(lambda x: x.cumsum(), axis=axis)\n\n @Appender(generic._shared_docs['isna'] % _shared_doc_kwargs)\n def isna(self):\n return self._apply_columns(lambda x: x.isna())\n isnull = isna\n\n @Appender(generic._shared_docs['notna'] % _shared_doc_kwargs)\n def notna(self):\n return self._apply_columns(lambda x: x.notna())\n notnull = notna\n\n def apply(self, func, axis=0, broadcast=None, reduce=None,\n result_type=None):\n \"\"\"\n Analogous to DataFrame.apply, for SparseDataFrame\n\n Parameters\n ----------\n func : function\n Function to apply to each column\n axis : {0, 1, 'index', 'columns'}\n broadcast : bool, default False\n For aggregation functions, return object of same size with values\n propagated\n\n .. deprecated:: 0.23.0\n This argument will be removed in a future version, replaced\n by result_type='broadcast'.\n\n reduce : boolean or None, default None\n Try to apply reduction procedures. If the DataFrame is empty,\n apply will use reduce to determine whether the result should be a\n Series or a DataFrame. If reduce is None (the default), apply's\n return value will be guessed by calling func an empty Series (note:\n while guessing, exceptions raised by func will be ignored). If\n reduce is True a Series will always be returned, and if False a\n DataFrame will always be returned.\n\n .. deprecated:: 0.23.0\n This argument will be removed in a future version, replaced\n by result_type='reduce'.\n\n result_type : {'expand', 'reduce', 'broadcast, None}\n These only act when axis=1 {columns}:\n\n * 'expand' : list-like results will be turned into columns.\n * 'reduce' : return a Series if possible rather than expanding\n list-like results. This is the opposite to 'expand'.\n * 'broadcast' : results will be broadcast to the original shape\n of the frame, the original index & columns will be retained.\n\n The default behaviour (None) depends on the return value of the\n applied function: list-like results will be returned as a Series\n of those. However if the apply function returns a Series these\n are expanded to columns.\n\n .. versionadded:: 0.23.0\n\n Returns\n -------\n applied : Series or SparseDataFrame\n \"\"\"\n if not len(self.columns):\n return self\n axis = self._get_axis_number(axis)\n\n if isinstance(func, np.ufunc):\n new_series = {}\n for k, v in compat.iteritems(self):\n applied = func(v)\n applied.fill_value = func(v.fill_value)\n new_series[k] = applied\n return self._constructor(\n new_series, index=self.index, columns=self.columns,\n default_fill_value=self._default_fill_value,\n default_kind=self._default_kind).__finalize__(self)\n\n from pandas.core.apply import frame_apply\n op = frame_apply(self,\n func=func,\n axis=axis,\n reduce=reduce,\n broadcast=broadcast,\n result_type=result_type)\n return op.get_result()\n\n def applymap(self, func):\n \"\"\"\n Apply a function to a DataFrame that is intended to operate\n elementwise, i.e. like doing map(func, series) for each series in the\n DataFrame\n\n Parameters\n ----------\n func : function\n Python function, returns a single value from a single value\n\n Returns\n -------\n applied : DataFrame\n \"\"\"\n return self.apply(lambda x: lmap(func, x))\n\n\ndef to_manager(sdf, columns, index):\n \"\"\" create and return the block manager from a dataframe of series,\n columns, index\n \"\"\"\n\n # from BlockManager perspective\n axes = [ensure_index(columns), ensure_index(index)]\n\n return create_block_manager_from_arrays(\n [sdf[c] for c in columns], columns, axes)\n\n\ndef stack_sparse_frame(frame):\n \"\"\"\n Only makes sense when fill_value is NaN\n \"\"\"\n lengths = [s.sp_index.npoints for _, s in compat.iteritems(frame)]\n nobs = sum(lengths)\n\n # this is pretty fast\n minor_codes = np.repeat(np.arange(len(frame.columns)), lengths)\n\n inds_to_concat = []\n vals_to_concat = []\n # TODO: Figure out whether this can be reached.\n # I think this currently can't be reached because you can't build a\n # SparseDataFrame with a non-np.NaN fill value (fails earlier).\n for _, series in compat.iteritems(frame):\n if not np.isnan(series.fill_value):\n raise TypeError('This routine assumes NaN fill value')\n\n int_index = series.sp_index.to_int_index()\n inds_to_concat.append(int_index.indices)\n vals_to_concat.append(series.sp_values)\n\n major_codes = np.concatenate(inds_to_concat)\n stacked_values = np.concatenate(vals_to_concat)\n index = MultiIndex(levels=[frame.index, frame.columns],\n codes=[major_codes, minor_codes],\n verify_integrity=False)\n\n lp = DataFrame(stacked_values.reshape((nobs, 1)), index=index,\n columns=['foo'])\n return lp.sort_index(level=0)\n\n\ndef homogenize(series_dict):\n \"\"\"\n Conform a set of SparseSeries (with NaN fill_value) to a common SparseIndex\n corresponding to the locations where they all have data\n\n Parameters\n ----------\n series_dict : dict or DataFrame\n\n Notes\n -----\n Using the dumbest algorithm I could think of. Should put some more thought\n into this\n\n Returns\n -------\n homogenized : dict of SparseSeries\n \"\"\"\n index = None\n\n need_reindex = False\n\n for _, series in compat.iteritems(series_dict):\n if not np.isnan(series.fill_value):\n raise TypeError('this method is only valid with NaN fill values')\n\n if index is None:\n index = series.sp_index\n elif not series.sp_index.equals(index):\n need_reindex = True\n index = index.intersect(series.sp_index)\n\n if need_reindex:\n output = {}\n for name, series in compat.iteritems(series_dict):\n if not series.sp_index.equals(index):\n series = series.sparse_reindex(index)\n\n output[name] = series\n else:\n output = series_dict\n\n return output\n\n\n# use unaccelerated ops for sparse objects\nops.add_flex_arithmetic_methods(SparseDataFrame)\nops.add_special_arithmetic_methods(SparseDataFrame)\n" ]
[ [ "pandas.core.generic.NDFrame.__init__", "pandas.compat.numpy.function.validate_cumsum", "pandas.core.dtypes.missing.notna", "numpy.concatenate", "pandas.core.internals.construction.prep_ndarray", "pandas.core.dtypes.common.is_scipy_sparse", "pandas.compat.iteritems", "pandas.core.frame.DataFrame", "scipy.sparse.coo_matrix", "pandas.core.series.Series", "pandas.core.ops.add_special_arithmetic_methods", "pandas.core.index.ensure_index", "pandas.compat.lmap", "pandas.core.arrays.sparse.SparseArray", "pandas._libs.sparse.BlockIndex", "pandas.core.common.dict_keys_to_ordered_list", "pandas.core.indexes.base.default_index", "pandas.core.index.MultiIndex", "pandas.concat", "pandas.core.apply.frame_apply", "pandas.util._decorators.Appender", "numpy.putmask", "numpy.isnan", "pandas.compat.numpy.function.validate_transpose", "pandas.io.pickle._unpickle_array", "pandas.core.dtypes.common.ensure_platform_int", "pandas.core.ops.add_flex_arithmetic_methods", "pandas.core.internals.create_block_manager_from_arrays", "pandas.core.sparse.series.SparseSeries", "pandas.core.dtypes.cast.find_common_type", "pandas._libs.sparse.get_blocks", "pandas.core.dtypes.cast.maybe_upcast", "numpy.float64", "pandas.core.dtypes.missing.isna", "pandas.core.index.Index" ] ]
SuwenJunliu/seisflows
[ "14d246691acf8e8549487a5db7c7cd877d23a2ae" ]
[ "seisflows/plugins/line_search/bracket.py" ]
[ "#\n# This is Seisflows\n#\n# See LICENCE file\n#\n#\n###############################################################################\n\n# Import numpy\nimport numpy as np\n\n# Local imports\nfrom seisflows.plugins.line_search import Base\nfrom seisflows.tools.math import backtrack2, polyfit2\n\n\nclass Bracket(Base):\n \"\"\" Implements bracketing line search\n\n Variables\n x - list of step lenths from current line search\n f - correpsonding list of function values\n gtg - dot product of gradient with itself\n gtp - dot product of gradient and search direction\n\n Status codes\n status > 0 : finished\n status == 0 : not finished\n status < 0 : failed\n \"\"\"\n\n def calculate_step(self):\n \"\"\" Determines step length and search status\n \"\"\"\n x, f, gtg, gtp, step_count, update_count = self.search_history()\n \n\n if step_count == 0 and update_count == 0:\n # based on idea from Dennis and Schnabel\n alpha = gtg[-1]**-1\n status = 0\n\n elif step_count == 0:\n # based on the first equation in sec 3.5 of Nocedal and Wright 2ed\n idx = np.argmin(self.func_vals[:-1])\n alpha = self.step_lens[idx] * gtp[-2]/gtp[-1]\n status = 0\n\n elif _check_bracket(x, f) and _good_enough(x, f):\n alpha = x[f.argmin()]\n status = 1\n\n elif _check_bracket(x, f):\n alpha = polyfit2(x, f)\n status = 0\n\n elif step_count <= self.step_count_max and all(f <= f[0]):\n # we need a larger step length\n alpha = 1.618034*x[-1]\n status = 0\n\n elif step_count <= self.step_count_max:\n print(\"we need a smaller step length\")\n # we need a smaller step length\n slope = gtp[-1]/gtg[-1]\n alpha = backtrack2(f[0], slope, x[1], f[1], b1=0.1, b2=0.5)\n #print(\"we need a smaller step length\")\n status = 0\n\n else:\n # failed because step_count_max exceeded\n alpha = None\n status = -1\n\n # apply optional step length safeguard\n if alpha > self.step_len_max and \\\n step_count == 0:\n alpha = 0.618034*self.step_len_max\n status = 0\n\n elif alpha > self.step_len_max:\n # stop because safeguard prevents us from going further\n alpha = self.step_len_max\n status = 1\n \n \n return alpha, status\n\n\ndef _check_bracket(step_lens, func_vals):\n \"\"\" Checks if minimum has been bracketed\n \"\"\"\n x, f = step_lens, func_vals\n imin, fmin = f.argmin(), f.min()\n if (fmin < f[0]) and any(f[imin:] > fmin):\n return 1\n else:\n print(\"not decrease_check_bracket\",f.min(),f[0])\n return 0\n\n\ndef _good_enough(step_lens, func_vals, thresh=np.log10(1.2)):\n \"\"\" Checks if step length is reasonably close to quadratic estimate\n \"\"\"\n x, f = step_lens, func_vals\n if not _check_bracket(x, f):\n return 0\n print(\"x\",x)\n print(\"f\",f)\n x0 = polyfit2(x, f)\n print(\"x0 \" + str(x0))\n if any(np.abs(np.log10(x[1:]/x0)) < thresh):\n return 1\n else:\n print(\"not good \",np.min(np.abs(np.log10(x[1:]/x0))),thresh)\n return 0\n" ]
[ [ "numpy.log10", "numpy.argmin" ] ]
xebastien/TomoMIST
[ "c2a77757e25e7c16d392de56457b8b75872a2b64" ]
[ "pagailleIO.py" ]
[ "\nimport fabio\nimport fabio.edfimage as edf\nimport fabio.tifimage as tif\n#import edfimage\n\n#from PIL import Image\nimport numpy as np\nimport sys\nimport os\nimport configparser as ConfigParser\n\n\ndef openImage(filename):\n filename=str(filename)\n im=fabio.open(filename)\n imarray=im.data\n return imarray\n\ndef getHeader(filename):\n im = fabio.open(filename)\n header= im.header\n return header\n\n\n\ndef saveTiff16bit(data,filename,minIm=0,maxIm=0,header=None):\n if(minIm==maxIm):\n minIm=np.amin(data)\n maxIm= np.amax(data)\n datatoStore=65536*(data-minIm)/(maxIm-minIm)\n datatoStore[datatoStore>65635]=65535\n datatoStore[datatoStore <0] = 0\n datatoStore=np.asarray(datatoStore,np.uint16)\n\n if(header!=None):\n tif.TifImage(data=datatoStore,header=header).write(filename)\n else:\n tif.TifImage(data=datatoStore).write(filename)\n\n\n\n\n\ndef openSeq(filenames):\n if len(filenames) >0 :\n data=openImage(str(filenames[0]))\n height,width=data.shape\n toReturn = np.zeros((len(filenames), height, width),dtype=np.float32)\n i=0\n for file in filenames:\n data=openImage(str(file))\n toReturn[i,:,:]=data\n i+=1\n return toReturn\n raise Exception('spytlabIOError')\n\n# ****************************************************************************\n# ********************** Interpreting the ini file\n# ****************************************************************************\n\ndef replace_default(key, value, data_type, use_default, default_val, condition, reason):\n \"\"\"Function that deals with replacing inputed values with default values\n when this is needed (and possible)\n \"\"\"\n \n value_out = value\n \n if (use_default):\n if (default_val):\n type_warn = (str(reason) + ' Parameter value for key ' + str(key) + ' of data type ' + str(data_type)\n + ' has been replaced with default value ' + str(default_val) + ' . Initially inputed value: '\n + str(value))\n test_warn(condition, 'check_key', type_warn)\n value_out = default_val\n else:\n type_err = (str(reason) + ' Parameter value for key ' + str(key) + ' of data type ' + str(data_type)\n + ' is NEEDED and there is no default value for this.' + ' Initially inputed value: ' + str(value))\n test_err(condition, 'check_key', type_err)\n \n return value_out\n\n\ndef test_warn(assertion, func='function', message='False assertion', verbose=True):\n \"\"\"Tests if assertion can be interpreted as False. If this is the case, print a warning message, but continue the\n execution of the program. Returns True if problem found. This can be used in an if clause to perform additional\n actions to compensate for the problem. (e.g. asign a default value to some variable).\n \"\"\"\n \n result = not bool(assertion)\n\n if (result and verbose):\n print('Function ' + func + ': ' + message)\n\n return result\n\n\ndef check_key(key, config, section, data_type='str', default_val=None, use_default=True, positive=False, acc_val=None):\n \"\"\"Check if key exists in dictionary. If it does not exist and no default value given, use error function.\n Otherwise print warning and use default. This function will change the input dictionary when needed, as it is\n a mutable object. If positive is True for a int/float, the code will check if the number is positive.\n If positive is True for a path, then the code will check if the path points to a true location, otherwise it will\n replace it with None\n \"\"\"\n\n # Check if key exists in dictionary. If not, replace with default\n # if possible or call error\n \n reason = 'Key does not exist in INI file.'\n condition = True if key in config[section] else False\n value = None\n \n if(condition):\n value = config.get(section, key)\n else:\n replace_default(key, value, data_type, use_default, default_val, condition, reason)\n\n # Remove leading and final quotes/apostrophes in case they were\n # introduced by the user\n try:\n basestring\n except NameError:\n basestring = str\n \n if(isinstance(value, str) or isinstance(value, basestring)):\n if value.startswith('\\\"') and value.endswith('\\\"'):\n value = value[1:-1]\n \n if value.startswith('\\'') and value.endswith('\\''):\n value = value[1:-1]\n \n # Check if inputed value is None or 'none'\n if (value == 'none'):\n value = None\n \n # Force correct type. If it cannot be done, replace with default\n # if possible or call error \n try:\n if(value):\n if (data_type == 'float'):\n value = float(value)\n elif (data_type == 'int'):\n value = int(value)\n elif (data_type == 'bool'):\n if (str(config.get(section, key)).lower() == 'true'):\n value = True\n elif (str(value).lower() == 'false' or int(value) == 0):\n value = False\n else:\n value = bool(value)\n \n \n elif (data_type == 'grid'):\n roi_list = value.split()\n roi_err1 = ('The string for ' + key + ' must be \\'none\\' or must contain 4 positive integers separated '\n 'by a space using this format \\'xmin xmax ymin ymax\\'')\n roi_err2 = ('At least one of the 4 values in the inputed string for ' + key + ' cannot be interpreted '\n 'as INTEGER')\n roi_err3 = ('The 4 values in the inputed string for ' + key + ' must all be POSITIVE INTEGERS')\n roi_err4 = 'In ' + key + ', check if xmin < xmax'\n roi_err5 = 'In ' + key + ', check if ymin < ymax'\n # roi_err6 = 'In ' + key + ', check if ymin < ymax'\n\n test_err(len(roi_list) == 4, 'check_key', roi_err1)\n \n try: \n roi_list = [int(i) for i in roi_list]\n value = roi_list\n except:\n test_err(False, 'check_key', roi_err2)\n \n test_err(any(item >= 0 for item in roi_list), 'check_key', roi_err3)\n test_err(roi_list[0] < roi_list[1], 'check_key', roi_err4)\n test_err(roi_list[2] < roi_list[3], 'check_key', roi_err5)\n \n elif (data_type == 'path'):\n value = os.path.abspath(value)\n if (not os.path.exists(value)):\n if(positive):\n warn = ('Path in key ' + str(key) + ' with value: ' + str(value) + ' does not exist on disk. '\n + ' Will try to create it.')\n test_warn(False, 'check_input', warn)\n #value = None\n #else:\n # Create path, check write permissions\n # try:\n # os.makedirs(value)\n # except:\n # write_err1 = ('Cannot create ' + value + '. Check write permissions')\n # test_err(False, 'check_input', write_err1) \n else:\n if (use_default):\n value = default_val\n exist_warn = ('Key ' + str(key) + ' does not exist or has ' + 'value None in INI file. It will created '\n + 'using the default value ' + str(default_val))\n if (test_warn(key in config.options(section), 'check_key', exist_warn)):\n config.set(section, key, default_val)\n else:\n exist_err = ('Key ' + str(key) + ' does not exist or has ' + 'value None in INI file. '\n + 'It MUST be included with a valid value. ')\n test_err(key in config.options(section), 'check_key', exist_err)\n except (ValueError, TypeError):\n reason = 'Input value cannot be parsed into correct data type.'\n condition = False\n replace_default(key, value, data_type, use_default, default_val, condition, reason)\n \n # Check if value is within accepted set of values\n if (acc_val):\n acc_list = acc_val.split()\n reason = 'Input value not in accepted list of values for key.'\n condition = bool(str(value) in acc_list)\n replace_default(key, value, data_type, use_default, default_val, condition, reason)\n \n # If int or float, test whether it is a positive value (if required)\n if(value and data_type in ['int', 'float'] and positive):\n pos_err = ('Key ' + str(key) + ' with input value ' + str(config.get(section, key)) + ' must be a POSITIVE ' \n 'number of type ' + data_type)\n test_err(value >= 0, 'check_key', pos_err)\n \n return value\n\n\n\ndef check_input(sCase,path_ini):\n \"\"\"Function to load, check and correct if possible the contents of the INI file for the detectorDistortion script.\n When possible, it will use default values if input ones are absent. It will also ensure that directory paths are\n int the absolute format and create output directories when and if needed. It can call warnings or errors, depending\n on how severe the issue is. Returns a dictionary to be used in the rest of the script\n \"\"\"\n \n # Create and load config object\n config = ConfigParser.ConfigParser()\n config.read(path_ini)\n\n error_msg = ('The provided INI file does not contain the ' + str(sCase) + ' tomoCase. All relevant user parameters'\n ' must be present in the INI file under that section/case.')\n test_err(sCase in config.sections(), 'check_input', error_msg)\n \n section_out = sCase + '_checked'\n\n \n # Prepare list of [key, data_type, default_val, use_default, positive, acc_value]\n key_list = [['nbImages', 'int', 1000, True, True, None],\n ['gridDigit', 'int', 3, True, True, None],\n ['gridImages', 'grid', None, False, True, None],\n ['middlePartStr', 'str', '__', True, True, None],\n ['darkName', 'str', 'dark', True, True, None],\n ['refstartN', 'str', 'refHST0000', True, True, None],\n ['refstopN', 'str', 'refHST2800', True, True, None],\n ['machinePrefix', 'str', 'ESRFcluster', True, True, None],\n ['MISTII_1', 'bool', True, True, True, None],\n ['MISTII_2', 'bool', True, False, True, None],\n \t\t ['computeEllipse', 'bool', True, False, True, None],\n ['expFolder', 'path', None, False, True, None],\n ['outputFolder', 'path', None, False, True, None],\n ['FolderBasis', 'str', None, True, True, None],\n ['cropOn', 'bool', True, True, True, None],\n ['cropDebX', 'int', 0, True, True, None],\n ['cropDebY', 'int', 0, True, True, None],\n ['cropEndX', 'int', 1850, True, True, None],\n ['cropEndY', 'int', 2048, True, True, None],\n ['NeighboursPix', 'int', 1, True, True, None],\n ['pixel', 'float', 5.8E-6, True, True, None],\n ['nbProj', 'int', 3000, True, True, None],\n ['distOD', 'int', 1, True, True, None],\n ['distSO', 'int', 140, True, True, None],\n ['energy', 'float', 30, True, True, None],\n ['delta', 'float', 8E-7, True, True, None],\n ['beta', 'float', 7E-10, True, True, None],\n ['sourceSize', 'float', 1E-6, True, True, None],\n ['detectorPSF', 'float', 1.5, True, True, None],\n ['padding', 'int', 0, True, True, None],\n ['padType', 'str', 'reflect', True, True, None],\n ['Deconvolution', 'bool', False, True, True, None],\n ['umpaMaxShift', 'int', 4, True, True, None],\n ['LCS_med_filter' ,'int', 0, True, True, None],\n ['LCS_gauss_filter','int', 0, True, True, None],\n ['DeconvType', 'str', 'unsupervised',True, True, None],\n ['DirDF_MedFilt', 'int', 1, True, True, None],\n ['timePavlovDirDF', 'int', 0, True, True, None],\n ['timeLCSv2', 'int', 0, True, True, None],\n ['sigmaRegularization','int', 0, True, True, None],\n ]\n \n\n # Initialize parameter dictionary\n param = {}\n \n # Add new section to config object\n config.add_section(section_out)\n \n # Check parameters related to files and directories\n for [key, data_type, default_value, use_default, positive, acc_value] in key_list:\n # SHOULD BE IMPLEMENTED FOR ROBUSTNESS\n value = check_key(key, config, sCase, data_type, default_value, use_default, positive, acc_value)\n \n # config.set(section_out, key, str(value))\n \n param[key] = value\n \n # For the ROI_default parameter, convert string to array of integers\n # Already done in check_key\n if((data_type == 'grid') and value):\n param[key] = np.array(value)\n \n \n # Print a modified INI file in output directory (with new section)\n #cfg_file = open(os.path.join(param['dir_out'], 'input_modified_' + dt + '.ini'), 'w')\n #config.write(cfg_file)\n #cfg_file.close()\n \n # Return dictionary containing needed parameters and their values\n return param\n \n \n \ndef test_err(assertion, func='function', message='False assertion', verbose = True):\n \"\"\"Tests if assertion can be interpreted as False. If this is the case, print an error message and stop the\n execution of the program.\n \"\"\"\n\n result = not bool(assertion)\n\n if (result):\n print('Function ' + func + ': ' + message)\n sys.exit(1)\n\n return result\n\n\n\n# ****************************************************************************\n# ********************** Motors\n# ****************************************************************************\n\n\ndef makeDarkMean(Darkfiedls):\n nbslices, height, width = Darkfiedls.shape\n meanSlice = np.mean(Darkfiedls, axis=0)\n print ('----------------------- mean Dark calculation done ------------------------- ')\n OutputFileName = '/Users/helene/PycharmProjects/spytlab/meanDarkTest.edf'\n outputEdf = edf.EdfFile(OutputFileName, access='wb+')\n outputEdf.WriteImage({}, meanSlice)\n return meanSlice\n\n\ndef saveEdf(data,filename):\n print(filename)\n dataToStore=data.astype(np.float32)\n edf.EdfImage(data=dataToStore).write(filename)\n\n\ndef save3D_Edf(data,filename):\n nbslices,height,width=data.shape\n for i in range(nbslices):\n textSlice='%4.4d'%i\n dataToSave=data[i,:,:]\n filenameSlice=filename+textSlice+'.edf'\n saveEdf(dataToSave,filenameSlice)\n\n\n\n#def savePNG(data,filename,min=0,max=0):\n #if min == max:\n # min=np.amin(data)\n # max= np.amax(data)\n #data16bit=data-min/(max-min)\n #data16bit=np.asarray(data16bit,dtype=np.uint16)\n\n #scipy.misc.imsave(filename,data16bit)\n\n\n\n\nif __name__ == \"__main__\":\n\n # filename='ref1-1.edf'\n # filenames=glob.glob('*.edf')\n # data=openImage(filename)\n # savePNG(data,'ref.png',100,450)\n # print( data.shape)\n #\n #\n # rootfolder = '/Volumes/VISITOR/md1097/id17/Phantoms/TwoDimensionalPhantom/GrilleFils/Absorption52keV/'\n # referencesFilenames = glob.glob(rootfolder + 'Projref/*.edf')\n # sampleFilenames = glob.glob(rootfolder + 'Proj/*.edf')\n # referencesFilenames.sort()\n # sampleFilenames.sort()\n # print(' lalalal ')\n # print (referencesFilenames)\n # print (sampleFilenames)\n\n inputImageFilename = '/Volumes/ID17/speckle/md1097/id17/Phantoms/ThreeDimensionalPhantom/OpticalFlow/dx32/dx_Speckle_Foam1_52keV_6um_xss_bis_012_0000.edf'\n data=openImage(inputImageFilename)\n print(data.dtype)\n print(data)\n outputImageFilename = '/Volumes/ID17/speckle/md1097/id17/Phantoms/ThreeDimensionalPhantom/OpticalFlowTest26Apr/dx0001_32bit.edf'\n saveEdf(data,outputImageFilename)\n print(data)\n print('At the end '+str(data.dtype))\n\n" ]
[ [ "numpy.amax", "numpy.asarray", "numpy.amin", "numpy.mean", "numpy.array" ] ]
florisdesmedt/EfficientDet
[ "a840ca1be55ad84f9aa2517114e467a574c6fea9" ]
[ "generators/common.py" ]
[ "import numpy as np\nimport random\nimport warnings\nimport cv2\nfrom tensorflow import keras\n\nfrom utils.anchors import anchors_for_shape, anchor_targets_bbox\n\n\nclass Generator(keras.utils.Sequence):\n \"\"\"\n Abstract generator class.\n \"\"\"\n\n def __init__(\n self,\n phi=0,\n image_sizes=(512, 640, 768, 896, 1024, 1280, 1408),\n misc_effect=None,\n visual_effect=None,\n batch_size=1,\n group_method='ratio', # one of 'none', 'random', 'ratio'\n shuffle_groups=True,\n ):\n \"\"\"\n Initialize Generator object.\n\n Args:\n batch_size: The size of the batches to generate.\n group_method: Determines how images are grouped together (defaults to 'ratio', one of ('none', 'random', 'ratio')).\n shuffle_groups: If True, shuffles the groups each epoch.\n image_sizes:\n \"\"\"\n self.misc_effect = misc_effect\n self.visual_effect = visual_effect\n self.batch_size = int(batch_size)\n self.group_method = group_method\n self.shuffle_groups = shuffle_groups\n self.image_size = image_sizes[phi]\n self.groups = None\n self.anchors = anchors_for_shape((self.image_size, self.image_size))\n self.current_index = 0\n\n # Define groups\n self.group_images()\n\n # Shuffle when initializing\n if self.shuffle_groups:\n random.shuffle(self.groups)\n\n def on_epoch_end(self):\n if self.shuffle_groups:\n random.shuffle(self.groups)\n self.current_index = 0\n\n def size(self):\n \"\"\"\n Size of the dataset.\n \"\"\"\n raise NotImplementedError('size method not implemented')\n\n def get_anchors(self):\n \"\"\"\n loads the anchors from a txt file\n \"\"\"\n with open(self.anchors_path) as f:\n anchors = f.readline()\n anchors = [float(x) for x in anchors.split(',')]\n # (N, 2), wh\n return np.array(anchors).reshape(-1, 2)\n\n def num_classes(self):\n \"\"\"\n Number of classes in the dataset.\n \"\"\"\n raise NotImplementedError('num_classes method not implemented')\n\n def has_label(self, label):\n \"\"\"\n Returns True if label is a known label.\n \"\"\"\n raise NotImplementedError('has_label method not implemented')\n\n def has_name(self, name):\n \"\"\"\n Returns True if name is a known class.\n \"\"\"\n raise NotImplementedError('has_name method not implemented')\n\n def name_to_label(self, name):\n \"\"\"\n Map name to label.\n \"\"\"\n raise NotImplementedError('name_to_label method not implemented')\n\n def label_to_name(self, label):\n \"\"\"\n Map label to name.\n \"\"\"\n raise NotImplementedError('label_to_name method not implemented')\n\n def image_aspect_ratio(self, image_index):\n \"\"\"\n Compute the aspect ratio for an image with image_index.\n \"\"\"\n raise NotImplementedError('image_aspect_ratio method not implemented')\n\n def load_image(self, image_index):\n \"\"\"\n Load an image at the image_index.\n \"\"\"\n raise NotImplementedError('load_image method not implemented')\n\n def load_annotations(self, image_index):\n \"\"\"\n Load annotations for an image_index.\n \"\"\"\n raise NotImplementedError('load_annotations method not implemented')\n\n def load_annotations_group(self, group):\n \"\"\"\n Load annotations for all images in group.\n \"\"\"\n annotations_group = [self.load_annotations(image_index) for image_index in group]\n for annotations in annotations_group:\n assert (isinstance(annotations,\n dict)), '\\'load_annotations\\' should return a list of dictionaries, received: {}'.format(\n type(annotations))\n assert (\n 'labels' in annotations), '\\'load_annotations\\' should return a list of dictionaries that contain \\'labels\\' and \\'bboxes\\'.'\n assert (\n 'bboxes' in annotations), '\\'load_annotations\\' should return a list of dictionaries that contain \\'labels\\' and \\'bboxes\\'.'\n\n return annotations_group\n\n def filter_annotations(self, image_group, annotations_group, group):\n \"\"\"\n Filter annotations by removing those that are outside of the image bounds or whose width/height < 0.\n \"\"\"\n # test all annotations\n for index, (image, annotations) in enumerate(zip(image_group, annotations_group)):\n # test x2 < x1 | y2 < y1 | x1 < 0 | y1 < 0 | x2 <= 0 | y2 <= 0 | x2 >= image.shape[1] | y2 >= image.shape[0]\n invalid_indices = np.where(\n (annotations['bboxes'][:, 2] <= annotations['bboxes'][:, 0]) |\n (annotations['bboxes'][:, 3] <= annotations['bboxes'][:, 1]) |\n (annotations['bboxes'][:, 0] < 0) |\n (annotations['bboxes'][:, 1] < 0) |\n (annotations['bboxes'][:, 2] <= 0) |\n (annotations['bboxes'][:, 3] <= 0) |\n (annotations['bboxes'][:, 2] > image.shape[1]) |\n (annotations['bboxes'][:, 3] > image.shape[0])\n )[0]\n\n # delete invalid indices\n if len(invalid_indices):\n warnings.warn('Image with id {} (shape {}) contains the following invalid boxes: {}.'.format(\n group[index],\n image.shape,\n annotations['bboxes'][invalid_indices, :]\n ))\n for k in annotations_group[index].keys():\n annotations_group[index][k] = np.delete(annotations[k], invalid_indices, axis=0)\n if annotations['bboxes'].shape[0] == 0:\n warnings.warn('Image with id {} (shape {}) contains no valid boxes before transform'.format(\n group[index],\n image.shape,\n ))\n return image_group, annotations_group\n\n def clip_transformed_annotations(self, image_group, annotations_group, group):\n \"\"\"\n Filter annotations by removing those that are outside of the image bounds or whose width/height < 0.\n \"\"\"\n # test all annotations\n filtered_image_group = []\n filtered_annotations_group = []\n for index, (image, annotations) in enumerate(zip(image_group, annotations_group)):\n image_height = image.shape[0]\n image_width = image.shape[1]\n # x1\n annotations['bboxes'][:, 0] = np.clip(annotations['bboxes'][:, 0], 0, image_width - 2)\n # y1\n annotations['bboxes'][:, 1] = np.clip(annotations['bboxes'][:, 1], 0, image_height - 2)\n # x2\n annotations['bboxes'][:, 2] = np.clip(annotations['bboxes'][:, 2], 1, image_width - 1)\n # y2\n annotations['bboxes'][:, 3] = np.clip(annotations['bboxes'][:, 3], 1, image_height - 1)\n # test x2 < x1 | y2 < y1 | x1 < 0 | y1 < 0 | x2 <= 0 | y2 <= 0 | x2 >= image.shape[1] | y2 >= image.shape[0]\n small_indices = np.where(\n (annotations['bboxes'][:, 2] - annotations['bboxes'][:, 0] < 10) |\n (annotations['bboxes'][:, 3] - annotations['bboxes'][:, 1] < 10)\n )[0]\n\n # delete invalid indices\n if len(small_indices):\n for k in annotations_group[index].keys():\n annotations_group[index][k] = np.delete(annotations[k], small_indices, axis=0)\n # import cv2\n # for invalid_index in small_indices:\n # x1, y1, x2, y2 = annotations['bboxes'][invalid_index]\n # label = annotations['labels'][invalid_index]\n # class_name = self.labels[label]\n # print('width: {}'.format(x2 - x1))\n # print('height: {}'.format(y2 - y1))\n # cv2.rectangle(image, (int(round(x1)), int(round(y1))), (int(round(x2)), int(round(y2))), (0, 255, 0), 2)\n # cv2.putText(image, class_name, (int(round(x1)), int(round(y1))), cv2.FONT_HERSHEY_SIMPLEX, 1.0, (0, 0, 255), 1)\n # cv2.namedWindow('image', cv2.WINDOW_NORMAL)\n # cv2.imshow('image', image)\n # cv2.waitKey(0)\n if annotations_group[index]['bboxes'].shape[0] != 0:\n filtered_image_group.append(image)\n filtered_annotations_group.append(annotations_group[index])\n else:\n warnings.warn('Image with id {} (shape {}) contains no valid boxes after transform'.format(\n group[index],\n image.shape,\n ))\n\n return filtered_image_group, filtered_annotations_group\n\n def load_image_group(self, group):\n \"\"\"\n Load images for all images in a group.\n \"\"\"\n return [self.load_image(image_index) for image_index in group]\n\n def random_visual_effect_group_entry(self, image, annotations):\n \"\"\"\n Randomly transforms image and annotation.\n \"\"\"\n # apply visual effect\n image = self.visual_effect(image)\n return image, annotations\n\n def random_visual_effect_group(self, image_group, annotations_group):\n \"\"\"\n Randomly apply visual effect on each image.\n \"\"\"\n assert (len(image_group) == len(annotations_group))\n\n if self.visual_effect is None:\n # do nothing\n return image_group, annotations_group\n\n for index in range(len(image_group)):\n # apply effect on a single group entry\n image_group[index], annotations_group[index] = self.random_visual_effect_group_entry(\n image_group[index], annotations_group[index]\n )\n\n return image_group, annotations_group\n\n def random_misc_group_entry(self, image, annotations):\n \"\"\"\n Randomly transforms image and annotation.\n \"\"\"\n assert annotations['bboxes'].shape[0] != 0\n\n # randomly transform both image and annotations\n image, boxes = self.misc_effect(image, annotations['bboxes'])\n # Transform the bounding boxes in the annotations.\n annotations['bboxes'] = boxes\n return image, annotations\n\n def random_misc_group(self, image_group, annotations_group):\n \"\"\"\n Randomly transforms each image and its annotations.\n \"\"\"\n\n assert (len(image_group) == len(annotations_group))\n\n if self.misc_effect is None:\n return image_group, annotations_group\n\n for index in range(len(image_group)):\n # transform a single group entry\n image_group[index], annotations_group[index] = self.random_misc_group_entry(image_group[index],\n annotations_group[index])\n\n return image_group, annotations_group\n\n def preprocess_group_entry(self, image, annotations):\n \"\"\"\n Preprocess image and its annotations.\n \"\"\"\n\n # preprocess the image\n image, scale, offset_h, offset_w = self.preprocess_image(image)\n\n # apply resizing to annotations too\n annotations['bboxes'] *= scale\n annotations['bboxes'][:, [0, 2]] += offset_w\n annotations['bboxes'][:, [1, 3]] += offset_h\n # print(annotations['bboxes'][:, [2, 3]] - annotations['bboxes'][:, [0, 1]])\n return image, annotations\n\n def preprocess_group(self, image_group, annotations_group):\n \"\"\"\n Preprocess each image and its annotations in its group.\n \"\"\"\n assert (len(image_group) == len(annotations_group))\n\n for index in range(len(image_group)):\n # preprocess a single group entry\n image_group[index], annotations_group[index] = self.preprocess_group_entry(image_group[index],\n annotations_group[index])\n\n return image_group, annotations_group\n\n def group_images(self):\n \"\"\"\n Order the images according to self.order and makes groups of self.batch_size.\n \"\"\"\n # determine the order of the images\n\n order = list(range(self.size()))\n if self.group_method == 'random':\n random.shuffle(order)\n elif self.group_method == 'ratio':\n order.sort(key=lambda x: self.image_aspect_ratio(x))\n\n # divide into groups, one group = one batch\n self.groups = [[order[x % len(order)] for x in range(i, i + self.batch_size)] for i in\n range(0, len(order), self.batch_size)]\n\n def compute_inputs(self, image_group, annotations_group):\n \"\"\"\n Compute inputs for the network using an image_group.\n \"\"\"\n batch_images = np.array(image_group).astype(np.float32)\n return [batch_images]\n\n def compute_targets(self, image_group, annotations_group):\n \"\"\"\n Compute target outputs for the network using images and their annotations.\n \"\"\"\n \"\"\"\n Compute target outputs for the network using images and their annotations.\n \"\"\"\n\n batches_targets = anchor_targets_bbox(\n self.anchors,\n image_group,\n annotations_group,\n self.num_classes()\n )\n return list(batches_targets)\n\n def compute_inputs_targets(self, group):\n \"\"\"\n Compute inputs and target outputs for the network.\n \"\"\"\n\n # load images and annotations\n # list\n image_group = self.load_image_group(group)\n annotations_group = self.load_annotations_group(group)\n\n # check validity of annotations\n image_group, annotations_group = self.filter_annotations(image_group, annotations_group, group)\n\n # randomly apply visual effect\n image_group, annotations_group = self.random_visual_effect_group(image_group, annotations_group)\n\n # randomly transform data\n # image_group, annotations_group = self.random_transform_group(image_group, annotations_group)\n\n # randomly apply misc effect\n image_group, annotations_group = self.random_misc_group(image_group, annotations_group)\n\n # perform preprocessing steps\n image_group, annotations_group = self.preprocess_group(image_group, annotations_group)\n\n # check validity of annotations\n image_group, annotations_group = self.clip_transformed_annotations(image_group, annotations_group, group)\n\n if len(image_group) == 0:\n return None, None\n\n # compute network inputs\n inputs = self.compute_inputs(image_group, annotations_group)\n\n # compute network targets\n targets = self.compute_targets(image_group, annotations_group)\n\n return inputs, targets\n\n def __len__(self):\n \"\"\"\n Number of batches for generator.\n \"\"\"\n\n return len(self.groups)\n\n def __getitem__(self, index):\n \"\"\"\n Keras sequence method for generating batches.\n \"\"\"\n group = self.groups[self.current_index]\n inputs, targets = self.compute_inputs_targets(group)\n while inputs is None:\n current_index = self.current_index + 1\n if current_index >= len(self.groups):\n current_index = current_index % (len(self.groups))\n self.current_index = current_index\n group = self.groups[self.current_index]\n inputs, targets = self.compute_inputs_targets(group)\n current_index = self.current_index + 1\n if current_index >= len(self.groups):\n current_index = current_index % (len(self.groups))\n self.current_index = current_index\n return inputs, targets\n\n def preprocess_image(self, image):\n image_height, image_width = image.shape[:2]\n if image_height > image_width:\n scale = self.image_size / image_height\n resized_height = self.image_size\n resized_width = int(image_width * scale)\n else:\n scale = self.image_size / image_width\n resized_height = int(image_height * scale)\n resized_width = self.image_size\n image = cv2.resize(image, (resized_width, resized_height))\n new_image = np.ones((self.image_size, self.image_size, 3), dtype=np.float32) * 128.\n offset_h = (self.image_size - resized_height) // 2\n offset_w = (self.image_size - resized_width) // 2\n new_image[offset_h:offset_h + resized_height, offset_w:offset_w + resized_width] = image.astype(np.float32)\n new_image /= 255.\n mean = [0.485, 0.456, 0.406]\n std = [0.229, 0.224, 0.225]\n new_image[..., 0] -= mean[0]\n new_image[..., 1] -= mean[1]\n new_image[..., 2] -= mean[2]\n new_image[..., 0] /= std[0]\n new_image[..., 1] /= std[1]\n new_image[..., 2] /= std[2]\n return new_image, scale, offset_h, offset_w\n\n def get_augmented_data(self, group):\n \"\"\"\n Compute inputs and target outputs for the network.\n \"\"\"\n\n # load images and annotations\n # list\n image_group = self.load_image_group(group)\n annotations_group = self.load_annotations_group(group)\n\n # check validity of annotations\n image_group, annotations_group = self.filter_annotations(image_group, annotations_group, group)\n\n # randomly apply visual effect\n image_group, annotations_group = self.random_visual_effect_group(image_group, annotations_group)\n\n # randomly transform data\n # image_group, annotations_group = self.random_transform_group(image_group, annotations_group)\n\n # randomly apply misc effect\n image_group, annotations_group = self.random_misc_group(image_group, annotations_group)\n\n # perform preprocessing steps\n image_group, annotations_group = self.preprocess_group(image_group, annotations_group)\n\n # check validity of annotations\n image_group, annotations_group = self.clip_transformed_annotations(image_group, annotations_group, group)\n\n return image_group, annotations_group\n" ]
[ [ "numpy.clip", "numpy.ones", "numpy.delete", "numpy.array", "numpy.where" ] ]
bxkftechteam/onnx-ml-demo
[ "91cd2b5674217233585870ff2b89c31a6cd2b960", "91cd2b5674217233585870ff2b89c31a6cd2b960" ]
[ "converter/inference_hmm.py", "train/infer.py" ]
[ "#!/usr/bin/env python3\n\n\"\"\"Run inference on HMM models\"\"\"\n\nimport sys\nfrom os import path\nimport numpy as np\nimport onnxruntime as ort\n\n\nif len(sys.argv) < 3:\n print(\"usage: {} <onnx_model_path> <N>\".format(\n sys.argv[0]))\n exit(1)\n\nonnx_model_path = sys.argv[1]\nN = int(sys.argv[2])\nfeatures = np.random.randint(low=0, high=6, size=N).astype(np.int32)\n\nproject_dir = path.dirname(path.dirname(path.abspath(__file__)))\nshared_library_path = path.join(project_dir, \"cpp/libviterbi.so\")\nsession_options = ort.SessionOptions()\nsession_options.register_custom_ops_library(shared_library_path)\n\nsess = ort.InferenceSession(onnx_model_path, session_options)\nres = sess.run(None, {\"input_states\": features})\nprint(res)\n", "#!/usr/bin/env python3\n\n\"\"\"Run inference using phone-play models\"\"\"\n\nfrom os import path\nimport pickle\nimport numpy as np\n\nfrom map_pred import map_pred\n\n\ndef infer(X, scaler, clf, hmm):\n X = scaler.transform(X)\n pred_probs = clf.predict_proba(X)[:, 1]\n pred_labels = np.array([map_pred(x) for x in pred_probs], dtype=np.int64)\n return hmm.predict(pred_labels.reshape(-1, 1))\n\n\nif __name__ == '__main__':\n project_dir = path.dirname(path.dirname(path.abspath(__file__)))\n scaler = pickle.load(open(path.join(project_dir, \"models/scaler.pkl\"), \"rb\"))\n clf = pickle.load(open(path.join(project_dir, \"models/clf.pkl\"), \"rb\"))\n hmm = pickle.load(open(path.join(project_dir, \"models/hmm.pkl\"), \"rb\"))\n dataset = pickle.load(open(path.join(project_dir, \"data/synthetic.npy\"), \"rb\"))\n features = np.vstack([d[\"X\"] for d in dataset])\n print(infer(features, scaler, clf, hmm))\n" ]
[ [ "numpy.random.randint" ], [ "numpy.vstack" ] ]
Armanfard-Lab/DSSL
[ "89c38ea299d4920c77fb80496b16be67c99bbea8" ]
[ "Code/train.py" ]
[ "\r\nfrom torch.utils.data import Dataset\r\nimport torch\r\nimport torch.nn as nn\r\nimport torchvision.datasets as dset\r\nimport torchvision.transforms as transforms\r\n\r\nfrom DSSL import DSSL\r\nfrom Network import AutoEncoder\r\n\r\nbatch_size = 500\r\ndataset_size = 70000\r\ntrain_set = dset.MNIST(root='/home/mrsadeghi/Spectral_clustering_network', train=True,\r\n transform=transforms.ToTensor(), download=True)\r\ntest_set = dset.MNIST(root='/home/mrsadeghi/Spectral_clustering_network', train=False,\r\n transform=transforms.ToTensor(), download=True)\r\n\r\nkwargs = {'num_workers': 1}\r\n\r\ntrain1 = torch.utils.data.ConcatDataset([train_set, test_set])\r\ndata_loader = torch.utils.data.DataLoader(\r\n dataset=train1,\r\n batch_size=batch_size,\r\n shuffle=True, **kwargs)\r\n\r\n\r\ndef weights_init(m):\r\n if isinstance(m, nn.Conv2d):\r\n torch.nn.init.xavier_uniform_(m.weight.data)\r\n if m.bias is not None:\r\n torch.nn.init.zeros_(m.bias.data)\r\n\r\n # torch.nn.init.xavier_uniform(m.bias.data)\r\n if isinstance(m, nn.Linear):\r\n torch.nn.init.xavier_uniform_(m.weight.data)\r\n if m.bias is not None:\r\n torch.nn.init.zeros_(m.bias.data)\r\n\r\n\r\n\r\nif __name__ == '__main__':\r\n AE = AutoEncoder().cuda()\r\n AE.apply(weights_init)\r\n\r\n\r\n batch_size = 500\r\n pretraining_epoch = 0\r\n MaxIter = 200\r\n num_cluster = 10\r\n m = 1.5\r\n T = 2\r\n latent_size = 10\r\n dataset_name = 'MNIST'\r\n\r\n DSSL = DSSL(AE, data_loader, dataset_size, batch_size=batch_size, pretraining_epoch =pretraining_epoch,\r\n MaxIter = MaxIter, num_cluster = num_cluster, m = m, T=T, latent_size = latent_size, dataset_name = dataset_name)\r\n\r\n if pretraining_epoch!= 0:\r\n DSSL.pretrain()\r\n if MaxIter != 0:\r\n DSSL.train()\r\n\r\n" ]
[ [ "torch.nn.init.zeros_", "torch.utils.data.ConcatDataset", "torch.utils.data.DataLoader", "torch.nn.init.xavier_uniform_" ] ]
Iamlegend-Imani/airbnb-plotly-dash-app
[ "837c93cded2f633d9ba9d7b0c8c75fd6a6c7d2a3" ]
[ "pages/predictionsbackup.py" ]
[ "# Imports from 3rd party libraries\nimport dash\nimport dash_bootstrap_components as dbc\nimport dash_core_components as dcc\nimport dash_html_components as html\nfrom dash.dependencies import Input, Output, State\nimport dash_daq as daq\nimport pandas as pd\nfrom datetime import date\nfrom tensorflow import keras\nimport numpy as np\nimport pickle\nimport sklearn\n\n# Imports from this application\nfrom app import app\nfrom pred_lists import zip_code, neighborhood, amenities, property\nfrom pred_lists import bathrooms_marks, amenities_marks\nfrom airbnb_model import *\nfrom model_tools_class import mt\n\n\n# load model trained on airbnb data\nmodel = keras.models.load_model('airbnb_model')\noe = mt.get_oe()\nprint('Model loaded successfully')\n\n\nmodel_columns = [\n 'property_type',\n 'room_type',\n 'bed_type',\n 'cancellation_policy',\n 'city',\n 'host_identity_verified',\n 'instant_bookable',\n 'neighbourhood',\n 'zipcode',\n 'amenities',\n 'accommodates',\n 'bathrooms',\n 'bedrooms',\n 'beds',\n 'host_since_days'\n]\n\n\n# create input form for User\nrow1 = html.Div(\n [\n # 1st Row. Introductory Marks\n dbc.Row(dbc.Col(html.Div('''Welcome to the Price Prediction Page! Fill out the form as\n accurately as possible, and we will compare similar\n properties (based on amenities and location) and\n provide you with the best estimate for your daily\n rental price on AirBnB.''', className='mb-4'))),\n # 2nd Row. Includes Property Type, Room Type\n dbc.Row(\n [\n dbc.Col(\n [\n dcc.Markdown(\"##### Property Type\", className='mb-1'),\n dcc.Dropdown(\n id='property',\n options=property.property_type,\n value='House',\n className='mb-4',\n style=dict(\n width='60%',\n verticalAlign=\"middle\"\n )\n ),\n ],\n style=dict(display='flex')\n ),\n dbc.Col(\n [\n dcc.Markdown(\"##### Room Type\", className='mb-1'),\n dcc.Dropdown(\n id='room',\n options=[\n {'label': 'Entire Home/Apartment',\n 'value': 'Entire home/apt'},\n {'label': 'Private Room', 'value': 'Private room'},\n {'label': 'Shared room', 'value': 'Shared room'}\n ],\n value='Entire home/apt',\n className='mb-4',\n ),\n ],\n ),\n ]\n ),\n # 3rd Row. Includes Accomadates, number of bathrooms\n dbc.Row(\n [\n dbc.Col(\n [\n dcc.Markdown(\"##### Accomadates\", className='mb-1'),\n daq.NumericInput(\n id='accomadates',\n min=1,\n max=16,\n value=1,\n className='mb-4',\n ),\n ],\n ),\n dbc.Col(\n [\n dcc.Markdown(\"##### Number of Bathrooms\",\n className='mb-1'),\n dcc.Slider(\n id='bathrooms',\n min=0,\n max=8,\n step=0.5,\n marks=bathrooms_marks.bathroom_marks,\n value=1,\n className='mb-4',\n ),\n ],\n ),\n ]\n ),\n # 4th Row. Includes Bedrooms, Beds\n dbc.Row(\n [\n dbc.Col(\n [\n dcc.Markdown(\"##### Number of Bedrooms\",\n className='mb-1'),\n daq.NumericInput(\n id='bedrooms',\n min=0,\n max=10,\n value=1,\n className='mb-4',\n ),\n ],\n ),\n dbc.Col(\n [\n dcc.Markdown(\"##### Number of Beds\", className='mb-1'),\n daq.NumericInput(\n id='beds',\n min=0,\n max=18,\n value=1,\n className='mb-4',\n ),\n ],\n ),\n ]\n ),\n # 5th Row. Includes bed_type, cancellation_policy\n dbc.Row(\n [\n dbc.Col(\n [\n dcc.Markdown(\"##### Bed Type\", className='mb-1'),\n dcc.Dropdown(\n id='bedtype',\n options=[\n {'label': 'Real Bed', 'value': 'Real Bed'},\n {'label': 'Futon', 'value': 'Futon'},\n {'label': 'Pull-out Sofa',\n 'value': 'Pull-out Sofa'},\n {'label': 'Airbed', 'value': 'Airbed'},\n {'label': 'Couch', 'value': 'Couch'},\n ],\n value='Real Bed',\n className='mb-4',\n ),\n ],\n ),\n dbc.Col(\n [\n dcc.Markdown(\"##### Cancellation Policy\",\n className='mb-1'),\n dcc.Dropdown(\n id='cancellation',\n options=[\n {'label': 'Strict', 'value': 'strict'},\n {'label': 'Flexible', 'value': 'flexible'},\n {'label': 'Moderate', 'value': 'moderate'},\n {'label': 'Super Strict 30',\n 'value': 'super_strict_30'},\n {'label': 'Super Strict 60',\n 'value': 'super_strict_60'},\n ],\n value='flexible',\n className='mb-4',\n ),\n ],\n ),\n ]\n ),\n # 6th Row. Includes city\n dbc.Row(\n [\n dbc.Col(\n [\n dcc.Markdown(\"##### City\", className='mb-1'),\n dcc.Dropdown(\n id='city',\n options=[\n {'label': 'New York City', 'value': 'NYC'},\n {'label': 'Los Angeles', 'value': 'LA'},\n {'label': 'San Francisco', 'value': 'SF'},\n {'label': 'Washington DC', 'value': 'DC'},\n {'label': 'Boston', 'value': 'Boston'},\n {'label': 'Chicago', 'value': 'Chicago'},\n ],\n placeholder=\"Select a city\",\n className='mb-4',\n ),\n ],\n ),\n ]\n ),\n # 7th Row. Includes host_identity_verified, instant_bookable, host_since_days\n dbc.Row(\n [\n dbc.Col(\n [\n dcc.Markdown(\n \"##### You Are a Verified Host\", className='mb-1'),\n dcc.Dropdown(\n id='bookable',\n options=[\n {'label': 'True', 'value': 'True'},\n {'label': 'False', 'value': 'False'},\n ],\n value='True',\n className='mb-4',)\n ]\n ),\n dbc.Col(\n [\n dcc.Markdown(\"##### Is Instantly Bookable\",\n className='mb-1'),\n dcc.Dropdown(\n id='verified_host',\n options=[\n {'label': 'True', 'value': 'True'},\n {'label': 'False', 'value': 'False'},\n ],\n value='True',\n className='mb-4')\n ]\n ),\n dbc.Col(\n [\n dcc.Markdown(\"##### Host Start Date\",\n className='mb-1'),\n dcc.DatePickerSingle(\n id='days_host',\n date=date(2019, 1, 1)\n )\n ],\n ),\n ]\n ),\n # 8th Row. Includes neighbourhood, zipcode\n dbc.Row(\n [\n dbc.Col(\n [\n dcc.Markdown(\"##### Neighborhood\", className='mb-1'),\n dcc.Dropdown(\n id='neighborhood',\n options=neighborhood.neighborhoods,\n placeholder=\"Select a Neighborhood\",\n className='mb-4',\n ),\n ],\n ),\n dbc.Col(\n [\n dcc.Markdown(\"##### Zipcode\", className='mb-1'),\n dcc.Dropdown(\n id='zipcode',\n options=zip_code.total_zip,\n placeholder=\"Choose a ZipCode\",\n className='mb-4',\n ),\n ],\n ),\n ]\n ),\n # 9th Row. Includes amenities\n dbc.Row(\n [\n dbc.Col(\n [\n dcc.Markdown(\"##### Amenities\", className='mb-1'),\n dcc.Slider(\n id='amenities',\n min=0,\n max=39,\n step=1,\n value=1,\n marks=amenities_marks.amenity_marks,\n className='mb-4',\n ),\n ],\n ),\n ]\n ),\n ]\n)\n\n\n# output section that returns estimated price based off inputs\nrow2 = html.Div(\n dbc.Col(\n [\n html.H2('Price Estimation', className='mb-5'),\n ]\n )\n)\n\n\nbutton = html.Div(\n [\n dbc.Button(\"Predict Price\", id=\"example-button\", color='primary',\n className=\"mr-2\"),\n html.Div(id='container-button-timestamp'),\n html.Span(id=\"example-output\",\n style={\"vertical-align\": \"middle\"}),\n ]\n)\n\n\n@app.callback(\n Output(\"container-button-timestamp\",\n \"children\"), [Input(\"example-button\", 'n_clicks')],\n [\n State('property', component_property='value'), State(\n 'room', component_property='value'),\n State('accomadates', component_property='value'), State(\n 'bathrooms', component_property='value'),\n State('bedrooms', component_property='value'), State(\n 'beds', component_property='value'),\n State('bedtype', component_property='value'), State(\n 'cancellation', component_property='value'),\n State('city', component_property='value'), State(\n 'verified_host', component_property='value'),\n State('bookable', component_property='value'), State(\n 'days_host', 'date'),\n State('neighborhood', component_property='value'), State(\n 'zipcode', component_property='value'),\n State('amenities', component_property='value')\n ]\n)\ndef on_button_click(n, property, room, accomadates, bathrooms, bedrooms, beds, bedtype, cancellation, city, verified_host, bookable, days_host, neighborhood, zipcode, amenities):\n '''\n on_button_click function passes information from the model on clicl\n '''\n if n is None:\n return \"Not clicked.\"\n else:\n return predict(property, room, accomadates, bathrooms, bedrooms, beds, bedtype, cancellation, city, verified_host, bookable, days_host, neighborhood, zipcode, amenities)[0]\n\n\ndef predict(\n property, room, accomadates, bathrooms,\n bedrooms, beds, bedtype, cancellation,\n city, verified_host, bookable,\n days_host, neighborhood, zipcode, amenities\n):\n '''\n predict function creates a dataframe and runs the dataframe in the\n get_prediction function\n '''\n df = pd.DataFrame(\n columns=[\n 'property_type', 'room_type', 'accommodates', 'bathrooms',\n 'bedrooms', 'beds', 'bed_type', 'cancellation_policy',\n 'city', 'host_identity_verified', 'instant_bookable',\n 'host_since_days', 'neighbourhood', 'zipcode', 'amenities'\n ],\n data=[\n [\n property, room, accomadates, bathrooms,\n bedrooms, beds, bedtype, cancellation,\n city, verified_host, bookable,\n days_host, neighborhood, zipcode, amenities\n ]\n ]\n )\n return get_prediction(df)\n\n\ndef get_confirm_df(input_list_objects, input_list_numbers, string_value_list):\n '''\n function to create confirmation df for viewing\n purposes for debugging\n '''\n df_rows = []\n for i in np.arange(9):\n df_rows.append(\n (model_columns[i], string_value_list[i], input_list_objects[0][i]))\n for i in np.arange(9, len(model_columns)):\n df_rows.append(\n (model_columns[i], input_list_numbers[i-9], input_list_numbers[i-9]))\n confirm_df = pd.DataFrame(\n df_rows, columns=['Variable', 'Value', 'Encoded'])\n return confirm_df\n\n\ndef get_prediction(df):\n '''\n function takes in a dataframe, transforms data, and runs \n data into a sequential model to return a prediction \n '''\n string_variable_list = ['property_type', 'room_type', 'bed_type',\n 'cancellation_policy', 'city', 'host_identity_verified',\n 'instant_bookable', 'neighbourhood', 'zipcode']\n number_variable_list = [\n 'amenities', 'accommodates', 'bathrooms',\n 'beds', 'bedrooms', 'host_since_days'\n ]\n\n number_value_list = []\n string_value_list = []\n\n for x in string_variable_list:\n string_value_list.append(df[x])\n for x in number_variable_list:\n if x != 'host_since_days':\n number_value_list.append(df[x].values[0])\n else:\n number_value_list.append(mt.get_days(df[x].values[0]))\n\n string_vectorized = oe.transform(\n np.array(string_value_list).reshape(1, -1))\n whole_input_vector = string_vectorized[0].tolist() + number_value_list\n confirm_df = get_confirm_df(\n string_vectorized, number_value_list, string_value_list)\n\n prediction = model.predict(np.array(whole_input_vector).reshape(1, -1))\n return prediction[0][0], confirm_df\n\n\ndef list_to_string(text):\n '''function to convert a list to a string'''\n str1 = \"\"\n for x in text:\n str1 += str(x)\n return str1\n\n\ndef get_confirm_df(input_list_objects, input_list_numbers, string_value_list):\n '''\n function to create confirmation df for viewing\n purposes for debugging\n '''\n df_rows = []\n for i in np.arange(9):\n df_rows.append(\n (model_columns[i], string_value_list[i], input_list_objects[0][i]))\n for i in np.arange(9, len(model_columns)):\n df_rows.append(\n (model_columns[i], input_list_numbers[i-9], input_list_numbers[i-9]))\n confirm_df = pd.DataFrame(\n df_rows, columns=['Variable', 'Value', 'Encoded'])\n return confirm_df\n\n\n# layout of the page\nlayout = dbc.Row([row1, row2, button])\n" ]
[ [ "tensorflow.keras.models.load_model", "numpy.array", "numpy.arange", "pandas.DataFrame" ] ]
bradkav/PBH_bounds
[ "b534defe718c2a40b1d8a66c9bdd6987e9c2a9f8" ]
[ "PlotPBHbounds.py" ]
[ "import numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib as mpl\nimport argparse\n\n\n#Specify the plot style\nmpl.rcParams.update({'font.size': 16,'font.family':'serif'})\nmpl.rcParams['xtick.major.size'] = 7\nmpl.rcParams['xtick.major.width'] = 1\nmpl.rcParams['xtick.minor.size'] = 3.5\nmpl.rcParams['xtick.minor.width'] = 1\nmpl.rcParams['ytick.major.size'] = 7\nmpl.rcParams['ytick.major.width'] = 1\nmpl.rcParams['ytick.minor.size'] = 3.5\nmpl.rcParams['ytick.minor.width'] = 1\nmpl.rcParams['xtick.direction'] = 'in'\nmpl.rcParams['ytick.direction'] = 'in'\nmpl.rcParams['lines.linewidth'] = 1.5\nmpl.rcParams['xtick.top'] = True\nmpl.rcParams['ytick.right'] = True\nmpl.rcParams['font.family'] = 'serif'\nmpl.rc('text', usetex=True)\n\nmpl.rcParams['legend.edgecolor'] = 'inherit'\n\n\n\n# Bounds taken from 1801.00808\n\n#General options\nplot_SGWB_range = True\n\n#Default values, overridden if you pass in command line arguments\nlistfile_default = \"listfiles/bounds_all.txt\" \noutfile_default = \"plots/PBH_bounds.pdf\"\n\n#Load in the filename with the list of bounds and the output filename\nparser = argparse.ArgumentParser(description='...')\nparser.add_argument('-lf','--listfile', help='File containing list of bounds to include',\n type=str, default=listfile_default)\nparser.add_argument('-of','--outfile', help='Filename (with extension) of output plot', \n type=str, default=outfile_default)\n \nparser.add_argument('-dark', '--dark', dest='dark', action='store_true')\nparser.set_defaults(dark=False)\n\nargs = parser.parse_args()\nlistfile = args.listfile\noutfile = args.outfile\n\nDARKMODE = args.dark\n\nalpha_val = 0.15\nif (DARKMODE):\n plt.style.use('dark_background')\n alpha_val = 0.35\n\nbounds = np.loadtxt(listfile, usecols=(0,), dtype=str)\ncolors = np.loadtxt(listfile, usecols=(1,), dtype=str)\nlines = np.loadtxt(listfile, usecols=(2,), dtype=str)\nxlist = np.loadtxt(listfile, usecols=(3,))\nylist = np.loadtxt(listfile, usecols=(4,))\nanglist = np.loadtxt(listfile, usecols=(5,))\n\nif (DARKMODE):\n for i, col in enumerate(colors):\n if (col == \"C1\"):\n colors[i] = \"C5\"\n if (col == \"C2\"):\n colors[i] = \"C6\"\n\ndef addConstraint(boundID, col='blue',x = 1e-30,y=1e-4,ang=0, linestyle='-'):\n m, f = np.loadtxt('bounds/' + boundID + '.txt', unpack=True)\n if (boundID != \"OGLE?\"):\n plt.fill_between(m , np.clip(f, 0,1), 1, alpha=alpha_val, color=col)\n linewidth = 1.0\n if (boundID in [\"Microlensing\", \"Evaporation\"]):\n linewidth=2.0\n plt.plot(m, np.clip(f, 0,1), color=col, lw=linewidth, linestyle=linestyle)\n \n if (x > 1e-20):\n plt.text(x, y, boundID, rotation=ang, fontsize=12, ha='center', va='center')\n\ndef addSIGWprojections(col='red', linestyle='--'):\n plt.fill_between([6.6e-14, 6.6e-12], 5e-3, 1, color=col, alpha = alpha_val, linewidth=0)\n #plt.plot([6.6e-14, 6.6e-12], [3e-3, 3e-3], 0, color='red', linestyle='--')\n plt.plot([6.6e-14, 6.6e-14], [5e-3, 1], color = col, linestyle=linestyle, lw=1.0)\n plt.plot([6.6e-12, 6.6e-12], [5e-3, 1], color = col, linestyle=linestyle, lw=1.0)\n \n #Rough indication of sensitive mass ranges: see e.g. https://arxiv.org/abs/1810.12218\n plt.text(8e-13, 7e-3, \"LISA\",fontsize=12, ha='center', va='bottom', rotation = 90)\n\n #AI/DECIGO\n plt.fill_between([1e-17, 1e-15], 5e-3, 1, color=col, alpha = alpha_val, linewidth=0)\n plt.plot([1e-17, 1e-17], [5e-3, 1], color = col, linestyle=linestyle, lw=1.0)\n plt.plot([1e-15, 1e-15], [5e-3, 1], color = col, linestyle=linestyle, lw=1.0)\n #plt.plot([1e-17, 1e-15], [3e-3, 3e-3], 0, color='red', linestyle='--')\n plt.text(1e-16, 7e-3, \"DECIGO/AI\",fontsize=12, ha='center', va='bottom', rotation = 90)\n \n plt.text(1e-14, 4e-3, \"SIGWs\", fontsize=12, ha='center', va='center')\n\n#------------------------------------------- \n \nplt.figure(figsize=(8,5))\n\nax = plt.gca()\nax.set_xscale('log')\nax.set_yscale('log')\nax.xaxis.tick_bottom()\nax.xaxis.set_tick_params(pad=5)\n\nfor i in range(len(bounds)): \n if (bounds[i] == \"SIGWs\"):\n addSIGWprojections(col=colors[i], linestyle=lines[i])\n else:\n addConstraint(bounds[i], col = colors[i], x = xlist[i], y = ylist[i], ang=anglist[i], linestyle=lines[i])\n\n\n\n#Plotting stuff\nplt.axhspan(1, 1.5, facecolor='grey', alpha=0.5)\n \nplt.ylim(1e-4, 1.5)\nplt.xlim(1e-18, 1e4)\n \nax.set_xticks(np.logspace(-18, 4, 23),minor=True)\nax.set_xticklabels([], minor=True)\n \nax.set_xlabel(r'$M_\\mathrm{PBH}$ [$M_\\odot$]')\nplt.ylabel(r'$f_\\mathrm{PBH} = \\Omega_\\mathrm{PBH}/\\Omega_\\mathrm{DM}$')\n\nax_top = ax.twiny()\nax_top.xaxis.tick_top()\nax_top.set_xscale('log')\nax_top.set_xlim(ax.get_xlim())\nax_top.set_xlabel(r'$M_\\mathrm{PBH}$ [g]', labelpad=7)\n\ng_ticks_minor = np.geomspace(1e15, 1e37, 23)\ng_ticks = g_ticks_minor[::3]\ng_to_Msun = 1/1.989e+33\n\ng_tick_labels = [r\"$10^{\" + str(int(np.log10(x))) +\"}$\" for x in g_ticks]\n\nax_top.set_xticks(g_ticks*g_to_Msun)\nax_top.set_xticklabels(g_tick_labels)\nax_top.xaxis.set_tick_params(pad=0)\n\nax_top.set_xticks(g_ticks_minor*g_to_Msun,minor=True)\nax_top.set_xticklabels([],minor=True)\n\n\nplt.savefig(outfile, bbox_inches='tight')\n \nplt.show()\n\n\n" ]
[ [ "matplotlib.pyplot.plot", "matplotlib.pyplot.gca", "numpy.clip", "matplotlib.pyplot.axhspan", "matplotlib.pyplot.text", "matplotlib.pyplot.style.use", "matplotlib.pyplot.figure", "numpy.logspace", "matplotlib.pyplot.ylim", "matplotlib.pyplot.savefig", "numpy.log10", "matplotlib.rcParams.update", "matplotlib.pyplot.fill_between", "matplotlib.pyplot.show", "matplotlib.rc", "matplotlib.pyplot.ylabel", "numpy.geomspace", "matplotlib.pyplot.xlim", "numpy.loadtxt" ] ]
Ros522/lazy-bot-tester
[ "30e7f50bcd7ca77e0ec9e11d069e047318ec2bdb" ]
[ "lazybot/collector/exchanges/bitflyer.py" ]
[ "import asyncio\nimport json\nfrom datetime import datetime\n\nimport numpy as np\nimport websockets\n\n\nclass BitFlyer:\n def __init__(self, tag=\"BITFLYERFX\", channel='lightning_executions_FX_BTC_JPY', retry=1, loop=None):\n self.loop = loop or asyncio.get_event_loop()\n self.tag = tag\n self.channel = channel\n self.task = None\n self.retry = retry\n self.queue = asyncio.Queue()\n\n async def __aenter__(self):\n self.task = asyncio.ensure_future(self.run())\n return self\n\n async def __aexit__(self, exc_type, exc, tb):\n self.task.cancel()\n\n async def run(self):\n while True:\n try:\n async with websockets.connect('wss://ws.lightstream.bitflyer.com/json-rpc') as ws:\n await ws.send(json.dumps({\"method\": \"subscribe\", \"params\": {\"channel\": self.channel}}))\n while True:\n data = await ws.recv()\n self.on_message(json.loads(data))\n except asyncio.CancelledError:\n raise\n except Exception as e:\n print(e)\n # retry after 1 sec\n await asyncio.sleep(self.retry)\n\n async def recv(self):\n return await self.queue.get()\n\n def on_message(self, message):\n from lazybot.collector.core import Tick\n\n if message['method'] == \"channelMessage\":\n tick = message['params']['message']\n now = np.datetime64(datetime.utcnow())\n\n # 同一タイムスタンプごとに集計\n _agged_tick = {}\n for t in tick:\n timestamp = np.datetime64(t[\"exec_date\"])\n _agged_tick[timestamp] = {\n \"timestamp\": timestamp,\n \"side\": t[\"side\"],\n \"price\": t[\"price\"],\n \"size\": _agged_tick[timestamp][\"size\"] + t[\"size\"] if timestamp in _agged_tick else t[\"size\"]\n }\n for item in _agged_tick.values():\n latency = (now - item[\"timestamp\"]).astype(np.int64) / 1000000000\n if len(item[\"side\"]) > 0:\n self.queue.put_nowait(\n Tick(timestamp=int(item[\"timestamp\"].astype('datetime64[ns]').astype('int')),\n code=self.tag,\n side=str(item[\"side\"]),\n price=float(item[\"price\"]),\n size=float(item[\"size\"]),\n latency=float(latency)\n )\n )\n\n @classmethod\n def connect(cls, **kwargs):\n return cls(**kwargs)\n" ]
[ [ "numpy.datetime64" ] ]
Miyoshichi/SimLight
[ "9f01dee5e324026bfdcdbe9f83cd29bbd447adda" ]
[ "SimLight/plottools/slidetools.py" ]
[ "# -*- coding: utf-8 -*-\n\n\"\"\"\nCreated on Nov 10, 2020\n@author: Zhou Xiang\n\"\"\"\n\nimport math\nfrom matplotlib.pyplot import bar\nimport numpy as np\nimport matplotlib\nimport matplotlib.pyplot as plt\nimport matplotlib.patches as patches\nfrom mpl_toolkits.mplot3d import Axes3D\nfrom mpl_toolkits.axes_grid1 import make_axes_locatable, axes_size\nfrom mpl_toolkits.axes_grid1.inset_locator import inset_axes\nfrom mpl_toolkits.axes_grid1.anchored_artists import AnchoredSizeBar\nfrom matplotlib_scalebar.scalebar import ScaleBar\nfrom numpy.lib.function_base import average\nimport scipy.interpolate\n\nimport SimLight as sl\nfrom ..utils import pv, rms, return_circle_aperature\nfrom ..calc import phase, intensity, psf, zernike_coeffs\nfrom ..units import *\n\nnp.random.seed(235)\n\n\ndef slide_plot_wavefront(field, noise=False, mask_r=None, dimension=2,\n unit='mm', title='', return_data=False, **kwargs):\n \"\"\"Plot the wavefront.\n\n Plot the wavefront of light field using matplotlib.\n\n Parameters\n ----------\n field : SimLight.Field\n A light field.\n mask_r : float, optional, from 0 to 1, default None\n Radius of a circle mask.\n dimension : int, optional, {1, 2, 3}, default 2\n Dimension of the showing wavefront, where\n 2 for surface,\n 3 for 3d.\n unit : str, optional, {'m', 'cm', 'mm', 'um', 'µm', 'nm'}, default 'µm'\n Unit used for FOV.\n title : str, optional\n Title of the figure.\n return_data : bool, optional, default False\n Return the wavefront data or not.\n\n Returns\n ----------\n phase_ : numpy.ndarray\n Wavefront data.\n \"\"\"\n unwrap = True\n\n field = sl.Field.copy(field)\n\n # check of input parameters\n if mask_r:\n if mask_r > 1 or mask_r < 0:\n raise ValueError('Invalid radius of circle mask.')\n if dimension:\n if dimension < 1 or dimension > 3 or type(dimension) is not int:\n raise ValueError('Invalid dimension.')\n if isinstance(field, sl.Field) is True:\n wavelength = field.wavelength\n size = field.size\n N = field.N\n phase_ = phase(field, unwrap=unwrap)\n lambdaflag = False\n elif isinstance(field, list) is True:\n if len(field) == 6:\n wavelength = field[0]\n size = field[1]\n N = field[2]\n phase_ratio = field[4]\n phase_ = phase(field[3],\n unwrap=unwrap,\n phase_ratio=phase_ratio)\n lambdaflag = False\n elif len(field) == 5:\n wavelength = field[0]\n size = field[1]\n N = field[2]\n phase_ = field[3]\n lambdaflag = True\n else:\n raise ValueError('Invalid light field.')\n else:\n raise ValueError('Invalid light field.')\n\n # unit\n units = {\n 'm': m,\n 'cm': cm,\n 'mm': mm,\n 'um': µm,\n 'µm': µm,\n 'nm': nm\n }\n unit_ = units[unit]\n\n if lambdaflag is False:\n phase_ = wavelength * phase_ / (2 * np.pi) / µm\n if noise is True:\n noise_data = np.random.rand(N, N) * 1e-1\n phase_ += noise_data\n\n if mask_r:\n _, _, norm_radius = return_circle_aperature(phase_, mask_r)\n max_value = np.max(phase_[norm_radius <= mask_r])\n min_value = np.min(phase_[norm_radius <= mask_r])\n PV = 'P-V: ' + str(round(pv(phase_, mask=True), 3)) + ' λ'\n RMS = 'RMS: ' + str(round(rms(phase_, mask=True), 3)) + ' λ'\n else:\n max_value = np.max(phase_)\n min_value = np.min(phase_)\n PV = 'P-V: ' + str(round(pv(phase_), 3)) + ' λ'\n RMS = 'RMS: ' + str(round(rms(phase_), 3)) + ' λ'\n\n if dimension == 2:\n fig = plt.figure()\n length = np.linspace(-size / 2, size / 2, phase_.shape[0])\n X, Y = np.meshgrid(length, length)\n extent = [-size / 2, size / 2, -size / 2, size / 2]\n ax = fig.add_subplot(111)\n im = ax.imshow(phase_, cmap='rainbow', extent=extent,\n vmin=min_value, vmax=max_value)\n if mask_r:\n mask = patches.Circle([0, 0], size * mask_r / 2,\n fc='none', ec='none',)\n ax.add_patch(mask)\n im.set_clip_path(mask)\n radius = np.sqrt(X**2 + Y**2)\n phase_[radius > size * mask_r / 2] = 0\n xticks = np.linspace(-size / 2, size / 2, 5)\n yticks = np.linspace(-size / 2, size / 2, 5)\n ax.set_xticks(xticks)\n ax.set_yticks(yticks)\n xticklabels = ax.get_xticks() / unit_\n yticklabels = ax.get_yticks() / unit_\n ax.set_xticklabels(xticklabels.astype(np.float16))\n ax.set_yticklabels(yticklabels.astype(np.float16))\n ax.set_xlabel('Size [%s]' % unit)\n ax.text(0.05, 0.95, PV, fontsize=12, horizontalalignment='left',\n transform=ax.transAxes)\n ax.text(0.05, 0.90, RMS, fontsize=12, horizontalalignment='left',\n transform=ax.transAxes)\n if kwargs['colorbar']:\n fig.colorbar(im)\n if title:\n fig.suptitle(title)\n elif dimension == 3:\n plt.rcParams.update({\n 'grid.linewidth': 0.5,\n 'grid.color': [0, 0, 0, 0.1],\n })\n length = np.linspace(-size / 2, size / 2, phase_.shape[0])\n X, Y = np.meshgrid(length, length)\n upper_value = max_value + (max_value - min_value) / 2\n lower_value = min_value - (max_value - min_value) / 5\n rccount = 100\n if mask_r:\n radius = np.sqrt(X**2 + Y**2)\n phase_[radius > size * mask_r / 2] = np.nan\n fig = plt.figure(figsize=(8, 5))\n if kwargs['colorbar']:\n ax = fig.add_subplot(111)\n caxins = inset_axes(ax,\n width='2.5%',\n height='85%',\n loc='right',\n bbox_to_anchor=(-0.075, -0.025, 1, 1),\n bbox_transform=ax.transAxes,\n borderpad=0)\n ax = fig.add_subplot(111, projection='3d')\n if PV != 'P-V: 0.0 λ' and RMS != 'RMS: 0.0 λ' and kwargs['cont']:\n cset = ax.contourf(X, Y, phase_,\n zdir='z',\n offset=lower_value,\n cmap='rainbow', alpha=0.5)\n im = ax.plot_surface(X, Y, phase_,\n rcount=rccount, ccount=rccount,\n cmap='rainbow', alpha=0.9,\n vmin=min_value, vmax=max_value)\n ax.view_init(elev=50, azim=45)\n if kwargs['labels']:\n ax.set_zlim(lower_value, upper_value)\n xticks = np.linspace(-size / 2, size / 2, 5)\n yticks = np.linspace(-size / 2, size / 2, 5)\n ax.set_xticks(xticks)\n ax.set_yticks(yticks)\n xticklabels = ax.get_xticks() / mm\n yticklabels = ax.get_yticks() / mm\n ax.set_xticklabels(xticklabels.astype(np.float16))\n ax.set_yticklabels(yticklabels.astype(np.float16))\n ax.set_xlabel('Size [%s]' % unit)\n ax.set_zlabel('Wavefront [λ]')\n else:\n ax._axis3don = False\n ax.grid(True) if kwargs['grid'] else ax.grid(False)\n if kwargs['pv_rms']:\n ax.text2D(0.925, 0.75, PV,\n fontsize=12,\n horizontalalignment='right',\n transform=ax.transAxes)\n ax.text2D(0.925, 0.70, RMS,\n fontsize=12,\n horizontalalignment='right',\n transform=ax.transAxes)\n if kwargs['colorbar']:\n fig.colorbar(im, cax=caxins)\n if mask_r:\n radius = np.sqrt(X**2 + Y**2)\n phase_[radius > size * mask_r / 2] = 0\n if title:\n if kwargs['colorbar']:\n fig.suptitle(title, x=0.575, y=0.9)\n else:\n plt.title(title)\n else:\n fig = plt.figure()\n ax = fig.add_subplot(111)\n center = int(phase_.shape[0] / 2)\n if mask_r:\n length = int((phase_.shape[0] * mask_r) / 2) * 2\n X = np.linspace(-size * mask_r / 2, size * mask_r / 2, length)\n [left, right] = [center - length / 2, center + length / 2]\n im = ax.plot(X, phase_[center][int(left):int(right)])\n else:\n X = np.linspace(-size / 2, size / 2, phase_.shape[0])\n im = ax.plot(X, phase_[center])\n xticklabels = ax.get_xticks() / mm\n ax.set_xticklabels(xticklabels.astype(int))\n ax.set_xlabel('Size [%s]' % unit)\n ax.set_ylabel('Wavefront [λ]')\n if title:\n fig.suptitle(title)\n\n plt.show()\n\n if noise is True or return_data is True:\n return phase_\n" ]
[ [ "numpy.sqrt", "numpy.random.seed", "numpy.min", "numpy.linspace", "numpy.meshgrid", "matplotlib.pyplot.title", "matplotlib.patches.Circle", "numpy.max", "numpy.random.rand", "matplotlib.pyplot.rcParams.update", "matplotlib.pyplot.show", "matplotlib.pyplot.figure" ] ]
leemengtaiwan/pytorch_lightning_applications
[ "8d277d0b7b740bcdc8e6ca39444ee3c0da23aa51" ]
[ "learnable_ai/vision/gan/core.py" ]
[ "# AUTOGENERATED! DO NOT EDIT! File to edit: notebooks/vision.gan.core.ipynb (unless otherwise specified).\n\n__all__ = ['logger', 'SPECTRAL_NORM', 'get_n_samplings', 'get_norm2d', 'get_activation', 'init_xavier_uniform',\n 'UpsampleConv2d', 'UnsqueezeLatent', 'SqueezeLogit', 'DownsampleConv2d', 'ConvGenerator',\n 'ConvDiscriminator', 'get_generater', 'get_discriminator', 'GAN']\n\n\n# Cell\nimport torch\nimport logging\nimport functools\nimport torchvision\nimport pytorch_lightning as pl\nfrom torch import nn\nfrom dotenv import load_dotenv\nfrom more_itertools import pairwise\nfrom collections import OrderedDict\nfrom ...layers import Identity\nfrom ...data import get_dataset, get_dataloader\nfrom .loss import get_adversarial_loss_fns\nfrom .hparams import (\n # dataset\n DATASET,\n LATENT_DIM,\n DIM,\n CHANNELS,\n # architecture, loss\n GENERATOR_TYPE,\n DISCRIMINATOR_TYPE,\n ADVERSARIAL_LOSS_TYPE,\n NORM_TYPE,\n DIM_CHANNEL_MULTIPLIER,\n KERNEL_SIZE,\n # training\n BATCH_SIZE,\n LR,\n BETA1,\n BETA2,\n)\n\n\n_ = load_dotenv()\nlogger = logging.getLogger()\nlogger.setLevel(\"INFO\")\n\n\n# Cell\nSPECTRAL_NORM = \"spectral\"\n\n\n# Cell\ndef get_n_samplings(dim):\n return int(torch.log2(torch.tensor(dim, dtype=torch.float32)).item()) - 2\n\n\n# Cell\ndef get_norm2d(name):\n if name == \"identity\":\n return Identity\n elif name == \"batch\":\n return nn.BatchNorm2d\n elif name == \"instance\":\n return functools.partial(nn.InstanceNorm2d, affine=True)\n elif name == \"layer\":\n return lambda num_features: nn.GroupNorm(1, num_features)\n else:\n raise NotImplementedError\n\n\n# Cell\ndef get_activation(name):\n if name == \"relu\":\n return nn.ReLU()\n elif name == \"leaky_relu\":\n return nn.LeakyReLU(0.2)\n elif name == \"tanh\":\n return nn.Tanh()\n else:\n raise NotImplementedError\n\n\n# Cell\ndef init_xavier_uniform(layer):\n if hasattr(layer, \"weight\"):\n torch.nn.init.xavier_uniform_(layer.weight)\n if hasattr(layer, \"bias\"):\n if hasattr(layer.bias, \"data\"):\n layer.bias.data.fill_(0)\n\n\n# Cell\nclass UpsampleConv2d(nn.Sequential):\n \"\"\"基本上採樣: ConvTransponse2d -> Norm -> Activation\"\"\"\n\n def __init__(self,\n in_channels,\n out_channels,\n kernel_size=KERNEL_SIZE,\n stride=2,\n padding=1,\n norm_type=\"batch\",\n act=\"relu\",\n bias=True):\n\n # TODO: try unsample without convtranspose2d\n conv = nn.ConvTranspose2d(in_channels,\n out_channels,\n kernel_size,\n stride,\n padding,\n bias=bias)\n layers = [conv]\n\n if norm_type != \"none\":\n layers.append(get_norm2d(norm_type)(out_channels))\n\n if act not in [\"none\", \"linear\"]:\n layers.append(get_activation(act))\n\n super().__init__(*layers)\n\n\n# Cell\nclass UnsqueezeLatent(nn.Module):\n \"\"\"將 latent vector unsqueeze\"\"\"\n def forward(self, x):\n return x[..., None, None]\n\n\n# Cell\nclass SqueezeLogit(nn.Module):\n \"\"\"Squeeze Discriminator logit\"\"\"\n def forward(self, x):\n return x.squeeze(-1).squeeze(-1)\n\n\n# Cell\nclass DownsampleConv2d(nn.Sequential):\n \"\"\"基本下採樣: Conv2d -> Norm -> Activation\"\"\"\n\n def __init__(self,\n in_channels,\n out_channels,\n kernel_size=KERNEL_SIZE,\n stride=2,\n padding=1,\n norm_type=\"batch\",\n act=\"leaky_relu\",\n bias=True):\n\n conv = nn.Conv2d(in_channels, out_channels, kernel_size,\n stride, padding, bias=bias)\n\n if norm_type == SPECTRAL_NORM:\n conv = nn.utils.spectral_norm(conv)\n conv.apply(init_xavier_uniform)\n layers = [conv]\n\n if norm_type not in [\"none\", SPECTRAL_NORM]:\n layers.append(get_norm2d(norm_type)(out_channels))\n\n layers.append(get_activation(act))\n super().__init__(*layers)\n\n\n# Cell\nclass ConvGenerator(nn.Sequential):\n \"\"\"將特定維度的潛在向量上採樣到指定圖片大小的生成器\"\"\"\n\n def __init__(self,\n latent_dim=LATENT_DIM,\n out_dim=DIM,\n out_channels=CHANNELS,\n kernel_size=KERNEL_SIZE,\n max_channels=None,\n norm_type=NORM_TYPE,\n act=\"relu\",\n dim_channel_multiplier=DIM_CHANNEL_MULTIPLIER):\n self.latent_dim = latent_dim\n self.out_dim = out_dim\n self.out_channels = out_channels\n self.kernel_size = kernel_size\n self.dim_channel_multiplier = dim_channel_multiplier\n self.norm_type = norm_type\n self.act = act\n self.max_channels = max_channels if max_channels else self.out_dim * self.dim_channel_multiplier\n\n # decide appropriate number of upsampling process based on expected output image shape\n self.n_upsamples = get_n_samplings(self.out_dim)\n\n # projected to spatial extent convolutional repr. with feature maps\n # x.shape == (batch_size, latent_dim)\n layers = [\n UnsqueezeLatent(),\n UpsampleConv2d(in_channels=self.latent_dim,\n out_channels=self.max_channels,\n kernel_size=self.kernel_size,\n stride=1, # no need to stride in first layer\n padding=0, # no padding in first layer\n norm_type=self.norm_type,\n act=self.act)]\n\n # upsamples\n # x.shape == (batch_size, max_channels, kernel_size, kernel_size)\n chs = [self.max_channels // (2 ** i) for i in range(self.n_upsamples)]\n chs.append(self.out_channels)\n\n layers.extend([\n UpsampleConv2d(in_channels=in_ch,\n out_channels=out_ch,\n kernel_size=self.kernel_size,\n stride=2,\n norm_type=self.norm_type if i != self.n_upsamples else \"none\",\n act=self.act if i != self.n_upsamples else \"tanh\",\n bias=False if i != self.n_upsamples else True)\n for i, (in_ch, out_ch) in enumerate(pairwise(chs), 1)])\n # out.shape == (batch_size, out_channels, out_dim, out_dim)\n\n # final act: tanh\n # using a bounded activation allowed the model to learn more quickly to\n # saturate and cover the color space of the training distribution.\n\n super().__init__(*layers)\n\n\n# Cell\nclass ConvDiscriminator(nn.Sequential):\n \"\"\"將特定大小圖片下採樣的辨識器\"\"\"\n\n def __init__(self,\n in_channels=CHANNELS,\n in_dim=DIM,\n norm_type=NORM_TYPE,\n kernel_size=KERNEL_SIZE,\n max_channels=None,\n dim_channel_multiplier=DIM_CHANNEL_MULTIPLIER):\n self.in_channels = in_channels\n self.in_dim = in_dim\n self.norm_type = norm_type\n self.kernel_size = kernel_size\n self.n_downsamples = get_n_samplings(self.in_dim)\n self.dim_channel_multiplier = dim_channel_multiplier\n self.max_channels = max_channels if max_channels else self.in_dim * self.dim_channel_multiplier\n\n # downsample\n chs = [self.in_channels]\n chs += sorted([self.max_channels // (2 ** i) for i in range(self.n_downsamples)])\n\n # x.shape == (batch_size, in_channels, in_dim, in_dim)\n layers = [\n DownsampleConv2d(in_ch,\n out_ch,\n self.kernel_size,\n stride=2,\n norm_type=self.norm_type if i != 1 or self.norm_type == SPECTRAL_NORM else \"none\",\n bias=True if i == 1 or self.norm_type == SPECTRAL_NORM else False)\n for i, (in_ch, out_ch) in enumerate(pairwise(chs), 1)]\n\n # compute logits\n # x.shape == (batch_size, max_channels, kernel_size, kernel_size)\n final_conv = nn.Conv2d(chs[-1], 1, kernel_size=self.kernel_size)\n if self.norm_type == SPECTRAL_NORM:\n final_conv = nn.utils.spectral_norm(final_conv)\n final_conv.apply(init_xavier_uniform)\n\n layers.extend([\n final_conv,\n SqueezeLogit()\n ])\n # out.shape == (batch_size, 1)\n\n super().__init__(*layers)\n\n\n# Cell\ndef get_generater(_type):\n if _type == \"conv\":\n return ConvGenerator\n else:\n raise NotImplementedError\n\ndef get_discriminator(_type):\n if _type == \"conv\":\n return ConvDiscriminator\n else:\n raise NotImplementedError\n\n\n# Cell\nclass GAN(pl.LightningModule):\n \"\"\"對抗生成網路\"\"\"\n\n def __init__(self, hparams):\n super(GAN, self).__init__()\n self.hparams = hparams\n\n # adversarial losses\n self.g_loss_fn, self.d_loss_fn = \\\n get_adversarial_loss_fns(self.hparams.adversarial_loss_type)\n\n # infer image size by dataset\n\n\n\n # initialize networks\n g = get_generater(self.hparams.generator_type)\n self.generator = g(latent_dim=self.hparams.latent_dim,\n out_dim=self.hparams.dim,\n out_channels=self.hparams.channels,\n kernel_size=self.hparams.kernel_size,\n norm_type=self.hparams.norm_type)\n\n if self.hparams.adversarial_loss_type == \"sngan\":\n self.hparams.norm_type = SPECTRAL_NORM\n\n d = get_discriminator(self.hparams.discriminator_type)\n self.discriminator = d(in_channels=self.hparams.channels,\n in_dim=self.hparams.dim,\n norm_type=self.hparams.norm_type,\n kernel_size=self.hparams.kernel_size)\n # temp\n for idx, m in enumerate(self.discriminator.modules()):\n m_name = m.__class__.__name__\n if m_name in ['Conv2d']:\n assert hasattr(m, \"weight_v\")\n assert hasattr(m, \"weight_u\")\n\n\n # cache for generated images\n self.generated_images = None\n self.last_real_images = None\n\n # keep track how many updates d has been made\n self.num_d_updates_required = self.hparams.num_discriminator_updates\n self.num_d_updates_performed = 0\n\n def prepare_data(self):\n self.train_dataset = get_dataset(dataset_name=self.hparams.dataset,\n split=\"train\",\n size=(self.hparams.dim, self.hparams.dim),\n return_label=False)\n\n self.valid_dataset = get_dataset(dataset_name=self.hparams.dataset,\n split=\"valid\",\n size=(self.hparams.dim, self.hparams.dim),\n return_label=False)\n\n def train_dataloader(self):\n return get_dataloader(self.train_dataset, batch_size=self.hparams.batch_size)\n\n def configure_optimizers(self):\n self.g_optim = torch.optim.Adam(self.generator.parameters(),\n lr=self.hparams.lr,\n betas=(self.hparams.beta1, self.hparams.beta2))\n self.d_optim = torch.optim.Adam(self.discriminator.parameters(),\n lr=self.hparams.lr,\n betas=(self.hparams.beta1, self.hparams.beta2))\n return [self.d_optim, self.g_optim], []\n\n def get_latent_vectors(self, n, on_gpu=True):\n z = torch.randn(n, self.hparams.latent_dim)\n if on_gpu:\n z = z.cuda(self.last_real_images.device.index)\n return z\n\n def training_step(self, batch, batch_idx, optimizer_idx):\n self.last_real_images = real_images = batch\n z = self.get_latent_vectors(n=self.hparams.batch_size, on_gpu=self.on_gpu)\n\n # discriminator's turn\n if optimizer_idx == 0:\n fake_images = self.generator(z).detach()\n real_logits = self.discriminator(real_images)\n fake_logits = self.discriminator(fake_images)\n\n d_real_loss, d_fake_loss = self.d_loss_fn(real_logits, fake_logits,\n on_gpu=self.on_gpu)\n d_loss = d_real_loss + d_fake_loss\n\n tqdm_dict = {'d_loss': d_loss}\n logger_dict = dict(tqdm_dict)\n logger_dict['d_real_loss'] = d_real_loss\n logger_dict['d_fake_loss'] = d_fake_loss\n\n output = OrderedDict({\n 'loss': d_loss,\n 'progress_bar': tqdm_dict,\n 'log': logger_dict\n })\n\n # keep trach number of updates\n self.num_d_updates_performed += 1\n\n return output\n\n # generator's turn\n if optimizer_idx == 1:\n # perform update if d has been trained for required times\n if self.num_d_updates_required > 1:\n if self.num_d_updates_performed < self.num_d_updates_required:\n {}\n else:\n self.num_d_updates_performed = 0\n\n # clip discriminator's weight if required\n clip_value = self.hparams.discriminator_weight_clip_value\n if clip_value:\n for p in self.discriminator.parameters():\n p.data.clamp_(-clip_value, clip_value)\n\n # genererator forward\n fake_images = self.generateed_images = self.generator(z)\n fake_logits = self.discriminator(fake_images)\n g_loss = self.g_loss_fn(fake_logits)\n\n tqdm_dict = {'g_loss': g_loss}\n output = OrderedDict({\n 'loss': g_loss,\n 'progress_bar': tqdm_dict,\n 'log': tqdm_dict\n })\n return output\n\n def forward(self, z):\n return self.generator(z)\n\n# def on_train_start(self):\n# # https://github.com/PyTorchLightning/pytorch-lightning/blob/af621f8590b2f2ba046b508da2619cfd4995d876/pytorch_lightning/core/hooks.py#L45-L49\n# # https://pytorch.org/docs/stable/tensorboard.html#torch.utils.tensorboard.writer.SummaryWriter.add_hparams\n# hparam_dict = {}\n# metric_dict = {}\n# self.logger.experiment.add_hparams({'lr': 0.1*i, 'bsize': i},{})\n\n def on_epoch_end(self):\n z = self.get_latent_vectors(n=64, on_gpu=self.on_gpu)\n sample_images = self.generator(z).clamp(0.0, 1.0)\n grid = torchvision.utils.make_grid(sample_images)\n self.logger.experiment.add_image('sample_images', grid, self.current_epoch)" ]
[ [ "torch.nn.ConvTranspose2d", "torch.randn", "torch.nn.utils.spectral_norm", "torch.nn.Conv2d", "torch.nn.Tanh", "torch.tensor", "torch.nn.LeakyReLU", "torch.nn.init.xavier_uniform_", "torch.nn.GroupNorm", "torch.nn.ReLU" ] ]
HPI-Information-Systems/TimeEval
[ "9b2717b89decd57dd09e04ad94c120f13132d7b8", "9b2717b89decd57dd09e04ad94c120f13132d7b8" ]
[ "timeeval_experiments/2021-11-26-runtime-benchmark-2.py", "scripts/calculate_metric.py" ]
[ "#!/usr/bin/env python3\nimport logging\nimport random\nimport shutil\nimport sys\nfrom pathlib import Path\nfrom typing import List, Tuple\n\nimport numpy as np\nfrom durations import Duration\n\nfrom timeeval import TimeEval, Datasets, TrainingType\nfrom timeeval.constants import HPI_CLUSTER\nfrom timeeval.remote import RemoteConfiguration\nfrom timeeval.resource_constraints import ResourceConstraints, GB\nfrom timeeval.utils.metrics import Metric\nfrom timeeval_experiments.algorithm_configurator import AlgorithmConfigurator\nfrom timeeval_experiments.algorithms import *\nfrom timeeval_experiments.baselines import Baselines\n\n\n# Setup logging\nlogging.basicConfig(\n filename=\"timeeval.log\",\n filemode=\"a\",\n level=logging.INFO,\n # force=True,\n format=\"%(asctime)s %(levelname)6.6s - %(name)20.20s: %(message)s\",\n)\n\nrandom.seed(42)\nnp.random.rand(42)\nMAX_CONTAMINATION = 0.1\nMIN_ANOMALIES = 1\n\n\ndef main():\n dm = Datasets(HPI_CLUSTER.akita_benchmark_path, create_if_missing=False)\n configurator = AlgorithmConfigurator(config_path=\"param-config.json\")\n\n # Select datasets and algorithms\n datasets: List[Tuple[str, str]] = []\n datasets += dm.select(collection_name=\"CalIt2\", max_contamination=MAX_CONTAMINATION, min_anomalies=MIN_ANOMALIES)\n datasets += dm.select(collection_name=\"Daphnet\", max_contamination=MAX_CONTAMINATION, min_anomalies=MIN_ANOMALIES)\n # no datasets match criteria for Dodgers\n # datasets += dm.select(collection_name=\"Dodgers\", max_contamination=MAX_CONTAMINATION, min_anomalies=MIN_ANOMALIES)\n # select 4 datasets of large-timeseries collection Exathlon\n datasets += random.sample(dm.select(collection_name=\"Exathlon\", train_type=TrainingType.SUPERVISED.value), 2)\n datasets += random.sample(dm.select(collection_name=\"Exathlon\", train_type=TrainingType.SEMI_SUPERVISED.value), 2)\n datasets += dm.select(collection_name=\"GHL\", max_contamination=MAX_CONTAMINATION, min_anomalies=MIN_ANOMALIES)\n datasets += dm.select(collection_name=\"Genesis\", max_contamination=MAX_CONTAMINATION, min_anomalies=MIN_ANOMALIES)\n # GutenTAG uses a separate run\n # select 4 datasets of large-timeseries collection IOPS\n datasets += random.sample(dm.select(collection_name=\"IOPS\", max_contamination=MAX_CONTAMINATION, min_anomalies=MIN_ANOMALIES), 4)\n # include everything from KDD-TSAD!\n datasets += dm.select(collection_name=\"KDD-TSAD\")\n datasets += dm.select(collection_name=\"Keogh\", max_contamination=MAX_CONTAMINATION, min_anomalies=MIN_ANOMALIES)\n # exclude Kitsune completely, bc it's too large!\n # datasets += random.sample(dm.select(collection_name=\"Kitsune\", max_contamination=MAX_CONTAMINATION, min_anomalies=MIN_ANOMALIES), 4)\n # exclude LTDB completely, bc it's too large!\n # datasets += random.sample(dm.select(collection_name=\"LTDB\", max_contamination=MAX_CONTAMINATION, min_anomalies=MIN_ANOMALIES), 4)\n datasets += dm.select(collection_name=\"MGAB\", max_contamination=MAX_CONTAMINATION, min_anomalies=MIN_ANOMALIES)\n datasets += dm.select(collection_name=\"MITDB\", max_contamination=MAX_CONTAMINATION, min_anomalies=MIN_ANOMALIES)\n datasets += dm.select(collection_name=\"Metro\", max_contamination=MAX_CONTAMINATION, min_anomalies=MIN_ANOMALIES)\n # include everything from NAB!\n datasets += dm.select(collection_name=\"NAB\")\n datasets += dm.select(collection_name=\"NASA-MSL\", max_contamination=MAX_CONTAMINATION, min_anomalies=MIN_ANOMALIES)\n datasets += dm.select(collection_name=\"NASA-SMAP\", max_contamination=MAX_CONTAMINATION, min_anomalies=MIN_ANOMALIES)\n datasets += dm.select(collection_name=\"OPPORTUNITY\", max_contamination=MAX_CONTAMINATION, min_anomalies=MIN_ANOMALIES)\n # no datasets match criteria for Occupancy\n datasets += dm.select(collection_name=\"Occupancy\", max_contamination=MAX_CONTAMINATION, min_anomalies=MIN_ANOMALIES)\n datasets += dm.select(collection_name=\"SMD\", max_contamination=MAX_CONTAMINATION, min_anomalies=MIN_ANOMALIES)\n # no datasets match criteria for SSA, bc contamination > 0.14 for all datasets\n # datasets += dm.select(collection_name=\"SSA\")\n datasets += dm.select(collection_name=\"SVDB\", max_contamination=MAX_CONTAMINATION, min_anomalies=MIN_ANOMALIES)\n datasets += dm.select(collection_name=\"WebscopeS5\", max_contamination=MAX_CONTAMINATION, min_anomalies=MIN_ANOMALIES)\n print(f\"Selecting {len(datasets)} datasets\")\n\n algorithms = [\n arima(),\n # autoencoder(), # exclude\n bagel(),\n cblof(),\n cof(),\n copod(),\n # dae(), # exclude\n dbstream(),\n deepant(),\n # deepnap(), # run later with less datasets\n donut(),\n dspot(),\n dwt_mlead(),\n eif(),\n encdec_ad(),\n # ensemble_gi(), # exclude\n # fast_mcd(), # exclude\n fft(),\n generic_rf(),\n generic_xgb(),\n grammarviz3(),\n hbos(),\n health_esn(),\n hif(),\n hotsax(),\n hybrid_knn(),\n if_lof(),\n iforest(),\n img_embedding_cae(),\n kmeans(),\n knn(),\n laser_dbn(),\n left_stampi(),\n lof(),\n lstm_ad(),\n # lstm_vae(), # exclude\n median_method(),\n # mscred(), # exclude\n # mtad_gat(), # exclude\n multi_hmm(),\n norma(),\n normalizing_flows(),\n # novelty_svr(), # exclude\n numenta_htm(),\n ocean_wnn(),\n omnianomaly(),\n pcc(),\n pci(),\n phasespace_svm(),\n pst(),\n random_black_forest(),\n robust_pca(),\n s_h_esd(),\n sand(),\n # sarima(), # exclude\n series2graph(),\n sr(),\n sr_cnn(),\n ssa(),\n stamp(),\n stomp(),\n # subsequence_fast_mcd(), # exclude\n subsequence_if(),\n subsequence_lof(),\n tanogan(),\n tarzan(),\n telemanom(),\n torsk(),\n triple_es(),\n ts_bitmap(),\n valmod(),\n Baselines.normal()\n ]\n print(f\"Selecting {len(algorithms)} algorithms\")\n\n print(\"Configuring algorithms...\")\n configurator.configure(algorithms, perform_search=False)\n\n print(\"\\nDatasets:\")\n print(\"=====================================================================================\")\n for collection in np.unique([c for (c, d) in datasets]):\n print(collection)\n cds = sorted([d for (c, d) in datasets if c == collection])\n for cd in cds:\n print(f\" {cd}\")\n print(\"=====================================================================================\\n\\n\")\n\n print(\"\\nParameter configurations:\")\n print(\"=====================================================================================\")\n for algo in algorithms:\n print(algo.name)\n for param in algo.param_config:\n print(f\" {param}\")\n print(\"=====================================================================================\\n\\n\")\n sys.stdout.flush()\n\n cluster_config = RemoteConfiguration(\n scheduler_host=HPI_CLUSTER.odin01,\n worker_hosts=HPI_CLUSTER.nodes\n )\n limits = ResourceConstraints(\n tasks_per_host=10,\n task_cpu_limit=1.,\n task_memory_limit=3*GB,\n use_preliminary_model_on_train_timeout=True,\n train_timeout=Duration(\"2 hours\"),\n execute_timeout=Duration(\"2 hours\"),\n )\n timeeval = TimeEval(dm, datasets, algorithms,\n repetitions=1,\n distributed=True,\n remote_config=cluster_config,\n resource_constraints=limits,\n skip_invalid_combinations=True,\n force_dimensionality_match=False,\n force_training_type_match=False,\n metrics=[Metric.ROC_AUC, Metric.PR_AUC, Metric.RANGE_PR_AUC, Metric.AVERAGE_PRECISION],\n # experiment_combinations_file=Path(\"/home/projects/akita/results/2021-11-26_runtime-benchmark-2/re-execution-experiments.csv\")\n )\n\n # copy parameter configuration file to results folder\n timeeval.results_path.mkdir(parents=True, exist_ok=True)\n shutil.copy2(configurator.config_path, timeeval.results_path)\n\n timeeval.run()\n print(timeeval.get_results(aggregated=True, short=True))\n\n\nif __name__ == \"__main__\":\n main()\n", "import argparse\n\nimport numpy as np\nimport pandas as pd\n\nfrom timeeval import Metric\n\n\ndef _create_arg_parser():\n parser = argparse.ArgumentParser(description=f\"Metric calculation and plotting\")\n\n parser.add_argument(\"input_file\", type=str, help=\"Path to input file with the anomaly scores (point-based)\")\n parser.add_argument(\"label_file\", type=str, help=\"Path to the label file (looks for 'is_anomaly' or \"\n \"'AnomalyLabel' column, otherwise takes the last column)\")\n parser.add_argument(\"--metric\", type=str, default=Metric.ROC_AUC.name,\n choices=[\n Metric.ROC_AUC.name, Metric.PR_AUC.name,\n Metric.RANGE_PR_AUC.name, Metric.AVERAGE_PRECISION.name\n ],\n help=\"Metric to compute\")\n parser.add_argument(\"-p\", \"--plot\", action=\"store_true\", help=\"Enable plotting the metric curve\")\n parser.add_argument(\"--save-plot\", action=\"store_true\", help=\"Save the metric plot as pdf\")\n\n return parser\n\n\nif __name__ == \"__main__\":\n parser = _create_arg_parser()\n args = parser.parse_args()\n if args.metric == Metric.AVERAGE_PRECISION.name and args.plot is True:\n print(\"Cannot create a curve plot for the average precision metric!\")\n args.plot = False\n\n anomaly_scores = pd.read_csv(args.input_file, header=None).iloc[:, 0].values\n df = pd.read_csv(args.label_file)\n if \"is_anomaly\" in df.columns:\n anomaly_labels = df[\"is_anomaly\"].values\n elif \"AnomalyLabel\" in df.columns:\n anomaly_labels = df[\"AnomalyLabel\"].values\n else:\n anomaly_labels = df.iloc[:, -1].values\n anomaly_labels = anomaly_labels.astype(np.int_)\n\n print(f\"Anomaly labels: {anomaly_labels}\")\n print(f\"Anomaly scores: {anomaly_scores}\")\n\n result = Metric[args.metric](anomaly_labels, anomaly_scores, plot=args.plot, plot_store=args.save_plot)\n print(f\"\\n{args.metric} score = {result}\")\n" ]
[ [ "numpy.random.rand", "numpy.unique" ], [ "pandas.read_csv" ] ]
m-r-munroe/alphazero-general
[ "221422e81b01f3b532da210b193692fe125a974c" ]
[ "alphazero/envs/tafl/players.py" ]
[ "from hnefatafl.engine import Move, BoardGameException\nfrom alphazero.envs.tafl.tafl import get_action\nfrom alphazero.envs.tafl.fastafl import get_action as ft_get_action\nfrom alphazero.GenericPlayers import BasePlayer\nfrom alphazero.Game import GameState\n\nimport pyximport, numpy\npyximport.install(setup_args={'include_dirs': numpy.get_include()})\n\nfrom fastafl.cengine import Square\nfrom fastafl.errors import InvalidMoveError\n\n\nclass HumanTaflPlayer(BasePlayer):\n def play(self, state: GameState):\n valid_moves = state.valid_moves()\n\n def string_to_action(player_inp: str) -> int:\n try:\n move_lst = [int(x) for x in player_inp.split()]\n move = Move(state._board, move_lst)\n return get_action(state._board, move)\n except (ValueError, AttributeError, BoardGameException):\n return -1\n \n action = string_to_action(input(f\"Enter the move to play for the player {state.player}: \"))\n while action == -1 or not valid_moves[action]:\n action = string_to_action(input(f\"Illegal move (action={action}, \"\n f\"in valids: {bool(valid_moves[action])}). Enter a valid move: \"))\n\n return action\n\n\nclass HumanFastaflPlayer(BasePlayer):\n def play(self, state: GameState):\n valid_moves = state.valid_moves()\n\n def string_to_action(player_inp: str) -> int:\n try:\n move_lst = [int(x) for x in player_inp.split()]\n return ft_get_action(state._board, (Square(*move_lst[:2]), Square(*move_lst[2:])))\n except (ValueError, AttributeError, InvalidMoveError):\n return -1\n \n action = string_to_action(input(f\"Enter the move to play for the player {state.player}: \"))\n while action == -1 or not valid_moves[action]:\n action = string_to_action(input(f\"Illegal move (action={action}, \"\n f\"in valids: {bool(valid_moves[action])}). Enter a valid move: \"))\n\n return action\n\n\nclass GreedyTaflPlayer(BasePlayer):\n def play(self, state: GameState):\n valids = state.valid_moves()\n candidates = []\n\n for a in range(state.action_size()):\n if not valids[a]: continue\n new_state = state.clone()\n new_state.play_action(a)\n candidates.append((-new_state.crude_value(), a))\n\n candidates.sort()\n return candidates[0][1]\n" ]
[ [ "numpy.get_include" ] ]
YangYunjia/cfdpost
[ "87199d1c2749c90ecdf18cd47a47a43aabff49c6" ]
[ "cfdpost/cfdresult.py" ]
[ "'''\nPost process of CFD results\n'''\nimport copy\nimport os\nimport platform\n\nimport numpy as np\nimport struct as st\n\n\nclass cfl3d():\n '''\n Extracting data from cfl3d results\n '''\n\n def __init__(self):\n print('All static method functions')\n pass\n\n @staticmethod\n def readCoef(path: str, n=100, output_error=False):\n '''\n Read clcd_wall.dat or clcd.dat of the CFL3D outputs.\n\n >>> converge, CL, CD, Cm, CDp, CDf = readCoef(path: str, n=100, output_error=False)\n >>> converge, CL, CD, Cm, CDp, CDf, errs = readCoef(path: str, n=100, output_error=True)\n\n ### Inputs:\n ```text\n path: folder that contains the results\n n: get the mean value of final n steps\n ```\n\n ### Return:\n ```text\n converge (bool), CL, CD, Cm(z), CDp, CDf\n errs = [err_CL, err_CD, err_Cm, err_CDp, err_CDf]\n ```\n '''\n converge = True\n CL = 0.0\n CD = 0.0\n Cm = 0.0\n CDp = 0.0\n CDf = 0.0\n errs = [0.0 for _ in range(5)]\n\n if platform.system() in 'Windows':\n out1 = path+'\\\\clcd.dat'\n out2 = path+'\\\\clcd_wall.dat'\n\n else:\n out1 = path+'/clcd.dat'\n out2 = path+'/clcd_wall.dat'\n\n if os.path.exists(out1):\n out = out1\n elif os.path.exists(out2): \n out = out2\n else:\n if output_error:\n return False, CL, CD, Cm, CDp, CDf, errs\n else:\n return False, CL, CD, Cm, CDp, CDf\n\n CLs = np.zeros(n)\n CDs = np.zeros(n)\n Cms = np.zeros(n)\n CDps = np.zeros(n)\n CDfs = np.zeros(n)\n with open(out, 'r') as f:\n lines = f.readlines()\n n_all = len(lines)\n\n i = 1\n k = 0\n while i<n_all-4 and k<n:\n\n L1 = lines[-i].split()\n L2 = lines[-i-1].split()\n i += 1\n\n if L1[2] == L2[2]:\n # Duplicated lines of the final step when using multiple blocks\n continue\n\n CLs[k] = float(L1[5])\n CDs[k] = float(L1[6])\n Cms[k] = float(L1[12])\n CDps[k] = float(L1[8])\n CDfs[k] = float(L1[9])\n k += 1\n\n CL_ = np.mean(CLs)\n if k < n*0.5:\n converge = False\n\n elif np.max(CLs)-np.min(CLs) < max(0.01, 0.01*CL_):\n CL = CL_\n CD = np.mean(CDs)\n Cm = np.mean(Cms)\n CDp = np.mean(CDps)\n CDf = np.mean(CDfs)\n errs[0] = np.max(CLs)-np.min(CLs)\n errs[1] = np.max(CDs)-np.min(CDs)\n errs[2] = np.max(Cms)-np.min(Cms)\n errs[3] = np.max(CDps)-np.min(CDps)\n errs[4] = np.max(CDfs)-np.min(CDfs)\n\n else:\n converge = False\n \n if output_error:\n return converge, CL, CD, Cm, CDp, CDf, errs\n else:\n return converge, CL, CD, Cm, CDp, CDf\n\n @staticmethod\n def readAoA(path: str, n=100, output_error=False):\n '''\n Read cfl3d.alpha of the CFL3D outputs.\n\n >>> succeed, AoA = readAoA(path: str, n=100, output_error=False)\n >>> succeed, AoA, err = readAoA(path: str, n=100, output_error=True)\n\n ### Inputs:\n ```text\n path: folder that contains the results\n n: get the mean value of final n steps\n ```\n\n ### Return:\n ```text\n succeed (bool), AoA\n ```\n '''\n succeed = True\n AoA = 0.0\n\n if platform.system() in 'Windows':\n out = path+'\\\\cfl3d.alpha'\n else:\n out = path+'/cfl3d.alpha'\n\n if not os.path.exists(out):\n if output_error:\n return False, AoA, 0.0\n else:\n return False, AoA\n\n AoAs = np.zeros(n)\n with open(out, 'r') as f:\n lines = f.readlines()\n\n if len(lines)<=n+10:\n f.close()\n if output_error:\n return False, AoA, 0.0\n else:\n return False, AoA\n\n for k in range(n):\n L1 = lines[-k-1].split()\n AoAs[k] = float(L1[3])\n\n AoA = np.mean(AoAs)\n\n if output_error:\n return succeed, AoA, np.max(AoAs)-np.min(AoAs)\n else:\n return succeed, AoA\n\n @staticmethod\n def readinput(path: str):\n '''\n Read cfl3d.inp of the CFL3D input.\n\n >>> succeed, Minf, AoA0, Re, l2D = readinput(path: str)\n\n ### Inputs:\n ```text\n path: folder that contains the input files\n ```\n\n ### Return:\n ```text\n succeed (bool), Minf, AoA0 (deg), Re (e6, /m), l2D(bool)\n ```\n '''\n\n succeed = True\n Minf = 0.0\n AoA0 = 0.0\n Re = 0.0\n l2D = False\n\n if platform.system() in 'Windows':\n inp = path+'\\\\cfl3d.inp'\n else:\n inp = path+'/cfl3d.inp'\n\n if not os.path.exists(inp):\n return False, Minf, AoA0, Re, l2D\n\n with open(inp, 'r') as f:\n lines = f.readlines()\n\n for i in range(len(lines)-1):\n line = lines[i].split()\n\n if 'XMACH' in line[0]:\n L1 = lines[i+1].split()\n Minf = float(L1[0])\n AoA0 = float(L1[1])\n Re = float(L1[3])\n\n if 'NGRID' in line[0]:\n L1 = lines[i+1].split()\n if int(L1[5])==1:\n l2D = True\n\n return succeed, Minf, AoA0, Re, l2D\n\n @staticmethod\n def readprt(path: str, fname='cfl3d.prt'):\n '''\n Read cfl3d.prt of the CFL3D output.\n\n >>> succeed = readprt(path: str, fname='cfl3d.prt')\n\n ### Inputs:\n ```text\n path: folder that contains the output files\n ```\n\n ### Return:\n ```text\n succeed (bool)\n ```\n '''\n mi = 10000000 # maximum size of i*j*k\n ijk = np.zeros([mi,3], dtype=int)\n xyz = np.zeros([mi,11], dtype=float)\n\n if platform.system() in 'Windows':\n prt = path+'\\\\'+fname\n out1 = path+'\\\\surface.dat'\n out2 = path+'\\\\surface2.dat'\n else:\n prt = path+'/'+fname\n out1 = path+'/surface.dat'\n out2 = path+'/surface2.dat'\n\n if not os.path.exists(prt):\n return False\n\n f0 = open(prt, 'r')\n f1 = None\n f2 = None\n\n block_p = 0\n block_v = 0\n while True:\n\n line = f0.readline()\n if line == '':\n break\n\n line = line.split()\n if len(line) == 0:\n continue\n if not line[0] in 'I':\n continue\n\n if line[6] in 'U/Uinf':\n #* Pressure distribution\n imax = 0\n jmax = 0\n kmax = 0\n imin = mi\n jmin = mi\n kmin = mi\n i0 = 0\n while True:\n L1 = f0.readline()\n L1 = L1.split()\n if len(L1) == 0:\n break\n if L1[0] in 'I':\n break\n for i in range(3):\n ijk[i0, i] = int(L1[i])\n for i in range(11):\n xyz[i0, i] = float(L1[i+3])\n \n imax = max(imax, ijk[i0,0])\n jmax = max(jmax, ijk[i0,1])\n kmax = max(kmax, ijk[i0,2])\n imin = min(imin, ijk[i0,0])\n jmin = min(jmin, ijk[i0,1])\n kmin = min(kmin, ijk[i0,2])\n i0 += 1\n \n nn = (imax-imin+1)*(jmax-jmin+1)*(kmax-kmin+1)\n if i0 == nn:\n\n if block_p==0:\n f1 = open(out1, 'w')\n f1.write('Variables = X Y Z I J K U V W P T M Cp ut \\n')\n\n block_p += 1\n print(' Read pressure block %d'%(block_p))\n\n if imax==imin:\n f1.write('zone T=\"%d\" i= %d j= %d k= %d \\n'%(block_p, imax-imin+1, jmax-jmin+1, kmax-kmin+1))\n elif jmax==jmin:\n f1.write('zone T=\"%d\" i= %d j= %d k= %d \\n'%(block_p, kmax-kmin+1, jmax-jmin+1, imax-imin+1))\n else:\n f1.write('zone T=\"%d\" i= %d j= %d k= %d \\n'%(block_p, jmax-jmin+1, imax-imin+1, kmax-kmin+1))\n for i in range(nn):\n L2 = '%18.10f %18.10f %18.10f'%(xyz[i,0], xyz[i,1], xyz[i,2])\n L2 = L2 + ' %5d %5d %5d'%(ijk[i,0], ijk[i,1], ijk[i,2])\n for j in range(8):\n L2 = L2 + ' %18.10f'%(xyz[i,3+j])\n f1.write(L2+'\\n')\n\n if line[6] in 'dn':\n #* Viscous distribution\n\n imax = 0\n jmax = 0\n kmax = 0\n imin = mi\n jmin = mi\n kmin = mi\n i0 = 0\n while True:\n L1 = f0.readline()\n L1 = L1.split()\n if len(L1) == 0:\n break\n if L1[0] in 'I':\n break\n\n for i in range(3):\n ijk[i0, i] = int(L1[i])\n for i in range(9):\n xyz[i0, i] = float(L1[i+3])\n \n imax = max(imax, ijk[i0,0])\n jmax = max(jmax, ijk[i0,1])\n kmax = max(kmax, ijk[i0,2])\n imin = min(imin, ijk[i0,0])\n jmin = min(jmin, ijk[i0,1])\n kmin = min(kmin, ijk[i0,2])\n i0 += 1\n \n nn = (imax-imin+1)*(jmax-jmin+1)*(kmax-kmin+1)\n if i0 == nn:\n\n if block_v==0:\n f2 = open(out2, 'w')\n f2.write('Variables = X Y Z I J K dn P T Cf Ch yplus \\n')\n\n if imax==imin:\n f2.write('zone i= %d j= %d k= %d \\n'%(imax-imin+1, jmax-jmin+1, kmax-kmin+1))\n elif jmax==jmin:\n f2.write('zone i= %d j= %d k= %d \\n'%(kmax-kmin+1, jmax-jmin+1, imax-imin+1))\n else:\n f2.write('zone i= %d j= %d k= %d \\n'%(jmax-jmin+1, imax-imin+1, kmax-kmin+1))\n for i in range(nn):\n L2 = '%18.10f %18.10f %18.10f'%(xyz[i,0], xyz[i,1], xyz[i,2])\n L2 = L2 + ' %5d %5d %5d'%(ijk[i,0], ijk[i,1], ijk[i,2])\n for j in range(6):\n L2 = L2 + ' %18.10f'%(xyz[i,3+j])\n f2.write(L2+'\\n')\n\n block_v += 1\n print(' Read viscous block %d'%(block_v))\n\n f0.close()\n if f1 is not None:\n f1.close()\n if f2 is not None:\n f2.close()\n\n return True\n\n @staticmethod\n def readprt_foil(path: str, j0: int, j1: int, fname='cfl3d.prt'):\n '''\n Read and extract foil Cp from cfl3d.prt\n\n >>> succeed, field, foil = readprt_foil(path: str, j0: int, j1: int, fname='cfl3d.prt')\n\n ### Inputs:\n ```text\n path: folder that contains the output files\n j0: j index of the lower surface TE\n j1: j index of the upper surface TE + 1\n ```\n\n ## cfl3d.prt index\n ```text\n i : 1 - 1 symmetry plane\n j : 1 - nj from far field of lower surface TE to far field of upper surface TE\n k : 1 - nk from surface to far field\n ```\n\n ### Return:\n ```text\n succeed (bool), (field: X,Y,U,V,P,T,Ma,Cp,vi), (foil: x, y, Cp)\n ```\n '''\n\n if platform.system() in 'Windows':\n prt = path+'\\\\'+fname\n else:\n prt = path+'/'+fname\n\n if not os.path.exists(prt):\n return False, None, None\n\n X = None\n\n f0 = open(prt, 'r')\n while True:\n\n line = f0.readline()\n if line == '':\n break\n\n line = line.split()\n if len(line) == 0:\n continue\n\n if 'BLOCK' in line[0]:\n ni = int(line[-3])\n nj = int(line[-2])\n nk = int(line[-1])\n\n X = np.zeros([nj, nk])\n Y = np.zeros([nj, nk])\n U = np.zeros([nj, nk])\n V = np.zeros([nj, nk])\n P = np.zeros([nj, nk])\n T = np.zeros([nj, nk])\n Ma = np.zeros([nj, nk])\n Cp = np.zeros([nj, nk])\n vi = np.zeros([nj, nk])\n continue\n\n if not line[0] in 'I':\n continue\n\n for k in range(nk):\n for j in range(nj):\n L1 = f0.readline()\n L1 = L1.split()\n\n X [j,k] = float(L1[3])\n Y [j,k] = float(L1[4])\n U [j,k] = float(L1[6])\n V [j,k] = float(L1[7])\n P [j,k] = float(L1[9])\n T [j,k] = float(L1[10])\n Ma[j,k] = float(L1[11])\n Cp[j,k] = float(L1[12])\n vi[j,k] = float(L1[13])\n\n break\n\n if X is None:\n return False, None, None\n\n field = (X,Y,U,V,P,T,Ma,Cp,vi)\n f0.close()\n\n foil = (X[j0:j1,0], Y[j0:j1,0], Cp[j0:j1,0])\n\n return True, field, foil\n\n @staticmethod\n def foildata(field_data: np.array, j0: int, j1: int):\n '''\n Extract wall data from field data\n\n >>> data = field_data[j0:j1,0]\n\n ### Inputs:\n ```text\n field_data: ndarray [nj,nk]\n j0: j index of the lower surface TE\n j1: j index of the upper surface TE + 1\n ```\n\n ## cfl3d.prt index\n ```text\n i : 1 - 1 symmetry plane\n j : 1 - nj from far field of lower surface TE to far field of upper surface TE\n k : 1 - nk from surface to far field\n ```\n '''\n return field_data[j0:j1,0]\n\n @staticmethod\n def readPlot2d(path: str, fname_grid='plot3d_grid.xyz', fname_sol='plot3d_sol.bin', binary=True, _double_precision=True):\n '''\n Plot3D Format grid and solution:\n 2D, Whole, Formatted, Single-Block Grid and Solution\n\n https://www.grc.nasa.gov/www/wind/valid/plot3d.html\n\n >>> xy, qq, mach, alfa, reyn = readPlot2d(path: str, \n >>> fname_grid='plot3d_grid.xyz', fname_sol='plot3d_sol.bin', binary=True)\n\n ### Input:\n ```text\n path: folder that contains the output files\n fname_grid: grid file name\n fname_sol: solution file name\n binary: binary or ASCII format\n ```\n\n ### Return:\n ```text\n xy: ndarray [ni,nj,2], or None\n qq: ndarray [ni,nj,4], or None\n non-dimensionalized RHO, RHO-U, RHO-V, E\n q1: density by the reference density, rho\n q*: velocity by the reference speed of sound, ar\n q4: total energy per unit volume by rho*ar^2\n mach: freestream Mach number, = ur/ar\n ur: reference velocity\n alfa: freestream angle-of-attack\n reyn: freestream Reynolds number, = rho*ar*Lr/miur\n Lr: reference length\n miur: reference viscosity\n ```\n '''\n xy = None\n qq = None\n mach = 0.0\n alfa = 0.0\n reyn = 0.0\n\n if _double_precision:\n r_format = 8\n s_format = 'd'\n else:\n r_format = 4\n s_format = 'f'\n\n if binary:\n\n with open(os.path.join(path, fname_grid), 'rb') as f:\n\n a, = st.unpack('i', f.read(4))\n ni, = st.unpack('i', f.read(4))\n nj, = st.unpack('i', f.read(4))\n xy = np.zeros((ni,nj,2))\n\n for v in range(2):\n for j in range(nj):\n for i in range(ni):\n xy[i,j,v], = st.unpack(s_format, f.read(r_format))\n\n with open(os.path.join(path, fname_sol), 'rb') as f:\n\n _, = st.unpack('i', f.read(4))\n ni, = st.unpack('i', f.read(4))\n nj, = st.unpack('i', f.read(4))\n qq = np.zeros((ni,nj,4))\n\n mach, = st.unpack(s_format, f.read(r_format)) # freestream Mach number\n alfa, = st.unpack(s_format, f.read(r_format)) # freestream angle-of-attack\n reyn, = st.unpack(s_format, f.read(r_format)) # freestream Reynolds number\n time, = st.unpack(s_format, f.read(r_format)) # time\n\n for q in range(4):\n for j in range(nj):\n for i in range(ni):\n qq[i,j,q], = st.unpack(s_format, f.read(r_format))\n\n\n else:\n\n with open(os.path.join(path, fname_grid), 'r') as f:\n lines = f.readlines()\n\n line = lines[1].split()\n ni = int(line[0])\n nj = int(line[1])\n xy = np.zeros((ni,nj,2))\n\n k_line = 2\n k_item = 0\n line = lines[k_line].split()\n len_line = len(line)\n data = [float(a) for a in line]\n\n for k in range(2):\n for j in range(nj):\n for i in range(ni):\n # Read next line\n if k_item >= len_line:\n k_line += 1\n k_item = 0\n line = lines[k_line].split()\n len_line = len(line)\n data = [float(a) for a in line]\n\n # Assign to xx, yy\n xy[i,j,k] = data[k_item]\n k_item += 1\n\n with open(os.path.join(path, fname_sol), 'r') as f:\n lines = f.readlines()\n\n line = lines[1].split()\n ni = int(line[0])\n nj = int(line[1])\n qq = np.zeros((ni,nj,4))\n\n line = lines[2].split()\n mach = float(line[0]) # freestream Mach number\n alfa = float(line[1]) # freestream angle-of-attack\n reyn = float(line[2]) # freestream Reynolds number\n time = float(line[3]) # time\n\n k_line = 3\n k_item = 0\n line = lines[k_line].split()\n len_line = len(line)\n data = [float(a) for a in line]\n\n for n in range(4):\n for j in range(nj):\n for i in range(ni):\n # Read next line\n if k_item >= len_line:\n k_line += 1\n k_item = 0\n line = lines[k_line].split()\n len_line = len(line)\n data = [float(a) for a in line]\n\n # Assign to qq\n qq[i,j,n] = data[k_item]\n k_item += 1\n\n\n return xy, qq, mach, alfa, reyn\n\n @staticmethod\n def readPlot3d(path: str, fname_grid='plot3d_grid.xyz', fname_sol='plot3d_sol.bin', binary=True, _double_precision=True):\n '''\n Plot3D Format grid and solution:\n 3D, Whole, Unformatted, Multi-Block Grid and Solution\n\n https://www.grc.nasa.gov/www/wind/valid/plot3d.html\n\n >>> xyz, qq, mach, alfa, reyn = readPlot3d(path: str, \n >>> fname_grid='plot3d_grid.xyz', fname_sol='plot3d_sol.bin', binary=True)\n\n ### Input:\n ```text\n path: folder that contains the output files\n fname_grid: grid file name\n fname_sol: solution file name\n binary: binary or ASCII format\n ```\n\n ### Return:\n ```text\n xyz: list of ndarray [ni,nj,nk,3], or None\n qq: list of ndarray [ni,nj,nk,5], or None\n non-dimensionalized RHO, RHO-U, RHO-V, RHO-W, E\n q1: density by the reference density, rho\n q*: velocity by the reference speed of sound, ar\n q5: total energy per unit volume by rho*ar^2\n mach: freestream Mach number, = ur/ar\n ur: reference velocity\n alfa: freestream angle-of-attack\n reyn: freestream Reynolds number, = rho*ar*Lr/miur\n Lr: reference length\n miur: reference viscosity\n ```\n '''\n xyz = None\n qq = None\n mach = 0.0\n alfa = 0.0\n reyn = 0.0\n\n if _double_precision:\n r_format = 8\n s_format = 'd'\n else:\n r_format = 4\n s_format = 'f'\n\n if binary:\n\n with open(os.path.join(path, fname_grid), 'rb') as f:\n\n num_block, = st.unpack('i', f.read(4))\n\n xyz = []\n ni = np.zeros(num_block)\n nj = np.zeros(num_block)\n nk = np.zeros(num_block)\n\n for n in range(num_block):\n ni[n],nj[n],nk[n], = st.unpack('iii', f.read(4))\n\n for n in range(num_block):\n temp = np.zeros((ni[n],nj[n],nk[n],3))\n for d in range(3):\n for k in range(nk[n]):\n for j in range(nj[n]):\n for i in range(ni[n]):\n temp[i,j,k,d], = st.unpack(s_format, f.read(r_format))\n\n xyz.append(copy.deepcopy(temp))\n\n with open(os.path.join(path, fname_sol), 'r') as f:\n \n num_block, = st.unpack('i', f.read(4))\n qq = []\n ni = np.zeros(num_block)\n nj = np.zeros(num_block)\n nk = np.zeros(num_block)\n\n for n in range(num_block):\n ni[n],nj[n],nk[n], = st.unpack('iii', f.read(4))\n\n for n in range(num_block):\n temp = np.zeros((ni[n],nj[n],nk[n],5))\n\n mach, = st.unpack(s_format, f.read(r_format)) # freestream Mach number\n alfa, = st.unpack(s_format, f.read(r_format)) # freestream angle-of-attack\n reyn, = st.unpack(s_format, f.read(r_format)) # freestream Reynolds number\n time, = st.unpack(s_format, f.read(r_format)) # time\n\n for d in range(5):\n for k in range(nk[n]):\n for j in range(nj[n]):\n for i in range(ni[n]):\n temp[i,j,k,d], = st.unpack(s_format, f.read(r_format))\n\n qq.append(copy.deepcopy(temp))\n\n\n else:\n\n with open(os.path.join(path, fname_grid), 'r') as f:\n xyz = []\n lines = f.readlines()\n\n line = lines[0].split()\n num_block = int(line[0])\n ni = np.zeros(num_block)\n nj = np.zeros(num_block)\n nk = np.zeros(num_block)\n\n for n in range(num_block):\n line = lines[1+n].split()\n ni[n] = int(line[0])\n nj[n] = int(line[1])\n nk[n] = int(line[2])\n\n k_line = 1+num_block\n k_item = 0\n line = lines[k_line].split()\n len_line = len(line)\n data = [float(a) for a in line]\n\n for n in range(num_block):\n temp = np.zeros((ni[n],nj[n],nk[n],3))\n for d in range(3):\n for k in range(nk[n]):\n for j in range(nj[n]):\n for i in range(ni[n]):\n # Read next line\n if k_item >= len_line:\n k_line += 1\n k_item = 0\n line = lines[k_line].split()\n len_line = len(line)\n data = [float(a) for a in line]\n\n # Assign to xx, yy\n temp[i,j,k,d] = data[k_item]\n k_item += 1\n\n xyz.append(copy.deepcopy(temp))\n\n with open(os.path.join(path, fname_sol), 'r') as f:\n qq = []\n lines = f.readlines()\n\n num_block = int(line[0])\n ni = np.zeros(num_block)\n nj = np.zeros(num_block)\n nk = np.zeros(num_block)\n\n for n in range(num_block):\n line = lines[1+n].split()\n ni[n] = int(line[0])\n nj[n] = int(line[1])\n nk[n] = int(line[2])\n\n k_line = 1+num_block\n k_item = 0\n line = lines[k_line].split()\n len_line = len(line)\n data = [float(a) for a in line]\n\n for n in range(num_block):\n temp = np.zeros((ni[n],nj[n],nk[n],5))\n\n line = lines[k_line].split()\n mach = float(line[0]) # freestream Mach number\n alfa = float(line[1]) # freestream angle-of-attack\n reyn = float(line[2]) # freestream Reynolds number\n time = float(line[3]) # time\n\n k_line += 1\n line = lines[k_line].split()\n len_line = len(line)\n data = [float(a) for a in line]\n\n for d in range(5):\n for k in range(nk[n]):\n for j in range(nj[n]):\n for i in range(ni[n]):\n # Read next line\n if k_item >= len_line:\n k_line += 1\n k_item = 0\n line = lines[k_line].split()\n len_line = len(line)\n data = [float(a) for a in line]\n\n # Assign to xx, yy\n temp[i,j,k,d] = data[k_item]\n k_item += 1\n\n qq.append(copy.deepcopy(temp))\n\n return xyz, qq, mach, alfa, reyn\n\n @staticmethod\n def analysePlot3d(Mr: float, qq, iVar:list, gamma_r=1.4):\n '''\n Calculate fluid variables from plot3d.\n\n All parameters are non-dimensional.\n\n >>> var = analysePlot3d(Mr: float, qq, iVar:list, gamma_r=1.4)\n\n ### Inputs:\n ```text\n Mr: freestream Mach number\n qq: ndarray [ni,nj,nk,5] or [ni,nj,4]\n iVar: list of int, index of variable(s)\n ```\n\n ### Return:\n ```text\n var: ndarray [ni,nj,nk,d] or [ni,nj,d]\n ```\n\n ### Formulas (Index of variable):\n ```text\n dimensionless gas constant: R = 1/gamma_r/Mr^2\n\n 1 static density: r = q1\n 2 u velocity: u = q2/r/Mr\n 3 v velocity: v = q3/r/Mr\n 4 w velocity: w = q4/r/Mr\n 5 total energy per unit volume: e = q5/Mr^2\n 6 velocity magnitude: V = sqrt(u^2+v^2+w^2)\n 7 static temperature: T = (gamma_r-1)/R*(e/r-V^2/2)\n 8 speed of sound: a = sqrt(gamma_r*R*T)\n 9 Mach number: M = V/a\n 10 static pressure: p = r*T\n 11 static pressure coefficient: cp = 2*R*(p-1)\n 12 internal energy: ei = R*T/(gamma_r-1)\n 13 kinetic energy: ek = V^2/2\n 14 static enthalpy: h = gamma_r*R*T/(gamma_r-1)\n\n 15 total energy et = e/r\n 16 total temperature: Tt = T*(1+(gamma_r-1)/2/M^2)\n 17 total density: rt = r*(1+(gamma_r-1)/2/M^2)^(1/(gamma_r-1))\n 18 total pressure: pt = p*(1+(gamma_r-1)/2/M^2)^(gamma_r/(gamma_r-1))\n pt0= (1+(gamma_r-1)/2*M^2)^(gamma_r/(gamma_r-1))\n 19 total pressure coefficient: cpt= 2*R*(pt-pt0)\n 20 total enthalpy: ht = gamma_r*R*Tt/(gamma_r-1)\n ```\n '''\n if len(qq.shape)==3:\n q = np.expand_dims(qq, 2) # [ni,nj,1,4]\n q = np.insert(q, 3, 0.0, axis=3) # [ni,nj,1,5]\n else:\n q = qq\n\n i_max = np.max(iVar)\n R = 1/gamma_r/Mr**2\n\n r = q[:,:,:,0]\n u = q[:,:,:,1]/r/Mr\n v = q[:,:,:,2]/r/Mr\n w = q[:,:,:,3]/r/Mr\n e = q[:,:,:,4]/Mr**2\n \n if i_max >= 5:\n V = np.sqrt(u**2+v**2+w**2)\n T = (gamma_r-1)/R*(e/r-V**2/2)\n a = np.sqrt(gamma_r*R*T)\n M = V/a\n p = r*T\n cp = 2*R*(p-1)\n\n var = []\n \n if True:\n\n if 1 in iVar:\n var.append(r)\n \n if 2 in iVar:\n var.append(u)\n\n if 3 in iVar:\n var.append(v)\n\n if 4 in iVar:\n var.append(w)\n\n if 5 in iVar:\n var.append(e)\n\n if 6 in iVar:\n var.append(V)\n \n if 7 in iVar:\n var.append(T)\n\n if 8 in iVar:\n var.append(a)\n\n if 9 in iVar:\n var.append(M)\n\n if 10 in iVar:\n var.append(p)\n\n if 11 in iVar:\n var.append(cp)\n \n if 12 in iVar:\n ei = R*T/(gamma_r-1)\n var.append(ei)\n\n if 13 in iVar:\n ek = V^2/2\n var.append(ek)\n\n if 14 in iVar:\n h = gamma_r*R*T/(gamma_r-1)\n var.append(h)\n\n if 15 in iVar:\n et = e/r\n var.append(et)\n\n if 16 in iVar:\n Tt = T*(1+(gamma_r-1)/2/M**2)\n var.append(Tt)\n \n if 17 in iVar:\n rt = r*(1+(gamma_r-1)/2/M**2)**(1/(gamma_r-1))\n var.append(rt)\n\n if 18 in iVar:\n pt = p*(1+(gamma_r-1)/2/M**2)**(gamma_r/(gamma_r-1))\n var.append(pt)\n\n if 19 in iVar:\n pt0= (1+(gamma_r-1)/2*M**2)**(gamma_r/(gamma_r-1))\n cpt= 2*R*(pt-pt0)\n var.append(cpt)\n\n if 20 in iVar:\n ht = gamma_r*R*Tt/(gamma_r-1)\n var.append(ht)\n\n var = np.array(var)\n if len(qq.shape)==3:\n var = np.squeeze(var, axis=3)\n var = np.transpose(var, axes=(1,2,0))\n else:\n var = np.transpose(var, axes=(1,2,3,0))\n\n return var\n\n @staticmethod\n def outputTecplot(xyz, variables, var_name: list, fname='flow-field.dat', append=False):\n '''\n Output tecplot format field data.\n\n >>> outputTecplot(xyz, variables, var_name: list, fname='flow-field.dat', append=False)\n\n ### Inputs:\n ```text\n xyz: ndarray [ni,nj,nk,3] or [ni,nj,3]\n variables: ndarray [ni,nj,nk,q] or [ni,nj,q]\n ```\n '''\n if len(xyz.shape)==3:\n l2d = True\n else:\n l2d = False\n nk = xyz.shape[2]\n \n ni = xyz.shape[0]\n nj = xyz.shape[1]\n nq = variables.shape[-1]\n\n if append:\n f = open(fname, 'a')\n else:\n f = open(fname, 'w')\n\n if l2d:\n f.write('Variables= X Y')\n else:\n f.write('Variables= X Y Z')\n\n for name in var_name:\n f.write(' %18s'%(name))\n f.write('\\n')\n\n if l2d:\n f.write('zone i=%d j=%d \\n'%(ni,nj))\n\n for j in range(nj):\n for i in range(ni):\n f.write(' %19.12e %19.12e'%(xyz[i,j,0], xyz[i,j,1]))\n for q in range(nq):\n f.write(' %19.12e'%(variables[i,j,q]))\n f.write('\\n')\n\n else:\n f.write('zone i=%d j=%d k=%d \\n'%(ni,nj,nk))\n\n for k in range(nk):\n for j in range(nj):\n for i in range(ni):\n f.write(' %19.12e %19.12e %19.12e'%(xyz[i,j,k,0], xyz[i,j,k,1], xyz[i,j,k,2]))\n for q in range(nq):\n f.write(' %19.12e'%(variables[i,j,k,q]))\n f.write('\\n')\n \n f.write('\\n')\n f.close()\n\n\n" ]
[ [ "numpy.expand_dims", "numpy.sqrt", "numpy.min", "numpy.squeeze", "numpy.max", "numpy.mean", "numpy.insert", "numpy.transpose", "numpy.array", "numpy.zeros" ] ]
hal-314/fastinference
[ "03e86920825520d842cf4ad75e5c9daf4614a143" ]
[ "fastinference/onnx.py" ]
[ "# AUTOGENERATED! DO NOT EDIT! File to edit: nbs/03_onnx.ipynb (unless otherwise specified).\n\n__all__ = ['fastONNX']\n\n# Cell\nfrom .soft_dependencies import SoftDependencies\nif not SoftDependencies.check()['onnxcpu']:\n raise ImportError(\"The onnxcpu or onnxgpu module is not installed.\")\n\n# Cell\nfrom fastai.learner import Learner\nfrom fastcore.all import *\nimport torch\nfrom torch import tensor, Tensor\n\nimport onnxruntime as ort\n\n# Cell\n#export\nfrom .inference.inference import _decode_loss\n\n# Cell\n#export\nclass fastONNX():\n \"ONNX wrapper for `Learner`\"\n def __init__(self, fn):\n self.ort_session = ort.InferenceSession(fn+'.onnx')\n try:\n self.ort_session.set_providers(['CUDAExecutionProvider'])\n cpu = False\n except:\n self.ort_session.set_providers(['CPUExecutionProvider'])\n cpu = True\n self.dls = torch.load(fn+'.pkl')\n\n def to_numpy(self, t:tensor): return t.detach.cpu().numpy() if t.requires_grad else t.cpu().numpy()\n\n def predict(self, inps):\n \"Predict a single numpy item\"\n if isinstance(inps[0], Tensor): inps = [self.to_numpy(x) for x in inps]\n names = [i.name for i in self.ort_session.get_inputs()]\n xs = {name:x for name,x in zip(names,inps)}\n outs = self.ort_session.run(None, xs)\n return outs\n\n def get_preds(self, dl=None, raw_outs=False, decoded_loss=True, fully_decoded=False):\n \"Get predictions with possible decoding\"\n inps, outs, dec_out, raw = [], [], [], []\n loss_func = self.dls.loss_func\n is_multi, n_inp = False, self.dls.n_inp\n if n_inp > 1:\n is_multi = true\n [inps.append([]) for _ in range(n_inp)]\n for batch in dl:\n batch_np = []\n if is_multi:\n for i in range(n_inp):\n item = self.to_numpy(batch[i])\n inps[i].append(item)\n batch_np.append(item)\n else:\n inps.append(self.to_numpy(batch[:n_inp]))\n if decoded_loss or fully_decoded:\n out = self.predict(batch_np)\n raw.append(out)\n dec_out.append(loss_func.decodes(tensor(out)))\n else:\n raw.append(self.predict(batch_np))\n axis = 1 if len(dl) > 1 else 0\n raw = np.concatenate(raw, axis=axis)\n if decoded_loss or fully_decoded:\n dec_out = np.concatenate(dec_out, axis=axis)\n if not raw_outs:\n try: outs.insert(0, loss_func.activation(tensor(raw)).numpy())\n except: outs.insert(0, dec_out)\n else:\n outs.insert(0, raw)\n if decoded_loss: outs = _decode_loss(self.dls.vocab, dec_out, outs)\n return outs\n\n def test_dl(self, test_items, **kwargs): return self.dls.test_dl(test_items, **kwargs)" ]
[ [ "torch.tensor", "torch.load" ] ]
usaito/unbiased-implicit-rec-real
[ "ff1435ea82613b1ed5c2690b77c130ddf57c0b27" ]
[ "src/models/rec_eval.py" ]
[ "import bottleneck as bn\nimport numpy as np\n\nfrom scipy import sparse\n\n\n\"\"\"\nAll the data should be in the shape of (n_users, n_items)\nAll the latent factors should in the shape of (n_users/n_items, n_components)\n\n1. train_data refers to the data that was used to train the model\n2. heldout_data refers to the data that was used for evaluation (could be test\nset or validation set)\n3. vad_data refers to the data that should be excluded as validation set, which\nshould only be used when calculating test scores\n\n\"\"\"\n\n\ndef prec_at_k(train_data, heldout_data, U, V, batch_users=5000, k=20,\n mu=None, vad_data=None, agg=np.nanmean):\n n_users = train_data.shape[0]\n res = list()\n for user_idx in user_idx_generator(n_users, batch_users):\n res.append(precision_at_k_batch(train_data, heldout_data,\n U, V.T, user_idx, k=k,\n mu=mu, vad_data=vad_data))\n mn_prec = np.hstack(res)\n if callable(agg):\n return agg(mn_prec)\n return mn_prec\n\n\ndef recall_at_k(train_data, heldout_data, U, V, batch_users=5000, k=20,\n mu=None, vad_data=None, agg=np.nanmean):\n n_users = train_data.shape[0]\n res = list()\n for user_idx in user_idx_generator(n_users, batch_users):\n res.append(recall_at_k_batch(train_data, heldout_data,\n U, V.T, user_idx, k=k,\n mu=mu, vad_data=vad_data))\n mn_recall = np.hstack(res)\n if callable(agg):\n return agg(mn_recall)\n return mn_recall\n\n\ndef ric_rank_at_k(train_data, heldout_data, U, V, batch_users=5000, k=5,\n mu=None, vad_data=None):\n n_users = train_data.shape[0]\n res = list()\n for user_idx in user_idx_generator(n_users, batch_users):\n res.append(mean_rrank_at_k_batch(train_data, heldout_data,\n U, V.T, user_idx, k=k,\n mu=mu, vad_data=vad_data))\n mrrank = np.hstack(res)\n return mrrank[mrrank > 0].mean()\n\n\ndef mean_perc_rank(train_data, heldout_data, U, V, batch_users=5000,\n mu=None, vad_data=None):\n n_users = train_data.shape[0]\n mpr = 0\n for user_idx in user_idx_generator(n_users, batch_users):\n mpr += mean_perc_rank_batch(train_data, heldout_data, U, V.T, user_idx,\n mu=mu, vad_data=vad_data)\n mpr /= heldout_data.sum()\n return mpr\n\n\ndef normalized_dcg(train_data, heldout_data, U, V, batch_users=5000,\n mu=None, vad_data=None, agg=np.nanmean):\n n_users = train_data.shape[0]\n res = list()\n for user_idx in user_idx_generator(n_users, batch_users):\n res.append(NDCG_binary_batch(train_data, heldout_data, U, V.T,\n user_idx, mu=mu, vad_data=vad_data))\n ndcg = np.hstack(res)\n if callable(agg):\n return agg(ndcg)\n return ndcg\n\n\ndef normalized_dcg_at_k(train_data, heldout_data, U, V, batch_users=5000,\n k=100, mu=None, vad_data=None, agg=np.nanmean):\n\n n_users = train_data.shape[0]\n res = list()\n for user_idx in user_idx_generator(n_users, batch_users):\n res.append(NDCG_binary_at_k_batch(train_data, heldout_data, U, V.T,\n user_idx, k=k, mu=mu,\n vad_data=vad_data))\n ndcg = np.hstack(res)\n if callable(agg):\n return agg(ndcg)\n return ndcg\n\n\ndef map_at_k(train_data, heldout_data, U, V, batch_users=5000, k=100, mu=None,\n vad_data=None, agg=np.nanmean):\n\n n_users = train_data.shape[0]\n res = list()\n for user_idx in user_idx_generator(n_users, batch_users):\n res.append(MAP_at_k_batch(train_data, heldout_data, U, V.T, user_idx,\n k=k, mu=mu, vad_data=vad_data))\n map = np.hstack(res)\n if callable(agg):\n return agg(map)\n return map\n\n\n# helper functions #\n\ndef user_idx_generator(n_users, batch_users):\n ''' helper function to generate the user index to loop through the dataset\n '''\n for start in range(0, n_users, batch_users):\n end = min(n_users, start + batch_users)\n yield slice(start, end)\n\n\ndef _make_prediction(train_data, Et, Eb, user_idx, batch_users, mu=None,\n vad_data=None):\n n_songs = train_data.shape[1]\n # exclude examples from training and validation (if any)\n item_idx = np.zeros((batch_users, n_songs), dtype=bool)\n item_idx[train_data[user_idx].nonzero()] = True\n if vad_data is not None:\n item_idx[vad_data[user_idx].nonzero()] = True\n X_pred = Et[user_idx].dot(Eb)\n if mu is not None:\n if isinstance(mu, np.ndarray):\n assert mu.size == n_songs # mu_i\n X_pred *= mu\n elif isinstance(mu, dict): # func(mu_ui)\n params, func = mu['params'], mu['func']\n args = [params[0][user_idx], params[1]]\n if len(params) > 2: # for bias term in document or length-scale\n args += [params[2][user_idx]]\n if not callable(func):\n raise TypeError(\"expecting a callable function\")\n X_pred *= func(*args)\n else:\n raise ValueError(\"unsupported mu type\")\n X_pred[item_idx] = -np.inf\n return X_pred\n\n\ndef precision_at_k_batch(train_data, heldout_data, Et, Eb, user_idx,\n k=20, normalize=True, mu=None, vad_data=None):\n batch_users = user_idx.stop - user_idx.start\n\n X_pred = _make_prediction(train_data, Et, Eb, user_idx,\n batch_users, mu=mu, vad_data=vad_data)\n idx = bn.argpartsort(-X_pred, k, axis=1)\n X_pred_binary = np.zeros_like(X_pred, dtype=bool)\n X_pred_binary[np.arange(batch_users)[:, np.newaxis], idx[:, :k]] = True\n\n X_true_binary = (heldout_data[user_idx] > 0).toarray()\n tmp = (np.logical_and(X_true_binary, X_pred_binary).sum(axis=1)).astype(\n np.float32)\n\n if normalize:\n precision = tmp / np.minimum(k, X_true_binary.sum(axis=1))\n else:\n precision = tmp / k\n return precision\n\n\ndef recall_at_k_batch(train_data, heldout_data, Et, Eb, user_idx,\n k=20, normalize=True, mu=None, vad_data=None):\n batch_users = user_idx.stop - user_idx.start\n\n X_pred = _make_prediction(train_data, Et, Eb, user_idx,\n batch_users, mu=mu, vad_data=vad_data)\n idx = bn.argpartsort(-X_pred, k, axis=1)\n X_pred_binary = np.zeros_like(X_pred, dtype=bool)\n X_pred_binary[np.arange(batch_users)[:, np.newaxis], idx[:, :k]] = True\n\n X_true_binary = (heldout_data[user_idx] > 0).toarray()\n tmp = (np.logical_and(X_true_binary, X_pred_binary).sum(axis=1)).astype(\n np.float32)\n recall = tmp / np.minimum(k, X_true_binary.sum(axis=1))\n return recall\n\n\ndef mean_rrank_at_k_batch(train_data, heldout_data, Et, Eb,\n user_idx, k=5, mu=None, vad_data=None):\n '''\n mean reciprocal rank@k: For each user, make predictions and rank for\n all the items. Then calculate the mean reciprocal rank for the top K that\n are in the held-out set.\n '''\n batch_users = user_idx.stop - user_idx.start\n\n X_pred = _make_prediction(train_data, Et, Eb, user_idx,\n batch_users, mu=mu, vad_data=vad_data)\n all_rrank = 1. / (np.argsort(np.argsort(-X_pred, axis=1), axis=1) + 1)\n X_true_binary = (heldout_data[user_idx] > 0).toarray()\n\n heldout_rrank = X_true_binary * all_rrank\n top_k = bn.partsort(-heldout_rrank, k, axis=1)\n return -top_k[:, :k].mean(axis=1)\n\n\ndef NDCG_binary_batch(train_data, heldout_data, Et, Eb, user_idx,\n mu=None, vad_data=None):\n '''\n normalized discounted cumulative gain for binary relevance\n '''\n batch_users = user_idx.stop - user_idx.start\n n_items = train_data.shape[1]\n\n X_pred = _make_prediction(train_data, Et, Eb, user_idx,\n batch_users, mu=mu, vad_data=vad_data)\n all_rank = np.argsort(np.argsort(-X_pred, axis=1), axis=1)\n # build the discount template\n tp = 1. / np.log2(np.arange(2, n_items + 2))\n all_disc = tp[all_rank]\n\n X_true_binary = (heldout_data[user_idx] > 0).tocoo()\n disc = sparse.csr_matrix((all_disc[X_true_binary.row, X_true_binary.col],\n (X_true_binary.row, X_true_binary.col)),\n shape=all_disc.shape)\n DCG = np.array(disc.sum(axis=1)).ravel()\n IDCG = np.array([tp[:n].sum()\n for n in heldout_data[user_idx].getnnz(axis=1)])\n return DCG / IDCG\n\n\ndef NDCG_binary_at_k_batch(train_data, heldout_data, Et, Eb, user_idx,\n mu=None, k=100, vad_data=None):\n '''\n normalized discounted cumulative gain@k for binary relevance\n ASSUMPTIONS: all the 0's in heldout_data indicate 0 relevance\n '''\n batch_users = user_idx.stop - user_idx.start\n\n X_pred = _make_prediction(train_data, Et, Eb, user_idx,\n batch_users, mu=mu, vad_data=vad_data)\n idx_topk_part = bn.argpartsort(-X_pred, k, axis=1)\n topk_part = X_pred[np.arange(batch_users)[:, np.newaxis],\n idx_topk_part[:, :k]]\n idx_part = np.argsort(-topk_part, axis=1)\n # X_pred[np.arange(batch_users)[:, np.newaxis], idx_topk] is the sorted\n # topk predicted score\n idx_topk = idx_topk_part[np.arange(batch_users)[:, np.newaxis], idx_part]\n # build the discount template\n tp = 1. / np.log2(np.arange(2, k + 2))\n\n heldout_batch = heldout_data[user_idx]\n DCG = (heldout_batch[np.arange(batch_users)[:, np.newaxis],\n idx_topk].toarray() * tp).sum(axis=1)\n IDCG = np.array([(tp[:min(n, k)]).sum()\n for n in heldout_batch.getnnz(axis=1)])\n return DCG / IDCG\n\n\ndef MAP_at_k_batch(train_data, heldout_data, Et, Eb, user_idx, mu=None, k=100,\n vad_data=None):\n '''\n mean average precision@k\n '''\n batch_users = user_idx.stop - user_idx.start\n\n X_pred = _make_prediction(train_data, Et, Eb, user_idx, batch_users, mu=mu,\n vad_data=vad_data)\n idx_topk_part = bn.argpartsort(-X_pred, k, axis=1)\n topk_part = X_pred[np.arange(batch_users)[:, np.newaxis],\n idx_topk_part[:, :k]]\n idx_part = np.argsort(-topk_part, axis=1)\n # X_pred[np.arange(batch_users)[:, np.newaxis], idx_topk] is the sorted\n # topk predicted score\n idx_topk = idx_topk_part[np.arange(batch_users)[:, np.newaxis], idx_part]\n\n aps = np.zeros(batch_users)\n for i, idx in enumerate(range(user_idx.start, user_idx.stop)):\n actual = heldout_data[idx].nonzero()[1]\n if len(actual) > 0:\n predicted = idx_topk[i]\n aps[i] = apk(actual, predicted, k=k)\n else:\n aps[i] = np.nan\n return aps\n\n\ndef mean_perc_rank_batch(train_data, heldout_data, Et, Eb, user_idx,\n mu=None, vad_data=None):\n '''\n mean percentile rank for a batch of users\n MPR of the full set is the sum of batch MPR's divided by the sum of all the\n feedbacks. (Eq. 8 in Hu et al.)\n This metric not necessarily constrains the data to be binary\n '''\n batch_users = user_idx.stop - user_idx.start\n\n X_pred = _make_prediction(train_data, Et, Eb, user_idx, batch_users,\n mu=mu, vad_data=vad_data)\n all_perc = np.argsort(np.argsort(-X_pred, axis=1), axis=1) / \\\n np.isfinite(X_pred).sum(axis=1, keepdims=True).astype(np.float32)\n perc_batch = (all_perc[heldout_data[user_idx].nonzero()] *\n heldout_data[user_idx].data).sum()\n return perc_batch\n\n\n# steal from https://github.com/benhamner/Metrics/blob/master/Python/ml_metrics/average_precision.py\ndef apk(actual, predicted, k=100):\n \"\"\"\n Computes the average precision at k.\n This function computes the average prescision at k between two lists of\n items.\n Parameters\n ----------\n actual : list\n A list of elements that are to be predicted (order doesn't matter)\n predicted : list\n A list of predicted elements (order does matter)\n k : int, optional\n The maximum number of predicted elements\n Returns\n -------\n score : double\n The average precision at k over the input lists\n \"\"\"\n if len(predicted) > k:\n predicted = predicted[:k]\n\n score = 0.0\n num_hits = 0.0\n\n for i, p in enumerate(predicted):\n if p in actual: # and p not in predicted[:i]: # not necessary for us since we will not make duplicated recs\n num_hits += 1.0\n score += num_hits / (i + 1.0)\n\n # we handle this part before making the function call\n # if not actual:\n # return np.nan\n\n return score / min(len(actual), k)\n" ]
[ [ "numpy.hstack", "numpy.isfinite", "numpy.arange", "scipy.sparse.csr_matrix", "numpy.zeros_like", "numpy.argsort", "numpy.logical_and", "numpy.zeros" ] ]
artificially-ai/clip-mania
[ "de612cbf94d0de7aa0d26e064e3d75b80909e776" ]
[ "tests/test_core/test_executor.py" ]
[ "import os\n\nfrom unittest import TestCase\n\nfrom pathlib import Path\n\nimport PIL\n\nimport torch\nimport clip\n\nimport numpy as np\n\nfrom clip_mania.core.executor import ModelExecutor\nfrom clip_mania.utils.data.preprocess import DatasetProcessor\n\n\nclass TestModelExecutor(TestCase):\n\n def setUp(self):\n self.device = \"cuda\" if torch.cuda.is_available() else \"cpu\"\n self.current_path = Path(os.path.dirname(os.path.realpath(__file__)))\n\n def test_instance(self):\n executor = ModelExecutor()\n self.assertIsNotNone(executor)\n\n models = ModelExecutor.get_available_models()\n self.assertIsNotNone(models)\n self.assertTrue(\"ViT-B/32\" in models)\n\n def test_train(self):\n dataset_path = os.path.join(self.current_path, \"dataset/train\")\n batch_size = 2 # number of classes\n executor = ModelExecutor(batch_size=batch_size, lr=1e-8, weight_decay=0.1)\n model, preprocess = executor.train(dataset_path, epochs=1)\n self.assertIsNotNone(model)\n self.assertIsNotNone(preprocess)\n\n prompts = DatasetProcessor.create_indexed_prompts(dataset_path)\n classes = list(prompts.keys())\n image_path = os.path.join(self.current_path, \"dataset/test/airplane/airplane1.jpg\")\n\n image = preprocess(PIL.Image.open(image_path)).unsqueeze(0).to(self.device)\n text = clip.tokenize(classes).to(self.device)\n\n with torch.no_grad():\n _image_features = model.encode_image(image)\n _text_features = model.encode_text(text)\n\n logits_per_image, logits_per_text = model(image, text)\n probs = logits_per_image.softmax(dim=-1).cpu().numpy()\n\n max_index = np.argmax(probs)\n prediction = classes[max_index]\n expected_prob = probs.flatten()[0]\n highest_prob = probs.flatten()[max_index]\n self.assertTrue(expected_prob > 0.7)\n self.assertTrue(expected_prob == highest_prob)\n self.assertTrue(prediction == \"This is a picture of a(n) airplane.\")\n print(f\"\\nExpected 'This is a picture of a(n) airplane.' and got '{prediction}'\")\n print(f\"Probability for the expected prompt was '{expected_prob:.4f}'\")\n print(f\"Expected probability was '{expected_prob:.4f}'\")\n print(f\"Highest probability was '{highest_prob:.4f}'\")\n" ]
[ [ "numpy.argmax", "torch.no_grad", "torch.cuda.is_available" ] ]
nion-software/nionui
[ "082c7a3eb9547491a8e00e5dd700aeb2f8d6bc30" ]
[ "nion/ui/DrawingContext.py" ]
[ "\"\"\"\n DrawingContext module contains classes related to drawing context.\n\n DrawingContexts are able to be handled directly by the UI system or\n produce javascript or svg to do the drawing.\n\"\"\"\nfrom __future__ import annotations\n\n# standard libraries\nimport base64\nimport collections\nimport contextlib\nimport copy\nimport io\nimport logging\nimport math\nimport re\nimport struct\nimport sys\nimport threading\nimport time\nimport typing\nimport xml.sax.saxutils\n\n# third party libraries\nimport imageio\nimport numpy\n\n# local libraries\nfrom nion.utils import Geometry\n\n\n# pylint: disable=star-args\n\n\nRGBA32Type = typing.Any\nRGBA8Type = typing.Any\nGrayscaleF32Type = typing.Any\nC8Type = typing.Any\n\nByteOrderType = typing.Optional[typing.Union[typing.Literal[\"little\"], typing.Literal[\"big\"]]]\n\n\ndef get_rgba_view_from_rgba_data(rgba_data: RGBA32Type) -> RGBA8Type:\n return rgba_data.view(numpy.uint8).reshape(rgba_data.shape + (4,))\n\n\ndef get_rgba_data_from_rgba(rgba_image: RGBA8Type) -> RGBA32Type:\n return rgba_image.view(numpy.uint32).reshape(rgba_image.shape[:-1])\n\n\ndef get_byte_view(rgba_image: RGBA32Type) -> RGBA8Type:\n return rgba_image.view(numpy.uint8).reshape(rgba_image.shape + (-1, ))\n\n\ndef get_red_view(rgba_image: RGBA32Type, byteorder: ByteOrderType = None) -> C8Type:\n if byteorder is None:\n byteorder = typing.cast(ByteOrderType, sys.byteorder)\n bytes = get_byte_view(rgba_image)\n assert bytes.shape[-1] == 4\n if byteorder == 'little':\n return typing.cast(C8Type, bytes[..., 2]) # strip A off BGRA\n else:\n return typing.cast(C8Type, bytes[..., 1]) # strip A off ARGB\n\n\ndef get_green_view(rgba_image: RGBA32Type, byteorder: ByteOrderType = None) -> C8Type:\n if byteorder is None:\n byteorder = typing.cast(ByteOrderType, sys.byteorder)\n bytes = get_byte_view(rgba_image)\n assert bytes.shape[-1] == 4\n if byteorder == 'little':\n return typing.cast(C8Type, bytes[..., 1]) # strip A off BGRA\n else:\n return typing.cast(C8Type, bytes[..., 2]) # strip A off ARGB\n\n\ndef get_blue_view(rgba_image: RGBA32Type, byteorder: ByteOrderType = None) -> C8Type:\n if byteorder is None:\n byteorder = typing.cast(ByteOrderType, sys.byteorder)\n bytes = get_byte_view(rgba_image)\n assert bytes.shape[-1] == 4\n if byteorder == 'little':\n return typing.cast(C8Type, bytes[..., 0]) # strip A off BGRA\n else:\n return typing.cast(C8Type, bytes[..., 3]) # strip A off ARGB\n\n\ndef get_alpha_view(rgba_image: RGBA32Type, byteorder: ByteOrderType = None) -> C8Type:\n if byteorder is None:\n byteorder = typing.cast(ByteOrderType, sys.byteorder)\n bytes = get_byte_view(rgba_image)\n assert bytes.shape[-1] == 4\n if byteorder == 'little':\n return typing.cast(C8Type, bytes[..., 3]) # A of BGRA\n else:\n return typing.cast(C8Type, bytes[..., 0]) # A of ARGB\n\n\nclass DrawingContext:\n \"\"\"\n Path commands (begin_path, close_path, move_to, line_to, etc.) should not be intermixed\n with transform commands (translate, scale, rotate).\n \"\"\"\n\n # TODO: stroke_fill\n # TODO: circle\n\n __image_id = 0\n __image_id_lock = threading.RLock()\n\n def __init__(self) -> None:\n self.commands: typing.List[typing.Sequence[typing.Any]] = []\n self.binary_commands = bytearray()\n self.save_count = 0\n self.images: typing.Dict[str, RGBA32Type] = dict()\n\n def copy_from(self, drawing_context: DrawingContext) -> None:\n assert self.save_count == 0\n assert drawing_context.save_count == 0\n self.commands = drawing_context.commands\n self.binary_commands = drawing_context.binary_commands\n self.images = drawing_context.images\n\n def add(self, drawing_context: DrawingContext) -> None:\n self.commands.extend(drawing_context.commands)\n self.binary_commands.extend(drawing_context.binary_commands)\n self.images.update(drawing_context.images)\n\n def clear(self) -> None:\n self.commands = []\n self.binary_commands = bytearray()\n self.save_count = 0\n self.images = dict()\n\n def to_js(self) -> str:\n js = \"\"\n for command in self.commands:\n command_id = command[0]\n command_args = command[1:]\n if command_id == \"save\":\n js += \"ctx.save();\"\n elif command_id == \"restore\":\n js += \"ctx.restore();\"\n elif command_id == \"beginPath\":\n js += \"ctx.beginPath();\"\n elif command_id == \"closePath\":\n js += \"ctx.closePath();\"\n elif command_id == \"clip\":\n js += \"ctx.beginPath();\"\n js += \"ctx.rect({0}, {1}, {2}, {3});\".format(*command_args)\n js += \"ctx.clip();\"\n elif command_id == \"translate\":\n js += \"ctx.translate({0}, {1});\".format(*command_args)\n elif command_id == \"scale\":\n js += \"ctx.scale({0}, {1});\".format(*command_args)\n elif command_id == \"rotate\":\n js += \"ctx.rotate({0});\".format(*command_args)\n elif command_id == \"moveTo\":\n js += \"ctx.moveTo({0}, {1});\".format(*command_args)\n elif command_id == \"lineTo\":\n js += \"ctx.lineTo({0}, {1});\".format(*command_args)\n elif command_id == \"rect\":\n js += \"ctx.rect({0}, {1}, {2}, {3});\".format(*command_args)\n elif command_id == \"arc\":\n x, y, r, sa, ea, ac = command_args\n js += \"ctx.arc({0}, {1}, {2}, {3}, {4}, {5});\".format(x, y, r, sa, ea, \"true\" if ac else \"false\")\n elif command_id == \"arcTo\":\n x1, y1, x2, y2, r = command_args\n js += \"ctx.arcTo({0}, {1}, {2}, {3}, {4});\".format(x1, y1, x2, y2, r)\n elif command_id == \"cubicTo\":\n x1, y1, x2, y2, x, y = command_args\n js += \"ctx.bezierCurveTo({0}, {1}, {2}, {3}, {4}, {5});\".format(x1, y1, x2, y2, x, y)\n elif command_id == \"quadraticTo\":\n x1, y1, x, y = command_args\n js += \"ctx.quadraticCurveTo({0}, {1}, {2}, {3});\".format(x1, y1, x, y)\n elif command_id == \"image\":\n w, h, image, image_id, a, b, c, d = command_args\n js += \"ctx.rect({0}, {1}, {2}, {3});\".format(a, b, c, d)\n elif command_id == \"data\":\n w, h, data, data_id, a, b, c, d, low, high, color_table = command_args\n js += \"ctx.rect({0}, {1}, {2}, {3});\".format(a, b, c, d)\n elif command_id == \"stroke\":\n js += \"ctx.stroke();\"\n elif command_id == \"sleep\":\n pass # used for performance testing\n elif command_id == \"fill\":\n js += \"ctx.fill();\"\n elif command_id == \"fillText\":\n text, x, y, max_width = command_args\n js += \"ctx.fillText('{0}', {1}, {2}{3});\".format(xml.sax.saxutils.escape(text), x, y, \", {0}\".format(max_width) if max_width else \"\")\n elif command_id == \"fillStyleGradient\":\n command_var = command_args[0]\n js += \"ctx.fillStyle = {0};\".format(\"grad\" + str(command_var))\n elif command_id == \"fillStyle\":\n js += \"ctx.fillStyle = '{0}';\".format(*command_args)\n elif command_id == \"font\":\n js += \"ctx.font = '{0}';\".format(*command_args)\n elif command_id == \"textAlign\":\n js += \"ctx.textAlign = '{0}';\".format(*command_args)\n elif command_id == \"textBaseline\":\n js += \"ctx.textBaseline = '{0}';\".format(*command_args)\n elif command_id == \"strokeStyle\":\n js += \"ctx.strokeStyle = '{0}';\".format(*command_args)\n elif command_id == \"lineWidth\":\n js += \"ctx.lineWidth = {0};\".format(*command_args)\n elif command_id == \"lineDash\":\n js += \"ctx.lineDash = {0};\".format(*command_args)\n elif command_id == \"lineCap\":\n js += \"ctx.lineCap = '{0}';\".format(*command_args)\n elif command_id == \"lineJoin\":\n js += \"ctx.lineJoin = '{0}';\".format(*command_args)\n elif command_id == \"gradient\":\n command_var, width, height, x1, y1, x2, y2 = command_args # pylint: disable=invalid-name\n js_var = \"grad\" + str(command_var)\n js += \"var {0} = ctx.createLinearGradient({1}, {2}, {3}, {4});\".format(js_var, x1, y1, x2 - x1, y2 - y1)\n elif command_id == \"colorStop\":\n command_var, x, color = command_args\n js_var = \"grad\" + str(command_var)\n js += \"{0}.addColorStop({1}, '{2}');\".format(js_var, x, color)\n return js\n\n def to_svg(self, size: Geometry.IntSize, viewbox: Geometry.IntRect) -> str:\n svg = \"\"\n defs = \"\"\n path = \"\"\n next_clip_id = 1\n transform: typing.List[str] = list()\n closers: typing.List[str] = list()\n fill_style: typing.Optional[str] = None\n fill_opacity = 1.0\n stroke_style: typing.Optional[str] = None\n stroke_opacity = 1.0\n line_cap = \"square\"\n line_join = \"bevel\"\n line_width = 1.0\n line_dash: typing.Optional[int] = None\n text_anchor = \"start\"\n text_baseline = \"alphabetic\"\n font_style: typing.Optional[str] = None\n font_weight: typing.Optional[str] = None\n font_size: typing.Optional[int] = None\n font_unit: typing.Optional[str] = None\n font_family: typing.Optional[str] = None\n # Python 3.9+: collections.deque[typing.Dict[str, typing.Any]]\n contexts: typing.Any = collections.deque()\n gradient_start: typing.Optional[str] = None\n gradient_stops: typing.List[str] = list()\n\n # make a SVG 1.1 compatible color, opacity tuple\n def parse_color(color_str: str) -> typing.Tuple[str, float]:\n color_str = ''.join(color_str.split())\n if color_str.startswith(\"rgba\"):\n c = re.split(\"rgba\\((\\d+),(\\d+),(\\d+),([\\d.]+)\\)\", color_str)\n return f\"rgb({c[1]}, {c[2]}, {c[3]})\", float(c[4])\n return color_str, 1.0\n\n for command in self.commands:\n command_id = command[0]\n #logging.debug(command_id)\n command_args = command[1:]\n if command_id == \"save\":\n context: typing.Dict[str, typing.Any] = dict()\n context[\"path\"] = path\n context[\"transform\"] = copy.deepcopy(transform)\n context[\"fill_style\"] = fill_style\n context[\"fill_opacity\"] = fill_opacity\n context[\"stroke_style\"] = stroke_style\n context[\"stroke_opacity\"] = stroke_opacity\n context[\"line_cap\"] = line_cap\n context[\"line_join\"] = line_join\n context[\"line_width\"] = line_width\n context[\"line_dash\"] = line_dash\n context[\"font_style\"] = font_style\n context[\"font_weight\"] = font_weight\n context[\"font_size\"] = font_size\n context[\"font_unit\"] = font_unit\n context[\"font_family\"] = font_family\n context[\"text_anchor\"] = text_anchor\n context[\"text_baseline\"] = text_baseline\n context[\"closers\"] = copy.deepcopy(closers)\n closers = list()\n contexts.append(context)\n elif command_id == \"restore\":\n svg += \"\".join(closers)\n context = contexts.pop()\n path = context[\"path\"]\n transform = context[\"transform\"]\n fill_style = context[\"fill_style\"]\n fill_opacity = context[\"fill_opacity\"]\n font_style = context[\"font_style\"]\n font_weight = context[\"font_weight\"]\n font_size = context[\"font_size\"]\n font_unit = context[\"font_unit\"]\n font_family = context[\"font_family\"]\n text_anchor = context[\"text_anchor\"]\n text_baseline = context[\"text_baseline\"]\n stroke_style = context[\"stroke_style\"]\n stroke_opacity = context[\"stroke_opacity\"]\n line_cap = context[\"line_cap\"]\n line_join = context[\"line_join\"]\n line_width = context[\"line_width\"]\n line_dash = context[\"line_dash\"]\n closers = context[\"closers\"]\n elif command_id == \"beginPath\":\n path = \"\"\n elif command_id == \"closePath\":\n path += \" Z\"\n elif command_id == \"moveTo\":\n path += \" M {0} {1}\".format(*command_args)\n elif command_id == \"lineTo\":\n path += \" L {0} {1}\".format(*command_args)\n elif command_id == \"rect\":\n x, y, w, h = command_args\n path += \" M {0} {1}\".format(x, y)\n path += \" L {0} {1}\".format(x + w, y)\n path += \" L {0} {1}\".format(x + w, y + h)\n path += \" L {0} {1}\".format(x, y + h)\n path += \" Z\"\n elif command_id == \"arc\":\n x, y, r, sa, ea, ac = command_args\n # js += \"ctx.arc({0}, {1}, {2}, {3}, {4}, {5});\".format(x, y, r, sa, ea, \"true\" if ac else \"false\")\n elif command_id == \"arcTo\":\n x1, y1, x2, y2, r = command_args\n # js += \"ctx.arcTo({0}, {1}, {2}, {3}, {4});\".format(x1, y1, x2, y2, r)\n elif command_id == \"cubicTo\":\n path += \" C {0} {1}, {2} {3}, {4} {5}\".format(*command_args)\n elif command_id == \"quadraticTo\":\n path += \" Q {0} {1}, {2} {3}\".format(*command_args)\n elif command_id == \"clip\":\n x, y, w, h = command_args\n clip_id = \"clip\" + str(next_clip_id)\n next_clip_id += 1\n transform_str = \" transform='{0}'\".format(\" \".join(transform)) if len(transform) > 0 else \"\"\n defs_format_str = \"<clipPath id='{0}'><rect x='{1}' y='{2}' width='{3}' height='{4}'{5} /></clipPath>\"\n defs += defs_format_str.format(clip_id, x, y, w, h, transform_str)\n svg += \"<g style='clip-path: url(#{0});'>\".format(clip_id)\n closers.append(\"</g>\")\n elif command_id == \"translate\":\n transform.append(\"translate({0},{1})\".format(*command_args))\n elif command_id == \"scale\":\n transform.append(\"scale({0},{1})\".format(*command_args))\n elif command_id == \"rotate\":\n transform.append(\"rotate({0})\".format(*command_args))\n elif command_id == \"image\":\n w, h, image, image_id, a, b, c, d = command_args\n png_file = io.BytesIO()\n rgba_data = get_rgba_view_from_rgba_data(image)\n # image compression is time consuming. pass parameters to make this step as fast as possible.\n # see nionswift-642.\n imageio.imwrite(png_file, rgba_data[..., (2,1,0,3)], \"png\", optimize=False, compress_level=1)\n png_encoded = base64.b64encode(png_file.getvalue()).decode('utf=8')\n transform_str = \" transform='{0}'\".format(\" \".join(transform)) if len(transform) > 0 else \"\"\n svg_format_str = \"<image x='{0}' y='{1}' width='{2}' height='{3}' xlink:href='data:image/png;base64,{4}'{5} />\"\n svg += svg_format_str.format(a, b, c, d, png_encoded, transform_str)\n elif command_id == \"data\":\n w, h, data, data_id, a, b, c, d, low, high, color_table, color_table_image_id = command_args\n m = 255.0 / (high - low) if high != low else 1\n image = numpy.empty(data.shape, numpy.uint32)\n if color_table is not None:\n adj_color_table = numpy.empty(color_table.shape, numpy.uint32)\n # ordering of color_table is BGRA\n # ordering of adj_color_table is RGBA\n get_byte_view(adj_color_table)[:, 0] = get_byte_view(color_table)[:, 2]\n get_byte_view(adj_color_table)[:, 1] = get_byte_view(color_table)[:, 1]\n get_byte_view(adj_color_table)[:, 2] = get_byte_view(color_table)[:, 0]\n get_byte_view(adj_color_table)[:, 3] = get_byte_view(color_table)[:, 3]\n clipped_array = numpy.clip((m * (data - low)).astype(int), 0, 255).astype(numpy.uint8)\n image[:] = adj_color_table[clipped_array]\n else:\n clipped_array = numpy.clip(data, low, high)\n numpy.subtract(clipped_array, low, out=clipped_array)\n numpy.multiply(clipped_array, m, out=clipped_array)\n get_red_view(image)[:] = clipped_array\n get_green_view(image)[:] = clipped_array\n get_blue_view(image)[:] = clipped_array\n get_alpha_view(image)[:] = 255\n png_file = io.BytesIO()\n # image compression is time consuming. pass parameters to make this step as fast as possible.\n # see nionswift-642.\n imageio.imwrite(png_file, get_rgba_view_from_rgba_data(image), \"png\", optimize=False, compress_level=1)\n png_encoded = base64.b64encode(png_file.getvalue()).decode('utf=8')\n transform_str = \" transform='{0}'\".format(\" \".join(transform)) if len(transform) > 0 else \"\"\n svg_format_str = \"<image x='{0}' y='{1}' width='{2}' height='{3}' xlink:href='data:image/png;base64,{4}'{5} />\"\n svg += svg_format_str.format(a, b, c, d, png_encoded, transform_str)\n elif command_id == \"stroke\":\n if stroke_style is not None:\n transform_str = \" transform='{0}'\".format(\" \".join(transform)) if len(transform) > 0 else \"\"\n dash_str = \" stroke-dasharray='{0}, {1}'\".format(line_dash, line_dash) if line_dash else \"\"\n svg += f\"<path d='{path}' fill='none' stroke='{stroke_style}' stroke-opacity='{stroke_opacity}' stroke-width='{line_width}' stroke-linejoin='{line_join}' stroke-linecap='{line_cap}'{dash_str}{transform_str} />\"\n elif command_id == \"sleep\":\n pass # used for performance testing\n elif command_id == \"fill\":\n if fill_style is not None:\n transform_str = \" transform='{0}'\".format(\" \".join(transform)) if len(transform) > 0 else \"\"\n svg += f\"<path d='{path}' fill='{fill_style}' fill-opacity='{fill_opacity}' stroke='none'{transform_str} />\"\n elif command_id == \"fillText\":\n text, x, y, max_width = command_args\n transform_str = \" transform='{0}'\".format(\" \".join(transform)) if len(transform) > 0 else \"\"\n font_str = \"\"\n if font_style:\n font_str += \" font-style='{0}'\".format(font_style)\n if font_weight:\n font_str += \" font-weight='{0}'\".format(font_weight)\n if font_size:\n font_str += \" font-size='{0}{1}'\".format(font_size, font_unit)\n if font_family:\n font_str += \" font-family='{0}'\".format(font_family)\n if fill_style:\n font_str += \" fill='{0}'\".format(fill_style)\n if fill_opacity < 1.0:\n font_str += \" fill-opacity='{0}'\".format(fill_opacity)\n svg_format_str = \"<text x='{0}' y='{1}' text-anchor='{3}' alignment-baseline='{4}'{5}{6}>{2}</text>\"\n svg += svg_format_str.format(x, y, xml.sax.saxutils.escape(text), text_anchor, text_baseline, font_str,\n transform_str)\n elif command_id == \"fillStyleGradient\":\n command_var = command_args[0]\n assert gradient_start is not None\n defs += gradient_start + \"\".join(gradient_stops) + \"</linearGradient>\"\n fill_style = \"url(#{0})\".format(\"grad\" + str(command_var))\n elif command_id == \"fillStyle\":\n fill_style, fill_opacity = parse_color(command_args[0])\n elif command_id == \"font\":\n font_style = None\n font_weight = None\n font_size = None\n font_unit = None\n font_family = None\n for font_part in [s for s in command_args[0].split(\" \") if s]:\n if font_part == \"italic\":\n font_style = \"italic\"\n elif font_part == \"bold\":\n font_weight = \"bold\"\n elif font_part.endswith(\"px\") and int(font_part[0:-2]) > 0:\n font_size = int(font_part[0:-2])\n font_unit = \"px\"\n elif font_part.endswith(\"pt\") and int(font_part[0:-2]) > 0:\n font_size = int(font_part[0:-2])\n font_unit = \"pt\"\n else:\n font_family = font_part\n elif command_id == \"textAlign\":\n text_anchors = {\"start\": \"start\", \"end\": \"end\", \"left\": \"start\", \"center\": \"middle\", \"right\": \"end\"}\n text_anchor = text_anchors.get(command_args[0], \"start\")\n elif command_id == \"textBaseline\":\n text_baselines = {\"top\": \"hanging\", \"hanging\": \"hanging\", \"middle\": \"middle\",\n \"alphabetic\": \"alphabetic\", \"ideaographic\": \"ideaographic\", \"bottom\": \"bottom\"}\n text_baseline = text_baselines.get(command_args[0], \"alphabetic\")\n elif command_id == \"strokeStyle\":\n stroke_style, stroke_opacity = parse_color(command_args[0])\n elif command_id == \"lineWidth\":\n line_width = command_args[0]\n elif command_id == \"lineDash\":\n line_dash = command_args[0]\n elif command_id == \"lineCap\":\n line_caps = {\"square\": \"square\", \"round\": \"round\", \"butt\": \"butt\"}\n line_cap = line_caps.get(command_args[0], \"square\")\n elif command_id == \"lineJoin\":\n line_joins = {\"round\": \"round\", \"miter\": \"miter\", \"bevel\": \"bevel\"}\n line_join = line_joins.get(command_args[0], \"bevel\")\n elif command_id == \"gradient\":\n # assumes that gradient will be used immediately after being\n # declared and stops being defined. this is currently enforced by\n # the way the commands are generated in drawing context.\n command_var, w, h, x1, y1, x2, y2 = command_args\n grad_id = \"grad\" + str(command_var)\n gradient_start = \"<linearGradient id='{0}' x1='{1}' y1='{2}' x2='{3}' y2='{4}'>\".format(grad_id,\n float(x1 / w),\n float(y1 / h),\n float(x2 / w),\n float(y2 / h))\n elif command_id == \"colorStop\":\n command_var, x, color = command_args\n gradient_stops.append(\"<stop offset='{0}%' stop-color='{1}' />\".format(int(x * 100), color))\n else:\n logging.debug(\"Unknown command %s\", command)\n xmlns = \"xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink'\"\n viewbox_str = \"{0} {1} {2} {3}\".format(viewbox.left, viewbox.top, viewbox.width, viewbox.height)\n result = \"<svg version='1.1' baseProfile='full' width='{0}' height='{1}' viewBox='{2}' {3}>\".format(size.width,\n size.height,\n viewbox_str,\n xmlns)\n result += \"<defs>\" + defs + \"</defs>\"\n result += svg\n result += \"</svg>\"\n return result\n\n @contextlib.contextmanager\n def saver(self) -> typing.Iterator[typing.Any]:\n self.save()\n try:\n yield\n finally:\n self.restore()\n\n def save(self) -> None:\n self.commands.append((\"save\", ))\n self.binary_commands.extend(b\"save\")\n self.save_count += 1\n\n def restore(self) -> None:\n self.commands.append((\"restore\", ))\n self.binary_commands.extend(b\"rest\")\n self.save_count -= 1\n\n def begin_layer(self, layer_id: int, layer_seed: int, a: float, b: float, c: float, d: float) -> None:\n self.commands.append((\"begin_layer\", int(layer_id), int(layer_seed), float(a), float(b), float(c), float(d)))\n self.binary_commands.extend(struct.pack(\"4siiffff\", b\"bgly\", int(layer_id), int(layer_seed), float(a), float(b), float(c), float(d)))\n\n def end_layer(self, layer_id: int, layer_seed: int, a: float, b: float, c: float, d: float) -> None:\n self.commands.append((\"end_layer\", int(layer_id), int(layer_seed), float(a), float(b), float(c), float(d)))\n self.binary_commands.extend(struct.pack(\"4siiffff\", b\"enly\", int(layer_id), int(layer_seed), float(a), float(b), float(c), float(d)))\n\n def begin_path(self) -> None:\n self.commands.append((\"beginPath\", ))\n self.binary_commands.extend(b\"bpth\")\n\n def close_path(self) -> None:\n self.commands.append((\"closePath\", ))\n self.binary_commands.extend(b\"cpth\")\n\n def clip_rect(self, a: float, b: float, c: float, d: float) -> None:\n self.commands.append((\"clip\", float(a), float(b), float(c), float(d)))\n self.binary_commands.extend(struct.pack(\"4sffff\", b\"clip\", float(a), float(b), float(c), float(d)))\n\n def translate(self, x: float, y: float) -> None:\n self.commands.append((\"translate\", float(x), float(y)))\n self.binary_commands.extend(struct.pack(\"4sff\", b\"tran\", float(x), float(y)))\n\n def scale(self, x: float, y: float) -> None:\n self.commands.append((\"scale\", float(x), float(y)))\n self.binary_commands.extend(struct.pack(\"4sff\", b\"scal\", float(x), float(y)))\n\n def rotate(self, radians: float) -> None:\n self.commands.append((\"rotate\", math.degrees(float(radians))))\n self.binary_commands.extend(struct.pack(\"4sf\", b\"rota\", math.degrees(float(radians))))\n\n def move_to(self, x: float, y: float) -> None:\n self.commands.append((\"moveTo\", float(x), float(y)))\n self.binary_commands.extend(struct.pack(\"4sff\", b\"move\", float(x), float(y)))\n\n def line_to(self, x: float, y: float) -> None:\n self.commands.append((\"lineTo\", float(x), float(y)))\n self.binary_commands.extend(struct.pack(\"4sff\", b\"line\", float(x), float(y)))\n\n def rect(self, l: float, t: float, w: float, h: float) -> None:\n self.commands.append((\"rect\", float(l), float(t), float(w), float(h)))\n self.binary_commands.extend(struct.pack(\"4sffff\", b\"rect\", float(l), float(t), float(w), float(h)))\n\n def round_rect(self, x: float, y: float, w: float, h: float, r: float) -> None:\n self.move_to(x + r, y)\n self.arc_to(x + w, y, x + w, y + r, r)\n self.arc_to(x + w, y + h, x + w - r, y + h, r)\n self.arc_to(x, y + h, x, y + h - r, r)\n self.arc_to(x, y, x + r, y, r)\n self.close_path()\n\n def arc(self, x: float, y: float, r: float, sa: float, ea: float, ac: bool = False) -> None:\n self.commands.append((\"arc\", float(x), float(y), float(r), float(sa), float(ea), bool(ac)))\n self.binary_commands.extend(struct.pack(\"4sfffffi\", b\"arc \", float(x), float(y), float(r), float(sa), float(ea), bool(ac)))\n\n def arc_to(self, x1: float, y1: float, x2: float, y2: float, r: float) -> None:\n self.commands.append((\"arcTo\", float(x1), float(y1), float(x2), float(y2), float(r)))\n self.binary_commands.extend(struct.pack(\"4sfffff\", b\"arct\", float(x1), float(y1), float(x2), float(y2), float(r)))\n\n def bezier_curve_to(self, x1: float, y1: float, x2: float, y2: float, x: float, y: float) -> None:\n self.commands.append((\"cubicTo\", float(x1), float(y1), float(x2), float(y2), float(x), float(y)))\n self.binary_commands.extend(struct.pack(\"4sffffff\", b\"cubc\", float(x1), float(y1), float(x2), float(y2), float(x), float(y)))\n\n def quadratic_curve_to(self, x1: float, y1: float, x: float, y: float) -> None:\n self.commands.append((\"quadraticTo\", float(x1), float(y1), float(x), float(y)))\n self.binary_commands.extend(struct.pack(\"4sffff\", b\"quad\", float(x1), float(y1), float(x), float(y)))\n\n def draw_image(self, img: RGBA32Type, x: float, y: float, width: float, height: float) -> None:\n # img should be rgba pack, uint32\n assert img.dtype == numpy.uint32\n with DrawingContext.__image_id_lock:\n DrawingContext.__image_id += 1\n image_id = DrawingContext.__image_id\n self.commands.append(\n (\"image\", img.shape[1], img.shape[0], img, int(image_id), float(x), float(y), float(width), float(height)))\n self.images[str(image_id)] = img\n self.binary_commands.extend(struct.pack(\"4siiiffff\", b\"imag\", img.shape[1], img.shape[0], int(image_id), float(x), float(y), float(width), float(height)))\n\n def draw_data(self, img: GrayscaleF32Type, x: float, y: float, width: float, height: float, low: float, high: float, color_map_data: typing.Optional[RGBA32Type]) -> None:\n # img should be float\n assert img.dtype == numpy.float32\n with DrawingContext.__image_id_lock:\n DrawingContext.__image_id += 1\n image_id = DrawingContext.__image_id\n if color_map_data is not None:\n DrawingContext.__image_id += 1\n color_map_image_id = DrawingContext.__image_id\n else:\n color_map_image_id = 0\n self.images[str(image_id)] = img\n if color_map_data is not None:\n self.images[str(color_map_image_id)] = color_map_data\n self.commands.append(\n (\"data\", img.shape[1], img.shape[0], img, int(image_id), float(x), float(y), float(width), float(height),\n float(low), float(high), color_map_data, int(color_map_image_id)))\n self.binary_commands.extend(\n struct.pack(\"4siiiffffffi\", b\"data\", img.shape[1], img.shape[0], int(image_id), float(x), float(y),\n float(width), float(height), float(low), float(high), int(color_map_image_id)))\n\n def stroke(self) -> None:\n self.commands.append((\"stroke\", ))\n self.binary_commands.extend(b\"strk\")\n\n def sleep(self, duration: float) -> None:\n self.commands.append((\"sleep\", float(duration)))\n self.binary_commands.extend(struct.pack(\"4sf\", b\"slep\", float(duration)))\n\n def mark_latency(self) -> None:\n self.commands.append((\"latency\", time.perf_counter()))\n self.binary_commands.extend(struct.pack(\"<4sd\", b\"latn\", time.perf_counter()))\n\n def message(self, text: str) -> None:\n self.commands.append((\"message\", text))\n text_encoded = text.encode(\"utf-8\")\n self.binary_commands.extend(struct.pack(\"4si{}s0i\".format(len(text_encoded)), b\"mesg\", len(text_encoded), text_encoded))\n\n def timestamp(self, timestamp: str) -> None:\n self.commands.append((\"timestamp\", timestamp))\n timestamp_encoded = timestamp.encode(\"utf-8\")\n self.binary_commands.extend(struct.pack(\"4si{}s0i\".format(len(timestamp_encoded)), b\"time\", len(timestamp_encoded), timestamp_encoded))\n\n def fill(self) -> None:\n self.commands.append((\"fill\", ))\n self.binary_commands.extend(b\"fill\")\n\n def fill_text(self, text: str, x: float, y: float, max_width: typing.Optional[int] = None) -> None:\n text = str(text) if text is not None else str()\n self.commands.append((\"fillText\", text, float(x), float(y), float(max_width) if max_width else 0))\n text_encoded = text.encode(\"utf-8\")\n self.binary_commands.extend(struct.pack(\"4si{}sfff\".format(len(text_encoded)), b\"text\", len(text_encoded), text_encoded, float(x), float(y), float(max_width) if max_width else 0))\n\n @property\n def fill_style(self) -> typing.Optional[typing.Union[str, LinearGradient]]:\n raise NotImplementedError()\n\n @fill_style.setter\n def fill_style(self, a: typing.Optional[typing.Union[str, LinearGradient]]) -> None:\n a = a or \"rgba(0, 0, 0, 0.0)\"\n if isinstance(a, DrawingContext.LinearGradient):\n self.commands.extend(a.commands)\n self.commands.append((\"fillStyleGradient\", int(a.command_var)))\n self.binary_commands.extend(a.binary_commands)\n self.binary_commands.extend(struct.pack(\"4si\", b\"flsg\", int(a.command_var)))\n else:\n self.commands.append((\"fillStyle\", str(a)))\n a_encoded = a.encode(\"utf-8\")\n self.binary_commands.extend(struct.pack(\"4si{}s0i\".format(len(a_encoded)), b\"flst\", len(a_encoded), a_encoded))\n\n @property\n def font(self) -> typing.Optional[str]:\n raise NotImplementedError()\n\n @font.setter\n def font(self, a: typing.Optional[str]) -> None:\n \"\"\"\n Set the text font.\n\n Supports 'normal', 'bold', 'italic', size specific as '14px', and font-family.\n \"\"\"\n assert a is not None\n self.commands.append((\"font\", str(a)))\n a_encoded = a.encode(\"utf-8\")\n self.binary_commands.extend(struct.pack(\"4si{}s0i\".format(len(a_encoded)), b\"font\", len(a_encoded), a_encoded))\n\n @property\n def text_align(self) -> typing.Optional[str]:\n raise NotImplementedError()\n\n @text_align.setter\n def text_align(self, a: typing.Optional[str]) -> None:\n \"\"\"Set text alignment.\n\n Valid values are 'start', 'end', 'left', 'center', 'right'. Default is 'start'.\n\n Default is 'start'.\n \"\"\"\n assert a is not None\n self.commands.append((\"textAlign\", str(a)))\n a_encoded = a.encode(\"utf-8\")\n self.binary_commands.extend(struct.pack(\"4si{}s0i\".format(len(a_encoded)), b\"algn\", len(a_encoded), a_encoded))\n\n @property\n def text_baseline(self) -> typing.Optional[str]:\n raise NotImplementedError()\n\n @text_baseline.setter\n def text_baseline(self, a: typing.Optional[str]) -> None:\n \"\"\"Set the text baseline.\n\n Valid values are 'top', 'hanging', 'middle', 'alphabetic', 'ideographic', and 'bottom'.\n\n Default is 'alphabetic'.\n \"\"\"\n assert a is not None\n self.commands.append((\"textBaseline\", str(a)))\n a_encoded = a.encode(\"utf-8\")\n self.binary_commands.extend(struct.pack(\"4si{}s0i\".format(len(a_encoded)), b\"tbas\", len(a_encoded), a_encoded))\n\n @property\n def stroke_style(self) -> typing.Optional[str]:\n raise NotImplementedError()\n\n @stroke_style.setter\n def stroke_style(self, a: typing.Optional[str]) -> None:\n a = a or \"rgba(0, 0, 0, 0.0)\"\n self.commands.append((\"strokeStyle\", str(a)))\n a_encoded = a.encode(\"utf-8\")\n self.binary_commands.extend(struct.pack(\"4si{}s0i\".format(len(a_encoded)), b\"stst\", len(a_encoded), a_encoded))\n\n @property\n def line_width(self) -> float:\n raise NotImplementedError()\n\n @line_width.setter\n def line_width(self, a: float) -> None:\n self.commands.append((\"lineWidth\", float(a)))\n self.binary_commands.extend(struct.pack(\"4sf\", b\"linw\", float(a)))\n\n @property\n def line_dash(self) -> typing.Optional[int]:\n raise NotImplementedError()\n\n @line_dash.setter\n def line_dash(self, a: typing.Optional[int]) -> None:\n \"\"\"Set the line dash. Takes a single value with the length of the dash.\"\"\"\n assert a is not None\n self.commands.append((\"lineDash\", float(a)))\n self.binary_commands.extend(struct.pack(\"4sf\", b\"ldsh\", float(a)))\n\n @property\n def line_cap(self) -> typing.Optional[str]:\n raise NotImplementedError()\n\n @line_cap.setter\n def line_cap(self, a: typing.Optional[str]) -> None:\n \"\"\"Set the line join. Valid values are 'square', 'round', 'butt'. Default is 'square'.\"\"\"\n assert a is not None\n self.commands.append((\"lineCap\", str(a)))\n a_encoded = a.encode(\"utf-8\")\n self.binary_commands.extend(struct.pack(\"4si{}s0i\".format(len(a_encoded)), b\"lcap\", len(a_encoded), a_encoded))\n\n @property\n def line_join(self) -> typing.Optional[str]:\n raise NotImplementedError()\n\n @line_join.setter\n def line_join(self, a: typing.Optional[str]) -> None:\n \"\"\"Set the line join. Valid values are 'round', 'miter', 'bevel'. Default is 'bevel'.\"\"\"\n assert a is not None\n self.commands.append((\"lineJoin\", str(a)))\n a_encoded = a.encode(\"utf-8\")\n self.binary_commands.extend(struct.pack(\"4si{}s0i\".format(len(a_encoded)), b\"lnjn\", len(a_encoded), a_encoded))\n\n class LinearGradient:\n next = 1\n\n def __init__(self, width: float, height: float, x1: float, y1: float, x2: float, y2: float) -> None:\n self.commands: typing.List[typing.Sequence[typing.Any]] = []\n self.binary_commands = bytearray()\n self.command_var = DrawingContext.LinearGradient.next\n self.commands.append((\"gradient\", self.command_var, float(width), float(height), float(x1), float(y1), float(x2), float(y2)))\n self.binary_commands.extend(struct.pack(\"4siffffff\", b\"grad\", self.command_var, float(width), float(height), float(x1), float(y1), float(x2), float(y2)))\n DrawingContext.LinearGradient.next += 1\n\n def add_color_stop(self, x: float, color: str) -> None:\n self.commands.append((\"colorStop\", self.command_var, float(x), str(color)))\n color_encoded = color.encode(\"utf-8\")\n self.binary_commands.extend(struct.pack(\"4sifi{}s0i\".format(len(color_encoded)), b\"grcs\", self.command_var, float(x), len(color_encoded), color_encoded))\n\n def create_linear_gradient(self, width: float, height: float, x1: float, y1: float, x2: float, y2: float) -> DrawingContext.LinearGradient:\n gradient = DrawingContext.LinearGradient(width, height, x1, y1, x2, y2)\n return gradient\n\n def statistics(self, stat_id: str) -> None:\n self.commands.append((\"statistics\", str(stat_id)))\n stat_id_encoded = stat_id.encode(\"utf-8\")\n self.binary_commands.extend(struct.pack(\"4si{}s0i\".format(len(stat_id_encoded)), b\"stat\", len(stat_id_encoded), stat_id_encoded))\n\n# https://www.w3.org/TR/SVG11/types.html#ColorKeywords\n\n# processed with:\n\n\"\"\"\nimport re\n\nwith open(\"colors.txt\", \"r\") as f:\n while True:\n color_line = f.readline()\n if not color_line:\n break\n color_line = color_line.strip()\n rgb_line = f.readline().strip().replace(\" \", \"\")\n c = re.split(\"rgb\\((\\d+),(\\d+),(\\d+)\\)\", rgb_line)\n print(f\"\\t\\\"{color_line}\\\": \\\"#{int(c[1]):02x}{int(c[2]):02x}{int(c[3]):02x}\\\",\")\n\"\"\"\n\nsvg_color_map = {\n \"aliceblue\": \"#f0f8ff\",\n \"antiquewhite\": \"#faebd7\",\n \"aqua\": \"#00ffff\",\n \"aquamarine\": \"#7fffd4\",\n \"azure\": \"#f0ffff\",\n \"beige\": \"#f5f5dc\",\n \"bisque\": \"#ffe4c4\",\n \"black\": \"#000000\",\n \"blanchedalmond\": \"#ffebcd\",\n \"blue\": \"#0000ff\",\n \"blueviolet\": \"#8a2be2\",\n \"brown\": \"#a52a2a\",\n \"burlywood\": \"#deb887\",\n \"cadetblue\": \"#5f9ea0\",\n \"chartreuse\": \"#7fff00\",\n \"chocolate\": \"#d2691e\",\n \"coral\": \"#ff7f50\",\n \"cornflowerblue\": \"#6495ed\",\n \"cornsilk\": \"#fff8dc\",\n \"crimson\": \"#dc143c\",\n \"cyan\": \"#00ffff\",\n \"darkblue\": \"#00008b\",\n \"darkcyan\": \"#008b8b\",\n \"darkgoldenrod\": \"#b8860b\",\n \"darkgray\": \"#a9a9a9\",\n \"darkgreen\": \"#006400\",\n \"darkgrey\": \"#a9a9a9\",\n \"darkkhaki\": \"#bdb76b\",\n \"darkmagenta\": \"#8b008b\",\n \"darkolivegreen\": \"#556b2f\",\n \"darkorange\": \"#ff8c00\",\n \"darkorchid\": \"#9932cc\",\n \"darkred\": \"#8b0000\",\n \"darksalmon\": \"#e9967a\",\n \"darkseagreen\": \"#8fbc8f\",\n \"darkslateblue\": \"#483d8b\",\n \"darkslategray\": \"#2f4f4f\",\n \"darkslategrey\": \"#2f4f4f\",\n \"darkturquoise\": \"#00ced1\",\n \"darkviolet\": \"#9400d3\",\n \"deeppink\": \"#ff1493\",\n \"deepskyblue\": \"#00bfff\",\n \"dimgray\": \"#696969\",\n \"dimgrey\": \"#696969\",\n \"dodgerblue\": \"#1e90ff\",\n \"firebrick\": \"#b22222\",\n \"floralwhite\": \"#fffaf0\",\n \"forestgreen\": \"#228b22\",\n \"fuchsia\": \"#ff00ff\",\n \"gainsboro\": \"#dcdcdc\",\n \"ghostwhite\": \"#f8f8ff\",\n \"gold\": \"#ffd700\",\n \"goldenrod\": \"#daa520\",\n \"gray\": \"#808080\",\n \"grey\": \"#808080\",\n \"green\": \"#008000\",\n \"greenyellow\": \"#adff2f\",\n \"honeydew\": \"#f0fff0\",\n \"hotpink\": \"#ff69b4\",\n \"indianred\": \"#cd5c5c\",\n \"indigo\": \"#4b0082\",\n \"ivory\": \"#fffff0\",\n \"khaki\": \"#f0e68c\",\n \"lavender\": \"#e6e6fa\",\n \"lavenderblush\": \"#fff0f5\",\n \"lawngreen\": \"#7cfc00\",\n \"lemonchiffon\": \"#fffacd\",\n \"lightblue\": \"#add8e6\",\n \"lightcoral\": \"#f08080\",\n \"lightcyan\": \"#e0ffff\",\n \"lightgoldenrodyellow\": \"#fafad2\",\n \"lightgray\": \"#d3d3d3\",\n \"lightgreen\": \"#90ee90\",\n \"lightgrey\": \"#d3d3d3\",\n \"lightpink\": \"#ffb6c1\",\n \"lightsalmon\": \"#ffa07a\",\n \"lightseagreen\": \"#20b2aa\",\n \"lightskyblue\": \"#87cefa\",\n \"lightslategray\": \"#778899\",\n \"lightslategrey\": \"#778899\",\n \"lightsteelblue\": \"#b0c4de\",\n \"lightyellow\": \"#ffffe0\",\n \"lime\": \"#00ff00\",\n \"limegreen\": \"#32cd32\",\n \"linen\": \"#faf0e6\",\n \"magenta\": \"#ff00ff\",\n \"maroon\": \"#800000\",\n \"mediumaquamarine\": \"#66cdaa\",\n \"mediumblue\": \"#0000cd\",\n \"mediumorchid\": \"#ba55d3\",\n \"mediumpurple\": \"#9370db\",\n \"mediumseagreen\": \"#3cb371\",\n \"mediumslateblue\": \"#7b68ee\",\n \"mediumspringgreen\": \"#00fa9a\",\n \"mediumturquoise\": \"#48d1cc\",\n \"mediumvioletred\": \"#c71585\",\n \"midnightblue\": \"#191970\",\n \"mintcream\": \"#f5fffa\",\n \"mistyrose\": \"#ffe4e1\",\n \"moccasin\": \"#ffe4b5\",\n \"navajowhite\": \"#ffdead\",\n \"navy\": \"#000080\",\n \"oldlace\": \"#fdf5e6\",\n \"olive\": \"#808000\",\n \"olivedrab\": \"#6b8e23\",\n \"orange\": \"#ffa500\",\n \"orangered\": \"#ff4500\",\n \"orchid\": \"#da70d6\",\n \"palegoldenrod\": \"#eee8aa\",\n \"palegreen\": \"#98fb98\",\n \"paleturquoise\": \"#afeeee\",\n \"palevioletred\": \"#db7093\",\n \"papayawhip\": \"#ffefd5\",\n \"peachpuff\": \"#ffdab9\",\n \"peru\": \"#cd853f\",\n \"pink\": \"#ffc0cb\",\n \"plum\": \"#dda0dd\",\n \"powderblue\": \"#b0e0e6\",\n \"purple\": \"#800080\",\n \"red\": \"#ff0000\",\n \"rosybrown\": \"#bc8f8f\",\n \"royalblue\": \"#4169e1\",\n \"saddlebrown\": \"#8b4513\",\n \"salmon\": \"#fa8072\",\n \"sandybrown\": \"#f4a460\",\n \"seagreen\": \"#2e8b57\",\n \"seashell\": \"#fff5ee\",\n \"sienna\": \"#a0522d\",\n \"silver\": \"#c0c0c0\",\n \"skyblue\": \"#87ceeb\",\n \"slateblue\": \"#6a5acd\",\n \"slategray\": \"#708090\",\n \"slategrey\": \"#708090\",\n \"snow\": \"#fffafa\",\n \"springgreen\": \"#00ff7f\",\n \"steelblue\": \"#4682b4\",\n \"tan\": \"#d2b48c\",\n \"teal\": \"#008080\",\n \"thistle\": \"#d8bfd8\",\n \"tomato\": \"#ff6347\",\n \"turquoise\": \"#40e0d0\",\n \"violet\": \"#ee82ee\",\n \"wheat\": \"#f5deb3\",\n \"white\": \"#ffffff\",\n \"whitesmoke\": \"#f5f5f5\",\n \"yellow\": \"#ffff00\",\n \"yellowgreen\": \"#9acd32\",\n}\n\n\nsvg_color_reverse_map = {v: k for k, v in svg_color_map.items()}\n\n\ndef color_without_alpha(color: typing.Optional[str]) -> typing.Optional[str]:\n if not color:\n return None\n color = color.strip().replace(\" \", \"\")\n c = re.split(\"rgba\\((\\d+),(\\d+),(\\d+),([\\d.]+)\\)\", color)\n if len(c) > 1:\n return f\"#{int(c[1]):02x}{int(c[2]):02x}{int(c[3]):02x}\"\n c = re.split(\"rgb\\((\\d+),(\\d+),(\\d+)\\)\", color)\n if len(c) > 1:\n return f\"#{int(c[1]):02x}{int(c[2]):02x}{int(c[3]):02x}\"\n if color.startswith(\"#\"):\n if len(color) == 9:\n return f\"#{color.lower()[3:]}\"\n if len(color) == 7:\n return color.lower()\n return color\n\n\ndef named_color_without_alpha(color: str) -> typing.Optional[str]:\n color_with_alpha = color_without_alpha(color)\n return svg_color_reverse_map.get(color_with_alpha, color_with_alpha) if color_with_alpha else None\n\n\ndef hex_color(color: str) -> typing.Optional[str]:\n if not color:\n return None\n color = color.strip().replace(\" \", \"\")\n c = re.split(\"rgba\\((\\d+),(\\d+),(\\d+),([\\d.]+)\\)\", color)\n if len(c) > 1:\n return f\"#{int(255 * float(c[4])):02x}{int(c[1]):02x}{int(c[2]):02x}{int(c[3]):02x}\"\n c = re.split(\"rgb\\((\\d+),(\\d+),(\\d+)\\)\", color)\n if len(c) > 1:\n return f\"#{int(c[1]):02x}{int(c[2]):02x}{int(c[3]):02x}\"\n if color.startswith(\"#\"):\n if len(color) == 9 or len(color) == 7:\n return color.lower()\n return svg_color_map.get(color, color)\n" ]
[ [ "numpy.multiply", "numpy.subtract", "numpy.empty", "numpy.clip" ] ]
jcoughlin11/yt
[ "31565b56571609fc3afff156cda77dbff8fc986c" ]
[ "yt/visualization/tests/test_plotwindow.py" ]
[ "import os\nimport shutil\nimport tempfile\nimport unittest\nfrom collections import OrderedDict\n\nimport numpy as np\nfrom nose.tools import assert_true\n\nfrom yt.loaders import load_uniform_grid\nfrom yt.testing import (\n assert_array_almost_equal,\n assert_array_equal,\n assert_equal,\n assert_fname,\n assert_raises,\n assert_rel_equal,\n fake_random_ds,\n requires_file,\n)\nfrom yt.units import kboltz\nfrom yt.units.yt_array import YTArray, YTQuantity\nfrom yt.utilities.answer_testing.framework import (\n PlotWindowAttributeTest,\n data_dir_load,\n requires_ds,\n)\nfrom yt.utilities.exceptions import YTInvalidFieldType\nfrom yt.visualization.api import (\n OffAxisProjectionPlot,\n OffAxisSlicePlot,\n ProjectionPlot,\n SlicePlot,\n plot_2d,\n)\n\n\ndef setup():\n \"\"\"Test specific setup.\"\"\"\n from yt.config import ytcfg\n\n ytcfg[\"yt\", \"internals\", \"within_testing\"] = True\n\n\nTEST_FLNMS = [\"test.png\"]\nM7 = \"DD0010/moving7_0010\"\n\nFPROPS = {\"family\": \"sans-serif\", \"style\": \"italic\", \"weight\": \"bold\", \"size\": 24}\n\nATTR_ARGS = {\n \"pan\": [(((0.1, 0.1),), {})],\n \"pan_rel\": [(((0.1, 0.1),), {})],\n \"set_axes_unit\": [\n ((\"kpc\",), {}),\n ((\"Mpc\",), {}),\n (((\"kpc\", \"kpc\"),), {}),\n (((\"kpc\", \"Mpc\"),), {}),\n ],\n \"set_buff_size\": [((1600,), {}), (((600, 800),), {})],\n \"set_center\": [(((0.4, 0.3),), {})],\n \"set_cmap\": [((\"density\", \"RdBu\"), {}), ((\"density\", \"kamae\"), {})],\n \"set_font\": [((OrderedDict(sorted(FPROPS.items(), key=lambda t: t[0])),), {})],\n \"set_log\": [((\"density\", False), {})],\n \"set_figure_size\": [((7.0,), {})],\n \"set_zlim\": [\n ((\"density\", 1e-25, 1e-23), {}),\n ((\"density\", 1e-25, None), {\"dynamic_range\": 4}),\n ],\n \"zoom\": [((10,), {})],\n \"toggle_right_handed\": [((), {})],\n}\n\n\nCENTER_SPECS = (\n \"m\",\n \"M\",\n \"max\",\n \"Max\",\n \"c\",\n \"C\",\n \"center\",\n \"Center\",\n [0.5, 0.5, 0.5],\n [[0.2, 0.3, 0.4], \"cm\"],\n YTArray([0.3, 0.4, 0.7], \"cm\"),\n)\n\nWIDTH_SPECS = {\n # Width choices map to xlim, ylim, width, axes_unit_name 4-tuples\n None: (\n ((0, \"code_length\"), (1, \"code_length\")),\n ((0, \"code_length\"), (1, \"code_length\")),\n ((1, \"code_length\"), (1, \"code_length\")),\n None,\n ),\n 0.2: (\n ((0.4, \"code_length\"), (0.6, \"code_length\")),\n ((0.4, \"code_length\"), (0.6, \"code_length\")),\n ((0.2, \"code_length\"), (0.2, \"code_length\")),\n None,\n ),\n (0.4, 0.3): (\n ((0.3, \"code_length\"), (0.7, \"code_length\")),\n ((0.35, \"code_length\"), (0.65, \"code_length\")),\n ((0.4, \"code_length\"), (0.3, \"code_length\")),\n None,\n ),\n (1.2, \"cm\"): (\n ((-0.1, \"code_length\"), (1.1, \"code_length\")),\n ((-0.1, \"code_length\"), (1.1, \"code_length\")),\n ((1.2, \"code_length\"), (1.2, \"code_length\")),\n (\"cm\", \"cm\"),\n ),\n ((1.2, \"cm\"), (2.0, \"cm\")): (\n ((-0.1, \"code_length\"), (1.1, \"code_length\")),\n ((-0.5, \"code_length\"), (1.5, \"code_length\")),\n ((1.2, \"code_length\"), (2.0, \"code_length\")),\n (\"cm\", \"cm\"),\n ),\n ((1.2, \"cm\"), (0.02, \"m\")): (\n ((-0.1, \"code_length\"), (1.1, \"code_length\")),\n ((-0.5, \"code_length\"), (1.5, \"code_length\")),\n ((1.2, \"code_length\"), (2.0, \"code_length\")),\n (\"cm\", \"m\"),\n ),\n}\n\nWEIGHT_FIELDS = (\n None,\n (\"gas\", \"density\"),\n)\n\nPROJECTION_METHODS = (\"integrate\", \"sum\", \"mip\")\n\nBUFF_SIZES = [(800, 800), (1600, 1600), (1254, 1254), (800, 600)]\n\n\ndef simple_contour(test_obj, plot):\n plot.annotate_contour(test_obj.plot_field)\n\n\ndef simple_velocity(test_obj, plot):\n plot.annotate_velocity()\n\n\ndef simple_streamlines(test_obj, plot):\n ax = test_obj.plot_axis\n xax = test_obj.ds.coordinates.x_axis[ax]\n yax = test_obj.ds.coordinates.y_axis[ax]\n xn = test_obj.ds.coordinates.axis_name[xax]\n yn = test_obj.ds.coordinates.axis_name[yax]\n plot.annotate_streamlines((\"gas\", f\"velocity_{xn}\"), (\"gas\", f\"velocity_{yn}\"))\n\n\nCALLBACK_TESTS = (\n (\"simple_contour\", (simple_contour,)),\n (\"simple_velocity\", (simple_velocity,)),\n # (\"simple_streamlines\", (simple_streamlines,)),\n # (\"simple_all\", (simple_contour, simple_velocity, simple_streamlines)),\n)\n\n\n@requires_ds(M7)\ndef test_attributes():\n \"\"\"Test plot member functions that aren't callbacks\"\"\"\n plot_field = (\"gas\", \"density\")\n decimals = 12\n\n ds = data_dir_load(M7)\n for ax in \"xyz\":\n for attr_name in ATTR_ARGS.keys():\n for args in ATTR_ARGS[attr_name]:\n test = PlotWindowAttributeTest(\n ds, plot_field, ax, attr_name, args, decimals\n )\n test_attributes.__name__ = test.description\n yield test\n for n, r in CALLBACK_TESTS:\n yield PlotWindowAttributeTest(\n ds,\n plot_field,\n ax,\n attr_name,\n args,\n decimals,\n callback_id=n,\n callback_runners=r,\n )\n\n\nclass TestHideAxesColorbar(unittest.TestCase):\n\n ds = None\n\n def setUp(self):\n if self.ds is None:\n self.ds = fake_random_ds(64)\n self.slc = SlicePlot(self.ds, 0, (\"gas\", \"density\"))\n self.tmpdir = tempfile.mkdtemp()\n self.curdir = os.getcwd()\n os.chdir(self.tmpdir)\n\n def tearDown(self):\n os.chdir(self.curdir)\n shutil.rmtree(self.tmpdir)\n del self.ds\n del self.slc\n\n def test_hide_show_axes(self):\n self.slc.hide_axes()\n self.slc.save()\n self.slc.show_axes()\n self.slc.save()\n\n def test_hide_show_colorbar(self):\n self.slc.hide_colorbar()\n self.slc.save()\n self.slc.show_colorbar()\n self.slc.save()\n\n def test_hide_axes_colorbar(self):\n self.slc.hide_colorbar()\n self.slc.hide_axes()\n self.slc.save()\n\n\nclass TestSetWidth(unittest.TestCase):\n\n ds = None\n\n def setUp(self):\n if self.ds is None:\n self.ds = fake_random_ds(64)\n self.slc = SlicePlot(self.ds, 0, (\"gas\", \"density\"))\n\n def tearDown(self):\n del self.ds\n del self.slc\n\n def _assert_05cm(self):\n assert_array_equal(\n [self.slc.xlim, self.slc.ylim, self.slc.width],\n [\n (YTQuantity(0.25, \"cm\"), YTQuantity(0.75, \"cm\")),\n (YTQuantity(0.25, \"cm\"), YTQuantity(0.75, \"cm\")),\n (YTQuantity(0.5, \"cm\"), YTQuantity(0.5, \"cm\")),\n ],\n )\n\n def _assert_05_075cm(self):\n assert_array_equal(\n [self.slc.xlim, self.slc.ylim, self.slc.width],\n [\n (YTQuantity(0.25, \"cm\"), YTQuantity(0.75, \"cm\")),\n (YTQuantity(0.125, \"cm\"), YTQuantity(0.875, \"cm\")),\n (YTQuantity(0.5, \"cm\"), YTQuantity(0.75, \"cm\")),\n ],\n )\n\n def test_set_width_one(self):\n assert_equal(\n [self.slc.xlim, self.slc.ylim, self.slc.width],\n [(0.0, 1.0), (0.0, 1.0), (1.0, 1.0)],\n )\n assert_true(self.slc._axes_unit_names is None)\n\n def test_set_width_nonequal(self):\n self.slc.set_width((0.5, 0.8))\n assert_rel_equal(\n [self.slc.xlim, self.slc.ylim, self.slc.width],\n [(0.25, 0.75), (0.1, 0.9), (0.5, 0.8)],\n 15,\n )\n assert_true(self.slc._axes_unit_names is None)\n\n def test_twoargs_eq(self):\n self.slc.set_width(0.5, \"cm\")\n self._assert_05cm()\n assert_true(self.slc._axes_unit_names == (\"cm\", \"cm\"))\n\n def test_tuple_eq(self):\n self.slc.set_width((0.5, \"cm\"))\n self._assert_05cm()\n assert_true(self.slc._axes_unit_names == (\"cm\", \"cm\"))\n\n def test_tuple_of_tuples_neq(self):\n self.slc.set_width(((0.5, \"cm\"), (0.75, \"cm\")))\n self._assert_05_075cm()\n assert_true(self.slc._axes_unit_names == (\"cm\", \"cm\"))\n\n\nclass TestPlotWindowSave(unittest.TestCase):\n def setUp(self):\n self.tmpdir = tempfile.mkdtemp()\n self.curdir = os.getcwd()\n os.chdir(self.tmpdir)\n\n def tearDown(self):\n os.chdir(self.curdir)\n shutil.rmtree(self.tmpdir)\n\n def test_slice_plot(self):\n test_ds = fake_random_ds(16)\n for dim in range(3):\n slc = SlicePlot(test_ds, dim, (\"gas\", \"density\"))\n for fname in TEST_FLNMS:\n assert_fname(slc.save(fname)[0])\n\n def test_repr_html(self):\n test_ds = fake_random_ds(16)\n slc = SlicePlot(test_ds, 0, (\"gas\", \"density\"))\n slc._repr_html_()\n\n def test_projection_plot(self):\n test_ds = fake_random_ds(16)\n for dim in range(3):\n proj = ProjectionPlot(test_ds, dim, (\"gas\", \"density\"))\n for fname in TEST_FLNMS:\n assert_fname(proj.save(fname)[0])\n\n def test_projection_plot_ds(self):\n test_ds = fake_random_ds(16)\n reg = test_ds.region([0.5] * 3, [0.4] * 3, [0.6] * 3)\n for dim in range(3):\n proj = ProjectionPlot(test_ds, dim, (\"gas\", \"density\"), data_source=reg)\n proj.save()\n\n def test_projection_plot_c(self):\n test_ds = fake_random_ds(16)\n for center in CENTER_SPECS:\n proj = ProjectionPlot(test_ds, 0, (\"gas\", \"density\"), center=center)\n proj.save()\n\n def test_projection_plot_wf(self):\n test_ds = fake_random_ds(16)\n for wf in WEIGHT_FIELDS:\n proj = ProjectionPlot(test_ds, 0, (\"gas\", \"density\"), weight_field=wf)\n proj.save()\n\n def test_projection_plot_m(self):\n test_ds = fake_random_ds(16)\n for method in PROJECTION_METHODS:\n proj = ProjectionPlot(test_ds, 0, (\"gas\", \"density\"), method=method)\n proj.save()\n\n def test_projection_plot_bs(self):\n test_ds = fake_random_ds(16)\n for bf in BUFF_SIZES:\n proj = ProjectionPlot(test_ds, 0, (\"gas\", \"density\"), buff_size=bf)\n image = proj.frb[\"gas\", \"density\"]\n\n # note that image.shape is inverted relative to the passed in buff_size\n assert_equal(image.shape[::-1], bf)\n\n def test_offaxis_slice_plot(self):\n test_ds = fake_random_ds(16)\n slc = OffAxisSlicePlot(test_ds, [1, 1, 1], (\"gas\", \"density\"))\n for fname in TEST_FLNMS:\n assert_fname(slc.save(fname)[0])\n\n def test_offaxis_projection_plot(self):\n test_ds = fake_random_ds(16)\n prj = OffAxisProjectionPlot(test_ds, [1, 1, 1], (\"gas\", \"density\"))\n for fname in TEST_FLNMS:\n assert_fname(prj.save(fname)[0])\n\n def test_creation_with_width(self):\n test_ds = fake_random_ds(16)\n for width in WIDTH_SPECS:\n xlim, ylim, pwidth, aun = WIDTH_SPECS[width]\n plot = ProjectionPlot(test_ds, 0, (\"gas\", \"density\"), width=width)\n\n xlim = [plot.ds.quan(el[0], el[1]) for el in xlim]\n ylim = [plot.ds.quan(el[0], el[1]) for el in ylim]\n pwidth = [plot.ds.quan(el[0], el[1]) for el in pwidth]\n\n [assert_array_almost_equal(px, x, 14) for px, x in zip(plot.xlim, xlim)]\n [assert_array_almost_equal(py, y, 14) for py, y in zip(plot.ylim, ylim)]\n [assert_array_almost_equal(pw, w, 14) for pw, w in zip(plot.width, pwidth)]\n assert_true(aun == plot._axes_unit_names)\n\n\nclass TestPerFieldConfig(unittest.TestCase):\n\n ds = None\n\n def setUp(self):\n from yt.config import ytcfg\n\n newConfig = {\n (\"yt\", \"default_colormap\"): \"viridis\",\n (\"plot\", \"gas\", \"log\"): False,\n (\"plot\", \"gas\", \"density\", \"units\"): \"lb/yard**3\",\n (\"plot\", \"gas\", \"density\", \"path_length_units\"): \"mile\",\n (\"plot\", \"gas\", \"density\", \"cmap\"): \"plasma\",\n (\"plot\", \"gas\", \"temperature\", \"log\"): True,\n (\"plot\", \"gas\", \"temperature\", \"linthresh\"): 100,\n (\"plot\", \"gas\", \"temperature\", \"cmap\"): \"hot\",\n (\"plot\", \"gas\", \"pressure\", \"log\"): True,\n (\"plot\", \"index\", \"radius\", \"linthresh\"): 1e3,\n }\n # Backup the old config\n oldConfig = {}\n for key in newConfig.keys():\n try:\n val = ytcfg[key]\n oldConfig[key] = val\n except KeyError:\n pass\n for key, val in newConfig.items():\n ytcfg[key] = val\n\n self.oldConfig = oldConfig\n self.newConfig = newConfig\n\n fields = [(\"gas\", \"density\"), (\"gas\", \"temperature\"), (\"gas\", \"pressure\")]\n units = [\"g/cm**3\", \"K\", \"dyn/cm**2\"]\n fields_to_plot = fields + [(\"index\", \"radius\")]\n if self.ds is None:\n self.ds = fake_random_ds(16, fields=fields, units=units)\n self.slc = ProjectionPlot(self.ds, 0, fields_to_plot)\n\n def tearDown(self):\n from yt.config import ytcfg\n\n del self.ds\n del self.slc\n for key in self.newConfig.keys():\n ytcfg.remove(*key)\n for key, val in self.oldConfig.items():\n ytcfg[key] = val\n\n def test_units(self):\n from unyt import Unit\n\n assert_equal(self.slc.frb[\"gas\", \"density\"].units, Unit(\"mile*lb/yd**3\"))\n assert_equal(self.slc.frb[\"gas\", \"temperature\"].units, Unit(\"cm*K\"))\n assert_equal(self.slc.frb[\"gas\", \"pressure\"].units, Unit(\"dyn/cm\"))\n\n def test_scale(self):\n assert_equal(self.slc._field_transform[\"gas\", \"density\"].name, \"linear\")\n assert_equal(self.slc._field_transform[\"gas\", \"temperature\"].name, \"symlog\")\n assert_equal(self.slc._field_transform[\"gas\", \"temperature\"].func, 100)\n assert_equal(self.slc._field_transform[\"gas\", \"pressure\"].name, \"log10\")\n assert_equal(self.slc._field_transform[\"index\", \"radius\"].name, \"log10\")\n\n def test_cmap(self):\n assert_equal(self.slc._colormap_config[\"gas\", \"density\"], \"plasma\")\n assert_equal(self.slc._colormap_config[\"gas\", \"temperature\"], \"hot\")\n assert_equal(self.slc._colormap_config[\"gas\", \"pressure\"], \"viridis\")\n\n\ndef test_on_off_compare():\n # fake density field that varies in the x-direction only\n den = np.arange(32 ** 3) / 32 ** 2 + 1\n den = den.reshape(32, 32, 32)\n den = np.array(den, dtype=np.float64)\n data = dict(density=(den, \"g/cm**3\"))\n bbox = np.array([[-1.5, 1.5], [-1.5, 1.5], [-1.5, 1.5]])\n ds = load_uniform_grid(data, den.shape, length_unit=\"Mpc\", bbox=bbox, nprocs=64)\n\n sl_on = SlicePlot(ds, \"z\", [(\"gas\", \"density\")])\n\n L = [0, 0, 1]\n north_vector = [0, 1, 0]\n sl_off = OffAxisSlicePlot(\n ds, L, (\"gas\", \"density\"), center=[0, 0, 0], north_vector=north_vector\n )\n\n assert_array_almost_equal(\n sl_on.frb[(\"gas\", \"density\")], sl_off.frb[(\"gas\", \"density\")]\n )\n\n sl_on.set_buff_size((800, 400))\n sl_on._recreate_frb()\n sl_off.set_buff_size((800, 400))\n sl_off._recreate_frb()\n\n assert_array_almost_equal(\n sl_on.frb[(\"gas\", \"density\")], sl_off.frb[(\"gas\", \"density\")]\n )\n\n\ndef test_plot_particle_field_error():\n ds = fake_random_ds(32, particles=100)\n\n field_names = [\n (\"all\", \"particle_mass\"),\n [(\"all\", \"particle_mass\"), (\"gas\", \"density\")],\n [(\"gas\", \"density\"), (\"all\", \"particle_mass\")],\n ]\n\n objects_normals = [\n (SlicePlot, 2),\n (SlicePlot, [1, 1, 1]),\n (ProjectionPlot, 2),\n (OffAxisProjectionPlot, [1, 1, 1]),\n ]\n\n for object, normal in objects_normals:\n for field_name_list in field_names:\n assert_raises(YTInvalidFieldType, object, ds, normal, field_name_list)\n\n\ndef test_setup_origin():\n origin_inputs = (\n \"domain\",\n \"left-window\",\n \"center-domain\",\n \"lower-right-window\",\n (\"window\",),\n (\"right\", \"domain\"),\n (\"lower\", \"window\"),\n (\"lower\", \"right\", \"window\"),\n (0.5, 0.5, \"domain\"),\n ((50, \"cm\"), (50, \"cm\"), \"domain\"),\n )\n w = (10, \"cm\")\n\n ds = fake_random_ds(32, length_unit=100.0)\n generated_limits = []\n # lower limit -> llim\n # upper limit -> ulim\n # xllim xulim yllim yulim\n correct_limits = [\n 45.0,\n 55.0,\n 45.0,\n 55.0,\n 0.0,\n 10.0,\n 0.0,\n 10.0,\n -5.0,\n 5.0,\n -5.0,\n 5.0,\n -10.0,\n 0,\n 0,\n 10.0,\n 0.0,\n 10.0,\n 0.0,\n 10.0,\n -55.0,\n -45.0,\n -55.0,\n -45.0,\n -5.0,\n 5.0,\n 0.0,\n 10.0,\n -10.0,\n 0,\n 0,\n 10.0,\n -5.0,\n 5.0,\n -5.0,\n 5.0,\n -5.0,\n 5.0,\n -5.0,\n 5.0,\n ]\n for o in origin_inputs:\n slc = SlicePlot(ds, 2, (\"gas\", \"density\"), width=w, origin=o)\n ax = slc.plots[(\"gas\", \"density\")].axes\n xlims = ax.get_xlim()\n ylims = ax.get_ylim()\n lims = [xlims[0], xlims[1], ylims[0], ylims[1]]\n for l in lims:\n generated_limits.append(l)\n assert_array_almost_equal(correct_limits, generated_limits)\n\n\ndef test_frb_regen():\n ds = fake_random_ds(32)\n slc = SlicePlot(ds, 2, (\"gas\", \"density\"))\n slc.set_buff_size(1200)\n assert_equal(slc.frb[(\"gas\", \"density\")].shape, (1200, 1200))\n slc.set_buff_size((400.0, 200.7))\n assert_equal(slc.frb[(\"gas\", \"density\")].shape, (200, 400))\n\n\ndef test_set_background_color():\n ds = fake_random_ds(32)\n plot = SlicePlot(ds, 2, (\"gas\", \"density\"))\n plot.set_background_color((\"gas\", \"density\"), \"red\")\n plot._setup_plots()\n ax = plot.plots[(\"gas\", \"density\")].axes\n assert_equal(ax.get_facecolor(), (1.0, 0.0, 0.0, 1.0))\n\n\ndef test_set_unit():\n ds = fake_random_ds(32, fields=((\"gas\", \"temperature\"),), units=(\"K\",))\n slc = SlicePlot(ds, 2, (\"gas\", \"temperature\"))\n\n orig_array = slc.frb[\"gas\", \"temperature\"].copy()\n\n slc.set_unit((\"gas\", \"temperature\"), \"degF\")\n\n assert str(slc.frb[\"gas\", \"temperature\"].units) == \"°F\"\n assert_array_almost_equal(\n np.array(slc.frb[\"gas\", \"temperature\"]), np.array(orig_array) * 1.8 - 459.67\n )\n\n # test that a plot modifying function that destroys the frb preserves the\n # new unit\n slc.set_buff_size(1000)\n\n assert str(slc.frb[\"gas\", \"temperature\"].units) == \"°F\"\n\n slc.set_buff_size(800)\n\n slc.set_unit((\"gas\", \"temperature\"), \"K\")\n assert str(slc.frb[\"gas\", \"temperature\"].units) == \"K\"\n assert_array_almost_equal(slc.frb[\"gas\", \"temperature\"], orig_array)\n\n slc.set_unit((\"gas\", \"temperature\"), \"keV\", equivalency=\"thermal\")\n assert str(slc.frb[\"gas\", \"temperature\"].units) == \"keV\"\n assert_array_almost_equal(\n slc.frb[\"gas\", \"temperature\"], (orig_array * kboltz).to(\"keV\")\n )\n\n # test that a plot modifying function that destroys the frb preserves the\n # new unit with an equivalency\n slc.set_buff_size(1000)\n\n assert str(slc.frb[\"gas\", \"temperature\"].units) == \"keV\"\n\n # test that destroying the FRB then changing the unit using an equivalency\n # doesn't error out, see issue #1316\n slc = SlicePlot(ds, 2, (\"gas\", \"temperature\"))\n slc.set_buff_size(1000)\n slc.set_unit((\"gas\", \"temperature\"), \"keV\", equivalency=\"thermal\")\n assert str(slc.frb[\"gas\", \"temperature\"].units) == \"keV\"\n\n\nWD = \"WDMerger_hdf5_chk_1000/WDMerger_hdf5_chk_1000.hdf5\"\nblast_wave = \"amrvac/bw_2d0000.dat\"\n\n\n@requires_file(WD)\n@requires_file(blast_wave)\ndef test_plot_2d():\n # Cartesian\n ds = fake_random_ds((32, 32, 1), fields=(\"temperature\",), units=(\"K\",))\n slc = SlicePlot(\n ds,\n \"z\",\n [(\"gas\", \"temperature\")],\n width=(0.2, \"unitary\"),\n center=[0.4, 0.3, 0.5],\n )\n slc2 = plot_2d(\n ds, (\"gas\", \"temperature\"), width=(0.2, \"unitary\"), center=[0.4, 0.3]\n )\n slc3 = plot_2d(\n ds,\n (\"gas\", \"temperature\"),\n width=(0.2, \"unitary\"),\n center=ds.arr([0.4, 0.3], \"cm\"),\n )\n assert_array_equal(\n slc.frb[(\"gas\", \"temperature\")], slc2.frb[(\"gas\", \"temperature\")]\n )\n assert_array_equal(\n slc.frb[(\"gas\", \"temperature\")], slc3.frb[(\"gas\", \"temperature\")]\n )\n # Cylindrical\n ds = data_dir_load(WD)\n slc = SlicePlot(ds, \"theta\", [(\"gas\", \"density\")], width=(30000.0, \"km\"))\n slc2 = plot_2d(ds, (\"gas\", \"density\"), width=(30000.0, \"km\"))\n assert_array_equal(slc.frb[(\"gas\", \"density\")], slc2.frb[(\"gas\", \"density\")])\n\n # Spherical\n ds = data_dir_load(blast_wave)\n slc = SlicePlot(ds, \"phi\", [(\"gas\", \"density\")], width=(1, \"unitary\"))\n slc2 = plot_2d(ds, (\"gas\", \"density\"), width=(1, \"unitary\"))\n assert_array_equal(slc.frb[(\"gas\", \"density\")], slc2.frb[(\"gas\", \"density\")])\n\n\ndef test_symlog_colorbar():\n ds = fake_random_ds(16)\n\n def _thresh_density(field, data):\n wh = data[(\"gas\", \"density\")] < 0.5\n ret = data[(\"gas\", \"density\")]\n ret[wh] = 0\n return ret\n\n def _neg_density(field, data):\n return -data[(\"gas\", \"threshold_density\")]\n\n ds.add_field(\n (\"gas\", \"threshold_density\"),\n function=_thresh_density,\n units=\"g/cm**3\",\n sampling_type=\"cell\",\n )\n ds.add_field(\n (\"gas\", \"negative_density\"),\n function=_neg_density,\n units=\"g/cm**3\",\n sampling_type=\"cell\",\n )\n\n for field in [\n (\"gas\", \"density\"),\n (\"gas\", \"threshold_density\"),\n (\"gas\", \"negative_density\"),\n ]:\n plot = SlicePlot(ds, 2, field)\n plot.set_log(field, True, linthresh=0.1)\n with tempfile.NamedTemporaryFile(suffix=\"png\") as f:\n plot.save(f.name)\n\n\ndef test_nan_data():\n data = np.random.random((16, 16, 16)) - 0.5\n data[:9, :9, :9] = np.nan\n\n data = {\"density\": data}\n\n ds = load_uniform_grid(data, [16, 16, 16])\n\n plot = SlicePlot(ds, \"z\", (\"gas\", \"density\"))\n\n with tempfile.NamedTemporaryFile(suffix=\"png\") as f:\n plot.save(f.name)\n" ]
[ [ "numpy.arange", "numpy.array", "numpy.random.random" ] ]
dshea89/luminoth
[ "18607a4ca42fbeaf1c0e4dc7901f1f0467118253" ]
[ "luminoth/utils/bbox_transform_tf.py" ]
[ "import tensorflow.compat.v1 as tf\n\n\ndef get_width_upright(bboxes):\n with tf.name_scope('BoundingBoxTransform/get_width_upright'):\n bboxes = tf.cast(bboxes, tf.float32)\n x1, y1, x2, y2 = tf.split(bboxes, 4, axis=1)\n width = x2 - x1 + 1.\n height = y2 - y1 + 1.\n\n # Calculate up right point of bbox (urx = up right x)\n urx = x1 + .5 * width\n ury = y1 + .5 * height\n\n return width, height, urx, ury\n\n\ndef encode(bboxes, gt_boxes, variances=None):\n with tf.name_scope('BoundingBoxTransform/encode'):\n (bboxes_width, bboxes_height,\n bboxes_urx, bboxes_ury) = get_width_upright(bboxes)\n\n (gt_boxes_width, gt_boxes_height,\n gt_boxes_urx, gt_boxes_ury) = get_width_upright(gt_boxes)\n\n if variances is None:\n variances = [1., 1.]\n\n targets_dx = (gt_boxes_urx - bboxes_urx)/(bboxes_width * variances[0])\n targets_dy = (gt_boxes_ury - bboxes_ury)/(bboxes_height * variances[0])\n\n targets_dw = tf.log(gt_boxes_width / bboxes_width) / variances[1]\n targets_dh = tf.log(gt_boxes_height / bboxes_height) / variances[1]\n\n targets = tf.concat(\n [targets_dx, targets_dy, targets_dw, targets_dh], axis=1)\n\n return targets\n\n\ndef decode(roi, deltas, variances=None):\n with tf.name_scope('BoundingBoxTransform/decode'):\n (roi_width, roi_height,\n roi_urx, roi_ury) = get_width_upright(roi)\n\n dx, dy, dw, dh = tf.split(deltas, 4, axis=1)\n\n if variances is None:\n variances = [1., 1.]\n\n pred_ur_x = dx * roi_width * variances[0] + roi_urx\n pred_ur_y = dy * roi_height * variances[0] + roi_ury\n pred_w = tf.exp(dw * variances[1]) * roi_width\n pred_h = tf.exp(dh * variances[1]) * roi_height\n\n bbox_x1 = pred_ur_x - 0.5 * pred_w\n bbox_y1 = pred_ur_y - 0.5 * pred_h\n\n # This -1. extra is different from reference implementation.\n bbox_x2 = pred_ur_x + 0.5 * pred_w - 1.\n bbox_y2 = pred_ur_y + 0.5 * pred_h - 1.\n\n bboxes = tf.concat(\n [bbox_x1, bbox_y1, bbox_x2, bbox_y2], axis=1)\n\n return bboxes\n\n\ndef clip_boxes(bboxes, imshape):\n \"\"\"\n Clips bounding boxes to image boundaries based on image shape.\n\n Args:\n bboxes: Tensor with shape (num_bboxes, 4)\n where point order is x1, y1, x2, y2.\n\n imshape: Tensor with shape (2, )\n where the first value is height and the next is width.\n\n Returns\n Tensor with same shape as bboxes but making sure that none\n of the bboxes are outside the image.\n \"\"\"\n with tf.name_scope('BoundingBoxTransform/clip_bboxes'):\n bboxes = tf.cast(bboxes, dtype=tf.float32)\n imshape = tf.cast(imshape, dtype=tf.float32)\n\n x1, y1, x2, y2 = tf.split(bboxes, 4, axis=1)\n width = imshape[1]\n height = imshape[0]\n x1 = tf.maximum(tf.minimum(x1, width - 1.0), 0.0)\n x2 = tf.maximum(tf.minimum(x2, width - 1.0), 0.0)\n\n y1 = tf.maximum(tf.minimum(y1, height - 1.0), 0.0)\n y2 = tf.maximum(tf.minimum(y2, height - 1.0), 0.0)\n\n bboxes = tf.concat([x1, y1, x2, y2], axis=1)\n\n return bboxes\n\n\ndef change_order(bboxes):\n \"\"\"Change bounding box encoding order.\n\n TensorFlow works with the (y_min, x_min, y_max, x_max) order while we work\n with the (x_min, y_min, x_max, y_min).\n\n While both encoding options have its advantages and disadvantages we\n decided to use the (x_min, y_min, x_max, y_min), forcing use to switch to\n TensorFlow's every time we want to use a std function that handles bounding\n boxes.\n\n Args:\n bboxes: A Tensor of shape (total_bboxes, 4)\n\n Returns:\n bboxes: A Tensor of shape (total_bboxes, 4) with the order swaped.\n \"\"\"\n with tf.name_scope('BoundingBoxTransform/change_order'):\n first_min, second_min, first_max, second_max = tf.unstack(\n bboxes, axis=1\n )\n bboxes = tf.stack(\n [second_min, first_min, second_max, first_max], axis=1\n )\n return bboxes\n\n\nif __name__ == '__main__':\n import numpy as np\n\n bboxes = tf.placeholder(tf.float32)\n bboxes_val = [[10, 10, 20, 22]]\n\n gt_boxes = tf.placeholder(tf.float32)\n gt_boxes_val = [[11, 13, 34, 31]]\n\n imshape = tf.placeholder(tf.int32)\n imshape_val = (100, 100)\n\n deltas = encode(bboxes, gt_boxes)\n decoded_bboxes = decode(bboxes, deltas)\n final_decoded_bboxes = clip_boxes(decoded_bboxes, imshape)\n\n with tf.Session() as sess:\n final_decoded_bboxes = sess.run(final_decoded_bboxes, feed_dict={\n bboxes: bboxes_val,\n gt_boxes: gt_boxes_val,\n imshape: imshape_val,\n })\n\n assert np.all(gt_boxes_val == final_decoded_bboxes)\n" ]
[ [ "tensorflow.compat.v1.stack", "tensorflow.compat.v1.exp", "tensorflow.compat.v1.concat", "tensorflow.compat.v1.split", "tensorflow.compat.v1.unstack", "tensorflow.compat.v1.Session", "tensorflow.compat.v1.placeholder", "numpy.all", "tensorflow.compat.v1.minimum", "tensorflow.compat.v1.cast", "tensorflow.compat.v1.log", "tensorflow.compat.v1.name_scope" ] ]
azedarach/reanalysis-dbns
[ "160f405762fb33cfde38b1d3d63cc19e0bb3d591" ]
[ "src/reanalysis_dbns/indices/indopacific_sst.py" ]
[ "\"\"\"\nProvides routines for computing indices associated with Indo-Pacific SST.\n\"\"\"\n\n# License: MIT\n\nfrom __future__ import absolute_import, division\n\nimport os\n\nimport dask.array\nimport geopandas as gp\nimport numpy as np\nimport regionmask as rm\nimport scipy.linalg\nimport xarray as xr\n\nimport reanalysis_dbns.utils as rdu\n\n\nINDIAN_PACIFIC_OCEAN_REGION_SHP = os.path.join(\n os.path.dirname(__file__), 'indian_pacific_ocean.shp')\n\n\ndef _project_onto_subspace(data, eofs, weight=None, sample_dim=None,\n mode_dim='mode'):\n \"\"\"Project given data onto (possibly non-orthogonal) basis.\"\"\"\n\n # Ensure given data is a data array\n data = rdu.ensure_data_array(data)\n\n sample_dim = (sample_dim if sample_dim is not None else\n rdu.get_time_name(data))\n\n if mode_dim is None:\n raise ValueError('No mode dimension given')\n\n if weight is not None:\n data = data * weight\n\n feature_dims = [d for d in data.dims if d != sample_dim]\n original_shape = [data.sizes[d] for d in feature_dims]\n\n if data.get_axis_num(sample_dim) != 0:\n data = data.transpose(*([sample_dim] + feature_dims))\n\n n_samples = data.sizes[sample_dim]\n n_features = np.product(original_shape)\n\n flat_data = data.values.reshape((n_samples, n_features))\n valid_data, missing_features = rdu.remove_missing_features(flat_data)\n valid_features = [d for d in range(n_features)\n if d not in missing_features]\n valid_data = valid_data.swapaxes(0, 1)\n\n if eofs.get_axis_num(mode_dim) != 0:\n eofs = eofs.transpose(*([mode_dim] + feature_dims))\n\n n_modes = eofs.sizes[mode_dim]\n\n flat_eofs = eofs.values.reshape((n_modes, n_features))\n valid_eofs = flat_eofs[:, valid_features].swapaxes(0, 1)\n\n if rdu.is_dask_array(flat_data):\n\n projection = dask.array.linalg.lstsq(valid_eofs, valid_data)\n\n else:\n\n projection = scipy.linalg.lstsq(valid_eofs, valid_data)[0]\n\n projection = xr.DataArray(\n projection.swapaxes(0, 1),\n coords={sample_dim: data[sample_dim],\n mode_dim: eofs[mode_dim]},\n dims=[sample_dim, mode_dim])\n\n return projection\n\n\ndef _fix_loading_pattern_phases(eofs, lon_name=None, lat_name=None):\n \"\"\"Ensure maximum positive SST anomaly occurs in Nino region.\"\"\"\n\n lat_name = lat_name if lat_name is not None else rdu.get_lat_name(eofs)\n lon_name = lon_name if lon_name is not None else rdu.get_lon_name(eofs)\n\n min_lon = eofs[lon_name].min()\n max_lon = eofs[lon_name].max()\n\n if min_lon < 0 and max_lon <= 180:\n leading_eof = eofs['EOFs'].where(\n (eofs[lon_name] <= -120) &\n (eofs[lon_name] >= -170) &\n (eofs[lat_name] >= -5) &\n (eofs[lat_name] <= 5), drop=True).isel(mode=0)\n else:\n leading_eof = eofs['EOFs'].where(\n (eofs[lon_name] >= 190) &\n (eofs[lon_name] <= 240) &\n (eofs[lat_name] >= -5) &\n (eofs[lat_name] <= 5), drop=True).isel(mode=0)\n\n flipped_leading_eof = -leading_eof\n nino34_max_anom = leading_eof.max()\n flipped_nino34_max_anom = flipped_leading_eof.max()\n\n if flipped_nino34_max_anom > nino34_max_anom:\n\n eofs['EOFs'] = xr.where(eofs['mode'] == 0, -eofs['EOFs'], eofs['EOFs'])\n eofs['PCs'] = xr.where(eofs['mode'] == 0, -eofs['PCs'], eofs['PCs'])\n\n return eofs\n\n\ndef dc_sst_loading_pattern(sst_anom, n_modes=None, n_rotated_modes=12,\n weights=None, lat_name=None, lon_name=None,\n time_name=None):\n \"\"\"Calculate rotated EOFs for the SST1 and SST2 index.\n\n Parameters\n ----------\n sst_anom : xarray.DataArray\n Array containing SST anomalies.\n\n n_modes : integer\n Number of modes to compute in EOFs calculation.\n If None, the minimum number of modes needed to perform the\n rotation are computed.\n\n n_rotated_modes : integer\n Number of modes to include in VARIMAX rotation.\n If None, all computed modes are included.\n\n weights : xarray.DataArray\n Weights to apply in calculating the EOFs.\n\n lat_name : str\n Name of the latitude coordinate.\n\n lon_name : str\n Name of the longitude coordinate.\n\n time_name : str\n Name of the time coordinate.\n\n Returns\n -------\n pattern: xarray.Dataset\n Dataset containing the computed rotated EOFs and PCs.\n \"\"\"\n\n # Ensure that the data provided is a data array\n sst_anom = rdu.ensure_data_array(sst_anom)\n\n lat_name = (lat_name if lat_name is not None else\n rdu.get_lat_name(sst_anom))\n lon_name = (lon_name if lon_name is not None else\n rdu.get_lon_name(sst_anom))\n time_name = (time_name if time_name is not None else\n rdu.get_time_name(sst_anom))\n\n if n_modes is None and n_rotated_modes is None:\n n_modes = 12\n n_rotated_modes = 12\n elif n_modes is None and n_rotated_modes is not None:\n n_modes = n_rotated_modes\n elif n_modes is not None and n_rotated_modes is None:\n n_rotated_modes = n_modes\n\n if not rdu.is_integer(n_modes) or n_modes < 1:\n raise ValueError(\n 'Invalid number of modes: got %r but must be at least 1')\n\n if not rdu.is_integer(n_rotated_modes) or n_rotated_modes < 1:\n raise ValueError(\n 'Invalid number of rotated modes: got %r but must be at least 1')\n\n if n_rotated_modes > n_modes:\n raise ValueError(\n 'Number of rotated modes must not be greater than'\n ' number of unrotated modes')\n\n eofs_ds = rdu.reofs(sst_anom, sample_dim=time_name, weight=weights,\n n_modes=n_modes, n_rotated_modes=n_rotated_modes)\n\n eofs_ds.attrs['n_modes'] = '{:d}'.format(n_modes)\n eofs_ds.attrs['n_rotated_modes'] = '{:d}'.format(n_rotated_modes)\n\n return _fix_loading_pattern_phases(\n eofs_ds, lat_name=lat_name, lon_name=lon_name)\n\n\ndef dc_sst(sst, frequency='monthly', n_modes=None, n_rotated_modes=12,\n base_period=None, lat_name=None, lon_name=None, time_name=None):\n \"\"\"Calculate the SST1 and SST2 index of Indo-Pacific SST.\n\n The indices are defined as the PCs associated with the\n first and second rotated EOFs of standardized\n Indo-Pacific SST anomalies.\n\n See Drosdowsky, W. and Chambers, L. E., \"Near-Global Sea Surface\n Temperature Anomalies as Predictors of Australian Seasonal\n Rainfall\", Journal of Climate 14, 1677 - 1687 (2001).\n\n Parameters\n ----------\n sst : xarray.DataArray\n Array containing SST values.\n\n frequency : str\n If given, downsample data to requested frequency.\n\n n_modes : integer\n Number of EOFs to retain before rotation.\n\n n_rotated_modes : integer\n Number of EOFs to include in VARIMAX rotation.\n\n base_period : list\n Earliest and latest times to use for standardization.\n\n lat_name : str\n Name of the latitude coordinate.\n\n lon_name : str\n Name of the longitude coordinate.\n\n time_name : str\n Name of the time coordinate.\n\n Returns\n -------\n result : xarray.Dataset\n Dataset containing the SST index loading patterns and indices.\n \"\"\"\n\n # Ensure that the data provided is a data array\n sst = rdu.ensure_data_array(sst)\n\n # Get coordinate names\n lat_name = lat_name if lat_name is not None else rdu.get_lat_name(sst)\n lon_name = lon_name if lon_name is not None else rdu.get_lon_name(sst)\n time_name = time_name if time_name is not None else rdu.get_time_name(sst)\n\n if frequency is None:\n frequency = 'monthly'\n\n if frequency not in ('daily', 'monthly'):\n raise ValueError(\"Unsupported frequency '%r'\" % frequency)\n\n base_period = rdu.check_base_period(sst, base_period=base_period,\n time_name=time_name)\n\n shape_data = gp.read_file(INDIAN_PACIFIC_OCEAN_REGION_SHP)\n\n region_mask = rm.Regions(shape_data['geometry'], numbers=[0])\n\n # Generate mask for SST region\n mask = region_mask.mask(sst[lon_name] % 360, sst[lat_name],\n lon_name=lon_name, lat_name=lat_name)\n mask[lon_name] = sst[lon_name]\n\n sst = sst.where(mask == 0)\n\n # EOFs are computed based on standardized monthly anomalies\n input_frequency = rdu.detect_frequency(sst, time_name=time_name)\n\n if input_frequency not in ('daily', 'monthly'):\n raise RuntimeError(\n 'Can only calculate index for daily or monthly data')\n\n if input_frequency == 'daily' and frequency == 'daily':\n\n base_period_monthly_sst = sst.where(\n (sst[time_name] >= base_period[0]) &\n (sst[time_name] <= base_period[1]), drop=True).resample(\n {time_name: '1MS'}).mean()\n\n base_period_monthly_sst_anom = rdu.standardized_anomalies(\n base_period_monthly_sst, base_period=base_period,\n standardize_by='month', time_name=time_name)\n\n sst_anom = rdu.standardized_anomalies(\n sst, base_period=base_period, standardize_by='dayofyear',\n time_name=time_name)\n\n elif input_frequency == 'daily' and frequency == 'monthly':\n\n sst = sst.resample({time_name: '1MS'}).mean()\n\n sst_anom = rdu.standardized_anomalies(\n sst, base_period=base_period, standardize_by='month',\n time_name=time_name)\n\n base_period_monthly_sst_anom = sst_anom.where(\n (sst_anom[time_name] >= base_period[0]) &\n (sst_anom[time_name] <= base_period[1]), drop=True)\n\n elif input_frequency == 'monthly' and frequency == 'daily':\n\n raise RuntimeError(\n 'Attempting to calculate daily index from monthly data')\n\n else:\n\n sst_anom = rdu.standardized_anomalies(\n sst, base_period=base_period, standardize_by='month',\n time_name=time_name)\n\n base_period_monthly_sst_anom = sst_anom.where(\n (sst_anom[time_name] >= base_period[0]) &\n (sst_anom[time_name] <= base_period[1]), drop=True)\n\n # Get square root of cos(latitude) weights\n scos_weights = np.cos(np.deg2rad(sst_anom[lat_name])).clip(0., 1.) ** 0.5\n\n # Calculate VARIMAX rotated EOFs of standardized monthly anomalies.\n loadings_ds = dc_sst_loading_pattern(\n base_period_monthly_sst_anom, n_modes=n_modes,\n n_rotated_modes=n_rotated_modes, weights=scos_weights,\n lat_name=lat_name, lon_name=lon_name, time_name=time_name)\n\n # Project weighted anomalies onto first and second REOFs.\n rotated_pcs = _project_onto_subspace(\n sst_anom, loadings_ds['EOFs'], weight=scos_weights,\n sample_dim=time_name)\n\n sst1_index = rotated_pcs.sel(mode=0).drop_vars('mode').rename('sst1_index')\n sst2_index = rotated_pcs.sel(mode=1).drop_vars('mode').rename('sst2_index')\n\n index_ds = xr.Dataset({'sst1_index': sst1_index,\n 'sst2_index': sst2_index})\n\n loadings_ds.attrs['base_period_start'] = rdu.datetime_to_string(\n base_period[0], '%Y%m%d')\n loadings_ds.attrs['base_period_end'] = rdu.datetime_to_string(\n base_period[1], '%Y%m%d')\n\n index_ds.attrs['base_period_start'] = rdu.datetime_to_string(\n base_period[0], '%Y%m%d')\n index_ds.attrs['base_period_end'] = rdu.datetime_to_string(\n base_period[1], '%Y%m%d')\n index_ds.attrs['n_modes'] = loadings_ds.attrs['n_modes']\n index_ds.attrs['n_rotated_modes'] = loadings_ds.attrs['n_rotated_modes']\n\n return loadings_ds, index_ds\n" ]
[ [ "numpy.deg2rad", "numpy.product" ] ]
Dhruv-Mohan/PoseEstimationForMobile
[ "5c17272be0336398d244c567eba80a2795135dc6" ]
[ "training/src/utils/pointIO.py" ]
[ "import numpy as np\n\ndef write_style_menpo(file_handle, pts):\n num_pts = pts.shape[0] # assuming pts is an nparray\n file_handle.write('version: 1\\nn_points: ' + str(num_pts) + '\\n{ \\n')\n for ptx, pty in pts:\n file_handle.write(str(ptx) + ' ' + str(pty) + '\\n')\n file_handle.write('}')\n\n\ndef write_style_normal(file_handle, pts):\n for ptx, pty in pts:\n file_handle.write(str(ptx) + ' ' + str(pty) + '\\n')\n\n\ndef write_pts(file_handle, pts, menpo=True):\n if menpo:\n write_style_menpo(file_handle, pts)\n else:\n write_style_normal(file_handle, pts)\n\n\ndef get_pts(file_name, patches):\n with open(file_name, 'r') as file_read:\n data = file_read.read()\n data = data.split()\n\n if data[-1] in '}':\n pts = get_type_menpo(data, patches)\n else:\n pts = get_type_normal(data, patches)\n\n return pts\n\n\ndef get_type_menpo(data, patches):\n data = data[5:-1]\n data = np.asarray(data, np.float32)\n data = np.reshape(data, (patches, 2))\n return data\n\n\ndef get_type_normal(data, patches = None):\n data = np.asarray(data, np.float32)\n data = np.reshape(data, (patches, 2))\n return data\n\n" ]
[ [ "numpy.asarray", "numpy.reshape" ] ]